hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
a598bfd07d0f3549d66728365e23343926e4b384
2,441
hpp
C++
include/nodes.hpp
mvousden/psap
5837ef787b80d1d4fe33286561c0537d1581d578
[ "BSD-3-Clause" ]
null
null
null
include/nodes.hpp
mvousden/psap
5837ef787b80d1d4fe33286561c0537d1581d578
[ "BSD-3-Clause" ]
null
null
null
include/nodes.hpp
mvousden/psap
5837ef787b80d1d4fe33286561c0537d1581d578
[ "BSD-3-Clause" ]
null
null
null
#ifndef NODES_HPP #define NODES_HPP #include <atomic> #include <memory> #include <mutex> #include <string> #include <set> #include <vector> class NodeH; /* A circle necessary for reasonable performance. */ typedef unsigned TransformCount; /* Nodes in general. All nodes are named. * * Locking and transformation behaviour is dependent on the properties of the * annealer: * * - Serial annealer: `lock` and `transformCount` are not used (and should be * optimised out during compilation). Synchronisation primitives are not * needed in the serial case. * * - Parallel synchronous annealer: The selected application node, the selected * hardware node, the hardware node origin of the selected application node, * and all neighbours of the application node are locked at selection * time. The atomic `transformCount` members are not used (and should be * optimised out during compilation). * * - Parallel semi-asynchronous annealer: Only the selected application node is * locked at selection time. Hardware nodes are locked on * transformation. This is the minimum amount of locking required to maintain * the data structure, and will result in computation with stale data. The * atomic `transformCount` members are used to identify whether a node has * been transformed compared to a known starting point. It does not matter if * they wrap, as only a difference in counter value is checked for (and * wrapping all the way around in one iteration is nigh-on impossible with * few compute workers). `transformCount` is only used while logging is * enabled, and so should be optimised out when logging is disabled. */ class Node { public: Node(std::string name): name(name){} std::string name; std::mutex lock; std::atomic<TransformCount> transformCount = 0; }; /* Node in the application graph. */ class NodeA: public Node { public: NodeA(std::string name): Node(name){} std::weak_ptr<NodeH> location; std::vector<std::weak_ptr<NodeA>> neighbours; }; /* Node in the hardware graph. */ class NodeH: public Node { public: NodeH(std::string name, unsigned index): Node(name), index(index){} NodeH(std::string name, unsigned index, float posHoriz, float posVerti): Node(name), index(index), posHoriz(posHoriz), posVerti(posVerti){} std::set<NodeA*> contents; unsigned index; float posHoriz = -1; float posVerti = -1; }; #endif
34.380282
79
0.723474
[ "vector" ]
a59ca54fbc4e0ea95e6153d3fee39b032b20eefb
22,263
cc
C++
tests/ut/ge/graph/passes/buffer_pool_memory_pass_unittest.cc
mindspore-ai/graphengine
460406cbd691b963d125837f022be5d8abd1a637
[ "Apache-2.0" ]
207
2020-03-28T02:12:50.000Z
2021-11-23T18:27:45.000Z
tests/ut/ge/graph/passes/buffer_pool_memory_pass_unittest.cc
mindspore-ai/graphengine
460406cbd691b963d125837f022be5d8abd1a637
[ "Apache-2.0" ]
4
2020-04-17T07:32:44.000Z
2021-06-26T04:55:03.000Z
tests/ut/ge/graph/passes/buffer_pool_memory_pass_unittest.cc
mindspore-ai/graphengine
460406cbd691b963d125837f022be5d8abd1a637
[ "Apache-2.0" ]
13
2020-03-28T02:52:26.000Z
2021-07-03T23:12:54.000Z
/** * Copyright 2019-2020 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <gtest/gtest.h> #include "common/ge_inner_error_codes.h" #include "common/types.h" #include "graph/manager/graph_var_manager.h" #include "graph/utils/attr_utils.h" #include "graph/utils/graph_utils.h" #include "graph/utils/tensor_utils.h" #include "inc/pass_manager.h" #include "graph_builder_utils.h" #include "../utils/buffer_pool_graph_builder.h" #include "graph/passes/buffer_pool_memory_pass.h" namespace ge { class UtestBufferPoolMemoryPass : public testing::Test { protected: void SetUp() {} void TearDown() {} }; TEST_F(UtestBufferPoolMemoryPass, buffer_pool_normal_success_test) { ut::BufferPoolGraphBuilder builder("NormalGraph"); ge::ComputeGraphPtr graph = builder.BuildNormalGraph(); BufferPoolMemoryPass buffer_pool_mem_pass; Status ret = buffer_pool_mem_pass.Run(graph); EXPECT_EQ(ret, SUCCESS); { std::vector<std::string> event_info; auto prefetch = graph->FindNode("prefetch1"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 1); EXPECT_EQ(event_info.at(0), "SendTo;add1;0"); } { std::vector<std::string> event_info; auto prefetch = graph->FindNode("prefetch2"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 1); EXPECT_EQ(event_info.at(0), "SendTo;add2;1"); } { std::vector<std::string> event_info; auto prefetch = graph->FindNode("prefetch3"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 1); EXPECT_EQ(event_info.at(0), "SendTo;add3;2"); } { std::vector<std::string> event_info; auto prefetch = graph->FindNode("prefetch4"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 2); EXPECT_EQ(event_info.at(0), "SendTo;add4;3"); EXPECT_EQ(event_info.at(1), "RecvFrom;add2;0"); auto in_ctrl_nodes = prefetch->GetInControlNodes(); EXPECT_EQ(in_ctrl_nodes.size(), 2); EXPECT_EQ(in_ctrl_nodes.at(0)->GetName(), "add2"); } { std::vector<std::string> event_info; auto prefetch = graph->FindNode("prefetch5"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 2); EXPECT_EQ(event_info.at(0), "SendTo;add5;0"); EXPECT_EQ(event_info.at(1), "RecvFrom;add3;1"); auto in_ctrl_nodes = prefetch->GetInControlNodes(); EXPECT_EQ(in_ctrl_nodes.size(), 2); EXPECT_EQ(in_ctrl_nodes.at(0)->GetName(), "add3"); } } TEST_F(UtestBufferPoolMemoryPass, buffer_pool_normal_graph_with_multi_buffer_pool_success_test) { ut::BufferPoolGraphBuilder builder("NormalGraphWithMultiBufferPool"); ge::ComputeGraphPtr graph = builder.BuildNormalGraphWithMultiBufferPool(); BufferPoolMemoryPass buffer_pool_mem_pass; Status ret = buffer_pool_mem_pass.Run(graph); EXPECT_EQ(ret, SUCCESS); { std::vector<std::string> event_info; auto prefetch = graph->FindNode("prefetch1"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 1); EXPECT_EQ(event_info.at(0), "SendTo;add1;0"); } { std::vector<std::string> event_info; auto prefetch = graph->FindNode("prefetch2"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 1); EXPECT_EQ(event_info.at(0), "SendTo;add2;3"); } { std::vector<std::string> event_info; auto prefetch = graph->FindNode("prefetch3"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 1); EXPECT_EQ(event_info.at(0), "SendTo;add3;1"); } { std::vector<std::string> event_info; auto prefetch = graph->FindNode("prefetch4"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 2); EXPECT_EQ(event_info.at(0), "SendTo;add4;2"); EXPECT_EQ(event_info.at(1), "RecvFrom;add3;0"); auto in_ctrl_nodes = prefetch->GetInControlNodes(); EXPECT_EQ(in_ctrl_nodes.size(), 2); EXPECT_EQ(in_ctrl_nodes.at(0)->GetName(), "add3"); } { std::vector<std::string> event_info; auto prefetch = graph->FindNode("prefetch5"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 1); EXPECT_EQ(event_info.at(0), "SendTo;add5;4"); } } TEST_F(UtestBufferPoolMemoryPass, buffer_pool_contain_one_node_success_test) { ut::BufferPoolGraphBuilder builder("SerialGraph"); ge::ComputeGraphPtr graph = builder.BuildSerialGraph(); BufferPoolMemoryPass buffer_pool_mem_pass; Status ret = buffer_pool_mem_pass.Run(graph); EXPECT_EQ(ret, SUCCESS); { std::vector<std::string> event_info; auto prefetch = graph->FindNode("prefetch1"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 1); EXPECT_EQ(event_info.at(0), "SendTo;add1;0"); } { std::vector<std::string> event_info; auto prefetch = graph->FindNode("prefetch2"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 2); EXPECT_EQ(event_info.at(0), "SendTo;add2;1"); EXPECT_EQ(event_info.at(1), "RecvFrom;add1;2"); auto in_ctrl_nodes = prefetch->GetInControlNodes(); EXPECT_EQ(in_ctrl_nodes.size(), 2); EXPECT_EQ(in_ctrl_nodes.at(0)->GetName(), "add1"); } { std::vector<std::string> event_info; auto prefetch = graph->FindNode("prefetch3"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 2); EXPECT_EQ(event_info.at(0), "SendTo;add3;2"); EXPECT_EQ(event_info.at(1), "RecvFrom;add2;0"); auto in_ctrl_nodes = prefetch->GetInControlNodes(); EXPECT_EQ(in_ctrl_nodes.size(), 2); EXPECT_EQ(in_ctrl_nodes.at(0)->GetName(), "add2"); } { std::vector<std::string> event_info; auto prefetch = graph->FindNode("prefetch4"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 2); EXPECT_EQ(event_info.at(0), "SendTo;add4;0"); EXPECT_EQ(event_info.at(1), "RecvFrom;add3;1"); auto in_ctrl_nodes = prefetch->GetInControlNodes(); EXPECT_EQ(in_ctrl_nodes.size(), 2); EXPECT_EQ(in_ctrl_nodes.at(0)->GetName(), "add3"); } { std::vector<std::string> event_info; auto prefetch = graph->FindNode("prefetch5"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 2); EXPECT_EQ(event_info.at(0), "SendTo;add5;1"); EXPECT_EQ(event_info.at(1), "RecvFrom;add4;2"); auto in_ctrl_nodes = prefetch->GetInControlNodes(); EXPECT_EQ(in_ctrl_nodes.size(), 2); EXPECT_EQ(in_ctrl_nodes.at(0)->GetName(), "add4"); } } TEST_F(UtestBufferPoolMemoryPass, calc_node_with_multi_buffer_pool_input_success_test) { ut::BufferPoolGraphBuilder builder("GraphWithMultiPrefetch"); ge::ComputeGraphPtr graph = builder.BuildGraphWithMultiPrefetch(); BufferPoolMemoryPass buffer_pool_mem_pass; Status ret = buffer_pool_mem_pass.Run(graph); EXPECT_EQ(ret, SUCCESS); { std::vector<std::string> event_info; auto prefetch = graph->FindNode("prefetch1"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 0); } { std::vector<std::string> event_info; auto prefetch = graph->FindNode("prefetch2"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 1); EXPECT_EQ(event_info.at(0), "SendTo;add1;0"); } { std::vector<std::string> event_info; auto prefetch = graph->FindNode("prefetch3"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 0); } { std::vector<std::string> event_info; auto prefetch = graph->FindNode("prefetch4"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 2); EXPECT_EQ(event_info.at(0), "SendTo;add2;1"); EXPECT_EQ(event_info.at(1), "RecvFrom;add1;2"); auto in_ctrl_nodes = prefetch->GetInControlNodes(); EXPECT_EQ(in_ctrl_nodes.size(), 2); EXPECT_EQ(in_ctrl_nodes.at(0)->GetName(), "add1"); } { std::vector<std::string> event_info; auto prefetch = graph->FindNode("prefetch5"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 2); EXPECT_EQ(event_info.at(0), "SendTo;add3;2"); EXPECT_EQ(event_info.at(1), "RecvFrom;add2;0"); auto in_ctrl_nodes = prefetch->GetInControlNodes(); EXPECT_EQ(in_ctrl_nodes.size(), 2); EXPECT_EQ(in_ctrl_nodes.at(0)->GetName(), "add2"); } } TEST_F(UtestBufferPoolMemoryPass, buffer_pool_in_different_subgraph_success_test) { ut::BufferPoolGraphBuilder builder("GraphWithSubgraph"); ge::ComputeGraphPtr graph = builder.BuildGraphWithSubgraph(); BufferPoolMemoryPass buffer_pool_mem_pass; Status ret = buffer_pool_mem_pass.Run(graph); EXPECT_EQ(ret, SUCCESS); std::map<std::string, NodePtr> all_nodes; for (auto node : graph->GetAllNodes()) { EXPECT_NE(node, nullptr); all_nodes[node->GetName()] = node; } { std::vector<std::string> event_info; auto prefetch = all_nodes.at("prefetch1"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 1); EXPECT_EQ(event_info.at(0), "SendTo;add1;0"); } { std::vector<std::string> event_info; auto prefetch = all_nodes.at("prefetch2"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 1); EXPECT_EQ(event_info.at(0), "SendTo;add2;1"); } { std::vector<std::string> event_info; auto prefetch = all_nodes.at("prefetch3"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 1); EXPECT_EQ(event_info.at(0), "SendTo;add3;2"); } { std::vector<std::string> event_info; auto prefetch = all_nodes.at("prefetch4"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 1); EXPECT_EQ(event_info.at(0), "SendTo;add4;3"); auto in_ctrl_nodes = prefetch->GetInControlNodes(); EXPECT_EQ(in_ctrl_nodes.size(), 0); } { std::vector<std::string> event_info; auto prefetch = all_nodes.at("prefetch5"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 1); EXPECT_EQ(event_info.at(0), "SendTo;add5;4"); auto in_ctrl_nodes = prefetch->GetInControlNodes(); EXPECT_EQ(in_ctrl_nodes.size(), 1); EXPECT_EQ(in_ctrl_nodes.at(0)->GetName(), "prefetch4"); } } TEST_F(UtestBufferPoolMemoryPass, buffer_pool_in_different_subgraph_with_inner_dependency_success_test) { ut::BufferPoolGraphBuilder builder("SubgraphWithInnerDependency"); ge::ComputeGraphPtr graph = builder.BuildSubgraphWithInnerDependency(); BufferPoolMemoryPass buffer_pool_mem_pass; Status ret = buffer_pool_mem_pass.Run(graph); EXPECT_EQ(ret, SUCCESS); std::map<std::string, NodePtr> all_nodes; for (auto node : graph->GetAllNodes()) { EXPECT_NE(node, nullptr); all_nodes[node->GetName()] = node; } { std::vector<std::string> event_info; auto prefetch = all_nodes.at("prefetch1"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 1); EXPECT_EQ(event_info.at(0), "SendTo;add1;0"); } { std::vector<std::string> event_info; auto prefetch = all_nodes.at("prefetch2"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 1); EXPECT_EQ(event_info.at(0), "SendTo;add2;1"); } { std::vector<std::string> event_info; auto prefetch = all_nodes.at("prefetch3"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 1); EXPECT_EQ(event_info.at(0), "SendTo;add3;2"); } { std::vector<std::string> event_info; auto prefetch = all_nodes.at("prefetch4"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 1); EXPECT_EQ(event_info.at(0), "SendTo;add4;3"); auto in_ctrl_nodes = prefetch->GetInControlNodes(); EXPECT_EQ(in_ctrl_nodes.size(), 1); EXPECT_EQ(in_ctrl_nodes.at(0)->GetName(), "prefetch3"); } { std::vector<std::string> event_info; auto prefetch = all_nodes.at("prefetch5"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 2); EXPECT_EQ(event_info.at(0), "SendTo;add5;4"); EXPECT_EQ(event_info.at(1), "RecvFrom;add3;0"); auto in_ctrl_nodes = prefetch->GetInControlNodes(); EXPECT_EQ(in_ctrl_nodes.size(), 2); EXPECT_EQ(in_ctrl_nodes.at(0)->GetName(), "add3"); } } TEST_F(UtestBufferPoolMemoryPass, buffer_pool_with_batch_label_success_test) { ut::BufferPoolGraphBuilder builder("GraphWithMultiBatch"); ge::ComputeGraphPtr graph = builder.BuildGraphWithMultiBatch(); BufferPoolMemoryPass buffer_pool_mem_pass; Status ret = buffer_pool_mem_pass.Run(graph); EXPECT_EQ(ret, SUCCESS); { std::vector<std::string> event_info; auto prefetch = graph->FindNode("batch_label_256/prefetch1"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 1); EXPECT_EQ(event_info.at(0), "SendTo;batch_label_256/add1;4"); } { std::vector<std::string> event_info; auto prefetch = graph->FindNode("batch_label_256/prefetch2"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 1); EXPECT_EQ(event_info.at(0), "SendTo;batch_label_256/add2;5"); } { std::vector<std::string> event_info; auto prefetch = graph->FindNode("batch_label_256/prefetch3"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 1); EXPECT_EQ(event_info.at(0), "SendTo;batch_label_256/add3;6"); } { std::vector<std::string> event_info; auto prefetch = graph->FindNode("batch_label_256/prefetch4"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 2); EXPECT_EQ(event_info.at(0), "SendTo;batch_label_256/add4;7"); EXPECT_EQ(event_info.at(1), "RecvFrom;batch_label_256/add2;4"); auto in_ctrl_nodes = prefetch->GetInControlNodes(); EXPECT_EQ(in_ctrl_nodes.size(), 2); EXPECT_EQ(in_ctrl_nodes.at(0)->GetName(), "batch_label_256/add2"); } { std::vector<std::string> event_info; auto prefetch = graph->FindNode("batch_label_256/prefetch5"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 2); EXPECT_EQ(event_info.at(0), "SendTo;batch_label_256/add5;4"); EXPECT_EQ(event_info.at(1), "RecvFrom;batch_label_256/add3;5"); auto in_ctrl_nodes = prefetch->GetInControlNodes(); EXPECT_EQ(in_ctrl_nodes.size(), 2); EXPECT_EQ(in_ctrl_nodes.at(0)->GetName(), "batch_label_256/add3"); } } TEST_F(UtestBufferPoolMemoryPass, buffer_pool_node_has_multi_output_success_test) { ut::BufferPoolGraphBuilder builder("GraphWithMultiOutputPrefetch"); ge::ComputeGraphPtr graph = builder.BuildGraphWithMultiOutputPrefetch(); BufferPoolMemoryPass buffer_pool_mem_pass; Status ret = buffer_pool_mem_pass.Run(graph); EXPECT_EQ(ret, SUCCESS); { std::vector<std::string> event_info; auto prefetch = graph->FindNode("prefetch1"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 1); EXPECT_EQ(event_info.at(0), "SendTo;prefetch1_memcpy_async;0"); } { std::vector<std::string> event_info; auto prefetch = graph->FindNode("prefetch2"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 1); EXPECT_EQ(event_info.at(0), "SendTo;prefetch2_memcpy_async;1"); } { std::vector<std::string> event_info; auto prefetch = graph->FindNode("prefetch3"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 1); EXPECT_EQ(event_info.at(0), "SendTo;prefetch3_memcpy_async;2"); } { std::vector<std::string> event_info; auto prefetch = graph->FindNode("prefetch4"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 2); EXPECT_EQ(event_info.at(0), "SendTo;prefetch4_memcpy_async;3"); EXPECT_EQ(event_info.at(1), "RecvFrom;prefetch2_memcpy_async;0"); auto in_ctrl_nodes = prefetch->GetInControlNodes(); EXPECT_EQ(in_ctrl_nodes.size(), 2); EXPECT_EQ(in_ctrl_nodes.at(0)->GetName(), "prefetch2_memcpy_async"); } { std::vector<std::string> event_info; auto prefetch = graph->FindNode("prefetch5"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::GetListStr(prefetch->GetOpDesc(), "_event_multiplexing", event_info); EXPECT_EQ(event_info.size(), 2); EXPECT_EQ(event_info.at(0), "SendTo;add5;0"); EXPECT_EQ(event_info.at(1), "RecvFrom;prefetch3_memcpy_async;1"); auto in_ctrl_nodes = prefetch->GetInControlNodes(); EXPECT_EQ(in_ctrl_nodes.size(), 2); EXPECT_EQ(in_ctrl_nodes.at(0)->GetName(), "prefetch3_memcpy_async"); } } TEST_F(UtestBufferPoolMemoryPass, buffer_pool_has_different_size_fail_test) { ut::BufferPoolGraphBuilder builder("NormalGraph"); ge::ComputeGraphPtr graph = builder.BuildNormalGraph(); const int64_t dummy_size = 256; auto prefetch = graph->FindNode("prefetch3"); EXPECT_NE(prefetch, nullptr); (void) AttrUtils::SetInt(prefetch->GetOpDesc(), "_buffer_pool_size", dummy_size); BufferPoolMemoryPass buffer_pool_mem_pass; Status ret = buffer_pool_mem_pass.Run(graph); EXPECT_EQ(ret, FAILED); } TEST_F(UtestBufferPoolMemoryPass, buffer_pool_size_is_not_enough_fail_test) { ut::BufferPoolGraphBuilder builder("NormalGraph"); ge::ComputeGraphPtr graph = builder.BuildNormalGraph(); const int64_t buffer_pool_id = 0; const int64_t buffer_pool_size = 5600; auto prefetch = graph->FindNode("prefetch3"); EXPECT_NE(prefetch, nullptr); builder.SetPrefetchNodeInfo(prefetch, buffer_pool_id, buffer_pool_size, {buffer_pool_size + 512}); BufferPoolMemoryPass buffer_pool_mem_pass; Status ret = buffer_pool_mem_pass.Run(graph); EXPECT_EQ(ret, FAILED); } TEST_F(UtestBufferPoolMemoryPass, buffer_pool_size_is_not_enough_for_multi_fail_test) { ut::BufferPoolGraphBuilder builder("GraphWithMultiPrefetch"); ge::ComputeGraphPtr graph = builder.BuildGraphWithMultiPrefetch(); const int64_t buffer_pool_id = 0; const int64_t buffer_pool_size = 5600; auto prefetch = graph->FindNode("prefetch3"); EXPECT_NE(prefetch, nullptr); builder.SetPrefetchNodeInfo(prefetch, buffer_pool_id, buffer_pool_size, {buffer_pool_size}); BufferPoolMemoryPass buffer_pool_mem_pass; Status ret = buffer_pool_mem_pass.Run(graph); EXPECT_EQ(ret, FAILED); } TEST_F(UtestBufferPoolMemoryPass, buffer_pool_node_has_multi_input_output_fail_test) { ut::BufferPoolGraphBuilder builder("GraphWithMultiInputOutputPrefetch"); ge::ComputeGraphPtr graph = builder.BuildGraphWithMultiInputOutputPrefetch(); BufferPoolMemoryPass buffer_pool_mem_pass; Status ret = buffer_pool_mem_pass.Run(graph); EXPECT_EQ(ret, FAILED); } } // namespace ge
37.606419
105
0.717379
[ "vector" ]
a5a3634758dfaea33e17284754aa7ebaeccd4a0d
1,303
cpp
C++
token/Token.cpp
agatak8/sapling
d80809e9c67cf308d920ef3e9b80ace4e27097e4
[ "MIT" ]
1
2018-05-07T15:00:00.000Z
2018-05-07T15:00:00.000Z
token/Token.cpp
agatak8/sapling
d80809e9c67cf308d920ef3e9b80ace4e27097e4
[ "MIT" ]
null
null
null
token/Token.cpp
agatak8/sapling
d80809e9c67cf308d920ef3e9b80ace4e27097e4
[ "MIT" ]
null
null
null
#include "Token.h" using namespace TokenType; bool Token::isTerminal() const { return type <= EOT; } Type Token::getType() const { return type; } int Token::getInt() const { return integer; } std::string Token::getString() const { return string; } std::string Token::getName() const { return names[type]; } void Token::setInt(int value) { type = INT_VALUE; integer = value; } void Token::setString(std::string value) { string = value; } bool Token::operator==(const Type type) const { return this->type == type; } bool Token::operator!=(const Type type) const { return this->type != type; } int Token::getLine() const { return line; } int Token::getPosition() const { return position; } void Token::setLine(int line) { this->line = line; } void Token::setPosition(int position) { this->position = position; } std::vector<std::string> Token::names = { "IF", "ELIF", "ELSE", "RETURN", "RETURN_ARROW", "COMMA", "LET", "NOT", "AND", "OR", "INT_VALUE", "IDENTIFIER", "ASSIGNMENT_OPERATOR", "LESS_THAN", "GREATER_THAN", "LESS_EQUAL", "GREATER_EQUAL", "EQUAL", "NOT_EQUAL", "POWER", "MULTIPLY", "DIVIDE", "MODULO", "ADD", "SUBTRACT", "CURLY_BRACE_OPEN", "CURLY_BRACE_CLOSE", "BRACE_OPEN", "BRACE_CLOSE", "EOT" };
20.046154
83
0.636224
[ "vector" ]
a5a8350ab4e6cdce4eba9596beb1b94168cc3295
20,757
cpp
C++
app/src/main/cpp/src/communication/CommandLine.cpp
CCH852573130/3DPrinting11
dfe6e6c1a17c1a222d93c5c835c67e5b43999024
[ "MIT" ]
null
null
null
app/src/main/cpp/src/communication/CommandLine.cpp
CCH852573130/3DPrinting11
dfe6e6c1a17c1a222d93c5c835c67e5b43999024
[ "MIT" ]
null
null
null
app/src/main/cpp/src/communication/CommandLine.cpp
CCH852573130/3DPrinting11
dfe6e6c1a17c1a222d93c5c835c67e5b43999024
[ "MIT" ]
3
2020-04-12T01:53:41.000Z
2020-07-06T08:07:49.000Z
//Copyright (c) 2018 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include <cstring> //For strtok and strcopy. #include <fstream> //To check if files exist. #include <errno.h> // error number when trying to read file #include <numeric> //For std::accumulate. #ifdef _OPENMP #include <omp.h> //To change the number of threads to slice with. #endif //_OPENMP #include <sys/resource.h> #define LOG_TAG "System.out.c" #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__) #include <rapidjson/rapidjson.h> #include <rapidjson/error/en.h> //Loading JSON documents to get settings from them. #include <rapidjson/filereadstream.h> #include <unordered_set> #include <android/log.h> #include "CommandLine.h" #include "../Application.h" //To get the extruders for material estimates. #include "../ExtruderTrain.h" #include "../FffProcessor.h" //To start a slice and get time estimates. #include "../Slice.h" #include "../utils/getpath.h" #include "../utils/floatpoint.h" #include "../utils/logoutput.h" namespace cura { CommandLine::CommandLine(const std::vector<std::string>& arguments) : arguments(arguments) , last_shown_progress(0) { } //These are not applicable to command line slicing. void CommandLine::beginGCode() { } void CommandLine::flushGCode() { } void CommandLine::sendCurrentPosition(const Point&) { } void CommandLine::sendFinishedSlicing() const { } void CommandLine::sendLayerComplete(const LayerIndex&, const coord_t&, const coord_t&) { } void CommandLine::sendLineTo(const PrintFeatureType&, const Point&, const coord_t&, const coord_t&, const Velocity&) { } void CommandLine::sendOptimizedLayerData() { } void CommandLine::sendPolygon(const PrintFeatureType&, const ConstPolygonRef&, const coord_t&, const coord_t&, const Velocity&) { } void CommandLine::sendPolygons(const PrintFeatureType&, const Polygons&, const coord_t&, const coord_t&, const Velocity&) { } void CommandLine::setExtruderForSend(const ExtruderTrain&) { } void CommandLine::setLayerForSend(const LayerIndex&) { } bool CommandLine::hasSlice() const { return !arguments.empty(); } bool CommandLine::isSequential() const { return true; //We have to receive the g-code in sequential order. Start g-code before the rest and so on. } void CommandLine::sendGCodePrefix(const std::string&) const { //TODO: Right now this is done directly in the g-code writer. For consistency it should be moved here? } void CommandLine::sendPrintTimeMaterialEstimates() const { std::vector<Duration> time_estimates = FffProcessor::getInstance()->getTotalPrintTimePerFeature(); double sum = std::accumulate(time_estimates.begin(), time_estimates.end(), 0.0); log("Total print time: %5.3fs\n", sum); sum = 0.0; for (size_t extruder_nr = 0; extruder_nr < Application::getInstance().current_slice->scene.extruders.size(); extruder_nr++) { sum += FffProcessor::getInstance()->getTotalFilamentUsed(extruder_nr); } } void CommandLine::sendProgress(const float& progress) const { const unsigned int rounded_amount = 100 * progress; if (last_shown_progress == rounded_amount) //No need to send another tiny update step. { return; } //TODO: Do we want to print a progress bar? We'd need a better solution to not have that progress bar be ruined by any logging. } void CommandLine::sliceNext() { FffProcessor::getInstance()->time_keeper.restart(); //Count the number of mesh groups to slice for. size_t num_mesh_groups = 1; for (size_t argument_index = 2; argument_index < arguments.size(); argument_index++) { if (arguments[argument_index].find("--next") == 0) //Starts with "--next". { num_mesh_groups++; } } Slice slice(num_mesh_groups); Application::getInstance().current_slice = &slice; size_t mesh_group_index = 0; Settings* last_settings = &slice.scene.settings; slice.scene.extruders.reserve(arguments.size() >> 1); //Allocate enough memory to prevent moves. slice.scene.extruders.emplace_back(0, &slice.scene.settings); //Always have one extruder. ExtruderTrain* last_extruder = &slice.scene.extruders[0]; for (size_t argument_index = 2; argument_index < arguments.size(); argument_index++) { std::string argument = arguments[argument_index]; if (argument[0] == '-') //Starts with "-". { if (argument[1] == '-') //Starts with "--". { if (argument.find("--next") == 0) //Starts with "--next". { try { log("Loaded from disk in %5.3fs\n", FffProcessor::getInstance()->time_keeper.restart()); mesh_group_index++; FffProcessor::getInstance()->time_keeper.restart(); last_settings = &slice.scene.mesh_groups[mesh_group_index].settings; } catch(...) { //Catch all exceptions. //This prevents the "something went wrong" dialogue on Windows to pop up on a thrown exception. //Only ClipperLib currently throws exceptions. And only in the case that it makes an internal error. logError("Unknown exception!\n"); exit(1); } } else { logError("Unknown option: %s\n", argument.c_str()); } } else //Starts with "-" but not with "--". { argument = arguments[argument_index]; switch(argument[1]) { case 'v': { increaseVerboseLevel(); break; } #ifdef _OPENMP case 'm': { int threads = stoi(argument.substr(2)); threads = std::max(1, threads); omp_set_num_threads(threads); break; } #endif //_OPENMP case 'p': { enableProgressLogging(); break; } case 'j': { argument_index++; if (argument_index >= arguments.size()) { logError("Missing JSON file with -j argument."); exit(1); } LOGI("file is read :wpx"); argument = arguments[argument_index]; if (loadJSON(argument, *last_settings)) { logError("Failed to load JSON file: %s\n", argument.c_str()); exit(1); } //If this was the global stack, create extruders for the machine_extruder_count setting. if (last_settings == &slice.scene.settings) { const size_t extruder_count = slice.scene.settings.get<size_t>("machine_extruder_count"); while (slice.scene.extruders.size() < extruder_count) { slice.scene.extruders.emplace_back(slice.scene.extruders.size(), &slice.scene.settings); } } //If this was an extruder stack, make sure that the extruder_nr setting is correct. if (last_settings == &last_extruder->settings) { last_extruder->settings.add("extruder_nr", std::to_string(last_extruder->extruder_nr)); } break; } case 'e': { size_t extruder_nr = stoul(argument.substr(2)); while (slice.scene.extruders.size() <= extruder_nr) //Make sure we have enough extruders up to the extruder_nr that the user wanted. { slice.scene.extruders.emplace_back(extruder_nr, &slice.scene.settings); } last_settings = &slice.scene.extruders[extruder_nr].settings; last_settings->add("extruder_nr", argument.substr(2)); last_extruder = &slice.scene.extruders[extruder_nr]; break; } case 'l': { argument_index++; if (argument_index >= arguments.size()) { logError("Missing model file with -l argument."); exit(1); } argument = arguments[argument_index]; const FMatrix3x3 transformation = last_settings->get<FMatrix3x3>("mesh_rotation_matrix"); //The transformation applied to the model when loaded. if (!loadMeshIntoMeshGroup(&slice.scene.mesh_groups[mesh_group_index], argument.c_str(), transformation, last_extruder->settings)) { logError("Failed to load model: %s. (error number %d)\n", argument.c_str(), errno); exit(1); } else { last_settings = &slice.scene.mesh_groups[mesh_group_index].meshes.back().settings; } break; } case 'o': { argument_index++; if (argument_index >= arguments.size()) { logError("Missing output file with -o argument."); exit(1); } argument = arguments[argument_index]; if (!FffProcessor::getInstance()->setTargetFile(argument.c_str())) { logError("Failed to open %s for output.\n", argument.c_str()); exit(1); } break; } case 'g': { last_settings = &slice.scene.mesh_groups[mesh_group_index].settings; break; } /* ... falls through ... */ case 's': { //Parse the given setting and store it. argument_index++; if (argument_index >= arguments.size()) { logError("Missing setting name and value with -s argument."); exit(1); } argument = arguments[argument_index]; const size_t value_position = argument.find("="); std::string key = argument.substr(0, value_position); if (value_position == std::string::npos) { logError("Missing value in setting argument: -s %s", argument.c_str()); exit(1); } std::string value = argument.substr(value_position + 1); last_settings->add(key, value); break; } default: { logError("Unknown option: -%c\n", argument[1]); Application::getInstance().printCall(); Application::getInstance().printHelp(); exit(1); break; } } } } else { logError("Unknown option: %s\n", argument.c_str()); Application::getInstance().printCall(); Application::getInstance().printHelp(); exit(1); } } arguments.clear(); //We've processed all arguments now. #ifndef DEBUG try { #endif //DEBUG slice.scene.mesh_groups[mesh_group_index].finalize(); log("Loaded from disk in %5.3fs\n", FffProcessor::getInstance()->time_keeper.restart()); //Start slicing. slice.compute(); #ifndef DEBUG } catch(...) { //Catch all exceptions. //This prevents the "something went wrong" dialogue on Windows to pop up on a thrown exception. //Only ClipperLib currently throws exceptions. And only in the case that it makes an internal error. logError("Unknown exception.\n"); exit(1); } #endif //DEBUG //Finalize the processor. This adds the end g-code and reports statistics. FffProcessor::getInstance()->finalize(); } int CommandLine::loadJSON(const std::string& json_filename, Settings& settings) { FILE* file = fopen(json_filename.c_str(), "rb"); if (!file) { LOGI("file is read :培"); logError("Couldn't open JSON file: %s\n", json_filename.c_str()); return 1; } rapidjson::Document json_document; char read_buffer[4096]; rapidjson::FileReadStream reader_stream(file, read_buffer, sizeof(read_buffer)); json_document.ParseStream(reader_stream); LOGI("file is read :魏"); fclose(file); if (json_document.HasParseError()) { logError("Error parsing JSON (offset %u): %s\n", static_cast<unsigned int>(json_document.GetErrorOffset()), GetParseError_En(json_document.GetParseError())); return 2; } std::unordered_set<std::string> search_directories = defaultSearchDirectories(); //For finding the inheriting JSON files. std::string directory = getPathName(json_filename); search_directories.emplace(directory); return loadJSON(json_document, search_directories, settings); } std::unordered_set<std::string> CommandLine::defaultSearchDirectories() { std::unordered_set<std::string> result; char* search_path_env = getenv("CURA_ENGINE_SEARCH_PATH"); if (search_path_env) { #if defined(__linux__) || (defined(__APPLE__) && defined(__MACH__)) char delims[] = ":"; //Colon for Unix. #else char delims[] = ";"; //Semicolon for Windows. #endif char paths[128 * 1024]; //Maximum length of environment variable. strcpy(paths, search_path_env); //Necessary because strtok actually modifies the original string, and we don't want to modify the environment variable itself. char* path = strtok(paths, delims); while (path != nullptr) { result.emplace(path); path = strtok(nullptr, ";:,"); //Continue searching in last call to strtok. } } return result; } int CommandLine::loadJSON(const rapidjson::Document& document, const std::unordered_set<std::string>& search_directories, Settings& settings) { //Inheritance from other JSON documents. if (document.HasMember("inherits") && document["inherits"].IsString()) { std::string parent_file = findDefinitionFile(document["inherits"].GetString(), search_directories); if (parent_file == "") { logError("Inherited JSON file \"%s\" not found.\n", document["inherits"].GetString()); return 1; } int error_code = loadJSON(parent_file, settings); //Head-recursively load the settings file that we inherit from. if (error_code) { return error_code; } } //Extruders defined from here, if any. //Note that this always puts the extruder settings in the slice of the current extruder. It doesn't keep the nested structure of the JSON files, if extruders would have their own sub-extruders. Scene& scene = Application::getInstance().current_slice->scene; if (document.HasMember("metadata") && document["metadata"].IsObject()) { const rapidjson::Value& metadata = document["metadata"]; if (metadata.HasMember("machine_extruder_trains") && metadata["machine_extruder_trains"].IsObject()) { const rapidjson::Value& extruder_trains = metadata["machine_extruder_trains"]; for (rapidjson::Value::ConstMemberIterator extruder_train = extruder_trains.MemberBegin(); extruder_train != extruder_trains.MemberEnd(); extruder_train++) { const int extruder_nr = atoi(extruder_train->name.GetString()); if (extruder_nr < 0) { continue; } while (scene.extruders.size() <= static_cast<size_t>(extruder_nr)) { scene.extruders.emplace_back(scene.extruders.size(), &scene.settings); } const rapidjson::Value& extruder_id = extruder_train->value; if (!extruder_id.IsString()) { continue; } const std::string extruder_definition_id(extruder_id.GetString()); const std::string extruder_file = findDefinitionFile(extruder_definition_id, search_directories); loadJSON(extruder_file, scene.extruders[extruder_nr].settings); } } } if (document.HasMember("settings") && document["settings"].IsObject()) { loadJSONSettings(document["settings"], settings); } if (document.HasMember("overrides") && document["overrides"].IsObject()) { loadJSONSettings(document["overrides"], settings); } return 0; } void CommandLine::loadJSONSettings(const rapidjson::Value& element, Settings& settings) { for (rapidjson::Value::ConstMemberIterator setting = element.MemberBegin(); setting != element.MemberEnd(); setting++) { const std::string name = setting->name.GetString(); const rapidjson::Value& setting_object = setting->value; if (!setting_object.IsObject()) { logError("JSON setting %s is not an object!\n", name.c_str()); continue; } if (setting_object.HasMember("children")) { loadJSONSettings(setting_object["children"], settings); } else //Only process leaf settings. We don't process categories or settings that have sub-settings. { if (!setting_object.HasMember("default_value")) { logWarning("JSON setting %s has no default_value!\n", name.c_str()); continue; } const rapidjson::Value& default_value = setting_object["default_value"]; std::string value_string; if (default_value.IsString()) { value_string = default_value.GetString(); } else if (default_value.IsTrue()) { value_string = "true"; } else if (default_value.IsFalse()) { value_string = "false"; } else if (default_value.IsNumber()) { std::ostringstream ss; ss << default_value.GetDouble(); value_string = ss.str(); } else { logWarning("Unrecognized data type in JSON setting %s\n", name.c_str()); continue; } settings.add(name, value_string); } } } const std::string CommandLine::findDefinitionFile(const std::string& definition_id, const std::unordered_set<std::string>& search_directories) { for (const std::string& search_directory : search_directories) { const std::string candidate = search_directory + std::string("/") + definition_id + std::string(".def.json"); const std::ifstream ifile(candidate.c_str()); //Check whether the file exists and is readable by opening it. if (ifile) { return candidate; } } logError("Couldn't find definition file with ID: %s\n", definition_id.c_str()); return std::string(""); } } //namespace cura
40.620352
197
0.548201
[ "mesh", "object", "vector", "model" ]
a5ac23e50d662a47210a10390fd4c61721878a31
4,226
inl
C++
reflection_helpers/runtime_helper.inl
phisko/putils
741e143cef837ae78526656dd7c926283ccbebc9
[ "MIT" ]
26
2018-11-12T03:29:13.000Z
2021-11-30T22:43:44.000Z
reflection_helpers/runtime_helper.inl
phisko/putils
741e143cef837ae78526656dd7c926283ccbebc9
[ "MIT" ]
null
null
null
reflection_helpers/runtime_helper.inl
phisko/putils
741e143cef837ae78526656dd7c926283ccbebc9
[ "MIT" ]
9
2018-12-28T08:37:06.000Z
2020-04-27T08:17:17.000Z
#include "runtime_helper.hpp" #include <map> #include <unordered_map> #include "to_string.hpp" #include "lengthof.hpp" #include "vector.hpp" #include "meta/traits/is_indexable.hpp" #include "meta/traits/indexed_type.hpp" #include "meta/traits/is_specialization.hpp" namespace putils::reflection::runtime { namespace impl { putils_member_detector(size); template<typename MemberType> static AttributeInfo::ArrayHelper makeArrayHelperImpl() noexcept { AttributeInfo::ArrayHelper helper{ .getSize = [](void * attribute) noexcept { auto * array = (MemberType *)attribute; if constexpr (std::is_array<MemberType>()) return putils::lengthof(*array); else return array->size(); }, .getElement = [](void * attribute, size_t index) noexcept -> void * { auto * array = (MemberType *)attribute; auto & element = (*array)[index]; return &element; }, .forEach = [](void * attribute, const AttributeInfo::ArrayHelper::Iterator & iterator) noexcept { auto * array = (MemberType *)attribute; for (auto & element : *array) iterator(&element); } }; using IndexedType = putils::indexed_type<MemberType>; fillAttributes<std::decay_t<IndexedType>>(helper.elementAttributes); return helper; } template<typename MemberType> static std::optional<AttributeInfo::ArrayHelper> makeArrayHelper() noexcept { if constexpr (std::is_array<MemberType>()) return makeArrayHelperImpl<MemberType>(); if constexpr (putils::is_indexable<MemberType>() && has_member_size<MemberType>()) if constexpr (std::is_reference<putils::indexed_type<MemberType>>()) // Need this in a nested if, as putils::is_indexable has to be checked first and there is no early-exit for if constexpr return makeArrayHelperImpl<MemberType>(); return std::nullopt; } template<typename MemberType> static AttributeInfo::MapHelper makeMapHelperImpl() noexcept { using KeyType = typename MemberType::key_type; using ValueType = typename MemberType::value_type; AttributeInfo::MapHelper helper{ .getSize = [](void * attribute) noexcept { auto * map = (MemberType *)attribute; return map->size(); }, .getValue = [](void * attribute, const char * keyString) noexcept -> void * { auto * map = (MemberType *)attribute; const auto key = putils::parse<KeyType>(keyString); const auto it = map->find(key); if (it != map->end()) return &*it; return nullptr; }, .forEach = [](void * attribute, const AttributeInfo::MapHelper::Iterator & iterator) noexcept { auto * map = (MemberType *)attribute; for (auto & [key, value] : *map) iterator(&key, &value); } }; fillAttributes<KeyType>(helper.keyAttributes); fillAttributes<ValueType>(helper.valueAttributes); return helper; } template<typename MemberType> static std::optional<AttributeInfo::MapHelper> makeMapHelper() noexcept { if constexpr (putils::is_specialization<MemberType, std::map>() || putils::is_specialization<MemberType, std::unordered_map>()) return makeMapHelperImpl<MemberType>(); return std::nullopt; } template<typename T> static void fillAttributes(AttributeMap & attributes) noexcept { putils::reflection::for_each_attribute<T>([&](std::string_view name, const auto member) noexcept { using MemberType = putils::MemberType<decltype(member)>; auto & attr = attributes[std::string(name)]; attr.size = sizeof(MemberType); attr.offset = putils::member_offset(member); attr.arrayHelper = makeArrayHelper<MemberType>(); attr.mapHelper = makeMapHelper<MemberType>(); fillAttributes<MemberType>(attr.attributes); }); } } template<typename T> const Attributes & getAttributes() noexcept { static const Attributes attributes = [] { Attributes ret; impl::fillAttributes<T>(ret.map); return ret; }(); return attributes; } template<typename T> const AttributeInfo * findAttribute(std::string_view path, std::string_view separator) noexcept { return findAttribute(getRuntimeAttributes<T>(), path, separator); } }
32.507692
193
0.680549
[ "vector" ]
a5b4fda9b884ceacab8654a07bab5d270b8674fb
5,202
cxx
C++
logger/safe_logger_client.cxx
trotill/11parts_CPP
53a69d516fdcb5c92b591b5dadc49dfdd2a3b26b
[ "MIT" ]
null
null
null
logger/safe_logger_client.cxx
trotill/11parts_CPP
53a69d516fdcb5c92b591b5dadc49dfdd2a3b26b
[ "MIT" ]
null
null
null
logger/safe_logger_client.cxx
trotill/11parts_CPP
53a69d516fdcb5c92b591b5dadc49dfdd2a3b26b
[ "MIT" ]
null
null
null
/* * safe_logger_client.cxx * * Created on: 20 сент. 2019 г. * Author: root */ #include "safe_logger_client.h" #include "algo_biphasic_offset.h" #include "dnk_biphasic_offset.h" eErrorTp safelogger_client::to_log(u32 count,Json::Value & json,u8 prec=JSONCPP_DEFAULT_PRECISION){ //Json::FastWriter wr; return safelogger_client::to_log(count,FastWriteJSON(json).c_str()); } eErrorTp safelogger_client::to_log(string str){ return safelogger_client::to_log(1,str.c_str()); } eErrorTp safelogger_client::to_log(u32 count,...){ va_list args; int result = 0; if (!unblock) return ERROR; if (slogger_skip_data_cntr<slogger_skip_data){ slogger_skip_data_cntr++; return NO_ERROR; } slogger_skip_data_cntr=0; stringstream ss; u32 fsize=formstr.size(); va_start(args, count); struct tm times; struct timeval tv; if (chType==sloggerChannelTypes::enuOverPipe){ if (f<=0){ if ((f = open(fifo_file.c_str(), O_WRONLY|O_NONBLOCK))<0){ GPRINT(NORMAL_LEVEL,"Error open %s\n",fifo_file.c_str()); return ERROR; } } } //ss<<',"'; //printf("atime %d atime_format %d\n",atime,atime_format); GetDataTime(&times,&tv); if (atime==true){ switch (atime_format){ case SLOGGER_STYLED_DATE:{ //printf("SLOGGER_STYLED_DATE\n"); string strdate=string_format("%04d-%02d-%02d %02d:%02d:%02d ",(times.tm_year+1900),(times.tm_mon+1),times.tm_mday, times.tm_hour,times.tm_min,times.tm_sec); ss << strdate; } break; case SLOGGER_JSON_DATE: { //printf("SLOGGER_JSON_DATE\n"); u64 ts_msec=(u64)((u64)tv.tv_sec*1000)+(u64)((u64)tv.tv_usec/1000); //printf("tv sec %llu usec %llu calc %llu\n",(long long int)(tv.tv_sec*1000),(long long int)(tv.tv_usec)/1000,(long long int)(time(NULL))); ss << "{\"m\":"<< ts_msec << ",\"t\":"<<tv.tv_sec<<",\"d\":"; } break; default: //printf("default\n"); break; } } for (u32 i = 0; i < count; ++i) { if (i<fsize){ ss << formstr[i] << va_arg(args, char *); } //result += va_arg(args, int); } if ((atime)&&(atime_format==SLOGGER_JSON_DATE)){ ss << "}"; } //ss<<'"'; //if (add_line_break) ss<<line_break; //printf("LOG:[%s]\n",ss.str().c_str()); //strncpy(str_buf,srst.c_str(),SLOGGER_READ_FIFO_BUF_SIZE); //ss << endl; if (chType==sloggerChannelTypes::enuOverPipe){ int ret=write(f,ss.str().c_str(),ss.str().size()+1); fd_set rfds; FD_ZERO(&rfds); FD_SET(0, &rfds); /* Wait up to 10 mS. */ tv.tv_sec = 0; tv.tv_usec = 10000; select(f, &rfds, NULL, NULL, &tv); int ret2=0; if (ret==-1){ GPRINT(NORMAL_LEVEL,"Error write to %s\n",fifo_file.c_str()); if (f!=0) close(f); f = open(fifo_file.c_str(), O_WRONLY|O_NONBLOCK); if (f<=0){ GPRINT(NORMAL_LEVEL,"Error reopen %s\n",fifo_file.c_str()); return ERROR; } ret2=write(f,ss.str().c_str(),ss.str().size()+1); } if ((ret==-1)&&(ret2==-1)){ GPRINT(NORMAL_LEVEL,"Error write to safe logger %s\n",fifo_file.c_str()); return ERROR; } return NO_ERROR; } #ifdef _HIREDIS if (chType==sloggerChannelTypes::enuOverRedis){ std::pair<eErrorTp, vector<string>> res; //printf("send %s\n",ss.str().c_str()); res=redB->command("LPUSH %s %s",redisListName.c_str(),(char*)ss.str().c_str()); if (res.first==ERROR){ return ERROR; } else return NO_ERROR; } #endif return ERROR; } safelogger_client::safelogger_client(string format,string config,eDebugTp debug_lvl):safelogger_base(debug_lvl,"client") { //time:$ arg1:$ arg2:$ if (SearchFile(config.c_str())==ERROR) { GPRINT(NORMAL_LEVEL,"Not found config %s, fifo_file file %s\n",config.c_str(),fifo_file.c_str()); return; } else ReadConfigConf(config); unblock=true; u32 fsize=format.size(); u32 offs=0; string str; for (u32 n=0;n<fsize;n++){ if (format[n]=='$'){ format[n]=0; str=&format.c_str()[offs]; formstr.emplace_back(str); offs=n+1; } } if (chType==sloggerChannelTypes::enuOverPipe){ f = open(fifo_file.c_str(), O_WRONLY|O_NONBLOCK); GPRINT(NORMAL_LEVEL,"Open %s\n",fifo_file.c_str()); } #ifdef _HIREDIS if (chType==sloggerChannelTypes::enuOverRedis){ redB=make_shared<redis>(debug_lvl,config); GPRINT(NORMAL_LEVEL,"Open redis DB\n"); } #endif } safelogger_client::~safelogger_client(){ if (chType==sloggerChannelTypes::enuOverPipe){ if (f!=0){ close(f); GPRINT(NORMAL_LEVEL,"Close %s\n",fifo_file.c_str()); } } } eErrorTp safelogger_client::ReadConfigConf(string conffile) { Json::Value root; std::ifstream config_doc(conffile.c_str(), std::ifstream::binary); config_doc >> root; JSON_ReadConfigField(root,"fifo_file",fifo_file); JSON_ReadConfigField(root,"slogger_atime",atime); JSON_ReadConfigField(root,"slogger_atime_format",atime_format); JSON_ReadConfigField(root,"slogger_skip_data",slogger_skip_data); string val; JSON_ReadConfigField(root,"slogger_channel",val); if (val=="redis"){ chType=sloggerChannelTypes::enuOverRedis; JSON_ReadConfigField(root,"redis_list",redisListName); } else chType=sloggerChannelTypes::enuOverPipe; return NO_ERROR; }
24.889952
145
0.653595
[ "vector" ]
a5c20f9cb7e7934870c338bdd2458f9e106cdac1
3,067
cpp
C++
android-28/android/content/pm/LabeledIntent.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-28/android/content/pm/LabeledIntent.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-30/android/content/pm/LabeledIntent.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "../Intent.hpp" #include "./PackageManager.hpp" #include "../../graphics/drawable/Drawable.hpp" #include "../../os/Parcel.hpp" #include "../../../JString.hpp" #include "../../../JString.hpp" #include "./LabeledIntent.hpp" namespace android::content::pm { // Fields JObject LabeledIntent::CREATOR() { return getStaticObjectField( "android.content.pm.LabeledIntent", "CREATOR", "Landroid/os/Parcelable$Creator;" ); } // QJniObject forward LabeledIntent::LabeledIntent(QJniObject obj) : android::content::Intent(obj) {} // Constructors LabeledIntent::LabeledIntent(JString arg0, jint arg1, jint arg2) : android::content::Intent( "android.content.pm.LabeledIntent", "(Ljava/lang/String;II)V", arg0.object<jstring>(), arg1, arg2 ) {} LabeledIntent::LabeledIntent(JString arg0, JString arg1, jint arg2) : android::content::Intent( "android.content.pm.LabeledIntent", "(Ljava/lang/String;Ljava/lang/CharSequence;I)V", arg0.object<jstring>(), arg1.object<jstring>(), arg2 ) {} LabeledIntent::LabeledIntent(android::content::Intent arg0, JString arg1, jint arg2, jint arg3) : android::content::Intent( "android.content.pm.LabeledIntent", "(Landroid/content/Intent;Ljava/lang/String;II)V", arg0.object(), arg1.object<jstring>(), arg2, arg3 ) {} LabeledIntent::LabeledIntent(android::content::Intent arg0, JString arg1, JString arg2, jint arg3) : android::content::Intent( "android.content.pm.LabeledIntent", "(Landroid/content/Intent;Ljava/lang/String;Ljava/lang/CharSequence;I)V", arg0.object(), arg1.object<jstring>(), arg2.object<jstring>(), arg3 ) {} // Methods jint LabeledIntent::getIconResource() const { return callMethod<jint>( "getIconResource", "()I" ); } jint LabeledIntent::getLabelResource() const { return callMethod<jint>( "getLabelResource", "()I" ); } JString LabeledIntent::getNonLocalizedLabel() const { return callObjectMethod( "getNonLocalizedLabel", "()Ljava/lang/CharSequence;" ); } JString LabeledIntent::getSourcePackage() const { return callObjectMethod( "getSourcePackage", "()Ljava/lang/String;" ); } android::graphics::drawable::Drawable LabeledIntent::loadIcon(android::content::pm::PackageManager arg0) const { return callObjectMethod( "loadIcon", "(Landroid/content/pm/PackageManager;)Landroid/graphics/drawable/Drawable;", arg0.object() ); } JString LabeledIntent::loadLabel(android::content::pm::PackageManager arg0) const { return callObjectMethod( "loadLabel", "(Landroid/content/pm/PackageManager;)Ljava/lang/CharSequence;", arg0.object() ); } void LabeledIntent::readFromParcel(android::os::Parcel arg0) const { callMethod<void>( "readFromParcel", "(Landroid/os/Parcel;)V", arg0.object() ); } void LabeledIntent::writeToParcel(android::os::Parcel arg0, jint arg1) const { callMethod<void>( "writeToParcel", "(Landroid/os/Parcel;I)V", arg0.object(), arg1 ); } } // namespace android::content::pm
24.733871
111
0.690251
[ "object" ]
a5c32a39cc34258fd14a439b20bed6d51d3a0839
6,080
hpp
C++
include/netp/app.hpp
kaocher82/netplus
4bc45c4d55ff4e21a65f5c7e92f70b4a25220a1f
[ "MIT" ]
null
null
null
include/netp/app.hpp
kaocher82/netplus
4bc45c4d55ff4e21a65f5c7e92f70b4a25220a1f
[ "MIT" ]
null
null
null
include/netp/app.hpp
kaocher82/netplus
4bc45c4d55ff4e21a65f5c7e92f70b4a25220a1f
[ "MIT" ]
null
null
null
#ifndef _NETP_APP_HPP_ #define _NETP_APP_HPP_ #include <netp/core.hpp> #include <netp/signal_broker.hpp> #include <netp/test.hpp> //#define NETP_DEBUG_OBJECT_SIZE namespace netp { typedef std::function<void()> fn_app_hook_t; struct app_cfg { std::string logfilepathname; std::vector<std::string> dnsnses; //dotip int poller_max[T_POLLER_MAX]; int poller_count[T_POLLER_MAX]; event_loop_cfg event_loop_cfgs[T_POLLER_MAX]; fn_app_hook_t app_startup_prev; fn_app_hook_t app_startup_post; fn_app_hook_t app_exit_prev; fn_app_hook_t app_exit_post; fn_app_hook_t app_event_loop_init_prev; fn_app_hook_t app_event_loop_init_post; fn_app_hook_t app_event_loop_deinit_prev; fn_app_hook_t app_event_loop_deinit_post; void __init_from_cfg_json(const char* jsonfile); void __parse_cfg(int argc, char** argv); void __cfg_default_loop_cfg() { const int corecount = std::thread::hardware_concurrency(); for (size_t i = 0; i < T_POLLER_MAX; ++i) { poller_max[i] = (corecount << 1); //0 means default if (i == NETP_DEFAULT_POLLER_TYPE) { cfg_poller_count(io_poller_type(i), int(std::ceil(corecount) * 1.5f)); } else { cfg_poller_count(io_poller_type(i), 0); } event_loop_cfgs[i].ch_buf_size = (128 * 1024); } } public: app_cfg(int argc, char** argv) : logfilepathname(), dnsnses(std::vector<std::string>()), app_startup_prev(nullptr), app_startup_post(nullptr), app_exit_prev(nullptr), app_exit_post(nullptr), app_event_loop_init_prev(nullptr), app_event_loop_init_post(nullptr), app_event_loop_deinit_prev(nullptr), app_event_loop_deinit_post(nullptr) { NETP_ASSERT( argc>=1 ); __cfg_default_loop_cfg(); std::string data=netp::curr_local_data_str(); std::string data_; netp::replace(data, std::string("-"), std::string("_"), data_); cfg_log_filepathname(std::string(argv[0]) + std::string(".") + data_ + ".log"); __parse_cfg(argc, argv); } app_cfg() : logfilepathname(), dnsnses(std::vector<std::string>()), app_startup_prev(nullptr), app_startup_post(nullptr), app_exit_prev(nullptr), app_exit_post(nullptr), app_event_loop_init_prev(nullptr), app_event_loop_init_post(nullptr), app_event_loop_deinit_prev(nullptr), app_event_loop_deinit_post(nullptr) { __cfg_default_loop_cfg(); std::string data = netp::curr_local_data_str(); std::string data_; netp::replace(data, std::string("-"), std::string("_"), data_); cfg_log_filepathname("netp_" + data_ + ".log"); } void cfg_poller_max(io_poller_type t, int c) { if (c > 0) { const int max = (std::thread::hardware_concurrency() << 1); if (c > max) { c = max; } else if (c < 1) { c = 1; } poller_max[t] = c; } } void cfg_poller_count(io_poller_type t, int c) { const int corecount = std::thread::hardware_concurrency(); if (c > poller_max[t]) { c = poller_max[t]; } else if (c <= 0) { c = 0; if (t == NETP_DEFAULT_POLLER_TYPE) { c = 1; } } poller_count[t] = c ; } void cfg_channel_buf(io_poller_type t, int buf_in_kbytes) { if (buf_in_kbytes > 0) { event_loop_cfgs[t].ch_buf_size = buf_in_kbytes * (1024); } } void cfg_add_dns(std::string const& dns_ns) { dnsnses.push_back(dns_ns); } void cfg_log_filepathname(std::string const& logfilepathname_) { if (logfilepathname_.length() == 0) { return; } logfilepathname = logfilepathname_; } }; class app_thread_init : public netp::singleton<app_thread_init> { public: app_thread_init(); ~app_thread_init(); }; class app { private: bool m_should_exit; netp::mutex m_mutex; netp::condition m_cond; std::vector<std::tuple<int,i64_t>> m_signo_tuple_vec; app_cfg m_cfg; fn_app_hook_t m_app_startup_prev; fn_app_hook_t m_app_startup_post; fn_app_hook_t m_app_exit_prev; fn_app_hook_t m_app_exit_post; fn_app_hook_t m_app_event_loop_init_prev; fn_app_hook_t m_app_event_loop_init_post; fn_app_hook_t m_app_event_loop_deinit_prev; fn_app_hook_t m_app_event_loop_deinit_post; public: //@warn: if we do need to create app on heap, we should always use new/delete, or std::shared_ptr app(app_cfg const& cfg); app(); ~app(); void _startup(); void _exit(); void _init(); void _deinit(); void __log_init(); void __log_deinit(); #ifndef NETP_DISABLE_INSTRUCTION_SET_DETECTOR void dump_arch_info(); #endif #ifdef NETP_DEBUG_OBJECT_SIZE void __dump_sizeof(); #endif void __signal_init(); void __signal_deinit(); void __net_init(); void __net_deinit(); void ___event_loop_init(); void ___event_loop_wait(); //ISSUE: if the waken thread is main thread, we would get stuck here void handle_signal(int signo); bool should_exit() const; int run() { netp::unique_lock<netp::mutex> ulk(m_mutex); while (!m_should_exit) { m_cond.wait(ulk); } return 0; } template <class _Rep, class _Period> int run_for(std::chrono::duration<_Rep, _Period> const& duration) { netp::unique_lock<netp::mutex> ulk(m_mutex); const std::chrono::time_point<std::chrono::steady_clock> exit_tp = std::chrono::steady_clock::now() + duration; while (!m_should_exit) { const std::chrono::time_point<std::chrono::steady_clock> now = std::chrono::steady_clock::now(); if (now>=exit_tp) { break; } m_cond.wait_for(ulk, exit_tp-now ); } return 0; } template <class _Clock, class _Duration> int run_until(std::chrono::time_point<_Clock, _Duration> const& tp) { netp::unique_lock<netp::mutex> ulk(m_mutex); while (!m_should_exit) { if (_Clock::now() >= tp) { break; } //NETP_INFO("to: %lld", tp.time_since_epoch().count() ); m_cond.wait_until(ulk, tp); } return 0; } }; class app_test_unit : public netp::test_unit { public: bool run(); void test_memory(); void test_packet(); void test_netp_allocator(size_t loop); void test_std_allocator(size_t loop); void test_generic_check(); void benchmark_hash(); }; } #endif
24.223108
114
0.692434
[ "vector" ]
77749346a328e69048acd635e97fdb9c2e77361f
10,651
cpp
C++
addons/ofxUI/src/ofxUIEnvelopeEditor.cpp
k4rm/AscoGraph
9038ae785b6f4f144a3ab5c4c5520761c0cd08f2
[ "MIT" ]
18
2015-01-18T22:34:22.000Z
2020-09-06T20:30:30.000Z
addons/ofxUI/src/ofxUIEnvelopeEditor.cpp
k4rm/AscoGraph
9038ae785b6f4f144a3ab5c4c5520761c0cd08f2
[ "MIT" ]
2
2015-08-04T00:07:46.000Z
2017-05-10T15:53:51.000Z
addons/ofxUI/src/ofxUIEnvelopeEditor.cpp
k4rm/AscoGraph
9038ae785b6f4f144a3ab5c4c5520761c0cd08f2
[ "MIT" ]
10
2015-01-18T23:46:10.000Z
2019-08-25T12:10:04.000Z
/********************************************************************************** Copyright (C) 2012 Syed Reza Ali (www.syedrezaali.com) Created by Mitchell Nordine on 28/01/2014. Refactored & Edited by Reza Ali on 02/02/2014 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 "ofxUIEnvelopeEditor.h" #include "ofxUI.h" #include "ofxUIUtils.h" ofxUIEnvelopeEditor::ofxUIEnvelopeEditor(string _name, float w, float h, float x, float y) : ofxUIWidgetWithLabel() { useReference = false; init(_name, NULL, w, h, x, y); } ofxUIEnvelopeEditor::ofxUIEnvelopeEditor(string _name, ofxUIEnvelope *_envelope, float w, float h, float x, float y) :ofxUIWidgetWithLabel() { useReference = true; init(_name, _envelope, w, h, x, y); } ofxUIEnvelopeEditor::~ofxUIEnvelopeEditor() { if(!useReference) { delete envelope; } } void ofxUIEnvelopeEditor::init(string _name, ofxUIEnvelope *_envelope, float w, float h, float x, float y) { initRect(x, y, w, h); name = string(_name); kind = OFX_UI_WIDGET_ENVELOPEEDITOR; draw_fill = true; draw_outline = true; if(useReference) { envelope = _envelope; } else { envelope = new ofxUIEnvelope(); } labelPrecision = 2; label = new ofxUILabel(0,h+padding*2.0,(name+" LABEL"), (name + ":"), OFX_UI_FONT_SMALL); addEmbeddedWidget(label); hitThreshold = 0.05; pointNodeRadius = OFX_UI_GLOBAL_PADDING*1.5; pointNodeRectWidth = OFX_UI_GLOBAL_PADDING*2.5; pointNodeRectHeight = OFX_UI_GLOBAL_PADDING*2.5; bHitPoint = false; bHitCurve = false; hitPoint = NULL; hitCurve = NULL; hitCurveNext = NULL; } void ofxUIEnvelopeEditor::updateEnvelopeData() { envelope->sortPointsByX(); float rX = rect->getX(); float rY = rect->getY(); polyline.clear(); for(int i = 0; i < rect->getWidth(); i++) { float x = rX + i; float nx = (double)i/rect->getWidth(); float y = rY + envelope->getY(nx)*rect->getHeight(); polyline.addVertex(x, y); } } void ofxUIEnvelopeEditor::drawFill() { if(draw_fill) { ofxUIFill(); ofxUISetColor(color_fill); drawEnvelope(); updateEnvelopeData(); } } void ofxUIEnvelopeEditor::setParent(ofxUIWidget *_parent) { ofxUIWidgetWithLabel::setParent(_parent); } void ofxUIEnvelopeEditor::mouseMoved(int x, int y) { if(rect->inside(x, y)) { state = OFX_UI_STATE_OVER; } else { state = OFX_UI_STATE_NORMAL; } stateChange(); } void ofxUIEnvelopeEditor::mouseDragged(int x, int y, int button) { if(hit && (bHitPoint || bHitCurve)) { state = OFX_UI_STATE_DOWN; ofxUIVec2f pos = rect->percentInside(x, y); pos.x = MIN(1.0, MAX(0.0, pos.x)); pos.y = MIN(1.0, MAX(0.0, pos.y)); if(bHitPoint) { moveGrabbedPoint(pos.x, pos.y); } else if(bHitCurve) { moveGrabbedCurve(pos.x, pos.y); } triggerEvent(this); } else { state = OFX_UI_STATE_NORMAL; } stateChange(); } //---------------------------------------------------- void ofxUIEnvelopeEditor::mousePressed(int x, int y, int button) { if(rect->inside(x, y)) { hit = true; state = OFX_UI_STATE_DOWN; ofxUIVec2f pos = rect->percentInside(x, y); pos.x = MIN(1.0, MAX(0.0, pos.x)); pos.y = MIN(1.0, MAX(0.0, pos.y)); if(button == 0) { checkForClosestPointNode(pos.x, pos.y); } else if(!bHitCurve && !hitPoint) { deleteClosestPointNode(pos.x, pos.y); } triggerEvent(this); } else { state = OFX_UI_STATE_NORMAL; } stateChange(); } //---------------------------------------------------- void ofxUIEnvelopeEditor::mouseReleased(int x, int y, int button) { if(hit) { #ifdef TARGET_OPENGLES state = OFX_UI_STATE_NORMAL; #else state = OFX_UI_STATE_OVER; #endif if(bHitPoint) { bHitPoint = false; hitPoint = NULL; } else if(bHitCurve) { bHitCurve = false; hitCurve = NULL; hitCurveNext = NULL; } else { ofxUIVec2f pos = rect->percentInside(x, y); pos.x = MIN(1.0, MAX(0.0, pos.x)); pos.y = MIN(1.0, MAX(0.0, pos.y)); addEnvelopePoint(pos.x, pos.y); triggerEvent(this); } } else { state = OFX_UI_STATE_NORMAL; } stateChange(); hit = false; } void ofxUIEnvelopeEditor::stateChange() { switch (state) { case OFX_UI_STATE_NORMAL: { draw_fill_highlight = false; draw_outline_highlight = false; label->unfocus(); } break; case OFX_UI_STATE_OVER: { draw_fill_highlight = false; draw_outline_highlight = true; label->unfocus(); } break; case OFX_UI_STATE_DOWN: { draw_outline_highlight = true; label->focus(); } break; case OFX_UI_STATE_SUSTAINED: { draw_fill_highlight = false; draw_outline_highlight = false; label->unfocus(); } break; default: break; } } bool ofxUIEnvelopeEditor::isDraggable() { return true; } void ofxUIEnvelopeEditor::setLabelPrecision(int _precision) { labelPrecision = _precision; } #ifndef OFX_UI_NO_XML void ofxUIEnvelopeEditor::saveState(ofxXmlSettings *XML) { // XML->setValue("XValue", getScaledValue().x, 0); // XML->setValue("YValue", getScaledValue().y, 0); } void ofxUIEnvelopeEditor::loadState(ofxXmlSettings *XML) { // setValue(ofxUIVec3f(XML->getValue("XValue", getScaledValue().x, 0), XML->getValue("YValue", getScaledValue().y, 0))); } #endif void ofxUIEnvelopeEditor::addEnvelopePoint(float x, float y) { envelope->addPoint(x, y); } void ofxUIEnvelopeEditor::setEnvelope(ofxUIEnvelope *_envelope) { if(!useReference) { delete envelope; useReference = true; } envelope = _envelope; } void ofxUIEnvelopeEditor::drawEnvelope(){ vector<ofVec3f> points = envelope->getPoints(); int size = points.size(); float rX = rect->getX(); float rY = rect->getY(); ofxUISetRectMode(OFX_UI_RECTMODE_CENTER); ofxUINoFill(); for (int i = 0; i < size; i++) { float x = rX + points[i].x*rect->getWidth(); float y = rY + points[i].y*rect->getHeight(); ofxUICircle(x, y, pointNodeRadius); if(i < size-1) { float nx = rX + points[i+1].x*rect->getWidth(); float hx = (x + nx)/2.0; ofxUIDrawRect(hx, rY + envelope->getY((hx-rX)/rect->getWidth())*rect->getHeight(), pointNodeRectWidth, pointNodeRectHeight); } } ofxUIFill(); ofxUISetRectMode(OFX_UI_RECTMODE_CORNER); polyline.draw(); } bool ofxUIEnvelopeEditor::checkForClosestPointNode(float x, float y) { vector<ofxUIVec3f> &points = envelope->getPoints(); int size = envelope->points.size(); for(int i=0; i < size; i++) { if(ofDist(points[i].x, points[i].y, x, y) <= hitThreshold) { bHitPoint = true; hitPoint = &points[i]; return bHitPoint; } if(checkForClosestCurveNode(i, x, y)) { return true; } } return false; } bool ofxUIEnvelopeEditor::deleteClosestPointNode(float x, float y) { int size = envelope->points.size(); for(int i=0; i < size; i++) { if(ofDist(envelope->points[i].x, envelope->points[i].y, x, y) <= hitThreshold) { envelope->points.erase(envelope->points.begin()+i); return true; } } return false; } bool ofxUIEnvelopeEditor::checkForClosestCurveNode(int i, float x, float y) { int size = envelope->points.size(); if(i < size-1) { float rW = rect->getWidth(); float rH = rect->getHeight(); float cX = envelope->points[i].x; float cY = envelope->points[i].y; float nX = envelope->points[i+1].x; float nY = envelope->points[i+1].y; float hX = (cX+nX)/2.0f; float hY = envelope->getY(hX); float distance = ofDist(hX, hY, x, y); if (distance <= hitThreshold) { bHitCurve = true; hitCurve = &envelope->points[i]; hitCurveNext = &envelope->points[i+1]; return true; } } return false; } void ofxUIEnvelopeEditor::moveGrabbedPoint(float x, float y) { if(hitPoint != NULL) { hitPoint->x = x; hitPoint->y = y; } } void ofxUIEnvelopeEditor::moveGrabbedCurve(float x, float y) { if(hitCurveNext != NULL && hitCurve != NULL) { float curveBasePoint = (hitCurve->y + hitCurveNext->y)/2.0f; if(hitCurveNext->y >= hitCurve->y) { hitCurve->z = ofxUIMap(y, curveBasePoint, hitCurveNext->y, 0.0f, 1.0f, true); } else if(hitCurveNext->y < hitCurve->y) { hitCurve->z = ofxUIMap(y, curveBasePoint, hitCurve->y, 0.0f, -1.0f, true); } } }
25.120283
140
0.569806
[ "vector" ]
7782083e671f45218cfba730dfbada11027fbcb4
5,410
cpp
C++
mkediscovery/src/mainwindow.cpp
MagikEyeInc/SDK
e4a3ac92a7ec5bf57978d15d43feb81b1f595653
[ "BSD-3-Clause-No-Nuclear-License-2014", "Unlicense" ]
12
2021-07-14T21:30:53.000Z
2021-11-01T08:39:30.000Z
mkediscovery/src/mainwindow.cpp
MagikEyeInc/SDK
e4a3ac92a7ec5bf57978d15d43feb81b1f595653
[ "BSD-3-Clause-No-Nuclear-License-2014", "Unlicense" ]
3
2021-07-23T06:30:29.000Z
2021-08-03T11:37:24.000Z
mkediscovery/src/mainwindow.cpp
MagikEyeInc/SDK
e4a3ac92a7ec5bf57978d15d43feb81b1f595653
[ "BSD-3-Clause-No-Nuclear-License-2014", "Unlicense" ]
4
2021-07-23T11:30:39.000Z
2022-01-12T03:39:13.000Z
#include <QUrl> #include <QDesktopServices> #include <QSettings> #include <QDesktopWidget> #include <QStyle> #include "aboutdialog.h" #include "mainwindow.h" #include "ui_mainwindow.h" #include "mke/net/ssdp/discovery.h" // ---------------------------------------------------------------------------- MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); // Version auto info_text = ui->info_label->text(); info_text.replace("@VERSION@", MKEDISCOVERY_VERSION); ui->info_label->setText(info_text); // MkE logos QColor color = this->palette().color(QWidget::backgroundRole()); if (color.lightness() < 128) { ui->logo_label->setPixmap(QPixmap(QString::fromUtf8(":/img/logos_inv"))); } // Device table ui->device_table->setModel(&devicelist_); ui->device_table->horizontalHeader()->setSectionResizeMode( QHeaderView::Stretch); // Initialize the window position to the center of the screen this->setGeometry( QStyle::alignedRect( Qt::LeftToRight, Qt::AlignCenter, this->size(), qApp->desktop()->availableGeometry() ) ); // Override the window position using a saved geometry, if availbe QSettings settings("MagikEye", "MkEDiscovery"); restoreGeometry(settings.value("geometry").toByteArray()); try { // Start SSDP daemon ssdpd_.setPatternURN("urn:schemas-upnp-org:device:Basic:1"); ssdpd_.setPatternProtocol("MkE"); ssdpd_.setDeviceAddedCallback( [this](const std::string& usn, const std::string& location, const std::string& xml_location, const std::string& protocol, const std::string& device_name, const std::string& unit_id, const std::string& urn) { QString q_usn(QLatin1String(usn.c_str())); QString q_location(QLatin1String(location.c_str())); QString q_xml_location(QLatin1String(xml_location.c_str())); QString q_apiType(QLatin1String(protocol.c_str())); QString q_device_name(QLatin1String(device_name.c_str())); QString q_unit_id(QLatin1String(unit_id.c_str())); QMetaObject::invokeMethod( this, "onSsdpDeviceAdded", Qt::QueuedConnection, Q_ARG(QString, q_usn), Q_ARG(QString, q_location), Q_ARG(QString, q_xml_location), Q_ARG(QString, q_apiType), Q_ARG(QString, q_device_name), Q_ARG(QString, q_unit_id)); }); ssdpd_.setDeviceRemovedCallback( [this](const std::string& usn, const std::string& location, const std::string& xml_location, const std::string& protocol, const std::string& device_name, const std::string& unit_id, const std::string& urn) { QString q_usn(QLatin1String(usn.c_str())); QString q_location(QLatin1String(location.c_str())); QString q_xml_location(QLatin1String(xml_location.c_str())); QString q_apiType(QLatin1String(protocol.c_str())); QString q_device_name(QLatin1String(device_name.c_str())); QString q_unit_id(QLatin1String(unit_id.c_str())); QMetaObject::invokeMethod( this, "onSsdpDeviceRemoved", Qt::QueuedConnection, Q_ARG(QString, q_usn), Q_ARG(QString, q_location), Q_ARG(QString, q_xml_location), Q_ARG(QString, q_apiType), Q_ARG(QString, q_device_name), Q_ARG(QString, q_unit_id)); }); ssdpd_.start(); } catch (std::exception& e) { } } // ---------------------------------------------------------------------------- void MainWindow::onSsdpDeviceAdded(QString usn, QString location, QString xml_location, QString apiType, QString device_name, QString unit_id) { try { QString name = device_name + "-" + unit_id; devicelist_.addDevice(name, location); } catch (std::exception& e) { } } // ---------------------------------------------------------------------------- void MainWindow::onSsdpDeviceRemoved(QString usn, QString location, QString xml_location, QString apiType, QString device_name, QString unit_id) { try { QString name = device_name + "-" + unit_id; devicelist_.removeDevice(name); } catch (std::exception& e) { } } // ---------------------------------------------------------------------------- void MainWindow::deviceSelected(QModelIndex index) { auto location = devicelist_.getDeviceLocation(index); if (location.toBool()) QDesktopServices::openUrl( QUrl(QString("http://") + location.toString(), QUrl::TolerantMode)); } // ---------------------------------------------------------------------------- void MainWindow::showAboutDialog() { AboutDialog about(this); about.exec(); } // ---------------------------------------------------------------------------- MainWindow::~MainWindow() { ssdpd_.stop(); QSettings settings("MagikEye", "MkEDiscovery"); settings.setValue("geometry", saveGeometry()); delete ui; }
31.453488
79
0.55841
[ "geometry" ]
77a710096f15a6ac8d8a0c299e67e54344732045
5,650
cc
C++
bin/cloud_provider_firebase/device_set/cloud_device_set_impl.cc
Acidburn0zzz/peridot
9a3b1fb8e834d0315092478d83d0176ef28cb765
[ "BSD-3-Clause" ]
1
2018-02-05T23:33:32.000Z
2018-02-05T23:33:32.000Z
bin/cloud_provider_firebase/device_set/cloud_device_set_impl.cc
Acidburn0zzz/peridot
9a3b1fb8e834d0315092478d83d0176ef28cb765
[ "BSD-3-Clause" ]
null
null
null
bin/cloud_provider_firebase/device_set/cloud_device_set_impl.cc
Acidburn0zzz/peridot
9a3b1fb8e834d0315092478d83d0176ef28cb765
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2017 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "peridot/bin/cloud_provider_firebase/device_set/cloud_device_set_impl.h" #include "lib/fxl/logging.h" #include "lib/fxl/strings/concatenate.h" namespace cloud_provider_firebase { namespace { std::string GetDeviceMapKey(fxl::StringView fingerprint) { return fxl::Concatenate({kDeviceMapRelpath, "/", fingerprint}); } std::vector<std::string> QueryParamsFromAuthToken(std::string auth_token) { std::vector<std::string> query_params; if (!auth_token.empty()) { query_params.push_back("auth=" + auth_token); } return query_params; } // Firebase-specific value that requests updating the timestamp. // See Firebase Database REST API documentation. const char kUpdateTimestampValue[] = "{\".sv\": \"timestamp\"}"; } // namespace CloudDeviceSetImpl::CloudDeviceSetImpl( std::unique_ptr<firebase::Firebase> user_firebase) : user_firebase_(std::move(user_firebase)) {} CloudDeviceSetImpl::~CloudDeviceSetImpl() { if (firebase_watcher_set_) { ResetWatcher(); } } void CloudDeviceSetImpl::CheckFingerprint( std::string auth_token, std::string fingerprint, std::function<void(Status)> callback) { auto query_params = QueryParamsFromAuthToken(auth_token); user_firebase_->Get( GetDeviceMapKey(fingerprint), query_params, [callback = std::move(callback)](firebase::Status status, const rapidjson::Value& value) { if (status != firebase::Status::OK) { FXL_LOG(WARNING) << "Unable to read version from the cloud."; callback(Status::NETWORK_ERROR); return; } if (value.IsNull()) { callback(Status::ERASED); return; } // If metadata are present, the version on the cloud is compatible. callback(Status::OK); }); } void CloudDeviceSetImpl::SetFingerprint(std::string auth_token, std::string fingerprint, std::function<void(Status)> callback) { auto query_params = QueryParamsFromAuthToken(auth_token); user_firebase_->Put( GetDeviceMapKey(fingerprint), query_params, kUpdateTimestampValue, [callback = std::move(callback)](firebase::Status status) { if (status != firebase::Status::OK) { FXL_LOG(WARNING) << "Unable to set local version on the cloud."; callback(Status::NETWORK_ERROR); return; } callback(Status::OK); }); } void CloudDeviceSetImpl::WatchFingerprint( std::string auth_token, std::string fingerprint, std::function<void(Status)> callback) { if (firebase_watcher_set_) { ResetWatcher(); } auto query_params = QueryParamsFromAuthToken(auth_token); user_firebase_->Watch(GetDeviceMapKey(fingerprint), query_params, this); firebase_watcher_set_ = true; watch_callback_ = callback; } void CloudDeviceSetImpl::EraseAllFingerprints( std::string auth_token, std::function<void(Status)> callback) { auto query_params = QueryParamsFromAuthToken(auth_token); user_firebase_->Delete( kDeviceMapRelpath, query_params, [callback = std::move(callback)](firebase::Status status) { if (status != firebase::Status::OK) { callback(Status::NETWORK_ERROR); return; } callback(Status::OK); }); } void CloudDeviceSetImpl::UpdateTimestampAssociatedWithFingerprint( std::string auth_token, std::string fingerprint) { auto query_params = QueryParamsFromAuthToken(auth_token); user_firebase_->Put(GetDeviceMapKey(fingerprint), query_params, kUpdateTimestampValue, [](firebase::Status status) { if (status != firebase::Status::OK) { FXL_LOG(WARNING) << "Firebase timestamp update returned status:" << status; } }); } void CloudDeviceSetImpl::OnPut(const std::string& /*path*/, const rapidjson::Value& value) { FXL_DCHECK(firebase_watcher_set_ && watch_callback_); if (value.IsNull()) { if (destruction_sentinel_.DestructedWhile( [this] { watch_callback_(Status::ERASED); })) { return; } ResetWatcher(); return; } watch_callback_(Status::OK); } void CloudDeviceSetImpl::OnPatch(const std::string& /*path*/, const rapidjson::Value& /*value*/) { FXL_DCHECK(firebase_watcher_set_ && watch_callback_); FXL_NOTIMPLEMENTED(); } void CloudDeviceSetImpl::OnCancel() { FXL_DCHECK(firebase_watcher_set_ && watch_callback_); FXL_NOTIMPLEMENTED(); } void CloudDeviceSetImpl::OnAuthRevoked(const std::string& /*reason*/) { if (destruction_sentinel_.DestructedWhile( [this] { watch_callback_(Status::NETWORK_ERROR); })) { return; } ResetWatcher(); } void CloudDeviceSetImpl::OnMalformedEvent() { FXL_DCHECK(firebase_watcher_set_ && watch_callback_); FXL_NOTIMPLEMENTED(); } void CloudDeviceSetImpl::OnConnectionError() { if (destruction_sentinel_.DestructedWhile( [this] { watch_callback_(Status::NETWORK_ERROR); })) { return; } ResetWatcher(); } void CloudDeviceSetImpl::ResetWatcher() { FXL_DCHECK(firebase_watcher_set_ && watch_callback_); user_firebase_->UnWatch(this); firebase_watcher_set_ = false; watch_callback_ = nullptr; } } // namespace cloud_provider_firebase
30.053191
81
0.659646
[ "vector" ]
77a880df90008795b9780e5af16568c40db68396
9,504
cpp
C++
performanceEval/test/lchol_csc_performance.cpp
CompOpt4Apps/Artifact-DataDepSimplify
4fa1bf2bda2902fec50a54ee79ae405a554fc9f4
[ "MIT" ]
5
2019-05-20T03:35:41.000Z
2021-09-16T22:22:13.000Z
performanceEval/test/lchol_csc_performance.cpp
CompOpt4Apps/Artifact-DataDepSimplify
4fa1bf2bda2902fec50a54ee79ae405a554fc9f4
[ "MIT" ]
null
null
null
performanceEval/test/lchol_csc_performance.cpp
CompOpt4Apps/Artifact-DataDepSimplify
4fa1bf2bda2902fec50a54ee79ae405a554fc9f4
[ "MIT" ]
null
null
null
// // Created by kazem on 11/14/18. // #include <stdio.h> //#include <cholmod.h> //#include <cholmod_function.h> #define MKL_ILP64 #define FLEXCOMPLEX typedef int INT; #define MKL_INT INT #include <iostream> #include <fstream> #include <sstream> #include <iostream> #include <chrono> //#include <mkl.h> #include <symbolic_analysis_CSC.h> #include <inspection_DAG03.h> #include "../src/lchol_csc_original.h" #include "../src/lchol_csc_inspector.h" #include "../src/lchol_csc_executor.h" #include "util.h" #define METIS 1 using namespace std; //#define DEBUG 1 #define VERIFY #define CPUTIME (SuiteSparse_time ( )) int main(int argc, char *argv[]) { if(argc != 2){ cout<<"\n\nMust be invoked like:" "\n ./fs_csc_per matList&Params.txt" "\n matlist.txt's first line must contain NThreads and NRuns (separated with comma)," "\n the subsequent line should be the list of input matricies." "\n NThreads being maximum number of threads to be used," "\n NRuns being number of runs to be averged\n\n"; return 1; } ofstream outSerT("results/table4.csv", std::ofstream::out | std::ofstream::app); ofstream outInsp("results/fig8.csv", std::ofstream::out | std::ofstream::app); ofstream outExec("results/fig7.csv", std::ofstream::out | std::ofstream::app); outSerT<<"\nL. Chol"; outInsp<<"\nL. Chol"; outExec<<"\nL. Chol"; std::string inputMatrix; int numThread=8; int nRuns=1; string parameters; ifstream inF(argv[1]); getline( inF, parameters ); sscanf(parameters.c_str(), "%d, %d",&numThread,&nRuns); int innerParts = 16;//atoi(argv[3]);//Inner parts int divRate = 5;//atoi(argv[4]); int chunk = innerParts/numThread + 1; int levelParam = 5;// level distance int blasThreads = 1; // Looping over input matricies for( ; getline( inF, inputMatrix ); ){ if(inputMatrix=="") break; std::string f1 = argv[1]; int *colA, *rowA; double *valL_nonblock; double *valA; int maxSupWid, maxCol; size_t n, nnzA; //std::vector<profilingInfo> piArray; std::chrono::time_point<std::chrono::system_clock> start, end; std::chrono::duration<double> elapsed_seconds; std::chrono::duration<double> elapsed_secondsT; double durationID[20] = {0.0}, durationIL[20] = {0.0}, durationE[20] = {0.0}, durationTT[20] = {0.0}, inspTT; double serialMedTT = 0.0, serialMedE = 0.0, serialAvgTT = 0.0, serialAvgE = 0.0; double durationSym = 0, duration3 = 0, duration2 = 0, duration1 = 0; std::cout <<"\n\n---------- Started Reading Matrix: "<< inputMatrix; if (!readMatrix(inputMatrix, n, nnzA, colA, rowA, valA)){ return 1; } /* int numThread = atoi(argv[2]); int innerParts = atoi(argv[4]);//Inner parts int divRate = atoi(argv[3]);// level distance int chunk = innerParts/numThread + 1; int blasThreads = 1; int levelParam = 5; std::chrono::time_point<std::chrono::system_clock> start, end; std::chrono::duration<double> elapsed_seconds; double duration = 0; */ omp_set_num_threads(numThread); // MKL_Set_Num_Threads(numThread); // MKL_Set_Num_Threads(1); // MKL_Domain_Set_Num_Threads(blasThreads, MKL_DOMAIN_BLAS); int *prunePtr, *pruneSet; int *levelPtr = NULL, *levelSet = NULL, *parPtr = NULL, *partition = NULL; int nLevels = 0, nPar = 0; double *nodeCost; double *timingChol = new double[4 + numThread]();//for time measurement double orderingTime = 0; int nrelax[3] = {4, 16, 48};//TODO double zrelax[3] = {0.8, 0.1, 0.05}; int status = 0; CSC *Amat = new CSC; Amat->nzmax = nnzA; Amat->ncol = Amat->nrow = n; Amat->stype = -1; Amat->xtype = CHOLMOD_REAL; Amat->packed = TRUE; Amat->p = colA; Amat->i = rowA; Amat->x = valA; Amat->nz = NULL; Amat->sorted = TRUE; BCSC *L = analyze_DAG_CSC(1, Amat, NULL, NULL, nrelax, zrelax, n, prunePtr, pruneSet, nLevels, levelPtr, levelSet, nPar, parPtr, partition, innerParts, levelParam, divRate, status, maxSupWid, maxCol, orderingTime); valL_nonblock = new double[L->xsize](); std::cout<<"\n\nRunning "<<f1<<"\n"; // # Inspector: std::vector<std::vector<int>> DAG; DAG.resize(n); //for(int i = 0 ; i < n ; i++ ) DAG[i].push_back(i); std::vector<std::set<int>> DAG_s; DAG_s.resize(n); start = std::chrono::system_clock::now(); // Creating the DAG with generated /*fs_csc_inspector(n,A2->p, A2->i, DAG_s); int *v, *edg; v = new int[n+1](); edg = new int[nnzA](); int ct=0, edges=0; for(ct = 0, edges = 0; ct < n; ct++){ v[ct] = edges; std::set<int> tms = DAG_s[ct]; edg[edges++] = ct; for (std::set<int>::iterator it= tms.begin(); it!=tms.end(); ++it) edg[edges++] = *it; }*/ lchol_csc_inspector(n,Amat->p, Amat->i, DAG); int *v, *edg; v = new int[n+1](); edg = new int[nnzA](); int cti,edges=0; for(cti = 0, edges = 0; cti < n; cti++){ v[cti] = edges; edg[edges++] = cti; for (int ctj = 0; ctj < DAG[cti].size(); ctj++) edg[edges++] = DAG[cti][ctj]; } v[cti] = edges; end = std::chrono::system_clock::now(); elapsed_secondsT = end - start; inspTT = elapsed_secondsT.count(); std::cout<<"\n\nInspector time = "<<inspTT<<"\n"; start = std::chrono::system_clock::now(); // build H- level set //Computing cost nodeCost = new double[n]; int *xi = new int[2*n](); for (int s = 0; s < n; ++s) { nodeCost[s]=L->ColCount[s]; } delete[]L->ColCount; //HACK to avoid conversion int *LP = new int[n+1]; for (int m = 0; m <= n; ++m) { LP[m] = static_cast<int>(L->p[m]); } nLevels = getCoarseLevelSet_DAG_CSC03(n,LP,L->i,nLevels, levelPtr, levelSet, nPar, parPtr, partition, innerParts, levelParam, divRate, nodeCost); end = std::chrono::system_clock::now(); elapsed_seconds = end - start; double HD = elapsed_seconds.count(); delete []LP; #if 0 bool *to_check = new bool[n](); for (int k = 0; k < nLevels; ++k) { for (int i = levelPtr[k]; i < levelPtr[k+1]; ++i) { assert(levelSet[i]<n); to_check[levelSet[i]] = true; } } for (int l = 0; l < n; ++l) { assert(to_check[l]); } #endif CSC *A1 = ptranspose(Amat, 2, L->Perm, NULL, 0, status); CSC *A2 = ptranspose(A1, 2, NULL, NULL, 0, status); // ------ Sequentially Run std::cout <<"-- Running the algorithm sequentially for #"<<nRuns<<" times:\n"; for (int l = 0; l < nRuns; ++l) { for (int i = 0; i < L->xsize; ++i) { valL_nonblock[i] = 0.0; } start = std::chrono::system_clock::now(); lchol_csc_original(n, A2->p, A2->i, A2->x, L->p, L->i, valL_nonblock, prunePtr,pruneSet); end = std::chrono::system_clock::now(); elapsed_secondsT = end - start; durationE[l] = elapsed_secondsT.count(); } // Calculating Median and Average of execution times for plotting std::sort(durationE, durationE+nRuns); double medE; if(nRuns%2) { medE = durationE[(int(nRuns/2))]; } else { medE = (durationE[(int(nRuns/2))]+durationE[(int(nRuns/2))-1])/2.0; } serialMedE = medE; std::cout <<"\n>>>>>>>>>>>> Median of Execution times = "<<medE <<"\n"; // --------- Wavefront run std::cout<<"\n\n--Running the algorithm with #" <<numThread<<" threads in parallel for #"<<nRuns<<" times:"; //****************Parallel H2 CSC for (int l = 0; l < nRuns; ++l) { for (int i = 0; i < L->xsize; ++i) { valL_nonblock[i] = 0.0; } start = std::chrono::system_clock::now(); lchol_csc_executor(n, A2->p, A2->i, A2->x, L->p, L->i, valL_nonblock, prunePtr,pruneSet, nLevels, levelPtr, levelSet, nPar, parPtr, partition, chunk); end = std::chrono::system_clock::now(); elapsed_secondsT = end-start; durationE[l] = elapsed_secondsT.count(); } // Calculating Median and Average of execution times for plotting std::sort(durationE, durationE+nRuns); if(nRuns%2) { medE = durationE[(int(nRuns/2))]; } else { medE = (durationE[(int(nRuns/2))]+durationE[(int(nRuns/2))-1])/2.0; } std::cout <<"\n>>>>>>>>>>>> Median of Inspector Dependence times = "<<inspTT <<"\n"; std::cout <<">>>>>>>>>>>> Median of Inspector Build Level Set times = "<<HD <<"\n"; std::cout <<">>>>>>>>>>>> Median of Execution times = "<<medE <<"\n"; std::cout <<"\n>>>>>>> Exec run break point = "<< (HD+inspTT)/(serialMedE-medE) <<"\n"; std::cout <<">>>>>>> Executor Speed up = "<< (serialMedE/medE) <<"\n"; // Outputing serial execution times (table 4) outSerT<<", "<<serialMedE; // Making Figures // Making stacked histogram number of executor run needed to make executor worth it outInsp<<", "<<(HD+inspTT)/(serialMedE-medE); // Making stacked histogram for executor speed up outExec<<", "<<(serialMedE/medE); allocateAC(A2, 0, 0, 0, FALSE); allocateAC(A1, 0, 0, 0, FALSE); allocateAC(Amat, 0, 0, 0, FALSE); delete []prunePtr; delete []pruneSet; delete []valL_nonblock; delete []levelPtr; delete []levelSet; } outSerT.close(); outInsp.close(); outExec.close(); return 1; }
28.887538
113
0.584701
[ "vector" ]
77b0ede1abcd9daf934a9823d7f3ad4df0ffb0a0
2,241
hpp
C++
include/libp2p/peer/key_repository.hpp
Alexey-N-Chernyshov/cpp-libp2p
8b52253f9658560a4b1311b3ba327f02284a42a6
[ "Apache-2.0", "MIT" ]
135
2020-06-13T08:57:36.000Z
2022-03-27T05:26:11.000Z
include/libp2p/peer/key_repository.hpp
igor-egorov/cpp-libp2p
7c9d83bf0760a5f653d86ddbb00645414c61d4fc
[ "Apache-2.0", "MIT" ]
41
2020-06-12T15:45:05.000Z
2022-03-07T23:10:33.000Z
include/libp2p/peer/key_repository.hpp
igor-egorov/cpp-libp2p
7c9d83bf0760a5f653d86ddbb00645414c61d4fc
[ "Apache-2.0", "MIT" ]
43
2020-06-15T10:12:45.000Z
2022-03-21T03:04:50.000Z
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef LIBP2P_KEY_REPOSITORY_HPP #define LIBP2P_KEY_REPOSITORY_HPP #include <unordered_set> #include <vector> #include <libp2p/crypto/key.hpp> #include <libp2p/peer/peer_id.hpp> #include <libp2p/outcome/outcome.hpp> namespace libp2p::peer { /** * @brief Class that provides access to public keys of other peers, and * keypairs of this peer. */ class KeyRepository { protected: using Pub = crypto::PublicKey; using PubVec = std::unordered_set<Pub>; using PubVecPtr = std::shared_ptr<PubVec>; using KeyPair = crypto::KeyPair; using KeyPairVec = std::unordered_set<KeyPair>; using KeyPairVecPtr = std::shared_ptr<KeyPairVec>; public: virtual ~KeyRepository() = default; /** * @brief remove all keys related to peer {@param p} * @param p peer */ virtual void clear(const PeerId &p) = 0; /** * @brief Getter for public keys of given {@param p} Peer. * @param p PeerId * @return pointer to a set of public keys associated with given peer. */ virtual outcome::result<PubVecPtr> getPublicKeys(const PeerId &p) = 0; /** * @brief Add public key to a set of public keys associated with {@param p} * PeerId. * @param p PeerId * @param pub public key * @return error code in case of error. */ virtual outcome::result<void> addPublicKey( const PeerId &p, const crypto::PublicKey &pub) = 0; /** * @brief Getter for keypairs associated with this peer. * @param p PeerId. * @return pointer to a set of keypairs associated with {@param p}. */ virtual outcome::result<KeyPairVecPtr> getKeyPairs() = 0; /** * @brief Associate a keypair {@param kp} with current peer. * @param kp KeyPair * @return error code in case of error. */ virtual outcome::result<void> addKeyPair(const KeyPair &kp) = 0; /** * @brief Returns set of peer ids known by this repository. * @return unordered set of peers */ virtual std::unordered_set<PeerId> getPeers() const = 0; }; } // namespace libp2p::peer #endif // LIBP2P_KEY_REPOSITORY_HPP
27.329268
79
0.652834
[ "vector" ]
77b3cd379aa297ffb3e4c22a57c6ea15427a1019
869
cpp
C++
graph/trajan.cpp
qwer312132/competive-programing
05ea48900c827753a7b5723ef54a0852f7e7cbc1
[ "CECILL-B" ]
null
null
null
graph/trajan.cpp
qwer312132/competive-programing
05ea48900c827753a7b5723ef54a0852f7e7cbc1
[ "CECILL-B" ]
null
null
null
graph/trajan.cpp
qwer312132/competive-programing
05ea48900c827753a7b5723ef54a0852f7e7cbc1
[ "CECILL-B" ]
null
null
null
struct Scc{ int n, nScc, vst[MXN], bln[MXN], num; int dfn[MXN], low[MXN]; vector<int> E[MXN]; stack<int> stk; void init(int _n){ n = _n; num = nScc = 0; for(int i = 0; i <= n; ++i) E[i].clear(); FZ(vst); FZ(dfn); FZ(low); while(!stk.empty()) stk.pop(); } void addEdge(int u, int v){E[u].pb(v);} void dfnlow(int u){ int v; dfn[u] = low[u] = ++num; stk.push(u); vst[u] = 1; for(int i = 0; i < E[u].size(); ++i){ v = E[u][i]; if(!dfn[v]){dfnlow(v);low[u] = min(low[u], low[v]);} else if(vst[v]) low[u] = min(low[u], dfn[v]); } if(dfn[u] == low[u]){ int t; ++nScc; do{ t = stk.top(); stk.pop(); vst[t] = 0; bln[t] = nScc; }while (t != u); } } void solve() { for(int i = 1; i <= n; ++i) if(!dfn[i]) dfnlow(i); } };
26.333333
59
0.428078
[ "vector" ]
77b6b832f1ccd05e7459dae4cf32b3f168e28a0a
3,209
cpp
C++
openikcape/core/vlefunctions.cpp
Nukleon84/openikcape
7612a7c68237920373c11f137130d74f7ad134eb
[ "MIT" ]
19
2020-09-08T07:23:10.000Z
2022-01-10T19:12:51.000Z
openikcape/core/vlefunctions.cpp
Nukleon84/openikcape
7612a7c68237920373c11f137130d74f7ad134eb
[ "MIT" ]
null
null
null
openikcape/core/vlefunctions.cpp
Nukleon84/openikcape
7612a7c68237920373c11f137130d74f7ad134eb
[ "MIT" ]
2
2020-09-09T15:10:39.000Z
2021-08-05T00:53:28.000Z
#include <string> #include <vector> #include <stdexcept> #include <math.h> #include "thermodynamics.h" #include "activityProperties.h" #include "vleqfunctions.h" using namespace std; using namespace Thermodynamics::Types; namespace Thermodynamics { namespace VLEQFunctions { ActivityProperties ActivityCoefficients(Real T, Real p, VectorXReal x, const Thermodynamics::Types::ThermodynamicSystem *sys) { switch (sys->activityMethod) { case ActivityMethod::NRTL: return calculateNRTL(T,p,x, sys); break; default: break; } return ActivityProperties(); } FugacityProperties FugacityCoefficients(Real T, Real p, VectorXReal y, const Thermodynamics::Types::ThermodynamicSystem *sys) { switch (sys->fugacityMethod) { default: FugacityProperties vprops; //Assume ideal gas phase for every system vprops.phi = VectorXReal::Ones(sys->NC); vprops.lnphi = VectorXReal::Zero(sys->NC); vprops.Gex = 0; vprops.Hex = 0; return vprops; break; } return FugacityProperties(); } VectorXReal WilsonKFactors(EquilibriumArguments args, const Thermodynamics::Types::ThermodynamicSystem *sys) { VectorXReal result = VectorXReal::Zero(sys->NC); for (int i = 0; i < sys->NC; i++) { double Pci = sys->substances[i].constants.at(MolecularProperties::CriticalPressure).amount; double wi= sys->substances[i].constants.at(MolecularProperties::AcentricFactor).amount; double Tci= sys->substances[i].constants.at(MolecularProperties::CriticalTemperature).amount; result[i] = exp(log(Pci / args.P) + 5.373 * (1 + wi) * (1 - Tci / args.T)); } return result; } VectorXReal KValues(EquilibriumArguments args, const Thermodynamics::Types::ThermodynamicSystem *sys) { VectorXReal result = VectorXReal(sys->NC); ActivityProperties lprops; FugacityProperties vprops; /*ActivityArguments act_args; act_args.T = args.T; act_args.P = args.P; act_args.x = args.x; FugacityArguments fug_args; fug_args.T = args.T; fug_args.P = args.P; fug_args.y = args.y;*/ if (sys->approach == EquilibriumApproach::GammaPhi) { lprops = ActivityCoefficients(args.T, args.P, args.x, sys); vprops = FugacityCoefficients(args.T, args.P, args.y, sys); for (int i = 0; i < sys->NC; i++) { auto vp = PureFunctions::get_pure_property(PureProperties::VaporPressure, i, args.T, sys); result[i] = lprops.gamma[i] * vp / (vprops.phi[i] * args.P); } } return result; } } // namespace VLEQFunctions } // namespace Thermodynamics
33.778947
134
0.555002
[ "vector" ]
77b7a133c1b80e54fa251f2a99709c7ee45f2818
2,774
hpp
C++
Doremi/Core/Include/PositionCorrectionHandler.hpp
meraz/doremi
452d08ebd10db50d9563c1cf97699571889ab18f
[ "MIT" ]
1
2020-03-23T15:42:05.000Z
2020-03-23T15:42:05.000Z
Doremi/Core/Include/PositionCorrectionHandler.hpp
Meraz/ssp15
452d08ebd10db50d9563c1cf97699571889ab18f
[ "MIT" ]
null
null
null
Doremi/Core/Include/PositionCorrectionHandler.hpp
Meraz/ssp15
452d08ebd10db50d9563c1cf97699571889ab18f
[ "MIT" ]
1
2020-03-23T15:42:06.000Z
2020-03-23T15:42:06.000Z
#pragma once #include <DirectXMath.h> #include <list> #include <vector> namespace DoremiEngine { namespace Core { class SharedContext; } } namespace Doremi { namespace Core { /** TODOCM doc */ struct MovementStamp { MovementStamp(DirectX::XMFLOAT3 p_position, DirectX::XMFLOAT4 p_orientation, DirectX::XMFLOAT3 p_movement, uint8_t p_sequence) : Position(p_position), Orientation(p_orientation), Movement(p_movement), Sequence(p_sequence) { } uint8_t Sequence; DirectX::XMFLOAT3 Position; DirectX::XMFLOAT4 Orientation; DirectX::XMFLOAT3 Movement; bool operator==(const uint8_t& p_sequence) const { return Sequence == p_sequence; } }; /** TODOCM doc */ class PositionCorrectionHandler { public: /** StartPositionCorrectionHandler needs to be called befor this */ static PositionCorrectionHandler* GetInstance(); /** Needs to be called befor GetInstance */ static void StartPositionCorrectionHandler(const DoremiEngine::Core::SharedContext& p_sharedContext); /** Checks a position retrieved from server and sets the correction to the next interpolation goal */ void InterpolatePositionFromServer(DirectX::XMFLOAT3 p_positionToCheck, uint8_t p_sequenceOfPosition); /** Doesn't extrapolate for now, but actually applies the physics position to the transform */ void ExtrapolatePosition(); /** Queues position and movement, used as we check vs server later */ void QueuePlayerPositionForCheck(DirectX::XMFLOAT3 p_position, DirectX::XMFLOAT4 p_orientation, DirectX::XMFLOAT3 p_movement, uint8_t p_sequence); private: /** Constructor */ PositionCorrectionHandler(const DoremiEngine::Core::SharedContext& p_sharedContext); /** Destructor */ ~PositionCorrectionHandler(); /** Singleton pointer */ static PositionCorrectionHandler* m_singleton; /** Sharedcontext, used to get physics */ const DoremiEngine::Core::SharedContext& m_sharedContext; /** Buffered positions and movements from the past we can use for checking vs server pos */ std::list<MovementStamp> m_PositionStamps; }; } }
29.510638
158
0.566691
[ "vector", "transform" ]
77b832dbe2da74cc90d312cbb99c502dd00a95b7
552
cpp
C++
LuoguCodes/CF1008A.cpp
Anguei/OI-Codes
0ef271e9af0619d4c236e314cd6d8708d356536a
[ "MIT" ]
null
null
null
LuoguCodes/CF1008A.cpp
Anguei/OI-Codes
0ef271e9af0619d4c236e314cd6d8708d356536a
[ "MIT" ]
null
null
null
LuoguCodes/CF1008A.cpp
Anguei/OI-Codes
0ef271e9af0619d4c236e314cd6d8708d356536a
[ "MIT" ]
null
null
null
#include <cctype> #include <set> #include <vector> #include <string> #include <iostream> #include <algorithm> int main() { std::string s; std::cin >> s; for (auto &i : s) if (isupper(i)) i += 32; std::set<char> set = { ';a';, ';e';, ';i';, ';o';, ';u'; }; for (int i = 0; i < s.size() - 1; ++i) if (!set.count(s[i]) && s[i] != ';n'; && !set.count(s[i + 1])) { std::cout << "No" << std::endl; return 0; } if (!set.count(s.back()) && s.back() != ';n';) std::cout << "No" << std::endl; else std::cout << "Yes" << std::endl; }
21.230769
64
0.483696
[ "vector" ]
77ba80648a050d77e0019568894a6fc8915f1eb2
9,104
hpp
C++
lib/malloy/http/routing/router.hpp
madmongo1/malloy
69e383d319d4d090888cab21b0c33e3c1499d8ab
[ "MIT" ]
null
null
null
lib/malloy/http/routing/router.hpp
madmongo1/malloy
69e383d319d4d090888cab21b0c33e3c1499d8ab
[ "MIT" ]
null
null
null
lib/malloy/http/routing/router.hpp
madmongo1/malloy
69e383d319d4d090888cab21b0c33e3c1499d8ab
[ "MIT" ]
null
null
null
#pragma once #include "route.hpp" #include "../request.hpp" #include "../response.hpp" #include "../http.hpp" #include "../generator.hpp" #include <boost/beast/core.hpp> #include <boost/beast/http.hpp> #include <boost/beast/version.hpp> #include <spdlog/logger.h> #include <filesystem> #include <functional> #include <memory> #include <string> #include <string_view> #include <vector> #include <ranges> namespace spdlog { class logger; } namespace malloy::http::server { using namespace malloy; // TODO: This might not be thread-safe the way we pass an instance to the listener and then from // there to each session. Investigate and fix this! /** * An HTTP request router. * * @details This class implements a basic router for HTTP requests. */ class router { public: /** * The method type to use. */ using method_type = http::method; /** * The request type to use. */ using request_type = malloy::http::request; /** * The response type to use. */ using response_type = malloy::http::response; /** * Default constructor. */ router() = default; /** * Constructor. * * @param logger The logger instance to use. */ explicit router(std::shared_ptr<spdlog::logger> logger); /** * Copy constructor. */ router(const router& other) = delete; /** * Move constructor. */ router(router&& other) noexcept = delete; /** * Destructor. */ virtual ~router() = default; /** * Copy assignment operator. * * @param rhs The right-hand-side object to copy-assign from. * @return A reference to the assignee. */ router& operator=(const router& rhs) = delete; /** * Move assignment operator. * * @param rhs The right-hand-side object to move-assign from. * @return A reference to the assignee. */ router& operator=(router&& rhs) noexcept = delete; /** * Set the logger to use. * * @param logger The logger to use. */ void set_logger(std::shared_ptr<spdlog::logger> logger); /** * Controls whether the router should automatically generate preflight responses. * * @note Currently only preflights for routes are generated. * * @param enabled Whether to enable automatic preflight response generation. */ void generate_preflights(const bool enabled) { m_generate_preflights = enabled; } /** * Add a handler for a specific method & resource. * * @param method The HTTP method. * @param target The resource path. * @param handler The handler to generate the response. * @return Whether adding the route was successful. */ bool add(method_type method, std::string_view target, std::function<response_type(const request_type&)>&& handler); /** * Add a sub-router for a specific resource. * * @param resource The resource base path for the sub-router. * @param sub_router The sub-router. * @return Whether adding the sub-router was successful. */ bool add_subrouter(std::string resource, std::shared_ptr<router> sub_router); /** * Add a file-serving location. * * @param resource * @param storage_base_path * @return Whether adding the file serving was successful. */ bool add_file_serving(std::string resource, std::filesystem::path storage_base_path); /** * Adds a redirection rule. * * @param resource_old * @param resource_new * @param status The HTTP status code to use. This must be a 3xx status code. * @return Whether adding the redirect was successful. */ bool add_redirect(http::status status, std::string&& resource_old, std::string&& resource_new); /** * Handle a request. * * @tparam Send The response writer type. * @param doc_root Path to the HTTP document root. * @param req The request to handle. * @param send The response writer to use. */ template<class Send> void handle_request( const std::filesystem::path& doc_root, request&& req, Send&& send ) { // Log m_logger->debug("handling request: {} {}", std::string_view{ req.method_string().data(), req.method_string().size() }, req.uri().resource_string() ); // Check sub-routers for (const auto& [resource_base, router] : m_sub_routers) { // Check match if (not req.uri().resource_starts_with(resource_base)) continue; // Log m_logger->debug("invoking sub-router on {}", resource_base); // Chop request resource path req.uri().chop_resource(resource_base); // Let the sub-router handle things from here... router->handle_request(doc_root, std::move(req), std::forward<Send>(send)); // We're done handling this request return; } // Check routes for (const auto& route : m_routes) { // Check match if (not route->matches(req)) continue; // Generate preflight response (if supposed to) if (m_generate_preflights and (req.method() == method::options)) { // Log m_logger->debug("automatically constructing preflight response."); // Generate auto resp = generate_preflight_response(req); // Send the response send_response(req, std::move(resp), std::forward<Send>(send)); // We're done handling this request return; } // Generate the response for the request auto resp = route->handle(req); // Send the response send_response(req, std::move(resp), std::forward<Send>(send)); // We're done handling this request return; } // If we end up where we have no meaningful way of handling this request return send_response(req, std::move(generator::bad_request("unknown request")), std::forward<Send>(send)); } private: std::shared_ptr<spdlog::logger> m_logger; std::unordered_map<std::string, std::shared_ptr<router>> m_sub_routers; std::vector<std::shared_ptr<route<request_type, response_type>>> m_routes; bool m_generate_preflights = false; /** * Adds a route to the list of routes. * * @note This uses @ref log_or_throw() internally and might therefore throw if no logger is available. * * @param r The route to add. * @return Whether adding the route was successful. */ bool add_route(std::shared_ptr<route<request_type, response_type>>&& r); response_type generate_preflight_response(const request_type& req) const; /** * Adds a message to the log or throws an exception if no logger is available. * * @tparam FormatString * @tparam Args * @param exception * @param level * @param fmt * @param args * @return */ template<typename FormatString, typename... Args> bool log_or_throw(const std::exception& exception, const spdlog::level::level_enum level, const FormatString& fmt, Args&&...args) { if (m_logger) { m_logger->log(level, fmt, std::forward<Args>(args)...); return false; } else { throw exception; } } /** * Send a response. * * @tparam Send The response writer type. * @param req The request to which we're responding. * @param resp The response. * @param send The response writer. */ template<typename Send> void send_response(const request_type& req, response_type&& resp, Send&& send) { // Add more information to the response resp.keep_alive(req.keep_alive()); resp.version(req.version()); resp.set(boost::beast::http::field::server, BOOST_BEAST_VERSION_STRING); resp.prepare_payload(); send(std::move(resp)); } }; }
30.756757
137
0.544925
[ "object", "vector" ]
77c09bd9d3ae45d0cf57a440744905cf0ff38357
8,167
cpp
C++
src/bounce/cloth/cloth_contact_manager.cpp
demiurgestudios/bounce
9f8dcae52a074ba76088da9c94471366f6e4ca8f
[ "Zlib" ]
26
2020-02-10T19:28:00.000Z
2021-09-23T22:36:37.000Z
src/bounce/cloth/cloth_contact_manager.cpp
demiurgestudios/bounce
9f8dcae52a074ba76088da9c94471366f6e4ca8f
[ "Zlib" ]
null
null
null
src/bounce/cloth/cloth_contact_manager.cpp
demiurgestudios/bounce
9f8dcae52a074ba76088da9c94471366f6e4ca8f
[ "Zlib" ]
7
2020-01-22T20:42:33.000Z
2021-02-25T02:34:54.000Z
/* * Copyright (c) 2016-2019 Irlan Robson https://irlanrobson.github.io * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include <bounce/cloth/cloth_contact_manager.h> #include <bounce/cloth/cloth.h> #include <bounce/cloth/cloth_mesh.h> #include <bounce/cloth/particle.h> #include <bounce/cloth/cloth_triangle.h> #include <bounce/dynamics/world.h> #include <bounce/dynamics/world_listeners.h> #include <bounce/dynamics/shapes/shape.h> #include <bounce/dynamics/body.h> b3ClothContactManager::b3ClothContactManager() : m_particleTriangleContactBlocks(sizeof(b3ParticleTriangleContact)), m_particleBodyContactBlocks(sizeof(b3ParticleBodyContact)) { } void b3ClothContactManager::FindNewContacts() { FindNewClothContacts(); FindNewBodyContacts(); } void b3ClothContactManager::FindNewClothContacts() { B3_PROFILE("Cloth Find New Cloth Contacts"); m_broadPhase.FindPairs(this); } class b3ClothContactManagerFindNewBodyContactsQueryListener : public b3QueryListener { public: virtual bool ReportShape(b3Shape* s2) { cm->AddPSPair(p1, s2); // Keep looking for overlaps return true; } b3ClothContactManager* cm; b3Particle* p1; }; void b3ClothContactManager::FindNewBodyContacts() { B3_PROFILE("Cloth Find New Body Contacts"); // Is there a world attached to this cloth? if (m_cloth->m_world == nullptr) { return; } for (b3Particle* p = m_cloth->m_particleList.m_head; p; p = p->m_next) { if (p->m_type != e_dynamicParticle) { continue; } b3AABB3 aabb = m_broadPhase.GetAABB(p->m_broadPhaseId); b3ClothContactManagerFindNewBodyContactsQueryListener listener; listener.cm = this; listener.p1 = p; m_cloth->m_world->QueryAABB(&listener, aabb); } } void b3ClothContactManager::AddPSPair(b3Particle* p1, b3Shape* s2) { // Check if there is a contact between the two entities. for (b3ParticleBodyContact* c = m_particleBodyContactList.m_head; c; c = c->m_next) { if (c->m_p1 == p1 && c->m_s2 == s2) { // A contact already exists. return; } } bool isntDynamic1 = p1->m_type != e_dynamicParticle; bool isntDynamic2 = s2->GetBody()->GetType() != e_dynamicBody; if (isntDynamic1 && isntDynamic2) { // The entities must not collide with each other. return; } // Create a new contact. b3ParticleBodyContact* c = CreateParticleBodyContact(); c->m_p1 = p1; c->m_s2 = s2; c->m_active = false; c->m_normalImpulse = 0.0f; c->m_tangentImpulse.SetZero(); // Add the contact to the body contact list. m_particleBodyContactList.PushFront(c); } void b3ClothContactManager::AddPair(void* data1, void* data2) { b3ClothAABBProxy* proxy1 = (b3ClothAABBProxy*)data1; b3ClothAABBProxy* proxy2 = (b3ClothAABBProxy*)data2; if (proxy1->type == e_particleProxy && proxy2->type == e_particleProxy) { // Particle-particle contacts are not supported. return; } if (proxy1->type == e_triangleProxy && proxy2->type == e_triangleProxy) { // Triangle-triangle contacts are not supported. return; } if (proxy1->type == e_triangleProxy) { // Ensure proxy1 is a particle and proxy 2 a triangle. b3Swap(proxy1, proxy2); } B3_ASSERT(proxy1->type == e_particleProxy); B3_ASSERT(proxy2->type == e_triangleProxy); b3Particle* p1 = (b3Particle*)proxy1->owner; b3ClothTriangle* t2 = (b3ClothTriangle*)proxy2->owner; b3ClothMeshTriangle* triangle = m_cloth->m_mesh->triangles + t2->m_triangle; b3Particle* p2 = m_cloth->m_particles[triangle->v1]; b3Particle* p3 = m_cloth->m_particles[triangle->v2]; b3Particle* p4 = m_cloth->m_particles[triangle->v3]; // Check if there is a contact between the two entities. for (b3ParticleTriangleContact* c = m_particleTriangleContactList.m_head; c; c = c->m_next) { if (c->m_p1 == p1 && c->m_t2 == t2) { // A contact already exists. return; } } bool isntDynamic1 = p1->m_type != e_dynamicParticle; bool isntDynamic2 = p2->m_type != e_dynamicParticle && p3->m_type != e_dynamicParticle && p4->m_type != e_dynamicParticle; if (isntDynamic1 && isntDynamic2) { // The entities must not collide with each other. return; } if (p1 == p2 || p1 == p3 || p1 == p4) { // The entities must not collide with each other. return; } // Create a new contact. b3ParticleTriangleContact* c = CreateParticleTriangleContact(); c->m_p1 = p1; c->m_t2 = t2; c->m_p2 = p2; c->m_p3 = p3; c->m_p4 = p4; c->m_normalImpulse = 0.0f; c->m_tangentImpulse1 = 0.0f; c->m_tangentImpulse2 = 0.0f; c->m_active = false; // Add the contact to the cloth contact list. m_particleTriangleContactList.PushFront(c); } b3ParticleTriangleContact* b3ClothContactManager::CreateParticleTriangleContact() { void* block = m_particleTriangleContactBlocks.Allocate(); return new(block) b3ParticleTriangleContact(); } void b3ClothContactManager::Destroy(b3ParticleTriangleContact* c) { m_particleTriangleContactList.Remove(c); c->~b3ParticleTriangleContact(); m_particleTriangleContactBlocks.Free(c); } b3ParticleBodyContact* b3ClothContactManager::CreateParticleBodyContact() { void* block = m_particleBodyContactBlocks.Allocate(); return new(block) b3ParticleBodyContact(); } void b3ClothContactManager::Destroy(b3ParticleBodyContact* c) { m_particleBodyContactList.Remove(c); c->~b3ParticleBodyContact(); m_particleBodyContactBlocks.Free(c); } void b3ClothContactManager::UpdateContacts() { UpdateClothContacts(); UpdateBodyContacts(); } void b3ClothContactManager::UpdateClothContacts() { B3_PROFILE("Cloth Update Cloth Contacts"); // Update the state of particle-triangle contacts. b3ParticleTriangleContact* c = m_particleTriangleContactList.m_head; while (c) { bool isntDynamic1 = c->m_p1->m_type != e_dynamicParticle; bool isntDynamic2 = c->m_p2->m_type != e_dynamicParticle && c->m_p3->m_type != e_dynamicParticle && c->m_p4->m_type != e_dynamicParticle; // Destroy the contact if primitives must not collide with each other. if (isntDynamic1 && isntDynamic2) { b3ParticleTriangleContact* quack = c; c = c->m_next; Destroy(quack); continue; } u32 proxy1 = c->m_p1->m_broadPhaseId; u32 proxy2 = c->m_t2->m_broadPhaseId; // Destroy the contact if primitive AABBs are not overlapping. bool overlap = m_broadPhase.TestOverlap(proxy1, proxy2); if (overlap == false) { b3ParticleTriangleContact* quack = c; c = c->m_next; Destroy(quack); continue; } // The contact persists. c->Update(); c = c->m_next; } } void b3ClothContactManager::UpdateBodyContacts() { B3_PROFILE("Cloth Update Body Contacts"); // Update the state of particle-body contacts. b3ParticleBodyContact* c = m_particleBodyContactList.m_head; while (c) { bool isntDynamic1 = c->m_p1->m_type != e_dynamicParticle; bool isntDynamic2 = c->m_s2->GetBody()->GetType() != e_dynamicBody; // Cease the contact if entities must not collide with each other. if (isntDynamic1 && isntDynamic2) { b3ParticleBodyContact* quack = c; c = c->m_next; Destroy(quack); continue; } b3AABB3 aabb1 = m_broadPhase.GetAABB(c->m_p1->m_broadPhaseId); b3AABB3 aabb2 = c->m_s2->GetAABB(); // Destroy the contact if entities AABBs are not overlapping. bool overlap = b3TestOverlap(aabb1, aabb2); if (overlap == false) { b3ParticleBodyContact* quack = c; c = c->m_next; Destroy(quack); continue; } // The contact persists. c->Update(); c = c->m_next; } }
25.926984
139
0.728909
[ "shape" ]
77c24f4c143df69d5a52cb97eab8cbb8b1d4e827
1,086
cpp
C++
atcoder/abc180/e.cpp
polylogarithm/cp
426cb6f6ba389ff5f492e5bc2e957aac128781b5
[ "MIT" ]
null
null
null
atcoder/abc180/e.cpp
polylogarithm/cp
426cb6f6ba389ff5f492e5bc2e957aac128781b5
[ "MIT" ]
null
null
null
atcoder/abc180/e.cpp
polylogarithm/cp
426cb6f6ba389ff5f492e5bc2e957aac128781b5
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; const int INF = 100000000; //https://atcoder.jp/contests/abc180/editorial/249 //https://atcoder.jp/contests/abc180/submissions?f.User=SSRS int main() { int N; cin >> N; vector<int> X(N), Y(N), Z(N); for (int i = 0; i < N; i++) { cin >> X[i] >> Y[i] >> Z[i]; } vector<vector<int>> d(N, vector<int>(N)); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { d[i][j] = abs(X[j] - X[i]) + abs(Y[j] - Y[i]) + max(0, Z[j] - Z[i]); } } vector<vector<int>> dp(1 << N, vector<int>(N, INF)); for (int i = 1; i < N; i++) { dp[1 << i][i] = d[0][i]; } for (int i = 1; i < (1 << N); i++) { for (int j = 0; j < N; j++) { if (dp[i][j] != INF) { for (int k = 0; k < N; k++) { if (!(i >> k & 1)) { dp[i + (1 << k)][k] = min(dp[i + (1 << k)][k], dp[i][j] + d[j][k]); } } } } } cout << dp[(1 << N) - 1][0] << endl; }
29.351351
91
0.368324
[ "vector" ]
77c7453441131ed5eb459e7e5e6eefd727876e6c
26,424
cpp
C++
surface/src/on_nurbs/global_optimization_pdm.cpp
yxlao/StanfordPCL
98a8663f896c1ba880d14efa2338b7cfbd01b6ef
[ "MIT" ]
null
null
null
surface/src/on_nurbs/global_optimization_pdm.cpp
yxlao/StanfordPCL
98a8663f896c1ba880d14efa2338b7cfbd01b6ef
[ "MIT" ]
null
null
null
surface/src/on_nurbs/global_optimization_pdm.cpp
yxlao/StanfordPCL
98a8663f896c1ba880d14efa2338b7cfbd01b6ef
[ "MIT" ]
null
null
null
/* * Software License Agreement (BSD License) * * Copyright (c) 2011, Thomas Mörwald * 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 Thomas Mörwald 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @author thomas.moerwald * */ #include <pcl/surface/on_nurbs/global_optimization_pdm.h> #include <pcl/surface/on_nurbs/closing_boundary.h> #include <stdexcept> #undef DEBUG using namespace pcl; using namespace on_nurbs; using namespace Eigen; GlobalOptimization::GlobalOptimization( const std::vector<NurbsDataSurface *> &data, const std::vector<ON_NurbsSurface *> &nurbs) { if (data.empty() || data.size() != nurbs.size()) printf("[GlobalOptimization::GlobalOptimization] Error, data empty or " "size does not match.\n"); m_data = data; m_nurbs = nurbs; im_max_steps = 100; im_accuracy = 1e-5; m_quiet = true; } void GlobalOptimization::setCommonBoundary(const vector_vec3d &boundary, const vector_vec2i &nurbs_indices) { if (boundary.empty() || boundary.size() != nurbs_indices.size()) { printf("[GlobalOptimization::setCommonBoundary] Error, common boundary " "empty or size does not match.\n"); return; } } void GlobalOptimization::assemble(Parameter params) { clock_t time_start, time_end; if (!m_quiet) time_start = clock(); // determine number of rows of matrix m_ncols = 0; unsigned nnurbs = m_nurbs.size(); unsigned nInt(0), nBnd(0), nCageRegInt(0), nCageRegBnd(0), nCommonBnd(0), nCommonPar(0); for (unsigned i = 0; i < nnurbs; i++) { nInt += m_data[i]->interior.size(); nBnd += m_data[i]->boundary.size(); nCommonBnd += m_data[i]->common_boundary_point.size(); nCommonPar += m_data[i]->common_idx.size(); nCageRegInt += (m_nurbs[i]->CVCount(0) - 2) * (m_nurbs[i]->CVCount(1) - 2); nCageRegBnd += 2 * (m_nurbs[i]->CVCount(0) - 1) + 2 * (m_nurbs[i]->CVCount(1) - 1); m_ncols += m_nurbs[i]->CVCount(); } m_nrows = 0; if (params.interior_weight > 0.0) m_nrows += nInt; if (params.boundary_weight > 0.0) m_nrows += nBnd; if (params.interior_smoothness > 0.0) m_nrows += nCageRegInt; if (params.boundary_smoothness > 0.0) m_nrows += nCageRegBnd; if (params.closing_weight > 0.0) { if (params.closing_samples > 0) m_nrows += (4 * params.closing_samples); else m_nrows += nBnd; } if (params.common_weight > 0.0) { m_nrows += nCommonBnd; m_nrows += nCommonPar; } if (!m_quiet) printf("[GlobalOptimization::assemble] Size of matrix: %dx%d\n", m_nrows, m_ncols); m_solver.assign(m_nrows, m_ncols, 3); for (unsigned i = 0; i < m_data.size(); i++) m_data[i]->common_boundary_param.clear(); // assemble matrix unsigned row(0); int ncps(0); // clock_t int_start, int_delta(0); // clock_t bnd_start, bnd_delta(0); // clock_t reg_start, reg_delta(0); // clock_t clo_start, clo_delta(0); // clock_t com_start, com_delta(0); for (unsigned id = 0; id < nnurbs; id++) { // interior points should lie on surface // int_start = clock(); assembleInteriorPoints(id, ncps, params.interior_weight, row); // int_delta += (clock() - int_start); // boundary points should lie on boundary of surface // bnd_start = clock(); assembleBoundaryPoints(id, ncps, params.boundary_weight, row); // bnd_delta += (clock() - bnd_start); // cage regularisation // reg_start = clock(); assembleRegularisation(id, ncps, params.interior_smoothness, params.boundary_smoothness, row); // reg_delta += (clock() - reg_start); // closing boundaries // clo_start = clock(); assembleClosingBoundaries(id, params.closing_samples, params.closing_sigma, params.closing_weight, row); // clo_delta += (clock() - clo_start); // common boundaries // com_start = clock(); assembleCommonBoundaries(id, params.common_weight, row); // com_delta += (clock() - com_start); // common parameter points assembleCommonParams(id, params.common_weight, row); ncps += m_nurbs[id]->CVCount(); } if (!m_quiet) { time_end = clock(); double solve_time = (double)(time_end - time_start) / (double)(CLOCKS_PER_SEC); // printf("[GlobalOptimization::assemble()] int: %f bnd: %f reg: %f // clo: %f com: %f\n", // double(int_delta) / (double) (CLOCKS_PER_SEC), // double(bnd_delta) / (double) (CLOCKS_PER_SEC), // double(reg_delta) / (double) (CLOCKS_PER_SEC), // double(clo_delta) / (double) (CLOCKS_PER_SEC), // double(com_delta) / (double) (CLOCKS_PER_SEC)); // printf("[GlobalOptimization::assemble()] int: %d bnd: %d reg: %d, // %d clo: %d com: %d\n", nInt, nBnd, // nCageRegInt, nCageRegBnd, (4 * params.closing_samples), // nCommonBnd); printf("[GlobalOptimization::assemble()] (nurbs: %d matrix: %d,%d: %f " "sec)\n", nnurbs, m_nrows, m_ncols, solve_time); } } void GlobalOptimization::solve(double damp) { if (m_solver.solve()) updateSurf(damp); } void GlobalOptimization::updateSurf(double damp) { int ncps(0); for (unsigned i = 0; i < m_nurbs.size(); i++) { ON_NurbsSurface *nurbs = m_nurbs[i]; int ncp = nurbs->CVCount(); for (int A = 0; A < ncp; A++) { int I = gl2gr(*nurbs, A); int J = gl2gc(*nurbs, A); ON_3dPoint cp_prev; nurbs->GetCV(I, J, cp_prev); ON_3dPoint cp; cp.x = cp_prev.x + damp * (m_solver.x(ncps + A, 0) - cp_prev.x); cp.y = cp_prev.y + damp * (m_solver.x(ncps + A, 1) - cp_prev.y); cp.z = cp_prev.z + damp * (m_solver.x(ncps + A, 2) - cp_prev.z); nurbs->SetCV(I, J, cp); } ncps += ncp; } } void GlobalOptimization::setInvMapParams(double im_max_steps, double im_accuracy) { this->im_max_steps = im_max_steps; this->im_accuracy = im_accuracy; } void GlobalOptimization::refine(unsigned id, int dim) { std::vector<double> xi; std::vector<double> elements = FittingSurface::getElementVector(*m_nurbs[id], dim); for (unsigned i = 0; i < elements.size() - 1; i++) xi.push_back(elements[i] + 0.5 * (elements[i + 1] - elements[i])); for (unsigned i = 0; i < xi.size(); i++) { m_nurbs[id]->InsertKnot(dim, xi[i], 1); } } void GlobalOptimization::assembleCommonParams(unsigned id1, double weight, unsigned &row) { if (weight <= 0.0) return; NurbsDataSurface *data = m_data[id1]; for (size_t i = 0; i < data->common_idx.size(); i++) addParamConstraint(Eigen::Vector2i(id1, data->common_idx[i]), data->common_param1[i], data->common_param2[i], weight, row); } void GlobalOptimization::assembleCommonBoundaries(unsigned id1, double weight, unsigned &row) { if (weight <= 0.0) return; // double ds = 1.0 / (2.0 * sigma * sigma); NurbsDataSurface *data1 = m_data[id1]; ON_NurbsSurface *nurbs1 = m_nurbs[id1]; if (nurbs1->Order(0) != nurbs1->Order(1)) printf("[GlobalOptimization::assembleCommonBoundaries] Warning, order " "in u and v direction differ (nurbs1).\n"); for (unsigned i = 0; i < data1->common_boundary_point.size(); i++) { Eigen::Vector3d p1, tu1, tv1, p2, tu2, tv2, t1, t2; Eigen::Vector2d params1, params2; double error1, error2; Eigen::Vector3d p0 = data1->common_boundary_point[i]; Eigen::Vector2i id(id1, data1->common_boundary_idx[i]); if (id(1) < 0 || id(1) >= m_nurbs.size()) throw std::runtime_error( "[GlobalOptimization::assembleCommonBoundaries] Error, common " "boundary index out of bounds.\n"); ON_NurbsSurface *nurbs2 = m_nurbs[id(1)]; double w(1.0); if (nurbs2->Order(0) != nurbs2->Order(1)) printf("[GlobalOptimization::assembleCommonBoundaries] Warning, " "order in u and v direction differ (nurbs2).\n"); if (nurbs1->Order(0) == nurbs2->Order(0)) { params1 = FittingSurface::inverseMappingBoundary( *m_nurbs[id(0)], p0, error1, p1, tu1, tv1, im_max_steps, im_accuracy, true); params2 = FittingSurface::inverseMappingBoundary( *m_nurbs[id(1)], p0, error2, p2, tu2, tv2, im_max_steps, im_accuracy, true); if (params1(0) == 0.0 || params1(0) == 1.0) t1 = tv1; if (params1(1) == 0.0 || params1(1) == 1.0) t1 = tu1; if (params2(0) == 0.0 || params2(0) == 1.0) t2 = tv2; if (params2(1) == 0.0 || params2(1) == 1.0) t2 = tu2; t1.normalize(); t2.normalize(); // weight according to parallel-ness of boundaries w = t1.dot(t2); if (w < 0.0) w = -w; } else { if (nurbs1->Order(0) < nurbs2->Order(0)) { params1 = FittingSurface::findClosestElementMidPoint( *m_nurbs[id(0)], p0); params1 = FittingSurface::inverseMapping( *m_nurbs[id(0)], p0, params1, error1, p1, tu1, tv1, im_max_steps, im_accuracy, true); params2 = FittingSurface::inverseMappingBoundary( *m_nurbs[id(1)], p0, error2, p2, tu2, tv2, im_max_steps, im_accuracy, true); } else { params1 = FittingSurface::inverseMappingBoundary( *m_nurbs[id(0)], p0, error1, p1, tu1, tv1, im_max_steps, im_accuracy, true); params2 = FittingSurface::findClosestElementMidPoint( *m_nurbs[id(1)], p0); params2 = FittingSurface::inverseMapping( *m_nurbs[id(1)], p0, params2, error2, p2, tu2, tv2, im_max_steps, im_accuracy); } } m_data[id(0)]->common_boundary_param.push_back(params1); m_data[id(1)]->common_boundary_param.push_back(params2); // double error = (p1-p2).norm(); // double w = weight * exp(-(error * error) * ds); addParamConstraint(id, params1, params2, weight * w, row); } } void GlobalOptimization::assembleClosingBoundaries(unsigned id, unsigned samples, double sigma, double weight, unsigned &row) { if (weight <= 0.0 || samples <= 0 || sigma < 0.0) return; double ds = 1.0 / (2.0 * sigma * sigma); ON_NurbsSurface *nurbs1 = m_nurbs[id]; // sample point list from nurbs1 vector_vec3d boundary1, boundary2; vector_vec2d params1, params2; ClosingBoundary::sampleFromBoundary(nurbs1, boundary1, params1, samples); // for each other nurbs for (unsigned n2 = (id + 1); n2 < m_nurbs.size(); n2++) { ON_NurbsSurface *nurbs2 = m_nurbs[n2]; // find closest point to boundary for (unsigned i = 0; i < boundary1.size(); i++) { double error; Eigen::Vector3d p, tu, tv; Eigen::Vector2d params; Eigen::Vector3d p0 = boundary1[i]; params = FittingSurface::inverseMappingBoundary( *nurbs2, p0, error, p, tu, tv, im_max_steps, im_accuracy, true); boundary2.push_back(p); params2.push_back(params); // double dist = (p - p0).norm(); // if (error < max_error && dist < max_dist) { double w = weight * exp(-(error * error) * ds); addParamConstraint(Eigen::Vector2i(id, n2), params1[i], params, w, row); // } } } } void GlobalOptimization::assembleInteriorPoints(unsigned id, int ncps, double weight, unsigned &row) { if (weight <= 0.0) return; ON_NurbsSurface *nurbs = m_nurbs[id]; NurbsDataSurface *data = m_data[id]; unsigned nInt = m_data[id]->interior.size(); // interior points should lie on surface data->interior_line_start.clear(); data->interior_line_end.clear(); data->interior_error.clear(); data->interior_normals.clear(); // data->interior_param.clear(); for (unsigned p = 0; p < nInt; p++) { Vector3d pcp; pcp(0) = data->interior[p](0); pcp(1) = data->interior[p](1); pcp(2) = data->interior[p](2); // inverse mapping Vector2d params; Vector3d pt, tu, tv, n; double error; if (p < data->interior_param.size()) { params = FittingSurface::inverseMapping( *nurbs, pcp, data->interior_param[p], error, pt, tu, tv, im_max_steps, im_accuracy); data->interior_param[p] = params; } else { params = FittingSurface::findClosestElementMidPoint(*nurbs, pcp); params = FittingSurface::inverseMapping(*nurbs, pcp, params, error, pt, tu, tv, im_max_steps, im_accuracy); data->interior_param.push_back(params); } data->interior_error.push_back(error); n = tu.cross(tv); n.normalize(); data->interior_normals.push_back(n); data->interior_line_start.push_back(pcp); data->interior_line_end.push_back(pt); addPointConstraint(id, ncps, params, pcp, weight, row); } } void GlobalOptimization::assembleBoundaryPoints(unsigned id, int ncps, double weight, unsigned &row) { if (weight <= 0.0) return; ON_NurbsSurface *nurbs = m_nurbs[id]; NurbsDataSurface *data = m_data[id]; unsigned nBnd = m_data[id]->boundary.size(); // interior points should lie on surface data->boundary_line_start.clear(); data->boundary_line_end.clear(); data->boundary_error.clear(); data->boundary_normals.clear(); data->boundary_param.clear(); for (unsigned p = 0; p < nBnd; p++) { Vector3d pcp; pcp(0) = data->boundary[p](0); pcp(1) = data->boundary[p](1); pcp(2) = data->boundary[p](2); // inverse mapping Vector3d pt, tu, tv, n; double error; Vector2d params = FittingSurface::inverseMappingBoundary( *nurbs, pcp, error, pt, tu, tv, im_max_steps, im_accuracy); data->boundary_error.push_back(error); if (p < data->boundary_param.size()) { data->boundary_param[p] = params; } else { data->boundary_param.push_back(params); } n = tu.cross(tv); n.normalize(); data->boundary_normals.push_back(n); data->boundary_line_start.push_back(pcp); data->boundary_line_end.push_back(pt); addPointConstraint(id, ncps, params, pcp, weight, row); } } void GlobalOptimization::assembleRegularisation(unsigned id, int ncps, double wCageRegInt, double wCageRegBnd, unsigned &row) { if (wCageRegBnd <= 0.0 || wCageRegInt <= 0.0) { printf("[GlobalOptimization::assembleRegularisation] Warning, no " "regularisation may lead " "to under-determined equation system. Add cage regularisation " "(smoothing) to avoid.\n"); } if (wCageRegInt > 0.0) addCageInteriorRegularisation(id, ncps, wCageRegInt, row); if (wCageRegBnd > 0.0) { addCageBoundaryRegularisation(id, ncps, wCageRegBnd, NORTH, row); addCageBoundaryRegularisation(id, ncps, wCageRegBnd, SOUTH, row); addCageBoundaryRegularisation(id, ncps, wCageRegBnd, WEST, row); addCageBoundaryRegularisation(id, ncps, wCageRegBnd, EAST, row); addCageCornerRegularisation(id, ncps, wCageRegBnd * 2.0, row); } } void GlobalOptimization::addParamConstraint(const Eigen::Vector2i &id, const Eigen::Vector2d &params1, const Eigen::Vector2d &params2, double weight, unsigned &row) { vector_vec2d params; params.push_back(params1); params.push_back(params2); for (unsigned n = 0; n < 2; n++) { ON_NurbsSurface *nurbs = m_nurbs[id(n)]; double N0[nurbs->Order(0) * nurbs->Order(0)]; double N1[nurbs->Order(1) * nurbs->Order(1)]; int E = ON_NurbsSpanIndex(nurbs->Order(0), nurbs->CVCount(0), nurbs->m_knot[0], params[n](0), 0, 0); int F = ON_NurbsSpanIndex(nurbs->Order(1), nurbs->CVCount(1), nurbs->m_knot[1], params[n](1), 0, 0); // int E = ntools.E(params[n](0)); // int F = ntools.F(params[n](1)); m_solver.f(row, 0, 0.0); m_solver.f(row, 1, 0.0); m_solver.f(row, 2, 0.0); int ncps(0); for (int i = 0; i < id(n); i++) ncps += m_nurbs[i]->CVCount(); ON_EvaluateNurbsBasis(nurbs->Order(0), nurbs->m_knot[0] + E, params[n](0), N0); ON_EvaluateNurbsBasis(nurbs->Order(1), nurbs->m_knot[1] + F, params[n](1), N1); double s(1.0); n == 0 ? s = 1.0 : s = -1.0; for (int i = 0; i < nurbs->Order(0); i++) { for (int j = 0; j < nurbs->Order(1); j++) { m_solver.K(row, ncps + lrc2gl(*nurbs, E, F, i, j), weight * N0[i] * N1[j] * s); } // j } // i } row++; // if (!m_quiet) // printf ("[GlobalOptimization::addParamConstraint] row: %d / %d\n", // row, m_nrows); } void GlobalOptimization::addPointConstraint(unsigned id, int ncps, const Eigen::Vector2d &params, const Eigen::Vector3d &point, double weight, unsigned &row) { ON_NurbsSurface *nurbs = m_nurbs[id]; double N0[nurbs->Order(0) * nurbs->Order(0)]; double N1[nurbs->Order(1) * nurbs->Order(1)]; int E = ON_NurbsSpanIndex(nurbs->Order(0), nurbs->CVCount(0), nurbs->m_knot[0], params(0), 0, 0); int F = ON_NurbsSpanIndex(nurbs->Order(1), nurbs->CVCount(1), nurbs->m_knot[1], params(1), 0, 0); ON_EvaluateNurbsBasis(nurbs->Order(0), nurbs->m_knot[0] + E, params(0), N0); ON_EvaluateNurbsBasis(nurbs->Order(1), nurbs->m_knot[1] + F, params(1), N1); m_solver.f(row, 0, point(0) * weight); m_solver.f(row, 1, point(1) * weight); m_solver.f(row, 2, point(2) * weight); for (int i = 0; i < nurbs->Order(0); i++) { for (int j = 0; j < nurbs->Order(1); j++) { m_solver.K(row, ncps + lrc2gl(*nurbs, E, F, i, j), weight * N0[i] * N1[j]); } // j } // i row++; // if (!m_quiet && !(row % 100)) // printf("[GlobalOptimization::addPointConstraint] row: %d / %d\n", row, // m_nrows); } void GlobalOptimization::addCageInteriorRegularisation(unsigned id, int ncps, double weight, unsigned &row) { ON_NurbsSurface *nurbs = m_nurbs[id]; for (int i = 1; i < (nurbs->CVCount(0) - 1); i++) { for (int j = 1; j < (nurbs->CVCount(1) - 1); j++) { m_solver.f(row, 0, 0.0); m_solver.f(row, 1, 0.0); m_solver.f(row, 2, 0.0); m_solver.K(row, ncps + grc2gl(*nurbs, i + 0, j + 0), -4.0 * weight); m_solver.K(row, ncps + grc2gl(*nurbs, i + 0, j - 1), 1.0 * weight); m_solver.K(row, ncps + grc2gl(*nurbs, i + 0, j + 1), 1.0 * weight); m_solver.K(row, ncps + grc2gl(*nurbs, i - 1, j + 0), 1.0 * weight); m_solver.K(row, ncps + grc2gl(*nurbs, i + 1, j + 0), 1.0 * weight); row++; } } // if (!m_quiet && !(row % 100)) // printf("[GlobalOptimization::addCageInteriorRegularisation] row: %d / // %d\n", row, m_nrows); } void GlobalOptimization::addCageBoundaryRegularisation(unsigned id, int ncps, double weight, int side, unsigned &row) { ON_NurbsSurface *nurbs = m_nurbs[id]; int i = 0; int j = 0; switch (side) { case SOUTH: j = nurbs->CVCount(1) - 1; case NORTH: for (i = 1; i < (nurbs->CVCount(0) - 1); i++) { m_solver.f(row, 0, 0.0); m_solver.f(row, 1, 0.0); m_solver.f(row, 2, 0.0); m_solver.K(row, ncps + grc2gl(*nurbs, i + 0, j), -2.0 * weight); m_solver.K(row, ncps + grc2gl(*nurbs, i - 1, j), 1.0 * weight); m_solver.K(row, ncps + grc2gl(*nurbs, i + 1, j), 1.0 * weight); row++; } break; case EAST: i = nurbs->CVCount(0) - 1; case WEST: for (j = 1; j < (nurbs->CVCount(1) - 1); j++) { m_solver.f(row, 0, 0.0); m_solver.f(row, 1, 0.0); m_solver.f(row, 2, 0.0); m_solver.K(row, ncps + grc2gl(*nurbs, i, j + 0), -2.0 * weight); m_solver.K(row, ncps + grc2gl(*nurbs, i, j - 1), 1.0 * weight); m_solver.K(row, ncps + grc2gl(*nurbs, i, j + 1), 1.0 * weight); row++; } break; } // if (!m_quiet && !(row % 100)) // printf("[GlobalOptimization::addCageBoundaryRegularisation] row: %d / // %d\n", row, m_nrows); } void GlobalOptimization::addCageCornerRegularisation(unsigned id, int ncps, double weight, unsigned &row) { ON_NurbsSurface *nurbs = m_nurbs[id]; { // NORTH-WEST int i = 0; int j = 0; m_solver.f(row, 0, 0.0); m_solver.f(row, 1, 0.0); m_solver.f(row, 2, 0.0); m_solver.K(row, ncps + grc2gl(*nurbs, i + 0, j + 0), -2.0 * weight); m_solver.K(row, ncps + grc2gl(*nurbs, i + 1, j + 0), 1.0 * weight); m_solver.K(row, ncps + grc2gl(*nurbs, i + 0, j + 1), 1.0 * weight); row++; } { // NORTH-EAST int i = nurbs->CVCount(0) - 1; int j = 0; m_solver.f(row, 0, 0.0); m_solver.f(row, 1, 0.0); m_solver.f(row, 2, 0.0); m_solver.K(row, ncps + grc2gl(*nurbs, i + 0, j + 0), -2.0 * weight); m_solver.K(row, ncps + grc2gl(*nurbs, i - 1, j + 0), 1.0 * weight); m_solver.K(row, ncps + grc2gl(*nurbs, i + 0, j + 1), 1.0 * weight); row++; } { // SOUTH-EAST int i = nurbs->CVCount(0) - 1; int j = nurbs->CVCount(1) - 1; m_solver.f(row, 0, 0.0); m_solver.f(row, 1, 0.0); m_solver.f(row, 2, 0.0); m_solver.K(row, ncps + grc2gl(*nurbs, i + 0, j + 0), -2.0 * weight); m_solver.K(row, ncps + grc2gl(*nurbs, i - 1, j + 0), 1.0 * weight); m_solver.K(row, ncps + grc2gl(*nurbs, i + 0, j - 1), 1.0 * weight); row++; } { // SOUTH-WEST int i = 0; int j = nurbs->CVCount(1) - 1; m_solver.f(row, 0, 0.0); m_solver.f(row, 1, 0.0); m_solver.f(row, 2, 0.0); m_solver.K(row, ncps + grc2gl(*nurbs, i + 0, j + 0), -2.0 * weight); m_solver.K(row, ncps + grc2gl(*nurbs, i + 1, j + 0), 1.0 * weight); m_solver.K(row, ncps + grc2gl(*nurbs, i + 0, j - 1), 1.0 * weight); row++; } // if (!m_quiet && !(row % 100)) // printf("[GlobalOptimization::addCageCornerRegularisation] row: %d / // %d\n", row, m_nrows); }
35.516129
80
0.535725
[ "vector" ]
77d8f7372a359a5975d7d8edb969fb1a1d5554cb
4,601
hpp
C++
include/utils/SharedTable.hpp
sroycode/zapdos
8818ef109e072dcbe990914d9a2a6d70ef190d3e
[ "MIT" ]
5
2018-11-11T21:09:30.000Z
2020-06-25T12:46:41.000Z
include/utils/SharedTable.hpp
vnaad/zapdos
8818ef109e072dcbe990914d9a2a6d70ef190d3e
[ "MIT" ]
1
2020-08-02T09:12:57.000Z
2020-08-02T09:12:57.000Z
include/utils/SharedTable.hpp
vnaad/zapdos
8818ef109e072dcbe990914d9a2a6d70ef190d3e
[ "MIT" ]
null
null
null
/** * @project zapdos * @file include/utils/SharedTable.hpp * @author S Roychowdhury < sroycode at gmail dot com > * @version 1.0.0 * * @section LICENSE * * Copyright (c) 2018-2020 S Roychowdhury * * 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. * * @section DESCRIPTION * * SharedTable.hpp : Shared Table of system data Headers * */ #ifndef _ZPDS_UTILS_SHAREDTABLE_HPP_ #define _ZPDS_UTILS_SHAREDTABLE_HPP_ #include <memory> #include <vector> #include <random> #include <boost/asio.hpp> #include "http/AsioCompat.hpp" #include "utils/SharedCounter.hpp" #include "utils/SharedPairMap.hpp" #include "utils/SharedMap.hpp" // #include "utils/SharedQueue.hpp" #include "store/StoreLevel.hpp" #include "store/CacheContainer.hpp" #ifdef ZPDS_BUILD_WITH_XAPIAN #include "search/WriteIndex.hpp" #include "jamspell/StoreJam.hpp" #endif #include "crypto/CryptoBase.hpp" namespace zpds { namespace utils { class SharedTable : public std::enable_shared_from_this<SharedTable> { public: using pointer=std::shared_ptr<SharedTable>; using dbpointer=zpds::store::StoreLevel::dbpointer; using SharedString = SharedObject<std::string>; using SharedUnsigned = SharedObject<uint64_t>; using SharedDBPointer = SharedObject<dbpointer>; using SharedBool = SharedObject<bool>; // using JobQueue = SharedQueue<std::string>; using SharedRemote = SharedPairMap<std::string,uint64_t,uint64_t>; using RemoteMapT = SharedPairMap<std::string,uint64_t,uint64_t>::PairMapT; using SharedTrans = SharedMap<uint64_t,std::string>; using SharedCache = zpds::store::CacheContainer::pointer; #ifdef ZPDS_BUILD_WITH_XAPIAN using SharedXap = zpds::search::WriteIndex::pointer; using SharedJam = zpds::jamspell::StoreJam::pointer; #endif using KeyRingT = std::unordered_map<std::string,std::shared_ptr<zpds::crypto::CryptoBase> >; // using LockT = boost::shared_mutex; // io_whatever std::shared_ptr<::zpds::http::io_whatever> io_whatever; // map of shared followers SharedRemote remotes; // map of shared transactions SharedTrans transactions; // string shared SharedString master; SharedString shared_secret; SharedString hostname; SharedString thisurl; SharedString lastslave; // keyring KeyRingT keyring; #ifdef ZPDS_BUILD_WITH_XAPIAN // xapian SharedString xapath; SharedXap xapdb; // spellcheck SharedJam jamdb; // xapian dont use SharedBool no_xapian; #endif // counter shared SharedCounter maincounter; SharedCounter logcounter; // database pointers SharedDBPointer maindb; SharedDBPointer logdb; // cache pointers SharedCache dbcache; SharedCache tmpcache; // booleans SharedBool is_master; SharedBool is_ready; SharedBool force_commit; SharedBool lock_updates; // shared SharedUnsigned max_fetch_records; SharedUnsigned max_user_sessions; // queue // JobQueue jobqueue; /** * make noncopyable */ SharedTable(const SharedTable&) = delete; SharedTable& operator=(const SharedTable&) = delete; /** * create : static construction creates new first time * * @return * pointer */ static pointer create() { return pointer{new SharedTable}; } /** * share : return instance * * @return * pointer */ pointer share() { return shared_from_this(); } /** * destructor */ virtual ~SharedTable () {} private: /** * Constructor : default private * * @return * none */ SharedTable() : dbcache(zpds::store::CacheContainer::create()), tmpcache(zpds::store::CacheContainer::create()) {} }; } // namespace utils } // namespace zpds #endif /* _ZPDS_UTILS_SHAREDTABLE_HPP_ */
23.237374
93
0.745925
[ "vector" ]
77daa29b596f7dde7564e97284a86a17446dbbdc
5,794
cpp
C++
src/molecular-graph.cpp
puls-group/percolation-analyzer
df8d0905109db922f38c6bb4dab5da27ceb787d9
[ "MIT" ]
null
null
null
src/molecular-graph.cpp
puls-group/percolation-analyzer
df8d0905109db922f38c6bb4dab5da27ceb787d9
[ "MIT" ]
null
null
null
src/molecular-graph.cpp
puls-group/percolation-analyzer
df8d0905109db922f38c6bb4dab5da27ceb787d9
[ "MIT" ]
1
2021-09-09T19:40:48.000Z
2021-09-09T19:40:48.000Z
/* * SPDX-FileCopyrightText: 2020 Kevin Höllring for PULS Group <kevin.hoellring@fau.de> * * SPDX-License-Identifier: MIT * * Copyright (c) 2020 Kevin Höllring for PULS Group <kevin.hoellring@fau.de> * * Authors: 2020 Kevin Höllring <kevin.hoellring@fau.de> * * 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 (including the next paragraph) * 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 "molecular-graph.hpp" namespace mol { MolecularGraph::MolecularGraph() : MolecularGraph(0) {} MolecularGraph::MolecularGraph(size_t num_atoms) { this->set_atom_count(num_atoms); } void MolecularGraph::set_atom_count(size_t num_atoms) { this->atom_positions.resize(num_atoms); this->bonds.resize(num_atoms); n_atoms = num_atoms; } bool MolecularGraph::set_basis(const std::vector<vec<graph_precision_type>> &triclinic_basis) { if (triclinic_basis[0][1] != 0.0 || triclinic_basis[0][2] != 0.0 || triclinic_basis[1][2] != 0.0 || triclinic_basis[0][0] == 0.0 || triclinic_basis[1][1] == 0.0 || triclinic_basis[2][2] == 0.0) { // Basis does not have triclinic properties return false; } this->triclinic_basis = triclinic_basis; return true; } bool MolecularGraph::set_atom_position(size_t atom_index, const vec<graph_precision_type> &pos) { if (atom_index >= n_atoms) { return false; } this->atom_positions[atom_index] = pos; return true; } bool MolecularGraph::add_bond(size_t atom_index_1, size_t atom_index_2) { if (atom_index_1 >= n_atoms || atom_index_2 >= n_atoms) { return false; } bonds[atom_index_1].push_back(atom_index_2); bonds[atom_index_2].push_back(atom_index_1); return true; } percolation::PercolationGraph MolecularGraph::get_percolation_graph() const { percolation::PercolationGraph res; // Resize the percolation graph appropriately res.reserve_vertices(n_atoms); // Transform all positions into normalized basis components // This is equivalent to moving them all into one pbc cell and transforming the coordinates // into cuboid shape, which makes everything simpler. std::vector<vec<graph_precision_type>> normalized_positions(n_atoms); for (size_t base = 0; base < n_atoms; base++) { normalized_positions[base] = normalize_basis_coefficients(decompose(atom_positions[base], triclinic_basis)); } // Parse the edges to be added: for (size_t base = 0; base < n_atoms; base++) { const vec<graph_precision_type> &b_pos = normalized_positions[base]; for (size_t n = 0; n < bonds[base].size(); n++) { size_t head = bonds[base][n]; if (head < base) { // Both directions of the edge were created, we only need to consider one. continue; } const vec<graph_precision_type> &h_pos = normalized_positions[head]; // Let us build the correct translation vector percolation::TranslationVector trans; for (size_t dim = 0; dim < vector_space_dimension; dim++) { if (b_pos[dim] < h_pos[dim]) { // The base lies below the head in the cell if (h_pos[dim] - b_pos[dim] > 0.5) { // The shorter connection intersects the cell boundary going down from the base trans[dim] = -1; } else { // The connection is within the cell trans[dim] = 0; } } else { // Need to check edge crossing the other way around // The base lies below the head in the cell if (b_pos[dim] - h_pos[dim] > 0.5) { // The shorter connection intersects the cell boundary going up from the base trans[dim] = +1; } else { // The connection is within the cell trans[dim] = 0; } } } res.add_edge(base, head, trans); } } return res; } }
38.370861
201
0.566793
[ "shape", "vector", "transform" ]
77e6924d329f7b115ceb67595ca03639e0f68cad
1,278
cpp
C++
Level 5/Arbres binaires/Maintenir un tableau avec modifications sur intervalles/main.cpp
Wurlosh/France-ioi
f5fb36003cbfc56a2e7cf64ad43c4452f086f198
[ "MIT" ]
31
2018-10-30T09:54:23.000Z
2022-03-02T21:45:51.000Z
Level 5/Arbres binaires/Maintenir un tableau avec modifications sur intervalles/main.cpp
Wurlosh/France-ioi
f5fb36003cbfc56a2e7cf64ad43c4452f086f198
[ "MIT" ]
2
2016-12-24T23:39:20.000Z
2017-07-02T22:51:28.000Z
Level 5/Arbres binaires/Maintenir un tableau avec modifications sur intervalles/main.cpp
Wurlosh/France-ioi
f5fb36003cbfc56a2e7cf64ad43c4452f086f198
[ "MIT" ]
30
2018-10-25T12:28:36.000Z
2022-01-31T14:31:02.000Z
#include <iostream> #define N (1<<18) using namespace std; //int find(vector <int>& C, int x){return (C[x]==x) ? x : C[x]=find(C, C[x]);} //C++ //int find(int x){return (C[x]==x)?x:C[x]=find(C[x]);} typedef pair<int,int> ii; ii arb[N]={{0,0}}; int n,m,a,b,v; char type; void update(int node,int l,int r,int a,int b,int val,int p) { if(a<=l && r<=b) { arb[node].first=val; arb[node].second=p; } else { int mid=(l+r)/2; if(a<=mid) update(node*2,l,mid,a,b,val,p); if(b>mid) update(2*node+1,mid+1,r,a,b,val,p); } } pair<int,int> search(int node,int l,int r,int a) { if(a==l && a==r) { return arb[node]; } else { int mid=(l+r)/2; ii cur; if(a<=mid) cur=search(2*node,l,mid,a); else cur=search(2*node+1,mid+1,r,a); if(cur.second<arb[node].second) return arb[node]; else return cur; } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin>>n; n=(1<<n); cin>>m; int p=0; for(int i=0;i<m;++i) { cin>>type; if(type=='M') { cin>>a>>b>>v; update(1,1,n,a+1,b+1,v,++p); } else if(type=='V') { cin>>a; cout<<search(1,1,n,a+1).first<<"\n"; } } return 0; }
17.04
84
0.482786
[ "vector" ]
77ea9a5d2a7f215e9dbbe1d1a1dd7227093f0d25
715
cpp
C++
src/core/cpp/object/GenericObject.cpp
NeroGames/Nero-Game-Engine
8543b8bb142738aa28bc20e929b342d3e6df066e
[ "MIT" ]
26
2020-09-02T18:14:36.000Z
2022-02-08T18:28:36.000Z
src/core/cpp/object/GenericObject.cpp
sk-landry/Nero-Game-Engine
8543b8bb142738aa28bc20e929b342d3e6df066e
[ "MIT" ]
14
2020-08-30T01:37:04.000Z
2021-07-19T20:47:29.000Z
src/core/cpp/object/GenericObject.cpp
sk-landry/Nero-Game-Engine
8543b8bb142738aa28bc20e929b342d3e6df066e
[ "MIT" ]
6
2020-09-02T18:14:57.000Z
2021-12-31T00:32:09.000Z
//////////////////////////////////////////////////////////// // Nero Game Engine // Copyright (c) 2016-2020 Sanou A. K. Landry ///////////////////////////////////////////////////////////// ///////////////////////////HEADERS/////////////////////////// //NERO #include <Nero/core/cpp/object/GameObject.h> ///////////////////////////////////////////////////////////// namespace nero { GenericObject::GenericObject() { } GenericObject::~GenericObject() { destroyObject(); } void GenericObject::destroyObject() { //m_Parent simply refers to the parent, it does not hold the parent, therefore we do not call delete(m_Parent) m_Parent = nullptr; } }
26.481481
119
0.420979
[ "object" ]
77f47f7075d241e4d1898fadb3e0bb0b2fa4d26f
118,080
cc
C++
samplecode/remoteattestation/GoogleMessages/Messages.pb.cc
nightmared/incubator-teaclave-sgx-sdk
1a30d2f8389e78cad71cf30e4e7d6c342f8cd280
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
null
null
null
samplecode/remoteattestation/GoogleMessages/Messages.pb.cc
nightmared/incubator-teaclave-sgx-sdk
1a30d2f8389e78cad71cf30e4e7d6c342f8cd280
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
null
null
null
samplecode/remoteattestation/GoogleMessages/Messages.pb.cc
nightmared/incubator-teaclave-sgx-sdk
1a30d2f8389e78cad71cf30e4e7d6c342f8cd280
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
null
null
null
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: Messages.proto #include "Messages.pb.h" #include <algorithm> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/wire_format_lite.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> namespace Messages { class InitialMessageDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<InitialMessage> _instance; } _InitialMessage_default_instance_; class MessageMsg0DefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<MessageMsg0> _instance; } _MessageMsg0_default_instance_; class MessageMSG1DefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<MessageMSG1> _instance; } _MessageMSG1_default_instance_; class MessageMSG2DefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<MessageMSG2> _instance; } _MessageMSG2_default_instance_; class MessageMSG3DefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<MessageMSG3> _instance; } _MessageMSG3_default_instance_; class AttestationMessageDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<AttestationMessage> _instance; } _AttestationMessage_default_instance_; } // namespace Messages static void InitDefaultsscc_info_AttestationMessage_Messages_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::Messages::_AttestationMessage_default_instance_; new (ptr) ::Messages::AttestationMessage(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_AttestationMessage_Messages_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_AttestationMessage_Messages_2eproto}, {}}; static void InitDefaultsscc_info_InitialMessage_Messages_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::Messages::_InitialMessage_default_instance_; new (ptr) ::Messages::InitialMessage(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_InitialMessage_Messages_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_InitialMessage_Messages_2eproto}, {}}; static void InitDefaultsscc_info_MessageMSG1_Messages_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::Messages::_MessageMSG1_default_instance_; new (ptr) ::Messages::MessageMSG1(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_MessageMSG1_Messages_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_MessageMSG1_Messages_2eproto}, {}}; static void InitDefaultsscc_info_MessageMSG2_Messages_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::Messages::_MessageMSG2_default_instance_; new (ptr) ::Messages::MessageMSG2(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_MessageMSG2_Messages_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_MessageMSG2_Messages_2eproto}, {}}; static void InitDefaultsscc_info_MessageMSG3_Messages_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::Messages::_MessageMSG3_default_instance_; new (ptr) ::Messages::MessageMSG3(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_MessageMSG3_Messages_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_MessageMSG3_Messages_2eproto}, {}}; static void InitDefaultsscc_info_MessageMsg0_Messages_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::Messages::_MessageMsg0_default_instance_; new (ptr) ::Messages::MessageMsg0(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_MessageMsg0_Messages_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_MessageMsg0_Messages_2eproto}, {}}; static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_Messages_2eproto[6]; static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_Messages_2eproto = nullptr; static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_Messages_2eproto = nullptr; const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_Messages_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { PROTOBUF_FIELD_OFFSET(::Messages::InitialMessage, _has_bits_), PROTOBUF_FIELD_OFFSET(::Messages::InitialMessage, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::Messages::InitialMessage, type_), PROTOBUF_FIELD_OFFSET(::Messages::InitialMessage, size_), 0, 1, PROTOBUF_FIELD_OFFSET(::Messages::MessageMsg0, _has_bits_), PROTOBUF_FIELD_OFFSET(::Messages::MessageMsg0, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::Messages::MessageMsg0, type_), PROTOBUF_FIELD_OFFSET(::Messages::MessageMsg0, epid_), PROTOBUF_FIELD_OFFSET(::Messages::MessageMsg0, status_), 0, 1, 2, PROTOBUF_FIELD_OFFSET(::Messages::MessageMSG1, _has_bits_), PROTOBUF_FIELD_OFFSET(::Messages::MessageMSG1, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::Messages::MessageMSG1, type_), PROTOBUF_FIELD_OFFSET(::Messages::MessageMSG1, gax_), PROTOBUF_FIELD_OFFSET(::Messages::MessageMSG1, gay_), PROTOBUF_FIELD_OFFSET(::Messages::MessageMSG1, gid_), 0, ~0u, ~0u, ~0u, PROTOBUF_FIELD_OFFSET(::Messages::MessageMSG2, _has_bits_), PROTOBUF_FIELD_OFFSET(::Messages::MessageMSG2, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::Messages::MessageMSG2, type_), PROTOBUF_FIELD_OFFSET(::Messages::MessageMSG2, size_), PROTOBUF_FIELD_OFFSET(::Messages::MessageMSG2, public_key_gx_), PROTOBUF_FIELD_OFFSET(::Messages::MessageMSG2, public_key_gy_), PROTOBUF_FIELD_OFFSET(::Messages::MessageMSG2, quote_type_), PROTOBUF_FIELD_OFFSET(::Messages::MessageMSG2, spid_), PROTOBUF_FIELD_OFFSET(::Messages::MessageMSG2, cmac_kdf_id_), PROTOBUF_FIELD_OFFSET(::Messages::MessageMSG2, signature_x_), PROTOBUF_FIELD_OFFSET(::Messages::MessageMSG2, signature_y_), PROTOBUF_FIELD_OFFSET(::Messages::MessageMSG2, smac_), PROTOBUF_FIELD_OFFSET(::Messages::MessageMSG2, size_sigrl_), PROTOBUF_FIELD_OFFSET(::Messages::MessageMSG2, sigrl_), 0, 1, ~0u, ~0u, 2, ~0u, 3, ~0u, ~0u, ~0u, 4, ~0u, PROTOBUF_FIELD_OFFSET(::Messages::MessageMSG3, _has_bits_), PROTOBUF_FIELD_OFFSET(::Messages::MessageMSG3, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::Messages::MessageMSG3, type_), PROTOBUF_FIELD_OFFSET(::Messages::MessageMSG3, size_), PROTOBUF_FIELD_OFFSET(::Messages::MessageMSG3, sgx_mac_), PROTOBUF_FIELD_OFFSET(::Messages::MessageMSG3, gax_msg3_), PROTOBUF_FIELD_OFFSET(::Messages::MessageMSG3, gay_msg3_), PROTOBUF_FIELD_OFFSET(::Messages::MessageMSG3, sec_property_), PROTOBUF_FIELD_OFFSET(::Messages::MessageMSG3, quote_), 0, 1, ~0u, ~0u, ~0u, ~0u, ~0u, PROTOBUF_FIELD_OFFSET(::Messages::AttestationMessage, _has_bits_), PROTOBUF_FIELD_OFFSET(::Messages::AttestationMessage, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::Messages::AttestationMessage, type_), PROTOBUF_FIELD_OFFSET(::Messages::AttestationMessage, size_), PROTOBUF_FIELD_OFFSET(::Messages::AttestationMessage, epid_group_status_), PROTOBUF_FIELD_OFFSET(::Messages::AttestationMessage, tcb_evaluation_status_), PROTOBUF_FIELD_OFFSET(::Messages::AttestationMessage, pse_evaluation_status_), PROTOBUF_FIELD_OFFSET(::Messages::AttestationMessage, latest_equivalent_tcb_psvn_), PROTOBUF_FIELD_OFFSET(::Messages::AttestationMessage, latest_pse_isvsvn_), PROTOBUF_FIELD_OFFSET(::Messages::AttestationMessage, latest_psda_svn_), PROTOBUF_FIELD_OFFSET(::Messages::AttestationMessage, performance_rekey_gid_), PROTOBUF_FIELD_OFFSET(::Messages::AttestationMessage, ec_sign256_x_), PROTOBUF_FIELD_OFFSET(::Messages::AttestationMessage, ec_sign256_y_), PROTOBUF_FIELD_OFFSET(::Messages::AttestationMessage, mac_smk_), PROTOBUF_FIELD_OFFSET(::Messages::AttestationMessage, result_size_), PROTOBUF_FIELD_OFFSET(::Messages::AttestationMessage, reserved_), PROTOBUF_FIELD_OFFSET(::Messages::AttestationMessage, payload_tag_), PROTOBUF_FIELD_OFFSET(::Messages::AttestationMessage, payload_), 0, 1, 2, 3, 4, ~0u, ~0u, ~0u, ~0u, ~0u, ~0u, ~0u, 5, ~0u, ~0u, ~0u, }; static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, 7, sizeof(::Messages::InitialMessage)}, { 9, 17, sizeof(::Messages::MessageMsg0)}, { 20, 29, sizeof(::Messages::MessageMSG1)}, { 33, 50, sizeof(::Messages::MessageMSG2)}, { 62, 74, sizeof(::Messages::MessageMSG3)}, { 81, 102, sizeof(::Messages::AttestationMessage)}, }; static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = { reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::Messages::_InitialMessage_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::Messages::_MessageMsg0_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::Messages::_MessageMSG1_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::Messages::_MessageMSG2_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::Messages::_MessageMSG3_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::Messages::_AttestationMessage_default_instance_), }; const char descriptor_table_protodef_Messages_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = "\n\016Messages.proto\022\010Messages\",\n\016InitialMes" "sage\022\014\n\004type\030\001 \002(\r\022\014\n\004size\030\002 \001(\r\"9\n\013Mess" "ageMsg0\022\014\n\004type\030\001 \002(\r\022\014\n\004epid\030\002 \002(\r\022\016\n\006s" "tatus\030\003 \001(\r\"N\n\013MessageMSG1\022\014\n\004type\030\001 \002(\r" "\022\017\n\003GaX\030\002 \003(\rB\002\020\001\022\017\n\003GaY\030\003 \003(\rB\002\020\001\022\017\n\003GI" "D\030\004 \003(\rB\002\020\001\"\205\002\n\013MessageMSG2\022\014\n\004type\030\001 \002(" "\r\022\014\n\004size\030\002 \001(\r\022\031\n\rpublic_key_gx\030\003 \003(\rB\002" "\020\001\022\031\n\rpublic_key_gy\030\004 \003(\rB\002\020\001\022\022\n\nquote_t" "ype\030\005 \001(\r\022\020\n\004spid\030\006 \003(\rB\002\020\001\022\023\n\013cmac_kdf_" "id\030\007 \001(\r\022\027\n\013signature_x\030\010 \003(\rB\002\020\001\022\027\n\013sig" "nature_y\030\t \003(\rB\002\020\001\022\020\n\004smac\030\n \003(\rB\002\020\001\022\022\n\n" "size_sigrl\030\013 \001(\r\022\021\n\005sigrl\030\014 \003(\rB\002\020\001\"\227\001\n\013" "MessageMSG3\022\014\n\004type\030\001 \002(\r\022\014\n\004size\030\002 \001(\r\022" "\023\n\007sgx_mac\030\003 \003(\rB\002\020\001\022\024\n\010gax_msg3\030\004 \003(\rB\002" "\020\001\022\024\n\010gay_msg3\030\005 \003(\rB\002\020\001\022\030\n\014sec_property" "\030\006 \003(\rB\002\020\001\022\021\n\005quote\030\007 \003(\rB\002\020\001\"\262\003\n\022Attest" "ationMessage\022\014\n\004type\030\001 \002(\r\022\014\n\004size\030\002 \002(\r" "\022\031\n\021epid_group_status\030\003 \001(\r\022\035\n\025tcb_evalu" "ation_status\030\004 \001(\r\022\035\n\025pse_evaluation_sta" "tus\030\005 \001(\r\022&\n\032latest_equivalent_tcb_psvn\030" "\006 \003(\rB\002\020\001\022\035\n\021latest_pse_isvsvn\030\007 \003(\rB\002\020\001" "\022\033\n\017latest_psda_svn\030\010 \003(\rB\002\020\001\022!\n\025perform" "ance_rekey_gid\030\t \003(\rB\002\020\001\022\030\n\014ec_sign256_x" "\030\n \003(\rB\002\020\001\022\030\n\014ec_sign256_y\030\013 \003(\rB\002\020\001\022\023\n\007" "mac_smk\030\014 \003(\rB\002\020\001\022\023\n\013result_size\030\r \001(\r\022\024" "\n\010reserved\030\016 \003(\rB\002\020\001\022\027\n\013payload_tag\030\017 \003(" "\rB\002\020\001\022\023\n\007payload\030\020 \003(\rB\002\020\001" ; static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_Messages_2eproto_deps[1] = { }; static ::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase*const descriptor_table_Messages_2eproto_sccs[6] = { &scc_info_AttestationMessage_Messages_2eproto.base, &scc_info_InitialMessage_Messages_2eproto.base, &scc_info_MessageMSG1_Messages_2eproto.base, &scc_info_MessageMSG2_Messages_2eproto.base, &scc_info_MessageMSG3_Messages_2eproto.base, &scc_info_MessageMsg0_Messages_2eproto.base, }; static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_Messages_2eproto_once; const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_Messages_2eproto = { false, false, descriptor_table_protodef_Messages_2eproto, "Messages.proto", 1066, &descriptor_table_Messages_2eproto_once, descriptor_table_Messages_2eproto_sccs, descriptor_table_Messages_2eproto_deps, 6, 0, schemas, file_default_instances, TableStruct_Messages_2eproto::offsets, file_level_metadata_Messages_2eproto, 6, file_level_enum_descriptors_Messages_2eproto, file_level_service_descriptors_Messages_2eproto, }; // Force running AddDescriptors() at dynamic initialization time. static bool dynamic_init_dummy_Messages_2eproto = (static_cast<void>(::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_Messages_2eproto)), true); namespace Messages { // =================================================================== class InitialMessage::_Internal { public: using HasBits = decltype(std::declval<InitialMessage>()._has_bits_); static void set_has_type(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_size(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static bool MissingRequiredFields(const HasBits& has_bits) { return ((has_bits[0] & 0x00000001) ^ 0x00000001) != 0; } }; InitialMessage::InitialMessage(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:Messages.InitialMessage) } InitialMessage::InitialMessage(const InitialMessage& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::memcpy(&type_, &from.type_, static_cast<size_t>(reinterpret_cast<char*>(&size_) - reinterpret_cast<char*>(&type_)) + sizeof(size_)); // @@protoc_insertion_point(copy_constructor:Messages.InitialMessage) } void InitialMessage::SharedCtor() { ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&type_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&size_) - reinterpret_cast<char*>(&type_)) + sizeof(size_)); } InitialMessage::~InitialMessage() { // @@protoc_insertion_point(destructor:Messages.InitialMessage) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void InitialMessage::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); } void InitialMessage::ArenaDtor(void* object) { InitialMessage* _this = reinterpret_cast< InitialMessage* >(object); (void)_this; } void InitialMessage::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void InitialMessage::SetCachedSize(int size) const { _cached_size_.Set(size); } const InitialMessage& InitialMessage::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_InitialMessage_Messages_2eproto.base); return *internal_default_instance(); } void InitialMessage::Clear() { // @@protoc_insertion_point(message_clear_start:Messages.InitialMessage) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000003u) { ::memset(&type_, 0, static_cast<size_t>( reinterpret_cast<char*>(&size_) - reinterpret_cast<char*>(&type_)) + sizeof(size_)); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* InitialMessage::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); switch (tag >> 3) { // required uint32 type = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { _Internal::set_has_type(&has_bits); type_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional uint32 size = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { _Internal::set_has_size(&has_bits); size_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* InitialMessage::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:Messages.InitialMessage) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required uint32 type = 1; if (cached_has_bits & 0x00000001u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(1, this->_internal_type(), target); } // optional uint32 size = 2; if (cached_has_bits & 0x00000002u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(2, this->_internal_size(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:Messages.InitialMessage) return target; } size_t InitialMessage::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:Messages.InitialMessage) size_t total_size = 0; // required uint32 type = 1; if (_internal_has_type()) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_type()); } ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // optional uint32 size = 2; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000002u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_size()); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void InitialMessage::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:Messages.InitialMessage) GOOGLE_DCHECK_NE(&from, this); const InitialMessage* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<InitialMessage>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:Messages.InitialMessage) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:Messages.InitialMessage) MergeFrom(*source); } } void InitialMessage::MergeFrom(const InitialMessage& from) { // @@protoc_insertion_point(class_specific_merge_from_start:Messages.InitialMessage) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { type_ = from.type_; } if (cached_has_bits & 0x00000002u) { size_ = from.size_; } _has_bits_[0] |= cached_has_bits; } } void InitialMessage::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:Messages.InitialMessage) if (&from == this) return; Clear(); MergeFrom(from); } void InitialMessage::CopyFrom(const InitialMessage& from) { // @@protoc_insertion_point(class_specific_copy_from_start:Messages.InitialMessage) if (&from == this) return; Clear(); MergeFrom(from); } bool InitialMessage::IsInitialized() const { if (_Internal::MissingRequiredFields(_has_bits_)) return false; return true; } void InitialMessage::InternalSwap(InitialMessage* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(InitialMessage, size_) + sizeof(InitialMessage::size_) - PROTOBUF_FIELD_OFFSET(InitialMessage, type_)>( reinterpret_cast<char*>(&type_), reinterpret_cast<char*>(&other->type_)); } ::PROTOBUF_NAMESPACE_ID::Metadata InitialMessage::GetMetadata() const { return GetMetadataStatic(); } // =================================================================== class MessageMsg0::_Internal { public: using HasBits = decltype(std::declval<MessageMsg0>()._has_bits_); static void set_has_type(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_epid(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static void set_has_status(HasBits* has_bits) { (*has_bits)[0] |= 4u; } static bool MissingRequiredFields(const HasBits& has_bits) { return ((has_bits[0] & 0x00000003) ^ 0x00000003) != 0; } }; MessageMsg0::MessageMsg0(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:Messages.MessageMsg0) } MessageMsg0::MessageMsg0(const MessageMsg0& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::memcpy(&type_, &from.type_, static_cast<size_t>(reinterpret_cast<char*>(&status_) - reinterpret_cast<char*>(&type_)) + sizeof(status_)); // @@protoc_insertion_point(copy_constructor:Messages.MessageMsg0) } void MessageMsg0::SharedCtor() { ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&type_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&status_) - reinterpret_cast<char*>(&type_)) + sizeof(status_)); } MessageMsg0::~MessageMsg0() { // @@protoc_insertion_point(destructor:Messages.MessageMsg0) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void MessageMsg0::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); } void MessageMsg0::ArenaDtor(void* object) { MessageMsg0* _this = reinterpret_cast< MessageMsg0* >(object); (void)_this; } void MessageMsg0::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void MessageMsg0::SetCachedSize(int size) const { _cached_size_.Set(size); } const MessageMsg0& MessageMsg0::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_MessageMsg0_Messages_2eproto.base); return *internal_default_instance(); } void MessageMsg0::Clear() { // @@protoc_insertion_point(message_clear_start:Messages.MessageMsg0) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000007u) { ::memset(&type_, 0, static_cast<size_t>( reinterpret_cast<char*>(&status_) - reinterpret_cast<char*>(&type_)) + sizeof(status_)); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* MessageMsg0::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); switch (tag >> 3) { // required uint32 type = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { _Internal::set_has_type(&has_bits); type_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // required uint32 epid = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { _Internal::set_has_epid(&has_bits); epid_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional uint32 status = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24)) { _Internal::set_has_status(&has_bits); status_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* MessageMsg0::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:Messages.MessageMsg0) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required uint32 type = 1; if (cached_has_bits & 0x00000001u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(1, this->_internal_type(), target); } // required uint32 epid = 2; if (cached_has_bits & 0x00000002u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(2, this->_internal_epid(), target); } // optional uint32 status = 3; if (cached_has_bits & 0x00000004u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(3, this->_internal_status(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:Messages.MessageMsg0) return target; } size_t MessageMsg0::RequiredFieldsByteSizeFallback() const { // @@protoc_insertion_point(required_fields_byte_size_fallback_start:Messages.MessageMsg0) size_t total_size = 0; if (_internal_has_type()) { // required uint32 type = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_type()); } if (_internal_has_epid()) { // required uint32 epid = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_epid()); } return total_size; } size_t MessageMsg0::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:Messages.MessageMsg0) size_t total_size = 0; if (((_has_bits_[0] & 0x00000003) ^ 0x00000003) == 0) { // All required fields are present. // required uint32 type = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_type()); // required uint32 epid = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_epid()); } else { total_size += RequiredFieldsByteSizeFallback(); } ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // optional uint32 status = 3; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000004u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_status()); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void MessageMsg0::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:Messages.MessageMsg0) GOOGLE_DCHECK_NE(&from, this); const MessageMsg0* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<MessageMsg0>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:Messages.MessageMsg0) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:Messages.MessageMsg0) MergeFrom(*source); } } void MessageMsg0::MergeFrom(const MessageMsg0& from) { // @@protoc_insertion_point(class_specific_merge_from_start:Messages.MessageMsg0) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x00000007u) { if (cached_has_bits & 0x00000001u) { type_ = from.type_; } if (cached_has_bits & 0x00000002u) { epid_ = from.epid_; } if (cached_has_bits & 0x00000004u) { status_ = from.status_; } _has_bits_[0] |= cached_has_bits; } } void MessageMsg0::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:Messages.MessageMsg0) if (&from == this) return; Clear(); MergeFrom(from); } void MessageMsg0::CopyFrom(const MessageMsg0& from) { // @@protoc_insertion_point(class_specific_copy_from_start:Messages.MessageMsg0) if (&from == this) return; Clear(); MergeFrom(from); } bool MessageMsg0::IsInitialized() const { if (_Internal::MissingRequiredFields(_has_bits_)) return false; return true; } void MessageMsg0::InternalSwap(MessageMsg0* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(MessageMsg0, status_) + sizeof(MessageMsg0::status_) - PROTOBUF_FIELD_OFFSET(MessageMsg0, type_)>( reinterpret_cast<char*>(&type_), reinterpret_cast<char*>(&other->type_)); } ::PROTOBUF_NAMESPACE_ID::Metadata MessageMsg0::GetMetadata() const { return GetMetadataStatic(); } // =================================================================== class MessageMSG1::_Internal { public: using HasBits = decltype(std::declval<MessageMSG1>()._has_bits_); static void set_has_type(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static bool MissingRequiredFields(const HasBits& has_bits) { return ((has_bits[0] & 0x00000001) ^ 0x00000001) != 0; } }; MessageMSG1::MessageMSG1(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena), gax_(arena), gay_(arena), gid_(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:Messages.MessageMSG1) } MessageMSG1::MessageMSG1(const MessageMSG1& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_), gax_(from.gax_), gay_(from.gay_), gid_(from.gid_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); type_ = from.type_; // @@protoc_insertion_point(copy_constructor:Messages.MessageMSG1) } void MessageMSG1::SharedCtor() { type_ = 0u; } MessageMSG1::~MessageMSG1() { // @@protoc_insertion_point(destructor:Messages.MessageMSG1) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void MessageMSG1::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); } void MessageMSG1::ArenaDtor(void* object) { MessageMSG1* _this = reinterpret_cast< MessageMSG1* >(object); (void)_this; } void MessageMSG1::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void MessageMSG1::SetCachedSize(int size) const { _cached_size_.Set(size); } const MessageMSG1& MessageMSG1::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_MessageMSG1_Messages_2eproto.base); return *internal_default_instance(); } void MessageMSG1::Clear() { // @@protoc_insertion_point(message_clear_start:Messages.MessageMSG1) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; gax_.Clear(); gay_.Clear(); gid_.Clear(); type_ = 0u; _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* MessageMSG1::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); switch (tag >> 3) { // required uint32 type = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { _Internal::set_has_type(&has_bits); type_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated uint32 GaX = 2 [packed = true]; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedUInt32Parser(_internal_mutable_gax(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16) { _internal_add_gax(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr)); CHK_(ptr); } else goto handle_unusual; continue; // repeated uint32 GaY = 3 [packed = true]; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedUInt32Parser(_internal_mutable_gay(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24) { _internal_add_gay(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr)); CHK_(ptr); } else goto handle_unusual; continue; // repeated uint32 GID = 4 [packed = true]; case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 34)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedUInt32Parser(_internal_mutable_gid(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 32) { _internal_add_gid(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr)); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* MessageMSG1::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:Messages.MessageMSG1) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required uint32 type = 1; if (cached_has_bits & 0x00000001u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(1, this->_internal_type(), target); } // repeated uint32 GaX = 2 [packed = true]; { int byte_size = _gax_cached_byte_size_.load(std::memory_order_relaxed); if (byte_size > 0) { target = stream->WriteUInt32Packed( 2, _internal_gax(), byte_size, target); } } // repeated uint32 GaY = 3 [packed = true]; { int byte_size = _gay_cached_byte_size_.load(std::memory_order_relaxed); if (byte_size > 0) { target = stream->WriteUInt32Packed( 3, _internal_gay(), byte_size, target); } } // repeated uint32 GID = 4 [packed = true]; { int byte_size = _gid_cached_byte_size_.load(std::memory_order_relaxed); if (byte_size > 0) { target = stream->WriteUInt32Packed( 4, _internal_gid(), byte_size, target); } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:Messages.MessageMSG1) return target; } size_t MessageMSG1::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:Messages.MessageMSG1) size_t total_size = 0; // required uint32 type = 1; if (_internal_has_type()) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_type()); } ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated uint32 GaX = 2 [packed = true]; { size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: UInt32Size(this->gax_); if (data_size > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size); _gax_cached_byte_size_.store(cached_size, std::memory_order_relaxed); total_size += data_size; } // repeated uint32 GaY = 3 [packed = true]; { size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: UInt32Size(this->gay_); if (data_size > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size); _gay_cached_byte_size_.store(cached_size, std::memory_order_relaxed); total_size += data_size; } // repeated uint32 GID = 4 [packed = true]; { size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: UInt32Size(this->gid_); if (data_size > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size); _gid_cached_byte_size_.store(cached_size, std::memory_order_relaxed); total_size += data_size; } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void MessageMSG1::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:Messages.MessageMSG1) GOOGLE_DCHECK_NE(&from, this); const MessageMSG1* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<MessageMSG1>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:Messages.MessageMSG1) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:Messages.MessageMSG1) MergeFrom(*source); } } void MessageMSG1::MergeFrom(const MessageMSG1& from) { // @@protoc_insertion_point(class_specific_merge_from_start:Messages.MessageMSG1) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; gax_.MergeFrom(from.gax_); gay_.MergeFrom(from.gay_); gid_.MergeFrom(from.gid_); if (from._internal_has_type()) { _internal_set_type(from._internal_type()); } } void MessageMSG1::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:Messages.MessageMSG1) if (&from == this) return; Clear(); MergeFrom(from); } void MessageMSG1::CopyFrom(const MessageMSG1& from) { // @@protoc_insertion_point(class_specific_copy_from_start:Messages.MessageMSG1) if (&from == this) return; Clear(); MergeFrom(from); } bool MessageMSG1::IsInitialized() const { if (_Internal::MissingRequiredFields(_has_bits_)) return false; return true; } void MessageMSG1::InternalSwap(MessageMSG1* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); gax_.InternalSwap(&other->gax_); gay_.InternalSwap(&other->gay_); gid_.InternalSwap(&other->gid_); swap(type_, other->type_); } ::PROTOBUF_NAMESPACE_ID::Metadata MessageMSG1::GetMetadata() const { return GetMetadataStatic(); } // =================================================================== class MessageMSG2::_Internal { public: using HasBits = decltype(std::declval<MessageMSG2>()._has_bits_); static void set_has_type(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_size(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static void set_has_quote_type(HasBits* has_bits) { (*has_bits)[0] |= 4u; } static void set_has_cmac_kdf_id(HasBits* has_bits) { (*has_bits)[0] |= 8u; } static void set_has_size_sigrl(HasBits* has_bits) { (*has_bits)[0] |= 16u; } static bool MissingRequiredFields(const HasBits& has_bits) { return ((has_bits[0] & 0x00000001) ^ 0x00000001) != 0; } }; MessageMSG2::MessageMSG2(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena), public_key_gx_(arena), public_key_gy_(arena), spid_(arena), signature_x_(arena), signature_y_(arena), smac_(arena), sigrl_(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:Messages.MessageMSG2) } MessageMSG2::MessageMSG2(const MessageMSG2& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_), public_key_gx_(from.public_key_gx_), public_key_gy_(from.public_key_gy_), spid_(from.spid_), signature_x_(from.signature_x_), signature_y_(from.signature_y_), smac_(from.smac_), sigrl_(from.sigrl_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::memcpy(&type_, &from.type_, static_cast<size_t>(reinterpret_cast<char*>(&size_sigrl_) - reinterpret_cast<char*>(&type_)) + sizeof(size_sigrl_)); // @@protoc_insertion_point(copy_constructor:Messages.MessageMSG2) } void MessageMSG2::SharedCtor() { ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&type_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&size_sigrl_) - reinterpret_cast<char*>(&type_)) + sizeof(size_sigrl_)); } MessageMSG2::~MessageMSG2() { // @@protoc_insertion_point(destructor:Messages.MessageMSG2) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void MessageMSG2::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); } void MessageMSG2::ArenaDtor(void* object) { MessageMSG2* _this = reinterpret_cast< MessageMSG2* >(object); (void)_this; } void MessageMSG2::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void MessageMSG2::SetCachedSize(int size) const { _cached_size_.Set(size); } const MessageMSG2& MessageMSG2::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_MessageMSG2_Messages_2eproto.base); return *internal_default_instance(); } void MessageMSG2::Clear() { // @@protoc_insertion_point(message_clear_start:Messages.MessageMSG2) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; public_key_gx_.Clear(); public_key_gy_.Clear(); spid_.Clear(); signature_x_.Clear(); signature_y_.Clear(); smac_.Clear(); sigrl_.Clear(); cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000001fu) { ::memset(&type_, 0, static_cast<size_t>( reinterpret_cast<char*>(&size_sigrl_) - reinterpret_cast<char*>(&type_)) + sizeof(size_sigrl_)); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* MessageMSG2::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); switch (tag >> 3) { // required uint32 type = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { _Internal::set_has_type(&has_bits); type_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional uint32 size = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { _Internal::set_has_size(&has_bits); size_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated uint32 public_key_gx = 3 [packed = true]; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedUInt32Parser(_internal_mutable_public_key_gx(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24) { _internal_add_public_key_gx(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr)); CHK_(ptr); } else goto handle_unusual; continue; // repeated uint32 public_key_gy = 4 [packed = true]; case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 34)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedUInt32Parser(_internal_mutable_public_key_gy(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 32) { _internal_add_public_key_gy(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr)); CHK_(ptr); } else goto handle_unusual; continue; // optional uint32 quote_type = 5; case 5: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 40)) { _Internal::set_has_quote_type(&has_bits); quote_type_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated uint32 spid = 6 [packed = true]; case 6: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 50)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedUInt32Parser(_internal_mutable_spid(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 48) { _internal_add_spid(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr)); CHK_(ptr); } else goto handle_unusual; continue; // optional uint32 cmac_kdf_id = 7; case 7: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 56)) { _Internal::set_has_cmac_kdf_id(&has_bits); cmac_kdf_id_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated uint32 signature_x = 8 [packed = true]; case 8: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 66)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedUInt32Parser(_internal_mutable_signature_x(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 64) { _internal_add_signature_x(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr)); CHK_(ptr); } else goto handle_unusual; continue; // repeated uint32 signature_y = 9 [packed = true]; case 9: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 74)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedUInt32Parser(_internal_mutable_signature_y(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 72) { _internal_add_signature_y(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr)); CHK_(ptr); } else goto handle_unusual; continue; // repeated uint32 smac = 10 [packed = true]; case 10: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 82)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedUInt32Parser(_internal_mutable_smac(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 80) { _internal_add_smac(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr)); CHK_(ptr); } else goto handle_unusual; continue; // optional uint32 size_sigrl = 11; case 11: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 88)) { _Internal::set_has_size_sigrl(&has_bits); size_sigrl_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated uint32 sigrl = 12 [packed = true]; case 12: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 98)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedUInt32Parser(_internal_mutable_sigrl(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 96) { _internal_add_sigrl(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr)); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* MessageMSG2::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:Messages.MessageMSG2) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required uint32 type = 1; if (cached_has_bits & 0x00000001u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(1, this->_internal_type(), target); } // optional uint32 size = 2; if (cached_has_bits & 0x00000002u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(2, this->_internal_size(), target); } // repeated uint32 public_key_gx = 3 [packed = true]; { int byte_size = _public_key_gx_cached_byte_size_.load(std::memory_order_relaxed); if (byte_size > 0) { target = stream->WriteUInt32Packed( 3, _internal_public_key_gx(), byte_size, target); } } // repeated uint32 public_key_gy = 4 [packed = true]; { int byte_size = _public_key_gy_cached_byte_size_.load(std::memory_order_relaxed); if (byte_size > 0) { target = stream->WriteUInt32Packed( 4, _internal_public_key_gy(), byte_size, target); } } // optional uint32 quote_type = 5; if (cached_has_bits & 0x00000004u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(5, this->_internal_quote_type(), target); } // repeated uint32 spid = 6 [packed = true]; { int byte_size = _spid_cached_byte_size_.load(std::memory_order_relaxed); if (byte_size > 0) { target = stream->WriteUInt32Packed( 6, _internal_spid(), byte_size, target); } } // optional uint32 cmac_kdf_id = 7; if (cached_has_bits & 0x00000008u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(7, this->_internal_cmac_kdf_id(), target); } // repeated uint32 signature_x = 8 [packed = true]; { int byte_size = _signature_x_cached_byte_size_.load(std::memory_order_relaxed); if (byte_size > 0) { target = stream->WriteUInt32Packed( 8, _internal_signature_x(), byte_size, target); } } // repeated uint32 signature_y = 9 [packed = true]; { int byte_size = _signature_y_cached_byte_size_.load(std::memory_order_relaxed); if (byte_size > 0) { target = stream->WriteUInt32Packed( 9, _internal_signature_y(), byte_size, target); } } // repeated uint32 smac = 10 [packed = true]; { int byte_size = _smac_cached_byte_size_.load(std::memory_order_relaxed); if (byte_size > 0) { target = stream->WriteUInt32Packed( 10, _internal_smac(), byte_size, target); } } // optional uint32 size_sigrl = 11; if (cached_has_bits & 0x00000010u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(11, this->_internal_size_sigrl(), target); } // repeated uint32 sigrl = 12 [packed = true]; { int byte_size = _sigrl_cached_byte_size_.load(std::memory_order_relaxed); if (byte_size > 0) { target = stream->WriteUInt32Packed( 12, _internal_sigrl(), byte_size, target); } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:Messages.MessageMSG2) return target; } size_t MessageMSG2::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:Messages.MessageMSG2) size_t total_size = 0; // required uint32 type = 1; if (_internal_has_type()) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_type()); } ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated uint32 public_key_gx = 3 [packed = true]; { size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: UInt32Size(this->public_key_gx_); if (data_size > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size); _public_key_gx_cached_byte_size_.store(cached_size, std::memory_order_relaxed); total_size += data_size; } // repeated uint32 public_key_gy = 4 [packed = true]; { size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: UInt32Size(this->public_key_gy_); if (data_size > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size); _public_key_gy_cached_byte_size_.store(cached_size, std::memory_order_relaxed); total_size += data_size; } // repeated uint32 spid = 6 [packed = true]; { size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: UInt32Size(this->spid_); if (data_size > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size); _spid_cached_byte_size_.store(cached_size, std::memory_order_relaxed); total_size += data_size; } // repeated uint32 signature_x = 8 [packed = true]; { size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: UInt32Size(this->signature_x_); if (data_size > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size); _signature_x_cached_byte_size_.store(cached_size, std::memory_order_relaxed); total_size += data_size; } // repeated uint32 signature_y = 9 [packed = true]; { size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: UInt32Size(this->signature_y_); if (data_size > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size); _signature_y_cached_byte_size_.store(cached_size, std::memory_order_relaxed); total_size += data_size; } // repeated uint32 smac = 10 [packed = true]; { size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: UInt32Size(this->smac_); if (data_size > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size); _smac_cached_byte_size_.store(cached_size, std::memory_order_relaxed); total_size += data_size; } // repeated uint32 sigrl = 12 [packed = true]; { size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: UInt32Size(this->sigrl_); if (data_size > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size); _sigrl_cached_byte_size_.store(cached_size, std::memory_order_relaxed); total_size += data_size; } cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000001eu) { // optional uint32 size = 2; if (cached_has_bits & 0x00000002u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_size()); } // optional uint32 quote_type = 5; if (cached_has_bits & 0x00000004u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_quote_type()); } // optional uint32 cmac_kdf_id = 7; if (cached_has_bits & 0x00000008u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_cmac_kdf_id()); } // optional uint32 size_sigrl = 11; if (cached_has_bits & 0x00000010u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_size_sigrl()); } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void MessageMSG2::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:Messages.MessageMSG2) GOOGLE_DCHECK_NE(&from, this); const MessageMSG2* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<MessageMSG2>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:Messages.MessageMSG2) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:Messages.MessageMSG2) MergeFrom(*source); } } void MessageMSG2::MergeFrom(const MessageMSG2& from) { // @@protoc_insertion_point(class_specific_merge_from_start:Messages.MessageMSG2) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; public_key_gx_.MergeFrom(from.public_key_gx_); public_key_gy_.MergeFrom(from.public_key_gy_); spid_.MergeFrom(from.spid_); signature_x_.MergeFrom(from.signature_x_); signature_y_.MergeFrom(from.signature_y_); smac_.MergeFrom(from.smac_); sigrl_.MergeFrom(from.sigrl_); cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x0000001fu) { if (cached_has_bits & 0x00000001u) { type_ = from.type_; } if (cached_has_bits & 0x00000002u) { size_ = from.size_; } if (cached_has_bits & 0x00000004u) { quote_type_ = from.quote_type_; } if (cached_has_bits & 0x00000008u) { cmac_kdf_id_ = from.cmac_kdf_id_; } if (cached_has_bits & 0x00000010u) { size_sigrl_ = from.size_sigrl_; } _has_bits_[0] |= cached_has_bits; } } void MessageMSG2::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:Messages.MessageMSG2) if (&from == this) return; Clear(); MergeFrom(from); } void MessageMSG2::CopyFrom(const MessageMSG2& from) { // @@protoc_insertion_point(class_specific_copy_from_start:Messages.MessageMSG2) if (&from == this) return; Clear(); MergeFrom(from); } bool MessageMSG2::IsInitialized() const { if (_Internal::MissingRequiredFields(_has_bits_)) return false; return true; } void MessageMSG2::InternalSwap(MessageMSG2* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); public_key_gx_.InternalSwap(&other->public_key_gx_); public_key_gy_.InternalSwap(&other->public_key_gy_); spid_.InternalSwap(&other->spid_); signature_x_.InternalSwap(&other->signature_x_); signature_y_.InternalSwap(&other->signature_y_); smac_.InternalSwap(&other->smac_); sigrl_.InternalSwap(&other->sigrl_); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(MessageMSG2, size_sigrl_) + sizeof(MessageMSG2::size_sigrl_) - PROTOBUF_FIELD_OFFSET(MessageMSG2, type_)>( reinterpret_cast<char*>(&type_), reinterpret_cast<char*>(&other->type_)); } ::PROTOBUF_NAMESPACE_ID::Metadata MessageMSG2::GetMetadata() const { return GetMetadataStatic(); } // =================================================================== class MessageMSG3::_Internal { public: using HasBits = decltype(std::declval<MessageMSG3>()._has_bits_); static void set_has_type(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_size(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static bool MissingRequiredFields(const HasBits& has_bits) { return ((has_bits[0] & 0x00000001) ^ 0x00000001) != 0; } }; MessageMSG3::MessageMSG3(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena), sgx_mac_(arena), gax_msg3_(arena), gay_msg3_(arena), sec_property_(arena), quote_(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:Messages.MessageMSG3) } MessageMSG3::MessageMSG3(const MessageMSG3& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_), sgx_mac_(from.sgx_mac_), gax_msg3_(from.gax_msg3_), gay_msg3_(from.gay_msg3_), sec_property_(from.sec_property_), quote_(from.quote_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::memcpy(&type_, &from.type_, static_cast<size_t>(reinterpret_cast<char*>(&size_) - reinterpret_cast<char*>(&type_)) + sizeof(size_)); // @@protoc_insertion_point(copy_constructor:Messages.MessageMSG3) } void MessageMSG3::SharedCtor() { ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&type_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&size_) - reinterpret_cast<char*>(&type_)) + sizeof(size_)); } MessageMSG3::~MessageMSG3() { // @@protoc_insertion_point(destructor:Messages.MessageMSG3) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void MessageMSG3::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); } void MessageMSG3::ArenaDtor(void* object) { MessageMSG3* _this = reinterpret_cast< MessageMSG3* >(object); (void)_this; } void MessageMSG3::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void MessageMSG3::SetCachedSize(int size) const { _cached_size_.Set(size); } const MessageMSG3& MessageMSG3::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_MessageMSG3_Messages_2eproto.base); return *internal_default_instance(); } void MessageMSG3::Clear() { // @@protoc_insertion_point(message_clear_start:Messages.MessageMSG3) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; sgx_mac_.Clear(); gax_msg3_.Clear(); gay_msg3_.Clear(); sec_property_.Clear(); quote_.Clear(); cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000003u) { ::memset(&type_, 0, static_cast<size_t>( reinterpret_cast<char*>(&size_) - reinterpret_cast<char*>(&type_)) + sizeof(size_)); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* MessageMSG3::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); switch (tag >> 3) { // required uint32 type = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { _Internal::set_has_type(&has_bits); type_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional uint32 size = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { _Internal::set_has_size(&has_bits); size_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated uint32 sgx_mac = 3 [packed = true]; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedUInt32Parser(_internal_mutable_sgx_mac(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24) { _internal_add_sgx_mac(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr)); CHK_(ptr); } else goto handle_unusual; continue; // repeated uint32 gax_msg3 = 4 [packed = true]; case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 34)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedUInt32Parser(_internal_mutable_gax_msg3(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 32) { _internal_add_gax_msg3(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr)); CHK_(ptr); } else goto handle_unusual; continue; // repeated uint32 gay_msg3 = 5 [packed = true]; case 5: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 42)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedUInt32Parser(_internal_mutable_gay_msg3(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 40) { _internal_add_gay_msg3(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr)); CHK_(ptr); } else goto handle_unusual; continue; // repeated uint32 sec_property = 6 [packed = true]; case 6: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 50)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedUInt32Parser(_internal_mutable_sec_property(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 48) { _internal_add_sec_property(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr)); CHK_(ptr); } else goto handle_unusual; continue; // repeated uint32 quote = 7 [packed = true]; case 7: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedUInt32Parser(_internal_mutable_quote(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 56) { _internal_add_quote(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr)); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* MessageMSG3::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:Messages.MessageMSG3) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required uint32 type = 1; if (cached_has_bits & 0x00000001u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(1, this->_internal_type(), target); } // optional uint32 size = 2; if (cached_has_bits & 0x00000002u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(2, this->_internal_size(), target); } // repeated uint32 sgx_mac = 3 [packed = true]; { int byte_size = _sgx_mac_cached_byte_size_.load(std::memory_order_relaxed); if (byte_size > 0) { target = stream->WriteUInt32Packed( 3, _internal_sgx_mac(), byte_size, target); } } // repeated uint32 gax_msg3 = 4 [packed = true]; { int byte_size = _gax_msg3_cached_byte_size_.load(std::memory_order_relaxed); if (byte_size > 0) { target = stream->WriteUInt32Packed( 4, _internal_gax_msg3(), byte_size, target); } } // repeated uint32 gay_msg3 = 5 [packed = true]; { int byte_size = _gay_msg3_cached_byte_size_.load(std::memory_order_relaxed); if (byte_size > 0) { target = stream->WriteUInt32Packed( 5, _internal_gay_msg3(), byte_size, target); } } // repeated uint32 sec_property = 6 [packed = true]; { int byte_size = _sec_property_cached_byte_size_.load(std::memory_order_relaxed); if (byte_size > 0) { target = stream->WriteUInt32Packed( 6, _internal_sec_property(), byte_size, target); } } // repeated uint32 quote = 7 [packed = true]; { int byte_size = _quote_cached_byte_size_.load(std::memory_order_relaxed); if (byte_size > 0) { target = stream->WriteUInt32Packed( 7, _internal_quote(), byte_size, target); } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:Messages.MessageMSG3) return target; } size_t MessageMSG3::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:Messages.MessageMSG3) size_t total_size = 0; // required uint32 type = 1; if (_internal_has_type()) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_type()); } ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated uint32 sgx_mac = 3 [packed = true]; { size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: UInt32Size(this->sgx_mac_); if (data_size > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size); _sgx_mac_cached_byte_size_.store(cached_size, std::memory_order_relaxed); total_size += data_size; } // repeated uint32 gax_msg3 = 4 [packed = true]; { size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: UInt32Size(this->gax_msg3_); if (data_size > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size); _gax_msg3_cached_byte_size_.store(cached_size, std::memory_order_relaxed); total_size += data_size; } // repeated uint32 gay_msg3 = 5 [packed = true]; { size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: UInt32Size(this->gay_msg3_); if (data_size > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size); _gay_msg3_cached_byte_size_.store(cached_size, std::memory_order_relaxed); total_size += data_size; } // repeated uint32 sec_property = 6 [packed = true]; { size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: UInt32Size(this->sec_property_); if (data_size > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size); _sec_property_cached_byte_size_.store(cached_size, std::memory_order_relaxed); total_size += data_size; } // repeated uint32 quote = 7 [packed = true]; { size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: UInt32Size(this->quote_); if (data_size > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size); _quote_cached_byte_size_.store(cached_size, std::memory_order_relaxed); total_size += data_size; } // optional uint32 size = 2; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000002u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_size()); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void MessageMSG3::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:Messages.MessageMSG3) GOOGLE_DCHECK_NE(&from, this); const MessageMSG3* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<MessageMSG3>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:Messages.MessageMSG3) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:Messages.MessageMSG3) MergeFrom(*source); } } void MessageMSG3::MergeFrom(const MessageMSG3& from) { // @@protoc_insertion_point(class_specific_merge_from_start:Messages.MessageMSG3) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; sgx_mac_.MergeFrom(from.sgx_mac_); gax_msg3_.MergeFrom(from.gax_msg3_); gay_msg3_.MergeFrom(from.gay_msg3_); sec_property_.MergeFrom(from.sec_property_); quote_.MergeFrom(from.quote_); cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { type_ = from.type_; } if (cached_has_bits & 0x00000002u) { size_ = from.size_; } _has_bits_[0] |= cached_has_bits; } } void MessageMSG3::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:Messages.MessageMSG3) if (&from == this) return; Clear(); MergeFrom(from); } void MessageMSG3::CopyFrom(const MessageMSG3& from) { // @@protoc_insertion_point(class_specific_copy_from_start:Messages.MessageMSG3) if (&from == this) return; Clear(); MergeFrom(from); } bool MessageMSG3::IsInitialized() const { if (_Internal::MissingRequiredFields(_has_bits_)) return false; return true; } void MessageMSG3::InternalSwap(MessageMSG3* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); sgx_mac_.InternalSwap(&other->sgx_mac_); gax_msg3_.InternalSwap(&other->gax_msg3_); gay_msg3_.InternalSwap(&other->gay_msg3_); sec_property_.InternalSwap(&other->sec_property_); quote_.InternalSwap(&other->quote_); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(MessageMSG3, size_) + sizeof(MessageMSG3::size_) - PROTOBUF_FIELD_OFFSET(MessageMSG3, type_)>( reinterpret_cast<char*>(&type_), reinterpret_cast<char*>(&other->type_)); } ::PROTOBUF_NAMESPACE_ID::Metadata MessageMSG3::GetMetadata() const { return GetMetadataStatic(); } // =================================================================== class AttestationMessage::_Internal { public: using HasBits = decltype(std::declval<AttestationMessage>()._has_bits_); static void set_has_type(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_size(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static void set_has_epid_group_status(HasBits* has_bits) { (*has_bits)[0] |= 4u; } static void set_has_tcb_evaluation_status(HasBits* has_bits) { (*has_bits)[0] |= 8u; } static void set_has_pse_evaluation_status(HasBits* has_bits) { (*has_bits)[0] |= 16u; } static void set_has_result_size(HasBits* has_bits) { (*has_bits)[0] |= 32u; } static bool MissingRequiredFields(const HasBits& has_bits) { return ((has_bits[0] & 0x00000003) ^ 0x00000003) != 0; } }; AttestationMessage::AttestationMessage(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena), latest_equivalent_tcb_psvn_(arena), latest_pse_isvsvn_(arena), latest_psda_svn_(arena), performance_rekey_gid_(arena), ec_sign256_x_(arena), ec_sign256_y_(arena), mac_smk_(arena), reserved_(arena), payload_tag_(arena), payload_(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:Messages.AttestationMessage) } AttestationMessage::AttestationMessage(const AttestationMessage& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_), latest_equivalent_tcb_psvn_(from.latest_equivalent_tcb_psvn_), latest_pse_isvsvn_(from.latest_pse_isvsvn_), latest_psda_svn_(from.latest_psda_svn_), performance_rekey_gid_(from.performance_rekey_gid_), ec_sign256_x_(from.ec_sign256_x_), ec_sign256_y_(from.ec_sign256_y_), mac_smk_(from.mac_smk_), reserved_(from.reserved_), payload_tag_(from.payload_tag_), payload_(from.payload_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::memcpy(&type_, &from.type_, static_cast<size_t>(reinterpret_cast<char*>(&result_size_) - reinterpret_cast<char*>(&type_)) + sizeof(result_size_)); // @@protoc_insertion_point(copy_constructor:Messages.AttestationMessage) } void AttestationMessage::SharedCtor() { ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&type_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&result_size_) - reinterpret_cast<char*>(&type_)) + sizeof(result_size_)); } AttestationMessage::~AttestationMessage() { // @@protoc_insertion_point(destructor:Messages.AttestationMessage) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void AttestationMessage::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); } void AttestationMessage::ArenaDtor(void* object) { AttestationMessage* _this = reinterpret_cast< AttestationMessage* >(object); (void)_this; } void AttestationMessage::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void AttestationMessage::SetCachedSize(int size) const { _cached_size_.Set(size); } const AttestationMessage& AttestationMessage::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_AttestationMessage_Messages_2eproto.base); return *internal_default_instance(); } void AttestationMessage::Clear() { // @@protoc_insertion_point(message_clear_start:Messages.AttestationMessage) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; latest_equivalent_tcb_psvn_.Clear(); latest_pse_isvsvn_.Clear(); latest_psda_svn_.Clear(); performance_rekey_gid_.Clear(); ec_sign256_x_.Clear(); ec_sign256_y_.Clear(); mac_smk_.Clear(); reserved_.Clear(); payload_tag_.Clear(); payload_.Clear(); cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000003fu) { ::memset(&type_, 0, static_cast<size_t>( reinterpret_cast<char*>(&result_size_) - reinterpret_cast<char*>(&type_)) + sizeof(result_size_)); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* AttestationMessage::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); switch (tag >> 3) { // required uint32 type = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { _Internal::set_has_type(&has_bits); type_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // required uint32 size = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { _Internal::set_has_size(&has_bits); size_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional uint32 epid_group_status = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24)) { _Internal::set_has_epid_group_status(&has_bits); epid_group_status_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional uint32 tcb_evaluation_status = 4; case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 32)) { _Internal::set_has_tcb_evaluation_status(&has_bits); tcb_evaluation_status_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional uint32 pse_evaluation_status = 5; case 5: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 40)) { _Internal::set_has_pse_evaluation_status(&has_bits); pse_evaluation_status_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated uint32 latest_equivalent_tcb_psvn = 6 [packed = true]; case 6: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 50)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedUInt32Parser(_internal_mutable_latest_equivalent_tcb_psvn(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 48) { _internal_add_latest_equivalent_tcb_psvn(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr)); CHK_(ptr); } else goto handle_unusual; continue; // repeated uint32 latest_pse_isvsvn = 7 [packed = true]; case 7: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedUInt32Parser(_internal_mutable_latest_pse_isvsvn(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 56) { _internal_add_latest_pse_isvsvn(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr)); CHK_(ptr); } else goto handle_unusual; continue; // repeated uint32 latest_psda_svn = 8 [packed = true]; case 8: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 66)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedUInt32Parser(_internal_mutable_latest_psda_svn(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 64) { _internal_add_latest_psda_svn(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr)); CHK_(ptr); } else goto handle_unusual; continue; // repeated uint32 performance_rekey_gid = 9 [packed = true]; case 9: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 74)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedUInt32Parser(_internal_mutable_performance_rekey_gid(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 72) { _internal_add_performance_rekey_gid(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr)); CHK_(ptr); } else goto handle_unusual; continue; // repeated uint32 ec_sign256_x = 10 [packed = true]; case 10: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 82)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedUInt32Parser(_internal_mutable_ec_sign256_x(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 80) { _internal_add_ec_sign256_x(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr)); CHK_(ptr); } else goto handle_unusual; continue; // repeated uint32 ec_sign256_y = 11 [packed = true]; case 11: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 90)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedUInt32Parser(_internal_mutable_ec_sign256_y(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 88) { _internal_add_ec_sign256_y(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr)); CHK_(ptr); } else goto handle_unusual; continue; // repeated uint32 mac_smk = 12 [packed = true]; case 12: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 98)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedUInt32Parser(_internal_mutable_mac_smk(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 96) { _internal_add_mac_smk(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr)); CHK_(ptr); } else goto handle_unusual; continue; // optional uint32 result_size = 13; case 13: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 104)) { _Internal::set_has_result_size(&has_bits); result_size_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated uint32 reserved = 14 [packed = true]; case 14: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 114)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedUInt32Parser(_internal_mutable_reserved(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 112) { _internal_add_reserved(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr)); CHK_(ptr); } else goto handle_unusual; continue; // repeated uint32 payload_tag = 15 [packed = true]; case 15: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 122)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedUInt32Parser(_internal_mutable_payload_tag(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 120) { _internal_add_payload_tag(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr)); CHK_(ptr); } else goto handle_unusual; continue; // repeated uint32 payload = 16 [packed = true]; case 16: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 130)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedUInt32Parser(_internal_mutable_payload(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 128) { _internal_add_payload(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr)); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* AttestationMessage::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:Messages.AttestationMessage) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required uint32 type = 1; if (cached_has_bits & 0x00000001u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(1, this->_internal_type(), target); } // required uint32 size = 2; if (cached_has_bits & 0x00000002u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(2, this->_internal_size(), target); } // optional uint32 epid_group_status = 3; if (cached_has_bits & 0x00000004u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(3, this->_internal_epid_group_status(), target); } // optional uint32 tcb_evaluation_status = 4; if (cached_has_bits & 0x00000008u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(4, this->_internal_tcb_evaluation_status(), target); } // optional uint32 pse_evaluation_status = 5; if (cached_has_bits & 0x00000010u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(5, this->_internal_pse_evaluation_status(), target); } // repeated uint32 latest_equivalent_tcb_psvn = 6 [packed = true]; { int byte_size = _latest_equivalent_tcb_psvn_cached_byte_size_.load(std::memory_order_relaxed); if (byte_size > 0) { target = stream->WriteUInt32Packed( 6, _internal_latest_equivalent_tcb_psvn(), byte_size, target); } } // repeated uint32 latest_pse_isvsvn = 7 [packed = true]; { int byte_size = _latest_pse_isvsvn_cached_byte_size_.load(std::memory_order_relaxed); if (byte_size > 0) { target = stream->WriteUInt32Packed( 7, _internal_latest_pse_isvsvn(), byte_size, target); } } // repeated uint32 latest_psda_svn = 8 [packed = true]; { int byte_size = _latest_psda_svn_cached_byte_size_.load(std::memory_order_relaxed); if (byte_size > 0) { target = stream->WriteUInt32Packed( 8, _internal_latest_psda_svn(), byte_size, target); } } // repeated uint32 performance_rekey_gid = 9 [packed = true]; { int byte_size = _performance_rekey_gid_cached_byte_size_.load(std::memory_order_relaxed); if (byte_size > 0) { target = stream->WriteUInt32Packed( 9, _internal_performance_rekey_gid(), byte_size, target); } } // repeated uint32 ec_sign256_x = 10 [packed = true]; { int byte_size = _ec_sign256_x_cached_byte_size_.load(std::memory_order_relaxed); if (byte_size > 0) { target = stream->WriteUInt32Packed( 10, _internal_ec_sign256_x(), byte_size, target); } } // repeated uint32 ec_sign256_y = 11 [packed = true]; { int byte_size = _ec_sign256_y_cached_byte_size_.load(std::memory_order_relaxed); if (byte_size > 0) { target = stream->WriteUInt32Packed( 11, _internal_ec_sign256_y(), byte_size, target); } } // repeated uint32 mac_smk = 12 [packed = true]; { int byte_size = _mac_smk_cached_byte_size_.load(std::memory_order_relaxed); if (byte_size > 0) { target = stream->WriteUInt32Packed( 12, _internal_mac_smk(), byte_size, target); } } // optional uint32 result_size = 13; if (cached_has_bits & 0x00000020u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(13, this->_internal_result_size(), target); } // repeated uint32 reserved = 14 [packed = true]; { int byte_size = _reserved_cached_byte_size_.load(std::memory_order_relaxed); if (byte_size > 0) { target = stream->WriteUInt32Packed( 14, _internal_reserved(), byte_size, target); } } // repeated uint32 payload_tag = 15 [packed = true]; { int byte_size = _payload_tag_cached_byte_size_.load(std::memory_order_relaxed); if (byte_size > 0) { target = stream->WriteUInt32Packed( 15, _internal_payload_tag(), byte_size, target); } } // repeated uint32 payload = 16 [packed = true]; { int byte_size = _payload_cached_byte_size_.load(std::memory_order_relaxed); if (byte_size > 0) { target = stream->WriteUInt32Packed( 16, _internal_payload(), byte_size, target); } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:Messages.AttestationMessage) return target; } size_t AttestationMessage::RequiredFieldsByteSizeFallback() const { // @@protoc_insertion_point(required_fields_byte_size_fallback_start:Messages.AttestationMessage) size_t total_size = 0; if (_internal_has_type()) { // required uint32 type = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_type()); } if (_internal_has_size()) { // required uint32 size = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_size()); } return total_size; } size_t AttestationMessage::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:Messages.AttestationMessage) size_t total_size = 0; if (((_has_bits_[0] & 0x00000003) ^ 0x00000003) == 0) { // All required fields are present. // required uint32 type = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_type()); // required uint32 size = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_size()); } else { total_size += RequiredFieldsByteSizeFallback(); } ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated uint32 latest_equivalent_tcb_psvn = 6 [packed = true]; { size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: UInt32Size(this->latest_equivalent_tcb_psvn_); if (data_size > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size); _latest_equivalent_tcb_psvn_cached_byte_size_.store(cached_size, std::memory_order_relaxed); total_size += data_size; } // repeated uint32 latest_pse_isvsvn = 7 [packed = true]; { size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: UInt32Size(this->latest_pse_isvsvn_); if (data_size > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size); _latest_pse_isvsvn_cached_byte_size_.store(cached_size, std::memory_order_relaxed); total_size += data_size; } // repeated uint32 latest_psda_svn = 8 [packed = true]; { size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: UInt32Size(this->latest_psda_svn_); if (data_size > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size); _latest_psda_svn_cached_byte_size_.store(cached_size, std::memory_order_relaxed); total_size += data_size; } // repeated uint32 performance_rekey_gid = 9 [packed = true]; { size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: UInt32Size(this->performance_rekey_gid_); if (data_size > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size); _performance_rekey_gid_cached_byte_size_.store(cached_size, std::memory_order_relaxed); total_size += data_size; } // repeated uint32 ec_sign256_x = 10 [packed = true]; { size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: UInt32Size(this->ec_sign256_x_); if (data_size > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size); _ec_sign256_x_cached_byte_size_.store(cached_size, std::memory_order_relaxed); total_size += data_size; } // repeated uint32 ec_sign256_y = 11 [packed = true]; { size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: UInt32Size(this->ec_sign256_y_); if (data_size > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size); _ec_sign256_y_cached_byte_size_.store(cached_size, std::memory_order_relaxed); total_size += data_size; } // repeated uint32 mac_smk = 12 [packed = true]; { size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: UInt32Size(this->mac_smk_); if (data_size > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size); _mac_smk_cached_byte_size_.store(cached_size, std::memory_order_relaxed); total_size += data_size; } // repeated uint32 reserved = 14 [packed = true]; { size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: UInt32Size(this->reserved_); if (data_size > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size); _reserved_cached_byte_size_.store(cached_size, std::memory_order_relaxed); total_size += data_size; } // repeated uint32 payload_tag = 15 [packed = true]; { size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: UInt32Size(this->payload_tag_); if (data_size > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size); _payload_tag_cached_byte_size_.store(cached_size, std::memory_order_relaxed); total_size += data_size; } // repeated uint32 payload = 16 [packed = true]; { size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: UInt32Size(this->payload_); if (data_size > 0) { total_size += 2 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size); _payload_cached_byte_size_.store(cached_size, std::memory_order_relaxed); total_size += data_size; } cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000003cu) { // optional uint32 epid_group_status = 3; if (cached_has_bits & 0x00000004u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_epid_group_status()); } // optional uint32 tcb_evaluation_status = 4; if (cached_has_bits & 0x00000008u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_tcb_evaluation_status()); } // optional uint32 pse_evaluation_status = 5; if (cached_has_bits & 0x00000010u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_pse_evaluation_status()); } // optional uint32 result_size = 13; if (cached_has_bits & 0x00000020u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_result_size()); } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void AttestationMessage::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:Messages.AttestationMessage) GOOGLE_DCHECK_NE(&from, this); const AttestationMessage* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<AttestationMessage>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:Messages.AttestationMessage) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:Messages.AttestationMessage) MergeFrom(*source); } } void AttestationMessage::MergeFrom(const AttestationMessage& from) { // @@protoc_insertion_point(class_specific_merge_from_start:Messages.AttestationMessage) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; latest_equivalent_tcb_psvn_.MergeFrom(from.latest_equivalent_tcb_psvn_); latest_pse_isvsvn_.MergeFrom(from.latest_pse_isvsvn_); latest_psda_svn_.MergeFrom(from.latest_psda_svn_); performance_rekey_gid_.MergeFrom(from.performance_rekey_gid_); ec_sign256_x_.MergeFrom(from.ec_sign256_x_); ec_sign256_y_.MergeFrom(from.ec_sign256_y_); mac_smk_.MergeFrom(from.mac_smk_); reserved_.MergeFrom(from.reserved_); payload_tag_.MergeFrom(from.payload_tag_); payload_.MergeFrom(from.payload_); cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x0000003fu) { if (cached_has_bits & 0x00000001u) { type_ = from.type_; } if (cached_has_bits & 0x00000002u) { size_ = from.size_; } if (cached_has_bits & 0x00000004u) { epid_group_status_ = from.epid_group_status_; } if (cached_has_bits & 0x00000008u) { tcb_evaluation_status_ = from.tcb_evaluation_status_; } if (cached_has_bits & 0x00000010u) { pse_evaluation_status_ = from.pse_evaluation_status_; } if (cached_has_bits & 0x00000020u) { result_size_ = from.result_size_; } _has_bits_[0] |= cached_has_bits; } } void AttestationMessage::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:Messages.AttestationMessage) if (&from == this) return; Clear(); MergeFrom(from); } void AttestationMessage::CopyFrom(const AttestationMessage& from) { // @@protoc_insertion_point(class_specific_copy_from_start:Messages.AttestationMessage) if (&from == this) return; Clear(); MergeFrom(from); } bool AttestationMessage::IsInitialized() const { if (_Internal::MissingRequiredFields(_has_bits_)) return false; return true; } void AttestationMessage::InternalSwap(AttestationMessage* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); latest_equivalent_tcb_psvn_.InternalSwap(&other->latest_equivalent_tcb_psvn_); latest_pse_isvsvn_.InternalSwap(&other->latest_pse_isvsvn_); latest_psda_svn_.InternalSwap(&other->latest_psda_svn_); performance_rekey_gid_.InternalSwap(&other->performance_rekey_gid_); ec_sign256_x_.InternalSwap(&other->ec_sign256_x_); ec_sign256_y_.InternalSwap(&other->ec_sign256_y_); mac_smk_.InternalSwap(&other->mac_smk_); reserved_.InternalSwap(&other->reserved_); payload_tag_.InternalSwap(&other->payload_tag_); payload_.InternalSwap(&other->payload_); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(AttestationMessage, result_size_) + sizeof(AttestationMessage::result_size_) - PROTOBUF_FIELD_OFFSET(AttestationMessage, type_)>( reinterpret_cast<char*>(&type_), reinterpret_cast<char*>(&other->type_)); } ::PROTOBUF_NAMESPACE_ID::Metadata AttestationMessage::GetMetadata() const { return GetMetadataStatic(); } // @@protoc_insertion_point(namespace_scope) } // namespace Messages PROTOBUF_NAMESPACE_OPEN template<> PROTOBUF_NOINLINE ::Messages::InitialMessage* Arena::CreateMaybeMessage< ::Messages::InitialMessage >(Arena* arena) { return Arena::CreateMessageInternal< ::Messages::InitialMessage >(arena); } template<> PROTOBUF_NOINLINE ::Messages::MessageMsg0* Arena::CreateMaybeMessage< ::Messages::MessageMsg0 >(Arena* arena) { return Arena::CreateMessageInternal< ::Messages::MessageMsg0 >(arena); } template<> PROTOBUF_NOINLINE ::Messages::MessageMSG1* Arena::CreateMaybeMessage< ::Messages::MessageMSG1 >(Arena* arena) { return Arena::CreateMessageInternal< ::Messages::MessageMSG1 >(arena); } template<> PROTOBUF_NOINLINE ::Messages::MessageMSG2* Arena::CreateMaybeMessage< ::Messages::MessageMSG2 >(Arena* arena) { return Arena::CreateMessageInternal< ::Messages::MessageMSG2 >(arena); } template<> PROTOBUF_NOINLINE ::Messages::MessageMSG3* Arena::CreateMaybeMessage< ::Messages::MessageMSG3 >(Arena* arena) { return Arena::CreateMessageInternal< ::Messages::MessageMSG3 >(arena); } template<> PROTOBUF_NOINLINE ::Messages::AttestationMessage* Arena::CreateMaybeMessage< ::Messages::AttestationMessage >(Arena* arena) { return Arena::CreateMessageInternal< ::Messages::AttestationMessage >(arena); } PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc>
38.60085
163
0.704632
[ "object" ]
af81b3747b87798ecc737e5c424544bb84d7259a
8,194
cc
C++
mindspore/lite/src/runtime/kernel/opencl/kernel/matmul.cc
Rossil2012/mindspore
8a20b5d784b3fec6d32e058581ec56ec553a06a0
[ "Apache-2.0" ]
1
2021-04-23T06:35:18.000Z
2021-04-23T06:35:18.000Z
mindspore/lite/src/runtime/kernel/opencl/kernel/matmul.cc
nudt-eddie/mindspore
55372b41fdfae6d2b88d7078971e06d537f6c558
[ "Apache-2.0" ]
null
null
null
mindspore/lite/src/runtime/kernel/opencl/kernel/matmul.cc
nudt-eddie/mindspore
55372b41fdfae6d2b88d7078971e06d537f6c558
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2019 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <set> #include <string> #include "nnacl/fp32/common_func.h" #include "src/kernel_registry.h" #include "src/runtime/opencl/opencl_runtime.h" #include "nnacl/fp32/matmul.h" #include "src/runtime/kernel/opencl/kernel/matmul.h" #ifndef PROGRAM_WITH_IL #include "src/runtime/kernel/opencl/cl/matmul.cl.inc" #endif using mindspore::kernel::KERNEL_ARCH::kGPU; using mindspore::lite::KernelRegistrar; using mindspore::schema::PrimitiveType_FullConnection; using mindspore::schema::PrimitiveType_MatMul; namespace mindspore::kernel { int MatMulOpenCLKernel::Init() { std::string kernel_name = "MatMul"; kernel_name += "_" + std::string(EnumNameFormat(op_format_)); auto ocl_runtime = lite::opencl::OpenCLRuntime::GetInstance(); enable_fp16_ = ocl_runtime->GetFp16Enable(); #ifdef PROGRAM_WITH_IL kernel_ = ocl_runtime->GetKernelFromBinary(kernel_name); #else std::set<std::string> build_options; std::string source = matmul_source; std::string program_name = "MatMul"; ocl_runtime->LoadSource(program_name, source); ocl_runtime->BuildKernel(kernel_, program_name, kernel_name, build_options); #endif int ci, co; if (in_tensors_[1]->shape().size() != 2) { MS_LOG(ERROR) << "matmul do not support input shape size=" << in_tensors_[1]->shape().size(); return RET_ERROR; } if (in_tensors_[1]->shape().size() == 2) { ci = in_tensors_[1]->shape()[1]; co = in_tensors_[1]->shape()[0]; } else { ci = in_tensors_[1]->shape()[3]; co = in_tensors_[1]->shape()[0]; } sizeCI = {ci, UP_DIV(ci, C4NUM)}; sizeCO = {co, UP_DIV(co, C4NUM)}; PadWeight(); in_ori_format_ = in_tensors_[0]->GetFormat(); out_ori_format_ = out_tensors_[0]->GetFormat(); in_tensors_[0]->SetFormat(op_format_); out_tensors_[0]->SetFormat(op_format_); MS_LOG(DEBUG) << kernel_name << " Init Done!"; return RET_OK; } int MatMulOpenCLKernel::ReSize() { return RET_OK; } void MatMulOpenCLKernel::PadWeight() { auto allocator = lite::opencl::OpenCLRuntime::GetInstance()->GetAllocator(); size_t dtype_size = enable_fp16_ ? sizeof(int16_t) : sizeof(float); padWeight_ = allocator->Malloc(sizeCI.s[1] * sizeCO.s[1] * C4NUM * C4NUM * dtype_size); padWeight_ = allocator->MapBuffer(padWeight_, CL_MAP_WRITE, nullptr, true); memset(padWeight_, 0x00, sizeCI.s[1] * sizeCO.s[1] * C4NUM * C4NUM * dtype_size); auto origin_weight = in_tensors_.at(kWeightIndex)->Data(); int divCI = sizeCI.s[1]; int divCO = sizeCO.s[1]; int co = sizeCO.s[0]; int index = 0; for (int i = 0; i < divCI; ++i) { for (int j = 0; j < divCO; ++j) { for (int k = 0; k < C4NUM; ++k) { for (int l = 0; l < C4NUM; ++l) { int src_x = i * C4NUM + l; int src_y = j * C4NUM + k; if (src_x < sizeCI.s[0] && src_y < sizeCO.s[0]) { if (enable_fp16_) { if (in_tensors_.at(kWeightIndex)->data_type() == kNumberTypeFloat32) { reinterpret_cast<uint16_t *>(padWeight_)[index++] = Float32ToShort(reinterpret_cast<float *>(origin_weight)[src_y * sizeCI.s[0] + src_x]); } else { reinterpret_cast<uint16_t *>(padWeight_)[index++] = reinterpret_cast<uint16_t *>(origin_weight)[src_y * sizeCI.s[0] + src_x]; } } else { if (in_tensors_.at(kWeightIndex)->data_type() == kNumberTypeFloat16) { reinterpret_cast<float *>(padWeight_)[index++] = ShortToFloat32(reinterpret_cast<uint16_t *>(origin_weight)[src_y * sizeCI.s[0] + src_x]); } else { reinterpret_cast<float *>(padWeight_)[index++] = reinterpret_cast<float *>(origin_weight)[src_y * sizeCI.s[0] + src_x]; } } } else { index++; } } } } } size_t im_dst_x, im_dst_y; im_dst_x = divCO; im_dst_y = 1; size_t img_dtype = CL_FLOAT; if (enable_fp16_) { img_dtype = CL_HALF_FLOAT; } std::vector<size_t> img_size{im_dst_x, im_dst_y, img_dtype}; bias_ = allocator->Malloc(im_dst_x * im_dst_y * C4NUM * dtype_size, img_size); bias_ = allocator->MapBuffer(bias_, CL_MAP_WRITE, nullptr, true); memset(bias_, 0x00, divCO * C4NUM * dtype_size); if (in_tensors_.size() >= 3) { if (in_tensors_[2]->data_type() == kNumberTypeFloat32 && enable_fp16_) { auto fdata = reinterpret_cast<float *>(in_tensors_[2]->Data()); for (int i = 0; i < co; i++) { reinterpret_cast<uint16_t *>(bias_)[i] = Float32ToShort(fdata[i]); } } else { memcpy(bias_, in_tensors_[2]->Data(), co * dtype_size); } } allocator->UnmapBuffer(bias_); } int MatMulOpenCLKernel::GetImageSize(size_t idx, std::vector<size_t> *img_size) { size_t im_dst_x, im_dst_y; if (op_format_ == schema::Format_NHWC4) { im_dst_x = sizeCO.s[1]; im_dst_y = 1; } else if (op_format_ == schema::Format_NC4HW4) { im_dst_x = 1; im_dst_y = sizeCO.s[1]; } else { MS_LOG(ERROR) << "not support op format:" << EnumNameFormat(op_format_); return RET_ERROR; } size_t img_dtype = CL_FLOAT; if (enable_fp16_) { img_dtype = CL_HALF_FLOAT; } img_size->clear(); std::vector<size_t> vec{im_dst_x, im_dst_y, img_dtype}; *img_size = vec; return RET_OK; } int MatMulOpenCLKernel::Run() { MS_LOG(DEBUG) << this->name() << " Running!"; auto ocl_runtime = lite::opencl::OpenCLRuntime::GetInstance(); // local size should less than MAX_GROUP_SIZE std::vector<size_t> local = {64, 4}; std::vector<size_t> global = {UP_ROUND(sizeCO.s[1], local[0]), 4}; int arg_count = 0; ocl_runtime->SetKernelArg(kernel_, arg_count++, in_tensors_[0]->Data()); ocl_runtime->SetKernelArg(kernel_, arg_count++, padWeight_, lite::opencl::MemType::BUF); ocl_runtime->SetKernelArg(kernel_, arg_count++, bias_); ocl_runtime->SetKernelArg(kernel_, arg_count++, out_tensors_[0]->Data()); ocl_runtime->SetKernelArg(kernel_, arg_count++, sizeCI); ocl_runtime->SetKernelArg(kernel_, arg_count++, sizeCO); ocl_runtime->SetKernelArg(kernel_, arg_count++, hasBias_ ? 1 : 0); ocl_runtime->RunKernel(kernel_, global, local, nullptr); return RET_OK; } kernel::LiteKernel *OpenCLMatMulKernelCreator(const std::vector<lite::tensor::Tensor *> &inputs, const std::vector<lite::tensor::Tensor *> &outputs, OpParameter *opParameter, const lite::Context *ctx, const kernel::KernelKey &desc, const mindspore::lite::PrimitiveC *primitive) { bool hasBias = false; if (opParameter->type_ == PrimitiveType_FullConnection) { hasBias = (reinterpret_cast<MatMulParameter *>(opParameter))->has_bias_; } auto *kernel = new (std::nothrow) MatMulOpenCLKernel(reinterpret_cast<OpParameter *>(opParameter), inputs, outputs, hasBias); if (kernel == nullptr) { MS_LOG(ERROR) << "kernel " << opParameter->name_ << "is nullptr."; return nullptr; } auto ret = kernel->Init(); if (ret != RET_OK) { delete kernel; return nullptr; } return kernel; } REG_KERNEL(kGPU, kNumberTypeFloat32, PrimitiveType_MatMul, OpenCLMatMulKernelCreator) REG_KERNEL(kGPU, kNumberTypeFloat32, PrimitiveType_FullConnection, OpenCLMatMulKernelCreator) REG_KERNEL(kGPU, kNumberTypeFloat16, PrimitiveType_MatMul, OpenCLMatMulKernelCreator) REG_KERNEL(kGPU, kNumberTypeFloat16, PrimitiveType_FullConnection, OpenCLMatMulKernelCreator) } // namespace mindspore::kernel
38.834123
114
0.658042
[ "shape", "vector" ]
af82cf8230199c9f3dda4b1dba4320f56ce6ca5b
2,485
hpp
C++
ACore/src/Stl.hpp
ecmwf/ecflow
2498d0401d3d1133613d600d5c0e0a8a30b7b8eb
[ "Apache-2.0" ]
11
2020-08-07T14:42:45.000Z
2021-10-21T01:59:59.000Z
ACore/src/Stl.hpp
CoollRock/ecflow
db61dddc84d3d2c7dd6af95fd799d717c6bc2a6d
[ "Apache-2.0" ]
10
2020-08-07T14:36:27.000Z
2022-02-22T06:51:24.000Z
ACore/src/Stl.hpp
CoollRock/ecflow
db61dddc84d3d2c7dd6af95fd799d717c6bc2a6d
[ "Apache-2.0" ]
6
2020-08-07T14:34:38.000Z
2022-01-10T12:06:27.000Z
#ifndef STL_HPP_ #define STL_HPP_ //============================================================================ // Name : stl // Author : Avi // Revision : $Revision: #5 $ // // Copyright 2009-2020 ECMWF. // This software is licensed under the terms of the Apache Licence version 2.0 // which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. // In applying this licence, ECMWF does not waive the privileges and immunities // granted to it by virtue of its status as an intergovernmental organisation // nor does it submit to any jurisdiction. // // Description : //============================================================================ /***************************************************************************** * Standard Library Include Files * *****************************************************************************/ #include <algorithm> //for for_each() namespace ecf { /// Helper struct that will aid the deletion of Pointer from a container template <typename T> struct TSeqDeletor { void operator ()(T pointer) const { // std::cout << "Destroy of this pointer" << std::endl; delete pointer; pointer = 0; } }; /// This function can be used to delete the pointers in a container /// i.e int main (int argc, char **argv) { /// std::vector <std::string *> vect; /// vect.push_back (new std::string ("Stephane")); /// DeletePtrs (vect); /// } template <typename Container> void DeletePtrs (Container& pContainer) { std::for_each( pContainer.begin (), pContainer.end (), TSeqDeletor<typename Container::value_type> ()); pContainer.clear(); } /// Helper struct that will aid the deletion of Pointer from a Associative container template <typename TPair> struct TAsoDeletor { void operator () (TPair& tElem) const { if(tElem.second) { delete tElem.second; } } }; /// This function can be used to delete the pointers in a Assoc container /// i.e int main (int argc, char **argv) { /// std::map <int,std::string *> theMap; /// theMap[0] = new std::string ("Stephane"); /// AssoDeletePtrs(theMap); /// } template <typename Container> void AssoDeletePtrs (Container& pContainer) { std::for_each( pContainer.begin (), pContainer.end (), TAsoDeletor<typename Container::value_type> ()); pContainer.clear(); } } #endif /* STL_HPP_ */
35.5
85
0.556137
[ "vector" ]
af86b181d32a153e12597ce50c847ea80ee53af2
9,058
cpp
C++
src/audio/sndbuffer.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
2
2019-06-22T23:29:44.000Z
2019-07-07T18:34:04.000Z
src/audio/sndbuffer.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
null
null
null
src/audio/sndbuffer.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
null
null
null
/** * @file sndbuffer.cpp * @brief Implementation of SndBuffer.h * @author Frederic SCHERMA (frederic.scherma@dreamoverflow.org) * @date 2003-04-11 * @copyright Copyright (c) 2001-2017 Dream Overflow. All rights reserved. * @details */ #include "o3d/audio/precompiled.h" #include "o3d/core/mutex.h" #include "o3d/audio/sndbuffer.h" #include "o3d/audio/sndstream.h" #include "o3d/audio/sound.h" #include "o3d/core/debug.h" #include "o3d/core/virtualfilelisting.h" #include "o3d/core/filemanager.h" #include "o3d/core/memorydbg.h" #include "o3d/engine/scene/scene.h" #include "o3d/audio/audio.h" #include "o3d/audio/al.h" #include "o3d/audio/alc.h" using namespace o3d; O3D_IMPLEMENT_DYNAMIC_CLASS1(SndBuffer, AUDIO_SND_BUFFER, SceneResource) // Default constructor SndBuffer::SndBuffer( BaseObject *parent, Float decodeMaxDuration) : SceneResource(parent), m_bufferObject(nullptr), m_frontBuffer(O3D_UNDEFINED), m_backBuffer(O3D_UNDEFINED), m_streamPos(0), m_decodeMaxDuration(decodeMaxDuration) { } // Construct using a generated and valid sound. SndBuffer::SndBuffer( BaseObject *parent, const Sound &sound, Float decodeMaxDuration) : SceneResource(parent), m_bufferObject(nullptr), m_frontBuffer(O3D_UNDEFINED), m_backBuffer(O3D_UNDEFINED), m_streamPos(0), m_decodeMaxDuration(decodeMaxDuration) { if (sound.isEmpty()) { O3D_ERROR(E_InvalidParameter("Sound must be valid")); } m_sound = sound; } // Destructor SndBuffer::~SndBuffer() { destroy(); } // Get the sound buffer sampling rate (8,11,22,44kHz). UInt32 SndBuffer::getSamplingRate() const { if (m_sound.isValid()) { return m_sound.getSamplingRate(); } else if (m_bufferObject) { return m_bufferObject->getSamplingRate(); } else { return 0; } } // Get the size of a channel in bits (8 or 16bits). UInt32 SndBuffer::getChannelFormat() const { if (m_sound.isValid()) { return m_sound.getFormat(); } else if (m_bufferObject) { return m_bufferObject->getFormat(); } else { return 0; } } // Get bit per sample (8,16). UInt32 SndBuffer::getBitsPerSample() const { UInt32 format = 0; if (m_sound.isValid()) { format = m_sound.getFormat(); } else if (m_bufferObject) { format = m_bufferObject->getFormat(); } switch (format) { case AL_FORMAT_MONO16: case AL_FORMAT_STEREO16: return 16; case AL_FORMAT_MONO8: case AL_FORMAT_STEREO8: return 8; default: return 0; } } // Get the number of channels (1 or 2). UInt32 SndBuffer::getNumChannels() const { UInt32 format = 0; if (m_sound.isValid()) { format = m_sound.getFormat(); } else if (m_bufferObject) { format = m_bufferObject->getFormat(); } switch (format) { case AL_FORMAT_MONO8: case AL_FORMAT_MONO16: return 1; case AL_FORMAT_STEREO8: case AL_FORMAT_STEREO16: return 2; default: return 0; } } // Create OpenAL buffer. Bool SndBuffer::create(Bool unloadSound) { if (m_bufferObject) { return True; } // if the sound data is no longer in memory we try to load it before if (m_sound.isEmpty()) { if (getResourceName().startsWith("<")) { return False; } // load the sound m_sound.load(getResourceName(), m_decodeMaxDuration); } // single buffer if ((m_sound.getDuration() <= m_decodeMaxDuration) || ((m_sound.getSize() <= SndStream::BUFFER_SIZE) && (m_sound.getSize() != 0))) { m_bufferObject = new ALBuffer(); // single buffer object m_bufferObject->load(m_sound); } else { // streamed with front and back buffers m_bufferObject = m_sound.createStreamer(); alGenBuffers(1, &m_frontBuffer); alGenBuffers(1, &m_backBuffer); } if (unloadSound) { m_sound.destroy(); } // Valid sound buffer onSndBufferValid(this); return True; } // Delete the buffer void SndBuffer::destroy() { m_streamPos = 0; deletePtr(m_bufferObject); if (m_frontBuffer != O3D_UNDEFINED) { O3D_SFREE(MemoryManager::SFX_STREAM_BUFFER, m_frontBuffer); alDeleteBuffers(1, &m_frontBuffer); m_frontBuffer = O3D_UNDEFINED; } if (m_backBuffer != O3D_UNDEFINED) { O3D_SFREE(MemoryManager::SFX_STREAM_BUFFER, m_backBuffer); alDeleteBuffers(1, &m_backBuffer); m_backBuffer = O3D_UNDEFINED; } m_sound.destroy(); } // Unload the sound data, but keep it in OpenAL void SndBuffer::unloadSound() { m_sound.destroy(); } // Get the front or single buffer id. UInt32 SndBuffer::getFrontBufferId() const { if (m_bufferObject) { if (m_bufferObject->isStream()) { return m_frontBuffer; } else { return static_cast<ALBuffer*>(m_bufferObject)->getBufferId(); } } else { return 0; } } // Get the back buffer id. UInt32 SndBuffer::getBackBufferId() const { if (m_bufferObject) { if (m_bufferObject->isStream()) { return m_backBuffer; } else { return 0; } } else { return 0; } } // update the buffer: only for streamed buffer (with a back-buffer) Bool SndBuffer::updateStream(UInt32 sourceId, Bool loop, UInt32 &position) { // only for a streamed sound if (!m_bufferObject->isStream()) { return False; } Int32 processed; Bool finished = False; alGetSourcei(sourceId, AL_BUFFERS_PROCESSED, &processed); SndStream *sndStream = static_cast<SndStream*>(m_bufferObject); m_streamPos = position; while (processed--) { ALuint bufferId; // un-queue the read buffer alSourceUnqueueBuffers(sourceId, 1, &bufferId); // update buffer data if not finished if (!finished) { UInt32 size; const UInt8 *data = sndStream->getStreamChunk(m_streamPos, size, finished); // is finished and loop needed if (finished && loop) { finished = False; m_streamPos = position = 0; // need data if (!data) data = sndStream->getStreamChunk(m_streamPos, size, finished); } // data to fill in ? if (data) { m_streamPos = position = sndStream->getStreamPos(); // fill the buffer alBufferData(bufferId, m_bufferObject->getFormat(), (ALvoid*)data, size, m_bufferObject->getSamplingRate()); // and queue the updated buffer alSourceQueueBuffers(sourceId, 1, &bufferId); } } } return !finished; } // prepare the stream to be played Bool SndBuffer::prepareStream(UInt32 sourceId, UInt32 &position) { // only for a streamed sound if (!m_bufferObject->isStream()) { return False; } UInt32 size; Bool finished = True; SndStream *sndStream = static_cast<SndStream*>(m_bufferObject); m_streamPos = 0; // set the front buffer if (m_frontBuffer != O3D_UNDEFINED) { const UInt8* data = sndStream->getStreamChunk(m_streamPos, size, finished); if (!data) { return False; } O3D_SALLOC(MemoryManager::SFX_STREAM_BUFFER, m_frontBuffer, size); alBufferData( m_frontBuffer, m_bufferObject->getFormat(), (ALvoid*)data, size, m_bufferObject->getSamplingRate()); m_streamPos = position = sndStream->getStreamPos(); // and queue the buffer alSourceQueueBuffers(sourceId, 1, &m_frontBuffer); } // set the back buffer if ((m_backBuffer != O3D_UNDEFINED) && !finished) { const UInt8* data = sndStream->getStreamChunk(m_streamPos, size, finished); if (!data) { return False; } O3D_SALLOC(MemoryManager::SFX_STREAM_BUFFER, m_backBuffer, size); alBufferData( m_backBuffer, m_bufferObject->getFormat(), (ALvoid*)data, size, m_bufferObject->getSamplingRate()); m_streamPos = position = sndStream->getStreamPos(); // and queue the buffer alSourceQueueBuffers(sourceId, 1, &m_backBuffer); } return True; } // Serialization Bool SndBuffer::writeToFile(OutStream &os) { BaseObject::writeToFile(os); os << m_resourceName << m_decodeMaxDuration; return True; } Bool SndBuffer::readFromFile(InStream &is) { BaseObject::readFromFile(is); is >> m_resourceName >> m_decodeMaxDuration; return True; } //--------------------------------------------------------------------------------------- // SndBufferTask //--------------------------------------------------------------------------------------- // Default constructor. SndBufferTask::SndBufferTask( SndBuffer *sndBuffer, const String &filename, Float decodeMaxDuration) : m_sndBuffer(sndBuffer), m_decodeMaxDuration(decodeMaxDuration) { if (!sndBuffer) { O3D_ERROR(E_InvalidParameter("The sound buffer must be valid")); } m_filename = FileManager::instance()->getFullFileName(filename); } Bool SndBufferTask::execute() { O3D_ASSERT(m_filename.isValid()); if (m_filename.isValid()) { try { m_sound.load(m_filename, m_decodeMaxDuration); } catch (E_BaseException &) { return False; } return True; } else { return False; } } Bool SndBufferTask::finalize() { if (m_sound.isValid()) { m_sndBuffer->getSound() = m_sound; return m_sndBuffer->create(); } else { return False; } }
21.566667
112
0.665047
[ "object" ]
af95c6a71359f5090b3aa4ec6bcff9fc1e1c5c11
686
cpp
C++
gym/103048/e/e.cpp
GoatGirl98/cf
4077ca8e0fe29dc2bbb7b60166989857cc062e17
[ "MIT" ]
null
null
null
gym/103048/e/e.cpp
GoatGirl98/cf
4077ca8e0fe29dc2bbb7b60166989857cc062e17
[ "MIT" ]
null
null
null
gym/103048/e/e.cpp
GoatGirl98/cf
4077ca8e0fe29dc2bbb7b60166989857cc062e17
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define watch(x) std::cout << (#x) << " is " << (x) << std::endl using LL = long long; int main() { //freopen("in", "r", stdin); std::cin.tie(nullptr)->sync_with_stdio(false); int n; std::cin >> n; std::vector<std::vector<int>> e(n); for (int i = 1, u, v; i < n; ++i) { std::cin >> u >> v; if (--u == --v) continue; e[u].emplace_back(v); e[v].emplace_back(u); } int a, b; std::cin >> a >> b; --a; --b; std::vector<int> dep(n); std::function<void(int, int)> dfs = [&](int u, int fa) { for (auto v : e[u]) if (v != fa) { dep[v] = dep[u] + 1; dfs(v, u); } }; dfs(a, -1); std::cout << (dep[b] & 1 ? "Yes\n" : "No\n"); return 0; }
22.866667
64
0.495627
[ "vector" ]
afa755859b3ea7fe2772ef1741ccdab8141f2853
5,618
cpp
C++
main.cpp
frostburn/raytrace
19c8f431e0efcac5e30632819757da584c8d6242
[ "MIT" ]
null
null
null
main.cpp
frostburn/raytrace
19c8f431e0efcac5e30632819757da584c8d6242
[ "MIT" ]
null
null
null
main.cpp
frostburn/raytrace
19c8f431e0efcac5e30632819757da584c8d6242
[ "MIT" ]
null
null
null
#include <iostream> #include <iomanip> #include <limits> #include <cmath> #include <vector> #include <memory> #include <random> #include <cassert> #include <string> #include "raytrace/quaternion.h" #include "raytrace/ray_traceable.h" #include "raytrace/gradient_traceable.h" #include "raytrace/sphere.h" #include "raytrace/clifford_torus.h" #include "raytrace/hyper_torus.h" #include "raytrace/trace.h" #include "raytrace/input_parser.h" using namespace std; int main(int argc, char *argv[]) { InputParser input(argc, argv); if(input.cmdOptionExists("-h") || input.cmdOptionExists("--help")){ cerr << "Usage: " << argv[0] << " --time 3.14 --width 200 --height 200" << endl; return EXIT_SUCCESS; } real t = 0; int width = 100; int height = 100; const std::string &time = input.getCmdOption("--time"); if (!time.empty()){ t = std::stod(time); } const std::string &width_ = input.getCmdOption("--width"); if (!width_.empty()){ width = std::stoi(width_); } const std::string &height_ = input.getCmdOption("--height"); if (!height_.empty()){ height = std::stoi(height_); } real aspect_ratio = (real)width / (real)height; quaternion camera_transform = {1, 0.2, 0.05, -0.5}; camera_transform = camera_transform / norm(camera_transform); quaternion target_transform = {1, 0.05, -0.15, 0.05}; target_transform = target_transform / norm(target_transform); // TODO: Sensible camera definitions // quaternion camera_pos = {1, 0.1, 0.05, -0.3}; // camera_pos = camera_pos / norm(camera_pos); // quaternion look_at = {1, 0, 0, 0}; // quaternion look_direction = look_at - camera_pos; // look_direction = look_direction / norm(look_direction); real view_width = 0.2; real view_depth = 0.5; vector<shared_ptr<RayTraceable>> objects; int grid_height = 3 - 1; int grid_width = 3 - 1; int grid_depth = 3 - 1; for (int j = 0; j <= grid_height; ++j) { real y = 1 - 2 * (j / (real) grid_height); for (int i = 0; i <= grid_width; ++i) { real x = 1 - 2 * (i / (real) grid_width); for (int k = 0; k <= grid_depth; ++k) { real z = 1 - 2 * (k / (real) grid_depth); shared_ptr<Sphere> point = make_shared<Sphere>(); point->location = {1, 0.2 * x, 0.2 * y, 0.2 * z}; point->location = point->location / norm(point->location); point->pigment = {0, 2.1 + x, 2.1 + y, 2.1 + z}; point->pigment = point->pigment / 3.2; point->scale = point->scale * 0.02; objects.push_back(point); quaternion q = {0, 0, 0, 1}; q = exp(q * t); point->location = q * point->location; } } } quaternion unit_scale = (quaternion){1, 1, 1, 1} * 0.05; shared_ptr<Sphere> unit = make_shared<Sphere>(); unit->location = {1, 0, 0, 0}; unit->scale = unit_scale; unit->reflection = 0.3; objects.push_back(unit); unit = make_shared<Sphere>(); unit->location = {0, 1, 0, 0}; unit->pigment = {0, 1, 0, 0}; unit->scale = unit_scale; unit->reflection = 0.3; objects.push_back(unit); unit = make_shared<Sphere>(); unit->location = {0, 0, 1, 0}; unit->pigment = {0, 0, 1, 0}; unit->scale = unit_scale; unit->reflection = 0.3; objects.push_back(unit); unit = make_shared<Sphere>(); unit->location = {0, 0, 0, 1}; unit->pigment = {0, 0, 0, 1}; unit->scale = unit_scale; unit->reflection = 0.3; objects.push_back(unit); unit = make_shared<Sphere>(); unit->location = {-1, 0, 0, 0}; unit->pigment = {0, 0.2, 0.2, 0.2}; unit->scale = unit_scale; unit->reflection = 0.5; objects.push_back(unit); shared_ptr<HyperTorus2> axis = make_shared<HyperTorus2>(); axis->location = {0, 0, 0, 0}; axis->minor_radius = 0.01; quaternion q = {0, 1, 0, 0}; axis->left_transform = exp(q * t * 0.25); axis->right_transform = exp(q * t * 0.25); objects.push_back(axis); axis = make_shared<HyperTorus2>(); axis->location = {0, 0, 0, 0}; axis->minor_radius = 0.01; quaternion p = {sqrt(0.5), sqrt(0.5), 0, 0}; q = {0, 0, 1, 0}; axis->left_transform = p * exp(q * t * 0.25); axis->right_transform = exp(q * t * 0.25) / p; objects.push_back(axis); default_random_engine generator; normal_distribution<real> distribution(0.0, 0.2 / (real) width); cout << "P3" << endl; cout << width << " " << height << endl; cout << 255 << endl; for (int j = 0; j < height; ++j) { cerr << (j * 100) / height << "%" << endl; real y_ = 1 - 2 * (j / (real) height); for (int i = 0; i < width; ++i) { real x = 1 - 2 * (i / (real) width); x *= aspect_ratio; x += distribution(generator); real y = y_ + distribution(generator); quaternion target = {0, x*view_width, y*view_width, view_depth}; target = 1 + target_transform * target / target_transform; target = target / norm(target); color pixel = raytrace_S3(camera_transform, target * camera_transform, 6, objects); pixel = clip_color(pixel); cout << setw(4) << left << (int) (pixel.x * 255); cout << setw(4) << left << (int) (pixel.y * 255); cout << setw(4) << left << (int) (pixel.z * 255); cout << " "; } cout << endl; } return EXIT_SUCCESS; }
33.242604
95
0.556782
[ "vector" ]
afb2dd2f064384da39904f6aceead4fa915a80f2
5,184
cc
C++
paddle/fluid/framework/async_executor.cc
PeterRK/Paddle
41e19eb4319695a02b01649409ebd34cbb6350d7
[ "Apache-2.0" ]
2
2019-03-08T03:04:48.000Z
2019-03-08T03:05:15.000Z
paddle/fluid/framework/async_executor.cc
PeterRK/Paddle
41e19eb4319695a02b01649409ebd34cbb6350d7
[ "Apache-2.0" ]
null
null
null
paddle/fluid/framework/async_executor.cc
PeterRK/Paddle
41e19eb4319695a02b01649409ebd34cbb6350d7
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/fluid/framework/async_executor.h" #include "google/protobuf/io/zero_copy_stream_impl.h" #include "google/protobuf/message.h" #include "google/protobuf/text_format.h" #include "gflags/gflags.h" #include "paddle/fluid/framework/data_feed_factory.h" #include "paddle/fluid/framework/executor_thread_worker.h" #include "paddle/fluid/framework/feed_fetch_method.h" #include "paddle/fluid/framework/feed_fetch_type.h" #include "paddle/fluid/framework/lod_rank_table.h" #include "paddle/fluid/framework/lod_tensor_array.h" #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/framework/reader.h" #include "paddle/fluid/inference/io.h" #include "paddle/fluid/platform/place.h" #include "paddle/fluid/pybind/pybind.h" namespace paddle { namespace framework { AsyncExecutor::AsyncExecutor(Scope* scope, const platform::Place& place) : root_scope_(scope), place_(place) {} void AsyncExecutor::CreateThreads( ExecutorThreadWorker* worker, const ProgramDesc& main_program, const std::shared_ptr<DataFeed>& reader, const std::vector<std::string>& fetch_var_names, Scope* root_scope, const int thread_index, const bool debug) { worker->SetThreadId(thread_index); worker->SetDebug(debug); worker->SetRootScope(root_scope); worker->CreateThreadResource(main_program, place_); worker->SetDataFeed(reader); worker->SetFetchVarNames(fetch_var_names); worker->BindingDataFeedMemory(); } void PrepareReaders(std::vector<std::shared_ptr<DataFeed>>& readers, // NOLINT const int thread_num, const DataFeedDesc& data_feed_desc, const std::vector<std::string>& filelist) { readers.resize(thread_num); for (size_t i = 0; i < readers.size(); ++i) { readers[i] = DataFeedFactory::CreateDataFeed(data_feed_desc.name()); readers[i]->Init(data_feed_desc); // set batch_size and queue_size here } readers[0]->SetFileList(filelist); } void AsyncExecutor::RunFromFile(const ProgramDesc& main_program, const std::string& data_feed_desc_str, const std::vector<std::string>& filelist, const int thread_num, const std::vector<std::string>& fetch_var_names, const bool debug) { std::vector<std::thread> threads; auto& block = main_program.Block(0); for (auto var_name : fetch_var_names) { auto var_desc = block.FindVar(var_name); auto shapes = var_desc->GetShape(); PADDLE_ENFORCE(shapes[shapes.size() - 1] == 1, "var %s: Fetched var has wrong shape, " "only variables with the last dimension size 1 supported", var_name); } DataFeedDesc data_feed_desc; google::protobuf::TextFormat::ParseFromString(data_feed_desc_str, &data_feed_desc); int actual_thread_num = thread_num; int file_cnt = filelist.size(); PADDLE_ENFORCE(file_cnt > 0, "File list cannot be empty"); if (actual_thread_num > file_cnt) { VLOG(1) << "Thread num = " << thread_num << ", file num = " << file_cnt << ". Changing thread_num = " << file_cnt; actual_thread_num = file_cnt; } /* readerDesc: protobuf description for reader initlization argument: class_name, batch_size, use_slot, queue_size, buffer_size, padding_index reader: 1) each thread has a reader, reader will read input data and put it into input queue 2) each reader has a Next() iterface, that can fetch an instance from the input queue */ // todo: should be factory method for creating datafeed std::vector<std::shared_ptr<DataFeed>> readers; PrepareReaders(readers, actual_thread_num, data_feed_desc, filelist); std::vector<std::shared_ptr<ExecutorThreadWorker>> workers; workers.resize(actual_thread_num); for (auto& worker : workers) { worker.reset(new ExecutorThreadWorker); } // prepare thread resource here for (int thidx = 0; thidx < actual_thread_num; ++thidx) { CreateThreads(workers[thidx].get(), main_program, readers[thidx], fetch_var_names, root_scope_, thidx, debug); } // start executing ops in multiple threads for (int thidx = 0; thidx < actual_thread_num; ++thidx) { threads.push_back( std::thread(&ExecutorThreadWorker::TrainFiles, workers[thidx].get())); } for (auto& th : threads) { th.join(); } root_scope_->DropKids(); return; } } // einit_modelnd namespace framework } // end namespace paddle
37.294964
80
0.69483
[ "shape", "vector" ]
afb7ffc78bb21f2408751a7cb56a24cf73c3ffc8
781
hpp
C++
source/tetris/tetris.hpp
menteralgo/tetris
1aa23b848a7694e3516d07029fdba5534a926edf
[ "MIT" ]
null
null
null
source/tetris/tetris.hpp
menteralgo/tetris
1aa23b848a7694e3516d07029fdba5534a926edf
[ "MIT" ]
null
null
null
source/tetris/tetris.hpp
menteralgo/tetris
1aa23b848a7694e3516d07029fdba5534a926edf
[ "MIT" ]
null
null
null
#pragma once #include "gn.hpp" using namespace gn; namespace tet { #define FIELD_WIDTH 10 #define FIELD_HEIGHT 20 #define SQUARE_SIZE 25 #define POLIES_NUM 7 #define NPB_WIDTH 4 #define NPB_HEIGHT 4 typedef void (*tetris_state)(); struct Polyomino { std::vector<vectorInt2> coords; uint8_t type; Polyomino() { } Polyomino(uint8_t type, std::vector<vectorInt2> data); void rotate(); }; void initTetris(); vectorInt2 putPolyomino(vectorInt2 position, const Polyomino &poly, uint8_t dest[][FIELD_HEIGHT]); uint8_t getCell(int x, int y); uint8_t getNextPolyCell(int x, int y); void runTetris(); void movePolyLeft(); void movePolyRight(); void rotatePoly(); }
19.525
102
0.641485
[ "vector" ]
afc4718f56bfcd39b4bedadd1f1b394a94a21174
3,047
cpp
C++
cartridge/cartridgeloader.cpp
spreetin/nesemu
0d9ca5a26f1ef6d1c99545f30ae52d4f7c093cb1
[ "MIT" ]
null
null
null
cartridge/cartridgeloader.cpp
spreetin/nesemu
0d9ca5a26f1ef6d1c99545f30ae52d4f7c093cb1
[ "MIT" ]
null
null
null
cartridge/cartridgeloader.cpp
spreetin/nesemu
0d9ca5a26f1ef6d1c99545f30ae52d4f7c093cb1
[ "MIT" ]
null
null
null
#include "cartridgeloader.h" #include "mappers/mapper_selecter.h" #include <fstream> #include <array> CartridgeLoader::CartridgeLoader() { } Cartridge *CartridgeLoader::loadFile(std::string filename) { iNES_Header header; std::vector<Byte> prgROM; std::vector<Byte> chrROM; bool ines2 = true; std::ifstream file(filename, std::ios::binary); file.read(reinterpret_cast<char*>(header.full), 16); //file >> header.full; if (!(header.Flags7.b3 && !header.Flags7.b2)){ ines2 = false; } std::vector<Byte> trainer; if (header.Flags6.b2){ trainer.resize(512); file.read(reinterpret_cast<char*>(trainer.data()), 512); } Word prglen; if (ines2){ if ((header.Flags9.byte & 0x0F) == 0xF){ prglen = (1 << ((header.PRGROM_Size & 0xF0) >> 4)) * (((header.PRGROM_Size & 0x0F) * 2) + 1); } else { prglen = header.PRGROM_Size + ((Word)(header.Flags9.byte & 0x0F) << 8); } } else { prglen = header.PRGROM_Size; } prgROM.resize(prglen*(long long)(16*1024)); file.read(reinterpret_cast<char*>(prgROM.data()), prglen*(long long)(16*1024)); Word chrlen; if (ines2){ if ((header.Flags9.byte & 0xF0) == 0xF0){ chrlen = (1 << ((header.CHRROM_Size & 0xF0) >> 4)) * (((header.CHRROM_Size & 0x0F) * 2) + 1); } else { chrlen = header.CHRROM_Size + ((Word)(header.Flags9.byte & 0xF0) << 4); } } else { chrlen = header.CHRROM_Size; } chrROM.resize(chrlen*(long long)(16*1024)); file.read(reinterpret_cast<char*>(chrROM.data()), chrlen*(long long)(16*1024)); Word mapperID = ((header.Flags6.byte & 0xF0) >> 4) | (header.Flags7.byte & 0xF0); if (ines2){ mapperID |= ((header.Flags8.byte & 0x0F) << 8); } Byte submapper = (header.Flags8.byte & 0xF0) >> 4; Word prgRAMsize = 0; Word prgNVRAMsize = 0; if (ines2){ if (header.Flags10.byte & 0x0F){ prgRAMsize = 64 << (header.Flags10.byte & 0x0F); } if (header.Flags10.byte & 0xF0){ prgNVRAMsize = 64 << ((header.Flags10.byte & 0xF0) >> 4); } } else { if (header.Flags10.b4){ prgRAMsize = header.Flags8.byte * (8*1024); } else { prgRAMsize = 0; } } Word chrRAMsize = 0; Word chrNVRAMsize = 0; if (header.Flags11.byte & 0x0F){ chrRAMsize = 64 << (header.Flags11.byte & 0x0F); } if (header.Flags11.byte & 0xF0){ chrNVRAMsize = 64 << ((header.Flags11.byte & 0xF0) >> 4); } TimingMode mode; switch (header.Flags12.byte & 0x03){ case 0: mode = NTSC; break; case 1: mode = PAL; break; case 2: mode = Multi; break; default: mode = Dendy; break; } Cartridge *cart = getCorrectMapper(mapperID, header, prgROM, chrROM); cart->setPRGRAM(prgRAMsize, prgNVRAMsize); if (ines2){ cart->setCHRRAM(chrRAMsize, chrNVRAMsize); } return cart; }
30.777778
105
0.566131
[ "vector" ]
afc53e9e336571bbac552d550503cc28be879284
27,784
cpp
C++
exchange/generated/src/ServerAsyncClient.cpp
danpape/mmx-node
99bae72a5135c9b208af9f402c0259351e8da151
[ "Apache-2.0" ]
null
null
null
exchange/generated/src/ServerAsyncClient.cpp
danpape/mmx-node
99bae72a5135c9b208af9f402c0259351e8da151
[ "Apache-2.0" ]
null
null
null
exchange/generated/src/ServerAsyncClient.cpp
danpape/mmx-node
99bae72a5135c9b208af9f402c0259351e8da151
[ "Apache-2.0" ]
null
null
null
// AUTO GENERATED by vnxcppcodegen #include <mmx/exchange/package.hxx> #include <mmx/exchange/ServerAsyncClient.hxx> #include <mmx/Block.hxx> #include <mmx/Transaction.hxx> #include <mmx/addr_t.hpp> #include <mmx/exchange/Server_approve.hxx> #include <mmx/exchange/Server_approve_return.hxx> #include <mmx/exchange/Server_cancel.hxx> #include <mmx/exchange/Server_cancel_return.hxx> #include <mmx/exchange/Server_execute.hxx> #include <mmx/exchange/Server_execute_return.hxx> #include <mmx/exchange/Server_get_orders.hxx> #include <mmx/exchange/Server_get_orders_return.hxx> #include <mmx/exchange/Server_get_price.hxx> #include <mmx/exchange/Server_get_price_return.hxx> #include <mmx/exchange/Server_match.hxx> #include <mmx/exchange/Server_match_return.hxx> #include <mmx/exchange/Server_place.hxx> #include <mmx/exchange/Server_place_return.hxx> #include <mmx/exchange/Server_reject.hxx> #include <mmx/exchange/Server_reject_return.hxx> #include <mmx/exchange/amount_t.hxx> #include <mmx/exchange/limit_order_t.hxx> #include <mmx/exchange/matched_order_t.hxx> #include <mmx/exchange/order_t.hxx> #include <mmx/exchange/trade_order_t.hxx> #include <mmx/exchange/trade_pair_t.hxx> #include <mmx/hash_t.hpp> #include <mmx/txio_key_t.hxx> #include <mmx/ulong_fraction_t.hxx> #include <vnx/ModuleInterface_vnx_get_config.hxx> #include <vnx/ModuleInterface_vnx_get_config_return.hxx> #include <vnx/ModuleInterface_vnx_get_config_object.hxx> #include <vnx/ModuleInterface_vnx_get_config_object_return.hxx> #include <vnx/ModuleInterface_vnx_get_module_info.hxx> #include <vnx/ModuleInterface_vnx_get_module_info_return.hxx> #include <vnx/ModuleInterface_vnx_get_type_code.hxx> #include <vnx/ModuleInterface_vnx_get_type_code_return.hxx> #include <vnx/ModuleInterface_vnx_restart.hxx> #include <vnx/ModuleInterface_vnx_restart_return.hxx> #include <vnx/ModuleInterface_vnx_self_test.hxx> #include <vnx/ModuleInterface_vnx_self_test_return.hxx> #include <vnx/ModuleInterface_vnx_set_config.hxx> #include <vnx/ModuleInterface_vnx_set_config_return.hxx> #include <vnx/ModuleInterface_vnx_set_config_object.hxx> #include <vnx/ModuleInterface_vnx_set_config_object_return.hxx> #include <vnx/ModuleInterface_vnx_stop.hxx> #include <vnx/ModuleInterface_vnx_stop_return.hxx> #include <vnx/TopicPtr.hpp> #include <vnx/addons/MsgServer.h> #include <vnx/Generic.hxx> #include <vnx/vnx.h> namespace mmx { namespace exchange { ServerAsyncClient::ServerAsyncClient(const std::string& service_name) : AsyncClient::AsyncClient(vnx::Hash64(service_name)) { } ServerAsyncClient::ServerAsyncClient(vnx::Hash64 service_addr) : AsyncClient::AsyncClient(service_addr) { } uint64_t ServerAsyncClient::vnx_get_config_object(const std::function<void(const ::vnx::Object&)>& _callback, const std::function<void(const vnx::exception&)>& _error_callback) { auto _method = ::vnx::ModuleInterface_vnx_get_config_object::create(); const auto _request_id = ++vnx_next_id; { std::lock_guard<std::mutex> _lock(vnx_mutex); vnx_pending[_request_id] = 0; vnx_queue_vnx_get_config_object[_request_id] = std::make_pair(_callback, _error_callback); } vnx_request(_method, _request_id); return _request_id; } uint64_t ServerAsyncClient::vnx_get_config(const std::string& name, const std::function<void(const ::vnx::Variant&)>& _callback, const std::function<void(const vnx::exception&)>& _error_callback) { auto _method = ::vnx::ModuleInterface_vnx_get_config::create(); _method->name = name; const auto _request_id = ++vnx_next_id; { std::lock_guard<std::mutex> _lock(vnx_mutex); vnx_pending[_request_id] = 1; vnx_queue_vnx_get_config[_request_id] = std::make_pair(_callback, _error_callback); } vnx_request(_method, _request_id); return _request_id; } uint64_t ServerAsyncClient::vnx_set_config_object(const ::vnx::Object& config, const std::function<void()>& _callback, const std::function<void(const vnx::exception&)>& _error_callback) { auto _method = ::vnx::ModuleInterface_vnx_set_config_object::create(); _method->config = config; const auto _request_id = ++vnx_next_id; { std::lock_guard<std::mutex> _lock(vnx_mutex); vnx_pending[_request_id] = 2; vnx_queue_vnx_set_config_object[_request_id] = std::make_pair(_callback, _error_callback); } vnx_request(_method, _request_id); return _request_id; } uint64_t ServerAsyncClient::vnx_set_config(const std::string& name, const ::vnx::Variant& value, const std::function<void()>& _callback, const std::function<void(const vnx::exception&)>& _error_callback) { auto _method = ::vnx::ModuleInterface_vnx_set_config::create(); _method->name = name; _method->value = value; const auto _request_id = ++vnx_next_id; { std::lock_guard<std::mutex> _lock(vnx_mutex); vnx_pending[_request_id] = 3; vnx_queue_vnx_set_config[_request_id] = std::make_pair(_callback, _error_callback); } vnx_request(_method, _request_id); return _request_id; } uint64_t ServerAsyncClient::vnx_get_type_code(const std::function<void(const ::vnx::TypeCode&)>& _callback, const std::function<void(const vnx::exception&)>& _error_callback) { auto _method = ::vnx::ModuleInterface_vnx_get_type_code::create(); const auto _request_id = ++vnx_next_id; { std::lock_guard<std::mutex> _lock(vnx_mutex); vnx_pending[_request_id] = 4; vnx_queue_vnx_get_type_code[_request_id] = std::make_pair(_callback, _error_callback); } vnx_request(_method, _request_id); return _request_id; } uint64_t ServerAsyncClient::vnx_get_module_info(const std::function<void(std::shared_ptr<const ::vnx::ModuleInfo>)>& _callback, const std::function<void(const vnx::exception&)>& _error_callback) { auto _method = ::vnx::ModuleInterface_vnx_get_module_info::create(); const auto _request_id = ++vnx_next_id; { std::lock_guard<std::mutex> _lock(vnx_mutex); vnx_pending[_request_id] = 5; vnx_queue_vnx_get_module_info[_request_id] = std::make_pair(_callback, _error_callback); } vnx_request(_method, _request_id); return _request_id; } uint64_t ServerAsyncClient::vnx_restart(const std::function<void()>& _callback, const std::function<void(const vnx::exception&)>& _error_callback) { auto _method = ::vnx::ModuleInterface_vnx_restart::create(); const auto _request_id = ++vnx_next_id; { std::lock_guard<std::mutex> _lock(vnx_mutex); vnx_pending[_request_id] = 6; vnx_queue_vnx_restart[_request_id] = std::make_pair(_callback, _error_callback); } vnx_request(_method, _request_id); return _request_id; } uint64_t ServerAsyncClient::vnx_stop(const std::function<void()>& _callback, const std::function<void(const vnx::exception&)>& _error_callback) { auto _method = ::vnx::ModuleInterface_vnx_stop::create(); const auto _request_id = ++vnx_next_id; { std::lock_guard<std::mutex> _lock(vnx_mutex); vnx_pending[_request_id] = 7; vnx_queue_vnx_stop[_request_id] = std::make_pair(_callback, _error_callback); } vnx_request(_method, _request_id); return _request_id; } uint64_t ServerAsyncClient::vnx_self_test(const std::function<void(const vnx::bool_t&)>& _callback, const std::function<void(const vnx::exception&)>& _error_callback) { auto _method = ::vnx::ModuleInterface_vnx_self_test::create(); const auto _request_id = ++vnx_next_id; { std::lock_guard<std::mutex> _lock(vnx_mutex); vnx_pending[_request_id] = 8; vnx_queue_vnx_self_test[_request_id] = std::make_pair(_callback, _error_callback); } vnx_request(_method, _request_id); return _request_id; } uint64_t ServerAsyncClient::execute(std::shared_ptr<const ::mmx::Transaction> tx, const std::function<void()>& _callback, const std::function<void(const vnx::exception&)>& _error_callback) { auto _method = ::mmx::exchange::Server_execute::create(); _method->tx = tx; const auto _request_id = ++vnx_next_id; { std::lock_guard<std::mutex> _lock(vnx_mutex); vnx_pending[_request_id] = 9; vnx_queue_execute[_request_id] = std::make_pair(_callback, _error_callback); } vnx_request(_method, _request_id); return _request_id; } uint64_t ServerAsyncClient::match(const ::mmx::exchange::trade_pair_t& pair, const ::mmx::exchange::trade_order_t& order, const std::function<void(const ::mmx::exchange::matched_order_t&)>& _callback, const std::function<void(const vnx::exception&)>& _error_callback) { auto _method = ::mmx::exchange::Server_match::create(); _method->pair = pair; _method->order = order; const auto _request_id = ++vnx_next_id; { std::lock_guard<std::mutex> _lock(vnx_mutex); vnx_pending[_request_id] = 10; vnx_queue_match[_request_id] = std::make_pair(_callback, _error_callback); } vnx_request(_method, _request_id); return _request_id; } uint64_t ServerAsyncClient::get_orders(const ::mmx::exchange::trade_pair_t& pair, const std::function<void(const std::vector<::mmx::exchange::order_t>&)>& _callback, const std::function<void(const vnx::exception&)>& _error_callback) { auto _method = ::mmx::exchange::Server_get_orders::create(); _method->pair = pair; const auto _request_id = ++vnx_next_id; { std::lock_guard<std::mutex> _lock(vnx_mutex); vnx_pending[_request_id] = 11; vnx_queue_get_orders[_request_id] = std::make_pair(_callback, _error_callback); } vnx_request(_method, _request_id); return _request_id; } uint64_t ServerAsyncClient::get_price(const ::mmx::addr_t& want, const ::mmx::exchange::amount_t& have, const std::function<void(const ::mmx::ulong_fraction_t&)>& _callback, const std::function<void(const vnx::exception&)>& _error_callback) { auto _method = ::mmx::exchange::Server_get_price::create(); _method->want = want; _method->have = have; const auto _request_id = ++vnx_next_id; { std::lock_guard<std::mutex> _lock(vnx_mutex); vnx_pending[_request_id] = 12; vnx_queue_get_price[_request_id] = std::make_pair(_callback, _error_callback); } vnx_request(_method, _request_id); return _request_id; } uint64_t ServerAsyncClient::place(const uint64_t& client, const ::mmx::exchange::trade_pair_t& pair, const ::mmx::exchange::limit_order_t& order, const std::function<void(const std::vector<::mmx::exchange::order_t>&)>& _callback, const std::function<void(const vnx::exception&)>& _error_callback) { auto _method = ::mmx::exchange::Server_place::create(); _method->client = client; _method->pair = pair; _method->order = order; const auto _request_id = ++vnx_next_id; { std::lock_guard<std::mutex> _lock(vnx_mutex); vnx_pending[_request_id] = 13; vnx_queue_place[_request_id] = std::make_pair(_callback, _error_callback); } vnx_request(_method, _request_id); return _request_id; } uint64_t ServerAsyncClient::cancel(const uint64_t& client, const std::vector<::mmx::txio_key_t>& orders, const std::function<void()>& _callback, const std::function<void(const vnx::exception&)>& _error_callback) { auto _method = ::mmx::exchange::Server_cancel::create(); _method->client = client; _method->orders = orders; const auto _request_id = ++vnx_next_id; { std::lock_guard<std::mutex> _lock(vnx_mutex); vnx_pending[_request_id] = 14; vnx_queue_cancel[_request_id] = std::make_pair(_callback, _error_callback); } vnx_request(_method, _request_id); return _request_id; } uint64_t ServerAsyncClient::reject(const uint64_t& client, const ::mmx::hash_t& txid, const std::function<void()>& _callback, const std::function<void(const vnx::exception&)>& _error_callback) { auto _method = ::mmx::exchange::Server_reject::create(); _method->client = client; _method->txid = txid; const auto _request_id = ++vnx_next_id; { std::lock_guard<std::mutex> _lock(vnx_mutex); vnx_pending[_request_id] = 15; vnx_queue_reject[_request_id] = std::make_pair(_callback, _error_callback); } vnx_request(_method, _request_id); return _request_id; } uint64_t ServerAsyncClient::approve(const uint64_t& client, std::shared_ptr<const ::mmx::Transaction> tx, const std::function<void()>& _callback, const std::function<void(const vnx::exception&)>& _error_callback) { auto _method = ::mmx::exchange::Server_approve::create(); _method->client = client; _method->tx = tx; const auto _request_id = ++vnx_next_id; { std::lock_guard<std::mutex> _lock(vnx_mutex); vnx_pending[_request_id] = 16; vnx_queue_approve[_request_id] = std::make_pair(_callback, _error_callback); } vnx_request(_method, _request_id); return _request_id; } int32_t ServerAsyncClient::vnx_purge_request(uint64_t _request_id, const vnx::exception& _ex) { std::unique_lock<std::mutex> _lock(vnx_mutex); const auto _iter = vnx_pending.find(_request_id); if(_iter == vnx_pending.end()) { return -1; } const auto _index = _iter->second; vnx_pending.erase(_iter); switch(_index) { case 0: { const auto _iter = vnx_queue_vnx_get_config_object.find(_request_id); if(_iter != vnx_queue_vnx_get_config_object.end()) { const auto _callback = std::move(_iter->second.second); vnx_queue_vnx_get_config_object.erase(_iter); _lock.unlock(); if(_callback) { _callback(_ex); } } break; } case 1: { const auto _iter = vnx_queue_vnx_get_config.find(_request_id); if(_iter != vnx_queue_vnx_get_config.end()) { const auto _callback = std::move(_iter->second.second); vnx_queue_vnx_get_config.erase(_iter); _lock.unlock(); if(_callback) { _callback(_ex); } } break; } case 2: { const auto _iter = vnx_queue_vnx_set_config_object.find(_request_id); if(_iter != vnx_queue_vnx_set_config_object.end()) { const auto _callback = std::move(_iter->second.second); vnx_queue_vnx_set_config_object.erase(_iter); _lock.unlock(); if(_callback) { _callback(_ex); } } break; } case 3: { const auto _iter = vnx_queue_vnx_set_config.find(_request_id); if(_iter != vnx_queue_vnx_set_config.end()) { const auto _callback = std::move(_iter->second.second); vnx_queue_vnx_set_config.erase(_iter); _lock.unlock(); if(_callback) { _callback(_ex); } } break; } case 4: { const auto _iter = vnx_queue_vnx_get_type_code.find(_request_id); if(_iter != vnx_queue_vnx_get_type_code.end()) { const auto _callback = std::move(_iter->second.second); vnx_queue_vnx_get_type_code.erase(_iter); _lock.unlock(); if(_callback) { _callback(_ex); } } break; } case 5: { const auto _iter = vnx_queue_vnx_get_module_info.find(_request_id); if(_iter != vnx_queue_vnx_get_module_info.end()) { const auto _callback = std::move(_iter->second.second); vnx_queue_vnx_get_module_info.erase(_iter); _lock.unlock(); if(_callback) { _callback(_ex); } } break; } case 6: { const auto _iter = vnx_queue_vnx_restart.find(_request_id); if(_iter != vnx_queue_vnx_restart.end()) { const auto _callback = std::move(_iter->second.second); vnx_queue_vnx_restart.erase(_iter); _lock.unlock(); if(_callback) { _callback(_ex); } } break; } case 7: { const auto _iter = vnx_queue_vnx_stop.find(_request_id); if(_iter != vnx_queue_vnx_stop.end()) { const auto _callback = std::move(_iter->second.second); vnx_queue_vnx_stop.erase(_iter); _lock.unlock(); if(_callback) { _callback(_ex); } } break; } case 8: { const auto _iter = vnx_queue_vnx_self_test.find(_request_id); if(_iter != vnx_queue_vnx_self_test.end()) { const auto _callback = std::move(_iter->second.second); vnx_queue_vnx_self_test.erase(_iter); _lock.unlock(); if(_callback) { _callback(_ex); } } break; } case 9: { const auto _iter = vnx_queue_execute.find(_request_id); if(_iter != vnx_queue_execute.end()) { const auto _callback = std::move(_iter->second.second); vnx_queue_execute.erase(_iter); _lock.unlock(); if(_callback) { _callback(_ex); } } break; } case 10: { const auto _iter = vnx_queue_match.find(_request_id); if(_iter != vnx_queue_match.end()) { const auto _callback = std::move(_iter->second.second); vnx_queue_match.erase(_iter); _lock.unlock(); if(_callback) { _callback(_ex); } } break; } case 11: { const auto _iter = vnx_queue_get_orders.find(_request_id); if(_iter != vnx_queue_get_orders.end()) { const auto _callback = std::move(_iter->second.second); vnx_queue_get_orders.erase(_iter); _lock.unlock(); if(_callback) { _callback(_ex); } } break; } case 12: { const auto _iter = vnx_queue_get_price.find(_request_id); if(_iter != vnx_queue_get_price.end()) { const auto _callback = std::move(_iter->second.second); vnx_queue_get_price.erase(_iter); _lock.unlock(); if(_callback) { _callback(_ex); } } break; } case 13: { const auto _iter = vnx_queue_place.find(_request_id); if(_iter != vnx_queue_place.end()) { const auto _callback = std::move(_iter->second.second); vnx_queue_place.erase(_iter); _lock.unlock(); if(_callback) { _callback(_ex); } } break; } case 14: { const auto _iter = vnx_queue_cancel.find(_request_id); if(_iter != vnx_queue_cancel.end()) { const auto _callback = std::move(_iter->second.second); vnx_queue_cancel.erase(_iter); _lock.unlock(); if(_callback) { _callback(_ex); } } break; } case 15: { const auto _iter = vnx_queue_reject.find(_request_id); if(_iter != vnx_queue_reject.end()) { const auto _callback = std::move(_iter->second.second); vnx_queue_reject.erase(_iter); _lock.unlock(); if(_callback) { _callback(_ex); } } break; } case 16: { const auto _iter = vnx_queue_approve.find(_request_id); if(_iter != vnx_queue_approve.end()) { const auto _callback = std::move(_iter->second.second); vnx_queue_approve.erase(_iter); _lock.unlock(); if(_callback) { _callback(_ex); } } break; } } return _index; } int32_t ServerAsyncClient::vnx_callback_switch(uint64_t _request_id, std::shared_ptr<const vnx::Value> _value) { std::unique_lock<std::mutex> _lock(vnx_mutex); const auto _iter = vnx_pending.find(_request_id); if(_iter == vnx_pending.end()) { throw std::runtime_error("ServerAsyncClient: received unknown return"); } const auto _index = _iter->second; vnx_pending.erase(_iter); switch(_index) { case 0: { const auto _iter = vnx_queue_vnx_get_config_object.find(_request_id); if(_iter == vnx_queue_vnx_get_config_object.end()) { throw std::runtime_error("ServerAsyncClient: callback not found"); } const auto _callback = std::move(_iter->second.first); vnx_queue_vnx_get_config_object.erase(_iter); _lock.unlock(); if(_callback) { if(auto _result = std::dynamic_pointer_cast<const ::vnx::ModuleInterface_vnx_get_config_object_return>(_value)) { _callback(_result->_ret_0); } else if(_value && !_value->is_void()) { _callback(_value->get_field_by_index(0).to<::vnx::Object>()); } else { throw std::logic_error("ServerAsyncClient: invalid return value"); } } break; } case 1: { const auto _iter = vnx_queue_vnx_get_config.find(_request_id); if(_iter == vnx_queue_vnx_get_config.end()) { throw std::runtime_error("ServerAsyncClient: callback not found"); } const auto _callback = std::move(_iter->second.first); vnx_queue_vnx_get_config.erase(_iter); _lock.unlock(); if(_callback) { if(auto _result = std::dynamic_pointer_cast<const ::vnx::ModuleInterface_vnx_get_config_return>(_value)) { _callback(_result->_ret_0); } else if(_value && !_value->is_void()) { _callback(_value->get_field_by_index(0).to<::vnx::Variant>()); } else { throw std::logic_error("ServerAsyncClient: invalid return value"); } } break; } case 2: { const auto _iter = vnx_queue_vnx_set_config_object.find(_request_id); if(_iter == vnx_queue_vnx_set_config_object.end()) { throw std::runtime_error("ServerAsyncClient: callback not found"); } const auto _callback = std::move(_iter->second.first); vnx_queue_vnx_set_config_object.erase(_iter); _lock.unlock(); if(_callback) { _callback(); } break; } case 3: { const auto _iter = vnx_queue_vnx_set_config.find(_request_id); if(_iter == vnx_queue_vnx_set_config.end()) { throw std::runtime_error("ServerAsyncClient: callback not found"); } const auto _callback = std::move(_iter->second.first); vnx_queue_vnx_set_config.erase(_iter); _lock.unlock(); if(_callback) { _callback(); } break; } case 4: { const auto _iter = vnx_queue_vnx_get_type_code.find(_request_id); if(_iter == vnx_queue_vnx_get_type_code.end()) { throw std::runtime_error("ServerAsyncClient: callback not found"); } const auto _callback = std::move(_iter->second.first); vnx_queue_vnx_get_type_code.erase(_iter); _lock.unlock(); if(_callback) { if(auto _result = std::dynamic_pointer_cast<const ::vnx::ModuleInterface_vnx_get_type_code_return>(_value)) { _callback(_result->_ret_0); } else if(_value && !_value->is_void()) { _callback(_value->get_field_by_index(0).to<::vnx::TypeCode>()); } else { throw std::logic_error("ServerAsyncClient: invalid return value"); } } break; } case 5: { const auto _iter = vnx_queue_vnx_get_module_info.find(_request_id); if(_iter == vnx_queue_vnx_get_module_info.end()) { throw std::runtime_error("ServerAsyncClient: callback not found"); } const auto _callback = std::move(_iter->second.first); vnx_queue_vnx_get_module_info.erase(_iter); _lock.unlock(); if(_callback) { if(auto _result = std::dynamic_pointer_cast<const ::vnx::ModuleInterface_vnx_get_module_info_return>(_value)) { _callback(_result->_ret_0); } else if(_value && !_value->is_void()) { _callback(_value->get_field_by_index(0).to<std::shared_ptr<const ::vnx::ModuleInfo>>()); } else { throw std::logic_error("ServerAsyncClient: invalid return value"); } } break; } case 6: { const auto _iter = vnx_queue_vnx_restart.find(_request_id); if(_iter == vnx_queue_vnx_restart.end()) { throw std::runtime_error("ServerAsyncClient: callback not found"); } const auto _callback = std::move(_iter->second.first); vnx_queue_vnx_restart.erase(_iter); _lock.unlock(); if(_callback) { _callback(); } break; } case 7: { const auto _iter = vnx_queue_vnx_stop.find(_request_id); if(_iter == vnx_queue_vnx_stop.end()) { throw std::runtime_error("ServerAsyncClient: callback not found"); } const auto _callback = std::move(_iter->second.first); vnx_queue_vnx_stop.erase(_iter); _lock.unlock(); if(_callback) { _callback(); } break; } case 8: { const auto _iter = vnx_queue_vnx_self_test.find(_request_id); if(_iter == vnx_queue_vnx_self_test.end()) { throw std::runtime_error("ServerAsyncClient: callback not found"); } const auto _callback = std::move(_iter->second.first); vnx_queue_vnx_self_test.erase(_iter); _lock.unlock(); if(_callback) { if(auto _result = std::dynamic_pointer_cast<const ::vnx::ModuleInterface_vnx_self_test_return>(_value)) { _callback(_result->_ret_0); } else if(_value && !_value->is_void()) { _callback(_value->get_field_by_index(0).to<vnx::bool_t>()); } else { throw std::logic_error("ServerAsyncClient: invalid return value"); } } break; } case 9: { const auto _iter = vnx_queue_execute.find(_request_id); if(_iter == vnx_queue_execute.end()) { throw std::runtime_error("ServerAsyncClient: callback not found"); } const auto _callback = std::move(_iter->second.first); vnx_queue_execute.erase(_iter); _lock.unlock(); if(_callback) { _callback(); } break; } case 10: { const auto _iter = vnx_queue_match.find(_request_id); if(_iter == vnx_queue_match.end()) { throw std::runtime_error("ServerAsyncClient: callback not found"); } const auto _callback = std::move(_iter->second.first); vnx_queue_match.erase(_iter); _lock.unlock(); if(_callback) { if(auto _result = std::dynamic_pointer_cast<const ::mmx::exchange::Server_match_return>(_value)) { _callback(_result->_ret_0); } else if(_value && !_value->is_void()) { _callback(_value->get_field_by_index(0).to<::mmx::exchange::matched_order_t>()); } else { throw std::logic_error("ServerAsyncClient: invalid return value"); } } break; } case 11: { const auto _iter = vnx_queue_get_orders.find(_request_id); if(_iter == vnx_queue_get_orders.end()) { throw std::runtime_error("ServerAsyncClient: callback not found"); } const auto _callback = std::move(_iter->second.first); vnx_queue_get_orders.erase(_iter); _lock.unlock(); if(_callback) { if(auto _result = std::dynamic_pointer_cast<const ::mmx::exchange::Server_get_orders_return>(_value)) { _callback(_result->_ret_0); } else if(_value && !_value->is_void()) { _callback(_value->get_field_by_index(0).to<std::vector<::mmx::exchange::order_t>>()); } else { throw std::logic_error("ServerAsyncClient: invalid return value"); } } break; } case 12: { const auto _iter = vnx_queue_get_price.find(_request_id); if(_iter == vnx_queue_get_price.end()) { throw std::runtime_error("ServerAsyncClient: callback not found"); } const auto _callback = std::move(_iter->second.first); vnx_queue_get_price.erase(_iter); _lock.unlock(); if(_callback) { if(auto _result = std::dynamic_pointer_cast<const ::mmx::exchange::Server_get_price_return>(_value)) { _callback(_result->_ret_0); } else if(_value && !_value->is_void()) { _callback(_value->get_field_by_index(0).to<::mmx::ulong_fraction_t>()); } else { throw std::logic_error("ServerAsyncClient: invalid return value"); } } break; } case 13: { const auto _iter = vnx_queue_place.find(_request_id); if(_iter == vnx_queue_place.end()) { throw std::runtime_error("ServerAsyncClient: callback not found"); } const auto _callback = std::move(_iter->second.first); vnx_queue_place.erase(_iter); _lock.unlock(); if(_callback) { if(auto _result = std::dynamic_pointer_cast<const ::mmx::exchange::Server_place_return>(_value)) { _callback(_result->_ret_0); } else if(_value && !_value->is_void()) { _callback(_value->get_field_by_index(0).to<std::vector<::mmx::exchange::order_t>>()); } else { throw std::logic_error("ServerAsyncClient: invalid return value"); } } break; } case 14: { const auto _iter = vnx_queue_cancel.find(_request_id); if(_iter == vnx_queue_cancel.end()) { throw std::runtime_error("ServerAsyncClient: callback not found"); } const auto _callback = std::move(_iter->second.first); vnx_queue_cancel.erase(_iter); _lock.unlock(); if(_callback) { _callback(); } break; } case 15: { const auto _iter = vnx_queue_reject.find(_request_id); if(_iter == vnx_queue_reject.end()) { throw std::runtime_error("ServerAsyncClient: callback not found"); } const auto _callback = std::move(_iter->second.first); vnx_queue_reject.erase(_iter); _lock.unlock(); if(_callback) { _callback(); } break; } case 16: { const auto _iter = vnx_queue_approve.find(_request_id); if(_iter == vnx_queue_approve.end()) { throw std::runtime_error("ServerAsyncClient: callback not found"); } const auto _callback = std::move(_iter->second.first); vnx_queue_approve.erase(_iter); _lock.unlock(); if(_callback) { _callback(); } break; } default: if(_index >= 0) { throw std::logic_error("ServerAsyncClient: invalid callback index"); } } return _index; } } // namespace mmx } // namespace exchange
34.428748
298
0.715592
[ "object", "vector" ]
afd1848e2f8ce879c6989e81a1e3716f6605eaf3
7,025
cpp
C++
cplusplus/zipdu.cpp
ShiftLeftSecurity/zipdu
57b6c2c17632500c8823df07a591f7667cbe0310
[ "Apache-2.0" ]
null
null
null
cplusplus/zipdu.cpp
ShiftLeftSecurity/zipdu
57b6c2c17632500c8823df07a591f7667cbe0310
[ "Apache-2.0" ]
null
null
null
cplusplus/zipdu.cpp
ShiftLeftSecurity/zipdu
57b6c2c17632500c8823df07a591f7667cbe0310
[ "Apache-2.0" ]
1
2021-11-29T15:52:49.000Z
2021-11-29T15:52:49.000Z
#include "Poco/Exception.h" #include "Poco/File.h" #include "Poco/FileStream.h" #include "Poco/Net/HTTPRequestHandlerFactory.h" #include "Poco/Net/HTTPRequestHandler.h" #include "Poco/Net/HTTPServer.h" #include "Poco/Net/HTTPServerParams.h" #include "Poco/Net/HTTPServerRequest.h" #include "Poco/Net/HTTPServerResponse.h" #include "Poco/Net/MultipartReader.h" #include "Poco/Net/PartHandler.h" #include "Poco/Net/ServerSocket.h" #include "Poco/Path.h" #include "Poco/StreamCopier.h" #include "Poco/Util/ServerApplication.h" #include "Poco/UUIDGenerator.h" #include "Poco/Zip/ParseCallback.h" #include "Poco/Zip/ZipArchive.h" #include "Poco/Zip/ZipCommon.h" #include "Poco/Zip/ZipException.h" #include "Poco/Zip/ZipLocalFileHeader.h" #include "Poco/Zip/ZipStream.h" #include <iostream> #include <sstream> using Poco::Net::HTTPRequestHandler; using Poco::Net::HTTPRequestHandlerFactory; using Poco::Net::HTTPResponse; using Poco::Net::HTTPServer; using Poco::Net::HTTPServerParams; using Poco::Net::HTTPServerRequest; using Poco::Net::HTTPServerResponse; using Poco::Net::ServerSocket; using Poco::Path; using Poco::Util::Application; using Poco::Util::ServerApplication; using Poco::UUIDGenerator; using Poco::Zip::ParseCallback; using Poco::Zip::ZipArchive; using Poco::Zip::ZipCommon; using Poco::Zip::ZipInputStream; using Poco::Zip::ZipLocalFileHeader; class ZipParseCallback: public Poco::Zip::ParseCallback { public: std::string outputDirectory; int numberOfFiles = 0; int totalSize = 0; ZipParseCallback(std::string outputDirectory) { this->outputDirectory = outputDirectory; } bool handleZipEntry(std::istream& zipStream, const ZipLocalFileHeader& header) { if (header.isDirectory()) { std::string dirName = header.getFileName(); Path dir(Path(this->outputDirectory), dirName); dir.makeDirectory(); Poco::File aFile(dir); aFile.createDirectories(); return true; } try { std::string fileName = header.getFileName(); Path file(this->outputDirectory, fileName); file.makeFile(); Poco::FileOutputStream out(file.toString()); Poco::Zip::ZipInputStream inp(zipStream, header, false); Poco::StreamCopier::copyStream(inp, out); out.close(); Poco::File aFile(file.toString()); if (!inp.crcValid()) { throw std::runtime_error("CRC invalid."); return false; } if (aFile.getSize() != header.getUncompressedSize()) { throw std::runtime_error("Decompressed file has invalid size."); return false; } std::pair<const ZipLocalFileHeader, const Path> tmp = std::make_pair(header, file); } catch (const std::exception& e) { throw std::runtime_error(e.what()); return false; } return true; } }; class ZipStatsHandler: public HTTPRequestHandler { public: std::string uploadsDirectoryPath; ZipStatsHandler(const std::string uploadsDirectoryPath) { this->uploadsDirectoryPath = uploadsDirectoryPath; } void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response) { response.setContentType("application/json"); const unsigned int contentLength = request.getContentLength(); if (contentLength == 0) { response.setStatus(HTTPResponse::HTTPStatus::HTTP_BAD_REQUEST); response.send(); } // copy request body into char buffer char buffer[contentLength]; int size = 0; char ch; static const int eof = std::char_traits<char>::eof(); while((ch = request.stream().get()) != eof) { buffer[size] = ch; size += 1; } std::istringstream requestBody(std::string(buffer, size)); // create directory inside uploads folder auto uuid_str = UUIDGenerator().createRandom().toString(); std::cout << this->uploadsDirectoryPath; Path outputPath; outputPath.pushDirectory(this->uploadsDirectoryPath); outputPath.pushDirectory(uuid_str); Poco::File outputDirectory(outputPath.toString()); if (outputDirectory.exists()) { response.setStatus(HTTPResponse::HTTPStatus::HTTP_BAD_REQUEST); response.send(); return; } if (!outputDirectory.createDirectory()) { response.setStatus(HTTPResponse::HTTPStatus::HTTP_BAD_REQUEST); response.send(); return; } // actual unzip operation int numberOfFiles = 0; int totalSize = 0; try { ZipParseCallback parseCallback = ZipParseCallback(outputDirectory.path()); Poco::Zip::ZipArchive archive(requestBody, parseCallback); } catch (const std::exception& e) { response.setStatus(HTTPResponse::HTTPStatus::HTTP_INTERNAL_SERVER_ERROR); response.send(); return; } response.setStatus(HTTPResponse::HTTPStatus::HTTP_OK); std::ostream& ostr = response.send(); ostr << "{\"uuid\": \""<< uuid_str << "\", \"totalSize\": "<< totalSize << ", \"numberOfFiles\": " << numberOfFiles <<"}"; } }; class EmptyHandler: public HTTPRequestHandler { public: void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response) { response.setStatus(HTTPResponse::HTTPStatus::HTTP_NOT_FOUND); std::ostream& ostr = response.send(); } }; class HealthHandler: public HTTPRequestHandler { public: void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response) { response.setContentType("application/json"); std::ostream& ostr = response.send(); ostr << "{\"ok\": true}"; } }; class HandlerFactory: public HTTPRequestHandlerFactory { public: std::string uploadsDirectoryPath; HandlerFactory(const std::string uploadsDirectoryPath) { this->uploadsDirectoryPath = uploadsDirectoryPath; } HTTPRequestHandler* createRequestHandler(const HTTPServerRequest& request) { if (request.getURI() == "/zipstats" && request.getMethod() == "POST") { return new ZipStatsHandler(this->uploadsDirectoryPath); } else if (request.getURI() == "/health" && request.getMethod() == "GET") { return new HealthHandler(); } else { return new EmptyHandler(); } } }; class Server: public Poco::Util::ServerApplication { public: std::string uploadsDirectoryPath; Server(const std::string uploadsDirectoryPath) { this->uploadsDirectoryPath = uploadsDirectoryPath; } protected: int main(const std::vector<std::string>& args) { HTTPServer srv(new HandlerFactory(this->uploadsDirectoryPath), ServerSocket(8000), new HTTPServerParams); srv.start(); waitForTerminationRequest(); srv.stop(); return Application::EXIT_OK; } }; int main(int argc, char** argv) { const std::string uploadsDirectoryPath = "uploads"; Poco::File uploadsDirectory(uploadsDirectoryPath); bool exists = uploadsDirectory.exists(); if (!exists) { std::cerr << "Could not find the `uploads` directory in the folder you executed zipdu in. Exitting." << std::endl; exit(1); } std::cout << "Starting up the server." << std::endl; Server app(uploadsDirectoryPath); return app.run(argc, argv); }
31.78733
126
0.698932
[ "vector" ]
afd448af8b2a37d0fdc69f5f49c2c9ab75532f00
7,372
cpp
C++
src/level.cpp
umi0451/libchthon
bfce67f92bb945e124681221b1b7abe83c98da4b
[ "WTFPL" ]
2
2018-07-03T13:38:33.000Z
2020-07-14T12:55:19.000Z
src/level.cpp
umi0451/libchthon
bfce67f92bb945e124681221b1b7abe83c98da4b
[ "WTFPL" ]
null
null
null
src/level.cpp
umi0451/libchthon
bfce67f92bb945e124681221b1b7abe83c98da4b
[ "WTFPL" ]
null
null
null
#include "level.h" #include "game.h" #include "objects.h" #include "monsters.h" #include "items.h" #include "pathfinding.h" #include "fov.h" #include "log.h" #include "format.h" #include <cmath> #include <algorithm> namespace Chthon { Level::Level() : map(1, 1) { } Level::~Level() { } Level::Level(unsigned map_width, unsigned map_height) : map(map_width, map_height) { } const CellType & Level::cell_type_at(const Point & pos) const { return deref_default(map.cell(pos).type); } const Monster & Level::get_player() const { foreach(const Monster & monster, monsters) { if(deref_default(monster.type).faction == Monster::PLAYER) { return monster; } } static Monster empty; return empty; } Monster & Level::get_player() { foreach( Monster & monster, monsters) { if(deref_default(monster.type).faction == Monster::PLAYER) { return monster; } } static Monster empty; empty = Monster(); return empty; } CompiledInfo Level::get_info(int x, int y) const { CompiledInfo result(Point(x, y)); return result.in(monsters).in(items).in(objects).in(map); } CompiledInfo Level::get_info(const Point & pos) const { return get_info(pos.x, pos.y); } void Level::invalidate_fov(Monster & monster) { for(int x = 0; x < int(map.width()); ++x) { for(int y = 0; y < int(map.height()); ++y) { map.cell(x, y).visible = false; } } std::set<Point> visible_points = get_fov( monster.pos, deref_default(monster.type).sight, [this](const Point & p) { return get_info(p).compiled().transparent; } ); for(const Point & p : visible_points) { if(!map.valid(p)) { continue; } map.cell(p).visible = true; if(deref_default(monster.type).faction == Monster::PLAYER) { map.cell(p).seen_sprite = get_info(p).compiled().sprite; } } } std::list<Point> Level::find_path(const Point & player_pos, const Point & target) { Pathfinder pathfinder; pathfinder.lee(player_pos, target, [this](const Point & pos) { return get_info(pos).compiled().passable; }); return pathfinder.directions; } void Level::erase_dead_monsters() { monsters.erase(std::remove_if(monsters.begin(), monsters.end(), std::mem_fun_ref(&Monster::is_dead)), monsters.end()); } void DungeonBuilder::fill_room(Map<Cell> & map, const std::pair<Point, Point> & room, const CellType * type) { for(int x = room.first.x; x <= room.second.x; ++x) { for(int y = room.first.y; y <= room.second.y; ++y) { map.cell(x, y) = Cell(type); } } } std::vector<Point> DungeonBuilder::random_positions(const std::pair<Point, Point> & room, unsigned count) { std::vector<Point> result; for(unsigned i = 0; i < count; ++i) { int width = (room.second.x - room.first.x); int height = (room.second.y - room.first.y); int counter = width * height; while(--counter > 0) { int x = rand() % width + room.first.x; int y = rand() % height + room.first.y; if(result.end() == std::find(result.begin(), result.end(), Point(x, y))) { result << Point(x, y); break; } } } for(size_t i = result.size(); i < count; ++i) { result << room.first; } return result; } std::pair<Point, Point> DungeonBuilder::connect_rooms(Level & level, const std::pair<Point, Point> & a, const std::pair<Point, Point> & b, const CellType * type) { if(a.first.x < b.first.x) { int start_y = std::max(a.first.y, b.first.y); int stop_y = std::min(a.second.y, b.second.y); int way = start_y + rand() % (stop_y - start_y); for(int x = a.second.x + 1; x != b.first.x; ++x) { level.map.cell(x, way) = Cell(type); } return std::make_pair(Point(a.second.x + 1, way), Point(b.first.x - 1, way)); } if(a.first.x > b.first.x) { int start_y = std::max(a.first.y, b.first.y); int stop_y = std::min(a.second.y, b.second.y); int way = start_y + rand() % (stop_y - start_y); for(int x = b.second.x + 1; x != a.first.x; ++x) { level.map.cell(x, way) = Cell(type); } return std::make_pair(Point(b.second.x + 1, way), Point(a.first.x - 1, way)); } if(a.first.y < b.first.y) { int start_x = std::max(a.first.x, b.first.x); int stop_x = std::min(a.second.x, b.second.x); int wax = start_x + rand() % (stop_x - start_x); for(int y = a.second.y + 1; y != b.first.y; ++y) { level.map.cell(wax, y) = Cell(type); } return std::make_pair(Point(wax, a.second.y + 1), Point(wax, b.first.y - 1)); } if(a.first.y > b.first.y) { int start_x = std::max(a.first.x, b.first.x); int stop_x = std::min(a.second.x, b.second.x); int wax = start_x + rand() % (stop_x - start_x); for(int y = b.second.y + 1; y != a.first.y; ++y) { level.map.cell(wax, y) = Cell(type); } return std::make_pair(Point(wax, b.second.y + 1), Point(wax, a.first.y - 1)); } return std::make_pair(Point(), Point()); } std::vector<std::pair<Point, Point> > DungeonBuilder::shuffle_rooms(const std::vector<std::pair<Point, Point> > & rooms) { static unsigned a00[] = { 8, 1, 2, 7, 0, 3, 6, 5, 4, }; static unsigned a01[] = { 6, 7, 8, 5, 0, 1, 4, 3, 2, }; static unsigned a02[] = { 4, 5, 6, 3, 0, 7, 2, 1, 8, }; static unsigned a03[] = { 2, 3, 4, 1, 0, 5, 8, 7, 6, }; static unsigned a04[] = { 2, 1, 8, 3, 0, 7, 4, 5, 6, }; static unsigned a05[] = { 8, 7, 6, 1, 0, 5, 2, 3, 4, }; static unsigned a06[] = { 6, 5, 4, 7, 0, 3, 8, 1, 2, }; static unsigned a07[] = { 4, 3, 2, 5, 0, 1, 6, 7, 8, }; static unsigned a08[] = { 0, 1, 2, 5, 4, 3, 6, 7, 8, }; static unsigned a09[] = { 0, 1, 2, 7, 6, 3, 8, 5, 4, }; static unsigned a10[] = { 0, 1, 2, 7, 8, 3, 6, 5, 4, }; static unsigned a11[] = { 0, 5, 6, 1, 4, 7, 2, 3, 8, }; static unsigned a12[] = { 0, 7, 8, 1, 6, 5, 2, 3, 4, }; static unsigned a13[] = { 0, 7, 6, 1, 8, 5, 2, 3, 4, }; static unsigned a14[] = { 6, 7, 8, 5, 4, 3, 0, 1, 2, }; static unsigned a15[] = { 8, 5, 4, 7, 6, 3, 0, 1, 2, }; static unsigned a16[] = { 6, 5, 4, 7, 8, 3, 0, 1, 2, }; static unsigned a17[] = { 2, 3, 8, 1, 4, 7, 0, 5, 6, }; static unsigned a18[] = { 2, 3, 4, 1, 6, 5, 0, 7, 8, }; static unsigned a19[] = { 2, 3, 4, 1, 8, 5, 0, 7, 6, }; static unsigned a20[] = { 2, 1, 0, 3, 4, 5, 8, 7, 6, }; static unsigned a21[] = { 2, 1, 0, 3, 6, 7, 4, 5, 8, }; static unsigned a22[] = { 2, 1, 0, 3, 8, 7, 4, 5, 6, }; static unsigned a23[] = { 6, 5, 0, 7, 4, 1, 8, 3, 2, }; static unsigned a24[] = { 8, 7, 0, 5, 6, 1, 4, 3, 2, }; static unsigned a25[] = { 6, 7, 0, 5, 8, 1, 4, 3, 2, }; static unsigned a26[] = { 8, 7, 6, 3, 4, 5, 2, 1, 0, }; static unsigned a27[] = { 4, 5, 8, 3, 6, 7, 2, 1, 0, }; static unsigned a28[] = { 4, 5, 6, 3, 8, 7, 2, 1, 0, }; static unsigned a29[] = { 8, 3, 2, 7, 4, 1, 6, 5, 0, }; static unsigned a30[] = { 4, 3, 2, 5, 6, 1, 8, 7, 0, }; static unsigned a31[] = { 4, 3, 2, 5, 8, 1, 6, 7, 0, }; static unsigned * layouts[] = { a00, a01, a02, a03, a04, a05, a06, a07, a08, a09, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, }; unsigned * a = layouts[rand() % 32]; std::vector<std::pair<Point, Point> > new_rooms(9); for(unsigned i = 0; i < rooms.size(); ++i) { new_rooms[a[i]] = rooms[i]; } return new_rooms; } void DungeonBuilder::pop_player_front(std::vector<Monster> & monsters) { if(monsters.empty()) { return; } foreach(Monster & monster, monsters) { if(deref_default(monster.type).faction == Monster::PLAYER) { std::swap(monster, monsters.front()); log("Player found."); break; } } } }
30.337449
161
0.590884
[ "vector" ]
afd509d8f6ac804561d498df38c34fbf9e393144
6,442
cpp
C++
src/beginner_tutorials/src/talker.cpp
rjb3vp/beginner_tutorials
01c1e3c32087852bfc4cf9719d28748018cdd43e
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
src/beginner_tutorials/src/talker.cpp
rjb3vp/beginner_tutorials
01c1e3c32087852bfc4cf9719d28748018cdd43e
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
src/beginner_tutorials/src/talker.cpp
rjb3vp/beginner_tutorials
01c1e3c32087852bfc4cf9719d28748018cdd43e
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
/** @file talker.cpp * @brief the ROS node that talks (publishes) messages * * Modified from the example * Modified from the example Copyright 2019 Ryan Bates, ROS.org Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <math.h> #include <tf/transform_broadcaster.h> #include <sstream> #include <cstdlib> #include "ros/ros.h" #include "std_msgs/String.h" #include "std_srvs/Empty.h" #include "beginner_tutorials/SetRandomRange.h" int randomRange = 100; int randomMean = 50; /** * @brief Sets the range and mean for random number generation. * @param req incoming request object with params to copy * @param res outgoing result to show if errors occurred in this method * @return bool to show whether this function executed or not */ bool setParams(beginner_tutorials::SetRandomRange::Request &req, beginner_tutorials::SetRandomRange::Response &res) { if (req.mean == 0) { ROS_WARN( "Mean value of 0 is technically permitted, but probably a mistake."); ROS_INFO_STREAM("Mean updated to " << req.mean << " with range of " << req.range); res.error = false; randomRange = req.range; randomMean = req.mean; } else if (req.mean < 0) { ROS_ERROR_STREAM("Mean cannot be " << req.mean << " which is < 0"); res.error = true; } else { ROS_INFO_STREAM("Mean updated to " << req.mean << " with range of " << req.range); res.error = false; randomRange = req.range; randomMean = req.mean; } return true; } /** * This tutorial demonstrates simple sending of messages over the ROS system. */ int main(int argc, char **argv) { /** * The ros::init() function needs to see argc and argv so that it can perform * any ROS arguments and name remapping that were provided at the command line. * For programmatic remappings you can use a different version of init() which takes * remappings directly, but for most command-line programs, passing argc and argv is * the easiest way to do it. The third argument to init() is the name of the node. * * You must call one of the versions of ros::init() before using any other * part of the ROS system. */ ros::init(argc, argv, "talker"); /** * NodeHandle is the main access point to communications with the ROS system. * The first NodeHandle constructed will fully initialize this node, and the last * NodeHandle destructed will close down the node. */ ros::NodeHandle n; /** * The advertise() function is how you tell ROS that you want to * publish on a given topic name. This invokes a call to the ROS * master node, which keeps a registry of who is publishing and who * is subscribing. After this advertise() call is made, the master * node will notify anyone who is trying to subscribe to this topic name, * and they will in turn negotiate a peer-to-peer connection with this * node. advertise() returns a Publisher object which allows you to * publish messages on that topic through a call to publish(). Once * all copies of the returned Publisher object are destroyed, the topic * will be automatically unadvertised. * * The second parameter to advertise() is the size of the message queue * used for publishing messages. If messages are published more quickly * than we can send them, the number here specifies how many messages to * buffer up before throwing some away. */ ros::ServiceServer service = n.advertiseService("random_data", setParams); ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000); ros::Rate loop_rate(10); /** * A count of how many messages we have sent. This is used to create * a unique string for each message. */ int count = 0; while (ros::ok()) { /** * This is a message object. You stuff it with data, and then publish it. */ std_msgs::String msg; std::stringstream ss; if (randomRange < -1) { ROS_FATAL_STREAM("Impossible range of " << randomRange << " detected, failure imminent."); } int baseNumber = floor(randomRange / 2); ROS_DEBUG_STREAM("Calculated base number is " << baseNumber); int output = (rand() % randomRange) + (randomMean + floor(randomRange / 2)); ss << "Our random value is=" << output; msg.data = ss.str(); ROS_DEBUG("HELP"); ROS_INFO_STREAM("Data: " << msg.data.c_str()); /** * The publish() function is how you send messages. The parameter * is the message object. The type of this object must agree with the type * given as a template parameter to the advertise<>() call, as was done * in the constructor above. */ chatter_pub.publish(msg); // Adapted from // wiki.ros.org/tf/Tutorials/Writing%20a%20tf%20broadcaster%20%28C%2B%2B%29 tf::TransformBroadcaster br; tf::Transform transform; // Handle translation here first transform.setOrigin(tf::Vector3(0.0 + output, 20.0, 0.0)); // Handle rotation here tf::Quaternion q; q.setRPY(0, 0, 45); // trivial change to see dynamics transform.setRotation(q); br.sendTransform(tf::StampedTransform(transform, ros::Time::now(), "world", "talk")); ros::spinOnce(); loop_rate.sleep(); ++count; } return 0; }
33.552083
755
0.705837
[ "object", "transform" ]
afd7f0bb68ed59f276e105add9caea2df73cc41e
818
cpp
C++
C++/src/bio/lib/background_models.cpp
JohnReid/biopsy
1eeb714ba5b53f2ecf776d865d32e2078cbc0338
[ "MIT" ]
null
null
null
C++/src/bio/lib/background_models.cpp
JohnReid/biopsy
1eeb714ba5b53f2ecf776d865d32e2078cbc0338
[ "MIT" ]
null
null
null
C++/src/bio/lib/background_models.cpp
JohnReid/biopsy
1eeb714ba5b53f2ecf776d865d32e2078cbc0338
[ "MIT" ]
null
null
null
/* Copyright John Reid 2007 */ #include "bio-pch.h" #include "bio/defs.h" #include "bio/background_models.h" #include "bio/hmm_dna.h" #include "bio/environment.h" #include <fstream> BIO_NS_START void gen_sequence_from_random_species_dna_hmm(seq_t & seq, size_t seq_length) { DnaHmmOrderNumStateMap::singleton().gen_sequence_from_random_hmm(seq, seq_length); } DnaModel::ptr_t DnaModelBroker::get_hmm_model(unsigned num_states, unsigned order) { if (! DnaHmmOrderNumStateMap::singleton().contains_model(num_states, order)) { throw BIO_MAKE_STRING("Do not have model with " << num_states << " states and order " << order); } return DnaHmmOrderNumStateMap::singleton().get_model_ptr( num_states, order ); } DnaModel::ptr_t DnaModelBroker::get_nmica_model() { return DnaModel::ptr_t(); } BIO_NS_END
18.177778
98
0.757946
[ "model" ]
afdc73b5bfc96f3fc28abe839c97c0edfdf954e7
570
cpp
C++
Algorithms/1679.Max_Number_of_K-Sum_Pairs.cpp
metehkaya/LeetCode
52f4a1497758c6f996d515ced151e8783ae4d4d2
[ "MIT" ]
2
2020-07-20T06:40:22.000Z
2021-11-20T01:23:26.000Z
Problems/LeetCode/Problems/1679.Max_Number_of_K-Sum_Pairs.cpp
metehkaya/Algo-Archive
03b5fdcf06f84a03125c57762c36a4e03ca6e756
[ "MIT" ]
null
null
null
Problems/LeetCode/Problems/1679.Max_Number_of_K-Sum_Pairs.cpp
metehkaya/Algo-Archive
03b5fdcf06f84a03125c57762c36a4e03ca6e756
[ "MIT" ]
null
null
null
class Solution { public: int maxOperations(vector<int>& ar, int k) { map<int,int> mp; int n = ar.size() , ans = 0; for( int i = 0 ; i < n ; i++ ) mp[ar[i]]++; for(auto it : mp) { int x = it.first; int xc = it.second; int y = k-x; if(x < y) { auto it2 = mp.find(y); if(it2 != mp.end()) ans += min(xc,it2->second); } else if(x == y) ans += xc/2; } return ans; } };
25.909091
47
0.350877
[ "vector" ]
afe48deb65c17812b9a3be9482a5bc1134cc35d6
10,356
cpp
C++
d3d11loadtest/Game.cpp
walbourn/directxtextest
c843ab9a7d75d01f3fc1fa134fcf4d94b12ea95b
[ "MIT" ]
6
2015-10-24T20:46:47.000Z
2021-10-17T06:11:26.000Z
d3d11loadtest/Game.cpp
walbourn/directxtextest
c843ab9a7d75d01f3fc1fa134fcf4d94b12ea95b
[ "MIT" ]
2
2018-01-19T19:14:47.000Z
2022-02-21T00:20:48.000Z
d3d11loadtest/Game.cpp
walbourn/directxtextest
c843ab9a7d75d01f3fc1fa134fcf4d94b12ea95b
[ "MIT" ]
1
2022-01-19T07:38:34.000Z
2022-01-19T07:38:34.000Z
// // Game.cpp // #include "pch.h" #include "Game.h" extern void ExitGame() noexcept; using namespace DirectX; using Microsoft::WRL::ComPtr; #include "DDSTextureLoader11.h" #include "WICTextureLoader11.h" #include "ScreenGrab11.h" #include "DirectXTex.h" #include "ReadData.h" #include <wincodec.h> namespace { struct Vertex { XMFLOAT4 position; XMFLOAT2 texcoord; }; } Game::Game() noexcept(false) : m_frame(0) { // Use gamma-correct rendering. m_deviceResources = std::make_unique<DX::DeviceResources>(DXGI_FORMAT_B8G8R8A8_UNORM_SRGB); m_deviceResources->RegisterDeviceNotify(this); } // Initialize the Direct3D resources required to run. void Game::Initialize(HWND window, int width, int height) { m_deviceResources->SetWindow(window, width, height); m_deviceResources->CreateDeviceResources(); CreateDeviceDependentResources(); m_deviceResources->CreateWindowSizeDependentResources(); CreateWindowSizeDependentResources(); } #pragma region Frame Update // Executes the basic game loop. void Game::Tick() { m_timer.Tick([&]() { Update(m_timer); }); Render(); ++m_frame; } // Updates the world. void Game::Update(DX::StepTimer const&) { } #pragma endregion #pragma region Frame Render // Draws the scene. void Game::Render() { // Don't try to render anything before the first Update. if (m_timer.GetFrameCount() == 0) { return; } Clear(); m_deviceResources->PIXBeginEvent(L"Render"); auto context = m_deviceResources->GetD3DDeviceContext(); // Set input assembler state. context->IASetInputLayout(m_spInputLayout.Get()); UINT strides = sizeof(Vertex); UINT offsets = 0; context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); context->IASetVertexBuffers(0, 1, m_spVertexBuffer.GetAddressOf(), &strides, &offsets); context->IASetIndexBuffer(m_spIndexBuffer.Get(), DXGI_FORMAT_R16_UINT, 0); // Set shaders. context->VSSetShader(m_spVertexShader.Get(), nullptr, 0); context->GSSetShader(nullptr, nullptr, 0); context->PSSetShader(m_spPixelShader.Get(), nullptr, 0); // Set texture and sampler. auto sampler = m_spSampler.Get(); context->PSSetSamplers(0, 1, &sampler); // Draw quad 1. auto texture = m_dx5logo.Get(); context->PSSetShaderResources(0, 1, &texture); context->DrawIndexed(6, 0, 0); // Draw quad 2. texture = m_cup.Get(); context->PSSetShaderResources(0, 1, &texture); context->DrawIndexed(6, 0, 4); m_deviceResources->PIXEndEvent(); if (!(m_frame % 100)) { OutputDebugStringA("Saving screenshot...\n"); ComPtr<ID3D11Resource> backbuffer; m_deviceResources->GetSwapChain()->GetBuffer(0, IID_PPV_ARGS(backbuffer.GetAddressOf())); DX::ThrowIfFailed(SaveDDSTextureToFile(context, backbuffer.Get(), L"screenshot.dds")); DX::ThrowIfFailed(SaveWICTextureToFile(context, backbuffer.Get(), GUID_ContainerFormatPng, L"screenshot.png", nullptr, nullptr, true)); DX::ThrowIfFailed(SaveWICTextureToFile(context, backbuffer.Get(), GUID_ContainerFormatJpeg, L"screenshot.jpg")); ScratchImage image; DX::ThrowIfFailed(CaptureTexture(m_deviceResources->GetD3DDevice(), context, backbuffer.Get(), image)); DX::ThrowIfFailed(SaveToDDSFile(image.GetImages(), image.GetImageCount(), image.GetMetadata(), DDS_FLAGS_NONE, L"screenshot2.dds")); DX::ThrowIfFailed(SaveToWICFile(*image.GetImage(0,0,0), WIC_FLAGS_NONE, GUID_ContainerFormatJpeg, L"screenshot2.jpg")); } // Show the new frame. m_deviceResources->Present(); } // Helper method to clear the back buffers. void Game::Clear() { m_deviceResources->PIXBeginEvent(L"Clear"); // Clear the views. auto context = m_deviceResources->GetD3DDeviceContext(); auto renderTarget = m_deviceResources->GetRenderTargetView(); auto depthStencil = m_deviceResources->GetDepthStencilView(); // Use linear clear color for gamma-correct rendering. XMVECTORF32 color; color.v = XMColorSRGBToRGB(Colors::CornflowerBlue); context->ClearRenderTargetView(renderTarget, color); context->ClearDepthStencilView(depthStencil, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); context->OMSetRenderTargets(1, &renderTarget, depthStencil); // Set the viewport. auto viewport = m_deviceResources->GetScreenViewport(); context->RSSetViewports(1, &viewport); m_deviceResources->PIXEndEvent(); } #pragma endregion #pragma region Message Handlers // Message handlers void Game::OnActivated() { } void Game::OnDeactivated() { } void Game::OnSuspending() { } void Game::OnResuming() { m_timer.ResetElapsedTime(); } void Game::OnWindowMoved() { auto r = m_deviceResources->GetOutputSize(); m_deviceResources->WindowSizeChanged(r.right, r.bottom); } void Game::OnWindowSizeChanged(int width, int height) { if (!m_deviceResources->WindowSizeChanged(width, height)) return; CreateWindowSizeDependentResources(); } // Properties void Game::GetDefaultSize(int& width, int& height) const noexcept { width = 800; height = 600; } #pragma endregion #pragma region Direct3D Resources // These are the resources that depend on the device. void Game::CreateDeviceDependentResources() { auto device = m_deviceResources->GetD3DDevice(); // Load and create shaders. auto vertexShaderBlob = DX::ReadData(L"VertexShader.cso"); DX::ThrowIfFailed( device->CreateVertexShader(vertexShaderBlob.data(), vertexShaderBlob.size(), nullptr, m_spVertexShader.ReleaseAndGetAddressOf())); auto pixelShaderBlob = DX::ReadData(L"PixelShader.cso"); DX::ThrowIfFailed( device->CreatePixelShader(pixelShaderBlob.data(), pixelShaderBlob.size(), nullptr, m_spPixelShader.ReleaseAndGetAddressOf())); // Create input layout. static const D3D11_INPUT_ELEMENT_DESC s_inputElementDesc[2] = { { "SV_Position", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 16, D3D11_INPUT_PER_VERTEX_DATA , 0 }, }; DX::ThrowIfFailed( device->CreateInputLayout(s_inputElementDesc, static_cast<UINT>(std::size(s_inputElementDesc)), vertexShaderBlob.data(), vertexShaderBlob.size(), m_spInputLayout.ReleaseAndGetAddressOf())); // Create vertex buffer. static const Vertex s_vertexData[] = { { { -1.0f, -0.5f, 0.5f, 1.0f },{ 0.f, 1.f } }, { { 0.0f, -0.5f, 0.5f, 1.0f },{ 1.f, 1.f } }, { { 0.0f, 0.5f, 0.5f, 1.0f },{ 1.f, 0.f } }, { { -1.0f, 0.5f, 0.5f, 1.0f },{ 0.f, 0.f } }, { { 0.f, -0.5f, 0.5f, 1.0f },{ 0.f, 1.f } }, { { 1.0f, -0.5f, 0.5f, 1.0f },{ 1.f, 1.f } }, { { 1.0f, 0.5f, 0.5f, 1.0f },{ 1.f, 0.f } }, { { 0.f, 0.5f, 0.5f, 1.0f },{ 0.f, 0.f } }, }; D3D11_SUBRESOURCE_DATA initialData = {}; initialData.pSysMem = s_vertexData; D3D11_BUFFER_DESC bufferDesc = {}; bufferDesc.ByteWidth = sizeof(s_vertexData); bufferDesc.Usage = D3D11_USAGE_IMMUTABLE; bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; bufferDesc.StructureByteStride = sizeof(Vertex); DX::ThrowIfFailed( device->CreateBuffer(&bufferDesc, &initialData, m_spVertexBuffer.ReleaseAndGetAddressOf())); // Create index buffer. static const uint16_t s_indexData[6] = { 3,1,0, 2,1,3, }; initialData.pSysMem = s_indexData; bufferDesc.ByteWidth = sizeof(s_indexData); bufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; bufferDesc.StructureByteStride = sizeof(uint16_t); DX::ThrowIfFailed( device->CreateBuffer(&bufferDesc, &initialData, m_spIndexBuffer.ReleaseAndGetAddressOf())); // Create sampler. D3D11_SAMPLER_DESC samplerDesc = {}; samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; samplerDesc.MinLOD = 0; samplerDesc.MaxLOD = D3D11_FLOAT32_MAX; DX::ThrowIfFailed( device->CreateSamplerState(&samplerDesc, m_spSampler.ReleaseAndGetAddressOf())); // Test DDSTextureLoader DX::ThrowIfFailed( CreateDDSTextureFromFileEx(device, L"dx5_logo.dds", 0, D3D11_USAGE_IMMUTABLE, D3D11_BIND_SHADER_RESOURCE, 0, 0, true, nullptr, m_dx5logo.ReleaseAndGetAddressOf())); { auto blob = DX::ReadData(L"dx5_logo.dds"); ComPtr<ID3D11ShaderResourceView> srv; DX::ThrowIfFailed( CreateDDSTextureFromMemoryEx(device, blob.data(), blob.size(), 0, D3D11_USAGE_IMMUTABLE, D3D11_BIND_SHADER_RESOURCE, 0, 0, true, nullptr, srv.ReleaseAndGetAddressOf())); } // Test WICTextureLoader DX::ThrowIfFailed( CreateWICTextureFromFile(device, L"cup_small.jpg", nullptr, m_cup.ReleaseAndGetAddressOf())); { auto blob = DX::ReadData(L"cup_small.jpg"); ComPtr<ID3D11ShaderResourceView> srv; DX::ThrowIfFailed( CreateWICTextureFromMemory(device, blob.data(), blob.size(), nullptr, srv.ReleaseAndGetAddressOf())); } } // Allocate all memory resources that change on a window SizeChanged event. void Game::CreateWindowSizeDependentResources() { } void Game::OnDeviceLost() { m_cup.Reset(); m_dx5logo.Reset(); m_spInputLayout.Reset(); m_spVertexBuffer.Reset(); m_spIndexBuffer.Reset(); m_spVertexShader.Reset(); m_spPixelShader.Reset(); m_spSampler.Reset(); } void Game::OnDeviceRestored() { CreateDeviceDependentResources(); CreateWindowSizeDependentResources(); } #pragma endregion
29.171831
144
0.657204
[ "render" ]
afe55f9608a4d859bd21679c3bc5fa4ff41020a3
1,155
cpp
C++
Contrib-Intel/RSD-PSME-RMM/common/agent-framework/discovery/src/discoverers/manager_discoverer.cpp
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
5
2019-11-11T07:57:26.000Z
2022-03-28T08:26:53.000Z
Contrib-Intel/RSD-PSME-RMM/common/agent-framework/discovery/src/discoverers/manager_discoverer.cpp
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
3
2019-09-05T21:47:07.000Z
2019-09-17T18:10:45.000Z
Contrib-Intel/RSD-PSME-RMM/common/agent-framework/discovery/src/discoverers/manager_discoverer.cpp
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
11
2019-07-20T00:16:32.000Z
2022-01-11T14:17:48.000Z
/*! * @brief Manager discoverer implementation. * * @copyright Copyright (c) 2018-2019 Intel Corporation. * * Licensed under the Apache License, Version 2.0 (the "License") override; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file manager_discoverer.cpp */ #include "agent-framework/discovery/discoverers/manager_discoverer.hpp" #include "agent-framework/discovery/builders/manager_builder.hpp" #include "agent-framework/version.hpp" using namespace agent_framework::discovery; agent_framework::model::Manager ManagerDiscoverer::discover() { auto manager = ManagerBuilder::build_enclosure(); manager.set_firmware_version(agent_framework::generic::Version::VERSION_STRING); return manager; }
38.5
86
0.770563
[ "model" ]
aff235d8a7711cce4578c36afa86fffb7e1cdb65
4,836
cc
C++
src/event.cc
IanBoyanZhang/kratos
4865e71e657c770fdc86528fcd56918e6f2103a1
[ "BSD-2-Clause" ]
39
2019-10-07T16:42:00.000Z
2022-03-31T20:33:28.000Z
src/event.cc
IanBoyanZhang/kratos
4865e71e657c770fdc86528fcd56918e6f2103a1
[ "BSD-2-Clause" ]
164
2019-06-29T03:43:19.000Z
2021-11-16T06:37:13.000Z
src/event.cc
IanBoyanZhang/kratos
4865e71e657c770fdc86528fcd56918e6f2103a1
[ "BSD-2-Clause" ]
11
2019-07-13T19:24:30.000Z
2022-01-21T22:52:18.000Z
#include "event.hh" #include <algorithm> #include "except.hh" #include "fmt/format.h" #include "generator.hh" #include "schema.hh" namespace kratos { void remove_empty_block(Generator *top); std::shared_ptr<EventTracingStmt> Event::fire( const std::map<std::string, std::shared_ptr<Var>> &fields) { auto stmt = std::make_shared<EventTracingStmt>(event_name_); for (auto const &[name, value] : fields) { stmt->add_event_field(name, value); } return stmt; } class EventVisitor : public IRVisitor { public: void visit(AuxiliaryStmt *stmt) override { if (stmt->aux_type() != AuxiliaryType::EventTracing) return; auto event = stmt->as<EventTracingStmt>(); add_info(event); } void add_info(const std::shared_ptr<EventTracingStmt> &stmt) { bool combinational = true; auto *p = stmt->parent(); while (p && p->ir_node_kind() == IRNodeKind::StmtKind) { auto *s = reinterpret_cast<Stmt *>(p); if (s->type() == StatementType::Block) { auto *b = reinterpret_cast<StmtBlock *>(s); if (b->block_type() == StatementBlockType::Sequential) { combinational = false; break; } } p = s->parent(); } EventInfo i; i.name = stmt->event_name(); i.transaction = stmt->transaction(); i.combinational = combinational; i.type = stmt->action_type(); i.fields = stmt->event_fields(); i.stmt = stmt; info.emplace_back(i); } std::vector<EventInfo> info; }; std::vector<EventInfo> extract_event_info(Generator *top) { EventVisitor visitor; visitor.visit_root(top); return visitor.info; } class EventRemoval : public IRVisitor { public: void visit(Generator *gen) override { auto stmt_count = gen->stmts_count(); std::vector<std::shared_ptr<Stmt>> stmts_to_remove; for (uint64_t i = 0; i < stmt_count; i++) { auto stmt = gen->get_stmt(i); if (stmt->type() == StatementType::Auxiliary) { auto aux = stmt->as<AuxiliaryStmt>(); if (aux->aux_type() == AuxiliaryType::EventTracing) stmts_to_remove.emplace_back(stmt); } } for (auto const &stmt : stmts_to_remove) { gen->remove_stmt(stmt); } } void visit(ScopedStmtBlock *block) override { process_block(block); } void visit(SequentialStmtBlock *block) override { process_block(block); } void visit(CombinationalStmtBlock *block) override { process_block(block); } static void process_block(StmtBlock *block) { auto stmt_count = block->size(); std::vector<std::shared_ptr<Stmt>> stmts_to_remove; for (uint64_t i = 0; i < stmt_count; i++) { auto const &stmt = block->get_stmt(i); if (stmt->type() == StatementType::Auxiliary) { auto aux = stmt->as<AuxiliaryStmt>(); if (aux->aux_type() == AuxiliaryType::EventTracing) stmts_to_remove.emplace_back(stmt); } } for (auto const &stmt : stmts_to_remove) { block->remove_stmt(stmt); } } }; void remove_event_stmts(Generator *top) { EventRemoval visitor; visitor.visit_root(top); // then remove empty block remove_empty_block(top); } std::string full_path(Var *var) { if (var->type() == VarType::ConstValue) { auto const &c = var->as<Const>(); return fmt::format("{0}", c->value()); } else { return var->handle_name(); } } std::string fields_to_json(const std::map<std::string, std::shared_ptr<Var>> &vars) { // layman's json serializer std::string result = "{"; std::vector<std::string> entries; entries.reserve(vars.size()); for (auto const &[name, var] : vars) { entries.emplace_back(fmt::format(R"("{0}": "{1}")", name, full_path(var.get()))); } auto content = fmt::format("{0}", fmt::join(entries.begin(), entries.end(), ", ")); result.append(content); result.append("}"); return result; } void save_events(hgdb::DebugDatabase &db, Generator *top) { // we first extract out every event statement auto infos = extract_event_info(top); // then for each info we create an entry for the db for (auto const &info : infos) { // need to serialize fields, matches etc auto fields = fields_to_json(info.fields); auto matches = fields_to_json(info.stmt->match_values()); auto action = static_cast<uint32_t>(info.type); hgdb::store_event(db, info.name, info.transaction, action, fields, matches, info.stmt->stmt_id()); } } } // namespace kratos
32.02649
89
0.592845
[ "vector" ]
aff7d25f1851c3d6f11f724d6415d66e2f4c8657
25,715
cxx
C++
main/sw/source/core/txtnode/fmtatr2.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/sw/source/core/txtnode/fmtatr2.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/sw/source/core/txtnode/fmtatr2.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #include <hintids.hxx> #include <poolfmt.hxx> #include "unomid.h" #include <basic/sbxvar.hxx> #include <svl/macitem.hxx> #include <svl/stritem.hxx> #include <svl/stylepool.hxx> #include <fmtautofmt.hxx> #include <fchrfmt.hxx> #include <fmtinfmt.hxx> #include <txtatr.hxx> #include <fmtruby.hxx> #include <charfmt.hxx> #include <hints.hxx> // SwUpdateAttr #include <unostyle.hxx> #include <unoevent.hxx> // SwHyperlinkEventDescriptor #include <com/sun/star/text/RubyAdjust.hdl> #include <cmdid.h> #include <com/sun/star/uno/Any.h> #include <SwStyleNameMapper.hxx> #include <fmtmeta.hxx> #include <ndtxt.hxx> // for meta #include <doc.hxx> // for meta #include <unometa.hxx> #include <docsh.hxx> #include <svl/zforlist.hxx> // GetNumberFormat #include <boost/bind.hpp> #include <algorithm> using namespace ::com::sun::star; using ::rtl::OUString; TYPEINIT1_AUTOFACTORY(SwFmtINetFmt, SfxPoolItem); TYPEINIT1_AUTOFACTORY(SwFmtAutoFmt, SfxPoolItem); /************************************************************************* |* |* class SwFmtCharFmt |* Beschreibung |* Ersterstellung JP 23.11.90 |* Letzte Aenderung JP 09.08.94 |* *************************************************************************/ SwFmtCharFmt::SwFmtCharFmt( SwCharFmt *pFmt ) : SfxPoolItem( RES_TXTATR_CHARFMT ), SwClient(pFmt), pTxtAttr( 0 ) { } SwFmtCharFmt::SwFmtCharFmt( const SwFmtCharFmt& rAttr ) : SfxPoolItem( RES_TXTATR_CHARFMT ), SwClient( rAttr.GetCharFmt() ), pTxtAttr( 0 ) { } SwFmtCharFmt::~SwFmtCharFmt() {} int SwFmtCharFmt::operator==( const SfxPoolItem& rAttr ) const { ASSERT( SfxPoolItem::operator==( rAttr ), "keine gleichen Attribute" ); return GetCharFmt() == ((SwFmtCharFmt&)rAttr).GetCharFmt(); } SfxPoolItem* SwFmtCharFmt::Clone( SfxItemPool* ) const { return new SwFmtCharFmt( *this ); } // weiterleiten an das TextAttribut void SwFmtCharFmt::Modify( const SfxPoolItem* pOld, const SfxPoolItem* pNew ) { if( pTxtAttr ) pTxtAttr->ModifyNotification( pOld, pNew ); } // weiterleiten an das TextAttribut sal_Bool SwFmtCharFmt::GetInfo( SfxPoolItem& rInfo ) const { return pTxtAttr ? pTxtAttr->GetInfo( rInfo ) : sal_False; } sal_Bool SwFmtCharFmt::QueryValue( uno::Any& rVal, sal_uInt8 ) const { String sCharFmtName; if(GetCharFmt()) SwStyleNameMapper::FillProgName(GetCharFmt()->GetName(), sCharFmtName, nsSwGetPoolIdFromName::GET_POOLID_CHRFMT, sal_True ); rVal <<= OUString( sCharFmtName ); return sal_True; } sal_Bool SwFmtCharFmt::PutValue( const uno::Any& , sal_uInt8 ) { DBG_ERROR("Zeichenvorlage kann mit PutValue nicht gesetzt werden!"); return sal_False; } /************************************************************************* |* |* class SwFmtAutoFmt |* Beschreibung |* Ersterstellung AMA 12.05.06 |* Letzte Aenderung AMA 12.05.06 |* *************************************************************************/ SwFmtAutoFmt::SwFmtAutoFmt( sal_uInt16 nInitWhich ) : SfxPoolItem( nInitWhich ) { } SwFmtAutoFmt::SwFmtAutoFmt( const SwFmtAutoFmt& rAttr ) : SfxPoolItem( rAttr.Which() ), mpHandle( rAttr.mpHandle ) { } SwFmtAutoFmt::~SwFmtAutoFmt() { } int SwFmtAutoFmt::operator==( const SfxPoolItem& rAttr ) const { ASSERT( SfxPoolItem::operator==( rAttr ), "different attributes" ); return mpHandle == ((SwFmtAutoFmt&)rAttr).mpHandle; } SfxPoolItem* SwFmtAutoFmt::Clone( SfxItemPool* ) const { return new SwFmtAutoFmt( *this ); } sal_Bool SwFmtAutoFmt::QueryValue( uno::Any& rVal, sal_uInt8 ) const { String sCharFmtName = StylePool::nameOf( mpHandle ); rVal <<= OUString( sCharFmtName ); return sal_True; } sal_Bool SwFmtAutoFmt::PutValue( const uno::Any& , sal_uInt8 ) { //the format is not renameable via API return sal_False; } /************************************************************************* |* |* class SwFmtINetFmt |* Beschreibung |* Ersterstellung AMA 02.08.96 |* Letzte Aenderung AMA 02.08.96 |* *************************************************************************/ SwFmtINetFmt::SwFmtINetFmt() : SfxPoolItem( RES_TXTATR_INETFMT ) , msURL() , msTargetFrame() , msINetFmtName() , msVisitedFmtName() , msHyperlinkName() , mpMacroTbl( 0 ) , mpTxtAttr( 0 ) , mnINetFmtId( 0 ) , mnVisitedFmtId( 0 ) {} SwFmtINetFmt::SwFmtINetFmt( const XubString& rURL, const XubString& rTarget ) : SfxPoolItem( RES_TXTATR_INETFMT ) , msURL( rURL ) , msTargetFrame( rTarget ) , msINetFmtName() , msVisitedFmtName() , msHyperlinkName() , mpMacroTbl( 0 ) , mpTxtAttr( 0 ) , mnINetFmtId( RES_POOLCHR_INET_NORMAL ) , mnVisitedFmtId( RES_POOLCHR_INET_VISIT ) { SwStyleNameMapper::FillUIName( mnINetFmtId, msINetFmtName ); SwStyleNameMapper::FillUIName( mnVisitedFmtId, msVisitedFmtName ); } SwFmtINetFmt::SwFmtINetFmt( const SwFmtINetFmt& rAttr ) : SfxPoolItem( RES_TXTATR_INETFMT ) , msURL( rAttr.GetValue() ) , msTargetFrame( rAttr.msTargetFrame ) , msINetFmtName( rAttr.msINetFmtName ) , msVisitedFmtName( rAttr.msVisitedFmtName ) , msHyperlinkName( rAttr.msHyperlinkName ) , mpMacroTbl( 0 ) , mpTxtAttr( 0 ) , mnINetFmtId( rAttr.mnINetFmtId ) , mnVisitedFmtId( rAttr.mnVisitedFmtId ) { if ( rAttr.GetMacroTbl() ) mpMacroTbl = new SvxMacroTableDtor( *rAttr.GetMacroTbl() ); } SwFmtINetFmt::~SwFmtINetFmt() { delete mpMacroTbl; } int SwFmtINetFmt::operator==( const SfxPoolItem& rAttr ) const { ASSERT( SfxPoolItem::operator==( rAttr ), "keine gleichen Attribute" ); sal_Bool bRet = SfxPoolItem::operator==( (SfxPoolItem&) rAttr ) && msURL == ((SwFmtINetFmt&)rAttr).msURL && msHyperlinkName == ((SwFmtINetFmt&)rAttr).msHyperlinkName && msTargetFrame == ((SwFmtINetFmt&)rAttr).msTargetFrame && msINetFmtName == ((SwFmtINetFmt&)rAttr).msINetFmtName && msVisitedFmtName == ((SwFmtINetFmt&)rAttr).msVisitedFmtName && mnINetFmtId == ((SwFmtINetFmt&)rAttr).mnINetFmtId && mnVisitedFmtId == ((SwFmtINetFmt&)rAttr).mnVisitedFmtId; if( !bRet ) return sal_False; const SvxMacroTableDtor* pOther = ((SwFmtINetFmt&)rAttr).mpMacroTbl; if( !mpMacroTbl ) return ( !pOther || !pOther->Count() ); if( !pOther ) return 0 == mpMacroTbl->Count(); const SvxMacroTableDtor& rOwn = *mpMacroTbl; const SvxMacroTableDtor& rOther = *pOther; // Anzahl unterschiedlich => auf jeden Fall ungleich if( rOwn.Count() != rOther.Count() ) return sal_False; // einzeln vergleichen; wegen Performance ist die Reihenfolge wichtig for( sal_uInt16 nNo = 0; nNo < rOwn.Count(); ++nNo ) { const SvxMacro *pOwnMac = rOwn.GetObject(nNo); const SvxMacro *pOtherMac = rOther.GetObject(nNo); if ( rOwn.GetKey(pOwnMac) != rOther.GetKey(pOtherMac) || pOwnMac->GetLibName() != pOtherMac->GetLibName() || pOwnMac->GetMacName() != pOtherMac->GetMacName() ) return sal_False; } return sal_True; } SfxPoolItem* SwFmtINetFmt::Clone( SfxItemPool* ) const { return new SwFmtINetFmt( *this ); } void SwFmtINetFmt::SetMacroTbl( const SvxMacroTableDtor* pNewTbl ) { if( pNewTbl ) { if( mpMacroTbl ) *mpMacroTbl = *pNewTbl; else mpMacroTbl = new SvxMacroTableDtor( *pNewTbl ); } else if( mpMacroTbl ) delete mpMacroTbl, mpMacroTbl = 0; } void SwFmtINetFmt::SetMacro( sal_uInt16 nEvent, const SvxMacro& rMacro ) { if( !mpMacroTbl ) mpMacroTbl = new SvxMacroTableDtor; SvxMacro *pOldMacro; if( 0 != ( pOldMacro = mpMacroTbl->Get( nEvent )) ) { delete pOldMacro; mpMacroTbl->Replace( nEvent, new SvxMacro( rMacro ) ); } else mpMacroTbl->Insert( nEvent, new SvxMacro( rMacro ) ); } const SvxMacro* SwFmtINetFmt::GetMacro( sal_uInt16 nEvent ) const { const SvxMacro* pRet = 0; if( mpMacroTbl && mpMacroTbl->IsKeyValid( nEvent ) ) pRet = mpMacroTbl->Get( nEvent ); return pRet; } sal_Bool SwFmtINetFmt::QueryValue( uno::Any& rVal, sal_uInt8 nMemberId ) const { sal_Bool bRet = sal_True; XubString sVal; nMemberId &= ~CONVERT_TWIPS; switch(nMemberId) { case MID_URL_URL: sVal = msURL; break; case MID_URL_TARGET: sVal = msTargetFrame; break; case MID_URL_HYPERLINKNAME: sVal = msHyperlinkName; break; case MID_URL_VISITED_FMT: sVal = msVisitedFmtName; if( !sVal.Len() && mnVisitedFmtId != 0 ) SwStyleNameMapper::FillUIName( mnVisitedFmtId, sVal ); if( sVal.Len() ) SwStyleNameMapper::FillProgName( sVal, sVal, nsSwGetPoolIdFromName::GET_POOLID_CHRFMT, sal_True ); break; case MID_URL_UNVISITED_FMT: sVal = msINetFmtName; if( !sVal.Len() && mnINetFmtId != 0 ) SwStyleNameMapper::FillUIName( mnINetFmtId, sVal ); if( sVal.Len() ) SwStyleNameMapper::FillProgName( sVal, sVal, nsSwGetPoolIdFromName::GET_POOLID_CHRFMT, sal_True ); break; case MID_URL_HYPERLINKEVENTS: { // create (and return) event descriptor SwHyperlinkEventDescriptor* pEvents = new SwHyperlinkEventDescriptor(); pEvents->copyMacrosFromINetFmt(*this); uno::Reference<container::XNameReplace> xNameReplace(pEvents); // all others return a string; so we just set rVal here and exit rVal <<= xNameReplace; return bRet; } default: break; } rVal <<= OUString(sVal); return bRet; } sal_Bool SwFmtINetFmt::PutValue( const uno::Any& rVal, sal_uInt8 nMemberId ) { sal_Bool bRet = sal_True; nMemberId &= ~CONVERT_TWIPS; // all properties except HyperlinkEvents are of type string, hence // we treat HyperlinkEvents specially if (MID_URL_HYPERLINKEVENTS == nMemberId) { uno::Reference<container::XNameReplace> xReplace; rVal >>= xReplace; if (xReplace.is()) { // Create hyperlink event descriptor. Then copy events // from argument into descriptor. Then copy events from // the descriptor into the format. SwHyperlinkEventDescriptor* pEvents = new SwHyperlinkEventDescriptor(); uno::Reference< lang::XServiceInfo> xHold = pEvents; pEvents->copyMacrosFromNameReplace(xReplace); pEvents->copyMacrosIntoINetFmt(*this); } else { // wrong type! bRet = sal_False; } } else { // all string properties: if(rVal.getValueType() != ::getCppuType((rtl::OUString*)0)) return sal_False; XubString sVal = *(rtl::OUString*)rVal.getValue(); switch(nMemberId) { case MID_URL_URL: msURL = sVal; break; case MID_URL_TARGET: msTargetFrame = sVal; break; case MID_URL_HYPERLINKNAME: msHyperlinkName = sVal; break; case MID_URL_VISITED_FMT: { String aString; SwStyleNameMapper::FillUIName( sVal, aString, nsSwGetPoolIdFromName::GET_POOLID_CHRFMT, sal_True ); msVisitedFmtName = OUString ( aString ); mnVisitedFmtId = SwStyleNameMapper::GetPoolIdFromUIName( msVisitedFmtName, nsSwGetPoolIdFromName::GET_POOLID_CHRFMT ); } break; case MID_URL_UNVISITED_FMT: { String aString; SwStyleNameMapper::FillUIName( sVal, aString, nsSwGetPoolIdFromName::GET_POOLID_CHRFMT, sal_True ); msINetFmtName = OUString ( aString ); mnINetFmtId = SwStyleNameMapper::GetPoolIdFromUIName( msINetFmtName, nsSwGetPoolIdFromName::GET_POOLID_CHRFMT ); } break; default: bRet = sal_False; } } return bRet; } /************************************************************************* |* class SwFmtRuby *************************************************************************/ SwFmtRuby::SwFmtRuby( const String& rRubyTxt ) : SfxPoolItem( RES_TXTATR_CJK_RUBY ), sRubyTxt( rRubyTxt ), pTxtAttr( 0 ), nCharFmtId( 0 ), nPosition( 0 ), nAdjustment( 0 ) { } SwFmtRuby::SwFmtRuby( const SwFmtRuby& rAttr ) : SfxPoolItem( RES_TXTATR_CJK_RUBY ), sRubyTxt( rAttr.sRubyTxt ), sCharFmtName( rAttr.sCharFmtName ), pTxtAttr( 0 ), nCharFmtId( rAttr.nCharFmtId), nPosition( rAttr.nPosition ), nAdjustment( rAttr.nAdjustment ) { } SwFmtRuby::~SwFmtRuby() { } SwFmtRuby& SwFmtRuby::operator=( const SwFmtRuby& rAttr ) { sRubyTxt = rAttr.sRubyTxt; sCharFmtName = rAttr.sCharFmtName; nCharFmtId = rAttr.nCharFmtId; nPosition = rAttr.nPosition; nAdjustment = rAttr.nAdjustment; pTxtAttr = 0; return *this; } int SwFmtRuby::operator==( const SfxPoolItem& rAttr ) const { ASSERT( SfxPoolItem::operator==( rAttr ), "keine gleichen Attribute" ); return sRubyTxt == ((SwFmtRuby&)rAttr).sRubyTxt && sCharFmtName == ((SwFmtRuby&)rAttr).sCharFmtName && nCharFmtId == ((SwFmtRuby&)rAttr).nCharFmtId && nPosition == ((SwFmtRuby&)rAttr).nPosition && nAdjustment == ((SwFmtRuby&)rAttr).nAdjustment; } SfxPoolItem* SwFmtRuby::Clone( SfxItemPool* ) const { return new SwFmtRuby( *this ); } sal_Bool SwFmtRuby::QueryValue( uno::Any& rVal, sal_uInt8 nMemberId ) const { sal_Bool bRet = sal_True; nMemberId &= ~CONVERT_TWIPS; switch( nMemberId ) { case MID_RUBY_TEXT: rVal <<= (OUString)sRubyTxt; break; case MID_RUBY_ADJUST: rVal <<= (sal_Int16)nAdjustment; break; case MID_RUBY_CHARSTYLE: { String aString; SwStyleNameMapper::FillProgName(sCharFmtName, aString, nsSwGetPoolIdFromName::GET_POOLID_CHRFMT, sal_True ); rVal <<= OUString ( aString ); } break; case MID_RUBY_ABOVE: { sal_Bool bAbove = !nPosition; rVal.setValue(&bAbove, ::getBooleanCppuType()); } break; default: bRet = sal_False; } return bRet; } sal_Bool SwFmtRuby::PutValue( const uno::Any& rVal, sal_uInt8 nMemberId ) { sal_Bool bRet = sal_True; nMemberId &= ~CONVERT_TWIPS; switch( nMemberId ) { case MID_RUBY_TEXT: { OUString sTmp; bRet = rVal >>= sTmp; sRubyTxt = sTmp; } break; case MID_RUBY_ADJUST: { sal_Int16 nSet = 0; rVal >>= nSet; if(nSet >= 0 && nSet <= text::RubyAdjust_INDENT_BLOCK) nAdjustment = nSet; else bRet = sal_False; } break; case MID_RUBY_ABOVE: { const uno::Type& rType = ::getBooleanCppuType(); if(rVal.hasValue() && rVal.getValueType() == rType) { sal_Bool bAbove = *(sal_Bool*)rVal.getValue(); nPosition = bAbove ? 0 : 1; } } break; case MID_RUBY_CHARSTYLE: { OUString sTmp; bRet = rVal >>= sTmp; if(bRet) sCharFmtName = SwStyleNameMapper::GetUIName(sTmp, nsSwGetPoolIdFromName::GET_POOLID_CHRFMT ); } break; default: bRet = sal_False; } return bRet; } /************************************************************************* class SwFmtMeta ************************************************************************/ SwFmtMeta * SwFmtMeta::CreatePoolDefault(const sal_uInt16 i_nWhich) { return new SwFmtMeta(i_nWhich); } SwFmtMeta::SwFmtMeta(const sal_uInt16 i_nWhich) : SfxPoolItem( i_nWhich ) , m_pMeta() , m_pTxtAttr( 0 ) { ASSERT((RES_TXTATR_META == i_nWhich) || (RES_TXTATR_METAFIELD == i_nWhich), "ERROR: SwFmtMeta: invalid which id!"); } SwFmtMeta::SwFmtMeta( ::boost::shared_ptr< ::sw::Meta > const & i_pMeta, const sal_uInt16 i_nWhich ) : SfxPoolItem( i_nWhich ) , m_pMeta( i_pMeta ) , m_pTxtAttr( 0 ) { ASSERT((RES_TXTATR_META == i_nWhich) || (RES_TXTATR_METAFIELD == i_nWhich), "ERROR: SwFmtMeta: invalid which id!"); ASSERT(m_pMeta, "SwFmtMeta: no Meta ?"); // DO NOT call m_pMeta->SetFmtMeta(this) here; only from SetTxtAttr! } SwFmtMeta::~SwFmtMeta() { if (m_pMeta && (m_pMeta->GetFmtMeta() == this)) { NotifyChangeTxtNode(0); m_pMeta->SetFmtMeta(0); } } int SwFmtMeta::operator==( const SfxPoolItem & i_rOther ) const { ASSERT( SfxPoolItem::operator==( i_rOther ), "i just copied this assert" ); return SfxPoolItem::operator==( i_rOther ) && (m_pMeta == static_cast<SwFmtMeta const &>( i_rOther ).m_pMeta); } SfxPoolItem * SwFmtMeta::Clone( SfxItemPool * /*pPool*/ ) const { // if this is indeed a copy, then DoCopy must be called later! return (m_pMeta) // #i105148# pool default may be cloned also! ? new SwFmtMeta( m_pMeta, Which() ) : new SwFmtMeta( Which() ); } void SwFmtMeta::SetTxtAttr(SwTxtMeta * const i_pTxtAttr) { OSL_ENSURE(!(m_pTxtAttr && i_pTxtAttr), "SwFmtMeta::SetTxtAttr: already has text attribute?"); OSL_ENSURE( m_pTxtAttr || i_pTxtAttr , "SwFmtMeta::SetTxtAttr: no attribute to remove?"); m_pTxtAttr = i_pTxtAttr; OSL_ENSURE(m_pMeta, "inserted SwFmtMeta has no sw::Meta?"); // the sw::Meta must be able to find the current text attribute! if (m_pMeta) { if (i_pTxtAttr) { m_pMeta->SetFmtMeta(this); } else if (m_pMeta->GetFmtMeta() == this) { // text attribute gone => de-register from text node! NotifyChangeTxtNode(0); m_pMeta->SetFmtMeta(0); } } } void SwFmtMeta::NotifyChangeTxtNode(SwTxtNode *const pTxtNode) { // N.B.: do not reset m_pTxtAttr here: see call in nodes.cxx, // where the hint is not deleted! OSL_ENSURE(m_pMeta, "SwFmtMeta::NotifyChangeTxtNode: no Meta?"); if (m_pMeta && (m_pMeta->GetFmtMeta() == this)) { // do not call Modify, that would call SwXMeta::Modify! m_pMeta->NotifyChangeTxtNode(pTxtNode); } } // this SwFmtMeta has been cloned and points at the same sw::Meta as the source // this method copies the sw::Meta void SwFmtMeta::DoCopy(::sw::MetaFieldManager & i_rTargetDocManager, SwTxtNode & i_rTargetTxtNode) { OSL_ENSURE(m_pMeta, "DoCopy called for SwFmtMeta with no sw::Meta?"); if (m_pMeta) { const ::boost::shared_ptr< ::sw::Meta> pOriginal( m_pMeta ); if (RES_TXTATR_META == Which()) { m_pMeta.reset( new ::sw::Meta(this) ); } else { ::sw::MetaField *const pMetaField( static_cast< ::sw::MetaField* >(pOriginal.get())); m_pMeta = i_rTargetDocManager.makeMetaField( this, pMetaField->m_nNumberFormat, pMetaField->IsFixedLanguage() ); } // Meta must have a text node before calling RegisterAsCopyOf m_pMeta->NotifyChangeTxtNode(& i_rTargetTxtNode); // this cannot be done in Clone: a Clone is not necessarily a copy! m_pMeta->RegisterAsCopyOf(*pOriginal); } } namespace sw { /************************************************************************* class sw::Meta ************************************************************************/ Meta::Meta(SwFmtMeta * const i_pFmt) : ::sfx2::Metadatable() , SwModify() , m_pFmt( i_pFmt ) { } Meta::~Meta() { } SwTxtMeta * Meta::GetTxtAttr() const { return (m_pFmt) ? m_pFmt->GetTxtAttr() : 0; } SwTxtNode * Meta::GetTxtNode() const { return m_pTxtNode; } void Meta::NotifyChangeTxtNodeImpl() { if (m_pTxtNode && (GetRegisteredIn() != m_pTxtNode)) { m_pTxtNode->Add(this); } else if (!m_pTxtNode && GetRegisteredIn()) { GetRegisteredInNonConst()->Remove(this); } } void Meta::NotifyChangeTxtNode(SwTxtNode *const pTxtNode) { m_pTxtNode = pTxtNode; NotifyChangeTxtNodeImpl(); if (!pTxtNode) // text node gone? invalidate UNO object! { SwPtrMsgPoolItem aMsgHint( RES_REMOVE_UNO_OBJECT, &static_cast<SwModify&>(*this) ); // cast to base class! this->Modify(&aMsgHint, &aMsgHint); } } // SwClient void Meta::Modify( const SfxPoolItem *pOld, const SfxPoolItem *pNew ) { NotifyClients(pOld, pNew); if (pOld && (RES_REMOVE_UNO_OBJECT == pOld->Which())) { // invalidate cached uno object SetXMeta(uno::Reference<rdf::XMetadatable>(0)); } } // sfx2::Metadatable ::sfx2::IXmlIdRegistry& Meta::GetRegistry() { SwTxtNode * const pTxtNode( GetTxtNode() ); // GetRegistry may only be called on a meta that is actually in the // document, which means it has a pointer to its text node OSL_ENSURE(pTxtNode, "ERROR: GetRegistry: no text node?"); if (!pTxtNode) throw uno::RuntimeException(); return pTxtNode->GetRegistry(); } bool Meta::IsInClipboard() const { const SwTxtNode * const pTxtNode( GetTxtNode() ); // no text node: in UNDO OSL_ENSURE(pTxtNode, "IsInClipboard: no text node?"); return (pTxtNode) ? pTxtNode->IsInClipboard() : false; } bool Meta::IsInUndo() const { const SwTxtNode * const pTxtNode( GetTxtNode() ); // no text node: in UNDO OSL_ENSURE(pTxtNode, "IsInUndo: no text node?"); return (pTxtNode) ? pTxtNode->IsInUndo() : true; } bool Meta::IsInContent() const { const SwTxtNode * const pTxtNode( GetTxtNode() ); OSL_ENSURE(pTxtNode, "IsInContent: no text node?"); return (pTxtNode) ? pTxtNode->IsInContent() : true; } ::com::sun::star::uno::Reference< ::com::sun::star::rdf::XMetadatable > Meta::MakeUnoObject() { return SwXMeta::CreateXMeta(*this); } /************************************************************************* class sw::MetaField ************************************************************************/ MetaField::MetaField(SwFmtMeta * const i_pFmt, const sal_uInt32 nNumberFormat, const bool bIsFixedLanguage) : Meta(i_pFmt) , m_nNumberFormat( nNumberFormat ) , m_bIsFixedLanguage( bIsFixedLanguage ) { } void MetaField::GetPrefixAndSuffix( ::rtl::OUString *const o_pPrefix, ::rtl::OUString *const o_pSuffix) { try { const uno::Reference<rdf::XMetadatable> xMetaField( MakeUnoObject() ); OSL_ENSURE(dynamic_cast<SwXMetaField*>(xMetaField.get()), "GetPrefixAndSuffix: no SwXMetaField?"); if (xMetaField.is()) { SwTxtNode * const pTxtNode( GetTxtNode() ); SwDocShell const * const pShell(pTxtNode->GetDoc()->GetDocShell()); const uno::Reference<frame::XModel> xModel( (pShell) ? pShell->GetModel() : 0, uno::UNO_SET_THROW); getPrefixAndSuffix(xModel, xMetaField, o_pPrefix, o_pSuffix); } } catch (uno::Exception) { OSL_ENSURE(false, "exception?"); } } sal_uInt32 MetaField::GetNumberFormat(::rtl::OUString const & rContent) const { //TODO: this probably lacks treatment for some special cases sal_uInt32 nNumberFormat( m_nNumberFormat ); SwTxtNode * const pTxtNode( GetTxtNode() ); if (pTxtNode) { SvNumberFormatter *const pNumberFormatter( pTxtNode->GetDoc()->GetNumberFormatter() ); double number; (void) pNumberFormatter->IsNumberFormat( rContent, nNumberFormat, number ); } return nNumberFormat; } void MetaField::SetNumberFormat(sal_uInt32 nNumberFormat) { // effectively, the member is only a default: // GetNumberFormat checks if the text actually conforms m_nNumberFormat = nNumberFormat; } /************************************************************************* class sw::MetaFieldManager ************************************************************************/ MetaFieldManager::MetaFieldManager() { } ::boost::shared_ptr<MetaField> MetaFieldManager::makeMetaField(SwFmtMeta * const i_pFmt, const sal_uInt32 nNumberFormat, const bool bIsFixedLanguage) { const ::boost::shared_ptr<MetaField> pMetaField( new MetaField(i_pFmt, nNumberFormat, bIsFixedLanguage) ); m_MetaFields.push_back(pMetaField); return pMetaField; } struct IsInUndo { bool operator()(::boost::weak_ptr<MetaField> const & pMetaField) { return pMetaField.lock()->IsInUndo(); } }; struct MakeUnoObject { uno::Reference<text::XTextField> operator()(::boost::weak_ptr<MetaField> const & pMetaField) { return uno::Reference<text::XTextField>( pMetaField.lock()->MakeUnoObject(), uno::UNO_QUERY); } }; ::std::vector< uno::Reference<text::XTextField> > MetaFieldManager::getMetaFields() { // erase deleted fields const MetaFieldList_t::iterator iter( ::std::remove_if(m_MetaFields.begin(), m_MetaFields.end(), ::boost::bind(&::boost::weak_ptr<MetaField>::expired, _1))); m_MetaFields.erase(iter, m_MetaFields.end()); // filter out fields in UNDO MetaFieldList_t filtered(m_MetaFields.size()); const MetaFieldList_t::iterator iter2( ::std::remove_copy_if(m_MetaFields.begin(), m_MetaFields.end(), filtered.begin(), IsInUndo())); filtered.erase(iter2, filtered.end()); // create uno objects ::std::vector< uno::Reference<text::XTextField> > ret(filtered.size()); ::std::transform(filtered.begin(), filtered.end(), ret.begin(), MakeUnoObject()); return ret; } } // namespace sw
27.951087
127
0.639666
[ "object", "vector", "transform" ]
9b7e20116583cf0dea9af37b3149373645b37b2c
19,725
cpp
C++
RobWork/src/rw/models/RevoluteJoint.cpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
1
2021-12-29T14:16:27.000Z
2021-12-29T14:16:27.000Z
RobWork/src/rw/models/RevoluteJoint.cpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
RobWork/src/rw/models/RevoluteJoint.cpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
/******************************************************************************** * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute, * Faculty of Engineering, University of Southern Denmark * * 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 "RevoluteJoint.hpp" using namespace rw::common; using namespace rw::models; using namespace rw::kinematics; using namespace rw::math; /* class RevoluteJointZeroOffsetImpl: public RevoluteJoint { public: RevoluteJointZeroOffsetImpl(const std::string& name, const Rotation3D<>& rotation) : RevoluteJoint(name), _transform(rotation) { } private: void doGetJointValueTransform(const Transform3D<>& parent, double q, Transform3D<>& result) const { const double a00 = parent.R()(0, 0); const double a01 = parent.R()(0, 1); const double a02 = parent.R()(0, 2); const double a10 = parent.R()(1, 0); const double a11 = parent.R()(1, 1); const double a12 = parent.R()(1, 2); const double a20 = parent.R()(2, 0); const double a21 = parent.R()(2, 1); const double a22 = parent.R()(2, 2); const double b00 = _transform.R()(0, 0); const double b01 = _transform.R()(0, 1); const double b02 = _transform.R()(0, 2); const double b10 = _transform.R()(1, 0); const double b11 = _transform.R()(1, 1); const double b12 = _transform.R()(1, 2); const double b20 = _transform.R()(2, 0); const double b21 = _transform.R()(2, 1); const double b22 = _transform.R()(2, 2); const double a00b00 = a00 * b00; const double a01b10 = a01 * b10; const double a01b11 = a01 * b11; const double a00b01 = a00 * b01; const double a02b21 = a02 * b21; const double a02b20 = a02 * b20; const double a10b00 = a10 * b00; const double a11b10 = a11 * b10; const double a11b11 = a11 * b11; const double a12b20 = a12 * b20; const double a12b21 = a12 * b21; const double a10b01 = a10 * b01; const double a20b00 = a20 * b00; const double a21b10 = a21 * b10; const double a22b20 = a22 * b20; const double a20b01 = a20 * b01; const double a21b11 = a21 * b11; const double a22b21 = a22 * b21; const double a20b01_a21b11_a22b21 = a20b01 + a21b11 + a22b21; const double a20b00_a21b10_a22b20 = a20b00 + a21b10 + a22b20; const double a10b01_a11b11_a12b21 = a10b01 + a11b11 + a12b21; const double a00b01_a01b11_a02b21 = a00b01 + a01b11 + a02b21; const double a10b00_a11b10_a12b20 = a10b00 + a11b10 + a12b20; const double a00b00_a01b10_a02b20 = a00b00 + a01b10 + a02b20; const double cq = cos(q); const double sq = sin(q); result.P() = parent.P(); result.R() = Rotation3D<> (a00b00_a01b10_a02b20 * cq + a00b01_a01b11_a02b21 * sq, a00b01_a01b11_a02b21 * cq - a00b00_a01b10_a02b20 * sq, a00 * b02 + a01 * b12 + a02 * b22, a10b00_a11b10_a12b20 * cq + a10b01_a11b11_a12b21 * sq, a10b01_a11b11_a12b21 * cq - a10b00_a11b10_a12b20 * sq, a10 * b02 + a11 * b12 + a12 * b22, a20b00_a21b10_a22b20 * cq + a20b01_a21b11_a22b21 * sq, a20b01_a21b11_a22b21 * cq - a20b00_a21b10_a22b20 * sq, a20 * b02 + a21 * b12 + a22 * b22); } private: Transform3D<> _transform; };*/ //} //---------------------------------------------------------------------- // RevoluteJoint //---------------------------------------------------------------------- RevoluteJoint::RevoluteJoint (const std::string& name, const Transform3D<>& transform) : Joint (name, 1) { if (transform.P () == Vector3D<> (0, 0, 0)) _impl = new RevoluteJointZeroOffsetImpl (transform.R ()); else _impl = new RevoluteJointBasic (transform); } RevoluteJoint::~RevoluteJoint () { delete _impl; } void RevoluteJoint::multiplyJointTransform (const Transform3D<>& parent, const Q& q, Transform3D<>& result) const { _impl->multiplyTransform (parent, q (0), result); } void RevoluteJoint::doMultiplyTransform (const Transform3D<>& parent, const State& state, Transform3D<>& result) const { _impl->multiplyTransform (parent, getData (state)[0], result); } Transform3D<> RevoluteJoint::doGetTransform (const State& state) const { return _impl->getTransform (getData (state)[0]); } void RevoluteJoint::getJacobian (size_t row, size_t col, const Transform3D<>& joint, const Transform3D<>& tcp, const State& state, Jacobian& jacobian) const { double q = getData (state)[0]; _impl->getJacobian (row, col, joint, tcp, q, jacobian); // const Vector3D<> axis = joint.R().getCol(2); // if (_impl->getJacobianScale() != 1) { // axis *= _impl->getJacobianScale(); //} // const Vector3D<> p = cross(axis, tcp.P() - joint.P()); // jacobian.addPosition(p, row, col); // jacobian.addRotation(axis,row, col); } rw::math::Transform3D<> RevoluteJoint::getFixedTransform () const { return _impl->getFixedTransform (); } void RevoluteJoint::setFixedTransform (const rw::math::Transform3D<>& t3d) { // this might change the impl, os RevoluteJointImpl* tmp = _impl; if (t3d.P () == Vector3D<> (0, 0, 0)) _impl = new RevoluteJointZeroOffsetImpl (t3d.R ()); else _impl = new RevoluteJointBasic (t3d); delete tmp; } void RevoluteJoint::setJointMapping (rw::math::Function1Diff<>::Ptr function) { RevoluteJointImpl* tmp = _impl; _impl = new RevoluteJointWithQMapping (tmp->getFixedTransform (), function); delete tmp; } void RevoluteJoint::removeJointMapping () { RevoluteJointImpl* tmp = _impl; Transform3D<> t3d = _impl->getFixedTransform (); if (t3d.P () == Vector3D<> (0, 0, 0)) _impl = new RevoluteJointZeroOffsetImpl (t3d.R ()); else _impl = new RevoluteJointBasic (t3d); delete tmp; } rw::math::Transform3D<> RevoluteJoint::getTransform (double q) const { return _impl->getTransform (q); } Transform3D<> RevoluteJoint::getJointTransform (double q) const { const double cq = cos (q); const double sq = sin (q); rw::math::Transform3D<> result; result (0, 0) = cq; result (0, 1) = -sq; result (0, 2) = 0; result (0, 3) = 0; result (1, 0) = sq; result (1, 1) = cq; result (1, 2) = 0; result (1, 3) = 0; result (2, 0) = 0; result (2, 1) = 0; result (2, 2) = 1; result (2, 3) = 0; return result; } rw::math::Transform3D<> RevoluteJoint::getJointTransform (const rw::kinematics::State& state) const { const double q = getData (state)[0]; return getJointTransform (q); } void RevoluteJoint::RevoluteJointImpl::getJacobian (size_t row, size_t col, const Transform3D<>& joint, const Transform3D<>& tcp, double q, Jacobian& jacobian) const { const Vector3D<> axis = joint.R ().getCol (2); const Vector3D<> p = cross (axis, tcp.P () - joint.P ()); jacobian.addPosition (p, row, col); jacobian.addRotation (axis, row, col); } RevoluteJoint::RevoluteJointBasic::RevoluteJointBasic (const rw::math::Transform3D<>& transform) : _transform (transform) {} void RevoluteJoint::RevoluteJointBasic::multiplyTransform (const rw::math::Transform3D<>& parent, double q, rw::math::Transform3D<>& result) const { const double a00 = parent.R () (0, 0); const double a01 = parent.R () (0, 1); const double a02 = parent.R () (0, 2); const double a10 = parent.R () (1, 0); const double a11 = parent.R () (1, 1); const double a12 = parent.R () (1, 2); const double a20 = parent.R () (2, 0); const double a21 = parent.R () (2, 1); const double a22 = parent.R () (2, 2); const double ax = parent.P () (0); const double ay = parent.P () (1); const double az = parent.P () (2); const double b00 = _transform.R () (0, 0); const double b01 = _transform.R () (0, 1); const double b02 = _transform.R () (0, 2); const double b10 = _transform.R () (1, 0); const double b11 = _transform.R () (1, 1); const double b12 = _transform.R () (1, 2); const double b20 = _transform.R () (2, 0); const double b21 = _transform.R () (2, 1); const double b22 = _transform.R () (2, 2); const double bx = _transform.P () (0); const double by = _transform.P () (1); const double bz = _transform.P () (2); const double a00b00 = a00 * b00; const double a01b10 = a01 * b10; const double a01b11 = a01 * b11; const double a00b01 = a00 * b01; const double a02b21 = a02 * b21; const double a02b20 = a02 * b20; const double a10b00 = a10 * b00; const double a11b10 = a11 * b10; const double a11b11 = a11 * b11; const double a12b20 = a12 * b20; const double a12b21 = a12 * b21; const double a10b01 = a10 * b01; const double a20b00 = a20 * b00; const double a21b10 = a21 * b10; const double a22b20 = a22 * b20; const double a20b01 = a20 * b01; const double a21b11 = a21 * b11; const double a22b21 = a22 * b21; const double a20b01_a21b11_a22b21 = a20b01 + a21b11 + a22b21; const double a20b00_a21b10_a22b20 = a20b00 + a21b10 + a22b20; const double a10b01_a11b11_a12b21 = a10b01 + a11b11 + a12b21; const double a00b01_a01b11_a02b21 = a00b01 + a01b11 + a02b21; const double a10b00_a11b10_a12b20 = a10b00 + a11b10 + a12b20; const double a00b00_a01b10_a02b20 = a00b00 + a01b10 + a02b20; const double cq = cos (q); const double sq = sin (q); result.P () = rw::math::Vector3D<> (ax + a00 * bx + a01 * by + a02 * bz, ay + a10 * bx + a11 * by + a12 * bz, az + a20 * bx + a21 * by + a22 * bz); result.R () = rw::math::Rotation3D<> (a00b00_a01b10_a02b20 * cq + a00b01_a01b11_a02b21 * sq, a00b01_a01b11_a02b21 * cq - a00b00_a01b10_a02b20 * sq, a00 * b02 + a01 * b12 + a02 * b22, a10b00_a11b10_a12b20 * cq + a10b01_a11b11_a12b21 * sq, a10b01_a11b11_a12b21 * cq - a10b00_a11b10_a12b20 * sq, a10 * b02 + a11 * b12 + a12 * b22, a20b00_a21b10_a22b20 * cq + a20b01_a21b11_a22b21 * sq, a20b01_a21b11_a22b21 * cq - a20b00_a21b10_a22b20 * sq, a20 * b02 + a21 * b12 + a22 * b22); } rw::math::Transform3D<> RevoluteJoint::RevoluteJointBasic::getTransform (double q) { const double b00 = _transform.R () (0, 0); const double b01 = _transform.R () (0, 1); const double b02 = _transform.R () (0, 2); const double b10 = _transform.R () (1, 0); const double b11 = _transform.R () (1, 1); const double b12 = _transform.R () (1, 2); const double b20 = _transform.R () (2, 0); const double b21 = _transform.R () (2, 1); const double b22 = _transform.R () (2, 2); const double bx = _transform.P () (0); const double by = _transform.P () (1); const double bz = _transform.P () (2); const double cq = cos (q); const double sq = sin (q); rw::math::Transform3D<> result; result (0, 0) = b00 * cq + b01 * sq; result (0, 1) = b01 * cq - b00 * sq; result (0, 2) = b02; result (0, 3) = bx; result (1, 0) = b10 * cq + b11 * sq; result (1, 1) = b11 * cq - b10 * sq; result (1, 2) = b12; result (1, 3) = by; result (2, 0) = b20 * cq + b21 * sq; result (2, 1) = b21 * cq - b20 * sq; result (2, 2) = b22; result (2, 3) = bz; return result; } rw::math::Transform3D<> RevoluteJoint::RevoluteJointBasic::getFixedTransform () const { return _transform; } //////////////////////////////////////////////////////////////////////////////////////// /////// RevoluteJointZeroOffsetImpl RevoluteJoint::RevoluteJointZeroOffsetImpl::RevoluteJointZeroOffsetImpl ( const rw::math::Rotation3D<>& rotation) : _transform (rotation) {} void RevoluteJoint::RevoluteJointZeroOffsetImpl::multiplyTransform ( const rw::math::Transform3D<>& parent, double q, rw::math::Transform3D<>& result) const { const double a00 = parent.R () (0, 0); const double a01 = parent.R () (0, 1); const double a02 = parent.R () (0, 2); const double a10 = parent.R () (1, 0); const double a11 = parent.R () (1, 1); const double a12 = parent.R () (1, 2); const double a20 = parent.R () (2, 0); const double a21 = parent.R () (2, 1); const double a22 = parent.R () (2, 2); const double b00 = _transform.R () (0, 0); const double b01 = _transform.R () (0, 1); const double b02 = _transform.R () (0, 2); const double b10 = _transform.R () (1, 0); const double b11 = _transform.R () (1, 1); const double b12 = _transform.R () (1, 2); const double b20 = _transform.R () (2, 0); const double b21 = _transform.R () (2, 1); const double b22 = _transform.R () (2, 2); const double a00b00 = a00 * b00; const double a01b10 = a01 * b10; const double a01b11 = a01 * b11; const double a00b01 = a00 * b01; const double a02b21 = a02 * b21; const double a02b20 = a02 * b20; const double a10b00 = a10 * b00; const double a11b10 = a11 * b10; const double a11b11 = a11 * b11; const double a12b20 = a12 * b20; const double a12b21 = a12 * b21; const double a10b01 = a10 * b01; const double a20b00 = a20 * b00; const double a21b10 = a21 * b10; const double a22b20 = a22 * b20; const double a20b01 = a20 * b01; const double a21b11 = a21 * b11; const double a22b21 = a22 * b21; const double a20b01_a21b11_a22b21 = a20b01 + a21b11 + a22b21; const double a20b00_a21b10_a22b20 = a20b00 + a21b10 + a22b20; const double a10b01_a11b11_a12b21 = a10b01 + a11b11 + a12b21; const double a00b01_a01b11_a02b21 = a00b01 + a01b11 + a02b21; const double a10b00_a11b10_a12b20 = a10b00 + a11b10 + a12b20; const double a00b00_a01b10_a02b20 = a00b00 + a01b10 + a02b20; const double cq = cos (q); const double sq = sin (q); result.P () = parent.P (); result.R () = rw::math::Rotation3D<> (a00b00_a01b10_a02b20 * cq + a00b01_a01b11_a02b21 * sq, a00b01_a01b11_a02b21 * cq - a00b00_a01b10_a02b20 * sq, a00 * b02 + a01 * b12 + a02 * b22, a10b00_a11b10_a12b20 * cq + a10b01_a11b11_a12b21 * sq, a10b01_a11b11_a12b21 * cq - a10b00_a11b10_a12b20 * sq, a10 * b02 + a11 * b12 + a12 * b22, a20b00_a21b10_a22b20 * cq + a20b01_a21b11_a22b21 * sq, a20b01_a21b11_a22b21 * cq - a20b00_a21b10_a22b20 * sq, a20 * b02 + a21 * b12 + a22 * b22); } rw::math::Transform3D<> RevoluteJoint::RevoluteJointZeroOffsetImpl::getTransform (double q) { const double b00 = _transform.R () (0, 0); const double b01 = _transform.R () (0, 1); const double b02 = _transform.R () (0, 2); const double b10 = _transform.R () (1, 0); const double b11 = _transform.R () (1, 1); const double b12 = _transform.R () (1, 2); const double b20 = _transform.R () (2, 0); const double b21 = _transform.R () (2, 1); const double b22 = _transform.R () (2, 2); const double cq = cos (q); const double sq = sin (q); rw::math::Transform3D<> result; result (0, 0) = b00 * cq + b01 * sq; result (0, 1) = b01 * cq - b00 * sq; result (0, 2) = b02; result (0, 3) = 0; result (1, 0) = b10 * cq + b11 * sq; result (1, 1) = b11 * cq - b10 * sq; result (1, 2) = b12; result (1, 3) = 0; result (2, 0) = b20 * cq + b21 * sq; result (2, 1) = b21 * cq - b20 * sq; result (2, 2) = b22; result (2, 3) = 0; return result; } rw::math::Transform3D<> RevoluteJoint::RevoluteJointZeroOffsetImpl::getFixedTransform () const { return _transform; } RevoluteJoint::RevoluteJointWithQMapping::RevoluteJointWithQMapping (const Transform3D<>& t3d, Function1Diff<>::Ptr mapping) : _mapping (mapping) { if (t3d.P () == Vector3D<> (0, 0, 0)) _impl = new RevoluteJointZeroOffsetImpl (t3d.R ()); else _impl = new RevoluteJointBasic (t3d); } RevoluteJoint::RevoluteJointWithQMapping::~RevoluteJointWithQMapping () { delete _impl; } void RevoluteJoint::RevoluteJointWithQMapping::multiplyTransform ( const rw::math::Transform3D<>& parent, double q, rw::math::Transform3D<>& result) const { double qnew = _mapping->f (q); _impl->multiplyTransform (parent, qnew, result); } rw::math::Transform3D<> RevoluteJoint::RevoluteJointWithQMapping::getTransform (double q) { double qnew = _mapping->f (q); return _impl->getTransform (qnew); } rw::math::Transform3D<> RevoluteJoint::RevoluteJointWithQMapping::getFixedTransform () const { return _impl->getFixedTransform (); } void RevoluteJoint::RevoluteJointWithQMapping::getJacobian (size_t row, size_t col, const Transform3D<>& joint, const Transform3D<>& tcp, double q, Jacobian& jacobian) const { Vector3D<> axis = joint.R ().getCol (2); // The axis is scaled with the first order derivative of the mapping to account for the mapping. axis *= _mapping->df (q); const Vector3D<> p = cross (axis, tcp.P () - joint.P ()); jacobian.addPosition (p, row, col); jacobian.addRotation (axis, row, col); }
37.5
100
0.551939
[ "transform" ]
9b7efd2a5c2f16cd801ea661bee60cf6051e5753
953
hpp
C++
wave_kinematics/include/wave/kinematics/two_wheel.hpp
wavelab/wavelib
7bebff52859c8b77f088e39913223904988c141e
[ "MIT" ]
80
2017-03-12T18:57:33.000Z
2022-03-30T11:44:33.000Z
wave_kinematics/include/wave/kinematics/two_wheel.hpp
wavelab/wavelib
7bebff52859c8b77f088e39913223904988c141e
[ "MIT" ]
210
2017-03-13T15:01:34.000Z
2022-01-15T03:19:44.000Z
wave_kinematics/include/wave/kinematics/two_wheel.hpp
wavelab/wavelib
7bebff52859c8b77f088e39913223904988c141e
[ "MIT" ]
31
2017-08-14T16:54:52.000Z
2022-01-21T06:44:16.000Z
/** @file * @ingroup kinematics */ #ifndef WAVE_KINEMATICS_TWOWHEEL_HPP #define WAVE_KINEMATICS_TWOWHEEL_HPP #include "wave/utils/utils.hpp" namespace wave { /** @addtogroup kinematics * @{ */ /** Generic two wheel robot motion model */ class TwoWheelRobot2DModel { public: /** Robot pose consisting of position in x and y (meters) and heading * (radians) */ Vec3 pose; TwoWheelRobot2DModel() : pose{0.0, 0.0, 0.0} {} explicit TwoWheelRobot2DModel(const Vec3 &pose) : pose{pose} {} /** Update two wheel model * * @param inputs Model input vector where first input is wheel velocity in * m/s and the second input is heading angular velocity rad/s * * @param dt Update time step in seconds * * @returns Updated pose of two wheel robot */ Vec3 update(const Vec2 &inputs, double dt); }; /** @} group kinematics */ } // namespace wave #endif // WAVE_KINEMATICS_TWOWHEEL_HPP
23.825
78
0.667366
[ "vector", "model" ]
9b80b7926eeff476d84ee6d2307c5a9fcb0aec56
174
cpp
C++
Dataset/Leetcode/test/136/428.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/test/136/428.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/test/136/428.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
class Solution { public: int singleNumber(vector<int>& nums) { int a=0; for(int num: nums){ a = a^num; } return a; } };
14.5
41
0.442529
[ "vector" ]
9b87c09747878b43b277c8681bb7024e0a42239a
13,714
cpp
C++
grasp_generation/graspitmodified_lm/Coin-3.1.3/src/shapenodes/SoIndexedNurbsSurface.cpp
KraftOreo/EBM_Hand
9ab1722c196b7eb99b4c3ecc85cef6e8b1887053
[ "MIT" ]
null
null
null
grasp_generation/graspitmodified_lm/Coin-3.1.3/src/shapenodes/SoIndexedNurbsSurface.cpp
KraftOreo/EBM_Hand
9ab1722c196b7eb99b4c3ecc85cef6e8b1887053
[ "MIT" ]
null
null
null
grasp_generation/graspitmodified_lm/Coin-3.1.3/src/shapenodes/SoIndexedNurbsSurface.cpp
KraftOreo/EBM_Hand
9ab1722c196b7eb99b4c3ecc85cef6e8b1887053
[ "MIT" ]
null
null
null
/**************************************************************************\ * * This file is part of the Coin 3D visualization library. * Copyright (C) by Kongsberg Oil & Gas Technologies. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * ("GPL") version 2 as published by the Free Software Foundation. * See the file LICENSE.GPL at the root directory of this source * distribution for additional information about the GNU GPL. * * For using Coin with software that can not be combined with the GNU * GPL, and for taking advantage of the additional benefits of our * support services, please contact Kongsberg Oil & Gas Technologies * about acquiring a Coin Professional Edition License. * * See http://www.coin3d.org/ for more information. * * Kongsberg Oil & Gas Technologies, Bygdoy Alle 5, 0257 Oslo, NORWAY. * http://www.sim.no/ sales@sim.no coin-support@coin3d.org * \**************************************************************************/ /*! \class SoIndexedNurbsSurface SoIndexedNurbsSurface.h Inventor/nodes/SoIndexedNurbsSurface.h \brief The SoIndexedNurbsSurface class can be used to render NURBS surfaces. \ingroup nodes It is very similar to the SoNurbsSurface class, but controlpoints can be specified using indices. <b>FILE FORMAT/DEFAULTS:</b> \code IndexedNurbsSurface { numUControlPoints 0 numVControlPoints 0 coordIndex 0 uKnotVector 0 vKnotVector 0 numSControlPoints 0 numTControlPoints 0 textureCoordIndex -1 sKnotVector 0 tKnotVector 0 } \endcode */ // FIXME: more class doc. Usage example! 20011220 mortene. #include <Inventor/nodes/SoIndexedNurbsSurface.h> #include "SoNurbsP.h" #ifdef HAVE_CONFIG_H #include <config.h> #endif // HAVE_CONFIG_H #include <Inventor/elements/SoCoordinateElement.h> #include <Inventor/elements/SoDrawStyleElement.h> #include <Inventor/bundles/SoMaterialBundle.h> #include <Inventor/actions/SoGLRenderAction.h> #include <Inventor/actions/SoRayPickAction.h> #include <Inventor/elements/SoPickStyleElement.h> #include <Inventor/misc/SoState.h> #include <Inventor/SoPrimitiveVertex.h> #include <Inventor/errors/SoDebugError.h> #include <Inventor/elements/SoGLCacheContextElement.h> #include <Inventor/elements/SoComplexityTypeElement.h> #include <Inventor/system/gl.h> #include "coindefs.h" // COIN_OBSOLETED() #include "glue/GLUWrapper.h" #include "nodes/SoSubNodeP.h" #include "misc/SoGL.h" /*! \var SoSFInt32 SoIndexedNurbsSurface::numUControlPoints Number of control points in the U direction. */ /*! \var SoSFInt32 SoIndexedNurbsSurface::numVControlPoints Number of control points in the V direction. */ /*! \var SoSFInt32 SoIndexedNurbsSurface::numSControlPoints Number of control points in the S direction. */ /*! \var SoSFInt32 SoIndexedNurbsSurface::numTControlPoints Number of control points in the T direction. */ /*! \var SoMFFloat SoIndexedNurbsSurface::uKnotVector The Bezier knot vector for the U direction. */ /*! \var SoMFFloat SoIndexedNurbsSurface::vKnotVector The Bezier knot vector for the V direction. */ /*! \var SoMFFloat SoIndexedNurbsSurface::sKnotVector The Bezier knot vector for the S direction. */ /*! \var SoMFFloat SoIndexedNurbsSurface::tKnotVector The Bezier knot vector for the T direction. */ /*! \var SoMFInt32 SoIndexedNurbsSurface::coordIndex The coordinate control point indices. */ /*! \var SoMFInt32 SoIndexedNurbsSurface::textureCoordIndex The texture coordinate control point indices. */ // ************************************************************************* class SoIndexedNurbsSurfaceP { public: SoIndexedNurbsSurfaceP(SoIndexedNurbsSurface * m) { this->owner = m; this->nurbsrenderer = NULL; this->offscreenctx = NULL; } ~SoIndexedNurbsSurfaceP() { if (this->offscreenctx) { cc_glglue_context_destruct(this->offscreenctx); } if (this->nurbsrenderer) { GLUWrapper()->gluDeleteNurbsRenderer(this->nurbsrenderer); } } void * offscreenctx; void * nurbsrenderer; void doNurbs(SoAction * action, const SbBool glrender); private: SoIndexedNurbsSurface * owner; }; #define PRIVATE(p) (p->pimpl) #define PUBLIC(p) (p->owner) // ************************************************************************* SO_NODE_SOURCE(SoIndexedNurbsSurface); /*! Constructor. */ SoIndexedNurbsSurface::SoIndexedNurbsSurface() { SO_NODE_INTERNAL_CONSTRUCTOR(SoIndexedNurbsSurface); SO_NODE_ADD_FIELD(numUControlPoints, (0)); SO_NODE_ADD_FIELD(numVControlPoints, (0)); SO_NODE_ADD_FIELD(coordIndex, (0)); SO_NODE_ADD_FIELD(uKnotVector, (0)); SO_NODE_ADD_FIELD(vKnotVector, (0)); SO_NODE_ADD_FIELD(numSControlPoints, (0)); SO_NODE_ADD_FIELD(numTControlPoints, (0)); SO_NODE_ADD_FIELD(textureCoordIndex, (-1)); SO_NODE_ADD_FIELD(sKnotVector, (0)); SO_NODE_ADD_FIELD(tKnotVector, (0)); PRIVATE(this) = new SoIndexedNurbsSurfaceP(this); } /*! Destructor. */ SoIndexedNurbsSurface::~SoIndexedNurbsSurface() { delete PRIVATE(this); } // doc from parent void SoIndexedNurbsSurface::initClass(void) { SO_NODE_INTERNAL_INIT_CLASS(SoIndexedNurbsSurface, SO_FROM_INVENTOR_1); } /*! Calculates the bounding box of all control points and sets the center to the average of these points. */ void SoIndexedNurbsSurface::computeBBox(SoAction * action, SbBox3f & box, SbVec3f & center) { SoState * state = action->getState(); const SoCoordinateElement * coordelem = SoCoordinateElement::getInstance(state); const int num = this->coordIndex.getNum(); const int32_t * idxptr = this->coordIndex.getValues(0); box.makeEmpty(); SbVec3f acccenter(0.0f, 0.0f, 0.0f); SbVec3f tmp3D; if (coordelem->is3D()) { const SbVec3f * coords = coordelem->getArrayPtr3(); assert(coords); for (int i = 0; i < num; i++) { tmp3D = coords[idxptr[i]]; box.extendBy(tmp3D); acccenter += tmp3D; } } else { const SbVec4f * coords = coordelem->getArrayPtr4(); assert(coords); for (int i = 0; i< num; i++) { coords[idxptr[i]].getReal(tmp3D); box.extendBy(tmp3D); acccenter += tmp3D; } } if (num) center = acccenter / float(num); } // Doc in superclass. void SoIndexedNurbsSurface::GLRender(SoGLRenderAction * action) { if (!this->shouldGLRender(action)) return; // initialize current material SoMaterialBundle mb(action); mb.sendFirst(); glEnable(GL_AUTO_NORMAL); PRIVATE(this)->doNurbs(action, TRUE); glDisable(GL_AUTO_NORMAL); SoState * state = action->getState(); if (SoComplexityTypeElement::get(state) == SoComplexityTypeElement::OBJECT_SPACE) { SoGLCacheContextElement::shouldAutoCache(state, SoGLCacheContextElement::DO_AUTO_CACHE); SoGLCacheContextElement::incNumShapes(state); } } // Doc in superclass. void SoIndexedNurbsSurface::rayPick(SoRayPickAction * action) { if (!this->shouldRayPick(action)) return; if (GLUWrapper()->versionMatchesAtLeast(1, 3, 0)) { SoShape::rayPick(action); // do normal generatePrimitives() pick } else { static SbBool firstpick = TRUE; if (firstpick) { firstpick = FALSE; SoDebugError::postWarning("SoIndexedNurbsSurface::rayPick", "Proper NURBS picking requires\n" "GLU version 1.3. Picking is done on bounding box."); } SoState * state = action->getState(); state->push(); SoPickStyleElement::set(state, this, SoPickStyleElement::BOUNDING_BOX); (void)this->shouldRayPick(action); // this will cause a pick on bbox state->pop(); } } // Documented in superclass. void SoIndexedNurbsSurface::getPrimitiveCount(SoGetPrimitiveCountAction * action) { // for now, just generate primitives to count. Very slow, of course. SoShape::getPrimitiveCount(action); } /*! This method is part of the original SGI Inventor API, but not implemented in Coin, as it looks like a method that should probably have been private in Open Inventor. */ void SoIndexedNurbsSurface::sendPrimitive(SoAction * , SoPrimitiveVertex *) { COIN_OBSOLETED(); } // Documented in superclass. void SoIndexedNurbsSurface::generatePrimitives(SoAction * action) { if (GLUWrapper()->versionMatchesAtLeast(1, 3, 0)) { // We've found that the SGI GLU NURBS renderer makes some OpenGL // calls even when in tessellate mode. So we need to set up an // offscreen context to be guaranteed to have a valid GL context // before making the GLU calls. if (PRIVATE(this)->offscreenctx == NULL) { PRIVATE(this)->offscreenctx = cc_glglue_context_create_offscreen(32, 32); } if (PRIVATE(this)->offscreenctx && cc_glglue_context_make_current(PRIVATE(this)->offscreenctx)) { PRIVATE(this)->doNurbs(action, FALSE); cc_glglue_context_reinstate_previous(PRIVATE(this)->offscreenctx); } } } // Documented in superclass. SoDetail * SoIndexedNurbsSurface::createTriangleDetail(SoRayPickAction * /* action */, const SoPrimitiveVertex * /*v1*/, const SoPrimitiveVertex * /*v2*/, const SoPrimitiveVertex * /*v3*/, SoPickedPoint * /* pp */) { return NULL; } typedef SoNurbsP<SoIndexedNurbsSurface>::coin_nurbs_cbdata coin_ins_cbdata; void SoIndexedNurbsSurfaceP::doNurbs(SoAction * action, const SbBool glrender) { if (GLUWrapper()->available == 0 || !GLUWrapper()->gluNewNurbsRenderer) { #if COIN_DEBUG static int first = 1; if (first) { SoDebugError::postInfo("SoIndexedNurbsCurveP::doNurbs", "Looks like your GLU library doesn't have NURBS " "functionality"); first = 0; } #endif // COIN_DEBUG return; } if (!PUBLIC(this)->coordIndex.getNum()) return; if (this->nurbsrenderer == NULL) { this->nurbsrenderer = GLUWrapper()->gluNewNurbsRenderer(); if (GLUWrapper()->versionMatchesAtLeast(1, 3, 0)) { GLUWrapper()->gluNurbsCallback(this->nurbsrenderer, (GLenum) GLU_NURBS_BEGIN_DATA, (gluNurbsCallback_cb_t)SoNurbsP<SoIndexedNurbsSurface>::tessBegin); GLUWrapper()->gluNurbsCallback(this->nurbsrenderer, (GLenum) GLU_NURBS_TEXTURE_COORD_DATA, (gluNurbsCallback_cb_t)SoNurbsP<SoIndexedNurbsSurface>::tessTexCoord); GLUWrapper()->gluNurbsCallback(this->nurbsrenderer, (GLenum) GLU_NURBS_NORMAL_DATA, (gluNurbsCallback_cb_t)SoNurbsP<SoIndexedNurbsSurface>::tessNormal); GLUWrapper()->gluNurbsCallback(this->nurbsrenderer, (GLenum) GLU_NURBS_VERTEX_DATA, (gluNurbsCallback_cb_t)SoNurbsP<SoIndexedNurbsSurface>::tessVertex); GLUWrapper()->gluNurbsCallback(this->nurbsrenderer, (GLenum) GLU_NURBS_END_DATA, (gluNurbsCallback_cb_t)SoNurbsP<SoIndexedNurbsSurface>::tessEnd); } } // NB, don't move this structure inside the if-statement. It needs // to be here so that the callbacks from sogl_render_nurbs_surface() // have a valid pointer to the structure. coin_ins_cbdata cbdata(action, PUBLIC(this), !SoCoordinateElement::getInstance(action->getState())->is3D()); if (GLUWrapper()->versionMatchesAtLeast(1, 3, 0)) { if (!glrender) { GLUWrapper()->gluNurbsCallbackData(this->nurbsrenderer, &cbdata); cbdata.vertex.setNormal(SbVec3f(0.0f, 0.0f, 1.0f)); cbdata.vertex.setMaterialIndex(0); cbdata.vertex.setTextureCoords(SbVec4f(0.0f, 0.0f, 0.0f, 1.0f)); cbdata.vertex.setPoint(SbVec3f(0.0f, 0.0f, 0.0f)); cbdata.vertex.setDetail(NULL); } } SbBool texindex = PUBLIC(this)->textureCoordIndex.getNum() && PUBLIC(this)->textureCoordIndex[0] >= 0; int displaymode = (int) GLU_FILL; if (glrender) { switch (SoDrawStyleElement::get(action->getState())) { case SoDrawStyleElement::LINES: displaymode = (int) GLU_OUTLINE_POLYGON; break; case SoDrawStyleElement::POINTS: // not possible to draw NURBS as points using GLU... displaymode = (int) GLU_OUTLINE_PATCH; break; default: break; } } GLUWrapper()->gluNurbsProperty(this->nurbsrenderer, (GLenum) GLU_DISPLAY_MODE, (GLfloat) displaymode); sogl_render_nurbs_surface(action, PUBLIC(this), this->nurbsrenderer, PUBLIC(this)->numUControlPoints.getValue(), PUBLIC(this)->numVControlPoints.getValue(), PUBLIC(this)->uKnotVector.getValues(0), PUBLIC(this)->vKnotVector.getValues(0), PUBLIC(this)->uKnotVector.getNum(), PUBLIC(this)->vKnotVector.getNum(), PUBLIC(this)->numSControlPoints.getValue(), PUBLIC(this)->numTControlPoints.getValue(), PUBLIC(this)->sKnotVector.getValues(0), PUBLIC(this)->tKnotVector.getValues(0), PUBLIC(this)->sKnotVector.getNum(), PUBLIC(this)->tKnotVector.getNum(), glrender, PUBLIC(this)->coordIndex.getNum(), PUBLIC(this)->coordIndex.getValues(0), texindex ? PUBLIC(this)->textureCoordIndex.getNum() : 0, texindex ? PUBLIC(this)->textureCoordIndex.getValues(0) : NULL); } #undef PRIVATE #undef PUBLIC
32.652381
167
0.664431
[ "render", "vector", "3d" ]
9b89cc18a27f902e3731d980eb4e68eeb563d208
8,308
hpp
C++
src/modules/lta_att_control/lta_att_control.hpp
flycloudline/Firmware
d8e36d8e025cbf288a2f816e03f368a8796cbc07
[ "BSD-3-Clause" ]
3
2020-04-29T13:16:19.000Z
2020-09-09T21:45:10.000Z
src/modules/lta_att_control/lta_att_control.hpp
flycloudline/Firmware
d8e36d8e025cbf288a2f816e03f368a8796cbc07
[ "BSD-3-Clause" ]
null
null
null
src/modules/lta_att_control/lta_att_control.hpp
flycloudline/Firmware
d8e36d8e025cbf288a2f816e03f368a8796cbc07
[ "BSD-3-Clause" ]
1
2020-04-27T17:53:40.000Z
2020-04-27T17:53:40.000Z
/**************************************************************************** * * Copyright (c) 2013-2018 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 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 OWNER 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 <lib/mixer/mixer.h> #include <matrix/matrix/math.hpp> #include <perf/perf_counter.h> #include <px4_config.h> #include <px4_defines.h> #include <px4_module.h> #include <px4_module_params.h> #include <px4_posix.h> #include <px4_platform_common/px4_work_queue/WorkItem.hpp> #include <uORB/Publication.hpp> #include <uORB/PublicationMulti.hpp> #include <uORB/Subscription.hpp> #include <uORB/SubscriptionCallback.hpp> #include <uORB/topics/actuator_controls.h> #include <uORB/topics/battery_status.h> #include <uORB/topics/manual_control_setpoint.h> #include <uORB/topics/multirotor_motor_limits.h> #include <uORB/topics/parameter_update.h> #include <uORB/topics/rate_ctrl_status.h> #include <uORB/topics/vehicle_angular_velocity.h> #include <uORB/topics/vehicle_attitude.h> #include <uORB/topics/vehicle_attitude_setpoint.h> #include <uORB/topics/vehicle_control_mode.h> #include <uORB/topics/vehicle_rates_setpoint.h> #include <uORB/topics/vehicle_status.h> #include <uORB/topics/vehicle_land_detected.h> #include <uORB/topics/landing_gear.h> #include <vtol_att_control/vtol_type.h> /** * Multicopter attitude control app start / stop handling function */ extern "C" __EXPORT int lta_att_control_main(int argc, char *argv[]); class LTAAttitudeControl : public ModuleBase<LTAAttitudeControl>, public ModuleParams, public px4::WorkItem { public: LTAAttitudeControl(); virtual ~LTAAttitudeControl(); /** @see ModuleBase */ static int task_spawn(int argc, char *argv[]); /** @see ModuleBase */ static int custom_command(int argc, char *argv[]); /** @see ModuleBase */ static int print_usage(const char *reason = nullptr); /** @see ModuleBase::print_status() */ int print_status() override; void Run() override; bool init(); private: /** * initialize some vectors/matrices from parameters */ void parameters_updated(); /** * Check for parameter update and handle it. */ void parameter_update_poll(); bool vehicle_attitude_poll(); void vehicle_motor_limits_poll(); void vehicle_status_poll(); void publish_actuator_controls(); void publish_rates_setpoint(); void publish_rate_controller_status(); /** * Generate & publish an attitude setpoint from stick inputs */ void generate_attitude_setpoint(float dt, bool reset_yaw_sp); /** * Get the landing gear state based on the manual control switch position * @return vehicle_attitude_setpoint_s::LANDING_GEAR_UP or vehicle_attitude_setpoint_s::LANDING_GEAR_DOWN */ float get_landing_gear_state(); /** * Attitude controller. */ void control_attitude(); /** * Attitude rates controller. */ void control_attitude_rates(float dt, const matrix::Vector3f &rates); uORB::Subscription _v_att_sub{ORB_ID(vehicle_attitude)}; /**< vehicle attitude subscription */ uORB::Subscription _v_att_sp_sub{ORB_ID(vehicle_attitude_setpoint)}; /**< vehicle attitude setpoint subscription */ uORB::Subscription _v_rates_sp_sub{ORB_ID(vehicle_rates_setpoint)}; /**< vehicle rates setpoint subscription */ uORB::Subscription _v_control_mode_sub{ORB_ID(vehicle_control_mode)}; /**< vehicle control mode subscription */ uORB::Subscription _parameter_update_sub{ORB_ID(parameter_update)}; /**< parameter updates subscription */ uORB::Subscription _manual_control_sp_sub{ORB_ID(manual_control_setpoint)}; /**< manual control setpoint subscription */ uORB::Subscription _vehicle_status_sub{ORB_ID(vehicle_status)}; /**< vehicle status subscription */ uORB::Subscription _motor_limits_sub{ORB_ID(multirotor_motor_limits)}; /**< motor limits subscription */ uORB::Subscription _battery_status_sub{ORB_ID(battery_status)}; /**< battery status subscription */ uORB::Subscription _vehicle_land_detected_sub{ORB_ID(vehicle_land_detected)}; /**< vehicle land detected subscription */ uORB::Subscription _landing_gear_sub{ORB_ID(landing_gear)}; uORB::SubscriptionCallbackWorkItem _vehicle_angular_velocity_sub{this, ORB_ID(vehicle_angular_velocity)}; uORB::PublicationMulti<rate_ctrl_status_s> _controller_status_pub{ORB_ID(rate_ctrl_status), ORB_PRIO_DEFAULT}; /**< controller status publication */ uORB::Publication<landing_gear_s> _landing_gear_pub{ORB_ID(landing_gear)}; uORB::Publication<vehicle_rates_setpoint_s> _v_rates_sp_pub{ORB_ID(vehicle_rates_setpoint)}; /**< rate setpoint publication */ orb_advert_t _actuators_0_pub{nullptr}; /**< attitude actuator controls publication */ orb_advert_t _vehicle_attitude_setpoint_pub{nullptr}; orb_id_t _actuators_id{nullptr}; /**< pointer to correct actuator controls0 uORB metadata structure */ orb_id_t _attitude_sp_id{nullptr}; /**< pointer to correct attitude setpoint uORB metadata structure */ bool _actuators_0_circuit_breaker_enabled{false}; /**< circuit breaker to suppress output */ struct vehicle_attitude_s _v_att {}; /**< vehicle attitude */ struct vehicle_attitude_setpoint_s _v_att_sp {}; /**< vehicle attitude setpoint */ struct vehicle_rates_setpoint_s _v_rates_sp {}; /**< vehicle rates setpoint */ struct manual_control_setpoint_s _manual_control_sp {}; /**< manual control setpoint */ struct vehicle_control_mode_s _v_control_mode {}; /**< vehicle control mode */ struct actuator_controls_s _actuators {}; /**< actuator controls */ struct vehicle_status_s _vehicle_status {}; /**< vehicle status */ struct battery_status_s _battery_status {}; /**< battery status */ struct vehicle_land_detected_s _vehicle_land_detected {}; struct landing_gear_s _landing_gear {}; MultirotorMixer::saturation_status _saturation_status{}; perf_counter_t _loop_perf; /**< loop performance counter */ static constexpr const float initial_update_rate_hz = 250.f; /**< loop update rate used for initialization */ float _loop_update_rate_hz{initial_update_rate_hz}; /**< current rate-controller loop update rate in [Hz] */ matrix::Vector3f _rates_sp; /**< angular rates setpoint */ matrix::Vector3f _att_control; /**< attitude control vector */ float _thrust_sp{0.0f}; /**< thrust setpoint */ float _man_yaw_sp{0.f}; /**< current yaw setpoint in manual mode */ bool _gear_state_initialized{false}; /**< true if the gear state has been initialized */ hrt_abstime _task_start{hrt_absolute_time()}; hrt_abstime _last_run{0}; float _dt_accumulator{0.0f}; int _loop_counter{0}; bool _reset_yaw_sp{true}; float _attitude_dt{0.0f}; bool _is_tailsitter{false}; matrix::Vector3f _acro_rate_max; /**< max attitude rates in acro mode */ float _man_tilt_max; /**< maximum tilt allowed for manual flight [rad] */ };
41.54
149
0.752648
[ "vector" ]
9b906df2578b373672ba38ab97f531e7a7e7fe4f
5,951
cpp
C++
cpp/godot-cpp/src/gen/TouchScreenButton.cpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
1
2021-03-16T09:51:00.000Z
2021-03-16T09:51:00.000Z
cpp/godot-cpp/src/gen/TouchScreenButton.cpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
null
null
null
cpp/godot-cpp/src/gen/TouchScreenButton.cpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
null
null
null
#include "TouchScreenButton.hpp" #include <core/GodotGlobal.hpp> #include <core/CoreTypes.hpp> #include <core/Ref.hpp> #include <core/Godot.hpp> #include "__icalls.hpp" #include "InputEvent.hpp" #include "BitMap.hpp" #include "Shape2D.hpp" #include "Texture.hpp" namespace godot { TouchScreenButton::___method_bindings TouchScreenButton::___mb = {}; void TouchScreenButton::___init_method_bindings() { ___mb.mb__input = godot::api->godot_method_bind_get_method("TouchScreenButton", "_input"); ___mb.mb_get_action = godot::api->godot_method_bind_get_method("TouchScreenButton", "get_action"); ___mb.mb_get_bitmask = godot::api->godot_method_bind_get_method("TouchScreenButton", "get_bitmask"); ___mb.mb_get_shape = godot::api->godot_method_bind_get_method("TouchScreenButton", "get_shape"); ___mb.mb_get_texture = godot::api->godot_method_bind_get_method("TouchScreenButton", "get_texture"); ___mb.mb_get_texture_pressed = godot::api->godot_method_bind_get_method("TouchScreenButton", "get_texture_pressed"); ___mb.mb_get_visibility_mode = godot::api->godot_method_bind_get_method("TouchScreenButton", "get_visibility_mode"); ___mb.mb_is_passby_press_enabled = godot::api->godot_method_bind_get_method("TouchScreenButton", "is_passby_press_enabled"); ___mb.mb_is_pressed = godot::api->godot_method_bind_get_method("TouchScreenButton", "is_pressed"); ___mb.mb_is_shape_centered = godot::api->godot_method_bind_get_method("TouchScreenButton", "is_shape_centered"); ___mb.mb_is_shape_visible = godot::api->godot_method_bind_get_method("TouchScreenButton", "is_shape_visible"); ___mb.mb_set_action = godot::api->godot_method_bind_get_method("TouchScreenButton", "set_action"); ___mb.mb_set_bitmask = godot::api->godot_method_bind_get_method("TouchScreenButton", "set_bitmask"); ___mb.mb_set_passby_press = godot::api->godot_method_bind_get_method("TouchScreenButton", "set_passby_press"); ___mb.mb_set_shape = godot::api->godot_method_bind_get_method("TouchScreenButton", "set_shape"); ___mb.mb_set_shape_centered = godot::api->godot_method_bind_get_method("TouchScreenButton", "set_shape_centered"); ___mb.mb_set_shape_visible = godot::api->godot_method_bind_get_method("TouchScreenButton", "set_shape_visible"); ___mb.mb_set_texture = godot::api->godot_method_bind_get_method("TouchScreenButton", "set_texture"); ___mb.mb_set_texture_pressed = godot::api->godot_method_bind_get_method("TouchScreenButton", "set_texture_pressed"); ___mb.mb_set_visibility_mode = godot::api->godot_method_bind_get_method("TouchScreenButton", "set_visibility_mode"); } TouchScreenButton *TouchScreenButton::_new() { return (TouchScreenButton *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, godot::api->godot_get_class_constructor((char *)"TouchScreenButton")()); } void TouchScreenButton::_input(const Ref<InputEvent> arg0) { ___godot_icall_void_Object(___mb.mb__input, (const Object *) this, arg0.ptr()); } String TouchScreenButton::get_action() const { return ___godot_icall_String(___mb.mb_get_action, (const Object *) this); } Ref<BitMap> TouchScreenButton::get_bitmask() const { return Ref<BitMap>::__internal_constructor(___godot_icall_Object(___mb.mb_get_bitmask, (const Object *) this)); } Ref<Shape2D> TouchScreenButton::get_shape() const { return Ref<Shape2D>::__internal_constructor(___godot_icall_Object(___mb.mb_get_shape, (const Object *) this)); } Ref<Texture> TouchScreenButton::get_texture() const { return Ref<Texture>::__internal_constructor(___godot_icall_Object(___mb.mb_get_texture, (const Object *) this)); } Ref<Texture> TouchScreenButton::get_texture_pressed() const { return Ref<Texture>::__internal_constructor(___godot_icall_Object(___mb.mb_get_texture_pressed, (const Object *) this)); } TouchScreenButton::VisibilityMode TouchScreenButton::get_visibility_mode() const { return (TouchScreenButton::VisibilityMode) ___godot_icall_int(___mb.mb_get_visibility_mode, (const Object *) this); } bool TouchScreenButton::is_passby_press_enabled() const { return ___godot_icall_bool(___mb.mb_is_passby_press_enabled, (const Object *) this); } bool TouchScreenButton::is_pressed() const { return ___godot_icall_bool(___mb.mb_is_pressed, (const Object *) this); } bool TouchScreenButton::is_shape_centered() const { return ___godot_icall_bool(___mb.mb_is_shape_centered, (const Object *) this); } bool TouchScreenButton::is_shape_visible() const { return ___godot_icall_bool(___mb.mb_is_shape_visible, (const Object *) this); } void TouchScreenButton::set_action(const String action) { ___godot_icall_void_String(___mb.mb_set_action, (const Object *) this, action); } void TouchScreenButton::set_bitmask(const Ref<BitMap> bitmask) { ___godot_icall_void_Object(___mb.mb_set_bitmask, (const Object *) this, bitmask.ptr()); } void TouchScreenButton::set_passby_press(const bool enabled) { ___godot_icall_void_bool(___mb.mb_set_passby_press, (const Object *) this, enabled); } void TouchScreenButton::set_shape(const Ref<Shape2D> shape) { ___godot_icall_void_Object(___mb.mb_set_shape, (const Object *) this, shape.ptr()); } void TouchScreenButton::set_shape_centered(const bool _bool) { ___godot_icall_void_bool(___mb.mb_set_shape_centered, (const Object *) this, _bool); } void TouchScreenButton::set_shape_visible(const bool _bool) { ___godot_icall_void_bool(___mb.mb_set_shape_visible, (const Object *) this, _bool); } void TouchScreenButton::set_texture(const Ref<Texture> texture) { ___godot_icall_void_Object(___mb.mb_set_texture, (const Object *) this, texture.ptr()); } void TouchScreenButton::set_texture_pressed(const Ref<Texture> texture_pressed) { ___godot_icall_void_Object(___mb.mb_set_texture_pressed, (const Object *) this, texture_pressed.ptr()); } void TouchScreenButton::set_visibility_mode(const int64_t mode) { ___godot_icall_void_int(___mb.mb_set_visibility_mode, (const Object *) this, mode); } }
45.776923
215
0.806419
[ "object", "shape" ]
9b90a3489fe1b992d1d31b48a13811847b313d17
475
cpp
C++
stats.cpp
clean-code-craft-tcq-1/start-stats-cpp-SangeethaChandran2021
d3982413232cfc60a120f9db718945d4c74751ea
[ "MIT" ]
null
null
null
stats.cpp
clean-code-craft-tcq-1/start-stats-cpp-SangeethaChandran2021
d3982413232cfc60a120f9db718945d4c74751ea
[ "MIT" ]
null
null
null
stats.cpp
clean-code-craft-tcq-1/start-stats-cpp-SangeethaChandran2021
d3982413232cfc60a120f9db718945d4c74751ea
[ "MIT" ]
null
null
null
#include "stats.h" #include <algorithm> using namespace Statistics; Stats Statistics::ComputeStatistics(const std::vector<float>& vect) { Stats tStats; float sum = 0.0F; for(std::vector<float>::const_iterator itr = vect.begin(); itr!=vect.end(); ++itr) { sum+= *itr; } tStats.min = *std::min_element(vect.begin(),vect.end()); tStats.max = *std::max_element(vect.begin(),vect.end()); tStats.avg = sum / vect.size(); return tStats; }
23.75
85
0.635789
[ "vector" ]
9b90ac42c5f73b0d72c655e6c1a8833a2df644aa
3,940
cpp
C++
Source/Client/IM-Client/IMClient/PictureObj.cpp
InstantBusinessNetwork/IBN
bbcf47de56bfc52049eeb2e46677642a28f38825
[ "MIT" ]
21
2015-07-22T15:22:41.000Z
2021-03-23T05:40:44.000Z
Source/Client/IM-Client/IMClient/PictureObj.cpp
InstantBusinessNetwork/IBN
bbcf47de56bfc52049eeb2e46677642a28f38825
[ "MIT" ]
11
2015-10-19T07:54:10.000Z
2021-09-01T08:47:56.000Z
Source/Client/IM-Client/IMClient/PictureObj.cpp
InstantBusinessNetwork/IBN
bbcf47de56bfc52049eeb2e46677642a28f38825
[ "MIT" ]
16
2015-07-22T15:23:09.000Z
2022-01-17T10:49:43.000Z
// PictureObj.cpp: implementation of the CPictureObj class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ofstv.h" #include "PictureObj.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif #define HIMETRIC_PER_INCH 2540 #define MAP_PIX_TO_LOGHIM(x,ppli) ( (HIMETRIC_PER_INCH*(x) + ((ppli)>>1)) / (ppli) ) #define MAP_LOGHIM_TO_PIX(x,ppli) ( ((ppli)*(x) + HIMETRIC_PER_INCH/2) / HIMETRIC_PER_INCH ) ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CPictureObj::CPictureObj() { m_pPicture = NULL; x = 0; y = 0; cx = 0; cy = 0; } CPictureObj::~CPictureObj() { if(m_pPicture) { delete m_pPicture; m_pPicture = NULL; } } BOOL CPictureObj::Create(IStream *pStream, long x, long y, long cx, long cy) { ASSERT(pStream != NULL); ASSERT(m_pPicture == NULL); BOOL bResult = FALSE; LPPICTURE pic = NULL; HRESULT hr = ::OleLoadPicture(pStream, 0, TRUE, IID_IPicture, (void**)&pic); if(SUCCEEDED(hr) && pic != NULL) { m_pPicture = new CResizableImage; m_pPicture->Create(pic); this->x = x; this->y = y; if(cx > 0 && cy > 0) { this->cx = cx; this->cy = cy; } else { pic->get_Width(&m_RealSize.cx); pic->get_Height(&m_RealSize.cy); HiMetricToPixel(&m_RealSize, &m_RealSize); this->cx = m_RealSize.cx; this->cy = m_RealSize.cy; } pic->Release(); bResult = TRUE; } return bResult; } void CPictureObj::GetRect(LPRECT pRect) { pRect->left = x; pRect->top = y; pRect->right = x + cx; pRect->bottom = y + cy; } void CPictureObj::SetRect(long x, long y, long cx, long cy) { this->x = x; this->y = y; this->cx = cx; this->cy = cy; } void CPictureObj::Render(HDC hDC) { if(m_pPicture) { RECT r; r.left = x; r.right = x + cx; r.top = y; r.bottom = y + cy; m_pPicture->Render(hDC, r); } } inline void CPictureObj::HiMetricToPixel(const SIZEL *lpSizeInHiMetric, LPSIZEL lpSizeInPix) { int nPixelsPerInchX; // Pixels per logical inch along width int nPixelsPerInchY; // Pixels per logical inch along height HDC hDCScreen = GetDC(NULL); _ASSERTE(hDCScreen != NULL); nPixelsPerInchX = GetDeviceCaps(hDCScreen, LOGPIXELSX); nPixelsPerInchY = GetDeviceCaps(hDCScreen, LOGPIXELSY); ReleaseDC(NULL, hDCScreen); lpSizeInPix->cx = MAP_LOGHIM_TO_PIX(lpSizeInHiMetric->cx, nPixelsPerInchX); lpSizeInPix->cy = MAP_LOGHIM_TO_PIX(lpSizeInHiMetric->cy, nPixelsPerInchY); } inline void CPictureObj::PixelToHiMetric(const SIZEL *lpSizeInPix, LPSIZEL lpSizeInHiMetric) { int nPixelsPerInchX; // Pixels per logical inch along width int nPixelsPerInchY; // Pixels per logical inch along height HDC hDCScreen = GetDC(NULL); _ASSERTE(hDCScreen != NULL); nPixelsPerInchX = GetDeviceCaps(hDCScreen, LOGPIXELSX); nPixelsPerInchY = GetDeviceCaps(hDCScreen, LOGPIXELSY); ReleaseDC(NULL, hDCScreen); lpSizeInHiMetric->cx = MAP_PIX_TO_LOGHIM(lpSizeInPix->cx, nPixelsPerInchX); lpSizeInHiMetric->cy = MAP_PIX_TO_LOGHIM(lpSizeInPix->cy, nPixelsPerInchY); } void CPictureObj::AddWholeImage(CResizableImage::ZoomType ZoomVal) { ASSERT(m_pPicture != NULL); if(m_pPicture) m_pPicture->AddWholeImage(ZoomVal); } void CPictureObj::Render(HDC hDC, RECT r) { ASSERT(m_pPicture != NULL); if(m_pPicture) m_pPicture->Render(hDC, r); } void CPictureObj::AddFragment(RECT PixelSurface, SIZE LTType, SIZE RBType, long type) { ASSERT(m_pPicture != NULL); if(m_pPicture == NULL) return; CResizableImage::ZoomType ztype = CResizableImage::STRETCH; if(type == 2) ztype = CResizableImage::DUPLICATE; m_pPicture->AddAnchor(PixelSurface, LTType, RBType, ztype); }
24.47205
95
0.636802
[ "render" ]
9b9c605ea94c204eec2beabad8214bc16ea8405c
604
cpp
C++
C++/maximum-absolute-sum-of-any-subarray.cpp
Priyansh2/LeetCode-Solutions
d613da1881ec2416ccbe15f20b8000e36ddf1291
[ "MIT" ]
3,269
2018-10-12T01:29:40.000Z
2022-03-31T17:58:41.000Z
C++/maximum-absolute-sum-of-any-subarray.cpp
Priyansh2/LeetCode-Solutions
d613da1881ec2416ccbe15f20b8000e36ddf1291
[ "MIT" ]
53
2018-12-16T22:54:20.000Z
2022-02-25T08:31:20.000Z
C++/maximum-absolute-sum-of-any-subarray.cpp
Priyansh2/LeetCode-Solutions
d613da1881ec2416ccbe15f20b8000e36ddf1291
[ "MIT" ]
1,236
2018-10-12T02:51:40.000Z
2022-03-30T13:30:37.000Z
// Time: O(n) // Space: O(1) class Solution { public: int maxAbsoluteSum(vector<int>& nums) { int curr = 0, mx = 0, mn = 0; for (const auto& num : nums) { curr += num; mx = max(mx, curr); mn = min(mn, curr); } return mx - mn; } }; // Time: O(n) // Space: O(1) class Solution2 { public: int maxAbsoluteSum(vector<int>& nums) { partial_sum(begin(nums), end(nums), begin(nums)); return max(*max_element(cbegin(nums), cend(nums)), 0) - min(*min_element(cbegin(nums), cend(nums)), 0); } };
22.37037
63
0.504967
[ "vector" ]
9ba686f80d6e60a3822070e90c58de03cdec43dc
986
cpp
C++
SiSiMEX/SiSiMEX/AgentContainer.cpp
UndistinguishedFellows/NetworkingP5_SiSimex
1e9baa856b2eae1d77fbc7d4a4aa0792124bca87
[ "MIT" ]
null
null
null
SiSiMEX/SiSiMEX/AgentContainer.cpp
UndistinguishedFellows/NetworkingP5_SiSimex
1e9baa856b2eae1d77fbc7d4a4aa0792124bca87
[ "MIT" ]
null
null
null
SiSiMEX/SiSiMEX/AgentContainer.cpp
UndistinguishedFellows/NetworkingP5_SiSimex
1e9baa856b2eae1d77fbc7d4a4aa0792124bca87
[ "MIT" ]
null
null
null
#include "AgentContainer.h" AgentContainer::AgentContainer() { } AgentContainer::~AgentContainer() { } void AgentContainer::addAgent(AgentPtr agent) { _agents.push_back(agent); } AgentPtr AgentContainer::getAgent(int agentId) { // Agent search for (auto agent : _agents) { if (agent->id() == agentId) { return agent; } } return nullptr; } bool AgentContainer::empty() const { return _agents.empty(); } void AgentContainer::update() { // Update all agents for (auto agent : _agents) { if (!agent->finished()) { agent->update(); } } } void AgentContainer::postUpdate() { // Track alive agents std::vector<AgentPtr> agentsAlive; // Update all agents for (auto agent : _agents) { // Keep track of alive agents if (!agent->finished()) { agentsAlive.push_back(agent); } } // Remove finished agents _agents.swap(agentsAlive); } void AgentContainer::finalize() { // Update all agents for (auto agent : _agents) { agent->finalize(); } }
14.085714
46
0.670385
[ "vector" ]
9ba7020a4f43a37070770b6f5a1c50c78f01f669
2,473
hpp
C++
test/unit_tests/shared/worker.hpp
egor-tensin/winapi-common
0691ab3e886fcac63a6ed13a346ad16ae90ee5cb
[ "MIT" ]
null
null
null
test/unit_tests/shared/worker.hpp
egor-tensin/winapi-common
0691ab3e886fcac63a6ed13a346ad16ae90ee5cb
[ "MIT" ]
null
null
null
test/unit_tests/shared/worker.hpp
egor-tensin/winapi-common
0691ab3e886fcac63a6ed13a346ad16ae90ee5cb
[ "MIT" ]
1
2021-10-30T20:18:50.000Z
2021-10-30T20:18:50.000Z
// Copyright (c) 2020 Egor Tensin <Egor.Tensin@gmail.com> // This file is part of the "winapi-common" project. // For details, see https://github.com/egor-tensin/winapi-common. // Distributed under the MIT License. #pragma once #include "command.hpp" #include <winapi/process.hpp> #include <windows.h> #include <exception> #include <string> #include <utility> #include <vector> namespace worker { class Worker { public: Worker(winapi::Process&& process) : m_cmd{Command::create()}, m_process{std::move(process)} {} Worker(Worker&& other) noexcept = default; Worker(const Worker&) = delete; Worker& operator=(const Worker& other) noexcept = default; ~Worker() { try { if (m_process.is_running()) { exit(); } } catch (const std::exception&) { } } HWND get_console_window() { HWND ret = NULL; m_cmd->get_result(Command::GET_CONSOLE_WINDOW, [&ret](const Command::Result& result) { ret = result.console_window; }); return ret; } bool is_window_visible() { bool ret = false; m_cmd->get_result(Command::IS_WINDOW_VISIBLE, [&ret](const Command::Result& result) { ret = result.is_window_visible; }); return ret; } StdHandles get_std_handles() { StdHandles ret; m_cmd->get_result(Command::GET_STD_HANDLES, [&ret](const Command::Result& result) { ret = result.std_handles; }); return ret; } StdHandles test_write() { StdHandles ret; m_cmd->get_result(Command::TEST_WRITE, [&ret](const Command::Result& result) { ret = result.std_handles; }); return ret; } std::vector<std::string> read_last_lines(std::size_t numof_lines) { std::vector<std::string> ret; const auto set_args = [numof_lines](Command::Args& args) { args.numof_lines = numof_lines; }; const auto read_result = [&ret](const Command::Result& result) { ret = result.console_buffer.extract(); }; m_cmd->get_result(Command::GET_CONSOLE_BUFFER, set_args, read_result); return ret; } int exit() { m_cmd->get_result(Command::EXIT); m_process.wait(); return m_process.get_exit_code(); } private: Command::Shared m_cmd; winapi::Process m_process; }; } // namespace worker
27.175824
98
0.596846
[ "vector" ]
9bafffefddc649ce22ed188bbe0b4187a9b672d7
1,948
cpp
C++
NCGB/Compile/src/RuleInformation.cpp
mcdeoliveira/NC
54b2a81ebda9e5260328f88f83f56fe8cf472ac3
[ "BSD-3-Clause" ]
103
2016-09-21T06:01:23.000Z
2022-03-27T06:52:10.000Z
NCGB/Compile/src/RuleInformation.cpp
albinjames/NC
157a55458931a18dd1f42478872c9df0de5cc450
[ "BSD-3-Clause" ]
11
2017-03-27T13:11:42.000Z
2022-03-08T13:46:14.000Z
NCGB/Compile/src/RuleInformation.cpp
albinjames/NC
157a55458931a18dd1f42478872c9df0de5cc450
[ "BSD-3-Clause" ]
21
2017-06-23T09:01:21.000Z
2022-02-18T06:24:00.000Z
// RuleInformation.c #include "RuleInformation.hpp" bool RuleInformation::divides(const RuleInformation & ri, Monomial & front,Monomial & back) const { bool result = false; int m = degree(); int n = ri.degree(); if((m==n)&&(d_r.LHS()==ri.d_r.LHS())) { front.setToOne(); back.setToOne(); result = true; } else if(m<n && dividesDoubleCount(variableDoubleCounts(), ri.variableDoubleCounts()) ) { result = true; DBG(); }; return result; }; // Determine if small is a subset of big. Both vectors are sorted. bool RuleInformation::dividesDoubleCount(const vector<int> & small, const vector<int> & big) const { bool result = true; int szSmall = small.size(); int szBig = big.size(); vector<int>::const_iterator ww = big.begin(); vector<int>::const_iterator ee = big.end(); vector<int>::const_iterator w = small.begin(); vector<int>::const_iterator e = small.end(); while(w!=e && result) { result = szSmall<=szBig; int n = *w; while(szSmall<=szBig&& ww!=ee &&*ww<n) {++ww;--szBig;} if(szSmall>szBig || ww==ee) { result = false; } else { result = *ww==n; }; ++w; --szSmall; }; return result; }; // can use Table[Prime[i],{i,1,n}] to get the first n primes int RuleInformation::s_primes[100] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541}; int RuleInformation::s_number_primes = 100;
33.016949
78
0.571355
[ "vector" ]
9bb3ba5de383639a33f45fda22ead36896563438
2,860
hpp
C++
tests/FiveWar/project/Classes/gameai/entityshapes/ps/WallPic.hpp
lyzardiar/engine-x
e4fed534b41cba0e7296f0c3ddfe4e853cc3772f
[ "MIT" ]
null
null
null
tests/FiveWar/project/Classes/gameai/entityshapes/ps/WallPic.hpp
lyzardiar/engine-x
e4fed534b41cba0e7296f0c3ddfe4e853cc3772f
[ "MIT" ]
null
null
null
tests/FiveWar/project/Classes/gameai/entityshapes/ps/WallPic.hpp
lyzardiar/engine-x
e4fed534b41cba0e7296f0c3ddfe4e853cc3772f
[ "MIT" ]
null
null
null
/* * Copyright (c) 2014 Peter Lager * <quark(a)lagers.org.uk> http:www.lagers.org.uk * * This software is provided 'as-is', without any express or implied warranty. * In no event will the authors be held liable for any damages arising from * the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it freely, * subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; * you must not claim that you wrote the original software. * If you use this software in a product, an acknowledgment in the product * documentation would be appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, * and must not be misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. */ package game2dai.entityshapes.ps; import game2dai.entities.BaseEntity; import game2dai.entities.Wall; import processing.core.PApplet; /** * A very basic wall picture created using a single line. <br> * * * @author Peter Lager * */ public class WallPic extends PicturePS { private int strokeCol; private float strokeWeight; /** * A thin black line. * @param papp */ public WallPic(PApplet papp){ super(papp); strokeCol = app.color(0); strokeWeight = 1f; } /** * User selected line colour and thickness. * @param papp * @param stroke the line colour * @param weight the line thickness */ public WallPic(PApplet papp, int stroke, float weight){ super(papp); strokeCol = stroke; strokeWeight = weight; } /** * Draw the entity. * @param owner the entity that owns this renderer. * @param posX real world position (x) * @param posY real world position (x) * @param velX magnitude of the velocity vector in the x direction * @param velY magnitude of the velocity vector in the y direction * @param headX magnitude of the heading vector in the x direction * @param headY magnitude of the heading vector in the y direction * @param etime the elapsed time in seconds since last update */ @Override public void draw(BaseEntity owner, float posX, float posY, float velX, float velY, float headX, float headY, float etime) { Wall w = (Wall) owner; // Prepare to draw entity app.pushStyle(); app.pushMatrix(); // Draw the wall app.strokeWeight(strokeWeight); app.stroke(strokeCol); app.line(posX, posY, (float)w.getEndPos().x, (float)w.getEndPos().y); // Finished drawing app.popMatrix(); app.popStyle(); } /** * Set wall colour and thickness (stroke weight) * * @param col * @param thickness */ public void wallDetails(int col, float thickness){ strokeCol = col; strokeWeight = thickness; } }
26.981132
83
0.709441
[ "vector" ]
9bb979561b3bacb1c209d4feb18abfd3a1b3be37
3,478
cc
C++
sources/player.cc
dvzrv/adljack
0b896bf77d3df06d57810fef6e91bc4cf8a1669d
[ "BSL-1.0" ]
26
2018-04-09T09:00:50.000Z
2022-02-09T03:12:49.000Z
sources/player.cc
dvzrv/adljack
0b896bf77d3df06d57810fef6e91bc4cf8a1669d
[ "BSL-1.0" ]
19
2018-05-10T20:29:21.000Z
2021-02-13T22:16:09.000Z
sources/player.cc
dvzrv/adljack
0b896bf77d3df06d57810fef6e91bc4cf8a1669d
[ "BSL-1.0" ]
6
2018-05-10T20:11:46.000Z
2020-07-10T19:06:28.000Z
// Copyright Jean Pierre Cimalando 2018. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE or copy at // http://www.boost.org/LICENSE_1_0.txt) #include "player.h" #include <stdlib.h> #include <string.h> #include <assert.h> Player *Player::create(Player_Type pt, unsigned sample_rate) { std::unique_ptr<Player> instance; switch (pt) { default: assert(false); abort(); #define PLAYER_CASE(x) \ case Player_Type::x: instance.reset(new Generic_Player<Player_Type::x>); break; EACH_PLAYER_TYPE(PLAYER_CASE); #undef PLAYER_CASE } if (!instance->init(sample_rate)) return nullptr; return instance.release(); } const char *Player::name(Player_Type pt) { switch (pt) { default: assert(false); abort(); #define PLAYER_CASE(x) \ case Player_Type::x: return Player_Traits<Player_Type::x>::name(); EACH_PLAYER_TYPE(PLAYER_CASE); #undef PLAYER_CASE } } const char *Player::version(Player_Type pt) { switch (pt) { default: assert(false); abort(); #define PLAYER_CASE(x) \ case Player_Type::x: return Player_Traits<Player_Type::x>::version(); EACH_PLAYER_TYPE(PLAYER_CASE); #undef PLAYER_CASE } } const char *Player::chip_name(Player_Type pt) { switch (pt) { default: assert(false); abort(); #define PLAYER_CASE(x) \ case Player_Type::x: return Player_Traits<Player_Type::x>::chip_name(); EACH_PLAYER_TYPE(PLAYER_CASE); #undef PLAYER_CASE } } double Player::output_gain(Player_Type pt) { switch (pt) { default: assert(false); abort(); #define PLAYER_CASE(x) \ case Player_Type::x: return Player_Traits<Player_Type::x>::output_gain; EACH_PLAYER_TYPE(PLAYER_CASE); #undef PLAYER_CASE } } auto Player::enumerate_emulators(Player_Type pt) -> std::vector<Emulator> { std::vector<Emulator> emus; emus.reserve(32); std::unique_ptr<Player> player(create(pt, 44100)); for (unsigned i = 0; i < 32; ++i) { if (player->set_emulator(i)) { Emulator emu; emu.id = i; emu.name = player->emulator_name(); emus.push_back(emu); } } return emus; } unsigned Player::emulator_by_name(Player_Type pt, const char *name) { std::vector<Emulator> emus = enumerate_emulators(pt); for (unsigned i = 0, n = emus.size(); i < n; ++i) if (!strcmp(emus[i].name, name)) return i; return (unsigned)-1; } Player_Type Player::type_by_name(const char *nam) { for (Player_Type pt : all_player_types) if (!strcmp(nam, name(pt))) return pt; return (Player_Type)-1; } bool Player::dynamic_set_chip_count(unsigned nchip) { auto lock = take_lock(); panic(); return set_chip_count(nchip); } bool Player::dynamic_set_emulator(unsigned emulator) { auto lock = take_lock(); panic(); return set_emulator(emulator); } bool Player::dynamic_load_bank(const char *bankfile) { auto lock = take_lock(); panic(); if (!load_bank_file(bankfile)) return false; return true; } void Player::dynamic_panic() { auto lock = take_lock(); panic(); }
26.150376
87
0.597757
[ "vector" ]
9bbad8a10fda190683f638009dde08370712bf4b
770
cpp
C++
LazyEngine/LazyEngine/src/LazyEngine/Renderer/RenderCommand.cpp
PhiliGuertler/ManifoldDMC
d9740e17ebadce0320f7cfb7dbb1cd728119a8ab
[ "MIT" ]
null
null
null
LazyEngine/LazyEngine/src/LazyEngine/Renderer/RenderCommand.cpp
PhiliGuertler/ManifoldDMC
d9740e17ebadce0320f7cfb7dbb1cd728119a8ab
[ "MIT" ]
null
null
null
LazyEngine/LazyEngine/src/LazyEngine/Renderer/RenderCommand.cpp
PhiliGuertler/ManifoldDMC
d9740e17ebadce0320f7cfb7dbb1cd728119a8ab
[ "MIT" ]
null
null
null
// ######################################################################### // // ### RenderCommand.cpp ################################################### // // ### Creates the rendererAPI implementation object, depending on the ### // // ### platform (OpenGL, Vulcan, ...). ### // // ######################################################################### // #include "LazyEngine/gepch.h" #include "RenderCommand.h" // --- OpenGL implementations --- // #include "LazyEngine/platform/OpenGL/OpenGLRendererAPI.h" // --- OpenGL implementations --- // namespace LazyEngine { // FIXME: dynamically create the rendererapi on application start Scope<RendererAPI> RenderCommand::s_rendererAPI = createScope<OpenGLRendererAPI>(); }
40.526316
84
0.479221
[ "object" ]
9bc5a89b67b877542906830a9660d3fbd6dac61d
2,457
cc
C++
cpp/Rendering_calendar.cc
iskhanba/epicode
fda752e5e016ab64011083450be91bec9ee8358a
[ "MIT" ]
null
null
null
cpp/Rendering_calendar.cc
iskhanba/epicode
fda752e5e016ab64011083450be91bec9ee8358a
[ "MIT" ]
null
null
null
cpp/Rendering_calendar.cc
iskhanba/epicode
fda752e5e016ab64011083450be91bec9ee8358a
[ "MIT" ]
null
null
null
// Copyright (c) 2015 Elements of Programming Interviews. All rights reserved. #include <algorithm> #include <cassert> #include <iostream> #include <random> #include <vector> using std::cout; using std::default_random_engine; using std::endl; using std::max; using std::random_device; using std::uniform_int_distribution; using std::vector; // @include struct Event { int start, finish; }; struct Endpoint { bool operator<(const Endpoint& e) const { // If times are equal, an endpoint that starts an interval comes first. return time != e.time ? time < e.time : (isStart && !e.isStart); } int time; bool isStart; }; int FindMaxSimultaneousEvents(const vector<Event>& A) { // Builds an array of all endpoints. vector<Endpoint> E; for (const Event& event : A) { E.emplace_back(Endpoint{event.start, true}); E.emplace_back(Endpoint{event.finish, false}); } // Sorts the endpoint array according to the time, breaking ties // by putting start times before end times. sort(E.begin(), E.end()); // Track the number of simultaneous events, and record the maximum // number of simultaneous events. int max_num_simultaneous_events = 0, num_simultaneous_events = 0; for (const Endpoint& endpoint : E) { if (endpoint.isStart) { ++num_simultaneous_events; max_num_simultaneous_events = max(num_simultaneous_events, max_num_simultaneous_events); } else { --num_simultaneous_events; } } return max_num_simultaneous_events; } // @exclude void SimpleTest() { vector<Event> A = {{1, 5}, {2, 7}, {4, 5}, {6, 10}, {8, 9}, {9, 17}, {11, 13}, {12, 15}, {14, 15} }; assert(FindMaxSimultaneousEvents(A) == 3); } int main(int argc, char* argv[]) { SimpleTest(); default_random_engine gen((random_device())()); int n; if (argc == 2) { n = atoi(argv[1]); } else { uniform_int_distribution<int> dis(1, 100000); n = dis(gen); } vector<Event> A; for (int i = 0; i < n; ++i) { Event temp; uniform_int_distribution<int> dis1(0, 99999); temp.start = dis1(gen); uniform_int_distribution<int> dis2(temp.start + 1, temp.start + 10000); temp.finish = dis2(gen); A.emplace_back(temp); } int ans = FindMaxSimultaneousEvents(A); cout << ans << endl; return 0; }
27.606742
79
0.619455
[ "vector" ]
9bca883f463849784ad39792a02baffe5c2ee9c9
5,531
cpp
C++
Qt-Tim-Like/serverRelease/release/moc_servermonitor.cpp
yujiecong/Qt-TimLike
54172a907bd9b8a96c0bc6a827f15abbdb152de8
[ "MIT" ]
null
null
null
Qt-Tim-Like/serverRelease/release/moc_servermonitor.cpp
yujiecong/Qt-TimLike
54172a907bd9b8a96c0bc6a827f15abbdb152de8
[ "MIT" ]
null
null
null
Qt-Tim-Like/serverRelease/release/moc_servermonitor.cpp
yujiecong/Qt-TimLike
54172a907bd9b8a96c0bc6a827f15abbdb152de8
[ "MIT" ]
null
null
null
/**************************************************************************** ** Meta object code from reading C++ file 'servermonitor.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.9.6) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../Ubuntu_qt/ServerTimLike/servermonitor.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'servermonitor.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.9.6. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_ServerMonitor_t { QByteArrayData data[12]; char stringdata0[240]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_ServerMonitor_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_ServerMonitor_t qt_meta_stringdata_ServerMonitor = { { QT_MOC_LITERAL(0, 0, 13), // "ServerMonitor" QT_MOC_LITERAL(1, 14, 12), // "updateServer" QT_MOC_LITERAL(2, 27, 0), // "" QT_MOC_LITERAL(3, 28, 16), // "hasNewConnection" QT_MOC_LITERAL(4, 45, 18), // "afterDisconnection" QT_MOC_LITERAL(5, 64, 11), // "shareScreen" QT_MOC_LITERAL(6, 76, 21), // "on_pushButton_clicked" QT_MOC_LITERAL(7, 98, 23), // "on_pushButton_2_clicked" QT_MOC_LITERAL(8, 122, 27), // "on_lineEdit_editingFinished" QT_MOC_LITERAL(9, 150, 29), // "on_lineEdit_2_editingFinished" QT_MOC_LITERAL(10, 180, 29), // "on_lineEdit_3_editingFinished" QT_MOC_LITERAL(11, 210, 29) // "on_lineEdit_4_editingFinished" }, "ServerMonitor\0updateServer\0\0" "hasNewConnection\0afterDisconnection\0" "shareScreen\0on_pushButton_clicked\0" "on_pushButton_2_clicked\0" "on_lineEdit_editingFinished\0" "on_lineEdit_2_editingFinished\0" "on_lineEdit_3_editingFinished\0" "on_lineEdit_4_editingFinished" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_ServerMonitor[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 10, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 2, 64, 2, 0x0a /* Public */, 3, 1, 69, 2, 0x0a /* Public */, 4, 1, 72, 2, 0x0a /* Public */, 5, 0, 75, 2, 0x0a /* Public */, 6, 0, 76, 2, 0x08 /* Private */, 7, 0, 77, 2, 0x08 /* Private */, 8, 0, 78, 2, 0x08 /* Private */, 9, 0, 79, 2, 0x08 /* Private */, 10, 0, 80, 2, 0x08 /* Private */, 11, 0, 81, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::QString, QMetaType::Int, 2, 2, QMetaType::Void, QMetaType::Int, 2, QMetaType::Void, QMetaType::Int, 2, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, 0 // eod }; void ServerMonitor::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { ServerMonitor *_t = static_cast<ServerMonitor *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->updateServer((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break; case 1: _t->hasNewConnection((*reinterpret_cast< int(*)>(_a[1]))); break; case 2: _t->afterDisconnection((*reinterpret_cast< int(*)>(_a[1]))); break; case 3: _t->shareScreen(); break; case 4: _t->on_pushButton_clicked(); break; case 5: _t->on_pushButton_2_clicked(); break; case 6: _t->on_lineEdit_editingFinished(); break; case 7: _t->on_lineEdit_2_editingFinished(); break; case 8: _t->on_lineEdit_3_editingFinished(); break; case 9: _t->on_lineEdit_4_editingFinished(); break; default: ; } } } const QMetaObject ServerMonitor::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_ServerMonitor.data, qt_meta_data_ServerMonitor, qt_static_metacall, nullptr, nullptr} }; const QMetaObject *ServerMonitor::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *ServerMonitor::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_ServerMonitor.stringdata0)) return static_cast<void*>(this); return QWidget::qt_metacast(_clname); } int ServerMonitor::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 10) qt_static_metacall(this, _c, _id, _a); _id -= 10; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 10) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 10; } return _id; } QT_WARNING_POP QT_END_MOC_NAMESPACE
35.229299
117
0.627192
[ "object" ]
9bcad2bc7d326f756b25d2e04153a7e5c085f441
8,948
cpp
C++
src/linux_parser.cpp
dezlotnik/CppND-System-Monitor
4fd046258e8261a8b061e03394a6108b679e9659
[ "MIT" ]
null
null
null
src/linux_parser.cpp
dezlotnik/CppND-System-Monitor
4fd046258e8261a8b061e03394a6108b679e9659
[ "MIT" ]
null
null
null
src/linux_parser.cpp
dezlotnik/CppND-System-Monitor
4fd046258e8261a8b061e03394a6108b679e9659
[ "MIT" ]
null
null
null
#include <dirent.h> #include <unistd.h> #include <string> #include <vector> #include <unistd.h> #include <set> #include "linux_parser.h" using std::stof; using std::string; using std::to_string; using std::vector; using std::set; // DONE: An example of how to read data from the filesystem string LinuxParser::OperatingSystem() { string line; string key; string value; std::ifstream filestream(kOSPath); if (filestream.is_open()) { while (std::getline(filestream, line)) { std::replace(line.begin(), line.end(), ' ', '_'); std::replace(line.begin(), line.end(), '=', ' '); std::replace(line.begin(), line.end(), '"', ' '); std::istringstream linestream(line); while (linestream >> key >> value) { if (key == "PRETTY_NAME") { std::replace(value.begin(), value.end(), '_', ' '); return value; } } } } return value; } // DONE: An example of how to read data from the filesystem string LinuxParser::Kernel() { string os, version, kernel; string line; std::ifstream stream(kProcDirectory + kVersionFilename); if (stream.is_open()) { std::getline(stream, line); std::istringstream linestream(line); linestream >> os >> version >> kernel; } return kernel; } // BONUS: Update this to use std::filesystem set<int> LinuxParser::Pids() { set<int> pids; DIR* directory = opendir(kProcDirectory.c_str()); struct dirent* file; while ((file = readdir(directory)) != nullptr) { // Is this a directory? if (file->d_type == DT_DIR) { // Is every character of the name a digit? string filename(file->d_name); if (std::all_of(filename.begin(), filename.end(), isdigit)) { int pid = stoi(filename); pids.insert(pid); } } } closedir(directory); return pids; } // TODO: Read and return the system memory utilization float LinuxParser::MemoryUtilization() { string line, key, value; float mem_total, mem_free; float memory_utilization = 0.0; std::ifstream filestream(kProcDirectory + kMeminfoFilename); if (filestream.is_open()) { while (std::getline(filestream,line)) { std::istringstream linestream(line); while (linestream >> key >> value) { if (key == "MemTotal:") { mem_total = std::stof(value); } else if (key == "MemFree:") { mem_free = std::stof(value); } } } memory_utilization = (mem_total - mem_free)/mem_total; } return memory_utilization; } // TODO: Read and return the system uptime long LinuxParser::UpTime() { string line, up_time, idle_time; long up = 0; std::ifstream stream(kProcDirectory + kUptimeFilename); if (stream.is_open()) { std::getline(stream,line); std::istringstream linestream(line); linestream >> up_time >> idle_time; up = std::stol(up_time); } return up; } // TODO: Read and return the number of jiffies for the system long LinuxParser::Jiffies() { return ActiveJiffies() + IdleJiffies(); } // TODO: Read and return the number of active jiffies for a PID // REMOVE: [[maybe_unused]] once you define the function long LinuxParser::ActiveJiffies(int pid) { int count = 0; int index = 14; string line, utime_str, stime_str, cutime_str, cstime_str; long utime, stime, cutime, cstime; long active_jiffies = 0; std::ifstream filestream(kProcDirectory + std::to_string(pid) + kStatFilename); if (filestream.is_open()) { std::getline(filestream, line); std::istringstream linestream(line); while( (linestream >> utime_str) && ++count < index); linestream >> stime_str >> cutime_str >> cstime_str; utime = std::stol(utime_str); stime = std::stol(stime_str); cutime = std::stol(cutime_str); cstime = std::stol(cstime_str); active_jiffies = utime + stime + cutime + cstime; } return active_jiffies; } // TODO: Read and return the number of active jiffies for the system long LinuxParser::ActiveJiffies() { vector<string> util = CpuUtilization(); // user + nice + system + irq + softirq + steal long user, nice, system, irq, softirq, steal; user = std::stol(util[CPUStates::kUser_]); nice = std::stol(util[CPUStates::kNice_]); system = std::stol(util[CPUStates::kSystem_]); irq = std::stol(util[CPUStates::kIRQ_]); softirq = std::stol(util[CPUStates::kSoftIRQ_]); steal = std::stol(util[CPUStates::kSteal_]); return user + nice + system + irq + softirq + steal; } // TODO: Read and return the number of idle jiffies for the system long LinuxParser::IdleJiffies() { vector<string> util = CpuUtilization(); long idle, iowait; idle = std::stol(util[CPUStates::kIdle_]); iowait = std::stol(util[CPUStates::kIOwait_]); return idle + iowait; } // TODO: Read and return CPU utilization vector<string> LinuxParser::CpuUtilization() { string line, key, value; vector<string> cpu_utilization; std::ifstream filestream(kProcDirectory + kStatFilename); if (filestream.is_open()) { while (std::getline(filestream,line)) {; std::istringstream linestream(line); linestream >> key; if (key == "cpu") { while (linestream >> value) { cpu_utilization.push_back(value); } } } } return cpu_utilization; } // TODO: Read and return the total number of processes int LinuxParser::TotalProcesses() { string line, key, value; int n_processes = 0; std::ifstream filestream(kProcDirectory + kStatFilename); if (filestream.is_open()) { while (std::getline(filestream,line)) {; std::istringstream linestream(line); while (linestream >> key >> value) { if (key == "processes") { n_processes = std::stoi(value); } } } } return n_processes; } // TODO: Read and return the number of running processes int LinuxParser::RunningProcesses() { string line, key, value; int procs_running = 0; std::ifstream filestream(kProcDirectory + kStatFilename); if (filestream.is_open()) { while (std::getline(filestream,line)) {; std::istringstream linestream(line); while (linestream >> key >> value) { if (key == "procs_running") { procs_running = std::stoi(value); } } } } return procs_running; } // TODO: Read and return the command associated with a process // REMOVE: [[maybe_unused]] once you define the function string LinuxParser::Command(int pid) { string line, cmd; std::ifstream stream(kProcDirectory + std::to_string(pid) + kCmdlineFilename); if (stream.is_open()) { std::getline(stream, line); std::istringstream linestream(line); linestream >> cmd; } return cmd; } // TODO: Read and return the memory used by a process // REMOVE: [[maybe_unused]] once you define the function string LinuxParser::Ram(int pid) { string line, key, value; std::ifstream filestream(kProcDirectory + std::to_string(pid) + kStatusFilename); if (filestream.is_open()) { while (std::getline(filestream,line)) { std::istringstream linestream(line); while (linestream >> key >> value) { if (key == "VmSize:") { // convert to MB float mem = std::stof(value)/1000.0f; value = std::to_string(mem); return value; } } } } return value; } // TODO: Read and return the user ID associated with a process // REMOVE: [[maybe_unused]] once you define the function string LinuxParser::Uid(int pid) { string line, key, value; std::ifstream filestream(kProcDirectory + std::to_string(pid) + kStatusFilename); if (filestream.is_open()) { while (std::getline(filestream,line)) { std::istringstream linestream(line); while (linestream >> key >> value) { if (key == "Uid:") { return value; } } } } return value; } // TODO: Read and return the user associated with a process // REMOVE: [[maybe_unused]] once you define the function string LinuxParser::User(int pid) { string uid = Uid(pid); string line, key, value, x; std::ifstream filestream(kPasswordPath); if (filestream.is_open()) { while (std::getline(filestream, line)) { std::replace(line.begin(), line.end(), ':', ' '); std::istringstream linestream(line); while (linestream >> value >> x >> key) { if (key == uid) { return value; } } } } return value; } // TODO: Read and return the uptime of a process // REMOVE: [[maybe_unused]] once you define the function long LinuxParser::UpTime(int pid) { int index = 22; int count = 0; string line, value; long uptime = 0; std::ifstream filestream(kProcDirectory + std::to_string(pid) + kStatFilename); if (filestream.is_open()) { std::getline(filestream, line); std::istringstream linestream(line); while( (linestream >> value) && ++count < index); uptime = LinuxParser::UpTime() - std::stol(value)/sysconf(_SC_CLK_TCK); } return uptime; }
29.826667
83
0.645172
[ "vector" ]
9bd2106c75a4a706e8bc4dfa2460126b203f2ed3
14,630
cpp
C++
Screens/StoryScene.cpp
CrusaderCrab/YugiohPhantomRealm
79bd1e9948d2d2d29acf042fd412804c30562a8e
[ "Zlib" ]
13
2018-04-13T22:10:00.000Z
2022-01-01T08:26:23.000Z
Screens/StoryScene.cpp
CrusaderCrab/YugiohPhantomRealm
79bd1e9948d2d2d29acf042fd412804c30562a8e
[ "Zlib" ]
null
null
null
Screens/StoryScene.cpp
CrusaderCrab/YugiohPhantomRealm
79bd1e9948d2d2d29acf042fd412804c30562a8e
[ "Zlib" ]
3
2017-02-22T16:35:06.000Z
2019-12-21T20:39:23.000Z
#include <sstream> #include <Utility\Clock.h> #include <Utility\InputUnit.h> #include <Screens\StoryScene.h> #include <Utility\TextureLoader.h> #include <Utility\TextPrinter.h> #include <Game\PlayerData.h> #include <DefinesAndTypedefs.h> #include <Screens\ScreenUnit.h> #include <Game\EnemyData.h> #include <Screens\Trunk.h> #include <Screens\TempleMapScreen.h> #include <Screens\WorldMapScreen.h> #include <Game\Animation\FadeUnit.h> #include <Screens\SplashScreen.h> #include <Game\Duel\Board.h> #include <Screens\FinalScreen.h> #include <Utility\SoundUnit.h> #define ZYUG_CH_START 0 #define ZYUG_CH_ACTIVE 1 #define ZYUG_CH_IDLE 2 #define ZYUG_CH_YESNO1 3 #define ZYUG_CH_YESNO2 4 #define ZYUG_CH_YESNO3 10 #define ZYUG_CH_END 5 #define ZYUG_CH_TALK1 6 #define ZYUG_CH_TALK2 7 #define ZYUG_CH_TALK3 8 #define ZYUG_CH_NEXT_PART 9 #define ZYUG_CH_YESNO_EXIT1 11 namespace Screen{ void StoryScene::startup(const char* fileLocal){ BaseScreen::startup(); fadeUnit.changeZ(-1.0f); fadeUnit.sheet.amtran = glm::vec4(0.0001f,0,0,1); //std::cout<<"SS: startup start() file="<<fileLocal<<"\n"; in = std::ifstream(fileLocal); std::string s; in>>id; //save scene ID in>>s; //get BG path //std::cout<<"SS: go bg path: "<<id<<" "<<s<<" "<<in.good()<<"\n"; in>>nextScreenKey; in>>nextFileString; //std::cout<<"SS: next screen file: "<<nextFileString<<"\n"; in>>musicStr; if(musicStr!="MUSIC"){ soundUnit.playLoop(musicStr.c_str()); } setupBG(s.c_str()); setupTextBox(); setupCursor(); setupYesNoCursor(); doRenderText = false; cursorTimer = 0; cursorTexPos = 0; yesNoPos = 0; chain = ZYUG_CH_START; isEarthquaking = false; in>>key; //std::cout<<"SS: startup end()\n"; } void StoryScene::cleanup(){ //std::cout<<"SS: cleanup start()\n"; bg.cleanup(); cursor.textureBO = cursorTexs[0]; textureLoader.deleteTexture(&(cursorTexs[1])); textureLoader.deleteTexture(&(cursorTexs[2])); cursor.cleanup(); textBox.cleanup(); textPrinter.amtran = glm::vec4(1,1,1,1); soundUnit.stopAll(); in.close(); } void StoryScene::readNextPart(){ //std::cout<<"Story: NextPart: haskey = "<<key<<std::endl; switch(key){ case ':': loadNewChar(); in>>key; break; case '&': moveCharIn(); in>>key; break; case '^': moveCharOut(); in>>key; break; case '{': startYesNo(); in>>key; break; case '_': jumpCharIn(); in>>key; break; case '@': startNewText(); in>>key; break; case ';': startFadeOut(); break; case '+': unlockDuelist(); in>>key; break; case '=': assignPlotPoint(); in>>key; break; case '~': startFadeIn(); in>>key; break; case '[': hideBg(); in>>key; break; case ']': showBg(); in>>key; break; case '$': startDuel(); in>>key; break; case '|': fadeOutBg(); in>>key; break; case '/': changeBG(); in>>key; break; case '<': readBattleMusicIn(); in>>key; break; case '>': earthquake(); in>>key; break; case '\'': zoomInBg(); in>>key; break; case '(': soundUnit.playOnce("GameData/sounds/music/ready/itemGot_o.wav"); in>>key; break; default: break; } } void StoryScene::earthquake(){ isEarthquaking = true; in>>quakeTimer; shakeTimer = 0; soundUnit.stopAll(); soundUnit.playOnce("GameData/sounds/magic/earthquake.wav"); chain = ZYUG_CH_IDLE; } void StoryScene::zoomInBg(){ bg.scale = glm::vec3(0.84f, 0.48f, 1); } void StoryScene::readBattleMusicIn(){ float f; std::string lead, main; in>>f; theBoard.leadInLength = f; in>>lead; theBoard.leadInTrack = lead; in>>main; theBoard.mainTrack = main; } void StoryScene::changeBG(){ std::string s; in>>s; textureLoader.deleteTexture(&bg.textureBO); textureLoader.loadTexture(s.c_str(), &bg.textureBO); } void StoryScene::fadeOutBg(){ bg.interpolateAmtran(glm::vec4(1,1,1,0), 0.3f); wait(0.3f); } void StoryScene::hideBg(){ bg.amtran = glm::vec4(1,1,1,0); } void StoryScene::showBg(){ bg.interpolateAmtran(glm::vec4(1,1,1,1), 0.3f); } void StoryScene::loadNewChar(){ std::string s; in>>s; Game::ModelLoader m; m.startup(YUG_PLANE_FILE_PATH, s.c_str()); m.doRender = true; m.ignoreCamera = true; m.scale = glm::vec3(0.65f, 0.45f, 1); m.position = glm::vec3(-2.2f, 0.2f, -1.998f); m.position.z -= chars.size()*0.00001f; chars.push_back(m); } void StoryScene::moveCharIn(){ int charNo = 0, scenePos = 0; in>>charNo; in>>scenePos; glm::vec3 start, end; float z = -1.998f + (charNo*0.00001f); Game::ModelLoader* charPtr = &(chars[charNo]); if(scenePos == 0){ //left start = glm::vec3(-2.2f, 0.2f, z); end = glm::vec3(-0.2f, 0.2f, z); }else if(scenePos == 1){ //right start = glm::vec3(2.3f, 0.2f, z); end = glm::vec3(0.3f, 0.2f, z); }else{ //centre start = glm::vec3(-2.2f, 0.2f, z); end = glm::vec3(0.0f, 0.2f, z); } //std::cout<<"Story: moveCharIn: old pos = "<<chars[charNo].position.z<<std::endl; chars[charNo].position = start; chars[charNo].interpolate(end, 0.5f); wait(0.5f); } void StoryScene::moveCharOut(){ int charNo = 0, scenePos = 0; in>>charNo; in>>scenePos; glm::vec3 end; Game::ModelLoader* charPtr = &(chars[charNo]); if(scenePos == 0){ //left end = glm::vec3(-2.2f, 0.2f, -1.998f); }else{ //right end = glm::vec3(2.3f, 0.2f, -1.998f); } charPtr->interpolate(end, 0.3f); wait(0.3f); } void StoryScene::jumpCharIn(){ int charNo = 0, scenePos = 0; in>>charNo; in>>scenePos; glm::vec3 end; Game::ModelLoader* charPtr = &(chars[charNo]); if(scenePos == 0){ //left end = glm::vec3(-0.2f, 0.2f, -1.998f); }else if(scenePos == 1){ //right end = glm::vec3(0.3f, 0.2f, -1.998f); }else{ //centre end = glm::vec3(0.0f, 0.2f, -1.998f); } charPtr->position = end; } void StoryScene::startNewText(){ // @ Im a goat " watch your butt % text.clear(); std::string s; std::stringstream ss; in>>s; if(s=="*") s=playerData.name; if(s=="*,") s=playerData.name+","; while(s[0]!='%'){ if(s[0]=='\"'){ text.push_back(ss.str()); ss.str(""); in>>s; if(s=="*") s=playerData.name; if(s=="*,") s=playerData.name+","; }else{ ss<<s; ss<<' '; in>>s; if(s=="*") s=playerData.name; if(s=="*,") s=playerData.name+","; } } text.push_back(ss.str()); textTimer = 0; textAmtran = glm::vec4(1,1,1,0); chain = ZYUG_CH_TALK1; doRenderText = true; } void StoryScene::startFadeOut(){ fadeOut(0.5f); chain = ZYUG_CH_END; wait(0.5f); } void StoryScene::unlockDuelist(){ int ul; in>>ul; playerData.unlockedDuelists[ul].hasUnlocked = true; playerData.plotUnlockedDuelists[ul] = true; } void StoryScene::assignPlotPoint(){ int pp; in>>pp; playerData.currentPlotPoint = pp; } void StoryScene::startFadeIn(){ fadeIn(0.3f); wait(0.1f); } void StoryScene::startYesNo(){ text.clear(); std::string s; std::stringstream ss; in>>s; while(s[0]!='%'){ if(s[0]=='\"'){ text.push_back(ss.str()); ss.str(""); in>>s; }else{ ss<<s; ss<<' '; in>>s; } } text.push_back(ss.str()); in>>yesStr; in>>noStr; textTimer = 0; textAmtran = glm::vec4(1,1,1,0); chain = ZYUG_CH_YESNO1; yesNoCursor.doRender = true; yesNoCursor.interpolateAmtran(glm::vec4(1,1,1,0.5f), 0.4f); doRenderText = true; } void StoryScene::startDuel(){ int duelNumber, fieldType; std::string winStr, loseStr; in>>duelNumber; in>>fieldType; trunkUnit.fieldType = fieldType; in>>winStr; screenUnit.winStr = winStr; in>>loseStr; screenUnit.loseStr = loseStr; std::stringstream ss; ss<<"GameData/enemies/"<<duelNumber<<".txt"; enemyData.loadData(ss.str()); startFadeOut(); } void StoryScene::earthquakeUpdate(){ if(!isEarthquaking) return; //std::cout<<"eq\n"; quakeTimer -= gameClock.lastLoopTime(); if(quakeTimer<=0){ isEarthquaking = false; bg.position = glm::vec3(0.0f,0.206f, -2.00f); chain = ZYUG_CH_NEXT_PART; }else{ shakeTimer += gameClock.lastLoopTime(); if(shakeTimer > 0.2f){ if(bg.position.x == 0.02f) bg.position.x = -0.02f; else bg.position.x = 0.02f; shakeTimer = 0; } } } void StoryScene::update(){ yesNoCursor.update(); bg.update(); cursorUpdate(); earthquakeUpdate(); for(unsigned int i = 0; i < chars.size(); i++) chars[i].update(); if(!isWaiting){ switch(chain){ case ZYUG_CH_START: firstUpdate(); break; case ZYUG_CH_NEXT_PART: readNextPart(); break; case ZYUG_CH_TALK1: fadeTextInUpdate(); break; case ZYUG_CH_TALK3: fadeTextOutUpdate(); break; case ZYUG_CH_YESNO1: fadeYesNoInUpdate(); break; case ZYUG_CH_YESNO3: fadeYesNoOutUpdate(); break; case ZYUG_CH_YESNO_EXIT1: yesNoExitUpdate(); break; case ZYUG_CH_END: endUpdate(); break; default: break; } }else{ continueWaiting(); } } void StoryScene::cursorUpdate(){ cursorTimer += gameClock.lastLoopTime()*3.2f; if(cursorTimer>=1.0f){ cursorTexPos = (cursorTexPos+1)%3; cursor.textureBO = cursorTexs[cursorTexPos]; cursorTimer = 0; } } void StoryScene::endUpdate(){ if(nextScreenKey=='s'){ screenUnit.comingScreen = new SplashScreen(); }else if(nextFileString[0]=='d'){ //std::cout<<"ss: to trunk\n"; screenUnit.comingScreen = &trunkUnit; }else if(nextFileString[0]=='a'){ screenUnit.comingScreen = new TempleMapScreen(); }else if(nextFileString[0]=='c'){ screenUnit.comingScreen = new TempleMapScreen(); }else if(nextFileString[0]=='e'){ screenUnit.comingScreen = new TempleMapScreen(); }else if(nextFileString[0]=='w'){ screenUnit.comingScreen = new TempleMapScreen(); nextFileString[0]='d'; }else if(nextFileString[0]=='h'){ screenUnit.comingScreen = new WorldMapScreen(); }else if(nextFileString[0]=='i'){ screenUnit.comingScreen = new WorldMapScreen(); }else if(nextFileString[0]=='j'){ screenUnit.comingScreen = new WorldMapScreen(); }else if(nextFileString[0]=='k'){ screenUnit.comingScreen = new WorldMapScreen(); }else if(nextFileString[0]=='l'){ screenUnit.comingScreen = new WorldMapScreen(); }else if(nextFileString[0]=='m'){ screenUnit.comingScreen = new WorldMapScreen(); }else if(nextFileString[0]=='n'){ screenUnit.comingScreen = new WorldMapScreen(); }else if(nextFileString[0]=='z'){ screenUnit.comingScreen = new FinalScreen(); }else{ screenUnit.comingScreen = new StoryScene(); } cleanup(); chain = ZYUG_CH_IDLE; toNextScreen(); } void StoryScene::toNextScreen(){ screenUnit.startUpComingScreen(nextFileString.c_str()); } void StoryScene::yesNoExitUpdate(){ if(yesNoPos==0) nextFileString = yesStr; else nextFileString = noStr; key = ';'; chain = ZYUG_CH_NEXT_PART; } void StoryScene::fadeTextInUpdate(){ textTimer += gameClock.lastLoopTime()*2.0f; if(textTimer >= 1.0f){ textAmtran = glm::vec4(1,1,1,1); chain = ZYUG_CH_TALK2; textTimer = 0; }else{ textAmtran.w = textTimer; } } void StoryScene::fadeTextOutUpdate(){ textTimer += gameClock.lastLoopTime()*2.5f; if(textTimer >= 1.0f){ textAmtran = glm::vec4(1,1,1,0); chain = ZYUG_CH_NEXT_PART; textTimer = 0; doRenderText = false; }else{ textAmtran.w = 1.0f-textTimer; } } void StoryScene::fadeYesNoInUpdate(){ textTimer += gameClock.lastLoopTime()*2.0f; if(textTimer >= 1.0f){ textAmtran = glm::vec4(1,1,1,1); chain = ZYUG_CH_YESNO2; textTimer = 0; }else{ textAmtran.w = textTimer; } } void StoryScene::fadeYesNoOutUpdate(){ textTimer += gameClock.lastLoopTime()*2.5f; if(textTimer >= 1.0f){ textAmtran = glm::vec4(1,1,1,0); chain = ZYUG_CH_YESNO_EXIT1; textTimer = 0; doRenderText = false; yesNoCursor.doRender = false; }else{ textAmtran.w = 1.0f-textTimer; } } void StoryScene::firstUpdate(){ refreshScreenUnit(); chain = ZYUG_CH_NEXT_PART; wait(0.3f); } void StoryScene::render(){ bg.render(); for(unsigned int i = 0; i < chars.size(); i++) chars[i].render(); textBox.render(); if(chain==ZYUG_CH_TALK2)cursor.render(); if(doRenderText){renderText();} yesNoCursor.render(); } void StoryScene::renderText(){ textPrinter.leftAlign = true; textPrinter.ignoreCamera = true; textPrinter.amtran = textAmtran; glm::vec3 posi = glm::vec3(-0.7f,-0.363f,-1.991f); for(int i = 0; i < text.size(); i++){ textPrinter.printText(text[i].c_str(), YUG_TEXT_INFO_FONT, glm::vec3(0.3f, 0.7f, 1), posi, glm::mat4()); posi.y -= 0.07f; } } void StoryScene::input(){ if(!isWaiting){ switch(chain){ case ZYUG_CH_TALK2: talkInput(); break; case ZYUG_CH_YESNO2: yesNoInput(); break; default: break; } } } void StoryScene::yesNoInput(){ if(inputUnit.isKeyActive(YUG_KEY_DOWN)){ yesNoPos = 1; yesNoCursor.position.y = -0.433f; soundUnit.cursorMove(); wait(0.2f); }else if(inputUnit.isKeyActive(YUG_KEY_UP)){ yesNoPos = 0; yesNoCursor.position.y = -0.363f; soundUnit.cursorMove(); wait(0.2f); }else if(inputUnit.isKeyActive(YUG_KEY_START)||inputUnit.isKeyActive(YUG_KEY_X)){ yesNoCursor.interpolateAmtran(glm::vec4(1,1,1,0), 0.25f); chain = ZYUG_CH_YESNO3; soundUnit.cursorSelect(); } } void StoryScene::talkInput(){ if(inputUnit.isKeyActive(YUG_KEY_START)||inputUnit.isKeyActive(YUG_KEY_X)){ chain = ZYUG_CH_TALK3; soundUnit.cursorSelect(); } } void StoryScene::setupBG(const char* local){ bg.startup( YUG_PLANE_FILE_PATH, local); bg.doRender = true; bg.ignoreCamera = true; bg.scale = glm::vec3(0.82f, 0.444f, 1); bg.position = glm::vec3(0.0f,0.206f, -2.00f); } void StoryScene::setupTextBox(){ textBox.startup( YUG_PLANE_FILE_PATH, YUG_SCREEN_WINDOW_TEXTURE_PATH); textBox.doRender = true; textBox.ignoreCamera = true; textBox.scale = glm::vec3(0.81f,0.217f,1); textBox.position = glm::vec3(0,-0.444f, -1.994f); } void StoryScene::setupCursor(){ cursor.startup( YUG_PLANE_FILE_PATH, "GameData/textures/screens/singles/textbutton1.png"); cursorTexs[0] = cursor.textureBO; textureLoader.loadTexture("GameData/textures/screens/singles/textbutton2.png", &cursorTexs[1]); textureLoader.loadTexture("GameData/textures/screens/singles/textbutton3.png", &cursorTexs[2]); cursor.doRender = true; cursor.ignoreCamera = true; cursor.scale = glm::vec3(0.03f, 0.03f, 1); cursor.position = glm::vec3(0.7f, -0.55f, -1.992f); } void StoryScene::setupYesNoCursor(){ yesNoCursor.startup(YUG_PLANE_FILE_PATH, "GameData/textures/models/positionunit/concursor.png"); yesNoCursor.doRender = false; yesNoCursor.ignoreCamera = true; yesNoCursor.amtran = glm::vec4(1,1,1,0); yesNoCursor.scale = glm::vec3(0.718f, 0.03f, 1); yesNoCursor.position = glm::vec3(-0.0f,-0.363f,-1.990f); } }
26.844037
97
0.657211
[ "render" ]
9bdd36c12fe6d369f15052a509bc5d91da64a2a5
659
cpp
C++
CHFM.cpp
swap612/compete
06c0e55beb8b5fa33431cecbb479c61d545dafbf
[ "MIT" ]
1
2018-10-14T06:05:53.000Z
2018-10-14T06:05:53.000Z
CHFM.cpp
swap612/compete
06c0e55beb8b5fa33431cecbb479c61d545dafbf
[ "MIT" ]
null
null
null
CHFM.cpp
swap612/compete
06c0e55beb8b5fa33431cecbb479c61d545dafbf
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { int T, W; long int N; long long int sum = 0; vector<long int> num; cin >> T; while (T > 0) { cin >> W; while (W--) { cin >> N; sum += N; num.push_back(N); } T--; double mean = ((double)sum / num.size()); // cout << num.size() << ":" << mean << "\n"; auto it = find(num.begin(), num.end(), mean); if (it != num.end()) cout << it - num.begin() + 1 << "\n"; else cout << "Impossible\n"; num.clear(); sum = 0; } }
19.969697
53
0.385432
[ "vector" ]
9bf85bd06584cc773be60c5f6e19ef21a8dd50bd
1,420
cpp
C++
06. Sorting/TopologicalSort.cpp
Ujjawalgupta42/Hacktoberfest2021-DSA
eccd9352055085973e3d6a1feb10dd193905584b
[ "MIT" ]
225
2021-10-01T03:09:01.000Z
2022-03-11T11:32:49.000Z
06. Sorting/TopologicalSort.cpp
Ujjawalgupta42/Hacktoberfest2021-DSA
eccd9352055085973e3d6a1feb10dd193905584b
[ "MIT" ]
252
2021-10-01T03:45:20.000Z
2021-12-07T18:32:46.000Z
06. Sorting/TopologicalSort.cpp
Ujjawalgupta42/Hacktoberfest2021-DSA
eccd9352055085973e3d6a1feb10dd193905584b
[ "MIT" ]
911
2021-10-01T02:55:19.000Z
2022-02-06T09:08:37.000Z
#include<bits/stdc++.h> using namespace std; void addEdge(vector<int> Graph[],int s,int e) { Graph[s].push_back(e); // Graph[e].push_back(s); } vector<int> topological(vector<int> graph[],int s) { vector<int> result; queue<int> q; vector<int> indegree(s,0); for(int i=0;i<s;i++) { for(int j=0;j<graph[i].size();j++) { indegree[graph[i][j]]++; } } for(int k=0;k<indegree.size();k++) { if(indegree[k]==0) { q.push(indegree[k]); } } while(!q.empty()) { int v = q.front(); q.pop(); result.push_back(v); for(auto adj = graph[v].begin();adj!=graph[v].end();adj++) { indegree[*adj]--; if(indegree[*adj]==0) { q.push(*adj); } } } return result; } int main() { int size = 5; vector<int> graph[size]; // graph formation addEdge(graph,0,1); addEdge(graph,0,2); addEdge(graph,1,3); addEdge(graph,1,2); addEdge(graph,2,3); addEdge(graph,2,4); cout<<endl<<endl; vector<int> result = topological(graph,size); cout<<"The sorted graph is\n"; for(int i: result) { cout<<i<<" "; } }
18.205128
67
0.430986
[ "vector" ]
50047290048d37a73173b9bec988f19b08dd5c45
22,610
cpp
C++
src/execution/execution.cpp
forsyde/DeSyDe
48c55861ed78dd240451787258ee286b0f46aea5
[ "BSD-2-Clause" ]
3
2016-09-06T14:00:07.000Z
2021-03-23T04:40:13.000Z
src/execution/execution.cpp
forsyde/DeSyDe
48c55861ed78dd240451787258ee286b0f46aea5
[ "BSD-2-Clause" ]
2
2019-02-19T13:02:40.000Z
2019-06-17T15:27:52.000Z
src/execution/execution.cpp
forsyde/DeSyDe
48c55861ed78dd240451787258ee286b0f46aea5
[ "BSD-2-Clause" ]
7
2016-10-05T10:04:49.000Z
2021-04-12T18:20:44.000Z
#ifndef __EXECUTION__ #define __EXECUTION__ /** * Copyright (c) 2013-2016, Nima Khalilzad <nkhal@kth.se> * Katrhin Rosvall <krosvall@kth.se> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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. */ /** * This class is a simple contraint model execution engine * It receives a CP model and a setting object */ #include <math.h> #include <iostream> #include <vector> #include <boost/math/common_factor.hpp> #include <cstring> #include <gecode/gist.hh> #include "../settings/config.hpp" #include "../system/mapping.hpp" #include <chrono> #include <fstream> using namespace std; using namespace Gecode; template<class CPModelTemplate> class Execution { public: Execution(CPModelTemplate* _model, Config& _cfg) : model(_model), cfg(_cfg) { geSearchOptions.threads = cfg.settings().threads; if(cfg.settings().timeout_first > 0){ Search::TimeStop* stop = new Search::TimeStop(cfg.settings().timeout_first); geSearchOptions.stop = stop; } } ; ~Execution() { delete geSearchOptions.stop; } /** * This funtion executes the CP model. * The CP model has to implement the following functions: * (i) print() * (ii) printCSV() */ int Execute(Mapping* map) { if(!cfg.settings().configTDN){ switch (cfg.settings().search) { case (Config::GIST_ALL): { Gist::Print<CPModelTemplate> p("Print solution"); Gist::Options options; options.inspect.click(&p); Gist::dfs(model, options); break; } case (Config::GIST_OPT): { Gist::Print<CPModelTemplate> p("Print solution"); Gist::Options options; options.inspect.click(&p); Gist::bab(model, options); break; } case (Config::FIRST): case (Config::ALL): { LOG_INFO("DFS engine ..."); DFS<CPModelTemplate> e(model, geSearchOptions); loopSolutions<DFS<CPModelTemplate>>(&e); break; } case (Config::OPTIMIZE): { LOG_INFO("BAB engine, optimizing ... "); BAB<CPModelTemplate> e(model, geSearchOptions); loopSolutions<BAB<CPModelTemplate>>(&e); break; } case (Config::OPTIMIZE_IT): { LOG_INFO("BAB engine, optimizing iteratively ... "); Search::Cutoff* cut = Search::Cutoff::luby(cfg.settings().luby_scale); geSearchOptions.cutoff = cut; geSearchOptions.nogoods_limit = cfg.settings().noGoodDepth; //geSearchOptions.share_afc = true; RBS<CPModelTemplate, BAB> e(model, geSearchOptions); loopSolutions<RBS<CPModelTemplate, BAB>>(&e); break; } default: THROW_EXCEPTION(RuntimeException, "unknown search type for main solver."); break; } }else{ loopForMinimalTDNConfig(map); } LOG_INFO("End of exploration. Result files written to " +cfg.settings().output_path+"out/"); return 1; } ; private: CPModelTemplate* model; /**< Pointer to the constraint model class. */ Config& cfg; /**< pointer to the config class. */ unsigned long nodes; /**< Number of nodes. */ int timerResets; /**< Number of incremental timer resets. */ Search::Options geSearchOptions; /**< Gecode search option object. */ ofstream out, outCSV, outCSV_opt, outMOSTCSV, outMappingCSV; /**< Output file streams: .txt and .csv. */ typedef std::chrono::high_resolution_clock runTimer; /**< Timer type. */ runTimer::time_point t_start, t_endAll; /**< Timer objects for start and end of experiment. */ vector<Config::SolutionValues> optData, solutionData; unsigned long infoFreq; /**< Adapt the printing frequency of how many solutions have been found to the number of solutions. */ void printMOSTCSV(Mapping* solution, int n, int split) { //N_TASKS;N_EDGES;N_PES;N_SLOTS;N_SCHEDS;MAP_PE1;MAP_PE2;FREQ_PE1;FREQ_PE2;MEM_PE1;MEM_PE2;SLOTS_PE1;SLOTS_PE2;MAP_T1;MAP_T2;MAP_T3;TASK_SCHED;COMM_SCHED;cluster; Applications* program = solution->getApplications(); const Platform* target = solution->getPlatform(); //print first row (column names) if((split != -1 && n % split == 1) || (split == -1 && n == 1)){ outMOSTCSV << "N_TASKS;N_EDGES;N_PES;N_SLOTS;N_SCHEDS;"; for(size_t j = 1; j <= target->nodes(); j++){ outMOSTCSV << "MAP_PE" << j << ";"; } for(size_t j = 1; j <= target->nodes(); j++){ outMOSTCSV << "FREQ_PE" << j << ";"; } for(size_t j = 1; j <= target->nodes(); j++){ outMOSTCSV << "MEM_PE" << j << ";"; } for(size_t j = 1; j <= target->nodes(); j++){ outMOSTCSV << "SLOTS_PE" << j << ";"; } for(size_t i = 1; i <= program->n_programEntities(); i++){ outMOSTCSV << "MAP_T" << i << ";"; } outMOSTCSV << "TASK_SCHED;COMM_SCHED;"; //COMM_ENTRIES"; for(size_t j = 1; j <= target->nodes(); j++){ outMOSTCSV << "MEMCONS_PE" << j << ";"; } for(size_t j = 1; j <= target->nodes(); j++){ outMOSTCSV << "U_PE" << j << ";"; } for(size_t a = 1; a <= solution->getNumberOfApps(); a++){ outMOSTCSV << "PERIOD_APP" << a << ";"; } for(size_t a = 1; a <= solution->getNumberOfApps(); a++){ outMOSTCSV << "THROUGHPUT_APP" << a << ";"; } for(size_t a = 1; a <= solution->getNumberOfApps(); a++){ outMOSTCSV << "LATENCY_APP" << a << ";"; } outMOSTCSV << "cluster;" << endl; outMOSTCSV << endl; } // "N_TASKS;N_EDGES;N_PES;N_SLOTS;N_SCHEDS;"; outMOSTCSV << "\"" << program->n_programEntities() << "\";"; outMOSTCSV << "\"" << program->n_SDFchannels() << "\";"; outMOSTCSV << "\"" << target->nodes() << "\";"; outMOSTCSV << "\"" << target->tdmaSlots() << "\";"; outMOSTCSV << "\"" << target->nodes() << "\";"; //"MAP_PE" for(size_t ji = 1; ji <= target->nodes(); ji++){ outMOSTCSV << "\"("; for(size_t jj = 1; jj <= target->nodes(); jj++){ if((ji == jj) && jj < target->nodes()) outMOSTCSV << "1-"; if((ji == jj) && jj == target->nodes()) outMOSTCSV << "1"; if((ji != jj) && jj < target->nodes()) outMOSTCSV << "0-"; if((ji != jj) && jj == target->nodes()) outMOSTCSV << "0"; } outMOSTCSV << ")\";"; } //"FREQ_PE" for(size_t j = 1; j <= target->nodes(); j++){ outMOSTCSV << "\"50\";"; } //"MEM_PE" for(size_t j = 0; j < target->nodes(); j++){ outMOSTCSV << "\"" << solution->getMemorySize(j) << "\";"; } //"SLOTS_PE" vector<int> tdmaSlots = solution->getTDMAslots(); for(size_t j = 0; j < tdmaSlots.size(); j++){ outMOSTCSV << "\"" << tdmaSlots[j] << "\";"; } //"MAP_T" vector<vector<int>> mapping = solution->getMappingSched(); for(size_t i = 0; i < program->n_SDFActors(); i++){ outMOSTCSV << "\"("; vector<int>::iterator it; for(size_t jj = 0; jj < target->nodes(); jj++){ vector<int> proc = mapping[jj]; it = find(proc.begin(), proc.end(), i); if((it != proc.end()) && jj < target->nodes() - 1) outMOSTCSV << "1-"; if((it != proc.end()) && jj == target->nodes() - 1) outMOSTCSV << "1"; if((it == proc.end()) && jj < target->nodes() - 1) outMOSTCSV << "0-"; if((it == proc.end()) && jj == target->nodes() - 1) outMOSTCSV << "0"; } outMOSTCSV << ")\";"; } //"TASK_SCHED" outMOSTCSV << "\"@"; for(size_t ji = 0; ji < target->nodes(); ji++){ vector<int> proc = mapping[ji]; for(size_t jj = 0; jj < proc.size(); jj++){ outMOSTCSV << proc[jj] + 1; if(jj < proc.size() - 1 || (ji < target->nodes() - 1 && !mapping[ji + 1].empty())) outMOSTCSV << "-"; } } outMOSTCSV << "@\";"; //"COMM_SCHED" vector<int> chIds; for(size_t k = 0; k < program->n_SDFchannels(); k++){ chIds.push_back(k); } int commEntries = 0; outMOSTCSV << "\"@"; //vector<vector<SDFChannel*>> msgOrder = solution->getMessageOrder(); vector<vector<int>> msgOrder = solution->getCommSched(); for(size_t k = 0; k < msgOrder.size(); k++){ //vector<SDFChannel*> sched = msgOrder[k]; vector<int> sched = msgOrder[k]; for(size_t i = 0; i < sched.size(); i++){ //outMOSTCSV << sched[i]->newId; //newId does not exist anymore //outMOSTCSV << sched[i]->id; outMOSTCSV << sched[i]; commEntries++; //chIds.erase(find(chIds.begin(), chIds.end(), sched[i]->newId));//newId does not exist anymore //chIds.erase(find(chIds.begin(), chIds.end(), sched[i]->id)); chIds.erase(find(chIds.begin(), chIds.end(), sched[i])); if(i < sched.size() - 1 || (k < target->nodes() - 1 && !msgOrder[k + 1].empty()) || !chIds.empty()) outMOSTCSV << "-"; } } for(size_t k = 0; k < chIds.size(); k++){ outMOSTCSV << chIds[k]; if(k < chIds.size() - 1) outMOSTCSV << "-"; } outMOSTCSV << "@\";"; //"COMM_ENTRIES" //outMOSTCSV << "\"" << commEntries << "\";"; //"MEMCONS_PE" vector<int> memLoad = solution->getMemLoads(); for(size_t j = 0; j < memLoad.size(); j++){ outMOSTCSV << "\"" << memLoad[j] << "\";"; } //"U_PE" for(size_t j = 0; j < target->nodes(); j++){ outMOSTCSV << "\"" << solution->getProcUtilization(j) << "\";"; } //"PERIOD_APP" for(size_t a = 0; a < solution->getNumberOfApps(); a++){ outMOSTCSV << "\"" << solution->getPeriod(a) << "\";"; } //"THROUGHPUT_APP" for(size_t a = 0; a < solution->getNumberOfApps(); a++){ outMOSTCSV << "\"" << 1.0 / ((double) solution->getPeriod(a)) << "\";"; } //"LATENCY_APP" for(size_t a = 0; a < solution->getNumberOfApps(); a++){ outMOSTCSV << "\"" << solution->getInitLatency(a) << "\";"; } outMOSTCSV << 0 << ";"; outMOSTCSV << endl; } /** * Prints the solutions in the ofstreams (out and outCSV_opt) */ template<class SearchEngine> void printSolution(SearchEngine *e, CPModelTemplate* s) { if(cfg.settings().out_file_type == Config::ALL_OUT || cfg.settings().out_file_type == Config::TXT){ auto durAll = t_endAll - t_start; auto durAll_ms = std::chrono::duration_cast<std::chrono::milliseconds>(durAll).count(); out << "*** Solution number: " << nodes << ", after " << durAll_ms << " ms" << ", search nodes: " << e->statistics().node << ", fail: " << e->statistics().fail << ", propagate: " << e->statistics().propagate << ", depth: " << e->statistics().depth << ", nogoods: " << e->statistics().nogood << ", restarts: " << e->statistics().restart << " ***\n"; s->print(out); } /// Printing CSV format output /*if(cfg.settings().out_file_type == Config::ALL_OUT || cfg.settings().out_file_type == Config::CSV){ outCSV_opt << nodes << "," << durAll_ms << ","; s->printCSV(outCSV_opt); s->printMappingCSV(outMappingCSV); }*/ /** * Calling printcsv for the MOST tool */ /*if(cfg.settings().out_file_type == Config::ALL_OUT || cfg.settings().out_file_type == Config::CSV_MOST){ Mapping* mapping = s->extractResult(); const int split = -1; printMOSTCSV(mapping, nodes, split); }*/ } ; /** * Loops through the solutions and prints them using the input search engine */ template<class SearchEngine> void loopSolutions(SearchEngine *e) { nodes = 0; timerResets = 0; infoFreq = 1; out.open(cfg.settings().output_path+"out/out.txt"); LOG_INFO("Opened file for printing results: " +cfg.settings().output_path+"out/out.txt"); if(cfg.doOptimize()){ outCSV_opt.open(cfg.settings().output_path+"out/out_opt.csv"); } if(!cfg.settings().printMetrics.empty()){ outCSV.open(cfg.settings().output_path+"out/out.csv"); } //outMOSTCSV.open(cfg.settings().output_path+"out/out-MOST.csv"); //outMappingCSV.open(cfg.settings().output_path+"out/out_mapping.csv"); LOG_INFO("started searching for " + cfg.get_search_type() + " solutions "); LOG_INFO("Printing frequency: " + cfg.get_out_freq()); out << "\n \n*** \n"; std::chrono::high_resolution_clock::duration presolver_delay(0); if((cfg.doPresolve() && cfg.is_presolved()) || cfg.doMultiStep()){ if(cfg.doOptimize()){ optData = cfg.getPresolverResults()->optResults; } if(!cfg.settings().printMetrics.empty()){ solutionData = cfg.getPresolverResults()->printResults; } presolver_delay = cfg.getPresolverResults()->presolver_delay; } CPModelTemplate * prev_sol = nullptr; t_start = runTimer::now(); while(CPModelTemplate * s = e->next()){ nodes++; if(nodes == 1){ if(cfg.settings().search == Config::FIRST){ t_endAll = runTimer::now(); printSolution(e, s); return; } if(cfg.settings().out_print_freq == Config::FIRSTandLAST){ t_endAll = runTimer::now(); printSolution(e, s); } } t_endAll = runTimer::now(); //cout << nodes << " solutions found." << endl; if(cfg.doOptimize()){ optData.push_back(Config::SolutionValues{t_endAll-t_start+presolver_delay, s->getOptimizationValues()}); } if(!cfg.settings().printMetrics.empty()){ solutionData.push_back(Config::SolutionValues{t_endAll-t_start+presolver_delay, ((CPModelTemplate*)s)->getPrintMetrics()}); } //cout << nodes << " solutions found." << endl; if(cfg.settings().out_print_freq == Config::ALL_SOL){ printSolution(e, s); } /// We want to keep the last solution in case we only print the last one if(prev_sol != nullptr) delete prev_sol; prev_sol = s; if(cfg.settings().out_print_freq == Config::FIRSTandLAST || cfg.settings().out_print_freq == Config::LAST || cfg.settings().out_print_freq == Config::ALL_SOL){ //if(nodes%infoFreq == 0){ LOG_INFO(tools::toString(nodes) +" solution found so far."); //if(nodes == 10){ // infoFreq = 5; //}else if(nodes > 10 && nodes%(20*infoFreq) == 0){ // infoFreq = 10*infoFreq; //} //} } if(cfg.settings().timeout_all){ ((Search::TimeStop*)geSearchOptions.stop)->reset(); ((Search::TimeStop*)geSearchOptions.stop)->limit(cfg.settings().timeout_all); timerResets++; } } auto durAll = runTimer::now() - t_start; auto durAll_s = std::chrono::duration_cast<std::chrono::seconds>(durAll).count(); auto durAll_ms = std::chrono::duration_cast<std::chrono::milliseconds>(durAll).count(); if(cfg.settings().out_print_freq == Config::LAST && nodes > 0){ printSolution(e, prev_sol); }else if(cfg.settings().out_print_freq == Config::LAST && nodes == 0){ out << "No (better) solution found." << endl; } if(cfg.settings().out_print_freq == Config::FIRSTandLAST && nodes > 1){ printSolution(e, prev_sol); }else if(cfg.settings().out_print_freq == Config::FIRSTandLAST && nodes == 1){ out << "No better solution found." << endl; } delete prev_sol; out << "===== search ended after: " << durAll_s << " s (" << durAll_ms << " ms)"; if(e->stopped()){ out << " due to time-out!"; } if(cfg.settings().timeout_all){ out << " (with " << timerResets << " incremental timer reset(s).)"; } out << " =====\n" << nodes << " solutions found\n" << "search nodes: " << e->statistics().node << ", fail: " << e->statistics().fail << ", propagate: " << e->statistics().propagate << ", depth: " << e->statistics().depth << ", nogoods: " << e->statistics().nogood << ", restarts: " << e->statistics().restart << " ***\n"; if(cfg.doOptimize()){ for(auto i: optData){ outCSV_opt << std::chrono::duration_cast<std::chrono::milliseconds>(i.time).count() << " "; for(auto j: i.values){ outCSV_opt << j << " "; } outCSV_opt << endl; } } if(!cfg.settings().printMetrics.empty()){ for(auto i: solutionData){ outCSV << std::chrono::duration_cast<std::chrono::milliseconds>(i.time).count() << " "; for(auto j: i.values){ outCSV << j << " "; } outCSV << endl; } } out.close(); if(cfg.doOptimize()){ outCSV_opt.close(); } if(!cfg.settings().printMetrics.empty()){ outCSV.close(); } //outMOSTCSV.close(); //outMappingCSV.close(); } template<class SearchEngine> bool findMinimalTDNConfig(SearchEngine *e) { bool solFound = false; if(CPModelTemplate * s = e->next()){ //"if" because one solution is sufficient t_endAll = runTimer::now(); printSolution(e, s); solFound = true; delete s; } auto durAll = runTimer::now() - t_start; auto durAll_s = std::chrono::duration_cast<std::chrono::seconds>(durAll).count(); auto durAll_ms = std::chrono::duration_cast<std::chrono::milliseconds>(durAll).count(); out << "===== search ended after: " << durAll_s << " s (" << durAll_ms << " ms)"; if(e->stopped()){ out << " due to time-out!"; } nodes = solFound ? 1 : 0; out << " =====\n" << nodes << " solutions found\n" << "search nodes: " << e->statistics().node << ", fail: " << e->statistics().fail << ", propagate: " << e->statistics().propagate << ", depth: " << e->statistics().depth << ", nogoods: " << e->statistics().nogood << ", restarts: " << e->statistics().restart << " ***\n\n"; //delete e; return solFound; } /** * Loops through the solutions and prints them using the input search engine */ void loopForMinimalTDNConfig(Mapping* map) { out.open(cfg.settings().output_path+"out/TDNconfig_out.txt"); LOG_INFO("Opened file for printing results: " +cfg.settings().output_path+"out/TDNconfig_out.txt"); LOG_INFO("started searching for " + cfg.get_search_type() + " solutions "); std::chrono::high_resolution_clock::duration presolver_delay(0); if((cfg.doPresolve() && cfg.is_presolved()) || cfg.doMultiStep()){ if(cfg.doOptimize()){ optData = cfg.getPresolverResults()->optResults; } if(!cfg.settings().printMetrics.empty()){ solutionData = cfg.getPresolverResults()->printResults; } presolver_delay = cfg.getPresolverResults()->presolver_delay; } t_start = runTimer::now(); bool solutionFound = false; size_t tdn_slots = map->getPlatform()->nodes(); LOG_INFO("Searching for minimal TDN config. Starting with "+tools::toString(tdn_slots)+" slots.\n"); while(!solutionFound){ LOG_INFO("### Trying "+tools::toString(tdn_slots)+" slots. #########################################"); out << "Trying " << tdn_slots << " slots..." << endl; map->getPlatform()->setTDNconfig(tdn_slots); model = new CPModelTemplate(map, &cfg); switch (cfg.settings().search) { case (Config::GIST_ALL): { Gist::Print<CPModelTemplate> p("Print solution"); Gist::Options options; options.inspect.click(&p); Gist::dfs(model, options); solutionFound = true; //only for testing/debugging break; } case (Config::GIST_OPT): { Gist::Print<CPModelTemplate> p("Print solution"); Gist::Options options; options.inspect.click(&p); Gist::bab(model, options); solutionFound = true; //only for testing/debugging break; } case (Config::FIRST): case (Config::ALL): { LOG_INFO("DFS engine ..."); DFS<CPModelTemplate> e(model, geSearchOptions); solutionFound = findMinimalTDNConfig<DFS<CPModelTemplate>>(&e); break; } case (Config::OPTIMIZE): { LOG_INFO("BAB engine, optimizing ... "); BAB<CPModelTemplate> e(model, geSearchOptions); solutionFound = findMinimalTDNConfig<BAB<CPModelTemplate>>(&e); break; } case (Config::OPTIMIZE_IT): { LOG_INFO("BAB engine, optimizing iteratively ... "); Search::Cutoff* cut = Search::Cutoff::luby(cfg.settings().luby_scale); geSearchOptions.cutoff = cut; geSearchOptions.nogoods_limit = cfg.settings().noGoodDepth; RBS<CPModelTemplate, BAB> e(model, geSearchOptions); solutionFound = findMinimalTDNConfig<RBS<CPModelTemplate, BAB>>(&e); break; } default: THROW_EXCEPTION(RuntimeException, "unknown search type for main solver."); break; } if(!solutionFound) tdn_slots++; } auto durAll = runTimer::now() - t_start; auto durAll_s = std::chrono::duration_cast<std::chrono::seconds>(durAll).count(); auto durAll_ms = std::chrono::duration_cast<std::chrono::milliseconds>(durAll).count(); out << "\n#####\n"; out << "===== search ended after: " << durAll_s << " s (" << durAll_ms << " ms)"; out.close(); } }; #endif
38
184
0.578461
[ "object", "vector", "model" ]
5005f9949d8fa8264681df5b63e9edd7cbfd617e
1,028
hpp
C++
src/include/client/graphical/meshopener/OBJOpener.hpp
arthurmco/familyline
849eee40cff266af9a3f848395ed139b7ce66197
[ "MIT" ]
6
2018-05-11T23:16:02.000Z
2019-06-13T01:35:07.000Z
src/include/client/graphical/meshopener/OBJOpener.hpp
arthurmco/familyline
849eee40cff266af9a3f848395ed139b7ce66197
[ "MIT" ]
33
2018-05-11T14:12:22.000Z
2022-03-12T00:55:25.000Z
src/include/client/graphical/meshopener/OBJOpener.hpp
arthurmco/familyline
849eee40cff266af9a3f848395ed139b7ce66197
[ "MIT" ]
1
2018-12-06T23:39:55.000Z
2018-12-06T23:39:55.000Z
/* * The .obj file opener * Each mesh is delimited by a mesh group * * (You can create a mesh group by selecting the meshes you want in Blender and pressing ctrl+g, * or something like that) * * If no mesh group is found, we create a mesh group composed of all meshes in the file * * Remember it also uses the meshes from the file. * Do not let the "New Mesh" and "New Mesh <2>" default names * NAME YOUR MESHES IN THE FILE * * Copyright (C) 2016-2018 Arthur Mendes */ #ifndef OBJOPENER_HPP #define OBJOPENER_HPP #include "../mesh.hpp" #include "MeshOpener.hpp" namespace familyline::graphics { class OBJOpener : public MeshOpener { public: OBJOpener() { OPENER_REGISTER("obj"); } /* Open only the file for that extension * (i.e, this method in a .obj file opener will only open .obj files */ virtual std::vector<Mesh*> OpenSpecialized(const char* file); virtual ~OBJOpener() { this->UnregisterExtension("obj"); }; }; } // namespace familyline::graphics #endif /* OBJOPENER_HPP */
25.7
96
0.694553
[ "mesh", "vector" ]
500efa0a31fefc2a00008d093b5ae25db4e2f744
30,300
cc
C++
icing/tokenization/raw-query-tokenizer_test.cc
PixelPlusUI-SnowCone/external_icing
206a7d6b4ab83c6acdb8b14565e2431751c9e4cf
[ "Apache-2.0" ]
null
null
null
icing/tokenization/raw-query-tokenizer_test.cc
PixelPlusUI-SnowCone/external_icing
206a7d6b4ab83c6acdb8b14565e2431751c9e4cf
[ "Apache-2.0" ]
null
null
null
icing/tokenization/raw-query-tokenizer_test.cc
PixelPlusUI-SnowCone/external_icing
206a7d6b4ab83c6acdb8b14565e2431751c9e4cf
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "icing/tokenization/raw-query-tokenizer.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "icing/helpers/icu/icu-data-file-helper.h" #include "icing/portable/platform.h" #include "icing/testing/common-matchers.h" #include "icing/testing/test-data.h" #include "icing/tokenization/language-segmenter-factory.h" #include "icing/tokenization/tokenizer-factory.h" #include "icing/tokenization/tokenizer.h" #include "unicode/uloc.h" namespace icing { namespace lib { namespace { using ::testing::ElementsAre; using ::testing::HasSubstr; class RawQueryTokenizerTest : public ::testing::Test { protected: void SetUp() override { if (!IsCfStringTokenization() && !IsReverseJniTokenization()) { ICING_ASSERT_OK( // File generated via icu_data_file rule in //icing/BUILD. icu_data_file_helper::SetUpICUDataFile( GetTestFilePath("icing/icu.dat"))); } } }; TEST_F(RawQueryTokenizerTest, CreationWithNullPointerShouldFail) { EXPECT_THAT(tokenizer_factory::CreateQueryTokenizer( tokenizer_factory::RAW_QUERY, /*lang_segmenter=*/nullptr), StatusIs(libtextclassifier3::StatusCode::FAILED_PRECONDITION)); } TEST_F(RawQueryTokenizerTest, Simple) { language_segmenter_factory::SegmenterOptions options(ULOC_US); ICING_ASSERT_OK_AND_ASSIGN( auto language_segmenter, language_segmenter_factory::Create(std::move(options))); ICING_ASSERT_OK_AND_ASSIGN( std::unique_ptr<Tokenizer> raw_query_tokenizer, tokenizer_factory::CreateQueryTokenizer(tokenizer_factory::RAW_QUERY, language_segmenter.get())); EXPECT_THAT(raw_query_tokenizer->TokenizeAll("Hello World!"), IsOkAndHolds(ElementsAre(EqualsToken(Token::REGULAR, "Hello"), EqualsToken(Token::REGULAR, "World")))); EXPECT_THAT(raw_query_tokenizer->TokenizeAll("hElLo WORLD"), IsOkAndHolds(ElementsAre(EqualsToken(Token::REGULAR, "hElLo"), EqualsToken(Token::REGULAR, "WORLD")))); } TEST_F(RawQueryTokenizerTest, Parentheses) { language_segmenter_factory::SegmenterOptions options(ULOC_US); ICING_ASSERT_OK_AND_ASSIGN( auto language_segmenter, language_segmenter_factory::Create(std::move(options))); ICING_ASSERT_OK_AND_ASSIGN( std::unique_ptr<Tokenizer> raw_query_tokenizer, tokenizer_factory::CreateQueryTokenizer(tokenizer_factory::RAW_QUERY, language_segmenter.get())); EXPECT_THAT(raw_query_tokenizer->TokenizeAll("()"), IsOkAndHolds(ElementsAre( EqualsToken(Token::QUERY_LEFT_PARENTHESES, ""), EqualsToken(Token::QUERY_RIGHT_PARENTHESES, "")))); EXPECT_THAT(raw_query_tokenizer->TokenizeAll("( )"), IsOkAndHolds(ElementsAre( EqualsToken(Token::QUERY_LEFT_PARENTHESES, ""), EqualsToken(Token::QUERY_RIGHT_PARENTHESES, "")))); EXPECT_THAT(raw_query_tokenizer->TokenizeAll("(term1 term2)"), IsOkAndHolds(ElementsAre( EqualsToken(Token::QUERY_LEFT_PARENTHESES, ""), EqualsToken(Token::REGULAR, "term1"), EqualsToken(Token::REGULAR, "term2"), EqualsToken(Token::QUERY_RIGHT_PARENTHESES, "")))); EXPECT_THAT(raw_query_tokenizer->TokenizeAll("((term1 term2) (term3 term4))"), IsOkAndHolds(ElementsAre( EqualsToken(Token::QUERY_LEFT_PARENTHESES, ""), EqualsToken(Token::QUERY_LEFT_PARENTHESES, ""), EqualsToken(Token::REGULAR, "term1"), EqualsToken(Token::REGULAR, "term2"), EqualsToken(Token::QUERY_RIGHT_PARENTHESES, ""), EqualsToken(Token::QUERY_LEFT_PARENTHESES, ""), EqualsToken(Token::REGULAR, "term3"), EqualsToken(Token::REGULAR, "term4"), EqualsToken(Token::QUERY_RIGHT_PARENTHESES, ""), EqualsToken(Token::QUERY_RIGHT_PARENTHESES, "")))); EXPECT_THAT(raw_query_tokenizer->TokenizeAll("term1(term2)"), IsOkAndHolds(ElementsAre( EqualsToken(Token::REGULAR, "term1"), EqualsToken(Token::QUERY_LEFT_PARENTHESES, ""), EqualsToken(Token::REGULAR, "term2"), EqualsToken(Token::QUERY_RIGHT_PARENTHESES, "")))); EXPECT_THAT( raw_query_tokenizer->TokenizeAll("(term1)term2"), IsOkAndHolds(ElementsAre(EqualsToken(Token::QUERY_LEFT_PARENTHESES, ""), EqualsToken(Token::REGULAR, "term1"), EqualsToken(Token::QUERY_RIGHT_PARENTHESES, ""), EqualsToken(Token::REGULAR, "term2")))); EXPECT_THAT(raw_query_tokenizer->TokenizeAll("(term1)(term2)"), IsOkAndHolds(ElementsAre( EqualsToken(Token::QUERY_LEFT_PARENTHESES, ""), EqualsToken(Token::REGULAR, "term1"), EqualsToken(Token::QUERY_RIGHT_PARENTHESES, ""), EqualsToken(Token::QUERY_LEFT_PARENTHESES, ""), EqualsToken(Token::REGULAR, "term2"), EqualsToken(Token::QUERY_RIGHT_PARENTHESES, "")))); EXPECT_THAT( raw_query_tokenizer->TokenizeAll("(term1)-term2"), IsOkAndHolds(ElementsAre(EqualsToken(Token::QUERY_LEFT_PARENTHESES, ""), EqualsToken(Token::REGULAR, "term1"), EqualsToken(Token::QUERY_RIGHT_PARENTHESES, ""), EqualsToken(Token::QUERY_EXCLUSION, ""), EqualsToken(Token::REGULAR, "term2")))); EXPECT_THAT( raw_query_tokenizer->TokenizeAll("(term1)OR term2"), IsOkAndHolds(ElementsAre(EqualsToken(Token::QUERY_LEFT_PARENTHESES, ""), EqualsToken(Token::REGULAR, "term1"), EqualsToken(Token::QUERY_RIGHT_PARENTHESES, ""), EqualsToken(Token::QUERY_OR, ""), EqualsToken(Token::REGULAR, "term2")))); EXPECT_THAT(raw_query_tokenizer->TokenizeAll("(term1)OR(term2)"), IsOkAndHolds(ElementsAre( EqualsToken(Token::QUERY_LEFT_PARENTHESES, ""), EqualsToken(Token::REGULAR, "term1"), EqualsToken(Token::QUERY_RIGHT_PARENTHESES, ""), EqualsToken(Token::QUERY_OR, ""), EqualsToken(Token::QUERY_LEFT_PARENTHESES, ""), EqualsToken(Token::REGULAR, "term2"), EqualsToken(Token::QUERY_RIGHT_PARENTHESES, "")))); EXPECT_THAT(raw_query_tokenizer->TokenizeAll("(term1):term2"), StatusIs(libtextclassifier3::StatusCode::INVALID_ARGUMENT, HasSubstr("Property name can't be a group"))); EXPECT_THAT(raw_query_tokenizer->TokenizeAll("((term1)"), StatusIs(libtextclassifier3::StatusCode::INVALID_ARGUMENT, HasSubstr("Unclosed left parentheses"))); EXPECT_THAT(raw_query_tokenizer->TokenizeAll("(term1))"), StatusIs(libtextclassifier3::StatusCode::INVALID_ARGUMENT, HasSubstr("Too many right parentheses"))); } TEST_F(RawQueryTokenizerTest, Exclustion) { language_segmenter_factory::SegmenterOptions options(ULOC_US); ICING_ASSERT_OK_AND_ASSIGN( auto language_segmenter, language_segmenter_factory::Create(std::move(options))); ICING_ASSERT_OK_AND_ASSIGN( std::unique_ptr<Tokenizer> raw_query_tokenizer, tokenizer_factory::CreateQueryTokenizer(tokenizer_factory::RAW_QUERY, language_segmenter.get())); EXPECT_THAT(raw_query_tokenizer->TokenizeAll("-term1"), IsOkAndHolds(ElementsAre(EqualsToken(Token::QUERY_EXCLUSION, ""), EqualsToken(Token::REGULAR, "term1")))); EXPECT_THAT(raw_query_tokenizer->TokenizeAll("(-term1)"), IsOkAndHolds(ElementsAre( EqualsToken(Token::QUERY_LEFT_PARENTHESES, ""), EqualsToken(Token::QUERY_EXCLUSION, ""), EqualsToken(Token::REGULAR, "term1"), EqualsToken(Token::QUERY_RIGHT_PARENTHESES, "")))); // Exclusion operator is ignored EXPECT_THAT(raw_query_tokenizer->TokenizeAll("- term1"), IsOkAndHolds(ElementsAre(EqualsToken(Token::REGULAR, "term1")))); // Exclusion operator is ignored EXPECT_THAT(raw_query_tokenizer->TokenizeAll("term1- term2"), IsOkAndHolds(ElementsAre(EqualsToken(Token::REGULAR, "term1"), EqualsToken(Token::REGULAR, "term2")))); // Exclusion operator is ignored EXPECT_THAT(raw_query_tokenizer->TokenizeAll("(term1 -)"), IsOkAndHolds(ElementsAre( EqualsToken(Token::QUERY_LEFT_PARENTHESES, ""), EqualsToken(Token::REGULAR, "term1"), EqualsToken(Token::QUERY_RIGHT_PARENTHESES, "")))); // First exclusion operator is ignored EXPECT_THAT(raw_query_tokenizer->TokenizeAll("--term1"), IsOkAndHolds(ElementsAre(EqualsToken(Token::QUERY_EXCLUSION, ""), EqualsToken(Token::REGULAR, "term1")))); // First "-" is exclusion operator, second is not and will be discarded. // In other words, exclusion only applies to the term right after it. EXPECT_THAT(raw_query_tokenizer->TokenizeAll("-term1-term2"), IsOkAndHolds(ElementsAre(EqualsToken(Token::QUERY_EXCLUSION, ""), EqualsToken(Token::REGULAR, "term1"), EqualsToken(Token::REGULAR, "term2")))); EXPECT_THAT(raw_query_tokenizer->TokenizeAll("-(term1)"), StatusIs(libtextclassifier3::StatusCode::INVALID_ARGUMENT, HasSubstr("Exclusion on groups is not supported"))); EXPECT_THAT( raw_query_tokenizer->TokenizeAll("-OR"), StatusIs(libtextclassifier3::StatusCode::INVALID_ARGUMENT, HasSubstr("Exclusion and OR operators can't be used together"))); EXPECT_THAT(raw_query_tokenizer->TokenizeAll("-:term1"), StatusIs(libtextclassifier3::StatusCode::INVALID_ARGUMENT, HasSubstr("Exclusion and property restriction operators " "can't be used together"))); EXPECT_THAT(raw_query_tokenizer->TokenizeAll("-property1:term1"), StatusIs(libtextclassifier3::StatusCode::INVALID_ARGUMENT, HasSubstr("Exclusion and property restriction operators " "can't be used together"))); } TEST_F(RawQueryTokenizerTest, PropertyRestriction) { language_segmenter_factory::SegmenterOptions options(ULOC_US); ICING_ASSERT_OK_AND_ASSIGN( auto language_segmenter, language_segmenter_factory::Create(std::move(options))); ICING_ASSERT_OK_AND_ASSIGN( std::unique_ptr<Tokenizer> raw_query_tokenizer, tokenizer_factory::CreateQueryTokenizer(tokenizer_factory::RAW_QUERY, language_segmenter.get())); EXPECT_THAT( raw_query_tokenizer->TokenizeAll("property1:term1"), IsOkAndHolds(ElementsAre(EqualsToken(Token::QUERY_PROPERTY, "property1"), EqualsToken(Token::REGULAR, "term1")))); EXPECT_THAT(raw_query_tokenizer->TokenizeAll("(property1:term1)"), IsOkAndHolds(ElementsAre( EqualsToken(Token::QUERY_LEFT_PARENTHESES, ""), EqualsToken(Token::QUERY_PROPERTY, "property1"), EqualsToken(Token::REGULAR, "term1"), EqualsToken(Token::QUERY_RIGHT_PARENTHESES, "")))); // Colon is ignored EXPECT_THAT(raw_query_tokenizer->TokenizeAll(":term1"), IsOkAndHolds(ElementsAre(EqualsToken(Token::REGULAR, "term1")))); // Colon is ignored EXPECT_THAT(raw_query_tokenizer->TokenizeAll("(:term1)"), IsOkAndHolds(ElementsAre( EqualsToken(Token::QUERY_LEFT_PARENTHESES, ""), EqualsToken(Token::REGULAR, "term1"), EqualsToken(Token::QUERY_RIGHT_PARENTHESES, "")))); // Colon is ignored EXPECT_THAT(raw_query_tokenizer->TokenizeAll("term1:"), IsOkAndHolds(ElementsAre(EqualsToken(Token::REGULAR, "term1")))); // property name can be a path EXPECT_THAT(raw_query_tokenizer->TokenizeAll("email.title:hello"), IsOkAndHolds( ElementsAre(EqualsToken(Token::QUERY_PROPERTY, "email.title"), EqualsToken(Token::REGULAR, "hello")))); // The first colon ":" triggers property restriction, the second colon is used // as a word connector per ICU's rule // (https://unicode.org/reports/tr29/#Word_Boundaries). EXPECT_THAT( raw_query_tokenizer->TokenizeAll("property:foo:bar"), IsOkAndHolds(ElementsAre(EqualsToken(Token::QUERY_PROPERTY, "property"), EqualsToken(Token::REGULAR, "foo:bar")))); // Property restriction only applies to the term right after it. // Note: "term1:term2" is not a term but 2 terms because word connectors // don't apply to numbers and alphabets. EXPECT_THAT( raw_query_tokenizer->TokenizeAll("property1:term1:term2"), IsOkAndHolds(ElementsAre(EqualsToken(Token::QUERY_PROPERTY, "property1"), EqualsToken(Token::REGULAR, "term1"), EqualsToken(Token::REGULAR, "term2")))); EXPECT_THAT( raw_query_tokenizer->TokenizeAll("property1:今天:天气"), IsOkAndHolds(ElementsAre(EqualsToken(Token::QUERY_PROPERTY, "property1"), EqualsToken(Token::REGULAR, "今天"), EqualsToken(Token::REGULAR, "天气")))); EXPECT_THAT( raw_query_tokenizer->TokenizeAll("property1:term1-"), IsOkAndHolds(ElementsAre(EqualsToken(Token::QUERY_PROPERTY, "property1"), EqualsToken(Token::REGULAR, "term1")))); // Multiple continuous colons will still be recognized as a property // restriction operator EXPECT_THAT( raw_query_tokenizer->TokenizeAll("property1::term1"), IsOkAndHolds(ElementsAre(EqualsToken(Token::QUERY_PROPERTY, "property1"), EqualsToken(Token::REGULAR, "term1")))); EXPECT_THAT( raw_query_tokenizer->TokenizeAll("property1:(term1)"), StatusIs(libtextclassifier3::StatusCode::INVALID_ARGUMENT, HasSubstr("Property restriction on groups is not supported"))); EXPECT_THAT( raw_query_tokenizer->TokenizeAll("property1:OR"), StatusIs( libtextclassifier3::StatusCode::INVALID_ARGUMENT, HasSubstr( "Property restriction and OR operators can't be used together"))); EXPECT_THAT(raw_query_tokenizer->TokenizeAll("property1:-term1"), StatusIs(libtextclassifier3::StatusCode::INVALID_ARGUMENT, HasSubstr("Exclusion and property restriction operators " "can't be used together"))); } TEST_F(RawQueryTokenizerTest, OR) { language_segmenter_factory::SegmenterOptions options(ULOC_US); ICING_ASSERT_OK_AND_ASSIGN( auto language_segmenter, language_segmenter_factory::Create(std::move(options))); ICING_ASSERT_OK_AND_ASSIGN( std::unique_ptr<Tokenizer> raw_query_tokenizer, tokenizer_factory::CreateQueryTokenizer(tokenizer_factory::RAW_QUERY, language_segmenter.get())); EXPECT_THAT(raw_query_tokenizer->TokenizeAll("term1 OR term2"), IsOkAndHolds(ElementsAre(EqualsToken(Token::REGULAR, "term1"), EqualsToken(Token::QUERY_OR, ""), EqualsToken(Token::REGULAR, "term2")))); // Two continuous "OR"s are treated as one EXPECT_THAT(raw_query_tokenizer->TokenizeAll("term1 OR OR term2"), IsOkAndHolds(ElementsAre(EqualsToken(Token::REGULAR, "term1"), EqualsToken(Token::QUERY_OR, ""), EqualsToken(Token::REGULAR, "term2")))); EXPECT_THAT( raw_query_tokenizer->TokenizeAll("(term1) OR term2"), IsOkAndHolds(ElementsAre(EqualsToken(Token::QUERY_LEFT_PARENTHESES, ""), EqualsToken(Token::REGULAR, "term1"), EqualsToken(Token::QUERY_RIGHT_PARENTHESES, ""), EqualsToken(Token::QUERY_OR, ""), EqualsToken(Token::REGULAR, "term2")))); EXPECT_THAT(raw_query_tokenizer->TokenizeAll("term1 OR (term2)"), IsOkAndHolds(ElementsAre( EqualsToken(Token::REGULAR, "term1"), EqualsToken(Token::QUERY_OR, ""), EqualsToken(Token::QUERY_LEFT_PARENTHESES, ""), EqualsToken(Token::REGULAR, "term2"), EqualsToken(Token::QUERY_RIGHT_PARENTHESES, "")))); EXPECT_THAT(raw_query_tokenizer->TokenizeAll("((term1) OR (term2))"), IsOkAndHolds(ElementsAre( EqualsToken(Token::QUERY_LEFT_PARENTHESES, ""), EqualsToken(Token::QUERY_LEFT_PARENTHESES, ""), EqualsToken(Token::REGULAR, "term1"), EqualsToken(Token::QUERY_RIGHT_PARENTHESES, ""), EqualsToken(Token::QUERY_OR, ""), EqualsToken(Token::QUERY_LEFT_PARENTHESES, ""), EqualsToken(Token::REGULAR, "term2"), EqualsToken(Token::QUERY_RIGHT_PARENTHESES, ""), EqualsToken(Token::QUERY_RIGHT_PARENTHESES, "")))); // Only "OR" (all in uppercase) is the operator EXPECT_THAT( raw_query_tokenizer->TokenizeAll("term1 or term2 Or term3 oR term4"), IsOkAndHolds(ElementsAre(EqualsToken(Token::REGULAR, "term1"), EqualsToken(Token::REGULAR, "or"), EqualsToken(Token::REGULAR, "term2"), EqualsToken(Token::REGULAR, "Or"), EqualsToken(Token::REGULAR, "term3"), EqualsToken(Token::REGULAR, "oR"), EqualsToken(Token::REGULAR, "term4")))); // "OR" is ignored EXPECT_THAT(raw_query_tokenizer->TokenizeAll("OR term1"), IsOkAndHolds(ElementsAre(EqualsToken(Token::REGULAR, "term1")))); // "OR" is ignored EXPECT_THAT(raw_query_tokenizer->TokenizeAll("term1 OR"), IsOkAndHolds(ElementsAre(EqualsToken(Token::REGULAR, "term1")))); // "OR" is ignored EXPECT_THAT(raw_query_tokenizer->TokenizeAll("(OR term1)"), IsOkAndHolds(ElementsAre( EqualsToken(Token::QUERY_LEFT_PARENTHESES, ""), EqualsToken(Token::REGULAR, "term1"), EqualsToken(Token::QUERY_RIGHT_PARENTHESES, "")))); // "OR" is ignored EXPECT_THAT(raw_query_tokenizer->TokenizeAll("( OR term1)"), IsOkAndHolds(ElementsAre( EqualsToken(Token::QUERY_LEFT_PARENTHESES, ""), EqualsToken(Token::REGULAR, "term1"), EqualsToken(Token::QUERY_RIGHT_PARENTHESES, "")))); // "OR" is ignored EXPECT_THAT(raw_query_tokenizer->TokenizeAll("(term1 OR)"), IsOkAndHolds(ElementsAre( EqualsToken(Token::QUERY_LEFT_PARENTHESES, ""), EqualsToken(Token::REGULAR, "term1"), EqualsToken(Token::QUERY_RIGHT_PARENTHESES, "")))); // "OR" is ignored EXPECT_THAT(raw_query_tokenizer->TokenizeAll("(term1 OR )"), IsOkAndHolds(ElementsAre( EqualsToken(Token::QUERY_LEFT_PARENTHESES, ""), EqualsToken(Token::REGULAR, "term1"), EqualsToken(Token::QUERY_RIGHT_PARENTHESES, "")))); // "OR" is ignored EXPECT_THAT(raw_query_tokenizer->TokenizeAll("( OR )"), IsOkAndHolds(ElementsAre( EqualsToken(Token::QUERY_LEFT_PARENTHESES, ""), EqualsToken(Token::QUERY_RIGHT_PARENTHESES, "")))); EXPECT_THAT(raw_query_tokenizer->TokenizeAll("term1 OR(term2)"), IsOkAndHolds(ElementsAre( EqualsToken(Token::REGULAR, "term1"), EqualsToken(Token::QUERY_OR, ""), EqualsToken(Token::QUERY_LEFT_PARENTHESES, ""), EqualsToken(Token::REGULAR, "term2"), EqualsToken(Token::QUERY_RIGHT_PARENTHESES, "")))); EXPECT_THAT( raw_query_tokenizer->TokenizeAll("term1 OR-term2"), StatusIs(libtextclassifier3::StatusCode::INVALID_ARGUMENT, HasSubstr("No whitespaces before or after OR operator"))); EXPECT_THAT( raw_query_tokenizer->TokenizeAll("term1 OR:term2"), StatusIs(libtextclassifier3::StatusCode::INVALID_ARGUMENT, HasSubstr("No whitespaces before or after OR operator"))); } // CJKT are treated the same way by language segmenter and raw tokenizer, so // here we test Chinese and Japanese to represent CJKT. TEST_F(RawQueryTokenizerTest, CJKT) { language_segmenter_factory::SegmenterOptions options(ULOC_US); ICING_ASSERT_OK_AND_ASSIGN( auto language_segmenter, language_segmenter_factory::Create(std::move(options))); ICING_ASSERT_OK_AND_ASSIGN( std::unique_ptr<Tokenizer> raw_query_tokenizer, tokenizer_factory::CreateQueryTokenizer(tokenizer_factory::RAW_QUERY, language_segmenter.get())); // Exclusion only applies to the term right after it. if (IsCfStringTokenization()) { EXPECT_THAT( raw_query_tokenizer->TokenizeAll("-今天天气很好"), IsOkAndHolds(ElementsAre(EqualsToken(Token::QUERY_EXCLUSION, ""), EqualsToken(Token::REGULAR, "今天"), EqualsToken(Token::REGULAR, "天气"), EqualsToken(Token::REGULAR, "很"), EqualsToken(Token::REGULAR, "好")))); } else { EXPECT_THAT( raw_query_tokenizer->TokenizeAll("-今天天气很好"), IsOkAndHolds(ElementsAre(EqualsToken(Token::QUERY_EXCLUSION, ""), EqualsToken(Token::REGULAR, "今天"), EqualsToken(Token::REGULAR, "天气"), EqualsToken(Token::REGULAR, "很好")))); } if (IsCfStringTokenization()) { EXPECT_THAT(raw_query_tokenizer->TokenizeAll("property1:你好"), IsOkAndHolds( ElementsAre(EqualsToken(Token::QUERY_PROPERTY, "property1"), EqualsToken(Token::REGULAR, "你"), EqualsToken(Token::REGULAR, "好")))); } else { EXPECT_THAT(raw_query_tokenizer->TokenizeAll("property1:你好"), IsOkAndHolds( ElementsAre(EqualsToken(Token::QUERY_PROPERTY, "property1"), EqualsToken(Token::REGULAR, "你好")))); } EXPECT_THAT( raw_query_tokenizer->TokenizeAll("标题:你好"), StatusIs(libtextclassifier3::StatusCode::INVALID_ARGUMENT, HasSubstr("Characters in property name must all be ASCII"))); EXPECT_THAT(raw_query_tokenizer->TokenizeAll("cat OR ねこ"), IsOkAndHolds(ElementsAre(EqualsToken(Token::REGULAR, "cat"), EqualsToken(Token::QUERY_OR, ""), EqualsToken(Token::REGULAR, "ねこ")))); EXPECT_THAT( raw_query_tokenizer->TokenizeAll("cat ORねこ"), StatusIs(libtextclassifier3::StatusCode::INVALID_ARGUMENT, HasSubstr("No whitespaces before or after OR operator"))); EXPECT_THAT( raw_query_tokenizer->TokenizeAll("ねこOR cat"), StatusIs(libtextclassifier3::StatusCode::INVALID_ARGUMENT, HasSubstr("No whitespaces before or after OR operator"))); EXPECT_THAT( raw_query_tokenizer->TokenizeAll("-ねこOR cat"), StatusIs(libtextclassifier3::StatusCode::INVALID_ARGUMENT, HasSubstr("No whitespaces before or after OR operator"))); EXPECT_THAT( raw_query_tokenizer->TokenizeAll("property:ねこOR cat"), StatusIs(libtextclassifier3::StatusCode::INVALID_ARGUMENT, HasSubstr("No whitespaces before or after OR operator"))); } // Raw tokenizer identifies all characters that it doesn't know as OTHER type, // so we can choose comma "," to represent all OTHER characters. TEST_F(RawQueryTokenizerTest, OtherChars) { language_segmenter_factory::SegmenterOptions options(ULOC_US); ICING_ASSERT_OK_AND_ASSIGN( auto language_segmenter, language_segmenter_factory::Create(std::move(options))); ICING_ASSERT_OK_AND_ASSIGN( std::unique_ptr<Tokenizer> raw_query_tokenizer, tokenizer_factory::CreateQueryTokenizer(tokenizer_factory::RAW_QUERY, language_segmenter.get())); // Comma is ignored EXPECT_THAT(raw_query_tokenizer->TokenizeAll(",term1, ,"), IsOkAndHolds(ElementsAre(EqualsToken(Token::REGULAR, "term1")))); EXPECT_THAT(raw_query_tokenizer->TokenizeAll("(,term1),"), IsOkAndHolds(ElementsAre( EqualsToken(Token::QUERY_LEFT_PARENTHESES, ""), EqualsToken(Token::REGULAR, "term1"), EqualsToken(Token::QUERY_RIGHT_PARENTHESES, "")))); // Exclusion operator and comma are ignored EXPECT_THAT(raw_query_tokenizer->TokenizeAll("-,term1"), IsOkAndHolds(ElementsAre(EqualsToken(Token::REGULAR, "term1")))); EXPECT_THAT(raw_query_tokenizer->TokenizeAll("-term1,"), IsOkAndHolds(ElementsAre(EqualsToken(Token::QUERY_EXCLUSION, ""), EqualsToken(Token::REGULAR, "term1")))); // Colon and comma are ignored EXPECT_THAT(raw_query_tokenizer->TokenizeAll("property1:,term1"), IsOkAndHolds(ElementsAre(EqualsToken(Token::REGULAR, "property1"), EqualsToken(Token::REGULAR, "term1")))); EXPECT_THAT( raw_query_tokenizer->TokenizeAll("property1:term1,term2"), IsOkAndHolds(ElementsAre(EqualsToken(Token::QUERY_PROPERTY, "property1"), EqualsToken(Token::REGULAR, "term1"), EqualsToken(Token::REGULAR, "term2")))); // This is a special case for OR, unknown chars are treated the same as // whitespaces before and after OR. EXPECT_THAT(raw_query_tokenizer->TokenizeAll("term1,OR,term2"), IsOkAndHolds(ElementsAre(EqualsToken(Token::REGULAR, "term1"), EqualsToken(Token::QUERY_OR, ""), EqualsToken(Token::REGULAR, "term2")))); } TEST_F(RawQueryTokenizerTest, Mix) { language_segmenter_factory::SegmenterOptions options(ULOC_US); ICING_ASSERT_OK_AND_ASSIGN( auto language_segmenter, language_segmenter_factory::Create(std::move(options))); ICING_ASSERT_OK_AND_ASSIGN( std::unique_ptr<Tokenizer> raw_query_tokenizer, tokenizer_factory::CreateQueryTokenizer(tokenizer_factory::RAW_QUERY, language_segmenter.get())); if (IsCfStringTokenization()) { EXPECT_THAT(raw_query_tokenizer->TokenizeAll( "こんにちはgood afternoon, title:今天 OR (ในวันนี้ -B12)"), IsOkAndHolds(ElementsAre( EqualsToken(Token::REGULAR, "こんにちは"), EqualsToken(Token::REGULAR, "good"), EqualsToken(Token::REGULAR, "afternoon"), EqualsToken(Token::QUERY_PROPERTY, "title"), EqualsToken(Token::REGULAR, "今天"), EqualsToken(Token::QUERY_OR, ""), EqualsToken(Token::QUERY_LEFT_PARENTHESES, ""), EqualsToken(Token::REGULAR, "ใน"), EqualsToken(Token::REGULAR, "วันนี้"), EqualsToken(Token::QUERY_EXCLUSION, ""), EqualsToken(Token::REGULAR, "B12"), EqualsToken(Token::QUERY_RIGHT_PARENTHESES, "")))); } else { ICING_ASSERT_OK_AND_ASSIGN( std::vector<Token> tokens, raw_query_tokenizer->TokenizeAll( "こんにちはgood afternoon, title:今天 OR (ในวันนี้ -B12)")); EXPECT_THAT(tokens, ElementsAre(EqualsToken(Token::REGULAR, "こんにちは"), EqualsToken(Token::REGULAR, "good"), EqualsToken(Token::REGULAR, "afternoon"), EqualsToken(Token::QUERY_PROPERTY, "title"), EqualsToken(Token::REGULAR, "今天"), EqualsToken(Token::QUERY_OR, ""), EqualsToken(Token::QUERY_LEFT_PARENTHESES, ""), EqualsToken(Token::REGULAR, "ใน"), EqualsToken(Token::REGULAR, "วัน"), EqualsToken(Token::REGULAR, "นี้"), EqualsToken(Token::QUERY_EXCLUSION, ""), EqualsToken(Token::REGULAR, "B12"), EqualsToken(Token::QUERY_RIGHT_PARENTHESES, ""))); } } } // namespace } // namespace lib } // namespace icing
47.867299
80
0.615842
[ "vector" ]
501b398b7a71302aa3508609061ffcd84d50c20e
3,398
cc
C++
src/tests.cc
malharthi/scc
004106ab3772e1b8710225f20f1401319b1c4743
[ "BSD-3-Clause" ]
8
2015-05-09T02:14:03.000Z
2021-05-13T21:14:32.000Z
src/tests.cc
malharthi/scc
004106ab3772e1b8710225f20f1401319b1c4743
[ "BSD-3-Clause" ]
null
null
null
src/tests.cc
malharthi/scc
004106ab3772e1b8710225f20f1401319b1c4743
[ "BSD-3-Clause" ]
1
2021-05-13T21:14:34.000Z
2021-05-13T21:14:34.000Z
// Copyright (c) 2009 Mohannad Alharthi (mohannad.harthi@gmail.com) // All rights reserved. // This source code is licensed under the BSD license, which can be found in // the LICENSE.txt file. #ifdef _TEST_BUILD #include <algorithm> #include <iostream> #include <string> #include <vector> #include "code_gen.h" #include "str_helper.h" //#include "intermediate.h" // Some helper macros #define CHECK_RESULT(condition, message, result) \ std::cout << message << (condition ? ": OK" : ": FAILD") << std::endl; \ if (!(condition)) \ std::cout << "\t" << result << std::endl; // A macro for adding a TestJob object to a TestSet object #define ADD_TEST(SET, JOB_PTR) SET.jobs_.push_back(JOB_PTR); // The base class for a test job (or task) class TestJob { public: virtual ~TestJob() { } virtual void operator()() = 0; }; void RunTest(TestJob* job) { (*job)(); } void Deallocate(TestJob* job) { delete job; } // A test set, containing pointers to TestJob objects class TestSet { public: TestSet(const std::string name) : name_(name) { } ~TestSet() { std::for_each(jobs_.begin(), jobs_.end(), Deallocate); } void Start() { std::cout << std::endl << name_ << std::endl; std::cout << std::string(25, '=') << std::endl; std::for_each(jobs_.begin(), jobs_.end(), RunTest); }; std::vector<TestJob*> jobs_; private: std::string name_; }; // Our unit tests class FormatTestJob : public TestJob { public: virtual void operator()() { using utilities::__Format; std::string test1 = Format("Hello, %s %d", "Mohannad", 1986); CHECK_RESULT(test1 == "Hello, Mohannad 1986", "utlities::__Format<char>(...) with 'const char*'", test1); std::string test2 = Format("Hello, %S %d !%", std::string("Mohannad"), 1986); CHECK_RESULT(test2 == "Hello, Mohannad 1986 !%", "utlities::__Format<char>(...) with 'std::string'", test2); std::wstring test3 = FormatW(L"wHello, %s %d !", L"wMohannad", 1986); CHECK_RESULT(test3 == L"wHello, wMohannad 1986 !", "utlities::__Format<wchar_t>(...) with 'const wchar_t*'", WstringToString(test3)); std::wstring test4 = FormatW(L"wHello, %S %d !", std::wstring(L"wMohannad"), 1986); CHECK_RESULT(test4 == L"wHello, wMohannad 1986 !", "utlities::__Format<wchar_t>(...) with 'std::wstring'", WstringToString(test4)); } private: // Bad helper function ! // wstring to string converter std::string WstringToString(const std::wstring& w_string) { std::string result(w_string.length(), ' '); std::copy(w_string.begin(), w_string.end(), result.begin()); return result; } }; //class IL_TestJob : public TestJob { // virtual void operator()() { // SymbolTable symbol_table(NULL); // symbol_table.Insert(new VariableSymbol("x")); // // VariableOperand var_x("x", &symbol_table); // IntermediateInstr instruction(kPlus, &var_x, &var_x, new NumberOperand(10)); // // std::string test1 = instruction.GetAsString(); // CHECK_RESULT("x = x + 10" == test1, test1, test1); // } //}; // The start point of testing void RunTests() { std::cout << "Running Tests\r\n" << std::endl; //TestSet intermediate_set("IL Tests"); //ADD_TEST(intermediate_set, new IL_TestJob); //intermediate_set.Start(); TestSet format_test("Format<Elem>(...) Test"); ADD_TEST(format_test, new FormatTestJob); format_test.Start(); } #endif // _TEST_BUILD
27.852459
137
0.651854
[ "object", "vector" ]
5022ca908b7453b23fca20b876621f3df4fa50aa
11,614
cpp
C++
test/test_dataset_tabular.cpp
accosmin/libnano
0c4014e1bc76c2e1b38d08211b000a4e17b00ed5
[ "MIT" ]
null
null
null
test/test_dataset_tabular.cpp
accosmin/libnano
0c4014e1bc76c2e1b38d08211b000a4e17b00ed5
[ "MIT" ]
32
2019-02-18T10:35:59.000Z
2021-12-10T10:37:15.000Z
test/test_dataset_tabular.cpp
accosmin/libnano
0c4014e1bc76c2e1b38d08211b000a4e17b00ed5
[ "MIT" ]
1
2019-08-05T06:11:09.000Z
2019-08-05T06:11:09.000Z
#include <fstream> #include <utest/utest.h> #include <nano/dataset/tabular.h> using namespace nano; static auto feature_cont() { return feature_t{"cont"}; } static auto feature_cont_opt() { return feature_t{"cont_opt"}.placeholder("?"); } static auto feature_cate() { return feature_t{"cate"}.labels({"cate0", "cate1", "cate2"}); } static auto feature_cate_opt() { return feature_t{"cate_opt"}.labels({"cate_opt0", "cate_opt1"}).placeholder("?"); } class fixture_dataset_t final : public tabular_dataset_t { public: static auto data_path() { return "test_dataset_tabular_data.csv"; } static auto test_path() { return "test_dataset_tabular_test.csv"; } static auto csvs(tensor_size_t data_expected = 20, tensor_size_t test_expected = 10) { return csvs_t( { csv_t{data_path()}.delim(",").header(false).expected(data_expected).skip('@'), csv_t{test_path()}.delim(",").header(true).expected(test_expected).skip('@').testing(0, test_expected) }); } fixture_dataset_t() : fixture_dataset_t(fixture_dataset_t::csvs(), features_t{}) { } fixture_dataset_t(features_t features, size_t target = string_t::npos) : fixture_dataset_t(fixture_dataset_t::csvs(), std::move(features), target) { } fixture_dataset_t(csvs_t csvs, features_t features, size_t target = string_t::npos) : tabular_dataset_t(std::move(csvs), std::move(features), target) { std::remove(data_path()); std::remove(test_path()); write_data(data_path()); write_test(test_path()); } fixture_dataset_t(fixture_dataset_t&&) = default; fixture_dataset_t(const fixture_dataset_t&) = delete; fixture_dataset_t& operator=(fixture_dataset_t&&) = default; fixture_dataset_t& operator=(const fixture_dataset_t&) = delete; ~fixture_dataset_t() override { std::remove(data_path()); std::remove(test_path()); } static void write_data(const char* path) { std::ofstream os(path); write(os, 1, 20, false); UTEST_REQUIRE(os); } static void write_test(const char* path) { std::ofstream os(path); write(os, 21, 10, true); UTEST_REQUIRE(os); } static void check(const scalar_t value, int row, const int col) { ++ row; switch (col) { case 0: check(value, row); break; case 1: check(value, (row % 2 == 0) ? feature_t::placeholder_value() : (3.0 - 0.2 * row)); break; case 2: check(value, row % 3); break; case 3: check(value, (row % 4 == 0) ? feature_t::placeholder_value() : (row % 2)); break; default: UTEST_REQUIRE(false); } } static void check(const scalar_t value, const scalar_t ground) { UTEST_CHECK_EQUAL(std::isfinite(value), std::isfinite(ground)); if (std::isfinite(value)) { UTEST_CHECK_CLOSE(value, ground, 1e-8); } } static void write(std::ostream& os, const int begin, const int size, const bool header) { if (header) { os << "cont,cont_opt,cate,cate_opt\n"; } for (auto index = begin; index < begin + size; ++ index) { os << index << ","; (index % 2 == 0) ? (os << "?,") : (os << (3.0 - 0.2 * index) << ","); os << "cate" << (index % 3) << ","; (index % 4 == 0) ? (os << "?,") : (os << "cate_opt" << (index % 2) << ","); os << "\n"; if (index % 7 == 0) { os << "\n"; } if (index % 9 == 0) { os << "@ this line should be skipped\n"; } } } }; UTEST_BEGIN_MODULE(test_dataset_tabular) UTEST_CASE(empty) { auto dataset = fixture_dataset_t{}; UTEST_CHECK(!dataset.target()); UTEST_CHECK_EQUAL(dataset.features(), 0); UTEST_CHECK_THROW(dataset.feature(0), std::out_of_range); } UTEST_CASE(config_no_target) { auto dataset = fixture_dataset_t{{feature_cont(), feature_cont_opt(), feature_cate(), feature_cate_opt()}}; UTEST_CHECK(!dataset.target()); UTEST_CHECK_EQUAL(dataset.features(), 0); UTEST_CHECK_EQUAL(dataset.feature(0), feature_cont()); UTEST_CHECK_EQUAL(dataset.feature(1), feature_cont_opt()); UTEST_CHECK_EQUAL(dataset.feature(2), feature_cate()); UTEST_CHECK_EQUAL(dataset.feature(3), feature_cate_opt()); } UTEST_CASE(config_with_target) { auto dataset = fixture_dataset_t{{feature_cont(), feature_cont_opt(), feature_cate(), feature_cate_opt()}, 0}; UTEST_CHECK_EQUAL(dataset.features(), 0); UTEST_CHECK_EQUAL(dataset.feature(0), feature_cont_opt()); UTEST_CHECK_EQUAL(dataset.feature(1), feature_cate()); UTEST_CHECK_EQUAL(dataset.feature(2), feature_cate_opt()); UTEST_CHECK_EQUAL(dataset.target(), feature_cont()); } UTEST_CASE(noload_no_data) { const auto csvs = csvs_t{}; auto dataset = fixture_dataset_t{csvs, {feature_cont(), feature_cont_opt(), feature_cate(), feature_cate_opt()}, 0}; UTEST_REQUIRE_THROW(dataset.load(), std::runtime_error); } UTEST_CASE(noload_no_features) { auto dataset = fixture_dataset_t{}; UTEST_REQUIRE_THROW(dataset.load(), std::runtime_error); } UTEST_CASE(noload_few_features) { auto dataset = fixture_dataset_t{{feature_cont(), feature_cont_opt(), feature_cate()}, 0}; UTEST_REQUIRE_THROW(dataset.load(), std::runtime_error); } UTEST_CASE(noload_wrong_features0) { auto dataset = fixture_dataset_t{{feature_cont_opt(), feature_cont(), feature_cate(), feature_cate_opt()}, 1}; UTEST_REQUIRE_THROW(dataset.load(), std::runtime_error); } UTEST_CASE(noload_wrong_features1) { auto dataset = fixture_dataset_t{{feature_cont(), feature_cont_opt(), feature_cate_opt(), feature_cate()}, 0}; UTEST_REQUIRE_THROW(dataset.load(), std::runtime_error); } UTEST_CASE(noload_wrong_expected0) { const auto csvs = fixture_dataset_t::csvs(21, 10); auto dataset = fixture_dataset_t{csvs, {feature_cont(), feature_cont_opt(), feature_cate(), feature_cate_opt()}, 0}; UTEST_REQUIRE_THROW(dataset.load(), std::runtime_error); } UTEST_CASE(noload_wrong_expected0) { const auto csvs = fixture_dataset_t::csvs(20, 9); auto dataset = fixture_dataset_t{csvs, {feature_cont(), feature_cont_opt(), feature_cate(), feature_cate_opt()}, 0}; UTEST_REQUIRE_THROW(dataset.load(), std::runtime_error); } UTEST_CASE(noload_invalid_target0) { auto dataset = fixture_dataset_t{{feature_cont(), feature_cont_opt(), feature_cate(), feature_cate_opt()}, 4}; UTEST_REQUIRE_THROW(dataset.load(), std::runtime_error); } UTEST_CASE(noload_invalid_target1) { auto dataset = fixture_dataset_t{{feature_cont(), feature_cont_opt(), feature_cate(), feature_cate_opt()}, 1}; UTEST_REQUIRE_THROW(dataset.load(), std::runtime_error); } UTEST_CASE(noload_invalid_target2) { auto dataset = fixture_dataset_t{{feature_cont(), feature_cont_opt(), feature_cate(), feature_cate_opt()}, 3}; UTEST_REQUIRE_THROW(dataset.load(), std::runtime_error); } UTEST_CASE(load_no_target) { auto dataset = fixture_dataset_t{{feature_cont(), feature_cont_opt(), feature_cate(), feature_cate_opt()}}; UTEST_REQUIRE_NOTHROW(dataset.load()); UTEST_CHECK_EQUAL(dataset.features(), 4); UTEST_CHECK_EQUAL(dataset.feature(0), feature_cont()); UTEST_CHECK_EQUAL(dataset.feature(1), feature_cont_opt()); UTEST_CHECK_EQUAL(dataset.feature(2), feature_cate()); UTEST_CHECK_EQUAL(dataset.feature(3), feature_cate_opt()); UTEST_CHECK(!dataset.target()); UTEST_CHECK_EQUAL(dataset.type(), task_type::unsupervised); UTEST_CHECK_EQUAL(dataset.idim(), make_dims(4, 1, 1)); UTEST_CHECK_EQUAL(dataset.tdim(), make_dims(0, 1, 1)); UTEST_CHECK_EQUAL(dataset.samples(), 30); UTEST_CHECK_EQUAL(dataset.train_samples(), ::nano::arange(0, 20)); UTEST_CHECK_EQUAL(dataset.test_samples(), ::nano::arange(20, 30)); const auto inputs = dataset.inputs(::nano::arange(10, 30)); const auto targets = dataset.targets(::nano::arange(10, 30)); UTEST_CHECK_EQUAL(inputs.dims(), make_dims(20, 4, 1, 1)); UTEST_CHECK_EQUAL(targets.dims(), make_dims(20, 0, 1, 1)); for (auto index = 0; index < 20; ++ index) { fixture_dataset_t::check(inputs(index, 0, 0, 0), index + 10, 0); fixture_dataset_t::check(inputs(index, 1, 0, 0), index + 10, 1); fixture_dataset_t::check(inputs(index, 2, 0, 0), index + 10, 2); fixture_dataset_t::check(inputs(index, 3, 0, 0), index + 10, 3); } } UTEST_CASE(load_with_cont_target) { auto dataset = fixture_dataset_t{{feature_cont(), feature_cont_opt(), feature_cate(), feature_cate_opt()}, 0}; UTEST_REQUIRE_NOTHROW(dataset.load()); UTEST_CHECK_EQUAL(dataset.features(), 3); UTEST_CHECK_EQUAL(dataset.feature(0), feature_cont_opt()); UTEST_CHECK_EQUAL(dataset.feature(1), feature_cate()); UTEST_CHECK_EQUAL(dataset.feature(2), feature_cate_opt()); UTEST_CHECK_EQUAL(dataset.target(), feature_cont()); UTEST_CHECK_EQUAL(dataset.type(), task_type::regression); UTEST_CHECK_EQUAL(dataset.idim(), make_dims(3, 1, 1)); UTEST_CHECK_EQUAL(dataset.tdim(), make_dims(1, 1, 1)); UTEST_CHECK_EQUAL(dataset.samples(), 30); UTEST_CHECK_EQUAL(dataset.train_samples(), ::nano::arange(0, 20)); UTEST_CHECK_EQUAL(dataset.test_samples(), ::nano::arange(20, 30)); const auto inputs = dataset.inputs(::nano::arange(10, 30)); const auto targets = dataset.targets(::nano::arange(10, 30)); UTEST_CHECK_EQUAL(inputs.dims(), make_dims(20, 3, 1, 1)); UTEST_CHECK_EQUAL(targets.dims(), make_dims(20, 1, 1, 1)); for (auto index = 0; index < 20; ++ index) { fixture_dataset_t::check(targets(index, 0, 0, 0), index + 10, 0); fixture_dataset_t::check(inputs(index, 0, 0, 0), index + 10, 1); fixture_dataset_t::check(inputs(index, 1, 0, 0), index + 10, 2); fixture_dataset_t::check(inputs(index, 2, 0, 0), index + 10, 3); } } UTEST_CASE(load_with_cate_target) { auto dataset = fixture_dataset_t{{feature_cont(), feature_cont_opt(), feature_cate(), feature_cate_opt()}, 2}; UTEST_REQUIRE_NOTHROW(dataset.load()); UTEST_CHECK_EQUAL(dataset.features(), 3); UTEST_CHECK_EQUAL(dataset.feature(0), feature_cont()); UTEST_CHECK_EQUAL(dataset.feature(1), feature_cont_opt()); UTEST_CHECK_EQUAL(dataset.feature(2), feature_cate_opt()); UTEST_CHECK_EQUAL(dataset.target(), feature_cate()); UTEST_CHECK_EQUAL(dataset.type(), task_type::sclassification); UTEST_CHECK_EQUAL(dataset.idim(), make_dims(3, 1, 1)); UTEST_CHECK_EQUAL(dataset.tdim(), make_dims(3, 1, 1)); UTEST_CHECK_EQUAL(dataset.samples(), 30); UTEST_CHECK_EQUAL(dataset.train_samples(), ::nano::arange(0, 20)); UTEST_CHECK_EQUAL(dataset.test_samples(), ::nano::arange(20, 30)); const auto inputs = dataset.inputs(::nano::arange(10, 30)); const auto targets = dataset.targets(::nano::arange(10, 30)); UTEST_CHECK_EQUAL(inputs.dims(), make_dims(20, 3, 1, 1)); UTEST_CHECK_EQUAL(targets.dims(), make_dims(20, 3, 1, 1)); for (auto index = 0; index < 20; ++ index) { fixture_dataset_t::check(inputs(index, 0, 0, 0), index + 10, 0); fixture_dataset_t::check(inputs(index, 1, 0, 0), index + 10, 1); tensor_size_t category = 0; targets.vector(index).maxCoeff(&category); fixture_dataset_t::check(category, index + 10, 2); fixture_dataset_t::check(inputs(index, 2, 0, 0), index + 10, 3); } } UTEST_END_MODULE()
34.668657
120
0.664198
[ "vector" ]
5025defac12ce06bb7b97d0a5ba0a3fcf2851ad0
15,211
cc
C++
absl/random/internal/chi_square_test.cc
lmxing/abseil-cpp
b2948198632099070e0cc7e21cbb28d93d60e4f3
[ "Apache-2.0" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
absl/random/internal/chi_square_test.cc
iWYZ-666/abseil-cpp
aad2c8a3966424bbaa2f26027d104d17f9c1c1ae
[ "Apache-2.0" ]
860
2017-09-26T03:38:59.000Z
2022-03-31T18:28:28.000Z
absl/random/internal/chi_square_test.cc
iWYZ-666/abseil-cpp
aad2c8a3966424bbaa2f26027d104d17f9c1c1ae
[ "Apache-2.0" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2017 The Abseil Authors. // // 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 "absl/random/internal/chi_square.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <iterator> #include <numeric> #include <vector> #include "gtest/gtest.h" #include "absl/base/macros.h" using absl::random_internal::ChiSquare; using absl::random_internal::ChiSquarePValue; using absl::random_internal::ChiSquareValue; using absl::random_internal::ChiSquareWithExpected; namespace { TEST(ChiSquare, Value) { struct { int line; double chi_square; int df; double confidence; } const specs[] = { // Testing lookup at 1% confidence {__LINE__, 0, 0, 0.01}, {__LINE__, 0.00016, 1, 0.01}, {__LINE__, 1.64650, 8, 0.01}, {__LINE__, 5.81221, 16, 0.01}, {__LINE__, 156.4319, 200, 0.01}, {__LINE__, 1121.3784, 1234, 0.01}, {__LINE__, 53557.1629, 54321, 0.01}, {__LINE__, 651662.6647, 654321, 0.01}, // Testing lookup at 99% confidence {__LINE__, 0, 0, 0.99}, {__LINE__, 6.635, 1, 0.99}, {__LINE__, 20.090, 8, 0.99}, {__LINE__, 32.000, 16, 0.99}, {__LINE__, 249.4456, 200, 0.99}, {__LINE__, 1131.1573, 1023, 0.99}, {__LINE__, 1352.5038, 1234, 0.99}, {__LINE__, 55090.7356, 54321, 0.99}, {__LINE__, 656985.1514, 654321, 0.99}, // Testing lookup at 99.9% confidence {__LINE__, 16.2659, 3, 0.999}, {__LINE__, 22.4580, 6, 0.999}, {__LINE__, 267.5409, 200, 0.999}, {__LINE__, 1168.5033, 1023, 0.999}, {__LINE__, 55345.1741, 54321, 0.999}, {__LINE__, 657861.7284, 654321, 0.999}, {__LINE__, 51.1772, 24, 0.999}, {__LINE__, 59.7003, 30, 0.999}, {__LINE__, 37.6984, 15, 0.999}, {__LINE__, 29.5898, 10, 0.999}, {__LINE__, 27.8776, 9, 0.999}, // Testing lookup at random confidences {__LINE__, 0.000157088, 1, 0.01}, {__LINE__, 5.31852, 2, 0.93}, {__LINE__, 1.92256, 4, 0.25}, {__LINE__, 10.7709, 13, 0.37}, {__LINE__, 26.2514, 17, 0.93}, {__LINE__, 36.4799, 29, 0.84}, {__LINE__, 25.818, 31, 0.27}, {__LINE__, 63.3346, 64, 0.50}, {__LINE__, 196.211, 128, 0.9999}, {__LINE__, 215.21, 243, 0.10}, {__LINE__, 285.393, 256, 0.90}, {__LINE__, 984.504, 1024, 0.1923}, {__LINE__, 2043.85, 2048, 0.4783}, {__LINE__, 48004.6, 48273, 0.194}, }; for (const auto& spec : specs) { SCOPED_TRACE(spec.line); // Verify all values are have at most a 1% relative error. const double val = ChiSquareValue(spec.df, spec.confidence); const double err = std::max(5e-6, spec.chi_square / 5e3); // 1 part in 5000 EXPECT_NEAR(spec.chi_square, val, err) << spec.line; } // Relaxed test for extreme values, from // http://www.ciphersbyritter.com/JAVASCRP/NORMCHIK.HTM#ChiSquare EXPECT_NEAR(49.2680, ChiSquareValue(100, 1e-6), 5); // 0.000'005 mark EXPECT_NEAR(123.499, ChiSquareValue(200, 1e-6), 5); // 0.000'005 mark EXPECT_NEAR(149.449, ChiSquareValue(100, 0.999), 0.01); EXPECT_NEAR(161.318, ChiSquareValue(100, 0.9999), 0.01); EXPECT_NEAR(172.098, ChiSquareValue(100, 0.99999), 0.01); EXPECT_NEAR(381.426, ChiSquareValue(300, 0.999), 0.05); EXPECT_NEAR(399.756, ChiSquareValue(300, 0.9999), 0.1); EXPECT_NEAR(416.126, ChiSquareValue(300, 0.99999), 0.2); } TEST(ChiSquareTest, PValue) { struct { int line; double pval; double chi_square; int df; } static const specs[] = { {__LINE__, 1, 0, 0}, {__LINE__, 0, 0.001, 0}, {__LINE__, 1.000, 0, 453}, {__LINE__, 0.134471, 7972.52, 7834}, {__LINE__, 0.203922, 28.32, 23}, {__LINE__, 0.737171, 48274, 48472}, {__LINE__, 0.444146, 583.1234, 579}, {__LINE__, 0.294814, 138.2, 130}, {__LINE__, 0.0816532, 12.63, 7}, {__LINE__, 0, 682.32, 67}, {__LINE__, 0.49405, 999, 999}, {__LINE__, 1.000, 0, 9999}, {__LINE__, 0.997477, 0.00001, 1}, {__LINE__, 0, 5823.21, 5040}, }; for (const auto& spec : specs) { SCOPED_TRACE(spec.line); const double pval = ChiSquarePValue(spec.chi_square, spec.df); EXPECT_NEAR(spec.pval, pval, 1e-3); } } TEST(ChiSquareTest, CalcChiSquare) { struct { int line; std::vector<int> expected; std::vector<int> actual; } const specs[] = { {__LINE__, {56, 234, 76, 1, 546, 1, 87, 345, 1, 234}, {2, 132, 4, 43, 234, 8, 345, 8, 236, 56}}, {__LINE__, {123, 36, 234, 367, 345, 2, 456, 567, 234, 567}, {123, 56, 2345, 8, 345, 8, 2345, 23, 48, 267}}, {__LINE__, {123, 234, 345, 456, 567, 678, 789, 890, 98, 76}, {123, 234, 345, 456, 567, 678, 789, 890, 98, 76}}, {__LINE__, {3, 675, 23, 86, 2, 8, 2}, {456, 675, 23, 86, 23, 65, 2}}, {__LINE__, {1}, {23}}, }; for (const auto& spec : specs) { SCOPED_TRACE(spec.line); double chi_square = 0; for (int i = 0; i < spec.expected.size(); ++i) { const double diff = spec.actual[i] - spec.expected[i]; chi_square += (diff * diff) / spec.expected[i]; } EXPECT_NEAR(chi_square, ChiSquare(std::begin(spec.actual), std::end(spec.actual), std::begin(spec.expected), std::end(spec.expected)), 1e-5); } } TEST(ChiSquareTest, CalcChiSquareInt64) { const int64_t data[3] = {910293487, 910292491, 910216780}; // $ python -c "import scipy.stats // > print scipy.stats.chisquare([910293487, 910292491, 910216780])[0]" // 4.25410123524 double sum = std::accumulate(std::begin(data), std::end(data), double{0}); size_t n = std::distance(std::begin(data), std::end(data)); double a = ChiSquareWithExpected(std::begin(data), std::end(data), sum / n); EXPECT_NEAR(4.254101, a, 1e-6); // ... Or with known values. double b = ChiSquareWithExpected(std::begin(data), std::end(data), 910267586.0); EXPECT_NEAR(4.254101, b, 1e-6); } TEST(ChiSquareTest, TableData) { // Test data from // http://www.itl.nist.gov/div898/handbook/eda/section3/eda3674.htm // 0.90 0.95 0.975 0.99 0.999 const double data[100][5] = { /* 1*/ {2.706, 3.841, 5.024, 6.635, 10.828}, /* 2*/ {4.605, 5.991, 7.378, 9.210, 13.816}, /* 3*/ {6.251, 7.815, 9.348, 11.345, 16.266}, /* 4*/ {7.779, 9.488, 11.143, 13.277, 18.467}, /* 5*/ {9.236, 11.070, 12.833, 15.086, 20.515}, /* 6*/ {10.645, 12.592, 14.449, 16.812, 22.458}, /* 7*/ {12.017, 14.067, 16.013, 18.475, 24.322}, /* 8*/ {13.362, 15.507, 17.535, 20.090, 26.125}, /* 9*/ {14.684, 16.919, 19.023, 21.666, 27.877}, /*10*/ {15.987, 18.307, 20.483, 23.209, 29.588}, /*11*/ {17.275, 19.675, 21.920, 24.725, 31.264}, /*12*/ {18.549, 21.026, 23.337, 26.217, 32.910}, /*13*/ {19.812, 22.362, 24.736, 27.688, 34.528}, /*14*/ {21.064, 23.685, 26.119, 29.141, 36.123}, /*15*/ {22.307, 24.996, 27.488, 30.578, 37.697}, /*16*/ {23.542, 26.296, 28.845, 32.000, 39.252}, /*17*/ {24.769, 27.587, 30.191, 33.409, 40.790}, /*18*/ {25.989, 28.869, 31.526, 34.805, 42.312}, /*19*/ {27.204, 30.144, 32.852, 36.191, 43.820}, /*20*/ {28.412, 31.410, 34.170, 37.566, 45.315}, /*21*/ {29.615, 32.671, 35.479, 38.932, 46.797}, /*22*/ {30.813, 33.924, 36.781, 40.289, 48.268}, /*23*/ {32.007, 35.172, 38.076, 41.638, 49.728}, /*24*/ {33.196, 36.415, 39.364, 42.980, 51.179}, /*25*/ {34.382, 37.652, 40.646, 44.314, 52.620}, /*26*/ {35.563, 38.885, 41.923, 45.642, 54.052}, /*27*/ {36.741, 40.113, 43.195, 46.963, 55.476}, /*28*/ {37.916, 41.337, 44.461, 48.278, 56.892}, /*29*/ {39.087, 42.557, 45.722, 49.588, 58.301}, /*30*/ {40.256, 43.773, 46.979, 50.892, 59.703}, /*31*/ {41.422, 44.985, 48.232, 52.191, 61.098}, /*32*/ {42.585, 46.194, 49.480, 53.486, 62.487}, /*33*/ {43.745, 47.400, 50.725, 54.776, 63.870}, /*34*/ {44.903, 48.602, 51.966, 56.061, 65.247}, /*35*/ {46.059, 49.802, 53.203, 57.342, 66.619}, /*36*/ {47.212, 50.998, 54.437, 58.619, 67.985}, /*37*/ {48.363, 52.192, 55.668, 59.893, 69.347}, /*38*/ {49.513, 53.384, 56.896, 61.162, 70.703}, /*39*/ {50.660, 54.572, 58.120, 62.428, 72.055}, /*40*/ {51.805, 55.758, 59.342, 63.691, 73.402}, /*41*/ {52.949, 56.942, 60.561, 64.950, 74.745}, /*42*/ {54.090, 58.124, 61.777, 66.206, 76.084}, /*43*/ {55.230, 59.304, 62.990, 67.459, 77.419}, /*44*/ {56.369, 60.481, 64.201, 68.710, 78.750}, /*45*/ {57.505, 61.656, 65.410, 69.957, 80.077}, /*46*/ {58.641, 62.830, 66.617, 71.201, 81.400}, /*47*/ {59.774, 64.001, 67.821, 72.443, 82.720}, /*48*/ {60.907, 65.171, 69.023, 73.683, 84.037}, /*49*/ {62.038, 66.339, 70.222, 74.919, 85.351}, /*50*/ {63.167, 67.505, 71.420, 76.154, 86.661}, /*51*/ {64.295, 68.669, 72.616, 77.386, 87.968}, /*52*/ {65.422, 69.832, 73.810, 78.616, 89.272}, /*53*/ {66.548, 70.993, 75.002, 79.843, 90.573}, /*54*/ {67.673, 72.153, 76.192, 81.069, 91.872}, /*55*/ {68.796, 73.311, 77.380, 82.292, 93.168}, /*56*/ {69.919, 74.468, 78.567, 83.513, 94.461}, /*57*/ {71.040, 75.624, 79.752, 84.733, 95.751}, /*58*/ {72.160, 76.778, 80.936, 85.950, 97.039}, /*59*/ {73.279, 77.931, 82.117, 87.166, 98.324}, /*60*/ {74.397, 79.082, 83.298, 88.379, 99.607}, /*61*/ {75.514, 80.232, 84.476, 89.591, 100.888}, /*62*/ {76.630, 81.381, 85.654, 90.802, 102.166}, /*63*/ {77.745, 82.529, 86.830, 92.010, 103.442}, /*64*/ {78.860, 83.675, 88.004, 93.217, 104.716}, /*65*/ {79.973, 84.821, 89.177, 94.422, 105.988}, /*66*/ {81.085, 85.965, 90.349, 95.626, 107.258}, /*67*/ {82.197, 87.108, 91.519, 96.828, 108.526}, /*68*/ {83.308, 88.250, 92.689, 98.028, 109.791}, /*69*/ {84.418, 89.391, 93.856, 99.228, 111.055}, /*70*/ {85.527, 90.531, 95.023, 100.425, 112.317}, /*71*/ {86.635, 91.670, 96.189, 101.621, 113.577}, /*72*/ {87.743, 92.808, 97.353, 102.816, 114.835}, /*73*/ {88.850, 93.945, 98.516, 104.010, 116.092}, /*74*/ {89.956, 95.081, 99.678, 105.202, 117.346}, /*75*/ {91.061, 96.217, 100.839, 106.393, 118.599}, /*76*/ {92.166, 97.351, 101.999, 107.583, 119.850}, /*77*/ {93.270, 98.484, 103.158, 108.771, 121.100}, /*78*/ {94.374, 99.617, 104.316, 109.958, 122.348}, /*79*/ {95.476, 100.749, 105.473, 111.144, 123.594}, /*80*/ {96.578, 101.879, 106.629, 112.329, 124.839}, /*81*/ {97.680, 103.010, 107.783, 113.512, 126.083}, /*82*/ {98.780, 104.139, 108.937, 114.695, 127.324}, /*83*/ {99.880, 105.267, 110.090, 115.876, 128.565}, /*84*/ {100.980, 106.395, 111.242, 117.057, 129.804}, /*85*/ {102.079, 107.522, 112.393, 118.236, 131.041}, /*86*/ {103.177, 108.648, 113.544, 119.414, 132.277}, /*87*/ {104.275, 109.773, 114.693, 120.591, 133.512}, /*88*/ {105.372, 110.898, 115.841, 121.767, 134.746}, /*89*/ {106.469, 112.022, 116.989, 122.942, 135.978}, /*90*/ {107.565, 113.145, 118.136, 124.116, 137.208}, /*91*/ {108.661, 114.268, 119.282, 125.289, 138.438}, /*92*/ {109.756, 115.390, 120.427, 126.462, 139.666}, /*93*/ {110.850, 116.511, 121.571, 127.633, 140.893}, /*94*/ {111.944, 117.632, 122.715, 128.803, 142.119}, /*95*/ {113.038, 118.752, 123.858, 129.973, 143.344}, /*96*/ {114.131, 119.871, 125.000, 131.141, 144.567}, /*97*/ {115.223, 120.990, 126.141, 132.309, 145.789}, /*98*/ {116.315, 122.108, 127.282, 133.476, 147.010}, /*99*/ {117.407, 123.225, 128.422, 134.642, 148.230}, /*100*/ {118.498, 124.342, 129.561, 135.807, 149.449} /**/}; // 0.90 0.95 0.975 0.99 0.999 for (int i = 0; i < ABSL_ARRAYSIZE(data); i++) { const double E = 0.0001; EXPECT_NEAR(ChiSquarePValue(data[i][0], i + 1), 0.10, E) << i << " " << data[i][0]; EXPECT_NEAR(ChiSquarePValue(data[i][1], i + 1), 0.05, E) << i << " " << data[i][1]; EXPECT_NEAR(ChiSquarePValue(data[i][2], i + 1), 0.025, E) << i << " " << data[i][2]; EXPECT_NEAR(ChiSquarePValue(data[i][3], i + 1), 0.01, E) << i << " " << data[i][3]; EXPECT_NEAR(ChiSquarePValue(data[i][4], i + 1), 0.001, E) << i << " " << data[i][4]; const double F = 0.1; EXPECT_NEAR(ChiSquareValue(i + 1, 0.90), data[i][0], F) << i; EXPECT_NEAR(ChiSquareValue(i + 1, 0.95), data[i][1], F) << i; EXPECT_NEAR(ChiSquareValue(i + 1, 0.975), data[i][2], F) << i; EXPECT_NEAR(ChiSquareValue(i + 1, 0.99), data[i][3], F) << i; EXPECT_NEAR(ChiSquareValue(i + 1, 0.999), data[i][4], F) << i; } } TEST(ChiSquareTest, ChiSquareTwoIterator) { // Test data from http://www.stat.yale.edu/Courses/1997-98/101/chigf.htm // Null-hypothesis: This data is normally distributed. const int counts[10] = {6, 6, 18, 33, 38, 38, 28, 21, 9, 3}; const double expected[10] = {4.6, 8.8, 18.4, 30.0, 38.2, 38.2, 30.0, 18.4, 8.8, 4.6}; double chi_square = ChiSquare(std::begin(counts), std::end(counts), std::begin(expected), std::end(expected)); EXPECT_NEAR(chi_square, 2.69, 0.001); // Degrees of freedom: 10 bins. two estimated parameters. = 10 - 2 - 1. const int dof = 7; // The critical value of 7, 95% => 14.067 (see above test) double p_value_05 = ChiSquarePValue(14.067, dof); EXPECT_NEAR(p_value_05, 0.05, 0.001); // 95%-ile p-value double p_actual = ChiSquarePValue(chi_square, dof); EXPECT_GT(p_actual, 0.05); // Accept the null hypothesis. } TEST(ChiSquareTest, DiceRolls) { // Assume we are testing 102 fair dice rolls. // Null-hypothesis: This data is fairly distributed. // // The dof value of 4, @95% = 9.488 (see above test) // The dof value of 5, @95% = 11.070 const int rolls[6] = {22, 11, 17, 14, 20, 18}; double sum = std::accumulate(std::begin(rolls), std::end(rolls), double{0}); size_t n = std::distance(std::begin(rolls), std::end(rolls)); double a = ChiSquareWithExpected(std::begin(rolls), std::end(rolls), sum / n); EXPECT_NEAR(a, 4.70588, 1e-5); EXPECT_LT(a, ChiSquareValue(4, 0.95)); double p_a = ChiSquarePValue(a, 4); EXPECT_NEAR(p_a, 0.318828, 1e-5); // Accept the null hypothesis. double b = ChiSquareWithExpected(std::begin(rolls), std::end(rolls), 17.0); EXPECT_NEAR(b, 4.70588, 1e-5); EXPECT_LT(b, ChiSquareValue(5, 0.95)); double p_b = ChiSquarePValue(b, 5); EXPECT_NEAR(p_b, 0.4528180, 1e-5); // Accept the null hypothesis. } } // namespace
41.560109
80
0.566366
[ "vector" ]
5026934a7603d0ffaa02ab17c3149d9c9dc245d9
11,976
cpp
C++
ats_trains/a2_wagons/config.cpp
gruppe-adler/ats_dev_build
ef35386706ece33db55d045157d622ee78657d33
[ "MIT" ]
null
null
null
ats_trains/a2_wagons/config.cpp
gruppe-adler/ats_dev_build
ef35386706ece33db55d045157d622ee78657d33
[ "MIT" ]
null
null
null
ats_trains/a2_wagons/config.cpp
gruppe-adler/ats_dev_build
ef35386706ece33db55d045157d622ee78657d33
[ "MIT" ]
null
null
null
#define private 0 #define protected 1 #define public 2 class CfgPatches { class ATS_Trains_A2Wagons { units[] = {}; weapons[] = {}; requiredVersion = 0.1; requiredAddons[] = {"ATS_Trains"}; }; }; class CfgVehicles { class Items_base_F; class ATS_Trains_Base: Items_base_F { class AnimationSources; }; class ATS_Trains_A2Wagon_Box: ATS_Trains_Base { scope = public; mapSize = 0.7; accuracy = 0.5; icon = "iconObject_2x5"; displayName = "A2 Wagon (Box)"; _generalMacro = "ATS_A2Wagon_Box"; model = "ats\trains\a2_wagons\wagon_box.p3d"; editorPreview = "\ats\trains\screenshots\ATS_Trains_A2Wagon_Box.jpg"; class AnimationSources: AnimationSources { class Door_L { source = "user"; animPeriod = 1; initPhase = 0; }; class Door_R { source = "user"; animPeriod = 1; initPhase = 0; }; }; class UserActions { class OpenDoor_L { displayNameDefault = "<img image='\A3\Ui_f\data\IGUI\Cfg\Actions\open_door_ca.paa' size='2.5' />"; // This is displayed in the center of the screen just below crosshair. In this case it's an icon, not a text. displayName = "Open Left Door"; // Label of the action used in the action menu itself. position = "door_left_begin"; // Point in Memory lod in p3d around which the action is available. priority = 0.4; // Priority coefficient used for sorting action in the action menu. radius = 1.5; // Range around the above defined point in which you need to be to access the action. onlyForPlayer = false; // Defines if the action is available only to players or AI as well. condition = "((this animationPhase ""Door_L"") < 2.4) && ((this getVariable [""bis_disabled_Door_1"",0]) != 1)"; // Condition for showing the action in action menu. In this case it checks if the door is closed and if the part of the house in which the door is located hasn't been destroyed yet). statement = "this animate [""Door_"",2.4]; this enableVehicleCargo true"; // Action taken when this action is selected in the action menu. In this case it calls a function that opens the door. }; class CloseDoor_L { displayNameDefault = "<img image='\A3\Ui_f\data\IGUI\Cfg\Actions\open_door_ca.paa' size='2.5' />"; // This is displayed in the center of the screen just below crosshair. In this case it's an icon, not a text. displayName = "Close Left Door"; // Label of the action used in the action menu itself. position = "door_left_begin"; // Point in Memory lod in p3d around which the action is available. priority = 0.4; // Priority coefficient used for sorting action in the action menu. radius = 1.5; // Range around the above defined point in which you need to be to access the action. onlyForPlayer = false; // Defines if the action is available only to players or AI as well. condition = "((this animationPhase ""Door_L"") > 0) && ((this getVariable [""bis_disabled_Door_1"",0]) != 1)"; // Condition for showing the action in action menu. In this case it checks if the door is closed and if the part of the house in which the door is located hasn't been destroyed yet). statement = "this animate [""Door_L"",0]; this enableVehicleCargo false"; // Action taken when this action is selected in the action menu. In this case it calls a function that opens the door. }; class OpenDoor_R { displayNameDefault = "<img image='\A3\Ui_f\data\IGUI\Cfg\Actions\open_door_ca.paa' size='2.5' />"; // This is displayed in the center of the screen just below crosshair. In this case it's an icon, not a text. displayName = "Open Right Door"; // Label of the action used in the action menu itself. position = "door_right_begin"; // Point in Memory lod in p3d around which the action is available. priority = 0.4; // Priority coefficient used for sorting action in the action menu. radius = 1.5; // Range around the above defined point in which you need to be to access the action. onlyForPlayer = false; // Defines if the action is available only to players or AI as well. condition = "((this animationPhase ""Door_R"") < 2.4) && ((this getVariable [""bis_disabled_Door_2"",0]) != 1)"; // Condition for showing the action in action menu. In this case it checks if the door is closed and if the part of the house in which the door is located hasn't been destroyed yet). statement = "this animate [""Door_R"",2.4]; this enableVehicleCargo true"; // Action taken when this action is selected in the action menu. In this case it calls a function that opens the door. }; class CloseDoor_R { displayNameDefault = "<img image='\A3\Ui_f\data\IGUI\Cfg\Actions\open_door_ca.paa' size='2.5' />"; // This is displayed in the center of the screen just below crosshair. In this case it's an icon, not a text. displayName = "Close Right Door"; // Label of the action used in the action menu itself. position = "door_right_begin"; // Point in Memory lod in p3d around which the action is available. priority = 0.4; // Priority coefficient used for sorting action in the action menu. radius = 1.5; // Range around the above defined point in which you need to be to access the action. onlyForPlayer = false; // Defines if the action is available only to players or AI as well. condition = "((this animationPhase ""Door_R"") > 0) && ((this getVariable [""bis_disabled_Door_2"",0]) != 1)"; // Condition for showing the action in action menu. In this case it checks if the door is closed and if the part of the house in which the door is located hasn't been destroyed yet). statement = "this animate [""Door_R"",0]; this enableVehicleCargo false"; // Action taken when this action is selected in the action menu. In this case it calls a function that opens the door. }; }; class Damage // damage changes material in specific places (visual in hitPoint) { tex[]={}; mat[]= { "ats\trains\a2_wagons\data\box_wagon.rvmat", // material mapped in model "ats\trains\data\damage.rvmat", // changes to this one once damage of the part reaches 0.5 "ats\trains\data\destruct.rvmat" // changes to this one once damage of the part reaches 1 }; }; class VehicleTransport { class Carrier { cargoBayDimensions[] = {"limit_1", "limit_2"}; // Memory points in model defining cargo space disableHeightLimit = 1; // If set to 1 disable height limit of transported vehicles maxLoadMass = 200000; // Maximum cargo weight (in Kg) which the vehicle can transport cargoAlignment[] = {"center", "front"}; // Array of 2 elements defining alignment of vehicles in cargo space. Possible values are left, right, center, front, back. Order is important. cargoSpacing[] = {0, 0.15, 0}; // Offset from X,Y,Z axes (in metres) exits[] = {"exit_1", "exit_2"}; // Memory points in model defining loading ramps, could have multiple unloadingInterval = 2; // Time between unloading vehicles (in seconds) loadingDistance = 10; // Maximal distance for loading in exit point (in meters). loadingAngle = 60; // Maximal sector where cargo vehicle must be to for loading (in degrees). //parachuteClassDefault = B_Parachute_02_F; // Type of parachute used when dropped in air. Can be overridden by parachuteClass in Cargo. //parachuteHeightLimitDefault = 50; // Minimal height above terrain when parachute is used. Can be overriden by parachuteHeightLimit in Cargo. }; }; class EventHandlers { init = "(_this select 0) enableVehicleCargo false"; }; }; class ATS_Trains_A2Wagon_TNT: ATS_Trains_Base { scope = public; displayName = "A2 Wagon (TNT)"; model = "ats\trains\a2_wagons\wagon_tnt.p3d"; editorPreview = "\ats\trains\screenshots\ATS_Trains_A2Wagon_TNT.jpg"; class Damage // damage changes material in specific places (visual in hitPoint) { tex[]={}; mat[]= { "ats\trains\a2_wagons\data\box_wagon.rvmat", // material mapped in model "ats\trains\data\damage.rvmat", // changes to this one once damage of the part reaches 0.5 "ats\trains\data\destruct.rvmat" // changes to this one once damage of the part reaches 1 }; }; }; class ATS_Trains_A2Wagon_Flat: ATS_Trains_Base { scope = public; mapSize = 0.7; accuracy = 0.5; icon = "iconObject_2x5"; displayName = "A2 Wagon (Flat)"; _generalMacro = "ATS_A2Wagon_Flat"; model = "ats\trains\a2_wagons\wagon_flat.p3d"; editorPreview = "\ats\trains\screenshots\ATS_Trains_A2Wagon_Flat.jpg"; class Damage // damage changes material in specific places (visual in hitPoint) { tex[]={}; mat[]= { "ats\trains\a2_wagons\data\flat_wagon.rvmat", // material mapped in model "ats\trains\data\damage.rvmat", // changes to this one once damage of the part reaches 0.5 "ats\trains\data\destruct.rvmat" // changes to this one once damage of the part reaches 1 }; }; class VehicleTransport { class Carrier { cargoBayDimensions[] = {"limit_1", "limit_2"}; // Memory points in model defining cargo space disableHeightLimit = 1; // If set to 1 disable height limit of transported vehicles maxLoadMass = 200000; // Maximum cargo weight (in Kg) which the vehicle can transport cargoAlignment[] = {"center", "front"}; // Array of 2 elements defining alignment of vehicles in cargo space. Possible values are left, right, center, front, back. Order is important. cargoSpacing[] = {0, 0.15, 0}; // Offset from X,Y,Z axes (in metres) exits[] = {"exit_1", "exit_2"}; // Memory points in model defining loading ramps, could have multiple unloadingInterval = 2; // Time between unloading vehicles (in seconds) loadingDistance = 10; // Maximal distance for loading in exit point (in meters). loadingAngle = 60; // Maximal sector where cargo vehicle must be to for loading (in degrees). //parachuteClassDefault = B_Parachute_02_F; // Type of parachute used when dropped in air. Can be overridden by parachuteClass in Cargo. //parachuteHeightLimitDefault = 50; // Minimal height above terrain when parachute is used. Can be overriden by parachuteHeightLimit in Cargo. }; }; class EventHandlers { init = "(_this select 0) enableVehicleCargo true"; }; }; class ATS_Trains_A2Wagon_Tanker: ATS_Trains_Base { scope = public; mapSize = 0.7; accuracy = 0.5; icon = "iconObject_2x5"; displayName = "A2 Wagon (Tanker)"; _generalMacro = "ATS_A2Wagon_Tanker"; model = "ats\trains\a2_wagons\wagon_tanker.p3d"; editorPreview = "\ats\trains\screenshots\ATS_Trains_A2Wagon_Tanker.jpg"; class Damage // damage changes material in specific places (visual in hitPoint) { tex[]={}; mat[]= { "ats\trains\a2_wagons\data\tanker_wagon.rvmat", // material mapped in model "ats\trains\data\damage.rvmat", // changes to this one once damage of the part reaches 0.5 "ats\trains\data\destruct.rvmat" // changes to this one once damage of the part reaches 1 }; }; }; }; class CfgNonAIVehicles { class ProxyRetex; class Proxywagon_tanker_wreck: ProxyRetex { hiddenSelections[] = {"damage"}; hiddenSelectionsTextures[] = {"ats\trains\a2_wagons\data\tanker_01_co.paa"}; model = "ats\trains\a2_wagons\wagon_tanker_wreck.p3d"; }; };
51.399142
299
0.660488
[ "model" ]
50271d915e9f0e2caf5bea1c5816fb3d8fba8c64
1,191
cpp
C++
BeakJoon/c++/solved/2000/2108.cpp
heeboy007/PS-MyAnswers
e5e02972ab64279d96eb43e85941a46b82315fbd
[ "MIT" ]
null
null
null
BeakJoon/c++/solved/2000/2108.cpp
heeboy007/PS-MyAnswers
e5e02972ab64279d96eb43e85941a46b82315fbd
[ "MIT" ]
null
null
null
BeakJoon/c++/solved/2000/2108.cpp
heeboy007/PS-MyAnswers
e5e02972ab64279d96eb43e85941a46b82315fbd
[ "MIT" ]
null
null
null
#include<iostream> #include<vector> #include<algorithm> #include<cstring> #include<cmath> using namespace std; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); long long sum = 0; int count; bool is_second = false; vector<int> numbers; int counter[8001]; memset(counter, 0, sizeof(counter)); cin >> count; for(int i = 0; i < count; i++){ int input; cin >> input; sum += input; numbers.push_back(input); counter[input + 4000]++; } sort(numbers.begin(), numbers.end()); int freq_max = 0, freq_what = -5000; for(int i = 0; i < 8001; i++){ if(counter[i] > freq_max){ freq_max = counter[i]; } } for(int i = 0; i < 8001; i++){ if(counter[i] >= freq_max){ freq_what = i - 4000; if(is_second) break; is_second = true; } } //cout << "---------------------\n"; cout << (int)round(sum / (double)count) << '\n'; //1 cout << numbers[count / 2] << '\n'; //2 cout << freq_what << '\n'; //3 cout << numbers[count - 1] - numbers[0] << '\n'; //4 return 0; }
22.055556
56
0.492024
[ "vector" ]
df25f8ad8ad63a894563fa436a562d6a09a9213d
12,014
cc
C++
CondTools/SiPixel/test/SiPixelTemplateDBObjectReader.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
CondTools/SiPixel/test/SiPixelTemplateDBObjectReader.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
CondTools/SiPixel/test/SiPixelTemplateDBObjectReader.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
#include "CondTools/SiPixel/test/SiPixelTemplateDBObjectReader.h" #include <iomanip> #include <fstream> #include <iostream> #include <cmath> #include "FWCore/ParameterSet/interface/FileInPath.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/EventSetup.h" #include "MagneticField/Engine/interface/MagneticField.h" SiPixelTemplateDBObjectReader::SiPixelTemplateDBObjectReader(const edm::ParameterSet& iConfig): theTemplateCalibrationLocation( iConfig.getParameter<std::string>("siPixelTemplateCalibrationLocation") ), theDetailedTemplateDBErrorOutput( iConfig.getParameter<bool>("wantDetailedTemplateDBErrorOutput") ), theFullTemplateDBOutput( iConfig.getParameter<bool>("wantFullTemplateDBOutput") ), testGlobalTag( iConfig.getParameter<bool>("TestGlobalTag") ), hasTriggeredWatcher(false) { } SiPixelTemplateDBObjectReader::~SiPixelTemplateDBObjectReader() { } void SiPixelTemplateDBObjectReader::beginJob() { } void SiPixelTemplateDBObjectReader::analyze(const edm::Event& iEvent, const edm::EventSetup& setup) { //To test with the ESProducer if(testGlobalTag) { edm::ESHandle<MagneticField> magfield; setup.get<IdealMagneticFieldRecord>().get(magfield); GlobalPoint center(0.0, 0.0, 0.0); float theMagField = magfield.product()->inTesla(center).mag(); std::cout << "\nTesting global tag at magfield = " << theMagField << std::endl; if(SiPixTemplDBObjWatcher_.check(setup)) { edm::ESHandle<SiPixelTemplateDBObject> templateH; setup.get<SiPixelTemplateDBObjectESProducerRcd>().get(templateH); dbobject = *templateH.product(); hasTriggeredWatcher=true; } } else { std::cout << "\nLoading from file " << std::endl; if(SiPixTemplDBObjWatcher_.check(setup)) { edm::ESHandle<SiPixelTemplateDBObject> templateH; setup.get<SiPixelTemplateDBObjectRcd>().get(templateH); dbobject = *templateH.product(); hasTriggeredWatcher=true; } } if(hasTriggeredWatcher) { std::vector<short> tempMapId; if(theFullTemplateDBOutput) std::cout << "Map info" << std::endl; std::map<unsigned int,short> templMap=dbobject.getTemplateIDs(); for(std::map<unsigned int,short>::const_iterator it=templMap.begin(); it!=templMap.end();++it) { if(tempMapId.size()==0) tempMapId.push_back(it->second); for(unsigned int i=0; i<tempMapId.size();++i) { if(tempMapId[i]==it->second) continue; else if(i==tempMapId.size()-1) { tempMapId.push_back(it->second); break; } } if(theFullTemplateDBOutput) std::cout<< "DetId: "<< it->first<<" TemplateID: "<< it->second<<"\n"; } std::cout << "\nMap stores template Id(s): "; for(unsigned int vindex=0; vindex < tempMapId.size(); ++ vindex) std::cout << tempMapId[vindex] << " "; std::cout << std::endl; //local variables const char * tempfile; char c; int numOfTempl = dbobject.numOfTempl(); int index = 0; float tempnum=0,diff=0; float tol = 1.0E-23; bool error=false,givenErrorMsg=false;; std::cout << "\nChecking Template DB object version " << dbobject.version() << " containing " << numOfTempl << " calibration(s) at " << dbobject.sVector()[index+22] <<"T\n"; for(int i=0; i<numOfTempl;++i) { //Removes header in db object from diff index+=20; //Tell the person viewing the output what the template ID and version are -- note that version is only valid for >=13 std::cout << "Calibration " << i+1 << " of " << numOfTempl << ", with Template ID " << dbobject.sVector()[index] << "\tand Version " << dbobject.sVector()[index+1] <<"\t-------- "; //Opening the text-based template calibration std::ostringstream tout; tout << theTemplateCalibrationLocation.c_str() << "/data/template_summary_zp" << std::setw(4) << std::setfill('0') << std::right << dbobject.sVector()[index] << ".out" << std::ends; edm::FileInPath file( tout.str()); tempfile = (file.fullPath()).c_str(); std::ifstream in_file(tempfile, std::ios::in); if(in_file.is_open()) { //Removes header in textfile from diff for(int header=0; (c=in_file.get()) != '\n'; ++header) {} //First read in from the text file -- this will be compared with index = 20 in_file >> tempnum; //Read until the end of the current text file while(!in_file.eof()) { //Calculate the difference between the text file and the db object diff = std::abs(tempnum - dbobject.sVector()[index]); //Is there a difference? if(diff > tol) { //We have the if statement to output the message only once if(!givenErrorMsg) std::cout << "does NOT match\n"; //If there is an error we want to display a message upon completion error = true; givenErrorMsg = true; //Do we want more detailed output? if(theDetailedTemplateDBErrorOutput) { std::cout << "from file = " << tempnum << "\t from dbobject = " << dbobject.sVector()[index] << "\tdiff = " << diff << "\t db index = " << index << std::endl; } } //Go to the next entries in_file >> tempnum; ++index; } //There were no errors, the two files match. if(!givenErrorMsg) std::cout << "MATCHES\n"; }//end current file in_file.close(); givenErrorMsg = false; }//end loop over all files if(error && !theDetailedTemplateDBErrorOutput) std::cout << "\nThe were differences found between the files and the database.\n" << "If you would like more detailed information please set\n" << "wantDetailedOutput = True in the cfg file. If you would like a\n" << "full output of the contents of the database file please set\n" << "wantFullOutput = True. Make sure that you pipe the output to a\n" << "log file. This could take a few minutes.\n\n"; if(theFullTemplateDBOutput) std::cout << dbobject << std::endl; } } void SiPixelTemplateDBObjectReader::endJob() { } std::ostream& operator<<(std::ostream& s, const SiPixelTemplateDBObject& dbobject){ //!-index to keep track of where we are in the object int index = 0; //!-these are modifiable parameters for the extended templates int txsize[4] = { 7,13,0,0}; int tysize[4] = {21,21,0,0}; //!-entries takes the number of entries in By,Bx,Fy,Fx from the object int entries[4] = {0}; //!-local indicies for loops int i,j,k,l,m,n,entry_it; //!-changes the size of the templates based on the version int sizeSetter=0,templateVersion=0; std::cout << "\n\nDBobject version: " << dbobject.version() << std::endl; for(m=0; m < dbobject.numOfTempl(); ++m) { //To change the size of the output based on which template version we are using" templateVersion = (int) dbobject.sVector_[index+21]; if(templateVersion<=10) { std::cout << "*****WARNING***** This code will not format this template version properly *****WARNING*****\n"; sizeSetter=0; } else if(templateVersion<=16) sizeSetter=1; else std::cout << "*****WARNING***** This code has not been tested at formatting this version *****WARNING*****\n"; std::cout << "\n\n*********************************************************************************************" << std::endl; std::cout << "*************** Reading Template ID " << dbobject.sVector_[index+20] << "\t(" << m+1 << "/" << dbobject.numOfTempl_ <<") ***************" << std::endl; std::cout << "*********************************************************************************************\n\n" << std::endl; //Header Title SiPixelTemplateDBObject::char2float temp; for (n=0; n < 20; ++n) { temp.f = dbobject.sVector_[index]; s << temp.c[0] << temp.c[1] << temp.c[2] << temp.c[3]; ++index; } entries[0] = (int) dbobject.sVector_[index+3]; // Y entries[1] = (int)(dbobject.sVector_[index+4]*dbobject.sVector_[index+5]); // X //Header s << dbobject.sVector_[index] <<"\t"<< dbobject.sVector_[index+1] <<"\t"<< dbobject.sVector_[index+2] <<"\t"<< dbobject.sVector_[index+3] <<"\t"<< dbobject.sVector_[index+4] <<"\t"<< dbobject.sVector_[index+5] <<"\t"<< dbobject.sVector_[index+6] <<"\t"<< dbobject.sVector_[index+7] <<"\t"<< dbobject.sVector_[index+8] <<"\t"<< dbobject.sVector_[index+9] <<"\t"<< dbobject.sVector_[index+10] <<"\t"<< dbobject.sVector_[index+11] <<"\t"<< dbobject.sVector_[index+12] <<"\t"<< dbobject.sVector_[index+13] <<"\t"<< dbobject.sVector_[index+14] <<"\t"<< dbobject.sVector_[index+15] <<"\t"<< dbobject.sVector_[index+16] << std::endl; index += 17; //Loop over By,Bx,Fy,Fx for(entry_it=0;entry_it<4;++entry_it) { //Run,costrk,qavg,...,clslenx for(i=0;i < entries[entry_it];++i) { s << dbobject.sVector_[index] << "\t" << dbobject.sVector_[index+1] << "\t" << dbobject.sVector_[index+2] << "\t" << dbobject.sVector_[index+3] << "\n" << dbobject.sVector_[index+4] << "\t" << dbobject.sVector_[index+5] << "\t" << dbobject.sVector_[index+6] << "\t" << dbobject.sVector_[index+7] << "\t" << dbobject.sVector_[index+8] << "\t" << dbobject.sVector_[index+9] << "\t" << dbobject.sVector_[index+10] << "\t" << dbobject.sVector_[index+11] << "\n" << dbobject.sVector_[index+12] << "\t" << dbobject.sVector_[index+13] << "\t" << dbobject.sVector_[index+14] << "\t" << dbobject.sVector_[index+15] << "\t" << dbobject.sVector_[index+16] << "\t" << dbobject.sVector_[index+17] << "\t" << dbobject.sVector_[index+18] << std::endl; index+=19; //YPar for(j=0;j<2;++j) { for(k=0;k<5;++k) { s << dbobject.sVector_[index] << "\t"; ++index; } s << std::endl; } //YTemp for(j=0;j<9;++j) { for(k=0;k<tysize[sizeSetter];++k) { s << dbobject.sVector_[index] << "\t"; ++index; } s << std::endl; } //XPar for(j=0;j<2;++j) { for(k=0;k<5;++k) { s << dbobject.sVector_[index] << "\t"; ++index; } s << std::endl; } //XTemp for(j=0;j<9;++j) { for(k=0;k<txsize[sizeSetter];++k) { s << dbobject.sVector_[index] << "\t"; ++index; } s << std::endl; } //Y average reco params for(j=0;j<4;++j) { for(k=0;k<4;++k) { s << dbobject.sVector_[index] << "\t"; ++index; } s << std::endl; } //Yflpar for(j=0;j<4;++j) { for(k=0;k<6;++k) { s << dbobject.sVector_[index] << "\t"; ++index; } s << std::endl; } //X average reco params for(j=0;j<4;++j) { for(k=0;k<4;++k) { s << dbobject.sVector_[index] << "\t"; ++index; } s << std::endl; } //Xflpar for(j=0;j<4;++j) { for(k=0;k<6;++k) { s << dbobject.sVector_[index] << "\t"; ++index; } s << std::endl; } //Chi2X,Y for(j=0;j<4;++j) { for(k=0;k<2;++k) { for(l=0;l<2;++l) { s << dbobject.sVector_[index] << "\t"; ++index; } } s << std::endl; } //Y average Chi2 params for(j=0;j<4;++j) { for(k=0;k<4;++k) { s << dbobject.sVector_[index] << "\t"; ++index; } s << std::endl; } //X average Chi2 params for(j=0;j<4;++j) { for(k=0;k<4;++k) { s << dbobject.sVector_[index] << "\t"; ++index; } s << std::endl; } //Y average reco params for CPE Generic for(j=0;j<4;++j) { for(k=0;k<4;++k) { s << dbobject.sVector_[index] << "\t"; ++index; } s << std::endl; } //X average reco params for CPE Generic for(j=0;j<4;++j) { for(k=0;k<4;++k) { s << dbobject.sVector_[index] << "\t"; ++index; } s << std::endl; } //SpareX,Y for(j=0;j<20;++j) { s << dbobject.sVector_[index] << "\t"; ++index; if(j==9 ||j==19) s << std::endl; } } } } return s; }
32.122995
175
0.580156
[ "object", "vector" ]
df29d69f0190dce2d063f2f33a7fb75481843ea7
17,622
cpp
C++
src/plugins/editing/CellMLAnnotationView/src/cellmlannotationvieweditingwidget.cpp
nickerso/opencor
63e164c6424dc855a4e46b835a777f6f84c617dc
[ "Apache-2.0" ]
null
null
null
src/plugins/editing/CellMLAnnotationView/src/cellmlannotationvieweditingwidget.cpp
nickerso/opencor
63e164c6424dc855a4e46b835a777f6f84c617dc
[ "Apache-2.0" ]
null
null
null
src/plugins/editing/CellMLAnnotationView/src/cellmlannotationvieweditingwidget.cpp
nickerso/opencor
63e164c6424dc855a4e46b835a777f6f84c617dc
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* Licensed to the OpenCOR team under one or more contributor license agreements. See the NOTICE.txt file distributed with this work for additional information regarding copyright ownership. The OpenCOR team licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *******************************************************************************/ //============================================================================== // CellML annotation view editing widget //============================================================================== #include "borderedwidget.h" #include "cellmlannotationviewcellmllistwidget.h" #include "cellmlannotationvieweditingwidget.h" #include "cellmlannotationviewmetadatanormalviewdetailswidget.h" #include "cellmlannotationviewmetadatadetailswidget.h" #include "cellmlannotationviewmetadataeditdetailswidget.h" #include "cellmlannotationviewmetadataviewdetailswidget.h" #include "cellmlannotationviewplugin.h" #include "cellmlannotationviewwidget.h" #include "cellmlfilemanager.h" #include "corecliutils.h" #include "treeviewwidget.h" //============================================================================== #include "ui_cellmlannotationvieweditingwidget.h" //============================================================================== #include <QComboBox> #include <QIODevice> #include <QLineEdit> #include <QPushButton> #include <QWebView> //============================================================================== namespace OpenCOR { namespace CellMLAnnotationView { //============================================================================== CellmlAnnotationViewEditingWidget::CellmlAnnotationViewEditingWidget(CellMLAnnotationViewPlugin *pPluginParent, const QString &pFileName, CellmlAnnotationViewWidget *pParent) : QSplitter(pParent), Core::CommonWidget(pParent), mGui(new Ui::CellmlAnnotationViewEditingWidget), mPluginParent(pPluginParent), mParent(pParent) { // Set up the GUI mGui->setupUi(this); // Retrieve some SVG diagrams Core::readTextFromFile(":/modelQualifier.svg", mModelQualifierSvg); Core::readTextFromFile(":/biologyQualifier.svg", mBiologyQualifierSvg); // Retrieve our output template Core::readTextFromFile(":/qualifierInformation.html", mQualifierInformationTemplate); // Retrieve and load, in case it's necessary, the requested CellML file mCellmlFile = CellMLSupport::CellmlFileManager::instance()->cellmlFile(pFileName); mCellmlFile->load(); // Customise our GUI which consists of two main parts: // // 1) A couple of lists (for CellML elements and metadata, resp.); and // 2) Some details (for a CellML element or metadata). // // These two main parts are widgets of ourselves and moving the splitter // will result in the splitter of other CellML files' view to be moved too // Create our two main parts mCellmlList = new CellmlAnnotationViewCellmlListWidget(this); mMetadataDetails = new CellmlAnnotationViewMetadataDetailsWidget(this); // Populate ourselves addWidget(new Core::BorderedWidget(mCellmlList, false, false, false, true)); addWidget(mMetadataDetails); // Keep track of our splitter being moved connect(this, SIGNAL(splitterMoved(int, int)), this, SLOT(emitSplitterMoved())); // A connection to let our details widget know that we want to see the // metadata details of some CellML element connect(mCellmlList, SIGNAL(metadataDetailsRequested(iface::cellml_api::CellMLElement *)), mMetadataDetails, SLOT(updateGui(iface::cellml_api::CellMLElement *))); // Make our CellML list widget our focus proxy setFocusProxy(mCellmlList); // Select the first item from our CellML list widget // Note: we need to do this after having set up the connections above since // we want our metadata details widget to get updated when the first // item from our CellML list widget gets selected... mCellmlList->treeViewWidget()->selectFirstItem(); } //============================================================================== CellmlAnnotationViewEditingWidget::~CellmlAnnotationViewEditingWidget() { // Delete the GUI delete mGui; } //============================================================================== void CellmlAnnotationViewEditingWidget::retranslateUi() { // Retranslate our lists and details widgets mCellmlList->retranslateUi(); mMetadataDetails->retranslateUi(); } //============================================================================== CellMLAnnotationViewPlugin * CellmlAnnotationViewEditingWidget::pluginParent() const { // Return our plugin parent return mPluginParent; } //============================================================================== CellmlAnnotationViewWidget * CellmlAnnotationViewEditingWidget::parent() const { // Return our parent return mParent; } //============================================================================== CellMLSupport::CellmlFile * CellmlAnnotationViewEditingWidget::cellmlFile() const { // Return the CellML file return mCellmlFile; } //============================================================================== void CellmlAnnotationViewEditingWidget::emitSplitterMoved() { // Let people know that our splitter has been moved emit splitterMoved(sizes()); } //============================================================================== CellmlAnnotationViewCellmlListWidget * CellmlAnnotationViewEditingWidget::cellmlList() const { // Return our CellML list widget return mCellmlList; } //============================================================================== CellmlAnnotationViewMetadataDetailsWidget * CellmlAnnotationViewEditingWidget::metadataDetails() const { // Return our metadata details widget return mMetadataDetails; } //============================================================================== void CellmlAnnotationViewEditingWidget::updateWebViewerWithQualifierDetails(QWebView *pWebView, const QString &pQualifier) { // The user requested a qualifier to be looked up, so generate a web page // containing some information about the qualifier // Note: ideally, there would be a way to refer to a particular qualifier // using http://biomodels.net/qualifiers/, but that would require // anchors and they don't have any, so instead we use the information // which can be found on that site and present it to the user in the // form of a web page... if (pQualifier.isEmpty()) return; // Generate the web page containing some information about the qualifier QString qualifierSvg; QString shortDescription; QString longDescription; if (!pQualifier.compare("model:is")) { qualifierSvg = mModelQualifierSvg; shortDescription = tr("Identity"); longDescription = tr("The modelling object represented by the model element is identical with the subject of the referenced resource (\"Modelling Object B\"). For instance, this qualifier might be used to link an encoded model to a database of models."); } else if (!pQualifier.compare("model:isDerivedFrom")) { qualifierSvg = mModelQualifierSvg; shortDescription = tr("Origin"); longDescription = tr("The modelling object represented by the model element is derived from the modelling object represented by the referenced resource (\"Modelling Object B\"). This relation may be used, for instance, to express a refinement or adaptation in usage for a previously described modelling component."); } else if (!pQualifier.compare("model:isDescribedBy")) { qualifierSvg = mModelQualifierSvg; shortDescription = tr("Description"); longDescription = tr("The modelling object represented by the model element is described by the subject of the referenced resource (\"Modelling Object B\"). This relation might be used to link a model or a kinetic law to the literature that describes it."); } else if (!pQualifier.compare("model:isInstanceOf")) { qualifierSvg = mModelQualifierSvg; shortDescription = tr("Class"); longDescription = tr("The modelling object represented by the model element is an instance of the subject of the referenced resource (\"Modelling Object B\"). For instance, this qualifier might be used to link a specific model with its generic form."); } else if (!pQualifier.compare("model:hasInstance")) { qualifierSvg = mModelQualifierSvg; shortDescription = tr("Instance"); longDescription = tr("The modelling object represented by the model element has for instance (is a class of) the subject of the referenced resource (\"Modelling Object B\"). For instance, this qualifier might be used to link a generic model with its specific forms."); } else if (!pQualifier.compare("bio:encodes")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Encodement"); longDescription = tr("The biological entity represented by the model element encodes, directly or transitively, the subject of the referenced resource (\"Biological Entity B\"). This relation may be used to express, for example, that a specific DNA sequence encodes a particular protein."); } else if (!pQualifier.compare("bio:hasPart")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Part"); longDescription = tr("The biological entity represented by the model element includes the subject of the referenced resource (\"Biological Entity B\"), either physically or logically. This relation might be used to link a complex to the description of its components."); } else if (!pQualifier.compare("bio:hasProperty")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Property"); longDescription = tr("The subject of the referenced resource (\"Biological Entity B\") is a property of the biological entity represented by the model element. This relation might be used when a biological entity exhibits a certain enzymatic activity or exerts a specific function."); } else if (!pQualifier.compare("bio:hasVersion")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Version"); longDescription = tr("The subject of the referenced resource (\"Biological Entity B\") is a version or an instance of the biological entity represented by the model element. This relation may be used to represent an isoform or modified form of a biological entity."); } else if (!pQualifier.compare("bio:is")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Indentity"); longDescription = tr("The biological entity represented by the model element has identity with the subject of the referenced resource (\"Biological Entity B\"). This relation might be used to link a reaction to its exact counterpart in a database, for instance."); } else if (!pQualifier.compare("bio:isDescribedBy")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Description"); longDescription = tr("The biological entity represented by the model element is described by the subject of the referenced resource (\"Biological Entity B\"). This relation should be used, for instance, to link a species or a parameter to the literature that describes the concentration of that species or the value of that parameter."); } else if (!pQualifier.compare("bio:isEncodedBy")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Encoder"); longDescription = tr("The biological entity represented by the model element is encoded, directly or transitively, by the subject of the referenced resource (\"Biological Entity B\"). This relation may be used to express, for example, that a protein is encoded by a specific DNA sequence."); } else if (!pQualifier.compare("bio:isHomologTo")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Homolog"); longDescription = tr("The biological entity represented by the model element is homologous to the subject of the referenced resource (\"Biological Entity B\"). This relation can be used to represent biological entities that share a common ancestor."); } else if (!pQualifier.compare("bio:isPartOf")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Parthood"); longDescription = tr("The biological entity represented by the model element is a physical or logical part of the subject of the referenced resource (\"Biological Entity B\"). This relation may be used to link a model component to a description of the complex in which it is a part."); } else if (!pQualifier.compare("bio:isPropertyOf")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Property bearer"); longDescription = tr("The biological entity represented by the model element is a property of the referenced resource (\"Biological Entity B\")."); } else if (!pQualifier.compare("bio:isVersionOf")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Hypernym"); longDescription = tr("The biological entity represented by the model element is a version or an instance of the subject of the referenced resource (\"Biological Entity B\"). This relation may be used to represent, for example, the 'superclass' or 'parent' form of a particular biological entity."); } else if (!pQualifier.compare("bio:occursIn")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Container"); longDescription = tr("The biological entity represented by the model element is physically limited to a location, which is the subject of the referenced resource (\"Biological Entity B\"). This relation may be used to ascribe a compartmental location, within which a reaction takes place."); } else if (!pQualifier.compare("bio:hasTaxon")) { qualifierSvg = mBiologyQualifierSvg; shortDescription = tr("Taxon"); longDescription = tr("The biological entity represented by the model element is taxonomically restricted, where the restriction is the subject of the referenced resource (\"Biological Entity B\"). This relation may be used to ascribe a species restriction to a biochemical reaction."); } else { qualifierSvg = ""; shortDescription = tr("Unknown"); longDescription = tr("Unknown"); } // Show the information pWebView->setHtml(mQualifierInformationTemplate.arg(pQualifier, qualifierSvg, shortDescription, longDescription)); } //============================================================================== void CellmlAnnotationViewEditingWidget::updateWebViewerWithResourceDetails(QWebView *pWebView, const QString &pResource) { // The user requested a resource to be looked up, so retrieve it using // identifiers.org pWebView->setUrl("http://identifiers.org/"+pResource+"/?redirect=true"); } //============================================================================== void CellmlAnnotationViewEditingWidget::updateWebViewerWithIdDetails(QWebView *pWebView, const QString &pResource, const QString &pId) { // The user requested a resource id to be looked up, so retrieve it using // identifiers.org pWebView->setUrl("http://identifiers.org/"+pResource+"/"+pId+"?profile=most_reliable&redirect=true"); } //============================================================================== void CellmlAnnotationViewEditingWidget::filePermissionsChanged() { // Let our metadata details widget know that the file has been un/locked // Note: we don't need to let our CellML list widget know about it since // anything that is related to file permissions is done on the fly (to // show a context menu)... mMetadataDetails->filePermissionsChanged(); } //============================================================================== } // namespace CellMLAnnotationView } // namespace OpenCOR //============================================================================== // End of file //==============================================================================
48.016349
346
0.632391
[ "object", "model" ]
df2d54f887124f9e05e79fedef17544fe507783e
4,744
cpp
C++
main.cpp
RidaAyed/boec
2b2c3e73b5f19fd32ce615d86738a8cedfd3d8c4
[ "BSD-3-Clause" ]
null
null
null
main.cpp
RidaAyed/boec
2b2c3e73b5f19fd32ce615d86738a8cedfd3d8c4
[ "BSD-3-Clause" ]
1
2021-09-28T15:32:09.000Z
2021-09-28T15:32:09.000Z
main.cpp
RidaAyed/boec
2b2c3e73b5f19fd32ce615d86738a8cedfd3d8c4
[ "BSD-3-Clause" ]
1
2021-09-28T13:04:40.000Z
2021-09-28T13:04:40.000Z
#include <iostream> #include <vector> #include <list> #include <fstream> #include "vendor/rapidxml/rapidxml.hpp" #include "lib/Transaction.cpp" #include "lib/Dictionary.cpp" int main(int argc, char* argv[]) { std::list<DictionaryEntry> dictionary; /** * Create the document from stdin */ std::string input_xml; std::string line; while (getline(std::cin, line)) { input_xml += line; } /** * Parse the input as XML. */ rapidxml::xml_document<> doc; std::vector<char> xml_copy(input_xml.begin(), input_xml.end()); xml_copy.push_back('\0'); doc.parse<0>(&xml_copy[0]); /** * Iterate over our XML DOM. */ rapidxml::xml_node<>* ledger = doc.first_node("ledger"); rapidxml::xml_node<>* accounts = ledger->first_node("accounts"); rapidxml::xml_node<>* transactions = ledger->first_node("transactions"); /** * Read each transaction into a Transaction struct. */ std::string outputBuffer = ""; rapidxml::xml_node<>* currentTransaction = transactions->first_node(); int transactionId = 1; while(currentTransaction != nullptr) { /** * Check the state of our transaction. For reporting, we'll only use * transactions that *have* a (or any) state. */ if (!currentTransaction->first_attribute("state")) { currentTransaction = currentTransaction->next_sibling(); continue; } auto transaction = new Transaction; transaction->id = transactionId; transaction->payee = currentTransaction->first_node("payee")->value(); transaction->date = currentTransaction->first_node("date")->value(); transaction->state = currentTransaction->first_node("date")->value(); transaction->note = currentTransaction->first_node("note") ? currentTransaction->first_node("note")->value() : ""; /** * Add the postings to the transaction. */ rapidxml::xml_node<>* currentPosting = currentTransaction->first_node("postings") ->first_node("posting"); std::string suffixCommodity = "S"; while (currentPosting != nullptr) { auto posting = new Posting; posting->accountName = currentPosting->first_node("account") ->first_node("name") ->value(); posting->amount = std::stof(currentPosting->first_node("post-amount") ->first_node("amount") ->first_node("quantity") ->value()); rapidxml::xml_node<>* currentCommodity = currentPosting->first_node("post-amount") ->first_node("amount") ->first_node("commodity"); if (currentCommodity && currentCommodity->first_attribute("flags")->value() == suffixCommodity) { posting->commodity = currentCommodity->first_node("symbol")->value(); } transaction->postings.push_back(*posting); currentPosting = currentPosting->next_sibling(); delete posting; } outputBuffer += transaction->toLatex(dictionary) + "\n"; delete transaction; currentTransaction = currentTransaction->next_sibling(); transactionId++; } std::string templatePath; for (int i = 1; i < argc; ++i) { if (std::string(argv[i]) == "--template") { if (i + 1 < argc) { templatePath = argv[i+1]; std::ifstream templateFile; templateFile.open(templatePath); if (templateFile.fail()) { std::cerr << "Sorry, the template \"" + templatePath + "\" could not be read." << std::endl; return 1; } while(!templateFile.eof()) { std::string templateLine; getline(templateFile, templateLine); if (templateLine.find("\\input{__BOEC__}") != std::string::npos) { std::cout << outputBuffer; continue; } else { std::cout << templateLine << std::endl; continue; } } return 0; } else { std::cerr << "Sorry, the --template option expects a path to a .tex file." << std::endl; return 1; } } } std::cout << outputBuffer; return 0; }
32.272109
122
0.524874
[ "vector" ]
df2dd661d670aa15a64fac365728ebbe2d3a5917
16,256
cpp
C++
Libs/Gui/src/GLOrthoCamera.cpp
n8vm/OpenVisus
dab633f6ecf13ffcf9ac2ad47d51e48902d4aaef
[ "Unlicense" ]
1
2019-04-30T12:11:24.000Z
2019-04-30T12:11:24.000Z
Libs/Gui/src/GLOrthoCamera.cpp
tjhei/OpenVisus
f0c3bf21cb0c02f303025a8efb68b8c36701a9fd
[ "Unlicense" ]
null
null
null
Libs/Gui/src/GLOrthoCamera.cpp
tjhei/OpenVisus
f0c3bf21cb0c02f303025a8efb68b8c36701a9fd
[ "Unlicense" ]
null
null
null
/*----------------------------------------------------------------------------- Copyright(c) 2010 - 2018 ViSUS L.L.C., Scientific Computing and Imaging Institute of the University of Utah ViSUS L.L.C., 50 W.Broadway, Ste. 300, 84101 - 2044 Salt Lake City, UT University of Utah, 72 S Central Campus Dr, Room 3750, 84112 Salt Lake City, UT All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met : * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. For additional information about this project contact : pascucci@acm.org For support : support@visus.net -----------------------------------------------------------------------------*/ #include <Visus/GLOrthoCamera.h> #include <Visus/LocalCoordinateSystem.h> namespace Visus { ////////////////////////////////////////////////// void GLOrthoCamera::mirror(int ref) { if (ref == 0) { auto ortho_params=getOrthoParams(); std::swap(ortho_params.left,ortho_params.right); setOrthoParams(ortho_params); return; } if (ref == 1) { auto ortho_params=getOrthoParams(); std::swap(ortho_params.top,ortho_params.bottom); setOrthoParams(ortho_params); return; } } //////////////////////////////////////////////////////////////// void GLOrthoCamera::glMousePressEvent(QMouseEvent* evt) { this->mouse.glMousePressEvent(evt); evt->accept(); last_mouse_pos[evt->button()] = Point2i(evt->x(),evt->y()); } //////////////////////////////////////////////////////////////// void GLOrthoCamera::glMouseMoveEvent(QMouseEvent* evt) { int button= (evt->buttons() & Qt::LeftButton )? Qt::LeftButton : (evt->buttons() & Qt::RightButton )? Qt::RightButton : (evt->buttons() & Qt::MiddleButton)? Qt::MiddleButton: 0; if (!button) return ; this->mouse.glMouseMoveEvent(evt); int W=getViewport().width; int H=getViewport().height; if (this->mouse.getButton(Qt::LeftButton).isDown && this->mouse.getButton(Qt::MidButton).isDown && (button==Qt::LeftButton || button==Qt::MidButton)) { //t1 and t2 are the old position, T1 and T2 are the touch position. FrustumMap map=needUnproject(); Point2d t1 = map.unprojectPoint(convertTo<Point2d>(last_mouse_pos[1])).dropZ(), T1 = map.unprojectPoint(convertTo<Point2d>(this->mouse.getButton(Qt::LeftButton).pos)).dropZ(); Point2d t2 = map.unprojectPoint(convertTo<Point2d>(last_mouse_pos[2])).dropZ(), T2 = map.unprojectPoint(convertTo<Point2d>(this->mouse.getButton(Qt::MidButton ).pos)).dropZ(); Point2d center = (t1 + t2)*0.5; //since I'm handling both buttons here, I need to "freeze" the actual situation (otherwise I will replicate the transformation twice) last_mouse_pos[1] = this->mouse.getButton(Qt::LeftButton).pos; last_mouse_pos[2] = this->mouse.getButton(Qt::MidButton).pos; /* what I want is as SCALE * TRANSLATE * ROTATE, the solution works only if I set a good center The system has 4 unknowns (a b tx ty) and 4 equations [t1-center]:=[x1 y1] [t2-center]:=[x2 y2] [T1-center]:=[x3 y3] [T2-center]:=[x4 y4] [ a b tx] [x1] = [x3] [-b a ty] [y1] = [y3] [ 0 0 1] [ 1] = [ 1] [ a b tx] [x2] = [x4] [-b a ty] [y2] = [y4] [ 0 0 1] [ 1] = [1 ] */ double x1 = t1.x-center.x, y1=t1.y-center.y, x2=t2.x-center.x, y2=t2.y-center.y; double x3 = T1.x-center.x, y3=T1.y-center.y, x4=T2.x-center.x, y4=T2.y-center.y; double D = ((y1-y2)*(y1-y2) + (x1-x2)*(x1-x2)); double a = ((y1-y2)*(y3-y4) + (x1-x2)*(x3-x4))/D; double b = ((y1-y2)*(x3-x4) - (x1-x2)*(y3-y4))/D; double tx = (x3-a*x1-b*y1); double ty = (y3+b*x1-a*y1); //invalid if (D == 0 || a == 0 || !Utils::isValidNumber(a ) || !Utils::isValidNumber(b ) || !Utils::isValidNumber(tx) || !Utils::isValidNumber(ty)) { evt->accept(); return; } double vs = 1.0/sqrt(a*a + b*b); beginUpdate(); { scale(vs, center); translate(-Point2d(tx, ty)); rotate(-atan2(b, a)); } endUpdate(); evt->accept(); return; } else if (this->mouse.getButton(Qt::LeftButton).isDown && button==Qt::LeftButton) { FrustumMap map=needUnproject(); Point2i p1 = last_mouse_pos[button]; Point2i p2 = this->mouse.getButton(button).pos; last_mouse_pos[button] = p2; Point2d t1 = map.unprojectPoint(convertTo<Point2d>(p1)).dropZ(); Point2d T1 = map.unprojectPoint(convertTo<Point2d>(p2)).dropZ(); beginUpdate(); { translate(t1 - T1); } endUpdate(); evt->accept(); return; } } //////////////////////////////////////////////////////////////// void GLOrthoCamera::glMouseReleaseEvent(QMouseEvent* evt) { this->mouse.glMouseReleaseEvent(evt); evt->accept(); last_mouse_pos[evt->button()] = Point2i(evt->x(),evt->y()); } //////////////////////////////////////////////////////////////// void GLOrthoCamera::glWheelEvent(QWheelEvent* evt) { FrustumMap map=needUnproject(); Point2d center = map.unprojectPoint(Point2d(evt->x(),evt->y())).dropZ(); double vs = evt->delta()>0 ? (1.0 / default_scale) : (default_scale); scale(vs,center); evt->accept(); } //////////////////////////////////////////////////////////////// void GLOrthoCamera::glKeyPressEvent(QKeyEvent* evt) { int key=evt->key(); if (key == Qt::Key_Left || key == Qt::Key_Right || key == Qt::Key_Up || key == Qt::Key_Down) { auto ortho_params=getOrthoParams(); double dx=0,dy=0; if (key==Qt::Key_Left ) dx=-ortho_params.getWidth(); if (key==Qt::Key_Right) dx=+ortho_params.getWidth(); if (key==Qt::Key_Up ) dy=+ortho_params.getHeight(); if (key==Qt::Key_Down ) dy=-ortho_params.getHeight(); translate(Point2d(dx,dy)); evt->accept(); return; } if (key==Qt::Key_Minus || key==Qt::Key_Plus) { double vs=key=='+'? 1.0/default_scale : default_scale; auto ortho_params=getOrthoParams(); auto center=ortho_params.getCenter().dropZ(); scale(vs,center); evt->accept(); return; } if (key==Qt::Key_M) { beginUpdate(); smooth=smooth? 0 : 0.90; endUpdate(); evt->accept(); return; } } //////////////////////////////////////////////////////////////// bool GLOrthoCamera::guessPosition(Position position,int ref) { Point3d C,X,Y,Z; Box3d bound; if (position.getTransformation().isIdentity()) { C=Point3d(0,0,0); X=Point3d(1,0,0); Y=Point3d(0,1,0); Z=Point3d(0,0,1); bound=position.getBox(); } else { LocalCoordinateSystem lcs(position); C=lcs.getCenter(); X=lcs.getAxis(0); Y=lcs.getAxis(1); Z=lcs.getAxis(2); bound.p2.x=X.module(); X=X.normalized(); bound.p2.y=Y.module(); Y=Y.normalized(); bound.p2.z=Z.module(); Z=Z.normalized(); bound.p1=-1*bound.p2; if (X[X.abs().biggest()]<0) X*=-1; if (Y[Y.abs().biggest()]<0) Y*=-1; if (Z[Z.abs().biggest()]<0) Z*=-1; } int W = getViewport().width ; if (!W) W=800; int H = getViewport().height; if (!H) H=800; if (ref==0 || (ref<0 && bound.p1.x==bound.p2.x && bound.p1.y!=bound.p2.y && bound.p1.z!=bound.p2.z)) { beginUpdate(); this->pos=+C; this->dir=-X; this->vup=+Z; this->rotation_angle = 0.0; double Xnear =-bound.p1.x,Xfar =-bound.p2.x; if (Xnear==Xfar) {Xnear+=1;Xfar-=1;} GLOrthoParams ortho_params = GLOrthoParams(bound.p1.y,bound.p2.y,bound.p1.z,bound.p2.z,Xnear,Xfar); ortho_params.fixAspectRatio((double)W/(double)H); setOrthoParams(ortho_params); endUpdate(); } else if (ref==1 || (ref<0 && bound.p1.x!=bound.p2.x && bound.p1.y==bound.p2.y && bound.p1.z!=bound.p2.z)) { beginUpdate(); this->pos=+C; this->dir=+Y; this->vup=+Z; this->rotation_angle = 0.0; double Ynear =+bound.p1.y,Yfar =+bound.p2.y; if (Ynear==Yfar) {Ynear-=1;Yfar+=1;} GLOrthoParams ortho_params(bound.p1.x,bound.p2.x,bound.p1.z,bound.p2.z,Ynear,Yfar); ortho_params.fixAspectRatio((double)W/(double)H); setOrthoParams(ortho_params); endUpdate(); } else { VisusAssert(ref<0 || ref==2); beginUpdate(); this->pos=+C; this->dir=-Z; this->vup=+Y; this->rotation_angle = 0.0; double Znear =-bound.p1.z,Zfar =-bound.p2.z; if (Znear==Zfar) {Znear+=1;Zfar-=1;} GLOrthoParams ortho_params(bound.p1.x,bound.p2.x,bound.p1.y,bound.p2.y,Znear,Zfar); ortho_params.fixAspectRatio((double)W/(double)H); setOrthoParams(ortho_params); endUpdate(); } return true; } ////////////////////////////////////////////////// void GLOrthoCamera::setOrthoParams(GLOrthoParams value) { VisusAssert(VisusHasMessageLock()); timer.stop(); if (getOrthoParams()==value) return; beginUpdate(); this->ortho_params = value; this->ortho_params_final = value; endUpdate(); } ////////////////////////////////////////////////// void GLOrthoCamera::setViewport(Viewport new_viewport) { auto old_viewport=this->viewport; if (old_viewport==new_viewport) return; auto ortho_params=getOrthoParams(); ortho_params.fixAspectRatio(old_viewport, new_viewport); beginUpdate(); this->viewport=new_viewport; setOrthoParams(ortho_params); endUpdate(); } //////////////////////////////////////////////////////////////// Frustum GLOrthoCamera::getFrustum(GLOrthoParams ortho_params) const { Frustum ret; ret.loadProjection(ortho_params.getProjectionMatrix(true)); ret.multProjection(Matrix::rotateAroundCenter(ortho_params.getCenter(),Point3d(0,0,1),rotation_angle)); ret.loadModelview(Matrix::lookAt(pos,pos+dir,vup)); ret.setViewport(this->viewport); return ret; } //////////////////////////////////////////////////////////////// void GLOrthoCamera::refineToFinal() { VisusAssert(VisusHasMessageLock()); if (smooth>0 && !timer.isActive()) timer.start(); GLOrthoParams ortho_params; ortho_params.left = (smooth) * this->ortho_params.left + (1-smooth) * this->ortho_params_final.left; ortho_params.right = (smooth) * this->ortho_params.right + (1-smooth) * this->ortho_params_final.right; ortho_params.bottom = (smooth) * this->ortho_params.bottom + (1-smooth) * this->ortho_params_final.bottom; ortho_params.top = (smooth) * this->ortho_params.top + (1-smooth) * this->ortho_params_final.top; ortho_params.zNear = (smooth) * this->ortho_params.zNear + (1-smooth) * this->ortho_params_final.zNear; ortho_params.zFar = (smooth) * this->ortho_params.zFar + (1-smooth) * this->ortho_params_final.zFar; if (ortho_params==this->ortho_params || ortho_params==this->ortho_params_final) { ortho_params=this->ortho_params_final; timer.stop(); } //limit the zoom to actual pixels visible if ((max_zoom>0 || min_zoom>0) && getViewport().valid()) { Point2d pixel_per_sample( (double)getViewport().width /ortho_params.getWidth (), (double)getViewport().height/ortho_params.getHeight()); if (max_zoom>0 && std::max(pixel_per_sample.x,pixel_per_sample.y) > max_zoom) { timer.stop(); return; } if (min_zoom>0 && std::min(pixel_per_sample.x,pixel_per_sample.y) < min_zoom) { timer.stop(); return; } } beginUpdate(); this->ortho_params=ortho_params; endUpdate(); } //////////////////////////////////////////////////////////////// void GLOrthoCamera::translate(Point2d vt) { if (!vt.x && !vt.y) return; this->ortho_params_final.translate(Point3d(vt)); refineToFinal(); } //////////////////////////////////////////////////////////////// void GLOrthoCamera::rotate(double quantity) { if (!quantity) return; beginUpdate(); this->rotation_angle += bDisableRotation ? 0.0 : quantity; endUpdate(); } //////////////////////////////////////////////////////////////// void GLOrthoCamera::scale(double vs,Point2d center) { if (vs==1 || vs==0) return; this->ortho_params_final.scaleAroundCenter(Point3d(vs,vs,1.0),Point3d(center)); refineToFinal(); } //////////////////////////////////////////////////////////////// void GLOrthoCamera::writeToObjectStream(ObjectStream& ostream) { GLCamera::writeToObjectStream(ostream); ostream.write("default_scale",cstring(default_scale)); ostream.write("disable_rotation",cstring(bDisableRotation)); ostream.write("rotation_angle", cstring(rotation_angle)); ostream.write("max_zoom",cstring(max_zoom)); ostream.write("min_zoom",cstring(min_zoom)); ostream.write("smooth",cstring(smooth)); ostream.write("pos",pos.toString()); ostream.write("dir",dir.toString()); ostream.write("vup",vup.toString()); ostream.pushContext("ortho_params"); ortho_params.writeToObjectStream(ostream); ostream.popContext("ortho_params"); } //////////////////////////////////////////////////////////////// void GLOrthoCamera::readFromObjectStream(ObjectStream& istream) { GLCamera::readFromObjectStream(istream); pos=Point3d(istream.read("pos","0 0 0")); dir=Point3d(istream.read("dir","0 0 -1")); vup=Point3d(istream.read("vup","0 1 0")); default_scale=cdouble(istream.read("default_scale")); bDisableRotation=cbool(istream.read("disable_rotation")); rotation_angle=cdouble(istream.read("rotation_angle")); max_zoom=cdouble(istream.read("max_zoom")); min_zoom=cdouble(istream.read("min_zoom")); smooth=cdouble(istream.read("smooth")); istream.pushContext("ortho_params"); { GLOrthoParams value; value.readFromObjectStream(istream); this->ortho_params = value; this->ortho_params_final = value; } istream.popContext("ortho_params"); } //////////////////////////////////////////////////////////////// void GLOrthoCamera::writeToSceneObjectStream(ObjectStream& ostream) { ostream.writeInline("type", "ortho"); // TODO generalize keyframes interpolation ostream.pushContext("keyframes"); ostream.writeInline("interpolation", "linear"); // TODO Loop through the keyframes set on this Object ostream.pushContext("keyframe"); ostream.writeInline("time", "0"); // write camera data ostream.write("pos",pos.toString()); ostream.write("dir",dir.toString()); ostream.write("vup",vup.toString()); ostream.pushContext("ortho_params"); ortho_params.writeToObjectStream(ostream); ostream.popContext("ortho_params"); ostream.popContext("keyframe"); // end keyframes loop ostream.popContext("keyframes"); } //////////////////////////////////////////////////////////////// void GLOrthoCamera::readFromSceneObjectStream(ObjectStream& istream) { pos=Point3d(istream.read("pos","0 0 0")); dir=Point3d(istream.read("dir","0 0 -1")); vup=Point3d(istream.read("vup","0 1 0")); rotation_angle=cdouble(istream.read("rotation_angle")); istream.pushContext("ortho_params"); { GLOrthoParams value; value.readFromObjectStream(istream); this->ortho_params = value; this->ortho_params_final = value; } istream.popContext("ortho_params"); } } //namespace
30.499062
179
0.62174
[ "object" ]
df35ad636182c350779083ce3cbc2208f28365e2
24,539
cpp
C++
Glitter/Sources/main.cpp
chenshaoyu1995/InstantReality
2aa68cdab7fe3450fda639419afa109249066de1
[ "MIT" ]
5
2022-02-20T08:26:25.000Z
2022-03-13T02:44:50.000Z
Glitter/Sources/main.cpp
chenshaoyu1995/InstantReality
2aa68cdab7fe3450fda639419afa109249066de1
[ "MIT" ]
null
null
null
Glitter/Sources/main.cpp
chenshaoyu1995/InstantReality
2aa68cdab7fe3450fda639419afa109249066de1
[ "MIT" ]
1
2022-03-13T02:58:19.000Z
2022-03-13T02:58:19.000Z
// Local Headers #include "glitter.hpp" #include "mesh.hpp" #include "shader.hpp" #include "utility.hpp" #include "vr.h" // System Headers #include <glad/glad.h> #include <GLFW/glfw3.h> #include <Eigen/Dense> #include <ppl.h> #include <ppltasks.h> #include <glm/gtx/string_cast.hpp> // Standard Headers #include <cstdio> #include <cstdlib> #include <memory> #include <algorithm> #include <vector> #include <queue> #include <random> #include <atomic> #include <zmq.hpp> #define STB_IMAGE_WRITE_IMPLEMENTATION #include <stb_image_write.h> #include <filesystem> using namespace Mirage; using namespace Eigen; using namespace concurrency; typedef Array<float, Dynamic, Dynamic, RowMajor> Array_t; typedef Array<unsigned char, Dynamic, Dynamic, RowMajor> Array_ub; typedef Array<unsigned int, Dynamic, Dynamic, RowMajor> Array_ui; typedef Array<std::complex<float>, Dynamic, Dynamic, RowMajor> Array_complex; typedef std::tuple<float, int, int> queue_t; // (weight, index, LOD) typedef std::tuple<size_t, size_t, size_t, size_t> edge_t; // (tri_id1, tri_idx1, tri_id2, tri_idx2) of an edge const float LOD2TESLEVEL[3] = { 1,4,32 }; const int NUMLOD = 2; const int BUDGET = 5000; const int LODCOST[2] = { 16,168 }; const float LAMBDA = 3.0f; const float ECCOFFSET = 2.0f; const float FOV = 110.0f; const float PI = 3.1415926f; const bool enableVR = true; class application { public: ~application() { if constexpr (enableVR) vr.Shutdown(); } void Init(GLFWwindow* window) { glPatchParameteri(GL_PATCH_VERTICES, 3); glEnable(GL_DEPTH_TEST); glPixelStorei(GL_PACK_ALIGNMENT, 1); // Setup OpenGL context mWindow = window; glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); glfwWindowHint(GLFW_CONTEXT_RELEASE_BEHAVIOR, GLFW_RELEASE_BEHAVIOR_NONE); mBGWindow = glfwCreateWindow(1, 1, "", NULL, mWindow); create_task([&] { glfwMakeContextCurrent(mBGWindow); glGenFramebuffers(1, &mBGFBO); glPixelStorei(GL_PACK_ALIGNMENT, 1); glfwMakeContextCurrent(NULL); }); // Setup background mSkyShader.attach("background.vert").attach("background.frag").link(); mSkybox = std::shared_ptr<Mesh>(new TexMesh("viking/viking-rotated.obj")); // Setup mesh mShader.attach("tessellation.vert").attach("tessellation.tcs").attach("tessellation.tes").attach("tessellation.frag").link().activate().bind("showGaze", 0); mObject = std::shared_ptr<Mesh>(new TessellationMesh("cman/cman.obj")); mShader.bind("displacementCof", 0.0f).bind("hasNormalMap", 0).bind("worldLightDir", glm::vec3({ 0.0, 1.0, 2.0 })).bind("diffuseOffset", 0.2f).bind("specularCoeff", 0.2f); std::dynamic_pointer_cast<TessellationMesh>(mObject)->mShader = &mShader; NUMFACES = mObject->getObjectNum(); // Setup framebuffers if constexpr (enableVR) { if (!vr.Init()) printf("Failed to initialize VR\n"); vr.setRenderTargetSize(&mWidth, &mHeight); mWidth = 1200; mHeight = 1344; InitFrameBuffer(m_leftFbo, m_leftFboTex, 3, mWidth * 2, mHeight * 2); InitFrameBuffer(m_rightFbo, m_rightFboTex, 3, mWidth * 2, mHeight * 2); } InitFrameBuffer(mFBO, mFBOTex, 3, mWidth * 2, mHeight * 2); InitFrameBuffer(mResizeFBO, mResizeFBOTex, 3, mWidth, mHeight); for (int i = 0; i < NUMLOD + 1; ++i) InitFrameBuffer(mPopFBO[i], mPopFBOTex[i], 3, mWidth, mHeight); // Setup members for popping calculation InitPoppingCaculation(); // Setup variables for tessellation; mFaceLOD = std::vector<int>(NUMFACES, 0); mFaceTesLevel = std::vector<float>(3 * NUMFACES, LOD2TESLEVEL[0]); mEdgeTesLevel = std::vector<float>(3 * NUMFACES, LOD2TESLEVEL[0]); glGenBuffers(1, &mFaceTesBuffer); glBindBuffer(GL_ARRAY_BUFFER, mFaceTesBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(int) * NUMFACES * 3, mFaceTesLevel.data(), GL_DYNAMIC_DRAW); glGenBuffers(1, &mEdgeTesBuffer); glBindBuffer(GL_ARRAY_BUFFER, mEdgeTesBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(int) * NUMFACES * 3, mEdgeTesLevel.data(), GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); std::dynamic_pointer_cast<TessellationMesh>(mObject->mSubMeshes[0])->SetupTesBuffer(mFaceTesBuffer, mEdgeTesBuffer); mEdgePair = CalculateEdgePair(mObject->mSubMeshes[0]->mIndices, mObject->mSubMeshes[0]->mVertices.size()); } void Render() { if constexpr (enableVR) { mSystemTimestamp = glfwGetTime(); auto viewMatrix = glm::lookAt(mEye, mLookAt, mUp); // Update pose and gaze auto oldGaze = mGaze; auto oldTimestamp = mTimestamp; bool updated = vr.getGaze(mGaze, mTimestamp); if (updated) { auto timeDiff = mTimestamp - oldTimestamp; auto gazeSpeed = acos(glm::dot(mGaze, oldGaze)) / PI * 180.0 / timeDiff; if (gazeSpeed > 180.0) mIsSaccade = true; else if (mIsSaccade) mIsSaccade = false; } glm::mat4 HMDPose; bool poseUpdated = vr.getMatrixPoseHead(HMDPose); if (poseUpdated) mViewMatrix = HMDPose * viewMatrix; glViewport(0, 0, mWidth * 2, mHeight * 2); // Render left eye mViewProjectionMatrix = vr.getProjectionMatrix(vr::Eye_Left) * vr.getMatrixPoseEye(vr::Eye_Left) * mViewMatrix; glBindFramebuffer(GL_FRAMEBUFFER, m_leftFbo); RenderImage(); // Render right eye mViewProjectionMatrix = vr.getProjectionMatrix(vr::Eye_Right) * vr.getMatrixPoseEye(vr::Eye_Right) * mViewMatrix; glBindFramebuffer(GL_FRAMEBUFFER, m_rightFbo); RenderImage(); // Submit to headset vr.submitFrame(m_leftFboTex[0], m_rightFboTex[0]); glBindFramebuffer(GL_FRAMEBUFFER, 0); } else { // Update gaze and VPmatrix mGaze = MouseToGaze(); auto viewMatrix = glm::lookAt(mEye, mLookAt, mUp); auto projMatrix = glm::perspective(FOV / 180.0f * 3.14159f, (float)mWidth / mHeight, 0.1f, 50000.0f); mViewMatrix = viewMatrix; mViewProjectionMatrix = projMatrix * mViewMatrix; // Rendering glViewport(0, 0, mWidth * 2, mHeight * 2); glBindFramebuffer(GL_FRAMEBUFFER, mFBO); RenderImage(); glBindFramebuffer(GL_FRAMEBUFFER, 0); } // Copy render result to screen RenderToScreen(); if (flag && !mBGWorking && !mBGUpdate) { CalculatePopping(mIsSaccade); } else if (mBGUpdate) { mFaceLOD = std::move(mNewLOD); // Update tessellation level mFaceTesLevel = std::move(mNewFaceTesLevel); glBindBuffer(GL_ARRAY_BUFFER, mFaceTesBuffer); glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(int) * NUMFACES * 3, mFaceTesLevel.data()); mEdgeTesLevel = std::move(mNewEdgeTesLevel); glBindBuffer(GL_ARRAY_BUFFER, mEdgeTesBuffer); glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(int) * NUMFACES * 3, mEdgeTesLevel.data()); mBGUpdate = false; } } void RenderImage() { glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); mSkyShader.activate().bind("gaze", mGaze).bind("view", mViewMatrix).bind("viewProjection", mViewProjectionMatrix); mSkybox->draw(mSkyShader.get()); glCheckError(); mShader.activate().bind("gaze", mGaze).bind("view", mViewMatrix).bind("viewProjection", mViewProjectionMatrix); mObject->draw(mShader.get()); glCheckError(); } void RenderToScreen() { if constexpr (enableVR) glBindFramebuffer(GL_READ_FRAMEBUFFER, m_rightFbo); else glBindFramebuffer(GL_READ_FRAMEBUFFER, mFBO); glReadBuffer(GL_COLOR_ATTACHMENT0); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); glBlitFramebuffer(0, 0, mWidth * 2, mHeight * 2, 0, 0, windowWidth, windowHeight, GL_COLOR_BUFFER_BIT, GL_LINEAR); } void KeyCallBack(int key, int scancode, int action, int mods) { if (action == GLFW_PRESS) { switch (key) { case GLFW_KEY_Q: flag = true; break; default: break; } } } void CalculatePopping(bool isSaccade = false) { mBGWorking = true; auto t = glfwGetTime(); // Render for each possible LOD for (int i = 1; i <= 1 + NUMLOD; ++i) { mObject->setUnifromLOD((float)LOD2TESLEVEL[i - 1]); glBindFramebuffer(GL_FRAMEBUFFER, mPopFBO[i - 1]); glViewport(0, 0, mWidth, mHeight); RenderImage(); } mObject->setUnifromLOD(0); // Readback user's view if constexpr (enableVR) glBindFramebuffer(GL_READ_FRAMEBUFFER, m_rightFbo); else glBindFramebuffer(GL_READ_FRAMEBUFFER, mFBO); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, mResizeFBO); glReadBuffer(GL_COLOR_ATTACHMENT1); glDrawBuffer(GL_COLOR_ATTACHMENT1); glBlitFramebuffer(0, 0, mWidth * 2, mHeight * 2, 0, 0, mWidth, mHeight, GL_COLOR_BUFFER_BIT, GL_NEAREST); glReadBuffer(GL_COLOR_ATTACHMENT2); glDrawBuffer(GL_COLOR_ATTACHMENT2); glBlitFramebuffer(0, 0, mWidth * 2, mHeight * 2, 0, 0, mWidth, mHeight, GL_COLOR_BUFFER_BIT, GL_NEAREST); glBindFramebuffer(GL_READ_FRAMEBUFFER, mResizeFBO); glReadBuffer(GL_COLOR_ATTACHMENT1); glReadPixels(0, 0, mWidth, mHeight, GL_RED, GL_UNSIGNED_BYTE, mCurrId0.data()); glReadPixels(0, 0, mWidth, mHeight, GL_GREEN, GL_UNSIGNED_BYTE, mCurrId1.data()); glReadBuffer(GL_COLOR_ATTACHMENT2); glReadPixels(0, 0, mWidth, mHeight, GL_RED, GL_FLOAT, mCurrEcc.data()); glBindFramebuffer(GL_FRAMEBUFFER, 0); create_task([this, isSaccade, t] { glfwMakeContextCurrent(mBGWindow); // Readback for each possible LOD glBindFramebuffer(GL_FRAMEBUFFER, mBGFBO); for (int i = 0; i < 1 + NUMLOD; ++i) { glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, mPopFBOTex[i][1], 0); glReadBuffer(GL_COLOR_ATTACHMENT0); glReadPixels(0, 0, mWidth, mHeight, GL_BLUE, GL_UNSIGNED_BYTE, mImage[i].data()); } glBindFramebuffer(GL_FRAMEBUFFER, 0); // Ecc importance for user's view mCurrId = mCurrId0.cast<unsigned int>() + mCurrId1.cast<unsigned int>() * 256; mTriEcc = 0; for (size_t i = 0; i < mHeight; ++i) { for (size_t j = 0; j < mWidth; ++j) { mTriEcc[mCurrId(i, j)] += mCurrEcc(i, j) + ECCOFFSET; } } mTriEcc[0] = 0; FFTCalculation(isSaccade); // Initialize heap std::vector<queue_t> container; for (int idx = 0; idx < NUMFACES; ++idx) { int lod = mFaceLOD[idx]; if (lod < NUMLOD && mTriEcc[idx] != 0) container.emplace_back(GetWeight(idx, lod, isSaccade), idx, lod + 1); } if (container.empty()) { flag = false; mBGWorking = false; glfwMakeContextCurrent(NULL); return; } std::priority_queue<queue_t> heap(std::less<queue_t>(), std::move(container)); mNewLOD = mFaceLOD; // Update LOD using heap int budget = BUDGET; while (!heap.empty()) { auto [w, idx, lod] = heap.top(); heap.pop(); if (budget < LODCOST[lod - 1])continue; budget -= LODCOST[lod - 1]; mNewLOD[idx] = lod; if (lod < NUMLOD) heap.emplace(GetWeight(idx, lod, isSaccade), idx, lod + 1); } TessellationEdgeHandler(); std::cout << glfwGetTime() - t << std::endl; mBGUpdate = true; mBGWorking = false; glfwMakeContextCurrent(NULL); }); } float GetWeight(int idx, int lod, bool isSaccade) const { if (!isSaccade) return (mTriEcc[idx] - LAMBDA * mTriPopping[lod][idx]) / LODCOST[lod]; else return mTriPopping[lod][idx] / LODCOST[lod]; } void TessellationEdgeHandler() { // Handle edge consistency std::vector<int> newEdgeLOD(3 * NUMFACES); for (size_t i = 0; i < mNewLOD.size(); ++i) { newEdgeLOD[3 * i] = mNewLOD[i]; newEdgeLOD[3 * i + 1] = mNewLOD[i]; newEdgeLOD[3 * i + 2] = mNewLOD[i]; } for (auto& edge : mEdgePair) { auto [t1, i1, t2, i2] = edge; auto maxLOD = std::max(mNewLOD[t1], mNewLOD[t2]); newEdgeLOD[3 * t1 + i1] = maxLOD; newEdgeLOD[3 * t2 + i2] = maxLOD; } // Map LOD to tessellation level mNewFaceTesLevel = std::vector<float>(3 * NUMFACES); mNewEdgeTesLevel = std::vector<float>(3 * NUMFACES); for (size_t i = 0; i < NUMFACES; ++i) { auto faceTesLevel = LOD2TESLEVEL[mNewLOD[i]]; mNewFaceTesLevel[3 * i] = faceTesLevel; mNewFaceTesLevel[3 * i + 1] = faceTesLevel; mNewFaceTesLevel[3 * i + 2] = faceTesLevel; mNewEdgeTesLevel[3 * i] = LOD2TESLEVEL[newEdgeLOD[3 * i]]; mNewEdgeTesLevel[3 * i + 1] = LOD2TESLEVEL[newEdgeLOD[3 * i + 1]]; mNewEdgeTesLevel[3 * i + 2] = LOD2TESLEVEL[newEdgeLOD[3 * i + 2]]; } } void InitPoppingCaculation() { // Pre-allocate memory mCurrId = Array_ui(mHeight, mWidth); mCurrId0 = Array_ub(mHeight, mWidth); mCurrId1 = Array_ub(mHeight, mWidth); mCurrEcc = Array_t(mHeight, mWidth); mTriEcc = ArrayXf(NUMFACES); mTriPopping = std::vector<ArrayXf>(NUMLOD, ArrayXf(NUMFACES)); mTriPoppingNomask = std::vector<ArrayXf>(NUMLOD, ArrayXf(NUMFACES)); InitFFT(); } std::vector<edge_t> CalculateEdgePair(const std::vector<GLuint>& indices, size_t numVert) { auto hashPair = [](const std::pair<size_t, size_t>& p) { return p.first ^ p.second; }; auto compPair = [](const std::pair<size_t, size_t>& p1, const std::pair<size_t, size_t>& p2) { return p1.first == p2.first && p1.second == p2.second; }; std::unordered_map<std::pair<size_t, size_t>, std::vector<size_t>, decltype(hashPair), decltype(compPair)> edgeMap(16, hashPair, compPair); // Edge -> Triangle // Calculate all edge -> triangle std::vector<size_t> v(3); for (size_t i = 0; i < indices.size() / 3; ++i) { v[0] = indices[3 * i]; v[1] = indices[3 * i + 1]; v[2] = indices[3 * i + 2]; std::sort(v.begin(), v.end()); edgeMap[std::make_pair(v[0], v[1])].push_back(i); edgeMap[std::make_pair(v[0], v[2])].push_back(i); edgeMap[std::make_pair(v[1], v[2])].push_back(i); } // Match triangles pair sharing edge std::vector<edge_t> edgePair; for (auto it = edgeMap.begin(); it != edgeMap.end(); ++it) { auto& k = it->first; auto& v = it->second; if (v.size() <= 1) continue; auto [v1, v2] = k; size_t pos1, pos2, t1 = v[0], t2 = v[1]; for (size_t i = 0; i < 3; ++i) { if (indices[3 * t1 + i] != v1 && indices[3 * t1 + i] != v2) { pos1 = i; break; } } for (size_t i = 0; i < 3; ++i) { if (indices[3 * t2 + i] != v1 && indices[3 * t2 + i] != v2) { pos2 = i; break; } } edgePair.emplace_back(t1, pos1, t2, pos2); } return edgePair; } void FFTCalculation(bool isSaccade) { // ID and FFT parallel_for(0, NUMLOD + 1, [&](int l) { mIn[l] = mImage[l].cast<float>(); fftwf_execute(mPlan[l]); }); // Bandpass parallel_for(0, (NUMLOD + 1) * (int)mFreq.size(), [&](int i) { auto lod = i / mFreq.size(); auto freqIdx = i % mFreq.size(); mRIn[i] = mOut[lod] * mAFFilter[freqIdx]; fftwf_execute(mRPlan[i]); mContrastIm[i] = mROut[i] / (mWidth * mHeight); mRIn[i] = mOut[lod] * mLFFilter[freqIdx]; fftwf_execute(mRPlan[i]); mContrastIm[i] = mContrastIm[i] / (mROut[i] / (mWidth * mHeight)).max(0.1f) * mFreqSensitivity[freqIdx]; if (!isSaccade)mContrastIm[i] = (mCurrEcc < (mFreq[freqIdx] / FOV)).select(0, mContrastIm[i]); }); // Popping parallel_for(0, NUMLOD, [&](int l) { mPopping[l] = 0; for (int i = 0; i < mFreq.size(); ++i) { auto& m1 = mContrastIm[i + l * mFreq.size()]; auto& m2 = mContrastIm[i + (l + 1) * mFreq.size()]; mPopping[l] += abs(m1 - m2) / (abs(m1) + 10); } }); // Assign to triangle by ID parallel_for(0, NUMLOD, [&](int l) { auto& triPopping = mTriPopping[l]; triPopping = 0; for (size_t i = 0; i < mHeight; ++i) { for (size_t j = 0; j < mWidth; ++j) { triPopping[mCurrId(i, j)] += mPopping[l](i, j); } } triPopping[0] = 0; }); } Array_t GenerateAF(float F) { auto norX = (float)mWidth / mHeight; auto norY = (float)mHeight / mHeight; Array<float, 1, Dynamic> x = Array<float, 1, Dynamic>::LinSpaced(mWidth / 2 + 1, 0, norX).square(); Array<float, Dynamic, 1> y(mHeight); y.head(mHeight / 2 + 1) = Array<float, 1, Dynamic>::LinSpaced(mHeight / 2 + 1, 0, norY); y.tail(mHeight / 2) = Array<float, 1, Dynamic>::LinSpaced(mHeight / 2 + 1, norY, 0).head(mHeight / 2); y = y.square(); auto meshgrid = (x.replicate(mHeight, 1) + y.replicate(1, mWidth / 2 + 1)).sqrt(); Array_t filter = exp(-(meshgrid - F).square() / (2 * 0.3 * F * 0.3 * F)); return filter; } Array_t GenerateLF(float F) { auto norX = (float)mWidth / mHeight; auto norY = (float)mHeight / mHeight; Array<float, 1, Dynamic> x = Array<float, 1, Dynamic>::LinSpaced(mWidth / 2 + 1, 0, norX).square(); Array<float, Dynamic, 1> y(mHeight); y.head(mHeight / 2 + 1) = Array<float, 1, Dynamic>::LinSpaced(mHeight / 2 + 1, 0, norY); y.tail(mHeight / 2) = Array<float, 1, Dynamic>::LinSpaced(mHeight / 2 + 1, norY, 0).head(mHeight / 2); y = y.square(); auto meshgrid = (x.replicate(mHeight, 1) + y.replicate(1, mWidth / 2 + 1)).sqrt(); Array_t filter = exp(-meshgrid.square() / (2 * 0.3 * F * 0.3 * F)); return filter; } void InitFFT() { // Pre-compute frequency and sensitivity const float L = 100.0; const float X = 10.0; const float b = 0.3 * pow(1 + 100 / L, 0.15); const float c = 0.06; auto s = [=](ArrayXf u) -> ArrayXf { float a = 540.0 * pow(1 + 0.7 / L, -0.2); auto aArray = a / (1 + 12 / (X * (1 + u / 3))); return aArray * u * exp(-b * u) * sqrt(1 + c * exp(b * u)); }; mFreq = Array<float, 9, 1>({ 1,2,4,8,16,32,64,128,256 }); mFreqSensitivity = s(mFreq / FOV); for (int i = 0; i < mFreq.size(); ++i) { mAFFilter.push_back(GenerateAF(mFreq[i] / (mHeight / 2))); mLFFilter.push_back(GenerateLF(mFreq[i] / (mHeight / 2))); } mImage = std::vector<Array_ub>(NUMLOD + 1, Array_ub(mHeight, mWidth)); mPopping = std::vector<Array_t>(NUMLOD, Array_t(mHeight, mWidth)); mPoppingNomask = std::vector<Array_t>(NUMLOD, Array_t(mHeight, mWidth)); mIn = std::vector<Array_t>(NUMLOD + 1, Array_t(mHeight, mWidth)); mOut = std::vector<Array_complex>(NUMLOD + 1, Array_complex(mHeight, mWidth / 2 + 1)); mPlan = std::vector<fftwf_plan>(NUMLOD + 1); for (int i = 0; i < NUMLOD + 1; ++i) mPlan[i] = fftwf_plan_dft_r2c_2d(mHeight, mWidth, mIn[i].data(), fftwf_cast(mOut[i].data()), FFTW_MEASURE); mRIn = std::vector<Array_complex>((NUMLOD + 1) * mFreq.size(), Array_complex(mHeight, mWidth / 2 + 1)); mROut = std::vector<Array_t>((NUMLOD + 1) * mFreq.size(), Array_t(mHeight, mWidth)); mRPlan = std::vector<fftwf_plan>((NUMLOD + 1) * mFreq.size()); for (int i = 0; i < (NUMLOD + 1) * mFreq.size(); ++i) mRPlan[i] = fftwf_plan_dft_c2r_2d(mHeight, mWidth, fftwf_cast(mRIn[i].data()), mROut[i].data(), FFTW_MEASURE); mContrastIm = std::vector<Array_t>((NUMLOD + 1) * mFreq.size(), Array_t(mHeight, mWidth)); mContrastImNomask = std::vector<Array_t>((NUMLOD + 1) * mFreq.size(), Array_t(mHeight, mWidth)); } // Helper functions bool InitFrameBuffer(GLuint& fbo, GLuint* fboTex, int numColorTex, int width, int height) { // Generate FBO and textures glGenFramebuffers(1, &fbo); glBindFramebuffer(GL_FRAMEBUFFER, fbo); GLenum* bufs = new GLenum[numColorTex]; // Setup textures for (int i = 0; i < numColorTex - 1; i++) { glGenTextures(1, &fboTex[i]); glBindTexture(GL_TEXTURE_2D, fboTex[i]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, fboTex[i], 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); bufs[i] = GL_COLOR_ATTACHMENT0 + i; } glGenTextures(1, &fboTex[numColorTex - 1]); glBindTexture(GL_TEXTURE_2D, fboTex[numColorTex - 1]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, width, height, 0, GL_RGBA, GL_FLOAT, NULL); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + numColorTex - 1, GL_TEXTURE_2D, fboTex[numColorTex - 1], 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); bufs[numColorTex - 1] = GL_COLOR_ATTACHMENT0 + numColorTex - 1; glGenTextures(1, &fboTex[numColorTex]); glBindTexture(GL_TEXTURE_2D, fboTex[numColorTex]); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, fboTex[numColorTex], 0); // Setup draw buffers glDrawBuffers(numColorTex, bufs); // Check status GLenum Status = glCheckFramebufferStatus(GL_FRAMEBUFFER); glCheckError(); if (Status != GL_FRAMEBUFFER_COMPLETE) printf("FB error, status: 0x%x\n", Status); return false; // Cleanup delete[] bufs; glBindFramebuffer(GL_FRAMEBUFFER, 0); return true; } glm::vec3 MouseToGaze() { double x, y; glfwGetCursorPos(mWindow, &x, &y); y = (mHeight - 1) - y; x = (2.0 * x - mWidth) / mHeight; y = 2.0 * y / mHeight - 1.0; glm::vec3 dir = { x * tan(FOV / 2.0 / 180.0 * PI), y * tan(FOV / 2.0 / 180.0 * PI), -1 }; return glm::normalize(dir); } void ResetLOD() { mUniformLODLevel = 0.0f; mFaceLOD = std::vector<int>(NUMFACES, 0); mFaceTesLevel = std::vector<float>(3 * NUMFACES, LOD2TESLEVEL[0]); mEdgeTesLevel = std::vector<float>(3 * NUMFACES, LOD2TESLEVEL[0]); glBindBuffer(GL_ARRAY_BUFFER, mFaceTesBuffer); glCheckError(); glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(int) * NUMFACES * 3, mFaceTesLevel.data()); glBindBuffer(GL_ARRAY_BUFFER, mEdgeTesBuffer); glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(int) * NUMFACES * 3, mEdgeTesLevel.data()); } // Members // Dimensions uint32_t mWidth = windowWidth; uint32_t mHeight = windowHeight; // Camera related glm::mat4 mViewProjectionMatrix; glm::mat4 mViewMatrix; glm::vec3 mEye = { -1.979,0,1.148 }; glm::vec3 mLookAt = { -1.272,0,0.4347 }; glm::vec3 mUp = {0,1,0}; // Objects and shaders Shader mShader; std::shared_ptr<Mesh> mObject; Shader mSkyShader; std::shared_ptr<Mesh> mSkybox; size_t NUMFACES; // Framebuffers GLuint mFBO; GLuint mFBOTex[4]; GLuint mPopFBO[NUMLOD + 1]; GLuint mPopFBOTex[NUMLOD + 1][4]; GLuint m_leftFbo; GLuint m_leftFboTex[4]; GLuint m_rightFbo; GLuint m_rightFboTex[4]; GLuint mBGFBO; GLuint mResizeFBO; GLuint mResizeFBOTex[4]; // Popping calculation pre-allocated memory Array_ui mCurrId; Array_ub mCurrId0; Array_ub mCurrId1; Array_t mCurrEcc; ArrayXf mTriEcc; std::vector<ArrayXf> mTriPopping; std::vector<ArrayXf> mTriPoppingNomask; ArrayXf mFreq; ArrayXf mFreqSensitivity; std::vector<Array_t> mAFFilter; std::vector<Array_t> mLFFilter; std::vector<Array_t> mPopping; std::vector<Array_t> mPoppingNomask; std::vector<Array_ub> mImage; std::vector<Array_t> mIn; std::vector<Array_complex> mOut; std::vector<fftwf_plan> mPlan; std::vector<Array_complex> mRIn; std::vector<Array_t> mROut; std::vector<fftwf_plan> mRPlan; std::vector<Array_t> mContrastIm; std::vector<Array_t> mContrastImNomask; // Tessellation related float mUniformLODLevel = 0.0f; std::vector<int> mFaceLOD; std::vector<int> mNewLOD; std::vector<float> mFaceTesLevel; std::vector<float> mEdgeTesLevel; std::vector<float> mNewFaceTesLevel; std::vector<float> mNewEdgeTesLevel; GLuint mFaceTesBuffer; GLuint mEdgeTesBuffer; std::vector<edge_t> mEdgePair; // Multithread related bool flag = false; GLFWwindow* mWindow; GLFWwindow* mBGWindow; std::atomic<bool> mBGWorking = false; std::atomic<bool> mBGUpdate = false; // VR related VRApplication vr; glm::vec3 mGaze = glm::vec3(0, 0, -1.0); double mTimestamp = 0; double mSystemTimestamp = 0; double mSaccadeEndTime; bool mIsSaccade = false; }; int main() { // Load GLFW and Create a Window glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); auto mWindow = glfwCreateWindow(windowWidth, windowHeight, "OpenGL", nullptr, nullptr); // Check for Valid Context if (mWindow == nullptr) { fprintf(stderr, "Failed to Create OpenGL Context"); return EXIT_FAILURE; } // Create Context and Load OpenGL Functions glfwMakeContextCurrent(mWindow); gladLoadGL(); fprintf(stderr, "OpenGL %s\n", glGetString(GL_VERSION)); application app; app.Init(mWindow); glfwSetWindowUserPointer(mWindow, &app); auto key_callback = [](GLFWwindow* window, int key, int scancode, int action, int mods) { static_cast<application*>(glfwGetWindowUserPointer(window))->KeyCallBack(key, scancode, action, mods); }; glfwSetKeyCallback(mWindow, key_callback); // Rendering Loop while (glfwWindowShouldClose(mWindow) == false) { if (glfwGetKey(mWindow, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(mWindow, true); app.Render(); // Flip Buffers and Draw glfwSwapBuffers(mWindow); glfwPollEvents(); } glfwTerminate(); return EXIT_SUCCESS; }
34.272346
172
0.685276
[ "mesh", "render", "vector" ]
df3ecd4cb01a32f8552bc1af5005c2d223103898
1,139
cpp
C++
Cpp/Stacks-and-Queues/Problems/largest-rectangle-in-histogram.cpp
mailtokartik1/InterviewBit-Solutions
8a9be25cf55947aff456c7c138e2ee6f518aa6a5
[ "MIT" ]
58
2019-06-15T01:35:06.000Z
2021-04-27T08:32:39.000Z
Stacks-and-Queues/Problems/largest-rectangle-in-histogram.cpp
mojo912/InterviewBit-Solutions
62fb19efff15bbe3b42183c12d2e6adf7c4c2a84
[ "MIT" ]
3
2019-06-17T00:20:13.000Z
2019-06-30T05:41:10.000Z
Stacks-and-Queues/Problems/largest-rectangle-in-histogram.cpp
mojo912/InterviewBit-Solutions
62fb19efff15bbe3b42183c12d2e6adf7c4c2a84
[ "MIT" ]
14
2019-06-15T01:35:09.000Z
2020-08-27T19:45:28.000Z
int Solution::largestRectangleArea(vector<int> &A) { stack<int> st; int sol = 0; int i = 0, n = A.size(); while(i < n){ // Push the elements on to the stack if it is empty or if the current element is greater than the top element if(st.empty() || A[st.top()] <= A[i]){ st.push(i); i++; } // Else find the area all of the elements in the stack and take its maximum else{ int top = st.top(); st.pop(); int area = 0; if(st.empty()){ area = A[top] * i; } else{ area = A[top] * (i - st.top() - 1); } sol = max(sol, area); } } // Do the same procedure for the end while(!st.empty()){ int top = st.top(); st.pop(); int area = 0; if(st.empty()){ area = A[top] * i; } else{ area = A[top] * (i - st.top() - 1); } sol = max(sol, area); } return sol; }
21.092593
117
0.389816
[ "vector" ]
df4d5d7503cf94096cb54aa66d1eb6856b4c852c
9,709
cpp
C++
doric-Qt/example/doric/plugin/DoricNavBarPlugin.cpp
Xcoder1011/Doric
ad1a409ef5edb9de8f3e1544748a9fa8015760c8
[ "Apache-2.0" ]
116
2019-12-30T11:34:47.000Z
2022-03-31T05:32:58.000Z
doric-Qt/example/doric/plugin/DoricNavBarPlugin.cpp
Xcoder1011/Doric
ad1a409ef5edb9de8f3e1544748a9fa8015760c8
[ "Apache-2.0" ]
9
2020-04-26T02:04:27.000Z
2022-01-26T07:31:01.000Z
doric-Qt/example/doric/plugin/DoricNavBarPlugin.cpp
Xcoder1011/Doric
ad1a409ef5edb9de8f3e1544748a9fa8015760c8
[ "Apache-2.0" ]
18
2020-01-24T15:42:03.000Z
2021-12-28T08:17:36.000Z
#include "DoricNavBarPlugin.h" #include "engine/DoricPromise.h" #include "shader/DoricViewNode.h" #include "utils/DoricUtils.h" #include <QJsonDocument> #include <QJsonObject> #include <QQmlComponent> void DoricNavBarPlugin::isHidden(QString jsValueString, QString callbackId) { getContext()->getDriver()->asyncCall( [this, callbackId] { QQuickItem *navbar = getContext() ->getQmlEngine() ->rootObjects() .at(0) ->findChild<QQuickItem *>("navbar"); if (navbar != nullptr) { bool hidden = !(navbar->isVisible()); QVariantList args; args.append(hidden); DoricPromise::resolve(getContext(), callbackId, args); } else { QVariantList args; args.append("Not implement NavBar"); DoricPromise::reject(getContext(), callbackId, args); } }, DoricThreadMode::UI); } void DoricNavBarPlugin::setHidden(QString jsValueString, QString callbackId) { QJsonDocument document = QJsonDocument::fromJson(jsValueString.toUtf8()); QJsonValue jsValue = document.object(); bool hidden = jsValue["hidden"].toBool(); getContext()->getDriver()->asyncCall( [this, callbackId, hidden] { QQuickItem *navbar = getContext() ->getQmlEngine() ->rootObjects() .at(0) ->findChild<QQuickItem *>("navbar"); if (navbar != nullptr) { navbar->setVisible(!hidden); QVariantList args; DoricPromise::resolve(getContext(), callbackId, args); } else { QVariantList args; args.append("Not implement NavBar"); DoricPromise::reject(getContext(), callbackId, args); } }, DoricThreadMode::UI); } void DoricNavBarPlugin::setTitle(QString jsValueString, QString callbackId) { QJsonDocument document = QJsonDocument::fromJson(jsValueString.toUtf8()); QJsonValue jsValue = document.object(); QString titleString = jsValue["title"].toString(); getContext()->getDriver()->asyncCall( [this, callbackId, titleString] { QQuickItem *navbar = getContext() ->getQmlEngine() ->rootObjects() .at(0) ->findChild<QQuickItem *>("navbar"); if (navbar != nullptr) { QQuickItem *title = navbar->findChild<QQuickItem *>("title"); title->setProperty("text", titleString); QVariantList args; DoricPromise::resolve(getContext(), callbackId, args); } else { QVariantList args; args.append("Not implement NavBar"); DoricPromise::reject(getContext(), callbackId, args); } }, DoricThreadMode::UI); } void DoricNavBarPlugin::setBgColor(QString jsValueString, QString callbackId) { QJsonDocument document = QJsonDocument::fromJson(jsValueString.toUtf8()); QJsonValue jsValue = document.object(); QString bgColor = DoricUtils::doricColor(jsValue["color"].toInt()).name(); getContext()->getDriver()->asyncCall( [this, callbackId, bgColor] { QQuickItem *navbar = getContext() ->getQmlEngine() ->rootObjects() .at(0) ->findChild<QQuickItem *>("navbar"); if (navbar != nullptr) { navbar->setProperty("color", bgColor); QVariantList args; DoricPromise::resolve(getContext(), callbackId, args); } else { QVariantList args; args.append("Not implement NavBar"); DoricPromise::reject(getContext(), callbackId, args); } }, DoricThreadMode::UI); } void DoricNavBarPlugin::setLeft(QString jsValueString, QString callbackId) { QJsonDocument document = QJsonDocument::fromJson(jsValueString.toUtf8()); QJsonValue jsValue = document.object(); getContext()->getDriver()->asyncCall( [this, callbackId, jsValue] { QQuickItem *navbar = getContext() ->getQmlEngine() ->rootObjects() .at(0) ->findChild<QQuickItem *>("navbar"); if (navbar != nullptr) { QString viewId = jsValue["id"].toString(); QString type = jsValue["type"].toString(); DoricViewNode *viewNode = getContext()->targetViewNode(viewId); if (viewNode == nullptr) { viewNode = DoricViewNode::create(getContext(), type); viewNode->setId(viewId); viewNode->init(nullptr); } viewNode->blend(jsValue["props"]); QQuickItem *left = navbar->findChild<QQuickItem *>("left"); foreach (QQuickItem *child, left->childItems()) { child->setParentItem(nullptr); child->deleteLater(); } viewNode->getNodeView()->setParentItem(left); getContext()->addHeadNode(TYPE_LEFT, viewNode); DoricLayouts *layout = (DoricLayouts *)(viewNode->getNodeView() ->property("doricLayout") .toULongLong()); layout->apply(QSizeF(navbar->width(), navbar->height())); QVariantList args; DoricPromise::resolve(getContext(), callbackId, args); } else { QVariantList args; args.append("Not implement NavBar"); DoricPromise::reject(getContext(), callbackId, args); } }, DoricThreadMode::UI); } void DoricNavBarPlugin::setRight(QString jsValueString, QString callbackId) { QJsonDocument document = QJsonDocument::fromJson(jsValueString.toUtf8()); QJsonValue jsValue = document.object(); getContext()->getDriver()->asyncCall( [this, callbackId, jsValue] { QQuickItem *navbar = getContext() ->getQmlEngine() ->rootObjects() .at(0) ->findChild<QQuickItem *>("navbar"); if (navbar != nullptr) { QString viewId = jsValue["id"].toString(); QString type = jsValue["type"].toString(); DoricViewNode *viewNode = getContext()->targetViewNode(viewId); if (viewNode == nullptr) { viewNode = DoricViewNode::create(getContext(), type); viewNode->setId(viewId); viewNode->init(nullptr); } viewNode->blend(jsValue["props"]); QQuickItem *right = navbar->findChild<QQuickItem *>("right"); foreach (QQuickItem *child, right->childItems()) { child->setParentItem(nullptr); child->deleteLater(); } viewNode->getNodeView()->setParentItem(right); getContext()->addHeadNode(TYPE_RIGHT, viewNode); DoricLayouts *layout = (DoricLayouts *)(viewNode->getNodeView() ->property("doricLayout") .toULongLong()); layout->apply(QSizeF(navbar->width(), navbar->height())); QVariantList args; DoricPromise::resolve(getContext(), callbackId, args); } else { QVariantList args; args.append("Not implement NavBar"); DoricPromise::reject(getContext(), callbackId, args); } }, DoricThreadMode::UI); } void DoricNavBarPlugin::setCenter(QString jsValueString, QString callbackId) { QJsonDocument document = QJsonDocument::fromJson(jsValueString.toUtf8()); QJsonValue jsValue = document.object(); getContext()->getDriver()->asyncCall( [this, callbackId, jsValue] { QQuickItem *navbar = getContext() ->getQmlEngine() ->rootObjects() .at(0) ->findChild<QQuickItem *>("navbar"); if (navbar != nullptr) { QString viewId = jsValue["id"].toString(); QString type = jsValue["type"].toString(); DoricViewNode *viewNode = getContext()->targetViewNode(viewId); if (viewNode == nullptr) { viewNode = DoricViewNode::create(getContext(), type); viewNode->setId(viewId); viewNode->init(nullptr); } viewNode->blend(jsValue["props"]); QQuickItem *center = navbar->findChild<QQuickItem *>("center"); foreach (QQuickItem *child, center->childItems()) { child->setParentItem(nullptr); child->deleteLater(); } viewNode->getNodeView()->setParentItem(center); getContext()->addHeadNode(TYPE_CENTER, viewNode); DoricLayouts *layout = (DoricLayouts *)(viewNode->getNodeView() ->property("doricLayout") .toULongLong()); layout->apply(QSizeF(navbar->width(), navbar->height())); QVariantList args; DoricPromise::resolve(getContext(), callbackId, args); } else { QVariantList args; args.append("Not implement NavBar"); DoricPromise::reject(getContext(), callbackId, args); } }, DoricThreadMode::UI); }
37.342308
79
0.541868
[ "object" ]
df5061b2fac16d44059d7434a10666d1ae268a6f
2,312
hpp
C++
modules/gapi/samples/pipeline_modeling_tool/utils.hpp
danopdev/opencv
046a7633ea388415b546db2324be4c1e6a0baba3
[ "Apache-2.0" ]
1
2022-02-06T12:02:15.000Z
2022-02-06T12:02:15.000Z
modules/gapi/samples/pipeline_modeling_tool/utils.hpp
danopdev/opencv
046a7633ea388415b546db2324be4c1e6a0baba3
[ "Apache-2.0" ]
null
null
null
modules/gapi/samples/pipeline_modeling_tool/utils.hpp
danopdev/opencv
046a7633ea388415b546db2324be4c1e6a0baba3
[ "Apache-2.0" ]
null
null
null
#ifndef OPENCV_GAPI_PIPELINE_MODELING_TOOL_UTILS_HPP #define OPENCV_GAPI_PIPELINE_MODELING_TOOL_UTILS_HPP #include <opencv2/core.hpp> #if defined(_WIN32) #include <windows.h> #endif // FIXME: It's better to place it somewhere in common.hpp struct OutputDescr { std::vector<int> dims; int precision; }; namespace utils { inline void generateRandom(cv::Mat& out) { switch (out.depth()) { case CV_8U: cv::randu(out, 0, 255); break; case CV_32F: cv::randu(out, 0.f, 1.f); break; case CV_16F: { cv::Mat fp32_mat(out.size(), CV_MAKETYPE(CV_32F, out.channels())); cv::randu(fp32_mat, 0.f, 1.f); fp32_mat.convertTo(out, out.type()); break; } default: throw std::logic_error("Unsupported preprocessing depth"); } } inline void sleep(double ms) { #if defined(_WIN32) // NB: It takes portions of 100 nanoseconds. int64_t ns_units = static_cast<int64_t>(ms * 1e4); // FIXME: Wrap it to RAII and instance only once. HANDLE timer = CreateWaitableTimer(NULL, true, NULL); if (!timer) { throw std::logic_error("Failed to create timer"); } LARGE_INTEGER li; li.QuadPart = -ns_units; if(!SetWaitableTimer(timer, &li, 0, NULL, NULL, false)){ CloseHandle(timer); throw std::logic_error("Failed to set timer"); } if (WaitForSingleObject(timer, INFINITE) != WAIT_OBJECT_0) { CloseHandle(timer); throw std::logic_error("Failed to wait timer"); } CloseHandle(timer); #else using namespace std::chrono; std::this_thread::sleep_for(duration<double, std::milli>(ms)); #endif } template <typename duration_t> typename duration_t::rep measure(std::function<void()> f) { using namespace std::chrono; auto start = high_resolution_clock::now(); f(); return duration_cast<duration_t>( high_resolution_clock::now() - start).count(); } template <typename duration_t> typename duration_t::rep timestamp() { using namespace std::chrono; auto now = high_resolution_clock::now(); return duration_cast<duration_t>(now.time_since_epoch()).count(); } } // namespace utils #endif // OPENCV_GAPI_PIPELINE_MODELING_TOOL_UTILS_HPP
28.195122
78
0.644464
[ "vector" ]
df645c1febae9a703e62dfaa973ecd3c39edd5e7
5,902
cpp
C++
RayTracer/RayTracer.cpp
maslychm/PathTracer
0674b048c7dce54e3aae4f027c5863f72bf5b510
[ "MIT" ]
null
null
null
RayTracer/RayTracer.cpp
maslychm/PathTracer
0674b048c7dce54e3aae4f027c5863f72bf5b510
[ "MIT" ]
null
null
null
RayTracer/RayTracer.cpp
maslychm/PathTracer
0674b048c7dce54e3aae4f027c5863f72bf5b510
[ "MIT" ]
null
null
null
#include "rtcommon.h" // My additions #include "image.h" #include "scene.h" #include <chrono> #include <iostream> #include <ctime> #include <string> #include "external/thread_pool.h" color ray_color(const ray& r, const color& background, const hittable& world, int depth) { hit_record rec; // If we've exceeded the ray bounce limit, no more light is gathered. if (depth <= 0) return color(0, 0, 0); // If the ray hits nothing, return the background color. if (!world.hit(r, 0.001, infinity, rec)) return background; ray scattered; color attenuation; color emitted = rec.mat_ptr->emitted(rec.u, rec.v, rec.p); if (!rec.mat_ptr->scatter(r, rec, attenuation, scattered)) return emitted; return emitted + attenuation * ray_color(scattered, background, world, depth - 1); } color render_pixel( shared_ptr<camera> cam, color& background, hittable_list& world, const int max_depth, const int samples_per_pixel, const int image_height, const int image_width, const int j, const int i) { color pixel_color(0, 0, 0); for (int s = 0; s < samples_per_pixel; ++s) { auto u = (i + random_double()) / (image_width - 1); auto v = (j + random_double()) / (image_height - 1); ray r = cam->get_ray(u, v); pixel_color += ray_color(r, background, world, max_depth); } return pixel_color; } void render_line( shared_ptr<camera> cam, color& background, hittable_list& world, image* img, const int max_depth, const int samples_per_pixel, const int line, const int image_height, const int image_width) { for (int i = 0; i < image_width; i++) { color pixel_color = render_pixel(cam, background, world, max_depth, samples_per_pixel, image_height, image_width, line, i); img->set_color(image_height - line - 1, i, pixel_color); } } class renderer { public: renderer() {}; void render() { finished = false; double aspect_ratio = 16.0 / 9.0; int image_width = 400; int samples_per_pixel = 200; int max_depth = 50; scene render_scene; hittable_list world; point3 lookfrom; point3 lookat; auto vfov = 40.0; auto aperture = 0.0; color background(0, 0, 0); // Create the scene render_scene = avatar_scene(); //render_scene = avatar_enhanced_scene(); //render_scene = random_scene(); //render_scene = two_perlin_spheres_scene(); //render_scene = earth_scene(); //render_scene = simple_light_scene(); //render_scene = cornell_box_scene(); //render_scene = cornell_smoke_scene(); //render_scene = final_scene(); // Get the scene's objects world = render_scene.world; // Get the scene's custom settings image_width = render_scene.image_width; aspect_ratio = render_scene.aspect_ratio; samples_per_pixel = render_scene.samples_per_pixel; max_depth = render_scene.max_depth; background = render_scene.background; lookfrom = render_scene.lookfrom; lookat = render_scene.lookat; vfov = render_scene.vfov; // Camera vec3 vup = render_scene.vup; auto dist_to_focus = render_scene.dist_to_focus; int image_height = static_cast<int>(image_width / aspect_ratio); shared_ptr<camera> cam = make_shared<camera>(lookfrom, lookat, vup, vfov, aspect_ratio, aperture, dist_to_focus, 0.0, 1.0); // Render img = new image(image_width, image_height, samples_per_pixel); int num_threads = std::thread::hardware_concurrency() - 1; thread_pool pool(num_threads); std::cout << "Rendering on " << num_threads << " threads\n"; std::cout << "W: " << image_width << " H: " << image_height << "\n"; std::cout << "Samples per pixel: " << samples_per_pixel << std::endl; // split by lines std::vector<std::future<void>> results; for (int j = 0; j < image_height; j++) { results.emplace_back( pool.enqueue( render_line, cam, background, world, img, max_depth, samples_per_pixel, j, image_height, image_width)); } for (auto&& result : results) result.get(); save_image(); finished = true; return; } float approx_completion_ratio() { return img->approx_completion(); } void save_image() { img->write_image("final.ppm"); } void generate_preview() { img->write_image("preview.ppm"); } void display_status() { img->print_progress(); } // Separate rendering thread to capture input in main void start_rendering() { render_thread = std::thread([this] { render(); }); } // Finish by joining the thread void finish_rendering() { render_thread.join(); } private: std::thread render_thread; image* img; public: bool finished; }; int main() { auto start = std::chrono::high_resolution_clock::now(); renderer rend = renderer(); rend.start_rendering(); std::cout << "/// enter p to generate a preview" << std::endl; std::cout << "/// enter s to display rendering status" << std::endl; std::cout << "/// enter t to estimate the remaining time" << std::endl; // Capture input until rendering is done std::string inp; while (!rend.finished) { std::cin >> inp; if (rend.finished) break; if (inp.find("p") != std::string::npos) { rend.generate_preview(); } else if (inp.find("s") != std::string::npos) { rend.display_status(); } else if (inp.find("t") != std::string::npos) { // Estimate time remaining auto now = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(now - start); double lasted = (double)duration.count() / 1000 / 60; double total_time = lasted / rend.approx_completion_ratio(); std::cout << "time remaining: " << total_time - lasted << " minutes" << std::endl; } } rend.finish_rendering(); auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::seconds>(stop - start); std::cout << "\nTook " << (double)duration.count() << " seconds to finish\n" << std::endl; system("pause"); return 0; }
23.894737
125
0.678414
[ "render", "vector" ]
df7ca134b28e54f624f8a53fda453b2e32221732
7,520
cc
C++
examples/multibody/four_bar/passive_simulation.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
2
2021-02-25T02:01:02.000Z
2021-03-17T04:52:04.000Z
examples/multibody/four_bar/passive_simulation.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
null
null
null
examples/multibody/four_bar/passive_simulation.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
1
2021-06-13T12:05:39.000Z
2021-06-13T12:05:39.000Z
/* @file A four bar linkage demo demonstrating the use of a linear bushing as a way to model a kinematic loop. It shows: - How to model a four bar linkage in SDF. - Use the `multibody::Parser` to load a model from an SDF file into a MultibodyPlant. - Model a revolute joint with a `multibody::LinearBushingRollPitchYaw` to model a closed kinematic chain. Refer to README.md for more details. */ #include <gflags/gflags.h> #include "drake/common/find_resource.h" #include "drake/geometry/drake_visualizer.h" #include "drake/multibody/parsing/parser.h" #include "drake/multibody/tree/linear_bushing_roll_pitch_yaw.h" #include "drake/multibody/tree/revolute_joint.h" #include "drake/systems/analysis/simulator.h" #include "drake/systems/analysis/simulator_gflags.h" #include "drake/systems/analysis/simulator_print_stats.h" #include "drake/systems/framework/diagram_builder.h" namespace drake { using Eigen::Vector3d; using geometry::SceneGraph; using multibody::Frame; using multibody::LinearBushingRollPitchYaw; using multibody::MultibodyPlant; using multibody::Parser; using multibody::RevoluteJoint; using systems::Context; using systems::DiagramBuilder; using systems::Simulator; namespace examples { namespace multibody { namespace four_bar { namespace { DEFINE_double(simulation_time, 10.0, "Duration of the simulation in seconds."); DEFINE_double( force_stiffness, 30000, "Force (translational) stiffness value for kx, ky, kz in N/m of the " "LinearBushingRollPitchYaw ForceElement."); DEFINE_double( force_damping, 1500, "Force (translational) damping value for dx, dy, dz in N·s/m of the " "LinearBushingRollPitchYaw ForceElement."); DEFINE_double(torque_stiffness, 30000, "Torque (rotational) stiffness value for k₀, k₁, k₂ in N·m/rad " "of the LinearBushingRollPitchYaw ForceElement."); DEFINE_double( torque_damping, 1500, "Torque (rotational) damping value for d₀, d₁, and d₂ in N·m·s/rad of " "the LinearBushingRollPitchYaw ForceElement."); DEFINE_double(applied_torque, 0.0, "Constant torque applied to joint_WA, denoted Tᴀ in the README."); DEFINE_double( initial_velocity, 3.0, "Initial velocity, q̇A, of joint_WA. Default set to 3 radians/second ≈ " "171.88 degrees/second so that the model has some motion."); int do_main() { // Build a generic MultibodyPlant and SceneGraph. DiagramBuilder<double> builder; auto [four_bar, scene_graph] = AddMultibodyPlantSceneGraph( &builder, std::make_unique<MultibodyPlant<double>>(0.0)); // Make and add the four_bar model from an SDF model. const std::string relative_name = "drake/examples/multibody/four_bar/four_bar.sdf"; const std::string full_name = FindResourceOrThrow(relative_name); Parser parser(&four_bar); parser.AddModelFromFile(full_name); // Get the two frames that define the bushing, namely frame Bc that is // welded to the end of link B and frame Cb that is welded to the end of // link C. Although the bushing allows 6 degrees-of-freedom between frames // Bc and Cb, the stiffness and damping constants are chosen to approximate // the connection between frames Bc and Cb as having only one rotational // degree of freedom along the bushing's z-axis. const Frame<double>& bc_bushing = four_bar.GetFrameByName("Bc_bushing"); const Frame<double>& cb_bushing = four_bar.GetFrameByName("Cb_bushing"); // See the README for a discussion of how these parameters were selected // for this particular example. const double k_xyz = FLAGS_force_stiffness; const double d_xyz = FLAGS_force_damping; const double k_012 = FLAGS_torque_stiffness; const double d_012 = FLAGS_torque_damping; // See the documentation for LinearBushingRollPitchYaw. // This particular choice of parameters models a z-axis revolute joint. // Note: since each link is constrained to rigid motion in the world X-Z // plane (X-Y plane of the bushing) by the revolute joints specified in the // SDF, it is unnecessary for the bushing to have non-zero values for: k_z, // d_z, k_0, d_0, k_1, d_1. They are left here as an example of how to // parameterize a general z-axis revolute joint without other constraints. const Vector3d force_stiffness_constants{k_xyz, k_xyz, k_xyz}; // N/m const Vector3d force_damping_constants{d_xyz, d_xyz, d_xyz}; // N·s/m const Vector3d torque_stiffness_constants{k_012, k_012, 0}; // N·m/rad const Vector3d torque_damping_constants{d_012, d_012, 0}; // N·m·s/rad // Add a bushing force element where the joint between link B and link C // should be in an ideal 4-bar linkage. four_bar.AddForceElement<LinearBushingRollPitchYaw>( bc_bushing, cb_bushing, torque_stiffness_constants, torque_damping_constants, force_stiffness_constants, force_damping_constants); // We are done defining the model. Finalize and build the diagram. four_bar.Finalize(); geometry::DrakeVisualizerd::AddToBuilder(&builder, scene_graph); auto diagram = builder.Build(); // Create a context for this system and sub-context for the four bar system. std::unique_ptr<Context<double>> diagram_context = diagram->CreateDefaultContext(); Context<double>& four_bar_context = four_bar.GetMyMutableContextFromRoot(diagram_context.get()); // A constant source for applied torque (Tᴀ) at joint_WA. four_bar.get_actuation_input_port().FixValue(&four_bar_context, FLAGS_applied_torque); // Set initial conditions so the model will have some motion const RevoluteJoint<double>& joint_WA = four_bar.GetJointByName<RevoluteJoint>("joint_WA"); const RevoluteJoint<double>& joint_WC = four_bar.GetJointByName<RevoluteJoint>("joint_WC"); const RevoluteJoint<double>& joint_AB = four_bar.GetJointByName<RevoluteJoint>("joint_AB"); // See the README for an explanation of these angles. const double qA = atan2(sqrt(15.0), 1.0); // about 75.52° const double qB = M_PI - qA; // about 104.48° const double qC = qB; // about 104.48° joint_WA.set_angle(&four_bar_context, qA); joint_AB.set_angle(&four_bar_context, qB); joint_WC.set_angle(&four_bar_context, qC); // Set q̇A,the rate of change in radians/second of the angle qA. joint_WA.set_angular_rate(&four_bar_context, FLAGS_initial_velocity); // Create a simulator and run the simulation std::unique_ptr<Simulator<double>> simulator = MakeSimulatorFromGflags(*diagram, std::move(diagram_context)); simulator->AdvanceTo(FLAGS_simulation_time); // Print some useful statistics PrintSimulatorStatistics(*simulator); return 0; } } // namespace } // namespace four_bar } // namespace multibody } // namespace examples } // namespace drake int main(int argc, char* argv[]) { gflags::SetUsageMessage( "A four bar linkage demo demonstrating the use of a linear bushing as " "a way to model a kinematic loop. Launch drake-visualizer before running " "this example."); // Changes the default realtime rate to 1.0, so the visualization looks // realistic. Otherwise, it finishes so fast that we can't appreciate the // motion. Users can still change it on command-line, e.g. " // --simulator_target_realtime_rate=0.5" to slow it down. FLAGS_simulator_target_realtime_rate = 1.0; gflags::ParseCommandLineFlags(&argc, &argv, true); return drake::examples::multibody::four_bar::do_main(); }
39.78836
80
0.736569
[ "geometry", "model" ]
df7d03a129a524b3367ee01eaebae871b964fc6c
7,045
cpp
C++
src/main.cpp
triSYCL/path_tracer
88bdd77cfc1b8a9ff5afb553d5aaad62339db9dc
[ "Apache-2.0" ]
12
2020-12-16T12:18:43.000Z
2022-03-29T01:11:19.000Z
src/main.cpp
triSYCL/path_tracer
88bdd77cfc1b8a9ff5afb553d5aaad62339db9dc
[ "Apache-2.0" ]
26
2020-12-14T23:19:20.000Z
2021-07-05T16:24:44.000Z
src/main.cpp
triSYCL/path_tracer
88bdd77cfc1b8a9ff5afb553d5aaad62339db9dc
[ "Apache-2.0" ]
5
2021-01-20T15:13:14.000Z
2022-01-07T15:51:19.000Z
#include "sycl.hpp" #include <algorithm> #include <chrono> #include <cstdint> #include <iostream> #include <iterator> #include <math.h> #include <thread> #include <vector> #define STB_IMAGE_WRITE_IMPLEMENTATION #include <stb/stb_image_write.h> #include "render.hpp" // Function to save image data in ppm format void dump_image_ppm(int width, int height, auto& fb_data) { std::cout << "P3\n" << width << " " << height << "\n255\n"; for (int y = height - 1; y >= 0; y--) { for (int x = 0; x < width; x++) { auto pixel_index = y * width + x; int r = static_cast<int>( 256 * std::clamp(sycl::sqrt(fb_data[pixel_index].x()), 0.0f, 0.999f)); int g = static_cast<int>( 256 * std::clamp(sycl::sqrt(fb_data[pixel_index].y()), 0.0f, 0.999f)); int b = static_cast<int>( 256 * std::clamp(sycl::sqrt(fb_data[pixel_index].z()), 0.0f, 0.999f)); std::cout << r << " " << g << " " << b << "\n"; } } } void save_image_png(int width, int height, sycl::buffer<color, 2> &fb) { constexpr unsigned num_channels = 3; auto fb_data = fb.get_access<sycl::access::mode::read>(); std::vector<uint8_t> pixels; pixels.resize(width * height * num_channels); int index = 0; for (int j = height - 1; j >= 0; --j) { for (int i = 0; i < width; ++i) { auto input_index = j * width + i; int r = static_cast<int>( 256 * std::clamp(sycl::sqrt(fb_data[j][i].x()), 0.0f, 0.999f)); int g = static_cast<int>( 256 * std::clamp(sycl::sqrt(fb_data[j][i].y()), 0.0f, 0.999f)); int b = static_cast<int>( 256 * std::clamp(sycl::sqrt(fb_data[j][i].z()), 0.0f, 0.999f)); pixels[index++] = r; pixels[index++] = g; pixels[index++] = b; } } stbi_write_png("out.png", width, height, num_channels, pixels.data(), width * num_channels); } int main() { // Frame buffer dimensions constexpr auto width = buildparams::output_width; constexpr auto height = buildparams::output_height; /// Graphical objects std::vector<hittable_t> hittables; // Generating a checkered ground and some random spheres texture_t t = checker_texture(color { 0.2f, 0.3f, 0.1f }, color { 0.9f, 0.9f, 0.9f }); material_t m = lambertian_material(t); hittables.emplace_back(sphere(point { 0, -1000, 0 }, 1000, m)); t = checker_texture(color { 0.9f, 0.9f, 0.9f }, color { 0.4f, 0.2f, 0.1f }); LocalPseudoRNG rng; for (int a = -11; a < 11; a++) { for (int b = -11; b < 11; b++) { // Based on a random variable , the material type is chosen auto choose_mat = rng.float_t(); // Spheres are placed at a point randomly displaced from a,b point center(a + 0.9f * rng.float_t(), 0.2f, b + 0.9f * rng.float_t()); if (sycl::length((center - point(4, 0.2f, 0))) > 0.9f) { if (choose_mat < 0.4f) { // Lambertian auto albedo = rng.vec_t() * rng.vec_t(); hittables.emplace_back( sphere(center, 0.2f, lambertian_material(albedo))); } else if (choose_mat < 0.8f) { // Lambertian movig spheres auto albedo = rng.vec_t() * rng.vec_t(); auto center2 = center + point { 0, rng.float_t(0, 0.25f), 0 }; hittables.emplace_back(sphere(center, center2, 0.0f, 1.0f, 0.2f, lambertian_material(albedo))); } else if (choose_mat < 0.95f) { // metal auto albedo = rng.vec_t(0.5f, 1); auto fuzz = rng.float_t(0, 0.5f); hittables.emplace_back( sphere(center, 0.2f, metal_material(albedo, fuzz))); } else { // glass hittables.emplace_back( sphere(center, 0.2f, dielectric_material(1.5f, color { 1.0f, 1.0f, 1.0f }))); } } } } // Pyramid hittables.emplace_back( triangle(point { 6.5f, 0.0f, 1.30f }, point { 6.25f, 0.50f, 1.05f }, point { 6.5f, 0.0f, 0.80f }, lambertian_material(color(0.68f, 0.50f, 0.1f)))); hittables.emplace_back( triangle(point { 6.0f, 0.0f, 1.30f }, point { 6.25f, 0.50f, 1.05f }, point { 6.5f, 0.0f, 1.30f }, lambertian_material(color(0.89f, 0.73f, 0.29f)))); hittables.emplace_back(triangle( point { 6.5f, 0.0f, 0.80f }, point { 6.25f, 0.50f, 1.05f }, point { 6.0f, 0.0f, 0.80f }, lambertian_material(color(0.0f, 0.0f, 1)))); hittables.emplace_back(triangle( point { 6.0f, 0.0f, 0.80f }, point { 6.25f, 0.50f, 1.05f }, point { 6.0f, 0.0f, 1.30f }, lambertian_material(color(0.0f, 0.0f, 1)))); // Glowing ball hittables.emplace_back( sphere(point { 4, 1, 0 }, 0.2f, lightsource_material(color(10, 0, 10)))); // Four large spheres of metal, dielectric and Lambertian material types t = image_texture::image_texture_factory("../images/Xilinx.jpg"); hittables.emplace_back(xy_rect(2, 4, 0, 1, -1, lambertian_material(t))); hittables.emplace_back( sphere(point { 4, 1, 2.25f }, 1, lambertian_material(t))); hittables.emplace_back( sphere(point { 0, 1, 0 }, 1, dielectric_material(1.5f, color { 1.0f, 0.5f, 0.5f }))); hittables.emplace_back(sphere(point { -4, 1, 0 }, 1, lambertian_material(color(0.4f, 0.2f, 0.1f)))); hittables.emplace_back(sphere(point { 0, 1, -2.25f }, 1, metal_material(color(0.7f, 0.6f, 0.5f), 0.0f))); t = image_texture::image_texture_factory("../images/SYCL.png", 5); // // Add a sphere with a SYCL logo in the background hittables.emplace_back( sphere { point { -60, 3, 5 }, 4, lambertian_material { t } }); // Add a metallic monolith hittables.emplace_back( box { point { 6.5f, 0, -1.5f }, point { 7.0f, 3.0f, -1.0f }, metal_material { color { 0.7f, 0.6f, 0.5f }, 0.25f } }); // Add a smoke ball sphere smoke_sphere = sphere { point { 5, 1, 3.5f }, 1, lambertian_material { color { 0.75f, 0.75f, 0.75f } } }; hittables.emplace_back( constant_medium { smoke_sphere, 1, color { 1, 1, 1 } }); // SYCL queue sycl::queue myQueue; // Camera setup /// Position of the camera point look_from { 13, 3, 3 }; /// The center of the scene point look_at { 0, -1, 0 }; // Make the camera oriented upwards vec vup { 0, 1, 0 }; /// Vertical angle of view in degree real_t angle = 40; // Lens aperture. 0 if not depth-of-field real_t aperture = 0.04f; // Make the focus on the point we are looking at real_t focus_dist = length(look_at - look_from); camera cam { look_from, look_at, vup, angle, static_cast<real_t>(width) / height, aperture, focus_dist, 0.0f, 1.0f }; // Sample per pixel constexpr auto samples = 100; // SYCL render kernel sycl::buffer<color, 2> fb(sycl::range<2>(height, width)); render<width, height, samples>(myQueue, fb, hittables, cam); // Save image to file save_image_png(width, height, fb); return 0; }
35.580808
80
0.582967
[ "render", "vector" ]
df7d17ee6681bd4cf71a4d30e47a061bdf7ae2e9
3,111
hpp
C++
src/util/SimpleRandomEngine.hpp
dlasalle/poros
a87e2dc1b64c47f94e0ce05adadbd7e35a63d166
[ "MIT" ]
1
2022-01-15T21:58:08.000Z
2022-01-15T21:58:08.000Z
src/util/SimpleRandomEngine.hpp
dlasalle/poros
a87e2dc1b64c47f94e0ce05adadbd7e35a63d166
[ "MIT" ]
15
2018-12-15T04:09:58.000Z
2019-09-29T18:51:06.000Z
src/util/SimpleRandomEngine.hpp
dlasalle/poros
a87e2dc1b64c47f94e0ce05adadbd7e35a63d166
[ "MIT" ]
null
null
null
/** * @file SimpleRandomEngine.hpp * @brief The SimpleRandomEngine class. * @author Dominique LaSalle <dominique@solidlake.com> * Copyright 2018 * @version 1 * @date 2018-05-20 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #ifndef POROS_SRC_SIMPLERANDOMENGINE_HPP #define POROS_SRC_SIMPLERANDOMENGINE_HPP #include "Base.hpp" #include "solidutils/FastIntDistribution.hpp" #include <cstdint> #include <random> #include <algorithm> namespace poros { class SimpleRandomEngine { public: using result_type = uint32_t; using RandomGenerator = std::mt19937; /** * @brief The minimum value returned from the () operator. * * @return The minimum value. */ constexpr static result_type min() { return RandomGenerator::min(); } /** * @brief The maximum value return from dthe () operator. * * @return The maximum value. */ constexpr static result_type max() { return RandomGenerator::max(); } /** * @brief Create a new random engine. * * @param seed The seed to use. */ SimpleRandomEngine( unsigned int seed = 0); /** * @brief Fill a vector with a vertex permutation. * * @param container The container. * @param start The starting vertex (inclusvie). * @param end The ending vertex (exclusive). */ void fillWithPerm( vtx_type * container, vtx_type const start, vtx_type const end); /** * @brief Get a random number with the given minimum and maximum values. * * @param min The minimum value (inclusive). * @param max The maximum value (inclusive). * * @return The random number. */ vtx_type randInRange( vtx_type const min, vtx_type const max) { return sl::FastIntDistribution<vtx_type>(min, max)(m_rng); } /** * @brief Generate a random number between min() and max(). * * @return The random number. */ result_type operator()() { return m_rng(); } /** * @brief Set the random seed to use. * * @param seed The seed to use. */ void setSeed( unsigned int seed); private: RandomGenerator m_rng; }; } #endif
22.543478
78
0.699775
[ "vector" ]
df7d34190a61ce3be5c07a07730fdb521d7c5a37
8,504
cpp
C++
tests/dist/mpi/test_mpi_functions.cpp
Shillaker/faabric
40da290179c650d9e285475a1992572dfe1c0b10
[ "Apache-2.0" ]
1
2020-09-01T13:37:54.000Z
2020-09-01T13:37:54.000Z
tests/dist/mpi/test_mpi_functions.cpp
Shillaker/faabric
40da290179c650d9e285475a1992572dfe1c0b10
[ "Apache-2.0" ]
null
null
null
tests/dist/mpi/test_mpi_functions.cpp
Shillaker/faabric
40da290179c650d9e285475a1992572dfe1c0b10
[ "Apache-2.0" ]
1
2020-09-13T15:21:16.000Z
2020-09-13T15:21:16.000Z
#include "faabric_utils.h" #include <catch2/catch.hpp> #include "fixtures.h" #include "init.h" #include "mpi/mpi_native.h" #include <faabric/scheduler/Scheduler.h> namespace tests { TEST_CASE_METHOD(MpiDistTestsFixture, "Test MPI all gather", "[mpi]") { // Set up this host's resources setLocalSlots(nLocalSlots); auto req = setRequest("allgather"); // Call the functions sch.callFunctions(req); checkAllocationAndResult(req); } TEST_CASE_METHOD(MpiDistTestsFixture, "Test MPI all reduce", "[mpi]") { // Set up this host's resources setLocalSlots(nLocalSlots); auto req = setRequest("allreduce"); // Call the functions sch.callFunctions(req); checkAllocationAndResult(req); } TEST_CASE_METHOD(MpiDistTestsFixture, "Test MPI all to all", "[mpi]") { // Set up this host's resources setLocalSlots(nLocalSlots); auto req = setRequest("alltoall"); // Call the functions sch.callFunctions(req); checkAllocationAndResult(req); } TEST_CASE_METHOD(MpiDistTestsFixture, "Test MPI all to all many times", "[mpi]") { int numRuns = 50; int oldNumLocalSlots = nLocalSlots; nLocalSlots = 4; int worldSize = 8; for (int i = 0; i < numRuns; i++) { SPDLOG_DEBUG("Starting run {}/{}", i + 1, numRuns); // Set up this host's resources setLocalSlots(nLocalSlots, worldSize); auto req = setRequest("alltoall"); // Call the functions sch.callFunctions(req); checkAllocationAndResult(req); } nLocalSlots = oldNumLocalSlots; } TEST_CASE_METHOD(MpiDistTestsFixture, "Test MPI all to all and sleep", "[mpi]") { // Set up this host's resources setLocalSlots(nLocalSlots); auto req = setRequest("alltoall-sleep"); // Call the functions sch.callFunctions(req); // Wait for extra time as the test will sleep for five seconds checkAllocationAndResult(req, 20000); } TEST_CASE_METHOD(MpiDistTestsFixture, "Test MPI barrier", "[mpi]") { // Set up this host's resources setLocalSlots(nLocalSlots); auto req = setRequest("barrier"); // Call the functions sch.callFunctions(req); checkAllocationAndResult(req); } TEST_CASE_METHOD(MpiDistTestsFixture, "Test MPI broadcast", "[mpi]") { // Set up this host's resources setLocalSlots(nLocalSlots); auto req = setRequest("bcast"); // Call the functions sch.callFunctions(req); checkAllocationAndResult(req); } TEST_CASE_METHOD(MpiDistTestsFixture, "Test MPI cart create", "[mpi]") { // Set up this host's resources setLocalSlots(nLocalSlots); auto req = setRequest("cart-create"); // Call the functions sch.callFunctions(req); checkAllocationAndResult(req); } TEST_CASE_METHOD(MpiDistTestsFixture, "Test MPI cartesian", "[mpi]") { // Set up this host's resources setLocalSlots(nLocalSlots); auto req = setRequest("cartesian"); // Call the functions sch.callFunctions(req); checkAllocationAndResult(req); } TEST_CASE_METHOD(MpiDistTestsFixture, "Test MPI checks", "[mpi]") { // Set up this host's resources setLocalSlots(nLocalSlots); auto req = setRequest("checks"); // Call the functions sch.callFunctions(req); checkAllocationAndResult(req); } TEST_CASE_METHOD(MpiDistTestsFixture, "Test MPI function migration", "[mpi]") { // We fist distribute the execution, and update the local slots // mid-execution to fit all ranks, and create a migration opportunity. int localSlots = 2; int worldSize = 4; setLocalSlots(localSlots, worldSize); auto req = setRequest("migration"); auto& msg = req->mutable_messages()->at(0); // Check very often for migration opportunities so that we detect it // right away msg.set_migrationcheckperiod(1); msg.set_inputdata(std::to_string(NUM_MIGRATION_LOOPS)); // Call the functions sch.callFunctions(req); // Sleep for a while to let the scheduler schedule the MPI calls SLEEP_MS(500); // Update the local slots so that a migration opportunity appears int newLocalSlots = worldSize; setLocalSlots(newLocalSlots, worldSize); // The current function migration approach breaks the execution graph, as // some messages are left dangling (deliberately) without return value std::vector<std::string> hostsBeforeMigration = { getMasterIP(), getMasterIP(), getWorkerIP(), getWorkerIP() }; std::vector<std::string> hostsAfterMigration(worldSize, getMasterIP()); checkAllocationAndResultMigration( req, hostsBeforeMigration, hostsAfterMigration, 15000); } TEST_CASE_METHOD(MpiDistTestsFixture, "Test MPI gather", "[mpi]") { // Set up this host's resources setLocalSlots(nLocalSlots); auto req = setRequest("gather"); // Call the functions sch.callFunctions(req); checkAllocationAndResult(req); } TEST_CASE_METHOD(MpiDistTestsFixture, "Test MPI hello world", "[mpi]") { // Set up this host's resources setLocalSlots(nLocalSlots); auto req = setRequest("hello-world"); // Call the functions sch.callFunctions(req); checkAllocationAndResult(req); } TEST_CASE_METHOD(MpiDistTestsFixture, "Test MPI async. send recv", "[mpi]") { // Set up this host's resources setLocalSlots(nLocalSlots); auto req = setRequest("isendrecv"); // Call the functions sch.callFunctions(req); checkAllocationAndResult(req); } TEST_CASE_METHOD(MpiDistTestsFixture, "Test MPI order", "[mpi]") { // Set up this host's resources setLocalSlots(nLocalSlots); auto req = setRequest("order"); // Call the functions sch.callFunctions(req); checkAllocationAndResult(req); } TEST_CASE_METHOD(MpiDistTestsFixture, "Test MPI reduce", "[mpi]") { // Set up this host's resources setLocalSlots(nLocalSlots); auto req = setRequest("reduce"); // Call the functions sch.callFunctions(req); checkAllocationAndResult(req); } TEST_CASE_METHOD(MpiDistTestsFixture, "Test MPI reduce many times", "[mpi]") { // Set up this host's resources setLocalSlots(nLocalSlots); auto req = setRequest("reduce-many"); // Call the functions sch.callFunctions(req); checkAllocationAndResult(req); } TEST_CASE_METHOD(MpiDistTestsFixture, "Test MPI scan", "[mpi]") { // Set up this host's resources setLocalSlots(nLocalSlots); auto req = setRequest("scan"); // Call the functions sch.callFunctions(req); checkAllocationAndResult(req); } TEST_CASE_METHOD(MpiDistTestsFixture, "Test MPI scatter", "[mpi]") { // Set up this host's resources setLocalSlots(nLocalSlots); auto req = setRequest("scatter"); // Call the functions sch.callFunctions(req); checkAllocationAndResult(req); } TEST_CASE_METHOD(MpiDistTestsFixture, "Test MPI send", "[mpi]") { // Set up this host's resources setLocalSlots(nLocalSlots); auto req = setRequest("send"); // Call the functions sch.callFunctions(req); checkAllocationAndResult(req); } TEST_CASE_METHOD(MpiDistTestsFixture, "Test sending sync and async messages", "[mpi]") { // Set up this host's resources setLocalSlots(nLocalSlots); auto req = setRequest("send-sync-async"); // Call the functions sch.callFunctions(req); checkAllocationAndResult(req); } TEST_CASE_METHOD(MpiDistTestsFixture, "Test sending many MPI messages", "[mpi]") { // Set up this host's resources setLocalSlots(nLocalSlots); auto req = setRequest("send-many"); // Call the functions sch.callFunctions(req); checkAllocationAndResult(req); } TEST_CASE_METHOD(MpiDistTestsFixture, "Test MPI send-recv", "[mpi]") { // Set up this host's resources setLocalSlots(nLocalSlots); auto req = setRequest("sendrecv"); // Call the functions sch.callFunctions(req); checkAllocationAndResult(req); } TEST_CASE_METHOD(MpiDistTestsFixture, "Test MPI status", "[mpi]") { // Set up this host's resources setLocalSlots(nLocalSlots); auto req = setRequest("status"); // Call the functions sch.callFunctions(req); checkAllocationAndResult(req); } TEST_CASE_METHOD(MpiDistTestsFixture, "Test MPI types sizes", "[mpi]") { // Set up this host's resources setLocalSlots(nLocalSlots); auto req = setRequest("typesize"); // Call the functions sch.callFunctions(req); checkAllocationAndResult(req); } }
24.436782
80
0.686383
[ "vector" ]
df803ad51e9548e9d106ba8deef160b912cd3b00
1,218
cc
C++
old/pat/a1005.cc
xsthunder/a
3c30f31c59030d70462b71ef28c5eee19c6eddd6
[ "MIT" ]
1
2018-07-22T04:52:10.000Z
2018-07-22T04:52:10.000Z
old/pat/a1005.cc
xsthunder/a
3c30f31c59030d70462b71ef28c5eee19c6eddd6
[ "MIT" ]
1
2018-08-11T13:29:59.000Z
2018-08-11T13:31:28.000Z
old/pat/a1005.cc
xsthunder/a
3c30f31c59030d70462b71ef28c5eee19c6eddd6
[ "MIT" ]
null
null
null
const bool test=1; #include<iostream> #include<cctype> #include<algorithm> #include<cstdio> #include<cstdlib> #include<vector> #include<map> #include<queue> #include<set> #include<cctype> #include<cstring> #include<utility> #include<cmath> const int inf=0x7fffffff; #define IF if(test) #define FI if(!test) #define gts(s) fgets((s),sizeof(s),stdin) typedef long long int ll; using namespace std; typedef pair<int,int> point; template <typename T> void pA(T *begin,int n){ for(int i=0;i<n;i++){ printf("%d " ,*(begin+i)); } printf("\n"); } char ans[10][100]={ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", }; void print(int x){ //cout<<x; bool fflag =0; vector<string> vs; if(x==0)vs.push_back(string("zero")); while(x!=0){ int r=x%10; x/=10; vs.push_back(string(ans[r])); } for(auto it =vs.rbegin();it!=vs.rend();it++){ if(fflag)printf(" "); fflag=1; cout<<*it; } printf("\n"); } void sol(){ string s; cin>>s; int sum=0; for(char x:s){ if(isdigit(x)){ sum+=x-'0'; } } print(sum); } int main() { sol(); return 0; } //a1005.cc //generated automatically at Sun Nov 27 21:56:10 2016 //by xsthunder //AC at Sun Nov 27 22:11:27 2016
16.24
91
0.619869
[ "vector" ]
df888b15122aeb8f1165b43210a86d51c594d000
3,823
cpp
C++
solver/tests/TestGurobi.cpp
ferdinand-wood/kino_dynamic_opt
ba6bef170819c55d1d26e40af835a744d1ae663f
[ "BSD-3-Clause" ]
26
2019-11-18T17:39:43.000Z
2021-12-18T00:38:22.000Z
solver/tests/TestGurobi.cpp
ferdinand-wood/kino_dynamic_opt
ba6bef170819c55d1d26e40af835a744d1ae663f
[ "BSD-3-Clause" ]
25
2019-11-11T19:54:51.000Z
2021-04-07T13:41:47.000Z
solver/tests/TestGurobi.cpp
ferdinand-wood/kino_dynamic_opt
ba6bef170819c55d1d26e40af835a744d1ae663f
[ "BSD-3-Clause" ]
10
2019-12-15T14:36:51.000Z
2021-09-29T10:42:19.000Z
/** * @file TestGurobi.cpp * @author Brahayam Ponton (brahayam.ponton@tuebingen.mpg.de) * @license License BSD-3-Clause * @copyright Copyright 2018, Gurobi Optimization, LLC * @date 2019-10-07 * * @brief Formulate a classic optimization problem * * This example formulates and solves the following simple QP model: * * minimize x + y + x^2 + x*y + y^2 + y*z + z^2 * subject to x + 2 y + 3 z >= 4 * x + y >= 1 * * The example illustrates the use of dense matrices to store A and Q * (and dense vectors for the other relevant data). We don't recommend * that you use dense matrices, but this example may be helpful if you * already have your data in this format. */ #include <iostream> #include <gurobi_c++.h> #include <gtest/gtest.h> #define PRECISION 0.01 class GurobiTest : public ::testing::Test { protected: virtual void SetUp() {} virtual void TearDown() {} }; template <typename Derived1, typename Derived2> void check_matrix(const Derived1& ref, const Derived2& val) { for (int i=0; i<ref.rows(); i++) { for (int j=0; j<ref.cols(); j++) { EXPECT_NEAR(ref(i,j), val(i,j), 0.01); } } } static bool dense_optimize(GRBEnv* env, int rows, int cols, double* c, /* linear portion of objective function */ double* Q, /* quadratic portion of objective function */ double* A, /* constraint matrix */ char* sense, /* constraint senses */ double* rhs, /* RHS vector */ double* lb, /* variable lower bounds */ double* ub, /* variable upper bounds */ char* vtype, /* variable types (continuous, binary, etc.) */ double* solution, double* objvalP) { GRBModel model = GRBModel(*env); int i, j; bool success = false; /* Add variables to the model */ GRBVar* vars = model.addVars(lb, ub, NULL, vtype, NULL, cols); /* Populate A matrix */ for (i = 0; i < rows; i++) { GRBLinExpr lhs = 0; for (j = 0; j < cols; j++) if (A[i*cols+j] != 0) lhs += A[i*cols+j]*vars[j]; model.addConstr(lhs, sense[i], rhs[i]); } GRBQuadExpr obj = 0; for (j = 0; j < cols; j++) obj += c[j]*vars[j]; for (i = 0; i < cols; i++) for (j = 0; j < cols; j++) if (Q[i*cols+j] != 0) obj += Q[i*cols+j]*vars[i]*vars[j]; model.setObjective(obj); model.optimize(); if (model.get(GRB_IntAttr_Status) == GRB_OPTIMAL) { *objvalP = model.get(GRB_DoubleAttr_ObjVal); for (i = 0; i < cols; i++) solution[i] = vars[i].get(GRB_DoubleAttr_X); success = true; } delete[] vars; return success; } TEST_F(GurobiTest, GurobiTest01) { GRBEnv* env = 0; try { env = new GRBEnv(); env->set(GRB_IntParam_OutputFlag, 0); double c[] = {1, 1, 0}; double Q[3][3] = {{1, 1, 0}, {0, 1, 1}, {0, 0, 1}}; double A[2][3] = {{1, 2, 3}, {1, 1, 0}}; char sense[] = {'>', '>'}; double rhs[] = {4, 1}; double lb[] = {0, 0, 0}; bool success; double objval, sol[3]; success = dense_optimize(env, 2, 3, c, &Q[0][0], &A[0][0], sense, rhs, lb, NULL, NULL, sol, &objval); EXPECT_NEAR(0.571429, sol[0], PRECISION); EXPECT_NEAR(0.428571, sol[1], PRECISION); EXPECT_NEAR(0.857143, sol[2], PRECISION); } catch(GRBException e) { std::cout << "Error code = " << e.getErrorCode() << std::endl; std::cout << e.getMessage() << std::endl; } catch(...) { std::cout << "Exception during optimization" << std::endl; } delete env; }
29.635659
107
0.531781
[ "vector", "model" ]
df959254726aac3add6eb30735cd81529547554d
1,328
hh
C++
SockServer.hh
shuLhan/libvos
831491b197fa8f267fd94966d406596896e6f25c
[ "BSD-3-Clause" ]
1
2017-09-14T13:31:16.000Z
2017-09-14T13:31:16.000Z
SockServer.hh
shuLhan/libvos
831491b197fa8f267fd94966d406596896e6f25c
[ "BSD-3-Clause" ]
null
null
null
SockServer.hh
shuLhan/libvos
831491b197fa8f267fd94966d406596896e6f25c
[ "BSD-3-Clause" ]
5
2015-04-11T02:59:06.000Z
2021-03-03T19:45:39.000Z
// // Copyright 2009-2017 M. Shulhan (ms@kilabit.info). All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #ifndef _LIBVOS_SOCKSERVER_HH #define _LIBVOS_SOCKSERVER_HH 1 #include <sys/time.h> #include "List.hh" #include "Socket.hh" namespace vos { /** * @class : SockServer * @attr : * - _timeout : time data used by socket as server. * - _client_lock : lock for accessing list of clients object. * - _clients : list of client connections. * - ADDR_WILCARD : static, wilcard address for IPv4. * - ADDR_WILCARD6 : static, wilcard address for IPv6. * @desc : * Module for creating socket as server. */ class SockServer : public Socket { public: SockServer(); ~SockServer(); int bind(const char* address, const uint16_t port); int listen(const unsigned int queue_len = 0); int bind_listen(const char* address, const uint16_t port); Error accept_conn(Socket** client); void add_client(Socket* client); void remove_client(Socket* client); struct timeval _timeout; List* _clients; static const char* ADDR_WILCARD; static const char* ADDR_WILCARD6; static const char* __cname; private: SockServer(const SockServer&); void operator=(const SockServer&); }; } /* namespace::vos */ #endif // vi: ts=8 sw=8 tw=78:
22.896552
73
0.711596
[ "object" ]
df9914deff6b21af2a491178c1ef4df87c38bed6
997
cpp
C++
android-31/android/net/vcn/VcnConfig_Builder.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/android/net/vcn/VcnConfig_Builder.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-31/android/net/vcn/VcnConfig_Builder.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "../../content/Context.hpp" #include "./VcnConfig.hpp" #include "./VcnGatewayConnectionConfig.hpp" #include "./VcnConfig_Builder.hpp" namespace android::net::vcn { // Fields // QJniObject forward VcnConfig_Builder::VcnConfig_Builder(QJniObject obj) : JObject(obj) {} // Constructors VcnConfig_Builder::VcnConfig_Builder(android::content::Context arg0) : JObject( "android.net.vcn.VcnConfig$Builder", "(Landroid/content/Context;)V", arg0.object() ) {} // Methods android::net::vcn::VcnConfig_Builder VcnConfig_Builder::addGatewayConnectionConfig(android::net::vcn::VcnGatewayConnectionConfig arg0) const { return callObjectMethod( "addGatewayConnectionConfig", "(Landroid/net/vcn/VcnGatewayConnectionConfig;)Landroid/net/vcn/VcnConfig$Builder;", arg0.object() ); } android::net::vcn::VcnConfig VcnConfig_Builder::build() const { return callObjectMethod( "build", "()Landroid/net/vcn/VcnConfig;" ); } } // namespace android::net::vcn
25.564103
141
0.727182
[ "object" ]
df9cc0448607443a4e72992352d4f2aae9fe0805
12,910
cc
C++
LimitCalc/src/RooFit_MCTemplate.cc
NTUHEP-Tstar/TstarAnalysis
d3bcdf6f0fd19b9a34bbacb1052143856917bea7
[ "MIT" ]
null
null
null
LimitCalc/src/RooFit_MCTemplate.cc
NTUHEP-Tstar/TstarAnalysis
d3bcdf6f0fd19b9a34bbacb1052143856917bea7
[ "MIT" ]
null
null
null
LimitCalc/src/RooFit_MCTemplate.cc
NTUHEP-Tstar/TstarAnalysis
d3bcdf6f0fd19b9a34bbacb1052143856917bea7
[ "MIT" ]
null
null
null
/******************************************************************************* * * Filename : RooFit_MCTemplate.cc * Description : Plotting to file for template methods.cc * Author : Yi-Mu "Enoch" Chen [ ensc@hep1.phys.ntu.edu.tw ] * *******************************************************************************/ #include "TstarAnalysis/LimitCalc/interface/Common.hpp" #include "TstarAnalysis/LimitCalc/interface/MakeKeysPdf.hpp" #include "TstarAnalysis/LimitCalc/interface/SampleRooFitMgr.hpp" #include "TstarAnalysis/LimitCalc/interface/SimFit.hpp" #include "TstarAnalysis/LimitCalc/interface/Template.hpp" #include "ManagerUtils/Maths/interface/RooFitExt.hpp" #include "ManagerUtils/PlotUtils/interface/Common.hpp" #include "ManagerUtils/PlotUtils/interface/RooFitUtils.hpp" #include "TstarAnalysis/Common/interface/PlotStyle.hpp" #include <boost/format.hpp> #include <fstream> #include <string> #include "RooDataSet.h" #include "RooNLLVar.h" #include "RooMinimizer.h" using namespace std; using namespace mgr; /******************************************************************************* * Object naming convention *******************************************************************************/ string TemplatePdfName( const std::string& datasetname ) { return datasetname + "template"; } extern const string StitchTemplatePdfName = "templatemaster"; /******************************************************************************* * Main control flow to be caleed by main function *******************************************************************************/ void MakeTemplate( SampleRooFitMgr* data, SampleRooFitMgr* bg, vector<SampleRooFitMgr*>& signal_list ) { vector<RooAbsPdf*> pdflist; vector<RooAbsReal*> funclist; for( auto& sig : signal_list ){ pdflist.push_back( MakeFullKeysPdf( sig ) ); // funclist.push_back( sig->Func(StitchKeyNormName)); } auto fitresultlist = MakeFullTemplate( bg ); MakeTemplatePlot( data, bg, signal_list.front(), fitresultlist.front(), true ); MakeTemplatePlot( data, bg, signal_list.front(), fitresultlist.front(), false ); pdflist.push_back( bg->Pdf( StitchTemplatePdfName ) ); SaveRooWorkSpace( data->DataSet( "" ), pdflist, {} ); for( auto& signal : signal_list ){ MakeTemplateCardFile( data, bg, signal ); } } /******************************************************************************* * Fitting function implementations *******************************************************************************/ RooFitResult* FitBackgroundTemplate( SampleRooFitMgr* bg, const string& datatag ) { const string bgpdfname = TemplatePdfName( datatag ); RooAbsPdf* bgpdf = bg->NewPdf( bgpdfname, limnamer.GetInput<string>( "fitfunc" ) ); // Manually calling NNL minizer functions static RooCmdArg min = RooFit::Minimizer( "Minuit", "Migrad" ); static RooCmdArg sumerr = RooFit::SumW2Error( kTRUE ); static RooCmdArg hesse = RooFit::Minos( kTRUE ); static RooCmdArg save = RooFit::Save(); //static RooCmdArg ncpu = RooFit::NumCPU( 6 ); static RooCmdArg verb = RooFit::Verbose( kFALSE ); static RooCmdArg printl = RooFit::PrintLevel( -1 ); static RooCmdArg printe = RooFit::PrintEvalErrors( -1 ); static RooCmdArg printw = RooFit::Warnings( kFALSE ); RooLinkedList fitopt; fitopt.Add( &min ); fitopt.Add( &sumerr ); fitopt.Add( &hesse ); fitopt.Add( &save ); //fitopt.Add( &ncpu ); fitopt.Add( &verb ); fitopt.Add( &printl ); fitopt.Add( &printe ); fitopt.Add( &printw ); const unsigned maxiter = 30; unsigned iter = 0 ; RooFitResult* ans = NULL ; while( !ans ){ ans = bgpdf->fitTo( *( bg->DataSet(datatag) ), fitopt ); if( ans->status() ){ // Not properly converged iter++; if( iter > maxiter ) { break; } delete ans; ans = NULL; } } cout << ">>>> BKG FIT iteration: " << iter << endl; bg->SetConstant( kTRUE );// Freezing all constants return ans; } /******************************************************************************/ vector<RooFitResult*> MakeFullTemplate( SampleRooFitMgr* bg ) { vector<string> bgpdflist; vector<RooFitResult*> ans; for( const auto& datasetname : bg->SetNameList() ){ ans.push_back( FitBackgroundTemplate( bg, datasetname ) ); bgpdflist.push_back( TemplatePdfName( datasetname ) ); } MakeSimpleStitchPdf( bg, StitchTemplatePdfName, bgpdflist ); return ans; } /******************************************************************************/ void MakeTemplateCardFile( SampleRooFitMgr* data, SampleRooFitMgr* bg, SampleRooFitMgr* sig ) { RooAbsData* dataobs = data->DataSet( "" ); RooAbsPdf* bgpdf = bg->Pdf( StitchTemplatePdfName ); RooAbsPdf* sigpdf = sig->Pdf( StitchKeyPdfName ); ofstream cardfile( limnamer.TextFileName( "card", {sig->Name()} ) ); MakeCardCommon( cardfile, dataobs, bgpdf, sigpdf ); cardfile << boost::format( "%12s %15lf %15lf" ) % "rate" % sig->DataSet()->sumEntries() % bg->DataSet()->sumEntries() << endl; cardfile << "----------------------------------------" << endl; const Parameter null( 0, 0, 0 ); const Parameter lumi( 1, 0.062, 0.062 ); const Parameter lepunc( 1, 0.03, 0.03 ); const Parameter sigstatunc = sig->Sample().SelectionEfficiency(); const Parameter bkgstatunc( 1, 0.03, 0.03 );// includes uncertaintly from cross section and selection effiency const Parameter sigjecunc = GetMCNormError( sig, "jecUp", "jecDown" ); const Parameter sigjerunc = GetMCNormError( sig, "jetresUp", "jetresDown" ); const Parameter siglepunc = GetMCNormError( sig, "lepUp", "lepDown" ); const Parameter sigbtagunc = GetMCNormError( sig, "btagUp", "btagDown" ); const Parameter sigpuunc = GetMCNormError( sig, "puUp", "puDown" ); const Parameter sigpdfunc = GetMCNormError( sig, "pdfUp", "pdfDown" ); const Parameter bkgjecunc = GetMCNormError( bg, "jecUp", "jecDown" ); const Parameter bkgjerunc = GetMCNormError( bg, "jetresUp", "jetresDown" ); const Parameter bkglepunc = GetMCNormError( bg, "lepUp", "lepDown" ); const Parameter bkgbtagunc = GetMCNormError( bg, "btagUp", "btagDown" ); const Parameter bkgpuunc = GetMCNormError( bg, "puUp", "puDown" ); const Parameter bkgpdfunc = GetMCNormError( bg, "pdfUp", "pdfDown" ); PrintNuisanceFloats( cardfile, "Lumi", "lnN", lumi, lumi ); PrintNuisanceFloats( cardfile, "lepsys", "lnN", lepunc, lepunc ); PrintNuisanceFloats( cardfile, "sigstat", "lnN", sigstatunc, null ); PrintNuisanceFloats( cardfile, "bkgstat", "lnN", null, bkgstatunc ); PrintNuisanceFloats( cardfile, "jec", "lnN", sigjecunc, bkgjecunc ); PrintNuisanceFloats( cardfile, "jer", "lnN", sigjerunc, bkgjerunc ); PrintNuisanceFloats( cardfile, "lep", "lnN", siglepunc, bkglepunc ); PrintNuisanceFloats( cardfile, "btag", "lnN", sigbtagunc, bkgbtagunc ); PrintNuisanceFloats( cardfile, "pileup", "lnN", sigpuunc, bkgpuunc ); PrintNuisanceFloats( cardfile, "pdf", "lnN", sigpdfunc, bkgpdfunc ); // Getting fitting parameters for( const auto& var : bg->VarContains( "template" ) ){ const string varname = var->GetName(); if( varname.find( "coeff" ) == string::npos ){ PrintFloatParam( cardfile, var ); } } // Getting stitching co-efficiencts for( const auto& var : bg->VarContains( "coeff" ) ){ PrintFlatParam( cardfile, var ); } for( const auto& var : sig->VarContains( "coeff" ) ){ PrintFlatParam( cardfile, var ); } cardfile.close(); } /******************************************************************************* * Plotting fit results *******************************************************************************/ void MakeTemplatePlot( SampleRooFitMgr* data, SampleRooFitMgr* mc, SampleRooFitMgr* signal, RooFitResult* fitresult, const bool use_data ) { // First plot against MC const double TotalLuminosity = mgr::SampleMgr::TotalLuminosity(); const double xmin = SampleRooFitMgr::x().getMin(); const double xmax = SampleRooFitMgr::x().getMax(); TCanvas* c = mgr::NewCanvas(); TPad* toppad = mgr::NewTopPad(); TPad* botpad = mgr::NewBottomPad(); RooPlot* frame = SampleRooFitMgr::x().frame(); // Objects to draw RooDataSet* set = (RooDataSet*)( use_data ? data->DataSet() : mc->DataSet() ); RooAbsPdf* bkgpdf = mc->Pdf( TemplatePdfName( "" ) );// Taking central value only RooAbsPdf* sigpdf = signal->Pdf( StitchKeyPdfName ); /******************************************************************************* * Objects for drawing top pad *******************************************************************************/ toppad->Draw(); toppad->cd(); TGraph* setplot = mgr::PlotOn( frame, set, RooFit::DrawOption( PGS_DATA ) ); TGraph* pdfplot = mgr::PlotFitErrorOn( frame, bkgpdf, fitresult, RooFit::Normalization( set->sumEntries(), RooAbsReal::NumEvent ) ); TGraph* sigplot = mgr::PlotOn( frame, sigpdf, RooFit::DrawOption( PGS_SIGNAL ), RooFit::Normalization( signal->ExpectedYield(), RooAbsReal::NumEvent ) ); tstar::RemoveDataXBar( (TGraphAsymmErrors*)setplot ); // Typical styling options frame->Draw(); frame->SetMinimum( 0.3 ); mgr::SetTopPlotAxis( frame ); frame->SetTitle(""); c->cd(); /******************************************************************************* * Objects for drawing bottom pad *******************************************************************************/ botpad->Draw(); botpad->cd(); TGraphAsymmErrors* bgrelplot = mgr::DividedGraph( (TGraphAsymmErrors*)pdfplot, pdfplot ); TGraphAsymmErrors* datarelplot = mgr::DividedGraph( (TGraphAsymmErrors*)setplot, pdfplot ); tstar::RemoveDataXBar( datarelplot ); bgrelplot->Draw( "AL3" ); datarelplot->Draw( PGS_DATA ); TLine cen( xmin, 1, xmax, 1 ); TLine lineup( xmin, 1.5, xmax, 1.5 ); TLine linedown( xmin, 0.5, xmax, 0.5 ); cen.Draw(); cen.SetLineColor( KBLUE ); cen.SetLineWidth( 2 ); lineup.Draw(); lineup.SetLineColor( kBlack ); lineup.SetLineStyle( 3 ); linedown.Draw(); linedown.SetLineColor( kBlack ); linedown.SetLineStyle( 3 ); // Title setting bgrelplot->GetXaxis()->SetTitle( frame->GetXaxis()->GetTitle() ); bgrelplot->GetXaxis()->SetRangeUser( xmin, xmax ); bgrelplot->GetYaxis()->SetTitle( "Data/Bkg.fit" ); bgrelplot->SetMaximum( 1.6 ); bgrelplot->SetMinimum( 0.4 ); mgr::SetBottomPlotAxis( bgrelplot ); c->cd(); /******************************************************************************* * Common styling and additiona objects *******************************************************************************/ tstar::SetSignalStyle( sigplot ); tstar::SetFitBGStyle( pdfplot ); tstar::SetSignalStyle( sigplot ); tstar::SetFitBGStyle( bgrelplot ); tstar::SetDataStyle( datarelplot ); tstar::SetDataStyle( setplot ); // Legend entries const double legend_x_min = 0.65; const double legend_y_min = 0.70; TLegend* l = mgr::NewLegend( legend_x_min, legend_y_min ); boost::format sigfmt( "%s" ); const string sigentry = str( sigfmt % signal->RootName() ); const string dataentry = ( use_data ) ? "Data" : "M.C. Bkg."; const string fitentry = string( "Bkg. fit to MC" ) + ( use_data ? "(Norm.)" : "" ); l->AddEntry( setplot, dataentry.c_str(), "pe" ); l->AddEntry( pdfplot, fitentry.c_str(), "l" ); l->AddEntry( sigplot, sigentry.c_str(), "l" ); l->Draw(); // Additional information plotting boost::format goffmt( "K = %.3lf" ); const double ksprob = KSTest( *( set ), *( bkgpdf ), SampleRooFitMgr::x() ); const string gofentry = str( goffmt % ksprob ); mgr::DrawCMSLabel(); mgr::DrawLuminosity( TotalLuminosity ); LatexMgr latex; latex.SetOrigin( PLOT_X_MIN, PLOT_Y_MAX + TEXT_MARGIN/2, TOP_LEFT ) .WriteLine( limnamer.GetChannelEXT( "Root Name" ) ) .SetOrigin( PLOT_X_TEXT_MAX, legend_y_min-TEXT_MARGIN, TOP_RIGHT ) .WriteLine( gofentry ); // Range setting and saving const double ymax = mgr::GetYmax( pdfplot, setplot, sigplot ); frame->SetMaximum( ymax * 1.5 ); const string rootfile = limnamer.PlotRootFile(); const string lastag = use_data ? "fitmc-vs-data" : "fitmc-vs-mc"; mgr::SaveToPDF( c, limnamer.PlotFileName( "", "fitplot", signal->Name(), lastag ) ); mgr::SaveToROOT( c, rootfile, limnamer.PlotFileName( "fitplot", signal->Name(), lastag ) ); frame->SetMaximum( ymax * 300 ); toppad->SetLogy( kTRUE ); mgr::SaveToPDF( c, limnamer.PlotFileName( "fitplot", signal->Name(), lastag, "log" ) ); // Cleaning up delete frame; delete c; delete l; }
34.891892
112
0.58993
[ "object", "vector" ]
dfa30f25cb4c2c661c14a76c9883dd4afb8763f1
28,046
cpp
C++
projects/Ader2_CPP/src/MonoWrap/MonoManager.cpp
nfwGytautas/Ader2
c32789ca4e8efb0da47a81c81779727298618f3e
[ "Apache-2.0" ]
null
null
null
projects/Ader2_CPP/src/MonoWrap/MonoManager.cpp
nfwGytautas/Ader2
c32789ca4e8efb0da47a81c81779727298618f3e
[ "Apache-2.0" ]
null
null
null
projects/Ader2_CPP/src/MonoWrap/MonoManager.cpp
nfwGytautas/Ader2
c32789ca4e8efb0da47a81c81779727298618f3e
[ "Apache-2.0" ]
null
null
null
#include "MonoManager.h" // For find_if #include <algorithm> // For browsing directories #include <filesystem> // For reading assembly to memory #include <fstream> // Engine messages #include "Enums/Messages.h" // Logger #include "Utility/Log.h" // Assert #include "Defs.h" // Field attributes #include <mono/metadata/attrdefs.h> #include <mono/metadata/mono-gc.h> #include <mono/metadata/threads.h> #include <mono/metadata/tokentype.h> #ifdef ADER_MACRO_DEBUG #include <mono/utils/mono-logger.h> #include <mono/metadata/mono-debug.h> #endif // Definitions #define ASSEMBLY_NAME "Ader2_SHARP.dll" #define SCRIPT_NAMESPACE "Ader2" #define ENGINE_NAMESPACE "Ader2.Core" #define ASSETS_NAMESPACE "Ader2.Core" #define SCENE_NAMESPACE "Ader2" #define SCRIPT_CLASS_NAME "AderScript" #define ENGINE_CLASS_NAME "AderEngine" #define SCENE_CLASS_NAME "AderScene" #define ASSETS_CLASS_NAME "AderAssets" #define SCRIPT_CLASS_FILTER(x) (x == "Internal" || x == "<Module>") #include <iostream> #include "MonoWrap/GLUE/InternalCalls.h" MonoManager* MonoManager::ms_pStaticThis = nullptr; MonoManager::MonoManager() : m_pAderScriptBase(new AderScriptBase()), m_pAderEngine(new AderEngineSharp()), m_pAderSceneBase(new AderSceneBase()), m_pAderAssets(new AderAssetsSharp()) { ms_pStaticThis = this; } MonoManager::~MonoManager() { if (m_pAderScriptBase) { delete m_pAderScriptBase; } if (m_pAderEngine) { delete m_pAderEngine; } if (m_pAderSceneBase) { delete m_pAderSceneBase; } if (m_pAderAssets) { delete m_pAderAssets; } } Memory::reference<SharpDomain> MonoManager::getDomain() { return m_appDomain; } void MonoManager::addInternalCall(const std::string& name, const void* callback) { // Add a mono internal call mono_add_internal_call(name.c_str(), callback); } bool MonoManager::canShutdown() { // Currently not blocking return true; } void MonoManager::shutdown() { // Destroy the current domain first m_appDomain = nullptr; // Clean up the domain mono_jit_cleanup(m_pMainDomain); } int MonoManager::onMessage(MessageBus::MessageType msg, MessageBus::DataType pData) { switch (msg) { case Messages::msg_Setup: return setup(); case Messages::msg_LoadAssemblies: return loadAssemblies(*static_cast<const std::string*>(pData)); case Messages::msg_ReloadAssemblies: return reloadAssemblies(); case Messages::msg_LoadScripts: return loadScripts(); case Messages::msg_InitScripts: return initScripts(); case Messages::msg_ScriptUpdate: return updateScripts(); case Messages::msg_StateBundleCreated: return setStateBundle(pData); case Messages::msg_LoadAderScenes: return loadAderScenes(); } return 0; } int MonoManager::setup() { // Set directories where mono libraries are at // By default using premake they will be copied to // lib and etc folders in the output folder mono_set_dirs("mono/lib", "mono/etc"); // Load the default Mono configuration file, this is needed // if you are planning on using the dll maps defined on the // system configuration mono_config_parse(NULL); #ifdef ADER_MACRO_DEBUG // clang-format off const char* options[] = { "--soft-breakpoints", "--debugger-agent=transport=dt_socket,suspend=n,server=y,address=127.0.0.1:55555,embedding=1", "--debug-domain-unload", // GC options: // check-remset-consistency: Makes sure that write barriers are properly issued in native code, // and therefore // all old->new generation references are properly present in the remset. This is easy to mess // up in native code by performing a simple memory copy without a barrier, so it's important to // keep the option on. // verify-before-collections: Unusure what exactly it does, but it sounds like it could help track // down // things like accessing released/moved objects, or attempting to release handles for an // unloaded domain. // xdomain-checks: Makes sure that no references are left when a domain is unloaded. "--gc-debug=check-remset-consistency,verify-before-collections,xdomain-checks" }; // clang-format on mono_jit_parse_options(sizeof(options) / sizeof(char*), const_cast<char**>(options)); mono_debug_init(MONO_DEBUG_FORMAT_MONO); #endif // Create the mono domain m_pMainDomain = mono_jit_init_version("MonoManager", "v4.0.30319"); // Initialize engine initEngine(); // Add internal calls addInternalCalls(); return 0; } int MonoManager::loadAssemblies(const std::string& assemblyDirectory) { // Check if haven't loaded this directory already if (std::find(m_loadDirs.begin(), m_loadDirs.end(), assemblyDirectory) == m_loadDirs.end()) { m_loadDirs.push_back(assemblyDirectory); } // Iterate over all files inside the directory and then load them for (const auto& entry : std::filesystem::directory_iterator(assemblyDirectory)) { // Make sure we are looking at a file if (!entry.is_directory()) { auto& path = entry.path(); // Check for .dll extension if(path.has_extension() && path.extension() == ".dll") { std::string& file = path.filename().string(); LOG_DEBUG("Loading assembly '{0}/{1}'", assemblyDirectory, file); m_appDomain->loadAssembly(assemblyDirectory, file); } } } return 0; } int MonoManager::reloadAssemblies() { int result = 0; this->postMessage(Messages::msg_ClearAssets); // Dereference the engine assembly so it can be cleaned up m_engineAssembly = nullptr; // Clear all scripts m_scripts.clear(); // Clear all scenes m_scenes.clear(); // Unload the domain m_appDomain->unload(); // Initialize engine initEngine(); // Set states if (m_pStates) { // Set fields setFields(); } // Iterate over all load directories for (const std::string& dir : m_loadDirs) { result = loadAssemblies(dir); if (result != 0) { LOG_ERROR("reloadAssemblies.loadAssemblies error '{0}' with '{1}'", result, dir); result = 0; } } // Load all scripts result = loadScripts(); // Load all scenes result = loadAderScenes(); // Invoke init on all scripts result = initScripts(); return result; } int MonoManager::loadScripts() { // Iterate over all assembly classes that inherit AderScript for (const Memory::reference<SharpClass>& klass : m_appDomain->getClassInherits(m_pAderScriptBase->Klass)) { // Push back the new script m_scripts.push_back(new AderScript(m_pAderScriptBase, klass)); LOG_DEBUG("Loaded '{0}' script", klass->getName()); } // Construct all classes for (const Memory::reference<AderScript>& script : m_scripts) { script->invokeConstruct(); } return 0; } int MonoManager::initScripts() { // Invoke all updates for (const Memory::reference<AderScript>& script : m_scripts) { // Invoke Update Memory::reference<SharpException> ex = script->invokeInit(); // Check if there was an exception if (ex.valid()) { LOG_WARN("Script '{0}' raised an exception!\n Message: '{1}'\n Stack trace:\n{2}", script->getName(), ex->getMessage(), ex->getStackTrace()); } } return 0; } int MonoManager::updateScripts() { // Invoke all updates for (const Memory::reference<AderScript>& script : m_scripts) { // Invoke Update Memory::reference<SharpException> ex = script->invokeUpdate(); // Check if there was an exception if (ex.valid()) { LOG_WARN("Script '{0}' raised an exception!\n Message: '{1}'\n Stack trace:\n{2}", script->getName(), ex->getMessage(), ex->getStackTrace()); } } return 0; } int MonoManager::setStateBundle(void* pState) { m_pStates = static_cast<StateBundle*>(pState); // Set fields setFields(); return 0; } void MonoManager::initEngine() { // Create domain m_appDomain = new SharpDomain("Domain" + m_appDomainIter++); // Load the engine assembly m_engineAssembly = m_appDomain->loadAssembly("", ASSEMBLY_NAME); // Assign engine variables m_pAderEngine->Klass = m_engineAssembly->getClass(ENGINE_NAMESPACE, ENGINE_CLASS_NAME); m_pAderEngine->FieldWndState = m_pAderEngine->Klass->getField("_wndState"); m_pAderEngine->FieldKeyState = m_pAderEngine->Klass->getField("_keyState"); // Assign script base variables m_pAderScriptBase->Klass = m_engineAssembly->getClass(SCRIPT_NAMESPACE, SCRIPT_CLASS_NAME); m_pAderScriptBase->Constructor = m_pAderScriptBase->Klass->getMethod(".ctor", "", false); m_pAderScriptBase->Init = m_pAderScriptBase->Klass->getMethod("Init", "", false); m_pAderScriptBase->Update = m_pAderScriptBase->Klass->getMethod("Update", "", false); // Assign scene base variables m_pAderSceneBase->Klass = m_engineAssembly->getClass(SCENE_NAMESPACE, SCENE_CLASS_NAME); m_pAderSceneBase->Constructor = m_pAderSceneBase->Klass->getMethod(".ctor", "", false); m_pAderSceneBase->LoadAssets = m_pAderSceneBase->Klass->getMethod("LoadAssets", "", false); m_pAderSceneBase->_CInstance = m_pAderSceneBase->Klass->getField("_CInstance"); // Assign assets variables m_pAderAssets->Klass = m_engineAssembly->getClass(ASSETS_NAMESPACE, ASSETS_CLASS_NAME); m_pAderAssets->_CInstance = m_pAderAssets->Klass->getField("_CInstance"); // Transmit the interface this->postMessage(Messages::msg_TransmitAssets, m_pAderAssets); } void MonoManager::setFields() { // Window state m_pAderEngine->FieldWndState->setValue(nullptr, &m_pStates->WndState); // Key state m_pAderEngine->FieldKeyState->setValue(nullptr, &m_pStates->KeyState); } int MonoManager::loadAderScenes() { // Iterate over all assembly classes that inherit AderScript for (const Memory::reference<SharpClass>& klass : m_appDomain->getClassInherits(m_pAderSceneBase->Klass)) { // Push back the new script m_scenes.push_back(new AderScene(m_pAderSceneBase, klass)); LOG_DEBUG("Loaded '{0}' scene", klass->getName()); } // Construct all classes for (const Memory::reference<AderScene>& scene : m_scenes) { scene->invokeConstruct(); } // Transmit scenes to the SceneManager this->postMessage(Messages::msg_TransmitScenes, &m_scenes); // Load the scene this->postMessage(Messages::msg_LoadCurrentScene); return 0; } void MonoManager::addInternalCalls() { AderInternals::addInternals(); } SharpDomain::SharpDomain(const std::string& name) { // Create domain m_pDomain = mono_domain_create_appdomain(const_cast<char*>(name.c_str()), nullptr); // Set the domain if (mono_domain_set(m_pDomain, 0)) { mono_thread_attach(m_pDomain); } } std::vector<Memory::reference<SharpClass>> SharpDomain::getClassInherits(Memory::reference<SharpClass> base) { std::vector<Memory::reference<SharpClass>> result; // Iterate over each loaded assembly for (const Memory::reference<SharpAssembly>& assembly : m_assemblies) { // Iterate over all assembly classes for (const Memory::reference<SharpClass>& klass : assembly->getAllClasses()) { // Check if class inherits from AderScript if (klass->hasBaseClass() && klass->hasBaseClass(base) && klass->getName() != base->getName()) { // Push back the new script result.push_back(klass); } } } return result; } MonoString* SharpDomain::createString(const std::string& from) { return mono_string_new(m_pDomain, from.c_str()); } Memory::relay_ptr<SharpAssembly> SharpDomain::loadAssembly(const std::string& folder, const std::string& name) { // Create the SharpAssembly Memory::reference<SharpAssembly> assembly = new SharpAssembly(m_pDomain, folder, name); // Check if it loaded correctly, return nullptr if it didn't if (assembly->loaded()) { m_assemblies.push_back(assembly); return assembly.asRelay(); } else { return nullptr; } } Memory::relay_ptr<SharpAssembly> SharpDomain::getAssembly(const std::string& name) { // Find assemblies where the name matches auto it = std::find_if(m_assemblies.begin(), m_assemblies.end(), [&](const Memory::reference<SharpAssembly>& assembly) { return assembly->getName() == name; }); // Check if assembly was found return invalid reference otherwise if (it == m_assemblies.end()) { return nullptr; } // Return reference to the assembly return (*it).asRelay(); } Memory::reference<SharpClass> SharpDomain::getClass(const std::string& nSpace, const std::string& name) { for (const Memory::reference<SharpAssembly>& assembly : m_assemblies) { Memory::reference<SharpClass> klass = assembly->getClass(nSpace, name); if (klass.valid()) { return klass; } } return nullptr; } SharpDomain::~SharpDomain() { if (!m_unloaded) { unload(); } } void SharpDomain::unload() { if (m_unloaded) { LOG_WARN("Unloading the same domain multiple times!"); return; } // Get the root and set it as the main domain MonoDomain* root = mono_get_root_domain(); if(mono_domain_set(root, 0)) { // Unload domain mono_domain_unload(m_pDomain); // Clean all objects mono_gc_collect(mono_gc_max_generation()); // Clear all loaded assemblies // This causes all assemblies to close their images and assemblies m_assemblies.clear(); } m_unloaded = true; } SharpAssembly::SharpAssembly(MonoDomain* pDomain, const std::string& folder, const std::string& name) : m_pDomain(pDomain), m_name(name) { std::string path; // Create the path to assembly if (folder == "") { path = name; } else { path = folder + "/" + name; } // For release builds we load it as #ifdef ADER_MACRO_RELEASE // Try to load the assembly m_pAssembly = mono_domain_assembly_open(m_pDomain, path.c_str()); // Check if the assembly was loaded correctly if (!m_pAssembly) { LOG_WARN("'{0}' could not be loaded!", path); return; } // Create an image of the assembly m_pImage = mono_assembly_get_image(m_pAssembly); // Check if the image was created correctly if (!m_pImage) { LOG_WARN("'{0}' image could not be created!", path); return; } #else // Else we read the entire assembly to memory this doesn't lock the file // and allows for easy reloading // Open the file and get the last position std::ifstream ifs(path, std::ios::binary | std::ios::ate); std::ifstream::pos_type pos = ifs.tellg(); // Initialize vector buffer std::vector<char> assemblyContents(pos); // Seek start and copy contents to vector ifs.seekg(0, std::ios::beg); ifs.read(assemblyContents.data(), pos); // Create image MonoImageOpenStatus status; m_pImage = mono_image_open_from_data_with_name(assemblyContents.data(), assemblyContents.size(), 1, &status, 0, path.c_str()); if (status != MONO_IMAGE_OK || m_pImage == nullptr) { LOG_WARN("'{0}' image could not be created!", path); return; } // load the assembly m_pAssembly = mono_assembly_load_from_full(m_pImage, path.c_str(), &status, false); if (status != MONO_IMAGE_OK || m_pAssembly == nullptr) { mono_image_close(m_pImage); LOG_WARN("'{0}' could not be loaded!", path); return; } #endif } SharpAssembly::~SharpAssembly() { #ifndef ADER_MACRO_RELEASE mono_image_close(m_pImage); #endif } Memory::reference<SharpClass> SharpAssembly::getClass(const std::string& nSpace, const std::string& name) const { // Create the SharpClass Memory::reference<SharpClass> klass = new SharpClass(m_pDomain, m_pImage, nSpace, name); // Check if it loaded correctly, return nullptr if it didn't if (klass->loaded()) { return klass; } else { return nullptr; } } std::vector<Memory::reference<SharpClass>> SharpAssembly::getAllClasses() const { // Vector that will contain all found classes std::vector<Memory::reference<SharpClass>> foundClasses; // Get the number of rows in the metadata table int numRows = mono_image_get_table_rows(m_pImage, MONO_TABLE_TYPEDEF); for (int i = 0; i < numRows; i++) // Skip Module { // Get class MonoClass* monoClass = mono_class_get(m_pImage, (i + 1) | MONO_TOKEN_TYPE_DEF); // Check if the class is found if (monoClass != nullptr) { Memory::reference<SharpClass> klass = new SharpClass(m_pDomain, m_pImage, monoClass); // Filter classes if (!SCRIPT_CLASS_FILTER(klass->getName())) { foundClasses.push_back(klass); } } } return foundClasses; } const std::string& SharpAssembly::getName() const { return m_name; } bool SharpAssembly::loaded() { return m_pAssembly != nullptr; } SharpClass::SharpClass(MonoDomain* pDomain, MonoImage* pImage, const std::string& nSpace, const std::string& name) : m_pDomain(pDomain), m_pImage(pImage) { // Create class m_pClass = mono_class_from_name(m_pImage, nSpace.c_str(), name.c_str()); // Check if the class was created correctly if (!m_pClass) { LOG_WARN("'{0}.{1}' class could not be created. It was not found or doesn't exist!", nSpace, name); return; } m_name = mono_class_get_name(m_pClass); m_nSpace = mono_class_get_namespace(m_pClass); } SharpClass::SharpClass(MonoDomain* pDomain, MonoImage* pImage, MonoClass* pClass) : m_pDomain(pDomain), m_pImage(pImage), m_pClass(pClass) { m_name = mono_class_get_name(m_pClass); m_nSpace = mono_class_get_namespace(m_pClass); } const std::string& SharpClass::getName() { return m_name; } const std::string& SharpClass::getNamespace() { return m_nSpace; } bool SharpClass::hasBaseClass() { return mono_class_get_parent(m_pClass) != nullptr; } bool SharpClass::hasBaseClass(Memory::reference<SharpClass> base) { return mono_class_is_subclass_of(m_pClass, base->m_pClass, 1) == 1; } Memory::reference<SharpClass> SharpClass::getBaseClass() { return new SharpClass(m_pDomain, m_pImage, mono_class_get_parent(m_pClass)); } void SharpClass::addInternalCall(const std::string& name, const void* callback) { // Construct the signature and map it to the callback mono_add_internal_call(methodSignature(name, "", false).c_str(), callback); } MonoObject* SharpClass::invokeMethod(const std::string& name, const std::string& signatureParams, void** params) { // Build a method description object MonoMethodDesc* methodDesc = mono_method_desc_new(methodSignature(name, signatureParams, true).c_str(), NULL); // Search the method in the image MonoMethod* method = mono_method_desc_search_in_image(methodDesc, m_pImage); // Free memory mono_method_desc_free(methodDesc); // Invoke the method return mono_runtime_invoke(method, nullptr, params, nullptr); } std::vector<Memory::reference<SharpMethod>> SharpClass::getAllMethods() { std::vector<Memory::reference<SharpMethod>> methods; void* iter = NULL; MonoMethod* method; while (method = mono_class_get_methods(m_pClass, &iter)) { methods.push_back(new SharpMethod(method)); } return methods; } Memory::reference<SharpMethod> SharpClass::getMethod(const std::string& name, const std::string& params, bool isStatic) { // Create the SharpClass Memory::reference<SharpMethod> method = new SharpMethod(m_pImage, methodSignature(name, params, isStatic)); // Check if it loaded correctly, return nullptr if it didn't if (method->loaded()) { return method; } else { return nullptr; } } Memory::reference<SharpProperty> SharpClass::getProperty(const std::string& name) { return Memory::reference<SharpProperty>(new SharpProperty(m_pClass, name)); } std::vector<Memory::reference<SharpProperty>> SharpClass::getAllProperties() { // All properties std::vector<Memory::reference<SharpProperty>> properties; // Iterate over properties void* iter = nullptr; MonoProperty* itProperty = mono_class_get_properties(m_pClass, &iter); while (itProperty != nullptr) { // Add property and iterate to the next one properties.push_back(new SharpProperty(itProperty)); itProperty = mono_class_get_properties(m_pClass, &iter); } return properties; } Memory::reference<SharpField> SharpClass::getField(const std::string& name) { return Memory::reference<SharpField>(new SharpField(m_pDomain, mono_class_get_field_from_name(m_pClass, name.c_str()))); } std::vector<Memory::reference<SharpAttribute>> SharpClass::getAttributes() { // All attributes std::vector<Memory::reference<SharpAttribute>> attributes; // Get attributes MonoCustomAttrInfo* attrInfo = mono_custom_attrs_from_class(m_pClass); // Check if there are any attributes if (attrInfo == nullptr) { return attributes; } // Iterate over attributes for (int i = 0; i < attrInfo->num_attrs; i++) { // Get attribute class MonoClass* attrClass = mono_method_get_class(attrInfo->attrs[i].ctor); // Get instance MonoObject* attrInstance = mono_custom_attrs_get_attr(attrInfo, m_pClass); // Add attribute attributes.push_back( new SharpAttribute( new SharpClass(m_pDomain, m_pImage, attrClass), attrInstance)); } // Free memory mono_custom_attrs_free(attrInfo); // Return the attributes return attributes; } MonoObject* SharpClass::createInstance() { // Create object from class return mono_object_new(m_pDomain, m_pClass); } MonoObject* SharpClass::boxValue(void* value) { return mono_value_box(m_pDomain, m_pClass, value); } bool SharpClass::loaded() { return m_pClass != nullptr; } std::string SharpClass::methodSignature(const std::string& name, const std::string& params, bool isStatic) { return getNamespace() + "." + getName() + (isStatic ? ":" : "::") + name + (params.length() > 0 ? "(" + params + ")" : ""); } SharpMethod::SharpMethod(MonoMethod* pMethod) : m_pMethod(pMethod) { if (m_pMethod == nullptr) { LOG_WARN("Can't create sharp method cause the MonoMethod* is invalid!"); } // Get the full name then copy to string and free the memory m_fullName = mono_method_full_name(m_pMethod, 1); } SharpMethod::SharpMethod(MonoImage* pImage, const std::string& signature) { //Build a method description object MonoMethodDesc* methodDesc = mono_method_desc_new(signature.c_str(), NULL); //Search the method in the image m_pMethod = mono_method_desc_search_in_image(methodDesc, pImage); // Get the full name then copy to string and free the memory m_fullName = mono_method_full_name(m_pMethod, 1); // Free memory mono_method_desc_free(methodDesc); // Check if the class was created correctly if (!m_pMethod) { LOG_WARN("'{0}' method could not be created. It was not found or doesn't exist!", signature); return; } } MonoObject* SharpMethod::invokeMethod(MonoObject* pInstance, void** params, MonoObject** exception) { // Invoke the method return mono_runtime_invoke(m_pMethod, pInstance, params, exception); } MonoObject* SharpMethod::invokeVirtualMethod(MonoObject* pInstance, void** params, MonoObject** exception) { // Get the virtual method and then invoke it MonoMethod* virtualMethod = mono_object_get_virtual_method(pInstance, m_pMethod); return mono_runtime_invoke(virtualMethod, pInstance, params, exception); } Memory::reference<SharpMethod> SharpMethod::getAsVirtual(MonoObject* pInstance) { return new SharpMethod(mono_object_get_virtual_method(pInstance, m_pMethod)); } void* SharpMethod::getThunk() { return mono_method_get_unmanaged_thunk(m_pMethod); } const std::string& SharpMethod::getFullName() { return m_fullName; } bool SharpMethod::loaded() { return m_pMethod != nullptr; } SharpProperty::SharpProperty(MonoProperty* pProperty) : m_pProperty(pProperty), m_getMethod(nullptr), m_setMethod(nullptr) { // Get methods MonoMethod* pGet = mono_property_get_get_method(pProperty); MonoMethod* pSet = mono_property_get_set_method(pProperty); // Check if they exist, if they do create them if (pGet) { m_getMethod = new SharpMethod(pGet); } if (pSet) { m_setMethod = new SharpMethod(pSet); } } SharpProperty::SharpProperty(MonoClass* pClass, const std::string& name) : SharpProperty(mono_class_get_property_from_name(pClass, name.c_str())) { } const std::string& SharpProperty::getName() { return mono_property_get_name(m_pProperty); } MonoObject* SharpProperty::getValue(MonoObject* pInstance) { ADER_ASSERT(m_getMethod.valid(), "Trying to use invalid property method"); return m_getMethod->invokeMethod(pInstance, nullptr); } void SharpProperty::setValue(MonoObject* pInstance, void** params) { ADER_ASSERT(m_setMethod.valid(), "Trying to use invalid property method"); m_setMethod->invokeMethod(pInstance, params); } void* SharpProperty::getGetThunk() { ADER_ASSERT(m_getMethod.valid(), "Trying to use invalid property method"); return m_getMethod->getThunk(); } void* SharpProperty::getSetThunk() { ADER_ASSERT(m_setMethod.valid(), "Trying to use invalid property method"); return m_setMethod->getThunk(); } bool SharpProperty::loaded() { return m_pProperty != nullptr; } SharpAttribute::SharpAttribute(Memory::reference<SharpClass> klass, MonoObject* pObject) : m_class(klass), m_pInstance(pObject) { for (Memory::reference<SharpProperty> prop : m_class->getAllProperties()) { m_properties[prop->getName()] = prop; } } MonoObject* SharpAttribute::getValue(const std::string& prop) { if (m_properties.find(prop) != m_properties.end()) { return m_properties[prop]->getValue(m_pInstance); } return nullptr; } Memory::reference<SharpClass> SharpAttribute::getClass() { return m_class; } SharpField::SharpField(MonoDomain* pDomain, MonoClassField* pField) : m_pField(pField) { // Check if the field is valid if (!m_pField) { LOG_WARN("Couldn't create a field, the passed pointer is invalid!"); return; } // Check if the field is static uint32_t flags = mono_field_get_flags(m_pField); m_isStatic = (flags & MONO_FIELD_ATTR_STATIC) != 0; // We have to make sure that the class is initialized if // the field is from a static class if (m_isStatic) { // Initialize class that whose field we are trying to access m_pVTable = mono_class_vtable(pDomain, mono_field_get_parent(m_pField)); mono_runtime_class_init(m_pVTable); } } void SharpField::getValue(MonoObject* pInstance, void* value) { // Check if field is static and set value accordingly if (m_isStatic) { mono_field_static_get_value(m_pVTable, m_pField, value); } else { mono_field_get_value(pInstance, m_pField, value); } } void SharpField::setValue(MonoObject* pInstance, void* value) { void* args[1]; args[0] = value; // Check if field is static and set value accordingly if (m_isStatic) { mono_field_static_set_value(m_pVTable, m_pField, args); } else { mono_field_set_value(pInstance, m_pField, args); } } bool SharpField::isStatic() const { return m_isStatic; } bool SharpField::loaded() { return m_pField != nullptr; } SharpException::SharpException(MonoObject* pException) { getValues(pException); } const std::string& SharpException::getMessage() const { return m_msg; } const std::string& SharpException::getStackTrace() const { return m_stackTrace; } void SharpException::getValues(MonoObject* pException) { // Get the class of the exception MonoClass* exceptionClass = mono_object_get_class(pException); // Create properties SharpProperty messageProperty(exceptionClass, "Message"); SharpProperty stackTraceProperty(exceptionClass, "StackTrace"); if (messageProperty.loaded() && stackTraceProperty.loaded()) { // Get values MonoObject* pMessage = messageProperty.getValue(pException); MonoObject* pStackTrace = stackTraceProperty.getValue(pException); // Convert to C++ types m_msg = SharpUtility::toString(pMessage); m_stackTrace = SharpUtility::toString(pStackTrace); } else { LOG_WARN("Can't find properties for the exception or the object is invalid!"); } } std::string SharpUtility::toString(MonoObject* pObject) { // Create mono string MonoString* pMonoStr = mono_object_to_string(pObject, nullptr); // Get the string value char* pStr = mono_string_to_utf8(pMonoStr); // Create std::string std::string str = reinterpret_cast<std::string::value_type*>(pStr); // Free the memory of the raw array mono_free(pStr); return str; } MonoString* SharpUtility::newString(const std::string& value) { return mono_string_new_wrapper(value.c_str()); } std::string SharpUtility::methodSignature(const std::string& nSpace, const std::string& klass, const std::string& method, const std::string& params, bool isStatic) { return nSpace + "." + klass + (isStatic ? "::" : ":") + method + (params.length() > 0 ? "(" + params + ")" : ""); } void* SharpUtility::unboxValue(MonoObject* object) { return mono_object_unbox(object); }
24.580193
163
0.732511
[ "object", "vector" ]
dfaae1956ab2a4d08c22a8b9ba4f011bf224350e
39,889
cpp
C++
AlleriaPintool/GlobalState.cpp
hadibrais/Alleria
ad4c9402bc0e442d4adc5e3de543540d1efbeba9
[ "MIT" ]
1
2019-10-16T19:24:43.000Z
2019-10-16T19:24:43.000Z
AlleriaPintool/GlobalState.cpp
hadibrais/Alleria
ad4c9402bc0e442d4adc5e3de543540d1efbeba9
[ "MIT" ]
null
null
null
AlleriaPintool/GlobalState.cpp
hadibrais/Alleria
ad4c9402bc0e442d4adc5e3de543540d1efbeba9
[ "MIT" ]
null
null
null
#include "GlobalState.h" #include <cstdlib> UINT32 GLOBAL_STATE::s_childWaitTimeOut; BOOL GLOBAL_STATE::processingThreadRunning; std::ofstream GLOBAL_STATE::gfstream; std::map<UINT32, UINT32> GLOBAL_STATE::gRoutineMap; std::wofstream GLOBAL_STATE::interceptorFileStreamText; std::ofstream GLOBAL_STATE::interceptorFileStreamBinary; std::ofstream GLOBAL_STATE::walkerFileStream; PIN_LOCK GLOBAL_STATE::gAppThreadLock; PIN_LOCK GLOBAL_STATE::gProcThreadLock; std::vector<std::ofstream*> GLOBAL_STATE::localStreams; std::vector<PIN_THREAD_UID> GLOBAL_STATE::processingThreadsIds; BUFFER_LIST_MANAGER GLOBAL_STATE::fullBuffersListManager; BUFFER_LIST_MANAGER GLOBAL_STATE::freeBuffersListManager; UINT64 GLOBAL_STATE::insCount; UINT64 GLOBAL_STATE::insMemCount; ADDRINT GLOBAL_STATE::currentProcessHandle; std::string GLOBAL_STATE::s_myDumpDirectory; GLOBAL_STATE::PpndbEntry *GLOBAL_STATE::myPpndbEntry; std::vector<std::pair<UINT32, TIME_STAMP> > GLOBAL_STATE::childProcesses; xed_syntax_enum_t GLOBAL_STATE::s_asmSyntax; TIME_STAMP GLOBAL_STATE::totalAppThreadWaitingTime; TIME_STAMP GLOBAL_STATE::totalAppThreadCount; BINARY_HEADER GLOBAL_STATE::s_binaryHeader; BINARY_PROCESS_FAMILY GLOBAL_STATE::s_binaryProcFamily; std::streampos GLOBAL_STATE::s_globalFuncSecOffset; std::streampos GLOBAL_STATE::s_globalImgSecOffset; std::streampos GLOBAL_STATE::s_globalProcFamilyOffset; std::streampos GLOBAL_STATE::s_funcSecOffset; std::streampos GLOBAL_STATE::s_imgSecOffset; PIN_THREAD_UID GLOBAL_STATE::timerthreadUID; PIN_THREAD_UID GLOBAL_STATE::walkerthreadUID; volatile BOOL GLOBAL_STATE::isAppExisting = FALSE; TIME_STAMP GLOBAL_STATE::totalAppThreadRunningWaitingTime; TIME_STAMP GLOBAL_STATE::totalProcessingThreadRunningWaitingTime; PIN_SEMAPHORE GLOBAL_STATE::tunerSemaphore; PIN_THREAD_UID GLOBAL_STATE::tuidTunerControl; BOOL GLOBAL_STATE::tuidTunerControlResume; UINT32 g_processNumber; BOOL g_isGenesis; const CHAR *g_mainExe; V2P_TRANS_MODE g_v2pTransMode; OUTPUT_FORMAT_MODE g_outputFormat; UINT8 g_virtualAddressSize; UINT8 g_physicalAddressSize; std::string g_outputDir; const UINT8 g_binSecDirFuncIndexMain = 2; const UINT8 g_binSecDirImgIndexMain = 3; const UINT8 g_binSecDirFuncIndexSub = 1; const UINT8 g_binSecDirImgIndexSub = 2; static std::vector<PORTABLE_PROCESSOR_PACKAGE> g_processors; #ifdef TARGET_WINDOWS ODS_MODE g_odsMode; #endif /* TARGET_WINDOWS */ // Maximum size of PPNDB in bytes. #define PPNDB_MAX_SIZE (1 << 16) #define SECTION_DIRECTORY_ENTRY_SET_TYPE(entry, value) \ entry.data = (entry.data & 0xFFFFFFFFFFFFFF00) | (value & 0xFF) #define SECTION_DIRECTORY_ENTRY_SET_OFFSET(entry, value) \ entry.data = (entry.data & 0xFF) | (value << 8) #define SECTION_DIRECTORY_ENTRY_SET(entry, type, offset) \ SECTION_DIRECTORY_ENTRY_SET_TYPE(entry, type); \ SECTION_DIRECTORY_ENTRY_SET_OFFSET(entry, offset) #define BUFFER_MIN_SIZE_KB 1 #define BUFFER_MAX_SIZE_KB 1024*1024 /* Alleria Knobs Definitions */ #define AlleriaKnobFamily "pintool" #define NumKBBufferSwitch "bs" #define NumberOfBuffersSwitch "bc" #define NumProcessingThreadsSwitch "ptc" #define ChildWaitTimeOutSecondsSwitch "cwto" #define AsmStyleSwitch "asm" #define OutputFormatSwitch "of" #define LLWEnabledSwitch "llw" #define TimerEnabledSwitch "ta" #define OuputInstructionEnabledSwitch "oi" #define TimerFreqSwitch "tf" #define DumpDirSwitch "dir" #define V2PTransModeSwitch "v2p" #define V2POutputDebugStringModeSwitch "ods" #define TrackProcessorsSwitch "tp" #define ConfigDirSwitch "cfg" #define TunerSwitch "tuner" #define NumKBBufferDefault 4096 #define NumberOfBuffersDefault 5 #define NumProcessingThreadsDefault 4 #define ChildWaitTimeOutSecondsDefault 30 #define AsmStyleDefault "intel" #define OutputFormatDefault "txt" #define LLWEnabledDefault "false" #define TimerEnabledDefault "true" #define OuputInstructionEnabledDefault "true" #define TimerFreqDefault 10000 #define DumpDirDefault "" #define V2PTransModeDefault "off" #define V2POutputDebugStringModeDefault "asrequired" #define TrackProcessorsDefault "false" #define ConfigDirDefault "" #define TunerDefault "false" #define NumKBBufferDesc "number of kibibytes in a buffer, default is 64" #define NumberOfBuffersDesc "number of buffers to allocate, default is 5. On Windows 10+, it must be at least 2 " \ " or maybe more because the OS creates dedicated threads that load libraries (parallel loader)." #define NumProcessingThreadsDesc "number of processing threads, default is 4" #define ChildWaitTimeOutSecondsDesc "number of seconds to wait for child processes to initialize, default is 30" #define AsmStyleDesc "syntax of assembly instructions: intel, att or xed, default is intel" #define OutputFormatDesc "format of the output file: txt for textual, bin for binary, default is txt" #define LLWEnabledDesc "enable or disable the live-lands walker, default is false" #define TimerEnabledDesc "enable or disable the timer thread, default is true" #define OuputInstructionEnabledDesc "enable or disable emitting instructions in profiles, default is true" #define TimerFreqDesc "timer resolution in milliseconds, default is 10000" #define DumpDirDesc "directory in which all output files will be stored" #define V2PTransModeDesc "mode of virtual address translation: off, fast or accurate, default is off" #define V2POutputDebugStringModeDesc "mode of OutputDebugString: asrequired or suppress. Windows only, default is asrequired" #define TrackProcessorsDesc "enable or disable recording the processor on which a thread is executing, default is false" #define ConfigDirDesc "directory in which the configuration file resides" #define TunerDesc "enable or disable adaptive profiling. bc and ptc are ignored" KNOB<UINT32> KnobNumKBBuffer( KNOB_MODE_WRITEONCE, AlleriaKnobFamily, NumKBBufferSwitch, LITERAL_TO_CHAR_PTR(NumKBBufferDefault), NumKBBufferDesc); KNOB<UINT32> KnobNumberOfBuffers( KNOB_MODE_WRITEONCE, AlleriaKnobFamily, NumberOfBuffersSwitch, LITERAL_TO_CHAR_PTR(NumberOfBuffersDefault), NumberOfBuffersDesc); KNOB<UINT32> KnobNumProcessingThreads( KNOB_MODE_OVERWRITE, AlleriaKnobFamily, NumProcessingThreadsSwitch, LITERAL_TO_CHAR_PTR(NumProcessingThreadsDefault), NumProcessingThreadsDesc); KNOB<UINT32> KnobChildWaitTimeOut( KNOB_MODE_OVERWRITE, AlleriaKnobFamily, ChildWaitTimeOutSecondsSwitch, LITERAL_TO_CHAR_PTR(ChildWaitTimeOutSecondsDefault), ChildWaitTimeOutSecondsDesc); KNOB<string> KnobAsmStyle( KNOB_MODE_OVERWRITE, AlleriaKnobFamily, AsmStyleSwitch, AsmStyleDefault, AsmStyleDesc); KNOB<string> KnobOutputFormat( KNOB_MODE_OVERWRITE, AlleriaKnobFamily, OutputFormatSwitch, OutputFormatDefault, OutputFormatDesc); KNOB<BOOL> KnobLLWEnabled( KNOB_MODE_OVERWRITE, AlleriaKnobFamily, LLWEnabledSwitch, LLWEnabledDefault, LLWEnabledDesc); KNOB<BOOL> KnobTimerEnabled( KNOB_MODE_OVERWRITE, AlleriaKnobFamily, TimerEnabledSwitch, TimerEnabledDefault, TimerEnabledDesc); KNOB<BOOL> KnobOuputInstructionEnabled( KNOB_MODE_OVERWRITE, AlleriaKnobFamily, OuputInstructionEnabledSwitch, OuputInstructionEnabledDefault, OuputInstructionEnabledDesc); KNOB<UINT32> KnobTimerFreq( KNOB_MODE_OVERWRITE, AlleriaKnobFamily, TimerFreqSwitch, LITERAL_TO_CHAR_PTR(TimerFreqDefault), TimerFreqDesc); KNOB<string> KnobDumpDir( KNOB_MODE_OVERWRITE, AlleriaKnobFamily, DumpDirSwitch, DumpDirDefault, DumpDirDesc); KNOB<string> KnobV2PTransMode( KNOB_MODE_OVERWRITE, AlleriaKnobFamily, V2PTransModeSwitch, V2PTransModeDefault, V2PTransModeDesc); #ifdef TARGET_WINDOWS KNOB<string> KnobOutputDebugStringMode( KNOB_MODE_OVERWRITE, AlleriaKnobFamily, V2POutputDebugStringModeSwitch, V2POutputDebugStringModeDefault, V2POutputDebugStringModeDesc); #endif /* TARGET_WINDOWS */ KNOB<BOOL> KnobTrackProcessorsEnabled( KNOB_MODE_OVERWRITE, AlleriaKnobFamily, TrackProcessorsSwitch, TrackProcessorsDefault, TrackProcessorsDesc); KNOB<string> KnobConfigDir( KNOB_MODE_OVERWRITE, AlleriaKnobFamily, ConfigDirSwitch, ConfigDirDefault, ConfigDirDesc); KNOB<BOOL> KnobTunerEnabled( KNOB_MODE_WRITEONCE, AlleriaKnobFamily, TunerSwitch, TunerDefault, TunerDesc); /* End Alleria Knobs Definitions */ #ifdef TARGET_WINDOWS #define PROCESS_TREE_MUTEX_NAME "AlleriaPpndbMutex" #define PROCESS_TREE_FILE_MAPPING_NAME "AlleriaPpndb" #elif defined(TARGET_LINUX) #define PROCESS_TREE_MUTEX_NAME "/AlleriaPpndbMutex" #define PROCESS_TREE_FILE_MAPPING_NAME "/AlleriaPpndb" #endif /* TARGET_WINDOWS */ xed_syntax_enum_t Str2AsmSyntax(const CHAR *str); void PathCombine(std::string& output, const std::string& path1, const std::string& path2) { output = ""; if (path1.length() > 0) { if (path1[path1.length() - 1] != PORTABLE_PATH_DELIMITER[0]) { output = path1 + PORTABLE_PATH_DELIMITER; } else { output = path1; } } output += path2; } static BOOL IsKnobV2PTransModeValid() { g_v2pTransMode = V2P_TRANS_MODE_INVALID; if (strcmp(KnobV2PTransMode.Value().c_str(), "off") == 0) g_v2pTransMode = V2P_TRANS_MODE_OFF; else if (strcmp(KnobV2PTransMode.Value().c_str(), "fast") == 0) g_v2pTransMode = V2P_TRANS_MODE_FAST; else if (strcmp(KnobV2PTransMode.Value().c_str(), "accurate") == 0) g_v2pTransMode = V2P_TRANS_MODE_ACCURATE; else return FALSE; return TRUE; } static BOOL IsKnobOutputFormatValid() { g_outputFormat = OUTPUT_FORMAT_MODE_INVALID; if (strcmp(KnobOutputFormat.Value().c_str(), "txt") == 0) g_outputFormat = OUTPUT_FORMAT_MODE_TEXTUAL; else if (strcmp(KnobOutputFormat.Value().c_str(), "bin") == 0) g_outputFormat = OUTPUT_FORMAT_MODE_BINARY; else return FALSE; return TRUE; } static BOOL IsKnobOdsModeValid() { #ifdef TARGET_WINDOWS g_odsMode = ODS_MODE_INVALID; if (strcmp(KnobOutputDebugStringMode.Value().c_str(), "asrequired") == 0) g_odsMode = ODS_MODE_AS_REQUIRED; else if (strcmp(KnobOutputDebugStringMode.Value().c_str(), "suppress") == 0) g_odsMode = ODS_MODE_SUPPRESS; else return FALSE; #endif /* TARGET_WINDOWS */ return TRUE; } static BOOL IsKnobAsmSyntaxValid() { xed_syntax_enum_t s = Str2AsmSyntax(KnobAsmStyle.Value().c_str()); if (s == xed_syntax_enum_t::XED_SYNTAX_INVALID) return false; else { GLOBAL_STATE::s_asmSyntax = s; return true; } } static UINT32 GetBinaryProfileHeaderFlags() { UINT32 flags = 0; flags = flags | (UINT32)KnobOuputInstructionEnabled; flags = flags | (UINT32)(KnobTrackProcessorsEnabled << 1); return flags; } xed_syntax_enum_t GLOBAL_STATE::GetAsmSyntaxStyle() { return s_asmSyntax; } VOID* GLOBAL_STATE::GetPpndbBase() { bool alreadExists; void *base = CreateNamedFileMapping(PPNDB_MAX_SIZE, PROCESS_TREE_FILE_MAPPING_NAME, &alreadExists); if (!base) { AlleriaSetLastError(ALLERIA_ERROR_INIT_FAILED); return NULL; } if (alreadExists) { } else { if (!EnsureCommited(base, GetVirtualPageSize())) return NULL; } return base; } UINT32 GLOBAL_STATE::ComputeMyProcessNumber(UINT32 pid, UINT32 ppid) { void *base = GetPpndbBase(); if (!base) { AlleriaSetLastError(ALLERIA_ERROR_INIT_FAILED); return PROCESS_INVALID_ID; } if (pid == PROCESS_INVALID_ID || ppid == PROCESS_INVALID_ID) { AlleriaSetLastError(ALLERIA_ERROR_INIT_FAILED); return PROCESS_INVALID_ID; } PMUTEX mutex = Mutex_CreateNamed(PROCESS_TREE_MUTEX_NAME); Mutex_Acquire(mutex); Ppndb *ppndbBase = reinterpret_cast<Ppndb*>(base); myPpndbEntry = NULL; PpndbEntry *ppndbEntry = &ppndbBase->base + ppndbBase->count - 1; for (UINT32 i = 0; i < ppndbBase->count; ++i) { if (ppndbEntry->pid == pid && ppndbEntry->endingTime == -1) { myPpndbEntry = ppndbEntry; break; } --ppndbEntry; } if (myPpndbEntry) { // Nothing to do here. My parent initialized me. } else { // This process is a genesis process. // It has to initialzie itself. PpndbEntry *ppndbEntry = &ppndbBase->base + ppndbBase->count; if (reinterpret_cast<UINT8*>(ppndbEntry) >= (reinterpret_cast<UINT8*>(base)+PPNDB_MAX_SIZE)) { AlleriaSetLastError(ALLERIA_ERROR_INIT_FAILED); return PROCESS_INVALID_ID; } else { if (!EnsureCommited(ppndbEntry, GetVirtualPageSize())) { AlleriaSetLastError(ALLERIA_ERROR_INIT_FAILED); return PROCESS_INVALID_ID; } } ppndbEntry->isGenesis = TRUE; ppndbEntry->reference = 1; ppndbEntry->processNumber = 1; ppndbEntry->pid = pid; myPpndbEntry = ppndbEntry; ++ppndbBase->count; } Mutex_Release(mutex); Mutex_Close(mutex); GetCurrentTimestamp(myPpndbEntry->startingTime); myPpndbEntry->endingTime = 0; return myPpndbEntry->processNumber; } UINT32 GLOBAL_STATE::ComputeChildProcessNumber(UINT32 pid, UINT32 ppid) { void *base = GetPpndbBase(); if (!base) { AlleriaSetLastError(ALLERIA_ERROR_INIT_FAILED); return PROCESS_INVALID_ID; } if (pid == PROCESS_INVALID_ID || ppid == PROCESS_INVALID_ID) { AlleriaSetLastError(ALLERIA_ERROR_INIT_FAILED); return PROCESS_INVALID_ID; } PMUTEX mutex = Mutex_CreateNamed(PROCESS_TREE_MUTEX_NAME); Mutex_Acquire(mutex); Ppndb *ppndbBase = reinterpret_cast<Ppndb*>(base); PpndbEntry *ppndbEntry = &ppndbBase->base + ppndbBase->count; if (reinterpret_cast<UINT8*>(ppndbEntry) >= (reinterpret_cast<UINT8*>(base)+PPNDB_MAX_SIZE)) { AlleriaSetLastError(ALLERIA_ERROR_INIT_FAILED); return PROCESS_INVALID_ID; } else { if (!EnsureCommited(ppndbEntry, GetVirtualPageSize())) { AlleriaSetLastError(ALLERIA_ERROR_INIT_FAILED); return PROCESS_INVALID_ID; } } PpndbEntry *parentPpndbEntry = (myPpndbEntry->isGenesis) ? myPpndbEntry : (&ppndbBase->base + myPpndbEntry->reference); UINT32 parentIndex = (UINT32)((parentPpndbEntry - &ppndbBase->base) / sizeof(PpndbEntry)); ppndbEntry->processNumber = parentPpndbEntry->reference + 1; ppndbEntry->reference = parentIndex; ppndbEntry->pid = pid; ppndbEntry->isGenesis = FALSE; ppndbEntry->endingTime = -1; ppndbEntry->startingTime = 0; parentPpndbEntry->reference = ppndbEntry->processNumber; ++ppndbBase->count; Mutex_Release(mutex); Mutex_Close(mutex); return ppndbEntry->processNumber; } VOID GLOBAL_STATE::InitProcessDumpDirectory() { std::string directory; if (KnobDumpDir.Value().size() == 0) { directory = PathToDirectory(PIN_ToolFullPath()); } else { // TODO: Support dirs with spaces by accepting quoted strings. directory = KnobDumpDir.Value(); } g_outputDir = directory; } BOOL GLOBAL_STATE::ValidateKnobs() { BOOL failed = FALSE; if (KnobNumKBBuffer < BUFFER_MIN_SIZE_KB || KnobNumKBBuffer > BUFFER_MAX_SIZE_KB) { AlleriaSetLastError(ALLERIA_ERROR_KNOB_NumKBInMemRefBuffer); failed = TRUE; } else if (KnobNumberOfBuffers == 0) { AlleriaSetLastError(ALLERIA_ERROR_KNOB_NumBuffersPerAppThread); failed = TRUE; } else if (!IsKnobAsmSyntaxValid()) { AlleriaSetLastError(ALLERIA_ERROR_KNOB_AsmStyle); failed = TRUE; } else if (!IsKnobOutputFormatValid()) { AlleriaSetLastError(ALLERIA_ERROR_KNOB_OutputFormat); failed = TRUE; } else if (KnobTimerFreq == 0) { AlleriaSetLastError(ALLERIA_ERROR_KNOB_TimerFreq); failed = TRUE; } else if (!IsKnobV2PTransModeValid()) { AlleriaSetLastError(ALLERIA_ERROR_KNOB_V2PTransMode); failed = TRUE; } else if (!IsKnobOdsModeValid()) { AlleriaSetLastError(ALLERIA_ERROR_KNOB_OutputDebugStringMode); failed = TRUE; } else if (KnobTunerEnabled && !KnobTimerEnabled) { AlleriaSetLastError(ALLERIA_ERROR_KNOB_TimerRequired); failed = TRUE; } else if (KnobTunerEnabled && KnobOutputFormat.ValueString() == "txt") { AlleriaSetLastError(ALLERIA_ERROR_KNOB_TUNER_NO_TXT); failed = TRUE; } return failed; } VOID GLOBAL_STATE::InitBinaryHeader() { GetSystemInfo(s_binaryHeader); s_binaryHeader.pAddrSize = (g_v2pTransMode == V2P_TRANS_MODE_OFF ? 0 : s_binaryHeader.pAddrSize); s_binaryHeader.processNumber = myPpndbEntry->processNumber; s_binaryHeader.processorVendor = GetProcessorVendor(); s_binaryHeader.type = BINARY_HEADER_TYPE_MAIN_PROFILE; s_binaryHeader.timestamp = time(0); s_binaryHeader.flags = GetBinaryProfileHeaderFlags(); #if defined(TARGET_IA32) s_binaryHeader.targetArch = PROCESSOR_ARCH_X86; #else s_binaryHeader.targetArch = PROCESSOR_ARCH_X64; #endif InitBinaryHeaderSectionDirectory(); } BOOL GLOBAL_STATE::InitOutputFilesTxt() { std::string fullPathStr; PathCombine(fullPathStr, s_myDumpDirectory, "g.ap"); gfstream.open(fullPathStr.c_str(), fomodetxt); gfstream << std::hex; PathCombine(fullPathStr, s_myDumpDirectory, "intercept.ap"); interceptorFileStreamText.open(fullPathStr.c_str(), fomodetxt); interceptorFileStreamText << std::hex; PathCombine(fullPathStr, s_myDumpDirectory, "walker.ap"); walkerFileStream.open(fullPathStr.c_str(), fomodetxt); walkerFileStream << std::hex; if (!gfstream.good() || !interceptorFileStreamText.good() || !walkerFileStream.good()) { AlleriaSetLastError(ALLERIA_ERROR_CANNOT_CREATE_PROFILE); return false; } //for (UINT32 i = 0; i < KnobNumProcessingThreads; ++i) //{ // std::string temp; // IntegerToString(i + 1, temp); // PathCombine(fullPathStr, s_myDumpDirectory, temp + ".ap"); // std::ofstream *stream = new std::ofstream(fullPathStr.c_str(), fomode); // // if (!(*stream).good()) // { // AlleriaSetLastError(ALLERIA_ERROR_CANNOT_CREATE_PROFILE); // return false; // Process terminates. // } // *stream << std::hex; // localStreams.push_back(stream); //} return true; } VOID GLOBAL_STATE::WriteBinaryHeader(std::ofstream& ofs, BINARY_HEADER_TYPE type) { // Write binary header ofs.write(s_binaryHeader.Id, strlen(s_binaryHeader.Id) + 1); // 0 + 10 bytes. ofs.write(s_binaryHeader.version, strlen(s_binaryHeader.version) + 1); // 10 + 4 bytes. WriteBinary(ofs, type); // 14 + 4 bytes. Don't use s_binaryHeader.type here. WriteBinary(ofs, s_binaryHeader.os); // 18 + 4 bytes. WriteBinary(ofs, s_binaryHeader.processorVendor); // 22 + 4 bytes. WriteBinary(ofs, s_binaryHeader.processorArch); // 26 + 4 bytes. WriteBinary(ofs, s_binaryHeader.targetArch); // 30 + 4 bytes. // time_t could be of any size. Convert to 64-bit. UINT64 portabletime = s_binaryHeader.timestamp; WriteBinary(ofs, portabletime); // 34 + 8 bytes. WriteBinary(ofs, s_binaryHeader.processNumber); // 42 + 4 bytes. WriteBinary(ofs, s_binaryHeader.processOsId); // 46 + 4 bytes. WriteBinary(ofs, s_binaryHeader.timeFreq); // 50 + 8 bytes. // time_t could be of any size. Convert to 64-bit. portabletime = s_binaryHeader.startingTime; WriteBinary(ofs, s_binaryHeader.startingTime); // To be patched later. At offset 58 = BINARY_HEADER_STARTING_TIME_OFFSET. // time_t could be of any size. Convert to 64-bit. portabletime = s_binaryHeader.endingTime; WriteBinary(ofs, s_binaryHeader.endingTime); // To be patched later. At offset 66 = BINARY_HEADER_ENDING_TIME_OFFSET. WriteBinary(ofs, s_binaryHeader.instructionCount); // To be patched later. At offset 74 = BINARY_HEADER_INS_COUNT_OFFSET. WriteBinary(ofs, s_binaryHeader.memoryInstructionCount); // To be patched later. At offset 82 = BINARY_HEADER_MEM_INS_COUNT_OFFSET. ofs.write(s_binaryHeader.mainExePath, strlen(s_binaryHeader.mainExePath) + 1); ofs.write(s_binaryHeader.systemDirectory, strlen(s_binaryHeader.systemDirectory) + 1); ofs.write(s_binaryHeader.currentDirectory, strlen(s_binaryHeader.currentDirectory) + 1); ofs.write(s_binaryHeader.cmdLine, strlen(s_binaryHeader.cmdLine) + 1); ofs.write(s_binaryHeader.osVersion, strlen(s_binaryHeader.osVersion) + 1); WriteBinary(ofs, s_binaryHeader.vAddrSize); WriteBinary(ofs, s_binaryHeader.pAddrSize); WriteBinary(ofs, s_binaryHeader.pageSize); ofs.write(reinterpret_cast<char*>(&s_binaryHeader.minAppAddr), s_binaryHeader.vAddrSize); ofs.write(reinterpret_cast<char*>(&s_binaryHeader.maxAppAddr), s_binaryHeader.vAddrSize); WriteBinary(ofs, s_binaryHeader.totalDram); WriteBinary(ofs, s_binaryHeader.flags); WriteBinary(ofs, s_binaryHeader.reserved); WriteBinary(ofs, s_binaryHeader.dirSize); } BINARY_SECION_CPUID* GLOBAL_STATE::GetCpuidInfo(unsigned int& sizeInElements, unsigned int& sizeInBytes) { PORTABLE_PROCESSOR_PACKAGE originalAffinifty; GetMyThreadAffinity(originalAffinifty); unsigned int byteCount = 0; /* When using the new operator to allocate an array of one element. Pin crashes when calling delete. This happens on Pin 2.14-71313. Therefore, use the malloc function. */ BINARY_SECION_CPUID *cpuidInfo = reinterpret_cast<BINARY_SECION_CPUID*>(malloc(sizeof(BINARY_SECION_CPUID)*g_processors.size())); BINARY_SECION_CPUID *cpuidInfoIterator = cpuidInfo; for (unsigned int i = 0; i < g_processors.size(); ++i) { SetMyThreadAffinity(g_processors[i]); GetProcessorIdentification(*cpuidInfoIterator); byteCount += (unsigned int)cpuidInfoIterator->cpuidInfo.size() * sizeof(CPUID_INFO); byteCount += 2 * sizeof(int); // nIds and nExIds. ++cpuidInfoIterator; } SetMyThreadAffinity(originalAffinifty); sizeInElements = (unsigned int)g_processors.size(); sizeInBytes = byteCount; return cpuidInfo; } VOID GLOBAL_STATE::WriteBinaryProfile(std::ofstream& ofs, BINARY_HEADER_TYPE type) { /* In the main profile, the order of sections is: 0- CPUID 1- Profile 2- Function Table 3- Image Table 4- Process Family All of them are always valid. In a sub profile, the order of sections is: 0- Profile 1- Function Table 2- Image Table All of them are always valid. See g_binSecDirFuncIndexMain and its brothers. */ std::ofstream::pos_type profileOffset = (unsigned long long)ofs.tellp() + (s_binaryHeader.sectionDirectory.size() * sizeof(SECTION_DIRECTORY_ENTRY)); BINARY_SECION_CPUID *cpuidInfo; unsigned int cpuidInfoCount; // Write the section directory. UINT32 startingIndex = 0; if (type == BINARY_HEADER_TYPE_MAIN_PROFILE) { std::ofstream::pos_type cpuidOffset = profileOffset; SECTION_DIRECTORY_ENTRY_SET( s_binaryHeader.sectionDirectory[startingIndex], BINARY_SECION_TYPE_CPUID, cpuidOffset); WriteBinary(ofs, s_binaryHeader.sectionDirectory[startingIndex]); ++startingIndex; unsigned int cpuidInfoBytes; cpuidInfo = GetCpuidInfo(cpuidInfoCount, cpuidInfoBytes); profileOffset = cpuidOffset + ((std::ofstream::pos_type)cpuidInfoBytes) + /*CPUID section header (number of cpuids)*/ ((std::ofstream::pos_type)sizeof(unsigned int)); } SECTION_DIRECTORY_ENTRY_SET( s_binaryHeader.sectionDirectory[startingIndex], BINARY_SECION_TYPE_PROFILE, profileOffset); WriteBinary(ofs, s_binaryHeader.sectionDirectory[startingIndex]); ++startingIndex; if (type == BINARY_HEADER_TYPE_MAIN_PROFILE) s_globalFuncSecOffset = ofs.tellp(); else if (type == BINARY_HEADER_TYPE_SUB_PROFILE) s_funcSecOffset = ofs.tellp(); // BINARY_SECION_TYPE_IMAGE_TABLE SECTION_DIRECTORY_ENTRY_SET( s_binaryHeader.sectionDirectory[startingIndex], BINARY_SECION_TYPE_INVALID, 0L); // To be patched later. WriteBinary(ofs, s_binaryHeader.sectionDirectory[startingIndex]); ++startingIndex; if (type == BINARY_HEADER_TYPE_MAIN_PROFILE) s_globalImgSecOffset = ofs.tellp(); else if (type == BINARY_HEADER_TYPE_SUB_PROFILE) s_imgSecOffset = ofs.tellp(); // BINARY_SECION_TYPE_FUNC_TABLE SECTION_DIRECTORY_ENTRY_SET( s_binaryHeader.sectionDirectory[startingIndex], BINARY_SECION_TYPE_INVALID, 0L); // To be patched later. WriteBinary(ofs, s_binaryHeader.sectionDirectory[startingIndex]); ++startingIndex; if (type == BINARY_HEADER_TYPE_MAIN_PROFILE) { s_globalProcFamilyOffset = ofs.tellp(); // BINARY_SECION_TYPE_PROCESS_FAMILY SECTION_DIRECTORY_ENTRY_SET( s_binaryHeader.sectionDirectory[startingIndex], BINARY_SECION_TYPE_INVALID, 0L); // To be patched later. WriteBinary(ofs, s_binaryHeader.sectionDirectory[startingIndex]); ++startingIndex; } UINT64 zero = 0; for (UINT32 i = startingIndex; i < s_binaryHeader.dirSize; ++i) { SECTION_DIRECTORY_ENTRY_SET( s_binaryHeader.sectionDirectory[i], BINARY_SECION_TYPE_INVALID, 0L); // Not used. WriteBinary(ofs, zero); } if (type == BINARY_HEADER_TYPE_MAIN_PROFILE) { // Write CPUID section. WriteBinary(ofs, cpuidInfoCount); BINARY_SECION_CPUID *cpuidInfoIterator = cpuidInfo; while (cpuidInfoCount > 0) { WriteBinary(ofs, cpuidInfoIterator->nIds); WriteBinary(ofs, cpuidInfoIterator->nExIds); for (UINT32 i = 0; i < cpuidInfoIterator->cpuidInfo.size(); ++i) { WriteBinary(ofs, cpuidInfoIterator->cpuidInfo[i].EAX); WriteBinary(ofs, cpuidInfoIterator->cpuidInfo[i].ECX); WriteBinary(ofs, cpuidInfoIterator->cpuidInfo[i].cpuInfo[0]); WriteBinary(ofs, cpuidInfoIterator->cpuidInfo[i].cpuInfo[1]); WriteBinary(ofs, cpuidInfoIterator->cpuidInfo[i].cpuInfo[2]); WriteBinary(ofs, cpuidInfoIterator->cpuidInfo[i].cpuInfo[3]); } ++cpuidInfoIterator; --cpuidInfoCount; } free(cpuidInfo); } } VOID GLOBAL_STATE::WriteBinaryLlw(std::ofstream& ofs) { std::ofstream::pos_type llwOffset = (unsigned long long)ofs.tellp() + (s_binaryHeader.sectionDirectory.size() * sizeof(SECTION_DIRECTORY_ENTRY)); UINT32 startingIndex = 0; SECTION_DIRECTORY_ENTRY_SET( s_binaryHeader.sectionDirectory[startingIndex], BINARY_SECION_TYPE_LLW, llwOffset); WriteBinary(ofs, s_binaryHeader.sectionDirectory[startingIndex]); ++startingIndex; UINT64 zero = 0; for (UINT32 i = startingIndex; i < s_binaryHeader.dirSize; ++i) { SECTION_DIRECTORY_ENTRY_SET( s_binaryHeader.sectionDirectory[i], BINARY_SECION_TYPE_INVALID, 0L); // Not used. WriteBinary(ofs, zero); } } VOID GLOBAL_STATE::WriteBinaryInterceptors(std::ofstream& ofs) { std::ofstream::pos_type typesOffset = (unsigned long long)ofs.tellp() + (s_binaryHeader.sectionDirectory.size() * sizeof(SECTION_DIRECTORY_ENTRY)); UINT32 startingIndex = 0; SECTION_DIRECTORY_ENTRY_SET( s_binaryHeader.sectionDirectory[startingIndex], BINARY_SECION_TYPE_TYPES, typesOffset); WriteBinary(ofs, s_binaryHeader.sectionDirectory[startingIndex]); ++startingIndex; std::ofstream::pos_type interOffsetOffset = ofs.tellp(); SECTION_DIRECTORY_ENTRY_SET( s_binaryHeader.sectionDirectory[startingIndex], BINARY_SECION_TYPE_INTERCEPTORS, 0L); // To be patched later. WriteBinary(ofs, s_binaryHeader.sectionDirectory[startingIndex]); ++startingIndex; UINT64 zero = 0; for (UINT32 i = startingIndex; i < s_binaryHeader.dirSize; ++i) { SECTION_DIRECTORY_ENTRY_SET( s_binaryHeader.sectionDirectory[i], BINARY_SECION_TYPE_INVALID, 0L); // Not used. WriteBinary(ofs, zero); } INTERCEPTOR_INFO::EmitBinaryProfileTypesSection(GLOBAL_STATE::interceptorFileStreamBinary); std::ofstream::pos_type interOffset = (unsigned long long)ofs.tellp(); ofs.seekp(interOffsetOffset); SECTION_DIRECTORY_ENTRY sde; SECTION_DIRECTORY_ENTRY_SET(sde, BINARY_SECION_TYPE_INTERCEPTORS, interOffset); WriteBinary(ofs, sde); ofs.seekp(interOffset); } VOID GLOBAL_STATE::PatchFuncImgSecOffsets(std::ofstream& ofs, BOOL isGlobal, UINT64 funcOffset, UINT64 imgOffset) { // Save the current value of the put pointer. std::ofstream::pos_type oldPos = ofs.tellp(); SECTION_DIRECTORY_ENTRY sde; SECTION_DIRECTORY_ENTRY_SET(sde, BINARY_SECION_TYPE_FUNC_TABLE, funcOffset); // Patch func sec offset. if (isGlobal) ofs.seekp(s_globalFuncSecOffset); else ofs.seekp(s_funcSecOffset); WriteBinary(ofs, sde); // Patch img sec offset. SECTION_DIRECTORY_ENTRY_SET(sde, BINARY_SECION_TYPE_IMAGE_TABLE, imgOffset); if (isGlobal) ofs.seekp(s_globalImgSecOffset); else ofs.seekp(s_imgSecOffset); WriteBinary(ofs, sde); // Restore the old value of the put pointer. ofs.seekp(oldPos); } BOOL GLOBAL_STATE::InitOutputFilesBin() { std::string fullPathStr; PathCombine(fullPathStr, s_myDumpDirectory, "g.ap"); gfstream.open(fullPathStr.c_str(), fomodebin); PathCombine(fullPathStr, s_myDumpDirectory, "intercept.ap"); interceptorFileStreamBinary.open(fullPathStr.c_str(), fomodebin); PathCombine(fullPathStr, s_myDumpDirectory, "walker.ap"); walkerFileStream.open(fullPathStr.c_str(), fomodebin); if (!gfstream.good() || !interceptorFileStreamBinary.good() || !walkerFileStream.good()) { AlleriaSetLastError(ALLERIA_ERROR_CANNOT_CREATE_PROFILE); return false; } WriteBinaryHeader(gfstream, BINARY_HEADER_TYPE_MAIN_PROFILE); WriteBinaryProfile(gfstream, BINARY_HEADER_TYPE_MAIN_PROFILE); WriteBinaryHeader(interceptorFileStreamBinary, BINARY_HEADER_TYPE_SUB_PROFILE); WriteBinaryInterceptors(interceptorFileStreamBinary); WriteBinaryHeader(walkerFileStream, BINARY_HEADER_TYPE_SUB_PROFILE); WriteBinaryLlw(walkerFileStream); //for (UINT32 i = 0; i < KnobNumProcessingThreads; ++i) //{ // std::string temp; // IntegerToString(i + 1, temp); // PathCombine(fullPathStr, s_myDumpDirectory, temp + ".ap"); // std::ofstream *stream = new std::ofstream(fullPathStr.c_str(), fomode); // // if (!(*stream).good()) // { // AlleriaSetLastError(ALLERIA_ERROR_CANNOT_CREATE_PROFILE); // return false; // Process terminates. // } // WriteBinaryHeader(*stream, BINARY_HEADER_TYPE_SUB_PROFILE); // WriteBinaryProfile(*stream, BINARY_HEADER_TYPE_SUB_PROFILE); // localStreams.push_back(stream); //} return true; } VOID GLOBAL_STATE::Init(INT32 argc, CHAR *argv[]) { // NOTE // Compute process number first before validating knobs is not necessary, but important. // It reduces the probability for the parent process, if exists, to wait for the child. ComputeMyProcessNumber(GetProcessIdPortable(GetCurrentProcessPortable()), GetParentProcessId()); ValidateKnobs(); // Must be called before InitBinaryHeader to properly initialize the knobs. InitBinaryHeader(); g_mainExe = s_binaryHeader.mainExePath; // Initialize g_mainExe. Used for error processing. InitProcessDumpDirectory(); // Initialize g_outputDir. Used for error processing. // Initialize g_processNumber and g_isGenesis both used for error processing. g_processNumber = myPpndbEntry->processNumber; g_isGenesis = myPpndbEntry->isGenesis; // ValidateKnobs(); if (AlleriaGetLastError() != ALLERIA_ERROR_SUCCESS) return; if (!GetProcessorPackages(g_processors)) { AlleriaSetLastError(ALLERIA_ERROR_INIT_FAILED); return; } GetAddressSizes(g_virtualAddressSize, g_physicalAddressSize); g_physicalAddressSize = (g_v2pTransMode == V2P_TRANS_MODE_OFF ? 0 : g_physicalAddressSize); PIN_InitLock(&gAppThreadLock); PIN_InitLock(&gProcThreadLock); totalAppThreadWaitingTime = 0; totalAppThreadCount = 0; processingThreadRunning = FALSE; s_childWaitTimeOut = KnobChildWaitTimeOut * 1000; // To milliseconds. BUFFER_LIST_MANAGER::SetBufferSize(KnobNumKBBuffer * 1024); for (UINT32 i = 0; i < (KnobTunerEnabled ? Tuner::InitialThreadCount : KnobNumberOfBuffers); ++i) { freeBuffersListManager.AddNewFreeBuffer(PIN_ThreadId()); } totalAppThreadRunningWaitingTime = 0; totalProcessingThreadRunningWaitingTime = 0; Tuner::Init(KnobTunerEnabled); PIN_SemaphoreInit(&tunerSemaphore); PIN_SemaphoreClear(&tunerSemaphore); tuidTunerControl = 0; tuidTunerControlResume = TRUE; } VOID GLOBAL_STATE::CreateOutputFiles() { std::string mainExePath = g_mainExe; std::string mainExeName; PathToName(mainExePath, mainExeName); std::string temp; IntegerToString(myPpndbEntry->processNumber, temp); std::string folderName = temp + " - " + mainExeName; PathCombine(s_myDumpDirectory, g_outputDir, folderName); if (!DirectoryExists(s_myDumpDirectory.c_str())) { if (!PortableCreateDirectory(s_myDumpDirectory.c_str())) AlleriaSetLastError(ALLERIA_ERROR_INIT_FAILED); } if (g_outputFormat == OUTPUT_FORMAT_MODE_TEXTUAL) InitOutputFilesTxt(); else if (g_outputFormat == OUTPUT_FORMAT_MODE_BINARY) InitOutputFilesBin(); IMAGE_COLLECTION::Init(); } VOID GLOBAL_STATE::Dispose() { if (gfstream.is_open()) { gfstream.flush(); gfstream.close(); } if (interceptorFileStreamText.is_open()) { interceptorFileStreamText.flush(); interceptorFileStreamText.close(); } if (interceptorFileStreamBinary.is_open()) { interceptorFileStreamBinary.flush(); interceptorFileStreamBinary.close(); } if (walkerFileStream.is_open()) { walkerFileStream.flush(); walkerFileStream.close(); } for (UINT32 i = 0; i < localStreams.size(); ++i) { if ((*localStreams[i]).is_open()) { (*localStreams[i]).flush(); (*localStreams[i]).close(); } } #ifdef TARGET_WINDOWS delete[] s_binaryHeader.mainExePath; delete[] s_binaryHeader.systemDirectory; delete[] s_binaryHeader.currentDirectory; delete[] s_binaryHeader.osVersion; #elif TARGET_LINUX delete[] s_binaryHeader.mainExePath; delete[] s_binaryHeader.cmdLine; free(s_binaryHeader.currentDirectory); #endif /* TARGET_WINDOWS */ MEMORY_REGISTRY::Destroy(); IMAGE_COLLECTION::Dispose(); PIN_SemaphoreFini(&tunerSemaphore); } BOOL GLOBAL_STATE::AboutToTerminateInternal() { void *base = GetPpndbBase(); if (!base) { AlleriaSetLastError(ALLERIA_ERROR_INIT_FAILED); return FALSE; } PMUTEX mutex = Mutex_CreateNamed(PROCESS_TREE_MUTEX_NAME); Mutex_Acquire(mutex); Ppndb *ppndbBase = reinterpret_cast<Ppndb*>(base); PpndbEntry *ppndbEntry = &ppndbBase->base; BOOL sleep = TRUE; UINT child = 0; for (UINT32 i = 0; i < ppndbBase->count; ++i) { if (ppndbEntry->pid == childProcesses[child].first && ppndbEntry->startingTime >= childProcesses[child].second && ppndbEntry->endingTime != -1) ++child; if (child >= childProcesses.size()) { sleep = FALSE; break; } ++ppndbEntry; } Mutex_Release(mutex); Mutex_Close(mutex); return sleep; } VOID GLOBAL_STATE::PatchHeaderTimes(std::ofstream& ofs) { // Save the current value of the put pointer. std::ofstream::pos_type oldPos = ofs.tellp(); // Patch starting time. ofs.seekp(BINARY_HEADER_offsetof(startingTime)); WriteBinary(ofs, s_binaryHeader.startingTime); // Patch ending time. ofs.seekp(BINARY_HEADER_offsetof(endingTime)); WriteBinary(ofs, s_binaryHeader.endingTime); // Restore the old value of the put pointer. ofs.seekp(oldPos); } VOID GLOBAL_STATE::PatchBinaryHeader() { // Patch the starting time and the ending time. s_binaryHeader.endingTime = time(0); PatchHeaderTimes(gfstream); PatchHeaderTimes(interceptorFileStreamBinary); PatchHeaderTimes(walkerFileStream); for (UINT32 i = 0; i < localStreams.size(); ++i) { PatchHeaderTimes((*localStreams[i])); } } VOID GLOBAL_STATE::AboutToTerminate() { if (childProcesses.size() > 0) { // Before this process terminates, it has to make sure that all its live children (if any) // has openned a handle to the PPNDB file-mapping object. // This ensures that the OS doesn't reclaim PPNDB file-mapping object which might happen // if this process terminates before any of the child processes obtain a handle to the object. BOOL sleep = AboutToTerminateInternal(); if (sleep) { /* It's possible that a child process failed to start or terminated abruptly. It's also possible that a child process is yet to access the PPNDB. Either way, put this thread to sleep for some time and hope that all child processes get the chance to access the PPNDB before it's reclaimed by the OS. If this happens, a child process will think it's a genesis. */ ALLERIA_WriteMessage(ALLERIA_REPORT_WAIT_FOR_CHILD); PIN_Sleep(s_childWaitTimeOut); sleep = AboutToTerminateInternal(); if (sleep) { ALLERIA_WriteMessage(ALLERIA_REPORT_WAIT_FOR_CHILD_FAILURE); } else { ALLERIA_WriteMessage(ALLERIA_REPORT_WAIT_FOR_CHILD_SUCCESS); } } } GetCurrentTimestamp(myPpndbEntry->endingTime); } VOID GLOBAL_STATE::AboutToStart() { s_binaryHeader.startingTime = time(0); } UINT32 GLOBAL_STATE::NewChild(UINT32 pid) { TIME_STAMP t; GetCurrentTimestamp(t); childProcesses.push_back(std::make_pair(pid, t)); // The timestamp in childProcesses must not be larger than the timestamp in the PPNDB. // So this has to occur after setting t. UINT32 pn = ComputeChildProcessNumber(pid, myPpndbEntry->pid); // This holds a sligtly more accurate timestamp. s_binaryProcFamily.procs.push_back({ pn, pid, time(0) }); return pn; } VOID GLOBAL_STATE::PatchProcFamily() { UINT64 offset = gfstream.tellp(); // Write the process family section. UINT32 size = (UINT32)s_binaryProcFamily.procs.size(); WriteBinary(gfstream, size); for (UINT32 i = 0; i < s_binaryProcFamily.procs.size(); ++i) { WriteBinary(gfstream, s_binaryProcFamily.procs[i].pn); WriteBinary(gfstream, s_binaryProcFamily.procs[i].pId); WriteBinary(gfstream, s_binaryProcFamily.procs[i].t); } // Patch the process family section offset. gfstream.seekp(s_globalProcFamilyOffset); SECTION_DIRECTORY_ENTRY sde; SECTION_DIRECTORY_ENTRY_SET(sde, BINARY_SECION_TYPE_PROCESS_FAMILY, offset); WriteBinary(gfstream, sde); // No need to restore the put pointer. } VOID GLOBAL_STATE::PatchInsCountsInternal(std::ofstream& ofs) { // Save the current value of the put pointer. std::ofstream::pos_type oldPos = ofs.tellp(); // Patch ins count. ofs.seekp(BINARY_HEADER_offsetof(instructionCount)); WriteBinary(ofs, insCount); // Patch mem in count. ofs.seekp(BINARY_HEADER_offsetof(memoryInstructionCount)); WriteBinary(ofs, insMemCount); // Restore the old value of the put pointer. ofs.seekp(oldPos); } VOID GLOBAL_STATE::PatchInsCounts() { PatchInsCountsInternal(gfstream); for (UINT32 i = 0; i < localStreams.size(); ++i) { PatchInsCountsInternal((*localStreams[i])); } } VOID GLOBAL_STATE::InitBinaryHeaderSectionDirectory() { UINT32 count = 0; // CPUID section. ++count; // Process family section. ++count; // Interceptors section. ++count; // Profile section, function table section and image table section // for each processing thread and one for all app threads. // TODO: processingThreadsIds.size() is dynamic when tuner is enabled. count += 3 * ((KnobTunerEnabled ? Tuner::MaxThreadCount : KnobNumProcessingThreads) + 1); if (KnobLLWEnabled) ++count; // 16 reserved for Alleria and 16 reserved for users. count += 32; s_binaryHeader.dirSize = count; SECTION_DIRECTORY_ENTRY sde; sde.data = 0; for (UINT32 i = 0; i < count; ++i) s_binaryHeader.sectionDirectory.insert(s_binaryHeader.sectionDirectory.begin(), sde); }
30.173222
133
0.737622
[ "object", "vector" ]
dfadf187bd154f63e06bdada671794bfc4494dc4
1,754
cpp
C++
src/modules/osgDB/generated_code/OutputException.pypp.cpp
JaneliaSciComp/osgpyplusplus
a5ae3f69c7e9101a32d8cc95fe680dab292f75ac
[ "BSD-3-Clause" ]
17
2015-06-01T12:19:46.000Z
2022-02-12T02:37:48.000Z
src/modules/osgDB/generated_code/OutputException.pypp.cpp
JaneliaSciComp/osgpyplusplus
a5ae3f69c7e9101a32d8cc95fe680dab292f75ac
[ "BSD-3-Clause" ]
7
2015-07-04T14:36:49.000Z
2015-07-23T18:09:49.000Z
src/modules/osgDB/generated_code/OutputException.pypp.cpp
JaneliaSciComp/osgpyplusplus
a5ae3f69c7e9101a32d8cc95fe680dab292f75ac
[ "BSD-3-Clause" ]
7
2015-11-28T17:00:31.000Z
2020-01-08T07:00:59.000Z
// This file has been generated by Py++. #include "boost/python.hpp" #include "wrap_osgdb.h" #include "wrap_referenced.h" #include "outputexception.pypp.hpp" namespace bp = boost::python; struct OutputException_wrapper : osgDB::OutputException, bp::wrapper< osgDB::OutputException > { OutputException_wrapper(::std::vector< std::string > const & fields, ::std::string const & err ) : osgDB::OutputException( boost::ref(fields), err ) , bp::wrapper< osgDB::OutputException >(){ // constructor } virtual void setThreadSafeRefUnref( bool threadSafe ) { if( bp::override func_setThreadSafeRefUnref = this->get_override( "setThreadSafeRefUnref" ) ) func_setThreadSafeRefUnref( threadSafe ); else{ this->osg::Referenced::setThreadSafeRefUnref( threadSafe ); } } void default_setThreadSafeRefUnref( bool threadSafe ) { osg::Referenced::setThreadSafeRefUnref( threadSafe ); } }; void register_OutputException_class(){ bp::class_< OutputException_wrapper, bp::bases< ::osg::Referenced >, osg::ref_ptr< OutputException_wrapper >, boost::noncopyable >( "OutputException", bp::init< std::vector< std::string > const &, std::string const & >(( bp::arg("fields"), bp::arg("err") )) ) .def( "getError" , (::std::string const & ( ::osgDB::OutputException::* )( )const)( &::osgDB::OutputException::getError ) , bp::return_value_policy< bp::copy_const_reference >() ) .def( "getField" , (::std::string const & ( ::osgDB::OutputException::* )( )const)( &::osgDB::OutputException::getField ) , bp::return_value_policy< bp::copy_const_reference >() ); }
38.130435
267
0.6374
[ "vector" ]
dfb173421de70e975188de6236966ce973f70bd1
514
cpp
C++
rain/src/scene/components/shape/materials/blinn_phong_material.cpp
brenov/rain
a7108dd643c10b96c3b91363be0247a85c514b29
[ "MIT" ]
6
2017-08-11T14:04:23.000Z
2021-08-21T03:20:17.000Z
rain/src/scene/components/shape/materials/blinn_phong_material.cpp
brenov/rain
a7108dd643c10b96c3b91363be0247a85c514b29
[ "MIT" ]
null
null
null
rain/src/scene/components/shape/materials/blinn_phong_material.cpp
brenov/rain
a7108dd643c10b96c3b91363be0247a85c514b29
[ "MIT" ]
null
null
null
#include "scene/components/shape/materials/blinn_phong_material.h" BlinnPhongMaterial::BlinnPhongMaterial(Vec3 ka, Vec3 kd, Vec3 ks, Vec3::RealType p) { this->ka = ka; this->kd = kd; this->ks = ks; this->p = p; } BlinnPhongMaterial::~BlinnPhongMaterial() { /* empty */ } bool BlinnPhongMaterial::scatter(const Ray& r, const HitRecord& hr, RGB& attenuation, Ray& sray) const { (void) (hr); sray = r; // No attenuation attenuation = Vec3(1, 1, 1); return true; }
23.363636
85
0.636187
[ "shape" ]
dfb7835293a16b8c883ebce2c8d5798c10862435
1,717
hpp
C++
algorithms/p629/629.hpp
baishuai/leetcode_go
440ff08cf15e03ee64b3aa18370af1f75e958d18
[ "Apache-2.0" ]
9
2017-06-05T15:10:35.000Z
2021-06-08T03:10:46.000Z
algorithms/p629/629.hpp
baishuai/leetcode
440ff08cf15e03ee64b3aa18370af1f75e958d18
[ "Apache-2.0" ]
3
2017-07-12T14:08:39.000Z
2017-10-11T03:08:15.000Z
algorithms/p629/629.hpp
baishuai/leetcode_go
440ff08cf15e03ee64b3aa18370af1f75e958d18
[ "Apache-2.0" ]
1
2017-07-21T03:51:51.000Z
2017-07-21T03:51:51.000Z
#include <iostream> #include <queue> #include <algorithm> using namespace std; /** * Given two integers n and k, find how many different arrays consist of numbers * from 1 to n such that there are exactly k inverse pairs. We define an inverse pair as following: For ith and jth element in the array, if i < j and a[i] > a[j] then it's an inverse pair; Otherwise, it's not. Since the answer may very large, the answer should be modulo 109 + 7. */ //todo need review class Solution { static const int mod = 1000000007; public: int kInversePairs(int n, int k) { vector<long long> dp(n + k + 2); dp[0] = 1; for (int i = 1; i <= n; ++i) { for (int j = dp.size() - 1 - i; j >= 0; --j) { dp[j + i] -= dp[j]; if (dp[j + i] < 0) { dp[j + i] += mod; } } } for (int i = 1; i <= n; ++i) { for (int j = 0; j < dp.size() - 1; ++j) { dp[j + 1] += dp[j]; dp[j + 1] %= mod; } } return int(dp[k]); } int kInversePairs2(int n, int k) { vector<vector<long long>> dp(n + 1, vector<long long>(k + 1)); dp[1][0] = 1; fill_n(dp[1].begin(), k, 0); for (int i = 2; i <= n; ++i) { dp[i][0] = 1; for (int j = 1; j <= k; ++j) { dp[i][j] = (dp[i][j - 1] + dp[i - 1][j]); if (dp[i][j] > mod) { dp[i][j] -= mod; } if (j >= i) { dp[i][j] = (dp[i][j] - dp[i - 1][j - 1]) % mod; } } } return dp[n][k]; } };
25.626866
80
0.414677
[ "vector" ]
dfbd644cb2f3b2366a6631456c2c6cc729c29cb3
3,470
cpp
C++
multimedia/directx/gamectrl/default/ff.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
multimedia/directx/gamectrl/default/ff.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
multimedia/directx/gamectrl/default/ff.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//=========================================================================== // FF.CPP // // Functions: // ForceFeedback_DlgProc() // //=========================================================================== #include "cplsvr1.h" #include "dicputil.h" //=========================================================================== // (C) Copyright 1997 Microsoft Corp. All rights reserved. // // You have a royalty-free right to use, modify, reproduce and // distribute the Sample Files (and/or any modified version) in // any way you find useful, provided that you agree that // Microsoft has no warranty obligations or liability for any // Sample Application Files which are modified. //=========================================================================== #define ID_SLIDERTIMER 2800 #define TIMER_FREQ 850 //=========================================================================== // ForceFeedback_DlgProc // // Parameters: // HWND hWnd - handle to dialog window // UINT uMsg - dialog message // WPARAM wParam - message specific data // LPARAM lParam - message specific data // // Returns: BOOL // //=========================================================================== INT_PTR CALLBACK ForceFeedback_DlgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { CDIGameCntrlPropSheet_X *pdiCpl; // = (CDIGameCntrlPropSheet_X*)GetWindowLong(hWnd, DWL_USER); static LPDIRECTINPUTDEVICE2 pdiDevice2 = NULL; static CSliderCtrl CReturnSlider, CForceSlider; switch(uMsg) { // OnInit case WM_INITDIALOG: { // get ptr to our object pdiCpl = (CDIGameCntrlPropSheet_X*)((LPPROPSHEETPAGE)lParam)->lParam; // Save our pointer so we can access it later SetWindowLong(hWnd, DWL_USER, (LPARAM)pdiCpl); // initialize DirectInput if(FAILED(InitDInput(GetParent(hWnd), pdiCpl))) { OutputDebugString(TEXT("FF.CPP: WM_INIT: InitDInput FAILED!\n")); } // Get the device2 interface pointer pdiCpl->GetDevice(&pdiDevice2); // Setup the Sliders HWND hCtrl = GetDlgItem(hWnd, IDC_SLIDER1); ASSERT (hCtrl); CReturnSlider.Attach(hCtrl); hCtrl = GetDlgItem(hWnd, IDC_SLIDER2); ASSERT (hCtrl); CForceSlider.Attach(hCtrl); // BLJ: TODO!!! // Setup the granularity of the sliders based on the device! // Set up timer to monitor button presses on the device!!! // SetTimer(hWnd, ID_SLIDERTIMER, TIMER_FREQ, 0); } break; // end of WM_INITDIALOG // OnTimer case WM_TIMER: break; // OnDestroy case WM_DESTROY: // KillTimer(hWnd, ID_SLIDERTIMER); CForceSlider.Detach(); CReturnSlider.Detach(); // Get the device2 interface pointer pdiDevice2->Unacquire(); break; // end of WM_DESTROY // OnNotify case WM_NOTIFY: switch(((NMHDR *)lParam)->code) { case PSN_SETACTIVE: // Do that Acquire thing... if(FAILED(pdiDevice2->Acquire())) { OutputDebugString(TEXT("FF.CPP: PSN_SETACTIVE: Acquire() FAILED!\n")); } break; case PSN_KILLACTIVE: // Do that Unacquire thing... pdiDevice2->Unacquire(); break; } break; // end of WM_NOTIFY } return FALSE; } //*** end Test_DlgProc()
28.442623
99
0.535447
[ "object" ]
dfc5d6dd1626e9785e43a5b3dccaaf135f07f745
1,644
cpp
C++
Atcoder/ABC183_F.cpp
edwinsun98/Competitive-Programming-Solutions
67d79a2193e6912a644d27b9a399ba02a60766b7
[ "MIT" ]
null
null
null
Atcoder/ABC183_F.cpp
edwinsun98/Competitive-Programming-Solutions
67d79a2193e6912a644d27b9a399ba02a60766b7
[ "MIT" ]
null
null
null
Atcoder/ABC183_F.cpp
edwinsun98/Competitive-Programming-Solutions
67d79a2193e6912a644d27b9a399ba02a60766b7
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #define p push #define f first #define s second #define all(vec) begin(vec), end(vec) #define pii pair<int,int> #define pli pair<ll,int> #define pil pair<int,ll> #define pll pair<ll,ll> #define ft front() #define bk back() #define pf push_front #define pb push_back #define lb lower_bound #define ub upper_bound typedef long long ll; using namespace std; const int N = (int)2e5+69; map<int,int> adj[N]; /*---------Disjoint Set---------*/ int parent[N], sz[N]; int find_set(int v){ if (v == parent[v])return v; return find_set(parent[v]); } void union_set(int a, int b){ int pa = find_set(a); int pb = find_set(b); if(sz[pa] < sz[pb]){ sz[pb] += sz[pa]; parent[pa] = pb; for(auto i : adj[pa]){ adj[pb][i.f] += i.s; } } else{ sz[pa] += sz[pb]; parent[pb] = pa; for(auto i : adj[pb]){ adj[pa][i.f] += i.s; } } } /*---------Disjoint Set End---------*/ int n, q; int main(){ ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n >> q; vector<int> a(n+1); for(int i = 1; i <= n; i++){ cin >> a[i]; parent[i] = i; sz[i] = 1; adj[i][a[i]] = 1; } for(int i = 0; i < q; i++){ int cmd, x, y; cin >> cmd >> x >> y; if(cmd == 1){ if(find_set(x) != find_set(y)){ union_set(x, y); } } else{ int t = find_set(x); cout << adj[t][y] << '\n'; } } }
20.810127
53
0.484793
[ "vector" ]
dfcc6ea910c3fc6681c583fad602556fc1f6df11
14,657
cc
C++
media/cast/rtcp/rtcp_unittest.cc
kurli/chromium-crosswalk
f4c5d15d49d02b74eb834325e4dff50b16b53243
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
media/cast/rtcp/rtcp_unittest.cc
kurli/chromium-crosswalk
f4c5d15d49d02b74eb834325e4dff50b16b53243
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
media/cast/rtcp/rtcp_unittest.cc
kurli/chromium-crosswalk
f4c5d15d49d02b74eb834325e4dff50b16b53243
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/test/simple_test_tick_clock.h" #include "media/cast/cast_defines.h" #include "media/cast/pacing/paced_sender.h" #include "media/cast/rtcp/mock_rtcp_receiver_feedback.h" #include "media/cast/rtcp/mock_rtcp_sender_feedback.h" #include "media/cast/rtcp/rtcp.h" #include "media/cast/rtcp/test_rtcp_packet_builder.h" #include "testing/gmock/include/gmock/gmock.h" namespace media { namespace cast { using testing::_; static const uint32 kSenderSsrc = 0x10203; static const uint32 kReceiverSsrc = 0x40506; static const uint32 kUnknownSsrc = 0xDEAD; static const std::string kCName("test@10.1.1.1"); static const uint32 kRtcpIntervalMs = 500; static const int64 kStartMillisecond = 123456789; static const int64 kAddedDelay = 123; static const int64 kAddedShortDelay= 100; class LocalRtcpTransport : public PacedPacketSender { public: explicit LocalRtcpTransport(base::SimpleTestTickClock* testing_clock) : short_delay_(false), testing_clock_(testing_clock) {} void SetRtcpReceiver(Rtcp* rtcp) { rtcp_ = rtcp; } void SetShortDelay() { short_delay_ = true; } virtual bool SendRtcpPacket(const std::vector<uint8>& packet) OVERRIDE { if (short_delay_) { testing_clock_->Advance( base::TimeDelta::FromMilliseconds(kAddedShortDelay)); } else { testing_clock_->Advance(base::TimeDelta::FromMilliseconds(kAddedDelay)); } rtcp_->IncomingRtcpPacket(&(packet[0]), packet.size()); return true; } virtual bool SendPacket(const std::vector<uint8>& packet, int num_of_packets) OVERRIDE { return false; } virtual bool ResendPacket(const std::vector<uint8>& packet, int num_of_packets) OVERRIDE { return false; } private: bool short_delay_; Rtcp* rtcp_; base::SimpleTestTickClock* testing_clock_; }; class RtcpPeer : public Rtcp { public: RtcpPeer(RtcpSenderFeedback* sender_feedback, PacedPacketSender* const paced_packet_sender, RtpSenderStatistics* rtp_sender_statistics, RtpReceiverStatistics* rtp_receiver_statistics, RtcpMode rtcp_mode, const base::TimeDelta& rtcp_interval, bool sending_media, uint32 local_ssrc, const std::string& c_name) : Rtcp(sender_feedback, paced_packet_sender, rtp_sender_statistics, rtp_receiver_statistics, rtcp_mode, rtcp_interval, sending_media, local_ssrc, c_name) { } using Rtcp::CheckForWrapAround; using Rtcp::OnReceivedLipSyncInfo; }; class RtcpTest : public ::testing::Test { protected: RtcpTest() : transport_(&testing_clock_) { testing_clock_.Advance( base::TimeDelta::FromMilliseconds(kStartMillisecond)); } ~RtcpTest() {} void SetUp() { EXPECT_CALL(mock_sender_feedback_, OnReceivedReportBlock(_)).Times(0); EXPECT_CALL(mock_sender_feedback_, OnReceivedIntraFrameRequest()).Times(0); EXPECT_CALL(mock_sender_feedback_, OnReceivedRpsi(_, _)).Times(0); EXPECT_CALL(mock_sender_feedback_, OnReceivedRemb(_)).Times(0); EXPECT_CALL(mock_sender_feedback_, OnReceivedNackRequest(_)).Times(0); EXPECT_CALL(mock_sender_feedback_, OnReceivedCastFeedback(_)).Times(0); } base::SimpleTestTickClock testing_clock_; LocalRtcpTransport transport_; MockRtcpSenderFeedback mock_sender_feedback_; }; TEST_F(RtcpTest, TimeToSend) { base::TimeTicks start_time = base::TimeTicks::FromInternalValue(kStartMillisecond * 1000); Rtcp rtcp(&mock_sender_feedback_, &transport_, NULL, NULL, kRtcpCompound, base::TimeDelta::FromMilliseconds(kRtcpIntervalMs), true, // Media sender. kSenderSsrc, kCName); rtcp.set_clock(&testing_clock_); transport_.SetRtcpReceiver(&rtcp); EXPECT_LE(start_time, rtcp.TimeToSendNextRtcpReport()); EXPECT_GE(start_time + base::TimeDelta::FromMilliseconds( kRtcpIntervalMs * 3 / 2), rtcp.TimeToSendNextRtcpReport()); base::TimeDelta delta = rtcp.TimeToSendNextRtcpReport() - start_time; testing_clock_.Advance(delta); EXPECT_EQ(testing_clock_.NowTicks(), rtcp.TimeToSendNextRtcpReport()); } TEST_F(RtcpTest, BasicSenderReport) { Rtcp rtcp(&mock_sender_feedback_, &transport_, NULL, NULL, kRtcpCompound, base::TimeDelta::FromMilliseconds(kRtcpIntervalMs), true, // Media sender. kSenderSsrc, kCName); transport_.SetRtcpReceiver(&rtcp); rtcp.SendRtcpReport(kUnknownSsrc); } TEST_F(RtcpTest, BasicReceiverReport) { EXPECT_CALL(mock_sender_feedback_, OnReceivedReportBlock(_)).Times(1); Rtcp rtcp(&mock_sender_feedback_, &transport_, NULL, NULL, kRtcpCompound, base::TimeDelta::FromMilliseconds(kRtcpIntervalMs), false, // Media receiver. kSenderSsrc, kCName); transport_.SetRtcpReceiver(&rtcp); rtcp.SetRemoteSSRC(kSenderSsrc); rtcp.SendRtcpReport(kSenderSsrc); } TEST_F(RtcpTest, BasicPli) { EXPECT_CALL(mock_sender_feedback_, OnReceivedReportBlock(_)).Times(1); EXPECT_CALL(mock_sender_feedback_, OnReceivedIntraFrameRequest()).Times(1); // Media receiver. Rtcp rtcp(&mock_sender_feedback_, &transport_, NULL, NULL, kRtcpReducedSize, base::TimeDelta::FromMilliseconds(kRtcpIntervalMs), false, kSenderSsrc, kCName); rtcp.set_clock(&testing_clock_); transport_.SetRtcpReceiver(&rtcp); rtcp.SetRemoteSSRC(kSenderSsrc); rtcp.SendRtcpPli(kSenderSsrc); } TEST_F(RtcpTest, BasicCast) { EXPECT_CALL(mock_sender_feedback_, OnReceivedCastFeedback(_)).Times(1); // Media receiver. Rtcp rtcp(&mock_sender_feedback_, &transport_, NULL, NULL, kRtcpReducedSize, base::TimeDelta::FromMilliseconds(kRtcpIntervalMs), false, kSenderSsrc, kCName); rtcp.set_clock(&testing_clock_); transport_.SetRtcpReceiver(&rtcp); rtcp.SetRemoteSSRC(kSenderSsrc); RtcpCastMessage cast_message(kSenderSsrc); cast_message.ack_frame_id_ = kAckFrameId; std::set<uint16_t> missing_packets; cast_message.missing_frames_and_packets_[ kLostFrameId] = missing_packets; missing_packets.insert(kLostPacketId1); missing_packets.insert(kLostPacketId2); missing_packets.insert(kLostPacketId3); cast_message.missing_frames_and_packets_[ kFrameIdWithLostPackets] = missing_packets; rtcp.SendRtcpCast(cast_message); } TEST_F(RtcpTest, Rtt) { // Media receiver. LocalRtcpTransport receiver_transport(&testing_clock_); Rtcp rtcp_receiver(&mock_sender_feedback_, &receiver_transport, NULL, NULL, kRtcpReducedSize, base::TimeDelta::FromMilliseconds(kRtcpIntervalMs), false, kReceiverSsrc, kCName); rtcp_receiver.set_clock(&testing_clock_); // Media sender. LocalRtcpTransport sender_transport(&testing_clock_); Rtcp rtcp_sender(&mock_sender_feedback_, &sender_transport, NULL, NULL, kRtcpReducedSize, base::TimeDelta::FromMilliseconds(kRtcpIntervalMs), true, kSenderSsrc, kCName); rtcp_sender.set_clock(&testing_clock_); receiver_transport.SetRtcpReceiver(&rtcp_sender); sender_transport.SetRtcpReceiver(&rtcp_receiver); rtcp_sender.SetRemoteSSRC(kReceiverSsrc); rtcp_receiver.SetRemoteSSRC(kSenderSsrc); EXPECT_CALL(mock_sender_feedback_, OnReceivedReportBlock(_)).Times(2); base::TimeDelta rtt; base::TimeDelta avg_rtt; base::TimeDelta min_rtt; base::TimeDelta max_rtt; EXPECT_FALSE(rtcp_sender.Rtt(&rtt, &avg_rtt, &min_rtt, &max_rtt)); EXPECT_FALSE(rtcp_receiver.Rtt(&rtt, &avg_rtt, &min_rtt, &max_rtt)); rtcp_sender.SendRtcpReport(kSenderSsrc); rtcp_receiver.SendRtcpReport(kSenderSsrc); EXPECT_TRUE(rtcp_sender.Rtt(&rtt, &avg_rtt, &min_rtt, &max_rtt)); EXPECT_FALSE(rtcp_receiver.Rtt(&rtt, &avg_rtt, &min_rtt, &max_rtt)); EXPECT_NEAR(2 * kAddedDelay, rtt.InMilliseconds(), 1); EXPECT_NEAR(2 * kAddedDelay, avg_rtt.InMilliseconds(), 1); EXPECT_NEAR(2 * kAddedDelay, min_rtt.InMilliseconds(), 1); EXPECT_NEAR(2 * kAddedDelay, max_rtt.InMilliseconds(), 1); rtcp_sender.SendRtcpReport(kSenderSsrc); EXPECT_TRUE(rtcp_receiver.Rtt(&rtt, &avg_rtt, &min_rtt, &max_rtt)); EXPECT_NEAR(2 * kAddedDelay, rtt.InMilliseconds(), 1); EXPECT_NEAR(2 * kAddedDelay, avg_rtt.InMilliseconds(), 1); EXPECT_NEAR(2 * kAddedDelay, min_rtt.InMilliseconds(), 1); EXPECT_NEAR(2 * kAddedDelay, max_rtt.InMilliseconds(), 1); receiver_transport.SetShortDelay(); sender_transport.SetShortDelay(); rtcp_receiver.SendRtcpReport(kSenderSsrc); EXPECT_TRUE(rtcp_sender.Rtt(&rtt, &avg_rtt, &min_rtt, &max_rtt)); EXPECT_NEAR(kAddedDelay + kAddedShortDelay, rtt.InMilliseconds(), 1); EXPECT_NEAR((kAddedShortDelay + 3 * kAddedDelay) / 2, avg_rtt.InMilliseconds(), 1); EXPECT_NEAR(kAddedDelay + kAddedShortDelay, min_rtt.InMilliseconds(), 1); EXPECT_NEAR(2 * kAddedDelay, max_rtt.InMilliseconds(), 1); rtcp_sender.SendRtcpReport(kSenderSsrc); EXPECT_TRUE(rtcp_receiver.Rtt(&rtt, &avg_rtt, &min_rtt, &max_rtt)); EXPECT_NEAR(2 * kAddedShortDelay, rtt.InMilliseconds(), 1); EXPECT_NEAR((2 * kAddedShortDelay + 2 * kAddedDelay) / 2, avg_rtt.InMilliseconds(), 1); EXPECT_NEAR(2 * kAddedShortDelay, min_rtt.InMilliseconds(), 1); EXPECT_NEAR(2 * kAddedDelay, max_rtt.InMilliseconds(), 1); } TEST_F(RtcpTest, NtpAndTime) { RtcpPeer rtcp_peer(&mock_sender_feedback_, NULL, NULL, NULL, kRtcpReducedSize, base::TimeDelta::FromMilliseconds(kRtcpIntervalMs), false, kReceiverSsrc, kCName); rtcp_peer.set_clock(&testing_clock_); uint32 ntp_seconds = 0; uint32 ntp_fractions = 0; base::TimeTicks input_time = base::TimeTicks::FromInternalValue( 12345678901000LL + kNtpEpochDeltaMicroseconds); ConvertTimeToNtp(input_time, &ntp_seconds, &ntp_fractions); EXPECT_EQ(12345678u, ntp_seconds); EXPECT_EQ(input_time, ConvertNtpToTime(ntp_seconds, ntp_fractions)); } TEST_F(RtcpTest, WrapAround) { RtcpPeer rtcp_peer(&mock_sender_feedback_, NULL, NULL, NULL, kRtcpReducedSize, base::TimeDelta::FromMilliseconds(kRtcpIntervalMs), false, kReceiverSsrc, kCName); rtcp_peer.set_clock(&testing_clock_); uint32 new_timestamp = 0; uint32 old_timestamp = 0; EXPECT_EQ(0, rtcp_peer.CheckForWrapAround(new_timestamp, old_timestamp)); new_timestamp = 1234567890; old_timestamp = 1234567000; EXPECT_EQ(0, rtcp_peer.CheckForWrapAround(new_timestamp, old_timestamp)); new_timestamp = 1234567000; old_timestamp = 1234567890; EXPECT_EQ(0, rtcp_peer.CheckForWrapAround(new_timestamp, old_timestamp)); new_timestamp = 123; old_timestamp = 4234567890; EXPECT_EQ(1, rtcp_peer.CheckForWrapAround(new_timestamp, old_timestamp)); new_timestamp = 4234567890; old_timestamp = 123; EXPECT_EQ(-1, rtcp_peer.CheckForWrapAround(new_timestamp, old_timestamp)); } TEST_F(RtcpTest, RtpTimestampInSenderTime) { RtcpPeer rtcp_peer(&mock_sender_feedback_, NULL, NULL, NULL, kRtcpReducedSize, base::TimeDelta::FromMilliseconds(kRtcpIntervalMs), false, kReceiverSsrc, kCName); rtcp_peer.set_clock(&testing_clock_); int frequency = 32000; uint32 rtp_timestamp = 64000; base::TimeTicks rtp_timestamp_in_ticks; // Test fail before we get a OnReceivedLipSyncInfo. EXPECT_FALSE(rtcp_peer.RtpTimestampInSenderTime(frequency, rtp_timestamp, &rtp_timestamp_in_ticks)); uint32 ntp_seconds = 0; uint32 ntp_fractions = 0; base::TimeTicks input_time = base::TimeTicks::FromInternalValue( 12345678901000LL + kNtpEpochDeltaMicroseconds); // Test exact match. ConvertTimeToNtp(input_time, &ntp_seconds, &ntp_fractions); rtcp_peer.OnReceivedLipSyncInfo(rtp_timestamp, ntp_seconds, ntp_fractions); EXPECT_TRUE(rtcp_peer.RtpTimestampInSenderTime(frequency, rtp_timestamp, &rtp_timestamp_in_ticks)); EXPECT_EQ(input_time, rtp_timestamp_in_ticks); // Test older rtp_timestamp. rtp_timestamp = 32000; EXPECT_TRUE(rtcp_peer.RtpTimestampInSenderTime(frequency, rtp_timestamp, &rtp_timestamp_in_ticks)); EXPECT_EQ(input_time - base::TimeDelta::FromMilliseconds(1000), rtp_timestamp_in_ticks); // Test older rtp_timestamp with wrap. rtp_timestamp = 4294903296; EXPECT_TRUE(rtcp_peer.RtpTimestampInSenderTime(frequency, rtp_timestamp, &rtp_timestamp_in_ticks)); EXPECT_EQ(input_time - base::TimeDelta::FromMilliseconds(4000), rtp_timestamp_in_ticks); // Test newer rtp_timestamp. rtp_timestamp = 128000; EXPECT_TRUE(rtcp_peer.RtpTimestampInSenderTime(frequency, rtp_timestamp, &rtp_timestamp_in_ticks)); EXPECT_EQ(input_time + base::TimeDelta::FromMilliseconds(2000), rtp_timestamp_in_ticks); // Test newer rtp_timestamp with wrap. rtp_timestamp = 4294903296; rtcp_peer.OnReceivedLipSyncInfo(rtp_timestamp, ntp_seconds, ntp_fractions); rtp_timestamp = 64000; EXPECT_TRUE(rtcp_peer.RtpTimestampInSenderTime(frequency, rtp_timestamp, &rtp_timestamp_in_ticks)); EXPECT_EQ(input_time + base::TimeDelta::FromMilliseconds(4000), rtp_timestamp_in_ticks); } } // namespace cast } // namespace media
35.6618
79
0.673467
[ "vector" ]
dfcc70c681f4480c237261638626141aba35f237
30,823
cpp
C++
TravelCrash/Plugins/HoudiniEngine/Source/HoudiniEngineRuntime/Private/Tests/HoudiniEngineRuntimeTest.cpp
all-in-one-of/HoudiniBugs
00ccf448e4536241c9e4cf25ee4906f38479032c
[ "Unlicense" ]
null
null
null
TravelCrash/Plugins/HoudiniEngine/Source/HoudiniEngineRuntime/Private/Tests/HoudiniEngineRuntimeTest.cpp
all-in-one-of/HoudiniBugs
00ccf448e4536241c9e4cf25ee4906f38479032c
[ "Unlicense" ]
null
null
null
TravelCrash/Plugins/HoudiniEngine/Source/HoudiniEngineRuntime/Private/Tests/HoudiniEngineRuntimeTest.cpp
all-in-one-of/HoudiniBugs
00ccf448e4536241c9e4cf25ee4906f38479032c
[ "Unlicense" ]
null
null
null
#include "HoudiniApi.h" #if WITH_EDITOR #include "CoreMinimal.h" #include "Editor.h" #include "Misc/AutomationTest.h" #include "FileCacheUtilities.h" #include "StaticMeshResources.h" #include "LevelEditorViewport.h" #include "AssetRegistryModule.h" #include "PropertyEditorModule.h" #include "Tests/AutomationCommon.h" #include "IDetailsView.h" #include "HoudiniEngine.h" #include "HoudiniAsset.h" #include "HoudiniEngineUtils.h" #include "HoudiniParamUtils.h" #include "HoudiniCookHandler.h" #include "HoudiniRuntimeSettings.h" #include "HoudiniAssetActor.h" #include "HoudiniAssetComponent.h" #include "HoudiniEngineRuntimeTest.h" #include "HoudiniAssetParameterInt.h" DEFINE_LOG_CATEGORY_STATIC( LogHoudiniTests, Log, All ); static constexpr int32 kTestFlags = EAutomationTestFlags::EditorContext | EAutomationTestFlags::ProductFilter; IMPLEMENT_SIMPLE_AUTOMATION_TEST( FHoudiniEngineRuntimeMeshMarshalTest, "Houdini.Runtime.MeshMarshalTest", kTestFlags ) IMPLEMENT_SIMPLE_AUTOMATION_TEST( FHoudiniEngineRuntimeUploadStaticMeshTest, "Houdini.Runtime.UploadStaticMesh", kTestFlags ) IMPLEMENT_SIMPLE_AUTOMATION_TEST( FHoudiniEngineRuntimeActorTest, "Houdini.Runtime.ActorTest", kTestFlags ) IMPLEMENT_SIMPLE_AUTOMATION_TEST( FHoudiniEngineRuntimeParamTest, "Houdini.Runtime.ParamTest", kTestFlags ) IMPLEMENT_SIMPLE_AUTOMATION_TEST( FHoudiniEngineRuntimeBatchTest, "Houdini.Runtime.BatchTest", kTestFlags ) static float TestTickDelay = 1.0f; struct FTestCookHandler : public FHoudiniCookParams, public IHoudiniCookHandler { /** Transient cache of last baked parts */ TMap<FHoudiniGeoPartObject, TWeakObjectPtr<class UPackage> > BakedStaticMeshPackagesForParts_; /** Transient cache of last baked materials and textures */ TMap<FString, TWeakObjectPtr<class UPackage> > BakedMaterialPackagesForIds_; /** Cache of the temp cook content packages created by the asset for its materials/textures **/ TMap<FHoudiniGeoPartObject, TWeakObjectPtr<class UPackage> > CookedTemporaryStaticMeshPackages_; /** Cache of the temp cook content packages created by the asset for its materials/textures **/ TMap<FString, TWeakObjectPtr<class UPackage> > CookedTemporaryPackages_; FTestCookHandler( class UHoudiniAsset* InHoudiniAsset ) : FHoudiniCookParams( InHoudiniAsset ) { BakedStaticMeshPackagesForParts = &BakedStaticMeshPackagesForParts_; BakedMaterialPackagesForIds = &BakedMaterialPackagesForIds_; CookedTemporaryStaticMeshPackages = &CookedTemporaryStaticMeshPackages_; CookedTemporaryPackages = &CookedTemporaryPackages_; } virtual ~FTestCookHandler() { } virtual FString GetBakingBaseName( const struct FHoudiniGeoPartObject& GeoPartObject ) const override { if( GeoPartObject.HasCustomName() ) { return GeoPartObject.PartName; } return FString::Printf( TEXT( "test_%d_%d_%d_%d" ), GeoPartObject.ObjectId, GeoPartObject.GeoId, GeoPartObject.PartId, GeoPartObject.SplitId ); } virtual void SetStaticMeshGenerationParameters( class UStaticMesh* StaticMesh ) const override { } virtual class UMaterialInterface * GetAssignmentMaterial( const FString& MaterialName ) override { return nullptr; } virtual void ClearAssignmentMaterials() override { } virtual void AddAssignmentMaterial( const FString& MaterialName, class UMaterialInterface* MaterialInterface ) override { } virtual class UMaterialInterface * GetReplacementMaterial( const struct FHoudiniGeoPartObject& GeoPartObject, const FString& MaterialName ) override { return nullptr; } }; struct FHVert { int32 PointNum; float Nx, Ny, Nz; float uv0, uv1, uv2; }; struct FSortVectors { bool operator()( const FVector& A, const FVector& B ) const { if( A.X == B.X ) if( A.Y == B.Y ) if( A.Z == B.Z ) return false; else return A.Z < B.Z; else return A.Y < B.Y; else return A.X < B.X; } }; #if 0 struct FParamBlock { }; typedef TMap< FHoudiniGeoPartObject, UStaticMesh * > PartMeshMap; struct IHoudiniPluginAPI { virtual void InstatiateLiveAsset( const char* AssetPath, TFunction<void ( HAPI_NodeId, FParamBlock ParamBlock )> OnComplete ) { FFunctionGraphTask::CreateAndDispatchWhenReady( [=]() { OnComplete( -1, FParamBlock() ); } , TStatId(), nullptr, ENamedThreads::GameThread ); } virtual void CookLiveAsset( HAPI_NodeId AssetId, const FParamBlock& ParamBlock, PartMeshMap& CurrentParts, TFunction<void ( bool, PartMeshMap )> OnComplete ) { FFunctionGraphTask::CreateAndDispatchWhenReady( [=]() { PartMeshMap NewParts; OnComplete( true, NewParts ); } , TStatId(), nullptr, ENamedThreads::GameThread ); } }; #endif UWorld* HelperGetWorld() { return GWorld; } UObject* FindAssetUObject( FName AssetUObjectPath ) { FAssetRegistryModule& AssetRegistryModule = FModuleManager::LoadModuleChecked<FAssetRegistryModule>( "AssetRegistry" ); TArray<FAssetData> AssetData; AssetRegistryModule.Get().GetAssetsByPackageName( AssetUObjectPath, AssetData ); if( AssetData.Num() > 0 ) { return AssetData[ 0 ].GetAsset(); } return nullptr; } template<typename T> T* HelperInstantiateAssetActor( FAutomationTestBase* Test, FName AssetPath ) { if( UHoudiniAsset* TestAsset = Cast<UHoudiniAsset>( FindAssetUObject( AssetPath ) ) ) { GEditor->ClickLocation = FVector::ZeroVector; GEditor->ClickPlane = FPlane( GEditor->ClickLocation, FVector::UpVector ); TArray<AActor*> NewActors = FLevelEditorViewportClient::TryPlacingActorFromObject( HelperGetWorld()->GetLevel( 0 ), TestAsset, true, RF_Transactional, nullptr ); Test->TestTrue( TEXT( "Placed Actor" ), NewActors.Num() > 0 ); if( NewActors.Num() > 0 ) { return Cast<T>( NewActors[ 0 ] ); } } return nullptr; } void HelperInstantiateAsset( FAutomationTestBase* Test, FName AssetPath, TFunction<void( FHoudiniEngineTaskInfo, UHoudiniAsset* )> OnFinishedInstantiate ) { UHoudiniAsset* TestAsset = Cast<UHoudiniAsset>( FindAssetUObject(AssetPath) ); HAPI_AssetLibraryId AssetLibraryId = -1; TArray< HAPI_StringHandle > AssetNames; HAPI_StringHandle AssetHapiName = -1; if( FHoudiniEngineUtils::GetAssetNames( TestAsset, AssetLibraryId, AssetNames ) ) { AssetHapiName = AssetNames[ 0 ]; } auto InstGUID = FGuid::NewGuid(); FHoudiniEngineTask Task( EHoudiniEngineTaskType::AssetInstantiation, InstGUID ); Task.Asset = TestAsset; Task.ActorName = TEXT( "TestActor" ); Task.bLoadedComponent = false; Task.AssetLibraryId = AssetLibraryId; Task.AssetHapiName = AssetHapiName; FHoudiniEngine::Get().AddTask( Task ); Test->AddCommand( new FDelayedFunctionLatentCommand( [=]() { // check back on status on Instantiate FHoudiniEngineTaskInfo InstantiateTaskInfo = {}; InstantiateTaskInfo.AssetId = -1; if( FHoudiniEngine::Get().RetrieveTaskInfo( InstGUID, InstantiateTaskInfo ) ) { if( InstantiateTaskInfo.TaskState != EHoudiniEngineTaskState::FinishedInstantiation ) { Test->AddError( FString::Printf( TEXT( "AssetInstantiation failed" ) ) ); } UE_LOG( LogHoudiniTests, Log, TEXT( "InstantiateTask.StatusText: %s" ), *InstantiateTaskInfo.StatusText.ToString() ); FHoudiniEngine::Get().RemoveTaskInfo( InstGUID ); OnFinishedInstantiate( InstantiateTaskInfo, TestAsset ); } }, 1.f )); } void HelperDeleteAsset( FAutomationTestBase* Test, HAPI_NodeId AssetId ) { // Now destroy asset auto DelGUID = FGuid::NewGuid(); FHoudiniEngineTask DeleteTask( EHoudiniEngineTaskType::AssetDeletion, DelGUID ); DeleteTask.AssetId = AssetId; FHoudiniEngine::Get().AddTask( DeleteTask ); Test->AddCommand( new FDelayedFunctionLatentCommand( [=] { FHoudiniEngineTaskInfo DeleteTaskInfo; if( FHoudiniEngine::Get().RetrieveTaskInfo( DelGUID, DeleteTaskInfo ) ) { // we don't have a task state to check since it's fire and forget if( DeleteTaskInfo.Result != HAPI_RESULT_SUCCESS ) { Test->AddError( FString::Printf( TEXT( "DeleteTask.Result: %d" ), (int32)DeleteTaskInfo.Result ) ); } UE_LOG( LogHoudiniTests, Log, TEXT( "DeleteTask.StatusText: %s" ), *DeleteTaskInfo.StatusText.ToString() ); FHoudiniEngine::Get().RemoveTaskInfo( DelGUID ); } }, 1.f ) ); } void HelperCookAsset( FAutomationTestBase* Test, class UHoudiniAsset* InHoudiniAsset, HAPI_NodeId AssetId, TFunction<void( bool, TMap< FHoudiniGeoPartObject, UStaticMesh * > )> OnFinishedCook ) { auto CookGUID = FGuid::NewGuid(); FHoudiniEngineTask CookTask( EHoudiniEngineTaskType::AssetCooking, CookGUID ); CookTask.AssetId = AssetId; FHoudiniEngine::Get().AddTask( CookTask ); Test->AddCommand( new FDelayedFunctionLatentCommand( [=] { FHoudiniEngineTaskInfo CookTaskInfo; if( FHoudiniEngine::Get().RetrieveTaskInfo( CookGUID, CookTaskInfo ) ) { bool CookSuccess = false; TMap< FHoudiniGeoPartObject, UStaticMesh * > StaticMeshesOut; if( CookTaskInfo.TaskState != EHoudiniEngineTaskState::FinishedCooking ) { Test->AddError( FString::Printf( TEXT( "CookTaskInfo.Result: %d, TaskState: %d" ), (int32)CookTaskInfo.Result, (int32)CookTaskInfo.TaskState ) ); } else { // Marshal the static mesh data float GeoScale = 1.f; if( const UHoudiniRuntimeSettings * HoudiniRuntimeSettings = GetDefault< UHoudiniRuntimeSettings >() ) { GeoScale = HoudiniRuntimeSettings->GeneratedGeometryScaleFactor; } TMap< FHoudiniGeoPartObject, UStaticMesh * > StaticMeshesIn; FTestCookHandler CookHandler ( InHoudiniAsset ); CookHandler.HoudiniCookManager = &CookHandler; CookHandler.StaticMeshBakeMode = EBakeMode::CookToTemp; FTransform AssetTransform; CookSuccess = FHoudiniEngineUtils::CreateStaticMeshesFromHoudiniAsset( AssetId, CookHandler, false, false, StaticMeshesIn, StaticMeshesOut, AssetTransform ); } OnFinishedCook( CookSuccess, StaticMeshesOut ); } }, 2.f )); } void HelperTestMeshEqual( FAutomationTestBase* Test, UStaticMesh* MeshA, UStaticMesh* MeshB ) { int32 InputNumVerts = 0; int32 InputNumTris = 0; Test->TestTrue( TEXT( "MeshA Valid" ), MeshA->RenderData->LODResources.Num() > 0 ); if( MeshA->RenderData->LODResources.Num() > 0 ) { FPositionVertexBuffer& VB = MeshA->RenderData->LODResources[ 0 ].VertexBuffers.PositionVertexBuffer; InputNumVerts = VB.GetNumVertices(); InputNumTris = MeshA->RenderData->LODResources[ 0 ].GetNumTriangles(); } Test->TestTrue( TEXT( "MeshB Valid" ), MeshB->RenderData->LODResources.Num() > 0 ); if( MeshB->RenderData->LODResources.Num() > 0 ) { Test->TestEqual( TEXT( "Num Triangles" ), InputNumTris, MeshB->RenderData->LODResources[ 0 ].GetNumTriangles() ); FPositionVertexBuffer& VB = MeshB->RenderData->LODResources[ 0 ].VertexBuffers.PositionVertexBuffer; Test->TestEqual( TEXT( "Num Verts" ), VB.GetNumVertices(), InputNumVerts ); } } bool FHoudiniEngineRuntimeParamTest::RunTest( const FString& Paramters ) { HelperInstantiateAsset( this, TEXT( "/HoudiniEngine/Test/TestParams" ), [=]( FHoudiniEngineTaskInfo InstantiateTaskInfo, UHoudiniAsset* HoudiniAsset ) { HAPI_NodeId AssetId = InstantiateTaskInfo.AssetId; if( AssetId < 0 ) return; UTestHoudiniParameterBuilder * Builder = NewObject<UTestHoudiniParameterBuilder>( HelperGetWorld(), TEXT("ParmBuilder"), RF_Standalone ); bool Ok = FHoudiniParamUtils::Build( AssetId, Builder, Builder->CurrentParameters, Builder->NewParameters ); TestTrue( TEXT( "Build success" ), Ok ); if ( Ok ) { // Look at old params TestEqual( TEXT( "No Old Parms" ), Builder->CurrentParameters.Num(), 0 ); TestEqual( TEXT( "New Parms" ), Builder->NewParameters.Num(), 1 ); // Look at new params for( auto& ParamPair : Builder->NewParameters ) { UHoudiniAssetParameter* Param = ParamPair.Value; UE_LOG( LogHoudiniTests, Log, TEXT( "New Parm: %s" ), *Param->GetParameterName() ); if( UHoudiniAssetParameterInt* ParamInt = Cast<UHoudiniAssetParameterInt>( Param ) ) { // Change a parameter int32 Val = ParamInt->GetParameterValue( 0, -1 ); TestEqual( TEXT("GetParamterValue"), Val, 1 ); ParamInt->SetValue( 2, 0, false, false ); ParamInt->UploadParameterValue(); /* ADD_LATENT_AUTOMATION_COMMAND( FTakeActiveEditorScreenshotCommand( TEXT( "FHoudiniEngineRuntimeParamTest_0.png" ) )); //Wait so the screenshots have a chance to save ADD_LATENT_AUTOMATION_COMMAND( FWaitLatentCommand( 0.1f ) ); */ break; } AddError( TEXT( "Didn't find Int Param" ) ); } // Requery and verify param Builder->CurrentParameters = Builder->NewParameters; Builder->NewParameters.Empty(); Ok = FHoudiniParamUtils::Build( AssetId, Builder, Builder->CurrentParameters, Builder->NewParameters ); TestTrue( TEXT( "Build success2" ), Ok ); if( Ok ) { TestEqual( TEXT( "No Old Parms2" ), Builder->CurrentParameters.Num(), 0 ); TestEqual( TEXT( "New Parms1" ), Builder->NewParameters.Num(), 1 ); for( auto& ParamPair : Builder->NewParameters ) { UHoudiniAssetParameter* Param = ParamPair.Value; UE_LOG( LogHoudiniTests, Log, TEXT( "New Parm: %s" ), *Param->GetParameterName() ); if( UHoudiniAssetParameterInt* ParamInt = Cast<UHoudiniAssetParameterInt>( Param ) ) { int32 Val = ParamInt->GetParameterValue( 0, 0 ); TestEqual( TEXT( "GetParamterValue2" ), Val, 2 ); break; } AddError( TEXT("Didn't find Int Param2") ); } } } Builder->ConditionalBeginDestroy(); HelperCookAsset( this, HoudiniAsset, AssetId, [=]( bool CookOk, TMap< FHoudiniGeoPartObject, UStaticMesh * > StaticMeshesOut ) { if( CookOk ) { TestEqual( TEXT( "Num Mesh" ), StaticMeshesOut.Num(), 1 ); } HelperDeleteAsset( this, AssetId ); } ); } ); return true; } bool FHoudiniEngineRuntimeBatchTest::RunTest( const FString& Paramters ) { HelperInstantiateAsset( this, TEXT( "/HoudiniEngine/Test/TestPolyReduce" ), [=]( FHoudiniEngineTaskInfo InstantiateTaskInfo, UHoudiniAsset* HoudiniAsset ) { HAPI_NodeId AssetId = InstantiateTaskInfo.AssetId; if( AssetId < 0 ) return; UTestHoudiniParameterBuilder * Builder = NewObject<UTestHoudiniParameterBuilder>( HelperGetWorld(), TEXT( "ParmBuilder" ), RF_Standalone ); bool Ok = FHoudiniParamUtils::Build( AssetId, Builder, Builder->CurrentParameters, Builder->NewParameters ); TestTrue( TEXT( "Build success" ), Ok ); if( Ok ) { // Build the inputs UHoudiniAssetInput* GeoInputParm = UHoudiniAssetInput::Create( Builder, 0, AssetId ); TestTrue( TEXT( "Found Input" ), GeoInputParm != nullptr ); int32 InputNumTris = 0; UStaticMesh * GeoInput = Cast<UStaticMesh>( StaticLoadObject( UObject::StaticClass(), nullptr, TEXT( "StaticMesh'/Engine/BasicShapes/Cube.Cube'" ), nullptr, LOAD_None, nullptr ) ); TestTrue( TEXT( "Load Input Mesh" ), GeoInput != nullptr ); if( ! GeoInput ) return; if( GeoInput->RenderData->LODResources.Num() > 0 ) { InputNumTris = GeoInput->RenderData->LODResources[ 0 ].GetNumTriangles(); } TestTrue( TEXT( "Find Geo Input" ), GeoInputParm != nullptr ); for( int32 Ix = 0; Ix < 3; ++Ix ) { GEditor->ClickLocation = FVector(0, Ix * 200, 0); GEditor->ClickPlane = FPlane( GEditor->ClickLocation, FVector::UpVector ); TArray<AActor*> NewActors = FLevelEditorViewportClient::TryPlacingActorFromObject( HelperGetWorld()->GetLevel( 0 ), GeoInput, true, RF_Transactional, nullptr ); TestTrue( TEXT( "Placed Actor" ), NewActors.Num() > 0 ); if( GeoInputParm && NewActors.Num() > 0 ) { AActor* SMActor = NewActors.Pop(); GeoInputParm->ClearInputs(); GeoInputParm->ForceSetInputObject( SMActor, 0, true ); // triggers upload of data auto CookGUID = FGuid::NewGuid(); FHoudiniEngineTask CookTask( EHoudiniEngineTaskType::AssetCooking, CookGUID ); CookTask.AssetId = AssetId; FHoudiniEngine::Get().AddTask( CookTask ); while( true ) { FHoudiniEngineTaskInfo CookTaskInfo; if( FHoudiniEngine::Get().RetrieveTaskInfo( CookGUID, CookTaskInfo ) ) { bool CookSuccess = false; TMap< FHoudiniGeoPartObject, UStaticMesh * > StaticMeshesOut; if( CookTaskInfo.TaskState == EHoudiniEngineTaskState::Processing ) { FPlatformProcess::Sleep( 1 ); continue; } else if( CookTaskInfo.TaskState == EHoudiniEngineTaskState::FinishedCookingWithErrors ) { AddError( FString::Printf( TEXT( "CookTaskInfo.Result: %d, TaskState: %d" ), (int32)CookTaskInfo.Result, (int32)CookTaskInfo.TaskState ) ); break; } else { // Marshal the static mesh data float GeoScale = 1.f; if( const UHoudiniRuntimeSettings * HoudiniRuntimeSettings = GetDefault< UHoudiniRuntimeSettings >() ) { GeoScale = HoudiniRuntimeSettings->GeneratedGeometryScaleFactor; } TMap< FHoudiniGeoPartObject, UStaticMesh * > StaticMeshesIn; FTestCookHandler CookHandler ( HoudiniAsset ); CookHandler.HoudiniCookManager = &CookHandler; CookHandler.StaticMeshBakeMode = EBakeMode::CookToTemp; FTransform AssetTransform; CookSuccess = FHoudiniEngineUtils::CreateStaticMeshesFromHoudiniAsset( AssetId, CookHandler, false, false, StaticMeshesIn, StaticMeshesOut, AssetTransform ); if( CookSuccess && StaticMeshesOut.Num() > 0) { for( auto SMPair : StaticMeshesOut ) { int32 OutputNumTris = SMPair.Value->RenderData->LODResources[ 0 ].GetNumTriangles(); TestTrue( TEXT( "reduce worked" ), OutputNumTris < InputNumTris ); } } else { AddError( TEXT( "Failed to get static mesh output" ) ); } } break; } else { AddError( TEXT( "Failed to get task state" ) ); break; } } } } Builder->ConditionalBeginDestroy(); HelperDeleteAsset( this, AssetId ); } } ); return true; } bool FHoudiniEngineRuntimeActorTest::RunTest( const FString& Paramters ) { AHoudiniAssetActor* Actor = HelperInstantiateAssetActor<AHoudiniAssetActor>( this, TEXT( "/HoudiniEngine/Test/InputEcho" ) ); AddCommand( new FDelayedFunctionLatentCommand( [=] { if( Actor && Actor->GetHoudiniAssetComponent() ) { UHoudiniAssetComponent* Comp = Actor->GetHoudiniAssetComponent(); TestEqual( TEXT( "Done Cooking" ), Comp->IsInstantiatingOrCooking(), false ); FPropertyEditorModule & PropertyModule = FModuleManager::Get().GetModuleChecked< FPropertyEditorModule >( "PropertyEditor" ); // Locate the details panel. FName DetailsPanelName = "LevelEditorSelectionDetails"; TSharedPtr< IDetailsView > DetailsView = PropertyModule.FindDetailView( DetailsPanelName ); if( DetailsView.IsValid() ) { /* auto DetailsW = StaticCastSharedRef<SWidget>( DetailsView->AsShared() ); if( FAutomationTestFramework::Get().IsScreenshotAllowed() ) { const FString TestName = TEXT( "HoudiniEngineRuntimeActorTest_0.png" ); TArray<FColor> OutImageData; FIntVector OutImageSize; if( FSlateApplication::Get().TakeScreenshot( DetailsW, OutImageData, OutImageSize ) ) { FAutomationScreenshotData Data; Data.Width = OutImageSize.X; Data.Height = OutImageSize.Y; Data.Path = TestName; FAutomationTestFramework::Get().OnScreenshotCaptured().ExecuteIfBound( OutImageData, Data ); } } */ } } }, 1.5f )); return true; } bool FHoudiniEngineRuntimeUploadStaticMeshTest::RunTest( const FString& Parameters ) { HelperInstantiateAsset( this, TEXT( "/HoudiniEngine/Test/InputEcho"), [=]( FHoudiniEngineTaskInfo InstantiateTaskInfo, UHoudiniAsset* HoudiniAsset ) { HAPI_NodeId AssetId = InstantiateTaskInfo.AssetId; if( AssetId < 0 ) { return; } TArray<UObject *> InputObjects; TArray< FTransform > InputTransforms; HAPI_NodeId ConnectedAssetId; TArray< HAPI_NodeId > GeometryInputAssetIds; UStaticMesh * GeoInput = Cast<UStaticMesh>( StaticLoadObject( UObject::StaticClass(), nullptr, TEXT( "StaticMesh'/Engine/BasicShapes/Cube.Cube'" ), nullptr, LOAD_None, nullptr )); TestTrue( TEXT("Load Input Mesh"), GeoInput != nullptr ); if( ! GeoInput ) return; InputObjects.Add( GeoInput ); InputTransforms.Add( FTransform::Identity ); if( ! FHoudiniEngineUtils::HapiCreateInputNodeForObjects( AssetId, InputObjects, InputTransforms, ConnectedAssetId, GeometryInputAssetIds, false ) ) { AddError( FString::Printf( TEXT( "HapiCreateInputNodeForData failed" ))); } // Now connect the input int32 InputIndex = 0; HAPI_Result Result = FHoudiniApi::ConnectNodeInput( FHoudiniEngine::Get().GetSession(), AssetId, InputIndex, ConnectedAssetId, 0 ); TestEqual( TEXT("ConnectNodeInput"), HAPI_RESULT_SUCCESS, Result ); HelperCookAsset( this, HoudiniAsset, AssetId, [=]( bool Ok, TMap< FHoudiniGeoPartObject, UStaticMesh * > StaticMeshesOut ) { if( Ok ) { TestEqual( TEXT( "Num Mesh" ), StaticMeshesOut.Num(), 1 ); } for( auto GeoPartSM : StaticMeshesOut ) { FHoudiniGeoPartObject& Part = GeoPartSM.Key; if( UStaticMesh* NewSM = GeoPartSM.Value ) { HelperTestMeshEqual( this, GeoInput, NewSM ); } break; } HelperDeleteAsset( this, AssetId ); } ); } ); return true; } bool FHoudiniEngineRuntimeMeshMarshalTest::RunTest( const FString& Parameters ) { HelperInstantiateAsset( this, TEXT( "/HoudiniEngine/Test/TestBox" ), [=]( FHoudiniEngineTaskInfo InstantiateTaskInfo, UHoudiniAsset* HoudiniAsset ) { HAPI_NodeId AssetId = InstantiateTaskInfo.AssetId; if( AssetId < 0 ) { return; } HelperCookAsset( this, HoudiniAsset, AssetId, [=]( bool Ok, TMap< FHoudiniGeoPartObject, UStaticMesh * > StaticMeshesOut ) { if( !Ok ) { return; } #define ExpectedNumVerts 24 #define ExpectedNumPoints 8 #define ExpectedNumTris 12 FHVert ExpectedVerts[ ExpectedNumVerts ] = { {1, -0.0, -0.0, -1.0, 0.333333, 0.666667, 0.0}, {5, -0.0, 0.0, -1.0, 0.333333, 0.982283, 0.0}, {4, -0.0, -0.0, -1.0, 0.64895, 0.982283, 0.0}, {0, 0.0, -0.0, -1.0, 0.64895, 0.666667, 0.0}, {2, 1.0, -0.0, -0.0, 0.0, 0.666667, 0.0}, {6, 1.0, -0.0, -0.0, 0.0, 0.982283, 0.0}, {5, 1.0, 0.0, 0.0, 0.315616, 0.982283, 0.0}, {1, 1.0, -0.0, -0.0, 0.315616, 0.666667, 0.0}, {3, -0.0, -0.0, 1.0, 0.0, 0.333333, 0.0}, {7, -0.0, -0.0, 1.0, 0.0, 0.64895, 0.0}, {6, -0.0, -0.0, 1.0, 0.315616, 0.64895, 0.0}, {2, 0.0, 0.0, 1.0, 0.315616, 0.333333, 0.0}, {0, -1.0, 0.0, -0.0, 0.333333, 0.333333, 0.0}, {4, -1.0, -0.0, -0.0, 0.333333, 0.64895, 0.0}, {7, -1.0, -0.0, 0.0, 0.64895, 0.64895, 0.0}, {3, -1.0, -0.0, -0.0, 0.64895, 0.333333, 0.0}, {2, 0.0, -1.0, -0.0, 0.64895, 0.315616, 0.0}, {1, -0.0, -1.0, -0.0, 0.64895, 0.0, 0.0}, {0, -0.0, -1.0, 0.0, 0.333333, 0.0, 0.0}, {3, -0.0, -1.0, -0.0, 0.333333, 0.315616, 0.0}, {5, -0.0, 1.0, -0.0, 0.315616, 0.315616, 0.0}, {6, -0.0, 1.0, -0.0, 0.315616, 0.0, 0.0}, {7, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0}, {4, -0.0, 1.0, -0.0, 0.0, 0.315616, 0.0}, }; FVector ExpectedPoints[ ExpectedNumPoints ] = { {-0.5, -0.5, -0.5}, {0.5, -0.5, -0.5}, {0.5, -0.5, 0.5}, {-0.5, -0.5, 0.5}, {-0.5, 0.5, -0.5}, {0.5, 0.5, -0.5}, {0.5, 0.5, 0.5}, {-0.5, 0.5, 0.5} }; // Scale our expected data into unreal space float GeoScale = 1.f; if( const UHoudiniRuntimeSettings * HoudiniRuntimeSettings = GetDefault< UHoudiniRuntimeSettings >() ) { GeoScale = HoudiniRuntimeSettings->GeneratedGeometryScaleFactor; } for( int32 Ix = 0; Ix < ExpectedNumPoints; ++Ix ) { ExpectedPoints[ Ix ] *= GeoScale; } TestEqual( TEXT( "Num Mesh" ), StaticMeshesOut.Num(), 1 ); for( auto GeoPartSM : StaticMeshesOut ) { FHoudiniGeoPartObject& Part = GeoPartSM.Key; if( UStaticMesh* NewSM = GeoPartSM.Value ) { if( NewSM->RenderData->LODResources.Num() > 0 ) { TestEqual( TEXT( "Num Triangles" ), ExpectedNumTris, NewSM->RenderData->LODResources[ 0 ].GetNumTriangles() ); FPositionVertexBuffer& VB = NewSM->RenderData->LODResources[ 0 ].VertexBuffers.PositionVertexBuffer; const int32 VertexCount = VB.GetNumVertices(); if( VertexCount != ExpectedNumVerts ) { TestEqual( TEXT( "Num Verts" ), VertexCount, ExpectedNumVerts ); break; } TArray<FVector> GeneratedPoints, ExpectedVertPositions; GeneratedPoints.SetNumUninitialized( VertexCount ); ExpectedVertPositions.SetNumUninitialized( VertexCount ); for( int32 Index = 0; Index < VertexCount; Index++ ) { GeneratedPoints[ Index ] = VB.VertexPosition( Index ); ExpectedVertPositions[ Index ] = ExpectedPoints[ ExpectedVerts[ Index ].PointNum ]; } GeneratedPoints.Sort( FSortVectors() ); ExpectedVertPositions.Sort( FSortVectors() ); for( int32 Index = 0; Index < VertexCount; Index++ ) { TestEqual( TEXT( "Points match" ), GeneratedPoints[ Index ], ExpectedVertPositions[ Index ] ); } } } break; } HelperDeleteAsset( this, AssetId ); } ); }); return true; } #endif // WITH_EDITOR
40.450131
176
0.570451
[ "mesh" ]