hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
5b75558839cebb66ae384088a86e15e9209ebfa5
8,715
cpp
C++
deprecate/tools/fpzip/src/write.cpp
novatig/CubismUP_3D_old
47f7dd5941d81853cfe879385080c7c2c68a9b71
[ "MIT" ]
2
2020-06-12T10:06:59.000Z
2021-04-22T00:44:27.000Z
deprecate/tools/fpzip/src/write.cpp
novatig/CubismUP_3D_old
47f7dd5941d81853cfe879385080c7c2c68a9b71
[ "MIT" ]
null
null
null
deprecate/tools/fpzip/src/write.cpp
novatig/CubismUP_3D_old
47f7dd5941d81853cfe879385080c7c2c68a9b71
[ "MIT" ]
null
null
null
#include <cstdio> #include <cstdlib> #include "pcencoder.h" #include "rcqsmodel.h" #include "front.h" #include "fpzip.h" #include "codec.h" #include "write.h" #if FPZIP_FP == FPZIP_FP_FAST || FPZIP_FP == FPZIP_FP_SAFE // compress 3D array at specified precision using floating-point arithmetic template <typename T, unsigned bits> static void compress3d( RCencoder* re, // entropy encoder const T* data, // flattened 3D array to compress unsigned nx, // number of x samples unsigned ny, // number of y samples unsigned nz // number of z samples ) { // initialize compressor typedef PCmap<T, bits> MAP; RCmodel* rm = new RCqsmodel(true, PCencoder<T, MAP>::symbols); PCencoder<T, MAP>* fe = new PCencoder<T, MAP>(re, &rm); FRONT<T> f(nx, ny); // encode difference between predicted (p) and actual (a) value unsigned x, y, z; for (z = 0, f.advance(0, 0, 1); z < nz; z++) for (y = 0, f.advance(0, 1, 0); y < ny; y++) for (x = 0, f.advance(1, 0, 0); x < nx; x++) { #if FPZIP_FP == FPZIP_FP_SAFE volatile T p = f(1, 1, 1); p += f(1, 0, 0); p -= f(0, 1, 1); p += f(0, 1, 0); p -= f(1, 0, 1); p += f(0, 0, 1); p -= f(1, 1, 0); #else T p = f(1, 0, 0) - f(0, 1, 1) + f(0, 1, 0) - f(1, 0, 1) + f(0, 0, 1) - f(1, 1, 0) + f(1, 1, 1); #endif T a = *data++; a = fe->encode(a, p); f.push(a); } delete fe; delete rm; } #elif FPZIP_FP == FPZIP_FP_EMUL #include "fpe.h" // compress 3D array at specified precision using floating-point emulation template <typename T, unsigned bits> static void compress3d( RCencoder* re, // entropy encoder const T* data, // flattened 3D array to compress unsigned nx, // number of x samples unsigned ny, // number of y samples unsigned nz // number of z samples ) { // initialize compressor typedef PCmap<T, bits> MAP; typedef FPE<T> FLOAT; RCmodel* rm = new RCqsmodel(true, PCencoder<T, MAP>::symbols); PCencoder<T, MAP>* fe = new PCencoder<T, MAP>(re, &rm); FRONT<FLOAT> f(nx, ny); // encode difference between predicted (p) and actual (a) value unsigned x, y, z; for (z = 0, f.advance(0, 0, 1); z < nz; z++) for (y = 0, f.advance(0, 1, 0); y < ny; y++) for (x = 0, f.advance(1, 0, 0); x < nx; x++) { FLOAT p = f(1, 0, 0) - f(0, 1, 1) + f(0, 1, 0) - f(1, 0, 1) + f(0, 0, 1) - f(1, 1, 0) + f(1, 1, 1); T a = *data++; a = fe->encode(a, T(p)); f.push(a); } delete fe; delete rm; } #else // FPZIP_FP_INT // compress 3D array at specified precision using integer arithmetic template <typename T, unsigned bits> static void compress3d( RCencoder* re, // entropy encoder const T* data, // flattened 3D array to compress unsigned nx, // number of x samples unsigned ny, // number of y samples unsigned nz // number of z samples ) { // initialize compressor typedef PCmap<T, bits> TMAP; typedef typename TMAP::RANGE U; typedef PCmap<U, bits, U> UMAP; RCmodel* rm = new RCqsmodel(true, PCencoder<U, UMAP>::symbols); PCencoder<U, UMAP>* fe = new PCencoder<U, UMAP>(re, &rm); TMAP map; FRONT<U> f(nx, ny, map.forward(0)); // encode difference between predicted (p) and actual (a) value unsigned x, y, z; for (z = 0, f.advance(0, 0, 1); z < nz; z++) for (y = 0, f.advance(0, 1, 0); y < ny; y++) for (x = 0, f.advance(1, 0, 0); x < nx; x++) { U p = f(1, 0, 0) - f(0, 1, 1) + f(0, 1, 0) - f(1, 0, 1) + f(0, 0, 1) - f(1, 1, 0) + f(1, 1, 1); U a = map.forward(*data++); a = fe->encode(a, p); f.push(a); } delete fe; delete rm; } #endif // compress 4D array template <typename T> static void compress4d( RCencoder* re, // entropy encoder const T* data, // flattened 4D array to compress const int* prec, // per field desired precision unsigned nx, // number of x samples unsigned ny, // number of y samples unsigned nz, // number of z samples unsigned nf // number of fields ) { // compress one field at a time for (unsigned i = 0; i < nf; i++) { int bits = prec ? prec[i] : CHAR_BIT * (int)sizeof(T); re->encode(bits, 32); switch (bits) { case subsize(T, 1): // 8-bit float, 16-bit double compress3d<T, subsize(T, 1)>(re, data, nx, ny, nz); break; case subsize(T, 2): // 16-bit float, 32-bit double compress3d<T, subsize(T, 2)>(re, data, nx, ny, nz); break; case subsize(T, 3): // 24-bit float, 48-bit double compress3d<T, subsize(T, 3)>(re, data, nx, ny, nz); break; case subsize(T, 4): // 32-bit float, 64-bit double compress3d<T, subsize(T, 4)>(re, data, nx, ny, nz); break; default: fprintf(stderr, "fpzip: precision %d not supported\n", bits); abort(); break; } data += nx * ny * nz; } } static void write_header( RCencoder* re, unsigned nx, unsigned ny, unsigned nz, unsigned nf, int dp ) { // magic re->encode('f', 8); re->encode('p', 8); re->encode('z', 8); re->encode('\0', 8); // format version re->encode(FPZ_MAJ_VERSION, 16); re->encode(FPZ_MIN_VERSION, 16); // array dimensions re->encode(nf, 32); re->encode(nz, 32); re->encode(ny, 32); re->encode(nx, 32); // single or double precision re->encode(!!dp); } static void fpzip_stream_write( RCencoder* re, // entropy encoder const void* data, // array to write const int* prec, // per field bits of precision int dp, // double precision array if nonzero unsigned nx, // number of x samples unsigned ny, // number of y samples unsigned nz, // number of z samples unsigned nf // number of fields ) { write_header(re, nx, ny, nz, nf, dp); if (dp) compress4d(re, (const double*)data, prec, nx, ny, nz, nf); else compress4d(re, (const float*)data, prec, nx, ny, nz, nf); re->finish(); } // compress and write a single or double precision 4D array to file unsigned fpzip_file_write( FILE* file, // binary output stream const void* data, // array to write const int* prec, // per field bits of precision int dp, // double precision array if nonzero unsigned nx, // number of x samples unsigned ny, // number of y samples unsigned nz, // number of z samples unsigned nf // number of fields ) { RCfileencoder* re = new RCfileencoder(file); fpzip_stream_write(re, data, prec, dp, nx, ny, nz, nf); re->flush(); unsigned bytes = re->error ? 0 : re->bytes(); delete re; return bytes; } // compress and write a single or double precision 4D array to file unsigned fpzip_memory_write( void* buffer, // pointer to compressed data unsigned size, // size of allocated storage const void* data, // array to write const int* prec, // per field bits of precision int dp, // double precision array if nonzero unsigned nx, // number of x samples unsigned ny, // number of y samples unsigned nz, // number of z samples unsigned nf // number of fields ) { RCmemencoder* re = new RCmemencoder(buffer, size); fpzip_stream_write(re, data, prec, dp, nx, ny, nz, nf); unsigned bytes = re->error ? 0 : re->bytes(); delete re; return bytes; } // wrappers for fortran calls void fpzip_file_write_f( const char* path, // path to output file const void* data, // array to write const int* prec, // per field bits of precision const int* dp, // double precision array if nonzero const int* nx, // number of x samples const int* ny, // number of y samples const int* nz, // number of z samples const int* nf // number of fields ) { FILE* file = fopen(path, "wb"); if (!file) { fprintf(stderr, "fpzip: cannot create file %s\n", path); abort(); } if (!fpzip_file_write(file, data, prec, *dp, *nx, *ny, *nz, *nf)) { fprintf(stderr, "fpzip: cannot write file %s\n", path); abort(); } fclose(file); } void fpzip_file_write_f_( const char* path, // path to output file const void* data, // array to write const int* prec, // per field bits of precision const int* dp, // double precision array if nonzero const int* nx, // number of x samples const int* ny, // number of y samples const int* nz, // number of z samples const int* nf // number of fields ) { fpzip_file_write_f(path, data, dp, prec, nx, ny, nz, nf); }
28.857616
75
0.5821
[ "3d" ]
5b7aa39a312539ca52d3e6b3b2389f028f3ee88a
1,807
cpp
C++
algorithm-c++/STL_Test/algorithm/modifiedSeqAlgo.cpp
mingrongchen/Algorithm
5ad264f0e199215b9b4f0f15f456d2727c5299bb
[ "MIT" ]
null
null
null
algorithm-c++/STL_Test/algorithm/modifiedSeqAlgo.cpp
mingrongchen/Algorithm
5ad264f0e199215b9b4f0f15f456d2727c5299bb
[ "MIT" ]
null
null
null
algorithm-c++/STL_Test/algorithm/modifiedSeqAlgo.cpp
mingrongchen/Algorithm
5ad264f0e199215b9b4f0f15f456d2727c5299bb
[ "MIT" ]
null
null
null
// // Created by MingR on 2021/4/15. // #include <iostream> #include <random> #include <ctime> #include <vector> #include <algorithm> using namespace std; typedef struct info { int age; int gender; } Info, *PInfo; static void test(); template <class T> static void FillValue (T& vect, int first, int last); static void print(int elem); template <class T> class Multiple { private: T theValue; public: // 构造函数 Multiple(const T& v):theValue(v) { } // 仿函数 void operator()(T& elem) const { elem *= theValue; } }; class SUM { private: long sum_D; public: // 构造函数 SUM() : sum_D(0){ } // 仿函数 void operator() (int elem) { sum_D += elem; } // 返回求解的和 operator double() { return static_cast<double>(sum_D); } }; void test() { vector<int> myVector; FillValue(myVector, 1, 10); for_each(myVector.begin(), myVector.end(), print); cout << endl; // 所有元素乘积测试 // for_each(myVector.begin(), myVector.end(), Multiple<int>(2)); // for_each(myVector.begin(), myVector.end(), print); // cout << endl; // 求和测试 double sum = for_each(myVector.begin(), myVector.end(), SUM()); cout << "The Sum : " << sum << endl; } template <class T> void FillValue (T& vect, int first, int last) { srand(time(0)); int temp; if (last >= first) { for (auto i = first; i <= last; ++i) { temp = rand() % 100 + 1; cout << "i : " << i << " ,temp : " << temp << endl; vect.insert(vect.end(), temp); } } else { cout << "The indexes is error: last < first. " << endl; } } void print(int elem) { cout << elem << " "; }
18.822917
68
0.516879
[ "vector" ]
5b7b82ad2a0f41e7ff0c86f216c6c78941099ddd
1,973
hpp
C++
src/mutex/Mutex.hpp
phisikus/monitor
cf74b299111d07c1dae6a14d79a06154811c8868
[ "BSD-3-Clause" ]
1
2016-06-08T12:27:26.000Z
2016-06-08T12:27:26.000Z
src/mutex/Mutex.hpp
phisikus/monitor
cf74b299111d07c1dae6a14d79a06154811c8868
[ "BSD-3-Clause" ]
null
null
null
src/mutex/Mutex.hpp
phisikus/monitor
cf74b299111d07c1dae6a14d79a06154811c8868
[ "BSD-3-Clause" ]
null
null
null
#ifndef INCLUDE_MUTEX_HPP #define INCLUDE_MUTEX_HPP #include "../message/Message.hpp" #include <vector> #include <algorithm> #include <list> #include <mutex> #include <stdexcept> #include <condition_variable> using namespace std; class Mutex { public: int id; // Mutex ID bool requesting = false; // It tells if this mutex is locked and waiting for C.S. bool locked = false; long requestClock = 0; // timestamp to reject AGREE packets that came late for previous request vector<bool> *agreeVector; // it will be filled with negation of activePeers vector. If other agrees we can enter C. S. list<int> heldUpRequests; // processes that sent REQUEST but should wait for their turn - we will send AGREE after unlock() mutex operationMutex; // local mutex that will block communicationLoop for this distributed Mutex during lock/unlock. mutex localMutex; // local mutex for thread safe behaviour Message *previousReturn = NULL; // This field will contain most recent RETURN message (based on clock) or DATA. When we enter CS it will be possible to get current data and save it to this variable. bool keepAlive = false; // true here means that there was no request for this mutex so no RETURN message was sent and in the future while sending AGREE no one will know that we had any data - instead we will send RETURN. condition_variable criticalSectionCondition; // On this variable lock() will wait till all agrees are collected by communicationLoop and DATA packet is send if needed unique_lock<mutex> *criticalSectionConditionLock; mutex criticalSectionConditionMutex; Mutex(int id); static Mutex * getMutex(int id); static list<Mutex *> * getMutexes(); bool agreeVectorTrue(); void * getData(); long getDataSize(); void setDataForReturn(void *data, long size); // Create new previousReturn Message of type DATA with given data private: static mutex mutexListMutex; static list<pair<int,Mutex*>> *existingMutexes; }; #endif
43.844444
222
0.760264
[ "vector" ]
5b83a3a212cf6d29ffaa157fc8d17467953d5f1b
1,105
cpp
C++
p209_Minimum_Size_Subarray_Sum/p209.cpp
Song1996/Leetcode
ecb0a2de67a57b899a12d0cb18272fb37dbf3ceb
[ "MIT" ]
null
null
null
p209_Minimum_Size_Subarray_Sum/p209.cpp
Song1996/Leetcode
ecb0a2de67a57b899a12d0cb18272fb37dbf3ceb
[ "MIT" ]
null
null
null
p209_Minimum_Size_Subarray_Sum/p209.cpp
Song1996/Leetcode
ecb0a2de67a57b899a12d0cb18272fb37dbf3ceb
[ "MIT" ]
null
null
null
#include <iostream> #include <memory> #include <vector> #include <stack> #include <map> #include <string> #include <assert.h> #include <stdlib.h> #include <fstream> #include <algorithm> using namespace std; class Solution { public: int minSubArrayLen(int s, vector<int>& nums) { if(nums.empty()) return 0; int t = nums[0]; int i = 1; if(t>=s) return 1; else while(i<nums.size() && t<s) t += nums[i++]; if(i == nums.size() && t<s) return 0; int ans = i; for(int j = 1; j < nums.size(); j++) { t -= nums[j-1]; if(t>=s) ans = min(ans, i-j); else { while(i<nums.size() && t<s) t += nums[i++]; if(i == nums.size() && t<s) return ans; ans = min(ans, i-j); } } return ans; } }; int main () { int xlist[] = {2,3,1,2,4,3}; vector<int> x(xlist, xlist+sizeof(xlist)/sizeof(int)); for(int i = 0; i < x.size(); i++) printf("%d ",x[i]); printf("\n"); Solution s; printf("%d\n",s.minSubArrayLen(7,x)); return 0; }
25.697674
71
0.489593
[ "vector" ]
5b873e0aa71b6132d9ce74765d0c881dc31b9ded
12,169
cpp
C++
tests/http_server_filter_tests.cpp
dmlys/netlib
81627e5f9bea8f1225b1083efa66a8b5dcb9c514
[ "BSL-1.0" ]
1
2018-05-14T13:46:59.000Z
2018-05-14T13:46:59.000Z
tests/http_server_filter_tests.cpp
dmlys/netlib
81627e5f9bea8f1225b1083efa66a8b5dcb9c514
[ "BSL-1.0" ]
null
null
null
tests/http_server_filter_tests.cpp
dmlys/netlib
81627e5f9bea8f1225b1083efa66a8b5dcb9c514
[ "BSL-1.0" ]
null
null
null
#include <ext/net/http/http_server.hpp> #include <ext/net/http/zlib_filter.hpp> #include <ext/stream_filtering.hpp> #include <ext/stream_filtering/zlib.hpp> #include <ext/base64.hpp> #include <boost/test/unit_test.hpp> #include <boost/test/data/test_case.hpp> #include <boost/test/data/dataset.hpp> #include "test_files.h" #include "http_server_tests_utils.hpp" using namespace ext::net; using namespace ext::net::http; using namespace ext::net::http::test_utils; using boost::unit_test::data::make; #ifdef EXT_ENABLE_CPPZLIB static std::string gzip(std::string_view data) { ext::stream_filtering::zlib_deflate_filter zipper; std::array filters = { &zipper }; std::string result; ext::stream_filtering::filter_memory(filters, data, result); return result; } static std::string ungzip(std::string_view data) { ext::stream_filtering::zlib_inflate_filter unzipper; std::array filters = { &unzipper }; std::string result; ext::stream_filtering::filter_memory(filters, data, result); return result; } static http_request make_gzip_request(std::string method, std::string url, std::string_view body) { http_request req; req.method = std::move(method); req.url = std::move(url); req.body = gzip(body); set_header(req.headers, "Content-Length", std::to_string(*size(req.body))); set_header(req.headers, "Content-Encoding", "gzip"); set_header(req.headers, "Accept-Encoding", "gzip"); return req; } #endif // EXT_ENABLE_CPPZLIB BOOST_AUTO_TEST_SUITE(http_server_tests) #ifdef EXT_ENABLE_CPPZLIB BOOST_DATA_TEST_CASE(zlib_filter_simple_test, make(configurations), configurator) { http_server server; auto addr = configurator(server); server.start(); server.add_filter(ext::make_intrusive<ext::net::http::zlib_filter>()); async_request_queue request_queue; server.add_handler("/echo", request_queue.handler(), http_body_type::string); auto sock = connect_socket(addr); auto httpreq = make_gzip_request("PUT", "/echo", "test"); write_request(sock, addr, httpreq); auto request = request_queue.next_request(); auto reqbody = std::get<std::string>(request.body); BOOST_CHECK_EQUAL(reqbody, "test"); request_queue.answer(make_response(200, "test")); auto response = receive_response(sock); BOOST_CHECK_EQUAL(response.http_code, 200); BOOST_REQUIRE_EQUAL(get_header_value(response.headers, "Content-Encoding"), "gzip"); auto respbody = ungzip(std::get<std::string>(response.body)); BOOST_CHECK_EQUAL(respbody, "test"); server.stop(); } BOOST_DATA_TEST_CASE(zlib_filter_simple_huge_test, make(configurations), configurator) { http_server server; auto addr = configurator(server); std::string reqbody; reqbody.resize(1024 * 1024, '1'); // one meg of '1' server.start(); server.add_filter(ext::make_intrusive<ext::net::http::zlib_filter>()); server.add_handler("/echo", [](std::string & str) { return str; }); auto sock = connect_socket(addr); auto httpreq = make_gzip_request("PUT", "/echo", reqbody); write_request(sock, addr, httpreq); auto httpresp = receive_response(sock); BOOST_CHECK_EQUAL(httpresp.http_code, 200); BOOST_REQUIRE_EQUAL(get_header_value(httpresp.headers, "Content-Encoding"), "gzip"); auto respbody = ungzip(std::get<std::string>(httpresp.body)); BOOST_CHECK(respbody == reqbody); } #endif // EXT_ENABLE_CPPZLIB BOOST_DATA_TEST_CASE(base64_filter_simple_test, make(configurations), configurator) { http_server server; auto addr = configurator(server); std::string reqbody; reqbody.resize(1024 * 1024, '1'); // one meg of '1' server.start(); server.add_filter(ext::make_intrusive<dumb_base64_filter>()); server.add_handler("/echo", [](std::string & str) { return str; }); auto httpresp = send_put_request(addr, "/echo", ext::encode_base64(reqbody)); BOOST_CHECK_EQUAL(httpresp.http_code, 200); auto respbody = std::get<std::string>(httpresp.body); respbody = ext::decode_base64(respbody); BOOST_CHECK(respbody == reqbody); } BOOST_DATA_TEST_CASE(base64_filter_stream_test, make(configurations), configurator) { http_server server; auto addr = configurator(server); std::string testbody, reqbody; testbody.resize(1024 * 1024, '1'); server.start(); server.add_filter(ext::make_intrusive<dumb_base64_filter>()); ext::promise<std::string> reqbody_promise; auto handler = [&reqbody_promise] (std::unique_ptr<std::streambuf> & stream) { auto body = read_stream(stream.get()); reqbody_promise.set_value(body); return std::make_unique<std::stringbuf>(body); }; server.add_handler("/test", handler); auto sock = connect_socket(addr); auto httpresp = send_put_request(addr, "/test", ext::encode_base64(testbody)); reqbody = reqbody_promise.get_future().get(); BOOST_CHECK(reqbody == testbody); BOOST_CHECK_EQUAL(httpresp.http_code, 200); auto respbody = std::get<std::string>(httpresp.body); respbody = ext::decode_base64(respbody); BOOST_CHECK(respbody == testbody); } BOOST_DATA_TEST_CASE(base64_filter_async_request_test, make(configurations), configurator) { http_server server; auto addr = configurator(server); async_request_queue request_queue; std::string testbody, reqbody; testbody.resize(1024 * 1024, '1'); server.start(); server.add_filter(ext::make_intrusive<dumb_base64_filter>()); server.add_handler("/test", request_queue.handler(), http_body_type::async); auto sock = connect_socket(addr); auto httpreq = make_request("PUT", "/test", testbody); httpreq.body = ext::encode_base64(std::get<std::string>(httpreq.body)); set_header(httpreq.headers, "Content-Length", std::to_string(*size(httpreq.body))); write_headers(sock, addr, httpreq); auto source_req = request_queue.next_request(); auto & body_source = std::get<std::unique_ptr<async_http_body_source>>(source_req.body); auto f = ext::async(ext::launch::async, [&body_source] { std::vector<char> buffer; std::string reqbody; for (;;) { auto f = body_source->read_some(std::move(buffer)); auto result = f.get(); if (not result) break; buffer = std::move(*result); reqbody.append(buffer.data(), buffer.size()); } return reqbody; }); auto & input_body = std::get<std::string>(httpreq.body); sock.write(input_body.data(), input_body.size()); reqbody = f.get(); BOOST_CHECK(reqbody == testbody); request_queue.answer(make_response(200, "")); auto httpresp = receive_response(sock); BOOST_CHECK_EQUAL(httpresp.http_code, 200); } BOOST_DATA_TEST_CASE(base64_filter_async_response_test, make(configurations), configurator) { http_server server; auto addr = configurator(server); async_request_queue request_queue; std::string testbody, respbody; testbody.resize(1024 * 1024, '1'); server.start(); server.add_filter(ext::make_intrusive<dumb_base64_filter>()); server.add_handler("/test", request_queue.handler(), http_body_type::async); auto sock = connect_socket(addr); write_get_request(sock, addr, "/test"); std::vector<std::string> async_parts; for (unsigned i = 0; i < 1024; i++) async_parts.push_back(std::string(testbody.substr(i * 1024, 1024))); http_response httpresp; httpresp.http_code = 200; httpresp.body = std::make_unique<parted_asource>(std::move(async_parts)); request_queue.answer(std::move(httpresp)); httpresp = receive_response(sock); BOOST_CHECK_EQUAL(httpresp.http_code, 200); respbody = std::get<std::string>(httpresp.body); respbody = ext::decode_base64(respbody); BOOST_CHECK(testbody == respbody); } #ifdef EXT_ENABLE_CPPZLIB BOOST_DATA_TEST_CASE(complex_filter_stream_request_test, make(configurations), configurator) { http_server server; auto addr = configurator(server); std::string testbody, reqbody; testbody.resize(1024 * 1024, '1'); server.start(); server.add_filter(ext::make_intrusive<ext::net::http::zlib_filter>()); server.add_filter(ext::make_intrusive<dumb_base64_filter>()); ext::promise<std::string> reqbody_promise; auto handler = [&reqbody_promise] (std::unique_ptr<std::streambuf> & stream) { auto body = read_stream(stream.get()); reqbody_promise.set_value(body); return ""; }; server.add_handler("/test", handler); auto sock = connect_socket(addr); auto httpreq = make_gzip_request("PUT", "/test", testbody); httpreq.body = ext::encode_base64(std::get<std::string>(httpreq.body)); set_header(httpreq.headers, "Content-Length", std::to_string(*size(httpreq.body))); write_request(sock, addr, httpreq); reqbody = reqbody_promise.get_future().get(); BOOST_CHECK(reqbody == testbody); auto httpresp = receive_response(sock); BOOST_CHECK_EQUAL(httpresp.http_code, 200); } BOOST_DATA_TEST_CASE(complex_filter_stream_response_test, make(configurations), configurator) { http_server server; auto addr = configurator(server); std::string testbody, respbody; testbody.resize(1024 * 1024, '1'); server.start(); server.add_filter(ext::make_intrusive<ext::net::http::zlib_filter>()); server.add_filter(ext::make_intrusive<dumb_base64_filter>()); auto handler = [&testbody] { return std::make_unique<std::stringbuf>(testbody); }; server.add_handler("/test", handler); auto sock = connect_socket(addr); http_request httpreq = make_request("GET", "/test", {}); set_header(httpreq.headers, "Accept-Encoding", "gzip"); write_request(sock, addr, httpreq); auto httpresp = receive_response(sock); BOOST_CHECK_EQUAL(httpresp.http_code, 200); BOOST_CHECK_EQUAL(get_header_value(httpresp.headers, "Content-Encoding"), "gzip"); respbody = std::get<std::string>(httpresp.body); respbody = ext::decode_base64(respbody); respbody = ungzip(respbody); BOOST_CHECK(testbody == respbody); } BOOST_DATA_TEST_CASE(complex_filter_async_request_test, make(configurations), configurator) { http_server server; auto addr = configurator(server); async_request_queue request_queue; std::string testbody, reqbody; testbody.resize(1024 * 1024, '1'); server.start(); server.add_filter(ext::make_intrusive<ext::net::http::zlib_filter>()); server.add_filter(ext::make_intrusive<dumb_base64_filter>()); server.add_handler("/test", request_queue.handler(), http_body_type::async); auto sock = connect_socket(addr); auto httpreq = make_gzip_request("PUT", "/test", testbody); httpreq.body = ext::encode_base64(std::get<std::string>(httpreq.body)); set_header(httpreq.headers, "Content-Length", std::to_string(*size(httpreq.body))); write_request(sock, addr, httpreq); auto source_req = request_queue.next_request(); auto & body_source = std::get<std::unique_ptr<async_http_body_source>>(source_req.body); reqbody = read_asource(body_source.get()); BOOST_CHECK(reqbody == testbody); request_queue.answer(make_response(200, "")); auto httpresp = receive_response(sock); BOOST_CHECK_EQUAL(httpresp.http_code, 200); } BOOST_DATA_TEST_CASE(complex_filter_async_response_test, make(configurations), configurator) { http_server server; auto addr = configurator(server); async_request_queue request_queue; std::string testbody, respbody; testbody.resize(1024 * 1024, '1'); server.start(); server.add_filter(ext::make_intrusive<ext::net::http::zlib_filter>()); server.add_filter(ext::make_intrusive<dumb_base64_filter>()); server.add_handler("/test", request_queue.handler(), http_body_type::async); auto sock = connect_socket(addr); http_request httpreq = make_request("GET", "/test", {}); set_header(httpreq.headers, "Accept-Encoding", "gzip"); write_request(sock, addr, httpreq); std::vector<std::string> async_parts; for (unsigned i = 0; i < 1024; i++) async_parts.push_back(std::string(testbody.substr(i * 1024, 1024))); http_response httpresp; httpresp.http_code = 200; httpresp.body = std::make_unique<parted_asource>(std::move(async_parts)); request_queue.answer(std::move(httpresp)); httpresp = receive_response(sock); BOOST_CHECK_EQUAL(httpresp.http_code, 200); BOOST_CHECK_EQUAL(get_header_value(httpresp.headers, "Content-Encoding"), "gzip"); respbody = std::get<std::string>(httpresp.body); respbody = ext::decode_base64(respbody); respbody = ungzip(respbody); BOOST_CHECK(testbody == respbody); } #endif // EXT_ENABLE_CPPZLIB BOOST_AUTO_TEST_SUITE_END()
30.046914
97
0.741556
[ "vector" ]
5b8acc386b147593c33629ed21f917ba25e8ebff
14,378
cc
C++
cartographer/evaluation/trajectory_builder_evaluation.cc
tu-darmstadt-ros-pkg/cartographer
ddbc9464cfc80e7d0b3bd32c068d6e14443cabf4
[ "Apache-2.0" ]
9
2017-05-04T06:57:07.000Z
2021-07-18T17:59:46.000Z
cartographer/evaluation/trajectory_builder_evaluation.cc
tu-darmstadt-ros-pkg/hectorgrapher
f04b15b2dbd31004d99d5e5584519416d11ac420
[ "Apache-2.0" ]
1
2020-09-23T10:41:32.000Z
2020-09-23T10:41:32.000Z
cartographer/evaluation/trajectory_builder_evaluation.cc
tu-darmstadt-ros-pkg/cartographer
ddbc9464cfc80e7d0b3bd32c068d6e14443cabf4
[ "Apache-2.0" ]
3
2019-09-01T05:47:22.000Z
2021-05-27T07:03:44.000Z
#include "cartographer/mapping/internal/3d/local_trajectory_builder_3d.h" #include <memory> #include <random> #include "matplotlibcpp.h" #include "Eigen/Core" #include "cartographer/common/lua_parameter_dictionary_test_helpers.h" #include "cartographer/common/time.h" #include "cartographer/evaluation/grid_drawer.h" #include "cartographer/evaluation/simulation/range_sensor.h" #include "cartographer/evaluation/simulation/scene.h" #include "cartographer/mapping/3d/hybrid_grid.h" #include "cartographer/mapping/internal/3d/local_trajectory_builder_options_3d.h" #include "cartographer/mapping/internal/3d/optimizing_local_trajectory_builder.h" #include "cartographer/sensor/range_data.h" #include "cartographer/transform/rigid_transform.h" #include "cartographer/transform/rigid_transform_test_helpers.h" #include "cartographer/transform/transform.h" namespace cartographer { namespace mapping { namespace { constexpr char kSensorId[] = "sensor_id"; class LocalTrajectoryBuilderEval { public: mapping::proto::LocalTrajectoryBuilderOptions3D CreateTrajectoryBuilderEvalOptions3D() { auto parameter_dictionary = common::MakeDictionary(R"text( return { min_range = 0.5, max_range = 50., num_accumulated_range_data = 1, voxel_filter_size = 0.2, high_resolution_adaptive_voxel_filter = { max_length = 0.7, min_num_points = 200, max_range = 50., }, low_resolution_adaptive_voxel_filter = { max_length = 0.7, min_num_points = 200, max_range = 50., }, use_online_correlative_scan_matching = false, real_time_correlative_scan_matcher = { linear_search_window = 0.2, angular_search_window = math.rad(1.), translation_delta_cost_weight = 1e-1, rotation_delta_cost_weight = 1., }, ceres_scan_matcher = { occupied_space_weight_0 = 5., occupied_space_weight_1 = 20., translation_weight = 0.1, rotation_weight = 0.3, only_optimize_yaw = false, ceres_solver_options = { use_nonmonotonic_steps = true, max_num_iterations = 20, num_threads = 1, }, }, motion_filter = { max_time_seconds = 0.2, max_distance_meters = 0.02, max_angle_radians = 0.001, }, imu_gravity_time_constant = 1., rotational_histogram_size = 120, submaps = { high_resolution = 0.2, high_resolution_max_range = 50., low_resolution = 0.5, num_range_data = 45000, grid_type = "TSDF", range_data_inserter = { range_data_inserter_type = "TSDF_INSERTER_3D", probability_grid_range_data_inserter = { hit_probability = 0.55, miss_probability = 0.49, num_free_space_voxels = 2, }, tsdf_range_data_inserter = { relative_truncation_distance = 4, maximum_weight = 1000., num_free_space_voxels = 0, project_sdf_distance_to_scan_normal = true, weight_function_epsilon = 1, weight_function_sigma = 4., normal_estimate_max_nn = 20., normal_estimate_radius = 0.3, }, }, }, optimizing_local_trajectory_builder = { high_resolution_grid_weight = 100, low_resolution_grid_weight = 10, velocity_weight = 1, translation_weight = 1, rotation_weight = 1, odometry_translation_weight = 1, odometry_rotation_weight = 1, initialize_map_orientation_with_imu = true, calibrate_imu = false, ct_window_horizon = 0.6, ct_window_rate = 0.3, imu_integrator = "RK4", imu_cost_term = "DIRECT", sync_control_points_with_range_data = true, }, } )text"); return mapping::CreateLocalTrajectoryBuilderOptions3D( parameter_dictionary.get()); } LocalTrajectoryBuilderEval() { local_trajectory_builder_.reset(new OptimizingLocalTrajectoryBuilder( CreateTrajectoryBuilderEvalOptions3D(), {kSensorId})); SetUp(); // VerifyAccuracy(GenerateCorkscrewTrajectory(), 1e-1); Evaluate(0.01); } public: struct TrajectoryNode { common::Time time; transform::Rigid3d pose; }; void SetUp() { scene_.AddBox({-5.f, -5.f, -1.f}, {10.f, 20.f, 10.f}); scene_.AddSphere({5.f, 5.f, 0.f}, 3.f); scene_.AddSphere({-3.f, 2.f, -1.f}, 1.f); scene_.AddSphere({-2.f, -2.f, 2.f}, 2.f); } void AddLinearOnlyImuObservation(const common::Time time, const transform::Rigid3d& expected_pose) { const Eigen::Vector3d gravity = expected_pose.rotation().inverse() * Eigen::Vector3d(0., 0., 9.81); local_trajectory_builder_->AddImuData( sensor::ImuData{time, gravity, Eigen::Vector3d::Zero()}); } void GetLinearTrajectory(double t, Eigen::Vector3f& p, Eigen::Vector3f& v, Eigen::Vector3f& a) { double t_init = 12.0; double velocity = 0.5; if (t <= t_init) { p = {0.f, 0.f, 0.f}; v = {0.f, 0.f, 0.f}; a = {0.f, 0.f, 0.f}; } else { p = {0.f, 0.f, float(t - t_init) * float(velocity)}; v = {0.f, 0.f, float(velocity)}; a = {0.f, 0.f, 0.f}; } } std::vector<TrajectoryNode> GenerateCorkscrewTrajectory() { std::vector<TrajectoryNode> trajectory; common::Time current_time = common::FromUniversal(12345678); // One second at zero velocity. for (int i = 0; i != 15; ++i) { current_time += common::FromSeconds(0.3); trajectory.push_back( TrajectoryNode{current_time, transform::Rigid3d::Identity()}); } // Corkscrew translation and constant velocity rotation. for (double t = 0.; t <= 1.6; t += 0.05) { current_time += common::FromSeconds(0.3); trajectory.push_back(TrajectoryNode{ current_time, transform::Rigid3d::Translation(Eigen::Vector3d(0, 0, 1. * t))}); // trajectory.push_back( // TrajectoryNode{current_time, transform::Rigid3d::Identity()}); } return trajectory; } // void VerifyAccuracy(const std::vector<TrajectoryNode>& // expected_trajectory, // double expected_accuracy) { // int num_poses = 0; // for (const TrajectoryNode& node : expected_trajectory) { // AddLinearOnlyImuObservation(node.time, node.pose); // const auto range_data = // range_sensor_.GenerateRangeData(node.pose, scene_); // const // std::unique_ptr<OptimizingLocalTrajectoryBuilder::MatchingResult> // matching_result = local_trajectory_builder_->AddRangeData( // kSensorId, sensor::TimedPointCloudData{ // node.time, range_data.origin, // range_data.returns}); // // sensor::WriteToPCD( // sensor::TransformTimedRangeData(range_data, // node.pose.cast<float>()), "range_data_" + // std::to_string(num_poses) + ".pcd"); // if (matching_result != nullptr) { // // cartographer::evaluation::GridDrawer grid_drawer = // // cartographer::evaluation::GridDrawer(static_cast<const // // // HybridGridTSDF&>(matching_result.get()->insertion_result.get()->insertion_submaps[0]->high_resolution_hybrid_grid())); // // cartographer::evaluation::GridDrawer grid_drawer = // // cartographer::evaluation::GridDrawer(); // // grid_drawer.DrawInterpolatedTSD(static_cast<const // // HybridGridTSDF&>( // // matching_result.get() // // ->insertion_result.get() // // ->insertion_submaps[0] // // ->low_resolution_hybrid_grid()), // // 0.2); // // grid_drawer.DrawPointcloud(sample.range_data.returns, // // transform::Rigid3d::Identity()); // // grid_drawer.ToFile("interpolated_grid_with_cloud" + // // std::to_string(num_poses) + ".png"); // LOG(INFO) << "res " << matching_result->local_pose; // LOG(INFO) << "res " << matching_result->time; // LOG(INFO) << "exp " << node.pose; // LOG(INFO) << "exp " << node.time; // // EXPECT_THAT(matching_result->local_pose, // // transform::IsNearly(node.pose, 1e-1)); // // ++num_poses; // LOG(INFO) << "num_poses: " << num_poses; // } // } // } void Evaluate(double expected_accuracy) { double imu_frequency = 100; double lidar_frequency = 20; double sim_step_duration = 0.01; double t_end = 4.0; int num_poses = 0; std::vector<float> positions_x_measured = {}; std::vector<float> positions_y_measured = {}; std::vector<float> positions_z_measured = {}; std::vector<float> positions_x_gt = {}; std::vector<float> positions_y_gt = {}; std::vector<float> positions_z_gt = {}; std::vector<float> timestamps_measured = {}; std::vector<float> timestamps_gt = {}; common::Time start_time = common::FromUniversal(12345678); common::Time last_imu_measurement_time = common::FromUniversal(0); common::Time last_lidar_measurement_time = common::FromUniversal(0); for (common::Time current_time = start_time; common::ToSeconds(current_time - start_time) < t_end; current_time += common::FromSeconds(sim_step_duration)) { Eigen::Vector3f p, v, a; GetLinearTrajectory(common::ToSeconds(current_time - start_time), p, v, a); transform::Rigid3d expected_pose = {p.cast<double>(), Eigen::Quaterniond::Identity()}; if (common::ToSeconds(current_time - last_imu_measurement_time) >= 1.0 / imu_frequency) { AddLinearOnlyImuObservation(current_time, expected_pose); last_imu_measurement_time = current_time; } if (common::ToSeconds(current_time - last_lidar_measurement_time) < 1.0 / lidar_frequency) { continue; } const auto range_data = range_sensor_.GenerateRangeData( common::ToSeconds(current_time - start_time), expected_pose, scene_); const std::unique_ptr<OptimizingLocalTrajectoryBuilder::MatchingResult> matching_result = local_trajectory_builder_->AddRangeData( kSensorId, sensor::TimedPointCloudData{current_time, range_data.origin, range_data.returns}); // sensor::WriteToPCD( // sensor::TransformTimedRangeData(range_data, // expected_pose.cast<float>()), "range_data_" + // std::to_string(num_poses) + ".pcd"); if (matching_result != nullptr) { // cartographer::evaluation::GridDrawer grid_drawer = // cartographer::evaluation::GridDrawer(static_cast<const // HybridGridTSDF&>(matching_result.get()->insertion_result.get()->insertion_submaps[0]->high_resolution_hybrid_grid())); // cartographer::evaluation::GridDrawer grid_drawer = // cartographer::evaluation::GridDrawer(); // grid_drawer.DrawInterpolatedTSD(static_cast<const // HybridGridTSDF&>( // matching_result.get() // ->insertion_result.get() // ->insertion_submaps[0] // ->low_resolution_hybrid_grid()), // 0.2); // grid_drawer.DrawPointcloud(sample.range_data.returns, // transform::Rigid3d::Identity()); // grid_drawer.ToFile("interpolated_grid_with_cloud" + // std::to_string(num_poses) + ".png"); LOG(INFO) << "res " << matching_result->local_pose; LOG(INFO) << "res " << common::ToSeconds(matching_result->time - start_time); LOG(INFO) << "exp " << expected_pose; LOG(INFO) << "exp " << common::ToSeconds(current_time - start_time); // EXPECT_THAT(matching_result->local_pose, // transform::IsNearly(node.pose, 1e-1)); positions_x_measured.push_back( matching_result->local_pose.translation().x()); positions_y_measured.push_back( matching_result->local_pose.translation().y()); positions_z_measured.push_back( matching_result->local_pose.translation().z()); timestamps_measured.push_back( common::ToSeconds(matching_result->time - start_time)); ++num_poses; LOG(INFO) << "num_poses: " << num_poses; } } matplotlibcpp::plot(); matplotlibcpp::named_plot("x", timestamps_measured, positions_x_measured); matplotlibcpp::named_plot("y", timestamps_measured, positions_y_measured); matplotlibcpp::named_plot("z", timestamps_measured, positions_z_measured); matplotlibcpp::legend(); matplotlibcpp::show(); } std::unique_ptr<OptimizingLocalTrajectoryBuilder> local_trajectory_builder_; evaluation::Scene scene_; evaluation::RangeSensor range_sensor_; }; } // namespace } // namespace mapping } // namespace cartographer int main(int argc, char** argv) { google::InitGoogleLogging(argv[0]); FLAGS_logtostderr = true; google::ParseCommandLineFlags(&argc, &argv, true); cartographer::mapping::LocalTrajectoryBuilderEval(); // LocalTrajectoryBuilderEval // cartographer::evaluation::RunScanMatchingEvaluationRotatingScan(); }
40.615819
138
0.588538
[ "vector", "transform", "3d" ]
5b9286bcc2a95ed31e6de6c9ceb9148ae9b648cb
31,780
tcc
C++
seqsvr/proto/gen-cpp2/seqsvr_types.tcc
jjzhang166/seqsvr
34ba38bae75033805246b3f7d62cda082c36ec20
[ "Apache-2.0" ]
103
2016-12-09T11:15:52.000Z
2020-10-31T07:51:10.000Z
seqsvr/proto/gen-cpp2/seqsvr_types.tcc
jjzhang166/seqsvr
34ba38bae75033805246b3f7d62cda082c36ec20
[ "Apache-2.0" ]
7
2017-01-06T09:28:14.000Z
2017-11-25T10:44:16.000Z
seqsvr/proto/gen-cpp2/seqsvr_types.tcc
jjzhang166/seqsvr
34ba38bae75033805246b3f7d62cda082c36ec20
[ "Apache-2.0" ]
31
2017-03-09T06:48:32.000Z
2020-11-03T04:19:40.000Z
/** * Autogenerated by Thrift * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ #pragma once #include "seqsvr_types.h" #include <thrift/lib/cpp/TApplicationException.h> #include <folly/io/IOBuf.h> #include <folly/io/IOBufQueue.h> #include <thrift/lib/cpp/transport/THeader.h> // #include <thrift/lib/cpp2/server/Cpp2ConnContext.h> #include <thrift/lib/cpp2/GeneratedCodeHelper.h> #include <thrift/lib/cpp2/GeneratedSerializationCodeHelper.h> #include <thrift/lib/cpp2/protocol/BinaryProtocol.h> #include <thrift/lib/cpp2/protocol/CompactProtocol.h> #include <thrift/lib/cpp2/protocol/SimpleJSONProtocol.h> namespace seqsvr { template <class Protocol_> uint32_t NodeAddrInfo::read(Protocol_* iprot) { uint32_t xfer = 0; std::string _fname; apache::thrift::protocol::TType _ftype; int16_t fid; xfer += iprot->readStructBegin(_fname); using apache::thrift::TProtocolException; while (true) { xfer += iprot->readFieldBegin(_fname, _ftype, fid); if (_ftype == apache::thrift::protocol::T_STOP) { break; } if (fid == std::numeric_limits<int16_t>::min()) { this->translateFieldName(_fname, fid, _ftype); } switch (fid) { case 1: { if (_ftype == apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->ip); this->__isset.ip = true; } else { xfer += iprot->skip(_ftype); } break; } case 2: { if (_ftype == apache::thrift::protocol::T_I32) { xfer += iprot->readI32(this->port); this->__isset.port = true; } else { xfer += iprot->skip(_ftype); } break; } default: { xfer += iprot->skip(_ftype); break; } } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); return xfer; } template <class Protocol_> uint32_t NodeAddrInfo::serializedSize(Protocol_ const* prot_) const { uint32_t xfer = 0; xfer += prot_->serializedStructSize("NodeAddrInfo"); xfer += prot_->serializedFieldSize("ip", apache::thrift::protocol::T_STRING, 1); xfer += prot_->serializedSizeString(this->ip); xfer += prot_->serializedFieldSize("port", apache::thrift::protocol::T_I32, 2); xfer += prot_->serializedSizeI32(this->port); xfer += prot_->serializedSizeStop(); return xfer; } template <class Protocol_> uint32_t NodeAddrInfo::serializedSizeZC(Protocol_ const* prot_) const { uint32_t xfer = 0; xfer += prot_->serializedStructSize("NodeAddrInfo"); xfer += prot_->serializedFieldSize("ip", apache::thrift::protocol::T_STRING, 1); xfer += prot_->serializedSizeString(this->ip); xfer += prot_->serializedFieldSize("port", apache::thrift::protocol::T_I32, 2); xfer += prot_->serializedSizeI32(this->port); xfer += prot_->serializedSizeStop(); return xfer; } template <class Protocol_> uint32_t NodeAddrInfo::write(Protocol_* prot_) const { uint32_t xfer = 0; xfer += prot_->writeStructBegin("NodeAddrInfo"); xfer += prot_->writeFieldBegin("ip", apache::thrift::protocol::T_STRING, 1); xfer += prot_->writeString(this->ip); xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldBegin("port", apache::thrift::protocol::T_I32, 2); xfer += prot_->writeI32(this->port); xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldStop(); xfer += prot_->writeStructEnd(); return xfer; } } // seqsvr namespace apache { namespace thrift { }} // apache::thrift namespace seqsvr { template <class Protocol_> uint32_t RangeID::read(Protocol_* iprot) { uint32_t xfer = 0; std::string _fname; apache::thrift::protocol::TType _ftype; int16_t fid; xfer += iprot->readStructBegin(_fname); using apache::thrift::TProtocolException; while (true) { xfer += iprot->readFieldBegin(_fname, _ftype, fid); if (_ftype == apache::thrift::protocol::T_STOP) { break; } if (fid == std::numeric_limits<int16_t>::min()) { this->translateFieldName(_fname, fid, _ftype); } switch (fid) { case 1: { if (_ftype == apache::thrift::protocol::T_I32) { xfer += iprot->readI32(this->id_begin); this->__isset.id_begin = true; } else { xfer += iprot->skip(_ftype); } break; } case 2: { if (_ftype == apache::thrift::protocol::T_I32) { xfer += iprot->readI32(this->size); this->__isset.size = true; } else { xfer += iprot->skip(_ftype); } break; } default: { xfer += iprot->skip(_ftype); break; } } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); return xfer; } template <class Protocol_> uint32_t RangeID::serializedSize(Protocol_ const* prot_) const { uint32_t xfer = 0; xfer += prot_->serializedStructSize("RangeID"); xfer += prot_->serializedFieldSize("id_begin", apache::thrift::protocol::T_I32, 1); xfer += prot_->serializedSizeI32(this->id_begin); xfer += prot_->serializedFieldSize("size", apache::thrift::protocol::T_I32, 2); xfer += prot_->serializedSizeI32(this->size); xfer += prot_->serializedSizeStop(); return xfer; } template <class Protocol_> uint32_t RangeID::serializedSizeZC(Protocol_ const* prot_) const { uint32_t xfer = 0; xfer += prot_->serializedStructSize("RangeID"); xfer += prot_->serializedFieldSize("id_begin", apache::thrift::protocol::T_I32, 1); xfer += prot_->serializedSizeI32(this->id_begin); xfer += prot_->serializedFieldSize("size", apache::thrift::protocol::T_I32, 2); xfer += prot_->serializedSizeI32(this->size); xfer += prot_->serializedSizeStop(); return xfer; } template <class Protocol_> uint32_t RangeID::write(Protocol_* prot_) const { uint32_t xfer = 0; xfer += prot_->writeStructBegin("RangeID"); xfer += prot_->writeFieldBegin("id_begin", apache::thrift::protocol::T_I32, 1); xfer += prot_->writeI32(this->id_begin); xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldBegin("size", apache::thrift::protocol::T_I32, 2); xfer += prot_->writeI32(this->size); xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldStop(); xfer += prot_->writeStructEnd(); return xfer; } } // seqsvr namespace apache { namespace thrift { }} // apache::thrift namespace seqsvr { template <class Protocol_> uint32_t RouterNode::read(Protocol_* iprot) { uint32_t xfer = 0; std::string _fname; apache::thrift::protocol::TType _ftype; int16_t fid; xfer += iprot->readStructBegin(_fname); using apache::thrift::TProtocolException; while (true) { xfer += iprot->readFieldBegin(_fname, _ftype, fid); if (_ftype == apache::thrift::protocol::T_STOP) { break; } if (fid == std::numeric_limits<int16_t>::min()) { this->translateFieldName(_fname, fid, _ftype); } switch (fid) { case 1: { if (_ftype == apache::thrift::protocol::T_STRUCT) { xfer += ::apache::thrift::Cpp2Ops< ::seqsvr::NodeAddrInfo>::read(iprot, &this->node_addr); this->__isset.node_addr = true; } else { xfer += iprot->skip(_ftype); } break; } case 2: { if (_ftype == apache::thrift::protocol::T_LIST) { this->section_ranges = std::vector< ::seqsvr::RangeID>(); xfer += ::apache::thrift::detail::pm::protocol_methods< ::apache::thrift::type_class::list<::apache::thrift::type_class::structure>, std::vector< ::seqsvr::RangeID>>::read(*iprot, this->section_ranges); this->__isset.section_ranges = true; } else { xfer += iprot->skip(_ftype); } break; } default: { xfer += iprot->skip(_ftype); break; } } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); return xfer; } template <class Protocol_> uint32_t RouterNode::serializedSize(Protocol_ const* prot_) const { uint32_t xfer = 0; xfer += prot_->serializedStructSize("RouterNode"); xfer += prot_->serializedFieldSize("node_addr", apache::thrift::protocol::T_STRUCT, 1); xfer += ::apache::thrift::Cpp2Ops< ::seqsvr::NodeAddrInfo>::serializedSize(prot_, &this->node_addr); xfer += prot_->serializedFieldSize("section_ranges", apache::thrift::protocol::T_LIST, 2); xfer += ::apache::thrift::detail::pm::protocol_methods< ::apache::thrift::type_class::list<::apache::thrift::type_class::structure>, std::vector< ::seqsvr::RangeID>>::serializedSize<false>(*prot_, this->section_ranges); xfer += prot_->serializedSizeStop(); return xfer; } template <class Protocol_> uint32_t RouterNode::serializedSizeZC(Protocol_ const* prot_) const { uint32_t xfer = 0; xfer += prot_->serializedStructSize("RouterNode"); xfer += prot_->serializedFieldSize("node_addr", apache::thrift::protocol::T_STRUCT, 1); xfer += ::apache::thrift::Cpp2Ops< ::seqsvr::NodeAddrInfo>::serializedSizeZC(prot_, &this->node_addr); xfer += prot_->serializedFieldSize("section_ranges", apache::thrift::protocol::T_LIST, 2); xfer += ::apache::thrift::detail::pm::protocol_methods< ::apache::thrift::type_class::list<::apache::thrift::type_class::structure>, std::vector< ::seqsvr::RangeID>>::serializedSize<false>(*prot_, this->section_ranges); xfer += prot_->serializedSizeStop(); return xfer; } template <class Protocol_> uint32_t RouterNode::write(Protocol_* prot_) const { uint32_t xfer = 0; xfer += prot_->writeStructBegin("RouterNode"); xfer += prot_->writeFieldBegin("node_addr", apache::thrift::protocol::T_STRUCT, 1); xfer += ::apache::thrift::Cpp2Ops< ::seqsvr::NodeAddrInfo>::write(prot_, &this->node_addr); xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldBegin("section_ranges", apache::thrift::protocol::T_LIST, 2); xfer += ::apache::thrift::detail::pm::protocol_methods< ::apache::thrift::type_class::list<::apache::thrift::type_class::structure>, std::vector< ::seqsvr::RangeID>>::write(*prot_, this->section_ranges); xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldStop(); xfer += prot_->writeStructEnd(); return xfer; } } // seqsvr namespace apache { namespace thrift { }} // apache::thrift namespace seqsvr { template <class Protocol_> uint32_t Router::read(Protocol_* iprot) { uint32_t xfer = 0; std::string _fname; apache::thrift::protocol::TType _ftype; int16_t fid; xfer += iprot->readStructBegin(_fname); using apache::thrift::TProtocolException; while (true) { xfer += iprot->readFieldBegin(_fname, _ftype, fid); if (_ftype == apache::thrift::protocol::T_STOP) { break; } if (fid == std::numeric_limits<int16_t>::min()) { this->translateFieldName(_fname, fid, _ftype); } switch (fid) { case 1: { if (_ftype == apache::thrift::protocol::T_I32) { xfer += iprot->readI32(this->version); this->__isset.version = true; } else { xfer += iprot->skip(_ftype); } break; } case 2: { if (_ftype == apache::thrift::protocol::T_LIST) { this->node_list = std::vector< ::seqsvr::RouterNode>(); xfer += ::apache::thrift::detail::pm::protocol_methods< ::apache::thrift::type_class::list<::apache::thrift::type_class::structure>, std::vector< ::seqsvr::RouterNode>>::read(*iprot, this->node_list); this->__isset.node_list = true; } else { xfer += iprot->skip(_ftype); } break; } default: { xfer += iprot->skip(_ftype); break; } } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); return xfer; } template <class Protocol_> uint32_t Router::serializedSize(Protocol_ const* prot_) const { uint32_t xfer = 0; xfer += prot_->serializedStructSize("Router"); xfer += prot_->serializedFieldSize("version", apache::thrift::protocol::T_I32, 1); xfer += prot_->serializedSizeI32(this->version); xfer += prot_->serializedFieldSize("node_list", apache::thrift::protocol::T_LIST, 2); xfer += ::apache::thrift::detail::pm::protocol_methods< ::apache::thrift::type_class::list<::apache::thrift::type_class::structure>, std::vector< ::seqsvr::RouterNode>>::serializedSize<false>(*prot_, this->node_list); xfer += prot_->serializedSizeStop(); return xfer; } template <class Protocol_> uint32_t Router::serializedSizeZC(Protocol_ const* prot_) const { uint32_t xfer = 0; xfer += prot_->serializedStructSize("Router"); xfer += prot_->serializedFieldSize("version", apache::thrift::protocol::T_I32, 1); xfer += prot_->serializedSizeI32(this->version); xfer += prot_->serializedFieldSize("node_list", apache::thrift::protocol::T_LIST, 2); xfer += ::apache::thrift::detail::pm::protocol_methods< ::apache::thrift::type_class::list<::apache::thrift::type_class::structure>, std::vector< ::seqsvr::RouterNode>>::serializedSize<false>(*prot_, this->node_list); xfer += prot_->serializedSizeStop(); return xfer; } template <class Protocol_> uint32_t Router::write(Protocol_* prot_) const { uint32_t xfer = 0; xfer += prot_->writeStructBegin("Router"); xfer += prot_->writeFieldBegin("version", apache::thrift::protocol::T_I32, 1); xfer += prot_->writeI32(this->version); xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldBegin("node_list", apache::thrift::protocol::T_LIST, 2); xfer += ::apache::thrift::detail::pm::protocol_methods< ::apache::thrift::type_class::list<::apache::thrift::type_class::structure>, std::vector< ::seqsvr::RouterNode>>::write(*prot_, this->node_list); xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldStop(); xfer += prot_->writeStructEnd(); return xfer; } } // seqsvr namespace apache { namespace thrift { }} // apache::thrift namespace seqsvr { template <class Protocol_> uint32_t SetNodeInfo::read(Protocol_* iprot) { uint32_t xfer = 0; std::string _fname; apache::thrift::protocol::TType _ftype; int16_t fid; xfer += iprot->readStructBegin(_fname); using apache::thrift::TProtocolException; while (true) { xfer += iprot->readFieldBegin(_fname, _ftype, fid); if (_ftype == apache::thrift::protocol::T_STOP) { break; } if (fid == std::numeric_limits<int16_t>::min()) { this->translateFieldName(_fname, fid, _ftype); } switch (fid) { case 1: { if (_ftype == apache::thrift::protocol::T_STRUCT) { xfer += ::apache::thrift::Cpp2Ops< ::seqsvr::RangeID>::read(iprot, &this->set_id); this->__isset.set_id = true; } else { xfer += iprot->skip(_ftype); } break; } case 2: { if (_ftype == apache::thrift::protocol::T_STRUCT) { xfer += ::apache::thrift::Cpp2Ops< ::seqsvr::NodeAddrInfo>::read(iprot, &this->node_addr); this->__isset.node_addr = true; } else { xfer += iprot->skip(_ftype); } break; } default: { xfer += iprot->skip(_ftype); break; } } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); return xfer; } template <class Protocol_> uint32_t SetNodeInfo::serializedSize(Protocol_ const* prot_) const { uint32_t xfer = 0; xfer += prot_->serializedStructSize("SetNodeInfo"); xfer += prot_->serializedFieldSize("set_id", apache::thrift::protocol::T_STRUCT, 1); xfer += ::apache::thrift::Cpp2Ops< ::seqsvr::RangeID>::serializedSize(prot_, &this->set_id); xfer += prot_->serializedFieldSize("node_addr", apache::thrift::protocol::T_STRUCT, 2); xfer += ::apache::thrift::Cpp2Ops< ::seqsvr::NodeAddrInfo>::serializedSize(prot_, &this->node_addr); xfer += prot_->serializedSizeStop(); return xfer; } template <class Protocol_> uint32_t SetNodeInfo::serializedSizeZC(Protocol_ const* prot_) const { uint32_t xfer = 0; xfer += prot_->serializedStructSize("SetNodeInfo"); xfer += prot_->serializedFieldSize("set_id", apache::thrift::protocol::T_STRUCT, 1); xfer += ::apache::thrift::Cpp2Ops< ::seqsvr::RangeID>::serializedSizeZC(prot_, &this->set_id); xfer += prot_->serializedFieldSize("node_addr", apache::thrift::protocol::T_STRUCT, 2); xfer += ::apache::thrift::Cpp2Ops< ::seqsvr::NodeAddrInfo>::serializedSizeZC(prot_, &this->node_addr); xfer += prot_->serializedSizeStop(); return xfer; } template <class Protocol_> uint32_t SetNodeInfo::write(Protocol_* prot_) const { uint32_t xfer = 0; xfer += prot_->writeStructBegin("SetNodeInfo"); xfer += prot_->writeFieldBegin("set_id", apache::thrift::protocol::T_STRUCT, 1); xfer += ::apache::thrift::Cpp2Ops< ::seqsvr::RangeID>::write(prot_, &this->set_id); xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldBegin("node_addr", apache::thrift::protocol::T_STRUCT, 2); xfer += ::apache::thrift::Cpp2Ops< ::seqsvr::NodeAddrInfo>::write(prot_, &this->node_addr); xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldStop(); xfer += prot_->writeStructEnd(); return xfer; } } // seqsvr namespace apache { namespace thrift { }} // apache::thrift namespace seqsvr { template <class Protocol_> uint32_t SetNodeInfoList::read(Protocol_* iprot) { uint32_t xfer = 0; std::string _fname; apache::thrift::protocol::TType _ftype; int16_t fid; xfer += iprot->readStructBegin(_fname); using apache::thrift::TProtocolException; while (true) { xfer += iprot->readFieldBegin(_fname, _ftype, fid); if (_ftype == apache::thrift::protocol::T_STOP) { break; } if (fid == std::numeric_limits<int16_t>::min()) { this->translateFieldName(_fname, fid, _ftype); } switch (fid) { case 1: { if (_ftype == apache::thrift::protocol::T_STRUCT) { xfer += ::apache::thrift::Cpp2Ops< ::seqsvr::RangeID>::read(iprot, &this->set_id); this->__isset.set_id = true; } else { xfer += iprot->skip(_ftype); } break; } case 2: { if (_ftype == apache::thrift::protocol::T_LIST) { this->node_addrs = std::vector< ::seqsvr::NodeAddrInfo>(); xfer += ::apache::thrift::detail::pm::protocol_methods< ::apache::thrift::type_class::list<::apache::thrift::type_class::structure>, std::vector< ::seqsvr::NodeAddrInfo>>::read(*iprot, this->node_addrs); this->__isset.node_addrs = true; } else { xfer += iprot->skip(_ftype); } break; } default: { xfer += iprot->skip(_ftype); break; } } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); return xfer; } template <class Protocol_> uint32_t SetNodeInfoList::serializedSize(Protocol_ const* prot_) const { uint32_t xfer = 0; xfer += prot_->serializedStructSize("SetNodeInfoList"); xfer += prot_->serializedFieldSize("set_id", apache::thrift::protocol::T_STRUCT, 1); xfer += ::apache::thrift::Cpp2Ops< ::seqsvr::RangeID>::serializedSize(prot_, &this->set_id); xfer += prot_->serializedFieldSize("node_addrs", apache::thrift::protocol::T_LIST, 2); xfer += ::apache::thrift::detail::pm::protocol_methods< ::apache::thrift::type_class::list<::apache::thrift::type_class::structure>, std::vector< ::seqsvr::NodeAddrInfo>>::serializedSize<false>(*prot_, this->node_addrs); xfer += prot_->serializedSizeStop(); return xfer; } template <class Protocol_> uint32_t SetNodeInfoList::serializedSizeZC(Protocol_ const* prot_) const { uint32_t xfer = 0; xfer += prot_->serializedStructSize("SetNodeInfoList"); xfer += prot_->serializedFieldSize("set_id", apache::thrift::protocol::T_STRUCT, 1); xfer += ::apache::thrift::Cpp2Ops< ::seqsvr::RangeID>::serializedSizeZC(prot_, &this->set_id); xfer += prot_->serializedFieldSize("node_addrs", apache::thrift::protocol::T_LIST, 2); xfer += ::apache::thrift::detail::pm::protocol_methods< ::apache::thrift::type_class::list<::apache::thrift::type_class::structure>, std::vector< ::seqsvr::NodeAddrInfo>>::serializedSize<false>(*prot_, this->node_addrs); xfer += prot_->serializedSizeStop(); return xfer; } template <class Protocol_> uint32_t SetNodeInfoList::write(Protocol_* prot_) const { uint32_t xfer = 0; xfer += prot_->writeStructBegin("SetNodeInfoList"); xfer += prot_->writeFieldBegin("set_id", apache::thrift::protocol::T_STRUCT, 1); xfer += ::apache::thrift::Cpp2Ops< ::seqsvr::RangeID>::write(prot_, &this->set_id); xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldBegin("node_addrs", apache::thrift::protocol::T_LIST, 2); xfer += ::apache::thrift::detail::pm::protocol_methods< ::apache::thrift::type_class::list<::apache::thrift::type_class::structure>, std::vector< ::seqsvr::NodeAddrInfo>>::write(*prot_, this->node_addrs); xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldStop(); xfer += prot_->writeStructEnd(); return xfer; } } // seqsvr namespace apache { namespace thrift { }} // apache::thrift namespace seqsvr { template <class Protocol_> uint32_t PerSetRouterTable::read(Protocol_* iprot) { uint32_t xfer = 0; std::string _fname; apache::thrift::protocol::TType _ftype; int16_t fid; xfer += iprot->readStructBegin(_fname); using apache::thrift::TProtocolException; while (true) { xfer += iprot->readFieldBegin(_fname, _ftype, fid); if (_ftype == apache::thrift::protocol::T_STOP) { break; } if (fid == std::numeric_limits<int16_t>::min()) { this->translateFieldName(_fname, fid, _ftype); } switch (fid) { case 1: { if (_ftype == apache::thrift::protocol::T_STRUCT) { xfer += ::apache::thrift::Cpp2Ops< ::seqsvr::RangeID>::read(iprot, &this->set_id); this->__isset.set_id = true; } else { xfer += iprot->skip(_ftype); } break; } case 2: { if (_ftype == apache::thrift::protocol::T_LIST) { this->node_list = std::vector< ::seqsvr::RouterNode>(); xfer += ::apache::thrift::detail::pm::protocol_methods< ::apache::thrift::type_class::list<::apache::thrift::type_class::structure>, std::vector< ::seqsvr::RouterNode>>::read(*iprot, this->node_list); this->__isset.node_list = true; } else { xfer += iprot->skip(_ftype); } break; } default: { xfer += iprot->skip(_ftype); break; } } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); return xfer; } template <class Protocol_> uint32_t PerSetRouterTable::serializedSize(Protocol_ const* prot_) const { uint32_t xfer = 0; xfer += prot_->serializedStructSize("PerSetRouterTable"); xfer += prot_->serializedFieldSize("set_id", apache::thrift::protocol::T_STRUCT, 1); xfer += ::apache::thrift::Cpp2Ops< ::seqsvr::RangeID>::serializedSize(prot_, &this->set_id); xfer += prot_->serializedFieldSize("node_list", apache::thrift::protocol::T_LIST, 2); xfer += ::apache::thrift::detail::pm::protocol_methods< ::apache::thrift::type_class::list<::apache::thrift::type_class::structure>, std::vector< ::seqsvr::RouterNode>>::serializedSize<false>(*prot_, this->node_list); xfer += prot_->serializedSizeStop(); return xfer; } template <class Protocol_> uint32_t PerSetRouterTable::serializedSizeZC(Protocol_ const* prot_) const { uint32_t xfer = 0; xfer += prot_->serializedStructSize("PerSetRouterTable"); xfer += prot_->serializedFieldSize("set_id", apache::thrift::protocol::T_STRUCT, 1); xfer += ::apache::thrift::Cpp2Ops< ::seqsvr::RangeID>::serializedSizeZC(prot_, &this->set_id); xfer += prot_->serializedFieldSize("node_list", apache::thrift::protocol::T_LIST, 2); xfer += ::apache::thrift::detail::pm::protocol_methods< ::apache::thrift::type_class::list<::apache::thrift::type_class::structure>, std::vector< ::seqsvr::RouterNode>>::serializedSize<false>(*prot_, this->node_list); xfer += prot_->serializedSizeStop(); return xfer; } template <class Protocol_> uint32_t PerSetRouterTable::write(Protocol_* prot_) const { uint32_t xfer = 0; xfer += prot_->writeStructBegin("PerSetRouterTable"); xfer += prot_->writeFieldBegin("set_id", apache::thrift::protocol::T_STRUCT, 1); xfer += ::apache::thrift::Cpp2Ops< ::seqsvr::RangeID>::write(prot_, &this->set_id); xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldBegin("node_list", apache::thrift::protocol::T_LIST, 2); xfer += ::apache::thrift::detail::pm::protocol_methods< ::apache::thrift::type_class::list<::apache::thrift::type_class::structure>, std::vector< ::seqsvr::RouterNode>>::write(*prot_, this->node_list); xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldStop(); xfer += prot_->writeStructEnd(); return xfer; } } // seqsvr namespace apache { namespace thrift { }} // apache::thrift namespace seqsvr { template <class Protocol_> uint32_t Sequence::read(Protocol_* iprot) { uint32_t xfer = 0; std::string _fname; apache::thrift::protocol::TType _ftype; int16_t fid; xfer += iprot->readStructBegin(_fname); using apache::thrift::TProtocolException; while (true) { xfer += iprot->readFieldBegin(_fname, _ftype, fid); if (_ftype == apache::thrift::protocol::T_STOP) { break; } if (fid == std::numeric_limits<int16_t>::min()) { this->translateFieldName(_fname, fid, _ftype); } switch (fid) { case 1: { if (_ftype == apache::thrift::protocol::T_I64) { xfer += iprot->readI64(this->sequence); this->__isset.sequence = true; } else { xfer += iprot->skip(_ftype); } break; } case 2: { if (_ftype == apache::thrift::protocol::T_STRUCT) { xfer += ::apache::thrift::Cpp2Ops< ::seqsvr::Router>::read(iprot, &this->router); this->__isset.router = true; } else { xfer += iprot->skip(_ftype); } break; } default: { xfer += iprot->skip(_ftype); break; } } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); return xfer; } template <class Protocol_> uint32_t Sequence::serializedSize(Protocol_ const* prot_) const { uint32_t xfer = 0; xfer += prot_->serializedStructSize("Sequence"); xfer += prot_->serializedFieldSize("sequence", apache::thrift::protocol::T_I64, 1); xfer += prot_->serializedSizeI64(this->sequence); if (this->__isset.router) { xfer += prot_->serializedFieldSize("router", apache::thrift::protocol::T_STRUCT, 2); xfer += ::apache::thrift::Cpp2Ops< ::seqsvr::Router>::serializedSize(prot_, &this->router); } xfer += prot_->serializedSizeStop(); return xfer; } template <class Protocol_> uint32_t Sequence::serializedSizeZC(Protocol_ const* prot_) const { uint32_t xfer = 0; xfer += prot_->serializedStructSize("Sequence"); xfer += prot_->serializedFieldSize("sequence", apache::thrift::protocol::T_I64, 1); xfer += prot_->serializedSizeI64(this->sequence); if (this->__isset.router) { xfer += prot_->serializedFieldSize("router", apache::thrift::protocol::T_STRUCT, 2); xfer += ::apache::thrift::Cpp2Ops< ::seqsvr::Router>::serializedSizeZC(prot_, &this->router); } xfer += prot_->serializedSizeStop(); return xfer; } template <class Protocol_> uint32_t Sequence::write(Protocol_* prot_) const { uint32_t xfer = 0; xfer += prot_->writeStructBegin("Sequence"); xfer += prot_->writeFieldBegin("sequence", apache::thrift::protocol::T_I64, 1); xfer += prot_->writeI64(this->sequence); xfer += prot_->writeFieldEnd(); if (this->__isset.router) { xfer += prot_->writeFieldBegin("router", apache::thrift::protocol::T_STRUCT, 2); xfer += ::apache::thrift::Cpp2Ops< ::seqsvr::Router>::write(prot_, &this->router); xfer += prot_->writeFieldEnd(); } xfer += prot_->writeFieldStop(); xfer += prot_->writeStructEnd(); return xfer; } } // seqsvr namespace apache { namespace thrift { }} // apache::thrift namespace seqsvr { template <class Protocol_> uint32_t MaxSeqsData::read(Protocol_* iprot) { uint32_t xfer = 0; std::string _fname; apache::thrift::protocol::TType _ftype; int16_t fid; xfer += iprot->readStructBegin(_fname); using apache::thrift::TProtocolException; while (true) { xfer += iprot->readFieldBegin(_fname, _ftype, fid); if (_ftype == apache::thrift::protocol::T_STOP) { break; } if (fid == std::numeric_limits<int16_t>::min()) { this->translateFieldName(_fname, fid, _ftype); } switch (fid) { case 1: { if (_ftype == apache::thrift::protocol::T_STRUCT) { xfer += ::apache::thrift::Cpp2Ops< ::seqsvr::RangeID>::read(iprot, &this->set_id); this->__isset.set_id = true; } else { xfer += iprot->skip(_ftype); } break; } case 2: { if (_ftype == apache::thrift::protocol::T_LIST) { this->max_seqs = std::vector<int64_t>(); xfer += ::apache::thrift::detail::pm::protocol_methods< ::apache::thrift::type_class::list<::apache::thrift::type_class::integral>, std::vector<int64_t>>::read(*iprot, this->max_seqs); this->__isset.max_seqs = true; } else { xfer += iprot->skip(_ftype); } break; } default: { xfer += iprot->skip(_ftype); break; } } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); return xfer; } template <class Protocol_> uint32_t MaxSeqsData::serializedSize(Protocol_ const* prot_) const { uint32_t xfer = 0; xfer += prot_->serializedStructSize("MaxSeqsData"); xfer += prot_->serializedFieldSize("set_id", apache::thrift::protocol::T_STRUCT, 1); xfer += ::apache::thrift::Cpp2Ops< ::seqsvr::RangeID>::serializedSize(prot_, &this->set_id); xfer += prot_->serializedFieldSize("max_seqs", apache::thrift::protocol::T_LIST, 2); xfer += ::apache::thrift::detail::pm::protocol_methods< ::apache::thrift::type_class::list<::apache::thrift::type_class::integral>, std::vector<int64_t>>::serializedSize<false>(*prot_, this->max_seqs); xfer += prot_->serializedSizeStop(); return xfer; } template <class Protocol_> uint32_t MaxSeqsData::serializedSizeZC(Protocol_ const* prot_) const { uint32_t xfer = 0; xfer += prot_->serializedStructSize("MaxSeqsData"); xfer += prot_->serializedFieldSize("set_id", apache::thrift::protocol::T_STRUCT, 1); xfer += ::apache::thrift::Cpp2Ops< ::seqsvr::RangeID>::serializedSizeZC(prot_, &this->set_id); xfer += prot_->serializedFieldSize("max_seqs", apache::thrift::protocol::T_LIST, 2); xfer += ::apache::thrift::detail::pm::protocol_methods< ::apache::thrift::type_class::list<::apache::thrift::type_class::integral>, std::vector<int64_t>>::serializedSize<false>(*prot_, this->max_seqs); xfer += prot_->serializedSizeStop(); return xfer; } template <class Protocol_> uint32_t MaxSeqsData::write(Protocol_* prot_) const { uint32_t xfer = 0; xfer += prot_->writeStructBegin("MaxSeqsData"); xfer += prot_->writeFieldBegin("set_id", apache::thrift::protocol::T_STRUCT, 1); xfer += ::apache::thrift::Cpp2Ops< ::seqsvr::RangeID>::write(prot_, &this->set_id); xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldBegin("max_seqs", apache::thrift::protocol::T_LIST, 2); xfer += ::apache::thrift::detail::pm::protocol_methods< ::apache::thrift::type_class::list<::apache::thrift::type_class::integral>, std::vector<int64_t>>::write(*prot_, this->max_seqs); xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldStop(); xfer += prot_->writeStructEnd(); return xfer; } } // seqsvr namespace apache { namespace thrift { }} // apache::thrift namespace seqsvr { } // seqsvr
34.319654
222
0.652517
[ "vector" ]
5b9dbee59158f6554e952f3bfd7d96a41c3c01c9
793
cc
C++
cpp/14.cc
arkbriar/hackerrank-projecteuler
e71a88f5546c69a0d681bb6f96524fc0c12d3d01
[ "MIT" ]
null
null
null
cpp/14.cc
arkbriar/hackerrank-projecteuler
e71a88f5546c69a0d681bb6f96524fc0c12d3d01
[ "MIT" ]
null
null
null
cpp/14.cc
arkbriar/hackerrank-projecteuler
e71a88f5546c69a0d681bb6f96524fc0c12d3d01
[ "MIT" ]
null
null
null
#include <cmath> #include <cstdio> #include <climits> #include <vector> #include <iostream> #include <algorithm> #include <unordered_map> #include <stack> using namespace std; const int N = 5e6; int lt[N + 1]; int res[N + 1]; int len(long n) { if (lt[n] > 0) return lt[n]; int res = 0; long x = n; while (x == n || x > N) { if (x & 1) x = 3 * x + 1; else x >>= 1; ++ res; } lt[n] = res + len(x); return lt[n]; } int main() { int t; cin >> t; lt[1] = 1; res[1] = 1; for (int i = 2; i <= N; ++ i) { if (len(i) >= len(res[i - 1])) { res[i] = i; } else res[i] = res[i - 1]; } while (t--) { int n; cin >> n; cout << res[n] << endl; } return 0; }
14.685185
40
0.432535
[ "vector" ]
5b9e979c01e841f983b46fb4762346c2a630d6c8
8,159
cpp
C++
src/kDataFrames/kDataFramePHMAP.cpp
dib-lab/kProcessor
8a3a48e51f3d3f73572aef21828a26f7a7d2e6ee
[ "BSD-3-Clause" ]
8
2018-10-12T11:02:55.000Z
2021-08-29T14:46:02.000Z
src/kDataFrames/kDataFramePHMAP.cpp
dib-lab/kProcessor
8a3a48e51f3d3f73572aef21828a26f7a7d2e6ee
[ "BSD-3-Clause" ]
79
2019-03-16T15:31:43.000Z
2022-03-21T18:56:55.000Z
src/kDataFrames/kDataFramePHMAP.cpp
dib-lab/kProcessor
8a3a48e51f3d3f73572aef21828a26f7a7d2e6ee
[ "BSD-3-Clause" ]
2
2019-06-21T11:48:11.000Z
2021-04-09T00:47:54.000Z
#include "kDataFrame.hpp" #include "parallel_hashmap/phmap_dump.h" #include <iostream> #include <fstream> #include "Utils/kmer.h" /* ***************************** *** kDataFramePHMAPIterator *** ***************************** */ kDataFramePHMAPIterator::kDataFramePHMAPIterator(flat_hash_map<uint64_t, uint64_t>::iterator it, kDataFramePHMAP *origin, uint64_t kSize) : _kDataFrameIterator(kSize) { iterator = it; this->origin = origin; this->KD = this->origin->KD; } kDataFramePHMAPIterator::kDataFramePHMAPIterator(const kDataFramePHMAPIterator &other) : _kDataFrameIterator(other.kSize) { iterator = other.iterator; this->origin = other.origin; this->KD = other.KD; } _kDataFrameIterator *kDataFramePHMAPIterator::clone() { return new kDataFramePHMAPIterator(*this); } kDataFramePHMAPIterator &kDataFramePHMAPIterator::operator++(int) { iterator++; return *this; } uint64_t kDataFramePHMAPIterator::getHashedKmer() { //return origin->getHasher()->hash(iterator->first); return iterator->first; } string kDataFramePHMAPIterator::getKmer() { return KD->ihash_kmer(iterator->first); // return iterator->first; } uint64_t kDataFramePHMAPIterator::getCount() { return iterator->second; } bool kDataFramePHMAPIterator::setCount(uint64_t count) { iterator->second = count; } bool kDataFramePHMAPIterator::operator==(const _kDataFrameIterator &other) { return iterator == ((kDataFramePHMAPIterator *) &other)->iterator; } bool kDataFramePHMAPIterator::operator!=(const _kDataFrameIterator &other) { return iterator != ((kDataFramePHMAPIterator *) &other)->iterator; } kDataFramePHMAPIterator::~kDataFramePHMAPIterator() { } /* ********************** *** kDataFramePHMAP *** ********************** */ kDataFramePHMAP::kDataFramePHMAP(uint64_t ksize) { this->class_name = "PHMAP"; // Temporary until resolving #17 this->kSize = ksize; KD = new Kmers(kSize, TwoBits_hasher); // hasher = new wrapperHasher<flat_hash_map<uint64_t, uint64_t>::hasher>(MAP.hash_function(), ksize); this->MAP = flat_hash_map<uint64_t, uint64_t>(1000); // this->hasher = (new IntegerHasher(ksize)); } kDataFramePHMAP::kDataFramePHMAP(uint64_t ksize, hashingModes hash_mode) { this->class_name = "PHMAP"; // Temporary until resolving #17 this->kSize = ksize; KD = new Kmers(kSize, hash_mode); // hasher = new wrapperHasher<flat_hash_map<uint64_t, uint64_t>::hasher>(MAP.hash_function(), ksize); this->MAP = flat_hash_map<uint64_t, uint64_t>(1000); // this->hasher = (new IntegerHasher(ksize)); } kDataFramePHMAP::kDataFramePHMAP(readingModes RM, hashingModes hash_mode, map<string, int> params) { this->class_name = "PHMAP"; // Temporary until resolving #17 KD = kmerDecoder::getInstance(RM, hash_mode, params); this->kSize = KD->get_kSize(); this->MAP = flat_hash_map<uint64_t, uint64_t>(1000); } kDataFramePHMAP::kDataFramePHMAP(uint64_t ksize,vector<uint64_t> kmersHistogram) { this->class_name = "PHMAP"; // Temporary until resolving #17 this->kSize = ksize; KD = new Kmers(kSize, TwoBits_hasher); // hasher = new wrapperHasher<flat_hash_map<uint64_t, uint64_t>::hasher>(MAP.hash_function(), ksize); uint64_t countSum=0; for(auto h:kmersHistogram) countSum+=h; reserve(countSum); // hasher = new wrapperHasher<std::map<uint64_t, uint64_t>::hasher>(MAP.hash_function(), ksize); // this->MAP = std::map<uint64_t, uint64_t>(1000); // this->hasher = (new IntegerHasher(ksize)); } kDataFramePHMAP::kDataFramePHMAP() { this->class_name = "PHMAP"; // Temporary until resolving #17 this->kSize = 23; this->MAP = flat_hash_map<uint64_t, uint64_t>(1000); KD = new Kmers(kSize, TwoBits_hasher); // hasher=new wrapperHasher<flat_hash_map<uint64_t,uint64_t>::hasher >(MAP.hash_function(),kSize); // this->hasher = (new IntegerHasher(23)); } inline bool kDataFramePHMAP::kmerExist(string kmerS) { return (this->MAP.find(KD->hash_kmer(kmerS)) == this->MAP.end()) ? 0 : 1; } bool kDataFramePHMAP::insert(string kmerS, uint64_t count) { this->MAP[KD->hash_kmer(kmerS)] += count; return true; } bool kDataFramePHMAP::insert(string kmerS) { this->MAP[KD->hash_kmer(kmerS)] += 1; return true; } bool kDataFramePHMAP::insert(uint64_t kmer, uint64_t count) { this->MAP[kmer] += count; return true; } bool kDataFramePHMAP::insert(uint64_t kmer) { this->MAP[kmer] += 1; return true; } bool kDataFramePHMAP::setCount(string kmerS, uint64_t tag) { this->MAP[KD->hash_kmer(kmerS)] = tag; return true; } bool kDataFramePHMAP::setCount(uint64_t kmerS, uint64_t tag) { this->MAP[kmerS] = tag; return true; } uint64_t kDataFramePHMAP::getCount(string kmerS) { phmap::flat_hash_map<uint64_t,uint64_t>::const_iterator got = this->MAP.find(KD->hash_kmer(kmerS)); if ( got == this->MAP.end() ) return 0; else return got->second; } uint64_t kDataFramePHMAP::getCount(uint64_t kmerS) { phmap::flat_hash_map<uint64_t,uint64_t>::const_iterator got = this->MAP.find(kmerS); if ( got == this->MAP.end() ) return 0; else return got->second; } uint64_t kDataFramePHMAP::bucket(string kmerS) { return 1; // return this->MAP.bucket(kmer::str_to_canonical_int(kmerS)); } bool kDataFramePHMAP::erase(string kmerS) { return this->MAP.erase(KD->hash_kmer(kmerS)); } bool kDataFramePHMAP::erase(uint64_t kmer) { return this->MAP.erase(kmer); } uint64_t kDataFramePHMAP::size() { return (uint64_t) this->MAP.size(); } uint64_t kDataFramePHMAP::max_size() { return (uint64_t) this->MAP.max_size(); } float kDataFramePHMAP::load_factor() { return this->MAP.load_factor(); } float kDataFramePHMAP::max_load_factor() { return this->MAP.max_load_factor(); } void kDataFramePHMAP::save(string filePath) { // Write the kmerSize ofstream file(filePath + ".extra"); file << kSize << endl; file << this->KD->hash_mode << endl; file << this->KD->slicing_mode << endl; file << this->KD->params_to_string() << endl; filePath += ".phmap"; { phmap::BinaryOutputArchive ar_out(filePath.c_str()); this->MAP.dump(ar_out); } } kDataFrame *kDataFramePHMAP::load(string filePath) { // Load kSize ifstream file(filePath + ".extra"); uint64_t filekSize; int hashing_mode, reading_mode; string KD_params_string; file >> filekSize; file >> hashing_mode; file >> reading_mode; file >> KD_params_string; hashingModes hash_mode = static_cast<hashingModes>(hashing_mode); readingModes slicing_mode = static_cast<readingModes>(reading_mode); map<string, int> kmerDecoder_params = kmerDecoder::string_to_params(KD_params_string); filePath += ".phmap"; kDataFramePHMAP *KMAP = new kDataFramePHMAP(slicing_mode, hash_mode, kmerDecoder_params); { phmap::BinaryInputArchive ar_in(filePath.c_str()); KMAP->MAP.load(ar_in); } return KMAP; } kDataFrame *kDataFramePHMAP::getTwin() { return ((kDataFrame *) new kDataFramePHMAP(kSize, this->KD->hash_mode)); } void kDataFramePHMAP::reserve(uint64_t n) { this->MAP.reserve(n); } void kDataFramePHMAP::reserve(vector<uint64_t> countHistogram) { uint64_t countSum=0; for(auto h:countHistogram) countSum+=h; reserve(countSum); } kDataFrameIterator kDataFramePHMAP::begin() { return *(new kDataFrameIterator( (_kDataFrameIterator *) new kDataFramePHMAPIterator(MAP.begin(), this, kSize), (kDataFrame *) this)); } kDataFrameIterator kDataFramePHMAP::end() { return *(new kDataFrameIterator( (_kDataFrameIterator *) new kDataFramePHMAPIterator(MAP.end(), this, kSize), (kDataFrame *) this)); } kDataFrameIterator kDataFramePHMAP::find(string kmer) { return *(new kDataFrameIterator( (_kDataFrameIterator *) new kDataFramePHMAPIterator(MAP.find(kmer::str_to_canonical_int(kmer)), this, kSize), (kDataFrame *) this)); }
28.527972
121
0.679005
[ "vector" ]
5ba05cdc479e0d81825433100ab66e570865904c
528
cc
C++
src/single_number/single_number.cc
cuprumz/LeetCode
5c57b0ab45e691e8d7750f531b29a25a19472d23
[ "MIT" ]
null
null
null
src/single_number/single_number.cc
cuprumz/LeetCode
5c57b0ab45e691e8d7750f531b29a25a19472d23
[ "MIT" ]
null
null
null
src/single_number/single_number.cc
cuprumz/LeetCode
5c57b0ab45e691e8d7750f531b29a25a19472d23
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; class Solution { public: int singleNumber(vector<int> &nums); }; int Solution::singleNumber(vector<int> &nums) { int res = 0; for (auto it = nums.begin(); it != nums.end(); it++) { res ^= *it; } return res; } int main(int argc, char **argv) { Solution s; vector<int> ex1 = {2, 2, 1}; cout << s.singleNumber(ex1) << endl; vector<int> ex2 = {4, 1, 2, 1, 2}; cout << s.singleNumber(ex2) << endl; return 0; }
15.085714
58
0.560606
[ "vector" ]
5ba57f4f329978d4bf5f0e51a38b6a51e2d41a87
574
hpp
C++
Iterator/Iterator.hpp
Yescafe/pattern_demo
b87d8d588683773cd37efff0e9e12fc70b13f187
[ "MIT" ]
1
2020-07-11T04:36:14.000Z
2020-07-11T04:36:14.000Z
Iterator/Iterator.hpp
Yescafe/pattern_demo
b87d8d588683773cd37efff0e9e12fc70b13f187
[ "MIT" ]
null
null
null
Iterator/Iterator.hpp
Yescafe/pattern_demo
b87d8d588683773cd37efff0e9e12fc70b13f187
[ "MIT" ]
null
null
null
#ifndef _ITERATOR_HPP_ #define _ITERATOR_HPP_ class Aggregate; using Object = int; class Iterator { public: virtual ~Iterator(); virtual void First() = 0; virtual void Next() = 0; virtual bool IsDone() = 0; virtual Object CurrentItem() = 0; protected: Iterator(); }; class ConcreteIterator : public Iterator { public: ConcreteIterator(Aggregate* ag, int idx = 0); ~ConcreteIterator(); void First(); void Next(); bool IsDone(); Object CurrentItem(); private: Aggregate* ag; int idx; }; #endif /* _ITERATOR_HPP_ */
17.9375
49
0.649826
[ "object" ]
5bb53d4e1d9cd4f8f9363638c566cdfd56c84cf9
17,463
cpp
C++
extlibs/cpp-utils/src/utils/sys.cpp
Krozark/SFML-book
397dd3dc0c73b694d4b5c117e974c7ebdb885572
[ "BSD-2-Clause" ]
75
2015-01-18T21:29:03.000Z
2022-02-09T14:11:05.000Z
extlibs/cpp-utils/src/utils/sys.cpp
Krozark/SFML-book
397dd3dc0c73b694d4b5c117e974c7ebdb885572
[ "BSD-2-Clause" ]
7
2015-03-12T10:41:55.000Z
2020-11-23T11:15:58.000Z
extlibs/cpp-utils/src/utils/sys.cpp
Krozark/SFML-book
397dd3dc0c73b694d4b5c117e974c7ebdb885572
[ "BSD-2-Clause" ]
33
2015-12-01T07:34:46.000Z
2022-03-23T03:37:42.000Z
#include <utils/sys.hpp> #include <utils/string.hpp> #include <stdexcept> #ifdef _WIN32 #include <windows.h> char *realpath(const char *path, char resolved_path[PATH_MAX]); #elif __unix || __unix__ #include <unistd.h> #include <ftw.h> #endif #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <errno.h> #include <cstring> #include <cstdlib> #include <cstdio> namespace utils { namespace sys { #ifdef _WIN32 char *realpath(const char *path, char resolved_path[PATH_MAX]); #endif std::string whereis(const std::string& name) { //compute path dirs vector std::vector<std::string> paths = utils::string::split(std::string(::getenv("PATH")), #ifdef _WIN32 //_WIN64 ";" #else ":" #endif ); for(std::string& bpath : paths) { std::string fpath = bpath; if(bpath.size() > 1) { #ifdef _WIN32 //_WIN64 if(bpath[bpath.size()-1] != '\\') fpath += '\\'; #else if(bpath[bpath.size()-1] != '/') fpath += '/'; #endif } fpath += name; if(utils::sys::file::exists(fpath)) return fpath; } return {}; } //Library Library::Library(const std::string& name) : _name(name),lib(nullptr) { #ifdef _WIN32 if(not utils::string::endswith(_name,".dll")) _name+=".dll"; #else if(not utils::string::endswith(_name,".so")) _name+=".so"; #endif } Library::~Library() { if(lib) close(); } bool Library::load() { #ifdef _WIN32 //_WIN64 lib = ::LoadLibrary(_name.c_str()); if (lib == nullptr) { utils::log::error("utils:sys::Library::load","Unable to load ",_name); return false; } #elif __linux //|| __unix //or __APPLE__ lib = ::dlopen(_name.c_str(), RTLD_LAZY); char* err = ::dlerror(); if (lib == nullptr or err) { utils::log::error("utils:sys::Library::load","Unable to load ",_name,err); return false; } #endif return true; } void Library::close() { //clear all linked functions for(auto& c : funcs) delete c.second; funcs.clear(); //delete the lib #ifdef _WIN32 //_WIN64 ::FreeLibrary(lib); #elif __linux ::dlclose(lib); ::dlerror(); #endif lib = nullptr; } void* Library::get_f(const std::string& name)const { void* f = nullptr; #ifdef _WIN32 //_WIN64 f = (void*)::GetProcAddress(lib,name.c_str()); if(f == nullptr) { utils::log::error("utils:sys::Library::get_f","Unable to load function",name); } #elif __linux //|| __unix //or __APPLE__ f = ::dlsym(lib,name.c_str()); char* err = ::dlerror(); if(f == nullptr or err) { f = nullptr; utils::log::error("utils:sys::Library::get_f","Unable to load function",name,err); } #endif return f; } utils::func::VFunc* Library::operator[](const std::string& name) { auto value = funcs.find(name); if(value != funcs.end()) return value->second; return nullptr; } const std::string Library::name()const { return _name; } //Compiler Compiler::Compiler() : _output("./out") { #ifdef _WIN32 //_WIN64 auto comp_list = {"mingw32-g++.exe","clang.exe"}; #else auto comp_list = {"g++","clang"}; #endif for(const std::string& c : comp_list) { std::string path = sys::whereis(c); if(not path.empty()) { _name = c; break; } } if(_name.empty()) throw std::runtime_error("no compilater " #ifdef _WIN32 //_WIN64 "mingw-g++.exe or clang.exe" #else "g++ or clang" #endif " find"); } Compiler::Compiler(const std::string& name) : _output("./out") { std::string path = sys::whereis(name); if(path.empty()) throw std::runtime_error(name); _name = path; } Compiler& Compiler::output(const std::string& out) { if(not out.empty()) { #ifdef _WIN32 //_WIN64 if(string::startswith(out,".\\")) _output = out; else _output = ".\\"+out; #else if(string::startswith(out,"./")) _output = out; else _output = "./"+out; #endif } return *this; } Library Compiler::get() const { //TODO build in thread::Pool[0.-1] for(const std::string& u : make_cmds()) { utils::log::info("utils:sys::Compiler::get","system("+u+")"); int res = ::system(u.c_str()); if(res == -1) { utils::log::error("utils:sys::Compiler::get","failed to make sytem call"); throw std::runtime_error("fork failed"); } else if(res != 0) { utils::log::error("utils:sys::Compiler::get","the command return the error code:",res); throw std::runtime_error("fork failed"); } } for(const std::string& f: _inputs) sys::file::rm(f+".o"); return {_output}; /*+ #ifdef _WIN32 ".dll" #else ".so" #endif ;*/ } std::ostream& operator<<(std::ostream& output,const Compiler& self) { for(const std::string& u : self.make_cmds()) output<<u<<std::endl; return output; } std::vector<std::string> Compiler::make_cmds() const { std::vector<std::string> res; //compile as .o unsigned int _size = _inputs.size(); for(unsigned int i=0;i<_size;++i) { std::string tmp = _name + " -fpic "; unsigned int _s = _flags.size(); for(unsigned int i=0;i<_s;++i) tmp+=" "+_flags[i]; tmp +=" -x c++ -c \"" +_inputs[i]+"\" -o \""+_inputs[i]+".o\""; res.push_back(std::move(tmp)); } //compile .o as .so/.dll { std::string tmp = _name + " -shared -o "+_output+ #ifdef _WIN32 ".dll"; #else ".so"; #endif for(unsigned int i=0;i<_size;++i) tmp+= " \""+_inputs[i]+".o\""; unsigned int _s = _links.size(); if(_s>0) { for(unsigned int i=0;i<_s;++i) tmp += " -l"+_links[i]; } res.push_back(std::move(tmp)); } return res; } namespace dir { int create(const std::string& dirpath,const int permissions) { int res = 1; //0 => error, 1 => created, 2 => already exist auto sp = string::split(dirpath,"/"); std::string current; if(dirpath.size() > 0 and dirpath[0] == '/') current = "/"; const unsigned int _size = sp.size(); for(unsigned int i=0; i<_size and res != 0;++i) { current += sp[i] + "/"; #if __WIN32 res = ::mkdir(current.c_str()); #else res = ::mkdir(current.c_str(), permissions); #endif if(res == 0) res = 1; else if(errno == EEXIST) res = 2; else res = 0; } return res; } std::list<std::string> list_files(const std::string& dirpath) { DIR *curDir; std::list<std::string> res; if ((curDir = opendir(dirpath.c_str())) == NULL) return res; dirent *curEntry =readdir(curDir); while (curEntry != NULL) { #if _WIN32 DWORD dwAttrib = GetFileAttributes(curEntry->d_name); if (dwAttrib != INVALID_FILE_ATTRIBUTES && not (dwAttrib & FILE_ATTRIBUTE_DIRECTORY)) #else if(curEntry->d_type == DT_REG) #endif // _WIN32 res.push_back(curEntry->d_name); curEntry =readdir(curDir); } ::closedir(curDir); return res; } std::list<std::string> list_dirs(const std::string& dirpath) { DIR *curDir; std::list<std::string> res; if ((curDir = opendir(dirpath.c_str())) == NULL) return res; dirent *curEntry =readdir(curDir); while (curEntry != NULL) { #if _WIN32 DWORD dwAttrib = GetFileAttributes(curEntry->d_name); if (dwAttrib != INVALID_FILE_ATTRIBUTES && (dwAttrib & FILE_ATTRIBUTE_DIRECTORY) #else if(curEntry->d_type == DT_DIR #endif and std::string(curEntry->d_name) != ".." and std::string(curEntry->d_name) != ".") res.push_back(curEntry->d_name); curEntry =readdir(curDir); } ::closedir(curDir); return res; } bool rm(const std::string& path,bool recusive) { bool res; if(not recusive) { #if _WIN32 res = RemoveDirectory(path.c_str()); #endif // _WIN32 #if __unix__ res = ::rmdir(path.c_str()) == 0; #endif } else { #if _WIN32 res = RemoveDirectory(path.c_str()); ///< todo rewove directory recursivjy #else auto f = [](const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf) -> int { int rv; switch(typeflag) { case FTW_F: rv = ::unlink(fpath);break; case FTW_D: case FTW_DP: rv = ::rmdir(fpath);break; default: rv = ::remove(fpath);break; } if (rv) ::perror(fpath); return rv; }; res = ::nftw(path.c_str(),f, 64, FTW_DEPTH | FTW_PHYS) == 0; #endif // _WIN32 } return res; } bool rm_if_empty(const std::string& path,bool recusive) { bool res; #if _WIN32 res = RemoveDirectory(path.c_str()); #endif // _WIN32 #if __unix__ res = ::rmdir(path.c_str()) == 0; #endif return res; } std::string pwd() { #if _WIN32 char path[256]; ::GetCurrentDirectory(256,path); std::string res(path); #else char* path = ::get_current_dir_name(); std::string res(path); ::free(path); #endif return res; } std::string abs_path(const std::string& relative_path) { char my_path[relative_path.size() + 1]; ::strcpy(my_path,relative_path.c_str()); char *resolved_path = realpath(my_path,nullptr); std::string res = resolved_path; ::free(resolved_path); return res; } } namespace file { bool rm(const std::string& path) { #if _WIN32 return false; ///< todo #else return ::unlink(path.c_str()) == 0; #endif } bool exists(const std::string& name) { if (FILE *file = fopen(name.c_str(), "rb")) { fclose(file); return true; } return false; } bool touch(const std::string& path) { //build dir tree #ifdef _WIN32 //_WIN64 std::string file_path = path; utils::string::replace(file_path,"\\","/"); #else const std::string& file_path = path; #endif std::vector<std::string> dirs = utils::string::split(file_path,"/"); if(dirs.size()>1) dirs.pop_back(); std::string dir_path = "/"+utils::string::join("/",dirs); if(not dir::create(dir_path)) return false; //create file if (FILE *file = fopen(file_path.c_str(), "ab")) { fclose(file); return true; } return false; } } #if _WIN32 #include <stdlib.h> #include <limits.h> #include <errno.h> #include <sys/stat.h> char *realpath(const char *path, char resolved_path[PATH_MAX]) { char *return_path = 0; if (path) //Else EINVAL { if (resolved_path) { return_path = resolved_path; } else { //Non standard extension that glibc uses return_path = (char*)malloc(PATH_MAX); } if (return_path) //Else EINVAL { //This is a Win32 API function similar to what realpath() is supposed to do size_t size = GetFullPathNameA(path, PATH_MAX, return_path, 0); //GetFullPathNameA() returns a size larger than buffer if buffer is too small if (size > PATH_MAX) { if (return_path != resolved_path) //Malloc'd buffer - Unstandard extension retry { size_t new_size; free(return_path); return_path = (char*)malloc(size); if (return_path) { new_size = GetFullPathNameA(path, size, return_path, 0); //Try again if (new_size > size) //If it's still too large, we have a problem, don't try again { free(return_path); return_path = 0; errno = ENAMETOOLONG; } else { size = new_size; } } else { //I wasn't sure what to return here, but the standard does say to return EINVAL //if resolved_path is null, and in this case we couldn't malloc large enough buffer errno = EINVAL; } } else //resolved_path buffer isn't big enough { return_path = 0; errno = ENAMETOOLONG; } } //GetFullPathNameA() returns 0 if some path resolve problem occured if (!size) { if (return_path != resolved_path) //Malloc'd buffer { free(return_path); } return_path = 0; //Convert MS errors into standard errors switch (GetLastError()) { case ERROR_FILE_NOT_FOUND: errno = ENOENT; break; case ERROR_PATH_NOT_FOUND: case ERROR_INVALID_DRIVE: errno = ENOTDIR; break; case ERROR_ACCESS_DENIED: errno = EACCES; break; default: //Unknown Error errno = EIO; break; } } //If we get to here with a valid return_path, we're still doing good if (return_path) { struct stat stat_buffer; //Make sure path exists, stat() returns 0 on success if (stat(return_path, &stat_buffer)) { if (return_path != resolved_path) { free(return_path); } return_path = 0; //stat() will set the correct errno for us } //else we succeeded! } } else { errno = EINVAL; } } else { errno = EINVAL; } return return_path; } #endif } }
27.328638
110
0.433431
[ "vector" ]
5bb7bdb5b848b99e197eb6e0de988ca8f3c2238a
268
cpp
C++
src/encrypt.cpp
Anmol-Singh-Jaggi/File-Locker
2af028e6371c0af01d3c733b82c4982af919052b
[ "MIT" ]
14
2015-09-29T08:56:01.000Z
2021-08-16T04:52:11.000Z
src/encrypt.cpp
Anmol-Singh-Jaggi/File-Locker
2af028e6371c0af01d3c733b82c4982af919052b
[ "MIT" ]
null
null
null
src/encrypt.cpp
Anmol-Singh-Jaggi/File-Locker
2af028e6371c0af01d3c733b82c4982af919052b
[ "MIT" ]
6
2015-09-30T18:20:42.000Z
2022-01-05T04:14:17.000Z
#include "encrypt.h" #include "common.h" using namespace std; void Encrypt( vector<unsigned char>& plainText, const string& key ) { int keyInt = ToInt( key ); for ( size_t i = 0; i < plainText.size(); i++ ) { plainText[i] = ( plainText[i] + keyInt ) % 128; } }
20.615385
67
0.634328
[ "vector" ]
5bbee823c958739ef81e4f737187559a0caf2520
3,744
cpp
C++
src/treent/GuiSystem.cpp
pourpluie/Pockets-team
cbae274cdabf2896ab7ecf113bccfbd005916ea7
[ "BSD-2-Clause" ]
null
null
null
src/treent/GuiSystem.cpp
pourpluie/Pockets-team
cbae274cdabf2896ab7ecf113bccfbd005916ea7
[ "BSD-2-Clause" ]
null
null
null
src/treent/GuiSystem.cpp
pourpluie/Pockets-team
cbae274cdabf2896ab7ecf113bccfbd005916ea7
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2014 David Wicks, sansumbrella.com * All rights reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "GuiSystem.h" using namespace cinder; #if 1 namespace treent { // // MARK: - GuiComponent // bool GuiComponent::contains( const ci::Vec2f &point, const MatrixAffine2f &world_transform ) { return interaction_bounds.contains( world_transform.invertCopy().transformPoint( point ) ); } // // MARK: - ButtonComponent // bool ButtonComponent::touchesBegan( ci::app::TouchEvent &event, const MatrixAffine2f &world_transform ) { for( auto &touch : event.getTouches() ) { if( contains( touch.getPos(), world_transform ) ) { _tracked_touch = touch.getId(); _is_hovering = true; return true; } } return false; } bool ButtonComponent::touchesMoved( ci::app::TouchEvent &event, const MatrixAffine2f &world_transform ) { for( auto &touch : event.getTouches() ) { if( touch.getId() == _tracked_touch ) { if( contains( touch.getPos(), world_transform ) ) _is_hovering = true; else _is_hovering = false; } } // don't capture moving touches return false; } bool ButtonComponent::touchesEnded( ci::app::TouchEvent &event, const MatrixAffine2f &world_transform ) { bool selected = false; for( auto &touch : event.getTouches() ) { if( touch.getId() == _tracked_touch ) { _tracked_touch = 0; // reset tracked touch _is_hovering = false; if( contains( touch.getPos(), world_transform ) ) { selected = true; break; } } } if( selected && select_fn ) { // call function last, as it may destroy this object select_fn(); } return false; } bool ButtonComponent::mouseDown( ci::app::MouseEvent &event, const MatrixAffine2f &world_transform ) { if( contains( event.getPos(), world_transform ) ) { _tracked_touch = MOUSE_ID; _is_hovering = true; return true; } return false; } bool ButtonComponent::mouseDrag( ci::app::MouseEvent &event, const MatrixAffine2f &world_transform ) { _is_hovering = contains( event.getPos(), world_transform ); return false; } bool ButtonComponent::mouseUp( ci::app::MouseEvent &event, const MatrixAffine2f &world_transform ) { bool selected = false; _tracked_touch = 0; if( contains( event.getPos(), world_transform ) ) selected = true; _is_hovering = false; if( selected && select_fn ) { select_fn(); } return false; } } #endif
27.529412
103
0.703793
[ "object" ]
5bc279e223ab5e57878b8627f66517116ee3c53d
553
cpp
C++
leetcode/Algorithms/PascalsTriangleII/solution.cpp
hxdone/puzzles
b729bce8a61f77ad7cbb70957e00c5ade9a0a35f
[ "Apache-2.0" ]
2
2015-07-03T03:05:30.000Z
2015-07-03T03:05:31.000Z
leetcode/Algorithms/PascalsTriangleII/solution.cpp
hxdone/puzzles
b729bce8a61f77ad7cbb70957e00c5ade9a0a35f
[ "Apache-2.0" ]
null
null
null
leetcode/Algorithms/PascalsTriangleII/solution.cpp
hxdone/puzzles
b729bce8a61f77ad7cbb70957e00c5ade9a0a35f
[ "Apache-2.0" ]
null
null
null
// by hxdone class Solution { public: vector<int> getRow(int rowIndex) { vector<int> cur_row; if (rowIndex < 0) return cur_row; vector<int> last_row; last_row.push_back(1); for (int i = 1; i <= rowIndex; ++i) { cur_row.clear(); cur_row.push_back(1); for (int j = 1; j < last_row.size(); ++j) cur_row.push_back(last_row[j-1]+last_row[j]); cur_row.push_back(1); last_row.swap(cur_row); } return last_row; } };
26.333333
61
0.509946
[ "vector" ]
5bc3e3b5eebb2371b35cf4aa5d5ea2f2805ff35b
4,550
hpp
C++
inc/manipulator.hpp
shinolab/dynamic-manipulation
d43bae688cecf87e15605ed6a9dbc80a782d72fc
[ "MIT" ]
null
null
null
inc/manipulator.hpp
shinolab/dynamic-manipulation
d43bae688cecf87e15605ed6a9dbc80a782d72fc
[ "MIT" ]
null
null
null
inc/manipulator.hpp
shinolab/dynamic-manipulation
d43bae688cecf87e15605ed6a9dbc80a782d72fc
[ "MIT" ]
null
null
null
#pragma once #include <fstream> #include "QPSolver.h" #include "arfModel.hpp" #include "FloatingObject.hpp" #include "tracker.hpp" #include "autd3.hpp" namespace dynaman { class Manipulator { public: Manipulator() {} virtual ~Manipulator() {} Manipulator(const Manipulator& m) = delete; Manipulator operator=(const Manipulator& m) = delete; Manipulator(Manipulator&& m) = default; Manipulator& operator=(Manipulator && m) = default; virtual int StartManipulation(FloatingObjectPtr pObject) = 0; virtual void FinishManipulation() = 0; virtual void PauseManipulation() = 0; virtual void ResumeManipulation() = 0; virtual void SetOnPause(std::function<void()>& func_on_pause) = 0; }; class MultiplexManipulator : public Manipulator { private: std::shared_ptr<autd::Controller> m_pAupa; std::shared_ptr<Tracker> m_pTracker; FloatingObjectPtr m_pObject; Eigen::Vector3f m_gainP; Eigen::Vector3f m_gainD; Eigen::Vector3f m_gainI; float m_freqLm; int m_period_control_ms; int m_period_track_ms; float m_lambda; std::shared_ptr<arfModelLinearBase> m_arfModelPtr; bool m_isRunning; bool m_isPaused; std::string m_obsLogName; std::string m_controlLogName; bool m_logEnabled; std::thread m_thr_control; std::thread m_thr_track; std::shared_mutex m_mtx_isRunning; std::mutex m_mtx_isPaused; std::mutex m_mtx_gain; std::ofstream m_obsLogStream; std::ofstream m_controlLogStream; std::function<void()> m_on_pause = []() {return; }; public: MultiplexManipulator( std::shared_ptr<autd::Controller> pAupa, std::shared_ptr<dynaman::Tracker> pTracker, const Eigen::Vector3f& gainP = Eigen::Vector3f::Constant(32.0f), const Eigen::Vector3f& gainD = Eigen::Vector3f::Constant(20.0f), const Eigen::Vector3f& gainI = Eigen::Vector3f::Constant(0.00f), float freqLm = 100.f, int period_control_ms = 10, int period_track_ms = 5, float lambda = 0.0f, std::shared_ptr<arfModelLinearBase> arfModelPtr = std::make_shared<arfModelFocusSphereR50>() ); MultiplexManipulator(const MultiplexManipulator& m) = delete; MultiplexManipulator operator=(const MultiplexManipulator& m) = delete; MultiplexManipulator(MultiplexManipulator&& m) = default; MultiplexManipulator& operator=(MultiplexManipulator && m) = default; static std::shared_ptr<Manipulator> Create( std::shared_ptr<autd::Controller> pAupa, std::shared_ptr<dynaman::Tracker> pTracker, const Eigen::Vector3f& gainP = Eigen::Vector3f::Constant(32.0f), const Eigen::Vector3f& gainD = Eigen::Vector3f::Constant(20.0f), const Eigen::Vector3f& gainI = Eigen::Vector3f::Constant(0.00f), float freqLm = 100.f, int period_control_ms = 10, int period_track_ms = 5, float lambda = 0.0f, std::shared_ptr<arfModelLinearBase> arfModelPtr = std::make_shared<arfModelFocusSphereR50>() ); int StartManipulation(FloatingObjectPtr pObject) override; void FinishManipulation() override; void PauseManipulation() override; void ResumeManipulation() override; void SetOnPause(std::function<void()>& func_on_pause) override; Eigen::Vector3f ComputeForce(DWORD systime, FloatingObjectPtr pObject); Eigen::VectorXf ComputeDuty(const Eigen::Vector3f& forceTarget, const Eigen::Vector3f& position); Eigen::Array<bool, -1, -1> chooseAupaToDrive( const Eigen::Vector3f& forceTarget, const Eigen::Vector3f& position ); Eigen::MatrixXf posRelActive( const Eigen::Vector3f& postiion, const Eigen::Array<bool, -1, -1>& isActive ); std::vector<Eigen::Matrix3f> rotsAupaActive( const Eigen::Array<bool, -1, -1>& isActive ); QuadraticProgram constructQp( const Eigen::Vector3f& forceTarget, const Eigen::MatrixXf& posRel, const std::vector<Eigen::Matrix3f>& rotsAupa ); void ApplyActuation(const Eigen::VectorXf& duties); std::vector<autd::GainPtr> CreateLateralGainList(const Eigen::VectorXf& duties, const Eigen::Vector3f& focus); Eigen::VectorXf expandDuty(const Eigen::VectorXf& dutiesThin, const Eigen::Array<bool, -1, -1>& is_active); void setGain(const Eigen::Vector3f& gainP, const Eigen::Vector3f& gainD, const Eigen::Vector3f& gainI); Eigen::Vector3f gainP(); Eigen::Vector3f gainD(); Eigen::Vector3f gainI(); bool IsRunning(); bool IsPaused(); std::shared_ptr<arfModelLinearBase> arfModel(); void EnableLog(const std::string& obsLogName, const std::string& controlLogName); void DisableLog(); private: void InitLogStream(); void ExecuteSingleObservation(); void ExecuteSingleActuation(); }; }
33.211679
112
0.737582
[ "vector" ]
5bcf23e7e8d1078ac9d085b947557eec7490b030
815
cpp
C++
src/shaman/tagged/global_vars.cpp
nestordemeure/Shaman
39a6d6d658535208fbcb255f37f6eaf1f0c02ca1
[ "Apache-2.0" ]
4
2021-04-16T23:32:28.000Z
2021-11-23T10:02:01.000Z
src/shaman/tagged/global_vars.cpp
nestordemeure/shaman
39a6d6d658535208fbcb255f37f6eaf1f0c02ca1
[ "Apache-2.0" ]
null
null
null
src/shaman/tagged/global_vars.cpp
nestordemeure/shaman
39a6d6d658535208fbcb255f37f6eaf1f0c02ca1
[ "Apache-2.0" ]
null
null
null
#include "global_vars.h" // used to model the stacktrace const Tag ShamanGlobals::tagUntagged = 0; std::vector<std::string> ShamanGlobals::tagDecryptor = std::vector<std::string>({"untagged_block"}); // array that associate with tags (indexes) with block-names std::unordered_map<std::string, Tag> ShamanGlobals::nameEncryptor = {{"untagged_block", ShamanGlobals::tagUntagged}}; // hashtable that associate block-names with tags thread_local std::stack<Tag> ShamanGlobals::tagStack({ShamanGlobals::tagUntagged}); // contains the current stack std::mutex ShamanGlobals::mutexAddName; // counter for the number of unstable branches std::atomic_int ShamanGlobals::unstableBranchCounter(0); std::unordered_map<Tag, unsigned int> ShamanGlobals::unstableBranchSummary; std::mutex ShamanGlobals::mutexAddUnstableBranch;
58.214286
167
0.792638
[ "vector", "model" ]
5bdc7765ea20f90a6152c6db034df9c05c465450
20,858
cpp
C++
Source/CLI/CommandLine_Parser.cpp
g-maxime/MediaConch_SourceCode
54208791ca0b6eb3f7bffd17f67e236777f69d89
[ "BSD-2-Clause" ]
null
null
null
Source/CLI/CommandLine_Parser.cpp
g-maxime/MediaConch_SourceCode
54208791ca0b6eb3f7bffd17f67e236777f69d89
[ "BSD-2-Clause" ]
null
null
null
Source/CLI/CommandLine_Parser.cpp
g-maxime/MediaConch_SourceCode
54208791ca0b6eb3f7bffd17f67e236777f69d89
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (c) MediaArea.net SARL. All Rights Reserved. * * Use of this source code is governed by a BSD-style license that can * be found in the License.html file in the root of the source tree. */ //--------------------------------------------------------------------------- #include <string> #include <vector> #include <algorithm> #ifdef __BORLANDC__ #pragma hdrstop #endif //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "CommandLine_Parser.h" #include "Help.h" //--------------------------------------------------------------------------- //Parse Command Line #define LAUNCH(_METHOD) \ { \ int Return=_METHOD(cli, argument); \ if (Return == CLI_RETURN_ERROR || Return == CLI_RETURN_FINISH) \ return Return; \ } \ #define OPTION(_TEXT, _TOLAUNCH) \ else if (argument.find(_TEXT)==0) LAUNCH(_TOLAUNCH) \ #define OPTION2(_TEXT, _TOLAUNCH) \ else if (argument.find(_TEXT)==0) _TOLAUNCH(); \ //*************************************************************************** // Defaults //*************************************************************************** ZenLib::Ztring LogFile_FileName; std::string Last_Argument; bool Separator = false; //*************************************************************************** // Main //*************************************************************************** static bool wait_for_another_argument(std::string& argument) { if (argument=="-pc") { Last_Argument = "--pluginsconfiguration="; return true; } else if (argument=="-p") { Last_Argument = "--policy="; return true; } else if (argument=="-d") { Last_Argument = "--display="; return true; } else if (argument=="-c") { Last_Argument = "--configuration="; return true; } else if (argument=="-i") { Last_Argument = "--implementationschema="; return true; } else if (argument=="-iv") { Last_Argument = "--implementationverbosity="; return true; } else if (argument=="-prf") { Last_Argument = "--policyreferencefile="; return true; } else if (argument=="-up") { Last_Argument = "--useplugin="; return true; } else if (argument=="-u") { Last_Argument = "--user="; return true; } else if (argument=="-wf") { Last_Argument = "--watchfolder="; return true; } else if (argument=="-wfr") { Last_Argument = "--watchfolder-reports="; return true; } else if (argument=="-wfu") { Last_Argument = "--watchfolder-user="; return true; } return false; } static void change_short_options_to_long(std::string& argument) { // Help short options if (argument=="-ha") argument = "--help=Advanced"; if (argument=="-v") argument = "--version"; if (argument=="-f") argument = "--force"; if (argument=="-nmil") argument = "--nomilanalyze"; // Backward compatibility if (argument=="-tc") argument = "--report=MediaConch"; if (argument=="-ti") argument = "--report=MediaInfo"; if (argument=="-tt") argument = "--report=MediaTrace"; // Report other options if (argument=="--mediaconch") argument = "-mc"; if (argument=="--mediainfo") argument = "-mi"; if (argument=="--mediatrace") argument = "-mt"; if (argument=="--micromediatrace") argument = "-mmt"; // Report short options if (argument=="-mc") argument = "--report=MediaConch"; if (argument=="-mi") argument = "--report=MediaInfo"; if (argument=="-mt") argument = "--report=MediaTrace"; if (argument=="-mmt") argument = "--report=MicroMediaTrace"; // Format short options if (argument=="-ft") argument = "--format=Text"; if (argument=="-fx") argument = "--format=XML"; if (argument=="-fa") argument = "--format=MAXML"; if (argument=="-fj") argument = "--format=JSTREE"; if (argument=="-fh") argument = "--format=HTML"; if (argument=="-fc") argument = "--format=CSV"; if (argument=="-fs") argument = "--format=SIMPLE"; // Compression short options if (argument=="-cz") argument = "--compression=zlib"; // Asynchronous mode if (argument=="-as") argument = "--async=yes"; if (argument=="-fi") argument = "--fileinformation"; // Watch Folder short options if (argument=="-wfnr") argument = "--watchfolder-not-recursive"; if (argument=="-wfl") argument = "--watchfolders-list"; } int Parse(MediaConch::CLI* cli, std::string& argument) { if (argument == "--") { Separator = true; return CLI_RETURN_NONE; } if (Separator) return CLI_RETURN_FILE; // With 1 other argument if (Last_Argument.length()) { argument = Last_Argument.append(argument); Last_Argument = ""; } if (wait_for_another_argument(argument)) return CLI_RETURN_NONE; change_short_options_to_long(argument); // Listing if (0); OPTION("--help", Help) OPTION("-h", Help) OPTION("--version", Version) OPTION("--report", Report) OPTION("--format", Format) OPTION("--policyreferencefile", PolicyReferenceFile) OPTION("--policy", PolicyOption) OPTION("--display", Display) OPTION("--logfile", LogFile) OPTION("--configuration", Configuration) OPTION("--implementationschema", ImplementationSchema) OPTION("--implementationverbosity", ImplementationVerbosity) OPTION("--compression", Compression) OPTION("--force", Force) OPTION("--nomilanalyze", NoMilAnalyze) OPTION("--async", Asynchronous) OPTION("--pluginslist", PluginsList) OPTION("--useplugin", UsePlugin) OPTION("--pluginsconfiguration", PluginsConfiguration) OPTION("--defaultvaluesfortype", DefaultValuesForType) OPTION("--createpolicy", CreatePolicy) OPTION("--fileinformation", FileInformation) OPTION("--watchfolders-list", WatchFoldersList) OPTION("--watchfolder-reports", WatchFolderReports) OPTION("--watchfolder-not-recursive", WatchFolderNotRecursive) OPTION("--watchfolder-user", WatchFolderUser) OPTION("--watchfolder", WatchFolder) OPTION("--user", User) OPTION("--list", List) //Default OPTION("--", Default) else { if (argument[0] == '-') return Help_Usage(); return CLI_RETURN_FILE; } return CLI_RETURN_NONE; } //--------------------------------------------------------------------------- CL_OPTION(Help) { (void)cli; //Form : --Help=Advanced size_t egal_pos = argument.find('='); if (egal_pos != std::string::npos) { std::string level = argument.substr(egal_pos + 1); transform(level.begin(), level.end(), level.begin(), (int(*)(int))tolower); //(int(*)(int)) is a patch for unix if (level == "advanced") return Help_Advanced(); else if (level == "ssl") return Help_Ssl(); else if (level == "ssh") return Help_Ssh(); } return Help(); } //--------------------------------------------------------------------------- CL_OPTION(Version) { (void)cli; (void)argument; return Version(); } //--------------------------------------------------------------------------- CL_OPTION(Report) { //Form : --Inform=Text size_t egal_pos = argument.find('='); if (egal_pos == std::string::npos) { Help(); return CLI_RETURN_ERROR; } // New requested reports std::string report_kind = argument.substr(egal_pos + 1); cli->set_report_set(report_kind); return CLI_RETURN_NONE; } //--------------------------------------------------------------------------- CL_OPTION(Format) { //Form : --Inform=Text size_t egal_pos = argument.find('='); if (egal_pos == std::string::npos) { Help(); return CLI_RETURN_ERROR; } std::string format = argument.substr(egal_pos + 1); return cli->set_format(format); } //--------------------------------------------------------------------------- CL_OPTION(PolicyOption) { //Form : --Inform=Text size_t egal_pos = argument.find('='); if (egal_pos == std::string::npos) { Help_Policy(); return CLI_RETURN_ERROR; } std::string file; file.assign(argument, egal_pos + 1, std::string::npos); cli->add_policy(file); return CLI_RETURN_NONE; } //--------------------------------------------------------------------------- CL_OPTION(Display) { //Form : --Inform=Text size_t egal_pos = argument.find('='); if (egal_pos == std::string::npos) { Help(); return CLI_RETURN_ERROR; } std::string file; file.assign(argument, egal_pos +1 , std::string::npos); cli->set_display_file(file); return CLI_RETURN_NONE; } //--------------------------------------------------------------------------- CL_OPTION(LogFile) { //Form : --LogFile=Text (void)cli; LogFile_FileName.assign(ZenLib::Ztring().From_UTF8(argument), 10, std::string::npos); return CLI_RETURN_NONE; } //--------------------------------------------------------------------------- CL_OPTION(Configuration) { //Form : --Configuration=File size_t egal_pos = argument.find('='); if (egal_pos == std::string::npos) { Help(); return CLI_RETURN_ERROR; } std::string file; file.assign(argument, egal_pos + 1 , std::string::npos); cli->set_configuration_file(file); return CLI_RETURN_NONE; } //--------------------------------------------------------------------------- CL_OPTION(ImplementationSchema) { //Form : --ImplemnetationSchema=File size_t egal_pos = argument.find('='); if (egal_pos == std::string::npos) { Help(); return CLI_RETURN_ERROR; } std::string file; file.assign(argument, egal_pos + 1 , std::string::npos); cli->set_implementation_schema_file(file); return CLI_RETURN_NONE; } //--------------------------------------------------------------------------- CL_OPTION(ImplementationVerbosity) { //Form : --ImplemnetationSchema=File size_t egal_pos = argument.find('='); if (egal_pos == std::string::npos) { Help_Usage(); return CLI_RETURN_ERROR; } std::string verbosity; verbosity.assign(argument, egal_pos + 1 , std::string::npos); cli->set_implementation_verbosity(verbosity); return CLI_RETURN_NONE; } //--------------------------------------------------------------------------- CL_OPTION(PolicyReferenceFile) { //Form : --PolicyReferenceFile=File size_t egal_pos = argument.find('='); if (egal_pos == std::string::npos) { Help(); return CLI_RETURN_ERROR; } std::string file; file.assign(argument, egal_pos + 1 , std::string::npos); cli->set_policy_reference_file(file); return CLI_RETURN_NONE; } //--------------------------------------------------------------------------- CL_OPTION(Compression) { //Form : --Compression=Mode size_t egal_pos = argument.find('='); if (egal_pos == std::string::npos) { Help(); return CLI_RETURN_ERROR; } std::string mode; mode.assign(argument, egal_pos + 1 , std::string::npos); transform(mode.begin(), mode.end(), mode.begin(), (int(*)(int))tolower); //(int(*)(int)) is a patch for unix return cli->set_compression_mode(mode); } //--------------------------------------------------------------------------- CL_OPTION(Force) { (void)argument; cli->set_force_analyze(true); return CLI_RETURN_NONE; } //--------------------------------------------------------------------------- CL_OPTION(NoMilAnalyze) { (void)argument; cli->set_mil_analyze(false); return CLI_RETURN_NONE; } //--------------------------------------------------------------------------- CL_OPTION(Asynchronous) { //Form : --Compression=Mode size_t egal_pos = argument.find('='); std::string async; if (egal_pos != std::string::npos) async.assign(argument, egal_pos + 1 , std::string::npos); else async = "yes"; transform(async.begin(), async.end(), async.begin(), (int(*)(int))tolower); //(int(*)(int)) is a patch for unix bool is_async = false; if (async == "yes") is_async = true; cli->set_asynchronous(is_async); return CLI_RETURN_NONE; } //--------------------------------------------------------------------------- CL_OPTION(UsePlugin) { //Form : --UsePlugin=IdPlugin size_t egal_pos = argument.find('='); if (egal_pos == std::string::npos) { Help(); return CLI_RETURN_ERROR; } std::string plugin; plugin.assign(argument, egal_pos + 1 , std::string::npos); cli->add_plugin_to_use(plugin); return CLI_RETURN_NONE; } //--------------------------------------------------------------------------- CL_OPTION(PluginsList) { //Form : --PluginsList (void)argument; cli->set_plugins_list_mode(); return CLI_RETURN_NONE; } //--------------------------------------------------------------------------- CL_OPTION(PluginsConfiguration) { //Form : --PluginsConfiguration=File size_t egal_pos = argument.find('='); if (egal_pos == std::string::npos) { Help(); return CLI_RETURN_ERROR; } std::string file; file.assign(argument, egal_pos + 1 , std::string::npos); cli->set_plugins_configuration_file(file); return CLI_RETURN_NONE; } //--------------------------------------------------------------------------- CL_OPTION(DefaultValuesForType) { //Form : --DefaultValuesForType=type,field size_t egal_pos = argument.find('='); if (egal_pos == std::string::npos) { Help(); return CLI_RETURN_ERROR; } size_t comma_pos = argument.find(','); if (comma_pos == std::string::npos) { Help(); return CLI_RETURN_ERROR; } std::string type, field; type = argument.substr(egal_pos + 1, comma_pos - egal_pos - 1); field.assign(argument, comma_pos + 1 , std::string::npos); std::vector<std::string> values; if (cli->get_values_for_type_field(type, field, values) < 0) return CLI_RETURN_ERROR; std::stringstream out; for (size_t i = 0; i < values.size(); ++i) { if (i) out << ","; out << values[i]; } ZenLib::Ztring str; str.From_UTF8(out.str()); STRINGOUT(str); return CLI_RETURN_FINISH; } //--------------------------------------------------------------------------- CL_OPTION(CreatePolicy) { (void)argument; //Form : --CreatePolicy cli->set_create_policy_mode(); return CLI_RETURN_NONE; } //--------------------------------------------------------------------------- CL_OPTION(FileInformation) { //Form : --FileInformation, -fi (void)argument; cli->set_file_information_mode(); return CLI_RETURN_NONE; } //--------------------------------------------------------------------------- CL_OPTION(WatchFoldersList) { //Form : --WatchFoldersList (void)argument; cli->set_list_watch_folders_mode(); return CLI_RETURN_NONE; } //--------------------------------------------------------------------------- CL_OPTION(WatchFolder) { //Form : --WatchFolder=folder, -wf folder size_t egal_pos = argument.find('='); if (egal_pos == std::string::npos) { Help(); return CLI_RETURN_ERROR; } std::string folder; folder.assign(argument, egal_pos + 1 , std::string::npos); cli->set_watch_folder(folder); return CLI_RETURN_NONE; } //--------------------------------------------------------------------------- CL_OPTION(WatchFolderReports) { //Form : --WatchFolderReports=folder, -wfr folder size_t egal_pos = argument.find('='); if (egal_pos == std::string::npos) { Help(); return CLI_RETURN_ERROR; } std::string folder; folder.assign(argument, egal_pos + 1 , std::string::npos); cli->set_watch_folder_reports(folder); return CLI_RETURN_NONE; } //--------------------------------------------------------------------------- CL_OPTION(WatchFolderNotRecursive) { //Form : --WatchFolderNotRecursive, -wfnr (void)argument; return cli->set_watch_folder_not_recursive(); } //--------------------------------------------------------------------------- CL_OPTION(WatchFolderUser) { //Form : --WatchFolderUser=user, -wfu user size_t egal_pos = argument.find('='); if (egal_pos == std::string::npos) { Help(); return CLI_RETURN_ERROR; } std::string user; user.assign(argument, egal_pos + 1 , std::string::npos); cli->set_watch_folder_user(user); return CLI_RETURN_NONE; } //--------------------------------------------------------------------------- CL_OPTION(User) { //Form : --User=user, -u user size_t egal_pos = argument.find('='); if (egal_pos == std::string::npos) { Help(); return CLI_RETURN_ERROR; } std::string user; user.assign(argument, egal_pos + 1 , std::string::npos); cli->set_user_to_use(user); return CLI_RETURN_NONE; } //--------------------------------------------------------------------------- CL_OPTION(List) { //Form : --list (void)argument; cli->set_list_mode(); return CLI_RETURN_NONE; } //--------------------------------------------------------------------------- CL_OPTION(Default) { //Form : --Option=Value, --Option if (argument.size() < 2) return CLI_RETURN_NONE; std::string key, value; size_t egal_pos = argument.find('='); if (egal_pos != std::string::npos) { key.assign(argument, 2, egal_pos - 2); value.assign(argument, egal_pos + 1 , std::string::npos); } else key.assign(argument, 2, std::string::npos); return cli->register_option(key, value); } //--------------------------------------------------------------------------- void LogFile_Action(ZenLib::Ztring Inform) { if (LogFile_FileName.empty()) return; std::string Inform_Ansi=Inform.To_UTF8(); std::fstream File(LogFile_FileName.To_Local().c_str(), std::ios_base::out|std::ios_base::trunc); File.write(Inform_Ansi.c_str(), Inform_Ansi.size()); } //--------------------------------------------------------------------------- void CallBack_Set(MediaConch::CLI* cli, void* Event_CallBackFunction) { //CallBack configuration std::stringstream callback_mem; callback_mem << "CallBack=memory://"; callback_mem << (size_t)Event_CallBackFunction; std::string value = callback_mem.str(); cli->register_option("Event_CallBackFunction", value); }
28.690509
120
0.469892
[ "vector", "transform" ]
5bde3ca78c807d9a14003fd8d471ee5a1a05b090
3,659
cpp
C++
src/test/test_assignments.cpp
alexey-milovidov/robin-hood-hashing
c57331b8a086cc427fae9aabedbdbb13eb72d69e
[ "MIT" ]
null
null
null
src/test/test_assignments.cpp
alexey-milovidov/robin-hood-hashing
c57331b8a086cc427fae9aabedbdbb13eb72d69e
[ "MIT" ]
null
null
null
src/test/test_assignments.cpp
alexey-milovidov/robin-hood-hashing
c57331b8a086cc427fae9aabedbdbb13eb72d69e
[ "MIT" ]
1
2022-02-09T06:50:44.000Z
2022-02-09T06:50:44.000Z
#include "test_base.h" #include <vector> // creates a map with some data in it template <class M> M createMap(int numElements) { M m; for (int i = 0; i < numElements; ++i) { m[static_cast<typename M::key_type>((i + 123) * 7)] = static_cast<typename M::mapped_type>(i); } return m; } TEMPLATE_TEST_CASE("copy and assign maps", "", FlatMap, NodeMap) { using Map = TestType; { Map a = createMap<Map>(15); } { Map a = createMap<Map>(100); } { Map a = createMap<Map>(1); Map b = a; REQUIRE(a == b); } { Map a; REQUIRE(a.empty()); a.clear(); REQUIRE(a.empty()); } { Map a = createMap<Map>(100); Map b = a; } { Map a; a[123] = 321; a.clear(); std::vector<Map> maps(10, a); for (size_t i = 0; i < maps.size(); ++i) { REQUIRE(maps[i].empty()); } } { std::vector<Map> maps(10); } { Map a; std::vector<Map> maps(10, a); } { Map a; a[123] = 321; std::vector<Map> maps(10, a); a[123] = 1; for (size_t i = 0; i < maps.size(); ++i) { REQUIRE(maps[i].size() == 1); REQUIRE(maps[i].find(123)->second == 321); } } } TEMPLATE_TEST_CASE("test assignment combinations", "", FlatMap, NodeMap) { using Map = TestType; { Map a; Map b; b = a; } { Map a; Map const& aConst = a; Map b; a[123] = 321; b = a; REQUIRE(a.find(123)->second == 321); REQUIRE(aConst.find(123)->second == 321); REQUIRE(b.find(123)->second == 321); a[123] = 111; REQUIRE(a.find(123)->second == 111); REQUIRE(aConst.find(123)->second == 111); REQUIRE(b.find(123)->second == 321); b[123] = 222; REQUIRE(a.find(123)->second == 111); REQUIRE(aConst.find(123)->second == 111); REQUIRE(b.find(123)->second == 222); } { Map a; Map b; a[123] = 321; a.clear(); b = a; REQUIRE(a.size() == 0); REQUIRE(b.size() == 0); } { Map a; Map b; b[123] = 321; b = a; REQUIRE(a.size() == 0); REQUIRE(b.size() == 0); } { Map a; Map b; b[123] = 321; b.clear(); b = a; REQUIRE(a.size() == 0); REQUIRE(b.size() == 0); } { Map a; a[1] = 2; Map b; b[3] = 4; b = a; REQUIRE(a.size() == 1); REQUIRE(b.size() == 1); REQUIRE(b.find(1)->second == 2); a[1] = 123; REQUIRE(a.size() == 1); REQUIRE(b.size() == 1); REQUIRE(b.find(1)->second == 2); } { Map a; a[1] = 2; a.clear(); Map b; REQUIRE(a == b); b[3] = 4; REQUIRE(a != b); b = a; REQUIRE(a == b); } { Map a; a[1] = 2; Map b; REQUIRE(a != b); b[3] = 4; b.clear(); REQUIRE(a != b); b = a; REQUIRE(a == b); } { Map a; a[1] = 2; a.clear(); Map b; b[3] = 4; REQUIRE(a != b); b.clear(); REQUIRE(a == b); b = a; REQUIRE(a == b); } } TEMPLATE_TEST_CASE("reserve", "", FlatMap, NodeMap) { TestType map; REQUIRE(0 == map.mask()); map.reserve(819); REQUIRE(1023 == map.mask()); map.reserve(820); REQUIRE(2047 == map.mask()); }
19.462766
74
0.408582
[ "vector" ]
5bdf8e0ed954504226dddb1bfd5e2e6a6d4d8b51
3,672
cpp
C++
src/core/DetectorExtractor.cpp
liyinnbw/MSFM
b846816594851c84094078586047a0d1f200f166
[ "MIT" ]
5
2020-02-02T23:43:59.000Z
2021-12-10T09:42:05.000Z
src/core/DetectorExtractor.cpp
projectcs2103t/MSFM
b846816594851c84094078586047a0d1f200f166
[ "MIT" ]
null
null
null
src/core/DetectorExtractor.cpp
projectcs2103t/MSFM
b846816594851c84094078586047a0d1f200f166
[ "MIT" ]
1
2020-02-12T13:24:13.000Z
2020-02-12T13:24:13.000Z
/* * Unified API for various feature detector/extractors * currently only ORB is usable */ #include "DetectorExtractor.h" // #include <brisk/brisk.h> // #include <brisk/scale-space-feature-detector.h> // #include <brisk/harris-score-calculator.h> #include <opencv2/imgproc/imgproc.hpp> DetectorExtractor& DetectorExtractor::GetInstance(){ static DetectorExtractor instance; return instance; } DetectorExtractor::DetectorExtractor() :octaves_(3), briskDetectionThreshold_(20),//10.0), briskDetectionAbsoluteThreshold_(800.0), maxFeatures_(800),//2000), briskDescriptionRotationInvariance_(true), briskDescriptionScaleInvariance_(true), briskMatchingThreshold_(60.0) { // detector.reset(new brisk::ScaleSpaceFeatureDetector<brisk::HarrisScoreCalculator>( // briskDetectionThreshold_, octaves_, // briskDetectionAbsoluteThreshold_, // maxFeatures_)); // detector_noOctave.reset(new brisk::ScaleSpaceFeatureDetector<brisk::HarrisScoreCalculator>( // briskDetectionThreshold_, 0, // briskDetectionAbsoluteThreshold_, // maxFeatures_)); // //detector.reset(new cv::GridAdaptedFeatureDetector(new cv::FastFeatureDetector(briskDetectionThreshold_),briskDetectionMaximumKeypoints_, 7, 4 )); // extractor.reset(new brisk::BriskDescriptorExtractor(briskDescriptionRotationInvariance_,briskDescriptionScaleInvariance_)); float scalef = 2.0f; //1.2f; int edgeThreshold = 31; //pixels int patchSize = 31; detectorExtractor = cv::ORB::create(maxFeatures_,scalef, octaves_, edgeThreshold, 0, 2, cv::ORB::HARRIS_SCORE, patchSize); int thresh = 30; //detectorExtractor = cv::BRISK::create(thresh, octaves_, scalef); } DetectorExtractor::~DetectorExtractor(){ } void DetectorExtractor::detectORB(const cv::Mat &img, std::vector<cv::KeyPoint> &kpts, const cv::Mat &mask){ kpts.clear(); detectorExtractor->detect(img,kpts,mask); } void DetectorExtractor::computeORB(const cv::Mat &img, std::vector<cv::KeyPoint> &kpts, cv::Mat &decs){ detectorExtractor->compute(img,kpts,decs); } void DetectorExtractor::detectBRISK(const cv::Mat &img, std::vector<cv::KeyPoint> &kpts, const cv::Mat &mask){ // kpts.clear(); // //XXX:for brisk, mask is not yet supported // detector->detect(img,kpts, mask); } void DetectorExtractor::detectBRISK_hasKpts(const cv::Mat &img, std::vector<cv::KeyPoint> &kpts, const cv::Mat &mask){ // //XXX:do not clear kpts, cos we use kpts to specify kepoints locations to detect // //XXX:for brisk, mask is not yet supported // detector_noOctave->detect(img,kpts, mask); } void DetectorExtractor::computeBRISK(const cv::Mat &img, std::vector<cv::KeyPoint> &kpts, cv::Mat &decs){ // //XXX:keypoints list will be modified! keypoits for which descriptor cannot be computed are removed // extractor->compute(img, kpts, decs); } // Bit set count operation from // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel int DetectorExtractor::descriptorDistance(const cv::Mat &a, const cv::Mat &b) { const int *pa = a.ptr<int32_t>(); const int *pb = b.ptr<int32_t>(); int dist=0; for(int i=0; i<8; i++, pa++, pb++) { unsigned int v = *pa ^ *pb; v = v - ((v >> 1) & 0x55555555); v = (v & 0x33333333) + ((v >> 2) & 0x33333333); dist += (((v + (v >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24; } return dist; }
36.72
154
0.654684
[ "vector" ]
5be383b22814a77072a2eca07aad933699bf316e
7,888
cc
C++
lib/k2hcryptcommon.cc
hiwakaba/k2hash
154257ccc3e0aaa5cefdb0361a354ec19b53616d
[ "MIT" ]
38
2016-12-09T01:44:43.000Z
2021-06-24T01:33:17.000Z
lib/k2hcryptcommon.cc
hiwakaba/k2hash
154257ccc3e0aaa5cefdb0361a354ec19b53616d
[ "MIT" ]
6
2016-12-09T05:38:38.000Z
2020-11-16T05:20:30.000Z
lib/k2hcryptcommon.cc
hiwakaba/k2hash
154257ccc3e0aaa5cefdb0361a354ec19b53616d
[ "MIT" ]
18
2016-12-09T01:48:33.000Z
2021-01-20T06:33:00.000Z
/* * K2HASH * * Copyright 2018 Yahoo Japan Corporation. * * K2HASH is key-valuew store base libraries. * K2HASH is made for the purpose of the construction of * original KVS system and the offer of the library. * The characteristic is this KVS library which Key can * layer. And can support multi-processing and multi-thread, * and is provided safely as available KVS. * * For the full copyright and license information, please view * the license file that was distributed with this source code. * * AUTHOR: Takeshi Nakatani * CREATE: Mon May 7 2018 * REVISION: * */ #include <string.h> #include <netdb.h> #include <unistd.h> #include "k2hcommon.h" #include "k2hcryptcommon.h" #include "k2hutil.h" #include "k2hdbg.h" using namespace std; //--------------------------------------------------------- // Common Utilities //--------------------------------------------------------- // // Get unique ID // // [NOTE] // This function generates system-wide unique ID. // If generated ID does not unique, but we do not care for it. // Because k2hash needs unique ID for only one key's history. // This means that it may be a unique only to one key. // // We generates it by following seed's data. // unique ID = // base64( // sha256( // bytes array( // 8 bytes - nano seconds(by clock_gettime) at calling this. // 8 bytes - seconds(by clock_gettime) at calling this. // 8 bytes - thread id on the box. // 8 bytes - random value by rand() function. // n bytes - hostname // ) // ) // ); // string k2h_get_uniqid_for_history(const struct timespec& rtime) { static unsigned int seed = 0; static char hostname[NI_MAXHOST]; static size_t hostnamelen; static bool init = false; if(!init){ // seed for rand() struct timespec tmprtime = {0, 0}; if(-1 == clock_gettime(CLOCK_REALTIME_COARSE, &tmprtime)){ WAN_K2HPRN("could not get clock time by errno(%d), so unix time is instead of it.", errno); seed = static_cast<unsigned int>(time(NULL)); // base is sec }else{ seed = static_cast<unsigned int>(tmprtime.tv_nsec / 1000); // base is us } // local hostname if(0 != gethostname(hostname, sizeof(hostname))){ WAN_K2HPRN("Could not get localhost name by errno(%d), so \"localhost\" is set.", errno); strcpy(hostname, "localhost"); } hostnamelen = strlen(hostname); init = true; } // set datas uint64_t ard64[4]; // [1]->nsec, [2]->sec, [3]->tid, [4]->rand ard64[0] = static_cast<uint64_t>(rtime.tv_nsec); ard64[1] = static_cast<uint64_t>(rtime.tv_sec); ard64[2] = static_cast<uint64_t>(gettid()); ard64[3] = static_cast<uint64_t>(rand_r(&seed)); // [TODO] should use MAC address instead of rand(). seed++; // not need barrier // set to binary array unsigned char bindata[NI_MAXHOST + (sizeof(uint64_t) * 4)]; size_t setpos; for(setpos = 0; setpos < (sizeof(uint64_t) * 4); ++setpos){ bindata[setpos] = static_cast<unsigned char>(((setpos % 8) ? (ard64[setpos / 8] >> ((setpos % 8) * 8)) : ard64[setpos / 8]) & 0xff); } memcpy(&bindata[setpos], hostname, hostnamelen); setpos += hostnamelen; // SHA256 return to_sha256_string(bindata, setpos); } // // Utilities for AES256 Salt // // [NOTE] // We might should be used such as std::random rather than rand(). // However, this function is performed only generation of salt, // salt need not be strictly random. And salt is not a problem // even if collision between threads. Thus, we use the rand. // However, this function is to be considerate of another functions // using rand, so this uses rand_r for not changing seed. // bool k2h_pkcs5_salt(unsigned char* salt, size_t length) { static unsigned int seed = 0; static bool init = false; if(!init){ struct timespec rtime = {0, 0}; if(-1 == clock_gettime(CLOCK_REALTIME_COARSE, &rtime)){ WAN_K2HPRN("could not get clock time by errno(%d), so unix time is instead of it.", errno); seed = static_cast<unsigned int>(time(NULL)); // base is sec }else{ seed = static_cast<unsigned int>(rtime.tv_nsec / 1000); // base is us } init = true; } if(!salt || 0 == length){ ERR_K2HPRN("parameters are wrong."); return false; } for(size_t cnt = 0; cnt < length; ++cnt){ seed = static_cast<unsigned int>(rand_r(&seed)); salt[cnt] = static_cast<unsigned char>(seed & 0xFF); } return true; } // // Utilities for AES256 IV // // [NOTE] // Initial Vector(IV) should be generated using functions of each // crypt library. However, it is complicated with OpenSSL(RAND_bytes)/ // gcrypt(gcry_randomize)/NSS(PK11_GenerateRandom)/nettle, and random // functions are not found with nettle alone. // As a result, nettle uses /dev/(u)random etc and uses random/rand // function. Therefore, we make initial seed as random as possible, // and make IV with this function like generating salt. // bool k2h_generate_iv(unsigned char* iv, size_t length) { static unsigned int seed = 0; static bool init = false; if(!init){ unsigned char tid = static_cast<unsigned char>(gettid()); // use thread id struct timespec rtime = {0, 0}; if(-1 == clock_gettime(CLOCK_REALTIME_COARSE, &rtime)){ WAN_K2HPRN("could not get clock time by errno(%d), so unix time is instead of it.", errno); seed = static_cast<unsigned int>(time(NULL)); // base is sec }else{ seed = static_cast<unsigned int>(rtime.tv_nsec / 1000); // base is us } seed = ((seed << 8) | (static_cast<unsigned int>(tid) & 0xff)); // merge init = true; } if(!iv || 0 == length){ ERR_K2HPRN("parameters are wrong."); return false; } for(size_t cnt = 0; cnt < length; ++cnt){ seed = static_cast<unsigned int>(rand_r(&seed)); iv[cnt] = static_cast<unsigned char>(seed & 0xFF); } return true; } // // Utilities for Iteration count // bool k2h_copy_iteration_count(unsigned char* setpos, int iter, size_t count) { if(!setpos || iter <= 0 || count < 4){ ERR_K2HPRN("parameters are wrong."); return false; } // force 4 bytes big endian int32_t tmpiter = static_cast<int32_t>(iter); tmpiter = htobe32(tmpiter); // 4 byte is iteration count(big endian) setpos[0] = static_cast<unsigned char>((tmpiter >> 24) & 0xff); setpos[1] = static_cast<unsigned char>((tmpiter >> 16) & 0xff); setpos[2] = static_cast<unsigned char>((tmpiter >> 8) & 0xff); setpos[3] = static_cast<unsigned char>(tmpiter & 0xff); // set rest bytes as dummy if(4 < count && !k2h_generate_iv(&setpos[4], (count - 4))){ return false; } return true; } // // Utilities for Iteration count // int k2h_get_iteration_count(const unsigned char* getpos) { if(!getpos){ ERR_K2HPRN("parameters are wrong."); return -1; } int32_t tmpiter = 0; tmpiter |= (static_cast<int32_t>(getpos[0]) << 24) & 0xff000000; tmpiter |= (static_cast<int32_t>(getpos[1]) << 16) & 0xff0000; tmpiter |= (static_cast<int32_t>(getpos[2]) << 8) & 0xff00; tmpiter |= static_cast<int32_t>(getpos[3]) & 0xff; // to host byte order tmpiter = be32toh(tmpiter); return static_cast<int>(tmpiter); } // // Base64 // string to_base64(const unsigned char* data, size_t length) { static const char* composechar = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; unsigned char block[4]; string result; for(size_t readpos = 0; readpos < length; readpos += 3){ block[0] = (data[readpos] & 0xfc) >> 2; block[1] = ((data[readpos] & 0x03) << 4) | ((((readpos + 1) < length ? data[readpos + 1] : 0x00) & 0xf0) >> 4); block[2] = (readpos + 1) < length ? (((data[readpos + 1] & 0x0f) << 2) | ((((readpos + 2) < length ? data[readpos + 2] : 0x00) & 0xc0) >> 6)) : 0x40; block[3] = (readpos + 2) < length ? (data[readpos + 2] & 0x3f) : 0x40; result += composechar[block[0]]; result += composechar[block[1]]; result += composechar[block[2]]; result += composechar[block[3]]; } return result; } /* * VIM modelines * * vim:set ts=4 fenc=utf-8: */
30.8125
151
0.659229
[ "vector" ]
5be5820f6b21d47799725b60d466a24e45423e68
1,170
cpp
C++
Cpp/data_structure/union_find.cpp
NatsubiSogan/comp_library
9f06d947951db40e051bd506fd8722fb75c3688b
[ "Apache-2.0" ]
2
2021-09-05T13:17:01.000Z
2021-09-05T13:17:06.000Z
Cpp/data_structure/union_find.cpp
NatsubiSogan/comp_library
9f06d947951db40e051bd506fd8722fb75c3688b
[ "Apache-2.0" ]
null
null
null
Cpp/data_structure/union_find.cpp
NatsubiSogan/comp_library
9f06d947951db40e051bd506fd8722fb75c3688b
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <cassert> #include <vector> struct union_find { public: union_find(int size) { n = size; parent.resize(n); rank.resize(n); for (int i = 0; i < n; i++) { parent[i] = i; rank[i] = 1; } cnt = n; } int find(int x) { assert(0 <= x && x < n); if (parent[x] == x) return x; return parent[x] = find(parent[x]); } int unite(int x, int y) { assert(0 <= x && x < n); assert(0 <= y && y < n); int p = find(x), q = find(y); if (p == q) return p; if (p > q) std::swap(p, q); rank[p] += rank[q]; parent[q] = p; cnt -= 1; return p; } bool same(int x, int y) { assert(0 <= x && x < n); assert(0 <= y && y < n); return find(x) == find(y); } int size(int x) { assert(0 <= x && x < n); return rank[x]; } int count() { return cnt; } private: int n, cnt; std::vector<int> parent, rank; }; int main() { int n, q, t, u, v; std::cin >> n >> q; union_find uf(n); for (int i = 0; i < q ; i++) { std::cin >> t >> u >> v; if (t == 0) uf.unite(u, v); else { if (uf.same(u, v)) std::cout << 1 << std::endl; else std::cout << 0 << std::endl; } } }
17.205882
50
0.477778
[ "vector" ]
5bea96843b026cba4f7a582b31d15d03e6c50b3e
5,485
cpp
C++
DynacoeSrc/srcs/Dynacoe/Decoders/DecodeOGG.cpp
jcorks/Dynacoe
2d606620e8072d8ae76aa2ecdc31512ac90362d9
[ "Apache-2.0", "MIT", "Libpng", "FTL", "BSD-3-Clause" ]
1
2015-11-06T18:10:11.000Z
2015-11-06T18:10:11.000Z
DynacoeSrc/srcs/Dynacoe/Decoders/DecodeOGG.cpp
jcorks/Dynacoe
2d606620e8072d8ae76aa2ecdc31512ac90362d9
[ "Apache-2.0", "MIT", "Libpng", "FTL", "BSD-3-Clause" ]
8
2018-01-25T03:54:32.000Z
2018-09-17T01:55:35.000Z
DynacoeSrc/srcs/Dynacoe/Decoders/DecodeOGG.cpp
jcorks/Dynacoe
2d606620e8072d8ae76aa2ecdc31512ac90362d9
[ "Apache-2.0", "MIT", "Libpng", "FTL", "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2018, Johnathan Corkery. (jcorkery@umich.edu) All rights reserved. This file is part of the Dynacoe project (https://github.com/jcorks/Dynacoe) Dynacoe was released under the MIT License, as detailed below. 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 <Dynacoe/Decoders/DecodeOGG.h> #include <vorbis/vorbisfile.h> #include <Dynacoe/Modules/Sound.h> #include <Dynacoe/Util/Iobuffer.h> #include <Dynacoe/AudioBlock.h> using std::string; using std::vector; using namespace Dynacoe; using Dynacoe::InputBuffer; struct OVDataSource { const uint8_t * buffer; uint64_t size; uint64_t position; }; static size_t ov_memory_read_func(void * ptr, size_t size, size_t nmemb, void * datasource); //static int ov_memery_seek_func(void * datasource, ogg_int64_t offset, int whence); //static int ov_memory_close_func(void * datasource); //static int ov_memory_tell_func(void * datasource); struct _OggBlock { _OggBlock(){ size = 4096; data = new char [4096]; } ~_OggBlock() { delete[] data; } char * data; long size; }; Asset * DecodeOGG::operator()( const std::string & path, const std::string &, const uint8_t * buffer, uint64_t sizeB ) { // Uses vorbisfile library to decode OggVorbis_File oggFile; OVDataSource datasource = { buffer, sizeB, 0 }; int status = ov_open_callbacks( &datasource, &oggFile, NULL, 0, ov_callbacks{ ov_memory_read_func, nullptr, nullptr, nullptr } ); /* int status = ov_open_callbacks( fopen(path.c_str(), "rb"), &oggFile, NULL, 0, OV_CALLBACKS_DEFAULT ); */ if (status != 0) { Console::Error() << "[OGG] Couldn't read ogg " << path << " ->"; if (status == OV_EREAD) Console::Error() << "Media read error\n"; if (status == OV_ENOTVORBIS) Console::Error() << "File is not a Vorbis Ogg file.\n"; if (status == OV_EVERSION) Console::Error() << "Vorbis version mismatch\n"; if (status == OV_EBADHEADER) Console::Error() << "Invalid Vorbis header. File possibly corrupt...\n"; if (status == OV_EFAULT) Console::Error() << "Internal logic fault. SOMETHING REALLY BAD HAPPENED\n"; return NULL; } // next, make sure it is compatible with our format. vorbis_info * info = ov_info(&oggFile, -1); int numChannels = info->channels; int rate = info->rate; if (numChannels != 2) { Console::Warning() << "[OGG] Reading " << path.c_str() << " -> Number of channels is not 2. Attempting to compensate...\n"; } /* if (rate != DYNACOE_SAMPLE_RATE) { Console::Info() << "[OGG] Reading " << path.c_str() << " -> Sample rate is different than Dynacoe's. Expect altered playback speed."; } */ // now read vector<_OggBlock *> blockList; int section = 0; int totalSize = 0; while(true) { _OggBlock * nextBlock = new _OggBlock(); int size = ov_read(&oggFile, nextBlock->data, nextBlock->size, 0, 2, 1, &section); if (!size) { //Console::Info() << "Done reading..\n"; break; } nextBlock->size = size; blockList.push_back(nextBlock); totalSize += size; } AudioBlock * out = new AudioBlock(path); char * data = new char[totalSize]; uint32_t size = totalSize; int bufferPos = 0; for(int i = 0; i < (int) blockList.size(); ++i) { _OggBlock * block = blockList[i]; memcpy(data + bufferPos, block->data, block->size); bufferPos += block->size; delete block; } out->Append((AudioSample*)data, size/sizeof(AudioSample)); out->SetVolume(.9); delete[] data; //out->volume = 255; return out; } ///// statics size_t ov_memory_read_func(void * ptr, size_t size, size_t nmemb, void * datasource) { OVDataSource * data = (OVDataSource*)(datasource); uint64_t bytesLeft = data->size - data->position; size_t numRead = (bytesLeft < size*nmemb ? bytesLeft : size*nmemb); memcpy(ptr, data->buffer+data->position, numRead); data->position += numRead; return numRead; }
26.370192
113
0.618414
[ "vector" ]
5bf05d8404d3b732576275ad7062590b0f93fdbd
1,939
cpp
C++
trick_source/sim_services/RealtimeInjector/RtiExec.cpp
gilbertguoze/trick
f0537efb0fa3cb5c0c84e36b60f055c1d1c60d21
[ "NASA-1.3" ]
647
2015-05-07T16:08:16.000Z
2022-03-30T02:33:21.000Z
trick_source/sim_services/RealtimeInjector/RtiExec.cpp
gilbertguoze/trick
f0537efb0fa3cb5c0c84e36b60f055c1d1c60d21
[ "NASA-1.3" ]
995
2015-04-30T19:44:31.000Z
2022-03-31T20:14:44.000Z
trick_source/sim_services/RealtimeInjector/RtiExec.cpp
gilbertguoze/trick
f0537efb0fa3cb5c0c84e36b60f055c1d1c60d21
[ "NASA-1.3" ]
251
2015-05-15T09:24:34.000Z
2022-03-22T20:39:05.000Z
#include "trick/RtiExec.hh" #include "trick/message_proto.h" #include "trick/exec_proto.h" Trick::RtiExec::RtiExec() : frame_multiple(1) , frame_offset(0) , debug(false) { pthread_mutex_init(&list_mutex, NULL) ; } Trick::RtiExec::~RtiExec() {} /** @details -# lock the file_list mutex -# add the new list to the fire_list -# unlock the file_list mutex */ void Trick::RtiExec::AddToFireList( RtiList * rti_list ) { pthread_mutex_lock(&list_mutex) ; fire_list.push_back(rti_list) ; pthread_mutex_unlock(&list_mutex) ; } /** @details -# If the current frame is the correct frame multiple and offset -# If there is a list of injections in the fire_list -# Try to unlock the file_list mutex -# If successful, execute the fire_list and clear the list -# unlock the mutex */ int Trick::RtiExec::Exec () { long long curr_frame = exec_get_frame_count() ; curr_frame %= frame_multiple ; if ( curr_frame == frame_offset ) { if ( ! fire_list.empty() ) { // use trylock so we don't block if the mutex is in use. if ( pthread_mutex_trylock(&list_mutex) == 0 ) { std::vector < RtiList * >::iterator rlit ; for ( rlit = fire_list.begin() ; rlit != fire_list.end() ; rlit++ ) { (*rlit)->execute(debug) ; delete (*rlit) ; } fire_list.clear() ; pthread_mutex_unlock(&list_mutex) ; } } } return (0); } void Trick::RtiExec::SetDebug( bool on_off ) { debug = on_off ; } int Trick::RtiExec::SetFrameMultiple( unsigned int mult ) { frame_multiple = mult ; return 0 ; } int Trick::RtiExec::SetFrameOffset( unsigned int offset ) { if ( offset >= frame_multiple ) { message_publish(MSG_ERROR, "RTI frame offset must be less than frame_multiple\n") ; return -1 ; } frame_offset = offset ; return 0 ; }
26.202703
91
0.615781
[ "vector" ]
5bf8efa6ceeb67948bbf03b6bcaa55125fc79e9a
856
cpp
C++
_includes/leet051/leet051_2.cpp
mingdaz/leetcode
64f2e5ad0f0446d307e23e33a480bad5c9e51517
[ "MIT" ]
null
null
null
_includes/leet051/leet051_2.cpp
mingdaz/leetcode
64f2e5ad0f0446d307e23e33a480bad5c9e51517
[ "MIT" ]
8
2019-12-19T04:46:05.000Z
2022-02-26T03:45:22.000Z
_includes/leet051/leet051_2.cpp
mingdaz/leetcode
64f2e5ad0f0446d307e23e33a480bad5c9e51517
[ "MIT" ]
null
null
null
class Solution { public: vector<vector<string>> solveNQueens(int n) { vector<vector<string>> res; vector<string> path; backtracking(res,path,n,0,0,0); return res; } void backtracking(vector<vector<string>>& res,vector<string>& path,int n, int col,int diag1,int diag2){ int j = path.size(); if(j==n) res.push_back(path); else{ string tmp(n,'.'); for(int i=0;i<n;i++){ if(!(col&(1<<i)) && !(diag1&(1<<(i+j))) && !(diag2&(1<<(i-j+n-1))) ){ tmp[i] = 'Q'; path.push_back(tmp); backtracking(res,path,n,col|(1<<i),diag1|(1<<(i+j)),diag2|(1<<(i-j+n-1))); path.pop_back(); tmp[i] = '.'; } } } } };
32.923077
107
0.424065
[ "vector" ]
750277c2fecac631c34cc514ffec0341386e4dbc
40,616
cpp
C++
applications/projects/Modeler/lib/GraphModeler.cpp
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
applications/projects/Modeler/lib/GraphModeler.cpp
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
applications/projects/Modeler/lib/GraphModeler.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 General Public License as published by the Free * * Software Foundation; either version 2 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/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include "GraphModeler.h" #include "AddPreset.h" #include <sofa/core/ComponentLibrary.h> #include <sofa/core/objectmodel/ConfigurationSetting.h> #include <sofa/simulation/Simulation.h> #include <sofa/gui/qt/FileManagement.h> //static functions to manage opening/ saving of files #include <sofa/helper/system/FileRepository.h> #include <sofa/helper/system/SetDirectory.h> #include <SofaSimulationCommon/xml/ObjectElement.h> #include <SofaSimulationCommon/xml/AttributeElement.h> #include <SofaSimulationCommon/xml/DataElement.h> #include <SofaSimulationCommon/xml/XML.h> #include <sofa/simulation/XMLPrintVisitor.h> #include <QMenu> #include <QMessageBox> #include <QHeaderView> #include <QDrag> #include <QMimeData> using sofa::core::ComponentLibrary; namespace sofa { namespace gui { namespace qt { namespace { int numNode= 0; int numComponent= 0; } GraphModeler::GraphModeler(QWidget* parent, const char* name, Qt::WindowFlags f): QTreeWidget(parent), graphListener(NULL), propertyWidget(NULL) { this->setObjectName(name); setWindowFlags(f); graphListener = new GraphListenerQListView(this); //addColumn("Graph"); header()->hide(); setSortingEnabled(false); setSelectionMode(QAbstractItemView::ExtendedSelection); this->setItemsExpandable(true); historyManager=new GraphHistoryManager(this); //Make the connections connect(this, SIGNAL(operationPerformed(GraphHistoryManager::Operation&)), historyManager, SLOT(operationPerformed(GraphHistoryManager::Operation&))); connect(this, SIGNAL(graphClean()), historyManager, SLOT(graphClean())); connect(historyManager, SIGNAL(undoEnabled(bool)), this, SIGNAL(undoEnabled(bool))); connect(historyManager, SIGNAL(redoEnabled(bool)), this, SIGNAL(redoEnabled(bool))); connect(historyManager, SIGNAL(graphModified(bool)), this, SIGNAL(graphModified(bool))); connect(historyManager, SIGNAL(displayMessage(const std::string&)), this, SIGNAL(displayMessage(const std::string&))); connect(this, SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)), this, SLOT( doubleClick(QTreeWidgetItem *, int))); connect(this, SIGNAL(itemSelectionChanged()), this, SLOT( addInPropertyWidget())); //connect(this, SIGNAL(itemClicked(QTreeWidgetItem*,int)), this, SLOT( rightClick(QTreeWidgetItem *, int ))); this->setContextMenuPolicy(Qt::CustomContextMenu); connect(this, SIGNAL(customContextMenuRequested(const QPoint&) ), this, SLOT( rightClick(const QPoint& ))); DialogAdd=NULL; } GraphModeler::~GraphModeler() { delete historyManager; simulation::getSimulation()->unload(getRoot()); //delete getRoot(); graphRoot.reset(); delete graphListener; if (DialogAdd) delete DialogAdd; } /* void GraphModeler::mouseReleaseEvent(QMouseEvent* event) { if (event->button() == Qt::RightButton) { QTreeWidgetItem* item; item = dynamic_cast<QTreeWidgetItem *>(this->childAt(event->pos())); if(item) rightClick(item, 0 ); } } */ Node::SPtr GraphModeler::addNode(Node::SPtr parent, Node::SPtr child, bool saveHistory) { Node::SPtr lastRoot = getRoot(); if (!child) { std::ostringstream oss; oss << Node::shortName(child.get()) << numNode++; child = Node::create(oss.str() ); if (!parent) child->setName("Root"); } if (parent != NULL) { parent->addChild(child); if (saveHistory) { GraphHistoryManager::Operation adding(child, GraphHistoryManager::Operation::ADD_Node); adding.info=std::string("Adding Node ") + child->getClassName(); emit operationPerformed(adding); } } else { graphListener->addChild(NULL, child.get()); //Set up the root this->topLevelItem(0)->setExpanded(true); if (saveHistory) historyManager->graphClean(); graphRoot = child; } if (!parent && this->children().size() > 1) { deleteComponent(graphListener->items[lastRoot.get()], saveHistory); } return child; } BaseObject::SPtr GraphModeler::addComponent(Node::SPtr parent, const ClassEntry::SPtr entry, const std::string &templateName, bool saveHistory, bool displayWarning) { BaseObject::SPtr object=NULL; if (!parent || !entry) return object; std::string templateUsed = templateName; xml::ObjectElement description("Default", entry->className.c_str() ); if (!templateName.empty()) description.setAttribute("template", templateName.c_str()); Creator::SPtr c; if (entry->creatorMap.size() <= 1) c=entry->creatorMap.begin()->second; else { if (templateName.empty()) { if (entry->creatorMap.find(entry->defaultTemplate) == entry->creatorMap.end()) { std::cerr << "Error: No template specified" << std::endl; return object;} c=entry->creatorMap.find(entry->defaultTemplate)->second; templateUsed=entry->defaultTemplate; } else { c=entry->creatorMap.find(templateName)->second; } } if (c->canCreate(parent->getContext(), &description)) { core::objectmodel::BaseObjectDescription arg; std::ostringstream oss; oss << c->shortName(&description) << numComponent++; arg.setName(oss.str()); object = c->createInstance(parent->getContext(), &arg); if (saveHistory) { GraphHistoryManager::Operation adding(object, GraphHistoryManager::Operation::ADD_OBJECT); adding.info=std::string("Adding Object ") + object->getClassName(); emit operationPerformed(adding); } } else { BaseObject* reference = parent->getContext()->getMechanicalState(); if (displayWarning) { if (entry->className.find("Mapping") == std::string::npos) { if (!reference) { //we accept the mappings as no initialization of the object has been done const QString caption("Creation Impossible"); const QString warning=QString("No MechanicalState found in your Node ") + QString(parent->getName().c_str()); if ( QMessageBox::warning ( this, caption,warning, QMessageBox::Cancel | QMessageBox::Default | QMessageBox::Escape, QMessageBox::Ignore ) == QMessageBox::Cancel ) return object; } else { //TODO: try to give the possibility to change the template by the correct detected one const QString caption("Creation Impossible"); const QString warning= QString("Your component won't be created: \n \t * <") + QString(reference->getTemplateName().c_str()) + QString("> DOFs are used in the Node ") + QString(parent->getName().c_str()) + QString("\n\t * <") + QString(templateUsed.c_str()) + QString("> is the type of your ") + QString(entry->className.c_str()); if ( QMessageBox::warning ( this, caption,warning, QMessageBox::Cancel | QMessageBox::Default | QMessageBox::Escape, QMessageBox::Ignore ) == QMessageBox::Cancel ) return object; } } } object = c->createInstance(parent->getContext(), NULL); GraphHistoryManager::Operation adding(object, GraphHistoryManager::Operation::ADD_OBJECT); adding.info=std::string("Adding Object ") + object->getClassName(); emit operationPerformed(adding); // parent->addObject(object); } return object; } void GraphModeler::dropEvent(QDropEvent* event) { QString text; if (event->mimeData()->hasText()) text = event->mimeData()->text(); if (!text.isEmpty()) { std::string filename(text.toStdString()); std::string test = filename; test.resize(4); if (test == "file") { #ifdef WIN32 filename = filename.substr(8); //removing file:/// #else filename = filename.substr(7); //removing file:// #endif if (filename[filename.size()-1] == '\n') { filename.resize(filename.size()-1); filename[filename.size()-1]='\0'; } QString f(filename.c_str()); emit(fileOpen(f)); return; } } if (text == QString("ComponentCreation")) { BaseObject::SPtr newComponent = addComponent(getNode(event->pos()), lastSelectedComponent.second, lastSelectedComponent.first ); if (newComponent) { QTreeWidgetItem *after = graphListener->items[newComponent.get()]; std::ostringstream oss; oss << newComponent->getClassName() << " " << newComponent->getName(); after->setText(0, QString(oss.str().c_str())); QTreeWidgetItem *item = itemAt(event->pos()); if (getObject(item)) initItem(after, item); } } else { if (text == QString("Node")) { Node* node=getNode(event->pos()); if (node) { Node::SPtr newNode=addNode(node); if (newNode) { QTreeWidgetItem *after = graphListener->items[newNode.get()]; QTreeWidgetItem *item = itemAt(event->pos()); if (getObject(item)) initItem(after,item); } } } } } Base* GraphModeler::getComponent(QTreeWidgetItem *item) const { if (!item) return NULL; std::map<core::objectmodel::Base*, QTreeWidgetItem* >::iterator it; for (it = graphListener->items.begin(); it != graphListener->items.end(); ++it) { if (it->second == item) { return it->first; } } return NULL; } BaseObject *GraphModeler::getObject(QTreeWidgetItem *item) const { Base* component=getComponent(item); return dynamic_cast<BaseObject*>(component); } Node *GraphModeler::getNode(const QPoint &pos) const { QTreeWidgetItem *item = itemAt(pos); if (!item) return NULL; return getNode(item); } Node *GraphModeler::getNode(QTreeWidgetItem *item) const { if (!item) return NULL; sofa::core::objectmodel::Base *component=getComponent(item); if (Node *node=dynamic_cast<Node*>(component)) return node; else { item = item->parent(); component=getComponent(item); if (Node *node=dynamic_cast<Node*>(component)) return node; return NULL; } } QTreeWidgetItem *GraphModeler::getItem(Base *component) const { if (!component) return NULL; std::map<core::objectmodel::Base*, QTreeWidgetItem* >::iterator it; for (it = graphListener->items.begin(); it != graphListener->items.end(); ++it) { if (it->first == component) { return it->second; } } return NULL; } void GraphModeler::openModifyObject() { helper::vector<QTreeWidgetItem*> selection; getSelectedItems(selection); for (unsigned int i=0; i<selection.size(); ++i) openModifyObject(selection[i]); } void GraphModeler::openModifyObject(QTreeWidgetItem *item) { if (!item) return; Base* object = graphListener->findObject(item); BaseData* data = graphListener->findData(item); if( data == NULL && object == NULL) { assert(0); } ModifyObjectFlags dialogFlags = ModifyObjectFlags(); dialogFlags.setFlagsForModeler(); if (data) //user clicked on a data { current_Id_modifyDialog = data; } else { if(object) { current_Id_modifyDialog = object; if (object->toConfigurationSetting()) dialogFlags.HIDE_FLAG=true; } else { assert(0); } } //Unicity and identification of the windows std::map< void*, QDialog* >::iterator testWindow = map_modifyObjectWindow.find( current_Id_modifyDialog); if ( testWindow != map_modifyObjectWindow.end()) { //Object already being modified: no need to open a new window (*testWindow).second->raise(); return; } ModifyObject *dialogModify = new ModifyObject( current_Id_modifyDialog,item,this,dialogFlags,item->text(0).toStdString().c_str()); connect(dialogModify, SIGNAL(beginObjectModification(sofa::core::objectmodel::Base*)), historyManager, SLOT(beginModification(sofa::core::objectmodel::Base*))); connect(dialogModify, SIGNAL(endObjectModification(sofa::core::objectmodel::Base*)), historyManager, SLOT(endModification(sofa::core::objectmodel::Base*))); if(data) { dialogModify->createDialog(data); } if(object) { dialogModify->createDialog(object); } if(object && propertyWidget) propertyWidget->addComponent(object->getName().c_str(), object, item); map_modifyObjectWindow.insert( std::make_pair(current_Id_modifyDialog, dialogModify)); //If the item clicked is a node, we add it to the list of the element modified map_modifyDialogOpened.insert ( std::make_pair ( current_Id_modifyDialog, item ) ); connect ( dialogModify, SIGNAL( dialogClosed(void *) ) , this, SLOT( modifyUnlock(void *))); dialogModify->show(); dialogModify->raise(); } void GraphModeler::addInPropertyWidget() { helper::vector<QTreeWidgetItem*> selection; getSelectedItems(selection); bool clear = true; for (unsigned int i=0; i<selection.size(); ++i) { addInPropertyWidget(selection[i], clear); clear = false; } } void GraphModeler::addInPropertyWidget(QTreeWidgetItem *item, bool clear) { if(!item) return; Base* object = graphListener->findObject(item); if(object == NULL) return; if(propertyWidget) propertyWidget->addComponent(object->getName().c_str(), object, item, clear); } void GraphModeler::doubleClick(QTreeWidgetItem *item, int /* column */) { if (!item) return; item->setExpanded(!item->isExpanded()); openModifyObject(item); } void GraphModeler::leftClick(QTreeWidgetItem *item, const QPoint & /*point*/, int /*index*/) { if (!item) return; item->setExpanded(!item->isExpanded() ); addInPropertyWidget(item); } void GraphModeler::rightClick(const QPoint& p /*, int index */) { QTreeWidgetItem* item = this->itemAt(p); std::cout << p.x() << " " << p.y() << std::endl; if (!item) return; bool isNode=true; helper::vector<QTreeWidgetItem*> selection; getSelectedItems(selection); bool isSingleSelection= (selection.size() == 1); for (unsigned int i=0; i<selection.size(); ++i) { if (getObject(item)!=NULL) { isNode = false; break; } } bool isLoader = false; if (dynamic_cast<sofa::core::loader::BaseLoader*>(getComponent(item)) != NULL) isLoader = true; QMenu *contextMenu = new QMenu ( this ); contextMenu->setObjectName("ContextMenu"); if (isNode) { contextMenu->addAction("Collapse", this, SLOT( collapseNode())); contextMenu->addAction("Expand" , this, SLOT( expandNode())); if (isSingleSelection) { contextMenu->addSeparator(); contextMenu->addAction("Load" , this, SLOT( loadNode())); preset->setTitle(QString(tr( "Preset"))); contextMenu->addMenu(preset); } } contextMenu->addAction("Save" , this, SLOT( saveComponents())); contextMenu->addAction("Delete" , this, SLOT( deleteComponent())); contextMenu->addAction("Modify" , this, SLOT( openModifyObject())); contextMenu->addAction("GlobalModification" , this, SLOT( globalModification())); if (!isNode && !isLoader) contextMenu->addAction("Link" , this, SLOT( linkComponent())); contextMenu->exec(this->mapToGlobal(p)); } void GraphModeler::collapseNode() { helper::vector<QTreeWidgetItem*> selection; getSelectedItems(selection); for (unsigned int i=0; i<selection.size(); ++i) collapseNode(selection[i]); } void GraphModeler::collapseNode(QTreeWidgetItem* item) { if (!item) return; for(int i=0; i<item->childCount();i++) { QTreeWidgetItem* child = item->child(i); child->setExpanded( false ); } item->setExpanded( true ); } void GraphModeler::expandNode() { helper::vector<QTreeWidgetItem*> selection; getSelectedItems(selection); for (unsigned int i=0; i<selection.size(); ++i) expandNode(selection[i]); } void GraphModeler::expandNode(QTreeWidgetItem* item) { if (!item) return; item->setExpanded( true ); if ( item != NULL ) { for(int i=0; i<item->childCount();i++) { QTreeWidgetItem* child = item->child(i); child->setExpanded( true ); expandNode(item); } } } Node::SPtr GraphModeler::loadNode() { return loadNode(currentItem()); } Node::SPtr GraphModeler::loadNode(QTreeWidgetItem* item, std::string filename, bool saveHistory) { Node::SPtr node; if (!item) node=NULL; else node=getNode(item); if (filename.empty()) { QString s = getOpenFileName ( this, NULL,"Scenes (*.scn *.xml *.simu *.pscn)", "open file dialog", "Choose a file to open" ); if (s.length() >0) { filename = s.toStdString(); } else return NULL; } return loadNode(node,filename, saveHistory); } void GraphModeler::globalModification() { //Get all the components which can be modified helper::vector< QTreeWidgetItem* > selection; getSelectedItems(selection); helper::vector< QTreeWidgetItem* > hierarchySelection; for (size_t i=0; i<selection.size(); ++i) getComponentHierarchy(selection[i], hierarchySelection); helper::vector< Base* > allComponentsSelected; for (size_t i=0; i<hierarchySelection.size(); ++i) allComponentsSelected.push_back(getComponent(hierarchySelection[i])); sofa::gui::qt::GlobalModification *window=new sofa::gui::qt::GlobalModification(allComponentsSelected, historyManager); connect(window, SIGNAL(displayMessage(const std::string&)), this, SIGNAL(displayMessage(const std::string&))); window->show(); } void GraphModeler::linkComponent() { // get the selected component helper::vector< QTreeWidgetItem* > selection; getSelectedItems(selection); // a component must be selected if(selection.empty()) return; QTreeWidgetItem *fromItem = *selection.begin(); BaseObject *fromObject = getObject(fromItem); // the object must exist if(!fromObject) return; // the object must not be a loader if(dynamic_cast<sofa::core::loader::BaseLoader*>(fromObject)) return; // store the partial component hierarchy i.e we store the parent Nodes only std::vector<QTreeWidgetItem*> items; for(QTreeWidgetItem *item = fromItem->parent(); item != NULL; item = item->parent()) items.push_back(item); // create and show the LinkComponent dialog box sofa::gui::qt::LinkComponent *window=new sofa::gui::qt::LinkComponent(this, items, fromItem); if(window->loaderNumber() == 0) { window->close(); QMessageBox* messageBox = new QMessageBox(QMessageBox::Warning, "No loaders", "This tree branch does not contain any loader to link with."); messageBox->show(); return; } connect(window, SIGNAL(displayMessage(const std::string&)), this, SIGNAL(displayMessage(const std::string&))); window->show(); } Node::SPtr GraphModeler::buildNodeFromBaseElement(Node::SPtr node,xml::BaseElement *elem, bool saveHistory) { const bool displayWarning=true; Node::SPtr newNode = Node::create(""); //Configure the new Node configureElement(newNode.get(), elem); if (newNode->getName() == "Group") { //We can't use the parent node, as it is null if (!node) return NULL; //delete newNode; newNode = node; } else { // if (node) { //Add as a child addNode(node,newNode,saveHistory); } } typedef xml::BaseElement::child_iterator<> elem_iterator; for (elem_iterator it=elem->begin(); it != elem->end(); ++it) { if (std::string(it->getClass()) == std::string("Node")) { buildNodeFromBaseElement(newNode, it,true); } else { const ComponentLibrary *component = sofaLibrary->getComponent(it->getType()); //Configure the new Component const std::string templateAttribute("template"); std::string templatename; templatename = it->getAttribute(templateAttribute, ""); const ClassEntry::SPtr info = component->getEntry(); BaseObject::SPtr newComponent=addComponent(newNode, info, templatename, saveHistory,displayWarning); if (!newComponent) continue; configureElement(newComponent.get(), it); QTreeWidgetItem* itemGraph = graphListener->items[newComponent.get()]; std::string name=itemGraph->text(0).toStdString(); std::string::size_type pos = name.find(' '); if (pos != std::string::npos) name.resize(pos); name += " "; name+=newComponent->getName(); itemGraph->setText(0,name.c_str()); } } newNode->clearWarnings(); return newNode; } void GraphModeler::configureElement(Base* b, xml::BaseElement *elem) { //Init the Attributes of the object typedef xml::BaseElement::child_iterator<xml::AttributeElement> attr_iterator; typedef xml::BaseElement::child_iterator<xml::DataElement> data_iterator; for (attr_iterator itAttribute=elem->begin<xml::AttributeElement>(); itAttribute != elem->end<xml::AttributeElement>(); ++itAttribute) { for (data_iterator itData=itAttribute->begin<xml::DataElement>(); itData != itAttribute->end<xml::DataElement>(); ++itData) itData->initNode(); const std::string nameAttribute = itAttribute->getAttribute("type",""); const std::string valueAttribute = itAttribute->getValue(); elem->setAttribute(nameAttribute, valueAttribute.c_str()); } const sofa::core::objectmodel::Base::VecData& vecDatas=b->getDataFields(); for (unsigned int i=0; i<vecDatas.size(); ++i) { std::string result = elem->getAttribute(vecDatas[i]->getName(), ""); if (!result.empty()) { if (result[0] == '@') vecDatas[i]->setParent(result); else vecDatas[i]->read(result); } } } Node::SPtr GraphModeler::loadNode(Node::SPtr node, std::string path, bool saveHistory) { xml::BaseElement* newXML=NULL; newXML = xml::loadFromFile (path.c_str() ); if (newXML == NULL) return NULL; //----------------------------------------------------------------- //Add the content of a xml file Node::SPtr newNode = buildNodeFromBaseElement(node, newXML, saveHistory); //----------------------------------------------------------------- return newNode; } void GraphModeler::loadPreset(std::string presetName) { xml::BaseElement* newXML = xml::loadFromFile (presetName.c_str() ); if (newXML == NULL) return; xml::BaseElement::child_iterator<> it(newXML->begin()); bool elementPresent[3]= {false,false,false}; for (; it!=newXML->end(); ++it) { if (it->getName() == std::string("VisualNode") || it->getType() == std::string("OglModel")) elementPresent[1] = true; else if (it->getName() == std::string("CollisionNode")) elementPresent[2] = true; else if (it->getType() == std::string("MeshObjLoader") || it->getType() == std::string("SparseGrid")) elementPresent[0] = true; } if (!DialogAdd) { DialogAdd = new AddPreset(this); DialogAdd->setPath(sofa::helper::system::DataRepository.getFirstPath()); } DialogAdd->setRelativePath(sofa::helper::system::SetDirectory::GetParentDir(filenameXML.c_str())); DialogAdd->setElementPresent(elementPresent); DialogAdd->setPresetFile(presetName); Node *node=getNode(currentItem()); DialogAdd->setParentNode(node); DialogAdd->show(); DialogAdd->raise(); } void GraphModeler::loadPreset(Node *parent, std::string presetFile, std::string *filenames, std::string translation, std::string rotation, std::string scale) { xml::BaseElement* newXML=NULL; newXML = xml::loadFromFile (presetFile.c_str() ); if (newXML == NULL) return; //bool collisionNodeFound=false; //xml::BaseElement *meshMecha=NULL; xml::BaseElement::child_iterator<> it(newXML->begin()); for (; it!=newXML->end(); ++it) { if (it->getType() == std::string("MechanicalObject")) { updatePresetNode(*it, std::string(), translation, rotation, scale); } if (it->getType() == std::string("MeshObjLoader") || it->getType() == std::string("SparseGrid")) { updatePresetNode(*it, filenames[0], translation, rotation, scale); //meshMecha = it; } if (it->getType() == std::string("OglModel")) { updatePresetNode(*it, filenames[1], translation, rotation, scale); } if (it->getName() == std::string("VisualNode")) { xml::BaseElement* visualXML = it; xml::BaseElement::child_iterator<> it_visual(visualXML->begin()); for (; it_visual!=visualXML->end(); ++it_visual) { if (it_visual->getType() == std::string("OglModel")) { updatePresetNode(*it_visual, filenames[1], translation, rotation, scale); } } } if (it->getName() == std::string("CollisionNode")) { //collisionNodeFound=true; xml::BaseElement* collisionXML = it; xml::BaseElement::child_iterator<> it_collision(collisionXML->begin()); for (; it_collision!=collisionXML->end(); ++it_collision) { if (it_collision->getType() == std::string("MechanicalObject")) { updatePresetNode(*it_collision, std::string(), translation, rotation, scale); } if (it_collision->getType() == std::string("MeshObjLoader")) { updatePresetNode(*it_collision, filenames[2], translation, rotation, scale); } } } } if (!newXML->init()) std::cerr<< "Objects initialization failed.\n"; Node *presetNode = dynamic_cast<Node*> ( newXML->getObject() ); if (presetNode) addNode(parent,presetNode); } void GraphModeler::updatePresetNode(xml::BaseElement &elem, std::string meshFile, std::string translation, std::string rotation, std::string scale) { if (elem.presenceAttribute(std::string("filename"))) elem.setAttribute(std::string("filename"), meshFile.c_str()); if (elem.presenceAttribute(std::string("fileMesh"))) elem.setAttribute(std::string("fileMesh"), meshFile.c_str()); if (elem.presenceAttribute(std::string("fileTopology"))) elem.setAttribute(std::string("fileTopology"), meshFile.c_str()); if (elem.presenceAttribute(std::string("translation"))) elem.setAttribute(std::string("translation"), translation.c_str()); if (elem.presenceAttribute(std::string("rotation"))) elem.setAttribute(std::string("rotation"), rotation.c_str()); if (elem.presenceAttribute(std::string("scale3d"))) elem.setAttribute(std::string("scale3d"), scale.c_str()); } bool GraphModeler::getSaveFilename(std::string &filename) { QString s = sofa::gui::qt::getSaveFileName ( this, NULL, "Scenes (*.scn *.xml)", "save file dialog", "Choose where the scene will be saved" ); if ( s.length() >0 ) { std::string extension=sofa::helper::system::SetDirectory::GetExtension(s.toStdString().c_str()); if (extension.empty()) s+=QString(".scn"); filename = s.toStdString(); return true; } return false; } void GraphModeler::save(const std::string &filename) { Node *node = getNode(this->topLevelItem(0)); simulation::getSimulation()->exportXML(node, filename.c_str()); emit graphClean(); } void GraphModeler::saveComponents() { helper::vector<QTreeWidgetItem*> selection; getSelectedItems(selection); if (selection.empty()) return; std::string filename; if ( getSaveFilename(filename) ) saveComponents(selection, filename); } void GraphModeler::saveComponents(helper::vector<QTreeWidgetItem*> items, const std::string &file) { std::ofstream out(file.c_str()); simulation::XMLPrintVisitor print(sofa::core::ExecParams::defaultInstance() /* PARAMS FIRST */, out); print.setLevel(1); out << "<Node name=\"Group\">\n"; for (unsigned int i=0; i<items.size(); ++i) { if (BaseObject* object=getObject(items[i])) print.processBaseObject(object); else if (Node *node=getNode(items[i])) print.execute(node); } out << "</Node>\n"; } void GraphModeler::clearGraph(bool saveHistory) { deleteComponent(this->topLevelItem(0), saveHistory); } void GraphModeler::deleteComponent(QTreeWidgetItem* item, bool saveHistory) { if (!item) return; Node *parent = getNode(item->parent()); bool isNode = getObject(item)==NULL; if (!isNode && isObjectErasable(getObject(item))) { BaseObject* object = getObject(item); if (saveHistory) { GraphHistoryManager::Operation removal(getObject(item),GraphHistoryManager::Operation::DELETE_OBJECT); removal.parent=getNode(item); removal.above=getComponentAbove(item); removal.info=std::string("Removing Object ") + object->getClassName(); emit operationPerformed(removal); } getNode(item)->removeObject(getObject(item)); } else { if (!isNodeErasable(getNode(item))) return; Node *node = getNode(item); if (saveHistory) { GraphHistoryManager::Operation removal(node,GraphHistoryManager::Operation::DELETE_Node); removal.parent = parent; removal.above=getComponentAbove(item); removal.info=std::string("Removing Node ") + node->getClassName(); emit operationPerformed(removal); } if (!parent) graphListener->removeChild(parent, node); else parent->removeChild((Node*)node); if (!parent && this->children().size() == 0) addNode(NULL); } } void GraphModeler::changeComponentDataValue(const std::string &name, const std::string &value, Base* component) const { if (!component) return; historyManager->beginModification(component); const std::vector< BaseData* > &data=component->findGlobalField(name); if (data.empty()) //this data is not present in the current component return; std::string v(value); for (unsigned int i=0; i<data.size(); ++i) data[i]->read(v); historyManager->endModification(component); } Base *GraphModeler::getComponentAbove(QTreeWidgetItem *item) { if (!item) return NULL; QTreeWidgetItem* itemAbove = this->itemAbove(item); while (itemAbove && itemAbove->parent() != item->parent() ) { itemAbove = itemAbove->parent(); } Base *result=getObject(itemAbove); if (!result) result=getNode(itemAbove); return result; } void GraphModeler::deleteComponent() { helper::vector<QTreeWidgetItem*> selection; getSelectedItems(selection); for (unsigned int i=0; i<selection.size(); ++i) deleteComponent(selection[i]); } void GraphModeler::modifyUnlock ( void *Id ) { map_modifyDialogOpened.erase( Id ); map_modifyObjectWindow.erase( Id ); } void GraphModeler::keyPressEvent ( QKeyEvent * e ) { switch ( e->key() ) { case Qt::Key_Delete : { deleteComponent(); break; } case Qt::Key_Return : case Qt::Key_Enter : { openModifyObject(); break; } default: { QTreeWidget::keyPressEvent(e); break; } } } /*****************************************************************************************************************/ // Test if a node can be erased in the graph : the condition is that none of its children has a menu modify opened bool GraphModeler::isNodeErasable ( BaseNode* node) { QTreeWidgetItem* item = graphListener->items[node]; if(item == NULL) { return false; } // check if there is already a dialog opened for that item in the graph std::map< void*, QTreeWidgetItem*>::iterator it; for (it = map_modifyDialogOpened.begin(); it != map_modifyDialogOpened.end(); ++it) { if (it->second == item) return false; } //check the item childs for(int i=0 ; i<item->childCount() ; i++) { QTreeWidgetItem *child = item->child(i); for( it = map_modifyDialogOpened.begin(); it != map_modifyDialogOpened.end(); ++it) { if( it->second == child) return false; } } return true; } bool GraphModeler::isObjectErasable ( core::objectmodel::Base* element ) { QTreeWidgetItem* item = graphListener->items[element]; std::map< void*, QTreeWidgetItem*>::iterator it; for (it = map_modifyDialogOpened.begin(); it != map_modifyDialogOpened.end(); ++it) { if (it->second == item) return false; } return true; } void GraphModeler::initItem(QTreeWidgetItem *item, QTreeWidgetItem *above) { moveItem(item, above); moveItem(above,item); } void GraphModeler::moveItem(QTreeWidgetItem *item, QTreeWidgetItem *above) { if (item) { if (above) { //item->moveItem(above); item->parent()->removeChild(item); QTreeWidgetItem *parent = above->parent(); parent->insertChild(parent->indexOfChild(above), item ); //Move the object in the Sofa Node. if (above && getObject(item)) { Node *n=getNode(item); Node::ObjectIterator A=n->object.end(); Node::ObjectIterator B=n->object.end(); BaseObject* objectA=getObject(above); BaseObject* objectB=getObject(item); bool inversion=false; //Find the two objects in the Sequence of the Node for (Node::ObjectIterator it=n->object.begin(); it!=n->object.end(); ++it) { if( *it == objectA) { A=it; if (B!=n->object.end()) inversion=true; } else if ( *it == objectB) B=it; } //One has not been found: should not happen if (A==n->object.end() || B==n->object.end()) return; //Invert the elements Node::ObjectIterator it; if (inversion) n->object.swap(A,B); else { for (it=B; it!=A+1; --it) n->object.swap(it,it-1); } } } else { //Object if (getObject(item)) { QTreeWidgetItem *nodeQt = graphListener->items[getNode(item)]; QTreeWidgetItem *firstComp=nodeQt->child(0); if (firstComp != item) initItem(item, firstComp); } //Node else { QTreeWidgetItem *nodeQt = graphListener->items[getNode(item->parent())]; QTreeWidgetItem *firstComp=nodeQt->child(0); if (firstComp != item) initItem(item, firstComp); } } } } /// Drag Management void GraphModeler::dragEnterEvent( QDragEnterEvent* event) { event->accept(event->answerRect()); } /// Drag Management void GraphModeler::dragMoveEvent( QDragMoveEvent* event) { QString text; if (event->mimeData()->hasText()) text = event->mimeData()->text(); if (!text.isEmpty()) { std::string filename(text.toStdString()); std::string test = filename; test.resize(4); if (test == "file") {event->accept(event->answerRect());} } else { if ( getNode(event->pos())) event->accept(event->answerRect()); else event->ignore(event->answerRect()); } } void GraphModeler::closeDialogs() { std::map< void*, QDialog* >::iterator it; ; for (it=map_modifyObjectWindow.begin(); it!=map_modifyObjectWindow.end(); ++it) { delete it->second; } map_modifyObjectWindow.clear(); } /*****************************************************************************************************************/ //History of operations management //TODO: not use the factory to create the elements! bool GraphModeler::cut(std::string path) { bool resultCopy=copy(path); if (resultCopy) { deleteComponent(); return true; } return false; } bool GraphModeler::copy(std::string path) { helper::vector< QTreeWidgetItem*> items; getSelectedItems(items); if (!items.empty()) { saveComponents(items,path); return true; } return false; } bool GraphModeler::paste(std::string path) { helper::vector< QTreeWidgetItem*> items; getSelectedItems(items); if (!items.empty()) { //Get the last item of the node: the new items will be inserted AFTER this last item. QTreeWidgetItem *last=items.front(); //while(last->nextSibling()) last=last->nextSibling(); last = last->child(last->childCount()-1); Node *node = getNode(items.front()); //Load the paste buffer loadNode(node, path); QTreeWidgetItem *pasteItem=items.front(); //Find all the QListViewItem inserted helper::vector< QTreeWidgetItem* > insertedItems; // QTreeWidgetItem *insertedItem=last; for(int i=0 ; i<last->parent()->childCount() ; i++) { QTreeWidgetItem *insertedItem = last->parent()->child(i); if(insertedItem != last) insertedItems.push_back(insertedItem); } //Initialize their position in the node for (unsigned int i=0; i<insertedItems.size(); ++i) initItem(insertedItems[i], pasteItem); } return !items.empty(); } } } }
32.082148
183
0.597917
[ "object", "vector" ]
7504d37a5dc13707cf2960f276a477ff9829f1c5
5,540
cpp
C++
VFS/RenderPass/Clipmap/CopyAlpha.cpp
Snowapril/VFS
a366f519c1382cfa2669b56346b67737513d6099
[ "MIT" ]
2
2022-02-14T16:34:39.000Z
2022-02-25T06:11:42.000Z
VFS/RenderPass/Clipmap/CopyAlpha.cpp
Snowapril/vk_voxel_cone_tracing
a366f519c1382cfa2669b56346b67737513d6099
[ "MIT" ]
null
null
null
VFS/RenderPass/Clipmap/CopyAlpha.cpp
Snowapril/vk_voxel_cone_tracing
a366f519c1382cfa2669b56346b67737513d6099
[ "MIT" ]
null
null
null
// Author : Jihong Shin (snowapril) #include <pch.h> #include <RenderPass/Clipmap/CopyAlpha.h> #include <VulkanFramework/Device.h> #include <VulkanFramework/Descriptors/DescriptorPool.h> #include <VulkanFramework/Descriptors/DescriptorSet.h> #include <VulkanFramework/Descriptors/DescriptorSetLayout.h> #include <VulkanFramework/Pipelines/ComputePipeline.h> #include <VulkanFramework/Pipelines/PipelineLayout.h> #include <VulkanFramework/Pipelines/PipelineConfig.h> #include <VulkanFramework/Commands/CommandPool.h> #include <VulkanFramework/Images/Image.h> #include <VulkanFramework/Images/ImageView.h> #include <VulkanFramework/Images/Sampler.h> #include <VulkanFramework/Sync/Fence.h> #include <VulkanFramework/Queue.h> #include <VulkanFramework/Buffers/Buffer.h> namespace vfs { CopyAlpha::CopyAlpha(DevicePtr device) : _device(device) { // Do nothing } CopyAlpha::~CopyAlpha() { destroyCopyAlpha(); } void CopyAlpha::destroyCopyAlpha(void) { _descSet.reset(); _pipeline.reset(); _pipelineLayout.reset(); _descLayout.reset(); _descPool.reset(); _device.reset(); } CopyAlpha& CopyAlpha::createDescriptors(const ImageView* srcImageView, const ImageView* dstImageView, const Sampler* imageSampler) { std::vector<VkDescriptorPoolSize> poolSizes = { { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1}, { VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1}, }; _descPool = std::make_shared<DescriptorPool>(_device, poolSizes, 1, 0); _descLayout = std::make_shared<DescriptorSetLayout>(_device); _descLayout->addBinding(VK_SHADER_STAGE_COMPUTE_BIT, 0, 1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0); _descLayout->addBinding(VK_SHADER_STAGE_COMPUTE_BIT, 1, 1, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 0); _descLayout->createDescriptorSetLayout(0); _descSet = std::make_shared<DescriptorSet>(_device, _descPool, _descLayout, 1); VkDescriptorImageInfo srcImageInfo = {}; srcImageInfo.imageView = srcImageView->getImageViewHandle(); srcImageInfo.sampler = imageSampler->getSamplerHandle(); srcImageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; _descSet->updateImage({ srcImageInfo }, 0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER); VkDescriptorImageInfo dstImageInfo = {}; dstImageInfo.imageView = dstImageView->getImageViewHandle(); dstImageInfo.sampler = imageSampler->getSamplerHandle(); dstImageInfo.imageLayout = VK_IMAGE_LAYOUT_GENERAL; _descSet->updateImage({ dstImageInfo }, 1, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE); return *this; } CopyAlpha& CopyAlpha::createPipeline(void) { assert(_descLayout != nullptr); // snowapril : Descriptor set layout must be initialized first _pipelineLayout = std::make_shared<PipelineLayout>(); _pipelineLayout->initialize(_device, { _descLayout }, { { VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(CopyAlphaDesc) } }); PipelineConfig config; config.pipelineLayout = _pipelineLayout->getLayoutHandle(); _pipeline = std::make_shared<ComputePipeline>(); _pipeline->initialize(_device); _pipeline->attachShaderModule(VK_SHADER_STAGE_COMPUTE_BIT, "Shaders/copyAlphaImage.comp.spv", nullptr); _pipeline->createPipeline(&config); return *this; } void CopyAlpha::cmdImageCopyAlpha(CommandBuffer cmdBuffer, const Image* dstImage, const Image* srcImage, const uint32_t clipLevel) { assert(clipLevel < DEFAULT_CLIP_REGION_COUNT); CopyAlphaDesc copyAlphaDesc = {}; copyAlphaDesc.clipLevel = static_cast<int32_t>(clipLevel); copyAlphaDesc.clipmapResolution = static_cast<int32_t>(DEFAULT_VOXEL_RESOLUTION); copyAlphaDesc.faceCount = static_cast<int32_t>(DEFAULT_VOXEL_FACE_COUNT); cmdBuffer.pushConstants(_pipelineLayout->getLayoutHandle(), VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(CopyAlphaDesc), &copyAlphaDesc); VkImageMemoryBarrier srcImageBarrier = srcImage->generateMemoryBarrier( 0, VK_ACCESS_SHADER_READ_BIT, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED ); VkImageMemoryBarrier dstImageBarrier = dstImage->generateMemoryBarrier( 0, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED ); cmdBuffer.pipelineBarrier(VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, {}, {}, { srcImageBarrier, dstImageBarrier }); cmdBuffer.bindPipeline(_pipeline); cmdBuffer.bindDescriptorSets(VK_PIPELINE_BIND_POINT_COMPUTE, _pipelineLayout->getLayoutHandle(), 0, { _descSet }, {}); const uint32_t groupCount = DEFAULT_VOXEL_RESOLUTION >> 3; cmdBuffer.dispatch(groupCount, groupCount, groupCount); srcImageBarrier = srcImage->generateMemoryBarrier( VK_ACCESS_SHADER_READ_BIT, VK_ACCESS_SHADER_READ_BIT, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED ); dstImageBarrier = dstImage->generateMemoryBarrier( VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED ); cmdBuffer.pipelineBarrier(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, {}, {}, { srcImageBarrier, dstImageBarrier }); } };
37.687075
119
0.792419
[ "vector" ]
7505668e78ec6f000a7ecb78da72bf5de890913b
13,128
cc
C++
precompiled/serialize.cc
asoffer/icarus
5c9af79d1a39e14d95da1adacbdd7392908eedc5
[ "Apache-2.0" ]
null
null
null
precompiled/serialize.cc
asoffer/icarus
5c9af79d1a39e14d95da1adacbdd7392908eedc5
[ "Apache-2.0" ]
null
null
null
precompiled/serialize.cc
asoffer/icarus
5c9af79d1a39e14d95da1adacbdd7392908eedc5
[ "Apache-2.0" ]
null
null
null
#include "precompiled/serialize.h" #include "base/macros.h" #include "ir/value/char.h" #include "type/array.h" #include "type/enum.h" #include "type/flags.h" #include "type/function.h" #include "type/generic.h" #include "type/generic_function.h" #include "type/opaque.h" #include "type/pointer.h" #include "type/primitive.h" #include "type/slice.h" #include "type/struct.h" #include "type/type.h" namespace precompiled { namespace { struct ValueSerializer { using signature = void(ir::CompleteResultRef); explicit ValueSerializer(type::TypeSystem const* system, Value* value) : system_(*ASSERT_NOT_NULL(system)), value_(*ASSERT_NOT_NULL(value)) {} void operator()(type::Type t, ir::CompleteResultRef ref) { t.visit<ValueSerializer>(*this, ref); } void operator()(auto const* t, ir::CompleteResultRef ref) { NOT_YET(t->to_string()); } void operator()(type::Function const* t, ir::CompleteResultRef ref) { ir::Fn fn = ref.get<ir::Fn>(); auto& proto_func = *value_.mutable_function(); proto_func.set_module_id(fn.module().value()); proto_func.set_function_id(fn.local().value()); } void operator()(type::Primitive const* p, ir::CompleteResultRef ref) { switch (p->kind()) { case type::Primitive::Kind::Bool: value_.set_boolean(ref.get<bool>()); break; case type::Primitive::Kind::Char: value_.set_unsigned_integer(ref.get<ir::Char>().as_type<uint8_t>()); break; case type::Primitive::Kind::I8: value_.set_signed_integer(ref.get<int8_t>()); break; case type::Primitive::Kind::I16: value_.set_signed_integer(ref.get<int16_t>()); break; case type::Primitive::Kind::I32: value_.set_signed_integer(ref.get<int32_t>()); break; case type::Primitive::Kind::I64: value_.set_signed_integer(ref.get<int64_t>()); break; case type::Primitive::Kind::U8: value_.set_unsigned_integer(ref.get<uint8_t>()); break; case type::Primitive::Kind::U16: value_.set_unsigned_integer(ref.get<uint16_t>()); break; case type::Primitive::Kind::U32: value_.set_unsigned_integer(ref.get<uint32_t>()); break; case type::Primitive::Kind::U64: value_.set_unsigned_integer(ref.get<uint64_t>()); break; case type::Primitive::Kind::F32: value_.set_real(ref.get<float>()); break; case type::Primitive::Kind::F64: value_.set_real(ref.get<double>()); break; case type::Primitive::Kind::Byte: value_.set_unsigned_integer(static_cast<uint8_t>(ref.get<std::byte>())); break; case type::Primitive::Kind::Type_: { size_t index = system_.index(ref.get<type::Type>()); ASSERT(index != std::numeric_limits<size_t>::max()); value_.set_type(index); } break; default: NOT_YET((int)p->kind()); } } private: type::TypeSystem const& system_; Value& value_; }; struct ValueDeserializer { using signature = void(ir::CompleteResultBuffer& buffer); explicit ValueDeserializer( module::ModuleTable const* module_table, google::protobuf::Map<uint32_t, std::string> const* module_map, type::TypeSystem const* system, Value const* value) : module_table_(*ASSERT_NOT_NULL(module_table)), module_map_(*ASSERT_NOT_NULL(module_map)), system_(*ASSERT_NOT_NULL(system)), value_(*ASSERT_NOT_NULL(value)) {} void operator()(type::Type t, ir::CompleteResultBuffer& buffer) { return t.visit<ValueDeserializer>(*this, buffer); } void operator()(auto const* t, ir::CompleteResultBuffer& buffer) { NOT_YET(); } void operator()(type::Function const*, ir::CompleteResultBuffer& buffer) { auto const& fn = value_.function(); auto iter = module_map_.find(fn.module_id()); ASSERT(iter != module_map_.end()); auto [id, m] = module_table_.module(iter->second); ASSERT(m != nullptr); ASSERT(id != ir::ModuleId::Invalid()); buffer.append(ir::Fn(id, ir::LocalFnId(fn.function_id()))); } void operator()(type::Primitive const* p, ir::CompleteResultBuffer& buffer) { switch (p->kind()) { case type::Primitive::Kind::Bool: buffer.append(value_.boolean()); break; case type::Primitive::Kind::Char: { ASSERT(value_.unsigned_integer() <= std::numeric_limits<uint8_t>::max()); buffer.append( ir::Char(static_cast<uint8_t>(value_.unsigned_integer()))); } break; case type::Primitive::Kind::I8: { ASSERT(value_.signed_integer() <= std::numeric_limits<int8_t>::max()); buffer.append(static_cast<int8_t>(value_.signed_integer())); } break; case type::Primitive::Kind::I16: { ASSERT(value_.signed_integer() <= std::numeric_limits<int16_t>::max()); buffer.append(static_cast<int16_t>(value_.signed_integer())); } break; case type::Primitive::Kind::I32: { ASSERT(value_.signed_integer() <= std::numeric_limits<int32_t>::max()); buffer.append(static_cast<int32_t>(value_.signed_integer())); } break; case type::Primitive::Kind::I64: { ASSERT(value_.signed_integer() <= std::numeric_limits<int64_t>::max()); buffer.append(static_cast<int64_t>(value_.signed_integer())); } break; case type::Primitive::Kind::U8: { ASSERT(value_.unsigned_integer() <= std::numeric_limits<uint8_t>::max()); buffer.append(static_cast<uint8_t>(value_.unsigned_integer())); } break; case type::Primitive::Kind::U16: { ASSERT(value_.unsigned_integer() <= std::numeric_limits<uint16_t>::max()); buffer.append(static_cast<uint16_t>(value_.unsigned_integer())); } break; case type::Primitive::Kind::U32: { ASSERT(value_.unsigned_integer() >= 0); buffer.append(static_cast<uint32_t>(value_.unsigned_integer())); } break; case type::Primitive::Kind::U64: { ASSERT(value_.unsigned_integer() <= std::numeric_limits<uint64_t>::max()); buffer.append(static_cast<uint64_t>(value_.unsigned_integer())); } break; case type::Primitive::Kind::F32: { buffer.append(static_cast<float>(value_.real())); } break; case type::Primitive::Kind::F64: { buffer.append(static_cast<double>(value_.real())); } break; case type::Primitive::Kind::Byte: { ASSERT(value_.unsigned_integer() <= std::numeric_limits<uint8_t>::max()); buffer.append( std::byte(static_cast<uint8_t>(value_.unsigned_integer()))); } break; case type::Primitive::Kind::Type_: { buffer.append(system_.from_index(value_.type())); } break; default: NOT_YET(); } } private: module::ModuleTable const& module_table_; google::protobuf::Map<uint32_t, std::string> const& module_map_; type::TypeSystem const& system_; Value const& value_; }; struct TypeSystemSerializingVisitor { using signature = void(TypeDefinition& out); explicit TypeSystemSerializingVisitor(type::TypeSystem const* system) : system_(*ASSERT_NOT_NULL(system)) {} void operator()(type::Type t, TypeDefinition& out) { t.visit(*this, out); } void operator()(auto const* t, TypeDefinition& out) { Visit(t, out); } private: void Visit(type::Primitive const* p, TypeDefinition& out) { out.set_primitive(static_cast<int>(p->kind())); } void Visit(type::Pointer const* p, TypeDefinition& out) { out.set_pointer(system_.index(p->pointee())); } void Visit(type::BufferPointer const* p, TypeDefinition& out) { out.set_buffer_pointer(system_.index(p->pointee())); } void Visit(type::Function const* f, TypeDefinition& out) { auto& fn = *out.mutable_function(); fn.set_eager(f->eager()); for (auto const& param : f->parameters()) { auto& p = *fn.add_parameter(); p.set_name(param.name); p.set_type(system_.index(param.value.type())); p.set_flags((param.flags.value() << uint8_t{8}) | param.value.quals().value()); } for (type::Type t : f->return_types()) { fn.add_return_type(system_.index(t)); } } void Visit(type::Slice const* s, TypeDefinition& out) { out.set_slice(system_.index(s->data_type())); } void Visit(type::Opaque const* o, TypeDefinition& out) { auto& opaque = *out.mutable_opaque(); opaque.set_module_id(o->defining_module().value()); opaque.set_numeric_id(o->numeric_id()); } void Visit(type::Enum const* e, TypeDefinition& out) { auto value_range = e->values(); auto& t = *out.mutable_enum_type(); t.set_module_id(e->defining_module().value()); t.mutable_values()->insert(value_range.begin(), value_range.end()); } void Visit(type::Flags const* f, TypeDefinition& out) { auto value_range = f->values(); auto& t = *out.mutable_flags_type(); t.set_module_id(f->defining_module().value()); t.mutable_values()->insert(value_range.begin(), value_range.end()); } void Visit(auto const* s, TypeDefinition& out) { NOT_YET(s->to_string()); } type::TypeSystem const& system_; }; } // namespace void SerializeValue(type::TypeSystem const& system, type::Type t, ir::CompleteResultRef ref, Value& value) { value.set_type_id(system.index(t)); ValueSerializer vs(&system, &value); vs(t, ref); } ir::CompleteResultBuffer DeserializeValue( module::ModuleTable const& module_table, google::protobuf::Map<uint32_t, std::string> const& module_map, type::TypeSystem const& system, Value const& value) { ir::CompleteResultBuffer result; ValueDeserializer vd(&module_table, &module_map, &system, &value); vd(system.from_index(value.type_id()), result); return result; } SymbolInformation ToProto(type::TypeSystem const& system, module::Module::SymbolInformation const& info) { SymbolInformation s; s.set_qualifiers(info.qualified_type.quals().value()); s.set_visible(info.visibility == module::Module::Visibility::Exported); SerializeValue(type::GlobalTypeSystem, info.qualified_type.type(), info.value[0], *s.mutable_value()); return s; } TypeSystem ToProto(type::TypeSystem const& system) { TypeSystem proto; TypeSystemSerializingVisitor v(&system); for (type::Type t : system.types()) { v(t, *proto.add_type()); } return proto; } void FromProto(TypeSystem const& proto, type::TypeSystem& system) { for (auto const& t : proto.type()) { switch (t.type_case()) { case TypeDefinition::kPrimitive: system.insert( MakePrimitive(static_cast<type::Primitive::Kind>(t.primitive()))); break; case TypeDefinition::kPointer: system.insert(Ptr(system.from_index(t.pointer()))); break; case TypeDefinition::kBufferPointer: system.insert(BufPtr(system.from_index(t.buffer_pointer()))); break; case TypeDefinition::kFunction: { core::Parameters<type::QualType> parameters; for (auto const& p : t.function().parameter()) { parameters.append( p.name(), type::QualType(system.from_index(p.type()), type::Quals::FromValue(p.flags() & 0xff)), core::ParameterFlags::FromValue(p.flags() >> uint8_t{8})); } std::vector<type::Type> return_types; return_types.reserve(t.function().return_type().size()); for (int64_t n : t.function().return_type()) { return_types.push_back(system.from_index(n)); } auto* make_func = (t.function().eager() ? type::EagerFunc : type::Func); system.insert( make_func(std::move(parameters), std::move(return_types))); } break; case TypeDefinition::kSlice: system.insert(Slc(system.from_index(t.slice()))); break; case TypeDefinition::kOpaque: NOT_YET(); break; case TypeDefinition::kEnumType: { auto const& proto_enum = t.enum_type(); auto* e = type::Allocate<type::Enum>(ir::ModuleId(proto_enum.module_id())); auto [index, inserted] = system.insert(e); ASSERT(inserted == true); absl::flat_hash_map<std::string, type::Enum::underlying_type> members( proto_enum.values().begin(), proto_enum.values().end()); e->SetMembers(std::move(members)); e->complete(); } break; case TypeDefinition::kFlagsType: { auto const& proto_flags = t.flags_type(); auto* f = type::Allocate<type::Flags>(ir::ModuleId(proto_flags.module_id())); auto [index, inserted] = system.insert(f); ASSERT(inserted == true); absl::flat_hash_map<std::string, type::Flags::underlying_type> members( proto_flags.values().begin(), proto_flags.values().end()); f->SetMembers(std::move(members)); f->complete(); } break; case TypeDefinition::TYPE_NOT_SET: UNREACHABLE(); } } } } // namespace precompiled
36.568245
80
0.638178
[ "vector" ]
7507d99b07f311b11597d240a0993c05b3e2626f
2,058
hh
C++
include/urbi/object/event-handler.hh
jcbaillie/urbi
fb17359b2838cdf8d3c0858abb141e167a9d4bdb
[ "BSD-3-Clause" ]
16
2016-05-10T05:50:58.000Z
2021-10-05T22:16:13.000Z
include/urbi/object/event-handler.hh
jcbaillie/urbi
fb17359b2838cdf8d3c0858abb141e167a9d4bdb
[ "BSD-3-Clause" ]
7
2016-09-05T10:08:33.000Z
2019-02-13T10:51:07.000Z
include/urbi/object/event-handler.hh
jcbaillie/urbi
fb17359b2838cdf8d3c0858abb141e167a9d4bdb
[ "BSD-3-Clause" ]
15
2015-01-28T20:27:02.000Z
2021-09-28T19:26:08.000Z
/* * Copyright (C) 2010-2012, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ #ifndef URBI_OBJECT_EVENT_INSTANCE_HH # define URBI_OBJECT_EVENT_INSTANCE_HH # include <urbi/object/object.hh> # include <urbi/object/event.hh> namespace urbi { namespace object { class URBI_SDK_API EventHandler: public CxxObject { URBI_CXX_OBJECT(EventHandler, CxxObject); friend class Event; public: EventHandler(rEventHandler model); EventHandler(rEvent parent, rList payload); /// Effective trigger action. void trigger(bool detach); /// Event stopping function. /// Same synchronicity as trigger function. void stop(); rEvent source(); rList payload(); private: typedef Event::callback_type callback_type; typedef Event::callbacks_type callbacks_type; /// Leave callbacks to trigger on stop. struct stop_job_type { stop_job_type(rSubscription s, objects_type& a, bool d) : subscription(s), args(a), detach(d) {} rSubscription subscription; objects_type args; // FIXME: not used. bool detach; }; typedef std::vector<stop_job_type> stop_jobs_type; /// Listener jobs execution function. void trigger_job(const rSubscription& actions, const objects_type& args, bool detach); /// Register the stop job. EventHandler& operator<<(const stop_job_type& stop_job); /// The parent Event of this handler. rEvent source_; /// The payload given to handler constructor. rList payload_; /// Copy of Boolean given to trigger, used for stop synchronicity. bool detach_; stop_jobs_type stop_jobs_; friend class Subscription; }; } } # include <urbi/object/event-handler.hxx> #endif
26.727273
73
0.661808
[ "object", "vector", "model" ]
750a5402b258deeb60fde35e7d20ec2a4dc58a9a
4,278
cpp
C++
demo/cpp/rapid.cpp
berak/opencv_smallfry
fd8f64980dff0527523791984d6cb3dfcd2bc9bc
[ "BSD-3-Clause" ]
57
2015-02-16T06:43:24.000Z
2022-03-16T06:21:36.000Z
demo/cpp/rapid.cpp
berak/opencv_smallfry
fd8f64980dff0527523791984d6cb3dfcd2bc9bc
[ "BSD-3-Clause" ]
4
2016-03-08T09:51:09.000Z
2021-03-29T10:18:55.000Z
demo/cpp/rapid.cpp
berak/opencv_smallfry
fd8f64980dff0527523791984d6cb3dfcd2bc9bc
[ "BSD-3-Clause" ]
27
2015-03-28T19:55:34.000Z
2022-01-09T15:03:15.000Z
#include "opencv2/core.hpp" #include "opencv2/calib3d.hpp" #include "opencv2/highgui.hpp" #include "opencv2/rapid.hpp" using namespace cv; #include <iostream> using namespace std; int main() { // a unit sized box std::vector<Vec3f> vtx = { {1, -1, -1}, {1, -1, 1}, {-1, -1, 1}, {-1, -1, -1}, {1, 1, -1}, {1, 1, 1}, {-1, 1, 1}, {-1, 1, -1}, }; std::vector<Vec3i> tris = { {2, 4, 1}, {8, 6, 5}, {5, 2, 1}, {6, 3, 2}, {3, 8, 4}, {1, 8, 5}, {2, 3, 4}, {8, 7, 6}, {5, 6, 2}, {6, 7, 3}, {3, 7, 8}, {1, 4, 8}, }; Mat(tris) -= Scalar(1, 1, 1); Vec3f rot(0,0,0), trans(0,0,0); Mat frame = imread("box.jpg"); Mat_<float> K(3,3); K << .15 * frame.cols, 0, frame.cols/2, 0, .15 * frame.rows, frame.rows/2, 0, 0, 1; cout << frame.size() << K << endl; Mat gray; cvtColor(frame,gray,COLOR_BGR2GRAY); for(int i = 0; i < 3; i++) {// do two iteration rapid::rapid(gray, 100, 20, vtx, tris, K, rot, trans); } cout << trans << " " << rot << endl; Mat pts2d; projectPoints(vtx, rot, trans, K, noArray(), pts2d); rapid::drawWireframe(frame, pts2d, tris, Scalar(200), LINE_8); imshow("R",frame); waitKey(); return 0; } /* int main() { // a unit sized box std::vector<Vec3f> vtx = { {1, -1, -1}, {1, -1, 1}, {-1, -1, 1}, {-1, -1, -1}, {1, 1, -1}, {1, 1, 1}, {-1, 1, 1}, {-1, 1, -1}, }; std::vector<Vec3i> tris = { {2, 4, 1}, {8, 6, 5}, {5, 2, 1}, {6, 3, 2}, {3, 8, 4}, {1, 8, 5}, {2, 3, 4}, {8, 7, 6}, {5, 6, 2}, {6, 7, 3}, {3, 7, 8}, {1, 4, 8}, }; Mat(tris) -= Scalar(1, 1, 1); Vec3f rot(0,0,0), trans(0,0,0); VideoCapture cap(0); int j=0, k=0; while(1) { Mat frame; cap >> frame; if (frame.empty()) break; Mat_<float> K(3,3); K << frame.cols, 0, frame.cols/2, 0, frame.rows, frame.rows/2, 0, 0, 1; cout << frame.size() << K << endl; Mat gray; cvtColor(frame,gray,COLOR_BGR2GRAY); if (k==' ') { for(int i = 0; i < 3; i++) {// do two iteration rapid::rapid(gray, 100, 20, vtx, tris, K, rot, trans); } cout << (j++) << " " << trans << " " << rot << endl; Mat pts2d; projectPoints(vtx, rot, trans, K, noArray(), pts2d); rapid::drawWireframe(frame, pts2d, tris, Scalar(200), LINE_8); } imshow("R",frame); k = waitKey(10); if (k == 27) break; } return 0; } */ /*int main() { // a unit sized box std::vector<Vec3f> vtx = { {1, -1, -1}, {1, -1, 1}, {-1, -1, 1}, {-1, -1, -1}, {1, 1, -1}, {1, 1, 1}, {-1, 1, 1}, {-1, 1, -1}, }; std::vector<Vec3i> tris = { {2, 4, 1}, {8, 6, 5}, {5, 2, 1}, {6, 3, 2}, {3, 8, 4}, {1, 8, 5}, {2, 3, 4}, {8, 7, 6}, {5, 6, 2}, {6, 7, 3}, {3, 7, 8}, {1, 4, 8}, }; Mat(tris) -= Scalar(1, 1, 1); // camera setup Size sz(1280, 720); Mat K = getDefaultNewCameraMatrix(Matx33f::diag(Vec3f(800, 800, 1)), sz, true); cout << "K " << K << endl; Vec3f trans = {0, 0, 5}; Vec3f rot = {0.7f, 0.6f, 0}; Vec3f rot0(rot); cout << "t " << trans << " " << rot0 << endl; // draw something Mat_<uchar> img(sz, uchar(0)); Mat pts2d; projectPoints(vtx, rot, trans, K, noArray(), pts2d); rapid::drawWireframe(img, pts2d, tris, Scalar(120), LINE_8); // recover pose form different position Vec3f t_init = Vec3f(0.1f, 0, 5); pts2d.release(); projectPoints(vtx, rot, t_init, K, noArray(), pts2d); rapid::drawWireframe(img, pts2d, tris, Scalar(180), LINE_8); cout << "i " << t_init << " " << rot << endl; for(int i = 0; i < 3; i++) {// do two iteration rapid::rapid(img, 100, 20, vtx, tris, K, rot, t_init); cout << i << " " << t_init << " " << rot << endl; } pts2d.release(); projectPoints(vtx, rot, t_init, K, noArray(), pts2d); rapid::drawWireframe(img, pts2d, tris, Scalar(255), LINE_8); // assert that it improved from init double nt = cv::norm(trans - t_init); double nr = cv::norm(rot - rot0); cout << "T " << nt << " R " << nr << endl; imshow("R",img); waitKey(); return 0; } */
31.226277
107
0.469612
[ "vector" ]
7510ccd4c46d9550380d2cfb80ea232a9ac778b1
7,739
cxx
C++
smtk/extension/paraview/widgets/plugin/pqPointPropertyWidget.cxx
jcfr/SMTK
0069ea37f8f71a440b8f10a157b84a56ca004551
[ "BSD-3-Clause-Clear" ]
40
2015-02-21T19:55:54.000Z
2022-01-06T13:13:05.000Z
smtk/extension/paraview/widgets/plugin/pqPointPropertyWidget.cxx
jcfr/SMTK
0069ea37f8f71a440b8f10a157b84a56ca004551
[ "BSD-3-Clause-Clear" ]
127
2015-01-15T20:55:45.000Z
2021-08-19T17:34:15.000Z
smtk/extension/paraview/widgets/plugin/pqPointPropertyWidget.cxx
jcfr/SMTK
0069ea37f8f71a440b8f10a157b84a56ca004551
[ "BSD-3-Clause-Clear" ]
27
2015-03-04T14:17:51.000Z
2021-12-23T01:05:42.000Z
//============================================================================= // // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. // //============================================================================= /*========================================================================= Program: ParaView Module: pqPointPropertyWidget.cxx Copyright (c) 2005,2006 Sandia Corporation, Kitware Inc. All rights reserved. ParaView is a free software; you can redistribute it and/or modify it under the terms of the ParaView license version 1.2. See License_v1.2.txt for the full ParaView license. A copy of this license can be obtained by contacting Kitware Inc. 28 Corporate Drive Clifton Park, NY 12065 USA 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 AUTHORS 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 "pqPointPropertyWidget.h" #include "ui_pqPointPropertyWidget.h" #include "smtk/extension/paraview/widgets/pqPointPickingVisibilityHelper.h" #include "pqActiveObjects.h" #include "pqPointPickingHelper.h" #include "vtkSMNewWidgetRepresentationProxy.h" #include "vtkSMPropertyGroup.h" #include "vtkSMPropertyHelper.h" #include <QCheckBox> #include <algorithm> #include <cctype> constexpr const char* tooltipInactive = "Edit point coordinates manually or click the checkbox to enable 3-d editing."; constexpr const char* tooltipVisible = "Edit point coordinates manually or drag the point in the render view. " "Click the checkbox to enable picking."; #ifdef Q_OS_MAC constexpr const char* tooltipActive = "Edit point coordinates manually or drag the point in the render view. " "Type 'P' to pick a point on any surface under the cursor or " "'Cmd+P' to snap to the closest point used to define the underlying surface. " "Click the checkbox to hide the 3-d widget."; #else constexpr const char* tooltipActive = "Edit point coordinates manually or drag the point in the render view. " "Type 'P' to pick a point on any surface under the cursor or " "'Ctrl+P' to snap to the closest point used to define the underlying surface. " "Click the checkbox to hide the 3-d widget."; #endif pqPointPropertyWidget::pqPointPropertyWidget( vtkSMProxy* smproxy, vtkSMPropertyGroup* smgroup, QWidget* parentObject) : Superclass("representations", "HandleWidgetRepresentation", smproxy, smgroup, parentObject) , m_state(0) , m_surfacePickHelper(nullptr) , m_pointPickHelper(nullptr) { Ui::PointPropertyWidget ui; ui.setupUi(this); if (vtkSMProperty* worldPosition = smgroup->GetProperty("WorldPosition")) { this->addPropertyLink( ui.worldPositionX, "text2", SIGNAL(textChangedAndEditingFinished()), worldPosition, 0); this->addPropertyLink( ui.worldPositionY, "text2", SIGNAL(textChangedAndEditingFinished()), worldPosition, 1); this->addPropertyLink( ui.worldPositionZ, "text2", SIGNAL(textChangedAndEditingFinished()), worldPosition, 2); } else { qCritical("Missing required property for function 'WorldPosition'"); } m_control = ui.show3DWidget; ui.show3DWidget->setCheckState(Qt::Checked); // If the user toggles the Qt checkbox, update the 3D widget state: this->connect(ui.show3DWidget, SIGNAL(stateChanged(int)), SLOT(setControlState(int))); this->setControlState("active"); } pqPointPropertyWidget::~pqPointPropertyWidget() = default; std::string pqPointPropertyWidget::controlState() { return m_state == 0 ? "inactive" : (m_state == 1 ? "visible" : "active"); } void pqPointPropertyWidget::setControlState(const std::string& data) { int startState = m_state; std::string state = data; std::transform( state.begin(), state.end(), state.begin(), [](unsigned char c) { return std::tolower(c); }); if (state == "active") { m_state = 3; this->setToolTip(tooltipActive); } else if (state == "visible") { m_state = 1; this->setToolTip(tooltipVisible); } else if (state == "inactive") { m_state = 0; this->setToolTip(tooltipInactive); } this->setWidgetVisible(m_state & 0x01); if (m_state & 0x02) { auto* currView = pqActiveObjects::instance().activeView(); if (!m_surfacePickHelper) { m_surfacePickHelper = new pqPointPickingHelper(QKeySequence(tr("P")), false, this); m_surfacePickHelper->connect(this, SIGNAL(viewChanged(pqView*)), SLOT(setView(pqView*))); this->connect( m_surfacePickHelper, SIGNAL(pick(double, double, double)), SLOT(setWorldPosition(double, double, double))); pqPointPickingVisibilityHelper<pqPointPickingHelper>{ *this, *m_surfacePickHelper }; m_surfacePickHelper->setView(currView); } if (!m_pointPickHelper) { m_pointPickHelper = new pqPointPickingHelper(QKeySequence(tr("Ctrl+P")), true, this); m_pointPickHelper->connect(this, SIGNAL(viewChanged(pqView*)), SLOT(setView(pqView*))); this->connect( m_pointPickHelper, SIGNAL(pick(double, double, double)), SLOT(setWorldPosition(double, double, double))); pqPointPickingVisibilityHelper<pqPointPickingHelper>{ *this, *m_pointPickHelper }; m_pointPickHelper->setView(currView); } } else { if (m_surfacePickHelper) { m_surfacePickHelper->disconnect(this); delete m_surfacePickHelper; m_surfacePickHelper = nullptr; } if (m_pointPickHelper) { m_pointPickHelper->disconnect(this); delete m_pointPickHelper; m_pointPickHelper = nullptr; } } if (startState != m_state) { m_control->setCheckState( m_state == 0x00 ? Qt::Unchecked : (m_state == 0x01 ? Qt::PartiallyChecked : Qt::Checked)); emit controlStateChanged(this->controlState()); } } void pqPointPropertyWidget::setControlState(int checkState) { // Note that \a checkState is **not** a proper value for m_state! // It is the value provided by a QCheckBox (Qt::CheckState). switch (checkState) { case Qt::Unchecked: this->setControlState("inactive"); break; case Qt::PartiallyChecked: this->setControlState("visible"); break; case Qt::Checked: this->setControlState("active"); break; default: std::cerr << "Invalid check state " << checkState << "\n"; break; } } void pqPointPropertyWidget::setControlVisibility(bool show) { m_control->setVisible(show); } void pqPointPropertyWidget::placeWidget() { // nothing to do. } void pqPointPropertyWidget::setWorldPosition(double wx, double wy, double wz) { vtkSMProxy* wdgProxy = this->widgetProxy(); double o[3] = { wx, wy, wz }; vtkSMPropertyHelper(wdgProxy, "WorldPosition").Set(o, 3); wdgProxy->UpdateVTKObjects(); emit this->changeAvailable(); this->render(); }
33.07265
96
0.688073
[ "render", "transform", "3d" ]
75138e44d6ddf8b2bef7f3396c10451a35563035
2,059
cc
C++
hbase/src/model/EnableHBaseueBackupRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
hbase/src/model/EnableHBaseueBackupRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
hbase/src/model/EnableHBaseueBackupRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/hbase/model/EnableHBaseueBackupRequest.h> using AlibabaCloud::HBase::Model::EnableHBaseueBackupRequest; EnableHBaseueBackupRequest::EnableHBaseueBackupRequest() : RpcServiceRequest("hbase", "2019-01-01", "EnableHBaseueBackup") { setMethod(HttpRequest::Method::Post); } EnableHBaseueBackupRequest::~EnableHBaseueBackupRequest() {} std::string EnableHBaseueBackupRequest::getClientToken()const { return clientToken_; } void EnableHBaseueBackupRequest::setClientToken(const std::string& clientToken) { clientToken_ = clientToken; setParameter("ClientToken", clientToken); } std::string EnableHBaseueBackupRequest::getHbaseueClusterId()const { return hbaseueClusterId_; } void EnableHBaseueBackupRequest::setHbaseueClusterId(const std::string& hbaseueClusterId) { hbaseueClusterId_ = hbaseueClusterId; setParameter("HbaseueClusterId", hbaseueClusterId); } int EnableHBaseueBackupRequest::getColdStorageSize()const { return coldStorageSize_; } void EnableHBaseueBackupRequest::setColdStorageSize(int coldStorageSize) { coldStorageSize_ = coldStorageSize; setParameter("ColdStorageSize", std::to_string(coldStorageSize)); } int EnableHBaseueBackupRequest::getNodeCount()const { return nodeCount_; } void EnableHBaseueBackupRequest::setNodeCount(int nodeCount) { nodeCount_ = nodeCount; setParameter("NodeCount", std::to_string(nodeCount)); }
27.824324
90
0.773191
[ "model" ]
751b16ea4b0a67dcd40f3b86900ab676bd170190
2,581
hpp
C++
src/libs/directorlib/sc_daemonctrl.hpp
suggitpe/RPMS
7a12da0128f79b8b0339fd7146105ba955079b8c
[ "Apache-2.0" ]
null
null
null
src/libs/directorlib/sc_daemonctrl.hpp
suggitpe/RPMS
7a12da0128f79b8b0339fd7146105ba955079b8c
[ "Apache-2.0" ]
null
null
null
src/libs/directorlib/sc_daemonctrl.hpp
suggitpe/RPMS
7a12da0128f79b8b0339fd7146105ba955079b8c
[ "Apache-2.0" ]
null
null
null
#ifndef __sc_daemonctrl_hpp #define __sc_daemonctrl_hpp #include <base/sa_threadbase.hpp> #include <base/st_spointer.hpp> #include <idllib/idls/sr_daemontask.h> namespace rpms { // pre decl class SA_Socket; /** * Class used to control a single daemon. * This class is the delegate for managing a single daemon. * * @author Peter Suggitt (2005) * @note Concrete class * */ class SC_DaemonCtrl : public SA_ThreadBase { public: /** Create a new object of type SC_DaemonCtrl */ static ST_SPointer<SC_DaemonCtrl> create( const std::string &aDaemonHost, const std::string &aThreadName ); /** Stop the thread */ void stop(); /** Virtual destructor */ virtual ~SC_DaemonCtrl(); /** Reset the thread */ void reset(); /** Get the remote daemon status*/ std::string getStatus(); /** Get the remote daemon process stats */ std::string getDaemonProcStats(); /** Getter method for the initialised flag */ bool isInitialised() const { return mInitialised; } /** Go to the underlying daemon and add to the state stack */ void addToDaemonStateQueue( const std::string &aState, const std::string &aArg ); protected: /** Main constructor. Called from the create method */ SC_DaemonCtrl( const std::string &aDaemonHost, const std::string &aThreadName ); /** The main runnable context for the thread */ void run(); private: /** Hidden copy constructor */ SC_DaemonCtrl( const SC_DaemonCtrl &aRhs ); /** Hidden assignment operator */ SC_DaemonCtrl& operator=( const SC_DaemonCtrl &aRhs ); /** Internal initialisation */ void init(); private: // members /** Flag to see whether this thread should run */ bool mShouldRun; /** Port number for the heartbeats on the daemon host */ int mHeartbeatPort; /** Socket for sending out heartbeats to the daemons */ ST_SPointer<SA_Socket> mSocket; /** Name of the remote daemon host */ std::string mDaemonHost; /** Remote object pointer (CORBA object) */ SR_DaemonTask_var mRemote; /** flag to show if initialised */ bool mInitialised; }; } // namespace #endif
34.878378
93
0.56606
[ "object" ]
970eee338212e3024000481520fce6e1aa865ee7
6,713
hpp
C++
src/cest.hpp
Malien/cest
c35754dead44f40b72accbda1af42a19605c9828
[ "MIT" ]
null
null
null
src/cest.hpp
Malien/cest
c35754dead44f40b72accbda1af42a19605c9828
[ "MIT" ]
3
2020-02-04T14:50:09.000Z
2020-02-05T08:54:25.000Z
src/cest.hpp
Malien/cest
c35754dead44f40b72accbda1af42a19605c9828
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <functional> #include <optional> #include <iostream> #include <sstream> #include <thread> #include <vector> #include <cmath> #include <typeinfo> #include "colorize.hpp" #include "message.hpp" #ifdef __COUNTER__ #define UNIQUE __COUNTER__ #else #define UNIQUE __LINE__ #endif #define PP_CAT(a, b) PP_CAT_I(a, b) #define PP_CAT_I(a, b) PP_CAT_II(~, a ## b) #define PP_CAT_II(p, res) res #define UNIQUE_NAME(base) PP_CAT(base, UNIQUE) #define test(name, test_func) cest::sequentialTest(name, test_func, __FILE__, __LINE__) #define testp(name, test_func) cest::ParallelTestHandler UNIQUE_NAME(__parallel_test_) = cest::parallelTest(name, test_func, __FILE__, __LINE__) #define expect(value) cest::expectImpl(value, __FILE__, __LINE__) namespace cest { class internal { static inline std::mutex consoleMutex; static inline int exitCode = EXIT_SUCCESS; friend void sequentialTest(const std::string_view&, std::function<void()>, const char*, int); friend int exitCode(); }; int exitCode() { return internal::exitCode; } enum class mode { sequential, parallel }; struct TestFailure { std::string file; int line; std::optional<std::string> expected_repr; std::string result_repr; bool negated = false; }; template <typename T> struct TestCase { const T& val; std::string file; int line; bool negated = false; template<class Cmp = std::equal_to<T>> void toBe(const T& val, Cmp comparator = Cmp{}) const { if (comparator(this->val, val) ^ !negated) { failWithExpected(val); } } template<typename I> typename std::enable_if<std::is_convertible<T, I>::value && std::is_floating_point<I>::value>::type toBeCloseTo(I val, I eps = 1e-4) const { if (((this->val == val) || (abs(this->val - val) < this->val * eps)) ^ !negated) { failWithExpected(val); } } void toPass(const std::function<bool(const T&)>& func) const { if (func(val) ^ !negated) { fail(val); } } template<typename U> void toPass(const std::function<bool(const T&, const U&)>& func, const U& param) const { if (func(val, param) ^ !negated) { fail(); } } // TODO: get rid of duck typing and provide template constraints template<typename U> void toThrow() const { std::string thrownName = typeid(U).name(); try { val(); throw Rethrow{}; } catch(U e) { if (negated) throw TestFailure{file, line, "To throw " + thrownName, thrownName, negated}; } catch(Rethrow e) { if (!negated) throw TestFailure{file, line, "To throw " + thrownName, "Nothing", negated}; } catch (std::exception e) { throw TestFailure{file, line, "To throw " + thrownName, e.what(), negated}; } catch(...) { throw TestFailure{file, line, "To throw " + thrownName, "Non STL exception", negated}; } } const TestCase<T> operator!() const { return { val, file, line, !negated }; } private: void fail(T val) const { std::stringstream result; result << val; throw TestFailure{file, line, std::nullopt, result.str(), negated}; } void failWithExpected(T val) const { std::stringstream expectedStream, resultStream; expectedStream << val; resultStream << this->val; throw TestFailure{file, line, expectedStream.str(), resultStream.str(), negated}; } struct Rethrow {}; }; template <typename T> const TestCase<T> expectImpl(const T& val, const char* filename = "Unknown", int line = 0) { return { val, filename, line }; } inline void sequentialTest(const std::string_view& name, std::function<void()> test_func, const char* filename = "Unknown", int line = 0) { using namespace colorize::standart; auto start = std::chrono::high_resolution_clock::now(); try { test_func(); std::unique_lock lock(internal::consoleMutex); std::cout << message::pass {name, filename, line, start} << std::endl; } catch (const TestFailure& failure) { std::unique_lock lock(internal::consoleMutex); std::string expectedMsg = (failure.negated) ? "Expected NOT: " : "Expected: "; std::cerr << message::fail {name, filename, line, start} << std::endl << "Test failed at " << foreground::brightBlack << failure.file << ':' << failure.line << colorize::end << std::endl; if (failure.expected_repr.has_value()) { std::cerr << foreground::cyan << "\t" << expectedMsg << "\n\t\t" << failure.expected_repr.value() << colorize::end << std::endl; } std::cerr << foreground::red << "\tGot: \n\t\t" << failure.result_repr << colorize::end << std::endl; internal::exitCode = EXIT_FAILURE; } catch (std::exception e) { std::unique_lock lock(internal::consoleMutex); std::cerr << message::fail {name, filename, line, start} << std::endl << "\tTest threw STL exception: " << foreground::brightRed << e.what() << colorize::end << std::endl; internal::exitCode = EXIT_FAILURE; } catch (...) { std::unique_lock lock(internal::consoleMutex); std::cerr << message::fail {name, filename, line, start} << std::endl << foreground::brightRed << "\tTest threw unknown exception" << colorize::end << std::endl; internal::exitCode = EXIT_FAILURE; } } struct ParallelTestHandler { std::thread thread; ~ParallelTestHandler() { thread.join(); } }; inline ParallelTestHandler parallelTest(const std::string_view& name, std::function<void()> test_func, const char* filename = "Unknown", int line = 0) { return {std::thread([=]{ sequentialTest(name, test_func, filename, line); })}; } }
37.926554
144
0.546254
[ "vector" ]
971a63ed45903e170520f23eac80234915b9d21e
318
hpp
C++
src/test/test_obj.hpp
artyomd/GPU-Playground
b79ad200c999a7374a038219272461fa1ad3240f
[ "Apache-2.0" ]
2
2019-10-15T20:34:54.000Z
2020-12-01T06:45:48.000Z
src/test/test_obj.hpp
artyomd/GPU-Playground
b79ad200c999a7374a038219272461fa1ad3240f
[ "Apache-2.0" ]
2
2020-03-31T22:08:08.000Z
2021-02-10T18:59:32.000Z
src/test/test_obj.hpp
artyomd/GPU-Playground
b79ad200c999a7374a038219272461fa1ad3240f
[ "Apache-2.0" ]
2
2020-05-12T09:38:03.000Z
2021-11-21T07:32:43.000Z
// // Created by artyomd on 5/1/20. // #pragma once #include "src/geometry/triangle.hpp" #include "src/test/test.h" #include "src/test/test_model.hpp" namespace test { class TestObj : public TestModel { public: explicit TestObj(std::shared_ptr<api::RenderingContext> renderer); void OnRender() override; }; }
16.736842
68
0.716981
[ "geometry" ]
971acfc8bbd59b5b425563d5edf471d05de68876
4,188
cpp
C++
src/codegen/statementgenerator.cpp
jroivas/nolang
761655bf851a978fb8426cc8f465e53cc86dec28
[ "MIT" ]
2
2021-04-13T20:16:04.000Z
2022-02-17T02:46:40.000Z
src/codegen/statementgenerator.cpp
jroivas/nolang
761655bf851a978fb8426cc8f465e53cc86dec28
[ "MIT" ]
null
null
null
src/codegen/statementgenerator.cpp
jroivas/nolang
761655bf851a978fb8426cc8f465e53cc86dec28
[ "MIT" ]
null
null
null
#include "statementgenerator.hh" #include "methodcallgenerator.hh" using namespace nolang; void StatementGenerator::reset() { lines.clear(); statementcode.clear(); } void StatementGenerator::generateString() { statementcode = cgen->applyPostponed(statementcode); statementcode.push_back(statement->code() + " "); } void StatementGenerator::generateNumber() { statementcode = cgen->applyPostponed(statementcode); statementcode.push_back(statement->code()); } void StatementGenerator::generateBoolean() { statementcode = cgen->applyPostponed(statementcode); statementcode.push_back(statement->code()); } void StatementGenerator::generateBraces() { statementcode = cgen->applyPostponed(statementcode); statementcode.push_back(statement->code() + " "); } void StatementGenerator::generateComparator() { statementcode = cgen->applyPostponed(statementcode); statementcode.push_back(statement->code() + " "); } void StatementGenerator::generateOperator() { std::string pp = statement->code(); if (pp == "div") pp = "/"; statementcode.push_back(pp + " "); } std::vector<std::string> StatementGenerator::generateMethodCall(const MethodCall *mc) { MethodCallGenerator gen(cgen, mc, method); std::vector<std::string> res; if (gen.isStruct()) res = gen.generateStructInitCall(); else res = gen.generateMethodCall(); cgen->clearPostponed(); return res; } void StatementGenerator::generateMethodCall() { const MethodCall *mc = static_cast<const MethodCall*>(statement); for (auto l : generateMethodCall(mc)) statementcode.push_back(l); } bool StatementGenerator::isAssignmentMethodCall(const Assignment *ass) const { for (auto sss : ass->statements()) { if (sss->type() == "MethodCall") return true; } return false; } void StatementGenerator::generateAssignmentWithDefinition(const Assignment *a) { cgen->clearPostponed(); for (auto s : StatementGenerator(cgen, a->def(), method).generateOne()) { if (!cgen->isPostponed()) cgen->appendPostponed("->"); cgen->appendPostponed(s); } } void StatementGenerator::generateAssignmentPreStatements(const Assignment *a) { if (isAssignmentWithDefinition(a)) generateAssignmentWithDefinition(a); else if (isAssignmentMethodCall(a)) cgen->setPostponedMethod(statement->code()); else cgen->setPostponed(statement->code()); } void StatementGenerator::generateAssignmentStatements(const Assignment *a) { std::vector<std::string> tmp = StatementGenerator(cgen, a->statements(), method).generate(); statementcode = applyToVector(statementcode, tmp); } void StatementGenerator::generateAssignment() { const Assignment *a = static_cast<const Assignment*>(statement); generateAssignmentPreStatements(a); generateAssignmentStatements(a); } void StatementGenerator::generateNamespace() { } void StatementGenerator::generateIdentfier() { statementcode = cgen->applyPostponed(statementcode); statementcode.push_back(statement->code() + " "); } void StatementGenerator::generateEOS() { statementcode.push_back("<EOS>"); } void StatementGenerator::generateStatementCode() { if (isString()) generateString(); else if (isNumber()) generateNumber(); else if (isBoolean()) generateBoolean(); else if (isBraces()) generateBraces(); else if (isComparator()) generateComparator(); else if (isOperator()) generateOperator(); else if (isMethodCall()) generateMethodCall(); else if (isAssignment()) generateAssignment(); else if (isNamespace()) generateNamespace(); else if (isIdentifier()) generateIdentfier(); else if (isEOS()) generateEOS(); else printError("Unhandled statement", statement); } void StatementGenerator::generateStatement() { statementcode.clear(); generateStatementCode(); if (!statementcode.empty()) lines = applyToVector(lines, statementcode); } void StatementGenerator::iterateStatements() { for (auto s : stmts) { statement = s; generateStatement(); } } std::vector<std::string> StatementGenerator::generate() { reset(); iterateStatements(); return lines; }
26.339623
96
0.711796
[ "vector" ]
971b3d9d90abdb7e0dc778d5a484fe74cc4b2ab2
7,208
cpp
C++
stareLibrary.cpp
NiklasPhabian/SciDB-HSTM
fecfba40616393cf7e90a4e5e46a5025868f872f
[ "BSD-3-Clause" ]
null
null
null
stareLibrary.cpp
NiklasPhabian/SciDB-HSTM
fecfba40616393cf7e90a4e5e46a5025868f872f
[ "BSD-3-Clause" ]
null
null
null
stareLibrary.cpp
NiklasPhabian/SciDB-HSTM
fecfba40616393cf7e90a4e5e46a5025868f872f
[ "BSD-3-Clause" ]
null
null
null
#include "stareLibrary.h" using namespace log4cxx; using namespace log4cxx::helpers; using namespace scidb; using namespace stare; using namespace boost::assign; enum { STARE_ERROR1 = SCIDB_USER_ERROR_CODE_START }; STARE stareIndex; // Spatial static void stare::stareFromResolutionLatLon(const scidb::Value** args, scidb::Value* res, void* v) { int32 resolution = args[0]->getInt32(); float64 latDegrees = args[1]->getDouble(); float64 lonDegrees = args[2]->getDouble(); STARE_ArrayIndexSpatialValue id = stareIndex.ValueFromLatLonDegrees(latDegrees, lonDegrees, resolution); *(STARE_ArrayIndexSpatialValue*)res->data() = id; } static void stare::latLonFromStare(const scidb::Value** args, scidb::Value* res, void* v) { STARE_ArrayIndexSpatialValue& id = *(STARE_ArrayIndexSpatialValue*)args[0]->data(); LatLonDegrees64 latlon = stareIndex.LatLonDegreesFromValue(id); *(LatLonDegrees64*)res->data() = latlon; }; static void stare::resolutionFromStare(const scidb::Value** args, scidb::Value* res, void* v) { //TBD }; static void constructStareSpatial(const scidb::Value** args, scidb::Value* res, void* v) { STARE_ArrayIndexSpatialValue id; *(STARE_ArrayIndexSpatialValue*)res->data() = id; } static void constructLatLon64(const scidb::Value** args, scidb::Value* res, void* v) { LatLonDegrees64 latlon(0, 0); *(LatLonDegrees64*)res->data() = latlon; } // Temporal static void stare::stareFromUTCDateTime(const scidb::Value** args, scidb::Value* res, void* v) { int resolution = args[0]->getInt32(); time_t datetime = args[1]->getDateTime(); // SciDB understands time_t as seconds since UNIX epoch STARE_ArrayIndexTemporalValue indexValue = stareIndex.ValueFromUTC(datetime, resolution, 2); *(STARE_ArrayIndexTemporalValue*)res->data() = indexValue; } static void stare::datetimeFromStare(const scidb::Value** args, scidb::Value* res, void* v) { struct tm tm; STARE_ArrayIndexTemporalValue& id = *(STARE_ArrayIndexTemporalValue*)args[0]->data(); Datetime datetime = stareIndex.UTCFromValue(id); tm.tm_year=datetime.year - 1900; tm.tm_mon=datetime.month - 1; tm.tm_mday=datetime.day; tm.tm_hour=datetime.hour; tm.tm_min=datetime.minute; tm.tm_sec=datetime.second; time_t dt = mktime(&tm); res->setDateTime(dt); } static void stare::convDateTime2TimeT(const scidb::Value** args, scidb::Value* res, void* v) { time_t dt = args[0]->getDateTime(); res->setUint64(static_cast<uint64_t>(dt)); } static void constructStareTemporal(const scidb::Value** args, scidb::Value* res, void* v) { STARE_ArrayIndexTemporalValue id; *(STARE_ArrayIndexTemporalValue*)res->data() = id; } // Converters static void stare::spatialIndexValueToString (const scidb::Value** args, scidb::Value* res, void* v) { STARE_ArrayIndexSpatialValue& id = *(STARE_ArrayIndexSpatialValue*)args[0]->data(); res->setString(to_string(id)); } static void stare::spatialIndexValueToInt64(const scidb::Value** args, scidb::Value* res, void* v) { STARE_ArrayIndexSpatialValue& id = *(STARE_ArrayIndexSpatialValue*)args[0]->data(); res->setInt64(id); } static void stare::temporalIndexValueToString (const scidb::Value** args, scidb::Value* res, void* v) { STARE_ArrayIndexTemporalValue& id = *(STARE_ArrayIndexTemporalValue*)args[0]->data(); res->setString(to_string(id)); } static void stare::LatLonDegreesToString (const scidb::Value** args, scidb::Value* res, void* v) { LatLonDegrees64& latlon = *(LatLonDegrees64*)args[0]->data(); char buffer [50]; sprintf(buffer, "(%f°, %f°)", latlon.lat, latlon.lon); res->setString(buffer); } REGISTER_CONVERTER(STARESpatial, string, EXPLICIT_CONVERSION_COST, stare::spatialIndexValueToString); REGISTER_CONVERTER(STARESpatial, in64, EXPLICIT_CONVERSION_COST, stare::spatialIndexValueToInt64); REGISTER_CONVERTER(STARETemporal, string, EXPLICIT_CONVERSION_COST, stare::temporalIndexValueToString); REGISTER_CONVERTER(LatLon64, string, EXPLICIT_CONVERSION_COST, stare::LatLonDegreesToString); vector<Type> _types; EXPORTED_FUNCTION const vector<Type>& GetTypes() { return _types; } vector<FunctionDescription> _functionDescs; EXPORTED_FUNCTION const vector<FunctionDescription>& GetFunctions() { return _functionDescs; } static class stareLibrary { public: stareLibrary() { // BasicConfigurator::configure(); LOG4CXX_INFO(stare::logger, "Entering constructor."); Type stareSpatialType("STARESpatial", sizeof(STARE)*8); // size in bits _types.push_back(stareSpatialType); Type stareTemporalType("STARETemporal", sizeof(STARE)*8); // size in bits _types.push_back(stareTemporalType); Type latlon64Type("LatLon64", sizeof(STARE)*8); // size in bits _types.push_back(latlon64Type); // Constructors _functionDescs.push_back(FunctionDescription("STARESpatial", ArgTypes(), TypeId("STARESpatial"), &constructStareSpatial)); _functionDescs.push_back(FunctionDescription("STARETemporal", ArgTypes(), TypeId("STARETemporal"), &constructStareTemporal)); _functionDescs.push_back(FunctionDescription("LatLon64", ArgTypes(), TypeId("LatLon64"), &constructLatLon64)); // Question is: Do we create a STARESpatial object or a TID_INT64 object? _functionDescs.push_back(FunctionDescription("stareFromResolutionLatLon", list_of(TID_INT64)(TID_DOUBLE)(TID_DOUBLE), TypeId(TID_INT64), &stare::stareFromResolutionLatLon)); _functionDescs.push_back(FunctionDescription("latLonFromStare", list_of(TID_INT64), TypeId("LatLon64"), &stare::latLonFromStare)); _functionDescs.push_back(FunctionDescription("stareFromUTCDateTime", list_of(TID_INT64)(TID_DATETIME), TypeId(TID_INT64), &stare::stareFromUTCDateTime)); _functionDescs.push_back(FunctionDescription("convDateTime2TimeT", list_of(TID_DATETIME), TypeId(TID_INT64), &stare::convDateTime2TimeT, (size_t) 0)); _functionDescs.push_back(FunctionDescription("datetimeFromStare", list_of(TID_INT64), TypeId(TID_DATETIME), &stare::datetimeFromStare, (size_t) 0)); _errors[STARE_ERROR1] = "STARE construction error."; scidb::ErrorsLibrary::getInstance()->registerErrors("stare",&_errors); } ~stareLibrary() { scidb::ErrorsLibrary::getInstance()->unregisterErrors("stare"); } private: scidb::ErrorsLibrary::ErrorsMessages _errors; } _instance;
38.752688
129
0.657741
[ "object", "vector" ]
971f364db7c396a93725a59d420a57bfe6c900c4
33,036
cpp
C++
src/Atema/VulkanRenderer/Vulkan.cpp
JordiSubirana/ATEMA
be14a61d34e3c947aadc9e92a091408461f1c0a1
[ "MIT" ]
3
2016-04-19T18:08:31.000Z
2016-09-23T15:11:11.000Z
src/Atema/VulkanRenderer/Vulkan.cpp
JordiSubirana/ATEMA
be14a61d34e3c947aadc9e92a091408461f1c0a1
[ "MIT" ]
null
null
null
src/Atema/VulkanRenderer/Vulkan.cpp
JordiSubirana/ATEMA
be14a61d34e3c947aadc9e92a091408461f1c0a1
[ "MIT" ]
1
2016-04-19T18:09:23.000Z
2016-04-19T18:09:23.000Z
/* Copyright 2021 Jordi SUBIRANA 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 <Atema/VulkanRenderer/Vulkan.hpp> #include <Atema/Renderer/Renderer.hpp> using namespace at; #define ATEMA_VULKAN_LOAD(AT_FUNCTION) \ AT_FUNCTION = reinterpret_cast<PFN_ ## AT_FUNCTION>(vkGetInstanceProcAddr(instance, #AT_FUNCTION)) Vulkan::Vulkan(VkInstance instance) { ATEMA_VULKAN_LOAD(vkCreateDebugUtilsMessengerEXT); ATEMA_VULKAN_LOAD(vkDestroyDebugUtilsMessengerEXT); #ifdef ATEMA_SYSTEM_WINDOWS ATEMA_VULKAN_LOAD(vkCreateWin32SurfaceKHR); #endif } Vulkan::~Vulkan() { } VkFormat Vulkan::getFormat(ImageFormat format) { switch (format) { // Color (8 bit components) case ImageFormat::R8_UNORM: return VK_FORMAT_R8_UNORM; case ImageFormat::R8_SNORM: return VK_FORMAT_R8_SNORM; case ImageFormat::R8_USCALED: return VK_FORMAT_R8_USCALED; case ImageFormat::R8_SSCALED: return VK_FORMAT_R8_SSCALED; case ImageFormat::R8_UINT: return VK_FORMAT_R8_UINT; case ImageFormat::R8_SINT: return VK_FORMAT_R8_SINT; case ImageFormat::R8_SRGB: return VK_FORMAT_R8_SRGB; case ImageFormat::RG8_UNORM: return VK_FORMAT_R8G8_UNORM; case ImageFormat::RG8_SNORM: return VK_FORMAT_R8G8_SNORM; case ImageFormat::RG8_USCALED: return VK_FORMAT_R8G8_USCALED; case ImageFormat::RG8_SSCALED: return VK_FORMAT_R8G8_SSCALED; case ImageFormat::RG8_UINT: return VK_FORMAT_R8G8_UINT; case ImageFormat::RG8_SINT: return VK_FORMAT_R8G8_SINT; case ImageFormat::RG8_SRGB: return VK_FORMAT_R8G8_SRGB; case ImageFormat::RGB8_UNORM: return VK_FORMAT_R8G8B8_UNORM; case ImageFormat::RGB8_SNORM: return VK_FORMAT_R8G8B8_SNORM; case ImageFormat::RGB8_USCALED: return VK_FORMAT_R8G8B8_USCALED; case ImageFormat::RGB8_SSCALED: return VK_FORMAT_R8G8B8_SSCALED; case ImageFormat::RGB8_UINT: return VK_FORMAT_R8G8B8_UINT; case ImageFormat::RGB8_SINT: return VK_FORMAT_R8G8B8_SINT; case ImageFormat::RGB8_SRGB: return VK_FORMAT_R8G8B8_SRGB; case ImageFormat::BGR8_UNORM: return VK_FORMAT_B8G8R8_UNORM; case ImageFormat::BGR8_SNORM: return VK_FORMAT_B8G8R8_SNORM; case ImageFormat::BGR8_USCALED: return VK_FORMAT_B8G8R8_USCALED; case ImageFormat::BGR8_SSCALED: return VK_FORMAT_B8G8R8_SSCALED; case ImageFormat::BGR8_UINT: return VK_FORMAT_B8G8R8_UINT; case ImageFormat::BGR8_SINT: return VK_FORMAT_B8G8R8_SINT; case ImageFormat::BGR8_SRGB: return VK_FORMAT_B8G8R8_SRGB; case ImageFormat::RGBA8_UNORM: return VK_FORMAT_R8G8B8A8_UNORM; case ImageFormat::RGBA8_SNORM: return VK_FORMAT_R8G8B8A8_SNORM; case ImageFormat::RGBA8_USCALED: return VK_FORMAT_R8G8B8A8_USCALED; case ImageFormat::RGBA8_SSCALED: return VK_FORMAT_R8G8B8A8_SSCALED; case ImageFormat::RGBA8_UINT: return VK_FORMAT_R8G8B8A8_UINT; case ImageFormat::RGBA8_SINT: return VK_FORMAT_R8G8B8A8_SINT; case ImageFormat::RGBA8_SRGB: return VK_FORMAT_R8G8B8A8_SRGB; case ImageFormat::BGRA8_UNORM: return VK_FORMAT_B8G8R8A8_UNORM; case ImageFormat::BGRA8_SNORM: return VK_FORMAT_B8G8R8A8_SNORM; case ImageFormat::BGRA8_USCALED: return VK_FORMAT_B8G8R8A8_USCALED; case ImageFormat::BGRA8_SSCALED: return VK_FORMAT_B8G8R8A8_SSCALED; case ImageFormat::BGRA8_UINT: return VK_FORMAT_B8G8R8A8_UINT; case ImageFormat::BGRA8_SINT: return VK_FORMAT_B8G8R8A8_SINT; case ImageFormat::BGRA8_SRGB: return VK_FORMAT_B8G8R8A8_SRGB; // Color (16 bit components) case ImageFormat::R16_UNORM: return VK_FORMAT_R16_UNORM; case ImageFormat::R16_SNORM: return VK_FORMAT_R16_SNORM; case ImageFormat::R16_USCALED: return VK_FORMAT_R16_USCALED; case ImageFormat::R16_SSCALED: return VK_FORMAT_R16_SSCALED; case ImageFormat::R16_UINT: return VK_FORMAT_R16_UINT; case ImageFormat::R16_SINT: return VK_FORMAT_R16_SINT; case ImageFormat::R16_SFLOAT: return VK_FORMAT_R16_SFLOAT; case ImageFormat::RG16_UNORM: return VK_FORMAT_R16G16_UNORM; case ImageFormat::RG16_SNORM: return VK_FORMAT_R16G16_SNORM; case ImageFormat::RG16_USCALED: return VK_FORMAT_R16G16_USCALED; case ImageFormat::RG16_SSCALED: return VK_FORMAT_R16G16_SSCALED; case ImageFormat::RG16_UINT: return VK_FORMAT_R16G16_UINT; case ImageFormat::RG16_SINT: return VK_FORMAT_R16G16_SINT; case ImageFormat::RG16_SFLOAT: return VK_FORMAT_R16G16_SFLOAT; case ImageFormat::RGB16_UNORM: return VK_FORMAT_R16G16B16_UNORM; case ImageFormat::RGB16_SNORM: return VK_FORMAT_R16G16B16_SNORM; case ImageFormat::RGB16_USCALED: return VK_FORMAT_R16G16B16_USCALED; case ImageFormat::RGB16_SSCALED: return VK_FORMAT_R16G16B16_SSCALED; case ImageFormat::RGB16_UINT: return VK_FORMAT_R16G16B16_UINT; case ImageFormat::RGB16_SINT: return VK_FORMAT_R16G16B16_SINT; case ImageFormat::RGB16_SFLOAT: return VK_FORMAT_R16G16B16_SFLOAT; case ImageFormat::RGBA16_UNORM: return VK_FORMAT_R16G16B16A16_UNORM; case ImageFormat::RGBA16_SNORM: return VK_FORMAT_R16G16B16A16_SNORM; case ImageFormat::RGBA16_USCALED: return VK_FORMAT_R16G16B16A16_USCALED; case ImageFormat::RGBA16_SSCALED: return VK_FORMAT_R16G16B16A16_SSCALED; case ImageFormat::RGBA16_UINT: return VK_FORMAT_R16G16B16A16_UINT; case ImageFormat::RGBA16_SINT: return VK_FORMAT_R16G16B16A16_SINT; case ImageFormat::RGBA16_SFLOAT: return VK_FORMAT_R16G16B16A16_SFLOAT; // Color (32 bit components) case ImageFormat::R32_UINT: return VK_FORMAT_R32_UINT; case ImageFormat::R32_SINT: return VK_FORMAT_R32_SINT; case ImageFormat::R32_SFLOAT: return VK_FORMAT_R32_SFLOAT; case ImageFormat::RG32_UINT: return VK_FORMAT_R32G32_UINT; case ImageFormat::RG32_SINT: return VK_FORMAT_R32G32_SINT; case ImageFormat::RG32_SFLOAT: return VK_FORMAT_R32G32_SFLOAT; case ImageFormat::RGB32_UINT: return VK_FORMAT_R32G32B32_UINT; case ImageFormat::RGB32_SINT: return VK_FORMAT_R32G32B32_SINT; case ImageFormat::RGB32_SFLOAT: return VK_FORMAT_R32G32B32_SFLOAT; case ImageFormat::RGBA32_UINT: return VK_FORMAT_R32G32B32A32_UINT; case ImageFormat::RGBA32_SINT: return VK_FORMAT_R32G32B32A32_SINT; case ImageFormat::RGBA32_SFLOAT: return VK_FORMAT_R32G32B32A32_SFLOAT; // Color (64 bit components) case ImageFormat::R64_UINT: return VK_FORMAT_R64_UINT; case ImageFormat::R64_SINT: return VK_FORMAT_R64_SINT; case ImageFormat::R64_SFLOAT: return VK_FORMAT_R64_SFLOAT; case ImageFormat::RG64_UINT: return VK_FORMAT_R64G64_UINT; case ImageFormat::RG64_SINT: return VK_FORMAT_R64G64_SINT; case ImageFormat::RG64_SFLOAT: return VK_FORMAT_R64G64_SFLOAT; case ImageFormat::RGB64_UINT: return VK_FORMAT_R64G64B64_UINT; case ImageFormat::RGB64_SINT: return VK_FORMAT_R64G64B64_SINT; case ImageFormat::RGB64_SFLOAT: return VK_FORMAT_R64G64B64_SFLOAT; case ImageFormat::RGBA64_UINT: return VK_FORMAT_R64G64B64A64_UINT; case ImageFormat::RGBA64_SINT: return VK_FORMAT_R64G64B64A64_SINT; case ImageFormat::RGBA64_SFLOAT: return VK_FORMAT_R64G64B64A64_SFLOAT; // DepthStencil case ImageFormat::D32F: return VK_FORMAT_D32_SFLOAT; case ImageFormat::D32F_S8U: return VK_FORMAT_D32_SFLOAT_S8_UINT; case ImageFormat::D24U_S8U: return VK_FORMAT_D24_UNORM_S8_UINT; default: { ATEMA_ERROR("Invalid image format"); } } return VK_FORMAT_UNDEFINED; } ImageFormat Vulkan::getFormat(VkFormat format) { switch (format) { // Color (8 bit components) case VK_FORMAT_R8_UNORM: return ImageFormat::R8_UNORM; case VK_FORMAT_R8_SNORM: return ImageFormat::R8_SNORM; case VK_FORMAT_R8_USCALED: return ImageFormat::R8_USCALED; case VK_FORMAT_R8_SSCALED: return ImageFormat::R8_SSCALED; case VK_FORMAT_R8_UINT: return ImageFormat::R8_UINT; case VK_FORMAT_R8_SINT: return ImageFormat::R8_SINT; case VK_FORMAT_R8_SRGB: return ImageFormat::R8_SRGB; case VK_FORMAT_R8G8_UNORM: return ImageFormat::RG8_UNORM; case VK_FORMAT_R8G8_SNORM: return ImageFormat::RG8_SNORM; case VK_FORMAT_R8G8_USCALED: return ImageFormat::RG8_USCALED; case VK_FORMAT_R8G8_SSCALED: return ImageFormat::RG8_SSCALED; case VK_FORMAT_R8G8_UINT: return ImageFormat::RG8_UINT; case VK_FORMAT_R8G8_SINT: return ImageFormat::RG8_SINT; case VK_FORMAT_R8G8_SRGB: return ImageFormat::RG8_SRGB; case VK_FORMAT_R8G8B8_UNORM: return ImageFormat::RGB8_UNORM; case VK_FORMAT_R8G8B8_SNORM: return ImageFormat::RGB8_SNORM; case VK_FORMAT_R8G8B8_USCALED: return ImageFormat::RGB8_USCALED; case VK_FORMAT_R8G8B8_SSCALED: return ImageFormat::RGB8_SSCALED; case VK_FORMAT_R8G8B8_UINT: return ImageFormat::RGB8_UINT; case VK_FORMAT_R8G8B8_SINT: return ImageFormat::RGB8_SINT; case VK_FORMAT_R8G8B8_SRGB: return ImageFormat::RGB8_SRGB; case VK_FORMAT_B8G8R8_UNORM: return ImageFormat::BGR8_UNORM; case VK_FORMAT_B8G8R8_SNORM: return ImageFormat::BGR8_SNORM; case VK_FORMAT_B8G8R8_USCALED: return ImageFormat::BGR8_USCALED; case VK_FORMAT_B8G8R8_SSCALED: return ImageFormat::BGR8_SSCALED; case VK_FORMAT_B8G8R8_UINT: return ImageFormat::BGR8_UINT; case VK_FORMAT_B8G8R8_SINT: return ImageFormat::BGR8_SINT; case VK_FORMAT_B8G8R8_SRGB: return ImageFormat::BGR8_SRGB; case VK_FORMAT_R8G8B8A8_UNORM: return ImageFormat::RGBA8_UNORM; case VK_FORMAT_R8G8B8A8_SNORM: return ImageFormat::RGBA8_SNORM; case VK_FORMAT_R8G8B8A8_USCALED: return ImageFormat::RGBA8_USCALED; case VK_FORMAT_R8G8B8A8_SSCALED: return ImageFormat::RGBA8_SSCALED; case VK_FORMAT_R8G8B8A8_UINT: return ImageFormat::RGBA8_UINT; case VK_FORMAT_R8G8B8A8_SINT: return ImageFormat::RGBA8_SINT; case VK_FORMAT_R8G8B8A8_SRGB: return ImageFormat::RGBA8_SRGB; case VK_FORMAT_B8G8R8A8_UNORM: return ImageFormat::BGRA8_UNORM; case VK_FORMAT_B8G8R8A8_SNORM: return ImageFormat::BGRA8_SNORM; case VK_FORMAT_B8G8R8A8_USCALED: return ImageFormat::BGRA8_USCALED; case VK_FORMAT_B8G8R8A8_SSCALED: return ImageFormat::BGRA8_SSCALED; case VK_FORMAT_B8G8R8A8_UINT: return ImageFormat::BGRA8_UINT; case VK_FORMAT_B8G8R8A8_SINT: return ImageFormat::BGRA8_SINT; case VK_FORMAT_B8G8R8A8_SRGB: return ImageFormat::BGRA8_SRGB; // Color (16 bit components) case VK_FORMAT_R16_UNORM: return ImageFormat::R16_UNORM; case VK_FORMAT_R16_SNORM: return ImageFormat::R16_SNORM; case VK_FORMAT_R16_USCALED: return ImageFormat::R16_USCALED; case VK_FORMAT_R16_SSCALED: return ImageFormat::R16_SSCALED; case VK_FORMAT_R16_UINT: return ImageFormat::R16_UINT; case VK_FORMAT_R16_SINT: return ImageFormat::R16_SINT; case VK_FORMAT_R16_SFLOAT: return ImageFormat::R16_SFLOAT; case VK_FORMAT_R16G16_UNORM: return ImageFormat::RG16_UNORM; case VK_FORMAT_R16G16_SNORM: return ImageFormat::RG16_SNORM; case VK_FORMAT_R16G16_USCALED: return ImageFormat::RG16_USCALED; case VK_FORMAT_R16G16_SSCALED: return ImageFormat::RG16_SSCALED; case VK_FORMAT_R16G16_UINT: return ImageFormat::RG16_UINT; case VK_FORMAT_R16G16_SINT: return ImageFormat::RG16_SINT; case VK_FORMAT_R16G16_SFLOAT: return ImageFormat::RG16_SFLOAT; case VK_FORMAT_R16G16B16_UNORM: return ImageFormat::RGB16_UNORM; case VK_FORMAT_R16G16B16_SNORM: return ImageFormat::RGB16_SNORM; case VK_FORMAT_R16G16B16_USCALED: return ImageFormat::RGB16_USCALED; case VK_FORMAT_R16G16B16_SSCALED: return ImageFormat::RGB16_SSCALED; case VK_FORMAT_R16G16B16_UINT: return ImageFormat::RGB16_UINT; case VK_FORMAT_R16G16B16_SINT: return ImageFormat::RGB16_SINT; case VK_FORMAT_R16G16B16_SFLOAT: return ImageFormat::RGB16_SFLOAT; case VK_FORMAT_R16G16B16A16_UNORM: return ImageFormat::RGBA16_UNORM; case VK_FORMAT_R16G16B16A16_SNORM: return ImageFormat::RGBA16_SNORM; case VK_FORMAT_R16G16B16A16_USCALED: return ImageFormat::RGBA16_USCALED; case VK_FORMAT_R16G16B16A16_SSCALED: return ImageFormat::RGBA16_SSCALED; case VK_FORMAT_R16G16B16A16_UINT: return ImageFormat::RGBA16_UINT; case VK_FORMAT_R16G16B16A16_SINT: return ImageFormat::RGBA16_SINT; case VK_FORMAT_R16G16B16A16_SFLOAT: return ImageFormat::RGBA16_SFLOAT; // Color (32 bit components) case VK_FORMAT_R32_UINT: return ImageFormat::R32_UINT; case VK_FORMAT_R32_SINT: return ImageFormat::R32_SINT; case VK_FORMAT_R32_SFLOAT: return ImageFormat::R32_SFLOAT; case VK_FORMAT_R32G32_UINT: return ImageFormat::RG32_UINT; case VK_FORMAT_R32G32_SINT: return ImageFormat::RG32_SINT; case VK_FORMAT_R32G32_SFLOAT: return ImageFormat::RG32_SFLOAT; case VK_FORMAT_R32G32B32_UINT: return ImageFormat::RGB32_UINT; case VK_FORMAT_R32G32B32_SINT: return ImageFormat::RGB32_SINT; case VK_FORMAT_R32G32B32_SFLOAT: return ImageFormat::RGB32_SFLOAT; case VK_FORMAT_R32G32B32A32_UINT: return ImageFormat::RGBA32_UINT; case VK_FORMAT_R32G32B32A32_SINT: return ImageFormat::RGBA32_SINT; case VK_FORMAT_R32G32B32A32_SFLOAT: return ImageFormat::RGBA32_SFLOAT; // Color (64 bit components) case VK_FORMAT_R64_UINT: return ImageFormat::R64_UINT; case VK_FORMAT_R64_SINT: return ImageFormat::R64_SINT; case VK_FORMAT_R64_SFLOAT: return ImageFormat::R64_SFLOAT; case VK_FORMAT_R64G64_UINT: return ImageFormat::RG64_UINT; case VK_FORMAT_R64G64_SINT: return ImageFormat::RG64_SINT; case VK_FORMAT_R64G64_SFLOAT: return ImageFormat::RG64_SFLOAT; case VK_FORMAT_R64G64B64_UINT: return ImageFormat::RGB64_UINT; case VK_FORMAT_R64G64B64_SINT: return ImageFormat::RGB64_SINT; case VK_FORMAT_R64G64B64_SFLOAT: return ImageFormat::RGB64_SFLOAT; case VK_FORMAT_R64G64B64A64_UINT: return ImageFormat::RGBA64_UINT; case VK_FORMAT_R64G64B64A64_SINT: return ImageFormat::RGBA64_SINT; case VK_FORMAT_R64G64B64A64_SFLOAT: return ImageFormat::RGBA64_SFLOAT; // DepthStencil case VK_FORMAT_D32_SFLOAT: return ImageFormat::D32F; case VK_FORMAT_D32_SFLOAT_S8_UINT: return ImageFormat::D32F_S8U; case VK_FORMAT_D24_UNORM_S8_UINT: return ImageFormat::D24U_S8U; default: { ATEMA_ERROR("Invalid image format"); } } return ImageFormat::RGBA8_SRGB; } VkFormat Vulkan::getFormat(VertexFormat format) { switch (format) { case VertexFormat::R8_UINT: return VK_FORMAT_R8_UINT; case VertexFormat::R8_SINT: return VK_FORMAT_R8_SINT; case VertexFormat::RG8_UINT: return VK_FORMAT_R8G8_UINT; case VertexFormat::RG8_SINT: return VK_FORMAT_R8G8_SINT; case VertexFormat::RGB8_UINT: return VK_FORMAT_R8G8B8_UINT; case VertexFormat::RGB8_SINT: return VK_FORMAT_R8G8B8_SINT; case VertexFormat::RGBA8_UINT: return VK_FORMAT_R8G8B8A8_UINT; case VertexFormat::RGBA8_SINT: return VK_FORMAT_R8G8B8A8_SINT; case VertexFormat::R16_UINT: return VK_FORMAT_R16_UINT; case VertexFormat::R16_SINT: return VK_FORMAT_R16_SINT; case VertexFormat::R16_SFLOAT: return VK_FORMAT_R16_SFLOAT; case VertexFormat::RG16_UINT: return VK_FORMAT_R16G16_UINT; case VertexFormat::RG16_SINT: return VK_FORMAT_R16G16_SINT; case VertexFormat::RG16_SFLOAT: return VK_FORMAT_R16G16_SFLOAT; case VertexFormat::RGB16_UINT: return VK_FORMAT_R16G16B16_UINT; case VertexFormat::RGB16_SINT: return VK_FORMAT_R16G16B16_SINT; case VertexFormat::RGB16_SFLOAT: return VK_FORMAT_R16G16B16_SFLOAT; case VertexFormat::RGBA16_UINT: return VK_FORMAT_R16G16B16A16_UINT; case VertexFormat::RGBA16_SINT: return VK_FORMAT_R16G16B16A16_SINT; case VertexFormat::RGBA16_SFLOAT: return VK_FORMAT_R16G16B16A16_SFLOAT; case VertexFormat::R32_UINT: return VK_FORMAT_R32_UINT; case VertexFormat::R32_SINT: return VK_FORMAT_R32_SINT; case VertexFormat::R32_SFLOAT: return VK_FORMAT_R32_SFLOAT; case VertexFormat::RG32_UINT: return VK_FORMAT_R32G32_UINT; case VertexFormat::RG32_SINT: return VK_FORMAT_R32G32_SINT; case VertexFormat::RG32_SFLOAT: return VK_FORMAT_R32G32_SFLOAT; case VertexFormat::RGB32_UINT: return VK_FORMAT_R32G32B32_UINT; case VertexFormat::RGB32_SINT: return VK_FORMAT_R32G32B32_SINT; case VertexFormat::RGB32_SFLOAT: return VK_FORMAT_R32G32B32_SFLOAT; case VertexFormat::RGBA32_UINT: return VK_FORMAT_R32G32B32A32_UINT; case VertexFormat::RGBA32_SINT: return VK_FORMAT_R32G32B32A32_SINT; case VertexFormat::RGBA32_SFLOAT: return VK_FORMAT_R32G32B32A32_SFLOAT; case VertexFormat::R64_UINT: return VK_FORMAT_R64_UINT; case VertexFormat::R64_SINT: return VK_FORMAT_R64_SINT; case VertexFormat::R64_SFLOAT: return VK_FORMAT_R64_SFLOAT; case VertexFormat::RG64_UINT: return VK_FORMAT_R64G64_UINT; case VertexFormat::RG64_SINT: return VK_FORMAT_R64G64_SINT; case VertexFormat::RG64_SFLOAT: return VK_FORMAT_R64G64_SFLOAT; case VertexFormat::RGB64_UINT: return VK_FORMAT_R64G64B64_UINT; case VertexFormat::RGB64_SINT: return VK_FORMAT_R64G64B64_SINT; case VertexFormat::RGB64_SFLOAT: return VK_FORMAT_R64G64B64_SFLOAT; case VertexFormat::RGBA64_UINT: return VK_FORMAT_R64G64B64A64_UINT; case VertexFormat::RGBA64_SINT: return VK_FORMAT_R64G64B64A64_SINT; case VertexFormat::RGBA64_SFLOAT: return VK_FORMAT_R64G64B64A64_SFLOAT; default: { ATEMA_ERROR("Invalid vertex attribute format"); } } return VK_FORMAT_UNDEFINED; } VkImageAspectFlags Vulkan::getAspect(ImageFormat format) { VkImageAspectFlags aspect = 0; if (Renderer::isDepthImageFormat(format)) aspect |= VK_IMAGE_ASPECT_DEPTH_BIT; if (Renderer::isStencilImageFormat(format)) aspect |= VK_IMAGE_ASPECT_STENCIL_BIT; if (!aspect) aspect = VK_IMAGE_ASPECT_COLOR_BIT; return aspect; } VkImageTiling Vulkan::getTiling(ImageTiling tiling) { switch (tiling) { case ImageTiling::Optimal: return VK_IMAGE_TILING_OPTIMAL; case ImageTiling::Linear: return VK_IMAGE_TILING_LINEAR; default: { ATEMA_ERROR("Invalid image tiling"); } } return VK_IMAGE_TILING_LINEAR; } VkImageUsageFlags Vulkan::getUsages(Flags<ImageUsage> usages, bool isDepth) { VkImageUsageFlags flags = 0; if (usages & ImageUsage::RenderTarget) { if (isDepth) flags |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; else flags |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; } if (usages & ImageUsage::ShaderInput) { //TODO: See for VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT flags |= VK_IMAGE_USAGE_SAMPLED_BIT; } if (usages & ImageUsage::TransferSrc) { flags |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; } if (usages & ImageUsage::TransferDst) { flags |= VK_IMAGE_USAGE_TRANSFER_DST_BIT; } return flags; } VkImageLayout Vulkan::getLayout(ImageLayout layout, bool isDepth) { switch (layout) { case ImageLayout::Undefined: return VK_IMAGE_LAYOUT_UNDEFINED; case ImageLayout::Attachment: { if (isDepth) return VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; return VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; } case ImageLayout::ShaderInput: return VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; case ImageLayout::TransferSrc: return VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; case ImageLayout::TransferDst: return VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; case ImageLayout::Present: return VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; case ImageLayout::All: return VK_IMAGE_LAYOUT_GENERAL; default: { ATEMA_ERROR("Invalid image layout"); } } return VK_IMAGE_LAYOUT_GENERAL; } VkSampleCountFlagBits Vulkan::getSamples(ImageSamples samples) { switch (samples) { case ImageSamples::S1: return VK_SAMPLE_COUNT_1_BIT; case ImageSamples::S2: return VK_SAMPLE_COUNT_2_BIT; case ImageSamples::S4: return VK_SAMPLE_COUNT_4_BIT; case ImageSamples::S8: return VK_SAMPLE_COUNT_8_BIT; case ImageSamples::S16: return VK_SAMPLE_COUNT_16_BIT; case ImageSamples::S32: return VK_SAMPLE_COUNT_32_BIT; case ImageSamples::S64: return VK_SAMPLE_COUNT_64_BIT; default: { ATEMA_ERROR("Invalid image samples"); } } return VK_SAMPLE_COUNT_1_BIT; } Flags<ImageSamples> Vulkan::getSamples(VkSampleCountFlags samples) { Flags<ImageSamples> flags = 0; if (samples & VK_SAMPLE_COUNT_1_BIT) flags |= ImageSamples::S1; if (samples & VK_SAMPLE_COUNT_2_BIT) flags |= ImageSamples::S2; if (samples & VK_SAMPLE_COUNT_4_BIT) flags |= ImageSamples::S4; if (samples & VK_SAMPLE_COUNT_8_BIT) flags |= ImageSamples::S8; if (samples & VK_SAMPLE_COUNT_16_BIT) flags |= ImageSamples::S16; if (samples & VK_SAMPLE_COUNT_32_BIT) flags |= ImageSamples::S32; if (samples & VK_SAMPLE_COUNT_64_BIT) flags |= ImageSamples::S64; return flags; } VkAttachmentLoadOp Vulkan::getAttachmentLoading(AttachmentLoading value) { switch (value) { case AttachmentLoading::Undefined: return VK_ATTACHMENT_LOAD_OP_DONT_CARE; case AttachmentLoading::Clear: return VK_ATTACHMENT_LOAD_OP_CLEAR; case AttachmentLoading::Load: return VK_ATTACHMENT_LOAD_OP_LOAD; default: { ATEMA_ERROR("Invalid attachment load"); } } return VK_ATTACHMENT_LOAD_OP_DONT_CARE; } VkAttachmentStoreOp Vulkan::getAttachmentStoring(AttachmentStoring value) { switch (value) { case AttachmentStoring::Undefined: return VK_ATTACHMENT_STORE_OP_DONT_CARE; case AttachmentStoring::Store: return VK_ATTACHMENT_STORE_OP_STORE; default: { ATEMA_ERROR("Invalid attachment store"); } } return VK_ATTACHMENT_STORE_OP_DONT_CARE; } VkPrimitiveTopology Vulkan::getPrimitiveTopology(PrimitiveTopology value) { switch (value) { case PrimitiveTopology::PointList: return VK_PRIMITIVE_TOPOLOGY_POINT_LIST; case PrimitiveTopology::LineList: return VK_PRIMITIVE_TOPOLOGY_LINE_LIST; case PrimitiveTopology::LineStrip: return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP; case PrimitiveTopology::TriangleList: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; case PrimitiveTopology::TriangleStrip: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP; case PrimitiveTopology::TriangleFan: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN; case PrimitiveTopology::LineListAdjacency: return VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY; case PrimitiveTopology::LineStripAdjacency: return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY; case PrimitiveTopology::TriangleListAdjacency: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY; case PrimitiveTopology::TriangleStripAdjacency: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY; case PrimitiveTopology::PatchList: return VK_PRIMITIVE_TOPOLOGY_PATCH_LIST; default: { ATEMA_ERROR("Invalid primitive topology"); } } return VK_PRIMITIVE_TOPOLOGY_POINT_LIST; } VkPolygonMode Vulkan::getPolygonMode(PolygonMode value) { switch (value) { case PolygonMode::Fill: return VK_POLYGON_MODE_FILL; case PolygonMode::Line: return VK_POLYGON_MODE_LINE; case PolygonMode::Point: return VK_POLYGON_MODE_POINT; default: { ATEMA_ERROR("Invalid polygon mode"); } } return VK_POLYGON_MODE_FILL; } VkCullModeFlags Vulkan::getCullMode(Flags<CullMode> value) { VkCullModeFlags flags = 0; if (value & CullMode::Front) flags |= VK_CULL_MODE_FRONT_BIT; if (value & CullMode::Back) flags |= VK_CULL_MODE_BACK_BIT; return flags; } VkFrontFace Vulkan::getFrontFace(FrontFace value) { switch (value) { case FrontFace::Clockwise: return VK_FRONT_FACE_CLOCKWISE; case FrontFace::CounterClockwise: return VK_FRONT_FACE_COUNTER_CLOCKWISE; default: { ATEMA_ERROR("Invalid front face"); } } return VK_FRONT_FACE_CLOCKWISE; } VkBlendOp Vulkan::getBlendOperation(BlendOperation value) { switch (value) { case BlendOperation::Add: return VK_BLEND_OP_ADD; case BlendOperation::Subtract: return VK_BLEND_OP_SUBTRACT; case BlendOperation::ReverseSubtract: return VK_BLEND_OP_REVERSE_SUBTRACT; case BlendOperation::Min: return VK_BLEND_OP_MIN; case BlendOperation::Max: return VK_BLEND_OP_MAX; default: { ATEMA_ERROR("Invalid blend operation"); } } return VK_BLEND_OP_ADD; } VkBlendFactor Vulkan::getBlendFactor(BlendFactor value) { switch (value) { case BlendFactor::Zero: return VK_BLEND_FACTOR_ZERO; case BlendFactor::One: return VK_BLEND_FACTOR_ONE; case BlendFactor::SrcColor: return VK_BLEND_FACTOR_SRC_COLOR; case BlendFactor::OneMinusSrcColor: return VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR; case BlendFactor::DstColor: return VK_BLEND_FACTOR_DST_COLOR; case BlendFactor::OneMinusDstColor: return VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR; case BlendFactor::SrcAlpha: return VK_BLEND_FACTOR_SRC_ALPHA; case BlendFactor::OneMinusSrcAlpha: return VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; case BlendFactor::DstAlpha: return VK_BLEND_FACTOR_DST_ALPHA; case BlendFactor::OneMinusDstAlpha: return VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA; case BlendFactor::ConstantColor: return VK_BLEND_FACTOR_CONSTANT_COLOR; case BlendFactor::OneMinusConstantColor: return VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR; case BlendFactor::ConstantAlpha: return VK_BLEND_FACTOR_CONSTANT_ALPHA; case BlendFactor::OneMinusConstantAlpha: return VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA; default: { ATEMA_ERROR("Invalid blend factor"); } } return VK_BLEND_FACTOR_ZERO; } VkCompareOp Vulkan::getCompareOperation(CompareOperation value) { switch (value) { case CompareOperation::Never: return VK_COMPARE_OP_NEVER; case CompareOperation::Less: return VK_COMPARE_OP_LESS; case CompareOperation::Equal: return VK_COMPARE_OP_EQUAL; case CompareOperation::LessOrEqual: return VK_COMPARE_OP_LESS_OR_EQUAL; case CompareOperation::Greater: return VK_COMPARE_OP_GREATER; case CompareOperation::NotEqual: return VK_COMPARE_OP_NOT_EQUAL; case CompareOperation::GreaterOrEqual: return VK_COMPARE_OP_GREATER_OR_EQUAL; case CompareOperation::Always: return VK_COMPARE_OP_ALWAYS; default: { ATEMA_ERROR("Invalid compare operation"); } } return VK_COMPARE_OP_LESS; } VkStencilOp Vulkan::getStencilOperation(StencilOperation value) { switch (value) { case StencilOperation::Keep: return VK_STENCIL_OP_KEEP; case StencilOperation::Zero: return VK_STENCIL_OP_ZERO; case StencilOperation::Replace: return VK_STENCIL_OP_REPLACE; case StencilOperation::IncrementAndClamp: return VK_STENCIL_OP_INCREMENT_AND_CLAMP; case StencilOperation::DecrementAndClamp: return VK_STENCIL_OP_DECREMENT_AND_CLAMP; case StencilOperation::Invert: return VK_STENCIL_OP_INVERT; case StencilOperation::IncrementAndWrap: return VK_STENCIL_OP_INCREMENT_AND_WRAP; case StencilOperation::DecrementAndWrap: return VK_STENCIL_OP_DECREMENT_AND_WRAP; default: { ATEMA_ERROR("Invalid stencil operation"); } } return VK_STENCIL_OP_KEEP; } VkDescriptorType Vulkan::getDescriptorType(DescriptorType value) { switch (value) { case DescriptorType::Sampler: return VK_DESCRIPTOR_TYPE_SAMPLER; case DescriptorType::CombinedImageSampler: return VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; case DescriptorType::SampledImage: return VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; case DescriptorType::StorageImage: return VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; case DescriptorType::UniformTexelBuffer: return VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER; case DescriptorType::StorageTexelBuffer: return VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER; case DescriptorType::UniformBuffer: return VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; case DescriptorType::StorageBuffer: return VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; case DescriptorType::UniformBufferDynamic: return VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; case DescriptorType::StorageBufferDynamic: return VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC; case DescriptorType::InputAttachment: return VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT; default: { ATEMA_ERROR("Invalid descriptor type"); } } return VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; } VkShaderStageFlags Vulkan::getShaderStages(Flags<ShaderStage> value) { VkShaderStageFlags flags = 0; if (value & ShaderStage::Vertex) flags |= VK_SHADER_STAGE_VERTEX_BIT; if (value & ShaderStage::TessellationControl) flags |= VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT; if (value & ShaderStage::TessellationEvaluation) flags |= VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT; if (value & ShaderStage::Geometry) flags |= VK_SHADER_STAGE_GEOMETRY_BIT; if (value & ShaderStage::Fragment) flags |= VK_SHADER_STAGE_FRAGMENT_BIT; if (value & ShaderStage::Compute) flags |= VK_SHADER_STAGE_COMPUTE_BIT; return flags; } VkPipelineStageFlags Vulkan::getPipelineStages(Flags<PipelineStage> value) { VkShaderStageFlags flags = 0; if (value & PipelineStage::TopOfPipe) flags |= VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; if (value & PipelineStage::DrawIndirect) flags |= VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT; if (value & PipelineStage::VertexInput) flags |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT; if (value & PipelineStage::VertexShader) flags |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT; if (value & PipelineStage::TessellationControl) flags |= VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT; if (value & PipelineStage::TessellationEvaluation) flags |= VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT; if (value & PipelineStage::GeometryShader) flags |= VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT; if (value & PipelineStage::FragmentShader) flags |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; if (value & PipelineStage::EarlyFragmentTests) flags |= VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT; if (value & PipelineStage::LateFragmentTests) flags |= VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; if (value & PipelineStage::ColorAttachmentOutput) flags |= VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; if (value & PipelineStage::ComputeShader) flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; if (value & PipelineStage::Transfer) flags |= VK_PIPELINE_STAGE_TRANSFER_BIT; if (value & PipelineStage::BottomOfPipe) flags |= VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; if (value & PipelineStage::Host) flags |= VK_PIPELINE_STAGE_HOST_BIT; return flags; } VkBufferUsageFlags Vulkan::getBufferUsages(BufferUsage value) { switch (value) { case BufferUsage::Vertex: return VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; case BufferUsage::Index: return VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; case BufferUsage::Uniform: return VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; case BufferUsage::Transfer: return VK_BUFFER_USAGE_TRANSFER_SRC_BIT; default: { ATEMA_ERROR("Invalid buffer usage"); } } return 0; } VkMemoryPropertyFlags Vulkan::getMemoryProperties(bool mappable) { // Try to go for device memory unless we need to be mappable if (mappable) return VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; return VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; } VkIndexType Vulkan::getIndexType(IndexType value) { switch (value) { case IndexType::U16: return VK_INDEX_TYPE_UINT16; case IndexType::U32: return VK_INDEX_TYPE_UINT32; default: { ATEMA_ERROR("Invalid index type"); } } return VK_INDEX_TYPE_UINT32; } VkFilter Vulkan::getSamplerFilter(SamplerFilter value) { switch (value) { case SamplerFilter::Nearest: return VK_FILTER_NEAREST; case SamplerFilter::Linear: return VK_FILTER_LINEAR; default: { ATEMA_ERROR("Invalid sampler filter"); } } return VK_FILTER_NEAREST; } VkSamplerAddressMode Vulkan::getSamplerAddressMode(SamplerAddressMode value) { switch (value) { case SamplerAddressMode::Repeat: return VK_SAMPLER_ADDRESS_MODE_REPEAT; case SamplerAddressMode::MirroredRepeat: return VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT; case SamplerAddressMode::ClampToEdge: return VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; case SamplerAddressMode::ClampToBorder: return VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER; default: { ATEMA_ERROR("Invalid sampler address mode"); } } return VK_SAMPLER_ADDRESS_MODE_REPEAT; } VkSamplerMipmapMode Vulkan::getSamplerMipmapMode(SamplerFilter value) { switch (value) { case SamplerFilter::Nearest: return VK_SAMPLER_MIPMAP_MODE_NEAREST; case SamplerFilter::Linear: return VK_SAMPLER_MIPMAP_MODE_LINEAR; default: { ATEMA_ERROR("Invalid sampler filter"); } } return VK_SAMPLER_MIPMAP_MODE_NEAREST; } SwapChainResult Vulkan::getSwapChainResult(VkResult value) { switch (value) { case VK_SUCCESS: return SwapChainResult::Success; case VK_NOT_READY: return SwapChainResult::NotReady; case VK_SUBOPTIMAL_KHR: return SwapChainResult::Suboptimal; case VK_ERROR_OUT_OF_DATE_KHR: case VK_ERROR_SURFACE_LOST_KHR: return SwapChainResult::OutOfDate; case VK_ERROR_OUT_OF_HOST_MEMORY: case VK_ERROR_OUT_OF_DEVICE_MEMORY: case VK_ERROR_DEVICE_LOST: case VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT: case VK_TIMEOUT: default: { break; } } return SwapChainResult::Error; }
37.841924
109
0.819106
[ "geometry" ]
97206b8c87f34ed644d90a4385733b03b4461afc
9,525
cc
C++
src/yb/yql/pggate/pg_operation_buffer.cc
tverona1/yugabyte-db
5099526ca75c25acf893e9bacda7aad33fabf6c8
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
src/yb/yql/pggate/pg_operation_buffer.cc
tverona1/yugabyte-db
5099526ca75c25acf893e9bacda7aad33fabf6c8
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
src/yb/yql/pggate/pg_operation_buffer.cc
tverona1/yugabyte-db
5099526ca75c25acf893e9bacda7aad33fabf6c8
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
// Copyright (c) YugaByte, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing permissions and limitations // under the License. // #include "yb/yql/pggate/pg_operation_buffer.h" #include <string> #include <ostream> #include <unordered_set> #include <utility> #include <vector> #include "yb/common/constants.h" #include "yb/common/pgsql_protocol.pb.h" #include "yb/common/ql_expr.h" #include "yb/common/ql_value.h" #include "yb/common/schema.h" #include "yb/docdb/doc_key.h" #include "yb/docdb/primitive_value.h" #include "yb/docdb/value_type.h" #include "yb/gutil/casts.h" #include "yb/gutil/port.h" #include "yb/util/lw_function.h" #include "yb/util/status.h" #include "yb/yql/pggate/pg_op.h" #include "yb/yql/pggate/pg_tabledesc.h" #include "yb/yql/pggate/pggate_flags.h" namespace yb { namespace pggate { namespace { docdb::KeyEntryValue NullValue(SortingType sorting) { using SortingType = SortingType; return docdb::KeyEntryValue( sorting == SortingType::kAscendingNullsLast || sorting == SortingType::kDescendingNullsLast ? docdb::KeyEntryType::kNullHigh : docdb::KeyEntryType::kNullLow); } std::vector<docdb::KeyEntryValue> InitKeyColumnPrimitiveValues( const ArenaList<LWPgsqlExpressionPB> &column_values, const Schema &schema, size_t start_idx) { std::vector<docdb::KeyEntryValue> result; size_t column_idx = start_idx; for (const auto& column_value : column_values) { const auto sorting_type = schema.column(column_idx).sorting_type(); if (column_value.has_value()) { const auto& value = column_value.value(); result.push_back( IsNull(value) ? NullValue(sorting_type) : docdb::KeyEntryValue::FromQLValuePB(value, sorting_type)); } else { // TODO(neil) The current setup only works for CQL as it assumes primary key value must not // be dependent on any column values. This needs to be fixed as PostgreSQL expression might // require a read from a table. // // Use regular executor for now. QLExprExecutor executor; LWExprResult expr_result(&column_value.arena()); auto s = executor.EvalExpr(column_value, nullptr, expr_result.Writer()); result.push_back(docdb::KeyEntryValue::FromQLValuePB(expr_result.Value(), sorting_type)); } ++column_idx; } return result; } // Represents row id (ybctid) from the DocDB's point of view. class RowIdentifier { public: RowIdentifier( const PgObjectId& table_id, const Schema& schema, const LWPgsqlWriteRequestPB& request) : table_id_(table_id) { if (request.has_ybctid_column_value()) { ybctid_ = request.ybctid_column_value().value().binary_value(); } else { auto hashed_components = InitKeyColumnPrimitiveValues( request.partition_column_values(), schema, 0 /* start_idx */); auto range_components = InitKeyColumnPrimitiveValues( request.range_column_values(), schema, schema.num_hash_key_columns()); if (hashed_components.empty()) { ybctid_holder_ = docdb::DocKey(std::move(range_components)).Encode().ToStringBuffer(); } else { ybctid_holder_ = docdb::DocKey(request.hash_code(), std::move(hashed_components), std::move(range_components)).Encode().ToStringBuffer(); } ybctid_ = Slice(static_cast<const char*>(nullptr), static_cast<size_t>(0)); } } Slice ybctid() const { return ybctid_.data() ? ybctid_ : ybctid_holder_; } const PgObjectId& table_id() const { return table_id_; } private: friend bool operator==(const RowIdentifier& k1, const RowIdentifier& k2); PgObjectId table_id_; Slice ybctid_; std::string ybctid_holder_; }; bool operator==(const RowIdentifier& k1, const RowIdentifier& k2) { return k1.table_id() == k2.table_id() && k1.ybctid() == k2.ybctid(); } size_t hash_value(const RowIdentifier& key) { size_t hash = 0; boost::hash_combine(hash, key.table_id()); boost::hash_combine(hash, key.ybctid()); return hash; } inline bool IsTableUsedByRequest(const LWPgsqlReadRequestPB& request, const Slice& table_id) { return request.table_id() == table_id || (request.has_index_request() && IsTableUsedByRequest(request.index_request(), table_id)); } } // namespace void BufferableOperations::Add(PgsqlOpPtr op, const PgObjectId& relation) { operations.push_back(std::move(op)); relations.push_back(relation); } void BufferableOperations::Swap(BufferableOperations* rhs) { operations.swap(rhs->operations); relations.swap(rhs->relations); } void BufferableOperations::Clear() { operations.clear(); relations.clear(); } void BufferableOperations::Reserve(size_t capacity) { operations.reserve(capacity); relations.reserve(capacity); } bool BufferableOperations::empty() const { return operations.empty(); } size_t BufferableOperations::size() const { return operations.size(); } class PgOperationBuffer::Impl { public: explicit Impl(const Flusher& flusher) : flusher_(flusher) { } CHECKED_STATUS Add(const PgTableDesc& table, PgsqlWriteOpPtr op, bool transactional) { // Check for buffered operation related to same row. // If multiple operations are performed in context of single RPC second operation will not // see the results of first operation on DocDB side. // Multiple operations on same row must be performed in context of different RPC. // Flush is required in this case. RowIdentifier row_id(table.id(), table.schema(), op->write_request()); if (PREDICT_FALSE(!keys_.insert(row_id).second)) { RETURN_NOT_OK(Flush()); keys_.insert(row_id); } auto& target = (transactional ? txn_ops_ : ops_); if (target.empty()) { target.Reserve(FLAGS_ysql_session_max_batch_size); } target.Add(std::move(op), table.id()); return keys_.size() >= FLAGS_ysql_session_max_batch_size ? Flush() : Status::OK(); } CHECKED_STATUS Flush() { return DoFlush(make_lw_function([this](BufferableOperations ops, bool txn) { return ResultToStatus(VERIFY_RESULT(flusher_(std::move(ops), txn)).Get()); })); } Result<BufferableOperations> FlushTake( const PgTableDesc& table, const PgsqlOp& op, bool transactional) { BufferableOperations result; if (IsFullFlushRequired(table, op)) { RETURN_NOT_OK(Flush()); } else { RETURN_NOT_OK(DoFlush(make_lw_function( [this, transactional, &result](BufferableOperations ops, bool txn) -> Status { if (txn == transactional) { ops.Swap(&result); return Status::OK(); } return ResultToStatus(VERIFY_RESULT(flusher_(std::move(ops), txn)).Get()); }))); } return result; } size_t Size() const { return keys_.size(); } void Clear() { VLOG_IF(1, !keys_.empty()) << "Dropping " << keys_.size() << " pending operations"; ops_.Clear(); txn_ops_.Clear(); keys_.clear(); } private: using SyncFlusher = LWFunction<Status(BufferableOperations, bool)>; CHECKED_STATUS DoFlush(const SyncFlusher& flusher) { BufferableOperations ops; BufferableOperations txn_ops; ops_.Swap(&ops); txn_ops_.Swap(&txn_ops); keys_.clear(); if (!ops.empty()) { RETURN_NOT_OK(flusher(std::move(ops), false /* transactional */)); } if (!txn_ops.empty()) { RETURN_NOT_OK(flusher(std::move(txn_ops), true /* transactional */)); } return Status::OK(); } bool IsFullFlushRequired(const PgTableDesc& table, const PgsqlOp& op) const { return op.is_read() ? IsSameTableUsedByBufferedOperations(down_cast<const PgsqlReadOp&>(op).read_request()) : keys_.find(RowIdentifier( table.id(), table.schema(), down_cast<const PgsqlWriteOp&>(op).write_request())) != keys_.end(); } bool IsSameTableUsedByBufferedOperations(const LWPgsqlReadRequestPB& request) const { for (const auto& k : keys_) { if (IsTableUsedByRequest(request, k.table_id().GetYbTableId())) { return true; } } return false; } const Flusher flusher_; BufferableOperations ops_; BufferableOperations txn_ops_; std::unordered_set<RowIdentifier, boost::hash<RowIdentifier>> keys_; }; PgOperationBuffer::PgOperationBuffer(const Flusher& flusher) : impl_(new Impl(flusher)) { } PgOperationBuffer::~PgOperationBuffer() = default; Status PgOperationBuffer::Add(const PgTableDesc& table, PgsqlWriteOpPtr op, bool transactional) { return impl_->Add(table, std::move(op), transactional); } CHECKED_STATUS PgOperationBuffer::Flush() { return impl_->Flush(); } Result<BufferableOperations> PgOperationBuffer::FlushTake( const PgTableDesc& table, const PgsqlOp& op, bool transactional) { return impl_->FlushTake(table, op, transactional); } size_t PgOperationBuffer::Size() const { return impl_->Size(); } void PgOperationBuffer::Clear() { impl_->Clear(); } } // namespace pggate } // namespace yb
31.229508
100
0.691129
[ "vector" ]
972db7dc0eaa3a2e8857827106bec8290e41238e
838
cpp
C++
src/ScriptComponent.cpp
Ravbug/RavEngine
73249827cb2cd3c938bb59447e9edbf7b6f0defc
[ "Apache-2.0" ]
48
2020-11-18T23:14:25.000Z
2022-03-11T09:13:42.000Z
src/ScriptComponent.cpp
Ravbug/RavEngine
73249827cb2cd3c938bb59447e9edbf7b6f0defc
[ "Apache-2.0" ]
1
2020-11-17T20:53:10.000Z
2020-12-01T20:27:36.000Z
src/ScriptComponent.cpp
Ravbug/RavEngine
73249827cb2cd3c938bb59447e9edbf7b6f0defc
[ "Apache-2.0" ]
3
2020-12-22T02:40:39.000Z
2021-10-08T02:54:22.000Z
#include "ScriptComponent.hpp" #include "Ref.hpp" #include "Entity.hpp" #include "World.hpp" using namespace RavEngine; bool RavEngine::ScriptComponent::Destroy() { auto owner = GetOwner().lock(); if (owner) { owner->Destroy(); return true; } return false; } bool RavEngine::ScriptComponent::IsInWorld() { auto owner = GetOwner().lock(); return owner && owner->IsInWorld(); } Ref<Transform> RavEngine::ScriptComponent::GetTransform() { auto owner = GetOwner().lock(); if (!owner) { throw std::runtime_error("Cannot get transform from Script with no attached Entity"); } return owner->GetTransform(); } Ref<RavEngine::World> RavEngine::ScriptComponent::GetWorld() { auto owner = Ref<Entity>(GetOwner()); if (!owner) { return nullptr; } return owner->GetWorld().lock(); }
20.439024
88
0.664678
[ "transform" ]
972dbbc55cb18e2d462403521ac7bab9843ff3fb
789
cpp
C++
cpp-linear-search/cpp-linear-search-2.cpp
rohanghosh7/Linear-Search
185840648e1942a3124d2d3bd00548aacd0716d4
[ "MIT" ]
23
2018-04-23T05:57:53.000Z
2020-03-29T02:05:24.000Z
cpp-linear-search/cpp-linear-search-2.cpp
rohanghosh7/Linear-Search
185840648e1942a3124d2d3bd00548aacd0716d4
[ "MIT" ]
44
2018-04-23T06:06:30.000Z
2019-10-20T05:44:07.000Z
cpp-linear-search/cpp-linear-search-2.cpp
rohanghosh7/Linear-Search
185840648e1942a3124d2d3bd00548aacd0716d4
[ "MIT" ]
134
2018-09-18T09:18:37.000Z
2022-03-09T05:42:03.000Z
/* STL IMPLEMENTATION OF LINEAR SEARCH IN C++ ~By Rahul Suresh (http://github.com/icy-meteor)~*/ //Header Files #include <iostream> #include <vector> using namespace std; //Main Function int main() { int a,n,key; vector<int> vec; vector<int>::iterator it; cout<<"Enter number of elements : "; cin>>n; cout<<"Enter element to search : "; cin>>key; for(int i=0;i<n;i++) //Pushing elements to vector { cin>>a; vec.push_back(a); } for(it=vec.begin();it!=vec.end();it++) //Comparing each element with key { if((*it)==key) { cout<<"Element "<<key<<" found at "<<(it-vec.begin())+1<<" position!"; return 0; } } cout<<"Element not found!"; return 0; }
21.324324
82
0.536122
[ "vector" ]
97358af550e7b93c1dec24e05e4e29bb7f0604fd
2,206
cpp
C++
services/se_standard/src/general-data-objects/response_all_ar_do.cpp
dawmlight/communication_nfc
84a10d69eb9cb3128e864230c53d5a5e6660dfb9
[ "Apache-2.0" ]
null
null
null
services/se_standard/src/general-data-objects/response_all_ar_do.cpp
dawmlight/communication_nfc
84a10d69eb9cb3128e864230c53d5a5e6660dfb9
[ "Apache-2.0" ]
null
null
null
services/se_standard/src/general-data-objects/response_all_ar_do.cpp
dawmlight/communication_nfc
84a10d69eb9cb3128e864230c53d5a5e6660dfb9
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "response_all_ar_do.h" #include "loghelper.h" #include "ref_ar_do.h" #include "se_common_exception.h" namespace OHOS::se::security { ResponseAllArDo::ResponseAllArDo(std::shared_ptr<BerTlv> berTlv, std::vector<RefArDo> refArDoArray) : BerTlv(berTlv->GetTag(), berTlv->GetLength(), berTlv->GetValue()), refArDoArray_(refArDoArray) { } ResponseAllArDo::~ResponseAllArDo() {} std::vector<RefArDo> ResponseAllArDo::GetRefArDoArray() { return refArDoArray_; } std::shared_ptr<ResponseAllArDo> ResponseAllArDo::BerTlvToResponseAllArDo(std::shared_ptr<BerTlv> berTlv) { int tag = berTlv->GetTag(); int length = berTlv->GetLength(); std::string value = berTlv->GetValue(); if (tag != RESPONSE_ALL_AR_DO_TAG) { ErrorLog("Invalid tag in ResponseAllArDo"); throw AccessControlError("Parsing data error"); } if (length > (int)value.length()) { ErrorLog("Value length not enough in ResponseAllArDo"); throw AccessControlError("Parsing data error"); } std::vector<RefArDo> refArDoArray; int remainLength = length; std::string remainValue = value; while (remainLength > 0) { std::shared_ptr<BerTlv> bt = BerTlv::StrToBerTlv(remainValue); std::shared_ptr<RefArDo> rad = RefArDo::BerTlvToRefArDo(bt); if (rad) { refArDoArray.push_back(*rad); } remainValue = remainValue.substr((bt->GetData()).length()); remainLength -= (bt->GetData()).length(); } return std::make_shared<ResponseAllArDo>(berTlv, refArDoArray); } } // namespace OHOS::se::security
35.580645
105
0.697189
[ "vector" ]
97371ed75ffbd93194d6a75276c29781c6ebc043
530
cpp
C++
src/tests/nnet_test.cpp
PandoraLS/PercepNet
cf3394e806280abef9823c0f889a32efc7ac6f7c
[ "BSD-3-Clause" ]
null
null
null
src/tests/nnet_test.cpp
PandoraLS/PercepNet
cf3394e806280abef9823c0f889a32efc7ac6f7c
[ "BSD-3-Clause" ]
null
null
null
src/tests/nnet_test.cpp
PandoraLS/PercepNet
cf3394e806280abef9823c0f889a32efc7ac6f7c
[ "BSD-3-Clause" ]
null
null
null
#include "nnet.h" #include "nnet_data.h" #include <vector> #include <stdio.h> int main(){ std::vector<float> fc_input(fc.nb_inputs, 0.5); std::vector<float> fc_output_c(fc.nb_neurons, 0); compute_dense(&fc, &fc_output_c[0], &fc_input[0]); for(int i=0; i<fc_output_c.size(); i++){ if(fc_output[i] != fc_output_c[i]){ printf("fail"); return 0; } } //compute_conv1d() //compute_gru(rnn->model->gb_gru, rnn->gb_gru_state, rnn->gru3_state); return 0; }
25.238095
74
0.586792
[ "vector", "model" ]
9737ea386f14c8f961fa912bdc6f72257c3bd5be
2,876
cpp
C++
src/Engine/PieceTypes/ChuShogi/FlyingStag.cpp
jweathers777/mShogi
941cd4dc37e6e6210d4f993c96a553753e228b19
[ "BSD-3-Clause" ]
4
2015-12-24T04:52:48.000Z
2021-11-09T11:31:36.000Z
src/Engine/PieceTypes/ChuShogi/FlyingStag.cpp
jweathers777/mShogi
941cd4dc37e6e6210d4f993c96a553753e228b19
[ "BSD-3-Clause" ]
null
null
null
src/Engine/PieceTypes/ChuShogi/FlyingStag.cpp
jweathers777/mShogi
941cd4dc37e6e6210d4f993c96a553753e228b19
[ "BSD-3-Clause" ]
null
null
null
//////////////////////////////////////////////////////////////////////////// // Name: FlyingStag.cpp // Description: Implementation for a class that represents a flying stag // Created: 08/31/2004 09:38:15 Eastern Daylight Time // Last Updated: $Date: 2004/09/18 22:23:06 $ // Revision: $Revision: 1.1 $ // Author: John Weathers // Email: hotanguish@hotmail.com // Copyright: (c) 2004 John Weathers //////////////////////////////////////////////////////////////////////////// // mShogi header files #include "FlyingStag.hpp" #include "Piece.hpp" #include "Move.hpp" #include "Board.hpp" using std::vector; using std::string; //-------------------------------------------------------------------------- // Class: FlyingStag // Method: FlyingStag // Description: Constructs an instance of a flying stag //-------------------------------------------------------------------------- FlyingStag::FlyingStag(Board* board, int value, int typevalue) { mpBoard = board; mValue = value; mTypeValue = typevalue; mSize = mpBoard->GetSize(); mNotation = "FS"; mNames[0] = "Flying Stag"; mNames[1] = "Hiroku"; mDescription = "Moves 1 square in any direction except vertically or any number of squares vertically"; // Set the size of the directions vector mDirections.resize(DIRECTION_COUNT); // Set up the directional method pointers mDirections[NORTH] = &Board::North; mDirections[SOUTH] = &Board::South; // Initialize flying stag's static attack patterns mStaticAttackBitboards = new Bitboard [mSize]; int square, nextsquare; for (square = 0; square < mSize; square++) { mStaticAttackBitboards[square].resize(mSize); // northwest nextsquare = mpBoard->NorthWest(0, square); if (nextsquare != Board::OFF_BOARD) { mStaticAttackBitboards[square].set(nextsquare); } // northeast nextsquare = mpBoard->NorthEast(0, square); if (nextsquare != Board::OFF_BOARD) { mStaticAttackBitboards[square].set(nextsquare); } // west nextsquare = mpBoard->West(0, square); if (nextsquare != Board::OFF_BOARD) { mStaticAttackBitboards[square].set(nextsquare); } // east nextsquare = mpBoard->East(0, square); if (nextsquare != Board::OFF_BOARD) { mStaticAttackBitboards[square].set(nextsquare); } // southwest nextsquare = mpBoard->SouthWest(0, square); if (nextsquare != Board::OFF_BOARD) { mStaticAttackBitboards[square].set(nextsquare); } // southeast nextsquare = mpBoard->SouthEast(0, square); if (nextsquare != Board::OFF_BOARD) { mStaticAttackBitboards[square].set(nextsquare); } } // Initialize flying stag's dynamic attack patterns InitAttackPatterns(); }
32.681818
94
0.576495
[ "vector" ]
9739bb8a55ed11f89e3980d0edaf8488536ee0eb
3,014
cpp
C++
gpu/face_detect/call_gpu.cpp
Mingcong/hadoop-1.2.1-cpu-gpu
da1c60956e548502a5964232fff406a606b964e1
[ "Apache-2.0" ]
null
null
null
gpu/face_detect/call_gpu.cpp
Mingcong/hadoop-1.2.1-cpu-gpu
da1c60956e548502a5964232fff406a606b964e1
[ "Apache-2.0" ]
null
null
null
gpu/face_detect/call_gpu.cpp
Mingcong/hadoop-1.2.1-cpu-gpu
da1c60956e548502a5964232fff406a606b964e1
[ "Apache-2.0" ]
null
null
null
#include "com_smc_vidproc_call_gpu.h" #include <iostream> #include <opencv2/core/core.hpp> #include <opencv2/contrib/contrib.hpp> #include <opencv2/objdetect/objdetect.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/gpu/gpu.hpp> #include <vector> using namespace std; using namespace cv; using namespace cv::gpu; JNIEXPORT jint JNICALL Java_com_smc_vidproc_call_1gpu_detect (JNIEnv *env, jclass, jstring video_in, jstring video_out) { double t = (double)getTickCount(); const char* in; const char* out; in = env->GetStringUTFChars(video_in, 0); out = env->GetStringUTFChars(video_out, 0); if(in == NULL || out == NULL) { std::cout << "fail to pass parameters!" << endl; return 0; /* OutOfMemoryError already thrown */ } std::cout << "video_in:" << in << "video_out:" << out <<std::endl; string cascadeName = "/home/ideal/hadoop-1.2.1/classifier/haarcascade_frontalface_alt.xml"; VideoCapture capture(in); if(!capture.isOpened()) { cout << "can not open video" << endl; return 0; } double fps = capture.get(CV_CAP_PROP_FPS); //get the width of frames of the video double dWidth = capture.get(CV_CAP_PROP_FRAME_WIDTH); //get the width of frames of the video double dHeight = capture.get(CV_CAP_PROP_FRAME_HEIGHT); //get the height of frames of the video cout << "Frame Size = " << dWidth << "x" << dHeight << endl; cout << "FPS = " << fps<< endl; Size frameSize(static_cast<int>(dWidth), static_cast<int>(dHeight)); VideoWriter v_o (out, CV_FOURCC('D','I','V','X'), fps, frameSize, true); //initialize the VideoWriter objec env->ReleaseStringUTFChars(video_in, in); env->ReleaseStringUTFChars(video_out, out); CascadeClassifier_GPU cascade_gpu; int gpuCnt = getCudaEnabledDeviceCount(); // gpuCnt >0 if CUDA device detected if(gpuCnt==0) { cout << "can not gpu" << endl; return 0; } if(!cascade_gpu.load(cascadeName)) { return 0; } Mat frame; capture >> frame; while(frame.data) { GpuMat faces; Mat frame_gray; cvtColor(frame, frame_gray, CV_BGR2GRAY); GpuMat gray_gpu(frame_gray); equalizeHist(frame_gray,frame_gray); int detect_num = cascade_gpu.detectMultiScale( gray_gpu, faces, 1.2, 4, Size(20, 20) ); Mat obj_host; faces.colRange(0, detect_num).download(obj_host); Rect* cfaces = obj_host.ptr<Rect>(); for(int i=0;i<detect_num;++i) { Point pt1 = cfaces[i].tl(); Size sz = cfaces[i].size(); Point pt2(pt1.x+sz.width, pt1.y+sz.height); rectangle(frame, pt1, pt2, Scalar(255)); } // imshow("faces", frame); // if(waitKey(2)==27) break; v_o.write(frame); capture >> frame; } capture.release(); v_o.release(); cascade_gpu.release(); t=((double)getTickCount()-t)/getTickFrequency(); cout << "processing time: " << t << endl; return 1; }
29.841584
108
0.647313
[ "vector" ]
973d0d04272dae49b9dfea6cac51b64e462b270c
757
cc
C++
src/util/fhist.cc
jinnaiyuu/pbnf
d197723e7499a91e2c15042de243ccab2cb0f9d5
[ "MIT" ]
4
2019-03-19T17:31:33.000Z
2022-01-08T12:27:33.000Z
src/util/fhist.cc
jinnaiyuu/pbnf
d197723e7499a91e2c15042de243ccab2cb0f9d5
[ "MIT" ]
null
null
null
src/util/fhist.cc
jinnaiyuu/pbnf
d197723e7499a91e2c15042de243ccab2cb0f9d5
[ "MIT" ]
1
2019-04-26T08:17:22.000Z
2019-04-26T08:17:22.000Z
// © 2014 the PBNF Authors under the MIT license. See AUTHORS for the list of authors. /** * \file fhist.cc * * A histogram of f values. * * \author eaburns * \date 08-09-2010 */ #include "fhist.h" #include "mutex.h" #include "fixed_point.h" #include <iostream> #include <vector> void F_hist::see_f(fp_type f) { unsigned long fint = (unsigned long) DOUBLE(f); if (Thread::current()) mutex.lock(); if (counts.size() < fint + 1) counts.resize(fint + 1); counts[fint] += 1; if (Thread::current()) mutex.unlock(); } void F_hist::output_above(std::ostream &o, fp_type opt) { for (unsigned int i = 0; i < counts.size(); i += 1) { if (counts[i] > 0) { o << (i / (double) DOUBLE(opt)) << '\t' << counts[i] << std::endl; } } }
18.02381
86
0.607662
[ "vector" ]
973f6c809f3faa0dd28e073c0accdd5f58cf3573
15,792
cpp
C++
MainGame/drawables/TextDrawable.cpp
JoaoBaptMG/ReboundTheGame
48c3d8b81de1f7fa7c622c3f815860257ccdba8e
[ "MIT" ]
63
2017-05-18T16:10:19.000Z
2022-03-26T18:05:59.000Z
MainGame/drawables/TextDrawable.cpp
JoaoBaptMG/ReboundTheGame
48c3d8b81de1f7fa7c622c3f815860257ccdba8e
[ "MIT" ]
1
2018-02-10T12:40:33.000Z
2019-01-11T07:33:13.000Z
MainGame/drawables/TextDrawable.cpp
JoaoBaptMG/ReboundTheGame
48c3d8b81de1f7fa7c622c3f815860257ccdba8e
[ "MIT" ]
4
2017-12-31T21:38:14.000Z
2019-11-20T15:13:00.000Z
// // Copyright (c) 2016-2018 João Baptista de Paula e Silva. // // 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 "TextDrawable.hpp" #include <algorithm> #include <utf8.h> #include <cmath> #include <predUtils.hpp> #include "unicode/UnicodeUtils.hpp" bool isGraphemeClusterBoundary(sf::Uint32 c1, sf::Uint32 c2) { // TODO: add all remaining cases return !unicode::isGraphemeExtender(c2); } bool (*const WordWrappingAlgorithms[])(uint32_t,uint32_t) = { // Normal [](uint32_t pc, uint32_t c) -> bool { return unicode::isCharacterWrappable(c) || unicode::isCharacterNewline(c); }, // Japanese [](uint32_t pc, uint32_t c) -> bool { if (pc <= 127 && c <= 127) return unicode::isCharacterWrappable(c) || unicode::isCharacterNewline(c); return unicode::isJapaneseWrappable(pc, c); }, // Simplified Chinese [](uint32_t pc, uint32_t c) -> bool { const std::string nextForbidden = u8"!%),.:;?]}¢°·’\"\"†‡›℃∶、。〃〆〕〗〞﹚﹜!"%'),.:;?!]}~"; const std::string prevForbidden = u8"$(£¥·‘\"〈《「『【〔〖〝﹙﹛$(.[{£¥"; if (nextForbidden.find(c) != std::string::npos) return false; if (prevForbidden.find(pc) != std::string::npos) return false; return true; }, // Traditional Chinese [](uint32_t pc, uint32_t c) -> bool { const std::string nextForbidden = u8"!),.:;?]}¢·–— ’\"•\" 、。〆〞〕〉》」︰︱︲︳﹐﹑﹒﹓﹔﹕﹖﹘﹚﹜!),.:;?︶︸︺︼︾﹀﹂﹗]|}、"; const std::string prevForbidden = u8"([{£¥‘\"‵〈《「『〔〝︴﹙﹛({︵︷︹︻︽︿﹁﹃﹏"; if (nextForbidden.find(c) != std::string::npos) return false; if (prevForbidden.find(pc) != std::string::npos) return false; return true; }, // Korean [](uint32_t pc, uint32_t c) -> bool { const std::string nextForbidden = u8"!%),.:;?]}¢°’\"†‡℃〆〈《「『〕!%),.:;?]}"; const std::string prevForbidden = u8"$([\\{£¥‘\"々〇〉》」〔$([{⦆¥₩ #"; if (nextForbidden.find(c) != std::string::npos) return false; if (prevForbidden.find(pc) != std::string::npos) return false; return true; }, }; TextDrawable::TextDrawable(std::shared_ptr<FontHandler> fontHandler) : fontHandler(fontHandler), utf8String(), fontSize(30), defaultColor(sf::Color::White), defaultOutlineColor(sf::Color::Black), outlineThickness(0), wordWrappingWidth(0), wordAlignment(TextDrawable::Alignment::Direct), horizontalAnchor(TextDrawable::HorAnchor::Left), verticalAnchor(TextDrawable::VertAnchor::Top), rtl(false), needsUpdateGeometry(false), vertices(sf::PrimitiveType::Triangles), verticesOutline(sf::PrimitiveType::Triangles), bounds(), graphemeClusters() { wordWrappingAlgorithm = WordWrappingAlgorithm::Normal; } inline static auto addGlyphQuad(sf::VertexArray& dest, sf::Vector2f position, sf::Color color, const sf::Glyph& glyph) { const auto& bounds = glyph.bounds; sf::FloatRect texRect((float)glyph.textureRect.left, (float)glyph.textureRect.top, (float)glyph.textureRect.width, (float)glyph.textureRect.height); auto s = dest.getVertexCount(); if (bounds == sf::FloatRect(0, 0, 0, 0)) return std::make_pair(s, s); dest.append(sf::Vertex(position + sf::Vector2f(bounds.left, bounds.top), color, sf::Vector2f(texRect.left, texRect.top))); dest.append(sf::Vertex(position + sf::Vector2f(bounds.left + bounds.width, bounds.top), color, sf::Vector2f(texRect.left + texRect.width, texRect.top))); dest.append(sf::Vertex(position + sf::Vector2f(bounds.left + bounds.width, bounds.top + bounds.height), color, sf::Vector2f(texRect.left + texRect.width, texRect.top + texRect.height))); dest.append(sf::Vertex(position + sf::Vector2f(bounds.left, bounds.top + bounds.height), color, sf::Vector2f(texRect.left, texRect.top + texRect.height))); dest.append(dest[s]); dest.append(dest[s+2]); return std::make_pair(s, s+6); } float TextDrawable::getLineSpacing() const { return fontHandler->getFont().getLineSpacing(fontSize); } float TextDrawable::getHeightForLineNumber(size_t lines) const { const auto& font = fontHandler->getFont(); if (lines == 0) return 0; return font.getDescent(fontSize) - font.getAscent(fontSize) + (lines-1) * font.getLineSpacing(fontSize); } void TextDrawable::buildGeometry() { if (!needsUpdateGeometry) return; vertices.clear(); verticesOutline.clear(); graphemeClusters.clear(); if (fontHandler == nullptr) return; if (utf8String.empty()) return; if (!utf8::is_valid(utf8String.begin(), utf8String.end())) #ifdef NDEBUG return; #else utf8String = u8"!!!INVALID UTF-8 STRING PASSED TO TextDrawable!!!"; #endif sf::Font& font = fontHandler->getFont(); HarfBuzzWrapper& wrapper = fontHandler->getHBWrapper(); wrapper.setFontSize(fontSize); bool outline = outlineThickness != 0; const char* curPos = utf8String.data(); const char* endPos = utf8String.data() + utf8String.size(); struct Word { size_t vertexBegin, vertexEnd, graphemeClusterEnd; uint32_t nextCharacter; float wordWidth; }; std::vector<Word> words; const char* nextWordPos; do { nextWordPos = curPos; uint32_t pc = 0; while (nextWordPos != endPos) { uint32_t c = utf8::unchecked::next(nextWordPos); if ((pc != 0 && WordWrappingAlgorithms[(size_t)wordWrappingAlgorithm](pc, c)) || unicode::isCharacterWordJoiner(c)) { utf8::unchecked::prior(nextWordPos); break; } pc = c; } size_t prevCluster = (size_t)-1; size_t curWordBegin = vertices.getVertexCount(); size_t curGraphemeBegin = graphemeClusters.size(); sf::Vector2f position; auto prop = wrapper.shape(curPos, nextWordPos - curPos); for (const auto& glyphData : prop.glyphs) { uint32_t c = glyphData.codepoint; size_t cluster = glyphData.cluster; if (outline) { auto tempPos = position + glyphData.offset - sf::Vector2f(outlineThickness, outlineThickness); const auto& glyph = font.getGlyphId(c, fontSize, false, outlineThickness); addGlyphQuad(verticesOutline, tempPos, defaultOutlineColor, glyph); } const auto& glyph = font.getGlyphId(c, fontSize, false); auto p = addGlyphQuad(vertices, position + glyphData.offset, defaultColor, glyph); position += glyphData.advance; if (prevCluster == cluster || p.first == p.second) { if (!graphemeClusters.empty()) graphemeClusters.back().vertexEnd = p.second; } else graphemeClusters.push_back({ p.first, p.second, (size_t)(curPos - utf8String.data()) }); prevCluster = cluster; } uint32_t c = 0; if (wordWrappingAlgorithm == WordWrappingAlgorithm::Normal && nextWordPos != endPos) c = utf8::unchecked::next(nextWordPos); words.push_back({ curWordBegin, vertices.getVertexCount(), graphemeClusters.size(), c, position.x }); if (prop.isRTL) { std::reverse(graphemeClusters.data() + curGraphemeBegin, graphemeClusters.data() + graphemeClusters.size()); } curPos = nextWordPos; } while (nextWordPos != endPos); { struct Line { size_t vertexBegin, vertexEnd, graphemeClusterEnd; float lineWidth; }; std::vector<Line> lines; sf::Vector2f curPos; if (wordWrappingWidth > 0) { bounds.left = rtl ? -wordWrappingWidth : 0; bounds.width = wordWrappingWidth; } else { bounds.left = 0; bounds.width = 0; } bounds.top = font.getAscent(fontSize); const Word* lastBegin = &words.front(); float curLineWidth = 0; for (size_t i = 0; i < words.size(); i++) { const auto& word = words[i]; if (wordWrappingWidth > 0) { float joinedWordWidth = word.wordWidth; for (size_t k = 0; k < words.size() && unicode::isCharacterWordJoiner(words[i+k].nextCharacter); k++) joinedWordWidth += words[i+k+1].wordWidth; if (rtl ? curPos.x - joinedWordWidth < -wordWrappingWidth : curPos.x + joinedWordWidth > wordWrappingWidth) { if (i > 0) lines.push_back({ lastBegin->vertexBegin, words[i-1].vertexEnd, words[i-1].graphemeClusterEnd, curLineWidth }); lastBegin = &word; curPos.x = 0; curPos.y += font.getLineSpacing(fontSize); } } if (rtl) curPos.x -= word.wordWidth; for (size_t i = word.vertexBegin; i < word.vertexEnd; i++) { vertices[i].position += curPos; if (outline) verticesOutline[i].position += curPos; //bounds = rectUnionWithPoint(bounds, vertices[i].position); } if (!rtl) curPos.x += word.wordWidth; bounds = rectUnionWithLineX(bounds, curPos.x); curLineWidth = curPos.x; if (word.nextCharacter) { if (unicode::isCharacterNewline(word.nextCharacter)) { lines.push_back({ lastBegin->vertexBegin, word.vertexEnd, word.graphemeClusterEnd, curLineWidth }); lastBegin = &words[i+1]; curPos.x = 0; curPos.y += font.getLineSpacing(fontSize); } else if (!unicode::isCharacterZeroWidth(word.nextCharacter)) { const auto& glyph = font.getGlyph(word.nextCharacter, fontSize, false); if (rtl) curPos.x -= glyph.advance; else curPos.x += glyph.advance; } } } bounds = rectUnionWithLineX(bounds, curLineWidth); lines.push_back({ lastBegin->vertexBegin, words.back().vertexEnd, words.back().graphemeClusterEnd, curLineWidth }); bounds.height = (lines.size() - 1) * font.getLineSpacing(fontSize) + font.getDescent(fontSize) - bounds.top; lineBoundaries.clear(); for (const auto& line : lines) { float lineDisplacement = (rtl ? -bounds.width : bounds.width) - line.lineWidth; switch (wordAlignment) { case Alignment::Direct: lineDisplacement = 0; break; case Alignment::Center: lineDisplacement = floorf(lineDisplacement/2); break; case Alignment::Inverse: break; } for (size_t i = line.vertexBegin; i < line.vertexEnd; i++) { vertices[i].position.x += lineDisplacement; if (outline) verticesOutline[i].position.x += lineDisplacement; } lineBoundaries.push_back(line.graphemeClusterEnd); } } sf::Vector2f revert; switch (horizontalAnchor) { case HorAnchor::Left: revert.x = bounds.left; break; case HorAnchor::Center: revert.x = floorf(bounds.left + bounds.width/2); break; case HorAnchor::Right: revert.x = bounds.left + bounds.width; break; } switch (verticalAnchor) { case VertAnchor::Top: revert.y = bounds.top; break; case VertAnchor::Center: revert.y = floorf(bounds.top + bounds.height/2); break; case VertAnchor::Bottom: revert.y = bounds.top + bounds.height; break; case VertAnchor::Baseline: break; } bounds.left -= revert.x; bounds.top -= revert.y; for (size_t i = 0; i < vertices.getVertexCount(); i++) { vertices[i].position -= revert; if (outline) verticesOutline[i].position -= revert; } needsUpdateGeometry = false; } TextDrawable::GraphemeRange TextDrawable::getGraphemeClusterInterval(size_t begin, size_t end, bool outline) { if (end > graphemeClusters.size()) end = graphemeClusters.size(); if (begin >= end) return { nullptr, nullptr }; if (outline && verticesOutline.getVertexCount() == 0) return { nullptr, nullptr }; const auto& clusterb = graphemeClusters.at(begin); const auto& clustere = graphemeClusters.at(end-1); auto vlist = outline ? &verticesOutline[0] : &vertices[0]; return { vlist+clusterb.vertexBegin, vlist+clustere.vertexEnd }; } TextDrawable::GraphemeRange TextDrawable::getGraphemeCluster(size_t index, bool outline) { if (index >= graphemeClusters.size()) return { nullptr, nullptr }; if (outline && verticesOutline.getVertexCount() == 0) return { nullptr, nullptr }; const auto& cluster = graphemeClusters.at(index); auto vlist = outline ? &verticesOutline[0] : &vertices[0]; return { vlist+cluster.vertexBegin, vlist+cluster.vertexEnd }; } size_t TextDrawable::getGraphemeClusterByteLocation(size_t index) const { if (index >= graphemeClusters.size()) return utf8String.size(); return graphemeClusters.at(index).byteLocation; } size_t TextDrawable::getGraphemeClusterLine(size_t index) const { if (index >= graphemeClusters.size()) return lineBoundaries.size(); auto it = std::upper_bound(lineBoundaries.begin(), lineBoundaries.end(), index); return (size_t)(it - lineBoundaries.begin()); } size_t TextDrawable::getNumberOfGraphemeClusters() const { return graphemeClusters.size(); } size_t TextDrawable::getLineBoundary(size_t index) const { if (lineBoundaries.empty()) return 0; if (index >= lineBoundaries.size()) index = lineBoundaries.size() - 1; return lineBoundaries.at(index); } size_t TextDrawable::getNumberOfLines() const { return lineBoundaries.size(); } TextDrawable::GraphemeRange TextDrawable::getAllVertices(bool outline) { if (graphemeClusters.empty()) return { nullptr, nullptr }; if (outline && verticesOutline.getVertexCount() == 0) return { nullptr, nullptr }; auto vlist = outline ? &verticesOutline[0] : &vertices[0]; auto size = outline ? verticesOutline.getVertexCount() : vertices.getVertexCount(); return { vlist, vlist+size }; } void TextDrawable::draw(sf::RenderTarget& target, sf::RenderStates states) const { if (!needsUpdateGeometry) states.texture = &fontHandler->getFont().getTexture(fontSize); target.draw(verticesOutline, states); target.draw(vertices, states); }
35.328859
123
0.616261
[ "shape", "vector" ]
97438333b42381675b3f5bd3ad3593a091fde6e1
3,279
cpp
C++
groups/bal/balst/balst_stacktraceframe.cpp
apaprocki/bde
ba252cb776f92fae082d5d422aa2852a9be46849
[ "Apache-2.0" ]
1
2021-04-28T13:51:30.000Z
2021-04-28T13:51:30.000Z
groups/bal/balst/balst_stacktraceframe.cpp
apaprocki/bde
ba252cb776f92fae082d5d422aa2852a9be46849
[ "Apache-2.0" ]
null
null
null
groups/bal/balst/balst_stacktraceframe.cpp
apaprocki/bde
ba252cb776f92fae082d5d422aa2852a9be46849
[ "Apache-2.0" ]
1
2019-06-26T13:28:48.000Z
2019-06-26T13:28:48.000Z
// balst_stacktraceframe.cpp -*-C++-*- // ---------------------------------------------------------------------------- // NOTICE // // This component is not up to date with current BDE coding standards, and // should not be used as an example for new development. // ---------------------------------------------------------------------------- #include <balst_stacktraceframe.h> #include <bsls_ident.h> BSLS_IDENT_RCSID(balst_stacktraceframe_cpp,"$Id$ $CSID$") #include <bslim_printer.h> #include <bsl_ostream.h> namespace BloombergLP { namespace balst { // --------------------- // class StackTraceFrame // --------------------- // ACCESSORS bsl::ostream& StackTraceFrame::print(bsl::ostream& stream, int level, int spacesPerLevel) const { if (stream.bad()) { return stream; // RETURN } bslim::Printer printer(&stream, level, spacesPerLevel); printer.start(); printer.printAttribute("address", d_address); printer.printAttribute("library file name", d_libraryFileName.c_str()); printer.printAttribute("line number", d_lineNumber); printer.printAttribute("mangled symbol name", d_mangledSymbolName.c_str()); printer.printAttribute("offset from symbol", d_offsetFromSymbol); printer.printAttribute("source file name", d_sourceFileName.c_str()); printer.printAttribute("symbol name", d_symbolName.c_str()); printer.end(); return stream; } // FREE OPERATORS bsl::ostream& operator<<(bsl::ostream& stream, const StackTraceFrame& object) { if (stream.bad()) { return stream; // RETURN } bslim::Printer printer(&stream, 0, -1); printer.start(); printer.printValue(object.address()); printer.printValue(object.libraryFileName().c_str()); printer.printValue(object.lineNumber()); printer.printValue(object.mangledSymbolName().c_str()); printer.printValue(object.offsetFromSymbol()); printer.printValue(object.sourceFileName().c_str()); printer.printValue(object.symbolName().c_str()); printer.end(); return stream; } } // close package namespace } // close enterprise namespace // ---------------------------------------------------------------------------- // Copyright 2015 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
36.433333
79
0.550473
[ "object" ]
9748aeb2ac875ce1b1592a5d1b5716c04ef64bd6
1,186
cpp
C++
containers_test/source/accumulation_vector_tests.cpp
dgu123/lean-cpp-lib
e4698699a743e567f287f5592af0f23219657929
[ "MIT" ]
null
null
null
containers_test/source/accumulation_vector_tests.cpp
dgu123/lean-cpp-lib
e4698699a743e567f287f5592af0f23219657929
[ "MIT" ]
null
null
null
containers_test/source/accumulation_vector_tests.cpp
dgu123/lean-cpp-lib
e4698699a743e567f287f5592af0f23219657929
[ "MIT" ]
null
null
null
#include "stdafx.h" #include <lean/containers/simple_vector.h> #include <lean/time/highres_timer.h> #include <vector> struct bla { int a; bla(int i) : a(i) { } ~bla() { } }; double perfTestSTL() { lean::highres_timer timer; for (int x = 0; x < 1000; ++x) { std::vector<int> a; // a.reserve(10000); for (int i = 0; i < 10000; ++i) a.push_back(i); } return timer.milliseconds(); } double perfTestLean() { lean::highres_timer timer; for (int x = 0; x < 1000; ++x) { lean::simple_vector<int, lean::simple_vector_policies::pod> a; // a.reserve(10000); for (int i = 0; i < 10000; ++i) a.push_back(i); } return timer.milliseconds(); } BOOST_AUTO_TEST_SUITE( simple_vector ) BOOST_AUTO_TEST_CASE( perf ) { double lean = perfTestLean(); double stl = perfTestSTL(); BOOST_CHECK_EQUAL(stl / lean, 1.0); stl = perfTestSTL(); lean = perfTestLean(); BOOST_CHECK_EQUAL(stl / lean, 1.0); lean = perfTestLean(); stl = perfTestSTL(); BOOST_CHECK_EQUAL(stl / lean, 1.0); stl = perfTestSTL(); lean = perfTestLean(); BOOST_CHECK_EQUAL(stl / lean, 1.0); } BOOST_AUTO_TEST_SUITE_END()
17.441176
65
0.614671
[ "vector" ]
97495be1dc8d15f536bf7752c1c00fdb26b235d3
1,168
hpp
C++
libs/input/include/sge/input/info/container.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/input/include/sge/input/info/container.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/input/include/sge/input/info/container.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_INPUT_INFO_CONTAINER_HPP_INCLUDED #define SGE_INPUT_INFO_CONTAINER_HPP_INCLUDED #include <sge/input/detail/symbol.hpp> #include <sge/input/info/container_fwd.hpp> #include <fcppt/optional/reference_fwd.hpp> #include <fcppt/config/external_begin.hpp> #include <vector> #include <fcppt/config/external_end.hpp> namespace sge::input::info { template <typename Id, typename Obj> class container { public: using id = Id; using size_type = id; using object = Obj; using value_type = object; using vector = std::vector<Obj>; SGE_INPUT_DETAIL_SYMBOL explicit container(vector &&); [[nodiscard]] SGE_INPUT_DETAIL_SYMBOL fcppt::optional::reference<Obj const> operator[](Id const &) const; [[nodiscard]] SGE_INPUT_DETAIL_SYMBOL Id size() const; [[nodiscard]] SGE_INPUT_DETAIL_SYMBOL bool empty() const; [[nodiscard]] SGE_INPUT_DETAIL_SYMBOL vector const &get() const; private: vector vector_; }; } #endif
22.461538
77
0.73887
[ "object", "vector" ]
974ba91d0fbaba8de1106032443d24caf7adba4a
2,708
cpp
C++
src/chartwork/plugins/PieChartPlugin.cpp
nazhor/chartwork
20cb8df257bec39153ea408305640274c9e09d4c
[ "MIT" ]
20
2018-08-29T07:33:21.000Z
2022-03-12T05:05:54.000Z
src/chartwork/plugins/PieChartPlugin.cpp
nazhor/chartwork
20cb8df257bec39153ea408305640274c9e09d4c
[ "MIT" ]
1
2020-10-27T15:04:46.000Z
2020-10-27T15:04:46.000Z
src/chartwork/plugins/PieChartPlugin.cpp
nazhor/chartwork
20cb8df257bec39153ea408305640274c9e09d4c
[ "MIT" ]
7
2015-07-09T20:38:28.000Z
2021-09-27T06:38:11.000Z
#include <chartwork/plugins/PieChartPlugin.h> #include <QtPlugin> #include <chartwork/PieChart.h> //////////////////////////////////////////////////////////////////////////////////////////////////// // // PieChartPlugin // //////////////////////////////////////////////////////////////////////////////////////////////////// PieChartPlugin::PieChartPlugin(QObject *parent) : QObject(parent) { m_isInitialized = false; } //////////////////////////////////////////////////////////////////////////////////////////////////// void PieChartPlugin::initialize(QDesignerFormEditorInterface *) { if (m_isInitialized) return; m_isInitialized = true; } //////////////////////////////////////////////////////////////////////////////////////////////////// bool PieChartPlugin::isInitialized() const { return m_isInitialized; } //////////////////////////////////////////////////////////////////////////////////////////////////// QWidget *PieChartPlugin::createWidget(QWidget *parent) { return new chartwork::PieChart(parent); } //////////////////////////////////////////////////////////////////////////////////////////////////// QString PieChartPlugin::name() const { return "chartwork::PieChart"; } //////////////////////////////////////////////////////////////////////////////////////////////////// QString PieChartPlugin::group() const { return "Chartwork"; } //////////////////////////////////////////////////////////////////////////////////////////////////// QIcon PieChartPlugin::icon() const { return QIcon("://icons/icon-pie-chart.png"); } //////////////////////////////////////////////////////////////////////////////////////////////////// QString PieChartPlugin::toolTip() const { return ""; } //////////////////////////////////////////////////////////////////////////////////////////////////// QString PieChartPlugin::whatsThis() const { return "Pie Chart"; } //////////////////////////////////////////////////////////////////////////////////////////////////// bool PieChartPlugin::isContainer() const { return false; } //////////////////////////////////////////////////////////////////////////////////////////////////// QString PieChartPlugin::domXml() const { return ("<ui language=\"c++\" displayname=\"PieChart\">\ <widget class=\"chartwork::PieChart\" name=\"pieChart\">\ <property name=\"geometry\">\ <rect>\ <x>0</x>\ <y>0</y>\ <width>400</width>\ <height>300</height>\ </rect>\ </property>\ </widget>\ </ui>"); } //////////////////////////////////////////////////////////////////////////////////////////////////// QString PieChartPlugin::includeFile() const { return QLatin1String("<chartwork/PieChart.h>"); }
24.618182
100
0.350812
[ "geometry" ]
974d4727e757acd9d18446db4d242d78c85a954f
864
cpp
C++
vo7/LambdaExpressions/numeric_example.cpp
michivo/osd
ccc76aa0d7fa9b62b63d012481dbb318be0f6382
[ "MIT" ]
null
null
null
vo7/LambdaExpressions/numeric_example.cpp
michivo/osd
ccc76aa0d7fa9b62b63d012481dbb318be0f6382
[ "MIT" ]
null
null
null
vo7/LambdaExpressions/numeric_example.cpp
michivo/osd
ccc76aa0d7fa9b62b63d012481dbb318be0f6382
[ "MIT" ]
null
null
null
#include "stdafx.h" #include <iostream> #include <vector> #include <functional> #include <climits> int aggregate(std::vector<int> numbers, std::function<int(int, int)> aggregator, int seed = 0) { int result = seed; for (auto x : numbers) { result = aggregator(x, result); } return result; } void numeric_example() { const std::vector<int> numbers{ 2, 1, 3, 4, 2 }; const auto sum = aggregate(numbers, [](int x, int y) -> int { return x + y; }); // return value may be specified const auto product = aggregate(numbers, [](int x, int y) {return x * y; }, 1); const auto max = aggregate(numbers, [](int x, int y) {return x > y ? x : y; }, INT_MIN); const auto min = aggregate(numbers, [](int x, int y) {return x > y ? y : x; }, INT_MAX); std::cout << "Sum:\t" << sum << "\nProd:\t" << product << "\nMax:\t" << max << "\nMin:\t" << min << "\n"; }
29.793103
113
0.606481
[ "vector" ]
974da9f6dab607ce760b0e8bd7e0072150dca04c
2,083
hpp
C++
include/mos/core/tracked_container.hpp
morganbengtsson/mo
c719ff6b35478b068988901d0bf7253cb672e87a
[ "MIT" ]
230
2016-02-15T20:46:01.000Z
2022-03-07T11:56:12.000Z
include/mos/core/tracked_container.hpp
morganbengtsson/mo
c719ff6b35478b068988901d0bf7253cb672e87a
[ "MIT" ]
79
2016-02-07T11:37:04.000Z
2021-09-29T09:14:27.000Z
include/mos/core/tracked_container.hpp
morganbengtsson/mo
c719ff6b35478b068988901d0bf7253cb672e87a
[ "MIT" ]
14
2018-05-16T13:10:22.000Z
2021-09-28T10:23:31.000Z
#pragma once #include <chrono> #include <initializer_list> #include <mos/core/container.hpp> #include <vector> namespace mos { template <class T> class Container; /** Container with modified time stamp. */ template <class T> class Tracked_container { public: using Items = std::vector<T>; using TimePoint = std::chrono::time_point<std::chrono::system_clock, std::chrono::nanoseconds>; using size_type = typename Items::size_type; Tracked_container() { invalidate(); } template <class It> explicit Tracked_container(const std::initializer_list<It> list) : Tracked_container(list.begin(), list.end()) {} template <class It> Tracked_container(It begin, It end) { assign(begin, end); } explicit Tracked_container(const Container<T> &container) : Tracked_container(container.begin(), container.end()) {} template <class It> void assign(It begin, It end) { items_.assign(begin, end); invalidate(); } typename Items::iterator begin() { invalidate(); return items_.begin(); } typename Items::iterator end() { invalidate(); return items_.end(); } typename Items::const_iterator begin() const { return items_.begin(); } typename Items::const_iterator end() const { return items_.end(); } typename Items::reference operator[](typename Items::size_type pos) { invalidate(); return items_[pos]; } typename Items::const_reference operator[](typename Items::size_type pos) const { return items_[pos]; } typename Items::size_type size() const { return items_.size(); } typename Items::reference back() { invalidate(); return items_.back(); } const T *data() const noexcept { return items_.data(); } void clear() { items_.clear(); invalidate(); } void push_back(const T &item) { items_.push_back(item); invalidate(); } TimePoint modified() const { return modified_; } private: void invalidate() { modified_ = std::chrono::system_clock::now(); } Items items_; TimePoint modified_; }; } // namespace mos
27.051948
73
0.668747
[ "vector" ]
97523e82d1beb9fb731de593cb0f39058ab86dd4
20,156
cpp
C++
main.cpp
bilginyuksel/cli-todo
324caa8e479c75e2f74de000e90b45b10886285c
[ "MIT" ]
null
null
null
main.cpp
bilginyuksel/cli-todo
324caa8e479c75e2f74de000e90b45b10886285c
[ "MIT" ]
null
null
null
main.cpp
bilginyuksel/cli-todo
324caa8e479c75e2f74de000e90b45b10886285c
[ "MIT" ]
1
2020-08-09T12:54:20.000Z
2020-08-09T12:54:20.000Z
#include "db_repo.h" #ifndef unordered_map #include <unordered_map> #endif #ifndef iostream #include <iostream> #endif #define RESET "\033[0m" #define MAGENTA "\033[35m" #define CYAN "\033[36m" #define GREEN "\033[32m" #define RED "\033[31m" #define YELLOW "\033[33m" void help(); void version(); void about(); void execute_branch(int, std::vector<std::string>&); void execute_note(int, std::vector<std::string>&); void execute_category(int, std::vector<std::string>&); void execute_checkout(int, std::vector<std::string>&); void execute_log(int); void about_note(); void about_branch(); void about_category(); void about_checkout(); void add_new_branch(std::string); void show_all_branches(); void delete_branch(int, std::vector<std::string>&); // it needs to throw an exception void delete_force_branch(int, std::vector<std::string>&); void show_notes(int, std::vector<std::string>&); void add_note(int, std::vector<std::string>&); void list_detailed_todos(std::vector<m_todo>&); void list_todos(std::vector<m_todo>&); void update_note(int); void delete_note(int); void list_category(int, std::vector<std::string>&); void delete_category(int); void add_category(int, std::vector<std::string>&); // EMOJI UNICODE START std::string red_circle = "\xF0\x9F\x94\xB4"; std::string blue_circle = "\xF0\x9F\x94\xB5"; std::string blue_book = "\xF0\x9F\x93\x98"; std::string left_point = "\xF0\x9F\x91\x88"; std::string right_point = "\xF0\x9F\x91\x89"; std::string poo = "\xF0\x9F\x92\xA9"; std::string confused_face = "\xF0\x9F\x98\x95"; std::string exclamation_mark = "\xE2\x9D\x97"; std::string question_mark = "\xE2\x9D\x93"; std::string base_cross_mark = "\xE2\x9D\x8E"; std::string cross_mark = "\xE2\x9D\x8C"; std::string check_mark = "\xE2\x9C\x85"; std::string warning_sign = "\xE2\x9A\xA0"; // very tiny std::string clock_emoji = "\xE2\x8C\x9B"; std::string dollar = "\xF0\x9F\x92\xB2"; std::string flame = "\xF0\x9F\x94\xA5"; // EMOJI UNICODE END CatRepo* cr = new CatRepo; ProjRepo* pr = new ProjRepo; SettingsRepo* sr = new SettingsRepo; TodoRepo* tr = new TodoRepo; LogRepo* lr = new LogRepo; int main(int argc, char** argv){ std::vector<std::string> cli_arguments; // std::cout<<"argc= "<<argc<<"\n"; for(int i=0; i<argc; ++i) cli_arguments.push_back(argv[i]); // application started without parameters if(argc == 1) about(); std::string action = cli_arguments[1]; // Help called if(action == "--help" || action == "-h") help(); if(action == "--version" || action == "-v") version(); /* * <command> [<args>] * [--<help>, -h], [--version, -v] * * */ // All code will be exited after execution. if(action == "branch" && argc>=2)execute_branch(argc, cli_arguments); if(action == "note" && argc>=3) execute_note(argc, cli_arguments); if(action == "category" && argc>=3) execute_category(argc, cli_arguments); if(action == "checkout" && argc>=3) execute_checkout(argc, cli_arguments); if(action == "log") execute_log(argc>=3?std::stoi(cli_arguments[2]):-1); } void help(){ about(); exit(1); } void about(){ std::cout<<"\n\n"<<flame<<flame<<" Usage "<<poo<<poo<<"\n\n"; std::cout<<" "<<dollar<<"tod <command> <options> [<args>]\n"; std::cout<<"\nGlobal Commands:\n"; std::cout<<"\n "<<dollar<<"branch [<options>] [<args>]....................Your notes will be stored at branches to avoid conflicts."; std::cout<<"\n "<<dollar<<"note <options> [<args>]........................You can register, delete, update a note to a branch."; std::cout<<"\n "<<dollar<<"category <options> [<args>]....................Categorize your notes. And get categorized notes of yours."; std::cout<<"\n "<<dollar<<"checkout [<branch-name>].......................Switch your working branches.\n"; // std::cout<<"\n"<<confused_face<<confused_face<<" Did you try to say ?"; std::cout<<"\n\n\n\n"; exit(1); } void about_branch(){ std::cout<<"\n\n"<<flame<<flame<<" Usage "<<poo<<poo<<"\n\n"; std::cout<<" "<<dollar<<"tod branch [<command>] [<args>], --help\n\n"; std::cout<<" Description:\n Use this command to create, delete, list and archive branches. You can save notes in branches and with that way your notes will be structured. When you have unfinished todos in your branch you can't delete it we have covered it up for you and if you have archived your branch also you can't delete it. Recommended way of using this branch system is; You can sync your branches with your projects git branches. That way you can save notes to specific branches of your project. Easy access and beatiful visualization."<<exclamation_mark<<exclamation_mark<<"\n"; std::cout<<"\n Example Usage:\n"; std::cout<<"\n To create new branches.\n"; std::cout<<"\n "<<dollar<<"tod branch my-new-branch\n"; std::cout<<"\nNOTE: You can't create branches that you already have.\n"; std::cout<<"\n To delete a branch.\n"; std::cout<<"\n "<<dollar<<"tod branch --delete my-new-branch\n"; std::cout<<" "<<dollar<<"tod branch -d my-new-branch\n"; std::cout<<"\n To list all branches.\n"; std::cout<<"\n "<<dollar<<"tod branch -a\n"; std::cout<<" "<<dollar<<"tod branch -all"; std::cout<<"\n\n\n"; // You can add all branch functionality and emoji explanations also. exit(1); } void about_note(){ std::cout<<"\n\n"<<flame<<flame<<" Usage "<<poo<<poo<<"\n\n"; std::cout<<" "<<dollar<<"tod note [<command>] [<args>], --help\n\n"; std::cout<<" Description:\n Use this command to create, delete, update and list notes. You can create notes only with title (title is mandatory) or you can also add multiple properties too. You can delete notes according to their id. You can list undone notes, done notes or detailed notes."; std::cout<<"\n\n Example Usage:\n"; std::cout<<"\n "<<dollar<<"tod note --title 'hello to my new todo'"; std::cout<<"\n Explanation: Created a note only with title.\n\n"; std::cout<<"\n "<<dollar<<"tod note -t <note-title> -i <0...2> -d <note-description> -c <category-name>"; std::cout<<"\n Explanation: Created a note with multiple properties.\n\n"; std::cout<<"\n "<<dollar<<"tod note --delete <note-id>"; std::cout<<"\n "<<dollar<<"tod note -d <note-id>"; std::cout<<"\n Explanation: Delete the note.\n\n"; std::cout<<"\n "<<dollar<<"tod note -l"; std::cout<<"\n "<<dollar<<"tod note -l -d"; std::cout<<"\n "<<dollar<<"tod note -l -u -d"; std::cout<<"\n Explanation: List the notes. First one for normal listing, second one for detailed listing. Use the third command to list undone todos only.\n\n"; std::cout<<"\n "<<dollar<<"tod note -f <note-id>"; std::cout<<"\n "<<dollar<<"tod note --finish <note-id>"; std::cout<<"\n Explanation: Change note's status unfinished to finished."; std::cout<<"\n\n\n"; exit(1); } void about_category(){ std::cout<<"\n\n"<<flame<<flame<<" Usage "<<poo<<poo<<"\n\n"; std::cout<<" "<<dollar<<"tod category [<command>] [<args>], --help\n\n"; std::cout<<" Description:\n Use this command to create, list, delete categories and you can get detailed info about category. This means you can print all of the information about category with todos belong to that category."; std::cout<<"\n Example Usage:\n"; std::cout<<"\n To create a new category.\n"; std::cout<<"\n "<<dollar<<"tod category -t 'Personal' -d 'Description about the category'\n"; std::cout<<"\nNOTE: Title is mandatory to create a category. Also you can specify the description to that category.\n"; std::cout<<"\n To list all categories with details.\n"; std::cout<<"\n "<<dollar<<"tod category -l -d\n"; std::cout<<"\n To delete a category.\n"; std::cout<<"\n "<<dollar<<"tod category --delete <category-id>\n"; std::cout<<"\n Get detailed info about category.\n"; std::cout<<"\n "<<dollar<<"tod category -di <category-name>\n"; std::cout<<"\nNOTE: With the method above you can have a detailed information about category. And the difference between -i and -di is; The first one prints todos non-detailed the second one also prints todos detailed to.\n"; std::cout<<"\n\n\n"; exit(1); } void about_checkout(){ std::cout<<"\n\n"<<flame<<flame<<" Usage "<<poo<<poo<<"\n\n"; std::cout<<" "<<dollar<<"tod checkout <branch-name>, --help\n\n"; std::cout<<" Description:\n Use this method to switch between branches.\n"; std::cout<<"\n Example Usage:\n"; std::cout<<"\n "<<dollar<<"tod checkout master\n"; std::cout<<"\nWith the command above you have successfully switched to branch master.\n\n\n"; exit(1); } void version(){ std::cout<<"\ncli-todo_v1.0.0\n"; exit(1); } void execute_checkout(int argc, std::vector<std::string>& argv){ if(argv[2] == "--help" || argv[2] == "-h") about_checkout(); project p = pr-> find(argv[2]); if(p.get_id() == -1) { std::cout<<"There is no "<<argv[2]<<" branch exist.\n"; exit(1); } int curr_branch_id = sr->curr_branch(); // std::cout<<"curr_branch_id: "<<curr_branch_id<<"\n"; // std::cout<<"p_get_id: "<<p.get_id()<<"\n"; if(curr_branch_id == p.get_id()){ std::cout<<"You are already in branch "<<argv[2]<<".\n"; exit(1); } project old = pr->find(curr_branch_id); std::cout<<"Changing branch "<<old.get_title()<<" to "<<argv[2]<<".\n"; sr->update_curr_branch(p.get_id()); int updated_branch = sr->curr_branch(); } void execute_branch(int argc, std::vector<std::string>& argv){ // branch name is a must // argv <options>, [-a, --all, -d, --delete] // argv [--name] if(argc==2) show_all_branches(); if(argv[2] == "--help" || argv[2] == "-h") about_branch(); if(argv[2] == "-a" || argv[2] == "--all") show_all_branches(); if(argv[2] == "-D") delete_force_branch(argc, argv); if(argv[2] == "-d" || argv[2] == "--delete") delete_branch(argc, argv); std::string new_branch = argv[2]; // add brnch here. add_new_branch(new_branch); } void add_new_branch(std::string name){ if(name[0]=='-' || name[0] == '/' || name[0] == '_' || name[0] =='*' || name[0]=='&') { std::cout<<"Branch name can't start with special character.\n"; exit(1); } // check if we have the branch or not. project any_branch = pr->find_exact_match(name); if(any_branch.get_id() != -1){ std::cout<<"There is already a branch "<<any_branch.get_title()<<" exist.\n"; exit(1); } project* p = new project(name); pr->save(p); project new_branch = pr->find(name); std::cout<<"New branch "<< new_branch.get_title() <<" created.\n"; exit(1); } void delete_branch(int argc, std::vector<std::string>& argv){ // expect a @param // param should be the branch name will be deleted. if(argc < 4) { std::cout<<"\nPlease enter a branch name to delete.\n"; exit(1); } std::string branch_name_to_delete = argv[3]; try{ pr->remove(branch_name_to_delete); }catch(const char* err){ std::cout<<err; } exit(1); } void delete_force_branch(int argc, std::vector<std::string>& argv){ if(argc<4){ std::cout<<"\nPlease enter a branch name to delete.\n"; exit(1); } std::string branch_name_to_delete = argv[3]; try{ pr->remove_force(branch_name_to_delete); }catch(const char* err){ std::cout<<err; } exit(1); } void show_all_branches(){ std::vector<project> proj = pr->findAll(); int curr_branch = sr->curr_branch(); std::cout<<std::endl; for(project p : proj){ // if(p.is_archived()) std::cout<<blue_book; std::cout<<(p.is_all_done()? blue_circle:red_circle)<<" "<<p.get_title(); if(p.get_id() == curr_branch) std::cout<<" "<<left_point; std::cout<<std::endl; } std::cout<<std::endl; exit(1); } void execute_note(int argc, std::vector<std::string>& argv){ if(argv[2] == "--help" || argv[2]=="-h") about_note(); if(argv[2] == "--list" || argv[2] == "-l") show_notes(argc, argv); if((argv[2] == "--delete" || argv[2] == "-d") && argc == 4) delete_note(std::stoi(argv[3])); if((argv[2] == "--finish" || argv[2] =="-f") && argc==4) update_note(std::stoi(argv[3])); // or add note if(argc>3) add_note(argc, argv); exit(1); } void update_note(int id){ // first avoid deletions from different branches int curr_branch = sr->curr_branch(); m_todo t = tr->find(id); if(t.get_project_id() != curr_branch){ std::cout<<std::endl<<RED<<"You can't update a note from another branch. You are allowed to update notes that are in your current branch."<<RESET<<std::endl; exit(1); } tr->make_todo_done(id); exit(1); } void show_notes(int argc, std::vector<std::string>& argv){ int curr_branch = sr->curr_branch(); if(argc == 3) { // If only list command run from user std::vector<m_todo> todos = tr->find_all_todos(curr_branch); list_todos(todos); } // First look there can be 2 commands here. if(argc == 4 && (argv[3]=="--details" || argv[3]=="-d")){ // list detailed notes here... std::vector<m_todo> todos = tr->find_all_todos(curr_branch); list_detailed_todos(todos); } if(argc == 4 && (argv[3]=="--undone" || argv[3]=="-u")){ // list only unfinished todos std::vector<m_todo> todos = tr->find_undone_todos(curr_branch); list_todos(todos); } if(argc == 5 && (argv[3]=="--details" || argv[3]=="-d") && (argv[4]=="--undone" || argv[4]=="-u")){ // list unfinsihed todos with details. std::vector<m_todo> todos = tr->find_undone_todos(curr_branch); list_detailed_todos(todos); } if(argc == 5 && (argv[3]=="--undone" || argv[3]=="-u") && (argv[4]=="--details" || argv[4]=="-d")){ // list unfinsihed todos with details. std::vector<m_todo> todos = tr->find_undone_todos(curr_branch); list_detailed_todos(todos); } // print help message here. // about_note(); exit(1); } void list_todos(std::vector<m_todo>& todos){ std::cout<<std::endl; for(m_todo tod : todos){ if(tod.is_done()) std::cout<<check_mark; else if(tod.get_importance_lvl()==2) std::cout<<exclamation_mark; else if(tod.get_importance_lvl()==1) std::cout<<question_mark; else if(tod.get_importance_lvl()==0) std::cout<<clock_emoji; std::cout<<(tod.is_done()?blue_circle: red_circle); // std::cout<<(tod.is_done()?GREEN: CYAN); std::cout<<" "<<tod.get_todo()<<RESET<<std::endl; }std::cout<<std::endl; } void list_detailed_todos(std::vector<m_todo>& todos){ std::cout<<std::endl; for(m_todo tod : todos){ std::cout<<YELLOW<<"\nDate: "<<tod.get_cr_time()<<RESET; category c = cr->find(tod.get_category_id()); std::cout<<"Id: "<<tod.get_id()<<","; std::cout<<"\tCategory: "<<(tod.get_category_id()?c.get_title():"NULL"); std::cout<<"\n\n\t"; if(tod.is_archived()) std::cout<<blue_book; if(tod.is_done()) std::cout<<check_mark; else if(tod.get_importance_lvl()==2) std::cout<<exclamation_mark; else if(tod.get_importance_lvl()==1) std::cout<<question_mark; else if(tod.get_importance_lvl()==0) std::cout<<clock_emoji; std::cout<<(tod.is_done()?blue_circle: red_circle); // std::cout<<(tod.is_done()?GREEN: CYAN); std::cout<<" "<<tod.get_todo()<<RESET<<std::endl; if(!tod.get_desc().empty()) std::cout<<"\tDescription: "<<tod.get_desc()<<"\n"; }std::cout<<std::endl; exit(1); } void delete_note(int id){ // notes can be deleted different ways. // Get uuid to delete note or give title to delete note. // Get id to delete note // first avoid deletions from different branches int curr_branch = sr->curr_branch(); m_todo t = tr->find(id); if(t.get_project_id() != curr_branch){ std::cout<<std::endl<<RED<<"You can't delete a note from another branch. You are allowed to delete notes that are in your current branch."<<RESET<<std::endl; exit(1); } tr->remove(id); exit(1); exit(1); } void add_note(int argc, std::vector<std::string>& argv){ if(argc%2!=0 || argc<4) { std::cout<<std::endl<<RED<<"Wrong number of arguments!"<<RESET<<std::endl; exit(1); } // std::cout<<"argc: "<<argc<<"\n"; // title is mandatory to create a new todo... // Next arguments will start at 4th index. // We don't know exactly which argument can be given // So I will create a map to fill and create a new todo std::unordered_map<std::string, std::string> command_map; for(int i=2; i<argc; i+=2) command_map[argv[i]] = argv[i+1]; // TESTING // for(auto it : command_map) // std::cout<<it.first<<", "<<it.second<<"\n"; if((command_map.find("--title") != command_map.end()) && (command_map.find("-t") != command_map.end())){ std::cout<<std::endl<<RED<<"Wrong number of arguments!"<<RESET<<std::endl; exit(1); } todo_builder* builder; if(command_map.find("--title") != command_map.end()) builder = new todo_builder(command_map["--title"]); else if(command_map.find("-t") != command_map.end()) builder = new todo_builder(command_map["-t"]); if(command_map.find("--description") != command_map.end()) builder->desc(command_map["--description"]); else if(command_map.find("-d") != command_map.end()) builder->desc(command_map["-d"]); if(command_map.find("--important") != command_map.end()) builder->important(std::stoi(command_map["--important"])); else if(command_map.find("-i") != command_map.end()) builder->important(std::stoi(command_map["-i"])); std::string cat_string; if(command_map.find("--category") != command_map.end()){ cat_string = command_map["--category"]; } else if(command_map.find("-c") != command_map.end()){ cat_string = command_map["-c"]; } // find category category c = cr->find_best_match(cat_string); int cat_id = c.get_id(); builder->category(cat_id); m_todo* new_note = builder->build(); tr->save(new_note); exit(1); } void execute_log(int num){ std::vector<log> logs = lr->findAll(); int border = logs.size()-num-1; for(int i=logs.size()-1; i> (num!=-1?border:-1); --i){ std::cout<<"\nLog Type: "<<MAGENTA<<logs[i].get_log_type()<<RESET; std::cout<<"\nLog Message: "<<logs[i].get_desc()<<"\n\n"; }std::cout<<std::endl; exit(1); } void execute_category(int argc, std::vector<std::string>& argv){ if(argv[2]=="--help" || argv[2]=="-h") about_category(); if(argv[2]=="--list" || argv[2]=="-l") list_category(argc, argv); if(!argc>=4) { std::cout<<std::endl<<RED<<"Wrong number of arguments."<<RESET<<std::endl; exit(1); } if((argv[2]=="--delete" || argv[2]=="-d") && argc==4) delete_category(std::stoi(argv[3])); if(argc==4 && (argv[2]=="--info" || argv[2]=="-i")){ category c = cr->find_best_match(argv[3]); std::vector<m_todo> todos = tr->find_all_by_category(c.get_id()); std::cout<<"Id: "<<c.get_id()<<std::endl; std::cout<<"Title: "<<c.get_title()<<std::endl; std::cout<<"Description: "<<c.get_desc()<<std::endl; std::cout<<"Todo count: "<<todos.size()<<"\n"; list_todos(todos); exit(1); } if(argc==4 && (argv[2]=="--detailed-info" || argv[2]=="-di")){ category c = cr->find_best_match(argv[3]); std::vector<m_todo> todos = tr->find_all_by_category(c.get_id()); std::cout<<"Id: "<<c.get_id()<<std::endl; std::cout<<"Title: "<<c.get_title()<<std::endl; std::cout<<"Description: "<<c.get_desc()<<std::endl; std::cout<<"Todo count: "<<todos.size()<<"\n"; list_detailed_todos(todos); exit(1); } add_category(argc, argv); exit(1); } void list_category(int argc, std::vector<std::string>& argv){ if(argc==3){ // just print all std::vector<category> categories = cr->findAll(); std::cout<<std::endl; for(category c : categories) std::cout<<c.get_title()<<"\n"; std::cout<<std::endl; exit(1); } if(argc==4 && (argv[3]=="--details" || argv[3]=="-d")){ std::vector<category> categories = cr->findAll(); for(category c : categories){ std::cout<<"Id: "<<c.get_id(); std::cout<<"\nTitle: "<<c.get_title(); std::cout<<"\nDescription: "<<c.get_desc()<<"\n\n"; } exit(1); } exit(1); } void delete_category(int id){ cr->remove(id); exit(1); } void add_category(int argc, std::vector<std::string>& argv){ if(argc==4 && (argv[2]=="--title" || argv[2]=="-t")){ std::string title = argv[3]; category* c = new category(title); cr->save(c); exit(1); } if(argc==6 && (argv[4]=="--description" || argv[4]=="-d")){ std::string title = argv[3]; std::string description = argv[5]; category* c = new category(title, description); cr->save(c); exit(1); } exit(1); }
33.315702
590
0.635195
[ "vector" ]
97530187c4414e69ad3145a99c605396c55a5ee4
7,889
cpp
C++
Parallel_BubbleSort.cpp
RicardoGtz/MPI_Parallel_BubbleSort
3e93150f6fb5d9755f8079e1edf80a2f4497bf0a
[ "MIT" ]
null
null
null
Parallel_BubbleSort.cpp
RicardoGtz/MPI_Parallel_BubbleSort
3e93150f6fb5d9755f8079e1edf80a2f4497bf0a
[ "MIT" ]
null
null
null
Parallel_BubbleSort.cpp
RicardoGtz/MPI_Parallel_BubbleSort
3e93150f6fb5d9755f8079e1edf80a2f4497bf0a
[ "MIT" ]
null
null
null
#include "mpi.h" #include <stdio.h> #include <stdlib.h> #include <math.h> #define SEED 5 #define N 200000 int *array; // Arreglo original int *localArray; // Arreglo de proceso int taskid, // ID del procesador */ numtasks, // Numero de procesadores a usar start, // Index de incio de su parte del arreglo size, // Tamaño de elementos del procesador left=-1, // Indice del vecino a la izquierda right=-1, // Indice del vecino a la derecha *result; void createFile(char c[]); void loadFile(char c[]); void splitArray(); void sendAndSort(); void collectFromWorkers(); void reportToMaster(); int main(int argc, char *argv[]) { char c[]="Array1.txt"; //Crea el arreglo a ordenar createFile(c); /* Inicializa MPI */ MPI_Init(&argc,&argv); MPI_Comm_rank(MPI_COMM_WORLD,&taskid); MPI_Comm_size(MPI_COMM_WORLD,&numtasks); //Carga el archivo loadFile(c); //Asigna los vecinos de cada proceso if(taskid==0){ right=taskid+1; }else if(taskid==numtasks-1){ left=taskid-1; }else{ right=taskid+1; left=taskid-1; } //Imprime el arreglo original if(taskid==0){ printf("Arreglo Original\n"); for(int i=0;i<N;i++) printf("%d ",array[i]); printf("\n"); } //Comienza a medir el Tiempo double ti= MPI_Wtime(); //Divide el arreglo a cada proceso splitArray(); //Cada proceso ordena su parte y se comunica sendAndSort(); if(taskid==0){ //Recolecta los resultados de los trabajadores collectFromWorkers(); }else{ //Envia los resultados al nodo maestro reportToMaster(); } //Termina de medir el tiempo double tf= MPI_Wtime(); if(taskid==0){ //Imprime el arreglo final ordenado printf("*****************************\n"); printf("Arreglo Ordenado\n"); for(int i=0;i<N;i++) printf("%d ",result[i]); printf("\n"); //Imprime el tiempo de ejecucion printf("Tiempo de ejecucion: %f\n",(tf-ti) ); free(result); } //Finaliza la seccion paralela MPI_Finalize(); free(array); free(localArray); return 0; } void createFile(char c[]){ //Crea un puntero tipo file FILE *file; file=fopen(c,"w"); if( file==NULL ) printf("Error to create File\n"); else { //Escribe una linea en el archivo fprintf(file,"%d\n",N); //Define la semilla para generar numeros aleatorios srand(SEED); //Escribe los n numeros en el archivo for(int i=0;i<N;i++){ fprintf(file,"%d\n",rand()%100); } } fclose(file); } void loadFile(char c[]){ //Creamos un puntero de tipo FILE FILE *fp; //Abrimos el archivo a leer if((fp = fopen (c,"r" ))==NULL){ printf("No se pudo leer el archivo\n"); }else{ int n=0; fscanf(fp,"%d",&n); array=(int *)malloc(n*sizeof(int)); //Cargamos los elementos del arreglo for (int i = 0; i < n; ++i) fscanf(fp,"%d",&array[i]); } } void splitArray(){ int nmin, nleft, nnum; //Define el tamaño de particion nmin=N/numtasks; nleft=N%numtasks; int k=0; for (int i = 0; i < numtasks; i++) { nnum = (i < nleft) ? nmin + 1 : nmin; if(i==taskid){ start=k+1; size=nnum; printf ("tarea=%2d Inicio=%2d tamaño=%2d right=%2d left=%2d\n", taskid,start, size, right, left); localArray=(int *)malloc((size+2)*sizeof(int)); //Copia los elemntos del arreglo original al local for(int j=1;j<size+1;j++) localArray[j]=array[k+j-1]; } k+=nnum; } } void sendAndSort(){ MPI_Status status; for(int i=0;i<N;i++){ int sleft=0,sright=0; //Corrida par if(i%2==0){ for(int j=0;j<numtasks;j++){ if(j==taskid){ int flag=(start+size-1)%2; if(flag==1 && taskid < numtasks-1){ sright++; //Enviar ultimo elemnto a la derecha //printf("Proceso %d envia a %d\n",taskid,right); MPI_Send(&localArray[size] //referencia al vector de elementos a enviar ,1 // tamaño del vector a enviar ,MPI_INT // Tipo de dato que envias ,right // pid del proceso destino ,0 //etiqueta ,MPI_COMM_WORLD); //Comunicador por el que se manda //Recibir de la tarea a la derecha //printf("Proceso %d recibe de %d\n",taskid,right); MPI_Recv(&localArray[size+1] // Referencia al vector donde se almacenara lo recibido ,1 // tamaño del vector a recibir ,MPI_INT // Tipo de dato que recibe ,right // pid del proceso origen de la que se recibe ,1 // etiqueta ,MPI_COMM_WORLD // Comunicador por el que se recibe ,&status); // estructura informativa del estado }/*else*/ if((start%2)==0 && taskid > 0){ sleft++; //Enviar primer elemnto a la Izquierda //printf("Proceso %d envia a %d\n",taskid,left); MPI_Send(&localArray[1],1,MPI_INT,left,1,MPI_COMM_WORLD); //Recibir ultimo elmento de la izquierda //printf("Proceso %d recibe de %d\n",taskid,left); MPI_Recv(&localArray[0],1,MPI_INT,left,0,MPI_COMM_WORLD,&status); } } } //Ordenamiento por corrida par for(int k=1-sleft;k<size+sright;k+=2) if(localArray[k]>localArray[k+1]){ //Intercambio binario localArray[k]^=localArray[k+1]; localArray[k+1]^=localArray[k]; localArray[k]^=localArray[k+1]; } } //Corrida non else{ for(int j=0;j<numtasks;j++){ if(j==taskid){ int flag=(start+size-1)%2; if((start%2)==1 && taskid > 0){ sleft++; //Enviar ultimo elemnto a la Izquierda //printf("Proceso %d envia a %d\n",taskid,left); MPI_Send(&localArray[1],1,MPI_INT,left,1,MPI_COMM_WORLD); //Recibir ultimo elmento de la izquierda //printf("Proceso %d recibe de %d\n",taskid,left); MPI_Recv(&localArray[0],1,MPI_INT,left,0,MPI_COMM_WORLD,&status); }/*else*/ if(flag==0 && taskid < numtasks-1){ sright++; //Enviar ultimo elemnto a la derecha //printf("Proceso %d envia a %d\n",taskid,right); MPI_Send(&localArray[size],1,MPI_INT,right,0,MPI_COMM_WORLD); //Recibir de la tarea a la derecha //printf("Proceso %d recibe de %d\n",taskid,right); MPI_Recv(&localArray[size+1],1,MPI_INT,right,1,MPI_COMM_WORLD,&status); } } } //Ordenamiento por corrida non for(int k=(start%2)+1-(sleft*2);k<size+sright;k+=2) if(localArray[k]>localArray[k+1]){ //Intercambio binario localArray[k]^=localArray[k+1]; localArray[k+1]^=localArray[k]; localArray[k]^=localArray[k+1]; } } } /*for(int i=1;i<size+1;i++) printf("[%d] %d ",taskid,localArray[i]); printf("\n");*/ } void collectFromWorkers(){ MPI_Status status; result= (int *)malloc(N*sizeof(int)); int buffer[2]; for(int i=1;i<numtasks;i++){ //Recibe parametros de los trabajadores MPI_Recv(buffer,2,MPI_INT,i,0,MPI_COMM_WORLD,&status); int iStart=buffer[0]; int iSize=buffer[1]; //Recibe la parte del arreglo de cada trabajador MPI_Recv(&result[iStart-1],iSize,MPI_INT,i,1,MPI_COMM_WORLD,&status); } //Añade los resultados del nodo maestro al resultados for(int i=start;i<start+size;i++) result[i-1]=localArray[i]; } void reportToMaster(){ int buffer[2]; buffer[0]=start; buffer[1]=size; //Envia los parametros al proceso Maestro MPI_Send(buffer,2,MPI_INT,0,0,MPI_COMM_WORLD); //Envia su parte del arrgelo al proceso Maestro MPI_Send(&localArray[1],size,MPI_INT,0,1,MPI_COMM_WORLD); }
30.816406
108
0.582837
[ "vector" ]
975bf636160a9d269a36081441506ab3fd9a4e75
6,269
cpp
C++
src/Emulator.cpp
NiwakaDev/X86_EMULATOR_2
2e725e0eaa543048ce9a20bd223bcdcde2df7a73
[ "MIT" ]
16
2021-11-19T22:26:22.000Z
2022-02-16T12:38:50.000Z
src/Emulator.cpp
NiwakaDev/X86_EMULATOR_2
2e725e0eaa543048ce9a20bd223bcdcde2df7a73
[ "MIT" ]
1
2022-02-19T04:56:47.000Z
2022-02-19T10:00:58.000Z
src/Emulator.cpp
NiwakaDev/X86_EMULATOR_2
2e725e0eaa543048ce9a20bd223bcdcde2df7a73
[ "MIT" ]
null
null
null
#include "Emulator.h" #include <fstream> #include "Bios.h" #include "Cpu.h" #include "Fdc.h" #include "Gui.h" #include "IoPort.h" #include "Kbc.h" #include "Memory.h" #include "Mouse.h" #include "Pic.h" #include "Timer.h" #include "Vga.h" using namespace std; #ifdef DEBUG extern bool niwaka_start_flg; #endif Emulator::Emulator(int argc, char* argv[]) { this->obj = make_unique<Object>(); #ifdef DEBUG this->disk_image_name = "haribote.img"; this->bios_name = "test386.bin"; #else if (this->ParseArgv(argc, argv) == 0) { fprintf(stderr, "Usage: ./x86 [ OPTIONS ]\n"); fprintf(stderr, " -image, -i : disk-image-name\n"); fprintf(stderr, " -d : debug\n"); fprintf(stderr, " -b : bios-name\n"); exit(EXIT_FAILURE); } #endif for (int i = 0; i < 16; i++) { this->io_devices[i] = NULL; } fstream disk_image_stream; disk_image_stream.open(disk_image_name, ios::in | ios::binary); if (!disk_image_stream.is_open()) { cerr << "can`t open " << this->disk_image_name << " at Emulator::Emulator" << endl; exit(EXIT_FAILURE); } auto file_read_callback = [&](uint8_t* buff, int size) { disk_image_stream.seekg(0); disk_image_stream.read((char*)buff, size); }; try { this->mem = make_unique<Memory>(MEM_SIZE); this->fdc = make_unique<Fdc>(file_read_callback); this->timer = make_unique<Timer>(); this->mouse = make_unique<Mouse>(); this->kbc = make_unique<Kbc>(*(this->mouse.get())); // TODO : マジックナンバーを修正 this->io_devices[0x00] = this->timer.get(); this->io_devices[0x01] = this->kbc.get(); this->io_devices[0x06] = this->fdc.get(); this->io_devices[0x0C] = this->mouse.get(); this->pic = make_unique<Pic>(this->io_devices); // TODO : 自動フォーマッタを使う。 this->vga = make_unique<Vga>( [&](const uint32_t addr) { return this->mem->Read8(addr); }); this->bios = make_unique<Bios>(file_read_callback, *(this->vga.get()), *(this->kbc.get())); this->cpu = make_unique<Cpu>( [&](Cpu& cpu, Memory& mem, const uint8_t bios_number) { this->bios->CallFunction(cpu, mem, bios_number); }, *(this->mem.get()), [&](uint16_t addr) { return this->io_port->In8(addr); }, [&](uint16_t addr, uint8_t data) { this->io_port->Out8(addr, data); }); this->io_port = make_unique<IoPort>( *(this->vga.get()), *(this->pic.get()), *(this->kbc.get()), *(this->timer.get()), *(this->fdc.get())); this->gui = make_unique<Gui>(DEFAULT_HEIGHT, DEFAULT_WIDTH); this->gui->AddIoDevice(Gui::KBD, [&](uint8_t data) { this->kbc->Push(data); }); this->gui->AddIoDevice(Gui::MOUSE, [&](uint8_t data) { this->mouse->Push(data); }); this->bios->LoadIpl(file_read_callback, [&](uint32_t addr, uint8_t data) { this->mem->Write(addr, data); }); for (int i = 0; i < 0x20; i++) { // full.img and fd.imgで利用, // 8086runを参考 this->mem->Write(i << 2, i); } } catch (const char* error_message) { cout << error_message << endl; exit(EXIT_FAILURE); } catch (const runtime_error& e) { cout << e.what() << endl; exit(EXIT_FAILURE); } #ifdef DEBUG // biosをロードする。 fstream bios_stream; bios_stream.open(this->bios_name, ios::in | ios::binary); if (!bios_stream.is_open()) { this->obj->Error("Cant open : %s", this->bios_name); } const int BIOS_ROM_SIZE = 65536; bios_stream.read((char*)this->mem->GetPointer(0x000f0000), BIOS_ROM_SIZE); // bios_stream.read((char*)this->mem->GetPointer(0xffff0000), BIOS_ROM_SIZE); bios_stream.close(); #endif } Emulator::~Emulator() {} int Emulator::ParseArgv(int argc, char* argv[]) { #ifdef DEBUG int parse_result = 0; argv++; argc--; while (argc > 0) { if ((strcmp("-image", argv[0]) == 0) || (strcmp("-i", argv[0]) == 0)) { this->disk_image_name = argv[1]; argc -= 2; argv += 2; parse_result += 1; continue; } if ((strcmp("-bios", argv[0]) == 0) || (strcmp("-b", argv[0]) == 0)) { this->bios_name = argv[1]; argc -= 2; argv += 2; parse_result += 1; continue; } return 0; } return parse_result; #else int parse_result = 0; argv++; argc--; while (argc > 0) { if ((strcmp("-image", argv[0]) == 0) || (strcmp("-i", argv[0]) == 0)) { this->disk_image_name = argv[1]; argc -= 2; argv += 2; parse_result += 1; continue; } return 0; } return parse_result; #endif } void Emulator::ThreadJoin() { this->emu_thread->join(); } void Emulator::RunMainLoop() { #ifdef DEBUG this->MainLoop(); #else this->emu_thread = make_unique<thread>(&Emulator::MainLoop, this); #endif } void Emulator::RunGuiThread() { this->gui->Display([&](Pixel* image, int* display_width, int* display_height, std::function<void()> resize_callback) { this->vga->SetImage(image, display_width, display_height, resize_callback); }); } void Emulator::MainLoop() { #ifdef DEBUG fstream log_stream; log_stream.open("output.txt", ios::out); if (!log_stream.is_open()) { cerr << "ファイルが開けませんでした" << endl; exit(EXIT_FAILURE); } fprintf(stderr, "DEBUG\n"); #endif try { while (!this->gui->IsQuit()) { if ((this->cpu->IsException()) || (this->cpu->IsFlag(IF) && this->cpu->IsProtectedMode())) { if (this->cpu->IsException()) { this->cpu->HandleInterrupt(this->cpu->GetVectorNumber()); } else if (this->pic->HasIrq()) { this->cpu->HandleInterrupt(this->pic->GetNowIrq() + 0x20); } } this->cpu->Run(); } } catch (const runtime_error& e) { this->cpu->ShowRegisters(); cout << e.what() << endl; this->gui->Finish(); } catch (const out_of_range& e) { this->cpu->ShowRegisters(); cout << e.what() << endl; this->gui->Finish(); } catch (const system_error& e) { this->cpu->ShowRegisters(); cout << e.what() << endl; this->gui->Finish(); } catch (const char* error_message) { this->cpu->ShowRegisters(); cerr << error_message << endl; this->gui->Finish(); } }
29.995215
79
0.579678
[ "object" ]
975c204f001d7b23e65cc7190d5d42122d5e172c
4,281
cpp
C++
src/Pyros3D/Assets/Renderable/Primitives/Shapes/TorusKnot.cpp
Peixinho/Pyros3D
d6857ce99f3731a851ca5e7d67afbb13aafd18e0
[ "MIT" ]
20
2016-02-15T23:22:06.000Z
2021-12-07T00:13:49.000Z
src/Pyros3D/Assets/Renderable/Primitives/Shapes/TorusKnot.cpp
Peixinho/Pyros3D
d6857ce99f3731a851ca5e7d67afbb13aafd18e0
[ "MIT" ]
1
2017-09-04T00:28:19.000Z
2017-09-05T11:00:12.000Z
src/Pyros3D/Assets/Renderable/Primitives/Shapes/TorusKnot.cpp
Peixinho/Pyros3D
d6857ce99f3731a851ca5e7d67afbb13aafd18e0
[ "MIT" ]
3
2016-08-10T02:44:08.000Z
2021-05-28T23:03:10.000Z
//============================================================================ // Name : Torus Knot // Author : Duarte Peixinho // Version : // Copyright : ;) // Description : Torus Knot Geometry //============================================================================ #include <Pyros3D/Assets/Renderable/Primitives/Shapes/TorusKnot.h> namespace p3d { TorusKnot::TorusKnot(const f32 radius, const f32 tube, const uint32 segmentsW, const uint32 segmentsH, const f32 p, const f32 q, const uint32 heightscale, bool smooth, bool flip, bool TangentBitangent) { isFlipped = flip; isSmooth = smooth; calculateTangentBitangent = TangentBitangent; this->radius = radius; this->p = p; this->q = q; this->heightScale = (f32)heightscale; Vec3 normal; // counters size_t i, j; // vars aux Vec3 tang, n, bitan; std::vector< std::vector <Vec3> > aVtc; for (i = 0; i < segmentsW; ++i) { std::vector<Vec3> aRow; for (j = 0; j < segmentsH; ++j) { f32 u = (f32)((f32)i / segmentsW * 2 * p*PI); f32 v = (f32)((f32)j / segmentsH * 2 * PI); Vec3 p = GetPos(u, v); Vec3 p2 = GetPos((f32)(u + .01), (f32)(v)); f32 cx, cy; tang.x = p2.x - p.x; tang.y = p2.y - p.y; tang.z = p2.z - p.z; n.x = p2.x + p.x; n.y = p2.y + p.y; n.z = p2.z + p.z; bitan = tang.cross(n); n = bitan.cross(tang); bitan.normalizeSelf(); n.normalizeSelf(); cx = tube*cos(v); cy = tube*sin(v); p.x += cx * n.x + cy * bitan.x; p.y += cx * n.y + cy * bitan.y; p.z += cx * n.z + cy * bitan.z; Vec3 oVtx = Vec3(p.x, p.z, p.y); aRow.push_back(oVtx); } aVtc.push_back(aRow); } for (i = 0; i < segmentsW; ++i) { for (j = 0; j < segmentsH; ++j) { int ip = (i + 1) % segmentsW; int jp = (j + 1) % segmentsH; Vec3 a = aVtc[i][j]; Vec3 b = aVtc[ip][j]; Vec3 c = aVtc[i][jp]; Vec3 d = aVtc[ip][jp]; Vec2 aUV = Vec2((f32)i / segmentsW, (f32)j / segmentsH); Vec2 bUV = Vec2((f32)(i + 1) / segmentsW, (f32)j / segmentsH); Vec2 cUV = Vec2((f32)i / segmentsW, (f32)(j + 1) / segmentsH); Vec2 dUV = Vec2((f32)(i + 1) / segmentsW, (f32)(j + 1) / segmentsH); normal = ((c - b).cross(a - b)).normalize(); geometry->tVertex.push_back(a); geometry->tNormal.push_back(normal); geometry->tTexcoord.push_back(aUV); geometry->tVertex.push_back(b); geometry->tNormal.push_back(normal); geometry->tTexcoord.push_back(bUV); geometry->tVertex.push_back(c); geometry->tNormal.push_back(normal); geometry->tTexcoord.push_back(cUV); geometry->index.push_back(geometry->tVertex.size() - 3); geometry->index.push_back(geometry->tVertex.size() - 2); geometry->index.push_back(geometry->tVertex.size() - 1); normal = ((b - c).cross(d - c)).normalize(); geometry->tVertex.push_back(d); geometry->tNormal.push_back(normal); geometry->tTexcoord.push_back(dUV); geometry->tVertex.push_back(c); geometry->tNormal.push_back(normal); geometry->tTexcoord.push_back(cUV); geometry->tVertex.push_back(b); geometry->tNormal.push_back(normal); geometry->tTexcoord.push_back(bUV); geometry->index.push_back(geometry->tVertex.size() - 3); geometry->index.push_back(geometry->tVertex.size() - 2); geometry->index.push_back(geometry->tVertex.size() - 1); } } Vec3 min = geometry->tVertex[0]; for (uint32 i = 0; i < geometry->tVertex.size(); i++) { if (geometry->tVertex[i].x < min.x) min.x = geometry->tVertex[i].x; if (geometry->tVertex[i].y < min.y) min.y = geometry->tVertex[i].y; if (geometry->tVertex[i].z < min.z) min.z = geometry->tVertex[i].z; geometry->tTexcoord[i].x = 1 - geometry->tTexcoord[i].x; } Build(); // Bounding Box minBounds = min; maxBounds = min.negate(); // Bounding Sphere BoundingSphereCenter = Vec3(0, 0, 0); BoundingSphereRadius = min.distance(Vec3::ZERO); } Vec3 TorusKnot::GetPos(const f32 u, const f32 v) const { f32 cu = cos(u); f32 su = sin(u); f32 quOverP = this->q / this->p*u; f32 cs = cos(quOverP); Vec3 pos; pos.x = (f32)(this->radius*(2 + cs)*.5*cu); pos.y = (f32)(this->radius*(2 + cs)*su*.5); pos.z = (f32)(heightScale*radius*sin(quOverP)*.5); return pos; } };
33.186047
202
0.580005
[ "geometry", "vector" ]
975c242a5ca6a9749ad7c018e2c34d085d5fb750
6,101
cpp
C++
modules/surface_matching/samples/ppf_load_match.cpp
Nondzu/opencv_contrib
0b0616a25d4239ee81fda965818b49b721620f56
[ "BSD-3-Clause" ]
7,158
2016-07-04T22:19:27.000Z
2022-03-31T07:54:32.000Z
modules/surface_matching/samples/ppf_load_match.cpp
Nondzu/opencv_contrib
0b0616a25d4239ee81fda965818b49b721620f56
[ "BSD-3-Clause" ]
2,184
2016-07-05T12:04:14.000Z
2022-03-30T19:10:12.000Z
modules/surface_matching/samples/ppf_load_match.cpp
Nondzu/opencv_contrib
0b0616a25d4239ee81fda965818b49b721620f56
[ "BSD-3-Clause" ]
5,535
2016-07-06T12:01:10.000Z
2022-03-31T03:13:24.000Z
// // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2014, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation 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. // // Author: Tolga Birdal <tbirdal AT gmail.com> #include "opencv2/surface_matching.hpp" #include <iostream> #include "opencv2/surface_matching/ppf_helpers.hpp" #include "opencv2/core/utility.hpp" using namespace std; using namespace cv; using namespace ppf_match_3d; static void help(const string& errorMessage) { cout << "Program init error : "<< errorMessage << endl; cout << "\nUsage : ppf_matching [input model file] [input scene file]"<< endl; cout << "\nPlease start again with new parameters"<< endl; } int main(int argc, char** argv) { // welcome message cout << "****************************************************" << endl; cout << "* Surface Matching demonstration : demonstrates the use of surface matching" " using point pair features." << endl; cout << "* The sample loads a model and a scene, where the model lies in a different" " pose than the training.\n* It then trains the model and searches for it in the" " input scene. The detected poses are further refined by ICP\n* and printed to the " " standard output." << endl; cout << "****************************************************" << endl; if (argc < 3) { help("Not enough input arguments"); exit(1); } #if (defined __x86_64__ || defined _M_X64) cout << "Running on 64 bits" << endl; #else cout << "Running on 32 bits" << endl; #endif #ifdef _OPENMP cout << "Running with OpenMP" << endl; #else cout << "Running without OpenMP and without TBB" << endl; #endif string modelFileName = (string)argv[1]; string sceneFileName = (string)argv[2]; Mat pc = loadPLYSimple(modelFileName.c_str(), 1); // Now train the model cout << "Training..." << endl; int64 tick1 = cv::getTickCount(); ppf_match_3d::PPF3DDetector detector(0.025, 0.05); detector.trainModel(pc); int64 tick2 = cv::getTickCount(); cout << endl << "Training complete in " << (double)(tick2-tick1)/ cv::getTickFrequency() << " sec" << endl << "Loading model..." << endl; // Read the scene Mat pcTest = loadPLYSimple(sceneFileName.c_str(), 1); // Match the model to the scene and get the pose cout << endl << "Starting matching..." << endl; vector<Pose3DPtr> results; tick1 = cv::getTickCount(); detector.match(pcTest, results, 1.0/40.0, 0.05); tick2 = cv::getTickCount(); cout << endl << "PPF Elapsed Time " << (tick2-tick1)/cv::getTickFrequency() << " sec" << endl; //check results size from match call above size_t results_size = results.size(); cout << "Number of matching poses: " << results_size; if (results_size == 0) { cout << endl << "No matching poses found. Exiting." << endl; exit(0); } // Get only first N results - but adjust to results size if num of results are less than that specified by N size_t N = 2; if (results_size < N) { cout << endl << "Reducing matching poses to be reported (as specified in code): " << N << " to the number of matches found: " << results_size << endl; N = results_size; } vector<Pose3DPtr> resultsSub(results.begin(),results.begin()+N); // Create an instance of ICP ICP icp(100, 0.005f, 2.5f, 8); int64 t1 = cv::getTickCount(); // Register for all selected poses cout << endl << "Performing ICP on " << N << " poses..." << endl; icp.registerModelToScene(pc, pcTest, resultsSub); int64 t2 = cv::getTickCount(); cout << endl << "ICP Elapsed Time " << (t2-t1)/cv::getTickFrequency() << " sec" << endl; cout << "Poses: " << endl; // debug first five poses for (size_t i=0; i<resultsSub.size(); i++) { Pose3DPtr result = resultsSub[i]; cout << "Pose Result " << i << endl; result->printPose(); if (i==0) { Mat pct = transformPCPose(pc, result->pose); writePLY(pct, "para6700PCTrans.ply"); } } return 0; }
38.13125
112
0.633503
[ "vector", "model" ]
976192a8b24854172395d234f58d183b6a8a1b99
7,707
cpp
C++
lab3/main.cpp
Failjak/cpp_lab_4term
a2e859143fdcc50e670a8eb4cf35c7b3c768c43e
[ "BSD-3-Clause" ]
null
null
null
lab3/main.cpp
Failjak/cpp_lab_4term
a2e859143fdcc50e670a8eb4cf35c7b3c768c43e
[ "BSD-3-Clause" ]
null
null
null
lab3/main.cpp
Failjak/cpp_lab_4term
a2e859143fdcc50e670a8eb4cf35c7b3c768c43e
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <vector> #include <memory> #include <algorithm> #include "Pharmacy.hpp" #include "Pharmacy.cpp" using namespace std; void exitFunc(); Pharmacy * createPharmacy(); int main_menu(); int order_menu(); int search_menu(); int sort_menu(); int choice_edit_field(); void get_pharmacy_list(Pharmacy *); void edit_pharmacy(Pharmacy *); int main() { Pharmacy * pharmacy = createPharmacy(); User user("Batk", "Semen", 12); bool flag = true; while(flag) { switch (main_menu()) { case 1: pharmacy->printInfo(); break; case 2: { system("clear"); Pharmacist * pharm = pharmacy->choicePharm(); pharm->printInfo(); Order * order = pharmacy->createOrder(&user); order->printInfo(); break; } case 3: { get_pharmacy_list(pharmacy); break; } case 4: { edit_pharmacy(pharmacy); break; } case 0: cout << "Exit" << endl; flag = false; break; default: cout << "Wrong choice" << endl; break; } } return 0; } void edit_pharmacy(Pharmacy * pharmacy) { switch (choice_edit_field()) { case 1: { string new_value; cout << "Enter a new value for the City: "; cin >> new_value; pharmacy->setCity(new_value); break; } case 2: { string new_value; cout << "Enter a new value for the Street: "; cin >> new_value; pharmacy->setStreet(new_value); break; } case 3: { string new_value; cout << "Enter a new value for the Building: "; cin >> new_value; pharmacy->setBuild(new_value); break; } case 0: break; default: cout << "Wrond chocie" << endl; break; } } int choice_edit_field() { cout << "Select the filed to edit." << endl; cout << "1 - City" << endl; cout << "2 - Street" << endl; cout << "3 - Building" << endl; int choice; while (1) { cin >> choice; if (cin.good()) { break; } cin.clear(); cout << "Wrong choice" << endl; cin.ignore(10, '\n'); } return choice; } /// COMPARATORS bool compareMedicaments(Medicament m1, Medicament m2) { return (m1.getTitle() < m2.getTitle()); } bool comparePharmacists(Pharmacist p1, Pharmacist p2) { return (p1.getSurname() < p2.getSurname()); } /// COMPARATORS void get_pharmacy_list(Pharmacy * pharmacy) { cout << "1 - just List\n" << "2 - Sort\n" << "3 - Search\n" << "0 - Exit\n" << endl; int choice; while (1) { cin >> choice; if (cin.good()) { break; } cin.clear(); cout << "Wrong choice" << endl; cin.ignore(10, '\n'); } switch (choice) { case 1: { pharmacy->printInfo(); break; } case 2: // SORT { switch (sort_menu()) { case 1: // medicaments { vector<Medicament> meds = pharmacy->getMedicaments(); sort(meds.begin(), meds.end(), compareMedicaments); cout << "After sorting" << endl; int i = 0; for (auto x : meds) cout << ++i << ")", x.printInfo(); break; } case 2: // pharmacists { vector<Pharmacist> pharms = pharmacy->getPharmacists(); sort(pharms.begin(), pharms.end(), comparePharmacists); cout << "After sorting" << endl; int i = 0; for (auto x : pharms) cout << ++i << ")" << x.getFullName() << endl; break; } case 0: break; default: cout << "Wrong choice (in sort)" << endl; return; } } case 3: // SEARCH { int search_choice = search_menu(); switch (search_choice) { case 1: // medicaments { string title; cout << "Enter title to search in Medicaments: "; cin >> title; for (auto x : pharmacy->getMedicaments()) if (x.getTitle() == title) { cout << "Found equal value:" << endl; x.printInfo(); } break; } case 2: // pharmacists { string surname; cout << "Enter surname to search in Pharmacists: "; cin >> surname; for (auto x : pharmacy->getPharmacists()) if (x.getSurname() == surname) { cout << "Found equal value:" << endl; x.printInfo(); } break; } case 0: break; default: cout << "Wrong choice" << endl; break; } } case 0: return; default: cout << "Wrong choice" << endl; return; } } int main_menu() { cout.setf(ios::right); cout.width(20); cout << "MAIN MENU" << endl; cout.unsetf(ios::right); cout << "1 - See info about the pharmacy\n" << "2 - Make an order\n" << "3 - Get list of the orders\n" << "4 - Edit info about the order\n" << "0 - Выход\n" << endl; int choice; while (1) { cin >> choice; if (cin.good()) { break; } cin.clear(); cout << "Wrong choice" << endl; cin.ignore(10, '\n'); } return choice; } int sort_menu() { cout << "Sort by ..." << endl; cout << "1 - Medicaments" << endl; cout << "2 - Pharmacists" << endl; int choice; while (1) { cin >> choice; if (cin.good()) { break; } cin.clear(); cout << "Wrong choice" << endl; cin.ignore(10, '\n'); } return choice; } int search_menu() { cout << "Search in ..." << endl; cout << "1 - Medicaments" << endl; cout << "2 - Pharmacists" << endl; int choice; while (1) { cin >> choice; if (cin.good()) { break; } cin.clear(); cout << "Wrong choice" << endl; cin.ignore(10, '\n'); } return choice; } Pharmacy * createPharmacy() { vector<Pharmacist> pharms = { Pharmacist("Gushtyn", "Nikita", -500), Pharmacist("Ageev", "Alex", 700) }; Medicament * medicments; try { while (true) { medicments = new Medicament[100000000000000]; } } catch (bad_alloc exept) { cout << "Возникло исключение " << exept.what() << endl; } vector<Medicament> medicaments = { Medicament("Xarelto", "At the risk of blood clots in the vessels", 20.0), Medicament("Ibuprofen", "For pain, fever, rheumatism, colds", 12.4), Medicament("Detralex", "With varicose veins", 10.3), Medicament("Mexidol", "With strokes, neuroses, alcoholism", 7.5), Medicament("Miramistin", "When it is necessary to disinfect the skin or mucous membranes", -2.5), }; Pharmacy * pharm(new Pharmacy(pharms, {"Minsk", "Pervomaiskaya", "35/2"}, medicaments)); return pharm; }; void exitFunc() { cout << "Функция завершения" << endl; exit(-1); }
19.2675
105
0.466848
[ "vector" ]
976b40b8d354a464ad64b683e597bc3fe291e4e0
4,411
cpp
C++
Data Structure Review/Chapter 7/UndirectedGraph.cpp
Freeman449s/Data-Structure-Review
e757c73a1ed75261f26de61afd4ba55df06bfe8d
[ "MIT" ]
null
null
null
Data Structure Review/Chapter 7/UndirectedGraph.cpp
Freeman449s/Data-Structure-Review
e757c73a1ed75261f26de61afd4ba55df06bfe8d
[ "MIT" ]
null
null
null
Data Structure Review/Chapter 7/UndirectedGraph.cpp
Freeman449s/Data-Structure-Review
e757c73a1ed75261f26de61afd4ba55df06bfe8d
[ "MIT" ]
null
null
null
// // Created by Freeman on 2021/9/23. // #include "../Util.hpp" #include "../Chapter 6/UnionFindSet.hpp" #include "UndirectedGraph.hpp" using namespace std; #ifndef DBL_MAX #define DBL_MAX 1E308 #endif bool UndirectedGraph::addEdge(int tail, int head) { if (tail < 0 || tail >= nVex || head < 0 || head >= nVex) throw IllegalArgumentException(); if (!vertices[tail].addEdge(head)) return false; else { nEdges += 1; vertices[head].addEdge(tail); return true; } } bool UndirectedGraph::addEdge(int tail, int head, double weight) { if (!weighted) throw IllegalOperationException(); if (tail < 0 || tail >= nVex || head < 0 || head >= nVex) throw IllegalArgumentException(); if (!vertices[tail].addEdge(head, weight)) return false; else { nEdges += 1; vertices[head].addEdge(tail, weight); return true; } } void UndirectedGraph::DFS(int startVex) { bool *visited = new bool[nVex]; for (int i = 0; i < nVex; i++) visited[i] = false; DFSRecur(startVex, visited); delete[] visited; } void UndirectedGraph::DFSRecur(int startVex, bool visited[]) { visit(startVex); visited[startVex] = true; EdgeNode *edge = vertices[startVex].firstEdge; while (edge) { if (!visited[edge->vexNO]) DFSRecur(edge->vexNO, visited); edge = edge->next; } } void UndirectedGraph::BFS(int startVex) { bool *visited = new bool[nVex]; for (int i = 0; i < nVex; i++) visited[i] = false; int queueSize = nVex; int *queue = new int[queueSize]; int front = 0, rear = 0; rear = (rear + 1) % queueSize; queue[rear] = startVex; while (front != rear) { front = (front + 1) % queueSize; int vexNO = queue[front]; visit(vexNO); visited[vexNO] = true; EdgeNode *edge = vertices[vexNO].firstEdge; while (edge) { if (!visited[edge->vexNO]) { rear = (rear + 1) % queueSize; queue[rear] = edge->vexNO; } edge = edge->next; } } delete[] queue; delete[] visited; } set<pair<int, int>> UndirectedGraph::Prim() { set<pair<int, int>> tree; // 记录了生成树含有的边 bool *inTree = new bool[nVex]; // 指示顶点是否已在树中 double *dist = new double[nVex]; // 树外顶点到树的距离,定义为与树中各邻接顶点的边的最小权值 int *closetVex = new int[nVex]; // 距离最近的顶点 for (int i = 0; i < nVex; i++) { inTree[i] = false; dist[i] = DBL_MAX; } inTree[0] = true; EdgeNode *edge = vertices[0].firstEdge; while (edge) { dist[edge->vexNO] = edge->weight; closetVex[edge->vexNO] = 0; edge = edge->next; } while (true) { // 寻找距离最近的顶点 double min = DBL_MAX; int min_index = -1; for (int i = 0; i < nVex; i++) { if (!inTree[i]) { if (dist[i] < min) { min = dist[i]; min_index = i; } } } if (min_index == -1) break; // 已经找不到与树直接相连的顶点 // 将顶点和边加入树 tree.insert(pair<int, int>(min_index, closetVex[min_index])); inTree[min_index] = true; edge = vertices[min_index].firstEdge; while (edge) { if (!inTree[edge->vexNO]) { if (dist[edge->vexNO] > edge->weight) { dist[edge->vexNO] = edge->weight; closetVex[edge->vexNO] = min_index; } } edge = edge->next; } } return tree; } set<pair<int, int>> UndirectedGraph::Kruskal() { vector<Edge> edges; set<pair<int, int>> tree; // 构建所有边的集合,排序由set容器完成。 for (int i = 0; i < nVex; i++) { EdgeNode *edgeNode = vertices[i].firstEdge; while (edgeNode) { Edge edge = Edge(i, edgeNode->vexNO, false, edgeNode->weight); edges.push_back(edge); edgeNode = edgeNode->next; } } Util::insertionSort<Edge>(edges); UnionFindSet UFSet = UnionFindSet(nVex); while (!edges.empty() && tree.size() < nVex - 1) { // 寻找连接树内和树外结点的最小边,将之加入树中。 Edge edge = *edges.begin(); edges.erase(edges.begin()); if (UFSet.Find(edge.head) != UFSet.Find(edge.tail)) { UFSet.Union(edge.head, edge.tail); tree.insert(pair<int, int>(edge.head, edge.tail)); } } return tree; }
28.095541
95
0.542961
[ "vector" ]
9770af8772faf86daab53ee0bd56ec29297b0713
6,281
cpp
C++
rtti/include/reflection/type/type_info.cpp
TheTryton/rtti
2ff97c6fe6d799f03754f4deaada5d6c57fd07fa
[ "MIT" ]
1
2018-12-14T04:56:46.000Z
2018-12-14T04:56:46.000Z
rtti/include/reflection/type/type_info.cpp
TheTryton/rtti
2ff97c6fe6d799f03754f4deaada5d6c57fd07fa
[ "MIT" ]
null
null
null
rtti/include/reflection/type/type_info.cpp
TheTryton/rtti
2ff97c6fe6d799f03754f4deaada5d6c57fd07fa
[ "MIT" ]
null
null
null
#pragma once #include "type_info.hpp" REFLECTION_NAMESPACE_BEGIN type_info::~type_info() { for(auto& constructor_info : _constructors) { delete constructor_info.second; } } bool type_info::is_same(const type_info* other) const { return other == this; } bool type_info::has_default_constructor() const { auto exists_default_constructor = find_if(_constructors.begin(), _constructors.end(), [](const auto& constructor_info) { return constructor_info.second->args_count() == 0; }); return exists_default_constructor != _constructors.end(); } bool type_info::has_copy_constructor() const { auto exists_copy_constructor = find_if(_constructors.begin(), _constructors.end(), [this](const auto& constructor_info) { if(constructor_info.second->args_count() == 1) { if(constructor_info.second->arg_type(0) == this) { return true; } } return false; }); return exists_copy_constructor != _constructors.end(); } bool type_info::has_constructor(constructor_uuid constructor_uuid) const { auto exists_constructor = _constructors.find(constructor_uuid); return exists_constructor != _constructors.end(); } bool type_info::has_constructor(vector<any>&& args) const { auto exists_constructor = find_if(_constructors.begin(), _constructors.end(), [&args](const auto& constructor_info) { auto constructor_native_types = constructor_info.second->args_native_types(); if (constructor_native_types.size() < args.size()) { return false; } for (size_t i = 0; i < constructor_native_types.size(); i++) { if(constructor_native_types[i] != type_index(args[i].type())) { return false; } } return true; }); return exists_constructor != _constructors.end(); } const constructor_info * type_info::find_constructor(constructor_uuid constructor_uuid) const { auto exists_constructor = _constructors.find(constructor_uuid); return (exists_constructor != _constructors.end()) ? exists_constructor->second : nullptr; } const constructor_info * type_info::find_constructor(vector<any>&& args) const { auto exists_constructor = find_if(_constructors.begin(), _constructors.end(), [&args](const auto& constructor_info) { auto constructor_native_types = constructor_info.second->args_native_types(); if (constructor_native_types.size() < args.size()) { return false; } for (size_t i = 0; i < constructor_native_types.size(); i++) { if (constructor_native_types[i] != type_index(args[i].type())) { return false; } } return true; }); return (exists_constructor != _constructors.end()) ? exists_constructor->second : nullptr; } void* type_info::construct() const { auto exists_default_constructor = find_if(_constructors.begin(), _constructors.end(), [](const auto& constructor_info) { return constructor_info.second->args_count() == 0; }); if(exists_default_constructor != _constructors.end()) { return exists_default_constructor->second->construct(); } return nullptr; } void* type_info::copy_construct(any && arg) const { auto exists_copy_constructor = find_if(_constructors.begin(), _constructors.end(), [this](const auto& constructor_info) { if (constructor_info.second->args_count() == 1) { if (constructor_info.second->arg_type(0) == this) { return true; } } return false; }); if (exists_copy_constructor != _constructors.end()) { return exists_copy_constructor->second->construct({ arg }); } return nullptr; } void* type_info::construct(vector<any>&& args) const { if (args.empty()) { return construct(); } auto exists_constructor = find_if(_constructors.begin(), _constructors.end(), [&args](const auto& constructor_info) { auto constructor_native_types = constructor_info.second->args_native_types(); if (constructor_native_types.size() < args.size()) { return false; } for (size_t i = 0; i < constructor_native_types.size(); i++) { if (constructor_native_types[i] != type_index(args[i].type())) { return false; } } return true; }); if (exists_constructor != _constructors.end()) { return exists_constructor->second->construct(forward<vector<any>>(args)); } return nullptr; } vector<const constructor_info*> type_info::constructors() const { vector<const constructor_info*> constructors(_constructors.size()); transform(_constructors.begin(), _constructors.end(), constructors.begin(), [](const auto& constructor_info) { return constructor_info.second; }); return constructors; } size_t type_info::constructors_count() const { return _constructors.size(); } bool type_info::is_enum() const { return false; } bool type_info::is_class() const { return false; } bool type_info::is_template_type() const { return false; } bool type_info::is_convertible_to(const type_info* other) const { if(!other) { return false; } if(has_const_specifier() && !other->has_const_specifier()) { return false; } if(is_integral() && other->is_integral()) { return true; } else if(is_integral() && other->is_floating_point()) { return true; } else if(is_floating_point() && other->is_floating_point()) { return true; } else if (is_floating_point() && other->is_integral()) { return true; } return false; } bool type_info::is_base_of(const type_info * other) const { return false; } const enum_info* type_info::as_enum_info() const { return nullptr; } const class_info* type_info::as_class_info() const { return nullptr; } const template_type_info* type_info::as_template_type_info() const { return nullptr; } REFLECTION_NAMESPACE_END
25.2249
125
0.638593
[ "vector", "transform" ]
9774ac2f7feb01c9db1b1f6f00471d1b6a4565f8
10,624
cpp
C++
tf2_bot_detector/Config/Rules.cpp
Chrissucks/tf2_bot_detector
4a073e576c96f017c01531e4a37541e4c74ee250
[ "MIT" ]
null
null
null
tf2_bot_detector/Config/Rules.cpp
Chrissucks/tf2_bot_detector
4a073e576c96f017c01531e4a37541e4c74ee250
[ "MIT" ]
null
null
null
tf2_bot_detector/Config/Rules.cpp
Chrissucks/tf2_bot_detector
4a073e576c96f017c01531e4a37541e4c74ee250
[ "MIT" ]
null
null
null
#include "Rules.h" #include "IPlayer.h" #include "JSONHelpers.h" #include "Log.h" #include "PlayerListJSON.h" #include "Settings.h" #include <mh/text/case_insensitive_string.hpp> #include <mh/text/string_insertion.hpp> #include <nlohmann/json.hpp> #include <fstream> #include <iomanip> #include <regex> #include <stdexcept> #include <string> using namespace std::string_literals; using namespace std::string_view_literals; using namespace tf2_bot_detector; namespace tf2_bot_detector { void to_json(nlohmann::json& j, const TextMatchMode& d) { switch (d) { case TextMatchMode::Equal: j = "equal"; break; case TextMatchMode::Contains: j = "contains"; break; case TextMatchMode::StartsWith: j = "starts_with"; break; case TextMatchMode::EndsWith: j = "ends_with"; break; case TextMatchMode::Regex: j = "regex"; break; case TextMatchMode::Word: j = "word"; break; default: throw std::runtime_error("Unknown TextMatchMode value "s << +std::underlying_type_t<TextMatchMode>(d)); } } void to_json(nlohmann::json& j, const TriggerMatchMode& d) { switch (d) { case TriggerMatchMode::MatchAll: j = "match_all"; break; case TriggerMatchMode::MatchAny: j = "match_any"; break; default: throw std::runtime_error("Unknown TriggerMatchMode value "s << +std::underlying_type_t<TriggerMatchMode>(d)); } } void to_json(nlohmann::json& j, const TextMatch& d) { j = { { "mode", d.m_Mode }, { "case_sensitive", d.m_CaseSensitive }, { "patterns", d.m_Patterns }, }; } void to_json(nlohmann::json& j, const ModerationRule::Triggers& d) { size_t count = 0; if (d.m_ChatMsgTextMatch) { j["chatmsg_text_match"] = *d.m_ChatMsgTextMatch; count++; } if (d.m_UsernameTextMatch) { j["username_text_match"] = *d.m_UsernameTextMatch; count++; } if (count > 1) j["mode"] = d.m_Mode; } void to_json(nlohmann::json& j, const ModerationRule::Actions& d) { if (!d.m_Mark.empty()) j["mark"] = d.m_Mark; if (!d.m_Unmark.empty()) j["unmark"] = d.m_Unmark; } void to_json(nlohmann::json& j, const ModerationRule& d) { j = { { "description", d.m_Description }, { "triggers", d.m_Triggers }, { "actions", d.m_Actions }, }; } void from_json(const nlohmann::json& j, TriggerMatchMode& d) { const std::string_view& str = j.get<std::string_view>(); if (str == "match_all"sv) d = TriggerMatchMode::MatchAll; else if (str == "match_any"sv) d = TriggerMatchMode::MatchAny; else throw std::runtime_error("Invalid value for TriggerMatchMode "s << std::quoted(str)); } void from_json(const nlohmann::json& j, TextMatchMode& mode) { const std::string_view str = j; if (str == "equal"sv) mode = TextMatchMode::Equal; else if (str == "contains"sv) mode = TextMatchMode::Contains; else if (str == "starts_with"sv) mode = TextMatchMode::StartsWith; else if (str == "ends_with"sv) mode = TextMatchMode::EndsWith; else if (str == "regex"sv) mode = TextMatchMode::Regex; else if (str == "word"sv) mode = TextMatchMode::Word; else throw std::runtime_error("Unable to parse TextMatchMode from "s << std::quoted(str)); } void from_json(const nlohmann::json& j, TextMatch& d) { d.m_Mode = j.at("mode"); d.m_Patterns = j.at("patterns").get<std::vector<std::string>>(); if (!try_get_to(j, "case_sensitive", d.m_CaseSensitive)) d.m_CaseSensitive = false; } void from_json(const nlohmann::json& j, ModerationRule::Triggers& d) { if (auto found = j.find("mode"); found != j.end()) d.m_Mode = *found; if (auto found = j.find("chatmsg_text_match"); found != j.end()) d.m_ChatMsgTextMatch.emplace(TextMatch(*found)); if (auto found = j.find("username_text_match"); found != j.end()) d.m_UsernameTextMatch.emplace(TextMatch(*found)); } void from_json(const nlohmann::json& j, ModerationRule::Actions& d) { try_get_to(j, "mark", d.m_Mark); try_get_to(j, "unmark", d.m_Unmark); } void from_json(const nlohmann::json& j, ModerationRule& d) { d.m_Description = j.at("description"); d.m_Triggers = j.at("triggers"); d.m_Actions = j.at("actions"); } } ModerationRules::ModerationRules(const Settings& settings) : m_Settings(&settings) { // Immediately load and resave to normalize any formatting Load(); Save(); } bool ModerationRules::Load() { if (!IsOfficial()) LoadFile("cfg/rules.json", m_UserRules); LoadFile("cfg/rules.official.json", m_OfficialRules); m_OtherRules.clear(); if (std::filesystem::is_directory("cfg")) { try { for (const auto& file : std::filesystem::directory_iterator("cfg", std::filesystem::directory_options::follow_directory_symlink | std::filesystem::directory_options::skip_permission_denied)) { static const std::regex s_RulesRegex(R"regex(rules\.(.*\.)?json)regex", std::regex::optimize); const auto path = file.path(); const auto filename = path.filename().string(); if (mh::case_insensitive_compare(filename, "rules.json"sv) || mh::case_insensitive_compare(filename, "rules.official.json"sv)) continue; if (std::regex_match(filename.begin(), filename.end(), s_RulesRegex)) { LoadFile(path, m_OtherRules); } } } catch (const std::filesystem::filesystem_error& e) { LogError(std::string(__FUNCTION__ ": Exception when loading rules.*.json files from ./cfg/: ") << e.what()); } } return true; } bool ModerationRules::Save() const { nlohmann::json json = { { "$schema", "./schema/rules.schema.json" }, }; json["rules"] = GetMutableList(); // Make sure we successfully serialize BEFORE we destroy our file auto jsonString = json.dump(1, '\t', true); { std::ofstream file(IsOfficial() ? "cfg/rules.official.json" : "cfg/rules.json"); file << jsonString << '\n'; } return true; } mh::generator<const ModerationRule*> tf2_bot_detector::ModerationRules::GetRules() const { for (const auto& rule : m_OfficialRules) co_yield &rule; for (const auto& rule : m_UserRules) co_yield &rule; for (const auto& rule : m_OtherRules) co_yield &rule; } bool ModerationRules::IsOfficial() const { // I'm special return m_Settings->m_LocalSteamID.IsPazer(); } bool ModerationRules::LoadFile(const std::filesystem::path& filename, RuleList_t& rules) const { Log("Loading rules list from "s << filename); nlohmann::json json; { std::ifstream file(filename); if (!file.good()) { LogWarning(std::string(__FUNCTION__ ": Failed to open ") << filename); return false; } try { file >> json; } catch (const std::exception& e) { LogError(std::string(__FUNCTION__ ": Exception when parsing JSON from ") << filename << ": " << e.what()); return false; } } bool success = true; if (auto found = json.find("rules"); found != json.end()) { rules = found->get<RuleList_t>(); } else { LogError(std::string(__FUNCTION__ ": Failed to find \"rules\" object when parsing JSON from ") << filename); success = false; } return success; } bool TextMatch::Match(const std::string_view& text) const { switch (m_Mode) { case TextMatchMode::Equal: { return std::any_of(m_Patterns.begin(), m_Patterns.end(), [&](const std::string_view& pattern) { if (m_CaseSensitive) return text == pattern; else return mh::case_insensitive_compare(text, pattern); }); } case TextMatchMode::Contains: { return std::any_of(m_Patterns.begin(), m_Patterns.end(), [&](const std::string_view& pattern) { if (m_CaseSensitive) return text.find(pattern) != text.npos; else return mh::case_insensitive_view(text).find(mh::case_insensitive_view(pattern)) != text.npos; }); break; } case TextMatchMode::StartsWith: { return std::any_of(m_Patterns.begin(), m_Patterns.end(), [&](const std::string_view& pattern) { if (m_CaseSensitive) return text.starts_with(pattern); else return mh::case_insensitive_view(text).starts_with(mh::case_insensitive_view(pattern)); }); } case TextMatchMode::EndsWith: { return std::any_of(m_Patterns.begin(), m_Patterns.end(), [&](const std::string_view& pattern) { if (m_CaseSensitive) return text.ends_with(pattern); else return mh::case_insensitive_view(text).ends_with(mh::case_insensitive_view(pattern)); }); } case TextMatchMode::Regex: { return std::any_of(m_Patterns.begin(), m_Patterns.end(), [&](const std::string_view& pattern) { std::regex_constants::syntax_option_type options{}; if (!m_CaseSensitive) options = std::regex_constants::icase; std::regex r(pattern.begin(), pattern.end(), options); return std::regex_match(text.begin(), text.end(), r); }); } case TextMatchMode::Word: { static const std::regex s_WordRegex(R"regex((\w+))regex", std::regex::optimize); const auto end = std::regex_iterator<std::string_view::const_iterator>{}; for (auto it = std::regex_iterator<std::string_view::const_iterator>(text.begin(), text.end(), s_WordRegex); it != end; ++it) { const std::string_view itStr(&*it->operator[](0).first, it->operator[](0).length()); const auto anyMatches = std::any_of(m_Patterns.begin(), m_Patterns.end(), [&](const std::string_view& pattern) { if (m_CaseSensitive) return itStr == pattern; else return mh::case_insensitive_compare(itStr, pattern); }); if (anyMatches) return true; } return false; } default: throw std::runtime_error("Unknown TextMatchMode "s << +std::underlying_type_t<TextMatchMode>(m_Mode)); } } bool ModerationRule::Match(const IPlayer& player) const { return Match(player, std::string_view{}); } bool ModerationRule::Match(const IPlayer& player, const std::string_view& chatMsg) const { const bool usernameMatch = [&]() { if (!m_Triggers.m_UsernameTextMatch) return false; const auto name = player.GetName(); if (name.empty()) return false; return m_Triggers.m_UsernameTextMatch->Match(name); }(); if (m_Triggers.m_Mode == TriggerMatchMode::MatchAny && usernameMatch) return true; const bool chatMsgMatch = [&]() { if (!m_Triggers.m_ChatMsgTextMatch || chatMsg.empty()) return false; return m_Triggers.m_ChatMsgTextMatch->Match(chatMsg); }(); if (m_Triggers.m_Mode == TriggerMatchMode::MatchAny && chatMsgMatch) return true; if (m_Triggers.m_Mode == TriggerMatchMode::MatchAll) { if (m_Triggers.m_UsernameTextMatch && m_Triggers.m_ChatMsgTextMatch) return usernameMatch && chatMsgMatch; else if (m_Triggers.m_UsernameTextMatch) return usernameMatch; else if (m_Triggers.m_ChatMsgTextMatch) return chatMsgMatch; } return false; }
25.97555
130
0.67837
[ "object", "vector" ]
9775262665649e751707941b62ff569274b81039
7,142
cpp
C++
src/addcontactdialog.cpp
SelfSellTeam/Wallet
15a047a308fb0145c6d5df4e54c53a58b59fbf07
[ "MIT" ]
1
2018-05-17T18:52:36.000Z
2018-05-17T18:52:36.000Z
src/addcontactdialog.cpp
SelfSellTeam/Wallet
15a047a308fb0145c6d5df4e54c53a58b59fbf07
[ "MIT" ]
null
null
null
src/addcontactdialog.cpp
SelfSellTeam/Wallet
15a047a308fb0145c6d5df4e54c53a58b59fbf07
[ "MIT" ]
null
null
null
#include "addcontactdialog.h" #include "ui_addcontactdialog.h" #include "datamgr.h" #include "goopal.h" #include <QDebug> #include <QMovie> AddContactDialog::AddContactDialog(QWidget *parent) : QDialog(parent), ui(new Ui::AddContactDialog) { ui->setupUi(this); // Goopal::getInstance()->appendCurrentDialogVector(this); setParent(Goopal::getInstance()->mainFrame); setAttribute(Qt::WA_TranslucentBackground, true); setWindowFlags(Qt::FramelessWindowHint); ui->widget->setObjectName("widget"); ui->widget->setStyleSheet("#widget {background-color:rgba(10, 10, 10,100);}"); ui->containerWidget->setObjectName("containerwidget"); ui->containerWidget->setStyleSheet("#containerwidget{background-color: rgb(246, 246, 246);border:1px groove rgb(180,180,180);}"); // connect( Goopal::getInstance(), SIGNAL(jsonDataUpdated(QString)), this, SLOT(jsonDataUpdated(QString))); QRegExp regx("[a-zA-Z0-9\-\.\ \n]+$"); QValidator *validator = new QRegExpValidator(regx, this); ui->addressLineEdit->setValidator( validator ); ui->addressLineEdit->setStyleSheet("color:black;border:1px solid #CCCCCC;border-radius:3px;"); ui->addressLineEdit->setTextMargins(8,0,0,0); ui->addressLineEdit->setPlaceholderText( tr("Please enter an account address or a registered account name.")); ui->addressLineEdit->setAttribute(Qt::WA_InputMethodEnabled, false); ui->remarkLineEdit->setStyleSheet("color:black;border:1px solid #CCCCCC;border-radius:3px;"); ui->remarkLineEdit->setTextMargins(8,0,0,0); ui->okBtn->setStyleSheet("QToolButton{background-color:#f49f17;color:#ffffff;border:0px solid rgb(64,153,255);border-radius:3px;}" "QToolButton:hover{background-color:#ffc362;}" "QToolButton:disabled{background-color:#cecece;}"); ui->okBtn->setEnabled(false); ui->cancelBtn->setStyleSheet("QToolButton{background-color:#ffffff;color:#282828;border:1px solid #62a9f8;border-radius:3px;}" "QToolButton:hover{color:#62a9f8;}"); ui->addressLineEdit->setFocus(); gif = new QMovie(DataMgr::getDataMgr()->getWorkPath() + "pic2/loading2.gif"); gif->setScaledSize( QSize(18,18)); ui->gifLabel->setMovie(gif); gif->start(); ui->gifLabel->hide(); setFontPixelSize(); } AddContactDialog::~AddContactDialog() { delete ui; // Goopal::getInstance()->removeCurrentDialogVector(this); } void AddContactDialog::setFontPixelSize() { QFont font = ui->contactLabel2->font(); font.setPixelSize(16); ui->contactLabel2->setFont(font); font = ui->label->font(); font.setPixelSize(13); ui->label->setFont(font); ui->label_2->setFont(font); font = ui->addressLineEdit->font(); font.setPixelSize(13); ui->addressLineEdit->setFont(font); ui->remarkLineEdit->setFont(font); font = ui->label_3->font(); font.setPixelSize(12); ui->label_3->setFont(font); } void AddContactDialog::pop() { // QEventLoop loop; // show(); // connect(this,SIGNAL(accepted()),&loop,SLOT(quit())); // loop.exec(); //进入事件 循环处理,阻塞 move(0,0); exec(); } void AddContactDialog::on_cancelBtn_clicked() { close(); // emit accepted(); } void AddContactDialog::on_addressLineEdit_textChanged(const QString &arg1) { ui->addressLineEdit->setText( ui->addressLineEdit->text().remove(" ")); ui->addressLineEdit->setText( ui->addressLineEdit->text().remove("\n")); if( ui->addressLineEdit->text().isEmpty()) { ui->tipLabel->setText(""); ui->tipLabel2->setPixmap(QPixmap("")); return; } if( ui->addressLineEdit->text().mid(0,3) == "GOP") { ui->tipLabel->setText(""); ui->tipLabel2->setPixmap(QPixmap("")); ui->okBtn->setEnabled(true); return; } QString str; if( ui->addressLineEdit->text().toInt() == 0) // 防止输入数字 { str = ui->addressLineEdit->text(); } else { str = "WRONG"; } // RpcThread* rpcThread = new RpcThread; // connect(rpcThread,SIGNAL(finished()),rpcThread,SLOT(deleteLater())); //// rpcThread->setLogin("a","b"); // rpcThread->setWriteData( toJsonFormat( "id_blockchain_get_account", "blockchain_get_account", QStringList() << str )); // rpcThread->start(); // Goopal::getInstance()->postRPC( toJsonFormat( "id_blockchain_get_account", "blockchain_get_account", QStringList() << str )); ui->gifLabel->show(); } void AddContactDialog::jsonDataUpdated(QString id) { if( id != "id_blockchain_get_account") return; QString result ;// = Goopal::getInstance()->jsonDataValue(id); ui->gifLabel->hide(); if( result == "\"result\":null") { ui->tipLabel->setText(tr("Invalid address")); ui->tipLabel2->setPixmap(QPixmap(DataMgr::getDataMgr()->getWorkPath() + "pic2/wrong.png")); ui->okBtn->setEnabled(false); } else { ui->tipLabel->setText(tr("<body><font color=green>Valid address</font></body>")); ui->tipLabel2->setPixmap(QPixmap(DataMgr::getDataMgr()->getWorkPath() + "pic2/correct.png")); ui->okBtn->setEnabled(true); } } void AddContactDialog::on_okBtn_clicked() { if( ui->addressLineEdit->text().simplified().isEmpty()) { ui->tipLabel->setText(tr("can not be empty")); ui->tipLabel2->setPixmap(QPixmap(DataMgr::getDataMgr()->getWorkPath() + "pic2/wrong.png")); return; } // if( !Goopal::getInstance()->contactsFile->open(QIODevice::ReadWrite)) if (true) { qDebug() << "contact.dat not exist"; return; } // QByteArray ba = QByteArray::fromBase64( Goopal::getInstance()->contactsFile->readAll()); // QString str(ba); QString str(""); QStringList strList = str.split(";"); strList.removeLast(); foreach (QString ss, strList) { if( (ss.mid(0, ss.indexOf('=')) == ui->addressLineEdit->text()) // && ss.mid( ss.indexOf('=') + 1) == ui->remarkLineEdit->text() ) { ui->tipLabel->setText(tr("Already existes")); ui->tipLabel2->setPixmap(QPixmap(DataMgr::getDataMgr()->getWorkPath() + "pic2/wrong.png")); // Goopal::getInstance()->contactsFile->close(); return; } } /* ba += ui->addressLineEdit->text().toUtf8() + '=' + ui->remarkLineEdit->text().toUtf8() + QString(";").toUtf8(); ba = ba.toBase64(); Goopal::getInstance()->contactsFile->resize(0); QTextStream ts(Goopal::getInstance()->contactsFile); ts << ba; Goopal::getInstance()->contactsFile->close(); */ close(); // emit accepted(); } void AddContactDialog::on_remarkLineEdit_textChanged(const QString &arg1) { QString remark = arg1; if( remark.contains("=") || remark.contains(";")) { remark.remove("="); remark.remove(";"); ui->remarkLineEdit->setText( remark); } }
32.463636
135
0.617054
[ "solid" ]
97846b87a0f120a6dbc8f47e2c5d21a640b9e7fa
7,251
cpp
C++
XRADSystem/Sources/PlatformSpecific/MSVC/Internal/FileNameOperations_Win32.cpp
n-kulberg/xrad
3d089cc24d942db4649f1a50defbd69f01739ae2
[ "BSD-3-Clause" ]
1
2021-04-02T16:47:00.000Z
2021-04-02T16:47:00.000Z
XRADSystem/Sources/PlatformSpecific/MSVC/Internal/FileNameOperations_Win32.cpp
n-kulberg/xrad
3d089cc24d942db4649f1a50defbd69f01739ae2
[ "BSD-3-Clause" ]
null
null
null
XRADSystem/Sources/PlatformSpecific/MSVC/Internal/FileNameOperations_Win32.cpp
n-kulberg/xrad
3d089cc24d942db4649f1a50defbd69f01739ae2
[ "BSD-3-Clause" ]
3
2021-08-30T11:26:23.000Z
2021-09-23T09:39:56.000Z
/* Copyright (c) 2021, Moscow Center for Diagnostics & Telemedicine All rights reserved. This file is licensed under BSD-3-Clause license. See LICENSE file for details. */ #include "pre.h" #include "FileNameOperations_Win32.h" #ifdef XRAD_USE_FILENAMES_WIN32_VERSION #ifndef _MSC_VER #error "This file is for MS Visual Studio only" #endif #include <XRADBasic/Sources/Containers/DataArray.h> #include <windows.h> #include <stdexcept> #include <algorithm> //for transform #include <cwctype> //for towupper XRAD_BEGIN //-------------------------------------------------------------- wstring CmpNormalizeFilename_MS(const wstring &filename) { if (filename.length() >= 0x7FFFFFFF) throw length_error("CmpNormalizeFilename_MS: File name is too long."); wstring result(filename); CharUpperBuffW(&result[0], (DWORD)result.length()); return result; } //note (Kovbas) Нормализация путей для корректной работы с длинными путями. //todo (Kovbas) Возможно, нужно как-то объединить с CmpNormalizeFilename_MS namespace { wstring long_path_prefix = L"\\\\?\\"; wstring long_path_prefix_gen = L"//?/"; wstring long_unc_prefix = long_path_prefix + L"UNC\\"; wstring long_unc_prefix_gen = long_path_prefix_gen + L"UNC/"; wstring network_prefix = L"\\\\"; wstring network_prefix_gen = L"//"; } inline wstring path_expander(const wstring &path_in) { DataArray<wchar_t> buf(path_in.size() + 1); size_t retLen = GetLongPathNameW(path_in.c_str(), buf.data(), static_cast<DWORD>(buf.size())); if (retLen == 0) return path_in; if (retLen > buf.size()) { buf.realloc(retLen); retLen = GetLongPathNameW(path_in.c_str(), buf.data(), static_cast<DWORD>(buf.size())); } auto string_end = std::find(buf.begin(), buf.end(), '\0'); return wstring(buf.begin(), string_end); } //TODO возможно, не на месте wstring delete_all_unnecessary_backslashes(const wstring& in_path) { if (!in_path.length()) return wstring(); wstring path(in_path); bool appended = false; if (path.back() != L'\\') { // Добавляем в конец '\\' для единообразного разбора последовательностей вида ".\\". path += L"\\"; appended = true; } // TODO: По-хорошему, надо сначала выделить корень ("C:\", "\\server\share", "\\?\C:\"...), // потом оставшуюся часть упростить (убрать двойные '\\', пути ".\\", "folder\\.."), // в конце склеить корень и урощенную часть. size_t real_path_start_index = 0; if (path.front() == L'\\') { for (auto el : path) { if (el == '\\') ++real_path_start_index; else break; } } vector<wchar_t> buffer; buffer.push_back(path[real_path_start_index]); for (size_t i = real_path_start_index + 1; i < path.size(); ++i) { if (buffer.back() == '\\') { if (path[i] == '\\') continue; if (!wcsncmp(path.c_str()+i, L".\\", 2)) { ++i; continue; } if (!wcsncmp(path.c_str()+i, L"..\\", 3)) { auto rpos = std::find(std::next(buffer.rbegin()), buffer.rend(), L'\\') - buffer.rbegin(); while (rpos--) buffer.pop_back(); i += 2; continue; } } buffer.push_back(path[i]); } if (appended && buffer.back() == L'\\') buffer.pop_back(); return wstring(buffer.data(), buffer.size()); } wstring GetPathGenericFromAutodetect_MS(const wstring &original_path) { #if 1 wstring path(original_path); std::replace(path.begin(), path.end(), L'\\', L'/'); if (path.length() > long_path_prefix_gen.length() && path.substr(0, long_path_prefix_gen.length()) == long_path_prefix_gen) { // "\\\\?\\" // "\\\\?\\UNC\\" if (path.length() > long_unc_prefix_gen.length() && get_upper(path.substr(0, long_unc_prefix_gen.length())) == long_unc_prefix_gen) { return network_prefix_gen + path.substr(long_unc_prefix_gen.length()); } return path.substr(long_path_prefix_gen.length()); } return path; #else wstring path(GetPathSystemRawFromGeneric_MS(original_path)); wstring prefix(path.substr(0, long_unc_prefix.size())); transform(prefix.begin(), prefix.end(), prefix.begin(), toupper); if (prefix == long_unc_prefix) path = network_prefix + path.substr(long_unc_prefix.size()); if (path.substr(0, long_path_prefix.size()) == long_path_prefix) path = path.substr(long_path_prefix.size()); wstring buffer(path.size(), L'\0'); std::replace_copy(path.begin(), path.end(), buffer.begin(), L'\\', L'/'); return buffer; #endif } wstring GetPathNativeFromGeneric_MS(const wstring &original_path) { // Проверка формата: для отладки. if (original_path.find(L'\\') != original_path.npos) { fprintf(stderr, "GetPathSystemRawFromGeneric_MS: Path format is not generic: \"%s\".\n", EnsureType<const char*>(convert_to_string(original_path).c_str())); } wstring path(original_path); std::replace(path.begin(), path.end(), L'/', L'\\'); return path; } wstring GetPathSystemRawFromGeneric_MS(const wstring &original_path) { // "\\?\D:\very long path" or "\\?\UNC\server\share" according to https://docs.microsoft.com/en-us/windows/desktop/fileio/naming-a-file //https://arsenmk.blogspot.com/2015/12/handling-long-paths-on-windows.html wstring buffer(original_path.size(), L'\0'); // Проверка формата: для отладки. if (original_path.find(L'\\') != original_path.npos) { fprintf(stderr, "GetPathSystemRawFromGeneric_MS: Path format is not generic: \"%s\".\n", EnsureType<const char*>(convert_to_string(original_path).c_str())); } std::replace_copy(original_path.begin(), original_path.end(), buffer.begin(), L'/', L'\\'); // Уже готовый длинный путь, нечего менять if (buffer.substr(0, long_path_prefix.size()) == long_path_prefix) return path_expander(long_path_prefix + delete_all_unnecessary_backslashes(buffer.substr(long_path_prefix.size()))); // "Короткий" путь с буквой диска, добавить префикс if (buffer.substr(1, 2) == L":\\") return path_expander(long_path_prefix + delete_all_unnecessary_backslashes(buffer)); // "Короткий" путь к сетевому диску, добавить префикс, убрав начальные '\\' if (buffer.substr(0, network_prefix.size()) == network_prefix) return path_expander(long_unc_prefix + delete_all_unnecessary_backslashes(buffer.substr(network_prefix.size()))); // "Длинный" путь к сетевому ресурсу, возвращаемый Qt. Требует корректировки wstring prefix(buffer.substr(0, 5)); toupper(prefix); if (prefix == L"\\UNC\\") return path_expander(long_unc_prefix + delete_all_unnecessary_backslashes(buffer.substr(5))); prefix = buffer.substr(0, 4); toupper(prefix); if (prefix == L"UNC\\") { ForceDebugBreak(); //note (Kovbas) для проверки возможности такого варианта return path_expander(long_unc_prefix + delete_all_unnecessary_backslashes(buffer.substr(4))); } return buffer; //note Kovbas всё, что не удовлетворяет условиям, либо относительные пути, либо неправильные пути. Пусть пользователь с ними сам разбирается. } //-------------------------------------------------------------- XRAD_END #else // XRAD_USE_FILENAMES_WIN32_VERSION #include <XRADBasic/Core.h> XRAD_BEGIN // To avoid warning LNK4221: This object file does not define any previously undefined public // symbols, so it will not be used by any link operation that consumes this library. // (MSVC 2015) void xrad__dummy_FileNameOperations_Win32() {} XRAD_END #endif // XRAD_USE_FILENAMES_WIN32_VERSION
30.594937
157
0.69287
[ "object", "vector", "transform" ]
9789b639edaa009e29d50cdf74caec7a5ba2c892
8,041
cpp
C++
src/sim/cgi/sim_Gates.cpp
marek-cel/fightersfs
5511162726861fee17357f39274461250370c224
[ "MIT" ]
4
2021-01-28T17:39:38.000Z
2022-02-11T20:13:46.000Z
src/sim/cgi/sim_Gates.cpp
marek-cel/fightersfs
5511162726861fee17357f39274461250370c224
[ "MIT" ]
null
null
null
src/sim/cgi/sim_Gates.cpp
marek-cel/fightersfs
5511162726861fee17357f39274461250370c224
[ "MIT" ]
3
2021-02-22T21:22:30.000Z
2022-01-10T19:32:12.000Z
/****************************************************************************//* * Copyright (C) 2021 Marek M. Cel * * 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 <sim/cgi/sim_Gates.h> #include <osg/Billboard> #include <osg/Geode> #include <osg/LineWidth> #include <sim/cgi/sim_Color.h> #include <sim/utils/sim_Convert.h> #include <sim/sim_Ownship.h> //////////////////////////////////////////////////////////////////////////////// using namespace sim; //////////////////////////////////////////////////////////////////////////////// const float Gates::_distMax = 0.9 * SIM_SKYDOME_RAD; const float Gates::_distScale = 2000.0f; const float Gates::_size = 2.0f * Gates::_distScale * tan( Convert::deg2rad( 10.0f * 90.0f / 1200.0f ) ); //////////////////////////////////////////////////////////////////////////////// Gates::Gates( float linesWidth, Module *parent ) : Module( new osg::Switch(), parent ), _linesWidth ( linesWidth ) { _switch = dynamic_cast<osg::Switch*>( _root.get() ); _pat0 = new osg::PositionAttitudeTransform(); _pat1 = new osg::PositionAttitudeTransform(); _pat2 = new osg::PositionAttitudeTransform(); _switch->addChild( _pat0.get() ); _switch->addChild( _pat1.get() ); _switch->addChild( _pat2.get() ); _geom0 = createGate( _pat0.get() ); _geom1 = createGate( _pat1.get() ); _geom2 = createGate( _pat2.get() ); } //////////////////////////////////////////////////////////////////////////////// Gates::~Gates() {} //////////////////////////////////////////////////////////////////////////////// void Gates::update() { ///////////////// Module::update(); ///////////////// if ( Data::get()->mission.status == Pending && !Data::get()->paused && ( Data::get()->camera.type == ViewChase || Data::get()->camera.type == ViewPilot ) ) { if ( Data::get()->ownship.waypoint ) { if ( Data::get()->ownship.waypoint_dist < _distMax ) { // current gate _switch->setValue( 0, true ); _pat0->setPosition( Vec3( Data::get()->ownship.waypoint_x, Data::get()->ownship.waypoint_y, Data::get()->ownship.waypoint_z ) ); float coef = Data::get()->ownship.waypoint_dist / _distScale; if ( coef > 1.0f ) { _pat0->setScale( Vec3( coef, coef, coef ) ); } else { _pat0->setScale( Vec3( 1.0f, 1.0f, 1.0f ) ); } // following gates Aircraft *ownship = Ownship::instance()->getAircraft(); if ( ownship ) { coef = updateGate( _geom1, _pat1, ownship, 1, coef ); coef = updateGate( _geom2, _pat2, ownship, 2, coef ); } else { _switch->setValue( 1, false ); _switch->setValue( 2, false ); } } else { _switch->setAllChildrenOff(); } } else { _switch->setAllChildrenOff(); } } else { _switch->setAllChildrenOff(); } } //////////////////////////////////////////////////////////////////////////////// osg::Geometry* Gates::createGate( osg::Group *parent ) { const float w_2 = _size / 2.0f; const float h_2 = _size / 2.0f; osg::ref_ptr<osg::Billboard> billboard = new osg::Billboard(); parent->addChild( billboard.get() ); billboard->setMode( osg::Billboard::AXIAL_ROT ); billboard->setAxis( osg::Vec3( 0.0f, 0.0f, 1.0f ) ); billboard->setNormal( osg::Vec3f( 0.0f, 1.0f, 0.0f ) ); osg::ref_ptr<osg::Geometry> geometry = new osg::Geometry(); billboard->addDrawable( geometry.get(), osg::Vec3( 0.0, 0.0, 0.0 ) ); osg::ref_ptr<osg::Vec3Array> v = new osg::Vec3Array(); // vertices osg::ref_ptr<osg::Vec3Array> n = new osg::Vec3Array(); // normals osg::ref_ptr<osg::Vec4Array> c = new osg::Vec4Array(); // colors v->push_back( Vec3( -w_2, 0.0f, h_2 ) ); v->push_back( Vec3( -w_2, 0.0f, -h_2 ) ); v->push_back( Vec3( w_2, 0.0f, -h_2 ) ); v->push_back( Vec3( w_2, 0.0f, h_2 ) ); n->push_back( osg::Vec3( 0.0f, 1.0f, 0.0f ) ); c->push_back( osg::Vec4( Color::lime, 0.8f ) ); geometry->setVertexArray( v.get() ); geometry->addPrimitiveSet( new osg::DrawArrays( osg::PrimitiveSet::LINE_LOOP, 0, v->size() ) ); geometry->setNormalArray( n.get() ); geometry->setNormalBinding( osg::Geometry::BIND_OVERALL ); geometry->setColorArray( c.get() ); geometry->setColorBinding( osg::Geometry::BIND_OVERALL ); osg::ref_ptr<osg::StateSet> stateSet = billboard->getOrCreateStateSet(); osg::ref_ptr<osg::LineWidth> lineWidth = new osg::LineWidth(); lineWidth->setWidth( _linesWidth ); stateSet->setAttributeAndModes( lineWidth, osg::StateAttribute::ON ); stateSet->setMode( GL_LIGHTING , osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF ); stateSet->setMode( GL_LIGHT0 , osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF ); stateSet->setMode( GL_BLEND , osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON ); stateSet->setRenderingHint( osg::StateSet::TRANSPARENT_BIN ); return geometry.get(); } //////////////////////////////////////////////////////////////////////////////// float Gates::updateGate( osg::Geometry *geom, osg::PositionAttitudeTransform *pat, Aircraft *ownship, int number, float coef_prev ) { float coef = 0.0f; UInt32 index = ownship->getWaypointIndex() + number; // next waypoint if ( ownship->getRoute().size() > index ) { Vec3 pos = ownship->getRoute()[ index ].first; coef = ( ownship->getPos() - pos ).length() / _distScale; if ( coef_prev <= 1.0f ) { _switch->setValue( number, true ); pat->setPosition( pos ); // scaling if ( coef > 1.0f ) { pat->setScale( Vec3( coef, coef, coef ) ); } else { pat->setScale( Vec3( 1.0f, 1.0f, 1.0f ) ); } // fade in osg::ref_ptr<osg::Vec4Array> c = dynamic_cast< osg::Vec4Array* >( geom->getColorArray() ); if ( c.valid() ) { c->clear(); c->push_back( osg::Vec4( Color::grey, 1.0f * ( 1.0f - coef_prev ) ) ); geom->setColorArray( c.get() ); } } else { _switch->setValue( number, false ); } } else { _switch->setValue( number, false ); } return coef; }
33.227273
105
0.516105
[ "geometry" ]
978c93c13dddf17bb1fc95304cc466a2e5b4299e
1,748
hpp
C++
Hyades/src/Renderer/SwapChain.hpp
nbrockett/hyades
18d2218501d1352a88df187efec282174c46d3e0
[ "MIT" ]
null
null
null
Hyades/src/Renderer/SwapChain.hpp
nbrockett/hyades
18d2218501d1352a88df187efec282174c46d3e0
[ "MIT" ]
null
null
null
Hyades/src/Renderer/SwapChain.hpp
nbrockett/hyades
18d2218501d1352a88df187efec282174c46d3e0
[ "MIT" ]
null
null
null
// SwapChain // // The swap chain own the image buffer and synchronisies their presentation // #pragma once #include <vulkan/vulkan.h> #include "../HyadesPCH.hpp" #include "QueueFamily.hpp" #include "GLFW/glfw3.h" namespace Hyades { struct SwapChainSupportDetails { VkSurfaceCapabilitiesKHR capabilities; std::vector<VkSurfaceFormatKHR> formats; std::vector<VkPresentModeKHR> presentModes; }; class SwapChain { public: SwapChain(VkSurfaceKHR& surface, GLFWwindow *window); ~SwapChain(); void create(VkPhysicalDevice physical_device, QueueFamilyIndices indices, VkDevice device); void recreate(const VkExtent2D& extent); void create_image_views(); void create_framebuffers(const VkRenderPass& render_pass); SwapChainSupportDetails query_swap_chain_support(VkPhysicalDevice device); void clean(); VkSurfaceFormatKHR choose_surface_format(const std::vector<VkSurfaceFormatKHR> &available_formats); VkPresentModeKHR choose_present_mode(const std::vector<VkPresentModeKHR> &available_present_modes); VkExtent2D choose_extent(const VkSurfaceCapabilitiesKHR &capabilities); VkSwapchainKHR swapChain = VK_NULL_HANDLE; VkFormat swapChainImageFormat; VkExtent2D swapChainExtent; // TODO: move these to seperate location/class std::vector<VkImageView> m_imageviews; std::vector<VkFramebuffer> m_framebuffers; std::vector<VkImage> m_images; private: const VkSurfaceKHR& m_surface; VkDevice m_device; GLFWwindow *m_window; SwapChainSupportDetails swap_chain_support; }; } // namespace Hyades
26.089552
107
0.701945
[ "vector" ]
978f301b919d3d28307d4bd20fce13ede07509a7
20,597
cpp
C++
src/uvdar_rx.cpp
ctu-mrs/uvdar_core
85f01498b433660fcff7410e40d35b79d3ca225a
[ "BSD-3-Clause" ]
4
2020-09-15T14:48:36.000Z
2022-02-05T22:56:02.000Z
src/uvdar_rx.cpp
ctu-mrs/uvdar_core
85f01498b433660fcff7410e40d35b79d3ca225a
[ "BSD-3-Clause" ]
2
2021-06-29T03:18:39.000Z
2021-08-30T15:28:43.000Z
src/uvdar_rx.cpp
ctu-mrs/uvdar_core
85f01498b433660fcff7410e40d35b79d3ca225a
[ "BSD-3-Clause" ]
4
2020-11-02T16:58:12.000Z
2022-02-05T23:00:09.000Z
#include <ros/ros.h> #include <ros/package.h> #include <mrs_lib/param_loader.h> #include <cv_bridge/cv_bridge.h> #include <mrs_msgs/ImagePointsWithFloatStamped.h> #include <mrs_lib/transformer.h> #include <mrs_msgs/String.h> #include <std_msgs/Float32.h> #include <uvdar_core/RecMsg.h> #include <string> #include <cmath> #define SCFFE 30 #define MAX_CLUSTER 100 #define CHANNEL_OFF 20 #define SB 15 #define MAX_FRAME_SIZE 60 #define MIN_FRAME_SIZE 30 std::string uav_name; std::string recieved_topic; int uav_id = 0; ros::Publisher pub_rec_msg; // int scffe = 30; // samples count for framerate estimate /* float frequencies[] = {10, 15, 30, 5}; */ std::vector<std::string> points_seen_topics; std::vector<std::string> blinkers_seen_topics; std::vector<std::string> estimated_framerate_topics; std::vector<ros::Publisher> pub_blinkers_seen; std::vector<ros::Publisher> pub_estimated_framerate; using points_seen_callback = boost::function<void(const mrs_msgs::ImagePointsWithFloatStampedConstPtr&)>; std::vector<points_seen_callback> callbacks_points_seen; std::vector<ros::Subscriber> subscribers_points_seen; namespace RX { class RX_processor { public: RX_processor(ros::NodeHandle& nh) { mrs_lib::ParamLoader param_loader(nh, "UVDARrx"); param_loader.loadParam("uav_name", uav_name); param_loader.loadParam("uav_id", uav_id); param_loader.loadParam("recieved_topic", recieved_topic); param_loader.loadParam("points_seen_topics", points_seen_topics, points_seen_topics); param_loader.loadParam("blinkers_seen_topics", blinkers_seen_topics, blinkers_seen_topics); param_loader.loadParam("estimated_framerate_topics", estimated_framerate_topics, estimated_framerate_topics); if (points_seen_topics.empty()) { ROS_WARN("[RX_processor]: No topics of points_seen_topics were supplied. Returning."); return; } // make publishers for viktors pose calculator and filter for (size_t i = 0; i < blinkers_seen_topics.size(); ++i) { pub_blinkers_seen.push_back(nh.advertise<mrs_msgs::ImagePointsWithFloatStamped>(blinkers_seen_topics[i], 1)); } for (size_t i = 0; i < estimated_framerate_topics.size(); ++i) { pub_estimated_framerate.push_back(nh.advertise<std_msgs::Float32>(estimated_framerate_topics[i], 1)); } pub_rec_msg = nh.advertise<uvdar_core::RecMsg>(recieved_topic, 1); // to publish decoded msgs for uvdar node std::vector<std::vector<PointSeen>> tmp; for (int i = 0; i < (int)points_seen_topics.size(); ++i) { point_seen.push_back(tmp); // initialize points_seen vector for number of camera used ROS_INFO("[RX_Processor]: Added camera %d on topic %s", i, points_seen_topics[i].c_str()); CamInfo ci_new; ci_new.cam_id = i; cam_info.push_back(ci_new); // callback of individual image frames points_seen_callback callback = [i, this](const mrs_msgs::ImagePointsWithFloatStampedConstPtr& pointsMessage) { VisiblePoints(pointsMessage, i); }; callbacks_points_seen.push_back(callback); subscribers_points_seen.push_back(nh.subscribe(points_seen_topics[i], 1, callbacks_points_seen[i])); } ROS_INFO("Node initialized"); } private: int DataFrameCheck(std::vector<int>& received_msg_corrected) { int rmc_size = received_msg_corrected.size(); for (int bs = (rmc_size - 1); bs >= 3; bs--) { // check of Bit Stuffing and BS bits separation if (received_msg_corrected[bs - 1] == received_msg_corrected[bs - 2] && received_msg_corrected[bs - 2] == received_msg_corrected[bs - 3]) { if (received_msg_corrected[bs - 1] != received_msg_corrected[bs]) { received_msg_corrected.erase(received_msg_corrected.begin() + bs); // bs += 2; rmc_size--; } else { // std::cout << " BS fail |"; return 1; break; } } } received_msg_corrected.erase(received_msg_corrected.begin()); // separation of the rest of SOF needed for BS check rmc_size--; if ((rmc_size != 8) && (rmc_size != 9) && (rmc_size != 13)) { // check of frame length // std::cout << " FL fail " << rmc_size << " |"; return 1; } int parity_check = 0; for (auto& cnt : received_msg_corrected) { // parity check if (cnt > 0) parity_check++; } if (parity_check % 2 != 1) { // std::cout << " PA fail |"; return 1; } return 0; } float transferValues(int pl_value, int pl_size, int pl_index, int pl_type) { // float real_value = transferValues(tmp_pl, payload_size, pl, rec_dtype); float payload = -1.0; float lu_table_1[1][4] = {{0.1, 22.5, -1.0, -1.0}}; //[pl_index][pl_type] float lu_table_2[2][4] = {{22.5, -1.0, -1.0, -1.0}, {0.1, -1.0, -1.0, -1.0}}; //[pl_index][pl_type] switch (pl_size) { case 1: payload = (float)pl_value * lu_table_1[pl_index][pl_type]; break; case 2: payload = (float)pl_value * lu_table_2[pl_index][pl_type]; break; default: ROS_ERROR("Unexpected payload size"); break; } return payload; } void VisiblePoints(const mrs_msgs::ImagePointsWithFloatStampedConstPtr& points_seen_msg, size_t camera_index) { /* *Estimation and publishing of camera framerate * */ if (cam_info[camera_index].samples == 0) cam_info[camera_index].last_stamp = points_seen_msg->stamp; cam_info[camera_index].samples += 1; if (cam_info[camera_index].samples == SCFFE) { cam_info[camera_index].framerate = (SCFFE - 1) / (points_seen_msg->stamp.toSec() - cam_info[camera_index].last_stamp.toSec()); cam_info[camera_index].samples = 0; std_msgs::Float32 msgFramerate; msgFramerate.data = cam_info[camera_index].framerate; pub_estimated_framerate[camera_index].publish(msgFramerate); } /* *Expand clusters with a new camera frame * */ int cluster_count = point_seen[camera_index].size(); // count of point cluster currently in point_seen for (int i = 0; i < cluster_count; i++) { // add new blank record for each cluster in new camera frame PointSeen tmp_ps; tmp_ps.decoded = point_seen[camera_index][i].back().decoded; tmp_ps.id = point_seen[camera_index][i].back().id; /* tmp_ps.frequency = point_seen[camera_index][i].back().frequency; */ tmp_ps.cnt_last_published = point_seen[camera_index][i].back().cnt_last_published + 1; tmp_ps.position = cv::Point2i(point_seen[camera_index][i].back().position.x, point_seen[camera_index][i].back().position.y); int last_val_SOF = point_seen[camera_index][i].back().start_frame_index; if (last_val_SOF >= 0) tmp_ps.start_frame_index = ++last_val_SOF; // incrementing of SOF index for frame detection tmp_ps.count = 0; tmp_ps.sample_time = points_seen_msg->stamp; point_seen[camera_index][i].push_back(tmp_ps); if (point_seen[camera_index][i].size() > MAX_CLUSTER) { // if there are more records than 100 in one cluster, pop the oldest one point_seen[camera_index][i].erase(point_seen[camera_index][i].begin()); } for (int j = 0; j < CHANNEL_OFF; j++) { // if leds in cluster were not visible in last 20 frames, remove the cluster if (point_seen[camera_index][i][point_seen[camera_index][i].size() - 1 - j].count > 1) break; if (j == (CHANNEL_OFF - 1)) { point_seen[camera_index].erase(point_seen[camera_index].begin() + i); cluster_count--; if (cluster_count > 0) i--; } } } /* *Process new points * */ for (auto& point : points_seen_msg->points) { // if there is no cluster in the current camera frame, add point into new cluster and add this cluster into camera container if (point_seen[camera_index].empty()) { std::vector<PointSeen> tmp_vec; PointSeen tmp_ps; tmp_ps.position = cv::Point2i(point.x, point.y); tmp_ps.positions.push_back(cv::Point2i(point.x, point.y)); tmp_ps.count = 1; tmp_ps.sample_time = points_seen_msg->stamp; tmp_vec.push_back(tmp_ps); point_seen[camera_index].push_back(tmp_vec); continue; } // if the new point is close to one of old clusters, add it to this cluser. Will be replaced by nearest neighbor in the future bool point_added = false; int closest_id = 0; int closest_dist = -1; // std::cout << "Camera: " << camera_index << "- "; int cluster_count = point_seen[camera_index].size(); for (int i = 0; i < cluster_count; i++) { // int dfc = sqrt(pow(point_seen[camera_index][i].back().position.x - point.x, 2) + // pow(point_seen[camera_index][i].back().position.y - point.y, 2)); // distance from cluster int go_back_n = 0; while (point_seen[camera_index][i].rbegin()[go_back_n].count <= 1 && (int)point_seen[camera_index][i].size() > go_back_n + 1) { go_back_n++; } for (auto& pnt : point_seen[camera_index][i].rbegin()[go_back_n].positions) { int actual_dist = abs(point.x - pnt.x) + abs(point.y - pnt.y); // std::cout << actual_dist << "x" << i << " "; if (closest_dist == -1) { closest_dist = actual_dist; closest_id = i; } if (closest_dist > actual_dist) { closest_dist = actual_dist; closest_id = i; } } } // std::cout << "- " << closest_dist << std::endl; if (closest_dist < 35) { point_seen[camera_index][closest_id].back().positions.push_back(cv::Point2i(point.x, point.y)); point_seen[camera_index][closest_id].back().count += 1; point_added = true; // ROS_INFO("My pos: %f, %f. Cl id: %d, dist %d ", point.x, point.y, closest_id, closest_dist); } else { point_added = false; } // if the point was too far from each cluster and it was not added, make a new cluster if (!point_added) { std::vector<PointSeen> tmp_vec; PointSeen tmp_ps; tmp_ps.position = cv::Point2i(point.x, point.y); tmp_ps.positions.push_back(cv::Point2i(point.x, point.y)); tmp_ps.count = 1; tmp_ps.sample_time = points_seen_msg->stamp; tmp_vec.push_back(tmp_ps); point_seen[camera_index].push_back(tmp_vec); continue; } } /* * detection of SOF and EOF and decoding follow* * */ cluster_count = point_seen[camera_index].size(); for (int i = 0; i < cluster_count; i++) { if (point_seen[camera_index][i].size() < (MAX_CLUSTER / 2)) continue; // we have stable channel connection // publishing on blinkers seen topic if (point_seen[camera_index][i].back().decoded) { if (!point_seen[camera_index][i].back().positions.empty()) { if (point_seen[camera_index][i].back().cnt_last_published >= 5) { mrs_msgs::ImagePointsWithFloatStamped msg; msg.stamp = point_seen[camera_index][i].back().sample_time; msg.image_width = points_seen_msg->image_width; msg.image_height = points_seen_msg->image_height; for (auto& blinker : point_seen[camera_index][i].back().positions) { mrs_msgs::Point2DWithFloat point; point.x = blinker.x; point.y = blinker.y; point.value = point_seen[camera_index][i].back().id; msg.points.push_back(point); } pub_blinkers_seen[camera_index].publish(msg); point_seen[camera_index][i].back().cnt_last_published = 0; } } } /* for(auto& bit : point_seen[camera_index][i]){ */ /* std::cout << bit.count; */ /* } */ /* std::cout << std::endl; */ /* * SOF and EOF detection * */ if (point_seen[camera_index][i].rbegin()[0].count == 0 && point_seen[camera_index][i].rbegin()[1].count) { // possible start of frame detection for (int j = 1; j < (SB + 1); j++) { if (point_seen[camera_index][i].rbegin()[j].count == 0) break; if (j == SB) { // SOF validation // ROS_INFO("SOF"); point_seen[camera_index][i].back().start_frame_index = 0; } } } int j = 0; if (point_seen[camera_index][i].rbegin()[SB].count == 0 && point_seen[camera_index][i].rbegin()[SB + 1].count == 0) { // possible end of frame detection for (j = 0; j < SB; j++) { if (point_seen[camera_index][i].rbegin()[j].count == 0) break; } } if (j != (SB - 1)) continue; // EOF validation int sof = point_seen[camera_index][i].back().start_frame_index; if (sof < SB || sof >= (int)point_seen[camera_index][i].size()-1) continue; // ROS_INFO("EOF"); std::vector<PointSeen> received_msg; std::copy(point_seen[camera_index][i].rbegin() + SB - 1, point_seen[camera_index][i].rbegin() + sof + 1, back_inserter(received_msg)); // cut of the frame in range of SOF-EOF std::reverse(received_msg.begin(), received_msg.end()); int rmr_size = received_msg.size(); if ((rmr_size > MAX_FRAME_SIZE) || (rmr_size < MIN_FRAME_SIZE)) continue; /* *Cleaning of received msg */ std::vector<int> received_msg_raw; for (auto& bits : received_msg) { int bit_val = bits.count; if (bit_val < 2) { received_msg_raw.push_back(0); } else { received_msg_raw.push_back(1); } } while (received_msg_raw.front() == 0) { // start synchronize, the second part of SOF (bit 1) remains for BS check received_msg_raw.erase(received_msg_raw.begin()); } while (received_msg_raw.back() == 0) { // end synchronization received_msg_raw.pop_back(); } /* * Bit corrections */ std::vector<std::vector<int>> sub_frames; std::vector<int> sub_frame; int curr_bit; while (!received_msg_raw.empty()) { curr_bit = received_msg_raw.back(); while (received_msg_raw.back() == curr_bit && !received_msg_raw.empty()) { sub_frame.push_back(curr_bit); received_msg_raw.pop_back(); } sub_frames.push_back(sub_frame); sub_frame.clear(); } for (auto& frame : sub_frames) { int extra_bits = (int)frame.size() % 3; switch (extra_bits) { case 1: if (frame.size() == 1) { // frame.index size_t front_index = &frame - &sub_frames.front(); size_t back_index = &sub_frames.back() - &frame; if (front_index == 0 || back_index == 0) { frame.push_back(frame.front()); frame.push_back(frame.front()); } else if ((int)sub_frames[front_index - 1].size() > 2 || (int)sub_frames[front_index + 1].size() > 2) { frame.push_back(frame.front()); frame.push_back(frame.front()); } else { frame.pop_back(); } } else { frame.pop_back(); } break; case 2: frame.push_back(frame.front()); break; default: // ROS_INFO("Ok"); break; } } received_msg_raw.clear(); while (!sub_frames.empty()) { int bit_cnt = sub_frames.back().size() / 3; if (bit_cnt > 3) { bit_cnt = 3; // ROS_INFO("Correction from hodne to 3"); } for (int p = 0; p < bit_cnt; p++) { received_msg_raw.push_back(sub_frames.back().back()); } sub_frames.pop_back(); } received_msg_raw.pop_back(); int faults; faults = DataFrameCheck(received_msg_raw); // verify if the data frame is correct if (faults != 0) { // if both corrections were not succesful, ignore received frame ROS_WARN("Not able to decode msg"); received_msg_raw.clear(); continue; } /* * Validations and corrections are OK, decode data frame * * Predelat vse odsud dale * * */ uvdar_core::RecMsg rm_pub; int rec_id = 2 * received_msg_raw[0] + received_msg_raw[1]; if (rec_id == uav_id) { ROS_ERROR("My ID %d, redirecting to ID: %d", rec_id, point_seen[camera_index][i].back().id); rec_id = point_seen[camera_index][i].back().id; } if (point_seen[camera_index][i].back().id < 0) point_seen[camera_index][i].back().id = rec_id; if (point_seen[camera_index][i].back().id != rec_id) { // ROS_ERROR("Ignoring msg, bad ID %d", rec_id); ROS_ERROR("Bad ID %d, redirecting to ID: %d", rec_id, point_seen[camera_index][i].back().id); // continue; rec_id = point_seen[camera_index][i].back().id; } rm_pub.uav_id = rec_id; float rec_heading; int rec_dtype; int rmc_size = received_msg_raw.size(); std::vector<float> payload; if (rmc_size == 8) { rec_heading = 22.5 * (8 * received_msg_raw[3] + 4 * received_msg_raw[4] + 2 * received_msg_raw[5] + received_msg_raw[6]); rm_pub.pl_carrying = false; rm_pub.heading = rec_heading; if(received_msg_raw[2]==1){ rm_pub.msg_type = 1; } else{ rm_pub.msg_type = 0; } ROS_INFO("Recieved id: %d, hd: %f, vis: %d", rec_id, rec_heading, rm_pub.msg_type); } else { int payload_size = (rmc_size - 5) / 4; rec_dtype = 2 * received_msg_raw[2] + received_msg_raw[3]; if (payload_size > 2 || payload_size < 0) { ROS_ERROR("Ignoring msg, bad payload size %d", payload_size); continue; } if (rec_dtype > 3 || rec_dtype < 0) { ROS_ERROR("Ignoring msg, bad msg type %d", rec_dtype); continue; } bool valid_data = true; for (int pl = 0; pl < payload_size; pl++) { int tmp_pl = (8 * received_msg_raw[4 + 4 * pl] + 4 * received_msg_raw[5 + 4 * pl] + 2 * received_msg_raw[6 + 4 * pl] + received_msg_raw[7 + 4 * pl]); float real_value = transferValues(tmp_pl, payload_size, pl, rec_dtype); if (real_value < 0) valid_data = false; payload.push_back(real_value); } if (!valid_data) continue; rm_pub.payload = payload; rm_pub.pl_carrying = true; rm_pub.msg_type = rec_dtype; ROS_INFO("Msg from UAV id: %d, msg_type: %d, payload: %f", rec_id, rec_dtype, payload[0]); } point_seen[camera_index][i].back().decoded = true; /* point_seen[camera_index][i].back().frequency = frequencies[rec_id]; */ // publish decoded message pub_rec_msg.publish(rm_pub); received_msg.clear(); received_msg_raw.clear(); } } struct CamInfo { bool init = false; int cam_id = 0; double framerate = 80.0; ros::Time last_stamp; int samples = 0; }; struct PointSeen { bool decoded = false; int id = -1; /* double frequency = 0; */ int cnt_last_published = 0; std::vector<cv::Point2i> positions; cv::Point2i position; // position in the camera frame int count; // number of visible leds in current frame ros::Time sample_time; // time of current frame int start_frame_index = -1; // marker of SOF }; std::vector<std::vector<std::vector<PointSeen>>> point_seen; // ith camera, jth cluster, kth time of visible point std::vector<CamInfo> cam_info; }; } // namespace RX int main(int argc, char** argv) { ros::init(argc, argv, "UVDARrx"); ros::NodeHandle nh("~"); RX::RX_processor rxko(nh); ROS_INFO("[RX_processor] Node initialized"); ros::spin(); return 0; }
36.326279
159
0.590669
[ "vector" ]
9799f1b10b69b50964688e045f31759fd404e0b9
1,834
cpp
C++
lib/commonAPI/audiocapture/ext/platform/wp8/src/Audiocapture_impl.cpp
mensfeld/rhodes
2962610a314ed563a0b7c83fcae6136913a1b033
[ "MIT" ]
173
2015-01-02T11:14:08.000Z
2022-03-05T09:54:54.000Z
lib/commonAPI/audiocapture/ext/platform/wp8/src/Audiocapture_impl.cpp
mensfeld/rhodes
2962610a314ed563a0b7c83fcae6136913a1b033
[ "MIT" ]
263
2015-01-05T04:35:22.000Z
2021-09-07T06:00:02.000Z
lib/commonAPI/audiocapture/ext/platform/wp8/src/Audiocapture_impl.cpp
watusi/rhodes
07161cca58ff6a960bbd1b79b36447b819bfa0eb
[ "MIT" ]
77
2015-01-12T20:57:18.000Z
2022-02-17T15:15:14.000Z
#include "../../../shared/generated/cpp/AudiocaptureBase.h" namespace rho { using namespace apiGenerator; class CAudiocaptureImpl: public CAudiocaptureBase { public: CAudiocaptureImpl(const rho::String& strID): CAudiocaptureBase() { } virtual void enable( const rho::Hashtable<rho::String, rho::String>& propertyMap, CMethodResult& oResult){} virtual void start(CMethodResult& oResult){} virtual void stop(CMethodResult& oResult){} virtual void disable(CMethodResult& oResult){} virtual void take( const rho::Hashtable<rho::String, rho::String>& propertyMap, CMethodResult& oResult){} }; class CAudiocaptureSingleton: public CAudiocaptureSingletonBase { ~CAudiocaptureSingleton(){} virtual rho::String getInitialDefaultID(); virtual void enumerate(CMethodResult& oResult); }; class CAudiocaptureFactory: public CAudiocaptureFactoryBase { ~CAudiocaptureFactory(){} virtual IAudiocaptureSingleton* createModuleSingleton(); virtual IAudiocapture* createModuleByID(const rho::String& strID); }; extern "C" void Init_Audiocapture_extension() { CAudiocaptureFactory::setInstance( new CAudiocaptureFactory() ); Init_Audiocapture_API(); } IAudiocapture* CAudiocaptureFactory::createModuleByID(const rho::String& strID) { return new CAudiocaptureImpl(strID); } IAudiocaptureSingleton* CAudiocaptureFactory::createModuleSingleton() { return new CAudiocaptureSingleton(); } void CAudiocaptureSingleton::enumerate(CMethodResult& oResult) { rho::Vector<rho::String> arIDs; arIDs.addElement("SC1"); arIDs.addElement("SC2"); oResult.set(arIDs); } rho::String CAudiocaptureSingleton::getInitialDefaultID() { CMethodResult oRes; enumerate(oRes); rho::Vector<rho::String>& arIDs = oRes.getStringArray(); return arIDs[0]; } }
25.830986
111
0.742094
[ "vector" ]
97a18bb73952e7df346c2f1b845cd45a69346810
2,213
cpp
C++
aws-cpp-sdk-codepipeline/source/model/ActionTypeUrls.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-05T18:20:03.000Z
2022-01-05T18:20:03.000Z
aws-cpp-sdk-codepipeline/source/model/ActionTypeUrls.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-codepipeline/source/model/ActionTypeUrls.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-12-30T04:25:33.000Z
2021-12-30T04:25:33.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/codepipeline/model/ActionTypeUrls.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace CodePipeline { namespace Model { ActionTypeUrls::ActionTypeUrls() : m_configurationUrlHasBeenSet(false), m_entityUrlTemplateHasBeenSet(false), m_executionUrlTemplateHasBeenSet(false), m_revisionUrlTemplateHasBeenSet(false) { } ActionTypeUrls::ActionTypeUrls(JsonView jsonValue) : m_configurationUrlHasBeenSet(false), m_entityUrlTemplateHasBeenSet(false), m_executionUrlTemplateHasBeenSet(false), m_revisionUrlTemplateHasBeenSet(false) { *this = jsonValue; } ActionTypeUrls& ActionTypeUrls::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("configurationUrl")) { m_configurationUrl = jsonValue.GetString("configurationUrl"); m_configurationUrlHasBeenSet = true; } if(jsonValue.ValueExists("entityUrlTemplate")) { m_entityUrlTemplate = jsonValue.GetString("entityUrlTemplate"); m_entityUrlTemplateHasBeenSet = true; } if(jsonValue.ValueExists("executionUrlTemplate")) { m_executionUrlTemplate = jsonValue.GetString("executionUrlTemplate"); m_executionUrlTemplateHasBeenSet = true; } if(jsonValue.ValueExists("revisionUrlTemplate")) { m_revisionUrlTemplate = jsonValue.GetString("revisionUrlTemplate"); m_revisionUrlTemplateHasBeenSet = true; } return *this; } JsonValue ActionTypeUrls::Jsonize() const { JsonValue payload; if(m_configurationUrlHasBeenSet) { payload.WithString("configurationUrl", m_configurationUrl); } if(m_entityUrlTemplateHasBeenSet) { payload.WithString("entityUrlTemplate", m_entityUrlTemplate); } if(m_executionUrlTemplateHasBeenSet) { payload.WithString("executionUrlTemplate", m_executionUrlTemplate); } if(m_revisionUrlTemplateHasBeenSet) { payload.WithString("revisionUrlTemplate", m_revisionUrlTemplate); } return payload; } } // namespace Model } // namespace CodePipeline } // namespace Aws
21.07619
73
0.758699
[ "model" ]
97aaf56fed44a80630f02781489812c6bb7e9ad8
939
cpp
C++
39.cpp
pengzhezhe/LeetCode
305ec0c5b4cb5ea7cd244b3308132dee778138bc
[ "Apache-2.0" ]
null
null
null
39.cpp
pengzhezhe/LeetCode
305ec0c5b4cb5ea7cd244b3308132dee778138bc
[ "Apache-2.0" ]
null
null
null
39.cpp
pengzhezhe/LeetCode
305ec0c5b4cb5ea7cd244b3308132dee778138bc
[ "Apache-2.0" ]
null
null
null
// // Created by pzz on 2021/11/29. // #include <iostream> #include <algorithm> #include <vector> using namespace std; class Solution { private: vector<vector<int>> result; vector<int> collection; int sum = 0; void backtracing(const vector<int> &candidates, int target, int start) { if (sum == target) { result.push_back(collection); return; } for (int i = start; i < candidates.size() && sum < target; i++) { sum += candidates[i]; collection.push_back(candidates[i]); backtracing(candidates, target, i); collection.pop_back(); sum -= candidates[i]; } } public: vector<vector<int>> combinationSum(vector<int> &candidates, int target) { sort(candidates.begin(), candidates.end()); backtracing(candidates, target, 0); return result; } }; int main() { return 0; }
22.357143
77
0.57295
[ "vector" ]
97abc65fc7a52c9d20652cd2ee54077a3cd3e789
16,269
cpp
C++
services/sensor/src/sensor_data_processer.cpp
openharmony-gitee-mirror/sensors_sensor
fb94366c2ec86afec09080fcefea026a47f13eaa
[ "Apache-2.0" ]
null
null
null
services/sensor/src/sensor_data_processer.cpp
openharmony-gitee-mirror/sensors_sensor
fb94366c2ec86afec09080fcefea026a47f13eaa
[ "Apache-2.0" ]
null
null
null
services/sensor/src/sensor_data_processer.cpp
openharmony-gitee-mirror/sensors_sensor
fb94366c2ec86afec09080fcefea026a47f13eaa
[ "Apache-2.0" ]
1
2021-09-13T11:20:30.000Z
2021-09-13T11:20:30.000Z
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "sensor_data_processer.h" #include <sys/socket.h> #include <thread> #include "permission_util.h" #include "securec.h" #include "sensor_basic_data_channel.h" #include "sensor_catalog.h" #include "sensors_errors.h" #include "system_ability_definition.h" namespace OHOS { namespace Sensors { using namespace OHOS::HiviewDFX; namespace { constexpr HiLogLabel LABEL = { LOG_CORE, SensorsLogDomain::SENSOR_UTILS, "SensorDataProcesser" }; enum { FIRST_INDEX = 1, SECOND_INDEX = 2, THIRD_INDEX = 3, }; constexpr uint32_t SENSOR_INDEX_SHIFT = 8; constexpr uint32_t SENSOR_TYPE_SHIFT = 16; constexpr uint32_t SENSOR_CATAGORY_SHIFT = 24; constexpr uint32_t FLUSH_COMPLETE_ID = ((uint32_t)OTHER << SENSOR_CATAGORY_SHIFT) | ((uint32_t)SENSOR_TYPE_FLUSH << SENSOR_TYPE_SHIFT) | ((uint32_t)FIRST_INDEX << SENSOR_INDEX_SHIFT); } // namespace SensorDataProcesser::SensorDataProcesser(const std::unordered_map<uint32_t, Sensor> &sensorMap) { sensorMap_.insert(sensorMap.begin(), sensorMap.end()); HiLog::Debug(LABEL, "%{public}s sensorMap_.size : %{public}d", __func__, int32_t { sensorMap_.size() }); } SensorDataProcesser::~SensorDataProcesser() { dataCountMap_.clear(); sensorMap_.clear(); } void SensorDataProcesser::SendNoneFifoCacheData(std::unordered_map<uint32_t, struct SensorEvent> &cacheBuf, sptr<SensorBasicDataChannel> &channel, struct SensorEvent &event, uint64_t periodCount) { std::vector<struct SensorEvent> sendEvents; std::lock_guard<std::mutex> dataCountLock(dataCountMutex_); sendEvents.push_back(event); uint32_t sensorId = event.sensorTypeId; if (sensorId == FLUSH_COMPLETE_ID) { sensorId = event.sensorTypeId; } auto dataCountIt = dataCountMap_.find(sensorId); if (dataCountIt == dataCountMap_.end()) { std::vector<sptr<FifoCacheData>> channelFifoList; sptr<FifoCacheData> fifoCacheData = new (std::nothrow) FifoCacheData(); if (fifoCacheData == nullptr) { HiLog::Error(LABEL, "%{public}s fifoCacheData cannot be null", __func__); return; } fifoCacheData->SetChannel(channel); channelFifoList.push_back(fifoCacheData); dataCountMap_.insert(std::make_pair(sensorId, channelFifoList)); SendRawData(cacheBuf, channel, sendEvents); return; } bool channelExist = false; for (const auto &fifoCacheData : dataCountIt->second) { if (fifoCacheData->GetChannel() != channel) { continue; } channelExist = true; uint64_t curCount = fifoCacheData->GetPeriodCount(); curCount++; fifoCacheData->SetPeriodCount(curCount); if (periodCount != 0 && fifoCacheData->GetPeriodCount() % periodCount != 0UL) { continue; } SendRawData(cacheBuf, channel, sendEvents); fifoCacheData->SetPeriodCount(0); return; } if (!channelExist) { sptr<FifoCacheData> fifoCacheData = new (std::nothrow) FifoCacheData(); if (fifoCacheData == nullptr) { HiLog::Error(LABEL, "%{public}s failed, fifoCacheData cannot be null", __func__); return; } fifoCacheData->SetChannel(channel); dataCountIt->second.push_back(fifoCacheData); SendRawData(cacheBuf, channel, sendEvents); } } void SensorDataProcesser::SendFifoCacheData(std::unordered_map<uint32_t, struct SensorEvent> &cacheBuf, sptr<SensorBasicDataChannel> &channel, struct SensorEvent &event, uint64_t periodCount, uint64_t fifoCount) { uint32_t sensorId = event.sensorTypeId; if (sensorId == FLUSH_COMPLETE_ID) { sensorId = event.sensorTypeId; } std::lock_guard<std::mutex> dataCountLock(dataCountMutex_); auto dataCountIt = dataCountMap_.find(sensorId); // there is no channelFifoList if (dataCountIt == dataCountMap_.end()) { std::vector<sptr<FifoCacheData>> channelFifoList; sptr<FifoCacheData> fifoCacheData = new (std::nothrow) FifoCacheData(); if (fifoCacheData == nullptr) { HiLog::Error(LABEL, "%{public}s fifoCacheData cannot be null", __func__); return; } fifoCacheData->SetChannel(channel); channelFifoList.push_back(fifoCacheData); dataCountMap_.insert(std::make_pair(sensorId, channelFifoList)); return; } // find channel in channelFifoList bool channelExist = false; for (auto &fifoData : dataCountIt->second) { if (fifoData->GetChannel() != channel) { continue; } channelExist = true; uint64_t curCount = fifoData->GetPeriodCount(); curCount++; fifoData->SetPeriodCount(curCount); if (fifoData->GetPeriodCount() % periodCount != 0UL) { continue; } fifoData->SetPeriodCount(0); std::vector<struct SensorEvent> fifoDataList = fifoData->GetFifoCacheData(); fifoDataList.push_back(event); fifoData->SetFifoCacheData(fifoDataList); if ((fifoData->GetFifoCacheData()).size() != fifoCount) { continue; } SendRawData(cacheBuf, channel, fifoData->GetFifoCacheData()); fifoData->InitFifoCache(); return; } // cannot find channel in channelFifoList if (!channelExist) { sptr<FifoCacheData> fifoCacheData = new (std::nothrow) FifoCacheData(); if (fifoCacheData == nullptr) { HiLog::Error(LABEL, "%{public}s failed, fifoCacheData cannot be null", __func__); return; } fifoCacheData->SetChannel(channel); dataCountIt->second.push_back(fifoCacheData); } } void SensorDataProcesser::ReportData(sptr<SensorBasicDataChannel> &channel, struct SensorEvent &event) { if (channel == nullptr) { HiLog::Error(LABEL, "%{public}s channel cannot be null", __func__); return; } uint32_t sensorId = event.sensorTypeId; if (sensorId == FLUSH_COMPLETE_ID) { sensorId = event.sensorTypeId; } auto &cacheBuf = const_cast<std::unordered_map<uint32_t, struct SensorEvent> &>(channel->GetDataCacheBuf()); if (ReportNotContinuousData(cacheBuf, channel, event)) { return; } uint64_t periodCount = clientInfo_.ComputeBestPeriodCount(sensorId, channel); if (periodCount == 0UL) { return; } auto fifoCount = clientInfo_.ComputeBestFifoCount(sensorId, channel); if (fifoCount <= 0) { SendNoneFifoCacheData(cacheBuf, channel, event, periodCount); return; } SendFifoCacheData(cacheBuf, channel, event, periodCount, fifoCount); } bool SensorDataProcesser::ReportNotContinuousData(std::unordered_map<uint32_t, struct SensorEvent> &cacheBuf, sptr<SensorBasicDataChannel> &channel, struct SensorEvent &event) { uint32_t sensorId = event.sensorTypeId; if (sensorId == FLUSH_COMPLETE_ID) { sensorId = event.sensorTypeId; } std::lock_guard<std::mutex> sensorLock(sensorMutex_); auto sensor = sensorMap_.find(sensorId); sensor->second.SetFlags(event.mode); if (sensor == sensorMap_.end()) { HiLog::Error(LABEL, "%{public}s data's sensorId is not supported", __func__); return false; } if (((SENSOR_ON_CHANGE & sensor->second.GetFlags()) == SENSOR_ON_CHANGE) || ((SENSOR_ONE_SHOT & sensor->second.GetFlags()) == SENSOR_ONE_SHOT)) { std::vector<struct SensorEvent> sendEvents; sendEvents.push_back(event); SendRawData(cacheBuf, channel, sendEvents); return true; } return false; } bool SensorDataProcesser::CheckSendDataPermission(sptr<SensorBasicDataChannel> channel, uint32_t sensorId) { return true; } void SensorDataProcesser::SendRawData(std::unordered_map<uint32_t, struct SensorEvent> &cacheBuf, sptr<SensorBasicDataChannel> channel, std::vector<struct SensorEvent> event) { if (channel == nullptr || event.empty()) { HiLog::Error(LABEL, "%{public}s channel cannot be null or event cannot be empty", __func__); return; } if (!CheckSendDataPermission(channel, event[0].sensorTypeId)) { HiLog::Error(LABEL, "%{public}s permission denied", __func__); return; } size_t eventSize = event.size(); std::vector<struct TransferSensorEvents> transferEvents; for (int32_t i = 0; i < (int32_t)eventSize; i++) { struct TransferSensorEvents transferEvent = { .sensorTypeId = event[i].sensorTypeId, .version = event[i].version, .timestamp = event[i].timestamp, .option = event[i].option, .mode = event[i].mode, .dataLen = event[i].dataLen }; if (memcpy_s(transferEvent.data, SENSOR_MAX_LENGTH, event[i].data, event[i].dataLen) != EOK) { HiLog::Error(LABEL, "%{public}s copy data failed", __func__); return; } transferEvents.push_back(transferEvent); } auto ret = channel->SendData(transferEvents.data(), eventSize * sizeof(struct TransferSensorEvents)); if (ret != ERR_OK) { HiLog::Error(LABEL, "%{public}s send data failed, ret : %{public}d", __func__, ret); uint32_t sensorId = event[eventSize - 1].sensorTypeId; if (sensorId == FLUSH_COMPLETE_ID) { sensorId = event[eventSize - 1].sensorTypeId; } cacheBuf[sensorId] = event[eventSize - 1]; } } int32_t SensorDataProcesser::CacheSensorEvent(const struct SensorEvent &event, sptr<SensorBasicDataChannel> &channel) { if (channel == nullptr) { HiLog::Error(LABEL, "%{public}s channel cannot be null", __func__); return INVALID_POINTER; } uint32_t ret = ERR_OK; auto &cacheBuf = const_cast<std::unordered_map<uint32_t, struct SensorEvent> &>(channel->GetDataCacheBuf()); uint32_t sensorId = event.sensorTypeId; if (sensorId == FLUSH_COMPLETE_ID) { sensorId = event.sensorTypeId; } auto cacheEvent = cacheBuf.find(sensorId); if (cacheEvent != cacheBuf.end()) { // Try to send the last failed value, if it still fails, replace the previous cache directly ret = channel->SendData(&cacheEvent->second, sizeof(struct SensorEvent)); if (ret != ERR_OK) { HiLog::Error(LABEL, "%{public}s ret : %{public}d", __func__, ret); } ret = channel->SendData(&event, sizeof(struct SensorEvent)); if (ret != ERR_OK) { HiLog::Error(LABEL, "%{public}s ret : %{public}d", __func__, ret); cacheBuf[sensorId] = event; } else { cacheBuf.erase(cacheEvent); } } else { ret = channel->SendData(&event, sizeof(struct SensorEvent)); if (ret != ERR_OK) { HiLog::Error(LABEL, "%{public}s ret : %{public}d", __func__, ret); cacheBuf[sensorId] = event; } } return ret; } void SensorDataProcesser::EventFilter(struct CircularEventBuf &eventsBuf) { HiLog::Debug(LABEL, "%{public}s begin", __func__); uint32_t realSensorId = 0; uint32_t sensorId = eventsBuf.circularBuf[eventsBuf.readPosition].sensorTypeId; std::vector<sptr<SensorBasicDataChannel>> channelList; if (sensorId == FLUSH_COMPLETE_ID) { realSensorId = eventsBuf.circularBuf[eventsBuf.readPosition].sensorTypeId; channelList = clientInfo_.GetSensorChannel(realSensorId); } else { channelList = clientInfo_.GetSensorChannel(sensorId); } auto flushInfo = flushInfo_.GetFlushInfo(); std::vector<struct FlushInfo> flushVec; if (sensorId == FLUSH_COMPLETE_ID) { HiLog::Debug(LABEL, "%{public}s sensorId : %{public}u", __func__, sensorId); auto it = flushInfo.find(realSensorId); if (it != flushInfo.end()) { flushVec = it->second; for (auto &channel : flushVec) { if (flushInfo_.IsFlushChannelValid(channelList, channel.flushChannel)) { SendEvents(channel.flushChannel, eventsBuf.circularBuf[eventsBuf.readPosition]); flushInfo_.ClearFlushInfoItem(realSensorId); break; } else { // The channel that store in the flushVec has invalid, so erase this channel directly HiLog::Debug(LABEL, "%{public}s clear flush info", __func__); flushInfo_.ClearFlushInfoItem(realSensorId); } } } } else { if (channelList.empty() || channelList.size() == 0) { HiLog::Error(LABEL, "%{public}s channelList is empty", __func__); } for (auto &channel : channelList) { int32_t index = flushInfo_.GetFlushChannelIndex(flushVec, channel); if (index >= 0) { if (flushVec[index].flushFromEnable) { HiLog::Info(LABEL, "%{public}s flushFromEnable", __func__); continue; } } /* if has some suspend flush, but this flush come from the flush function rather than enable, so we need to calling GetSensorStatus to decided whether send this event. */ if (channel->GetSensorStatus()) { SendEvents(channel, eventsBuf.circularBuf[eventsBuf.readPosition]); } } } } int32_t SensorDataProcesser::ProcessEvents(sptr<ReportDataCallback> dataCallback) { if (dataCallback == nullptr) { HiLog::Error(LABEL, "%{public}s dataCallback cannot be null", __func__); return INVALID_POINTER; } std::unique_lock<std::mutex> lk(SensorServiceImpl::dataMutex_); SensorServiceImpl::dataCondition_.wait(lk); auto &eventsBuf = dataCallback->GetEventData(); if (eventsBuf.eventNum <= 0) { HiLog::Error(LABEL, "%{public}s data cannot be empty", __func__); return NO_EVENT; } int32_t eventNum = eventsBuf.eventNum; for (int32_t i = 0; i < eventNum; i++) { EventFilter(eventsBuf); delete eventsBuf.circularBuf[eventsBuf.readPosition].data; eventsBuf.circularBuf[eventsBuf.readPosition].data = nullptr; eventsBuf.readPosition++; if (eventsBuf.readPosition == CIRCULAR_BUF_LEN) { eventsBuf.readPosition = 0; } eventsBuf.eventNum--; } return SUCCESS; } int32_t SensorDataProcesser::SendEvents(sptr<SensorBasicDataChannel> &channel, struct SensorEvent &event) { if (channel == nullptr) { HiLog::Error(LABEL, "%{public}s channel cannot be null", __func__); return INVALID_POINTER; } clientInfo_.UpdateDataQueue(event.sensorTypeId, event); auto &cacheBuf = channel->GetDataCacheBuf(); if (cacheBuf.empty()) { ReportData(channel, event); } else { CacheSensorEvent(event, channel); } clientInfo_.StoreEvent(event); return SUCCESS; } int32_t SensorDataProcesser::DataThread(sptr<SensorDataProcesser> dataProcesser, sptr<ReportDataCallback> dataCallback) { HiLog::Debug(LABEL, "%{public}s begin", __func__); do { if (dataProcesser->ProcessEvents(dataCallback) == INVALID_POINTER) { HiLog::Error(LABEL, "%{public}s callback cannot be null", __func__); return INVALID_POINTER; } } while (1); } } // namespace Sensors } // namespace OHOS
39.392252
119
0.640236
[ "vector" ]
97b2ae39b334a99d14d5119a2fab0c8e6195f494
2,127
hpp
C++
Libraries/Editor/EditorUtility.hpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
3
2022-02-11T10:34:33.000Z
2022-02-24T17:44:17.000Z
Libraries/Editor/EditorUtility.hpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
null
null
null
Libraries/Editor/EditorUtility.hpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
null
null
null
// MIT Licensed (see LICENSE.md). #pragma once namespace Zero { class Cog; // Get the text drawing position for a given cog Vec3 GetObjectTextPosition(Cog* cog); DeclareEnum2(IncludeMode, OnlyRoot, Children); // Get an Aabb for a cog and its children Aabb GetAabb(Cog* cog, IncludeMode::Type includeMode = IncludeMode::Children, bool world = true); Aabb GetAabb(HandleParam metaObject, IncludeMode::Type includeMode = IncludeMode::Children, bool world = true); // Get an Aabb for selection Aabb GetAabb(MetaSelection* selection, IncludeMode::Type includeMode = IncludeMode::Children); // Expand the aabb by this object size void ExpandAabb(Cog* cog, Aabb& aabb, IncludeMode::Type includeMode = IncludeMode::Children, bool world = true, bool toParent = false, bool expandTransform = false); void ExpandAabb(HandleParam metaObject, Aabb& aabb, IncludeMode::Type includeMode = IncludeMode::Children, bool world = true, bool toParent = false, bool expandTransform = false); // Expand the aabb by this object's childrens' sizes only, but not the object's // size itself. void ExpandAabbChildrenOnly(HandleParam instance, Aabb& aabb, bool world = true, bool expandTransform = false); // Get distance needed to full view an Aabb float GetViewDistance(Aabb& aabb); /// Takes in a code definition, validates, then displays it void DisplayCodeDefinition(CodeDefinition& definition); template <typename metaRangeType> Aabb GetAabbFromObjects(metaRangeType objects, IncludeMode::Type includeMode = IncludeMode::Children) { Aabb aabb = Aabb(Vec3::cZero, Vec3::cZero); if (objects.Empty()) return aabb; // If this didn't happen before going through the range below, then the min // point of the aabb will always be (0,0,0), which is incorrect. aabb = GetAabb(objects.Front(), includeMode); forRange (Handle instance, objects) { Aabb currAabb = GetAabb(instance, includeMode); aabb.Combine(currAabb); } return aabb; } } // namespace Zero
32.723077
111
0.697696
[ "object" ]
b6333a48d90872b2d44c6c166b9ea2428ee333a0
1,263
cpp
C++
test/unit/math/prim/fun/positive_transform_test.cpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
null
null
null
test/unit/math/prim/fun/positive_transform_test.cpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
null
null
null
test/unit/math/prim/fun/positive_transform_test.cpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
null
null
null
#include <stan/math/prim.hpp> #include <test/unit/util.hpp> #include <gtest/gtest.h> TEST(prob_transform, positive) { EXPECT_FLOAT_EQ(exp(-1.0), stan::math::positive_constrain(-1.0)); } TEST(prob_transform, positive_j) { double lp = 15.0; EXPECT_FLOAT_EQ(exp(-1.0), stan::math::positive_constrain(-1.0, lp)); EXPECT_FLOAT_EQ(15.0 - 1.0, lp); } TEST(prob_transform, positive_f) { EXPECT_FLOAT_EQ(log(0.5), stan::math::positive_free(0.5)); } TEST(prob_transform, positive_f_exception) { EXPECT_THROW(stan::math::positive_free(-1.0), std::domain_error); } TEST(prob_transform, positive_rt) { double x = -1.0; double xc = stan::math::positive_constrain(x); double xcf = stan::math::positive_free(xc); EXPECT_FLOAT_EQ(x, xcf); double xcfc = stan::math::positive_constrain(xcf); EXPECT_FLOAT_EQ(xc, xcfc); } TEST(prob_transform, positive_vectorized) { double lp = 0; Eigen::VectorXd x = Eigen::VectorXd::Random(4); std::vector<Eigen::VectorXd> x_vec = {x, x, x}; std::vector<Eigen::VectorXd> y_vec = stan::math::positive_constrain<false>(x_vec, lp); std::vector<Eigen::VectorXd> x_free_vec = stan::math::positive_free(y_vec); for (int i = 0; i < x_vec.size(); ++i) { EXPECT_MATRIX_FLOAT_EQ(x_vec[i], x_free_vec[i]); } }
33.236842
77
0.697546
[ "vector" ]
b634cbbc2e4a1df34e223aa5f077b602602b01b5
19,998
hpp
C++
metric/modules/utils/crossfilter/include/detail/crossfilter.hpp
Stepka/telegram_clustering_contest
52a012af2ce821410caa98cba840364710eb4256
[ "Apache-2.0" ]
2
2019-12-03T17:08:04.000Z
2021-08-25T05:06:29.000Z
metric/modules/utils/crossfilter/include/detail/crossfilter.hpp
Stepka/telegram_clustering_contest
52a012af2ce821410caa98cba840364710eb4256
[ "Apache-2.0" ]
1
2021-09-02T02:25:51.000Z
2021-09-02T02:25:51.000Z
metric/modules/utils/crossfilter/include/detail/crossfilter.hpp
Stepka/telegram_clustering_contest
52a012af2ce821410caa98cba840364710eb4256
[ "Apache-2.0" ]
null
null
null
/*This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Copyright (c) 2018 Dmitry Vinokurov */ #ifndef _METRIC_CROSSFILTER_DETAILS_CROSSFILTER_HPP #define _METRIC_CROSSFILTER_DETAILS_CROSSFILTER_HPP #include <functional> #include <vector> #include <type_traits> #include <sstream> #include <cstddef> #include "../detail/crossfilter_impl.hpp" #include "../detail/dimension_impl.hpp" #include "../detail/feature_impl.hpp" #include "../detail/utils.hpp" #include "../detail/thread_policy.hpp" namespace cross { template <typename, typename, typename, typename> struct dimension; template <typename T, typename Hash = trivial_hash<T>> struct filter : private impl::filter_impl<T, Hash> { public: using this_type_t = filter<T, Hash>; using impl_type_t = impl::filter_impl<T, Hash>; using record_type_t = typename impl::filter_impl<T, Hash>::record_type_t; using value_type_t = typename impl::filter_impl<T, Hash>::value_type_t; template <typename U> using dimension_t = cross::dimension<U, T, cross::non_iterable, Hash>; template <typename U> using iterable_dimension_t = cross::dimension<U, T, cross::iterable, Hash>; using data_iterator = typename impl::filter_impl<T, Hash>::data_iterator; using base_type_t = impl::filter_impl<T, Hash>; using connection_type_t = typename impl::filter_impl<T, Hash>::connection_type_t; template <typename F> using signal_type_t = typename impl::filter_impl<T, Hash>::template signal_type_t<F>; template <typename, typename, typename, bool> friend struct impl::feature_impl; template <typename, typename, typename, typename> friend struct impl::dimension_impl; using reader_lock_t = cross::thread_policy::read_lock_t; using writer_lock_t = cross::thread_policy::write_lock_t; using impl::filter_impl<T, Hash>::mutex; signal_type_t<void(cross::event)> on_change_signal; private: bool empty_unlocked() const { return impl_type_t::data.empty(); } void trigger_on_change(cross::event event) override { on_change_signal(event); } public: struct iterator { using iterator_category = std::input_iterator_tag; using value_type = T; using difference_type = std::ptrdiff_t; using pointer = value_type*; using reference = value_type&; private: std::size_t index; std::vector<T>& data; iterator(std::size_t i, std::vector<T>& d) : index(i) , data(d) { } friend struct filter; public: iterator(const iterator& i) : index(i.index) , data(i.data) { } iterator& operator=(iterator&& i) { if (&i == this) return *this; index = i.index; data = i.data; return *this; } bool operator==(const iterator& i) const noexcept { return index == i.index; } bool operator!=(const iterator& i) const noexcept { return !(*this == i); } bool operator<(const iterator& i) const noexcept { return index < i.index; } bool operator>(const iterator& i) const noexcept { return index > i.index; } iterator& operator++() { index++; return *this; } iterator operator++(int) { auto result(*this); index++; return result; } iterator& operator--() { index--; return *this; } iterator operator--(int) { auto result(*this); index--; return result; } const T& operator*() const { return data[index]; } T const* operator->() { return &data[index]; } }; struct reverse_iterator { using iterator_category = std::input_iterator_tag; using value_type = T; using difference_type = std::ptrdiff_t; using pointer = value_type*; using reference = value_type&; private: iterator current; friend struct filter; public: reverse_iterator(const iterator& x) : current(x) { } reverse_iterator(const reverse_iterator& i) : current(i.current) { } reverse_iterator& operator=(reverse_iterator&& i) { if (&i == this) return *this; current = std::move(i.current); return *this; } bool operator==(const reverse_iterator& i) const noexcept { return current == i.current; } bool operator!=(const reverse_iterator& i) const noexcept { return !(*this == i); } bool operator<(const reverse_iterator& i) const noexcept { return current < i.current; } bool operator>(const reverse_iterator& i) const noexcept { return current > i.current; } reverse_iterator& operator++() { current--; return *this; } reverse_iterator operator++(int) { auto result(*this); current--; return result; } reverse_iterator& operator--() { current++; return *this; } reverse_iterator operator--(int) { auto result(*this); current++; return result; } const T& operator*() const { iterator tmp = current; return *--tmp; } T const* operator->() { return &(operator*()); } }; static constexpr bool get_is_iterable() { return false; } /** Create crossfilter with empty data */ filter(Hash h = Hash()) : impl_type_t(h) { } /** Create crossfilter and add data from 'data' \param[in] data Container of elements with type T, must support std::begin/end concept */ template <typename C> explicit filter(const C& data, Hash h = Hash()) : impl_type_t(std::begin(data), std::end(data), h) { } /** Constructs the container with the contents of the initializer list \param[in] init initializer list */ filter(std::initializer_list<T> init, Hash h = Hash()) : impl_type_t(init.begin(), init.end(), h) { } #ifdef CROSS_FILTER_USE_THREAD_POOL /** set size of internal thread pool \param[in] thread_num - amount of threads in thread pool */ void set_thread_pool_size(uint32_t thread_num) { impl_type_t::set_thread_pool_size(thread_num); } #endif /** Add all data from container to crossfilter \param[in] new_data Container of elements with type T, must support std::begin/end concept */ template <typename C> typename std::enable_if<!std::is_same<C, T>::value, filter&>::type add( const C& new_data, bool allow_duplicates = true); /** Add one element of type T to crossfilter \param[in] new_data - element to be added to crossfilter */ filter& add(const T& new_data, bool allow_duplicates = true); /** Returns the number of records in the crossfilter, independent of any filters */ std::size_t size() const; /** Returns all of the raw records in the crossfilter, independent of any filters */ std::vector<T> all() const { reader_lock_t lk(mutex); (void)lk; // avoid AppleClang warning about unused variable; return impl_type_t::all(); } /** Returns all of the raw records in the crossfilter, with filters applied. Can optionally ignore filters that are defined on dimension list [dimensions] */ template <typename... Ts> std::vector<T> all_filtered(Ts&... dimensions) const { reader_lock_t lk(mutex); (void)lk; // avoid AppleClang warning about unused variable; return impl_type_t::all_filtered(dimensions...); } /** Returns all of the raw records in the crossfilter, with filters of selected dfimensions applied. */ template <typename... Ts> std::vector<T> all_filtered_by(Ts&... dimensions) const { reader_lock_t lk(mutex); (void)lk; // avoid AppleClang warning about unused variable; return impl_type_t::all_filtered_by(dimensions...); } /** auxilary method for n-api. analog of all_filtered */ std::vector<T> all_filtered_except_mask(const std::vector<uint8_t>& mask) const { reader_lock_t lk(mutex); (void)lk; // avoid AppleClang warning about unused variable; return impl_type_t::all_filtered_except_mask(mask); } /** Check if the data record at index i is excluded by the current filter set. Can optionally ignore filters that are defined on dimension list [dimensions] */ template <typename... Ts> bool is_element_filtered(std::size_t index, Ts&... dimensions) const { reader_lock_t lk(mutex); (void)lk; // avoid AppleClang warning about unused variable; return impl_type_t::is_element_filtered(index, dimensions...); } bool is_element_filtered_except_mask(std::size_t index, const std::vector<uint8_t>& mask) const { reader_lock_t lk(mutex); (void)lk; // avoid AppleClang warning about unused variable; return impl_type_t::is_element_filtered_except_mask(index, mask); } /** Constructs a new dimension using the specified value accessor function. */ template <typename F> auto dimension(F getter) -> cross::dimension<decltype(getter(std::declval<record_type_t>())), T, cross::non_iterable, Hash> { // writer_lock_t lk(mutex); return impl_type_t::dimension(getter); } /** Constructs a new dimension using the specified value accessor function. Getter function must return container of elements. */ template <typename F> auto iterable_dimension(F getter) -> cross::dimension<decltype(getter(std::declval<record_type_t>())), T, cross::iterable, Hash> { writer_lock_t lk(mutex); (void)lk; // avoid AppleClang warning about unused variable; using value_type = decltype(getter(record_type_t())); return impl_type_t::template iterable_dimension<value_type>(getter); } /** removes all records matching the predicate (ignoring filters). */ void remove(std::function<bool(const T&, int)> predicate); /** Removes all records that match the current filters */ void remove(); /** A convenience function for grouping all records and reducing to a single value, with given reduce functions. */ template <typename AddFunc, typename RemoveFunc, typename InitialFunc> auto feature(AddFunc add_func_, RemoveFunc remove_func_, InitialFunc initial_func_) -> cross::feature<std::size_t, decltype(initial_func_()), this_type_t, true>; /** A convenience function for grouping all records and reducing to a single value, with predefined reduce functions to count records */ auto feature_count() -> cross::feature<std::size_t, std::size_t, this_type_t, true>; /** A convenience function for grouping all records and reducing to a single value, with predefined reduce functions to sum records */ template <typename G> auto feature_sum(G value) -> cross::feature<std::size_t, decltype(value(record_type_t())), this_type_t, true>; // /** // Equivalent ot groupAllReduceCount() // */ // cross::feature<std::size_t, std::size_t, this_type_t, true> feature(); /** Calls callback when certain changes happen on the Crossfilter. Crossfilter will pass the event type to callback as one of the following strings: * dataAdded * dataRemoved * filtered */ connection_type_t onChange(std::function<void(cross::event)> callback) { return on_change_signal.connect(callback); } void assign(std::size_t n, const T& val, bool allow_duplicate = true) { { writer_lock_t lk(mutex); (void)lk; // avoid AppleClang warning about unused variable; if (!this->empty_unlocked()) { impl_type_t::clear(); } if (!allow_duplicate) { impl_type_t::add(impl_type_t::size(), val, allow_duplicate); } else { for (std::size_t i = 0; i < n; i++) impl_type_t::add(impl_type_t::size(), val, allow_duplicate); } } on_change_signal(cross::dataAdded); } template <typename InputIterator> void assign(InputIterator first, InputIterator last, bool allow_duplicate = true) { { writer_lock_t lk(mutex); (void)lk; // avoid AppleClang warning about unused variable; if (!empty_unlocked()) { impl_type_t::clear(); } impl_type_t::add(0, first, last, allow_duplicate); } on_change_signal(cross::dataAdded); } void assign(std::initializer_list<T> l, bool allow_duplicate = true) { assign(l.begin(), l.end(), allow_duplicate); } const T& at(std::size_t n) const { reader_lock_t lk(mutex); (void)lk; // avoid AppleClang warning about unused variable; if (n > impl_type_t::size() - 1) { std::ostringstream os; os << "n (which is " << n << ") >= " << size() << " (which is " << size() << ")"; throw std::out_of_range(os.str()); } return impl_type_t::get_raw(n); } const T& back() const noexcept { reader_lock_t lk(mutex); (void)lk; // avoid AppleClang warning about unused variable; return impl_type_t::data.back(); } iterator begin() noexcept { return iterator(0, impl_type_t::data); } iterator end() noexcept { return iterator(impl_type_t::size(), impl_type_t::data); } iterator cbegin() const noexcept { return iterator(0, impl_type_t::data); } iterator cend() const noexcept { return iterator(size(), impl_type_t::data); } void clear() { writer_lock_t lk(mutex); (void)lk; // avoid AppleClang warning about unused variable; impl_type_t::clear(); } reverse_iterator crbegin() const noexcept { return reverse_iterator(end()); } reverse_iterator crend() const noexcept { return reverse_iterator(begin()); } reverse_iterator rbegin() noexcept { return reverse_iterator(end()); } reverse_iterator rend() noexcept { return reverse_iterator(begin()); }; bool empty() const noexcept { reader_lock_t lk(mutex); (void)lk; // avoid AppleClang warning about unused variable; return size() == 0; } iterator erase(iterator position) { std::size_t dist = 0; mutex.lock(); dist = std::distance(begin(), position); impl_type_t::remove(position.index, position.index + 1); auto p = begin(); std::advance(p, dist); mutex.unlock(); on_change_signal(cross::dataRemoved); return p; } iterator erase(iterator first, iterator last) { mutex.lock(); std::size_t dist = std::distance(begin(), last); impl_type_t::remove(first.index, last.index); auto p = begin(); std::advance(p, dist); mutex.unlock(); on_change_signal(cross::dataRemoved); return p; } const T& front() const noexcept { reader_lock_t lk(mutex); (void)lk; // avoid AppleClang warning about unused variable; return impl_type_t::data.front(); } iterator insert(iterator pos, const T& x, bool allow_duplicates = true) { { writer_lock_t lk(mutex); (void)lk; // avoid AppleClang warning about unused variable; impl_type_t::add(pos.index, x, allow_duplicates); } on_change_signal(cross::dataAdded); return iterator(pos.index, impl_type_t::data); } iterator insert(iterator pos, std::initializer_list<T> l, bool allow_duplicates = true) { { writer_lock_t lk(mutex); (void)lk; // avoid AppleClang warning about unused variable; impl_type_t::add(pos.index, l.begin(), l.end(), allow_duplicates); } on_change_signal(cross::dataAdded); return iterator(pos.index, impl_type_t::data); } iterator insert(iterator pos, std::size_t n, const T& x, bool allow_duplicates = true) { { writer_lock_t lk(mutex); (void)lk; // avoid AppleClang warning about unused variable; if (pos == end()) { std::vector<T> tmp(n, x); impl_type_t::add(tmp, allow_duplicates); } else { std::vector<T> tmp(impl_type_t::data.begin() + pos.index, impl_type_t::data.end()); tmp.insert(tmp.begin(), n, x); impl_type_t::add(pos.index, tmp.begin(), tmp.end(), allow_duplicates); } } on_change_signal(cross::dataAdded); return iterator(pos.index, impl_type_t::data); } template <typename InputIterator> iterator insert(iterator pos, InputIterator first, InputIterator last, bool allow_duplicates = true) { { writer_lock_t lk(mutex); (void)lk; // avoid AppleClang warning about unused variable; impl_type_t::add(pos.index, first, last, allow_duplicates); } return iterator(pos.index, impl_type_t::data); } filter& operator=(const filter& x) { assign(x.begin(), x.end()); } filter& operator=(filter&& x) noexcept { assign(x.begin(), x.end()); } filter& operator=(std::initializer_list<T> l) { assign(l.begin(), l.end()); } const T& operator[](std::size_t n) const noexcept { reader_lock_t lk(mutex); (void)lk; // avoid AppleClang warning about unused variable; return impl_type_t::get_raw(n); } void pop_back() noexcept { writer_lock_t lk(mutex); (void)lk; // avoid AppleClang warning about unused variable; std::size_t last = size() - 1; impl_type_t::remove([last](const auto&, int i) { return std::size_t(i) == last; }); } void push_back(const T& x, bool allow_duplicates = true) { writer_lock_t lk(mutex); (void)lk; // avoid AppleClang warning about unused variable; impl_type_t::add(impl_type_t::data.size(), x, allow_duplicates); } const T* data() const noexcept { reader_lock_t lk(mutex); (void)lk; // avoid AppleClang warning about unused variable; return impl_type_t::data.data(); } template <typename... _Args> iterator emplace(iterator position, _Args&&... args) { writer_lock_t lk(mutex); (void)lk; // avoid AppleClang warning about unused variable; auto index = impl_type_t::emplace(position.index, args...); return iterator(index, data); } template <typename... _Args> void emplace_back(_Args&&... args) { writer_lock_t lk(mutex); (void)lk; // avoid AppleClang warning about unused variable; impl_type_t::emplace(end().index, args...); } void reserve(std::size_t n) { writer_lock_t lk(mutex); (void)lk; // avoid AppleClang warning about unused variable; impl_type_t::data.reserve(n); } void shrink_to_fit() { writer_lock_t lk(mutex); (void)lk; // avoid AppleClang warning about unused variable; impl_type_t::data.shrink_to_fit(); } //void swap (filter & x) noexcept; std::size_t filters_size() const { return impl_type_t::filters.size(); } }; } #include "impl/crossfilter.ipp" #endif
33.894915
149
0.612861
[ "vector" ]
b63b653082a6502657588d33062141ddcf1c063b
10,781
cpp
C++
src/guide/customedit.cpp
rzvdaniel/GUI-
1501b54a038f7e3f66d683f125fa53d3ab73672c
[ "MIT" ]
2
2017-06-16T19:27:55.000Z
2020-04-05T02:18:07.000Z
src/guide/customedit.cpp
rzvdaniel/GUI-
1501b54a038f7e3f66d683f125fa53d3ab73672c
[ "MIT" ]
null
null
null
src/guide/customedit.cpp
rzvdaniel/GUI-
1501b54a038f7e3f66d683f125fa53d3ab73672c
[ "MIT" ]
2
2019-09-03T19:23:20.000Z
2020-08-29T21:46:17.000Z
#define N_IMPLEMENTS TCustomEdit //------------------------------------------------------------------- // customedit.cpp // (C) 2004 R.Predescu //------------------------------------------------------------------- #include "guide/customedit.h" #include "guide/debug.h" //------------------------------------------------------------------- /** Constructor. */ //------------------------------------------------------------------- TCustomEdit::TCustomEdit() { MaxLength = 0; CursorPos = 0; SelStart = 0; SelEnd = 0; Modified = false; AutoSize = false; ReadOnly = false; AutoSelect = false; HideSelection = true; CharCase = ecNormal; ColorCaret = clBlack; PasswordChar = '\0'; } //------------------------------------------------------------------- /** Destructor. */ //------------------------------------------------------------------- TCustomEdit::~TCustomEdit() { } //------------------------------------------------------------------- /** */ //------------------------------------------------------------------- void TCustomEdit::Create(TComponent* AOwner, const TRect& Rect) { TWinControl::Create(AOwner, Rect); } //------------------------------------------------------------------- /** */ //------------------------------------------------------------------- void TCustomEdit::Assign(TObject* Object) { TWinControl::Assign(Object); } //------------------------------------------------------------------- /** */ //------------------------------------------------------------------- void TCustomEdit::ApplySkin(TObject* Object) { TWinControl::ApplySkin(Object); TCustomEdit* CustomEdit = (TCustomEdit*)Object; if(CustomEdit != NULL) { SetCaretColor(CustomEdit->GetCaretColor()); SetTextMargins(CustomEdit->GetTextMargins()); } } //------------------------------------------------------------------- /** */ //------------------------------------------------------------------- void TCustomEdit::SetMaxLength(int Value) { MaxLength = Value; } //------------------------------------------------------------------- /** @brief Set the character that will be used for a password edit control. Password character will be used when displaying the text of the control. This will not affect the real control's text, but only the way it will looks for the user. */ //------------------------------------------------------------------- void TCustomEdit::SetPasswordChar(char Value) { if(PasswordChar != Value) PasswordChar = Value; } //------------------------------------------------------------------- /** Adjust the height of the control to the height of the font. It doesn't changes the control's width. */ //------------------------------------------------------------------- void TCustomEdit::SetAutoSize(bool Value) { if(AutoSize != Value) AutoSize = Value; if(AutoSize == true) SetBounds(GetLeft(), GetTop(), GetWidth(), GetFont()->GetHeight()); } //------------------------------------------------------------------- /** Transforms the characters of the specified string to uppercase letters. @note This function is from www.bruceeckel.com. */ //------------------------------------------------------------------- TString TCustomEdit::UpperCase(TString& String) { for(unsigned int i = 0; i < String.length(); i++) String[i] = toupper(String[i]); return String; } //------------------------------------------------------------------- /** Transforms the characters of the specified string to lowercase letters. @note This function is from www.bruceeckel.com. */ //------------------------------------------------------------------- TString TCustomEdit::LowerCase(TString& String) { for(unsigned int i = 0; i < String.length(); i++) String[i] = tolower(String[i]); return String; } //------------------------------------------------------------------- /** Set the character case of the control. @param Value An TEditCharCase enum: <code> ecNormal </code> for normal case (both uppercase and lowercase letters), <code> ecLowerCase </code> if the control should contains only lowercase letters and <code> ecUpperCase </code> for only uppercase letters. */ //------------------------------------------------------------------- void TCustomEdit::SetCharCase(TEditCharCase Value) { if(CharCase != Value) { CharCase = Value; TString String; String.assign(GetText()); switch(CharCase) { case ecNormal: break; case ecLowerCase: SetText(LowerCase(String)); break; case ecUpperCase: SetText(UpperCase(String)); break; } } } //------------------------------------------------------------------- /** Clear the content of the string and reset cursor position to 0. */ //------------------------------------------------------------------- void TCustomEdit::Clear(void) { GetText().erase(0, GetText().size()); SetCursorPos(0); SelStart = 0; SelEnd = 0; } //------------------------------------------------------------------- /** @return <code>true</code> if the string is empty, <code>false</code> if not. */ //------------------------------------------------------------------- bool TCustomEdit::IsEmpty(void) const { return GetText().empty(); } //------------------------------------------------------------------- /** */ //------------------------------------------------------------------- int TCustomEdit::GetMaxCursorPos() const { return GetText().size(); } //------------------------------------------------------------------- /** @param Value New cursor position. */ //------------------------------------------------------------------- void TCustomEdit::SetCursorPos(int Value) { if(CursorPos != Value) { CursorPos = Value; if(CursorPos > GetMaxCursorPos()) CursorPos = GetMaxCursorPos(); else if(CursorPos < 0) CursorPos = 0; } } //------------------------------------------------------------------- /** */ //------------------------------------------------------------------- void TCustomEdit::CursorHome() { SetCursorPos(0); SelStart = 0; } //------------------------------------------------------------------- /** Change selection end position too. */ //------------------------------------------------------------------- void TCustomEdit::CursorEnd() { SetCursorPos(GetMaxCursorPos()); SelEnd = 0; } //------------------------------------------------------------------- /** */ //------------------------------------------------------------------- void TCustomEdit::CursorLeft() { SetCursorPos(GetCursorPos() - 1); } //------------------------------------------------------------------- /** */ //------------------------------------------------------------------- void TCustomEdit::CursorRight() { SetCursorPos(GetCursorPos() + 1); } //------------------------------------------------------------------- /** */ //------------------------------------------------------------------- void TCustomEdit::DeleteLeft() { if(GetReadOnly() == false ) { int SelLength = GetSelectionLength(); // If we have selected text if(SelLength > 0) { ReplaceSelectedSubstring(""); } // If we don't have selected text else if(GetSelectionStart() > 0) { SetSelectionStart(SelStart - 1); SetSelectionEnd(GetSelectionStart()); SetCursorPos(GetSelectionStart()); TString Str = GetText(); Str.erase(GetSelectionStart(), 1); SetText(Str); } } } //------------------------------------------------------------------- /** */ //------------------------------------------------------------------- void TCustomEdit::DeleteRight() { if(GetReadOnly() == false ) { // If we have selected text if(GetSelectionLength() > 0) { ReplaceSelectedSubstring(""); } else if(GetSelectionStart() < (int)GetText().size()) { TString Str = GetText(); Str.erase(GetSelectionStart(), 1); SetText(Str); } } } //------------------------------------------------------------------- /** @note It doesn't change the cursor position. */ //------------------------------------------------------------------- void TCustomEdit::SetSelectionStart(int Value) { if(SelStart != Value) { SelStart = Value; if(SelStart > (int)GetText().size()) SelStart = (int)GetText().size(); else if(SelStart < 0) SelStart = 0; } } //------------------------------------------------------------------- /** It doesn't change the cursor position. */ //------------------------------------------------------------------- void TCustomEdit::SetSelectionEnd(int Value) { if(SelEnd != Value) { SelEnd = Value; if(SelEnd > (int)GetText().size()) SelEnd = (int)GetText().size(); else if(SelEnd < 0) SelEnd = 0; } } //------------------------------------------------------------------- /** */ //------------------------------------------------------------------- int TCustomEdit::GetSelectionLength(void) { // Check if selection end is greater than selection start if(SelEnd > SelStart) return SelEnd - SelStart; return 0; } //------------------------------------------------------------------- /** */ //------------------------------------------------------------------- TString TCustomEdit::GetSelection(void) { return GetText().substr(SelStart, GetSelectionLength()); } //------------------------------------------------------------------- /** */ //------------------------------------------------------------------- void TCustomEdit::ReplaceSelectedSubstring(TString Str) { ReplaceSelectedSubstring(Str.c_str()); } //------------------------------------------------------------------- /** Also adjust selection start, selection end and cursor position. */ //------------------------------------------------------------------- void TCustomEdit::ReplaceSelectedSubstring(const char* Str) { TString CurrentText = GetText(); CurrentText.erase(SelStart, GetSelectionLength()); CurrentText.insert(SelStart, Str); SetText(CurrentText); SelStart += strlen(Str); SelEnd = SelStart; SetCursorPos(SelStart); } //------------------------------------------------------------------- // ParseSkin() // 20-Apr-2007 rzv created //------------------------------------------------------------------- void TCustomEdit::ParseSkin(TiXmlElement* XmlElement) { TWinControl::ParseSkin(XmlElement); const char *value = NULL; // Set caret color value = XmlElement->Attribute("CaretColor"); if(value != NULL) sscanf(value, "%x", &ColorCaret); } //------------------------------------------------------------------- // EOF //-------------------------------------------------------------------
25.189252
75
0.398293
[ "object" ]
b646cf51a8c52ee594da9b0141f2bcc164e41838
3,027
cpp
C++
luogu/3722/3722.cpp
jinzhengyu1212/Clovers
0efbb0d87b5c035e548103409c67914a1f776752
[ "MIT" ]
null
null
null
luogu/3722/3722.cpp
jinzhengyu1212/Clovers
0efbb0d87b5c035e548103409c67914a1f776752
[ "MIT" ]
null
null
null
luogu/3722/3722.cpp
jinzhengyu1212/Clovers
0efbb0d87b5c035e548103409c67914a1f776752
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; const int N=200005; typedef pair<int,int> pii; #define mk make_pair #define int long long int n,m,p1,p2; int a[N],nxt[N],pre[N]; namespace BIT{ int sum[N]; int lowbit(int x){return x&(-x);} void update(int x,int add){ for(int i=x;i<=n;i+=lowbit(i)) sum[i]+=add; } int query(int x){ int ret=0; for(int i=x;i;i-=lowbit(i)) ret+=sum[i]; return ret; } } struct Segment_Tree{ int sum[N<<2],tag[N<<2]; void pushup(int x){sum[x]=sum[x<<1]+sum[x<<1|1];} void build(int x,int l,int r){ sum[x]=0; tag[x]=0; if(l==r) return; int mid=(l+r)>>1; build(x<<1,l,mid); build(x<<1|1,mid+1,r); pushup(x); } void pushdown(int x,int l,int mid,int r){ if(!tag[x]) return; tag[x<<1]+=tag[x]; tag[x<<1|1]+=tag[x]; sum[x<<1]+=tag[x]*(mid-l+1); sum[x<<1|1]+=tag[x]*(r-mid); tag[x]=0; } void update(int x,int l,int r,int L,int R){ if(L<=l&&r<=R){sum[x]+=(r-l+1); tag[x]++; return;} int mid=(l+r)>>1; pushdown(x,l,mid,r); if(mid>=L) update(x<<1,l,mid,L,R); if(mid<R) update(x<<1|1,mid+1,r,L,R); pushup(x); } int query(int x,int l,int r,int L,int R){ if(L<=l&&r<=R) return sum[x]; int mid=(l+r)>>1; pushdown(x,l,mid,r); int ret=0; if(mid>=L) ret+=query(x<<1,l,mid,L,R); if(mid<R) ret+=query(x<<1|1,mid+1,r,L,R); return ret; } }tree; struct node{ int id,flag,L,R; node(){} node(int id,int flag,int L,int R):id(id),flag(flag),L(L),R(R){} }; vector<int> V[N]; vector<pii> G[N]; vector<node> Q[N]; int q[N],top=0; void init(){ scanf("%lld%lld%lld%lld",&n,&m,&p1,&p2); for(int i=1;i<=n;i++) scanf("%lld",&a[i]); a[0]=a[n+1]=n+1;q[++top]=0; for(int i=1;i<=n+1;i++) { while(a[q[top]]<a[i]) nxt[q[top]]=i,top--; pre[i]=q[top];q[++top]=i; } tree.build(1,1,n); for(int i=1;i<=n;i++){ int l=pre[i]; int r=nxt[i]; if(l!=0&&r!=n+1) V[r].push_back(l); if(i<r-1) G[l].push_back(mk(i+1,r-1)); if(l<i-1) G[r].push_back(mk(l+1,i-1)); } } int ans[N]; void solve(){ for(int i=1;i<=m;i++){ int L,R; scanf("%lld%lld",&L,&R); Q[L-1].push_back(node(i,-1,L,R)); Q[R].push_back(node(i,1,L,R)); } for(int i=1;i<=n;i++){ for(int j=0;j<(int)V[i].size();j++){ BIT::update(V[i][j],1); } for(int j=0;j<(int)G[i].size();j++){ tree.update(1,1,n,G[i][j].first,G[i][j].second); } for(int j=0;j<(int)Q[i].size();j++){ node now=Q[i][j]; int L=now.L,R=now.R,id=now.id; ans[id]+=now.flag*p2*tree.query(1,1,n,L,R); if(now.flag==1) ans[id]+=p1*(BIT::query(R)-BIT::query(L-1)); if(now.flag==1) ans[id]+=(R-L)*p1; } } for(int i=1;i<=m;i++) printf("%lld\n",ans[i]); } signed main(){ init(); solve(); return 0; }
27.026786
76
0.474067
[ "vector" ]
b6474f1b42de7301a337af45eb8dec16b6f692c9
1,866
cpp
C++
src/processor.cpp
ajhsutton/CppND-System-Monitor-Project-Updated
f5fc8d109c4a85c6b6b850b4b617c4c237acca23
[ "MIT" ]
null
null
null
src/processor.cpp
ajhsutton/CppND-System-Monitor-Project-Updated
f5fc8d109c4a85c6b6b850b4b617c4c237acca23
[ "MIT" ]
null
null
null
src/processor.cpp
ajhsutton/CppND-System-Monitor-Project-Updated
f5fc8d109c4a85c6b6b850b4b617c4c237acca23
[ "MIT" ]
null
null
null
#include "processor.h" #include "linux_parser.h" #include <string> #include <vector> // DONE: Return the aggregate CPU utilization float Processor::Utilization() { std::vector<std::string> cpu_utilization = LinuxParser::CpuUtilization(); // Parse CPU Utilization data from: // https://stackoverflow.com/questions/23367857/accurate-calculation-of-cpu-usage-given-in-percentage-in-linux long int usertime = std::stol(cpu_utilization[0]); long int nicetime = std::stol(cpu_utilization[1]); long int systemtime = std::stol(cpu_utilization[2]); long int idletime = std::stol(cpu_utilization[3]); long int ioWait = std::stol(cpu_utilization[4]); long int irqtime = std::stol(cpu_utilization[5]); long int softirqtime = std::stol(cpu_utilization[6]); long int stealtime = std::stol(cpu_utilization[7]); long int guesttime = std::stol(cpu_utilization[8]); long int guestnice = std::stol(cpu_utilization[9]); // Utlization // Guest time is already accounted in usertime usertime = usertime - guesttime; // As you see here, it subtracts guest from user time nicetime = nicetime - guestnice; // and guest_nice from nice time auto systemalltime = systemtime + irqtime + softirqtime; auto virtalltime = guesttime + guestnice; auto idlealltime = idletime + ioWait; // ioWait is added in the idleTime auto nonidletime = usertime + nicetime + systemalltime + stealtime; auto totaltime = usertime + nicetime + systemalltime + idlealltime + stealtime + virtalltime; long idle_diff = idlealltime - prevIdle; auto prevTotal = prevIdle + prevNonIdle; // Update internal state prevIdle = idlealltime; prevNonIdle = nonidletime; // differentiate: actual value minus the previous one auto totald = totaltime - prevTotal; float cpu_pct = float(totald - idle_diff)/totald; return cpu_pct; };
41.466667
112
0.724544
[ "vector" ]
b65bda4494f32e0d1d634d441fb151ef52a2f773
1,621
cpp
C++
tests/KmerCounterTest.cpp
ASLeonard/pangenie
aeb0c2aa28bf69041755855306d32f5523371274
[ "MIT" ]
8
2021-12-10T10:30:08.000Z
2022-03-30T08:49:01.000Z
tests/KmerCounterTest.cpp
ASLeonard/pangenie
aeb0c2aa28bf69041755855306d32f5523371274
[ "MIT" ]
7
2022-02-09T15:28:23.000Z
2022-03-22T10:12:50.000Z
tests/KmerCounterTest.cpp
ASLeonard/pangenie
aeb0c2aa28bf69041755855306d32f5523371274
[ "MIT" ]
1
2022-02-08T09:56:36.000Z
2022-02-08T09:56:36.000Z
#include "catch.hpp" #include "utils.hpp" #include "../src/jellyfishcounter.hpp" #include "../src/jellyfishreader.hpp" #include <vector> #include <string> using namespace std; TEST_CASE("JellyfishCounter", "[JellyfishCounter]") { JellyfishCounter counter("../tests/data/reads.fa", 10); string read = "ATGCTGTAAAAAAACGGC"; for (size_t i = 0; i < read.size()-9; ++i) { string kmer = read.substr(i,10); REQUIRE(counter.getKmerAbundance(kmer) == 1); } KmerCounter* t = new JellyfishCounter ("../tests/data/reads.fa", 10); delete t; } TEST_CASE("JellyfishCounter_if", "[JellyfishCounter_if]") { JellyfishCounter counter("../tests/data/reads.fa", "../tests/data/kmerfile.fa", 10); // these two kmers are in kmerfile.fa and should have been counted REQUIRE(counter.getKmerAbundance("ATGCTGTAAA") == 1); REQUIRE(counter.getKmerAbundance("TGCTGTAAAA") == 1); // the following kmers are not contained in kmerfile.fa, thus they should have count 0 string kmers = "GCTGTAAAAAAACGGC"; for (size_t i = 0; i < kmers.size()-9; ++i) { string kmer = kmers.substr(i,10); REQUIRE(counter.getKmerAbundance(kmer) == 0); } } TEST_CASE("JellyfishReader", "[JellyfishReader]") { JellyfishReader reader ("../tests/data/reads.jf", 10); string read = "ATGCTGTAAAAAAACGGC"; for (size_t i = 0; i < read.size()-9; ++i) { string kmer = read.substr(i,10); REQUIRE(reader.getKmerAbundance(kmer) == 1); } // reads where counted without the -C option REQUIRE_THROWS(JellyfishReader("../tests/data/reads.no-canonical.jf", 10)); // wrong kmer size used REQUIRE_THROWS(JellyfishReader("../tests/data/reads.jf", 11)); }
33.081633
87
0.700185
[ "vector" ]
b65e38cf5efeb88c88644eddffad78b8d40329ba
25,828
cpp
C++
core/ctroll/programwidget.cpp
c-toolbox/C-Troll
7fa6cc16677e179cf6a73bb60361a8cce158a95a
[ "BSD-3-Clause" ]
4
2017-01-05T12:45:41.000Z
2020-10-05T15:58:32.000Z
core/ctroll/programwidget.cpp
c-toolbox/C-Troll
7fa6cc16677e179cf6a73bb60361a8cce158a95a
[ "BSD-3-Clause" ]
20
2016-09-22T11:40:19.000Z
2022-03-04T08:05:10.000Z
core/ctroll/programwidget.cpp
c-toolbox/C-Troll
7fa6cc16677e179cf6a73bb60361a8cce158a95a
[ "BSD-3-Clause" ]
null
null
null
/***************************************************************************************** * * * Copyright (c) 2016 - 2020 * * Alexander Bock, Erik Sunden, Emil Axelsson * * * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without modification, are * * permitted provided that the following conditions are met: * * * * 1. Redistributions of source code must retain the above copyright notice, this list * * of conditions and the following disclaimer. * * * * 2. Redistributions in binary form must reproduce the above copyright notice, this * * list of conditions and the following disclaimer in the documentation and/or other * * materials provided with the distribution. * * * * 3. Neither the name of the copyright holder nor the names of its contributors may be * * used to endorse or promote products derived from this software without specific * * prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * * SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * * DAMAGE. * * * ****************************************************************************************/ #include "programwidget.h" #include "cluster.h" #include "configuration.h" #include "database.h" #include "logging.h" #include <QApplication> #include <QCheckBox> #include <QComboBox> #include <QDesktopWidget> #include <QHBoxLayout> #include <QLabel> #include <QLineEdit> #include <QMenu> #include <QScrollArea> #include <QVBoxLayout> #include <fmt/format.h> #include <set> namespace programs { ProgramButton::ProgramButton(const Cluster* cluster, const Program::Configuration* configuration) : QPushButton(QString::fromStdString(configuration->name)) , _cluster(cluster) , _configuration(configuration) , _actionMenu(new QMenu(this)) { assert(cluster); assert(configuration); setToolTip(QString::fromStdString(configuration->description)); setEnabled(false); connect(this, &QPushButton::clicked, this, &ProgramButton::handleButtonPress); } void ProgramButton::updateStatus() { std::vector<const Node*> nodes = data::findNodesForCluster(*_cluster); const bool allConnected = std::all_of( nodes.cbegin(), nodes.cend(), std::mem_fn(&Node::isConnected) ); setEnabled(allConnected); } void ProgramButton::processUpdated(Process::ID processId) { const Process* process = data::findProcess(processId); auto it = std::find_if( _processes.cbegin(), _processes.cend(), [processId](const std::pair<const Node::ID, ProcessInfo>& p) { return p.second.processId.v == processId.v; } ); if (it == _processes.end()) { // This is a brand new process, so it better be in a Starting status ProcessInfo info; info.processId = processId; const Node* node = data::findNode(process->nodeId); assert(node); info.menuAction = new QAction(QString::fromStdString(node->name)); // We store the name of the node as the user data in order to sort them later info.menuAction->setData(QString::fromStdString(node->name)); _processes[process->nodeId] = info; } else { // This is a process that already exists and we should update it depending on the // status of the incoming process assert(it->second.processId.v == processId.v); } updateButton(); } void ProgramButton::handleButtonPress() { // This slot should only be invoked if either all processes are running, or no process // are running assert(hasNoProcessRunning() || hasAllProcessesRunning()); if (hasNoProcessRunning()) { emit startProgram(_configuration->id); // We disable the button until we get another message back from the tray setEnabled(false); } else if (hasAllProcessesRunning()) { emit stopProgram(_configuration->id); // We disable the button until we get another message back from the tray setEnabled(false); } else { // This slot should only be invoked if either all processes are running, or no // process are running assert(false); } } void ProgramButton::updateButton() { setEnabled(true); // If all processes don't exist or are in NormalExit/CrashExit/FailedToStart, we show // the regular start button without any menus attached if (hasNoProcessRunning()) { setMenu(nullptr); setObjectName("start"); // used in the QSS sheet to style this button // @TODO (abock, 2020-02-25) Replace when putting the QSS in place setText(QString::fromStdString(_configuration->name)); } else if (hasAllProcessesRunning()) { setMenu(nullptr); setObjectName("stop"); // used in the QSS sheet to style this button // @TODO (abock, 2020-02-25) Replace when putting the QSS in place setText(QString::fromStdString("Stop:" + _cluster->name)); } else { setMenu(_actionMenu); setObjectName("mixed"); // used in the QSS sheet to style this button // @TODO (abock, 2020-02-25) Replace when putting the QSS in place setText(QString::fromStdString("Mixed:" + _cluster->name)); updateMenu(); } } void ProgramButton::updateMenu() { // First a bit of cleanup so that we don't have old signal connections laying around for (const std::pair<const Node::ID, ProcessInfo>& p : _processes) { QObject::disconnect(p.second.menuAction); } _actionMenu->clear(); std::vector<QAction*> actions; actions.reserve(_processes.size()); for (const std::pair<const Node::ID, ProcessInfo>& p : _processes) { actions.push_back(p.second.menuAction); } std::sort( actions.begin(), actions.end(), [](QAction* lhs, QAction* rhs) { return lhs->data().toString() < rhs->data().toString(); } ); for (QAction* action : actions) { QString actName = action->data().toString(); const std::string nodeName = actName.toLocal8Bit().constData(); const auto it = std::find_if( _processes.cbegin(), _processes.cend(), [nodeName](const std::pair<const Node::ID, ProcessInfo>& p) { const Node* node = data::findNode(p.first); return node->name == nodeName; } ); // If we are getting this far, the node for this action has to exist in the map assert(it != _processes.cend()); // We only going to update the actions if some of the nodes are not running but // some others are. So we basically have to provide the ability to start the nodes // that are currently not running and close the ones that currently are if (isProcessRunning(it->first)) { setObjectName("stop"); // used in the QSS sheet to style this button connect( action, &QAction::triggered, [this, id = it->second.processId]() { emit stopProcess(id); } ); // @TODO (abock, 2020-02-25) Replace when putting the QSS in place action->setText("Stop: " + actName); } else { setObjectName("restart"); // used in the QSS sheet to style this button connect( action, &QAction::triggered, [this, id = it->second.processId]() { emit restartProcess(id); } ); // @TODO (abock, 2020-02-25) Replace when putting the QSS in place action->setText("Restart: " + actName); } _actionMenu->addAction(action); } } bool ProgramButton::isProcessRunning(Node::ID nodeId) const { using Status = common::ProcessStatusMessage::Status; const auto it = _processes.find(nodeId); return (it != _processes.cend()) && data::findProcess(it->second.processId)->status == Status::Running; } bool ProgramButton::hasNoProcessRunning() const { return std::none_of( _cluster->nodes.cbegin(), _cluster->nodes.cend(), [this](const std::string& n) { const Node* node = data::findNode(n); return isProcessRunning(node->id); } ); } bool ProgramButton::hasAllProcessesRunning() const { return std::all_of( _cluster->nodes.cbegin(), _cluster->nodes.cend(), [this](const std::string& n) { const Node* node = data::findNode(n); return isProcessRunning(node->id); } ); } ////////////////////////////////////////////////////////////////////////////////////////// ClusterWidget::ClusterWidget(const Cluster* cluster, const std::vector<Program::Configuration>& configurations) { assert(cluster); setTitle(QString::fromStdString(cluster->name)); setToolTip(QString::fromStdString(cluster->description)); QBoxLayout* layout = new QVBoxLayout(this); layout->setContentsMargins(5, 5, 5, 5); for (const Program::Configuration& configuration : configurations) { ProgramButton* button = new ProgramButton(cluster, &configuration); connect( button, &ProgramButton::startProgram, this, &ClusterWidget::startProgram ); connect( button, &ProgramButton::stopProgram, this, &ClusterWidget::stopProgram ); connect( button, &ProgramButton::restartProcess, this, &ClusterWidget::restartProcess ); connect( button, &ProgramButton::stopProcess, this, &ClusterWidget::stopProcess ); _startButtons[configuration.id] = button; layout->addWidget(button); } } void ClusterWidget::updateStatus() { std::for_each( _startButtons.cbegin(), _startButtons.cend(), [](const std::pair<const Program::Configuration::ID, ProgramButton*>& p) { p.second->updateStatus(); } ); } void ClusterWidget::processUpdated(Process::ID processId) { const Process* process = data::findProcess(processId); const auto it = _startButtons.find(process->configurationId); if (it != _startButtons.end()) { it->second->processUpdated(processId); } } ////////////////////////////////////////////////////////////////////////////////////////// TagInfoWidget::TagInfoWidget(const std::vector<std::string>& tags) { QBoxLayout* layout = new QVBoxLayout(this); layout->setMargin(0); for (const std::string& tag : tags) { QWidget* w = new QWidget; Color color = data::colorForTag(tag); w->setStyleSheet(QString::fromStdString(fmt::format( "background: #{0:02x}{1:02x}{2:02x}", color.r, color.g, color.b ))); w->setToolTip(QString::fromStdString(tag)); layout->addWidget(w); } } ////////////////////////////////////////////////////////////////////////////////////////// ProgramWidget::ProgramWidget(const Program& program) : QGroupBox(QString::fromStdString(program.name)) { setToolTip(QString::fromStdString(program.description)); QBoxLayout* layout = new QHBoxLayout(this); layout->setContentsMargins(5, 5, 5, 5); layout->setSpacing(10); layout->addWidget(new TagInfoWidget(program.tags)); std::vector<const Cluster*> clusters = data::findClustersForProgram(program); for (const Cluster* cluster : clusters) { assert(cluster); ClusterWidget* w = new ClusterWidget(cluster, program.configurations); connect( w, &ClusterWidget::startProgram, [this, clusterId = cluster->id](Program::Configuration::ID configurationId) { emit startProgram(clusterId, configurationId); } ); connect( w, &ClusterWidget::stopProgram, [this, clusterId = cluster->id](Program::Configuration::ID configurationId) { emit stopProgram(clusterId, configurationId); } ); connect(w, &ClusterWidget::restartProcess, this, &ProgramWidget::restartProcess); connect(w, &ClusterWidget::stopProcess, this, &ProgramWidget::stopProcess); _widgets[cluster->id] = w; layout->addWidget(w); } } void ProgramWidget::updateStatus(Cluster::ID clusterId) { const auto it = _widgets.find(clusterId); // We have to check as a cluster that is active might not have any associated programs if (it != _widgets.end()) { it->second->updateStatus(); } } void ProgramWidget::processUpdated(Process::ID processId) { const Process* process = data::findProcess(processId); const auto it = _widgets.find(process->clusterId); assert(it != _widgets.end()); it->second->processUpdated(processId); } ////////////////////////////////////////////////////////////////////////////////////////// TagsWidget::TagsWidget() : QGroupBox("Tags") { QBoxLayout* layout = new QVBoxLayout(this); layout->setContentsMargins(5, 5, 5, 5); std::set<std::string> tags = data::findTags(); for (const std::string& tag : tags) { QPushButton* button = new QPushButton(QString::fromStdString(tag)); Color color = data::colorForTag(tag); constexpr const int Delta = 40; Color lightColor = Color { std::min(255, color.r + Delta), std::min(255, color.g + Delta), std::min(255, color.b + Delta), "" }; Color darkColor = Color { std::max(0, color.r - Delta), std::max(0, color.g - Delta), std::max(0, color.b - Delta), "" }; std::string colorText = fmt::format( R"( QPushButton {{ background-color: #{0:02x}{1:02x}{2:02x}; }} QPushButton:hover {{ background-color: #{3:02x}{4:02x}{5:02x}; }} QPushButton:pressed {{ background-color: #{6:02x}{7:02x}{8:02x}; }} QPushButton:open {{ background-color: #{6:02x}{7:02x}{8:02x}; }} )", color.r, color.g, color.b, lightColor.r, lightColor.g, lightColor.b, darkColor.r, darkColor.g, darkColor.b ); button->setStyleSheet(QString::fromStdString(colorText)); // @TODO (abock, 2020-09-29): Calculate the value of the background color and // set a dynamic property to set the text color to either bright or dark to make // the text legible regardless of what the user chose for the background color button->setCheckable(true); connect(button, &QPushButton::clicked, this, &TagsWidget::buttonPressed); layout->addWidget(button); _buttons[button] = tag; } layout->addStretch(); } void TagsWidget::buttonPressed() { std::vector<std::string> selectedTags; for (std::pair<const QPushButton*, std::string> p : _buttons) { if (p.first->isChecked()) { selectedTags.push_back(p.second); } } emit pickedTags(selectedTags); } ////////////////////////////////////////////////////////////////////////////////////////// CustomProgramWidget::CustomProgramWidget(QWidget* parent) : QWidget(parent) { QBoxLayout* layout = new QHBoxLayout(this); layout->setContentsMargins(0, 0, 0, 0); QComboBox* targetList = new QComboBox; std::vector<const Cluster*> clusters = data::clusters(); if (!clusters.empty()) { targetList->addItem("Clusters", TagSeparator); for (const Cluster* c : clusters) { targetList->addItem(QString::fromStdString(c->name), TagCluster); } } std::vector<const Node*> nodes = data::nodes(); if (!nodes.empty()) { if (!clusters.empty()) { targetList->addItem("", TagSeparator); } targetList->addItem("Nodes", TagSeparator); targetList->addItem("------------", TagSeparator); for (const Node* n : nodes) { targetList->addItem(QString::fromStdString(n->name), TagNode); } } targetList->setCurrentIndex(-1); layout->addWidget(targetList); QLineEdit* executable = new QLineEdit; executable->setPlaceholderText("Executable name"); layout->addWidget(executable); QLineEdit* workingDirectory = new QLineEdit; workingDirectory->setPlaceholderText("Working directory"); layout->addWidget(workingDirectory); QLineEdit* parameters = new QLineEdit; parameters->setPlaceholderText("Parameters (optional)"); layout->addWidget(parameters); layout->addStretch(0); QPushButton* run = new QPushButton("Run"); run->setObjectName("run"); run->setEnabled(false); // since the "Clusters" target will be selected by default connect( run, &QPushButton::clicked, [this, targetList, executable, workingDirectory, parameters]() { const std::string exec = executable->text().toStdString(); const std::string workDir = workingDirectory->text().toStdString(); const std::string args = parameters->text().toStdString(); const int tag = targetList->currentData().toInt(); assert(tag == TagCluster || tag == TagNode); if (tag == TagCluster) { const std::string cluster = targetList->currentText().toStdString(); const Cluster* c = data::findCluster(cluster); assert(c); for (const std::string& node : c->nodes) { const Node* n = data::findNode(node); assert(n); emit startCustomProgram(n->id, exec, workDir, args); } } else { const std::string node = targetList->currentText().toStdString(); const Node* n = data::findNode(node); assert(n); emit startCustomProgram(n->id, exec, workDir, args); } } ); layout->addWidget(run); QPushButton* clear = new QPushButton("Clear"); connect( clear, &QPushButton::clicked, [targetList, executable, workingDirectory, parameters]() { targetList->setCurrentIndex(-1); executable->setText(""); workingDirectory->setText(""); parameters->setText(""); } ); layout->addWidget(clear); auto updateRunButton = [targetList, executable, run]() { const bool goodTarget = targetList->currentData().toInt() != TagSeparator; const bool goodExec = !executable->text().isEmpty(); run->setEnabled(goodTarget && goodExec); }; connect( targetList, QOverload<int>::of(&QComboBox::currentIndexChanged), updateRunButton ); connect( executable, &QLineEdit::textChanged, updateRunButton ); } ////////////////////////////////////////////////////////////////////////////////////////// ProgramsWidget::ProgramsWidget() { QGridLayout* layout = new QGridLayout(this); layout->setContentsMargins(10, 2, 2, 2); layout->addWidget(createControls(), 0, 0); layout->addWidget(createPrograms(), 0, 1); layout->setColumnStretch(1, 5); CustomProgramWidget* customPrograms = new CustomProgramWidget(this); connect( customPrograms, &CustomProgramWidget::startCustomProgram, this, &ProgramsWidget::startCustomProgram ); layout->addWidget(customPrograms, 1, 0, 1, 2); } QWidget* ProgramsWidget::createControls() { QWidget* controls = new QWidget; QBoxLayout* layout = new QVBoxLayout(controls); layout->setMargin(0); QLineEdit* search = new QLineEdit; search->setPlaceholderText("Search..."); layout->addWidget(search); connect( search, &QLineEdit::textChanged, [this](const QString& str) { emit searchUpdated(str.toLocal8Bit().constData()); } ); TagsWidget* tags = new TagsWidget; connect(tags, &TagsWidget::pickedTags, this, &ProgramsWidget::tagsPicked); layout->addWidget(tags); return controls; } QWidget* ProgramsWidget::createPrograms() { QScrollArea* area = new QScrollArea; area->setWidgetResizable(true); area->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); QWidget* content = new QWidget; area->setWidget(content); QBoxLayout* contentLayout = new QVBoxLayout(content); contentLayout->setContentsMargins(5, 5, 5, 5); area->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Expanding); for (const Program* p : data::programs()) { ProgramWidget* w = new ProgramWidget(*p); connect( w, &ProgramWidget::startProgram, [this, programId = p->id](Cluster::ID clusterId, Program::Configuration::ID configurationId) { emit startProgram(clusterId, programId, configurationId); } ); connect( w, &ProgramWidget::stopProgram, [this, programId = p->id](Cluster::ID clusterId, Program::Configuration::ID configurationId) { emit stopProgram(clusterId, programId, configurationId); } ); connect(w, &ProgramWidget::restartProcess, this, &ProgramsWidget::restartProcess); connect(w, &ProgramWidget::stopProcess, this, &ProgramsWidget::stopProcess); _widgets[p->id] = w; VisibilityInfo info; info.bySearch = true; info.byTag = true; _visibilities[p->id] = info; contentLayout->addWidget(w); } contentLayout->addStretch(0); return area; } void ProgramsWidget::processUpdated(Process::ID processId) { const Process* process = data::findProcess(processId); const auto it = _widgets.find(process->programId); if (it != _widgets.cend()) { it->second->processUpdated(processId); } } void ProgramsWidget::connectedStatusChanged(Cluster::ID cluster, Node::ID) { for (const std::pair<const Program::ID, ProgramWidget*>& p : _widgets) { p.second->updateStatus(cluster); } } void ProgramsWidget::tagsPicked(std::vector<std::string> tags) { if (tags.empty()) { for (std::pair<const Program::ID, VisibilityInfo>& p : _visibilities) { p.second.byTag = true; } } else { for (std::pair<const Program::ID, VisibilityInfo>& p : _visibilities) { const bool hasTag = data::hasTag(p.first, tags); p.second.byTag = hasTag; } } updatedVisibilityState(); } void ProgramsWidget::searchUpdated(std::string text) { if (text.empty()) { for (std::pair<const Program::ID, VisibilityInfo>& p : _visibilities) { p.second.bySearch = true; } } else { for (std::pair<const Program::ID, VisibilityInfo>& p : _visibilities) { const Program* program = data::findProgram(p.first); if (text.size() > program->name.size()) { p.second.bySearch = false; } else { auto toLower = [](const std::string& str) { std::string res; std::transform( str.cbegin(), str.cend(), std::back_inserter(res), [](char c) { return static_cast<char>(::tolower(c)); } ); return res; }; const std::string sub = program->name.substr(0, text.size()); p.second.bySearch = toLower(sub) == toLower(text); } } } updatedVisibilityState(); } void ProgramsWidget::updatedVisibilityState() { for (std::pair<const Program::ID, ProgramWidget*>& p : _widgets) { VisibilityInfo vi = _visibilities[p.first]; p.second->setVisible(vi.bySearch && vi.byTag); } } } // namespace programs
36.123077
90
0.572634
[ "vector", "transform" ]
b663f24dd36f1ca39a554b9f06068fba626e19a2
801
cc
C++
test/core/test2.4.2-1/test.cc
XpressAI/frovedis
bda0f2c688fb832671c5b542dd8df1c9657642ff
[ "BSD-2-Clause" ]
63
2018-06-21T14:11:59.000Z
2022-03-30T11:24:36.000Z
test/core/test2.4.2-1/test.cc
XpressAI/frovedis
bda0f2c688fb832671c5b542dd8df1c9657642ff
[ "BSD-2-Clause" ]
5
2018-09-22T14:01:53.000Z
2021-12-27T16:11:05.000Z
test/core/test2.4.2-1/test.cc
XpressAI/frovedis
bda0f2c688fb832671c5b542dd8df1c9657642ff
[ "BSD-2-Clause" ]
12
2018-08-23T15:59:44.000Z
2022-02-20T06:47:22.000Z
#include <frovedis.hpp> #define BOOST_TEST_MODULE FrovedisTest #include <boost/test/unit_test.hpp> using namespace frovedis; using namespace std; struct n_times { n_times(){} n_times(int n_) : n(n_) {} int operator()(int i){return i*n;} int n; SERIALIZE(n) }; BOOST_AUTO_TEST_CASE( frovedis_test ) { int argc = 1; char** argv = NULL; use_frovedis use(argc, argv); // filling sample input and output vectors std::vector<int> v, ref_out; for(size_t i = 1; i <= 8; i++) v.push_back(i); for(size_t i = 1; i <= 8; i++) ref_out.push_back(i*3); // testing dvector::map on functor auto d1 = frovedis::make_dvector_scatter(v); auto d2 = d1.map<int>(n_times(3)); auto r = d2.gather(); // confirming resultant vector with expected output BOOST_CHECK(r == ref_out); }
22.25
56
0.670412
[ "vector" ]
b6653820b18f33f5d7316c0a993533e31bd11e99
2,550
cpp
C++
src/main.cpp
arrufat/tiler
85ef5ac355dd6b8a127833a708f8a963f5be022c
[ "BSL-1.0" ]
null
null
null
src/main.cpp
arrufat/tiler
85ef5ac355dd6b8a127833a708f8a963f5be022c
[ "BSL-1.0" ]
null
null
null
src/main.cpp
arrufat/tiler
85ef5ac355dd6b8a127833a708f8a963f5be022c
[ "BSL-1.0" ]
null
null
null
#include <algorithm> #include <iostream> #include <sstream> #include <dlib/cmd_line_parser.h> #include <dlib/image_io.h> #include <dlib/gui_widgets.h> #include <dlib/dir_nav.h> #include <dlib/image_transforms.h> int main(int argc, char** argv) try { dlib::command_line_parser cmd_parser; cmd_parser.add_option("max-size", "max num of pixels per image", 1); cmd_parser.add_option("max-images", "maximum number of images", 1); cmd_parser.add_option("show", "show the resulting image"); cmd_parser.set_group_name("Help Options"); cmd_parser.add_option("h", ""); cmd_parser.add_option("help", "display this message and exit"); cmd_parser.parse(argc, argv); if (cmd_parser.number_of_arguments() == 0 || cmd_parser.option("h") || cmd_parser.option("help")) { std::cout << "\nUsage: tiler [options] directory\n\n"; cmd_parser.print_options(); return EXIT_SUCCESS; } const std::string& root = cmd_parser[0]; const double max_size = dlib::get_option(cmd_parser, "max-size", std::numeric_limits<double>::max()); const size_t max_images = dlib::get_option(cmd_parser, "max-images", std::numeric_limits<size_t>::max()); auto files = dlib::get_files_in_directory_tree(root, dlib::match_endings(".jpg .JPG .jpeg .JPEG .png .PNG")); std::sort(files.begin(), files.end()); std::cout << "Found " << files.size() << " images\n"; auto num_images = std::min(max_images, files.size()); files.erase(files.begin() + num_images, files.end()); std::cout << "Generating tiled image with " << files.size() << " images\n"; std::vector<dlib::matrix<dlib::rgb_pixel>> images; images.assign(files.size(), dlib::matrix<dlib::rgb_pixel>()); dlib::parallel_for(0, files.size(), [&files, max_size, &images](size_t i) { const auto& file = files[i]; dlib::matrix<dlib::rgb_pixel> image; dlib::load_image(image, file.full_name()); if (const auto scaling_factor = std::sqrt(max_size / image.size()); scaling_factor < 1) { dlib::resize_image(scaling_factor, image); } images[i] = std::move(image); }); dlib::matrix<dlib::rgb_pixel> tiled_image = dlib::tile_images(images); dlib::save_jpeg(tiled_image, "tiled_image.jpg"); if (cmd_parser.option("show")) { dlib::image_window win(tiled_image, "tiled image"); win.wait_until_closed(); } return EXIT_SUCCESS; } catch (std::exception& e) { std::cout << e.what() << std::endl; return EXIT_FAILURE; }
38.059701
113
0.651765
[ "vector" ]
b670e567f80187193e99487eb4515e8bc199c613
6,420
cpp
C++
rs/test/catch_test.cpp
dymk/rs
b75ab0df5f235ac12ec4da825e6bd6e1fa9e7493
[ "Apache-2.0" ]
19
2017-05-15T08:20:00.000Z
2021-12-03T05:58:32.000Z
rs/test/catch_test.cpp
dymk/rs
b75ab0df5f235ac12ec4da825e6bd6e1fa9e7493
[ "Apache-2.0" ]
null
null
null
rs/test/catch_test.cpp
dymk/rs
b75ab0df5f235ac12ec4da825e6bd6e1fa9e7493
[ "Apache-2.0" ]
3
2018-01-16T18:07:30.000Z
2021-06-30T07:33:44.000Z
// Copyright 2017 Per Grön. 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 <catch.hpp> #include <vector> #include <rs/catch.h> #include <rs/empty.h> #include <rs/just.h> #include <rs/pipe.h> #include <rs/start_with.h> #include <rs/throw.h> #include "backpressure_violator.h" #include "test_util.h" namespace shk { TEST_CASE("Catch") { auto null_catch = Catch([](std::exception_ptr &&) { CHECK(!"should not be called"); return Empty(); }); auto empty_catch = Catch([](std::exception_ptr &&) { return Empty(); }); auto single_catch = Catch([](std::exception_ptr &&) { return Just(14); }); auto failing = Throw(std::runtime_error("test")); auto failing_catch = Catch([failing](std::exception_ptr &&) { return failing; }); auto failing_later = Pipe( Throw(std::runtime_error("test")), StartWith(13)); static_assert( IsPublisher<decltype(empty_catch(Just()))>, "Catch stream should be a publisher"); SECTION("subscription is default constructible") { SECTION("as returned from Catch") { auto stream = null_catch(Just()); decltype(stream.Subscribe(MakeNonDefaultConstructibleSubscriber())) sub; sub.Request(ElementCount(1)); sub.Cancel(); } SECTION("CatchSubscription") { auto subscriber = MakeNonDefaultConstructibleSubscriber(); auto callback = [](auto) { return Empty(); }; using CatchT = detail::Catch< decltype(subscriber), decltype(callback), AnySubscription>; typename CatchT::CatchSubscription sub; sub.Request(ElementCount(1)); sub.Cancel(); } } SECTION("succeeding input") { SECTION("empty") { CHECK(GetAll<int>(null_catch(Just())) == std::vector<int>({})); } SECTION("one value") { CHECK(GetAll<int>(null_catch(Just(1))) == std::vector<int>({ 1 })); } } SECTION("failing input") { SECTION("empty catch") { SECTION("empty input") { CHECK(GetAll<int>(empty_catch(failing)) == std::vector<int>({})); } SECTION("one input value") { CHECK( GetAll<int>(empty_catch(failing_later)) == std::vector<int>({ 13 })); } } SECTION("nonempty catch") { SECTION("empty input") { CHECK(GetAll<int>(single_catch(failing)) == std::vector<int>({ 14 })); } SECTION("one input value") { CHECK( GetAll<int>(single_catch(failing_later)) == std::vector<int>({ 13, 14 })); } SECTION("one input value, request 0") { CHECK( GetAll<int>(single_catch(failing_later), ElementCount(0), false) == std::vector<int>({})); } SECTION("one input value, request 1") { CHECK( GetAll<int>(single_catch(failing_later), ElementCount(1), false) == std::vector<int>({ 13 })); } SECTION("one input value, request 2") { CHECK( GetAll<int>(single_catch(failing_later), ElementCount(2)) == std::vector<int>({ 13, 14 })); } SECTION("one input value, request 3") { CHECK( GetAll<int>(single_catch(failing_later), ElementCount(3)) == std::vector<int>({ 13, 14 })); } } SECTION("failing catch") { SECTION("empty input") { auto stream = failing_catch(failing); auto error = GetError(stream); CHECK(GetErrorWhat(error) == "test"); CHECK(GetAll<int>(empty_catch(stream)) == std::vector<int>({})); } SECTION("one input value") { auto stream = failing_catch(failing_later); auto error = GetError(stream); CHECK(GetErrorWhat(error) == "test"); CHECK(GetAll<int>(empty_catch(stream)) == std::vector<int>({ 13 })); } } } SECTION("don't leak the subscriber") { CheckLeak(empty_catch(Just(1))); CheckLeak(empty_catch(failing)); } SECTION("cancellation") { SECTION("cancel before failing") { bool cancelled = false; auto stream = null_catch(MakePublisher([&cancelled](auto &&subscriber) { return MakeSubscription( [](ElementCount count) {}, [&cancelled] { CHECK(!cancelled); cancelled = true; }); })); auto sub = stream.Subscribe(MakeSubscriber()); CHECK(!cancelled); sub.Cancel(); CHECK(cancelled); } SECTION("cancel after failing") { bool cancelled = false; auto check_catch = Catch([&cancelled](std::exception_ptr &&) { return MakePublisher([&cancelled](auto &&subscriber) { return MakeSubscription( [](ElementCount count) {}, [&cancelled] { CHECK(!cancelled); cancelled = true; }); }); }); auto stream = check_catch(Throw(std::runtime_error("test"))); auto sub = stream.Subscribe(MakeSubscriber()); CHECK(!cancelled); sub.Cancel(); CHECK(cancelled); } SECTION("do not invoke catch if fail after cancel") { std::function<void ()> fail; auto fail_on_demand = MakePublisher([&fail](auto subscriber) { auto subscriber_ptr = std::make_shared<decltype(subscriber)>( std::move(subscriber)); fail = [subscriber_ptr]() mutable { subscriber_ptr->OnError( std::make_exception_ptr(std::runtime_error("test"))); }; return MakeSubscription(); }); auto stream = null_catch(fail_on_demand); auto sub = stream.Subscribe(MakeSubscriber()); sub.Cancel(); fail(); // This should not invoke null_catch's callback } } SECTION("backpressure violation") { auto stream = null_catch(BackpressureViolator(1, [] { return 0; })); auto error = GetError(stream, ElementCount(1)); CHECK(GetErrorWhat(error) == "Got value that was not Request-ed"); } } } // namespace shk
29.585253
79
0.602181
[ "vector" ]
b67429adcd1c9db10ccab16f0384b826266877f5
2,304
cc
C++
src/RequestRawReader.cc
AmiraLearning/asr-server
d551d7a471300360a846009a31852662d0ba7b23
[ "Apache-2.0" ]
143
2017-10-15T00:21:50.000Z
2022-03-24T13:37:12.000Z
src/RequestRawReader.cc
AmiraLearning/asr-server
d551d7a471300360a846009a31852662d0ba7b23
[ "Apache-2.0" ]
33
2017-11-02T20:03:15.000Z
2021-12-29T09:41:11.000Z
src/RequestRawReader.cc
AmiraLearning/asr-server
d551d7a471300360a846009a31852662d0ba7b23
[ "Apache-2.0" ]
75
2017-11-04T19:58:29.000Z
2022-03-24T13:37:01.000Z
// RequestRawReader.cc // 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 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #include "RequestRawReader.h" #include "Timing.h" #include <algorithm> namespace apiai { const milliseconds_t data_wait_interval_ms = 500; kaldi::SubVector<kaldi::BaseFloat> *RequestRawReader::NextChunk(kaldi::int32 samples_count) { return NextChunk(samples_count, 0); } kaldi::SubVector<kaldi::BaseFloat> *RequestRawReader::NextChunk(kaldi::int32 samples_count, kaldi::int32 timeout_ms) { // TODO: timeout_ms is not supported because libfcgi do not provides "readsome" functionality if (samples_count <= 0) { return NULL; } if (fail_) { return NULL; } int frame_size = bytes_per_sample_ * channels_; kaldi::int32 chunk_size = samples_count * frame_size; int offset = channel_index_ * bytes_per_sample_; std::vector<char> audioData(chunk_size); int bytes_read = 0; is_->read(audioData.data(), chunk_size); bytes_read = is_->gcount(); if (is_->gcount() == 0) { fail_ = true; last_error_message_ == "Failed to read any data"; return NULL; } buffer_.clear(); for (int index = 0; index < bytes_read; index += frame_size) { kaldi::int16 value = *reinterpret_cast<kaldi::int16*>(audioData.data() + index + offset); kaldi::BaseFloat fvalue = kaldi::BaseFloat(value); buffer_.push_back(fvalue); } if (current_chunk_ && (current_chunk_->Dim() != buffer_.size())) { delete current_chunk_; current_chunk_ = NULL; } if (!current_chunk_) { current_chunk_ = new kaldi::SubVector<kaldi::BaseFloat>(buffer_.data(), buffer_.size()); } else { KALDI_ASSERT(buffer_.size() == current_chunk_->Dim()); std::copy(buffer_.begin(), buffer_.end(), current_chunk_->Data()); } return current_chunk_; } } /* namespace apiai */
28.097561
118
0.72526
[ "vector" ]
b682035c3ff00e9b2b08c7946d8efe7022dbbf16
1,789
cpp
C++
data/dailyCodingProblem912.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
2
2020-09-04T20:56:23.000Z
2021-06-11T07:42:26.000Z
data/dailyCodingProblem912.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
null
null
null
data/dailyCodingProblem912.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; /* Two nodes in a binary tree can be called cousins if they are on the same level of the tree but have different parents. For example, in the following diagram 4 and 6 are cousins. 1 / \ 2 3 / \ \ 4 5 6 Given a binary tree and a particular node, find all cousins of that node. */ struct node{ int data; node *left, *right; }; node* newNode(int data){ auto root = new node; root->data = data; root->left = root->right = nullptr; return root; } void printInorder(node* root){ if(root){ printInorder(root->left); cout << root->data << " "; printInorder(root->right); } } vector<node*> cousionsNode(node* root, node* nd){ if(nd == nullptr || root == nd) return {}; bool found = false; vector<node*> ans; queue<node*> q({root}); while(!q.empty()){ int size = q.size(); while(size--){ auto f = q.front(); q.pop(); if(f->left == nd || f->right == nd){ found = true; } else { if(f->left) q.push(f->left); if(f->right) q.push(f->right); } } if(found){ while(!q.empty()){ ans.push_back(q.front()); q.pop(); } break; } } return ans; } // main function int main(){ auto root = newNode(1); root->left = newNode(2); root->left->left = newNode(4); root->left->right = newNode(5); root->right = newNode(3); root->right->right = newNode(6); printInorder(root); cout << "\n"; for(auto nd : cousionsNode(root, root->right->right)){ cout << nd->data << "\n"; } return 0; }
20.101124
66
0.505869
[ "vector" ]
b689d3a31075e8d1f7b6485f85d7853db3f284bb
1,422
cpp
C++
codeforces/787/B.cpp
metaflow/contests
5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2
[ "MIT" ]
1
2019-05-12T23:41:00.000Z
2019-05-12T23:41:00.000Z
codeforces/787/B.cpp
metaflow/contests
5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2
[ "MIT" ]
null
null
null
codeforces/787/B.cpp
metaflow/contests
5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using vi = vector<int>; using vvi = vector<vi>; using ii = pair<int,int>; using vii = vector<ii>; using l = long long; using vl = vector<l>; using vvl = vector<vl>; using ll = pair<l,l>; using vll = vector<ll>; using vvll = vector<vll>; using lu = unsigned long long; using vb = vector<bool>; using vvb = vector<vb>; using vd = vector<double>; using vvd = vector<vd>; const int INF = numeric_limits<int>::max(); const double EPS = 1e-10; const l e0=1, e3=1000, e5=100000, e6=e3*e3, e7=10*e6, e8=10*e7, e9=10*e8; #define ALL(x) begin(x), end(x) #define F(a,b,c) for (l a = l(b); a < l(c); a++) #define B(a,b,c) for (l a = l(b); a > l(c); a--) // #define ONLINE_JUDGE #if defined ONLINE_JUDGE const bool enable_log = false; #else const bool enable_log = true; #endif struct VoidStream { void operator&(std::ostream&) { } }; #define LOG !(enable_log) ? (void) 0 : VoidStream() & cerr int main() { ios_base::sync_with_stdio(false); cin.tie(0); l n, m; while (cin >> n >> m) { bool doomed = false; F(i, 0, m) { vb g(n * 2 + 1); l k; cin >> k; bool f = true; F(j, 0, k) { l x; cin >> x; x *= 2; if (x < 0) x = -x - 1; g[x] = true; if (g[x - 1 + 2 * (x % 2)]) f = false; } doomed = doomed or f; } if (doomed) { cout << "YES\n"; } else { cout << "NO\n"; } } }
26.830189
73
0.552039
[ "vector" ]
b694bfc2c6583efd497d3a11ab87a8591138b653
606
cpp
C++
PAT (Advanced Level) Practice/1009 Product of Polynomials (25).cpp
vuzway/PAT
5db8ca9295b51ad9e99c815a46e4ac764d7d06c1
[ "MIT" ]
5
2020-02-10T08:26:19.000Z
2020-07-09T00:11:16.000Z
PAT (Advanced Level) Practice/1009 Product of Polynomials (25).cpp
Assassin2016/zju_data_structures_and_algorithms_in_MOOC
5db8ca9295b51ad9e99c815a46e4ac764d7d06c1
[ "MIT" ]
null
null
null
PAT (Advanced Level) Practice/1009 Product of Polynomials (25).cpp
Assassin2016/zju_data_structures_and_algorithms_in_MOOC
5db8ca9295b51ad9e99c815a46e4ac764d7d06c1
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; double a[1010], b[2020]; int main() { int k1, k2, e, cnt = 0; double c; cin >> k1; for (int i = 0; i < k1; i++) { scanf("%d%lf", &e, &c); a[e] += c; } cin >> k2; for (int i = 0; i < k2; i++) { scanf("%d%lf", &e, &c); for (int j = 0; j < 1010; j++) if (a[j] != 0) b[e+j] += a[j] * c; } vector<pair<int, double>> v; for (int i = 2019; i >= 0; i--) if (b[i] != 0) { cnt++; v.push_back({i, b[i]}); } printf("%d", cnt); for (int i = 0; i < v.size(); i++) printf(" %d %.1f", v[i].first, v[i].second); return 0; }
19.548387
46
0.462046
[ "vector" ]
b696a5255c38f223a31553bbd936424333c8fe9e
47,927
cpp
C++
dali-toolkit/internal/controls/buttons/button-impl.cpp
zyndor/dali-toolkit
9e3fd659c4d25706ab65345bc7c562ac27248325
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
dali-toolkit/internal/controls/buttons/button-impl.cpp
zyndor/dali-toolkit
9e3fd659c4d25706ab65345bc7c562ac27248325
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
dali-toolkit/internal/controls/buttons/button-impl.cpp
zyndor/dali-toolkit
9e3fd659c4d25706ab65345bc7c562ac27248325
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2020 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // CLASS HEADER #include "button-impl.h" // EXTERNAL INCLUDES #include <cstring> // for strcmp #include <dali/devel-api/scripting/enum-helper.h> #include <dali/integration-api/debug.h> #include <dali/public-api/events/touch-event.h> #include <dali/public-api/object/type-registry.h> #include <dali/public-api/object/type-registry-helper.h> #include <dali/public-api/size-negotiation/relayout-container.h> #include <dali/devel-api/object/property-helper-devel.h> #include <dali/devel-api/scripting/scripting.h> // INTERNAL INCLUDES #include <dali-toolkit/public-api/controls/text-controls/text-label.h> #include <dali-toolkit/public-api/controls/image-view/image-view.h> #include <dali-toolkit/public-api/visuals/color-visual-properties.h> #include <dali-toolkit/public-api/visuals/image-visual-properties.h> #include <dali-toolkit/public-api/align-enumerations.h> #include <dali-toolkit/devel-api/controls/control-depth-index-ranges.h> #include <dali-toolkit/devel-api/controls/control-devel.h> #include <dali-toolkit/devel-api/controls/buttons/button-devel.h> #include <dali-toolkit/devel-api/visual-factory/visual-factory.h> #include <dali-toolkit/internal/visuals/text/text-visual.h> #include <dali-toolkit/public-api/visuals/text-visual-properties.h> #include <dali-toolkit/public-api/visuals/visual-properties.h> #if defined(DEBUG_ENABLED) Debug::Filter* gLogButtonFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_BUTTON_CONTROL"); #endif namespace Dali { namespace Toolkit { namespace Internal { namespace { BaseHandle Create() { // empty handle as we cannot create button (but type registered for clicked signal) return BaseHandle(); } // Setup properties, signals and actions using the type-registry. DALI_TYPE_REGISTRATION_BEGIN( Toolkit::Button, Toolkit::Control, Create ) DALI_PROPERTY_REGISTRATION( Toolkit, Button, "disabled", BOOLEAN, DISABLED ) DALI_PROPERTY_REGISTRATION( Toolkit, Button, "autoRepeating", BOOLEAN, AUTO_REPEATING ) DALI_PROPERTY_REGISTRATION( Toolkit, Button, "initialAutoRepeatingDelay", FLOAT, INITIAL_AUTO_REPEATING_DELAY ) DALI_PROPERTY_REGISTRATION( Toolkit, Button, "nextAutoRepeatingDelay", FLOAT, NEXT_AUTO_REPEATING_DELAY ) DALI_PROPERTY_REGISTRATION( Toolkit, Button, "togglable", BOOLEAN, TOGGLABLE ) DALI_PROPERTY_REGISTRATION( Toolkit, Button, "selected", BOOLEAN, SELECTED ) DALI_PROPERTY_REGISTRATION( Toolkit, Button, "unselectedVisual", MAP, UNSELECTED_VISUAL ) DALI_PROPERTY_REGISTRATION( Toolkit, Button, "selectedVisual", MAP, SELECTED_VISUAL ) DALI_PROPERTY_REGISTRATION( Toolkit, Button, "disabledSelectedVisual", MAP, DISABLED_SELECTED_VISUAL ) DALI_PROPERTY_REGISTRATION( Toolkit, Button, "disabledUnselectedVisual", MAP, DISABLED_UNSELECTED_VISUAL ) DALI_PROPERTY_REGISTRATION( Toolkit, Button, "unselectedBackgroundVisual", MAP, UNSELECTED_BACKGROUND_VISUAL ) DALI_PROPERTY_REGISTRATION( Toolkit, Button, "label", MAP, LABEL ) DALI_PROPERTY_REGISTRATION( Toolkit, Button, "selectedBackgroundVisual", MAP, SELECTED_BACKGROUND_VISUAL ) DALI_PROPERTY_REGISTRATION( Toolkit, Button, "disabledUnselectedBackgroundVisual", MAP, DISABLED_UNSELECTED_BACKGROUND_VISUAL ) DALI_PROPERTY_REGISTRATION( Toolkit, Button, "disabledSelectedBackgroundVisual", MAP, DISABLED_SELECTED_BACKGROUND_VISUAL ) DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, Button, "labelRelativeAlignment", STRING, LABEL_RELATIVE_ALIGNMENT ) DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, Button, "labelPadding", VECTOR4, LABEL_PADDING ) DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, Button, "visualPadding", VECTOR4, VISUAL_PADDING ) // Signals: DALI_SIGNAL_REGISTRATION( Toolkit, Button, "pressed", SIGNAL_PRESSED ) DALI_SIGNAL_REGISTRATION( Toolkit, Button, "released", SIGNAL_RELEASED ) DALI_SIGNAL_REGISTRATION( Toolkit, Button, "clicked", SIGNAL_CLICKED ) DALI_SIGNAL_REGISTRATION( Toolkit, Button, "stateChanged", SIGNAL_STATE_CHANGED ) // Actions: DALI_ACTION_REGISTRATION( Toolkit, Button, "buttonClick", ACTION_BUTTON_CLICK ) DALI_TYPE_REGISTRATION_END() DALI_ENUM_TO_STRING_TABLE_BEGIN( ALIGNMENT ) DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Internal::Button, BEGIN ) DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Internal::Button, END ) DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Internal::Button, TOP ) DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Internal::Button, BOTTOM ) DALI_ENUM_TO_STRING_TABLE_END( ALIGNMENT ) const Scripting::StringEnum ALIGNMENT_STRING_TABLE[] = { { "BEGIN", Button::BEGIN }, { "END", Button::END }, { "TOP", Button::TOP }, { "BOTTOM", Button::BOTTOM }, }; const unsigned int ALIGNMENT_STRING_TABLE_COUNT = sizeof( ALIGNMENT_STRING_TABLE ) / sizeof( ALIGNMENT_STRING_TABLE[0] ); const Property::Index VISUAL_INDEX_FOR_STATE[][Button::STATE_COUNT] = { { Toolkit::Button::Property::UNSELECTED_BACKGROUND_VISUAL, Toolkit::Button::Property::UNSELECTED_VISUAL }, { Toolkit::Button::Property::SELECTED_BACKGROUND_VISUAL, Toolkit::Button::Property::SELECTED_VISUAL }, { Toolkit::Button::Property::DISABLED_UNSELECTED_BACKGROUND_VISUAL, Toolkit::Button::Property::DISABLED_UNSELECTED_VISUAL }, { Toolkit::Button::Property::DISABLED_SELECTED_BACKGROUND_VISUAL, Toolkit::Button::Property::DISABLED_SELECTED_VISUAL } }; /** * Checks if given map contains a text string */ bool MapContainsTextString( Property::Map& map ) { bool result = false; Property::Value* value = map.Find( Toolkit::TextVisual::Property::TEXT ); if ( value ) { std::string textString; value->Get( textString ); if ( !textString.empty() ) { result = true; } } return result; } } // unnamed namespace Button::Button() : Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ), mAutoRepeatingTimer(), mTextLabelAlignment( END ), mAutoRepeating( false ), mTogglableButton( false ), mTextStringSetFlag( false ), mInitialAutoRepeatingDelay( 0.0f ), mNextAutoRepeatingDelay( 0.0f ), mAnimationTime( 0.0f ), mButtonPressedState( UNPRESSED ), mButtonState( UNSELECTED_STATE ), mPreviousButtonState( mButtonState ), mClickActionPerforming( false ) { } Button::~Button() { } void Button::SetAutoRepeating( bool autoRepeating ) { mAutoRepeating = autoRepeating; // An autorepeating button can't be a toggle button. if( autoRepeating ) { if( IsSelected() ) { SetSelected( false ); // UnSelect before switching off Toggle feature. } mTogglableButton = false; } } void Button::SetInitialAutoRepeatingDelay( float initialAutoRepeatingDelay ) { DALI_ASSERT_DEBUG( initialAutoRepeatingDelay > 0.f ); mInitialAutoRepeatingDelay = initialAutoRepeatingDelay; } void Button::SetNextAutoRepeatingDelay( float nextAutoRepeatingDelay ) { DALI_ASSERT_DEBUG( nextAutoRepeatingDelay > 0.f ); mNextAutoRepeatingDelay = nextAutoRepeatingDelay; } void Button::SetTogglableButton( bool togglable ) { mTogglableButton = togglable; // A toggle button can't be an autorepeating button. if( togglable ) { mAutoRepeating = false; } } void Button::SetSelected( bool selected ) { if( mTogglableButton ) { DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::SetSelected (%s)\n", (selected?"true":"false") ); if ( selected && ( mButtonState != SELECTED_STATE ) ) { ChangeState( SELECTED_STATE ); } else if ( !selected && ( mButtonState != UNSELECTED_STATE ) ) { ChangeState( UNSELECTED_STATE ); } } } void Button::SetDisabled( bool disabled ) { DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::SetDisabled(%s) state(%d)\n", (disabled)?"disabled":"active", mButtonState ); if ( disabled ) { if ( mButtonState == SELECTED_STATE ) { ChangeState( DISABLED_SELECTED_STATE ); } else if ( mButtonState == UNSELECTED_STATE ) { ChangeState( DISABLED_UNSELECTED_STATE ); } } else { if ( mButtonState == DISABLED_SELECTED_STATE ) { ChangeState( SELECTED_STATE ); } else if ( mButtonState == DISABLED_UNSELECTED_STATE ) { ChangeState( UNSELECTED_STATE ); } } } bool Button::IsDisabled() const { return ( mButtonState == DISABLED_SELECTED_STATE || mButtonState == DISABLED_UNSELECTED_STATE ) ; } bool Button::ValidateState( State requestedState ) { /* Below tables shows allowed state transitions * Match rows in first column to following columns, if true then transition allowed. * eg UNSELECTED_STATE to DISABLED_UNSELECTED_STATE is true so state transition allowed. * to| UNSELECTED_STATE | SELECTED_STATE | DISABLED_UNSELECTED_STATE | DISABLED_SELECTED_STATE |*/ /* from*/ bool transitionTable[4][4] = { /* UNSELECTED_STATE*/ { false, true, true, false }, /* SELECTED_STATE*/ { true, false, false, true }, /* DISABLED_UNSELECTED_STATE*/{ true, true, false, false }, /* DISABLED_SELECTED_STATE*/ { false, true, false, false } }; DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::ValidateState ReuestedState:%d, CurrentState:%d, result:%s\n", requestedState, mButtonState, (transitionTable[mButtonState][requestedState])?"change-accepted":"change-denied"); return transitionTable[mButtonState][requestedState]; } void Button::ChangeState( State requestedState ) { DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::ChangeState ReuestedState(%d)\n", requestedState ); // Validate State before changing if ( !ValidateState( requestedState )) { DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::ChangeState ReuestedState(%d) not validated\n", requestedState ); return; } // If not on stage the button could have still been set to selected so update state mPreviousButtonState = mButtonState; // Store previous state for visual removal (used when animations ended) mButtonState = requestedState; // Update current state if ( Self().GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ) ) { OnStateChange( mButtonState ); // Notify derived buttons SelectRequiredVisual( VISUAL_INDEX_FOR_STATE[ mButtonState ][ BACKGROUND ] ); SelectRequiredVisual( VISUAL_INDEX_FOR_STATE[ mButtonState ][ FOREGROUND ] ); // If animation supported then visual removal should be performed after any transition animation has completed. // If Required Visual is not loaded before current visual is removed then a flickering will be evident. // Derived button can override OnButtonVisualRemoval OnButtonVisualRemoval( VISUAL_INDEX_FOR_STATE[ mPreviousButtonState ][ BACKGROUND ] ); OnButtonVisualRemoval( VISUAL_INDEX_FOR_STATE[ mPreviousButtonState ][ FOREGROUND ] ); RelayoutRequest(); } Toolkit::Button handle( GetOwner() ); // Emit signal. mStateChangedSignal.Emit( handle ); } bool Button::IsSelected() const { bool selected = ( mButtonState == SELECTED_STATE ) || ( mButtonState == DISABLED_SELECTED_STATE ); return mTogglableButton && selected; } void Button::MergeWithExistingLabelProperties( const Property::Map& inMap, Property::Map& outMap ) { DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "MergeLabelProperties with %d properties\n", inMap.Count() ); /** * Properties for the Label visual could be from a style sheet but after being set the "TEXT" property could be set. * Hence would need to create the Text Visual with the complete merged set of properties. * * 1) Find Label Visual * 2) Retrieve current properties ( settings ) * 3) Merge with new properties ( settings ) * 4) Return new merged map */ Toolkit::Visual::Base visual = DevelControl::GetVisual( *this, Toolkit::Button::Property::LABEL ); if ( visual ) { DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "MergeLabelProperties Visual already exists, retrieving existing map\n"); visual.CreatePropertyMap( outMap ); DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "MergeLabelProperties retrieved %d properties\n", outMap.Count() ); } outMap.Merge( inMap ); // Store if a text string has been supplied. mTextStringSetFlag = MapContainsTextString( outMap ); DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "MergeLabelProperties now has %d properties\n", outMap.Count() ); } void Button::SetLabelAlignment( Button::Align labelAlignment) { mTextLabelAlignment = labelAlignment; RelayoutRequest(); } Button::Align Button::GetLabelAlignment() { return mTextLabelAlignment; } /** * Create Visual for given index from a property map or url. * 1) Check if value passed in is a url and create visual * 2) Create visual from map if step (1) is false * 3) Register visual with control with false for enable flag. Button will later enable visual when needed ( Button::SelectRequiredVisual ) * 4) Unregister visual if empty map was provided. This is the method to remove a visual */ void Button::CreateVisualsForComponent( Property::Index index, const Property::Value& value, const int visualDepth ) { DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "CreateVisualsForComponent index(%d)\n", index ); Toolkit::VisualFactory visualFactory = Toolkit::VisualFactory::Get(); Toolkit::Visual::Base buttonVisual; std::string imageUrl; if( value.Get( imageUrl ) ) { DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "CreateVisualsForComponent Using image URL(%d)\n", index ); if ( !imageUrl.empty() ) { DALI_ASSERT_DEBUG( index != Toolkit::Button::Property::LABEL && "Creating a Image Visual instead of Text Visual " ); buttonVisual = visualFactory.CreateVisual( imageUrl, ImageDimensions() ); } } else { // if its not a string then get a Property::Map from the property if possible. const Property::Map *map = value.GetMap(); if( map && !map->Empty() ) // Empty map results in current visual removal. { DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "CreateVisualsForComponent Using Map(%d)\n", index ); buttonVisual = visualFactory.CreateVisual( *map ); } } if ( buttonVisual ) { DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "CreateVisualsForComponent RegisterVisual index(%d) enabled(%s)\n", index, DevelControl::IsVisualEnabled( *this, index )?"true":"false" ); // enable the visual if needed for current state const bool enabled = ( ( index == VISUAL_INDEX_FOR_STATE[ mButtonState ][ BACKGROUND ] )|| ( index == VISUAL_INDEX_FOR_STATE[ mButtonState ][ FOREGROUND ] )|| ( index == Toolkit::Button::Property::LABEL ) ); DevelControl::RegisterVisual( *this, index, buttonVisual, enabled, visualDepth ); } else { DevelControl::UnregisterVisual( *this, index ); DALI_LOG_INFO( gLogButtonFilter, Debug::General, "CreateVisualsForComponent Visual not created or empty map (clearing visual).(%d)\n", index); } RelayoutRequest(); } bool Button::GetPropertyMapForVisual( Property::Index visualIndex, Property::Map& retreivedMap ) const { DALI_LOG_INFO( gLogButtonFilter, Debug::General, "GetPropertyMapForVisual visual(%d)\n", visualIndex); bool success = false; Toolkit::Visual::Base visual = DevelControl::GetVisual( *this, visualIndex ); if ( visual ) { visual.CreatePropertyMap( retreivedMap ); success = true; } DALI_LOG_INFO( gLogButtonFilter, Debug::General, "GetPropertyMapForVisual %s\n", success?"Success":"Failure"); return success; } bool Button::DoAction( BaseObject* object, const std::string& actionName, const Property::Map& attributes ) { bool ret = false; Dali::BaseHandle handle( object ); Toolkit::Button button = Toolkit::Button::DownCast( handle ); DALI_ASSERT_DEBUG( button ); if( 0 == strcmp( actionName.c_str(), ACTION_BUTTON_CLICK ) ) { ret = GetImplementation( button ).DoClickAction( attributes ); } return ret; } bool Button::DoClickAction( const Property::Map& attributes ) { // Prevents the button signals from doing a recursive loop by sending an action // and re-emitting the signals. if( !mClickActionPerforming ) { mClickActionPerforming = true; ButtonDown(); if ( !mTogglableButton ) { mButtonPressedState = DEPRESSED; } ButtonUp(); mClickActionPerforming = false; return true; } return false; } void Button::ButtonDown() { if( mTogglableButton ) { if ( mButtonState != SELECTED_STATE ) { SetSelected( true ); mButtonPressedState = TOGGLE_DEPRESSED; } else { mButtonPressedState = DEPRESSED; } } else { Pressed(); mButtonPressedState = DEPRESSED; if( mAutoRepeating ) { SetUpTimer( mInitialAutoRepeatingDelay ); } } // The pressed signal should be emitted regardless of toggle mode. Toolkit::Button handle( GetOwner() ); mPressedSignal.Emit( handle ); } void Button::ButtonUp() { bool emitSignalsForPressAndReleaseAction = false; if( DEPRESSED == mButtonPressedState ) { if( mTogglableButton ) // Button up will change state { emitSignalsForPressAndReleaseAction = OnToggleReleased(); // Derived toggle buttons can override this to provide custom behaviour } else { Released(); // Button up will result in unselected state if( mAutoRepeating ) { mAutoRepeatingTimer.Reset(); } emitSignalsForPressAndReleaseAction = true; } } else if ( TOGGLE_DEPRESSED == mButtonPressedState ) { emitSignalsForPressAndReleaseAction = true; // toggle released after being pressed, a click } if ( emitSignalsForPressAndReleaseAction ) { // The clicked and released signals should be emitted regardless of toggle mode. Toolkit::Button handle( GetOwner() ); mReleasedSignal.Emit( handle ); mClickedSignal.Emit( handle ); } } bool Button::OnToggleReleased() { SetSelected( !IsSelected() ); mButtonPressedState = UNPRESSED; return true; } void Button::OnTouchPointLeave() { if( DEPRESSED == mButtonPressedState ) { if( !mTogglableButton ) { Released(); if( mAutoRepeating ) { mAutoRepeatingTimer.Reset(); } } mButtonPressedState = UNPRESSED; // The released signal should be emitted regardless of toggle mode. Toolkit::Button handle( GetOwner() ); mReleasedSignal.Emit( handle ); } } void Button::OnTouchPointInterrupted() { OnTouchPointLeave(); } Toolkit::Button::ButtonSignalType& Button::PressedSignal() { return mPressedSignal; } Toolkit::Button::ButtonSignalType& Button::ReleasedSignal() { return mReleasedSignal; } Toolkit::Button::ButtonSignalType& Button::ClickedSignal() { return mClickedSignal; } Toolkit::Button::ButtonSignalType& Button::StateChangedSignal() { return mStateChangedSignal; } bool Button::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor ) { Dali::BaseHandle handle( object ); bool connected( true ); Toolkit::Button button = Toolkit::Button::DownCast( handle ); if( 0 == strcmp( signalName.c_str(), SIGNAL_PRESSED ) ) { button.PressedSignal().Connect( tracker, functor ); } else if( 0 == strcmp( signalName.c_str(), SIGNAL_RELEASED ) ) { button.ReleasedSignal().Connect( tracker, functor ); } else if( 0 == strcmp( signalName.c_str(), SIGNAL_CLICKED ) ) { button.ClickedSignal().Connect( tracker, functor ); } else if( 0 == strcmp( signalName.c_str(), SIGNAL_STATE_CHANGED ) ) { button.StateChangedSignal().Connect( tracker, functor ); } else { // signalName does not match any signal connected = false; } return connected; } void Button::OnInitialize() { DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::OnInitialize\n" ); Actor self = Self(); mTapDetector = TapGestureDetector::New(); mTapDetector.Attach( self ); mTapDetector.DetectedSignal().Connect(this, &Button::OnTap); self.SetProperty( Actor::Property::KEYBOARD_FOCUSABLE, true ); self.SetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true ); self.TouchedSignal().Connect( this, &Button::OnTouch ); } bool Button::OnAccessibilityActivated() { return OnKeyboardEnter(); } bool Button::OnTouch( Actor actor, const TouchEvent& touch ) { if( !IsDisabled() && (actor == touch.GetHitActor(0)) ) { if ( 1 == touch.GetPointCount() ) { switch( touch.GetState( 0 ) ) { case PointState::DOWN: { ButtonDown(); break; } case PointState::UP: { ButtonUp(); break; } case PointState::INTERRUPTED: { OnTouchPointInterrupted(); break; } case PointState::LEAVE: { OnTouchPointLeave(); break; } case PointState::MOTION: case PointState::STATIONARY: // FALLTHROUGH { // Nothing to do break; } } } else if( 1 < touch.GetPointCount() ) { OnTouchPointLeave(); // Notification for derived classes. // Sets the button state to the default mButtonPressedState = UNPRESSED; } } return false; } bool Button::OnKeyboardEnter() { // When the enter key is pressed, or button is activated, the click action is performed. Property::Map attributes; bool ret = DoClickAction( attributes ); return ret; } void Button::OnSceneDisconnection() { if( DEPRESSED == mButtonPressedState ) { if( !mTogglableButton ) { Released(); if( mAutoRepeating ) { mAutoRepeatingTimer.Reset(); } } } mButtonPressedState = UNPRESSED; Control::OnSceneDisconnection(); // Visuals will be set off stage } void Button::OnSceneConnection( int depth ) { DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::OnSceneConnection ptr(%p) \n", this ); OnButtonVisualRemoval( VISUAL_INDEX_FOR_STATE[ mPreviousButtonState ][ BACKGROUND ] ); OnButtonVisualRemoval( VISUAL_INDEX_FOR_STATE[ mPreviousButtonState ][ FOREGROUND ] ); SelectRequiredVisual( Toolkit::Button::Property::LABEL ); SelectRequiredVisual( VISUAL_INDEX_FOR_STATE[ mButtonState ][ BACKGROUND ] ); SelectRequiredVisual( VISUAL_INDEX_FOR_STATE[ mButtonState ][ FOREGROUND ] ); Control::OnSceneConnection( depth ); // Enabled visuals will be put on stage RelayoutRequest(); } Vector3 Button::GetNaturalSize() { Vector3 size = Vector3::ZERO; bool horizontalAlignment = mTextLabelAlignment == BEGIN || mTextLabelAlignment == END; // label and visual side by side // Get natural size of foreground ( largest of the possible visuals ) Size largestProvidedVisual; Size labelSize = Size::ZERO; bool foreGroundVisualUsed = false; for ( int state = Button::UNSELECTED_STATE; state < Button::STATE_COUNT; state++ ) { Toolkit::Visual::Base visual = DevelControl::GetVisual( *this, VISUAL_INDEX_FOR_STATE[state][FOREGROUND] ); Size visualSize; if ( visual ) { visual.GetNaturalSize( visualSize ); largestProvidedVisual.width = std::max(largestProvidedVisual.width, visualSize.width ); largestProvidedVisual.height = std::max(largestProvidedVisual.height, visualSize.height ); foreGroundVisualUsed = true; } } if ( !foreGroundVisualUsed ) // If foreground visual not supplied then use the background visual to calculate Natural size { for ( int state = Button::UNSELECTED_STATE; state < Button::STATE_COUNT; state++ ) { Toolkit::Visual::Base visual = DevelControl::GetVisual( *this, VISUAL_INDEX_FOR_STATE[state][BACKGROUND] ); Size visualSize; if ( visual ) { visual.GetNaturalSize( visualSize ); largestProvidedVisual.width = std::max(largestProvidedVisual.width, visualSize.width ); largestProvidedVisual.height = std::max(largestProvidedVisual.height, visualSize.height ); } } } // Get horizontal padding total if ( largestProvidedVisual.width > 0 ) // if visual exists { size.width += largestProvidedVisual.width + mForegroundPadding.left + mForegroundPadding.right; } // Get vertical padding total if ( largestProvidedVisual.height > 0 ) { size.height += largestProvidedVisual.height + mForegroundPadding.top + mForegroundPadding.bottom; } DALI_LOG_INFO( gLogButtonFilter, Debug::General, "GetNaturalSize visual Size(%f,%f)\n", largestProvidedVisual.width, largestProvidedVisual.height ); // Get natural size of label if text has been set if ( mTextStringSetFlag ) { Toolkit::Visual::Base visual = DevelControl::GetVisual( *this, Toolkit::Button::Property::LABEL ); if ( visual ) { visual.GetNaturalSize( labelSize ); DALI_LOG_INFO( gLogButtonFilter, Debug::General, "GetNaturalSize labelSize(%f,%f) padding(%f,%f)\n", labelSize.width, labelSize.height, mLabelPadding.left + mLabelPadding.right, mLabelPadding.top + mLabelPadding.bottom); labelSize.width += mLabelPadding.left + mLabelPadding.right; labelSize.height += mLabelPadding.top + mLabelPadding.bottom; // Add label size to height or width depending on alignment position if ( horizontalAlignment ) { size.width += labelSize.width; size.height = std::max(size.height, labelSize.height ); } else { size.height += labelSize.height; size.width = std::max(size.width, labelSize.width ); } } } if( size.width < 1 && size.height < 1 ) { // if no image or label then use Control's natural size DALI_LOG_INFO( gLogButtonFilter, Debug::General, "GetNaturalSize Using control natural size\n"); size = Control::GetNaturalSize(); } DALI_LOG_INFO( gLogButtonFilter, Debug::General, "Button GetNaturalSize (%f,%f)\n", size.width, size.height ); return size; } void Button::OnSetResizePolicy( ResizePolicy::Type policy, Dimension::Type dimension ) { DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnSetResizePolicy\n"); RelayoutRequest(); } /** * Visuals are sized and positioned in this function. * Whilst the control has it's size negotiated it has to size it's visuals explicitly here. */ void Button::OnRelayout( const Vector2& size, RelayoutContainer& container ) { DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnRelayout targetSize(%f,%f) ptr(%p) state[%d]\n", size.width, size.height, this, mButtonState ); Toolkit::Visual::Base currentVisual = DevelControl::GetVisual( *this, VISUAL_INDEX_FOR_STATE[mButtonState][FOREGROUND] ); Toolkit::Visual::Base currentBackGroundVisual = DevelControl::GetVisual( *this, VISUAL_INDEX_FOR_STATE[mButtonState][BACKGROUND] ); // Sizes and padding set to zero, if not present then values will no effect calculations. Vector2 visualPosition = Vector2::ZERO; Vector2 labelPosition = Vector2::ZERO; Size visualSize = Size::ZERO; Padding foregroundVisualPadding = Padding(0.0f, 0.0f, 0.0f, 0.0f ); Padding labelVisualPadding = Padding(0.0f, 0.0f, 0.0f, 0.0f ); if ( mTextStringSetFlag ) { DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnRelayout Label padding setting padding:%f,%f,%f,%f\n", mLabelPadding.y, mLabelPadding.x, mLabelPadding.width,mLabelPadding.height ); labelVisualPadding = mLabelPadding; } if ( currentVisual ) { DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnRelayout Foreground Visual setting padding:%f,%f,%f,%f\n", mForegroundPadding.y, mForegroundPadding.x, mForegroundPadding.width,mForegroundPadding.height ); currentVisual.GetNaturalSize( visualSize ); foregroundVisualPadding = mForegroundPadding; } Toolkit::Align::Type visualAnchorPoint = Toolkit::Align::TOP_BEGIN; Vector2 visualAndPaddingSize = Vector2( ( foregroundVisualPadding.x + visualSize.width + foregroundVisualPadding.y ), ( foregroundVisualPadding.width + visualSize.height + foregroundVisualPadding.height )); DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnRelayout visualAndPaddingSize(%f,%f)\n", visualAndPaddingSize.width, visualAndPaddingSize.height); // Text Visual should take all space available after foreground visual size and all padding is considered. // Remaining Space priority, Foreground padding, foreground visual, Text padding then Text visual. Size remainingSpaceForText = Size::ZERO; switch ( mTextLabelAlignment ) { case BEGIN : { visualAnchorPoint = Toolkit::Align::TOP_END; visualPosition.x = foregroundVisualPadding.right; visualPosition.y = foregroundVisualPadding.top; labelPosition.x = labelVisualPadding.x; labelPosition.y = labelVisualPadding.top; remainingSpaceForText.width = size.width - visualAndPaddingSize.width - labelVisualPadding.x - labelVisualPadding.y; remainingSpaceForText.height = size.height - labelVisualPadding.top - labelVisualPadding.bottom; break; } case END : { visualAnchorPoint = Toolkit::Align::TOP_BEGIN; visualPosition.x = foregroundVisualPadding.left; visualPosition.y = foregroundVisualPadding.top; labelPosition.x = visualAndPaddingSize.width + labelVisualPadding.x; labelPosition.y = labelVisualPadding.top; remainingSpaceForText.width = size.width - visualAndPaddingSize.width - labelVisualPadding.x - labelVisualPadding.y; remainingSpaceForText.height = size.height - labelVisualPadding.top - labelVisualPadding.bottom; break; } case TOP : { visualAnchorPoint = Toolkit::Align::BOTTOM_END; visualPosition.x = foregroundVisualPadding.left; visualPosition.y = foregroundVisualPadding.bottom; labelPosition.x = labelVisualPadding.left; labelPosition.y = labelVisualPadding.top; remainingSpaceForText.width = size.width - labelVisualPadding.x - labelVisualPadding.y; remainingSpaceForText.height = size.height - visualAndPaddingSize.height - labelVisualPadding.top - labelVisualPadding.bottom; break; } case BOTTOM : { visualAnchorPoint = Toolkit::Align::TOP_END; visualPosition.x = foregroundVisualPadding.left; visualPosition.y = foregroundVisualPadding.top; labelPosition.x = labelVisualPadding.left; labelPosition.y = visualAndPaddingSize.height + labelVisualPadding.top; remainingSpaceForText.width = size.width - labelVisualPadding.x - labelVisualPadding.y; remainingSpaceForText.height = size.height - visualAndPaddingSize.height - labelVisualPadding.top - labelVisualPadding.bottom; break; } } if ( currentBackGroundVisual ) { DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnRelayout Setting visual background size to(%f,%f)\n", size.width, size.height); Property::Map visualTransform; visualTransform.Add( Toolkit::Visual::Transform::Property::SIZE, size ) .Add( Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) ); currentBackGroundVisual.SetTransformAndSize( visualTransform, size ); } if ( currentVisual ) { DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnRelayout Setting visual size to(%f,%f)\n", visualSize.width, visualSize.height); Property::Map visualTransform; visualTransform.Add( Toolkit::Visual::Transform::Property::SIZE, visualSize ) .Add( Toolkit::Visual::Transform::Property::OFFSET, visualPosition ) .Add( Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) ) .Add( Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) ) .Add( Toolkit::Visual::Transform::Property::ORIGIN, Toolkit::Align::TOP_BEGIN ) .Add( Toolkit::Visual::Transform::Property::ANCHOR_POINT, visualAnchorPoint ); currentVisual.SetTransformAndSize( visualTransform, size ); } if ( mTextStringSetFlag ) { Toolkit::Visual::Base textVisual = DevelControl::GetVisual( *this, Toolkit::Button::Property::LABEL ); // No need to search for Label visual if no text set. if ( textVisual ) { if ( !currentVisual ) { DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnRelayout Only Text\n"); labelPosition.x = labelVisualPadding.left; labelPosition.y = labelVisualPadding.height; } Vector2 preSize = Vector2( static_cast< int >( remainingSpaceForText.x ), static_cast< int >( remainingSpaceForText.y )); DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnRelayout text Size(%f,%f) text Position(%f,%f) \n", remainingSpaceForText.width, remainingSpaceForText.height, labelPosition.x, labelPosition.y); DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnRelayout text Size -- (%f,%f) text Position(%f,%f) \n", preSize.width, preSize.height, labelPosition.x, labelPosition.y); Property::Map textVisualTransform; textVisualTransform.Add( Toolkit::Visual::Transform::Property::SIZE, preSize ) .Add( Toolkit::Visual::Transform::Property::OFFSET, labelPosition ) .Add( Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) ) .Add( Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) ) .Add( Toolkit::Visual::Transform::Property::ORIGIN, Toolkit::Align::TOP_BEGIN ) .Add( Toolkit::Visual::Transform::Property::ANCHOR_POINT, visualAnchorPoint ); textVisual.SetTransformAndSize( textVisualTransform, size ); } } DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnRelayout selected (%s) \n", IsSelected()?"yes":"no" ); DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnRelayout << \n"); } void Button::OnTap(Actor actor, const TapGesture& tap) { // Prevents Parent getting a tap event } void Button::SetUpTimer( float delay ) { mAutoRepeatingTimer = Dali::Timer::New( static_cast<unsigned int>( 1000.f * delay ) ); mAutoRepeatingTimer.TickSignal().Connect( this, &Button::AutoRepeatingSlot ); mAutoRepeatingTimer.Start(); } bool Button::AutoRepeatingSlot() { bool consumed = false; if( !IsDisabled() ) { // Restart the autorepeat timer. SetUpTimer( mNextAutoRepeatingDelay ); Pressed(); Toolkit::Button handle( GetOwner() ); //Emit signal. consumed = mReleasedSignal.Emit( handle ); consumed = mClickedSignal.Emit( handle ); consumed |= mPressedSignal.Emit( handle ); } return consumed; } void Button::Pressed() { DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::Pressed\n" ); if( mButtonState == UNSELECTED_STATE ) { ChangeState( SELECTED_STATE ); OnPressed(); // Notifies the derived class the button has been pressed. } } void Button::Released() { DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::Released\n" ); if( mButtonState == SELECTED_STATE && !mTogglableButton ) { ChangeState( UNSELECTED_STATE ); OnReleased(); // // Notifies the derived class the button has been released. } mButtonPressedState = UNPRESSED; } void Button::SelectRequiredVisual( Property::Index visualIndex ) { DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::SelectRequiredVisual index(%d) state(%d)\n", visualIndex, mButtonState ); // only enable visuals that exist if( DevelControl::GetVisual( *this, visualIndex ) ) { DevelControl::EnableVisual( *this, visualIndex, true ); } } void Button::RemoveVisual( Property::Index visualIndex ) { // Use OnButtonVisualRemoval if want button developer to have the option to override removal. DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::RemoveVisual index(%d) state(%d)\n", visualIndex, mButtonState ); Toolkit::Visual::Base visual = DevelControl::GetVisual( *this, visualIndex ); if( visual ) { DevelControl::EnableVisual( *this, visualIndex, false ); } } void Button::OnButtonVisualRemoval( Property::Index visualIndex ) { // Derived Buttons can over ride this to prevent default removal. DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::OnButtonVisualRemoval index(%d)\n", visualIndex ); RemoveVisual( visualIndex ); } void Button::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value ) { Toolkit::Button button = Toolkit::Button::DownCast( Dali::BaseHandle( object ) ); DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::SetProperty index[%d]\n", index ); if ( button ) { switch ( index ) { case Toolkit::Button::Property::DISABLED: { GetImplementation( button ).SetDisabled( value.Get< bool >() ); break; } case Toolkit::Button::Property::AUTO_REPEATING: { GetImplementation( button ).SetAutoRepeating( value.Get< bool >() ); break; } case Toolkit::Button::Property::INITIAL_AUTO_REPEATING_DELAY: { GetImplementation( button ).SetInitialAutoRepeatingDelay( value.Get< float >() ); break; } case Toolkit::Button::Property::NEXT_AUTO_REPEATING_DELAY: { GetImplementation( button ).SetNextAutoRepeatingDelay( value.Get< float >() ); break; } case Toolkit::Button::Property::TOGGLABLE: { GetImplementation( button ).SetTogglableButton( value.Get< bool >() ); break; } case Toolkit::Button::Property::SELECTED: { GetImplementation( button ).SetSelected( value.Get< bool >() ); break; } case Toolkit::Button::Property::UNSELECTED_VISUAL: case Toolkit::Button::Property::SELECTED_VISUAL: case Toolkit::Button::Property::DISABLED_SELECTED_VISUAL: case Toolkit::Button::Property::DISABLED_UNSELECTED_VISUAL: { GetImplementation( button ).CreateVisualsForComponent( index, value, DepthIndex::CONTENT ); break; } case Toolkit::Button::Property::UNSELECTED_BACKGROUND_VISUAL: case Toolkit::Button::Property::SELECTED_BACKGROUND_VISUAL: case Toolkit::Button::Property::DISABLED_SELECTED_BACKGROUND_VISUAL: case Toolkit::Button::Property::DISABLED_UNSELECTED_BACKGROUND_VISUAL: { GetImplementation( button ).CreateVisualsForComponent( index , value, DepthIndex::BACKGROUND); break; } case Toolkit::Button::Property::LABEL: { Property::Map outTextVisualProperties; std::string textString; if ( value.Get( textString ) ) { DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::SetProperty Setting TextVisual with string[%s]\n", textString.c_str() ); Property::Map setPropertyMap; setPropertyMap.Add( Toolkit::Visual::Property::TYPE, Toolkit::Visual::TEXT ) .Add( Toolkit::TextVisual::Property::TEXT, textString ); GetImplementation( button ).MergeWithExistingLabelProperties( setPropertyMap, outTextVisualProperties ); } else { // Get a Property::Map from the property if possible. const Property::Map* setPropertyMap = value.GetMap(); if( setPropertyMap ) { Property::Map indexKeys = TextVisual::ConvertStringKeysToIndexKeys( *setPropertyMap ); GetImplementation( button ).MergeWithExistingLabelProperties( indexKeys, outTextVisualProperties ); } } if( !outTextVisualProperties.Empty() ) { GetImplementation( button ).CreateVisualsForComponent( index, outTextVisualProperties, DepthIndex::CONTENT ); } break; } case Toolkit::DevelButton::Property::LABEL_RELATIVE_ALIGNMENT: { Button::Align labelAlignment(END); Scripting::GetEnumeration< Button::Align> ( value.Get< std::string >().c_str(), ALIGNMENT_TABLE, ALIGNMENT_TABLE_COUNT, labelAlignment ); GetImplementation( button ).SetLabelAlignment( labelAlignment ); break; } case Toolkit::DevelButton::Property::LABEL_PADDING: { Vector4 padding ( value.Get< Vector4 >() ); GetImplementation( button ).SetLabelPadding( Padding( padding.x, padding.y, padding.z, padding.w ) ); break; } case Toolkit::DevelButton::Property::VISUAL_PADDING: { Vector4 padding ( value.Get< Vector4 >() ); GetImplementation( button ).SetForegroundPadding( Padding( padding.x, padding.y, padding.z, padding.w ) ); break; } } } } Property::Value Button::GetProperty( BaseObject* object, Property::Index propertyIndex ) { Property::Value value; Toolkit::Button button = Toolkit::Button::DownCast( Dali::BaseHandle( object ) ); if ( button ) { switch ( propertyIndex ) { case Toolkit::Button::Property::DISABLED: { value = GetImplementation( button ).IsDisabled(); break; } case Toolkit::Button::Property::AUTO_REPEATING: { value = GetImplementation( button ).mAutoRepeating; break; } case Toolkit::Button::Property::INITIAL_AUTO_REPEATING_DELAY: { value = GetImplementation( button ).mInitialAutoRepeatingDelay; break; } case Toolkit::Button::Property::NEXT_AUTO_REPEATING_DELAY: { value = GetImplementation( button ).mNextAutoRepeatingDelay; break; } case Toolkit::Button::Property::TOGGLABLE: { value = GetImplementation( button ).mTogglableButton; break; } case Toolkit::Button::Property::SELECTED: { value = GetImplementation( button ).IsSelected(); break; } case Toolkit::Button::Property::UNSELECTED_VISUAL: case Toolkit::Button::Property::SELECTED_VISUAL: case Toolkit::Button::Property::DISABLED_SELECTED_VISUAL: case Toolkit::Button::Property::DISABLED_UNSELECTED_VISUAL: case Toolkit::Button::Property::UNSELECTED_BACKGROUND_VISUAL: case Toolkit::Button::Property::SELECTED_BACKGROUND_VISUAL: case Toolkit::Button::Property::DISABLED_SELECTED_BACKGROUND_VISUAL: case Toolkit::Button::Property::DISABLED_UNSELECTED_BACKGROUND_VISUAL: case Toolkit::Button::Property::LABEL: { Property::Map visualProperty; if ( GetImplementation( button ).GetPropertyMapForVisual( propertyIndex, visualProperty ) ) { value = visualProperty; } break; } case Toolkit::DevelButton::Property::LABEL_RELATIVE_ALIGNMENT: { const char* alignment = Scripting::GetEnumerationName< Button::Align >( GetImplementation( button ).GetLabelAlignment(), ALIGNMENT_STRING_TABLE, ALIGNMENT_STRING_TABLE_COUNT ); if( alignment ) { value = std::string( alignment ); } break; } case Toolkit::DevelButton::Property::LABEL_PADDING: { Padding padding = GetImplementation( button ).GetLabelPadding(); value = Vector4( padding.x, padding.y, padding.top, padding.bottom); break; } case Toolkit::DevelButton::Property::VISUAL_PADDING: { Padding padding = GetImplementation( button ).GetForegroundPadding(); value = Vector4( padding.x, padding.y, padding.top, padding.bottom); } } } return value; } void Button::SetLabelPadding( const Padding& padding) { DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::SetLabelPadding padding(%f,%f,%f,%f)\n", padding.left, padding.right, padding.bottom, padding.top ); mLabelPadding = Padding( padding.left, padding.right, padding.bottom, padding.top ); RelayoutRequest(); } Padding Button::GetLabelPadding() { return mLabelPadding; } void Button::SetForegroundPadding( const Padding& padding) { DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::SetForegroundPadding padding(%f,%f,%f,%f)\n", padding.left, padding.right, padding.bottom, padding.top ); mForegroundPadding = Padding( padding.left, padding.right, padding.bottom, padding.top ); RelayoutRequest(); } Padding Button::GetForegroundPadding() { return mForegroundPadding; } std::string Button::AccessibleImpl::GetNameRaw() { std::string labelText; auto slf = Toolkit::Button::DownCast( self ); Property::Map labelMap = slf.GetProperty<Property::Map>( Toolkit::Button::Property::LABEL ); Property::Value* textPropertyPtr = labelMap.Find( Toolkit::TextVisual::Property::TEXT ); if ( textPropertyPtr ) { textPropertyPtr->Get( labelText ); } return labelText; } Property::Index Button::AccessibleImpl::GetNamePropertyIndex() { Property::Index label = Toolkit::Button::Property::LABEL; Property::Map labelMap = self.GetProperty<Property::Map>(label); if (MapContainsTextString(labelMap)) return label; else return Property::INVALID_INDEX; } Dali::Accessibility::States Button::AccessibleImpl::CalculateStates() { auto tmp = Control::Impl::AccessibleImpl::CalculateStates(); tmp[Dali::Accessibility::State::SELECTABLE] = true; auto slf = Toolkit::Button::DownCast( self ); tmp[Dali::Accessibility::State::ENABLED] = !slf.GetProperty<bool>( Toolkit::Button::Property::DISABLED ); tmp[Dali::Accessibility::State::CHECKED] = slf.GetProperty<bool>( Toolkit::Button::Property::SELECTED ); return tmp; } } // namespace Internal } // namespace Toolkit } // namespace Dali
35.266372
212
0.682037
[ "object", "transform" ]
b69a115ff9938d3802cbef85b97a8f8a65a6ffae
2,470
cpp
C++
ui/tests/typing_game.cpp
dobson156/irc_client
9afc098087a64c88f599e3dae956b7be1407bb96
[ "BSL-1.0" ]
1
2019-07-13T18:43:38.000Z
2019-07-13T18:43:38.000Z
ui/tests/typing_game.cpp
dobson156/irc_client
9afc098087a64c88f599e3dae956b7be1407bb96
[ "BSL-1.0" ]
null
null
null
ui/tests/typing_game.cpp
dobson156/irc_client
9afc098087a64c88f599e3dae956b7be1407bb96
[ "BSL-1.0" ]
null
null
null
#include <console.hpp> #include <boost/algorithm/string.hpp> //starts_with #include <chrono> #include <string> #include <random> #include <vector> #include <fstream> #include <sstream> #include <iterator> #include <algorithm> class stentence_maker { using isi=std::istream_iterator<std::string>; std::vector<std::string> dict; std::mt19937 eng { std::random_device()() }; std::uniform_int_distribution<std::size_t> dist { 0, dict.size()-1 }; public: stentence_maker(std::istream& is) : dict { isi(is), isi() } , eng { std::random_device()() } , dist { 0, dict.size()-1 } { } std::string operator()(std::size_t n) { std::ostringstream oss; for(std::size_t i=0; i!=n; ++i) { if(i) oss << ' '; oss << dict[dist(eng)]; } return oss.str(); } }; struct score { std::size_t n; double t; }; struct score_stencil { using value_type=score; int require_y(int, const score&) const { return 3; }; cons::point write_to(cons::frame& frame_, const score& sc) { const auto& dim=frame_.get_dimension(); int ts=std::min(dim.y, 3); switch(ts) { case 3: frame_.write({0, 2}, "words: "+std::to_string(sc.n)); case 2: frame_.write({0, 1}, "time: "+std::to_string(sc.t)); case 1: frame_.write({0, 0}, "wpm: "+std::to_string(sc.n*60/sc.t)); } return { ts, dim.x }; } }; int main() { const std::string dict_path="/usr/share/dict/cracklib-small"; std::ifstream file { dict_path }; stentence_maker sm(file); using text_box =cons::stenciled_frame<cons::string_stencil>; using score_box =cons::stenciled_frame<score_stencil>; using anchor_btm=cons::anchor_view<cons::anchors::bottom>; anchor_btm anc { cons::make_window(), 1 }; auto& inp=anc.emplace_anchor<cons::input_box>(); inp.reg_on_grow( [&anc](cons::point pt) { anc.set_partition(pt.y); anc.refresh(); return true; } ); int i=0; do { std::size_t n=5; const auto& word=sm(n); anc.emplace_fill<text_box>(word); inp.clear(); anc.refresh(); auto tstart=std::chrono::system_clock::now(); do { inp.get_char(); inp.set_foreground(boost::starts_with(word, inp.get_value()) ? COLOR_GREEN : COLOR_RED); inp.refresh(); } while(inp.get_value()!=word); double t=std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::system_clock::now()-tstart).count(); inp.clear(); anc.emplace_fill<score_box>(score{ n, t/1000.0 }); anc.refresh(); i=inp.get_char(); } while(i!='q'); }
24.7
71
0.643725
[ "vector" ]
b69bd5ff4f796e08620dafbadb6d978f12c4f9c0
2,325
cpp
C++
src/sse/Handler.cpp
jgorset/eventhub
189f3e464fec97df184ed0408edcd6768a0c41c3
[ "MIT" ]
null
null
null
src/sse/Handler.cpp
jgorset/eventhub
189f3e464fec97df184ed0408edcd6768a0c41c3
[ "MIT" ]
null
null
null
src/sse/Handler.cpp
jgorset/eventhub
189f3e464fec97df184ed0408edcd6768a0c41c3
[ "MIT" ]
null
null
null
#include <functional> #include <memory> #include <string> #include <vector> #include "sse/Handler.hpp" #include "sse/Response.hpp" #include "http/Response.hpp" #include "Common.hpp" #include "Util.hpp" #include "Server.hpp" #include "Config.hpp" #include "Connection.hpp" #include "ConnectionWorker.hpp" #include "HandlerContext.hpp" #include "TopicManager.hpp" namespace eventhub { namespace sse { void Handler::HandleRequest(HandlerContext& ctx, http::Parser* req) { auto conn = ctx.connection(); auto& redis = ctx.server()->getRedis(); auto& accessController = conn->getAccessController(); auto path = Util::uriDecode(req->getPath()); auto lastEventId = req->getHeader("Last-Event-ID"); auto sinceStr = req->getQueryString("since"); auto limitStr = req->getQueryString("limit"); long long limit = Config.getInt("MAX_CACHE_REQUEST_LIMIT"); if (path.at(0) == '/') { path = path.substr(1, std::string::npos); } if (path.empty() || !TopicManager::isValidTopicOrFilter(path)) { response::error(conn, "Invalid topic requested."); return; } // Check authorization. if (!accessController.allowSubscribe(path)) { response::error(conn, "Insufficient access.", 401); return; } // Get last-event-id. if (!req->getQueryString("lastEventId").empty()) { lastEventId = req->getQueryString("lastEventId"); } // Parse limit parameter. if (!limitStr.empty()) { try { auto limitParam = std::stoull(limitStr, nullptr, 10); if (limitParam < (unsigned long long)Config.getInt("MAX_CACHE_REQUEST_LIMIT")) { limit = limitParam; } } catch(...) {} } response::ok(conn); conn->setState(ConnectionState::SSE); conn->subscribe(path, 0); // Send cache if requested. nlohmann::json result; if (!lastEventId.empty()) { try { redis.getCacheSinceId(path, lastEventId, limit, TopicManager::isValidTopicFilter(path), result); } catch(...) {} } else if (!sinceStr.empty()) { try { auto since = std::stoull(sinceStr, nullptr, 10); redis.getCacheSince(path, since, limit, TopicManager::isValidTopicFilter(path), result); } catch(...) {} } for (const auto& cacheItem : result) { response::sendEvent(conn, cacheItem["id"], cacheItem["message"]); } } } // namespace SSE } // namespace eventhub
27.034884
102
0.666237
[ "vector" ]
b69c3aa69ee317b85b763ad62901da429b2d6b60
1,681
cpp
C++
802/B[ Heidi and Library (medium) ].cpp
mejanvijay/codeforces-jvj_iit-submissions
2a2aac7e93ca92e75887eff92361174aa36207c8
[ "MIT" ]
null
null
null
802/B[ Heidi and Library (medium) ].cpp
mejanvijay/codeforces-jvj_iit-submissions
2a2aac7e93ca92e75887eff92361174aa36207c8
[ "MIT" ]
null
null
null
802/B[ Heidi and Library (medium) ].cpp
mejanvijay/codeforces-jvj_iit-submissions
2a2aac7e93ca92e75887eff92361174aa36207c8
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define sd(x) scanf("%d",&x) #define su(x) scanf("%u",&x) #define slld(x) scanf("%lld",&x) #define sc(x) scanf("%c",&x) #define ss(x) scanf("%s",x) #define sf(x) scanf("%f",&x) #define slf(x) scanf("%lf",&x) #define ll long long int #define mod(x,n) (x+n)%n #define pb push_back #define mp make_pair #define pii pair<int,int> #define vi vector<int> #define all(a) (a).begin(),(a).end() #define F first #define S second #define sz(x) (int)x.size() #define Mod 1000000007 set< pair<int,int> > St; set< pair<int,int> >::iterator it; int A[400007][2]; int Occ[400007]; pair<int,int> temp; int main() { // freopen("input_file_name.in","r",stdin); // freopen("output_file_name.out","w",stdout); int i,j,k,l,m,n,x,y,z,a=0,b,r; // ll i,j,k,l,m,n,x,y,z,a,b,r; sd(n); sd(k); for(i=0;i<n;i++) sd(A[i][0]); for(i=0;i<400007;i++) Occ[i] = n; for(i=n-1;i>=0;i--) { A[i][1] = Occ[ A[i][0] ]; Occ[ A[i][0] ] = i; // printf("%d ", A[i][1] ); } // printf("\n"); for(i=0;i<400007;i++) Occ[i] = -1; for(i=0;i<n;i++) { if(Occ[A[i][0]]!=-1) { St.erase( mp(Occ[A[i][0]],A[i][0]) ); St.insert( mp(A[i][1],A[i][0]) ); Occ[A[i][0]] = A[i][1]; } else if(St.size()<k && Occ[A[i][0]]==-1) { St.insert( mp(A[i][1],A[i][0]) ); Occ[ A[i][0] ] = A[i][1]; a++; } else { if(Occ[A[i][0]]==-1) { it = St.end(); it--; temp = *it; St.erase(temp); Occ[temp.S] = -1; St.insert(mp(A[i][1],A[i][0])); Occ[ A[i][0] ] = A[i][1]; a++; } } } printf("%d\n", a ); return 0; }
18.271739
47
0.477692
[ "vector" ]
b6ad74371b4d71008592440e35150b889848f5fc
2,239
cpp
C++
src/pacs.cpp
chandu1263/openGL
5d1a9ae1e1cdca06ad5d8cde60da907321f305bc
[ "MIT" ]
null
null
null
src/pacs.cpp
chandu1263/openGL
5d1a9ae1e1cdca06ad5d8cde60da907321f305bc
[ "MIT" ]
null
null
null
src/pacs.cpp
chandu1263/openGL
5d1a9ae1e1cdca06ad5d8cde60da907321f305bc
[ "MIT" ]
null
null
null
#include "pacs.h" #include "main.h" Pacs::Pacs(float x, float y, color_t color,float r,double speed,int a) { this->position = glm::vec3(x, y, 0); this->rotation = 0; this->appear=1; this->pacflag=1; this->speed=speed; this->r=r; GLfloat vertex_buffer_data[360*9]; float angle=0; this->a=a; for(int i=0;i<360*9*5/6;i++) { vertex_buffer_data[i++]=0.0f; vertex_buffer_data[i++]=0.0f; vertex_buffer_data[i++]=0.0f; vertex_buffer_data[i++]=r*cos(angle); vertex_buffer_data[i++]= r*sin(angle); vertex_buffer_data[i++]=0.0f; vertex_buffer_data[i++]= r*cos(angle+M_PI/180); vertex_buffer_data[i++]= r*sin(angle+M_PI/180); vertex_buffer_data[i]=0.0f; angle+=M_PI/180; } this->object[0] = create3DObject(GL_TRIANGLES, 360*3*5/6, vertex_buffer_data,color , GL_FILL); if(a) { GLfloat buffer_data[]={ r*sqrt(2),0,0, 0,r*sqrt(2),0, r*sqrt(2)+0.05,0.05,0, r*sqrt(2)+0.05,0.05,0, 0,r*sqrt(2),0, 0.05,r*sqrt(2)+0.05,0, }; this->slope=rand()%2; if(slope) this->rotation=90; this->object[1]=create3DObject(GL_TRIANGLES,6,buffer_data,COLOR_BROWN,GL_FILL); } } void Pacs::draw(glm::mat4 VP,int a) { Matrices.model = glm::mat4(1.0f); glm::mat4 translate = glm::translate (this->position); // glTranslatef glm::mat4 rotate = glm::rotate((float) (this->rotation * M_PI / 180.0f), glm::vec3(0, 0, 1)); rotate = rotate * glm::translate(glm::vec3(0, 0, 0)); Matrices.model *= (translate * rotate); glm::mat4 MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(this->object[0]); if(a) draw3DObject(this->object[1]); } void Pacs::set_position(float x, float y) { this->position = glm::vec3(x, y, 0); } void Pacs::tick() { this->position.x += speed; } bounding_box_t Pacs::bounding_box() { float x = this->position.x, y = this->position.y; bounding_box_t bbox = { x, y, this->r}; return bbox; }
25.443182
100
0.557392
[ "object", "model" ]
b6b0367f3db3a52e7e4829cbba61a19ae4fcb6a3
2,391
cpp
C++
Bicoloring2/bicoloringanalizer.cpp
informatik01/programming-tasks
2955e67173c5482206dd4a0c59bda1d9e2703dd5
[ "MIT" ]
null
null
null
Bicoloring2/bicoloringanalizer.cpp
informatik01/programming-tasks
2955e67173c5482206dd4a0c59bda1d9e2703dd5
[ "MIT" ]
null
null
null
Bicoloring2/bicoloringanalizer.cpp
informatik01/programming-tasks
2955e67173c5482206dd4a0c59bda1d9e2703dd5
[ "MIT" ]
null
null
null
#include <fstream> #include <iostream> #include <stdexcept> #include <queue> #include "BicoloringAnalizer.h" BicoloringAnalizer::BicoloringAnalizer(){} BicoloringAnalizer::~BicoloringAnalizer(){} void BicoloringAnalizer::analizeGraphs(string fileName) { int numOfVertices; int numOfEdges; int vertex; int adjacentVertex; std::ifstream input; input.exceptions(std::ios_base::failbit | std::ios_base::badbit); try { input.open(fileName, std::ios_base::in); input >> numOfVertices; while (numOfVertices != 0) { if (numOfVertices < 2 || numOfVertices > 199) { input.close(); throw std::runtime_error("Wrong number of nodes. Must be \"1 < nodes < 200\"\n"); } input >> numOfEdges; if (numOfEdges < 1) { input.close(); throw std::runtime_error("Wrong data in file.\n"); } graph.clear(); graph.resize(numOfVertices); for (int i = 0; i < numOfEdges; i++) { input >> vertex >> adjacentVertex; if (vertex >= 0 && vertex < numOfVertices && adjacentVertex >= 0 && adjacentVertex < numOfVertices) graph[vertex].push_back(adjacentVertex); else { input.close(); throw std::runtime_error("Wrong vertex label. Must be \"0 <= vertex_label < numOfVertices\"\n"); } } if (isBipartite(numOfVertices)) std::cout << "BICOLORABLE." << std::endl; else std::cout << "NOT BICOLORABLE." << std::endl; input >> numOfVertices; } } catch (std::ios_base::failure) { std::cerr << "Error reading file: "; input.close(); throw; } input.close(); } bool BicoloringAnalizer::isBipartite(int n) { int startVertex = 0; int currentColor = 0; std::queue<int> queueOfVertices; std::vector<bool> visited(n, false); std::vector<int> vertexColor(n, 1); queueOfVertices.push(startVertex); visited[startVertex] = true; vertexColor[startVertex] = currentColor; while (!queueOfVertices.empty()) { int currentVertex = queueOfVertices.front(); queueOfVertices.pop(); for (size_t i = 0; i < graph[currentVertex].size(); i++) { int adjacentVertex = graph[currentVertex][i]; if (!visited[adjacentVertex]) { visited[adjacentVertex] = true; vertexColor[adjacentVertex] = ~currentColor; queueOfVertices.push(adjacentVertex); } else { if (vertexColor[currentVertex] == vertexColor[adjacentVertex]) return false; } } currentColor = ~currentColor; } return true; }
24.649485
103
0.671267
[ "vector" ]
b6c18e6aa14386ec11025b4ca151f7ee15b2fff7
1,759
cpp
C++
src/dicom/Patient.cpp
RWTHmediTEC/CarnaDICOM
b767cc5f7484b85d24b7557d5d86efebad57b2ef
[ "BSD-3-Clause" ]
null
null
null
src/dicom/Patient.cpp
RWTHmediTEC/CarnaDICOM
b767cc5f7484b85d24b7557d5d86efebad57b2ef
[ "BSD-3-Clause" ]
1
2015-07-25T13:26:42.000Z
2015-07-25T13:26:42.000Z
src/dicom/Patient.cpp
RWTHmediTEC/CarnaDICOM
b767cc5f7484b85d24b7557d5d86efebad57b2ef
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2010 - 2015 Leonid Kostrykin * * Chair of Medical Engineering (mediTEC) * RWTH Aachen University * Pauwelsstr. 20 * 52074 Aachen * Germany * */ #include <Carna/dicom/Patient.h> #include <Carna/dicom/Study.h> #include <algorithm> #include <map> namespace Carna { namespace dicom { // ---------------------------------------------------------------------------------- // Patient :: Details // ---------------------------------------------------------------------------------- struct Patient::Details { std::vector< Study* > studies; std::map< std::string, Study* > studyByName; }; // ---------------------------------------------------------------------------------- // Patient // ---------------------------------------------------------------------------------- Patient::Patient( const std::string& name ) : pimpl( new Details() ) , name( name ) { } Patient::~Patient() { std::for_each( pimpl->studies.begin(), pimpl->studies.end(), std::default_delete< Study >() ); } const std::vector< Study* >& Patient::studies() const { return pimpl->studies; } void Patient::take( Study* study ) { CARNA_ASSERT( pimpl->studyByName.find( study->name ) == pimpl->studyByName.end() ); pimpl->studies.push_back( study ); pimpl->studyByName[ name ] = study; } Study& Patient::study( const std::string& name ) { const auto itr = pimpl->studyByName.find( name ); if( itr == pimpl->studyByName.end() ) { Study* const study = new Study( name ); pimpl->studyByName[ name ] = study; pimpl->studies.push_back( study ); return *study; } else { return *itr->second; } } } // namespace Carna :: dicom } // namespace Carna
19.764045
98
0.495736
[ "vector" ]
b6c57d7b5f514bc8bdf6b575b3a0281da41b16f0
5,907
cpp
C++
Server/src/Services/Feature/OpUpdateFeatures.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
2
2017-04-19T01:38:30.000Z
2020-07-31T03:05:32.000Z
Server/src/Services/Feature/OpUpdateFeatures.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
null
null
null
Server/src/Services/Feature/OpUpdateFeatures.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
1
2021-12-29T10:46:12.000Z
2021-12-29T10:46:12.000Z
// // Copyright (C) 2004-2011 by Autodesk, Inc. // // This library is free software; you can redistribute it and/or // modify it under the terms of version 2.1 of the GNU Lesser // General Public License as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // #include "ServerFeatureServiceDefs.h" #include "OpUpdateFeatures.h" #include "ServerFeatureService.h" #include "LogManager.h" ///---------------------------------------------------------------------------- /// <summary> /// Constructs the object. /// </summary> ///---------------------------------------------------------------------------- MgOpUpdateFeatures::MgOpUpdateFeatures() { } ///---------------------------------------------------------------------------- /// <summary> /// Destructs the object. /// </summary> ///---------------------------------------------------------------------------- MgOpUpdateFeatures::~MgOpUpdateFeatures() { } ///---------------------------------------------------------------------------- /// <summary> /// Executes the operation. /// </summary> /// /// <exceptions> /// MgException /// </exceptions> ///---------------------------------------------------------------------------- void MgOpUpdateFeatures::Execute() { ACE_DEBUG((LM_DEBUG, ACE_TEXT(" (%t) MgOpUpdateFeatures::Execute()\n"))); STRING partialFailureMsg; Ptr<MgPropertyCollection> rowsAffected; MG_LOG_OPERATION_MESSAGE(L"UpdateFeatures"); MG_FEATURE_SERVICE_TRY() MG_LOG_OPERATION_MESSAGE_INIT(m_packet.m_OperationVersion, m_packet.m_NumArguments); ACE_ASSERT(m_stream != NULL); if (3 == m_packet.m_NumArguments) { // Get the feature source Ptr<MgResourceIdentifier> resource = (MgResourceIdentifier*)m_stream->GetObject(); // Get properties collection Ptr<MgFeatureCommandCollection> commands = (MgFeatureCommandCollection*)m_stream->GetObject(); // Get the filter text bool useTransaction; m_stream->GetBoolean(useTransaction); BeginExecution(); MG_LOG_OPERATION_MESSAGE_PARAMETERS_START(); MG_LOG_OPERATION_MESSAGE_ADD_STRING((NULL == resource) ? L"MgResourceIdentifier" : resource->ToString().c_str()); MG_LOG_OPERATION_MESSAGE_ADD_SEPARATOR(); MG_LOG_OPERATION_MESSAGE_ADD_STRING(L"MgFeatureCommandCollection"); MG_LOG_OPERATION_MESSAGE_ADD_SEPARATOR(); MG_LOG_OPERATION_MESSAGE_ADD_BOOL(useTransaction); MG_LOG_OPERATION_MESSAGE_ADD_SEPARATOR(); MG_LOG_OPERATION_MESSAGE_PARAMETERS_END(); Validate(); // Execute the operation rowsAffected = m_service->UpdateFeatures(resource, commands, useTransaction); // #649: Exceptions are only thrown in transactional cases (which will never reach here). For non-transactional cases, // we check for any MgStringProperty instances. These are "serialized" FDO exception messages indicating failure for that // particular command. We can't throw for non-transactional cases, instead we put the onus on the consuming caller to do // the same check we are doing here. for (INT32 i = 0; i < rowsAffected->GetCount(); i++) { Ptr<MgProperty> prop = rowsAffected->GetItem(i); if (prop->GetPropertyType() == MgPropertyType::String) { MgStringProperty* sprop = static_cast<MgStringProperty*>(prop.p); //One is enough to flag partial failure (should we go through all of them?) partialFailureMsg = sprop->GetValue(); break; } } if (mgException == NULL && partialFailureMsg.empty()) { // Only Write the response if there no Fdo Exception // if there is an exception, Response will be written by MgFeatureServiceHandler::ProcessOperation catching it EndExecution(rowsAffected); } } else { MG_LOG_OPERATION_MESSAGE_PARAMETERS_START(); MG_LOG_OPERATION_MESSAGE_PARAMETERS_END(); } if (!m_argsRead) { throw new MgOperationProcessingException(L"MgOpUpdateFeatures.Execute", __LINE__, __WFILE__, NULL, L"", NULL); } if (partialFailureMsg.empty()) { // Successful operation MG_LOG_OPERATION_MESSAGE_ADD_STRING(MgResources::Success.c_str()); } MG_FEATURE_SERVICE_CATCH(L"MgOpUpdateFeatures.Execute") if (mgException != NULL || !partialFailureMsg.empty()) { // Failed operation MG_LOG_OPERATION_MESSAGE_ADD_STRING(MgResources::Failure.c_str()); // Only thrown exceptions are logged, so for this partial failure to be logged into Error.log // we have to log it here if (mgException == NULL && !partialFailureMsg.empty()) { //NOTE: Serialized MgFdoException already has the stack trace, so stub an empty string to //satisfy the logging macro STRING sTrace = L""; MG_LOG_EXCEPTION_ENTRY(partialFailureMsg, sTrace); //DO NOT THROW A NEW EXCEPTION! We must respect the original contract of the API as perceived by the //calling web tier code. That is: Write out the original MgPropertyCollection EndExecution(rowsAffected); } } // Add access log entry for operation MG_LOG_OPERATION_MESSAGE_ACCESS_ENTRY(); MG_FEATURE_SERVICE_THROW() }
36.239264
130
0.622651
[ "object" ]
b6c91d0aa9c6aa6f52343608eac8c2024e0e4cf1
536
cpp
C++
SDLtest/PathGen.cpp
asderfghj/AI-Pathfinding-Demo
48737c999c4bb8f73543de05088001565ad7cc77
[ "MIT" ]
null
null
null
SDLtest/PathGen.cpp
asderfghj/AI-Pathfinding-Demo
48737c999c4bb8f73543de05088001565ad7cc77
[ "MIT" ]
null
null
null
SDLtest/PathGen.cpp
asderfghj/AI-Pathfinding-Demo
48737c999c4bb8f73543de05088001565ad7cc77
[ "MIT" ]
null
null
null
/// @file PathGen.cpp /// @brief The function to generate a path #include "pathgen.h" std::vector<node*> GeneratePath(node *_endnode) { std::vector<node*> path; node* currentpathpoint; path.push_back(_endnode); currentpathpoint = path.front(); while (currentpathpoint->Getm_startNode() != true && currentpathpoint->Getm_parNode() != NULL) { path.push_back(currentpathpoint->Getm_parNode()); //currentpathpoint = path.front() - i; <--- Don't do that currentpathpoint = currentpathpoint->Getm_parNode(); } return path; }
28.210526
95
0.712687
[ "vector" ]
b6cf6b2ea34a7ea161ecde3d9864c7110d340eaf
5,951
cpp
C++
src/paintown-engine/object/stimulation.cpp
marstau/shinsango
d9468787ae8e18fa478f936770d88e9bf93c11c0
[ "BSD-3-Clause" ]
1
2021-06-16T15:25:47.000Z
2021-06-16T15:25:47.000Z
src/paintown-engine/object/stimulation.cpp
marstau/shinsango
d9468787ae8e18fa478f936770d88e9bf93c11c0
[ "BSD-3-Clause" ]
null
null
null
src/paintown-engine/object/stimulation.cpp
marstau/shinsango
d9468787ae8e18fa478f936770d88e9bf93c11c0
[ "BSD-3-Clause" ]
null
null
null
#include "stimulation.h" #include "object.h" #include "util/graphics/bitmap.h" #include "util/token.h" #include "util/token_exception.h" #include "character.h" #include "draw-effect.h" namespace Paintown{ Stimulation::Stimulation(){ } Stimulation::Stimulation( const Stimulation & copy ){ } void Stimulation::stimulate(Object & obj) const { } void Stimulation::stimulate(Character & obj) const { stimulate((Object&) obj); } void Stimulation::stimulate(Player & obj) const { stimulate((Character&) obj); } Stimulation * Stimulation::create(const Token & token){ try{ const Token * child; token.view() >> child; if (*child == "health"){ return new HealthStimulation(*child); } if (*child == "invincibility"){ return new InvincibilityStimulation(*child); } if (*child == "speed"){ return new SpeedStimulation(*child); } if (*child == "extra-life"){ return new ExtraLifeStimulation(*child); } Global::debug(0) << "Unknown stimulation type: " << child->getName() << std::endl; } catch (const TokenException & fail){ Global::debug(0) << "Could not parse stimulation: " << fail.getTrace() << std::endl; } return NULL; } Stimulation * Stimulation::create(Network::Message & message){ int type = 0; message >> type; switch (type){ case Health: return new HealthStimulation(message); case Invincibility: return new InvincibilityStimulation(message); case Speed: return new SpeedStimulation(message); case ExtraLife: return new ExtraLifeStimulation(message); } return NULL; } Stimulation * Stimulation::copy() const { return new Stimulation(*this); } void Stimulation::createMessage(Network::Message & message) const { } /* std::string Stimulation::typeToName(Type type){ switch (type){ case Health: return "health"; case Invincibility: return "invincibility"; case Speed: return "speed"; } return ""; } */ Stimulation::~Stimulation(){ } HealthStimulation::HealthStimulation( int value ): value(value){ } HealthStimulation::HealthStimulation(const Token & data){ if (!data.match("_", value)){ throw TokenException(__FILE__, __LINE__, "Expected an integer following health: (health 10)"); } } HealthStimulation::HealthStimulation( const HealthStimulation & h ): value(h.value){ } HealthStimulation::HealthStimulation(Network::Message & message){ message >> value; } void HealthStimulation::stimulate( Character & c ) const { /* cause negative hurt */ c.hurt(-value); c.addEffect(new DrawCountdownEffect(new DrawGlowEffect(&c, Graphics::makeColor(50,50,0), Graphics::makeColor(190, 190, 20), 50), 150)); } void HealthStimulation::createMessage(Network::Message & message) const { message << Stimulation::Health << value; } Stimulation * HealthStimulation::copy() const { return new HealthStimulation(*this); } InvincibilityStimulation::InvincibilityStimulation(int duration): duration(duration){ if (duration < 0){ duration = 0; } } InvincibilityStimulation::InvincibilityStimulation(Network::Message & data){ data >> duration; } InvincibilityStimulation::InvincibilityStimulation(const Token & data){ if (!data.match("_", duration)){ throw TokenException(__FILE__, __LINE__, "Expected an integer following invincibility: (invincibility 10)"); } } InvincibilityStimulation::InvincibilityStimulation(const InvincibilityStimulation & copy): duration(copy.duration){ } void InvincibilityStimulation::stimulate(Character & guy) const { guy.setInvincibility(duration); } Stimulation * InvincibilityStimulation::copy() const { return new InvincibilityStimulation(duration); } void InvincibilityStimulation::createMessage(Network::Message & message) const { message << Stimulation::Invincibility << duration; } SpeedStimulation::SpeedStimulation(double boost, int ticks): boost(boost), ticks(ticks){ if (boost < 0){ boost = 0; } } SpeedStimulation::SpeedStimulation(const Token & data){ if (!data.match("_", boost, ticks)){ throw TokenException(__FILE__, __LINE__, "Expected two numbers after speed: (speed 1.2 20)"); } if (boost < 0){ boost = 0; } } SpeedStimulation::SpeedStimulation(Network::Message & data){ int value = 0; data >> value >> ticks; boost = value / 100.0; } SpeedStimulation::SpeedStimulation(const SpeedStimulation & copy): boost(copy.boost), ticks(copy.ticks){ } void SpeedStimulation::stimulate(Character & guy) const { guy.setSpeedBoost(boost, ticks); guy.addEffect(new DrawCountdownEffect(new DrawGlowEffect(&guy, Graphics::makeColor(64,10,0), Graphics::makeColor(190, 30, 20), 50), ticks)); } Stimulation * SpeedStimulation::copy() const { return new SpeedStimulation(boost, ticks); } void SpeedStimulation::createMessage(Network::Message & message) const { message << Stimulation::Speed << (int) (boost * 100) << ticks; } ExtraLifeStimulation::ExtraLifeStimulation(const int lives): lives(lives){ } ExtraLifeStimulation::ExtraLifeStimulation(const Token & data): lives(0){ if (!data.match("_", lives)){ throw TokenException(__FILE__, __LINE__, "Expected a number after extra-life: (extra-life 1)"); } } ExtraLifeStimulation::ExtraLifeStimulation(Network::Message & data): lives(0){ data >> lives; } ExtraLifeStimulation::ExtraLifeStimulation(const ExtraLifeStimulation & copy): lives(copy.lives){ } void ExtraLifeStimulation::stimulate(Character & guy) const { guy.setLives(guy.getLives() + lives); } Stimulation * ExtraLifeStimulation::copy() const { return new ExtraLifeStimulation(*this); } void ExtraLifeStimulation::createMessage(Network::Message & message) const { message << Stimulation::ExtraLife << lives; } }
26.566964
144
0.685431
[ "object" ]
b6d2c9fd275367c42a248476a52b8ac1f1ebc71e
2,084
cpp
C++
competitive programming/codeforces/266B - Queue at the School.cpp
sureshmangs/Code
de91ffc7ef06812a31464fb40358e2436734574c
[ "MIT" ]
16
2020-06-02T19:22:45.000Z
2022-02-05T10:35:28.000Z
competitive programming/codeforces/266B - Queue at the School.cpp
codezoned/Code
de91ffc7ef06812a31464fb40358e2436734574c
[ "MIT" ]
null
null
null
competitive programming/codeforces/266B - Queue at the School.cpp
codezoned/Code
de91ffc7ef06812a31464fb40358e2436734574c
[ "MIT" ]
2
2020-08-27T17:40:06.000Z
2022-02-05T10:33:52.000Z
/* During the break the schoolchildren, boys and girls, formed a queue of n people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward each second. Let's describe the process more precisely. Let's say that the positions in the queue are sequentially numbered by integers from 1 to n, at that the person in the position number 1 is served first. Then, if at time x a boy stands on the i-th position and a girl stands on the (i?+?1)-th position, then at time x?+?1 the i-th position will have a girl and the (i?+?1)-th position will have a boy. The time is given in seconds. You've got the initial position of the children, at the initial moment of time. Determine the way the queue is going to look after t seconds. Input The first line contains two integers n and t (1?=?n,?t?=?50), which represent the number of children in the queue and the time after which the queue will transform into the arrangement you need to find. The next line contains string s, which represents the schoolchildren's initial arrangement. If the i-th position in the queue contains a boy, then the i-th character of string s equals "B", otherwise the i-th character equals "G". Output Print string a, which describes the arrangement after t seconds. If the i-th position has a boy after the needed time, then the i-th character a must equal "B", otherwise it must equal "G". Examples inputCopy 5 1 BGGBG outputCopy GBGGB inputCopy 5 2 BGGBG outputCopy GGBGB inputCopy 4 1 GGGB outputCopy GGGB */ #include<bits/stdc++.h> using namespace std; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int n, t; cin >> n >> t; string s; cin >> s; while (t--) { bool isSwap = false; for(int i = 0; i < n - 1; i++){ if(s[i] == 'B' && s[i + 1] == 'G'){ swap(s[i], s[i + 1]); i++; isSwap = true; } } if(isSwap == false) break; } cout << s; return 0; }
29.771429
424
0.710173
[ "transform" ]
b6d6a5f7a1ed6c27eba26b65856290a5f4c75278
3,677
cpp
C++
kernel/devices/ps2/Ps2Mouse.cpp
DeanoBurrito/northport
6da490b02bfe7d0a12a25316db879ecc249be1c7
[ "MIT" ]
19
2021-12-10T12:48:44.000Z
2022-03-30T09:17:14.000Z
kernel/devices/ps2/Ps2Mouse.cpp
DeanoBurrito/northport
6da490b02bfe7d0a12a25316db879ecc249be1c7
[ "MIT" ]
24
2021-11-30T10:00:05.000Z
2022-03-29T10:19:21.000Z
kernel/devices/ps2/Ps2Mouse.cpp
DeanoBurrito/northport
6da490b02bfe7d0a12a25316db879ecc249be1c7
[ "MIT" ]
2
2021-11-24T00:52:10.000Z
2021-12-27T23:47:32.000Z
#include <devices/ps2/Ps2Mouse.h> #include <devices/ps2/Ps2Driver.h> #include <devices/IoApic.h> #include <devices/Keyboard.h> #include <devices/Mouse.h> #include <Platform.h> #include <Cpu.h> #include <Log.h> namespace Kernel::Devices::Ps2 { void Ps2Mouse::Init() { state = DeviceState::Initializing; inputBuffer = new uint8_t[4]; inputLength = 0; leftMousePrevDown = rightMousePrevDown = middleMousePrevDown = false; //enable data reporting WriteData(useSecondaryPort, Cmds::EnableDataReporting); if (ReadData() != Cmds::Acknowledge) Log("Mouse did not acknowledge command: enable data reporting.", LogSeverity::Error); //remap irq12 to our interrupt vector of choice auto overrideDetails = IoApic::TranslateToGsi(12); IoApic::Global(overrideDetails.gsiNum)->WriteRedirect(0, overrideDetails); IoApic::Global(overrideDetails.gsiNum)->SetPinMask(overrideDetails.irqNum, false); state = DeviceState::Ready; } void Ps2Mouse::Deinit() { state = DeviceState::Deinitializing; WriteData(useSecondaryPort, Cmds::DisableDataReporting); state = DeviceState::Shutdown; } void Ps2Mouse::Reset() { Deinit(); Init(); } extern Ps2Driver* ps2DriverInstance; sl::Opt<Drivers::GenericDriver*> Ps2Mouse::GetDriverInstance() { if (ps2DriverInstance == nullptr) return {}; return ps2DriverInstance; } size_t Ps2Mouse::ButtonCount() { return 0; } size_t Ps2Mouse::AxisCount() { return 0; } KeyEvent CreateKeyEvent(KeyIdentity id, bool pressed) { KeyEvent ev; ev.id = id; ev.inputDeviceId = (uint8_t)BuiltInInputDevices::Ps2Mouse; ev.mods = KeyModFlags::None; ev.tags = pressed ? KeyTags::Pressed : KeyTags::Released; return ev; } void Ps2Mouse::HandleIrq() { while (!OutputBufferEmpty()) { inputBuffer[inputLength] = ReadData(); inputLength++; } if (inputLength < 3) return; //not a full packet int32_t relativeX = inputBuffer[1]; if (inputBuffer[0] & (1 << 4)) relativeX |= 0xFFFFFF00; int32_t relativeY = inputBuffer[2]; if (inputBuffer[0] & (1 << 5)) relativeY |= 0xFFFFFF00; Mouse::Global()->PushMouseEvent({ relativeX, relativeY }); if ((inputBuffer[0] & 0b001) != 0 && !leftMousePrevDown) Keyboard::Global()->PushKeyEvent(CreateKeyEvent(KeyIdentity::MouseLeft, true)); if ((inputBuffer[0] & 0b001) == 0 && leftMousePrevDown) Keyboard::Global()->PushKeyEvent(CreateKeyEvent(KeyIdentity::MouseLeft, true)); leftMousePrevDown = (inputBuffer[0] & 0b001) != 0; if ((inputBuffer[0] & 0b010) != 0 && !rightMousePrevDown) Keyboard::Global()->PushKeyEvent(CreateKeyEvent(KeyIdentity::MouseRight, true)); if ((inputBuffer[0] & 0b010) == 0 && rightMousePrevDown) Keyboard::Global()->PushKeyEvent(CreateKeyEvent(KeyIdentity::MouseRight, true)); rightMousePrevDown = (inputBuffer[0] & 0b010) != 0; if ((inputBuffer[0] & 0b100) != 0 && !middleMousePrevDown) Keyboard::Global()->PushKeyEvent(CreateKeyEvent(KeyIdentity::MouseMiddle, true)); if ((inputBuffer[0] & 0b100) == 0 && middleMousePrevDown) Keyboard::Global()->PushKeyEvent(CreateKeyEvent(KeyIdentity::MouseMiddle, true)); middleMousePrevDown = (inputBuffer[0] & 0b100) != 0; inputLength = 0; } }
31.698276
97
0.614903
[ "vector" ]
b6dadc3cfa5ec044e76f123527886233b05c9479
6,210
cpp
C++
src/Patch/InstrRule.cpp
pistach3/QBDI
ff94f9c6ed18d5271013f0fcc77f6996d32db3cf
[ "Apache-2.0" ]
null
null
null
src/Patch/InstrRule.cpp
pistach3/QBDI
ff94f9c6ed18d5271013f0fcc77f6996d32db3cf
[ "Apache-2.0" ]
null
null
null
src/Patch/InstrRule.cpp
pistach3/QBDI
ff94f9c6ed18d5271013f0fcc77f6996d32db3cf
[ "Apache-2.0" ]
null
null
null
/* * This file is part of QBDI. * * Copyright 2017 - 2021 Quarkslab * * 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 "Patch/InstrRule.h" #include "Patch/InstrRules.h" #include "Patch/Patch.h" #include "Patch/PatchGenerator.h" #include "Patch/RelocatableInst.h" #include "Utility/InstAnalysis_prive.h" #include "Utility/LogSys.h" namespace QBDI { void InstrRule::instrument(Patch &patch, const llvm::MCInstrInfo *MCII, const llvm::MCRegisterInfo *MRI, const PatchGenerator::UniquePtrVec &patchGen, bool breakToHost, InstPosition position) const { if (patchGen.size() == 0 && breakToHost == false) { return; } /* The instrument function needs to handle several different cases. An * instrumentation can be either prepended or appended to the patch and, in * each case, can trigger a break to host. */ RelocatableInst::UniquePtrVec instru; TempManager tempManager(patch.metadata.inst, MCII, MRI, true); // Generate the instrumentation code from the original instruction context for (const PatchGenerator::UniquePtr &g : patchGen) { append(instru, g->generate(&patch.metadata.inst, patch.metadata.address, patch.metadata.instSize, MCII, &tempManager, nullptr)); } // In case we break to the host, we need to ensure the value of PC in the // context is correct. This value needs to be set when instrumenting before // the instruction or when instrumenting after an instruction which does not // set PC. if (breakToHost) { if (position == InstPosition::PREINST || patch.metadata.modifyPC == false) { switch (position) { // In PREINST PC is set to the current address case InstPosition::PREINST: append(instru, GetConstant(Temp(0), Constant(patch.metadata.address)) .generate(&patch.metadata.inst, patch.metadata.address, patch.metadata.instSize, MCII, &tempManager, nullptr)); break; // In POSTINST PC is set to the next instruction address case InstPosition::POSTINST: append(instru, GetConstant(Temp(0), Constant(patch.metadata.address + patch.metadata.instSize)) .generate(&patch.metadata.inst, patch.metadata.address, patch.metadata.instSize, MCII, &tempManager, nullptr)); break; } append(instru, SaveReg(tempManager.getRegForTemp(0), Offset(Reg(REG_PC)))); } } // The breakToHost code requires one temporary register. If none were // allocated by the instrumentation we thus need to add one. if (breakToHost && tempManager.getUsedRegisterNumber() == 0) { tempManager.getRegForTemp(Temp(0)); } // Prepend the temporary register saving code to the instrumentation Reg::Vec usedRegisters = tempManager.getUsedRegisters(); for (uint32_t i = 0; i < usedRegisters.size(); i++) { prepend(instru, SaveReg(usedRegisters[i], Offset(usedRegisters[i]))); } // In the break to host case the first used register is not restored and // instead given to the break to host code as a scratch. It will later be // restored by the break to host code. if (breakToHost) { for (uint32_t i = 1; i < usedRegisters.size(); i++) { append(instru, LoadReg(usedRegisters[i], Offset(usedRegisters[i]))); } append(instru, getBreakToHost(usedRegisters[0])); } // Normal case where we append the temporary register restoration code to the // instrumentation else { for (uint32_t i = 0; i < usedRegisters.size(); i++) { append(instru, LoadReg(usedRegisters[i], Offset(usedRegisters[i]))); } } // The resulting instrumentation is either appended or prepended as per the // InstPosition if (position == PREINST) { patch.prepend(std::move(instru)); } else if (position == POSTINST) { patch.append(std::move(instru)); } else { QBDI_ERROR("Invalid position 0x{:x}", position); abort(); } } bool InstrRuleBasic::canBeApplied(const Patch &patch, const llvm::MCInstrInfo *MCII) const { return condition->test(patch.metadata.inst, patch.metadata.address, patch.metadata.instSize, MCII); } bool InstrRuleDynamic::canBeApplied(const Patch &patch, const llvm::MCInstrInfo *MCII) const { return condition->test(patch.metadata.inst, patch.metadata.address, patch.metadata.instSize, MCII); } bool InstrRuleUser::tryInstrument(Patch &patch, const llvm::MCInstrInfo *MCII, const llvm::MCRegisterInfo *MRI, const Assembly *assembly) const { if (!range.contains( Range<rword>(patch.metadata.address, patch.metadata.address + patch.metadata.instSize))) { return false; } QBDI_DEBUG("Call user InstrCB at 0x{:x} with analysisType 0x{:x}", cbk, analysisType); const InstAnalysis *ana = analyzeInstMetadata(patch.metadata, analysisType, *assembly); std::vector<InstrRuleDataCBK> vec = cbk(vm, ana, cbk_data); QBDI_DEBUG("InstrCB return {} callback(s)", vec.size()); if (vec.size() == 0) { return false; } for (const InstrRuleDataCBK &cbkToAdd : vec) { instrument(patch, MCII, MRI, getCallbackGenerator(cbkToAdd.cbk, cbkToAdd.data), true, cbkToAdd.position); } return true; } } // namespace QBDI
37.409639
80
0.639775
[ "vector" ]
b6e24ef7a528ea335a4dcc36fe4c66c4e613672e
769
hpp
C++
src/hazel/renderer/renderer.hpp
aceiii/hazel-mac
10c61fd9ca371c49828c074ff88a263cb4ee275a
[ "Apache-2.0" ]
1
2021-01-11T21:07:04.000Z
2021-01-11T21:07:04.000Z
src/hazel/renderer/renderer.hpp
aceiii/hazel-mac
10c61fd9ca371c49828c074ff88a263cb4ee275a
[ "Apache-2.0" ]
null
null
null
src/hazel/renderer/renderer.hpp
aceiii/hazel-mac
10c61fd9ca371c49828c074ff88a263cb4ee275a
[ "Apache-2.0" ]
null
null
null
#pragma once #include "hazel/renderer/orthographic_camera.hpp" #include "hazel/renderer/render_command.hpp" #include "hazel/renderer/renderer_api.hpp" #include "hazel/renderer/shader.hpp" #include "hazel/renderer/vertex_array.hpp" namespace hazel { class Renderer { public: static void init(); static void on_window_resize(uint32_t width, uint32_t height); static void begin_scene(OrthographicCamera&); static void end_scene(); static void submit(const Shader*, const VertexArray*, const glm::mat4& transform = glm::mat4(1.0f)); static inline RendererAPI::API api() { return RendererAPI::api(); } private: struct SceneData { glm::mat4 view_projection_matrix; }; static SceneData* scene_data_; }; } // namespace hazel
21.971429
69
0.728218
[ "transform" ]