hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
ce3761c6141bb4ed1abcc92b7b91d30584e23061
301
cpp
C++
src/sdm/utils/linear_programming/ndpomdp_naming.cpp
SDMStudio/sdms
43a86973081ffd86c091aed69b332f0087f59361
[ "MIT" ]
null
null
null
src/sdm/utils/linear_programming/ndpomdp_naming.cpp
SDMStudio/sdms
43a86973081ffd86c091aed69b332f0087f59361
[ "MIT" ]
null
null
null
src/sdm/utils/linear_programming/ndpomdp_naming.cpp
SDMStudio/sdms
43a86973081ffd86c091aed69b332f0087f59361
[ "MIT" ]
null
null
null
#include <sdm/utils/linear_programming/ndpomdp_naming.hpp> namespace sdm { std::string NDPOMDPNaming::getTransitionName(const std::shared_ptr<State> &x, const std::shared_ptr<State> &y) { std::ostringstream oss; oss << "tr:" << x << ":" << y; return oss.str(); } }
27.363636
114
0.621262
SDMStudio
ce3a12a8fbe10c4c915dd603f022d69b38c4d3a1
6,604
cpp
C++
test/unit/MessageBuffer_test.cpp
mgukowsky/Omulator
82e6d112ee09fa02cce8d0d4ad2e9077cc73e870
[ "0BSD" ]
1
2022-01-17T22:16:47.000Z
2022-01-17T22:16:47.000Z
test/unit/MessageBuffer_test.cpp
mgukowsky/Omulator
82e6d112ee09fa02cce8d0d4ad2e9077cc73e870
[ "0BSD" ]
14
2019-05-14T02:43:53.000Z
2019-05-26T23:05:22.000Z
test/unit/MessageBuffer_test.cpp
mgukowsky/Omulator
82e6d112ee09fa02cce8d0d4ad2e9077cc73e870
[ "0BSD" ]
null
null
null
#include "omulator/msg/MessageBuffer.hpp" #include "omulator/util/reinterpret.hpp" #include <gtest/gtest.h> #include <cmath> #include <cstddef> using omulator::U16; using omulator::U32; using omulator::U8; using omulator::msg::MessageBuffer; using omulator::util::reinterpret; namespace { constexpr int MAGIC = 42; } TEST(MessageBuffer_test, simpleAlloc) { MessageBuffer mb = MessageBuffer::make_buff(); EXPECT_TRUE(mb.empty()) << "MessageBuffers should be empty immediately after construction"; constexpr U16 MSG_SIZ = sizeof(U32); std::byte * pAllocation = reinterpret_cast<std::byte *>(mb.alloc(MAGIC, MSG_SIZ)); MessageBuffer::MessageHeader &header = reinterpret<MessageBuffer::MessageHeader>(pAllocation - MessageBuffer::HEADER_SIZE); EXPECT_FALSE(mb.empty()) << "MessageBuffers should no longer be empty immediately following an allocation"; *(reinterpret_cast<U32 *>(pAllocation)) = 0x1234'5678; std::byte *pAllocation2 = reinterpret_cast<std::byte *>(mb.alloc(MAGIC + 1, MSG_SIZ)); MessageBuffer::MessageHeader &header2 = reinterpret<MessageBuffer::MessageHeader>(pAllocation2 - MessageBuffer::HEADER_SIZE); EXPECT_EQ(MAGIC, header.id) << "MessageBuffers should correctly record the ID of an allocated message"; EXPECT_EQ(0x1234'5678, *(reinterpret_cast<U32 *>(pAllocation))) << "Headers for MessageBuffer allocations should not overwrite previously allocated memory " "within the message buffer"; EXPECT_EQ(MAGIC + 1, header2.id) << "MessageBuffers should correctly record the ID of an allocated message"; const std::ptrdiff_t allocDistance = std::abs(pAllocation2 - pAllocation); EXPECT_EQ(allocDistance, header.offsetNext) << "Allocations within MessageBuffers should point to the next message in the buffer, if one " "exists"; EXPECT_EQ(MessageBuffer::HEADER_SIZE + MSG_SIZ, header2.offsetNext) << "The MessageHeader for the last allocation within a MessageBuffer should point to the " "memory directly after the allocation, where the next MessageHeader will be placed"; } TEST(MessageBuffer_test, maxAllocation) { MessageBuffer mb = MessageBuffer::make_buff(); EXPECT_THROW(mb.alloc(MAGIC, MessageBuffer::MAX_MSG_SIZE + 1), std::runtime_error) << "Attempting an allocation larger than MessageBuffer::MAX_MSG_SIZE should cause an exception " "to be raised."; MessageBuffer mb2 = MessageBuffer::make_buff(); EXPECT_NE(nullptr, mb2.alloc(MAGIC, MessageBuffer::MAX_MSG_SIZE)) << "An empty MessageBuffer should be able to allocate up to MessageBuffer::MAX_MSG_SIZE bytes"; EXPECT_EQ(nullptr, mb2.alloc(MAGIC, 1)) << "MessageBuffer::alloc should return a nullptr when the MessageBuffer cannot accomodate an " "allocation of the requested number of bytes"; } TEST(MessageBuffer_test, headerOnlyAllocations) { MessageBuffer mb = MessageBuffer::make_buff(); /** * The static assert within the MessageBuffer implementation ensures that BUFFER_SIZE will be * divisible by HEADER_SIZE. */ const MessageBuffer::Offset_t LIMIT = MessageBuffer::BUFFER_SIZE / MessageBuffer::HEADER_SIZE; std::byte * pHeader = reinterpret_cast<std::byte *>(mb.alloc(MAGIC)); const std::byte * const pInitialHeader = pHeader; for(MessageBuffer::Offset_t i = 0; i < LIMIT - 1; i++) { MessageBuffer::MessageHeader &hdr = reinterpret<MessageBuffer::MessageHeader>(pHeader); EXPECT_EQ(MAGIC, hdr.id) << "A header-only allocation within a MessageBuffer should correctly record a message ID"; EXPECT_EQ(MessageBuffer::HEADER_SIZE, hdr.offsetNext) << "A header-only allocation within a MessageBuffer should point to the next location within " "the buffer where a header will be placed"; EXPECT_EQ((&hdr) + 1, mb.end()) << "A header-only allocation within a MessageBuffer should " "update the address returned by MessageBuffer::end"; pHeader = reinterpret_cast<std::byte *>(mb.alloc(MAGIC)); } MessageBuffer::MessageHeader &hdr = reinterpret<MessageBuffer::MessageHeader>(pHeader); EXPECT_EQ(MAGIC, hdr.id) << "A header-only allocation within a MessageBuffer should correctly record a message ID"; EXPECT_EQ(MessageBuffer::HEADER_SIZE, hdr.offsetNext) << "The final header-only allocation within a MessageBuffer should point just past the end of " "the buffer"; EXPECT_EQ((&hdr) + 1, mb.end()) << "A header-only allocation within a MessageBuffer should " "update the address returned by MessageBuffer::end"; EXPECT_EQ(static_cast<std::ptrdiff_t>(MessageBuffer::BUFFER_SIZE), (std::abs(pHeader - pInitialHeader) + hdr.offsetNext)) << "A MessageBuffer filled with header-only messages should span the entire buffer with no " "wasted space"; } TEST(MessageBuffer_test, beginAndEnd) { MessageBuffer mb = MessageBuffer::make_buff(); EXPECT_EQ(nullptr, mb.begin()) << "MessageBuffer::begin should return nullptr when the buffer is empty"; EXPECT_EQ(nullptr, mb.end()) << "MessageBuffer::end should return nullptr when the buffer is empty"; MessageBuffer::MessageHeader *alloca = reinterpret_cast<MessageBuffer::MessageHeader *>(mb.alloc(MAGIC)); MessageBuffer::MessageHeader *allocb = reinterpret_cast<MessageBuffer::MessageHeader *>(mb.alloc(MAGIC)); EXPECT_EQ(alloca, mb.begin()) << "MessageBuffer::begin should return the address of the first MessageHeader in the buffer"; EXPECT_EQ(allocb + 1, mb.end()) << "MessageBuffer::end should return the address directly after the last message in the buffer"; } TEST(MessageBuffer_test, beginAndEndWithData) { constexpr std::size_t MSGSIZ = 0x10; MessageBuffer mb = MessageBuffer::make_buff(); EXPECT_EQ(nullptr, mb.begin()) << "MessageBuffer::begin should return nullptr when the buffer is empty"; EXPECT_EQ(nullptr, mb.end()) << "MessageBuffer::end should return nullptr when the buffer is empty"; const std::byte *alloca = reinterpret_cast<const std::byte *>(mb.alloc(MAGIC, MSGSIZ)); const std::byte *allocb = reinterpret_cast<const std::byte *>(mb.alloc(MAGIC, MSGSIZ)); EXPECT_EQ(alloca - sizeof(MessageBuffer::MessageHeader), reinterpret_cast<const std::byte *>(mb.begin())) << "MessageBuffer::begin should return the address of the first MessageHeader in the buffer"; EXPECT_EQ(allocb + MSGSIZ, reinterpret_cast<const std::byte *>(mb.end())) << "MessageBuffer::end should return the address directly after the last message in the buffer"; }
44.621622
100
0.726075
mgukowsky
ce3b9f8bc7b42cacfd21af37d7c193993324ab96
1,052
hpp
C++
include/cond_check.hpp
MatthiasKillat/template_metaprogramming
a0f65d11052c317387d09a2fdf967cac2bb987a2
[ "Apache-2.0" ]
null
null
null
include/cond_check.hpp
MatthiasKillat/template_metaprogramming
a0f65d11052c317387d09a2fdf967cac2bb987a2
[ "Apache-2.0" ]
null
null
null
include/cond_check.hpp
MatthiasKillat/template_metaprogramming
a0f65d11052c317387d09a2fdf967cac2bb987a2
[ "Apache-2.0" ]
null
null
null
#pragma once #include <type_traits> //some helper aliases/templates to make reasoning about what happens a little easier template <bool Value = true> using Boolean = std::integral_constant<bool, Value>; using True = Boolean<true>; using False = Boolean<false>; template <typename Cond> using TrueOrFail = typename std::enable_if<Cond::value, True>::type; //can evaluate the condition into its bool value and a type //Cond is expected to be Boolean, otherwise weird things may happen... template <typename Cond> struct Eval { static_assert(std::is_same<Cond, True>::value || std::is_same<Cond, False>::value); template <typename U = Cond> static constexpr bool value(typename std::enable_if<std::is_same<U, True>::value, void *>::type = nullptr) { return std::true_type::value; } template <typename U = Cond> static constexpr bool value(typename std::enable_if<std::is_same<U, False>::value, void *>::type = nullptr) { return std::false_type::value; } using type = typename Cond::type; };
29.222222
111
0.701521
MatthiasKillat
ce3c24bd470b1a00b64490111036387bd630ce2f
3,725
cpp
C++
Sources/x10/xla_tensor/ops/xla_avg_pool.cpp
vguerra/swift-apis
215c1380874c55d2f12ae81ce78968f9e25ed723
[ "Apache-2.0" ]
848
2019-02-12T00:27:29.000Z
2022-01-26T04:41:50.000Z
Sources/x10/xla_tensor/ops/xla_avg_pool.cpp
BradLarson/swift-apis
02f31d531cbbfbd72de2b2f288f24f8645ee5bcb
[ "Apache-2.0" ]
698
2019-02-12T12:35:54.000Z
2022-01-25T00:48:53.000Z
Sources/x10/xla_tensor/ops/xla_avg_pool.cpp
ProfFan/swift-apis
f51ee4618d652a2419e998bf9418ad80bda67454
[ "Apache-2.0" ]
181
2019-02-12T00:33:34.000Z
2021-12-05T19:15:55.000Z
// Copyright 2020 TensorFlow 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 // // 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 "tensorflow/compiler/tf2xla/xla_tensor/ops/xla_avg_pool.h" #include "tensorflow/compiler/tf2xla/xla_tensor/lowering_context.h" #include "tensorflow/compiler/tf2xla/xla_tensor/ops/infer_output_shape.h" #include "tensorflow/compiler/tf2xla/xla_tensor/pooling.h" namespace swift_xla { namespace ir { namespace ops { namespace { // Infers the output shape of the average pooling operation. xla::Shape NodeOutputShape( const Value& operand, absl::Span<const xla::int64> kernel_size, absl::Span<const xla::int64> stride, absl::Span<const std::pair<xla::int64, xla::int64>> padding, const xla::TensorFormat& data_format, const bool counts_include_padding) { auto lower_for_shape_fn = [&](absl::Span<const xla::XlaOp> operands) -> xla::XlaOp { CHECK_EQ(operands.size(), 1) << "Unexpected number of operands: " << operands.size(); return xla::AvgPool(operands[0], kernel_size, stride, padding, data_format, counts_include_padding); }; return InferOutputShape({operand.shape()}, lower_for_shape_fn); } } // namespace XlaAvgPool::XlaAvgPool(const Value& operand, std::vector<xla::int64> kernel_size, std::vector<xla::int64> stride, std::vector<std::pair<xla::int64, xla::int64>> padding, const xla::TensorFormat& data_format, const bool counts_include_padding) : Node(ir::OpKind(at::aten::xla_avg_pool), {operand}, [&]() { return NodeOutputShape(operand, kernel_size, stride, padding, data_format, counts_include_padding); }, /*num_outputs=*/1, xla::util::MHash(kernel_size, stride, PaddingToList(padding), DataFormatToList(data_format), counts_include_padding)), kernel_size_(std::move(kernel_size)), stride_(std::move(stride)), padding_(std::move(padding)), data_format_(data_format), counts_include_padding_(counts_include_padding) {} NodePtr XlaAvgPool::Clone(OpList operands) const { return MakeNode<XlaAvgPool>(operands.at(0), kernel_size_, stride_, padding_, data_format_, counts_include_padding_); } XlaOpVector XlaAvgPool::Lower(LoweringContext* loctx) const { xla::XlaOp input = loctx->GetOutputOp(operand(0)); xla::XlaOp output = xla::AvgPool(input, kernel_size_, stride_, padding_, data_format_, counts_include_padding_); return ReturnOp(output, loctx); } std::string XlaAvgPool::ToString() const { std::stringstream ss; ss << Node::ToString() << ", kernel_size=[" << absl::StrJoin(kernel_size_, ", ") << "], stride=[" << absl::StrJoin(stride_, ", ") << "], padding=[" << absl::StrJoin(PaddingToList(padding_), ", ") << "], data_format=[" << absl::StrJoin(DataFormatToList(data_format_), ", ") << "], counts_include_padding=" << counts_include_padding_; return ss.str(); } } // namespace ops } // namespace ir } // namespace swift_xla
40.934066
79
0.656644
vguerra
ce3d505ecb23510ee8c55d106cfcec90f5cd6f75
106
hpp
C++
buildSystemTests/single_exec/code/inc/MyClass.hpp
iblis-ms/python_cmake_build_system
9f52f004241c6e8efc4a036d5c58f67a6d40e7ec
[ "MIT" ]
null
null
null
buildSystemTests/single_exec/code/inc/MyClass.hpp
iblis-ms/python_cmake_build_system
9f52f004241c6e8efc4a036d5c58f67a6d40e7ec
[ "MIT" ]
6
2020-10-11T21:03:24.000Z
2020-10-12T20:32:13.000Z
buildSystemTests/single_exec/code/inc/MyClass.hpp
iblis-ms/python_cmake_build_system
9f52f004241c6e8efc4a036d5c58f67a6d40e7ec
[ "MIT" ]
null
null
null
#ifndef MY_CLASS_HPP_ #define MY_CLASS_HPP_ struct CMyClass { void fun(); }; #endif // MY_CLASS_HPP_
13.25
23
0.726415
iblis-ms
ce45bae2fc9f82c959a4547d8432730acb3e384d
15,261
hpp
C++
test/test_types.hpp
lingjf/h2un
7735c2f07f58ea8b92a9e9608c9b45c98c94c670
[ "Apache-2.0" ]
null
null
null
test/test_types.hpp
lingjf/h2un
7735c2f07f58ea8b92a9e9608c9b45c98c94c670
[ "Apache-2.0" ]
null
null
null
test/test_types.hpp
lingjf/h2un
7735c2f07f58ea8b92a9e9608c9b45c98c94c670
[ "Apache-2.0" ]
null
null
null
#if defined __GNUC__ || defined __clang__ #pragma GCC diagnostic ignored "-Wunused-variable" #pragma GCC diagnostic ignored "-Wunused-function" #endif extern char buffer[1024]; extern "C" { int foobar0(); } static int foobar0_fake() { return -1; } int foobar1(int a); static int foobar1_fake(int a) { return -1; } int foobar2(int a, const char* b); static int foobar2_fake(int a, const char* b) { return -2; } static void foobar21(int& a, char* b) { } static void foobar22() { } int foobar3(int a); const char* foobar3(const char* a); template <typename T1> int foobar4(T1 a) { return 4; } static int foobar4_fake(int a) { return -4; } template <typename T1, typename T2> int foobar5(T1 a, T2 b) { return 5; } static int foobar5_fake(int a, float b) { return -5; } int foobar6(char* a, ...); static int foobar6_fake(char* a, ...) { return -6; } static int foobar16(int _0, int _1, int _2, int _3, int _4, int _5, int _6, int _7, int _8, int _9, int _10, int _11, int _12, int _13, int _14, int _15) { return 0; } namespace test_ns { int foobar1(float a); int foobar2(int a, const char* b); } struct A_PlainStruct { int a; double b; char c[100]; }; struct B_ClassStruct { int a; int f(int b) { return a + b; } }; class A_AbstractClass { public: char a; A_AbstractClass() : a('a') {} private: static const char* static_f1(int x) { return sprintf(buffer, "A.static_f1(%d)", x), buffer; } const char* normal_f1(int x) { return sprintf(buffer, "A.normal_f1(%d)%c", x, a), buffer; } virtual const char* virtual_f1(int x) { return sprintf(buffer, "A.virtual_f1(%d)%c", x, a), buffer; } virtual const char* pure_f0() = 0; }; class B_DerivedClass : public A_AbstractClass { public: char b; char* s; B_DerivedClass() : b('b') { s = (char*)malloc(11); } virtual ~B_DerivedClass() { free(s); } private: static const char* static_f2(int x, int y) { return sprintf(buffer, "B.static_f2(%d,%d)", x, y), buffer; } const char* normal_f2(int x, int y) { return sprintf(buffer, "B.normal_f2(%d,%d)%c", x, y, b), buffer; } virtual const char* virtual_f2(int x, int y) { return sprintf(buffer, "B.virtual_f2(%d,%d)%c", x, y, b), buffer; } virtual const char* pure_f0() { return sprintf(buffer, "B.pure_f0()%c", b), buffer; } }; class C_OverrideClass : public A_AbstractClass { public: char c; std::string s; C_OverrideClass() : c('c'), s(10000, 's') {} virtual ~C_OverrideClass() {} private: static const char* static_f1(int x) { return sprintf(buffer, "C.static_f1(%d)", x), buffer; } static const char* static_f2(int x, int y) { return sprintf(buffer, "C.static_f2(%d,%d)", x, y), buffer; } const char* normal_f1(int x) { return sprintf(buffer, "C.normal_f1(%d)%c", x, c), buffer; } const char* normal_f2(int x, int y) { return sprintf(buffer, "C.normal_f2(%d,%d)%c", x, y, c), buffer; } virtual const char* virtual_f1(int x) { return sprintf(buffer, "C.virtual_f1(%d)%c", x, c), buffer; } virtual const char* virtual_f2(int x, int y) { return sprintf(buffer, "C.virtual_f2(%d,%d)%c", x, y, c), buffer; } virtual const char* pure_f0() { return sprintf(buffer, "C.pure_f0()%c", c), buffer; } }; class D_NoConstructorClass : public B_DerivedClass, public C_OverrideClass { public: char d; D_NoConstructorClass() = delete; D_NoConstructorClass(int, int, int, int, int, int, int, int, int, int, int) : d('d') {} private: static const char* static_f1(int x) { return sprintf(buffer, "D.static_f1(%d)", x), buffer; } static const char* static_f2(int x, int y) { return sprintf(buffer, "D.static_f2(%d,%d)", x, y), buffer; } static const char* static_f3(int x, int y, int z) { return sprintf(buffer, "D.static_f3(%d,%d,%d)", x, y, z), buffer; } const char* normal_f1(int x) { return sprintf(buffer, "D.normal_f1(%d)%c", x, d), buffer; } const char* normal_f2(int x, int y) { return sprintf(buffer, "D.normal_f2(%d,%d)%c", x, y, d), buffer; } const char* normal_f3(int x, int y, int z) { return sprintf(buffer, "D.normal_f3(%d,%d,%d)%c", x, y, z, d), buffer; } virtual const char* virtual_f1(int x) { return sprintf(buffer, "D.virtual_f1(%d)%c", x, d), buffer; } virtual const char* virtual_f2(int x, int y) { return sprintf(buffer, "D.virtual_f2(%d,%d)%c", x, y, d), buffer; } virtual const char* virtual_f3(int x, int y, int z) { return sprintf(buffer, "D.virtual_f3(%d,%d,%d)%c", x, y, z, d), buffer; } }; namespace test_ns { class E_NamespaceClass : public A_AbstractClass { public: char e; E_NamespaceClass() : e('e') {} virtual ~E_NamespaceClass() {} private: virtual const char* pure_f0() { return sprintf(buffer, "E.pure_f0()%c", e), buffer; } }; } static const char* A_normal_f1_fake(A_AbstractClass* This, int x) { return sprintf(buffer, "-A.normal_f1(%d)%c", x, This->a), buffer; } static const char* A_virtual_f1_fake(A_AbstractClass* This, int x) { return sprintf(buffer, "-A.virtual_f1(%d)%c", x, This->a), buffer; } static const char* B_static_f1_fake(int x) { return sprintf(buffer, "-B.static_f1(%d)", x), buffer; } static const char* B_normal_f1_fake(B_DerivedClass* This, int x) { return sprintf(buffer, "-B.normal_f1(%d)%c", x, This->b), buffer; } static const char* B_normal_f2_fake(B_DerivedClass* This, int x, int y) { return sprintf(buffer, "-B.normal_f2(%d,%d)%c", x, y, This->b), buffer; } static const char* B_virtual_f1_fake(B_DerivedClass* This, int x) { return sprintf(buffer, "-B.virtual_f1(%d)%c", x, This->b), buffer; } static const char* B_virtual_f2_fake(B_DerivedClass* This, int x, int y) { return sprintf(buffer, "-B.virtual_f2(%d,%d)%c", x, y, This->b), buffer; } static const char* C_normal_f1_fake(C_OverrideClass* This, int x) { return sprintf(buffer, "-C.normal_f1(%d)%c", x, This->c), buffer; } static const char* C_virtual_f1_fake(C_OverrideClass* This, int x) { return sprintf(buffer, "-C.virtual_f1(%d)%c", x, This->c), buffer; } static const char* D_virtual_f3_fake(D_NoConstructorClass* This, int x, int y, int z) { return sprintf(buffer, "-D.virtual_f3(%d,%d,%d)%c", x, y, z, This->d), buffer; } static const char* E_virtual_f1_fake(test_ns::E_NamespaceClass* This, int x) { return sprintf(buffer, "-E.virtual_f1(%d)%c", x, This->e), buffer; } template <typename T> struct F_TemplateClass { char f = 'f'; virtual ~F_TemplateClass() {} static const char* static_f1(T x) { return sprintf(buffer, "F.static_f1(%d)", x), buffer; } template <typename U> const char* normal_f1(U x) { return sprintf(buffer, "F.normal_f1(%d)%c", x, f), buffer; } virtual const char* virtual_f1(T x) { return sprintf(buffer, "F.virtual_f1(%d)%c", x, f), buffer; } }; template <typename T1, typename T2> struct G_TemplateClass { char g = 'g'; T1 G = 7; template <typename U1, typename U2> static const char* static_f2(U1 x, U2 y) { return sprintf(buffer, "G.static_f2(%d,%d)", x, y), buffer; } template <typename U1, typename U2> const char* normal_f2(U1 x, U2 y) { return sprintf(buffer, "G.normal_f2(%d,%d)%c", x, y, g), buffer; } template <typename U1, typename U2> std::pair<const char*, double> virtual_f2(U1 x, U2 y) { return std::make_pair("G.virtual_f2", x * 10 + y + G / 10.0); } }; static const char* F_static_f1_fake(int x) { return sprintf(buffer, "-F.static_f1(%d)", x), buffer; } static const char* F_normal_f1_fake(F_TemplateClass<int>* This, int x) { return sprintf(buffer, "-F.normal_f1(%d)%c", x, This->f), buffer; } static const char* F_virtual_f1_fake(F_TemplateClass<int>* This, int x) { return sprintf(buffer, "-F.virtual_f1(%d)%c", x, This->f), buffer; } static const char* G_static_f2_fake(int x, int y) { return sprintf(buffer, "-G.static_f2(%d,%d)", x, y), buffer; } static const char* G_normal_f2_fake(G_TemplateClass<int, int>* This, int x, int y) { return sprintf(buffer, "-G.normal_f2(%d,%d)%c", x, y, This->g), buffer; } static std::pair<const char*, double> G_virtual_f2_fake(G_TemplateClass<int, int>* This, int x, int y) { return std::make_pair("-G.virtual_f2", x * 10 + y + This->G / 10.0); } #define NUMBER0_DECL_LIST \ static char char_0 = 0; \ static signed char signed_char_0 = 0; \ static short int short_int_0 = 0; \ static int int_0 = 0; \ static long int long_int_0 = 0; \ static long long int long_long_int_0 = 0LL; \ static float float_0 = 0; \ static double double_0 = 0; \ static long double long_double_0 = 0; \ static bool bool_0 = false; \ static int& int_ref_0 = int_0; \ static const int& const_int_ref_0 = 0; \ static const char const_char_0 = 0; \ static const int const_int_0 = 0; \ static const float const_float_0 = 0; \ static const bool const_bool_0 = false; \ enum { enum_0 = 0 }; #define NUMBER1_DECL_LIST \ static char char_1 = 1; \ static signed char signed_char_1 = 1; \ static short int short_int_1 = 1; \ static int int_1 = 1; \ static long int long_int_1 = 1; \ static long long int long_long_int_1 = 1LL; \ static float float_1 = 1; \ static double double_1 = 1; \ static long double long_double_1 = 1; \ static bool bool_1 = true; \ static int& int_ref_1 = int_1; \ static const int& const_int_ref_1 = 1; \ static const char const_char_1 = 1; \ static const int const_int_1 = 1; \ static const float const_float_1 = 1; \ static const bool const_bool_1 = true; \ enum { enum_1 = 1 }; #define NUMBER0_VAR_LIST \ 0, 0L, 0LL, \ char_0, \ signed_char_0, \ short_int_0, \ int_0, \ long_int_0, \ long_long_int_0, \ float_0, \ double_0, \ long_double_0, \ bool_0, \ int_ref_0, \ const_int_ref_0, \ const_char_0, \ const_int_0, \ const_float_0, \ const_bool_0, \ enum_0 #define NUMBER1_VAR_LIST \ 1, 1L, 1LL, \ char_1, \ signed_char_1, \ short_int_1, \ int_1, \ long_int_1, \ long_long_int_1, \ float_1, \ double_1, \ long_double_1, \ bool_1, \ int_ref_1, \ const_int_ref_1, \ const_char_1, \ const_int_1, \ const_float_1, \ const_bool_1, \ enum_1 #define STRING_VAR_LIST \ "h2unit", \ const_char_const_p1, \ const_char_p1, \ char_const_p1, \ char_p1, \ char_ref_p1, \ char_array1, \ const_char_array1, \ const_h2string1, \ h2string1, \ h2stringref1, \ const_stdstring1, \ stdstring1, \ stdstringref1 #define STRING_DECL_LIST \ const char* const const_char_const_p1 = "h2unit"; \ const char* const_char_p1 = "h2unit"; \ char* const char_const_p1 = (char* const)"h2unit"; \ char* char_p1 = (char*)"h2unit"; \ char*& char_ref_p1 = char_p1; \ char char_array1[1024] = "h2unit"; \ const char const_char_array1[1024] = "h2unit"; \ const h2::h2_string const_h2string1 = "h2unit"; \ h2::h2_string h2string1 = "h2unit"; \ h2::h2_string& h2stringref1 = h2string1; \ const std::string const_stdstring1 = "h2unit"; \ std::string stdstring1 = "h2unit"; \ std::string& stdstringref1 = stdstring1; struct test_ptr { int a; float b; }; #define PTR_FILL_DECL_LIST \ static void* void_ptr = (void*)"h2unit0123456789"; \ static const void* const_void_ptr = (const void*)"h2unit0123456789"; \ static char* char_ptr = (char*)"h2unit0123456789"; \ static const char* const_char_ptr = (const char*)"h2unit0123456789"; \ static int* int_ptr = (int*)"h2unit0123456789"; \ static const int* const_int_ptr = (const int*)"h2unit0123456789"; \ static test_ptr* test_ptr_ptr = (test_ptr*)"h2unit0123456789"; \ static const test_ptr* const_test_ptr_ptr = (const test_ptr*)"h2unit0123456789"; #define PTR_NULL_DECL_LIST \ static void* void_nullptr = nullptr; \ static const void* const_void_nullptr = nullptr; \ static char* char_nullptr = nullptr; \ static const char* const_char_nullptr = nullptr; \ static int* int_nullptr = nullptr; \ static const int* const_int_nullptr = nullptr; \ static test_ptr* test_ptr_nullptr = nullptr; \ static const test_ptr* const_test_ptr_nullptr = nullptr; #define PTR_LIST \ void_nullptr, \ const_void_nullptr, \ char_nullptr, \ const_char_nullptr, \ int_nullptr, \ const_int_nullptr, \ test_ptr_nullptr, \ const_test_ptr_nullptr #define PTR_FILL_VALUE_LIST \ "h2unit0123456789", \ void_ptr, \ const_void_ptr, \ char_ptr, \ const_char_ptr, \ int_ptr, \ const_int_ptr, \ test_ptr_ptr, \ const_test_ptr_ptr #define PTR_NULL_VALUE_LIST \ nullptr, \ void_nullptr, \ const_void_nullptr, \ char_nullptr, \ const_char_nullptr, \ int_nullptr, \ const_int_nullptr, \ test_ptr_nullptr, \ const_test_ptr_nullptr, \ NULL, 0 int my_printf(const char* fmt, ...); int my_fprintf(FILE* stream, const char* fmt, ...); int my_sprintf(char* t, const char* fmt, ...); int my_snprintf(char* t, int n, const char* fmt, ...); void* my_pthread(void* arg); enum A_Enum { America = 1, Bazil = 2, China = 3 }; typedef int (*A_FunctionPointer)(int a, int b); #if defined _MSC_VER #define CloseSocket closesocket #else #define CloseSocket close #endif #if defined _MSC_VER #define _long_long "__int64" #define _enum "enum " #define _struct "struct " #define _class "class " #else #define _long_long "long long" #define _enum #define _struct #define _class #endif #if defined _MSC_VER #if defined __x86_64__ || defined _M_X64 #define _pointer " * __ptr64" #define _fptr "__cdecl*" #else #define _pointer " *" #define _fptr " *" #endif #else #define _pointer "*" #define _fptr "*" #endif extern const char* node_type_tostring(const int type); extern h2::h2_string node_tojson(h2::h2_json_node* node); extern h2::h2_string node_dump(h2::h2_json_node* node); class a_exception : public std::exception { public: virtual const char* what() const noexcept override { return "Test Exception"; } };
35.163594
175
0.607169
lingjf
ce47fca96d5b02ef1201fbd8a6957389ba9fe8ee
1,268
cc
C++
tests/test_integration_2d.cc
stvdwtt/adamantine
af396f02089a488a35146ab83234974ae465ada2
[ "BSD-3-Clause" ]
null
null
null
tests/test_integration_2d.cc
stvdwtt/adamantine
af396f02089a488a35146ab83234974ae465ada2
[ "BSD-3-Clause" ]
null
null
null
tests/test_integration_2d.cc
stvdwtt/adamantine
af396f02089a488a35146ab83234974ae465ada2
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2016 - 2020, the adamantine authors. * * This file is subject to the Modified BSD License and may not be distributed * without copyright and license information. Please refer to the file LICENSE * for the text and further information on this license. */ #define BOOST_TEST_MODULE Integration_2D #include "../application/adamantine.hh" #include <fstream> #include "main.cc" BOOST_AUTO_TEST_CASE(intregation_2D) { MPI_Comm communicator = MPI_COMM_WORLD; std::vector<adamantine::Timer> timers; initialize_timers(communicator, timers); // Read the input. std::string const filename = "integration_2d.info"; adamantine::ASSERT_THROW(boost::filesystem::exists(filename) == true, "The file " + filename + " does not exist."); boost::property_tree::ptree database; boost::property_tree::info_parser::read_info(filename, database); auto result = run<2, dealii::MemorySpace::Host>(communicator, database, timers); std::ifstream gold_file("integration_2d_gold.txt"); double const tolerance = 0.1; for (unsigned int i = 0; i < result.local_size(); ++i) { double gold_value = -1.; gold_file >> gold_value; BOOST_CHECK_CLOSE(result.local_element(i), gold_value, tolerance); } }
30.190476
78
0.713722
stvdwtt
ce49e472e8df388706447b5f15ebbd415c166ffa
1,002
cpp
C++
Game/Source/Cores/TestCore.cpp
wobbier/portals
c9f603318137f80b773bab5aad12be265c17e846
[ "MIT" ]
null
null
null
Game/Source/Cores/TestCore.cpp
wobbier/portals
c9f603318137f80b773bab5aad12be265c17e846
[ "MIT" ]
null
null
null
Game/Source/Cores/TestCore.cpp
wobbier/portals
c9f603318137f80b773bab5aad12be265c17e846
[ "MIT" ]
null
null
null
#include "TestCore.h" #include "Components/Transform.h" #include "Components/Camera.h" #include "Engine/Input.h" #include "Events/EventManager.h" #include "optick.h" #include "Engine/World.h" #include "Components/Graphics/Model.h" TestCore::TestCore() : Base(ComponentFilter().Requires<Transform>()) { } void TestCore::OnEntityAdded(Entity& NewEntity) { } void TestCore::OnEntityRemoved(Entity& InEntity) { } #if ME_EDITOR void TestCore::OnEditorInspect() { } #endif void TestCore::Update(float dt) { } void TestCore::Init() { } void TestCore::OnStart() { { auto ent = GameWorld->CreateEntity(); auto& trans = ent->AddComponent<Transform>("Red"); ent->AddComponent<Model>("Assets/Cube.fbx"); trans.SetPosition({-1,0,0}); } { auto ent = GameWorld->CreateEntity(); auto& trans = ent->AddComponent<Transform>("Blue"); ent->AddComponent<Model>("Assets/Cube.fbx"); trans.SetPosition({ 1,0,0 }); trans.Rotate({ 0,90,0 }); } }
18.90566
69
0.658683
wobbier
ce4a913d3b0cb97664f722fc1e8d752122a706a4
2,881
hpp
C++
src/include/portaudio/portaudioDuplex.hpp
elinjammal/opensmile
0ae2da44e61744ff1aaa9bae2b95d747febb08de
[ "W3C" ]
245
2020-10-24T16:27:13.000Z
2022-03-31T03:01:11.000Z
src/include/portaudio/portaudioDuplex.hpp
elinjammal/opensmile
0ae2da44e61744ff1aaa9bae2b95d747febb08de
[ "W3C" ]
41
2021-01-13T11:30:42.000Z
2022-01-14T14:36:11.000Z
src/include/portaudio/portaudioDuplex.hpp
elinjammal/opensmile
0ae2da44e61744ff1aaa9bae2b95d747febb08de
[ "W3C" ]
43
2020-12-11T15:28:19.000Z
2022-03-20T11:55:58.000Z
/*F*************************************************************************** * This file is part of openSMILE. * * Copyright (c) audEERING GmbH. All rights reserved. * See the file COPYING for details on license terms. ***************************************************************************E*/ /* openSMILE component: portAudio dataSink for live audio playback (?? known to work on windows, linux, and mac) */ #ifndef __CPORTAUDIODUPLEX_HPP #define __CPORTAUDIODUPLEX_HPP #include <core/smileCommon.hpp> #include <core/dataProcessor.hpp> #ifdef HAVE_PORTAUDIO #include <portaudio.h> #define COMPONENT_DESCRIPTION_CPORTAUDIODUPLEX "dataProcessor for full-duplex playback and recording of live audio using PortAudio library" #define COMPONENT_NAME_CPORTAUDIODUPLEX "cPortaudioDuplex" #define PA_STREAM_STOPPED 0 #define PA_STREAM_STARTED 1 #undef class class DLLEXPORT cPortaudioDuplex : public cDataProcessor { private: PaStream *stream; long paFrames; int deviceId; int streamStatus; int listDevices; int numDevices; int lastDataCount; int isPaInit; long audioBuffersize; double audioBuffersize_sec; //long mBuffersize; int monoMixdownPB, monoMixdownREC; // if set to 1, multi-channel files will be mixed down to 1 channel int eof, abort; // NOTE : when setting abort, first lock the callbackMtx!!! int channels, sampleRate, nBits, nBPS; //int setupDevice(); protected: SMILECOMPONENT_STATIC_DECL_PR virtual void myFetchConfig() override; virtual int myConfigureInstance() override; virtual int myFinaliseInstance() override; virtual eTickResult myTick(long long t) override; virtual int configureWriter(sDmLevelConfig &c) override; virtual int setupNewNames(long nEl) override; public: SMILECOMPONENT_STATIC_DECL // variables for the callback method: //smileMutex dataFlagMtx; smileMutex callbackMtx; smileCond callbackCond; int dataFlagR, dataFlagW; cMatrix *callbackMatrix; cPortaudioDuplex(const char *_name); void printDeviceList(); int startDuplex(); int stopDuplex(); int stopDuplexWait(); cDataReader * getReader() { return reader_; } cDataWriter * getWriter() { return writer_; } /*void setReadDataFlag() { smileMutexLock(dataFlagMtx); dataFlag = 1; //lastDataCount=0; smileMutexUnlock(dataFlagMtx); }*/ int getNBPS() { return nBPS; } int getNBits() { return nBits; } int getChannels() { return channels; } int getSampleRate() { return sampleRate; } int isAbort() { return abort; } int isMonoMixdownPB() { return monoMixdownPB; } int isMonoMixdownREC() { return monoMixdownREC; } virtual ~cPortaudioDuplex(); }; #endif // HAVE_PORTAUDIO #endif // __CPORTAUDIODUPLEX_HPP
25.27193
139
0.669212
elinjammal
ce4c7f43b84d2b460d9f9beadab57b8a36a1105e
1,122
cpp
C++
engine/engine/render_system/render_system.cpp
phossc/game-engine
7695ed2795cfe44aa295da2114dffc49f258af33
[ "Zlib" ]
1
2019-01-13T14:43:15.000Z
2019-01-13T14:43:15.000Z
engine/engine/render_system/render_system.cpp
phossc/game-engine
7695ed2795cfe44aa295da2114dffc49f258af33
[ "Zlib" ]
null
null
null
engine/engine/render_system/render_system.cpp
phossc/game-engine
7695ed2795cfe44aa295da2114dffc49f258af33
[ "Zlib" ]
1
2019-01-13T14:43:02.000Z
2019-01-13T14:43:02.000Z
#include "engine/render_system/render_system.hpp" #include "engine/core/profiler.hpp" #include "engine/core/system.hpp" #include "engine/update_priorities.hpp" #include "glad/glad.h" #include <cassert> namespace engine { void Render_system::activate() { glClearColor(0.8f, 0.8f, 0.8f, 1.0f); sys->update_system().register_variable_update( this, static_cast<std::int32_t>(Update_priority::rendering)); } void Render_system::deactivate() { sys->update_system().deregister_variable_update(this); } void Render_system::variable_update(double dt) { PROFILE("Render system", "Variable update"); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); for (auto renderer : renderers_) { renderer.second->render(dt); } dependency<Window>()->swap_buffers(); } void Render_system::register_renderer(Renderer* renderer) { assert(renderer != nullptr); renderers_.emplace(renderer->priority(), renderer); } void Render_system::deregister_renderer(Renderer* renderer) { assert(renderer != nullptr); renderers_.erase(renderer->priority()); } } // namespace engine
26.714286
73
0.721034
phossc
ce53554d719dd9023260a439fb8379b5023f734f
1,633
hpp
C++
ext/src/java/awt/Container_AccessibleAWTContainer.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/src/java/awt/Container_AccessibleAWTContainer.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/src/java/awt/Container_AccessibleAWTContainer.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar #pragma once #include <atomic> #include <fwd-POI.hpp> #include <java/awt/fwd-POI.hpp> #include <java/awt/event/fwd-POI.hpp> #include <java/beans/fwd-POI.hpp> #include <javax/accessibility/fwd-POI.hpp> #include <java/awt/Component_AccessibleAWTComponent.hpp> struct default_init_tag; class java::awt::Container_AccessibleAWTContainer : public Component_AccessibleAWTComponent { public: typedef Component_AccessibleAWTComponent super; public: /* protected */ ::java::awt::event::ContainerListener* accessibleContainerHandler { }; private: std::atomic< int32_t > propertyListenersCount { }; static constexpr int64_t serialVersionUID { int64_t(5081320404842566097LL) }; public: /* package */ Container* this$0 { }; protected: void ctor(); public: void addPropertyChangeListener(::java::beans::PropertyChangeListener* listener) override; ::javax::accessibility::Accessible* getAccessibleAt(Point* p) override; ::javax::accessibility::Accessible* getAccessibleChild(int32_t i) override; int32_t getAccessibleChildrenCount() override; void removePropertyChangeListener(::java::beans::PropertyChangeListener* listener) override; // Generated public: /* protected */ Container_AccessibleAWTContainer(Container *Container_this); protected: Container_AccessibleAWTContainer(Container *Container_this, const ::default_init_tag&); public: static ::java::lang::Class *class_(); Container *Container_this; private: virtual ::java::lang::Class* getClass0(); };
28.649123
97
0.753827
pebble2015
ce594b71cd4b88e19a72e197efce997c98b9f5d6
15,592
cpp
C++
source/coolprj/lisp.cpp
pierrebestwork/owl-next
94ba85e8b4dcb978f095b479f85fe4ba3af2fe4e
[ "Zlib" ]
null
null
null
source/coolprj/lisp.cpp
pierrebestwork/owl-next
94ba85e8b4dcb978f095b479f85fe4ba3af2fe4e
[ "Zlib" ]
null
null
null
source/coolprj/lisp.cpp
pierrebestwork/owl-next
94ba85e8b4dcb978f095b479f85fe4ba3af2fe4e
[ "Zlib" ]
null
null
null
/////////////////////////////////////////////////////////////////////////// // // Copyright: Ferdinand Prantl, portions by Stcherbatchenko Andrei // E-mail: prantl@ff.cuni.cz // // LISP (particularly AutoLISP) syntax highlighing definition // // You are free to use or modify this code to the following restrictions: // - Acknowledge me somewhere in your about box, simple "Parts of code by.." // will be enough. If you can't (or don't want to), contact me personally. // - LEAVE THIS HEADER INTACT //////////////////////////////////////////////////////////////////////////// #include <coolprj/pch.h> #pragma hdrstop #include <coolprj/cooledit.h> using namespace owl; // C++ keywords (MSVC5.0 + POET5.0) static LPCTSTR s_apszLispKeywordList[] = { _T ("abs"), _T ("acad_colordlg"), _T ("acad_helpdlg"), _T ("acad_strlsort"), _T ("action_tile"), _T ("add_list"), _T ("ads"), _T ("alert"), _T ("alloc"), _T ("and"), _T ("angle"), _T ("angtof"), _T ("angtos"), _T ("append"), _T ("apply"), _T ("arxload"), _T ("arxunload"), _T ("arx"), _T ("ascii"), _T ("assoc"), _T ("atan"), _T ("atof"), _T ("atoi"), _T ("atoms-family"), _T ("atom"), _T ("autoarxload"), _T ("autoload"), _T ("autoxload"), _T ("boole"), _T ("boundp"), _T ("caaaar"), _T ("caaadr"), _T ("caaar"), _T ("caadar"), _T ("caaddr"), _T ("caadr"), _T ("caar"), _T ("cadaar"), _T ("cadadr"), _T ("cadar"), _T ("caddar"), _T ("cadddr"), _T ("caddr"), _T ("cadr"), _T ("car"), _T ("cdaaar"), _T ("cdaadr"), _T ("cdaar"), _T ("cdadar"), _T ("cdaddr"), _T ("cdadr"), _T ("cdar"), _T ("cddaar"), _T ("cddadr"), _T ("cddar"), _T ("cdddar"), _T ("cddddr"), _T ("cdddr"), _T ("cddr"), _T ("cdr"), _T ("chr"), _T ("client_data_tile"), _T ("close"), _T ("command"), _T ("cond"), _T ("cons"), _T ("cos"), _T ("cvunit"), _T ("defun"), _T ("dictnext"), _T ("dictsearch"), _T ("dimx_tile"), _T ("dimy_tile"), _T ("distance"), _T ("distof"), _T ("done_dialog"), _T ("end_image"), _T ("end_list"), _T ("entdel"), _T ("entget"), _T ("entlast"), _T ("entmake"), _T ("entmod"), _T ("entnext"), _T ("entsel"), _T ("entupd"), _T ("equal"), _T ("eq"), _T ("eval"), _T ("exit"), _T ("expand"), _T ("expt"), _T ("exp"), _T ("fill_image"), _T ("findfile"), _T ("fix"), _T ("float"), _T ("foreach"), _T ("gcd"), _T ("gc"), _T ("get_attr"), _T ("get_tile"), _T ("getangle"), _T ("getcfg"), _T ("getcorner"), _T ("getdist"), _T ("getenv"), _T ("getfield"), _T ("getint"), _T ("getkword"), _T ("getorient"), _T ("getpoint"), _T ("getreal"), _T ("getstring"), _T ("getvar"), _T ("graphscr"), _T ("grclear"), _T ("grdraw"), _T ("grread"), _T ("grtext"), _T ("grvecs"), _T ("handent"), _T ("if"), _T ("help"), _T ("initget"), _T ("inters"), _T ("itoa"), _T ("lambda"), _T ("last"), _T ("length"), _T ("listp"), _T ("list"), _T ("load_dialog"), _T ("load"), _T ("logand"), _T ("logior"), _T ("log"), _T ("lsh"), _T ("mapcar"), _T ("max"), _T ("member"), _T ("mem"), _T ("menucmd"), _T ("minusp"), _T ("min"), _T ("mode_tile"), _T ("namedobjdict"), _T ("nentsel"), _T ("nentselp"), _T ("new_dialog"), _T ("not"), _T ("nth"), _T ("null"), _T ("numberp"), _T ("open"), _T ("or"), _T ("osnap"), _T ("polar"), _T ("prin1"), _T ("princ"), _T ("print"), _T ("progn"), _T ("prompt"), _T ("quit"), _T ("quote"), _T ("read-char"), _T ("read-line"), _T ("read"), _T ("redraw"), _T ("regapp"), _T ("rem"), _T ("repeat"), _T ("reverse"), _T ("rtos"), _T ("setcfg"), _T ("setfunhelp"), _T ("setq"), _T ("setvar"), _T ("set_tile"), _T ("set"), _T ("sin"), _T ("slide_image"), _T ("snvalid"), _T ("sqrt"), _T ("ssadd"), _T ("ssdel"), _T ("ssget"), _T ("sslength"), _T ("ssmemb"), _T ("ssname"), _T ("startapp"), _T ("start_dialog"), _T ("start_image"), _T ("start_list"), _T ("strcase"), _T ("strcat"), _T ("strlen"), _T ("substr"), _T ("subst"), _T ("tablet"), _T ("tblnext"), _T ("tblobjname"), _T ("tblsearch"), _T ("term_dialog"), _T ("terpri"), _T ("textbox"), _T ("textpage"), _T ("textscr"), _T ("trace"), _T ("trans"), _T ("type"), _T ("unload_dialog"), _T ("untrace"), _T ("vector_image"), _T ("ver"), _T ("vmon"), _T ("vports"), _T ("wcmatch"), _T ("while"), _T ("write-char"), _T ("write-line"), _T ("xdroom"), _T ("xdsize"), _T ("xload"), _T ("xunload"), _T ("zerop"), NULL }; static BOOL IsXKeyword (LPCTSTR apszKeywords[], LPCTSTR pszChars, int nLength) { for (int L = 0; apszKeywords[L] != NULL; L++) { if (_tcsncmp (apszKeywords[L], pszChars, nLength) == 0 && apszKeywords[L][nLength] == 0) return TRUE; } return FALSE; } static BOOL IsLispKeyword (LPCTSTR pszChars, int nLength) { return IsXKeyword (s_apszLispKeywordList, pszChars, nLength); } static BOOL IsLispNumber (LPCTSTR pszChars, int nLength) { if (nLength > 2 && pszChars[0] == '0' && pszChars[1] == 'x') { for (int I = 2; I < nLength; I++) { if (_istdigit (pszChars[I]) || (pszChars[I] >= 'A' && pszChars[I] <= 'F') || (pszChars[I] >= 'a' && pszChars[I] <= 'f')) continue; return FALSE; } return TRUE; } if (!_istdigit (pszChars[0])) return FALSE; for (int I = 1; I < nLength; I++) { if (!_istdigit (pszChars[I]) && pszChars[I] != '+' && pszChars[I] != '-' && pszChars[I] != '.' && pszChars[I] != 'e' && pszChars[I] != 'E') return FALSE; } return TRUE; } #define DEFINE_BLOCK(pos, syntaxindex) \ CHECK((pos) >= 0 && (pos) <= nLength);\ if (pBuf != NULL){\ if (nActualItems == 0 || pBuf[nActualItems - 1].CharPos <= (pos)){\ pBuf[nActualItems].CharPos = (pos);\ pBuf[nActualItems].SyntaxIndex = (syntaxindex);\ nActualItems++;\ }\ } #define COOKIE_COMMENT 0x0001 #define COOKIE_PREPROCESSOR 0x0002 #define COOKIE_EXT_COMMENT 0x0004 #define COOKIE_STRING 0x0008 #define COOKIE_CHAR 0x0010 // // // struct TLispSyntaxParser: public TSyntaxParser { public: TLispSyntaxParser(TCoolTextWnd* parent):TSyntaxParser(parent){} uint32 ParseLine(uint32 cookie, int index, TCoolTextWnd::TTextBlock* buf, int& items); }; // _COOLEDFUNC(TSyntaxParser*) LispParserCreator(TCoolTextWnd* parent) { return new TLispSyntaxParser(parent); } // uint32 TLispSyntaxParser::ParseLine(uint32 dwCookie, int nLineIndex, TCoolTextWnd::TTextBlock* pBuf, int& nActualItems) { int nLength = Parent->GetLineLength(nLineIndex); if (nLength <= 1) return dwCookie & COOKIE_EXT_COMMENT; LPCTSTR pszChars = GetLineText(nLineIndex); BOOL bFirstChar = (dwCookie & ~COOKIE_EXT_COMMENT) == 0; BOOL bRedefineBlock = TRUE; BOOL bWasCommentStart = FALSE; BOOL bDecIndex = FALSE; int nIdentBegin = -1; BOOL bDefun = FALSE; int I; for (I = 0;; I++) { if (bRedefineBlock) { int nPos = I; if (bDecIndex) nPos--; if (dwCookie & (COOKIE_COMMENT | COOKIE_EXT_COMMENT)){ DEFINE_BLOCK (nPos, COLORINDEX_COMMENT); } else if (dwCookie & (COOKIE_CHAR | COOKIE_STRING)) { DEFINE_BLOCK (nPos, COLORINDEX_STRING); } else { if (xisalnum (pszChars[nPos]) || pszChars[nPos] == '.') { DEFINE_BLOCK (nPos, COLORINDEX_NORMALTEXT); } else { DEFINE_BLOCK (nPos, COLORINDEX_OPERATOR); bRedefineBlock = TRUE; bDecIndex = TRUE; goto out; } } bRedefineBlock = FALSE; bDecIndex = FALSE; } out: if (I == nLength) break; if (dwCookie & COOKIE_COMMENT) { DEFINE_BLOCK (I, COLORINDEX_COMMENT); dwCookie |= COOKIE_COMMENT; break; } // String constant "...." if (dwCookie & COOKIE_STRING) { if (pszChars[I] == '"' && ( I == 0 || // "... (I >= 1 && pszChars[I - 1] != '\\') || // ...?"... (I >= 2 && pszChars[I - 1] == '\\' && pszChars[I - 2] == '\\') // ...\\"... // TODO: What about ...\\\"...? )) { dwCookie &= ~COOKIE_STRING; bRedefineBlock = TRUE; } continue; } // Char constant '..' if (dwCookie & COOKIE_CHAR) { if (pszChars[I] == '\'' && ( I == 0 || // '... (I >= 1 && pszChars[I - 1] != '\\') || // ...?'... (I >= 2 && pszChars[I - 1] == '\\' && pszChars[I - 2] == '\\') // ...\\'... // TODO: What about ...\\\'...? )) { dwCookie &= ~COOKIE_CHAR; bRedefineBlock = TRUE; } continue; } // Extended comment /*....*/ if (dwCookie & COOKIE_EXT_COMMENT) { // if (I > 0 && pszChars[I] == ';' && pszChars[I - 1] == '|') if ((I > 1 && pszChars[I] == ';' && pszChars[I - 1] == '|' /*&& pszChars[I - 2] != ';'*/ && !bWasCommentStart) || (I == 1 && pszChars[I] == ';' && pszChars[I - 1] == '|')) { dwCookie &= ~COOKIE_EXT_COMMENT; bRedefineBlock = TRUE; } bWasCommentStart = FALSE; continue; } if (I > 0 && pszChars[I] != '|' && pszChars[I - 1] == ';') { DEFINE_BLOCK (I - 1, COLORINDEX_COMMENT); dwCookie |= COOKIE_COMMENT; break; } // Normal text if (pszChars[I] == '"') { DEFINE_BLOCK (I, COLORINDEX_STRING); dwCookie |= COOKIE_STRING; continue; } if (pszChars[I] == '\'') { DEFINE_BLOCK (I, COLORINDEX_STRING); dwCookie |= COOKIE_CHAR; continue; } if (I > 0 && pszChars[I] == '|' && pszChars[I - 1] == ';') { DEFINE_BLOCK (I - 1, COLORINDEX_COMMENT); dwCookie |= COOKIE_EXT_COMMENT; bWasCommentStart = TRUE; continue; } bWasCommentStart = FALSE; if (bFirstChar) { if (!isspace (pszChars[I])) bFirstChar = FALSE; } if (pBuf == NULL) continue; // We don't need to extract keywords, // for faster parsing skip the rest of loop if (xisalnum (pszChars[I]) || pszChars[I] == '.') { if (nIdentBegin == -1) nIdentBegin = I; } else { if (nIdentBegin >= 0) { if (IsLispKeyword (pszChars + nIdentBegin, I - nIdentBegin)) { if (!_tcsnicmp (_T ("defun"), pszChars + nIdentBegin, 5)) { bDefun = TRUE; } DEFINE_BLOCK (nIdentBegin, COLORINDEX_KEYWORD); } else if (IsLispNumber (pszChars + nIdentBegin, I - nIdentBegin)) { DEFINE_BLOCK (nIdentBegin, COLORINDEX_NUMBER); } else { bool bFunction = FALSE; if (!bDefun) { for (int j = nIdentBegin; --j >= 0;) { if (!isspace (pszChars[j])) { if (pszChars[j] == '(') { bFunction = TRUE; } break; } } } if (!bFunction) { for (int j = I; j >= 0; j--) { if (!isspace (pszChars[j])) { if (pszChars[j] == '(') { bFunction = TRUE; } break; } } } if (bFunction) { DEFINE_BLOCK (nIdentBegin, COLORINDEX_FUNCNAME); } } bRedefineBlock = TRUE; bDecIndex = TRUE; nIdentBegin = -1; } } } if (nIdentBegin >= 0) { if (IsLispKeyword (pszChars + nIdentBegin, I - nIdentBegin)) { if (!_tcsnicmp (_T ("defun"), pszChars + nIdentBegin, 5)) { bDefun = TRUE; InUse(bDefun); } DEFINE_BLOCK (nIdentBegin, COLORINDEX_KEYWORD); } else if (IsLispNumber (pszChars + nIdentBegin, I - nIdentBegin)) { DEFINE_BLOCK (nIdentBegin, COLORINDEX_NUMBER); } else { bool bFunction = FALSE; if (!bDefun) { for (int j = nIdentBegin; --j >= 0;) { if (!isspace (pszChars[j])) { if (pszChars[j] == '(') { bFunction = TRUE; } break; } } } if (!bFunction) { for (int j = I; j >= 0; j--) { if (!isspace (pszChars[j])) { if (pszChars[j] == '(') { bFunction = TRUE; } break; } } } if (bFunction) { DEFINE_BLOCK (nIdentBegin, COLORINDEX_FUNCNAME); } } } dwCookie &= COOKIE_EXT_COMMENT; return dwCookie; }
26.205042
182
0.40617
pierrebestwork
ce5ca3a37be366ff132c49a2351fe3b9d6531e52
2,052
cpp
C++
src/pool/executor_thread_pool.cpp
juruen/cavalieri
c3451579193fc8f081b6228ae295b463a0fd23bd
[ "MIT" ]
54
2015-01-14T21:11:56.000Z
2021-06-27T13:29:40.000Z
src/pool/executor_thread_pool.cpp
juruen/cavalieri
c3451579193fc8f081b6228ae295b463a0fd23bd
[ "MIT" ]
null
null
null
src/pool/executor_thread_pool.cpp
juruen/cavalieri
c3451579193fc8f081b6228ae295b463a0fd23bd
[ "MIT" ]
10
2015-07-15T05:09:34.000Z
2019-01-10T07:32:02.000Z
#include <glog/logging.h> #include <pool/executor_thread_pool.h> namespace { const std::string k_exec_pool_service = "executor pool queue size"; const std::string k_exec_pool_desc = "number of pending tasks"; const size_t k_stop_attempts = 50; const size_t k_stop_interval_check_ms = 100; const size_t k_max_queue_size = 1e+7; } executor_thread_pool::executor_thread_pool( instrumentation::instrumentation & instr, const config & conf) : task_guague_(instr.add_gauge(k_exec_pool_service, k_exec_pool_desc)), finished_threads_(conf.executor_pool_size, 0), next_thread_(0), tasks_(conf.executor_pool_size) { auto run_fn = [=](const int i) { run_tasks(i); }; for (size_t i = 0; i < conf.executor_pool_size; i++) { tasks_[i].set_capacity(k_max_queue_size); threads_.push_back(std::move(std::thread(run_fn, i))); } } void executor_thread_pool::add_task(const task_fn_t & task) { task_guague_.incr_fn(1); tasks_[next_thread_].push({task, false}); next_thread_ = (next_thread_ + 1) % tasks_.size(); } void executor_thread_pool::stop() { VLOG(3) << "stopping executor_thread_pool"; for (size_t i = 0; i < threads_.size(); i++) { tasks_[i].clear(); tasks_[i].push({{}, true}); } for (size_t attempts = k_stop_attempts; attempts > 0; attempts--) { size_t stopped = 0 ; for (const auto & t: finished_threads_) { if (t) stopped++; } if (stopped == threads_.size()) { break; } VLOG(3) << "Waiting for " << threads_.size() - stopped << " threads"; std::this_thread::sleep_for( std::chrono::milliseconds(k_stop_interval_check_ms)); } for (size_t i = 0; i < threads_.size(); i++) { threads_[i].join(); } } void executor_thread_pool::run_tasks(const int i) { VLOG(3) << "starting executor thread"; task_t task; while (true) { tasks_[i].pop(task); if (task.stop) { break; } task.fn(); task_guague_.decr_fn(1); } finished_threads_[i] = 1; VLOG(3) << "run_tasks()--"; }
19.730769
73
0.649123
juruen
ce5d9b20ca0e1b4316efffb721be5acd3ce048a8
2,554
cpp
C++
Codeforces-Code/8VC Venture Cup 2016 - Final Round/G.cpp
PrayStarJirachi/Exercise-Code
801a5926eccc971ab2182e5e99e3a0746bd6a7f0
[ "MIT" ]
null
null
null
Codeforces-Code/8VC Venture Cup 2016 - Final Round/G.cpp
PrayStarJirachi/Exercise-Code
801a5926eccc971ab2182e5e99e3a0746bd6a7f0
[ "MIT" ]
null
null
null
Codeforces-Code/8VC Venture Cup 2016 - Final Round/G.cpp
PrayStarJirachi/Exercise-Code
801a5926eccc971ab2182e5e99e3a0746bd6a7f0
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> const int MAXN = 4001; int r, c, n, k, a[MAXN], p[MAXN], L[MAXN], R[MAXN], sA[MAXN], sB[MAXN], pA[MAXN], pB[MAXN]; std::pair<int, int> z[MAXN]; std::vector<int> d[MAXN]; long long answer; bool cmp(const std::pair<int, int> &a, const std::pair<int, int> &b) { return a.second < b.second; } void del(int now, long long &answer) { int tA = 0, tB = 0, zL = now, zR = now; if (!--a[now]) { R[L[now]] = R[now]; L[R[now]] = L[now]; } for (int i = 1; i <= k + 1 && zL != 0; i++, zL = L[zL]) { sA[++tA] = a[zL]; pA[tA] = zL; } for (int i = 1; i <= k + 1 && zR != c + 1; i++, zR = R[zR]) { sB[++tB] = a[zR]; pB[tB] = zR; } for (int i = 1; i <= tA; i++) sA[i] += sA[i - 1]; for (int i = 1; i <= tB; i++) sB[i] += sB[i - 1]; for (int i = tA, j = 1; i >= 1; i--) { while (j <= tB && sA[i] + sB[j] - a[now] + 1 < k) j++; if (j <= tB && sA[i] + sB[j] - a[now] + 1 == k) { int pred = (i == tA) ? 0 : pA[i + 1]; int succ = (j == tB) ? c + 1 : pB[j + 1]; answer += 1ll * (pA[i] - pred) * (succ - pB[j]); assert(pA[i] >= pred); } } //puts(""); } int main() { freopen("G.in", "r", stdin); std::cin >> r >> c >> n >> k; for (int i = 1; i <= n; i++) { std::cin >> z[i].first >> z[i].second; } std::sort(z + 1, z + n + 1, cmp); for (int i = 1; i <= n; i++) { d[z[i].first].push_back(i); } long long base = 0; for (int i = 1; i <= r; i++) for (int j = 1; j <= c; j++) base += 1ll * i * j; for (int i = 1; i <= r; i++) { int tot = 0; R[0] = c + 1; L[c + 1] = 0; static int tmp[MAXN], cnt[MAXN]; std::fill(tmp, tmp + c + 1, 0); std::fill(a, a + c + 1, 0); std::fill(cnt, cnt + n + 1, 0); for (int j = n; j >= 1; j--) { if (z[j].first < i) continue; if (a[z[j].second] == 0) { p[j] = z[j].second; L[z[j].second] = 0; R[z[j].second] = R[0]; L[R[0]] = z[j].second; R[0] = z[j].second; } a[z[j].second]++; tmp[z[j].second]++; } long long counter = 0; for (int j = 1; j <= c; j++) { tmp[j] += tmp[j - 1]; } for (int j = 1; j <= c; j++) { cnt[tmp[j - 1]]++; for (int h = 0; h < k && h <= tmp[j]; h++) { counter += cnt[tmp[j] - h]; } } for (int j = r; j >= i; j--) { answer -= counter; //std::cout << "(" << i << ", " << j << ") = " << counter << std::endl; for (auto v : d[j]) { del(z[v].second, counter); } //std::cout << "After = " << counter << std::endl; } } //std::cout << base << std::endl; //std::cout << -answer << std::endl; std::cout << base + answer << std::endl; return 0; }
25.54
91
0.434612
PrayStarJirachi
ce611cb18716c369627b86e45bceca05fc3a4c7e
1,740
hpp
C++
src/solvers/agent_routing/AgentTask.hpp
tomcreutz/planning-templ
55e35ede362444df9a7def6046f6df06851fe318
[ "BSD-3-Clause" ]
1
2022-03-31T12:15:15.000Z
2022-03-31T12:15:15.000Z
src/solvers/agent_routing/AgentTask.hpp
tomcreutz/planning-templ
55e35ede362444df9a7def6046f6df06851fe318
[ "BSD-3-Clause" ]
null
null
null
src/solvers/agent_routing/AgentTask.hpp
tomcreutz/planning-templ
55e35ede362444df9a7def6046f6df06851fe318
[ "BSD-3-Clause" ]
1
2021-12-29T10:38:07.000Z
2021-12-29T10:38:07.000Z
#ifndef TEMPL_AGENT_ROUTING_AGENT_TASK_HPP #define TEMPL_AGENT_ROUTING_AGENT_TASK_HPP #include <cstdint> #include "../../symbols/constants/Location.hpp" #include "../../solvers/temporal/Interval.hpp" namespace templ { namespace solvers { namespace agent_routing { typedef uint32_t TaskPriority; typedef uint32_t TaskDuration; class AgentTask { public: typedef std::vector<AgentTask> List; AgentTask(); void setTaskPriority(TaskPriority p) { mPriority = p; } TaskPriority getTaskPriority() const { return mPriority; } void setLocation(const symbols::constants::Location& c) { mLocation = c; } const symbols::constants::Location& getLocation() const { return mLocation; } void setTaskDuration(const TaskDuration& t) { mTaskDuration = t; } TaskDuration getTaskDuration() const { return mTaskDuration; } void setArrival(const solvers::temporal::point_algebra::TimePoint::Ptr& t) { mArrival = t; } solvers::temporal::point_algebra::TimePoint::Ptr getArrival() const { return mArrival; } void setDeparture(const solvers::temporal::point_algebra::TimePoint::Ptr& t) { mDeparture = t; } solvers::temporal::point_algebra::TimePoint::Ptr getDeparture() const { return mDeparture; } std::string toString(uint32_t indent = 0) const; static std::string toString(const AgentTask::List& list, uint32_t uindent); private: TaskPriority mPriority; symbols::constants::Location mLocation; TaskDuration mTaskDuration; solvers::temporal::point_algebra::TimePoint::Ptr mArrival; solvers::temporal::point_algebra::TimePoint::Ptr mDeparture; }; } // end namespace agent_routing } // end namespace solvers } // end namespace templ #endif // TEMPL_AGENT_ROUTING_AGENT_TASK_HPP
33.461538
100
0.744828
tomcreutz
ce6259027340728f6bba8d36f06a7b60a07a71e8
6,761
cpp
C++
SpatialGDK/Source/SpatialGDK/Private/Tests/SpatialView/AuthorityRecordTest.cpp
elizabethking2/UnrealGDK
e3a8aee7c71c6bd0c33f4f88c10b6725d8039d74
[ "MIT" ]
363
2018-07-30T12:57:42.000Z
2022-03-25T14:30:28.000Z
SpatialGDK/Source/SpatialGDK/Private/Tests/SpatialView/AuthorityRecordTest.cpp
elizabethking2/UnrealGDK
e3a8aee7c71c6bd0c33f4f88c10b6725d8039d74
[ "MIT" ]
1,634
2018-07-30T14:30:25.000Z
2022-03-03T01:55:15.000Z
SpatialGDK/Source/SpatialGDK/Private/Tests/SpatialView/AuthorityRecordTest.cpp
elizabethking2/UnrealGDK
e3a8aee7c71c6bd0c33f4f88c10b6725d8039d74
[ "MIT" ]
153
2018-07-31T13:45:02.000Z
2022-03-03T05:20:24.000Z
// Copyright (c) Improbable Worlds Ltd, All Rights Reserved #include "Tests/TestDefinitions.h" #include "SpatialView/AuthorityRecord.h" #define AUTHORITYRECORD_TEST(TestName) \ GDK_TEST(Core, AuthorityRecord, TestName) using namespace SpatialGDK; namespace { class AuthorityChangeRecordFixture { public: const Worker_EntityId kTestEntityId = 1337; const Worker_ComponentId kTestComponentId = 1338; const EntityComponentId kEntityComponentId{ kTestEntityId, kTestComponentId }; AuthorityRecord Record; TArray<EntityComponentId> ExpectedAuthorityGained; TArray<EntityComponentId> ExpectedAuthorityLost; TArray<EntityComponentId> ExpectedAuthorityLostTemporarily; }; } // anonymous namespace AUTHORITYRECORD_TEST(GIVEN_EmptyAuthorityRecord_WHEN_set_to_authoritative_THEN_AuthorityRecord_has_AuthorityGainedRecord) { // GIVEN AuthorityChangeRecordFixture Fixture; // WHEN Fixture.Record.SetAuthority(Fixture.kTestEntityId, Fixture.kTestComponentId, WORKER_AUTHORITY_AUTHORITATIVE); // THEN Fixture.ExpectedAuthorityGained.Push(Fixture.kEntityComponentId); TestTrue(TEXT("Comparing AuthorityGained"), Fixture.Record.GetAuthorityGained() == Fixture.ExpectedAuthorityGained); TestTrue(TEXT("Comparing AuthorityLost"), Fixture.Record.GetAuthorityLost() == Fixture.ExpectedAuthorityLost); TestTrue(TEXT("Comparing AuthorityLostTemporarily"), Fixture.Record.GetAuthorityLostTemporarily() == Fixture.ExpectedAuthorityLostTemporarily); return true; } AUTHORITYRECORD_TEST(GIVEN_AuthorityRecord_with_AuthoritativeRecord_WHEN_set_to_NonAuthoritative_THEN_AuthorityRecord_has_no_records) { // GIVEN AuthorityChangeRecordFixture Fixture; Fixture.Record.SetAuthority(Fixture.kTestEntityId, Fixture.kTestComponentId, WORKER_AUTHORITY_AUTHORITATIVE); // WHEN Fixture.Record.SetAuthority(Fixture.kTestEntityId, Fixture.kTestComponentId, WORKER_AUTHORITY_NOT_AUTHORITATIVE); // THEN TestTrue(TEXT("Comparing AuthorityGained"), Fixture.Record.GetAuthorityGained() == Fixture.ExpectedAuthorityGained); TestTrue(TEXT("Comparing AuthorityLost"), Fixture.Record.GetAuthorityLost() == Fixture.ExpectedAuthorityLost); TestTrue(TEXT("Comparing AuthorityLostTemporarily"), Fixture.Record.GetAuthorityLostTemporarily() == Fixture.ExpectedAuthorityLostTemporarily); return true; } AUTHORITYRECORD_TEST(GIVEN_empty_AuthorityRecord_WHEN_set_to_NonAuthoritative_THEN_has_AuthorityLostRecord) { // GIVEN AuthorityChangeRecordFixture Fixture; // WHEN Fixture.Record.SetAuthority(Fixture.kTestEntityId, Fixture.kTestComponentId, WORKER_AUTHORITY_NOT_AUTHORITATIVE); // THEN Fixture.ExpectedAuthorityLost.Push(Fixture.kEntityComponentId); TestTrue(TEXT("Comparing AuthorityGained"), Fixture.Record.GetAuthorityGained() == Fixture.ExpectedAuthorityGained); TestTrue(TEXT("Comparing AuthorityLost"), Fixture.Record.GetAuthorityLost() == Fixture.ExpectedAuthorityLost); TestTrue(TEXT("Comparing AuthorityLostTemporarily"), Fixture.Record.GetAuthorityLostTemporarily() == Fixture.ExpectedAuthorityLostTemporarily); return true; } AUTHORITYRECORD_TEST(GIVEN_AuthorityRecord_with_NonAuthoritativeRecord_WHEN_set_to_Authoritative_THEN_has_AuthorityLostTemporarilyRecord) { // GIVEN AuthorityChangeRecordFixture Fixture; Fixture.Record.SetAuthority(Fixture.kTestEntityId, Fixture.kTestComponentId, WORKER_AUTHORITY_NOT_AUTHORITATIVE); // WHEN Fixture.Record.SetAuthority(Fixture.kTestEntityId, Fixture.kTestComponentId, WORKER_AUTHORITY_AUTHORITATIVE); // THEN Fixture.ExpectedAuthorityLostTemporarily.Push(Fixture.kEntityComponentId); TestTrue(TEXT("Comparing AuthorityGained"), Fixture.Record.GetAuthorityGained() == Fixture.ExpectedAuthorityGained); TestTrue(TEXT("Comparing AuthorityLost"), Fixture.Record.GetAuthorityLost() == Fixture.ExpectedAuthorityLost); TestTrue(TEXT("Comparing AuthorityLostTemporarily"), Fixture.Record.GetAuthorityLostTemporarily() == Fixture.ExpectedAuthorityLostTemporarily); return true; } AUTHORITYRECORD_TEST(GIVEN_AuthorityRecord_with_NonAuthoritativeRecord_WHEN_set_to_Authoritative_and_NonAuthoritative_THEN_has_AuthorityLostRecord) { // GIVEN AuthorityChangeRecordFixture Fixture; Fixture.Record.SetAuthority(Fixture.kTestEntityId, Fixture.kTestComponentId, WORKER_AUTHORITY_NOT_AUTHORITATIVE); // WHEN Fixture.Record.SetAuthority(Fixture.kTestEntityId, Fixture.kTestComponentId, WORKER_AUTHORITY_AUTHORITATIVE); Fixture.Record.SetAuthority(Fixture.kTestEntityId, Fixture.kTestComponentId, WORKER_AUTHORITY_NOT_AUTHORITATIVE); // THEN Fixture.ExpectedAuthorityLost.Push(Fixture.kEntityComponentId); TestTrue(TEXT("Comparing AuthorityGained"), Fixture.Record.GetAuthorityGained() == Fixture.ExpectedAuthorityGained); TestTrue(TEXT("Comparing AuthorityLost"), Fixture.Record.GetAuthorityLost() == Fixture.ExpectedAuthorityLost); TestTrue(TEXT("Comparing AuthorityLostTemporarily"), Fixture.Record.GetAuthorityLostTemporarily() == Fixture.ExpectedAuthorityLostTemporarily); return true; } AUTHORITYRECORD_TEST(GIVEN_AuthorityRecord_with_AuthoritativeRecord_NonAuthoritativeRecord_and_AuthorityLostTemporarilyRecorde_WHEN_Cleared_THEN_has_no_records) { // GIVEN AuthorityChangeRecordFixture Fixture; Fixture.Record.SetAuthority(Fixture.kTestEntityId, 1, WORKER_AUTHORITY_NOT_AUTHORITATIVE); Fixture.Record.SetAuthority(Fixture.kTestEntityId, 2, WORKER_AUTHORITY_AUTHORITATIVE); Fixture.Record.SetAuthority(Fixture.kTestEntityId, 3, WORKER_AUTHORITY_NOT_AUTHORITATIVE); Fixture.Record.SetAuthority(Fixture.kTestEntityId, 3, WORKER_AUTHORITY_AUTHORITATIVE); Fixture.ExpectedAuthorityLost.Push(EntityComponentId{ Fixture.kTestEntityId, 1 }); Fixture.ExpectedAuthorityGained.Push(EntityComponentId{ Fixture.kTestEntityId, 2 }); Fixture.ExpectedAuthorityLostTemporarily.Push(EntityComponentId{ Fixture.kTestEntityId, 3 }); TestTrue(TEXT("Comparing AuthorityGained"), Fixture.Record.GetAuthorityGained() == Fixture.ExpectedAuthorityGained); TestTrue(TEXT("Comparing AuthorityLost"), Fixture.Record.GetAuthorityLost() == Fixture.ExpectedAuthorityLost); TestTrue(TEXT("Comparing AuthorityLostTemporarily"), Fixture.Record.GetAuthorityLostTemporarily() == Fixture.ExpectedAuthorityLostTemporarily); // WHEN Fixture.Record.Clear(); // THEN Fixture.ExpectedAuthorityLost.Empty(); Fixture.ExpectedAuthorityGained.Empty(); Fixture.ExpectedAuthorityLostTemporarily.Empty(); TestTrue(TEXT("Comparing AuthorityGained"), Fixture.Record.GetAuthorityGained() == Fixture.ExpectedAuthorityGained); TestTrue(TEXT("Comparing AuthorityLost"), Fixture.Record.GetAuthorityLost() == Fixture.ExpectedAuthorityLost); TestTrue(TEXT("Comparing AuthorityLostTemporarily"), Fixture.Record.GetAuthorityLostTemporarily() == Fixture.ExpectedAuthorityLostTemporarily); return true; }
46.308219
160
0.845289
elizabethking2
ce6b700b7d210e0917bcaca2f5360e853a4caf6f
2,186
cpp
C++
src/platform.cpp
dev2alert/node-samp-plugin
ad3bf531aacaae99b653154b0af2e6809429f212
[ "MIT" ]
2
2022-01-13T15:37:15.000Z
2022-02-06T11:55:23.000Z
src/platform.cpp
dev2alert/node-samp-plugin
ad3bf531aacaae99b653154b0af2e6809429f212
[ "MIT" ]
null
null
null
src/platform.cpp
dev2alert/node-samp-plugin
ad3bf531aacaae99b653154b0af2e6809429f212
[ "MIT" ]
null
null
null
#include "platform.h" #include "env.h" #include "json.hpp" namespace nodesamp { Platform::Platform(const std::vector<std::string>& options, std::string path, const std::vector<std::string>& args): path(path) { this->args.push_back(""); for(std::string option: options) this->args.push_back(option); this->args.push_back(path); for(std::string arg: args) this->args.push_back(arg); } void Platform::init() { using namespace v8; std::vector<std::string> execArgs; std::vector<std::string> errors; node::InitializeNodeWithArgs(&this->args, &execArgs, &errors); this->platform = node::MultiIsolatePlatform::Create(4); V8::InitializePlatform(this->platform.get()); V8::Initialize(); } Environment* Platform::loadDefaultEnv() { if(this->defaultEnv != nullptr) return this->defaultEnv.get(); this->defaultEnv = std::unique_ptr<Environment>(new Environment(this, "")); this->defaultEnv->load(); return this->defaultEnv.get(); } Environment* Platform::getDefaultEnv() { return this->defaultEnv.get(); } void Platform::stopDefaultEnv() { if(this->defaultEnv == nullptr) return; this->defaultEnv->stop(); this->defaultEnv.reset(); } void Platform::tick() { if(this->defaultEnv == nullptr) return; this->defaultEnv->tick(); } void Platform::callAmxPublic(AMX* amx, std::string name, cell* params, cell* retval) { if(this->defaultEnv == nullptr) return; this->defaultEnv->callAmxPublic(amx, name, params, retval); } void Platform::uninit() { using namespace v8; this->stopDefaultEnv(); V8::Dispose(); V8::ShutdownPlatform(); this->platform.reset(); } std::unique_ptr<Platform> InitPlatform(const std::vector<std::string>& options, std::string path, const std::vector<std::string>& args) { std::unique_ptr<Platform> platform(new Platform(options, path, args)); platform->init(); return platform; } }
31.681159
141
0.595608
dev2alert
ce6eac4783780cacc30f2eac52b346bbfa7db469
1,457
cpp
C++
aashishgahlawat/codeforces/B/834-B/834-B-32840837.cpp
aashishgahlawat/CompetetiveProgramming
12d6b2682765ae05b622968b9a26b0b519e170aa
[ "MIT" ]
null
null
null
aashishgahlawat/codeforces/B/834-B/834-B-32840837.cpp
aashishgahlawat/CompetetiveProgramming
12d6b2682765ae05b622968b9a26b0b519e170aa
[ "MIT" ]
null
null
null
aashishgahlawat/codeforces/B/834-B/834-B-32840837.cpp
aashishgahlawat/CompetetiveProgramming
12d6b2682765ae05b622968b9a26b0b519e170aa
[ "MIT" ]
null
null
null
#include <iostream> #include <bits/stdc++.h> #include <math.h> #include <string.h> #include <algorithm> #define endl '\n' #define ll long long int #define pb push_back #define mp make_pair #define foriter(it, x) for (__typeof((x).begin()) it = (x).begin(); it != (x).end(); it++) using namespace std; int mod=1000000007; long long int answer; void printVector(vector<int> v) { // lambda expression to print vector for_each(v.begin(), v.end(), [](int i){std::cout << i << " ";});//from to fn, lambda cout << endl; } int lInd[26];//last index of abcd... bool visit[26]; int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif // ONLINE_JUDGE ios_base::sync_with_stdio(false); ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); // aashish gahlawat int pCount,gCount; cin>>pCount>>gCount; string people; cin>>people; for(int i=0;i<people.size();i++){ lInd[people[i]-65]=i; } int onDuty=0; for(int i=0;i<people.size();i++){ if(!visit[people[i]-65]){ visit[people[i]-65]=true; onDuty++; } if(onDuty>gCount){cout<<"YES"; return 0;} if(visit[people[i]-65] && i==lInd[people[i]-65]) onDuty--; } cout<<"NO"; #ifndef ONLINE_JUDGE cout<<endl<<endl<< "Time elapsed: " << (double)clock() / CLOCKS_PER_SEC * 1000 << " ms.\n"; #endif // LOCAL return 0; }
27.490566
95
0.586822
aashishgahlawat
ce7318de225a1db368a9b0c8d64199de117d9107
1,003
hpp
C++
third_party/boost/simd/function/sec.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
6
2018-02-25T22:23:33.000Z
2021-01-15T15:13:12.000Z
third_party/boost/simd/function/sec.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
null
null
null
third_party/boost/simd/function/sec.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
7
2017-12-12T12:36:31.000Z
2020-02-10T14:27:07.000Z
//================================================================================================== /*! @file @copyright 2016 NumScale SAS Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ //================================================================================================== #ifndef BOOST_SIMD_FUNCTION_SEC_HPP_INCLUDED #define BOOST_SIMD_FUNCTION_SEC_HPP_INCLUDED #if defined(DOXYGEN_ONLY) namespace boost { namespace simd { /*! @ingroup group-trigonometric This function object returns the secant of the angle in radian: \f$1/\cos(x)\f$. @see cos, secd, secpi @par Header <boost/simd/function/sec.hpp> @par Example: @snippet sec.cpp sec @par Possible output: @snippet sec.txt sec **/ IEEEValue sec(IEEEValue const& x); } } #endif #include <boost/simd/function/scalar/sec.hpp> #include <boost/simd/function/simd/sec.hpp> #endif
22.288889
100
0.565304
SylvainCorlay
707153a6e4726f68eaa4fdea21e44b99dae2d71f
14,212
cpp
C++
quantitative_finance/L2/benchmarks/MCAmericanEngineMultiKernel/src/main.cpp
Aperture-Electronic/Vitis_Libraries
e178d54f82c90f1a1e47f599f401f8cbf8df86d7
[ "Apache-2.0" ]
1
2020-10-27T07:37:10.000Z
2020-10-27T07:37:10.000Z
quantitative_finance/L2/benchmarks/MCAmericanEngineMultiKernel/src/main.cpp
Aperture-Electronic/Vitis_Libraries
e178d54f82c90f1a1e47f599f401f8cbf8df86d7
[ "Apache-2.0" ]
null
null
null
quantitative_finance/L2/benchmarks/MCAmericanEngineMultiKernel/src/main.cpp
Aperture-Electronic/Vitis_Libraries
e178d54f82c90f1a1e47f599f401f8cbf8df86d7
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019 Xilinx, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef HLS_TEST #include "xcl2.hpp" #endif #include <sys/time.h> #include <cstring> #include <fstream> #include <iostream> #include <vector> #include "MCAE_kernel.hpp" #include "ap_int.h" #include "utils.hpp" class ArgParser { public: ArgParser(int& argc, const char** argv) { for (int i = 1; i < argc; ++i) mTokens.push_back(std::string(argv[i])); } bool getCmdOption(const std::string option, std::string& value) const { std::vector<std::string>::const_iterator itr; itr = std::find(this->mTokens.begin(), this->mTokens.end(), option); if (itr != this->mTokens.end() && ++itr != this->mTokens.end()) { value = *itr; return true; } return false; } private: std::vector<std::string> mTokens; }; int main(int argc, const char* argv[]) { std::cout << "\n----------------------MC(American) Engine-----------------\n"; // cmd parser ArgParser parser(argc, argv); std::string xclbin_path; #ifndef HLS_TEST if (!parser.getCmdOption("-xclbin", xclbin_path)) { std::cout << "ERROR:xclbin path is not set!\n"; return 1; } #endif std::string mode = "hw"; if (std::getenv("XCL_EMULATION_MODE") != nullptr) { mode = std::getenv("XCL_EMULATION_MODE"); } std::cout << "[INFO]Running in " << mode << " mode" << std::endl; // AXI depth int data_size = depthP; // 20480;//= depthP = 1024(calibrate // samples)*10(steps) *2(iter), width: 64*UN int matdata_size = depthM; ////180;//=depthM = 9*10(steps)*2(iter), width: 64 int coefdata_size = COEF_DEPTH; // TIMESTEPS - 1; // 9;//=(steps-1), width: 4*64 std::cout << "data_size is " << data_size << std::endl; ap_uint<64 * UN_K1>* output_price[2]; ap_uint<64>* output_mat[2]; // = aligned_alloc<ap_uint<64> >(matdata_size); ap_uint<64 * COEF>* coef[2]; // = aligned_alloc<ap_uint<64 * COEF> >(coefdata_size); for (int i = 0; i < 2; ++i) { output_price[i] = aligned_alloc<ap_uint<64 * UN_K1> >(data_size); // 64*UN output_mat[i] = aligned_alloc<ap_uint<64> >(matdata_size); coef[i] = aligned_alloc<ap_uint<64 * COEF> >(coefdata_size); } // -------------setup params--------------- int timeSteps = 100; TEST_DT underlying = 36; TEST_DT strike = 40.0; int optionType = 1; TEST_DT volatility = 0.20; TEST_DT riskFreeRate = 0.06; TEST_DT dividendYield = 0.0; TEST_DT timeLength = 1; TEST_DT requiredTolerance = 0.02; unsigned int seeds[2] = {11111, 111111}; unsigned int requiredSamples; //= 24576 / KN2; int calibSamples = 4096; int maxsamples = 0; double golden_output = 3.978; std::string num_str; int loop_nm = 100; if (parser.getCmdOption("-cal", num_str)) { try { calibSamples = std::stoi(num_str); } catch (...) { calibSamples = 4096; } } if (parser.getCmdOption("-s", num_str)) { try { timeSteps = std::stoi(num_str); } catch (...) { timeSteps = 100; } } if (mode.compare("hw_emu") == 0) { timeSteps = UN_K2_STEP; golden_output = 4.18; loop_nm = 1; } else if (mode.compare("sw_emu") == 0) { loop_nm = 1; } std::cout << "loop_nm: " << loop_nm << std::endl; #ifdef HLS_TEST MCAE_k0(underlying, volatility, riskFreeRate, dividendYield, timeLength, strike, optionType, output_price_b, output_mat_b, calibSamples, timeSteps); MCAE_k1(timeLength, riskFreeRate, strike, optionType, output_price_b, output_mat_b, coef_b, calibSamples, timeSteps); MCAE_k2(underlying, volatility, dividendYield, riskFreeRate, timeLength, strike, optionType, coef_b, output_b, requiredTolerance, requiredSamples, timeSteps); #else struct timeval start_time, end_time; // platform related operations std::vector<cl::Device> devices = xcl::get_xil_devices(); cl::Device device = devices[0]; // Creating Context and Command Queue for selected Device cl::Context context(device); #ifdef SW_EMU_TEST cl::CommandQueue q(context, device, CL_QUEUE_PROFILING_ENABLE); #else cl::CommandQueue q(context, device, CL_QUEUE_PROFILING_ENABLE | CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE); #endif std::string devName = device.getInfo<CL_DEVICE_NAME>(); printf("Found Device=%s\n", devName.c_str()); // cl::Program::Binaries xclBins = // xcl::import_binary_file("../xclbin/MCAE_u250_hw.xclbin"); cl::Program::Binaries xclBins = xcl::import_binary_file(xclbin_path); devices.resize(1); cl::Program program(context, devices, xclBins); cl::Kernel kernel_MCAE_k0[2]; kernel_MCAE_k0[0] = cl::Kernel(program, "MCAE_k0"); kernel_MCAE_k0[1] = cl::Kernel(program, "MCAE_k0"); cl::Kernel kernel_MCAE_k1[2]; kernel_MCAE_k1[0] = cl::Kernel(program, "MCAE_k1"); kernel_MCAE_k1[1] = cl::Kernel(program, "MCAE_k1"); std::string krnl_name = "MCAE_k2"; cl_uint cu_number; { cl::Kernel k(program, krnl_name.c_str()); k.getInfo(CL_KERNEL_COMPUTE_UNIT_COUNT, &cu_number); } if (parser.getCmdOption("-p", num_str)) { try { requiredSamples = std::stoi(num_str); } catch (...) { requiredSamples = 24576 / cu_number; } } else { requiredSamples = 24576 / cu_number; } std::cout << "paths: " << requiredSamples << std::endl; std::vector<TEST_DT*> output_a(cu_number); std::vector<TEST_DT*> output_b(cu_number); for (int c = 0; c < cu_number; ++c) { output_a[c] = aligned_alloc<TEST_DT>(1); output_b[c] = aligned_alloc<TEST_DT>(1); } std::vector<cl::Kernel> kernel_MCAE_k2_a(cu_number); std::vector<cl::Kernel> kernel_MCAE_k2_b(cu_number); for (cl_uint i = 0; i < cu_number; ++i) { std::string krnl_full_name = krnl_name + ":{" + krnl_name + "_" + std::to_string(i + 1) + "}"; kernel_MCAE_k2_a[i] = cl::Kernel(program, krnl_full_name.c_str()); kernel_MCAE_k2_b[i] = cl::Kernel(program, krnl_full_name.c_str()); } std::cout << "kernel has been created" << std::endl; cl_mem_ext_ptr_t mext_o_m[2][3]; std::vector<cl_mem_ext_ptr_t> mext_o_a(cu_number); std::vector<cl_mem_ext_ptr_t> mext_o_b(cu_number); for (int i = 0; i < 2; ++i) { mext_o_m[i][0] = {7, output_price[i], kernel_MCAE_k0[i]()}; mext_o_m[i][1] = {8, output_mat[i], kernel_MCAE_k0[i]()}; mext_o_m[i][2] = {6, coef[i], kernel_MCAE_k1[i]()}; ; } for (int c = 0; c < cu_number; ++c) { mext_o_a[c] = {9, output_a[c], kernel_MCAE_k2_a[c]()}; mext_o_b[c] = {9, output_b[c], kernel_MCAE_k2_b[c]()}; } // create device buffer and map dev buf to host buf cl::Buffer output_price_buf[2]; cl::Buffer output_mat_buf[2]; cl::Buffer coef_buf[2]; for (int i = 0; i < 2; ++i) { output_price_buf[i] = cl::Buffer(context, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, sizeof(ap_uint<64 * UN_K1>) * data_size, &mext_o_m[i][0]); output_mat_buf[i] = cl::Buffer(context, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, sizeof(ap_uint<64>) * matdata_size, &mext_o_m[i][1]); coef_buf[i] = cl::Buffer(context, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, sizeof(ap_uint<64 * COEF>) * coefdata_size, &mext_o_m[i][2]); } std::vector<cl::Buffer> output_buf_a(cu_number); std::vector<cl::Buffer> output_buf_b(cu_number); for (int c = 0; c < cu_number; ++c) { output_buf_a[c] = cl::Buffer(context, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, sizeof(TEST_DT), &mext_o_a[c]); output_buf_b[c] = cl::Buffer(context, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, sizeof(TEST_DT), &mext_o_b[c]); } std::vector<cl::Memory> ob_out; for (int c = 0; c < cu_number; ++c) { ob_out.push_back(output_buf_a[c]); } std::vector<cl::Memory> ob_out_b; for (int c = 0; c < cu_number; ++c) { ob_out_b.push_back(output_buf_b[c]); } for (int i = 0; i < 2; ++i) { kernel_MCAE_k0[i].setArg(0, underlying); kernel_MCAE_k0[i].setArg(1, volatility); kernel_MCAE_k0[i].setArg(2, riskFreeRate); kernel_MCAE_k0[i].setArg(3, dividendYield); kernel_MCAE_k0[i].setArg(4, timeLength); kernel_MCAE_k0[i].setArg(5, strike); kernel_MCAE_k0[i].setArg(6, optionType); kernel_MCAE_k0[i].setArg(7, output_price_buf[i]); kernel_MCAE_k0[i].setArg(8, output_mat_buf[i]); kernel_MCAE_k0[i].setArg(9, calibSamples); kernel_MCAE_k0[i].setArg(10, timeSteps); kernel_MCAE_k1[i].setArg(0, timeLength); kernel_MCAE_k1[i].setArg(1, riskFreeRate); kernel_MCAE_k1[i].setArg(2, strike); kernel_MCAE_k1[i].setArg(3, optionType); kernel_MCAE_k1[i].setArg(4, output_price_buf[i]); kernel_MCAE_k1[i].setArg(5, output_mat_buf[i]); kernel_MCAE_k1[i].setArg(6, coef_buf[i]); kernel_MCAE_k1[i].setArg(7, calibSamples); kernel_MCAE_k1[i].setArg(8, timeSteps); } for (int c = 0; c < cu_number; ++c) { kernel_MCAE_k2_a[c].setArg(0, seeds[c]); kernel_MCAE_k2_a[c].setArg(1, underlying); kernel_MCAE_k2_a[c].setArg(2, volatility); kernel_MCAE_k2_a[c].setArg(3, dividendYield); kernel_MCAE_k2_a[c].setArg(4, riskFreeRate); kernel_MCAE_k2_a[c].setArg(5, timeLength); kernel_MCAE_k2_a[c].setArg(6, strike); kernel_MCAE_k2_a[c].setArg(7, optionType); kernel_MCAE_k2_a[c].setArg(8, coef_buf[0]); kernel_MCAE_k2_a[c].setArg(9, output_buf_a[c]); kernel_MCAE_k2_a[c].setArg(10, requiredTolerance); kernel_MCAE_k2_a[c].setArg(11, requiredSamples); kernel_MCAE_k2_a[c].setArg(12, timeSteps); kernel_MCAE_k2_b[c].setArg(0, seeds[c]); kernel_MCAE_k2_b[c].setArg(1, underlying); kernel_MCAE_k2_b[c].setArg(2, volatility); kernel_MCAE_k2_b[c].setArg(3, dividendYield); kernel_MCAE_k2_b[c].setArg(4, riskFreeRate); kernel_MCAE_k2_b[c].setArg(5, timeLength); kernel_MCAE_k2_b[c].setArg(6, strike); kernel_MCAE_k2_b[c].setArg(7, optionType); kernel_MCAE_k2_b[c].setArg(8, coef_buf[1]); kernel_MCAE_k2_b[c].setArg(9, output_buf_b[c]); kernel_MCAE_k2_b[c].setArg(10, requiredTolerance); kernel_MCAE_k2_b[c].setArg(11, requiredSamples); kernel_MCAE_k2_b[c].setArg(12, timeSteps); } // number of call for kernel std::vector<std::vector<cl::Event> > evt0(loop_nm); std::vector<std::vector<cl::Event> > evt1(loop_nm); std::vector<std::vector<cl::Event> > evt2(loop_nm); std::vector<std::vector<cl::Event> > evt3(loop_nm); for (int i = 0; i < loop_nm; i++) { evt0[i].resize(1); evt1[i].resize(1); evt2[i].resize(cu_number); evt3[i].resize(1); } std::cout << "kernel start------" << std::endl; q.finish(); gettimeofday(&start_time, 0); for (int i = 0; i < loop_nm; ++i) { // launch kernel and calculate kernel execution time int use_a = i & 1; if (use_a) { if (i < 2) { q.enqueueTask(kernel_MCAE_k0[0], nullptr, &evt0[i][0]); } else { q.enqueueTask(kernel_MCAE_k0[0], &evt3[i - 2], &evt0[i][0]); } q.enqueueTask(kernel_MCAE_k1[0], &evt0[i], &evt1[i][0]); for (int c = 0; c < cu_number; ++c) { q.enqueueTask(kernel_MCAE_k2_a[c], &evt1[i], &evt2[i][c]); } q.enqueueMigrateMemObjects(ob_out, 1, &evt2[i], &evt3[i][0]); } else { if (i < 2) { q.enqueueTask(kernel_MCAE_k0[1], nullptr, &evt0[i][0]); } else { q.enqueueTask(kernel_MCAE_k0[1], &evt3[i - 2], &evt0[i][0]); } q.enqueueTask(kernel_MCAE_k1[1], &evt0[i], &evt1[i][0]); for (int c = 0; c < cu_number; ++c) { q.enqueueTask(kernel_MCAE_k2_b[c], &evt1[i], &evt2[i][c]); } q.enqueueMigrateMemObjects(ob_out_b, 1, &evt2[i], &evt3[i][0]); } } q.flush(); q.finish(); gettimeofday(&end_time, 0); std::cout << "kernel end------" << std::endl; TEST_DT out_price = 0; for (int c = 0; c < cu_number; ++c) { out_price += output_b[c][0]; } if (loop_nm == 1) { out_price = out_price / cu_number; } else { for (int c = 0; c < cu_number; ++c) { out_price += output_a[c][0]; } out_price = out_price / 2 / cu_number; } std::cout << "out_price = " << out_price << std::endl; int exec_time = tvdiff(&start_time, &end_time); double time_elapsed = double(exec_time) / 1000 / 1000; std::cout << "FPGA execution time: " << time_elapsed << " s\n" << "options number: " << loop_nm << " \n" << "opt/sec: " << double(loop_nm) / time_elapsed << std::endl; double diff = std::fabs(out_price - golden_output); if (diff > requiredTolerance) { std::cout << "Output is wrong!" << std::endl; return -1; } #endif return 0; }
37.010417
114
0.595835
Aperture-Electronic
707402dafbf6db8e7e3b3f05a70de164b09eeeea
1,441
hpp
C++
liblumi/include/Matrix.hpp
Rertsyd/LumiRT
d562fd786f769b385bc051e2ea8bcd26162a9dc6
[ "MIT" ]
null
null
null
liblumi/include/Matrix.hpp
Rertsyd/LumiRT
d562fd786f769b385bc051e2ea8bcd26162a9dc6
[ "MIT" ]
null
null
null
liblumi/include/Matrix.hpp
Rertsyd/LumiRT
d562fd786f769b385bc051e2ea8bcd26162a9dc6
[ "MIT" ]
null
null
null
/* ************************************************************************** */ /* ,, */ /* `7MMF' db `7MM"""Mq. MMP""MM""YMM */ /* MM MM `MM.P' MM `7 */ /* MM `7MM `7MM `7MMpMMMb.pMMMb. `7MM MM ,M9 MM */ /* MM MM MM MM MM MM MM MMmmdM9 MM */ /* MM , MM MM MM MM MM MM MM YM. MM */ /* MM ,M MM MM MM MM MM MM MM `Mb. MM */ /* .JMMmmmmMMM `Mbod"YML..JMML JMML JMML..JMML..JMML. .JMM. .JMML. */ /* */ /* ************************************************************************** */ #pragma once #include "Vector.hpp" class Matrix { Vector _mat[3]; static Matrix InitMatRotX(const double rotX); static Matrix InitMatRotY(const double rotY); static Matrix InitMatRotZ(const double rotZ); public: Matrix(); ~Matrix() = default; void InitRotation(const Vector rot); Matrix& operator=(const Matrix& m); Vector& operator [](const uint8_t i); const Vector& operator [](const uint8_t i) const; Vector operator*(const Vector& v) const; Matrix operator*(const Matrix& m) const; //Matrix& operator*=(const Matrix& m); };
36.025
80
0.390007
Rertsyd
7075e1e7e10acf94d09cf6ff48955f05a6a9631f
4,305
cpp
C++
batch/src/v20170312/model/Instance.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
batch/src/v20170312/model/Instance.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
batch/src/v20170312/model/Instance.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/batch/v20170312/model/Instance.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Batch::V20170312::Model; using namespace std; Instance::Instance() : m_instanceIdHasBeenSet(false), m_imageIdHasBeenSet(false), m_loginSettingsHasBeenSet(false) { } CoreInternalOutcome Instance::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("InstanceId") && !value["InstanceId"].IsNull()) { if (!value["InstanceId"].IsString()) { return CoreInternalOutcome(Core::Error("response `Instance.InstanceId` IsString=false incorrectly").SetRequestId(requestId)); } m_instanceId = string(value["InstanceId"].GetString()); m_instanceIdHasBeenSet = true; } if (value.HasMember("ImageId") && !value["ImageId"].IsNull()) { if (!value["ImageId"].IsString()) { return CoreInternalOutcome(Core::Error("response `Instance.ImageId` IsString=false incorrectly").SetRequestId(requestId)); } m_imageId = string(value["ImageId"].GetString()); m_imageIdHasBeenSet = true; } if (value.HasMember("LoginSettings") && !value["LoginSettings"].IsNull()) { if (!value["LoginSettings"].IsObject()) { return CoreInternalOutcome(Core::Error("response `Instance.LoginSettings` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_loginSettings.Deserialize(value["LoginSettings"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_loginSettingsHasBeenSet = true; } return CoreInternalOutcome(true); } void Instance::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_instanceIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "InstanceId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_instanceId.c_str(), allocator).Move(), allocator); } if (m_imageIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ImageId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_imageId.c_str(), allocator).Move(), allocator); } if (m_loginSettingsHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "LoginSettings"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_loginSettings.ToJsonObject(value[key.c_str()], allocator); } } string Instance::GetInstanceId() const { return m_instanceId; } void Instance::SetInstanceId(const string& _instanceId) { m_instanceId = _instanceId; m_instanceIdHasBeenSet = true; } bool Instance::InstanceIdHasBeenSet() const { return m_instanceIdHasBeenSet; } string Instance::GetImageId() const { return m_imageId; } void Instance::SetImageId(const string& _imageId) { m_imageId = _imageId; m_imageIdHasBeenSet = true; } bool Instance::ImageIdHasBeenSet() const { return m_imageIdHasBeenSet; } LoginSettings Instance::GetLoginSettings() const { return m_loginSettings; } void Instance::SetLoginSettings(const LoginSettings& _loginSettings) { m_loginSettings = _loginSettings; m_loginSettingsHasBeenSet = true; } bool Instance::LoginSettingsHasBeenSet() const { return m_loginSettingsHasBeenSet; }
27.774194
137
0.688037
suluner
707741214e08d77199f8244fd2fe89ae5696f21c
587
cpp
C++
src/Actions/Model/ModelDeleteAction.cpp
viveret/script-ai
15f8dc561e55812de034bb729e83ff01bec61743
[ "BSD-3-Clause" ]
null
null
null
src/Actions/Model/ModelDeleteAction.cpp
viveret/script-ai
15f8dc561e55812de034bb729e83ff01bec61743
[ "BSD-3-Clause" ]
null
null
null
src/Actions/Model/ModelDeleteAction.cpp
viveret/script-ai
15f8dc561e55812de034bb729e83ff01bec61743
[ "BSD-3-Clause" ]
null
null
null
#include "../Actions.hpp" #include "../../Program.hpp" #include "../../AIModelAdapter.hpp" #include <iostream> using namespace ScriptAI; ModelDeleteAction::ModelDeleteAction(AIProgram *prog): MenuAction(prog) { } const char* ModelDeleteAction::label() { return "model delete"; } std::string ModelDeleteAction::description() { return "Delete neural network"; } void ModelDeleteAction::run() { if (this->_prog->m_model->exists()) { this->_prog->m_model->delete_model(); std::cout << "Success!" << std::endl; } else { std::cerr << "Model does not exist" << std::endl; } }
20.241379
73
0.678024
viveret
7078a9eb480d1728bbcf836655ee08d8b10f50d7
1,816
cc
C++
scrummer2.cc
alexhairyman/scrummy
e6c0aa72930967895dccda8e5bea3372d9969e1f
[ "MIT" ]
null
null
null
scrummer2.cc
alexhairyman/scrummy
e6c0aa72930967895dccda8e5bea3372d9969e1f
[ "MIT" ]
null
null
null
scrummer2.cc
alexhairyman/scrummy
e6c0aa72930967895dccda8e5bea3372d9969e1f
[ "MIT" ]
1
2019-01-16T16:50:26.000Z
2019-01-16T16:50:26.000Z
/* Copyright (c) 2012 Alex Herrmann alexhairyman@gmail.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "scrummer2.hh" namespace scrum { void FLalertbox(const char* alert) { fl_alert(alert); } // typedef const string propstr; // _win32 = "http://dynamic.scrumbleship.com/system/files/ScrumbleShip-0.14-win-full.zip"; // _lin32 = "http://dynamic.scrumbleship.com/system/files/ScrumbleShip-0.14-lin32-full.zip"; // _lin64 = "http://dynamic.scrumbleship.com/system/files/ScrumbleShip-0.14-lin64-full.zip"; // _src = "http://dynamic.scrumbleship.com/system/files/ScrumbleShip-0.14.1-source.zip"; // _win32_name = "ScrumbleShip-0.14-win-full.zip"; // _lin32_name = "ScrumbleShip-0.14-lin32-full.zip"; // _lin64_name = "ScrumbleShip-0.14-lin64-full.zip"; // _src_name = "ScrumbleShip-0.14.1-source.zip"; }
41.272727
93
0.765419
alexhairyman
707b7103c26594505bd1802695743b3709cca465
4,317
inl
C++
iceoryx_posh/include/iceoryx_posh/internal/runtime/shared_memory_creator.inl
budrus/iceoryx
77c84ae339db8aaedd3b34962474a13272cd59e7
[ "Apache-2.0" ]
1
2020-02-20T23:52:22.000Z
2020-02-20T23:52:22.000Z
iceoryx_posh/include/iceoryx_posh/internal/runtime/shared_memory_creator.inl
michael-poehnl/iceoryx
77c84ae339db8aaedd3b34962474a13272cd59e7
[ "Apache-2.0" ]
null
null
null
iceoryx_posh/include/iceoryx_posh/internal/runtime/shared_memory_creator.inl
michael-poehnl/iceoryx
77c84ae339db8aaedd3b34962474a13272cd59e7
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2019 by Robert Bosch GmbH. 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. namespace iox { namespace runtime { template <typename ShmType> inline SharedMemoryCreator<ShmType>::SharedMemoryCreator(const RouDiConfig_t& config) noexcept { /// @todo these are internal mempool for the introspection, move to a better place mepoo::MePooConfig mempoolConfig; mempoolConfig.m_mempoolConfig.push_back( {static_cast<uint32_t>(cxx::align(sizeof(roudi::MemPoolIntrospectionTopic), 32ul)), 250}); mempoolConfig.m_mempoolConfig.push_back( {static_cast<uint32_t>(cxx::align(sizeof(roudi::ProcessIntrospectionFieldTopic), 32ul)), 10}); mempoolConfig.m_mempoolConfig.push_back( {static_cast<uint32_t>(cxx::align(sizeof(roudi::PortIntrospectionFieldTopic), 32ul)), 10}); mempoolConfig.m_mempoolConfig.push_back( {static_cast<uint32_t>(cxx::align(sizeof(roudi::PortThroughputIntrospectionFieldTopic), 32ul)), 10}); mempoolConfig.optimize(); uint64_t totalSharedMemorySize = ShmType::getRequiredSharedMemory() + mepoo::SegmentManager<>::requiredManagementMemorySize(config) + mepoo::MemoryManager::requiredFullMemorySize(mempoolConfig); auto pageSize = posix::pageSize().value_or(posix::MaxPageSize); // we let the OS decide where to map the shm segments constexpr void* BASE_ADDRESS_HINT{nullptr}; // create and map a shared memory region m_shmObject = posix::SharedMemoryObject::create( SHM_NAME, totalSharedMemorySize, posix::AccessMode::readWrite, posix::OwnerShip::mine, BASE_ADDRESS_HINT); if (!m_shmObject.has_value()) { errorHandler(Error::kPOSH__SHM_BAD_ALLOC); } if (nullptr == m_shmObject->getBaseAddress()) { errorHandler(Error::kPOSH__SHM_ROUDI_MAPP_ERR); } auto managementSegmentId = RelativePointer::registerPtr(m_shmObject->getBaseAddress(), m_shmObject->getSizeInBytes()); LogInfo() << "Roudi registered management segment " << iox::log::HexFormat(reinterpret_cast<uint64_t>(m_shmObject->getBaseAddress())) << " with size " << m_shmObject->getSizeInBytes() << " to id " << managementSegmentId; // now construct our POSH shared memory object m_shmTypePtr = static_cast<ShmType*>(m_shmObject->allocate(sizeof(ShmType))); m_shmTypePtr = new (m_shmTypePtr) ShmType( m_shmObject->getAllocator(), config, cxx::align(reinterpret_cast<uintptr_t>(m_shmObject->getBaseAddress()) + totalSharedMemorySize, pageSize), config.roudi.m_verifySharedMemoryPlacement); m_shmTypePtr->m_segmentId = managementSegmentId; m_shmTypePtr->m_roudiMemoryManager.configureMemoryManager( mempoolConfig, m_shmObject->getAllocator(), m_shmObject->getAllocator()); m_shmObject->finalizeAllocation(); } template <typename ShmType> inline SharedMemoryCreator<ShmType>::~SharedMemoryCreator() noexcept { if (m_shmTypePtr) { m_shmTypePtr->~ShmType(); } } template <typename ShmType> inline std::string SharedMemoryCreator<ShmType>::getBaseAddrString() const noexcept { size_t ptr = reinterpret_cast<size_t>(m_shmObject->getBaseAddress()); return std::to_string(ptr); } template <typename ShmType> inline uint64_t SharedMemoryCreator<ShmType>::getShmSizeInBytes() const noexcept { return m_shmObject->getSizeInBytes(); } template <typename ShmType> inline ShmType* SharedMemoryCreator<ShmType>::getShmInterface() const noexcept { return m_shmTypePtr; } template <typename ShmType> inline uint64_t SharedMemoryCreator<ShmType>::getSegmentId() const noexcept { return m_shmTypePtr->m_segmentId; } } // namespace runtime } // namespace iox
37.53913
114
0.726199
budrus
707d1f44fcaf490c374f380c4a3ed254471773ec
872
cpp
C++
test/classwork_test/03_assign_test/decisions_tests.cpp
acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-Irvingperez
52f01b57eea81445f5ef13325969a8a1bd868c50
[ "MIT" ]
null
null
null
test/classwork_test/03_assign_test/decisions_tests.cpp
acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-Irvingperez
52f01b57eea81445f5ef13325969a8a1bd868c50
[ "MIT" ]
null
null
null
test/classwork_test/03_assign_test/decisions_tests.cpp
acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-Irvingperez
52f01b57eea81445f5ef13325969a8a1bd868c50
[ "MIT" ]
null
null
null
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file #include "catch.hpp" //#include "loops.h" #include "decision.h" TEST_CASE("Verify Test Configuration", "verification") { REQUIRE(true == true); } TEST_CASE("Verify Test Configuration for IF function ") { REQUIRE(get_letter_grade_using_if(95) == "A"); REQUIRE(get_letter_grade_using_if(85) == "B"); REQUIRE(get_letter_grade_using_if(75) == "C"); REQUIRE(get_letter_grade_using_if(65) == "D"); REQUIRE(get_letter_grade_using_if(50) == "F"); } TEST_CASE("Verify Test Configuration for SWITCH function ") { REQUIRE(get_letter_grade_using_switch(95) == "A"); REQUIRE(get_letter_grade_using_switch(80) == "B"); REQUIRE(get_letter_grade_using_switch(70) == "C"); REQUIRE(get_letter_grade_using_switch(60) == "D"); REQUIRE(get_letter_grade_using_switch(40) == "F"); }
32.296296
97
0.733945
acc-cosc-1337-fall-2020
707e28817fd4752255ed94a3c57620a50c5e75e6
1,376
hpp
C++
viennacl/device_specific/builtin_database/matrix_axpy.hpp
denis14/ViennaCL-1.5.2
fec808905cca30196e10126681611bdf8da5297a
[ "MIT" ]
null
null
null
viennacl/device_specific/builtin_database/matrix_axpy.hpp
denis14/ViennaCL-1.5.2
fec808905cca30196e10126681611bdf8da5297a
[ "MIT" ]
null
null
null
viennacl/device_specific/builtin_database/matrix_axpy.hpp
denis14/ViennaCL-1.5.2
fec808905cca30196e10126681611bdf8da5297a
[ "MIT" ]
null
null
null
#ifndef VIENNACL_DEVICE_SPECIFIC_BUILTIN_DATABASE_MATRIX_AXPY_HPP_ #define VIENNACL_DEVICE_SPECIFIC_BUILTIN_DATABASE_MATRIX_AXPY_HPP_ #include "viennacl/ocl/device_utils.hpp" #include "viennacl/scheduler/forwards.h" #include "viennacl/device_specific/forwards.h" #include "viennacl/device_specific/builtin_database/common.hpp" #include "viennacl/device_specific/builtin_database/devices/accelerator/fallback.hpp" #include "viennacl/device_specific/builtin_database/devices/cpu/fallback.hpp" #include "viennacl/device_specific/builtin_database/devices/gpu/fallback.hpp" namespace viennacl { namespace device_specific { namespace builtin_database { inline database_type<matrix_axpy_template::parameters_type> init_matrix_axpy() { database_type<matrix_axpy_template::parameters_type> result; devices::accelerator::fallback::add_4B(result); devices::accelerator::fallback::add_8B(result); devices::cpu::fallback::add_4B(result); devices::cpu::fallback::add_8B(result); devices::gpu::fallback::add_4B(result); devices::gpu::fallback::add_8B(result); return result; } static database_type<matrix_axpy_template::parameters_type> matrix_axpy = init_matrix_axpy(); template<class NumericT> matrix_axpy_template::parameters_type const & matrix_axpy_params(ocl::device const & device) { return get_parameters<NumericT>(matrix_axpy, device); } } } } #endif
27.52
93
0.817587
denis14
708187f2f61e57848314f089193d38abe44b82e9
8,542
cpp
C++
src/Test_binaryCompare.cpp
leekt216/HElib
d2700ba62d2399213b5293686e715d01ad65e6c0
[ "Apache-2.0" ]
1
2022-02-14T02:37:58.000Z
2022-02-14T02:37:58.000Z
homomorphic_evaluation/lib/helib_pack/src/test/Test_binaryCompare.cpp
dklee0501/Lobster
f2b73df9165c76e8b521d8ebd639d68321e3862b
[ "MIT" ]
1
2017-05-16T09:26:15.000Z
2017-05-16T09:26:15.000Z
homomorphic_evaluation/lib/helib_pack/src/test/Test_binaryCompare.cpp
dklee0501/Lobster
f2b73df9165c76e8b521d8ebd639d68321e3862b
[ "MIT" ]
2
2019-02-01T11:34:34.000Z
2021-11-27T14:49:27.000Z
/* Copyright (C) 2012-2017 IBM Corp. * This program is 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. See accompanying LICENSE file. */ #include <iostream> #include <cassert> #include <fstream> #include <vector> #include <cmath> #include <algorithm> #include <NTL/BasicThreadPool.h> NTL_CLIENT #include "EncryptedArray.h" #include "FHE.h" #include "intraSlot.h" #include "binaryArith.h" #include "binaryCompare.h" #ifdef DEBUG_PRINTOUT #include "debugging.h" #endif // define flags FLAG_PRINT_ZZX, FLAG_PRINT_POLY, FLAG_PRINT_VEC, functions // decryptAndPrint(ostream, ctxt, sk, ea, flags) // decryptAndCompare(ctxt, sk, ea, pa); static std::vector<zzX> unpackSlotEncoding; // a global variable static bool verbose=false; static long mValues[][15] = { // { p, phi(m), m, d, m1, m2, m3, g1, g2, g3, ord1,ord2,ord3, B,c} { 2, 48, 105, 12, 3, 35, 0, 71, 76, 0, 2, 2, 0, 25, 2}, { 2 , 600, 1023, 10, 11, 93, 0, 838, 584, 0, 10, 6, 0, 25, 2}, { 2, 2304, 4641, 24, 7, 3,221, 3979, 3095, 3760, 6, 2, -8, 25, 3}, { 2, 15004, 15709, 22, 23,683, 0, 4099, 13663, 0, 22, 31, 0, 25, 3}, { 2, 27000, 32767, 15, 31, 7, 151, 11628, 28087,25824, 30, 6, -10, 28, 4} }; void testCompare(FHESecKey& secKey, long bitSize, bool bootstrap=false); int main(int argc, char *argv[]) { ArgMapping amap; long prm=1; amap.arg("prm", prm, "parameter size (0-tiny,...,4-huge)"); long bitSize = 5; amap.arg("bitSize", bitSize, "bitSize of input integers (<=32)"); long nTests = 3; amap.arg("nTests", nTests, "number of tests to run"); bool bootstrap = false; amap.arg("bootstrap", bootstrap, "test comparison with bootstrapping"); long seed=0; amap.arg("seed", seed, "PRG seed"); long nthreads=1; amap.arg("nthreads", nthreads, "number of threads"); amap.arg("verbose", verbose, "print more information"); amap.parse(argc, argv); assert(prm >= 0 && prm < 5); if (seed) NTL::SetSeed(ZZ(seed)); if (nthreads>1) NTL::SetNumThreads(nthreads); if (bitSize<=0) bitSize=5; else if (bitSize>32) bitSize=32; long* vals = mValues[prm]; long p = vals[0]; // long phim = vals[1]; long m = vals[2]; NTL::Vec<long> mvec; append(mvec, vals[4]); if (vals[5]>1) append(mvec, vals[5]); if (vals[6]>1) append(mvec, vals[6]); std::vector<long> gens; gens.push_back(vals[7]); if (vals[8]>1) gens.push_back(vals[8]); if (vals[9]>1) gens.push_back(vals[9]); std::vector<long> ords; ords.push_back(vals[10]); if (abs(vals[11])>1) ords.push_back(vals[11]); if (abs(vals[12])>1) ords.push_back(vals[12]); long B = vals[13]; long c = vals[14]; // Compute the number of levels long L; if (bootstrap) L = 900; // that should be enough else L = 30*(7+ NTL::NumBits(bitSize+2)); if (verbose) { cout <<"input bitSize="<<bitSize <<", running "<<nTests<<" tests for each function\n"; if (nthreads>1) cout << " using "<<NTL::AvailableThreads()<<" threads\n"; cout << "computing key-independent tables..." << std::flush; } FHEcontext context(m, p, /*r=*/1, gens, ords); buildModChain(context, L, c,/*willBeBootstrappable=*/bootstrap); if (bootstrap) { context.makeBootstrappable(mvec, /*t=*/0); } buildUnpackSlotEncoding(unpackSlotEncoding, *context.ea); if (verbose) { cout << " done.\n"; context.zMStar.printout(); cout << " L="<<L<<", B="<<B<<endl; cout << "\ncomputing key-dependent tables..." << std::flush; } FHESecKey secKey(context); secKey.GenSecKey(); addSome1DMatrices(secKey); // compute key-switching matrices addFrbMatrices(secKey); if (bootstrap) secKey.genRecryptData(); if (verbose) cout << " done\n"; activeContext = &context; // make things a little easier sometimes #ifdef DEBUG_PRINTOUT dbgEa = (EncryptedArray*) context.ea; dbgKey = &secKey; #endif for (long i=0; i<nTests; i++) testCompare(secKey, bitSize, bootstrap); cout << "GOOD\n"; if (verbose) printAllTimers(cout); return 0; } void testCompare(FHESecKey& secKey, long bitSize, bool bootstrap) { const FHEcontext& context = secKey.getContext(); const EncryptedArray& ea = *(context.ea); // Choose two random n-bit integers long pa = RandomBits_long(bitSize); long pb = RandomBits_long(bitSize+1); long pMax = std::max(pa,pb); long pMin = std::min(pa,pb); bool pMu = pa>pb; bool pNi = pa<pb; // Encrypt the individual bits NTL::Vec<Ctxt> eMax, eMin, enca, encb; Ctxt mu(secKey), ni(secKey); resize(enca, bitSize, mu); resize(encb, bitSize+1, ni); for (long i=0; i<=bitSize; i++) { if (i<bitSize) secKey.Encrypt(enca[i], ZZX((pa>>i)&1)); secKey.Encrypt(encb[i], ZZX((pb>>i)&1)); if (bootstrap) { // put them at a lower level if (i<bitSize) enca[i].bringToSet(context.getCtxtPrimes(5)); encb[i].bringToSet(context.getCtxtPrimes(5)); } } #ifdef DEBUG_PRINTOUT decryptAndPrint((cout<<" before comparison: "), encb[0], secKey, ea,0); #endif vector<long> slotsMin, slotsMax, slotsMu, slotsNi; //cmp only compareTwoNumbers(mu, ni, CtPtrs_VecCt(enca), CtPtrs_VecCt(encb), &unpackSlotEncoding); ea.decrypt(mu, secKey, slotsMu); ea.decrypt(ni, secKey, slotsNi); if (slotsMu[0]!=pMu || slotsNi[0]!=pNi) { cout << "BAD\n"; if (verbose) cout << "Comparison (without min max) error: a="<<pa<<", b="<<pb << ", mu="<<slotsMu[0]<<", ni="<<slotsNi[0]<<endl; exit(0); } else if (verbose) { cout << "Comparison (without min max) succeeded: "; cout << '('<<pa<<','<<pb<<")=> mu="<<slotsMu[0]<<", ni="<<slotsNi[0]<<endl; } {CtPtrs_VecCt wMin(eMin), wMax(eMax); // A wrappers around output vectors //cmp with max and min compareTwoNumbers(wMax, wMin, mu, ni, CtPtrs_VecCt(enca), CtPtrs_VecCt(encb), &unpackSlotEncoding); decryptBinaryNums(slotsMax, wMax, secKey, ea); decryptBinaryNums(slotsMin, wMin, secKey, ea); } // get rid of the wrapper ea.decrypt(mu, secKey, slotsMu); ea.decrypt(ni, secKey, slotsNi); if (slotsMax[0]!=pMax || slotsMin[0]!=pMin || slotsMu[0]!=pMu || slotsNi[0]!=pNi) { cout << "BAD\n"; if (verbose) cout << "Comparison (with min max) error: a="<<pa<<", b="<<pb << ", but min="<<slotsMin[0]<<", max="<<slotsMax[0] << ", mu="<<slotsMu[0]<<", ni="<<slotsNi[0]<<endl; exit(0); } else if (verbose) { cout << "Comparison (with min max) succeeded: "; cout << '('<<pa<<','<<pb<<")=>("<<slotsMin[0]<<','<<slotsMax[0] <<"), mu="<<slotsMu[0]<<", ni="<<slotsNi[0]<<endl; } #ifdef DEBUG_PRINTOUT const Ctxt* minLvlCtxt = nullptr; long minLvl=1000; for (const Ctxt& c: eMax) { long lvl = c.findBaseLevel(); if (lvl < minLvl) { minLvlCtxt = &c; minLvl = lvl; } } decryptAndPrint((cout<<" after comparison: "), *minLvlCtxt, secKey, ea,0); cout << endl; #endif } #if 0 e2=a2+b2+1 e1=a1+b1+1 e0=a0+b0+1, ne0 = a0+b0 e*2 = e2 e*1 = e2 e1 e*0 = e*1 e0, ne*0 = e*1 ne0 a*2 = a2 , b*2 = b2 a*1 = e2 a1 , b*1 = e*1 -e2 - a*1 a*0 = e*1 a0, b*0 = ne*0 -a*0 c2 = a2 b2 c1 = a1 b1 c0 = a0 b0 c*2 = c2 c*1 = e2 c1 c*0 = e*1 c0 A2 = a2, B2 = b2, C2 = c2 A1 = a2 +a*1, B1 = b2 +b*1, C1 = c2 + c*1 A0 = A1 +a*0, B0 = B1 +b*0, C0 = C1 + c*0 (a>b) = A0+C0 (a<b) = B0+C0 mx2 = a2+b2+c2 mx1 = a*1+b*1+c1 + a1(a2+c2) + b1(b2+c) X ab01 = b1 a0 X b10 = b1 b0 mx0 = a0+b0+c*0 + a0(A1+C1) = a0 A1 + a0(c*2 +a*1 b1) = a0(A1+c*2) + a*1 ab01 + b0(B1+C1) = b0 B1 + b0(c*2 +a*1 b1) = b0(B1+c*2) + a*1 b10 = a0(1+A1+c*2) + b0(1+B1+c*2) + a*1(b10+ab01) + c*0 mn0 = c0 + a0(B1+C1) = a0 B1 + a0(c*2 +a*1 b1) = a0(B1+c*2) + a*1 ab01 + b0(A1+C1) = b0 A1 + b0(c*2 +a*1 b1) = b0(A1+c*2) + a*1 b10 = a0(B1+c*2) + b0(A1+C*2) + a*1(b10 + ab01) + c*0 e20 = e2 ne0 a*1(b10+ab01)=(a2+b2+1)a1 b1(a0+b0) = e20 c1 mx0 = a0(1+A1+c*2) + b0(1+B1+c*2) + e20 c1 + c*0 mn0 = a0(B1+c*2) + b0(A1+c*2) + e20 c1 + c*0 #endif
29.659722
79
0.602552
leekt216
7088c3ce3731cd3b803ead4fb5e4c790e4826711
4,341
hpp
C++
include/synthizer/spatialization_math.hpp
wiresong/synthizer
d6fb7a5f9eb0c5760411eee29b12a10fdd7ad420
[ "Unlicense" ]
25
2020-09-05T18:21:21.000Z
2021-12-05T02:47:42.000Z
include/synthizer/spatialization_math.hpp
wiresong/synthizer
d6fb7a5f9eb0c5760411eee29b12a10fdd7ad420
[ "Unlicense" ]
77
2020-07-08T23:33:46.000Z
2022-03-19T05:34:26.000Z
include/synthizer/spatialization_math.hpp
wiresong/synthizer
d6fb7a5f9eb0c5760411eee29b12a10fdd7ad420
[ "Unlicense" ]
9
2020-07-08T18:16:53.000Z
2022-03-02T21:35:28.000Z
#pragma once #include "synthizer_constants.h" #include <array> #include <cmath> namespace synthizer { struct DistanceParams { /* Distance is set by the user. */ double distance = 0.0; double distance_ref = 1.0; double distance_max = 50.0; double rolloff = 1.0; double closeness_boost = 0.0; double closeness_boost_distance = 0.0; enum SYZ_DISTANCE_MODEL distance_model = SYZ_DISTANCE_MODEL_LINEAR; /* records whether or not we think that this set of parameters has changed. Used when materializing from properties. */ bool changed = false; }; /* * These templates materialize and/or set properties on anything with all of the properties for distance models. * * They're not instance methods because the distance model struct itself will probably become public as part of being * able to configure effect sends. * */ template <typename T> DistanceParams materializeDistanceParamsFromProperties(T *source) { DistanceParams ret; int distance_model; ret.changed = source->acquireDistanceRef(ret.distance_ref) | source->acquireDistanceMax(ret.distance_max) | source->acquireRolloff(ret.rolloff) | source->acquireClosenessBoost(ret.closeness_boost) | source->acquireClosenessBoostDistance(ret.closeness_boost_distance) | /* This one needs a cast, so pull it to a different vairable first. */ source->acquireDistanceModel(distance_model); ret.distance_model = (enum SYZ_DISTANCE_MODEL)distance_model; return ret; } /** * Used on e.g. contexts, to build one from defaults. * */ template <typename T> DistanceParams materializeDistanceParamsFromDefaultProperties(T *source) { DistanceParams ret; int distance_model; ret.changed = source->acquireDefaultDistanceRef(ret.distance_ref) | source->acquireDefaultDistanceMax(ret.distance_max) | source->acquireDefaultRolloff(ret.rolloff) | source->acquireDefaultClosenessBoost(ret.closeness_boost) | source->acquireDefaultClosenessBoostDistance(ret.closeness_boost_distance) | /* This one needs a cast, so pull it to a different vairable first. */ source->acquireDefaultDistanceModel(distance_model); ret.distance_model = (enum SYZ_DISTANCE_MODEL)distance_model; return ret; } template <typename T> void setPropertiesFromDistanceParams(T *dest, const DistanceParams &&params) { dest->setDistanceRef(params.distance_ref); dest->setDistanceMax(params.distance_max); dest->setRolloff(params.rolloff); dest->setClosenessBoost(params.closeness_boost); dest->setClosenessBoostDistance(params.closeness_boost_distance); dest->setDistanceModel((int)params.distance_model); } double mulFromDistanceParams(const DistanceParams &params); /* * Helper class which can be used to augment anything with a distance model, with Synthizer-compatible property * getter/setter pairs. * * How this works is you inherit from it somewhere in the hierarchy, then define properties as usual * */ class DistanceParamsMixin { public: DistanceParams &getDistanceParams(); void setDistanceParams(const DistanceParams &params); double getDistanceRef(); void setDistanceRef(double val); double getDistanceMax(); void setDistanceMax(double val); double getRolloff(); void setRolloff(double val); double getClosenessBoost(); void setClosenessBoost(double val); double getClosenessBoostDistance(); void setClosenessBoostDistance(double val); int getDistanceModel(); void setDistanceModel(int val); private: DistanceParams distance_params{}; }; typedef std::array<double, 3> Vec3d; inline double dotProduct(const Vec3d &a, const Vec3d &b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; } inline Vec3d crossProduct(const Vec3d &a, const Vec3d &b) { return { a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0], }; } inline double magnitude(const Vec3d &x) { return std::sqrt(x[0] * x[0] + x[1] * x[1] + x[2] * x[2]); } inline double distance(const Vec3d &a, const Vec3d &b) { return magnitude({a[0] - b[0], a[1] - b[1], a[2] - b[2]}); } inline Vec3d normalize(const Vec3d &x) { double m = magnitude(x); return {x[0] / m, x[1] / m, x[2] / m}; } void throwIfParallel(const Vec3d &a, const Vec3d &b); } // namespace synthizer
35.008065
118
0.717807
wiresong
708af932cf1a554ad106f91001d5c3861ee3a3ba
1,371
cpp
C++
src/SFML View/Core/VerticalLayout.cpp
BenPyton/2D-Dungeon-Generator
87d68926a72a73442e8355f7024154b403b8fd71
[ "MIT" ]
7
2019-01-24T07:48:19.000Z
2022-02-14T03:31:22.000Z
src/SFML View/Core/VerticalLayout.cpp
BenPyton/2D-Dungeon-Generator
87d68926a72a73442e8355f7024154b403b8fd71
[ "MIT" ]
null
null
null
src/SFML View/Core/VerticalLayout.cpp
BenPyton/2D-Dungeon-Generator
87d68926a72a73442e8355f7024154b403b8fd71
[ "MIT" ]
2
2019-01-24T07:11:48.000Z
2022-02-14T03:31:23.000Z
/* * @author PELLETIER Benoit * * @file VerticalLayout.cpp * * @date 02/11/2018 * * @brief Define a vertical flow for ui * */ #include "stdafx.h" #include "VerticalLayout.h" VerticalLayout::VerticalLayout(int x, int y, int width, int height) : Layout(x, y, width, height), m_paddingLeft(0), m_paddingRight(0), m_paddingTop(0), m_paddingBottom(0), m_spacing(0) { } VerticalLayout::~VerticalLayout() { } void VerticalLayout::setPaddings(float left, float right, float top, float bottom) { m_paddingLeft = left; m_paddingRight = right; m_paddingTop = top; m_paddingBottom = bottom; } void VerticalLayout::getPaddings(float & left, float & right, float & top, float & bottom) { left = m_paddingLeft; right = m_paddingRight; top = m_paddingTop; bottom = m_paddingBottom; } void VerticalLayout::update() { // update first all children Layout::update(); // override their positions float yoffset = m_paddingTop; for (list<AbstractUI*>::iterator it = m_children.begin(); it != m_children.end(); ++it) { AbstractUI* ui = *it; ui->setPosition(sf::Vector2f(0, yoffset)); yoffset += m_spacing + ui->getSize().y; ui->setMargins(m_paddingLeft, m_paddingRight, 0, 0); ui->setAnchorMin(sf::Vector2f(0, 0)); ui->setAnchorMax(sf::Vector2f(1, 0)); //ui->setSize(sf::Vector2f(m_rect->getSize().x - m_paddingLeft - m_paddingRight, ui->getSize().y)); } }
23.237288
118
0.701678
BenPyton
708ca709e71a6db75d63e484922cca41ceb04d56
4,800
cc
C++
src/Serial.cc
bakterian/arduino-mock
e59117bd75d4e3f05f86249f70e8cea356b527ef
[ "0BSD" ]
40
2015-02-03T03:51:06.000Z
2022-03-22T11:42:48.000Z
src/Serial.cc
bakterian/arduino-mock
e59117bd75d4e3f05f86249f70e8cea356b527ef
[ "0BSD" ]
14
2015-01-01T04:08:19.000Z
2017-02-26T19:49:22.000Z
src/Serial.cc
bakterian/arduino-mock
e59117bd75d4e3f05f86249f70e8cea356b527ef
[ "0BSD" ]
43
2015-01-21T05:45:18.000Z
2022-01-31T14:08:30.000Z
// Copyright 2014 http://switchdevice.com #include "arduino-mock/Serial.h" static SerialMock* gSerialMock = NULL; SerialMock* serialMockInstance() { if(!gSerialMock) { gSerialMock = new SerialMock(); } return gSerialMock; } void releaseSerialMock() { if(gSerialMock) { delete gSerialMock; gSerialMock = NULL; } } // Serial.print(78, BIN) gives "1001110" // Serial.print(78, OCT) gives "116" // Serial.print(78, DEC) gives "78" // Serial.print(78, HEX) gives "4E" // Serial.println(1.23456, 0) gives "1" // Serial.println(1.23456, 2) gives "1.23" // Serial.println(1.23456, 4) gives "1.2346" void printDouble(double num, int digits) { std::streamsize ss = std::cout.precision(); std::cout << std::setprecision(digits) << std::fixed << num; std::cout.unsetf(std::ios::fixed); std::cout.precision (ss); } template<typename T> void printBase(T num, int base) { switch (base) { case BIN: assert (! "Need to implement this"); break; case OCT: std::cout << std::oct; break; case DEC: std::cout << std::dec; break; case HEX: std::cout << std::hex; break; } std::cout << num << std::dec; } bool Serial_::printToCout = false; void Serial_::setPrintToCout(bool flag) { printToCout = flag; } size_t Serial_::print(const char *s) { if (printToCout) { std::cout << s; return 0; } assert (gSerialMock != NULL); return gSerialMock->print(s); } size_t Serial_::print(char c) { if (printToCout) { std::cout << c; return 0; } assert (gSerialMock != NULL); return gSerialMock->print(c); } size_t Serial_::print(unsigned char c, int base) { if (printToCout) { printBase(c, base); return 0; } assert (gSerialMock != NULL); return gSerialMock->print(c, base); } size_t Serial_::print(int num, int base) { if (printToCout) { printBase(num, base); return 0; } assert (gSerialMock != NULL); return gSerialMock->print(num, base); } size_t Serial_::print(unsigned int num, int base) { if (printToCout) { printBase(num, base); return 0; } assert (gSerialMock != NULL); return gSerialMock->print(num, base); } size_t Serial_::print(long num, int base) { if (printToCout) { printBase(num, base); return 0; } assert (gSerialMock != NULL); return gSerialMock->print(num, base); } size_t Serial_::print(unsigned long num, int base) { if (printToCout) { printBase(num, base); return 0; } assert (gSerialMock != NULL); return gSerialMock->print(num, base); } size_t Serial_::print(double num, int digits) { if (printToCout) { printDouble(num, digits); return 0; } assert (gSerialMock != NULL); return gSerialMock->print(num, digits); } size_t Serial_::println(const char *s) { if (printToCout) { std::cout << s << std::endl; return 0; } assert (gSerialMock != NULL); return gSerialMock->println(s); } size_t Serial_::println(char c) { if (printToCout) { std::cout << c << std::endl; return 0; } assert (gSerialMock != NULL); return gSerialMock->println(c); } size_t Serial_::println(unsigned char c, int base) { assert (gSerialMock != NULL); return gSerialMock->println(c, base); } size_t Serial_::println(int num, int base) { assert (gSerialMock != NULL); return gSerialMock->println(num, base); } size_t Serial_::println(unsigned int num, int base) { assert (gSerialMock != NULL); return gSerialMock->println(num, base); } size_t Serial_::println(long num, int base) { assert (gSerialMock != NULL); return gSerialMock->println(num, base); } size_t Serial_::println(unsigned long num, int base) { assert (gSerialMock != NULL); return gSerialMock->println(num, base); } size_t Serial_::println(double num, int digits) { assert (gSerialMock != NULL); return gSerialMock->println(num, digits); } size_t Serial_::println(void) { if (printToCout) { std::cout << std::endl; return 0; } assert (gSerialMock != NULL); return gSerialMock->println(); } size_t Serial_::write(uint8_t val) { assert (gSerialMock != NULL); return gSerialMock->write(val); } size_t Serial_::write(const char *str) { assert (gSerialMock != NULL); return gSerialMock->write(str); } size_t Serial_::write(const uint8_t *buffer, size_t size) { assert (gSerialMock != NULL); return gSerialMock->write(buffer, size); } uint8_t Serial_::begin(uint32_t port) { assert (gSerialMock != NULL); return gSerialMock->begin(port); } void Serial_::flush() { assert (gSerialMock != NULL); return gSerialMock->flush(); } uint8_t Serial_::available() { assert (gSerialMock != NULL); return gSerialMock->available(); } uint8_t Serial_::read() { assert (gSerialMock != NULL); return gSerialMock->read(); } // Preinstantiate Objects Serial_ Serial;
21.333333
62
0.6575
bakterian
708f03c56398af90c7955dac56cb807b4eace1e6
1,216
hpp
C++
include/codegen/include/UnityEngine/UILineInfo.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/UnityEngine/UILineInfo.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/UnityEngine/UILineInfo.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:37 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes // Including type: System.ValueType #include "System/ValueType.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Completed forward declares // Type namespace: UnityEngine namespace UnityEngine { // Autogenerated type: UnityEngine.UILineInfo struct UILineInfo : public System::ValueType { public: // public System.Int32 startCharIdx // Offset: 0x0 int startCharIdx; // public System.Int32 height // Offset: 0x4 int height; // public System.Single topY // Offset: 0x8 float topY; // public System.Single leading // Offset: 0xC float leading; // Creating value type constructor for type: UILineInfo UILineInfo(int startCharIdx_ = {}, int height_ = {}, float topY_ = {}, float leading_ = {}) : startCharIdx{startCharIdx_}, height{height_}, topY{topY_}, leading{leading_} {} }; // UnityEngine.UILineInfo } DEFINE_IL2CPP_ARG_TYPE(UnityEngine::UILineInfo, "UnityEngine", "UILineInfo"); #pragma pack(pop)
33.777778
177
0.666118
Futuremappermydud
709067c1afb446c2fbf1b1ad263e4c530a40ac95
476
cpp
C++
aoj/ITP1_10_B.cpp
yu3mars/proconcpp
f951a8612e542b4ae974e61671dfff64f73ba3f0
[ "MIT" ]
null
null
null
aoj/ITP1_10_B.cpp
yu3mars/proconcpp
f951a8612e542b4ae974e61671dfff64f73ba3f0
[ "MIT" ]
null
null
null
aoj/ITP1_10_B.cpp
yu3mars/proconcpp
f951a8612e542b4ae974e61671dfff64f73ba3f0
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define REP(i,n) for(int i=0;i<(int)(n);i++) #define ALL(x) (x).begin(),(x).end() typedef long long ll; typedef long double ld; // const ld eps = 1e-12, const ld pi = acos(-1.0); // const ll inf = 1e12; using namespace std; int main() { double a,b,c,s,l,h; cin >> a>>b>>c; c = c*pi/180; s = a*b*sin(c)/2; l =a+b+sqrt(pow(a*sin(c),2)+pow(b-a*cos(c),2)); h = b*sin(c); cout <<fixed<<setprecision(8)<<s<< " "<<l<< " "<<h<<endl; return 0; }
19.833333
58
0.556723
yu3mars
70950e4fa8a4929c6cc1a81327a4540faf997af4
6,904
cpp
C++
cocos2d/cocos/audio/android/PcmAudioService.cpp
otakuidoru/Connect
bcbc6d790c956fad435547c9484ea8fd6e5f794f
[ "MIT" ]
141
2019-07-09T06:29:35.000Z
2022-03-30T06:25:16.000Z
cocos2d/cocos/audio/android/PcmAudioService.cpp
otakuidoru/Connect
bcbc6d790c956fad435547c9484ea8fd6e5f794f
[ "MIT" ]
16
2019-12-23T06:53:18.000Z
2021-10-19T17:01:01.000Z
cocos2d/cocos/audio/android/PcmAudioService.cpp
otakuidoru/Connect
bcbc6d790c956fad435547c9484ea8fd6e5f794f
[ "MIT" ]
47
2019-08-14T11:12:34.000Z
2022-03-30T06:25:19.000Z
/**************************************************************************** Copyright (c) 2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #define LOG_TAG "PcmAudioService" #include "audio/android/PcmAudioService.h" #include "audio/android/AudioMixerController.h" namespace cocos2d { static std::vector<char> __silenceData; #define AUDIO_PLAYER_BUFFER_COUNT (2) class SLPcmAudioPlayerCallbackProxy { public: static void samplePlayerCallback(SLAndroidSimpleBufferQueueItf bq, void *context) { PcmAudioService *thiz = reinterpret_cast<PcmAudioService *>(context); thiz->bqFetchBufferCallback(bq); } }; PcmAudioService::PcmAudioService(SLEngineItf engineItf, SLObjectItf outputMixObject) : _engineItf(engineItf), _outputMixObj(outputMixObject), _playObj(nullptr), _playItf(nullptr), _volumeItf(nullptr), _bufferQueueItf(nullptr), _numChannels(-1), _sampleRate(-1), _bufferSizeInBytes(0), _controller(nullptr), _isInitialised(false) { } PcmAudioService::~PcmAudioService() { ALOGV("PcmAudioServicee() (%p), before destroy play object", this); SL_DESTROY_OBJ(_playObj); ALOGV("PcmAudioServicee() end"); } bool PcmAudioService::enqueue() { if (_controller->hasPlayingTacks()) { if (_controller->isPaused()) { SLresult r = (*_bufferQueueItf)->Enqueue(_bufferQueueItf, __silenceData.data(), __silenceData.size()); SL_RETURN_VAL_IF_FAILED(r, false, "enqueue silent data failed!"); } else { _controller->mixOneFrame(); auto current = _controller->current(); ALOG_ASSERT(current != nullptr, "current buffer is nullptr ..."); SLresult r = (*_bufferQueueItf)->Enqueue(_bufferQueueItf, current->buf, current->size); SL_RETURN_VAL_IF_FAILED(r, false, "enqueue failed!"); } } else { SLresult r = (*_bufferQueueItf)->Enqueue(_bufferQueueItf, __silenceData.data(), __silenceData.size()); SL_RETURN_VAL_IF_FAILED(r, false, "enqueue silent data failed!"); } return true; } void PcmAudioService::bqFetchBufferCallback(SLAndroidSimpleBufferQueueItf bq) { // FIXME: PcmAudioService instance may be destroyed, we need to find a way to wait... // It's in sub thread enqueue(); } bool PcmAudioService::init(AudioMixerController* controller, int numChannels, int sampleRate, int bufferSizeInBytes) { _controller = controller; _numChannels = numChannels; _sampleRate = sampleRate; _bufferSizeInBytes = bufferSizeInBytes; SLuint32 channelMask = SL_SPEAKER_FRONT_CENTER; if (numChannels > 1) { channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT; } SLDataFormat_PCM formatPcm = { SL_DATAFORMAT_PCM, (SLuint32) numChannels, (SLuint32) sampleRate * 1000, SL_PCMSAMPLEFORMAT_FIXED_16, SL_PCMSAMPLEFORMAT_FIXED_16, channelMask, SL_BYTEORDER_LITTLEENDIAN }; SLDataLocator_AndroidSimpleBufferQueue locBufQueue = { SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, AUDIO_PLAYER_BUFFER_COUNT }; SLDataSource source = {&locBufQueue, &formatPcm}; SLDataLocator_OutputMix locOutmix = { SL_DATALOCATOR_OUTPUTMIX, _outputMixObj }; SLDataSink sink = {&locOutmix, nullptr}; const SLInterfaceID ids[] = { SL_IID_PLAY, SL_IID_VOLUME, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, }; const SLboolean req[] = { SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE, }; SLresult r; r = (*_engineItf)->CreateAudioPlayer(_engineItf, &_playObj, &source, &sink, sizeof(ids) / sizeof(ids[0]), ids, req); SL_RETURN_VAL_IF_FAILED(r, false, "CreateAudioPlayer failed"); r = (*_playObj)->Realize(_playObj, SL_BOOLEAN_FALSE); SL_RETURN_VAL_IF_FAILED(r, false, "Realize failed"); r = (*_playObj)->GetInterface(_playObj, SL_IID_PLAY, &_playItf); SL_RETURN_VAL_IF_FAILED(r, false, "GetInterface SL_IID_PLAY failed"); r = (*_playObj)->GetInterface(_playObj, SL_IID_VOLUME, &_volumeItf); SL_RETURN_VAL_IF_FAILED(r, false, "GetInterface SL_IID_VOLUME failed"); r = (*_playObj)->GetInterface(_playObj, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &_bufferQueueItf); SL_RETURN_VAL_IF_FAILED(r, false, "GetInterface SL_IID_ANDROIDSIMPLEBUFFERQUEUE failed"); r = (*_bufferQueueItf)->RegisterCallback(_bufferQueueItf, SLPcmAudioPlayerCallbackProxy::samplePlayerCallback, this); SL_RETURN_VAL_IF_FAILED(r, false, "_bufferQueueItf RegisterCallback failed"); if (__silenceData.empty()) { __silenceData.resize(_numChannels * _bufferSizeInBytes, 0x00); } r = (*_bufferQueueItf)->Enqueue(_bufferQueueItf, __silenceData.data(), __silenceData.size()); SL_RETURN_VAL_IF_FAILED(r, false, "_bufferQueueItf Enqueue failed"); r = (*_playItf)->SetPlayState(_playItf, SL_PLAYSTATE_PLAYING); SL_RETURN_VAL_IF_FAILED(r, false, "SetPlayState failed"); _isInitialised = true; return true; } void PcmAudioService::pause() { if (_isInitialised) { SLresult r = (*_playItf)->SetPlayState(_playItf, SL_PLAYSTATE_PAUSED); SL_RETURN_IF_FAILED(r, "PcmAudioService::pause failed"); } } void PcmAudioService::resume() { if (_isInitialised) { SLresult r = (*_playItf)->SetPlayState(_playItf, SL_PLAYSTATE_PLAYING); SL_RETURN_IF_FAILED(r, "PcmAudioService::resume failed"); } } } // namespace cocos2d {
34.348259
116
0.677723
otakuidoru
709c69cad2fa198dfd6558457e66378db23cb28f
2,276
cpp
C++
non_shared_substring.cpp
agaitanis/strings
13688cc3e9007d0dadaf92feca198272e135fe60
[ "MIT" ]
2
2018-10-30T08:13:30.000Z
2019-03-05T22:49:40.000Z
non_shared_substring.cpp
agaitanis/strings
13688cc3e9007d0dadaf92feca198272e135fe60
[ "MIT" ]
null
null
null
non_shared_substring.cpp
agaitanis/strings
13688cc3e9007d0dadaf92feca198272e135fe60
[ "MIT" ]
null
null
null
#include <algorithm> #include <cassert> #include <iostream> #include <queue> #include <string> #include <unordered_set> #include <vector> using namespace std; #define LETTERS_NUM 6 struct Node { Node () : letter(' '), is_text1(false), is_text2(false), prev(-1) { for (int i = 0; i < LETTERS_NUM; i++) { next[i] = -1; } } char letter; bool is_text1; bool is_text2; int prev; int next[LETTERS_NUM]; }; typedef vector<Node> Trie; static int letter_to_index(char letter) { switch (letter) { case 'A': return 0; case 'C': return 1; case 'T': return 2; case 'G': return 3; case '#': return 4; case '$': return 5; default: assert(0); return -1; } } static Trie create_suffix_trie(const string &text) { Trie trie(1); bool is_text1 = true; bool is_text2 = false; for (size_t i = 0; i < text.size(); i++) { int v = 0; for (size_t j = i; j < text.size(); j++) { int index = letter_to_index(text[j]); int w = trie[v].next[index]; if (w == -1) { w = trie.size(); trie.push_back(Node()); trie[v].next[letter_to_index(text[j])] = w; trie[w].letter = text[j]; trie[w].prev = v; } if (is_text1) trie[w].is_text1 = true; if (is_text2) trie[w].is_text2 = true; v = w; } if (text[i] == '#') { is_text1 = false; is_text2 = true; } } return trie; } static string solve(const string &text1, const string &text2) { string text = text1 + "#" + text2 + "$"; Trie trie = create_suffix_trie(text); queue<int> q; vector<bool> visited(trie.size(), false); int w = -1; q.push(0); visited[0] = true; while (!q.empty()) { int v = q.front(); q.pop(); if (trie[v].letter == '#') continue; if (trie[v].letter == '$') continue; if (trie[v].is_text1 && !trie[v].is_text2) { w = v; break; } for (int i = 0; i < LETTERS_NUM; i++) { int z = trie[v].next[i]; if (z != -1 && !visited[z]) { q.push(z); visited[z] = true; } } } if (w == -1) return text1; string result; while (w != 0) { result += trie[w].letter; w = trie[w].prev; } reverse(result.begin(), result.end()); return result; } int main(void) { string text1, text2; cin >> text1; cin >> text2; cout << solve(text1, text2) << endl; return 0; }
15.589041
61
0.56942
agaitanis
709cb81520e5dc1eca4c80fcf8168449a551ae53
2,805
cpp
C++
src/astro/low_thrust/lowThrustOptimisationSetup.cpp
kimonito98/tudat
c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092
[ "BSD-3-Clause" ]
null
null
null
src/astro/low_thrust/lowThrustOptimisationSetup.cpp
kimonito98/tudat
c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092
[ "BSD-3-Clause" ]
null
null
null
src/astro/low_thrust/lowThrustOptimisationSetup.cpp
kimonito98/tudat
c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2010-2018, Delft University of Technology * All rigths reserved * * This file is part of the Tudat. Redistribution and use in source and * binary forms, with or without modification, are permitted exclusively * under the terms of the Modified BSD license. You should have received * a copy of the license with this file. If not, please or visit: * http://tudat.tudelft.nl/LICENSE. */ #include "tudat/astro/LowThrustTrajectories/lowThrustOptimisationSetup.h" namespace tudat { namespace low_thrust_trajectories { TrajectoryOptimisationProblem::TrajectoryOptimisationProblem( std::function< Eigen::Vector6d( const double ) > departureStateFunction, std::function< Eigen::Vector6d( const double ) > arrivalStateFunction, std::pair< double, double > departureTimeBounds, std::pair< double, double > timeOfFlightBounds, const std::shared_ptr< low_thrust_trajectories::LowThrustLegSettings >& lowThrustLegSettings ) : departureStateFunction_( departureStateFunction ), arrivalStateFunction_( arrivalStateFunction ), departureTimeBounds_( departureTimeBounds ), timeOfFlightBounds_( timeOfFlightBounds ), lowThrustLegSettings_( lowThrustLegSettings ) { initialSpacecraftMass_ = bodies_[ bodyToPropagate_ ]->getBodyMass(); } //! Descriptive name of the problem std::string TrajectoryOptimisationProblem::get_name() const { return "Low-thrust trajectory leg optimisation to minimise the required deltaV."; } //! Get bounds std::pair< std::vector< double >, std::vector< double > > TrajectoryOptimisationProblem::get_bounds() const { // Define lower bounds. std::vector< double > lowerBounds; lowerBounds.push_back( departureTimeBounds_.first ); lowerBounds.push_back( timeOfFlightBounds_.first ); // Define upper bounds. std::vector< double > upperBounds; upperBounds.push_back( departureTimeBounds_.second ); upperBounds.push_back( timeOfFlightBounds_.second ); return { lowerBounds, upperBounds }; } //! Fitness function. std::vector< double > TrajectoryOptimisationProblem::fitness( const std::vector< double > &designVariables ) const{ std::vector< double > fitness; double departureTime = designVariables[ 0 ]; double timeOfFlight = designVariables[ 1 ]; Eigen::Vector6d stateAtDeparture = departureStateFunction_( departureTime ); Eigen::Vector6d stateAtArrival = arrivalStateFunction_( departureTime + timeOfFlight ); std::shared_ptr< LowThrustLeg > lowThrustLeg = createLowThrustLeg( lowThrustLegSettings_, stateAtDeparture, stateAtArrival, timeOfFlight ); fitness.push_back( lowThrustLeg->computeDeltaV( ) ); return fitness; } } // namespace low_thrust_trajectories } // namespace tudat
35.506329
115
0.742602
kimonito98
709ce43164d55378ca5e5a9331d35832659f7318
2,336
hpp
C++
include/Cursor.hpp
psx95/collaborative-text-editor
457fee0c9aebf874e0ee3ac0a505220a7b493189
[ "MIT" ]
null
null
null
include/Cursor.hpp
psx95/collaborative-text-editor
457fee0c9aebf874e0ee3ac0a505220a7b493189
[ "MIT" ]
null
null
null
include/Cursor.hpp
psx95/collaborative-text-editor
457fee0c9aebf874e0ee3ac0a505220a7b493189
[ "MIT" ]
1
2021-04-30T17:51:44.000Z
2021-04-30T17:51:44.000Z
// // Created by psx95 on 11/16/20. // #ifndef COLLABORATIVE_TEXT_EDITOR_SRC_EDITOR_CURSOR_HPP_ #define COLLABORATIVE_TEXT_EDITOR_SRC_EDITOR_CURSOR_HPP_ #include <SFML/Graphics/RenderWindow.hpp> // This class represents the visual cursor and is mainly responsible for maintaining the cursor's properties. class Cursor { private: int line_number; // current line number int column_number; // current column number void UpdateCursorPosition(int _column_number, int _line_number); public: /*! * @brief The public constructor for the class. */ explicit Cursor(); /*! * @brief This method is responsible for providing the current cursor position as a pair of ints. * @details The first element of the pair represents the column number at which the cursor is currently present and * the second element is responsible for providing the line number of the cursor. * @return The current position of cursor as a std::pair of ints. */ std::pair<int, int> GetCurrentPosition() const; /*! * @brief A convenience method and is used to retrieve the current line number at which cursor is currently present. * @return The current line number for the cursor. */ int GetLineNumber() const; /*! * @brief A convenience method and is used to retrieve the current column number at which cursor is currently present. * @return The current column number for the cursor. */ int GetColumnNumber() const; /*! * @brief This method moves the cursor up by one line. */ void MoveCursorUp(); /*! * @brief This method is responsible for moving the cursor down by one line. */ void MoveCursorDown(); /*! * @brief This method is responsible for moving the cursor left by one column, if possible. */ void MoveCursorLeft(); /*! * @brief This method is responsible for moving the cursor right by one column. */ void MoveCursorRight(); /*! * @brief This method can be used to update the current position of the cursor to any other position. * @param _column_number The new column number to which the cursor needs to be moved to. * @param _line_number The new line number to which the cursor needs to be moved to. */ void MoveCursorToPosition(int _column_number, int _line_number); }; #endif //COLLABORATIVE_TEXT_EDITOR_SRC_EDITOR_CURSOR_HPP_
32.444444
120
0.729452
psx95
70a5d8706433f4e2bbb4553aaa4419a9184bfaa9
6,456
cpp
C++
libs/libupmq/transport/SimplePriorityMessageDispatchChannel.cpp
ivk-jsc/broker
8f43d85f115d605aac9d5b5875ccecc0c54d3217
[ "Apache-2.0" ]
10
2019-10-31T14:36:01.000Z
2022-02-25T13:47:23.000Z
libs/libupmq/transport/SimplePriorityMessageDispatchChannel.cpp
ivk-jsc/broker
8f43d85f115d605aac9d5b5875ccecc0c54d3217
[ "Apache-2.0" ]
6
2019-11-07T14:55:50.000Z
2021-03-03T09:31:35.000Z
libs/libupmq/transport/SimplePriorityMessageDispatchChannel.cpp
ivk-jsc/broker
8f43d85f115d605aac9d5b5875ccecc0c54d3217
[ "Apache-2.0" ]
3
2019-11-07T14:23:33.000Z
2020-11-05T18:35:16.000Z
/* * Copyright 2014-present IVK JSC. 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 "SimplePriorityMessageDispatchChannel.h" #include <cms/Message.h> #include <decaf/lang/Math.h> #include "UPMQCommand.h" using namespace std; using namespace upmq; using namespace upmq::transport; using namespace decaf; using namespace decaf::lang; using namespace decaf::util; using namespace decaf::util::concurrent; //////////////////////////////////////////////////////////////////////////////// const int SimplePriorityMessageDispatchChannel::MAX_PRIORITIES = 10; //////////////////////////////////////////////////////////////////////////////// SimplePriorityMessageDispatchChannel::SimplePriorityMessageDispatchChannel() : closed(false), running(false), mutex(), channels(MAX_PRIORITIES), enqueued(0) {} //////////////////////////////////////////////////////////////////////////////// SimplePriorityMessageDispatchChannel::~SimplePriorityMessageDispatchChannel() {} //////////////////////////////////////////////////////////////////////////////// void SimplePriorityMessageDispatchChannel::enqueue(const Pointer<Command>& message) { synchronized(&mutex) { this->getChannel(message).addLast(message); this->enqueued++; mutex.notify(); } } //////////////////////////////////////////////////////////////////////////////// void SimplePriorityMessageDispatchChannel::enqueueFirst(const Pointer<Command>& message) { synchronized(&mutex) { this->getChannel(message).addFirst(message); this->enqueued++; mutex.notify(); } } //////////////////////////////////////////////////////////////////////////////// bool SimplePriorityMessageDispatchChannel::isEmpty() const { return this->enqueued == 0; } //////////////////////////////////////////////////////////////////////////////// Pointer<Command> SimplePriorityMessageDispatchChannel::dequeue(long long timeout) { Pointer<Command> command; synchronized(&mutex) { // Wait until the channel is ready to deliver messages. while (timeout != 0 && !closed && (isEmpty() || !running)) { if (timeout == -1) { mutex.wait(); } else { mutex.wait(timeout); break; } } if (!closed && running && !isEmpty()) { command = removeFirst(); } } return command; } //////////////////////////////////////////////////////////////////////////////// Pointer<Command> SimplePriorityMessageDispatchChannel::dequeueNoWait() { Pointer<Command> command; synchronized(&mutex) { if (!closed && running && !isEmpty()) { command = removeFirst(); } } return command; } //////////////////////////////////////////////////////////////////////////////// Pointer<Command> SimplePriorityMessageDispatchChannel::peek() const { Pointer<Command> command; synchronized(&mutex) { if (!closed && running && !isEmpty()) { command = getFirst(); } } return command; } //////////////////////////////////////////////////////////////////////////////// void SimplePriorityMessageDispatchChannel::start() { synchronized(&mutex) { if (!closed) { running = true; mutex.notifyAll(); } } } //////////////////////////////////////////////////////////////////////////////// void SimplePriorityMessageDispatchChannel::stop() { synchronized(&mutex) { running = false; mutex.notifyAll(); } } //////////////////////////////////////////////////////////////////////////////// void SimplePriorityMessageDispatchChannel::close() { synchronized(&mutex) { if (!closed) { running = false; closed = true; } mutex.notifyAll(); } } //////////////////////////////////////////////////////////////////////////////// void SimplePriorityMessageDispatchChannel::clear() { synchronized(&mutex) { for (int i = 0; i < MAX_PRIORITIES; i++) { this->channels[i].clear(); } } } //////////////////////////////////////////////////////////////////////////////// int SimplePriorityMessageDispatchChannel::size() const { int size = 0; synchronized(&mutex) { size = this->enqueued; } return size; } //////////////////////////////////////////////////////////////////////////////// std::vector<Pointer<Command> > SimplePriorityMessageDispatchChannel::removeAll() { std::vector<Pointer<Command> > result; synchronized(&mutex) { for (int i = MAX_PRIORITIES - 1; i >= 0; --i) { std::vector<Pointer<Command> > temp(channels[i].toArray()); result.insert(result.end(), temp.begin(), temp.end()); this->enqueued -= (int)temp.size(); channels[i].clear(); } } return result; } //////////////////////////////////////////////////////////////////////////////// LinkedList<Pointer<Command> >& SimplePriorityMessageDispatchChannel::getChannel(const Pointer<Command>& dispatch) { int priority = cms::Message::DEFAULT_MSG_PRIORITY; if (dispatch.get() != nullptr) { priority = Math::max(((UPMQCommand*)dispatch.get())->_header->message().priority(), 0); priority = Math::min(priority, 9); } return this->channels[priority]; } //////////////////////////////////////////////////////////////////////////////// Pointer<Command> SimplePriorityMessageDispatchChannel::removeFirst() { if (this->enqueued > 0) { for (int i = MAX_PRIORITIES - 1; i >= 0; i--) { LinkedList<Pointer<Command> >& channel = channels[i]; if (!channel.isEmpty()) { this->enqueued--; return channel.pop(); } } } return Pointer<Command>(); } //////////////////////////////////////////////////////////////////////////////// Pointer<Command> SimplePriorityMessageDispatchChannel::getFirst() const { if (this->enqueued > 0) { for (int i = MAX_PRIORITIES - 1; i >= 0; i--) { LinkedList<Pointer<Command> >& channel = channels[i]; if (!channel.isEmpty()) { return channel.getFirst(); } } } return Pointer<Command>(); }
30.597156
115
0.52246
ivk-jsc
70a8eeac396e22b487ee2ce7e7cb8455947bea78
7,281
cc
C++
src/glasgow_clique_solver.cc
KyleBurns/bigraph-stuff
a17db9566343a8cc21bb9192156534dbf1c7c85e
[ "MIT" ]
null
null
null
src/glasgow_clique_solver.cc
KyleBurns/bigraph-stuff
a17db9566343a8cc21bb9192156534dbf1c7c85e
[ "MIT" ]
null
null
null
src/glasgow_clique_solver.cc
KyleBurns/bigraph-stuff
a17db9566343a8cc21bb9192156534dbf1c7c85e
[ "MIT" ]
null
null
null
/* vim: set sw=4 sts=4 et foldmethod=syntax : */ #include "formats/read_file_format.hh" #include "clique.hh" #include "configuration.hh" #include <boost/program_options.hpp> #include <chrono> #include <cstdlib> #include <ctime> #include <exception> #include <iomanip> #include <iostream> #include <memory> #include <optional> #include <unistd.h> namespace po = boost::program_options; using std::boolalpha; using std::cerr; using std::cout; using std::endl; using std::exception; using std::function; using std::localtime; using std::make_optional; using std::make_pair; using std::make_shared; using std::make_unique; using std::put_time; using std::string; using std::string_view; using std::chrono::duration_cast; using std::chrono::milliseconds; using std::chrono::operator""s; using std::chrono::seconds; using std::chrono::steady_clock; using std::chrono::system_clock; auto colour_class_order_from_string(string_view s) -> ColourClassOrder { if (s == "colour") return ColourClassOrder::ColourOrder; else if (s == "singletons-first") return ColourClassOrder::SingletonsFirst; else if (s == "sorted") return ColourClassOrder::Sorted; else throw UnsupportedConfiguration{ "Unknown colour class order '" + string(s) + "'" }; } auto main(int argc, char * argv[]) -> int { try { po::options_description display_options{ "Program options" }; display_options.add_options() ("help", "Display help information") ("timeout", po::value<int>(), "Abort after this many seconds") ("format", po::value<string>(), "Specify input file format (auto, lad, labelledlad, dimacs)") ("decide", po::value<int>(), "Solve this decision problem"); po::options_description configuration_options{ "Advanced configuration options" }; configuration_options.add_options() ("colour-ordering", po::value<string>(), "Specify colour-ordering (colour / singletons-first / sorted)") ("restarts-constant", po::value<int>(), "How often to perform restarts (disabled by default)") ("geometric-restarts", po::value<double>(), "Use geometric restarts with the specified multiplier (default is Luby)"); display_options.add(configuration_options); po::options_description all_options{ "All options" }; all_options.add_options() ("graph-file", "Specify the graph file") ; all_options.add(display_options); po::positional_options_description positional_options; positional_options .add("graph-file", 1) ; po::variables_map options_vars; po::store(po::command_line_parser(argc, argv) .options(all_options) .positional(positional_options) .run(), options_vars); po::notify(options_vars); /* --help? Show a message, and exit. */ if (options_vars.count("help")) { cout << "Usage: " << argv[0] << " [options] graph-file" << endl; cout << endl; cout << display_options << endl; return EXIT_SUCCESS; } /* No algorithm or no input file specified? Show a message and exit. */ if (! options_vars.count("graph-file")) { cout << "Usage: " << argv[0] << " [options] graph-file" << endl; return EXIT_FAILURE; } /* Figure out what our options should be. */ CliqueParams params; if (options_vars.count("decide")) params.decide = make_optional(options_vars["decide"].as<int>()); if (options_vars.count("restarts-constant")) { if (options_vars.count("geometric-restarts")) { double initial_value = GeometricRestartsSchedule::default_initial_value; double multiplier = options_vars["geometric-restarts"].as<double>(); initial_value = options_vars["restarts-constant"].as<int>(); params.restarts_schedule = make_unique<GeometricRestartsSchedule>(initial_value, multiplier); } else { long long multiplier = LubyRestartsSchedule::default_multiplier; multiplier = options_vars["restarts-constant"].as<int>(); params.restarts_schedule = make_unique<LubyRestartsSchedule>(multiplier); } } else params.restarts_schedule = make_unique<NoRestartsSchedule>(); if (options_vars.count("colour-ordering")) params.colour_class_order = colour_class_order_from_string(options_vars["colour-ordering"].as<string>()); char hostname_buf[255]; if (0 == gethostname(hostname_buf, 255)) cout << "hostname = " << string(hostname_buf) << endl; cout << "commandline ="; for (int i = 0 ; i < argc ; ++i) cout << " " << argv[i]; cout << endl; auto started_at = system_clock::to_time_t(system_clock::now()); cout << "started_at = " << put_time(localtime(&started_at), "%F %T") << endl; /* Read in the graphs */ string pattern_format_name = options_vars.count("format") ? options_vars["format"].as<string>() : "auto"; auto graph = read_pattern_file_format(pattern_format_name, options_vars["graph-file"].as<string>()); cout << "file = " << options_vars["graph-file"].as<string>() << endl; /* Prepare and start timeout */ params.timeout = make_shared<Timeout>(options_vars.count("timeout") ? seconds{ options_vars["timeout"].as<int>() } : 0s); /* Start the clock */ params.start_time = steady_clock::now(); auto result = solve_clique_problem(graph, params); /* Stop the clock. */ auto overall_time = duration_cast<milliseconds>(steady_clock::now() - params.start_time); params.timeout->stop(); cout << "status = "; if (params.timeout->aborted()) cout << "aborted"; else if (! result.clique.empty()) cout << "true"; else cout << "false"; cout << endl; cout << "nodes = " << result.nodes << endl; if (! result.clique.empty()) { cout << "omega = " << result.clique.size() << endl; cout << "clique ="; for (auto v : result.clique) cout << " " << graph.vertex_name(v); cout << endl; } cout << "runtime = " << overall_time.count() << endl; for (const auto & s : result.extra_stats) cout << s << endl; return EXIT_SUCCESS; } catch (const GraphFileError & e) { cerr << "Error: " << e.what() << endl; if (e.file_at_least_existed()) cerr << "Maybe try specifying --format?" << endl; return EXIT_FAILURE; } catch (const po::error & e) { cerr << "Error: " << e.what() << endl; cerr << "Try " << argv[0] << " --help" << endl; return EXIT_FAILURE; } catch (const exception & e) { cerr << "Error: " << e.what() << endl; return EXIT_FAILURE; } }
35.691176
135
0.586458
KyleBurns
70aa81247916a1e9793565f730b8cb361430bb4b
4,570
cpp
C++
PeteBrown.Devices.Midi/PeteBrown.Devices.Midi/MidiClockGenerator.cpp
Psychlist1972/Windows-10-MIDI-Library
a7b0390fea19407b168870480927678624d46c12
[ "MIT" ]
29
2016-08-11T12:34:37.000Z
2022-03-31T00:25:54.000Z
PeteBrown.Devices.Midi/PeteBrown.Devices.Midi/MidiClockGenerator.cpp
SeYoungLee/Windows-10-MIDI-Library
a7b0390fea19407b168870480927678624d46c12
[ "MIT" ]
4
2017-04-28T18:53:03.000Z
2020-12-03T13:09:02.000Z
PeteBrown.Devices.Midi/PeteBrown.Devices.Midi/MidiClockGenerator.cpp
SeYoungLee/Windows-10-MIDI-Library
a7b0390fea19407b168870480927678624d46c12
[ "MIT" ]
5
2016-08-11T14:41:48.000Z
2021-09-26T13:34:20.000Z
#include "pch.h" #include "MidiClockGenerator.h" #include <Windows.h> #include <tchar.h> #include <collection.h> using namespace PeteBrown::Devices::Midi; using namespace Platform; using namespace Platform::Collections; using namespace Windows::Devices::Midi; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::System::Threading; MidiClockGenerator::MidiClockGenerator() { _isRunning = false; _outputPorts = ref new Vector<IMidiOutPort^>(); QueryPerformanceFrequency(&_performanceCounterFrequency); OutputDebugString(_T(" MidiClock: Query Performance Frequency returned\n")); } bool MidiClockGenerator::SendMidiStartMessage::get() { return _sendMidiStartMessage; } void MidiClockGenerator::SendMidiStartMessage::set(bool value) { _sendMidiStartMessage = value; } bool MidiClockGenerator::SendMidiStopMessage::get() { return _sendMidiStopMessage; } void MidiClockGenerator::SendMidiStopMessage::set(bool value) { _sendMidiStopMessage = value; } Windows::Foundation::Collections::IVector<IMidiOutPort^>^ MidiClockGenerator::OutputPorts::get() { return _outputPorts; } // // Important examples // At 120bpm, 24ppqn, we need 48 clock messages per second (120/60 * 24) : one every 20.83333 ms // At 320bpm, 24ppqn, we need 128 clock messages per second (320/60 * 24) : one every 7.8125 ms. // That helps give minimum resolutions for this loop. void MidiClockGenerator::ThreadWorker(IAsyncAction^ operation) { LARGE_INTEGER lastTime; LONGLONG nextTime; LARGE_INTEGER currentTime; currentTime.QuadPart = 0; double errorAccumulator = 0.0; // Send the MIDI stop message to start the sequencer if (_sendMidiStartMessage) { BroadcastMessage(ref new MidiStartMessage()); } //byte clockMessage = 0xF8; // We'll reuse this one clockMessage for every time we want to send out a pulse MidiTimingClockMessage^ clockMessage = ref new MidiTimingClockMessage(); // Note that it also swallows most of a CPU logical core :) // this is a number you can play with to balance CPU usage and resolution while (_isRunning) { QueryPerformanceCounter(&lastTime); // send the message // ideally, this would include the timestamp and just be scheduled. We don't have that yet, though. BroadcastMessage(clockMessage); nextTime = lastTime.QuadPart + _tickInterval; // consider trying concurrency::wait in here. May be too chunky, though. if (errorAccumulator >= 1.0) { // get the whole number part of the error and then remove it from // the accumulator (which is a double) nextTime += (long)(std::trunc(errorAccumulator)); errorAccumulator -= (long)(std::trunc(errorAccumulator)); } // spin until this cycle is done // This is the one part I really dislike here. // sleeping the thread is no good due to durations required while (currentTime.QuadPart < nextTime) { QueryPerformanceCounter(&currentTime); } // accumulate some error :) errorAccumulator += _tickTruncationError; } // Send the MIDI stop message to stop the sequencer if (_sendMidiStopMessage) { BroadcastMessage(ref new MidiStopMessage()); } OutputDebugString(_T(" MidiClock: Stopped Running (in background thread)\n")); } void MidiClockGenerator::Start() { if (_outputPorts && _outputPorts->Size > 0) { _isRunning = true; ThreadPool::RunAsync( ref new WorkItemHandler(this, &MidiClockGenerator::ThreadWorker)); OutputDebugString(_T(" MidiClock: Started.\n")); } else { OutputDebugString(_T(" MidiClock: No output ports specified.\n")); } } void MidiClockGenerator::Stop() { _isRunning = false; OutputDebugString(_T(" MidiClock: Stop request received.\n")); } double MidiClockGenerator::Tempo::get() { return _tempoBpm; } void MidiClockGenerator::Tempo::set(double tempo) { const int ppqn = 24; _tempoBpm = tempo; // this is going to have rounding errors // we account for this in the clock worker thread function _tickInterval = (LONGLONG)(std::trunc(((double)_performanceCounterFrequency.QuadPart / (_tempoBpm / 60.0F)) / ppqn)); _tickTruncationError = (double)(((double)_performanceCounterFrequency.QuadPart / (_tempoBpm / 60.0F)) / ppqn) - _tickInterval; OutputDebugString(_T(" MidiClock: Tempo set.\n")); }
25.530726
127
0.694092
Psychlist1972
70adeae6801ad10c9eaef7286ad8d8672a350cc1
284
cpp
C++
Lectures/Lecture5/stringConcatenation.cpp
Emin-Abdurahmanov/BasicsOfProgramming
0742b1639170c81047a36ead989df29fdfcf6fba
[ "MIT" ]
1
2021-11-12T13:11:22.000Z
2021-11-12T13:11:22.000Z
Lectures/Lecture5/stringConcatenation.cpp
Emin-Abdurahmanov/BasicsOfProgramming
0742b1639170c81047a36ead989df29fdfcf6fba
[ "MIT" ]
null
null
null
Lectures/Lecture5/stringConcatenation.cpp
Emin-Abdurahmanov/BasicsOfProgramming
0742b1639170c81047a36ead989df29fdfcf6fba
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace std; int main(int argc, char** argv) { string sentence = "Hello"; string name; cout << "Type your name please.\n"; cin >> name; sentence = sentence + " "; sentence += name; cout << sentence; return 0; }
16.705882
37
0.609155
Emin-Abdurahmanov
70af95592aa562684f8aa09e857778d3849e119a
27,071
cpp
C++
lib/Target/Mips/MicroMipsSizeReduction.cpp
URSec/Silhouette-Compiler-Legacy
28b37f3617c5543a87537decc074b168f4803d87
[ "Apache-2.0" ]
938
2015-12-03T16:45:43.000Z
2022-03-17T20:28:02.000Z
lib/Target/Mips/MicroMipsSizeReduction.cpp
URSec/Silhouette-Compiler-Legacy
28b37f3617c5543a87537decc074b168f4803d87
[ "Apache-2.0" ]
127
2015-12-03T21:42:53.000Z
2019-11-21T14:34:20.000Z
lib/Target/Mips/MicroMipsSizeReduction.cpp
URSec/Silhouette-Compiler-Legacy
28b37f3617c5543a87537decc074b168f4803d87
[ "Apache-2.0" ]
280
2015-12-03T16:51:35.000Z
2022-01-24T00:01:54.000Z
//=== MicroMipsSizeReduction.cpp - MicroMips size reduction pass --------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// ///\file /// This pass is used to reduce the size of instructions where applicable. /// /// TODO: Implement microMIPS64 support. //===----------------------------------------------------------------------===// #include "Mips.h" #include "MipsInstrInfo.h" #include "MipsSubtarget.h" #include "llvm/ADT/Statistic.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/Support/Debug.h" using namespace llvm; #define DEBUG_TYPE "micromips-reduce-size" #define MICROMIPS_SIZE_REDUCE_NAME "MicroMips instruction size reduce pass" STATISTIC(NumReduced, "Number of instructions reduced (32-bit to 16-bit ones, " "or two instructions into one"); namespace { /// Order of operands to transfer // TODO: Will be extended when additional optimizations are added enum OperandTransfer { OT_NA, ///< Not applicable OT_OperandsAll, ///< Transfer all operands OT_Operands02, ///< Transfer operands 0 and 2 OT_Operand2, ///< Transfer just operand 2 OT_OperandsXOR, ///< Transfer operands for XOR16 OT_OperandsLwp, ///< Transfer operands for LWP OT_OperandsSwp, ///< Transfer operands for SWP OT_OperandsMovep, ///< Transfer operands for MOVEP }; /// Reduction type // TODO: Will be extended when additional optimizations are added enum ReduceType { RT_TwoInstr, ///< Reduce two instructions into one instruction RT_OneInstr ///< Reduce one instruction into a smaller instruction }; // Information about immediate field restrictions struct ImmField { ImmField() : ImmFieldOperand(-1), Shift(0), LBound(0), HBound(0) {} ImmField(uint8_t Shift, int16_t LBound, int16_t HBound, int8_t ImmFieldOperand) : ImmFieldOperand(ImmFieldOperand), Shift(Shift), LBound(LBound), HBound(HBound) {} int8_t ImmFieldOperand; // Immediate operand, -1 if it does not exist uint8_t Shift; // Shift value int16_t LBound; // Low bound of the immediate operand int16_t HBound; // High bound of the immediate operand }; /// Information about operands // TODO: Will be extended when additional optimizations are added struct OpInfo { OpInfo(enum OperandTransfer TransferOperands) : TransferOperands(TransferOperands) {} OpInfo() : TransferOperands(OT_NA) {} enum OperandTransfer TransferOperands; ///< Operands to transfer to the new instruction }; // Information about opcodes struct OpCodes { OpCodes(unsigned WideOpc, unsigned NarrowOpc) : WideOpc(WideOpc), NarrowOpc(NarrowOpc) {} unsigned WideOpc; ///< Wide opcode unsigned NarrowOpc; ///< Narrow opcode }; typedef struct ReduceEntryFunArgs ReduceEntryFunArgs; /// ReduceTable - A static table with information on mapping from wide /// opcodes to narrow struct ReduceEntry { enum ReduceType eRType; ///< Reduction type bool (*ReduceFunction)( ReduceEntryFunArgs *Arguments); ///< Pointer to reduce function struct OpCodes Ops; ///< All relevant OpCodes struct OpInfo OpInf; ///< Characteristics of operands struct ImmField Imm; ///< Characteristics of immediate field ReduceEntry(enum ReduceType RType, struct OpCodes Op, bool (*F)(ReduceEntryFunArgs *Arguments), struct OpInfo OpInf, struct ImmField Imm) : eRType(RType), ReduceFunction(F), Ops(Op), OpInf(OpInf), Imm(Imm) {} unsigned NarrowOpc() const { return Ops.NarrowOpc; } unsigned WideOpc() const { return Ops.WideOpc; } int16_t LBound() const { return Imm.LBound; } int16_t HBound() const { return Imm.HBound; } uint8_t Shift() const { return Imm.Shift; } int8_t ImmField() const { return Imm.ImmFieldOperand; } enum OperandTransfer TransferOperands() const { return OpInf.TransferOperands; } enum ReduceType RType() const { return eRType; } // operator used by std::equal_range bool operator<(const unsigned int r) const { return (WideOpc() < r); } // operator used by std::equal_range friend bool operator<(const unsigned int r, const struct ReduceEntry &re) { return (r < re.WideOpc()); } }; // Function arguments for ReduceFunction struct ReduceEntryFunArgs { MachineInstr *MI; // Instruction const ReduceEntry &Entry; // Entry field MachineBasicBlock::instr_iterator &NextMII; // Iterator to next instruction in block ReduceEntryFunArgs(MachineInstr *argMI, const ReduceEntry &argEntry, MachineBasicBlock::instr_iterator &argNextMII) : MI(argMI), Entry(argEntry), NextMII(argNextMII) {} }; typedef llvm::SmallVector<ReduceEntry, 32> ReduceEntryVector; class MicroMipsSizeReduce : public MachineFunctionPass { public: static char ID; MicroMipsSizeReduce(); static const MipsInstrInfo *MipsII; const MipsSubtarget *Subtarget; bool runOnMachineFunction(MachineFunction &MF) override; llvm::StringRef getPassName() const override { return "microMIPS instruction size reduction pass"; } private: /// Reduces width of instructions in the specified basic block. bool ReduceMBB(MachineBasicBlock &MBB); /// Attempts to reduce MI, returns true on success. bool ReduceMI(const MachineBasicBlock::instr_iterator &MII, MachineBasicBlock::instr_iterator &NextMII); // Attempts to reduce LW/SW instruction into LWSP/SWSP, // returns true on success. static bool ReduceXWtoXWSP(ReduceEntryFunArgs *Arguments); // Attempts to reduce two LW/SW instructions into LWP/SWP instruction, // returns true on success. static bool ReduceXWtoXWP(ReduceEntryFunArgs *Arguments); // Attempts to reduce LBU/LHU instruction into LBU16/LHU16, // returns true on success. static bool ReduceLXUtoLXU16(ReduceEntryFunArgs *Arguments); // Attempts to reduce SB/SH instruction into SB16/SH16, // returns true on success. static bool ReduceSXtoSX16(ReduceEntryFunArgs *Arguments); // Attempts to reduce two MOVE instructions into MOVEP instruction, // returns true on success. static bool ReduceMoveToMovep(ReduceEntryFunArgs *Arguments); // Attempts to reduce arithmetic instructions, returns true on success. static bool ReduceArithmeticInstructions(ReduceEntryFunArgs *Arguments); // Attempts to reduce ADDIU into ADDIUSP instruction, // returns true on success. static bool ReduceADDIUToADDIUSP(ReduceEntryFunArgs *Arguments); // Attempts to reduce ADDIU into ADDIUR1SP instruction, // returns true on success. static bool ReduceADDIUToADDIUR1SP(ReduceEntryFunArgs *Arguments); // Attempts to reduce XOR into XOR16 instruction, // returns true on success. static bool ReduceXORtoXOR16(ReduceEntryFunArgs *Arguments); // Changes opcode of an instruction, replaces an instruction with a // new one, or replaces two instructions with a new instruction // depending on their order i.e. if these are consecutive forward // or consecutive backward static bool ReplaceInstruction(MachineInstr *MI, const ReduceEntry &Entry, MachineInstr *MI2 = nullptr, bool ConsecutiveForward = true); // Table with transformation rules for each instruction. static ReduceEntryVector ReduceTable; }; char MicroMipsSizeReduce::ID = 0; const MipsInstrInfo *MicroMipsSizeReduce::MipsII; // This table must be sorted by WideOpc as a main criterion and // ReduceType as a sub-criterion (when wide opcodes are the same). ReduceEntryVector MicroMipsSizeReduce::ReduceTable = { // ReduceType, OpCodes, ReduceFunction, // OpInfo(TransferOperands), // ImmField(Shift, LBound, HBound, ImmFieldPosition) {RT_OneInstr, OpCodes(Mips::ADDiu, Mips::ADDIUR1SP_MM), ReduceADDIUToADDIUR1SP, OpInfo(OT_Operands02), ImmField(2, 0, 64, 2)}, {RT_OneInstr, OpCodes(Mips::ADDiu, Mips::ADDIUSP_MM), ReduceADDIUToADDIUSP, OpInfo(OT_Operand2), ImmField(0, 0, 0, 2)}, {RT_OneInstr, OpCodes(Mips::ADDiu_MM, Mips::ADDIUR1SP_MM), ReduceADDIUToADDIUR1SP, OpInfo(OT_Operands02), ImmField(2, 0, 64, 2)}, {RT_OneInstr, OpCodes(Mips::ADDiu_MM, Mips::ADDIUSP_MM), ReduceADDIUToADDIUSP, OpInfo(OT_Operand2), ImmField(0, 0, 0, 2)}, {RT_OneInstr, OpCodes(Mips::ADDu, Mips::ADDU16_MM), ReduceArithmeticInstructions, OpInfo(OT_OperandsAll), ImmField(0, 0, 0, -1)}, {RT_OneInstr, OpCodes(Mips::ADDu_MM, Mips::ADDU16_MM), ReduceArithmeticInstructions, OpInfo(OT_OperandsAll), ImmField(0, 0, 0, -1)}, {RT_OneInstr, OpCodes(Mips::LBu, Mips::LBU16_MM), ReduceLXUtoLXU16, OpInfo(OT_OperandsAll), ImmField(0, -1, 15, 2)}, {RT_OneInstr, OpCodes(Mips::LBu_MM, Mips::LBU16_MM), ReduceLXUtoLXU16, OpInfo(OT_OperandsAll), ImmField(0, -1, 15, 2)}, {RT_OneInstr, OpCodes(Mips::LEA_ADDiu, Mips::ADDIUR1SP_MM), ReduceADDIUToADDIUR1SP, OpInfo(OT_Operands02), ImmField(2, 0, 64, 2)}, {RT_OneInstr, OpCodes(Mips::LEA_ADDiu_MM, Mips::ADDIUR1SP_MM), ReduceADDIUToADDIUR1SP, OpInfo(OT_Operands02), ImmField(2, 0, 64, 2)}, {RT_OneInstr, OpCodes(Mips::LHu, Mips::LHU16_MM), ReduceLXUtoLXU16, OpInfo(OT_OperandsAll), ImmField(1, 0, 16, 2)}, {RT_OneInstr, OpCodes(Mips::LHu_MM, Mips::LHU16_MM), ReduceLXUtoLXU16, OpInfo(OT_OperandsAll), ImmField(1, 0, 16, 2)}, {RT_TwoInstr, OpCodes(Mips::LW, Mips::LWP_MM), ReduceXWtoXWP, OpInfo(OT_OperandsLwp), ImmField(0, -2048, 2048, 2)}, {RT_OneInstr, OpCodes(Mips::LW, Mips::LWSP_MM), ReduceXWtoXWSP, OpInfo(OT_OperandsAll), ImmField(2, 0, 32, 2)}, {RT_TwoInstr, OpCodes(Mips::LW16_MM, Mips::LWP_MM), ReduceXWtoXWP, OpInfo(OT_OperandsLwp), ImmField(0, -2048, 2048, 2)}, {RT_TwoInstr, OpCodes(Mips::LW_MM, Mips::LWP_MM), ReduceXWtoXWP, OpInfo(OT_OperandsLwp), ImmField(0, -2048, 2048, 2)}, {RT_OneInstr, OpCodes(Mips::LW_MM, Mips::LWSP_MM), ReduceXWtoXWSP, OpInfo(OT_OperandsAll), ImmField(2, 0, 32, 2)}, {RT_TwoInstr, OpCodes(Mips::MOVE16_MM, Mips::MOVEP_MM), ReduceMoveToMovep, OpInfo(OT_OperandsMovep), ImmField(0, 0, 0, -1)}, {RT_OneInstr, OpCodes(Mips::SB, Mips::SB16_MM), ReduceSXtoSX16, OpInfo(OT_OperandsAll), ImmField(0, 0, 16, 2)}, {RT_OneInstr, OpCodes(Mips::SB_MM, Mips::SB16_MM), ReduceSXtoSX16, OpInfo(OT_OperandsAll), ImmField(0, 0, 16, 2)}, {RT_OneInstr, OpCodes(Mips::SH, Mips::SH16_MM), ReduceSXtoSX16, OpInfo(OT_OperandsAll), ImmField(1, 0, 16, 2)}, {RT_OneInstr, OpCodes(Mips::SH_MM, Mips::SH16_MM), ReduceSXtoSX16, OpInfo(OT_OperandsAll), ImmField(1, 0, 16, 2)}, {RT_OneInstr, OpCodes(Mips::SUBu, Mips::SUBU16_MM), ReduceArithmeticInstructions, OpInfo(OT_OperandsAll), ImmField(0, 0, 0, -1)}, {RT_OneInstr, OpCodes(Mips::SUBu_MM, Mips::SUBU16_MM), ReduceArithmeticInstructions, OpInfo(OT_OperandsAll), ImmField(0, 0, 0, -1)}, {RT_TwoInstr, OpCodes(Mips::SW, Mips::SWP_MM), ReduceXWtoXWP, OpInfo(OT_OperandsSwp), ImmField(0, -2048, 2048, 2)}, {RT_OneInstr, OpCodes(Mips::SW, Mips::SWSP_MM), ReduceXWtoXWSP, OpInfo(OT_OperandsAll), ImmField(2, 0, 32, 2)}, {RT_TwoInstr, OpCodes(Mips::SW16_MM, Mips::SWP_MM), ReduceXWtoXWP, OpInfo(OT_OperandsSwp), ImmField(0, -2048, 2048, 2)}, {RT_TwoInstr, OpCodes(Mips::SW_MM, Mips::SWP_MM), ReduceXWtoXWP, OpInfo(OT_OperandsSwp), ImmField(0, -2048, 2048, 2)}, {RT_OneInstr, OpCodes(Mips::SW_MM, Mips::SWSP_MM), ReduceXWtoXWSP, OpInfo(OT_OperandsAll), ImmField(2, 0, 32, 2)}, {RT_OneInstr, OpCodes(Mips::XOR, Mips::XOR16_MM), ReduceXORtoXOR16, OpInfo(OT_OperandsXOR), ImmField(0, 0, 0, -1)}, {RT_OneInstr, OpCodes(Mips::XOR_MM, Mips::XOR16_MM), ReduceXORtoXOR16, OpInfo(OT_OperandsXOR), ImmField(0, 0, 0, -1)}}; } // end anonymous namespace INITIALIZE_PASS(MicroMipsSizeReduce, DEBUG_TYPE, MICROMIPS_SIZE_REDUCE_NAME, false, false) // Returns true if the machine operand MO is register SP. static bool IsSP(const MachineOperand &MO) { if (MO.isReg() && ((MO.getReg() == Mips::SP))) return true; return false; } // Returns true if the machine operand MO is register $16, $17, or $2-$7. static bool isMMThreeBitGPRegister(const MachineOperand &MO) { if (MO.isReg() && Mips::GPRMM16RegClass.contains(MO.getReg())) return true; return false; } // Returns true if the machine operand MO is register $0, $17, or $2-$7. static bool isMMSourceRegister(const MachineOperand &MO) { if (MO.isReg() && Mips::GPRMM16ZeroRegClass.contains(MO.getReg())) return true; return false; } // Returns true if the operand Op is an immediate value // and writes the immediate value into variable Imm. static bool GetImm(MachineInstr *MI, unsigned Op, int64_t &Imm) { if (!MI->getOperand(Op).isImm()) return false; Imm = MI->getOperand(Op).getImm(); return true; } // Returns true if the value is a valid immediate for ADDIUSP. static bool AddiuspImmValue(int64_t Value) { int64_t Value2 = Value >> 2; if (((Value & (int64_t)maskTrailingZeros<uint64_t>(2)) == Value) && ((Value2 >= 2 && Value2 <= 257) || (Value2 >= -258 && Value2 <= -3))) return true; return false; } // Returns true if the variable Value has the number of least-significant zero // bits equal to Shift and if the shifted value is between the bounds. static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound) { int64_t Value2 = Value >> Shift; if (((Value & (int64_t)maskTrailingZeros<uint64_t>(Shift)) == Value) && (Value2 >= LBound) && (Value2 < HBound)) return true; return false; } // Returns true if immediate operand is in range. static bool ImmInRange(MachineInstr *MI, const ReduceEntry &Entry) { int64_t offset; if (!GetImm(MI, Entry.ImmField(), offset)) return false; if (!InRange(offset, Entry.Shift(), Entry.LBound(), Entry.HBound())) return false; return true; } // Returns true if MI can be reduced to lwp/swp instruction static bool CheckXWPInstr(MachineInstr *MI, bool ReduceToLwp, const ReduceEntry &Entry) { if (ReduceToLwp && !(MI->getOpcode() == Mips::LW || MI->getOpcode() == Mips::LW_MM || MI->getOpcode() == Mips::LW16_MM)) return false; if (!ReduceToLwp && !(MI->getOpcode() == Mips::SW || MI->getOpcode() == Mips::SW_MM || MI->getOpcode() == Mips::SW16_MM)) return false; unsigned reg = MI->getOperand(0).getReg(); if (reg == Mips::RA) return false; if (!ImmInRange(MI, Entry)) return false; if (ReduceToLwp && (MI->getOperand(0).getReg() == MI->getOperand(1).getReg())) return false; return true; } // Returns true if the registers Reg1 and Reg2 are consecutive static bool ConsecutiveRegisters(unsigned Reg1, unsigned Reg2) { static SmallVector<unsigned, 31> Registers = { Mips::AT, Mips::V0, Mips::V1, Mips::A0, Mips::A1, Mips::A2, Mips::A3, Mips::T0, Mips::T1, Mips::T2, Mips::T3, Mips::T4, Mips::T5, Mips::T6, Mips::T7, Mips::S0, Mips::S1, Mips::S2, Mips::S3, Mips::S4, Mips::S5, Mips::S6, Mips::S7, Mips::T8, Mips::T9, Mips::K0, Mips::K1, Mips::GP, Mips::SP, Mips::FP, Mips::RA}; for (uint8_t i = 0; i < Registers.size() - 1; i++) { if (Registers[i] == Reg1) { if (Registers[i + 1] == Reg2) return true; else return false; } } return false; } // Returns true if registers and offsets are consecutive static bool ConsecutiveInstr(MachineInstr *MI1, MachineInstr *MI2) { int64_t Offset1, Offset2; if (!GetImm(MI1, 2, Offset1)) return false; if (!GetImm(MI2, 2, Offset2)) return false; unsigned Reg1 = MI1->getOperand(0).getReg(); unsigned Reg2 = MI2->getOperand(0).getReg(); return ((Offset1 == (Offset2 - 4)) && (ConsecutiveRegisters(Reg1, Reg2))); } MicroMipsSizeReduce::MicroMipsSizeReduce() : MachineFunctionPass(ID) {} bool MicroMipsSizeReduce::ReduceMI(const MachineBasicBlock::instr_iterator &MII, MachineBasicBlock::instr_iterator &NextMII) { MachineInstr *MI = &*MII; unsigned Opcode = MI->getOpcode(); // Search the table. ReduceEntryVector::const_iterator Start = std::begin(ReduceTable); ReduceEntryVector::const_iterator End = std::end(ReduceTable); std::pair<ReduceEntryVector::const_iterator, ReduceEntryVector::const_iterator> Range = std::equal_range(Start, End, Opcode); if (Range.first == Range.second) return false; for (ReduceEntryVector::const_iterator Entry = Range.first; Entry != Range.second; ++Entry) { ReduceEntryFunArgs Arguments(&(*MII), *Entry, NextMII); if (((*Entry).ReduceFunction)(&Arguments)) return true; } return false; } bool MicroMipsSizeReduce::ReduceXWtoXWSP(ReduceEntryFunArgs *Arguments) { MachineInstr *MI = Arguments->MI; const ReduceEntry &Entry = Arguments->Entry; if (!ImmInRange(MI, Entry)) return false; if (!IsSP(MI->getOperand(1))) return false; return ReplaceInstruction(MI, Entry); } bool MicroMipsSizeReduce::ReduceXWtoXWP(ReduceEntryFunArgs *Arguments) { const ReduceEntry &Entry = Arguments->Entry; MachineBasicBlock::instr_iterator &NextMII = Arguments->NextMII; const MachineBasicBlock::instr_iterator &E = Arguments->MI->getParent()->instr_end(); if (NextMII == E) return false; MachineInstr *MI1 = Arguments->MI; MachineInstr *MI2 = &*NextMII; // ReduceToLwp = true/false - reduce to LWP/SWP instruction bool ReduceToLwp = (MI1->getOpcode() == Mips::LW) || (MI1->getOpcode() == Mips::LW_MM) || (MI1->getOpcode() == Mips::LW16_MM); if (!CheckXWPInstr(MI1, ReduceToLwp, Entry)) return false; if (!CheckXWPInstr(MI2, ReduceToLwp, Entry)) return false; unsigned Reg1 = MI1->getOperand(1).getReg(); unsigned Reg2 = MI2->getOperand(1).getReg(); if (Reg1 != Reg2) return false; bool ConsecutiveForward = ConsecutiveInstr(MI1, MI2); bool ConsecutiveBackward = ConsecutiveInstr(MI2, MI1); if (!(ConsecutiveForward || ConsecutiveBackward)) return false; NextMII = std::next(NextMII); return ReplaceInstruction(MI1, Entry, MI2, ConsecutiveForward); } bool MicroMipsSizeReduce::ReduceArithmeticInstructions( ReduceEntryFunArgs *Arguments) { MachineInstr *MI = Arguments->MI; const ReduceEntry &Entry = Arguments->Entry; if (!isMMThreeBitGPRegister(MI->getOperand(0)) || !isMMThreeBitGPRegister(MI->getOperand(1)) || !isMMThreeBitGPRegister(MI->getOperand(2))) return false; return ReplaceInstruction(MI, Entry); } bool MicroMipsSizeReduce::ReduceADDIUToADDIUR1SP( ReduceEntryFunArgs *Arguments) { MachineInstr *MI = Arguments->MI; const ReduceEntry &Entry = Arguments->Entry; if (!ImmInRange(MI, Entry)) return false; if (!isMMThreeBitGPRegister(MI->getOperand(0)) || !IsSP(MI->getOperand(1))) return false; return ReplaceInstruction(MI, Entry); } bool MicroMipsSizeReduce::ReduceADDIUToADDIUSP(ReduceEntryFunArgs *Arguments) { MachineInstr *MI = Arguments->MI; const ReduceEntry &Entry = Arguments->Entry; int64_t ImmValue; if (!GetImm(MI, Entry.ImmField(), ImmValue)) return false; if (!AddiuspImmValue(ImmValue)) return false; if (!IsSP(MI->getOperand(0)) || !IsSP(MI->getOperand(1))) return false; return ReplaceInstruction(MI, Entry); } bool MicroMipsSizeReduce::ReduceLXUtoLXU16(ReduceEntryFunArgs *Arguments) { MachineInstr *MI = Arguments->MI; const ReduceEntry &Entry = Arguments->Entry; if (!ImmInRange(MI, Entry)) return false; if (!isMMThreeBitGPRegister(MI->getOperand(0)) || !isMMThreeBitGPRegister(MI->getOperand(1))) return false; return ReplaceInstruction(MI, Entry); } bool MicroMipsSizeReduce::ReduceSXtoSX16(ReduceEntryFunArgs *Arguments) { MachineInstr *MI = Arguments->MI; const ReduceEntry &Entry = Arguments->Entry; if (!ImmInRange(MI, Entry)) return false; if (!isMMSourceRegister(MI->getOperand(0)) || !isMMThreeBitGPRegister(MI->getOperand(1))) return false; return ReplaceInstruction(MI, Entry); } // Returns true if Reg can be a source register // of MOVEP instruction static bool IsMovepSrcRegister(unsigned Reg) { if (Reg == Mips::ZERO || Reg == Mips::V0 || Reg == Mips::V1 || Reg == Mips::S0 || Reg == Mips::S1 || Reg == Mips::S2 || Reg == Mips::S3 || Reg == Mips::S4) return true; return false; } // Returns true if Reg can be a destination register // of MOVEP instruction static bool IsMovepDestinationReg(unsigned Reg) { if (Reg == Mips::A0 || Reg == Mips::A1 || Reg == Mips::A2 || Reg == Mips::A3 || Reg == Mips::S5 || Reg == Mips::S6) return true; return false; } // Returns true if the registers can be a pair of destination // registers in MOVEP instruction static bool IsMovepDestinationRegPair(unsigned R0, unsigned R1) { if ((R0 == Mips::A0 && R1 == Mips::S5) || (R0 == Mips::A0 && R1 == Mips::S6) || (R0 == Mips::A0 && R1 == Mips::A1) || (R0 == Mips::A0 && R1 == Mips::A2) || (R0 == Mips::A0 && R1 == Mips::A3) || (R0 == Mips::A1 && R1 == Mips::A2) || (R0 == Mips::A1 && R1 == Mips::A3) || (R0 == Mips::A2 && R1 == Mips::A3)) return true; return false; } bool MicroMipsSizeReduce::ReduceMoveToMovep(ReduceEntryFunArgs *Arguments) { const ReduceEntry &Entry = Arguments->Entry; MachineBasicBlock::instr_iterator &NextMII = Arguments->NextMII; const MachineBasicBlock::instr_iterator &E = Arguments->MI->getParent()->instr_end(); if (NextMII == E) return false; MachineInstr *MI1 = Arguments->MI; MachineInstr *MI2 = &*NextMII; unsigned RegDstMI1 = MI1->getOperand(0).getReg(); unsigned RegSrcMI1 = MI1->getOperand(1).getReg(); if (!IsMovepSrcRegister(RegSrcMI1)) return false; if (!IsMovepDestinationReg(RegDstMI1)) return false; if (MI2->getOpcode() != Entry.WideOpc()) return false; unsigned RegDstMI2 = MI2->getOperand(0).getReg(); unsigned RegSrcMI2 = MI2->getOperand(1).getReg(); if (!IsMovepSrcRegister(RegSrcMI2)) return false; bool ConsecutiveForward; if (IsMovepDestinationRegPair(RegDstMI1, RegDstMI2)) { ConsecutiveForward = true; } else if (IsMovepDestinationRegPair(RegDstMI2, RegDstMI1)) { ConsecutiveForward = false; } else return false; NextMII = std::next(NextMII); return ReplaceInstruction(MI1, Entry, MI2, ConsecutiveForward); } bool MicroMipsSizeReduce::ReduceXORtoXOR16(ReduceEntryFunArgs *Arguments) { MachineInstr *MI = Arguments->MI; const ReduceEntry &Entry = Arguments->Entry; if (!isMMThreeBitGPRegister(MI->getOperand(0)) || !isMMThreeBitGPRegister(MI->getOperand(1)) || !isMMThreeBitGPRegister(MI->getOperand(2))) return false; if (!(MI->getOperand(0).getReg() == MI->getOperand(2).getReg()) && !(MI->getOperand(0).getReg() == MI->getOperand(1).getReg())) return false; return ReplaceInstruction(MI, Entry); } bool MicroMipsSizeReduce::ReduceMBB(MachineBasicBlock &MBB) { bool Modified = false; MachineBasicBlock::instr_iterator MII = MBB.instr_begin(), E = MBB.instr_end(); MachineBasicBlock::instr_iterator NextMII; // Iterate through the instructions in the basic block for (; MII != E; MII = NextMII) { NextMII = std::next(MII); MachineInstr *MI = &*MII; // Don't reduce bundled instructions or pseudo operations if (MI->isBundle() || MI->isTransient()) continue; // Try to reduce 32-bit instruction into 16-bit instruction Modified |= ReduceMI(MII, NextMII); } return Modified; } bool MicroMipsSizeReduce::ReplaceInstruction(MachineInstr *MI, const ReduceEntry &Entry, MachineInstr *MI2, bool ConsecutiveForward) { enum OperandTransfer OpTransfer = Entry.TransferOperands(); LLVM_DEBUG(dbgs() << "Converting 32-bit: " << *MI); ++NumReduced; if (OpTransfer == OT_OperandsAll) { MI->setDesc(MipsII->get(Entry.NarrowOpc())); LLVM_DEBUG(dbgs() << " to 16-bit: " << *MI); return true; } else { MachineBasicBlock &MBB = *MI->getParent(); const MCInstrDesc &NewMCID = MipsII->get(Entry.NarrowOpc()); DebugLoc dl = MI->getDebugLoc(); MachineInstrBuilder MIB = BuildMI(MBB, MI, dl, NewMCID); switch (OpTransfer) { case OT_Operand2: MIB.add(MI->getOperand(2)); break; case OT_Operands02: { MIB.add(MI->getOperand(0)); MIB.add(MI->getOperand(2)); break; } case OT_OperandsXOR: { if (MI->getOperand(0).getReg() == MI->getOperand(2).getReg()) { MIB.add(MI->getOperand(0)); MIB.add(MI->getOperand(1)); MIB.add(MI->getOperand(2)); } else { MIB.add(MI->getOperand(0)); MIB.add(MI->getOperand(2)); MIB.add(MI->getOperand(1)); } break; } case OT_OperandsMovep: case OT_OperandsLwp: case OT_OperandsSwp: { if (ConsecutiveForward) { MIB.add(MI->getOperand(0)); MIB.add(MI2->getOperand(0)); MIB.add(MI->getOperand(1)); if (OpTransfer == OT_OperandsMovep) MIB.add(MI2->getOperand(1)); else MIB.add(MI->getOperand(2)); } else { // consecutive backward MIB.add(MI2->getOperand(0)); MIB.add(MI->getOperand(0)); MIB.add(MI2->getOperand(1)); if (OpTransfer == OT_OperandsMovep) MIB.add(MI->getOperand(1)); else MIB.add(MI2->getOperand(2)); } LLVM_DEBUG(dbgs() << "and converting 32-bit: " << *MI2 << " to: " << *MIB); MBB.erase_instr(MI); MBB.erase_instr(MI2); return true; } default: llvm_unreachable("Unknown operand transfer!"); } // Transfer MI flags. MIB.setMIFlags(MI->getFlags()); LLVM_DEBUG(dbgs() << " to 16-bit: " << *MIB); MBB.erase_instr(MI); return true; } return false; } bool MicroMipsSizeReduce::runOnMachineFunction(MachineFunction &MF) { Subtarget = &static_cast<const MipsSubtarget &>(MF.getSubtarget()); // TODO: Add support for the subtarget microMIPS32R6. if (!Subtarget->inMicroMipsMode() || !Subtarget->hasMips32r2() || Subtarget->hasMips32r6()) return false; MipsII = static_cast<const MipsInstrInfo *>(Subtarget->getInstrInfo()); bool Modified = false; MachineFunction::iterator I = MF.begin(), E = MF.end(); for (; I != E; ++I) Modified |= ReduceMBB(*I); return Modified; } /// Returns an instance of the MicroMips size reduction pass. FunctionPass *llvm::createMicroMipsSizeReducePass() { return new MicroMipsSizeReduce(); }
33.923559
80
0.672823
URSec
70b251881aebf9669a7c0a84430b4268a17be44e
891
cpp
C++
Sonic.cpp
DaCao/Sonic
0bc327b97560c83cb6cc22b2b2a1e399554194d8
[ "MIT" ]
2
2018-09-19T08:58:06.000Z
2022-03-25T00:42:18.000Z
Sonic.cpp
brandon999/Sonic
2f2b81b94c875b157e195b984a22629a638b2013
[ "MIT" ]
null
null
null
Sonic.cpp
brandon999/Sonic
2f2b81b94c875b157e195b984a22629a638b2013
[ "MIT" ]
null
null
null
// // Sonic.cpp // Demo // // Created by Philadelphia Game Lab on 8/8/14. // Copyright (c) 2014 Philadelphia Game Lab. All rights reserved. // #include "Sonic.h" void Sonic::createWorld() { Sonic::cau = new CustomAudioUnit(); } AudioObj* Sonic::addAudioObject(string wavFileName, VariableForLocation x, VariableForLocation y, VariableForLocation z) { return(Sonic::cau->addAudioObjectInWorld(wavFileName, x, y, z)); } void Sonic::startPlaying() { Sonic::cau->play(); } void Sonic::stopPlaying() { Sonic::cau->stop(); } void Sonic::setPlayerLocation(VariableForLocation x, VariableForLocation y, VariableForLocation z) { Sonic::cau->setPlayerPosition(x, y, z); } void Sonic::setPlayerBearing(float bearing) { Sonic::cau->setPlayerBearing(bearing); } void Sonic::reset() { Sonic::stopPlaying(); delete cau; Sonic::cau = new CustomAudioUnit(); }
18.957447
120
0.695847
DaCao
70b582f0d8201e071d19dfe18081e57325afe730
7,646
cpp
C++
src/object_stores/MongoDBClient.cpp
akougkas/iris
ae8b077afa6cec7ce3ea845dc7caad9b5e105c9d
[ "Apache-2.0" ]
1
2019-04-06T08:43:15.000Z
2019-04-06T08:43:15.000Z
src/object_stores/MongoDBClient.cpp
akougkas/iris
ae8b077afa6cec7ce3ea845dc7caad9b5e105c9d
[ "Apache-2.0" ]
1
2019-04-15T09:49:13.000Z
2019-04-15T09:49:13.000Z
src/object_stores/MongoDBClient.cpp
akougkas/iris
ae8b077afa6cec7ce3ea845dc7caad9b5e105c9d
[ "Apache-2.0" ]
null
null
null
/****************************************************************************** *include files ******************************************************************************/ #include "MongoDBClient.h" #include "../utils/tools/Buffer.h" #include <mpi.h> #include <bsoncxx/builder/basic/document.hpp> #include <mongocxx/logger.hpp> #include <bsoncxx/stdx/make_unique.hpp> /****************************************************************************** *Initialization of static ******************************************************************************/ std::shared_ptr<MongoDBClient> MongoDBClient::instance = nullptr; /****************************************************************************** *Constructors ******************************************************************************/ MongoDBClient::MongoDBClient() :objectID(){ if (init() != OPERATION_SUCCESSFUL) { fprintf(stderr, "MongoDB failed to initialize!\n"); exit(-1); } } /****************************************************************************** *Destructor ******************************************************************************/ MongoDBClient::~MongoDBClient() {} /****************************************************************************** *Init function ******************************************************************************/ int MongoDBClient::init() { #ifdef TIMER Timer timer = Timer(); timer.startTime(); #endif int rank=0; MPI_Comm_rank ( MPI_COMM_WORLD, &rank); class noop_logger : public mongocxx::logger { public: virtual void operator()(mongocxx::log_level, mongocxx::stdx::string_view, mongocxx::stdx::string_view) noexcept {} }; /* Setup the MongoDB client */ mongocxx::instance instance{mongocxx::stdx::make_unique<noop_logger>()}; auto uri = mongocxx::uri{ConfigurationManager::getInstance()->MONGO_URI}; client = mongocxx::client{uri}; /* make sure the client is OK */ if (!client) { fprintf(stderr, "Cannot create MongoDB client.\n"); return MONGO_CLIENT_CREATION_FAILED; } mongocxx::database db = client[MONGO_DATABASE]; if (!db) { fprintf(stderr, "Cannot connect to IRIS MongoDB database.\n"); return MONGO_DB_CONNECTION_FAILED; } mongocxx::collection file; filename = MONGO_COLLECTION; if(rank==0) { file = client.database(MONGO_DATABASE).has_collection(filename) ? db.collection(filename) : db.create_collection(filename); std::string enableShardingCmd = "/home/anthony/Dropbox/Projects/iris/scripts/shardCollection.sh " + MONGO_DATABASE + " " + filename; system(enableShardingCmd.c_str()); } MPI_Barrier(MPI_COMM_WORLD); file = db.collection(filename); if (!file) { return MONGO_COLLECTION_CREATION_FAILED; } #ifdef DEBUG printf("MongoDB client created.\n\n"); #endif /* DEBUG*/ #ifdef TIMER timer.endTime(__FUNCTION__); #endif return OPERATION_SUCCESSFUL; } /****************************************************************************** *Interface ******************************************************************************/ int MongoDBClient::get(std::shared_ptr<Key> &key) { #ifdef TIMER Timer timer = Timer(); timer.startTime(); #endif try{ //std::cout<<"get key " << key->name<< " size "<< key->size<<"\n"; /*retrieve the unique objectID from map*/ bsoncxx::oid insertedID; mongocxx::collection file = client[MONGO_DATABASE].collection(filename); auto oidIterator = objectID.find(key->name); if(oidIterator == objectID.end()) return MONGO_GET_NOT_FOUND; else insertedID = bsoncxx::oid{mongocxx::stdx::string_view{oidIterator->second}}; // Create the query filter using bsoncxx::builder::stream::finalize; bsoncxx::builder::stream::document filter; filter << "_id" << bsoncxx::oid{mongocxx::stdx::string_view{insertedID.to_string()}} << finalize; // Execute the query to find the document auto getDoc = file.find_one(filter.view()); if(getDoc){ bsoncxx::document::element value = getDoc->view()["value"]; key->size = value.get_utf8().value.to_string().length(); key->data = (void *) value.get_utf8().value.to_string().c_str(); } else{ std::cout << "Document not found!" << "\n"; } }catch (const std::exception& xcp) { std::cout << "failed: " << xcp.what() << "\n"; return MONGO_GET_OPERATION_FAILED; } #ifdef TIMER timer.endTime(__FUNCTION__); #endif return OPERATION_SUCCESSFUL; } int MongoDBClient::put(std::shared_ptr<Key> &key) { #ifdef TIMER Timer timer = Timer(); timer.startTime(); #endif int status = 0; std::shared_ptr<Key> originalKey = std::shared_ptr<Key>(new Key()); originalKey->name = key->name; originalKey->offset = key->offset; originalKey->size = key->size; originalKey->data = key->data; Buffer dataBuffer; mongocxx::collection file = client[MONGO_DATABASE].collection(filename); try{ if (key->offset == 0) { //std::cout<<"aligned key " << key->name<< " size "<< key->size<<"\n"; if (key->size != ConfigurationManager::getInstance()->MAX_OBJ_SIZE) { status = get(key); if (status == OPERATION_SUCCESSFUL && key->size > originalKey->size) { dataBuffer = Buffer(key->data, key->size); dataBuffer.assign(originalKey->data, originalKey->size); key->data = dataBuffer.data(); } } } else { //std::cout<<"merge key " << key->name<< " size "<< key->size<<"\n"; status = get(key); if (status == OPERATION_SUCCESSFUL) { if (key->size > originalKey->offset + originalKey->size) { std::memcpy((char *) key->data + originalKey->offset, originalKey->data, originalKey->size); } else { if(key->size<originalKey->offset){ dataBuffer = Buffer(key->data, key->size); }else{ dataBuffer = Buffer(key->data, originalKey->offset); } dataBuffer.append(originalKey->data, originalKey->size); key->offset = 0; key->size = dataBuffer.size(); key->data = dataBuffer.data(); } } } //std::cout<<"put key " << key->name<< " size "<< key->size<<"\n"; //Using the basic builder, create the kv pair or document auto document = bsoncxx::builder::basic::document{}; using bsoncxx::builder::basic::kvp; std::string data((const char*)key->data,key->size); std::string keyName(key->name,std::strlen(key->name)); //std::cout<<"KeyName :"<<keyName<<"\n"; document.append(kvp("key",keyName),kvp("value",data)); //adding the created key-value pair to the collection bsoncxx::document::view putView = document.view();//get the view //retrieve the unique objectID from map auto oidIterator = objectID.find(keyName); if(oidIterator != objectID.end()){ objectID.erase(oidIterator); } auto add = file.insert_one(putView);//insert it to collection if (!add) { std::cout << "Unacknowledged write. No id available." << "\n"; return MONGO_PUT_OPERATION_FAILED; } if (add->inserted_id().type() == bsoncxx::type::k_oid) { bsoncxx::oid id = add->inserted_id().get_oid().value; objectID.insert({keyName, id.to_string()}); } else std::cout << "Inserted id was not an OID type" << "\n"; }catch (const std::exception& xcp) { std::cout << "Exception with failed: " << xcp.what() << "\n"; return MONGO_PUT_OPERATION_FAILED; } #ifdef TIMER timer.endTime(__FUNCTION__); #endif key->offset=originalKey->offset; key->size=originalKey->size; return OPERATION_SUCCESSFUL; } int MongoDBClient::remove(std::shared_ptr<Key> &key) { return OPERATION_SUCCESSFUL; }
36.759615
101
0.575595
akougkas
70b6622b7b0545debb49eb0ae1152d2d8ed7c1d3
1,567
hpp
C++
include/oalplus/error/al.hpp
Extrunder/oglplus
c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791
[ "BSL-1.0" ]
459
2016-03-16T04:11:37.000Z
2022-03-31T08:05:21.000Z
include/oalplus/error/al.hpp
Extrunder/oglplus
c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791
[ "BSL-1.0" ]
2
2016-08-08T18:26:27.000Z
2017-05-08T23:42:22.000Z
include/oalplus/error/al.hpp
Extrunder/oglplus
c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791
[ "BSL-1.0" ]
47
2016-05-31T15:55:52.000Z
2022-03-28T14:49:40.000Z
/** * @file oalplus/error/al.hpp * @brief Declaration of OALplus' OpenAL exceptions * * @author Matus Chochlik * * Copyright 2010-2015 Matus Chochlik. Distributed under the Boost * Software License, Version 1.0. (See accompanying file * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #pragma once #ifndef OALPLUS_ERROR_AL_1107121317_HPP #define OALPLUS_ERROR_AL_1107121317_HPP #include <oalplus/error/basic.hpp> #include <oalplus/enums/al_error_code.hpp> namespace oalplus { class ErrorAL : public Error { public: static const char* Message(ALenum error_code) { return ::alGetString(error_code); } ErrorAL(const char* message) : Error(message) { } ALErrorCode Code(void) const OALPLUS_NOEXCEPT(true) { return ALErrorCode(_code); } }; #define OALPLUS_ALFUNC_CHECK(FUNC_NAME, ERROR, ERROR_INFO)\ OALPLUS_HANDLE_ERROR_IF(\ error_code != AL_NO_ERROR,\ alGetError(),\ ERROR::Message(error_code),\ ERROR,\ ERROR_INFO.\ ALFunc(FUNC_NAME)\ ) #define OALPLUS_CHECK(ALFUNC, ERROR, ERROR_INFO) \ OALPLUS_ALFUNC_CHECK(#ALFUNC, ERROR, ERROR_INFO) #define OALPLUS_CHECK_SIMPLE(ALFUNC) \ OALPLUS_CHECK(ALFUNC, ErrorAL, NoInfo()) #if !OALPLUS_LOW_PROFILE #define OALPLUS_VERIFY(ALFUNC, ERROR, ERROR_INFO) \ OALPLUS_CHECK(ALFUNC, ERROR, ERROR_INFO) #else #define OALPLUS_VERIFY(ALFUNC, ERROR, ERROR_INFO) #endif #define OALPLUS_VERIFY_SIMPLE(ALFUNC) \ OALPLUS_CHECK(ALFUNC, ErrorAL, NoInfo()) #define OALPLUS_IGNORE(ALLIB, PARAM) ::ALLIB ## GetError(); } // namespace oalplus #endif // include guard
21.763889
68
0.749202
Extrunder
70baa52af3d2484fd19e3bffe73c7ab1b48b33c6
11,777
cpp
C++
src/factory/ImageFactory.cpp
menshiva/ascii-art-terminal
798a479d691de462d5fdfc1e4b6ed9d603d80059
[ "Apache-2.0" ]
1
2021-12-05T21:19:17.000Z
2021-12-05T21:19:17.000Z
src/factory/ImageFactory.cpp
menshiva/ascii-art-terminal
798a479d691de462d5fdfc1e4b6ed9d603d80059
[ "Apache-2.0" ]
null
null
null
src/factory/ImageFactory.cpp
menshiva/ascii-art-terminal
798a479d691de462d5fdfc1e4b6ed9d603d80059
[ "Apache-2.0" ]
null
null
null
#include "ImageFactory.hpp" ImageFactory::ImageFactory() : grayscaleLevel(AsciiConsts::DEFAULT_GRAYSCALE_LEVEL) {} ImageFactory::~ImageFactory() { for (Image *img : images) delete img; } const std::vector<Image *> &ImageFactory::getAllImages() const { return images; } bool ImageFactory::readImage() { // if at least 1 image was added successfully bool isImageRead = false; while (true) { fs::path path; std::string pathStr; std::cout << "\n" << ConsoleConsts::TITLE_SYMBOL << ConsoleConsts::ENTER_IMAGE_PATH << "\n" << std::endl; while (true) { pathStr.clear(); std::cin.clear(); std::cout << ConsoleConsts::INPUT_SYMBOLS; // read path std::getline(std::cin, pathStr); Utils::trim(pathStr); if (pathStr.empty()) continue; else if (pathStr == "q") return isImageRead; // if pathStr contains leading and trailing apostrophes if (pathStr.front() == '\'') pathStr.erase(pathStr.begin()); if (pathStr.back() == '\'') pathStr.erase(pathStr.end() - 1); path = fs::path(pathStr); if (!fs::exists(path)) { std::cout << "\n" << ConsoleConsts::TITLE_SYMBOL << ConsoleConsts::ERROR_FILE_NOT_FOUND << " " << ConsoleConsts::TRY_ANOTHER_FILE << "\n" << std::endl; continue; } if (path.is_relative()) { std::cout << "\n" << ConsoleConsts::TITLE_SYMBOL << ConsoleConsts::ERROR_PATH_RELATIVE << " " << ConsoleConsts::TRY_AGAIN << "\n" << std::endl; continue; } // check file suffix and normalize it if (path.extension() == ".jpg" || path.extension() == ".JPG" || path.extension() == ".JPEG") path.replace_extension(".jpeg"); else if (path.extension() == ".PPM") path.replace_extension(".ppm"); else if (path.extension() != ".jpeg" && path.extension() != ".ppm") { std::cout << "\n" << ConsoleConsts::TITLE_SYMBOL << ConsoleConsts::ERROR_FILE_UNSUPPORTED << " " << ConsoleConsts::TRY_ANOTHER_FILE << "\n" << std::endl; continue; } // check if file can be opened std::ifstream imgStream(pathStr); if (imgStream.bad() || !imgStream.is_open()) { std::cout << "\n" << ConsoleConsts::TITLE_SYMBOL << ConsoleConsts::ERROR_FILE_READ_FAIL << " " << ConsoleConsts::TRY_ANOTHER_FILE << "\n" << std::endl; continue; } imgStream.close(); break; } // initialize image Image *newImg; if (path.extension() == ".jpeg") newImg = new JPEGImage(pathStr); else newImg = new PPMImage(pathStr); if (!newImg->loadFromFile()) { std::cout << "\n" << ConsoleConsts::TITLE_SYMBOL << ConsoleConsts::ERROR_FILE_BAD_CODING << " " << ConsoleConsts::TRY_ANOTHER_FILE << "\n" << std::endl; delete newImg; continue; } std::cout << "\n" << ConsoleConsts::TITLE_SYMBOL << ConsoleConsts::STATUS_CONVERTING_WAIT << std::endl; newImg->convertToAscii(grayscaleLevel); images.push_back(newImg); std::cout << ConsoleConsts::TITLE_SYMBOL << ConsoleConsts::STATUS_CONVERTING_SUCCESS << std::endl; isImageRead = true; } } void ImageFactory::removeImage(Image *image) { auto eraseIt = std::find(images.begin(), images.end(), image); if (eraseIt != images.end()) images.erase(eraseIt); delete image; } bool ImageFactory::readGrayscaleLevel() { std::string level; std::cout << "\n" << ConsoleConsts::TITLE_SYMBOL << ConsoleConsts::ENTER_GRAY_LEVEL << "\n" << std::endl; // input new grayscaleLevel while (true) { level.clear(); std::cin.clear(); std::cout << ConsoleConsts::INPUT_SYMBOLS; std::getline(std::cin, level); if (!level.empty()) break; } if (level == "q") return false; // check if new grayscaleLevel is not the same as the old bool isChanged = false; if (level == "d") { if (grayscaleLevel != AsciiConsts::DEFAULT_GRAYSCALE_LEVEL) { isChanged = true; grayscaleLevel = AsciiConsts::DEFAULT_GRAYSCALE_LEVEL; } } else { if (grayscaleLevel != level) { isChanged = true; grayscaleLevel = level; } } if (!isChanged) return false; // convert all images based on new grayscaleLevel std::cout << "\n" << ConsoleConsts::TITLE_SYMBOL << ConsoleConsts::STATUS_CONVERTING_WAIT << std::endl; for (Image *img : images) img->convertToAscii(grayscaleLevel); std::cout << ConsoleConsts::TITLE_SYMBOL << ConsoleConsts::STATUS_CONVERTING_SUCCESS << " " << ConsoleConsts::STATUS_CONVERTING_EXIT << std::endl; getchar(); return true; } bool ImageFactory::applyEffect(Image *image) { size_t chosenIndex; std::cout << "\n" << ConsoleConsts::TITLE_SYMBOL << ConsoleConsts::PICK_EFFECT << "\n" << std::endl; while (true) { // print all supported effects std::cout << "1) " << ((image->hasContrast()) ? "Remove " : "Add ") << "contrast effect\n" << "2) " << ((image->hasNegative()) ? "Remove " : "Add ") << "negative effect\n" << "3) " << ((image->hasSharpen()) ? "Remove " : "Add ") << "sharpen effect\n" << std::endl; std::string str; std::cin.clear(); std::cout << ConsoleConsts::INPUT_SYMBOLS; std::getline(std::cin, str); if (str.empty()) continue; else if (str == "q") return false; // read index of the chosen effect if (sscanf(str.c_str(), "%zu", &chosenIndex) != 1) { std::cout << "\n" << ConsoleConsts::TITLE_SYMBOL << ConsoleConsts::ERROR_IMAGE_NOT_INDEX << " " << ConsoleConsts::TRY_AGAIN << "\n" << std::endl; continue; } if (chosenIndex < 1 || chosenIndex > 3) { std::cout << "\n" << ConsoleConsts::TITLE_SYMBOL << ConsoleConsts::ERROR_IMAGE_BAD_INDEX << " " << ConsoleConsts::TRY_AGAIN << "\n" << std::endl; continue; } break; } switch (chosenIndex) { case 1: image->toggleContrast(); break; case 2: image->toggleNegative(); break; case 3: image->toggleSharpen(); break; default: break; } std::cout << "\n" << ConsoleConsts::TITLE_SYMBOL << ConsoleConsts::STATUS_CONVERTING_WAIT << std::endl; image->convertToAscii(grayscaleLevel); std::cout << ConsoleConsts::TITLE_SYMBOL << ConsoleConsts::STATUS_CONVERTING_SUCCESS << " " << ConsoleConsts::STATUS_CONVERTING_EXIT << std::endl; getchar(); return true; } void ImageFactory::exportImage(const Image *image) { fs::path path; std::string pathStr; std::cout << "\n" << ConsoleConsts::TITLE_SYMBOL << ConsoleConsts::ENTER_TXT_PATH << "\n" << std::endl; while (true) { pathStr.clear(); std::cin.clear(); std::cout << ConsoleConsts::INPUT_SYMBOLS; // read path std::getline(std::cin, pathStr); Utils::trim(pathStr); if (pathStr.empty()) continue; else if (pathStr == "q") return; // if pathStr contains leading and trailing apostrophes if (pathStr.front() == '\'') pathStr.erase(pathStr.begin()); if (pathStr.back() == '\'') pathStr.erase(pathStr.end() - 1); path = fs::path(pathStr); if (fs::exists(path)) { std::cout << "\n" << ConsoleConsts::TITLE_SYMBOL << ConsoleConsts::ERROR_FILE_EXISTS << " " << ConsoleConsts::TRY_ANOTHER_FILE << "\n" << std::endl; continue; } if (path.is_relative()) { std::cout << "\n" << ConsoleConsts::TITLE_SYMBOL << ConsoleConsts::ERROR_PATH_RELATIVE << " " << ConsoleConsts::TRY_AGAIN << "\n" << std::endl; continue; } if (path.extension() != ".txt") { std::cout << "\n" << ConsoleConsts::TITLE_SYMBOL << ConsoleConsts::ERROR_FILE_UNSUPPORTED << " " << ConsoleConsts::TRY_ANOTHER_FILE << "\n" << std::endl; continue; } // if directories in path doesn't exist, create them! if (!fs::exists(path.root_directory())) fs::create_directories(path); break; } std::cout << "\n" << ConsoleConsts::TITLE_SYMBOL << ConsoleConsts::STATUS_EXPORT_WAIT << std::endl; // print art to file auto exportData = image->getRawAsciiData(); std::ofstream outfile(pathStr); for (auto &line : exportData) outfile << line << "\n"; outfile.flush(); outfile.close(); std::cout << ConsoleConsts::TITLE_SYMBOL << ConsoleConsts::STATUS_EXPORT_SUCCESS << " " << ConsoleConsts::STATUS_CONVERTING_EXIT << std::endl; getchar(); } Image *ImageFactory::chooseImageFromList(const char *firstMessage) const { size_t chosenIndex; std::cout << "\n" << ConsoleConsts::TITLE_SYMBOL << firstMessage << "\n" << std::endl; while (true) { // print loaded images paths for (size_t i = 0; i < images.size(); ++i) std::cout << i + 1 << ") " << images[i]->getPath() << "\n"; std::cout << std::endl; std::string path; std::cin.clear(); std::cout << ConsoleConsts::INPUT_SYMBOLS; std::getline(std::cin, path); if (path.empty()) continue; else if (path == "q") return nullptr; // read index of chosen path if (sscanf(path.c_str(), "%zu", &chosenIndex) != 1) { std::cout << "\n" << ConsoleConsts::TITLE_SYMBOL << ConsoleConsts::ERROR_IMAGE_NOT_INDEX << " " << ConsoleConsts::TRY_AGAIN << "\n" << std::endl; continue; } if (chosenIndex < 1 || chosenIndex > images.size()) { std::cout << "\n" << ConsoleConsts::TITLE_SYMBOL << ConsoleConsts::ERROR_IMAGE_BAD_INDEX << " " << ConsoleConsts::TRY_AGAIN << "\n" << std::endl; continue; } break; } return images[chosenIndex - 1]; }
33.841954
113
0.491127
menshiva
70bd26fd4b5b5c4953cf605176a667339b759959
490
hpp
C++
Tools/RegistersGenerator/Msp432P401Y/BitsField/compe1bitsfield.hpp
snorkysnark/CortexLib
0db035332ebdfbebf21ca36e5e04b78a5a908a49
[ "MIT" ]
22
2019-09-07T22:38:01.000Z
2022-01-31T21:35:55.000Z
Tools/RegistersGenerator/Msp432P401Y/BitsField/compe1bitsfield.hpp
snorkysnark/CortexLib
0db035332ebdfbebf21ca36e5e04b78a5a908a49
[ "MIT" ]
null
null
null
Tools/RegistersGenerator/Msp432P401Y/BitsField/compe1bitsfield.hpp
snorkysnark/CortexLib
0db035332ebdfbebf21ca36e5e04b78a5a908a49
[ "MIT" ]
9
2019-09-22T11:26:24.000Z
2022-03-21T10:53:15.000Z
/******************************************************************************* * Filename : compe1bitsfield.hpp * * Details : Enumerations related with COMP_E1 peripheral. This header file * is auto-generated for MSP432P401Y device. * * *******************************************************************************/ #if !defined(COMPE1ENUMS_HPP) #define COMPE1ENUMS_HPP #include "fieldvalue.hpp" //for BitsField #endif //#if !defined(COMPE1ENUMS_HPP)
30.625
80
0.465306
snorkysnark
70bd544850adddc8f8af80216c2266d4d4250718
5,078
cpp
C++
test/unit-tests/coap-dispatcher-test.cpp
moducom/mc-coap
d77e5be89d6f7a08ecfa1929aaa49cb6ce2ae2ae
[ "MIT" ]
1
2018-06-01T01:27:57.000Z
2018-06-01T01:27:57.000Z
test/unit-tests/coap-dispatcher-test.cpp
moducom/mc-coap
d77e5be89d6f7a08ecfa1929aaa49cb6ce2ae2ae
[ "MIT" ]
null
null
null
test/unit-tests/coap-dispatcher-test.cpp
moducom/mc-coap
d77e5be89d6f7a08ecfa1929aaa49cb6ce2ae2ae
[ "MIT" ]
null
null
null
// // Created by malachi on 12/27/17. // // 12/4/2019: OBSOLETE - using prior / unrealized dispatcher flavor (function pointer/virtual based) // rather than newer embr subject-observer style #include <catch.hpp> #include <obsolete/coap-dispatcher.h> #include "coap-uripath-dispatcher.h" #include "test-data.h" #include "test-observer.h" #include "coap/decoder/subject.hpp" using namespace embr::coap; using namespace embr::coap::experimental; using namespace moducom::pipeline; extern dispatcher_handler_factory_fn test_sub_factories[]; template <class TRequestContext> IDecoderObserver<TRequestContext>* context_handler_factory(TRequestContext& ctx) { #ifdef FEATURE_MCCOAP_INLINE_TOKEN return new (ctx) ContextDispatcherHandler<TRequestContext>(ctx); #else static moducom::dynamic::PoolBase<embr::coap::layer2::Token, 8> token_pool; return new (ctx.handler_memory.data()) ContextDispatcherHandler(ctx, token_pool); #endif } template <class TRequestContext> IDecoderObserver<TRequestContext>* test_buffer16bitdelta_observer(TRequestContext& ctx) { return new (ctx) Buffer16BitDeltaObserver<TRequestContext>(IsInterestedBase::Never); } /* // Does not work because compiler struggles to cast back down to IMessageObserver // for some reason template <const char* uri_path, IMessageObserver* observer> IDispatcherHandler* uri_helper3(MemoryChunk chunk) { return new (chunk.data()) UriPathDispatcherHandler(uri_path, *observer); } */ template <typename T> struct array_helper { static CONSTEXPR int count() { return 0; } }; template <typename T, ptrdiff_t N> struct array_helper<T[N]> { typedef T element_t; static CONSTEXPR ptrdiff_t count() { return N; } }; /* template <class TArray> int _array_helper_count(TArray array) { array_helper<TArray, > array_descriptor; return array_helper<TArray>::count(); } */ template <typename T, int size> CONSTEXPR int _array_helper_count(T (&) [size]) { return size; } template <typename T, int size> CONSTEXPR T* _array_helper_contents(T (&t) [size]) { return t; } /* template <typename T, int size> CONSTEXPR dispatcher_handler_factory_fn uri_helper_helper(T a [size], const char* name) { return &uri_plus_factory_dispatcher<TEST_FACTORY4_NAME, a, size>; }; */ template <class TRequestContext> IDecoderObserver<TRequestContext>* test_single_uri_observer(TRequestContext& ctx) { // FIX: Clumsy, but should be effective for now; ensures order of allocation is correct // so that later deallocation for objstack doesn't botch void* buffer1 = ctx.objstack.alloc(sizeof(SingleUriPathObserver<TRequestContext>)); FactoryDispatcherHandler<TRequestContext>* fdh = new (ctx) FactoryDispatcherHandler<TRequestContext>( ctx, test_sub_factories, 1); return new (buffer1) SingleUriPathObserver<TRequestContext>("v1", *fdh); } extern CONSTEXPR char STR_TEST[] = "TEST"; dispatcher_handler_factory_fn test_factories[] = { context_handler_factory, test_buffer16bitdelta_observer, test_single_uri_observer, uri_plus_factory_dispatcher<STR_TEST, test_sub_factories, 1> }; template <class TRequestContext> class TestDispatcherHandler2 : public DecoderObserverBase<TRequestContext> { public: void on_payload(const MemoryChunk::readonly_t& payload_part, bool last_chunk) OVERRIDE { REQUIRE(payload_part[0] == 0x10); REQUIRE(payload_part[1] == 0x11); REQUIRE(payload_part[2] == 0x12); REQUIRE(payload_part.length() == 7); } }; extern CONSTEXPR char POS_HANDLER_URI[] = "POS"; //extern TestDispatcherHandler2<> pos_handler; //TestDispatcherHandler2<> pos_handler; dispatcher_handler_factory_fn test_sub_factories[] = { uri_plus_observer_dispatcher<POS_HANDLER_URI, TestDispatcherHandler2<ObserverContext> > }; TEST_CASE("CoAP dispatcher tests", "[coap-dispatcher]") { SECTION("Dispatcher Factory") { //MemoryChunk chunk(buffer_plausible, sizeof(buffer_plausible)); estd::const_buffer chunk(buffer_plausible); moducom::pipeline::layer3::MemoryChunk<512> dispatcherBuffer; ObserverContext context(dispatcherBuffer); FactoryDispatcherHandler<ObserverContext> fdh(context, test_factories); DecoderSubjectBase<IDecoderObserver<ObserverContext> & > decoder_subject(fdh); decoder_subject.dispatch(chunk); } SECTION("Array experimentation") { int array[] = { 1, 2, 3 }; int count = _array_helper_count(array); REQUIRE(count == 3); } SECTION("Size ofs") { int size1 = sizeof(IMessageObserver); #ifdef FEATURE_DISCRETE_OBSERVERS int size2 = sizeof(IOptionAndPayloadObserver); int size3 = sizeof(IOptionObserver); #endif int size4 = sizeof(IDecoderObserver<>); int size5 = sizeof(IIsInterested); int size6 = sizeof(DecoderObserverBase<>); int size7 = sizeof(SingleUriPathObserver<IncomingContext<uint32_t> >); int size8 = sizeof(FactoryDispatcherHandler<>); } }
27.748634
100
0.729618
moducom
70bd62b1b26a7f3b488c934a4cca26b575fc39fb
9,929
cc
C++
src/dsp/arm/intrapred_filter_neon.cc
jbeich/libgav1
a65020e665c2cf76651b50b6626c1baa61a5c718
[ "Apache-2.0" ]
null
null
null
src/dsp/arm/intrapred_filter_neon.cc
jbeich/libgav1
a65020e665c2cf76651b50b6626c1baa61a5c718
[ "Apache-2.0" ]
null
null
null
src/dsp/arm/intrapred_filter_neon.cc
jbeich/libgav1
a65020e665c2cf76651b50b6626c1baa61a5c718
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 The libgav1 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 // // 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 "src/dsp/intrapred_filter.h" #include "src/utils/cpu.h" #if LIBGAV1_ENABLE_NEON #include <arm_neon.h> #include <cassert> #include <cstddef> #include <cstdint> #include "src/dsp/arm/common_neon.h" #include "src/dsp/constants.h" #include "src/dsp/dsp.h" #include "src/utils/common.h" namespace libgav1 { namespace dsp { namespace low_bitdepth { namespace { // Transpose kFilterIntraTaps and convert the first row to unsigned values. // // With the previous orientation we were able to multiply all the input values // by a single tap. This required that all the input values be in one vector // which requires expensive set up operations (shifts, vext, vtbl). All the // elements of the result needed to be summed (easy on A64 - vaddvq_s16) but // then the shifting, rounding, and clamping was done in GP registers. // // Switching to unsigned values allows multiplying the 8 bit inputs directly. // When one value was negative we needed to vmovl_u8 first so that the results // maintained the proper sign. // // We take this into account when summing the values by subtracting the product // of the first row. alignas(8) constexpr uint8_t kTransposedTaps[kNumFilterIntraPredictors][7][8] = {{{6, 5, 3, 3, 4, 3, 3, 3}, // Original values are negative. {10, 2, 1, 1, 6, 2, 2, 1}, {0, 10, 1, 1, 0, 6, 2, 2}, {0, 0, 10, 2, 0, 0, 6, 2}, {0, 0, 0, 10, 0, 0, 0, 6}, {12, 9, 7, 5, 2, 2, 2, 3}, {0, 0, 0, 0, 12, 9, 7, 5}}, {{10, 6, 4, 2, 10, 6, 4, 2}, // Original values are negative. {16, 0, 0, 0, 16, 0, 0, 0}, {0, 16, 0, 0, 0, 16, 0, 0}, {0, 0, 16, 0, 0, 0, 16, 0}, {0, 0, 0, 16, 0, 0, 0, 16}, {10, 6, 4, 2, 0, 0, 0, 0}, {0, 0, 0, 0, 10, 6, 4, 2}}, {{8, 8, 8, 8, 4, 4, 4, 4}, // Original values are negative. {8, 0, 0, 0, 4, 0, 0, 0}, {0, 8, 0, 0, 0, 4, 0, 0}, {0, 0, 8, 0, 0, 0, 4, 0}, {0, 0, 0, 8, 0, 0, 0, 4}, {16, 16, 16, 16, 0, 0, 0, 0}, {0, 0, 0, 0, 16, 16, 16, 16}}, {{2, 1, 1, 0, 1, 1, 1, 1}, // Original values are negative. {8, 3, 2, 1, 4, 3, 2, 2}, {0, 8, 3, 2, 0, 4, 3, 2}, {0, 0, 8, 3, 0, 0, 4, 3}, {0, 0, 0, 8, 0, 0, 0, 4}, {10, 6, 4, 2, 3, 4, 4, 3}, {0, 0, 0, 0, 10, 6, 4, 3}}, {{12, 10, 9, 8, 10, 9, 8, 7}, // Original values are negative. {14, 0, 0, 0, 12, 1, 0, 0}, {0, 14, 0, 0, 0, 12, 0, 0}, {0, 0, 14, 0, 0, 0, 12, 1}, {0, 0, 0, 14, 0, 0, 0, 12}, {14, 12, 11, 10, 0, 0, 1, 1}, {0, 0, 0, 0, 14, 12, 11, 9}}}; void FilterIntraPredictor_NEON(void* LIBGAV1_RESTRICT const dest, ptrdiff_t stride, const void* LIBGAV1_RESTRICT const top_row, const void* LIBGAV1_RESTRICT const left_column, FilterIntraPredictor pred, int width, int height) { const auto* const top = static_cast<const uint8_t*>(top_row); const auto* const left = static_cast<const uint8_t*>(left_column); assert(width <= 32 && height <= 32); auto* dst = static_cast<uint8_t*>(dest); uint8x8_t transposed_taps[7]; for (int i = 0; i < 7; ++i) { transposed_taps[i] = vld1_u8(kTransposedTaps[pred][i]); } uint8_t relative_top_left = top[-1]; const uint8_t* relative_top = top; uint8_t relative_left[2] = {left[0], left[1]}; int y = 0; do { uint8_t* row_dst = dst; int x = 0; do { uint16x8_t sum = vdupq_n_u16(0); const uint16x8_t subtrahend = vmull_u8(transposed_taps[0], vdup_n_u8(relative_top_left)); for (int i = 1; i < 5; ++i) { sum = vmlal_u8(sum, transposed_taps[i], vdup_n_u8(relative_top[i - 1])); } for (int i = 5; i < 7; ++i) { sum = vmlal_u8(sum, transposed_taps[i], vdup_n_u8(relative_left[i - 5])); } const int16x8_t sum_signed = vreinterpretq_s16_u16(vsubq_u16(sum, subtrahend)); const int16x8_t sum_shifted = vrshrq_n_s16(sum_signed, 4); uint8x8_t sum_saturated = vqmovun_s16(sum_shifted); StoreLo4(row_dst, sum_saturated); StoreHi4(row_dst + stride, sum_saturated); // Progress across relative_top_left = relative_top[3]; relative_top += 4; relative_left[0] = row_dst[3]; relative_left[1] = row_dst[3 + stride]; row_dst += 4; x += 4; } while (x < width); // Progress down. relative_top_left = left[y + 1]; relative_top = dst + stride; relative_left[0] = left[y + 2]; relative_left[1] = left[y + 3]; dst += 2 * stride; y += 2; } while (y < height); } void Init8bpp() { Dsp* const dsp = dsp_internal::GetWritableDspTable(kBitdepth8); assert(dsp != nullptr); dsp->filter_intra_predictor = FilterIntraPredictor_NEON; } } // namespace } // namespace low_bitdepth //------------------------------------------------------------------------------ #if LIBGAV1_MAX_BITDEPTH >= 10 namespace high_bitdepth { namespace { alignas(kMaxAlignment) constexpr int16_t kTransposedTaps[kNumFilterIntraPredictors][7][8] = { {{-6, -5, -3, -3, -4, -3, -3, -3}, {10, 2, 1, 1, 6, 2, 2, 1}, {0, 10, 1, 1, 0, 6, 2, 2}, {0, 0, 10, 2, 0, 0, 6, 2}, {0, 0, 0, 10, 0, 0, 0, 6}, {12, 9, 7, 5, 2, 2, 2, 3}, {0, 0, 0, 0, 12, 9, 7, 5}}, {{-10, -6, -4, -2, -10, -6, -4, -2}, {16, 0, 0, 0, 16, 0, 0, 0}, {0, 16, 0, 0, 0, 16, 0, 0}, {0, 0, 16, 0, 0, 0, 16, 0}, {0, 0, 0, 16, 0, 0, 0, 16}, {10, 6, 4, 2, 0, 0, 0, 0}, {0, 0, 0, 0, 10, 6, 4, 2}}, {{-8, -8, -8, -8, -4, -4, -4, -4}, {8, 0, 0, 0, 4, 0, 0, 0}, {0, 8, 0, 0, 0, 4, 0, 0}, {0, 0, 8, 0, 0, 0, 4, 0}, {0, 0, 0, 8, 0, 0, 0, 4}, {16, 16, 16, 16, 0, 0, 0, 0}, {0, 0, 0, 0, 16, 16, 16, 16}}, {{-2, -1, -1, -0, -1, -1, -1, -1}, {8, 3, 2, 1, 4, 3, 2, 2}, {0, 8, 3, 2, 0, 4, 3, 2}, {0, 0, 8, 3, 0, 0, 4, 3}, {0, 0, 0, 8, 0, 0, 0, 4}, {10, 6, 4, 2, 3, 4, 4, 3}, {0, 0, 0, 0, 10, 6, 4, 3}}, {{-12, -10, -9, -8, -10, -9, -8, -7}, {14, 0, 0, 0, 12, 1, 0, 0}, {0, 14, 0, 0, 0, 12, 0, 0}, {0, 0, 14, 0, 0, 0, 12, 1}, {0, 0, 0, 14, 0, 0, 0, 12}, {14, 12, 11, 10, 0, 0, 1, 1}, {0, 0, 0, 0, 14, 12, 11, 9}}}; void FilterIntraPredictor_NEON(void* LIBGAV1_RESTRICT const dest, ptrdiff_t stride, const void* LIBGAV1_RESTRICT const top_row, const void* LIBGAV1_RESTRICT const left_column, FilterIntraPredictor pred, int width, int height) { const auto* const top = static_cast<const uint16_t*>(top_row); const auto* const left = static_cast<const uint16_t*>(left_column); assert(width <= 32 && height <= 32); auto* dst = static_cast<uint16_t*>(dest); stride >>= 1; int16x8_t transposed_taps[7]; for (int i = 0; i < 7; ++i) { transposed_taps[i] = vld1q_s16(kTransposedTaps[pred][i]); } uint16_t relative_top_left = top[-1]; const uint16_t* relative_top = top; uint16_t relative_left[2] = {left[0], left[1]}; int y = 0; do { uint16_t* row_dst = dst; int x = 0; do { int16x8_t sum = vmulq_s16(transposed_taps[0], vreinterpretq_s16_u16(vdupq_n_u16(relative_top_left))); for (int i = 1; i < 5; ++i) { sum = vmlaq_s16(sum, transposed_taps[i], vreinterpretq_s16_u16(vdupq_n_u16(relative_top[i - 1]))); } for (int i = 5; i < 7; ++i) { sum = vmlaq_s16(sum, transposed_taps[i], vreinterpretq_s16_u16(vdupq_n_u16(relative_left[i - 5]))); } const int16x8_t sum_shifted = vrshrq_n_s16(sum, 4); const uint16x8_t sum_saturated = vminq_u16( vreinterpretq_u16_s16(vmaxq_s16(sum_shifted, vdupq_n_s16(0))), vdupq_n_u16((1 << kBitdepth10) - 1)); vst1_u16(row_dst, vget_low_u16(sum_saturated)); vst1_u16(row_dst + stride, vget_high_u16(sum_saturated)); // Progress across relative_top_left = relative_top[3]; relative_top += 4; relative_left[0] = row_dst[3]; relative_left[1] = row_dst[3 + stride]; row_dst += 4; x += 4; } while (x < width); // Progress down. relative_top_left = left[y + 1]; relative_top = dst + stride; relative_left[0] = left[y + 2]; relative_left[1] = left[y + 3]; dst += 2 * stride; y += 2; } while (y < height); } void Init10bpp() { Dsp* dsp = dsp_internal::GetWritableDspTable(kBitdepth10); assert(dsp != nullptr); dsp->filter_intra_predictor = FilterIntraPredictor_NEON; } } // namespace } // namespace high_bitdepth #endif // LIBGAV1_MAX_BITDEPTH >= 10 void IntraPredFilterInit_NEON() { low_bitdepth::Init8bpp(); #if LIBGAV1_MAX_BITDEPTH >= 10 high_bitdepth::Init10bpp(); #endif } } // namespace dsp } // namespace libgav1 #else // !LIBGAV1_ENABLE_NEON namespace libgav1 { namespace dsp { void IntraPredFilterInit_NEON() {} } // namespace dsp } // namespace libgav1 #endif // LIBGAV1_ENABLE_NEON
32.34202
80
0.545674
jbeich
70c0a5ada1bfc5e3a621981fe9bd6ba9e92945af
1,932
cpp
C++
src/pic.cpp
Codesmith512/Apex
c230c53ab8f32a5371dcf7b40d25fa9fbb85ac6b
[ "MIT" ]
1
2021-04-01T09:34:26.000Z
2021-04-01T09:34:26.000Z
src/pic.cpp
Codesmith512/Apex
c230c53ab8f32a5371dcf7b40d25fa9fbb85ac6b
[ "MIT" ]
null
null
null
src/pic.cpp
Codesmith512/Apex
c230c53ab8f32a5371dcf7b40d25fa9fbb85ac6b
[ "MIT" ]
null
null
null
#include "pic" #include "interrupts" #include "ports" #define PIC1_CMD 0x20 #define PIC1_DATA 0x21 #define PIC2_CMD 0xa0 #define PIC2_DATA 0xa1 /** Enables the PIC, but with all IRQs masked */ void pic::initialize() { /* Initialization Command */ ports::out_8(PIC1_CMD, 0x11); ports::io_wait(); ports::out_8(PIC2_CMD, 0x11); ports::io_wait(); /* Setup IRQs at INT 0x20~0x2f */ ports::out_8(PIC1_DATA, 0x20); ports::io_wait(); ports::out_8(PIC2_DATA, 0x28); ports::io_wait(); /* Inform master it has a slave at IRQ2 (0000 0100) */ ports::out_8(PIC1_DATA, 0x04); ports::io_wait(); /* Give slave it's cascade identity (0000 0010) */ ports::out_8(PIC2_DATA, 0x02); ports::io_wait(); /* Set 8086/8088 mode */ ports::out_8(PIC1_DATA, 0x01); ports::io_wait(); ports::out_8(PIC2_DATA, 0x01); ports::io_wait(); /* Set interrupt masks */ mask(irq_t::ALL); } /* Unmask IRQ */ void pic::unmask(irq_t irqs) { ports::out_8(PIC1_DATA, ports::in_8(PIC1_DATA) & ~static_cast<uint8_t>(irqs & 0xff)); ports::out_8(PIC2_DATA, ports::in_8(PIC2_DATA) & ~static_cast<uint8_t>((irqs >> 8) & 0xff)); } /* Mask IRQ */ void pic::mask(irq_t irqs) { ports::out_8(PIC1_DATA, ports::in_8(PIC1_DATA) | static_cast<uint8_t>(irqs & 0xff)); ports::out_8(PIC2_DATA, ports::in_8(PIC2_DATA) | static_cast<uint8_t>((irqs >> 8) & 0xff)); } /* Acknowledge IRQ */ void pic::acknowledge(irq_t irq) { ports::out_8(PIC1_CMD, 0x20); if(irq > 0xff) ports::out_8(PIC2_CMD, 0x20); } /* Obtain Interrupt Request Register */ pic::irq_t pic::get_irr() { ports::out_8(PIC1_CMD, 0x0a); ports::out_8(PIC2_CMD, 0x0a); return (ports::in_8(PIC1_CMD)) | (ports::in_8(PIC2_CMD) << 8); } /* Obtain Interrupt Status Register */ pic::irq_t pic::get_isr() { ports::out_8(PIC1_CMD, 0x0b); ports::out_8(PIC2_CMD, 0x0b); return (ports::in_8(PIC1_CMD)) | (ports::in_8(PIC2_CMD) << 8); }
22.729412
94
0.65735
Codesmith512
70c0ad65fa5ebbd91e9cb6ab1915806c109233f6
7,870
cpp
C++
src/src/test.cpp
jcleng/nix-kangle-3.5.13.2
cc7bbaa429ada9a7eb7a023a152b6e2fc5defe3f
[ "MIT" ]
null
null
null
src/src/test.cpp
jcleng/nix-kangle-3.5.13.2
cc7bbaa429ada9a7eb7a023a152b6e2fc5defe3f
[ "MIT" ]
null
null
null
src/src/test.cpp
jcleng/nix-kangle-3.5.13.2
cc7bbaa429ada9a7eb7a023a152b6e2fc5defe3f
[ "MIT" ]
null
null
null
/* * test.cpp * * Created on: 2010-5-31 * Author: keengo * * Copyright (c) 2010, NanChang BangTeng Inc * All Rights Reserved. * * You may use the Software for free for non-commercial use * under the License Restrictions. * * You may modify the source code(if being provieded) or interface * of the Software under the License Restrictions. * * You may use the Software for commercial use after purchasing the * commercial license.Moreover, according to the license you purchased * you may get specified term, manner and content of technical * support from NanChang BangTeng Inc * * See COPYING file for detail. */ #include <vector> #include <assert.h> #include <string.h> #include "global.h" #include "lib.h" #include "KGzip.h" #include "do_config.h" #include "malloc_debug.h" #include "KLineFile.h" #include "KHttpFieldValue.h" #include "KHttpField.h" #include "KPipeStream.h" #include "KFileName.h" #include "KVirtualHost.h" #include "KChunked.h" #include "KExpressionParseTree.h" #include "KHtAccess.h" #include "KTimeMatch.h" #include "KReg.h" #include "KFile.h" #include "KXml.h" #include "KUrlParser.h" #include "cache.h" #include "KConnectionSelectable.h" #ifdef ENABLE_INPUT_FILTER #include "KMultiPartInputFilter.h" #endif using namespace std; char *getString(char *str, char **substr); void test_file() { const char *test_file = "c:\\windows\\temp\\test.txt"; KFile file; assert(file.open(test_file,fileWrite)); assert(file.write("test",4)); file.close(); assert(file.open(test_file,fileRead)); char buf[8]; int len = file.read(buf,8); assert(len==4); assert(strncmp(buf,"test",4)==0); file.seek(1,seekBegin); len = file.read(buf,8); assert(len==3); file.close(); file.open(test_file,fileAppend); file.write("t2",2); file.close(); file.open(test_file,fileRead); assert(file.read(buf,8)==6); file.close(); } bool test_pipe() { return true; } void test_regex() { KReg reg; reg.setModel("s",0); int ovector[6]; int ret = reg.match("sjj",-1,PCRE_PARTIAL,ovector,6); //printf("ret=%d\n",ret); //KRegSubString *ss = reg.matchSubString("t", 1, 0); //assert(ss); } /* void test_cache() { const char *host = "abcdef"; for (int i=0;i<100;i++) { std::stringstream s; int h = rand()%6; s << "http://" << host[h] << "/" << rand(); KHttpObject *obj = new KHttpObject; create_http_object(obj,s.str().c_str(),false); obj->release(); } } */ void test_container() { /* unsigned char buf[18]; const char *hostname = ".test.com"; assert(revert_hostname(hostname,strlen(hostname),buf,sizeof(buf))); printf("ret=[%s]\n",buf); */ } void test_htaccess() { //static const char *file = "/home/keengo/httpd.conf"; //KHtAccess htaccess; //KFileName file; //file.setName("/","/home/keengo/"); //printf("result=%d\n",htaccess.load("/","/home/keengo/")); } void test_expr() { static const char *to_test[] = { "name=name", "name!=name", "name!=name2", "name=/na/", "name=/na/ && name!=aaa", "test=ddd || (test=test && a=/b/)" }; static ExpResult result[] = { Exp_true, Exp_false, Exp_true, Exp_true, Exp_true, Exp_false }; KSSIContext context; for (size_t i = 0; i < sizeof(result) / sizeof(ExpResult); i++) { KExpressionParseTree *parser = new KExpressionParseTree; parser->setContext(&context); char *buf = xstrdup(to_test[i]); ExpResult result1 = parser->evaluate(buf); if (result1 != result[i]) { fprintf(stderr, "test exp[%s] result=[%d] test result[%d] failed.", buf, result[i], result1); abort(); } xfree(buf); delete parser; } } void test_file(const char *path) { #if 0 KFileName file; std::string doc_root = "d:\\project\\kangle\\www\\"; bool result = file.setName(doc_root.c_str(), path, FOLLOW_LINK_NO|FOLLOW_PATH_INFO); printf("triped_path=[%s],result=%d\n",path,result); if(result){ printf("pre_dir=%d,is_dir=%d,path_info=[%d],filename=[%s]\n",file.isPrevDirectory(),file.isDirectory(),file.getPathInfoLength(),file.getName()); } #endif } void test_files() { test_file("/test.php"); test_file("/test.php/a/b"); test_file("/"); test_file("/a/"); test_file("/a"); test_file("/b"); } void test_timematch() { KTimeMatch *t = new KTimeMatch; t->set("* * * * *"); t->Show(); delete t; t = new KTimeMatch; t->set("*/5 */5 * * *"); t->Show(); delete t; t = new KTimeMatch; t->set("2-10/3,50 0-6 * * *"); t->Show(); delete t; } void test_url_decode() { char buf2[5]; //strcpy(buf2,"test"); memcpy(buf2,"test",4); buf2[4] = '*'; url_decode(buf2, 4,NULL,true); // printf("buf=[%s]\n",buf2); assert(buf2[4]=='*'); //strcpy(buf2,"test"); memcpy(buf2,"%20t",4); url_decode(buf2, 4,NULL,true); //printf("buf=[%s]\n",buf2); assert(buf2[2]=='\0'); } void test_dechunk() { KDechunkEngine engine; int buf_len; const char *piece; int piece_length; const char *buf = "1\r\na\r\n"; buf_len = strlen(buf); assert(engine.dechunk(&buf, buf_len, &piece, piece_length) == dechunk_success); assert(strncmp(piece, "a",piece_length) == 0); assert(engine.dechunk(&buf, buf_len, &piece, piece_length) == dechunk_continue); buf = "1"; buf_len = 1; assert(engine.dechunk(&buf, buf_len, &piece, piece_length) == dechunk_continue); buf = "0\r\n012345"; buf_len = strlen(buf); assert(engine.dechunk(&buf, buf_len, &piece, piece_length) == dechunk_continue); assert(piece_length==6 && strncmp(piece, "012345", piece_length) == 0); buf = "6789abcdef0\r\n"; buf_len = strlen(buf); assert(engine.dechunk(&buf, buf_len, &piece, piece_length) == dechunk_success); assert(piece_length==10 && strncmp(piece, "6789abcdef", piece_length) == 0); } void test_white_list() { #ifdef ENABLE_BLACK_LIST kgl_current_sec = time(NULL); wlm.add(".", NULL, "1"); wlm.add(".", NULL, "2"); wlm.add(".", NULL, "3"); wlm.flush(time(NULL)+100, 10); #endif } void test_line_file() { KStreamFile lf; lf.open("d:\\line.txt"); for (;;) { char *line = lf.read(); if (line == NULL) { break; } printf("line=[%s]\n", line); } } void test_suffix_corrupt() { char *str = new char[4]; memcpy(str,"test1",5); delete[] str; } void test_prefix_corrupt() { char *str = (char *)malloc(4); void *pp = str - 1; memcpy(pp,"test",4); free(str); } void test_freed_memory() { char *str = (char *)malloc(4); free(str); memcpy(str,"test",4); } bool test() { //test_freed_memory(); //test_suffix_corrupt(); //test_prefix_corrupt(); //printf("sizeof(KSelectable) = %d\n",sizeof(KSelectable)); //printf("sizeof(KConnectionSelectable)=%d\n",sizeof(KConnectionSelectable)); //printf("sizeof(KHttpRequest) = %d\n",sizeof(KHttpRequest)); //printf("sizeof(pthread_mutex_t)=%d\n",sizeof(pthread_mutex_t)); //printf("sizeof(lock)=%d\n",sizeof(KMutex)); //test_cache(); //test_file(); //test_timematch(); //test_xml(); //printf("sizeof(kgl_str_t)=%d\n",sizeof(kgl_str_t)); //test_ip_map(); //test_line_file(); #ifdef ENABLE_HTTP2 test_http2(); #endif buff b; b.flags = 0; test_url_decode(); test_regex(); test_htaccess(); test_expr(); test_container(); test_dechunk(); test_white_list(); //printf("sizeof(KHttpRequest)=%d\n",sizeof(KHttpRequest)); // test_pipe(); //printf("sizeof(obj)=%d,%d\n",sizeof(KHttpObject),sizeof(HttpObjectIndex)); time_t nowTime = time(NULL); char timeStr[41]; mk1123time(nowTime, timeStr, sizeof(timeStr) - 1); //printf("parse1123=%d\n",parse1123time(timeStr)); assert(parse1123time(timeStr)==nowTime); INT64 t = 123; char buf[INT2STRING_LEN]; int2string(t, buf); //printf("sizeof(sockaddr_i)=%d\n",sizeof(sockaddr_i)); if (strcmp(buf, "123") != 0) { fprintf(stderr, "Warning int2string function is not correct\n"); assert(false); } else if (string2int(buf) != 123) { fprintf(stderr, "Warning string2int function is not correct\n"); assert(false); } KHttpField field; // test_files(); return true; }
25.973597
146
0.658196
jcleng
70c22245464a0233b7ea09a06ddecf41d2064596
2,325
cc
C++
lua/runtime/lua_runtime.cc
Alcanderian/ppl.nn
e127cf6dda87412bc9bb551da6aa5d29d7ca22fd
[ "Apache-2.0" ]
2
2021-09-14T03:00:04.000Z
2021-11-18T07:29:44.000Z
lua/runtime/lua_runtime.cc
Alcanderian/ppl.nn
e127cf6dda87412bc9bb551da6aa5d29d7ca22fd
[ "Apache-2.0" ]
1
2021-12-20T11:04:17.000Z
2021-12-20T11:04:17.000Z
lua/runtime/lua_runtime.cc
Alcanderian/ppl.nn
e127cf6dda87412bc9bb551da6aa5d29d7ca22fd
[ "Apache-2.0" ]
null
null
null
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "lua_runtime.h" #include "luacpp.h" #include "lua_tensor.h" using namespace std; using namespace luacpp; using namespace ppl::common; namespace ppl { namespace nn { namespace lua { void RegisterRuntime(const shared_ptr<LuaState>& lstate, const shared_ptr<LuaTable>& lmodule) { auto tensor_class = LuaClass<LuaTensor>(lmodule->Get("Tensor")); auto lclass = lstate->CreateClass<LuaRuntime>() .DefMember("GetInputCount", [](const LuaRuntime* lruntime) -> uint32_t { return lruntime->ptr->GetInputCount(); }) .DefMember("GetInputTensor", [tensor_class, lstate](const LuaRuntime* lruntime, uint32_t idx) -> LuaObject { auto tensor = lruntime->ptr->GetInputTensor(idx); if (!tensor) { return lstate->CreateNil(); } return tensor_class.CreateUserData(tensor); }) .DefMember("Run", [](LuaRuntime* lruntime) -> RetCode { return lruntime->ptr->Run(); }) .DefMember("GetOutputCount", [](const LuaRuntime* lruntime) -> uint32_t { return lruntime->ptr->GetOutputCount(); }) .DefMember("GetOutputTensor", [tensor_class, lstate](const LuaRuntime* lruntime, uint32_t idx) -> LuaObject { auto tensor = lruntime->ptr->GetOutputTensor(idx); if (!tensor) { return lstate->CreateNil(); } return tensor_class.CreateUserData(tensor); }); lmodule->Set("Runtime", lclass); } }}}
40.086207
117
0.664516
Alcanderian
70c2909bc97ac18f6f1d6ca2ec85c70004fc3edc
58,861
cpp
C++
src/OutputFile.cpp
RemiMattheyDoret/SimBit
ed0e64c0abb97c6c889bc0adeec1277cbc6cbe43
[ "MIT" ]
11
2017-06-06T23:02:48.000Z
2021-08-17T20:13:05.000Z
src/OutputFile.cpp
RemiMattheyDoret/SimBit
ed0e64c0abb97c6c889bc0adeec1277cbc6cbe43
[ "MIT" ]
1
2017-06-06T23:08:05.000Z
2017-06-07T09:28:08.000Z
src/OutputFile.cpp
RemiMattheyDoret/SimBit
ed0e64c0abb97c6c889bc0adeec1277cbc6cbe43
[ "MIT" ]
null
null
null
/* Author: Remi Matthey-Doret MIT License Copyright (c) 2017 Remi Matthey-Doret 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 WARRAreadLineNTIES 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. */ std::vector<T1_locusDescription> OutputFile::getSubsetToConsider(int speciesIndex) { assert(speciesIndex < this->subset.size()); return this->subset[speciesIndex]; } template<typename T> std::vector<T> OutputFile::removeSitesWeDontWant(std::vector<T> sites, int speciesIndex) { // sites must be sorted //std::cout << "From OutputFile::removeSitesWeDontWant: speciesIndex = " << speciesIndex << "\n"; //std::cout << "From OutputFile::removeSitesWeDontWant: this->subset.size() = " << this->subset.size() << "\n"; assert(speciesIndex < this->subset.size()); return intersection(this->subset[speciesIndex], sites); } const std::vector<std::string> OutputFile::OutputFileTypesNames = { "Oops... failed to find file type name", "Logfile", "T1_vcfFile", "T1_LargeOutputFile", "T1_AlleleFreqFile", "MeanLDFile", "LongestRunFile", "HybridIndexFile", "ExpectiMinRecFile", "T2_LargeOutputFile", "SaveBinaryFile", "T3_MeanVarFile", "T3_LargeOutputFile", "fitness", "fitnessStats", "T1_FST", "extraGeneticInfo", "patchSize", "extinction", "genealogy", "fitnessSubsetLoci", "T4_LargeOutputFile", "T4_vcfFile", "T4_SFS_file", "T1_SFS_file", "T4_printTree", "T5_vcfFile", "T5_SFS_file", "T5_AlleleFreqFile", "T5_LargeOutputFile", "T4CoalescenceFst", "T1_AverageHybridIndexFile", "T1_haplotypeFreqs_file", "sampleSeq_file", "T4_paintedHaploSegmentsOrigin_file", "T8_SNPfreq_file", "T8_largeOutput_file" }; const std::vector<int> OutputFile::listOfOutputFileTypeThatCanTakeASubset = { extraGeneticInfo, T1_FST, // not fitnessStats // not patchSize // not fitnessSubsetLoci (obviously) // not fitness (fitnessSubsetLoci is here for that) T1_AlleleFreqFile, MeanLDFile, LongestRunFile, // not T2_LargeOutputFile T1_LargeOutputFile, HybridIndexFile, ExpectiMinRecFile, T1_vcfFile, // not T3_LargeOutputFile // T3_MeanVarFile // extinction // not genealogy // not SaveBinaryFile // not Logfile // not T4_LargeOutputFile, // not T4_vcfFile // not T4_SFS_file T1_SFS_file, // not T4_printTree // not T5_vcfFile // not T5_SFS_file // not T5_AlleleFreqFile // not T5_LargeOutputFile // not T4CoalescenceFst T1_AverageHybridIndexFile, T1_haplotypeFreqs_file, // not sampleSeq_file // not T4_paintedHaploSegmentsOrigin_file // not T8_SNPfreq_file // not T8_largeOutput_file }; void OutputFile::openAndReadLine(std::string& line, int generation) { std::ifstream ifs(this->getPath(generation)); std::getline(ifs,line); } void OutputFile::mergeFiles(std::vector<std::string> listOfFiles) { // https://stackoverflow.com/questions/19564450/concatenate-two-huge-files-in-c std::string path = this->getPathWithoutGenerationDespiteBeingGenerationSpecific(); std::remove(path.c_str()); ofs.open(path, std::ios_base::app); if (!ofs.is_open()) { std::cout << "OutputFileType " << getFileTypeName(OutputFileType) << "(index "<< OutputFileType <<")" << " with path '" << path << "' failed to open in mergeFiles!" << "\n"; abort(); } for (std::string p : listOfFiles) { std::ifstream ifs(p); ofs << ifs.rdbuf(); } ofs << "\n"; /*for (std::string p : listOfFiles) { std::cout << "p = " << p << std::endl; std::ifstream ifs(p); std::string line; std::getline(ifs, line); std::cout << "line = "<< line << std::endl; ofs << line << "\n"; }*/ } bool OutputFile::isLocusInSubset(T1_locusDescription L, int speciesIndex) { assert(speciesIndex < this->subset.size()); bool x = std::binary_search( subset[speciesIndex].begin(), subset[speciesIndex].end(), L, [](const T1_locusDescription& right, const T1_locusDescription& left){return right.locus < left.locus;} ); return x; // 'operator==' between 'T1_locusDescription' and 'int' compares with the attribute 'locus' } bool OutputFile::isLocusInSubset(int locus, int speciesIndex) { T1_locusDescription L(locus); // minimalist instantiation (no division by eight) used only to search in 'subset' return isLocusInSubset(L, speciesIndex); // 'operator==' between 'T1_locusDescription' and 'int' compares with the attribute 'locus' } std::string OutputFile::getPathForSeed() { return GeneralPath + filename + "_seed" + std::string("_G") + std::to_string(GP->CurrentGeneration) + sequencingErrorStringToAddToFilnames + extension; } std::string OutputFile::getPath(std::string patchIndexString, size_t mutPlacementIndex) { if (this->isSpeciesSpecific) { assert(SSP != nullptr); if (this->isGenerationSpecific) { if (GP->nbSpecies == 1 && SSP->speciesName == "sp") { if (isT4MutationPlacementSpecific) { assert(mutPlacementIndex >= 0); return GeneralPath + filename + std::string("_G") + std::to_string(GP->CurrentGeneration) + patchIndexString + sequencingErrorStringToAddToFilnames + std::string("_mutPlac") + std::to_string(mutPlacementIndex) + extension; } else { assert(mutPlacementIndex == 0); return GeneralPath + filename + std::string("_G") + std::to_string(GP->CurrentGeneration) + patchIndexString + sequencingErrorStringToAddToFilnames + extension; } } else { if (isT4MutationPlacementSpecific) { assert(mutPlacementIndex >= 0); return GeneralPath + filename + "_" + SSP->speciesName + std::string("_G") + std::to_string(GP->CurrentGeneration) + patchIndexString + sequencingErrorStringToAddToFilnames + std::string("_mutPlac") + std::to_string(mutPlacementIndex) + extension; } else { assert(mutPlacementIndex == 0); return GeneralPath + filename + "_" + SSP->speciesName + std::string("_G") + std::to_string(GP->CurrentGeneration) + patchIndexString + sequencingErrorStringToAddToFilnames + extension; } } } else { if (GP->nbSpecies == 1 && SSP->speciesName == "sp") { if (isT4MutationPlacementSpecific) { assert(mutPlacementIndex >= 0); return GeneralPath + filename + patchIndexString + sequencingErrorStringToAddToFilnames + std::string("_mutPlac") + std::to_string(mutPlacementIndex) + extension; } else { assert(mutPlacementIndex == 0); return GeneralPath + filename + patchIndexString + sequencingErrorStringToAddToFilnames + extension; } } else { if (isT4MutationPlacementSpecific) { assert(mutPlacementIndex >= 0); return GeneralPath + filename + "_" + SSP->speciesName + patchIndexString + sequencingErrorStringToAddToFilnames + std::string("_mutPlac") + std::to_string(mutPlacementIndex) + extension; } else { assert(mutPlacementIndex == 0); return GeneralPath + filename + "_" + SSP->speciesName + patchIndexString + sequencingErrorStringToAddToFilnames + extension; } } } } else { if (this->isGenerationSpecific) { if (isT4MutationPlacementSpecific) { assert(mutPlacementIndex >= 0); return GeneralPath + filename + std::string("_G") + std::to_string(GP->CurrentGeneration) + patchIndexString + sequencingErrorStringToAddToFilnames + std::string("_mutPlac") + std::to_string(mutPlacementIndex) + extension; } else { assert(mutPlacementIndex == 0); return GeneralPath + filename + std::string("_G") + std::to_string(GP->CurrentGeneration) + patchIndexString + sequencingErrorStringToAddToFilnames + extension; } } else { return GeneralPath + filename + patchIndexString + sequencingErrorStringToAddToFilnames + extension; } } } std::string OutputFile::getPathWithoutGenerationDespiteBeingGenerationSpecific(size_t mutPlacementIndex) { if (this->isSpeciesSpecific) { assert(SSP != nullptr); if (GP->nbSpecies == 1 && SSP->speciesName == "sp") { if (isT4MutationPlacementSpecific) { assert(mutPlacementIndex >= 0); return GeneralPath + filename + sequencingErrorStringToAddToFilnames + std::string("_mutPlac") + std::to_string(mutPlacementIndex) + extension; } else { assert(mutPlacementIndex == 0); return GeneralPath + filename + sequencingErrorStringToAddToFilnames + extension; } } else { if (isT4MutationPlacementSpecific) { assert(mutPlacementIndex >= 0); return GeneralPath + filename + "_" + SSP->speciesName + sequencingErrorStringToAddToFilnames + std::string("_mutPlac") + std::to_string(mutPlacementIndex) + extension; } else { assert(mutPlacementIndex == 0); return GeneralPath + filename + "_" + SSP->speciesName + sequencingErrorStringToAddToFilnames + extension; } } } else { if (isT4MutationPlacementSpecific) { assert(mutPlacementIndex >= 0); return GeneralPath + filename + sequencingErrorStringToAddToFilnames + std::string("_mutPlac") + std::to_string(mutPlacementIndex) + extension; } else { assert(mutPlacementIndex == 0); return GeneralPath + filename + sequencingErrorStringToAddToFilnames + extension; } } } std::string OutputFile::getPath(int generation, std::string patchIndexString, size_t mutPlacementIndex) { assert(this->isGenerationSpecific); if (this->isSpeciesSpecific) { assert(SSP != nullptr); if (GP->nbSpecies == 1 && SSP->speciesName == "sp") { if (isT4MutationPlacementSpecific) { assert(mutPlacementIndex >= 0); return GeneralPath + filename + std::string("_G") + std::to_string(generation) + patchIndexString + sequencingErrorStringToAddToFilnames + std::string("_mutPlac") + std::to_string(mutPlacementIndex) + extension; } else { assert(mutPlacementIndex == 0); return GeneralPath + filename + std::string("_G") + std::to_string(generation) + patchIndexString + sequencingErrorStringToAddToFilnames + extension; } } else { if (isT4MutationPlacementSpecific) { assert(mutPlacementIndex >= 0); return GeneralPath + filename + "_" + SSP->speciesName + std::string("_G") + std::to_string(generation) + patchIndexString + sequencingErrorStringToAddToFilnames + std::string("_mutPlac") + std::to_string(mutPlacementIndex) + extension; } else { assert(mutPlacementIndex == 0); return GeneralPath + filename + "_" + SSP->speciesName + std::string("_G") + std::to_string(generation) + patchIndexString + sequencingErrorStringToAddToFilnames + extension; } } } else { if (isT4MutationPlacementSpecific) { assert(mutPlacementIndex >= 0); return GeneralPath + filename + std::string("_G") + std::to_string(generation) + patchIndexString + sequencingErrorStringToAddToFilnames + std::string("_mutPlac") + std::to_string(mutPlacementIndex) + extension; } else { assert(mutPlacementIndex == 0); return GeneralPath + filename + std::string("_G") + std::to_string(generation) + patchIndexString + sequencingErrorStringToAddToFilnames + extension; } } } void OutputFile::interpretTimeForPaintedHaplo(InputReader& input) { std::vector<int> observedGenerations; while (input.IsThereMoreToRead()) { // Assert I get keyword 'generations' { auto keywordgenerations = input.GetNextElementString(); if (keywordgenerations != "generations") { std::cout << "For outputs concerning painted haplotypes, expected the keyword 'generations' but received '" << keywordgenerations << "' instead.\n"; abort(); } } auto token = input.GetNextElementString(); auto sepPos = token.find("-"); if (sepPos == std::string::npos) { std::cout << "For outputs concerning painted haplotypes, expected times in format 'paintedGeneration->observedGeneration' (e.g. '50-200'). Received token " << token << "' that did not include any '-' (dash) sign. Note if you wrote something like '50 - 200' (note the spaces), then the tokens will be read as '50', '-' and '200' which does not work. So please, don't put spaces around '-'."; abort(); } std::string paintedGeneration_s = token.substr(0, sepPos); std::string observedGeneration_s = token.substr(sepPos + 1); int paintedGeneration; int observedGeneration; if (paintedGeneration_s == "end") { std::cout << "For outputs concerning painted haplotypes, expected times in format 'paintedGeneration-observedGeneration' (e.g. '50->200'). The paintedGeneration received is 'end' (end = " << GP->CurrentGeneration << "). Sorry, you cannot paint the haplotype at the last generation as you need to leave at least one generation between the generation when you paint the haplotypes and the generation when you observe how the painted piece have segregated.\n"; abort(); } else { if (paintedGeneration_s == "anc") { paintedGeneration = std::numeric_limits<int>::lowest(); } else { paintedGeneration = (int) std::stod(paintedGeneration_s); } } if (observedGeneration_s == "end") { observedGeneration = GP->nbGenerations; } else { observedGeneration = (int) std::stod(observedGeneration_s); } if (observedGeneration > GP->nbGenerations) { std::cout << "For outputs concerning painted haplotypes, expected times in format 'paintedGeneration-observedGeneration' (e.g. '50-200'). The paintedGeneration received is '"<<paintedGeneration<<"' and the observedGeneration received is '"<<observedGeneration<<"'. observedGeneration must be lower or equal to the total nuumber of generations simulated (as indicated with option --nbGens (--nbGenerations), the total number of generations simulated is "<< GP->nbGenerations<<")\n"; abort(); } if (paintedGeneration >= observedGeneration) { std::cout << "For outputs concerning painted haplotypes, expected times in format 'paintedGeneration-observedGeneration' (e.g. '50-200'). The paintedGeneration received is '"<<paintedGeneration<<"' and the observedGeneration received is '"<<observedGeneration<<"'. observedGeneration must be strictly greater than paintedGeneration\n"; abort(); } auto generation_index = std::upper_bound(GP->__GenerationChange.begin(), GP->__GenerationChange.end(), observedGeneration) - GP->__GenerationChange.begin() - 1; assert(generation_index < GP->__PatchNumber.size()); // Assert I get keyword 'patch' { auto keywordPatch = input.GetNextElementString(); if (keywordPatch != "patch") { std::cout << "For outputs concerning painted haplotypes, expected the keyword 'patch' but received " << keywordPatch << " instead.\n"; abort(); } } std::vector<int> patch_indices; while (input.IsThereMoreToRead() && input.PeakNextElementString() != "nbHaplos" && input.PeakNextElementString() != "generations" && input.PeakNextElementString() != "patch") { auto patch_index = input.GetNextElementInt(); patch_indices.push_back(patch_index); if (patch_index >= GP->__PatchNumber[generation_index]) { std::cout << "For outputs concerning painted haplotypes, received the patch_index " << patch_index << " for observation at generation " << observedGeneration << " of haplotypes painted at generation " << paintedGeneration << ". generation " << observedGeneration << " there are however only " << GP->__PatchNumber[generation_index] << " patches. It is therefore impossible to sample from patch " << patch_index << ". As a reminder, the patch_index (just like any other indices in SimBit) is zero-based counting.\n"; abort(); } } if (patch_indices.size() == 0) { std::cout << "For outputs concerning painted haplotypes, expected some input (different from keywords 'patch', 'nbHaplos' or 'generations') after the keyword 'patch'\n"; abort(); } // Assert I got keyword 'nbHaplos' { auto keywordnbHaplos = input.GetNextElementString(); if (keywordnbHaplos != "nbHaplos") { std::cout << "For outputs concerning painted haplotypes, expected the keyword 'nbHaplos' but received " << keywordnbHaplos << " instead. Note this sounds like an internal bug as the code should have been able to run this line only if the keyword 'nbHaplos' had been found. Weird! Even if you end up finding it is caused by a non-sense input of yours, please let Remi know about it.\n"; abort(); } } assert(patch_indices.size()); std::vector<int> nbHaplotypes; while (input.IsThereMoreToRead() && input.PeakNextElementString() != "nbHaplos" && input.PeakNextElementString() != "generations" && input.PeakNextElementString() != "patch") { if (input.PeakNextElementString() == "all") { input.skipElement(); nbHaplotypes.push_back(-1); } else { nbHaplotypes.push_back(input.GetNextElementInt()); } auto& nbH = nbHaplotypes.back(); if (nbHaplotypes.size() > patch_indices.size()) { std::cout << "For outputs concerning painted haplotypes, received more values following the keyword 'nbHaplos' than values following the keyword 'patch'\n"; abort(); } assert(nbHaplotypes.size() - 1 < patch_indices.size()); if (GP->nbSpecies == 1) { if (!allParameters.SSPs[0].T4_paintedHaplo_shouldIgnorePatchSizeSecurityChecks) { auto patch_index = patch_indices[nbHaplotypes.size() - 1]; auto maxNbHaplotypes = 2 * allParameters.SSPs[0].__patchCapacity[generation_index][patch_index]; if (nbH > maxNbHaplotypes) { std::cout << "For outputs concerning painted haplotypes, received the patch_index " << patch_index << " for observation at generation " << observedGeneration << " of haplotypes painted at generation " << paintedGeneration << ". You asked for sampling " << nbH << " haplotypes. The carrying capacity for the patch " << patch_index << " at generation " << observedGeneration << " is only " << maxNbHaplotypes/2 << " individuals (or " << maxNbHaplotypes<< " haplotypes).\n"; abort(); } else if (nbH < 0) { if (nbH == -1) { nbH = maxNbHaplotypes; } else { std::cout << "For outputs concerning painted haplotypes, received the patch_index " << patch_index << " for observation at generation " << observedGeneration << " of haplotypes painted at generation " << paintedGeneration << ". You asked for sampling " << nbH << " haplotypes. The carrying capacity for the patch " << patch_index << " at generation " << observedGeneration << " is only " << maxNbHaplotypes/2 << " individuals (or " << maxNbHaplotypes<< " haplotypes). You cannot ask for a negative number of haplotypes (exception of '-1' which is synonym 'all' meaning that all haploypes should be sampled)\n"; abort(); } } } } } if (nbHaplotypes.size() == 0) { std::cout << "For outputs concerning painted haplotypes, expected some input (different from keywords 'patch', 'nbHaplos' or 'generations') after the keyword 'patch'\n"; abort(); } if (nbHaplotypes.size() != patch_indices.size()) { std::cout << "For outputs concerning painted haplotypes, received " << patch_indices.size() << " patches (after keyword 'patch') but " << nbHaplotypes.size() << " number of haplotypes per patch values (after keyword 'nbHaplos').\n"; abort(); } observedGenerations.push_back(observedGeneration); T4TreeRec::generationsToKeepInTheTree.push_back(paintedGeneration); this->T4_paintedHaplo_information.push_back( { (int) paintedGeneration, (int) observedGeneration, patch_indices, nbHaplotypes } ); } std::sort(observedGenerations.begin(), observedGenerations.end()); observedGenerations.erase( std::unique( observedGenerations.begin(), observedGenerations.end() ), observedGenerations.end() ); this->setTimes(observedGenerations); std::sort(T4TreeRec::generationsToKeepInTheTree.begin(), T4TreeRec::generationsToKeepInTheTree.end()); T4TreeRec::generationsToKeepInTheTree.erase( std::unique( T4TreeRec::generationsToKeepInTheTree.begin(), T4TreeRec::generationsToKeepInTheTree.end() ), T4TreeRec::generationsToKeepInTheTree.end() ); assert(this->T4_paintedHaplo_information.size()); std::sort( this->T4_paintedHaplo_information.begin(), this->T4_paintedHaplo_information.end(), [](const OutputFile::T4_paintedHaplo_info& lhs, const OutputFile::T4_paintedHaplo_info& rhs) { if (lhs.observedGeneration == rhs.observedGeneration) { return lhs.paintedGeneration < rhs.paintedGeneration; } else { return lhs.observedGeneration < rhs.observedGeneration; } } ); assert(this->T4_paintedHaplo_information.size()); /* for (size_t i = 1 ; i < this->T4_paintedHaplo_information.size() ; ++i) { auto& curr = this->T4_paintedHaplo_information[i]; auto& prev = this->T4_paintedHaplo_information[i-1]; if (curr.observedGeneration == prev.observedGeneration && curr.paintedGeneration == prev.paintedGeneration && curr.patch_indices == prev.patch_indices) { std::cout << "For outputs concerning painted haplotypes, received twice the information to sample the sames patches at generation " << prev.observedGeneration << " of haplotypes painted at generation " << curr.paintedGeneration << ". Maybe you only meant to add up the number of haplotypes but I am unsure that's what you meant so I prefer to just raise an error message just in case.\n"; abort(); } } */ assert(this->T4_paintedHaplo_information.size()); } bool OutputFile::getIsT4MutationPlacementSpecific() { return isT4MutationPlacementSpecific; } void OutputFile::interpretTimeAndSubsetInput(InputReader& input) { if (!input.IsThereMoreToRead()) { std::cout << input.GetErrorMessage() << "was expecting time information after file name!\n"; abort(); } std::vector<int> v; while (input.IsThereMoreToRead()) { if (input.PeakNextElementString() == "subset" || input.PeakNextElementString() == "sequence") { break; } if (input.PeakNextElementString() == "fromtoby" || input.PeakNextElementString() == "FromToBy" || input.PeakNextElementString() == "fromToBy") { input.skipElement(); int from = input.GetNextElementInt(); int to; if (input.PeakNextElementString() == "end") { input.skipElement(); to = GP->nbGenerations; } else { to = input.GetNextElementInt(); } int by = input.GetNextElementInt(); /* std::cout << "from = " << from << "\n"; std::cout << "to = " << to << "\n"; std::cout << "by = " << by << "\n"; */ for (int t = from ; t <= to ; t+=by) { v.push_back(t); } if (v.back() < to) v.push_back(to); } else { if (input.PeakNextElementString() == "end") { input.skipElement(); v.push_back(GP->nbGenerations); } else { v.push_back(input.GetNextElementInt()); } } } this->setTimes(v); if (std::find(listOfOutputFileTypeThatCanTakeASubset.begin(), listOfOutputFileTypeThatCanTakeASubset.end(), this->OutputFileType) != listOfOutputFileTypeThatCanTakeASubset.end()) { if (input.IsThereMoreToRead() && input.PeakNextElementString() != "sequence") { assert(input.GetNextElementString() == "subset"); if (std::find(listOfOutputFileTypeThatCanTakeASubset.begin(), listOfOutputFileTypeThatCanTakeASubset.end(), this->OutputFileType) == listOfOutputFileTypeThatCanTakeASubset.end()) { std::cout << "Received the 'subset' keyword for outputFile of type " << getFileTypeName(OutputFileType) << " but only the types {"; for (auto& elem : listOfOutputFileTypeThatCanTakeASubset) std::cout << getFileTypeName(elem) << " "; std::cout << "}\n"; abort(); } input.removeAlreadyRead(); std::vector<std::pair<int, int>> rangesToSubsetFullInput = input.GetRangeOfIndicesForEachSpecies(); assert(rangesToSubsetFullInput.size() == GP->nbSpecies); auto SSP_toReset = SSP; for (int speciesIndex = 0 ; speciesIndex < GP->nbSpecies ; speciesIndex++) { SSP = allParameters.getSSPaddress(speciesIndex); // It is important to reset this because InputReader uses SSP assert(SSP != nullptr); int from = rangesToSubsetFullInput[speciesIndex].first; int to = rangesToSubsetFullInput[speciesIndex].second; assert(from <= to); InputReader inputOneSpecies(input, from, to, speciesIndex); std::vector<T1_locusDescription> oneSpeciesSubset; while (inputOneSpecies.IsThereMoreToRead()) { int locus = inputOneSpecies.GetNextElementInt(); oneSpeciesSubset.push_back({locus/8, locus%8, locus}); } inputOneSpecies.workDone(); this->subset.push_back(oneSpeciesSubset); } SSP = SSP_toReset; } else { // empty subset means all loci are in subset for (int speciesIndex = 0 ; speciesIndex < GP->nbSpecies; speciesIndex++) { std::vector<T1_locusDescription> oneSpeciesSubset; for (int locus = 0 ; locus < allParameters.getSSPaddress(speciesIndex)->Gmap.T1_nbLoci; locus++) oneSpeciesSubset.push_back({locus/8, locus%8, locus}); this->subset.push_back(oneSpeciesSubset); } } assert(this->subset.size() == GP->nbSpecies); } } bool OutputFile::isEmpty(std::ifstream& pFile) { return pFile.peek() == std::ifstream::traits_type::eof(); } bool OutputFile::containsRightNumberOfLines(std::ifstream& pFile) { int number_of_lines = 0; std::string line; while (std::getline(pFile, line)) ++number_of_lines; int nbExpectedLines; if (this->OutputFileType == extraGeneticInfo) { nbExpectedLines = 3; } else { nbExpectedLines = this->getTimes().size() + 1; } if (nbExpectedLines < number_of_lines) { if (this->OutputFileType != T1_vcfFile && this->OutputFileType != T4_vcfFile && this->OutputFileType != T56_vcfFile && this->OutputFileType != SaveBinaryFile) { std::cout << "\tThe file of type " << getFileTypeName(OutputFileType) << " (index "<< OutputFileType <<")" << " seems to contain more lines than the simulation is expected to produce. Simulation should produce " << nbExpectedLines << " lines (incl. header) and the current file contains " << number_of_lines << " lines." << "\n"; } } return nbExpectedLines == number_of_lines; } bool OutputFile::DoesFileExist() { // check file exists and contain at least one line std::string path = this->getPath(); std::ifstream f(path); if (f.good()) { if (this->containsRightNumberOfLines(f)) { return true; } } return false; } bool OutputFile::DoesFileExist(int generation) { // check file exists and contain at least one line bool ret = false; int ForReset = GP->CurrentGeneration; GP->CurrentGeneration = generation; std::string path = this->getPath(); std::ifstream f(path); //std::cout << "path = " << path << "\n"; if (f.good()) { if (this->containsRightNumberOfLines(f)) { ret = true; } } GP->CurrentGeneration = ForReset; return ret; } bool OutputFile::DoAllFilesOfTypeAlreadyExist() { if (isGenerationSpecific) { std::vector<int>& filetimes = getTimes(); for ( int& generation : filetimes) { if (!this->DoesFileExist(generation)) { return false; } } return true; } else { return this->DoesFileExist(); } } bool OutputFile::DoesAtLeastOneFileOfTypeAlreadyExist() { if (isGenerationSpecific) { std::vector<int>& filetimes = getTimes(); for ( int& generation : filetimes) { if (this->DoesFileExist(generation)) { return true; } } return false; } else { return this->DoesFileExist(); } } std::vector<int>& OutputFile::getTimes() { return times; } bool OutputFile::isTime() { if (!doesTimeNeedsToBeSet) { std::cout << "Internal error: Tried to get times for a file typeDoesTimeNeedsToBeSet who does not need time to be set\n"; abort(); } /* std::cout << "Trying to find time " << GP->CurrentGeneration << "\n"; std::cout << "times was set at "; for (auto& t : times) std::cout << t << " "; std::cout << "\n"; if (std::find(times.begin(), times.end(), GP->CurrentGeneration) != times.end()) std::cout << "time has been found!"; */ if (KillOnDemand::justAboutToKill) { if (times.back() > GP->CurrentGeneration) { return true; } else { return false; } } else { return std::find(times.begin(), times.end(), GP->CurrentGeneration) != times.end(); } } OutputFile::OutputFile(OutputFile&& f) : filename(std::move(f.filename)), extension(f.extension), OutputFileType(f.OutputFileType), times(f.times), isGenerationSpecific(f.isGenerationSpecific), isSpeciesSpecific(f.isSpeciesSpecific), isPatchSpecific(f.isPatchSpecific), isNbLinesEqualNbOutputTimes(f.isNbLinesEqualNbOutputTimes), doesTimeNeedsToBeSet(f.doesTimeNeedsToBeSet), isT4MutationPlacementSpecific(f.isT4MutationPlacementSpecific), subset(f.subset), T4_paintedHaplo_information(std::move(f.T4_paintedHaplo_information)) {} OutputFile::OutputFile(std::string f, OutputFileTypes t) :filename(f), OutputFileType(t) { if (filename == "NFN" || filename == "nfn") { filename = ""; } if (t == Logfile) { this->extension = std::string(".log"); isGenerationSpecific = false; isSpeciesSpecific = false; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = false; doesTimeNeedsToBeSet = false; isT4MutationPlacementSpecific = false; } else if (t == T1_vcfFile) { this->extension = std::string(".T1vcf"); isGenerationSpecific = true; isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = false; doesTimeNeedsToBeSet = true; isT4MutationPlacementSpecific = false; } else if (t == T1_LargeOutputFile) { this->extension = std::string(".T1LO"); isGenerationSpecific = false; isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = true; doesTimeNeedsToBeSet = true; isT4MutationPlacementSpecific = false; } else if (t == T1_AlleleFreqFile) { this->extension = std::string(".T1AllFreq"); isGenerationSpecific = false; isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = true; doesTimeNeedsToBeSet = true; isT4MutationPlacementSpecific = false; } else if (t == MeanLDFile) { this->extension = std::string(".T1LD"); isGenerationSpecific = false; isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = true; doesTimeNeedsToBeSet = true; } else if (t == LongestRunFile) { this->extension = std::string(".T1LR"); isGenerationSpecific = false; isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = true; doesTimeNeedsToBeSet = true; isT4MutationPlacementSpecific = false; } else if (t == HybridIndexFile) { this->extension = std::string(".T1HI"); isGenerationSpecific = false; isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = true; doesTimeNeedsToBeSet = true; isT4MutationPlacementSpecific = false; } else if (t == T1_AverageHybridIndexFile) { this->extension = std::string(".T1AverageHI"); isGenerationSpecific = false; isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = true; doesTimeNeedsToBeSet = true; isT4MutationPlacementSpecific = false; } else if (t == T1_haplotypeFreqs_file) { this->extension = std::string(".T1haploFreqs"); isGenerationSpecific = true; // Generation specific because the number of columns will vary isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = true; doesTimeNeedsToBeSet = true; isT4MutationPlacementSpecific = false; } else if (t == ExpectiMinRecFile) { this->extension = std::string(".T1EMR"); isGenerationSpecific = false; isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = true; doesTimeNeedsToBeSet = true; isT4MutationPlacementSpecific = false; } else if (t == T2_LargeOutputFile) { this->extension = std::string(".T2LO"); isGenerationSpecific = false; isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = true; doesTimeNeedsToBeSet = true; isT4MutationPlacementSpecific = false; } else if (t == SaveBinaryFile) { this->extension = std::string(".bin"); isGenerationSpecific = true; isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = false; doesTimeNeedsToBeSet = true; isT4MutationPlacementSpecific = false; } else if (t == T3_MeanVarFile) { this->extension = std::string(".T3MeanVar"); isGenerationSpecific = false; isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = true; doesTimeNeedsToBeSet = true; isT4MutationPlacementSpecific = false; } else if (t == T3_LargeOutputFile) { this->extension = std::string(".T3LO"); isGenerationSpecific = false; isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = true; doesTimeNeedsToBeSet = true; isT4MutationPlacementSpecific = false; } else if (t == fitness) { this->extension = std::string(".fit"); isGenerationSpecific = false; isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = true; doesTimeNeedsToBeSet = true; isT4MutationPlacementSpecific = false; } else if (t == fitnessStats) { this->extension = std::string(".fitStats"); isGenerationSpecific = false; isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = true; doesTimeNeedsToBeSet = true; isT4MutationPlacementSpecific = false; } else if (t == T1_FST) { this->extension = std::string(".T1_FST"); isGenerationSpecific = false; isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = true; doesTimeNeedsToBeSet = true; isT4MutationPlacementSpecific = false; } else if (t == extraGeneticInfo) { this->extension = std::string(".extraGeneticInfo"); isGenerationSpecific = false; isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = false; doesTimeNeedsToBeSet = false; isT4MutationPlacementSpecific = false; } else if (t == patchSize) { this->extension = std::string(".patchSize"); isGenerationSpecific = false; isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = true; doesTimeNeedsToBeSet = true; isT4MutationPlacementSpecific = false; } else if (t == extinction) { this->extension = std::string(".extinction"); isGenerationSpecific = false; isSpeciesSpecific = false; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = false; doesTimeNeedsToBeSet = false; isT4MutationPlacementSpecific = false; } else if (t == genealogy) { this->extension = std::string(".genealogy"); isGenerationSpecific = true; // Actually the end result is not. SimBit uses getPathWithoutGenerationDespiteBeingGenerationSpecific to produce the last file. isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = false; doesTimeNeedsToBeSet = true; isT4MutationPlacementSpecific = false; } else if (t == fitnessSubsetLoci) { this->extension = std::string(".fitSubLoci"); isGenerationSpecific = false; isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = true; doesTimeNeedsToBeSet = true; isT4MutationPlacementSpecific = false; } else if (t == T4_LargeOutputFile) { this->extension = std::string(".T4LO"); isGenerationSpecific = false; isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = true; doesTimeNeedsToBeSet = true; isT4MutationPlacementSpecific = true; } else if (t == T4_vcfFile) { this->extension = std::string(".T4vcf"); isGenerationSpecific = true; isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = false; doesTimeNeedsToBeSet = true; isT4MutationPlacementSpecific = true; } else if (t == T4_SFS_file) { this->extension = std::string(".T4SFS"); isGenerationSpecific = false; isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = true; doesTimeNeedsToBeSet = true; isT4MutationPlacementSpecific = true; } else if (t == T1_SFS_file) { this->extension = std::string(".T1SFS"); isGenerationSpecific = false; isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = true; doesTimeNeedsToBeSet = true; isT4MutationPlacementSpecific = false; } else if (t == T4_printTree) { this->extension = std::string(".T4tree"); // The following false/true should not matter as this file is not going into the outputWriter isGenerationSpecific = false; isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = false; isT4MutationPlacementSpecific = false; } else if (t == T56_vcfFile) { this->extension = std::string(".T5vcf"); isGenerationSpecific = true; isSpeciesSpecific = true; isPatchSpecific = true; isNbLinesEqualNbOutputTimes = false; doesTimeNeedsToBeSet = true; isT4MutationPlacementSpecific = false; } else if (t == T56_SFS_file) { this->extension = std::string(".T5SFS"); isGenerationSpecific = false; isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = true; doesTimeNeedsToBeSet = true; isT4MutationPlacementSpecific = false; } else if (t == T56_AlleleFreqFile) { this->extension = std::string(".T5AllFreq"); isGenerationSpecific = false; isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = true; doesTimeNeedsToBeSet = true; isT4MutationPlacementSpecific = false; } else if (t == T56_LargeOutputFile) { this->extension = std::string(".T5LO"); isGenerationSpecific = false; isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = true; doesTimeNeedsToBeSet = true; isT4MutationPlacementSpecific = false; } else if (t == T4CoalescenceFst) { this->extension = std::string(".T4CoalescenceFst"); isGenerationSpecific = false; isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = true; doesTimeNeedsToBeSet = true; isT4MutationPlacementSpecific = false; } else if (t == sampleSeq_file) { this->extension = std::string(".seq"); isGenerationSpecific = true; isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = false; doesTimeNeedsToBeSet = true; isT4MutationPlacementSpecific = true; } else if (t == T4_paintedHaplo_file) { this->extension = std::string(".paintedHaplo"); isGenerationSpecific = false; isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = false; doesTimeNeedsToBeSet = true; isT4MutationPlacementSpecific = false; } else if (t == T4_paintedHaploSegmentsDiversity_file) { this->extension = std::string(".paintedHaploDiversity"); isGenerationSpecific = false; isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = false; doesTimeNeedsToBeSet = true; isT4MutationPlacementSpecific = false; } else if (t == T4_SNPfreq_file) { this->extension = std::string(".T4_SNPfreq"); isGenerationSpecific = false; isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = false; doesTimeNeedsToBeSet = true; isT4MutationPlacementSpecific = true; } else if (t == Tx_SNPfreq_file) { this->extension = std::string(".Tx_SNPfreq"); isGenerationSpecific = false; isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = false; doesTimeNeedsToBeSet = true; isT4MutationPlacementSpecific = true; } else if (t == burnInLength_file) { this->extension = std::string(".burnInLength"); isGenerationSpecific = false; isSpeciesSpecific = false; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = false; doesTimeNeedsToBeSet = false; isT4MutationPlacementSpecific = false; } else if (t == T4_paintedHaploSegmentsOrigin_file) { this->extension = std::string(".paintedHaploOrigin"); isGenerationSpecific = false; isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = false; doesTimeNeedsToBeSet = true; isT4MutationPlacementSpecific = false; } else if (t == T8_SNPfreq_file) { this->extension = std::string(".T8SNPfreq"); isGenerationSpecific = false; isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = false; doesTimeNeedsToBeSet = true; isT4MutationPlacementSpecific = false; } else if (t == T8_largeOutput_file) { this->extension = std::string(".T8LO"); isGenerationSpecific = false; isSpeciesSpecific = true; isPatchSpecific = false; isNbLinesEqualNbOutputTimes = false; doesTimeNeedsToBeSet = true; isT4MutationPlacementSpecific = false; } else { std::cout << "Internal Error: In class 'OutputFile' in 'set_path', unknown fileType\n"; abort(); } } void OutputFile::openForSeed() { assert(OutputFileType == SaveBinaryFile); std::string path = this->getPathForSeed(); ofs.open(path, std::ios::out | std::ios::binary); if (!ofs.is_open()) { std::cout << "When trying to print the random seed to a binary file, the path '" << path << "' failed to open!" << "\n"; abort(); } } void OutputFile::openPatchSpecific(int patch_index) { std::string patchIndexString(""); if (patch_index != -1) { patchIndexString = std::string("_P") + std::to_string(patch_index); } std::string path = this->getPath(patchIndexString); if (OutputFileType == SaveBinaryFile) { ofs.open(path, std::ios::out | std::ios::binary); } else { ofs.open(path, std::ios_base::app); } if (!ofs.is_open()) { std::cout << "OutputFileType " << getFileTypeName(OutputFileType) << "(index "<< OutputFileType <<")" << " with path '" << path << "' failed to open!" << "\n"; abort(); } } void OutputFile::open() { std::string path = this->getPath(); if (OutputFileType == SaveBinaryFile) { ofs.open(path, std::ios::out | std::ios::binary | std::ios::trunc); } else { ofs.open(path, std::ios_base::app); } if (!ofs.is_open()) { std::cout << "OutputFileType " << getFileTypeName(OutputFileType) << "(index "<< OutputFileType <<")" << " with path '" << path << "' failed to open!" << "\n"; abort(); } } void OutputFile::openT4(size_t mutPlacementIndex) { std::string emptyString(""); std::string path = this->getPath(emptyString, mutPlacementIndex); ofs.open(path, std::ios_base::app); if (!ofs.is_open()) { std::cout << "OutputFileType " << getFileTypeName(OutputFileType) << "(index "<< OutputFileType <<")" << " with path '" << path << "' failed to open!" << "\n"; abort(); } } void OutputFile::openWithoutGenerationDespiteBeingGenerationSpecific() { std::string path = this->getPathWithoutGenerationDespiteBeingGenerationSpecific(); ofs.open(path, std::ios_base::app); if (!ofs.is_open()) { std::cout << "OutputFileType " << getFileTypeName(OutputFileType) << "(index "<< OutputFileType <<")" << " with path '" << path << "' failed to open!" << "\n"; abort(); } } void OutputFile::open(int generation) { std::string path = this->getPath(generation); ofs.open(path, std::ios_base::app); if (!ofs.is_open()) { std::cout << "OutputFileType " << getFileTypeName(OutputFileType) << "(index "<< OutputFileType <<")" << " with path '" << path << "' failed to open!" << "\n"; abort(); } } void OutputFile::remove() { std::string path; if (this->isPatchSpecific) { for (uint32_t patch_index = 0 ; patch_index < GP->maxEverPatchNumber; ++patch_index) { assert(!isT4MutationPlacementSpecific); std::string patchIndexString = std::string("_P") + std::to_string(patch_index); path = this->getPath(patchIndexString); ofs.open(path, std::ofstream::out | std::ofstream::trunc); if (!ofs.is_open()) { std::cout << "OutputFileType " << getFileTypeName(OutputFileType) << "(index "<< OutputFileType <<")" << " with path '" << path << "' failed to open!" << "\n"; abort(); } ofs.close(); std::remove(path.c_str()); } } else { if (isT4MutationPlacementSpecific) { for (size_t mutPlacingIndex = 0 ; mutPlacingIndex < SSP->T4_nbMutationPlacingsPerOutput ; ++mutPlacingIndex) { std::string emptyString(""); path = this->getPath(emptyString, mutPlacingIndex); ofs.open(path, std::ofstream::out | std::ofstream::trunc); if (!ofs.is_open()) { std::cout << "OutputFileType " << getFileTypeName(OutputFileType) << "(index "<< OutputFileType <<")" << " with path '" << path << "' failed to open!" << "\n"; abort(); } ofs.close(); std::remove(path.c_str()); } } else { path = this->getPath(); ofs.open(path, std::ofstream::out | std::ofstream::trunc); if (!ofs.is_open()) { std::cout << "OutputFileType " << getFileTypeName(OutputFileType) << "(index "<< OutputFileType <<")" << " with path '" << path << "' failed to open!" << "\n"; abort(); } ofs.close(); std::remove(path.c_str()); } } } void OutputFile::clearContent() { std::string path; if (this->isPatchSpecific) { for (uint32_t patch_index = 0 ; patch_index < GP->maxEverPatchNumber; ++patch_index) { std::string patchIndexString = std::string("_P") + std::to_string(patch_index); path = this->getPath(patchIndexString); ofs.open(path, std::ofstream::out | std::ofstream::trunc); if (!ofs.is_open()) { std::cout << "OutputFileType " << getFileTypeName(OutputFileType) << "(index "<< OutputFileType <<")" << " with path '" << path << "' failed to open!" << "\n"; abort(); } ofs.close(); } } else { path = this->getPath(); ofs.open(path, std::ofstream::out | std::ofstream::trunc); if (!ofs.is_open()) { std::cout << "OutputFileType " << getFileTypeName(OutputFileType) << "(index "<< OutputFileType <<")" << " with path '" << path << "' failed to open!" << "\n"; abort(); } ofs.close(); } } void OutputFile::clearContentAndLeaveOpen(int generation) { std::string path; path = this->getPath(generation); ofs.open(path, std::ofstream::out | std::ofstream::trunc); if (!ofs.is_open()) { std::cout << "OutputFileType " << getFileTypeName(OutputFileType) << "(index "<< OutputFileType <<")" << " with path '" << path << "' failed to open!" << "\n"; abort(); } } bool OutputFile::isOpen() { return ofs.is_open(); } void OutputFile::write(const std::string& s) { //assert(this->isOpen()); ofs << s; } void OutputFile::write(const std::vector<std::string>& s) { for (const auto& elem : s) write(elem); } template<typename T> void OutputFile::writeBinary(const T x) { //std::cout << "sizeof(x) = " << sizeof(x) << "\n"; assert(this->isOpen()); ofs.write((char*)&x, sizeof(T)); //std::cout << "write: " << x << " of type " << typeid(T).name() << "\n"; } template<typename T> void OutputFile::writeBinary(const std::vector<T>& x) { assert(this->isOpen()); this->writeBinary((size_t) x.size()); /* std::cout <<"write: "; for (size_t i = 0 ; i < x.size() ; ++i) { std::cout << x[i] << " "; } std::cout << " of type " << typeid(T).name() << "\n"; */ ofs.write( reinterpret_cast<const char*>(&x[0]), x.size()*sizeof(T) ); } void OutputFile::writeBinary(const char* first, int second) { //std::cout << "write first second\n"; assert(this->isOpen()); ofs.write(first, second); } void OutputFile::writeBinary(const RNG_type x) { //std::cout << "write RNG\n"; assert(this->isOpen()); ofs << x; //std::cout << x << "\n"; } void OutputFile::close() { ofs.close(); assert(!this->isOpen()); } OutputFileTypes OutputFile::getFileType() { return OutputFileType; } void OutputFile::setTimes(std::vector<int> x) { // assertions for (int i = 0 ; i < x.size(); i++) { if (i!= 0) { if (x[i-1] >= x[i]) { std::cout << "For file type '" << getFileTypeName(OutputFileType) << "(index "<< OutputFileType <<")" << "', received a time value that is larger or equal to the previous one. (The "<< i << "th value received is " << x[i] << " while the "<< i-1 <<"th value received is "<< x[i-1] <<"). Please indicate strictly increasing values for the '..._time' options.\n"; abort(); } } if (x[i] < 0) { std::cout << "For file type '" << getFileTypeName(OutputFileType) << "(index "<< OutputFileType <<")" << "', received a time value that is negative (Received " << x[i] << ") Note that a generation of 0 refers to sampling before any evolutionary process has happened.\n"; abort(); } if (x[i] > GP->nbGenerations) { std::cout << "For file type '" << getFileTypeName(OutputFileType) << "(index "<< OutputFileType <<")" << "', received a time value that is greater than the number of generations (Received " << x[i] << " while nbGenerations = "<< GP->nbGenerations <<"). Note that a generation of 0 refers to sampling before any evolutionary process has happened.\n"; abort(); } } if (OutputFileType == 1 || OutputFileType == 16 || OutputFileType == 18) { std::cout << "Internal error: Attempt to set times for outputFileType = " << getFileTypeName(OutputFileType) << "(index "<< OutputFileType <<")" << "\n"; abort(); } x.erase(std::remove_if( x.begin(), x.end(), [](const int& generation) { return generation < GP->startAtGeneration; } ), x.end()); // set times this->times = x; /* std::cout << "\ttimes set at "; for (auto& t : times) std::cout << t << " "; std::cout << "\n"; */ } bool OutputFile::getDoesTimeNeedsToBeSet() { return doesTimeNeedsToBeSet; } std::string OutputFile::getFileTypeName(int fileTypeIndex) { if (fileTypeIndex > OutputFileTypesNames.size() || fileTypeIndex == 0) { return "index " + std::to_string(fileTypeIndex); } else { return OutputFileTypesNames[fileTypeIndex]; } } void OutputFile::assertSubsetSize() { if (std::find(listOfOutputFileTypeThatCanTakeASubset.begin(), listOfOutputFileTypeThatCanTakeASubset.end(), this->OutputFileType) != listOfOutputFileTypeThatCanTakeASubset.end()) { assert(this->subset.size() == GP->nbSpecies); } }
36.996229
638
0.598529
RemiMattheyDoret
70c4aec7124fd496c7e8b08c826ab103414b6bd5
35,331
cpp
C++
src/core/dist_matrix/star_md.cpp
ahmadia/Elemental-1
f9a82c76a06728e9e04a4316e41803efbadb5a19
[ "BSD-3-Clause" ]
null
null
null
src/core/dist_matrix/star_md.cpp
ahmadia/Elemental-1
f9a82c76a06728e9e04a4316e41803efbadb5a19
[ "BSD-3-Clause" ]
null
null
null
src/core/dist_matrix/star_md.cpp
ahmadia/Elemental-1
f9a82c76a06728e9e04a4316e41803efbadb5a19
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2009-2013, Jack Poulson All rights reserved. This file is part of Elemental and is under the BSD 2-Clause License, which can be found in the LICENSE file in the root directory, or at http://opensource.org/licenses/BSD-2-Clause */ #include "elemental-lite.hpp" namespace elem { template<typename T,typename Int> DistMatrix<T,STAR,MD,Int>::DistMatrix( const elem::Grid& g ) : AbstractDistMatrix<T,Int> (0,0,false,false,0,0, 0,(g.InGrid() && g.DiagPath()==0 ? g.DiagPathRank() : 0), 0,0,g), diagPath_(0) { } template<typename T,typename Int> DistMatrix<T,STAR,MD,Int>::DistMatrix ( Int height, Int width, const elem::Grid& g ) : AbstractDistMatrix<T,Int> (height,width,false,false,0,0, 0, (g.InGrid() && g.DiagPath()==0 ? g.DiagPathRank() : 0),height, (g.InGrid() && g.DiagPath()==0 ? Length(width,g.DiagPathRank(),0,g.LCM()) : 0),g), diagPath_(0) { } template<typename T,typename Int> DistMatrix<T,STAR,MD,Int>::DistMatrix ( Int height, Int width, Int rowAlignmentVC, const elem::Grid& g ) : AbstractDistMatrix<T,Int> (height,width,false,true,0,g.DiagPathRank(rowAlignmentVC), 0, (g.InGrid() && g.DiagPath()==g.DiagPath(rowAlignmentVC) ? Shift(g.DiagPathRank(),g.DiagPathRank(rowAlignmentVC),g.LCM()) : 0), height, (g.InGrid() && g.DiagPath()==g.DiagPath(rowAlignmentVC) ? Length(width,g.DiagPathRank(),g.DiagPathRank(rowAlignmentVC),g.LCM()) : 0),g), diagPath_(g.DiagPath(rowAlignmentVC)) { } template<typename T,typename Int> DistMatrix<T,STAR,MD,Int>::DistMatrix ( Int height, Int width, Int rowAlignmentVC, Int ldim, const elem::Grid& g ) : AbstractDistMatrix<T,Int> (height,width,false,true,0,g.DiagPathRank(rowAlignmentVC), 0, (g.InGrid() && g.DiagPath()==g.DiagPath(rowAlignmentVC) ? Shift(g.DiagPathRank(),g.DiagPathRank(rowAlignmentVC),g.LCM()) : 0), height, (g.InGrid() && g.DiagPath()==g.DiagPath(rowAlignmentVC) ? Length(width,g.DiagPathRank(),g.DiagPathRank(rowAlignmentVC),g.LCM()) : 0),ldim,g), diagPath_(g.DiagPath(rowAlignmentVC)) { } template<typename T,typename Int> DistMatrix<T,STAR,MD,Int>::DistMatrix ( Int height, Int width, Int rowAlignmentVC, const T* buffer, Int ldim, const elem::Grid& g ) : AbstractDistMatrix<T,Int> (height,width,0,g.DiagPathRank(rowAlignmentVC), 0, (g.InGrid() && g.DiagPath()==g.DiagPath(rowAlignmentVC) ? Shift(g.DiagPathRank(),g.DiagPathRank(rowAlignmentVC),g.LCM()) : 0), height, (g.InGrid() && g.DiagPath()==g.DiagPath(rowAlignmentVC) ? Length(width,g.DiagPathRank(),g.DiagPathRank(rowAlignmentVC),g.LCM()) : 0),buffer,ldim,g), diagPath_(g.DiagPath(rowAlignmentVC)) { } template<typename T,typename Int> DistMatrix<T,STAR,MD,Int>::DistMatrix ( Int height, Int width, Int rowAlignmentVC, T* buffer, Int ldim, const elem::Grid& g ) : AbstractDistMatrix<T,Int> (height,width,0,g.DiagPathRank(rowAlignmentVC), 0, (g.InGrid() && g.DiagPath()==g.DiagPath(rowAlignmentVC) ? Shift(g.DiagPathRank(),g.DiagPathRank(rowAlignmentVC),g.LCM()) : 0), height, (g.InGrid() && g.DiagPath()==g.DiagPath(rowAlignmentVC) ? Length(width,g.DiagPathRank(),g.DiagPathRank(rowAlignmentVC),g.LCM()) : 0),buffer,ldim,g), diagPath_(g.DiagPath(rowAlignmentVC)) { } template<typename T,typename Int> DistMatrix<T,STAR,MD,Int>::DistMatrix( const DistMatrix<T,STAR,MD,Int>& A ) : AbstractDistMatrix<T,Int>(0,0,false,false,0,0, 0,(A.Participating() ? A.RowRank() : 0), 0,0,A.Grid()), diagPath_(0) { #ifndef RELEASE CallStackEntry entry("DistMatrix[* ,MD]::DistMatrix"); #endif if( &A != this ) *this = A; else throw std::logic_error("Tried to construct [* ,MD] with itself"); } template<typename T,typename Int> template<Distribution U,Distribution V> DistMatrix<T,STAR,MD,Int>::DistMatrix( const DistMatrix<T,U,V,Int>& A ) : AbstractDistMatrix<T,Int>(0,0,false,false,0,0, 0,(A.Participating() ? A.RowRank() : 0), 0,0,A.Grid()), diagPath_(0) { #ifndef RELEASE CallStackEntry entry("DistMatrix[* ,MD]::DistMatrix"); #endif if( STAR != U || MD != V || reinterpret_cast<const DistMatrix<T,STAR,MD,Int>*>(&A) != this ) *this = A; else throw std::logic_error("Tried to construct [* ,MD] with itself"); } template<typename T,typename Int> DistMatrix<T,STAR,MD,Int>::~DistMatrix() { } template<typename T,typename Int> elem::DistData<Int> DistMatrix<T,STAR,MD,Int>::DistData() const { elem::DistData<Int> data; data.colDist = STAR; data.rowDist = MD; data.colAlignment = 0; data.rowAlignment = this->rowAlignment_; data.diagPath = this->diagPath_; data.grid = this->grid_; return data; } template<typename T,typename Int> Int DistMatrix<T,STAR,MD,Int>::ColStride() const { return 1; } template<typename T,typename Int> Int DistMatrix<T,STAR,MD,Int>::RowStride() const { return this->grid_->LCM(); } template<typename T,typename Int> Int DistMatrix<T,STAR,MD,Int>::ColRank() const { return 0; } template<typename T,typename Int> Int DistMatrix<T,STAR,MD,Int>::RowRank() const { return this->grid_->DiagPathRank(); } template<typename T,typename Int> bool DistMatrix<T,STAR,MD,Int>::Participating() const { const Grid& g = this->Grid(); return ( g.InGrid() && g.DiagPath()==this->diagPath_ ); } template<typename T,typename Int> Int DistMatrix<T,STAR,MD,Int>::DiagPath() const { return this->diagPath_; } template<typename T,typename Int> void DistMatrix<T,STAR,MD,Int>::AlignWith( const elem::DistData<Int>& data ) { #ifndef RELEASE CallStackEntry entry("[* ,MD]::AlignWith"); this->AssertFreeRowAlignment(); #endif const Grid& grid = *data.grid; this->SetGrid( grid ); if( data.colDist == MD && data.rowDist == STAR ) { this->rowAlignment_ = data.colAlignment; this->diagPath_ = data.diagPath; } else if( data.colDist == STAR && data.rowDist == MD ) { this->rowAlignment_ = data.rowAlignment; this->diagPath_ = data.diagPath; } #ifndef RELEASE else throw std::logic_error("Invalid alignment"); #endif this->constrainedRowAlignment_ = true; this->SetShifts(); } template<typename T,typename Int> void DistMatrix<T,STAR,MD,Int>::AlignWith( const AbstractDistMatrix<T,Int>& A ) { this->AlignWith( A.DistData() ); } template<typename T,typename Int> void DistMatrix<T,STAR,MD,Int>::AlignRowsWith( const elem::DistData<Int>& data ) { this->AlignWith( data ); } template<typename T,typename Int> void DistMatrix<T,STAR,MD,Int>::AlignRowsWith( const AbstractDistMatrix<T,Int>& A ) { this->AlignWith( A.DistData() ); } template<typename T,typename Int> bool DistMatrix<T,STAR,MD,Int>::AlignedWithDiagonal ( const elem::DistData<Int>& data, Int offset ) const { #ifndef RELEASE CallStackEntry entry("[* ,MD]::AlignedWithDiagonal"); #endif const Grid& grid = this->Grid(); if( grid != *data.grid ) return false; bool aligned; const Int r = grid.Height(); const Int c = grid.Width(); const Int firstDiagRow = 0; const Int firstDiagCol = this->diagPath_; const Int diagRow = (firstDiagRow+this->RowAlignment()) % r; const Int diagCol = (firstDiagCol+this->RowAlignment()) % c; if( data.colDist == MC && data.rowDist == MR ) { if( offset >= 0 ) { const Int ownerRow = data.colAlignment; const Int ownerCol = (data.rowAlignment + offset) % c; aligned = ( ownerRow==diagRow && ownerCol==diagCol ); } else { const Int ownerRow = (data.colAlignment-offset) % r; const Int ownerCol = data.rowAlignment; aligned = ( ownerRow==diagRow && ownerCol==diagCol ); } } else if( data.colDist == MR && data.rowDist == MC ) { if( offset >= 0 ) { const Int ownerCol = data.colAlignment; const Int ownerRow = (data.rowAlignment + offset) % r; aligned = ( ownerRow==diagRow && ownerCol==diagCol ); } else { const Int ownerCol = (data.colAlignment-offset) % c; const Int ownerRow = data.rowAlignment; aligned = ( ownerRow==diagRow && ownerCol==diagCol ); } } else if( data.colDist == MD && data.rowDist == STAR ) { aligned = ( this->diagPath_==data.diagPath && this->rowAlignment_==data.colAlignment ); } else if( data.colDist == STAR && data.rowDist == MD ) { aligned = ( this->diagPath_==data.diagPath && this->rowAlignment_==data.rowAlignment ); } else aligned = false; return aligned; } template<typename T,typename Int> bool DistMatrix<T,STAR,MD,Int>::AlignedWithDiagonal ( const AbstractDistMatrix<T,Int>& A, Int offset ) const { return this->AlignedWithDiagonal( A.DistData(), offset ); } template<typename T,typename Int> void DistMatrix<T,STAR,MD,Int>::AlignWithDiagonal ( const elem::DistData<Int>& data, Int offset ) { #ifndef RELEASE CallStackEntry entry("[* ,MD]::AlignWithDiagonal"); this->AssertFreeRowAlignment(); #endif const Grid& grid = *data.grid; this->SetGrid( grid ); const Int r = grid.Height(); const Int c = grid.Width(); const Int lcm = grid.LCM(); if( data.colDist == MC && data.rowDist == MR ) { Int owner; if( offset >= 0 ) { const Int ownerRow = data.colAlignment; const Int ownerCol = (data.rowAlignment + offset) % c; owner = ownerRow + r*ownerCol; } else { const Int ownerRow = (data.colAlignment-offset) % r; const Int ownerCol = data.rowAlignment; owner = ownerRow + r*ownerCol; } this->diagPath_ = grid.DiagPath(owner); this->rowAlignment_ = grid.DiagPathRank(owner); } else if( data.colDist == MR && data.rowDist == MC ) { Int owner; if( offset >= 0 ) { const Int ownerCol = data.colAlignment; const Int ownerRow = (data.rowAlignment + offset) % r; owner = ownerRow + r*ownerCol; } else { const Int ownerCol = (data.colAlignment-offset) % c; const Int ownerRow = data.rowAlignment; owner = ownerRow + r*ownerCol; } this->diagPath_ = grid.DiagPath(owner); this->rowAlignment_ = grid.DiagPathRank(owner); } else if( data.colDist == MD && data.rowDist == STAR ) { this->diagPath_ = data.diagPath; this->rowAlignment_ = data.colAlignment; } else if( data.colDist == STAR && data.rowDist == MD ) { this->diagPath_ = data.diagPath; this->rowAlignment_ = data.rowAlignment; } #ifndef RELEASE else throw std::logic_error("Nonsensical AlignWithDiagonal"); #endif this->constrainedRowAlignment_ = true; this->SetShifts(); } template<typename T,typename Int> void DistMatrix<T,STAR,MD,Int>::AlignWithDiagonal ( const AbstractDistMatrix<T,Int>& A, Int offset ) { this->AlignWithDiagonal( A.DistData(), offset ); } template<typename T,typename Int> void DistMatrix<T,STAR,MD,Int>::PrintBase ( std::ostream& os, const std::string msg ) const { #ifndef RELEASE CallStackEntry entry("[* ,MD]::PrintBase"); #endif if( this->Grid().Rank() == 0 && msg != "" ) os << msg << std::endl; const Int height = this->Height(); const Int width = this->Width(); const Int localWidth = this->LocalWidth(); const Int lcm = this->Grid().LCM(); if( height == 0 || width == 0 || !this->Grid().InGrid() ) return; std::vector<T> sendBuf(height*width,0); if( this->Participating() ) { const Int colShift = this->ColShift(); const T* thisBuffer = this->LockedBuffer(); const Int thisLDim = this->LDim(); #ifdef HAVE_OPENMP #pragma omp parallel for #endif for( Int jLocal=0; jLocal<localWidth; ++jLocal ) { T* destCol = &sendBuf[colShift+jLocal*lcm*height]; const T* sourceCol = &thisBuffer[jLocal*thisLDim]; for( Int i=0; i<height; ++i ) destCol[i] = sourceCol[i]; } } // If we are the root, allocate a receive buffer std::vector<T> recvBuf; if( this->Grid().Rank() == 0 ) recvBuf.resize( height*width ); // Sum the contributions and send to the root mpi::Reduce ( &sendBuf[0], &recvBuf[0], height*width, mpi::SUM, 0, this->Grid().Comm() ); if( this->Grid().Rank() == 0 ) { // Print the data for( Int i=0; i<height; ++i ) { for( Int j=0; j<width; ++j ) os << recvBuf[i+j*height] << " "; os << "\n"; } os << std::endl; } } template<typename T,typename Int> void DistMatrix<T,STAR,MD,Int>::Attach ( Int height, Int width, Int rowAlignmentVC, T* buffer, Int ldim, const elem::Grid& grid ) { #ifndef RELEASE CallStackEntry entry("[* ,MD]::Attach"); #endif this->Empty(); this->grid_ = &grid; this->height_ = height; this->width_ = width; this->diagPath_ = grid.DiagPath(rowAlignmentVC); this->rowAlignment_ = grid.DiagPathRank(rowAlignmentVC); this->viewing_ = true; this->SetRowShift(); if( this->Participating() ) { const Int localWidth = Length(width,this->rowShift_,grid.LCM()); this->matrix_.Attach( height, localWidth, buffer, ldim ); } } template<typename T,typename Int> void DistMatrix<T,STAR,MD,Int>::LockedAttach ( Int height, Int width, Int rowAlignmentVC, const T* buffer, Int ldim, const elem::Grid& grid ) { #ifndef RELEASE CallStackEntry entry("[* ,MD]::LockedAttach"); #endif this->Empty(); this->grid_ = &grid; this->height_ = height; this->width_ = width; this->diagPath_ = grid.DiagPath(rowAlignmentVC); this->rowAlignment_ = grid.DiagPathRank(rowAlignmentVC); this->viewing_ = true; this->locked_ = true; this->SetRowShift(); if( this->Participating() ) { const Int localWidth = Length(width,this->rowShift_,grid.LCM()); this->matrix_.LockedAttach( height, localWidth, buffer, ldim ); } } template<typename T,typename Int> void DistMatrix<T,STAR,MD,Int>::ResizeTo( Int height, Int width ) { #ifndef RELEASE CallStackEntry entry("[* ,MD]::ResizeTo"); this->AssertNotLocked(); if( height < 0 || width < 0 ) throw std::logic_error("Height and width must be non-negative"); #endif this->height_ = height; this->width_ = width; if( this->Participating() ) { const Int lcm = this->Grid().LCM(); this->matrix_.ResizeTo( height, Length(width,this->RowShift(),lcm) ); } } template<typename T,typename Int> T DistMatrix<T,STAR,MD,Int>::Get( Int i, Int j ) const { #ifndef RELEASE CallStackEntry entry("[* ,MD]::Get"); this->AssertValidEntry( i, j ); #endif // We will determine the owner of entry (i,j) and broadcast from it const elem::Grid& g = this->Grid(); const Int r = g.Height(); const Int c = g.Width(); const Int ownerRow = (j + this->rowAlignment_) % r; const Int ownerCol = (j + this->rowAlignment_ + this->diagPath_) % c; const Int ownerRank = ownerRow + r*ownerCol; T u; if( g.VCRank() == ownerRank ) { const Int jLoc = (j-this->RowShift()) / g.LCM(); u = this->GetLocal(i,jLoc); } mpi::Broadcast( &u, 1, g.VCToViewingMap(ownerRank), g.ViewingComm() ); return u; } template<typename T,typename Int> void DistMatrix<T,STAR,MD,Int>::Set( Int i, Int j, T u ) { #ifndef RELEASE CallStackEntry entry("[* ,MD]::Set"); this->AssertValidEntry( i, j ); #endif const elem::Grid& g = this->Grid(); const Int r = g.Height(); const Int c = g.Width(); const Int ownerRow = (j + this->rowAlignment_) % r; const Int ownerCol = (j + this->rowAlignment_ + this->diagPath_) % c; const Int ownerRank = ownerRow + r*ownerCol; if( g.VCRank() == ownerRank ) { const Int jLoc = (j-this->RowShift()) / g.LCM(); this->SetLocal(i,jLoc,u); } } template<typename T,typename Int> void DistMatrix<T,STAR,MD,Int>::Update( Int i, Int j, T u ) { #ifndef RELEASE CallStackEntry entry("[* ,MD]::Update"); this->AssertValidEntry( i, j ); #endif const elem::Grid& g = this->Grid(); const Int r = g.Height(); const Int c = g.Width(); const Int ownerRow = (j + this->rowAlignment_) % r; const Int ownerCol = (j + this->rowAlignment_ + this->diagPath_) % c; const Int ownerRank = ownerRow + r*ownerCol; if( g.VCRank() == ownerRank ) { const Int jLoc = (j-this->RowShift()) / g.LCM(); this->UpdateLocal(i,jLoc,u); } } // // Utility functions, e.g., operator= // template<typename T,typename Int> const DistMatrix<T,STAR,MD,Int>& DistMatrix<T,STAR,MD,Int>::operator=( const DistMatrix<T,MC,MR,Int>& A ) { #ifndef RELEASE CallStackEntry entry("[* ,MD] = [MC,MR]"); this->AssertNotLocked(); this->AssertSameGrid( A.Grid() ); if( this->Viewing() ) this->AssertSameSize( A.Height(), A.Width() ); #endif throw std::logic_error("[* ,MD] = [MC,MR] not yet implemented"); return *this; } template<typename T,typename Int> const DistMatrix<T,STAR,MD,Int>& DistMatrix<T,STAR,MD,Int>::operator=( const DistMatrix<T,MC,STAR,Int>& A ) { #ifndef RELEASE CallStackEntry entry("[* ,MD] = [MC,* ]"); this->AssertNotLocked(); this->AssertSameGrid( A.Grid() ); if( this->Viewing() ) this->AssertSameSize( A.Height(), A.Width() ); #endif throw std::logic_error("[* ,MD] = [MC,* ] not yet implemented"); return *this; } template<typename T,typename Int> const DistMatrix<T,STAR,MD,Int>& DistMatrix<T,STAR,MD,Int>::operator=( const DistMatrix<T,STAR,MR,Int>& A ) { #ifndef RELEASE CallStackEntry entry("[* ,MD] = [* ,MR]"); this->AssertNotLocked(); this->AssertSameGrid( A.Grid() ); if( this->Viewing() ) this->AssertSameSize( A.Height(), A.Width() ); #endif throw std::logic_error("[* ,MD] = [* ,MR] not yet implemented"); return *this; } template<typename T,typename Int> const DistMatrix<T,STAR,MD,Int>& DistMatrix<T,STAR,MD,Int>::operator=( const DistMatrix<T,MD,STAR,Int>& A ) { #ifndef RELEASE CallStackEntry entry("[* ,MD] = [MD,* ]"); this->AssertNotLocked(); this->AssertSameGrid( A.Grid() ); if( this->Viewing() ) this->AssertSameSize( A.Height(), A.Width() ); #endif throw std::logic_error("[* ,MD] = [MD,* ] not yet implemented"); return *this; } template<typename T,typename Int> const DistMatrix<T,STAR,MD,Int>& DistMatrix<T,STAR,MD,Int>::operator=( const DistMatrix<T,STAR,MD,Int>& A ) { #ifndef RELEASE CallStackEntry entry("[* ,MD] = [* ,MD]"); this->AssertNotLocked(); this->AssertSameGrid( A.Grid() ); if( this->Viewing() ) this->AssertSameSize( A.Height(), A.Width() ); #endif if( !this->Viewing() ) { if( !this->ConstrainedRowAlignment() ) { this->diagPath_ = A.diagPath_; this->rowAlignment_ = A.rowAlignment_; if( this->Participating() ) this->rowShift_ = A.RowShift(); } this->ResizeTo( A.Height(), A.Width() ); } if( this->diagPath_ == A.diagPath_ && this->rowAlignment_ == A.rowAlignment_ ) { this->matrix_ = A.LockedMatrix(); } else { #ifdef UNALIGNED_WARNINGS if( this->Grid().Rank() == 0 ) std::cerr << "Unaligned [* ,MD] <- [* ,MD]." << std::endl; #endif throw std::logic_error ("Unaligned [* ,MD] = [* ,MD] not yet implemented"); } return *this; } template<typename T,typename Int> const DistMatrix<T,STAR,MD,Int>& DistMatrix<T,STAR,MD,Int>::operator=( const DistMatrix<T,MR,MC,Int>& A ) { #ifndef RELEASE CallStackEntry entry("[* ,MD] = [MR,MC]"); this->AssertNotLocked(); this->AssertSameGrid( A.Grid() ); if( this->Viewing() ) this->AssertSameSize( A.Height(), A.Width() ); #endif throw std::logic_error("[* ,MD] = [MR,MC] not yet implemented"); return *this; } template<typename T,typename Int> const DistMatrix<T,STAR,MD,Int>& DistMatrix<T,STAR,MD,Int>::operator=( const DistMatrix<T,MR,STAR,Int>& A ) { #ifndef RELEASE CallStackEntry entry("[* ,MD] = [MR,* ]"); this->AssertNotLocked(); this->AssertSameGrid( A.Grid() ); if( this->Viewing() ) this->AssertSameSize( A.Height(), A.Width() ); #endif throw std::logic_error("[* ,MD] = [MR,* ] not yet implemented"); return *this; } template<typename T,typename Int> const DistMatrix<T,STAR,MD,Int>& DistMatrix<T,STAR,MD,Int>::operator=( const DistMatrix<T,STAR,MC,Int>& A ) { #ifndef RELEASE CallStackEntry entry("[* ,MD] = [* ,MC]"); this->AssertNotLocked(); this->AssertSameGrid( A.Grid() ); if( this->Viewing() ) this->AssertSameSize( A.Height(), A.Width() ); #endif throw std::logic_error("[* ,MD] = [* ,MC] not yet implemented"); return *this; } template<typename T,typename Int> const DistMatrix<T,STAR,MD,Int>& DistMatrix<T,STAR,MD,Int>::operator=( const DistMatrix<T,VC,STAR,Int>& A ) { #ifndef RELEASE CallStackEntry entry("[* ,MD] = [VC,* ]"); this->AssertNotLocked(); this->AssertSameGrid( A.Grid() ); if( this->Viewing() ) this->AssertSameSize( A.Height(), A.Width() ); #endif throw std::logic_error("[* ,MD] = [VC,* ] not yet implemented"); return *this; } template<typename T,typename Int> const DistMatrix<T,STAR,MD,Int>& DistMatrix<T,STAR,MD,Int>::operator=( const DistMatrix<T,STAR,VC,Int>& A ) { #ifndef RELEASE CallStackEntry entry("[* ,MD] = [* ,VC]"); this->AssertNotLocked(); this->AssertSameGrid( A.Grid() ); if( this->Viewing() ) this->AssertSameSize( A.Height(), A.Width() ); #endif throw std::logic_error("[* ,MD] = [* ,VC] not yet implemented"); return *this; } template<typename T,typename Int> const DistMatrix<T,STAR,MD,Int>& DistMatrix<T,STAR,MD,Int>::operator=( const DistMatrix<T,VR,STAR,Int>& A ) { #ifndef RELEASE CallStackEntry entry("[* ,MD] = [VR,* ]"); this->AssertNotLocked(); this->AssertSameGrid( A.Grid() ); if( this->Viewing() ) this->AssertSameSize( A.Height(), A.Width() ); #endif throw std::logic_error("[* ,MD] = [VR,* ] not yet implemented"); return *this; } template<typename T,typename Int> const DistMatrix<T,STAR,MD,Int>& DistMatrix<T,STAR,MD,Int>::operator=( const DistMatrix<T,STAR,VR,Int>& A ) { #ifndef RELEASE CallStackEntry entry("[* ,MD] = [* ,VR]"); this->AssertNotLocked(); this->AssertSameGrid( A.Grid() ); if( this->Viewing() ) this->AssertSameSize( A.Height(), A.Width() ); #endif throw std::logic_error("[* ,MD] = [* ,VR] not yet implemented"); return *this; } template<typename T,typename Int> const DistMatrix<T,STAR,MD,Int>& DistMatrix<T,STAR,MD,Int>::operator=( const DistMatrix<T,STAR,STAR,Int>& A ) { #ifndef RELEASE CallStackEntry entry("[* ,MD] = [* ,* ]"); this->AssertNotLocked(); this->AssertSameGrid( A.Grid() ); if( this->Viewing() ) this->AssertSameSize( A.Height(), A.Width() ); #endif if( !this->Viewing() ) this->ResizeTo( A.Height(), A.Width() ); if( this->Participating() ) { const Int lcm = this->Grid().LCM(); const Int rowShift = this->RowShift(); const Int height = this->Height(); const Int localWidth = this->LocalWidth(); T* thisBuffer = this->Buffer(); const Int thisLDim = this->LDim(); const T* ABuffer = A.LockedBuffer(); const Int ALDim = A.LDim(); #ifdef HAVE_OPENMP #pragma omp parallel for #endif for( Int jLocal=0; jLocal<localWidth; ++jLocal ) { const T* ACol = &ABuffer[(rowShift+jLocal*lcm)*ALDim]; T* thisCol = &thisBuffer[jLocal*thisLDim]; MemCopy( thisCol, ACol, height ); } } return *this; } // // Routines which explicitly work in the complex plane // template<typename T,typename Int> BASE(T) DistMatrix<T,STAR,MD,Int>::GetRealPart( Int i, Int j ) const { #ifndef RELEASE CallStackEntry entry("[* ,MD]::GetRealPart"); this->AssertValidEntry( i, j ); #endif typedef BASE(T) R; // We will determine the owner of entry (i,j) and broadcast from it const elem::Grid& g = this->Grid(); const Int r = g.Height(); const Int c = g.Width(); const Int ownerRow = (j + this->rowAlignment_) % r; const Int ownerCol = (j + this->rowAlignment_ + this->diagPath_) % c; const Int ownerRank = ownerRow + r*ownerCol; R u; if( g.VCRank() == ownerRank ) { const Int jLocal = (j-this->RowShift()) / g.LCM(); u = this->GetLocalRealPart( i, jLocal ); } mpi::Broadcast( &u, 1, g.VCToViewingMap(ownerRank), g.ViewingComm() ); return u; } template<typename T,typename Int> BASE(T) DistMatrix<T,STAR,MD,Int>::GetImagPart( Int i, Int j ) const { #ifndef RELEASE CallStackEntry entry("[* ,MD]::GetImagPart"); this->AssertValidEntry( i, j ); #endif typedef BASE(T) R; // We will determine the owner of entry (i,j) and broadcast from it const elem::Grid& g = this->Grid(); const Int r = g.Height(); const Int c = g.Width(); const Int ownerRow = (j + this->rowAlignment_) % r; const Int ownerCol = (j + this->rowAlignment_ + this->diagPath_) % c; const Int ownerRank = ownerRow + r*ownerCol; R u; if( g.VCRank() == ownerRank ) { const Int jLocal = (j-this->RowShift()) / g.LCM(); u = this->GetLocalImagPart( i, jLocal ); } mpi::Broadcast( &u, 1, g.VCToViewingMap(ownerRank), g.ViewingComm() ); return u; } template<typename T,typename Int> void DistMatrix<T,STAR,MD,Int>::SetRealPart( Int i, Int j, BASE(T) u ) { #ifndef RELEASE CallStackEntry entry("[* ,MD]::SetRealPart"); this->AssertValidEntry( i, j ); #endif const elem::Grid& g = this->Grid(); const Int r = g.Height(); const Int c = g.Width(); const Int ownerRow = (j + this->rowAlignment_) % r; const Int ownerCol = (j + this->rowAlignment_ + this->diagPath_) % c; const Int ownerRank = ownerRow + r*ownerCol; if( g.VCRank() == ownerRank ) { const Int jLocal = (j-this->RowShift()) / g.LCM(); this->SetLocalRealPart( i, jLocal, u ); } } template<typename T,typename Int> void DistMatrix<T,STAR,MD,Int>::SetImagPart( Int i, Int j, BASE(T) u ) { #ifndef RELEASE CallStackEntry entry("[* ,MD]::SetImagPart"); this->AssertValidEntry( i, j ); #endif if( !IsComplex<T>::val ) throw std::logic_error("Called complex-only routine with real data"); const elem::Grid& g = this->Grid(); const Int r = g.Height(); const Int c = g.Width(); const Int ownerRow = (j + this->rowAlignment_) % r; const Int ownerCol = (j + this->rowAlignment_ + this->diagPath_) % c; const Int ownerRank = ownerRow + r*ownerCol; if( g.VCRank() == ownerRank ) { const Int jLocal = (j-this->RowShift()) / g.LCM(); this->SetLocalImagPart( i, jLocal, u ); } } template<typename T,typename Int> void DistMatrix<T,STAR,MD,Int>::UpdateRealPart( Int i, Int j, BASE(T) u ) { #ifndef RELEASE CallStackEntry entry("[* ,MD]::UpdateRealPart"); this->AssertValidEntry( i, j ); #endif const elem::Grid& g = this->Grid(); const Int r = g.Height(); const Int c = g.Width(); const Int ownerRow = (j + this->rowAlignment_) % r; const Int ownerCol = (j + this->rowAlignment_ + this->diagPath_) % c; const Int ownerRank = ownerRow + r*ownerCol; if( g.VCRank() == ownerRank ) { const Int jLocal = (j-this->RowShift()) / g.LCM(); this->UpdateLocalRealPart( i, jLocal, u ); } } template<typename T,typename Int> void DistMatrix<T,STAR,MD,Int>::UpdateImagPart( Int i, Int j, BASE(T) u ) { #ifndef RELEASE CallStackEntry entry("[* ,MD]::UpdateImagPart"); this->AssertValidEntry( i, j ); #endif if( !IsComplex<T>::val ) throw std::logic_error("Called complex-only routine with real data"); const elem::Grid& g = this->Grid(); const Int r = g.Height(); const Int c = g.Width(); const Int ownerRow = (j + this->rowAlignment_) % r; const Int ownerCol = (j + this->rowAlignment_ + this->diagPath_) % c; const Int ownerRank = ownerRow + r*ownerCol; if( g.VCRank() == ownerRank ) { const Int jLocal = (j-this->RowShift()) / g.LCM(); this->UpdateLocalImagPart( i, jLocal, u ); } } template class DistMatrix<int,STAR,MD,int>; template DistMatrix<int,STAR,MD,int>::DistMatrix( const DistMatrix<int,MC, MR, int>& A ); template DistMatrix<int,STAR,MD,int>::DistMatrix( const DistMatrix<int,MC, STAR,int>& A ); template DistMatrix<int,STAR,MD,int>::DistMatrix( const DistMatrix<int,MD, STAR,int>& A ); template DistMatrix<int,STAR,MD,int>::DistMatrix( const DistMatrix<int,MR, MC, int>& A ); template DistMatrix<int,STAR,MD,int>::DistMatrix( const DistMatrix<int,MR, STAR,int>& A ); template DistMatrix<int,STAR,MD,int>::DistMatrix( const DistMatrix<int,STAR,MC, int>& A ); template DistMatrix<int,STAR,MD,int>::DistMatrix( const DistMatrix<int,STAR,MR, int>& A ); template DistMatrix<int,STAR,MD,int>::DistMatrix( const DistMatrix<int,STAR,STAR,int>& A ); template DistMatrix<int,STAR,MD,int>::DistMatrix( const DistMatrix<int,STAR,VC, int>& A ); template DistMatrix<int,STAR,MD,int>::DistMatrix( const DistMatrix<int,STAR,VR, int>& A ); template DistMatrix<int,STAR,MD,int>::DistMatrix( const DistMatrix<int,VC, STAR,int>& A ); template DistMatrix<int,STAR,MD,int>::DistMatrix( const DistMatrix<int,VR, STAR,int>& A ); #ifndef DISABLE_FLOAT template class DistMatrix<float,STAR,MD,int>; template DistMatrix<float,STAR,MD,int>::DistMatrix( const DistMatrix<float,MC, MR, int>& A ); template DistMatrix<float,STAR,MD,int>::DistMatrix( const DistMatrix<float,MC, STAR,int>& A ); template DistMatrix<float,STAR,MD,int>::DistMatrix( const DistMatrix<float,MD, STAR,int>& A ); template DistMatrix<float,STAR,MD,int>::DistMatrix( const DistMatrix<float,MR, MC, int>& A ); template DistMatrix<float,STAR,MD,int>::DistMatrix( const DistMatrix<float,MR, STAR,int>& A ); template DistMatrix<float,STAR,MD,int>::DistMatrix( const DistMatrix<float,STAR,MC, int>& A ); template DistMatrix<float,STAR,MD,int>::DistMatrix( const DistMatrix<float,STAR,MR, int>& A ); template DistMatrix<float,STAR,MD,int>::DistMatrix( const DistMatrix<float,STAR,STAR,int>& A ); template DistMatrix<float,STAR,MD,int>::DistMatrix( const DistMatrix<float,STAR,VC, int>& A ); template DistMatrix<float,STAR,MD,int>::DistMatrix( const DistMatrix<float,STAR,VR, int>& A ); template DistMatrix<float,STAR,MD,int>::DistMatrix( const DistMatrix<float,VC, STAR,int>& A ); template DistMatrix<float,STAR,MD,int>::DistMatrix( const DistMatrix<float,VR, STAR,int>& A ); #endif // ifndef DISABLE_FLOAT template class DistMatrix<double,STAR,MD,int>; template DistMatrix<double,STAR,MD,int>::DistMatrix( const DistMatrix<double,MC, MR, int>& A ); template DistMatrix<double,STAR,MD,int>::DistMatrix( const DistMatrix<double,MC, STAR,int>& A ); template DistMatrix<double,STAR,MD,int>::DistMatrix( const DistMatrix<double,MD, STAR,int>& A ); template DistMatrix<double,STAR,MD,int>::DistMatrix( const DistMatrix<double,MR, MC, int>& A ); template DistMatrix<double,STAR,MD,int>::DistMatrix( const DistMatrix<double,MR, STAR,int>& A ); template DistMatrix<double,STAR,MD,int>::DistMatrix( const DistMatrix<double,STAR,MC, int>& A ); template DistMatrix<double,STAR,MD,int>::DistMatrix( const DistMatrix<double,STAR,MR, int>& A ); template DistMatrix<double,STAR,MD,int>::DistMatrix( const DistMatrix<double,STAR,STAR,int>& A ); template DistMatrix<double,STAR,MD,int>::DistMatrix( const DistMatrix<double,STAR,VC, int>& A ); template DistMatrix<double,STAR,MD,int>::DistMatrix( const DistMatrix<double,STAR,VR, int>& A ); template DistMatrix<double,STAR,MD,int>::DistMatrix( const DistMatrix<double,VC, STAR,int>& A ); template DistMatrix<double,STAR,MD,int>::DistMatrix( const DistMatrix<double,VR, STAR,int>& A ); #ifndef DISABLE_COMPLEX #ifndef DISABLE_FLOAT template class DistMatrix<Complex<float>,STAR,MD,int>; template DistMatrix<Complex<float>,STAR,MD,int>::DistMatrix( const DistMatrix<Complex<float>,MC, MR, int>& A ); template DistMatrix<Complex<float>,STAR,MD,int>::DistMatrix( const DistMatrix<Complex<float>,MC, STAR,int>& A ); template DistMatrix<Complex<float>,STAR,MD,int>::DistMatrix( const DistMatrix<Complex<float>,MD, STAR,int>& A ); template DistMatrix<Complex<float>,STAR,MD,int>::DistMatrix( const DistMatrix<Complex<float>,MR, MC, int>& A ); template DistMatrix<Complex<float>,STAR,MD,int>::DistMatrix( const DistMatrix<Complex<float>,MR, STAR,int>& A ); template DistMatrix<Complex<float>,STAR,MD,int>::DistMatrix( const DistMatrix<Complex<float>,STAR,MC, int>& A ); template DistMatrix<Complex<float>,STAR,MD,int>::DistMatrix( const DistMatrix<Complex<float>,STAR,MR, int>& A ); template DistMatrix<Complex<float>,STAR,MD,int>::DistMatrix( const DistMatrix<Complex<float>,STAR,STAR,int>& A ); template DistMatrix<Complex<float>,STAR,MD,int>::DistMatrix( const DistMatrix<Complex<float>,STAR,VC, int>& A ); template DistMatrix<Complex<float>,STAR,MD,int>::DistMatrix( const DistMatrix<Complex<float>,STAR,VR, int>& A ); template DistMatrix<Complex<float>,STAR,MD,int>::DistMatrix( const DistMatrix<Complex<float>,VC, STAR,int>& A ); template DistMatrix<Complex<float>,STAR,MD,int>::DistMatrix( const DistMatrix<Complex<float>,VR, STAR,int>& A ); #endif // ifndef DISABLE_FLOAT template class DistMatrix<Complex<double>,STAR,MD,int>; template DistMatrix<Complex<double>,STAR,MD,int>::DistMatrix( const DistMatrix<Complex<double>,MC, MR, int>& A ); template DistMatrix<Complex<double>,STAR,MD,int>::DistMatrix( const DistMatrix<Complex<double>,MC, STAR,int>& A ); template DistMatrix<Complex<double>,STAR,MD,int>::DistMatrix( const DistMatrix<Complex<double>,MD, STAR,int>& A ); template DistMatrix<Complex<double>,STAR,MD,int>::DistMatrix( const DistMatrix<Complex<double>,MR, MC, int>& A ); template DistMatrix<Complex<double>,STAR,MD,int>::DistMatrix( const DistMatrix<Complex<double>,MR, STAR,int>& A ); template DistMatrix<Complex<double>,STAR,MD,int>::DistMatrix( const DistMatrix<Complex<double>,STAR,MC, int>& A ); template DistMatrix<Complex<double>,STAR,MD,int>::DistMatrix( const DistMatrix<Complex<double>,STAR,MR, int>& A ); template DistMatrix<Complex<double>,STAR,MD,int>::DistMatrix( const DistMatrix<Complex<double>,STAR,STAR,int>& A ); template DistMatrix<Complex<double>,STAR,MD,int>::DistMatrix( const DistMatrix<Complex<double>,STAR,VC, int>& A ); template DistMatrix<Complex<double>,STAR,MD,int>::DistMatrix( const DistMatrix<Complex<double>,STAR,VR, int>& A ); template DistMatrix<Complex<double>,STAR,MD,int>::DistMatrix( const DistMatrix<Complex<double>,VC, STAR,int>& A ); template DistMatrix<Complex<double>,STAR,MD,int>::DistMatrix( const DistMatrix<Complex<double>,VR, STAR,int>& A ); #endif // ifndef DISABLE_COMPLEX } // namespace elem
33.809569
115
0.644222
ahmadia
70c912c728b318119c33e8cda2880a02a2410278
855
cpp
C++
test/unit/concepts/object/movable.cpp
cjdb/clang-concepts-ranges
7019754e97c8f3863035db74de62004ae3814954
[ "Apache-2.0" ]
4
2019-03-02T01:09:07.000Z
2019-10-16T15:46:21.000Z
test/unit/concepts/object/movable.cpp
cjdb/cjdb-ranges
7019754e97c8f3863035db74de62004ae3814954
[ "Apache-2.0" ]
5
2019-11-29T12:23:55.000Z
2019-12-14T13:03:00.000Z
test/unit/concepts/object/movable.cpp
cjdb/clang-concepts-ranges
7019754e97c8f3863035db74de62004ae3814954
[ "Apache-2.0" ]
3
2020-06-08T18:27:28.000Z
2021-03-27T17:49:46.000Z
// Copyright Casey Carter // // Use, modification and distribution is subject to the // Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // Derived from: https://github.com/caseycarter/cmcstl2 // Project home: https://github.com/cjdb/clang-concepts-ranges // #include "cjdb/concepts/object/movable.hpp" #include "../object.hpp" static_assert(cjdb::movable<int>); static_assert(not cjdb::movable<const int>); static_assert(cjdb::movable<double>); static_assert(not cjdb::movable<void>); static_assert(cjdb::movable<copyable>); static_assert(cjdb::movable<moveonly>); static_assert(not cjdb::movable<nonmovable>); static_assert(not cjdb::movable<copyonly>); // https://github.com/ericniebler/stl2/issues/310 static_assert(not cjdb::movable<int&&>); int main() {}
30.535714
62
0.747368
cjdb
70c9a0ad80a4b478dd8bd564fa33e9309bc5f8e5
817
hpp
C++
src/database/kernels/xger/xger.hpp
vbkaisetsu/CLBlast
441373c8fd1442cc4c024e59e7778b4811eb210c
[ "Apache-2.0" ]
null
null
null
src/database/kernels/xger/xger.hpp
vbkaisetsu/CLBlast
441373c8fd1442cc4c024e59e7778b4811eb210c
[ "Apache-2.0" ]
null
null
null
src/database/kernels/xger/xger.hpp
vbkaisetsu/CLBlast
441373c8fd1442cc4c024e59e7778b4811eb210c
[ "Apache-2.0" ]
1
2020-09-09T21:04:21.000Z
2020-09-09T21:04:21.000Z
// ================================================================================================= // This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. It // is auto-generated by the 'scripts/database/database.py' Python script. // // This file populates the database with best-found tuning parameters for the 'Xger' kernels. // // ================================================================================================= #include "database/database_structure.hpp" namespace clblast { namespace database { extern const DatabaseEntry XgerHalf; extern const DatabaseEntry XgerSingle; extern const DatabaseEntry XgerComplexSingle; extern const DatabaseEntry XgerDouble; extern const DatabaseEntry XgerComplexDouble; } // namespace database } // namespace clblast
35.521739
100
0.599755
vbkaisetsu
70c9a5d535d3ccf3a44720dc282ec6a2dc50d46d
7,001
cpp
C++
mod/vulkan/VulkanTexture.cpp
Lyatus/L
0b594d722200d5ee0198b5d7b9ee72a5d1e12611
[ "Unlicense" ]
45
2018-08-24T12:57:38.000Z
2021-11-12T11:21:49.000Z
mod/vulkan/VulkanTexture.cpp
Lyatus/L
0b594d722200d5ee0198b5d7b9ee72a5d1e12611
[ "Unlicense" ]
null
null
null
mod/vulkan/VulkanTexture.cpp
Lyatus/L
0b594d722200d5ee0198b5d7b9ee72a5d1e12611
[ "Unlicense" ]
4
2019-09-16T02:48:42.000Z
2020-07-10T03:50:31.000Z
#include "VulkanRenderer.h" #include <string.h> #include "VulkanBuffer.h" using namespace L; static void transition_layout(VulkanTexture* tex, VkCommandBuffer cmd_buffer, VkImageLayout new_layout) { VkImageMemoryBarrier barrier = {}; barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; barrier.oldLayout = tex->layout; barrier.newLayout = new_layout; barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.image = tex->image; barrier.subresourceRange.baseMipLevel = 0; barrier.subresourceRange.levelCount = 1; barrier.subresourceRange.baseArrayLayer = 0; barrier.subresourceRange.layerCount = tex->layer_count; if(new_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) { barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; if(VulkanRenderer::get()->is_stencil_format(tex->format)) { barrier.subresourceRange.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT; } } else { barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; } VkPipelineStageFlags src_stage; VkPipelineStageFlags dst_stage; if(tex->layout == VK_IMAGE_LAYOUT_UNDEFINED && new_layout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) { barrier.srcAccessMask = 0; barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; src_stage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; dst_stage = VK_PIPELINE_STAGE_TRANSFER_BIT; } else if(tex->layout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && new_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) { barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; src_stage = VK_PIPELINE_STAGE_TRANSFER_BIT; dst_stage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; } else if(tex->layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL && new_layout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) { barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT; barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; src_stage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; dst_stage = VK_PIPELINE_STAGE_TRANSFER_BIT; } else if(tex->layout == VK_IMAGE_LAYOUT_UNDEFINED && new_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) { barrier.srcAccessMask = 0; barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; src_stage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; dst_stage = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT; } else { return error("Unsupported Texture layout transition"); } vkCmdPipelineBarrier(cmd_buffer, src_stage, dst_stage, 0, 0, nullptr, 0, nullptr, 1, &barrier); tex->layout = new_layout; } TextureImpl* VulkanRenderer::create_texture(uint32_t width, uint32_t height, L::RenderFormat format, const void* data, size_t size) { const bool depth_texture(Renderer::is_depth_format(format)); const bool compressed_texture(Renderer::is_block_format(format)); const bool cubemap(width*6==height); VulkanTexture* tex = Memory::new_type<VulkanTexture>(); tex->width = width; tex->height = height; tex->is_depth = depth_texture; VkImageCreateInfo image_info = {}; image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; image_info.imageType = VK_IMAGE_TYPE_2D; image_info.extent.width = width; image_info.extent.height = height = cubemap ? width : height; image_info.extent.depth = 1; image_info.mipLevels = 1; image_info.arrayLayers = tex->layer_count = cubemap ? 6 : 1; image_info.format = tex->format = to_vk_format(format); image_info.tiling = VK_IMAGE_TILING_OPTIMAL; image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; image_info.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; if(depth_texture) image_info.usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; if(!depth_texture && !compressed_texture) image_info.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; image_info.samples = VK_SAMPLE_COUNT_1_BIT; if(cubemap) image_info.flags |= VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT; L_VK_CHECKED(vkCreateImage(VulkanRenderer::get()->device(), &image_info, nullptr, &tex->image)); VkMemoryRequirements requirements; vkGetImageMemoryRequirements(VulkanRenderer::get()->device(), tex->image, &requirements); VkMemoryAllocateInfo allocInfo = {}; allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; allocInfo.allocationSize = requirements.size; allocInfo.memoryTypeIndex = VulkanRenderer::find_memory_type(requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); L_VK_CHECKED(vkAllocateMemory(_device, &allocInfo, nullptr, &tex->memory)); vkBindImageMemory(_device, tex->image, tex->memory, 0); VkImageViewCreateInfo viewInfo = {}; viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; viewInfo.image = tex->image; viewInfo.viewType = cubemap ? VK_IMAGE_VIEW_TYPE_CUBE : VK_IMAGE_VIEW_TYPE_2D; viewInfo.format = tex->format; viewInfo.subresourceRange.aspectMask = depth_texture ? VK_IMAGE_ASPECT_DEPTH_BIT : VK_IMAGE_ASPECT_COLOR_BIT; viewInfo.subresourceRange.baseMipLevel = 0; viewInfo.subresourceRange.levelCount = 1; viewInfo.subresourceRange.baseArrayLayer = 0; viewInfo.subresourceRange.layerCount = tex->layer_count; L_VK_CHECKED(vkCreateImageView(_device, &viewInfo, nullptr, &tex->view)); if(data) { // Optional loading of texture data load_texture(tex, data, size, 0, Vector3i(width, height, 1)); } return tex; } void VulkanRenderer::destroy_texture(TextureImpl* tex) { VulkanTexture* vk_tex = (VulkanTexture*)tex; VulkanRenderer::destroy_image(vk_tex->image, vk_tex->memory); Memory::delete_type(vk_tex); } void VulkanRenderer::load_texture(TextureImpl* tex, const void* data, size_t size, const L::Vector3i& offset, const L::Vector3i& extent) { VulkanTexture* vk_tex = (VulkanTexture*)tex; VulkanBuffer buffer(size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT); void* mapped_mem; vkMapMemory(_device, buffer, 0, size, 0, &mapped_mem); memcpy(mapped_mem, data, size); vkUnmapMemory(_device, buffer); VkCommandBuffer cmd(begin_command_buffer()); transition_layout(vk_tex, cmd, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); VkBufferImageCopy region = {}; region.bufferOffset = 0; region.bufferRowLength = 0; region.bufferImageHeight = 0; region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; region.imageSubresource.mipLevel = 0; region.imageSubresource.baseArrayLayer = 0; region.imageSubresource.layerCount = vk_tex->layer_count; region.imageOffset = {int32_t(offset.x()), int32_t(offset.y()), int32_t(offset.z())}; region.imageExtent = {uint32_t(extent.x()), uint32_t(extent.y()), uint32_t(extent.z())}; vkCmdCopyBufferToImage( cmd, buffer, vk_tex->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &region ); transition_layout(vk_tex, cmd, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); end_command_buffer(cmd); }
40.468208
138
0.783031
Lyatus
70cb4c8e7bb1362e74699611074c0954c4bd0e63
722
hpp
C++
include/tao/pq/internal/demangle.hpp
huzaifanazir/taopq
8f939d33840f14d7c08311729745fe7bb8cd9898
[ "BSL-1.0" ]
69
2016-08-05T19:16:04.000Z
2018-11-24T15:13:46.000Z
include/tao/pq/internal/demangle.hpp
huzaifanazir/taopq
8f939d33840f14d7c08311729745fe7bb8cd9898
[ "BSL-1.0" ]
13
2016-11-24T16:42:28.000Z
2018-09-11T18:55:40.000Z
include/tao/pq/internal/demangle.hpp
huzaifanazir/taopq
8f939d33840f14d7c08311729745fe7bb8cd9898
[ "BSL-1.0" ]
13
2016-09-22T17:31:10.000Z
2018-10-18T02:56:49.000Z
// Copyright (c) 2016-2022 Daniel Frey and Dr. Colin Hirsch // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt) #ifndef TAO_PQ_INTERNAL_DEMANGLE_HPP #define TAO_PQ_INTERNAL_DEMANGLE_HPP #include <string> #include <typeinfo> namespace tao::pq::internal { [[nodiscard]] auto demangle( const char* const symbol ) -> std::string; [[nodiscard]] inline auto demangle( const std::type_info& type_info ) { return demangle( type_info.name() ); } template< typename T > [[nodiscard]] auto demangle() { return internal::demangle( typeid( T ) ); } } // namespace tao::pq::internal #endif
24.896552
91
0.699446
huzaifanazir
70cdd7e1cbee6c60eeca96464f1c535a594e9792
1,224
cpp
C++
LeetCode/ThousandOne/0463-island_perimeter.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
LeetCode/ThousandOne/0463-island_perimeter.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
LeetCode/ThousandOne/0463-island_perimeter.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
#include "leetcode.hpp" /* 463. 岛屿的周长 给定一个包含 0 和 1 的二维网格地图,其中 1 表示陆地 0 表示水域。 网格中的格子水平和垂直方向相连(对角线方向不相连)。整个网格被水完全包围,但其中恰好有一个岛屿(或者说,一个或多个表示陆地的格子相连组成的岛屿)。 岛屿中没有“湖”(“湖” 指水域在岛屿内部且不和岛屿周围的水相连)。格子是边长为 1 的正方形。网格为长方形,且宽度和高度均不超过 100 。计算这个岛屿的周长。 示例 : 输入: [[0,1,0,0}, [1,1,1,0}, [0,1,0,0}, [1,1,0,0}} 输出: 16 解释: 它的周长是下面图片中的 16 个黄色的边: https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/10/12/island.png https://assets.leetcode.com/uploads/2018/10/12/island.png */ int islandPerimeter(vector<vector<int>>& grid) { int const xdir[4] = { 0, -1, 1, 0 }; int const ydir[4] = { -1, 0, 0, 1 }; int perimeter = 0; unsigned rows = grid.size(); if (rows == 0) return 0; unsigned cols = grid[0].size(); for (unsigned h = 0; h < rows; ++h) { int const* ptr = grid[h].data(); for (unsigned w = 0; w < cols; ++w) { if (ptr[w] == 0) continue; for (int d = 0; d < 4; ++d) { unsigned dy = h + ydir[d]; unsigned dx = w + xdir[d]; if (dy >= rows || dx >= cols || grid[dy][dx] == 0) ++perimeter; } } } return perimeter; } int main() { vector<vector<int>> grid = { { 0, 1, 0, 0 }, { 1, 1, 1, 0 }, { 0, 1, 0, 0 }, { 1, 1, 0, 0 } }; OutExpr(islandPerimeter(grid), "%d"); }
18.830769
81
0.577614
Ginkgo-Biloba
70ce716e42597346c786920f7378b69a19fcd559
2,347
hpp
C++
include/Game/Game.hpp
darwin-s/nanocraft
dcb8b590fa3310b726529ab5e36b18893f6a3b1f
[ "Apache-2.0" ]
2
2021-08-12T10:05:53.000Z
2021-08-13T16:25:49.000Z
include/Game/Game.hpp
darwin-s/nanocraft
dcb8b590fa3310b726529ab5e36b18893f6a3b1f
[ "Apache-2.0" ]
null
null
null
include/Game/Game.hpp
darwin-s/nanocraft
dcb8b590fa3310b726529ab5e36b18893f6a3b1f
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 Sirbu Dan // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef NC_GAME_GAME_HPP #define NC_GAME_GAME_HPP #include <General/TextureAtlas.hpp> #include <Game/GameState.hpp> #include <Game/GameRegistry.hpp> #include <SFML/Graphics.hpp> #include <nlohmann/json.hpp> #include <spdlog/spdlog.h> #include <spdlog/sinks/ostream_sink.h> #include <entt/entt.hpp> #include <sstream> #include <memory> namespace nc { class Game { public: static constexpr float TIMESTEP = 1.0f / 60.0f; public: Game(int argc, char** argv); void run(); const nlohmann::json& getSettings() const; void saveSettings(); TextureAtlas& getTextureAtlas(); sf::View& getView(); void setTimeScale(float scale); float getTimeScale() const; void setState(GameState* newState); GameState* getState() const; sf::RenderWindow& getWindow(); GameRegistry& getRegistry(); static Game* getInstance(); private: void setup(); void execute(); void loadSettings(); void createDefaultSettings(); void loadTextures(); void loadItems(); void loadTiles(); private: static Game* m_inst; // Game instance int m_argc; char** m_argv; bool m_drawConsole; GameState* m_gameState; // Game state object GameState* m_requestedState; // Requested game state GameRegistry m_reg; // Game registry nlohmann::json m_settings; std::ostringstream m_logData; // Log data stream std::shared_ptr<spdlog::sinks::ostream_sink_mt> m_sink; // Log sink std::shared_ptr<spdlog::logger> m_logger; // Logger sf::Clock m_delta; // Delta time clock TextureAtlas m_atlas; // Texture atlas sf::RenderWindow m_win; // Game window sf::View m_view; // Main camera float m_timeScale; // Game time scale }; } #endif // !NC_GAME_GAME_HPP
26.977011
75
0.701321
darwin-s
70d2c517ca31ef38a4ad04cba199cc6cf1457bce
710
cpp
C++
Sid's Contests/LeetCode contests/April Challenge/Rotate Image.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
14
2021-08-22T18:21:14.000Z
2022-03-08T12:04:23.000Z
Sid's Contests/LeetCode contests/April Challenge/Rotate Image.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
1
2021-10-17T18:47:17.000Z
2021-10-17T18:47:17.000Z
Sid's Contests/LeetCode contests/April Challenge/Rotate Image.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
5
2021-09-01T08:21:12.000Z
2022-03-09T12:13:39.000Z
class Solution { public: void rotate(vector<vector<int>>& matrix) { //OM GAN GANAPATHAYE NAMO NAMAH //JAI SHRI RAM //JAI BAJRANGBALI //AMME NARAYANA, DEVI NARAYANA, LAKSHMI NARAYANA, BHADRE NARAYANA for(int i = 0; i < matrix.size(); i++) { for(int j = 0; j <= i; j++) { swap(matrix[i][j], matrix[j][i]); } } //reverse each row for(int i = 0; i < matrix.size(); i++) { for(int j = 0; j < (matrix[i].size()/2); j++) { int x = matrix[i].size(); swap(matrix[i][j], matrix[i][x-j-1]); } } } };
27.307692
73
0.416901
Tiger-Team-01
70d529f5d2285b20a267995b35c49010d882a796
7,019
cpp
C++
src/petuum_ps/client/thread_table.cpp
ForrestGan/public
2cada36c4b523cf80f16a4f0d0fdc01166a69df1
[ "BSD-3-Clause" ]
null
null
null
src/petuum_ps/client/thread_table.cpp
ForrestGan/public
2cada36c4b523cf80f16a4f0d0fdc01166a69df1
[ "BSD-3-Clause" ]
null
null
null
src/petuum_ps/client/thread_table.cpp
ForrestGan/public
2cada36c4b523cf80f16a4f0d0fdc01166a69df1
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2014, Sailing Lab // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the <ORGANIZATION> nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <petuum_ps/client/thread_table.hpp> #include <petuum_ps/thread/context.hpp> #include <petuum_ps_common/include/row_access.hpp> #include <glog/logging.h> #include <functional> namespace petuum { ThreadTable::ThreadTable(const AbstractRow *sample_row) : oplog_index_(GlobalContext::get_num_bg_threads()), sample_row_(sample_row){ } ThreadTable::~ThreadTable() { for (auto iter = row_storage_.begin(); iter != row_storage_.end(); iter++) { if (iter->second != 0) delete iter->second; } for (auto iter = oplog_map_.begin(); iter != oplog_map_.end(); iter++) { if (iter->second != 0) delete iter->second; } } void ThreadTable::IndexUpdate(int32_t row_id) { int32_t partition_num = GlobalContext::GetBgPartitionNum(row_id); oplog_index_[partition_num].insert(row_id); } void ThreadTable::FlushOpLogIndex(TableOpLogIndex &table_oplog_index) { for (int32_t i = 0; i < GlobalContext::get_num_bg_threads(); ++i) { const std::unordered_set<int32_t> &partition_oplog_index = oplog_index_[i]; table_oplog_index.AddIndex(i, partition_oplog_index); oplog_index_[i].clear(); } } AbstractRow *ThreadTable::GetRow(int32_t row_id) { boost::unordered_map<int32_t, AbstractRow* >::iterator row_iter = row_storage_.find(row_id); if (row_iter == row_storage_.end()) { return 0; } return row_iter->second; } void ThreadTable::InsertRow(int32_t row_id, const AbstractRow *to_insert) { AbstractRow *row = to_insert->Clone(); boost::unordered_map<int32_t, AbstractRow* >::iterator row_iter = row_storage_.find(row_id); if (row_iter != row_storage_.end()) { delete row_iter->second; row_iter->second = row; } else { row_storage_[row_id] = row; } boost::unordered_map<int32_t, RowOpLog* >::iterator oplog_iter = oplog_map_.find(row_id); if (oplog_iter != oplog_map_.end()) { int32_t column_id; void *delta = oplog_iter->second->BeginIterate(&column_id); while (delta != 0) { row->ApplyInc(column_id, delta); delta = oplog_iter->second->Next(&column_id); } } } void ThreadTable::Inc(int32_t row_id, int32_t column_id, const void *delta) { boost::unordered_map<int32_t, RowOpLog* >::iterator oplog_iter = oplog_map_.find(row_id); RowOpLog *row_oplog; if (oplog_iter == oplog_map_.end()) { row_oplog = new RowOpLog(sample_row_->get_update_size(), std::bind(&AbstractRow::InitUpdate, sample_row_, std::placeholders::_1, std::placeholders::_2)); oplog_map_[row_id] = row_oplog; } else { row_oplog = oplog_iter->second; } void *oplog_delta = row_oplog->FindCreate(column_id); sample_row_->AddUpdates(column_id, oplog_delta, delta); boost::unordered_map<int32_t, AbstractRow* >::iterator row_iter = row_storage_.find(row_id); if (row_iter != row_storage_.end()) { row_iter->second->ApplyIncUnsafe(column_id, delta); } } void ThreadTable::BatchInc(int32_t row_id, const int32_t *column_ids, const void *deltas, int32_t num_updates) { boost::unordered_map<int32_t, RowOpLog* >::iterator oplog_iter = oplog_map_.find(row_id); RowOpLog *row_oplog; if (oplog_iter == oplog_map_.end()) { row_oplog = new RowOpLog(sample_row_->get_update_size(), std::bind(&AbstractRow::InitUpdate, sample_row_, std::placeholders::_1, std::placeholders::_2)); oplog_map_[row_id] = row_oplog; } else { row_oplog = oplog_iter->second; } const uint8_t* deltas_uint8 = reinterpret_cast<const uint8_t*>(deltas); for (int i = 0; i < num_updates; ++i) { void *oplog_delta = row_oplog->FindCreate(column_ids[i]); sample_row_->AddUpdates(column_ids[i], oplog_delta, deltas_uint8 + sample_row_->get_update_size()*i); } boost::unordered_map<int32_t, AbstractRow* >::iterator row_iter = row_storage_.find(row_id); if (row_iter != row_storage_.end()) { row_iter->second->ApplyBatchIncUnsafe(column_ids, deltas, num_updates); } } void ThreadTable::FlushCache(ProcessStorage &process_storage, TableOpLog &table_oplog, const AbstractRow *sample_row) { for (auto oplog_iter = oplog_map_.begin(); oplog_iter != oplog_map_.end(); oplog_iter++) { int32_t row_id = oplog_iter->first; int32_t partition_num = GlobalContext::GetBgPartitionNum(row_id); OpLogAccessor oplog_accessor; table_oplog.FindInsertOpLog(row_id, &oplog_accessor); RowAccessor row_accessor; bool found = process_storage.Find(row_id, &row_accessor); int32_t column_id; void *delta = oplog_iter->second->BeginIterate(&column_id); while (delta != 0) { void *oplog_delta = oplog_accessor.FindCreate(column_id); sample_row_->AddUpdates(column_id, oplog_delta, delta); oplog_index_[partition_num].insert(row_id); if (found) { row_accessor.GetRowData()->ApplyInc(column_id, delta); } delta = oplog_iter->second->Next(&column_id); } delete oplog_iter->second; } oplog_map_.clear(); for (auto iter = row_storage_.begin(); iter != row_storage_.end(); iter++) { if (iter->second != 0) delete iter->second; } row_storage_.clear(); } }
35.449495
78
0.684855
ForrestGan
70d8fc7ab1e54c13ca01b0a32eb2dbce02dc6d8d
2,260
cpp
C++
src/Components/DrawableEntity.cpp
charlieSewell/YOKAI
4fb39975e58e9a49bc984bc6e844721a7ad9462e
[ "MIT" ]
null
null
null
src/Components/DrawableEntity.cpp
charlieSewell/YOKAI
4fb39975e58e9a49bc984bc6e844721a7ad9462e
[ "MIT" ]
null
null
null
src/Components/DrawableEntity.cpp
charlieSewell/YOKAI
4fb39975e58e9a49bc984bc6e844721a7ad9462e
[ "MIT" ]
null
null
null
#include "DrawableEntity.hpp" #include "ImGuizmo.h" DrawableEntity::DrawableEntity(GameObject* parent) : Component(parent), m_offset(1.0f){} void DrawableEntity::Start() { if(m_parent->GetComponent<Transform>() == nullptr) { m_parent->AddComponent<Transform>(); } } void DrawableEntity::Update(float deltaTime) { if(m_animator != nullptr) { m_animator->BoneTransform(deltaTime); } } void DrawableEntity::Draw() { //m_parent->GetComponent<Transform>()->getMatrix() + m_offset; glm::mat4 temp = m_parent->GetComponent<Transform>()->GetMatrix() * m_offset; if(m_animator == nullptr) { Yokai::getInstance().GetModelManager()->DrawModel(m_modelID, temp); } else { //Yokai::getInstance().getModelManager()->DrawModel(m_modelID,m_parent->GetComponent<Transform>()->getMatrix(),m_animator->finalTransforms); Yokai::getInstance().GetModelManager()->DrawModel(m_modelID,temp,m_animator->finalTransforms); } } unsigned int DrawableEntity::LoadModel(std::string filename) { m_modelID = Yokai::getInstance().GetModelManager()->GetModelID(filename); Model* model = Yokai::getInstance().GetModelManager()->GetModel(m_modelID); if(model->IsAnimated()) { m_animator = new Animator(model); } else { delete m_animator; m_animator = nullptr; } return m_modelID; } void DrawableEntity::SetAnimation(std::string animation) { m_animator->SetAnimation(animation); } void DrawableEntity::RenderGUI() { float position[3]; float rotation[3]; float scale[3]; if(ImGui::TreeNode("Model")) { ImGuizmo::DecomposeMatrixToComponents(&m_offset[0][0],&position[0],&rotation[0],&scale[0]); ImGui::DragFloat3("Position: ",&position[0],0.01f); ImGui::DragFloat3("Rotation: ",&rotation[0],0.01f); ImGui::DragFloat3("Scale: ",&scale[0],0.01f); ImGui::TreePop(); ImGui::Separator(); ImGuizmo::RecomposeMatrixFromComponents(&position[0],&rotation[0],&scale[0],&m_offset[0][0]); } } void DrawableEntity::SetOffset(glm::mat4 offset) { m_offset = offset; } glm::mat4 DrawableEntity::GetOffset() { return m_offset; } void DrawableEntity::SetModelID(unsigned int modelID) { m_modelID = modelID; }
25.393258
148
0.679204
charlieSewell
70d930ee9828bfda90242514675ff30e149ff85c
1,400
cpp
C++
libs/api/libbpf_object.cpp
dbarac/ebpf-for-windows
5f5e2c0d1f031ceb41b11ba8d0e708a51cfba5d2
[ "MIT" ]
1
2021-07-27T21:46:52.000Z
2021-07-27T21:46:52.000Z
libs/api/libbpf_object.cpp
dbarac/ebpf-for-windows
5f5e2c0d1f031ceb41b11ba8d0e708a51cfba5d2
[ "MIT" ]
2
2021-07-28T16:48:31.000Z
2021-08-12T22:32:26.000Z
libs/api/libbpf_object.cpp
dbarac/ebpf-for-windows
5f5e2c0d1f031ceb41b11ba8d0e708a51cfba5d2
[ "MIT" ]
1
2021-07-27T21:41:59.000Z
2021-07-27T21:41:59.000Z
// Copyright (c) Microsoft Corporation // SPDX-License-Identifier: MIT #include "api_internal.h" #pragma warning(push) #pragma warning(disable : 4200) #include "libbpf.h" #pragma warning(pop) #include "libbpf_internal.h" // This file implements APIs in LibBPF's libbpf.h and is based on code in external/libbpf/src/libbpf.c // used under the BSD-2-Clause license, so the coding style tries to match the libbpf.c style to // minimize diffs until libbpf becomes cross-platform capable. This is a temporary workaround for // issue #351 until we can compile and use libbpf.c directly. const char* bpf_object__name(const struct bpf_object* object) { return object->file_name; } int bpf_object__pin(struct bpf_object* obj, const char* path) { int err; err = bpf_object__pin_maps(obj, path); if (err) return libbpf_err(err); err = bpf_object__pin_programs(obj, path); if (err) { bpf_object__unpin_maps(obj, path); return libbpf_err(err); } return 0; } void bpf_object__close(struct bpf_object* object) { ebpf_object_close(object); } struct bpf_program* bpf_object__find_program_by_name(const struct bpf_object* obj, const char* name) { struct bpf_program* prog; bpf_object__for_each_program(prog, obj) { if (!strcmp(prog->program_name, name)) return prog; } errno = ENOENT; return nullptr; }
23.728814
102
0.710714
dbarac
70d9d1eabc8a7f08cee0197efbe32ff9b2e03dae
13,369
cpp
C++
src/dataView.cpp
jcjramos/QuodDB
20da3727818c8c2f8f7da5cb1506d64cc6300f24
[ "Apache-2.0" ]
null
null
null
src/dataView.cpp
jcjramos/QuodDB
20da3727818c8c2f8f7da5cb1506d64cc6300f24
[ "Apache-2.0" ]
null
null
null
src/dataView.cpp
jcjramos/QuodDB
20da3727818c8c2f8f7da5cb1506d64cc6300f24
[ "Apache-2.0" ]
null
null
null
/*------------------------------------------------------------------------------ Generic Symbian Data View For DbMaster generated files JCR 3.2004 ------------------------------------------------------------------------------*/ #include "dataView.h" #include "DbMaster.h" #include <eikmenup.h> // CEikMenuPane #include <eikbtgpc.h> #include <aknviewappui.h> // CAknViewAppUi #include <avkon.rsg> #include <avkon.hrh> #include <akntitle.h> #include "dataView.hrh" #include "genAppRes.h" #ifndef __GEN_APP_RESOURCE_INCLUDE_FILE__ #error Please create a GenAppRes.H file including the AppName.RSH & RSH files #error Then include dataView.RSS in your application resource file! #endif //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ data_view_c* data_view_c::NewL( data_view_handler_c *handler ) { data_view_c* self = data_view_c::NewLC( handler ); CleanupStack::Pop(self); return self; } data_view_c* data_view_c::NewLC( data_view_handler_c *handler ) { data_view_c* self = new (ELeave) data_view_c( handler ); CleanupStack::PushL(self); self->ConstructL(); return self; } data_view_c::data_view_c( data_view_handler_c * _handler ):observer( this ) { handler = _handler; iNaviPane = 0; iTabGroup = 0; iDecoratedTabGroup = 0; edit_mode = true; full_options = false; list_top_item = 0; list_cur_item = 0; } data_view_c::~data_view_c() { } void data_view_c::ConstructL( int res_id ) { BaseConstructL( res_id ? res_id : R_DATA_VIEW_MASTER_VIEW ); CEikStatusPane* sp = AppUi()->StatusPane(); iNaviPane = (CAknNavigationControlContainer *)sp->ControlL(TUid::Uid(EEikStatusPaneUidNavi)); } TUid data_view_c::Id() const { return TUid::Uid( E_data_view_id ); } void data_view_c::DoActivateL(const TVwsViewId& , TUid , const TDesC8& ) { if( !dbmanip.live( edit_mode, (edit_mode == false || full_options == true) ? true : false ) ) return; iDecoratedTabGroup = iNaviPane->CreateTabGroupL(); iTabGroup = (CAknTabGroup*) iDecoratedTabGroup->DecoratedControl(); iTabGroup->SetTabFixedWidthL(KTabWidthWithTwoTabs); for( int n = 0; n < dbmanip.n_visible_columns(); n++ ) { dbm_field_c *ff = dbmanip.get_visible_column( n ); iTabGroup->AddTabL( ff->id(), ff->name() ); } iTabGroup->SetActiveTabByIndex(0); iNaviPane->PushL( *iDecoratedTabGroup ); if (!iContainer) { iContainer = new (ELeave) list_box_container_c( &observer ); iContainer->SetMopParent(this); // ATT: Mudar a ordem deste gajo faz desaparecer as setas !!! iContainer->ConstructL( ClientRect() ); AppUi()->AddToStackL(*this, iContainer); } RebuildList(); int res_id = edit_mode ? R_DATA_VIEW_STR_DATA_EDITION : R_DATA_VIEW_STR_DATA_REPORT; ChangeTitleText( res_id, dbmanip.get_file()->name() ); } void data_view_c::DoDeactivate() { iNaviPane->Pop( iDecoratedTabGroup ); delete iDecoratedTabGroup; iDecoratedTabGroup = 0; iTabGroup = 0; if (iContainer) { AppUi()->RemoveFromStack(iContainer); delete iContainer; iContainer = NULL; } dbmanip.die(); } void data_view_c::RebuildHeader() { iNaviPane->Pop( iDecoratedTabGroup ); for( int t = 0; t < iTabGroup->TabCount(); ) { int id = iTabGroup->TabIdFromIndex( t ); iTabGroup->DeleteTabL( id ); } for( int n = 0; n < dbmanip.n_visible_columns(); n++ ) { dbm_field_c *ff = dbmanip.get_visible_column( n ); iTabGroup->AddTabL( ff->id(), ff->name() ); } iNaviPane->PushL( *iDecoratedTabGroup ); iTabGroup->SetActiveTabByIndex(0); } void data_view_c::RebuildList( bool redraw ) { TInt active = iTabGroup ? iTabGroup->ActiveTabIndex() : 0; CDesCArrayFlat *tArray = dbmanip.reload_as_array( active ); if( tArray ) { iContainer->Rebuild( dbmanip.get_use_heading() ? LBCT_HEADER : LBCT_NO_HEADER, tArray, ELbmOwnsItemArray , redraw ); } } void data_view_c::HandleCommandL(TInt aCommand) { bool done = false; if( handler ) done = handler->HandleCommandL( this,aCommand ); if( done ) return; switch( aCommand ) { case EDataViewMenuNew: { bool first = true; if( iContainer->GetNumListItems() ) { SaveListPosition(); first = false; } dbmanip.add_line(); RebuildList(); if( !first ) { ResumeListPosition(); } } break; case EDataViewMenuEdit: { SaveListPosition(); if(!edit_mode) // Non editable form doesn't clear the header ... iNaviPane->Pop( iDecoratedTabGroup ); dbmanip.edit_line( iContainer ? iContainer->GetCurrentItemIdx() : -1 ); if(!edit_mode) iNaviPane->PushL( *iDecoratedTabGroup ); RebuildList(); ResumeListPosition(); } break; case EDataViewMenuDelete: { dbmanip.delete_line( iContainer ? iContainer->GetCurrentItemIdx() : -1 ); RebuildList(); } break; case EDataViewMenuHeader: { if( dbmanip.select_header() ) RebuildList(); } break; case EDataViewMenuSort: { if( dbmanip.select_sort() ) RebuildList(); } break; case EDataViewMenuPages: { if( dbmanip.select_pages() ) { RebuildHeader(); RebuildList(); } } break; case EDataViewMenuFiltersAdd: { if( dbmanip.select_filters_add() ) RebuildList(); } break; case EDataViewMenuFiltersRemove: { if( dbmanip.select_filters_remove() ) RebuildList(); } break; case EDataViewMenuExternalImport: { dbmanip.get_import_export().do_import_csv(); RebuildList(); } break; case EDataViewMenuExternalExport: { dbmanip.get_import_export().do_export_csv(); } break; case EDataViewMenuExternalSeparator: { dbmanip.get_import_export().select_separator(); } break; case EDataViewMenuExternalUndoImport: { dbmanip.get_import_export().undo_import(); RebuildList(); } break; case EDataViewMenuELookup: { int ret = dbmanip.select_lookup(); if( ret >= 0 ) { list_top_item = ret; list_cur_item = ret; ResumeListPosition(); if( iContainer ) iContainer->DrawNow(); } else { HBufC *strTextError = CEikonEnv::Static()->AllocReadResourceL( R_DATA_VIEW_STR_NOT_FOUND ); CEikonEnv::Static()->InfoWinL( *strTextError , _L("") ); delete strTextError; } } break; default: AppUi()->HandleCommandL(aCommand); break; } } void data_view_c::DynInitMenuPaneL(TInt aResourceId, CEikMenuPane* aMenuPane) { if (aResourceId == R_DATA_VIEW_MAIN_MENU_EXTERNAL ) { if( !dbmanip.get_import_export().possible_undo() ) { aMenuPane->SetItemDimmed( EDataViewMenuExternalUndoImport,ETrue); } } if (aResourceId == R_DATA_VIEW_MAIN_MENU_FILTERS ) { if( !dbmanip.n_filters() ) { aMenuPane->SetItemDimmed( EDataViewMenuFiltersRemove,ETrue); } } if (aResourceId == R_DATA_VIEW_MAIN_MENU ) { // No Select ! if( !dbmanip.get_number_of_keys() ) { aMenuPane->SetItemDimmed( EDataViewMenuSort,ETrue); } if( !edit_mode ) { aMenuPane->SetItemDimmed( EDataViewMenuDelete,ETrue); aMenuPane->SetItemDimmed( EDataViewMenuNew,ETrue); aMenuPane->SetItemDimmed( EDataViewMenuExternal,ETrue); } else { if( !full_options ) aMenuPane->SetItemDimmed( EDataViewMenuFilters,ETrue); } if( iContainer && !iContainer->GetNumListItems() ) { aMenuPane->SetItemDimmed( EDataViewMenuDelete,ETrue); aMenuPane->SetItemDimmed( EDataViewMenuEdit,ETrue); aMenuPane->SetItemDimmed( EDataViewMenuELookup,ETrue); } } } void data_view_c::ChangeTitleText( int resource_id , TPtrC extra ) { CAknTitlePane* titlePane = STATIC_CAST( CAknTitlePane*, StatusPane()->ControlL( TUid::Uid( EEikStatusPaneUidTitle ) ) ); if ( !resource_id ) { titlePane->SetTextToDefaultL(); } else { TBuf<1024> titleText( NULL ); iEikonEnv->ReadResource( titleText, resource_id ); if( extra.Length() ) { titleText.Append( extra ); } titlePane->SetTextL( titleText ); } } void data_view_c::set_edit_mode( bool on_or_off ) { edit_mode = on_or_off; } void data_view_c::set_full_options( bool on_or_off ) { full_options = on_or_off; } void data_view_c::SaveListPosition() { list_top_item = iContainer->GetTopItemIdx(); list_cur_item = iContainer->GetCurrentItemIdx(); } void data_view_c::ResumeListPosition() { if(!iContainer ) return; if( list_top_item >= iContainer->GetNumListItems() || list_cur_item >= iContainer->GetNumListItems() ) //HERE return; iContainer->SetTopItemIdx( list_top_item ); iContainer->SetCurrentItemIdx( list_cur_item ); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ data_view_list_box_container_enhanced_observer_c::data_view_list_box_container_enhanced_observer_c( data_view_c *_daddy ) { daddy = _daddy; } void data_view_list_box_container_enhanced_observer_c::HandleListBoxEventL( CEikListBox* aListBox, MEikListBoxObserver::TListBoxEvent aListBoxEvent ) { }; TKeyResponse data_view_list_box_container_enhanced_observer_c::OfferKeyEventL(const TKeyEvent& aKeyEvent, TEventCode aType) { if (aType == EEventKey) { if (daddy->iTabGroup == NULL || daddy->iContainer->GetNumListItems() == 0 ) { return EKeyWasNotConsumed; } TInt active = daddy->iTabGroup->ActiveTabIndex(); TInt count = daddy->iTabGroup->TabCount(); switch (aKeyEvent.iCode) { case EKeyDevice3: // OK { daddy->HandleCommandL(EDataViewMenuEdit); return EKeyWasConsumed; } case EKeyLeftArrow: if (active > 0) { daddy->SaveListPosition(); active--; daddy->iTabGroup->SetActiveTabByIndex(active); daddy->RebuildList(false); daddy->ResumeListPosition(); if(daddy->iContainer ) daddy->iContainer->Redraw(); return EKeyWasConsumed; } break; case EKeyRightArrow: if((active + 1) < count) { daddy->SaveListPosition(); active++; daddy->iTabGroup->SetActiveTabByIndex(active); daddy->RebuildList( false ); daddy->ResumeListPosition(); if(daddy->iContainer ) daddy->iContainer->Redraw(); return EKeyWasConsumed; } break; default: break; } } return EKeyWasNotConsumed; } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // End of File
25.759152
149
0.507517
jcjramos
70dd84c6cf607c378b54ab56e74d5d1f16b0db1d
1,096
cpp
C++
Source/Packet.cpp
zcharli/snow-olsr
3617044d3ad1a0541b346669bce76702f71f4d0c
[ "MIT" ]
3
2018-08-08T22:31:52.000Z
2019-12-17T14:02:59.000Z
Source/Packet.cpp
zcharli/snow-olsr
3617044d3ad1a0541b346669bce76702f71f4d0c
[ "MIT" ]
null
null
null
Source/Packet.cpp
zcharli/snow-olsr
3617044d3ad1a0541b346669bce76702f71f4d0c
[ "MIT" ]
null
null
null
// // Created by czl on 03/04/16. // #include "Headers/Packet.h" Packet::Packet(char* src, char* dst, char* messageBuffer, int header_offset = 0) : mSource(src), mDestination(dst), mBuffer(messageBuffer), offset(header_offset) { mAddress = NULL; #if verbose PRINTLN(Initialized a packet.) #endif } Packet::Packet() { } Packet::~Packet() { //PRINTLN(Destroying a packet does not destroy buffer.); // if(mAddress != NULL) // delete mAddress; // delete mBuffer; } MACAddress& Packet::getSource(){ return mSource; } MACAddress& Packet::getDestination() { return mDestination; } char* Packet::getBuffer() { return mBuffer; } char* Packet::getMyAddress() { return mAddress; } int Packet::getOffset() { return offset; } void Packet::setSource(MACAddress data){ mSource = data; } void Packet::setDestination(MACAddress data){ mDestination = data; } void Packet::setBuffer(char* data){ mBuffer = data; } void Packet::setMyAddress(char* data) { mAddress = data; } void Packet::setOffset(int offset) { offset = offset; }
19.571429
86
0.663321
zcharli
70dd87e1a1f9d7fad32b8f181414d67f46db1826
666
cpp
C++
Cpp/fost-crypto/crypto.cpp
KayEss/fost-base
05ac1b6a1fb672c61ba6502efea86f9c5207e28f
[ "BSL-1.0" ]
2
2016-05-25T22:17:38.000Z
2019-04-02T08:34:17.000Z
Cpp/fost-crypto/crypto.cpp
KayEss/fost-base
05ac1b6a1fb672c61ba6502efea86f9c5207e28f
[ "BSL-1.0" ]
5
2018-07-13T10:43:05.000Z
2019-09-02T14:54:42.000Z
Cpp/fost-crypto/crypto.cpp
KayEss/fost-base
05ac1b6a1fb672c61ba6502efea86f9c5207e28f
[ "BSL-1.0" ]
1
2020-10-22T20:44:24.000Z
2020-10-22T20:44:24.000Z
/** Copyright 2015-2019 Red Anchor Trading Co. Ltd. Distributed under the Boost Software License, Version 1.0. See <http://www.boost.org/LICENSE_1_0.txt> */ #include "fost-crypto.hpp" #include <fost/crypto.hpp> const fostlib::module fostlib::c_fost_crypto(c_fost, "crypto"); bool fostlib::crypto_compare( fostlib::array_view<const unsigned char> left, fostlib::array_view<const unsigned char> right) { if (left.size() != right.size()) { return false; } unsigned char iored{0}; for (std::size_t index{0}; index != left.size(); ++index) { iored |= (left[index] xor right[index]); } return iored == 0u; }
25.615385
63
0.651652
KayEss
70e4eea0f08e109a000ecfdcaf66aeee95e0b63c
1,747
cpp
C++
src/SumRootToLeafNumbers.cpp
harborn/LeetCode
8488c0bcf306b8672492fd6220e496e335e2b9fe
[ "MIT" ]
null
null
null
src/SumRootToLeafNumbers.cpp
harborn/LeetCode
8488c0bcf306b8672492fd6220e496e335e2b9fe
[ "MIT" ]
1
2021-12-14T15:56:11.000Z
2021-12-14T15:56:11.000Z
src/SumRootToLeafNumbers.cpp
harborn/LeetCode
8488c0bcf306b8672492fd6220e496e335e2b9fe
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <vector> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; vector<string> helper(TreeNode *root) { vector<string> res; if (root == NULL) return res; vector<string> l = helper(root->left); vector<string> r = helper(root->right); if (l.empty() && r.empty()) res.push_back(std::to_string(root->val)); for (int i = 0; i < l.size(); i++) { string s = std::to_string(root->val); res.push_back(s.append(l[i])); } for (int i = 0; i < r.size(); i++) { string s = std::to_string(root->val); res.push_back(s.append(r[i])); } return res; } int stringAdd(string s1, string s2) { int res = 0; int size1 = s1.size(); int size2 = s2.size(); int carry = 0; int i = 0, j = 0; while (i < size1 && j < size2) { int n = s1[i] - '0' + s2[j] - '0' + carry; res = res * 10 + n % 10; carry = n / 10; i++; j++; } while (i < size1) { int n = s1[i] - '0' + carry; res = res * 10 + n % 10; carry = n / 10; i++; } while (j < size2) { int n = s2[i] - '0' + carry; res = res * 10 + n % 10; carry = n / 10; j++; } return res; } int sumNumbers(TreeNode *root) { vector<string> res = helper(root); int sum = 0; for (int i = 0; i < res.size(); i++) { sum += stoi(res[i]); } return sum; } int main(void) { int n = atoi("32"); //int n = stringAdd("12", "3"); TreeNode *tree; TreeNode n1(1), n2(2), n3(3), n4(4), n5(5), n6(6), n7(7), n8(8), n12(12); n1.left = &n2; n1.right = &n3; n2.left = &n4; n3.left = &n6; n6.left = &n12; n3.right = &n7; n4.left = &n8; tree = &n1; vector<string> res = helper(tree); int sum = sumNumbers(tree); return 0; }
16.798077
74
0.550086
harborn
70e85da2070f8aa2ffbab5515a01ddd3ad325324
4,333
hpp
C++
srcs/common/trackfragmentheaderbox.hpp
Reflectioner/heif
bdac2fc9c66d8c1e8994eaf81f1a5db116b863ab
[ "BSD-3-Clause" ]
null
null
null
srcs/common/trackfragmentheaderbox.hpp
Reflectioner/heif
bdac2fc9c66d8c1e8994eaf81f1a5db116b863ab
[ "BSD-3-Clause" ]
null
null
null
srcs/common/trackfragmentheaderbox.hpp
Reflectioner/heif
bdac2fc9c66d8c1e8994eaf81f1a5db116b863ab
[ "BSD-3-Clause" ]
null
null
null
/* This file is part of Nokia HEIF library * * Copyright (c) 2015-2020 Nokia Corporation and/or its subsidiary(-ies). All rights reserved. * * Contact: heif@nokia.com * * This software, including documentation, is protected by copyright controlled by Nokia Corporation and/ or its * subsidiaries. All rights are reserved. * * Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior * written consent of Nokia. */ #ifndef TRACKFRAGMENTHEADERBOX_HPP #define TRACKFRAGMENTHEADERBOX_HPP #include "bitstream.hpp" #include "customallocator.hpp" #include "fullbox.hpp" #include "moviefragmentsdatatypes.hpp" /** * @brief Track Fragment Header Box class * @details 'tfhd' box implementation as specified in the ISOBMFF specification. */ class TrackFragmentHeaderBox : public FullBox { public: TrackFragmentHeaderBox(std::uint32_t tr_flags = 0); ~TrackFragmentHeaderBox() override = default; enum TrackFragmentHeaderFlags { BaseDataOffsetPresent = 0x000001, SampleDescriptionIndexPresent = 0x000002, DefaultSampleDurationPresent = 0x000008, DefaultSampleSizePresent = 0x000010, DefaultSampleFlagsPresent = 0x000020, DurationIsEmpty = 0x010000, DefaultBaseIsMoof = 0x020000 }; /** @brief Set Track ID of the TrackFragmentHeaderBox. * @param [in] uint32_t trackId */ void setTrackId(const uint32_t trackId); /** @brief Get Track ID of the TrackFragmentHeaderBox. * @return uint32_t as specified in 8.8.7.1 of ISO/IEC 14496-12:2015(E) */ uint32_t getTrackId() const; /** @brief Set Base Data Offset of the TrackFragmentHeaderBox. * @param [in] uint64_t baseDataOffset */ void setBaseDataOffset(const uint64_t baseDataOffset); /** @brief Get Base Data Offset of the TrackFragmentHeaderBox. * @return uint64_t as specified in 8.8.7.1 of ISO/IEC 14496-12:2015(E) */ uint64_t getBaseDataOffset() const; /** @brief Set Sample Description Index of the TrackFragmentHeaderBox. * @param [in] uint32_t sampleDescriptionIndex */ void setSampleDescriptionIndex(const uint32_t sampleDescriptionIndex); /** @brief Get Sample Description Index of the TrackFragmentHeaderBox. * @return uint32_t as specified in 8.8.7.1 of ISO/IEC 14496-12:2015(E) */ uint32_t getSampleDescriptionIndex() const; /** @brief Set Default Sample Duration of the TrackFragmentHeaderBox. * @param [in] uint32_t defaultSampleDuration **/ void setDefaultSampleDuration(const uint32_t defaultSampleDuration); /** @brief Get Default Sample Duration of the TrackFragmentHeaderBox. * @return uint32_t as specified in 8.8.7.1 of ISO/IEC 14496-12:2015(E) */ uint32_t getDefaultSampleDuration() const; /** @brief Set Default Sample Size of the TrackFragmentHeaderBox. * @param [in] uint32_t defaultSampleSize**/ void setDefaultSampleSize(const uint32_t defaultSampleSize); /** @brief Get Default Sample Size of the TrackFragmentHeaderBox. * @return uint32_t as specified in 8.8.7.1 of ISO/IEC 14496-12:2015(E) */ uint32_t getDefaultSampleSize() const; /** @brief Set of the TrackFragmentHeaderBox. * @param [in] MOVIEFRAGMENTS::SampleFlags (uint32_t) defaultSampleFlags */ void setDefaultSampleFlags(const MOVIEFRAGMENTS::SampleFlags defaultSampleFlags); /** @brief Get of the TrackFragmentHeaderBox. * @return MOVIEFRAGMENTS::SampleFlags (uint32_t) as specified in 8.8.3.1 of ISO/IEC 14496-12:2015(E) */ MOVIEFRAGMENTS::SampleFlags getDefaultSampleFlags() const; /** * @brief Serialize box data to the ISOBMFF::BitStream. * @see Box::writeBox() */ void writeBox(ISOBMFF::BitStream& bitstr) const override; /** * @brief Deserialize box data from the ISOBMFF::BitStream. * @see Box::parseBox() */ void parseBox(ISOBMFF::BitStream& bitstr) override; private: uint32_t mTrackId; // Optional fields: uint64_t mBaseDataOffset; uint32_t mSampleDescriptionIndex; uint32_t mDefaultSampleDuration; uint32_t mDefaultSampleSize; MOVIEFRAGMENTS::SampleFlags mDefaultSampleFlags; }; #endif /* end of include guard: TRACKFRAGMENTHEADERBOX_HPP */
37.678261
115
0.71567
Reflectioner
70e8f549e8e946eb4154cd5e6f923bca602682ee
1,605
cpp
C++
solutions/715.range-module.246936325.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
78
2020-10-22T11:31:53.000Z
2022-02-22T13:27:49.000Z
solutions/715.range-module.246936325.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
null
null
null
solutions/715.range-module.246936325.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
26
2020-10-23T15:10:44.000Z
2021-11-07T16:13:50.000Z
map<int, int>::iterator lower_bound2(map<int, int> &mp, int key) { if (mp.empty()) return mp.end(); auto it = mp.lower_bound(key); if (it->first == key) return it; if (it == mp.begin()) return mp.end(); it--; return it; } class RangeModule { map<int, int> mp; public: RangeModule() {} void addRange(int left, int right) { removeRange(left, right); auto it = lower_bound2(mp, left); right--; if (it != mp.end() && it->second == left - 1) left = it->first; if (mp.count(right + 1)) { int t = right + 1; right = mp.find(t)->second; mp.erase(t); } mp[left] = right; } bool queryRange(int left, int right) { right--; auto it = lower_bound2(mp, left); return it != mp.end() && it->second >= right; } void removeRange(int left, int right) { right--; if (mp.empty()) return; auto it = mp.lower_bound(left); if (it != mp.begin()) { it--; if (it->first < left) { if (it->second >= left) { if (it->second > right) mp[right + 1] = it->second; it->second = left - 1; } } it++; } while (it != mp.end() && it->first <= right) { auto temp = it; it++; if (temp->second > right) mp[right + 1] = temp->second; mp.erase(temp); } } }; /** * Your RangeModule object will be instantiated and called as such: * RangeModule* obj = new RangeModule(); * obj->addRange(left,right); * bool param_2 = obj->queryRange(left,right); * obj->removeRange(left,right); */
18.238636
67
0.522118
satu0king
70e8f90c6c3e07e93868054efb8cc9d6c8157ec3
2,546
cpp
C++
Userland/Libraries/LibWeb/Page/Page.cpp
xspager/serenity
39b7fbfeb9e469b4089f5424dc61aa074023bb5a
[ "BSD-2-Clause" ]
1
2022-03-29T16:59:10.000Z
2022-03-29T16:59:10.000Z
Userland/Libraries/LibWeb/Page/Page.cpp
xspager/serenity
39b7fbfeb9e469b4089f5424dc61aa074023bb5a
[ "BSD-2-Clause" ]
null
null
null
Userland/Libraries/LibWeb/Page/Page.cpp
xspager/serenity
39b7fbfeb9e469b4089f5424dc61aa074023bb5a
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2020, Andreas Kling <kling@serenityos.org> * * SPDX-License-Identifier: BSD-2-Clause */ #include <LibWeb/HTML/BrowsingContext.h> #include <LibWeb/Page/Page.h> namespace Web { Page::Page(PageClient& client) : m_client(client) { m_top_level_browsing_context = HTML::BrowsingContext::create(*this); } Page::~Page() = default; HTML::BrowsingContext& Page::focused_context() { if (m_focused_context) return *m_focused_context; return top_level_browsing_context(); } void Page::set_focused_browsing_context(Badge<EventHandler>, HTML::BrowsingContext& browsing_context) { m_focused_context = browsing_context.make_weak_ptr(); } void Page::load(const AK::URL& url) { top_level_browsing_context().loader().load(url, FrameLoader::Type::Navigation); } void Page::load(LoadRequest& request) { top_level_browsing_context().loader().load(request, FrameLoader::Type::Navigation); } void Page::load_html(StringView html, const AK::URL& url) { top_level_browsing_context().loader().load_html(html, url); } Gfx::Palette Page::palette() const { return m_client.palette(); } Gfx::IntRect Page::screen_rect() const { return m_client.screen_rect(); } CSS::PreferredColorScheme Page::preferred_color_scheme() const { return m_client.preferred_color_scheme(); } bool Page::handle_mousewheel(const Gfx::IntPoint& position, unsigned button, unsigned modifiers, int wheel_delta_x, int wheel_delta_y) { return top_level_browsing_context().event_handler().handle_mousewheel(position, button, modifiers, wheel_delta_x, wheel_delta_y); } bool Page::handle_mouseup(const Gfx::IntPoint& position, unsigned button, unsigned modifiers) { return top_level_browsing_context().event_handler().handle_mouseup(position, button, modifiers); } bool Page::handle_mousedown(const Gfx::IntPoint& position, unsigned button, unsigned modifiers) { return top_level_browsing_context().event_handler().handle_mousedown(position, button, modifiers); } bool Page::handle_mousemove(const Gfx::IntPoint& position, unsigned buttons, unsigned modifiers) { return top_level_browsing_context().event_handler().handle_mousemove(position, buttons, modifiers); } bool Page::handle_keydown(KeyCode key, unsigned modifiers, u32 code_point) { return focused_context().event_handler().handle_keydown(key, modifiers, code_point); } bool Page::handle_keyup(KeyCode key, unsigned modifiers, u32 code_point) { return focused_context().event_handler().handle_keyup(key, modifiers, code_point); } }
27.376344
134
0.761587
xspager
70f6733926fca4a255c4feab16fb5726d5bb021f
928
cpp
C++
Engine/src/Platform/GraphicsAPI/OpenGL/glRenderCommand.cpp
Light3039/Light
cc4fc0293164ca48efdc833d0054d3ff8e60b65d
[ "Apache-2.0" ]
23
2021-05-23T10:13:55.000Z
2022-03-24T14:49:30.000Z
Engine/src/Platform/GraphicsAPI/OpenGL/glRenderCommand.cpp
Light3039/Light
cc4fc0293164ca48efdc833d0054d3ff8e60b65d
[ "Apache-2.0" ]
1
2021-09-07T12:26:33.000Z
2021-09-27T19:06:00.000Z
Engine/src/Platform/GraphicsAPI/OpenGL/glRenderCommand.cpp
Light3039/Light
cc4fc0293164ca48efdc833d0054d3ff8e60b65d
[ "Apache-2.0" ]
3
2021-05-30T17:31:47.000Z
2021-09-20T06:42:39.000Z
#include "glRenderCommand.h" #include <glad/glad.h> #include <GLFW/glfw3.h> namespace Light { glRenderCommand::glRenderCommand(GLFWwindow* windowHandle) : m_WindowHandle(windowHandle) { } void glRenderCommand::SwapBuffers() { glfwSwapBuffers(m_WindowHandle); } void glRenderCommand::ClearBackBuffer(const glm::vec4& clearColor) { glClearColor(clearColor.r, clearColor.g, clearColor.b, clearColor.a); glClear(GL_COLOR_BUFFER_BIT); } void glRenderCommand::Draw(unsigned int count) { glDrawArrays(GL_TRIANGLES, 0, count); } void glRenderCommand::DrawIndexed(unsigned int count) { glDrawElements(GL_TRIANGLES, count, GL_UNSIGNED_INT, nullptr); } void glRenderCommand::DefaultTargetFramebuffer() { glBindFramebuffer(GL_FRAMEBUFFER, NULL); } void glRenderCommand::SetViewport(unsigned int x, unsigned int y, unsigned int width, unsigned int height) { glViewport(x, y, width, height); } }
21.090909
107
0.755388
Light3039
70f6a6b33da51d752d26a912229ecf68ce6f6c75
4,181
hpp
C++
include/fl/model/transition/interface/transition_function.hpp
aeolusbot-tommyliu/fl
a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02
[ "MIT" ]
17
2015-07-03T06:53:05.000Z
2021-05-15T20:55:12.000Z
include/fl/model/transition/interface/transition_function.hpp
aeolusbot-tommyliu/fl
a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02
[ "MIT" ]
3
2015-02-20T12:48:17.000Z
2019-12-18T08:45:13.000Z
include/fl/model/transition/interface/transition_function.hpp
aeolusbot-tommyliu/fl
a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02
[ "MIT" ]
15
2015-02-20T11:34:14.000Z
2021-05-15T20:55:13.000Z
/* * This is part of the fl library, a C++ Bayesian filtering library * (https://github.com/filtering-library) * * Copyright (c) 2015 Max Planck Society, * Autonomous Motion Department, * Institute for Intelligent Systems * * This Source Code Form is subject to the terms of the MIT License (MIT). * A copy of the license can be found in the LICENSE file distributed with this * source code. */ /** * \file transition_function.hpp * \date October 2014 * \author Jan Issac (jan.issac@gmail.com) */ #pragma once #include <fl/util/traits.hpp> namespace fl { template < typename State_, typename Noise_, typename Input_, int Id = 0 > class TransitionFunction : internal::NonAdditiveNoiseModelType { public: typedef internal::NonAdditiveNoiseModelType Type; typedef State_ State; typedef Noise_ Noise; typedef Input_ Input; public: /** * \brief Overridable default destructor */ virtual ~TransitionFunction() noexcept { } /// \todo: we should have a second function state which does not require /// a control input. this function would represent the uncontrolled /// dynamics. in most cases this would just call the function below /// with a zero input for the controls. virtual State state(const State& prev_state, const Noise& noise, const Input& input) const = 0; /** * \return Dimension of the state variable $\f$x\f$ */ virtual int state_dimension() const = 0; /** * \return Dimension of the noise term \f$w\f$ */ virtual int noise_dimension() const = 0; /** * \return Dimension of the input \f$u_t\f$ */ virtual int input_dimension() const = 0; /** * \return Model id number * * In case of multiple sensors of the same kind, this function returns the * id of the individual model. */ virtual int id() const { return Id; } /** * Sets the model id * * \param new_id Model's new ID */ virtual void id(int) { /* const ID */ } }; /// \todo: this needs to disappear template < typename State, typename Noise, typename Input > class TransitionInterface : public internal::TransitionType { public: typedef internal::TransitionType ModelType; public: /** * Sets the conditional arguments \f$x_t, u_t\f$ of \f$p(x\mid x_t, u_t)\f$ * * \param delta_time Prediction duration \f$\Delta t\f$ * \param state Previous state \f$x_{t}\f$ * \param input Control input \f$u_t\f$ * * Once the conditional have been set, may either sample from this model * since it also represents a conditional distribution or you may map * a SNV noise term \f$v_t\f$ onto the distribution using * \c map_standard_variate(\f$v_t\f$) if implemented. */ virtual void condition(const double& delta_time, const State& state, const Input& input = Input()) { } /** * Predicts the state conditioned on the previous state and input. * * \param delta_time Prediction duration \f$\Delta t\f$ * \param state Previous state \f$x_{t}\f$ * \param noise Additive or non-Additive noise \f$v_t\f$ * \param input Control input \f$u_t\f$ * * \return State \f$x_{t+1}\sim p(x\mid x_t, u_t)\f$ */ /// \todo have a default argument for the input, a default function which /// has to be implemented by the derived classes virtual State predict_state(double delta_time, const State& state, const Noise& noise, const Input& input) = 0; /** * \return \f$\dim(x_t)\f$, dimension of the state */ virtual int state_dimension() const = 0; /** * \return \f$\dim(v_t)\f$, dimension of the noise */ virtual int noise_dimension() const = 0; /** * \return \f$\dim(u_t)\f$, dimension of the control input */ virtual int input_dimension() const = 0; }; }
24.886905
79
0.602727
aeolusbot-tommyliu
70fb15234dadd1ac4f3cc6767647fb3298d2dca7
2,838
cpp
C++
src/lang/scope.cpp
dmcdougall/occa
4cc784e86459c01c8821da0a02eea3ad4fb36ef5
[ "MIT" ]
null
null
null
src/lang/scope.cpp
dmcdougall/occa
4cc784e86459c01c8821da0a02eea3ad4fb36ef5
[ "MIT" ]
null
null
null
src/lang/scope.cpp
dmcdougall/occa
4cc784e86459c01c8821da0a02eea3ad4fb36ef5
[ "MIT" ]
null
null
null
#include <occa/lang/scope.hpp> #include <occa/lang/variable.hpp> #include <occa/lang/type.hpp> namespace occa { namespace lang { scope_t::scope_t() {} scope_t::~scope_t() { clear(); } void scope_t::clear() { freeKeywords(keywords, true); } scope_t scope_t::clone() const { scope_t other; keywordMap::const_iterator it = keywords.begin(); while (it != keywords.end()) { other.keywords[it->first] = it->second->clone(); ++it; } return other; } void scope_t::swap(scope_t &other) { keywords.swap(other.keywords); } int scope_t::size() { return (int) keywords.size(); } bool scope_t::has(const std::string &name) { return (keywords.find(name) != keywords.end()); } keyword_t& scope_t::get(const std::string &name) { static keyword_t noKeyword; keywordMapIterator it = keywords.find(name); if (it != keywords.end()) { return *it->second; } return noKeyword; } bool scope_t::add(keyword_t &keyword, const bool force) { const int kType = keyword.type(); if (kType & keywordType::variable) { return add(((const variableKeyword&) keyword).variable, force); } else if (kType & keywordType::function) { return add(((const functionKeyword&) keyword).function, force); } else if (kType & keywordType::type) { return add(((const typeKeyword&) keyword).type_, force); } return false; } bool scope_t::add(type_t &type, const bool force) { return genericAdd<typeKeyword>(type, force); } bool scope_t::add(function_t &func, const bool force) { return genericAdd<functionKeyword>(func, force); } bool scope_t::add(variable_t &var, const bool force) { return genericAdd<variableKeyword>(var, force); } void scope_t::remove(const std::string &name, const bool deleteSource) { keywordMapIterator it = keywords.find(name); if (it != keywords.end()) { keyword_t &keyword = *(it->second); if (deleteSource) { keyword.deleteSource(); } delete &keyword; keywords.erase(it); } } void scope_t::moveTo(scope_t &scope) { scope.keywords.insert(keywords.begin(), keywords.end()); keywords.clear(); } void scope_t::debugPrint() const { keywordMap::const_iterator it = keywords.begin(); while (it != keywords.end()) { io::stdout << '[' << stringifySetBits(it->second->type()) << "] " << it->first << '\n'; ++it; } } } }
25.567568
71
0.544397
dmcdougall
70ff2d1921c87b4c2c60a17372d7cbb52c94f4cb
3,877
cpp
C++
MinimalDrawAMP.cpp
newpolaris/MinimalDrawAMP
41d8d8361c9d64ebbf8b1a19e05d4f30000d1c85
[ "Unlicense" ]
null
null
null
MinimalDrawAMP.cpp
newpolaris/MinimalDrawAMP
41d8d8361c9d64ebbf8b1a19e05d4f30000d1c85
[ "Unlicense" ]
null
null
null
MinimalDrawAMP.cpp
newpolaris/MinimalDrawAMP
41d8d8361c9d64ebbf8b1a19e05d4f30000d1c85
[ "Unlicense" ]
null
null
null
#include <amp.h> #include <amp_graphics.h> #include <d3dcommon.h> #include <d3d11.h> #include <atlcomcli.h> #include "DirectXTK/WICTextureLoader.h" #pragma comment(lib, "dxguid.lib") #pragma comment(lib, "d3d11.lib") #pragma comment(lib, "dxgi.lib") int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPTSTR lpCmdLine, _In_ int nCmdShow) { WNDCLASSEX wcex = { sizeof(wcex) }; wcex.lpfnWndProc = DefWindowProc; wcex.hInstance = hInstance; wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.lpszClassName = _T(__FUNCTION__); HWND hWnd = CreateWindow( MAKEINTATOM(RegisterClassEx(&wcex)), wcex.lpszClassName, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); if (!hWnd) return 1; ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); CComPtr<ID3D11Device> dev; CComPtr<ID3D11DeviceContext> ctx; CComPtr<IDXGISwapChain> swapchain; DXGI_SWAP_CHAIN_DESC desc = {}; desc.BufferCount = 1; desc.SampleDesc.Count = 1; desc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; desc.OutputWindow = hWnd; desc.Windowed = TRUE; desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT | DXGI_USAGE_UNORDERED_ACCESS | DXGI_USAGE_SHADER_INPUT;; D3D_FEATURE_LEVEL FeatureLevel = D3D_FEATURE_LEVEL_11_0; D3D11CreateDeviceAndSwapChain( 0, D3D_DRIVER_TYPE_HARDWARE, 0, D3D11_CREATE_DEVICE_DEBUG, &FeatureLevel, 1, D3D11_SDK_VERSION, &desc, &swapchain, &dev, 0, &ctx); if (!swapchain) return 1; using namespace concurrency::direct3d; using namespace concurrency::graphics; using namespace concurrency::graphics::direct3d; auto av = create_accelerator_view(dev); CComPtr<ID3D11Texture2D> image; CComPtr<ID3D11ShaderResourceView> image_srv; if (FAILED(CreateWICTextureFromFile(dev, ctx, L"honkai_impact.png", reinterpret_cast<ID3D11Resource**>(&image), &image_srv))) return 1; D3D11_TEXTURE2D_DESC input_tex_desc; image->GetDesc(&input_tex_desc); UINT img_width = input_tex_desc.Width; UINT img_height = input_tex_desc.Height; // create a texture the same size as image, it's used to store the effect applied texture texture<unorm4, 2> processed_texture( static_cast<int>(img_height), static_cast<int>(img_width), 8U, av); RECT rc; GetClientRect( hWnd, &rc ); size_t wd_width = rc.right - rc.left; size_t wd_height = rc.bottom - rc.top; DXGI_SWAP_CHAIN_DESC sd; swapchain->GetDesc(&sd); if (sd.BufferDesc.Width != wd_width || sd.BufferDesc.Height != wd_height) { if (FAILED(swapchain->ResizeBuffers(sd.BufferCount, (UINT)wd_width, (UINT)wd_height, sd.BufferDesc.Format, 0))) return false; } CComPtr<ID3D11Texture2D> backbuffer; swapchain->GetBuffer(0, IID_PPV_ARGS(&backbuffer)); auto tex = make_texture<unorm4, 2>(av, backbuffer); texture_view<unorm4, 2> tv(tex); const auto ext = tv.extent; auto image_texture = make_texture<unorm4, 2>(av, image); bool bInvert = false; MSG msg; while (::IsWindow(hWnd)) if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { DispatchMessage(&msg); switch (msg.message) { case WM_KEYDOWN: bInvert = !bInvert; break; } } else { const float t = (msg.time%1000)*0.001f; concurrency::parallel_for_each( tv.accelerator_view, ext, [=, &image_texture](concurrency::index<2> idx) restrict(amp) { unorm4 val = image_texture[idx]; if (bInvert) val = unorm4(1.0) - val; val += unorm4(1.f*idx[1] / ext[1], 1.f*idx[0] / ext[0], t, 0); tv.set(idx, val); }); swapchain->Present(1, 0); } return 0; }
30.769841
127
0.66211
newpolaris
cb02ab44386a7e578d72c146c8fb2b199e348abe
1,644
cc
C++
src/GeomModels/EdgeInverseLength.cc
lucydot/devsim
2c69fcc05551bb50ca134490279e206cdeaf91a6
[ "Apache-2.0" ]
100
2015-02-02T23:47:38.000Z
2022-03-15T06:15:15.000Z
src/GeomModels/EdgeInverseLength.cc
lucydot/devsim
2c69fcc05551bb50ca134490279e206cdeaf91a6
[ "Apache-2.0" ]
75
2015-05-13T02:16:41.000Z
2022-02-23T12:20:21.000Z
src/GeomModels/EdgeInverseLength.cc
lucydot/devsim
2c69fcc05551bb50ca134490279e206cdeaf91a6
[ "Apache-2.0" ]
50
2015-10-28T17:24:24.000Z
2022-03-30T17:48:46.000Z
/*** DEVSIM Copyright 2013 Devsim 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 "EdgeInverseLength.hh" #include "EdgeModel.hh" #include "Vector.hh" #include "Region.hh" #include "Edge.hh" #include "dsAssert.hh" template <typename DoubleType> EdgeInverseLength<DoubleType>::EdgeInverseLength(RegionPtr rp) : EdgeModel("EdgeInverseLength", rp, EdgeModel::DisplayType::SCALAR) { RegisterCallback("EdgeLength"); } template <typename DoubleType> void EdgeInverseLength<DoubleType>::calcEdgeScalarValues() const { ConstEdgeModelPtr elen = GetRegion().GetEdgeModel("EdgeLength"); dsAssert(elen.get(), "UNEXPECTED"); const EdgeScalarList<DoubleType> &evals = elen->GetScalarValues<DoubleType>(); std::vector<DoubleType> ev(evals.size()); for (size_t i = 0; i < ev.size(); ++i) { ev[i] = 1.0 / evals[i]; } SetValues(ev); } template <typename DoubleType> void EdgeInverseLength<DoubleType>::Serialize(std::ostream &of) const { SerializeBuiltIn(of); } template class EdgeInverseLength<double>; #ifdef DEVSIM_EXTENDED_PRECISION #include "Float128.hh" template class EdgeInverseLength<float128>; #endif
26.095238
82
0.747567
lucydot
cb02e9f700447b690d504acdccec7dfce4987bbc
1,416
hpp
C++
libz/types/real64.hpp
kmc7468/zlang
08f9ba5dab502224bea5baa6f7a78c546094b7d0
[ "MIT" ]
5
2017-01-11T03:20:57.000Z
2017-01-15T11:20:30.000Z
libz/types/real64.hpp
kmc7468/zlang
08f9ba5dab502224bea5baa6f7a78c546094b7d0
[ "MIT" ]
null
null
null
libz/types/real64.hpp
kmc7468/zlang
08f9ba5dab502224bea5baa6f7a78c546094b7d0
[ "MIT" ]
null
null
null
#pragma once #include "../utility.hpp" #include "../variable.hpp" #include "../exces/invalid_call.hpp" #include <cmath> #include <cstdint> #include <memory> #include <utility> namespace libz::types { class real64 final : public instance { private: double m_data = 0.0; public: inline real64() : instance(type::real64) {} inline real64(const double& data) : instance(type::real64), m_data(data) {} inline real64(const real64& org) : instance(type::real64), m_data(org.m_data) {} inline real64(real64&& org) : instance(type::real64), m_data(std::move(org.m_data)) {} public: using instance::operator=; public: inline real64& assign(const real64& ins) { this->m_data = ins.m_data; return *this; } inline real64& assign(real64&& ins) { this->m_data = std::move(ins.m_data); return *this; } virtual int compare(const instance& ins) const override; virtual ptr<instance> add(const instance& ins) const override; virtual ptr<instance> sub(const instance& ins) const override; virtual ptr<instance> mul(const instance& ins) const override; virtual ptr<instance> div(const instance& ins) const override; virtual ptr<instance> mod(const instance& ins) const override; virtual ptr<instance> sign() const override; inline const double& value() const { return this->m_data; } inline double& value() { return this->m_data; } }; }
22.47619
64
0.684322
kmc7468
cb051db2720bc4dbc1bc0badd8a29a16f3b19a9d
9,382
cpp
C++
src/examples/generic_primitive/main.cpp
tjachmann/visionaray
5f181268c8da28c7d9b397300cc9759cec2bf7b3
[ "MIT" ]
416
2015-02-01T22:19:30.000Z
2022-03-29T10:48:00.000Z
src/examples/generic_primitive/main.cpp
tjachmann/visionaray
5f181268c8da28c7d9b397300cc9759cec2bf7b3
[ "MIT" ]
24
2015-06-26T17:48:08.000Z
2021-11-06T00:20:58.000Z
src/examples/generic_primitive/main.cpp
tjachmann/visionaray
5f181268c8da28c7d9b397300cc9759cec2bf7b3
[ "MIT" ]
39
2015-02-02T11:47:21.000Z
2022-03-29T10:44:43.000Z
// This file is distributed under the MIT license. // See the LICENSE file for details. #include <chrono> #include <iostream> #include <memory> #include <ostream> #include <vector> #include <GL/glew.h> #include <visionaray/detail/platform.h> #include <visionaray/cpu_buffer_rt.h> #include <visionaray/generic_primitive.h> #include <visionaray/kernels.h> #include <visionaray/material.h> #include <visionaray/pinhole_camera.h> #include <visionaray/point_light.h> #include <visionaray/scheduler.h> #include <common/manip/arcball_manipulator.h> #include <common/manip/pan_manipulator.h> #include <common/manip/zoom_manipulator.h> #include <common/viewer_glut.h> using namespace visionaray; using viewer_type = viewer_glut; //------------------------------------------------------------------------------------------------- // struct with state variables // struct renderer : viewer_type { using host_ray_type = basic_ray<simd::float4>; using primitive_type = generic_primitive<basic_triangle<3, float>, basic_sphere<float>>; renderer() : viewer_type(512, 512, "Visionaray Generic Primitive Example") , bbox({ -1.0f, -1.0f, 0.0f }, { 1.0f, 1.0f, 2.0f }) , host_sched(8) { } aabb bbox; pinhole_camera cam; cpu_buffer_rt<PF_RGBA8, PF_UNSPECIFIED> host_rt; tiled_sched<host_ray_type> host_sched; // rendering data aligned_vector<primitive_type> primitives; aligned_vector<vec3> normals; aligned_vector<plastic<float>> materials; void generate_frame(); protected: void on_display(); void on_resize(int w, int h); }; //------------------------------------------------------------------------------------------------- // Generate an animation frame // void renderer::generate_frame() { static const size_t N = 14; primitives.resize(N); normals.resize(N); materials.resize(4); using sphere_type = basic_sphere<float>; using triangle_type = basic_triangle<3, float>; // triangles // 1st pyramid triangle_type triangles[N]; triangles[ 0].v1 = vec3(-1, -1, 1); triangles[ 0].e1 = vec3( 1, -1, 1) - triangles[ 0].v1; triangles[ 0].e2 = vec3( 0, 1, 0) - triangles[ 0].v1; triangles[ 1].v1 = vec3( 1, -1, 1); triangles[ 1].e1 = vec3( 1, -1, -1) - triangles[ 1].v1; triangles[ 1].e2 = vec3( 0, 1, 0) - triangles[ 1].v1; triangles[ 2].v1 = vec3( 1, -1, -1); triangles[ 2].e1 = vec3(-1, -1, -1) - triangles[ 2].v1; triangles[ 2].e2 = vec3( 0, 1, 0) - triangles[ 2].v1; triangles[ 3].v1 = vec3(-1, -1, -1); triangles[ 3].e1 = vec3(-1, -1, 1) - triangles[ 3].v1; triangles[ 3].e2 = vec3( 0, 1, 0) - triangles[ 3].v1; triangles[ 4].v1 = vec3( 1, -1, 1); triangles[ 4].e1 = vec3(-1, -1, 1) - triangles[ 4].v1; triangles[ 4].e2 = vec3( 1, -1, -1) - triangles[ 4].v1; triangles[ 5].v1 = vec3(-1, -1, 1); triangles[ 5].e1 = vec3(-1, -1, -1) - triangles[ 5].v1; triangles[ 5].e2 = vec3( 1, -1, -1) - triangles[ 5].v1; // 2nd pyramid triangles[ 6].v1 = vec3(0.3, 0.3, 0.7); triangles[ 6].e1 = vec3(0.7, 0.3, 0.7) - triangles[ 6].v1; triangles[ 6].e2 = vec3(0.5, 0.7, 0.5) - triangles[ 6].v1; triangles[ 7].v1 = vec3(0.7, 0.3, 0.7); triangles[ 7].e1 = vec3(0.7, 0.3, 0.3) - triangles[ 7].v1; triangles[ 7].e2 = vec3(0.5, 0.7, 0.5) - triangles[ 7].v1; triangles[ 8].v1 = vec3(0.7, 0.3, 0.3); triangles[ 8].e1 = vec3(0.3, 0.3, 0.3) - triangles[ 8].v1; triangles[ 8].e2 = vec3(0.5, 0.7, 0.5) - triangles[ 8].v1; triangles[ 9].v1 = vec3(0.3, 0.3, 0.3); triangles[ 9].e1 = vec3(0.3, 0.3, 0.7) - triangles[ 9].v1; triangles[ 9].e2 = vec3(0.5, 0.7, 0.5) - triangles[ 9].v1; triangles[10].v1 = vec3(0.7, 0.3, 0.7); triangles[10].e1 = vec3(0.3, 0.3, 0.7) - triangles[10].v1; triangles[10].e2 = vec3(0.7, 0.3, 0.3) - triangles[10].v1; triangles[11].v1 = vec3(0.3, 0.3, 0.7); triangles[11].e1 = vec3(0.3, 0.3, 0.3) - triangles[11].v1; triangles[11].e2 = vec3(0.7, 0.3, 0.3) - triangles[11].v1; // // generate face normals assign id's: // prim_id links primitives and normals // geom_id links primitives and materials // for (size_t i = 0; i < N - 2; ++i) { triangles[i].prim_id = static_cast<unsigned>(i); triangles[i].geom_id = i < 6 ? 0 : 1; normals[i] = normalize( cross(triangles[i].e1, triangles[i].e2) ); primitives[i] = triangles[i]; } // animated spheres using namespace std::chrono; auto now = high_resolution_clock::now(); auto secs = duration_cast<milliseconds>(now.time_since_epoch()).count(); static float y = -0.5f; static float m = 0.1f; static const int interval = 1; if (secs % interval == 0) { y += 0.2f * m; if (y < -0.5f) { m = 0.1f; } else if (y > 1.0f) { m = -0.1f; } } sphere_type s1; s1.prim_id = N - 2; s1.geom_id = 2; s1.center = vec3(-0.7f, y, 0.8); s1.radius = 0.5f; primitives[N - 2] = s1; sphere_type s2; s2.prim_id = N - 1; s2.geom_id = 3; s2.center = vec3(1.0f, 0.8, -.0f); s2.radius = 0.3f; primitives[N - 1] = s2; // materials materials[0].ca() = from_rgb(0.0f, 0.0f, 0.0f); materials[0].cd() = from_rgb(0.0f, 1.0f, 1.0f); materials[0].cs() = from_rgb(0.2f, 0.4f, 0.4f); materials[0].specular_exp() = 16.0f; materials[1].ca() = from_rgb(0.0f, 0.0f, 0.0f); materials[1].cd() = from_rgb(1.0f, 0.0f, 0.0f); materials[1].cs() = from_rgb(0.5f, 0.2f, 0.2f); materials[1].specular_exp() = 128.0f; materials[2].ca() = from_rgb(0.0f, 0.0f, 0.0f); materials[2].cd() = from_rgb(0.0f, 0.0f, 1.0f); materials[2].cs() = from_rgb(1.0f, 1.0f, 1.0f); materials[2].specular_exp() = 128.0f; materials[3].ca() = from_rgb(0.0f, 0.0f, 0.0f); materials[3].cd() = from_rgb(1.0f, 1.0f, 1.0f); materials[3].cs() = from_rgb(1.0f, 1.0f, 1.0f); materials[3].specular_exp() = 32.0f; for (auto& m : materials) { m.ka() = 1.0f; m.kd() = 1.0f; m.ks() = 1.0f; } } //------------------------------------------------------------------------------------------------- // Display function // void renderer::on_display() { // some setup auto sparams = make_sched_params( cam, host_rt ); // a light positioned slightly distant above the scene point_light<float> light; light.set_cl( vec3(1.0f, 1.0f, 1.0f) ); light.set_kl( 1.0f ); light.set_position( vec3(0.0f, 10.0f, 10.0f) ); light.set_constant_attenuation(1.0f); light.set_linear_attenuation(0.0f); light.set_quadratic_attenuation(0.0f); std::vector<point_light<float>> lights; lights.push_back(light); generate_frame(); auto kparams = make_kernel_params( normals_per_face_binding{}, primitives.data(), primitives.data() + primitives.size(), normals.data(), (vec3*)nullptr, // no shading normals! materials.data(), lights.data(), lights.data() + lights.size(), 4, // number of reflective bounces 0.0001 // epsilon to avoid self intersection by secondary rays ); whitted::kernel<decltype(kparams)> kernel; kernel.params = kparams; host_sched.frame(kernel, sparams); // display the rendered image auto bgcolor = background_color(); glClearColor(bgcolor.x, bgcolor.y, bgcolor.z, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); host_rt.display_color_buffer(); } //------------------------------------------------------------------------------------------------- // resize event // void renderer::on_resize(int w, int h) { cam.set_viewport(0, 0, w, h); float aspect = w / static_cast<float>(h); cam.perspective(45.0f * constants::degrees_to_radians<float>(), aspect, 0.001f, 1000.0f); host_rt.resize(w, h); viewer_type::on_resize(w, h); } //------------------------------------------------------------------------------------------------- // Main function, performs initialization // int main(int argc, char** argv) { renderer rend; try { rend.init(argc, argv); } catch (std::exception const& e) { std::cerr << e.what() << '\n'; return EXIT_FAILURE; } float aspect = rend.width() / static_cast<float>(rend.height()); rend.cam.perspective(45.0f * constants::degrees_to_radians<float>(), aspect, 0.001f, 1000.0f); rend.cam.view_all( rend.bbox ); rend.add_manipulator( std::make_shared<arcball_manipulator>(rend.cam, mouse::Left) ); rend.add_manipulator( std::make_shared<pan_manipulator>(rend.cam, mouse::Middle) ); // Additional "Alt + LMB" pan manipulator for setups w/o middle mouse button rend.add_manipulator( std::make_shared<pan_manipulator>(rend.cam, mouse::Left, keyboard::Alt) ); rend.add_manipulator( std::make_shared<zoom_manipulator>(rend.cam, mouse::Right) ); rend.event_loop(); }
28.344411
100
0.551055
tjachmann
cb096e4ebdbb923b370f240351c604d35495e6f4
1,696
cpp
C++
lib/Basic/CXCodeGenOptions.cpp
Gnimuc/libclangex
3d519fba37210d06578b10ea9bdb1d496be0e9d0
[ "Apache-2.0", "MIT-0", "MIT" ]
1
2022-01-11T00:49:42.000Z
2022-01-11T00:49:42.000Z
lib/Basic/CXCodeGenOptions.cpp
Gnimuc/libclangex
3d519fba37210d06578b10ea9bdb1d496be0e9d0
[ "Apache-2.0", "MIT-0", "MIT" ]
4
2021-08-01T06:07:06.000Z
2022-02-04T14:14:15.000Z
lib/Basic/CXCodeGenOptions.cpp
Gnimuc/libclangex
3d519fba37210d06578b10ea9bdb1d496be0e9d0
[ "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
#include "clang-ex/Basic/CXCodeGenOptions.h" #include "clang/Basic/CodeGenOptions.h" #include "llvm/Support/raw_ostream.h" CXCodeGenOptions clang_CodeGenOptions_create(CXInit_Error *ErrorCode) { CXInit_Error Err = CXInit_NoError; std::unique_ptr<clang::CodeGenOptions> ptr = std::make_unique<clang::CodeGenOptions>(); if (!ptr) { fprintf(stderr, "LIBCLANGEX ERROR: failed to create `clang::CodeGenOptions`\n"); Err = CXInit_CanNotCreate; } if (ErrorCode) *ErrorCode = Err; return ptr.release(); } void clang_CodeGenOptions_dispose(CXCodeGenOptions DO) { delete static_cast<clang::CodeGenOptions *>(DO); } const char *clang_CodeGenOptions_getArgv0(CXCodeGenOptions CGO) { return static_cast<clang::CodeGenOptions *>(CGO)->Argv0; } void clang_CodeGenOptions_PrintStats(CXCodeGenOptions CGO) { auto Opts = static_cast<clang::CodeGenOptions *>(CGO); llvm::errs() << "\n*** CodeGenOptions Stats:\n"; llvm::errs() << " CodeModel: " << Opts->CodeModel << "\n"; llvm::errs() << " DebugPass: " << Opts->DebugPass << "\n"; llvm::errs() << " FloatABI: " << Opts->FloatABI << "\n"; llvm::errs() << " LimitFloatPrecision: " << Opts->LimitFloatPrecision << "\n"; llvm::errs() << " MainFileName: " << Opts->MainFileName << "\n"; llvm::errs() << " TrapFuncName: " << Opts->TrapFuncName << "\n"; llvm::errs() << " DependentLibraries: \n"; for (const auto &Dep : Opts->DependentLibraries) llvm::errs() << " " << Dep << "\n"; llvm::errs() << " LinkerOptions: \n"; for (const auto &Opt : Opts->LinkerOptions) llvm::errs() << " " << Opt << "\n"; llvm::errs() << " CudaGpuBinaryFileName: " << Opts->CudaGpuBinaryFileName << "\n"; }
36.085106
89
0.65625
Gnimuc
cb0a34fa3ea68fe0c9d9ed617abdf51a5ec6a377
1,832
cpp
C++
vislib/tests/clusterTest/PlainServer.cpp
azuki-monster/megamol
f5d75ae5630f9a71a7fbf81624bfd4f6b253c655
[ "BSD-3-Clause" ]
2
2020-10-16T10:15:37.000Z
2021-01-21T13:06:00.000Z
vislib/tests/clusterTest/PlainServer.cpp
azuki-monster/megamol
f5d75ae5630f9a71a7fbf81624bfd4f6b253c655
[ "BSD-3-Clause" ]
null
null
null
vislib/tests/clusterTest/PlainServer.cpp
azuki-monster/megamol
f5d75ae5630f9a71a7fbf81624bfd4f6b253c655
[ "BSD-3-Clause" ]
1
2021-01-28T01:19:54.000Z
2021-01-28T01:19:54.000Z
/* * PlainServer.cpp * * Copyright (C) 2008 by Universitaet Stuttgart (VIS). Alle Rechte vorbehalten. */ #include "PlainServer.h" #include <iostream> #include "vislib/net/cluster/clustermessages.h" /* * PlainServer::GetInstance */ PlainServer& PlainServer::GetInstance(void) { static PlainServer *instance = NULL; if (instance == NULL) { instance = new PlainServer(); } return *instance; } /* * PlainServer::~PlainServer */ PlainServer::~PlainServer(void) { } /* * PlainServer::Initialise */ void PlainServer::Initialise(vislib::sys::CmdLineProviderA& inOutCmdLine) { vislib::net::cluster::AbstractServerNode::Initialise(inOutCmdLine); } /* * PlainServer::Initialise */ void PlainServer::Initialise(vislib::sys::CmdLineProviderW& inOutCmdLine) { vislib::net::cluster::AbstractServerNode::Initialise(inOutCmdLine); } /* * PlainServer::Run */ DWORD PlainServer::Run(void) { DWORD retval = vislib::net::cluster::AbstractServerNode::Run(); char dowel; std::cin >> dowel; return retval; } /* * PlainServer::PlainServer */ PlainServer::PlainServer(void) : vislib::net::cluster::AbstractServerNode() { } /* * PlainServer::onMessageReceived */ bool PlainServer::onMessageReceived(const vislib::net::Socket& src, const UINT msgId, const BYTE *body, const SIZE_T cntBody) { std::cout << "PlainServer received message " << msgId << " with " << cntBody << " Bytes of body data" << std::endl; switch (msgId) { case VLC1_USER_MSG_ID(1): { char *str = const_cast<char *>(reinterpret_cast<const char *>( body)); str[cntBody - 1] = 0; std::cout << str << std::endl; } return true; default: break; } return false; }
19.698925
79
0.629913
azuki-monster
cb0e3af2988c8628f40695361d1d23bb9adc8c73
3,892
cpp
C++
Project1/cpp/src/system.cpp
ErlendLima/FYS4411
e7221d9871e0e2fdaf7b9721fb414a9fad74022b
[ "MIT" ]
null
null
null
Project1/cpp/src/system.cpp
ErlendLima/FYS4411
e7221d9871e0e2fdaf7b9721fb414a9fad74022b
[ "MIT" ]
null
null
null
Project1/cpp/src/system.cpp
ErlendLima/FYS4411
e7221d9871e0e2fdaf7b9721fb414a9fad74022b
[ "MIT" ]
null
null
null
#include "system.hpp" #include "InitialStates/initialstate.hpp" #include "Hamiltonians/hamiltonian.hpp" #include "WaveFunctions/wavefunction.hpp" #include "particles.hpp" #include "sampler.hpp" #include <string> #include <random> #include <iostream> #include <cmath> double* System::stepBruteForce(int particle) { for(int i = 0; i < getNumDim(); i++) { m_step[i] = 2*m_stepLength*(getRandomUniform() - 0.5); } return m_step; } double* System::stepImportanceSampling(int particle) { Particles* particles = getParticles(); double* position = particles->position(particle); double sqrtdt = std::sqrt(m_stepLength); getWavefunction()->gradient(m_gradientOld, particle, position); for(int i = 0; i < getNumDim(); i++) { m_step[i] = m_gradientOld[i]*m_stepLength + getRandomNormal()*sqrtdt; } return m_step; } double System::greenFunction(double dt) { int numDim = getNumDim(); Particles* particles = getParticles(); int movedParticle = particles->getMovedParticle(); double* x = particles->position(movedParticle); double* y = particles->getAdjustPos(); getWavefunction()->gradient(m_gradientNew, movedParticle, y); double temp1, temp2, expo = 0; for (int i = 0; i < numDim; i++) { temp1 = (x[i] - y[i] - m_gradientNew[i]*dt); temp1 = temp1*temp1; temp2 = (y[i] - x[i] - m_gradientOld[i]*dt); temp2 = temp2*temp2; expo -= (temp1 - temp2); } expo /= 2*dt; return std::exp(expo); } double System::acceptanceRatioBruteForce() { return getWavefunction()->amplitudeRatio(); } double System::acceptanceRatioImportanceSampling() { return greenFunction(m_stepLength)*getWavefunction()->amplitudeRatio(); } void System::initiate() { m_initState->initiate(); m_wavefunction->initiate(); m_sampler->initiate(); m_step = new double [getNumDim()]; m_gradientOld = new double [getNumDim()]; m_gradientNew = new double [getNumDim()]; } void System::runMetropolis() { bool accepted; int particle; initiate(); getSampler()->sample(true); //sample the initial configuration m_acceptanceRate = 0; for(int i=0; i < m_metropolisSteps - 1; i++) { //propose adjustment to some particle particle = i%m_numParticles; getParticles()->proposeAdjustPos((this->*step)(particle), particle); accepted = ((this->*acceptanceRatio)() > getRandomUniform()); if (accepted) { getParticles()->commitAdjustPos(); m_acceptanceRate += 1; } getSampler()->sample(accepted); } m_acceptanceRate /= getMetropolisSteps(); getSampler()->close(); } void System::setImportanceSampling(int importanceSampling) { if (importanceSampling == 1) { step = &System::stepImportanceSampling; acceptanceRatio = &System::acceptanceRatioImportanceSampling; } else { step = &System::stepBruteForce; acceptanceRatio = &System::acceptanceRatioBruteForce; } } void System::setInitialState(InitialState* initState) { m_initState = initState; m_initState->setSystem(this); } void System::setHamiltonian(Hamiltonian* hamiltonian) { m_hamiltonian = hamiltonian; m_hamiltonian->setSystem(this); } void System::setWaveFunction(WaveFunction* wavefunction) { m_wavefunction = wavefunction; m_wavefunction->setSystem(this); } void System::setParticles(Particles* particles) { m_particles = particles; m_particles->setSystem(this); } void System::setSampler(Sampler* sampler) { m_sampler = sampler; m_sampler->setSystem(this); } void System::setSeed(int seed) { gen = new std::mt19937(seed); distUniform = new std::uniform_real_distribution<double>(0, 1); distNormal = new std::normal_distribution<double>(0, 1); }
22.49711
77
0.658787
ErlendLima
cb0f6675ad780987480e94d90e81048339558373
895
cpp
C++
src/Nazara/Shader/SpirvSectionBase.cpp
jayrulez/NazaraEngine
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
src/Nazara/Shader/SpirvSectionBase.cpp
jayrulez/NazaraEngine
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
src/Nazara/Shader/SpirvSectionBase.cpp
jayrulez/NazaraEngine
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) // This file is part of the "Nazara Engine - Shader module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Shader/SpirvSectionBase.hpp> #include <Nazara/Core/Endianness.hpp> #include <Nazara/Shader/Debug.hpp> namespace Nz { std::size_t SpirvSectionBase::AppendRaw(const Raw& raw) { std::size_t offset = GetOutputOffset(); const UInt8* ptr = static_cast<const UInt8*>(raw.ptr); std::size_t size4 = CountWord(raw); for (std::size_t i = 0; i < size4; ++i) { UInt32 codepoint = 0; for (std::size_t j = 0; j < 4; ++j) { #ifdef NAZARA_BIG_ENDIAN std::size_t pos = i * 4 + (3 - j); #else std::size_t pos = i * 4 + j; #endif if (pos < raw.size) codepoint |= UInt32(ptr[pos]) << (j * 8); } AppendRaw(codepoint); } return offset; } }
22.948718
77
0.650279
jayrulez
cb152d81198207382384496bce3c971d7bfc5999
2,494
cpp
C++
ex01/ScavTrap.cpp
Igors78/cpp03
211de909cee642e63dca1bb273cb910c6cdf4104
[ "Unlicense" ]
3
2021-11-14T06:49:22.000Z
2022-01-27T19:23:23.000Z
ex02/ScavTrap.cpp
Igors78/cpp03
211de909cee642e63dca1bb273cb910c6cdf4104
[ "Unlicense" ]
null
null
null
ex02/ScavTrap.cpp
Igors78/cpp03
211de909cee642e63dca1bb273cb910c6cdf4104
[ "Unlicense" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ScavTrap.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ioleinik <ioleinik@students.42wolfsburg.de +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/11/13 10:08:36 by ioleinik #+# #+# */ /* Updated: 2021/11/13 10:35:55 by ioleinik ### ########.fr */ /* */ /* ************************************************************************** */ #include "ScavTrap.hpp" ScavTrap::ScavTrap() { this->_hitpoints = 100; this->_energy_points = 50; this->_attack_damage = 20; this->_name = "Default"; std::cout << "Default ScavTrap (CHILD) constructor called" << std::endl; } ScavTrap::ScavTrap(std::string const name) { this->_hitpoints = 100; this->_energy_points = 50; this->_attack_damage = 20; this->_name = name; std::cout << name << " ScavTrap (CHILD) constructor called" << std::endl; } ScavTrap::~ScavTrap() { std::cout << this->_name << " ScavTrap (CHILD) destructor called" << std::endl; } ScavTrap::ScavTrap(const ScavTrap &source) { std::cout << "ScavTrap (CHILD) Copy constructor called" << std::endl; *this = source; } ScavTrap &ScavTrap::operator=(const ScavTrap &right) { if (this != &right) { std::string local; local = right.getName(); this->_name = local + "(copy)"; this->_hitpoints = right.getHitpoints(); this->_energy_points = right.getEnergyPoints(); this->_attack_damage = right.getAttackDamage(); std::cout << "ScavTrap (CHILD) Assignment called" << std::endl; } return (*this); } void ScavTrap::guardGate() { std::cout << "ScavTrap " << this->_name << " entered Gate keeper mode" << std::endl; } void ScavTrap::attack(std::string const &target) { if (this->_energy_points < this->_attack_damage) std::cout << "Not enought energy to attack" << std::endl; else { this->_energy_points -= this->_attack_damage; std::cout << "ScavTrap " << this->_name << " attack " << target << ", causing " << this->_attack_damage << " points of damage!" << std::endl; } }
31.974359
80
0.463512
Igors78
cb15b9c007ec330342fab3f7813b386b570cbe56
893
cpp
C++
Unrest-iOS/GameOverMenu.cpp
arvindrajayadav/unrest
d89f20e95fbcdef37a47ab1454b2479522a0e43f
[ "MIT" ]
11
2020-08-04T08:37:46.000Z
2022-03-31T22:35:15.000Z
CRAB/GameOverMenu.cpp
arvindrajayadav/unrest
d89f20e95fbcdef37a47ab1454b2479522a0e43f
[ "MIT" ]
1
2020-12-16T16:51:52.000Z
2020-12-18T06:35:38.000Z
Unrest-iOS/GameOverMenu.cpp
arvindrajayadav/unrest
d89f20e95fbcdef37a47ab1454b2479522a0e43f
[ "MIT" ]
7
2020-08-04T09:34:20.000Z
2021-09-11T03:00:16.000Z
#include "stdafx.h" #include "GameOverMenu.h" using namespace pyrodactyl::ui; using namespace pyrodactyl::image; void GameOverMenu::Load(rapidxml::xml_node<char> *node) { if (NodeValid(node)) { if (NodeValid("bg", node)) bg.Load(node->first_node("bg")); if (NodeValid("title", node)) { rapidxml::xml_node<char> *tinode = node->first_node("title"); title.Load(tinode); for (auto n = tinode->first_node("quote"); n != NULL; n = n->next_sibling("quote")) { std::string str; LoadStr(str, "text", n); quote.push_back(str); } } menu.Load(node->first_node("menu")); } } int GameOverMenu::HandleEvents(const SDL_Event &Event) { return menu.HandleEvents(Event); } void GameOverMenu::Draw() { bg.Draw(); if (cur < quote.size()) title.Draw(quote.at(cur)); menu.Draw(); } void GameOverMenu::SetUI() { bg.SetUI(); title.SetUI(); menu.SetUI(); }
17.509804
86
0.646137
arvindrajayadav
cb16454aadb1194febe24d76e7eb60025498a12b
764
cpp
C++
Challenge Array/MaximumSubarraySum4.cpp
sgpritam/cbcpp
192b55d8d6930091d1ceb883f6dccf06735a391f
[ "MIT" ]
2
2019-11-11T17:16:52.000Z
2020-10-04T06:05:49.000Z
Challenge Array/MaximumSubarraySum4.cpp
codedevmdu/cbcpp
85c94d81d6e491f67e3cc1ea12534065b7cde16e
[ "MIT" ]
null
null
null
Challenge Array/MaximumSubarraySum4.cpp
codedevmdu/cbcpp
85c94d81d6e491f67e3cc1ea12534065b7cde16e
[ "MIT" ]
4
2019-10-24T16:58:10.000Z
2020-10-04T06:05:47.000Z
// C++ program to print largest contiguous array sum #include<iostream> #include<climits> using namespace std; int maxSubArraySum(int a[], int size) { int max_so_far = INT_MIN, max_ending_here = 0; for (int i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i]; if (max_so_far < max_ending_here) max_so_far = max_ending_here; if (max_ending_here < 0) max_ending_here = 0; } return max_so_far; } int main() { int t; cin>>t; for(int j=0;j<t;j++) { int n; cin>>n; int a[n]; for(int i=0;i<n;i++) { cin>>a[i]; } int max_sum = maxSubArraySum(a, n); cout << max_sum<<endl; } return 0; }
19.589744
53
0.524869
sgpritam
0e11c85eca835a2034d76206a0b0424bf1c8988a
2,018
cc
C++
lite/operators/unstack_op.cc
AIpioneer/Paddle-Lite
bd2a37468343e91b684d3ff1e3241be8de502ff6
[ "Apache-2.0" ]
1
2021-11-30T18:19:44.000Z
2021-11-30T18:19:44.000Z
lite/operators/unstack_op.cc
AIpioneer/Paddle-Lite
bd2a37468343e91b684d3ff1e3241be8de502ff6
[ "Apache-2.0" ]
null
null
null
lite/operators/unstack_op.cc
AIpioneer/Paddle-Lite
bd2a37468343e91b684d3ff1e3241be8de502ff6
[ "Apache-2.0" ]
2
2021-02-10T13:37:56.000Z
2021-02-25T07:32:30.000Z
// Copyright (c) 2020 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 "lite/operators/unstack_op.h" #include "lite/core/op_lite.h" #include "lite/core/op_registry.h" namespace paddle { namespace lite { namespace operators { bool UnstackOp::CheckShape() const { CHECK(param_.X); for (auto out : param_.Out) { CHECK(out); } return true; } bool UnstackOp::InferShapeImpl() const { auto x = param_.X; auto outs = param_.Out; int axis = param_.axis; if (axis < 0) { axis += x->dims().size(); } int num = param_.num; auto x_shape = x->dims().Vectorize(); CHECK_EQ(x_shape[axis], static_cast<int64_t>(num)) << "num(attr) should be equal to x_dims[axis]. But received x_dims: " << x->dims() << ", axis: " << param_.axis << ", num: " << num; auto out_shape = x_shape; out_shape.erase(out_shape.begin() + axis); for (auto out : outs) { out->Resize(out_shape); } return true; } bool UnstackOp::AttachImpl(const cpp::OpDesc &op_desc, lite::Scope *scope) { param_.X = scope->FindTensor(op_desc.Input("X").front()); auto out_names = op_desc.Output("Y"); for (auto out_name : out_names) { param_.Out.emplace_back(scope->FindMutableTensor(out_name)); } param_.axis = op_desc.GetAttr<int>("axis"); param_.num = op_desc.GetAttr<int>("num"); return true; } } // namespace operators } // namespace lite } // namespace paddle REGISTER_LITE_OP(unstack, paddle::lite::operators::UnstackOp);
29.246377
76
0.685332
AIpioneer
0e192263af379d9b47eb9e3ddfa77d8a0d0533e9
6,748
cpp
C++
src/Visioneer/Core/AnnotationRenderer.cpp
teplandr/Visioneer
8aee849eabe9b3bd0dcb169c315733b550df63c9
[ "MIT" ]
6
2022-01-24T03:54:04.000Z
2022-01-26T12:42:00.000Z
src/Visioneer/Core/AnnotationRenderer.cpp
teplandr/Visioneer
8aee849eabe9b3bd0dcb169c315733b550df63c9
[ "MIT" ]
null
null
null
src/Visioneer/Core/AnnotationRenderer.cpp
teplandr/Visioneer
8aee849eabe9b3bd0dcb169c315733b550df63c9
[ "MIT" ]
null
null
null
#include "AnnotationRenderer.h" #include <unordered_map> namespace Visioneer { static std::vector<const char*> ClassNamesCOCO { "person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat", "traffic light", "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee", "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard", "tennis racket", "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "couch", "potted plant", "bed", "dining table", "toilet", "tv", "laptop", "mouse", "remote", "keyboard", "cell phone", "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase", "scissors", "teddy bear", "hair drier", "toothbrush" }; static std::vector<uint32_t> ColorsCOCO { 0xff3c14dc, 0xffa9a9a9, 0xffdcdcdc, 0xff4f4f2f, 0xff2f6b55, 0xff13458b, 0xff238e6b, 0xff578b2e, 0xff228b22, 0xff00007f, 0xff701919, 0xff006400, 0xff008080, 0xff8b3d48, 0xff2222b2, 0xffa09e5f, 0xff998877, 0xff71b33c, 0xff8f8fbc, 0xff993366, 0xff808000, 0xff6bb7bd, 0xff3f85cd, 0xffb48246, 0xff1e69d2, 0xff32cd9a, 0xffaab220, 0xff5c5ccd, 0xff8b0000, 0xff82004b, 0xff32cd32, 0xff20a5da, 0xff8fbc8f, 0xff800080, 0xff6030b0, 0xffaacd66, 0xffcc3299, 0xff0045ff, 0xff008cff, 0xff00a5ff, 0xff00d7ff, 0xff00ffff, 0xff8515c7, 0xffcd0000, 0xff87b8de, 0xffd0e040, 0xff00ff7f, 0xff00ff00, 0xffd355ba, 0xff9afa00, 0xffe22b8a, 0xff7fff00, 0xffe16941, 0xff7a96e9, 0xff696969, 0xffffff00, 0xffffbf00, 0xffdb7093, 0xffff0000, 0xff2fffad, 0xffd670da, 0xffd8bfd8, 0xffdec4b0, 0xff507fff, 0xffff00ff, 0xff9370db, 0xff7280fa, 0xffaae8ee, 0xff54ffff, 0xffed9564, 0xffdda0dd, 0xffe6e0b0, 0xff90ee90, 0xff9314ff, 0xffee687b, 0xffface87, 0xffd4ff7f, 0xffb9daff, 0xffb469ff, 0xffc1b6ff }; static std::unordered_map<BBoxesAnnotation::DatasetType, std::vector<const char*>> TypeSpecificClassNames { {BBoxesAnnotation::DatasetType::OneClass, std::vector<const char*>{""}}, {BBoxesAnnotation::DatasetType::COCO, ClassNamesCOCO} }; static std::unordered_map<BBoxesAnnotation::DatasetType, std::vector<uint32_t>> TypeSpecificColors { {BBoxesAnnotation::DatasetType::OneClass, std::vector<uint32_t>{0xff3c14dc}}, {BBoxesAnnotation::DatasetType::COCO, ColorsCOCO} }; static std::vector<const char*> ClassNamesVOC { "background", "aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor" }; static std::vector<uint32_t> ColorsVOC { 0xff000000, 0xff3c14dc, 0xffdcdcdc, 0xff4f4f2f, 0xff2f6b55, 0xff13458b, 0xff238e6b, 0xff578b2e, 0xff228b22, 0xff00007f, 0xff701919, 0xff006400, 0xff008080, 0xff8b3d48, 0xff2222b2, 0xffa09e5f, 0xff998877, 0xff71b33c, 0xff8f8fbc, 0xff993366, 0xffa9a9a9 }; void AnnotationRenderer::operator()(const EmptyAnnotation&) { } void AnnotationRenderer::operator()(const BBoxesAnnotation& annotation) { ImDrawList *drawList = ImGui::GetWindowDrawList(); bool isBBoxSelected = false; for (const auto& [bbox, score, classID] : annotation.Items) { ImVec2 tl(mInitPos.x + bbox.X1 * mViewerSize.x, mInitPos.y + bbox.Y1 * mViewerSize.y); ImVec2 br(mInitPos.x + bbox.X2 * mViewerSize.x, mInitPos.y + bbox.Y2 * mViewerSize.y); drawList->AddRect(tl, br, TypeSpecificColors.at(annotation.Type).at(classID), 0.f, 0, 3.f); if (!isBBoxSelected && mMousePos.x >= tl.x && mMousePos.x <= br.x && mMousePos.y >= tl.y && mMousePos.y <= br.y) { drawList->AddRectFilled(tl, br, changeAlpha(TypeSpecificColors.at(annotation.Type).at(classID), 0.25f), 0.f, 0); ImGui::SetTooltip("%s (%.3f)", TypeSpecificClassNames.at(annotation.Type).at(classID), score); isBBoxSelected = true; } } } void AnnotationRenderer::operator()(const SemanticSegmentAnnotation& annotation) { // In future, this transform should be done by shader uint8_t selectedClassID = 255; if (mMousePos.x > 0.f && mMousePos.y > 0.f) { int hoveredRow = static_cast<int>(annotation.Mask.rows * (mMousePos.y - mInitPos.y) / mViewerSize.y); int hoveredCol = static_cast<int>(annotation.Mask.cols * (mMousePos.x - mInitPos.x) / mViewerSize.x); selectedClassID = annotation.Mask.at<uint8_t>(hoveredRow, hoveredCol); ImGui::SetTooltip("%s", ClassNamesVOC[selectedClassID]); } std::vector<cv::Vec4b> preprocessedColorsVOC(ColorsVOC.size()); for (uint32_t colorIndex = 0; colorIndex < ColorsVOC.size(); ++colorIndex) { float alpha = (selectedClassID == colorIndex) ? 0.5f : 0.4f; preprocessedColorsVOC[colorIndex] = abgr2bgra(changeAlpha(ColorsVOC[colorIndex], alpha)); } cv::Mat coloredMask(annotation.Mask.size(), CV_8UC4); for (int row = 0; row < coloredMask.rows; ++row) { for (int col = 0; col < coloredMask.cols; ++col) { auto classID = annotation.Mask.at<uint8_t>(row, col); coloredMask.at<cv::Vec4b>(row, col) = preprocessedColorsVOC[classID]; } } if (!mSegmentationMask || (mSegmentationMask->width() != (uint32_t)annotation.Mask.cols) || (mSegmentationMask->height() != (uint32_t)annotation.Mask.rows)) mSegmentationMask = std::make_shared<Texture>(coloredMask); else mSegmentationMask->setData(coloredMask); ImDrawList *drawList = ImGui::GetWindowDrawList(); drawList->AddImage(reinterpret_cast<ImTextureID>(mSegmentationMask->rendererID()), mInitPos, {mInitPos.x + mViewerSize.x, mInitPos.y + mViewerSize.y}); } void AnnotationRenderer::operator()(const KeypointsAnnotation&) { } ImU32 AnnotationRenderer::changeAlpha(ImU32 color, float desiredAlpha) { const ImU32 colorMask = 0xffffff; float alphaF = desiredAlpha * 255.f; // from 0.f to 255.f ImU32 alpha = (ImU32)(alphaF) << 24; // alpha is left-most byte return (alpha & ~colorMask) | (color & colorMask); // set alpha and do not change color } cv::Vec4b AnnotationRenderer::abgr2bgra(ImU32 color) { static const uint32_t aMask = 0xff000000; static const uint32_t bMask = 0x00ff0000; static const uint32_t gMask = 0x0000ff00; static const uint32_t rMask = 0x000000ff; return {uint8_t((color & bMask) >> 16), uint8_t((color & gMask) >> 8), uint8_t(color & rMask), uint8_t((color & aMask) >> 24)}; } }
45.288591
160
0.686129
teplandr
0e1c4928d846bddc909d36645764899356cc1c8a
7,988
cpp
C++
test_scripts/TestNative.cpp
chatra-lang/chatra
fdae457fcbd066ac8c0d44d6b763d4a18bf524f7
[ "Apache-2.0" ]
3
2019-10-14T12:25:23.000Z
2021-01-06T17:53:17.000Z
test_scripts/TestNative.cpp
chatra-lang/chatra
fdae457fcbd066ac8c0d44d6b763d4a18bf524f7
[ "Apache-2.0" ]
3
2019-10-15T14:40:34.000Z
2020-08-29T14:25:06.000Z
test_scripts/TestNative.cpp
chatra-lang/chatra
fdae457fcbd066ac8c0d44d6b763d4a18bf524f7
[ "Apache-2.0" ]
null
null
null
/* * Programming language 'Chatra' reference implementation * * Copyright(C) 2019-2020 Chatra Project Team * * 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. * * author: Satoshi Hosokawa (chatra.hosokawa@gmail.com) */ #include "chatra.h" #include <unordered_map> constexpr const char* packageName = "test_native"; static const char* script = #include "test_native.cha" ; struct TestNativeData final : public cha::INativePtr { int value; explicit TestNativeData(int value = 0) : value(value) {} }; struct PackageData final { std::unique_ptr<cha::Event> event; }; static std::unordered_map<cha::RuntimeId, std::unique_ptr<PackageData>> packageDataMap; struct TestPackageInterface final : public cha::IPackage { std::vector<uint8_t> savePackage(cha::PackageContext& pct) override { auto& packageData = packageDataMap[pct.runtimeId()]; if (!packageData || !packageData->event) return {}; return pct.saveEvent(packageData->event.get()); } void restorePackage(cha::PackageContext& pct, const std::vector<uint8_t>& stream) override { auto& packageData = packageDataMap[pct.runtimeId()]; if (!packageData) packageData.reset(new PackageData()); packageData->event.reset(); if (!stream.empty()) packageData->event.reset(pct.restoreEvent(stream)); } std::vector<uint8_t> saveNativePtr(cha::PackageContext& pct, cha::INativePtr* ptr) override { (void)pct; auto* p = static_cast<TestNativeData*>(ptr); std::vector<uint8_t> data(8); *reinterpret_cast<int32_t*>(data.data()) = static_cast<int32_t>(p->value); return data; } cha::INativePtr* restoreNativePtr(cha::PackageContext& pct, const std::vector<uint8_t>& stream) override { (void)pct; if (stream.size() != 8) throw cha::NativeException(); return new TestNativeData(static_cast<int>(*reinterpret_cast<const int32_t*>(stream.data()))); } }; static void testCommand(cha::Ct& ct) { auto& a0 = ct.at(0); if (!a0.isString()) throw cha::NativeException(); auto verb = a0.get<std::string>(); // NativeCallContext if (verb == "runtimeId") { ct.set(static_cast<std::underlying_type<cha::RuntimeId>::type>(ct.runtimeId())); return; } if (verb == "instanceId") { ct.set(static_cast<std::underlying_type<cha::InstanceId>::type>(ct.instanceId())); return; } if (verb == "hasSelf") { ct.set(ct.hasSelf()); return; } if (verb == "self") { auto* ptr = ct.self<TestNativeData>(); ct.set(ptr == nullptr ? 0 : ptr->value); return; } if (verb == "isConstructor") { ct.set(ct.isConstructor()); return; } if (verb == "name") { ct.set(ct.name()); return; } if (verb == "subName") { ct.set(ct.subName()); return; } if (verb == "size") { ct.set(ct.size()); return; } if (verb == "setSelf") { ct.setSelf(new TestNativeData(ct.at(1).get<int>())); return; } if (verb == "setNull") { ct.setNull(); return; } if (verb == "setBool") { ct.set(!ct.at(1).get<bool>()); return; } if (verb == "setInt") { ct.set(ct.at(1).get<int>() + 100); return; } if (verb == "setFloat") { ct.set(ct.at(1).get<double>() + 1000.0); return; } if (verb == "setString") { ct.set(ct.at(1).get<std::string>() + "hoge"); return; } if (verb == "setCString") { ct.set("hogehoge"); return; } if (verb == "pause") { auto& packageData = packageDataMap[ct.runtimeId()]; if (!packageData) packageData.reset(new PackageData()); if (packageData->event) throw cha::NativeException(); packageData->event.reset(ct.pause()); return; } if (verb == "resume") { auto& packageData = packageDataMap[ct.runtimeId()]; if (!packageData || !packageData->event) throw cha::NativeException(); auto event = std::move(packageData->event); event->unlock(); event.reset(); return; } if (verb == "log") { ct.log(ct[1].get<std::string>()); return; } // NativeReference auto index = (ct.size() >= 2 && ct.at(1).isInt() ? ct.at(1).get<size_t>() : SIZE_MAX); if (verb == "arg_isNull") { ct.set(ct[index].isNull()); return; } if (verb == "arg_isBool") { ct.set(ct[index].is<bool>()); return; } if (verb == "arg_isInt") { ct.set(ct[index].is<int>()); return; } if (verb == "arg_isFloat") { ct.set(ct[index].is<double>()); return; } if (verb == "arg_isString") { ct.set(ct[index].is<std::string>()); return; } if (verb == "arg_isArray") { ct.set(ct[index].isArray()); return; } if (verb == "arg_isDict") { ct.set(ct[index].isDict()); return; } if (verb == "arg_className") { ct.set(ct[index].className()); return; } if (verb == "arg_getBool") { ct.set(!ct[index].get<bool>()); return; } if (verb == "arg_getInt") { ct.set(ct[index].get<int>() + 200); return; } if (verb == "arg_getFloat") { ct.set(ct[index].get<double>() + 2000.0); return; } if (verb == "arg_getString") { ct.set(ct[index].get<std::string>() + "uhe"); return; } if (verb == "arg_size") { ct.set(ct[index].size()); return; } if (verb == "arg_keys") { auto& dest = ct.at(2); for (auto& key : ct[index].keys()) dest.add().set<std::string>(key); return; } if (verb == "arg_setPtr") { ct[index].setNative(new TestNativeData(ct.at(2).get<int>())); return; } if (verb == "arg_getPtr") { auto* ptr = ct[index].native<TestNativeData>(); ct.set(ptr == nullptr ? 0 : ptr->value + 500); return; } // Array if (ct.size() >= 3 && ct.at(2).isInt()) { auto arrayIndex = ct.at(2).get<size_t>(); if (verb == "arg_array_at_isNull") { ct.set(ct[index][arrayIndex].isNull()); return; } if (verb == "arg_array_at_isInt") { ct.set(ct[index][arrayIndex].is<int>()); return; } if (verb == "arg_array_at_isString") { ct.set(ct[index][arrayIndex].is<std::string>()); return; } if (verb == "arg_array_at_setNull") { ct[index][arrayIndex].setNull(); return; } if (verb == "arg_array_at_setBool") { ct[index][arrayIndex].set(!ct.at(3).get<bool>()); return; } if (verb == "arg_array_at_setInt") { ct[index][arrayIndex].set(ct.at(3).get<int>() + 300); return; } if (verb == "arg_array_at_setFloat") { ct[index][arrayIndex].set(ct.at(3).get<double>() + 3000.0); return; } if (verb == "arg_array_at_setString") { ct[index][arrayIndex].set(ct.at(3).get<std::string>() + "array"); return; } } // Dict if (ct.size() >= 3 && ct.at(2).isString()) { auto key = ct.at(2).get<std::string>(); if (verb == "arg_has") { ct.set(ct[index].has(key)); return; } if (verb == "arg_dict_at_isNull") { ct.set(ct[index][key].isNull()); return; } if (verb == "arg_dict_at_isInt") { ct.set(ct[index][key].is<int>()); return; } if (verb == "arg_dict_at_isString") { ct.set(ct[index][key].is<std::string>()); return; } if (verb == "arg_dict_at_setNull") { ct[index][key].setNull(); return; } if (verb == "arg_dict_at_setBool") { ct[index][key].set(!ct.at(3).get<bool>()); return; } if (verb == "arg_dict_at_setInt") { ct[index][key].set(ct.at(3).get<int>() + 400); return; } if (verb == "arg_dict_at_setFloat") { ct[index][key].set(ct.at(3).get<double>() + 4000.0); return; } if (verb == "arg_dict_at_setString") { ct[index][key].set(ct.at(3).get<std::string>() + "dict"); return; } } throw cha::NativeException(); } cha::PackageInfo getTestNativePackage() { std::vector<cha::Script> scripts = {{packageName, script}}; std::vector<cha::HandlerInfo> handlers = { {testCommand, "testCommand"}, {testCommand, "TestClass", "init"}, {testCommand, "TestClass", "init", "native"}, {testCommand, "TestClass", "method"} }; return {scripts, handlers, std::make_shared<TestPackageInterface>()}; }
30.723077
117
0.641087
chatra-lang
0e1d3646327ed0aa2d49fde59e57973785f10d99
3,194
hpp
C++
libfma/include/fma/core/DataBlock.hpp
BenjaminSchulte/fma
df2aa5b0644c75dd34a92defeff9beaa4a32ffea
[ "MIT" ]
14
2018-01-25T10:31:05.000Z
2022-02-19T13:08:11.000Z
libfma/include/fma/core/DataBlock.hpp
BenjaminSchulte/fma
df2aa5b0644c75dd34a92defeff9beaa4a32ffea
[ "MIT" ]
1
2020-12-24T10:10:28.000Z
2020-12-24T10:10:28.000Z
libfma/include/fma/core/DataBlock.hpp
BenjaminSchulte/fma
df2aa5b0644c75dd34a92defeff9beaa4a32ffea
[ "MIT" ]
null
null
null
#ifndef __FMA_CORE_DATABLOCK_H__ #define __FMA_CORE_DATABLOCK_H__ #include <fma/types/Class.hpp> #include <fma/types/RootModule.hpp> namespace FMA { class Project; namespace plugin { class MemoryBlock; } namespace core { class DataBlockClass : public types::Class { public: static types::ClassPtr create(const types::RootModulePtr &root, const types::ClassPtr &Class); static interpret::ResultPtr createInstance(const interpret::ContextPtr &context, const types::MacroPtr &macro); // PROTOTYPE static interpret::ResultPtr initialize(const interpret::ContextPtr &context, const interpret::GroupedParameterList &parameter); static interpret::ResultPtr op_call(const interpret::ContextPtr &context, const interpret::GroupedParameterList &parameter); static interpret::ResultPtr op_call_direct(const interpret::ContextPtr &context, const interpret::GroupedParameterList &parameter); static interpret::ResultPtr __current_block(const interpret::ContextPtr &context, const interpret::GroupedParameterList &parameter); static interpret::ResultPtr to_n(const interpret::ContextPtr &context, const interpret::GroupedParameterList &parameter); static interpret::ResultPtr to_b(const interpret::ContextPtr &context, const interpret::GroupedParameterList &parameter); static interpret::ResultPtr to_sym(const interpret::ContextPtr &context, const interpret::GroupedParameterList &parameter); static interpret::ResultPtr to_s(const interpret::ContextPtr &context, const interpret::GroupedParameterList &parameter); static interpret::ResultPtr override_located_at(const interpret::ContextPtr &context, const interpret::GroupedParameterList &parameter); static interpret::ResultPtr allow(const interpret::ContextPtr &context, const interpret::GroupedParameterList &parameter); static interpret::ResultPtr deny(const interpret::ContextPtr &context, const interpret::GroupedParameterList &parameter); static interpret::ResultPtr db(const interpret::ContextPtr &context, const interpret::GroupedParameterList &parameter); static interpret::ResultPtr dw(const interpret::ContextPtr &context, const interpret::GroupedParameterList &parameter); static interpret::ResultPtr dd(const interpret::ContextPtr &context, const interpret::GroupedParameterList &parameter); static interpret::ResultPtr create_label(const interpret::ContextPtr &context, const interpret::GroupedParameterList &parameter); static interpret::ResultPtr label(const interpret::ContextPtr &context, const interpret::GroupedParameterList &parameter); // ACCESS static plugin::MemoryBlock* memoryBlock(const interpret::ContextPtr &context); static plugin::MemoryBlock* memoryBlock(const Project *project, const types::TypePtr &context); protected: static interpret::ResultPtr writeData(const interpret::ContextPtr &context, const interpret::GroupedParameterList &parameter, uint8_t itemSize); static void writeDataRecursive(plugin::MemoryBlock *block, const interpret::ContextPtr &context, const types::TypePtr &value, uint8_t itemSize, uint32_t &maxBytes); static types::ObjectPtr convertToWriteableType(const interpret::ContextPtr &context, const types::TypePtr &value); }; } } #endif
60.264151
166
0.811522
BenjaminSchulte
0e1f905292f7435188b808d1a82b3b997c057dc6
108
cpp
C++
bridge/src/World.cpp
olekristensen/oresund
acfd604bda68e7fec0d07e14530eee546e497386
[ "MIT" ]
1
2018-09-04T11:41:38.000Z
2018-09-04T11:41:38.000Z
bridge/src/World.cpp
olekristensen/oresund
acfd604bda68e7fec0d07e14530eee546e497386
[ "MIT" ]
null
null
null
bridge/src/World.cpp
olekristensen/oresund
acfd604bda68e7fec0d07e14530eee546e497386
[ "MIT" ]
1
2021-04-18T05:41:35.000Z
2021-04-18T05:41:35.000Z
// // World.cpp // bridge // // Created by Johan Bichel Lindegaard on 8/30/18. // #include "World.hpp"
10.8
50
0.611111
olekristensen
0e1ff0b110f3c4d51d7cca6619a2f42ec2caff14
3,217
cpp
C++
lolCompiler/main.cpp
NeutralNoise/lol_script
632b6a56c9caa3d44e93e2006cedec5d6730e3e2
[ "MIT" ]
null
null
null
lolCompiler/main.cpp
NeutralNoise/lol_script
632b6a56c9caa3d44e93e2006cedec5d6730e3e2
[ "MIT" ]
null
null
null
lolCompiler/main.cpp
NeutralNoise/lol_script
632b6a56c9caa3d44e93e2006cedec5d6730e3e2
[ "MIT" ]
null
null
null
#include <iostream> #include <regex> #include <string> #include "Tokenizer.h" #include <vector> #include <fstream> #include "ParseTokens.h" #include "AST.h" //#include "ASTParser.h" // This isn't needed anymore i don't think. //Check for key words //TODO find a better place for this :D void CheckTokenKeywords(const std::vector<std::string> &key, std::vector<Token> *toks) { for (size_t i = 0; i < toks->size(); i++) { for (size_t k = 0; k < key.size(); k++) { if (strcmp(key[k].c_str(), toks->operator[](i).GetToken().c_str()) == 0) { toks->at(i).type = TokenType::KEYWORD; break; } } } } int main(int argc, char** argv) { Tokenizer tokens; ParseTokens parser; AST ast; //std::string fileName = "../../Documents/Examples/test2.lol"; #if defined(_WIN32) || defined(__CYGWIN__) #ifdef __CYGWIN__ std::string fileName = "../../Documents/Examples/test2.lol"; #else std::string fileName = "../Documents/Examples/test2.lol"; #endif #elif __linux__ std::string fileName = "../../Documents/Examples/test2.lol"; //std::string fileName = "Documents/Examples/test2.lol"; #endif std::ifstream file(fileName); std::vector<std::string> test; std::cout << "Loading File!\n"; if (file.is_open()) { std::cout << fileName << std::endl; std::string tmpLine; while (std::getline(file, tmpLine)) { test.push_back(tmpLine); } } else { std::cout << "Failed to load file: " << fileName << std::endl; } std::cout << "Generating Tokens!\n"; int current_pos = 0; int current_size = test.size(); std::vector<Token> tokenVec; for (size_t i = 0; i < test.size(); i++) { Token tok("", TokenType::ASSIGN); while (tok.GetType() != TokenType::NONE) { tok = tokens.nextToken(&test[i], (i + 1), current_pos); current_pos += tok.token.size(); if (tok.GetType() != TokenType::WHITE_SPACE && tok.GetType() != TokenType::NONE) { std::cout << tok.GetToken() << " LINE: " << tok.line << " POS: " << tok.linePos << std::endl; } if (tok.GetType() != TokenType::NONE) { tokenVec.push_back(tok); } } } std::vector<std::string> keyWords; //TODO load these from a file or something. keyWords.push_back("void"); keyWords.push_back("int"); keyWords.push_back("return"); CheckTokenKeywords(keyWords, &tokenVec); std::cout << "Generating AST!\n"; parser.Parse(tokenVec, &ast); std::cout << "TOKENS:\n"; ASTNode * root = ast.GetRoot(); root->PrintNodes(); std::cout << "Writing binary file!\n"; #if defined(_WIN32) || defined(__CYGWIN__) #ifdef __CYGWIN__ std::ofstream ofile("../../Documents/Examples/test2.lolc"); #else std::ofstream ofile("../Documents/Examples/test2.lolc"); #endif #elif __linux__ std::ofstream ofile("../../Documents/Examples/test2.lolc"); #endif //std::ofstream ofile; //ofile.open("Documents/Examples/test2.lolc"); if(!ofile.is_open()) { std::cout << "Failed to open output file\n"; return 0; } /* if (ofile.is_open()) { //WriteByte(ofile, 't'); unsigned char writeTest[12] = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '\n' }; WriteBytes(ofile, &writeTest[0], sizeof("Hello World\n") - 1); } */ ast.WriteAST(ofile); //Convert ast to binary std::cout << "Done!\n"; std::cin.get(); return 0; }
26.586777
97
0.635375
NeutralNoise
0e210411416f0bb81abc91ef24ce068d5e32737e
1,319
cpp
C++
OsakaEngine/Hiccups.cpp
osakahq/OsakaEngine
47dd0ec5b67a176c552441a25168ecb48b52e14b
[ "Zlib", "MIT" ]
2
2016-04-04T06:00:28.000Z
2016-04-18T15:39:38.000Z
OsakaEngine/Hiccups.cpp
osakahq/OsakaEngine
47dd0ec5b67a176c552441a25168ecb48b52e14b
[ "Zlib", "MIT" ]
null
null
null
OsakaEngine/Hiccups.cpp
osakahq/OsakaEngine
47dd0ec5b67a176c552441a25168ecb48b52e14b
[ "Zlib", "MIT" ]
null
null
null
#include "stdafx.h" #include "ConsoleColors.h" #include "Hiccups.h" namespace Osaka{ namespace RPGLib{ Hiccups::Hiccups(){ fills_in_array.reserve(15); } Hiccups::~Hiccups(){ } void Hiccups::Frame(const int frame_ms){ if( frame_ms < 0 ){ throw std::exception("[Hiccups] frame_ms cannot be lesser than 0."); } if( frame_ms >= HICCUPS_MAX_ARRAY ){ LOG("[Hiccups] Current frame is longer than HICCUPS_MAX_ARRAY < [%d]\n", frame_ms); return; } if( hiccups_array[frame_ms].quantity == 0 ){ fills_in_array.push_back(frame_ms); } hiccups_array[frame_ms].quantity++; } void Hiccups::EndSet(const float average_ms){ const float comparison = (average_ms * 0.7f)*2; bool printed = false; for(unsigned int i = 0; i < fills_in_array.size(); ++i){ if( fills_in_array[i] > 1 && fills_in_array[i] >= comparison ){ if( printed == false ){ std::cout << Debug::yellow; LOG("[Hiccups]"); std::cout << Debug::white; } printed = true; LOG(" %d[%dms], ", hiccups_array[fills_in_array[i]].quantity, fills_in_array[i]); } hiccups_array[fills_in_array[i]].quantity = 0; } fills_in_array.clear(); if( printed ){ LOG("Average was: %fms\n", average_ms); } } } }
26.38
88
0.603487
osakahq
0e211990ecc427fa3242626bd062c6a9149f0413
245
cpp
C++
exemplos/char2.cpp
wllynilson/flash-clip-2018-2
09d20d67042376c51aec54503456cb38e55ecca4
[ "MIT" ]
null
null
null
exemplos/char2.cpp
wllynilson/flash-clip-2018-2
09d20d67042376c51aec54503456cb38e55ecca4
[ "MIT" ]
1
2018-10-12T03:55:20.000Z
2018-10-12T03:55:20.000Z
exemplos/char2.cpp
wllynilson/flash-clip-2018-2
09d20d67042376c51aec54503456cb38e55ecca4
[ "MIT" ]
null
null
null
// char2.c #include <iostream> using namespace std; int main() { char caractere1 = 50; char caractere2 = 41; char caractere3 = caractere1 + caractere2; cout << "Caractere: " << caractere3 << endl; } //Output: [
16.333333
49
0.587755
wllynilson
0e244bb51b9aa99a8e211f806a73864929a4a10a
40,387
cpp
C++
Source/Urho3D/Navigation/DynamicNavigationMesh.cpp
TEAdvanced/Urho3D
c5c9c5ccccb0fee6283b2689fbb54155f017db72
[ "MIT" ]
null
null
null
Source/Urho3D/Navigation/DynamicNavigationMesh.cpp
TEAdvanced/Urho3D
c5c9c5ccccb0fee6283b2689fbb54155f017db72
[ "MIT" ]
null
null
null
Source/Urho3D/Navigation/DynamicNavigationMesh.cpp
TEAdvanced/Urho3D
c5c9c5ccccb0fee6283b2689fbb54155f017db72
[ "MIT" ]
1
2022-01-15T20:50:09.000Z
2022-01-15T20:50:09.000Z
// // Copyright (c) 2008-2022 the Urho3D project. // // 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 "../Precompiled.h" #include "../Core/Context.h" #include "../Core/Profiler.h" #include "../Graphics/DebugRenderer.h" #include "../IO/Log.h" #include "../IO/MemoryBuffer.h" #include "../Navigation/CrowdAgent.h" #include "../Navigation/DynamicNavigationMesh.h" #include "../Navigation/NavArea.h" #include "../Navigation/NavBuildData.h" #include "../Navigation/NavigationEvents.h" #include "../Navigation/Obstacle.h" #include "../Navigation/OffMeshConnection.h" #include "../Scene/Node.h" #include "../Scene/Scene.h" #include "../Scene/SceneEvents.h" #include <LZ4/lz4.h> #include <Detour/DetourNavMesh.h> #include <Detour/DetourNavMeshBuilder.h> #include <DetourTileCache/DetourTileCache.h> #include <DetourTileCache/DetourTileCacheBuilder.h> #include <Recast/Recast.h> // DebugNew is deliberately not used because the macro 'free' conflicts with DetourTileCache's LinearAllocator interface //#include "../DebugNew.h" static const unsigned TILECACHE_MAXLAYERS = 255; namespace Urho3D { extern const char* NAVIGATION_CATEGORY; static const int DEFAULT_MAX_OBSTACLES = 1024; static const int DEFAULT_MAX_LAYERS = 16; struct DynamicNavigationMesh::TileCacheData { unsigned char* data; int dataSize; }; struct TileCompressor : public dtTileCacheCompressor { int maxCompressedSize(const int bufferSize) override { return (int)(bufferSize * 1.05f); } dtStatus compress(const unsigned char* buffer, const int bufferSize, unsigned char* compressed, const int /*maxCompressedSize*/, int* compressedSize) override { *compressedSize = LZ4_compress_default((const char*)buffer, (char*)compressed, bufferSize, LZ4_compressBound(bufferSize)); return DT_SUCCESS; } dtStatus decompress(const unsigned char* compressed, const int compressedSize, unsigned char* buffer, const int maxBufferSize, int* bufferSize) override { *bufferSize = LZ4_decompress_safe((const char*)compressed, (char*)buffer, compressedSize, maxBufferSize); return *bufferSize < 0 ? DT_FAILURE : DT_SUCCESS; } }; struct MeshProcess : public dtTileCacheMeshProcess { DynamicNavigationMesh* owner_; PODVector<Vector3> offMeshVertices_; PODVector<float> offMeshRadii_; PODVector<unsigned short> offMeshFlags_; PODVector<unsigned char> offMeshAreas_; PODVector<unsigned char> offMeshDir_; inline explicit MeshProcess(DynamicNavigationMesh* owner) : owner_(owner) { } void process(struct dtNavMeshCreateParams* params, unsigned char* polyAreas, unsigned short* polyFlags) override { // Update poly flags from areas. // \todo Assignment of flags from areas? for (int i = 0; i < params->polyCount; ++i) { if (polyAreas[i] != RC_NULL_AREA) polyFlags[i] = RC_WALKABLE_AREA; } BoundingBox bounds; rcVcopy(&bounds.min_.x_, params->bmin); rcVcopy(&bounds.max_.x_, params->bmin); // collect off-mesh connections PODVector<OffMeshConnection*> offMeshConnections = owner_->CollectOffMeshConnections(bounds); if (offMeshConnections.Size() > 0) { if (offMeshConnections.Size() != offMeshRadii_.Size()) { Matrix3x4 inverse = owner_->GetNode()->GetWorldTransform().Inverse(); ClearConnectionData(); for (unsigned i = 0; i < offMeshConnections.Size(); ++i) { OffMeshConnection* connection = offMeshConnections[i]; Vector3 start = inverse * connection->GetNode()->GetWorldPosition(); Vector3 end = inverse * connection->GetEndPoint()->GetWorldPosition(); offMeshVertices_.Push(start); offMeshVertices_.Push(end); offMeshRadii_.Push(connection->GetRadius()); offMeshFlags_.Push((unsigned short)connection->GetMask()); offMeshAreas_.Push((unsigned char)connection->GetAreaID()); offMeshDir_.Push((unsigned char)(connection->IsBidirectional() ? DT_OFFMESH_CON_BIDIR : 0)); } } params->offMeshConCount = offMeshRadii_.Size(); params->offMeshConVerts = &offMeshVertices_[0].x_; params->offMeshConRad = &offMeshRadii_[0]; params->offMeshConFlags = &offMeshFlags_[0]; params->offMeshConAreas = &offMeshAreas_[0]; params->offMeshConDir = &offMeshDir_[0]; } } void ClearConnectionData() { offMeshVertices_.Clear(); offMeshRadii_.Clear(); offMeshFlags_.Clear(); offMeshAreas_.Clear(); offMeshDir_.Clear(); } }; // From the Detour/Recast Sample_TempObstacles.cpp struct LinearAllocator : public dtTileCacheAlloc { unsigned char* buffer; int capacity; int top; int high; explicit LinearAllocator(const int cap) : buffer(nullptr), capacity(0), top(0), high(0) { resize(cap); } ~LinearAllocator() override { dtFree(buffer); } void resize(const int cap) { if (buffer) dtFree(buffer); buffer = (unsigned char*)dtAlloc(cap, DT_ALLOC_PERM); capacity = cap; } void reset() override { high = Max(high, top); top = 0; } void* alloc(const size_t size) override { if (!buffer) return nullptr; if (top + size > capacity) return nullptr; unsigned char* mem = &buffer[top]; top += size; return mem; } void free(void*) override { } }; DynamicNavigationMesh::DynamicNavigationMesh(Context* context) : NavigationMesh(context), maxLayers_(DEFAULT_MAX_LAYERS) { // 64 is the largest tile-size that DetourTileCache will tolerate without silently failing tileSize_ = 64; partitionType_ = NAVMESH_PARTITION_MONOTONE; allocator_ = new LinearAllocator(32000); //32kb to start compressor_ = new TileCompressor(); meshProcessor_ = new MeshProcess(this); } DynamicNavigationMesh::~DynamicNavigationMesh() { ReleaseNavigationMesh(); } void DynamicNavigationMesh::RegisterObject(Context* context) { context->RegisterFactory<DynamicNavigationMesh>(NAVIGATION_CATEGORY); URHO3D_COPY_BASE_ATTRIBUTES(NavigationMesh); URHO3D_ACCESSOR_ATTRIBUTE("Max Obstacles", GetMaxObstacles, SetMaxObstacles, unsigned, DEFAULT_MAX_OBSTACLES, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Max Layers", GetMaxLayers, SetMaxLayers, unsigned, DEFAULT_MAX_LAYERS, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Draw Obstacles", GetDrawObstacles, SetDrawObstacles, bool, false, AM_DEFAULT); } bool DynamicNavigationMesh::Allocate(const BoundingBox& boundingBox, unsigned maxTiles) { // Release existing navigation data and zero the bounding box ReleaseNavigationMesh(); if (!node_) return false; if (!node_->GetWorldScale().Equals(Vector3::ONE)) URHO3D_LOGWARNING("Navigation mesh root node has scaling. Agent parameters may not work as intended"); boundingBox_ = boundingBox.Transformed(node_->GetWorldTransform().Inverse()); maxTiles = NextPowerOfTwo(maxTiles); // Calculate number of tiles int gridW = 0, gridH = 0; float tileEdgeLength = (float)tileSize_ * cellSize_; rcCalcGridSize(&boundingBox_.min_.x_, &boundingBox_.max_.x_, cellSize_, &gridW, &gridH); numTilesX_ = (gridW + tileSize_ - 1) / tileSize_; numTilesZ_ = (gridH + tileSize_ - 1) / tileSize_; // Calculate max number of polygons, 22 bits available to identify both tile & polygon within tile unsigned tileBits = LogBaseTwo(maxTiles); unsigned maxPolys = 1u << (22 - tileBits); dtNavMeshParams params; // NOLINT(hicpp-member-init) rcVcopy(params.orig, &boundingBox_.min_.x_); params.tileWidth = tileEdgeLength; params.tileHeight = tileEdgeLength; params.maxTiles = maxTiles; params.maxPolys = maxPolys; navMesh_ = dtAllocNavMesh(); if (!navMesh_) { URHO3D_LOGERROR("Could not allocate navigation mesh"); return false; } if (dtStatusFailed(navMesh_->init(&params))) { URHO3D_LOGERROR("Could not initialize navigation mesh"); ReleaseNavigationMesh(); return false; } dtTileCacheParams tileCacheParams; // NOLINT(hicpp-member-init) memset(&tileCacheParams, 0, sizeof(tileCacheParams)); rcVcopy(tileCacheParams.orig, &boundingBox_.min_.x_); tileCacheParams.ch = cellHeight_; tileCacheParams.cs = cellSize_; tileCacheParams.width = tileSize_; tileCacheParams.height = tileSize_; tileCacheParams.maxSimplificationError = edgeMaxError_; tileCacheParams.maxTiles = maxTiles * maxLayers_; tileCacheParams.maxObstacles = maxObstacles_; // Settings from NavigationMesh tileCacheParams.walkableClimb = agentMaxClimb_; tileCacheParams.walkableHeight = agentHeight_; tileCacheParams.walkableRadius = agentRadius_; tileCache_ = dtAllocTileCache(); if (!tileCache_) { URHO3D_LOGERROR("Could not allocate tile cache"); ReleaseNavigationMesh(); return false; } if (dtStatusFailed(tileCache_->init(&tileCacheParams, allocator_.Get(), compressor_.Get(), meshProcessor_.Get()))) { URHO3D_LOGERROR("Could not initialize tile cache"); ReleaseNavigationMesh(); return false; } URHO3D_LOGDEBUG("Allocated empty navigation mesh with max " + String(maxTiles) + " tiles"); // Scan for obstacles to insert into us PODVector<Node*> obstacles; GetScene()->GetChildrenWithComponent<Obstacle>(obstacles, true); for (unsigned i = 0; i < obstacles.Size(); ++i) { auto* obs = obstacles[i]->GetComponent<Obstacle>(); if (obs && obs->IsEnabledEffective()) AddObstacle(obs); } // Send a notification event to concerned parties that we've been fully rebuilt { using namespace NavigationMeshRebuilt; VariantMap& buildEventParams = GetContext()->GetEventDataMap(); buildEventParams[P_NODE] = node_; buildEventParams[P_MESH] = this; SendEvent(E_NAVIGATION_MESH_REBUILT, buildEventParams); } return true; } bool DynamicNavigationMesh::Build() { URHO3D_PROFILE(BuildNavigationMesh); // Release existing navigation data and zero the bounding box ReleaseNavigationMesh(); if (!node_) return false; if (!node_->GetWorldScale().Equals(Vector3::ONE)) URHO3D_LOGWARNING("Navigation mesh root node has scaling. Agent parameters may not work as intended"); Vector<NavigationGeometryInfo> geometryList; CollectGeometries(geometryList); if (geometryList.Empty()) return true; // Nothing to do // Build the combined bounding box for (unsigned i = 0; i < geometryList.Size(); ++i) boundingBox_.Merge(geometryList[i].boundingBox_); // Expand bounding box by padding boundingBox_.min_ -= padding_; boundingBox_.max_ += padding_; { URHO3D_PROFILE(BuildNavigationMesh); // Calculate number of tiles int gridW = 0, gridH = 0; float tileEdgeLength = (float)tileSize_ * cellSize_; rcCalcGridSize(&boundingBox_.min_.x_, &boundingBox_.max_.x_, cellSize_, &gridW, &gridH); numTilesX_ = (gridW + tileSize_ - 1) / tileSize_; numTilesZ_ = (gridH + tileSize_ - 1) / tileSize_; // Calculate max. number of tiles and polygons, 22 bits available to identify both tile & polygon within tile unsigned maxTiles = NextPowerOfTwo((unsigned)(numTilesX_ * numTilesZ_)) * maxLayers_; unsigned tileBits = LogBaseTwo(maxTiles); unsigned maxPolys = 1u << (22 - tileBits); dtNavMeshParams params; // NOLINT(hicpp-member-init) rcVcopy(params.orig, &boundingBox_.min_.x_); params.tileWidth = tileEdgeLength; params.tileHeight = tileEdgeLength; params.maxTiles = maxTiles; params.maxPolys = maxPolys; navMesh_ = dtAllocNavMesh(); if (!navMesh_) { URHO3D_LOGERROR("Could not allocate navigation mesh"); return false; } if (dtStatusFailed(navMesh_->init(&params))) { URHO3D_LOGERROR("Could not initialize navigation mesh"); ReleaseNavigationMesh(); return false; } dtTileCacheParams tileCacheParams; // NOLINT(hicpp-member-init) memset(&tileCacheParams, 0, sizeof(tileCacheParams)); rcVcopy(tileCacheParams.orig, &boundingBox_.min_.x_); tileCacheParams.ch = cellHeight_; tileCacheParams.cs = cellSize_; tileCacheParams.width = tileSize_; tileCacheParams.height = tileSize_; tileCacheParams.maxSimplificationError = edgeMaxError_; tileCacheParams.maxTiles = numTilesX_ * numTilesZ_ * maxLayers_; tileCacheParams.maxObstacles = maxObstacles_; // Settings from NavigationMesh tileCacheParams.walkableClimb = agentMaxClimb_; tileCacheParams.walkableHeight = agentHeight_; tileCacheParams.walkableRadius = agentRadius_; tileCache_ = dtAllocTileCache(); if (!tileCache_) { URHO3D_LOGERROR("Could not allocate tile cache"); ReleaseNavigationMesh(); return false; } if (dtStatusFailed(tileCache_->init(&tileCacheParams, allocator_.Get(), compressor_.Get(), meshProcessor_.Get()))) { URHO3D_LOGERROR("Could not initialize tile cache"); ReleaseNavigationMesh(); return false; } // Build each tile unsigned numTiles = 0; for (int z = 0; z < numTilesZ_; ++z) { for (int x = 0; x < numTilesX_; ++x) { TileCacheData tiles[TILECACHE_MAXLAYERS]; int layerCt = BuildTile(geometryList, x, z, tiles); for (int i = 0; i < layerCt; ++i) { dtCompressedTileRef tileRef; int status = tileCache_->addTile(tiles[i].data, tiles[i].dataSize, DT_COMPRESSEDTILE_FREE_DATA, &tileRef); if (dtStatusFailed((dtStatus)status)) { dtFree(tiles[i].data); tiles[i].data = nullptr; } } tileCache_->buildNavMeshTilesAt(x, z, navMesh_); ++numTiles; } } // For a full build it's necessary to update the nav mesh // not doing so will cause dependent components to crash, like CrowdManager tileCache_->update(0, navMesh_); URHO3D_LOGDEBUG("Built navigation mesh with " + String(numTiles) + " tiles"); // Send a notification event to concerned parties that we've been fully rebuilt { using namespace NavigationMeshRebuilt; VariantMap& buildEventParams = GetContext()->GetEventDataMap(); buildEventParams[P_NODE] = node_; buildEventParams[P_MESH] = this; SendEvent(E_NAVIGATION_MESH_REBUILT, buildEventParams); } // Scan for obstacles to insert into us PODVector<Node*> obstacles; GetScene()->GetChildrenWithComponent<Obstacle>(obstacles, true); for (unsigned i = 0; i < obstacles.Size(); ++i) { auto* obs = obstacles[i]->GetComponent<Obstacle>(); if (obs && obs->IsEnabledEffective()) AddObstacle(obs); } return true; } } bool DynamicNavigationMesh::Build(const BoundingBox& boundingBox) { URHO3D_PROFILE(BuildPartialNavigationMesh); if (!node_) return false; if (!navMesh_) { URHO3D_LOGERROR("Navigation mesh must first be built fully before it can be partially rebuilt"); return false; } if (!node_->GetWorldScale().Equals(Vector3::ONE)) URHO3D_LOGWARNING("Navigation mesh root node has scaling. Agent parameters may not work as intended"); BoundingBox localSpaceBox = boundingBox.Transformed(node_->GetWorldTransform().Inverse()); float tileEdgeLength = (float)tileSize_ * cellSize_; Vector<NavigationGeometryInfo> geometryList; CollectGeometries(geometryList); int sx = Clamp((int)((localSpaceBox.min_.x_ - boundingBox_.min_.x_) / tileEdgeLength), 0, numTilesX_ - 1); int sz = Clamp((int)((localSpaceBox.min_.z_ - boundingBox_.min_.z_) / tileEdgeLength), 0, numTilesZ_ - 1); int ex = Clamp((int)((localSpaceBox.max_.x_ - boundingBox_.min_.x_) / tileEdgeLength), 0, numTilesX_ - 1); int ez = Clamp((int)((localSpaceBox.max_.z_ - boundingBox_.min_.z_) / tileEdgeLength), 0, numTilesZ_ - 1); unsigned numTiles = BuildTiles(geometryList, IntVector2(sx, sz), IntVector2(ex, ez)); URHO3D_LOGDEBUG("Rebuilt " + String(numTiles) + " tiles of the navigation mesh"); return true; } bool DynamicNavigationMesh::Build(const IntVector2& from, const IntVector2& to) { URHO3D_PROFILE(BuildPartialNavigationMesh); if (!node_) return false; if (!navMesh_) { URHO3D_LOGERROR("Navigation mesh must first be built fully before it can be partially rebuilt"); return false; } if (!node_->GetWorldScale().Equals(Vector3::ONE)) URHO3D_LOGWARNING("Navigation mesh root node has scaling. Agent parameters may not work as intended"); Vector<NavigationGeometryInfo> geometryList; CollectGeometries(geometryList); unsigned numTiles = BuildTiles(geometryList, from, to); URHO3D_LOGDEBUG("Rebuilt " + String(numTiles) + " tiles of the navigation mesh"); return true; } PODVector<unsigned char> DynamicNavigationMesh::GetTileData(const IntVector2& tile) const { VectorBuffer ret; WriteTiles(ret, tile.x_, tile.y_); return ret.GetBuffer(); } bool DynamicNavigationMesh::IsObstacleInTile(Obstacle* obstacle, const IntVector2& tile) const { const BoundingBox tileBoundingBox = GetTileBoundingBox(tile); const Vector3 obstaclePosition = obstacle->GetNode()->GetWorldPosition(); return tileBoundingBox.DistanceToPoint(obstaclePosition) < obstacle->GetRadius(); } bool DynamicNavigationMesh::AddTile(const PODVector<unsigned char>& tileData) { MemoryBuffer buffer(tileData); return ReadTiles(buffer, false); } void DynamicNavigationMesh::RemoveTile(const IntVector2& tile) { if (!navMesh_) return; dtCompressedTileRef existing[TILECACHE_MAXLAYERS]; const int existingCt = tileCache_->getTilesAt(tile.x_, tile.y_, existing, maxLayers_); for (int i = 0; i < existingCt; ++i) { unsigned char* data = nullptr; if (!dtStatusFailed(tileCache_->removeTile(existing[i], &data, nullptr)) && data != nullptr) dtFree(data); } NavigationMesh::RemoveTile(tile); } void DynamicNavigationMesh::RemoveAllTiles() { int numTiles = tileCache_->getTileCount(); for (int i = 0; i < numTiles; ++i) { const dtCompressedTile* tile = tileCache_->getTile(i); assert(tile); if (tile->header) tileCache_->removeTile(tileCache_->getTileRef(tile), nullptr, nullptr); } NavigationMesh::RemoveAllTiles(); } void DynamicNavigationMesh::DrawDebugGeometry(DebugRenderer* debug, bool depthTest) { if (!debug || !navMesh_ || !node_) return; const Matrix3x4& worldTransform = node_->GetWorldTransform(); const dtNavMesh* navMesh = navMesh_; for (int j = 0; j < navMesh->getMaxTiles(); ++j) { const dtMeshTile* tile = navMesh->getTile(j); assert(tile); if (!tile->header) continue; for (int i = 0; i < tile->header->polyCount; ++i) { dtPoly* poly = tile->polys + i; for (unsigned j = 0; j < poly->vertCount; ++j) { debug->AddLine(worldTransform * *reinterpret_cast<const Vector3*>(&tile->verts[poly->verts[j] * 3]), worldTransform * *reinterpret_cast<const Vector3*>(&tile->verts[poly->verts[(j + 1) % poly->vertCount] * 3]), Color::YELLOW, depthTest); } } } Scene* scene = GetScene(); if (scene) { // Draw Obstacle components if (drawObstacles_) { PODVector<Node*> obstacles; scene->GetChildrenWithComponent<Obstacle>(obstacles, true); for (unsigned i = 0; i < obstacles.Size(); ++i) { auto* obstacle = obstacles[i]->GetComponent<Obstacle>(); if (obstacle && obstacle->IsEnabledEffective()) obstacle->DrawDebugGeometry(debug, depthTest); } } // Draw OffMeshConnection components if (drawOffMeshConnections_) { PODVector<Node*> connections; scene->GetChildrenWithComponent<OffMeshConnection>(connections, true); for (unsigned i = 0; i < connections.Size(); ++i) { auto* connection = connections[i]->GetComponent<OffMeshConnection>(); if (connection && connection->IsEnabledEffective()) connection->DrawDebugGeometry(debug, depthTest); } } // Draw NavArea components if (drawNavAreas_) { PODVector<Node*> areas; scene->GetChildrenWithComponent<NavArea>(areas, true); for (unsigned i = 0; i < areas.Size(); ++i) { auto* area = areas[i]->GetComponent<NavArea>(); if (area && area->IsEnabledEffective()) area->DrawDebugGeometry(debug, depthTest); } } } } void DynamicNavigationMesh::DrawDebugGeometry(bool depthTest) { Scene* scene = GetScene(); if (scene) { auto* debug = scene->GetComponent<DebugRenderer>(); if (debug) DrawDebugGeometry(debug, depthTest); } } void DynamicNavigationMesh::SetNavigationDataAttr(const PODVector<unsigned char>& value) { ReleaseNavigationMesh(); if (value.Empty()) return; MemoryBuffer buffer(value); boundingBox_ = buffer.ReadBoundingBox(); numTilesX_ = buffer.ReadInt(); numTilesZ_ = buffer.ReadInt(); dtNavMeshParams params; // NOLINT(hicpp-member-init) buffer.Read(&params, sizeof(dtNavMeshParams)); navMesh_ = dtAllocNavMesh(); if (!navMesh_) { URHO3D_LOGERROR("Could not allocate navigation mesh"); return; } if (dtStatusFailed(navMesh_->init(&params))) { URHO3D_LOGERROR("Could not initialize navigation mesh"); ReleaseNavigationMesh(); return; } dtTileCacheParams tcParams; // NOLINT(hicpp-member-init) buffer.Read(&tcParams, sizeof(tcParams)); tileCache_ = dtAllocTileCache(); if (!tileCache_) { URHO3D_LOGERROR("Could not allocate tile cache"); ReleaseNavigationMesh(); return; } if (dtStatusFailed(tileCache_->init(&tcParams, allocator_.Get(), compressor_.Get(), meshProcessor_.Get()))) { URHO3D_LOGERROR("Could not initialize tile cache"); ReleaseNavigationMesh(); return; } ReadTiles(buffer, true); // \todo Shall we send E_NAVIGATION_MESH_REBUILT here? } PODVector<unsigned char> DynamicNavigationMesh::GetNavigationDataAttr() const { VectorBuffer ret; if (navMesh_ && tileCache_) { ret.WriteBoundingBox(boundingBox_); ret.WriteInt(numTilesX_); ret.WriteInt(numTilesZ_); const dtNavMeshParams* params = navMesh_->getParams(); ret.Write(params, sizeof(dtNavMeshParams)); const dtTileCacheParams* tcParams = tileCache_->getParams(); ret.Write(tcParams, sizeof(dtTileCacheParams)); for (int z = 0; z < numTilesZ_; ++z) for (int x = 0; x < numTilesX_; ++x) WriteTiles(ret, x, z); } return ret.GetBuffer(); } void DynamicNavigationMesh::SetMaxLayers(unsigned maxLayers) { // Set 3 as a minimum due to the tendency of layers to be constructed inside the hollow space of stacked objects // That behavior is unlikely to be expected by the end user maxLayers_ = Max(3U, Min(maxLayers, TILECACHE_MAXLAYERS)); } void DynamicNavigationMesh::WriteTiles(Serializer& dest, int x, int z) const { dtCompressedTileRef tiles[TILECACHE_MAXLAYERS]; const int ct = tileCache_->getTilesAt(x, z, tiles, maxLayers_); for (int i = 0; i < ct; ++i) { const dtCompressedTile* tile = tileCache_->getTileByRef(tiles[i]); if (!tile || !tile->header || !tile->dataSize) continue; // Don't write "void-space" tiles // The header conveniently has the majority of the information required dest.Write(tile->header, sizeof(dtTileCacheLayerHeader)); dest.WriteInt(tile->dataSize); dest.Write(tile->data, (unsigned)tile->dataSize); } } bool DynamicNavigationMesh::ReadTiles(Deserializer& source, bool silent) { tileQueue_.Clear(); while (!source.IsEof()) { dtTileCacheLayerHeader header; // NOLINT(hicpp-member-init) source.Read(&header, sizeof(dtTileCacheLayerHeader)); const int dataSize = source.ReadInt(); auto* data = (unsigned char*)dtAlloc(dataSize, DT_ALLOC_PERM); if (!data) { URHO3D_LOGERROR("Could not allocate data for navigation mesh tile"); return false; } source.Read(data, (unsigned)dataSize); if (dtStatusFailed(tileCache_->addTile(data, dataSize, DT_TILE_FREE_DATA, nullptr))) { URHO3D_LOGERROR("Failed to add tile"); dtFree(data); return false; } const IntVector2 tileIdx = IntVector2(header.tx, header.ty); if (tileQueue_.Empty() || tileQueue_.Back() != tileIdx) tileQueue_.Push(tileIdx); } for (unsigned i = 0; i < tileQueue_.Size(); ++i) tileCache_->buildNavMeshTilesAt(tileQueue_[i].x_, tileQueue_[i].y_, navMesh_); tileCache_->update(0, navMesh_); // Send event if (!silent) { for (unsigned i = 0; i < tileQueue_.Size(); ++i) { using namespace NavigationTileAdded; VariantMap& eventData = GetContext()->GetEventDataMap(); eventData[P_NODE] = GetNode(); eventData[P_MESH] = this; eventData[P_TILE] = tileQueue_[i]; SendEvent(E_NAVIGATION_TILE_ADDED, eventData); } } return true; } int DynamicNavigationMesh::BuildTile(Vector<NavigationGeometryInfo>& geometryList, int x, int z, TileCacheData* tiles) { URHO3D_PROFILE(BuildNavigationMeshTile); tileCache_->removeTile(navMesh_->getTileRefAt(x, z, 0), nullptr, nullptr); const BoundingBox tileBoundingBox = GetTileBoundingBox(IntVector2(x, z)); DynamicNavBuildData build(allocator_.Get()); rcConfig cfg; // NOLINT(hicpp-member-init) memset(&cfg, 0, sizeof cfg); cfg.cs = cellSize_; cfg.ch = cellHeight_; cfg.walkableSlopeAngle = agentMaxSlope_; cfg.walkableHeight = (int)ceilf(agentHeight_ / cfg.ch); cfg.walkableClimb = (int)floorf(agentMaxClimb_ / cfg.ch); cfg.walkableRadius = (int)ceilf(agentRadius_ / cfg.cs); cfg.maxEdgeLen = (int)(edgeMaxLength_ / cellSize_); cfg.maxSimplificationError = edgeMaxError_; cfg.minRegionArea = (int)sqrtf(regionMinSize_); cfg.mergeRegionArea = (int)sqrtf(regionMergeSize_); cfg.maxVertsPerPoly = 6; cfg.tileSize = tileSize_; cfg.borderSize = cfg.walkableRadius + 3; // Add padding cfg.width = cfg.tileSize + cfg.borderSize * 2; cfg.height = cfg.tileSize + cfg.borderSize * 2; cfg.detailSampleDist = detailSampleDistance_ < 0.9f ? 0.0f : cellSize_ * detailSampleDistance_; cfg.detailSampleMaxError = cellHeight_ * detailSampleMaxError_; rcVcopy(cfg.bmin, &tileBoundingBox.min_.x_); rcVcopy(cfg.bmax, &tileBoundingBox.max_.x_); cfg.bmin[0] -= cfg.borderSize * cfg.cs; cfg.bmin[2] -= cfg.borderSize * cfg.cs; cfg.bmax[0] += cfg.borderSize * cfg.cs; cfg.bmax[2] += cfg.borderSize * cfg.cs; BoundingBox expandedBox(*reinterpret_cast<Vector3*>(cfg.bmin), *reinterpret_cast<Vector3*>(cfg.bmax)); GetTileGeometry(&build, geometryList, expandedBox); if (build.vertices_.Empty() || build.indices_.Empty()) return 0; // Nothing to do build.heightField_ = rcAllocHeightfield(); if (!build.heightField_) { URHO3D_LOGERROR("Could not allocate heightfield"); return 0; } if (!rcCreateHeightfield(build.ctx_, *build.heightField_, cfg.width, cfg.height, cfg.bmin, cfg.bmax, cfg.cs, cfg.ch)) { URHO3D_LOGERROR("Could not create heightfield"); return 0; } unsigned numTriangles = build.indices_.Size() / 3; SharedArrayPtr<unsigned char> triAreas(new unsigned char[numTriangles]); memset(triAreas.Get(), 0, numTriangles); rcMarkWalkableTriangles(build.ctx_, cfg.walkableSlopeAngle, &build.vertices_[0].x_, build.vertices_.Size(), &build.indices_[0], numTriangles, triAreas.Get()); rcRasterizeTriangles(build.ctx_, &build.vertices_[0].x_, build.vertices_.Size(), &build.indices_[0], triAreas.Get(), numTriangles, *build.heightField_, cfg.walkableClimb); rcFilterLowHangingWalkableObstacles(build.ctx_, cfg.walkableClimb, *build.heightField_); rcFilterLedgeSpans(build.ctx_, cfg.walkableHeight, cfg.walkableClimb, *build.heightField_); rcFilterWalkableLowHeightSpans(build.ctx_, cfg.walkableHeight, *build.heightField_); build.compactHeightField_ = rcAllocCompactHeightfield(); if (!build.compactHeightField_) { URHO3D_LOGERROR("Could not allocate create compact heightfield"); return 0; } if (!rcBuildCompactHeightfield(build.ctx_, cfg.walkableHeight, cfg.walkableClimb, *build.heightField_, *build.compactHeightField_)) { URHO3D_LOGERROR("Could not build compact heightfield"); return 0; } if (!rcErodeWalkableArea(build.ctx_, cfg.walkableRadius, *build.compactHeightField_)) { URHO3D_LOGERROR("Could not erode compact heightfield"); return 0; } // area volumes for (unsigned i = 0; i < build.navAreas_.Size(); ++i) rcMarkBoxArea(build.ctx_, &build.navAreas_[i].bounds_.min_.x_, &build.navAreas_[i].bounds_.max_.x_, build.navAreas_[i].areaID_, *build.compactHeightField_); if (this->partitionType_ == NAVMESH_PARTITION_WATERSHED) { if (!rcBuildDistanceField(build.ctx_, *build.compactHeightField_)) { URHO3D_LOGERROR("Could not build distance field"); return 0; } if (!rcBuildRegions(build.ctx_, *build.compactHeightField_, cfg.borderSize, cfg.minRegionArea, cfg.mergeRegionArea)) { URHO3D_LOGERROR("Could not build regions"); return 0; } } else { if (!rcBuildRegionsMonotone(build.ctx_, *build.compactHeightField_, cfg.borderSize, cfg.minRegionArea, cfg.mergeRegionArea)) { URHO3D_LOGERROR("Could not build monotone regions"); return 0; } } build.heightFieldLayers_ = rcAllocHeightfieldLayerSet(); if (!build.heightFieldLayers_) { URHO3D_LOGERROR("Could not allocate height field layer set"); return 0; } if (!rcBuildHeightfieldLayers(build.ctx_, *build.compactHeightField_, cfg.borderSize, cfg.walkableHeight, *build.heightFieldLayers_)) { URHO3D_LOGERROR("Could not build height field layers"); return 0; } int retCt = 0; for (int i = 0; i < build.heightFieldLayers_->nlayers; ++i) { dtTileCacheLayerHeader header; // NOLINT(hicpp-member-init) header.magic = DT_TILECACHE_MAGIC; header.version = DT_TILECACHE_VERSION; header.tx = x; header.ty = z; header.tlayer = i; rcHeightfieldLayer* layer = &build.heightFieldLayers_->layers[i]; // Tile info. rcVcopy(header.bmin, layer->bmin); rcVcopy(header.bmax, layer->bmax); header.width = (unsigned char)layer->width; header.height = (unsigned char)layer->height; header.minx = (unsigned char)layer->minx; header.maxx = (unsigned char)layer->maxx; header.miny = (unsigned char)layer->miny; header.maxy = (unsigned char)layer->maxy; header.hmin = (unsigned short)layer->hmin; header.hmax = (unsigned short)layer->hmax; if (dtStatusFailed( dtBuildTileCacheLayer(compressor_.Get()/*compressor*/, &header, layer->heights, layer->areas/*areas*/, layer->cons, &(tiles[retCt].data), &tiles[retCt].dataSize))) { URHO3D_LOGERROR("Failed to build tile cache layers"); return 0; } else ++retCt; } // Send a notification of the rebuild of this tile to anyone interested { using namespace NavigationAreaRebuilt; VariantMap& eventData = GetContext()->GetEventDataMap(); eventData[P_NODE] = GetNode(); eventData[P_MESH] = this; eventData[P_BOUNDSMIN] = Variant(tileBoundingBox.min_); eventData[P_BOUNDSMAX] = Variant(tileBoundingBox.max_); SendEvent(E_NAVIGATION_AREA_REBUILT, eventData); } return retCt; } unsigned DynamicNavigationMesh::BuildTiles(Vector<NavigationGeometryInfo>& geometryList, const IntVector2& from, const IntVector2& to) { unsigned numTiles = 0; for (int z = from.y_; z <= to.y_; ++z) { for (int x = from.x_; x <= to.x_; ++x) { dtCompressedTileRef existing[TILECACHE_MAXLAYERS]; const int existingCt = tileCache_->getTilesAt(x, z, existing, maxLayers_); for (int i = 0; i < existingCt; ++i) { unsigned char* data = nullptr; if (!dtStatusFailed(tileCache_->removeTile(existing[i], &data, nullptr)) && data != nullptr) dtFree(data); } TileCacheData tiles[TILECACHE_MAXLAYERS]; int layerCt = BuildTile(geometryList, x, z, tiles); for (int i = 0; i < layerCt; ++i) { dtCompressedTileRef tileRef; int status = tileCache_->addTile(tiles[i].data, tiles[i].dataSize, DT_COMPRESSEDTILE_FREE_DATA, &tileRef); if (dtStatusFailed((dtStatus)status)) { dtFree(tiles[i].data); tiles[i].data = nullptr; } else { tileCache_->buildNavMeshTile(tileRef, navMesh_); ++numTiles; } } } } return numTiles; } PODVector<OffMeshConnection*> DynamicNavigationMesh::CollectOffMeshConnections(const BoundingBox& bounds) { PODVector<OffMeshConnection*> connections; node_->GetComponents<OffMeshConnection>(connections, true); for (unsigned i = 0; i < connections.Size(); ++i) { OffMeshConnection* connection = connections[i]; if (!(connection->IsEnabledEffective() && connection->GetEndPoint())) { // discard this connection connections.Erase(i); --i; } } return connections; } void DynamicNavigationMesh::ReleaseNavigationMesh() { NavigationMesh::ReleaseNavigationMesh(); ReleaseTileCache(); } void DynamicNavigationMesh::ReleaseTileCache() { dtFreeTileCache(tileCache_); tileCache_ = nullptr; } void DynamicNavigationMesh::OnSceneSet(Scene* scene) { // Subscribe to the scene subsystem update, which will trigger the tile cache to update the nav mesh if (scene) SubscribeToEvent(scene, E_SCENESUBSYSTEMUPDATE, URHO3D_HANDLER(DynamicNavigationMesh, HandleSceneSubsystemUpdate)); else UnsubscribeFromEvent(E_SCENESUBSYSTEMUPDATE); } void DynamicNavigationMesh::AddObstacle(Obstacle* obstacle, bool silent) { if (tileCache_) { float pos[3]; Vector3 obsPos = obstacle->GetNode()->GetWorldPosition(); rcVcopy(pos, &obsPos.x_); dtObstacleRef refHolder; // Because dtTileCache doesn't process obstacle requests while updating tiles // it's necessary update until sufficient request space is available while (tileCache_->isObstacleQueueFull()) tileCache_->update(1, navMesh_); if (dtStatusFailed(tileCache_->addObstacle(pos, obstacle->GetRadius(), obstacle->GetHeight(), &refHolder))) { URHO3D_LOGERROR("Failed to add obstacle"); return; } obstacle->obstacleId_ = refHolder; assert(refHolder > 0); if (!silent) { using namespace NavigationObstacleAdded; VariantMap& eventData = GetContext()->GetEventDataMap(); eventData[P_NODE] = obstacle->GetNode(); eventData[P_OBSTACLE] = obstacle; eventData[P_POSITION] = obstacle->GetNode()->GetWorldPosition(); eventData[P_RADIUS] = obstacle->GetRadius(); eventData[P_HEIGHT] = obstacle->GetHeight(); SendEvent(E_NAVIGATION_OBSTACLE_ADDED, eventData); } } } void DynamicNavigationMesh::ObstacleChanged(Obstacle* obstacle) { if (tileCache_) { RemoveObstacle(obstacle, true); AddObstacle(obstacle, true); } } void DynamicNavigationMesh::RemoveObstacle(Obstacle* obstacle, bool silent) { if (tileCache_ && obstacle->obstacleId_ > 0) { // Because dtTileCache doesn't process obstacle requests while updating tiles // it's necessary update until sufficient request space is available while (tileCache_->isObstacleQueueFull()) tileCache_->update(1, navMesh_); if (dtStatusFailed(tileCache_->removeObstacle(obstacle->obstacleId_))) { URHO3D_LOGERROR("Failed to remove obstacle"); return; } obstacle->obstacleId_ = 0; // Require a node in order to send an event if (!silent && obstacle->GetNode()) { using namespace NavigationObstacleRemoved; VariantMap& eventData = GetContext()->GetEventDataMap(); eventData[P_NODE] = obstacle->GetNode(); eventData[P_OBSTACLE] = obstacle; eventData[P_POSITION] = obstacle->GetNode()->GetWorldPosition(); eventData[P_RADIUS] = obstacle->GetRadius(); eventData[P_HEIGHT] = obstacle->GetHeight(); SendEvent(E_NAVIGATION_OBSTACLE_REMOVED, eventData); } } } void DynamicNavigationMesh::HandleSceneSubsystemUpdate(StringHash eventType, VariantMap& eventData) { using namespace SceneSubsystemUpdate; if (tileCache_ && navMesh_ && IsEnabledEffective()) tileCache_->update(eventData[P_TIMESTEP].GetFloat(), navMesh_); } }
34.756454
134
0.646297
TEAdvanced
0e26bb1dcfd0676efcb7c02e271f663eb3b5b48f
673
cpp
C++
livro/cap_02 (finalizado)/10_limite_de_credito.cpp
sueyvid/Atividade_de_programacao_cpp
691941fc94125eddd4e5466862d5a1fe04dfb520
[ "MIT" ]
null
null
null
livro/cap_02 (finalizado)/10_limite_de_credito.cpp
sueyvid/Atividade_de_programacao_cpp
691941fc94125eddd4e5466862d5a1fe04dfb520
[ "MIT" ]
null
null
null
livro/cap_02 (finalizado)/10_limite_de_credito.cpp
sueyvid/Atividade_de_programacao_cpp
691941fc94125eddd4e5466862d5a1fe04dfb520
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { float saldo_inicial, debitos, creditos, limite_credito_autorizado; saldo_inicial = 500; debitos = 100; creditos = 200; limite_credito_autorizado = saldo_inicial - debitos - creditos; cout << "Numero da conta: xxx-xxx-xxx" << endl << "Saldo no inicio do mes: " << saldo_inicial << " conto" << endl << "Total de debitos no mes: " << debitos << " conto" << endl << "Total de creditos aplicados à conta no mes: " << creditos << " conto" << endl << "Limite de credita autorizado: " << limite_credito_autorizado << " conto" << endl; return 0; }
32.047619
94
0.609212
sueyvid
0e273118fc1c494940d04d75b856e80c26c786d6
14,540
cpp
C++
src/core/processors/canvasprocessor.cpp
guillempd/inviwo
4567a9750a1efc3a0416ceb0bcb25ba0e96620a1
[ "BSD-2-Clause" ]
349
2015-01-30T09:21:52.000Z
2022-03-25T03:10:02.000Z
src/core/processors/canvasprocessor.cpp
guillempd/inviwo
4567a9750a1efc3a0416ceb0bcb25ba0e96620a1
[ "BSD-2-Clause" ]
641
2015-09-23T08:54:06.000Z
2022-03-23T09:50:55.000Z
src/core/processors/canvasprocessor.cpp
guillempd/inviwo
4567a9750a1efc3a0416ceb0bcb25ba0e96620a1
[ "BSD-2-Clause" ]
124
2015-02-27T23:45:02.000Z
2022-02-21T09:37:14.000Z
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2012-2021 Inviwo Foundation * 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. * *********************************************************************************/ #include <inviwo/core/common/inviwoapplication.h> #include <inviwo/core/processors/canvasprocessor.h> #include <inviwo/core/common/inviwoapplication.h> #include <inviwo/core/util/canvas.h> #include <inviwo/core/util/datetime.h> #include <inviwo/core/util/stringconversion.h> #include <inviwo/core/processors/canvasprocessorwidget.h> #include <inviwo/core/processors/processorwidget.h> #include <inviwo/core/io/datawriterfactory.h> #include <inviwo/core/datastructures/image/layer.h> #include <inviwo/core/util/filesystem.h> #include <inviwo/core/util/fileextension.h> #include <inviwo/core/util/filedialog.h> #include <inviwo/core/util/dialogfactory.h> #include <inviwo/core/io/imagewriterutil.h> #include <inviwo/core/network/networklock.h> namespace inviwo { CanvasProcessor::CanvasProcessor(InviwoApplication* app) : Processor() , inport_("inport") , inputSize_("inputSize", "Input Dimension Parameters") , dimensions_("dimensions", "Canvas Size", size2_t(256, 256), size2_t(1, 1), size2_t(10000, 10000), size2_t(1, 1), InvalidationLevel::Valid) , enableCustomInputDimensions_("enableCustomInputDimensions", "Separate Image Size", false, InvalidationLevel::Valid) , customInputDimensions_("customInputDimensions", "Image Size", size2_t(256, 256), size2_t(1, 1), size2_t(10000, 10000), size2_t(1, 1), InvalidationLevel::Valid) , keepAspectRatio_("keepAspectRatio", "Lock Aspect Ratio", true, InvalidationLevel::Valid) , aspectRatioScaling_("aspectRatioScaling", "Image Scale", 1.f, 0.1f, 4.f, 0.01f, InvalidationLevel::Valid) , position_("position", "Canvas Position", ivec2(128, 128), ivec2(std::numeric_limits<int>::lowest()), ivec2(std::numeric_limits<int>::max()), ivec2(1, 1), InvalidationLevel::Valid, PropertySemantics::Text) , visibleLayer_("visibleLayer", "Visible Layer", {{"color", "Color layer", LayerType::Color}, {"depth", "Depth layer", LayerType::Depth}, {"picking", "Picking layer", LayerType::Picking}}, 0) , colorLayer_("colorLayer_", "Color Layer ID", 0, 0, 0) , imageTypeExt_( "fileExt", "Image Type", [app]() { const auto exts = app->getDataWriterFactory()->getExtensionsForType<Layer>(); std::vector<OptionPropertyOption<FileExtension>> res; std::transform(exts.begin(), exts.end(), std::back_inserter(res), [](auto& ext) { return OptionPropertyOption<FileExtension>{ext.toString(), ext.toString(), ext}; }); return res; }(), [app]() { const auto exts = app->getDataWriterFactory()->getExtensionsForType<Layer>(); const auto it = std::find_if(exts.begin(), exts.end(), [](auto& ext) { return ext.extension_ == "png"; }); return it == exts.end() ? 0 : std::distance(exts.begin(), it); }()) , saveLayerDirectory_("layerDir", "Output Directory", "", "image") , saveLayerButton_( "saveLayer", "Save Image Layer", [this]() { saveImageLayer(); }, InvalidationLevel::Valid) , saveLayerToFileButton_( "saveLayerToFile", "Save Image Layer to File...", [this]() { if (auto layer = getVisibleLayer()) { util::saveLayer(*layer); } else { LogError("Could not find visible layer"); } }, InvalidationLevel::Valid) , fullScreen_("fullscreen", "Toggle Full Screen", false) , fullScreenEvent_( "fullscreenEvent", "FullScreen", [this](Event*) { fullScreen_.set(!fullScreen_); }, IvwKey::F, KeyState::Press, KeyModifier::Shift) , saveLayerEvent_( "saveLayerEvent", "Save Image Layer", [this](Event*) { saveImageLayer(); }, IvwKey::Undefined, KeyState::Press) , allowContextMenu_("allowContextMenu", "Allow Context Menu", true) , evaluateWhenHidden_("evaluateWhenHidden", "Evaluate When Hidden", false) , previousImageSize_(customInputDimensions_) , widgetMetaData_{ createMetaData<ProcessorWidgetMetaData>(ProcessorWidgetMetaData::CLASS_IDENTIFIER)} { addPort(inport_); widgetMetaData_->addObserver(this); setEvaluateWhenHidden(false); dimensions_.setSerializationMode(PropertySerializationMode::None); dimensions_.onChange([this]() { widgetMetaData_->setDimensions(dimensions_.get()); }); position_.onChange([this]() { widgetMetaData_->setPosition(position_.get()); }); fullScreen_.onChange([this]() { widgetMetaData_->setFullScreen(fullScreen_.get()); }); enableCustomInputDimensions_.onChange([this]() { sizeChanged(); }); customInputDimensions_.onChange([this]() { sizeChanged(); }); keepAspectRatio_.onChange([this]() { sizeChanged(); }); aspectRatioScaling_.onChange([this]() { sizeChanged(); }); keepAspectRatio_.setVisible(false); customInputDimensions_.setVisible(false); aspectRatioScaling_.setVisible(false); inputSize_.addProperties(dimensions_, enableCustomInputDimensions_, customInputDimensions_, keepAspectRatio_, aspectRatioScaling_); colorLayer_.setVisible(false); colorLayer_.setSerializationMode(PropertySerializationMode::All); visibleLayer_.onChange([&]() { if (inport_.hasData()) { auto layers = inport_.getData()->getNumberOfColorLayers(); colorLayer_.setVisible(layers > 1 && visibleLayer_.get() == LayerType::Color); } }); evaluateWhenHidden_.onChange([this]() { setEvaluateWhenHidden(evaluateWhenHidden_.get()); }); imageTypeExt_.setSerializationMode(PropertySerializationMode::None); addProperties(inputSize_, position_, visibleLayer_, colorLayer_, saveLayerDirectory_, imageTypeExt_, saveLayerButton_, saveLayerToFileButton_, fullScreen_, fullScreenEvent_, saveLayerEvent_, allowContextMenu_, evaluateWhenHidden_); inport_.onChange([&]() { int layers = static_cast<int>(inport_.getData()->getNumberOfColorLayers()); colorLayer_.setVisible(layers > 1 && visibleLayer_.get() == LayerType::Color); colorLayer_.setMaxValue(layers - 1); }); inport_.onConnect([&]() { sizeChanged(); }); setAllPropertiesCurrentStateAsDefault(); } CanvasProcessor::~CanvasProcessor() { if (processorWidget_) { processorWidget_->setVisible(false); getCanvas()->setEventPropagator(nullptr); } } void CanvasProcessor::setProcessorWidget(std::unique_ptr<ProcessorWidget> processorWidget) { if (processorWidget && !dynamic_cast<CanvasProcessorWidget*>(processorWidget.get())) { throw Exception("Expected CanvasProcessorWidget in CanvasProcessor::setProcessorWidget", IVW_CONTEXT); } Processor::setProcessorWidget(std::move(processorWidget)); isSink_.update(); isReady_.update(); } void CanvasProcessor::accept(NetworkVisitor& visitor) { if (visitor.visit(*this)) { for (auto* elem : properties_) { elem->accept(visitor); } } } void CanvasProcessor::onProcessorWidgetPositionChange(ProcessorWidgetMetaData*) { if (widgetMetaData_->getPosition() != position_.get()) { Property::OnChangeBlocker blocker{position_}; position_.set(widgetMetaData_->getPosition()); } } void CanvasProcessor::onProcessorWidgetDimensionChange(ProcessorWidgetMetaData*) { if (widgetMetaData_->getDimensions() != dimensions_.get()) { Property::OnChangeBlocker blocker{dimensions_}; dimensions_.set(widgetMetaData_->getDimensions()); } } void CanvasProcessor::onProcessorWidgetVisibilityChange(ProcessorWidgetMetaData*) { isSink_.update(); isReady_.update(); invalidate(InvalidationLevel::InvalidOutput); } void CanvasProcessor::setCanvasSize(size2_t dim) { NetworkLock lock(this); dimensions_.set(dim); sizeChanged(); } size2_t CanvasProcessor::getCanvasSize() const { return dimensions_; } bool CanvasProcessor::getUseCustomDimensions() const { return enableCustomInputDimensions_; } size2_t CanvasProcessor::getCustomDimensions() const { return customInputDimensions_; } void CanvasProcessor::sizeChanged() { NetworkLock lock(this); customInputDimensions_.setVisible(enableCustomInputDimensions_); customInputDimensions_.setReadOnly(keepAspectRatio_); keepAspectRatio_.setVisible(enableCustomInputDimensions_); aspectRatioScaling_.setVisible(enableCustomInputDimensions_ && keepAspectRatio_); if (keepAspectRatio_) { Property::OnChangeBlocker block{customInputDimensions_}; // avoid recursive onChange customInputDimensions_.set(calcScaledSize(dimensions_, aspectRatioScaling_)); } ResizeEvent resizeEvent{enableCustomInputDimensions_ ? customInputDimensions_ : dimensions_, previousImageSize_}; previousImageSize_ = resizeEvent.size(); inputSize_.invalidate(InvalidationLevel::Valid, &customInputDimensions_); inport_.propagateEvent(&resizeEvent); } size2_t CanvasProcessor::calcScaledSize(size2_t size, float scale) { const int maxDim = size.x >= size.y ? 0 : 1; const int minDim = size.x >= size.y ? 1 : 0; const double ratio = static_cast<double>(size[minDim]) / static_cast<double>(size[maxDim]); size[maxDim] = static_cast<int>(static_cast<double>(size[maxDim]) * scale); size[minDim] = static_cast<int>(static_cast<double>(size[maxDim]) * ratio); return size; } void CanvasProcessor::saveImageLayer() { if (saveLayerDirectory_.get().empty()) saveLayerDirectory_.requestFile(); std::string snapshotPath(saveLayerDirectory_.get() + "/" + toLower(getIdentifier()) + "-" + currentDateTime() + "." + imageTypeExt_->extension_); saveImageLayer(snapshotPath, imageTypeExt_); } void CanvasProcessor::saveImageLayer(std::string_view snapshotPath, const FileExtension& extension) { if (auto layer = getVisibleLayer()) { util::saveLayer(*layer, snapshotPath, extension); } else { LogError("Could not find visible layer"); } } const Layer* CanvasProcessor::getVisibleLayer() const { if (auto image = inport_.getData()) { return image->getLayer(visibleLayer_, colorLayer_); } else { return nullptr; } } std::shared_ptr<const Image> CanvasProcessor::getImage() const { return inport_.getData(); } Canvas* CanvasProcessor::getCanvas() const { if (auto canvasWidget = static_cast<CanvasProcessorWidget*>(processorWidget_.get())) { return canvasWidget->getCanvas(); } else { return nullptr; } } void CanvasProcessor::process() { if (processorWidget_->isVisible()) { if (auto c = getCanvas()) { c->render(inport_.getData(), visibleLayer_, colorLayer_); } } } void CanvasProcessor::doIfNotReady() { if (processorWidget_->isVisible()) { if (auto c = getCanvas()) { c->render(nullptr, visibleLayer_, colorLayer_); } } } void CanvasProcessor::propagateEvent(Event* event, Outport* source) { if (event->hasVisitedProcessor(this)) return; event->markAsVisited(this); invokeEvent(event); if (event->hasBeenUsed()) return; if (auto resizeEvent = event->getAs<ResizeEvent>()) { // Avoid continues evaluation when port dimensions changes NetworkLock lock(this); dimensions_.set(resizeEvent->size()); if (enableCustomInputDimensions_) { sizeChanged(); } else { inport_.propagateEvent(resizeEvent, nullptr); // Make sure this processor is invalidated. invalidate(InvalidationLevel::InvalidOutput); } } else { bool used = event->hasBeenUsed(); for (auto inport : getInports()) { if (event->shouldPropagateTo(inport, this, source)) { inport->propagateEvent(event); used |= event->hasBeenUsed(); event->markAsUnused(); } } if (used) event->markAsUsed(); } } bool CanvasProcessor::isContextMenuAllowed() const { return allowContextMenu_; } void CanvasProcessor::setEvaluateWhenHidden(bool value) { if (value) { isSink_.setUpdate([]() { return true; }); isReady_.setUpdate([this]() { return allInportsAreReady(); }); } else { isSink_.setUpdate([this]() { return processorWidget_ && processorWidget_->isVisible(); }); isReady_.setUpdate([this]() { return allInportsAreReady() && processorWidget_ && processorWidget_->isVisible(); }); } } } // namespace inviwo
41.542857
100
0.664305
guillempd
0e2b40ce351abeae00636d16cabbef609a4a692e
2,174
cc
C++
learn/cpp_learn/template/Demo2.cc
qiuhoude/skynet_learn_dir
ae000c051cc44eb8f858fb5851fca16058b62410
[ "MIT" ]
null
null
null
learn/cpp_learn/template/Demo2.cc
qiuhoude/skynet_learn_dir
ae000c051cc44eb8f858fb5851fca16058b62410
[ "MIT" ]
null
null
null
learn/cpp_learn/template/Demo2.cc
qiuhoude/skynet_learn_dir
ae000c051cc44eb8f858fb5851fca16058b62410
[ "MIT" ]
null
null
null
#include <cstring> #include <iostream> using namespace std; // 在定义类型参数时我们使用了 class,而不是 typename template <class T> class CArray { private: int size; //数组元素的个数 T *ptr; //指向动态分配的数组 public: CArray(int s = 0); CArray(CArray &a); ~CArray(); void push_back(const T &v); //用于在数组尾部添加一个元素v CArray &operator=(const CArray &a); //用于数组对象间的赋值 int length() { return size; } const T &operator[](int i) { return ptr[i]; } }; template <class T> CArray<T>::CArray(int s) : size(s) { if (s <= 0) ptr = NULL; else ptr = new T[s]; } template <class T> CArray<T>::CArray(CArray &a) { if (!a.ptr) { ptr = NULL; size = 0; return; } ptr = new T[a.size]; memcpy(ptr, a.ptr, sizeof(T) * a.size); size = a.size; } template <class T> CArray<T>::~CArray() { if (ptr) delete[] ptr; } template <class T> CArray<T> &CArray<T>::operator=(const CArray &a) { //赋值号的作用是使"="左边对象里存放的数组,大小和内容都和右边的对象一样 if (this == &a) //防止a=a这样的赋值导致出错 return *this; if (a.ptr == NULL) { //如果a里面的数组是空的 if (ptr) delete[] ptr; ptr = NULL; size = 0; return *this; } if (size < a.size) { //如果原有空间够大,就不用分配新的空间 if (ptr) delete[] ptr; ptr = new T[a.size]; } memcpy(ptr, a.ptr, sizeof(T) * a.size); size = a.size; return *this; } template <class T> void CArray<T>::push_back(const T &v) { //在数组尾部添加一个元素 if (ptr) { T *tmpPtr = new T[size + 1]; //重新分配空间 memcpy(tmpPtr, ptr, sizeof(T) * size); //拷贝原数组内容 delete[] ptr; ptr = tmpPtr; } else //数组本来是空的 ptr = new T[1]; ptr[size++] = v; //加入新的数组元素 } int main() { CArray<double> a; for (int i = 0; i < 5; ++i) a.push_back(i * 1.1); for (int i = 0; i < a.length(); ++i) cout << a[i] << " "; cout << endl; cout << "----------------------------" << endl; // CArray<int> b; // b = a; // for (int i = 0; i < b.length(); ++i) // cout << b[i] << " "; // cout << endl; return 0; }
19.585586
58
0.484821
qiuhoude
0e2f6eea9d6c0da58dc93a7a6df739c4c711409c
21,641
cpp
C++
src/eepp/ui/uimenu.cpp
SpartanJ/eepp
21e8ae53af9bc5eb3fd1043376f2b3a4b3ff5fac
[ "MIT" ]
37
2020-01-20T06:21:24.000Z
2022-03-21T17:44:50.000Z
src/eepp/ui/uimenu.cpp
SpartanJ/eepp
21e8ae53af9bc5eb3fd1043376f2b3a4b3ff5fac
[ "MIT" ]
null
null
null
src/eepp/ui/uimenu.cpp
SpartanJ/eepp
21e8ae53af9bc5eb3fd1043376f2b3a4b3ff5fac
[ "MIT" ]
9
2019-03-22T00:33:07.000Z
2022-03-01T01:35:59.000Z
#include <eepp/graphics/drawablesearcher.hpp> #include <eepp/graphics/font.hpp> #include <eepp/ui/css/propertydefinition.hpp> #include <eepp/ui/uiiconthememanager.hpp> #include <eepp/ui/uimenu.hpp> #include <eepp/ui/uipopupmenu.hpp> #include <eepp/ui/uiscenenode.hpp> #include <eepp/ui/uithememanager.hpp> #include <pugixml/pugixml.hpp> namespace EE { namespace UI { UIMenu* UIMenu::New() { return eeNew( UIMenu, () ); } UIMenu::UIMenu() : UIWidget( "menu" ), mMaxWidth( 0 ), mNextPosY( 0 ), mBiggestIcon( 0 ), mItemSelected( nullptr ), mItemSelectedIndex( eeINDEX_NOT_FOUND ), mResizing( false ), mOwnerNode( nullptr ) { mFlags |= UI_AUTO_SIZE; onSizeChange(); applyDefaultTheme(); } UIMenu::~UIMenu() {} Uint32 UIMenu::getType() const { return UI_TYPE_MENU; } bool UIMenu::isType( const Uint32& type ) const { return UIMenu::getType() == type ? true : UIWidget::isType( type ); } void UIMenu::setTheme( UITheme* theme ) { UIWidget::setTheme( theme ); setThemeSkin( theme, "menu" ); onThemeLoaded(); } void UIMenu::onThemeLoaded() { UIWidget::onThemeLoaded(); autoPadding(); onSizeChange(); } void UIMenu::onPaddingChange() { widgetsSetPos(); } UIMenuItem* UIMenu::createMenuItem( const String& text, Drawable* icon, const String& shortcutText ) { UIMenuItem* widget = UIMenuItem::New(); widget->setHorizontalAlign( UI_HALIGN_LEFT ); widget->setParent( this ); widget->setIconMinimumSize( mIconMinSize ); widget->setIcon( icon ); widget->setText( text ); widget->setShortcutText( shortcutText ); return widget; } UIMenuItem* UIMenu::add( const String& text, Drawable* icon, const String& shortcutText ) { UIMenuItem* menuItem = createMenuItem( text, icon, shortcutText ); add( menuItem ); return menuItem; } UIMenuCheckBox* UIMenu::createMenuCheckBox( const String& text, const bool& active, const String& shortcutText ) { UIMenuCheckBox* widget = UIMenuCheckBox::New(); widget->setHorizontalAlign( UI_HALIGN_LEFT ); widget->setParent( this ); widget->setIconMinimumSize( mIconMinSize ); widget->setText( text ); widget->setShortcutText( shortcutText ); if ( active ) widget->setActive( active ); return widget; } UIMenuCheckBox* UIMenu::addCheckBox( const String& text, const bool& active, const String& shortcutText ) { UIMenuCheckBox* chkBox = createMenuCheckBox( text, active, shortcutText ); add( chkBox ); return chkBox; } UIMenuRadioButton* UIMenu::createMenuRadioButton( const String& text, const bool& active ) { UIMenuRadioButton* widget = UIMenuRadioButton::New(); widget->setHorizontalAlign( UI_HALIGN_LEFT ); widget->setParent( this ); widget->setIconMinimumSize( mIconMinSize ); widget->setText( text ); if ( active ) widget->setActive( active ); return widget; } UIMenuRadioButton* UIMenu::addRadioButton( const String& text, const bool& active ) { UIMenuRadioButton* radioButton = createMenuRadioButton( text, active ); add( radioButton ); return radioButton; } UIMenuSubMenu* UIMenu::createSubMenu( const String& text, Drawable* icon, UIMenu* subMenu ) { UIMenuSubMenu* menu = UIMenuSubMenu::New(); menu->setHorizontalAlign( UI_HALIGN_LEFT ); menu->setParent( this ); menu->setIconMinimumSize( mIconMinSize ); menu->setIcon( icon ); menu->setText( text ); menu->setSubMenu( subMenu ); return menu; } UIMenuSubMenu* UIMenu::addSubMenu( const String& text, Drawable* icon, UIMenu* subMenu ) { UIMenuSubMenu* menu = createSubMenu( text, icon, subMenu ); add( menu ); return menu; } bool UIMenu::widgetCheckSize( UIWidget* widget, const bool& resize ) { if ( widget->isType( UI_TYPE_MENUITEM ) ) { UIMenuItem* tItem = widget->asType<UIMenuItem>(); if ( nullptr != tItem->getIcon() && tItem->getIcon()->getLayoutMargin().Left + tItem->getIcon()->getLayoutMargin().Right + tItem->getIcon()->getSize().getWidth() > (Int32)mBiggestIcon ) { mBiggestIcon = tItem->getIcon()->getLayoutMargin().Left + tItem->getIcon()->getLayoutMargin().Right + tItem->getIcon()->getSize().getWidth(); } if ( mFlags & UI_AUTO_SIZE ) { Sizef contentSize( tItem->getContentSize() ); if ( contentSize.getWidth() > (Int32)mMaxWidth ) { mMaxWidth = contentSize.getWidth(); if ( resize ) { widgetsResize(); return true; } } } } return false; } UIWidget* UIMenu::add( UIWidget* widget ) { if ( this != widget->getParent() ) widget->setParent( this ); widgetCheckSize( widget ); setWidgetSize( widget ); widget->setPixelsPosition( mPaddingPx.Left, mPaddingPx.Top + mNextPosY ); mNextPosY += widget->getPixelsSize().getHeight(); mItems.push_back( widget ); widget->addEventListener( Event::OnSizeChange, [&]( const Event* ) { if ( !mResizing ) { widgetsSetPos(); widgetsResize(); } } ); resizeMe(); return widget; } void UIMenu::setWidgetSize( UIWidget* widget ) { mResizing = true; widget->setPixelsSize( mSize.getWidth(), widget->getPixelsSize().getHeight() ); mResizing = false; } UIMenuSeparator* UIMenu::addSeparator() { UIMenuSeparator* separator = UIMenuSeparator::New(); separator->setParent( this ); separator->setPixelsPosition( mPaddingPx.Left, mPaddingPx.Top + mNextPosY ); separator->setPixelsSize( mSize.getWidth() - mPaddingPx.Left - mPaddingPx.Right, PixelDensity::dpToPxI( separator->getSkinSize().getHeight() ) ); mNextPosY += separator->getPixelsSize().getHeight(); mItems.push_back( separator ); resizeMe(); separator->addEventListener( Event::OnSizeChange, [&]( const Event* ) { if ( !mResizing ) { widgetsSetPos(); widgetsResize(); } } ); return separator; } UIWidget* UIMenu::getItem( const Uint32& index ) { eeASSERT( index < mItems.size() ); return mItems[index]; } UIWidget* UIMenu::getItem( const String& text ) { for ( Uint32 i = 0; i < mItems.size(); i++ ) { if ( mItems[i]->isType( UI_TYPE_MENUITEM ) ) { UIMenuItem* tMenuItem = mItems[i]->asType<UIMenuItem>(); if ( tMenuItem->getText() == text ) return tMenuItem; } } return nullptr; } Uint32 UIMenu::getItemIndex( UIWidget* item ) { for ( Uint32 i = 0; i < mItems.size(); i++ ) { if ( mItems[i] == item ) return i; } return eeINDEX_NOT_FOUND; } Uint32 UIMenu::getCount() const { return mItems.size(); } UIWidget* UIMenu::getItemSelected() const { return mItemSelected; } void UIMenu::remove( const Uint32& index ) { eeASSERT( index < mItems.size() ); mItems[index]->close(); mItems.erase( mItems.begin() + index ); widgetsSetPos(); widgetsResize(); } void UIMenu::remove( UIWidget* widget ) { for ( Uint32 i = 0; i < mItems.size(); i++ ) { if ( mItems[i] == widget ) { remove( i ); break; } } } void UIMenu::removeAll() { for ( Uint32 i = 0; i < mItems.size(); i++ ) { mItems[i]->close(); } mItems.clear(); mNextPosY = 0; mMaxWidth = 0; resizeMe(); } void UIMenu::insert( const String& text, Drawable* icon, const Uint32& index ) { insert( createMenuItem( text, icon ), index ); } void UIMenu::insert( UIWidget* widget, const Uint32& index ) { mItems.insert( mItems.begin() + index, widget ); childAddAt( widget, index ); widgetsSetPos(); widgetsResize(); } bool UIMenu::isSubMenu( Node* node ) { for ( Uint32 i = 0; i < mItems.size(); i++ ) { if ( nullptr != mItems[i] ) { if ( mItems[i] == node || ( mItems[i]->isType( UI_TYPE_MENUSUBMENU ) && mItems[i]->asType<UIMenuSubMenu>()->getSubMenu() == node ) ) return true; } } if ( mOwnerNode && mOwnerNode->isType( UI_TYPE_MENUSUBMENU ) ) { if ( mOwnerNode->getParent() == node || mOwnerNode->getParent()->asType<UIMenu>()->isSubMenu( node ) ) return true; } return false; } Uint32 UIMenu::onMessage( const NodeMessage* msg ) { switch ( msg->getMsg() ) { case NodeMessage::MouseOver: { if ( mOwnerNode && mOwnerNode->isType( UI_TYPE_MENUSUBMENU ) ) { mOwnerNode->getParent()->asType<UIMenu>()->setItemSelected( mOwnerNode ); } break; } case NodeMessage::MouseUp: { if ( msg->getSender()->getParent() == this && ( msg->getFlags() & EE_BUTTONS_LRM ) ) { Event itemEvent( msg->getSender(), Event::OnItemClicked ); sendEvent( &itemEvent ); return 1; } break; } case NodeMessage::FocusLoss: { if ( nullptr != getEventDispatcher() ) { Node* focusNode = getEventDispatcher()->getFocusNode(); if ( this != focusNode && !isParentOf( focusNode ) && !isSubMenu( focusNode ) && mOwnerNode != focusNode ) { backpropagateHide(); return 1; } } break; } } return 0; } void UIMenu::onSizeChange() { Float minWidth = 0; if ( !mMinWidthEq.empty() ) { minWidth = lengthFromValueAsDp( mMinWidthEq, CSS::PropertyRelativeTarget::None ); } if ( 0 != minWidth && getSize().getWidth() < (Int32)minWidth ) { setSize( minWidth, PixelDensity::pxToDpI( mNextPosY ) + mPadding.Top + mPadding.Bottom ); } UIWidget::onSizeChange(); } void UIMenu::autoPadding() { if ( mFlags & UI_AUTO_PADDING ) { setPadding( makePadding() ); } } void UIMenu::widgetsResize() { resizeMe(); for ( Uint32 i = 0; i < mItems.size(); i++ ) { setWidgetSize( mItems[i] ); } } void UIMenu::widgetsSetPos() { Uint32 i; mNextPosY = 0; mBiggestIcon = mIconMinSize.getWidth(); if ( mFlags & UI_AUTO_SIZE ) { mMaxWidth = 0; for ( i = 0; i < mItems.size(); i++ ) { widgetCheckSize( mItems[i], false ); } } for ( i = 0; i < mItems.size(); i++ ) { UIWidget* widget = mItems[i]; widget->setPixelsPosition( mPaddingPx.Left, mPaddingPx.Top + mNextPosY ); mNextPosY += widget->getPixelsSize().getHeight(); } resizeMe(); invalidateDraw(); } void UIMenu::resizeMe() { if ( mFlags & UI_AUTO_SIZE ) { setPixelsSize( mMaxWidth, mNextPosY + mPaddingPx.Top + mPaddingPx.Bottom ); } else { setPixelsSize( mSize.getWidth(), mNextPosY + mPaddingPx.Top + mPaddingPx.Bottom ); } } bool UIMenu::show() { setEnabled( true ); setVisible( true ); return true; } bool UIMenu::hide() { setEnabled( false ); setVisible( false ); safeHide(); return true; } void UIMenu::safeHide() { if ( mOwnerNode && mOwnerNode->isType( UI_TYPE_MENUSUBMENU ) ) { UIMenu* menu = mOwnerNode->getParent()->asType<UIMenu>(); if ( menu->mCurrentSubMenu == this ) menu->mCurrentSubMenu = nullptr; if ( mOwnerNode == menu->getItemSelected() ) menu->unselectSelected(); if ( getEventDispatcher()->getFocusNode() == this || isParentOf( getEventDispatcher()->getFocusNode() ) ) menu->setFocus(); } unselectSelected(); if ( mCurrentSubMenu ) { mCurrentSubMenu->hide(); mCurrentSubMenu = nullptr; } } void UIMenu::unselectSelected() { if ( nullptr != mItemSelected ) mItemSelected->popState( UIState::StateSelected ); mItemSelected = nullptr; mItemSelectedIndex = eeINDEX_NOT_FOUND; } void UIMenu::setItemSelected( UIWidget* item ) { if ( nullptr != mItemSelected ) mItemSelected->popState( UIState::StateSelected ); if ( nullptr != item ) item->pushState( UIState::StateSelected ); if ( mItemSelected != item ) { mItemSelected = item; mItemSelectedIndex = getItemIndex( mItemSelected ); } } void UIMenu::trySelect( UIWidget* node, bool up ) { if ( mItems.size() ) { if ( !node->isType( UI_TYPE_MENU_SEPARATOR ) ) { setItemSelected( node ); } else { Uint32 index = getItemIndex( node ); if ( index != eeINDEX_NOT_FOUND ) { if ( up ) { if ( index > 0 ) { for ( Int32 i = (Int32)index - 1; i >= 0; i-- ) { if ( !mItems[i]->isType( UI_TYPE_MENU_SEPARATOR ) ) { setItemSelected( mItems[i] ); return; } } } setItemSelected( mItems[mItems.size()] ); } else { for ( Uint32 i = index + 1; i < mItems.size(); i++ ) { if ( !mItems[i]->isType( UI_TYPE_MENU_SEPARATOR ) ) { setItemSelected( mItems[i] ); return; } } setItemSelected( mItems[0] ); } } } } } void UIMenu::backpropagateHide() { hide(); if ( mOwnerNode && mOwnerNode->getParent()->isType( UI_TYPE_MENU ) ) { mOwnerNode->getParent()->asType<UIMenu>()->backpropagateHide(); } } const Clock& UIMenu::getInactiveTime() const { return mInactiveTime; } void UIMenu::nextSel() { if ( mItems.size() ) { if ( mItemSelectedIndex != eeINDEX_NOT_FOUND ) { if ( mItemSelectedIndex + 1 < mItems.size() ) { trySelect( mItems[mItemSelectedIndex + 1], false ); } else { trySelect( mItems[0], false ); } } else { trySelect( mItems[0], false ); } } } void UIMenu::prevSel() { if ( mItems.size() ) { if ( mItemSelectedIndex != eeINDEX_NOT_FOUND ) { if ( mItemSelectedIndex >= 1 ) { trySelect( mItems[mItemSelectedIndex - 1], true ); } else { trySelect( mItems[mItems.size() - 1], true ); } } else { trySelect( mItems[0], true ); } } } Uint32 UIMenu::onKeyDown( const KeyEvent& event ) { switch ( event.getKeyCode() ) { case KEY_DOWN: nextSel(); break; case KEY_UP: prevSel(); break; case KEY_RIGHT: if ( nullptr != mItemSelected && mItemSelected->isType( UI_TYPE_MENUSUBMENU ) ) mItemSelected->asType<UIMenuSubMenu>()->showSubMenu(); break; case KEY_LEFT: case KEY_ESCAPE: hide(); break; case KEY_KP_ENTER: case KEY_RETURN: if ( nullptr != mItemSelected && nullptr != getEventDispatcher() ) { mItemSelected->sendMouseEvent( Event::MouseClick, getEventDispatcher()->getMousePos(), EE_BUTTON_LMASK ); NodeMessage msg( mItemSelected, NodeMessage::MouseUp, EE_BUTTON_LMASK ); mItemSelected->messagePost( &msg ); } break; default: break; } return UIWidget::onKeyDown( event ); } static Drawable* getIconDrawable( const std::string& name, UIIconThemeManager* iconThemeManager ) { Drawable* iconDrawable = nullptr; if ( nullptr != iconThemeManager ) { UIIcon* icon = iconThemeManager->findIcon( name ); if ( icon ) { // TODO: Fix size iconDrawable = icon->getSize( PixelDensity::dpToPx( 16 ) ); } } if ( nullptr == iconDrawable ) iconDrawable = DrawableSearcher::searchByName( name ); return iconDrawable; } void UIMenu::loadFromXmlNode( const pugi::xml_node& node ) { beginAttributesTransaction(); UIWidget::loadFromXmlNode( node ); for ( pugi::xml_node item = node.first_child(); item; item = item.next_sibling() ) { std::string name( item.name() ); String::toLowerInPlace( name ); if ( name == "menuitem" || name == "item" ) { std::string text( item.attribute( "text" ).as_string() ); std::string icon( item.attribute( "icon" ).as_string() ); if ( nullptr != mSceneNode && mSceneNode->isUISceneNode() ) add( static_cast<UISceneNode*>( mSceneNode )->getTranslatorString( text ), getIconDrawable( icon, getUISceneNode()->getUIIconThemeManager() ) ); } else if ( name == "menuseparator" || name == "separator" ) { addSeparator(); } else if ( name == "menucheckbox" || name == "checkbox" ) { std::string text( item.attribute( "text" ).as_string() ); bool active( item.attribute( "active" ).as_bool() ); if ( nullptr != mSceneNode && mSceneNode->isUISceneNode() ) addCheckBox( static_cast<UISceneNode*>( mSceneNode )->getTranslatorString( text ), active ); } else if ( name == "menuradiobutton" || name == "radiobutton" ) { std::string text( item.attribute( "text" ).as_string() ); bool active( item.attribute( "active" ).as_bool() ); if ( nullptr != mSceneNode && mSceneNode->isUISceneNode() ) addRadioButton( static_cast<UISceneNode*>( mSceneNode )->getTranslatorString( text ), active ); } else if ( name == "menusubmenu" || name == "submenu" ) { std::string text( item.attribute( "text" ).as_string() ); std::string icon( item.attribute( "icon" ).as_string() ); UIPopUpMenu* subMenu = UIPopUpMenu::New(); if ( nullptr != getDrawInvalidator() ) subMenu->setParent( getDrawInvalidator() ); subMenu->loadFromXmlNode( item ); if ( nullptr != mSceneNode && mSceneNode->isUISceneNode() ) addSubMenu( static_cast<UISceneNode*>( mSceneNode )->getTranslatorString( text ), getIconDrawable( icon, getUISceneNode()->getUIIconThemeManager() ), subMenu ); } } endAttributesTransaction(); } std::string UIMenu::getPropertyString( const PropertyDefinition* propertyDef, const Uint32& propertyIndex ) { if ( nullptr == propertyDef ) return ""; switch ( propertyDef->getPropertyId() ) { case PropertyId::MinIconSize: return String::format( "%ddp", mIconMinSize.getWidth() ) + " " + String::format( "%ddp", mIconMinSize.getHeight() ); default: return UIWidget::getPropertyString( propertyDef, propertyIndex ); } } bool UIMenu::applyProperty( const StyleSheetProperty& attribute ) { if ( !checkPropertyDefinition( attribute ) ) return false; switch ( attribute.getPropertyDefinition()->getPropertyId() ) { case PropertyId::MinIconSize: setIconMinimumSize( attribute.asSizei() ); break; default: return UIWidget::applyProperty( attribute ); } return true; } UINode* UIMenu::getOwnerNode() const { return mOwnerNode; } void UIMenu::setOwnerNode( UIWidget* ownerNode ) { mOwnerNode = ownerNode; } void UIMenu::setIconMinimumSize( const Sizei& minIconSize ) { mIconMinSize = minIconSize; mBiggestIcon = eemax( mBiggestIcon, mIconMinSize.getWidth() ); for ( Uint32 i = 0; i < mItems.size(); i++ ) { if ( mItems[i]->isType( UI_TYPE_MENUITEM ) ) mItems[i]->asType<UIMenuItem>()->setIconMinimumSize( mIconMinSize ); } widgetsSetPos(); widgetsResize(); } const Sizei& UIMenu::getIconMinimumSize() const { return mIconMinSize; } void UIMenu::onVisibilityChange() { UIWidget::onVisibilityChange(); if ( mOwnerNode && mOwnerNode->isType( UI_TYPE_MENUSUBMENU ) ) { if ( mVisible ) { mInactiveTime.restart(); subscribeScheduledUpdate(); } else { unsubscribeScheduledUpdate(); } } else { mInactiveTime.restart(); } } void UIMenu::scheduledUpdate( const Time& ) { if ( !mVisible ) return; Node* node = getEventDispatcher()->getMouseOverNode(); if ( node && ( isChildOfMeOrSubMenu( node ) || getItemSelected() ) ) mInactiveTime.restart(); if ( mInactiveTime.getElapsedTime() > Seconds( 1 ) ) hide(); } bool UIMenu::isChildOfMeOrSubMenu( Node* node ) { return isParentOf( node ) || mOwnerNode == node || ( mCurrentSubMenu && mCurrentSubMenu->isChildOfMeOrSubMenu( node ) ); } void UIMenu::findBestMenuPos( Vector2f& pos, UIMenu* menu, UIMenu* parent, UIMenuSubMenu* subMenu ) { SceneNode* sceneNode = menu->getSceneNode(); if ( nullptr == sceneNode ) return; Rectf qScreen( 0.f, 0.f, sceneNode->getPixelsSize().getWidth(), sceneNode->getPixelsSize().getHeight() ); Rectf qPos( pos.x, pos.y, pos.x + menu->getPixelsSize().getWidth(), pos.y + menu->getPixelsSize().getHeight() ); if ( nullptr != parent && nullptr != subMenu ) { Rectf qPrevMenu; bool clipMenu = parent->getOwnerNode() && parent->getOwnerNode()->getParent() && parent->getOwnerNode()->getParent()->isType( UI_TYPE_MENU ); Vector2f sPos = subMenu->getPixelsPosition(); subMenu->nodeToWorldTranslation( sPos ); Vector2f pPos = parent->getPixelsPosition(); parent->nodeToWorldTranslation( pPos ); if ( clipMenu ) { UIMenu* parentOwner = parent->getOwnerNode()->getParent()->asType<UIMenu>(); Vector2f poPos = parentOwner->getPixelsPosition(); parentOwner->nodeToWorldTranslation( poPos ); qPrevMenu = Rectf( poPos.x, poPos.y, poPos.x + parentOwner->getPixelsSize().getWidth(), poPos.y + parentOwner->getPixelsSize().getHeight() ); } Rectf qParent( pPos.x, pPos.y, pPos.x + parent->getPixelsSize().getWidth(), pPos.y + parent->getPixelsSize().getHeight() ); pos.x = qParent.Right; pos.y = sPos.y; qPos.Left = pos.x; qPos.Right = qPos.Left + menu->getPixelsSize().getWidth(); qPos.Top = pos.y; qPos.Bottom = qPos.Top + menu->getPixelsSize().getHeight(); if ( !qScreen.contains( qPos ) || ( clipMenu && qPrevMenu.overlap( qPos ) ) ) { pos.y = sPos.y + subMenu->getPixelsSize().getHeight() - menu->getPixelsSize().getHeight(); qPos.Top = pos.y; qPos.Bottom = qPos.Top + menu->getPixelsSize().getHeight(); if ( !qScreen.contains( qPos ) || ( clipMenu && qPrevMenu.overlap( qPos ) ) ) { pos.x = qParent.Left - menu->getPixelsSize().getWidth(); pos.y = sPos.y; qPos.Left = pos.x; qPos.Right = qPos.Left + menu->getPixelsSize().getWidth(); qPos.Top = pos.y; qPos.Bottom = qPos.Top + menu->getPixelsSize().getHeight(); if ( !qScreen.contains( qPos ) || ( clipMenu && qPrevMenu.overlap( qPos ) ) ) { pos.y = sPos.y + subMenu->getPixelsSize().getHeight() - menu->getPixelsSize().getHeight(); qPos.Top = pos.y; qPos.Bottom = qPos.Top + menu->getPixelsSize().getHeight(); if ( !qScreen.contains( qPos ) ) { if ( menu->getPixelsSize().getHeight() <= qScreen.getHeight() ) { pos = { pos.x, eefloor( ( qScreen.getHeight() - menu->getPixelsSize().getHeight() ) * 0.5f ) }; } else { pos = { pos.x, 0 }; } } } } } } else { if ( !qScreen.contains( qPos ) ) { pos.y -= menu->getPixelsSize().getHeight(); qPos.Top -= menu->getPixelsSize().getHeight(); qPos.Bottom -= menu->getPixelsSize().getHeight(); if ( !qScreen.contains( qPos ) ) { pos.x -= menu->getPixelsSize().getWidth(); qPos.Left -= menu->getPixelsSize().getWidth(); qPos.Right -= menu->getPixelsSize().getWidth(); if ( !qScreen.contains( qPos ) ) { pos.y += menu->getPixelsSize().getHeight(); qPos.Top += menu->getPixelsSize().getHeight(); qPos.Bottom += menu->getPixelsSize().getHeight(); } } } } } }} // namespace EE::UI
28.701592
99
0.660644
SpartanJ
0e2ff3205bf320555738defdc319a2f9b81d3ea2
3,738
cpp
C++
core/storage/changes_trie/impl/storage_changes_tracker_impl.cpp
iceseer/kagome
a405921659cc19e9fdb851e5f13f1e607fdf8af4
[ "Apache-2.0" ]
null
null
null
core/storage/changes_trie/impl/storage_changes_tracker_impl.cpp
iceseer/kagome
a405921659cc19e9fdb851e5f13f1e607fdf8af4
[ "Apache-2.0" ]
null
null
null
core/storage/changes_trie/impl/storage_changes_tracker_impl.cpp
iceseer/kagome
a405921659cc19e9fdb851e5f13f1e607fdf8af4
[ "Apache-2.0" ]
null
null
null
#include "storage/changes_trie/impl/storage_changes_tracker_impl.hpp" #include "scale/scale.hpp" #include "storage/changes_trie/impl/changes_trie.hpp" OUTCOME_CPP_DEFINE_CATEGORY(kagome::storage::changes_trie, StorageChangesTrackerImpl::Error, e) { using E = kagome::storage::changes_trie::StorageChangesTrackerImpl::Error; switch (e) { case E::EXTRINSIC_IDX_GETTER_UNINITIALIZED: return "The delegate that returns extrinsic index is uninitialized"; case E::INVALID_PARENT_HASH: return "The supplied parent hash doesn't match the one of the current " "block"; } return "Unknown error"; } namespace kagome::storage::changes_trie { StorageChangesTrackerImpl::StorageChangesTrackerImpl( std::shared_ptr<storage::trie::PolkadotTrieFactory> trie_factory, std::shared_ptr<storage::trie::Codec> codec) : trie_factory_(std::move(trie_factory)), codec_(std::move(codec)), parent_hash_{}, parent_number_{std::numeric_limits<primitives::BlockNumber>::max()} { BOOST_ASSERT(trie_factory_ != nullptr); BOOST_ASSERT(codec_ != nullptr); } outcome::result<void> StorageChangesTrackerImpl::onBlockChange( primitives::BlockHash new_parent_hash, primitives::BlockNumber new_parent_number) { parent_hash_ = new_parent_hash; parent_number_ = new_parent_number; // new block -- new extrinsics extrinsics_changes_.clear(); new_entries_.clear(); return outcome::success(); } void StorageChangesTrackerImpl::setExtrinsicIdxGetter( GetExtrinsicIndexDelegate f) { get_extrinsic_index_ = std::move(f); } outcome::result<void> StorageChangesTrackerImpl::onPut( const common::Buffer &key, bool is_new_entry) { auto change_it = extrinsics_changes_.find(key); OUTCOME_TRY(idx_bytes, get_extrinsic_index_()); OUTCOME_TRY(idx, scale::decode<primitives::ExtrinsicIndex>(idx_bytes)); // if key was already changed in the same block, just add extrinsic to // the changers list if (change_it != extrinsics_changes_.end()) { change_it->second.push_back(idx); } else { extrinsics_changes_.insert(std::make_pair(key, std::vector{idx})); if (is_new_entry) { new_entries_.insert(key); } } return outcome::success(); } outcome::result<void> StorageChangesTrackerImpl::onRemove( const common::Buffer &key) { auto change_it = extrinsics_changes_.find(key); OUTCOME_TRY(idx_bytes, get_extrinsic_index_()); OUTCOME_TRY(idx, scale::decode<primitives::ExtrinsicIndex>(idx_bytes)); // if key was already changed in the same block, just add extrinsic to // the changers list if (change_it != extrinsics_changes_.end()) { // if new entry, i. e. it doesn't exist in the persistent storage, then // don't track it, because it's just temporary if (auto i = new_entries_.find(key); i != new_entries_.end()) { extrinsics_changes_.erase(change_it); new_entries_.erase(i); } else { change_it->second.push_back(idx); } } else { extrinsics_changes_.insert(std::make_pair(key, std::vector{idx})); } return outcome::success(); } outcome::result<common::Hash256> StorageChangesTrackerImpl::constructChangesTrie( const primitives::BlockHash &parent, const ChangesTrieConfig &conf) { if (parent != parent_hash_) { return Error::INVALID_PARENT_HASH; } OUTCOME_TRY( trie, ChangesTrie::buildFromChanges( parent_number_, trie_factory_, codec_, extrinsics_changes_, conf)); return trie->getHash(); } } // namespace kagome::storage::changes_trie
35.264151
79
0.688604
iceseer
0e385503db972714a2efe1c70a8694fe74c8d394
15,475
cpp
C++
rosplan_knowledge_base/src/KnowledgeBase.cpp
Emresav/ROSPlan
22d2cad209242bc8d98fca7ab25c322265ae69a6
[ "BSD-2-Clause" ]
null
null
null
rosplan_knowledge_base/src/KnowledgeBase.cpp
Emresav/ROSPlan
22d2cad209242bc8d98fca7ab25c322265ae69a6
[ "BSD-2-Clause" ]
null
null
null
rosplan_knowledge_base/src/KnowledgeBase.cpp
Emresav/ROSPlan
22d2cad209242bc8d98fca7ab25c322265ae69a6
[ "BSD-2-Clause" ]
1
2018-10-02T12:30:52.000Z
2018-10-02T12:30:52.000Z
#include "rosplan_knowledge_base/KnowledgeBase.h" namespace KCL_rosplan { /*-----------------*/ /* knowledge query */ /*-----------------*/ bool KnowledgeBase::queryKnowledge(rosplan_knowledge_msgs::KnowledgeQueryService::Request &req, rosplan_knowledge_msgs::KnowledgeQueryService::Response &res) { res.all_true = true; std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator iit; for(iit = req.knowledge.begin(); iit!=req.knowledge.end(); iit++) { bool present = false; if(iit->knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::INSTANCE) { // check if instance exists std::vector<std::string>::iterator sit; sit = find(model_instances[iit->instance_type].begin(), model_instances[iit->instance_type].end(), iit->instance_name); present = (sit!=model_instances[iit->instance_type].end()); } else if(iit->knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::FUNCTION) { // check if function exists; TODO inequalities std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator pit; for(pit=model_functions.begin(); pit!=model_functions.end(); pit++) { if(KnowledgeComparitor::containsKnowledge(*iit, *pit)) { present = true; pit = model_functions.end(); } } } else if(iit->knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::FACT) { // check if fact is true std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator pit; for(pit=model_facts.begin(); pit!=model_facts.end(); pit++) { if(KnowledgeComparitor::containsKnowledge(*iit, *pit)) { present = true; break; } } } if(!present) { res.all_true = false; res.false_knowledge.push_back(*iit); } } return true; } /*------------------*/ /* knowledge update */ /*------------------*/ bool KnowledgeBase::updateKnowledge(rosplan_knowledge_msgs::KnowledgeUpdateService::Request &req, rosplan_knowledge_msgs::KnowledgeUpdateService::Response &res) { if(req.update_type == rosplan_knowledge_msgs::KnowledgeUpdateService::Request::ADD_KNOWLEDGE) addKnowledge(req.knowledge); else if(req.update_type == rosplan_knowledge_msgs::KnowledgeUpdateService::Request::ADD_GOAL) addMissionGoal(req.knowledge); else if(req.update_type == rosplan_knowledge_msgs::KnowledgeUpdateService::Request::REMOVE_KNOWLEDGE) removeKnowledge(req.knowledge); else if(req.update_type == rosplan_knowledge_msgs::KnowledgeUpdateService::Request::REMOVE_GOAL) removeMissionGoal(req.knowledge); res.success = true; return true; } /*----------------*/ /* removing items */ /*----------------*/ void KnowledgeBase::removeKnowledge(rosplan_knowledge_msgs::KnowledgeItem &msg) { if(msg.knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::INSTANCE) { // search for instance std::vector<std::string>::iterator iit; for(iit = model_instances[msg.instance_type].begin(); iit!=model_instances[msg.instance_type].end(); iit++) { std::string name = *iit; if(name.compare(msg.instance_name)==0 || msg.instance_name.compare("")==0) { // remove instance from knowledge base ROS_INFO("KCL: (KB) Removing instance (%s, %s)", msg.instance_type.c_str(), (msg.instance_name.compare("")==0) ? "ALL" : msg.instance_name.c_str()); iit = model_instances[msg.instance_type].erase(iit); if(iit!=model_instances[msg.instance_type].begin()) iit--; plan_filter.checkFilters(msg, false); // remove affected domain attributes std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator pit; for(pit=model_facts.begin(); pit!=model_facts.end(); pit++) { if(KnowledgeComparitor::containsInstance(*pit, name)) { ROS_INFO("KCL: (KB) Removing domain attribute (%s)", pit->attribute_name.c_str()); plan_filter.checkFilters(*pit, false); pit = model_facts.erase(pit); if(pit!=model_facts.begin()) pit--; if(pit==model_facts.end()) break; } } // finish if(iit==model_instances[msg.instance_type].end()) break; } } } else if(msg.knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::FUNCTION) { // remove domain attribute (function) from knowledge base std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator pit; for(pit=model_functions.begin(); pit!=model_functions.end(); pit++) { if(KnowledgeComparitor::containsKnowledge(msg, *pit)) { ROS_INFO("KCL: (KB) Removing domain attribute (%s)", msg.attribute_name.c_str()); plan_filter.checkFilters(msg, false); pit = model_functions.erase(pit); if(pit!=model_functions.begin()) pit--; if(pit==model_functions.end()) break; } } } else if(msg.knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::FACT) { // remove domain attribute (predicate) from knowledge base std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator pit; for(pit=model_facts.begin(); pit!=model_facts.end(); pit++) { if(KnowledgeComparitor::containsKnowledge(msg, *pit)) { ROS_INFO("KCL: (KB) Removing domain attribute (%s)", msg.attribute_name.c_str()); plan_filter.checkFilters(msg, false); pit = model_facts.erase(pit); if(pit!=model_facts.begin()) pit--; if(pit==model_facts.end()) break; } } } } /** * remove mission goal */ void KnowledgeBase::removeMissionGoal(rosplan_knowledge_msgs::KnowledgeItem &msg) { bool changed = false; std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator git; for(git=model_goals.begin(); git!=model_goals.end(); git++) { if(KnowledgeComparitor::containsKnowledge(msg, *git)) { ROS_INFO("KCL: (KB) Removing goal (%s)", msg.attribute_name.c_str()); git = model_goals.erase(git); if(git!=model_goals.begin()) git--; if(git==model_goals.end()) break; } } if(changed) { rosplan_knowledge_msgs::Notification notMsg; notMsg.function = rosplan_knowledge_msgs::Notification::REMOVED; notMsg.knowledge_item = msg; plan_filter.notification_publisher.publish(notMsg); } } /*--------------*/ /* adding items */ /*--------------*/ /* * add an instance, domain predicate, or function to the knowledge base */ void KnowledgeBase::addKnowledge(rosplan_knowledge_msgs::KnowledgeItem &msg) { if(msg.knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::INSTANCE) { // check if instance is already in knowledge base std::vector<std::string>::iterator iit; iit = find(model_instances[msg.instance_type].begin(), model_instances[msg.instance_type].end(), msg.instance_name); // add instance if(iit==model_instances[msg.instance_type].end()) { ROS_INFO("KCL: (KB) Adding instance (%s, %s)", msg.instance_type.c_str(), msg.instance_name.c_str()); model_instances[msg.instance_type].push_back(msg.instance_name); plan_filter.checkFilters(msg, true); } } else if(msg.knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::FACT) { // add domain attribute std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator pit; for(pit=model_facts.begin(); pit!=model_facts.end(); pit++) { if(KnowledgeComparitor::containsKnowledge(msg, *pit)) return; } ROS_INFO("KCL: (KB) Adding domain attribute (%s)", msg.attribute_name.c_str()); model_facts.push_back(msg); plan_filter.checkFilters(msg, true); } else if(msg.knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::FUNCTION) { // add domain function std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator pit; for(pit=model_functions.begin(); pit!=model_functions.end(); pit++) { if(KnowledgeComparitor::containsKnowledge(msg, *pit)) { // already added TODO value check ROS_INFO("KCL: (KB) Updating domain function (%s)", msg.attribute_name.c_str()); pit->function_value = msg.function_value; return; } } ROS_INFO("KCL: (KB) Adding domain function (%s)", msg.attribute_name.c_str()); model_functions.push_back(msg); plan_filter.checkFilters(msg, true); } } /* * add mission goal to knowledge base */ void KnowledgeBase::addMissionGoal(rosplan_knowledge_msgs::KnowledgeItem &msg) { std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator pit; for(pit=model_goals.begin(); pit!=model_goals.end(); pit++) { if(KnowledgeComparitor::containsKnowledge(msg, *pit)) return; } ROS_INFO("KCL: (KB) Adding mission goal (%s)", msg.attribute_name.c_str()); model_goals.push_back(msg); } /*----------------*/ /* fetching items */ /*----------------*/ bool KnowledgeBase::getCurrentInstances(rosplan_knowledge_msgs::GetInstanceService::Request &req, rosplan_knowledge_msgs::GetInstanceService::Response &res) { // fetch the instances of the correct type if(""==req.type_name) { std::map<std::string,std::vector<std::string> >::iterator iit; for(iit=model_instances.begin(); iit != model_instances.end(); iit++) { for(size_t j=0; j<iit->second.size(); j++) res.instances.push_back(iit->second[j]); } } else { std::map<std::string,std::vector<std::string> >::iterator iit; iit = model_instances.find(req.type_name); if(iit != model_instances.end()) { for(size_t j=0; j<iit->second.size(); j++) res.instances.push_back(iit->second[j]); } } return true; } bool KnowledgeBase::getCurrentKnowledge(rosplan_knowledge_msgs::GetAttributeService::Request &req, rosplan_knowledge_msgs::GetAttributeService::Response &res) { // fetch the knowledgeItems of the correct attribute for(size_t i=0; i<model_facts.size(); i++) { if(0==req.predicate_name.compare(model_facts[i].attribute_name) || ""==req.predicate_name) res.attributes.push_back(model_facts[i]); } // ...or fetch the knowledgeItems of the correct function for(size_t i=0; i<model_functions.size(); i++) { if(0==req.predicate_name.compare(model_functions[i].attribute_name) || ""==req.predicate_name) res.attributes.push_back(model_functions[i]); } return true; } bool KnowledgeBase::getCurrentGoals(rosplan_knowledge_msgs::GetAttributeService::Request &req, rosplan_knowledge_msgs::GetAttributeService::Response &res) { for(size_t i=0; i<model_goals.size(); i++) res.attributes.push_back(model_goals[i]); return true; } /*-----------------*/ /* fetching domain */ /*-----------------*/ /* get domain types */ bool KnowledgeBase::getTyes(rosplan_knowledge_msgs::GetDomainTypeService::Request &req, rosplan_knowledge_msgs::GetDomainTypeService::Response &res) { std::vector<std::string>::iterator iit; for(iit = domain_parser.domain_types.begin(); iit!=domain_parser.domain_types.end(); iit++) res.types.push_back(*iit); return true; } /* get domain predicates */ bool KnowledgeBase::getPredicates(rosplan_knowledge_msgs::GetDomainAttributeService::Request &req, rosplan_knowledge_msgs::GetDomainAttributeService::Response &res) { std::map< std::string, PDDLAtomicFormula>::iterator iit; for(iit = domain_parser.domain_predicates.begin(); iit!=domain_parser.domain_predicates.end(); iit++) { rosplan_knowledge_msgs::DomainFormula formula; formula.name = iit->second.name; for(size_t i=0; i<iit->second.vars.size(); i++) { diagnostic_msgs::KeyValue param; param.key = iit->second.vars[i].name; param.value = iit->second.vars[i].type; formula.typed_parameters.push_back(param); } res.items.push_back(formula); } return true; } /* get domain functions */ bool KnowledgeBase::getFunctions(rosplan_knowledge_msgs::GetDomainAttributeService::Request &req, rosplan_knowledge_msgs::GetDomainAttributeService::Response &res) { std::map< std::string, PDDLAtomicFormula>::iterator iit; for(iit = domain_parser.domain_functions.begin(); iit!=domain_parser.domain_functions.end(); iit++) { rosplan_knowledge_msgs::DomainFormula formula; formula.name = iit->second.name; for(size_t i=0; i<iit->second.vars.size(); i++) { diagnostic_msgs::KeyValue param; param.key = iit->second.vars[i].name; param.value = iit->second.vars[i].type; formula.typed_parameters.push_back(param); } res.items.push_back(formula); } return true; } /* get domain operators */ bool KnowledgeBase::getOperators(rosplan_knowledge_msgs::GetDomainOperatorService::Request &req, rosplan_knowledge_msgs::GetDomainOperatorService::Response &res) { std::map< std::string, PDDLOperator>::iterator iit; for(iit = domain_parser.domain_operators.begin(); iit!=domain_parser.domain_operators.end(); iit++) { rosplan_knowledge_msgs::DomainFormula formula; formula.name = iit->second.name; for(size_t i=0; i<iit->second.parameters.size(); i++) { diagnostic_msgs::KeyValue param; param.key = iit->second.parameters[i].name; param.value = iit->second.parameters[i].type; formula.typed_parameters.push_back(param); } res.operators.push_back(formula); } return true; } } // close namespace /*-------------*/ /* main method */ /*-------------*/ int main(int argc, char **argv) { ros::init(argc, argv, "KCL_knowledge_base"); ros::NodeHandle n; // parameters std::string domainPath; n.param("/domain_path", domainPath, std::string("common/domain.pddl")); KCL_rosplan::KnowledgeBase kb; ROS_INFO("KCL: (KB) Parsing domain"); kb.domain_parser.domain_parsed = false; kb.domain_parser.parseDomain(domainPath); // fetch domain info ros::ServiceServer typeServer = n.advertiseService("/kcl_rosplan/get_domain_types", &KCL_rosplan::KnowledgeBase::getTyes, &kb); ros::ServiceServer predicateServer = n.advertiseService("/kcl_rosplan/get_domain_predicates", &KCL_rosplan::KnowledgeBase::getPredicates, &kb); ros::ServiceServer functionServer = n.advertiseService("/kcl_rosplan/get_domain_functions", &KCL_rosplan::KnowledgeBase::getFunctions, &kb); ros::ServiceServer operatorServer = n.advertiseService("/kcl_rosplan/get_domain_operators", &KCL_rosplan::KnowledgeBase::getOperators, &kb); // query knowledge ros::ServiceServer queryServer = n.advertiseService("/kcl_rosplan/query_knowledge_base", &KCL_rosplan::KnowledgeBase::queryKnowledge, &kb); // update knowledge ros::ServiceServer updateServer = n.advertiseService("/kcl_rosplan/update_knowledge_base", &KCL_rosplan::KnowledgeBase::updateKnowledge, &kb); // fetch knowledge ros::ServiceServer currentInstanceServer = n.advertiseService("/kcl_rosplan/get_current_instances", &KCL_rosplan::KnowledgeBase::getCurrentInstances, &kb); ros::ServiceServer currentKnowledgeServer = n.advertiseService("/kcl_rosplan/get_current_knowledge", &KCL_rosplan::KnowledgeBase::getCurrentKnowledge, &kb); ros::ServiceServer currentGoalServer = n.advertiseService("/kcl_rosplan/get_current_goals", &KCL_rosplan::KnowledgeBase::getCurrentGoals, &kb); // planning and mission filter kb.plan_filter.notification_publisher = n.advertise<rosplan_knowledge_msgs::Notification>("/kcl_rosplan/notification", 10, true); ros::Subscriber planningFilterSub = n.subscribe("/kcl_rosplan/plan_filter", 100, &KCL_rosplan::PlanFilter::planningFilterCallback, &kb.plan_filter); ros::Subscriber missionFilterSub = n.subscribe("/kcl_rosplan/plan_filter", 100, &KCL_rosplan::PlanFilter::missionFilterCallback, &kb.plan_filter); // wait for and clear mongoDB ROS_INFO("KCL: (KB) Waiting for MongoDB"); ros::service::waitForService("/message_store/delete",-1); system("mongo message_store --eval \"printjson(db.message_store.remove())\""); ROS_INFO("KCL: (KB) Ready to receive"); ros::spin(); return 0; }
38.115764
168
0.708562
Emresav