hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
d9ef6378ff8a25a2feaa85428776e8cab4a6c3ee
3,621
cpp
C++
libraries/WiFlySerial/Examples/WFSv3/WFSEthernetServer.cpp
ternarylabs/orb
8c89894dc1eabfd99743f16d35786ff354dcc4e5
[ "MIT" ]
2
2017-06-22T16:56:06.000Z
2017-12-14T20:54:14.000Z
src/libraries/WiFlySerial/Examples/WFSv3/WFSEthernetServer.cpp
snrub/big-red-button
dbaaf6969959717de60ad57c933f11e2894621dc
[ "MIT" ]
null
null
null
src/libraries/WiFlySerial/Examples/WFSv3/WFSEthernetServer.cpp
snrub/big-red-button
dbaaf6969959717de60ad57c933f11e2894621dc
[ "MIT" ]
1
2020-05-21T14:00:46.000Z
2020-05-21T14:00:46.000Z
/* * WFSEthernetServer.cpp * Arduino Ethernet Server class for wifi devices * Based on Arduino 1.0 EthernetServer class * * Credits: * First to the Arduino Ethernet team for their model upon which this is based. * Modifications: * Copyright GPL 2.1 Tom Waldock 2012 Version 1.07 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "WiFlySerial.h" #include "WFSsocket.h" extern "C" { #include "string.h" } #include "WFSEthernet.h" #include "WFSEthernetClient.h" #include "WFSEthernetServer.h" WFSEthernetServer::WFSEthernetServer(uint16_t port) { _port = port; } // begin // Sets basics for device configuration void WFSEthernetServer::begin() { char bufRequest[COMMAND_BUFFER_SIZE]; wifi.SendCommand( (char*) F("set u m 0x1") ,WiFlyFixedPrompts[WIFLY_MSG_PROMPT], bufRequest, COMMAND_BUFFER_SIZE); wifi.SendCommand( (char*) F("set comm idle 30") ,WiFlyFixedPrompts[WIFLY_MSG_PROMPT], bufRequest, COMMAND_BUFFER_SIZE); wifi.SendCommand( (char*) F("set comm time 1000") ,WiFlyFixedPrompts[WIFLY_MSG_PROMPT], bufRequest, COMMAND_BUFFER_SIZE); wifi.SendCommand( (char*) F("set comm size 255") ,WiFlyFixedPrompts[WIFLY_MSG_PROMPT], bufRequest, COMMAND_BUFFER_SIZE); } // setProfile // Configures server to respond in manner specified // Assumes wifi device is semi-automnous. // // Parameters: // serverProfile bit-mapped flag of profile options long WFSEthernetServer::setProfile(long serverProfile) { char bufRequest[SMALL_COMMAND_BUFFER_SIZE]; // Defaults as according to device. // Settings may be residual values from prior saved sessions. if ( serverProfile & ES_DEVICE_DEFAULT) { // Set to default somehow (factory reset?) } if ( serverProfile & ES_HTTP_SERVER ) { // No *HELLO* on connection - confuses browsers wifi.SendCommand( (char*) F("set comm remote 0") ,WiFlyFixedPrompts[WIFLY_MSG_PROMPT], bufRequest, SMALL_COMMAND_BUFFER_SIZE); // Send packet on each tab character issued wifi.SendCommand( (char*) F("set comm match 0x9") ,WiFlyFixedPrompts[WIFLY_MSG_PROMPT], bufRequest, SMALL_COMMAND_BUFFER_SIZE); } // Telnet response setup if ( serverProfile & ES_TELNET_SERVER) { } // UDP not implemented yet on CS libraries if ( serverProfile & ES_UDP_SERVER ) { } return serverProfile; } void WFSEthernetServer::accept() { int listening = 0; wifi.serveConnection(); } // returns a WFSEthernetClient using an available socket. // WiFly has one socket so ... use it. WFSEthernetClient WFSEthernetServer::available() { accept(); WFSEthernetClient client(_port); return client; // return WFSEthernetClient(MAX_SOCK_NUM); } size_t WFSEthernetServer::write(uint8_t b) { return write(&b, 1); } size_t WFSEthernetServer::write(const uint8_t *buffer, size_t size) { return wifi.write(buffer, size); }
28.289063
133
0.719967
ternarylabs
d9f26db61de0feadeb15def7a7c52cc7681c21e0
671
cpp
C++
1002.cpp
WhiteDOU/LeetCode
47fee5bfc74c1417a17e6bc426a356ce9864d2b2
[ "MIT" ]
1
2019-03-07T13:08:06.000Z
2019-03-07T13:08:06.000Z
1002.cpp
WhiteDOU/LeetCode
47fee5bfc74c1417a17e6bc426a356ce9864d2b2
[ "MIT" ]
null
null
null
1002.cpp
WhiteDOU/LeetCode
47fee5bfc74c1417a17e6bc426a356ce9864d2b2
[ "MIT" ]
null
null
null
class Solution { public: vector<string> commonChars(vector<string> &A) { int mem[100][27]; vector<string> ans; for (int i = 0; i < 100; ++i) { for (int j = 0; j < 27; ++j) { mem[i][j] = 0; } } for (int i = 0; i < A.size(); ++i) { for (int j = 0; j < A[i].length(); ++j) { char temp = A[i][j]; mem[i][temp - 'a' + 1]++; } } for (int j = 1; j <= 26; ++j) { int Min = 1000; for (int i = 0; i < A.size(); ++i) { Min = min(Min, mem[i][j]); } char temp = 'a' - 1 + j; string input; input = input + temp; for (int i = 0; i < Min; ++i) { ans.push_back(input); } } return ans; } };
15.25
46
0.435171
WhiteDOU
d9f35e6d4889e81b956f3e104f23722883ad65eb
6,971
cc
C++
unittest/core_engine_wide_and_deep_executor_test.cc
ComputationalAdvertising/openmi
1d986ada6c57fecf482f4b8dc4d2488cb0189a3e
[ "Apache-2.0" ]
null
null
null
unittest/core_engine_wide_and_deep_executor_test.cc
ComputationalAdvertising/openmi
1d986ada6c57fecf482f4b8dc4d2488cb0189a3e
[ "Apache-2.0" ]
null
null
null
unittest/core_engine_wide_and_deep_executor_test.cc
ComputationalAdvertising/openmi
1d986ada6c57fecf482f4b8dc4d2488cb0189a3e
[ "Apache-2.0" ]
null
null
null
#include <unordered_set> #include "executor.h" #include "session.h" #include "attr_value_utils.h" #include "base/protobuf_op.h" #include "base/logging.h" #include "openmi/idl/proto/engine.pb.h" #include "openmi/idl/proto/communication.pb.h" using namespace openmi; Tensor* GetTensor(Executor& exec, std::string name) { Tensor* t = nullptr; Status status = exec.GetSessionState()->GetTensor(name, &t); CHECK(t != nullptr) << "tensor not found from session state. name: " << name; return t; } void InitColEmbedding(Tensor** t, std::vector<uint64_t>& batch_dims, const int rank, float v) { TensorShape shape(batch_dims); (*t)->AllocateTensor(shape); (*t)->tensor<float, 2>().setConstant(v); DLOG(INFO) << "placeholder variable:\n" << (*t)->tensor<float, 2>(); } void FillFeatureWeight(Tensor** t, std::vector<uint64_t>& batch_dims, int colid, float v) { TensorShape shape(batch_dims); (*t)->AllocateTensor(shape); (*t)->tensor<float, 2>().setConstant(v); LOG(INFO) << __FUNCTION__ << " colid[" << colid << "] feature weight:\n" << (*t)->tensor<float, 2>(); } void FillFeatureValue(Tensor** t, std::vector<uint64_t>& batch_dims, int colid, float v) { TensorShape shape(batch_dims); (*t)->AllocateTensor(shape); (*t)->tensor<float, 2>().setConstant(v); LOG(INFO) << __FUNCTION__ << " colid[" << colid << "] feature value:\n" << (*t)->tensor<float, 2>(); } void FillRowOffset(Tensor** t, std::vector<uint64_t>& batch_dims, int colid, int max_offset) { typedef int32_t T; TensorShape shape(batch_dims); (*t)->AllocateTensor(shape); (*t)->vec<T>().setConstant(1); for (int i = 0; i < batch_dims[0]; ++i) { int offset = (i == batch_dims[0] - 1) ? max_offset : i+1; (*t)->vec<T>()(i) = offset; } LOG(INFO) << __FUNCTION__ << " colid[" << colid << "], row offset:\n" << (*t)->vec<T>(); } void Iter(Executor& exec, int batch_size) { LOG(INFO) << "================= [placeholder embedding] weigth/value/offset ================= \n"; LOG(INFO) << "batch_size[" << batch_size << "]. update feature weight/value/offset."; int value_size = batch_size * 2; int embedding_size = 8; std::vector<uint64_t> weight_dims; weight_dims.push_back(value_size); weight_dims.push_back(embedding_size); Tensor* embed_c1 = GetTensor(exec, "embed_c1"); Tensor* embed_c2 = GetTensor(exec, "embed_c2"); FillFeatureWeight(&embed_c1, weight_dims, 1, 0.1); FillFeatureWeight(&embed_c2, weight_dims, 2, 0.2); weight_dims[1] = 1; Tensor* x_c1 = GetTensor(exec, "x_c1"); Tensor* x_c2 = GetTensor(exec, "x_c2"); FillFeatureValue(&x_c1, weight_dims, 1, 0.1); FillFeatureValue(&x_c2, weight_dims, 2, 0.2); std::vector<uint64_t> offset_dims; offset_dims.push_back(batch_size); //offset_dims.push_back(1); Tensor* row_offset_c1 = GetTensor(exec, "row_offset_c1"); Tensor* row_offset_c2 = GetTensor(exec, "row_offset_c2"); FillRowOffset(&row_offset_c1, offset_dims, 1, value_size); FillRowOffset(&row_offset_c2, offset_dims, 2, value_size); LOG(INFO) << "================= [placeholder linear] ================= \n"; std::vector<uint64_t> linear_batch_dims; linear_batch_dims.push_back(batch_size); linear_batch_dims.push_back(1L); Tensor* c1_linear = GetTensor(exec, "c1_linear"); Tensor* c3_linear = GetTensor(exec, "c3_linear"); InitColEmbedding(&c1_linear, linear_batch_dims, 2, 0.0001); InitColEmbedding(&c3_linear, linear_batch_dims, 2, 0.0003); LOG(INFO) << "================= [label] ================= \n"; int num_label_dim = 1; Tensor* label = GetTensor(exec, "label"); std::vector<uint64_t> label_dims; label_dims.push_back(batch_size); label_dims.push_back(num_label_dim); TensorShape lshape(label_dims); label->AllocateTensor(lshape); label->tensor<float, 2>().setConstant(1); label->tensor<float, 2>()(0, 0) = 0; DLOG(INFO) << "label:\n" << label->tensor<float, 2>(); LOG(INFO) << "================= [w_layer1] ================= \n"; Tensor* w = GetTensor(exec, "w_layer1"); w->tensor<float, 2>().setConstant(0.03); DLOG(INFO) << "Variable(w_layer1):\n" << w->tensor<float, 2>(); LOG(INFO) << "================= [b_layer1] ================= \n"; Tensor* b = GetTensor(exec, "b_layer1"); b->vec<float>().setConstant(0.00002); DLOG(INFO) << "Variable(b_layer1):\n" << b->vec<float>(); // 2. forward & backword LOG(INFO) << "================= [exec.run] ================= \n"; Status s = exec.Run(); LOG(INFO) << "================= [after run. get grad info] ================= \n"; for (Node* node: exec.GetGraph()->reversed_variable_nodes()) { std::string grad_node_name = node->def().name(); std::string related_node_name = node->related_node_name(); Tensor* grad = GetTensor(exec, grad_node_name); LOG(INFO) << "grad node:" << grad_node_name << ", related_node_name:" << related_node_name; LOG(INFO) << "value:\n" << grad->matrix<float>(); LOG(INFO) << "its shape: " << grad->shape().DebugString(); } LOG(DEBUG) << "done"; } void VariableGradTest(std::unordered_map<std::string, Tensor*>& node2tensor_) { LOG(INFO) << "all valid source node."; for (auto it = node2tensor_.begin(); it != node2tensor_.end(); it++) { LOG(INFO) << "node: " + it->first << ", shape: " << it->second->shape().DebugString(); } } int main(int argc, char** argv) { const char* file = "unittest/conf/wide_and_deep_graph_demo.conf"; LOG(INFO) << "file: " << file; proto::GraphDef gdef; if (ProtobufOp::LoadObjectFromPbFile<proto::GraphDef>(file, &gdef) != 0) { LOG(ERROR) << "load graph def proto file failed."; return -1; } LOG(INFO) << "load graph file done."; Session sess; if (sess.Init(gdef) != 0) { LOG(ERROR) << "session init failed."; return -1; } LOG(INFO) << "session init done."; Executor* exec = sess.GetExecutor().get(); // int batch_size = 5; // Iter(*exec, batch_size); // Iter(*exec, batch_size*2); InstancesPtr instances = std::make_shared<proto::Instances>(); std::unordered_map<uint64_t, proto::comm::ValueList> model_weights; int batch_size = 5; for (int i = 0; i < batch_size; ++i) { auto ins1 = instances->add_instance(); ins1->mutable_label()->add_labels(i % 2 == 0 ? 1 : 0); int f_size = 10; for (int j = 0; j < f_size; ++j) { auto f = ins1->add_feature(); f->set_colid(j); f->set_weight((j+1)*0.1); uint64_t fid = (j*1000 + j); f->set_fid(fid); auto f2 = ins1->add_feature(); f2->set_colid(j); f2->set_weight((j+1)*0.1 + 0.1); auto fid2 = fid + 1; f2->set_fid(fid2); proto::comm::ValueList val_list; for (int k = 0; k < 9; ++k) { val_list.add_val(j*0.1); } model_weights.insert({fid, val_list}); model_weights.insert({fid2, val_list}); } } sess.Run(instances, true); // 1. 获取所有的SourceNode节点 (理应包括所有的reversed variable node) LOG(DEBUG) << "done"; return 0; }
34.855
103
0.619136
ComputationalAdvertising
d9fa341332c3fe9081905474b42b48e22e5b3d8d
1,440
cpp
C++
Assignment 2/main.cpp
John-Ghaly88/ProgrammingIII_CPP_Course
4a6d37d192d0035e07771e7586308623a3f28377
[ "MIT" ]
null
null
null
Assignment 2/main.cpp
John-Ghaly88/ProgrammingIII_CPP_Course
4a6d37d192d0035e07771e7586308623a3f28377
[ "MIT" ]
null
null
null
Assignment 2/main.cpp
John-Ghaly88/ProgrammingIII_CPP_Course
4a6d37d192d0035e07771e7586308623a3f28377
[ "MIT" ]
null
null
null
// make sure you include your own header file with the righ name . // make sure you implement the methods using the same signature as the assignment #include <iostream> #include "dlist.h" #include "dlist.cpp" using namespace std; int main(int argc, char* argv[]) { DList queue; initializeDList(queue); //insert 5 values for (int i = 1; i <= 5; i++) { cout << "put: " << 10 * i << endl; put(queue, 10 * i); } cout<<"______________________________________________________________________________"<<endl; //remove 3 values and print them to console for (int j = 1; j <= 3; j++) { int value; if (get(queue, value)) cout << " get: " << value << endl; } cout<<""<<endl; cout << "Length: " << dlistLength(queue) << endl; cout<<"______________________________________________________________________________"<<endl; //insert 5 values for (int i = 6; i <= 10; i++) { cout << "put: " << 10 * i << endl; put(queue, 10 * i); } cout<<""<<endl; cout << "Length: " << dlistLength(queue) << endl; cout<<"______________________________________________________________________________"<<endl; //remove all values and print them while(!isEmpty(queue)) { int value; get(queue, value); cout << " get: " << value << endl; } cout<<"______________________________________________________________________________"<<endl; cin.sync(); cin.get(); return 0; }
26.666667
97
0.647222
John-Ghaly88
d9fd9a2e05f7dfc05a1523451347f594e202ba1b
1,617
cpp
C++
ReduceSum/main_cuda.cpp
qiao-bo/halide-app-private
e78f90d6346c03e84199356aab08110381bac6a5
[ "MIT" ]
null
null
null
ReduceSum/main_cuda.cpp
qiao-bo/halide-app-private
e78f90d6346c03e84199356aab08110381bac6a5
[ "MIT" ]
null
null
null
ReduceSum/main_cuda.cpp
qiao-bo/halide-app-private
e78f90d6346c03e84199356aab08110381bac6a5
[ "MIT" ]
null
null
null
#include <iostream> #include <limits> #include "Halide.h" #include "halide_benchmark.h" #define WIDTH 65536 #define USE_AUTO using namespace Halide; using namespace Halide::Tools; class PipelineClass { public: Func output; Buffer<int> input; PipelineClass(Buffer<int> in) : input(in) { // Parallel reduction: summation output() = 0; RDom r(0, WIDTH); output() = output() + input(r.x); } bool test_performance() { target = get_host_target(); target.set_feature(Target::CUDA); if (!target.has_gpu_feature()) { return false; } #ifdef USE_AUTO Pipeline p(output); p.auto_schedule(target); output.compile_jit(target); printf("Using auto-scheduler...\n"); #else output.compute_root(); output.compile_jit(target); printf("Computing from root...\n"); #endif // The equivalent C is: int c_ref = 0; for (int y = 0; y < WIDTH; y++) { c_ref += input(y); } input.copy_to_device(target); double best_time = benchmark(10, 5, [&]() { Buffer<int> out = output.realize(); out.copy_to_host(); out.device_sync(); }); printf("Halide time (best): %gms\n", best_time * 1e3); return true; } private: Var x; Target target; }; int main(int argc, char **argv) { const int width = WIDTH; // Initialize with random data Buffer<int> input(width); for (int x = 0; x < input.width(); x++) { input(x) = rand() & 0xfff; } printf("Running Halide pipeline...\n"); PipelineClass pipe(input); if (!pipe.test_performance()) { printf("Scheduling failed\n"); } return 0; }
19.719512
58
0.619048
qiao-bo
d9ffa7a99ce2696459ad8e7b2b4f86b83c223b6d
438
cpp
C++
MoravaEngine/src/Mono/ConsoleGameLib/RandomWord.cpp
imgui-works/MoravaEngine_opengl_vulkan_2d_3d_game_engine
b8e6ee3c3c890e9b8cf5de7bcb564b32f6767b6b
[ "Apache-2.0" ]
168
2020-07-18T04:20:27.000Z
2022-03-31T23:39:38.000Z
MoravaEngine/src/Mono/ConsoleGameLib/RandomWord.cpp
imgui-works/MoravaEngine_opengl_vulkan_2d_3d_game_engine
b8e6ee3c3c890e9b8cf5de7bcb564b32f6767b6b
[ "Apache-2.0" ]
5
2020-11-23T12:33:06.000Z
2022-01-05T15:15:30.000Z
MoravaEngine/src/Mono/ConsoleGameLib/RandomWord.cpp
dtrajko/MoravaEngine
dab8a9e84bde6bdb5e979596c29cabccb566b9d4
[ "Apache-2.0" ]
8
2020-09-07T03:04:18.000Z
2022-03-25T13:47:16.000Z
#include "RandomWord.h" #include "RWord.h" #include <cstdlib> const char* CGL::getRandomWord() { // Word is null at begining const char* word = nullptr; // Get random value CGL_internal::RWord* ptrWord = CGL_internal::RWord::get(); if (ptrWord) { // Compute random value unsigned int randomValue = rand() % ptrWord->getWordCount(); // Load word word = ptrWord->getWord(randomValue); } // Return word return word; }
17.52
62
0.678082
imgui-works
8a015aaf02070aa5ab41f54da4b423aceab25dd1
1,018
cpp
C++
samples/snippets/cpp/VS_Snippets_CLR_Classic/classic ArrayList Example/CPP/source.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
421
2018-04-01T01:57:50.000Z
2022-03-28T15:24:42.000Z
samples/snippets/cpp/VS_Snippets_CLR_Classic/classic ArrayList Example/CPP/source.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
5,797
2018-04-02T21:12:23.000Z
2022-03-31T23:54:38.000Z
samples/snippets/cpp/VS_Snippets_CLR_Classic/classic ArrayList Example/CPP/source.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
1,482
2018-03-31T11:26:20.000Z
2022-03-30T22:36:45.000Z
// <Snippet1> using namespace System; using namespace System::Collections; void PrintValues( IEnumerable^ myList ); int main() { // Creates and initializes a new ArrayList. ArrayList^ myAL = gcnew ArrayList; myAL->Add( "Hello" ); myAL->Add( "World" ); myAL->Add( "!" ); // Displays the properties and values of the ArrayList. Console::WriteLine( "myAL" ); Console::WriteLine( " Count: {0}", myAL->Count ); Console::WriteLine( " Capacity: {0}", myAL->Capacity ); Console::Write( " Values:" ); PrintValues( myAL ); } void PrintValues( IEnumerable^ myList ) { IEnumerator^ myEnum = myList->GetEnumerator(); while ( myEnum->MoveNext() ) { Object^ obj = safe_cast<Object^>(myEnum->Current); Console::Write( " {0}", obj ); } Console::WriteLine(); } /* This code produces output similar to the following: myAL Count: 3 Capacity: 4 Values: Hello World ! */ // </Snippet1>
22.622222
62
0.586444
hamarb123
8a06805a3233bdb9a497400bef9eae588661a939
7,956
cc
C++
planner/predicate.cc
MiaoDragon/planet
54238a892ddf78ac3327665f4c6859681c6d4142
[ "MIT" ]
7
2020-10-11T08:23:42.000Z
2022-03-03T10:23:55.000Z
planner/predicate.cc
MiaoDragon/planet
54238a892ddf78ac3327665f4c6859681c6d4142
[ "MIT" ]
null
null
null
planner/predicate.cc
MiaoDragon/planet
54238a892ddf78ac3327665f4c6859681c6d4142
[ "MIT" ]
1
2020-06-17T21:03:46.000Z
2020-06-17T21:03:46.000Z
#include <stdexcept> #include "cspace.hh" #include "fmt/format.h" #include "predicate.hh" #include "predicate-impl.hh" constexpr char TRACEBACK_NAME[] = "err_func"; static int traceback(lua_State* L) { // 'message' not a string? if (!lua_isstring(L, 1)) { return 1; // Keep it intact } lua_getfield(L, LUA_GLOBALSINDEX, "debug"); if (!lua_istable(L, -1)) { lua_pop(L, 1); return 1; } lua_getfield(L, -1, "traceback"); if (!lua_isfunction(L, -1)) { lua_pop(L, 2); return 1; } lua_pushvalue(L, 1); // Pass error message lua_pushinteger(L, 2); // Skip this function and traceback lua_call(L, 2, 1); // Call debug.traceback return 1; } static int wrap_exceptions(lua_State* L, lua_CFunction f) { try { return f(L); // Call wrapped function and return result. } catch (const char* s) { // Catch and convert exceptions. lua_pushstring(L, s); } catch (std::exception& e) { lua_pushstring(L, e.what()); } catch (...) { lua_pushliteral(L, "caught (...)"); } return lua_error(L); // Rethrow as a Lua error. } namespace symbolic::predicate { const structures::object::ObjectSet* objects = nullptr; const structures::object::ObjectSet* obstacles = nullptr; namespace cspace = planner::cspace; namespace { void load_c_fns(lua_State* L) { lua_pushcfunction(L, traceback); lua_setglobal(L, TRACEBACK_NAME); #ifdef DEBUG_LUA lua_pushlightuserdata(L, reinterpret_cast<void*>(wrap_exceptions)); luaJIT_setmode(L, -1, LUAJIT_MODE_WRAPCFUNC | LUAJIT_MODE_ON); lua_pop(L, 1); #endif load_metatables(L); load_math_lib(L); } } // namespace bool LuaEnv<bool>::call(const spec::Formula& formula, const Map<Str, Str>& bindings, structures::scenegraph::Graph* const sg, const ob::State* const state, const ob::StateSpace* const space, const bool base_movable) { setup_world<double>(formula, bindings, sg); Transform3r base_tf; const auto& state_vec = generate_state_vector(space, state, base_movable); const double* const cont_vals = &(*state_vec.begin()) + (base_movable ? 4 : 0); const double* const joint_vals = cont_vals + planner::cspace::cont_joint_idxs.size(); if (base_movable) { make_base_tf(state_vec, base_tf); } sg->update_transforms(cont_vals, joint_vals, base_tf, [&](const structures::scenegraph::Node* const node, const bool new_value, const Transform3r& pose, const Transform3r& coll_pose) { update_object(node->name, pose); }); const bool result = call_formula<bool>(formula); teardown_world(formula); return result; } Vec<double> generate_state_vector(const ob::StateSpace* const space, const ob::State* const state, const bool base_movable) { // The state vector has the form [robot base pose (if it exists), continuous joints, other // joints] Vec<double> result(cspace::num_dims); // Separate out the state spaces for dimension and index information auto full_space = space->as<ob::CompoundStateSpace>(); auto robot_space = full_space->getSubspace(cspace::ROBOT_SPACE)->as<ob::CompoundStateSpace>(); const auto cstate = state->as<ob::CompoundState>(); const auto& robot_state = cstate->as<ob::CompoundState>(full_space->getSubspaceIndex(cspace::ROBOT_SPACE)); int offset = 0; if (base_movable) { auto robot_base_state = robot_state->as<cspace::RobotBaseSpace::StateType>( robot_space->getSubspaceIndex(cspace::BASE_SPACE)); // NOTE: This is only valid because we're only getting pose. Could be cleaner, too result[0] = robot_base_state->getX(); result[1] = robot_base_state->getY(); result[2] = robot_base_state->getZ(); const ob::SO2StateSpace::StateType& base_rotation = robot_base_state->rotation(); result[3] = base_rotation.value; offset += 4; } const auto& joint_state = robot_state->as<cspace::RobotJointSpace::StateType>( robot_space->getSubspaceIndex(cspace::JOINT_SPACE)); for (size_t i = 0; i < cspace::cont_joint_idxs.size(); ++i) { const auto idx = cspace::cont_joint_idxs[i]; result[offset + i] = robot_state->as<ob::SO2StateSpace::StateType>(idx)->value; } offset += cspace::cont_joint_idxs.size(); for (size_t i = 0; i < cspace::joint_bounds.size(); ++i) { result[offset + i] = joint_state->values[i]; } return result; } LuaEnvData::LuaEnvData(const Str& name, const Str& prelude_filename) : name(name) { log = spdlog::stdout_color_st(fmt::format("lua-{}", name)); L = luaL_newstate(); luaL_openlibs(L); load_c_fns(L); if (!prelude_filename.empty()) { log->debug("Loading prelude from {}", prelude_filename); if (luaL_dofile(L, prelude_filename.c_str()) != 0) { auto err_msg = lua_tostring(L, -1); log->error("Loading prelude from {} failed: {}", prelude_filename, err_msg); throw std::runtime_error("Failed to load Lua prelude!"); } } } bool LuaEnvData::load_predicates(const Str& predicates_filename) const { log->debug("Loading predicates from {}", predicates_filename); if (luaL_dofile(L, predicates_filename.c_str()) != 0) { auto err_msg = lua_tostring(L, -1); log->error("Loading predicates from {} failed: {}", predicates_filename, err_msg); throw std::runtime_error( fmt::format("Failed to load predicates from {}: {}", predicates_filename, err_msg)); } return true; } bool LuaEnvData::load_formula(spec::Formula* formula) const { log->debug("Loading formula: {}", formula->name); if (luaL_dostring(L, formula->normal_def.c_str()) != 0) { auto err_msg = lua_tostring(L, -1); log->error("Loading formula {} failed: {}", formula->name, err_msg); throw std::runtime_error(fmt::format("Failed to load formula {}: {}", formula->name, err_msg)); } lua_getglobal(L, formula->normal_fn_name.c_str()); formula->normal_fn[name] = luaL_ref(L, LUA_REGISTRYINDEX); return true; } void LuaEnvData::teardown_world(const spec::Formula& formula) const { // NOTE: If we for some reason stop making one object/binding (e.g. if there's something weird // with globals), then this is wrong and will cause segfaults lua_pop(L, formula.bindings.size()); } void LuaEnvData::cleanup() const { lua_gc(L, LUA_GCCOLLECT, 0); } int LuaEnvData::call_helper(const spec::Formula& formula, const int start_top) const { init_dn_block(); clear_dn_block(); // Push traceback lua_getglobal(L, TRACEBACK_NAME); const int err_func_idx = lua_gettop(L); // Retrieve the formula function ref - use at() to maintain constness lua_rawgeti(L, LUA_REGISTRYINDEX, formula.normal_fn.at(name)); // Copy the object tables as arguments for (size_t i = 0; i < binding_idx.size(); ++i) { lua_pushvalue(L, start_top - i); } // Call the function ref if (lua_pcall(L, binding_idx.size(), 1, err_func_idx) != 0) { auto err_msg = lua_tostring(L, -1); log->error("Error calling {} for gradient: {}", formula.name, err_msg); int top_idx = lua_gettop(L); lua_pop(L, top_idx - err_func_idx + 1); throw std::runtime_error( fmt::format("Failed to call {} for gradient: {}", formula.name, err_msg)); } return err_func_idx; } void LuaEnvData::cleanup_helper(const int start_top, const int err_func_idx) const { // Pop cruft from the stack: the result table, a, v, err_func int top_idx = lua_gettop(L); lua_pop(L, top_idx - err_func_idx + 1); const auto end_top = lua_gettop(L); if (end_top != start_top) { log->error("Top grew from {} to {}", start_top, end_top); } } } // namespace symbolic::predicate
34.742358
99
0.651081
MiaoDragon
8a0b091ef9904d3ef700368612e82e5e3199c856
338
cpp
C++
C to C++/C to C++ 004/004.cpp
Jasonchan35/SimpleTalkCpp_Tutorial
b193074c25e33e77ce15004a053bcc037054282e
[ "MIT" ]
44
2017-11-08T14:20:55.000Z
2021-03-18T14:22:52.000Z
C to C++/C to C++ 004/004.cpp
Jasonchan35/SimpleTalkCpp_Tutorial
b193074c25e33e77ce15004a053bcc037054282e
[ "MIT" ]
null
null
null
C to C++/C to C++ 004/004.cpp
Jasonchan35/SimpleTalkCpp_Tutorial
b193074c25e33e77ce15004a053bcc037054282e
[ "MIT" ]
19
2017-08-01T12:59:29.000Z
2021-04-11T08:09:59.000Z
#define _CRT_SECURE_NO_WARNINGS #include "Student.h" static void HelperFunc() { printf("main helper"); } int main() { //class (type) a object (instance) Student a("John"); a.print(); a.print(); a.print(); printf("=== Program Ended ===\n"); printf("Press any to key to Exit !"); _getch(); return 0; }
15.363636
39
0.585799
Jasonchan35
8a12ef3f57a57c7bc0255930d13bd156353dbf09
500
hpp
C++
include/CppML/Vocabulary/Value.hpp
changjurhee/CppML
6d4cc6d0dd2fa3055823f191dc7fe953e4966fc5
[ "MIT" ]
48
2019-05-14T10:07:08.000Z
2021-04-08T08:26:20.000Z
include/CppML/Vocabulary/Value.hpp
changjurhee/CppML
6d4cc6d0dd2fa3055823f191dc7fe953e4966fc5
[ "MIT" ]
null
null
null
include/CppML/Vocabulary/Value.hpp
changjurhee/CppML
6d4cc6d0dd2fa3055823f191dc7fe953e4966fc5
[ "MIT" ]
4
2019-11-18T15:35:32.000Z
2021-12-02T05:23:04.000Z
/** * Copyright Žiga Sajovic, XLAB 2019 * Distributed under the MIT License * * https://github.com/ZigaSajovic/CppML **/ #ifndef CPPML_VALUE_HPP #define CPPML_VALUE_HPP namespace ml { /* * Value: * Represents a typed value * */ template <typename T, T t> struct Value { using type = T; static constexpr T value = t; }; template <int N> using Int = Value<int, N>; template <bool N> using Bool = Value<bool, N>; template <char C> using Char = Value<char, C>; }; // namespace ml #endif
17.857143
46
0.674
changjurhee
8a1356ae8ff9ef2c3dfe56fc3070aadc5dcca86d
1,762
cpp
C++
SDK/ARKSurvivalEvolved_Tek_CloningChamber_Placement_Emitter_functions.cpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_Tek_CloningChamber_Placement_Emitter_functions.cpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_Tek_CloningChamber_Placement_Emitter_functions.cpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
// ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_Tek_CloningChamber_Placement_Emitter_parameters.hpp" namespace sdk { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function Tek_CloningChamber_Placement_Emitter.Tek_CloningChamber_Placement_Emitter_C.UserConstructionScript // () void ATek_CloningChamber_Placement_Emitter_C::UserConstructionScript() { static auto fn = UObject::FindObject<UFunction>("Function Tek_CloningChamber_Placement_Emitter.Tek_CloningChamber_Placement_Emitter_C.UserConstructionScript"); ATek_CloningChamber_Placement_Emitter_C_UserConstructionScript_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Tek_CloningChamber_Placement_Emitter.Tek_CloningChamber_Placement_Emitter_C.ExecuteUbergraph_Tek_CloningChamber_Placement_Emitter // () // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void ATek_CloningChamber_Placement_Emitter_C::ExecuteUbergraph_Tek_CloningChamber_Placement_Emitter(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function Tek_CloningChamber_Placement_Emitter.Tek_CloningChamber_Placement_Emitter_C.ExecuteUbergraph_Tek_CloningChamber_Placement_Emitter"); ATek_CloningChamber_Placement_Emitter_C_ExecuteUbergraph_Tek_CloningChamber_Placement_Emitter_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
30.912281
191
0.749716
2bite
8a16c01655e531689e15acb938a2ff977093b8c5
2,772
cc
C++
src/engine/Time.cc
skroon/dsmic-oakfoam
02f9b8ac6eb2b0aa97c461b80337e5273e83153f
[ "BSD-2-Clause" ]
2
2019-08-27T04:18:45.000Z
2021-04-20T23:14:24.000Z
src/engine/Time.cc
skroon/dsmic-oakfoam
02f9b8ac6eb2b0aa97c461b80337e5273e83153f
[ "BSD-2-Clause" ]
null
null
null
src/engine/Time.cc
skroon/dsmic-oakfoam
02f9b8ac6eb2b0aa97c461b80337e5273e83153f
[ "BSD-2-Clause" ]
null
null
null
#include "Time.h" #include "Parameters.h" Time::Time(Parameters *prms, float main, float overtime, int stones) : params(prms), base_main(main), base_overtime(overtime), base_stones(stones) { this->setupTimeForColors(); } Time::Time(Parameters *prms, float main) : params(prms), base_main(main), base_overtime(0), base_stones(0) { this->setupTimeForColors(); } void Time::setupTimeForColors() { if (base_main>0) { black_time_left=base_main; white_time_left=base_main; black_stones_left=0; white_stones_left=0; } else if (this->isCanadianOvertime()) { black_time_left=base_overtime; white_time_left=base_overtime; black_stones_left=base_stones; white_stones_left=base_stones; } else { black_time_left=0; white_time_left=0; black_stones_left=0; white_stones_left=0; } } float *Time::timeLeftForColor(Go::Color col) const { if (col==Go::BLACK) return (float *)&black_time_left; else return (float *)&white_time_left; } int *Time::stonesLeftForColor(Go::Color col) const { if (col==Go::BLACK) return (int *)&black_stones_left; else return (int *)&white_stones_left; } void Time::useTime(Go::Color col, float timeused) { if (timeused>0 && !this->isNoTiming()) { float *timeleft=this->timeLeftForColor(col); *timeleft-=timeused; if (*timeleft<0) // time finished or starting overtime { if (this->isAbsoluteTiming() || this->inOvertime(col)) // time run out *timeleft=1; else // entering overtime { *timeleft+=base_overtime; *(this->stonesLeftForColor(col))=base_stones; } } else if (this->inOvertime(col)) { (*(this->stonesLeftForColor(col)))--; if (*(this->stonesLeftForColor(col))==0) { *timeleft=base_overtime; *(this->stonesLeftForColor(col))=base_stones; } } } } void Time::updateTimeLeft(Go::Color col, float time, int stones) { *(this->timeLeftForColor(col))=time; *(this->stonesLeftForColor(col))=stones; } float Time::getAllocatedTimeForNextTurn(Go::Color col) const { if (this->isNoTiming()) return 0; else { if (this->inOvertime(col)) { float time_per_move=((this->timeLeft(col)-params->time_buffer)/this->stonesLeft(col)); if (time_per_move<params->time_move_minimum) time_per_move=params->time_move_minimum; return time_per_move; } else { float time_left=this->timeLeft(col); time_left-=params->time_buffer; float time_per_move=time_left/params->time_k; //allow much more time in beginning if (time_per_move<params->time_move_minimum) time_per_move=params->time_move_minimum; return time_per_move; } } }
22.536585
92
0.65873
skroon
8a1c02917a8be16ab96fc64890730c6cee695f6a
554
cpp
C++
lib/derived_libs/lib_routines/game_handler.cpp
mrbuzz/Network-Lib
b2a92e69d2446fdd21fa9a4e1d7f96bae2c9b664
[ "MIT" ]
null
null
null
lib/derived_libs/lib_routines/game_handler.cpp
mrbuzz/Network-Lib
b2a92e69d2446fdd21fa9a4e1d7f96bae2c9b664
[ "MIT" ]
null
null
null
lib/derived_libs/lib_routines/game_handler.cpp
mrbuzz/Network-Lib
b2a92e69d2446fdd21fa9a4e1d7f96bae2c9b664
[ "MIT" ]
null
null
null
#include "../../../include/game_handler.h" void * game_handler::run() { game_msg * msg; std::string message; std::cout << "[+] Thread game_handler running " << self() << "\n"; for(int i = 0; ;i++) { msg = _msg_pool.remove(); message = msg->get_message(); game_player * user = msg->get_dest(); if(strcmp(message.c_str(),"EXIT") == 0) { std::cout << "[-] Thread game_handler " << self() << " terminating execution "<< "\n"; pthread_exit(NULL); } else user->send_message(message); } return NULL; }
19.785714
87
0.563177
mrbuzz
8a1ca7667f1c19acb49674d2687a78694185d17d
12,724
cpp
C++
Common/network/src/socket_manager.cpp
deeptexas-ai/test
f06b798d18f2d53c9206df41406d02647004ce84
[ "MIT" ]
4
2021-10-20T09:18:06.000Z
2022-03-27T05:08:26.000Z
Common/network/src/socket_manager.cpp
deeptexas-ai/test
f06b798d18f2d53c9206df41406d02647004ce84
[ "MIT" ]
1
2021-11-05T03:28:41.000Z
2021-11-06T07:48:05.000Z
Common/network/src/socket_manager.cpp
deeptexas-ai/test
f06b798d18f2d53c9206df41406d02647004ce84
[ "MIT" ]
1
2021-12-13T16:04:22.000Z
2021-12-13T16:04:22.000Z
/** * \file socket_manager.cpp * \brief 网络套接字管理类函数的实现 */ #include "pch.h" #include "socket_manager.h" #include "shstd.h" #include "system.pb.h" using namespace shstd::hashmap; /*#define SM_MAX_CONNECT_CNT (65000) //支持的最大连接数 static uint32 SMSocketHash(const int32 &nSock) { return (uint32)nSock; }*/ namespace network { /** * \brief 构造函数 */ CSocketManager::CSocketManager(void) { //m_pEventBase = NULL; } /** * \brief 析构函数 */ CSocketManager::~CSocketManager(void) { Release(); } /** * \brief 创建 * \param pEventBase 事件根基 * \return 创建成功返回true,否则返回false */ bool CSocketManager::Init(uint32 nLocalServerID, uint32 nTcpTimeOut, uint32 nSocketCnt, uint8 nLimitedLogEnable) { m_nLimitedLogEnable = nLimitedLogEnable; m_nSocketCnt = nSocketCnt; if(m_nSocketCnt > 0x7FFFF) { LOG(LT_ERROR, "Socket manager init| check socket count| cnt=%u", m_nSocketCnt); return false; } m_pSocket = new TcpSocket[m_nSocketCnt]; if(NULL == m_pSocket) { LOG(LT_ERROR, "Socket manager init| new tcp socket failed"); return false; } for(uint32 i = 0; i < m_nSocketCnt; i++) { m_pSocket[i].SetSocketManager(this); } m_nLocalServerID = nLocalServerID; m_nTcpTimeOut = nTcpTimeOut; LOG(LT_INFO, "Socket manager init succ| socket_cnt=%u| limited_log_enable=%d", m_nSocketCnt, m_nLimitedLogEnable); return true; } /** * \brief 释放 */ void CSocketManager::Release() { for(uint32 i = 0; i < m_nSocketCnt; i++) { m_pSocket[i].CloseConnect(); } } /** * \brief 开启服务器监听服务 * \param szAddr 监听IP地址 * \param nPort 监听端口 * \param pHandler 回调对象 * \return 开启成功返回true,失败返回false */ bool CSocketManager::Listen(const char *szAddr, uint16 nPort, bool bBinaryMode) { sockid nSockID = Socket::GlobalSocket(SOCK_STREAM, IPPROTO_TCP); if (nSockID <= 0) { LOG(LT_ERROR, "Socket manager listen failed| msg=%s", strerror(errno)); return false; } else if((uint32)nSockID >= m_nSocketCnt) { LOG(LT_ERROR, "Socket manager listen| exceed socket| fd=%d", nSockID); close(nSockID); return false; } TcpSocket &oListener = m_pSocket[nSockID]; bool bSuccess = false; do { // 创建 if (!oListener.Create(nSockID)) { break; } // 保持连接 if (!oListener.SetKeepAlive(true)) { break; } // 不粘包 if (!oListener.SetNoDelay(true)) { break; } // 非阻塞模式 if (!oListener.SetNonBlock()) { break; } // 延时关闭 if (!oListener.SetLinger()) { break; } // 可重复使用 if (!oListener.SetReuse(true)) { break; } // 绑定 if (!oListener.Bind(szAddr, nPort)) { break; } // 开始监听 if (!oListener.Listen()) { break; } oListener.SetSocketHandler(NULL, bBinaryMode); CNotifyFd oNotify(NOTIFY_TYPE_LISTEN, oListener.GetSockID(), szAddr, nPort, "", 0, bBinaryMode, NULL); if(!CNetWorker::Instance()->GetAcceptThread()->PushNotifyFd(oNotify)) { LOG(LT_ERROR, "Listen failed| errno=%d| errmsg=%s|", errno, strerror(errno)); break; } bSuccess = true; } while (false); // 利用循环来处理判断 // 开启失败,关闭socket if (!bSuccess) { oListener.Close(); //不能调用Release, 导致多线程使用同一个event_base, 引起core return false; } LOG(LT_INFO, "Socket manager listen succ| fd=%d", oListener.GetSockID()); return true; } /** * \brief 连接服务器 * \param szAddr 服务器IP地址 * \param nPort 服务器端口 * \param pHandler 回调对象 * \return 连接成功返回true,失败返回false */ bool CSocketManager::Connect(const char *szAddr, uint16 nPort, ISocketHandler *pHandler, bool bBinaryMode) { sockid nSockID = Socket::GlobalSocket(SOCK_STREAM, IPPROTO_TCP); if (nSockID <= 0) { LOG(LT_ERROR, "Socket manager connect failed| msg=%s", strerror(errno)); return false; } else if((uint32)nSockID >= m_nSocketCnt) { LOG(LT_ERROR, "Socket manager connect| exceed socket| fd=%d", nSockID); close(nSockID); return false; } CNotifyFd oNotify(NOTIFY_TYPE_CONNECT, nSockID, "", 0, szAddr, nPort, bBinaryMode, pHandler); if(!CNetWorker::Instance()->GetDataThread(nSockID)->PushNotifyFd(oNotify)) { LOG(LT_ERROR, "Socket manager accept new| notify failed| fd=%d| remote_addr=%s:%d| binary_mode=%d", nSockID, oNotify.m_szRemoteAddr, oNotify.m_nRemotePort, oNotify.m_bBinaryMode ); } else { LOG(LT_INFO, "Socket manager new connect| fd=%d| remote_addr=%s:%d| binary_mode=%d", nSockID, oNotify.m_szRemoteAddr, oNotify.m_nRemotePort, oNotify.m_bBinaryMode ); } return true; } /** * \brief 发送数据给单个连接对象 * \param pMsg 消息数据 * \param nLen 数据大小 * \param nRemoteFd 指定发送连接对象ID * \return 发送成功返回true,否则返回false */ void CSocketManager::Send(LISTSMG *p) { if(NULL == p) { return; } TcpSocket *pSocket = NULL; if(PKT_TYPE_DISCARD == p->cPacketType) { LOG(LT_INFO_TRANS, p->szTransID, "Socket manager send discard packet| fd=%d| unique_id=0x%x| pkt_type=%d", p->connfd, p->nUniqueID, p->cPacketType); } else if(NULL == (pSocket = GetTcpSocket(p->connfd))) { LOG(LT_ERROR_TRANS, p->szTransID, "Socket manager send| find socket failed| fd=%d| unique_id=0x%x", p->connfd, p->nUniqueID); } else if(!pSocket->SendMsg(p)) { LOG(LT_ERROR_TRANS, p->szTransID, "Socket manager send| do failed| fd=%d| unique_id=0x%x", p->connfd, p->nUniqueID); } CQUEUE_List::Instance()->SetNode(p, QUEUE_FREE); return; } /** * \brief 获得连接信息 * \param nFd 连接对象ID * \param strAddr 返回连接对象IP地址 * \param nPort 返回连接对象端口 * \param bLocal 是否获取本地连接信息 * \return 获取成功返回true,否则返回false */ bool CSocketManager::GetConnectInfo(int32 nFd, std::string &strAddr, uint16 &nPort) { TcpSocket *pSocket = GetTcpSocket(nFd); if (NULL == pSocket) { return false; } if(!pSocket->IsAcceptFd()) { strAddr = pSocket->GetLocalAddr(); nPort = pSocket->GetLocalPort(); } else { strAddr = pSocket->GetRemoteAddr(); nPort = pSocket->GetRemotePort(); } return true; } /** * \brief 设置连接对象消息回调 * \param nFd 连接ID * \param pHandler 回调对象 * \param bPkgLen 收发消息处理长度 */ void CSocketManager::SetSocketHandler(int32 nFd, ISocketHandler *pHandler, bool bPkgLen /*= true*/) { TcpSocket *pSocket = GetTcpSocket(nFd); if (NULL != pSocket) { pSocket->SetSocketHandler(pHandler, bPkgLen); } } /** * \brief 判断指定连接是否处于连接状态 * \param nFd 连接ID * \return 连接中返回true,否则返回false */ bool CSocketManager::IsValidConnected(int32 nFd, uint32 nUniqueID) { TcpSocket *pSocket = GetTcpSocket(nFd); if (NULL == pSocket) { return false; } if (!pSocket->IsValid()) { return false; } if(pSocket->GetUniqueID() != nUniqueID) { return false; } return true; } /** * \brief 关闭指定连接 * \param nFd 连接对象ID * \return 成功关闭返回true,否则返回false */ bool CSocketManager::CloseConnect(int32 nFd)//, uint32 nUniqueID) { TcpSocket *pSocket = GetTcpSocket(nFd); if (NULL == pSocket) { return false; } /*else if(pSocket->GetUniqueID() != nUniqueID) { LOG(LT_ERROR, "Socket manager close check unique_id failed| fd=%d| close_unique_id=0x%x| unique_id=0x%x", nUniqueID, pSocket->GetUniqueID()); return false; }*/ pSocket->CloseConnect(); return true; } //获取连接的下一个TransID std::string CSocketManager::GetNextTransID(int32 nFd) { TcpSocket *pSocket = GetTcpSocket(nFd); if (NULL == pSocket) { return std::string(""); } return pSocket->NextTransID(); } //设置注册ID bool CSocketManager::SetRemoteServerID(int32 nFd, uint32 nRemoteServerID) { TcpSocket *pSocket = GetTcpSocket(nFd); if (NULL == pSocket) { return false; } pSocket->SetRemoteServerID(nRemoteServerID); return true; } /** * \brief 关闭所有连接 */ void CSocketManager::CloseAllConnect() { Lock l(&m_lock); for(uint32 i = 0; i < m_nSocketCnt; i++) { TcpSocket &oSocket = m_pSocket[i]; if(Socket::SOCK_STATE_LISTEN != oSocket.GetState()) { oSocket.CloseConnect(); } } } /** * \brief 获得连接 * \param nFd 连接ID * \return 连接对象 */ TcpSocket * CSocketManager::GetTcpSocket(int32 nFd) { if(nFd < 0 || (uint32)nFd >= m_nSocketCnt) { return NULL; } return &m_pSocket[nFd]; } /** * \brief 接收到新连接 * \param pListener 监听连接 * \return 新连接对象 */ void CSocketManager::OnAccept(TcpSocket *pListener) { assert(NULL != pListener); // 使用新的连接对象准备连接 sockaddr_in addrRemote; sockid nSockID = Socket::GlobalAccept(pListener->GetSockID(), addrRemote); if (nSockID <= 0) { LOG(LT_ERROR, "Socket manager accept failed| msg=%s", strerror(errno)); return ; } else if((uint32)nSockID >= m_nSocketCnt) { LOG(LT_ERROR, "Socket manager accept| exceed socket| fd=%d", nSockID); close(nSockID); return; } CNotifyFd oNotify(NOTIFY_TYPE_ACCEPT, nSockID, pListener->GetLocalAddr().c_str(), pListener->GetLocalPort(), inet_ntoa(addrRemote.sin_addr), ntohs(addrRemote.sin_port), pListener->GetBinaryMode(), NULL); if(!CNetWorker::Instance()->GetDataThread(nSockID)->PushNotifyFd(oNotify)) { LOG(LT_ERROR, "Socket manager accept new| notify failed| fd=%d| remote_addr=%s:%d| binary_mode=%d", nSockID, oNotify.m_szRemoteAddr, oNotify.m_nRemotePort, oNotify.m_bBinaryMode ); close(nSockID); return; } LOG(LT_INFO, "Socket manager accept new socket| fd=%d| local_addr=%s:%d| remote_addr=%s:%d| binary_mode=%d", nSockID, oNotify.m_szLocalAddr, oNotify.m_nLocalPort, oNotify.m_szRemoteAddr, oNotify.m_nRemotePort, oNotify.m_bBinaryMode ); return; } /** * \brief 连接成功事件 * \param pSocket 连接成功的对象 * \return 成功返回true,否则返回false */ bool CSocketManager::OnConnect(TcpSocket *pSocket) { /*if (NULL == pSocket) { return false; } SERVERKEY sk(m_nLocalServerID); pSocket->SetUniqueID(GetSequence()); pSocket->SetTransID(sk.nType, sk.nInstID); */ return true; } /** * \brief 连接断开事件 * \param pSocket 断开连接的对象 * \return 成功返回true,否则返回false */ bool CSocketManager::OnClose(TcpSocket *pSocket) { if (NULL == pSocket) { return false; } LOG(LT_INFO, "Socket manager on close| fd=%d", pSocket->GetSockID()); return true; } uint32 CSocketManager::GetSequence() { uint32 nTime = time(NULL)%0xFFFF; Lock l(&m_lock); ++m_nSequence; return ((nTime << 16) + m_nSequence); } }
26.675052
160
0.530729
deeptexas-ai
8a1d20103c9724b90310138603b0ce1c0f513824
473
cpp
C++
Week16/790.cpp
bobsingh149/LeetCode
293ed4931960bf5b9a3d5c4331ba4dfddccfcd55
[ "MIT" ]
101
2021-02-26T14:32:37.000Z
2022-03-16T18:46:37.000Z
Week16/790.cpp
bobsingh149/LeetCode
293ed4931960bf5b9a3d5c4331ba4dfddccfcd55
[ "MIT" ]
null
null
null
Week16/790.cpp
bobsingh149/LeetCode
293ed4931960bf5b9a3d5c4331ba4dfddccfcd55
[ "MIT" ]
30
2021-03-09T05:16:48.000Z
2022-03-16T21:16:33.000Z
class Solution { public: int numTilings(int n) { vector<long long> dp (n+1, 0); long long modulo=1000000007; dp[0]=1; dp[1]=1; for(int i=2; i<=n; i++){ dp[i]+=dp[i-1]; dp[i]%=modulo; dp[i]+=dp[i-2]; dp[i]%=modulo; for(int j=i-3; j>=0; j--){ dp[i]+=(2*dp[j]); dp[i]%=modulo; } } return dp[n]; } };
21.5
38
0.353066
bobsingh149
8a1e9c7a13fae2780526246fc2ed172f58ee3855
21,884
cpp
C++
super-knowledge-platform/skpServer/trunk/src/core/skpEvent.cpp
yefy/skp
a9fafa09eacd6a0a802ea6550efd30ace79e4a4f
[ "MIT" ]
null
null
null
super-knowledge-platform/skpServer/trunk/src/core/skpEvent.cpp
yefy/skp
a9fafa09eacd6a0a802ea6550efd30ace79e4a4f
[ "MIT" ]
null
null
null
super-knowledge-platform/skpServer/trunk/src/core/skpEvent.cpp
yefy/skp
a9fafa09eacd6a0a802ea6550efd30ace79e4a4f
[ "MIT" ]
null
null
null
#include "skpEvent.h" #include "skpEvent_p.h" #include "skpMallocPoolEx.h" #include "skpAutoFree.h" #include "skpLog.h" #define EPOLL_EVENT_LT 0 ///全部LT #define EPOLL_EVENT_ET 1 ///全部ET #define EPOLL_EVENT_LT_ET 2 ///LT ET一起支持 #define EPOLL_EVENT_TYPE EPOLL_EVENT_LT_ET #define NODE_TYPE_MAP 0 ///即使申请 #define NODE_TYPE_NODE 1 ///固定申请 #define NODE_TYPE_MORE 2 ///变长申请 #define NODE_TYPE NODE_TYPE_MORE #define IS_CHECK_ERROR 0 SkpEventPrivate::SkpEventPrivate() : SkpObjectDataPrivate() { skp_event_base_new(); } SkpEventPrivate::~SkpEventPrivate() { skp_event_base_free(); } void SkpEventPrivate::skp_event_base_new() { m_base.m_epfd = epoll_create(32000); SKP_ASSERT(m_base.m_epfd != -1); m_base.m_nodeSize = 0; m_base.m_nodeList = NULL; m_base.m_nodeChangeList = new SkpList(); m_base.m_nodeReadyList = new SkpList(); m_base.pool = new SkpMallocPoolEx(1024 * 1024); m_isThread = skp_false; } void SkpEventPrivate::skp_event_base_free() { ::close(m_base.m_epfd); skp_delete(m_base.m_nodeChangeList); skp_delete(m_base.m_nodeReadyList); m_base.m_nodeSize = 0; m_base.m_nodeList = NULL; skp_delete(m_base.pool); } void SkpEventPrivate::skp_event_base_loop() { skp_change_event(); int64 timer = 100; if(m_base.m_nodeReadyList->size() > 0) { timer = 0; } int nevents = 0; nevents = epoll_wait(m_base.m_epfd, m_base.m_events, sizeof(m_base.m_events) / sizeof(struct epoll_event), timer); if(!m_isThread) { skp_update_system_time_ms(skp_true); } for(int i = 0; i < nevents; ++i) { struct epoll_event *epollEvent = &m_base.m_events[i]; skp_epoll_node *node = (skp_epoll_node *)epollEvent->data.ptr; if ((epollEvent->events & (EPOLLERR|EPOLLHUP)) && (epollEvent->events & (EPOLLIN|EPOLLOUT)) == 0) { epollEvent->events |= EPOLLIN|EPOLLOUT; node->m_errorNumber++; } if(node->m_flags == EPOLLET) { skp_add_ready_node(node); if(epollEvent->events & EPOLLIN) { node->m_read.m_ready = 1; node->m_read.m_readyNumber++; } if(epollEvent->events & EPOLLOUT) { node->m_write.m_ready = 1; node->m_write.m_readyNumber++; } } else { if(epollEvent->events & EPOLLIN) { skp_epoll_data *read = &node->m_read; skp_event_callback(read); } if(epollEvent->events & EPOLLOUT) { skp_epoll_data *write = &node->m_write; skp_event_callback(write); } } } skp_ready_callback(); skp_min_tbtree(); } void SkpEventPrivate::skp_change_event() { skp_epoll_node *node = NULL; while((node = skp_remove_change_node())) { uint flags = 0; int op = 0; struct epoll_event ee; bool isDeleteNode = skp_false; if(node->m_read.m_state == skp::epoll_state_null && node->m_write.m_state == skp::epoll_state_null) { op = EPOLL_CTL_DEL; node->m_read.m_active = 0; node->m_write.m_active = 0; node->m_read.m_ready = 0; node->m_write.m_ready = 0; isDeleteNode = skp_true; } if(op != EPOLL_CTL_DEL) { if(node->m_read.m_active || node->m_write.m_active) { op = EPOLL_CTL_MOD; } else { op = EPOLL_CTL_ADD; } } if(node->m_read.m_state == skp::epoll_state_start) { flags |= EPOLLIN; node->m_read.m_active = skp_true; } else { node->m_read.m_ready = 0; } if(node->m_write.m_state == skp::epoll_state_start) { flags |= EPOLLOUT; node->m_write.m_active = skp_true; } else { node->m_write.m_ready = 0; } if(!node->m_read.m_ready && !node->m_write.m_ready) { skp_remove_ready_node(node); } flags |= node->m_flags; if(op != EPOLL_CTL_DEL) { if(node->m_oldFlags && node->m_oldFlags == flags) continue; node->m_oldFlags = flags; ee.events = flags; ee.data.ptr = node; } else { node->m_oldFlags = 0; ee.events = 0; ee.data.ptr = NULL; } int ret = epoll_ctl(m_base.m_epfd, op, node->m_fd, &ee); skpLogDebug_g("epoll change fd = %d, ret = %d\n", node->m_fd, ret); if(ret == -1) { if (op == EPOLL_CTL_MOD && errno == ENOENT) { skpLogError_g("epoll change EPOLL_CTL_ADD \n"); ret = epoll_ctl(m_base.m_epfd, EPOLL_CTL_ADD, node->m_fd, &ee); } else if (op == EPOLL_CTL_ADD && errno == EEXIST) { skpLogError_g("epoll change EPOLL_CTL_MOD \n"); ret = epoll_ctl(m_base.m_epfd, EPOLL_CTL_MOD, node->m_fd, &ee); } if(op != EPOLL_CTL_DEL) SKP_ASSERT(ret != -1); } if(isDeleteNode) { skp_remove_ready_node(node); skp_reset_node(node); } } } void SkpEventPrivate::skp_ready_callback() { if(!m_base.m_nodeReadyList->isEmpty()) { m_base.m_nodeReadyList->begin(); void *data = NULL; while((data = m_base.m_nodeReadyList->data())) { skp_epoll_node *node = (skp_epoll_node *)data; if(node->m_read.m_ready) { skp_epoll_data *read = &node->m_read; skp_event_callback(read); } if(node->m_write.m_ready) { skp_epoll_data *write = &node->m_write; skp_event_callback(write); } m_base.m_nodeReadyList->next(); if(!node->m_read.m_ready && !node->m_write.m_ready) { skp_remove_ready_node(node); } } } } void SkpEventPrivate::skp_event_callback(skp_epoll_data *data) { if(data->m_fd > 0 && (data->m_state == skp::epoll_state_start)) { data->m_callbackNumber++; data->m_updateTime = skp_get_system_time_ms(); if(!data->m_singleShot) { skp_delete_timeout(data); skp_event_delete(data); } (*(data->m_func))(data->m_fd, skp_false, data->m_arg); } } void SkpEventPrivate::skp_min_tbtree() { util_rbtree_node_t *rbNode = NULL; while((rbNode = m_base.m_rbtree.min()) && rbNode && rbNode->key <= skp_get_system_time_ms()) { skp_epoll_data *data = (skp_epoll_data *)rbNode->data; if(data->m_type != skp::epoll_type_timeout) { int64 key = data->m_rbNode->key; int64 updateTime = data->m_updateTime; int64 diff = key - updateTime; if(diff < 0) diff = 0; if(diff >= data->m_time) { skp_delete_timeout(data); if(data->m_singleShot) { skp_insert_timeout(data, data->m_time); } else { skp_event_delete(data); } if(data->m_fd > 0 && (data->m_state == skp::epoll_state_start)) { (*(data->m_func))(data->m_fd, skp_true, data->m_arg); } } else { int64 time = data->m_time - diff; skp_delete_timeout(data); skp_insert_timeout(data, time); data->m_updateTime = updateTime; } } else { skp_delete_timeout(data); if(data->m_singleShot) skp_insert_timeout(data, data->m_time); (*(data->m_func))(data->m_fd, skp_true, data->m_arg); } } } void SkpEventPrivate::skp_event_base_dispatch() { } void *SkpEventPrivate::skp_event_base_timeout(int64 time, skp_callback_function func, void *arg, bool singleShot) { SKP_ASSERT(time > 0); skp_epoll_data *timeout = skp_malloc_data(); timeout->m_type = skp::epoll_type_timeout; timeout->m_state = skp::epoll_state_start; timeout->m_time = time; timeout->m_func = func; timeout->m_arg = arg; timeout->m_singleShot = singleShot; skp_add_timeout(timeout); return timeout; } void *SkpEventPrivate::skp_event_base_read(int fd, skp_callback_function func, void *arg, bool singleShot, int64 time, bool isET) { skp_epoll_node *epollNode = skp_malloc_node(fd); if(epollNode->m_fd != 0 && epollNode->m_fd != fd) { SKP_ASSERT(skp_false); } SKP_ASSERT(epollNode->m_read.m_fd == 0); if(epollNode->m_fd == 0) { skp_reset_node(epollNode); epollNode->m_fd = fd; } if(EPOLL_EVENT_TYPE == EPOLL_EVENT_LT) { epollNode->m_flags = 0; } else if(EPOLL_EVENT_TYPE == EPOLL_EVENT_ET) { epollNode->m_flags = EPOLLET; } else if(EPOLL_EVENT_TYPE == EPOLL_EVENT_LT_ET) { if(isET) { epollNode->m_flags = EPOLLET; } } else { SKP_ASSERT(skp_false); } skp_add_change_node(epollNode); skp_epoll_data *read = &epollNode->m_read; read->m_type = skp::epoll_type_read; read->m_state = skp::epoll_state_start; read->m_fd = fd; read->m_time = time; read->m_func = func; read->m_arg = arg; read->m_singleShot = singleShot; skp_add_timeout(read); return read; } void *SkpEventPrivate::skp_event_base_write(int fd, skp_callback_function func, void *arg, bool singleShot, int64 time, bool isET) { skp_epoll_node *epollNode = skp_malloc_node(fd); if(epollNode->m_fd != 0 && epollNode->m_fd != fd) { SKP_ASSERT(skp_false); } SKP_ASSERT(epollNode->m_write.m_fd == 0); if(epollNode->m_fd == 0) { skp_reset_node(epollNode); epollNode->m_fd = fd; } if(EPOLL_EVENT_TYPE == EPOLL_EVENT_LT) { epollNode->m_flags = 0; } else if(EPOLL_EVENT_TYPE == EPOLL_EVENT_ET) { epollNode->m_flags = EPOLLET; } else if(EPOLL_EVENT_TYPE == EPOLL_EVENT_LT_ET) { if(isET) { epollNode->m_flags = EPOLLET; } } else { SKP_ASSERT(skp_false); } skp_add_change_node(epollNode); skp_epoll_data *write = &epollNode->m_write; write->m_type = skp::epoll_type_write; write->m_state = skp::epoll_state_start; write->m_fd = fd; write->m_time = time; write->m_func = func; write->m_arg = arg; write->m_singleShot = singleShot; skp_add_timeout(write); return write; } #define IS_ADD_TIMEOUT 0 void SkpEventPrivate::skp_event_delete(void *data) { skp_epoll_data *event = (skp_epoll_data *)data; SKP_ASSERT(event); SKP_ASSERT(event->m_type >= skp::epoll_type_timeout && event->m_type <= skp::epoll_type_write); if(event->m_type == skp::epoll_type_timeout) { skp_sub_timeout(event); } else { if(event->m_state != skp::epoll_state_stop) skp_change_node(event, skp::epoll_state_stop); #if IS_ADD_TIMEOUT skp_delete_timeout(event); #endif } } void SkpEventPrivate::skp_event_free(void *data) { skp_epoll_data *event = (skp_epoll_data *)data; SKP_ASSERT(event); SKP_ASSERT(event->m_type >= skp::epoll_type_timeout && event->m_type <= skp::epoll_type_write); if(event->m_type == skp::epoll_type_timeout) { skp_delete_timeout(event); skp_free_data(event); } else { if(event->m_state != skp::epoll_state_null) skp_change_node(event, skp::epoll_state_null); skp_delete_timeout(event); } } void SkpEventPrivate::skp_event_start(void *data, int64 time) { skp_epoll_data *event = (skp_epoll_data *)data; SKP_UNUSED(time); SKP_ASSERT(event); SKP_ASSERT(event->m_type >= skp::epoll_type_timeout && event->m_type <= skp::epoll_type_write); if(event->m_type == skp::epoll_type_timeout) { skp_add_timeout(event); } else { if(event->m_state != skp::epoll_state_start) skp_change_node(event, skp::epoll_state_start); #if IS_ADD_TIMEOUT skp_add_timeout(event); #else if(event->m_time != time) { printf("event->m_time != time \n"); skp_delete_timeout(event); event->m_time = time; skp_add_timeout(event); } else { event->m_updateTime = skp_get_system_time_ms(); } #endif } } void SkpEventPrivate::skp_add_timeout(skp_epoll_data *event) { SKP_ASSERT(event); SKP_ASSERT(!event->m_rbNode); skp_insert_timeout(event, event->m_time); } void SkpEventPrivate::skp_sub_timeout(skp_epoll_data *event) { SKP_ASSERT(event); SKP_ASSERT(event->m_rbNode); skp_delete_timeout(event); } void SkpEventPrivate::skp_insert_timeout(skp_epoll_data *event, int64 time) { if(event->m_time > 0 && !event->m_rbNode) { event->m_updateTime = skp_get_system_time_ms(); int64 msec = skp_rbtree_time(event, time); util_rbtree_node_t *rbNode = m_base.m_rbtree.insert(msec, event); event->m_rbNode = rbNode; } } void SkpEventPrivate::skp_delete_timeout(skp_epoll_data *event) { if(event->m_rbNode) { m_base.m_rbtree.remove(event->m_rbNode); event->m_rbNode = NULL; } } int64 SkpEventPrivate::skp_rbtree_time(skp_epoll_data *event, int64 time) { SKP_UNUSED(event); int64 msec = time + skp_get_system_time_ms(); return msec; } bool SkpEventPrivate::skp_is_delete_timeout(skp_epoll_data *event) { if(event->m_rbNode) { int64 msec = skp_rbtree_time(event, event->m_time); if(msec != event->m_rbNode->key) return skp_true; } return skp_false; } void SkpEventPrivate::skp_change_node(skp_epoll_data *event, skp::epoll_state state) { skp_epoll_node *epollNode = event->m_node; if(!epollNode) { SKP_ASSERT(skp_false);; } skp_add_change_node(epollNode); event->m_state = state; } skp_epoll_data *SkpEventPrivate::skp_malloc_data() { skp_epoll_data *data = (skp_epoll_data *)skp_pool_calloc(m_base.pool, sizeof(skp_epoll_data)); return data; } skp_epoll_node *SkpEventPrivate::skp_malloc_node() { skp_epoll_node *node = (skp_epoll_node *)skp_pool_calloc(m_base.pool, sizeof(skp_epoll_node)); return node; } skp_epoll_node *SkpEventPrivate::skp_malloc_node(int fd) { if (NODE_TYPE == NODE_TYPE_MAP) { skp_epoll_node *epollNode = NULL; auto iter = m_base.m_nodeMap.find(fd); if(iter != m_base.m_nodeMap.end()) { epollNode = iter->second; } else { epollNode = skp_malloc_node(); m_base.m_nodeMap.insert(std::pair<int, skp_epoll_node*>(fd, epollNode)); } return epollNode; } int size = m_base.m_nodeSize; if(m_base.m_nodeSize == 0) { if (NODE_TYPE == NODE_TYPE_NODE) { m_base.m_nodeSize = 1000; } else if (NODE_TYPE == NODE_TYPE_MORE) { m_base.m_nodeSize = 10000; } else { SKP_ASSERT(skp_false); return skp_null; } } if(fd >= m_base.m_nodeSize) { while(fd >= m_base.m_nodeSize) m_base.m_nodeSize = (m_base.m_nodeSize * 2); } if(m_base.m_nodeSize > size) { skp_epoll_node **nodeList = (skp_epoll_node **)skp_pool_calloc(m_base.pool, sizeof(skp_epoll_node *) * m_base.m_nodeSize); if(size > 0) { memcpy(nodeList, m_base.m_nodeList, sizeof(skp_epoll_node *) * size); skp_pool_free(m_base.pool, m_base.m_nodeList); } m_base.m_nodeList = nodeList; skp_epoll_node *node = (skp_epoll_node *)skp_pool_calloc(m_base.pool, sizeof(skp_epoll_node) * (m_base.m_nodeSize - size)); int lenth = m_base.m_nodeSize - size; for(int i = 0; i < lenth; i++) { m_base.m_nodeList[i + size] = &node[i]; } } return m_base.m_nodeList[fd]; } void SkpEventPrivate::skp_free_data(skp_epoll_data *data) { if(data) { skp_pool_free(m_base.pool, data); } } void SkpEventPrivate::skp_free_node(skp_epoll_node *node) { if(node) { skp_pool_free(m_base.pool, node); } } void SkpEventPrivate::skp_reset_node(skp_epoll_node *node) { memset(node, 0x00, sizeof(skp_epoll_node)); node->m_read.m_node = node; node->m_write.m_node = node; } bool SkpEventPrivate::skp_add_change_node(skp_epoll_node *node) { SKP_ASSERT(node); if(!node->m_isChange) { node->m_isChange = skp_true; m_base.m_nodeChangeList->push_back(node, &node->m_nodeChange); return skp_true; } else { if(IS_CHECK_ERROR) { m_base.m_nodeChangeList->begin(); void *data = NULL; while((data = m_base.m_nodeChangeList->data())) { skp_epoll_node *tempNode = (skp_epoll_node *)data; if(tempNode == node) return skp_false; m_base.m_nodeChangeList->next(); } SKP_ASSERT(skp_false); } } return skp_false; } skp_epoll_node *SkpEventPrivate::skp_remove_change_node() { if(m_base.m_nodeChangeList && !m_base.m_nodeChangeList->isEmpty()) { skp_epoll_node *node = (skp_epoll_node *)m_base.m_nodeChangeList->take_pop(); node->m_isChange = !node->m_isChange; return node; } return NULL; } void SkpEventPrivate::skp_add_ready_node(skp_epoll_node *node) { SKP_ASSERT(node); if(!node->m_isReady) { node->m_isReady = skp_true; m_base.m_nodeReadyList->push_pop(node, &node->m_nodeReady); } else { if(IS_CHECK_ERROR) { m_base.m_nodeReadyList->begin(); void *data = NULL; while((data = m_base.m_nodeReadyList->data())) { skp_epoll_node *tempNode = (skp_epoll_node *)data; if(tempNode == node) return; m_base.m_nodeReadyList->next(); } SKP_ASSERT(skp_false); } } } void SkpEventPrivate::skp_remove_ready_node(skp_epoll_node *node) { SKP_ASSERT(node); if(node->m_isReady) { if(IS_CHECK_ERROR) { m_base.m_nodeReadyList->begin(); void *data = NULL; while((data = m_base.m_nodeReadyList->data())) { skp_epoll_node *tempNode = (skp_epoll_node *)data; if(tempNode == node) break; m_base.m_nodeReadyList->next(); } if(!data) { SKP_ASSERT(skp_false); } } node->m_isReady = skp_false; m_base.m_nodeReadyList->remove(&node->m_nodeReady); } } void SkpEventPrivate::removeReadReady(void *data) { skp_epoll_data *event = (skp_epoll_data *)data; if(event) { skp_epoll_node *node = event->m_node; if(node) node->m_read.m_ready = 0; } } void SkpEventPrivate::addReadReady(void *data) { skp_epoll_data *event = (skp_epoll_data *)data; if(event) { skp_epoll_node *node = event->m_node; if(node) { skp_add_ready_node(node); node->m_read.m_ready = 1; } } } void SkpEventPrivate::skp_set_event_thread() { m_isThread = skp_true; } ///===========================SkpEvent SkpEvent::SkpEvent(SkpEventPrivate &d) : SkpObjectData(d) { } SkpEvent::~SkpEvent() { } void SkpEvent::loop() { SKP_D(SkpEvent); skpD->skp_event_base_loop(); } void SkpEvent::dispatch() { SKP_D(SkpEvent); skpD->skp_event_base_dispatch(); } void *SkpEvent::timeout(int64 time, skp_callback_function func, void *arg, bool singleShot) { SKP_D(SkpEvent); return skpD->skp_event_base_timeout(time, func, arg, singleShot); } void *SkpEvent::read(int fd, skp_callback_function func, void *arg, bool singleShot, int64 time, bool isET) { SKP_D(SkpEvent); return skpD->skp_event_base_read(fd, func, arg, singleShot, time, isET); } void * SkpEvent::write(int fd, skp_callback_function func, void *arg, bool singleShot, int64 time, bool isET) { SKP_D(SkpEvent); return skpD->skp_event_base_write(fd, func, arg, singleShot, time, isET); } void SkpEvent::stop(void *data) { SKP_D(SkpEvent); skpD->skp_event_delete(data); } void SkpEvent::free(void *data) { SKP_D(SkpEvent); skpD->skp_event_free(data); } void SkpEvent::start(void *data, int64 time) { SKP_D(SkpEvent); skpD->skp_event_start(data, time); } void SkpEvent::skp_break() { SKP_D(SkpEvent); skpD->skp_event_break(); } void *SkpEvent::skp_base() { SKP_D(SkpEvent); return skpD->skp_base(); } void SkpEvent::removeReadReady(void *data) { SKP_D(SkpEvent); skpD->removeReadReady(data); } void SkpEvent::addReadReady(void *data) { SKP_D(SkpEvent); skpD->addReadReady(data); } void SkpEvent::skp_set_event_thread() { SKP_D(SkpEvent); skpD->skp_set_event_thread(); }
27.218905
132
0.57919
yefy
8a21221e1ef0da6055b2f4d76c99b02d78331233
5,042
cpp
C++
source/AsioExpress/MessagePort/Ipc/IpcMessagePort.cpp
suhao/asioexpress
2f3453465934afdcdf4a575a2d933d86929b23c7
[ "BSL-1.0" ]
null
null
null
source/AsioExpress/MessagePort/Ipc/IpcMessagePort.cpp
suhao/asioexpress
2f3453465934afdcdf4a575a2d933d86929b23c7
[ "BSL-1.0" ]
null
null
null
source/AsioExpress/MessagePort/Ipc/IpcMessagePort.cpp
suhao/asioexpress
2f3453465934afdcdf4a575a2d933d86929b23c7
[ "BSL-1.0" ]
null
null
null
// Copyright Ross MacGregor 2013 // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include "AsioExpress/pch.hpp" #include "AsioExpressConfig/config.hpp" #include "AsioExpress/Platform/DebugMessage.hpp" #include "AsioExpress/MessagePort/Ipc/ErrorCodes.hpp" #include "AsioExpress/MessagePort/Ipc/MessagePort.hpp" #include "AsioExpress/MessagePort/Ipc/private/IpcCommandConnect.hpp" #include "AsioExpress/MessagePort/Ipc/private/IpcCommandReceive.hpp" namespace AsioExpress { namespace MessagePort { namespace Ipc { MessagePort::MessagePort(boost::asio::io_service & ioService) : m_ioService(ioService) { } MessagePort::~MessagePort() { Disconnect(); } void MessagePort::Disconnect() { // Before allowing a disconnect, make sure any threads are completed. // if (m_receiveThread) m_receiveThread->Close(); if (m_sendThread) m_sendThread->Close(); // Queues can be just deleted and removed // if ( m_recvMessageQueue ) { m_recvMessageQueue.reset(); } if ( m_sendMessageQueue ) { m_recvMessageQueue.reset(); } // Delete the queues from the system // if ( !m_sendMessageQueueName.empty() ) { boost::interprocess::message_queue::remove(m_sendMessageQueueName.c_str()); m_sendMessageQueueName = ""; } if ( !m_recvMessageQueueName.empty() ) { boost::interprocess::message_queue::remove(m_recvMessageQueueName.c_str()); m_recvMessageQueueName = ""; } } void MessagePort::AsyncConnect( EndPoint endPoint, AsioExpress::CompletionHandler completionHandler) { IpcCommandConnect(endPoint, *this, completionHandler)(); } void MessagePort::AsyncSend( AsioExpress::MessagePort::DataBufferPointer buffer, AsioExpress::CompletionHandler completionHandler) { // Check that we're connected #ifdef DEBUG_IPC DebugMessage("MessagePort::AsyncSend: Sending message.\n"); #endif if ( !m_sendMessageQueue ) { #ifdef DEBUG_IPC DebugMessage("MessagePort::AsyncSend: No connection has been established!\n"); #endif AsioExpress::Error err( ErrorCode::Disconnected, "MessagePort::AsyncSend(): No connection has been established."); AsioExpress::CallCompletionHandler(m_ioService, completionHandler, err); return; } try { // Send the message or fail if queue is full m_sendThread->AsyncSend( buffer, 0, completionHandler); } catch(AsioExpress::CommonException const & e) { // Disconnect on serious send errors (other errors would result in errors // getting propagated back by completion handlers, but the connection still // being active) Disconnect(); // Call completion handler as it will not get called if exception is thrown AsioExpress::CallCompletionHandler(m_ioService, completionHandler, e.GetError()); } } void MessagePort::AsyncReceive( AsioExpress::MessagePort::DataBufferPointer buffer, AsioExpress::CompletionHandler completionHandler) { // Check that we're connected if ( !m_recvMessageQueue ) { AsioExpress::Error err( ErrorCode::Disconnected, "MessagePort::AsyncReceive(): No connection has been established."); AsioExpress::CallCompletionHandler(m_ioService, completionHandler, err); return; } // Receive the next message & copy to the buffer IpcCommandReceive(m_ioService, m_receiveThread, m_recvMessageQueue, buffer, completionHandler, 0)(); } AsioExpress::Error MessagePort::SetupWithMessageQueues(const std::string& sendQueue, const std::string& recvQueue) { Disconnect(); try { m_sendMessageQueueName = sendQueue; m_recvMessageQueueName = recvQueue; m_sendMessageQueue.reset(new boost::interprocess::message_queue(boost::interprocess::open_only, m_sendMessageQueueName.c_str())); m_recvMessageQueue.reset(new boost::interprocess::message_queue(boost::interprocess::open_only, m_recvMessageQueueName.c_str())); m_receiveThread.reset(new IpcReceiveThread(m_ioService, m_recvMessageQueue, IpcReceiveThread::EnablePing)); m_sendThread.reset(new IpcSendThread(m_ioService, m_sendMessageQueue, IpcSendThread::EnablePing)); } catch(boost::interprocess::interprocess_exception& ex) { Disconnect(); AsioExpress::Error err(boost::system::error_code( ex.get_native_error(), boost::system::get_system_category()), "MessagePort::SetupWithMessageQueues(): Unable to open client/server message queues."); return err; } return AsioExpress::Error(); } void MessagePort::SetMessagePortOptions() { } } // namespace Ipc } // namespace MessagePort } // namespace AsioExpress
28.011111
134
0.685244
suhao
8a23faa51086448e9c124cfbce896418e4d8eaf3
31,397
cpp
C++
src/api/jsonutils.cpp
EnyoYoen/Fast-Discord
8d483a87d302370df770d47d311d16e95d6e3951
[ "MIT" ]
30
2021-09-18T15:50:30.000Z
2022-03-25T14:12:57.000Z
src/api/jsonutils.cpp
EnyoYoen/Fast-Discord
3fde017d67f6673205d0e7ff3de7cf2a572a6aec
[ "MIT" ]
3
2021-11-22T11:11:42.000Z
2021-12-11T12:28:26.000Z
src/api/jsonutils.cpp
EnyoYoen/Fast-Discord
8d483a87d302370df770d47d311d16e95d6e3951
[ "MIT" ]
2
2022-01-11T02:50:04.000Z
2022-01-22T14:04:33.000Z
#include "api/jsonutils.h" #include "api/message.h" #include "api/attachment.h" #include "api/user.h" #include "api/overwrite.h" #include "api/channel.h" #include "api/thread.h" #include "api/team.h" #include "api/application.h" #include "api/guildmember.h" #include "api/voice.h" #include "api/guild.h" #include "api/client.h" #include "api/presence.h" #include <string> #include <QJsonObject> namespace Api { std::string *getString(QJsonObject jsonObj, const char *key) { std::string str = jsonObj[QString(key)].toString().toUtf8().constData(); return new std::string(str); } std::vector<std::string> *getStringsFromJson(QJsonArray jsonArray) { std::vector<std::string> *strings = new std::vector<std::string>; // Filling the vector for (int i = 0 ; i < jsonArray.size() ; i++) { strings->push_back(jsonArray[i].toString().toUtf8().constData()); } return strings; } // All the specialization of 'unmarshal' template <> void unmarshal<User>(QJsonObject jsonObj, User **object) { *object = new User { getString(jsonObj, "username"), getString(jsonObj, "discriminator"), getString(jsonObj, "avatar"), getString(jsonObj, "locale"), getString(jsonObj, "email"), getString(jsonObj, "id"), jsonObj["flags"].toInt(-1), jsonObj["premium_type"].toInt(-1), jsonObj["public_flags"].toInt(-1), jsonObj["bot"].toBool(), jsonObj["system"].toBool(), jsonObj["mfa_enabled"].toBool(), jsonObj["verified"].toBool() }; } template <> void unmarshal<Overwrite>(QJsonObject jsonObj, Overwrite **object) { *object = new Overwrite { getString(jsonObj, "id"), getString(jsonObj, "allow"), getString(jsonObj, "deny"), jsonObj["type"].toInt(-1) }; } template <> void unmarshal<ThreadMember>(QJsonObject jsonObj, ThreadMember **object) { *object = new ThreadMember { getString(jsonObj, "join_timestamp"), getString(jsonObj, "id"), getString(jsonObj, "user_id"), jsonObj["flags"].toInt(-1) }; } template <> void unmarshal<ThreadMetadata>(QJsonObject jsonObj, ThreadMetadata **object) { *object = new ThreadMetadata { getString(jsonObj, "archive_timestamp"), jsonObj["auto_archive_duration"].toInt(-1), jsonObj["archived"].toBool(), jsonObj["locked"].toBool() }; } template <> void unmarshal<Channel>(QJsonObject jsonObj, Channel **object) { std::vector<User *> *recipients = new std::vector<User *>; std::vector<Overwrite *> *permissionOverwrites = new std::vector<Overwrite *>; ThreadMember *member = new ThreadMember; ThreadMetadata *threadMetadata = new ThreadMetadata; unmarshalMultiple<User>(jsonObj["recipients"].toArray(), &recipients); unmarshalMultiple<Overwrite>(jsonObj["permission_overwrites"].toArray(), &permissionOverwrites); unmarshal<ThreadMember>(jsonObj["member"].toObject(), &member); unmarshal<ThreadMetadata>(jsonObj["thread_metadata"].toObject(), &threadMetadata); *object = new Channel { recipients, permissionOverwrites, member, threadMetadata, getString(jsonObj, "id"), getString(jsonObj, "name"), getString(jsonObj, "topic"), getString(jsonObj, "icon"), getString(jsonObj, "last_pin_timestamp"), getString(jsonObj, "rtc_region"), getString(jsonObj, "permissions"), getString(jsonObj, "guild_id"), getString(jsonObj, "last_message_id"), getString(jsonObj, "owner_id"), getString(jsonObj, "application_id"), getString(jsonObj, "parent_id"), jsonObj["type"].toInt(-1), jsonObj["position"].toInt(-1), jsonObj["bitrate"].toInt(-1), jsonObj["user_limit"].toInt(-1), jsonObj["rate_limit_per_user"].toInt(-1), jsonObj["video_quality_mode"].toInt(-1), jsonObj["message_count"].toInt(-1), jsonObj["member_count"].toInt(-1), jsonObj["default_auto_archive_duration"].toInt(-1), jsonObj["nsfw"].toBool() }; } template <> void unmarshal<PrivateChannel>(QJsonObject jsonObj, PrivateChannel **object) { *object = new PrivateChannel { getStringsFromJson(jsonObj["recipient_ids"].toArray()), getString(jsonObj, "icon"), getString(jsonObj, "id"), getString(jsonObj, "last_message_id"), getString(jsonObj, "name"), getString(jsonObj, "owner_id"), jsonObj["type"].toInt(-1) }; } template <> void unmarshal<TeamMember>(QJsonObject jsonObj, TeamMember **object) { User *user = new User; unmarshal<User>(jsonObj, "user", &user); *object = new TeamMember { user, getStringsFromJson(jsonObj["permissions"].toArray()), getString(jsonObj, "team_id"), jsonObj["member_ship_state"].toInt(-1) }; } template <> void unmarshal<Team>(QJsonObject jsonObj, Team **object) { std::vector<TeamMember *> *members = new std::vector<TeamMember *>; unmarshalMultiple<TeamMember>(jsonObj, "members", &members); *object = new Team { members, getString(jsonObj, "icon"), getString(jsonObj, "id"), getString(jsonObj, "name"), getString(jsonObj, "owner_user_id") }; } template <> void unmarshal<Application>(QJsonObject jsonObj, Application **object) { User *owner = new User; Team *team = new Team; unmarshal<User>(jsonObj, "owner", &owner); unmarshal<Team>(jsonObj, "team", &team); *object = new Application { owner, team, getStringsFromJson(jsonObj["rpc_origins"].toArray()), getString(jsonObj, "id"), getString(jsonObj, "name"), getString(jsonObj, "icon"), getString(jsonObj, "description"), getString(jsonObj, "terms_of_service_url"), getString(jsonObj, "privacy_policy_url"), getString(jsonObj, "summary"), getString(jsonObj, "verify_key"), getString(jsonObj, "guild_id"), getString(jsonObj, "primary_sku_id"), getString(jsonObj, "slug"), getString(jsonObj, "cover_image"), jsonObj["flags"].toInt(-1), jsonObj["bot_public"].toBool(), jsonObj["bot_require_code_grant"].toBool() }; } template <> void unmarshal<MessageActivity>(QJsonObject jsonObj, MessageActivity **object) { *object = new MessageActivity { getString(jsonObj, "party_id"), jsonObj["type"].toInt(-1) }; } template <> void unmarshal<GuildMessageMember>(QJsonObject jsonObj, GuildMessageMember **object) { *object = new GuildMessageMember { getStringsFromJson(jsonObj["roles"].toArray()), getString(jsonObj, "nick"), getString(jsonObj, "joined_at"), getString(jsonObj, "premium_since"), getString(jsonObj, "permissions"), jsonObj["deaf"].toBool(), jsonObj["mute"].toBool(), jsonObj["pending"].toBool() }; } template <> void unmarshal<MessageInteraction>(QJsonObject jsonObj, MessageInteraction **object) { User *user = new User; unmarshal<User>(jsonObj, "user", &user); *object = new MessageInteraction { user, getString(jsonObj, "id"), getString(jsonObj, "name"), jsonObj["type"].toInt(-1) }; } template <> void unmarshal<Emoji>(QJsonObject jsonObj, Emoji **object) { User *user = new User; unmarshal<User>(jsonObj, "user", &user); *object = new Emoji { user, getStringsFromJson(jsonObj["roles"].toArray()), getString(jsonObj, "id"), getString(jsonObj, "name"), jsonObj["requireColons"].toBool(), jsonObj["managed"].toBool(), jsonObj["animated"].toBool(), jsonObj["available"].toBool() }; } template <> void unmarshal<Reaction>(QJsonObject jsonObj, Reaction **object) { Emoji *emoji = new Emoji; unmarshal<Emoji>(jsonObj, "emoji", &emoji); *object = new Reaction { emoji, jsonObj["count"].toInt(-1), jsonObj["me"].toBool() }; } template <> void unmarshal<EmbedField>(QJsonObject jsonObj, EmbedField **object) { *object = new EmbedField { getString(jsonObj, "name"), getString(jsonObj, "value"), jsonObj["inline"].toBool() }; } template <> void unmarshal<EmbedFooter>(QJsonObject jsonObj, EmbedFooter **object) { *object = new EmbedFooter { getString(jsonObj, "text"), getString(jsonObj, "icon_url"), getString(jsonObj, "proxy_icon_url"), }; } template <> void unmarshal<EmbedTVI>(QJsonObject jsonObj, EmbedTVI **object) { *object = new EmbedTVI { getString(jsonObj, "url"), getString(jsonObj, "proxy_url"), jsonObj["height"].toInt(-1), jsonObj["width"].toInt(-1) }; } template <> void unmarshal<EmbedProvider>(QJsonObject jsonObj, EmbedProvider **object) { *object = new EmbedProvider { getString(jsonObj, "name"), getString(jsonObj, "url"), }; } template <> void unmarshal<EmbedAuthor>(QJsonObject jsonObj, EmbedAuthor **object) { *object = new EmbedAuthor { getString(jsonObj, "name"), getString(jsonObj, "url"), getString(jsonObj, "icon_url"), getString(jsonObj, "proxy_icon_url") }; } template <> void unmarshal<Embed>(QJsonObject jsonObj, Embed **object) { std::vector<EmbedField *> *fields = new std::vector<EmbedField *>; EmbedFooter *footer = new EmbedFooter; EmbedTVI *image = new EmbedTVI; EmbedTVI *thumbnail = new EmbedTVI; EmbedTVI *video = new EmbedTVI; EmbedProvider *provider = new EmbedProvider; EmbedAuthor *author = new EmbedAuthor; unmarshalMultiple<EmbedField>(jsonObj, "fields", &fields); unmarshal<EmbedFooter>(jsonObj, "footer", &footer); unmarshal<EmbedTVI>(jsonObj, "image", &image); unmarshal<EmbedTVI>(jsonObj, "thumbnail", &thumbnail); unmarshal<EmbedTVI>(jsonObj, "video", &video); unmarshal<EmbedProvider>(jsonObj, "provider", &provider); unmarshal<EmbedAuthor>(jsonObj, "author", &author); *object = new Embed { fields, footer, image, thumbnail, video, provider, author, getString(jsonObj, "title"), getString(jsonObj, "type"), getString(jsonObj, "description"), getString(jsonObj, "url"), getString(jsonObj, "timestamp"), jsonObj["color"].toInt(-1) }; } template <> void unmarshal<Attachment>(QJsonObject jsonObj, Attachment **object) { *object = new Attachment { getString(jsonObj, "id"), getString(jsonObj, "filename"), getString(jsonObj, "content_type"), getString(jsonObj, "url"), getString(jsonObj, "proxy_url"), jsonObj["size"].toInt(-1), jsonObj["height"].toInt(-1), jsonObj["width"].toInt(-1) }; } template <> void unmarshal<ChannelMention>(QJsonObject jsonObj, ChannelMention **object) { *object = new ChannelMention { getString(jsonObj, "id"), getString(jsonObj, "guild_id"), getString(jsonObj, "name"), jsonObj["type"].toInt(-1) }; } template <> void unmarshal<SelectOption>(QJsonObject jsonObj, SelectOption **object) { Emoji *emoji = new Emoji; unmarshal<Emoji>(jsonObj, "emoji", &emoji); *object = new SelectOption { emoji, getString(jsonObj, "label"), getString(jsonObj, "value"), getString(jsonObj, "description"), jsonObj["default"].toBool() }; } template <> void unmarshal<MessageComponent>(QJsonObject jsonObj, MessageComponent **object) { Emoji *emoji = new Emoji; std::vector<SelectOption *> *components = new std::vector<SelectOption *>; unmarshal<Emoji>(jsonObj, "emoji", &emoji); unmarshalMultiple<SelectOption>(jsonObj, "components", &components); *object = new MessageComponent { emoji, components, nullptr, getString(jsonObj, "custom_id"), getString(jsonObj, "label"), getString(jsonObj, "url"), getString(jsonObj, "placeholder"), jsonObj["type"].toInt(-1), jsonObj["style"].toInt(-1), jsonObj["min_values"].toInt(-1), jsonObj["max_values"].toInt(-1), jsonObj["disabled"].toBool() }; } template <> void unmarshal<StickerItem>(QJsonObject jsonObj, StickerItem **object) { *object = new StickerItem { getString(jsonObj, "id"), getString(jsonObj, "name"), jsonObj["format_type"].toInt(-1) }; } template <> void unmarshal<Sticker>(QJsonObject jsonObj, Sticker **object) { User *user = new User; unmarshal<User>(jsonObj, "user", &user); *object = new Sticker { user, getString(jsonObj, "id"), getString(jsonObj, "pack_id"), getString(jsonObj, "name"), getString(jsonObj, "description"), getString(jsonObj, "tags"), getString(jsonObj, "asset"), getString(jsonObj, "guild_id"), jsonObj["type"].toInt(-1), jsonObj["format_type"].toInt(-1), jsonObj["sort_value"].toInt(-1), jsonObj["available"].toBool() }; } Message *getPartialMessage(QJsonObject jsonObj, const QString& key) { Application *application = new Application; User *author = new User; MessageActivity *activity = new MessageActivity; GuildMessageMember *member = new GuildMessageMember; Channel *thread = new Channel; MessageInteraction *interaction = new MessageInteraction; std::vector<Reaction *> *reactions = new std::vector<Reaction *>; std::vector<User *> *mentions = new std::vector<User *>; std::vector<Attachment *> *attachments = new std::vector<Attachment *>; std::vector<ChannelMention *> *mentionChannels = new std::vector<ChannelMention *>; std::vector<MessageComponent *> *components = new std::vector<MessageComponent *>; std::vector<StickerItem *> *stickerItems = new std::vector<StickerItem *>; std::vector<Sticker *> *stickers = new std::vector<Sticker *>; unmarshal<Application>(jsonObj, "application", &application); unmarshal<User>(jsonObj, "author", &author); unmarshal<MessageActivity>(jsonObj, "activity", &activity); unmarshal<GuildMessageMember>(jsonObj, "member", &member); unmarshal<Channel>(jsonObj, "thread", &thread); unmarshal<MessageInteraction>(jsonObj, "interaction", &interaction); unmarshalMultiple<Reaction>(jsonObj, "reactions", &reactions); unmarshalMultiple<User>(jsonObj, "mentions", &mentions); unmarshalMultiple<Attachment>(jsonObj, "attachments", &attachments); unmarshalMultiple<ChannelMention>(jsonObj, "mention_channels", &mentionChannels); unmarshalMultiple<MessageComponent>(jsonObj, "components", &components); unmarshalMultiple<StickerItem>(jsonObj, "sticker_items", &stickerItems); unmarshalMultiple<Sticker>(jsonObj, "stickers", &stickers); if (key == QString("") && jsonObj[key].type() == QJsonValue::Undefined) { return nullptr; } jsonObj = key == QString("") ? jsonObj : jsonObj[key].toObject(); return new Message { application, author, activity, member, nullptr, thread, interaction, reactions, nullptr, mentions, attachments, mentionChannels, getStringsFromJson(jsonObj["mention_roles"].toArray()), components, stickerItems, stickers, getString(jsonObj, "id"), getString(jsonObj, "channel_id"), getString(jsonObj, "guild_id"), getString(jsonObj, "content"), getString(jsonObj, "timestamp"), getString(jsonObj, "edited_timestamp"), getString(jsonObj, "webhook_id"), getString(jsonObj, "application_id"), getString(jsonObj, "nonce"), jsonObj["nonce"].toInt(-1), jsonObj["author_public_flags"].toInt(-1), jsonObj["type"].toInt(-1), jsonObj["flags"].toInt(-1), jsonObj["tts"].toBool(), jsonObj["pinned"].toBool(), jsonObj["mention_everyone"].toBool() }; } template <> void unmarshal<Message>(QJsonObject jsonObj, Message **object) { Application *application = new Application; User *author = new User; MessageActivity *activity = new MessageActivity; GuildMessageMember *member = new GuildMessageMember; Channel *thread = new Channel; MessageInteraction *interaction = new MessageInteraction; std::vector<Reaction *> *reactions = new std::vector<Reaction *>; std::vector<User *> *mentions = new std::vector<User *>; std::vector<Attachment *> *attachments = new std::vector<Attachment *>; std::vector<ChannelMention *> *mentionChannels = new std::vector<ChannelMention *>; std::vector<MessageComponent *> *components = new std::vector<MessageComponent *>; std::vector<StickerItem *> *stickerItems = new std::vector<StickerItem *>; std::vector<Sticker *> *stickers = new std::vector<Sticker *>; unmarshal<Application>(jsonObj, "application", &application); unmarshal<User>(jsonObj, "author", &author); unmarshal<MessageActivity>(jsonObj, "activity", &activity); unmarshal<GuildMessageMember>(jsonObj, "member", &member); unmarshal<Channel>(jsonObj, "thread", &thread); unmarshal<MessageInteraction>(jsonObj, "interaction", &interaction); unmarshalMultiple<Reaction>(jsonObj, "reactions", &reactions); unmarshalMultiple<User>(jsonObj, "mentions", &mentions); unmarshalMultiple<Attachment>(jsonObj, "attachments", &attachments); unmarshalMultiple<ChannelMention>(jsonObj, "mention_channels", &mentionChannels); unmarshalMultiple<MessageComponent>(jsonObj, "components", &components); unmarshalMultiple<StickerItem>(jsonObj, "sticker_items", &stickerItems); unmarshalMultiple<Sticker>(jsonObj, "stickers", &stickers); *object = new Message { application, author, activity, member, getPartialMessage(jsonObj, "referenced_message"), thread, interaction, reactions, nullptr, mentions, attachments, mentionChannels, getStringsFromJson(jsonObj["mention_roles"].toArray()), components, stickerItems, stickers, getString(jsonObj, "id"), getString(jsonObj, "channel_id"), getString(jsonObj, "guild_id"), getString(jsonObj, "content"), getString(jsonObj, "timestamp"), getString(jsonObj, "edited_timestamp"), getString(jsonObj, "webhook_id"), getString(jsonObj, "application_id"), getString(jsonObj, "nonce"), jsonObj["nonce"].toInt(-1), jsonObj["author_public_flags"].toInt(-1), jsonObj["type"].toInt(-1), jsonObj["flags"].toInt(-1), jsonObj["tts"].toBool(), jsonObj["pinned"].toBool(), jsonObj["mention_everyone"].toBool() }; } template <> void unmarshal<GuildMember>(QJsonObject jsonObj, GuildMember **object) { User *user = new User; unmarshal<User>(jsonObj, "user", &user); *object = new GuildMember { user, getStringsFromJson(jsonObj["roles"].toArray()), getString(jsonObj, "nick"), getString(jsonObj, "avatar"), getString(jsonObj, "joined_at"), getString(jsonObj, "premium_since"), getString(jsonObj, "permissions"), jsonObj["deaf"].toBool(), jsonObj["mute"].toBool(), jsonObj["pending"].toBool() }; } template <> void unmarshal<VoiceState>(QJsonObject jsonObj, VoiceState **object) { GuildMember *member = new GuildMember; unmarshal<GuildMember>(jsonObj, "member", &member); *object = new VoiceState { member, getString(jsonObj, "guild_id"), getString(jsonObj, "channel_id"), getString(jsonObj, "user_id"), getString(jsonObj, "session_id"), getString(jsonObj, "request_to_speak_timestamp"), jsonObj["deaf"].toBool(), jsonObj["mute"].toBool(), jsonObj["self_deaf"].toBool(), jsonObj["self_mute"].toBool(), jsonObj["self_stream"].toBool(), jsonObj["self_video"].toBool(), jsonObj["suppress"].toBool() }; } template <> void unmarshal<WelcomeScreenChannel>(QJsonObject jsonObj, WelcomeScreenChannel **object) { *object = new WelcomeScreenChannel { getString(jsonObj, "channel_id"), getString(jsonObj, "description"), getString(jsonObj, "emoji_id"), getString(jsonObj, "emoji_name"), }; } template <> void unmarshal<WelcomeScreen>(QJsonObject jsonObj, WelcomeScreen **object) { std::vector<WelcomeScreenChannel *> *welcomeChannels = new std::vector<WelcomeScreenChannel *>; unmarshalMultiple<WelcomeScreenChannel>(jsonObj, "welcome_channels", &welcomeChannels); *object = new WelcomeScreen { welcomeChannels, getString(jsonObj, "description"), }; } template <> void unmarshal<StageInstance>(QJsonObject jsonObj, StageInstance **object) { *object = new StageInstance { getString(jsonObj, "id"), getString(jsonObj, "guild_id"), getString(jsonObj, "channel_id"), getString(jsonObj, "topic"), jsonObj["privacy_level"].toInt(-1), jsonObj["discoverable_disabled"].toBool() }; } template <> void unmarshal<Guild>(QJsonObject jsonObj, Guild **object) { WelcomeScreen *welcomeScreen = new WelcomeScreen; std::vector<VoiceState *> *voiceStates = new std::vector<VoiceState *>; std::vector<GuildMember *> *members = new std::vector<GuildMember *>; std::vector<Channel *> *channels = new std::vector<Channel *>; std::vector<Channel *> *threads = new std::vector<Channel *>; std::vector<StageInstance *> *stageInstances = new std::vector<StageInstance *>; std::vector<Sticker *> *stickers = new std::vector<Sticker *>; unmarshal<WelcomeScreen>(jsonObj["welcome_screen"].toObject(), &welcomeScreen); unmarshalMultiple<VoiceState>(jsonObj["voice_states"].toArray(), &voiceStates); unmarshalMultiple<GuildMember>(jsonObj["members"].toArray(), &members); unmarshalMultiple<Channel>(jsonObj["channels"].toArray(), &channels); unmarshalMultiple<Channel>(jsonObj["threads"].toArray(), &threads); unmarshalMultiple<StageInstance>(jsonObj["stage_instances"].toArray(), &stageInstances); unmarshalMultiple<Sticker>(jsonObj["stickers"].toArray(), &stickers); *object = new Guild { welcomeScreen, getStringsFromJson(jsonObj["guild_features"].toArray()), voiceStates, members, channels, threads, nullptr, stageInstances, stickers, getString(jsonObj, "id"), getString(jsonObj, "name"), getString(jsonObj, "icon"), getString(jsonObj, "icon_hash"), getString(jsonObj, "splash"), getString(jsonObj, "discovery_splash"), getString(jsonObj, "owner_id"), getString(jsonObj, "permissions"), getString(jsonObj, "region"), getString(jsonObj, "afk_channel_id"), getString(jsonObj, "widget_channel_id"), getString(jsonObj, "application_id"), getString(jsonObj, "system_channel_id"), getString(jsonObj, "rules_channel_id"), getString(jsonObj, "joined_at"), getString(jsonObj, "vanity_url_code"), getString(jsonObj, "description"), getString(jsonObj, "banner"), getString(jsonObj, "preferred_locale"), getString(jsonObj, "public_updates_channel_id"), jsonObj["afk_timeout"].toInt(-1), jsonObj["verification_level"].toInt(-1), jsonObj["default_message_notifications"].toInt(-1), jsonObj["explicit_content_filter"].toInt(-1), jsonObj["mfa_level"].toInt(-1), jsonObj["system_channel_flags"].toInt(-1), jsonObj["member_count"].toInt(-1), jsonObj["max_presences"].toInt(-1), jsonObj["max_members"].toInt(-1), jsonObj["premium_tier"].toInt(-1), jsonObj["premium_subscription_count"].toInt(-1), jsonObj["max_video_channel_users"].toInt(-1), jsonObj["approximate_member_count"].toInt(-1), jsonObj["approximate_presence_count"].toInt(-1), jsonObj["nsfw_level"].toInt(-1), jsonObj["owner"].toBool(), jsonObj["widget_enabled"].toBool(), jsonObj["large"].toBool(), jsonObj["unavailable"].toBool() }; } template <> void unmarshal<CustomStatus>(QJsonObject jsonObj, CustomStatus **object) { *object = new CustomStatus { getString(jsonObj, "text"), getString(jsonObj, "expires_at"), getString(jsonObj, "emoji_name"), getString(jsonObj, "emoji_id") }; } template <> void unmarshal<FriendSourceFlags>(QJsonObject jsonObj, FriendSourceFlags **object) { *object = new FriendSourceFlags { jsonObj["all"].toBool(), jsonObj["mutual_friends"].toBool(), jsonObj["mutual_guilds"].toBool() }; } template <> void unmarshal<GuildFolder>(QJsonObject jsonObj, GuildFolder **object) { *object = new GuildFolder { getStringsFromJson(jsonObj["guild_ids"].toArray()), getString(jsonObj, "name"), jsonObj["id"].toInt(-1), jsonObj["color"].toInt(-1) }; } template <> void unmarshal<ClientSettings>(QJsonObject jsonObj, ClientSettings **object) { CustomStatus *customStatus = new CustomStatus; FriendSourceFlags *friendSourceFlags = new FriendSourceFlags; std::vector<GuildFolder *> *guildFolders = new std::vector<GuildFolder *>; unmarshal<CustomStatus>(jsonObj, "custom_status", &customStatus); unmarshal<FriendSourceFlags>(jsonObj, "friend_source_flags", &friendSourceFlags); unmarshalMultiple<GuildFolder>(jsonObj, "guild_folders", &guildFolders); *object = new ClientSettings { customStatus, friendSourceFlags, guildFolders, getStringsFromJson(jsonObj["guild_positions"].toArray()), getStringsFromJson(jsonObj["restricted_guilds"].toArray()), getString(jsonObj, "locale"), getString(jsonObj, "status"), getString(jsonObj, "theme"), jsonObj["afk_timeout"].toInt(-1), jsonObj["animate_stickers"].toInt(-1), jsonObj["explicit_content_filter"].toInt(-1), jsonObj["friend_discovery_flags"].toInt(-1), jsonObj["timezone_offset"].toInt(-1), jsonObj["allow_accessibility_detection"].toBool(), jsonObj["animate_emoji"].toBool(), jsonObj["contact_sync_enabled"].toBool(), jsonObj["convert_emoticons"].toBool(), jsonObj["default_guilds_restricted"].toBool(), jsonObj["detect_platform_accounts"].toBool(), jsonObj["developer_mode"].toBool(), jsonObj["disable_games_tab"].toBool(), jsonObj["enable_tts_command"].toBool(), jsonObj["gif_auto_play"].toBool(), jsonObj["inline_attachment_media"].toBool(), jsonObj["inline_embed_media"].toBool(), jsonObj["message_display_compact"].toBool(), jsonObj["native_phone_integration_enabled"].toBool(), jsonObj["render_embeds"].toBool(), jsonObj["render_reactions"].toBool(), jsonObj["show_current_game"].toBool(), jsonObj["stream_notifications_enabled"].toBool(), jsonObj["view_nsfw_guilds"].toBool() }; } template <> void unmarshal<Client>(QJsonObject jsonObj, Client **object) { *object = new Client { getString(jsonObj, "id"), getString(jsonObj, "username"), getString(jsonObj, "avatar"), getString(jsonObj, "discriminator"), getString(jsonObj, "banner"), getString(jsonObj, "bio"), getString(jsonObj, "locale"), getString(jsonObj, "email"), getString(jsonObj, "phone"), jsonObj["public_flags"].toInt(-1), jsonObj["flags"].toInt(-1), jsonObj["purchased_flags"].toInt(-1), jsonObj["banner_color"].toInt(-1), jsonObj["accent_color"].toInt(-1), jsonObj["nsfw_allowed"].toBool(), jsonObj["mfa_enabled"].toBool(), jsonObj["verified"].toBool() }; } template <> void unmarshal<ActivityTimestamps>(QJsonObject jsonObj, ActivityTimestamps **object) { *object = new ActivityTimestamps { jsonObj["start"].toInt(-1), jsonObj["end"].toInt(-1) }; } template <> void unmarshal<ActivityAssets>(QJsonObject jsonObj, ActivityAssets **object) { *object = new ActivityAssets { getString(jsonObj, "large_image"), getString(jsonObj, "large_text"), getString(jsonObj, "small_image"), getString(jsonObj, "small_text") }; } template <> void unmarshal<PartySize>(QJsonObject jsonObj, PartySize **object) { *object = new PartySize { jsonObj["current_size"].toInt(-1), jsonObj["max_size"].toInt(-1) }; } template <> void unmarshal<ActivityParty>(QJsonObject jsonObj, ActivityParty **object) { PartySize *size = new PartySize; unmarshal<PartySize>(jsonObj, "size", &size); *object = new ActivityParty { size, getString(jsonObj, "id") }; } template <> void unmarshal<ActivitySecrets>(QJsonObject jsonObj, ActivitySecrets **object) { *object = new ActivitySecrets { getString(jsonObj, "match"), getString(jsonObj, "join"), getString(jsonObj, "spectate") }; } template <> void unmarshal<Activity>(QJsonObject jsonObj, Activity **object) { ActivityTimestamps *timestamps = new ActivityTimestamps; ActivityAssets *assets = new ActivityAssets; ActivityParty *party = new ActivityParty; ActivitySecrets *secrets = new ActivitySecrets; unmarshal<ActivityTimestamps>(jsonObj, "timestamps", &timestamps); unmarshal<ActivityAssets>(jsonObj, "assets", &assets); unmarshal<ActivityParty>(jsonObj, "party", &party); unmarshal<ActivitySecrets>(jsonObj, "secrets", &secrets); *object = new Activity { timestamps, assets, party, secrets, getString(jsonObj, "application_id"), getString(jsonObj, "id"), getString(jsonObj, "name"), getString(jsonObj, "state"), getString(jsonObj, "details"), jsonObj["created_at"].toInt(-1), jsonObj["type"].toInt(-1), jsonObj["instance"].toBool(false) }; } template <> void unmarshal<ClientStatus>(QJsonObject jsonObj, ClientStatus **object) { *object = new ClientStatus { getString(jsonObj, "desktop"), getString(jsonObj, "mobile"), getString(jsonObj, "web") }; } template <> void unmarshal<Presence>(QJsonObject jsonObj, Presence **object) { User *user = new User; ClientStatus *clientStatus = new ClientStatus; std::vector<Activity *> *activities = new std::vector<Activity *>; unmarshal<User>(jsonObj, "user", &user); unmarshal<ClientStatus>(jsonObj, "client_status", &clientStatus); unmarshalMultiple<Activity>(jsonObj, "activities", &activities); *object = new Presence { user, clientStatus, activities, getString(jsonObj, "user_id"), getString(jsonObj, "guild_id"), getString(jsonObj, "status") }; } } // namespace Api
29.845057
100
0.640093
EnyoYoen
8a2705444d86f835b50e88630b346e54a9168b24
11,754
cpp
C++
source/trt_engine/trt_network_crt/plugins/grid_sampler_plugin/grid_sampler_plugin.cpp
jinyouzhi/Forward
4d01f50fbc05e1a052bfe7c1f61f80ba865a8f88
[ "BSD-3-Clause" ]
491
2021-03-12T08:16:02.000Z
2022-03-30T02:25:18.000Z
source/trt_engine/trt_network_crt/plugins/grid_sampler_plugin/grid_sampler_plugin.cpp
jinyouzhi/Forward
4d01f50fbc05e1a052bfe7c1f61f80ba865a8f88
[ "BSD-3-Clause" ]
26
2021-03-17T09:09:27.000Z
2022-01-23T01:49:55.000Z
source/trt_engine/trt_network_crt/plugins/grid_sampler_plugin/grid_sampler_plugin.cpp
jinyouzhi/Forward
4d01f50fbc05e1a052bfe7c1f61f80ba865a8f88
[ "BSD-3-Clause" ]
67
2021-03-15T09:03:29.000Z
2022-03-30T04:19:02.000Z
// Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing permissions and limitations under // the License. // // ╔════════════════════════════════════════════════════════════════════════════════════════╗ // ║──█████████╗───███████╗───████████╗───██╗──────██╗───███████╗───████████╗───████████╗───║ // ║──██╔══════╝──██╔════██╗──██╔════██╗──██║──────██║──██╔════██╗──██╔════██╗──██╔════██╗──║ // ║──████████╗───██║────██║──████████╔╝──██║──█╗──██║──█████████║──████████╔╝──██║────██║──║ // ║──██╔═════╝───██║────██║──██╔════██╗──██║█████╗██║──██╔════██║──██╔════██╗──██║────██║──║ // ║──██║─────────╚███████╔╝──██║────██║──╚████╔████╔╝──██║────██║──██║────██║──████████╔╝──║ // ║──╚═╝──────────╚══════╝───╚═╝────╚═╝───╚═══╝╚═══╝───╚═╝────╚═╝──╚═╝────╚═╝──╚═══════╝───║ // ╚════════════════════════════════════════════════════════════════════════════════════════╝ // // Authors: Aster JIAN ([email protected]) // Yzx ([email protected]) // Ao LI ([email protected]) // Paul LU ([email protected]) #include "trt_engine/trt_network_crt/plugins/grid_sampler_plugin/grid_sampler_plugin.h" #include <cuda_fp16.h> #include "trt_engine/trt_network_crt/plugins/common/serialize.hpp" // #define ENABLE_GRID_SAMPLER_FLOAT16 FWD_TRT_NAMESPACE_BEGIN GridSamplerPlugin::GridSamplerPlugin(int interpolation_mode, int padding_mode, int align_corners, nvinfer1::DataType data_type) : interpolation_mode_(interpolation_mode), padding_mode_(padding_mode), align_corners_(align_corners), data_type_(data_type) {} GridSamplerPlugin::GridSamplerPlugin(void const* serialData, size_t serialLength) { deserialize_value(&serialData, &serialLength, &interpolation_mode_); deserialize_value(&serialData, &serialLength, &padding_mode_); deserialize_value(&serialData, &serialLength, &align_corners_); deserialize_value(&serialData, &serialLength, &data_type_); } GridSamplerPlugin::~GridSamplerPlugin() { terminate(); } int GridSamplerPlugin::getNbOutputs() const noexcept { return 1; } nvinfer1::DimsExprs GridSamplerPlugin::getOutputDimensions( int outputIndex, const nvinfer1::DimsExprs* inputs, int nbInputs, nvinfer1::IExprBuilder& exprBuilder) noexcept { // [N, C, H, W], [N, H', W', 2] -> [N, C, H', W'] ASSERT(nbInputs == 2); assert(inputs[0].nbDims == 4 || inputs[0].nbDims == 5); assert(inputs[1].nbDims == 4 || inputs[1].nbDims == 5); nvinfer1::DimsExprs output(inputs[0]); output.d[2] = inputs[1].d[1]; output.d[3] = inputs[1].d[2]; if (inputs[0].nbDims == 5) { // [N, C, D, H, W], [N, D', H', W', 2] -> [N, C, D', H', W'] output.d[4] = inputs[1].d[3]; } return output; } int GridSamplerPlugin::initialize() noexcept { return 0; } void GridSamplerPlugin::terminate() noexcept {} size_t GridSamplerPlugin::getWorkspaceSize(const nvinfer1::PluginTensorDesc* inputs, int nbInputs, const nvinfer1::PluginTensorDesc* outputs, int nbOutputs) const noexcept { return 0; } int GridSamplerPlugin::enqueue(const nvinfer1::PluginTensorDesc* inputDesc, const nvinfer1::PluginTensorDesc* outputDesc, const void* const* inputs, void* const* outputs, void* workspace, cudaStream_t stream) noexcept { #ifdef ENABLE_GRID_SAMPLER_FLOAT16 nvinfer1::DataType type = data_type_; #else nvinfer1::DataType type = inputDesc[0].type; #endif if (inputDesc[0].dims.nbDims == 4) { if (type == nvinfer1::DataType::kFLOAT) { TensorInfo<float> output_tensor{static_cast<float*>(outputs[0]), outputDesc[0].dims}; GridSampler2DCuda<float>({static_cast<const float*>(inputs[0]), inputDesc[0].dims}, {static_cast<const float*>(inputs[1]), inputDesc[1].dims}, output_tensor, interpolation_mode_, padding_mode_, align_corners_, stream); } else if (type == nvinfer1::DataType::kHALF) { TensorInfo<__half> output_tensor{static_cast<__half*>(outputs[0]), outputDesc[0].dims}; GridSampler2DCuda<__half>({static_cast<const __half*>(inputs[0]), inputDesc[0].dims}, {static_cast<const __half*>(inputs[1]), inputDesc[1].dims}, output_tensor, interpolation_mode_, padding_mode_, align_corners_, stream); } else { getLogger()->log(nvinfer1::ILogger::Severity::kERROR, "[Grid Sampler] Unsupported input data type"); return -1; } } else if (inputDesc[0].dims.nbDims == 5) { if (type == nvinfer1::DataType::kFLOAT) { TensorInfo<float> output_tensor{static_cast<float*>(outputs[0]), outputDesc[0].dims}; GridSampler3DCuda<float>({static_cast<const float*>(inputs[0]), inputDesc[0].dims}, {static_cast<const float*>(inputs[1]), inputDesc[1].dims}, output_tensor, interpolation_mode_, padding_mode_, align_corners_, stream); } else if (type == nvinfer1::DataType::kHALF) { TensorInfo<__half> output_tensor{static_cast<__half*>(outputs[0]), outputDesc[0].dims}; GridSampler3DCuda<__half>({static_cast<const __half*>(inputs[0]), inputDesc[0].dims}, {static_cast<const __half*>(inputs[1]), inputDesc[1].dims}, output_tensor, interpolation_mode_, padding_mode_, align_corners_, stream); } else { getLogger()->log(nvinfer1::ILogger::Severity::kERROR, "[Grid Sampler] Unsupported input data type"); return -1; } } else { getLogger()->log(nvinfer1::ILogger::Severity::kERROR, "GridSampler do not support input dims > 5"); return -1; } CUDA_CHECK(cudaGetLastError()); return 0; } size_t GridSamplerPlugin::getSerializationSize() const noexcept { return serialized_size(interpolation_mode_) + serialized_size(padding_mode_) + serialized_size(align_corners_) + serialized_size(data_type_); } void GridSamplerPlugin::serialize(void* buffer) const noexcept { serialize_value(&buffer, interpolation_mode_); serialize_value(&buffer, padding_mode_); serialize_value(&buffer, align_corners_); serialize_value(&buffer, data_type_); } bool GridSamplerPlugin::supportsFormatCombination(int pos, const nvinfer1::PluginTensorDesc* inOut, int nbInputs, int nbOutputs) noexcept { ASSERT(inOut && nbInputs == 2 && nbOutputs == 1 && pos < (nbInputs + nbOutputs)); #ifdef ENABLE_GRID_SAMPLER_FLOAT16 return ((inOut[pos].type == nvinfer1::DataType::kFLOAT || inOut[pos].type == nvinfer1::DataType::kHALF) && inOut[pos].format == nvinfer1::TensorFormat::kLINEAR); #else return (inOut[pos].type == nvinfer1::DataType::kFLOAT && inOut[pos].format == nvinfer1::TensorFormat::kLINEAR); #endif } const char* GridSamplerPlugin::getPluginType() const noexcept { return GRID_SAMPLER_PLUGIN_NAME; } const char* GridSamplerPlugin::getPluginVersion() const noexcept { return GRID_SAMPLER_PLUGIN_VERSION; } void GridSamplerPlugin::destroy() noexcept { delete this; } nvinfer1::IPluginV2DynamicExt* GridSamplerPlugin::clone() const noexcept { return new GridSamplerPlugin{interpolation_mode_, padding_mode_, align_corners_, data_type_}; } void GridSamplerPlugin::setPluginNamespace(const char* pluginNamespace) noexcept { mPluginNamespace = pluginNamespace; } const char* GridSamplerPlugin::getPluginNamespace() const noexcept { return mPluginNamespace; } nvinfer1::DataType GridSamplerPlugin::getOutputDataType(int index, const nvinfer1::DataType* inputTypes, int nbInputs) const noexcept { ASSERT(inputTypes && nbInputs > 0 && index == 0); return inputTypes[0]; } void GridSamplerPlugin::configurePlugin(const nvinfer1::DynamicPluginTensorDesc* in, int nbInputs, const nvinfer1::DynamicPluginTensorDesc* out, int nbOutputs) noexcept { // for (int i = 0; i < nbInputs; i++) { // for (int j = 0; j < in[i].desc.dims.nbDims; j++) { // // Do not support dynamic dimensions // ASSERT(in[i].desc.dims.d[j] != -1); // } // } } GridSamplerPluginCreator::GridSamplerPluginCreator() { mPluginAttributes.emplace_back( nvinfer1::PluginField("interpolation_mode", nullptr, nvinfer1::PluginFieldType::kINT32, 1)); mPluginAttributes.emplace_back( nvinfer1::PluginField("padding_mode", nullptr, nvinfer1::PluginFieldType::kINT32, 1)); mPluginAttributes.emplace_back( nvinfer1::PluginField("align_corners", nullptr, nvinfer1::PluginFieldType::kINT32, 1)); mPluginAttributes.emplace_back( nvinfer1::PluginField("data_type", nullptr, nvinfer1::PluginFieldType::kINT32, 1)); mFC.nbFields = mPluginAttributes.size(); mFC.fields = mPluginAttributes.data(); } const char* GridSamplerPluginCreator::getPluginName() const noexcept { return GRID_SAMPLER_PLUGIN_NAME; } const char* GridSamplerPluginCreator::getPluginVersion() const noexcept { return GRID_SAMPLER_PLUGIN_VERSION; } const nvinfer1::PluginFieldCollection* GridSamplerPluginCreator::getFieldNames() noexcept { return &mFC; } nvinfer1::IPluginV2DynamicExt* GridSamplerPluginCreator::createPlugin( const char* name, const nvinfer1::PluginFieldCollection* fc) noexcept { int interpolation_mode{}, padding_mode{}, align_corners{}; const nvinfer1::PluginField* fields = fc->fields; int data_type = 0; for (int i = 0; i < fc->nbFields; ++i) { const char* attrName = fields[i].name; if (!strcmp(attrName, "interpolation_mode")) { ASSERT(fields[i].type == nvinfer1::PluginFieldType::kINT32); interpolation_mode = *(static_cast<const int*>(fields[i].data)); } else if (!strcmp(attrName, "padding_mode")) { ASSERT(fields[i].type == nvinfer1::PluginFieldType::kINT32); padding_mode = *(static_cast<const int*>(fields[i].data)); } else if (!strcmp(attrName, "align_corners")) { ASSERT(fields[i].type == nvinfer1::PluginFieldType::kINT32); align_corners = *(static_cast<const int*>(fields[i].data)); } else if (!strcmp(attrName, "data_type")) { ASSERT(fields[i].type == nvinfer1::PluginFieldType::kINT32); data_type = *(static_cast<const int*>(fields[i].data)); } else { ASSERT(false); } } auto obj = new GridSamplerPlugin(interpolation_mode, padding_mode, align_corners, static_cast<nvinfer1::DataType>(data_type)); obj->setPluginNamespace(mNamespace.c_str()); return obj; } nvinfer1::IPluginV2DynamicExt* GridSamplerPluginCreator::deserializePlugin( const char* name, const void* serialData, size_t serialLength) noexcept { auto* obj = new GridSamplerPlugin{serialData, serialLength}; obj->setPluginNamespace(mNamespace.c_str()); return obj; } FWD_TRT_NAMESPACE_END
43.858209
100
0.623022
jinyouzhi
8a2d54b489bc1e899c9ffa6a8b293b8a74bd565f
619
hpp
C++
bunsan/pm/src/lib/repository/local_system.hpp
bacsorg/bacs
2b52feb9efc805655cdf7829cf77ee028d567969
[ "Apache-2.0" ]
null
null
null
bunsan/pm/src/lib/repository/local_system.hpp
bacsorg/bacs
2b52feb9efc805655cdf7829cf77ee028d567969
[ "Apache-2.0" ]
10
2018-02-06T14:46:36.000Z
2018-03-20T13:37:20.000Z
bunsan/pm/src/lib/repository/local_system.hpp
bacsorg/bacs
2b52feb9efc805655cdf7829cf77ee028d567969
[ "Apache-2.0" ]
1
2021-11-26T10:59:09.000Z
2021-11-26T10:59:09.000Z
#pragma once #include <bunsan/pm/repository.hpp> #include <bunsan/tempfile.hpp> #include <bunsan/utility/custom_resolver.hpp> #include <boost/noncopyable.hpp> namespace bunsan::pm { class repository::local_system : private boost::noncopyable { public: local_system(repository &self, const local_system_config &config); utility::resolver &resolver(); /// Empty dir for possibly large files. tempfile tempdir_for_build(); /// Empty file. tempfile small_tempfile(); private: repository &m_self; local_system_config m_config; utility::custom_resolver m_resolver; }; } // namespace bunsan::pm
19.967742
68
0.746365
bacsorg
8a454539e831ef699299d1f035c75bf42a7977fc
1,285
cpp
C++
src/tests/rng.cpp
jjbandit/game
c28affd868201d3151ca75a20883e7fb26e09302
[ "WTFPL" ]
null
null
null
src/tests/rng.cpp
jjbandit/game
c28affd868201d3151ca75a20883e7fb26e09302
[ "WTFPL" ]
null
null
null
src/tests/rng.cpp
jjbandit/game
c28affd868201d3151ca75a20883e7fb26e09302
[ "WTFPL" ]
null
null
null
#include <bonsai_types.h> #include <tests/test_utils.cpp> s32 main(s32 ArgCount, const char** Args) { TestSuiteBegin("RNG", ArgCount, Args); #if 0 random_series Entropy = {43215426453}; const u32 TableSize = 256; u32 HitTable[TableSize] = {}; u32 MaxValue = 0; memory_arena* Memory = AllocateArena(Megabytes(8)); ansi_stream WordStream = AnsiStreamFromFile(CS(TEST_FIXTURES_PATH "/words.txt"), Memory); while (Remaining(&WordStream)) { counted_string Word = PopWordCounted(&WordStream); u32 HashValue = Hash(&Word) % TableSize; ++HitTable[HashValue]; if (HitTable[HashValue] > MaxValue) { MaxValue = HitTable[HashValue]; } } Log("Max: %u\n", MaxValue); u32 MappedRowSize = 128; for (u32 TableIndex = 0; TableIndex < TableSize; ++TableIndex) { u32 TableValue = HitTable[TableIndex]; r32 Value = (r32)TableValue / (r32)MaxValue; u32 Mapped = MapValueToRange(0, Value, MappedRowSize); for (u32 ValueIndex = 0; ValueIndex < MappedRowSize; ++ValueIndex) { if (ValueIndex < Mapped) { Log("."); } else { Log(" "); } } Log(" | (%u %u) \n", TableValue, Mapped); } #endif TestSuiteEnd(); exit(TestsFailed); }
19.469697
91
0.61323
jjbandit
8a48d3123adb1a0ef856e62372e4ac7e6c70e767
1,135
cpp
C++
chapters/11/ex11_09.cpp
yG620/cpp_primer_5th_solutions
68fdb2e5167228a3d31ac31c221c1055c2500b91
[ "Apache-2.0" ]
null
null
null
chapters/11/ex11_09.cpp
yG620/cpp_primer_5th_solutions
68fdb2e5167228a3d31ac31c221c1055c2500b91
[ "Apache-2.0" ]
null
null
null
chapters/11/ex11_09.cpp
yG620/cpp_primer_5th_solutions
68fdb2e5167228a3d31ac31c221c1055c2500b91
[ "Apache-2.0" ]
null
null
null
// // ex11_09.cpp // Exercise 11.09 // // Created by yG620 on 20/9/16 // // @Brief > Define a map that associates words with a list of line // numbers on which the word might occur. // // @KeyPoint 1. bug: error: expected unqualified-id before ‘[’ token // fix: using WordLineNo = map<string, list<int>>; WordLineNo can not be used directly. #include <iostream> #include <fstream> #include <sstream> #include <map> #include <list> #include <string> #include <algorithm> using namespace std; using WordLineNo = map<string, list<int>>; int main(int argc, char *argv[]) { ifstream ifs(argv[1]); string line; string word; int lineno = 0; WordLineNo Words; while (getline(ifs, line)) { ++lineno; istringstream word_line(line); while (word_line >> word) { Words[word].push_back(lineno); } } for (const auto &word : Words) { cout << word.first << " is on the "; for (const auto & lineno : word.second) cout << lineno << " line." << endl; } return 0; }
23.163265
103
0.570044
yG620
8a4e26a8e4cf447fdc5689bdf4642f807eb67c7b
2,379
cpp
C++
Pacman/Debug.cpp
GeraldBostock/Pacman
db8b30f2f04a85678f01c7311a9cf706fdd31804
[ "MIT" ]
null
null
null
Pacman/Debug.cpp
GeraldBostock/Pacman
db8b30f2f04a85678f01c7311a9cf706fdd31804
[ "MIT" ]
null
null
null
Pacman/Debug.cpp
GeraldBostock/Pacman
db8b30f2f04a85678f01c7311a9cf706fdd31804
[ "MIT" ]
null
null
null
#include "Debug.h" Debug::Debug() { } Debug::~Debug() { } void Debug::init(SDL_Renderer* renderer, int windowWidth, int windowHeight) { if (TTF_Init() == -1) { printf("SDL_ttf could not initialize! SDL_ttf Error: %s\n", TTF_GetError()); } m_blendedRect = createDebugRect(windowWidth, windowHeight, renderer); m_font = TTF_OpenFont("Assets/font.ttf", 20); m_textColor = { 255, 255, 255 }; m_posXLabel.loadFromRenderedText("X: ", m_textColor, m_font, renderer); m_posYLabel.loadFromRenderedText("Y: ", m_textColor, m_font, renderer); m_appleCountLabel.loadFromRenderedText("Apples Left: ", m_textColor, m_font, renderer); m_fpsLabel.loadFromRenderedText("FPS: ", m_textColor, m_font, renderer); m_fire.init(25, 25); m_fire.loadAnim("Assets/fire.png", renderer, 4, 0.08f, 0.2f); } void Debug::draw(SDL_Renderer* renderer, int windowWidth, int windowHeight, int posX, int posY, int appleNum, float fps) { SDL_Rect debugPanel = { 0, 0, windowWidth / 4, windowHeight }; SDL_RenderCopy(renderer, m_blendedRect, NULL, &debugPanel); m_posXLabel.draw(50, 50, renderer, NULL, 0.0); m_posYLabel.draw(50, 75, renderer, NULL, 0.0); m_appleCountLabel.draw(50, 100, renderer, NULL, 0.0); m_fpsLabel.draw(50, 125, renderer, NULL, 0); m_playerPosX.loadFromRenderedText(std::to_string(posX), m_textColor, m_font, renderer); m_playerPosY.loadFromRenderedText(std::to_string(posY), m_textColor, m_font, renderer); m_appleCount.loadFromRenderedText(std::to_string(appleNum), m_textColor, m_font, renderer); m_fpsValue.loadFromRenderedText(std::to_string(fps), m_textColor, m_font, renderer); m_playerPosX.draw(75, 50, renderer, NULL, 0.0); m_playerPosY.draw(75, 75, renderer, NULL, 0.0); m_appleCount.draw(175, 100, renderer, NULL, 0.0); m_fpsValue.draw(115, 125, renderer, NULL, 0.0); m_fire.draw(renderer); } SDL_Texture* Debug::createDebugRect(int windowWidth, int windowHeight, SDL_Renderer* renderer) { SDL_Surface* rect = NULL; SDL_Texture* blendedTex = NULL; rect = SDL_CreateRGBSurface(0, windowWidth, windowHeight, 32, 0, 0, 0, 0); if (rect == NULL) { printf("%s", SDL_GetError()); } blendedTex = SDL_CreateTextureFromSurface(renderer, rect); if (blendedTex == NULL) { printf("%s", SDL_GetError()); } SDL_SetTextureBlendMode(blendedTex, SDL_BLENDMODE_BLEND); SDL_SetTextureAlphaMod(blendedTex, 150); return blendedTex; }
29.012195
120
0.733922
GeraldBostock
8a4e6c5abfd83ae41c2ef4295e4459fc715167db
547
cpp
C++
src/pyco_tree/pico_tree/_pyco_tree/_pyco_tree.cpp
Jaybro/pico_tree
c6f7fb798b60452add7d0e940c4a7737cd72a992
[ "MIT" ]
23
2020-07-19T23:03:01.000Z
2022-03-07T15:06:26.000Z
src/pyco_tree/pico_tree/_pyco_tree/_pyco_tree.cpp
Jaybro/pico_tree
c6f7fb798b60452add7d0e940c4a7737cd72a992
[ "MIT" ]
1
2021-01-26T16:53:16.000Z
2021-01-26T23:20:54.000Z
src/pyco_tree/pico_tree/_pyco_tree/_pyco_tree.cpp
Jaybro/pico_tree
c6f7fb798b60452add7d0e940c4a7737cd72a992
[ "MIT" ]
4
2021-03-04T14:03:28.000Z
2021-05-27T05:36:40.000Z
#include <pybind11/pybind11.h> #include <iostream> #include "darray.hpp" #include "def_core.hpp" #include "def_darray.hpp" #include "def_kd_tree.hpp" PYBIND11_MODULE(_pyco_tree, m) { m.doc() = "PicoTree is a module for nearest neighbor searches and range searches " "using a KdTree. It wraps the C++ PicoTree library."; // Registered dtypes. PYBIND11_NUMPY_DTYPE(pyco_tree::Neighborf, index, distance); PYBIND11_NUMPY_DTYPE(pyco_tree::Neighbord, index, distance); pyco_tree::DefDArray(&m); pyco_tree::DefKdTree(&m); }
24.863636
78
0.725777
Jaybro
8a52f8bbfc86473a4bbca1b74a930f7e4cc77dcf
2,999
cpp
C++
src/util/models/modelitem.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
1
2017-01-12T07:05:45.000Z
2017-01-12T07:05:45.000Z
src/util/models/modelitem.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
null
null
null
src/util/models/modelitem.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
null
null
null
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. **********************************************************************/ #include "modelitem.h" #include <algorithm> namespace LeechCraft { namespace Util { ModelItem::ModelItem () : Model_ { nullptr } { } ModelItem::ModelItem (QAbstractItemModel *model, const QModelIndex& idx, const ModelItem_wtr& parent) : ModelItemBase { parent } , Model_ { model } , SrcIdx_ { idx } { } ModelItem* ModelItem::EnsureChild (int row) { if (Children_.value (row)) return Children_.at (row).get (); if (Children_.size () <= row) Children_.resize (row + 1); const auto& childIdx = Model_->index (row, 0, SrcIdx_); Children_ [row] = std::make_shared<ModelItem> (Model_, childIdx, shared_from_this ()); return Children_.at (row).get (); } const QModelIndex& ModelItem::GetIndex () const { return SrcIdx_; } void ModelItem::RefreshIndex (int modelStartingRow) { if (SrcIdx_.isValid ()) SrcIdx_ = Model_->index (GetRow () - modelStartingRow, 0, Parent_.lock ()->GetIndex ()); } QAbstractItemModel* ModelItem::GetModel () const { return Model_; } ModelItem_ptr ModelItem::FindChild (QModelIndex index) const { index = index.sibling (index.row (), 0); const auto pos = std::find_if (Children_.begin (), Children_.end (), [&index] (const ModelItem_ptr& item) { return item->GetIndex () == index; }); return pos == Children_.end () ? ModelItem_ptr {} : *pos; } } }
34.079545
102
0.687229
MellonQ
a437049631a5705c20e9dfdabb0254f5fc0d7722
618
hpp
C++
Scott_Sidoli Level 7 HW Submission/Exercise 3/Exercise73/lessThan.hpp
scottsidoli/C-for-Financial-Engineering---Baruch-Pre-MFE-Certificate
79c2fb297a85c914d5f0b8671bb17636801e3ce7
[ "MIT" ]
1
2021-11-05T08:14:37.000Z
2021-11-05T08:14:37.000Z
Scott_Sidoli Level 7 HW Submission/Exercise 3/Exercise73/lessThan.hpp
scottsidoli/C-for-Financial-Engineering---Baruch-Pre-MFE-Certificate
79c2fb297a85c914d5f0b8671bb17636801e3ce7
[ "MIT" ]
null
null
null
Scott_Sidoli Level 7 HW Submission/Exercise 3/Exercise73/lessThan.hpp
scottsidoli/C-for-Financial-Engineering---Baruch-Pre-MFE-Certificate
79c2fb297a85c914d5f0b8671bb17636801e3ce7
[ "MIT" ]
null
null
null
// Exercise 7.3 - STL Algorithms // // by Scott Sidoli // // 5-28-19 // // lessThan.hpp // // lessThan class with global function and function object. #ifndef lessThan_hpp #define lessThan_hpp extern double threshold; class lessThan { private: double boundary; // Threshold value public: lessThan(double value); // Constructor with a threshold value ~lessThan(); // Destructor bool operator () (double value); // Overloaded operator }; // Global function template template <typename T> bool less_than(const T& value) { return (value < threshold); } #endif
16.702703
66
0.658576
scottsidoli
a43a1975be6bc1664f07c5d1eea75494fde1e886
334
cpp
C++
src/main.cpp
kaidokert/MosquitoBorneDisease
b3584f12a9c3be2907360152c04032b213f19cd1
[ "BSD-3-Clause" ]
null
null
null
src/main.cpp
kaidokert/MosquitoBorneDisease
b3584f12a9c3be2907360152c04032b213f19cd1
[ "BSD-3-Clause" ]
8
2018-11-13T14:33:26.000Z
2018-11-23T18:01:38.000Z
src/main.cpp
kaidokert/MosquitoBorneDisease
b3584f12a9c3be2907360152c04032b213f19cd1
[ "BSD-3-Clause" ]
2
2019-08-05T07:21:28.000Z
2019-08-23T06:24:23.000Z
/* # main routines # # This file is part of SMosMod. # Copyright (c) 2017-2018, Imperial College London # For licensing information, see the LICENSE file distributed with the SMosMod # software package. */ #include <iostream> #include "world.hpp" #include "agent.hpp" int main() { std::cout << "Hi Ben\n"; return 0; }
15.904762
79
0.676647
kaidokert
a43f462c5aab064b525b2a0f5661660a93c41e94
670
cpp
C++
Arrays/Monotonic Array/Solution1.cpp
jabbala-ai/competitive-programming
8ab4f3d291068e24b2ffe3e916f8f8a5c8f839c7
[ "MIT" ]
null
null
null
Arrays/Monotonic Array/Solution1.cpp
jabbala-ai/competitive-programming
8ab4f3d291068e24b2ffe3e916f8f8a5c8f839c7
[ "MIT" ]
null
null
null
Arrays/Monotonic Array/Solution1.cpp
jabbala-ai/competitive-programming
8ab4f3d291068e24b2ffe3e916f8f8a5c8f839c7
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <algorithm> #include <climits> using namespace std; bool breaksDirection(int direction, int previousInt, int currentInt) { int difference = currentInt - previousInt; if(direction > 0){ return direction < 0; } return direction >0; } // Time Complexity - O(N) // Space Complexity - O(1) bool isMonotonic(vector<int> array) { if(array.size() <= 2) { return true; } int direction = array[1] - array[0]; for(int i=2; i<array.size(); i++) { if(direction == 0) { direction = array[i] - array[i - 1]; continue; } if(breaksDirection(direction, array[i-1], array[i])) return false; } return true; }
18.611111
68
0.656716
jabbala-ai
a444168398f0f4149c70f26a6f2627bf0e3bec2f
3,239
cc
C++
Mu2eG4/src/addPointTrajectories.cc
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
null
null
null
Mu2eG4/src/addPointTrajectories.cc
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
1
2019-11-22T14:45:51.000Z
2019-11-22T14:50:03.000Z
Mu2eG4/src/addPointTrajectories.cc
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
2
2019-10-14T17:46:58.000Z
2020-03-30T21:05:15.000Z
// // Extract trajectories from the G4 internals and add them to the event. // Skip trajectories with too few points. // // $Id: addPointTrajectories.cc,v 1.5 2014/01/18 04:31:53 kutschke Exp $ // $Author: kutschke $ // $Date: 2014/01/18 04:31:53 $ // // Original author Rob Kutschke // // Notes: // 1) The data product is filled via two phase construction. // This avoids extra copies of the (often long) vector of points. // If and when we get move aware STL libraries we can go back // to single phase construction. // #include "G4AttDef.hh" #include "G4Event.hh" #include "G4TrajectoryContainer.hh" #include "G4TrajectoryPoint.hh" #include "Mu2eG4/inc/addPointTrajectories.hh" #include "Mu2eG4/inc/SimParticleHelper.hh" #include <iostream> #include <map> using namespace std; namespace mu2e{ void addPointTrajectories ( const G4Event* g4event, PointTrajectoryCollection& pointTrajectories, const SimParticleHelper& spHelper, CLHEP::Hep3Vector const& mu2eOriginInWorld, int minSteps ){ typedef PointTrajectoryCollection::key_type key_type; typedef PointTrajectoryCollection::mapped_type mapped_type; typedef std::map<key_type,mapped_type> map_type; // Check that there is information to be copied. G4TrajectoryContainer const* trajectories = g4event->GetTrajectoryContainer(); if ( !trajectories ) return; TrajectoryVector const& vect = *trajectories->GetVector(); if ( vect.empty() ) return; // Need to pre-sort before insertion into the collection; do it using this map. map_type tempMap; // Insert mostly empty PointTrajecotry objects into the temporary map. These contain // only the ID and an empty std::vector so they are small. for ( size_t i=0; i<vect.size(); ++i){ G4VTrajectory const& traj = *vect[i]; key_type kid(spHelper.particleKeyFromG4TrackID(traj.GetTrackID())); // Cut if too few points. Need to make this a variable. if ( traj.GetPointEntries() < minSteps ) { continue; } tempMap[kid] = PointTrajectory(kid.asInt()); } // Phase 1 of construction of the data product. See note 1. pointTrajectories.insert( tempMap.begin(), tempMap.end() ); // Phase 2 of construction. Add the vector of points. for ( size_t i=0; i<vect.size(); ++i){ G4VTrajectory const& traj = *vect[i]; // Which trajectory are we looking for? key_type kid(spHelper.particleKeyFromG4TrackID(traj.GetTrackID())); // Locate this trajectory in the data product. // It is OK if we do not find it since we applied cuts above. PointTrajectoryCollection::iterator iter = pointTrajectories.find(kid); if ( iter == pointTrajectories.end() ){ continue; } PointTrajectory& ptraj = iter->second; // Add the points. for ( int j=0; j<traj.GetPointEntries(); ++j){ G4VTrajectoryPoint const& pt = *traj.GetPoint(j); ptraj.addPoint( pt.GetPosition()-mu2eOriginInWorld ); } } // end phase 2 } // end addPointTrajectories. } // end namespace mu2e
34.457447
89
0.654523
bonventre
a44b6796e9dc3bb76fb39df63a71aca44cadcb98
475
cpp
C++
sources/Renderer/OpenGL/GLCoreProfile/GLCoreExtensions.cpp
beldenfox/LLGL
3a54125ebfa79bb06fccf8c413d308ff22186b52
[ "BSD-3-Clause" ]
1,403
2016-09-28T21:48:07.000Z
2022-03-31T23:58:57.000Z
sources/Renderer/OpenGL/GLCoreProfile/GLCoreExtensions.cpp
beldenfox/LLGL
3a54125ebfa79bb06fccf8c413d308ff22186b52
[ "BSD-3-Clause" ]
70
2016-10-13T20:15:58.000Z
2022-01-12T23:51:12.000Z
sources/Renderer/OpenGL/GLCoreProfile/GLCoreExtensions.cpp
beldenfox/LLGL
3a54125ebfa79bb06fccf8c413d308ff22186b52
[ "BSD-3-Clause" ]
122
2016-10-23T15:33:44.000Z
2022-03-07T07:41:23.000Z
/* * GLCoreExtensions.cpp * * This file is part of the "LLGL" project (Copyright (c) 2015-2019 by Lukas Hermanns) * See "LICENSE.txt" for license information. */ #include "GLCoreExtensions.h" namespace LLGL { #define LLGL_DEF_GL_EXT_PROCS // Include inline header for object definitions #include "GLCoreExtensionsDecl.inl" #undef LLGL_DEF_GL_EXT_PROCS } // /namespace LLGL // ================================================================================
16.964286
86
0.606316
beldenfox
a4569a35daa91f7a3d46db798aea0e059fe962fc
989
cc
C++
examples/string.cc
knocknote/libhtml5
46e18a9122097b4d681c91f0747aa78a20611cab
[ "MIT" ]
7
2019-08-29T05:22:05.000Z
2020-07-07T15:35:50.000Z
examples/string.cc
blastrain/libhtml5
46e18a9122097b4d681c91f0747aa78a20611cab
[ "MIT" ]
3
2019-07-12T09:43:31.000Z
2019-09-10T03:36:45.000Z
examples/string.cc
blastrain/libhtml5
46e18a9122097b4d681c91f0747aa78a20611cab
[ "MIT" ]
3
2019-10-25T05:35:30.000Z
2020-07-21T21:40:52.000Z
#include "libhtml5.h" static void stringTest() { { html5::string s = "hello world"; std::cout << s << std::endl; html5::console->log(s); } { std::string s = "hello"; html5::string s2 = s; s2 += "world"; std::cout << s2 << std::endl; } { html5::string a = "hello"; html5::string b = "world"; html5::string c = a + b; std::cout << c << std::endl; } { html5::string s = "hello world"; for (const auto &splitted : s.split(" ")) { html5::string v = splitted; std::cout << v << std::endl; std::cout << "includes h? " << v.includes("h") << std::endl; } } { html5::string s = "0123456789abcdef"; std::string primitiveStr = s.substr(1, 10).toUpperCase(); std::cout << primitiveStr << std::endl; } } EMSCRIPTEN_BINDINGS(string) { emscripten::function("stringTest", &stringTest); }
24.725
72
0.484328
knocknote
a46099fe7b14fd6177cedd9034bd22c05d0a0431
826
hpp
C++
scratch/simulator/mutils.hpp
2535Rover/RoverSystem
300dd4d754bac2e4caff25ed1da244c109d289be
[ "Apache-2.0" ]
1
2018-10-16T02:32:49.000Z
2018-10-16T02:32:49.000Z
scratch/simulator/mutils.hpp
2535Rover/RoverSystem
300dd4d754bac2e4caff25ed1da244c109d289be
[ "Apache-2.0" ]
13
2018-10-23T20:35:10.000Z
2018-11-23T22:44:32.000Z
scratch/simulator/mutils.hpp
2535Rover/RoverSystem
300dd4d754bac2e4caff25ed1da244c109d289be
[ "Apache-2.0" ]
1
2018-10-16T03:11:39.000Z
2018-10-16T03:11:39.000Z
#ifndef MUTILS_H #define MUTILS_H #ifndef M_PI #define M_PI 3.1415926535 #endif struct Mat3f { float data[9]; }; void mat3f_zero_inplace(Mat3f* mat); Mat3f mat3f_zero_copy(); void mat3f_identity_inplace(Mat3f* mat); Mat3f mat3f_identity_copy(); void mat3f_projection_inplace(Mat3f* mat, float left, float right, float top, float bottom); Mat3f mat3f_projection_copy(float left, float right, float top, float bottom); void mat3f_transformation_inplace(Mat3f* mat, float scale, float angle, float transx, float transy); Mat3f mat3f_transformation_copy(float scale, float angle, float transx, float transy); Mat3f mat3f_camera_copy(float scalex, float scaley, float angle, float transx, float transy); void mat3f_camera_inplace(Mat3f* mat, float scalex, float scaley, float angle, float transx, float transy); #endif
29.5
107
0.789346
2535Rover
a468ecf79ee24066e45867ca1d343e8bf12e8017
1,405
cpp
C++
C语言程序设计基础/H24. 爱刷题的PQ大神(选作).cpp
xiabee/BIT-CS
5d8d8331e6b9588773991a872c259e430ef1eae1
[ "Apache-2.0" ]
63
2021-01-10T02:32:17.000Z
2022-03-30T04:08:38.000Z
C语言程序设计基础/H24. 爱刷题的PQ大神(选作).cpp
xiabee/BIT-CS
5d8d8331e6b9588773991a872c259e430ef1eae1
[ "Apache-2.0" ]
2
2021-06-09T05:38:58.000Z
2021-12-14T13:53:54.000Z
C语言程序设计基础/H24. 爱刷题的PQ大神(选作).cpp
xiabee/BIT-CS
5d8d8331e6b9588773991a872c259e430ef1eae1
[ "Apache-2.0" ]
20
2021-01-12T11:49:36.000Z
2022-03-26T11:04:58.000Z
#include <stdio.h> #include <stdlib.h> #include <string.h> int cmp(const void *a, const void *b) { if (*((int*)a + 1) != *((int*)b + 1)) return -( *((int*)a + 1) - *((int*)b + 1) ); else { int na = *(int*)a; int nb = *(int*)b; char sa[15], sb[15]; int i = 0; while(na) { sa[i++] = na % 10 + '0'; na /= 10; } sa[i] = '\0'; for (int j = 0; j <= (i - 1) / 2; j++) { char temp = sa[j]; sa[j] = sa[i - 1 - j]; sa[i - 1 - j] = temp; } //printf ("%s\n", sa); i = 0; while(nb) { sb[i++] = nb % 10 + '0'; nb /= 10; } sb[i]= '\0'; for (int j = 0; j <= (i - 1) / 2; j++) { char temp = sb[j]; sb[j] = sb[i - 1 - j]; sb[i - 1 - j] = temp; } int len1 = strlen(sa), len2 = strlen(sb); if (len1 != len2) return len1 - len2; else return strcmp(sa, sb); } } int a[1000005][2]; int main() { char name[20]; gets(name); FILE * fp; fp = fopen(name, "r"); int T; fscanf (fp, "%d", &T); while(T--) { int n, i = 0; memset(a, 0, sizeof(a)); fscanf (fp, "%d", &n); int tmp = n; while(!feof(fp) && tmp--) { fscanf (fp, "%d %d", &a[i][0], &a[i][1]); i++; } qsort(a, n, sizeof(int)*2, cmp); if (a[0][1] < 100) printf ("This OJ is too easy for PQ Dashen!\n"); else { int i = 0; while(a[i][1] >= 100) { printf ("%d\n", a[i][0]); i++; } } if (T > 0) printf ("\n"); } fclose(fp); }
16.927711
83
0.427758
xiabee
a46d42802b4b60c8c3de875ebd2bfbb4ca07df86
6,699
cc
C++
src/server/signal_handler_thread.test.cc
dspeterson/dory
7261fb5481283fdd69b382c3cddbc9b9bd24366d
[ "Apache-2.0" ]
82
2016-06-11T23:12:40.000Z
2022-02-21T21:01:36.000Z
src/server/signal_handler_thread.test.cc
dspeterson/dory
7261fb5481283fdd69b382c3cddbc9b9bd24366d
[ "Apache-2.0" ]
18
2016-06-16T22:55:12.000Z
2020-07-02T10:32:53.000Z
src/server/signal_handler_thread.test.cc
dspeterson/dory
7261fb5481283fdd69b382c3cddbc9b9bd24366d
[ "Apache-2.0" ]
14
2016-06-15T18:34:08.000Z
2021-09-06T23:16:28.000Z
/* <server/signal_handler_thread.test.cc> ---------------------------------------------------------------------------- Copyright 2019 Dave Peterson <[email protected]> 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. ---------------------------------------------------------------------------- Unit tests for <server/signal_handler_thread.h>. */ #include <server/signal_handler_thread.h> #include <gtest/gtest.h> #include <atomic> #include <cstring> #include <signal.h> #include <sys/types.h> #include <unistd.h> #include <base/on_destroy.h> #include <base/sig_set.h> #include <base/time_util.h> #include <base/tmp_file.h> #include <base/zero.h> #include <base/wr/process_util.h> #include <base/wr/signal_util.h> #include <test_util/test_logging.h> #include <thread/fd_managed_thread.h> using namespace Base; using namespace Server; using namespace TestUtil; using namespace Thread; namespace { /* The fixture for testing class TFdManagedThread. */ class TSignalHandlerThreadTest : public ::testing::Test { protected: TSignalHandlerThreadTest() = default; ~TSignalHandlerThreadTest() override = default; void SetUp() override { } void TearDown() override { } }; // TSignalHandlerThreadTest static std::atomic<bool> GotSIGUSR1(false); static siginfo_t InfoSIGUSR1; static std::atomic<bool> GotSIGCHLD(false); static siginfo_t InfoSIGCHLD; static void SignalCallback(int signum, const siginfo_t &info) noexcept { ASSERT_TRUE((signum == SIGUSR1) || (signum == SIGCHLD)); switch (signum) { case SIGUSR1: { /* Do memcpy() _before_ setting GotSIGUSR1 so other thread is guaranteed to see what we wrote to InfoSIGUSR1 when it sees GotSIGUSR1 become true. */ std::memcpy(&InfoSIGUSR1, &info, sizeof(info)); GotSIGUSR1.store(true); break; } case SIGCHLD: { /* Do memcpy() _before_ setting GotSIGCHLD so other thread is guaranteed to see what we wrote to InfoSIGCHLD when it sees GotSIGCHLD become true. */ std::memcpy(&InfoSIGCHLD, &info, sizeof(info)); GotSIGCHLD.store(true); break; } default: { ASSERT_TRUE(false); break; } } } TEST_F(TSignalHandlerThreadTest, BasicTest) { Zero(InfoSIGUSR1); GotSIGUSR1.store(false); Zero(InfoSIGCHLD); GotSIGCHLD.store(false); TSignalHandlerThread &handler_thread = TSignalHandlerThread::The(); /* Make sure signal handler thread gets shut down, no matter what happens during test. */ auto thread_stop = OnDestroy( [&handler_thread]() noexcept { if (handler_thread.IsStarted()) { try { handler_thread.RequestShutdown(); handler_thread.Join(); } catch (...) { ASSERT_TRUE(false); } } }); handler_thread.Init(SignalCallback, {SIGUSR1, SIGCHLD}); handler_thread.Start(); const TSigSet mask = TSigSet::FromSigmask(); /* For this thread, all signals should be blocked (except SIGKILL and SIGSTOP, which can't be blocked) after call to Start(). Here we don't bother checking blocked status for POSIX realtime signals. */ for (int i = 1; i < 32 /* Linux-specific */; ++i) { ASSERT_TRUE((i == SIGKILL) || (i == SIGSTOP) || mask[i]); } ASSERT_FALSE(GotSIGUSR1.load()); ASSERT_EQ(InfoSIGUSR1.si_signo, 0); ASSERT_FALSE(GotSIGCHLD.load()); ASSERT_EQ(InfoSIGCHLD.si_signo, 0); /* Send SIGUSR1 to self. Then make sure our callback got called for SIGUSR1. */ int ret = Wr::kill(Wr::TDisp::Nonfatal, {}, getpid(), SIGUSR1); ASSERT_EQ(ret, 0); for (size_t i = 0; i < 1000; ++i) { if (GotSIGUSR1.load()) { break; } SleepMilliseconds(10); } ASSERT_TRUE(GotSIGUSR1.load()); ASSERT_EQ(InfoSIGUSR1.si_signo, SIGUSR1); ASSERT_FALSE(GotSIGCHLD.load()); ASSERT_EQ(InfoSIGCHLD.si_signo, 0); Zero(InfoSIGUSR1); GotSIGUSR1.store(false); /* fork() a child and cause the child to exit immediately. This will cause us to get SIGCHLD. Then make sure our callback got called for SIGCHLD. */ const pid_t pid = Wr::fork(); switch (pid) { case -1: { ASSERT_TRUE(false); // fork() failed break; } case 0: { /* Child exits immediately. Parent should then get SIGCHLD. */ _exit(0); break; } default: { break; // Parent continues executing. } } for (size_t i = 0; i < 1000; ++i) { if (GotSIGCHLD.load()) { break; } SleepMilliseconds(10); } ASSERT_TRUE(GotSIGCHLD.load()); ASSERT_EQ(InfoSIGCHLD.si_signo, SIGCHLD); ASSERT_EQ(InfoSIGCHLD.si_pid, pid); ASSERT_FALSE(GotSIGUSR1.load()); ASSERT_EQ(InfoSIGUSR1.si_signo, 0); Zero(InfoSIGCHLD); GotSIGCHLD.store(false); /* Try SIGUSR1 again to verify that we still get notified for a second signal. */ ret = Wr::kill(getpid(), SIGUSR1); ASSERT_EQ(ret, 0); for (size_t i = 0; i < 1000; ++i) { if (GotSIGUSR1.load()) { break; } SleepMilliseconds(10); } ASSERT_TRUE(GotSIGUSR1.load()); ASSERT_EQ(InfoSIGUSR1.si_signo, SIGUSR1); ASSERT_FALSE(GotSIGCHLD.load()); ASSERT_EQ(InfoSIGCHLD.si_signo, 0); /* Tell signal handler thread to shut down. Then verify that it shuts down properly. */ ASSERT_TRUE(handler_thread.IsStarted()); handler_thread.RequestShutdown(); for (size_t i = 0; i < 1000; ++i) { if (handler_thread.GetShutdownWaitFd().IsReadableIntr()) { break; } SleepMilliseconds(10); } ASSERT_TRUE(handler_thread.GetShutdownWaitFd().IsReadableIntr()); /* Make sure handler didn't throw an exception. */ try { handler_thread.Join(); } catch (const TFdManagedThread::TWorkerError &) { ASSERT_TRUE(false); } } } // namespace int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); TTmpFile test_logfile = InitTestLogging(argv[0]); return RUN_ALL_TESTS(); }
27.9125
79
0.627855
dspeterson
a46d8d2c231e1051c293f0be67af2890c51d33c2
5,629
hpp
C++
include/opengv/absolute_pose/modules/Epnp.hpp
PXLVision/opengv
e48f77da4db7b8cee36ec677ed4ff5c5354571bb
[ "BSD-3-Clause" ]
null
null
null
include/opengv/absolute_pose/modules/Epnp.hpp
PXLVision/opengv
e48f77da4db7b8cee36ec677ed4ff5c5354571bb
[ "BSD-3-Clause" ]
null
null
null
include/opengv/absolute_pose/modules/Epnp.hpp
PXLVision/opengv
e48f77da4db7b8cee36ec677ed4ff5c5354571bb
[ "BSD-3-Clause" ]
null
null
null
/****************************************************************************** * Author: Laurent Kneip * * Contact: [email protected] * * License: Copyright (c) 2013 Laurent Kneip, ANU. All rights reserved. * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * * Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * * Neither the name of ANU 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 ANU OR THE 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. * ******************************************************************************/ // Note: this code has been downloaded from the homepage of the "Computer // Vision Laboratory" at EPFL Lausanne, and was originally developped by the // authors of [4]. I only adapted it to Eigen. #ifndef OPENGV_ABSOLUTE_POSE_MODULES_EPNP_HPP_ #define OPENGV_ABSOLUTE_POSE_MODULES_EPNP_HPP_ #include <stdlib.h> #include <Eigen/Eigen> namespace opengv { namespace absolute_pose { namespace modules { class Epnp { public: Epnp(void); ~Epnp(); void set_maximum_number_of_correspondences(const int n); void reset_correspondences(void); void add_correspondence( const double X, const double Y, const double Z, const double x, const double y, const double z); double compute_pose(double R[3][3], double T[3]); void relative_error( double & rot_err, double & transl_err, const double Rtrue[3][3], const double ttrue[3], const double Rest[3][3], const double test[3]); void print_pose(const double R[3][3], const double t[3]); double reprojection_error(const double R[3][3], const double t[3]); private: void choose_control_points(void); void compute_barycentric_coordinates(void); void fill_M( Eigen::MatrixXd & M, const int row, const double * alphas, const double u, const double v); void compute_ccs(const double * betas, const Eigen::MatrixXd & ut); void compute_pcs(void); void solve_for_sign(void); void find_betas_approx_1( const Eigen::Matrix<double,6,10> & L_6x10, const Eigen::Matrix<double,6,1> & Rho, double * betas); void find_betas_approx_2( const Eigen::Matrix<double,6,10> & L_6x10, const Eigen::Matrix<double,6,1> & Rho, double * betas); void find_betas_approx_3( const Eigen::Matrix<double,6,10> & L_6x10, const Eigen::Matrix<double,6,1> & Rho, double * betas); void qr_solve( Eigen::Matrix<double,6,4> & A, Eigen::Matrix<double,6,1> & b, Eigen::Matrix<double,4,1> & X); double dot(const double * v1, const double * v2); double dist2(const double * p1, const double * p2); void compute_rho(Eigen::Matrix<double,6,1> & Rho); void compute_L_6x10( const Eigen::MatrixXd & Ut, Eigen::Matrix<double,6,10> & L_6x10 ); void gauss_newton( const Eigen::Matrix<double,6,10> & L_6x10, const Eigen::Matrix<double,6,1> & Rho, double current_betas[4]); void compute_A_and_b_gauss_newton( const Eigen::Matrix<double,6,10> & L_6x10, const Eigen::Matrix<double,6,1> & Rho, double cb[4], Eigen::Matrix<double,6,4> & A, Eigen::Matrix<double,6,1> & b); double compute_R_and_t( const Eigen::MatrixXd & Ut, const double * betas, double R[3][3], double t[3]); void estimate_R_and_t(double R[3][3], double t[3]); void copy_R_and_t( const double R_dst[3][3], const double t_dst[3], double R_src[3][3], double t_src[3]); void mat_to_quat(const double R[3][3], double q[4]); double uc, vc, fu, fv; double * pws, * us, * alphas, * pcs; int * signs; //added! int maximum_number_of_correspondences; int number_of_correspondences; double cws[4][3], ccs[4][3]; double cws_determinant; }; } } } #endif /* OPENGV_ABSOLUTE_POSE_MODULES_EPNP_HPP_ */
34.962733
80
0.606324
PXLVision
a46fdc9e38e3404e73486cc2634bf47e4e824d7b
873
cpp
C++
source/Ch08/drill/drill2.cpp
AttilaAV/UDProg-Introduction
791fe2120cfa3c47346e28cc588d06420842cf5f
[ "CC0-1.0" ]
null
null
null
source/Ch08/drill/drill2.cpp
AttilaAV/UDProg-Introduction
791fe2120cfa3c47346e28cc588d06420842cf5f
[ "CC0-1.0" ]
null
null
null
source/Ch08/drill/drill2.cpp
AttilaAV/UDProg-Introduction
791fe2120cfa3c47346e28cc588d06420842cf5f
[ "CC0-1.0" ]
null
null
null
#include "std_lib_facilities.h" void swap_v(int a, int b) { int temp{0}; temp = a; a = b; b = temp; } void swap_r(int& a, int& b) { int temp{0}; temp = a; a = b; b = temp; } /* THIS FUNC WONT COMPILE BECAUSE CONSTS ARE READ-ONLY error: assignment of read-only reference ‘a’ 'b' void swap_cr(const int& a, const int& b) { int temp{0}; temp = a; a = b; b = temp; } */ int main() { int x = 7; int y = 9; cout << "x = " << x << " y = " << y << endl; cout << "calling swap_r" << endl; swap_r(x,y); cout << "x = " << x << " y = " << y << endl << endl; cout << "x = " << x << " y = " << y << endl; cout << "calling swap_v" << endl; swap_v(x,y); cout << "x = " << x << " y = " << y << endl << endl; // nothing changes cus, they are only swaped in the function //swap_r(7, 9); const int cx = 7; const int cy = 9; //not working with const, read only! }
18.574468
114
0.532646
AttilaAV
a4702beab18564bd72014078d1a3c51a34e93b1e
429
hpp
C++
src/afk/ai/behaviour/BaseBehaviour.hpp
christocs/ICT397
5ff6e4ed8757effad19b88fdb91f36504208f942
[ "ISC" ]
null
null
null
src/afk/ai/behaviour/BaseBehaviour.hpp
christocs/ICT397
5ff6e4ed8757effad19b88fdb91f36504208f942
[ "ISC" ]
null
null
null
src/afk/ai/behaviour/BaseBehaviour.hpp
christocs/ICT397
5ff6e4ed8757effad19b88fdb91f36504208f942
[ "ISC" ]
null
null
null
#pragma once #include <glm/glm.hpp> namespace Afk { namespace AI { /** * Base AI movement behaviour */ class BaseBehaviour { public: /** * Get a new position based on the current position */ virtual auto update(const glm::vec3 &current_position) -> glm::vec3 = 0; protected: BaseBehaviour() = default; virtual ~BaseBehaviour() = default; }; } }
18.652174
78
0.571096
christocs
a470ed5fdcb650839dcf406dfd58513c260183f0
8,750
cpp
C++
src/main/cpp/subsystems/Climber.cpp
frc3512/Robot-2020
c6811155900ccffba93ea9ba131192dcb9fcb1bd
[ "BSD-3-Clause" ]
10
2020-02-07T04:13:15.000Z
2022-02-26T00:13:39.000Z
src/main/cpp/subsystems/Climber.cpp
frc3512/Robot-2020
c6811155900ccffba93ea9ba131192dcb9fcb1bd
[ "BSD-3-Clause" ]
82
2020-02-12T03:05:15.000Z
2022-02-18T02:14:38.000Z
src/main/cpp/subsystems/Climber.cpp
frc3512/Robot-2020
c6811155900ccffba93ea9ba131192dcb9fcb1bd
[ "BSD-3-Clause" ]
5
2020-02-14T16:24:01.000Z
2022-03-31T09:10:01.000Z
// Copyright (c) 2020-2021 FRC Team 3512. All Rights Reserved. #include "subsystems/Climber.hpp" #include <cmath> #include <frc/DriverStation.h> #include <frc/Joystick.h> #include <frc/RobotBase.h> #include <frc/RobotController.h> #include <frc/StateSpaceUtil.h> #include <frc/smartdashboard/SmartDashboard.h> #include <wpi/MathExtras.h> #include <wpi/numbers> #include "CANSparkMaxUtil.hpp" #include "HWConfig.hpp" #include "subsystems/Turret.hpp" using namespace frc3512; using namespace frc3512::HWConfig::Climber; Climber::Climber(Turret& turret) : m_turret{turret} { SetCANSparkMaxBusUsage(m_elevator, Usage::kPositionOnly); m_elevator.SetSmartCurrentLimit(40); SetCANSparkMaxBusUsage(m_traverser, Usage::kMinimal); m_traverser.SetSmartCurrentLimit(40); m_matcher.AddColorMatch(kRedTarget); m_matcher.AddColorMatch(kBlueTarget); m_matcher.AddColorMatch(kGreenTarget); m_matcher.AddColorMatch(kYellowTarget); } units::meter_t Climber::GetElevatorPosition() { constexpr double kG = 1.0 / 20.0; // Gear ratio if constexpr (frc::RobotBase::IsSimulation()) { return units::meter_t{m_elevatorSim.GetOutput(0)}; } else { double rotations = -m_elevatorEncoder.GetPosition(); return units::meter_t{ 0.04381 * wpi::numbers::pi * kG * rotations / (1.0 + 0.014983 * wpi::numbers::pi * kG * rotations)}; } } bool Climber::HasPassedTopLimit() { // Top of travel is 52.75 inches IRL return GetElevatorPosition() > 1.1129_m; } bool Climber::HasPassedBottomLimit() { return GetElevatorPosition() < 0_m; } units::volt_t Climber::GetElevatorMotorOutput() const { return units::volt_t{-m_elevator.Get()}; } void Climber::RobotPeriodic() { m_elevatorEncoderEntry.SetDouble(GetElevatorPosition().to<double>()); m_changedColorNumEntry.SetDouble(m_changedColorCount); m_currentColor = m_matcher.MatchClosestColor(m_colorSensor.GetColor(), m_confidence); if (m_currentColor == kRedTarget) { m_colorSensorOutputEntry.SetString("Red"); } else if (m_currentColor == kBlueTarget) { m_colorSensorOutputEntry.SetString("Blue"); } else if (m_currentColor == kYellowTarget) { m_colorSensorOutputEntry.SetString("Yellow"); } else if (m_currentColor == kGreenTarget) { m_colorSensorOutputEntry.SetString("Green"); } else { m_colorSensorOutputEntry.SetString("No Color"); } if (m_state == ControlPanelState::kInit) { m_colorStateMachineEntry.SetString("Init"); } else if (m_state == ControlPanelState::kRotateWheel) { m_colorStateMachineEntry.SetString("Rotate Wheel"); } else if (m_state == ControlPanelState::kStopOnColor) { m_colorStateMachineEntry.SetString("Stop on Color"); } if constexpr (frc::RobotBase::IsSimulation()) { m_elevatorSim.SetInput(frc::MakeMatrix<1, 1>( -m_elevator.Get() * frc::RobotController::GetInputVoltage())); m_elevatorSim.Update(20_ms); } } void Climber::TeleopPeriodic() { static frc::Joystick appendageStick1{HWConfig::kAppendageStick1Port}; static frc::Joystick appendageStick2{HWConfig::kAppendageStick2Port}; // Climber traverser if (m_state == ControlPanelState::kInit) { SetTraverser(appendageStick2.GetX()); } bool readyToClimb = m_debouncer.Calculate(appendageStick1.GetRawButton(1) && std::abs(appendageStick1.GetY()) > 0.02); if (!m_prevReadyToClimb && readyToClimb) { // Move the turret out of the way of the climber and set new soft limit. // Also, disable auto-aim. m_turret.SetGoal(units::radian_t{wpi::numbers::pi / 2}, 0_rad_per_s); m_turret.SetControlMode(TurretController::ControlMode::kClosedLoop); m_turret.SetCWLimit(Turret::kCWLimitForClimbing); } else if (!readyToClimb && GetElevatorPosition() < 1.5_in) { // Let turret move full range again once climber is back down m_turret.SetCWLimit(TurretController::kCWLimit); } m_prevReadyToClimb = readyToClimb; // Make sure the turret is out of the way of the climber elevator before // moving it if (appendageStick1.GetRawButton(1) && !m_turret.HasPassedCWLimit()) { SetElevator(-appendageStick1.GetY()); } else { SetElevator(0.0); } // Control panel if (appendageStick1.GetRawButtonPressed(6)) { m_colorSensorArm.Set(0.5); } else if (appendageStick1.GetRawButtonPressed(7)) { m_colorSensorArm.Set(0.0); } if (appendageStick1.GetRawButtonPressed(8)) { m_state = ControlPanelState::kRotateWheel; m_prevColor = m_currentColor; m_startColor = m_currentColor; } else if (appendageStick1.GetRawButtonPressed(9)) { m_state = ControlPanelState::kStopOnColor; } RunControlPanelSM(); } void Climber::TestPeriodic() { static frc::Joystick appendageStick1{HWConfig::kAppendageStick1Port}; // Positive voltage should move climber in the positive X direction double speed = -appendageStick1.GetY(); // Ignore soft limits so the user can manually reset the elevator before // rebooting the robot if (std::abs(speed) > 0.02) { // Unlock climber if it's being commanded to move m_pancake.Set(true); m_elevator.Set(-speed); } else { m_pancake.Set(false); m_elevator.Set(0.0); } } void Climber::SetTraverser(double speed) { static constexpr double kDeadband = 0.1; static constexpr double kMinInput = 0.5; // Apply a deadband to the input to avoid chattering if (std::abs(speed) < kDeadband) { speed = 0.0; } // This equation rescales the following function // // [-1 .. 0) -> [-1 .. 0) and 0 -> 0 and (0 .. 1] -> (0 .. 1] // // to // // [-1 .. 0) -> [-1 .. -0.5) and 0 -> 0 and (0 .. 1] -> (0.5 .. 1] // // This provides a minimum input of 0.5 in either direction to overcome // friction while still linearly increasing to 1. m_traverser.Set((1.0 - kMinInput) * speed + kMinInput * wpi::sgn(speed)); } void Climber::SetElevator(double speed) { if ((speed > 0.02 && !HasPassedTopLimit()) || (speed < -0.02 && !HasPassedBottomLimit())) { // Unlock climber if it's being commanded to move m_pancake.Set(true); m_elevator.Set(-speed); } else { m_pancake.Set(false); m_elevator.Set(0.0); } } void Climber::RunControlPanelSM() { // If climbing, stop control panel mechanism if the process never completed if (m_state != ControlPanelState::kInit && GetElevatorPosition() > 1.5_in) { SetTraverser(0.0); m_state = ControlPanelState::kInit; } if (m_state == ControlPanelState::kInit) { } else if (m_state == ControlPanelState::kRotateWheel) { SetTraverser(1.0); // Check that the wheel has spun to the same color as the beginning // color. If previous color is the same as the start color, control // panel hasn't been moved yet. if (m_currentColor == m_startColor && m_prevColor != m_startColor) { m_changedColorCount++; } if (m_prevColor != m_currentColor) { m_prevColor = m_currentColor; } // 3 to 5 rotations of the control panel are required in the match. // Each color appears twice on the control panel, and the state machine // rotates the wheel 3.5 times. 2 * 3.5 = 7, so when a color is detected // 7 times, 3.5 rotations have occurred. if (m_changedColorCount >= 7) { SetTraverser(0.0); m_changedColorCount = 0; m_state = ControlPanelState::kInit; } } else if (m_state == ControlPanelState::kStopOnColor) { SetTraverser(1.0); // Read game-specific data from the Field Management System (FMS) char desiredColor = frc::DriverStation::GetInstance().GetGameSpecificMessage()[0]; // If there's no game-specific data, stop the state machine if (desiredColor != 'Y' && desiredColor != 'R' && desiredColor != 'B' && desiredColor != 'G') { m_state = ControlPanelState::kInit; } // If the color sensor is 90° away from the desired color, stop moving if ((desiredColor == 'Y' && m_currentColor == kGreenTarget) || (desiredColor == 'R' && m_currentColor == kBlueTarget) || (desiredColor == 'B' && m_currentColor == kRedTarget) || (desiredColor == 'G' && m_currentColor == kYellowTarget)) { SetTraverser(0.0); m_state = ControlPanelState::kInit; } } }
35.140562
80
0.648686
frc3512
a4746f359ddf371aceff41bb484ccbb6791f8527
457
cpp
C++
src/codechef/contests/LP1TO202/COLGLF2.cpp
tllaw/cp
91c131792cd00ebd12f7a2dddb26a863970b00ce
[ "MIT" ]
null
null
null
src/codechef/contests/LP1TO202/COLGLF2.cpp
tllaw/cp
91c131792cd00ebd12f7a2dddb26a863970b00ce
[ "MIT" ]
null
null
null
src/codechef/contests/LP1TO202/COLGLF2.cpp
tllaw/cp
91c131792cd00ebd12f7a2dddb26a863970b00ce
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(0); cin.tie(0); long long t, s, e, l; cin >> t; while(t--) { cin >> s; long long q[s] = {0}, r = 0; for(long long i = 0; i < s; i++) { cin >> q[i]; r += q[i]; } for(long long i = 0; i < s; i++) { cin >> e; while(e--) { cin >> l; r += l - q[i]; } } cout << r << endl; } return 0; }
13.441176
38
0.391685
tllaw
a4747547e801bbff6eb42cb93ffe61adc6192ca6
4,708
cpp
C++
src/updater.cpp
DarXe/Logus
af80cdcaccde3c536ef2b47d36912d9a505f7ef6
[ "0BSD" ]
6
2019-06-11T20:09:01.000Z
2021-05-28T01:18:27.000Z
src/updater.cpp
DarXe/Logus
af80cdcaccde3c536ef2b47d36912d9a505f7ef6
[ "0BSD" ]
7
2019-06-14T20:28:31.000Z
2020-08-11T14:51:03.000Z
src/updater.cpp
DarXe/Logus
af80cdcaccde3c536ef2b47d36912d9a505f7ef6
[ "0BSD" ]
1
2020-11-07T05:28:23.000Z
2020-11-07T05:28:23.000Z
// Copyright © 2020 Niventill // This file is licensed under ISC License. See "LICENSE" in the top level directory for more info. //standard libraries #include <filesystem> #include <iostream> #include <fstream> //header includes #include <config.hpp> #include <var.hpp> #include <common.hpp> #include <debug.hpp> #include <stopwatch.hpp> #include <ver.hpp> #include "updater.hpp" void updateDependencies() { if (updateChannel != "disable") { if (!std::filesystem::exists("bin")) std::filesystem::create_directory("bin"); if (!std::filesystem::exists("bin\\curl.exe")) { if (std::filesystem::exists("c:\\windows\\system32\\curl.exe")) std::filesystem::copy("c:\\windows\\system32\\curl.exe", "bin\\curl.exe"); if (!std::filesystem::exists("bin\\curl.exe")) engLang ? std::cout << " Couldn't find curl, auto-update will be limited.\n" : std::cout << " Nie udało się znaleźć curl. Możliwości auto-update będą ograniczone.\n"; else cls(); } } } void checkLogusUpdate() { int fail = 0; std::fstream check; std::string repoVersion; engLang ? std::cout << " Checking updates, please wait...\n" : std::cout << " Sprawdzanie aktualizacji. Proszę czekać...\n"; if (updateChannel == "release") fail = system("bin\\curl --progress-bar --fail https://raw.githubusercontent.com/DarXe/Logus/master/version -o version.tmp"); else if (updateChannel == "experimental" || updateChannel == "nightly") fail = system("bin\\curl --progress-bar --fail https://raw.githubusercontent.com/DarXe/Logus/experimental/version_experimental -o version.tmp"); if (fail) { remove("version.tmp"); return; } cls(); check.open("version.tmp"); long long repoVersionNumber = 0; if (check.good()) { getline(check, repoVersion); try { repoVersionNumber = stoll(repoVersion); } catch (...) { engLang ? std::cout << " Error while checking version \"" << repoVersion << "\".\n" : std::cout << " Błąd podczas sprawdzania wersji \"" << repoVersion << "\".\n"; return; } if (repoVersionNumber == getLogusBuildVersion()) { engLang ? std::cout << " Checking successful! Logus is up to date.\n" : std::cout << " Sprawdzanie powiodło się! Posiadasz najnowszą wersję.\n"; return; } else if (repoVersionNumber < getLogusBuildVersion()) { engLang ? std::cout << " Checking successful! Logus is newer than the version in the repository.\n" : std::cout << " Sprawdzanie powiodło się! Posiadasz wersją nowszą niż ta obecna w repozytorium.\n"; return; } } else { engLang ? std::cout << " Couldn't find curl, auto update will not be possible.\n" : std::cout << " Nie udało się znaleźć curl. Aktualizacja nie będzie możliwa.\n"; return; } if (updateChannel == "release" && repoVersionNumber > getLogusBuildVersion()) { engLang ? std::cout << " Updating Logus, please wait...\n" : std::cout << " Aktualizowanie Logusia. Proszę czekać...\n"; rename("Logus.exe", "Logusold.exe"); Stopwatch rele; fail = system("bin\\curl --progress-bar --fail --location https://github.com/DarXe/Logus/releases/latest/download/Logus.exe -o Logus.exe"); rele.stop(); LDebug::DebugOutput("Pobieranie Logus (release): wersja: %s, czas: %s", {repoVersion, rele.pre(ms)}); } else if ((updateChannel == "experimental" || updateChannel == "nightly") && repoVersionNumber > getLogusBuildVersion()) { if (updateChannel == "nightly") updateChannel = "experimental"; engLang ? std::cout << " Updating Logus, please wait...\n" : std::cout << " Aktualizowanie Logusia. Proszę czekać...\n"; rename("Logus.exe", "Logusold.exe"); Stopwatch exp; fail = system("bin\\curl --progress-bar --fail --location https://raw.githubusercontent.com/DarXe/Logus/experimental/Logus.exe -o Logus.exe"); exp.stop(); LDebug::DebugOutput("Pobieranie Logus (experimental): wersja: %s, czas: %s", {repoVersion, exp.pre(ms)}); } if (fail) { engLang ? std::cout << " Update unsuccessful!\n" : std::cout << " Aktualizacja nie powiodła się!\n"; remove("Logus.exe"); rename("Logusold.exe", "Logus.exe"); } else { engLang ? std::cout << " Update successful! Restart Logus to finish the installation.\n" : std::cout << " Aktualizacja powiodła się! Zrestartuj Logusia aby dokończyć aktualizację.\n"; } check.close(); remove("version.tmp"); } void checkUpdates() { SetConsoleTextAttribute(h, 10); if (getVer() != getLogusBuildVersion()) { saveConfig(0); showUpdateInfo(); remove("Logusold.exe"); } else { if (updateChannel != "disable") checkLogusUpdate(); } }
34.874074
206
0.647409
DarXe
a47bf8f6ba17ef54debc2e7d6d15ba1727eded46
4,446
cpp
C++
lib/maths/Spline.cpp
maldicion069/monkeybrush-
2bccca097402ff1f5344e356f06de19c8c70065b
[ "MIT" ]
1
2016-11-15T09:04:12.000Z
2016-11-15T09:04:12.000Z
lib/maths/Spline.cpp
maldicion069/monkeybrush-
2bccca097402ff1f5344e356f06de19c8c70065b
[ "MIT" ]
null
null
null
lib/maths/Spline.cpp
maldicion069/monkeybrush-
2bccca097402ff1f5344e356f06de19c8c70065b
[ "MIT" ]
null
null
null
/* * Copyright (c) 2016 maldicion069 * * Authors: Cristian Rodríguez Bernal <[email protected]> * * This file is part of MonkeyBrushPlusPlus <https://github.com/maldicion069/monkeybrushplusplus> * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3.0 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 Street, Fifth Floor, Boston, MA 02110-1301 USA. * */ #include "Spline.hpp" #include "Interpolation.hpp" #include "Mathf.hpp" namespace mb { Spline2D::Spline2D(InterpolationMode intpMode, const std::vector<Vect2>& points) : _intpMode(intpMode) , controlPoints(points) { } Vect2 Spline2D::evaluate(const float t) { auto point = (this->controlPoints.size() - 1) * t; auto intPoint = std::floor(point); auto w = point - intPoint; Vect2 p0 = this->controlPoints[intPoint == 0 ? intPoint : intPoint - 1]; Vect2 p1 = this->controlPoints[intPoint]; Vect2 p2 = this->controlPoints[intPoint > this->controlPoints.size() - 2 ? this->controlPoints.size() - 1 : intPoint + 1]; Vect2 p3 = this->controlPoints[intPoint > this->controlPoints.size() - 3 ? this->controlPoints.size() - 1 : intPoint + 2]; switch (_intpMode) { case InterpolationMode::catmullRom: return Vect2( Interpolation::catmullRom(p0.x(), p1.x(), p2.x(), p3.x(), w), Interpolation::catmullRom(p0.y(), p1.y(), p2.y(), p3.y(), w) ); break; case InterpolationMode::linear: return Vect2( Interpolation::linear(p0.x(), p3.x(), w), Interpolation::linear(p0.y(), p3.y(), w) ); break; case InterpolationMode::bezier: return Vect2( Interpolation::bezier(p0.x(), p1.x(), p2.x(), p3.x(), w), Interpolation::bezier(p0.y(), p1.y(), p2.y(), p3.y(), w) ); break; } throw; } Spline3D::Spline3D(InterpolationMode intpMode, const std::vector<Vect3>& points) : _intpMode(intpMode) , controlPoints(points) { } Vect3 Spline3D::evaluate(const float t) { auto point = (this->controlPoints.size() - 1) * t; auto intPoint = std::floor(point); auto w = point - intPoint; Vect3 p0 = this->controlPoints[intPoint == 0 ? intPoint : intPoint - 1]; Vect3 p1 = this->controlPoints[intPoint]; Vect3 p2 = this->controlPoints[intPoint > this->controlPoints.size() - 2 ? this->controlPoints.size() - 1 : intPoint + 1]; Vect3 p3 = this->controlPoints[intPoint > this->controlPoints.size() - 3 ? this->controlPoints.size() - 1 : intPoint + 2]; switch (_intpMode) { case InterpolationMode::catmullRom: return Vect3( Interpolation::catmullRom(p0.x(), p1.x(), p2.x(), p3.x(), w), Interpolation::catmullRom(p0.y(), p1.y(), p2.y(), p3.y(), w), Interpolation::catmullRom(p0.z(), p1.z(), p2.z(), p3.z(), w) ); break; case InterpolationMode::linear: return Vect3( Interpolation::linear(p0.x(), p3.x(), w), Interpolation::linear(p0.y(), p3.y(), w), Interpolation::linear(p0.z(), p3.z(), w) ); break; case InterpolationMode::bezier: return Vect3( Interpolation::bezier(p0.x(), p1.x(), p2.x(), p3.x(), w), Interpolation::bezier(p0.y(), p1.y(), p2.y(), p3.y(), w), Interpolation::bezier(p0.z(), p1.z(), p2.z(), p3.z(), w) ); break; } throw; } Vect3 Spline3D::getTangent(const float oldDT, const float currentDT) { Vect3 p0 = this->evaluate(oldDT); Vect3 p1 = this->evaluate(currentDT); Vect3 s = Vect3::sub(p1, p0); s.normalize(); return s; } float Spline3D::angleBetweenPoints(const float oldDT, const float currentDT) { Vect3 p0 = this->evaluate(oldDT); Vect3 p1 = this->evaluate(currentDT); float angle = std::atan2(p1.z() - p0.z(), p1.x() - p0.x()); return Mathf::degToRad(angle); } }
33.428571
96
0.617859
maldicion069
a481147d9118873aea62da21afee94fea64fe1f5
17,033
hpp
C++
core/ntsSingleCPUGraphOp.hpp
Sanzo00/NeutronStarLite
57d92d1f7f6cd55c55a83ca086096a710185d531
[ "Apache-2.0" ]
1
2022-03-10T07:41:55.000Z
2022-03-10T07:41:55.000Z
core/ntsSingleCPUGraphOp.hpp
Sanzo00/NeutronStarLite
57d92d1f7f6cd55c55a83ca086096a710185d531
[ "Apache-2.0" ]
null
null
null
core/ntsSingleCPUGraphOp.hpp
Sanzo00/NeutronStarLite
57d92d1f7f6cd55c55a83ca086096a710185d531
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2021-2022 Qiange Wang, Northeastern University Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef NTSSINGLECPUGRAPHOP_HPP #define NTSSINGLECPUGRAPHOP_HPP #include <assert.h> #include <map> #include <math.h> #include <stack> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <vector> #include "core/graph.hpp" #include "core/ntsBaseOp.hpp" #include "core/PartitionedGraph.hpp" namespace nts { namespace op { class SingleCPUSrcDstScatterOp : public ntsGraphOp{ public: std::vector<CSC_segment_pinned *> subgraphs; SingleCPUSrcDstScatterOp(PartitionedGraph *partitioned_graph,VertexSubset *active) : ntsGraphOp(partitioned_graph, active) { subgraphs = partitioned_graph->graph_chunks; } NtsVar forward(NtsVar &f_input){ int feature_size = f_input.size(1); NtsVar f_output=graph_->Nts->NewKeyTensor({graph_->gnnctx->l_e_num, 2*feature_size},torch::DeviceType::CPU); ValueType *f_input_buffer = graph_->Nts->getWritableBuffer(f_input, torch::DeviceType::CPU); ValueType *f_output_buffer = graph_->Nts->getWritableBuffer(f_output, torch::DeviceType::CPU); graph_->local_vertex_operation<int, ValueType>( // For EACH Vertex [&](VertexId vtx, CSC_segment_pinned *subgraph, VertexId recv_id) { // iterate the incoming edge for vtx for (long eid = subgraph->column_offset[vtx]; eid < subgraph->column_offset[vtx + 1]; eid++) { VertexId src = subgraph->row_indices[eid]; nts_copy(f_output_buffer, eid * 2, f_input_buffer, src, feature_size,1); nts_copy(f_output_buffer, eid * 2 + 1, f_input_buffer, vtx, feature_size,1); } }, subgraphs, feature_size, active_); return f_output; } NtsVar backward(NtsVar &f_output_grad){ int feature_size=f_output_grad.size(1); assert(feature_size%2==0); NtsVar f_input_grad=graph_->Nts->NewLeafTensor({graph_->gnnctx->l_v_num, feature_size/2},torch::DeviceType::CPU); ValueType *f_input_grad_buffer = graph_->Nts->getWritableBuffer(f_input_grad, torch::DeviceType::CPU); ValueType *f_output_grad_buffer = graph_->Nts->getWritableBuffer(f_output_grad, torch::DeviceType::CPU); feature_size/=2; graph_->local_vertex_operation<int, ValueType>( // For EACH Vertex [&](VertexId vtx, CSC_segment_pinned *subgraph, VertexId recv_id) { // iterate the incoming edge for vtx for (long eid = subgraph->column_offset[vtx]; eid < subgraph->column_offset[vtx + 1]; eid++) { VertexId src = subgraph->row_indices[eid]; nts_acc(f_input_grad_buffer + src * feature_size, f_output_grad_buffer + (feature_size * eid * 2), feature_size); nts_acc(f_input_grad_buffer + vtx * feature_size, f_output_grad_buffer + (feature_size * (eid * 2 + 1)), feature_size); } }, subgraphs, feature_size, active_); return f_input_grad; } }; class SingleCPUSrcScatterOp : public ntsGraphOp{ public: std::vector<CSC_segment_pinned *> subgraphs; SingleCPUSrcScatterOp(PartitionedGraph *partitioned_graph,VertexSubset *active) : ntsGraphOp(partitioned_graph, active) { subgraphs = partitioned_graph->graph_chunks; } NtsVar forward(NtsVar &f_input){ int feature_size = f_input.size(1); NtsVar f_output=graph_->Nts->NewKeyTensor({graph_->gnnctx->l_e_num, feature_size},torch::DeviceType::CPU); ValueType *f_input_buffer = graph_->Nts->getWritableBuffer(f_input, torch::DeviceType::CPU); ValueType *f_output_buffer = graph_->Nts->getWritableBuffer(f_output, torch::DeviceType::CPU); graph_->local_vertex_operation<int, ValueType>( // For EACH Vertex [&](VertexId vtx, CSC_segment_pinned *subgraph, VertexId recv_id) { // iterate the incoming edge for vtx for (long eid = subgraph->column_offset[vtx]; eid < subgraph->column_offset[vtx + 1]; eid++) { VertexId src = subgraph->row_indices[eid]; nts_copy(f_output_buffer, eid, f_input_buffer, src, feature_size,1); } }, subgraphs, feature_size, active_); return f_output; } NtsVar backward(NtsVar &f_output_grad){ int feature_size=f_output_grad.size(1); NtsVar f_input_grad=graph_->Nts->NewLeafTensor({graph_->gnnctx->l_v_num, feature_size},torch::DeviceType::CPU); ValueType *f_input_grad_buffer = graph_->Nts->getWritableBuffer(f_input_grad, torch::DeviceType::CPU); ValueType *f_output_grad_buffer = graph_->Nts->getWritableBuffer(f_output_grad, torch::DeviceType::CPU); graph_->local_vertex_operation<int, ValueType>( // For EACH Vertex [&](VertexId vtx, CSC_segment_pinned *subgraph, VertexId recv_id) { // iterate the incoming edge for vtx for (long eid = subgraph->column_offset[vtx]; eid < subgraph->column_offset[vtx + 1]; eid++) { VertexId src = subgraph->row_indices[eid]; nts_acc(f_output_grad_buffer + (feature_size * eid), f_input_grad_buffer + src * feature_size, feature_size); } }, subgraphs, feature_size, active_); return f_input_grad; } }; class SingleCPUDstAggregateOp : public ntsGraphOp{ public: std::vector<CSC_segment_pinned *> subgraphs; SingleCPUDstAggregateOp(PartitionedGraph *partitioned_graph,VertexSubset *active) : ntsGraphOp(partitioned_graph, active) { subgraphs = partitioned_graph->graph_chunks; } NtsVar forward(NtsVar &f_input){// input edge output vertex int feature_size = f_input.size(1); NtsVar f_output=graph_->Nts->NewKeyTensor({graph_->gnnctx->l_v_num, feature_size},torch::DeviceType::CPU); ValueType *f_input_buffer = graph_->Nts->getWritableBuffer(f_input, torch::DeviceType::CPU); ValueType *f_output_buffer = graph_->Nts->getWritableBuffer(f_output, torch::DeviceType::CPU); graph_->local_vertex_operation<int, ValueType>( // For EACH Vertex [&](VertexId vtx, CSC_segment_pinned *subgraph, VertexId recv_id) { // iterate the incoming edge for vtx for (long eid = subgraph->column_offset[vtx]; eid < subgraph->column_offset[vtx + 1]; eid++) { VertexId src = subgraph->row_indices[eid]; nts_acc(f_output_buffer + vtx * feature_size, f_input_buffer + eid * feature_size, feature_size); } }, subgraphs, feature_size, active_); return f_output; } NtsVar backward(NtsVar &f_output_grad){// input vtx grad; output edge grad int feature_size=f_output_grad.size(1); NtsVar f_input_grad=graph_->Nts->NewLeafTensor({graph_->gnnctx->l_e_num, feature_size},torch::DeviceType::CPU); ValueType *f_input_grad_buffer = graph_->Nts->getWritableBuffer(f_input_grad, torch::DeviceType::CPU); ValueType *f_output_grad_buffer = graph_->Nts->getWritableBuffer(f_output_grad, torch::DeviceType::CPU); graph_->local_vertex_operation<int, ValueType>( // For EACH Vertex [&](VertexId vtx, CSC_segment_pinned *subgraph, VertexId recv_id) { // iterate the incoming edge for vtx for (long eid = subgraph->column_offset[vtx]; eid < subgraph->column_offset[vtx + 1]; eid++) { VertexId src = subgraph->row_indices[eid]; nts_acc(f_input_grad_buffer+ (feature_size * eid), f_output_grad_buffer + vtx * feature_size, feature_size); } }, subgraphs, feature_size, active_); return f_input_grad; } }; class SingleCPUDstAggregateOpMin : public ntsGraphOp{ public: std::vector<CSC_segment_pinned *> subgraphs; VertexId* record; SingleCPUDstAggregateOpMin(PartitionedGraph *partitioned_graph,VertexSubset *active) : ntsGraphOp(partitioned_graph, active) { subgraphs = partitioned_graph->graph_chunks; } ~SingleCPUDstAggregateOpMin(){ delete [] record; } NtsVar forward(NtsVar &f_input){// input edge output vertex int feature_size = f_input.size(1); record=new VertexId(partitioned_graph_->owned_vertices*feature_size); NtsVar f_output=graph_->Nts->NewKeyTensor({graph_->gnnctx->l_v_num, feature_size},torch::DeviceType::CPU); ValueType *f_input_buffer = graph_->Nts->getWritableBuffer(f_input, torch::DeviceType::CPU); ValueType *f_output_buffer = graph_->Nts->getWritableBuffer(f_output, torch::DeviceType::CPU); graph_->local_vertex_operation<int, ValueType>( // For EACH Vertex [&](VertexId vtx, CSC_segment_pinned *subgraph, VertexId recv_id) { // iterate the incoming edge for vtx for (long eid = subgraph->column_offset[vtx]; eid < subgraph->column_offset[vtx + 1]; eid++) { VertexId src = subgraph->row_indices[eid]; nts_min(f_output_buffer+ vtx * feature_size, f_input_buffer + eid * feature_size, record + vtx * feature_size, feature_size,eid); } }, subgraphs, feature_size, active_); return f_output; } NtsVar backward(NtsVar &f_output_grad){// input vtx grad; output edge grad int feature_size=f_output_grad.size(1); NtsVar f_input_grad=graph_->Nts->NewLeafTensor({graph_->gnnctx->l_e_num, feature_size},torch::DeviceType::CPU); ValueType *f_input_grad_buffer = graph_->Nts->getWritableBuffer(f_input_grad, torch::DeviceType::CPU); ValueType *f_output_grad_buffer = graph_->Nts->getWritableBuffer(f_output_grad, torch::DeviceType::CPU); graph_->local_vertex_operation<int, ValueType>( // For EACH Vertex [&](VertexId vtx, CSC_segment_pinned *subgraph, VertexId recv_id) { // iterate the incoming edge for vtx nts_assign(f_input_grad_buffer, f_output_grad_buffer+feature_size*vtx, record+feature_size*vtx, feature_size); // for (long eid = subgraph->column_offset[vtx]; // eid < subgraph->column_offset[vtx + 1]; eid++) { // VertexId src = subgraph->row_indices[eid]; // //// nts_acc(f_input_grad_buffer+ (feature_size * eid), //// f_output_grad_buffer + vtx * feature_size, //// feature_size); // } }, subgraphs, feature_size, active_); return f_input_grad; } }; class SingleCPUDstAggregateOpMax : public ntsGraphOp{ public: std::vector<CSC_segment_pinned *> subgraphs; VertexId* record; SingleCPUDstAggregateOpMax(PartitionedGraph *partitioned_graph,VertexSubset *active) : ntsGraphOp(partitioned_graph, active) { subgraphs = partitioned_graph->graph_chunks; } ~SingleCPUDstAggregateOpMax(){ delete [] record; } NtsVar forward(NtsVar &f_input){// input edge output vertex int feature_size = f_input.size(1); record=new VertexId(partitioned_graph_->owned_vertices*feature_size); NtsVar f_output=graph_->Nts->NewKeyTensor({graph_->gnnctx->l_v_num, feature_size},torch::DeviceType::CPU); ValueType *f_input_buffer = graph_->Nts->getWritableBuffer(f_input, torch::DeviceType::CPU); ValueType *f_output_buffer = graph_->Nts->getWritableBuffer(f_output, torch::DeviceType::CPU); graph_->local_vertex_operation<int, ValueType>( // For EACH Vertex [&](VertexId vtx, CSC_segment_pinned *subgraph, VertexId recv_id) { // iterate the incoming edge for vtx for (long eid = subgraph->column_offset[vtx]; eid < subgraph->column_offset[vtx + 1]; eid++) { VertexId src = subgraph->row_indices[eid]; nts_max(f_output_buffer+ vtx * feature_size, f_input_buffer + eid * feature_size, record + vtx * feature_size, feature_size,eid); } }, subgraphs, feature_size, active_); return f_output; } NtsVar backward(NtsVar &f_output_grad){// input vtx grad; output edge grad int feature_size=f_output_grad.size(1); NtsVar f_input_grad=graph_->Nts->NewLeafTensor({graph_->gnnctx->l_e_num, feature_size},torch::DeviceType::CPU); ValueType *f_input_grad_buffer = graph_->Nts->getWritableBuffer(f_input_grad, torch::DeviceType::CPU); ValueType *f_output_grad_buffer = graph_->Nts->getWritableBuffer(f_output_grad, torch::DeviceType::CPU); graph_->local_vertex_operation<int, ValueType>( // For EACH Vertex [&](VertexId vtx, CSC_segment_pinned *subgraph, VertexId recv_id) { // iterate the incoming edge for vtx nts_assign(f_input_grad_buffer, f_output_grad_buffer+feature_size*vtx, record+feature_size*vtx, feature_size); // for (long eid = subgraph->column_offset[vtx]; // eid < subgraph->column_offset[vtx + 1]; eid++) { // VertexId src = subgraph->row_indices[eid]; // //// nts_acc(f_input_grad_buffer+ (feature_size * eid), //// f_output_grad_buffer + vtx * feature_size, //// feature_size); // } }, subgraphs, feature_size, active_); return f_input_grad; } }; class SingleEdgeSoftMax : public ntsGraphOp{ public: std::vector<CSC_segment_pinned *> subgraphs; NtsVar IntermediateResult; SingleEdgeSoftMax(PartitionedGraph *partitioned_graph,VertexSubset *active) : ntsGraphOp(partitioned_graph, active) { subgraphs = partitioned_graph->graph_chunks; } NtsVar forward(NtsVar &f_input_){// input i_msg output o_msg //NtsVar f_input_=f_input.detach(); int feature_size = f_input_.size(1); NtsVar f_output=graph_->Nts->NewKeyTensor({graph_->gnnctx->l_e_num, feature_size},torch::DeviceType::CPU); ValueType *f_input_buffer = graph_->Nts->getWritableBuffer(f_input_, torch::DeviceType::CPU); ValueType *f_output_buffer = graph_->Nts->getWritableBuffer(f_output, torch::DeviceType::CPU); graph_->local_vertex_operation<int, ValueType>( // For EACH Vertex [&](VertexId vtx, CSC_segment_pinned *subgraph, VertexId recv_id) { long eid_start = subgraph->column_offset[vtx]; long eid_end = subgraph->column_offset[vtx + 1]; assert(eid_end <= graph_->edges); assert(eid_start >= 0); NtsVar d = f_input_.slice(0, eid_start, eid_end, 1).softmax(0); ValueType *d_buffer = graph_->Nts->getWritableBuffer(d, torch::DeviceType::CPU); nts_copy(f_output_buffer, eid_start, d_buffer, 0, feature_size,(eid_end-eid_start)); }, subgraphs, f_input_.size(1), this->active_); IntermediateResult=f_output; return f_output; } NtsVar backward(NtsVar &f_output_grad){// input vtx grad; output edge grad int feature_size=f_output_grad.size(1); NtsVar f_input_grad=graph_->Nts->NewLeafTensor({graph_->gnnctx->l_e_num, feature_size},torch::DeviceType::CPU); ValueType *f_input_grad_buffer = graph_->Nts->getWritableBuffer(f_input_grad, torch::DeviceType::CPU); graph_->local_vertex_operation<int, ValueType>( // For EACH Vertex [&](VertexId vtx, CSC_segment_pinned *subgraph, VertexId recv_id) { long eid_start = subgraph->column_offset[vtx]; long eid_end = subgraph->column_offset[vtx + 1]; assert(eid_end <= graph_->edges); assert(eid_start >= 0); NtsVar d = f_output_grad.slice(0, eid_start, eid_end, 1); NtsVar imr =IntermediateResult.slice(0, eid_start, eid_end, 1); //s4=(s2*s1)-(s2)*(s2.t().mm(s1)); NtsVar d_o =(imr*d)-imr*(d.t().mm(imr)); ValueType *d_o_buffer = graph_->Nts->getWritableBuffer(d_o, torch::DeviceType::CPU); nts_copy(f_input_grad_buffer, eid_start, d_o_buffer, 0, feature_size,(eid_end-eid_start)); }, subgraphs, f_output_grad.size(1), this->active_); return f_input_grad; } }; } // namespace graphop } // namespace nts #endif
41.043373
86
0.655727
Sanzo00
a482b221c55ea3dd711168344e2d43bfc1c4f26f
2,062
cpp
C++
librbr/src/mdp/mdp.cpp
kylewray/librbr
ea3dcef7c37b4f177373ac6fec1f4c4566cf7bd8
[ "MIT" ]
null
null
null
librbr/src/mdp/mdp.cpp
kylewray/librbr
ea3dcef7c37b4f177373ac6fec1f4c4566cf7bd8
[ "MIT" ]
11
2015-04-02T01:32:47.000Z
2015-04-02T01:32:47.000Z
librbr/src/mdp/mdp.cpp
kylewray/librbr
ea3dcef7c37b4f177373ac6fec1f4c4566cf7bd8
[ "MIT" ]
null
null
null
/** * The MIT License (MIT) * * Copyright (c) 2014 Kyle Hollins Wray, University of Massachusetts * * 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 "../../include/mdp/mdp.h" MDP::MDP() { states = nullptr; actions = nullptr; stateTransitions = nullptr; rewards = nullptr; horizon = nullptr; } MDP::MDP(States *S, Actions *A, StateTransitions *T, Rewards *R, Horizon *h) { states = S; actions = A; stateTransitions = T; rewards = R; horizon = h; } MDP::~MDP() { if (states != nullptr) { delete states; } if (actions != nullptr) { delete actions; } if (stateTransitions != nullptr) { delete stateTransitions; } if (rewards != nullptr) { delete rewards; } if (horizon != nullptr) { delete horizon; } } States *MDP::get_states() { return states; } Actions *MDP::get_actions() { return actions; } StateTransitions *MDP::get_state_transitions() { return stateTransitions; } Rewards *MDP::get_rewards() { return rewards; } Horizon *MDP::get_horizon() { return horizon; }
23.431818
84
0.710475
kylewray
a494e4a3a4beedc35057517904c72cca21c15cac
480
hpp
C++
TriVEngine/Source/Engine/Events/BaseEngineEvent.hpp
FrostByteGER/TriVEngine
77db65a04950fc843515452af9a2bc2c940ab2c7
[ "BSL-1.0" ]
null
null
null
TriVEngine/Source/Engine/Events/BaseEngineEvent.hpp
FrostByteGER/TriVEngine
77db65a04950fc843515452af9a2bc2c940ab2c7
[ "BSL-1.0" ]
null
null
null
TriVEngine/Source/Engine/Events/BaseEngineEvent.hpp
FrostByteGER/TriVEngine
77db65a04950fc843515452af9a2bc2c940ab2c7
[ "BSL-1.0" ]
null
null
null
#pragma once #include "EventExecutionType.hpp" #include <iostream> namespace TriV::Engine::Core::Events { class BaseEngineEvent { private: EventExecutionType executionType; protected: explicit BaseEngineEvent(const EventExecutionType executionType) { this->executionType = executionType; } public: virtual ~BaseEngineEvent() = default; virtual void executeEvent() = 0; EventExecutionType getExecutionType() const { return executionType; } }; }
16
66
0.739583
FrostByteGER
a495ce7ace5135817f71187173b2487e38a63af9
17,700
cpp
C++
src/scsi2sd-util6/wxWidgets/src/gtk/assertdlg_gtk.cpp
fhgwright/SCSI2SD-V6
29555b30d3f96257ac12a546e75891490603aee8
[ "BSD-3-Clause" ]
3
2020-04-11T13:00:31.000Z
2020-12-07T03:19:10.000Z
src/scsi2sd-util6/wxWidgets/src/gtk/assertdlg_gtk.cpp
tweakoz/SCSI2SD-V6
77db5f86712213e25c9b12fa5c9fa9c54b80cb80
[ "BSD-3-Clause" ]
null
null
null
src/scsi2sd-util6/wxWidgets/src/gtk/assertdlg_gtk.cpp
tweakoz/SCSI2SD-V6
77db5f86712213e25c9b12fa5c9fa9c54b80cb80
[ "BSD-3-Clause" ]
1
2020-04-11T13:00:04.000Z
2020-04-11T13:00:04.000Z
/* /////////////////////////////////////////////////////////////////////////// // Name: src/gtk/assertdlg_gtk.cpp // Purpose: GtkAssertDialog // Author: Francesco Montorsi // Copyright: (c) 2006 Francesco Montorsi // Licence: wxWindows licence /////////////////////////////////////////////////////////////////////////// */ #include "wx/wxprec.h" #if wxDEBUG_LEVEL #include <gtk/gtk.h> #include "wx/gtk/assertdlg_gtk.h" #include "wx/gtk/private/gtk2-compat.h" #include <stdio.h> /* ---------------------------------------------------------------------------- Constants ---------------------------------------------------------------------------- */ /* NB: when changing order of the columns also update the gtk_list_store_new() call in gtk_assert_dialog_create_backtrace_list_model() function */ #define STACKFRAME_LEVEL_COLIDX 0 #define FUNCTION_PROTOTYPE_COLIDX 1 #define SOURCE_FILE_COLIDX 2 #define LINE_NUMBER_COLIDX 3 /* ---------------------------------------------------------------------------- GtkAssertDialog helpers ---------------------------------------------------------------------------- */ static GtkWidget *gtk_assert_dialog_add_button_to (GtkBox *box, const gchar *label, const gchar *stock) { /* create the button */ GtkWidget *button = gtk_button_new_with_mnemonic (label); gtk_widget_set_can_default(button, true); /* add a stock icon inside it */ GtkWidget *image = gtk_image_new_from_stock (stock, GTK_ICON_SIZE_BUTTON); gtk_button_set_image (GTK_BUTTON (button), image); /* add to the given (container) widget */ if (box) gtk_box_pack_end (box, button, FALSE, TRUE, 8); return button; } static GtkWidget *gtk_assert_dialog_add_button (GtkAssertDialog *dlg, const gchar *label, const gchar *stock, gint response_id) { /* create the button */ GtkWidget* button = gtk_assert_dialog_add_button_to(NULL, label, stock); /* add the button to the dialog's action area */ gtk_dialog_add_action_widget (GTK_DIALOG (dlg), button, response_id); return button; } #if wxUSE_STACKWALKER static void gtk_assert_dialog_append_text_column (GtkWidget *treeview, const gchar *name, int index) { GtkCellRenderer *renderer; GtkTreeViewColumn *column; renderer = gtk_cell_renderer_text_new (); column = gtk_tree_view_column_new_with_attributes (name, renderer, "text", index, NULL); gtk_tree_view_insert_column (GTK_TREE_VIEW (treeview), column, index); gtk_tree_view_column_set_resizable (column, TRUE); gtk_tree_view_column_set_reorderable (column, TRUE); } static GtkWidget *gtk_assert_dialog_create_backtrace_list_model () { GtkListStore *store; GtkWidget *treeview; /* create list store */ store = gtk_list_store_new (4, G_TYPE_UINT, /* stack frame number */ G_TYPE_STRING, /* function prototype */ G_TYPE_STRING, /* source file name */ G_TYPE_STRING); /* line number */ /* create the tree view */ treeview = gtk_tree_view_new_with_model (GTK_TREE_MODEL(store)); g_object_unref (store); gtk_tree_view_set_rules_hint (GTK_TREE_VIEW (treeview), TRUE); /* append columns */ gtk_assert_dialog_append_text_column(treeview, "#", STACKFRAME_LEVEL_COLIDX); gtk_assert_dialog_append_text_column(treeview, "Function Prototype", FUNCTION_PROTOTYPE_COLIDX); gtk_assert_dialog_append_text_column(treeview, "Source file", SOURCE_FILE_COLIDX); gtk_assert_dialog_append_text_column(treeview, "Line #", LINE_NUMBER_COLIDX); return treeview; } static void gtk_assert_dialog_process_backtrace (GtkAssertDialog *dlg) { /* set busy cursor */ GdkWindow *parent = gtk_widget_get_window(GTK_WIDGET(dlg)); GdkCursor *cur = gdk_cursor_new (GDK_WATCH); gdk_window_set_cursor (parent, cur); gdk_flush (); (*dlg->callback)(dlg->userdata); /* toggle busy cursor */ gdk_window_set_cursor (parent, NULL); #ifdef __WXGTK3__ g_object_unref(cur); #else gdk_cursor_unref (cur); #endif } extern "C" { /* ---------------------------------------------------------------------------- GtkAssertDialog signal handlers ---------------------------------------------------------------------------- */ static void gtk_assert_dialog_expander_callback(GtkWidget*, GtkAssertDialog* dlg) { /* status is not yet updated so we need to invert it to get the new one */ gboolean expanded = !gtk_expander_get_expanded (GTK_EXPANDER(dlg->expander)); gtk_window_set_resizable (GTK_WINDOW (dlg), expanded); if (dlg->callback == NULL) /* was the backtrace already processed? */ return; gtk_assert_dialog_process_backtrace (dlg); /* mark the work as done (so that next activate we won't call the callback again) */ dlg->callback = NULL; } static void gtk_assert_dialog_save_backtrace_callback(GtkWidget*, GtkAssertDialog* dlg) { GtkWidget *dialog; dialog = gtk_file_chooser_dialog_new ("Save assert info to file", GTK_WINDOW(dlg), GTK_FILE_CHOOSER_ACTION_SAVE, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT, NULL); if (gtk_dialog_run (GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT) { char *filename, *msg, *backtrace; FILE *fp; filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog)); if ( filename ) { msg = gtk_assert_dialog_get_message (dlg); backtrace = gtk_assert_dialog_get_backtrace (dlg); /* open the file and write all info inside it */ fp = fopen (filename, "w"); if (fp) { fprintf (fp, "ASSERT INFO:\n%s\n\nBACKTRACE:\n%s", msg, backtrace); fclose (fp); } g_free (filename); g_free (msg); g_free (backtrace); } } gtk_widget_destroy (dialog); } static void gtk_assert_dialog_copy_callback(GtkWidget*, GtkAssertDialog* dlg) { char *msg, *backtrace; GtkClipboard *clipboard; GString *str; msg = gtk_assert_dialog_get_message (dlg); backtrace = gtk_assert_dialog_get_backtrace (dlg); /* combine both in a single string */ str = g_string_new(""); g_string_printf (str, "ASSERT INFO:\n%s\n\nBACKTRACE:\n%s\n\n", msg, backtrace); /* copy everything in default clipboard */ clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD); gtk_clipboard_set_text (clipboard, str->str, str->len); /* copy everything in primary clipboard too */ clipboard = gtk_clipboard_get (GDK_SELECTION_PRIMARY); gtk_clipboard_set_text (clipboard, str->str, str->len); g_free (msg); g_free (backtrace); g_string_free (str, TRUE); } } // extern "C" #endif // wxUSE_STACKWALKER extern "C" { static void gtk_assert_dialog_continue_callback(GtkWidget*, GtkAssertDialog* dlg) { gint response = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON(dlg->shownexttime)) ? GTK_ASSERT_DIALOG_CONTINUE : GTK_ASSERT_DIALOG_CONTINUE_SUPPRESSING; gtk_dialog_response (GTK_DIALOG(dlg), response); } } // extern "C" /* ---------------------------------------------------------------------------- GtkAssertDialogClass implementation ---------------------------------------------------------------------------- */ extern "C" { static void gtk_assert_dialog_init(GTypeInstance* instance, void*); } GType gtk_assert_dialog_get_type() { static GType assert_dialog_type; if (!assert_dialog_type) { const GTypeInfo assert_dialog_info = { sizeof (GtkAssertDialogClass), NULL, /* base_init */ NULL, /* base_finalize */ NULL, NULL, /* class_finalize */ NULL, /* class_data */ sizeof (GtkAssertDialog), 16, /* n_preallocs */ gtk_assert_dialog_init, NULL }; assert_dialog_type = g_type_register_static (GTK_TYPE_DIALOG, "GtkAssertDialog", &assert_dialog_info, (GTypeFlags)0); } return assert_dialog_type; } extern "C" { static void gtk_assert_dialog_init(GTypeInstance* instance, void*) { GtkAssertDialog* dlg = GTK_ASSERT_DIALOG(instance); GtkWidget *continuebtn; { GtkWidget *vbox, *hbox, *image; /* start the main vbox */ gtk_widget_push_composite_child (); vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 8); gtk_container_set_border_width (GTK_CONTAINER(vbox), 8); gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(dlg))), vbox, true, true, 5); /* add the icon+message hbox */ hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); gtk_box_pack_start (GTK_BOX(vbox), hbox, FALSE, FALSE, 0); /* icon */ image = gtk_image_new_from_stock (GTK_STOCK_DIALOG_ERROR, GTK_ICON_SIZE_DIALOG); gtk_box_pack_start (GTK_BOX(hbox), image, FALSE, FALSE, 12); { GtkWidget *vbox2, *info; /* message */ vbox2 = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); gtk_box_pack_start (GTK_BOX (hbox), vbox2, TRUE, TRUE, 0); info = gtk_label_new ("An assertion failed!"); gtk_box_pack_start (GTK_BOX(vbox2), info, TRUE, TRUE, 8); /* assert message */ dlg->message = gtk_label_new (NULL); gtk_label_set_selectable (GTK_LABEL (dlg->message), TRUE); gtk_label_set_line_wrap (GTK_LABEL (dlg->message), TRUE); gtk_label_set_justify (GTK_LABEL (dlg->message), GTK_JUSTIFY_LEFT); gtk_widget_set_size_request (GTK_WIDGET(dlg->message), 450, -1); gtk_box_pack_end (GTK_BOX(vbox2), GTK_WIDGET(dlg->message), TRUE, TRUE, 8); } #if wxUSE_STACKWALKER /* add the expander */ dlg->expander = gtk_expander_new_with_mnemonic ("Back_trace:"); gtk_box_pack_start (GTK_BOX(vbox), dlg->expander, TRUE, TRUE, 0); g_signal_connect (dlg->expander, "activate", G_CALLBACK(gtk_assert_dialog_expander_callback), dlg); #endif // wxUSE_STACKWALKER } #if wxUSE_STACKWALKER { GtkWidget *hbox, *vbox, *button, *sw; /* create expander's vbox */ vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); gtk_container_add (GTK_CONTAINER (dlg->expander), vbox); /* add a scrollable window under the expander */ sw = gtk_scrolled_window_new (NULL, NULL); gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (sw), GTK_SHADOW_ETCHED_IN); gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (sw), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); gtk_box_pack_start (GTK_BOX(vbox), sw, TRUE, TRUE, 8); /* add the treeview to the scrollable window */ dlg->treeview = gtk_assert_dialog_create_backtrace_list_model (); gtk_widget_set_size_request (GTK_WIDGET(dlg->treeview), -1, 180); gtk_container_add (GTK_CONTAINER (sw), dlg->treeview); /* create button's hbox */ hbox = gtk_button_box_new(GTK_ORIENTATION_HORIZONTAL); gtk_box_pack_end (GTK_BOX(vbox), hbox, FALSE, FALSE, 0); gtk_button_box_set_layout (GTK_BUTTON_BOX(hbox), GTK_BUTTONBOX_END); /* add the buttons */ button = gtk_assert_dialog_add_button_to (GTK_BOX(hbox), "Save to _file", GTK_STOCK_SAVE); g_signal_connect (button, "clicked", G_CALLBACK(gtk_assert_dialog_save_backtrace_callback), dlg); button = gtk_assert_dialog_add_button_to (GTK_BOX(hbox), "Copy to clip_board", GTK_STOCK_COPY); g_signal_connect (button, "clicked", G_CALLBACK(gtk_assert_dialog_copy_callback), dlg); } #endif // wxUSE_STACKWALKER /* add the checkbutton */ dlg->shownexttime = gtk_check_button_new_with_mnemonic("Show this _dialog the next time"); gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON(dlg->shownexttime), TRUE); gtk_box_pack_end(GTK_BOX(gtk_dialog_get_action_area(GTK_DIALOG(dlg))), dlg->shownexttime, false, true, 8); /* add the stop button */ gtk_assert_dialog_add_button (dlg, "_Stop", GTK_STOCK_QUIT, GTK_ASSERT_DIALOG_STOP); /* add the continue button */ continuebtn = gtk_assert_dialog_add_button (dlg, "_Continue", GTK_STOCK_YES, GTK_ASSERT_DIALOG_CONTINUE); gtk_dialog_set_default_response (GTK_DIALOG (dlg), GTK_ASSERT_DIALOG_CONTINUE); g_signal_connect (continuebtn, "clicked", G_CALLBACK(gtk_assert_dialog_continue_callback), dlg); /* complete creation */ dlg->callback = NULL; dlg->userdata = NULL; /* the resizable property of this window is modified by the expander: when it's collapsed, the window must be non-resizable! */ gtk_window_set_resizable (GTK_WINDOW (dlg), FALSE); gtk_widget_pop_composite_child (); gtk_widget_show_all (GTK_WIDGET(dlg)); } } /* ---------------------------------------------------------------------------- GtkAssertDialog public API ---------------------------------------------------------------------------- */ gchar *gtk_assert_dialog_get_message (GtkAssertDialog *dlg) { /* NOTES: 1) returned string must g_free()d ! 2) Pango markup is automatically stripped off by GTK */ return g_strdup (gtk_label_get_text (GTK_LABEL(dlg->message))); } #if wxUSE_STACKWALKER gchar *gtk_assert_dialog_get_backtrace (GtkAssertDialog *dlg) { gchar *function, *sourcefile, *linenum; guint count; GtkTreeModel *model; GtkTreeIter iter; GString *string; g_return_val_if_fail (GTK_IS_ASSERT_DIALOG (dlg), NULL); model = gtk_tree_view_get_model (GTK_TREE_VIEW(dlg->treeview)); string = g_string_new(""); /* iterate over the list */ if (!gtk_tree_model_get_iter_first (model, &iter)) return NULL; do { /* append this stack frame's info to the string */ gtk_tree_model_get(model, &iter, STACKFRAME_LEVEL_COLIDX, &count, FUNCTION_PROTOTYPE_COLIDX, &function, SOURCE_FILE_COLIDX, &sourcefile, LINE_NUMBER_COLIDX, &linenum, -1); g_string_append_printf(string, "[%u] %s", count, function); if (sourcefile[0] != '\0') g_string_append_printf (string, " %s", sourcefile); if (linenum[0] != '\0') g_string_append_printf (string, ":%s", linenum); g_string_append (string, "\n"); g_free (function); g_free (sourcefile); g_free (linenum); } while (gtk_tree_model_iter_next (model, &iter)); /* returned string must g_free()d */ return g_string_free (string, FALSE); } #endif // wxUSE_STACKWALKER void gtk_assert_dialog_set_message(GtkAssertDialog *dlg, const gchar *msg) { /* prepend and append the <b> tag NOTE: g_markup_printf_escaped() is not used because it's available only for glib >= 2.4 */ gchar *escaped_msg = g_markup_escape_text (msg, -1); gchar *decorated_msg = g_strdup_printf ("<b>%s</b>", escaped_msg); g_return_if_fail (GTK_IS_ASSERT_DIALOG (dlg)); gtk_label_set_markup (GTK_LABEL(dlg->message), decorated_msg); g_free (decorated_msg); g_free (escaped_msg); } #if wxUSE_STACKWALKER void gtk_assert_dialog_set_backtrace_callback(GtkAssertDialog *assertdlg, GtkAssertDialogStackFrameCallback callback, void *userdata) { assertdlg->callback = callback; assertdlg->userdata = userdata; } void gtk_assert_dialog_append_stack_frame(GtkAssertDialog *dlg, const gchar *function, const gchar *sourcefile, guint line_number) { GtkTreeModel *model; GtkTreeIter iter; GString *linenum; gint count; g_return_if_fail (GTK_IS_ASSERT_DIALOG (dlg)); model = gtk_tree_view_get_model (GTK_TREE_VIEW(dlg->treeview)); /* how many items are in the list up to now ? */ count = gtk_tree_model_iter_n_children (model, NULL); linenum = g_string_new(""); if ( line_number != 0 ) g_string_printf (linenum, "%u", line_number); /* add data to the list store */ gtk_list_store_append (GTK_LIST_STORE(model), &iter); gtk_list_store_set (GTK_LIST_STORE(model), &iter, STACKFRAME_LEVEL_COLIDX, count+1, /* start from 1 and not from 0 */ FUNCTION_PROTOTYPE_COLIDX, function, SOURCE_FILE_COLIDX, sourcefile, LINE_NUMBER_COLIDX, linenum->str, -1); g_string_free (linenum, TRUE); } #endif // wxUSE_STACKWALKER GtkWidget *gtk_assert_dialog_new(void) { void* dialog = g_object_new(GTK_TYPE_ASSERT_DIALOG, NULL); return GTK_WIDGET (dialog); } #endif // wxDEBUG_LEVEL
35.119048
125
0.60774
fhgwright
a49ae046552c0aebf7784dd930a60fe403c4102b
8,305
cc
C++
research/carls/knowledge_bank/knowledge_bank_test.cc
otiliastr/neural-structured-learning
4a574b84c0a02e08ed3ef58e60284555e7e7c7e2
[ "Apache-2.0" ]
1
2021-05-10T10:46:57.000Z
2021-05-10T10:46:57.000Z
research/carls/knowledge_bank/knowledge_bank_test.cc
Saiprasad16/neural-structured-learning
bde9105b12b2797c909a0fe20ef74bb7fff6100b
[ "Apache-2.0" ]
null
null
null
research/carls/knowledge_bank/knowledge_bank_test.cc
Saiprasad16/neural-structured-learning
bde9105b12b2797c909a0fe20ef74bb7fff6100b
[ "Apache-2.0" ]
null
null
null
/*Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "research/carls/knowledge_bank/knowledge_bank.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "research/carls/base/file_helper.h" #include "research/carls/knowledge_bank/initializer.pb.h" // proto to pb #include "research/carls/knowledge_bank/initializer_helper.h" #include "research/carls/testing/test_helper.h" namespace carls { namespace { using ::testing::Eq; using ::testing::TempDir; class FakeEmbedding : public KnowledgeBank { public: explicit FakeEmbedding(const KnowledgeBankConfig& config, int dimension) : KnowledgeBank(config, dimension) {} absl::Status Lookup(const absl::string_view key, EmbeddingVectorProto* result) const override { CHECK(result != nullptr); std::string str_key(key); if (!data_table_.embedding_table().contains(str_key)) { return absl::InvalidArgumentError("Data not found"); } *result = data_table_.embedding_table().find(str_key)->second; return absl::OkStatus(); } absl::Status LookupWithUpdate(const absl::string_view key, EmbeddingVectorProto* result) override { CHECK(result != nullptr); std::string str_key(key); if (!data_table_.embedding_table().contains(str_key)) { (*data_table_.mutable_embedding_table())[str_key] = InitializeEmbedding(embedding_dimension(), config().initializer()); keys_.push_back(data_table_.embedding_table().find(str_key)->first); } *result = data_table_.embedding_table().find(str_key)->second; return absl::OkStatus(); } absl::Status Update(const absl::string_view key, const EmbeddingVectorProto& value) override { std::string str_key(key); if (!data_table_.embedding_table().contains(str_key)) { (*data_table_.mutable_embedding_table())[str_key] = value; keys_.push_back(data_table_.embedding_table().find(str_key)->first); } else { data_table_.mutable_embedding_table()->at(str_key) = value; } return absl::OkStatus(); } absl::Status ExportInternal(const std::string& dir, std::string* exported_path) override { *exported_path = "fake_checkpoint"; return absl::OkStatus(); } absl::Status ImportInternal(const std::string& saved_path) override { return absl::OkStatus(); } size_t Size() const override { return data_table_.embedding_table_size(); } std::vector<absl::string_view> Keys() const { return keys_; } bool Contains(absl::string_view key) const { return data_table_.embedding_table().contains(std::string(key)); } private: InProtoKnowledgeBankConfig::EmbeddingData data_table_; std::vector<absl::string_view> keys_; }; REGISTER_KNOWLEDGE_BANK_FACTORY(KnowledgeBankConfig, [](const KnowledgeBankConfig& config, int dimension) -> std::unique_ptr<KnowledgeBank> { return std::unique_ptr<KnowledgeBank>( new FakeEmbedding(config, dimension)); }); } // namespace class KnowledgeBankTest : public ::testing::Test { protected: KnowledgeBankTest() {} std::unique_ptr<KnowledgeBank> CreateDefaultStore(int embedding_dimension) { KnowledgeBankConfig config; config.mutable_initializer()->mutable_zero_initializer(); return KnowledgeBankFactory::Make(config, embedding_dimension); } }; TEST_F(KnowledgeBankTest, Basic) { auto store = CreateDefaultStore(10); EXPECT_EQ(10, store->embedding_dimension()); EmbeddingVectorProto embed; ASSERT_OK(store->LookupWithUpdate("key1", &embed)); EXPECT_TRUE(store->Contains("key1")); EXPECT_FALSE(store->Contains("key2")); } TEST_F(KnowledgeBankTest, LookupAndUpdate) { auto store = CreateDefaultStore(2); EmbeddingInitializer initializer; initializer.mutable_zero_initializer(); EmbeddingVectorProto value = InitializeEmbedding(2, initializer); EXPECT_OK(store->Update("key1", value)); EmbeddingVectorProto result; EXPECT_OK(store->Lookup("key1", &result)); EXPECT_THAT(result, EqualsProto<EmbeddingVectorProto>(R"pb( value: 0 value: 0 )pb")); EXPECT_EQ(1, store->Size()); ASSERT_EQ(1, store->Keys().size()); EXPECT_EQ("key1", store->Keys()[0]); } TEST_F(KnowledgeBankTest, BatchLookupAndUpdate) { auto store = CreateDefaultStore(2); EmbeddingInitializer initializer; initializer.mutable_zero_initializer(); EmbeddingVectorProto value1 = InitializeEmbedding(2, initializer); EmbeddingVectorProto value2 = InitializeEmbedding(2, initializer); EXPECT_THAT( store->BatchUpdate({"key1", "key2"}, {value1, value2}), Eq(std::vector<absl::Status>{absl::OkStatus(), absl::OkStatus()})); std::vector<absl::variant<EmbeddingVectorProto, std::string>> value_or_errors; store->BatchLookup({"key1", "key2", "key3"}, &value_or_errors); ASSERT_EQ(3, value_or_errors.size()); for (int i = 0; i < 2; ++i) { ASSERT_TRUE( absl::holds_alternative<EmbeddingVectorProto>(value_or_errors[i])); EXPECT_THAT(absl::get<EmbeddingVectorProto>(value_or_errors[i]), EqualsProto<EmbeddingVectorProto>(R"pb( value: 0 value: 0 )pb")); } ASSERT_TRUE(absl::holds_alternative<std::string>(value_or_errors[2])); EXPECT_EQ("Data not found", absl::get<std::string>(value_or_errors[2])); EXPECT_EQ(2, store->Size()); ASSERT_EQ(2, store->Keys().size()); EXPECT_EQ("key1", store->Keys()[0]); EXPECT_EQ("key2", store->Keys()[1]); } TEST_F(KnowledgeBankTest, BatchLookupWithUpdate) { auto store = CreateDefaultStore(2); std::vector<absl::variant<EmbeddingVectorProto, std::string>> value_or_errors; store->BatchLookupWithUpdate({"key1", "key2", "key3"}, &value_or_errors); ASSERT_EQ(3, value_or_errors.size()); for (int i = 0; i < 3; ++i) { ASSERT_TRUE( absl::holds_alternative<EmbeddingVectorProto>(value_or_errors[i])); EXPECT_THAT(absl::get<EmbeddingVectorProto>(value_or_errors[i]), EqualsProto<EmbeddingVectorProto>(R"pb( value: 0 value: 0 )pb")); } EXPECT_EQ(3, store->Size()); ASSERT_EQ(3, store->Keys().size()); EXPECT_EQ("key1", store->Keys()[0]); EXPECT_EQ("key2", store->Keys()[1]); EXPECT_EQ("key3", store->Keys()[2]); } TEST_F(KnowledgeBankTest, Export) { auto store = CreateDefaultStore(2); // Export to a new dir. std::string exported_path; ASSERT_OK(store->Export(TempDir(), "", &exported_path)); EXPECT_EQ(JoinPath(TempDir(), "embedding_store_meta_data.pbtxt"), exported_path); // Export to the same dir again, it overwrites existing checkpoint. ASSERT_OK(store->Export(TempDir(), "", &exported_path)); } TEST_F(KnowledgeBankTest, Import) { auto store = CreateDefaultStore(2); // Some updates. EmbeddingVectorProto result; EXPECT_OK(store->LookupWithUpdate("key1", &result)); EXPECT_OK(store->LookupWithUpdate("key2", &result)); EXPECT_OK(store->LookupWithUpdate("key3", &result)); EXPECT_OK(store->LookupWithUpdate("key2", &result)); EXPECT_OK(store->LookupWithUpdate("key2", &result)); // Now saves a checkpoint. std::string exported_path; ASSERT_OK(store->Export(TempDir(), "", &exported_path)); // Some updates. EXPECT_OK(store->LookupWithUpdate("key1", &result)); EXPECT_OK(store->LookupWithUpdate("key4", &result)); EXPECT_OK(store->LookupWithUpdate("key5", &result)); // Import previous state. ASSERT_OK(store->Import(exported_path)); } } // namespace carls
35.643777
80
0.680433
otiliastr
a4a0a3af308b4fd393f56a2bea193adba9fb6a04
9,919
cpp
C++
Quartz/Engine/Source/Platform/GLWindow.cpp
tobyplowy/quartz-engine
d08ff18330c9bb59ab8739b40d5a4781750697c1
[ "BSD-3-Clause" ]
null
null
null
Quartz/Engine/Source/Platform/GLWindow.cpp
tobyplowy/quartz-engine
d08ff18330c9bb59ab8739b40d5a4781750697c1
[ "BSD-3-Clause" ]
null
null
null
Quartz/Engine/Source/Platform/GLWindow.cpp
tobyplowy/quartz-engine
d08ff18330c9bb59ab8739b40d5a4781750697c1
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2019 Genten Studios // // 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 <Quartz/Graphics/RHI/OpenGL/GLCommon.hpp> #include <Quartz/Platform/GLWindow.hpp> #include <Quartz/QuartzPCH.hpp> #include <Quartz/Utilities/Logger.hpp> #include <glad/glad.h> using namespace qz::gfx::rhi::gl; using namespace qz; void GLWindow::startFrame() { m_gui.startFrame(); } void GLWindow::endFrame() { m_gui.endFrame(); swapBuffers(); pollEvents(); } void GLWindow::dispatchToListeners(events::Event& event) { for (events::IEventListener* eventListener : m_eventListeners) { eventListener->onEvent(event); } } GLWindow::GLWindow(const std::string& title, int width, int height) : m_vsync(false), m_fullscreen(false) { SDL_Init(SDL_INIT_EVERYTHING); SDL_SetMainReady(); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); #ifdef QZ_DEBUG SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG); #endif SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 2); m_window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_OPENGL); if (m_window == nullptr) { SDL_Quit(); LFATAL("Couldn't create window, need OpenGL >= 3.3"); exit(EXIT_FAILURE); } m_cachedScreenSize = {static_cast<float>(width), static_cast<float>(height)}; m_context = SDL_GL_CreateContext(m_window); SDL_GL_MakeCurrent(m_window, m_context); if (!gladLoadGLLoader(static_cast<GLADloadproc>(SDL_GL_GetProcAddress))) { LFATAL("Failed to initialize GLAD"); exit(EXIT_FAILURE); } #ifdef QZ_DEBUG GLint flags; glGetIntegerv(GL_CONTEXT_FLAGS, &flags); if (flags & GL_CONTEXT_FLAG_DEBUG_BIT) { glEnable(GL_DEBUG_OUTPUT); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); glDebugMessageCallback(gfx::rhi::gl::glDebugOutput, nullptr); glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE); } #endif LINFO("---------- OpenGL Details ----------"); LINFO("Vendor: ", glGetString(GL_VENDOR)); LINFO("Renderer: ", glGetString(GL_RENDERER)); LINFO("Version: ", glGetString(GL_VERSION)); LINFO("------------------------------------"); SDL_ShowWindow(m_window); GLCheck(glEnable(GL_DEPTH_TEST)); GLCheck(glEnable(GL_MULTISAMPLE)); m_running = true; m_gui.init(m_window, &m_context); } GLWindow::~GLWindow() { SDL_GL_DeleteContext(m_context); SDL_DestroyWindow(m_window); SDL_Quit(); } void GLWindow::pollEvents() { SDL_Event event; while (SDL_PollEvent(&event) > 0) { using namespace events; Event e; m_gui.pollEvents(&event); switch (event.type) { case SDL_QUIT: e.type = EventType::WINDOW_CLOSED; dispatchToListeners(e); m_running = false; break; case SDL_MOUSEBUTTONDOWN: e.type = EventType::MOUSE_BUTTON_PRESSED; e.mouse.button = static_cast<MouseButtons>(event.button.button); e.mouse.x = event.button.x; e.mouse.y = event.button.y; break; case SDL_MOUSEBUTTONUP: e.type = EventType::MOUSE_BUTTON_RELEASED; e.mouse.button = static_cast<MouseButtons>(event.button.button); dispatchToListeners(e); break; case SDL_MOUSEMOTION: e.type = EventType::CURSOR_MOVED; e.position.x = event.motion.x; e.position.y = event.motion.y; dispatchToListeners(e); break; case SDL_KEYDOWN: e.type = EventType::KEY_PRESSED; e.keyboard.key = static_cast<Keys>(event.key.keysym.scancode); e.keyboard.mods = static_cast<Mods>( event.key.keysym.mod); // access these with bitwise operators // like AND (&) and OR (|) dispatchToListeners(e); break; case SDL_KEYUP: e.type = EventType::KEY_RELEASED; e.keyboard.key = static_cast<Keys>(event.key.keysym.scancode); e.keyboard.mods = static_cast<Mods>( event.key.keysym.mod); // access these with bitwise operators // like AND (&) and OR (|) dispatchToListeners(e); break; case SDL_WINDOWEVENT: switch (event.window.event) { case SDL_WINDOWEVENT_RESIZED: case SDL_WINDOWEVENT_SIZE_CHANGED: e.type = EventType::WINDOW_RESIZED; e.size.width = event.window.data1; e.size.width = event.window.data1; dispatchToListeners(e); break; case SDL_WINDOWEVENT_FOCUS_GAINED: e.type = EventType::WINDOW_FOCUSED; dispatchToListeners(e); break; case SDL_WINDOWEVENT_FOCUS_LOST: e.type = EventType::WINDOW_DEFOCUSED; dispatchToListeners(e); break; case SDL_WINDOWEVENT_CLOSE: e.type = EventType::WINDOW_CLOSED; dispatchToListeners(e); break; case SDL_WINDOWEVENT_MINIMIZED: e.type = EventType::WINDOW_MINIMIZED; dispatchToListeners(e); break; case SDL_WINDOWEVENT_MAXIMIZED: e.type = EventType::WINDOW_MAXIMIZED; dispatchToListeners(e); break; case SDL_WINDOWEVENT_RESTORED: e.type = EventType::WINDOW_RESTORED; dispatchToListeners(e); break; case SDL_WINDOWEVENT_LEAVE: e.type = EventType::CURSOR_LEFT; dispatchToListeners(e); break; case SDL_WINDOWEVENT_ENTER: e.type = EventType::CURSOR_ENTERED; dispatchToListeners(e); break; case SDL_WINDOWEVENT_MOVED: e.type = EventType::WINDOW_MOVED; e.position.x = event.window.data1; e.position.y = event.window.data2; dispatchToListeners(e); break; default: break; } } } } void GLWindow::swapBuffers() const { SDL_GL_SwapWindow(m_window); } void GLWindow::registerEventListener(events::IEventListener* listener) { m_eventListeners.emplace_back(listener); } void GLWindow::show() const { SDL_ShowWindow(m_window); } void GLWindow::hide() const { SDL_HideWindow(m_window); } void GLWindow::maximize() const { SDL_MaximizeWindow(m_window); } void GLWindow::minimize() const { SDL_MinimizeWindow(m_window); } void GLWindow::focus() const { SDL_SetWindowInputFocus(m_window); } void GLWindow::close() { m_running = false; } bool GLWindow::isRunning() const { return m_running; } void GLWindow::resize(Vector2 size) { SDL_SetWindowSize(m_window, static_cast<int>(size.x), static_cast<int>(size.y)); } void GLWindow::setResizable(bool enabled) { SDL_SetWindowResizable(m_window, enabled ? SDL_TRUE : SDL_FALSE); } Vector2 GLWindow::getSize() const { int x; int y; SDL_GetWindowSize(m_window, &x, &y); return {static_cast<float>(x), static_cast<float>(y)}; } void GLWindow::setVSync(bool enabled) { m_vsync = enabled; SDL_GL_SetSwapInterval(m_vsync ? 1 : 0); } bool GLWindow::isVSync() const { return m_vsync; } void GLWindow::setTitle(const std::string& title) const { SDL_SetWindowTitle(m_window, title.c_str()); } void GLWindow::setFullscreen(bool enabled) { m_fullscreen = enabled; if (enabled) { SDL_DisplayMode current; const int check = SDL_GetCurrentDisplayMode(0, &current); if (check != 0) { LFATAL("Uh oh! Something went very wrong, send this error message " "to a developer: ", SDL_GetError()); } else { m_cachedScreenSize = getSize(); resize( {static_cast<float>(current.w), static_cast<float>(current.h)}); SDL_SetWindowFullscreen(m_window, SDL_WINDOW_FULLSCREEN); glViewport(0, 0, current.w, current.h); } } else { SDL_SetWindowFullscreen(m_window, 0); resize(m_cachedScreenSize); glViewport(0, 0, static_cast<int>(m_cachedScreenSize.x), static_cast<int>(m_cachedScreenSize.y)); } } bool GLWindow::isFullscreen() const { return m_fullscreen; } void GLWindow::setCursorState(gfx::CursorState state) { const bool on = state == gfx::CursorState::NORMAL; SDL_ShowCursor(on); } void GLWindow::setCursorPosition(Vector2 pos) { SDL_WarpMouseInWindow(m_window, static_cast<int>(pos.x), static_cast<int>(pos.y)); } Vector2 GLWindow::getCursorPosition() const { int x, y; SDL_GetMouseState(&x, &y); return {static_cast<float>(x), static_cast<float>(y)}; } bool GLWindow::isKeyDown(events::Keys key) const { return SDL_GetKeyboardState(nullptr)[static_cast<SDL_Scancode>(key)]; }
28.019774
80
0.710959
tobyplowy
a4a7297b8e21b7fafb7dc6174503c1f9ffda5c43
2,138
hpp
C++
modules/boost/simd/base/include/boost/simd/arithmetic/functions/remround.hpp
feelpp/nt2
4d121e2c7450f24b735d6cff03720f07b4b2146c
[ "BSL-1.0" ]
34
2017-05-19T18:10:17.000Z
2022-01-04T02:18:13.000Z
modules/boost/simd/base/include/boost/simd/arithmetic/functions/remround.hpp
feelpp/nt2
4d121e2c7450f24b735d6cff03720f07b4b2146c
[ "BSL-1.0" ]
null
null
null
modules/boost/simd/base/include/boost/simd/arithmetic/functions/remround.hpp
feelpp/nt2
4d121e2c7450f24b735d6cff03720f07b4b2146c
[ "BSL-1.0" ]
7
2017-12-02T12:59:17.000Z
2021-07-31T12:46:14.000Z
//============================================================================== // Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef BOOST_SIMD_ARITHMETIC_FUNCTIONS_REMROUND_HPP_INCLUDED #define BOOST_SIMD_ARITHMETIC_FUNCTIONS_REMROUND_HPP_INCLUDED #include <boost/simd/include/functor.hpp> #include <boost/dispatch/include/functor.hpp> namespace boost { namespace simd { namespace tag { /*! @brief rem generic tag Represents the remround function in generic contexts. @par Models: Hierarchy **/ struct remround_ : ext::elementwise_<remround_> { /// @brief Parent hierarchy typedef ext::elementwise_<remround_> parent; template<class... Args> static BOOST_FORCEINLINE BOOST_AUTO_DECLTYPE dispatch(Args&&... args) BOOST_AUTO_DECLTYPE_BODY( dispatching_remround_( ext::adl_helper(), static_cast<Args&&>(args)... ) ) }; } namespace ext { template<class Site> BOOST_FORCEINLINE generic_dispatcher<tag::remround_, Site> dispatching_remround_(adl_helper, boost::dispatch::meta::unknown_<Site>, ...) { return generic_dispatcher<tag::remround_, Site>(); } template<class... Args> struct impl_remround_; } /*! Computes the remainder of division. The return value is a0-n*a1, where n is the value a0/a1, rounded toward infinity. @par semantic: For any given value @c x, @c y of type @c T: @code T r = remround(x, y); @endcode For floating point values the code is equivalent to: @code T r = x-divround(x, y)*y; @endcode @param a0 @param a1 @return a value of the same type as the input. **/ BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::remround_, remround, 2) } } #endif
29.287671
139
0.615529
feelpp
a4ae31b62b0195c58107025fc5f64b52d24b1ad5
4,133
cpp
C++
tests/filter_tests.cpp
obruns/bluetoe
de13682bce39335878262212f3615254e0af1702
[ "MIT" ]
1
2019-02-01T09:38:00.000Z
2019-02-01T09:38:00.000Z
tests/filter_tests.cpp
obruns/bluetoe
de13682bce39335878262212f3615254e0af1702
[ "MIT" ]
null
null
null
tests/filter_tests.cpp
obruns/bluetoe
de13682bce39335878262212f3615254e0af1702
[ "MIT" ]
null
null
null
#include <iostream> #include <bluetoe/filter.hpp> #include <bluetoe/attribute.hpp> #include <bluetoe/uuid.hpp> #define BOOST_TEST_MODULE #include <boost/test/included/unit_test.hpp> namespace blued = bluetoe::details; namespace { template < class UUID > blued::uuid_filter fixture() { return blued::uuid_filter( &UUID::bytes[ 0 ], UUID::is_128bit ); } typedef bluetoe::details::uuid< 0x1, 0x2, 0x3, 0x4, 0x5 > big_uuid; blued::attribute_access_result equal_to_big_uuid( blued::attribute_access_arguments& args, std::uint16_t ) { if ( args.type == blued::attribute_access_type::compare_128bit_uuid ) { assert( args.buffer_size == 16 ); if ( std::equal( std::begin( big_uuid::bytes ), std::end( big_uuid::bytes ), args.buffer ) ) return blued::attribute_access_result::uuid_equal; } return blued::attribute_access_result::read_not_permitted; } } BOOST_AUTO_TEST_CASE( fitting_16bit ) { const auto filter = fixture< bluetoe::details::uuid16< 0x1234 > >(); const blued::attribute attribute = { 0x1234, nullptr }; BOOST_CHECK( filter( 1, attribute ) ); BOOST_CHECK( filter( 4711, attribute ) ); } BOOST_AUTO_TEST_CASE( not_fitting_16bit ) { const auto filter = fixture< bluetoe::details::uuid16< 0x1234 > >(); const blued::attribute attribute = { 0x4711, nullptr }; BOOST_CHECK( !filter( 1, attribute ) ); BOOST_CHECK( !filter( 4711, attribute ) ); } BOOST_AUTO_TEST_CASE( fitting_16bit_compaired_with_bluetooth_base_uuid ) { const auto filter = fixture< blued::bluetooth_base_uuid::from_16bit< 0x1234 > >(); const blued::attribute attribute = { 0x1234, nullptr }; BOOST_CHECK( filter( 1, attribute ) ); BOOST_CHECK( filter( 4711, attribute ) ); } BOOST_AUTO_TEST_CASE( not_fitting_16bit_compaired_with_bluetooth_base_uuid ) { const auto filter = fixture< blued::bluetooth_base_uuid::from_16bit< 0x1234 > >(); const blued::attribute attribute = { 0x4711, nullptr }; BOOST_CHECK( !filter( 1, attribute ) ); BOOST_CHECK( !filter( 4711, attribute ) ); } BOOST_AUTO_TEST_CASE( fitting_128bit ) { const auto filter = fixture< bluetoe::details::uuid< 0x1, 0x2, 0x3, 0x4, 0x5 > >(); const blued::attribute attribute = { bits( blued::gatt_uuids::internal_128bit_uuid ), equal_to_big_uuid }; BOOST_CHECK( filter( 1, attribute ) ); BOOST_CHECK( filter( 4711, attribute ) ); } BOOST_AUTO_TEST_CASE( not_fitting_128bit ) { const auto filter = fixture< bluetoe::details::uuid< 0x1, 0x2, 0x3, 0x4, 0x6 > >(); const blued::attribute attribute = { bits( blued::gatt_uuids::internal_128bit_uuid ), equal_to_big_uuid }; BOOST_CHECK( !filter( 1, attribute ) ); BOOST_CHECK( !filter( 4711, attribute ) ); } BOOST_AUTO_TEST_CASE( compare_16bit_with_128bit ) { const auto filter = fixture< bluetoe::details::uuid16< 0x1234 > >(); const blued::attribute attribute = { bits( blued::gatt_uuids::internal_128bit_uuid ), equal_to_big_uuid }; BOOST_CHECK( !filter( 1, attribute ) ); BOOST_CHECK( !filter( 4711, attribute ) ); } BOOST_AUTO_TEST_CASE( compare_128bit_with_16bit ) { const auto filter = fixture< bluetoe::details::uuid< 0x1, 0x2, 0x3, 0x4, 0x6 > >(); const blued::attribute attribute = { 0x4711, nullptr }; BOOST_CHECK( !filter( 1, attribute ) ); BOOST_CHECK( !filter( 4711, attribute ) ); } BOOST_AUTO_TEST_CASE( matching_uuid16_filter ) { blued::uuid16_filter< blued::uuid16< 0x2800 > > filter; const blued::attribute attribute = { 0x2800, nullptr }; BOOST_CHECK( filter( 1, attribute ) ); BOOST_CHECK( filter( 4711, attribute ) ); } BOOST_AUTO_TEST_CASE( nomatching_uuid16_filter ) { blued::uuid16_filter< blued::uuid16< 0x2800 > > filter; const blued::attribute attribute = { 0x2801, nullptr }; BOOST_CHECK( !filter( 1, attribute ) ); BOOST_CHECK( !filter( 4711, attribute ) ); }
33.064
111
0.65836
obruns
a4aeac9d036c8e6283235efbd6285376ee5d7156
685
cpp
C++
UVa-11498-DivisionOfNlogonia.cpp
antisocialamp/lowerBound
6b0678954075dd07b247d057b62c2e55669c8cf1
[ "MIT" ]
1
2020-08-07T07:25:23.000Z
2020-08-07T07:25:23.000Z
UVa-11498-DivisionOfNlogonia.cpp
chatziiola/lowerBound
6b0678954075dd07b247d057b62c2e55669c8cf1
[ "MIT" ]
null
null
null
UVa-11498-DivisionOfNlogonia.cpp
chatziiola/lowerBound
6b0678954075dd07b247d057b62c2e55669c8cf1
[ "MIT" ]
null
null
null
#include <cstdio> int main(){ // INPUT PROCESS HAS BEEN MODIFIED DUE TO MULTIPLY CASES IN ONE INPUT // integer K is the number of queries // integers N, M are the coordinates (x,y) of point A (The division point) int K, N, M; // integers a and b stand for the coordinates of point X whose location we must determine int a,b; while ( scanf ("%d %d %d", &K, &N, &M) != EOF ){ for ( int l = 0; l < K; l++){ scanf ( "%d %d", &a, &b); if ( a == N || b == M) printf ( "divisa\n" ); else if ( a < N ) { if ( b > M ) printf ( "NO\n" ); else printf ("SO\n"); } else { if ( b > M ) printf ( "NE\n" ); else printf ( "SE\n" ); } } } }
24.464286
90
0.525547
antisocialamp
a4b445b45998b88c1783a10823f78dc5bf0c4cb0
3,437
hpp
C++
include/Library/Physics/Environment/Objects/CelestialBodies/Sun.hpp
cowlicks/library-physics
dd314011132430fcf074a9a1633b24471745cf92
[ "Apache-2.0" ]
null
null
null
include/Library/Physics/Environment/Objects/CelestialBodies/Sun.hpp
cowlicks/library-physics
dd314011132430fcf074a9a1633b24471745cf92
[ "Apache-2.0" ]
null
null
null
include/Library/Physics/Environment/Objects/CelestialBodies/Sun.hpp
cowlicks/library-physics
dd314011132430fcf074a9a1633b24471745cf92
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @project Library ▸ Physics /// @file Library/Physics/Environment/Objects/CelestialBodies/Sun.hpp /// @author Lucas Brémond <[email protected]> /// @license Apache License 2.0 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef __Library_Physics_Environment_Objects_CelestialBodies_Sun__ #define __Library_Physics_Environment_Objects_CelestialBodies_Sun__ #include <Library/Physics/Environment/Objects/Celestial.hpp> #include <Library/Physics/Environment/Object.hpp> #include <Library/Physics/Environment/Ephemeris.hpp> #include <Library/Physics/Units/Derived.hpp> #include <Library/Physics/Units/Length.hpp> #include <Library/Mathematics/Geometry/3D/Objects/Sphere.hpp> #include <Library/Core/Types/Real.hpp> #include <Library/Core/Types/Shared.hpp> //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace library { namespace physics { namespace env { namespace obj { namespace celest { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using library::core::types::Shared ; using library::core::types::Real ; using library::math::geom::d3::objects::Sphere ; using library::physics::units::Length ; using library::physics::units::Derived ; using library::physics::env::Ephemeris ; using library::physics::env::Object ; using library::physics::env::obj::Celestial ; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class Sun : public Celestial { public: static Derived GravitationalParameter ; static Length EquatorialRadius ; static Real Flattening ; Sun ( const Shared<Ephemeris>& anEphemeris, const Instant& anInstant ) ; virtual ~Sun ( ) override ; virtual Sun* clone ( ) const override ; static Sun Default ( ) ; private: static Object::Geometry Geometry ( const Shared<const Frame>& aFrameSPtr ) ; } ; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } } } } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #endif ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
38.617978
163
0.348851
cowlicks
a4b46e4de6a7cba12fdd44604fc2b9818b3b6040
663
cpp
C++
sources/Core/Instance.cpp
palchukovsky/TunnelEx
ec645271ab8b79225e378345ff108795110c57de
[ "Apache-2.0" ]
null
null
null
sources/Core/Instance.cpp
palchukovsky/TunnelEx
ec645271ab8b79225e378345ff108795110c57de
[ "Apache-2.0" ]
null
null
null
sources/Core/Instance.cpp
palchukovsky/TunnelEx
ec645271ab8b79225e378345ff108795110c57de
[ "Apache-2.0" ]
null
null
null
/************************************************************************** * Created: 2008/07/22 6:56 * Author: Eugene V. Palchukovsky * E-mail: [email protected] * ------------------------------------------------------------------- * Project: TunnelEx * URL: http://tunnelex.net * Copyright: 2007 - 2008 Eugene V. Palchukovsky **************************************************************************/ #include "Prec.h" #include "Instance.hpp" using namespace TunnelEx; Instance::Instance() { /*...*/ } Instance::~Instance() { /*...*/ } Instance::Id Instance::GetInstanceId() const { return reinterpret_cast<Id>(this); }
23.678571
76
0.431373
palchukovsky
8a5465a4bdec3f0699a9dfc975923e47d15c5cf6
4,486
cpp
C++
src/Daemon.cpp
JadedCtrl/rifen
eddbc45d987abe6524715a25ed56e09e8c349300
[ "MIT" ]
4
2021-03-22T06:38:33.000Z
2021-03-23T04:57:44.000Z
src/Daemon.cpp
JadedCtrl/rifen
eddbc45d987abe6524715a25ed56e09e8c349300
[ "MIT" ]
12
2021-02-25T22:13:36.000Z
2021-05-03T01:21:50.000Z
src/Daemon.cpp
JadedCtrl/rifen
eddbc45d987abe6524715a25ed56e09e8c349300
[ "MIT" ]
1
2021-10-11T06:40:06.000Z
2021-10-11T06:40:06.000Z
/* * Copyright 2021, Jaidyn Levesque <[email protected]> * All rights reserved. Distributed under the terms of the MIT license. */ #include "Daemon.h" #include <iostream> #include <MessageRunner.h> #include <Roster.h> #include <Url.h> #include "DeskbarView.h" #include "FeedController.h" #include "Notifier.h" #include "Preferences.h" #include "Util.h" App::App() : BApplication("application/x-vnd.PoggerDaemon") { fPreferences = new Preferences; fPreferences->Load(); fFeedController = new FeedController(); fNotifier = new Notifier(); BMessage updateMessage(kUpdateSubscribed); int64 interval = fPreferences->UpdateInterval(); int32 count = -1; if (interval == -1) count = 0; else MessageReceived(&updateMessage); fUpdateRunner = new BMessageRunner(this, updateMessage, interval, count); installDeskbar(); } void App::MessageReceived(BMessage* msg) { switch(msg->what) { case kPreferencesUpdated: { _ReloadPreferences(); break; } case kEnqueueFeed: case kUpdateSubscribed: case kControllerCheck: case kClearQueue: { fFeedController->MessageReceived(msg); break; } case kProgress: case kParseComplete: case kParseFail: case kDownloadFail: fNotifier->MessageReceived(msg); case kDownloadComplete: case kDownloadStart: { BMessenger toApp("application/x-vnd.Pogger"); if (toApp.IsValid()) toApp.SendMessage(msg); break; } default: BApplication::MessageReceived(msg); } } bool App::QuitRequested() { delete fUpdateRunner, fFeedController, fPreferences; removeDeskbar(); return true; } void App::ArgvReceived(int32 argc, char** argv) { BMessage refMsg(B_REFS_RECEIVED); for (int i = 1; i < argc; i++) { entry_ref ref; BEntry entry(argv[i]); if (entry.Exists() && entry.GetRef(&ref) == B_OK) { refMsg.AddRef("refs", &ref); } else if (BUrl(argv[i]).IsValid()) { BString url = BString(argv[i]); BMessage enqueue = BMessage(kEnqueueFeed); enqueue.AddData("feedPaths", B_STRING_TYPE, &url, sizeof(BString)); MessageReceived(&enqueue); } } RefsReceived(&refMsg); } void App::RefsReceived(BMessage* message) { int i = 0; entry_ref ref; BFile file; BNodeInfo info; char type[B_FILE_NAME_LENGTH]; while (message->HasRef("refs", i)) { BMessage msg(B_REFS_RECEIVED); message->FindRef("refs", i++, &ref); msg.AddRef("refs", &ref); file.SetTo(&ref, B_READ_ONLY); info.SetTo(&file); info.GetType(type); if (BString(type) == "application/x-feed-entry" || BString(type) == "text/x-feed-entry") _OpenEntryFile(&msg); else if (BString(type) == "application/x-feed-source") _OpenSourceFile(&msg); } } void App::_OpenEntryFile(BMessage* refMessage) { entry_ref entryRef; refMessage->FindRef("refs", &entryRef); BFile entryFile(&entryRef, B_WRITE_ONLY); BString readStatus("Read"); entryFile.WriteAttrString("Feed:status", &readStatus); if (fPreferences->EntryOpenAsHtml()) _OpenEntryFileAsHtml(entryRef); else _OpenEntryFileAsUrl(entryRef); } void App::_OpenEntryFileAsHtml(entry_ref ref) { const char* openWith = fPreferences->EntryOpenWith(); entry_ref openWithRef; BString entryTitle("untitled"); BFile(&ref, B_READ_ONLY).ReadAttrString("Feed:name", &entryTitle); entry_ref tempRef = tempHtmlFile(&ref, entryTitle.String()); BMessage newRefMessage(B_REFS_RECEIVED); newRefMessage.AddRef("refs", &tempRef); if (BMimeType(openWith).IsValid()) BRoster().Launch(openWith, &newRefMessage); else if (BEntry(openWith).GetRef(&openWithRef) == B_OK) BRoster().Launch(&openWithRef, &newRefMessage); } void App::_OpenEntryFileAsUrl(entry_ref ref) { const char* openWith = fPreferences->EntryOpenWith(); entry_ref openWithRef; BString entryUrl; if (BFile(&ref, B_READ_ONLY).ReadAttrString("META:url", &entryUrl) != B_OK) return; const char* urlArg = entryUrl.String(); if (BMimeType(openWith).IsValid()) BRoster().Launch(openWith, 1, &urlArg); else if (BEntry(openWith).GetRef(&openWithRef) == B_OK) BRoster().Launch(&openWithRef, 1, &urlArg); } void App::_OpenSourceFile(BMessage* refMessage) { BRoster roster; roster.Launch("application/x-vnd.Pogger", refMessage); } void App::_ReloadPreferences() { fPreferences->Load(); int64 interval = fPreferences->UpdateInterval(); if (interval == -1) fUpdateRunner->SetCount(0); else { fUpdateRunner->SetCount(-1); fUpdateRunner->SetInterval(interval); } } int main(int argc, char** arv) { App app; app.Run(); return 0; }
19.849558
76
0.708426
JadedCtrl
8a57cd016755c5f2542523c05a0a681508d0a43d
3,366
cpp
C++
multibase/server/tcpsrv.cpp
Zzzzipper/cppprojects
e9c9b62ca1e411320c24a3d168cab259fa2590d3
[ "MIT" ]
null
null
null
multibase/server/tcpsrv.cpp
Zzzzipper/cppprojects
e9c9b62ca1e411320c24a3d168cab259fa2590d3
[ "MIT" ]
1
2021-09-03T13:03:20.000Z
2021-09-03T13:03:20.000Z
multibase/server/tcpsrv.cpp
Zzzzipper/cppprojects
e9c9b62ca1e411320c24a3d168cab259fa2590d3
[ "MIT" ]
null
null
null
#include "tcpsrv.h" #include "processor.h" #include "json.h" #include "m_types.h" namespace multibase { /** * @brief session::session * @param socket */ Session::Session(tcp::socket socket) : socket_(std::move(socket)) { } /** * @brief session::start */ void Session::start(Processor& p_) { doRead(p_); } /** * @brief session::doRead */ void Session::doRead(Processor& p_) { auto self(shared_from_this()); socket_.async_read_some(boost::asio::buffer(data_, MAX_MESSAGE_LENGTH), [&, self](boost::system::error_code ec, std::size_t length) { try { if (!ec) { LOG_TRACE << data_; using boost::spirit::ascii::space; typedef std::string::const_iterator iterator_type; typedef request_parser<iterator_type> request_parser; request_parser g; // Our grammar std::string buffer(data_); size_t startpos = buffer.find_first_not_of("}"); if( std::string::npos != startpos ) { buffer = buffer.substr( startpos ); } request r; std::string::const_iterator iter = buffer.begin(); std::string::const_iterator end = buffer.end(); bool result = phrase_parse(iter, end, g, space, r); if(result) { response resp = p_.exec(r); std::ostringstream streamBuf; json::serializer<response>::serialize(streamBuf, resp); std::string copy = streamBuf.str(); length = (copy.length() > MAX_MESSAGE_LENGTH)? MAX_MESSAGE_LENGTH: copy.length(); strncpy(data_, copy.c_str(), length); data_[length - 1] = '\0'; } doWrite(length, p_); } } catch (std::exception e) { LOG_ERROR << "Exception (Session::doRead): " << e.what(); } }); } /** * @brief session::doRead * @param length */ void Session::doWrite(std::size_t length, Processor& p_) { auto self(shared_from_this()); boost::asio::async_write(socket_, boost::asio::buffer(data_, length), [&, self](boost::system::error_code ec, std::size_t /*length*/) { if (!ec) { doRead(p_); } }); } /** * @brief server::server * @param io_context * @param port */ Server::Server(boost::asio::io_context& io_context, unsigned short port, Processor& p) : acceptor_(io_context, tcp::endpoint(tcp::v4(), port)) { doAccept(p); } /** * @brief server::doAccept */ void Server::doAccept(Processor& p) { acceptor_.async_accept( [&](boost::system::error_code ec, tcp::socket socket) { if (!ec) { std::make_shared<Session>(std::move(socket))->start(p); } doAccept(p); }); } }
30.053571
96
0.468509
Zzzzipper
8a5f2dcd1db9f849aa46606d0095a4d151269317
1,792
cpp
C++
test/extra_test/catch2/main.cpp
KaiserLancelot/kpkg
c19d2a027d47ec2dff7c3eeaa6eb86284aeefcd4
[ "MIT" ]
1
2022-02-28T12:31:46.000Z
2022-02-28T12:31:46.000Z
test/extra_test/catch2/main.cpp
KaiserLancelot/kpkg
c19d2a027d47ec2dff7c3eeaa6eb86284aeefcd4
[ "MIT" ]
null
null
null
test/extra_test/catch2/main.cpp
KaiserLancelot/kpkg
c19d2a027d47ec2dff7c3eeaa6eb86284aeefcd4
[ "MIT" ]
1
2021-11-06T14:20:25.000Z
2021-11-06T14:20:25.000Z
#include <cstdint> #include <vector> #include <catch2/catch.hpp> std::uint64_t factorial(std::uint64_t number) { return number > 1 ? factorial(number - 1) * number : 1; } // https://github.com/catchorg/Catch2/blob/devel/docs/tutorial.md // https://github.com/catchorg/Catch2/blob/devel/docs/benchmarks.md TEST_CASE("factorial") { // 失败则终止 test case REQUIRE(factorial(0) == 1); // 失败也继续执行 CHECK(factorial(0) == 1); REQUIRE(factorial(1) == 1); REQUIRE(factorial(2) == 2); REQUIRE(factorial(3) == 6); REQUIRE(factorial(10) == 3628800); BENCHMARK("factorial 10") { return factorial(10); }; BENCHMARK_ADVANCED("factorial 10 advanced") (Catch::Benchmark::Chronometer meter) { meter.measure([] { return factorial(10); }); }; } TEST_CASE("float") { REQUIRE([] { return 0.5 + 0.8; }() == Approx(1.3)); } SCENARIO("vectors can be sized and resized") { GIVEN("A vector with some items") { std::vector<std::int32_t> v(5); REQUIRE(v.size() == 5); REQUIRE(v.capacity() >= 5); WHEN("the size is increased") { v.resize(10); THEN("the size and capacity change") { REQUIRE(v.size() == 10); REQUIRE(v.capacity() >= 10); } } WHEN("the size is reduced") { v.resize(0); THEN("the size changes but not capacity") { REQUIRE(v.size() == 0); REQUIRE(v.capacity() >= 5); } } WHEN("more capacity is reserved") { v.reserve(10); THEN("the capacity changes but not the size") { REQUIRE(v.size() == 5); REQUIRE(v.capacity() >= 10); } } WHEN("less capacity is reserved") { v.reserve(0); THEN("neither size nor capacity are changed") { REQUIRE(v.size() == 5); REQUIRE(v.capacity() >= 5); } } } }
23.578947
67
0.582031
KaiserLancelot
8a5f4a69438e3fefb9daeb2033f78c90e9cd2849
2,503
cpp
C++
src/entities/CTask.cpp
nizikawa-worms/wkJellyWorm
ddc1b00d38eb92c501bf3554804f4e02319b7bd9
[ "WTFPL" ]
5
2021-04-19T14:29:50.000Z
2022-01-07T02:46:30.000Z
src/entities/CTask.cpp
nizikawa-worms/wkJellyWorm
ddc1b00d38eb92c501bf3554804f4e02319b7bd9
[ "WTFPL" ]
null
null
null
src/entities/CTask.cpp
nizikawa-worms/wkJellyWorm
ddc1b00d38eb92c501bf3554804f4e02319b7bd9
[ "WTFPL" ]
1
2021-04-19T14:29:24.000Z
2021-04-19T14:29:24.000Z
#include "../Lua.h" #include <sol/sol.hpp> #include "../Hooks.h" #include "CTask.h" DWORD *(__stdcall *origConstructCTask)(DWORD *This, int a2, int a3); DWORD *__stdcall CTask::hookConstructCTask(DWORD *This, int a2, int a3) { return origConstructCTask(This, a2, a3); } CTask * (__fastcall *origGetHashStoreObject)(int a1, int a2, CTask * This); CTask *CTask::callGetHashStoreObject(int a1, int a2, CTask *This) { return origGetHashStoreObject(a1, a2, This); } int CTask::install(SignatureScanner &signatureScanner, module mod) { auto * lua = Lua::getInstance().getState(); sol::usertype <CTask> ut = lua->new_usertype <CTask> ("CTask"); ut["parent"] = &CTask::parent; ut["children"] = &CTask::children; ut["unknown1C"] = &CTask::unknown1C; ut["classtype"] = &CTask::classtype; ut["unknown24"] = &CTask::unknown24; ut["unknown28"] = &CTask::unknown28; ut["unknown2C"] = &CTask::unknown2C; ut["getOffset"] = &CTask::getOffset; ut["setOffset"] = &CTask::setOffset; ut["getAddr"] = &CTask::getAddr; lua->new_usertype<CTaskList>("CTaskList", "iterable", [](CTaskList& ns) { return sol::as_container(ns);}, "size", &CTaskList::size, "get", [](CTaskList& ns, int index) { return ns[index-1];} ); DWORD addrConstructCTask = Hooks::scanPattern("ConstructCTask", "\x64\xA1\x00\x00\x00\x00\x6A\xFF\x68\x00\x00\x00\x00\x50\x64\x89\x25\x00\x00\x00\x00\x56\x57\x8B\x7C\x24\x18\xC7\x07\x00\x00\x00\x00\x6A\x60\xC7\x47\x00\x00\x00\x00\x00\xC7\x47\x00\x00\x00\x00\x00\xC7\x47\x00\x00\x00\x00\x00\xE8\x00\x00\x00\x00\x6A\x40", "??????xxx????xxxx????xxxxxxxx????xxxx?????xx?????xx?????x????xx", 0x5625A0); origGetHashStoreObject = (CTask *(__fastcall *)(int,int,CTask *))Hooks::scanPattern("CTaskGetHashStoreObject", "\x8B\xC1\xC1\xE0\x04\x03\xC2\x03\xC1\x25\x00\x00\x00\x00\x56\x79\x07\x48\x0D\x00\x00\x00\x00\x40\x8B\x74\x24\x08\x8B\x76\x24\x8B\x04\x86\x85\xC0\x5E\x74\x10", "??????xxxx????xxxxx????xxxxxxxxxxxxxxxx", 0x4FDF90); DWORD * addrCTaskVTable = *(DWORD**)(addrConstructCTask + 0x1D); CTaskAddVTHooks(CTask, addrCTaskVTable) CTaskAddLuaVTHooks(CTask) Hooks::polyhook("constructCTask", addrConstructCTask, (DWORD *) &hookConstructCTask, (DWORD *) &origConstructCTask); lua->set_function("getHashStoreObject", &callGetHashStoreObject); return 0; } DWORD CTask::getOffset(DWORD offset) { return *(DWORD*)(this + offset); } void CTask::setOffset(DWORD offset, DWORD value) { *(DWORD*)(this + offset) = value; } DWORD CTask::getAddr() { return (DWORD)this; }
38.507692
399
0.695965
nizikawa-worms
8a60ffc6eba71542ceee88cba78ab310385560bb
5,049
hpp
C++
include/Core/Transform/Rect.hpp
Tzupy/ObEngine
fa5c36aa41be1586088b76319c648d39c7f57cdf
[ "MIT" ]
null
null
null
include/Core/Transform/Rect.hpp
Tzupy/ObEngine
fa5c36aa41be1586088b76319c648d39c7f57cdf
[ "MIT" ]
null
null
null
include/Core/Transform/Rect.hpp
Tzupy/ObEngine
fa5c36aa41be1586088b76319c648d39c7f57cdf
[ "MIT" ]
null
null
null
#pragma once #include <Transform/Movable.hpp> #include <Transform/Referential.hpp> namespace obe::Transform { /** * \brief A Class that does represent a Rectangle with various methods to * manipulate it * @Bind */ class Rect : public Movable { protected: /** * \brief Size of the Rect */ UnitVector m_size; float m_angle = 0; public: /** * \brief Conversion Type for Referential Usage */ enum class ConversionType { /** * \brief Factor x1 (GetPosition) */ From, /** * \brief Factor x-1 (SetPosition) */ To }; /** * \brief Transform the UnitVector passed by reference using the given * Referential \param vec The UnitVector you want to transform \param * ref The chosen Rect::Referential \param type The way you want to * transform your UnitVector * - From : Referential::TopLeft to ref * - To : ref to Referential::TopLeft */ void transformRef(UnitVector& vec, Referential ref, ConversionType type) const; Rect(); Rect(const Transform::UnitVector& position, const Transform::UnitVector& size); /** * \brief Set the position of the Rect (Movable override) using an * UnitVector \param position Position to affect to the Rect (Movable * override) */ void setPosition(const UnitVector& position) override; /** * \brief Get the Position of the Rect (Movable Override) * \return The Position of the given Referential of the Rect (Movable * Override) */ UnitVector getPosition() const override; /** * \brief Set the position of the Rect using an UnitVector * \param position Position to affect to the Rect * \param ref Referential used to set the Position */ virtual void setPosition(const UnitVector& position, Referential ref); /** * \brief Moves the Rectangle (Adds the given position to the current * one) \param position Position to add to the current Position */ void move(const UnitVector& position) override; /** * \brief Get the Position of the Rect * \param ref Referential of the Rect you want to use to get the * Position \return The Position of the given Referential of the Rect */ virtual UnitVector getPosition(Referential ref) const; /** * \brief Set the Position of a specific Referential of the Rect (The * opposite Point won't move) \param position Position to affect to the * specific Referential \param ref Referential you want to move */ void setPointPosition(const UnitVector& position, Referential ref = Referential::TopLeft); /** * \brief Move a specific Referential of the Rect (The opposite Point * won't move) \param position Position to add to the specific * Referential \param ref Referential you want to move */ void movePoint(const UnitVector& position, Referential ref = Referential::TopLeft); /** * \brief Set the size of the Rect * \param size New size of the Rect * \param ref Referential used to resize the Rect (Referential that * won't move) */ void setSize(const UnitVector& size, Referential ref = Referential::TopLeft); /** * \brief Scales the Rect (Relative to the current size) * \param size Size to multiply to the current size * \param ref Referential used to scale the Rect (Referential that won't * move) */ void scale(const UnitVector& size, Referential ref = Referential::TopLeft); /** * \brief Get the Size of the Rect * \return An UnitVector containing the size of the Rect (Default Unit * is SceneUnits) */ virtual UnitVector getSize() const; /** * \brief Get the Scale Factor of the Rect * \return An UnitVector containing the Scale Factors of the Rect. \n * x attribute will be equal to -1 if the Rect is flipped * horizontally, 1 otherwise. \n y attribute will be equal to -1 if the * Rect is flipped vertically, 1 otherwise. */ UnitVector getScaleFactor() const; float getRotation() const; void setRotation(float angle, Transform::UnitVector origin); void rotate(float angle, Transform::UnitVector origin); /** * \brief Draws the Rect for debug purposes <REMOVE> */ void draw(int posX, int posY) const; }; } // namespace obe::Transform
37.4
80
0.576946
Tzupy
8a75c25038fddc0ec336ca4c1fb25fcc4ab95c35
2,904
hpp
C++
include/boost/channels/error_code.hpp
cblauvelt/boost_channels
455772295caf9a3a215b9d2569e484f0e2f91022
[ "BSL-1.0" ]
23
2021-05-29T04:26:25.000Z
2022-03-23T07:12:13.000Z
include/boost/channels/error_code.hpp
cblauvelt/boost_channels
455772295caf9a3a215b9d2569e484f0e2f91022
[ "BSL-1.0" ]
2
2021-09-28T20:00:22.000Z
2021-09-28T20:10:39.000Z
include/boost/channels/error_code.hpp
cblauvelt/boost_channels
455772295caf9a3a215b9d2569e484f0e2f91022
[ "BSL-1.0" ]
1
2021-10-03T01:12:37.000Z
2021-10-03T01:12:37.000Z
// // Copyright (c) 2021 Richard Hodges ([email protected]) // // 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) // // Official repository: https://github.com/madmongo1/boost_channels // #ifndef BOOST_CHANNELS_INCLUDE_BOOST_CHANNELS_ERROR_CODE_HPP #define BOOST_CHANNELS_INCLUDE_BOOST_CHANNELS_ERROR_CODE_HPP #include <string_view> #include <boost/system/error_category.hpp> #include <boost/system/error_code.hpp> namespace boost::channels { using ::boost::system::error_category; using ::boost::system::error_code; struct errors { enum channel_errors { channel_null = 1, //! The channel does not have an implementation channel_closed = 2, //! The channel has been closed }; struct channel_category final : error_category { const char * name() const noexcept override { return "boost::channel::channel_errors"; } virtual std::string message(int ev) const override { auto const source = get_message(ev); return std::string(source.begin(), source.end()); } char const * message(int ev, char *buffer, std::size_t len) const noexcept override { auto const source = get_message(ev); // Short circuit when buffer of size zero is offered. // Note that this is safe because the string_view's data actually // points to a c-style string. if (len == 0) return source.data(); auto to_copy = (std::min)(len - 1, source.size()); std::copy(source.data(), source.data() + to_copy, buffer); buffer[len] = '\0'; return buffer; } private: std::string_view get_message(int code) const { static const std::string_view messages[] = { "Invalid code", "Channel is null", "Channel is closed" }; auto ubound = static_cast< int >(std::extent_v< decltype(messages) >); if (code < 1 || code >= ubound) code = 0; return messages[code]; } }; }; inline errors::channel_category const & channel_category() { constinit static const errors::channel_category cat; return cat; }; inline error_code make_error_code(errors::channel_errors code) { return error_code(static_cast< int >(code), channel_category()); } } // namespace boost::channels namespace boost::system { template <> struct is_error_code_enum< ::boost::channels::errors::channel_errors > : std::true_type { }; } // namespace boost::system #endif // BOOST_CHANNELS_INCLUDE_BOOST_CHANNELS_ERROR_CODE_HPP
27.923077
79
0.603994
cblauvelt
8a7cb03762dc2b98162431636f480cfd9d9111cd
1,024
cpp
C++
Source/SystemQOR/MSWindows/WinQL/GUI/Controllers/WinQLRowContainer.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
9
2016-05-27T01:00:39.000Z
2021-04-01T08:54:46.000Z
Source/SystemQOR/MSWindows/WinQL/GUI/Controllers/WinQLRowContainer.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
1
2016-03-03T22:54:08.000Z
2016-03-03T22:54:08.000Z
Source/SystemQOR/MSWindows/WinQL/GUI/Controllers/WinQLRowContainer.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
4
2016-05-27T01:00:43.000Z
2018-08-19T08:47:49.000Z
//RowContainer.cpp //#include "stdafx.h" #include "WinQL/GUI/Controllers/RowContainer.h" #include "WinQL/GUI/Window.h" //-------------------------------------------------------------------------------- namespace nsWin32 { //-------------------------------------------------------------------------------- namespace nsGUI { /* //-------------------------------------------------------------------------------- bool CRowContainer::ProcessMessage( COSWindow* pWindow, WindowHandle hWnd, Cmp_long_ptr& lResult, unsigned int uMsg, Cmp_uint_ptr wParam, Cmp_long_ptr lParam ) { bool bProcessed = ProcessHook( pWindow, hWnd, lResult, uMsg, wParam, lParam ); switch ( uMsg ) { default: { unsigned int uiLoop; for( uiLoop = 0; uiLoop < m_apControllers.Size(); uiLoop ++ ) { bProcessed |= m_apControllers[ uiLoop ]->ProcessMessage( pWindow, hWnd, lResult, uMsg, wParam, lParam ); } } } return bProcessed; } */ };//namespace nsGUI };//namespace nsWin32
27.675676
161
0.5
mfaithfull
8a7d79370e318de649b0b85f333029193f1e959c
4,681
cpp
C++
source/test/unit-test.cpp
CaptainCrowbar/rs-tl
fe9e3f072683f638a427d44d132e27435af5bd40
[ "BSL-1.0" ]
null
null
null
source/test/unit-test.cpp
CaptainCrowbar/rs-tl
fe9e3f072683f638a427d44d132e27435af5bd40
[ "BSL-1.0" ]
null
null
null
source/test/unit-test.cpp
CaptainCrowbar/rs-tl
fe9e3f072683f638a427d44d132e27435af5bd40
[ "BSL-1.0" ]
null
null
null
// This file is generated by the rs-update-tests script #include "rs-unit-test.hpp" int main(int argc, char** argv) { RS::UnitTest::begin_tests(argc, argv); // types-test.cpp UNIT_TEST(rs_tl_types_mixins) UNIT_TEST(rs_tl_types_traits) UNIT_TEST(rs_tl_types_iterator_category) UNIT_TEST(rs_tl_types_range_category) // enum-test.cpp UNIT_TEST(rs_format_enum_definition) UNIT_TEST(rs_format_enum_bitmask_operators) // iterator-test.cpp UNIT_TEST(rs_tl_iterator_mixins) UNIT_TEST(rs_tl_iterator_append_overwrite) UNIT_TEST(rs_tl_iterator_dereference) UNIT_TEST(rs_tl_iterator_iota) UNIT_TEST(rs_tl_iterator_subrange) // log-test.cpp UNIT_TEST(rs_format_logging) UNIT_TEST(rs_format_logging_output) // meta-test.cpp UNIT_TEST(rs_tl_meta_append) UNIT_TEST(rs_tl_meta_concat) UNIT_TEST(rs_tl_meta_insert) UNIT_TEST(rs_tl_meta_insert_at) UNIT_TEST(rs_tl_meta_prefix) UNIT_TEST(rs_tl_meta_repeat) UNIT_TEST(rs_tl_meta_repeat_list) UNIT_TEST(rs_tl_meta_resize) UNIT_TEST(rs_tl_meta_skip) UNIT_TEST(rs_tl_meta_sublist) UNIT_TEST(rs_tl_meta_take) UNIT_TEST(rs_tl_meta_at_index) UNIT_TEST(rs_tl_meta_head) UNIT_TEST(rs_tl_meta_tail) UNIT_TEST(rs_tl_meta_most) UNIT_TEST(rs_tl_meta_last) UNIT_TEST(rs_tl_meta_max_min) UNIT_TEST(rs_tl_meta_fold) UNIT_TEST(rs_tl_meta_make_set) UNIT_TEST(rs_tl_meta_map) UNIT_TEST(rs_tl_meta_partial_reduce) UNIT_TEST(rs_tl_meta_remove) UNIT_TEST(rs_tl_meta_reverse) UNIT_TEST(rs_tl_meta_select) UNIT_TEST(rs_tl_meta_sort) UNIT_TEST(rs_tl_meta_unique) UNIT_TEST(rs_tl_meta_zip) UNIT_TEST(rs_tl_meta_inherit) UNIT_TEST(rs_tl_meta_tuples) UNIT_TEST(rs_tl_meta_all_of) UNIT_TEST(rs_tl_meta_count) UNIT_TEST(rs_tl_meta_find) UNIT_TEST(rs_tl_meta_in_list) UNIT_TEST(rs_tl_meta_is_empty) UNIT_TEST(rs_tl_meta_is_unique) UNIT_TEST(rs_tl_meta_length_of) // algorithm-test.cpp UNIT_TEST(rs_tl_algorithm_container_algorithms) UNIT_TEST(rs_tl_algorithm_diff) UNIT_TEST(rs_tl_algorithm_edit_distance) UNIT_TEST(rs_tl_algorithm_hash_compare) UNIT_TEST(rs_tl_algorithm_subsets) // binary-test.cpp UNIT_TEST(rs_tl_binary_byte_order) UNIT_TEST(rs_tl_binary_birwise_operations) UNIT_TEST(rs_tl_binary_signed_overflow_detection) UNIT_TEST(rs_tl_binary_unsigned_overflow_detection) // fixed-binary-small-binary-5-test.cpp UNIT_TEST(rs_tl_fixed_binary_small_binary_5) // fixed-binary-small-binary-35-test.cpp UNIT_TEST(rs_tl_fixed_binary_small_binary_35) // fixed-binary-large-binary-35-test.cpp UNIT_TEST(rs_tl_fixed_binary_large_binary_35) // fixed-binary-large-binary-100-test.cpp UNIT_TEST(rs_tl_fixed_binary_large_binary_100) // fixed-binary-misc-test.cpp UNIT_TEST(rs_tl_fixed_binary_implementation_selection) UNIT_TEST(rs_tl_fixed_binary_type_conversions) UNIT_TEST(rs_tl_fixed_binary_string_parsing) UNIT_TEST(rs_tl_fixed_binary_hash_set) // guard-test.cpp UNIT_TEST(rs_tl_scope_guards) // bounded-array-construction-test.cpp UNIT_TEST(rs_tl_bounded_array_construction) // bounded-array-insertion-test.cpp UNIT_TEST(rs_tl_bounded_array_insertion) // bounded-array-tracking-test.cpp UNIT_TEST(rs_tl_bounded_array_tracking) // bounded-array-misc-test.cpp UNIT_TEST(rs_tl_bounded_array_capacity) UNIT_TEST(rs_tl_bounded_array_keys) // compact-array-construction-test.cpp UNIT_TEST(rs_tl_compact_array_construction) // compact-array-insertion-test.cpp UNIT_TEST(rs_tl_compact_array_insertion) // compact-array-tracking-test.cpp UNIT_TEST(rs_tl_compact_array_tracking) // compact-array-misc-test.cpp UNIT_TEST(rs_tl_compact_array_capacity) UNIT_TEST(rs_tl_compact_array_keys) // index-table-test.cpp UNIT_TEST(rs_tl_index_table_classes) // mirror-map-test.cpp UNIT_TEST(rs_tl_mirror_map_construct) UNIT_TEST(rs_tl_mirror_map_iterators) UNIT_TEST(rs_tl_mirror_map_insert) UNIT_TEST(rs_tl_mirror_map_erase) UNIT_TEST(rs_tl_mirror_map_search) UNIT_TEST(rs_tl_mirror_map_duplicates) // stack-test.cpp UNIT_TEST(rs_tl_stack) // thread-test.cpp UNIT_TEST(rs_tl_thread) // time-test.cpp UNIT_TEST(rs_tl_time_waiter) // topological-order-test.cpp UNIT_TEST(rs_tl_topological_order) UNIT_TEST(rs_tl_topological_order_reverse) // uuid-test.cpp UNIT_TEST(rs_tl_uuid) // version-test.cpp UNIT_TEST(rs_tl_version) // unit-test.cpp return RS::UnitTest::end_tests(); }
28.717791
58
0.771203
CaptainCrowbar
8a7d9f390c699a974d904a1db836d9520d3aed98
5,813
cpp
C++
Blink.cpp
CPaladiya/14_BlackJack
4a65abbefac00d362e1017f064a10a15ae8f8a73
[ "Linux-OpenIB" ]
null
null
null
Blink.cpp
CPaladiya/14_BlackJack
4a65abbefac00d362e1017f064a10a15ae8f8a73
[ "Linux-OpenIB" ]
null
null
null
Blink.cpp
CPaladiya/14_BlackJack
4a65abbefac00d362e1017f064a10a15ae8f8a73
[ "Linux-OpenIB" ]
null
null
null
#include "GameGUI.h" //Will set tile to yellow color background to player score void Window::PlayerScoreYellowTile(){ PlayerScore_->setStyleSheet("background-color : yellow ; font-size : 60 px; font-weight : bold; color : black"); } //Will set tile to yellow color background to dealer score void Window::DealerScoreYellowTile(){ DealerScore_->setStyleSheet("background-color : yellow ; font-size : 60 px; font-weight : bold; color : black"); } //Func will set tile to green color background to dealer score void Window::ScoreDefaultTile(){ DealerScore_->setStyleSheet("background-color : black ; font-size : 60 px; font-weight : bold; color : red"); PlayerScore_->setStyleSheet("background-color : black ; font-size : 60 px; font-weight : bold; color : white"); } //Func to blink score tile when player's score is updated void Window::PlayerScoreUpdateBlink(){ QTimer::singleShot(100,this,&Window::PlayerScoreYellowTile); QTimer::singleShot(200,this,&Window::ScoreDefaultTile); } //Func to blink score tile when dealer's score is updated void Window::DealerScoreUpdateBlink(){ QTimer::singleShot(100,this,&Window::DealerScoreYellowTile); QTimer::singleShot(200,this,&Window::ScoreDefaultTile); } //Tile to blink with Red color background for players fund void Window::FundRedTile(){ PlayersFundInfoLabel_->setStyleSheet("background-color : red ; font-size : 60 px; font-weight : bold; color : black"); } //Tile to blink with Green color background for players fund void Window::FundGreenTile(){ PlayersFundInfoLabel_->setStyleSheet("background-color : green ; font-size : 60 px; font-weight : bold; color : black"); } //Tile to blink with Default color background for players fund void Window::FundDefaultTile(){ PlayersFundInfoLabel_->setStyleSheet("background-color : black ; font-size : 60 px; font-weight : bold; color : white"); } //Player winning status blink - blinking 3 times with distance of 200 ms void Window::PlayerWonFundBlink(){ QTimer::singleShot(0,this,&Window::FundGreenTile); QTimer::singleShot(200,this,&Window::FundDefaultTile); QTimer::singleShot(400,this,&Window::FundGreenTile); QTimer::singleShot(600,this,&Window::FundDefaultTile); QTimer::singleShot(800,this,&Window::FundGreenTile); QTimer::singleShot(1000,this,&Window::FundDefaultTile); } //Player winning status blink - blinking 3 times with distance of 200 ms void Window::PlayerLostFundBlink(){ QTimer::singleShot(0,this,&Window::FundRedTile); QTimer::singleShot(200,this,&Window::FundDefaultTile); QTimer::singleShot(400,this,&Window::FundRedTile); QTimer::singleShot(600,this,&Window::FundDefaultTile); QTimer::singleShot(800,this,&Window::FundRedTile); QTimer::singleShot(1000,this,&Window::FundDefaultTile); } //Tile to blink with green color background for status of the game void Window::MessgaePromptGreenTile(){ MessageLabel_->setStyleSheet("background-color : green ; font-size : 60 px; font-weight : bold; color : black"); } //Tile to blink with red color background for status of the game void Window::MessgaePromptRedTile(){ MessageLabel_->setStyleSheet("background-color : red ; font-size : 60 px; font-weight : bold; color : black"); } //Tile to blink with default color background for status of the game void Window::MessgaePromptDefaultTile(){ MessageLabel_->setStyleSheet("background-color : black ; font-size : 60 px; font-weight : bold; color : white"); } //Tile to blink when player wins void Window::PlayerWonBlink(){ MessageLabel_->setText("You Won "+QString::number(CurrentBet_)+"$!"); QTimer::singleShot(0,this,&Window::MessgaePromptGreenTile); QTimer::singleShot(200,this,&Window::MessgaePromptDefaultTile); QTimer::singleShot(400,this,&Window::MessgaePromptGreenTile); QTimer::singleShot(600,this,&Window::MessgaePromptDefaultTile); QTimer::singleShot(800,this,&Window::MessgaePromptGreenTile); QTimer::singleShot(1000,this,&Window::MessgaePromptDefaultTile); } //Tile to blink when player wins blackjack void Window::PlayerBlackJackBlink(){ MessageLabel_->setText("Black Jack of "+QString::number(CurrentBet_*1.5)+"$!"); QTimer::singleShot(0,this,&Window::MessgaePromptGreenTile); QTimer::singleShot(200,this,&Window::MessgaePromptDefaultTile); QTimer::singleShot(400,this,&Window::MessgaePromptGreenTile); QTimer::singleShot(600,this,&Window::MessgaePromptDefaultTile); QTimer::singleShot(800,this,&Window::MessgaePromptGreenTile); QTimer::singleShot(1000,this,&Window::MessgaePromptDefaultTile); } //Tile to blink when player loses void Window::PlayerLostBlink(){ MessageLabel_->setText("You Lost "+QString::number(CurrentBet_)+"$!"); QTimer::singleShot(0,this,&Window::MessgaePromptRedTile); QTimer::singleShot(200,this,&Window::MessgaePromptDefaultTile); QTimer::singleShot(400,this,&Window::MessgaePromptRedTile); QTimer::singleShot(600,this,&Window::MessgaePromptDefaultTile); QTimer::singleShot(800,this,&Window::MessgaePromptRedTile); QTimer::singleShot(1000,this,&Window::MessgaePromptDefaultTile); } //Tile to blink when game is draw void Window::GameDrawBlink(){ MessageLabel_->setText("Game Draw!"); QTimer::singleShot(0,this,&Window::MessgaePromptGreenTile); QTimer::singleShot(200,this,&Window::MessgaePromptDefaultTile); QTimer::singleShot(400,this,&Window::MessgaePromptGreenTile); QTimer::singleShot(600,this,&Window::MessgaePromptDefaultTile); QTimer::singleShot(800,this,&Window::MessgaePromptGreenTile); QTimer::singleShot(1000,this,&Window::MessgaePromptDefaultTile); } void Window::PlayWinningSound(){ WonSound_->play(); } void Window::PlayLostSound(){ LostSound_->play(); } void Window::PlayDrawSound(){ DrawSound_->play(); }
42.742647
124
0.744194
CPaladiya
8a7e58908b7c902cd91155801a4cac3dd6a6307f
1,676
cpp
C++
pack/cpp/deltas_amd64.cpp
viant/vec
51f2e71bebfbfa80ab44f3d00bca1adeb4a9c3c9
[ "Apache-2.0" ]
1
2022-02-21T22:44:50.000Z
2022-02-21T22:44:50.000Z
pack/cpp/deltas_amd64.cpp
viant/vec
51f2e71bebfbfa80ab44f3d00bca1adeb4a9c3c9
[ "Apache-2.0" ]
null
null
null
pack/cpp/deltas_amd64.cpp
viant/vec
51f2e71bebfbfa80ab44f3d00bca1adeb4a9c3c9
[ "Apache-2.0" ]
null
null
null
#include <smmintrin.h> void compute_deltas(const int32_t * input, size_t length, int32_t * output, int32_t starting_point) asm("compute_deltas"); void compute_deltas(const int32_t * input, size_t length, int32_t * output, int32_t starting_point) { __m128i prev = _mm_set1_epi32(starting_point); size_t i = 0; for (; i < length / 4; i++) { __m128i curr = _mm_lddqu_si128((const __m128i *) input + i); __m128i delta = _mm_sub_epi32(curr, _mm_alignr_epi8(curr, prev, 12)); _mm_storeu_si128((__m128i *) output + i, delta); prev = curr; } int32_t lastprev = _mm_extract_epi32(prev, 3); for (i = 4 * i; i < length; ++i) { int32_t curr = input[i]; output[i] = curr - lastprev; lastprev = curr; } } void compute_prefix_sum(const int32_t * input, size_t length, int32_t * output, int32_t starting_point) asm("compute_prefix_sum"); void compute_prefix_sum(const int32_t * input, size_t length, int32_t * output, int32_t starting_point) { __m128i prev = _mm_set1_epi32(starting_point); size_t i = 0; for(; i < length/4; i++) { __m128i curr = _mm_lddqu_si128 (( const __m128i*) input + i ); const __m128i _tmp1 = _mm_add_epi32(_mm_slli_si128(curr, 8), curr); const __m128i _tmp2 = _mm_add_epi32(_mm_slli_si128(_tmp1, 4), _tmp1); prev = _mm_add_epi32(_tmp2, _mm_shuffle_epi32(prev, 0xff)); _mm_storeu_si128((__m128i*)output + i,prev); } int32_t lastprev = _mm_extract_epi32(prev,3); for(i = 4 * i; i < length; ++i) { lastprev = lastprev + input[i]; output[i] = lastprev; } }
42.974359
132
0.636038
viant
8a8169088648ed0531c5139f5793c4df1f1641f6
198
hpp
C++
sprout/type/algorithm.hpp
osyo-manga/Sprout
8885b115f739ef255530f772067475d3bc0dcef7
[ "BSL-1.0" ]
1
2020-02-04T05:16:01.000Z
2020-02-04T05:16:01.000Z
sprout/type/algorithm.hpp
jwakely/Sprout
a64938fad0a64608f22d39485bc55a1e0dc07246
[ "BSL-1.0" ]
null
null
null
sprout/type/algorithm.hpp
jwakely/Sprout
a64938fad0a64608f22d39485bc55a1e0dc07246
[ "BSL-1.0" ]
null
null
null
#ifndef SPROUT_TYPE_ALGORITHM_HPP #define SPROUT_TYPE_ALGORITHM_HPP #include <sprout/config.hpp> #include <sprout/type/algorithm/find_index.hpp> #endif // #ifndef SPROUT_TYPE_ALGORITHM_HPP
24.75
48
0.80303
osyo-manga
8a81783e43cfe2326d44e3a56d4a3a8e9b13f88a
436
hpp
C++
Internal/Vulkan/DescriptorsAllocator.hpp
artamonovoleg/EternityGraphic
0702cca3cca64d3af06afe7bfa5cb1464d04da8f
[ "MIT" ]
null
null
null
Internal/Vulkan/DescriptorsAllocator.hpp
artamonovoleg/EternityGraphic
0702cca3cca64d3af06afe7bfa5cb1464d04da8f
[ "MIT" ]
null
null
null
Internal/Vulkan/DescriptorsAllocator.hpp
artamonovoleg/EternityGraphic
0702cca3cca64d3af06afe7bfa5cb1464d04da8f
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include <vulkan/vulkan.hpp> #include <DescriptorsAllocator.h> namespace Eternity { class DescriptorsAllocator { private: std::unique_ptr<vke::DescriptorAllocatorPool> mDescriptorPool; public: void Init(uint32_t framesNum); void Shutdown(); void Allocate(const vk::DescriptorSetLayout& layout, vk::DescriptorSet& set) const; void Flip(); }; }
21.8
91
0.674312
artamonovoleg
8a81a8e144950f4b3c94fec4c916e191b983e661
907
hpp
C++
include/unet/wire/ethernet.hpp
andreimaximov/unet
10b6aa82b1ce74fa40c9050f4593c902f9d0fd61
[ "MIT" ]
null
null
null
include/unet/wire/ethernet.hpp
andreimaximov/unet
10b6aa82b1ce74fa40c9050f4593c902f9d0fd61
[ "MIT" ]
null
null
null
include/unet/wire/ethernet.hpp
andreimaximov/unet
10b6aa82b1ce74fa40c9050f4593c902f9d0fd61
[ "MIT" ]
null
null
null
#pragma once #include <cstdint> #include <ostream> #include <unet/wire/wire.hpp> namespace unet { struct UNET_PACK EthernetAddr { struct MemcmpTag {}; std::uint8_t addr[6]; }; UNET_ASSERT_SIZE(EthernetAddr, 6); std::ostream& operator<<(std::ostream& os, EthernetAddr ethAddr); struct UNET_PACK EthernetHeader { struct MemcmpTag {}; EthernetAddr dstAddr; EthernetAddr srcAddr; std::uint16_t ethType; }; UNET_ASSERT_SIZE(EthernetHeader, 14); constexpr EthernetAddr kEthernetBcastAddr{{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}}; // EtherType constants: https://en.wikipedia.org/wiki/EtherType namespace eth_type { static const std::uint16_t kIpv4 = hostToNet<std::uint16_t>(0x0800); static const std::uint16_t kArp = hostToNet<std::uint16_t>(0x0806); } // namespace eth_type } // namespace unet UNET_STD_HASH_AS_MEM_HASH(unet::EthernetAddr) UNET_STD_HASH_AS_MEM_HASH(unet::EthernetHeader)
22.675
80
0.759647
andreimaximov
8a84ae7e2fd4993fd455b4d55f1f18c5258259e7
1,444
cpp
C++
tests/gtests/internals/test_bfloat16.cpp
NomotoKazuhiro/oneDNN
18795301d6776bc1431ec808cba7bdf83d191bf8
[ "Apache-2.0" ]
13
2020-05-29T07:39:23.000Z
2021-11-22T14:01:28.000Z
tests/gtests/internals/test_bfloat16.cpp
NomotoKazuhiro/oneDNN
18795301d6776bc1431ec808cba7bdf83d191bf8
[ "Apache-2.0" ]
8
2020-09-04T02:05:19.000Z
2021-12-24T02:18:37.000Z
tests/gtests/internals/test_bfloat16.cpp
NomotoKazuhiro/oneDNN
18795301d6776bc1431ec808cba7bdf83d191bf8
[ "Apache-2.0" ]
24
2020-08-07T04:21:48.000Z
2021-12-09T02:03:35.000Z
/******************************************************************************* * Copyright 2020 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "dnnl_test_common.hpp" #include "gtest/gtest.h" #include "src/common/bfloat16.hpp" namespace dnnl { TEST(test_bfloat16_plus_float, TestDenormF32) { const float denorm_f32 {FLT_MIN / 2.0f}; const bfloat16_t initial_value_bf16 {FLT_MIN}; bfloat16_t expect_bf16 {float {initial_value_bf16} + denorm_f32}; ASSERT_GT(float {expect_bf16}, float {initial_value_bf16}); bfloat16_t bf16_plus_equal_f32 = initial_value_bf16; bf16_plus_equal_f32 += denorm_f32; ASSERT_EQ(float {bf16_plus_equal_f32}, float {expect_bf16}); bfloat16_t bf16_plus_f32 = initial_value_bf16 + denorm_f32; ASSERT_EQ(float {bf16_plus_f32}, float {expect_bf16}); } } // namespace dnnl
36.1
80
0.674515
NomotoKazuhiro
8a850c5a3cb8d7b820dca0a6f73f7197c0687f55
306
hpp
C++
tests/future/future_full.hpp
olegpublicprofile/stdfwd
19671bcc8e53bd4c008f07656eaf25a22495e093
[ "MIT" ]
11
2021-03-15T07:06:21.000Z
2021-09-27T13:54:25.000Z
tests/future/future_full.hpp
olegpublicprofile/stdfwd
19671bcc8e53bd4c008f07656eaf25a22495e093
[ "MIT" ]
null
null
null
tests/future/future_full.hpp
olegpublicprofile/stdfwd
19671bcc8e53bd4c008f07656eaf25a22495e093
[ "MIT" ]
1
2021-06-24T10:46:46.000Z
2021-06-24T10:46:46.000Z
#pragma once //------------------------------------------------------------------------------ namespace future_tests { //------------------------------------------------------------------------------ void run_full(); //------------------------------------------------------------------------------ }
21.857143
80
0.140523
olegpublicprofile
8a85dc0a072208ef6f64954f0e6788b7cf962b06
524
cpp
C++
src/cmd/kits/tpcc/templates.cpp
lslersch/zero
ab779235f3c3bf58d6a3aa9d2a0a5296578ee498
[ "Spencer-94" ]
27
2015-04-21T08:52:37.000Z
2022-03-18T03:38:58.000Z
src/cmd/kits/tpcc/templates.cpp
lslersch/zero
ab779235f3c3bf58d6a3aa9d2a0a5296578ee498
[ "Spencer-94" ]
24
2015-07-04T10:45:41.000Z
2018-05-03T08:52:36.000Z
src/cmd/kits/tpcc/templates.cpp
lslersch/zero
ab779235f3c3bf58d6a3aa9d2a0a5296578ee498
[ "Spencer-94" ]
15
2015-03-31T09:57:10.000Z
2021-06-09T13:44:58.000Z
#include "tpcc_schema.h" #include "sort.h" #include "table_man.cpp" template class table_man_t<tpcc::customer_t>; template class table_man_t<tpcc::district_t>; template class table_man_t<tpcc::history_t>; template class table_man_t<tpcc::item_t>; template class table_man_t<tpcc::new_order_t>; template class table_man_t<tpcc::order_line_t>; template class table_man_t<tpcc::order_t>; template class table_man_t<tpcc::stock_t>; template class table_man_t<tpcc::warehouse_t>; template class table_man_t<asc_sort_buffer_t>;
32.75
47
0.812977
lslersch
8a8f2b624ce6a94fbed1149ecfe5a72603f0c3ff
5,092
cpp
C++
src/Reflines.cpp
data-bridge/build
1bd37f7061d9bd5caf0c1bd9c5cbbd85c7a45486
[ "BSD-2-Clause", "Apache-2.0" ]
null
null
null
src/Reflines.cpp
data-bridge/build
1bd37f7061d9bd5caf0c1bd9c5cbbd85c7a45486
[ "BSD-2-Clause", "Apache-2.0" ]
null
null
null
src/Reflines.cpp
data-bridge/build
1bd37f7061d9bd5caf0c1bd9c5cbbd85c7a45486
[ "BSD-2-Clause", "Apache-2.0" ]
null
null
null
/* Part of BridgeData. Copyright (C) 2016-17 by Soren Hein. See LICENSE and README. */ #include <iostream> #include <fstream> #include <sstream> #include <regex> #include "RefLines.h" #include "Buffer.h" #include "parse.h" #include "Bexcept.h" RefLines::RefLines() { RefLines::reset(); } RefLines::~RefLines() { } void RefLines::reset() { lines.clear(); bufferLines = 0; numHands = 0; numBoards = 0; control = ERR_REF_STANDARD; headerComment.reset(); } void RefLines::setFileData( const unsigned bufIn, const unsigned numHandsIn, const unsigned numBoardsIn) { bufferLines = bufIn; numHands = numHandsIn; numBoards = numBoardsIn; } bool RefLines::parseComment( const string& fname, string& line) { string s; if (! getNextWord(line, s)) return false; if (s == "skip") control = ERR_REF_SKIP; else if (s == "noval") control = ERR_REF_NOVAL; else if (s == "orderCOCO") control = ERR_REF_OUT_COCO; else if (s == "orderOOCC") control = ERR_REF_OUT_OOCC; else return false; unsigned end; headerComment.parse(fname, line, 0, end); return true; } void RefLines::read(const string& fname) { regex re("\\.\\w+$"); string refName = regex_replace(fname, re, string(".ref")); control = ERR_REF_STANDARD; // There might not be a .ref file (not an error). ifstream refstr(refName.c_str()); if (! refstr.is_open()) return; string line; while (getline(refstr, line)) { if (line.empty() || line.at(0) == '%') continue; RefLine refLine; if (refLine.parse(fname, line)) lines.push_back(refLine); else if (! RefLines::parseComment(fname, line)) THROW("Ref file " + refName + ": Bad line in '" + line + "'"); } refstr.close(); } bool RefLines::hasComments() const { return (lines.size() > 0 || headerComment.isCommented()); } bool RefLines::skip() const { return (control == ERR_REF_SKIP); } bool RefLines::validate() const { return (control != ERR_REF_NOVAL); } void RefLines::setOrder(const BoardOrder order) { if (order == ORDER_OCOC) control = ERR_REF_STANDARD; else if (order == ORDER_COCO) control = ERR_REF_OUT_COCO; else if (order == ORDER_OOCC) control = ERR_REF_OUT_OOCC; else THROW("Unexpected input order: " + STR(order)); } bool RefLines::orderCOCO() const { return (control == ERR_REF_OUT_COCO); } bool RefLines::orderOOCC() const { return (control == ERR_REF_OUT_OOCC); } BoardOrder RefLines::order() const { if (control == ERR_REF_STANDARD) return ORDER_OCOC; else if (control == ERR_REF_OUT_COCO) return ORDER_COCO; else if (control == ERR_REF_OUT_OOCC) return ORDER_OOCC; else return ORDER_GENERAL; } bool RefLines::getHeaderEntry( CommentType& cat, RefEntry& re) const { if (bufferLines == 0) return false; if (headerComment.isCommented()) { headerComment.getEntry(cat, re); // Fix the order. re.count.lines = re.count.units; re.count.units = 0; re.noRefLines = 1; if (cat == ERR_SIZE) cat = static_cast<CommentType>(0); } else { // Synthesize a mini-header. cat = static_cast<CommentType>(0); re.files = 1; re.noRefLines = lines.size(); re.count.lines = bufferLines; re.count.units = 0; re.count.hands = numHands; re.count.boards = numBoards; } return true; } void RefLines::getHeaderData( unsigned& nl, unsigned& nh, unsigned& nb) const { nl = bufferLines; nh = numHands; nb = numBoards; } bool RefLines::getControlEntry( CommentType& cat, RefEntry& re) const { if (control == ERR_REF_STANDARD) return false; headerComment.getEntry(cat, re); re.count.lines = 1; return true; } void RefLines::checkEntries( const RefEntry& re, const RefEntry& ractual) const { if (re.count.units == ractual.count.units && re.count.hands == ractual.count.hands && re.count.boards == ractual.count.boards) return; THROW( headerComment.refFile() + ": (" + STR(re.count.units) + "," + STR(re.count.hands) + "," + STR(re.count.boards) + ") vs (" + STR(ractual.count.units) + "," + STR(ractual.count.hands) + "," + STR(ractual.count.boards) + ")"); } void RefLines::checkHeader() const { RefEntry ra, re; ra.count.units = bufferLines; ra.count.hands = numHands; ra.count.boards = numBoards; if (headerComment.isCommented()) { // noval and order. CommentType cat; headerComment.getEntry(cat, re); RefLines::checkEntries(re, ra); } // In some cases (e.g. rs), the changes to a given tag have to // add up the global number. map<string, vector<RefEntry>> cumulCount; for (auto &rl: lines) rl.checkHeader(ra, cumulCount); RefEntry rsum; for (auto &p: cumulCount) { rsum.count.units = 0; rsum.count.hands = 0; rsum.count.boards = 0; for (auto &q: p.second) { rsum.count.hands += q.count.hands; rsum.count.boards += q.count.boards; } rsum.count.units = bufferLines; RefLines::checkEntries(rsum, ra); } }
18.185714
68
0.639631
data-bridge
8a922fb0cda6605a0faa3442d065cd28158375e5
2,495
cpp
C++
src/BinaryLogger.cpp
TalexDreamSoul/Sharpen
9167c4080438a1f150232d733c4da878639d6f66
[ "MIT" ]
null
null
null
src/BinaryLogger.cpp
TalexDreamSoul/Sharpen
9167c4080438a1f150232d733c4da878639d6f66
[ "MIT" ]
null
null
null
src/BinaryLogger.cpp
TalexDreamSoul/Sharpen
9167c4080438a1f150232d733c4da878639d6f66
[ "MIT" ]
null
null
null
#include <sharpen/BinaryLogger.hpp> #include <sharpen/FileOps.hpp> #include <sharpen/Varint.hpp> #include <sharpen/IntOps.hpp> sharpen::BinaryLogger::BinaryLogger(const char *logName,sharpen::EventEngine &engine) :channel_(nullptr) ,logName_(logName) ,offset_(0) { this->channel_ = sharpen::MakeFileChannel(logName,sharpen::FileAccessModel::All,sharpen::FileOpenModel::CreateOrOpen); this->channel_->Register(engine); this->offset_ = this->channel_->GetFileSize(); } sharpen::BinaryLogger::~BinaryLogger() noexcept { if(this->channel_) { this->channel_->Close(); } } sharpen::BinaryLogger &sharpen::BinaryLogger::operator=(Self &&other) noexcept { if(this != std::addressof(other)) { this->channel_ = std::move(other.channel_); this->logName_ = std::move(other.logName_); this->offset_ = other.offset_; other.offset_ = 0; } return *this; } void sharpen::BinaryLogger::Remove() { this->channel_->Close(); sharpen::RemoveFile(this->logName_.c_str()); } void sharpen::BinaryLogger::Clear() { this->channel_->Truncate(); } void sharpen::BinaryLogger::Log(const sharpen::WriteBatch &batch) { sharpen::ByteBuffer buf; batch.StoreTo(buf); sharpen::Uint64 size{buf.GetSize()}; try { this->channel_->WriteAsync(reinterpret_cast<const char*>(&size),sizeof(size),this->offset_); this->channel_->WriteAsync(buf,this->offset_ + sizeof(size)); this->offset_ += buf.GetSize() + sizeof(size); } catch(const std::exception&) { this->channel_->Truncate(this->offset_); throw; } } std::list<sharpen::WriteBatch> sharpen::BinaryLogger::GetWriteBatchs() { std::list<sharpen::WriteBatch> batchs; sharpen::Uint64 offset{0}; sharpen::ByteBuffer buf; while (offset != this->offset_) { sharpen::WriteBatch batch; sharpen::Uint64 size{0}; this->channel_->ReadAsync(reinterpret_cast<char*>(&size),sizeof(size),offset); buf.ExtendTo(sharpen::IntCast<sharpen::Size>(size)); try { this->channel_->ReadAsync(buf,offset + sizeof(size)); batch.LoadFrom(buf); offset += size + sizeof(size); } catch(const std::exception&) { this->channel_->Truncate(offset); this->offset_ = offset; throw; } batchs.emplace_back(std::move(batch)); } return batchs; }
27.119565
122
0.627655
TalexDreamSoul
8a9735ec1e98e7bbb007bf3e601dbf4c598e7bf7
1,372
hpp
C++
wfc/core/wfcglobal.hpp
mambaru/wfc
170bf87302487c0cedc40b47c84447a765894774
[ "MIT" ]
1
2018-10-18T10:15:53.000Z
2018-10-18T10:15:53.000Z
wfc/core/wfcglobal.hpp
mambaru/wfc
170bf87302487c0cedc40b47c84447a765894774
[ "MIT" ]
7
2019-12-04T23:36:03.000Z
2021-04-21T12:37:07.000Z
wfc/core/wfcglobal.hpp
mambaru/wfc
170bf87302487c0cedc40b47c84447a765894774
[ "MIT" ]
null
null
null
// // Author: Vladimir Migashko <[email protected]>, (C) 2013-2015 // // Copyright: See COPYING file that comes with this distribution // #pragma once #include <wfc/core/object_registry.hpp> #include <wfc/core/fire_list.hpp> #include <wfc/core/extended_args.hpp> #include <wfc/core/ibuild_info.hpp> #include <wfc/core/workflow.hpp> #include <wfc/core/cpuset.hpp> #include <wfc/asio.hpp> #include <atomic> namespace wfc{ struct wfcglobal { typedef std::shared_ptr<wfcglobal> ptr; typedef std::function<bool()> fire_handler; typedef fire_list< fire_handler > fakir; typedef boost::asio::io_context io_context_type; typedef std::function<void(const std::string&)> callback_handler_t; std::string program_name; std::string instance_name; std::shared_ptr<ibuild_info> program_build_info; std::shared_ptr<ibuild_info> wfc_build_info; extended_args args; fakir idle; fakir after_start; fakir before_stop; fakir after_stop; std::atomic_bool disable_statistics; callback_handler_t nocall_handler; callback_handler_t doublecall_handler; cpuset cpu; object_registry registry; io_context_type& io_context; std::shared_ptr< wflow::workflow > common_workflow; static ptr static_global; std::atomic_bool stop_signal_flag; explicit wfcglobal( io_context_type& io_context); virtual ~wfcglobal(); virtual void clear(); }; }
23.254237
69
0.760933
mambaru
8a98b494f158726ef5473f4de4bf57fc5c781b00
2,595
cpp
C++
2021/14/b.cpp
kidonm/advent-of-code
b304d99d60dcdd9d67105964f2c6a6d8729ecfd6
[ "Apache-2.0" ]
null
null
null
2021/14/b.cpp
kidonm/advent-of-code
b304d99d60dcdd9d67105964f2c6a6d8729ecfd6
[ "Apache-2.0" ]
null
null
null
2021/14/b.cpp
kidonm/advent-of-code
b304d99d60dcdd9d67105964f2c6a6d8729ecfd6
[ "Apache-2.0" ]
null
null
null
#include <algorithm> #include <iostream> #include <map> #include <queue> #include <set> #include <sstream> #include <string> #include <unordered_map> #include <unordered_set> #include <vector> using namespace std; typedef unsigned long long ll; ll dfs(string &l, char targetChar, int d, int targetDepth, unordered_map<string, pair<char, vector<string>>> &rules, vector<unordered_map<string, ll>> &mem) { if (d == targetDepth) return 0; // printf("%s %d\n", l.c_str(), d); auto srch1 = mem[d].find(l); if (srch1 != mem[d].end()) { return srch1->second; } // printf("%d %s \n", d, l.c_str()); auto search = rules.find(l); ll ans = 0; if (search != rules.end()) { if (search->second.first == targetChar) ans++; ans += dfs(search->second.second[0], targetChar, d + 1, targetDepth, rules, mem); ans += dfs(search->second.second[1], targetChar, d + 1, targetDepth, rules, mem); }; mem[d].insert({l, ans}); return ans; }; int main() { string start; unordered_map<string, pair<char, vector<string>>> rules; unordered_map<char, ll> counts; vector<unordered_map<string, ll>> mem; int depth = 40; cin >> start; for (string s; getline(cin, s);) { if (s.empty()) continue; stringstream ss(s); string l = s.substr(0, 2); char r = (s.substr(6))[0]; string s1, s2; s1.push_back(l[0]); s1.push_back(r); s2.push_back(r); s2.push_back(l[1]); pair<char, vector<string>> pr = {r, vector<string>{s1, s2}}; rules.insert({l, pr}); } // for (auto r : rules) { // printf("%s -> %s\n", r.first.c_str(), r.second.c_str()); // } // printf("here\n"); for (int i = 0; i < depth; i++) { unordered_map<string, ll> tmp; mem.push_back(tmp); } for (char c = 'A'; c <= 'Z'; c++) { counts.insert({c, 0}); } for (char c : start) { counts[c]++; } for (char c = 'A'; c <= 'Z'; c++) { mem = vector<unordered_map<string, ll>>(depth, unordered_map<string, ll>()); ll count = 0; for (int i = 0; i < start.size() - 1; i++) { string begin = start.substr(i, 2); dfs(begin, c, 0, depth, rules, mem); count += mem[0][begin]; } counts[c] += count; // printf("%llu", count); } // ll mini = coun; // ll maxi = INT_MIN; for (auto count : counts) { if (count.second == 0) continue; printf("%c %llu\n", count.first, count.second); // mini = min(mini, count.second); // maxi = max(maxi, count.second); } // printf("%llu %llu", start.size(), maxi - mini); return 0; }
21.625
80
0.56185
kidonm
8a9bbc28b89a5dcb0015ec77efcf527e12bcbbff
11,998
cpp
C++
decode.cpp
Phlicess/wtNoe
01dc1bcd3325a90d1ad04775aa0ff41efa93aa77
[ "BSD-2-Clause" ]
null
null
null
decode.cpp
Phlicess/wtNoe
01dc1bcd3325a90d1ad04775aa0ff41efa93aa77
[ "BSD-2-Clause" ]
null
null
null
decode.cpp
Phlicess/wtNoe
01dc1bcd3325a90d1ad04775aa0ff41efa93aa77
[ "BSD-2-Clause" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sqlite3.h> #include <string> #include <vector> #include <map> #include <zlib.h> #include <math.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/mman.h> #include <protozero/pbf_reader.hpp> #include "mvt.hpp" #include "projection.hpp" #include "geometry.hpp" void printq(const char *s) { putchar('"'); for (; *s; s++) { if (*s == '\\' || *s == '"') { printf("\\%c", *s); } else if (*s >= 0 && *s < ' ') { printf("\\u%04x", *s); } else { putchar(*s); } } putchar('"'); } struct lonlat { int op; double lon; double lat; int x; int y; lonlat(int nop, double nlon, double nlat, int nx, int ny) { this->op = nop; this->lon = nlon; this->lat = nlat; this->x = nx; this->y = ny; } }; void handle(std::string message, int z, unsigned x, unsigned y, int describe) { int within = 0; mvt_tile tile; try { if (!tile.decode(message)) { fprintf(stderr, "Couldn't parse tile %d/%u/%u\n", z, x, y); exit(EXIT_FAILURE); } } catch (protozero::unknown_pbf_wire_type_exception e) { fprintf(stderr, "PBF decoding error in tile %d/%u/%u\n", z, x, y); exit(EXIT_FAILURE); } printf("{ \"type\": \"FeatureCollection\""); if (describe) { printf(", \"properties\": { \"zoom\": %d, \"x\": %d, \"y\": %d }", z, x, y); if (projection != projections) { printf(", \"crs\": { \"type\": \"name\", \"properties\": { \"name\": "); printq(projection->alias); printf(" } }"); } } printf(", \"features\": [\n"); for (size_t l = 0; l < tile.layers.size(); l++) { mvt_layer &layer = tile.layers[l]; int extent = layer.extent; if (describe) { if (l != 0) { printf(",\n"); } printf("{ \"type\": \"FeatureCollection\""); printf(", \"properties\": { \"layer\": "); printq(layer.name.c_str()); printf(", \"version\": %d, \"extent\": %d", layer.version, layer.extent); printf(" }"); printf(", \"features\": [\n"); within = 0; } for (size_t f = 0; f < layer.features.size(); f++) { mvt_feature &feat = layer.features[f]; if (within) { printf(",\n"); } within = 1; printf("{ \"type\": \"Feature\""); if (feat.has_id) { printf(", \"id\": %llu", feat.id); } printf(", \"properties\": { "); for (size_t t = 0; t + 1 < feat.tags.size(); t += 2) { if (t != 0) { printf(", "); } if (feat.tags[t] >= layer.keys.size()) { fprintf(stderr, "Error: out of bounds feature key\n"); exit(EXIT_FAILURE); } if (feat.tags[t + 1] >= layer.values.size()) { fprintf(stderr, "Error: out of bounds feature value\n"); exit(EXIT_FAILURE); } const char *key = layer.keys[feat.tags[t]].c_str(); mvt_value const &val = layer.values[feat.tags[t + 1]]; if (val.type == mvt_string) { printq(key); printf(": "); printq(val.string_value.c_str()); } else if (val.type == mvt_int) { printq(key); printf(": %lld", (long long) val.numeric_value.int_value); } else if (val.type == mvt_double) { printq(key); double v = val.numeric_value.double_value; if (v == (long long) v) { printf(": %lld", (long long) v); } else { printf(": %g", v); } } else if (val.type == mvt_float) { printq(key); double v = val.numeric_value.float_value; if (v == (long long) v) { printf(": %lld", (long long) v); } else { printf(": %g", v); } } else if (val.type == mvt_sint) { printq(key); printf(": %lld", (long long) val.numeric_value.sint_value); } else if (val.type == mvt_uint) { printq(key); printf(": %lld", (long long) val.numeric_value.uint_value); } else if (val.type == mvt_bool) { printq(key); printf(": %s", val.numeric_value.bool_value ? "true" : "false"); } } printf(" }, \"geometry\": { "); std::vector<lonlat> ops; for (size_t g = 0; g < feat.geometry.size(); g++) { int op = feat.geometry[g].op; long long px = feat.geometry[g].x; long long py = feat.geometry[g].y; if (op == VT_MOVETO || op == VT_LINETO) { long long scale = 1LL << (32 - z); long long wx = scale * x + (scale / extent) * px; long long wy = scale * y + (scale / extent) * py; double lat, lon; projection->unproject(wx, wy, 32, &lon, &lat); ops.push_back(lonlat(op, lon, lat, px, py)); } else { ops.push_back(lonlat(op, 0, 0, 0, 0)); } } if (feat.type == VT_POINT) { if (ops.size() == 1) { printf("\"type\": \"Point\", \"coordinates\": [ %f, %f ]", ops[0].lon, ops[0].lat); } else { printf("\"type\": \"MultiPoint\", \"coordinates\": [ "); for (size_t i = 0; i < ops.size(); i++) { if (i != 0) { printf(", "); } printf("[ %f, %f ]", ops[i].lon, ops[i].lat); } printf(" ]"); } } else if (feat.type == VT_LINE) { int movetos = 0; for (size_t i = 0; i < ops.size(); i++) { if (ops[i].op == VT_MOVETO) { movetos++; } } if (movetos < 2) { printf("\"type\": \"LineString\", \"coordinates\": [ "); for (size_t i = 0; i < ops.size(); i++) { if (i != 0) { printf(", "); } printf("[ %f, %f ]", ops[i].lon, ops[i].lat); } printf(" ]"); } else { printf("\"type\": \"MultiLineString\", \"coordinates\": [ [ "); int state = 0; for (size_t i = 0; i < ops.size(); i++) { if (ops[i].op == VT_MOVETO) { if (state == 0) { printf("[ %f, %f ]", ops[i].lon, ops[i].lat); state = 1; } else { printf(" ], [ "); printf("[ %f, %f ]", ops[i].lon, ops[i].lat); state = 1; } } else { printf(", [ %f, %f ]", ops[i].lon, ops[i].lat); } } printf(" ] ]"); } } else if (feat.type == VT_POLYGON) { std::vector<std::vector<lonlat> > rings; std::vector<double> areas; for (size_t i = 0; i < ops.size(); i++) { if (ops[i].op == VT_MOVETO) { rings.push_back(std::vector<lonlat>()); areas.push_back(0); } int n = rings.size() - 1; if (n >= 0) { if (ops[i].op == VT_CLOSEPATH) { rings[n].push_back(rings[n][0]); } else { rings[n].push_back(ops[i]); } } } int outer = 0; for (size_t i = 0; i < rings.size(); i++) { long double area = 0; for (size_t k = 0; k < rings[i].size(); k++) { if (rings[i][k].op != VT_CLOSEPATH) { area += rings[i][k].x * rings[i][(k + 1) % rings[i].size()].y; area -= rings[i][k].y * rings[i][(k + 1) % rings[i].size()].x; } } areas[i] = area; if (areas[i] >= 0 || i == 0) { outer++; } // printf("area %f\n", area / .00000274 / .00000274); } if (outer > 1) { printf("\"type\": \"MultiPolygon\", \"coordinates\": [ [ [ "); } else { printf("\"type\": \"Polygon\", \"coordinates\": [ [ "); } int state = 0; for (size_t i = 0; i < rings.size(); i++) { if (areas[i] >= 0) { if (state != 0) { // new multipolygon printf(" ] ], [ [ "); } state = 1; } if (state == 2) { // new ring in the same polygon printf(" ], [ "); } for (size_t j = 0; j < rings[i].size(); j++) { if (rings[i][j].op != VT_CLOSEPATH) { if (j != 0) { printf(", "); } printf("[ %f, %f ]", rings[i][j].lon, rings[i][j].lat); } else { if (j != 0) { printf(", "); } printf("[ %f, %f ]", rings[i][0].lon, rings[i][0].lat); } } state = 2; } if (outer > 1) { printf(" ] ] ]"); } else { printf(" ] ]"); } } printf(" } }\n"); } if (describe) { printf("] }\n"); } } printf("] }\n"); } void decode(char *fname, int z, unsigned x, unsigned y) { sqlite3 *db; int oz = z; unsigned ox = x, oy = y; int fd = open(fname, O_RDONLY); if (fd >= 0) { struct stat st; if (fstat(fd, &st) == 0) { if (st.st_size < 50 * 1024 * 1024) { char *map = (char *) mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0); if (map != NULL && map != MAP_FAILED) { if (strcmp(map, "SQLite format 3") != 0) { if (z >= 0) { std::string s = std::string(map, st.st_size); handle(s, z, x, y, 1); munmap(map, st.st_size); return; } else { fprintf(stderr, "Must specify zoom/x/y to decode a single pbf file\n"); exit(EXIT_FAILURE); } } } munmap(map, st.st_size); } } else { perror("fstat"); } close(fd); } else { perror(fname); } if (sqlite3_open(fname, &db) != SQLITE_OK) { fprintf(stderr, "%s: %s\n", fname, sqlite3_errmsg(db)); exit(EXIT_FAILURE); } if (z < 0) { printf("{ \"type\": \"FeatureCollection\", \"properties\": {\n"); const char *sql2 = "SELECT name, value from metadata order by name;"; sqlite3_stmt *stmt2; if (sqlite3_prepare_v2(db, sql2, -1, &stmt2, NULL) != SQLITE_OK) { fprintf(stderr, "%s: select failed: %s\n", fname, sqlite3_errmsg(db)); exit(EXIT_FAILURE); } int within = 0; while (sqlite3_step(stmt2) == SQLITE_ROW) { if (within) { printf(",\n"); } within = 1; const unsigned char *name = sqlite3_column_text(stmt2, 0); const unsigned char *value = sqlite3_column_text(stmt2, 1); printq((char *) name); printf(": "); printq((char *) value); } sqlite3_finalize(stmt2); const char *sql = "SELECT tile_data, zoom_level, tile_column, tile_row from tiles order by zoom_level, tile_column, tile_row;"; sqlite3_stmt *stmt; if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) { fprintf(stderr, "%s: select failed: %s\n", fname, sqlite3_errmsg(db)); exit(EXIT_FAILURE); } printf("\n}, \"features\": [\n"); within = 0; while (sqlite3_step(stmt) == SQLITE_ROW) { if (within) { printf(",\n"); } within = 1; int len = sqlite3_column_bytes(stmt, 0); int tz = sqlite3_column_int(stmt, 1); int tx = sqlite3_column_int(stmt, 2); int ty = sqlite3_column_int(stmt, 3); ty = (1LL << tz) - 1 - ty; const char *s = (const char *) sqlite3_column_blob(stmt, 0); handle(std::string(s, len), tz, tx, ty, 1); } printf("] }\n"); sqlite3_finalize(stmt); } else { int handled = 0; while (z >= 0 && !handled) { const char *sql = "SELECT tile_data from tiles where zoom_level = ? and tile_column = ? and tile_row = ?;"; sqlite3_stmt *stmt; if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) { fprintf(stderr, "%s: select failed: %s\n", fname, sqlite3_errmsg(db)); exit(EXIT_FAILURE); } sqlite3_bind_int(stmt, 1, z); sqlite3_bind_int(stmt, 2, x); sqlite3_bind_int(stmt, 3, (1LL << z) - 1 - y); while (sqlite3_step(stmt) == SQLITE_ROW) { int len = sqlite3_column_bytes(stmt, 0); const char *s = (const char *) sqlite3_column_blob(stmt, 0); if (z != oz) { fprintf(stderr, "%s: Warning: using tile %d/%u/%u instead of %d/%u/%u\n", fname, z, x, y, oz, ox, oy); } handle(std::string(s, len), z, x, y, 0); handled = 1; } sqlite3_finalize(stmt); z--; x /= 2; y /= 2; } } if (sqlite3_close(db) != SQLITE_OK) { fprintf(stderr, "%s: could not close database: %s\n", fname, sqlite3_errmsg(db)); exit(EXIT_FAILURE); } } void usage(char **argv) { fprintf(stderr, "Usage: %s [-t projection] file.mbtiles zoom x y\n", argv[0]); exit(EXIT_FAILURE); } int main(int argc, char **argv) { extern int optind; extern char *optarg; int i; while ((i = getopt(argc, argv, "t:")) != -1) { switch (i) { case 't': set_projection_or_exit(optarg); break; default: usage(argv); } } if (argc == optind + 4) { decode(argv[optind], atoi(argv[optind + 1]), atoi(argv[optind + 2]), atoi(argv[optind + 3])); } else if (argc == optind + 1) { decode(argv[optind], -1, -1, -1); } else { usage(argv); } return 0; }
24.044088
129
0.520253
Phlicess
8a9d818b6e36183fd424976b6107bf4d97fcfd0e
1,741
cpp
C++
3/3.21.cpp
tjzhym/CPP-Primer
04eab308e990cc4cf2dbf1e7a7035bff825f29dc
[ "MIT" ]
null
null
null
3/3.21.cpp
tjzhym/CPP-Primer
04eab308e990cc4cf2dbf1e7a7035bff825f29dc
[ "MIT" ]
null
null
null
3/3.21.cpp
tjzhym/CPP-Primer
04eab308e990cc4cf2dbf1e7a7035bff825f29dc
[ "MIT" ]
null
null
null
// 3.21.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> #include <vector> using namespace std; void printVector (vector<int> v) { cout << "The size of the vector is: " << endl; cout << v.size() << endl; cout << "The contents of the vector are: " << endl; for (auto it = v.begin(); it != v.end(); ++it) { cout << *it << ' '; } cout << endl << endl; } void printVector(vector<string> v) { cout << "The size of the vector is: " << endl; cout << v.size() << endl; cout << "The contents of the vector are: " << endl; for (auto it = v.begin(); it != v.end(); ++it) { cout << *it << ' '; } cout << endl << endl; } int main() { vector<int> v1; vector<int> v2(10); vector<int> v3(10, 42); vector<int> v4{ 10 }; vector<int> v5{ 10, 42 }; vector<string> v6{ 10 }; vector<string> v7{ 10, "hi" }; printVector(v1); printVector(v2); printVector(v3); printVector(v4); printVector(v5); printVector(v6); printVector(v7); return 0; } // Run program: Ctrl + F5 or Debug > Start Without Debugging menu // Debug program: F5 or Debug > Start Debugging menu // Tips for Getting Started: // 1. Use the Solution Explorer window to add/manage files // 2. Use the Team Explorer window to connect to source control // 3. Use the Output window to see build output and other messages // 4. Use the Error List window to view errors // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
30.54386
135
0.611143
tjzhym
8a9ecb8b49a8b1cfe66f665236173800d7ef7406
1,115
cpp
C++
learncpp.com/04_Fundamental_Data_Types/Question03/src/Main.cpp
KoaLaYT/Learn-Cpp
0bfc98c3eca9c2fde5bff609c67d7e273fde5196
[ "MIT" ]
null
null
null
learncpp.com/04_Fundamental_Data_Types/Question03/src/Main.cpp
KoaLaYT/Learn-Cpp
0bfc98c3eca9c2fde5bff609c67d7e273fde5196
[ "MIT" ]
null
null
null
learncpp.com/04_Fundamental_Data_Types/Question03/src/Main.cpp
KoaLaYT/Learn-Cpp
0bfc98c3eca9c2fde5bff609c67d7e273fde5196
[ "MIT" ]
null
null
null
/** * Chapter 4 :: Question 3 * * prompt user to input two floating number, * and the operation, then caculate the result. * * CAUTION: no error handling * * KoaLaYT 00:41 30/01/2020 * */ #include <iostream> double read_number() { std::cout << "Enter a double value: "; double input{}; std::cin >> input; return input; } char read_operator() { std::cout << "Enter one of the following: +, -, *, or /: "; char op{}; std::cin >> op; return op; } bool check_validation(char op) { return op == '+' || op == '-' || op == '*' || op == '/'; } double calculate(char op, double fst, double snd) { switch (op) { case '+': return fst + snd; case '-': return fst - snd; case '*': return fst * snd; case '/': return fst / snd; default: throw "Unknown operator"; } } int main() { double fst{read_number()}; double snd{read_number()}; char op{read_operator()}; if (!check_validation(op)) { // unknown operator return 1; } double res = calculate(op, fst, snd); std::cout << fst << ' ' << op << ' ' << snd << " is " << res << '\n'; }
16.893939
71
0.556054
KoaLaYT
8aa0ff946a1a1f66febc0c2bde78611d95acd3d5
4,051
hpp
C++
src/Import3DS.hpp
moonwho101/DungeonStompDirectX11PixelShader
d3f044d2a56285f900d39bc0fa2c6eeda20ba8c1
[ "MIT" ]
null
null
null
src/Import3DS.hpp
moonwho101/DungeonStompDirectX11PixelShader
d3f044d2a56285f900d39bc0fa2c6eeda20ba8c1
[ "MIT" ]
null
null
null
src/Import3DS.hpp
moonwho101/DungeonStompDirectX11PixelShader
d3f044d2a56285f900d39bc0fa2c6eeda20ba8c1
[ "MIT" ]
null
null
null
#ifndef __IMPORT3DS_H #define __IMPORT3DS_H #include <stdio.h> #include <io.h> #include <fcntl.h> #include <windows.h> #include "world.hpp" #define MAX_NUM_3DS_TRIANGLES 10000 #define MAX_NUM_3DS_VERTICES 10000 #define MAX_NUM_3DS_FACES 10000 #define MAX_NAME_LENGTH 256 #define MAX_NUM_3DS_TEXTURES 200 //#define MAX_NUM_3DS_FRAMES 50 #define MAX_NUM_3DS_FRAMES 1 #define MAX_NUM_3DS_OBJECTS 10000 #define MAIN3DS 0x4D4D // level 1 #define M3DS_VERSION 0x0002 #define MESH_VERSION 0x3D3E #define EDIT3DS 0x3D3D // level 1 #define NAMED_OBJECT 0x4000 // level 2 #define TRIANGLE_MESH 0x4100 // level 3 #define TRIANGLE_VERTEXLIST 0x4110 // level 4 #define TRIANGLE_VERTEXOPTIONS 0x4111 // level 4 #define TRIANGLE_MAPPINGCOORS 0x4140 // level 4 #define TRIANGLE_MAPPINGSTANDARD 0x4170 // level 4 #define TRIANGLE_FACELIST 0x4120 // level 4 #define TRIANGLE_SMOOTH 0x4150 // level 5 #define TRIANGLE_MATERIAL 0x4130 // level 5 #define TRI_LOCAL 0x4160 // level 4 #define TRI_VISIBLE 0x4165 // level 4 #define INT_PERCENTAGE 0x0030 #define MASTER_SCALE 0x0100 #define EDIT_MATERIAL 0xAFFF // level 2 #define MAT_NAME01 0xA000 // level 3 #define TEXTURE_MAP 0xA200 // level 4? #define MAPPING_NAME 0xA300 // level 5? #define MATERIAL_AMBIENT 0xA010 #define MATERIAL_DIFFUSE 0xA020 #define MATERIAL_SPECULAR 0xA030 #define MATERIAL_SHININESS 0xA040 #define MATERIAL_SHIN_STRENGTH 0xA041 #define MAPPING_PARAMETERS 0xA351 #define BLUR_PERCENTAGE 0xA353 #define TRANS_PERCENT 0xA050 #define TRANS_FALLOFF_PERCENT 0xA052 #define REFLECTION_BLUR_PER 0xA053 #define RENDER_TYPE 0xA100 #define SELF_ILLUM 0xA084 #define WIRE_THICKNESS 0xA087 #define IN_TRANC 0xA08A #define SOFTEN 0xA08C #define KEYFRAME 0xB000 // level 1 #define KEYFRAME_MESH_INFO 0xB002 #define KEYFRAME_START_AND_END 0xB008 #define KEYFRAME_HEADER 0xb00a #define POS_TRACK_TAG 0xb020 #define ROT_TRACK_TAG 0xb021 #define SCL_TRACK_TAG 0xb022 #define FOV_TRACK_TAG 0xb023 #define ROLL_TRACK_TAG 0xb024 #define COL_TRACK_TAG 0xb025 #define MORPH_TRACK_TAG 0xb026 #define HOT_TRACK_TAG 0xb027 #define FALL_TRACK_TAG 0xb028 #define HIDE_TRACK_TAG 0xb029 #define PIVOT 0xb013 #define NODE_HDR 0xb010 #define NODE_ID 0xb030 #define KFCURTIME 0xb009 typedef struct { float x; float y; float z; } VERT3DS; typedef struct { short v[4]; int tex; } FACE3DS; typedef struct { float x; float y; } MAPPING_COORDINATES; typedef struct { VERT3DS verts[3]; MAPPING_COORDINATES texmapcoords[3]; short material; short tex_alias; char mat_name[MAX_NAME_LENGTH]; } TRIANGLE3DS; typedef struct { short framenum; long lunknown; float rotation_rad; float axis_x; float axis_y; float axis_z; } ROT_TRACK3DS; typedef struct { short framenum; long lunknown; float pos_x; float pos_y; float pos_z; } POS_TRACK3DS; typedef struct { short framenum; long lunknown; float scale_x; float scale_y; float scale_z; } SCL_TRACK3DS; typedef struct { int verts_start; int verts_end; short rotkeys; short poskeys; short sclkeys; VERT3DS pivot; ROT_TRACK3DS rot_track[MAX_NUM_3DS_FRAMES]; POS_TRACK3DS pos_track[MAX_NUM_3DS_FRAMES]; SCL_TRACK3DS scl_track[MAX_NUM_3DS_FRAMES]; float local_centre_x; float local_centre_y; float local_centre_z; } OBJECT3DS; BOOL Import3DS(char* filename, int pmodel_id, float scale); BOOL ProcessVertexData(FILE* fp); BOOL ProcessFaceData(FILE* fp); void ProcessTriLocalData(FILE* fp); void ProcessTriSmoothData(FILE* fp); void ProcessMappingData(FILE* fp); void ProcessMaterialData(FILE* fp, int pmodel_id); void AddMaterialName(FILE* fp); void AddMapName(FILE* fp, int pmodel_id); void ProcessPositionTrack(FILE* fp); void ProcessRotationTrack(FILE* fp); void ProcessPivots(FILE* fp); void ProcessScaleTrack(FILE* fp); void ProcessNodeHeader(FILE* fp); void ProcessNodeId(FILE* fp); void ProcessMasterScale(FILE* fp); void Process3DSVersion(FILE* fp); void PrintLogFile(FILE* logfile, char* commmand); void Write_pmdata_debugfile(int pmodel_id); void ReleaseTempMemory(); #endif //__IMPORT3DS_H
20.881443
59
0.793631
moonwho101
8aa743f717213070380398933b551ae8668c23c7
2,579
cpp
C++
PostView2/DlgSelectRange.cpp
febiosoftware/PostView
45c60aec1ae8832d0e6f6410e774aeaded2037c0
[ "MIT" ]
9
2020-03-22T08:27:03.000Z
2021-09-24T10:02:37.000Z
PostView2/DlgSelectRange.cpp
febiosoftware/PostView
45c60aec1ae8832d0e6f6410e774aeaded2037c0
[ "MIT" ]
1
2021-03-02T06:45:59.000Z
2021-03-02T06:45:59.000Z
PostView2/DlgSelectRange.cpp
febiosoftware/PostView
45c60aec1ae8832d0e6f6410e774aeaded2037c0
[ "MIT" ]
2
2020-06-27T13:59:49.000Z
2021-09-08T16:39:39.000Z
/*This file is part of the PostView source code and is licensed under the MIT license listed below. See Copyright-PostView.txt for details. Copyright (c) 2020 University of Utah, The Trustees of Columbia University in the City of New York, and others. 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 "stdafx.h" #include "DlgSelectRange.h" #include <QBoxLayout> #include <QFormLayout> #include <QCheckBox> #include <QDialogButtonBox> #include "CIntInput.h" class Ui::CDlgSelectRange { public: CFloatInput *pmin, *pmax; QCheckBox* prange; public: void setupUi(QDialog* parent) { QVBoxLayout* pv = new QVBoxLayout; QFormLayout* pform = new QFormLayout; pform->addRow("min:", pmin = new CFloatInput); pform->addRow("max:", pmax = new CFloatInput); pv->addLayout(pform); prange = new QCheckBox("Apply to current selection"); pv->addWidget(prange); QDialogButtonBox* pb = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); pv->addWidget(pb); parent->setLayout(pv); QObject::connect(pb, SIGNAL(accepted()), parent, SLOT(accept())); QObject::connect(pb, SIGNAL(rejected()), parent, SLOT(reject())); } }; CDlgSelectRange::CDlgSelectRange(QWidget* parent) : QDialog(parent), ui(new Ui::CDlgSelectRange) { ui->setupUi(this); ui->pmin->setValue(0); ui->pmax->setValue(0); } int CDlgSelectRange::exec() { ui->pmin->setValue(m_min); ui->pmax->setValue(m_max); return QDialog::exec(); } void CDlgSelectRange::accept() { m_min = ui->pmin->value(); m_max = ui->pmax->value(); m_brange = ui->prange->isChecked(); QDialog::accept(); }
29.306818
96
0.749128
febiosoftware
8aae2b18b65f77d4801d7e2d1bd66b101205708d
448
hh
C++
src/Zynga/Framework/Service/V2/Client/Mock/HasResponseBatchTest.hh
chintan-j-patel/zynga-hacklang-framework
d9893b8873e3c8c7223772fd3c94d2531760172a
[ "MIT" ]
19
2018-04-23T09:30:48.000Z
2022-03-06T21:35:18.000Z
src/Zynga/Framework/Service/V2/Client/Mock/HasResponseBatchTest.hh
chintan-j-patel/zynga-hacklang-framework
d9893b8873e3c8c7223772fd3c94d2531760172a
[ "MIT" ]
22
2017-11-27T23:39:25.000Z
2019-08-09T08:56:57.000Z
src/Zynga/Framework/Service/V2/Client/Mock/HasResponseBatchTest.hh
chintan-j-patel/zynga-hacklang-framework
d9893b8873e3c8c7223772fd3c94d2531760172a
[ "MIT" ]
28
2017-11-16T20:53:56.000Z
2021-01-04T11:13:17.000Z
<?hh //strict namespace Zynga\Framework\Service\V2\Client\Mock; use Zynga\Framework\Service\V2\Client\Mock\Batch as MockBatch; use Zynga\Framework\Service\V2\Client\Mock\HasResponseBatch as Batch; use Zynga\Framework\Testing\TestCase\V2\Base as TestCase; class HasResponseBatchTest extends TestCase { public function testIsBatchStarted(): void { $batch = new Batch(new MockBatch()); $this->assertFalse($batch->isBatchStarted()); } }
29.866667
69
0.767857
chintan-j-patel
8ab1b9b74dc3b56190a373ae7a5ef0b056252939
2,557
hpp
C++
blaise-lang/include/gasp/blaise/impl/blaise_ast_expression_utility.hpp
sanelli/gasp
108700e8739534e9c152d7c8e2f1308917cf8611
[ "MIT" ]
null
null
null
blaise-lang/include/gasp/blaise/impl/blaise_ast_expression_utility.hpp
sanelli/gasp
108700e8739534e9c152d7c8e2f1308917cf8611
[ "MIT" ]
null
null
null
blaise-lang/include/gasp/blaise/impl/blaise_ast_expression_utility.hpp
sanelli/gasp
108700e8739534e9c152d7c8e2f1308917cf8611
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include <gasp/blaise/impl/blaise_ast_expression.hpp> namespace gasp::blaise::ast { class blaise_ast_expression_utility { public: static std::shared_ptr<blaise_ast_expression_boolean_value> as_boolean_literal(std::shared_ptr<blaise_ast_expression> expression); static std::shared_ptr<blaise_ast_expression_string_value> as_string_literal(std::shared_ptr<blaise_ast_expression> expression); static std::shared_ptr<blaise_ast_expression_char_value> as_char_literal(std::shared_ptr<blaise_ast_expression> expression); static std::shared_ptr<blaise_ast_expression_double_value> as_double_literal(std::shared_ptr<blaise_ast_expression> expression); static std::shared_ptr<blaise_ast_expression_float_value> as_float_literal(std::shared_ptr<blaise_ast_expression> expression); static std::shared_ptr<blaise_ast_expression_byte_value> as_byte_literal(std::shared_ptr<blaise_ast_expression> expression); static std::shared_ptr<blaise_ast_expression_short_value> as_short_literal(std::shared_ptr<blaise_ast_expression> expression); static std::shared_ptr<blaise_ast_expression_integer_value> as_integer_literal(std::shared_ptr<blaise_ast_expression> expression); static std::shared_ptr<blaise_ast_expression_long_value> as_long_literal(std::shared_ptr<blaise_ast_expression> expression); static std::shared_ptr<blaise_ast_expression_generic_memory_access> as_memory_access(std::shared_ptr<blaise_ast_expression> expression); static std::shared_ptr<blaise_ast_expression_unary> as_unary(std::shared_ptr<blaise_ast_expression> expression); static std::shared_ptr<blaise_ast_expression_binary> as_binary(std::shared_ptr<blaise_ast_expression> expression); static std::shared_ptr<blaise_ast_expression_subroutine_call> as_subroutine_call(std::shared_ptr<blaise_ast_expression> expression); static std::shared_ptr<blaise_ast_expression_cast> as_cast(std::shared_ptr<blaise_ast_expression> expression); static std::shared_ptr<blaise_ast_expression_ternary> as_ternary(std::shared_ptr<blaise_ast_expression> expression); static std::shared_ptr<blaise_ast_expression_new> as_new(std::shared_ptr<blaise_ast_expression> expression); static std::shared_ptr<blaise_ast_expression_memory_access> as_variable_memory_access(std::shared_ptr<blaise_ast_expression_generic_memory_access> expression); static std::shared_ptr<blaise_ast_expression_array_access> as_array_memory_access(std::shared_ptr<blaise_ast_expression_generic_memory_access> expression); }; } // namespace gasp::blaise::ast
73.057143
162
0.853344
sanelli
8ab64d8589a058c91ce21452fe86f3ead7b9a00f
9,574
cpp
C++
XInput/RumbleController/RumbleController.cpp
zzgchina888/directx_sdk_sample
1982d2323be0e44fc060515cd712f42cfdb38339
[ "MIT" ]
1
2021-04-29T15:44:11.000Z
2021-04-29T15:44:11.000Z
XInput/RumbleController/RumbleController.cpp
zzgchina888/directx_sdk_sample
1982d2323be0e44fc060515cd712f42cfdb38339
[ "MIT" ]
null
null
null
XInput/RumbleController/RumbleController.cpp
zzgchina888/directx_sdk_sample
1982d2323be0e44fc060515cd712f42cfdb38339
[ "MIT" ]
1
2021-08-03T02:40:50.000Z
2021-08-03T02:40:50.000Z
//----------------------------------------------------------------------------- // File: RumbleController.cpp // // Simple use of XInput rumble force-feedback // // Note: This sample works with all versions of XInput (1.4, 1.3, and 9.1.0) // // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <stdio.h> #include <commdlg.h> #include <basetsd.h> #include <objbase.h> #ifdef USE_DIRECTX_SDK #include <C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\include\xinput.h> #pragma comment(lib,"xinput.lib") #elif (_WIN32_WINNT >= 0x0602 /*_WIN32_WINNT_WIN8*/) #include <XInput.h> #pragma comment(lib,"xinput.lib") #else #include <XInput.h> #pragma comment(lib,"xinput9_1_0.lib") #endif //----------------------------------------------------------------------------- // Function-prototypes //----------------------------------------------------------------------------- LRESULT WINAPI MsgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ); HRESULT UpdateControllerState(); void RenderFrame(); //----------------------------------------------------------------------------- // Defines, constants, and global variables //----------------------------------------------------------------------------- #define MAX_CONTROLLERS 4 //----------------------------------------------------------------------------- // Struct to hold xinput state //----------------------------------------------------------------------------- struct CONTROLLER_STATE { XINPUT_STATE lastState; XINPUT_STATE state; DWORD dwResult; bool bLockVibration; XINPUT_VIBRATION vibration; }; CONTROLLER_STATE g_Controllers[MAX_CONTROLLERS]; WCHAR g_szMessage[4][1024] = {0}; HWND g_hWnd; //----------------------------------------------------------------------------- // Name: WinMain() // Desc: Entry point for the application. Since we use a simple dialog for // user interaction we don't need to pump messages. //----------------------------------------------------------------------------- int WINAPI wWinMain( _In_ HINSTANCE hInstance, _In_opt_ HINSTANCE, _In_ LPWSTR, _In_ int ) { // Initialize COM HRESULT hr; if( FAILED( hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED) ) ) return 1; // Register the window class HBRUSH hBrush = CreateSolidBrush( 0xFF0000 ); WNDCLASSEX wc = { sizeof( WNDCLASSEX ), 0, MsgProc, 0L, 0L, hInstance, nullptr, LoadCursor( nullptr, IDC_ARROW ), hBrush, nullptr, L"XInputSample", nullptr }; RegisterClassEx( &wc ); // Create the application's window g_hWnd = CreateWindow( L"XInputSample", L"XInput Sample: RumbleController", WS_OVERLAPPED | WS_VISIBLE | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX, CW_USEDEFAULT, CW_USEDEFAULT, 600, 600, nullptr, nullptr, hInstance, nullptr ); // Init state ZeroMemory( g_Controllers, sizeof( CONTROLLER_STATE ) * MAX_CONTROLLERS ); // Enter the message loop bool bGotMsg; MSG msg; msg.message = WM_NULL; while( WM_QUIT != msg.message ) { // Use PeekMessage() so we can use idle time to render the scene and call pEngine->DoWork() bGotMsg = ( PeekMessage( &msg, nullptr, 0U, 0U, PM_REMOVE ) != 0 ); if( bGotMsg ) { // Translate and dispatch the message TranslateMessage( &msg ); DispatchMessage( &msg ); } else { UpdateControllerState(); RenderFrame(); } } // Clean up UnregisterClass( L"XInputSample", nullptr ); CoUninitialize(); return 0; } //----------------------------------------------------------------------------- HRESULT UpdateControllerState() { for( DWORD i = 0; i < MAX_CONTROLLERS; i++ ) { g_Controllers[i].lastState = g_Controllers[i].state; g_Controllers[i].dwResult = XInputGetState( i, &g_Controllers[i].state ); } return S_OK; } //----------------------------------------------------------------------------- void RenderFrame() { bool bRepaint = false; WCHAR sz[4][1024]; for( DWORD i = 0; i < MAX_CONTROLLERS; i++ ) { if( g_Controllers[i].dwResult == ERROR_SUCCESS ) { if( !g_Controllers[i].bLockVibration ) { // Map bLeftTrigger's 0-255 to wLeftMotorSpeed's 0-65535 if( g_Controllers[i].state.Gamepad.bLeftTrigger > 0 ) g_Controllers[i].vibration.wLeftMotorSpeed = ( ( g_Controllers[i].state.Gamepad.bLeftTrigger + 1 ) * 256 ) - 1; else g_Controllers[i].vibration.wLeftMotorSpeed = 0; // Map bRightTrigger's 0-255 to wRightMotorSpeed's 0-65535 if( g_Controllers[i].state.Gamepad.bRightTrigger > 0 ) g_Controllers[i].vibration.wRightMotorSpeed = ( ( g_Controllers[i].state.Gamepad.bRightTrigger + 1 ) * 256 ) - 1; else g_Controllers[i].vibration.wRightMotorSpeed = 0; } if( ( g_Controllers[i].state.Gamepad.wButtons ) && ( g_Controllers[i].lastState.Gamepad.wButtons == 0 ) ) { if( !( !g_Controllers[i].bLockVibration && g_Controllers[i].vibration.wRightMotorSpeed == 0 && g_Controllers[i].vibration.wLeftMotorSpeed == 0 ) ) g_Controllers[i].bLockVibration = !g_Controllers[i].bLockVibration; } XInputSetState( i, &g_Controllers[i].vibration ); swprintf_s( sz[i], 1024, L"Controller %u: Connected\n" L" Left Motor Speed: %u\n" L" Right Motor Speed: %u\n" L" Rumble Lock: %d\n", i, g_Controllers[i].vibration.wLeftMotorSpeed, g_Controllers[i].vibration.wRightMotorSpeed, g_Controllers[i].bLockVibration ); } else if( g_Controllers[i].dwResult == ERROR_DEVICE_NOT_CONNECTED ) { swprintf_s( sz[i], 1024, L"Controller %u: Not connected", i ); } else { swprintf_s( sz[i], 1024, L"Controller %u: Generic error", i ); } if( wcscmp( sz[i], g_szMessage[i] ) != 0 ) { wcscpy_s( g_szMessage[i], 1024, sz[i] ); bRepaint = true; } } if( bRepaint ) { // Repaint the window if needed InvalidateRect( g_hWnd, nullptr, TRUE ); UpdateWindow( g_hWnd ); } // This sample doesn't use Direct3D. Instead, it just yields CPU time to other // apps but this is not typically done when rendering Sleep( 10 ); } //----------------------------------------------------------------------------- // Window message handler //----------------------------------------------------------------------------- LRESULT WINAPI MsgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch( msg ) { case WM_ACTIVATEAPP: { #if ((_WIN32_WINNT >= 0x0602 /*_WIN32_WINNT_WIN8*/) && (_WIN32_WINNT < 0x0A00 /*_WIN32_WINNT_WIN10*/)) || defined(USE_DIRECTX_SDK) // // XInputEnable is implemented by XInput 1.3 and 1.4, but not 9.1.0 // if( wParam == TRUE ) { // App is now active, so re-enable XInput XInputEnable( TRUE ); } else { // App is now inactive, so disable XInput to prevent // user input from effecting application and to // disable rumble. XInputEnable( FALSE ); } #endif break; } case WM_PAINT: { // Paint some simple explanation text PAINTSTRUCT ps; HDC hDC = BeginPaint( hWnd, &ps ); SetBkColor( hDC, 0xFF0000 ); SetTextColor( hDC, 0xFFFFFF ); RECT rect; GetClientRect( hWnd, &rect ); rect.top = 20; rect.left = 20; DrawText( hDC, L"Use the controller's left/right trigger to adjust the speed of the left/right rumble motor.\n" L"Press any controller button to lock or unlock at the current rumble speed.\n", -1, &rect, 0 ); for( DWORD i = 0; i < MAX_CONTROLLERS; i++ ) { rect.top = i * 80 + 90; rect.left = 20; DrawText( hDC, g_szMessage[i], -1, &rect, 0 ); } EndPaint( hWnd, &ps ); return 0; } case WM_DESTROY: { PostQuitMessage( 0 ); break; } } return DefWindowProc( hWnd, msg, wParam, lParam ); }
33.592982
131
0.469187
zzgchina888
8ab89337337edf8390b55cc6fcffb4ee8a314cc9
1,483
hpp
C++
test/test_headless.hpp
hfsm/HFSM2
61ecd4d36508dcc348049ee72d51f6cfca095311
[ "MIT" ]
2
2021-01-26T02:50:53.000Z
2021-07-14T02:07:52.000Z
test/test_headless.hpp
hfsm/HFSM2
61ecd4d36508dcc348049ee72d51f6cfca095311
[ "MIT" ]
1
2021-01-26T02:51:46.000Z
2021-01-26T06:06:31.000Z
test/test_headless.hpp
hfsm/HFSM2
61ecd4d36508dcc348049ee72d51f6cfca095311
[ "MIT" ]
null
null
null
#include "test_shared.hpp" namespace test_headless { //------------------------------------------------------------------------------ struct Context {}; using M = hfsm2::Machine<Context>; //////////////////////////////////////////////////////////////////////////////// #define S(s) struct s using FSM = M::OrthogonalPeerRoot< M::OrthogonalPeers< S(Composite_1), S(Composite_2) >, M::OrthogonalPeers< S(Orthogonal_1), S(Orthogonal_2) > >; #undef S static_assert(FSM::stateId<Composite_1>() == 2, ""); static_assert(FSM::stateId<Composite_2>() == 3, ""); static_assert(FSM::stateId<Orthogonal_1>() == 5, ""); static_assert(FSM::stateId<Orthogonal_2>() == 6, ""); //------------------------------------------------------------------------------ struct Composite_1 : FSM::State {}; struct Composite_2 : FSM::State {}; struct Orthogonal_1 : FSM::State {}; struct Orthogonal_2 : FSM::State {}; //////////////////////////////////////////////////////////////////////////////// static_assert(FSM::Instance::DEEP_WIDTH == 0, "DEEP_WIDTH"); static_assert(FSM::Instance::STATE_COUNT == 7, "STATE_COUNT"); static_assert(FSM::Instance::COMPO_COUNT == 0, "COMPO_COUNT"); static_assert(FSM::Instance::ORTHO_COUNT == 3, "ORTHO_COUNT"); static_assert(FSM::Instance::ORTHO_UNITS == 3, "ORTHO_UNITS"); static_assert(FSM::Instance::PRONG_COUNT == 0, "PRONG_COUNT"); //////////////////////////////////////////////////////////////////////////////// }
28.519231
80
0.495617
hfsm
8ab8e443b2687a69937866a1269e9a93e3dfec11
2,103
cpp
C++
projs/hello_renderer/src/app.cpp
colintan95/gl_projects
ad9bcdeaaa65474f45968b26a9a565cbe34af68e
[ "MIT" ]
null
null
null
projs/hello_renderer/src/app.cpp
colintan95/gl_projects
ad9bcdeaaa65474f45968b26a9a565cbe34af68e
[ "MIT" ]
null
null
null
projs/hello_renderer/src/app.cpp
colintan95/gl_projects
ad9bcdeaaa65474f45968b26a9a565cbe34af68e
[ "MIT" ]
null
null
null
#include "app.h" #include <iostream> #include <cstdlib> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtx/string_cast.hpp> #include "gfx_utils/primitives.h" static const float kPi = 3.14159265358979323846f; static const int kWindowWidth = 1920; static const int kWindowHeight = 1080; static const std::string kLightPassVertShaderPath = "shaders/simple_light.vert"; static const std::string kLightPassFragShaderPath = "shaders/simple_light.frag"; static const std::string kShadowPassVertShaderPath = "shaders/shadow_pass.vert"; static const std::string kShadowPassFragShaderPath = "shaders/shadow_pass.frag"; static const int kShadowTexWidth = 1024; static const int kShadowTexHeight = 1024; void App::Run() { Startup(); MainLoop(); Cleanup(); } void App::MainLoop() { bool should_quit = false; while (!should_quit) { renderer_.Render(scene_.GetEntities()); window_.SwapBuffers(); window_.TickMainLoop(); if (window_.ShouldQuit()) { should_quit = true; } } } void App::Startup() { if (!window_.Inititalize(kWindowWidth, kWindowHeight, "Shadow Map")) { std::cerr << "Failed to initialize gfx window" << std::endl; exit(1); } if (!camera_.Initialize(&window_)) { std::cerr << "Failed to initialize camera" << std::endl; exit(1); } scene_.LoadSceneFromJson("assets/scene.json"); // Add custom room entity auto room_model_ptr = std::make_shared<gfx_utils::Model>("room"); room_model_ptr->GetMeshes() = std::move(gfx_utils::CreateRoom(30.f, 20.f, 80.f)); auto room_entity_ptr = std::make_shared<gfx_utils::Entity>("room"); room_entity_ptr->SetModel(room_model_ptr); scene_.AddEntity(room_entity_ptr); gl_resource_manager_.SetScene(&scene_); gl_resource_manager_.CreateGLResources(); renderer_.Initialize(); renderer_.SetResourceManager(&gl_resource_manager_); renderer_.SetWindow(&window_); renderer_.SetCamera(&camera_); } void App::Cleanup() { renderer_.Destroy(); gl_resource_manager_.Cleanup(); window_.Destroy(); }
23.897727
80
0.719924
colintan95
8abc0dff5ba7c17b23beda13b48d8b1874bfde92
1,459
cpp
C++
Code/Core/Reflection/ReflectionIter.cpp
qq573011406/FASTBuild_UnrealEngine
29c49672f82173a903cb32f0e4656e2fd07ebef2
[ "MIT" ]
30
2020-07-15T06:16:55.000Z
2022-02-10T21:37:52.000Z
Code/Core/Reflection/ReflectionIter.cpp
qq573011406/FASTBuild_UnrealEngine
29c49672f82173a903cb32f0e4656e2fd07ebef2
[ "MIT" ]
1
2020-11-23T13:35:00.000Z
2020-11-23T13:35:00.000Z
Code/Core/Reflection/ReflectionIter.cpp
qq573011406/FASTBuild_UnrealEngine
29c49672f82173a903cb32f0e4656e2fd07ebef2
[ "MIT" ]
12
2020-09-16T17:39:34.000Z
2021-08-17T11:32:37.000Z
// ReflectionIter.cpp //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include "ReflectionIter.h" #include "Core/Reflection/ReflectionInfo.h" // CONSTRUCTOR //------------------------------------------------------------------------------ ReflectionIter::ReflectionIter( const ReflectionInfo * info, uint32_t index ) : m_Info( info ) , m_Index( index ) { } // operator == //------------------------------------------------------------------------------ bool ReflectionIter::operator == ( const ReflectionIter & other ) const { ASSERT( other.m_Info == m_Info ); // invalid to compare iterators on different objects return ( other.m_Index == m_Index ); } // operator ++ //------------------------------------------------------------------------------ void ReflectionIter::operator ++() { ++m_Index; } // operator -> //------------------------------------------------------------------------------ const ReflectedProperty & ReflectionIter::operator ->() const { return m_Info->GetReflectedProperty( m_Index ); } // operator * //------------------------------------------------------------------------------ const ReflectedProperty & ReflectionIter::operator *() const { return m_Info->GetReflectedProperty( m_Index ); } //------------------------------------------------------------------------------
30.395833
90
0.388622
qq573011406
8abc6009e1ec035a964b32437a9bb94f40d8920c
7,434
cpp
C++
assignment1/tokeniser.cpp
raymondsim/Computer-System
0b4de4d55157d92e64cae4af048933e39cb09c1f
[ "MIT" ]
null
null
null
assignment1/tokeniser.cpp
raymondsim/Computer-System
0b4de4d55157d92e64cae4af048933e39cb09c1f
[ "MIT" ]
null
null
null
assignment1/tokeniser.cpp
raymondsim/Computer-System
0b4de4d55157d92e64cae4af048933e39cb09c1f
[ "MIT" ]
null
null
null
// AUTHOR: Mong Yuan SIM (a1808469) // tokeniser implementation for the workshop example language #include "tokeniser-extras.h" // to shorten the code using namespace std; // we are extending the Assignment_Tokeniser namespace namespace Assignment_Tokeniser { // token ::= ... // * wspace ::= '\t' | '\n' | '\r' | ' ' static void parse_wspace() { if (next_char_isa(cg_wspace)) next_char_mustbe(cg_wspace); else did_not_find_char(cg_wspace); } // - id_letter ::= 'a'-'z'|'A'-'Z'|'0'-'9'|'_'|'$'|'.' static void parse_id_letter() { if (next_char_isa(cg_id_letter)) next_char_mustbe(cg_id_letter); } // * identifier ::= ('a'-'z'|'A'-'Z'|'^') id_letter* '?'? static void parse_identifier() { if (next_char_isa(cg_identifier)) next_char_mustbe(cg_identifier); while (next_char_isa(cg_id_letter)) parse_id_letter(); if (next_char_isa('?')) next_char_mustbe('?'); } // - bin_digit ::= '0' | '1' static void parse_bin_digit() { if(next_char_isa(cg_bin_digit)) next_char_mustbe(cg_bin_digit); } // - bin_fraction ::= '.' bin_digit* static void parse_bin_fraction() { next_char_mustbe('.'); while (next_char_isa(cg_bin_digit)) next_char_mustbe(cg_bin_digit); } // - binary ::= '0' 'b' bin_digit+ bin_fraction? static void parse_binary() { next_char_mustbe('b'); next_char_mustbe(cg_bin_digit); while (next_char_isa(cg_bin_digit)) parse_bin_digit(); if (next_char_isa(cg_bin_fraction)) parse_bin_fraction(); } // - oct_fraction ::= '.' oct_digit* static void parse_oct_fraction() { next_char_mustbe('.'); while (next_char_isa(cg_oct_digit)) next_char_mustbe(cg_oct_digit); } // - octal ::= '0' oct_digit+ oct_fraction? static void parse_octal() { next_char_mustbe(cg_oct_digit); while (next_char_isa(cg_oct_digit)) next_char_mustbe(cg_oct_digit); if (next_char_isa(cg_oct_fraction)) parse_oct_fraction(); } // - decimal19 ::= ('1'-'9') dec_digit* static void parse_decimal19() { next_char_mustbe(cg_decimal19); while (next_char_isa(cg_dec_digit)) next_char_mustbe(cg_dec_digit); } // - dec_fraction ::= '.' dec_digit* static void parse_dec_fraction() { next_char_mustbe('.'); while (next_char_isa(cg_dec_digit)) next_char_mustbe(cg_dec_digit); } // - decimal ::= ('0' | decimal19) dec_fraction? static void parse_decimal() { parse_decimal19(); if (next_char_isa(cg_dec_fraction)) parse_dec_fraction(); } // - hex_digit ::= '0'-'9'|'A'-'F' static void parse_hex_digit() { if(next_char_isa(cg_hex_digit)) next_char_mustbe(cg_hex_digit); } // - hex_fraction ::= '.' hex_digit* static void parse_hex_fraction() { next_char_mustbe('.'); while (next_char_isa(cg_hex_digit)) next_char_mustbe(cg_hex_digit); } // - hexadecimal ::= '0' 'x' hex_digit+ hex_fraction? static void parse_hexadecimal() { next_char_mustbe('x'); next_char_mustbe(cg_hex_digit); while (next_char_isa(cg_hex_digit)) parse_hex_digit(); if (next_char_isa(cg_hex_fraction)) parse_hex_fraction(); } // * string ::= '"' instring* '"' static void parse_string() { next_char_mustbe('"'); while (next_char_isa(cg_instring)) next_char_mustbe(cg_instring); next_char_mustbe('"'); } //to parse adhoc suffix static void parse_adhoc_suffix_extra() { next_char_mustbe(cg_not_div); while (next_char_isa(cg_not_star)) next_char_mustbe(cg_not_star); next_char_mustbe('*'); while (next_char_isa('*')) next_char_mustbe('*'); } // - adhoc_suffix ::= '*' adhoc_char* '*/' static void parse_adhoc_suffix() { next_char_mustbe('*'); while (next_char_isa(cg_not_star)) next_char_mustbe(cg_not_star); while (next_char_isa('*')) next_char_mustbe('*'); while (next_char_isa(cg_not_div)) parse_adhoc_suffix_extra(); next_char_mustbe('/'); } // * adhoc_comment ::= '/' adhoc_suffix static void parse_adhoc_comment() { if (next_char_isa('*')) parse_adhoc_suffix(); } // * symbol ::= '@'|';'|':'|'!='|','|'.'|'=='|'<=>'|'{'|'}'|'('|')'|'['|']'|'/' // - symbols each have their own TokenKind static void parse_symbol() { if (next_char_isa('!')) { next_char_mustbe('!'); if (next_char_isa('=')) next_char_mustbe('='); } else if (next_char_isa('<')) { next_char_mustbe('<'); next_char_mustbe('='); next_char_mustbe('>'); } else if (next_char_isa('=')) { next_char_mustbe('='); next_char_mustbe('='); } else if (next_char_isa('/')) { next_char_mustbe('/'); if (next_char_isa('/')) { next_char_mustbe('/'); while (next_char_isa(cg_eol_char)) next_char_mustbe(cg_eol_char); next_char_mustbe('\n'); } else if (next_char_isa('*')) { parse_adhoc_comment(); } } else { next_char_mustbe(cg_symbol); } } //parse number with four kind of numbers static void parse_number() { if (next_char_isa(cg_decimal19)) parse_decimal(); else if (next_char_isa('0')) { next_char_mustbe('0'); if (next_char_isa('b')) parse_binary(); else if (next_char_isa(cg_oct_digit)) parse_octal(); else if (next_char_isa('.')) parse_dec_fraction(); else if (next_char_isa('x')) parse_hexadecimal(); } else did_not_find_char(cg_number); } //parse token with different kind of inputs static void parse_token() { if (next_char_isa(cg_wspace)) parse_wspace(); else if (next_char_isa(cg_identifier)) parse_identifier(); else if (next_char_isa(cg_number)) parse_number(); else if (next_char_isa(cg_string)) parse_string(); else if (next_char_isa(cg_symbol)) parse_symbol(); else if (next_char_isa(EOF)) /* do nothing once at end of input */ ; else did_not_find_char(cg_token); } // parse the next token in the input and return a new // Token object that describes its kind and spelling // Note: you must not call new_token() anywhere else in your program // Note: you should not modify this function Token read_next_token() { parse_token(); return new_token(); } }
27.533333
83
0.539817
raymondsim
8ac039edbac845978fcfdfd70740fdfa80c04395
4,056
cpp
C++
hw1.skel/HW.cpp
edzh/csc472-hw
036ef3fdeda1cc68549a93d23a8bd9bdb661849d
[ "MIT" ]
1
2020-08-17T08:21:34.000Z
2020-08-17T08:21:34.000Z
HW.cpp
jguerrero12/OpenGL-HW
11d61fda94538e47c91d58af8b781c26b06e5da4
[ "Apache-2.0" ]
null
null
null
HW.cpp
jguerrero12/OpenGL-HW
11d61fda94538e47c91d58af8b781c26b06e5da4
[ "Apache-2.0" ]
null
null
null
// =============================================================== // Computer Graphics Homework Solutions // Copyright (C) 2017 by George Wolberg // // HW.cpp - HW class. Base class of homework solutions. // // Written by: George Wolberg, 2017 // =============================================================== #include "HW.h" QString GroupBoxStyle = "QGroupBox { \ border: 1px solid gray; \ border-radius: 9px; \ font-weight: bold; \ margin-top: 0.5em;} \ QGroupBox::title { \ subcontrol-origin: margin; \ left: 10px; \ padding: 0 3px 0 3px; \ }"; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // HW::HW: // // HW constructor. // This is base class for homework solutions that will replace // the control panel, reset function, and add homework solution. // HW::HW(const QGLFormat &glf, QWidget *parent) : QGLWidget (glf, parent) {} // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // HW::controlPanel: // // Create a control panel of widgets for homework solution. // QGroupBox* HW::controlPanel() { return NULL; } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // HW::reset: // // Reset parameters in control panel. // void HW::reset() {} // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // HW::initShader: // // Initialize vertex and fragment shaders. // void HW::initShader(int shaderID, QString vshaderName, QString fshaderName, UniformMap uniforms) { // due to bug in Qt, in order to use higher OpenGL version (>2.1), we need to add lines // up to initShader() to render properly uint vao; typedef void (APIENTRY *_glGenVertexArrays) (GLsizei, GLuint*); typedef void (APIENTRY *_glBindVertexArray) (GLuint); _glGenVertexArrays glGenVertexArrays; _glBindVertexArray glBindVertexArray; glGenVertexArrays = (_glGenVertexArrays) QGLWidget::context()->getProcAddress("glGenVertexArrays"); glBindVertexArray = (_glBindVertexArray) QGLWidget::context()->getProcAddress("glBindVertexArray"); glGenVertexArrays(1, &vao); glBindVertexArray(vao); // compile vertex shader bool flag = m_program[shaderID].addShaderFromSourceFile(QGLShader::Vertex, vshaderName); if(!flag) { QMessageBox::critical(0, "Error", "Vertex shader error: " + vshaderName + "\n" + m_program[shaderID].log(), QMessageBox::Ok); exit(-1); } // compile fragment shader if(!m_program[shaderID].addShaderFromSourceFile(QGLShader::Fragment, fshaderName)) { QMessageBox::critical(0, "Error", "Fragment shader error: " + fshaderName + "\n" + m_program[shaderID].log(), QMessageBox::Ok); exit(-1); } // bind the attribute variable in the glsl program with a generic vertex attribute index; // values provided via ATTRIB_VERTEX will modify the value of "a_position") glBindAttribLocation(m_program[shaderID].programId(), ATTRIB_VERTEX, "a_Position"); glBindAttribLocation(m_program[shaderID].programId(), ATTRIB_COLOR, "a_Color" ); glBindAttribLocation(m_program[shaderID].programId(), ATTRIB_TEXCOORD, "a_TexCoord"); glBindAttribLocation(m_program[shaderID].programId(), ATTRIB_NORMAL, "a_Normal" ); // link shader pipeline; attribute bindings go into effect at this point if(!m_program[shaderID].link()) { QMessageBox::critical(0, "Error", "Could not link shader: " + vshaderName + "\n" + m_program[shaderID].log(), QMessageBox::Ok); qDebug() << m_program[shaderID].log(); exit(-1); } // iterate over all uniform variables; map each uniform name to shader location ID for(std::map<QString, GLuint>::iterator iter = uniforms.begin(); iter != uniforms.end(); ++iter) { QString uniformName = iter->first; GLuint uniformID = iter->second; // get storage location m_uniform[shaderID][uniformID]=glGetUniformLocation(m_program[shaderID].programId(), uniformName.toStdString().c_str()); if(m_uniform[shaderID][uniformID] < 0) { qDebug() << m_program[shaderID].log(); qDebug() << "Failed to get the storage location of " + uniformName; } } }
30.961832
100
0.634369
edzh
8ac4d479a812e90669464437d2c692e2078b83c2
669
hpp
C++
Incursion/Code/Game/Tile.hpp
yixuan-wei/Incursion
fa76fd30d1867cd05ffbc165d3577bc45cfde7ba
[ "MIT" ]
null
null
null
Incursion/Code/Game/Tile.hpp
yixuan-wei/Incursion
fa76fd30d1867cd05ffbc165d3577bc45cfde7ba
[ "MIT" ]
null
null
null
Incursion/Code/Game/Tile.hpp
yixuan-wei/Incursion
fa76fd30d1867cd05ffbc165d3577bc45cfde7ba
[ "MIT" ]
null
null
null
#pragma once #include "Engine/Math/IntVec2.hpp" struct AABB2; struct Rgba8; struct Vec2; enum TileType : int { TILE_TYPE_GRASS = 0, TILE_TYPE_STONE, TILE_TYPE_MUD, TILE_TYPE_GROUND, TILE_TYPE_EXIT, TILE_TYPE_SAND, TILE_TYPE_DIRT, TILE_TYPE_BRICK, TILE_TYPE_WATER, TILE_TYPE_STEEL, TILE_TYPE_QUARTZ, NUM_TILE_TYPE }; class Tile { public: //default tile type is grass. Tile(int posX, int posY); ~Tile()=default; void Render()const; //origin is at the left bottom corner. AABB2 GetBounds() const; void GetUVCoords(Vec2& out_uvAtMins, Vec2& uvAtMaxs) const; public: //every tile is 1x1 in definition IntVec2 m_tileCoords; TileType m_type; };
15.55814
60
0.750374
yixuan-wei
8ac4fb3ce878f4e92d12d999fa227e2f2a4b8431
3,628
hpp
C++
media/papers/OpenPatternMatching/artifact/code/patterns/regex.hpp
akrzemi1/Mach7
eef288eb9fe59712ff153dd70791365391b7b118
[ "BSD-3-Clause" ]
1,310
2015-01-04T03:44:04.000Z
2022-03-18T04:44:01.000Z
media/papers/OpenPatternMatching/artifact/code/patterns/regex.hpp
akrzemi1/Mach7
eef288eb9fe59712ff153dd70791365391b7b118
[ "BSD-3-Clause" ]
62
2015-01-12T07:59:17.000Z
2021-11-14T22:02:14.000Z
media/papers/OpenPatternMatching/artifact/code/patterns/regex.hpp
akrzemi1/Mach7
eef288eb9fe59712ff153dd70791365391b7b118
[ "BSD-3-Clause" ]
108
2015-02-13T17:39:07.000Z
2021-11-18T11:06:59.000Z
/// /// \file regex.hpp /// /// This file defines regular expression pattern. /// /// \author Yuriy Solodkyy <[email protected]> /// /// This file is a part of Mach7 library (http://parasol.tamu.edu/mach7/). /// Copyright (C) 2011-2012 Texas A&M University. /// All rights reserved. /// #pragma once #include "common.hpp" #include <regex> #include <string> namespace mch ///< Mach7 library namespace { //------------------------------------------------------------------------------ /// RegEx pattern of 0 arguments struct regex0 : std::regex { /// Type function returning a type that will be accepted by the pattern for /// a given subject type S. We use type function instead of an associated /// type, because there is no a single accepted type for a #wildcard pattern /// for example. Requirement of #Pattern concept. template <typename S> struct accepted_type_for { typedef std::string type; }; regex0(const char* re) : std::regex(re) {} bool operator()(const std::string& s) const noexcept { return operator()(s.c_str()); } bool operator()(const char* s) const noexcept { std::cmatch m; return regex_match(s,m,*this); } }; //------------------------------------------------------------------------------ /// RegEx pattern of 1 arguments template <typename P1> struct regex1 : std::regex { static_assert(is_pattern<P1>::value, "Argument P1 of a regex-pattern must be a pattern"); /// Type function returning a type that will be accepted by the pattern for /// a given subject type S. We use type function instead of an associated /// type, because there is no a single accepted type for a #wildcard pattern /// for example. Requirement of #Pattern concept. template <typename S> struct accepted_type_for { typedef std::string type; }; explicit regex1(const char* re, const P1& p1) noexcept : std::regex(re), m_p1(p1) {} explicit regex1(const char* re, P1&& p1) noexcept : std::regex(re), m_p1(std::move(p1)) {} regex1(regex1&& r) noexcept : std::regex(std::move(r)), m_p1(std::move(r.m_p1)) {} regex1& operator=(const regex1&); ///< Assignment is not allowed for this class bool operator()(const std::string& s) const noexcept { return operator()(s.c_str()); } bool operator()(const char* s) const noexcept { std::cmatch m; if (regex_match(s,m,*this)) { XTL_ASSERT(m.size() >= 1); // There should be enough capture groups for each of the pattern arguments typename P1::template accepted_type_for<std::string>::type m1; std::stringstream ss(m[1]); return (ss >> m1) && m_p1(m1); } return false; } P1 m_p1; }; //------------------------------------------------------------------------------ inline regex0 rex(const char* re) noexcept { return regex0(re); } template <typename P1> inline auto rex(const char* re, P1&& p1) noexcept -> XTL_RETURN ( regex1< typename underlying<decltype(filter(std::forward<P1>(p1)))>::type >( re, filter(std::forward<P1>(p1)) ) ) //------------------------------------------------------------------------------ template <> struct is_pattern_<regex0> { static const bool value = true; }; template <typename P1> struct is_pattern_<regex1<P1>> { static const bool value = true; }; //------------------------------------------------------------------------------ } // of namespace mch
36.646465
115
0.553197
akrzemi1
8acbd57f29ae8cf70f9a2c9eb01ad0c1b78a441a
3,914
cpp
C++
fmo-cpp/tests/test-processing.cpp
sverbach/fmo-android
b4957ea51a4e0df6dc5315eaaf16b73c954d16a4
[ "MIT" ]
37
2019-03-11T09:08:20.000Z
2022-02-26T19:01:51.000Z
fmo-cpp/tests/test-processing.cpp
sverbach/fmo-android
b4957ea51a4e0df6dc5315eaaf16b73c954d16a4
[ "MIT" ]
83
2020-09-22T09:04:38.000Z
2021-06-10T16:15:17.000Z
fmo-cpp/tests/test-processing.cpp
sverbach/fmo-android
b4957ea51a4e0df6dc5315eaaf16b73c954d16a4
[ "MIT" ]
10
2020-06-29T03:22:28.000Z
2021-10-01T15:28:25.000Z
#include "../catch/catch.hpp" #include <fmo/subsampler.hpp> #include "test-data.hpp" #include "test-tools.hpp" SCENARIO("performing per-pixel operations", "[image][processing]") { GIVEN("an empty destination image") { fmo::Image dst{ }; WHEN("source image is BGR") { fmo::Image src{fmo::Format::BGR, IM_4x2_DIMS, IM_4x2_BGR.data()}; THEN("calling less_than() throws") { REQUIRE_THROWS(fmo::less_than(src, dst, 0x95)); } THEN("calling greater_than() throws") { REQUIRE_THROWS(fmo::greater_than(src, dst, 0x95)); } } GIVEN("a GRAY source image (4x2)") { fmo::Image src{fmo::Format::GRAY, IM_4x2_DIMS, IM_4x2_GRAY.data()}; WHEN("less_than() is called") { fmo::less_than(src, dst, 0x95); THEN("result is as expected") { REQUIRE(dst.dims() == src.dims()); REQUIRE(dst.format() == fmo::Format::GRAY); REQUIRE(exact_match(dst, IM_4x2_LESS_THAN)); } } WHEN("greater_than() is called") { fmo::greater_than(src, dst, 0x95); THEN("result is as expected") { REQUIRE(dst.dims() == src.dims()); REQUIRE(dst.format() == fmo::Format::GRAY); REQUIRE(exact_match(dst, IM_4x2_GREATER_THAN)); } } GIVEN("a second GRAY source image (4x2_LESS_THAN)") { fmo::Image src2{fmo::Format::GRAY, IM_4x2_DIMS, IM_4x2_LESS_THAN.data()}; WHEN("absdiff() is called") { fmo::absdiff(src, src2, dst); THEN("result is as expected") { REQUIRE(dst.dims() == src.dims()); REQUIRE(dst.format() == src.format()); REQUIRE(exact_match(dst, IM_4x2_ABSDIFF)); } } } } } } SCENARIO("performing complex operations", "[image][processing]") { GIVEN("an empty destination image") { fmo::Image dst{ }; GIVEN("a GRAY source image") { fmo::Image src{fmo::Format::GRAY, IM_4x2_DIMS, IM_4x2_GRAY.data()}; WHEN("subsample() is called") { fmo::subsample(src, dst); THEN("result is as expected") { REQUIRE(dst.format() == src.format()); REQUIRE((dst.dims() == fmo::Dims{2, 1})); std::array<uint8_t, 2> expected = {{0x7F, 0x7F}}; REQUIRE(exact_match(dst, expected)); } } } GIVEN("a YUV420SP source image") { fmo::Image src{fmo::Format::YUV420SP, IM_4x2_DIMS, IM_4x2_YUV420SP_2.data()}; WHEN("Subsampler is used on a YUV420SP image") { fmo::Subsampler sub; sub(src, dst); THEN("result is as expected") { REQUIRE(dst.format() == fmo::Format::YUV); REQUIRE((dst.dims() == fmo::Dims{2, 1})); REQUIRE(exact_match(dst, IM_4x2_SUBSAMPLED)); } } } GIVEN("random GRAY source images") { fmo::Image src1{fmo::Format::GRAY, IM_4x2_DIMS, IM_4x2_RANDOM_1.data()}; fmo::Image src2{fmo::Format::GRAY, IM_4x2_DIMS, IM_4x2_RANDOM_2.data()}; fmo::Image src3{fmo::Format::GRAY, IM_4x2_DIMS, IM_4x2_RANDOM_3.data()}; WHEN("median3() is called") { fmo::median3(src1, src2, src3, dst); THEN("result is as expected") { REQUIRE(dst.dims() == src1.dims()); REQUIRE(dst.format() == src1.format()); REQUIRE(exact_match(dst, IM_4x2_MEDIAN3)); } } } } }
43.010989
98
0.490802
sverbach
8acf606e1275b391623e888e74947842eea93bdb
88,169
cpp
C++
tests/Secrets/tst_secretsrequests/tst_secretsrequests.cpp
Denis-Semakin/sailfish-secrets
aebe33ad93ca2378f4f20d455fc43bacba8e9c89
[ "BSD-3-Clause" ]
null
null
null
tests/Secrets/tst_secretsrequests/tst_secretsrequests.cpp
Denis-Semakin/sailfish-secrets
aebe33ad93ca2378f4f20d455fc43bacba8e9c89
[ "BSD-3-Clause" ]
null
null
null
tests/Secrets/tst_secretsrequests/tst_secretsrequests.cpp
Denis-Semakin/sailfish-secrets
aebe33ad93ca2378f4f20d455fc43bacba8e9c89
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2018 Jolla Ltd. * Contact: Chris Adams <[email protected]> * All rights reserved. * BSD 3-Clause License, see LICENSE. */ #include <QtTest> #include <QObject> #include <QElapsedTimer> #include <QDBusReply> #include <QQuickView> #include <QQuickItem> #include "Secrets/secretmanager.h" #include "Secrets/secret.h" #include "Secrets/interactionparameters.h" #include "Secrets/collectionnamesrequest.h" #include "Secrets/createcollectionrequest.h" #include "Secrets/deletecollectionrequest.h" #include "Secrets/deletesecretrequest.h" #include "Secrets/findsecretsrequest.h" #include "Secrets/interactionrequest.h" #include "Secrets/lockcoderequest.h" #include "Secrets/plugininforequest.h" #include "Secrets/storedsecretrequest.h" #include "Secrets/storesecretrequest.h" using namespace Sailfish::Secrets; #define DEFAULT_TEST_STORAGE_PLUGIN SecretManager::DefaultStoragePluginName + QLatin1String(".test") #define DEFAULT_TEST_ENCRYPTION_PLUGIN SecretManager::DefaultEncryptionPluginName + QLatin1String(".test") #define DEFAULT_TEST_ENCRYPTEDSTORAGE_PLUGIN SecretManager::DefaultEncryptedStoragePluginName + QLatin1String(".test") #define IN_APP_TEST_AUTHENTICATION_PLUGIN SecretManager::InAppAuthenticationPluginName + QLatin1String(".test") // Cannot use waitForFinished() for some replies, as ui flows require user interaction / event handling. #define WAIT_FOR_FINISHED_WITHOUT_BLOCKING(request) \ do { \ int maxWait = 60000; \ while (request.status() != Request::Finished && maxWait > 0) { \ QTest::qWait(100); \ maxWait -= 100; \ } \ } while (0) class tst_secretsrequests : public QObject { Q_OBJECT public slots: void init(); void cleanup(); private slots: void getPluginInfo(); void devicelockCollection(); void devicelockCollectionSecret(); void devicelockStandaloneSecret(); void customlockCollection(); void customlockCollectionSecret(); void customlockStandaloneSecret(); void encryptedStorageCollection(); void storeUserSecret(); void requestUserInput(); void accessControl(); void lockCode(); void pluginThreading(); private: SecretManager sm; }; void tst_secretsrequests::init() { } void tst_secretsrequests::cleanup() { } void tst_secretsrequests::getPluginInfo() { PluginInfoRequest r; r.setManager(&sm); QSignalSpy ss(&r, &PluginInfoRequest::statusChanged); QSignalSpy sps(&r, &PluginInfoRequest::storagePluginsChanged); QSignalSpy eps(&r, &PluginInfoRequest::encryptionPluginsChanged); QSignalSpy esps(&r, &PluginInfoRequest::encryptedStoragePluginsChanged); QSignalSpy aps(&r, &PluginInfoRequest::authenticationPluginsChanged); QCOMPARE(r.status(), Request::Inactive); r.startRequest(); QCOMPARE(ss.count(), 1); QCOMPARE(r.status(), Request::Active); QCOMPARE(r.result().code(), Result::Pending); r.waitForFinished(); QCOMPARE(ss.count(), 2); QCOMPARE(r.status(), Request::Finished); QCOMPARE(r.result().code(), Result::Succeeded); QCOMPARE(sps.count(), 1); QCOMPARE(eps.count(), 1); QCOMPARE(esps.count(), 1); QCOMPARE(aps.count(), 1); QVERIFY(r.storagePlugins().size()); QStringList storagePluginNames; for (auto p : r.storagePlugins()) { storagePluginNames.append(p.name()); } QVERIFY(storagePluginNames.contains(DEFAULT_TEST_STORAGE_PLUGIN)); QVERIFY(r.encryptionPlugins().size()); QStringList encryptionPluginNames; for (auto p : r.encryptionPlugins()) { encryptionPluginNames.append(p.name()); } QVERIFY(encryptionPluginNames.contains(DEFAULT_TEST_ENCRYPTION_PLUGIN)); QVERIFY(r.encryptedStoragePlugins().size()); QStringList encryptedStoragePluginNames; for (auto p : r.encryptedStoragePlugins()) { encryptedStoragePluginNames.append(p.name()); } QVERIFY(encryptedStoragePluginNames.contains(DEFAULT_TEST_ENCRYPTEDSTORAGE_PLUGIN)); QVERIFY(r.authenticationPlugins().size()); QStringList authenticationPluginNames; for (auto p : r.authenticationPlugins()) { authenticationPluginNames.append(p.name()); } QVERIFY(authenticationPluginNames.contains(IN_APP_TEST_AUTHENTICATION_PLUGIN)); } void tst_secretsrequests::devicelockCollection() { // create a new collection CreateCollectionRequest ccr; ccr.setManager(&sm); QSignalSpy ccrss(&ccr, &CreateCollectionRequest::statusChanged); ccr.setCollectionLockType(CreateCollectionRequest::DeviceLock); QCOMPARE(ccr.collectionLockType(), CreateCollectionRequest::DeviceLock); ccr.setCollectionName(QLatin1String("testcollection")); QCOMPARE(ccr.collectionName(), QLatin1String("testcollection")); ccr.setStoragePluginName(DEFAULT_TEST_STORAGE_PLUGIN); QCOMPARE(ccr.storagePluginName(), DEFAULT_TEST_STORAGE_PLUGIN); ccr.setEncryptionPluginName(DEFAULT_TEST_ENCRYPTION_PLUGIN); QCOMPARE(ccr.encryptionPluginName(), DEFAULT_TEST_ENCRYPTION_PLUGIN); ccr.setDeviceLockUnlockSemantic(SecretManager::DeviceLockKeepUnlocked); QCOMPARE(ccr.deviceLockUnlockSemantic(), SecretManager::DeviceLockKeepUnlocked); ccr.setAccessControlMode(SecretManager::OwnerOnlyMode); QCOMPARE(ccr.accessControlMode(), SecretManager::OwnerOnlyMode); QCOMPARE(ccr.status(), Request::Inactive); ccr.startRequest(); QCOMPARE(ccrss.count(), 1); QCOMPARE(ccr.status(), Request::Active); QCOMPARE(ccr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(ccr); QCOMPARE(ccrss.count(), 2); QCOMPARE(ccr.status(), Request::Finished); QCOMPARE(ccr.result().code(), Result::Succeeded); // ensure that the name of the collection is returned from a CollectionNamesRequest CollectionNamesRequest cnr; cnr.setManager(&sm); cnr.setStoragePluginName(DEFAULT_TEST_STORAGE_PLUGIN); QSignalSpy cnrss(&cnr, &CollectionNamesRequest::statusChanged); QCOMPARE(cnr.status(), Request::Inactive); cnr.startRequest(); QCOMPARE(cnrss.count(), 1); QCOMPARE(cnr.status(), Request::Active); QCOMPARE(cnr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(cnr); QCOMPARE(cnrss.count(), 2); QCOMPARE(cnr.status(), Request::Finished); QCOMPARE(cnr.result().code(), Result::Succeeded); QCOMPARE(cnr.collectionNames(), QStringList() << QLatin1String("testcollection")); // delete the collection DeleteCollectionRequest dcr; dcr.setManager(&sm); QSignalSpy dcrss(&dcr, &DeleteCollectionRequest::statusChanged); dcr.setCollectionName(QLatin1String("testcollection")); QCOMPARE(dcr.collectionName(), QLatin1String("testcollection")); dcr.setStoragePluginName(DEFAULT_TEST_STORAGE_PLUGIN); QCOMPARE(dcr.storagePluginName(), DEFAULT_TEST_STORAGE_PLUGIN); dcr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(dcr.userInteractionMode(), SecretManager::ApplicationInteraction); QCOMPARE(dcr.status(), Request::Inactive); dcr.startRequest(); QCOMPARE(dcrss.count(), 1); QCOMPARE(dcr.status(), Request::Active); QCOMPARE(dcr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(dcr); QCOMPARE(dcrss.count(), 2); QCOMPARE(dcr.status(), Request::Finished); QCOMPARE(dcr.result().code(), Result::Succeeded); // ensure that it is no longer returned. cnr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(cnr); QVERIFY(cnr.collectionNames().isEmpty()); } void tst_secretsrequests::devicelockCollectionSecret() { // create a collection CreateCollectionRequest ccr; ccr.setManager(&sm); QSignalSpy ccrss(&ccr, &CreateCollectionRequest::statusChanged); ccr.setCollectionLockType(CreateCollectionRequest::DeviceLock); QCOMPARE(ccr.collectionLockType(), CreateCollectionRequest::DeviceLock); ccr.setCollectionName(QLatin1String("testcollection")); QCOMPARE(ccr.collectionName(), QLatin1String("testcollection")); ccr.setStoragePluginName(DEFAULT_TEST_STORAGE_PLUGIN); QCOMPARE(ccr.storagePluginName(), DEFAULT_TEST_STORAGE_PLUGIN); ccr.setEncryptionPluginName(DEFAULT_TEST_ENCRYPTION_PLUGIN); QCOMPARE(ccr.encryptionPluginName(), DEFAULT_TEST_ENCRYPTION_PLUGIN); ccr.setDeviceLockUnlockSemantic(SecretManager::DeviceLockKeepUnlocked); QCOMPARE(ccr.deviceLockUnlockSemantic(), SecretManager::DeviceLockKeepUnlocked); ccr.setAccessControlMode(SecretManager::OwnerOnlyMode); QCOMPARE(ccr.accessControlMode(), SecretManager::OwnerOnlyMode); QCOMPARE(ccr.status(), Request::Inactive); ccr.startRequest(); QCOMPARE(ccrss.count(), 1); QCOMPARE(ccr.status(), Request::Active); QCOMPARE(ccr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(ccr); QCOMPARE(ccrss.count(), 2); QCOMPARE(ccr.status(), Request::Finished); QCOMPARE(ccr.result().code(), Result::Succeeded); // store a new secret into the collection Secret testSecret(Secret::Identifier( QLatin1String("testsecretname"), QLatin1String("testcollection"), DEFAULT_TEST_STORAGE_PLUGIN)); testSecret.setData("testsecretvalue"); testSecret.setType(Secret::TypeBlob); testSecret.setFilterData(QLatin1String("domain"), QLatin1String("sailfishos.org")); testSecret.setFilterData(QLatin1String("test"), QLatin1String("true")); StoreSecretRequest ssr; ssr.setManager(&sm); QSignalSpy ssrss(&ssr, &StoreSecretRequest::statusChanged); ssr.setSecretStorageType(StoreSecretRequest::CollectionSecret); QCOMPARE(ssr.secretStorageType(), StoreSecretRequest::CollectionSecret); ssr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(ssr.userInteractionMode(), SecretManager::ApplicationInteraction); ssr.setSecret(testSecret); QCOMPARE(ssr.secret(), testSecret); QCOMPARE(ssr.status(), Request::Inactive); ssr.startRequest(); QCOMPARE(ssrss.count(), 1); QCOMPARE(ssr.status(), Request::Active); QCOMPARE(ssr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(ssr); QCOMPARE(ssrss.count(), 2); QCOMPARE(ssr.status(), Request::Finished); QCOMPARE(ssr.result().code(), Result::Succeeded); // retrieve the secret, ensure it matches StoredSecretRequest gsr; gsr.setManager(&sm); QSignalSpy gsrss(&gsr, &StoredSecretRequest::statusChanged); gsr.setIdentifier(testSecret.identifier()); QCOMPARE(gsr.identifier(), testSecret.identifier()); gsr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(gsr.userInteractionMode(), SecretManager::ApplicationInteraction); QCOMPARE(gsr.status(), Request::Inactive); gsr.startRequest(); QCOMPARE(gsrss.count(), 1); QCOMPARE(gsr.status(), Request::Active); QCOMPARE(gsr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(gsr); QCOMPARE(gsrss.count(), 2); QCOMPARE(gsr.status(), Request::Finished); QCOMPARE(gsr.result().code(), Result::Succeeded); QCOMPARE(gsr.secret().data(), testSecret.data()); QCOMPARE(gsr.secret().type(), testSecret.type()); QCOMPARE(gsr.secret().filterData(), testSecret.filterData()); QCOMPARE(gsr.secret().name(), testSecret.name()); QCOMPARE(gsr.secret().collectionName(), testSecret.collectionName()); // test filtering, first with AND with both matching metadata field values, expect match Secret::FilterData filter; filter.insert(QLatin1String("domain"), testSecret.filterData(QLatin1String("domain"))); filter.insert(QLatin1String("test"), testSecret.filterData(QLatin1String("test"))); FindSecretsRequest fsr; fsr.setManager(&sm); QSignalSpy fsrss(&fsr, &FindSecretsRequest::statusChanged); fsr.setCollectionName(QLatin1String("testcollection")); QCOMPARE(fsr.collectionName(), QLatin1String("testcollection")); fsr.setStoragePluginName(DEFAULT_TEST_STORAGE_PLUGIN); QCOMPARE(fsr.storagePluginName(), DEFAULT_TEST_STORAGE_PLUGIN); fsr.setFilter(filter); QCOMPARE(fsr.filter(), filter); fsr.setFilterOperator(SecretManager::OperatorAnd); QCOMPARE(fsr.filterOperator(), SecretManager::OperatorAnd); fsr.setUserInteractionMode(SecretManager::PreventInteraction); QCOMPARE(fsr.userInteractionMode(), SecretManager::PreventInteraction); QCOMPARE(fsr.status(), Request::Inactive); fsr.startRequest(); QCOMPARE(fsrss.count(), 1); QCOMPARE(fsr.status(), Request::Active); QCOMPARE(fsr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(fsr); QCOMPARE(fsrss.count(), 2); QCOMPARE(fsr.status(), Request::Finished); QCOMPARE(fsr.result().code(), Result::Succeeded); QCOMPARE(fsr.identifiers().size(), 1); QCOMPARE(fsr.identifiers().at(0), testSecret.identifier()); // now test filtering with AND with one matching and one non-matching value, expect no-match filter.insert(QLatin1String("test"), QLatin1String("false")); fsr.setFilter(filter); fsr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(fsr); QCOMPARE(fsr.status(), Request::Finished); QCOMPARE(fsr.result().code(), Result::Succeeded); QCOMPARE(fsr.identifiers().size(), 0); // test filtering with OR with one matching and one non-matching value, expect match fsr.setFilterOperator(SecretManager::OperatorOr); fsr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(fsr); QCOMPARE(fsr.status(), Request::Finished); QCOMPARE(fsr.result().code(), Result::Succeeded); QCOMPARE(fsr.identifiers().size(), 1); QCOMPARE(fsr.identifiers().at(0), testSecret.identifier()); // test filtering with OR with zero matching values, expect no-match filter.insert(QLatin1String("domain"), QLatin1String("jolla.com")); fsr.setFilter(filter); fsr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(fsr); QCOMPARE(fsr.status(), Request::Finished); QCOMPARE(fsr.result().code(), Result::Succeeded); QCOMPARE(fsr.identifiers().size(), 0); // delete the secret DeleteSecretRequest dsr; dsr.setManager(&sm); QSignalSpy dsrss(&dsr, &DeleteSecretRequest::statusChanged); dsr.setIdentifier(testSecret.identifier()); QCOMPARE(dsr.identifier(), testSecret.identifier()); dsr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(dsr.userInteractionMode(), SecretManager::ApplicationInteraction); QCOMPARE(dsr.status(), Request::Inactive); dsr.startRequest(); QCOMPARE(dsrss.count(), 1); QCOMPARE(dsr.status(), Request::Active); QCOMPARE(dsr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(dsr); QCOMPARE(dsrss.count(), 2); QCOMPARE(dsr.status(), Request::Finished); QCOMPARE(dsr.result().code(), Result::Succeeded); // ensure that the delete worked properly. gsr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(gsr); QCOMPARE(gsr.result().code(), Result::Failed); // finally, clean up the collection DeleteCollectionRequest dcr; dcr.setManager(&sm); QSignalSpy dcrss(&dcr, &DeleteCollectionRequest::statusChanged); dcr.setCollectionName(QLatin1String("testcollection")); QCOMPARE(dcr.collectionName(), QLatin1String("testcollection")); dcr.setStoragePluginName(DEFAULT_TEST_STORAGE_PLUGIN); QCOMPARE(dcr.storagePluginName(), DEFAULT_TEST_STORAGE_PLUGIN); dcr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(dcr.userInteractionMode(), SecretManager::ApplicationInteraction); QCOMPARE(dcr.status(), Request::Inactive); dcr.startRequest(); QCOMPARE(dcrss.count(), 1); QCOMPARE(dcr.status(), Request::Active); QCOMPARE(dcr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(dcr); QCOMPARE(dcrss.count(), 2); QCOMPARE(dcr.status(), Request::Finished); QCOMPARE(dcr.result().code(), Result::Succeeded); } void tst_secretsrequests::devicelockStandaloneSecret() { // write the secret Secret testSecret(Secret::Identifier( QStringLiteral("testsecretname"), QString(), DEFAULT_TEST_STORAGE_PLUGIN)); testSecret.setData("testsecretvalue"); testSecret.setType(Secret::TypeBlob); testSecret.setFilterData(QLatin1String("domain"), QLatin1String("sailfishos.org")); testSecret.setFilterData(QLatin1String("test"), QLatin1String("true")); StoreSecretRequest ssr; ssr.setManager(&sm); QSignalSpy ssrss(&ssr, &StoreSecretRequest::statusChanged); ssr.setSecretStorageType(StoreSecretRequest::StandaloneDeviceLockSecret); QCOMPARE(ssr.secretStorageType(), StoreSecretRequest::StandaloneDeviceLockSecret); ssr.setDeviceLockUnlockSemantic(SecretManager::DeviceLockKeepUnlocked); QCOMPARE(ssr.deviceLockUnlockSemantic(), SecretManager::DeviceLockKeepUnlocked); ssr.setAccessControlMode(SecretManager::OwnerOnlyMode); QCOMPARE(ssr.accessControlMode(), SecretManager::OwnerOnlyMode); ssr.setEncryptionPluginName(DEFAULT_TEST_ENCRYPTION_PLUGIN); QCOMPARE(ssr.encryptionPluginName(), DEFAULT_TEST_ENCRYPTION_PLUGIN); ssr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(ssr.userInteractionMode(), SecretManager::ApplicationInteraction); ssr.setSecret(testSecret); QCOMPARE(ssr.secret(), testSecret); QCOMPARE(ssr.status(), Request::Inactive); ssr.startRequest(); QCOMPARE(ssrss.count(), 1); QCOMPARE(ssr.status(), Request::Active); QCOMPARE(ssr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(ssr); QCOMPARE(ssrss.count(), 2); QCOMPARE(ssr.status(), Request::Finished); QCOMPARE(ssr.result().code(), Result::Succeeded); // read the secret StoredSecretRequest gsr; gsr.setManager(&sm); QSignalSpy gsrss(&gsr, &StoredSecretRequest::statusChanged); gsr.setIdentifier(testSecret.identifier()); QCOMPARE(gsr.identifier(), testSecret.identifier()); gsr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(gsr.userInteractionMode(), SecretManager::ApplicationInteraction); QCOMPARE(gsr.status(), Request::Inactive); gsr.startRequest(); QCOMPARE(gsrss.count(), 1); QCOMPARE(gsr.status(), Request::Active); QCOMPARE(gsr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(gsr); QCOMPARE(gsrss.count(), 2); QCOMPARE(gsr.status(), Request::Finished); QCOMPARE(gsr.result().code(), Result::Succeeded); QCOMPARE(gsr.secret().data(), testSecret.data()); QCOMPARE(gsr.secret().type(), testSecret.type()); QCOMPARE(gsr.secret().filterData(), testSecret.filterData()); QCOMPARE(gsr.secret().name(), testSecret.name()); QCOMPARE(gsr.secret().collectionName(), testSecret.collectionName()); // delete the secret DeleteSecretRequest dsr; dsr.setManager(&sm); QSignalSpy dsrss(&dsr, &DeleteSecretRequest::statusChanged); dsr.setIdentifier(testSecret.identifier()); QCOMPARE(dsr.identifier(), testSecret.identifier()); dsr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(dsr.userInteractionMode(), SecretManager::ApplicationInteraction); QCOMPARE(dsr.status(), Request::Inactive); dsr.startRequest(); QCOMPARE(dsrss.count(), 1); QCOMPARE(dsr.status(), Request::Active); QCOMPARE(dsr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(dsr); QCOMPARE(dsrss.count(), 2); QCOMPARE(dsr.status(), Request::Finished); QCOMPARE(dsr.result().code(), Result::Succeeded); // ensure that the delete worked properly. gsr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(gsr); QCOMPARE(gsr.result().code(), Result::Failed); } void tst_secretsrequests::customlockCollection() { // construct the in-process authentication key UI. QQuickView v(QUrl::fromLocalFile(QStringLiteral("%1/tst_secretsrequests.qml").arg(QCoreApplication::applicationDirPath()))); v.show(); QObject *interactionView = v.rootObject()->findChild<QObject*>("interactionview"); QVERIFY(interactionView); QMetaObject::invokeMethod(interactionView, "setSecretManager", Qt::DirectConnection, Q_ARG(QObject*, &sm)); // create a new custom-lock collection CreateCollectionRequest ccr; ccr.setManager(&sm); QSignalSpy ccrss(&ccr, &CreateCollectionRequest::statusChanged); ccr.setCollectionLockType(CreateCollectionRequest::CustomLock); QCOMPARE(ccr.collectionLockType(), CreateCollectionRequest::CustomLock); ccr.setCollectionName(QLatin1String("testcollection")); QCOMPARE(ccr.collectionName(), QLatin1String("testcollection")); ccr.setStoragePluginName(DEFAULT_TEST_STORAGE_PLUGIN); QCOMPARE(ccr.storagePluginName(), DEFAULT_TEST_STORAGE_PLUGIN); ccr.setEncryptionPluginName(DEFAULT_TEST_ENCRYPTION_PLUGIN); QCOMPARE(ccr.encryptionPluginName(), DEFAULT_TEST_ENCRYPTION_PLUGIN); ccr.setAuthenticationPluginName(IN_APP_TEST_AUTHENTICATION_PLUGIN); QCOMPARE(ccr.authenticationPluginName(), IN_APP_TEST_AUTHENTICATION_PLUGIN); ccr.setCustomLockUnlockSemantic(SecretManager::CustomLockKeepUnlocked); QCOMPARE(ccr.customLockUnlockSemantic(), SecretManager::CustomLockKeepUnlocked); ccr.setAccessControlMode(SecretManager::OwnerOnlyMode); QCOMPARE(ccr.accessControlMode(), SecretManager::OwnerOnlyMode); ccr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(ccr.userInteractionMode(), SecretManager::ApplicationInteraction); QCOMPARE(ccr.status(), Request::Inactive); ccr.startRequest(); QCOMPARE(ccrss.count(), 1); QCOMPARE(ccr.status(), Request::Active); QCOMPARE(ccr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(ccr); QCOMPARE(ccrss.count(), 2); QCOMPARE(ccr.status(), Request::Finished); QCOMPARE(ccr.result().code(), Result::Succeeded); // delete the collection DeleteCollectionRequest dcr; dcr.setManager(&sm); QSignalSpy dcrss(&dcr, &DeleteCollectionRequest::statusChanged); dcr.setCollectionName(QLatin1String("testcollection")); QCOMPARE(dcr.collectionName(), QLatin1String("testcollection")); dcr.setStoragePluginName(DEFAULT_TEST_STORAGE_PLUGIN); QCOMPARE(dcr.storagePluginName(), DEFAULT_TEST_STORAGE_PLUGIN); dcr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(dcr.userInteractionMode(), SecretManager::ApplicationInteraction); QCOMPARE(dcr.status(), Request::Inactive); dcr.startRequest(); QCOMPARE(dcrss.count(), 1); QCOMPARE(dcr.status(), Request::Active); QCOMPARE(dcr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(dcr); QCOMPARE(dcrss.count(), 2); QCOMPARE(dcr.status(), Request::Finished); QCOMPARE(dcr.result().code(), Result::Succeeded); } void tst_secretsrequests::customlockCollectionSecret() { // construct the in-process authentication key UI. QQuickView v(QUrl::fromLocalFile(QStringLiteral("%1/tst_secretsrequests.qml").arg(QCoreApplication::applicationDirPath()))); v.show(); QObject *interactionView = v.rootObject()->findChild<QObject*>("interactionview"); QVERIFY(interactionView); QMetaObject::invokeMethod(interactionView, "setSecretManager", Qt::DirectConnection, Q_ARG(QObject*, &sm)); // create a new custom-lock collection CreateCollectionRequest ccr; ccr.setManager(&sm); QSignalSpy ccrss(&ccr, &CreateCollectionRequest::statusChanged); ccr.setCollectionLockType(CreateCollectionRequest::CustomLock); QCOMPARE(ccr.collectionLockType(), CreateCollectionRequest::CustomLock); ccr.setCollectionName(QLatin1String("testcollection")); QCOMPARE(ccr.collectionName(), QLatin1String("testcollection")); ccr.setStoragePluginName(DEFAULT_TEST_STORAGE_PLUGIN); QCOMPARE(ccr.storagePluginName(), DEFAULT_TEST_STORAGE_PLUGIN); ccr.setEncryptionPluginName(DEFAULT_TEST_ENCRYPTION_PLUGIN); QCOMPARE(ccr.encryptionPluginName(), DEFAULT_TEST_ENCRYPTION_PLUGIN); ccr.setAuthenticationPluginName(IN_APP_TEST_AUTHENTICATION_PLUGIN); QCOMPARE(ccr.authenticationPluginName(), IN_APP_TEST_AUTHENTICATION_PLUGIN); ccr.setCustomLockUnlockSemantic(SecretManager::CustomLockKeepUnlocked); QCOMPARE(ccr.customLockUnlockSemantic(), SecretManager::CustomLockKeepUnlocked); ccr.setAccessControlMode(SecretManager::OwnerOnlyMode); QCOMPARE(ccr.accessControlMode(), SecretManager::OwnerOnlyMode); ccr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(ccr.userInteractionMode(), SecretManager::ApplicationInteraction); QCOMPARE(ccr.status(), Request::Inactive); ccr.startRequest(); QCOMPARE(ccrss.count(), 1); QCOMPARE(ccr.status(), Request::Active); QCOMPARE(ccr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(ccr); QCOMPARE(ccrss.count(), 2); QCOMPARE(ccr.status(), Request::Finished); QCOMPARE(ccr.result().code(), Result::Succeeded); // store a new secret into that collection Secret testSecret( Secret::Identifier( QLatin1String("testsecretname"), QLatin1String("testcollection"), DEFAULT_TEST_STORAGE_PLUGIN)); testSecret.setData("testsecretvalue"); testSecret.setType(Secret::TypeBlob); testSecret.setFilterData(QLatin1String("domain"), QLatin1String("sailfishos.org")); testSecret.setFilterData(QLatin1String("test"), QLatin1String("true")); StoreSecretRequest ssr; ssr.setManager(&sm); QSignalSpy ssrss(&ssr, &StoreSecretRequest::statusChanged); ssr.setSecretStorageType(StoreSecretRequest::CollectionSecret); QCOMPARE(ssr.secretStorageType(), StoreSecretRequest::CollectionSecret); ssr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(ssr.userInteractionMode(), SecretManager::ApplicationInteraction); ssr.setSecret(testSecret); QCOMPARE(ssr.secret(), testSecret); QCOMPARE(ssr.status(), Request::Inactive); ssr.startRequest(); QCOMPARE(ssrss.count(), 1); QCOMPARE(ssr.status(), Request::Active); QCOMPARE(ssr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(ssr); QCOMPARE(ssrss.count(), 2); QCOMPARE(ssr.status(), Request::Finished); QCOMPARE(ssr.result().code(), Result::Succeeded); // retrieve the secret StoredSecretRequest gsr; gsr.setManager(&sm); QSignalSpy gsrss(&gsr, &StoredSecretRequest::statusChanged); gsr.setIdentifier(testSecret.identifier()); QCOMPARE(gsr.identifier(), testSecret.identifier()); gsr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(gsr.userInteractionMode(), SecretManager::ApplicationInteraction); QCOMPARE(gsr.status(), Request::Inactive); gsr.startRequest(); QCOMPARE(gsrss.count(), 1); QCOMPARE(gsr.status(), Request::Active); QCOMPARE(gsr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(gsr); QCOMPARE(gsrss.count(), 2); QCOMPARE(gsr.status(), Request::Finished); QCOMPARE(gsr.result().code(), Result::Succeeded); QCOMPARE(gsr.secret(), testSecret); // delete the secret DeleteSecretRequest dsr; dsr.setManager(&sm); QSignalSpy dsrss(&dsr, &DeleteSecretRequest::statusChanged); dsr.setIdentifier(testSecret.identifier()); QCOMPARE(dsr.identifier(), testSecret.identifier()); dsr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(dsr.userInteractionMode(), SecretManager::ApplicationInteraction); QCOMPARE(dsr.status(), Request::Inactive); dsr.startRequest(); QCOMPARE(dsrss.count(), 1); QCOMPARE(dsr.status(), Request::Active); QCOMPARE(dsr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(dsr); QCOMPARE(dsrss.count(), 2); QCOMPARE(dsr.status(), Request::Finished); QCOMPARE(dsr.result().code(), Result::Succeeded); // ensure that the delete worked properly. gsr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(gsr); QCOMPARE(gsr.result().code(), Result::Failed); // finally, clean up the collection DeleteCollectionRequest dcr; dcr.setManager(&sm); QSignalSpy dcrss(&dcr, &DeleteCollectionRequest::statusChanged); dcr.setCollectionName(QLatin1String("testcollection")); QCOMPARE(dcr.collectionName(), QLatin1String("testcollection")); dcr.setStoragePluginName(DEFAULT_TEST_STORAGE_PLUGIN); QCOMPARE(dcr.storagePluginName(), DEFAULT_TEST_STORAGE_PLUGIN); dcr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(dcr.userInteractionMode(), SecretManager::ApplicationInteraction); QCOMPARE(dcr.status(), Request::Inactive); dcr.startRequest(); QCOMPARE(dcrss.count(), 1); QCOMPARE(dcr.status(), Request::Active); QCOMPARE(dcr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(dcr); QCOMPARE(dcrss.count(), 2); QCOMPARE(dcr.status(), Request::Finished); QCOMPARE(dcr.result().code(), Result::Succeeded); } void tst_secretsrequests::customlockStandaloneSecret() { // construct the in-process authentication key UI. QQuickView v(QUrl::fromLocalFile(QStringLiteral("%1/tst_secretsrequests.qml").arg(QCoreApplication::applicationDirPath()))); v.show(); QObject *interactionView = v.rootObject()->findChild<QObject*>("interactionview"); QVERIFY(interactionView); QMetaObject::invokeMethod(interactionView, "setSecretManager", Qt::DirectConnection, Q_ARG(QObject*, &sm)); Secret testSecret(Secret::Identifier( QLatin1String("testsecretname"), QString(), DEFAULT_TEST_STORAGE_PLUGIN)); testSecret.setData("testsecretvalue"); testSecret.setType(Secret::TypeBlob); testSecret.setFilterData(QLatin1String("domain"), QLatin1String("sailfishos.org")); testSecret.setFilterData(QLatin1String("test"), QLatin1String("true")); // store the secret StoreSecretRequest ssr; ssr.setManager(&sm); QSignalSpy ssrss(&ssr, &StoreSecretRequest::statusChanged); ssr.setSecretStorageType(StoreSecretRequest::StandaloneCustomLockSecret); QCOMPARE(ssr.secretStorageType(), StoreSecretRequest::StandaloneCustomLockSecret); ssr.setCustomLockUnlockSemantic(SecretManager::CustomLockKeepUnlocked); QCOMPARE(ssr.customLockUnlockSemantic(), SecretManager::CustomLockKeepUnlocked); ssr.setAccessControlMode(SecretManager::OwnerOnlyMode); QCOMPARE(ssr.accessControlMode(), SecretManager::OwnerOnlyMode); ssr.setEncryptionPluginName(DEFAULT_TEST_ENCRYPTION_PLUGIN); QCOMPARE(ssr.encryptionPluginName(), DEFAULT_TEST_ENCRYPTION_PLUGIN); ssr.setAuthenticationPluginName(IN_APP_TEST_AUTHENTICATION_PLUGIN); QCOMPARE(ssr.authenticationPluginName(), IN_APP_TEST_AUTHENTICATION_PLUGIN); ssr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(ssr.userInteractionMode(), SecretManager::ApplicationInteraction); ssr.setSecret(testSecret); QCOMPARE(ssr.secret(), testSecret); QCOMPARE(ssr.status(), Request::Inactive); ssr.startRequest(); QCOMPARE(ssrss.count(), 1); QCOMPARE(ssr.status(), Request::Active); QCOMPARE(ssr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(ssr); QCOMPARE(ssrss.count(), 2); QCOMPARE(ssr.status(), Request::Finished); QCOMPARE(ssr.result().code(), Result::Succeeded); // retrieve the secret StoredSecretRequest gsr; gsr.setManager(&sm); QSignalSpy gsrss(&gsr, &StoredSecretRequest::statusChanged); gsr.setIdentifier(testSecret.identifier()); QCOMPARE(gsr.identifier(), testSecret.identifier()); gsr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(gsr.userInteractionMode(), SecretManager::ApplicationInteraction); QCOMPARE(gsr.status(), Request::Inactive); gsr.startRequest(); QCOMPARE(gsrss.count(), 1); QCOMPARE(gsr.status(), Request::Active); QCOMPARE(gsr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(gsr); QCOMPARE(gsrss.count(), 2); QCOMPARE(gsr.status(), Request::Finished); QCOMPARE(gsr.result().code(), Result::Succeeded); QCOMPARE(gsr.secret().data(), testSecret.data()); QCOMPARE(gsr.secret().type(), testSecret.type()); QCOMPARE(gsr.secret().filterData(), testSecret.filterData()); QCOMPARE(gsr.secret().name(), testSecret.name()); QCOMPARE(gsr.secret().collectionName(), testSecret.collectionName()); // delete the secret DeleteSecretRequest dsr; dsr.setManager(&sm); QSignalSpy dsrss(&dsr, &DeleteSecretRequest::statusChanged); dsr.setIdentifier(testSecret.identifier()); QCOMPARE(dsr.identifier(), testSecret.identifier()); dsr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(dsr.userInteractionMode(), SecretManager::ApplicationInteraction); QCOMPARE(dsr.status(), Request::Inactive); dsr.startRequest(); QCOMPARE(dsrss.count(), 1); QCOMPARE(dsr.status(), Request::Active); QCOMPARE(dsr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(dsr); QCOMPARE(dsrss.count(), 2); QCOMPARE(dsr.status(), Request::Finished); QCOMPARE(dsr.result().code(), Result::Succeeded); // ensure that the delete worked properly. gsr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(gsr); QCOMPARE(gsr.result().code(), Result::Failed); } void tst_secretsrequests::encryptedStorageCollection() { // construct the in-process authentication key UI. QQuickView v(QUrl::fromLocalFile(QStringLiteral("%1/tst_secretsrequests.qml").arg(QCoreApplication::applicationDirPath()))); v.show(); QObject *interactionView = v.rootObject()->findChild<QObject*>("interactionview"); QVERIFY(interactionView); QMetaObject::invokeMethod(interactionView, "setSecretManager", Qt::DirectConnection, Q_ARG(QObject*, &sm)); // create a new custom-lock collection stored in by an encrypted storage plugin CreateCollectionRequest ccr; ccr.setManager(&sm); QSignalSpy ccrss(&ccr, &CreateCollectionRequest::statusChanged); ccr.setCollectionLockType(CreateCollectionRequest::CustomLock); QCOMPARE(ccr.collectionLockType(), CreateCollectionRequest::CustomLock); ccr.setCollectionName(QLatin1String("testencryptedcollection")); QCOMPARE(ccr.collectionName(), QLatin1String("testencryptedcollection")); ccr.setStoragePluginName(DEFAULT_TEST_ENCRYPTEDSTORAGE_PLUGIN); QCOMPARE(ccr.storagePluginName(), DEFAULT_TEST_ENCRYPTEDSTORAGE_PLUGIN); ccr.setEncryptionPluginName(DEFAULT_TEST_ENCRYPTEDSTORAGE_PLUGIN); QCOMPARE(ccr.encryptionPluginName(), DEFAULT_TEST_ENCRYPTEDSTORAGE_PLUGIN); ccr.setAuthenticationPluginName(IN_APP_TEST_AUTHENTICATION_PLUGIN); QCOMPARE(ccr.authenticationPluginName(), IN_APP_TEST_AUTHENTICATION_PLUGIN); ccr.setCustomLockUnlockSemantic(SecretManager::CustomLockKeepUnlocked); QCOMPARE(ccr.customLockUnlockSemantic(), SecretManager::CustomLockKeepUnlocked); ccr.setAccessControlMode(SecretManager::OwnerOnlyMode); QCOMPARE(ccr.accessControlMode(), SecretManager::OwnerOnlyMode); ccr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(ccr.userInteractionMode(), SecretManager::ApplicationInteraction); QCOMPARE(ccr.status(), Request::Inactive); ccr.startRequest(); QCOMPARE(ccrss.count(), 1); QCOMPARE(ccr.status(), Request::Active); QCOMPARE(ccr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(ccr); QCOMPARE(ccrss.count(), 2); QCOMPARE(ccr.status(), Request::Finished); QCOMPARE(ccr.result().code(), Result::Succeeded); // store a secret into the collection Secret testSecret( Secret::Identifier( QLatin1String("testsecretname"), QLatin1String("testencryptedcollection"), DEFAULT_TEST_ENCRYPTEDSTORAGE_PLUGIN)); testSecret.setData("testsecretvalue"); testSecret.setType(Secret::TypeBlob); testSecret.setFilterData(QLatin1String("domain"), QLatin1String("sailfishos.org")); testSecret.setFilterData(QLatin1String("test"), QLatin1String("true")); StoreSecretRequest ssr; ssr.setManager(&sm); QSignalSpy ssrss(&ssr, &StoreSecretRequest::statusChanged); ssr.setSecretStorageType(StoreSecretRequest::CollectionSecret); QCOMPARE(ssr.secretStorageType(), StoreSecretRequest::CollectionSecret); ssr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(ssr.userInteractionMode(), SecretManager::ApplicationInteraction); ssr.setSecret(testSecret); QCOMPARE(ssr.secret(), testSecret); QCOMPARE(ssr.status(), Request::Inactive); ssr.startRequest(); QCOMPARE(ssrss.count(), 1); QCOMPARE(ssr.status(), Request::Active); QCOMPARE(ssr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(ssr); QCOMPARE(ssrss.count(), 2); QCOMPARE(ssr.status(), Request::Finished); QCOMPARE(ssr.result().code(), Result::Succeeded); // retrieve the secret, ensure it matches StoredSecretRequest gsr; gsr.setManager(&sm); QSignalSpy gsrss(&gsr, &StoredSecretRequest::statusChanged); gsr.setIdentifier(testSecret.identifier()); QCOMPARE(gsr.identifier(), testSecret.identifier()); gsr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(gsr.userInteractionMode(), SecretManager::ApplicationInteraction); QCOMPARE(gsr.status(), Request::Inactive); gsr.startRequest(); QCOMPARE(gsrss.count(), 1); QCOMPARE(gsr.status(), Request::Active); QCOMPARE(gsr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(gsr); QCOMPARE(gsrss.count(), 2); QCOMPARE(gsr.status(), Request::Finished); QCOMPARE(gsr.result().code(), Result::Succeeded); QCOMPARE(gsr.secret().data(), testSecret.data()); // delete the secret DeleteSecretRequest dsr; dsr.setManager(&sm); QSignalSpy dsrss(&dsr, &DeleteSecretRequest::statusChanged); dsr.setIdentifier(testSecret.identifier()); QCOMPARE(dsr.identifier(), testSecret.identifier()); dsr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(dsr.userInteractionMode(), SecretManager::ApplicationInteraction); QCOMPARE(dsr.status(), Request::Inactive); dsr.startRequest(); QCOMPARE(dsrss.count(), 1); QCOMPARE(dsr.status(), Request::Active); QCOMPARE(dsr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(dsr); QCOMPARE(dsrss.count(), 2); QCOMPARE(dsr.status(), Request::Finished); QCOMPARE(dsr.result().code(), Result::Succeeded); // ensure that the delete worked properly. gsr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(gsr); QCOMPARE(gsr.result().code(), Result::Failed); // finally, clean up the collection DeleteCollectionRequest dcr; dcr.setManager(&sm); QSignalSpy dcrss(&dcr, &DeleteCollectionRequest::statusChanged); dcr.setCollectionName(QLatin1String("testencryptedcollection")); QCOMPARE(dcr.collectionName(), QLatin1String("testencryptedcollection")); dcr.setStoragePluginName(DEFAULT_TEST_ENCRYPTEDSTORAGE_PLUGIN); QCOMPARE(dcr.storagePluginName(), DEFAULT_TEST_ENCRYPTEDSTORAGE_PLUGIN); dcr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(dcr.userInteractionMode(), SecretManager::ApplicationInteraction); QCOMPARE(dcr.status(), Request::Inactive); dcr.startRequest(); QCOMPARE(dcrss.count(), 1); QCOMPARE(dcr.status(), Request::Active); QCOMPARE(dcr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(dcr); QCOMPARE(dcrss.count(), 2); QCOMPARE(dcr.status(), Request::Finished); QCOMPARE(dcr.result().code(), Result::Succeeded); } void tst_secretsrequests::storeUserSecret() { // construct the in-process authentication key UI. QQuickView v(QUrl::fromLocalFile(QStringLiteral("%1/tst_secretsrequests.qml").arg(QCoreApplication::applicationDirPath()))); v.show(); QObject *interactionView = v.rootObject()->findChild<QObject*>("interactionview"); QVERIFY(interactionView); QMetaObject::invokeMethod(interactionView, "setSecretManager", Qt::DirectConnection, Q_ARG(QObject*, &sm)); // in this test, the secret data is requested from the user by the secrets service. { // test storing the secret in a device-locked collection. // create a collection CreateCollectionRequest ccr; ccr.setManager(&sm); QSignalSpy ccrss(&ccr, &CreateCollectionRequest::statusChanged); ccr.setCollectionLockType(CreateCollectionRequest::DeviceLock); QCOMPARE(ccr.collectionLockType(), CreateCollectionRequest::DeviceLock); ccr.setCollectionName(QLatin1String("testcollection")); QCOMPARE(ccr.collectionName(), QLatin1String("testcollection")); ccr.setStoragePluginName(DEFAULT_TEST_STORAGE_PLUGIN); QCOMPARE(ccr.storagePluginName(), DEFAULT_TEST_STORAGE_PLUGIN); ccr.setEncryptionPluginName(DEFAULT_TEST_ENCRYPTION_PLUGIN); QCOMPARE(ccr.encryptionPluginName(), DEFAULT_TEST_ENCRYPTION_PLUGIN); ccr.setDeviceLockUnlockSemantic(SecretManager::DeviceLockKeepUnlocked); QCOMPARE(ccr.deviceLockUnlockSemantic(), SecretManager::DeviceLockKeepUnlocked); ccr.setAccessControlMode(SecretManager::OwnerOnlyMode); QCOMPARE(ccr.accessControlMode(), SecretManager::OwnerOnlyMode); QCOMPARE(ccr.status(), Request::Inactive); ccr.startRequest(); QCOMPARE(ccrss.count(), 1); QCOMPARE(ccr.status(), Request::Active); QCOMPARE(ccr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(ccr); QCOMPARE(ccrss.count(), 2); QCOMPARE(ccr.status(), Request::Finished); QCOMPARE(ccr.result().code(), Result::Succeeded); // store a new secret into the collection, where the secret data is requested from the user. Secret testSecret(Secret::Identifier( QLatin1String("testsecretname"), QLatin1String("testcollection"), DEFAULT_TEST_STORAGE_PLUGIN)); testSecret.setType(Secret::TypeBlob); testSecret.setFilterData(QLatin1String("domain"), QLatin1String("sailfishos.org")); testSecret.setFilterData(QLatin1String("test"), QLatin1String("true")); InteractionParameters uiParams; uiParams.setInputType(InteractionParameters::AlphaNumericInput); uiParams.setEchoMode(InteractionParameters::NormalEcho); uiParams.setPromptText(tr("Enter the secret data")); uiParams.setAuthenticationPluginName(IN_APP_TEST_AUTHENTICATION_PLUGIN); StoreSecretRequest ssr; ssr.setManager(&sm); QSignalSpy ssrss(&ssr, &StoreSecretRequest::statusChanged); ssr.setSecretStorageType(StoreSecretRequest::CollectionSecret); QCOMPARE(ssr.secretStorageType(), StoreSecretRequest::CollectionSecret); ssr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(ssr.userInteractionMode(), SecretManager::ApplicationInteraction); ssr.setSecret(testSecret); QCOMPARE(ssr.secret(), testSecret); ssr.setInteractionParameters(uiParams); QCOMPARE(ssr.interactionParameters(), uiParams); QCOMPARE(ssr.status(), Request::Inactive); ssr.startRequest(); QCOMPARE(ssrss.count(), 1); QCOMPARE(ssr.status(), Request::Active); QCOMPARE(ssr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(ssr); QCOMPARE(ssrss.count(), 2); QCOMPARE(ssr.status(), Request::Finished); QCOMPARE(ssr.result().code(), Result::Succeeded); // retrieve the secret, ensure it has the expected data. StoredSecretRequest gsr; gsr.setManager(&sm); QSignalSpy gsrss(&gsr, &StoredSecretRequest::statusChanged); gsr.setIdentifier(testSecret.identifier()); QCOMPARE(gsr.identifier(), testSecret.identifier()); gsr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(gsr.userInteractionMode(), SecretManager::ApplicationInteraction); QCOMPARE(gsr.status(), Request::Inactive); gsr.startRequest(); QCOMPARE(gsrss.count(), 1); QCOMPARE(gsr.status(), Request::Active); QCOMPARE(gsr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(gsr); QCOMPARE(gsrss.count(), 2); QCOMPARE(gsr.status(), Request::Finished); QCOMPARE(gsr.result().code(), Result::Succeeded); Secret expectedSecret = testSecret; expectedSecret.setData("example custom password"); QCOMPARE(gsr.secret(), expectedSecret); // delete the secret DeleteSecretRequest dsr; dsr.setManager(&sm); QSignalSpy dsrss(&dsr, &DeleteSecretRequest::statusChanged); dsr.setIdentifier(testSecret.identifier()); QCOMPARE(dsr.identifier(), testSecret.identifier()); dsr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(dsr.userInteractionMode(), SecretManager::ApplicationInteraction); QCOMPARE(dsr.status(), Request::Inactive); dsr.startRequest(); QCOMPARE(dsrss.count(), 1); QCOMPARE(dsr.status(), Request::Active); QCOMPARE(dsr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(dsr); QCOMPARE(dsrss.count(), 2); QCOMPARE(dsr.status(), Request::Finished); QCOMPARE(dsr.result().code(), Result::Succeeded); // ensure that the delete worked properly. gsr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(gsr); QCOMPARE(gsr.result().code(), Result::Failed); // finally, clean up the collection DeleteCollectionRequest dcr; dcr.setManager(&sm); QSignalSpy dcrss(&dcr, &DeleteCollectionRequest::statusChanged); dcr.setCollectionName(QLatin1String("testcollection")); QCOMPARE(dcr.collectionName(), QLatin1String("testcollection")); dcr.setStoragePluginName(DEFAULT_TEST_STORAGE_PLUGIN); QCOMPARE(dcr.storagePluginName(), DEFAULT_TEST_STORAGE_PLUGIN); dcr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(dcr.userInteractionMode(), SecretManager::ApplicationInteraction); QCOMPARE(dcr.status(), Request::Inactive); dcr.startRequest(); QCOMPARE(dcrss.count(), 1); QCOMPARE(dcr.status(), Request::Active); QCOMPARE(dcr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(dcr); QCOMPARE(dcrss.count(), 2); QCOMPARE(dcr.status(), Request::Finished); QCOMPARE(dcr.result().code(), Result::Succeeded); } { // now a standalone device-locked secret. // write the secret Secret testSecret(Secret::Identifier( QStringLiteral("testsecretname"), QString(), DEFAULT_TEST_STORAGE_PLUGIN)); testSecret.setType(Secret::TypeBlob); testSecret.setFilterData(QLatin1String("domain"), QLatin1String("sailfishos.org")); testSecret.setFilterData(QLatin1String("test"), QLatin1String("true")); InteractionParameters uiParams; uiParams.setInputType(InteractionParameters::AlphaNumericInput); uiParams.setEchoMode(InteractionParameters::NormalEcho); uiParams.setPromptText(tr("Enter the secret data")); uiParams.setAuthenticationPluginName(IN_APP_TEST_AUTHENTICATION_PLUGIN); StoreSecretRequest ssr; ssr.setManager(&sm); QSignalSpy ssrss(&ssr, &StoreSecretRequest::statusChanged); ssr.setSecretStorageType(StoreSecretRequest::StandaloneDeviceLockSecret); QCOMPARE(ssr.secretStorageType(), StoreSecretRequest::StandaloneDeviceLockSecret); ssr.setDeviceLockUnlockSemantic(SecretManager::DeviceLockKeepUnlocked); QCOMPARE(ssr.deviceLockUnlockSemantic(), SecretManager::DeviceLockKeepUnlocked); ssr.setAccessControlMode(SecretManager::OwnerOnlyMode); QCOMPARE(ssr.accessControlMode(), SecretManager::OwnerOnlyMode); ssr.setEncryptionPluginName(DEFAULT_TEST_ENCRYPTION_PLUGIN); QCOMPARE(ssr.encryptionPluginName(), DEFAULT_TEST_ENCRYPTION_PLUGIN); ssr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(ssr.userInteractionMode(), SecretManager::ApplicationInteraction); ssr.setSecret(testSecret); QCOMPARE(ssr.secret(), testSecret); ssr.setInteractionParameters(uiParams); QCOMPARE(ssr.interactionParameters(), uiParams); QCOMPARE(ssr.status(), Request::Inactive); ssr.startRequest(); QCOMPARE(ssrss.count(), 1); QCOMPARE(ssr.status(), Request::Active); QCOMPARE(ssr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(ssr); QCOMPARE(ssrss.count(), 2); QCOMPARE(ssr.status(), Request::Finished); QCOMPARE(ssr.result().code(), Result::Succeeded); // read the secret StoredSecretRequest gsr; gsr.setManager(&sm); QSignalSpy gsrss(&gsr, &StoredSecretRequest::statusChanged); gsr.setIdentifier(testSecret.identifier()); QCOMPARE(gsr.identifier(), testSecret.identifier()); gsr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(gsr.userInteractionMode(), SecretManager::ApplicationInteraction); QCOMPARE(gsr.status(), Request::Inactive); gsr.startRequest(); QCOMPARE(gsrss.count(), 1); QCOMPARE(gsr.status(), Request::Active); QCOMPARE(gsr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(gsr); QCOMPARE(gsrss.count(), 2); QCOMPARE(gsr.status(), Request::Finished); QCOMPARE(gsr.result().code(), Result::Succeeded); Secret expectedSecret(testSecret); expectedSecret.setData("example custom password"); QCOMPARE(gsr.secret(), expectedSecret); // delete the secret DeleteSecretRequest dsr; dsr.setManager(&sm); QSignalSpy dsrss(&dsr, &DeleteSecretRequest::statusChanged); dsr.setIdentifier(testSecret.identifier()); QCOMPARE(dsr.identifier(), testSecret.identifier()); dsr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(dsr.userInteractionMode(), SecretManager::ApplicationInteraction); QCOMPARE(dsr.status(), Request::Inactive); dsr.startRequest(); QCOMPARE(dsrss.count(), 1); QCOMPARE(dsr.status(), Request::Active); QCOMPARE(dsr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(dsr); QCOMPARE(dsrss.count(), 2); QCOMPARE(dsr.status(), Request::Finished); QCOMPARE(dsr.result().code(), Result::Succeeded); // ensure that the delete worked properly. gsr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(gsr); QCOMPARE(gsr.result().code(), Result::Failed); } { // now a custom-locked collection secret. // create a new custom-lock collection CreateCollectionRequest ccr; ccr.setManager(&sm); QSignalSpy ccrss(&ccr, &CreateCollectionRequest::statusChanged); ccr.setCollectionLockType(CreateCollectionRequest::CustomLock); QCOMPARE(ccr.collectionLockType(), CreateCollectionRequest::CustomLock); ccr.setCollectionName(QLatin1String("testcollection")); QCOMPARE(ccr.collectionName(), QLatin1String("testcollection")); ccr.setStoragePluginName(DEFAULT_TEST_STORAGE_PLUGIN); QCOMPARE(ccr.storagePluginName(), DEFAULT_TEST_STORAGE_PLUGIN); ccr.setEncryptionPluginName(DEFAULT_TEST_ENCRYPTION_PLUGIN); QCOMPARE(ccr.encryptionPluginName(), DEFAULT_TEST_ENCRYPTION_PLUGIN); ccr.setAuthenticationPluginName(IN_APP_TEST_AUTHENTICATION_PLUGIN); QCOMPARE(ccr.authenticationPluginName(), IN_APP_TEST_AUTHENTICATION_PLUGIN); ccr.setCustomLockUnlockSemantic(SecretManager::CustomLockKeepUnlocked); QCOMPARE(ccr.customLockUnlockSemantic(), SecretManager::CustomLockKeepUnlocked); ccr.setAccessControlMode(SecretManager::OwnerOnlyMode); QCOMPARE(ccr.accessControlMode(), SecretManager::OwnerOnlyMode); ccr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(ccr.userInteractionMode(), SecretManager::ApplicationInteraction); QCOMPARE(ccr.status(), Request::Inactive); ccr.startRequest(); QCOMPARE(ccrss.count(), 1); QCOMPARE(ccr.status(), Request::Active); QCOMPARE(ccr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(ccr); QCOMPARE(ccrss.count(), 2); QCOMPARE(ccr.status(), Request::Finished); QCOMPARE(ccr.result().code(), Result::Succeeded); // store a new secret into that collection Secret testSecret( Secret::Identifier( QLatin1String("testsecretname"), QLatin1String("testcollection"), DEFAULT_TEST_STORAGE_PLUGIN)); testSecret.setData("testsecretvalue"); testSecret.setFilterData(QLatin1String("domain"), QLatin1String("sailfishos.org")); testSecret.setFilterData(QLatin1String("test"), QLatin1String("true")); InteractionParameters uiParams; uiParams.setInputType(InteractionParameters::AlphaNumericInput); uiParams.setEchoMode(InteractionParameters::NormalEcho); uiParams.setPromptText(tr("Enter the secret data")); uiParams.setAuthenticationPluginName(IN_APP_TEST_AUTHENTICATION_PLUGIN); StoreSecretRequest ssr; ssr.setManager(&sm); QSignalSpy ssrss(&ssr, &StoreSecretRequest::statusChanged); ssr.setSecretStorageType(StoreSecretRequest::CollectionSecret); QCOMPARE(ssr.secretStorageType(), StoreSecretRequest::CollectionSecret); ssr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(ssr.userInteractionMode(), SecretManager::ApplicationInteraction); ssr.setSecret(testSecret); QCOMPARE(ssr.secret(), testSecret); ssr.setInteractionParameters(uiParams); QCOMPARE(ssr.interactionParameters(), uiParams); QCOMPARE(ssr.status(), Request::Inactive); ssr.startRequest(); QCOMPARE(ssrss.count(), 1); QCOMPARE(ssr.status(), Request::Active); QCOMPARE(ssr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(ssr); QCOMPARE(ssrss.count(), 2); QCOMPARE(ssr.status(), Request::Finished); QCOMPARE(ssr.result().code(), Result::Succeeded); // retrieve the secret StoredSecretRequest gsr; gsr.setManager(&sm); QSignalSpy gsrss(&gsr, &StoredSecretRequest::statusChanged); gsr.setIdentifier(testSecret.identifier()); QCOMPARE(gsr.identifier(), testSecret.identifier()); gsr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(gsr.userInteractionMode(), SecretManager::ApplicationInteraction); QCOMPARE(gsr.status(), Request::Inactive); gsr.startRequest(); QCOMPARE(gsrss.count(), 1); QCOMPARE(gsr.status(), Request::Active); QCOMPARE(gsr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(gsr); QCOMPARE(gsrss.count(), 2); QCOMPARE(gsr.status(), Request::Finished); QCOMPARE(gsr.result().code(), Result::Succeeded); Secret expectedSecret(testSecret); expectedSecret.setData("example custom password"); QCOMPARE(gsr.secret(), expectedSecret); // delete the secret DeleteSecretRequest dsr; dsr.setManager(&sm); QSignalSpy dsrss(&dsr, &DeleteSecretRequest::statusChanged); dsr.setIdentifier(testSecret.identifier()); QCOMPARE(dsr.identifier(), testSecret.identifier()); dsr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(dsr.userInteractionMode(), SecretManager::ApplicationInteraction); QCOMPARE(dsr.status(), Request::Inactive); dsr.startRequest(); QCOMPARE(dsrss.count(), 1); QCOMPARE(dsr.status(), Request::Active); QCOMPARE(dsr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(dsr); QCOMPARE(dsrss.count(), 2); QCOMPARE(dsr.status(), Request::Finished); QCOMPARE(dsr.result().code(), Result::Succeeded); // ensure that the delete worked properly. gsr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(gsr); QCOMPARE(gsr.result().code(), Result::Failed); // finally, clean up the collection DeleteCollectionRequest dcr; dcr.setManager(&sm); QSignalSpy dcrss(&dcr, &DeleteCollectionRequest::statusChanged); dcr.setCollectionName(QLatin1String("testcollection")); QCOMPARE(dcr.collectionName(), QLatin1String("testcollection")); dcr.setStoragePluginName(DEFAULT_TEST_STORAGE_PLUGIN); QCOMPARE(dcr.storagePluginName(), DEFAULT_TEST_STORAGE_PLUGIN); dcr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(dcr.userInteractionMode(), SecretManager::ApplicationInteraction); QCOMPARE(dcr.status(), Request::Inactive); dcr.startRequest(); QCOMPARE(dcrss.count(), 1); QCOMPARE(dcr.status(), Request::Active); QCOMPARE(dcr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(dcr); QCOMPARE(dcrss.count(), 2); QCOMPARE(dcr.status(), Request::Finished); QCOMPARE(dcr.result().code(), Result::Succeeded); } { // now a standalone custom-locked secret. Secret testSecret(Secret::Identifier( QLatin1String("testsecretname"), QString(), DEFAULT_TEST_STORAGE_PLUGIN)); testSecret.setType(Secret::TypeBlob); testSecret.setFilterData(QLatin1String("domain"), QLatin1String("sailfishos.org")); testSecret.setFilterData(QLatin1String("test"), QLatin1String("true")); InteractionParameters uiParams; uiParams.setInputType(InteractionParameters::AlphaNumericInput); uiParams.setEchoMode(InteractionParameters::NormalEcho); uiParams.setPromptText(tr("Enter the secret data")); uiParams.setAuthenticationPluginName(IN_APP_TEST_AUTHENTICATION_PLUGIN); // store the secret StoreSecretRequest ssr; ssr.setManager(&sm); QSignalSpy ssrss(&ssr, &StoreSecretRequest::statusChanged); ssr.setSecretStorageType(StoreSecretRequest::StandaloneCustomLockSecret); QCOMPARE(ssr.secretStorageType(), StoreSecretRequest::StandaloneCustomLockSecret); ssr.setCustomLockUnlockSemantic(SecretManager::CustomLockKeepUnlocked); QCOMPARE(ssr.customLockUnlockSemantic(), SecretManager::CustomLockKeepUnlocked); ssr.setAccessControlMode(SecretManager::OwnerOnlyMode); QCOMPARE(ssr.accessControlMode(), SecretManager::OwnerOnlyMode); ssr.setEncryptionPluginName(DEFAULT_TEST_ENCRYPTION_PLUGIN); QCOMPARE(ssr.encryptionPluginName(), DEFAULT_TEST_ENCRYPTION_PLUGIN); ssr.setAuthenticationPluginName(IN_APP_TEST_AUTHENTICATION_PLUGIN); QCOMPARE(ssr.authenticationPluginName(), IN_APP_TEST_AUTHENTICATION_PLUGIN); ssr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(ssr.userInteractionMode(), SecretManager::ApplicationInteraction); ssr.setSecret(testSecret); QCOMPARE(ssr.secret(), testSecret); ssr.setInteractionParameters(uiParams); QCOMPARE(ssr.interactionParameters(), uiParams); QCOMPARE(ssr.status(), Request::Inactive); ssr.startRequest(); QCOMPARE(ssrss.count(), 1); QCOMPARE(ssr.status(), Request::Active); QCOMPARE(ssr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(ssr); QCOMPARE(ssrss.count(), 2); QCOMPARE(ssr.status(), Request::Finished); QCOMPARE(ssr.result().code(), Result::Succeeded); // retrieve the secret StoredSecretRequest gsr; gsr.setManager(&sm); QSignalSpy gsrss(&gsr, &StoredSecretRequest::statusChanged); gsr.setIdentifier(testSecret.identifier()); QCOMPARE(gsr.identifier(), testSecret.identifier()); gsr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(gsr.userInteractionMode(), SecretManager::ApplicationInteraction); QCOMPARE(gsr.status(), Request::Inactive); gsr.startRequest(); QCOMPARE(gsrss.count(), 1); QCOMPARE(gsr.status(), Request::Active); QCOMPARE(gsr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(gsr); QCOMPARE(gsrss.count(), 2); QCOMPARE(gsr.status(), Request::Finished); QCOMPARE(gsr.result().code(), Result::Succeeded); Secret expectedSecret(testSecret); expectedSecret.setData("example custom password"); QCOMPARE(gsr.secret(), expectedSecret); // delete the secret DeleteSecretRequest dsr; dsr.setManager(&sm); QSignalSpy dsrss(&dsr, &DeleteSecretRequest::statusChanged); dsr.setIdentifier(testSecret.identifier()); QCOMPARE(dsr.identifier(), testSecret.identifier()); dsr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(dsr.userInteractionMode(), SecretManager::ApplicationInteraction); QCOMPARE(dsr.status(), Request::Inactive); dsr.startRequest(); QCOMPARE(dsrss.count(), 1); QCOMPARE(dsr.status(), Request::Active); QCOMPARE(dsr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(dsr); QCOMPARE(dsrss.count(), 2); QCOMPARE(dsr.status(), Request::Finished); QCOMPARE(dsr.result().code(), Result::Succeeded); // ensure that the delete worked properly. gsr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(gsr); QCOMPARE(gsr.result().code(), Result::Failed); } } void tst_secretsrequests::requestUserInput() { // construct the in-process authentication key UI. QQuickView v(QUrl::fromLocalFile(QStringLiteral("%1/tst_secretsrequests.qml").arg(QCoreApplication::applicationDirPath()))); v.show(); QObject *interactionView = v.rootObject()->findChild<QObject*>("interactionview"); QVERIFY(interactionView); QMetaObject::invokeMethod(interactionView, "setSecretManager", Qt::DirectConnection, Q_ARG(QObject*, &sm)); // define the interaction parameters InteractionParameters uiParams; uiParams.setInputType(InteractionParameters::AlphaNumericInput); uiParams.setEchoMode(InteractionParameters::NormalEcho); uiParams.setPromptText(QLatin1String("Enter the passphrase for the unit test")); uiParams.setAuthenticationPluginName(IN_APP_TEST_AUTHENTICATION_PLUGIN); // request input from the user InteractionRequest ir; ir.setManager(&sm); QSignalSpy irss(&ir, &CreateCollectionRequest::statusChanged); ir.setInteractionParameters(uiParams); QCOMPARE(ir.interactionParameters(), uiParams); QCOMPARE(ir.status(), Request::Inactive); ir.startRequest(); QCOMPARE(irss.count(), 1); QCOMPARE(ir.status(), Request::Active); QCOMPARE(ir.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(ir); QCOMPARE(irss.count(), 2); QCOMPARE(ir.status(), Request::Finished); QCOMPARE(ir.result().code(), Result::Succeeded); QCOMPARE(ir.userInput(), QByteArray("example passphrase for unit test")); } void tst_secretsrequests::accessControl() { // This test is meant to be run second, with tst_secrets::accessControl() run second. // This test must be run as non-privileged, to avoid being classified as a platform app. // Artifacts from the test will have to be removed manually from the filesystem. QSKIP("This test should only be run manually, as it is not stand-alone!"); Secret unreadableSecret(Secret::Identifier( QLatin1String("unreadablesecret"), QLatin1String("owneronlycollection"), DEFAULT_TEST_STORAGE_PLUGIN)); Secret readableSecret(Secret::Identifier( QLatin1String("readablesecret"), QLatin1String("noaccesscontrolcollection"), DEFAULT_TEST_STORAGE_PLUGIN)); // attempt to read a secret in an owner-only collection created by another process. // this should fail. StoredSecretRequest gsr; gsr.setManager(&sm); gsr.setIdentifier(unreadableSecret.identifier()); gsr.setUserInteractionMode(SecretManager::ApplicationInteraction); gsr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(gsr); QCOMPARE(gsr.status(), Request::Finished); QCOMPARE(gsr.result().code(), Result::Failed); QCOMPARE(gsr.result().errorCode(), Result::PermissionsError); // attempt to delete a secret in an owner-only collection created by another process. // this should fail. DeleteSecretRequest dsr; dsr.setManager(&sm); dsr.setIdentifier(unreadableSecret.identifier()); dsr.setUserInteractionMode(SecretManager::ApplicationInteraction); dsr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(dsr); QCOMPARE(dsr.status(), Request::Finished); QCOMPARE(dsr.result().code(), Result::Failed); QCOMPARE(dsr.result().errorCode(), Result::PermissionsError); // attempt to store a secret in an owner-only collection created by another process. // this should fail. Secret failsecret(Secret::Identifier( QLatin1String("failsecret"), QLatin1String("owneronlycollection"), DEFAULT_TEST_STORAGE_PLUGIN)); failsecret.setData("failsecretvalue"); failsecret.setType(Secret::TypeBlob); failsecret.setFilterData(QLatin1String("domain"), QLatin1String("sailfishos.org")); failsecret.setFilterData(QLatin1String("test"), QLatin1String("true")); StoreSecretRequest ssr; ssr.setManager(&sm); ssr.setSecretStorageType(StoreSecretRequest::CollectionSecret); ssr.setUserInteractionMode(SecretManager::ApplicationInteraction); ssr.setSecret(failsecret); ssr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(ssr); QCOMPARE(ssr.status(), Request::Finished); QCOMPARE(ssr.result().code(), Result::Failed); QCOMPARE(ssr.result().errorCode(), Result::PermissionsError); // attempt to delete an owner-only collection created by another process. // this should fail. DeleteCollectionRequest dcr; dcr.setManager(&sm); dcr.setCollectionName(QLatin1String("owneronlycollection")); dcr.setUserInteractionMode(SecretManager::ApplicationInteraction); dcr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(dcr); QCOMPARE(dcr.status(), Request::Finished); QCOMPARE(dcr.result().code(), Result::Failed); QCOMPARE(dcr.result().errorCode(), Result::PermissionsError); // attempt to read a secret in an owner-only collection created by another process. // this should succeed. gsr.setIdentifier(readableSecret.identifier()); gsr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(gsr); QCOMPARE(gsr.status(), Request::Finished); QCOMPARE(gsr.result().code(), Result::Succeeded); QCOMPARE(gsr.secret().data(), QByteArray("readablesecretvalue")); // attempt to delete a secret in an owner-only collection created by another process. // this should succeed. dsr.setIdentifier(readableSecret.identifier()); dsr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(dsr); QCOMPARE(dsr.status(), Request::Finished); QCOMPARE(dsr.result().code(), Result::Succeeded); // attempt to store a secret in an owner-only collection created by another process. // this should succeed. Secret succeedsecret(Secret::Identifier( QLatin1String("succeedsecret"), QLatin1String("noaccesscontrolcollection"), DEFAULT_TEST_STORAGE_PLUGIN)); succeedsecret.setData("succeedsecretvalue"); succeedsecret.setType(Secret::TypeBlob); succeedsecret.setFilterData(QLatin1String("domain"), QLatin1String("sailfishos.org")); succeedsecret.setFilterData(QLatin1String("test"), QLatin1String("true")); ssr.setSecret(succeedsecret); ssr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(ssr); QCOMPARE(ssr.status(), Request::Finished); QCOMPARE(ssr.result().code(), Result::Succeeded); // attempt to delete a no-access-control collection created by another process. // this should succeed. dcr.setCollectionName(QLatin1String("noaccesscontrolcollection")); dcr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(dcr); QCOMPARE(dcr.status(), Request::Finished); QCOMPARE(dcr.result().code(), Result::Succeeded); } void tst_secretsrequests::lockCode() { // construct the in-process authentication key UI. QQuickView v(QUrl::fromLocalFile(QStringLiteral("%1/tst_secretsrequests.qml").arg(QCoreApplication::applicationDirPath()))); v.show(); QObject *interactionView = v.rootObject()->findChild<QObject*>("interactionview"); QVERIFY(interactionView); QMetaObject::invokeMethod(interactionView, "setSecretManager", Qt::DirectConnection, Q_ARG(QObject*, &sm)); // create a collection in a normal storage plugin CreateCollectionRequest ccr; ccr.setManager(&sm); QSignalSpy ccrss(&ccr, &CreateCollectionRequest::statusChanged); ccr.setCollectionLockType(CreateCollectionRequest::DeviceLock); QCOMPARE(ccr.collectionLockType(), CreateCollectionRequest::DeviceLock); ccr.setCollectionName(QLatin1String("testcollection")); QCOMPARE(ccr.collectionName(), QLatin1String("testcollection")); ccr.setStoragePluginName(DEFAULT_TEST_STORAGE_PLUGIN); QCOMPARE(ccr.storagePluginName(), DEFAULT_TEST_STORAGE_PLUGIN); ccr.setEncryptionPluginName(DEFAULT_TEST_ENCRYPTION_PLUGIN); QCOMPARE(ccr.encryptionPluginName(), DEFAULT_TEST_ENCRYPTION_PLUGIN); ccr.setDeviceLockUnlockSemantic(SecretManager::DeviceLockKeepUnlocked); QCOMPARE(ccr.deviceLockUnlockSemantic(), SecretManager::DeviceLockKeepUnlocked); ccr.setAccessControlMode(SecretManager::OwnerOnlyMode); QCOMPARE(ccr.accessControlMode(), SecretManager::OwnerOnlyMode); QCOMPARE(ccr.status(), Request::Inactive); ccr.startRequest(); QCOMPARE(ccrss.count(), 1); QCOMPARE(ccr.status(), Request::Active); QCOMPARE(ccr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(ccr); QCOMPARE(ccrss.count(), 2); QCOMPARE(ccr.status(), Request::Finished); QCOMPARE(ccr.result().code(), Result::Succeeded); // store a new secret into the collection Secret testSecret(Secret::Identifier( QLatin1String("testsecretname"), QLatin1String("testcollection"), DEFAULT_TEST_STORAGE_PLUGIN)); testSecret.setData("testsecretvalue"); testSecret.setType(Secret::TypeBlob); testSecret.setFilterData(QLatin1String("domain"), QLatin1String("sailfishos.org")); testSecret.setFilterData(QLatin1String("test"), QLatin1String("true")); StoreSecretRequest ssr; ssr.setManager(&sm); QSignalSpy ssrss(&ssr, &StoreSecretRequest::statusChanged); ssr.setSecretStorageType(StoreSecretRequest::CollectionSecret); QCOMPARE(ssr.secretStorageType(), StoreSecretRequest::CollectionSecret); ssr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(ssr.userInteractionMode(), SecretManager::ApplicationInteraction); ssr.setSecret(testSecret); QCOMPARE(ssr.secret(), testSecret); QCOMPARE(ssr.status(), Request::Inactive); ssr.startRequest(); QCOMPARE(ssrss.count(), 1); QCOMPARE(ssr.status(), Request::Active); QCOMPARE(ssr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(ssr); QCOMPARE(ssrss.count(), 2); QCOMPARE(ssr.status(), Request::Finished); QCOMPARE(ssr.result().code(), Result::Succeeded); // retrieve the secret, ensure it matches StoredSecretRequest gsr; gsr.setManager(&sm); QSignalSpy gsrss(&gsr, &StoredSecretRequest::statusChanged); gsr.setIdentifier(testSecret.identifier()); QCOMPARE(gsr.identifier(), testSecret.identifier()); gsr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(gsr.userInteractionMode(), SecretManager::ApplicationInteraction); QCOMPARE(gsr.status(), Request::Inactive); gsr.startRequest(); QCOMPARE(gsrss.count(), 1); QCOMPARE(gsr.status(), Request::Active); QCOMPARE(gsr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(gsr); QCOMPARE(gsrss.count(), 2); QCOMPARE(gsr.status(), Request::Finished); QCOMPARE(gsr.result().code(), Result::Succeeded); QCOMPARE(gsr.secret().data(), testSecret.data()); // now create an encrypted-storage collection ccr.setCollectionName(QLatin1String("estestcollection")); ccr.setStoragePluginName(DEFAULT_TEST_ENCRYPTEDSTORAGE_PLUGIN); ccr.setEncryptionPluginName(DEFAULT_TEST_ENCRYPTEDSTORAGE_PLUGIN); ccr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(ccr); QCOMPARE(ccr.status(), Request::Finished); QCOMPARE(ccr.result().code(), Result::Succeeded); // and store a secret into the encrypted-storage collection Secret estestSecret(Secret::Identifier( QLatin1String("estestsecretname"), QLatin1String("estestcollection"), DEFAULT_TEST_ENCRYPTEDSTORAGE_PLUGIN)); estestSecret.setData("estestsecretvalue"); estestSecret.setType(Secret::TypeBlob); estestSecret.setFilterData(QLatin1String("domain"), QLatin1String("sailfishos.org")); estestSecret.setFilterData(QLatin1String("test"), QLatin1String("true")); ssr.setSecret(estestSecret); ssr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(ssr); QCOMPARE(ssr.status(), Request::Finished); QCOMPARE(ssr.result().code(), Result::Succeeded); // test that we can retrieve it gsr.setIdentifier(estestSecret.identifier()); gsr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(gsr); QCOMPARE(gsr.status(), Request::Finished); QCOMPARE(gsr.result().code(), Result::Succeeded); QCOMPARE(gsr.secret().data(), estestSecret.data()); // Now set the master lock code. LockCodeRequest lcr; lcr.setManager(&sm); QSignalSpy lcrss(&lcr, &LockCodeRequest::statusChanged); lcr.setLockCodeRequestType(LockCodeRequest::ModifyLockCode); QCOMPARE(lcr.lockCodeRequestType(), LockCodeRequest::ModifyLockCode); lcr.setLockCodeTargetType(LockCodeRequest::MetadataDatabase); QCOMPARE(lcr.lockCodeTargetType(), LockCodeRequest::MetadataDatabase); lcr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(lcr.userInteractionMode(), SecretManager::ApplicationInteraction); InteractionParameters uiParams; uiParams.setAuthenticationPluginName(IN_APP_TEST_AUTHENTICATION_PLUGIN); uiParams.setInputType(InteractionParameters::AlphaNumericInput); uiParams.setEchoMode(InteractionParameters::PasswordEcho); lcr.setInteractionParameters(uiParams); lcr.setLockCodeTarget(QString()); lcr.startRequest(); QCOMPARE(lcrss.count(), 1); QCOMPARE(lcr.status(), Request::Active); QCOMPARE(lcr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(lcr); QCOMPARE(lcrss.count(), 2); QCOMPARE(lcr.status(), Request::Finished); QCOMPARE(lcr.result().code(), Result::Succeeded); // Retrieve the secrets again, make sure we can. gsr.setIdentifier(estestSecret.identifier()); gsr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(gsr); QCOMPARE(gsr.status(), Request::Finished); QCOMPARE(gsr.result().code(), Result::Succeeded); QCOMPARE(gsr.secret().data(), estestSecret.data()); gsr.setIdentifier(testSecret.identifier()); gsr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(gsr); QCOMPARE(gsr.status(), Request::Finished); QCOMPARE(gsr.result().code(), Result::Succeeded); QCOMPARE(gsr.secret().data(), testSecret.data()); // Tell the service to forget the lock code. lcr.setLockCodeRequestType(LockCodeRequest::ForgetLockCode); lcr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(lcr); QCOMPARE(lcr.status(), Request::Finished); QCOMPARE(lcr.result().code(), Result::Succeeded); // Ensure that attempting to read secrets will now fail gsr.setIdentifier(estestSecret.identifier()); gsr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(gsr); QCOMPARE(gsr.status(), Request::Finished); QCOMPARE(gsr.result().code(), Result::Failed); gsr.setIdentifier(testSecret.identifier()); gsr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(gsr); QCOMPARE(gsr.status(), Request::Finished); QCOMPARE(gsr.result().code(), Result::Failed); // Now provide the lock code again to unlock the service. lcr.setLockCodeRequestType(LockCodeRequest::ProvideLockCode); uiParams.setAuthenticationPluginName(IN_APP_TEST_AUTHENTICATION_PLUGIN); lcr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(lcr); QCOMPARE(lcr.status(), Request::Finished); QCOMPARE(lcr.result().code(), Result::Succeeded); // Retrieve the secrets again, make sure that it succeeds again. gsr.setIdentifier(estestSecret.identifier()); gsr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(gsr); QCOMPARE(gsr.status(), Request::Finished); QCOMPARE(gsr.result().code(), Result::Succeeded); QCOMPARE(gsr.secret().data(), estestSecret.data()); gsr.setIdentifier(testSecret.identifier()); gsr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(gsr); QCOMPARE(gsr.status(), Request::Finished); QCOMPARE(gsr.result().code(), Result::Succeeded); QCOMPARE(gsr.secret().data(), testSecret.data()); // Set the lock code back. lcr.setLockCodeRequestType(LockCodeRequest::ModifyLockCode); uiParams.setAuthenticationPluginName(IN_APP_TEST_AUTHENTICATION_PLUGIN); lcr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(lcr); QCOMPARE(lcr.status(), Request::Finished); QCOMPARE(lcr.result().code(), Result::Succeeded); // Retrieve the secrets again, make sure we still can. gsr.setIdentifier(estestSecret.identifier()); gsr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(gsr); QCOMPARE(gsr.status(), Request::Finished); QCOMPARE(gsr.result().code(), Result::Succeeded); QCOMPARE(gsr.secret().data(), estestSecret.data()); gsr.setIdentifier(testSecret.identifier()); gsr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(gsr); QCOMPARE(gsr.status(), Request::Finished); QCOMPARE(gsr.result().code(), Result::Succeeded); QCOMPARE(gsr.secret().data(), testSecret.data()); // delete the secrets DeleteSecretRequest dsr; dsr.setManager(&sm); QSignalSpy dsrss(&dsr, &DeleteSecretRequest::statusChanged); dsr.setIdentifier(testSecret.identifier()); QCOMPARE(dsr.identifier(), testSecret.identifier()); dsr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(dsr.userInteractionMode(), SecretManager::ApplicationInteraction); QCOMPARE(dsr.status(), Request::Inactive); dsr.startRequest(); QCOMPARE(dsrss.count(), 1); QCOMPARE(dsr.status(), Request::Active); QCOMPARE(dsr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(dsr); QCOMPARE(dsrss.count(), 2); QCOMPARE(dsr.status(), Request::Finished); QCOMPARE(dsr.result().code(), Result::Succeeded); dsr.setIdentifier(estestSecret.identifier()); dsr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(dsr); QCOMPARE(dsr.status(), Request::Finished); QCOMPARE(dsr.result().code(), Result::Succeeded); // finally, clean up the collections DeleteCollectionRequest dcr; dcr.setManager(&sm); QSignalSpy dcrss(&dcr, &DeleteCollectionRequest::statusChanged); dcr.setCollectionName(QLatin1String("testcollection")); QCOMPARE(dcr.collectionName(), QLatin1String("testcollection")); dcr.setStoragePluginName(DEFAULT_TEST_STORAGE_PLUGIN); QCOMPARE(dcr.storagePluginName(), DEFAULT_TEST_STORAGE_PLUGIN); dcr.setUserInteractionMode(SecretManager::ApplicationInteraction); QCOMPARE(dcr.userInteractionMode(), SecretManager::ApplicationInteraction); QCOMPARE(dcr.status(), Request::Inactive); dcr.startRequest(); QCOMPARE(dcrss.count(), 1); QCOMPARE(dcr.status(), Request::Active); QCOMPARE(dcr.result().code(), Result::Pending); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(dcr); QCOMPARE(dcrss.count(), 2); QCOMPARE(dcr.status(), Request::Finished); QCOMPARE(dcr.result().code(), Result::Succeeded); dcr.setCollectionName(QLatin1String("estestcollection")); dcr.setStoragePluginName(DEFAULT_TEST_ENCRYPTEDSTORAGE_PLUGIN); dcr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(dcr); QCOMPARE(dcr.status(), Request::Finished); QCOMPARE(dcr.result().code(), Result::Succeeded); // now test plugin lock codes uiParams.setPromptText(QLatin1String("Modify the lock code for the storage plugin")); lcr.setLockCodeRequestType(LockCodeRequest::ModifyLockCode); lcr.setLockCodeTargetType(LockCodeRequest::ExtensionPlugin); lcr.setLockCodeTarget(DEFAULT_TEST_STORAGE_PLUGIN); lcr.setInteractionParameters(uiParams); uiParams.setAuthenticationPluginName(IN_APP_TEST_AUTHENTICATION_PLUGIN); lcr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(lcr); QCOMPARE(lcr.status(), Request::Finished); QCOMPARE(lcr.result().code(), Result::Failed); QCOMPARE(lcr.result().errorMessage(), QStringLiteral("storage plugin %1 does not support locking") .arg(DEFAULT_TEST_STORAGE_PLUGIN)); uiParams.setPromptText(QLatin1String("Provide the lock code for the storage plugin")); lcr.setLockCodeRequestType(LockCodeRequest::ProvideLockCode); lcr.setInteractionParameters(uiParams); uiParams.setAuthenticationPluginName(IN_APP_TEST_AUTHENTICATION_PLUGIN); lcr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(lcr); QCOMPARE(lcr.status(), Request::Finished); QCOMPARE(lcr.result().code(), Result::Failed); QCOMPARE(lcr.result().errorMessage(), QStringLiteral("storage plugin %1 does not support locking") .arg(DEFAULT_TEST_STORAGE_PLUGIN)); lcr.setLockCodeRequestType(LockCodeRequest::ForgetLockCode); lcr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(lcr); QCOMPARE(lcr.status(), Request::Finished); QCOMPARE(lcr.result().code(), Result::Failed); QCOMPARE(lcr.result().errorMessage(), QStringLiteral("storage plugin %1 does not support locking") .arg(DEFAULT_TEST_STORAGE_PLUGIN)); } void tst_secretsrequests::pluginThreading() { // This test is meant to be run manually and // concurrently with tst_cryptorequests::pluginThreading(). // It performs a series of simple secrets requests which // will use the OpenSSL secrets encryption plugin to encrypt // and decrypt data in the Secrets Plugins Thread. // The tst_cryptorequests::pluginThreading() will concurrently // be using the OpenSSL crypto plugin to encrypt and decrypt // data in the Crypto Plugins Thread. // If the appropriate locking and multithreading has not been // implemented, we expect the daemon to crash, or to produce // incorrect data. CreateCollectionRequest ccr; ccr.setManager(&sm); ccr.setCollectionLockType(CreateCollectionRequest::DeviceLock); ccr.setCollectionName(QLatin1String("testthreadscollection")); ccr.setStoragePluginName(DEFAULT_TEST_STORAGE_PLUGIN); ccr.setEncryptionPluginName(DEFAULT_TEST_ENCRYPTION_PLUGIN); ccr.setDeviceLockUnlockSemantic(SecretManager::DeviceLockKeepUnlocked); ccr.setAccessControlMode(SecretManager::OwnerOnlyMode); ccr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(ccr); QCOMPARE(ccr.status(), Request::Finished); QCOMPARE(ccr.result().code(), Result::Succeeded); QElapsedTimer et; et.start(); while (et.elapsed() < 15000) { Secret testSecret(Secret::Identifier( QLatin1String("testsecretname"), QLatin1String("testthreadscollection"), DEFAULT_TEST_STORAGE_PLUGIN)); testSecret.setData("testsecretvalue"); testSecret.setType(Secret::TypeBlob); testSecret.setFilterData(QLatin1String("domain"), QLatin1String("sailfishos.org")); testSecret.setFilterData(QLatin1String("test"), QLatin1String("true")); // store a new secret into the collection StoreSecretRequest ssr; ssr.setManager(&sm); ssr.setSecretStorageType(StoreSecretRequest::CollectionSecret); ssr.setUserInteractionMode(SecretManager::ApplicationInteraction); ssr.setSecret(testSecret); ssr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(ssr); QCOMPARE(ssr.status(), Request::Finished); QCOMPARE(ssr.result().code(), Result::Succeeded); // retrieve the secret, ensure it matches StoredSecretRequest gsr; gsr.setManager(&sm); gsr.setIdentifier(testSecret.identifier()); gsr.setUserInteractionMode(SecretManager::ApplicationInteraction); gsr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(gsr); QCOMPARE(gsr.status(), Request::Finished); QCOMPARE(gsr.result().code(), Result::Succeeded); QCOMPARE(gsr.secret().data(), testSecret.data()); QCOMPARE(gsr.secret().type(), testSecret.type()); QCOMPARE(gsr.secret().filterData(), testSecret.filterData()); QCOMPARE(gsr.secret().name(), testSecret.name()); QCOMPARE(gsr.secret().collectionName(), testSecret.collectionName()); // delete the secret DeleteSecretRequest dsr; dsr.setManager(&sm); dsr.setIdentifier(testSecret.identifier()); dsr.setUserInteractionMode(SecretManager::ApplicationInteraction); dsr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(dsr); QCOMPARE(dsr.status(), Request::Finished); QCOMPARE(dsr.result().code(), Result::Succeeded); } DeleteCollectionRequest dcr; dcr.setManager(&sm); dcr.setCollectionName(QLatin1String("testthreadscollection")); dcr.setStoragePluginName(DEFAULT_TEST_STORAGE_PLUGIN); dcr.setUserInteractionMode(SecretManager::ApplicationInteraction); dcr.startRequest(); WAIT_FOR_FINISHED_WITHOUT_BLOCKING(dcr); QCOMPARE(dcr.status(), Request::Finished); QCOMPARE(dcr.result().code(), Result::Succeeded); } #include "tst_secretsrequests.moc" QTEST_MAIN(tst_secretsrequests)
46.551742
128
0.71651
Denis-Semakin
8ad271d72780b1da2ab16494ae3059a8a6ce425f
2,336
cpp
C++
test/test_dispatcher.cpp
mjgigli/libaopp
d603127f4e5d9cc1caa6ec5def4f743b2e775812
[ "MIT" ]
null
null
null
test/test_dispatcher.cpp
mjgigli/libaopp
d603127f4e5d9cc1caa6ec5def4f743b2e775812
[ "MIT" ]
null
null
null
test/test_dispatcher.cpp
mjgigli/libaopp
d603127f4e5d9cc1caa6ec5def4f743b2e775812
[ "MIT" ]
null
null
null
/* * Copyright (c) 2019 Matt Gigli * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE * SOFTWARE. */ #include <gtest/gtest.h> #include "libaopp/util/dispatcher.hpp" class A { public: A() : some_data(0){}; A(int d) : some_data(d){}; virtual ~A() = default; int some_data; }; class B : public A {}; class C : public A {}; class D : public A {}; class E : public A {}; int handle_event(const A& a) { static auto dispatch = aopp::util::make_dispatcher<A, int>( [&](const A& a) { (void)a; std::cout << "Event not handled" << std::endl; return 0; }, [&](const B& b) { (void)b; std::cout << "B event handled" << std::endl; return 1; }, [&](const C& c) { (void)c; std::cout << "C event handled" << std::endl; return 2; }, [&](const D& d) { (void)d; std::cout << "D event handled" << std::endl; return 3; }); return dispatch(a); } TEST(Dispatcher, DispatchDerivedEvents) { int r; A* evt; B b; evt = &b; r = handle_event(*evt); EXPECT_EQ(r, 1); C c; evt = &c; r = handle_event(*evt); EXPECT_EQ(r, 2); D d; evt = &d; r = handle_event(*evt); EXPECT_EQ(r, 3); E e; evt = &e; r = handle_event(*evt); EXPECT_EQ(r, 0); }
24.589474
79
0.624144
mjgigli
8ad3be829a82febcdebf128ffc1c0fc8b66e14ad
7,003
cpp
C++
src/h5geo/h5mapimpl.cpp
kerim371/h5geo
a023d8c667ff002de361e8184165e6d72e510bde
[ "MIT" ]
1
2021-06-17T23:40:52.000Z
2021-06-17T23:40:52.000Z
src/h5geo/h5mapimpl.cpp
tierra-colada/h5geo
1d577f4194c0f7826a3e584742fc9714831ec368
[ "MIT" ]
null
null
null
src/h5geo/h5mapimpl.cpp
tierra-colada/h5geo
1d577f4194c0f7826a3e584742fc9714831ec368
[ "MIT" ]
null
null
null
#include "../../include/h5geo/misc/h5mapimpl.h" #include "../../include/h5geo/h5mapcontainer.h" #include "../../include/h5geo/h5core.h" #include "../../include/h5geo/misc/h5core_enum_string.h" #include <units/units.hpp> #ifdef H5GEO_USE_GDAL #include <gdal/gdal.h> #include <gdal/gdal_priv.h> #endif H5MapImpl::H5MapImpl(const h5gt::Group &group) : H5BaseObjectImpl(group){} bool H5MapImpl::writeData( Eigen::Ref<Eigen::MatrixXd> M, const std::string& dataUnits) { auto opt = getMapD(); if (!opt.has_value()) return false; return h5geo::overwriteResizableDataset( objG, opt->getPath(), M, dataUnits, getDataUnits()); } Eigen::MatrixXd H5MapImpl::getData(const std::string& dataUnits){ auto opt = getMapD(); if (!opt.has_value()) return Eigen::MatrixXd(); return h5geo::readDoubleEigenMtxDataset( objG, opt->getPath(), getDataUnits(), dataUnits); } bool H5MapImpl::setDomain(const h5geo::Domain& val){ unsigned v = static_cast<unsigned>(val); return h5geo::overwriteAttribute( objG, std::string{h5geo::detail::Domain}, v); } bool H5MapImpl::setOrigin( Eigen::Ref<Eigen::Vector2d> v, const std::string& lengthUnits, bool doCoordTransform) { #ifdef H5GEO_USE_GDAL if (doCoordTransform){ OGRCoordinateTransformation* coordTrans = createCoordinateTransformationToWriteData(lengthUnits); if (!coordTrans) return false; coordTrans->Transform(1, &v(0), &v(1)); return h5geo::overwriteAttribute( objG, std::string{h5geo::detail::origin}, v); } #endif return h5geo::overwriteAttribute( objG, std::string{h5geo::detail::origin}, v, lengthUnits, getLengthUnits()); } bool H5MapImpl::setPoint1( Eigen::Ref<Eigen::Vector2d> v, const std::string& lengthUnits, bool doCoordTransform) { #ifdef H5GEO_USE_GDAL if (doCoordTransform){ OGRCoordinateTransformation* coordTrans = createCoordinateTransformationToWriteData(lengthUnits); if (!coordTrans) return false; coordTrans->Transform(1, &v(0), &v(1)); return h5geo::overwriteAttribute( objG, std::string{h5geo::detail::point1}, v); } #endif return h5geo::overwriteAttribute( objG, std::string{h5geo::detail::point1}, v, lengthUnits, getLengthUnits()); } bool H5MapImpl::setPoint2( Eigen::Ref<Eigen::Vector2d> v, const std::string& lengthUnits, bool doCoordTransform){ #ifdef H5GEO_USE_GDAL if (doCoordTransform){ OGRCoordinateTransformation* coordTrans = createCoordinateTransformationToWriteData(lengthUnits); if (!coordTrans) return false; coordTrans->Transform(1, &v(0), &v(1)); return h5geo::overwriteAttribute( objG, std::string{h5geo::detail::point2}, v); } #endif return h5geo::overwriteAttribute( objG, std::string{h5geo::detail::point2}, v, lengthUnits, getLengthUnits()); } bool H5MapImpl::addAttribute(H5Map* map, std::string name){ if (this->getH5File() != map->getH5File()) return false; if (name.empty()) name = map->getName(); if (objG.hasObject(name, h5gt::ObjectType::Group)) return false; objG.createLink(map->getObjG(), name, h5gt::LinkType::Soft); return true; } bool H5MapImpl::addExternalAttribute(H5Map* map, std::string name){ if (this->getH5File() == map->getH5File()) return false; if (name.empty()) name = map->getName(); if (objG.hasObject(name, h5gt::ObjectType::Group)) return false; objG.createLink(map->getObjG(), name, h5gt::LinkType::External); return true; } bool H5MapImpl::removeAttribute(const std::string& name){ if (name.empty()) return false; if (!objG.hasObject(name, h5gt::ObjectType::Group)) return false; objG.unlink(name); return true; } H5Map* H5MapImpl::getAttribute(const std::string& name){ if (!objG.hasObject(name, h5gt::ObjectType::Group)) return nullptr; h5gt::Group group = objG.getGroup(name); if (!isGeoObjectByType(group, h5geo::ObjectType::MAP)) return nullptr; return new H5MapImpl(group); } h5geo::Domain H5MapImpl::getDomain(){ return static_cast<h5geo::Domain>( h5geo::readEnumAttribute( objG, std::string{h5geo::detail::Domain})); } Eigen::VectorXd H5MapImpl::getOrigin( const std::string& lengthUnits, bool doCoordTransform) { #ifdef H5GEO_USE_GDAL if (doCoordTransform){ OGRCoordinateTransformation* coordTrans = createCoordinateTransformationToReadData(lengthUnits); if (!coordTrans) return Eigen::VectorXd(); Eigen::VectorXd v = h5geo::readDoubleEigenVecAttribute( objG, std::string{h5geo::detail::origin}); if (v.size() != 2) return Eigen::VectorXd(); coordTrans->Transform(1, &v(0), &v(1)); return v; } #endif return h5geo::readDoubleEigenVecAttribute( objG, std::string{h5geo::detail::origin}, getLengthUnits(), lengthUnits); } Eigen::VectorXd H5MapImpl::getPoint1( const std::string& lengthUnits, bool doCoordTransform) { #ifdef H5GEO_USE_GDAL if (doCoordTransform){ OGRCoordinateTransformation* coordTrans = createCoordinateTransformationToReadData(lengthUnits); if (!coordTrans) return Eigen::VectorXd(); Eigen::VectorXd v = h5geo::readDoubleEigenVecAttribute( objG, std::string{h5geo::detail::point1}); if (v.size() != 2) return Eigen::VectorXd(); coordTrans->Transform(1, &v(0), &v(1)); return v; } #endif return h5geo::readDoubleEigenVecAttribute( objG, std::string{h5geo::detail::point1}, getLengthUnits(), lengthUnits); } Eigen::VectorXd H5MapImpl::getPoint2( const std::string& lengthUnits, bool doCoordTransform) { #ifdef H5GEO_USE_GDAL if (doCoordTransform){ OGRCoordinateTransformation* coordTrans = createCoordinateTransformationToReadData(lengthUnits); if (!coordTrans) return Eigen::VectorXd(); Eigen::VectorXd v = h5geo::readDoubleEigenVecAttribute( objG, std::string{h5geo::detail::point2}); if (v.size() != 2) return Eigen::VectorXd(); coordTrans->Transform(1, &v(0), &v(1)); return v; } #endif return h5geo::readDoubleEigenVecAttribute( objG, std::string{h5geo::detail::point2}, getLengthUnits(), lengthUnits); } H5MapContainer* H5MapImpl::getMapContainer() const{ h5gt::File file = getH5File(); return h5geo::createMapContainer( file, h5geo::CreationType::OPEN_OR_CREATE); } std::optional<h5gt::DataSet> H5MapImpl::getMapD() const { std::string name = std::string{h5geo::detail::map_data}; return getDatasetOpt(objG, name); } H5Map* h5geo::openMap(h5gt::Group group){ if (isGeoObjectByType(group, h5geo::ObjectType::MAP)) return new H5MapImpl(group); return nullptr; }
23.982877
67
0.659574
kerim371
8ad4be86b0655fff00eaef640e6f514311295235
4,996
hh
C++
hackt_docker/hackt/src/util/persistent.hh
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
hackt_docker/hackt/src/util/persistent.hh
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
hackt_docker/hackt/src/util/persistent.hh
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
/** \file "util/persistent.hh" Base class interface for persistent, serializable objects. $Id: persistent.hh,v 1.16 2007/07/31 23:23:43 fang Exp $ */ #ifndef __UTIL_PERSISTENT_H__ #define __UTIL_PERSISTENT_H__ #include <iosfwd> #include "util/persistent_fwd.hh" #include "util/new_functor_fwd.hh" //============================================================================= // macros /** Some classes just need to satisfy the persistent requirements without actually implementing them, because no objects of their type will actually ever be saved at run-time. This macro supplies default no-op definitions for them. */ #define PERSISTENT_METHODS_DUMMY_IMPLEMENTATION(T) \ void \ T::collect_transient_info(persistent_object_manager&) const { } \ void \ T::write_object(const persistent_object_manager&, ostream&) const { } \ void \ T::load_object(const persistent_object_manager&, istream&) { } /** Default implementation of ostream& what(ostream&) const member function, which need not be derived from persistent. Requires inclusion of "util/what.h". */ #define PERSISTENT_WHAT_DEFAULT_IMPLEMENTATION(T) \ std::ostream& \ T::what(std::ostream& o) const { \ return o << util::what<T >::name(); \ } //----------------------------------------------------------------------------- // macros for use in write_object and load_object, // have been relocated to persistent_object_manager.cc (2005-02-01) //============================================================================= /** Handy utilities go here. */ namespace util { using std::istream; using std::ostream; //============================================================================= /** Interface prerequisites for persistent, serializable objects. This class works closely with the persistent_object_manager class. Concept requirement: allocation In addition to implementing the pure virtual functions, there also needs to be a function (may be static) that returns an allocated persistent object; cannot be a method because object doesn't exist yet -- don't know what type. The allocator should return a pointer to this persistent base type. */ class persistent { public: /** Type for auxiliary construction argument. Should be small like a char for space-efficiency. NOTE: currently construct_empty does NOT follow this... This should be fixed for consistency sake. */ typedef unsigned char aux_alloc_arg_type; public: /** standard default destructor, but virtual */ virtual ~persistent() { } /** The infamous what-function */ virtual ostream& what(ostream& o) const = 0; /** walks object hierarchy and registers reachable pointers with manager */ virtual void collect_transient_info(persistent_object_manager& m) const = 0; /** Writes the object out to a managed buffer */ virtual void write_object(const persistent_object_manager& m, ostream& o) const = 0; /** Loads the object from a managed buffer */ virtual void load_object(const persistent_object_manager& m, istream& i) = 0; public: /** General purpose flag for printing or suppressing warning messages about unimplemented or partially implemented interface functions. */ static bool warn_unimplemented; public: class hash_key; }; // end class persistent //----------------------------------------------------------------------------- /** This macro is only effective in the util namespace! */ #define SPECIALIZE_PERSISTENT_TRAITS_DECLARATION(T) \ template <> \ struct persistent_traits<T> { \ typedef persistent_traits<T> this_type; \ typedef T type; \ static const persistent::hash_key type_key; \ static const persistent::aux_alloc_arg_type \ sub_index; \ static const int type_id; \ static \ persistent* \ construct_empty(void); \ \ static const new_functor<T,persistent> empty_constructor; \ }; // end struct persistent_traits (specialized) /** This macro is only effective in the util namespace! */ #define SPECIALIZE_PERSISTENT_TRAITS_INITIALIZATION(T, key, index) \ const persistent::hash_key \ persistent_traits<T>::type_key(key); \ const persistent::aux_alloc_arg_type \ persistent_traits<T>::sub_index = index; \ persistent* \ persistent_traits<T>::construct_empty(void) { \ return new T(); \ } \ const new_functor<T,persistent> \ persistent_traits<T>::empty_constructor; \ const int \ persistent_traits<T>::type_id = \ persistent_object_manager::register_persistent_type<T>(); #define SPECIALIZE_PERSISTENT_TRAITS_FULL_DEFINITION(T, key, index) \ SPECIALIZE_PERSISTENT_TRAITS_DECLARATION(T) \ SPECIALIZE_PERSISTENT_TRAITS_INITIALIZATION(T, key, index) //----------------------------------------------------------------------------- } // end namespace util //============================================================================= #endif // __UTIL_PERSISTENT_H__
31.421384
79
0.647718
broken-wheel
8ad5187c0902df7abe9f2876e1aa7a5523a3bbf0
3,336
cpp
C++
maxexport/LODUtil.cpp
Andrewich/deadjustice
48bea56598e79a1a10866ad41aa3517bf7d7c724
[ "BSD-3-Clause" ]
3
2019-04-20T10:16:36.000Z
2021-03-21T19:51:38.000Z
maxexport/LODUtil.cpp
Andrewich/deadjustice
48bea56598e79a1a10866ad41aa3517bf7d7c724
[ "BSD-3-Clause" ]
null
null
null
maxexport/LODUtil.cpp
Andrewich/deadjustice
48bea56598e79a1a10866ad41aa3517bf7d7c724
[ "BSD-3-Clause" ]
2
2020-04-18T20:04:24.000Z
2021-09-19T05:07:41.000Z
#include "StdAfx.h" #include "LODUtil.h" #ifdef SGEXPORT_LODCTRL #include "LODCtrl.h" #endif #include <lang/Debug.h> #include <lang/Character.h> #include <lang/Exception.h> #include <lang/NumberReader.h> //----------------------------------------------------------------------------- using namespace lang; //----------------------------------------------------------------------------- /** LOD group name base substring. */ const String LOD_GROUP_BASE_ID = "_LOD"; /** LOD group name size (pixels) substring. */ const String LOD_GROUP_SIZE_ID = "_SIZE"; //----------------------------------------------------------------------------- /** * Parses integer from a string. * @exception Exception */ static int parseInt( const String& str, int i, const String& name ) { int pos = i; NumberReader<int> nr; while ( i < str.length() && str.charAt(i) < 0x80 && Character::isDigit( str.charAt(i) ) && 1 == nr.put( (char)str.charAt(i) ) ) ++i; if ( !nr.valid() ) throw Exception( Format("Failed to parse {0} from {1} (index {2,#})", name, str, pos) ); return nr.value(); } //----------------------------------------------------------------------------- bool LODUtil::isLODHead( INode* node ) { return getLODHeadID(node) != ""; } String LODUtil::getLODHeadID( INode* node ) { #ifdef SGEXPORT_LODCTRL // check for plugin LOD for ( int i = 0 ; i < node->NumberOfChildren() ; ++i ) { INode* child = node->GetChildNode( i ); if ( child->IsGroupMember() ) { Control* vis = child->GetVisController(); if ( vis && LOD_CONTROL_CLASS_ID == vis->ClassID() ) { LODCtrl* lod = (LODCtrl*)vis; return String::valueOf( lod->grpID ); } } } #endif // check for name based LOD String str = node->GetName(); int baseIndex = str.indexOf( LOD_GROUP_BASE_ID ); int numIndex = str.lastIndexOf( "_" ); if ( -1 != baseIndex ) { int baseLen = LOD_GROUP_BASE_ID.length(); int serNum = parseInt( str, numIndex+1, "LOD serial number" ); String lodBaseID = str.substring( 0, baseIndex+baseLen ); String lodID = lodBaseID + "_" + String::valueOf( serNum ); return lodID; } return ""; } void LODUtil::getLODMemberInfo( INode* node, String* lodID, float* lodMin, float* lodMax ) { // defaults *lodID = ""; *lodMin = 0.f; *lodMax = 0.f; #ifdef SGEXPORT_LODCTRL // get level of detail from lod plugin INode* visnode = node; Control* vis = visnode->GetVisController(); if ( vis && LOD_CONTROL_CLASS_ID == vis->ClassID() ) { LODCtrl* lod = (LODCtrl*)vis; *lodID = String::valueOf( lod->grpID ); *lodMin = lod->min; *lodMax = lod->max; return; } #endif // get level of detail from name String str = node->GetName(); int baseIndex = str.indexOf( LOD_GROUP_BASE_ID ); int sizeIndex = str.indexOf( LOD_GROUP_SIZE_ID ); int numIndex = str.lastIndexOf( "_" ); if ( -1 != baseIndex ) { int baseLen = LOD_GROUP_BASE_ID.length(); int sizeLen = LOD_GROUP_SIZE_ID.length(); int serNum = parseInt( str, numIndex+1, "LOD serial number" ); String lodBaseID = str.substring( 0, baseIndex+baseLen ); *lodID = lodBaseID + "_" + String::valueOf( serNum ); *lodMin = 0.f; *lodMax = parseInt( str, sizeIndex+sizeLen, "LOD size" ); return; } }
26.0625
91
0.566247
Andrewich
e9d66aeaac4e09c6fa7cc7ebec141d02d1b24117
929
cpp
C++
acm/shuoj/timu/1015.cpp
xiaohuihuigh/cpp
c28bdb79ecb86f44a92971ac259910546dba29a7
[ "MIT" ]
17
2016-01-01T12:57:25.000Z
2022-02-06T09:55:12.000Z
acm/shuoj/timu/1015.cpp
xiaohuihuigh/cpp
c28bdb79ecb86f44a92971ac259910546dba29a7
[ "MIT" ]
null
null
null
acm/shuoj/timu/1015.cpp
xiaohuihuigh/cpp
c28bdb79ecb86f44a92971ac259910546dba29a7
[ "MIT" ]
8
2018-12-27T01:31:49.000Z
2022-02-06T09:55:12.000Z
#include<cstring> #include<iostream> using namespace std; const int maxn = 300; int line[maxn],sum[maxn]; int n,m,Max,Min; int ma[200][20]; int mi[200][20]; void dp(int a[]){ for(int i = 1;i<=n;i++) sum[i] = sum[i-1] + a[i]; memset(ma,0,sizeof(ma)); memset(mi,0x3f,sizeof(mi)); for(int i = 1;i<=n;i++){ ma[i][1] = mi[i][1] = (sum[i]%10+10)%10; } for(int j = 2;j<=m;j++) for(int i = j;i<=n;i++) for(int k = j-1;k<i;k++){ ma[i][j] = max(ma[i][j] , ma[k][j-1]*(((sum[i]-sum[k])%10+10)%10)); mi[i][j] = min(mi[i][j], mi[k][j-1]* ( ( (sum[i] - sum[k])%10+10 )%10) ); } Max = max(Max,ma[n][m]); Min = min(Min,mi[n][m]); } int main(){ Max = 0; Min = 0x3f3f3f3f; cin>>n>>m; for(int i = 1;i<=n;i++){ cin>>line[i]; line[i+n]= line[i]; } for(int i = 0;i<n;i++) dp(line+i); cout<<Min<<endl<<Max<<endl; }
23.225
82
0.455328
xiaohuihuigh
e9d6e50343051d7a46cd39ba8de15e3b50100248
2,369
cpp
C++
Source/OpenTournament/UR_Ammo.cpp
NATOcm/OpenTournament
d279034fdad80bdbacb4d0dc687c334545364688
[ "OML" ]
null
null
null
Source/OpenTournament/UR_Ammo.cpp
NATOcm/OpenTournament
d279034fdad80bdbacb4d0dc687c334545364688
[ "OML" ]
null
null
null
Source/OpenTournament/UR_Ammo.cpp
NATOcm/OpenTournament
d279034fdad80bdbacb4d0dc687c334545364688
[ "OML" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "UR_Ammo.h" #include "UR_Weapon.h" #include "UR_InventoryComponent.h" #include "Engine.h" #include "OpenTournament.h" #include "UR_Character.h" // Sets default values AUR_Ammo::AUR_Ammo(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { Tbox = CreateDefaultSubobject<UBoxComponent>(TEXT("Box")); Tbox->SetGenerateOverlapEvents(true); Tbox->OnComponentBeginOverlap.AddDynamic(this, &AUR_Ammo::OnTriggerEnter); Tbox->OnComponentEndOverlap.AddDynamic(this, &AUR_Ammo::OnTriggerExit); RootComponent = Tbox; SM_TBox = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Box Mesh")); SM_TBox->SetupAttachment(RootComponent); AmmoMesh = ObjectInitializer.CreateDefaultSubobject<UStaticMeshComponent>(this, TEXT("AmmoMesh1")); AmmoMesh->SetupAttachment(RootComponent); Sound = ObjectInitializer.CreateDefaultSubobject<UAudioComponent>(this, TEXT("Sound")); Sound->SetupAttachment(RootComponent); PrimaryActorTick.bCanEverTick = true; } // Called when the game starts or when spawned void AUR_Ammo::BeginPlay() { Super::BeginPlay(); Sound->SetActive(false); } // Called every frame void AUR_Ammo::Tick(float DeltaTime) { Super::Tick(DeltaTime); if (PlayerController != NULL) { if (bItemIsWithinRange) { Pickup(); } } } void AUR_Ammo::Pickup() { Sound->SetActive(true); Sound = UGameplayStatics::SpawnSoundAtLocation(this, Sound->Sound, this->GetActorLocation(), FRotator::ZeroRotator, 1.0f, 1.0f, 0.0f, nullptr, nullptr, true); PlayerController->InventoryComponent->Add(this); Destroy(); } void AUR_Ammo::GetPlayer(AActor* Player) { PlayerController = Cast<AUR_Character>(Player); } void AUR_Ammo::OnTriggerEnter(UPrimitiveComponent* HitComp, AActor* Other, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult) { bItemIsWithinRange = true; GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("HI this is ammo"))); GetPlayer(Other); } void AUR_Ammo::OnTriggerExit(UPrimitiveComponent* HitComp, AActor* Other, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex) { GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("BYE this is ammo"))); }
29.987342
177
0.743774
NATOcm
e9d828303c4ff6fb18b1755be725f7294977499b
629
cpp
C++
_posts/KickStart/2021_Round_B/Increasing Substring.cpp
Yukun4119/Yukun4119.github.io
152f87e46295bcb09f485bce2dd27ae2b9316d6a
[ "MIT" ]
null
null
null
_posts/KickStart/2021_Round_B/Increasing Substring.cpp
Yukun4119/Yukun4119.github.io
152f87e46295bcb09f485bce2dd27ae2b9316d6a
[ "MIT" ]
null
null
null
_posts/KickStart/2021_Round_B/Increasing Substring.cpp
Yukun4119/Yukun4119.github.io
152f87e46295bcb09f485bce2dd27ae2b9316d6a
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; #define ll long long #define ar array void solve(int len, string str){ int curSum = 1; cout << 1 << " "; for(int i = 1; i < len; i++){ if(str[i] > str[i - 1]) { curSum++; } else{ curSum = 1; } cout << curSum << " "; } } int main(){ ios::sync_with_stdio(0); cin.tie(0); int t; cin >> t; int i = 1; while(t--){ int len; string str; cin >> len >> str; cout << "Case #" << i++ << ": "; solve(len, str); cout << endl; } }
17
40
0.406995
Yukun4119
e9da2f8a629a8c55e28158299f6c63c553f29559
13,581
cpp
C++
spine-cocos2dx/MBSpineFramework/cocos2d-x-3.17.2/tests/performance-tests/Classes/tests/controller.cpp
BowenCoder/spine-cocos2dx
cfac5100b78782b2d4ce84b472a435f46aff4da9
[ "MIT" ]
null
null
null
spine-cocos2dx/MBSpineFramework/cocos2d-x-3.17.2/tests/performance-tests/Classes/tests/controller.cpp
BowenCoder/spine-cocos2dx
cfac5100b78782b2d4ce84b472a435f46aff4da9
[ "MIT" ]
null
null
null
spine-cocos2dx/MBSpineFramework/cocos2d-x-3.17.2/tests/performance-tests/Classes/tests/controller.cpp
BowenCoder/spine-cocos2dx
cfac5100b78782b2d4ce84b472a435f46aff4da9
[ "MIT" ]
null
null
null
/**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. http://www.cocos2d-x.org 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 "controller.h" #include <functional> #include <chrono> #include "BaseTest.h" #include "tests.h" #include "Profile.h" USING_NS_CC; #define TEST_TIME_OUT 6000 #define CREATE_TIME_OUT 25 #define LOG_INDENTATION " " #define LOG_TAG "[TestController]" static void initCrashCatch(); static void disableCrashCatch(); class RootTests : public TestList { public: RootTests() { addTest("Alloc Tests", []() { return new PerformceAllocTests(); }); addTest("Node Children Tests", []() { return new PerformceNodeChildrenTests(); }); addTest("Particle Tests", []() { return new PerformceParticleTests(); }); addTest("Particle3D Tests", []() { return new PerformceParticle3DTests(); }); addTest("Sprite Tests", []() { return new PerformceSpriteTests(); }); addTest("Texture Tests", []() { return new PerformceTextureTests(); }); addTest("Label Tests", []() { return new PerformceLabelTests(); }); addTest("EventDispatcher Tests", []() { return new PerformceEventDispatcherTests(); }); addTest("Scenario Tests", []() { return new PerformceScenarioTests(); }); addTest("Callback Tests", []() { return new PerformceCallbackTests(); }); addTest("Math Tests", []() { return new PerformceMathTests(); }); addTest("Container Tests", []() { return new PerformceContainerTests(); }); } }; TestController::TestController() : _stopAutoTest(true) , _isRunInBackground(false) , _testSuite(nullptr) { _director = Director::getInstance(); _rootTestList = new (std::nothrow) RootTests; _rootTestList->runThisTest(); } TestController::~TestController() { _rootTestList->release(); _rootTestList = nullptr; } void TestController::startAutoTest() { if (!_autoTestThread.joinable()) { _stopAutoTest = false; _logIndentation = ""; _autoTestThread = std::thread(&TestController::traverseThreadFunc, this); _autoTestThread.detach(); } } void TestController::stopAutoTest() { _stopAutoTest = true; if (_autoTestThread.joinable()) { _sleepCondition.notify_all(); _autoTestThread.join(); } } void TestController::traverseThreadFunc() { std::mutex sleepMutex; auto lock = std::unique_lock<std::mutex>(sleepMutex); _sleepUniqueLock = &lock; traverseTestList(_rootTestList); _sleepUniqueLock = nullptr; // write the test data into file. Profile::getInstance()->flush(); Profile::destroyInstance(); } void TestController::traverseTestList(TestList* testList) { if (testList == _rootTestList) { _sleepCondition.wait_for(*_sleepUniqueLock, std::chrono::milliseconds(500)); } else { _logIndentation += LOG_INDENTATION; _sleepCondition.wait_for(*_sleepUniqueLock, std::chrono::milliseconds(500)); } logEx("%s%sBegin traverse TestList:%s", LOG_TAG, _logIndentation.c_str(), testList->getTestName().c_str()); auto scheduler = _director->getScheduler(); int testIndex = 0; for (auto& callback : testList->_testCallbacks) { if (_stopAutoTest) break; while (_isRunInBackground) { logEx("_director is paused"); _sleepCondition.wait_for(*_sleepUniqueLock, std::chrono::milliseconds(500)); } if (callback) { auto test = callback(); test->setTestParent(testList); test->setTestName(testList->_childTestNames[testIndex++]); if (test->isTestList()) { scheduler->performFunctionInCocosThread([&](){ test->runThisTest(); }); traverseTestList((TestList*)test); } else { traverseTestSuite((TestSuite*)test); } } } if (testList == _rootTestList) { _stopAutoTest = true; } else { if (!_stopAutoTest) { //Backs up one level and release TestList object. scheduler->performFunctionInCocosThread([&](){ testList->_parentTest->runThisTest(); }); _sleepCondition.wait_for(*_sleepUniqueLock, std::chrono::milliseconds(500)); testList->release(); } _logIndentation.erase(_logIndentation.rfind(LOG_INDENTATION)); } } void TestController::traverseTestSuite(TestSuite* testSuite) { auto scheduler = _director->getScheduler(); int testIndex = 0; float testCaseDuration = 0.0f; _logIndentation += LOG_INDENTATION; logEx("%s%sBegin traverse TestSuite:%s", LOG_TAG, _logIndentation.c_str(), testSuite->getTestName().c_str()); _logIndentation += LOG_INDENTATION; testSuite->_currTestIndex = -1; auto logIndentation = _logIndentation; for (auto& callback : testSuite->_testCallbacks) { auto testName = testSuite->_childTestNames[testIndex++]; Scene* testScene = nullptr; TestCase* testCase = nullptr; TransitionScene* transitionScene = nullptr; if (_stopAutoTest) break; while (_isRunInBackground) { logEx("_director is paused"); _sleepCondition.wait_for(*_sleepUniqueLock, std::chrono::milliseconds(500)); } //Run test case in the cocos[GL] thread. scheduler->performFunctionInCocosThread([&, logIndentation, testName](){ if (_stopAutoTest) return; logEx("%s%sRun test:%s.", LOG_TAG, logIndentation.c_str(), testName.c_str()); auto scene = callback(); if (_stopAutoTest) return; if (scene) { transitionScene = dynamic_cast<TransitionScene*>(scene); if (transitionScene) { testCase = (TestCase*)transitionScene->getInScene(); testCaseDuration = transitionScene->getDuration() + 0.5f; } else { testCase = (TestCase*)scene; testCaseDuration = testCase->getDuration(); } testSuite->_currTestIndex++; testCase->setTestSuite(testSuite); testCase->setTestCaseName(testName); testCase->setAutoTesting(true); _director->replaceScene(scene); testScene = scene; } }); if (_stopAutoTest) break; //Wait for the test case be created. float waitTime = 0.0f; while (!testScene && !_stopAutoTest) { _sleepCondition.wait_for(*_sleepUniqueLock, std::chrono::milliseconds(50)); if (!_isRunInBackground) { waitTime += 0.05f; } if (waitTime > CREATE_TIME_OUT) { logEx("%sCreate test %s time out", LOG_TAG, testName.c_str()); _stopAutoTest = true; break; } } if (_stopAutoTest) break; //Wait for test completed. _sleepCondition.wait_for(*_sleepUniqueLock, std::chrono::milliseconds(int(1000 * testCaseDuration))); if (transitionScene == nullptr) { waitTime = 0.0f; while (!_stopAutoTest && testCase->isAutoTesting()) { _sleepCondition.wait_for(*_sleepUniqueLock, std::chrono::milliseconds(50)); if (!_isRunInBackground) { waitTime += 0.05f; } if (waitTime > TEST_TIME_OUT) { logEx("%sRun test %s time out", LOG_TAG, testName.c_str()); _stopAutoTest = true; break; } } if (!_stopAutoTest) { //Check the result of test. checkTest(testCase); } } } if (!_stopAutoTest) { //Backs up one level and release TestSuite object. auto parentTest = testSuite->_parentTest; scheduler->performFunctionInCocosThread([parentTest](){ parentTest->runThisTest(); }); _sleepCondition.wait_for(*_sleepUniqueLock, std::chrono::milliseconds(1000)); testSuite->release(); } _logIndentation.erase(_logIndentation.rfind(LOG_INDENTATION)); _logIndentation.erase(_logIndentation.rfind(LOG_INDENTATION)); } bool TestController::checkTest(TestCase* testCase) { if (testCase) { switch (testCase->getTestType()) { case TestCase::Type::UNIT: { if (testCase && testCase->getExpectedOutput() != testCase->getActualOutput()) { logEx("%s %s test fail", LOG_TAG, testCase->getTestCaseName().c_str()); } else { logEx("%s %s test pass", LOG_TAG, testCase->getTestCaseName().c_str()); } break; } case TestCase::Type::ROBUSTNESS: { break; } case TestCase::Type::MANUAL: { break; } default: break; } } return true; } void TestController::handleCrash() { disableCrashCatch(); logEx("%sCatch an crash event", LOG_TAG); if (!_stopAutoTest) { stopAutoTest(); } } void TestController::onEnterBackground() { _isRunInBackground = true; } void TestController::onEnterForeground() { _isRunInBackground = false; } void TestController::logEx(const char * format, ...) { char buff[1024]; va_list args; va_start(args, format); vsnprintf(buff, 1020, format, args); strcat(buff, "\n"); #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID __android_log_print(ANDROID_LOG_DEBUG, "cocos2d-x debug info", "%s", buff); #elif CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT WCHAR wszBuf[1024] = { 0 }; MultiByteToWideChar(CP_UTF8, 0, buff, -1, wszBuf, sizeof(wszBuf)); OutputDebugStringW(wszBuf); #else // Linux, Mac, iOS, etc fprintf(stdout, "%s", buff); fflush(stdout); #endif va_end(args); } static TestController* s_testController = nullptr; TestController* TestController::getInstance() { if (s_testController == nullptr) { s_testController = new (std::nothrow) TestController; initCrashCatch(); } return s_testController; } void TestController::destroyInstance() { if (s_testController) { s_testController->stopAutoTest(); delete s_testController; s_testController = nullptr; } disableCrashCatch(); } bool TestController::blockTouchBegan(Touch* touch, Event* event) { return !_stopAutoTest; } //================================================================================================== #if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 #include <windows.h> static long __stdcall windowExceptionFilter(_EXCEPTION_POINTERS* excp) { if (s_testController) { s_testController->handleCrash(); } return EXCEPTION_EXECUTE_HANDLER; } static void initCrashCatch() { SetUnhandledExceptionFilter(windowExceptionFilter); } static void disableCrashCatch() { SetUnhandledExceptionFilter(UnhandledExceptionFilter); } #elif CC_TARGET_PLATFORM == CC_PLATFORM_MAC || CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID static int s_fatal_signals[] = { SIGILL, SIGABRT, SIGBUS, SIGFPE, SIGSEGV, SIGSTKFLT, SIGPIPE, }; #else static int s_fatal_signals[] = { SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV, SIGTRAP, SIGTERM, SIGKILL }; #endif static void signalHandler(int sig) { if (s_testController) { s_testController->handleCrash(); } } static void initCrashCatch() { for (auto sig : s_fatal_signals) { signal(sig, signalHandler); } } static void disableCrashCatch() { for (auto sig : s_fatal_signals) { signal(sig, SIG_DFL); } } #else static void initCrashCatch() { } static void disableCrashCatch() { } #endif
27.381048
129
0.600545
BowenCoder
e9dba42178d9d92f71535b72fa3fb4a4ab1115f5
6,214
cc
C++
src/quicksilver/PopulationControl.cc
cpc/hipcl-samples
59ce99784b5e3158a9e23a9790a277586ada70e5
[ "MIT" ]
1
2020-12-29T21:44:16.000Z
2020-12-29T21:44:16.000Z
src/quicksilver/PopulationControl.cc
cpc/hipcl-samples
59ce99784b5e3158a9e23a9790a277586ada70e5
[ "MIT" ]
null
null
null
src/quicksilver/PopulationControl.cc
cpc/hipcl-samples
59ce99784b5e3158a9e23a9790a277586ada70e5
[ "MIT" ]
1
2020-04-09T22:04:18.000Z
2020-04-09T22:04:18.000Z
#include "PopulationControl.hh" #include "Globals.hh" #include "MC_Particle.hh" #include "MC_Processor_Info.hh" #include "MonteCarlo.hh" #include "NVTX_Range.hh" #include "ParticleVault.hh" #include "ParticleVaultContainer.hh" #include "utilsMpi.hh" #include <vector> namespace { void PopulationControlGuts(const double splitRRFactor, uint64_t currentNumParticles, ParticleVaultContainer *my_particle_vault, Balance &taskBalance); } void PopulationControl(MonteCarlo *monteCarlo, bool loadBalance) { NVTX_Range range("PopulationControl"); uint64_t targetNumParticles = monteCarlo->_params.simulationParams.nParticles; uint64_t globalNumParticles = 0; uint64_t localNumParticles = monteCarlo->_particleVaultContainer->sizeProcessing(); if (loadBalance) { // If we are parallel, we will have one domain per mpi processs. The // targetNumParticles is across all MPI processes, so we need to divide by // the number or ranks to get the per-mpi-process number targetNumParticles targetNumParticles = ceil((double)targetNumParticles / (double)mcco->processor_info->num_processors); // NO LONGER SPLITING VAULTS BY THREADS // // If we are threaded, targetNumParticles should be divided by the // number of threads (tasks) to balance // // the particles across the thread level vaults. // targetNumParticles = ceil((double)targetNumParticles / // (double)mcco->processor_info->num_tasks); } else { mpiAllreduce(&localNumParticles, &globalNumParticles, 1, MPI_UINT64_T, MPI_SUM, MPI_COMM_WORLD); } Balance &taskBalance = monteCarlo->_tallies->_balanceTask[0]; double splitRRFactor = 1.0; if (loadBalance) { int currentNumParticles = localNumParticles; if (currentNumParticles != 0) splitRRFactor = (double)targetNumParticles / (double)currentNumParticles; else splitRRFactor = 1.0; } else { splitRRFactor = (double)targetNumParticles / (double)globalNumParticles; } if (splitRRFactor != 1.0) // no need to split if population is already correct. PopulationControlGuts(splitRRFactor, localNumParticles, monteCarlo->_particleVaultContainer, taskBalance); monteCarlo->_particleVaultContainer->collapseProcessing(); return; } namespace { void PopulationControlGuts(const double splitRRFactor, uint64_t currentNumParticles, ParticleVaultContainer *my_particle_vault, Balance &taskBalance) { uint64_t vault_size = my_particle_vault->getVaultSize(); uint64_t fill_vault_index = currentNumParticles / vault_size; // March backwards through the vault so killed particles doesn't mess up the // indexing for (int particleIndex = currentNumParticles - 1; particleIndex >= 0; particleIndex--) { uint64_t vault_index = particleIndex / vault_size; ParticleVault &taskProcessingVault = *(my_particle_vault->getTaskProcessingVault(vault_index)); uint64_t taskParticleIndex = particleIndex % vault_size; MC_Base_Particle &currentParticle = taskProcessingVault[taskParticleIndex]; double randomNumber = rngSample(&currentParticle.random_number_seed); if (splitRRFactor < 1) { if (randomNumber > splitRRFactor) { // Kill taskProcessingVault.eraseSwapParticle(taskParticleIndex); taskBalance._rr++; } else { currentParticle.weight /= splitRRFactor; } } else if (splitRRFactor > 1) { // Split int splitFactor = (int)floor(splitRRFactor); if (randomNumber > (splitRRFactor - splitFactor)) { splitFactor--; } currentParticle.weight /= splitRRFactor; MC_Base_Particle splitParticle = currentParticle; for (int splitFactorIndex = 0; splitFactorIndex < splitFactor; splitFactorIndex++) { taskBalance._split++; splitParticle.random_number_seed = rngSpawn_Random_Number_Seed(&currentParticle.random_number_seed); splitParticle.identifier = splitParticle.random_number_seed; my_particle_vault->addProcessingParticle(splitParticle, fill_vault_index); } } } } } // anonymous namespace // Roulette low-weight particles relative to the source particle weight. void RouletteLowWeightParticles(MonteCarlo *monteCarlo) { NVTX_Range range("RouletteLowWeightParticles"); const double lowWeightCutoff = monteCarlo->_params.simulationParams.lowWeightCutoff; if (lowWeightCutoff > 0.0) { uint64_t currentNumParticles = monteCarlo->_particleVaultContainer->sizeProcessing(); uint64_t vault_size = monteCarlo->_particleVaultContainer->getVaultSize(); Balance &taskBalance = monteCarlo->_tallies->_balanceTask[0]; // March backwards through the vault so killed particles don't mess up the // indexing const double source_particle_weight = monteCarlo->source_particle_weight; const double weightCutoff = lowWeightCutoff * source_particle_weight; for (int64_t particleIndex = currentNumParticles - 1; particleIndex >= 0; particleIndex--) { uint64_t vault_index = particleIndex / vault_size; ParticleVault &taskProcessingVault = *(monteCarlo->_particleVaultContainer->getTaskProcessingVault( vault_index)); uint64_t taskParticleIndex = particleIndex % vault_size; MC_Base_Particle &currentParticle = taskProcessingVault[taskParticleIndex]; if (currentParticle.weight <= weightCutoff) { double randomNumber = rngSample(&currentParticle.random_number_seed); if (randomNumber <= lowWeightCutoff) { // The particle history continues with an increased weight. currentParticle.weight /= lowWeightCutoff; } else { // Kill taskProcessingVault.eraseSwapParticle(taskParticleIndex); taskBalance._rr++; } } } monteCarlo->_particleVaultContainer->collapseProcessing(); } }
36.769231
80
0.691664
cpc
e9de7686b8409d39b981c1368ed62c5d3aeef028
212
cc
C++
src/commands/text_processing/TSR.cc
jhhuh/imgui-terminal
134f9cb6779738ecf00d6aba8315702986f71115
[ "MIT" ]
32
2017-09-19T07:25:29.000Z
2022-03-21T08:21:48.000Z
src/commands/text_processing/TSR.cc
jhhuh/imgui-terminal
134f9cb6779738ecf00d6aba8315702986f71115
[ "MIT" ]
1
2017-10-24T18:56:36.000Z
2017-10-24T18:56:36.000Z
src/commands/text_processing/TSR.cc
jhhuh/imgui-terminal
134f9cb6779738ecf00d6aba8315702986f71115
[ "MIT" ]
10
2017-10-18T05:08:14.000Z
2022-03-21T09:29:04.000Z
#include <terminal/Terminal.hh> namespace terminal { // Tabulation Stop Remove // ECMA-48 8.3.156 bool Terminal::TSR(uint32_t p) { // no default log("TSR(%u)", p); //! @todo return false; } }
10.095238
31
0.608491
jhhuh
e9e194746202dfce6120c13d255a498a8d780fd5
2,848
cpp
C++
Deitel/Chapter05/exercises/5.30/Question.cpp
SebastianTirado/Cpp-Learning-Archive
fb83379d0cc3f9b2390cef00119464ec946753f4
[ "MIT" ]
19
2019-09-15T12:23:51.000Z
2020-06-18T08:31:26.000Z
Deitel/Chapter05/exercises/5.30/Question.cpp
eirichan/CppLearingArchive
07a4baf63f0765d41eb0cc6d32a4c9d2ae1d5bac
[ "MIT" ]
15
2021-12-07T06:46:03.000Z
2022-01-31T07:55:32.000Z
Deitel/Chapter05/exercises/5.30/Question.cpp
eirichan/CppLearingArchive
07a4baf63f0765d41eb0cc6d32a4c9d2ae1d5bac
[ "MIT" ]
13
2019-06-29T02:58:27.000Z
2020-05-07T08:52:22.000Z
/* * ===================================================================================== * * Filename: * * Description: * * Version: 1.0 * Created: Thanks to github you know it * Revision: none * Compiler: g++ * * Author: Mahmut Erdem ÖZGEN [email protected] * * * ===================================================================================== */ #include <string> #include "Question.hpp" // INITIALISATION // checks if question and answers are set and sets them if not // creates and randomises an answers vector void Question::initialise() { std::string tmp; if (_q.empty()) { std::cout << "Enter a question: "; std::cin >> tmp; setQuestion(tmp); } if (_a.empty()) { std::cout << "Enter correct answer: "; std::cin >> tmp; setA(tmp); } if (_b.empty()) { std::cout << "Enter first incorrect answer: "; std::cin >> tmp; setB(tmp); } if (_c.empty()) { std::cout << "Enter second incorrect answer: "; std::cin >> tmp; setC(tmp); } if (_d.empty()) { std::cout << "Enter third incorrect answer: "; std::cin >> tmp; setD(tmp); } // build the answers vector _answers.push_back(_a); _answers.push_back(_b); _answers.push_back(_c); _answers.push_back(_d); // randomise answers vector unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); shuffle(_answers.begin(), _answers.end(), std::default_random_engine(seed)); } // SETTERS void Question::setQuestion(const std::string& Q) { _q = Q; } void Question::setA(const std::string& A) { _a = A; } void Question::setB(const std::string& B) { _b = B; } void Question::setC(const std::string& C) { _c = C; } void Question::setD(const std::string& D) { _d = D; } // GETTERS // prints the question and randomised answers vector void Question::getQuestion() const { // question std::cout << _q << std::endl << std::endl; // answers for (unsigned int i = 0; i < _answers.size(); i++) { std::cout << _answers[i] << std::endl; } std::cout << std::endl; } // answer the question // CHAR ANSWER bool Question::answer(char& ans) { if (ans == 'a' && _answers[0] == _a) { _correct = 1; return true; } if (ans == 'b' && _answers[1] == _a) { _correct = 1; return true; } if (ans == 'c' && _answers[2] == _a) { _correct = 1; return true; } if (ans == 'd' && _answers[3] == _a) { _correct = 1; return true; } return false; } // INT ANSWER bool Question::answer(int ans) { ans--; if (_answers[ans] == _a) { _correct = 1; return true; } return false; }
24.982456
88
0.508076
SebastianTirado