hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
3cea8a7a69c5d9848c8e5526ef045920898444b4
5,237
cc
C++
mindspore/lite/src/delegate/npu/op/resize_npu.cc
Vincent34/mindspore
a39a60878a46e7e9cb02db788c0bca478f2fa6e5
[ "Apache-2.0" ]
null
null
null
mindspore/lite/src/delegate/npu/op/resize_npu.cc
Vincent34/mindspore
a39a60878a46e7e9cb02db788c0bca478f2fa6e5
[ "Apache-2.0" ]
null
null
null
mindspore/lite/src/delegate/npu/op/resize_npu.cc
Vincent34/mindspore
a39a60878a46e7e9cb02db788c0bca478f2fa6e5
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2020-2021 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "src/delegate/npu/op/resize_npu.h" #include <memory> #include "src/delegate/npu/npu_converter_utils.h" namespace mindspore { int ResizeNPUOp::IsSupport(const schema::Primitive *primitive, const std::vector<tensor::MSTensor *> &in_tensors, const std::vector<tensor::MSTensor *> &out_tensors) { auto resize_prim = primitive->value_as_Resize(); if (resize_prim == nullptr) { MS_LOG(ERROR) << "Get null primitive value for op ." << name_; return RET_ERROR; } resize_method_ = resize_prim->method(); if (resize_method_ != schema::ResizeMethod_LINEAR && resize_method_ != schema::ResizeMethod_NEAREST) { MS_LOG(WARNING) << "Unsupported resize method type: " << resize_method_; return RET_NOT_SUPPORT; } if (in_tensors[0]->shape()[1] > out_tensors[0]->shape()[1] || in_tensors[0]->shape()[2] > out_tensors[0]->shape()[2]) { MS_LOG(WARNING) << "Npu resize does not support reduction."; return RET_NOT_SUPPORT; } return RET_OK; } int ResizeNPUOp::Init(const schema::Primitive *primitive, const std::vector<tensor::MSTensor *> &in_tensors, const std::vector<tensor::MSTensor *> &out_tensors) { auto resize_prim = primitive->value_as_Resize(); if (resize_prim == nullptr) { MS_LOG(ERROR) << "Get null primitive value for op ." << name_; return RET_ERROR; } if (in_tensors.size() == 1) { new_height_ = resize_prim->new_height(); new_width_ = resize_prim->new_width(); } else if (in_tensors.size() == 2) { auto out_size = in_tensors.at(1)->data(); if (out_size == nullptr) { MS_LOG(ERROR) << "Out size is not assigned"; return RET_ERROR; } new_height_ = out_tensors.at(0)->shape().at(1); new_width_ = out_tensors.at(0)->shape().at(2); } else { MS_LOG(ERROR) << "Get resize op new_height and new_width error."; return RET_ERROR; } ge::TensorDesc sizeTensorDesc(ge::Shape({2}), ge::FORMAT_NCHW, ge::DT_INT32); ge::TensorPtr sizeTensor = std::make_shared<hiai::Tensor>(sizeTensorDesc); vector<int32_t> dataValue = {static_cast<int32_t>(new_height_), static_cast<int32_t>(new_width_)}; sizeTensor->SetData(reinterpret_cast<uint8_t *>(dataValue.data()), 2 * sizeof(int32_t)); out_size_ = new (std::nothrow) hiai::op::Const(name_ + "_size"); out_size_->set_attr_value(sizeTensor); if (resize_method_ == schema::ResizeMethod_LINEAR) { auto resize_bilinear = new (std::nothrow) hiai::op::ResizeBilinearV2(name_); if (resize_bilinear == nullptr) { MS_LOG(ERROR) << " resize_ is nullptr."; return RET_ERROR; } resize_bilinear->set_attr_align_corners(resize_prim->coordinate_transform_mode() == schema::CoordinateTransformMode_ALIGN_CORNERS); resize_bilinear->set_input_size(*out_size_); resize_bilinear->set_attr_half_pixel_centers(resize_prim->preserve_aspect_ratio()); resize_ = resize_bilinear; } else if (resize_method_ == schema::ResizeMethod_NEAREST) { auto resize_nearest = new (std::nothrow) hiai::op::ResizeNearestNeighborV2(name_); if (resize_nearest == nullptr) { MS_LOG(ERROR) << " resize_ is nullptr."; return RET_ERROR; } resize_nearest->set_attr_align_corners(resize_prim->coordinate_transform_mode() == schema::CoordinateTransformMode_ALIGN_CORNERS); resize_nearest->set_input_size(*out_size_); } else { MS_LOG(WARNING) << "Unsupported resize method type:" << resize_method_; return RET_ERROR; } return RET_OK; } int ResizeNPUOp::SetNPUInputs(const std::vector<tensor::MSTensor *> &in_tensors, const std::vector<tensor::MSTensor *> &out_tensors, const std::vector<ge::Operator *> &npu_inputs) { if (resize_method_ == schema::ResizeMethod_LINEAR) { auto resize_bilinear = reinterpret_cast<hiai::op::ResizeBilinearV2 *>(resize_); resize_bilinear->set_input_x(*npu_inputs[0]); } else if (resize_method_ == schema::ResizeMethod_NEAREST) { auto resize_nearest = reinterpret_cast<hiai::op::ResizeNearestNeighborV2 *>(resize_); resize_nearest->set_input_x(*npu_inputs[0]); } else { MS_LOG(WARNING) << "Unsupported resize method type:" << resize_method_; return RET_ERROR; } return RET_OK; } ge::Operator *ResizeNPUOp::GetNPUOp() { return this->resize_; } ResizeNPUOp::~ResizeNPUOp() { if (resize_ != nullptr) { delete resize_; resize_ = nullptr; } if (out_size_ != nullptr) { delete out_size_; out_size_ = nullptr; } } } // namespace mindspore
40.596899
113
0.681688
Vincent34
3cecf3a259e168980807cb0d7d99953dd41b5975
28,125
cc
C++
chrome/browser/protector/protector_service_browsertest.cc
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
1
2019-04-23T15:57:04.000Z
2019-04-23T15:57:04.000Z
chrome/browser/protector/protector_service_browsertest.cc
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
null
null
null
chrome/browser/protector/protector_service_browsertest.cc
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/protector/mock_setting_change.h" #include "chrome/browser/protector/protector_service.h" #include "chrome/browser/protector/protector_service_factory.h" #include "chrome/browser/protector/settings_change_global_error.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/global_error.h" #include "chrome/browser/ui/global_error_bubble_view_base.h" #include "chrome/browser/ui/global_error_service.h" #include "chrome/browser/ui/global_error_service_factory.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" using ::testing::InvokeWithoutArgs; using ::testing::NiceMock; using ::testing::Return; namespace protector { class ProtectorServiceTest : public InProcessBrowserTest { public: virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE { // Make sure protector is enabled. command_line->AppendSwitch(switches::kProtector); } virtual void SetUpOnMainThread() OVERRIDE { protector_service_ = ProtectorServiceFactory::GetForProfile(browser()->profile()); // ProtectService will own this change instance. mock_change_ = new NiceMock<MockSettingChange>(); } protected: GlobalError* GetGlobalError(BaseSettingChange* change) { for (ProtectorService::Items::iterator item = protector_service_->items_.begin(); item != protector_service_->items_.end(); item++) { if (item->change.get() == change) return item->error.get(); } return NULL; } // Checks that |protector_service_| has an error instance corresponding to // |change| and that GlobalErrorService knows about it. bool IsGlobalErrorActive(BaseSettingChange* change) { GlobalError* error = GetGlobalError(change); if (!error) return false; if (!GlobalErrorServiceFactory::GetForProfile(browser()->profile())-> GetGlobalErrorByMenuItemCommandID(error->MenuItemCommandID())) { return false; } return protector_service_->IsShowingChange(); } ProtectorService* protector_service_; MockSettingChange* mock_change_; }; IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, ChangeInitError) { // Init fails and causes the change to be ignored. EXPECT_CALL(*mock_change_, MockInit(browser()->profile())). WillOnce(Return(false)); protector_service_->ShowChange(mock_change_); EXPECT_FALSE(IsGlobalErrorActive(mock_change_)); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(IsGlobalErrorActive(mock_change_)); EXPECT_FALSE(protector_service_->GetLastChange()); } IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, ShowAndDismiss) { // Show the change and immediately dismiss it. EXPECT_CALL(*mock_change_, MockInit(browser()->profile())). WillOnce(Return(true)); protector_service_->ShowChange(mock_change_); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_TRUE(IsGlobalErrorActive(mock_change_)); EXPECT_EQ(mock_change_, protector_service_->GetLastChange()); protector_service_->DismissChange(mock_change_); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(IsGlobalErrorActive(mock_change_)); EXPECT_FALSE(protector_service_->GetLastChange()); } IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, ShowAndApply) { // Show the change and apply it. EXPECT_CALL(*mock_change_, MockInit(browser()->profile())). WillOnce(Return(true)); protector_service_->ShowChange(mock_change_); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_TRUE(IsGlobalErrorActive(mock_change_)); EXPECT_CALL(*mock_change_, Apply(browser())); protector_service_->ApplyChange(mock_change_, browser()); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(IsGlobalErrorActive(mock_change_)); } // ProtectorServiceTest.ShowAndApplyManually is timing out frequently on Win // bots. http://crbug.com/130590 #if defined(OS_WIN) #define MAYBE_ShowAndApplyManually DISABLED_ShowAndApplyManually #else #define MAYBE_ShowAndApplyManually ShowAndApplyManually #endif IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, MAYBE_ShowAndApplyManually) { // Show the change and apply it, mimicking a button click. EXPECT_CALL(*mock_change_, MockInit(browser()->profile())). WillOnce(Return(true)); protector_service_->ShowChange(mock_change_); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_TRUE(IsGlobalErrorActive(mock_change_)); EXPECT_CALL(*mock_change_, Apply(browser())); // Pressing Cancel applies the change. GlobalError* error = GetGlobalError(mock_change_); ASSERT_TRUE(error); error->BubbleViewCancelButtonPressed(browser()); error->GetBubbleView()->CloseBubbleView(); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(IsGlobalErrorActive(mock_change_)); } IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, ShowAndDiscard) { // Show the change and discard it. EXPECT_CALL(*mock_change_, MockInit(browser()->profile())). WillOnce(Return(true)); protector_service_->ShowChange(mock_change_); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_TRUE(IsGlobalErrorActive(mock_change_)); EXPECT_CALL(*mock_change_, Discard(browser())); protector_service_->DiscardChange(mock_change_, browser()); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(IsGlobalErrorActive(mock_change_)); } IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, ShowAndDiscardManually) { // Show the change and discard it, mimicking a button click. EXPECT_CALL(*mock_change_, MockInit(browser()->profile())). WillOnce(Return(true)); protector_service_->ShowChange(mock_change_); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_TRUE(IsGlobalErrorActive(mock_change_)); EXPECT_CALL(*mock_change_, Discard(browser())); // Pressing Apply discards the change. GlobalError* error = GetGlobalError(mock_change_); ASSERT_TRUE(error); error->BubbleViewAcceptButtonPressed(browser()); error->GetBubbleView()->CloseBubbleView(); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(IsGlobalErrorActive(mock_change_)); } IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, BubbleClosedInsideApply) { EXPECT_CALL(*mock_change_, MockInit(browser()->profile())). WillOnce(Return(true)); protector_service_->ShowChange(mock_change_); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_TRUE(IsGlobalErrorActive(mock_change_)); GlobalError* error = GetGlobalError(mock_change_); ASSERT_TRUE(error); GlobalErrorBubbleViewBase* bubble_view = error->GetBubbleView(); ASSERT_TRUE(bubble_view); EXPECT_CALL(*mock_change_, Apply(browser())).WillOnce(InvokeWithoutArgs( bubble_view, &GlobalErrorBubbleViewBase::CloseBubbleView)); // Pressing Cancel applies the change. error->BubbleViewCancelButtonPressed(browser()); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(IsGlobalErrorActive(mock_change_)); } IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, ShowMultipleChangesAndApply) { // Show the first change. EXPECT_CALL(*mock_change_, MockInit(browser()->profile())). WillOnce(Return(true)); protector_service_->ShowChange(mock_change_); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_TRUE(IsGlobalErrorActive(mock_change_)); EXPECT_EQ(mock_change_, protector_service_->GetLastChange()); // ProtectService will own this change instance as well. MockSettingChange* mock_change2 = new NiceMock<MockSettingChange>(); // Show the second change. EXPECT_CALL(*mock_change2, MockInit(browser()->profile())). WillOnce(Return(true)); EXPECT_CALL(*mock_change2, CanBeMerged()).WillRepeatedly(Return(false)); protector_service_->ShowChange(mock_change2); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_TRUE(IsGlobalErrorActive(mock_change_)); EXPECT_TRUE(IsGlobalErrorActive(mock_change2)); EXPECT_EQ(mock_change2, protector_service_->GetLastChange()); // Apply the first change, the second should still be active. EXPECT_CALL(*mock_change_, Apply(browser())); protector_service_->ApplyChange(mock_change_, browser()); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(IsGlobalErrorActive(mock_change_)); EXPECT_TRUE(IsGlobalErrorActive(mock_change2)); EXPECT_EQ(mock_change2, protector_service_->GetLastChange()); // Finally apply the second change. EXPECT_CALL(*mock_change2, Apply(browser())); protector_service_->ApplyChange(mock_change2, browser()); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(IsGlobalErrorActive(mock_change_)); EXPECT_FALSE(IsGlobalErrorActive(mock_change2)); EXPECT_FALSE(protector_service_->GetLastChange()); } IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, ShowMultipleChangesDismissAndApply) { // Show the first change. EXPECT_CALL(*mock_change_, MockInit(browser()->profile())). WillOnce(Return(true)); protector_service_->ShowChange(mock_change_); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_TRUE(IsGlobalErrorActive(mock_change_)); // ProtectService will own this change instance as well. MockSettingChange* mock_change2 = new NiceMock<MockSettingChange>(); // Show the second change. EXPECT_CALL(*mock_change2, MockInit(browser()->profile())). WillOnce(Return(true)); EXPECT_CALL(*mock_change2, CanBeMerged()).WillRepeatedly(Return(false)); protector_service_->ShowChange(mock_change2); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_TRUE(IsGlobalErrorActive(mock_change_)); EXPECT_TRUE(IsGlobalErrorActive(mock_change2)); // Dismiss the first change, the second should still be active. protector_service_->DismissChange(mock_change_); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(IsGlobalErrorActive(mock_change_)); EXPECT_TRUE(IsGlobalErrorActive(mock_change2)); // Finally apply the second change. EXPECT_CALL(*mock_change2, Apply(browser())); protector_service_->ApplyChange(mock_change2, browser()); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(IsGlobalErrorActive(mock_change_)); EXPECT_FALSE(IsGlobalErrorActive(mock_change2)); } IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, ShowMultipleChangesAndApplyManually) { // Show the first change. EXPECT_CALL(*mock_change_, MockInit(browser()->profile())). WillOnce(Return(true)); protector_service_->ShowChange(mock_change_); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_TRUE(IsGlobalErrorActive(mock_change_)); // The first bubble view has been displayed. GlobalError* error = GetGlobalError(mock_change_); ASSERT_TRUE(error); ASSERT_TRUE(error->HasShownBubbleView()); // ProtectService will own this change instance as well. MockSettingChange* mock_change2 = new NiceMock<MockSettingChange>(); // Show the second change. EXPECT_CALL(*mock_change2, MockInit(browser()->profile())). WillOnce(Return(true)); EXPECT_CALL(*mock_change2, CanBeMerged()).WillRepeatedly(Return(false)); protector_service_->ShowChange(mock_change2); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_TRUE(IsGlobalErrorActive(mock_change_)); EXPECT_TRUE(IsGlobalErrorActive(mock_change2)); // The second bubble view hasn't been displayed because the first is still // shown. GlobalError* error2 = GetGlobalError(mock_change2); ASSERT_TRUE(error2); EXPECT_FALSE(error2->HasShownBubbleView()); // Apply the first change, mimicking a button click; the second should still // be active. EXPECT_CALL(*mock_change_, Apply(browser())); error->BubbleViewCancelButtonPressed(browser()); error->GetBubbleView()->CloseBubbleView(); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(IsGlobalErrorActive(mock_change_)); EXPECT_TRUE(IsGlobalErrorActive(mock_change2)); // Now the second bubble view should be shown. ASSERT_TRUE(error2->HasShownBubbleView()); // Finally apply the second change. EXPECT_CALL(*mock_change2, Apply(browser())); error2->BubbleViewCancelButtonPressed(browser()); error2->GetBubbleView()->CloseBubbleView(); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(IsGlobalErrorActive(mock_change_)); EXPECT_FALSE(IsGlobalErrorActive(mock_change2)); } IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, ShowMultipleChangesAndApplyManuallyBeforeOther) { // Show the first change. EXPECT_CALL(*mock_change_, MockInit(browser()->profile())). WillOnce(Return(true)); protector_service_->ShowChange(mock_change_); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_TRUE(IsGlobalErrorActive(mock_change_)); // The first bubble view has been displayed. GlobalError* error = GetGlobalError(mock_change_); ASSERT_TRUE(error); ASSERT_TRUE(error->HasShownBubbleView()); // Apply the first change, mimicking a button click. EXPECT_CALL(*mock_change_, Apply(browser())); error->BubbleViewCancelButtonPressed(browser()); error->GetBubbleView()->CloseBubbleView(); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(IsGlobalErrorActive(mock_change_)); // ProtectService will own this change instance as well. MockSettingChange* mock_change2 = new NiceMock<MockSettingChange>(); // Show the second change. EXPECT_CALL(*mock_change2, MockInit(browser()->profile())). WillOnce(Return(true)); EXPECT_CALL(*mock_change2, CanBeMerged()).WillRepeatedly(Return(false)); protector_service_->ShowChange(mock_change2); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_TRUE(IsGlobalErrorActive(mock_change2)); // The second bubble view has been displayed. GlobalError* error2 = GetGlobalError(mock_change2); ASSERT_TRUE(error2); ASSERT_TRUE(error2->HasShownBubbleView()); // Finally apply the second change. EXPECT_CALL(*mock_change2, Apply(browser())); error2->BubbleViewCancelButtonPressed(browser()); error2->GetBubbleView()->CloseBubbleView(); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(IsGlobalErrorActive(mock_change2)); } IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, ShowMultipleDifferentURLs) { GURL url1("http://example.com/"); GURL url2("http://example.net/"); // Show the first change with some non-empty URL. EXPECT_CALL(*mock_change_, MockInit(browser()->profile())). WillOnce(Return(true)); EXPECT_CALL(*mock_change_, GetNewSettingURL()).WillRepeatedly(Return(url1)); EXPECT_CALL(*mock_change_, CanBeMerged()).WillRepeatedly(Return(true)); protector_service_->ShowChange(mock_change_); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_TRUE(IsGlobalErrorActive(mock_change_)); EXPECT_EQ(mock_change_, protector_service_->GetLastChange()); // ProtectService will own this change instance as well. MockSettingChange* mock_change2 = new NiceMock<MockSettingChange>(); // Show the second change with another non-empty URL. EXPECT_CALL(*mock_change2, MockInit(browser()->profile())). WillOnce(Return(true)); EXPECT_CALL(*mock_change2, GetNewSettingURL()).WillRepeatedly(Return(url2)); EXPECT_CALL(*mock_change2, CanBeMerged()).WillRepeatedly(Return(true)); protector_service_->ShowChange(mock_change2); ui_test_utils::RunAllPendingInMessageLoop(); // Both changes are shown separately, not composited. EXPECT_TRUE(IsGlobalErrorActive(mock_change_)); EXPECT_TRUE(IsGlobalErrorActive(mock_change2)); EXPECT_EQ(mock_change2, protector_service_->GetLastChange()); protector_service_->DismissChange(mock_change_); protector_service_->DismissChange(mock_change2); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(protector_service_->GetLastChange()); } IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, ShowCompositeAndDismiss) { GURL url1("http://example.com/"); // Show the first change. EXPECT_CALL(*mock_change_, MockInit(browser()->profile())). WillOnce(Return(true)); EXPECT_CALL(*mock_change_, GetNewSettingURL()).WillRepeatedly(Return(url1)); EXPECT_CALL(*mock_change_, CanBeMerged()).WillRepeatedly(Return(true)); protector_service_->ShowChange(mock_change_); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_TRUE(IsGlobalErrorActive(mock_change_)); EXPECT_EQ(mock_change_, protector_service_->GetLastChange()); // The first bubble view has been displayed. GlobalError* error = GetGlobalError(mock_change_); ASSERT_TRUE(error); EXPECT_TRUE(error->HasShownBubbleView()); // ProtectService will own this change instance as well. MockSettingChange* mock_change2 = new NiceMock<MockSettingChange>(); // Show the second change. EXPECT_CALL(*mock_change2, MockInit(browser()->profile())). WillOnce(Return(true)); EXPECT_CALL(*mock_change2, GetNewSettingURL()).WillRepeatedly(Return(url1)); EXPECT_CALL(*mock_change2, CanBeMerged()).WillRepeatedly(Return(true)); protector_service_->ShowChange(mock_change2); ui_test_utils::RunAllPendingInMessageLoop(); // Now ProtectorService should be showing a single composite change. EXPECT_FALSE(IsGlobalErrorActive(mock_change_)); EXPECT_FALSE(IsGlobalErrorActive(mock_change2)); BaseSettingChange* composite_change = protector_service_->GetLastChange(); ASSERT_TRUE(composite_change); EXPECT_TRUE(IsGlobalErrorActive(composite_change)); // The second (composite) bubble view has been displayed. GlobalError* error2 = GetGlobalError(composite_change); ASSERT_TRUE(error2); EXPECT_TRUE(error2->HasShownBubbleView()); protector_service_->DismissChange(composite_change); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(IsGlobalErrorActive(composite_change)); EXPECT_FALSE(protector_service_->GetLastChange()); // Show the third change. MockSettingChange* mock_change3 = new NiceMock<MockSettingChange>(); EXPECT_CALL(*mock_change3, MockInit(browser()->profile())). WillOnce(Return(true)); EXPECT_CALL(*mock_change3, GetNewSettingURL()).WillRepeatedly(Return(url1)); EXPECT_CALL(*mock_change3, CanBeMerged()).WillRepeatedly(Return(true)); protector_service_->ShowChange(mock_change3); ui_test_utils::RunAllPendingInMessageLoop(); // The third change should not be composed with the previous. EXPECT_TRUE(IsGlobalErrorActive(mock_change3)); EXPECT_EQ(mock_change3, protector_service_->GetLastChange()); protector_service_->DismissChange(mock_change3); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(IsGlobalErrorActive(mock_change3)); EXPECT_FALSE(protector_service_->GetLastChange()); } IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, ShowCompositeAndOther) { GURL url1("http://example.com/"); GURL url2("http://example.net/"); // Show the first change. EXPECT_CALL(*mock_change_, MockInit(browser()->profile())). WillOnce(Return(true)); EXPECT_CALL(*mock_change_, GetNewSettingURL()).WillRepeatedly(Return(url1)); EXPECT_CALL(*mock_change_, CanBeMerged()).WillRepeatedly(Return(true)); protector_service_->ShowChange(mock_change_); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_TRUE(IsGlobalErrorActive(mock_change_)); EXPECT_EQ(mock_change_, protector_service_->GetLastChange()); // ProtectService will own this change instance as well. MockSettingChange* mock_change2 = new NiceMock<MockSettingChange>(); // Show the second change. EXPECT_CALL(*mock_change2, MockInit(browser()->profile())). WillOnce(Return(true)); EXPECT_CALL(*mock_change2, GetNewSettingURL()).WillRepeatedly(Return(url1)); EXPECT_CALL(*mock_change2, CanBeMerged()).WillRepeatedly(Return(true)); protector_service_->ShowChange(mock_change2); ui_test_utils::RunAllPendingInMessageLoop(); // Now ProtectorService should be showing a single composite change. BaseSettingChange* composite_change = protector_service_->GetLastChange(); ASSERT_TRUE(composite_change); EXPECT_TRUE(IsGlobalErrorActive(composite_change)); // Show the third change, with the same URL as 1st and 2nd. MockSettingChange* mock_change3 = new NiceMock<MockSettingChange>(); EXPECT_CALL(*mock_change3, MockInit(browser()->profile())). WillOnce(Return(true)); EXPECT_CALL(*mock_change3, GetNewSettingURL()).WillRepeatedly(Return(url1)); EXPECT_CALL(*mock_change3, CanBeMerged()).WillRepeatedly(Return(true)); protector_service_->ShowChange(mock_change3); ui_test_utils::RunAllPendingInMessageLoop(); // The third change should be composed with the previous. EXPECT_FALSE(IsGlobalErrorActive(mock_change3)); EXPECT_EQ(composite_change, protector_service_->GetLastChange()); EXPECT_TRUE(IsGlobalErrorActive(composite_change)); // Show the 4th change, now with a different URL. MockSettingChange* mock_change4 = new NiceMock<MockSettingChange>(); EXPECT_CALL(*mock_change4, MockInit(browser()->profile())). WillOnce(Return(true)); EXPECT_CALL(*mock_change4, GetNewSettingURL()).WillRepeatedly(Return(url2)); EXPECT_CALL(*mock_change4, CanBeMerged()).WillRepeatedly(Return(true)); protector_service_->ShowChange(mock_change4); ui_test_utils::RunAllPendingInMessageLoop(); // The 4th change is shown independently. EXPECT_TRUE(IsGlobalErrorActive(composite_change)); EXPECT_TRUE(IsGlobalErrorActive(mock_change4)); EXPECT_EQ(mock_change4, protector_service_->GetLastChange()); protector_service_->DismissChange(composite_change); protector_service_->DismissChange(mock_change4); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(IsGlobalErrorActive(composite_change)); EXPECT_FALSE(IsGlobalErrorActive(mock_change4)); EXPECT_FALSE(protector_service_->GetLastChange()); } IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, ShowCompositeAndDismissSingle) { GURL url1("http://example.com/"); GURL url2("http://example.net/"); // Show the first change. EXPECT_CALL(*mock_change_, MockInit(browser()->profile())). WillOnce(Return(true)); EXPECT_CALL(*mock_change_, GetNewSettingURL()).WillRepeatedly(Return(url1)); EXPECT_CALL(*mock_change_, CanBeMerged()).WillRepeatedly(Return(true)); protector_service_->ShowChange(mock_change_); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_TRUE(IsGlobalErrorActive(mock_change_)); EXPECT_EQ(mock_change_, protector_service_->GetLastChange()); // ProtectService will own this change instance as well. MockSettingChange* mock_change2 = new NiceMock<MockSettingChange>(); // Show the second change. EXPECT_CALL(*mock_change2, MockInit(browser()->profile())). WillOnce(Return(true)); EXPECT_CALL(*mock_change2, GetNewSettingURL()).WillRepeatedly(Return(url1)); EXPECT_CALL(*mock_change2, CanBeMerged()).WillRepeatedly(Return(true)); protector_service_->ShowChange(mock_change2); ui_test_utils::RunAllPendingInMessageLoop(); // Now ProtectorService should be showing a single composite change. EXPECT_FALSE(IsGlobalErrorActive(mock_change_)); EXPECT_FALSE(IsGlobalErrorActive(mock_change2)); BaseSettingChange* composite_change = protector_service_->GetLastChange(); ASSERT_TRUE(composite_change); EXPECT_TRUE(IsGlobalErrorActive(composite_change)); // Show the third change with a different URL. MockSettingChange* mock_change3 = new NiceMock<MockSettingChange>(); EXPECT_CALL(*mock_change3, MockInit(browser()->profile())). WillOnce(Return(true)); EXPECT_CALL(*mock_change3, GetNewSettingURL()).WillRepeatedly(Return(url2)); EXPECT_CALL(*mock_change3, CanBeMerged()).WillRepeatedly(Return(true)); protector_service_->ShowChange(mock_change3); ui_test_utils::RunAllPendingInMessageLoop(); // The third change should not be composed with the previous. EXPECT_TRUE(IsGlobalErrorActive(mock_change3)); EXPECT_TRUE(IsGlobalErrorActive(composite_change)); EXPECT_EQ(mock_change3, protector_service_->GetLastChange()); // Now dismiss the first change. protector_service_->DismissChange(mock_change_); ui_test_utils::RunAllPendingInMessageLoop(); // This should effectively dismiss the whole composite change. EXPECT_FALSE(IsGlobalErrorActive(composite_change)); EXPECT_TRUE(IsGlobalErrorActive(mock_change3)); EXPECT_EQ(mock_change3, protector_service_->GetLastChange()); protector_service_->DismissChange(mock_change3); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(IsGlobalErrorActive(mock_change3)); EXPECT_FALSE(protector_service_->GetLastChange()); } // Verifies that changes with different URLs but same domain are merged. IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, SameDomainDifferentURLs) { GURL url1("http://www.example.com/abc"); GURL url2("http://example.com/def"); // Show the first change with some non-empty URL. EXPECT_CALL(*mock_change_, MockInit(browser()->profile())). WillOnce(Return(true)); EXPECT_CALL(*mock_change_, GetNewSettingURL()).WillRepeatedly(Return(url1)); EXPECT_CALL(*mock_change_, CanBeMerged()).WillRepeatedly(Return(true)); protector_service_->ShowChange(mock_change_); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_TRUE(IsGlobalErrorActive(mock_change_)); EXPECT_EQ(mock_change_, protector_service_->GetLastChange()); // ProtectService will own this change instance as well. MockSettingChange* mock_change2 = new NiceMock<MockSettingChange>(); // Show the second change with another non-empty URL having same domain. EXPECT_CALL(*mock_change2, MockInit(browser()->profile())). WillOnce(Return(true)); EXPECT_CALL(*mock_change2, GetNewSettingURL()).WillRepeatedly(Return(url2)); EXPECT_CALL(*mock_change2, CanBeMerged()).WillRepeatedly(Return(true)); protector_service_->ShowChange(mock_change2); ui_test_utils::RunAllPendingInMessageLoop(); // Changes should be merged. EXPECT_FALSE(IsGlobalErrorActive(mock_change_)); EXPECT_FALSE(IsGlobalErrorActive(mock_change2)); BaseSettingChange* composite_change = protector_service_->GetLastChange(); ASSERT_TRUE(composite_change); EXPECT_TRUE(IsGlobalErrorActive(composite_change)); protector_service_->DismissChange(composite_change); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(IsGlobalErrorActive(composite_change)); EXPECT_FALSE(protector_service_->GetLastChange()); } // Verifies that changes with different Google URLs are merged. IN_PROC_BROWSER_TEST_F(ProtectorServiceTest, DifferentGoogleDomains) { GURL url1("http://www.google.com/search?q="); GURL url2("http://google.ru/search?q="); // Show the first change with some non-empty URL. EXPECT_CALL(*mock_change_, MockInit(browser()->profile())). WillOnce(Return(true)); EXPECT_CALL(*mock_change_, GetNewSettingURL()).WillRepeatedly(Return(url1)); EXPECT_CALL(*mock_change_, CanBeMerged()).WillRepeatedly(Return(true)); protector_service_->ShowChange(mock_change_); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_TRUE(IsGlobalErrorActive(mock_change_)); EXPECT_EQ(mock_change_, protector_service_->GetLastChange()); // ProtectService will own this change instance as well. MockSettingChange* mock_change2 = new NiceMock<MockSettingChange>(); // Show the second change with another non-empty URL having same domain. EXPECT_CALL(*mock_change2, MockInit(browser()->profile())). WillOnce(Return(true)); EXPECT_CALL(*mock_change2, GetNewSettingURL()).WillRepeatedly(Return(url2)); EXPECT_CALL(*mock_change2, CanBeMerged()).WillRepeatedly(Return(true)); protector_service_->ShowChange(mock_change2); ui_test_utils::RunAllPendingInMessageLoop(); // Changes should be merged. EXPECT_FALSE(IsGlobalErrorActive(mock_change_)); EXPECT_FALSE(IsGlobalErrorActive(mock_change2)); BaseSettingChange* composite_change = protector_service_->GetLastChange(); ASSERT_TRUE(composite_change); EXPECT_TRUE(IsGlobalErrorActive(composite_change)); protector_service_->DismissChange(composite_change); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(IsGlobalErrorActive(composite_change)); EXPECT_FALSE(protector_service_->GetLastChange()); } // TODO(ivankr): Timeout test. } // namespace protector
42.808219
78
0.780978
1065672644894730302
3cee5c9c41096baec5a2fa929d822d9f616f7af5
968
cpp
C++
leetcode-problems/medium/17-phone-number.cpp
formatkaka/dsalgo
a7c7386c5c161e23bc94456f93cadd0f91f102fa
[ "Unlicense" ]
null
null
null
leetcode-problems/medium/17-phone-number.cpp
formatkaka/dsalgo
a7c7386c5c161e23bc94456f93cadd0f91f102fa
[ "Unlicense" ]
null
null
null
leetcode-problems/medium/17-phone-number.cpp
formatkaka/dsalgo
a7c7386c5c161e23bc94456f93cadd0f91f102fa
[ "Unlicense" ]
null
null
null
// // Created by Siddhant on 2019-11-15. // #include "iostream" #include "vector" #include "string" using namespace std; vector<string> map = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; vector<string> letterCombinations(string digits) { vector<string> s; vector<string> old; for (int i = 0; i < digits.size(); i++) { int digit = digits[i] - '0'; if (s.empty()) { for (int j = 0; j < map[digit].size(); j++) { string character(1,map[digit][j]); s.push_back(character); } old = s; continue; } s = {}; for (int j = 0; j < map[digit].size(); j++) { for (int k = 0; k < old.size(); k++) { s.push_back(old[k] + map[digit][j]); } } old = s; } return s; } int main() { letterCombinations("23"); cout << "hello"; return 0; }
18.264151
88
0.44938
formatkaka
3ceeffa74ff7d034e15e310b190f62700940aa1d
840
hpp
C++
SDK/ARKSurvivalEvolved_MissionRace_Interface_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_MissionRace_Interface_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_MissionRace_Interface_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_MissionRace_Interface_structs.hpp" namespace sdk { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass MissionRace_Interface.MissionRace_Interface_C // 0x0000 (0x0028 - 0x0028) class UMissionRace_Interface_C : public UInterface { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass MissionRace_Interface.MissionRace_Interface_C"); return ptr; } void GetPlayerRanking(int PlayerIndex, int* Ranking); void GetRaceData(TArray<struct FRacePlayerData>* RaceData); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
21
112
0.638095
2bite
3cf2225aa62bdc226603bb84188fa7a1a8dd50b6
24,500
cpp
C++
src/examples/scene.cpp
SCIInstitute/SCI-Solver_Peridynamic
b0b6b82151bbfdea5365bca156b449ca671cddc1
[ "MIT" ]
14
2018-02-01T08:26:26.000Z
2021-12-18T11:37:26.000Z
src/examples/scene.cpp
SCIInstitute/SCI-Solver_Peridynamic
b0b6b82151bbfdea5365bca156b449ca671cddc1
[ "MIT" ]
null
null
null
src/examples/scene.cpp
SCIInstitute/SCI-Solver_Peridynamic
b0b6b82151bbfdea5365bca156b449ca671cddc1
[ "MIT" ]
4
2018-05-30T05:11:34.000Z
2021-05-08T09:06:29.000Z
//------------------------------------------------------------------------------------------ // // // Created on: 2/1/2015 // Author: Nghia Truong // //------------------------------------------------------------------------------------------ #include <iostream> #include <cmath> #include <core/helper_math.h> #include "scene.h" #include "core/cutil_math_ext.h" #include "core/monitor.h" #include "cyTriMesh.h" //------------------------------------------------------------------------------------------ Scene::Scene(SimulationParameters& simParams, RunningParameters& runningParams, ParticleArrangement _arrangement): simParams_(simParams), runningParams_(runningParams), arrangement_(_arrangement) { if(simParams_.num_pd_particle == 0) { return; } cyTriMesh triMesh; triMesh.LoadFromFileObj(runningParams_.obj_file); triMesh.ComputeBoundingBox(); cyPoint3f box_min = triMesh.GetBoundMin(); cyPoint3f box_max = triMesh.GetBoundMax(); cyPoint3f diff = box_max - box_min; double maxDiff = fmaxf(fmaxf(fabs(diff.x), fabs(diff.y)), fabs(diff.z)); double scale = fminf(fminf(simParams_.boundary_max_x - simParams_.boundary_min_x, simParams_.boundary_max_y - simParams_.boundary_min_y), simParams_.boundary_max_z - simParams_.boundary_min_z) * 0.9 / maxDiff; // how small the mesh object will be: scale *= 0.5f; // scale /= simParams_.scaleFactor; // scale = fmin(scale*0.9, 1.0); box_min.x *= scale; box_min.y *= scale; box_min.z *= scale; box_max.x *= scale; box_max.y *= scale; box_max.z *= scale; // translate the object if needed double shift_x = simParams_.boundary_min_x - box_min.x; double shift_y = simParams_.boundary_min_y - box_min.y; double shift_z = simParams_.boundary_min_z - box_min.z; box_min.x += shift_x; box_max.x += shift_x; box_min.y += shift_y; box_max.y += shift_y; box_min.z += shift_z; box_max.z += shift_z; std::cout << Monitor::PADDING << "Bounding box for mesh object: [" << box_min.x << ", " << box_min.y << ", " << box_min.z << "] -> [" << box_max.x << ", " << box_max.y << ", " << box_max.z << "]" << std::endl; int grid3d[3]; createPeridynamicsGrid(box_min, box_max, grid3d); int max_num_pd_particles = grid3d[0] * grid3d[1] * grid3d[2]; double* vertices = new double[triMesh.NV() * 3]; int* faces = new int[triMesh.NF() * 3]; for(int i = 0; i < triMesh.NV(); ++i) { cyPoint3f vertex = triMesh.V(i); vertices[i * 3] = (double) vertex[0] * scale + shift_x; vertices[i * 3 + 1] = (double) vertex[1] * scale + shift_y; vertices[i * 3 + 2] = (double) vertex[2] * scale + shift_z; } for(int i = 0; i < triMesh.NF(); ++i) { cyTriMesh::cyTriFace face = triMesh.F(i); faces[i * 3] = (int) face.v[0]; faces[i * 3 + 1] = (int) face.v[1]; faces[i * 3 + 2] = (int) face.v[2]; } MeshObject* meshObject = construct_mesh_object(triMesh.NV(), vertices, triMesh.NF(), faces); pd_position_cache_ = new real4_t[max_num_pd_particles]; real_t jitter; real_t margin; real_t spacing; if(arrangement_ == Scene::REGULAR_GRID) { jitter = 0.0f; } else { jitter = JITTER * simParams_.pd_particle_radius; } margin = simParams_.pd_particle_radius; spacing = 2 * simParams_.pd_particle_radius; simParams_.num_pd_particle = fillParticlesToMesh(meshObject, box_min, box_max, pd_position_cache_, grid3d, spacing, jitter, max_num_pd_particles); simParams_.num_total_particle = simParams_.num_sph_particle + simParams_.num_pd_particle; simParams_.num_clists = simParams_.num_pd_particle; while(simParams_.num_clists % 8 != 0) { simParams_.num_clists++; } // else // { // simParams_.num_clists = (int) (floor(simParams_.num_pd_particle / 8.0) + 1) * 8; // } std::cout << Monitor::PADDING << "Num. clist: " << simParams_.num_clists << std::endl; } //------------------------------------------------------------------------------------------ void Scene::initSPHParticles(int* sph_activity, real4_t* sph_position, real4_t* sph_velocity) { if(simParams_.num_sph_particle == 0) { return; } real_t jitter; real_t margin3d[3]; real_t spacing, border; if(arrangement_ == Scene::REGULAR_GRID) { jitter = 0.0f; } else { jitter = JITTER * simParams_.sph_particle_radius; } margin3d[0] = simParams_.sph_particle_radius; margin3d[1] = simParams_.sph_particle_radius; margin3d[2] = simParams_.sph_particle_radius; spacing = 2 * simParams_.sph_particle_radius; border = simParams_.sph_particle_radius; int grid3d[3]; createSPHGrid(grid3d); srand(1546); fillParticles(sph_position, grid3d, margin3d, border, spacing, jitter, simParams_.num_sph_particle, true); // set the activity and velocity for(int i = 0; i < simParams_.num_sph_particle; ++i) { sph_activity[i] = ACTIVE; sph_velocity[i] = MAKE_REAL4(0, 0, runningParams_.sph_initial_velocity, 0); } } //------------------------------------------------------------------------------------------ inline double kernel_poly6(const real_t t) { double val = 0.0; if(t >= 1.0) { return val; } const double tmp = 1.0 - t; val = tmp * tmp * tmp; return val; } void Scene::initSPHBoundaryParticles(real4_t* sph_boundary_pos) { if(simParams_.num_sph_particle == 0) { return; } int plane_size = simParams_.boundaryPlaneSize; real_t spacing = 2 * simParams_.sph_particle_radius; int index = 0; int num_plane_particles = (plane_size + 2) * (plane_size + 2); simParams_.boundaryPlaneBottomIndex = index; simParams_.boundaryPlaneBottomSize = num_plane_particles; simParams_.boundaryPlaneTopIndex = index + num_plane_particles; simParams_.boundaryPlaneTopSize = num_plane_particles; real_t px, py, pz; // The top and bottom planes have size (size+2)^2 for (int x = 0; x < plane_size + 2; x++) { for (int z = 0; z < plane_size + 2; z++) { // Bottom plane px = spacing * x + simParams_.boundary_min_x - simParams_.sph_particle_radius; py = simParams_.boundary_min_y - simParams_.sph_particle_radius; pz = spacing * z + simParams_.boundary_min_z - simParams_.sph_particle_radius; sph_boundary_pos[index] = MAKE_REAL4(px, py, pz, 0.0f); // Top plane px = spacing * x + simParams_.boundary_min_x - simParams_.sph_particle_radius; py = simParams_.boundary_min_y + simParams_.sph_particle_radius; pz = spacing * z + simParams_.boundary_min_z - simParams_.sph_particle_radius; sph_boundary_pos[index + num_plane_particles] = MAKE_REAL4(px, py, pz, 0.0f); index++; } } index += num_plane_particles; num_plane_particles = (plane_size + 1) * plane_size; simParams_.boundaryPlaneFrontIndex = index; simParams_.boundaryPlaneFrontSize = num_plane_particles; simParams_.boundaryPlaneBackIndex = index + num_plane_particles; simParams_.boundaryPlaneBackSize = num_plane_particles; // Front and back plane have size (size+1)*size for (int x = 0; x < plane_size + 1; x++) { for (int y = 0; y < plane_size; y++) { // Front plane px = spacing * x + simParams_.boundary_min_x + simParams_.sph_particle_radius; py = spacing * y + simParams_.boundary_min_y + simParams_.sph_particle_radius; pz = simParams_.boundary_max_z + simParams_.sph_particle_radius; sph_boundary_pos[index] = MAKE_REAL4(px, py, pz, 0.0f); // Back plane px = spacing * x + simParams_.boundary_min_x - simParams_.sph_particle_radius; py = spacing * y + simParams_.boundary_min_y + simParams_.sph_particle_radius; pz = simParams_.boundary_min_z - simParams_.sph_particle_radius; sph_boundary_pos[index + num_plane_particles] = MAKE_REAL4(px, py, pz, 0.0f); index++; } } index += num_plane_particles; simParams_.boundaryPlaneLeftSideIndex = index; simParams_.boundaryPlaneLeftSideSize = num_plane_particles; simParams_.boundaryPlaneRightSideIndex = index + num_plane_particles; simParams_.boundaryPlaneRightSideSize = num_plane_particles; for (int y = 0; y < plane_size; y++) { for (int z = 0; z < plane_size + 1; z++) { // Left side plane px = simParams_.boundary_min_x - simParams_.sph_particle_radius; py = spacing * y + simParams_.boundary_min_y + simParams_.sph_particle_radius; pz = spacing * z + simParams_.boundary_min_z + simParams_.sph_particle_radius; sph_boundary_pos[index] = MAKE_REAL4(px, py, pz, 0.0f); // Right side plane px = simParams_.boundary_max_x + simParams_.sph_particle_radius; py = spacing * y + simParams_.boundary_min_y + simParams_.sph_particle_radius; pz = spacing * z + simParams_.boundary_min_z - simParams_.sph_particle_radius; sph_boundary_pos[index + num_plane_particles] = MAKE_REAL4(px, py, pz, 0.0f); index++; } } std::cout << Monitor::PADDING << "Boundary planes size: " << plane_size << std::endl; std::cout << Monitor::PADDING << Monitor::PADDING << "Bottom plane index: " << simParams_.boundaryPlaneBottomIndex << ", size: " << simParams_.boundaryPlaneBottomSize << std::endl; std::cout << Monitor::PADDING << Monitor::PADDING << "Top plane index: " << simParams_.boundaryPlaneTopIndex << ", size: " << simParams_.boundaryPlaneTopSize << std::endl; std::cout << Monitor::PADDING << Monitor::PADDING << "Front plane index: " << simParams_.boundaryPlaneFrontIndex << ", size: " << simParams_.boundaryPlaneFrontSize << std::endl; std::cout << Monitor::PADDING << Monitor::PADDING << "Back plane index: " << simParams_.boundaryPlaneBackIndex << ", size: " << simParams_.boundaryPlaneBackSize << std::endl; std::cout << Monitor::PADDING << Monitor::PADDING << "Left plane index: " << simParams_.boundaryPlaneLeftSideIndex << ", size; " << simParams_.boundaryPlaneLeftSideSize << std::endl; std::cout << Monitor::PADDING << Monitor::PADDING << "Right plane index: " << simParams_.boundaryPlaneRightSideIndex << ", size: " << simParams_.boundaryPlaneRightSideSize << std::endl; ///////////////////////////////////////////////////////////////// // calculate rest density real_t dist_sq; double sumW = 0; int span = (int)ceil(simParams_.sph_kernel_coeff / 2); for (int z = -span; z <= span; ++z) { for (int y = -span; y <= span; ++y) { for (int x = -span; x <= span; ++x) { px = 2 * x * simParams_.sph_particle_radius; py = 2 * y * simParams_.sph_particle_radius; pz = 2 * z * simParams_.sph_particle_radius; dist_sq = px * px + py * py + pz * pz; sumW += kernel_poly6(dist_sq / simParams_.sph_kernel_smooth_length_squared); } } } simParams_.sph_rest_density = (real_t) sumW * simParams_.sph_particle_mass * simParams_.sph_kernel_poly6; std::cout << Monitor::PADDING << "SPH rest density: " << simParams_.sph_rest_density << std::endl; } //------------------------------------------------------------------------------------------ void Scene::initPeridynamicsParticles(int* pd_activity, real4_t* pd_position, real4_t *pd_velocity) { if(simParams_.num_pd_particle == 0) { return; } memcpy(pd_position, pd_position_cache_, sizeof(real4_t)*simParams_.num_pd_particle); real4_t translation = MAKE_REAL4(runningParams_.mesh_translation_x / simParams_.scaleFactor, runningParams_.mesh_translation_y / simParams_.scaleFactor, runningParams_.mesh_translation_z / simParams_.scaleFactor, 0.0f); real4_t rotation = MAKE_REAL4(0.0, 0.0f, 0.0f, 0.0f); // real4_t rotation = MAKE_REAL4(0.0, M_PI / 6.0f, 0.0f, 0.0f); std::cout << Monitor::PADDING << "PD particles translated by: " << translation.x << ", " << translation.y << ", " << translation.z << std::endl; std::cout << Monitor::PADDING << "PD particles rotated by: " << rotation.x << " degree around axis: " << rotation.y << ", " << rotation.z << ", " << rotation.w << std::endl; transformParticles(pd_position, translation, rotation, simParams_.num_pd_particle); // set the activity for(int i = 0; i < simParams_.num_pd_particle; ++i) { pd_activity[i] = ACTIVE; pd_velocity[i] = MAKE_REAL4_FROM_REAL(runningParams_.pd_initial_velocity); } } //------------------------------------------------------------------------------------------ void Scene::fillParticles(real4_t* particles, int* grid3d, real_t* margin3d, real_t border, real_t spacing, real_t jitter, int num_particles, bool position_correction) { real_t pX, pY, pZ; for (int z = 0; z < grid3d[2]; z++) { for (int y = 0; y < grid3d[1]; y++) { for (int x = 0; x < grid3d[0]; x++) { int i = (z * grid3d[1] * grid3d[0]) + (y * grid3d[0]) + x; if (i >= num_particles) { continue; } pX = simParams_.boundary_min_x + margin3d[0] + x * spacing + (frand() * 2.0f - 1.0f) * jitter; pY = simParams_.boundary_min_y + margin3d[1] + y * spacing + (frand() * 2.0f - 1.0f) * jitter; pZ = simParams_.boundary_min_z + margin3d[2] + z * spacing + (frand() * 2.0f - 1.0f) * jitter; // Correction of position if(position_correction) { if(pX > simParams_.boundary_min_x) { if(pX < simParams_.boundary_min_x + border) { pX = simParams_.boundary_min_x + border; } } else { if(pX > simParams_.boundary_min_x - border) { pX = simParams_.boundary_min_x - border; } } if(pX < simParams_.boundary_max_x) { if(pX > simParams_.boundary_max_x - border) { pX = simParams_.boundary_max_x - border; } } else { if(pX < simParams_.boundary_max_x + border) { pX = simParams_.boundary_max_x + border; } } if(pY > simParams_.boundary_min_y) { if(pY < simParams_.boundary_min_y + border) { pY = simParams_.boundary_min_y + border; } } else { if(pY > simParams_.boundary_min_y - border) { pY = simParams_.boundary_min_y - border; } } if(pY < simParams_.boundary_max_y) { if(pY > simParams_.boundary_max_y - border) { pY = simParams_.boundary_max_y - border; } } else { if(pY < simParams_.boundary_max_y + border) { pY = simParams_.boundary_max_y + border; } } if(pZ > simParams_.boundary_min_z) { if(pZ < simParams_.boundary_min_z + border) { pZ = simParams_.boundary_min_z + border; } } else { if(pZ > simParams_.boundary_min_z - border) { pZ = simParams_.boundary_min_z - border; } } if(pZ < simParams_.boundary_max_z) { if(pZ > simParams_.boundary_max_z - border) { pZ = simParams_.boundary_max_z - border; } } else { if(pZ < simParams_.boundary_max_z + border) { pZ = simParams_.boundary_max_z + border; } } } particles[i] = MAKE_REAL4(pX, pY, pZ, 0.0f); // printf("p: %d, %f, %f, %f\n", i, pX, pY, pZ); } } } } //------------------------------------------------------------------------------------------ int Scene::fillParticlesToMesh(MeshObject* meshObject, cyPoint3f box_min, cyPoint3f box_max, real4_t* particles, int* grid3d, real_t spacing, real_t jitter, int max_num_particles) { real_t pX, pY, pZ; int num_particles = 0; double point[3]; // bool y0=false; for (int z = 0; z < grid3d[2]; z++) { for (int y = 0; y < grid3d[1]; y++) { for (int x = 0; x < grid3d[0]; x++) { int i = (z * grid3d[1] * grid3d[0]) + (y * grid3d[0]) + x; if (i >= max_num_particles) { continue; } // if(y0 && y==1) // continue; // if(count == 3) // continue; pX = box_min.x + x * spacing + (frand() * 2.0f - 1.0f) * jitter; pY = box_min.y + y * spacing + (frand() * 2.0f - 1.0f) * jitter; pZ = box_min.z + z * spacing + (frand() * 2.0f - 1.0f) * jitter; point[0] = (double)pX; point[1] = (double)pY; point[2] = (double)pZ; if(point_inside_mesh(point, meshObject)) { // Correction of position pX = (pX < box_min.x) ? box_min.x : pX; pX = (pX > box_max.x) ? box_max.x : pX; pY = (pY < box_min.y) ? box_min.y : pY; pY = (pY > box_max.y) ? box_max.y : pY; pZ = (pZ < box_min.z) ? box_min.z : pZ; pZ = (pZ > box_max.z) ? box_max.z : pZ; //if(!y0 && y==1) y0 = true; //printf("P: %d, %d, %d, %f, %f, %f\n", x, y, z, pX, pY, pZ); particles[num_particles] = MAKE_REAL4(pX, pY, pZ, 0.0); ++num_particles; } } } } std::cout << Monitor::PADDING << "Total filled Peridynamics particles: " << num_particles << std::endl; return num_particles; } //------------------------------------------------------------------------------------------ void Scene::fillTubeParticles(real4_t* particles, int tube_radius, real3_t base_center, int* up_direction, real_t spacing, real_t jitter, int num_particles) { } //------------------------------------------------------------------------------------------ void Scene::createSPHGrid(int* grid3d) { grid3d[0] = (int) floor((simParams_.boundary_max_x - simParams_.boundary_min_x) / (2.0f * simParams_.sph_particle_radius)) - 10; grid3d[1] = (int) floor((simParams_.boundary_max_y - simParams_.boundary_min_y) / (2.0f * simParams_.sph_particle_radius)) - 3; grid3d[2] = (int) floor((simParams_.boundary_max_z - simParams_.boundary_min_z) / (2.0f * simParams_.sph_particle_radius)); std::cout << Monitor::PADDING << "Maximum SPH grid: " << grid3d[0] << "x" << grid3d[1] << "x" << grid3d[2] << std::endl; } //------------------------------------------------------------------------------------------ void Scene::createPeridynamicsGrid(int* grid3d) { grid3d[0] = (int) floor((simParams_.boundary_max_x - simParams_.boundary_min_x) / (2.0f * simParams_.pd_particle_radius)); grid3d[1] = (int) floor((simParams_.boundary_max_y - simParams_.boundary_min_y) / (2.0f * simParams_.pd_particle_radius)); grid3d[2] = (int) floor((simParams_.boundary_max_z - simParams_.boundary_min_z) / (2.0f * simParams_.pd_particle_radius)); std::cout << Monitor::PADDING << "Maximum Peridynamics grid: " << grid3d[0] << "x" << grid3d[1] << "x" << grid3d[2] << std::endl; } //------------------------------------------------------------------------------------------ void Scene::createPeridynamicsGrid(cyPoint3f box_min, cyPoint3f box_max, int* grid3d) { grid3d[0] = (int) ceil((box_max.x - box_min.x) / (2.0f * simParams_.pd_particle_radius)) + 1; grid3d[1] = (int) ceil((box_max.y - box_min.y) / (2.0f * simParams_.pd_particle_radius)) + 1; grid3d[2] = (int) ceil((box_max.z - box_min.z) / (2.0f * simParams_.pd_particle_radius)) + 1; std::cout << Monitor::PADDING << "Maximum Peridynamics grid: " << grid3d[0] << "x" << grid3d[1] << "x" << grid3d[2] << std::endl; } //------------------------------------------------------------------------------------------ inline double dot3(double a[3], real4_t b) { return (a[0] * b.x + a[1] * b.y + a[2] * b.z); } void Scene::transformParticles(real4_t* particles, real4_t translation, real4_t rotation, int num_particles) { int i, j; double azimuth = rotation.x; double elevation = rotation.y; double roll = rotation.z; double sinA, cosA, sinE, cosE, sinR, cosR; double R[3][3]; double tmp[4]; sinA = std::sin(azimuth); cosA = std::cos(azimuth); sinE = std::sin(elevation); cosE = std::cos(elevation); sinR = std::sin(roll); cosR = std::cos(roll); R[0][0] = cosR * cosA - sinR * sinA * sinE; R[0][1] = sinR * cosA + cosR * sinA * sinE; R[0][2] = -sinA * cosE; R[1][0] = -sinR * cosE; R[1][1] = cosR * cosE; R[1][2] = sinE; R[2][0] = cosR * sinA + sinR * cosA * sinE; R[2][1] = sinR * sinA - cosR * cosA * sinE; R[2][2] = cosA * cosE; for (i = 0; i < num_particles; ++i) { for (j = 0; j < 3; ++j) { tmp[j] = dot3(R[j], particles[i]); } particles[i] = MAKE_REAL4(tmp[0] + translation.x, tmp[1] + translation.y, tmp[2] + translation.z, 0.0f); } }
35.302594
113
0.495673
SCIInstitute
3cf2700a6aa1adfce4e21b2d01c332e038240877
215
hpp
C++
bunsan/utility/include/bunsan/utility/error.hpp
bacsorg/bacs
2b52feb9efc805655cdf7829cf77ee028d567969
[ "Apache-2.0" ]
null
null
null
bunsan/utility/include/bunsan/utility/error.hpp
bacsorg/bacs
2b52feb9efc805655cdf7829cf77ee028d567969
[ "Apache-2.0" ]
10
2018-02-06T14:46:36.000Z
2018-03-20T13:37:20.000Z
bunsan/utility/include/bunsan/utility/error.hpp
bacsorg/bacs
2b52feb9efc805655cdf7829cf77ee028d567969
[ "Apache-2.0" ]
1
2021-11-26T10:59:09.000Z
2021-11-26T10:59:09.000Z
#pragma once #include <bunsan/error.hpp> namespace bunsan::utility { struct error : virtual bunsan::error { error() = default; explicit error(const std::string &message_); }; } // namespace bunsan::utility
16.538462
46
0.702326
bacsorg
3cf324aced73cd76bf7562e3d4abe3e8ed820631
1,338
cpp
C++
CppSTL/cppstdlib/alloc/myalloc11.cpp
webturing/CPlusPlus
6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f
[ "AFL-2.0" ]
14
2018-06-21T14:41:26.000Z
2021-12-19T14:43:51.000Z
CppSTL/cppstdlib/alloc/myalloc11.cpp
webturing/CPlusPlus
6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f
[ "AFL-2.0" ]
null
null
null
CppSTL/cppstdlib/alloc/myalloc11.cpp
webturing/CPlusPlus
6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f
[ "AFL-2.0" ]
2
2020-04-20T11:16:53.000Z
2021-01-02T15:58:35.000Z
/* The following code example is taken from the book * "The C++ Standard Library - A Tutorial and Reference, 2nd Edition" * by Nicolai M. Josuttis, Addison-Wesley, 2012 * * (C) Copyright Nicolai M. Josuttis 2012. * Permission to copy, use, modify, sell and distribute this software * is granted provided this copyright notice appears in all copies. * This software is provided "as is" without express or implied * warranty, and with no claim as to its suitability for any purpose. */ #include "myalloc11.hpp" #include <vector> #include <map> #include <string> #include <functional> int main() { // a vector with special allocator std::vector<int, MyAlloc<int>> v; // an int/float map with special allocator std::map<int, float, std::less<int>, MyAlloc<std::pair<const int, float>>> m; // a string with special allocator std::basic_string<char, std::char_traits<char>, MyAlloc<char>> s; // special string type that uses special allocator typedef std::basic_string<char, std::char_traits<char>, MyAlloc<char>> MyString; // special string/string map type that uses special allocator typedef std::map <MyString, MyString, std::less<MyString>, MyAlloc<std::pair<const MyString, MyString>>> MyMap; // create object of this type MyMap mymap; //... }
33.45
69
0.692078
webturing
3cf43adb15c2d36bcf0c212a4eb39b22a66cb18c
6,381
cpp
C++
src/mongo/s/s_only.cpp
guanhe0/mongo
75077b7f56bfe8f3cc187477c2f06527e14f7ad3
[ "Apache-2.0" ]
14
2019-01-11T05:01:29.000Z
2021-11-01T00:39:46.000Z
src/mongo/s/s_only.cpp
guanhe0/mongo
75077b7f56bfe8f3cc187477c2f06527e14f7ad3
[ "Apache-2.0" ]
1
2022-03-05T02:55:28.000Z
2022-03-05T05:28:00.000Z
src/mongo/s/s_only.cpp
guanhe0/mongo
75077b7f56bfe8f3cc187477c2f06527e14f7ad3
[ "Apache-2.0" ]
7
2019-02-08T16:28:36.000Z
2021-05-08T14:25:47.000Z
// s_only.cpp /* Copyright 2009 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the GNU Affero General Public License in all respects * for all of the code used other than as permitted herein. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you do not * wish to do so, delete this exception statement from your version. If you * delete this exception statement from all source files in the program, * then also delete it in the license file. */ #define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kSharding #include "mongo/platform/basic.h" #include <tuple> #include "mongo/db/auth/authorization_manager.h" #include "mongo/db/auth/authorization_manager_global.h" #include "mongo/db/auth/authorization_session.h" #include "mongo/db/client.h" #include "mongo/db/commands.h" #include "mongo/db/service_context.h" #include "mongo/db/stats/counters.h" #include "mongo/rpc/metadata.h" #include "mongo/rpc/reply_builder_interface.h" #include "mongo/rpc/request_interface.h" #include "mongo/s/cluster_last_error_info.h" #include "mongo/util/assert_util.h" #include "mongo/util/concurrency/thread_name.h" #include "mongo/util/log.h" namespace mongo { using std::string; using std::stringstream; bool isMongos() { return true; } /** When this callback is run, we record a shard that we've used for useful work * in an operation to be read later by getLastError() */ void usingAShardConnection(const std::string& addr) { ClusterLastErrorInfo::get(cc()).addShardHost(addr); } // called into by the web server. For now we just translate the parameters // to their old style equivalents. void Command::execCommand(OperationContext* txn, Command* command, const rpc::RequestInterface& request, rpc::ReplyBuilderInterface* replyBuilder) { int queryFlags = 0; BSONObj cmdObj; std::tie(cmdObj, queryFlags) = uassertStatusOK( rpc::downconvertRequestMetadata(request.getCommandArgs(), request.getMetadata())); std::string db = request.getDatabase().rawData(); BSONObjBuilder result; execCommandClientBasic(txn, command, *txn->getClient(), queryFlags, request.getDatabase().rawData(), cmdObj, result); replyBuilder->setCommandReply(result.done()).setMetadata(rpc::makeEmptyMetadata()); } void Command::execCommandClientBasic(OperationContext* txn, Command* c, ClientBasic& client, int queryOptions, const char* ns, BSONObj& cmdObj, BSONObjBuilder& result) { std::string dbname = nsToDatabase(ns); if (cmdObj.getBoolField("help")) { stringstream help; help << "help for: " << c->name << " "; c->help(help); result.append("help", help.str()); result.append("lockType", c->isWriteCommandForConfigServer() ? 1 : 0); appendCommandStatus(result, true, ""); return; } Status status = checkAuthorization(c, txn, dbname, cmdObj); if (!status.isOK()) { appendCommandStatus(result, status); return; } c->_commandsExecuted.increment(); if (c->shouldAffectCommandCounter()) { globalOpCounters.gotCommand(); } std::string errmsg; bool ok = false; try { ok = c->run(txn, dbname, cmdObj, queryOptions, errmsg, result); } catch (const DBException& e) { result.resetToEmpty(); const int code = e.getCode(); // Codes for StaleConfigException if (code == ErrorCodes::RecvStaleConfig || code == ErrorCodes::SendStaleConfig) { throw; } errmsg = e.what(); result.append("code", code); } if (!ok) { c->_commandsFailed.increment(); } appendCommandStatus(result, ok, errmsg); } void Command::runAgainstRegistered(OperationContext* txn, const char* ns, BSONObj& jsobj, BSONObjBuilder& anObjBuilder, int queryOptions) { // It should be impossible for this uassert to fail since there should be no way to get // into this function with any other collection name. uassert(16618, "Illegal attempt to run a command against a namespace other than $cmd.", nsToCollectionSubstring(ns) == "$cmd"); BSONElement e = jsobj.firstElement(); std::string commandName = e.fieldName(); Command* c = e.type() ? Command::findCommand(commandName) : NULL; if (!c) { Command::appendCommandStatus( anObjBuilder, false, str::stream() << "no such cmd: " << commandName); anObjBuilder.append("code", ErrorCodes::CommandNotFound); Command::unknownCommands.increment(); return; } execCommandClientBasic(txn, c, cc(), queryOptions, ns, jsobj, anObjBuilder); } void Command::registerError(OperationContext* txn, const DBException& exception) {} } // namespace mongo
36.050847
91
0.629995
guanhe0
3cf50ddd33c54036104018b9bd178806536d4ef2
4,882
cpp
C++
bin/ch/JITProcessManager.cpp
vinay72/ChakraCore
bff3ae27d0e95abe6bbbaf4691218be37b8125ee
[ "MIT" ]
1
2019-05-08T21:39:33.000Z
2019-05-08T21:39:33.000Z
bin/ch/JITProcessManager.cpp
Dachande663/ChakraCore
ed98335e71a98b45629d9ab957960121d66790a2
[ "MIT" ]
5
2019-01-07T10:15:23.000Z
2019-01-08T08:59:03.000Z
bin/ch/JITProcessManager.cpp
Dachande663/ChakraCore
ed98335e71a98b45629d9ab957960121d66790a2
[ "MIT" ]
1
2019-01-18T12:55:24.000Z
2019-01-18T12:55:24.000Z
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #include "stdafx.h" #ifdef _WIN32 HANDLE JITProcessManager::s_rpcServerProcessHandle = 0; // 0 is the "invalid handle" value for process handles UUID JITProcessManager::s_connectionId = GUID_NULL; HRESULT JITProcessManager::StartRpcServer(int argc, __in_ecount(argc) LPWSTR argv[]) { HRESULT hr = S_OK; JITProcessManager::RemoveArg(_u("-dynamicprofilecache:"), &argc, &argv); JITProcessManager::RemoveArg(_u("-dpc:"), &argc, &argv); JITProcessManager::RemoveArg(_u("-dynamicprofileinput:"), &argc, &argv); if (IsEqualGUID(s_connectionId, GUID_NULL)) { RPC_STATUS status = UuidCreate(&s_connectionId); if (status == RPC_S_OK || status == RPC_S_UUID_LOCAL_ONLY) { hr = CreateServerProcess(argc, argv); } else { hr = HRESULT_FROM_WIN32(status); } } return hr; } /* static */ void JITProcessManager::RemoveArg(LPCWSTR flag, int * argc, __in_ecount(*argc) LPWSTR * argv[]) { size_t flagLen = wcslen(flag); int flagIndex; while ((flagIndex = HostConfigFlags::FindArg(*argc, *argv, flag, flagLen)) >= 0) { HostConfigFlags::RemoveArg(*argc, *argv, flagIndex); } } HRESULT JITProcessManager::CreateServerProcess(int argc, __in_ecount(argc) LPWSTR argv[]) { HRESULT hr; PROCESS_INFORMATION processInfo = { 0 }; STARTUPINFOW si = { 0 }; // overallocate constant cmd line (jshost -jitserver:<guid>) size_t cmdLineSize = (MAX_PATH + (size_t)argc) * sizeof(WCHAR); for (int i = 0; i < argc; ++i) { // calculate space requirement for each arg cmdLineSize += wcslen(argv[i]) * sizeof(WCHAR); } WCHAR* cmdLine = (WCHAR*)malloc(cmdLineSize); if (cmdLine == nullptr) { return E_OUTOFMEMORY; } RPC_WSTR connectionUuidString = NULL; #pragma warning(suppress: 6386) // buffer overrun #ifdef ENABLE_DEBUG_CONFIG_OPTIONS hr = StringCchCopyW(cmdLine, cmdLineSize, _u("ch.exe -OOPCFGRegistration- -CheckOpHelpers -jitserver:")); #else hr = StringCchCopyW(cmdLine, cmdLineSize, _u("ch.exe -jitserver:")); #endif if (FAILED(hr)) { return hr; } RPC_STATUS status = UuidToStringW(&s_connectionId, &connectionUuidString); if (status != S_OK) { return HRESULT_FROM_WIN32(status); } hr = StringCchCatW(cmdLine, cmdLineSize, (WCHAR*)connectionUuidString); if (FAILED(hr)) { return hr; } for (int i = 1; i < argc; ++i) { hr = StringCchCatW(cmdLine, cmdLineSize, _u(" ")); if (FAILED(hr)) { return hr; } hr = StringCchCatW(cmdLine, cmdLineSize, argv[i]); if (FAILED(hr)) { return hr; } } if (!CreateProcessW( NULL, cmdLine, NULL, NULL, FALSE, NULL, NULL, NULL, &si, &processInfo)) { return HRESULT_FROM_WIN32(GetLastError()); } free(cmdLine); CloseHandle(processInfo.hThread); s_rpcServerProcessHandle = processInfo.hProcess; if (HostConfigFlags::flags.EnsureCloseJITServer) { // create job object so if parent ch gets killed, server is killed as well // under a flag because it's preferable to let server close naturally // only useful in scenarios where ch is expected to be force terminated HANDLE jobObject = CreateJobObject(nullptr, nullptr); if (jobObject == nullptr) { return HRESULT_FROM_WIN32(GetLastError()); } if (!AssignProcessToJobObject(jobObject, s_rpcServerProcessHandle)) { return HRESULT_FROM_WIN32(GetLastError()); } JOBOBJECT_EXTENDED_LIMIT_INFORMATION jobInfo = { 0 }; jobInfo.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; if (!SetInformationJobObject(jobObject, JobObjectExtendedLimitInformation, &jobInfo, sizeof(jobInfo))) { return HRESULT_FROM_WIN32(GetLastError()); } } return NOERROR; } void JITProcessManager::TerminateJITServer() { if (s_rpcServerProcessHandle) { TerminateProcess(s_rpcServerProcessHandle, 1); CloseHandle(s_rpcServerProcessHandle); s_rpcServerProcessHandle = NULL; } } HANDLE JITProcessManager::GetRpcProccessHandle() { return s_rpcServerProcessHandle; } UUID JITProcessManager::GetRpcConnectionId() { return s_connectionId; } #endif
27.897143
110
0.612659
vinay72
3cf609518aad5663eac95909b8bce993dd0a4264
2,606
cpp
C++
src/Phases/economyPhase.cpp
spChalk/cardGame
cb0332ed007cd7f137cd67f410f9a5908f3cc2df
[ "MIT" ]
7
2020-03-06T18:59:15.000Z
2020-12-06T13:31:07.000Z
src/Phases/economyPhase.cpp
spChalk/Card-Game
cb0332ed007cd7f137cd67f410f9a5908f3cc2df
[ "MIT" ]
null
null
null
src/Phases/economyPhase.cpp
spChalk/Card-Game
cb0332ed007cd7f137cd67f410f9a5908f3cc2df
[ "MIT" ]
1
2020-03-06T20:39:11.000Z
2020-03-06T20:39:11.000Z
/* economyPhase.cpp */ #include <iostream> #include <string> #include "basicHeader.hpp" using std::cout; using std::endl; /* ========================================================================= */ void Game::economyPhase(PlayerPtr pl) { printF ("Economy Phase Started !" , 1 , YEL , FILL); printF ("Press ENTER to continue . . ." , 1); std::cin.clear(); std::cin.sync(); std::cin.get(); printF ("Player : " , 0 , MAG , BOLD); cout << pl->getUserName(); printF (" can now buy Provinces!" , 1 , MAG , BOLD); printF ("Printing " , 0 , MAG); cout << pl->getUserName(); printF ("'s Provinces : " , 1 , MAG); pl->printProvinces(); printF ("Type 'Y' (YES) or '<any other key>' (NO) after each card's \ appearance, to proceed to purchase. " , 1 , MAG , BOLD); /* Buy provinces */ for (auto i : *(pl->getProvinces())) /* For every province */ { if (i->checkBroken() == false && i->getCard()->checkRevealed() == true) { if (pl->getCurrMoney() == 0) { cout << "No money left !" << endl; return; } else if (pl->getCurrMoney() < i->getCard()->getCost()) continue; else { cout << pl->getUserName(); printF ("'s Current balance: " , 0 , YEL , BOLD); cout << pl->getCurrMoney() << endl; } i->print(); /* If it is revealed and not broken */ cout << endl << pl->getUserName(); printF (" , do you want to proceed to purchase ?\n> Your answer: " , 0 , YEL , BOLD); std::string answer; std::getline(std::cin, answer); cout << endl; if ((answer == "Y")||(answer == "y")) /* Attempt to make the purchase */ { if (pl->makePurchase(i->getCard()->getCost()) == true) { printF ("Purchase Completed ! " , 1 , YEL , BOLD); i->getCard()->setTapped(); /* Can't be used for this round */ i->getCard()->attachToPlayer(pl); if (pl->getDynastyDeck()->empty() == false) i->setCard( pl->drawBlackCard() ); /* Replace the card bought */ else { printF ("Dynasty deck is empty! No more Black Cards for player \'" , 0 , MAG , BOLD); cout << pl->getUserName(); printF ("\' !" , 1 , MAG , BOLD); } } else printF ("You don't have enough money to buy this province!" , 1 , MAG , BOLD); } } } printF ("Economy Phase Ended !" , 1 , YEL , FILL); } /* ========================================================================= */
31.39759
97
0.480046
spChalk
3cf707efa2dafcb4ad1efe63aa9a2145a730a90f
8,279
cpp
C++
libs/unordered/test/unordered/unnecessary_copy_tests.cpp
coxlab/boost_patched_for_objcplusplus
5316cd54bbd03994ae785185efcde62b57fd5e93
[ "BSL-1.0" ]
1
2017-07-31T02:19:48.000Z
2017-07-31T02:19:48.000Z
libs/unordered/test/unordered/unnecessary_copy_tests.cpp
boost-cmake/vintage
dcfb7da3177134eddaee6789d6f582259cb0d6ee
[ "BSL-1.0" ]
null
null
null
libs/unordered/test/unordered/unnecessary_copy_tests.cpp
boost-cmake/vintage
dcfb7da3177134eddaee6789d6f582259cb0d6ee
[ "BSL-1.0" ]
1
2021-03-07T05:20:43.000Z
2021-03-07T05:20:43.000Z
// Copyright 2006-2009 Daniel James. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <boost/unordered_set.hpp> #include <boost/unordered_map.hpp> #include "../helpers/test.hpp" namespace unnecessary_copy_tests { struct count_copies { static int copies; static int moves; count_copies() : tag_(0) { ++copies; } explicit count_copies(int tag) : tag_(tag) { ++copies; } // This bizarre constructor is an attempt to confuse emplace. // // unordered_map<count_copies, count_copies> x: // x.emplace(count_copies(1), count_copies(2)); // x.emplace(count_copies(1), count_copies(2), count_copies(3)); // // The first emplace should use the single argument constructor twice. // The second emplace should use the single argument contructor for // the key, and this constructor for the value. count_copies(count_copies const&, count_copies const& x) : tag_(x.tag_) { ++copies; } count_copies(count_copies const& x) : tag_(x.tag_) { ++copies; } #if defined(BOOST_HAS_RVALUE_REFS) count_copies(count_copies&& x) : tag_(x.tag_) { x.tag_ = -1; ++moves; } #endif int tag_; private: count_copies& operator=(count_copies const&); }; bool operator==(count_copies const& x, count_copies const& y) { return x.tag_ == y.tag_; } template <class T> T source() { return T(); } void reset() { count_copies::copies = 0; count_copies::moves = 0; } } #if defined(BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP) namespace boost #else namespace unnecessary_copy_tests #endif { std::size_t hash_value(unnecessary_copy_tests::count_copies const& x) { return x.tag_; } } #define COPY_COUNT(n) \ if(count_copies::copies != n) { \ BOOST_ERROR("Wrong number of copies."); \ std::cerr<<"Number of copies: "<<count_copies::copies<<" expecting: "<<n<<std::endl; \ } #define MOVE_COUNT(n) \ if(count_copies::moves != n) { \ BOOST_ERROR("Wrong number of moves."); \ std::cerr<<"Number of moves: "<<count_copies::moves<<" expecting: "<<n<<std::endl; \ } #define COPY_COUNT_RANGE(a, b) \ if(count_copies::copies < a || count_copies::copies > b) { \ BOOST_ERROR("Wrong number of copies."); \ std::cerr<<"Number of copies: "<<count_copies::copies<<" expecting: ["<<a<<", "<<b<<"]"<<std::endl; \ } #define MOVE_COUNT_RANGE(a, b) \ if(count_copies::moves < a || count_copies::moves > b) { \ BOOST_ERROR("Wrong number of moves."); \ std::cerr<<"Number of moves: "<<count_copies::copies<<" expecting: ["<<a<<", "<<b<<"]"<<std::endl; \ } namespace unnecessary_copy_tests { int count_copies::copies; int count_copies::moves; template <class T> void unnecessary_copy_insert_test(T*) { T x; BOOST_DEDUCED_TYPENAME T::value_type a; reset(); x.insert(a); COPY_COUNT(1); } boost::unordered_set<count_copies>* set; boost::unordered_multiset<count_copies>* multiset; boost::unordered_map<int, count_copies>* map; boost::unordered_multimap<int, count_copies>* multimap; UNORDERED_TEST(unnecessary_copy_insert_test, ((set)(multiset)(map)(multimap))) template <class T> void unnecessary_copy_emplace_test(T*) { reset(); T x; BOOST_DEDUCED_TYPENAME T::value_type a; COPY_COUNT(1); x.emplace(a); COPY_COUNT(2); } template <class T> void unnecessary_copy_emplace_rvalue_test(T*) { reset(); T x; x.emplace(source<BOOST_DEDUCED_TYPENAME T::value_type>()); #if defined(BOOST_HAS_RVALUE_REFS) && defined(BOOST_HAS_VARIADIC_TMPL) COPY_COUNT(1); #else COPY_COUNT(2); #endif } UNORDERED_TEST(unnecessary_copy_emplace_test, ((set)(multiset)(map)(multimap))) UNORDERED_TEST(unnecessary_copy_emplace_rvalue_test, ((set)(multiset)(map)(multimap))) #if defined(BOOST_HAS_RVALUE_REFS) && defined(BOOST_HAS_VARIADIC_TMPL) template <class T> void unnecessary_copy_emplace_move_test(T*) { reset(); T x; BOOST_DEDUCED_TYPENAME T::value_type a; COPY_COUNT(1); MOVE_COUNT(0); x.emplace(std::move(a)); COPY_COUNT(1); MOVE_COUNT(1); } UNORDERED_TEST(unnecessary_copy_emplace_move_test, ((set)(multiset)(map)(multimap))) #endif UNORDERED_AUTO_TEST(unnecessary_copy_emplace_set_test) { reset(); boost::unordered_set<count_copies> x; count_copies a; x.insert(a); COPY_COUNT(2); MOVE_COUNT(0); // // 0 arguments // // The container will have to create a copy in order to compare with // the existing element. reset(); x.emplace(); COPY_COUNT(1); MOVE_COUNT(0); // // 1 argument // // Emplace should be able to tell that there already is an element // without creating a new one. reset(); x.emplace(a); COPY_COUNT(0); MOVE_COUNT(0); // A new object is created by source, but it shouldn't be moved or // copied. reset(); x.emplace(source<count_copies>()); COPY_COUNT(1); MOVE_COUNT(0); #if defined(BOOST_HAS_RVALUE_REFS) // No move should take place. reset(); x.emplace(std::move(a)); COPY_COUNT(0); MOVE_COUNT(0); #endif // Just in case a did get moved... count_copies b; // The container will have to create a copy in order to compare with // the existing element. reset(); x.emplace(b.tag_); COPY_COUNT(1); MOVE_COUNT(0); // // 2 arguments // // The container will have to create b copy in order to compare with // the existing element. // // Note to self: If copy_count == 0 it's an error not an optimization. // TODO: Devise a better test. reset(); x.emplace(b, b); COPY_COUNT(1); MOVE_COUNT(0); } UNORDERED_AUTO_TEST(unnecessary_copy_emplace_map_test) { reset(); boost::unordered_map<count_copies, count_copies> x; // TODO: Run tests for pairs without const etc. std::pair<count_copies const, count_copies> a; x.emplace(a); COPY_COUNT(4); MOVE_COUNT(0); // // 0 arguments // // COPY_COUNT(1) would be okay here. reset(); x.emplace(); COPY_COUNT(2); MOVE_COUNT(0); // // 1 argument // reset(); x.emplace(a); COPY_COUNT(0); MOVE_COUNT(0); // A new object is created by source, but it shouldn't be moved or // copied. reset(); x.emplace(source<std::pair<count_copies, count_copies> >()); COPY_COUNT(2); MOVE_COUNT(0); // TODO: This doesn't work on older versions of gcc. //count_copies part; std::pair<count_copies const, count_copies> b; //reset(); //std::pair<count_copies const&, count_copies const&> a_ref(part, part); //x.emplace(a_ref); //COPY_COUNT(0); MOVE_COUNT(0); #if defined(BOOST_HAS_RVALUE_REFS) // No move should take place. // (since a is already in the container) reset(); x.emplace(std::move(a)); COPY_COUNT(0); MOVE_COUNT(0); #endif // // 2 arguments // reset(); x.emplace(b.first, b.second); COPY_COUNT(0); MOVE_COUNT(0); reset(); x.emplace(source<count_copies>(), source<count_copies>()); COPY_COUNT(2); MOVE_COUNT(0); // source<count_copies> creates a single copy. reset(); x.emplace(b.first, source<count_copies>()); COPY_COUNT(1); MOVE_COUNT(0); reset(); x.emplace(count_copies(b.first.tag_), count_copies(b.second.tag_)); COPY_COUNT(2); MOVE_COUNT(0); } } RUN_TESTS()
27.875421
109
0.590651
coxlab
3cf7306c1722bc9d3fcf25dc626c66fe83d5a036
9,141
cpp
C++
inference-engine/tests/functional/inference_engine/transformations/ngraph_1d_ops_reshape_test.cpp
Andruxin52rus/openvino
d824e371fe7dffb90e6d3d58e4e34adecfce4606
[ "Apache-2.0" ]
2
2020-11-18T14:14:06.000Z
2020-11-28T04:55:57.000Z
inference-engine/tests/functional/inference_engine/transformations/ngraph_1d_ops_reshape_test.cpp
Andruxin52rus/openvino
d824e371fe7dffb90e6d3d58e4e34adecfce4606
[ "Apache-2.0" ]
30
2020-11-13T11:44:07.000Z
2022-02-21T13:03:16.000Z
inference-engine/tests/functional/inference_engine/transformations/ngraph_1d_ops_reshape_test.cpp
mmakridi/openvino
769bb7709597c14debdaa356dd60c5a78bdfa97e
[ "Apache-2.0" ]
1
2021-07-28T17:30:46.000Z
2021-07-28T17:30:46.000Z
// Copyright (C) 2018-2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <gtest/gtest.h> #include "common_test_utils/test_common.hpp" #include <string> #include <sstream> #include <fstream> #include <memory> #include <map> #include <ngraph/function.hpp> #include <ngraph/op/constant.hpp> #include <ngraph_ops/convolution_ie.hpp> #include <ngraph/pass/constant_folding.hpp> #include <legacy/transformations/convert_opset1_to_legacy/reshape_1d_ops.hpp> #include <transformations/init_node_info.hpp> #include <ngraph/opsets/opset1.hpp> #include <ngraph/pass/manager.hpp> #include "common_test_utils/ngraph_test_utils.hpp" using namespace testing; using namespace ngraph; TEST(TransformationTests, ConvReshapeTest1) { auto input = ngraph::op::Constant::create(ngraph::element::f32, ngraph::Shape{1, 3, 64}, {1}); auto w = ngraph::op::Constant::create(ngraph::element::f32, ngraph::Shape{6, 3, 3/*OIW*/}, {1}); std::shared_ptr<ngraph::Function> f(nullptr); { ngraph::Strides strides{1}, dilations{1}; ngraph::CoordinateDiff pads_begin{0}, pads_end{0}; ngraph::Shape output_shape{1, 6, 62}; auto conv = std::make_shared<ngraph::op::ConvolutionIE>(input, w, strides, dilations, pads_begin, pads_end, ngraph::element::f32, 1); f = std::make_shared<ngraph::Function>(ngraph::NodeVector{conv}, ngraph::ParameterVector{}); ngraph::pass::InitNodeInfo().run_on_function(f); ngraph::pass::Reshape1DOps().run_on_function(f); ASSERT_NO_THROW(check_rt_info(f)); ngraph::pass::ConstantFolding().run_on_function(f); } std::vector<size_t> ref_shape{1, 6, 1, 62}; ngraph::Strides ref_strides{1, 1}; ngraph::CoordinateDiff ref_pads_begin{0, 0}, ref_pads_end{0, 0}; for (auto op : f->get_ops()) { if (auto conv = ngraph::as_type_ptr<ngraph::op::ConvolutionIE>(op)) { ASSERT_EQ(conv->get_shape(), ref_shape); ASSERT_EQ(conv->get_strides(), ref_strides); ASSERT_EQ(conv->get_dilations(), ref_strides); ASSERT_EQ(conv->get_pads_begin(), ref_pads_begin); ASSERT_EQ(conv->get_pads_end(), ref_pads_end); } } } TEST(TransformationTests, ConvBiasReshapeTest1) { auto input = ngraph::op::Constant::create(ngraph::element::f32, ngraph::Shape{1, 3, 64}, {1}); auto w = ngraph::op::Constant::create(ngraph::element::f32, ngraph::Shape{6, 3, 3/*OIW*/}, {1}); auto b = ngraph::op::Constant::create(ngraph::element::f32, ngraph::Shape{6}, {1}); std::shared_ptr<ngraph::Function> f(nullptr); { ngraph::Strides strides{1}, dilations{1}; ngraph::CoordinateDiff pads_begin{0}, pads_end{0}; ngraph::Shape output_shape{1, 6, 62}; auto conv = std::make_shared<ngraph::op::ConvolutionIE>(input, w, b, strides, dilations, pads_begin, pads_end, ngraph::element::f32, 1); f = std::make_shared<ngraph::Function>(ngraph::NodeVector{conv}, ngraph::ParameterVector{}); ngraph::pass::InitNodeInfo().run_on_function(f); ngraph::pass::Reshape1DOps().run_on_function(f); ASSERT_NO_THROW(check_rt_info(f)); ngraph::pass::ConstantFolding().run_on_function(f); } std::vector<size_t> ref_shape{1, 6, 1, 62}; ngraph::Strides ref_strides{1, 1}; ngraph::CoordinateDiff ref_pads_begin{0, 0}, ref_pads_end{0, 0}; for (auto op : f->get_ops()) { if (auto conv = ngraph::as_type_ptr<ngraph::op::ConvolutionIE>(op)) { ASSERT_EQ(conv->get_shape(), ref_shape); ASSERT_EQ(conv->get_strides(), ref_strides); ASSERT_EQ(conv->get_dilations(), ref_strides); ASSERT_EQ(conv->get_pads_begin(), ref_pads_begin); ASSERT_EQ(conv->get_pads_end(), ref_pads_end); } } } TEST(TransformationTests, MaxPoolReshapeTest1) { std::shared_ptr<ngraph::Function> f(nullptr), f_ref(nullptr); { auto input = std::make_shared<opset1::Parameter>(ngraph::element::f32, ngraph::Shape{1, 3, 64}); ngraph::Strides strides{1}; ngraph::Shape pads_begin{0}, pads_end{0}, kernel{3}; auto pool = std::make_shared<ngraph::opset1::MaxPool>(input, strides, pads_begin, pads_end, kernel, ngraph::op::RoundingType::FLOOR); f = std::make_shared<ngraph::Function>(ngraph::NodeVector{pool}, ngraph::ParameterVector{input}); ngraph::pass::InitNodeInfo().run_on_function(f); ngraph::pass::Reshape1DOps().run_on_function(f); ASSERT_NO_THROW(check_rt_info(f)); } { auto input = std::make_shared<opset1::Parameter>(ngraph::element::f32, ngraph::Shape{1, 3, 64}); auto reshape_begin = std::make_shared<opset1::Reshape>(input, opset1::Constant::create(element::i64, Shape{4}, {1, 3, 1, 64}), true); ngraph::Strides strides{1, 1}; ngraph::Shape pads_begin{0, 0}, pads_end{0, 0}, kernel{1, 3}; auto pool = std::make_shared<ngraph::opset1::MaxPool>(reshape_begin, strides, pads_begin, pads_end, kernel, ngraph::op::RoundingType::FLOOR); auto reshape_end = std::make_shared<opset1::Reshape>(pool, opset1::Constant::create(element::i64, Shape{3}, {1, 3, 62}), true); f_ref = std::make_shared<ngraph::Function>(ngraph::NodeVector{reshape_end}, ngraph::ParameterVector{input}); } auto res = compare_functions(f, f_ref); ASSERT_TRUE(res.first) << res.second; } TEST(TransformationTests, AvgPoolReshapeTest1) { std::shared_ptr<ngraph::Function> f(nullptr), f_ref(nullptr); { auto input = std::make_shared<opset1::Parameter>(ngraph::element::f32, ngraph::Shape{1, 3, 64}); ngraph::Strides strides{1}; ngraph::Shape pads_begin{0}, pads_end{0}, kernel{3}; auto pool = std::make_shared<ngraph::opset1::AvgPool>(input, strides, pads_begin, pads_end, kernel, false, ngraph::op::RoundingType::FLOOR); f = std::make_shared<ngraph::Function>(ngraph::NodeVector{pool}, ngraph::ParameterVector{input}); ngraph::pass::InitNodeInfo().run_on_function(f); ngraph::pass::Reshape1DOps().run_on_function(f); ASSERT_NO_THROW(check_rt_info(f)); } { auto input = std::make_shared<opset1::Parameter>(ngraph::element::f32, ngraph::Shape{1, 3, 64}); auto reshape_begin = std::make_shared<opset1::Reshape>(input, opset1::Constant::create(element::i64, Shape{4}, {1, 3, 1, 64}), true); ngraph::Strides strides{1, 1}; ngraph::Shape pads_begin{0, 0}, pads_end{0, 0}, kernel{1, 3}; auto pool = std::make_shared<ngraph::opset1::AvgPool>(reshape_begin, strides, pads_begin, pads_end, kernel, false, ngraph::op::RoundingType::FLOOR); auto reshape_end = std::make_shared<opset1::Reshape>(pool, opset1::Constant::create(element::i64, Shape{3}, {1, 3, 62}), true); f_ref = std::make_shared<ngraph::Function>(ngraph::NodeVector{reshape_end}, ngraph::ParameterVector{input}); } auto res = compare_functions(f, f_ref); ASSERT_TRUE(res.first) << res.second; } TEST(TransformationTests, ReshapeDynamicTest1) { { auto input = std::make_shared<opset1::Parameter>(ngraph::element::f32, ngraph::PartialShape::dynamic()); ngraph::Strides strides{1}; ngraph::Shape pads_begin{0}, pads_end{0}, kernel{3}; auto pool = std::make_shared<ngraph::opset1::AvgPool>(input, strides, pads_begin, pads_end, kernel, false, ngraph::op::RoundingType::FLOOR); auto f = std::make_shared<ngraph::Function>(ngraph::NodeVector{pool}, ngraph::ParameterVector{input}); pass::Manager manager; manager.register_pass<ngraph::pass::Reshape1DOps>(); ASSERT_NO_THROW(manager.run_passes(f)); } { auto input = std::make_shared<opset1::Parameter>(ngraph::element::f32, ngraph::Shape{1, 3, 64}); ngraph::Strides strides{1}; ngraph::Shape pads_begin{0}, pads_end{0}, kernel{3}; auto pool = std::make_shared<ngraph::opset1::MaxPool>(input, strides, pads_begin, pads_end, kernel, ngraph::op::RoundingType::FLOOR); auto f = std::make_shared<ngraph::Function>(ngraph::NodeVector{pool}, ngraph::ParameterVector{input}); pass::Manager manager; manager.register_pass<ngraph::pass::Reshape1DOps>(); ASSERT_NO_THROW(manager.run_passes(f)); } { auto input = ngraph::op::Constant::create(ngraph::element::f32, ngraph::Shape{1, 3, 64}, {1}); auto w = ngraph::op::Constant::create(ngraph::element::f32, ngraph::Shape{6, 3, 3/*OIW*/}, {1}); auto b = ngraph::op::Constant::create(ngraph::element::f32, ngraph::Shape{6}, {1}); ngraph::Strides strides{1}, dilations{1}; ngraph::CoordinateDiff pads_begin{0}, pads_end{0}; ngraph::Shape output_shape{1, 6, 62}; auto conv = std::make_shared<ngraph::op::ConvolutionIE>(input, w, b, strides, dilations, pads_begin, pads_end, 1); auto f = std::make_shared<ngraph::Function>(ngraph::NodeVector{conv}, ngraph::ParameterVector{}); pass::Manager manager; manager.register_pass<ngraph::pass::Reshape1DOps>(); ASSERT_NO_THROW(manager.run_passes(f)); } }
45.934673
156
0.665245
Andruxin52rus
3cf7c4cdd1c0914438ac10e3bcbee98d0f4f71f2
10,099
cpp
C++
HelperFunctions/getvkDebugUtilsMessengerCallbackDataEXT.cpp
dkaip/jvulkan-natives-Linux-x86_64
ea7932f74e828953c712feea11e0b01751f9dc9b
[ "Apache-2.0" ]
null
null
null
HelperFunctions/getvkDebugUtilsMessengerCallbackDataEXT.cpp
dkaip/jvulkan-natives-Linux-x86_64
ea7932f74e828953c712feea11e0b01751f9dc9b
[ "Apache-2.0" ]
null
null
null
HelperFunctions/getvkDebugUtilsMessengerCallbackDataEXT.cpp
dkaip/jvulkan-natives-Linux-x86_64
ea7932f74e828953c712feea11e0b01751f9dc9b
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019-2020 Douglas Kaip * * 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. */ /* * getvkDebugUtilsMessengerCallbackDataEXT.cpp * * Created on: Apr 30, 2019 * Author: Douglas Kaip */ #include <stdlib.h> #include "JVulkanHelperFunctions.hh" #include "slf4j.hh" namespace jvulkan { void getvkDebugUtilsMessengerCallbackDataEXT( JNIEnv *env, const jobject jVkDebugUtilsMessengerCallbackDataEXTObject, VkDebugUtilsMessengerCallbackDataEXT *vkDebugUtilsMessengerCallbackDataEXT, std::vector<void *> *memoryToFree) { jclass vkDebugUtilsMessengerCallbackDataEXTClass = env->GetObjectClass(jVkDebugUtilsMessengerCallbackDataEXTObject); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error trying to GetObjectClass for jVkDebugUtilsMessengerCallbackDataEXTObject"); return; } //////////////////////////////////////////////////////////////////////// VkStructureType sTypeValue = getSType(env, jVkDebugUtilsMessengerCallbackDataEXTObject); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error trying to getSType"); return; } //////////////////////////////////////////////////////////////////////// jobject pNextObject = getpNextObject(env, jVkDebugUtilsMessengerCallbackDataEXTObject); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Call to getpNext failed."); return; } if (pNextObject != nullptr) { LOGERROR(env, "%s", "pNext must be null."); return; } void *pNext = nullptr; //////////////////////////////////////////////////////////////////////// jmethodID methodId = env->GetMethodID(vkDebugUtilsMessengerCallbackDataEXTClass, "getFlags", "()Ljava/util/EnumSet;"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error trying to get getFlags methodId"); return; } jobject flagsObject = env->CallObjectMethod(jVkDebugUtilsMessengerCallbackDataEXTObject, methodId); VkDebugUtilsMessengerCallbackDataFlagsEXT flags = getEnumSetValue( env, flagsObject, "com/CIMthetics/jvulkan/VulkanExtensions/Enums/VkDebugUtilsMessengerCallbackDataFlagBitsEXT"); //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(vkDebugUtilsMessengerCallbackDataEXTClass, "getMessageIdName", "()Ljava/lang/String;"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error trying to get getMessageIdName methodId"); return; } jstring jMessageIdName = (jstring)env->CallObjectMethod(jVkDebugUtilsMessengerCallbackDataEXTObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallObjectMethod for getMessageIdName"); return; } char *theMessageIdName = nullptr; if (jMessageIdName != nullptr) { const char *tempString1 = env->GetStringUTFChars(jMessageIdName, 0); theMessageIdName = (char *)calloc(1, strlen(tempString1) + 1); memoryToFree->push_back(theMessageIdName); strcpy(theMessageIdName, tempString1); env->ReleaseStringUTFChars(jMessageIdName, tempString1); } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(vkDebugUtilsMessengerCallbackDataEXTClass, "getMessageIdNumber", "()I"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error trying to get getMessageIdNumber methodId"); return; } jint messageIdNumber = env->CallIntMethod(jVkDebugUtilsMessengerCallbackDataEXTObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallIntMethod for getMessageIdNumber"); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(vkDebugUtilsMessengerCallbackDataEXTClass, "getMessage", "()Ljava/lang/String;"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error trying to get getMessage methodId"); return; } jstring jMessage = (jstring)env->CallObjectMethod(jVkDebugUtilsMessengerCallbackDataEXTObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallObjectMethod for getMessage"); return; } char *message = nullptr; if (jMessage != nullptr) { const char *tempString2 = env->GetStringUTFChars(jMessage, 0); message = (char *)calloc(1, strlen(tempString2) + 1); memoryToFree->push_back(message); strcpy(message, tempString2); env->ReleaseStringUTFChars(jMessage, tempString2); } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(vkDebugUtilsMessengerCallbackDataEXTClass, "getQueueLabels", "()Ljava/util/Collection;"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error trying to get getQueueLabels methodId"); return; } jobject jVkDebugUtilsLabelEXTCollectionObject = env->CallObjectMethod(jVkDebugUtilsMessengerCallbackDataEXTObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallObjectMethod for getQueueLabels"); return; } int numberOfQLabels = 0; VkDebugUtilsLabelEXT *queueLabels = nullptr; if (jVkDebugUtilsLabelEXTCollectionObject != nullptr) { jvulkan::getVkDebugUtilsLabelEXTCollection( env, jVkDebugUtilsLabelEXTCollectionObject, &queueLabels, &numberOfQLabels, memoryToFree); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Call to getVkDebugUtilsLabelEXTCollection failed"); return; } } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(vkDebugUtilsMessengerCallbackDataEXTClass, "getCmdBufLabels", "()Ljava/util/Collection;"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error trying to get getCmdBufLabels methodId"); return; } jVkDebugUtilsLabelEXTCollectionObject = env->CallObjectMethod(jVkDebugUtilsMessengerCallbackDataEXTObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallObjectMethod for getCmdBufLabels"); return; } int numberOfCmdBufLabels = 0; VkDebugUtilsLabelEXT *cmdBufLabels = nullptr; if (jVkDebugUtilsLabelEXTCollectionObject != nullptr) { jvulkan::getVkDebugUtilsLabelEXTCollection( env, jVkDebugUtilsLabelEXTCollectionObject, &cmdBufLabels, &numberOfCmdBufLabels, memoryToFree); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Call to getVkDebugUtilsLabelEXTCollection failed"); return; } } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(vkDebugUtilsMessengerCallbackDataEXTClass, "getObjects", "()Ljava/util/Collection;"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error trying to get getObjects methodId"); return; } jobject jVkDebugUtilsObjectNameInfoEXTCollectionObject = env->CallObjectMethod(jVkDebugUtilsMessengerCallbackDataEXTObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallObjectMethod for getObjects"); return; } int numberOfObjects = 0; VkDebugUtilsObjectNameInfoEXT *objects = nullptr; if (jVkDebugUtilsObjectNameInfoEXTCollectionObject != nullptr) { jvulkan::getVkDebugUtilsObjectNameInfoEXTCollection( env, jVkDebugUtilsObjectNameInfoEXTCollectionObject, &objects, &numberOfObjects, memoryToFree); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Call to getVkDebugUtilsLabelEXTCollection failed"); return; } } vkDebugUtilsMessengerCallbackDataEXT->sType = sTypeValue; vkDebugUtilsMessengerCallbackDataEXT->pNext = (void *)pNext; vkDebugUtilsMessengerCallbackDataEXT->flags = flags; vkDebugUtilsMessengerCallbackDataEXT->pMessageIdName = theMessageIdName; vkDebugUtilsMessengerCallbackDataEXT->messageIdNumber = messageIdNumber; vkDebugUtilsMessengerCallbackDataEXT->pMessage = message; vkDebugUtilsMessengerCallbackDataEXT->queueLabelCount = numberOfQLabels; vkDebugUtilsMessengerCallbackDataEXT->pQueueLabels = queueLabels; vkDebugUtilsMessengerCallbackDataEXT->cmdBufLabelCount = numberOfCmdBufLabels; vkDebugUtilsMessengerCallbackDataEXT->pCmdBufLabels = cmdBufLabels; vkDebugUtilsMessengerCallbackDataEXT->objectCount = numberOfObjects; vkDebugUtilsMessengerCallbackDataEXT->pObjects = objects; } }
38.39924
142
0.600852
dkaip
3cfb7b723efebb24dbcb72dd1f603a83f9044e6f
5,778
cpp
C++
Viewer/ecflowUI/src/VNState.cpp
mpartio/ecflow
ea4b89399d1e7b897ff48c59b1e885e6d53cc8d6
[ "Apache-2.0" ]
null
null
null
Viewer/ecflowUI/src/VNState.cpp
mpartio/ecflow
ea4b89399d1e7b897ff48c59b1e885e6d53cc8d6
[ "Apache-2.0" ]
null
null
null
Viewer/ecflowUI/src/VNState.cpp
mpartio/ecflow
ea4b89399d1e7b897ff48c59b1e885e6d53cc8d6
[ "Apache-2.0" ]
null
null
null
//============================================================================ // Copyright 2009- ECMWF. // This software is licensed under the terms of the Apache Licence version 2.0 // which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. // In applying this licence, ECMWF does not waive the privileges and immunities // granted to it by virtue of its status as an intergovernmental organisation // nor does it submit to any jurisdiction. // //============================================================================ #include "VNState.hpp" #include <QDebug> #include <QImage> #include <QImageReader> #include <cstdlib> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <map> #include "VNode.hpp" #include "ServerHandler.hpp" #include "Submittable.hpp" #include "UserMessage.hpp" #include "VConfigLoader.hpp" #include "VProperty.hpp" std::map<std::string,VNState*> VNState::items_; static std::map<NState::State,VNState*> stateMap_; static std::map<unsigned char,VNState*> idMap_; static VNState unSt("unknown",NState::UNKNOWN); static VNState compSt("complete",NState::COMPLETE); static VNState queuedSt("queued",NState::QUEUED); static VNState abortedSt("aborted",NState::ABORTED); static VNState submittedSt("submitted",NState::SUBMITTED); static VNState activeSt("active",NState::ACTIVE); static VNState suspendedSt("suspended"); static unsigned char ucIdCnt=0; VNState::VNState(const std::string& name,NState::State nstate) : VParam(name), ucId_(ucIdCnt++) { items_[name]=this; stateMap_[nstate]=this; idMap_[ucId_]=this; } VNState::VNState(const std::string& name) : VParam(name) { items_[name]=this; } //=============================================================== // // Static methods // //=============================================================== std::vector<VParam*> VNState::filterItems() { std::vector<VParam*> v; for(std::map<std::string,VNState*>::const_iterator it=items_.begin(); it != items_.end(); ++it) { v.push_back(it->second); } return v; } VNState* VNState::toState(const VNode *n) { if(!n || !n->node().get()) return nullptr; node_ptr node=n->node(); if(node->isSuspended()) return items_["suspended"]; else { std::map<NState::State,VNState*>::const_iterator it=stateMap_.find(node->state()); if(it != stateMap_.end()) return it->second; } return nullptr; } VNState* VNState::toRealState(const VNode *n) { if(!n || !n->node().get()) return nullptr; node_ptr node=n->node(); std::map<NState::State,VNState*>::const_iterator it=stateMap_.find(node->state()); if(it != stateMap_.end()) return it->second; return nullptr; } VNState* VNState::toDefaultState(const VNode *n) { if(!n || !n->node()) return nullptr; node_ptr node=n->node(); const char *dStateName=DState::toString(node->defStatus()); assert(dStateName); std::string dsn(dStateName); return find(dsn); } VNState* VNState::find(const std::string& name) { std::map<std::string,VNState*>::const_iterator it=items_.find(name); if(it != items_.end()) return it->second; return nullptr; } VNState* VNState::find(unsigned char ucId) { std::map<unsigned char,VNState*>::const_iterator it=idMap_.find(ucId); if(it != idMap_.end()) return it->second; return nullptr; } // //Has to be very quick!! // QColor VNState::toColour(const VNode *n) { VNState *obj=VNState::toState(n); return (obj)?(obj->colour()):QColor(); } QColor VNState::toRealColour(const VNode *n) { VNState *obj=VNState::toRealState(n); return (obj)?(obj->colour()):QColor(); } QColor VNState::toFontColour(const VNode *n) { VNState *obj=VNState::toState(n); return (obj)?(obj->fontColour()):QColor(); } QColor VNState::toTypeColour(const VNode *n) { VNState *obj=VNState::toState(n); return (obj)?(obj->typeColour()):QColor(); } QString VNState::toName(const VNode *n) { VNState *obj=VNState::toState(n); return (obj)?(obj->name()):QString(); } QString VNState::toDefaultStateName(const VNode *n) { VNState *obj=VNState::toDefaultState(n); return (obj)?(obj->name()):QString(); } QString VNState::toRealStateName(const VNode *n) { VNState *obj=VNState::toRealState(n); return (obj)?(obj->name()):QString(); } bool VNState::isActive(unsigned char ucId) { VNState *obj=VNState::find(ucId); return (obj)?(obj->name() == "active"):false; } bool VNState::isComplete(unsigned char ucId) { VNState *obj=VNState::find(ucId); return (obj)?(obj->name() == "complete"):false; } bool VNState::isSubmitted(unsigned char ucId) { VNState *obj=VNState::find(ucId); return (obj)?(obj->name() == "submitted"):false; } //================================================== // Server state //================================================== VNState* VNState::toState(ServerHandler *s) { if(!s) return nullptr; bool susp=false; NState::State ns=s->state(susp); if(susp) return items_["suspended"]; else { std::map<NState::State,VNState*>::const_iterator it=stateMap_.find(ns); if(it != stateMap_.end()) return it->second; } return nullptr; } QString VNState::toName(ServerHandler *s) { VNState *obj=VNState::toState(s); return (obj)?(obj->name()):QString(); } QColor VNState::toColour(ServerHandler *s) { VNState *obj=VNState::toState(s); return (obj)?(obj->colour()):QColor(); } QColor VNState::toFontColour(ServerHandler *s) { VNState *obj=VNState::toState(s); return (obj)?(obj->fontColour()):QColor(); } void VNState::load(VProperty* group) { Q_FOREACH(VProperty* p,group->children()) { if(VNState* obj=VNState::find(p->strName())) { obj->setProperty(p); } } } static SimpleLoader<VNState> loader("nstate");
22.395349
96
0.632399
mpartio
3cfc529d9a5efdcf874b75ceceb00a285f64cbc9
4,617
cpp
C++
src/gpu/ocl/gemm_matmul.cpp
Acidburn0zzz/mkl-dnn
7b5378563e4774ff4165aecb8155d8f5c626ece1
[ "Apache-2.0" ]
1
2020-02-21T07:00:06.000Z
2020-02-21T07:00:06.000Z
src/gpu/ocl/gemm_matmul.cpp
riju/mkl-dnn
b8b06f9de7b3d58ca0c7c8d4df1838adbf1e75cc
[ "Apache-2.0" ]
null
null
null
src/gpu/ocl/gemm_matmul.cpp
riju/mkl-dnn
b8b06f9de7b3d58ca0c7c8d4df1838adbf1e75cc
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright 2020 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "gpu/ocl/gemm_matmul.hpp" #include "gpu/ocl/gemm/ocl_gemm_utils.hpp" namespace dnnl { namespace impl { namespace gpu { namespace ocl { status_t gemm_matmul_t::execute(const exec_ctx_t &ctx) const { using namespace gemm_utils; const auto src_d = ctx.memory_mdw(DNNL_ARG_SRC); const auto weights_d = ctx.memory_mdw(DNNL_ARG_WEIGHTS); const auto dst_d = ctx.memory_mdw(DNNL_ARG_DST); const auto bia_d = ctx.memory_mdw(DNNL_ARG_BIAS); memory_storage_t *scales = &CTX_IN_STORAGE(DNNL_ARG_ATTR_OUTPUT_SCALES); memory_storage_t *a0 = &CTX_IN_STORAGE(DNNL_ARG_ATTR_ZERO_POINTS | DNNL_ARG_SRC); memory_storage_t *b0 = &CTX_IN_STORAGE(DNNL_ARG_ATTR_ZERO_POINTS | DNNL_ARG_WEIGHTS); memory_storage_t *c0 = &CTX_IN_STORAGE(DNNL_ARG_ATTR_ZERO_POINTS | DNNL_ARG_DST); const bool is_batched = src_d.ndims() == 3; const dim_t MB = is_batched ? dst_d.dims()[0] : 1; const dim_t M = dst_d.dims()[is_batched + 0]; const dim_t N = dst_d.dims()[is_batched + 1]; const dim_t K = src_d.dims()[is_batched + 1]; const auto &dst_bd = dst_d.blocking_desc(); const auto &src_strides = &src_d.blocking_desc().strides[0]; const auto &weights_strides = &weights_d.blocking_desc().strides[0]; const auto &dst_strides = &dst_d.blocking_desc().strides[0]; int bias_mask = 0; if (is_batched) bias_mask |= (bia_d.dims()[0] > 1) ? 1 << 0 : 0; for (int d = is_batched; d < bia_d.ndims(); ++d) { bias_mask |= (bia_d.dims()[d] > 1) ? 1 << (bia_d.ndims() - d) : 0; } const transpose_t transA = src_strides[is_batched + 1] == 1 && src_d.dims()[is_batched + 0] > 1 ? transpose::notrans : transpose::trans; const transpose_t transB = weights_strides[is_batched + 1] == 1 && weights_d.dims()[is_batched + 0] > 1 ? transpose::notrans : transpose::trans; const int lda = (int) src_strides[is_batched + (transA == transpose::notrans ? 0 : 1)]; const int ldb = (int)weights_strides[is_batched + (transB == transpose::notrans ? 0 : 1)]; const int ldc = (int)dst_bd.strides[is_batched + 0]; const auto d = pd()->desc(); const auto src_dt = d->src_desc.data_type; const auto wei_dt = d->weights_desc.data_type; const auto bia_dt = d->bias_desc.data_type; const auto dst_dt = d->dst_desc.data_type; const auto acc_dt = d->accum_data_type; const int stride_a = (int)src_strides[0]; const int stride_b = (int)weights_strides[0]; const int stride_c = (int)dst_strides[0]; gemm_exec_args_t gemm_args; gemm_args.a = &CTX_IN_STORAGE(DNNL_ARG_WEIGHTS); gemm_args.b = &CTX_IN_STORAGE(DNNL_ARG_SRC); gemm_args.c = &CTX_OUT_STORAGE(DNNL_ARG_DST); gemm_args.bias = &CTX_IN_STORAGE(DNNL_ARG_BIAS); gemm_args.a_zero_point = b0; gemm_args.b_zero_point = a0; gemm_args.c_zero_point = c0; gemm_args.output_scales = scales; gemm_desc_t gemm_desc; gemm_desc.transa = transB; gemm_desc.transb = transA; gemm_desc.batch = MB; gemm_desc.m = N; gemm_desc.n = M; gemm_desc.k = K; gemm_desc.stride_a = stride_b; gemm_desc.stride_b = stride_a; gemm_desc.stride_c = stride_c; gemm_desc.lda = ldb; gemm_desc.ldb = lda; gemm_desc.ldc = ldc; gemm_desc.bias_mask = bias_mask; gemm_desc.a_type = wei_dt; gemm_desc.b_type = src_dt; gemm_desc.c_type = dst_dt; gemm_desc.acc_type = acc_dt; gemm_desc.bias_type = bia_dt; gemm_exec_ctx_t gemm_ctx(ctx.stream(), gemm_args, &gemm_desc); status_t gemm_status = gemm_impl(gemm_)->execute(gemm_ctx); if (gemm_status != status::success) return gemm_status; return status::success; } } // namespace ocl } // namespace gpu } // namespace impl } // namespace dnnl
35.790698
80
0.651722
Acidburn0zzz
3cfd1ad1843b87edf827622e2ae413e11d86faac
3,121
cpp
C++
simulations/ros2_bdi_on_webots/src/blocksworld/gripper/actions/gripper_pickup.cpp
devis12/ROS2-BDI
28a8b7d9545ddcc6862f3cb338737791eef709a6
[ "Apache-2.0" ]
4
2022-01-11T12:05:44.000Z
2022-03-31T19:34:02.000Z
simulations/ros2_bdi_on_webots/src/blocksworld/gripper/actions/gripper_pickup.cpp
devis12/ROS2-BDI
28a8b7d9545ddcc6862f3cb338737791eef709a6
[ "Apache-2.0" ]
8
2022-01-27T09:02:22.000Z
2022-02-21T16:41:27.000Z
simulations/ros2_bdi_on_webots/src/blocksworld/gripper/actions/gripper_pickup.cpp
devis12/ROS2-BDI
28a8b7d9545ddcc6862f3cb338737791eef709a6
[ "Apache-2.0" ]
1
2022-01-11T08:58:28.000Z
2022-01-11T08:58:28.000Z
#include <string> #include "rclcpp/rclcpp.hpp" #include "ros2_bdi_skills/bdi_action_executor.hpp" #include "example_interfaces/msg/string.hpp" #include "webots_ros2_simulations_interfaces/msg/move_status.hpp" using std::string; using example_interfaces::msg::String; using webots_ros2_simulations_interfaces::msg::MoveStatus; typedef enum {LOW, CLOSE, HIGH} PickupStatus; class GripperPickup : public BDIActionExecutor { public: GripperPickup() : BDIActionExecutor("gripper_pickup", 3) { robot_name_ = this->get_parameter("agent_id").as_string(); gripper_pose_cmd_publisher_ = this->create_publisher<String>("/"+robot_name_+"/cmd_gripper_pose", rclcpp::QoS(1).keep_all()); gripper_status_cmd_publisher_ = this->create_publisher<String>("/"+robot_name_+"/cmd_gripper_status", rclcpp::QoS(1).keep_all()); } rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn on_activate(const rclcpp_lifecycle::State & previous_state) { action_status_ = LOW; repeat_ = 0; gripper_pose_cmd_publisher_->on_activate(); gripper_status_cmd_publisher_->on_activate(); return BDIActionExecutor::on_activate(previous_state); } rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn on_deactivate(const rclcpp_lifecycle::State & previous_state) { gripper_pose_cmd_publisher_->on_deactivate(); gripper_status_cmd_publisher_->on_deactivate(); return BDIActionExecutor::on_deactivate(previous_state); } float advanceWork() { auto msg = String(); msg.data = (action_status_ == LOW)? "low" : ( (action_status_ == CLOSE)? "close" : "high" ); if(action_status_ == CLOSE) { gripper_status_cmd_publisher_->publish(msg); } else { gripper_pose_cmd_publisher_->publish(msg); } repeat_++; if(repeat_ == 3) { //publish same cmd for three action steps then switch to new status repeat_ = 0; action_status_ = (action_status_ == LOW)? CLOSE : HIGH; } return 0.112f; } private: PickupStatus action_status_; uint8_t repeat_; rclcpp_lifecycle::LifecyclePublisher<String>::SharedPtr gripper_pose_cmd_publisher_; rclcpp_lifecycle::LifecyclePublisher<String>::SharedPtr gripper_status_cmd_publisher_; rclcpp::Subscription<MoveStatus>::SharedPtr gripper_move_status_subscriber_; string robot_name_; }; int main(int argc, char ** argv) { rclcpp::init(argc, argv); auto actionNode = std::make_shared<GripperPickup>(); rclcpp::spin(actionNode->get_node_base_interface()); rclcpp::shutdown(); return 0; }
32.510417
141
0.612304
devis12
3cfd1fb8153ceae058e76c1c5e42a81c11fe0552
1,853
cc
C++
chrome/installer/util/create_dir_work_item.cc
rwatson/chromium-capsicum
b03da8e897f897c6ad2cda03ceda217b760fd528
[ "BSD-3-Clause" ]
11
2015-03-20T04:08:08.000Z
2021-11-15T15:51:36.000Z
chrome/installer/util/create_dir_work_item.cc
rwatson/chromium-capsicum
b03da8e897f897c6ad2cda03ceda217b760fd528
[ "BSD-3-Clause" ]
null
null
null
chrome/installer/util/create_dir_work_item.cc
rwatson/chromium-capsicum
b03da8e897f897c6ad2cda03ceda217b760fd528
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include "chrome/installer/util/create_dir_work_item.h" #include "chrome/installer/util/logging_installer.h" CreateDirWorkItem::~CreateDirWorkItem() { } CreateDirWorkItem::CreateDirWorkItem(const FilePath& path) : path_(path), rollback_needed_(false) { } void CreateDirWorkItem::GetTopDirToCreate() { if (file_util::PathExists(path_)) { top_path_ = FilePath(); return; } FilePath parent_dir(path_); do { top_path_ = parent_dir; parent_dir = parent_dir.DirName(); } while ((parent_dir != top_path_) && !file_util::PathExists(parent_dir)); return; } bool CreateDirWorkItem::Do() { LOG(INFO) << "creating directory " << path_.value(); GetTopDirToCreate(); if (top_path_.empty()) return true; LOG(INFO) << "top directory that needs to be created: " \ << top_path_.value(); bool result = file_util::CreateDirectory(path_); LOG(INFO) << "directory creation result: " << result; rollback_needed_ = true; return result; } void CreateDirWorkItem::Rollback() { if (!rollback_needed_) return; // Delete all the directories we created to rollback. // Note we can not recusively delete top_path_ since we don't want to // delete non-empty directory. (We may have created a shared directory). // Instead we walk through path_ to top_path_ and delete directories // along the way. FilePath path_to_delete(path_); while (1) { if (file_util::PathExists(path_to_delete)) { if (!RemoveDirectory(path_to_delete.value().c_str())) break; } if (path_to_delete == top_path_) break; path_to_delete = path_to_delete.DirName(); } return; }
26.471429
76
0.69401
rwatson
3cfdb53f39fad5fc2ad53400721f7fe9f5f0db96
834
hpp
C++
sel_map_mesh_publisher/include/sel_map_mesh_publisher/TriangularMeshPublisher.hpp
roahmlab/sel_map
51c5ac738eb7475f409f826c0d30f555f98757b3
[ "MIT" ]
2
2022-02-24T21:10:32.000Z
2022-03-11T20:00:09.000Z
sel_map_mesh_publisher/include/sel_map_mesh_publisher/TriangularMeshPublisher.hpp
roahmlab/sel_map
51c5ac738eb7475f409f826c0d30f555f98757b3
[ "MIT" ]
null
null
null
sel_map_mesh_publisher/include/sel_map_mesh_publisher/TriangularMeshPublisher.hpp
roahmlab/sel_map
51c5ac738eb7475f409f826c0d30f555f98757b3
[ "MIT" ]
null
null
null
#pragma once #include <ros/ros.h> #include <string> #include "msg_adaptor/MeshGeometryStampedCustom.hpp" // Placing all lib elements into a sel_map namespace, partly in case this is extended upon later, partly to reduce pollution. namespace sel_map::publisher{ template <typename MeshAdaptorType> class TriangularMeshPublisher{ ros::NodeHandle node_handle; ros::Publisher mesh_publisher; sel_map::msg_adaptor::MeshGeometryStampedCustom cached_message; public: MeshAdaptorType mesh_adaptor; TriangularMeshPublisher(const MeshAdaptorType& mesh_adaptor, std::string uuid, std::string frame_id, std::string mesh_topic); bool pubAlive(); void publishMesh(); unsigned int getSingleClassifications(int* buffer, unsigned int length); }; }
30.888889
133
0.718225
roahmlab
3cfe35544080783e5498d639955729242cf09caa
3,804
cpp
C++
Engine/source/T3D/containerQuery.cpp
jnoyola/Torque3D_GDDEast
15738ed79185c45e353ea4520dee0a94872ee870
[ "Unlicense" ]
1
2019-01-15T09:47:35.000Z
2019-01-15T09:47:35.000Z
Engine/source/T3D/containerQuery.cpp
jnoyola/Torque3D_GDDEast
15738ed79185c45e353ea4520dee0a94872ee870
[ "Unlicense" ]
null
null
null
Engine/source/T3D/containerQuery.cpp
jnoyola/Torque3D_GDDEast
15738ed79185c45e353ea4520dee0a94872ee870
[ "Unlicense" ]
null
null
null
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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 "platform/platform.h" #include "T3D/containerQuery.h" #include "scene/sceneObject.h" #include "environment/waterObject.h" #include "T3D/physicalZone.h" void findRouter( SceneObject *obj, void *key ) { if (obj->getTypeMask() & WaterObjectType) waterFind(obj, key); else if (obj->getTypeMask() & PhysicalZoneObjectType) physicalZoneFind(obj, key); else { AssertFatal(false, "Error, must be either water or physical zone here!"); } } void waterFind( SceneObject *obj, void *key ) { PROFILE_SCOPE( waterFind ); // This is called for each WaterObject the ShapeBase object is overlapping. ContainerQueryInfo *info = static_cast<ContainerQueryInfo*>(key); WaterObject *water = dynamic_cast<WaterObject*>(obj); AssertFatal( water != NULL, "containerQuery - waterFind(), passed object was not of class WaterObject!"); // Get point at the bottom/center of the box. Point3F testPnt = info->box.getCenter(); testPnt.z = info->box.minExtents.z; F32 coverage = water->getWaterCoverage(info->box); // Since a WaterObject can have global bounds we may get this call // even though we have zero coverage. If so we want to early out and // not save the water properties. if ( coverage == 0.0f ) return; // Add in flow force. Would be appropriate to try scaling it by coverage // thought. Or perhaps have getFlow do that internally and take // the box parameter. info->appliedForce += water->getFlow( testPnt ); // Only save the following properties for the WaterObject with the // greatest water coverage for this ShapeBase object. if ( coverage < info->waterCoverage ) return; info->waterCoverage = coverage; info->liquidType = water->getLiquidType(); info->waterViscosity = water->getViscosity(); info->waterDensity = water->getDensity(); info->waterHeight = water->getSurfaceHeight( Point2F(testPnt.x,testPnt.y) ); info->waterObject = water; } void physicalZoneFind(SceneObject* obj, void *key) { PROFILE_SCOPE( physicalZoneFind ); ContainerQueryInfo *info = static_cast<ContainerQueryInfo*>(key); PhysicalZone* pz = dynamic_cast<PhysicalZone*>(obj); AssertFatal(pz != NULL, "Error, not a physical zone!"); if (pz == NULL || pz->testBox(info->box) == false) return; if (pz->isActive()) { info->gravityScale *= pz->getGravityMod(); info->airResistanceScale *= pz->getAirResistanceMod(); info->appliedForce += pz->getForce(); } }
38.424242
114
0.680862
jnoyola
a70110104f41bdb2b9bac4086a9ea01d702272dd
947
cc
C++
src/connectivity/bluetooth/core/bt-host/l2cap/channel_configuration_fuzztest.cc
dahlia-os/fuchsia-pine64-pinephone
57aace6f0b0bd75306426c98ab9eb3ff4524a61d
[ "BSD-3-Clause" ]
14
2020-10-25T05:48:36.000Z
2021-09-20T02:46:20.000Z
src/connectivity/bluetooth/core/bt-host/l2cap/channel_configuration_fuzztest.cc
JokeZhang/fuchsia
d6e9dea8dca7a1c8fa89d03e131367e284b30d23
[ "BSD-3-Clause" ]
1
2022-01-14T23:38:40.000Z
2022-01-14T23:38:40.000Z
src/connectivity/bluetooth/core/bt-host/l2cap/channel_configuration_fuzztest.cc
JokeZhang/fuchsia
d6e9dea8dca7a1c8fa89d03e131367e284b30d23
[ "BSD-3-Clause" ]
4
2020-12-28T17:04:45.000Z
2022-03-12T03:20:44.000Z
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/connectivity/bluetooth/core/bt-host/l2cap/channel_configuration.h" #include "src/connectivity/bluetooth/core/bt-host/common/byte_buffer.h" #include "src/connectivity/bluetooth/core/bt-host/common/log.h" // Prevent "undefined symbol: __zircon_driver_rec__" error. BT_DECLARE_FAKE_DRIVER(); namespace bt { namespace l2cap { namespace internal { void fuzz(const uint8_t* data, size_t size) { DynamicByteBuffer buf(size); memcpy(buf.mutable_data(), data, size); ChannelConfiguration config; bool _result = config.ReadOptions(buf); // unused. (void)_result; } } // namespace internal } // namespace l2cap } // namespace bt extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { bt::l2cap::internal::fuzz(data, size); return 0; }
27.852941
80
0.74868
dahlia-os
a706248e68aead38a05656fb8465c8a270245089
960
cpp
C++
src/Modules/Helpers/Helpers/libhelpers/Dx/DxDeviceMt.cpp
sssr33/LuaModules
357a8c9445a237f2c98685000f6c7da668ea0e72
[ "MIT" ]
1
2020-02-24T22:21:04.000Z
2020-02-24T22:21:04.000Z
src/Modules/Helpers/Helpers/libhelpers/Dx/DxDeviceMt.cpp
sssr33/LuaModules
357a8c9445a237f2c98685000f6c7da668ea0e72
[ "MIT" ]
null
null
null
src/Modules/Helpers/Helpers/libhelpers/Dx/DxDeviceMt.cpp
sssr33/LuaModules
357a8c9445a237f2c98685000f6c7da668ea0e72
[ "MIT" ]
1
2019-10-11T12:48:44.000Z
2019-10-11T12:48:44.000Z
#include "DxDeviceMt.h" IDWriteFactory *DxDeviceMt::GetDwriteFactory() const { return this->dwriteFactory.Get(); } ID2D1Factory1 *DxDeviceMt::GetD2DFactory() const { return this->d2dFactory.Get(); } ID3D11Device *DxDeviceMt::GetD3DDevice() const { return this->d3dDev.Get(); } ID2D1Device *DxDeviceMt::GetD2DDevice() const { return this->d2dDevice.Get(); } D2DCtxMt *DxDeviceMt::GetD2DCtxMt() const { // TODO try to find better approach than const_cast D2DCtxMt *tmp = const_cast<D2DCtxMt *>(&this->d2dCtxMt); return tmp; } Microsoft::WRL::ComPtr<IDWriteFactory> DxDeviceMt::GetDwriteFactoryCPtr() const { return this->dwriteFactory; } Microsoft::WRL::ComPtr<ID2D1Factory1> DxDeviceMt::GetD2DFactoryCPtr() const { return this->d2dFactory; } Microsoft::WRL::ComPtr<ID3D11Device> DxDeviceMt::GetD3DDeviceCPtr() const { return this->d3dDev; } Microsoft::WRL::ComPtr<ID2D1Device> DxDeviceMt::GetD2DDeviceCPtr() const { return this->d2dDevice; }
24.615385
81
0.755208
sssr33
a7077296f0f92eed8004f61790ccc5839dd3de68
614
cpp
C++
water.cpp
sergiosvieira/mog
f23d2b18851bb58c3e60aae9b10deec023f2c9c8
[ "MIT" ]
null
null
null
water.cpp
sergiosvieira/mog
f23d2b18851bb58c3e60aae9b10deec023f2c9c8
[ "MIT" ]
null
null
null
water.cpp
sergiosvieira/mog
f23d2b18851bb58c3e60aae9b10deec023f2c9c8
[ "MIT" ]
null
null
null
#include "water.h" Water::Water(): TaticalMovingObject() { } Water::Water ( const Coordinates& position, const Vector& velocity, unsigned int initialTime, unsigned int lifeTime, const Vector &acceleration ): TaticalMovingObject(position, velocity, initialTime, lifeTime, acceleration, ObjectCategory::NavalShip) { } void Water::setMaxDepth(double value) { this->maxDepth = value; } double Water::getMaxDepth() const { return this->maxDepth; } void Water::setMinDepth(double value) { this->minDepth = value; } double Water::getMinDepth() const { return this->minDepth; }
15.74359
106
0.70684
sergiosvieira
a709f6fab3e2fd6c6b106b8bf667b7faadce9586
2,789
hpp
C++
Source/Utility/Maths.hpp
storm20200/WaterEngine
537910bc03e6d4016c9b22cf616d25afe40f77af
[ "MIT" ]
null
null
null
Source/Utility/Maths.hpp
storm20200/WaterEngine
537910bc03e6d4016c9b22cf616d25afe40f77af
[ "MIT" ]
2
2015-03-17T01:32:10.000Z
2015-03-19T18:58:28.000Z
Source/Utility/Maths.hpp
storm20200/WaterEngine
537910bc03e6d4016c9b22cf616d25afe40f77af
[ "MIT" ]
null
null
null
#if !defined WATER_UTILITY_MATHS_INCLUDED #define WATER_UTILITY_MATHS_INCLUDED // STL headers. #include <cmath> #include <type_traits> // Utility namespace. namespace util { ///////////////////// /// Miscellaneous /// ///////////////////// /// <summary> Checks if two float values are relatively equal to each other. </summary> /// <param name="margin"> The absolute margin of error between the two floats. Must be a positive value. </param> inline bool roughlyEquals (const float lhs, const float rhs, const float margin = 0.1f) { // Test the upper and lower limits. return std::abs (lhs - rhs) <= margin; } /////////////////// /// Comparisons /// /////////////////// /// <summary> Returns the minimum value, passed by value for arithmetic types. </summary> template <typename T> typename std::enable_if<std::is_arithmetic<T>::value, T>::type min (const T a, const T b) { return a < b ? a : b; } /// <summary> Returns the maximum value, passed by value for arithmetic types. </summary> template <typename T> typename std::enable_if<std::is_arithmetic<T>::value, T>::type max (const T a, const T b) { return a > b ? a : b; } /// <summary> Returns the minimum value, passed by reference for non-arithmetic types. </summary> template <typename T> typename std::enable_if<!std::is_arithmetic<T>::value, T>::type& min (const T& a, const T& b) { return a < b ? a : b; } /// <summary> Returns the maximum value, passed by reference for non-arithmetic types. </summary> template <typename T> typename std::enable_if<!std::is_arithmetic<T>::value, T>::type& max (const T& a, const T& b) { return a > b ? a : b; } /// <summary> Clamps a value between a given minimum and maximum value. Arithmetic types are passed by value. </summary> /// <param name="value"> The value to clamp. </param> template <typename T> typename std::enable_if<std::is_arithmetic<T>::value, T>::type clamp (const T value, const T min, const T max) { if (value < min) { return min; } if (value > max) { return max; } return value; } /// <summary> Clamps a value between a given minimum and maximum value. Non-arithmetic types are passed by reference. </summary> /// <param name="value"> The value to clamp. </param> template <typename T> typename std::enable_if<!std::is_arithmetic<T>::value, T>::type clamp (const T& value, const T& min, const T& max) { if (value < min) { return min; } if (value > max) { return max; } return value; } } #endif
29.357895
140
0.585873
storm20200
a70a5694f3dc2cd9c7593c0eb4bbda7485459800
634
cpp
C++
1001-1020/1005.cpp
nedchu/PTA-Advanced-Solution
9713142a48e7e416fd087980b6ac8251ae2b200f
[ "MIT" ]
1
2020-01-13T04:57:01.000Z
2020-01-13T04:57:01.000Z
1001-1020/1005.cpp
nedchu/PTA-Advanced-Solution
9713142a48e7e416fd087980b6ac8251ae2b200f
[ "MIT" ]
null
null
null
1001-1020/1005.cpp
nedchu/PTA-Advanced-Solution
9713142a48e7e416fd087980b6ac8251ae2b200f
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define all(x) (x).begin(), (x).end() #define fi first #define se second typedef long long ll; typedef pair<int,int> pii; // head const int N = 105; char s[105]; char dig[15][15] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; int main() { while (scanf("%s", s) == 1) { int n = strlen(s); int sum = 0; for (int i = 0; i < n; i++) { sum += s[i] - '0'; } sprintf(s, "%d", sum); n = strlen(s); for (int i = 0; i < n; i++) { printf("%s%c", dig[s[i]-'0'], i==n-1 ? '\n' : ' '); } } return 0; }
17.611111
57
0.477918
nedchu
a70c2edf4348da637b12849392e0cbdd483c3ccb
4,765
cc
C++
cvmfs/swissknife_lease_curl.cc
chrisburr/cvmfs
74691036341e6010c83e9dff093f0bcad6fd08e1
[ "BSD-3-Clause" ]
2
2021-05-15T05:22:23.000Z
2021-05-15T05:23:00.000Z
cvmfs/swissknife_lease_curl.cc
chrisburr/cvmfs
74691036341e6010c83e9dff093f0bcad6fd08e1
[ "BSD-3-Clause" ]
2
2021-11-18T16:48:22.000Z
2022-03-03T13:38:57.000Z
cvmfs/swissknife_lease_curl.cc
chrisburr/cvmfs
74691036341e6010c83e9dff093f0bcad6fd08e1
[ "BSD-3-Clause" ]
1
2021-12-13T00:20:14.000Z
2021-12-13T00:20:14.000Z
/** * This file is part of the CernVM File System. */ #include "swissknife_lease_curl.h" #include "cvmfs_config.h" #include "gateway_util.h" #include "hash.h" #include "json_document.h" #include "logging.h" #include "util/pointer.h" #include "util/string.h" namespace { CURL* PrepareCurl(const std::string& method) { const char* user_agent_string = "cvmfs/" VERSION; CURL* h_curl = curl_easy_init(); if (h_curl) { curl_easy_setopt(h_curl, CURLOPT_NOPROGRESS, 1L); curl_easy_setopt(h_curl, CURLOPT_USERAGENT, user_agent_string); curl_easy_setopt(h_curl, CURLOPT_MAXREDIRS, 50L); curl_easy_setopt(h_curl, CURLOPT_CUSTOMREQUEST, method.c_str()); } return h_curl; } size_t RecvCB(void* buffer, size_t size, size_t nmemb, void* userp) { CurlBuffer* my_buffer = static_cast<CurlBuffer*>(userp); if (size * nmemb < 1) { return 0; } my_buffer->data = static_cast<char*>(buffer); return my_buffer->data.size(); } } // namespace bool MakeAcquireRequest(const std::string& key_id, const std::string& secret, const std::string& repo_path, const std::string& repo_service_url, CurlBuffer* buffer) { CURLcode ret = static_cast<CURLcode>(0); CURL* h_curl = PrepareCurl("POST"); if (!h_curl) { return false; } const std::string payload = "{\"path\" : \"" + repo_path + "\", \"api_version\" : \"" + StringifyInt(gateway::APIVersion()) + "\"}"; shash::Any hmac(shash::kSha1); shash::HmacString(secret, payload, &hmac); const std::string header_str = std::string("Authorization: ") + key_id + " " + Base64(hmac.ToString(false)); struct curl_slist* auth_header = NULL; auth_header = curl_slist_append(auth_header, header_str.c_str()); curl_easy_setopt(h_curl, CURLOPT_HTTPHEADER, auth_header); // Make request to acquire lease from repo services curl_easy_setopt(h_curl, CURLOPT_URL, (repo_service_url + "/leases").c_str()); curl_easy_setopt(h_curl, CURLOPT_POSTFIELDSIZE_LARGE, static_cast<curl_off_t>(payload.length())); curl_easy_setopt(h_curl, CURLOPT_POSTFIELDS, payload.c_str()); curl_easy_setopt(h_curl, CURLOPT_WRITEFUNCTION, RecvCB); curl_easy_setopt(h_curl, CURLOPT_WRITEDATA, buffer); ret = curl_easy_perform(h_curl); if (ret) { LogCvmfs(kLogUploadGateway, kLogStderr, "Make lease acquire request failed: %d. Reply: %s", ret, buffer->data.c_str()); } curl_easy_cleanup(h_curl); h_curl = NULL; return !ret; } bool MakeEndRequest(const std::string& method, const std::string& key_id, const std::string& secret, const std::string& session_token, const std::string& repo_service_url, const std::string& request_payload, CurlBuffer* reply) { CURLcode ret = static_cast<CURLcode>(0); CURL* h_curl = PrepareCurl(method); if (!h_curl) { return false; } shash::Any hmac(shash::kSha1); shash::HmacString(secret, session_token, &hmac); const std::string header_str = std::string("Authorization: ") + key_id + " " + Base64(hmac.ToString(false)); struct curl_slist* auth_header = NULL; auth_header = curl_slist_append(auth_header, header_str.c_str()); curl_easy_setopt(h_curl, CURLOPT_HTTPHEADER, auth_header); curl_easy_setopt(h_curl, CURLOPT_URL, (repo_service_url + "/leases/" + session_token).c_str()); if (request_payload != "") { curl_easy_setopt(h_curl, CURLOPT_POSTFIELDSIZE_LARGE, static_cast<curl_off_t>(request_payload.length())); curl_easy_setopt(h_curl, CURLOPT_POSTFIELDS, request_payload.c_str()); } else { curl_easy_setopt(h_curl, CURLOPT_POSTFIELDSIZE_LARGE, static_cast<curl_off_t>(0)); curl_easy_setopt(h_curl, CURLOPT_POSTFIELDS, NULL); } curl_easy_setopt(h_curl, CURLOPT_WRITEFUNCTION, RecvCB); curl_easy_setopt(h_curl, CURLOPT_WRITEDATA, reply); ret = curl_easy_perform(h_curl); if (ret) { LogCvmfs(kLogUploadGateway, kLogStderr, "Lease end request - curl_easy_perform failed: %d", ret); } UniquePtr<JsonDocument> reply_json(JsonDocument::Create(reply->data)); const JSON *reply_status = JsonDocument::SearchInObject(reply_json->root(), "status", JSON_STRING); const bool ok = (reply_status != NULL && std::string(reply_status->string_value) == "ok"); if (!ok) { LogCvmfs(kLogUploadGateway, kLogStderr, "Lease end request - error reply: %s", reply->data.c_str()); } curl_easy_cleanup(h_curl); h_curl = NULL; return ok && !ret; }
32.195946
80
0.658342
chrisburr
a70d5dd955b42d4cf5a025fd252d7d27e99bcb74
1,987
cpp
C++
cryptopp562/algparam.cpp
xlplbo/cryptopp
a831383b9c407c2836d35154ad4d34778597ca5b
[ "Apache-2.0" ]
505
2016-02-04T15:54:46.000Z
2022-03-27T18:43:01.000Z
src/cryptopp/algparam.cpp
brozkeff/Slothcoin
a4af51f5d3292f993ef7c3d95ead1f344c38ad4a
[ "MIT" ]
528
2016-02-06T19:50:12.000Z
2022-01-15T10:21:16.000Z
src/cryptopp/algparam.cpp
brozkeff/Slothcoin
a4af51f5d3292f993ef7c3d95ead1f344c38ad4a
[ "MIT" ]
208
2015-01-02T10:31:40.000Z
2021-12-14T07:37:36.000Z
// algparam.cpp - written and placed in the public domain by Wei Dai #include "pch.h" #ifndef CRYPTOPP_IMPORTS #include "algparam.h" NAMESPACE_BEGIN(CryptoPP) PAssignIntToInteger g_pAssignIntToInteger = NULL; bool CombinedNameValuePairs::GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const { if (strcmp(name, "ValueNames") == 0) return m_pairs1.GetVoidValue(name, valueType, pValue) && m_pairs2.GetVoidValue(name, valueType, pValue); else return m_pairs1.GetVoidValue(name, valueType, pValue) || m_pairs2.GetVoidValue(name, valueType, pValue); } void AlgorithmParametersBase::operator=(const AlgorithmParametersBase& rhs) { assert(false); } bool AlgorithmParametersBase::GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const { if (strcmp(name, "ValueNames") == 0) { NameValuePairs::ThrowIfTypeMismatch(name, typeid(std::string), valueType); if (m_next.get()) m_next->GetVoidValue(name, valueType, pValue); (*reinterpret_cast<std::string *>(pValue) += m_name) += ";"; return true; } else if (strcmp(name, m_name) == 0) { AssignValue(name, valueType, pValue); m_used = true; return true; } else if (m_next.get()) return m_next->GetVoidValue(name, valueType, pValue); else return false; } AlgorithmParameters::AlgorithmParameters() : m_defaultThrowIfNotUsed(true) { } AlgorithmParameters::AlgorithmParameters(const AlgorithmParameters &x) : m_defaultThrowIfNotUsed(x.m_defaultThrowIfNotUsed) { m_next.reset(const_cast<AlgorithmParameters &>(x).m_next.release()); } AlgorithmParameters & AlgorithmParameters::operator=(const AlgorithmParameters &x) { m_next.reset(const_cast<AlgorithmParameters &>(x).m_next.release()); return *this; } bool AlgorithmParameters::GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const { if (m_next.get()) return m_next->GetVoidValue(name, valueType, pValue); else return false; } NAMESPACE_END #endif
26.144737
113
0.749874
xlplbo
a70e6941e1e1b44237cdc12c9f340d89f24d5274
4,087
cpp
C++
Project/src/Player.cpp
ishohois/DivisionEngine2D
3e38c2bf39e54b743bd01281980c4bdc502c93e4
[ "MIT" ]
null
null
null
Project/src/Player.cpp
ishohois/DivisionEngine2D
3e38c2bf39e54b743bd01281980c4bdc502c93e4
[ "MIT" ]
1
2021-12-14T08:33:06.000Z
2021-12-14T08:33:06.000Z
Project/src/Player.cpp
ishohois/DivisionEngine2D
3e38c2bf39e54b743bd01281980c4bdc502c93e4
[ "MIT" ]
null
null
null
#include "Player.h" #include <SystemResources.h> #include "TextureManager.h" #include "CollisionHandler.h" #include "Contact.h" #include "Input.h" #include "GameManager.h" #include "Bullet.h" namespace diva { /* */ Player::Player(int x, int y, int w, int h) : GameObject(), position(x, y), collider(position, w, h, "Player") { setTag("Player"); // laddar in spriten som ska användas samt sätter ett ID så att man kan hämta texuren från en map. sätter även en renderare. TextureManager::getInstance()->load((resPath + "images/PlayerSprite/RBS.png").c_str(), tag, system.renderer); rb.setGravity(0); // Eftersom spelet är topdown och vi fortfarande vill använda våran ridigbody klass så sätter vi gravity till 0. shootCounter = shootTime; counter = damageTimer; } void Player::gameObjectUpdate(float dt) { rb.resetForce(); //[Uträkning för vilken grad som spriten ska titta på] getAngle(); // Kolla imputs för att röra spelaren. if (InputHandler::getInstance()->getKeyDown(KEYS::A)) { rb.applyForceX(-6.0f); } if (InputHandler::getInstance()->getKeyDown(KEYS::D)) { rb.applyForceX(6.0f); } if (InputHandler::getInstance()->getKeyDown(KEYS::W)) { rb.applyForceY(-6.0f); } if (InputHandler::getInstance()->getKeyDown(KEYS::S)) { rb.applyForceY(6.0f); } shootCounter -= (dt / 100); if (InputHandler::getInstance()->getMouseButton(MOUSEBUTTON::LMB)) { shoot(shootCounter); } // När spelaren sjukter så ska den instanziera en annan klass som är av typ "Skott" eller liknande cf = int(((SDL_GetTicks() / 100) % 2)); rb.updatePhysics(dt); position += rb.getRbPosition(); if (rb.getVelocity().x != 0 || rb.getVelocity().y != 0) { isWalking = true; } else { isWalking = false; } collider.updateCollider(); if (isDamaged) { counter -= (dt / 100); } if (counter <= 0) { hp--; counter = damageTimer; isDamaged = false; } if (hp <= 0) { GameManager::getInstance()->remove(this); GameManager::getInstance()->removeCollider(collider); } } void Player::updateCollision(BoxCollider2D collision) { Contact c; if (CollisionHandler::collisionDetection(collider, collision, c)) { if (collision.getObjectTag() == "Enemy") { isDamaged = true; } if (collision.getObjectTag() == "Wall") { position += CollisionHandler::collisionResolution(collider, c); } } } void Player::draw() const { // OM player Velocity == 0 TextureManager::getInstance()->draw(tag, (int)position.x, (int)position.y, 57, 43, system.renderer, degrees, Spriteflip::HORIZONTALFLIP); if (isWalking) TextureManager::getInstance()->drawFrame(tag, (int)position.x, (int)position.y, 57, 43, cr, cf, system.renderer, degrees, Spriteflip::HORIZONTALFLIP); } void Player::getAngle() { float distX = collider.getCenterPoint().x - InputHandler::getInstance()->mousePos.x; float distY = InputHandler::getInstance()->mousePos.y - collider.getCenterPoint().y; float radians = (atan2(distY, distX)); degrees = -radians * (180 / 3.14); } void Player::shoot(float &sTime) { //Bullet *bull = nullptr; if (sTime >= 0) { return; } Vector2D v{(float)InputHandler::getInstance()->mousePos.x, (float)InputHandler::getInstance()->mousePos.y}; Bullet *bull = new Bullet(position, v); sTime = shootTime; bull = nullptr; } Player::~Player() { } }
27.246667
162
0.553707
ishohois
a7135529b1a781871edb93e6262ea6f251140998
5,332
hpp
C++
src/ascent/runtimes/ascent_mfem_data_adapter.hpp
jameskress/ascent
db799bc1e076b5413607ed45913d4c9c2b7fa421
[ "BSD-3-Clause" ]
null
null
null
src/ascent/runtimes/ascent_mfem_data_adapter.hpp
jameskress/ascent
db799bc1e076b5413607ed45913d4c9c2b7fa421
[ "BSD-3-Clause" ]
null
null
null
src/ascent/runtimes/ascent_mfem_data_adapter.hpp
jameskress/ascent
db799bc1e076b5413607ed45913d4c9c2b7fa421
[ "BSD-3-Clause" ]
2
2018-02-28T14:15:23.000Z
2018-07-05T18:30:07.000Z
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// // Copyright (c) 2015-2019, Lawrence Livermore National Security, LLC. // // Produced at the Lawrence Livermore National Laboratory // // LLNL-CODE-716457 // // All rights reserved. // // This file is part of Ascent. // // For details, see: http://ascent.readthedocs.io/. // // Please also read ascent/LICENSE // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the disclaimer below. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the disclaimer (as noted below) in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the LLNS/LLNL 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 LAWRENCE LIVERMORE NATIONAL SECURITY, // LLC, THE U.S. DEPARTMENT OF ENERGY 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. // //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// //----------------------------------------------------------------------------- /// /// file: ascent_mfem_data_adapter.hpp /// //----------------------------------------------------------------------------- #ifndef ASCENT_MFEM_DATA_ADAPTER_HPP #define ASCENT_MFEM_DATA_ADAPTER_HPP // conduit includes #include <conduit.hpp> #include <mfem.hpp> //----------------------------------------------------------------------------- // -- begin ascent:: -- //----------------------------------------------------------------------------- namespace ascent { class MFEMDataSet { public: using FieldMap = std::map<std::string, mfem::GridFunction*>; MFEMDataSet(); ~MFEMDataSet(); MFEMDataSet(mfem::Mesh *mesh); void set_mesh(mfem::Mesh *mesh); mfem::Mesh* get_mesh(); void add_field(mfem::GridFunction *field, const std::string &name); bool has_field(const std::string &field_name); mfem::GridFunction* get_field(const std::string &field_name); int num_fields(); FieldMap get_field_map(); protected: FieldMap m_fields; mfem::Mesh *m_mesh; }; struct MFEMDomains { std::vector<MFEMDataSet*> m_data_sets; std::vector<int> m_domain_ids; ~MFEMDomains() { for(int i = 0; i < m_data_sets.size(); ++i) { delete m_data_sets[i]; } } }; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Class that Handles Blueprint to mfem //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- class MFEMDataAdapter { public: // convert blueprint mfem data to a mfem data set // assumes "n" conforms to the mesh blueprint // // conduit::blueprint::mesh::verify(n,info) == true // static MFEMDomains* BlueprintToMFEMDataSet(const conduit::Node &n, const std::string &topo_name=""); static bool IsHighOrder(const conduit::Node &n); static void Linearize(MFEMDomains *ho_domains, conduit::Node &output, const int refinement); static void GridFunctionToBlueprintField(mfem::GridFunction *gf, conduit::Node &out, const std::string &main_topology_name = "main"); static void MeshToBlueprintMesh(mfem::Mesh *m, conduit::Node &out, const std::string &coordset_name = "coords", const std::string &main_topology_name = "main", const std::string &boundary_topology_name = "boundary"); static std::string ElementTypeToShapeName(mfem::Element::Type element_type); }; //----------------------------------------------------------------------------- }; //----------------------------------------------------------------------------- // -- end ascent:: -- //----------------------------------------------------------------------------- #endif //----------------------------------------------------------------------------- // -- end header ifdef guard //-----------------------------------------------------------------------------
36.027027
96
0.525319
jameskress
a716143b80f1c96106e3eecbc7787226e960ea8a
3,221
cpp
C++
Source/WebCore/svg/SVGClipPathElement.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
6
2021-07-05T16:09:39.000Z
2022-03-06T22:44:42.000Z
Source/WebCore/svg/SVGClipPathElement.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
7
2022-03-15T13:25:39.000Z
2022-03-15T13:25:44.000Z
Source/WebCore/svg/SVGClipPathElement.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (C) 2004, 2005, 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org> * Copyright (C) 2004, 2005, 2006, 2007, 2008 Rob Buis <buis@kde.org> * Copyright (C) Research In Motion Limited 2009-2010. All rights reserved. * Copyright (C) 2018 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "SVGClipPathElement.h" #include "Document.h" #include "ImageBuffer.h" #include "RenderSVGResourceClipper.h" #include "SVGNames.h" #include "StyleResolver.h" #include <wtf/IsoMallocInlines.h> #include <wtf/NeverDestroyed.h> namespace WebCore { WTF_MAKE_ISO_ALLOCATED_IMPL(SVGClipPathElement); inline SVGClipPathElement::SVGClipPathElement(const QualifiedName& tagName, Document& document) : SVGGraphicsElement(tagName, document) { ASSERT(hasTagName(SVGNames::clipPathTag)); static std::once_flag onceFlag; std::call_once(onceFlag, [] { PropertyRegistry::registerProperty<SVGNames::clipPathUnitsAttr, SVGUnitTypes::SVGUnitType, &SVGClipPathElement::m_clipPathUnits>(); });} Ref<SVGClipPathElement> SVGClipPathElement::create(const QualifiedName& tagName, Document& document) { return adoptRef(*new SVGClipPathElement(tagName, document)); } void SVGClipPathElement::parseAttribute(const QualifiedName& name, const AtomString& value) { if (name == SVGNames::clipPathUnitsAttr) { auto propertyValue = SVGPropertyTraits<SVGUnitTypes::SVGUnitType>::fromString(value); if (propertyValue > 0) m_clipPathUnits->setBaseValInternal<SVGUnitTypes::SVGUnitType>(propertyValue); return; } SVGGraphicsElement::parseAttribute(name, value); } void SVGClipPathElement::svgAttributeChanged(const QualifiedName& attrName) { if (PropertyRegistry::isKnownAttribute(attrName)) { InstanceInvalidationGuard guard(*this); if (RenderObject* object = renderer()) object->setNeedsLayout(); return; } SVGGraphicsElement::svgAttributeChanged(attrName); } void SVGClipPathElement::childrenChanged(const ChildChange& change) { SVGGraphicsElement::childrenChanged(change); if (change.source == ChildChangeSource::Parser) return; if (RenderObject* object = renderer()) object->setNeedsLayout(); } RenderPtr<RenderElement> SVGClipPathElement::createElementRenderer(RenderStyle&& style, const RenderTreePosition&) { return createRenderer<RenderSVGResourceClipper>(*this, WTFMove(style)); } }
33.905263
139
0.743247
jacadcaps
a7195ffdfcf572028748b287b7f6513194f62166
1,856
hpp
C++
third_party/boost/simd/arch/ppc/vmx/simd/function/rsqrt.hpp
xmar/pythran
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
[ "BSD-3-Clause" ]
1
2018-01-14T12:49:14.000Z
2018-01-14T12:49:14.000Z
third_party/boost/simd/arch/ppc/vmx/simd/function/rsqrt.hpp
xmar/pythran
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
[ "BSD-3-Clause" ]
null
null
null
third_party/boost/simd/arch/ppc/vmx/simd/function/rsqrt.hpp
xmar/pythran
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
[ "BSD-3-Clause" ]
2
2017-12-12T12:29:52.000Z
2019-04-08T15:55:25.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_ARCH_PPC_VMX_SIMD_FUNCTION_RSQRT_HPP_INCLUDED #define BOOST_SIMD_ARCH_PPC_VMX_SIMD_FUNCTION_RSQRT_HPP_INCLUDED #include <boost/simd/detail/overload.hpp> #include <boost/simd/constant/one.hpp> #include <boost/simd/constant/half.hpp> #include <boost/simd/constant/zero.hpp> #include <boost/simd/function/fma.hpp> #include <boost/simd/function/sqr.hpp> namespace boost { namespace simd { namespace ext { namespace bd = boost::dispatch; namespace bs = boost::simd; BOOST_DISPATCH_OVERLOAD( rsqrt_ , (typename A0) , bs::vmx_ , bs::pack_< bd::single_<A0>, bs::vmx_> ) { BOOST_FORCEINLINE A0 operator()(const A0& a0) const BOOST_NOEXCEPT { A0 o = One<A0>(); A0 estimate = fast_(rsqrt)(a0); A0 se = sqr(estimate); A0 he = estimate*Half<A0>(); A0 st = vec_nmsub(a0.storage(),se.storage(),o.storage()); return fma(st, he, estimate); } }; BOOST_DISPATCH_OVERLOAD( rsqrt_ , (typename A0) , bs::vmx_ , bs::fast_tag , bs::pack_< bd::single_<A0>, bs::vmx_> ) { BOOST_FORCEINLINE A0 operator()(bs::fast_tag const&, const A0& a0) const BOOST_NOEXCEPT { return vec_rsqrte( a0.storage() ); } }; } } } #endif
32
100
0.515086
xmar
a71a4a9cfa00696c592dbb3c5c783fe891256ce8
3,756
hpp
C++
altona/wz4lib/build.hpp
kebby/Werkkzeug4
f2ff557020d62c348b54d88e137999175b5c18a3
[ "BSD-2-Clause" ]
10
2020-11-26T09:45:15.000Z
2022-03-18T00:18:27.000Z
altona/wz4lib/build.hpp
kebby/Werkkzeug4
f2ff557020d62c348b54d88e137999175b5c18a3
[ "BSD-2-Clause" ]
null
null
null
altona/wz4lib/build.hpp
kebby/Werkkzeug4
f2ff557020d62c348b54d88e137999175b5c18a3
[ "BSD-2-Clause" ]
3
2020-01-02T19:11:44.000Z
2022-03-18T00:21:45.000Z
/*+**************************************************************************/ /*** ***/ /*** Copyright (C) by Dierk Ohlerich ***/ /*** all rights reserverd ***/ /*** ***/ /*** To license this software, please contact the copyright holder. ***/ /*** ***/ /**************************************************************************+*/ #ifndef FILE_WERKKZEUG4_BUILD_HPP #define FILE_WERKKZEUG4_BUILD_HPP #ifndef __GNUC__ #pragma once #endif #include "base/types2.hpp" #include "doc.hpp" class ScriptCompiler; class ScriptContext; /****************************************************************************/ struct wNode { wOp *Op; // each node has to represent an op. wOp *ScriptOp; // copy script from this op. Used for subroutine argumtent injection wNode **Inputs; wType *OutType; // real output type. Some ops specify "AnyType" as output. sInt InputCount; sInt FakeInputCount; // parameter only inputs sInt CycleCheck; sInt CallId; // this node is part of a subroutine call sPoolString LoopName; // for injecting loop counters with a fake op sF32 LoopValue; sInt LoopFlag; // inside call or loop (possibly multiple different results for the same op) sInt OutputCount; // used internally to find out good cache points sU8 StoreCache; // while execution, store cache sU8 LoadCache; // do no execute op, just load cache sU8 Visited; // used during recursion (OptimizeCacheR) wCommand *StoreCacheDone; // use the store cache! }; struct wBuilderPush { wNode *CallInputs; wOp *CallOp; sArray<wNode *> FakeInputs; // for call and loop sInt CurrentCallId; sInt LoopFlag; void GetFrom(wBuilder *); void PutTo(wBuilder *); }; class wBuilder { friend struct wBuilderPush; sMemoryPool *Pool; wNode *Root; wNode *MakeNode(sInt ic,sInt fc=0); const sChar *MakeString(const sChar *str1,const sChar *str2=0,const sChar *str3=0); wNode *ParseR(wOp *op,sInt recursion); void OptimizeCacheR(wNode **node); wCommand *OutputR(wExecutive &,wNode *node); wNode *SkipToSlowR(wNode *node); wCommand *MakeCommand(wExecutive &exe,wOp *op,wCommand **inputs,sInt inputcount,wOp *scriptop,wOp *d0,const sChar *d1,sInt callid,sInt fakeinputcount); void Error(wOp *op,const sChar *text); sInt Errors; void rssall(wNode *node,sInt flag); wNode *CallInputs; wOp *CallOp; sArray<wNode *> FakeInputs; // for call and loop sInt CallId; sInt CurrentCallId; sInt TypeCheckOnly; sInt LoopFlag; struct RecursionData_ { sArray<wOp *> inputs; sEndlessArray<sInt> inputloop; RecursionData_() : inputloop(-1) {} }; sEndlessArray<RecursionData_ *> RecursionData; // the new and delete in the recursion are very costly, especially with debug runtime. We can reuse the arrays! public: wBuilder(); ~wBuilder(); sBool Parse(wOp *root); sBool Optimize(sBool Cache); sBool TypeCheck(); sBool Output(wExecutive &); void SkipToSlow(sBool honorslow); sBool Check(wOp *root); sBool Depend(wExecutive &exe,wOp *root); wObject *Execute(wExecutive &,wOp *root,sBool honorslow,sBool progress); wObject *FindCache(wOp *root); sArray<wNode *> AllNodes; }; /****************************************************************************/ #endif // FILE_WERKKZEUG4_BUILD_HPP
33.238938
160
0.561235
kebby
a71ad25bdf939c6c0bfca9a4594ea7403041f7b3
1,290
cpp
C++
hiro/gtk/widget/vertical-slider.cpp
moon-chilled/Ares
909fb098c292f8336d0502dc677050312d8b5c81
[ "0BSD" ]
7
2020-07-25T11:44:39.000Z
2021-01-29T13:21:31.000Z
hiro/gtk/widget/vertical-slider.cpp
jchw-forks/ares
d78298a1e95fd0ce65feabfd4f13b60e31210a7a
[ "0BSD" ]
null
null
null
hiro/gtk/widget/vertical-slider.cpp
jchw-forks/ares
d78298a1e95fd0ce65feabfd4f13b60e31210a7a
[ "0BSD" ]
1
2021-03-22T16:15:30.000Z
2021-03-22T16:15:30.000Z
#if defined(Hiro_VerticalSlider) namespace hiro { static auto VerticalSlider_change(GtkRange* gtkRange, pVerticalSlider* p) -> void { auto position = (uint)gtk_range_get_value(gtkRange); if(p->state().position == position) return; p->state().position = position; if(!p->locked()) p->self().doChange(); } auto pVerticalSlider::construct() -> void { #if HIRO_GTK==2 gtkWidget = gtk_vscale_new_with_range(0, 100, 1); #elif HIRO_GTK==3 gtkWidget = gtk_scale_new_with_range(GTK_ORIENTATION_VERTICAL, 0, 100, 1); #endif gtk_scale_set_draw_value(GTK_SCALE(gtkWidget), false); setLength(state().length); setPosition(state().position); g_signal_connect(G_OBJECT(gtkWidget), "value-changed", G_CALLBACK(VerticalSlider_change), (gpointer)this); pWidget::construct(); } auto pVerticalSlider::destruct() -> void { gtk_widget_destroy(gtkWidget); } auto pVerticalSlider::minimumSize() const -> Size { return {20, 3}; } auto pVerticalSlider::setLength(uint length) -> void { length += length == 0; gtk_range_set_range(GTK_RANGE(gtkWidget), 0, max(1u, length - 1)); gtk_range_set_increments(GTK_RANGE(gtkWidget), 1, length >> 3); } auto pVerticalSlider::setPosition(uint position) -> void { gtk_range_set_value(GTK_RANGE(gtkWidget), position); } } #endif
26.326531
108
0.727907
moon-chilled
a71ea393263a96910de8d964b8af7ef71c21d279
2,304
hpp
C++
liboslayer/Pool.hpp
bjtj/oslayer
92cc41288a4bae8e63a680fe714806e89421df16
[ "MIT" ]
1
2020-03-08T14:25:24.000Z
2020-03-08T14:25:24.000Z
liboslayer/Pool.hpp
bjtj/oslayer
92cc41288a4bae8e63a680fe714806e89421df16
[ "MIT" ]
null
null
null
liboslayer/Pool.hpp
bjtj/oslayer
92cc41288a4bae8e63a680fe714806e89421df16
[ "MIT" ]
null
null
null
#ifndef __POOL_HPP__ #define __POOL_HPP__ #include <algorithm> #include <deque> #include "Mutex.hpp" namespace osl { template <typename T> class Pool { private: Mutex _avail_lock; Mutex _work_lock; std::deque<T*> _avails; std::deque<T*> _works; size_t _size; public: Pool(size_t size) : _size(size) { alloc(); } virtual ~Pool() { clear(); } protected: void alloc() { for (size_t i = 0; i < _size; i++) { T * t = new T; _avails.push_back(t); } } void clear() { for (typename std::deque<T*>::iterator iter = _avails.begin(); iter != _avails.end(); iter++) { delete *iter; } for (typename std::deque<T*>::iterator iter = _works.begin(); iter != _works.end(); iter++) { delete *iter; } _avails.clear(); _works.clear(); } public: void lock_avail() { _avail_lock.lock(); } void unlock_avail() { _avail_lock.unlock(); } void lock_work() { _work_lock.lock(); } void unlock_work() { _work_lock.unlock(); } T * acquire() { _avail_lock.lock(); T * item = _avails.size() > 0 ? _avails.front() : NULL; if (item) { _avails.pop_front(); } _avail_lock.unlock(); return item; } void release(T * t) { _avail_lock.lock(); if (std::find(_avails.begin(), _avails.end(), t) == _avails.end()) { _avails.push_back(t); } _avail_lock.unlock(); } void enqueue(T * t) { _work_lock.lock(); if (std::find(_works.begin(), _works.end(), t) == _works.end()) { _works.push_back(t); } _work_lock.unlock(); } T * dequeue() { _work_lock.lock(); T * item = _works.size() > 0 ? _works.front() : NULL; if (item) { _works.pop_front(); } _work_lock.unlock(); return item; } void rest(T * t) { _work_lock.lock(); for (typename std::deque<T*>::iterator iter = _works.begin(); iter != _works.end(); iter++) { if (*iter == t) { _works.erase(iter); break; } } _work_lock.unlock(); } size_t available() const { return _avails.size(); } size_t busy() const { return _works.size(); } std::deque<T*> & avail_queue() { return _avails; } std::deque<T*> & work_queue() { return _works; } size_t size() const { return _size; } }; } #endif
19.862069
100
0.565538
bjtj
a71ea451de4e885b9a84996a0b6cbcb50850eebc
23,336
cc
C++
src/stim/dem/detector_error_model.test.cc
noajshu/Stim
503de420b1e56e90d7f44337ead1065a2ae26740
[ "Apache-2.0" ]
null
null
null
src/stim/dem/detector_error_model.test.cc
noajshu/Stim
503de420b1e56e90d7f44337ead1065a2ae26740
[ "Apache-2.0" ]
null
null
null
src/stim/dem/detector_error_model.test.cc
noajshu/Stim
503de420b1e56e90d7f44337ead1065a2ae26740
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "stim/dem/detector_error_model.h" #include <gtest/gtest.h> #include "stim/test_util.test.h" using namespace stim; TEST(detector_error_model, init_equality) { DetectorErrorModel model1; DetectorErrorModel model2; ASSERT_TRUE(model1 == model2); ASSERT_TRUE(!(model1 != model2)); model1.append_shift_detectors_instruction({}, 5); ASSERT_TRUE(model1 != model2); ASSERT_TRUE(!(model1 == model2)); model2.append_shift_detectors_instruction({}, 4); ASSERT_NE(model1, model2); model1.clear(); model2.clear(); ASSERT_EQ(model1, model2); model1.append_repeat_block(5, {}); model2.append_repeat_block(4, {}); ASSERT_NE(model1, model2); model1.append_error_instruction(0.2, {}); model2.append_repeat_block(4, {}); ASSERT_NE(model1, model2); } TEST(detector_error_model, append_shift_detectors_instruction) { DetectorErrorModel model; ASSERT_EQ(model.instructions.size(), 0); ASSERT_EQ(model.blocks.size(), 0); std::vector<double> arg_data{1.5, 2.5}; ConstPointerRange<double> arg_data_ref = arg_data; model.append_shift_detectors_instruction(arg_data_ref, 5); ASSERT_EQ(model.instructions.size(), 1); ASSERT_EQ(model.instructions[0].type, DEM_SHIFT_DETECTORS); ASSERT_EQ(model.instructions[0].target_data.size(), 1); ASSERT_EQ(model.instructions[0].target_data[0].data, 5); ASSERT_EQ(model.instructions[0].arg_data, arg_data_ref); ASSERT_EQ(model.blocks.size(), 0); } TEST(detector_error_model, append_detector_instruction) { DetectorErrorModel model; ASSERT_EQ(model.instructions.size(), 0); ASSERT_EQ(model.blocks.size(), 0); std::vector<double> arg_data{1.5, 2.5}; ConstPointerRange<double> arg_data_ref = arg_data; model.append_detector_instruction(arg_data_ref, DemTarget::relative_detector_id(5)); ASSERT_EQ(model.instructions.size(), 1); ASSERT_EQ(model.instructions[0].type, DEM_DETECTOR); ASSERT_EQ(model.instructions[0].target_data.size(), 1); ASSERT_EQ(model.instructions[0].target_data[0], DemTarget::relative_detector_id(5)); ASSERT_EQ(model.instructions[0].arg_data, arg_data_ref); ASSERT_EQ(model.blocks.size(), 0); ASSERT_THROW({ model.append_detector_instruction({}, DemTarget::separator()); }, std::invalid_argument); ASSERT_THROW({ model.append_detector_instruction({}, DemTarget::observable_id(4)); }, std::invalid_argument); model.append_detector_instruction({}, DemTarget::relative_detector_id(4)); } TEST(detector_error_model, append_logical_observable_instruction) { DetectorErrorModel model; ASSERT_EQ(model.instructions.size(), 0); ASSERT_EQ(model.blocks.size(), 0); model.append_logical_observable_instruction(DemTarget::observable_id(5)); ASSERT_EQ(model.instructions.size(), 1); ASSERT_EQ(model.instructions[0].type, DEM_LOGICAL_OBSERVABLE); ASSERT_EQ(model.instructions[0].target_data.size(), 1); ASSERT_EQ(model.instructions[0].target_data[0], DemTarget::observable_id(5)); ASSERT_EQ(model.instructions[0].arg_data.size(), 0); ASSERT_EQ(model.blocks.size(), 0); ASSERT_THROW({ model.append_logical_observable_instruction(DemTarget::separator()); }, std::invalid_argument); ASSERT_THROW( { model.append_logical_observable_instruction(DemTarget::relative_detector_id(4)); }, std::invalid_argument); model.append_logical_observable_instruction(DemTarget::observable_id(4)); } TEST(detector_error_model, append_error_instruction) { DetectorErrorModel model; std::vector<DemTarget> symptoms; symptoms.push_back(DemTarget::observable_id(3)); symptoms.push_back(DemTarget::relative_detector_id(4)); model.append_error_instruction(0.25, symptoms); ASSERT_EQ(model.instructions.size(), 1); ASSERT_EQ(model.blocks.size(), 0); ASSERT_EQ(model.instructions[0].type, DEM_ERROR); ASSERT_EQ(model.instructions[0].target_data, (PointerRange<DemTarget>)symptoms); ASSERT_EQ(model.instructions[0].arg_data.size(), 1); ASSERT_EQ(model.instructions[0].arg_data[0], 0.25); model.clear(); ASSERT_EQ(model.instructions.size(), 0); symptoms.push_back(DemTarget::separator()); symptoms.push_back(DemTarget::observable_id(4)); model.append_error_instruction(0.125, symptoms); ASSERT_EQ(model.instructions.size(), 1); ASSERT_EQ(model.blocks.size(), 0); ASSERT_EQ(model.instructions[0].type, DEM_ERROR); ASSERT_EQ(model.instructions[0].target_data, (PointerRange<DemTarget>)symptoms); ASSERT_EQ(model.instructions[0].arg_data.size(), 1); ASSERT_EQ(model.instructions[0].arg_data[0], 0.125); ASSERT_THROW({ model.append_error_instruction(1.5, symptoms); }, std::invalid_argument); ASSERT_THROW({ model.append_error_instruction(-0.5, symptoms); }, std::invalid_argument); symptoms = {DemTarget::separator()}; ASSERT_THROW({ model.append_error_instruction(0.25, symptoms); }, std::invalid_argument); symptoms = {DemTarget::separator(), DemTarget::observable_id(0)}; ASSERT_THROW({ model.append_error_instruction(0.25, symptoms); }, std::invalid_argument); symptoms = {DemTarget::observable_id(0), DemTarget::separator()}; ASSERT_THROW({ model.append_error_instruction(0.25, symptoms); }, std::invalid_argument); symptoms = { DemTarget::observable_id(0), DemTarget::separator(), DemTarget::separator(), DemTarget::relative_detector_id(4)}; ASSERT_THROW({ model.append_error_instruction(0.25, symptoms); }, std::invalid_argument); symptoms = {DemTarget::observable_id(0), DemTarget::separator(), DemTarget::relative_detector_id(4)}; model.append_error_instruction(0.25, symptoms); } TEST(detector_error_model, append_block) { DetectorErrorModel model; DetectorErrorModel block; block.append_shift_detectors_instruction({}, 3); DetectorErrorModel block2 = block; model.append_repeat_block(5, block); block.append_shift_detectors_instruction({}, 4); model.append_repeat_block(6, std::move(block)); model.append_repeat_block(20, block2); ASSERT_EQ(model.instructions.size(), 3); ASSERT_EQ(model.blocks.size(), 3); ASSERT_EQ(model.instructions[0].type, DEM_REPEAT_BLOCK); ASSERT_EQ(model.instructions[0].target_data[0].data, 5); ASSERT_EQ(model.instructions[0].target_data[1].data, 0); ASSERT_EQ(model.instructions[1].type, DEM_REPEAT_BLOCK); ASSERT_EQ(model.instructions[1].target_data[0].data, 6); ASSERT_EQ(model.instructions[1].target_data[1].data, 1); ASSERT_EQ(model.instructions[2].type, DEM_REPEAT_BLOCK); ASSERT_EQ(model.instructions[2].target_data[0].data, 20); ASSERT_EQ(model.instructions[2].target_data[1].data, 2); ASSERT_EQ(model.blocks[0], block2); ASSERT_EQ(model.blocks[2], block2); block2.append_shift_detectors_instruction({}, 4); ASSERT_EQ(model.blocks[1], block2); } TEST(detector_error_model, round_trip_str) { const char *t = R"MODEL(error(0.125) D0 repeat 100 { repeat 200 { error(0.25) D0 D1 L0 ^ D2 shift_detectors(1.5, 3) 10 detector(0.5) D0 detector D1 } error(0.375) D0 D1 shift_detectors 20 logical_observable L0 })MODEL"; ASSERT_EQ(DetectorErrorModel(t).str(), std::string(t)); } TEST(detector_error_model, parse) { DetectorErrorModel expected; ASSERT_EQ(DetectorErrorModel(""), expected); expected.append_error_instruction(0.125, (std::vector<DemTarget>{DemTarget::relative_detector_id(0)})); ASSERT_EQ( DetectorErrorModel(R"MODEL( error(0.125) D0 )MODEL"), expected); expected.append_error_instruction(0.125, (std::vector<DemTarget>{DemTarget::relative_detector_id(5)})); ASSERT_EQ( DetectorErrorModel(R"MODEL( error(0.125) D0 error(0.125) D5 )MODEL"), expected); expected.append_error_instruction( 0.25, (std::vector<DemTarget>{ DemTarget::relative_detector_id(5), DemTarget::separator(), DemTarget::observable_id(4)})); ASSERT_EQ( DetectorErrorModel(R"MODEL( error(0.125) D0 error(0.125) D5 error(0.25) D5 ^ L4 )MODEL"), expected); expected.append_shift_detectors_instruction(std::vector<double>{1.5, 2}, 60); ASSERT_EQ( DetectorErrorModel(R"MODEL( error(0.125) D0 error(0.125) D5 error(0.25) D5 ^ L4 shift_detectors(1.5, 2) 60 )MODEL"), expected); expected.append_repeat_block(100, expected); ASSERT_EQ( DetectorErrorModel(R"MODEL( error(0.125) D0 error(0.125) D5 error(0.25) D5 ^ L4 shift_detectors(1.5, 2) 60 repeat 100 { error(0.125) D0 error(0.125) D5 error(0.25) D5 ^ L4 shift_detectors(1.5, 2) 60 } )MODEL"), expected); } TEST(detector_error_model, movement) { const char *t = R"MODEL( error(0.2) D0 REPEAT 100 { REPEAT 200 { error(0.1) D0 D1 L0 ^ D2 shift_detectors 10 } error(0.1) D0 D2 shift_detectors 20 } )MODEL"; DetectorErrorModel d1(t); DetectorErrorModel d2(d1); ASSERT_EQ(d1, d2); ASSERT_EQ(d1, DetectorErrorModel(t)); DetectorErrorModel d3(std::move(d1)); ASSERT_EQ(d1, DetectorErrorModel()); ASSERT_EQ(d2, d3); ASSERT_EQ(d2, DetectorErrorModel(t)); d1 = d3; ASSERT_EQ(d1, d2); ASSERT_EQ(d2, d3); ASSERT_EQ(d2, DetectorErrorModel(t)); d1 = std::move(d2); ASSERT_EQ(d1, d3); ASSERT_EQ(d2, DetectorErrorModel()); ASSERT_EQ(d1, DetectorErrorModel(t)); } TEST(dem_target, general) { DemTarget d = DemTarget::relative_detector_id(3); ASSERT_TRUE(d == DemTarget::relative_detector_id(3)); ASSERT_TRUE(!(d != DemTarget::relative_detector_id(3))); ASSERT_TRUE(!(d == DemTarget::relative_detector_id(4))); ASSERT_TRUE(d != DemTarget::relative_detector_id(4)); ASSERT_EQ(d, DemTarget::relative_detector_id(3)); ASSERT_NE(d, DemTarget::observable_id(5)); ASSERT_NE(d, DemTarget::separator()); DemTarget d3 = DemTarget::relative_detector_id(72); DemTarget s = DemTarget::separator(); DemTarget o = DemTarget::observable_id(3); ASSERT_EQ(d.str(), "D3"); ASSERT_EQ(d3.str(), "D72"); ASSERT_EQ(o.str(), "L3"); ASSERT_EQ(s.str(), "^"); ASSERT_TRUE(!o.is_separator()); ASSERT_TRUE(!d3.is_separator()); ASSERT_TRUE(s.is_separator()); ASSERT_TRUE(o.is_observable_id()); ASSERT_TRUE(!d3.is_observable_id()); ASSERT_TRUE(!s.is_observable_id()); ASSERT_TRUE(!o.is_relative_detector_id()); ASSERT_TRUE(d3.is_relative_detector_id()); ASSERT_TRUE(!s.is_relative_detector_id()); } TEST(dem_instruction, general) { std::vector<DemTarget> d1; d1.push_back(DemTarget::observable_id(4)); d1.push_back(DemTarget::relative_detector_id(3)); std::vector<DemTarget> d2; d2.push_back(DemTarget::observable_id(4)); std::vector<double> p125{0.125}; std::vector<double> p25{0.25}; std::vector<double> p126{0.126}; DemInstruction i1{p125, d1, DEM_ERROR}; DemInstruction i1a{p125, d1, DEM_ERROR}; DemInstruction i2{p125, d2, DEM_ERROR}; ASSERT_TRUE(i1 == i1a); ASSERT_TRUE(!(i1 != i1a)); ASSERT_TRUE(!(i2 == i1a)); ASSERT_TRUE(i2 != i1a); ASSERT_EQ(i1, (DemInstruction{p125, d1, DEM_ERROR})); ASSERT_NE(i1, (DemInstruction{p125, d2, DEM_ERROR})); ASSERT_NE(i1, (DemInstruction{p25, d1, DEM_ERROR})); ASSERT_NE(((DemInstruction{{}, {}, DEM_DETECTOR})), (DemInstruction{{}, {}, DEM_LOGICAL_OBSERVABLE})); ASSERT_TRUE(i1.approx_equals(DemInstruction{p125, d1, DEM_ERROR}, 0)); ASSERT_TRUE(!i1.approx_equals(DemInstruction{p126, d1, DEM_ERROR}, 0)); ASSERT_TRUE(i1.approx_equals(DemInstruction{p126, d1, DEM_ERROR}, 0.01)); ASSERT_TRUE(!i1.approx_equals(DemInstruction{p125, d2, DEM_ERROR}, 9999)); ASSERT_EQ(i1.str(), "error(0.125) L4 D3"); ASSERT_EQ(i2.str(), "error(0.125) L4"); d1.push_back(DemTarget::separator()); d1.push_back(DemTarget::observable_id(11)); ASSERT_EQ((DemInstruction{p25, d1, DEM_ERROR}).str(), "error(0.25) L4 D3 ^ L11"); } TEST(detector_error_model, total_detector_shift) { ASSERT_EQ(DetectorErrorModel("").total_detector_shift(), 0); ASSERT_EQ(DetectorErrorModel("error(0.3) D2").total_detector_shift(), 0); ASSERT_EQ(DetectorErrorModel("shift_detectors 5").total_detector_shift(), 5); ASSERT_EQ(DetectorErrorModel("shift_detectors 5\nshift_detectors 4").total_detector_shift(), 9); ASSERT_EQ( DetectorErrorModel(R"MODEL( shift_detectors 5 repeat 1000 { shift_detectors 4 } )MODEL") .total_detector_shift(), 4005); } TEST(detector_error_model, count_detectors) { ASSERT_EQ(DetectorErrorModel("").count_detectors(), 0); ASSERT_EQ(DetectorErrorModel("error(0.3) D2 L1000").count_detectors(), 3); ASSERT_EQ(DetectorErrorModel("shift_detectors 5").count_detectors(), 0); ASSERT_EQ(DetectorErrorModel("shift_detectors 5\ndetector D3").count_detectors(), 9); ASSERT_EQ( DetectorErrorModel(R"MODEL( shift_detectors 50 repeat 1000 { detector D0 error(0.1) D0 D1 shift_detectors 4 } )MODEL") .count_detectors(), 4048); } TEST(detector_error_model, count_observables) { ASSERT_EQ(DetectorErrorModel("").count_observables(), 0); ASSERT_EQ(DetectorErrorModel("error(0.3) L2 D9999").count_observables(), 3); ASSERT_EQ(DetectorErrorModel("shift_detectors 5\nlogical_observable L3").count_observables(), 4); ASSERT_EQ( DetectorErrorModel(R"MODEL( shift_detectors 50 repeat 1000 { logical_observable L5 error(0.1) D0 D1 L6 shift_detectors 4 } )MODEL") .count_observables(), 7); } TEST(detector_error_model, from_file) { FILE *f = tmpfile(); const char *program = R"MODEL( error(0.125) D1 REPEAT 99 { error(0.25) D3 D4 shift_detectors 1 } )MODEL"; fprintf(f, "%s", program); rewind(f); auto d = DetectorErrorModel::from_file(f); ASSERT_EQ(d, DetectorErrorModel(program)); d.clear(); rewind(f); d.append_from_file(f); ASSERT_EQ(d, DetectorErrorModel(program)); d.clear(); rewind(f); d.append_from_file(f, false); ASSERT_EQ(d, DetectorErrorModel(program)); d.clear(); rewind(f); d.append_from_file(f, true); ASSERT_EQ(d, DetectorErrorModel("error(0.125) D1")); d.append_from_file(f, true); ASSERT_EQ(d, DetectorErrorModel(program)); } TEST(detector_error_model, py_get_slice) { DetectorErrorModel d(R"MODEL( detector D2 logical_observable L1 error(0.125) D0 L1 REPEAT 100 { shift_detectors(0.25) 5 REPEAT 20 { } } error(0.125) D1 D2 REPEAT 999 { } )MODEL"); ASSERT_EQ(d.py_get_slice(0, 1, 6), d); ASSERT_EQ(d.py_get_slice(0, 1, 4), DetectorErrorModel(R"MODEL( detector D2 logical_observable L1 error(0.125) D0 L1 REPEAT 100 { shift_detectors(0.25) 5 REPEAT 20 { } } )MODEL")); ASSERT_EQ(d.py_get_slice(2, 1, 3), DetectorErrorModel(R"MODEL( error(0.125) D0 L1 REPEAT 100 { shift_detectors(0.25) 5 REPEAT 20 { } } error(0.125) D1 D2 )MODEL")); ASSERT_EQ(d.py_get_slice(4, -1, 3), DetectorErrorModel(R"MODEL( error(0.125) D1 D2 REPEAT 100 { shift_detectors(0.25) 5 REPEAT 20 { } } error(0.125) D0 L1 )MODEL")); ASSERT_EQ(d.py_get_slice(5, -2, 3), DetectorErrorModel(R"MODEL( REPEAT 999 { } REPEAT 100 { shift_detectors(0.25) 5 REPEAT 20 { } } logical_observable L1 )MODEL")); DetectorErrorModel d2 = d; DetectorErrorModel d3 = d2.py_get_slice(0, 1, 6); d2.clear(); ASSERT_EQ(d, d3); } TEST(detector_error_model, mul) { DetectorErrorModel original(R"MODEL( error(0.25) D0 REPEAT 999 { error(0.25) D1 } )MODEL"); DetectorErrorModel d = original; ASSERT_EQ(d * 3, DetectorErrorModel(R"MODEL( REPEAT 3 { error(0.25) D0 REPEAT 999 { error(0.25) D1 } } )MODEL")); ASSERT_EQ(d * 1, d); ASSERT_EQ(d * 0, DetectorErrorModel()); ASSERT_EQ(d, original); } TEST(detector_error_model, imul) { DetectorErrorModel original(R"MODEL( error(0.25) D0 REPEAT 999 { error(0.25) D1 } )MODEL"); DetectorErrorModel d = original; d *= 3; ASSERT_EQ(d, DetectorErrorModel(R"MODEL( REPEAT 3 { error(0.25) D0 REPEAT 999 { error(0.25) D1 } } )MODEL")); d = original; d *= 1; ASSERT_EQ(d, original); d = original; d *= 0; ASSERT_EQ(d, DetectorErrorModel()); } TEST(detector_error_model, add) { DetectorErrorModel a(R"MODEL( error(0.25) D0 REPEAT 999 { error(0.25) D1 } )MODEL"); DetectorErrorModel b(R"MODEL( error(0.125) D1 REPEAT 2 { REPEAT 3 { error(0.125) D1 } } )MODEL"); ASSERT_EQ(a + b, DetectorErrorModel(R"MODEL( error(0.25) D0 REPEAT 999 { error(0.25) D1 } error(0.125) D1 REPEAT 2 { REPEAT 3 { error(0.125) D1 } } )MODEL")); ASSERT_EQ(a + DetectorErrorModel(), a); ASSERT_EQ(DetectorErrorModel() + a, a); ASSERT_EQ(b + DetectorErrorModel(), b); ASSERT_EQ(DetectorErrorModel() + b, b); ASSERT_EQ(DetectorErrorModel() + DetectorErrorModel(), DetectorErrorModel()); } TEST(detector_error_model, iadd) { DetectorErrorModel a(R"MODEL( error(0.25) D0 REPEAT 999 { error(0.25) D1 } )MODEL"); DetectorErrorModel b(R"MODEL( error(0.125) D1 REPEAT 2 { REPEAT 3 { error(0.125) D1 } } )MODEL"); a += b; ASSERT_EQ(a, DetectorErrorModel(R"MODEL( error(0.25) D0 REPEAT 999 { error(0.25) D1 } error(0.125) D1 REPEAT 2 { REPEAT 3 { error(0.125) D1 } } )MODEL")); DetectorErrorModel original = b; b += DetectorErrorModel(); ASSERT_EQ(b, original); b += a; ASSERT_NE(b, original); // Aliased. a = original; a += a; a = DetectorErrorModel(a.str().data()); // Remove memory deduplication, because it affects equality. ASSERT_EQ(a, original + original); } TEST(detector_error_model, iter_flatten_error_instructions) { DetectorErrorModel d(R"MODEL( error(0.25) D0 shift_detectors 1 error(0.375) D0 D1 repeat 5 { error(0.125) D0 D1 D2 L0 shift_detectors 2 } detector D5000 logical_observable L5000 )MODEL"); DetectorErrorModel dem; d.iter_flatten_error_instructions([&](const DemInstruction &e) { EXPECT_EQ(e.type, DEM_ERROR); dem.append_error_instruction(e.arg_data[0], e.target_data); }); ASSERT_EQ(dem, DetectorErrorModel(R"MODEL( error(0.25) D0 error(0.375) D1 D2 error(0.125) D1 D2 D3 L0 error(0.125) D3 D4 D5 L0 error(0.125) D5 D6 D7 L0 error(0.125) D7 D8 D9 L0 error(0.125) D9 D10 D11 L0 )MODEL")); } TEST(detector_error_model, get_detector_coordinates_nested_loops) { DetectorErrorModel dem(R"MODEL( repeat 200 { repeat 100 { detector(0, 0, 0, 4) D1 shift_detectors(1, 0, 0) 10 } detector(0, 0, 0, 3) D2 shift_detectors(0, 1, 0) 0 } detector(0, 0, 0, 2) D3 )MODEL"); ASSERT_THROW({ dem.get_detector_coordinates({4000000000}); }, std::invalid_argument); ASSERT_THROW({ dem.get_detector_coordinates({dem.count_detectors()}); }, std::invalid_argument); auto result = dem.get_detector_coordinates({ 0, 1, 11, 991, 1001, 1002, 1011, 1021, }); ASSERT_EQ( result, (std::map<uint64_t, std::vector<double>>{ {0, {}}, {1, {0, 0, 0, 4}}, {11, {1, 0, 0, 4}}, {991, {99, 0, 0, 4}}, {1001, {100, 1, 0, 4}}, {1002, {100, 0, 0, 3}}, {1011, {101, 1, 0, 4}}, {1021, {102, 1, 0, 4}}, })); } TEST(detector_error_model, get_detector_coordinates_trivial) { DetectorErrorModel dem; dem = DetectorErrorModel(R"MODEL( detector(1, 2) D1 )MODEL"); ASSERT_EQ(dem.get_detector_coordinates({0, 1}), (std::map<uint64_t, std::vector<double>>{ {0, {}}, {1, {1, 2}}, })); ASSERT_THROW({ dem.get_detector_coordinates({2}); }, std::invalid_argument); dem = DetectorErrorModel(R"MODEL( error(0.25) D0 D1 )MODEL"); ASSERT_EQ(dem.get_detector_coordinates({0, 1}), (std::map<uint64_t, std::vector<double>>{ {0, {}}, {1, {}}, })); ASSERT_THROW({ dem.get_detector_coordinates({2}); }, std::invalid_argument); dem = DetectorErrorModel(R"MODEL( error(0.25) D0 D1 detector(1, 2, 3) D1 shift_detectors(5) 1 detector(1, 2) D2 )MODEL"); ASSERT_EQ(dem.get_detector_coordinates({0, 1, 2, 3}), (std::map<uint64_t, std::vector<double>>{ {0, {}}, {1, {1, 2, 3}}, {2, {}}, {3, {6, 2}}, })); ASSERT_THROW({ dem.get_detector_coordinates({4}); }, std::invalid_argument); } TEST(detector_error_model, final_detector_and_coord_shift) { DetectorErrorModel dem(R"MODEL( repeat 1000 { repeat 2000 { repeat 3000 { shift_detectors(0, 0, 1) 0 } shift_detectors(1) 2 } shift_detectors(0, 1) 0 } )MODEL"); ASSERT_EQ( dem.final_detector_and_coord_shift(), (std::pair<uint64_t, std::vector<double>>{4000000, {2000000, 1000, 6000000000}})); }
31.706522
117
0.625857
noajshu
a71fd3fb8c339b2ab32c4b0525c64ca7c8fc088c
26,785
cpp
C++
Launcher/src/mainwindow.cpp
ProtocolONE/cord.app
0defd4e2cbc25d4f414fa68f8c1dfe65eadc02e7
[ "Apache-2.0" ]
8
2019-01-16T07:09:39.000Z
2020-11-06T23:13:46.000Z
Launcher/src/mainwindow.cpp
ProtocolONE/cord.app
0defd4e2cbc25d4f414fa68f8c1dfe65eadc02e7
[ "Apache-2.0" ]
null
null
null
Launcher/src/mainwindow.cpp
ProtocolONE/cord.app
0defd4e2cbc25d4f414fa68f8c1dfe65eadc02e7
[ "Apache-2.0" ]
3
2019-09-30T02:45:09.000Z
2019-09-30T23:17:26.000Z
#include <mainwindow.h> #include <Player.h> #include <BestInstallPath.h> #include <HostMessageAdapter.h> #include <Helper/CacheNetworkManagerFactory.h> #include <Features/PlainFileCache.h> #include <Features/Marketing/MarketingIntegrationMarker.h> #include <viewmodel/UpdateViewModel.h> #include <viewmodel/ApplicationStatisticViewModel.h> #include <viewmodel/SettingsViewModel.h> #include <viewmodel/GameSettingsViewModel.h> #include <viewmodel/ServiceHandleViewModel.h> #include <viewmodel/SettingsManagerViewModel.h> #include <Host/Translation.h> #include <Host/ClientConnection.h> #include <Host/Dbus/DbusConnection.h> #include <Host/Dbus/DownloaderBridgeProxy.h> #include <Host/Dbus/DownloaderSettingsBridgeProxy.h> #include <Host/Dbus/ServiceSettingsBridgeProxy.h> #include <Host/Dbus/ExecutorBridgeProxy.h> #include <Host/Dbus/ApplicationBridgeProxy.h> #include <Host/Dbus/ApplicationStatisticBridgeProxy.h> #include <Host/Dbus/LicenseManagerBridgeProxy.h> #include <Core/UI/Message.h> #include <Core/Marketing.h> #include <Core/System/FileInfo.h> #include <Core/System/HardwareId.h> #include <GameExecutor/GameExecutorService.h> #include <UpdateSystem/UpdateInfoGetterResultInterface.h> #include <RestApi/Request/RequestFactory.h> #include <Application/WindowHelper.h> #include <Settings/settings.h> #include <QtCore/QTranslator> #include <QtCore/QSysInfo> #include <QtCore/QFlags> #include <QtCore/QStringList> #include <QtCore/QSysInfo> #include <QtWidgets/QBoxLayout> #include <QtWidgets/QDesktopWidget> #include <QQmlEngine> #include <QQmlContext> #include <QQuickItem> #include <QQmlError> #include <QMetaType> #define SIGNAL_CONNECT_CHECK(X) { bool result = X; Q_ASSERT_X(result, __FUNCTION__ , #X); } using P1::Host::DBus::DBusConnection; using P1::Host::ClientConnection; using P1::RestApi::ProtocolOneCredential; MainWindow::MainWindow(QWindow *parent) : QQuickView(parent) , _gameArea(P1::Core::Service::Live) , _downloader(nullptr) , _downloaderSettings(nullptr) , _serviceSettings(nullptr) , _executor(nullptr) , _applicationProxy(nullptr) , _applicationStatistic(nullptr) , _clientConnection(nullptr) , _bestInstallPath(nullptr) { this->hide(); QString path = QCoreApplication::applicationDirPath(); path += "/Config.yaml"; if (!this->_configManager.load(path)) qWarning() << "Cannot read application config file: " << path; } MainWindow::~MainWindow() { } void MainWindow::initialize() { qRegisterMetaType<P1::Host::Bridge::DownloadProgressArgs>("P1::Host::Bridge::DownloadProgressArgs"); qDBusRegisterMetaType<P1::Host::Bridge::DownloadProgressArgs>(); // DBUS... QDBusConnection &connection = DBusConnection::bus(); QString dbusService("com.protocolone.launcher.dbus"); this->_clientConnection = new ClientConnection("Launcher", this); this->_clientConnection->init(); QObject::connect(this->_clientConnection, &ClientConnection::disconnected, this, &MainWindow::onWindowClose); QObject::connect(this->_clientConnection, &ClientConnection::authorizationError, this, &MainWindow::authorizationError); this->_applicationProxy = new ApplicationBridgeProxy(dbusService, "/application", connection, this); this->_downloader = new DownloaderBridgeProxy(dbusService, "/downloader", connection, this); this->_downloaderSettings = new DownloaderSettingsBridgeProxy(dbusService, "/downloader/settings", connection, this); this->_serviceSettings = new ServiceSettingsBridgeProxy(dbusService, "/serviceSettings", connection, this); this->_executor = new ExecutorBridgeProxy(dbusService, "/executor", connection, this); this->_applicationStatistic = new ApplicationStatisticBridgeProxy(dbusService, "/applicationStatistic", connection, this); this->_licenseManager = new LicenseManagerBridgeProxy(dbusService, "/licenseManager", connection, this); QObject::connect(this->_applicationProxy, &ApplicationBridgeProxy::languageChanged, this, &MainWindow::languageChanged); this->_bestInstallPath = new BestInstallPath(this); this->_bestInstallPath->setServiceSettings(this->_serviceSettings); QObject::connect(this->_applicationProxy, &ApplicationBridgeProxy::initCompleted, this, &MainWindow::initCompleted); QObject::connect(this->_applicationProxy, &ApplicationBridgeProxy::restartUIRequest, this, &MainWindow::restartUIRequest); QObject::connect(this->_applicationProxy, &ApplicationBridgeProxy::shutdownUIRequest, this, &MainWindow::shutdownUIRequest); QObject::connect(this->_applicationProxy, &ApplicationBridgeProxy::uninstallServiceRequest, this, &MainWindow::uninstallServiceRequest); QObject::connect(this->_applicationProxy, &ApplicationBridgeProxy::additionalResourcesReady, this, &MainWindow::additionalResourcesReady); qRegisterMetaType<P1::Host::Bridge::DownloadProgressArgs>("P1::Host::Bridge::DownloadProgressArgs"); qDBusRegisterMetaType<P1::Host::Bridge::DownloadProgressArgs>(); new HostMessageAdapter(this); this->initRestApi(); this->_commandLineArguments.parse(QCoreApplication::arguments()); if (this->_commandLineArguments.contains("gamepts")) this->_gameArea = P1::Core::Service::Pts; if (this->_commandLineArguments.contains("gametest")) this->_gameArea = P1::Core::Service::Tst; this->setFileVersion(P1::Core::System::FileInfo::version(QCoreApplication::applicationFilePath())); this->setTitle("ProtocolOne " + this->_fileVersion); this->setColor(QColor(0, 0, 0, 0)); this->setFlags(Qt::Window | Qt::FramelessWindowHint | Qt::WindowMinimizeButtonHint | Qt::WindowSystemMenuHint); //Этот код уберет все внешние элементы формы P1::Host::Translation::load(this->translators, this); this->selectLanguage(this->_applicationProxy->language()); this->checkDesktopDepth(); this->settingsViewModel = new SettingsViewModel(this); this->settingsViewModel->setDownloaderSettings(this->_downloaderSettings); this->settingsViewModel->setApplicationProxy(this->_applicationProxy); qmlRegisterType<UpdateViewModel>("Launcher.Library", 1, 0, "UpdateViewModel"); qmlRegisterType<Player>("Launcher.Library", 1, 0, "Player"); qmlRegisterType<P1::Core::UI::Message>("Launcher.Library", 1, 0, "Message"); qmlRegisterType<ApplicationStatisticViewModel>("Launcher.Library", 1, 0, "ApplicationStatistic"); qmlRegisterType<ServiceHandleViewModel>("Launcher.Library", 1, 0, "ServiceHandle"); qmlRegisterType<SettingsManagerViewModel>("Launcher.Library", 1, 0, "SettingsManager"); qmlRegisterUncreatableType<P1::Downloader::DownloadResultsWrapper>("Launcher.Library", 1, 0, "DownloadResults", ""); qmlRegisterUncreatableType<P1::UpdateSystem::UpdateInfoGetterResultsWrapper>("Launcher.Library", 1, 0, "UpdateInfoGetterResults", ""); //this->initMarketing(); this->engine()->setNetworkAccessManagerFactory(new CacheNetworkManagerFactory(this)); this->engine()->addImportPath(":/"); this->engine()->addImportPath((QCoreApplication::applicationDirPath() + "/plugins5/")); this->engine()->addPluginPath(QCoreApplication::applicationDirPath() + "/plugins5/"); QObject::connect( &this->_restapiManager, &P1::RestApi::RestApiManager::authorizationError, this, &MainWindow::onAuthorizationError); messageAdapter = new QmlMessageAdapter(this); this->_gameSettingsViewModel = new GameSettingsViewModel(this); this->_gameSettingsViewModel->setDownloader(this->_downloader); this->_gameSettingsViewModel->setServiceSettings(this->_serviceSettings); this->rootContext()->setContextProperty("keyboardHook", &this->_keyboardLayoutHelper); this->rootContext()->setContextProperty("mainWindow", this); this->rootContext()->setContextProperty("installPath", "file:///" + QCoreApplication::applicationDirPath() + "/"); this->rootContext()->setContextProperty("settingsViewModel", settingsViewModel); this->rootContext()->setContextProperty("messageBox", messageAdapter); this->rootContext()->setContextProperty("gameSettingsModel", this->_gameSettingsViewModel); this->setResizeMode(QQuickView::SizeRootObjectToView); this->setSource(QUrl("qrc:/Main.qml")); if (this->status() == QQuickView::Status::Error) { Q_FOREACH(const QQmlError& error, this->errors()) { DEBUG_LOG << error; } // UNDONE решить что делать в случаи фейла верстки } QObject::connect(this->engine(), &QQmlEngine::quit, this, &MainWindow::onWindowClose); QObject::connect(this, &MainWindow::quit, this, &MainWindow::onWindowClose); Message::setAdapter(messageAdapter); if (this->_commandLineArguments.contains("minimized")) { //this->showMinimized(); this->hide(); } else { DEBUG_LOG; this->activateWindow(); } this->sendStartingMarketing(); this->_keyboardLayoutHelper.update(); } void MainWindow::hideToTaskBar() { this->showMinimized(); } void MainWindow::sendStartingMarketing() { int dwMajorVersion = 6; int dwMinorVersion = 1; switch (QSysInfo::windowsVersion()) { case QSysInfo::WV_5_1: dwMajorVersion = 5; dwMinorVersion = 1; break; case QSysInfo::WV_6_0: dwMajorVersion = 6; dwMinorVersion = 0; break; case QSysInfo::WV_6_1: dwMajorVersion = 6; dwMinorVersion = 1; break; case QSysInfo::WV_6_2: dwMajorVersion = 6; dwMinorVersion = 2; break; case QSysInfo::WV_6_3: dwMajorVersion = 6; dwMinorVersion = 3; break; case QSysInfo::WV_10_0: dwMajorVersion = 10; dwMinorVersion = 0; break; } QVariantMap params; params["windowsMajorVersion"] = dwMajorVersion; params["windowsMinorVersion"] = dwMinorVersion; params["windowsVersion"] = QSysInfo::productVersion(); params["updateArea"] = this->settingsViewModel->updateArea(); params["version"] = this->_fileVersion; P1::Core::Marketing::send(P1::Core::Marketing::AnyStartLauncher, params); P1::Core::Marketing::sendOnce(P1::Core::Marketing::FirstRunLauncher); } void MainWindow::restartUISlot(bool minimized) { this->_applicationProxy->restartApplication(minimized); } void MainWindow::shutdownUISlot() { this->_applicationProxy->shutdownUIResult(); this->onWindowClose(); } void MainWindow::terminateGame(const QString& serviceId) { this->_executor->terminateGame(serviceId); } bool MainWindow::isInitCompleted() { return this->_applicationProxy->isInitCompleted(); } void MainWindow::checkDesktopDepth() { QDesktopWidget widget; if (widget.depth() == 16) { QString info = QObject::tr("SCREEN_DEPTH_LOVER_THAN_16_INFO"); QString caption = QObject::tr("SCREEN_DEPTH_LOVER_THAN_16_CAPTION"); MessageBoxW(0, info.toStdWString().c_str(), caption.toStdWString().c_str(), MB_OK | MB_ICONINFORMATION); } } bool MainWindow::nativeEvent(const QByteArray & eventType, void * message, long * result) { if (message != nullptr && reinterpret_cast<MSG*>(message)->message == WM_KEYUP) this->_keyboardLayoutHelper.update(); return QQuickView::nativeEvent(eventType, message, result); } void MainWindow::activateWindow() { DEBUG_LOG << "activateWindow"; this->show(); // Это нам покажет окно //this->setFocusPolicy(Qt::StrongFocus); //this->setWindowState(Qt::WindowActive); this->showNormal(); // Эта функция активирует окно и поднмиает его повех всех окон P1::Application::WindowHelper::activate(reinterpret_cast<HWND>(this->winId())); this->_taskBarHelper.restore(); //this->repaint(); } bool MainWindow::isDownloading(QString serviceId) { return this->_downloader->isInProgress(serviceId); } QString MainWindow::language() { return this->_applicationProxy->language(); } const QString& MainWindow::fileVersion() const { return _fileVersion; } void MainWindow::saveLanguage(const QString& language) { this->_applicationProxy->setLanguage(language); } void MainWindow::selectLanguage(const QString& language) { if (this->translators[language]) QApplication::installTranslator(this->translators[language]); emit this->languageChanged(); } void MainWindow::onWindowClose() { DEBUG_LOG << "Shutting down"; //this->repaint(); this->hide(); this->_clientConnection->close(); QCoreApplication::quit(); } void MainWindow::authSuccessSlot(const QString& accessToken, const QString& acccessTokenExpiredTime) { this->_credential.setAcccessTokent(accessToken); this->_credential.setAccessTokenExpiredTime(acccessTokenExpiredTime); qDebug() << "Auth success with userId " << this->_credential.userId(); this->_restapiManager.setCridential(this->_credential); this->_clientConnection->setCredential(this->_credential); } void MainWindow::updateAuthCredential(const QString& accessTokenOld, const QString& acccessTokenExpiredTimeOld , const QString& accessTokenNew, const QString& acccessTokenExpiredTimeNew) { if (accessTokenOld == this->_credential.acccessTokent()) { this->_credential.setAcccessTokent(accessTokenNew); this->_credential.setAccessTokenExpiredTime(acccessTokenExpiredTimeNew); this->_restapiManager.setCridential(this->_credential); this->_clientConnection->setCredential(this->_credential); } ProtocolOneCredential oldValue(accessTokenOld, acccessTokenExpiredTimeOld); ProtocolOneCredential newValue(accessTokenNew, acccessTokenExpiredTimeNew); this->_restapiManager.updateCredential(oldValue, newValue); this->_clientConnection->updateCredential(oldValue, newValue); } void MainWindow::restartApplication(bool shouldStartWithSameArguments) { this->_applicationProxy->restartApplication(shouldStartWithSameArguments); } void MainWindow::openExternalUrlWithAuth(const QString& url) { //QString authUrl; //if(this->_credential.appKey().isEmpty()) { // authUrl = url; //} else { // authUrl = "https://gnlogin.ru/?auth="; // authUrl.append(this->_credential.cookie()); // authUrl.append("&rp="); // authUrl.append(QUrl::toPercentEncoding(url)); //} //authUrl.append('\0'); // UNDONE There are no shared auth between sites now. this->openExternalUrl(url); } void MainWindow::openExternalUrl(const QString& url) { QDesktopServices::openUrl(url); } void MainWindow::logout() { this->_credential.clear(); this->_restapiManager.setCridential(this->_credential); this->_clientConnection->setCredential(this->_credential); } void MainWindow::prepairGameDownloader() { using P1::GameDownloader::GameDownloadService; QObject::connect(this->_downloader, &DownloaderBridgeProxy::totalProgress, this, &MainWindow::downloadGameTotalProgressChanged); QObject::connect(this->_downloader, &DownloaderBridgeProxy::downloadProgress, this, &MainWindow::downloadGameProgressChanged); QObject::connect(this->_downloader, &DownloaderBridgeProxy::started, this, &MainWindow::gameDownloaderStarted); QObject::connect(this->_downloader, &DownloaderBridgeProxy::finished, this, &MainWindow::gameDownloaderFinished); QObject::connect(this->_downloader, &DownloaderBridgeProxy::stopped, this, &MainWindow::gameDownloaderStopped); QObject::connect(this->_downloader, &DownloaderBridgeProxy::stopping, this, &MainWindow::gameDownloaderStopping); QObject::connect(this->_downloader, &DownloaderBridgeProxy::failed, this, &MainWindow::gameDownloaderFailed); QObject::connect(this->_downloader, &DownloaderBridgeProxy::statusMessageChanged, this, &MainWindow::gameDownloaderStatusMessageChanged); QObject::connect(this->_downloader, &DownloaderBridgeProxy::serviceInstalled, this, &MainWindow::gameDownloaderServiceInstalled); QObject::connect(this->_downloader, &DownloaderBridgeProxy::serviceUpdated, this, &MainWindow::gameDownloaderServiceUpdated); QObject::connect(this->_downloader, &DownloaderBridgeProxy::accessRequired, this, &MainWindow::gameDownloaderAccessRequired); } void MainWindow::downloadGameTotalProgressChanged(const QString& serviceId, int progress) { emit totalProgressChanged(serviceId, progress); } void MainWindow::downloadGameProgressChanged( const QString& serviceId, int progress, P1::Host::Bridge::DownloadProgressArgs args) { if (args.status == static_cast<int>(P1::Libtorrent::EventArgs::ProgressEventArgs::CheckingFiles)) { emit this->rehashProgressChanged(serviceId, progress, args.progress * 100); return; } emit this->downloadProgressChanged(serviceId, progress, args.totalWantedDone, args.totalWanted, args.directTotalDownload, args.peerTotalDownload, args.payloadTotalDownload, args.peerPayloadDownloadRate, args.payloadDownloadRate, args.directPayloadDownloadRate, args.payloadUploadRate, args.totalPayloadUpload); } void MainWindow::gameDownloaderStarted(const QString& serviceId, int startType) { emit this->downloaderStarted(serviceId, startType); } void MainWindow::gameDownloaderFinished(const QString& serviceId) { emit this->downloaderFinished(serviceId); } bool MainWindow::executeService(QString id) { if (this->_executor->isGameStarted(id)) return false; if (!this->isWindowVisible()) { emit this->selectService(id); return false; } // UNDONE we shouldn't check here //if (!this->_restapiManager.credential().isValid()) { // emit this->authBeforeStartGameRequest(id); // return false; //} if (!this->_serviceSettings->isDownloadable(id)) this->_licenseManager->acceptWebLicense(); P1::RestApi::ProtocolOneCredential baseCredential = P1::RestApi::RestApiManager::commonInstance()->credential(); this->_executor->execute( id, baseCredential.acccessTokent(), baseCredential.accessTokenExpiredTimeAsString()); this->startGame(id); return true; } void MainWindow::gameDownloaderStopped(const QString& serviceId) { emit this->downloaderStopped(serviceId); } void MainWindow::gameDownloaderStopping(const QString& serviceId) { emit this->downloaderStopping(serviceId); } void MainWindow::updateFinishedSlot() { this->postUpdateInit(); } void MainWindow::gameDownloaderFailed(const QString& serviceId) { emit this->downloaderFailed(serviceId); } void MainWindow::removeStartGame(QString serviceId) { int totalCount = this->_applicationStatistic->executeGameTotalCount(serviceId); if (totalCount > 0) { this->selectService(serviceId); return; } this->downloadButtonStart(serviceId); } void MainWindow::downloadButtonStart(QString serviceId) { qDebug() << "downloadButtonStart " << serviceId; emit this->downloadButtonStartSignal(serviceId); if (!this->_serviceSettings->isDownloadable(serviceId)) { int totalCount = this->_applicationStatistic->executeGameTotalCount(serviceId); if (0 == totalCount) { emit this->showWebLicense(serviceId); return; } this->startGame(serviceId); return; } if (this->isLicenseAccepted(serviceId)) { this->startGame(serviceId); return; } DEBUG_LOG; this->activateWindow(); emit this->showLicense(serviceId); } void MainWindow::downloadButtonPause(QString serviceId) { if (this->_serviceSettings->isDownloadable(serviceId)) { this->_downloader->stop(serviceId); return; } P1::RestApi::ProtocolOneCredential baseCredential = P1::RestApi::RestApiManager::commonInstance()->credential(); this->_executor->execute(serviceId , baseCredential.acccessTokent() , baseCredential.accessTokenExpiredTimeAsString()); } void MainWindow::uninstallService(const QString serviceId) { this->_downloader->start(serviceId, P1::GameDownloader::Uninstall); } void MainWindow::cancelServiceUninstall(const QString serviceId) { this->_applicationProxy->cancelUninstallServiceRequest(serviceId); } bool MainWindow::isLicenseAccepted(const QString& serviceId) { return this->_licenseManager->hasAcceptedLicense(serviceId); } void MainWindow::startGame(const QString& serviceId) { if (this->_executor->isGameStarted(serviceId)) return; if (this->_serviceSettings->isDownloadable(serviceId)) { this->_downloader->start(serviceId, static_cast<int>(P1::GameDownloader::Normal)); return; } // UNDONE we shouldn't check here //bool isAuthed = !this->_restapiManager.credential().isValid(); //if (!isAuthed) { // emit this->authBeforeStartGameRequest(serviceId); // return; //} P1::RestApi::ProtocolOneCredential baseCredential = P1::RestApi::RestApiManager::commonInstance()->credential(); this->_executor->execute( serviceId, baseCredential.acccessTokent(), baseCredential.accessTokenExpiredTimeAsString()); } void MainWindow::commandRecieved(QString name, QStringList arguments) { DEBUG_LOG << name << arguments; if (name == "quit") { this->onWindowClose(); return; } if (name == "settings") { emit this->navigate("ApplicationSettings"); return; } if (name == "activate") { DEBUG_LOG; this->activateWindow(); return; } if (name == "goprotocolonemoney") { this->navigate("goprotocolonemoney"); return; } if (name == "uninstall" && arguments.size() > 0) { QString serviceId = arguments.at(0); emit this->uninstallServiceRequest(serviceId); } } void MainWindow::onServiceStarted(const QString &serviceId) { emit this->serviceStarted(serviceId); } void MainWindow::onServiceFinished(const QString &serviceId, int state) { emit this->serviceFinished(serviceId, state); } void MainWindow::gameDownloaderStatusMessageChanged(const QString& serviceId, const QString& message) { emit this->downloaderServiceStatusMessageChanged(serviceId, message); } void MainWindow::onAuthorizationError(const P1::RestApi::ProtocolOneCredential &credential) { if (credential.userId() == this->_credential.userId() && this->_credential != credential && this->_credential.isValid()) { this->_clientConnection->updateCredential(credential, this->_credential); } emit this->authorizationError(credential.acccessTokent(), credential.accessTokenExpiredTimeAsString()); } void MainWindow::showEvent(QShowEvent* event) { this->_taskBarHelper.prepare(reinterpret_cast<HWND>(this->winId())); emit this->taskBarButtonMsgRegistered(this->_taskBarHelper.getTaskbarCreatedMessageId()); QQuickView::showEvent(event); } bool MainWindow::isWindowVisible() { return this->isVisible() && this->windowState() != Qt::WindowMinimized; } void MainWindow::gameDownloaderServiceInstalled(const QString& serviceId) { emit this->serviceInstalled(serviceId); } void MainWindow::gameDownloaderServiceUpdated(const QString& serviceId) { DEBUG_LOG; this->activateWindow(); emit this->selectService(serviceId); } void MainWindow::postUpdateInit() { this->prepairGameDownloader(); QObject::connect(this->_executor, &ExecutorBridgeProxy::serviceStarted, this, &MainWindow::onServiceStarted); QObject::connect(this->_executor, &ExecutorBridgeProxy::serviceFinished, this, &MainWindow::onServiceFinished); } bool MainWindow::anyLicenseAccepted() { return this->_licenseManager->hasAcceptedLicense(); } QString MainWindow::startingService() { if (!this->_commandLineArguments.contains("startservice")) return "0"; QStringList arguments = this->_commandLineArguments.commandArguments("startservice"); if (arguments.count() > 0) return arguments.at(0); return "0"; } QString MainWindow::getExpectedInstallPath(const QString& serviceId) { return this->_bestInstallPath->expectedPath(serviceId); } QString MainWindow::getBestInstallPath(const QString& serviceId) { return this->_bestInstallPath->bestInstallPath(serviceId); } void MainWindow::setServiceInstallPath(const QString& serviceId, const QString& path) { this->_serviceSettings->setInstallPath(serviceId, path); if (!this->_serviceSettings->hasDownloadPath(serviceId)) { this->_serviceSettings->setDownloadPath(serviceId, path); return; } QString downloadPath = this->_serviceSettings->isDefaultDownloadPath(serviceId) ? QString("%1/dist").arg(path) : this->_serviceSettings->downloadPath(serviceId); this->_serviceSettings->setDownloadPath(serviceId, downloadPath); } void MainWindow::acceptFirstLicense(const QString& serviceId) { this->_licenseManager->acceptLicense(serviceId, "1"); } void MainWindow::initFinished() { emit this->updateFinished(); } void MainWindow::initRestApi() { QString apiUrl = this->_configManager.value<QString>("api\\url", "https://api.tst.protocol.one/"); qDebug() << "Using RestApi url " << apiUrl; this->_restapiManager.setUri(apiUrl); this->_restapiManager.setCache(new Features::PlainFileCache(&this->_restapiManager)); bool debugLogEnabled = this->_configManager.value<bool>("api\\debug", false); this->_restapiManager.setDebugLogEnabled(debugLogEnabled); P1::RestApi::RestApiManager::setCommonInstance(&this->_restapiManager); } bool MainWindow::event(QEvent* event) { switch(event->type()) { case QEvent::Close: this->hide(); event->ignore(); break; } return QQuickView::event(event); } //void MainWindow::initMarketing() //{ // QSettings midSettings( // QSettings::NativeFormat, // QSettings::UserScope, // QCoreApplication::organizationName(), // QCoreApplication::applicationName()); // // QString mid = midSettings.value("MID", "").toString(); // this->_marketingTargetFeatures.init("Launcher", mid); // // int installerKey = midSettings.value("InstKey").toInt(); // this->_marketingTargetFeatures.setInstallerKey(installerKey); // this->_marketingTargetFeatures.setRequestInterval(1000); //} void MainWindow::mousePressEvent(QMouseEvent* event) { if (event->button() & Qt::LeftButton) emit this->leftMousePress(event->x(), event->y()); QQuickView::mousePressEvent(event); } void MainWindow::mouseReleaseEvent(QMouseEvent* event) { if (event->button() & Qt::LeftButton) emit this->leftMouseRelease(event->x(), event->y()); QQuickView::mouseReleaseEvent(event); } void MainWindow::onTaskbarButtonCreated() { this->_taskBarHelper.init(); } void MainWindow::onProgressUpdated(int progressValue, const QString &status) { TaskBarHelper::Status newStatus = TaskBarHelper::StatusUnknown; if (status == "Normal") { newStatus = TaskBarHelper::StatusNormal; } else if (status == "Paused") { newStatus = TaskBarHelper::StatusPaused; } else if (status == "Error") { newStatus = TaskBarHelper::StatusError; } this->_taskBarHelper.setProgress(progressValue); this->_taskBarHelper.setStatus(newStatus); } void MainWindow::setTaskbarIcon(const QString &iconSource) { this->_taskBarHelper.setIcon(iconSource); } void MainWindow::onLanguageChanged() { this->_keyboardLayoutHelper.update(); } void MainWindow::switchClientVersion() { this->_applicationProxy->switchClientVersion(); }
29.927374
137
0.746985
ProtocolONE
a721bf4888f6362919db9cb5450793d3b4785417
3,624
cpp
C++
groups/bal/ball/doc/keyfeatures_example2.cpp
eddiepierce/bde
45953ece9dd1cd8732f01a1cd24bbe838791d298
[ "Apache-2.0" ]
1
2021-11-10T16:53:42.000Z
2021-11-10T16:53:42.000Z
groups/bal/ball/doc/keyfeatures_example2.cpp
eddiepierce/bde
45953ece9dd1cd8732f01a1cd24bbe838791d298
[ "Apache-2.0" ]
2
2020-11-05T15:20:55.000Z
2021-01-05T19:38:43.000Z
groups/bal/ball/doc/keyfeatures_example2.cpp
eddiepierce/bde
45953ece9dd1cd8732f01a1cd24bbe838791d298
[ "Apache-2.0" ]
2
2020-01-16T17:58:12.000Z
2020-08-11T20:59:30.000Z
// keyfeatures_example2.cpp -*-C++-*- #include <ball_log.h> #include <ball_loggermanager.h> #include <ball_loggermanagerconfiguration.h> #include <ball_fileobserver.h> #include <ball_scopedattribute.h> #include <bslma_allocator.h> #include <bslma_default.h> #include <bsl_iostream.h> #include <bsl_memory.h> using namespace BloombergLP; ///Key Example 2: Initialization ///- - - - - - - - - - - - - - - // Clients that perform logging must first instantiate the singleton logger // manager using the 'ball::LoggerManagerScopedGuard' class. This example // shows how to create a logger manager with basic "default behavior". // Subsequent examples will show more customized behavior. // // The following snippets of code illustrate the initialization sequence // (typically performed near the top of 'main'). // // First, we create a 'ball::LoggerManagerConfiguration' object, // 'configuration', and set the logging "pass-through" level -- the level at // which log records are published to registered observers -- to 'WARN' (see // {'Categories, Severities, and Threshold Levels'}): //.. // myApp.cpp // int main() { ball::LoggerManagerConfiguration configuration; configuration.setDefaultThresholdLevelsIfValid(ball::Severity::e_WARN); //.. // Next, create a 'ball::LoggerManagerScopedGuard' object whose constructor // takes the configuration object just created. The guard will initialize the // logger manager singleton on creation and destroy the singleton upon // destruction. This guarantees that any resources used by the logger manager // will be properly released when they are not needed: //.. ball::LoggerManagerScopedGuard guard(configuration); //.. // Note that the application is now prepared to log messages using the 'ball' // logging subsystem, but until the application registers an observer, all log // messages will be discarded. // // Finally, we create a 'ball::FileObserver' object 'observer' that will // publish records to a file, and exceptional records to 'stdout'. We // configure the log format to publish log attributes (see // {Key Example 1: Write to a Log}, enable the logger to write to a log file, // and then register 'observer' with the logger manager. Note that observers // must be registered by name; this example simply uses "default" for a name: //.. bslma::Allocator *alloc = bslma::Default::globalAllocator(0); // bsl::shared_ptr<ball::FileObserver> observer = bsl::allocate_shared<ball::FileObserver>(alloc); observer->setLogFormat( ball::RecordStringFormatter::k_BASIC_ATTRIBUTE_FORMAT, ball::RecordStringFormatter::k_BASIC_ATTRIBUTE_FORMAT); if (0 != observer->enableFileLogging("myapplication.log.%T")) { bsl::cout << "Failed to enable logging" << bsl::endl; return -1; } ball::LoggerManager::singleton().registerObserver(observer, "default"); //.. // The application is now prepared to log messages using the 'ball' logging // subsystem: //.. // ... // BALL_LOG_SET_CATEGORY("MYLIBRARY.MYSUBSYSTEM"); BALL_LOG_ERROR << "Exiting the application (0)"; return 0; } //.. // Note that concrete observers that can be configured after their creation // (e.g., as to whether log records are published in UTC or local time) // generally can have their configuration adjusted at any time, either before // or after being registered with a logger manager. For an example of such an // observer, see 'ball_asyncfileobserver'.
41.181818
79
0.700607
eddiepierce
a7224bf0b37c6f87d5513c1751520f59e4f05702
14,355
hpp
C++
SDK/ARKSurvivalEvolved_DinoBlueprintBase_VariableMovement_parameters.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_DinoBlueprintBase_VariableMovement_parameters.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_DinoBlueprintBase_VariableMovement_parameters.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_DinoBlueprintBase_VariableMovement_classes.hpp" namespace sdk { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.BlueprintPlayAnimationEvent struct UDinoBlueprintBase_VariableMovement_C_BlueprintPlayAnimationEvent_Params { class UAnimMontage** AnimationMontage; // (Parm, ZeroConstructor, IsPlainOldData) float* PlayRate; // (Parm, ZeroConstructor, IsPlainOldData) float playedAnimLength; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5076 struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5076_Params { }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3750 struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3750_Params { }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5075 struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5075_Params { }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_ModifyBone_774 struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_ModifyBone_774_Params { }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3749 struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3749_Params { }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3748 struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3748_Params { }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3747 struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3747_Params { }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3746 struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3746_Params { }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5074 struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5074_Params { }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5073 struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5073_Params { }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3745 struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3745_Params { }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3744 struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3744_Params { }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5070 struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5070_Params { }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_RotationOffsetBlendSpace_240 struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_RotationOffsetBlendSpace_240_Params { }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5069 struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5069_Params { }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3743 struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3743_Params { }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3742 struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3742_Params { }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5068 struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5068_Params { }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5067 struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5067_Params { }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3741 struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3741_Params { }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3740 struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3740_Params { }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3739 struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3739_Params { }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_ModifyBone_773 struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_ModifyBone_773_Params { }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3738 struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3738_Params { }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3737 struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3737_Params { }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3736 struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3736_Params { }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_GroundBones_228 struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_GroundBones_228_Params { }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_GroundBones_227 struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_GroundBones_227_Params { }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_ApplyAdditive_408 struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_ApplyAdditive_408_Params { }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3735 struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3735_Params { }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_RotationOffsetBlendSpace_239 struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_RotationOffsetBlendSpace_239_Params { }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3734 struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_BlendListByBool_3734_Params { }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_ApplyAdditive_407 struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_ApplyAdditive_407_Params { }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5062 struct UDinoBlueprintBase_VariableMovement_C_EvaluateGraphExposedInputs_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_AnimGraphNode_SequencePlayer_5062_Params { }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.BlueprintUpdateAnimation struct UDinoBlueprintBase_VariableMovement_C_BlueprintUpdateAnimation_Params { float* DeltaTimeX; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function DinoBlueprintBase_VariableMovement.DinoBlueprintBase_VariableMovement_C.ExecuteUbergraph_DinoBlueprintBase_VariableMovement struct UDinoBlueprintBase_VariableMovement_C_ExecuteUbergraph_DinoBlueprintBase_VariableMovement_Params { int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
67.712264
205
0.911181
2bite
a729fc2aba67070dc2232a6ecd145f572758e1c6
397
cpp
C++
gripper/schmalz-ecbpi/main/SimGripper.cpp
opcua-skills/plug-and-produce
5567cd6177f973e97579fbd9d06ebbf23569ccfb
[ "Unlicense" ]
5
2020-04-15T03:24:48.000Z
2021-11-03T17:39:59.000Z
gripper/schmalz-ecbpi/main/SimGripper.cpp
opcua-skills/plug-and-produce
5567cd6177f973e97579fbd9d06ebbf23569ccfb
[ "Unlicense" ]
null
null
null
gripper/schmalz-ecbpi/main/SimGripper.cpp
opcua-skills/plug-and-produce
5567cd6177f973e97579fbd9d06ebbf23569ccfb
[ "Unlicense" ]
2
2020-07-04T16:01:25.000Z
2021-07-05T09:33:55.000Z
/* * This file is subject to the terms and conditions defined in * file 'LICENSE', which is part of this source code package. * * Copyright (c) 2020 fortiss GmbH, Stefan Profanter * All rights reserved. */ #include "SimGripper.h" bool SimGripper::startVaccum() { return true; } bool SimGripper::stopVaccum() { return true; } bool SimGripper::dropOff() { return true; }
18.045455
62
0.677582
opcua-skills
a731b845abc25134e8b1d4bd03e8d441bf82682f
341
cpp
C++
Problem/Presents.cpp
Shahin-Sheikh/Competitive-Programming
f66d9e1bb9013cc36bdb41faef699494fd73b952
[ "MIT" ]
1
2021-05-03T07:00:50.000Z
2021-05-03T07:00:50.000Z
Problem/Presents.cpp
Shahin-Sheikh/Codeforces
578e1eed1c8a77e55f217ab6036fee1206af1d3a
[ "MIT" ]
null
null
null
Problem/Presents.cpp
Shahin-Sheikh/Codeforces
578e1eed1c8a77e55f217ab6036fee1206af1d3a
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main(){ int n,x,res=0; cin>>n; for(int i=0;i<n;i++){ cin>>x; } if(n==1){ res = 1; cout<<res<<"\n"; } else if(n==1){ res = 2; cout<<res<<"\n"; } else{ res = n/2; cout<<res<<"\n"; } return 0; }
14.826087
25
0.375367
Shahin-Sheikh
a7378f6273e6b76e61b451a678410b037c0ddaac
209
cpp
C++
reverse-bits/reverse-bits.cpp
itzpankajpanwar/Leetcode
bf933bc8a16f4b9d7a0e8b82f01684e60b544bed
[ "MIT" ]
2
2021-08-29T12:51:09.000Z
2021-10-18T23:24:41.000Z
reverse-bits/reverse-bits.cpp
itzpankajpanwar/Leetcode
bf933bc8a16f4b9d7a0e8b82f01684e60b544bed
[ "MIT" ]
null
null
null
reverse-bits/reverse-bits.cpp
itzpankajpanwar/Leetcode
bf933bc8a16f4b9d7a0e8b82f01684e60b544bed
[ "MIT" ]
null
null
null
class Solution { public: uint32_t reverseBits(uint32_t n) { uint32_t result= 0; for(int i=0; i<32; i++) result = (result<<1) + (n>>i &1); return result; } };
20.9
45
0.488038
itzpankajpanwar
a7387164ac60c79366c2eee434735c5d2c870a4e
8,873
cc
C++
mgmt/FileManager.cc
hnakamur/trafficserver-deb
60efe9253292f7a4fb8c37430a12ce9056190711
[ "Apache-2.0" ]
2
2020-12-05T03:28:25.000Z
2021-07-10T06:03:57.000Z
mgmt/FileManager.cc
wikimedia/operations-debs-trafficserver
96248f009fc67b253119665458486e6db23b6a81
[ "Apache-2.0" ]
null
null
null
mgmt/FileManager.cc
wikimedia/operations-debs-trafficserver
96248f009fc67b253119665458486e6db23b6a81
[ "Apache-2.0" ]
null
null
null
/** @file Code for class to manage configuration updates @section license License 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 "tscore/ink_platform.h" #include "tscore/ink_file.h" #include "tscore/I_Layout.h" #include "FileManager.h" #include "Main.h" #include "Rollback.h" #include "WebMgmtUtils.h" #include "MgmtUtils.h" #include "ExpandingArray.h" #include "MgmtSocket.h" #include <vector> #include <algorithm> #define DIR_MODE S_IRWXU #define FILE_MODE S_IRWXU FileManager::FileManager() { bindings = ink_hash_table_create(InkHashTableKeyType_String); ink_assert(bindings != nullptr); ink_mutex_init(&accessLock); ink_mutex_init(&cbListLock); } // FileManager::~FileManager // // There is only FileManager object in the process and it // should never need to be destructed except at // program exit // FileManager::~FileManager() { callbackListable *cb; Rollback *rb; InkHashTableEntry *entry; InkHashTableIteratorState iterator_state; // Let other operations finish and do not start any new ones ink_mutex_acquire(&accessLock); for (cb = cblist.pop(); cb != nullptr; cb = cblist.pop()) { delete cb; } for (entry = ink_hash_table_iterator_first(bindings, &iterator_state); entry != nullptr; entry = ink_hash_table_iterator_next(bindings, &iterator_state)) { rb = (Rollback *)ink_hash_table_entry_value(bindings, entry); delete rb; } ink_hash_table_destroy(bindings); ink_mutex_release(&accessLock); ink_mutex_destroy(&accessLock); ink_mutex_destroy(&cbListLock); } // void FileManager::registerCallback(FileCallbackFunc func) // // Adds a new callback function // callbacks are made whenever a configuration file has // changed // // The callback function is responsible for free'ing // the string the string it is passed // void FileManager::registerCallback(FileCallbackFunc func) { callbackListable *newcb = new callbackListable(); ink_assert(newcb != nullptr); newcb->func = func; ink_mutex_acquire(&cbListLock); cblist.push(newcb); ink_mutex_release(&cbListLock); } // void FileManager::addFile(char* fileName, const configFileInfo* file_info, // Rollback* parentRollback) // // for the baseFile, creates a Rollback object for it // // if file_info is not null, a WebFileEdit object is also created for // the file // // Pointers to the new objects are stored in the bindings hashtable // void FileManager::addFile(const char *fileName, bool root_access_needed, Rollback *parentRollback, unsigned flags) { ink_mutex_acquire(&accessLock); addFileHelper(fileName, root_access_needed, parentRollback, flags); ink_mutex_release(&accessLock); } // caller must hold the lock void FileManager::addFileHelper(const char *fileName, bool root_access_needed, Rollback *parentRollback, unsigned flags) { ink_assert(fileName != nullptr); Rollback *rb = new Rollback(fileName, root_access_needed, parentRollback, flags); rb->configFiles = this; ink_hash_table_insert(bindings, fileName, rb); } // bool FileManager::getRollbackObj(char* fileName, Rollback** rbPtr) // // Sets rbPtr to the rollback object associated // with the passed in fileName. // // If there is no binding, falseis returned // bool FileManager::getRollbackObj(const char *fileName, Rollback **rbPtr) { InkHashTableValue lookup = nullptr; int found; ink_mutex_acquire(&accessLock); found = ink_hash_table_lookup(bindings, fileName, &lookup); ink_mutex_release(&accessLock); *rbPtr = (Rollback *)lookup; return (found == 0) ? false : true; } // bool FileManager::fileChanged(const char* fileName) // // Called by the Rollback class whenever a a config has changed // Initiates callbacks // // void FileManager::fileChanged(const char *fileName, bool incVersion) { callbackListable *cb; char *filenameCopy; Debug("lm", "filename changed %s", fileName); ink_mutex_acquire(&cbListLock); for (cb = cblist.head; cb != nullptr; cb = cb->link.next) { // Dup the string for each callback to be // defensive incase it modified when it is not supposed to be filenameCopy = ats_strdup(fileName); (*cb->func)(filenameCopy, incVersion); ats_free(filenameCopy); } ink_mutex_release(&cbListLock); } // void FileManger::rereadConfig() // // Interates through the list of managed files and // calls Rollback::checkForUserUpdate on them // // although it is tempting, DO NOT CALL FROM SIGNAL HANDLERS // This function is not Async-Signal Safe. It // is thread safe void FileManager::rereadConfig() { Rollback *rb; InkHashTableEntry *entry; InkHashTableIteratorState iterator_state; std::vector<Rollback *> changedFiles; std::vector<Rollback *> parentFileNeedChange; size_t n; ink_mutex_acquire(&accessLock); for (entry = ink_hash_table_iterator_first(bindings, &iterator_state); entry != nullptr; entry = ink_hash_table_iterator_next(bindings, &iterator_state)) { rb = (Rollback *)ink_hash_table_entry_value(bindings, entry); if (rb->checkForUserUpdate(rb->isVersioned() ? ROLLBACK_CHECK_AND_UPDATE : ROLLBACK_CHECK_ONLY)) { changedFiles.push_back(rb); if (rb->isChildRollback()) { if (std::find(parentFileNeedChange.begin(), parentFileNeedChange.end(), rb->getParentRollback()) == parentFileNeedChange.end()) { parentFileNeedChange.push_back(rb->getParentRollback()); } } } } std::vector<Rollback *> childFileNeedDelete; n = changedFiles.size(); for (size_t i = 0; i < n; i++) { if (changedFiles[i]->isChildRollback()) { continue; } // for each parent file, if it is changed, then delete all its children for (entry = ink_hash_table_iterator_first(bindings, &iterator_state); entry != nullptr; entry = ink_hash_table_iterator_next(bindings, &iterator_state)) { rb = (Rollback *)ink_hash_table_entry_value(bindings, entry); if (rb->getParentRollback() == changedFiles[i]) { if (std::find(childFileNeedDelete.begin(), childFileNeedDelete.end(), rb) == childFileNeedDelete.end()) { childFileNeedDelete.push_back(rb); } } } } n = childFileNeedDelete.size(); for (size_t i = 0; i < n; i++) { ink_hash_table_delete(bindings, childFileNeedDelete[i]->getFileName()); delete childFileNeedDelete[i]; } ink_mutex_release(&accessLock); n = parentFileNeedChange.size(); for (size_t i = 0; i < n; i++) { if (std::find(changedFiles.begin(), changedFiles.end(), parentFileNeedChange[i]) == changedFiles.end()) { fileChanged(parentFileNeedChange[i]->getFileName(), true); } } // INKqa11910 // need to first check that enable_customizations is enabled bool found; int enabled = (int)REC_readInteger("proxy.config.body_factory.enable_customizations", &found); if (found && enabled) { fileChanged("proxy.config.body_factory.template_sets_dir", true); } fileChanged("proxy.config.ssl.server.ticket_key.filename", true); } bool FileManager::isConfigStale() { Rollback *rb; InkHashTableEntry *entry; InkHashTableIteratorState iterator_state; bool stale = false; ink_mutex_acquire(&accessLock); for (entry = ink_hash_table_iterator_first(bindings, &iterator_state); entry != nullptr; entry = ink_hash_table_iterator_next(bindings, &iterator_state)) { rb = (Rollback *)ink_hash_table_entry_value(bindings, entry); if (rb->checkForUserUpdate(ROLLBACK_CHECK_ONLY)) { stale = true; break; } } ink_mutex_release(&accessLock); return stale; } // void configFileChild(const char *parent, const char *child) // // Add child to the bindings with parentRollback void FileManager::configFileChild(const char *parent, const char *child, unsigned flags) { InkHashTableValue lookup; Rollback *parentRollback = nullptr; ink_mutex_acquire(&accessLock); int htfound = ink_hash_table_lookup(bindings, parent, &lookup); if (htfound) { parentRollback = (Rollback *)lookup; addFileHelper(child, parentRollback->rootAccessNeeded(), parentRollback, flags); } ink_mutex_release(&accessLock); }
30.596552
115
0.724107
hnakamur
a739ba0ccf2cd05f459e7d3790a53a71a66f6ee6
438
cpp
C++
CodeBlocks/Codeforces/Solved/Codeforces266B.cpp
ash1247/DocumentsWindows
66f65b5170a1ba766cfae08b7104b63ab87331c2
[ "MIT" ]
null
null
null
CodeBlocks/Codeforces/Solved/Codeforces266B.cpp
ash1247/DocumentsWindows
66f65b5170a1ba766cfae08b7104b63ab87331c2
[ "MIT" ]
null
null
null
CodeBlocks/Codeforces/Solved/Codeforces266B.cpp
ash1247/DocumentsWindows
66f65b5170a1ba766cfae08b7104b63ab87331c2
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main( void ) { int n = 0, t = 0; cin >> n >> t; char pos[n]; cin >> pos; while( t-- ) { for(int i = 1; i < n; i++) { if( pos[i] == 'G' && pos[i - 1] == 'B') { pos[i] = 'B'; pos[i - 1] = 'G'; i++; } } } cout << pos << endl; return 0; }
13.272727
51
0.296804
ash1247
a73a580e93f2029733d71888c7713e41a4ef71e6
332
hpp
C++
core/interface/i_node.hpp
auyunli/enhance
ca99530c80b42842e713ed4b62e40d12e56ee24a
[ "BSD-2-Clause" ]
null
null
null
core/interface/i_node.hpp
auyunli/enhance
ca99530c80b42842e713ed4b62e40d12e56ee24a
[ "BSD-2-Clause" ]
null
null
null
core/interface/i_node.hpp
auyunli/enhance
ca99530c80b42842e713ed4b62e40d12e56ee24a
[ "BSD-2-Clause" ]
null
null
null
#ifndef E2_I_NODE_INOUT_HPP #define E2_I_NODE_INOUT_HPP #include <thread> #include <functional> #include <type_traits> #include <list> namespace e2 { namespace interface { template< class Impl > class i_node_inout : public Impl { public: std::list< i_node_inout * > _in; std::list< i_node_inout * > _out; }; } } #endif
15.809524
37
0.716867
auyunli
a73b3100617bf9d71525ee7c9cf6e598ae4887a7
29,880
hpp
C++
src/nonlinear_solvers.hpp
Pressio/pressio4py
36676dbd112a7c7960ccbf302ff14d4376c819ec
[ "Unlicense", "BSD-3-Clause" ]
4
2020-07-06T20:01:39.000Z
2022-03-05T09:23:40.000Z
src/nonlinear_solvers.hpp
Pressio/pressio4py
36676dbd112a7c7960ccbf302ff14d4376c819ec
[ "Unlicense", "BSD-3-Clause" ]
19
2020-02-27T20:52:53.000Z
2022-01-13T16:24:49.000Z
src/nonlinear_solvers.hpp
Pressio/pressio4py
36676dbd112a7c7960ccbf302ff14d4376c819ec
[ "Unlicense", "BSD-3-Clause" ]
1
2022-03-03T16:05:09.000Z
2022-03-03T16:05:09.000Z
/* //@HEADER // ************************************************************************ // // nonlinear_solvers.hpp // Pressio // Copyright 2019 // National Technology & Engineering Solutions of Sandia, LLC (NTESS) // // Under the terms of Contract DE-NA0003525 with NTESS, the // U.S. Government retains certain rights in this software. // // Pressio is licensed under BSD-3-Clause terms of use: // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING // IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Questions? Contact Francesco Rizzi (fnrizzi@sandia.gov) // // ************************************************************************ //@HEADER */ #ifndef PRESSIO4PY_PYBINDINGS_NONLINEAR_SOLVERS_HPP_ #define PRESSIO4PY_PYBINDINGS_NONLINEAR_SOLVERS_HPP_ namespace pressio4py{ namespace solvers{ void bindUpdatingEnums(pybind11::module & m) { pybind11::enum_<pressio::nonlinearsolvers::Update>(m, "update") .value("Standard", pressio::nonlinearsolvers::Update::Standard) .value("Armijo", pressio::nonlinearsolvers::Update::Armijo) .value("LMSchedule1", pressio::nonlinearsolvers::Update::LMSchedule1) .value("LMSchedule2", pressio::nonlinearsolvers::Update::LMSchedule2) .export_values(); } void bindStoppingEnums(pybind11::module & m) { pybind11::enum_<pressio::nonlinearsolvers::Stop>(m, "stop") .value("WhenCorrectionAbsoluteNormBelowTolerance", pressio::nonlinearsolvers::Stop::WhenCorrectionAbsoluteNormBelowTolerance) .value("WhenCorrectionRelativeNormBelowTolerance", pressio::nonlinearsolvers::Stop::WhenCorrectionRelativeNormBelowTolerance) .value("WhenResidualAbsoluteNormBelowTolerance", pressio::nonlinearsolvers::Stop::WhenResidualAbsoluteNormBelowTolerance) .value("WhenResidualRelativeNormBelowTolerance", pressio::nonlinearsolvers::Stop::WhenResidualRelativeNormBelowTolerance) .value("WhenGradientAbsoluteNormBelowTolerance", pressio::nonlinearsolvers::Stop::WhenGradientAbsoluteNormBelowTolerance) .value("WhenGradientRelativeNormBelowTolerance", pressio::nonlinearsolvers::Stop::WhenGradientRelativeNormBelowTolerance) .value("AfterMaxIters", pressio::nonlinearsolvers::Stop::AfterMaxIters) .export_values(); } template <typename nonlinear_solver_t> void bindCommonSolverMethods(pybind11::class_<nonlinear_solver_t> & solverObj) { // methods to set and query num of iterations solverObj.def("maxIterations", &nonlinear_solver_t::maxIterations); solverObj.def("setMaxIterations", &nonlinear_solver_t::setMaxIterations); // updating criterion solverObj.def("setUpdatingCriterion", &nonlinear_solver_t::setUpdatingCriterion); solverObj.def("updatingCriterion", &nonlinear_solver_t::updatingCriterion); } template <typename nonlinear_solver_t> void bindTolerancesMethods(pybind11::class_<nonlinear_solver_t> & solverObj) { // tolerances solverObj.def("setTolerance", &nonlinear_solver_t::setTolerance); solverObj.def("setCorrectionAbsoluteTolerance", &nonlinear_solver_t::setCorrectionAbsoluteTolerance); solverObj.def("setCorrectionRelativeTolerance", &nonlinear_solver_t::setCorrectionRelativeTolerance); solverObj.def("setResidualAbsoluteTolerance", &nonlinear_solver_t::setResidualAbsoluteTolerance); solverObj.def("setResidualRelativeTolerance", &nonlinear_solver_t::setResidualRelativeTolerance); solverObj.def("setGradientAbsoluteTolerance", &nonlinear_solver_t::setGradientAbsoluteTolerance); solverObj.def("setGradientRelativeTolerance", &nonlinear_solver_t::setGradientRelativeTolerance); solverObj.def("correctionAbsoluteTolerance", &nonlinear_solver_t::correctionAbsoluteTolerance); solverObj.def("correctionRelativeTolerance", &nonlinear_solver_t::correctionRelativeTolerance); solverObj.def("residualAbsoluteTolerance", &nonlinear_solver_t::residualAbsoluteTolerance); solverObj.def("residualRelativeTolerance", &nonlinear_solver_t::residualRelativeTolerance); solverObj.def("gradientAbsoluteTolerance", &nonlinear_solver_t::gradientAbsoluteTolerance); solverObj.def("gradientRelativeTolerance", &nonlinear_solver_t::gradientRelativeTolerance); } template <typename nonlinear_solver_t> void bindStoppingCriteria(pybind11::class_<nonlinear_solver_t> & solverObj) { // stopping criterion solverObj.def("setStoppingCriterion", &nonlinear_solver_t::setStoppingCriterion); solverObj.def("stoppingCriterion", &nonlinear_solver_t::stoppingCriterion); }; //------------------------------------------------ // template <typename T, typename = void> // struct has_system_typedef : std::false_type{}; // template <typename T> // struct has_system_typedef< // T, pressio::mpl::enable_if_t< !std::is_void<typename T::system_t >::value > // > : std::true_type{}; // template <typename T, typename = void> // struct has_stepper_typedef : std::false_type{}; // template <typename T> // struct has_stepper_typedef< // T, pressio::mpl::enable_if_t< !std::is_void<typename T::stepper_t >::value > // > : std::true_type{}; // //----------------------------------------------- // template<typename, typename = void> // struct _have_rj_api; // template<class T> // struct _have_rj_api< // T, pressio::mpl::enable_if_t< has_system_typedef<T>::value > // > // { // static constexpr auto value = // pressio::solvers::constraints::system_residual_jacobian<typename T::system_t>::value; // }; // template<class T> // struct _have_rj_api< // T, pressio::mpl::enable_if_t< has_stepper_typedef<T>::value > // > // { // static constexpr auto value = // pressio::solvers::constraints::system_residual_jacobian<typename T::stepper_t>::value; // }; // //------------------------------------------------ // template<class...> // struct _have_rj_api_var; // template<class head> // struct _have_rj_api_var<head> // { // static constexpr auto value = _have_rj_api<head>::value; // }; // template<class head, class... tail> // struct _have_rj_api_var<head, tail...> // { // static constexpr auto value = _have_rj_api<head>::value // and _have_rj_api_var<tail...>::value; // }; // //------------------------------------------------ // template<class ...> struct bindCreateSolverVariadic; // template<class SystemType> // struct bindCreateSolverVariadic<SystemType> // { // template<class nonlinear_solver_t, class lin_s_t, typename tag> // static void bind(pybind11::module & m, const std::string & createFuncName) // { // m.def(createFuncName.c_str(), // &createSolver<nonlinear_solver_t, lin_s_t, SystemType, tag>, // pybind11::return_value_policy::take_ownership); // } // }; // template<class head, class ... tail> // struct bindCreateSolverVariadic<head, tail...> // { // template<class nonlinear_solver_t, class lin_s_t, class tag> // static void bind(pybind11::module & m, const std::string & name) // { // bindCreateSolverVariadic<head>::template bind<nonlinear_solver_t, lin_s_t, tag>(m, name); // bindCreateSolverVariadic<tail...>::template bind<nonlinear_solver_t, lin_s_t, tag>(m, name); // } // }; // template<class nonlinear_solver_t, class rom_problem_t, class tagT> // pressio::mpl::enable_if_t<std::is_same<tagT, Unweighted>::value, nonlinear_solver_t> // createSolver(rom_problem_t & romProb, // const typename rom_problem_t::lspg_native_state_t & romState, // pybind11::object pyobj) //linear or QR solver is a native python class // { // return nonlinear_solver_t(romProb, romState, pyobj); // } // template<class nonlinear_solver_t, class rom_problem_t, class tagT> // pressio::mpl::enable_if_t<std::is_same<tagT, Weighted>::value, nonlinear_solver_t> // createSolver(rom_problem_t & romProb, // const typename rom_problem_t::lspg_native_state_t & romState, // pybind11::object pyobj, // linear solver for norm eq is a native python class // pybind11::object wO) // weighting operator is a native python class // { // return nonlinear_solver_t(romProb, romState, pyobj, wO); // } // template<class nonlinear_solver_t, class rom_problem_t, class tagT> // pressio::mpl::enable_if_t<std::is_same<tagT, Irwls>::value, nonlinear_solver_t> // createSolver(rom_problem_t & romProb, // const typename rom_problem_t::lspg_native_state_t & romState, // pybind11::object pyobj, // linear solver for norm eq is a native python class // typename rom_problem_t::traits::scalar_t pNorm) // value of p-norm // { // return nonlinear_solver_t(romProb, romState, pyobj, pNorm); // } // template<class nonlinear_solver_t, class lin_s_t, class system_t, class tagT> // pressio::mpl::enable_if_t<std::is_same<tagT, NewtonRaphson>::value, nonlinear_solver_t> // createSolver(system_t & system, // ::pressio4py::py_f_arr romState, // pybind11::object pyobj) // { // std::cout << " create " << &system << " " << pyobj << "\n"; // return nonlinear_solver_t(system, romState, lin_s_t(pyobj)); // } // helper tags struct NewtonRaphson{}; struct LSUnweighted{}; struct LSWeighted{}; // struct Irwls{}; template<class nonlinear_solver_t, class lin_s_t, class system_t, class tagT> pressio::mpl::enable_if_t<std::is_same<tagT, LSUnweighted>::value, nonlinear_solver_t> createSolver(pybind11::object pysystem, ::pressio4py::py_f_arr romState, pybind11::object pysol) { return nonlinear_solver_t(system_t(pysystem), romState, lin_s_t(pysol)); } template<class nonlinear_solver_t, class lin_s_t, class system_t, class WeighWrapper, class tagT> pressio::mpl::enable_if_t<std::is_same<tagT, LSWeighted>::value, nonlinear_solver_t> createSolver(pybind11::object pysystem, ::pressio4py::py_f_arr romState, pybind11::object pysol, // py solver pybind11::object pywo) // py weighting operator { return nonlinear_solver_t(system_t(pysystem), romState, lin_s_t(pysol), WeighWrapper(pywo)); } template<class nonlinear_solver_t, class lin_s_t, class system_t, class tagT> pressio::mpl::enable_if_t<std::is_same<tagT, NewtonRaphson>::value, nonlinear_solver_t> createSolver(pybind11::object pysystem, ::pressio4py::py_f_arr romState, pybind11::object pysol) { return nonlinear_solver_t(system_t(pysystem), romState, lin_s_t(pysol)); } //--------------------------------------------------- /* newton-raphson */ //--------------------------------------------------- template<class linear_solver_t, class ResJacSystemWrapper> struct NewtonRaphsonBinder { using nonlinear_solver_t = typename pressio::nonlinearsolvers::impl::ComposeNewtonRaphson< pressio4py::py_f_arr, ResJacSystemWrapper, linear_solver_t >::type; static void bindClassAndMethods(pybind11::module & m) { pybind11::class_<nonlinear_solver_t> solver(m, "NewtonRaphClass"); // Note we don't bind the constructor because from Python we use the create // function (see below) to instantiate a solver object, we never // use the class name directly. m.def("create_newton_raphson", &createSolver<nonlinear_solver_t, linear_solver_t, ResJacSystemWrapper, NewtonRaphson>, pybind11::return_value_policy::take_ownership); bindTolerancesMethods(solver); bindStoppingCriteria(solver); bindCommonSolverMethods(solver); solver.def("solve", &nonlinear_solver_t::template solveForPy<ResJacSystemWrapper>); } // static void bindCreate(pybind11::module & m){ // const std::string name = "create_newton_raphson"; // m.def(name.c_str(), // &createSolverForPy<nonlinear_solver_t, linear_solver_t, ResJacSystemWrapper, NewtonRaphson>, // pybind11::return_value_policy::take_ownership); // } // template<class ...Systems> // static void bindCreate(pybind11::module & m){ // const std::string name = "create_newton_raphson"; // bindCreateSolverVariadic<Systems...>::template bind< // nonlinear_solver_t, linear_solver_t, NewtonRaphson>(m, name); // } }; //------------------------------------------------ /* GN: R/J API with normal equations */ //------------------------------------------------ template<class linear_solver_t, class ResJacSystemWrapper> struct GNNormalEqResJacApiBinder{ using nonlinear_solver_t = typename pressio::nonlinearsolvers::impl::Compose< pressio4py::py_f_arr, ResJacSystemWrapper, ::pressio::nonlinearsolvers::GaussNewton, void, linear_solver_t >::type; static void bindClassAndMethods(pybind11::module & m) { pybind11::class_<nonlinear_solver_t> solver(m, "GaussNewton"); m.def("create_gauss_newton", &createSolver<nonlinear_solver_t, linear_solver_t, ResJacSystemWrapper, LSUnweighted>, pybind11::return_value_policy::take_ownership); bindTolerancesMethods(solver); bindStoppingCriteria(solver); bindCommonSolverMethods(solver); solver.def("solve", &nonlinear_solver_t::template solveForPy<ResJacSystemWrapper>); } }; //------------------------------------------------ /* WEIGHTED GN: R/J API with normal equations */ //------------------------------------------------ template<class linear_solver_t, class ResJacSystemWrapper, class WeighWrapper> struct WeighGNNormalEqResJacApiBinder{ using nonlinear_solver_t = typename pressio::nonlinearsolvers::impl::Compose< pressio4py::py_f_arr, ResJacSystemWrapper, ::pressio::nonlinearsolvers::GaussNewton, void, linear_solver_t, WeighWrapper >::type; static void bindClassAndMethods(pybind11::module & m) { pybind11::class_<nonlinear_solver_t> solver(m, "WeightedGaussNewton"); m.def("create_weighted_gauss_newton", &createSolver<nonlinear_solver_t, linear_solver_t, ResJacSystemWrapper, WeighWrapper, LSWeighted>, pybind11::return_value_policy::take_ownership); bindTolerancesMethods(solver); bindStoppingCriteria(solver); bindCommonSolverMethods(solver); solver.def("solve", &nonlinear_solver_t::template solveForPy<ResJacSystemWrapper>); } }; //------------------------------------------------ /* GN: R/J API with QR */ //------------------------------------------------ template<class qr_solver_t, class ResJacSystemWrapper> struct GNQRResJacApiBinder{ using nonlinear_solver_t = typename pressio::nonlinearsolvers::impl::ComposeGNQR< pressio4py::py_f_arr, ResJacSystemWrapper, qr_solver_t >::type; static void bindClassAndMethods(pybind11::module & m) { pybind11::class_<nonlinear_solver_t> solver(m, "GaussNewtonQR"); m.def("create_gauss_newton_qr", &createSolver<nonlinear_solver_t, qr_solver_t, ResJacSystemWrapper, LSUnweighted>, pybind11::return_value_policy::take_ownership); bindTolerancesMethods(solver); bindStoppingCriteria(solver); bindCommonSolverMethods(solver); solver.def("solve", &nonlinear_solver_t::template solveForPy<ResJacSystemWrapper>); } }; //------------------------------------------------ /* LM: R/J API with normal equations */ //------------------------------------------------ template<class linear_solver_t, class ResJacSystemWrapper> struct LMNormalEqResJacApiBinder { using nonlinear_solver_t = typename pressio::nonlinearsolvers::impl::Compose< pressio4py::py_f_arr, ResJacSystemWrapper, ::pressio::nonlinearsolvers::LM, void, linear_solver_t >::type; static void bindClassAndMethods(pybind11::module & m) { pybind11::class_<nonlinear_solver_t> solver(m, "LevenbergMarquardt"); m.def("create_levenberg_marquardt", &createSolver<nonlinear_solver_t, linear_solver_t, ResJacSystemWrapper, LSUnweighted>, pybind11::return_value_policy::take_ownership); bindTolerancesMethods(solver); bindStoppingCriteria(solver); bindCommonSolverMethods(solver); solver.def("solve", &nonlinear_solver_t::template solveForPy<ResJacSystemWrapper>); } }; //------------------------------------------------ /* WEIGHTED LM: R/J API with normal equations */ //------------------------------------------------ template<class linear_solver_t, class ResJacSystemWrapper, class WeighWrapper> struct WeighLMNormalEqResJacApiBinder { using nonlinear_solver_t = typename pressio::nonlinearsolvers::impl::Compose< pressio4py::py_f_arr, ResJacSystemWrapper, ::pressio::nonlinearsolvers::LM, void, linear_solver_t, WeighWrapper >::type; static void bindClassAndMethods(pybind11::module & m) { pybind11::class_<nonlinear_solver_t> solver(m, "WeightedLevenbergMarquardt"); m.def("create_weighted_levenberg_marquardt", &createSolver<nonlinear_solver_t, linear_solver_t, ResJacSystemWrapper, WeighWrapper, LSWeighted>, pybind11::return_value_policy::take_ownership); bindTolerancesMethods(solver); bindStoppingCriteria(solver); bindCommonSolverMethods(solver); solver.def("solve", &nonlinear_solver_t::template solveForPy<ResJacSystemWrapper>); } }; }}//end namespace #endif // template<bool do_gn, typename ...> // struct LeastSquaresNormalEqResJacApiBinder; // template<bool do_gn, typename linear_solver_wrapper_t, typename ...Problems> // struct LeastSquaresNormalEqResJacApiBinder<do_gn, linear_solver_wrapper_t, std::tuple<Problems...>> // { // static_assert(_have_rj_api_var<Problems...>::value, ""); // // it does not matter here if we use the steady system or stepper_t // // as template arg to compose the solver type in the code below as long as it // // meets the res-jac api. But since we are here, this condition is met // // because it is asserted above. so just pick the first problem type in the // // pack, which should be a steady lspg problem, and so it has a system_t typedef // // that we can use for compose solver below // using head_problem_t = typename std::tuple_element<0, std::tuple<Problems...>>::type; // using system_t = typename head_problem_t::system_t; // // gauss-newton solver type // using gn_type = pressio::nonlinearsolvers::impl::composeGaussNewton_t // <system_t, linear_solver_wrapper_t>; // // lm solver type // using lm_type = pressio::nonlinearsolvers::impl::composeLevenbergMarquardt_t // <system_t, linear_solver_wrapper_t>; // // pick gn or lm conditioned on the bool argument // using nonlinear_solver_t = typename std::conditional<do_gn, gn_type, lm_type>::type; // static void bindClass(pybind11::module & m, const std::string & solverPythonName) // { // pybind11::class_<nonlinear_solver_t> nonLinSolver(m, solverPythonName.c_str()); // bindTolerancesMethods(nonLinSolver); // bindStoppingCriteria(nonLinSolver); // bindCommonSolverMethods(nonLinSolver); // // Note we don't bind the constructor because from Python we use the create // // function (see below) to instantiate a solver object, we never // // use the class name directly. This is useful because it allows us // // to overcome the problem of needing unique class names in python // } // static void bindCreate(pybind11::module & m) // { // const std::string name = do_gn ? "createGaussNewton" : "createLevenbergMarquardt"; // bindCreateSolverVariadic<Problems...>::template bind< // nonlinear_solver_t, Unweighted>(m, name); // } // }; // //------------------------------------------------ // /* GN, R/H API solved with QR */ // //------------------------------------------------ // template<bool do_gn, class ...> // struct LeastSquaresQRBinder; // template<bool do_gn, class qr_solver_t, class ...Problems> // struct LeastSquaresQRBinder< // do_gn, qr_solver_t, std::tuple<Problems...> // > // { // static_assert(do_gn, "QR-based solver only supported for GN"); // static_assert(_have_rj_api_var<Problems...>::value, ""); // // it does not matter here if we use the steady system or stepper_t // // as template arg to compose the solver type in the code below as long as it // // meets the res-jac api. But since we are here, this condition is met // // because it is asserted above. so just pick the first problem type in the // // pack, which should be a steady lspg problem, and so it has a system_t typedef // // that we can use for compose solver below // using head_problem_t = typename std::tuple_element<0, std::tuple<Problems...>>::type; // using system_t = typename head_problem_t::system_t; // using nonlinear_solver_t = // pressio::nonlinearsolvers::impl::composeGaussNewtonQR_t<system_t, qr_solver_t>; // static void bindClass(pybind11::module & m, const std::string & solverPythonName) // { // pybind11::class_<nonlinear_solver_t> nonLinSolver(m, solverPythonName.c_str()); // bindTolerancesMethods(nonLinSolver); // bindStoppingCriteria(nonLinSolver); // bindCommonSolverMethods(nonLinSolver); // // Note we don't bind the constructor because from Python we use the create // // function (see below) to instantiate a solver object, we never // // use the class name directly. This is useful because it allows us // // to overcome the problem of needing unique class names in python // } // static void bindCreate(pybind11::module & m) // { // const std::string name = do_gn ? "createGaussNewtonQR" : "createLevenbergMarquardtQR"; // bindCreateSolverVariadic<Problems...>::template bind< // nonlinear_solver_t, Unweighted>(m, name); // } // }; // //---------------------------------------------------- // /* weighted GN or LM, R/J API with normal equations */ // //---------------------------------------------------- // template<bool do_gn, class ...> // struct WeightedLeastSquaresNormalEqBinder; // template< // bool do_gn, // typename linear_solver_t, // typename weigher_t, // class ... Problems // > // struct WeightedLeastSquaresNormalEqBinder< // do_gn, linear_solver_t, weigher_t, std::tuple<Problems...> // > // { // static_assert(_have_rj_api_var<Problems...>::value, ""); // // it does not matter here if we use the steady system or stepper_t // // as template arg to compose the solver type in the code below as long as it // // meets the res-jac api. But since we are here, this condition is met // // because it is asserted above. so just pick the first problem type in the // // pack, which should be a steady lspg problem, and so it has a system_t typedef // // that we can use for compose solver below // using head_problem_t = typename std::tuple_element<0, std::tuple<Problems...>>::type; // using system_t = typename head_problem_t::system_t; // // gauss-newton solver type // using gn_type = // pressio::nonlinearsolvers::impl::composeGaussNewton_t<system_t, linear_solver_t, weigher_t>; // // lm solver type // using lm_type = // pressio::nonlinearsolvers::impl::composeLevenbergMarquardt_t<system_t, linear_solver_t, weigher_t>; // // pick the final nonlin solver type is based on the do_gn // using nonlinear_solver_t = typename std::conditional<do_gn, gn_type, lm_type>::type; // static void bindClass(pybind11::module & m, const std::string & solverPythonName) // { // pybind11::class_<nonlinear_solver_t> nonLinSolver(m, solverPythonName.c_str()); // bindTolerancesMethods(nonLinSolver); // bindStoppingCriteria(nonLinSolver); // bindCommonSolverMethods(nonLinSolver); // // Note we don't bind the constructor because from Python we use the create // // function (see below) to instantiate a solver object, we never // // use the class name directly. This is useful because it allows us // // to overcome the problem of needing unique class names in python // } // static void bindCreate(pybind11::module & m) // { // const std::string name = // do_gn ? "createWeightedGaussNewton" : "createWeightedLevenbergMarquardt"; // bindCreateSolverVariadic<Problems...>::template bind< // nonlinear_solver_t, Weighted>(m, name); // } // }; // //---------------------------------------- // /* IRWGN normal equations */ // //---------------------------------------- // template<class ...> // struct IrwLeastSquaresNormalEqBinder; // template<class linear_solver_t, class ...Problems> // struct IrwLeastSquaresNormalEqBinder<linear_solver_t, std::tuple<Problems...>> // { // static_assert(_have_rj_api_var<Problems...>::value, ""); // // it does not matter here if we use the steady system or stepper_t // // as template arg to compose the solver type in the code below as long as it // // meets the res-jac api. But since we are here, this condition is met // // because it is asserted above. so just pick the first problem type in the // // pack, which should be a steady lspg problem, and so it has a system_t typedef // // that we can use for compose solver below // using head_problem_t = typename std::tuple_element<0, std::tuple<Problems...>>::type; // using system_t = typename head_problem_t::system_t; // using composer_t = pressio::nonlinearsolvers::impl::composeIrwGaussNewton<system_t, linear_solver_t>; // using w_t = typename composer_t::weighting_t; // using nonlinear_solver_t = typename composer_t::type; // static void bindClass(pybind11::module & m, const std::string & solverPythonName) // { // pybind11::class_<nonlinear_solver_t> nonLinSolver(m, solverPythonName.c_str()); // bindTolerancesMethods(nonLinSolver); // bindStoppingCriteria(nonLinSolver); // bindCommonSolverMethods(nonLinSolver); // // Note we don't bind the constructor because from Python we use the create // // function (see below) to instantiate a solver object, we never // // use the class name directly. This is useful because it allows us // // to overcome the problem of needing unique class names in python // } // static void bindCreate(pybind11::module & m) // { // const std::string name = "createIrwGaussNewton"; // bindCreateSolverVariadic<Problems...>::template bind< // nonlinear_solver_t, Irwls>(m, name); // } // }; // //------------------------------------------------- // /* GN or LM with normal equations, hess-grad api */ // //------------------------------------------------- // template<bool do_gn, typename ...> // struct LeastSquaresNormalEqHessGrapApiBinder; // template<bool do_gn, typename linear_solver_wrapper_t, typename ...Problems> // struct LeastSquaresNormalEqHessGrapApiBinder< // do_gn, linear_solver_wrapper_t, std::tuple<Problems...> // > // { // using system_t = typename std::tuple_element<0, std::tuple<Problems...>>::type; // // gauss-newton solver type // using gn_type = pressio::nonlinearsolvers::impl::composeGaussNewton_t // <system_t, linear_solver_wrapper_t>; // // lm solver type // using lm_type = pressio::nonlinearsolvers::impl::composeLevenbergMarquardt_t // <system_t, linear_solver_wrapper_t>; // // pick gn or lm conditioned on the bool argument // using nonlinear_solver_t = typename std::conditional<do_gn, gn_type, lm_type>::type; // static void bindClass(pybind11::module & m, const std::string & solverPythonName) // { // pybind11::class_<nonlinear_solver_t> nonLinSolver(m, solverPythonName.c_str()); // bindTolerancesMethods(nonLinSolver); // bindStoppingCriteria(nonLinSolver); // bindCommonSolverMethods(nonLinSolver); // // Note we don't bind the constructor because from Python we use the create // // function (see below) to instantiate a solver object, we never // // use the class name directly. This is useful because it allows us // // to overcome the problem of needing unique class names in python // } // static void bindCreate(pybind11::module & m) // { // const std::string name = "createGaussNewton"; // bindCreateSolverVariadic<Problems...>::template bind< // nonlinear_solver_t, UnweightedWls>(m, name); // } // }; // //------------------------------------------------ // // helper metafunction for dealing with types in a tuple // //------------------------------------------------ // template<template<bool, typename...> class T, bool, typename...> // struct instantiate_from_tuple_pack { }; // template< // template<bool, typename...> class T, // bool b, class T1, typename... Ts // > // struct instantiate_from_tuple_pack<T, b, T1, std::tuple<Ts...>> // { // using type = T<b, T1, Ts...>; // }; // template< // template<bool, typename...> class T, // bool b, class T1, class T2, typename... Ts // > // struct instantiate_from_tuple_pack<T, b, T1, T2, std::tuple<Ts...>> // { // using type = T<b, T1, T2, Ts...>; // };
38.90625
106
0.692537
Pressio
a73de8b258197059f53de6a0513f4fc464af1299
1,113
cpp
C++
module/PocoLib/Register.cpp
theKAKAN/SqMod
0c4c78da6e5f2741b0f65215fe08b84232a02fec
[ "MIT" ]
10
2018-06-12T17:56:02.000Z
2020-04-06T12:02:16.000Z
module/PocoLib/Register.cpp
theKAKAN/SqMod
0c4c78da6e5f2741b0f65215fe08b84232a02fec
[ "MIT" ]
45
2016-06-19T09:31:22.000Z
2020-04-16T08:54:13.000Z
module/PocoLib/Register.cpp
theKAKAN/SqMod
0c4c78da6e5f2741b0f65215fe08b84232a02fec
[ "MIT" ]
16
2016-07-07T06:48:35.000Z
2020-05-24T09:43:52.000Z
// ------------------------------------------------------------------------------------------------ #include "PocoLib/Register.hpp" // ------------------------------------------------------------------------------------------------ namespace SqMod { // ------------------------------------------------------------------------------------------------ extern void Register_POCO_Crypto(HSQUIRRELVM vm, Table & ns); extern void Register_POCO_Data(HSQUIRRELVM vm, Table & ns); extern void Register_POCO_Net(HSQUIRRELVM vm, Table & ns); extern void Register_POCO_RegEx(HSQUIRRELVM vm, Table & ns); extern void Register_POCO_Time(HSQUIRRELVM vm, Table & ns); extern void Register_POCO_Util(HSQUIRRELVM vm, Table & ns); // ================================================================================================ void Register_POCO(HSQUIRRELVM vm) { Table ns(vm); Register_POCO_Crypto(vm, ns); Register_POCO_Data(vm, ns); Register_POCO_Net(vm, ns); Register_POCO_RegEx(vm, ns); Register_POCO_Time(vm, ns); Register_POCO_Util(vm, ns); RootTable(vm).Bind(_SC("Sq"), ns); } } // Namespace:: SqMod
35.903226
99
0.483378
theKAKAN
a73e036704fd31a260695150b85b95c61fac9377
5,777
cc
C++
src/plat-linux/drivers/sg_driver.cc
jc-lab/jcu-dparm
140efc844e339ca22d79a9958bdcbc7195701835
[ "Apache-2.0" ]
null
null
null
src/plat-linux/drivers/sg_driver.cc
jc-lab/jcu-dparm
140efc844e339ca22d79a9958bdcbc7195701835
[ "Apache-2.0" ]
null
null
null
src/plat-linux/drivers/sg_driver.cc
jc-lab/jcu-dparm
140efc844e339ca22d79a9958bdcbc7195701835
[ "Apache-2.0" ]
null
null
null
/** * @file sg_driver.cc * @author Joseph Lee <development@jc-lab.net> * @date 2020/07/23 * @copyright Copyright (C) 2020 jc-lab.\n * This software may be modified and distributed under the terms * of the Apache License 2.0. See the LICENSE file for details. */ #include <unistd.h> #include <sys/types.h> #include <sys/fcntl.h> #include <scsi/scsi.h> #include <scsi/sg.h> #include <sys/ioctl.h> #include "sg_driver.h" #include "../../intl_utils.h" #include "../sgio.h" #include <jcu-dparm/ata_types.h> #include <jcu-dparm/ata_utils.h> namespace jcu { namespace dparm { namespace plat_linux { namespace drivers { class SgDriverHandle : public LinuxDriverHandle { private: scsi_sg_device dev_; std::string path_; public: std::string getDriverName() const override { return "LinuxSgDriver"; } SgDriverHandle(const scsi_sg_device& dev, const std::string& path, ata::ata_identify_device_data_t *identify_device_data) : dev_(dev), path_(path) { const unsigned char *raw_identify_device_data = (const unsigned char *)identify_device_data; driving_type_ = kDrivingAtapi; ata_identify_device_buf_.insert( ata_identify_device_buf_.end(), &raw_identify_device_data[0], &raw_identify_device_data[sizeof(ata::ata_identify_device_data_t)] ); } int getFD() const override { return dev_.fd; } void close() override { if (dev_.fd > 0) { ::close(dev_.fd); dev_.fd = 0; } } int reopenWritable() override { int new_fd = ::open(path_.c_str(), O_RDWR | O_NONBLOCK); if (new_fd < 0) { return new_fd; } ::close(dev_.fd); dev_.fd = new_fd; return 0; } bool driverIsAtaCmdSupported() const override { return true; } DparmResult doAtaCmd( int rw, unsigned char* cdb, unsigned int cdb_bytes, void *data, unsigned int data_bytes, int pack_id, unsigned int timeout_secs, unsigned char *sense_buf, unsigned int sense_buf_bytes ) override { int rc = do_sg_ata(&dev_, rw, cdb, cdb_bytes, data, data_bytes, pack_id, timeout_secs, sense_buf, sense_buf_bytes); if (rc > 0) { return { DPARME_ATA_FAILED, rc }; }else if (rc < 0 ) { return { DPARME_SYS, errno }; } return { DPARME_OK, 0 }; } bool driverIsTaskfileCmdSupported() const override { return true; } DparmResult doTaskfileCmd( int rw, int dma, ata::ata_tf_t *tf, void *data, unsigned int data_bytes, unsigned int timeout_secs ) override { unsigned char sense_data[32] = { 0 }; if (dma < 0) { dma = ata::is_dma(tf->command); } int rc = sg16(&dev_, rw, dma, tf, data, data_bytes, timeout_secs, sense_data, sizeof(sense_data)); if (rc > 0) { return { DPARME_ATA_FAILED, rc }; }else if (rc < 0 ) { return { DPARME_SYS, errno }; } return { DPARME_OK, 0 }; } /** * Reference: https://www.seagate.com/files/staticfiles/support/docs/manual/Interface%20manuals/100293068j.pdf */ DparmReturn<InquiryDeviceResult> inquiryDeviceInfo() override { InquiryDeviceResult info = {}; for (int i=0; i < 2; i++) { int result; struct sg_io_hdr io_hdr; unsigned char payload_buffer[192] = {0}; unsigned char sense[32] = {0}; // Standard INQUIRY unsigned char inq_cmd[] = { INQUIRY, 0, 0, 0, sizeof(payload_buffer), 0 }; if (i == 1) { inq_cmd[1] = 1; inq_cmd[2] = 0x80; } memset(&io_hdr, 0, sizeof(io_hdr)); io_hdr.interface_id = 'S'; io_hdr.cmdp = inq_cmd; io_hdr.cmd_len = sizeof(inq_cmd); io_hdr.dxferp = payload_buffer; io_hdr.dxfer_len = sizeof(payload_buffer); io_hdr.dxfer_direction = SG_DXFER_FROM_DEV; io_hdr.sbp = sense; io_hdr.mx_sb_len = sizeof(sense); io_hdr.timeout = 5000; result = ioctl(dev_.fd, SG_IO, &io_hdr); if (result < 0) { return {DPARME_IOCTL_FAILED, errno}; } if ((io_hdr.info & SG_INFO_OK_MASK) != SG_INFO_OK) { return {DPARME_IOCTL_FAILED, 0, (int32_t) io_hdr.info}; } // fixed length... It may not be the full name. if (i == 0) { info.vendor_identification = intl::trimString(intl::readString(&payload_buffer[8], 8)); info.product_identification = intl::trimString(intl::readString(&payload_buffer[16], 16)); info.product_revision_level = intl::trimString(intl::readString(&payload_buffer[32], 4)); } else { info.drive_serial_number = intl::trimString(intl::readString(&payload_buffer[4], payload_buffer[3])); } } return { DPARME_OK, 0, 0, info }; } }; DparmReturn<std::unique_ptr<LinuxDriverHandle>> SgDriver::open(const char *path) { std::string strpath(path); DparmResult result; scsi_sg_device dev = {0}; unsigned char sense_data[32]; do { dev.fd = ::open(path, O_RDONLY | O_NONBLOCK); if (dev.fd == -1) { result = { DPARME_SYS, errno }; break; } dev.debug_puts = options_.debug_puts; dev.verbose = options_.verbose; apt_detect(&dev); ata::ata_tf_t tf = {0}; ata::ata_identify_device_data_t temp = {0}; tf.command = 0xec; if (sg16(&dev, 0, 0, &tf, &temp, sizeof(temp), 3, sense_data, sizeof(sense_data)) == -1) { result = { DPARME_SYS, dev.last_errno }; break; } std::unique_ptr<SgDriverHandle> driver_handle(new SgDriverHandle(dev, strpath, &temp)); return {DPARME_OK, 0, 0, std::move(driver_handle)}; } while (0); if (dev.fd > 0) { ::close(dev.fd); } return { result.code, result.sys_error }; } } // namespace dparm } // namespace plat_linux } // namespace dparm } // namespace jcu
26.259091
123
0.629566
jc-lab
a73ff525c3b31bc92a198ea0fd5a3a220f38a258
1,496
cpp
C++
201722/dec201722_1.cpp
jibsen/aocpp2017
8c53665ffc99a58b905758b6baf4f960d65d058c
[ "MIT" ]
null
null
null
201722/dec201722_1.cpp
jibsen/aocpp2017
8c53665ffc99a58b905758b6baf4f960d65d058c
[ "MIT" ]
null
null
null
201722/dec201722_1.cpp
jibsen/aocpp2017
8c53665ffc99a58b905758b6baf4f960d65d058c
[ "MIT" ]
null
null
null
// // Advent of Code 2017, day 22, part one // #include <algorithm> #include <iostream> #include <string> #include <unordered_set> #include <utility> #include <vector> struct PairHash { template<typename T1, typename T2> std::size_t operator()(const std::pair<T1, T2> &p) const noexcept { std::size_t h1 = std::hash<T1>()(p.first); std::size_t h2 = std::hash<T2>()(p.second); return (17 * 37 + h1) * 37 + h2; } }; using Infected = std::unordered_set<std::pair<int, int>, PairHash>; auto read_map() { std::vector<std::string> map; for (std::string line; std::getline(std::cin, line) && !line.empty(); ) { map.push_back(std::move(line)); } return map; } auto get_infected_from_map(const auto &map) { Infected infected; int mid_y = map.size() / 2; int mid_x = map[0].size() / 2; for (int y = 0; y < map.size(); ++y) { for (int x = 0; x < map[y].size(); ++x) { if (map[y][x] == '#') { infected.insert({x - mid_x, mid_y - y}); } } } return infected; } int main() { auto map = read_map(); auto infected = get_infected_from_map(map); int x = 0; int y = 0; int dx = 0; int dy = 1; std::size_t num_became_infected = 0; for (std::size_t bursts = 0; bursts != 10'000; ++bursts) { if (auto [it, success] = infected.insert({x, y}); !success) { dx = std::exchange(dy, -dx); infected.erase(it); } else { dy = std::exchange(dx, -dy); ++num_became_infected; } x += dx; y += dy; } std::cout << num_became_infected << '\n'; }
17.809524
74
0.596925
jibsen
a7404fe1594510cd4ef0fe820aba984d3e85cbd9
3,934
cpp
C++
src/qt/qtbase/examples/widgets/itemviews/spreadsheet/spreadsheetdelegate.cpp
power-electro/phantomjs-Gohstdriver-DIY-openshift
a571d301a9658a4c1b524d07e15658b45f8a0579
[ "BSD-3-Clause" ]
1
2020-04-30T15:47:35.000Z
2020-04-30T15:47:35.000Z
src/qt/qtbase/examples/widgets/itemviews/spreadsheet/spreadsheetdelegate.cpp
power-electro/phantomjs-Gohstdriver-DIY-openshift
a571d301a9658a4c1b524d07e15658b45f8a0579
[ "BSD-3-Clause" ]
null
null
null
src/qt/qtbase/examples/widgets/itemviews/spreadsheet/spreadsheetdelegate.cpp
power-electro/phantomjs-Gohstdriver-DIY-openshift
a571d301a9658a4c1b524d07e15658b45f8a0579
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the demonstration applications of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "spreadsheetdelegate.h" #include <QtWidgets> SpreadSheetDelegate::SpreadSheetDelegate(QObject *parent) : QItemDelegate(parent) {} QWidget *SpreadSheetDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &, const QModelIndex &index) const { if (index.column() == 1) { QDateTimeEdit *editor = new QDateTimeEdit(parent); editor->setDisplayFormat("dd/M/yyyy"); editor->setCalendarPopup(true); return editor; } QLineEdit *editor = new QLineEdit(parent); // create a completer with the strings in the column as model QStringList allStrings; for (int i = 1; i<index.model()->rowCount(); i++) { QString strItem(index.model()->data(index.sibling(i, index.column()), Qt::EditRole).toString()); if (!allStrings.contains(strItem)) allStrings.append(strItem); } QCompleter *autoComplete = new QCompleter(allStrings); editor->setCompleter(autoComplete); connect(editor, &QLineEdit::editingFinished, this, &SpreadSheetDelegate::commitAndCloseEditor); return editor; } void SpreadSheetDelegate::commitAndCloseEditor() { QLineEdit *editor = qobject_cast<QLineEdit *>(sender()); emit commitData(editor); emit closeEditor(editor); } void SpreadSheetDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { QLineEdit *edit = qobject_cast<QLineEdit*>(editor); if (edit) { edit->setText(index.model()->data(index, Qt::EditRole).toString()); return; } QDateTimeEdit *dateEditor = qobject_cast<QDateTimeEdit *>(editor); if (dateEditor) { dateEditor->setDate(QDate::fromString( index.model()->data(index, Qt::EditRole).toString(), "d/M/yyyy")); } } void SpreadSheetDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { QLineEdit *edit = qobject_cast<QLineEdit *>(editor); if (edit) { model->setData(index, edit->text()); return; } QDateTimeEdit *dateEditor = qobject_cast<QDateTimeEdit *>(editor); if (dateEditor) model->setData(index, dateEditor->date().toString("dd/M/yyyy")); }
36.766355
99
0.655313
power-electro
a744186fff242abf21dc98757d412311e8a45580
1,415
cc
C++
third_party/blink/renderer/platform/testing/noop_web_url_loader.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
third_party/blink/renderer/platform/testing/noop_web_url_loader.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
third_party/blink/renderer/platform/testing/noop_web_url_loader.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/platform/testing/noop_web_url_loader.h" #include "services/network/public/cpp/resource_request.h" #include "third_party/blink/public/platform/resource_load_info_notifier_wrapper.h" #include "third_party/blink/public/platform/web_url_request_extra_data.h" namespace blink { void NoopWebURLLoader::LoadSynchronously( std::unique_ptr<network::ResourceRequest> request, scoped_refptr<WebURLRequestExtraData> url_request_extra_data, bool pass_response_pipe_to_client, bool no_mime_sniffing, base::TimeDelta timeout_interval, WebURLLoaderClient*, WebURLResponse&, absl::optional<WebURLError>&, WebData&, int64_t& encoded_data_length, int64_t& encoded_body_length, WebBlobInfo& downloaded_blob, std::unique_ptr<blink::ResourceLoadInfoNotifierWrapper> resource_load_info_notifier_wrapper) { NOTREACHED(); } void NoopWebURLLoader::LoadAsynchronously( std::unique_ptr<network::ResourceRequest> request, scoped_refptr<WebURLRequestExtraData> url_request_extra_data, bool no_mime_sniffing, std::unique_ptr<blink::ResourceLoadInfoNotifierWrapper> resource_load_info_notifier_wrapper, WebURLLoaderClient*) {} } // namespace blink
35.375
82
0.787279
zealoussnow
a745df55c25a7cba822d143b33c40e82b16ab61c
3,095
cpp
C++
src/gs/gsVertex.cpp
frmr/gs
b9721ad27f59ca2e19f637bccd9eba32b663b6a3
[ "MIT" ]
2
2016-12-06T17:51:30.000Z
2018-06-21T08:52:58.000Z
src/gs/gsVertex.cpp
frmr/gs
b9721ad27f59ca2e19f637bccd9eba32b663b6a3
[ "MIT" ]
null
null
null
src/gs/gsVertex.cpp
frmr/gs
b9721ad27f59ca2e19f637bccd9eba32b663b6a3
[ "MIT" ]
null
null
null
#include "gsVertex.hpp" #include "gsEdge.hpp" #include "gsTile.hpp" #include <algorithm> #include <iostream> #include <limits> using std::cerr; using std::endl; int gs::Vertex::idCounter = 0; void gs::Vertex::AddLink(const gs::Link<gs::Vertex>& link) { links.push_back(link); } void gs::Vertex::AddTile(const shared_ptr<gs::Tile> tile) { tiles.push_back(tile); } void gs::Vertex::CalculateHeight() { double total = 0; for (const auto& tile : tiles) { total += tile->GetHeight(); } height = total / (double) tiles.size(); } vector<shared_ptr<gs::Edge>> gs::Vertex::GetEdges() const { return edges; } shared_ptr<gs::Edge> gs::Vertex::GetEdgeWith(const shared_ptr<gs::Vertex> refVertex) const { for (auto link : links) { if (link.edge->HasVertex(refVertex)) { return link.edge; } } return nullptr; } double gs::Vertex::GetHeight() const { return height; } //gs::Vec3d gs::Vertex::GetPosition() const //{ // return position; //} bool gs::Vertex::IsRiver() const { return (riverId != -1); } // //void gs::Vertex::SetPosition(const gs::Vec3d& newPosition) //{ // position = newPosition; //} bool gs::Vertex::SetRiver(const int newRiverId) { if (riverId == newRiverId) { //river converges with itself, which is impossible return false; } else if (riverId != -1) { //two rivers converge return true; } //else, the vertex is not already a river //stop if vertex touches the sea for (const auto& tile : tiles) { if (tile->GetSurface() == gs::Tile::Type::WATER) { return true; } } riverId = newRiverId; vector<int> visitedIds; bool childSucceeded = false; while (!childSucceeded) { gs::EdgePtr lowestEdge = nullptr; gs::VertexPtr lowestVertex = nullptr; double lowestHeight = GetHeight(); for (auto& link : links) { bool targetVisited = (std::find(visitedIds.begin(), visitedIds.end(), link.target->id) != visitedIds.end()); if (!targetVisited && link.target->GetHeight() < lowestHeight) { lowestEdge = link.edge; lowestVertex = link.target; lowestHeight = link.target->GetHeight(); } } if (lowestEdge == nullptr) { riverId = -1; return false; } else { childSucceeded = lowestVertex->SetRiver(newRiverId); if (childSucceeded) { lowestEdge->SetRiver(); } else { visitedIds.push_back(lowestVertex->id); } } } return true; } gs::Vertex::Vertex(const gs::Vec3d& position) : id(idCounter++), position(position), height(0.0), riverId(-1) { }
21.054422
121
0.527625
frmr
a74600e2f90d3fd754c2f5d30e5d24cb71c686f6
1,349
cpp
C++
leetcode/131.palindrome-partitioning.cpp
geemaple/algorithm
68bc5032e1ee52c22ef2f2e608053484c487af54
[ "MIT" ]
177
2017-08-21T08:57:43.000Z
2020-06-22T03:44:22.000Z
leetcode/131.palindrome-partitioning.cpp
geemaple/algorithm
68bc5032e1ee52c22ef2f2e608053484c487af54
[ "MIT" ]
2
2018-09-06T13:39:12.000Z
2019-06-03T02:54:45.000Z
leetcode/131.palindrome-partitioning.cpp
geemaple/algorithm
68bc5032e1ee52c22ef2f2e608053484c487af54
[ "MIT" ]
23
2017-08-23T06:01:28.000Z
2020-04-20T03:17:36.000Z
class Solution { private: vector<vector<bool>> isPalindrome; void helper(string& s, int start, vector<string>& ans, vector<vector<string>>& res) { if (start == s.size()) { res.push_back(ans); return; } for (auto i = start; i < s.size(); ++i) { if (isPalindrome[start][i]) { ans.push_back(s.substr(start, i - start + 1)); helper(s, i + 1, ans, res); ans.pop_back(); } } } public: vector<vector<string>> partition(string s) { int size = s.size(); isPalindrome.resize(size, vector<bool>(size, false)); int i, j =0; for (auto t = 0; t < size; ++t) { i = j = t; while(i >= 0 && j < size && s[i] == s[j]) { isPalindrome[i][j] = true; i--; j++; } i = t; j = t + 1; while(i >= 0 && j < size && s[i] == s[j]) { isPalindrome[i][j] = true; i--; j++; } } vector<string> ans; vector<vector<string>> res; helper(s, 0, ans, res); return res; } };
24.527273
87
0.364715
geemaple
a746069e133aeaef9f162224b4b9d83ebcd4cffe
319
cpp
C++
src/Test.PlcNext/Deployment/InitializedStructPortField/src/InitializedStructPortFieldProgram.cpp
PLCnext/PLCnext_CLI
cf8ad590f05196747b403da891bdd5da86f82469
[ "Apache-2.0" ]
7
2020-10-08T12:37:49.000Z
2021-03-29T07:49:52.000Z
src/Test.PlcNext/Deployment/InitializedStructPortField/src/InitializedStructPortFieldProgram.cpp
PLCnext/PLCnext_CLI
cf8ad590f05196747b403da891bdd5da86f82469
[ "Apache-2.0" ]
10
2020-10-09T14:04:01.000Z
2022-03-09T09:38:58.000Z
src/Test.PlcNext/Deployment/InitializedStructPortField/src/InitializedStructPortFieldProgram.cpp
PLCnext/PLCnext_CLI
cf8ad590f05196747b403da891bdd5da86f82469
[ "Apache-2.0" ]
2
2020-09-04T06:45:39.000Z
2020-10-30T10:07:33.000Z
#include "InitializedStructPortFieldProgram.hpp" #include "Arp/System/Commons/Logging.h" #include "Arp/System/Core/ByteConverter.hpp" namespace InitializedStructPortField { void InitializedStructPortFieldProgram::Execute() { //implement program } } // end of namespace InitializedStructPortField
22.785714
50
0.768025
PLCnext
a7460b0917459ed8bacb876f17aa6ffb1f846cfd
430
cpp
C++
gator-game-jam-2021/UidGenerator.cpp
lukas-vaiciunas/haterminator
7f42e5a4ed4c5dee21368859989b74ba6c80898b
[ "MIT" ]
null
null
null
gator-game-jam-2021/UidGenerator.cpp
lukas-vaiciunas/haterminator
7f42e5a4ed4c5dee21368859989b74ba6c80898b
[ "MIT" ]
null
null
null
gator-game-jam-2021/UidGenerator.cpp
lukas-vaiciunas/haterminator
7f42e5a4ed4c5dee21368859989b74ba6c80898b
[ "MIT" ]
null
null
null
#include "UidGenerator.h" UidGenerator::UidGenerator() : next_(1) {} UidGenerator &UidGenerator::instance() { static UidGenerator uidGenerator; return uidGenerator; } unsigned int UidGenerator::generate() { unsigned int uid = 0; if (!released_.empty()) { uid = released_.front(); released_.pop(); } else { uid = next_++; } return uid; } void UidGenerator::release(unsigned int uid) { released_.push(uid); }
13.030303
44
0.686047
lukas-vaiciunas
a7469abfc20ec604a21dbfac6f6e605e79ef2312
1,370
cpp
C++
bin/old/main.cpp
beckerrh/simfemsrc
d857eb6f6f8627412d4f9d89a871834c756537db
[ "MIT" ]
null
null
null
bin/old/main.cpp
beckerrh/simfemsrc
d857eb6f6f8627412d4f9d89a871834c756537db
[ "MIT" ]
1
2019-01-31T10:59:11.000Z
2019-01-31T10:59:11.000Z
bin/old/main.cpp
beckerrh/simfemsrc
d857eb6f6f8627412d4f9d89a871834c756537db
[ "MIT" ]
null
null
null
#include "simfem/timestepping.hpp" // typedef double (*nlfct)(double u, double v); //Hopf // double global_Du = 0.0; // double global_Dv = 0.0; // double global_a = 1.0; // double global_b = 2.1; // double global_T = 50.0; // double global_eps = 0.01; //spatial pattern // double global_Du = 0.001; // double global_Dv = 0.01; // double global_a = 1.0; // double global_b = 2.0; // double global_T = 30.0; // double global_eps = 0.01; //Turing double global_Du = 0.0001; double global_Dv = 0.01; double global_a = 1.0; double global_b = 1.5; double global_T = 1.0; double global_eps = 0.01; /*---------------------------------------------------------------------------*/ int main(int argc, char** argv) { if (argc !=4) { printf("%s needs arguments <nx, nt, scheme>\n", argv[0]); exit(1); } int nx = atoi(argv[1]); int nt = atoi(argv[2]); std::string scheme = argv[3]; TimeSteppingData timesteppingdata; timesteppingdata.T = global_T; timesteppingdata.nt = nt; timesteppingdata.nx = nx; timesteppingdata.scheme = scheme; Nonlinearity nonlinearity("brusselator"); nonlinearity.set_Du(global_Du); nonlinearity.set_Dv(global_Dv); nonlinearity.set_eps(global_eps); nonlinearity.set_a(global_a); nonlinearity.set_b(global_b); TimeStepping timestepping(timesteppingdata, nonlinearity); timestepping.run(); return 0; }
24.909091
79
0.643796
beckerrh
a7495d8bed1dfb48e06a6b7beeda4d7a0a46d6ed
2,764
hpp
C++
tcpp/minion2/minion/system/minlib/immutable_string.hpp
Behrouz-Babaki/TCPP-chuffed
d832b44690914ef4b73d71bc7e565efb98e42937
[ "MIT" ]
1
2021-09-09T13:03:02.000Z
2021-09-09T13:03:02.000Z
tcpp/minion2/minion/system/minlib/immutable_string.hpp
Behrouz-Babaki/TCPP-chuffed
d832b44690914ef4b73d71bc7e565efb98e42937
[ "MIT" ]
null
null
null
tcpp/minion2/minion/system/minlib/immutable_string.hpp
Behrouz-Babaki/TCPP-chuffed
d832b44690914ef4b73d71bc7e565efb98e42937
[ "MIT" ]
null
null
null
#ifndef IMMUTABLE_STRING_HPP #define IMMUTABLE_STRING_HPP #include "basic_sys.hpp" #include "hash.hpp" class ImmutableStringCache { public: static ImmutableStringCache& getInstance() { static ImmutableStringCache instance; return instance; } private: ImmutableStringCache(){}; ImmutableStringCache(ImmutableStringCache const&); // Don't Implement void operator=(ImmutableStringCache const&); // Don't implement std::set<std::string> strings; // we special case this, as we need it often std::string empty_string; public: const std::string* cachedString(const std::string& in) { if(in == empty_string) return &empty_string; auto it = strings.find(in); if(it != strings.end()) return &*it; strings.insert(in); it = strings.find(in); if(it != strings.end()) return &*it; abort(); } const std::string* cachedEmptyString() { return &empty_string; } }; class ImmutableString { // In the long term, this could be made more efficient const std::string* ptr; public: const std::string& getStdString() const { return *ptr; } // The reason these are explicit is because constructing an 'ImmutableString' // is fairly // expensive, so we want to know when we do it. explicit ImmutableString(const std::string& s) : ptr(ImmutableStringCache::getInstance().cachedString(s)) {} explicit ImmutableString(const char* s) : ptr(ImmutableStringCache::getInstance().cachedString(s)) {} ImmutableString() : ptr(ImmutableStringCache::getInstance().cachedEmptyString()) {} char operator[](int i) const { return (*ptr)[i]; } auto begin() -> decltype(ptr->begin()) { return ptr->begin(); } auto end() -> decltype(ptr->end()) { return ptr->end(); } friend bool operator==(const ImmutableString& lhs, const ImmutableString& rhs) { return lhs.ptr == rhs.ptr; } friend bool operator==(const ImmutableString& lhs, const char* c) { return *(lhs.ptr) == c; } friend bool operator==(const char* c, const ImmutableString& rhs) { return *(rhs.ptr) == c; } // this is the only operator where we really have to compare the true strings friend bool operator<(const ImmutableString& lhs, const ImmutableString& rhs) { return *(lhs.ptr) < *(rhs.ptr); } friend bool operator!=(const ImmutableString& lhs, const ImmutableString& rhs) { return lhs.ptr != rhs.ptr; } friend std::ostream& operator<<(std::ostream& o, const ImmutableString& is) { return o << *(is.ptr); } }; namespace std { template <> struct hash<ImmutableString> : minlib_hash_base<ImmutableString> { public: size_t operator()(const ImmutableString& p) const { return getHash(p.getStdString()); } }; } #endif
23.827586
85
0.672576
Behrouz-Babaki
a74e24e98940f4aa2888e6b5994f1ef1ba01c2ee
2,296
cpp
C++
LIP_Core/src/BandSplitter.cpp
KyrietS/lossy-image-processor
d73552ee3ccb64ae97c55b586e4ce766155bb80c
[ "MIT" ]
null
null
null
LIP_Core/src/BandSplitter.cpp
KyrietS/lossy-image-processor
d73552ee3ccb64ae97c55b586e4ce766155bb80c
[ "MIT" ]
null
null
null
LIP_Core/src/BandSplitter.cpp
KyrietS/lossy-image-processor
d73552ee3ccb64ae97c55b586e4ce766155bb80c
[ "MIT" ]
null
null
null
#include "BandSplitter.hpp" #include <cassert> using byte_t = uint8_t; BandSplitter::BandSplitter(const std::vector<byte_t>& data) { split(data); } BandSplitter::BandSplitter(const std::vector<float>& upper, const std::vector<float>& lower) { upper_band = upper; lower_band = lower; } void BandSplitter::split(const std::vector<byte_t>& data) { if (data.size() == 0) return; lower_band.clear(); upper_band.clear(); for (size_t i = 1; i < data.size(); i += 2) { float lower = ((float)data[i] + (float)data[i - 1]) / 2.0f; float upper = ((float)data[i] - (float)data[i - 1]) / 2.0f; lower_band.push_back(lower); upper_band.push_back(upper); } // If data is not even sized if (data.size() % 2 != 0) { float lower = (float)data[data.size() - 1] / 2.0f; float upper = -1 * (float)data[data.size() - 1] / 2.0f; lower_band.push_back(lower); upper_band.push_back(upper); } } std::vector<byte_t> BandSplitter::mergeEven() { return merge(true); } std::vector<byte_t> BandSplitter::mergeUneven() { return merge(false); } std::vector<byte_t> BandSplitter::merge(bool even_result) { assert(lower_band.size() == upper_band.size()); const size_t BAND_SIZE = lower_band.size(); std::vector<byte_t> result; if (even_result) { for (int i = 0; i < BAND_SIZE; i++) { float even = lower_band[i] - upper_band[i]; float uneven = lower_band[i] + upper_band[i]; even = even < 0 ? 0 : even; even = even > 255 ? 255 : even; uneven = uneven < 0 ? 0 : uneven; uneven = uneven > 255 ? 255 : uneven; result.push_back((byte_t)even); result.push_back((byte_t)uneven); } } else if (BAND_SIZE > 0) { for (int i = 0; i < BAND_SIZE - 1; i++) { float even = lower_band[i] - upper_band[i]; float uneven = lower_band[i] + upper_band[i]; result.push_back((byte_t)even); result.push_back((byte_t)uneven); } float last_element = lower_band[BAND_SIZE - 1] - upper_band[BAND_SIZE - 1]; result.push_back((byte_t)last_element); } return result; }
24.956522
92
0.56838
KyrietS
a74f7bdcd583cfbdd0e0dd2633eaf4ca5b951194
1,470
cpp
C++
ace/ace/FIFO_Send.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
46
2015-12-04T17:12:58.000Z
2022-03-11T04:30:49.000Z
ace/ace/FIFO_Send.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
null
null
null
ace/ace/FIFO_Send.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
23
2016-10-24T09:18:14.000Z
2022-02-25T02:11:35.000Z
// FIFO_Send.cpp // FIFO_Send.cpp,v 4.10 2000/10/07 08:03:47 brunsch Exp #include "ace/FIFO_Send.h" #include "ace/Log_Msg.h" #if defined (ACE_LACKS_INLINE_FUNCTIONS) #include "ace/FIFO_Send.i" #endif ACE_RCSID(ace, FIFO_Send, "FIFO_Send.cpp,v 4.10 2000/10/07 08:03:47 brunsch Exp") ACE_ALLOC_HOOK_DEFINE(ACE_FIFO_Send) void ACE_FIFO_Send::dump (void) const { ACE_TRACE ("ACE_FIFO_Send::dump"); ACE_FIFO::dump (); } ACE_FIFO_Send::ACE_FIFO_Send (void) { // ACE_TRACE ("ACE_FIFO_Send::ACE_FIFO_Send"); } int ACE_FIFO_Send::open (const ACE_TCHAR *rendezvous_name, int flags, int perms, LPSECURITY_ATTRIBUTES sa) { ACE_TRACE ("ACE_FIFO_Send::open"); return ACE_FIFO::open (rendezvous_name, flags | O_WRONLY, perms, sa); } ACE_FIFO_Send::ACE_FIFO_Send (const ACE_TCHAR *fifo_name, int flags, int perms, LPSECURITY_ATTRIBUTES sa) { ACE_TRACE ("ACE_FIFO_Send::ACE_FIFO_Send"); if (this->ACE_FIFO_Send::open (fifo_name, flags, perms, sa) == -1) ACE_ERROR ((LM_ERROR, ACE_LIB_TEXT ("%p\n"), ACE_LIB_TEXT ("ACE_FIFO_Send::ACE_FIFO_Send"))); }
27.222222
82
0.531973
tharindusathis
a750311cd53ec8d89e180190f3c9d3856f6e176c
467
cpp
C++
serial_comm/MessageReceiver.cpp
ZaoLahma/ArduinoStuff
9f02ce2fed1163b66c35fb01448212824f64caf8
[ "MIT" ]
null
null
null
serial_comm/MessageReceiver.cpp
ZaoLahma/ArduinoStuff
9f02ce2fed1163b66c35fb01448212824f64caf8
[ "MIT" ]
null
null
null
serial_comm/MessageReceiver.cpp
ZaoLahma/ArduinoStuff
9f02ce2fed1163b66c35fb01448212824f64caf8
[ "MIT" ]
null
null
null
#include "MessageReceiver.h" #include "Arduino.h" MessageReceiver::MessageReceiver() : currMessage(0u) { } MessageBase* MessageReceiver::getNextMessage() { MessageBase* retVal = NULL; if (messages.size() > currMessage) { retVal = messages.element_at(currMessage); currMessage++; } else { messages.clear(); currMessage = 0u; } return retVal; } void MessageReceiver::storeMessage(MessageBase* msg) { messages.push_back(msg); }
15.064516
52
0.685225
ZaoLahma
a750c3ac105055db5803df4e2006290e4e2acc10
12,274
cpp
C++
cpp/src/arrow.cpp
mvilim/bamboo
6636478346a2f1e9910e18d9bdde97aee4a7a176
[ "Apache-2.0" ]
1
2021-11-07T13:09:13.000Z
2021-11-07T13:09:13.000Z
cpp/src/arrow.cpp
mvilim/bamboo
6636478346a2f1e9910e18d9bdde97aee4a7a176
[ "Apache-2.0" ]
null
null
null
cpp/src/arrow.cpp
mvilim/bamboo
6636478346a2f1e9910e18d9bdde97aee4a7a176
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2019 Michael Vilim // // This file is part of the bamboo library. It is currently hosted at // https://github.com/mvilim/bamboo // // 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 <arrow.hpp> namespace bamboo { namespace arrow { unique_ptr<Node> convert(const Array& array); void update_nulls(const Array& array, Node& node) { // it would be better to directly copy the null array values (or do it in a way that is more // conducive to optimization) for (size_t i = 0; i < array.length(); i++) { if (array.IsNull(i)) { node.add_null(); } else { node.add_not_null(); } } } template <class T> void add_primitives(const NumericArray<T>& array, PrimitiveNode& node) { for (size_t i = 0; i < array.length(); i++) { node.add(array.Value(i)); } } // we should share pieces of this (indexing) with the node visitor, but the templating is a bit // tricky class IndexArrayVisitor : public virtual ArrayVisitor { private: vector<size_t> indices; PrimitiveNode& enum_node; public: IndexArrayVisitor(PrimitiveNode& enum_node) : enum_node(enum_node) {} vector<size_t> take_result() { return std::move(indices); } template <class T> Status handle_numeric(const NumericArray<T>& array) { for (size_t i = 0; i < array.length(); i++) { if (!array.IsNull(i)) { indices.push_back(array.Value(i)); } } return Status::OK(); } virtual Status Visit(const Int8Array& array) final override { return handle_numeric(array); } virtual Status Visit(const Int16Array& array) final override { return handle_numeric(array); } virtual Status Visit(const Int32Array& array) final override { return handle_numeric(array); } virtual Status Visit(const Int64Array& array) final override { return handle_numeric(array); } virtual Status Visit(const UInt8Array& array) final override { return handle_numeric(array); } virtual Status Visit(const UInt16Array& array) final override { return handle_numeric(array); } virtual Status Visit(const UInt32Array& array) final override { return handle_numeric(array); } virtual Status Visit(const UInt64Array& array) final override { return handle_numeric(array); } }; struct ArrowDynamicEnum : public DynamicEnum { ArrowDynamicEnum(unique_ptr<PrimitiveNode> enum_values_node) : enum_values_node(std::move(enum_values_node)){}; virtual ~ArrowDynamicEnum() final override = default; virtual PrimitiveVector& get_enums() final override { return *enum_values_node->get_vector(); } // assume that every arrow enum is consistently sourced virtual const void* source() final override { return 0; } private: unique_ptr<PrimitiveNode> enum_values_node; }; class NodeArrayVisitor : public virtual ArrayVisitor { private: unique_ptr<Node> node; public: unique_ptr<Node> take_result() { return std::move(node); } template <class A, class P> Status handle_generic(A array, std::function<P(A, size_t i)> const& extractor) { node = make_unique<PrimitiveNode>(); PrimitiveNode& pn = static_cast<PrimitiveNode&>(*node); for (size_t i = 0; i < array.length(); i++) { if (!array.IsNull(i)) { pn.add(extractor(array, i)); } } return Status::OK(); } // could we share more of this code with the generic version? Status handle_float16(const HalfFloatArray& array) { node = make_unique<PrimitiveNode>(); PrimitiveNode& pn = static_cast<PrimitiveNode&>(*node); for (size_t i = 0; i < array.length(); i++) { if (!array.IsNull(i)) { pn.add_by_type<PrimitiveType::FLOAT16>(array.Value(i)); } } return Status::OK(); } template <class T> Status handle_numeric(const NumericArray<T>& array) { return handle_generic<const NumericArray<T>&, typename T::c_type>( array, [](const NumericArray<T>& a, size_t i) { return a.Value(i); }); } virtual Status Visit(const NullArray& array) final override { // how do we merge the nulls into the combined array? return Status::NotImplemented("NullArray not implemented"); }; virtual Status Visit(const BooleanArray& array) final override { return handle_generic<const BooleanArray&, bool>( array, [](const BooleanArray& a, size_t i) { return a.Value(i); }); } virtual Status Visit(const Int8Array& array) final override { return handle_numeric(array); } virtual Status Visit(const Int16Array& array) final override { return handle_numeric(array); } virtual Status Visit(const Int32Array& array) final override { return handle_numeric(array); } virtual Status Visit(const Int64Array& array) final override { return handle_numeric(array); } virtual Status Visit(const UInt8Array& array) final override { return handle_numeric(array); } virtual Status Visit(const UInt16Array& array) final override { return handle_numeric(array); } virtual Status Visit(const UInt32Array& array) final override { return handle_numeric(array); } virtual Status Visit(const UInt64Array& array) final override { return handle_numeric(array); } virtual Status Visit(const HalfFloatArray& array) final override { return handle_float16(array); } virtual Status Visit(const FloatArray& array) final override { return handle_numeric(array); } virtual Status Visit(const DoubleArray& array) final override { return handle_numeric(array); } virtual Status Visit(const StringArray& array) final override { node = make_unique<PrimitiveNode>(); PrimitiveNode& pn = static_cast<PrimitiveNode&>(*node); for (size_t i = 0; i < array.length(); i++) { pn.add(array.GetString(i)); } return Status::OK(); } virtual Status Visit(const BinaryArray& array) final override { return Status::NotImplemented("BinaryArray not implemented"); } virtual Status Visit(const FixedSizeBinaryArray& array) final override { return Status::NotImplemented("FixedSizeBinaryArray not implemented"); } virtual Status Visit(const Date32Array& array) final override { return Status::NotImplemented("Date32Array not implemented"); } virtual Status Visit(const Date64Array& array) final override { return Status::NotImplemented("Date64Array not implemented"); } virtual Status Visit(const Time32Array& array) final override { return Status::NotImplemented("Time32Array not implemented"); } virtual Status Visit(const Time64Array& array) final override { return Status::NotImplemented("Time64Array not implemented"); } virtual Status Visit(const TimestampArray& array) final override { return Status::NotImplemented("TimestampArray not implemented"); } virtual Status Visit(const Decimal128Array& array) final override { return Status::NotImplemented("Decimal128Array not implemented"); } virtual Status Visit(const ListArray& array) final override { node = make_unique<ListNode>(); // is there a cleaner way to do this without a raw pointer or cast? ListNode& ln = static_cast<ListNode&>(*node); for (size_t i = 0; i < array.length(); i++) { if (!array.IsNull(i)) { size_t length = array.value_offset(i + 1) - array.value_offset(i); ln.add_list(length); } } unique_ptr<Node>& sub_node = ln.get_list(); sub_node = convert(*array.values()); return Status::OK(); } virtual Status Visit(const StructArray& array) final override { node = make_unique<RecordNode>(); // is there a cleaner way to do this without a raw pointer or cast? RecordNode& rn = static_cast<RecordNode&>(*node); for (auto child : array.struct_type()->children()) { unique_ptr<Node>& field_node = rn.get_field(child->name()); field_node = convert(*array.GetFieldByName(child->name())); } return Status::OK(); } virtual Status Visit(const UnionArray& array) final override { return Status::NotImplemented("UnionArray not implemented"); } virtual Status Visit(const DictionaryArray& array) final override { node = make_unique<PrimitiveNode>(); // is there a cleaner way to do this without a raw pointer or cast? PrimitiveNode& pn = static_cast<PrimitiveNode&>(*node); NodeArrayVisitor enum_visitor; Status status = array.dictionary()->Accept(&enum_visitor); // can an enum have a non-primitive type? // this is a bit ugly -- do we have a better way? std::unique_ptr<PrimitiveNode> enum_values_node = std::unique_ptr<PrimitiveNode>( dynamic_cast<PrimitiveNode*>(enum_visitor.take_result().release())); shared_ptr<ArrowDynamicEnum> enum_value = std::make_shared<ArrowDynamicEnum>(std::move(enum_values_node)); IndexArrayVisitor index_visitor(pn); Status index_status = array.indices()->Accept(&index_visitor); // would be better if we could move this DynamicEnumVector enum_vector; enum_vector.index = index_visitor.take_result(); enum_vector.values = enum_value; pn.get_vector() = make_unique<PrimitiveEnumVector>(std::move(enum_vector)); return Status::OK(); } }; unique_ptr<Node> convert(const Array& array) { NodeArrayVisitor node_visitor; Status status = array.Accept(&node_visitor); if (status.ok()) { unique_ptr<Node> node = node_visitor.take_result(); update_nulls(array, *node); return node; } else { throw std::runtime_error(status.message()); } } unique_ptr<Node> convert(std::istream& is, const ColumnFilter* column_filter) { std::shared_ptr<RecordBatchReader> output; std::shared_ptr<ArrowInputStream> ais = std::make_shared<ArrowInputStream>(is); std::shared_ptr<InputStream> ais_base = std::static_pointer_cast<InputStream>(ais); Status status = ipc::RecordBatchStreamReader::Open(ais_base, &output); std::shared_ptr<RecordBatch> batch; // need to merge the nodes after these record batches // or should the merge be done on the python side? unique_ptr<ListNode> ln = make_unique<ListNode>(); ln->get_list() = make_unique<RecordNode>(); int64_t list_counter = 0; while (true) { Status batch_status = output->ReadNext(&batch); if (!batch_status.ok()) { throw std::runtime_error("Error while running Arrow batch reader"); } if (batch) { RecordNode& rn = static_cast<RecordNode&>(*ln->get_list().get()); for (size_t i = 0; i < batch->num_columns(); i++) { std::shared_ptr<Array> column = batch->column(i); unique_ptr<Node>& column_node = rn.get_field(batch->column_name(i)); column_node = convert(*column); } for (size_t i = 0; i < batch->num_rows(); i++) { rn.add_not_null(); } list_counter += batch->num_rows(); } else { break; } } ln->add_list(list_counter); ln->add_not_null(); return std::move(ln); } } // namespace arrow } // namespace bamboo
37.193939
96
0.647303
mvilim
a751cd7697460236499118eeb5ebfa8111fe6a83
547
hpp
C++
src/Server/Modelo/Juego/Terrenos/CabezaEnemigo.hpp
brunograssano/SuperMarioBros-Honguitos
f945e434bc317a6d8c8d682b1042d8a385929156
[ "MIT" ]
4
2021-02-21T17:12:46.000Z
2021-02-25T20:36:27.000Z
src/Server/Modelo/Juego/Terrenos/CabezaEnemigo.hpp
brunograssano/SuperMarioBros-Honguitos
f945e434bc317a6d8c8d682b1042d8a385929156
[ "MIT" ]
null
null
null
src/Server/Modelo/Juego/Terrenos/CabezaEnemigo.hpp
brunograssano/SuperMarioBros-Honguitos
f945e434bc317a6d8c8d682b1042d8a385929156
[ "MIT" ]
2
2021-02-20T19:49:33.000Z
2021-02-25T20:35:22.000Z
#ifndef TP_TALLER_DE_PROGRAMACION_FIUBA_CABEZAENEMIGO_HPP #define TP_TALLER_DE_PROGRAMACION_FIUBA_CABEZAENEMIGO_HPP #include "Terreno.hpp" class CabezaEnemigo : public Terreno{ public: CabezaEnemigo(); float aplicarCoeficienteDeRozamiento(float velocidadX) override; float obtenerImpulsoHorizontal(float aceleracion) override; float obtenerImpulsoVertical(float fuerza) override; float amortiguarVelocidad(float velocidadY) override; }; #endif //TP_TALLER_DE_PROGRAMACION_FIUBA_CABEZAENEMIGO_HPP
27.35
72
0.795247
brunograssano
a753ef7ad0553099fd0f0d7b72d98d7cdfa237e0
2,061
cpp
C++
src/plugins/advancednotifications/plugins/dolle/notificationhandler.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
120
2015-01-22T14:10:39.000Z
2021-11-25T12:57:16.000Z
src/plugins/advancednotifications/plugins/dolle/notificationhandler.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
8
2015-02-07T19:38:19.000Z
2017-11-30T20:18:28.000Z
src/plugins/advancednotifications/plugins/dolle/notificationhandler.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
33
2015-02-07T16:59:55.000Z
2021-10-12T00:36:40.000Z
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt) **********************************************************************/ #include "notificationhandler.h" #include <numeric> #include <QtDebug> #include <interfaces/structures.h> #include <interfaces/advancednotifications/inotificationrule.h> #include <interfaces/advancednotifications/types.h> #include "dockutil.h" namespace LC { namespace AdvancedNotifications { namespace Dolle { NotificationMethod NotificationHandler::GetHandlerMethod () const { return NMTray; } void NotificationHandler::Handle (const Entity& e, const INotificationRule& rule) { const QString& cat = e.Additional_ ["org.LC.AdvNotifications.EventCategory"].toString (); const QString& type = e.Additional_ ["org.LC.AdvNotifications.EventType"].toString (); const QString& eventId = e.Additional_ ["org.LC.AdvNotifications.EventID"].toString (); auto& data = Counts_ [type]; if (cat != "org.LC.AdvNotifications.Cancel") { if (const int delta = e.Additional_.value ("org.LC.AdvNotifications.DeltaCount", 0).toInt ()) data.Counts_ [eventId] += delta; else data.Counts_ [eventId] = e.Additional_.value ("org.LC.AdvNotifications.Count", 1).toInt (); data.Color_ = rule.GetColor (); data.Total_ = std::accumulate (data.Counts_.constBegin (), data.Counts_.constEnd (), 0); } else { QMutableMapIterator<QString, NotificationData> it { Counts_ }; bool removed = false; while (it.hasNext () && !removed) { NotificationData& nd = it.next ().value (); if (nd.Counts_.remove (eventId)) { nd.Total_ = std::accumulate (data.Counts_.constBegin (), data.Counts_.constEnd (), 0); removed = true; } } if (!removed) return; } DU::SetDockBadges (Counts_.values ()); } } } }
30.308824
96
0.654537
Maledictus
a754e102d7849bcfabd82fbfc54daef55101b8d9
12,948
cxx
C++
Servers/Filters/vtkDesktopDeliveryClient.cxx
matthb2/ParaView-beforekitwareswtichedtogit
e47e57d6ce88444d9e6af9ab29f9db8c23d24cef
[ "BSD-3-Clause" ]
1
2021-07-31T19:38:03.000Z
2021-07-31T19:38:03.000Z
Servers/Filters/vtkDesktopDeliveryClient.cxx
matthb2/ParaView-beforekitwareswtichedtogit
e47e57d6ce88444d9e6af9ab29f9db8c23d24cef
[ "BSD-3-Clause" ]
null
null
null
Servers/Filters/vtkDesktopDeliveryClient.cxx
matthb2/ParaView-beforekitwareswtichedtogit
e47e57d6ce88444d9e6af9ab29f9db8c23d24cef
[ "BSD-3-Clause" ]
2
2019-01-22T19:51:40.000Z
2021-07-31T19:38:05.000Z
/*========================================================================= Program: ParaView Module: $RCSfile$ Copyright (c) Kitware, Inc. All rights reserved. See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkDesktopDeliveryClient.h" #include "vtkDesktopDeliveryServer.h" #include "vtkCallbackCommand.h" #include "vtkCamera.h" #include "vtkCubeSource.h" #include "vtkDoubleArray.h" #include "vtkLight.h" #include "vtkLightCollection.h" #include "vtkMultiProcessController.h" #include "vtkObjectFactory.h" #include "vtkPolyDataMapper.h" #include "vtkRendererCollection.h" #include "vtkRenderWindow.h" #include "vtkSquirtCompressor.h" #include "vtkTimerLog.h" #include "vtkUnsignedCharArray.h" //----------------------------------------------------------------------------- static void vtkDesktopDeliveryClientReceiveImageCallback(vtkObject *, unsigned long, void *clientdata, void *) { vtkDesktopDeliveryClient *self = reinterpret_cast<vtkDesktopDeliveryClient *>(clientdata); self->ReceiveImageFromServer(); } //----------------------------------------------------------------------------- vtkCxxRevisionMacro(vtkDesktopDeliveryClient, "$Revision$"); vtkStandardNewMacro(vtkDesktopDeliveryClient); //---------------------------------------------------------------------------- vtkDesktopDeliveryClient::vtkDesktopDeliveryClient() { this->ReplaceActors = 1; this->Squirt = 0; this->SquirtCompressionLevel = 5; this->SquirtBuffer = vtkUnsignedCharArray::New(); this->UseCompositing = 0; this->RemoteDisplay = 1; this->ReceivedImageFromServer = 1; vtkCallbackCommand *cbc = vtkCallbackCommand::New(); cbc->SetClientData(this); cbc->SetCallback(vtkDesktopDeliveryClientReceiveImageCallback); this->ReceiveImageCallback = cbc; } //---------------------------------------------------------------------------- vtkDesktopDeliveryClient::~vtkDesktopDeliveryClient() { this->SquirtBuffer->Delete(); this->ReceiveImageCallback->Delete(); } //---------------------------------------------------------------------------- void vtkDesktopDeliveryClient::SetUseCompositing(int v) { this->Superclass::SetUseCompositing(v); if (this->RemoteDisplay) { this->SetParallelRendering(v); } } //---------------------------------------------------------------------------- void vtkDesktopDeliveryClient::SetController(vtkMultiProcessController *controller) { vtkDebugMacro("SetController"); if (controller && (controller->GetNumberOfProcesses() != 2)) { vtkErrorMacro("vtkDesktopDelivery needs controller with 2 processes"); return; } this->Superclass::SetController(controller); if (this->Controller) { this->RootProcessId = this->Controller->GetLocalProcessId(); this->ServerProcessId = 1 - this->RootProcessId; } } //---------------------------------------------------------------------------- void vtkDesktopDeliveryClient::SetRenderWindow(vtkRenderWindow *renWin) { //Make sure the renWin has at least one renderer if (renWin) { vtkRendererCollection *rens = renWin->GetRenderers(); if (rens->GetNumberOfItems() < 1) { vtkRenderer *ren = vtkRenderer::New(); renWin->AddRenderer(ren); ren->Delete(); } } this->Superclass::SetRenderWindow(renWin); } //---------------------------------------------------------------------------- // Called only on the client. float vtkDesktopDeliveryClient::GetZBufferValue(int x, int y) { float z; if (this->UseCompositing == 0) { // This could cause a problem between setting this ivar and rendering. // We could always composite, and always consider client z. float *pz; pz = this->RenderWindow->GetZbufferData(x, y, x, y); z = *pz; delete [] pz; return z; } // TODO: // This first int is to check for byte swapping. // int pArg[3]; // pArg[0] = 1; // pArg[1] = x; // pArg[2] = y; // this->ClientController->TriggerRMI(1, (void*)pArg, sizeof(int)*3, // vtkClientCompositeManager::GATHER_Z_RMI_TAG); // this->ClientController->Receive(&z, 1, 1, vtkClientCompositeManager::CLIENT_Z_TAG); z = 1.0; return z; } //---------------------------------------------------------------------------- void vtkDesktopDeliveryClient::CollectWindowInformation(vtkMultiProcessStream& stream) { this->Superclass::CollectWindowInformation(stream); vtkDesktopDeliveryServer::SquirtOptions squirt_options; squirt_options.Enabled = this->Squirt; squirt_options.CompressLevel = this->SquirtCompressionLevel; squirt_options.Save(stream); } //---------------------------------------------------------------------------- void vtkDesktopDeliveryClient::PreRenderProcessing() { // Get remote display flag this->Controller->Receive(&this->RemoteDisplay, 1, this->ServerProcessId, vtkDesktopDeliveryServer::REMOTE_DISPLAY_TAG); if (this->ImageReductionFactor > 1) { // Since we're not really doing parallel rendering, restore the renderer // viewports. vtkRendererCollection *rens = this->GetRenderers(); vtkRenderer *ren; int i; for (rens->InitTraversal(), i = 0; (ren = rens->GetNextItem()); i++) { ren->SetViewport(this->Viewports->GetTuple(i)); } } this->ReceivedImageFromServer = 0; if (!this->SyncRenderWindowRenderers) { // Establish a callback so that the image from the server is retrieved // before we draw renderers that we are not synced with. This will fail if // a non-synced renderer is on a layer equal or less than a synced renderer. vtkRendererCollection *allren = this->RenderWindow->GetRenderers(); vtkCollectionSimpleIterator cookie; vtkRenderer *ren; for (allren->InitTraversal(cookie); (ren = allren->GetNextRenderer(cookie)) != NULL; ) { if (!this->Renderers->IsItemPresent(ren)) { ren->AddObserver(vtkCommand::StartEvent, this->ReceiveImageCallback); } } } // Turn swap buffers off before the render so the end render method has a // chance to add to the back buffer. if (this->UseBackBuffer) { this->RenderWindow->SwapBuffersOff(); } } //---------------------------------------------------------------------------- void vtkDesktopDeliveryClient::PostRenderProcessing() { this->ReceiveImageFromServer(); this->Timer->StopTimer(); this->RenderTime += this->Timer->GetElapsedTime(); if (!this->SyncRenderWindowRenderers) { vtkRendererCollection *allren = this->RenderWindow->GetRenderers(); vtkCollectionSimpleIterator cookie; vtkRenderer *ren; for (allren->InitTraversal(cookie); (ren = allren->GetNextRenderer(cookie)) != NULL; ) { ren->RemoveObservers(vtkCommand::StartEvent, this->ReceiveImageCallback); } } // Swap buffers here. if (this->UseBackBuffer) { this->RenderWindow->SwapBuffersOn(); } this->RenderWindow->Frame(); } //----------------------------------------------------------------------------- void vtkDesktopDeliveryClient::ReceiveImageFromServer() { if (this->ReceivedImageFromServer) return; this->ReceivedImageFromServer = 1; vtkDesktopDeliveryServer::ImageParams ip; int comm_success = this->Controller->Receive((int *)(&ip), vtkDesktopDeliveryServer::IMAGE_PARAMS_SIZE, this->ServerProcessId, vtkDesktopDeliveryServer::IMAGE_PARAMS_TAG); // Adjust render time for actual render on server. this->Timer->StopTimer(); this->RenderTime += this->Timer->GetElapsedTime(); if (comm_success && ip.RemoteDisplay) { // Receive image. this->Timer->StartTimer(); this->ReducedImageSize[0] = ip.ImageSize[0]; this->ReducedImageSize[1] = ip.ImageSize[1]; this->ReducedImage->SetNumberOfComponents(ip.NumberOfComponents); if ( this->FullImageSize[0] == this->ReducedImageSize[0] && this->FullImageSize[1] == this->ReducedImageSize[1] ) { this->FullImage->SetNumberOfComponents(ip.NumberOfComponents); this->FullImage->SetNumberOfTuples( this->FullImageSize[0] * this->FullImageSize[1]); this->FullImageUpToDate = true; this->ReducedImage->SetArray(this->FullImage->GetPointer(0), this->FullImage->GetSize(), 1); } this->ReducedImage->SetNumberOfTuples( this->ReducedImageSize[0] * this->ReducedImageSize[1]); if (ip.SquirtCompressed) { this->SquirtBuffer->SetNumberOfComponents(ip.NumberOfComponents); this->SquirtBuffer->SetNumberOfTuples( ip.BufferSize / ip.NumberOfComponents); this->Controller->Receive(this->SquirtBuffer->GetPointer(0), ip.BufferSize, this->ServerProcessId, vtkDesktopDeliveryServer::IMAGE_TAG); this->SquirtDecompress(this->SquirtBuffer, this->ReducedImage); } else { this->Controller->Receive(this->ReducedImage->GetPointer(0), ip.BufferSize, this->ServerProcessId, vtkDesktopDeliveryServer::IMAGE_TAG); } this->ReducedImageUpToDate = true; this->RenderWindowImageUpToDate = false; this->Timer->StopTimer(); this->TransferTime = this->Timer->GetElapsedTime(); } else { // No remote display means no transfer time. this->TransferTime = 0.0; // Leave the image in the window alone. this->RenderWindowImageUpToDate = true; } vtkDesktopDeliveryServer::TimingMetrics tm; this->Controller->Receive((double *)(&tm), vtkDesktopDeliveryServer::TIMING_METRICS_SIZE, this->ServerProcessId, vtkDesktopDeliveryServer::TIMING_METRICS_TAG); this->RemoteImageProcessingTime = tm.ImageProcessingTime; this->WriteFullImage(); this->Timer->StartTimer(); } //---------------------------------------------------------------------------- void vtkDesktopDeliveryClient::ComputeVisiblePropBounds(vtkRenderer *ren, double bounds[6]) { this->Superclass::ComputeVisiblePropBounds(ren, bounds); if (this->ReplaceActors) { vtkDebugMacro("Replacing actors."); ren->GetActors()->RemoveAllItems(); vtkCubeSource* source = vtkCubeSource::New(); source->SetBounds(bounds); vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); mapper->SetInput(source->GetOutput()); vtkActor* actor = vtkActor::New(); actor->SetMapper(mapper); ren->AddActor(actor); source->Delete(); mapper->Delete(); actor->Delete(); } } //---------------------------------------------------------------------------- void vtkDesktopDeliveryClient::SetImageReductionFactorForUpdateRate(double desiredUpdateRate) { this->Superclass::SetImageReductionFactorForUpdateRate(desiredUpdateRate); if (this->Squirt) { if (this->ImageReductionFactor == 1) { this->SetSquirtCompressionLevel(0); } else { this->SetSquirtCompressionLevel(5); } } } //---------------------------------------------------------------------------- void vtkDesktopDeliveryClient::SquirtDecompress(vtkUnsignedCharArray *in, vtkUnsignedCharArray *out) { vtkSquirtCompressor *compressor = vtkSquirtCompressor::New(); compressor->SetInput(in); compressor->SetOutput(out); compressor->Decompress(); compressor->Delete(); } //---------------------------------------------------------------------------- void vtkDesktopDeliveryClient::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "ServerProcessId: " << this->ServerProcessId << endl; os << indent << "ReplaceActors: " << (this->ReplaceActors ? "On" : "Off") << endl; os << indent << "RemoteDisplay: " << (this->RemoteDisplay ? "On" : "Off") << endl; os << indent << "Squirt: " << (this->Squirt? "On" : "Off") << endl; os << indent << "RemoteImageProcessingTime: " << this->RemoteImageProcessingTime << endl; os << indent << "TransferTime: " << this->TransferTime << endl; os << indent << "SquirtCompressionLevel: " << this->SquirtCompressionLevel << endl; }
32.61461
93
0.588585
matthb2
a758a5063ba258d5644c1b20bec41a65bb72f9cb
7,581
cpp
C++
assignment4/stdlibQueueImplementation/main.cpp
matticoli/CS2303
5399fa2c8bdfcd0620793356dba108ba92f36da3
[ "Apache-2.0" ]
null
null
null
assignment4/stdlibQueueImplementation/main.cpp
matticoli/CS2303
5399fa2c8bdfcd0620793356dba108ba92f36da3
[ "Apache-2.0" ]
null
null
null
assignment4/stdlibQueueImplementation/main.cpp
matticoli/CS2303
5399fa2c8bdfcd0620793356dba108ba92f36da3
[ "Apache-2.0" ]
null
null
null
// // Created by Mikel Matticoli on 2/14/18. // #include <iostream> #include <math.h> #include "Event.h" #include "CustomerEvent.h" #include "SortedEventQueue.h" #include "TellerEvent.h" // Function prototypes for non-class functions int randTime(double min, double max); int runSim(int customerCount, int tellerCount, double simDuration, double avgSvcTime, bool sharedQueue); /** * Parses command line arguments and runs simulation with and without shared queue * @param argc number of args * @param argv string array of args * @return program exit code (==0 for success, !=0 for error) */ int main(int argc, char *argv[]) { // If missing args, print usage if(argc < 5) { std::cout << "Usage:" << std::endl << "./qSim #customers #tellers simulationTime averageServiceTime <seed>" << std::endl; return 1; } // Parse command line args int customerCount = atoi(argv[1]); int tellerCount = atoi(argv[2]); double simDuration = atof(argv[3]); double avgSvcTime = atof(argv[4]); if(argc == 6) { int seed = atoi(argv[5]); srand(seed); } else { srand(time(NULL)); } // If any args are invalid, print usage and >0 warning if(!customerCount || !tellerCount || !simDuration || !avgSvcTime) { std::cout << "Usage:" << std::endl << "./qSim #customers #tellers simulationTime averageServiceTime <seed>" << std::endl << "Note that all required parameters must be greater than 0" << std::endl; return 1; } return runSim(customerCount, tellerCount, simDuration, avgSvcTime, true) + runSim(customerCount, tellerCount, simDuration, avgSvcTime, false); } /** * Run simulation with given parameters * @param customerCount number of customers * @param tellerCount number of tellers * @param simDuration simulation duration (minutes) * @param avgSvcTime average service time (minutes) * @param sharedQueue whether or not to use one shared TellerQueue across all tellers * @return 0 for success, 1 for error */ int runSim(int customerCount, int tellerCount, double simDuration, double avgSvcTime, bool sharedQueue) { std::cout << "\nRunning simulation with " << (sharedQueue ? "shared queue" : "individual queues") << std::endl; int simTime = 0; // Counter to track simulation time (minutes) double avgWaitTime = 0; // Counter to track wait time double customerWaitTimes[customerCount] = { }; // Array to track customer wait times for calculating statistics int customerIndex = 0; // Current index in wait times array SortedEventQueue *eventQueue = new SortedEventQueue(); // If using a shared queue, init a shared queue TellerQueue *customerQueue; if(sharedQueue) customerQueue = new TellerQueue(); // Create arrival events for customers and add them to the event queue for(int i = 0; i < customerCount; i++) { // Invariant: new CustomerEvent will be created and added to event queue CustomerEvent *c = new CustomerEvent(randTime(0, simDuration), CEventType::ARRIVE); eventQueue->add(c); // Invariant: CustomerEvent c has been created and added to eventQueue } // Create teller events at time 0 (bank open) and add them to the event queue for(int i = 0; i < tellerCount; i++) { // Invariant: new TellerEvent will be created and added to event queue // Init with shared queue or new unique queue TellerEvent *t = new TellerEvent(0, (sharedQueue ? customerQueue : new TellerQueue()) ); eventQueue->add(t); // Invariant: TellerEvent c has been created and added to eventQueue } while(simTime < simDuration) { // Process events at head of queue that are timestamped at current time // Invariant: simTime will be incremented by 1 while(eventQueue->peek()->startTime == simTime) { // Invariant: First event in eventQueue will be processed and retasked/deleted Event *e = eventQueue->pop(); if(e->getType() == "Teller") { TellerEvent *t = static_cast<TellerEvent *>(e); // If there's a customer waiting if(t->queue->peek() != nullptr) { // Serve the customer for a random amount of time CustomerEvent *c = t->queue->pop(); int serveTime = randTime(1, avgSvcTime * 2); c->retask(simTime + serveTime, CEventType::SERVED); t->retask(simTime + serveTime); eventQueue->add(t); eventQueue->add(c); } else { //No customers, idle for random amount of time int idleTime = randTime(1, avgSvcTime * 2); t->retask(simTime + idleTime); eventQueue->add(t); } } else if (e->getType() == "Customer") { CustomerEvent *c = static_cast<CustomerEvent *>(e); switch(c->eventType) { case CEventType ::ARRIVE: // Customer arrived, put them in the shortest customer queue // If using shared queue, shortestTellerQueue will always point to the same queue c->retask(simTime, CEventType::WAIT); TellerQueue::shortestTellerQueue->add(c); break; default: case CEventType ::SERVED: // Customer is done being served and can now leave. Save necessary data for stats and delete customerWaitTimes[customerIndex] = simTime - c->arrivalTime; customerIndex++; avgWaitTime += simTime - c->arrivalTime; delete c; break; } } else { std::cerr << "Error, unrecognized event type" << std::endl; return 1; } // Invariant: First event in eventQueue has been processed and retasked/deleted } simTime++; // Invariant: simTime has been incremented by 1 } // Calculate the average avgWaitTime /= customerCount; // Calculate the standard deviation: double stdDv = 0.0; // Calculate sum( (x-xbar)^2 ) for(int i = 0; i < customerCount; i++) { // Invariant stdDv will be incremented by (x-xbar)^2 for x=ith element of customerWaitTimes double dx = (customerWaitTimes[i] - avgWaitTime); stdDv += dx*dx; // Invariant stdDv has been incremented by (x-xbar)^2 for x=ith element of customerWaitTimes } // Divide by x-1 and take root to get s stdDv /= customerCount - 1; stdDv = sqrt(stdDv); std::cout << "Average wait time with " << (sharedQueue ? "shared queue" : "individual queues") << " is " << round(avgWaitTime * 100) / 100 << " minutes" << std::endl; std::cout << "Standard deviation of wait times with " << (sharedQueue ? "shared queue" : "individual queues") << " is " << round(stdDv * 100) / 100 << " minutes" << std::endl; return 0; } /** * Generate random time in minutes between min and max time * @param min lower bound for rand time * @param max upper bound for rand time (exclusive) * @return random time between min and max */ int randTime(double min, double max) { return (int)(rand() * (max - min) / float(RAND_MAX) + min); }
42.351955
116
0.599129
matticoli
a7594f21165947c01912098481f1427ba1c17c09
3,620
cpp
C++
src/main.cpp
parzibyte/escribir-leer-rfid
953a05de25c90741fe585b5f70b61a28e7f78b9f
[ "MIT" ]
null
null
null
src/main.cpp
parzibyte/escribir-leer-rfid
953a05de25c90741fe585b5f70b61a28e7f78b9f
[ "MIT" ]
null
null
null
src/main.cpp
parzibyte/escribir-leer-rfid
953a05de25c90741fe585b5f70b61a28e7f78b9f
[ "MIT" ]
null
null
null
#include <Arduino.h> #include <SPI.h> #include <MFRC522.h> #define LONGITUD_BYTES 18 #define LONGITUD_BYTES_ESCRITURA 16 /* Pines para conectar el lector */ #define RST_PIN D3 #define SS_PIN D4 // Constantes para el ejemplo #define MODO_LECTURA 1 #define MODO_ESCRITURA 2 #define MODO MODO_ESCRITURA MFRC522 lector(SS_PIN, RST_PIN); MFRC522::MIFARE_Key clave; bool leer(char mensaje[LONGITUD_BYTES]) { if (!lector.PICC_IsNewCardPresent()) { return false; } if (!lector.PICC_ReadCardSerial()) { Serial.println("Error leyendo serial"); return false; } byte bloque = 1; // El bloque que leemos byte longitud = LONGITUD_BYTES; byte buferLectura[LONGITUD_BYTES]; MFRC522::StatusCode estado; estado = lector.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, bloque, &clave, &(lector.uid)); if (estado != MFRC522::STATUS_OK) { Serial.println("Error autenticando"); Serial.println(lector.GetStatusCodeName(estado)); return false; } estado = lector.MIFARE_Read(bloque, buferLectura, &longitud); if (estado != MFRC522::STATUS_OK) { Serial.println("Error leyendo bloque"); Serial.println(lector.GetStatusCodeName(estado)); return false; } for (uint8_t i = 0; i < LONGITUD_BYTES - 2; i++) { mensaje[i] = buferLectura[i]; } // Ya pueden retirar la tarjeta lector.PICC_HaltA(); lector.PCD_StopCrypto1(); return true; } bool escribir(char cadena[LONGITUD_BYTES_ESCRITURA]) { if (!lector.PICC_IsNewCardPresent()) { return false; } if (!lector.PICC_ReadCardSerial()) { Serial.println("Error leyendo serial"); return false; } byte bloque = 1; byte buferEscritura[LONGITUD_BYTES_ESCRITURA]; // Copiar cadena al búfer for (uint8_t i = 0; i < LONGITUD_BYTES_ESCRITURA; i++) { buferEscritura[i] = cadena[i]; } MFRC522::StatusCode estado; estado = lector.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, bloque, &clave, &(lector.uid)); if (estado != MFRC522::STATUS_OK) { Serial.println("Error autenticando"); Serial.println(lector.GetStatusCodeName(estado)); return false; } estado = lector.MIFARE_Write(bloque, buferEscritura, LONGITUD_BYTES_ESCRITURA); if (estado != MFRC522::STATUS_OK) { Serial.println("Error escribiendo bloque"); Serial.println(lector.GetStatusCodeName(estado)); return false; } // Ya pueden retirar la tarjeta lector.PICC_HaltA(); lector.PCD_StopCrypto1(); return true; } void setup() { Serial.begin(9600); while (!Serial) { // Esperar serial. Nota: la tarjeta NO HARÁ NADA hasta que haya comunicación Serial (es decir, que el monitor serial sea abierto) // si tú no quieres esto, simplemente elimina todas las llamadas a Serial } // Iniciar lector SPI.begin(); lector.PCD_Init(); // Preparar la clave para leer las tarjetas RFID for (byte i = 0; i < 6; i++) { clave.keyByte[i] = 0xFF; } Serial.println("Iniciado correctamente"); } void loop() { if (MODO == MODO_LECTURA) { char contenidoRfid[LONGITUD_BYTES] = ""; bool lecturaExitosa = leer(contenidoRfid); if (lecturaExitosa) { Serial.println("Lo que hay escrito es:"); Serial.println(contenidoRfid); } else { Serial.println("Error leyendo. Tal vez no hay RFID presente"); } } else if (MODO == MODO_ESCRITURA) { char mensaje[] = "parzibyte"; bool escrituraExitosa = escribir(mensaje); if (escrituraExitosa) { Serial.println("Escrito ok"); } else { Serial.println("Error escribiendo. Tal vez no hay RFID presente"); } } delay(1000); }
24.133333
133
0.68232
parzibyte
a75b573423c78c83e3e12ac848623622f1f028ec
112
cxx
C++
CMake/vtkTestCompilerIsVC6.cxx
Lin1225/vtk_v5.10.0
b54ac74f4716572862365fbff28cd0ecb8d08c3d
[ "BSD-3-Clause" ]
2
2015-07-11T13:30:23.000Z
2017-12-19T05:23:38.000Z
CMake/vtkTestCompilerIsVC6.cxx
Armand0s/homemade_vtk
6bc7b595a4a7f86e8fa969d067360450fa4e0a6a
[ "BSD-3-Clause" ]
null
null
null
CMake/vtkTestCompilerIsVC6.cxx
Armand0s/homemade_vtk
6bc7b595a4a7f86e8fa969d067360450fa4e0a6a
[ "BSD-3-Clause" ]
5
2015-03-23T21:13:19.000Z
2022-01-03T11:15:39.000Z
/* Compile if this is MSVC 6. */ #if defined(_MSC_VER) && (_MSC_VER == 1200) int main() { return 0; } #endif
14
43
0.607143
Lin1225
a7621b00088d2de9f2ecc9f4af940f5537291cb5
501
cpp
C++
src/base/pch_std.cpp
dufferprog/verbexx
bfc3c30ad2ca6c246c8f88405b386475278f9ecc
[ "MIT" ]
null
null
null
src/base/pch_std.cpp
dufferprog/verbexx
bfc3c30ad2ca6c246c8f88405b386475278f9ecc
[ "MIT" ]
1
2018-09-14T00:07:27.000Z
2018-09-14T00:07:27.000Z
src/base/pch_std.cpp
dufferprog/verbexx
bfc3c30ad2ca6c246c8f88405b386475278f9ecc
[ "MIT" ]
1
2018-09-13T23:43:12.000Z
2018-09-13T23:43:12.000Z
// pch_std.cpp ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // pch_std.cpp -- pre-compiled headers -- non-clr compiles // =========== ---------------------------------------- // // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include "h__include.h" #pragma hdrstop("../pch/pch_std.pch")
33.4
135
0.191617
dufferprog
a7639aa9219011d216e1f621411328d10d3cf144
5,922
cpp
C++
samples/Events/Events.cpp
amaiorano/Vulkan-Hpp
3c481ba37409a71d92b6f1e93386b5031921453b
[ "Apache-2.0" ]
2
2018-03-26T10:49:16.000Z
2019-07-25T12:08:32.000Z
samples/Events/Events.cpp
amaiorano/Vulkan-Hpp
3c481ba37409a71d92b6f1e93386b5031921453b
[ "Apache-2.0" ]
null
null
null
samples/Events/Events.cpp
amaiorano/Vulkan-Hpp
3c481ba37409a71d92b6f1e93386b5031921453b
[ "Apache-2.0" ]
1
2020-01-30T07:25:25.000Z
2020-01-30T07:25:25.000Z
// Copyright(c) 2019, NVIDIA CORPORATION. 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. // // VulkanHpp Samples : Events // Use basic events #include "../utils/utils.hpp" #include "vulkan/vulkan.hpp" #include <iostream> static char const * AppName = "Events"; static char const * EngineName = "Vulkan.hpp"; int main( int /*argc*/, char ** /*argv*/ ) { try { vk::Instance instance = vk::su::createInstance( AppName, EngineName, {}, vk::su::getInstanceExtensions() ); #if !defined( NDEBUG ) vk::DebugUtilsMessengerEXT debugUtilsMessenger = instance.createDebugUtilsMessengerEXT( vk::su::makeDebugUtilsMessengerCreateInfoEXT() ); #endif vk::PhysicalDevice physicalDevice = instance.enumeratePhysicalDevices().front(); uint32_t graphicsQueueFamilyIndex = vk::su::findGraphicsQueueFamilyIndex( physicalDevice.getQueueFamilyProperties() ); vk::Device device = vk::su::createDevice( physicalDevice, graphicsQueueFamilyIndex ); vk::CommandPool commandPool = vk::su::createCommandPool( device, graphicsQueueFamilyIndex ); vk::CommandBuffer commandBuffer = device.allocateCommandBuffers( vk::CommandBufferAllocateInfo( commandPool, vk::CommandBufferLevel::ePrimary, 1 ) ) .front(); vk::Queue graphicsQueue = device.getQueue( graphicsQueueFamilyIndex, 0 ); /* VULKAN_KEY_START */ // Start with a trivial command buffer and make sure fence wait doesn't time out commandBuffer.begin( vk::CommandBufferBeginInfo( vk::CommandBufferUsageFlags() ) ); commandBuffer.setViewport( 0, vk::Viewport( 0.0f, 0.0f, 10.0f, 10.0f, 0.0f, 1.0f ) ); commandBuffer.end(); vk::Fence fence = device.createFence( vk::FenceCreateInfo() ); vk::SubmitInfo submitInfo( {}, {}, commandBuffer ); graphicsQueue.submit( submitInfo, fence ); // Make sure timeout is long enough for a simple command buffer without waiting for an event vk::Result result; int timeouts = -1; do { result = device.waitForFences( fence, true, vk::su::FenceTimeout ); timeouts++; } while ( result == vk::Result::eTimeout ); assert( result == vk::Result::eSuccess ); if ( timeouts != 0 ) { std::cout << "Unsuitable timeout value, exiting\n"; exit( -1 ); } // Now create an event and wait for it on the GPU vk::Event event = device.createEvent( vk::EventCreateInfo( vk::EventCreateFlags() ) ); commandBuffer.reset( vk::CommandBufferResetFlags() ); commandBuffer.begin( vk::CommandBufferBeginInfo() ); commandBuffer.waitEvents( event, vk::PipelineStageFlagBits::eHost, vk::PipelineStageFlagBits::eBottomOfPipe, nullptr, nullptr, nullptr ); commandBuffer.end(); device.resetFences( fence ); // Note that stepping through this code in the debugger is a bad idea because the GPU can TDR waiting for the event. // Execute the code from vk::Queue::submit() through vk::Device::setEvent() without breakpoints graphicsQueue.submit( submitInfo, fence ); // We should timeout waiting for the fence because the GPU should be waiting on the event result = device.waitForFences( fence, true, vk::su::FenceTimeout ); if ( result != vk::Result::eTimeout ) { std::cout << "Didn't get expected timeout in vk::Device::waitForFences, exiting\n"; exit( -1 ); } // Set the event from the CPU and wait for the fence. // This should succeed since we set the event device.setEvent( event ); do { result = device.waitForFences( fence, true, vk::su::FenceTimeout ); } while ( result == vk::Result::eTimeout ); assert( result == vk::Result::eSuccess ); commandBuffer.reset( {} ); device.resetFences( fence ); device.resetEvent( event ); // Now set the event from the GPU and wait on the CPU commandBuffer.begin( vk::CommandBufferBeginInfo() ); commandBuffer.setEvent( event, vk::PipelineStageFlagBits::eBottomOfPipe ); commandBuffer.end(); // Look for the event on the CPU. It should be vk::Result::eEventReset since we haven't sent the command buffer yet. result = device.getEventStatus( event ); assert( result == vk::Result::eEventReset ); // Send the command buffer and loop waiting for the event graphicsQueue.submit( submitInfo, fence ); int polls = 0; do { result = device.getEventStatus( event ); polls++; } while ( result != vk::Result::eEventSet ); printf( "%d polls to find the event set\n", polls ); do { result = device.waitForFences( fence, true, vk::su::FenceTimeout ); } while ( result == vk::Result::eTimeout ); assert( result == vk::Result::eSuccess ); device.destroyEvent( event ); device.destroyFence( fence ); /* VULKAN_KEY_END */ device.freeCommandBuffers( commandPool, commandBuffer ); device.destroyCommandPool( commandPool ); device.destroy(); #if !defined( NDEBUG ) instance.destroyDebugUtilsMessengerEXT( debugUtilsMessenger ); #endif instance.destroy(); } catch ( vk::SystemError & err ) { std::cout << "vk::SystemError: " << err.what() << std::endl; exit( -1 ); } catch ( std::exception & err ) { std::cout << "std::exception: " << err.what() << std::endl; exit( -1 ); } catch ( ... ) { std::cout << "unknown error\n"; exit( -1 ); } return 0; }
35.461078
120
0.670719
amaiorano
a765c886e7a183f57b827d06a8cc1c5343658dfa
1,367
cc
C++
src/schema/test/display_name_test.cc
biswajit-mandal/contrail-controller
80c4a7e8515f7296b18ba4c21a439bd3daefcc4a
[ "Apache-2.0" ]
5
2015-01-08T17:34:41.000Z
2017-09-28T16:00:25.000Z
src/schema/test/display_name_test.cc
biswajit-mandal/contrail-controller
80c4a7e8515f7296b18ba4c21a439bd3daefcc4a
[ "Apache-2.0" ]
2
2018-12-04T02:20:52.000Z
2018-12-22T06:16:30.000Z
src/schema/test/display_name_test.cc
biswajit-mandal/contrail-controller
80c4a7e8515f7296b18ba4c21a439bd3daefcc4a
[ "Apache-2.0" ]
18
2017-01-12T09:28:44.000Z
2019-04-18T20:47:42.000Z
/* * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved. */ #include "schema/vnc_cfg_types.h" #include <pugixml/pugixml.hpp> #include "base/logging.h" #include "ifmap/ifmap_server_parser.h" #include "ifmap/ifmap_server_table.h" #include "testing/gunit.h" using namespace std; class DisplayNameTest : public ::testing::Test { protected: virtual void SetUp() { xparser_ = IFMapServerParser::GetInstance("vnc_cfg"); vnc_cfg_ParserInit(xparser_); } pugi::xml_document xdoc_; IFMapServerParser *xparser_; }; TEST_F(DisplayNameTest, Load) { pugi::xml_parse_result result = xdoc_.load_file("controller/src/schema/testdata/display_name.xml"); EXPECT_TRUE(result); IFMapServerParser::RequestList requests; xparser_->ParseResults(xdoc_, &requests); EXPECT_EQ(1, requests.size()); DBRequest *request = requests.front(); IFMapServerTable::RequestData *data = static_cast<IFMapServerTable::RequestData *>(request->data.get()); ASSERT_TRUE(data); autogen::VirtualNetwork::StringProperty *display_name = static_cast<autogen::VirtualNetwork::StringProperty *>(data->content.get()); EXPECT_EQ("foo", display_name->data); } int main(int argc, char **argv) { LoggingInit(); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
26.288462
82
0.697879
biswajit-mandal
a7671f70f4843dc4e7cc6c6e9f7638ecc9ec8d1a
800
cpp
C++
MozJpegGUI/MozJpegGUI/GetLastErrorToString.cpp
nibasya/MozJpegGUI
26e37f4c0c028800142ebeaa3470f3cc2a228475
[ "IJG", "Unlicense" ]
3
2021-06-05T11:43:44.000Z
2022-03-19T04:03:58.000Z
MozJpegGUI/MozJpegGUI/GetLastErrorToString.cpp
nibasya/MozJpegGUI
26e37f4c0c028800142ebeaa3470f3cc2a228475
[ "IJG", "Unlicense" ]
null
null
null
MozJpegGUI/MozJpegGUI/GetLastErrorToString.cpp
nibasya/MozJpegGUI
26e37f4c0c028800142ebeaa3470f3cc2a228475
[ "IJG", "Unlicense" ]
2
2020-07-20T06:04:45.000Z
2022-03-19T04:03:57.000Z
#include "pch.h" // enable for visual studio version >= 2019 // #include "stdafx.h" // enable for visual studio version < 2019 #include "GetLastErrorToString.h" GetLastErrorToString::operator CString() { CreateMsg(); return m_msg; } GetLastErrorToString::operator LPCTSTR() { CreateMsg(); return (LPCTSTR)m_msg; } void GetLastErrorToString::CreateMsg() { LPTSTR *buff; m_ID = GetLastError(); FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, m_ID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&buff, 10, NULL); m_msg.Format(_T("%s"), (TCHAR*)buff); LocalFree(buff); #ifdef UNICODE _RPTW2(_CRT_WARN, _T("Error ID: %d Msg: %s"), m_ID, m_msg); #else _RPT2(_CRT_WARN, _T("Error ID: %d Msg: %s"), m_ID, m_msg); #endif }
26.666667
188
0.73
nibasya
a767296d3fbc38c294fc63e71db83bfc2f2ab623
361
cpp
C++
sha3test/main.cpp
ericosur/myqt
e96f77f99442c44e51a1dbe1ee93edfa09b3db0f
[ "MIT" ]
null
null
null
sha3test/main.cpp
ericosur/myqt
e96f77f99442c44e51a1dbe1ee93edfa09b3db0f
[ "MIT" ]
null
null
null
sha3test/main.cpp
ericosur/myqt
e96f77f99442c44e51a1dbe1ee93edfa09b3db0f
[ "MIT" ]
null
null
null
#include <QCoreApplication> #include <QString> #include <QDateTime> #include <QDebug> #include "core.h" #include "commonutil.h" int main(int argc, char** argv) { // Q_UNUSED(argc); // Q_UNUSED(argv); // qInstallMessageHandler(myMessageOutput); QCoreApplication app(argc, argv); Core::getInstance()->start(); return app.exec(); }
17.190476
44
0.66205
ericosur
a767557abd1d96e09f4ad2f9a0fdfe9ada561e30
545
cpp
C++
multiview/multiview_cpp/src/testcases/optimization/kz-filter_tc.cpp
prcvlabs/multiview
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
[ "Apache-2.0" ]
5
2021-09-03T23:12:08.000Z
2022-03-04T21:43:32.000Z
multiview/multiview_cpp/src/testcases/optimization/kz-filter_tc.cpp
prcvlabs/multiview
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
[ "Apache-2.0" ]
3
2021-09-08T02:57:46.000Z
2022-02-26T05:33:02.000Z
multiview/multiview_cpp/src/testcases/optimization/kz-filter_tc.cpp
prcvlabs/multiview
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
[ "Apache-2.0" ]
2
2021-09-26T03:14:40.000Z
2022-01-26T06:42:52.000Z
#define CATCH_CONFIG_PREFIX_ALL #include <algorithm> #include <iostream> #include <numeric> #include <vector> #include "perceive/contrib/catch.hpp" #include "perceive/optimization/kz-filter.hpp" namespace perceive { // ------------------------------------------------------------------- TEST_CASE // CATCH_TEST_CASE("KzFilter0", "[kz-filter-0]") { CATCH_SECTION("kz-filter-0") { // INFO("HEllo"); // KzFilter filter; // filter.init(5, 4); // cout << str(filter) << endl; } } } // namespace perceive
17.580645
80
0.559633
prcvlabs
a767b58cea305262300f3e21ce74318c33292bc1
446
cpp
C++
src/qak_plugin.cpp
Larpon/Qak
a91cafddaa77dcdaeaff1bb1e8b8e4436acee67a
[ "MIT" ]
23
2017-01-06T15:31:13.000Z
2021-11-21T13:58:19.000Z
src/qak_plugin.cpp
Larpon/Qak
a91cafddaa77dcdaeaff1bb1e8b8e4436acee67a
[ "MIT" ]
3
2021-09-08T09:37:48.000Z
2022-01-19T13:53:20.000Z
src/qak_plugin.cpp
Larpon/Qak
a91cafddaa77dcdaeaff1bb1e8b8e4436acee67a
[ "MIT" ]
3
2018-01-16T23:57:51.000Z
2019-11-02T07:44:09.000Z
#include "qak_plugin.h" #include "maskedmousearea.h" #include "propertytoggle.h" #include "resource.h" #include "store.h" #include <qqml.h> void QakPlugin::registerTypes(const char *uri) { // @uri Qak qmlRegisterType<MaskedMouseArea>(uri, 1, 0, "MaskedMouseArea"); qmlRegisterType<Resource>(uri, 1, 0, "Resource"); qmlRegisterType<Store>(uri, 1, 0, "Store"); qmlRegisterType<PropertyToggle>(uri, 1, 0, "PropertyToggle"); }
24.777778
67
0.699552
Larpon
a768bf9793927b924e767bd3c410daa48bd5adb3
10,237
cpp
C++
test/entt/signal/sigh.cpp
Husenap/entt
5ffa14a7af519cdad646a359572af080cd7582db
[ "MIT" ]
1
2021-04-23T17:31:59.000Z
2021-04-23T17:31:59.000Z
test/entt/signal/sigh.cpp
Husenap/entt
5ffa14a7af519cdad646a359572af080cd7582db
[ "MIT" ]
null
null
null
test/entt/signal/sigh.cpp
Husenap/entt
5ffa14a7af519cdad646a359572af080cd7582db
[ "MIT" ]
4
2021-09-06T20:44:47.000Z
2021-10-04T22:05:12.000Z
#include <utility> #include <vector> #include <gtest/gtest.h> #include <entt/signal/sigh.hpp> struct sigh_listener { static void f(int &v) { v = 42; } bool g(int) { k = !k; return true; } bool h(const int &) { return k; } void i() {} // useless definition just because msvc does weird things if both are empty void l() { k = k && k; } bool k{false}; }; struct before_after { void add(int v) { value += v; } void mul(int v) { value *= v; } static void static_add(int v) { before_after::value += v; } static void static_mul(before_after &instance, int v) { instance.value *= v; } static inline int value{}; }; struct SigH: ::testing::Test { void SetUp() override { before_after::value = 0; } }; struct const_nonconst_noexcept { void f() { ++cnt; } void g() noexcept { ++cnt; } void h() const { ++cnt; } void i() const noexcept { ++cnt; } mutable int cnt{0}; }; TEST_F(SigH, Lifetime) { using signal = entt::sigh<void(void)>; ASSERT_NO_FATAL_FAILURE(signal{}); signal src{}, other{}; ASSERT_NO_FATAL_FAILURE(signal{src}); ASSERT_NO_FATAL_FAILURE(signal{std::move(other)}); ASSERT_NO_FATAL_FAILURE(src = other); ASSERT_NO_FATAL_FAILURE(src = std::move(other)); ASSERT_NO_FATAL_FAILURE(delete new signal{}); } TEST_F(SigH, Clear) { entt::sigh<void(int &)> sigh; entt::sink sink{sigh}; sink.connect<&sigh_listener::f>(); ASSERT_FALSE(sink.empty()); ASSERT_FALSE(sigh.empty()); sink.disconnect(static_cast<const void *>(nullptr)); ASSERT_FALSE(sink.empty()); ASSERT_FALSE(sigh.empty()); sink.disconnect(); ASSERT_TRUE(sink.empty()); ASSERT_TRUE(sigh.empty()); } TEST_F(SigH, Swap) { entt::sigh<void(int &)> sigh1; entt::sigh<void(int &)> sigh2; entt::sink sink1{sigh1}; entt::sink sink2{sigh2}; sink1.connect<&sigh_listener::f>(); ASSERT_FALSE(sink1.empty()); ASSERT_TRUE(sink2.empty()); ASSERT_FALSE(sigh1.empty()); ASSERT_TRUE(sigh2.empty()); std::swap(sigh1, sigh2); ASSERT_TRUE(sink1.empty()); ASSERT_FALSE(sink2.empty()); ASSERT_TRUE(sigh1.empty()); ASSERT_FALSE(sigh2.empty()); } TEST_F(SigH, Functions) { entt::sigh<void(int &)> sigh; entt::sink sink{sigh}; int v = 0; sink.connect<&sigh_listener::f>(); sigh.publish(v); ASSERT_FALSE(sigh.empty()); ASSERT_EQ(1u, sigh.size()); ASSERT_EQ(42, v); v = 0; sink.disconnect<&sigh_listener::f>(); sigh.publish(v); ASSERT_TRUE(sigh.empty()); ASSERT_EQ(0u, sigh.size()); ASSERT_EQ(v, 0); } TEST_F(SigH, FunctionsWithPayload) { entt::sigh<void()> sigh; entt::sink sink{sigh}; int v = 0; sink.connect<&sigh_listener::f>(v); sigh.publish(); ASSERT_FALSE(sigh.empty()); ASSERT_EQ(1u, sigh.size()); ASSERT_EQ(42, v); v = 0; sink.disconnect<&sigh_listener::f>(v); sigh.publish(); ASSERT_TRUE(sigh.empty()); ASSERT_EQ(0u, sigh.size()); ASSERT_EQ(v, 0); sink.connect<&sigh_listener::f>(v); sink.disconnect(v); sigh.publish(); ASSERT_EQ(v, 0); } TEST_F(SigH, Members) { sigh_listener l1, l2; entt::sigh<bool(int)> sigh; entt::sink sink{sigh}; sink.connect<&sigh_listener::g>(l1); sigh.publish(42); ASSERT_TRUE(l1.k); ASSERT_FALSE(sigh.empty()); ASSERT_EQ(1u, sigh.size()); sink.disconnect<&sigh_listener::g>(l1); sigh.publish(42); ASSERT_TRUE(l1.k); ASSERT_TRUE(sigh.empty()); ASSERT_EQ(0u, sigh.size()); sink.connect<&sigh_listener::g>(&l1); sink.connect<&sigh_listener::h>(l2); ASSERT_FALSE(sigh.empty()); ASSERT_EQ(2u, sigh.size()); sink.disconnect(static_cast<const void *>(nullptr)); ASSERT_FALSE(sigh.empty()); ASSERT_EQ(2u, sigh.size()); sink.disconnect(&l1); ASSERT_FALSE(sigh.empty()); ASSERT_EQ(1u, sigh.size()); } TEST_F(SigH, Collector) { sigh_listener listener; entt::sigh<bool(int)> sigh; entt::sink sink{sigh}; int cnt = 0; sink.connect<&sigh_listener::g>(&listener); sink.connect<&sigh_listener::h>(listener); listener.k = true; sigh.collect([&listener, &cnt](bool value) { ASSERT_TRUE(value); listener.k = true; ++cnt; }, 42); ASSERT_FALSE(sigh.empty()); ASSERT_EQ(cnt, 2); cnt = 0; sigh.collect([&cnt](bool value) { // gtest and its macro hell are sometimes really annoying... [](auto v) { ASSERT_TRUE(v); }(value); ++cnt; return true; }, 42); ASSERT_EQ(cnt, 1); } TEST_F(SigH, CollectorVoid) { sigh_listener listener; entt::sigh<void(int)> sigh; entt::sink sink{sigh}; int cnt = 0; sink.connect<&sigh_listener::g>(&listener); sink.connect<&sigh_listener::h>(listener); sigh.collect([&cnt]() { ++cnt; }, 42); ASSERT_FALSE(sigh.empty()); ASSERT_EQ(cnt, 2); cnt = 0; sigh.collect([&cnt]() { ++cnt; return true; }, 42); ASSERT_EQ(cnt, 1); } TEST_F(SigH, Connection) { entt::sigh<void(int &)> sigh; entt::sink sink{sigh}; int v = 0; auto conn = sink.connect<&sigh_listener::f>(); sigh.publish(v); ASSERT_FALSE(sigh.empty()); ASSERT_TRUE(conn); ASSERT_EQ(42, v); v = 0; conn.release(); sigh.publish(v); ASSERT_TRUE(sigh.empty()); ASSERT_FALSE(conn); ASSERT_EQ(0, v); } TEST_F(SigH, ScopedConnection) { sigh_listener listener; entt::sigh<void(int)> sigh; entt::sink sink{sigh}; { ASSERT_FALSE(listener.k); entt::scoped_connection conn = sink.connect<&sigh_listener::g>(listener); sigh.publish(42); ASSERT_FALSE(sigh.empty()); ASSERT_TRUE(listener.k); ASSERT_TRUE(conn); } sigh.publish(42); ASSERT_TRUE(sigh.empty()); ASSERT_TRUE(listener.k); } TEST_F(SigH, ScopedConnectionConstructorsAndOperators) { sigh_listener listener; entt::sigh<void(int)> sigh; entt::sink sink{sigh}; { entt::scoped_connection inner{}; ASSERT_TRUE(sigh.empty()); ASSERT_FALSE(listener.k); ASSERT_FALSE(inner); inner = sink.connect<&sigh_listener::g>(listener); sigh.publish(42); ASSERT_FALSE(sigh.empty()); ASSERT_TRUE(listener.k); ASSERT_TRUE(inner); inner.release(); ASSERT_TRUE(sigh.empty()); ASSERT_FALSE(inner); auto basic = sink.connect<&sigh_listener::g>(listener); inner = std::as_const(basic); sigh.publish(42); ASSERT_FALSE(sigh.empty()); ASSERT_FALSE(listener.k); ASSERT_TRUE(inner); } sigh.publish(42); ASSERT_TRUE(sigh.empty()); ASSERT_FALSE(listener.k); } TEST_F(SigH, ConstNonConstNoExcept) { entt::sigh<void()> sigh; entt::sink sink{sigh}; const_nonconst_noexcept functor; const const_nonconst_noexcept cfunctor; sink.connect<&const_nonconst_noexcept::f>(functor); sink.connect<&const_nonconst_noexcept::g>(&functor); sink.connect<&const_nonconst_noexcept::h>(cfunctor); sink.connect<&const_nonconst_noexcept::i>(&cfunctor); sigh.publish(); ASSERT_EQ(functor.cnt, 2); ASSERT_EQ(cfunctor.cnt, 2); sink.disconnect<&const_nonconst_noexcept::f>(functor); sink.disconnect<&const_nonconst_noexcept::g>(&functor); sink.disconnect<&const_nonconst_noexcept::h>(cfunctor); sink.disconnect<&const_nonconst_noexcept::i>(&cfunctor); sigh.publish(); ASSERT_EQ(functor.cnt, 2); ASSERT_EQ(cfunctor.cnt, 2); } TEST_F(SigH, BeforeFunction) { entt::sigh<void(int)> sigh; entt::sink sink{sigh}; before_after functor; sink.connect<&before_after::add>(functor); sink.connect<&before_after::static_add>(); sink.before<&before_after::static_add>().connect<&before_after::mul>(functor); sigh.publish(2); ASSERT_EQ(functor.value, 6); } TEST_F(SigH, BeforeMemberFunction) { entt::sigh<void(int)> sigh; entt::sink sink{sigh}; before_after functor; sink.connect<&before_after::static_add>(); sink.connect<&before_after::add>(functor); sink.before<&before_after::add>(functor).connect<&before_after::mul>(functor); sigh.publish(2); ASSERT_EQ(functor.value, 6); } TEST_F(SigH, BeforeFunctionWithPayload) { entt::sigh<void(int)> sigh; entt::sink sink{sigh}; before_after functor; sink.connect<&before_after::static_add>(); sink.connect<&before_after::static_mul>(functor); sink.before<&before_after::static_mul>(functor).connect<&before_after::add>(functor); sigh.publish(2); ASSERT_EQ(functor.value, 8); } TEST_F(SigH, BeforeInstanceOrPayload) { entt::sigh<void(int)> sigh; entt::sink sink{sigh}; before_after functor; sink.connect<&before_after::static_mul>(functor); sink.connect<&before_after::add>(functor); sink.before(functor).connect<&before_after::static_add>(); sigh.publish(2); ASSERT_EQ(functor.value, 6); } TEST_F(SigH, BeforeAnythingElse) { entt::sigh<void(int)> sigh; entt::sink sink{sigh}; before_after functor; sink.connect<&before_after::add>(functor); sink.before().connect<&before_after::mul>(functor); sigh.publish(2); ASSERT_EQ(functor.value, 2); } TEST_F(SigH, BeforeListenerNotPresent) { entt::sigh<void(int)> sigh; entt::sink sink{sigh}; before_after functor; sink.connect<&before_after::mul>(functor); sink.before<&before_after::add>(&functor).connect<&before_after::add>(functor); sigh.publish(2); ASSERT_EQ(functor.value, 2); } TEST_F(SigH, UnboundDataMember) { sigh_listener listener; entt::sigh<bool &(sigh_listener &)> sigh; entt::sink sink{sigh}; ASSERT_FALSE(listener.k); sink.connect<&sigh_listener::k>(); sigh.collect([](bool &value) { value = !value; }, listener); ASSERT_TRUE(listener.k); } TEST_F(SigH, UnboundMemberFunction) { sigh_listener listener; entt::sigh<void(sigh_listener *, int)> sigh; entt::sink sink{sigh}; ASSERT_FALSE(listener.k); sink.connect<&sigh_listener::g>(); sigh.publish(&listener, 42); ASSERT_TRUE(listener.k); }
23.004494
89
0.631533
Husenap
a76921d32cde3d80c4a94502831a99a2d2ba5c9b
9,980
cpp
C++
src/xalanc/XercesParserLiaison/Deprecated/FormatterToDeprecatedXercesDOM.cpp
ulisesten/xalanc
a722de08e61ce66965c4a828242f7d1250950621
[ "Apache-2.0" ]
24
2015-07-29T22:49:17.000Z
2022-03-25T10:14:17.000Z
src/xalanc/XercesParserLiaison/Deprecated/FormatterToDeprecatedXercesDOM.cpp
ulisesten/xalanc
a722de08e61ce66965c4a828242f7d1250950621
[ "Apache-2.0" ]
14
2019-05-10T16:25:50.000Z
2021-11-24T18:04:47.000Z
src/xalanc/XercesParserLiaison/Deprecated/FormatterToDeprecatedXercesDOM.cpp
ulisesten/xalanc
a722de08e61ce66965c4a828242f7d1250950621
[ "Apache-2.0" ]
28
2015-04-20T15:50:51.000Z
2022-01-26T14:56:55.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(XALAN_BUILD_DEPRECATED_DOM_BRIDGE) // Class header file. #include "FormatterToDeprecatedXercesDOM.hpp" #include <cassert> #include <xercesc/sax/AttributeList.hpp> #if XERCES_VERSION_MAJOR >= 2 #include <xercesc/dom/deprecated/DOM_CDATASection.hpp> #include <xercesc/dom/deprecated/DOM_Comment.hpp> #include <xercesc/dom/deprecated/DOM_EntityReference.hpp> #include <xercesc/dom/deprecated/DOM_ProcessingInstruction.hpp> #include <xercesc/dom/deprecated/DOM_Text.hpp> #else #include <xercesc/dom/DOM_CDATASection.hpp> #include <xercesc/dom/DOM_Comment.hpp> #include <xercesc/dom/DOM_EntityReference.hpp> #include <xercesc/dom/DOM_ProcessingInstruction.hpp> #include <xercesc/dom/DOM_Text.hpp> #endif #include <xalanc/XalanDOM/XalanDOMString.hpp> #include <xalanc/PlatformSupport/DOMStringHelper.hpp> #include <xalanc/PlatformSupport/PrefixResolver.hpp> #include <xalanc/DOMSupport/DOMServices.hpp> #include <xalanc/XercesParserLiaison/XercesDOMException.hpp> namespace XALAN_CPP_NAMESPACE { const XalanDOMString FormatterToDeprecatedXercesDOM::s_emptyString; FormatterToDeprecatedXercesDOM::FormatterToDeprecatedXercesDOM( DOM_Document_Type& doc, DOM_DocumentFragmentType& docFrag, DOM_ElementType& currentElement) : FormatterListener(OUTPUT_METHOD_DOM), m_doc(doc), m_docFrag(docFrag), m_currentElem(currentElement), m_elemStack(), m_buffer(), m_textBuffer() { assert(m_doc != 0 && m_docFrag != 0); } FormatterToDeprecatedXercesDOM::FormatterToDeprecatedXercesDOM( DOM_Document_Type& doc, DOM_ElementType& elem) : FormatterListener(OUTPUT_METHOD_DOM), m_doc(doc), m_docFrag(), m_currentElem(elem), m_elemStack(), m_buffer(), m_textBuffer() { assert(m_doc != 0); } FormatterToDeprecatedXercesDOM::FormatterToDeprecatedXercesDOM( DOM_Document_Type& doc) : FormatterListener(OUTPUT_METHOD_DOM), m_doc(doc), m_docFrag(), m_currentElem(), m_elemStack(), m_buffer(), m_textBuffer() { assert(m_doc != 0); } FormatterToDeprecatedXercesDOM::~FormatterToDeprecatedXercesDOM() { } void FormatterToDeprecatedXercesDOM::setDocumentLocator(const Locator* const /* locator */) { // No action for the moment. } void FormatterToDeprecatedXercesDOM::startDocument() { // No action for the moment. } void FormatterToDeprecatedXercesDOM::endDocument() { // No action for the moment. } void FormatterToDeprecatedXercesDOM::startElement( const XMLCh* const name, AttributeListType& attrs) { try { processAccumulatedText(); DOM_ElementType elem = createElement(name, attrs); append(elem); m_elemStack.push_back(m_currentElem); m_currentElem = elem; } catch(const xercesc::DOMException& theException) { throw XercesDOMException(theException); } } void FormatterToDeprecatedXercesDOM::endElement(const XMLCh* const /* name */) { try { processAccumulatedText(); if(m_elemStack.empty() == false) { m_currentElem = m_elemStack.back(); m_elemStack.pop_back(); } else { m_currentElem = 0; } } catch(const xercesc::DOMException& theException) { throw XercesDOMException(theException); } } void FormatterToDeprecatedXercesDOM::characters( const XMLCh* const chars, const unsigned int length) { m_textBuffer.append(chars, length); } void FormatterToDeprecatedXercesDOM::charactersRaw( const XMLCh* const chars, const unsigned int length) { try { processAccumulatedText(); cdata(chars, length); } catch(const xercesc::DOMException& theException) { throw XercesDOMException(theException); } } void FormatterToDeprecatedXercesDOM::entityReference(const XMLCh* const name) { try { processAccumulatedText(); DOM_EntityReferenceType theXercesNode = m_doc.createEntityReference(name); assert(theXercesNode.isNull() == false); append(theXercesNode); } catch(const xercesc::DOMException& theException) { throw XercesDOMException(theException); } } void FormatterToDeprecatedXercesDOM::ignorableWhitespace( const XMLCh* const chars, const unsigned int length) { try { processAccumulatedText(); assign(m_buffer, chars, length); DOM_TextType theXercesNode = m_doc.createTextNode(m_buffer.c_str()); assert(theXercesNode.isNull() == false); append(theXercesNode); } catch(const xercesc::DOMException& theException) { throw XercesDOMException(theException); } } void FormatterToDeprecatedXercesDOM::processingInstruction( const XMLCh* const target, const XMLCh* const data) { try { processAccumulatedText(); DOM_ProcessingInstructionType theXercesNode = m_doc.createProcessingInstruction(target, data); assert(theXercesNode.isNull() == false); append(theXercesNode); } catch(const xercesc::DOMException& theException) { throw XercesDOMException(theException); } } void FormatterToDeprecatedXercesDOM::resetDocument() { } void FormatterToDeprecatedXercesDOM::comment(const XMLCh* const data) { try { processAccumulatedText(); DOM_CommentType theXercesNode = m_doc.createComment(data); assert(theXercesNode.isNull() == false); append(theXercesNode); } catch(const xercesc::DOMException& theException) { throw XercesDOMException(theException); } } void FormatterToDeprecatedXercesDOM::cdata( const XMLCh* const ch, const unsigned int length) { try { processAccumulatedText(); assign(m_buffer, ch, length); DOM_CDATASectionType theXercesNode = m_doc.createCDATASection(m_buffer.c_str()); assert(theXercesNode.isNull() == false); append(theXercesNode); } catch(const xercesc::DOMException& theException) { throw XercesDOMException(theException); } } void FormatterToDeprecatedXercesDOM::append(DOM_NodeType &newNode) { assert(newNode != 0); if(m_currentElem.isNull() == false) { m_currentElem.appendChild(newNode); } else if(m_docFrag.isNull() == false) { m_docFrag.appendChild(newNode); } else { m_doc.appendChild(newNode); } } DOM_ElementType FormatterToDeprecatedXercesDOM::createElement( const XalanDOMChar* theElementName, AttributeListType& attrs) { DOM_ElementType theElement; if (m_prefixResolver == 0) { theElement = m_doc.createElement(theElementName); addAttributes(theElement, attrs); } else { // Check for the namespace... const XalanDOMString* const theNamespace = DOMServices::getNamespaceForPrefix(theElementName, *m_prefixResolver, false , m_buffer); if (theNamespace == 0 || length(*theNamespace) == 0) { theElement = m_doc.createElement(theElementName); } else { theElement = m_doc.createElementNS(theNamespace->c_str(), theElementName); } addAttributes(theElement, attrs); } return theElement; } void FormatterToDeprecatedXercesDOM::addAttributes( DOM_ElementType& theElement, AttributeListType& attrs) { const unsigned int nAtts = attrs.getLength(); if (m_prefixResolver == 0) { for(unsigned int i = 0; i < nAtts; i++) { theElement.setAttribute(attrs.getName(i), attrs.getValue(i)); } } else { for(unsigned int i = 0; i < nAtts; i++) { const XalanDOMChar* const theName = attrs.getName(i); assert(theName != 0); // Check for the namespace... const XalanDOMString* const theNamespace = DOMServices::getNamespaceForPrefix(theName, *m_prefixResolver, true, m_buffer); if (theNamespace == 0 || length(*theNamespace) == 0) { theElement.setAttribute(theName, attrs.getValue(i)); } else { theElement.setAttributeNS(theNamespace->c_str(), theName, attrs.getValue(i)); } } } } void FormatterToDeprecatedXercesDOM::processAccumulatedText() { if (m_textBuffer.empty() == false) { DOM_TextType theXercesNode = m_doc.createTextNode(m_textBuffer.c_str()); assert(theXercesNode.isNull() == false); append(theXercesNode); clear(m_textBuffer); } } } #endif //XALAN_BUILD_DEPRECATED_DOM_BRIDGE
20.835073
104
0.647295
ulisesten
a76b080776c0582331328d0da8f40a9423bd8258
11,142
cpp
C++
src/test/cpp/pistis/util/ImmutableListTests.cpp
tomault/pistis-util
0008e8193e210e582201ae906f6933bf82288355
[ "Apache-2.0" ]
null
null
null
src/test/cpp/pistis/util/ImmutableListTests.cpp
tomault/pistis-util
0008e8193e210e582201ae906f6933bf82288355
[ "Apache-2.0" ]
null
null
null
src/test/cpp/pistis/util/ImmutableListTests.cpp
tomault/pistis-util
0008e8193e210e582201ae906f6933bf82288355
[ "Apache-2.0" ]
null
null
null
/** @file ImmutableListTests.cpp * * Unit tests for pistis::util::ImmutableList */ #include <pistis/util/ImmutableList.hpp> #include <pistis/exceptions/OutOfRangeError.hpp> #include <pistis/testing/Allocator.hpp> #include <gtest/gtest.h> #include <sstream> #include <stdint.h> using namespace pistis::exceptions; using namespace pistis::util; namespace pt = pistis::testing; namespace { typedef ::pt::Allocator<uint32_t> TestAllocator; typedef ImmutableList<uint32_t, TestAllocator> UInt32List; typedef std::vector<uint32_t> TrueList; inline std::string toStr(bool v) { return v ? "true" : "false"; } template <typename T> inline std::unique_ptr<T> make_result(const T& result) { return std::unique_ptr<T>(new T(result)); } template <typename Item, typename Allocator> std::unique_ptr<::testing::AssertionResult> verifyListAccessors( std::unique_ptr<::testing::AssertionResult> prior, const std::vector<Item>& truth, const ImmutableList<Item, Allocator>& list ) { if (!*prior) { return std::move(prior); } if (truth.empty() != list.empty()) { return make_result( ::testing::AssertionFailure() << "truth.empty() != list.empty() [ " << toStr(truth.empty()) << " != " << toStr(list.empty()) << " ]" ); } if (truth.size() != list.size()) { return make_result( ::testing::AssertionFailure() << "truth.size() != list.size() [ " << truth.size() << " != " << list.size() << " ]" ); } // list.size() == truth.size() by prior assertion if (!list.size()) { // Don't check front() and back() } else if (truth.front() != list.front()) { return make_result( ::testing::AssertionFailure() << "truth.front() != list.front() [ " << truth.front() << " != " << list.front() << " ]" ); } else if (truth.back() != list.back()) { return make_result( ::testing::AssertionFailure() << "truth.back() != list.back() [ " << truth.back() << " != " << list.back() << " ]" ); } return make_result(::testing::AssertionSuccess()); } template <typename ListIterator, typename TruthIterator> std::unique_ptr<::testing::AssertionResult> verifyRange( std::unique_ptr<::testing::AssertionResult> prior, TruthIterator truthBegin, ListIterator listBegin, ListIterator listEnd) { if (!*prior) { return std::move(prior); } auto i = truthBegin; uint32_t ndx = 0; for (auto j = listBegin; j != listEnd; ++i, ++j, ++ndx) { if (*i != *j) { return make_result( ::testing::AssertionFailure() << "truth[" << ndx << "] (which is " << *i << " ) != list[" << ndx << "] (which is " << *j << ")" ); } } return make_result(::testing::AssertionSuccess()); } template <typename Item, typename Allocator> ::testing::AssertionResult verifyList( const std::vector<Item>& truth, const ImmutableList<Item, Allocator>& list ) { std::unique_ptr<::testing::AssertionResult> result = make_result(::testing::AssertionSuccess()); result = verifyListAccessors(std::move(result), truth, list); result = verifyRange(std::move(result), truth.begin(), list.begin(), list.end()); result = verifyRange(std::move(result), truth.cbegin(), list.cbegin(), list.cend()); return *result; } } TEST(ImmutableListTests, CreateEmpty) { const TestAllocator allocator("TEST_1"); UInt32List list(allocator); EXPECT_EQ(allocator.name(), list.allocator().name()); EXPECT_TRUE(verifyList(TrueList(), list)); } TEST(ImmutableListTests, CreateFromSingleItem) { const TestAllocator allocator("TEST_1"); UInt32List list(3, 16, allocator); TrueList truth{ 16, 16, 16 }; EXPECT_EQ(allocator.name(), list.allocator().name()); EXPECT_TRUE(verifyList(truth, list)); } TEST(ImmutableListTests, CreateFromLengthAndIterator) { const std::vector<uint32_t> DATA{ 5, 16, 2, 23 }; const TestAllocator allocator("TEST_1"); TrueList truth(DATA); UInt32List list(DATA.size(), DATA.begin(), allocator); EXPECT_EQ(allocator.name(), list.allocator().name()); EXPECT_TRUE(verifyList(truth, list)); } TEST(ImmutableListTests, CreateFromRange) { const std::vector<uint32_t> DATA{ 5, 16, 2, 23 }; const TestAllocator allocator("TEST_1"); TrueList truth(DATA); UInt32List list(DATA.begin(), DATA.end(), allocator); EXPECT_EQ(allocator.name(), list.allocator().name()); EXPECT_TRUE(verifyList(truth, list)); } TEST(ImmutableListTests, CreateFromInitializerList) { const TestAllocator allocator("TEST_1"); TrueList truth{ 7, 4, 9, 22, 27 }; UInt32List list{ { 7, 4, 9, 22, 27 }, allocator }; EXPECT_EQ(allocator.name(), list.allocator().name()); EXPECT_TRUE(verifyList(truth, list)); } TEST(ImmutableListTests, CreateFromCopy) { const TestAllocator allocator("TEST_1"); const TestAllocator otherAllocator("TEST_2"); const std::vector<uint32_t> DATA{ 4, 12, 9 }; const TrueList truth(DATA); UInt32List list( DATA.begin(), DATA.end(), allocator); ASSERT_EQ(allocator.name(), list.allocator().name()); ASSERT_TRUE(verifyList(truth, list)); UInt32List copy(list); EXPECT_EQ(allocator.name(), copy.allocator().name()); EXPECT_TRUE(verifyList(truth, copy)); EXPECT_EQ(allocator.name(), list.allocator().name()); EXPECT_TRUE(verifyList(truth, list)); UInt32List copyWithNewAllocator(list, otherAllocator); EXPECT_EQ(otherAllocator.name(), copyWithNewAllocator.allocator().name()); EXPECT_TRUE(verifyList(truth, copyWithNewAllocator)); EXPECT_EQ(allocator.name(), list.allocator().name()); EXPECT_TRUE(verifyList(truth, list)); } TEST(ImmutableListTests, Back) { const std::vector<uint32_t> DATA{ 3, 2, 1, 4 }; UInt32List list(DATA.begin(), DATA.end()); EXPECT_EQ(4, list.back()); EXPECT_EQ(4, list.back(0)); EXPECT_EQ(1, list.back(1)); EXPECT_EQ(2, list.back(2)); EXPECT_EQ(3, list.back(3)); } TEST(ImmutableListTests, At) { const std::vector<uint32_t> DATA{ 3, 2, 1, 4 }; UInt32List list(DATA.begin(), DATA.end()); for (uint32_t i = 0; i != DATA.size(); ++i) { EXPECT_EQ(DATA[i], list.at(i)); } EXPECT_THROW(list.at(list.size()), std::range_error); } TEST(ImmutableListTests, Sublist) { const TestAllocator allocator("TEST_1"); const TrueList truth{3, 4, 5, 6}; UInt32List list{ { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, allocator }; UInt32List sublist(list.sublist(3, 7)); EXPECT_EQ(allocator.name(), sublist.allocator().name()); EXPECT_TRUE(verifyList(truth, sublist)); EXPECT_TRUE(verifyList(TrueList(), list.sublist(3, 3))); EXPECT_TRUE(verifyList(TrueList(), list.sublist(10, 10))); EXPECT_THROW(list.sublist(11, 15), OutOfRangeError); EXPECT_THROW(list.sublist(10, 11), OutOfRangeError); EXPECT_THROW(list.sublist( 7, 3), IllegalValueError); } TEST(ImmutableListTests, Concat) { const TestAllocator allocator("TEST_1"); const TrueList trueConcatenated{ 5, 4, 2, 7, 1, 9, 4 }; UInt32List list1{ { 5, 4, 2, 7 }, allocator }; UInt32List list2{ { 1, 9, 4 }, allocator }; UInt32List empty{ allocator }; UInt32List concatenated = list1.concat(list2); EXPECT_EQ(allocator.name(), concatenated.allocator().name()); EXPECT_TRUE(verifyList(trueConcatenated, concatenated)); EXPECT_TRUE(verifyList(TrueList{ 5, 4, 2, 7 }, list1.concat(empty))); EXPECT_TRUE(verifyList(TrueList{ 5, 4, 2, 7 }, empty.concat(list1))); EXPECT_TRUE(verifyList(TrueList{ 1, 9, 4 }, list2.concat(empty))); EXPECT_TRUE(verifyList(TrueList{ 1, 9, 4 }, empty.concat(list2))); } TEST(ImmutableListTests, Add) { const TestAllocator allocator("TEST_1"); const TrueList trueOriginal{ 5, 4, 2, 7 }; const TrueList trueAddedToEnd{ 5, 4, 2, 7, 3 }; UInt32List list{ { 5, 4, 2, 7 }, allocator }; UInt32List empty{ allocator }; EXPECT_TRUE(verifyList(trueAddedToEnd, list.add(3))); EXPECT_TRUE(verifyList(trueOriginal, list)); EXPECT_TRUE(verifyList(TrueList{ 10 }, empty.add(10))); } TEST(ImmutableListTests, Insert) { const TestAllocator allocator("TEST_1"); const TrueList trueAddedAtStart{ 6, 5, 4, 2, 7 }; const TrueList trueAddedInMiddle{ 5, 4, 1, 2, 7 }; const TrueList trueAddedAtEnd{ 5, 4, 2, 7, 9 }; UInt32List list{ { 5, 4, 2, 7 }, allocator }; UInt32List empty{ allocator }; EXPECT_TRUE(verifyList(trueAddedAtStart, list.insert(0, 6))); EXPECT_TRUE(verifyList(trueAddedInMiddle, list.insert(2, 1))); EXPECT_TRUE(verifyList(trueAddedAtEnd, list.insert(4, 9))); EXPECT_TRUE(verifyList(TrueList{ 10 }, empty.insert(0, 10))); } TEST(ImmutableListTests, Remove) { const TestAllocator allocator("TEST_1"); const TrueList trueRemovedAtStart{ 4, 2, 7 }; const TrueList trueRemovedInMiddle{ 5, 4, 7 }; const TrueList trueRemovedAtEnd{ 5, 4, 2 }; UInt32List list{ { 5, 4, 2, 7 }, allocator }; UInt32List oneItem{ { 10 }, allocator }; EXPECT_TRUE(verifyList(trueRemovedAtStart, list.remove(0))); EXPECT_TRUE(verifyList(trueRemovedInMiddle, list.remove(2))); EXPECT_TRUE(verifyList(trueRemovedAtEnd, list.remove(4))); EXPECT_TRUE(verifyList(TrueList{ }, oneItem.remove(0))); } TEST(ImmutableListTests, Replace) { const TestAllocator allocator("TEST_1"); const TrueList trueReplacedAtStart{ 6, 4, 2, 7 }; const TrueList trueReplacedInMiddle{ 5, 4, 9, 7 }; const TrueList trueReplacedAtEnd{ 5, 4, 2, 1 }; UInt32List list{ { 5, 4, 2, 7 }, allocator }; EXPECT_TRUE(verifyList(trueReplacedAtStart, list.replace((size_t)0, 6))); EXPECT_TRUE(verifyList(trueReplacedInMiddle, list.replace(2, 9))); EXPECT_TRUE(verifyList(trueReplacedAtEnd, list.replace(3, 1))); } TEST(ImmutableListTests, Map) { const TestAllocator allocator("TEST_1"); const std::vector<std::string> truth{ "5", "2", "7", "13" }; UInt32List list{ { 5, 2, 7, 13 }, allocator }; ImmutableList< std::string, pt::Allocator<std::string> > mapped( list.map([](uint32_t x) { std::ostringstream tmp; tmp << x; return tmp.str(); }) ); EXPECT_EQ(allocator.name(), mapped.allocator().name()); EXPECT_TRUE(verifyList(truth, mapped)); } TEST(ImmutableListTest, Reduce) { UInt32List list{ 5, 2, 7, 13 }; UInt32List emptyList; auto concat = [](const std::string& s, uint32_t x) { std::ostringstream tmp; tmp << s << ", " << x; return tmp.str(); }; auto mix = [](uint32_t x, uint32_t y) { return x * 100 + y; }; EXPECT_EQ("**, 5, 2, 7, 13", list.reduce(concat, "**")); EXPECT_EQ("**", emptyList.reduce(concat, "**")); EXPECT_EQ(5020713, list.reduce(mix)); EXPECT_THROW(emptyList.reduce(mix), IllegalStateError); } TEST(ImmutableListTests, ListEquality) { UInt32List list{ 3, 2, 5, 10, 7 }; UInt32List same{ 3, 2, 5, 10, 7 }; UInt32List different{ 3, 2, 9, 10, 7 }; EXPECT_TRUE(list == same); EXPECT_FALSE(list == different); EXPECT_TRUE(list != different); EXPECT_FALSE(list != same); } TEST(ImmutableListTests, RandomAccess) { const std::vector<uint32_t> DATA{ 3, 2, 5, 10, 7 }; UInt32List list(DATA.begin(), DATA.end()); for (uint32_t i = 0; i < DATA.size(); ++i) { EXPECT_EQ(DATA[i], list[i]); } }
32.770588
76
0.662179
tomault
a76fb6bb8c0cbb05e44c24489d39382f2cd13ca2
9,138
cpp
C++
xx_tool_sprite/main.cpp
aconstlink/natus_examples
2716ce7481172bcd14035b18d09b44b74ec78a7e
[ "MIT" ]
null
null
null
xx_tool_sprite/main.cpp
aconstlink/natus_examples
2716ce7481172bcd14035b18d09b44b74ec78a7e
[ "MIT" ]
null
null
null
xx_tool_sprite/main.cpp
aconstlink/natus_examples
2716ce7481172bcd14035b18d09b44b74ec78a7e
[ "MIT" ]
null
null
null
#include "main.h" #include <natus/application/global.h> #include <natus/application/app.h> #include <natus/tool/imgui/sprite_editor.h> #include <natus/device/global.h> #include <natus/gfx/camera/pinhole_camera.h> #include <natus/graphics/shader/nsl_bridge.hpp> #include <natus/graphics/variable/variable_set.hpp> #include <natus/profile/macros.h> #include <natus/format/global.h> #include <natus/format/nsl/nsl_module.h> #include <natus/geometry/mesh/polygon_mesh.h> #include <natus/geometry/mesh/tri_mesh.h> #include <natus/geometry/mesh/flat_tri_mesh.h> #include <natus/geometry/3d/cube.h> #include <natus/geometry/3d/tetra.h> #include <natus/math/vector/vector3.hpp> #include <natus/math/vector/vector4.hpp> #include <natus/math/matrix/matrix4.hpp> #include <natus/math/utility/angle.hpp> #include <natus/math/utility/3d/transformation.hpp> #include <thread> namespace this_file { using namespace natus::core::types ; class test_app : public natus::application::app { natus_this_typedefs( test_app ) ; private: natus::graphics::async_views_t _graphics ; app::window_async_t _wid_async ; app::window_async_t _wid_async2 ; natus::graphics::state_object_res_t _root_render_states ; natus::gfx::pinhole_camera_t _camera_0 ; natus::io::database_res_t _db ; natus::device::three_device_res_t _dev_mouse ; natus::device::ascii_device_res_t _dev_ascii ; bool_t _do_tool = true ; natus::tool::sprite_editor_res_t _se ; public: test_app( void_t ) { natus::application::app::window_info_t wi ; #if 0 _wid_async = this_t::create_window( "A Render Window", wi, { natus::graphics::backend_type::gl3, natus::graphics::backend_type::d3d11} ) ; _wid_async2 = this_t::create_window( "A Render Window", wi) ; _wid_async.window().position( 50, 50 ) ; _wid_async.window().resize( 800, 800 ) ; _wid_async2.window().position( 50 + 800, 50 ) ; _wid_async2.window().resize( 800, 800 ) ; _graphics = natus::graphics::async_views_t( { _wid_async.async(), _wid_async2.async() } ) ; #else _wid_async = this_t::create_window( "A Render Window", wi ) ; _wid_async.window().resize( 1000, 1000 ) ; #endif _db = natus::io::database_t( natus::io::path_t( DATAPATH ), "./working", "data" ) ; _se = natus::tool::sprite_editor_res_t( natus::tool::sprite_editor_t( _db ) ) ; } test_app( this_cref_t ) = delete ; test_app( this_rref_t rhv ) : app( ::std::move( rhv ) ) { _wid_async = std::move( rhv._wid_async ) ; _wid_async2 = std::move( rhv._wid_async2 ) ; _camera_0 = std::move( rhv._camera_0 ) ; _db = std::move( rhv._db ) ; _graphics = std::move( rhv._graphics ) ; _se = std::move( rhv._se ) ; } virtual ~test_app( void_t ) {} virtual natus::application::result on_event( window_id_t const, this_t::window_event_info_in_t wei ) noexcept { _camera_0.perspective_fov( natus::math::angle<float_t>::degree_to_radian( 90.0f ), float_t(wei.w) / float_t(wei.h), 1.0f, 1000.0f ) ; return natus::application::result::ok ; } private: virtual natus::application::result on_init( void_t ) noexcept { natus::device::global_t::system()->search( [&] ( natus::device::idevice_res_t dev_in ) { if( natus::device::three_device_res_t::castable( dev_in ) ) { _dev_mouse = dev_in ; } else if( natus::device::ascii_device_res_t::castable( dev_in ) ) { _dev_ascii = dev_in ; } } ) ; if( !_dev_mouse.is_valid() ) natus::log::global_t::status( "no three mouse found" ) ; if( !_dev_ascii.is_valid() ) natus::log::global_t::status( "no ascii keyboard found" ) ; { _camera_0.look_at( natus::math::vec3f_t( 0.0f, 60.0f, -50.0f ), natus::math::vec3f_t( 0.0f, 1.0f, 0.0f ), natus::math::vec3f_t( 0.0f, 0.0f, 0.0f )) ; } // root render states { natus::graphics::state_object_t so = natus::graphics::state_object_t( "root_render_states" ) ; { natus::graphics::render_state_sets_t rss ; rss.depth_s.do_change = true ; rss.depth_s.ss.do_activate = false ; rss.depth_s.ss.do_depth_write = false ; rss.polygon_s.do_change = true ; rss.polygon_s.ss.do_activate = true ; rss.polygon_s.ss.ff = natus::graphics::front_face::clock_wise ; rss.polygon_s.ss.cm = natus::graphics::cull_mode::back ; rss.polygon_s.ss.fm = natus::graphics::fill_mode::fill ; so.add_render_state_set( rss ) ; } _root_render_states = std::move( so ) ; _graphics.for_each( [&]( natus::graphics::async_view_t a ) { a.configure( _root_render_states ) ; } ) ; } { //_se->add_sprite_sheet( "industrial", natus::io::location_t( "images.industrial.industrial.v2.png" ) ) ; //_se->add_sprite_sheet( "enemies", natus::io::location_t( "images.Paper-Pixels-8x8.Enemies.png" ) ) ; //_se->add_sprite_sheet( "player", natus::io::location_t( "images.Player.png" ) ) ; //_se->add_sprite_sheet( "tiles", natus::io::location_t( "images.Tiles.png" ) ) ; _se->add_sprite_sheet( "sprite_sheets", natus::io::location_t( "sprite_sheets.natus" ) ) ; } return natus::application::result::ok ; } float value = 0.0f ; virtual natus::application::result on_update( natus::application::app_t::update_data_in_t ) noexcept { NATUS_PROFILING_COUNTER_HERE( "Update Clock" ) ; return natus::application::result::ok ; } virtual natus::application::result on_device( natus::application::app_t::device_data_in_t ) noexcept { { natus::device::layouts::ascii_keyboard_t ascii( _dev_ascii ) ; if( ascii.get_state( natus::device::layouts::ascii_keyboard_t::ascii_key::f8 ) == natus::device::components::key_state::released ) { } else if( ascii.get_state( natus::device::layouts::ascii_keyboard_t::ascii_key::f9 ) == natus::device::components::key_state::released ) { } else if( ascii.get_state( natus::device::layouts::ascii_keyboard_t::ascii_key::f2 ) == natus::device::components::key_state::released ) { _do_tool = !_do_tool ; } } NATUS_PROFILING_COUNTER_HERE( "Device Clock" ) ; return natus::application::result::ok ; } virtual natus::application::result on_graphics( natus::application::app_t::render_data_in_t ) noexcept { // render the root render state sets render object // this will set the root render states { _graphics.for_each( [&]( natus::graphics::async_view_t a ) { a.push( _root_render_states ) ; } ) ; } // render the root render state sets render object // this will set the root render states { _graphics.for_each( [&]( natus::graphics::async_view_t a ) { a.pop( natus::graphics::backend::pop_type::render_state ); } ) ; } NATUS_PROFILING_COUNTER_HERE( "Render Clock" ) ; return natus::application::result::ok ; } virtual natus::application::result on_tool( natus::tool::imgui_view_t imgui ) noexcept { if( !_do_tool ) return natus::application::result::no_imgui ; { bool_t show_demo = true ; ImGui::ShowDemoWindow( &show_demo ) ; } _se->do_tool( imgui ) ; return natus::application::result::ok ; } virtual natus::application::result on_shutdown( void_t ) noexcept { return natus::application::result::ok ; } }; natus_res_typedef( test_app ) ; } int main( int argc, char ** argv ) { return natus::application::global_t::create_application( this_file::test_app_res_t( this_file::test_app_t() ) )->exec() ; }
36.552
121
0.552637
aconstlink
a770b77f699c26e5194a4be7cadaf389a2a99c75
7,019
cc
C++
Simulation/OMNeT++/inet/src/inet/transportlayer/tcp_common/TCPSegment.cc
StarStuffSteve/masters-research-project
47c1874913d0961508f033ca9a1144850eb8f8b7
[ "Apache-2.0" ]
1
2017-03-13T15:51:22.000Z
2017-03-13T15:51:22.000Z
Simulation/OMNeT++/inet/src/inet/transportlayer/tcp_common/TCPSegment.cc
StarStuffSteve/masters-research-project
47c1874913d0961508f033ca9a1144850eb8f8b7
[ "Apache-2.0" ]
null
null
null
Simulation/OMNeT++/inet/src/inet/transportlayer/tcp_common/TCPSegment.cc
StarStuffSteve/masters-research-project
47c1874913d0961508f033ca9a1144850eb8f8b7
[ "Apache-2.0" ]
null
null
null
// // Copyright (C) 2004 Andras Varga // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program; if not, see <http://www.gnu.org/licenses/>. // #include "inet/transportlayer/tcp_common/TCPSegment.h" namespace inet { namespace tcp { Register_Class(Sack); bool Sack::empty() const { return start_var == 0 && end_var == 0; } bool Sack::contains(const Sack& other) const { return seqLE(start_var, other.start_var) && seqLE(other.end_var, end_var); } void Sack::clear() { start_var = end_var = 0; } void Sack::setSegment(unsigned int start_par, unsigned int end_par) { setStart(start_par); setEnd(end_par); } std::string Sack::str() const { std::stringstream out; out << "[" << start_var << ".." << end_var << ")"; return out.str(); } Register_Class(TCPSegment); uint32_t TCPSegment::getSegLen() { return payloadLength_var + (finBit_var ? 1 : 0) + (synBit_var ? 1 : 0); } void TCPSegment::truncateSegment(uint32 firstSeqNo, uint32 endSeqNo) { ASSERT(payloadLength_var > 0); // must have common part: #ifndef NDEBUG if (!(seqLess(sequenceNo_var, endSeqNo) && seqLess(firstSeqNo, sequenceNo_var + payloadLength_var))) { throw cRuntimeError(this, "truncateSegment(%u,%u) called on [%u, %u) segment\n", firstSeqNo, endSeqNo, sequenceNo_var, sequenceNo_var + payloadLength_var); } #endif // ifndef NDEBUG unsigned int truncleft = 0; unsigned int truncright = 0; if (seqLess(sequenceNo_var, firstSeqNo)) { truncleft = firstSeqNo - sequenceNo_var; } if (seqGreater(sequenceNo_var + payloadLength_var, endSeqNo)) { truncright = sequenceNo_var + payloadLength_var - endSeqNo; } truncateData(truncleft, truncright); } unsigned short TCPSegment::getHeaderOptionArrayLength() { unsigned short usedLength = 0; for (uint i = 0; i < getHeaderOptionArraySize(); i++) usedLength += getHeaderOption(i)->getLength(); return usedLength; } TCPSegment& TCPSegment::operator=(const TCPSegment& other) { if (this == &other) return *this; clean(); TCPSegment_Base::operator=(other); copy(other); return *this; } void TCPSegment::copy(const TCPSegment& other) { for (const auto & elem : other.payloadList) addPayloadMessage(elem.msg->dup(), elem.endSequenceNo); for (const auto opt: other.headerOptionList) addHeaderOption(opt->dup()); } TCPSegment::~TCPSegment() { clean(); } void TCPSegment::clean() { dropHeaderOptions(); while (!payloadList.empty()) { cPacket *msg = payloadList.front().msg; payloadList.pop_front(); dropAndDelete(msg); } } void TCPSegment::truncateData(unsigned int truncleft, unsigned int truncright) { ASSERT(payloadLength_var >= truncleft + truncright); if (0 != byteArray_var.getDataArraySize()) byteArray_var.truncateData(truncleft, truncright); while (!payloadList.empty() && (payloadList.front().endSequenceNo - sequenceNo_var) <= truncleft) { cPacket *msg = payloadList.front().msg; payloadList.pop_front(); dropAndDelete(msg); } sequenceNo_var += truncleft; payloadLength_var -= truncleft + truncright; // truncate payload data correctly while (!payloadList.empty() && (payloadList.back().endSequenceNo - sequenceNo_var) > payloadLength_var) { cPacket *msg = payloadList.back().msg; payloadList.pop_back(); dropAndDelete(msg); } } void TCPSegment::parsimPack(cCommBuffer *b) PARSIMPACK_CONST { TCPSegment_Base::parsimPack(b); b->pack((int)headerOptionList.size()); for (const auto opt: headerOptionList) { b->packObject(opt); } b->pack((int)payloadList.size()); for (PayloadList::const_iterator it = payloadList.begin(); it != payloadList.end(); it++) { b->pack(it->endSequenceNo); b->packObject(it->msg); } } void TCPSegment::parsimUnpack(cCommBuffer *b) { TCPSegment_Base::parsimUnpack(b); int i, n; b->unpack(n); for (i = 0; i < n; i++) { TCPOption *opt = check_and_cast<TCPOption*>(b->unpackObject()); headerOptionList.push_back(opt); } b->unpack(n); for (i = 0; i < n; i++) { TCPPayloadMessage payload; b->unpack(payload.endSequenceNo); payload.msg = check_and_cast<cPacket*>(b->unpackObject()); payloadList.push_back(payload); } } void TCPSegment::setPayloadArraySize(unsigned int size) { throw cRuntimeError(this, "setPayloadArraySize() not supported, use addPayloadMessage()"); } unsigned int TCPSegment::getPayloadArraySize() const { return payloadList.size(); } TCPPayloadMessage& TCPSegment::getPayload(unsigned int k) { auto i = payloadList.begin(); while (k > 0 && i != payloadList.end()) (++i, --k); if (i == payloadList.end()) throw cRuntimeError("Model error at getPayload(): index out of range"); return *i; } void TCPSegment::setPayload(unsigned int k, const TCPPayloadMessage& payload_var) { throw cRuntimeError(this, "setPayload() not supported, use addPayloadMessage()"); } void TCPSegment::addPayloadMessage(cPacket *msg, uint32 endSequenceNo) { take(msg); TCPPayloadMessage payload; payload.endSequenceNo = endSequenceNo; payload.msg = msg; payloadList.push_back(payload); } cPacket *TCPSegment::removeFirstPayloadMessage(uint32& endSequenceNo) { if (payloadList.empty()) return nullptr; cPacket *msg = payloadList.front().msg; endSequenceNo = payloadList.front().endSequenceNo; payloadList.pop_front(); drop(msg); return msg; } void TCPSegment::addHeaderOption(TCPOption *option) { headerOptionList.push_back(option); } void TCPSegment::setHeaderOptionArraySize(unsigned int size) { throw cRuntimeError(this, "setHeaderOptionArraySize() not supported, use addHeaderOption()"); } unsigned int TCPSegment::getHeaderOptionArraySize() const { return headerOptionList.size(); } TCPOptionPtr& TCPSegment::getHeaderOption(unsigned int k) { return headerOptionList.at(k); } void TCPSegment::setHeaderOption(unsigned int k, const TCPOptionPtr& headerOption) { throw cRuntimeError(this, "setHeaderOption() not supported, use addHeaderOption()"); } void TCPSegment::dropHeaderOptions() { for (auto opt : headerOptionList) delete opt; headerOptionList.clear(); } } // namespace tcp } // namespace inet
25.805147
109
0.682576
StarStuffSteve
a77174a760f57f32c171183044d4196695837821
505
cpp
C++
tests/csimsbw/csimsbw.cpp
OpenCMISS-Dependencies/csim
74ec3c767afcb4a6dc900aeb4d8c5bc1812ea0f1
[ "Apache-2.0" ]
null
null
null
tests/csimsbw/csimsbw.cpp
OpenCMISS-Dependencies/csim
74ec3c767afcb4a6dc900aeb4d8c5bc1812ea0f1
[ "Apache-2.0" ]
2
2016-01-07T00:03:00.000Z
2016-01-25T21:08:00.000Z
tests/csimsbw/csimsbw.cpp
OpenCMISS-Dependencies/csim
74ec3c767afcb4a6dc900aeb4d8c5bc1812ea0f1
[ "Apache-2.0" ]
2
2015-11-29T06:02:19.000Z
2021-03-29T06:00:22.000Z
#include "gtest/gtest.h" #include <string> #include "csimsbw.h" #include "csim/error_codes.h" // generated with test resource locations #include "test_resources.h" TEST(SBW, model_string) { char* modelString; int length; int code = csim_serialiseCellmlFromUrl( TestResources::getLocation( TestResources::CELLML_SINE_IMPORTS_MODEL_RESOURCE), &modelString, &length); EXPECT_EQ(code, 0); EXPECT_NE(std::string(modelString), ""); }
22.954545
71
0.659406
OpenCMISS-Dependencies
a777ace1664fd926477699b879b9b96a9a4f2e1d
1,822
cpp
C++
src/Algorand/Signer.cpp
Khaos-Labs/khaos-wallet-core
2c06d49fddf978e0815b208dddef50ee2011c551
[ "MIT" ]
2
2020-11-16T08:06:30.000Z
2021-06-18T03:21:44.000Z
src/Algorand/Signer.cpp
Khaos-Labs/khaos-wallet-core
2c06d49fddf978e0815b208dddef50ee2011c551
[ "MIT" ]
null
null
null
src/Algorand/Signer.cpp
Khaos-Labs/khaos-wallet-core
2c06d49fddf978e0815b208dddef50ee2011c551
[ "MIT" ]
null
null
null
// Copyright © 2017-2020 Khaos Wallet. // // This file is part of Trust. The full Trust copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. #include "Signer.h" #include "Address.h" #include "../PublicKey.h" using namespace TW; using namespace TW::Algorand; const Data TRANSACTION_TAG = {84, 88}; const std::string TRANSACTION_PAY = "pay"; Proto::SigningOutput Signer::sign(const Proto::SigningInput &input) noexcept { auto protoOutput = Proto::SigningOutput(); auto key = PrivateKey(Data(input.private_key().begin(), input.private_key().end())); auto pubkey = key.getPublicKey(TWPublicKeyTypeED25519); auto from = Address(pubkey); auto note = Data(input.note().begin(), input.note().end()); auto genesisId = input.genesis_id(); auto genesisHash = Data(input.genesis_hash().begin(), input.genesis_hash().end()); if (input.has_transaction_pay()) { auto message = input.transaction_pay(); auto to = Address(message.to_address()); auto transaction = Transaction(from, to, message.fee(), message.amount(), message.first_round(), message.last_round(), note, TRANSACTION_PAY, genesisId, genesisHash); auto signature = sign(key, transaction); auto serialized = transaction.serialize(signature); protoOutput.set_encoded(serialized.data(), serialized.size()); } return protoOutput; } Data Signer::sign(const PrivateKey &privateKey, Transaction &transaction) noexcept { Data data; append(data, TRANSACTION_TAG); append(data, transaction.serialize()); auto signature = privateKey.sign(data, TWCurveED25519); return Data(signature.begin(), signature.end()); }
38.765957
104
0.694841
Khaos-Labs
a77823a4d029474d69084e3fa30e4490328e92a6
748
cpp
C++
Medium/C++/229. Majority Element II.cpp
Hussein-A/Leetcode
20e46b9adb3a4929d0b2eee1ff120fb2348be96d
[ "MIT" ]
null
null
null
Medium/C++/229. Majority Element II.cpp
Hussein-A/Leetcode
20e46b9adb3a4929d0b2eee1ff120fb2348be96d
[ "MIT" ]
null
null
null
Medium/C++/229. Majority Element II.cpp
Hussein-A/Leetcode
20e46b9adb3a4929d0b2eee1ff120fb2348be96d
[ "MIT" ]
null
null
null
/* Given an integer array of size n, find all elements that appear more than ? n/3 ? times. Note: The algorithm should run in linear time and in O(1) space. Runtime: 16 ms, faster than 87.33% of C++ online submissions for Majority Element II. Memory Usage: 10.7 MB, less than 50.89% of C++ online submissions for Majority Element II. */ class Solution { public: vector<int> majorityElement(vector<int>& nums) { vector<int> result; if (nums.size() == 0) return result; int min_bound = nums.size() / 3; //use hash unordered_map<int, int> mymap; for (const int& x : nums) { ++mymap[x]; } for (auto p : mymap) { if (p.second > min_bound) result.push_back(p.first); } sort(result.begin(), result.end()); return result; } };
27.703704
90
0.673797
Hussein-A
a778c2ff335d175f25a2d199f1367bda500ad831
2,934
cc
C++
parma/diffMC/parma_dcpartFixer.cc
Thomas-Ulrich/core
1c7bc7ff994c3570ab22b96d37be0c4c993e5940
[ "BSD-3-Clause" ]
138
2015-01-05T15:50:20.000Z
2022-02-25T01:09:58.000Z
parma/diffMC/parma_dcpartFixer.cc
Thomas-Ulrich/core
1c7bc7ff994c3570ab22b96d37be0c4c993e5940
[ "BSD-3-Clause" ]
337
2015-08-07T18:24:58.000Z
2022-03-31T14:39:03.000Z
parma/diffMC/parma_dcpartFixer.cc
Thomas-Ulrich/core
1c7bc7ff994c3570ab22b96d37be0c4c993e5940
[ "BSD-3-Clause" ]
70
2015-01-17T00:58:41.000Z
2022-02-13T04:58:20.000Z
#include "PCU.h" #include "parma_dcpart.h" #include "parma_commons.h" #include "parma_convert.h" #include <maximalIndependentSet/mis.h> #include <pcu_util.h> typedef std::map<unsigned, unsigned> muu; namespace { bool isInMis(muu& mt) { unsigned seed = TO_UINT(PCU_Comm_Self()+1); mis_init(seed); misLuby::partInfo part; part.id = PCU_Comm_Self(); std::set<int> targets; APF_ITERATE(muu, mt, mtItr) { int peer = TO_INT(mtItr->second); if( !targets.count(peer) ) { part.adjPartIds.push_back(peer); part.net.push_back(peer); targets.insert(peer); } } part.net.push_back(part.id); return mis(part,false,true); } } class dcPartFixer::PartFixer : public dcPart { public: PartFixer(apf::Mesh* mesh, unsigned verbose=0) : dcPart(mesh,verbose), m(mesh), vb(verbose) { fix(); } private: apf::Mesh* m; unsigned vb; int totNumDc() { int ndc = TO_INT(numDisconnectedComps()); return PCU_Add_Int(ndc); } void setupPlan(muu& dcCompTgts, apf::Migration* plan) { apf::MeshEntity* e; apf::MeshIterator* itr = m->begin(m->getDimension()); while( (e = m->iterate(itr)) ) { if( isIsolated(e) ) continue; unsigned id = compId(e); if ( dcCompTgts.count(id) ) plan->send(e, TO_INT(dcCompTgts[id])); } m->end(itr); } /** * @brief remove the disconnected set(s) of elements from the part * @remark migrate the disconnected set(s) of elements into the adjacent part * that shares the most faces with the disconnected set of elements * requires that the sets of elements forming disconnected components * are tagged */ void fix() { double t1 = PCU_Time(); int loop = 0; int ndc = 0; while( (ndc = totNumDc()) && loop++ < 50 ) { double t2 = PCU_Time(); muu dcCompTgts; unsigned maxSz = 0; for(unsigned i=0; i<getNumComps(); i++) if( getCompSize(i) > maxSz ) maxSz = getCompSize(i); for(unsigned i=0; i<getNumComps(); i++) if( getCompSize(i) != maxSz ) dcCompTgts[i] = getCompPeer(i); PCU_ALWAYS_ASSERT( dcCompTgts.size() == getNumComps()-1 ); apf::Migration* plan = new apf::Migration(m); if ( isInMis(dcCompTgts) ) setupPlan(dcCompTgts, plan); reset(); double t3 = PCU_Time(); m->migrate(plan); if( ! PCU_Comm_Self() && vb) parmaCommons::status( "loop %d components %d seconds <fix migrate> %.3f %.3f\n", loop, ndc, t3-t2, PCU_Time()-t3); } parmaCommons::printElapsedTime(__func__, PCU_Time() - t1); } }; dcPartFixer::dcPartFixer(apf::Mesh* mesh, unsigned verbose) : pf( new PartFixer(mesh,verbose) ) {} dcPartFixer::~dcPartFixer() { delete pf; }
27.942857
81
0.582481
Thomas-Ulrich
a77959f0e89a7b99097f2af7afbdd048e8b7d490
2,457
cc
C++
ofstd/tests/tststack.cc
chrisvana/dcmtk_copy
f929ab8590aca5b7a319c95af4fe2ee31be52f46
[ "Apache-2.0" ]
24
2015-07-22T05:07:51.000Z
2019-02-28T04:52:33.000Z
ofstd/tests/tststack.cc
chrisvana/dcmtk_copy
f929ab8590aca5b7a319c95af4fe2ee31be52f46
[ "Apache-2.0" ]
13
2015-07-23T05:43:02.000Z
2021-07-17T17:14:45.000Z
ofstd/tests/tststack.cc
chrisvana/dcmtk_copy
f929ab8590aca5b7a319c95af4fe2ee31be52f46
[ "Apache-2.0" ]
13
2015-07-23T01:07:30.000Z
2021-01-05T09:49:30.000Z
/* * * Copyright (C) 1997-2010, OFFIS e.V. * All rights reserved. See COPYRIGHT file for details. * * This software and supporting documentation were developed by * * OFFIS e.V. * R&D Division Health * Escherweg 2 * D-26121 Oldenburg, Germany * * * Module: ofstd * * Author: Andreas Barth * * Purpose: test programm for class OFStack * * Last Update: $Author: joergr $ * Update Date: $Date: 2010-10-14 13:15:16 $ * CVS/RCS Revision: $Revision: 1.11 $ * Status: $State: Exp $ * * CVS/RCS Log at end of file * */ #include "dcmtk/config/osconfig.h" #include "dcmtk/ofstd/ofstream.h" #include "dcmtk/ofstd/ofstack.h" #include "dcmtk/ofstd/ofconsol.h" int main() { OFStack<int> st; st.push(1); st.push(2); st.push(3); OFStack<int> nst(st); COUT << "Output of number of Elements in st: " << st.size() << OFendl; COUT << "Output and deletion of st: "; while(!st.empty()) { COUT << st.top() << " "; st.pop(); } COUT << OFendl; COUT << "Output of number of Elements in copy from st: " << nst.size() << OFendl; COUT << "Output and deletion of copy from st: "; while(!nst.empty()) { COUT << nst.top() << " "; nst.pop(); } COUT << OFendl; } /* ** ** CVS/RCS Log: ** $Log: tststack.cc,v $ ** Revision 1.11 2010-10-14 13:15:16 joergr ** Updated copyright header. Added reference to COPYRIGHT file. ** ** Revision 1.10 2006/08/14 16:42:48 meichel ** Updated all code in module ofstd to correctly compile if the standard ** namespace has not included into the global one with a "using" directive. ** ** Revision 1.9 2005/12/08 15:49:11 meichel ** Changed include path schema for all DCMTK header files ** ** Revision 1.8 2004/01/16 10:37:23 joergr ** Removed acknowledgements with e-mail addresses from CVS log. ** ** Revision 1.7 2002/04/16 13:37:01 joergr ** Added configurable support for C++ ANSI standard includes (e.g. streams). ** ** Revision 1.6 2001/06/01 15:51:41 meichel ** Updated copyright header ** ** Revision 1.5 2000/03/08 16:36:08 meichel ** Updated copyright header. ** ** Revision 1.4 2000/03/03 14:02:53 meichel ** Implemented library support for redirecting error messages into memory ** instead of printing them to stdout/stderr for GUI applications. ** ** Revision 1.3 1998/11/27 12:42:11 joergr ** Added copyright message to source files and changed CVS header. ** ** ** */
24.57
85
0.638991
chrisvana
a779e73de1486642d329cc195c088afd6bc82c0c
9,172
cpp
C++
libraries/disp3D/engine/model/items/sensordata/gpuinterpolationitem.cpp
ChunmingGu/mne-cpp-master
36f21b3ab0c65a133027da83fa8e2a652acd1485
[ "BSD-3-Clause" ]
null
null
null
libraries/disp3D/engine/model/items/sensordata/gpuinterpolationitem.cpp
ChunmingGu/mne-cpp-master
36f21b3ab0c65a133027da83fa8e2a652acd1485
[ "BSD-3-Clause" ]
null
null
null
libraries/disp3D/engine/model/items/sensordata/gpuinterpolationitem.cpp
ChunmingGu/mne-cpp-master
36f21b3ab0c65a133027da83fa8e2a652acd1485
[ "BSD-3-Clause" ]
null
null
null
//============================================================================================================= /** * @file gpuinterpolationitem.cpp * @author Lars Debor <lars.debor@tu-ilmenau.de>; * Matti Hamalainen <msh@nmr.mgh.harvard.edu> * @version 1.0 * @date October, 2017 * * @section LICENSE * * Copyright (C) 2017, Lars Debor and Matti Hamalainen. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that * the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and * the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of MNE-CPP authors nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * * @brief GpuInterpolationItem class definition. * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "gpuinterpolationitem.h" #include "../../materials/gpuinterpolationmaterial.h" #include "../../3dhelpers/custommesh.h" #include <mne/mne_bem_surface.h> //************************************************************************************************************* //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <Qt3DCore/QEntity> #include <Qt3DCore/QTransform> #include <Qt3DRender/QComputeCommand> #include <Qt3DRender/QAttribute> #include <Qt3DRender/QGeometryRenderer> //************************************************************************************************************* //============================================================================================================= // Eigen INCLUDES //============================================================================================================= //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace DISP3DLIB; using namespace Qt3DRender; using namespace Qt3DCore; //************************************************************************************************************* //============================================================================================================= // DEFINE GLOBAL METHODS //============================================================================================================= //************************************************************************************************************* //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= GpuInterpolationItem::GpuInterpolationItem(Qt3DCore::QEntity *p3DEntityParent, int iType, const QString &text) : Abstract3DTreeItem(p3DEntityParent, iType, text) , m_bIsDataInit(false) , m_pMaterial(new GpuInterpolationMaterial) { initItem(); } //************************************************************************************************************* void GpuInterpolationItem::initData(const MNELIB::MNEBemSurface &tMneBemSurface, QSharedPointer<SparseMatrix<double> > tInterpolationMatrix) { if(m_bIsDataInit == true) { qDebug("GpuInterpolationItem::initData data already initialized"); return; } m_pMaterial->setWeightMatrix(tInterpolationMatrix); //Create draw entity if needed if(!m_pMeshDrawEntity) { m_pMeshDrawEntity = new QEntity(this); m_pCustomMesh = new CustomMesh; //Interpolated signal attribute QAttribute *pInterpolatedSignalAttrib = new QAttribute; pInterpolatedSignalAttrib->setAttributeType(Qt3DRender::QAttribute::VertexAttribute); pInterpolatedSignalAttrib->setDataType(Qt3DRender::QAttribute::Float); pInterpolatedSignalAttrib->setVertexSize(4); pInterpolatedSignalAttrib->setByteOffset(0); pInterpolatedSignalAttrib->setByteStride(4 * sizeof(float)); pInterpolatedSignalAttrib->setName(QStringLiteral("OutputColor")); pInterpolatedSignalAttrib->setBuffer(m_pMaterial->getOutputColorBuffer()); //add interpolated signal Attribute m_pCustomMesh->addAttribute(pInterpolatedSignalAttrib); m_pMeshDrawEntity->addComponent(m_pCustomMesh); m_pMeshDrawEntity->addComponent(m_pMaterial); } //Create compute entity if needed if(!m_pComputeEntity) { m_pComputeEntity = new QEntity(this); m_pComputeCommand = new QComputeCommand; m_pComputeEntity->addComponent(m_pComputeCommand); m_pComputeEntity->addComponent(m_pMaterial); } const uint iWeightMatRows = tMneBemSurface.rr.rows(); //Set work group size const uint iWorkGroupsSize = static_cast<uint>(std::ceil(std::sqrt(iWeightMatRows))); m_pComputeCommand->setWorkGroupX(iWorkGroupsSize); m_pComputeCommand->setWorkGroupY(iWorkGroupsSize); m_pComputeCommand->setWorkGroupZ(1); //Set custom mesh data //generate mesh base color QColor baseColor = QColor(80, 80, 80, 255); MatrixX3f matVertColor(tMneBemSurface.rr.rows(),3); for(int i = 0; i < matVertColor.rows(); ++i) { matVertColor(i,0) = baseColor.redF(); matVertColor(i,1) = baseColor.greenF(); matVertColor(i,2) = baseColor.blueF(); } //Set renderable 3D entity mesh and color data m_pCustomMesh->setMeshData(tMneBemSurface.rr, tMneBemSurface.nn, tMneBemSurface.tris, matVertColor, Qt3DRender::QGeometryRenderer::Triangles); m_bIsDataInit = true; } //************************************************************************************************************* void GpuInterpolationItem::setWeightMatrix(QSharedPointer<SparseMatrix<double> > tInterpolationMatrix) { if(m_bIsDataInit == false) { qDebug("GpuInterpolationItem::setWeightMatrix item data is not initialized!"); return; } m_pMaterial->setWeightMatrix(tInterpolationMatrix); } //************************************************************************************************************* void GpuInterpolationItem::addNewRtData(const VectorXf &tSignalVec) { if(m_pMaterial && m_bIsDataInit) { m_pMaterial->addSignalData(tSignalVec); } } //************************************************************************************************************* void GpuInterpolationItem::setNormalization(const QVector3D &tVecThresholds) { m_pMaterial->setNormalization(tVecThresholds); } //************************************************************************************************************* void GpuInterpolationItem::setColormapType(const QString &tColormapType) { m_pMaterial->setColormapType(tColormapType); } //************************************************************************************************************* void GpuInterpolationItem::initItem() { this->setEditable(false); this->setCheckable(true); this->setCheckState(Qt::Checked); this->setToolTip(this->text()); } //*************************************************************************************************************
39.878261
116
0.490188
ChunmingGu
a77b539c8e18e780822445d43a7e28e2c127b9e6
25,800
inl
C++
include/eagine/app/opengl_eglplus.inl
matus-chochlik/eagine-app
7aeecbf765a6e4316adfe145f9116aded6cdb550
[ "BSL-1.0" ]
null
null
null
include/eagine/app/opengl_eglplus.inl
matus-chochlik/eagine-app
7aeecbf765a6e4316adfe145f9116aded6cdb550
[ "BSL-1.0" ]
null
null
null
include/eagine/app/opengl_eglplus.inl
matus-chochlik/eagine-app
7aeecbf765a6e4316adfe145f9116aded6cdb550
[ "BSL-1.0" ]
null
null
null
/// @file /// /// Copyright 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 /// #include <eagine/app/context.hpp> #include <eagine/extract.hpp> #include <eagine/integer_range.hpp> #include <eagine/logging/type/yes_no_maybe.hpp> #include <eagine/maybe_unused.hpp> #include <eagine/oglplus/config/basic.hpp> #include <eagine/valid_if/decl.hpp> #include <eagine/eglplus/egl.hpp> #include <eagine/eglplus/egl_api.hpp> namespace eagine::app { //------------------------------------------------------------------------------ // surface //------------------------------------------------------------------------------ class eglplus_opengl_surface : public main_ctx_object , public video_provider { public: eglplus_opengl_surface(main_ctx_parent parent, eglplus::egl_api& egl) : main_ctx_object{EAGINE_ID(EGLPbuffer), parent} , _egl_api{egl} {} auto get_context_attribs( execution_context&, const bool gl_otherwise_gles, const launch_options&, const video_options&) const -> std::vector<eglplus::egl_types::int_type>; auto initialize( execution_context&, const eglplus::display_handle, const eglplus::egl_types::config_type, const launch_options&, const video_options&) -> bool; auto initialize( execution_context&, const eglplus::display_handle, const valid_if_nonnegative<span_size_t>& device_idx, const launch_options&, const video_options&) -> bool; auto initialize( execution_context&, const identifier instance, const launch_options&, const video_options&) -> bool; void clean_up(); auto video_kind() const noexcept -> video_context_kind final; auto instance_id() const noexcept -> identifier final; auto is_offscreen() noexcept -> tribool final; auto has_framebuffer() noexcept -> tribool final; auto surface_size() noexcept -> std::tuple<int, int> final; auto surface_aspect() noexcept -> float final; void parent_context_changed(const video_context&) final; void video_begin(execution_context&) final; void video_end(execution_context&) final; void video_commit(execution_context&) final; private: eglplus::egl_api& _egl_api; identifier _instance_id; eglplus::display_handle _display{}; eglplus::surface_handle _surface{}; eglplus::context_handle _context{}; int _width{1}; int _height{1}; }; //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_surface::get_context_attribs( execution_context&, const bool gl_otherwise_gles, const launch_options&, const video_options& video_opts) const -> std::vector<eglplus::egl_types::int_type> { const auto& EGL = _egl_api.constants(); const auto add_major_version = [&](auto attribs) { return attribs + (EGL.context_major_version | (video_opts.gl_version_major() / 3)); }; const auto add_minor_version = [&](auto attribs) { eglplus::context_attrib_traits::value_type fallback = 0; if(gl_otherwise_gles) { if(!video_opts.gl_compatibility_context()) { fallback = 3; } } return attribs + (EGL.context_minor_version | (video_opts.gl_version_minor() / fallback)); }; const auto add_profile_mask = [&](auto attribs) { const auto compat = video_opts.gl_compatibility_context(); if(compat) { return attribs + (EGL.context_opengl_profile_mask | EGL.context_opengl_compatibility_profile_bit); } else { return attribs + (EGL.context_opengl_profile_mask | EGL.context_opengl_core_profile_bit); } }; const auto add_debugging = [&](auto attribs) { return attribs + (EGL.context_opengl_debug | video_opts.gl_debug_context()); }; const auto add_robustness = [&](auto attribs) { return attribs + (EGL.context_opengl_robust_access | video_opts.gl_robust_access()); }; return add_robustness( add_debugging(add_profile_mask(add_minor_version( add_major_version(eglplus::context_attribute_base()))))) .copy(); } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_surface::initialize( execution_context& exec_ctx, const eglplus::display_handle display, const eglplus::egl_types::config_type config, const launch_options& opts, const video_options& video_opts) -> bool { const auto& [egl, EGL] = _egl_api; const auto apis{egl.get_client_api_bits(display)}; const bool has_gl = apis.has(EGL.opengl_bit); const bool has_gles = apis.has(EGL.opengl_es_bit); if(!has_gl && !has_gles) { log_info("display does not support any OpenAPI APIs;skipping"); return false; } log_info("display device supports GL APIs") .arg(EAGINE_ID(OpenGL), yes_no_maybe(has_gl)) .arg(EAGINE_ID(OpenGL_ES), yes_no_maybe(has_gles)) .arg(EAGINE_ID(PreferES), yes_no_maybe(video_opts.prefer_gles())); const bool gl_otherwise_gles = has_gl && !video_opts.prefer_gles(); _width = video_opts.surface_width() / 1; _height = video_opts.surface_height() / 1; const auto surface_attribs = (EGL.width | _width) + (EGL.height | _height); if(ok surface{ egl.create_pbuffer_surface(display, config, surface_attribs)}) { _surface = surface; const auto gl_api = gl_otherwise_gles ? eglplus::client_api(EGL.opengl_api) : eglplus::client_api(EGL.opengl_es_api); if(ok bound{egl.bind_api(gl_api)}) { const auto context_attribs = get_context_attribs( exec_ctx, gl_otherwise_gles, opts, video_opts); if(ok ctxt{egl.create_context( display, config, eglplus::context_handle{}, view(context_attribs))}) { _context = ctxt; return true; } else { log_error("failed to create context") .arg(EAGINE_ID(message), (!ctxt).message()); } } else { log_error("failed to bind OpenGL API") .arg(EAGINE_ID(message), (!bound).message()); } } else { log_error("failed to create pbuffer ${width}x${height}") .arg(EAGINE_ID(width), _width) .arg(EAGINE_ID(height), _height) .arg(EAGINE_ID(message), (!surface).message()); } return false; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_surface::initialize( execution_context& exec_ctx, const eglplus::display_handle display, const valid_if_nonnegative<span_size_t>& device_idx, const launch_options& opts, const video_options& video_opts) -> bool { const auto& [egl, EGL] = _egl_api; if(device_idx) { log_info("trying EGL device ${index}") .arg(EAGINE_ID(index), extract(device_idx)); } else { exec_ctx.log_info("trying default EGL display device"); } if(ok initialized{egl.initialize(display)}) { if(auto conf_driver_name{video_opts.driver_name()}) { if(egl.MESA_query_driver(display)) { if(ok driver_name{egl.get_display_driver_name(display)}) { if(are_equal( extract(video_opts.driver_name()), extract(driver_name))) { log_info("using the ${driver} MESA display driver") .arg( EAGINE_ID(driver), EAGINE_ID(Identifier), extract(driver_name)); } else { log_info( "${current} does not match the configured " "${config} display driver; skipping") .arg( EAGINE_ID(current), EAGINE_ID(Identifier), extract(driver_name)) .arg( EAGINE_ID(config), EAGINE_ID(Identifier), extract(conf_driver_name)); return false; } } else { log_error("failed to get EGL display driver name"); return false; } } else { log_info( "cannot determine current display driver to match " "with configured ${config} driver; skipping") .arg( EAGINE_ID(config), EAGINE_ID(Identifier), extract(conf_driver_name)); return false; } } else { if(egl.MESA_query_driver(display)) { if(ok driver_name{egl.get_display_driver_name(display)}) { log_info("using the ${driver} MESA display driver") .arg( EAGINE_ID(driver), EAGINE_ID(Identifier), extract(driver_name)); } } } _display = display; const auto config_attribs = (EGL.red_size | (video_opts.color_bits() / EGL.dont_care)) + (EGL.green_size | (video_opts.color_bits() / EGL.dont_care)) + (EGL.blue_size | (video_opts.color_bits() / EGL.dont_care)) + (EGL.alpha_size | (video_opts.alpha_bits() / EGL.dont_care)) + (EGL.depth_size | (video_opts.depth_bits() / EGL.dont_care)) + (EGL.stencil_size | (video_opts.stencil_bits() / EGL.dont_care)) + (EGL.color_buffer_type | EGL.rgb_buffer) + (EGL.surface_type | EGL.pbuffer_bit) + (EGL.renderable_type | (EGL.opengl_bit | EGL.opengl_es3_bit)); if(ok count{egl.choose_config.count(_display, config_attribs)}) { log_info("found ${count} suitable framebuffer configurations") .arg(EAGINE_ID(count), extract(count)); if(ok config{egl.choose_config(_display, config_attribs)}) { return initialize(exec_ctx, _display, config, opts, video_opts); } else { const string_view dont_care{"-"}; log_error("no matching framebuffer configuration found") .arg( EAGINE_ID(color), EAGINE_ID(integer), video_opts.color_bits(), dont_care) .arg( EAGINE_ID(alpha), EAGINE_ID(integer), video_opts.alpha_bits(), dont_care) .arg( EAGINE_ID(depth), EAGINE_ID(integer), video_opts.depth_bits(), dont_care) .arg( EAGINE_ID(stencil), EAGINE_ID(integer), video_opts.stencil_bits(), dont_care) .arg(EAGINE_ID(message), (!config).message()); } } else { log_error("failed to query framebuffer configurations") .arg(EAGINE_ID(message), (!count).message()); } } else { exec_ctx.log_error("failed to initialize EGL display") .arg(EAGINE_ID(message), (!initialized).message()); } return false; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_surface::initialize( execution_context& exec_ctx, const identifier id, const launch_options& opts, const video_options& video_opts) -> bool { _instance_id = id; const auto& [egl, EGL] = _egl_api; const auto device_kind = video_opts.device_kind(); const auto device_path = video_opts.device_path(); const auto device_idx = video_opts.device_index(); const bool select_device = device_kind.is_valid() || device_path.is_valid() || device_idx.is_valid() || video_opts.driver_name().is_valid(); if(select_device && egl.EXT_device_enumeration) { if(ok dev_count{egl.query_devices.count()}) { const auto n = std_size(extract(dev_count)); std::vector<eglplus::egl_types::device_type> devices; devices.resize(n); if(egl.query_devices(cover(devices))) { for(const auto cur_dev_idx : integer_range(n)) { bool matching_device = true; auto device = eglplus::device_handle(devices[cur_dev_idx]); if(device_idx) { if(std_size(extract(device_idx)) == cur_dev_idx) { log_info("explicitly selected device ${index}") .arg(EAGINE_ID(index), extract(device_idx)); } else { matching_device = false; log_info( "current device index is ${current} but, " "device ${config} requested; skipping") .arg(EAGINE_ID(current), cur_dev_idx) .arg(EAGINE_ID(config), extract(device_idx)); } } if(device_kind) { if(extract(device_kind) == video_device_kind::hardware) { if(!egl.MESA_device_software(device)) { log_info( "device ${index} seems to be hardware as " "explicitly specified by configuration") .arg(EAGINE_ID(index), cur_dev_idx); } else { matching_device = false; log_info( "device ${index} is software but, " "hardware device requested; skipping") .arg(EAGINE_ID(index), cur_dev_idx); } } else if( extract(device_kind) == video_device_kind::software) { if(!egl.EXT_device_drm(device)) { log_info( "device ${index} seems to be software as " "explicitly specified by configuration") .arg(EAGINE_ID(index), cur_dev_idx); } else { matching_device = false; log_info( "device ${index} is hardware but, " "software device requested; skipping") .arg(EAGINE_ID(index), cur_dev_idx); } } } if(device_path) { if(egl.EXT_device_drm(device)) { if(ok path{egl.query_device_string( device, EGL.drm_device_file)}) { if(are_equal( extract(device_path), extract(path))) { log_info( "using DRM device ${path} as " "explicitly specified by configuration") .arg( EAGINE_ID(path), EAGINE_ID(FsPath), extract(path)); } else { matching_device = false; log_info( "device file is ${current}, but " "${config} was requested; skipping") .arg( EAGINE_ID(current), EAGINE_ID(FsPath), extract(path)) .arg( EAGINE_ID(config), EAGINE_ID(FsPath), extract(device_path)); } } } else { log_warning( "${config} requested by config, but cannot " "determine current device file path") .arg( EAGINE_ID(config), EAGINE_ID(FsPath), extract(device_path)); } } if(matching_device) { if(ok display{egl.get_platform_display(device)}) { if(initialize( exec_ctx, display, signedness_cast(cur_dev_idx), opts, video_opts)) { return true; } else { _egl_api.terminate(display); } } } } } } } else { if(ok display{egl.get_display()}) { return initialize(exec_ctx, display, -1, opts, video_opts); } else { exec_ctx.log_error("failed to get EGL display") .arg(EAGINE_ID(message), (!display).message()); } } return false; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC void eglplus_opengl_surface::clean_up() { if(_display) { if(_context) { _egl_api.destroy_context(_display, _context); } if(_surface) { _egl_api.destroy_surface(_display, _surface); } _egl_api.terminate(_display); } } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_surface::video_kind() const noexcept -> video_context_kind { return video_context_kind::opengl; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_surface::instance_id() const noexcept -> identifier { return _instance_id; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_surface::is_offscreen() noexcept -> tribool { return true; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_surface::has_framebuffer() noexcept -> tribool { return true; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_surface::surface_size() noexcept -> std::tuple<int, int> { return {_width, _height}; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_surface::surface_aspect() noexcept -> float { return float(_width) / float(_height); } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC void eglplus_opengl_surface::parent_context_changed(const video_context&) {} //------------------------------------------------------------------------------ EAGINE_LIB_FUNC void eglplus_opengl_surface::video_begin(execution_context&) { _egl_api.make_current(_display, _surface, _context); } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC void eglplus_opengl_surface::video_end(execution_context&) { _egl_api.make_current.none(_display); } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC void eglplus_opengl_surface::video_commit(execution_context&) { _egl_api.swap_buffers(_display, _surface); } //------------------------------------------------------------------------------ // provider //------------------------------------------------------------------------------ class eglplus_opengl_provider : public main_ctx_object , public hmi_provider { public: eglplus_opengl_provider(main_ctx_parent parent) : main_ctx_object{EAGINE_ID(EGLPPrvdr), parent} {} auto is_implemented() const noexcept -> bool final; auto implementation_name() const noexcept -> string_view final; auto is_initialized() -> bool final; auto should_initialize(execution_context&) -> bool final; auto initialize(execution_context&) -> bool final; void update(execution_context&) final; void clean_up(execution_context&) final; void input_enumerate( callable_ref<void(std::shared_ptr<input_provider>)>) final; void video_enumerate( callable_ref<void(std::shared_ptr<video_provider>)>) final; void audio_enumerate( callable_ref<void(std::shared_ptr<audio_provider>)>) final; private: eglplus::egl_api _egl_api; std::map<identifier, std::shared_ptr<eglplus_opengl_surface>> _surfaces; }; //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_provider::is_implemented() const noexcept -> bool { return _egl_api.get_display && _egl_api.initialize && _egl_api.terminate && _egl_api.get_configs && _egl_api.choose_config && _egl_api.get_config_attrib && _egl_api.query_string && _egl_api.swap_buffers; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_provider::implementation_name() const noexcept -> string_view { return {"eglplus"}; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_provider::is_initialized() -> bool { return !_surfaces.empty(); } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_provider::should_initialize(execution_context& exec_ctx) -> bool { for(auto& [inst, video_opts] : exec_ctx.options().video_requirements()) { EAGINE_MAYBE_UNUSED(inst); if(video_opts.has_provider(implementation_name())) { return true; } } return false; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC auto eglplus_opengl_provider::initialize(execution_context& exec_ctx) -> bool { if(_egl_api.get_display) { auto& options = exec_ctx.options(); for(auto& [inst, video_opts] : options.video_requirements()) { const bool should_create_surface = video_opts.has_provider(implementation_name()) && (video_opts.video_kind() == video_context_kind::opengl); if(should_create_surface) { if(auto surface{std::make_shared<eglplus_opengl_surface>( *this, _egl_api)}) { if(extract(surface).initialize( exec_ctx, inst, options, video_opts)) { _surfaces[inst] = std::move(surface); } else { extract(surface).clean_up(); } } } } return true; } exec_ctx.log_error("EGL is context is not supported"); return false; } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC void eglplus_opengl_provider::update(execution_context&) {} //------------------------------------------------------------------------------ EAGINE_LIB_FUNC void eglplus_opengl_provider::clean_up(execution_context&) { for(auto& entry : _surfaces) { entry.second->clean_up(); } } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC void eglplus_opengl_provider::input_enumerate( callable_ref<void(std::shared_ptr<input_provider>)>) {} //------------------------------------------------------------------------------ EAGINE_LIB_FUNC void eglplus_opengl_provider::video_enumerate( callable_ref<void(std::shared_ptr<video_provider>)> handler) { for(auto& p : _surfaces) { handler(p.second); } } //------------------------------------------------------------------------------ EAGINE_LIB_FUNC void eglplus_opengl_provider::audio_enumerate( callable_ref<void(std::shared_ptr<audio_provider>)>) {} //------------------------------------------------------------------------------ auto make_eglplus_opengl_provider(main_ctx_parent parent) -> std::shared_ptr<hmi_provider> { return {std::make_shared<eglplus_opengl_provider>(parent)}; } //------------------------------------------------------------------------------ } // namespace eagine::app
40
81
0.496783
matus-chochlik
a77b972fd1434bfad2a10e073e42174a893bda96
5,891
cpp
C++
libextra/source/FontCache.cpp
PRImA-Research-Lab/prima-image-lib
9072672cf1f42caf35e8c69d6b09ee6217fb24a6
[ "Apache-2.0" ]
4
2017-10-04T06:23:11.000Z
2019-05-09T14:39:12.000Z
libextra/source/FontCache.cpp
PRImA-Research-Lab/prima-image-lib
9072672cf1f42caf35e8c69d6b09ee6217fb24a6
[ "Apache-2.0" ]
null
null
null
libextra/source/FontCache.cpp
PRImA-Research-Lab/prima-image-lib
9072672cf1f42caf35e8c69d6b09ee6217fb24a6
[ "Apache-2.0" ]
2
2018-10-11T02:01:42.000Z
2019-02-09T21:30:59.000Z
#include "FontCache.h" using Gdiplus::FontStyleRegular; using Gdiplus::UnitPixel; using Gdiplus::UnitPoint; using Gdiplus::FontCollection; namespace PRImA { /* * Class CFontCache * * Static cache for fonts used in Aletheia * * CC 05.10.2011 - created */ const wchar_t * CFontCache::FONT_ALETHEIA_SANS = _T("Aletheia Sans"); const wchar_t * CFontCache::FONT_ARIAL = _T("Arial"); const wchar_t * CFontCache::FONT_MS_SHELL_DLG = L"MS Shell Dlg"; map<CUniString, map<int, CFont *> * > CFontCache::s_NormalFonts; map<CUniString, map<int, CFont *> * > CFontCache::s_BoldFonts; map<CUniString, map<double, Gdiplus::Font *> * > CFontCache::s_GdiPlusFonts; CCriticalSection CFontCache::s_CriticalSect; PrivateFontCollection * CFontCache::s_GdiPlusFontCollection = NULL; set<CUniString> CFontCache::s_PrivateGdiPlusFonts; /* * Constructor */ CFontCache::CFontCache(void) { } /* * Destructor */ CFontCache::~CFontCache(void) { } /* * Initialises a font collection for GDI+ fonts (thread-safe) */ void CFontCache::InitPrivateFontCollection() { CSingleLock lock(&s_CriticalSect, TRUE); if (s_GdiPlusFontCollection == NULL) s_GdiPlusFontCollection = new PrivateFontCollection(); lock.Unlock(); } /* * Adds non-installed font from a file for usage with GDI+ */ void CFontCache::AddPrivateGdiPlusFont(CUniString fontName, CUniString filepath) { InitPrivateFontCollection(); s_GdiPlusFontCollection->AddFontFile(filepath.GetBuffer()); s_PrivateGdiPlusFonts.insert(fontName); } /* * Deletes all cached fonts */ void CFontCache::DeleteFonts() { CSingleLock lock(&s_CriticalSect, TRUE); for (map<CUniString, map<int, CFont *> * >::iterator it = s_NormalFonts.begin(); it != s_NormalFonts.end(); it++) { map<int, CFont *> * map2 = (*it).second; for (map<int, CFont *>::iterator it2 = map2->begin(); it2 != map2->end(); it2++) { (*it2).second->DeleteObject(); delete (*it2).second; } delete map2; } for (map<CUniString, map<int, CFont *> * >::iterator it = s_BoldFonts.begin(); it != s_BoldFonts.end(); it++) { map<int, CFont *> * map2 = (*it).second; for (map<int, CFont *>::iterator it2 = map2->begin(); it2 != map2->end(); it2++) { (*it2).second->DeleteObject(); delete (*it2).second; } delete map2; } for (map<CUniString, map<double, Gdiplus::Font *> * >::iterator it3 = s_GdiPlusFonts.begin(); it3 != s_GdiPlusFonts.end(); it3++) { map<double, Gdiplus::Font *> * map2 = (*it3).second; for (map<double, Gdiplus::Font *>::iterator it4 = map2->begin(); it4 != map2->end(); it4++) { delete (*it4).second; } delete map2; } lock.Unlock(); } /* * Returns a font of the given name (see CFontCache::FONT_...) and height (in pixel). */ CFont * CFontCache::GetFont(CUniString id, int height, bool bold /*= false*/) { CSingleLock lock(&s_CriticalSect, TRUE); map<CUniString, map<int, CFont *> * > & fonts = bold ? s_BoldFonts : s_NormalFonts; //Id map<CUniString, map<int, CFont *> * >::iterator itId = fonts.find(id); map<int, CFont *> * heightMap = NULL; if (itId == fonts.end()) { heightMap = new map<int, CFont *>(); fonts.insert(pair<CUniString, map<int, CFont *> *>(id, heightMap)); } else heightMap = (*itId).second; //Size map<int, CFont *>::iterator itHeight = heightMap->find(height); CFont * font = NULL; if (itHeight == heightMap->end()) { //Create font font = new CFont(); font->CreateFont( height, // nHeight 0, // nWidth 0, // nEscapement 0, // nOrientation bold ? FW_BOLD : FW_NORMAL,// nWeight FALSE, // bItalic FALSE, // bUnderline 0, // cStrikeOut ANSI_CHARSET, // nwchar_tSet OUT_DEFAULT_PRECIS, // nOutPrecision CLIP_DEFAULT_PRECIS, // nClipPrecision DEFAULT_QUALITY, // nQuality DEFAULT_PITCH | FF_SWISS, // nPitchAndFamily id); // lpszFacename heightMap->insert(pair<int, CFont*>(height, font)); } else font = (*itHeight).second; lock.Unlock(); return font; } /* * Returns a font of the given name (see CFontCache::FONT_...) and size (in pixel or point). * * 'unitIsPoint' - If true, the size is interpreted as point, otherwise as pixel */ Gdiplus::Font * CFontCache::GetGdiPlusFont(CUniString id, double size, bool unitIsPoint /*= true*/) { InitPrivateFontCollection(); CSingleLock lock(&s_CriticalSect, TRUE); //Id map<CUniString, map<double, Gdiplus::Font *> * >::iterator itId = s_GdiPlusFonts.find(id); map<double, Gdiplus::Font *> * heightMap = NULL; if (itId == s_GdiPlusFonts.end()) { heightMap = new map<double, Gdiplus::Font *>(); s_GdiPlusFonts.insert(pair<const wchar_t *, map<double, Gdiplus::Font *> *>(id, heightMap)); } else heightMap = (*itId).second; //Size map<double, Gdiplus::Font *>::iterator itHeight = heightMap->find(size); Gdiplus::Font * font = NULL; if (itHeight == heightMap->end()) { //Is the font a private one? set<CUniString>::iterator itPrivate = s_PrivateGdiPlusFonts.find(id); if (itPrivate != s_PrivateGdiPlusFonts.end()) //Private { //Create font if (unitIsPoint) font = new Gdiplus::Font(id, (Gdiplus::REAL)size, FontStyleRegular, UnitPoint, s_GdiPlusFontCollection); else font = new Gdiplus::Font(id, (Gdiplus::REAL)size, FontStyleRegular, UnitPixel, s_GdiPlusFontCollection); } else //Normal system font { //Create font if (unitIsPoint) font = new Gdiplus::Font(id, (Gdiplus::REAL)size, FontStyleRegular); else font = new Gdiplus::Font(id, (Gdiplus::REAL)size, FontStyleRegular, UnitPixel); } heightMap->insert(pair<double, Gdiplus::Font*>(size, font)); } else font = (*itHeight).second; lock.Unlock(); return font; } } //end namespace
28.186603
130
0.648786
PRImA-Research-Lab
a77d5d08599b35023ed74a3c445c214264380b15
9,544
cpp
C++
Applications/CLI/ogs.cpp
OlafKolditz/ogs
e33400e1d9503d33ce80509a3441a873962ad675
[ "BSD-4-Clause" ]
1
2020-03-24T13:33:52.000Z
2020-03-24T13:33:52.000Z
Applications/CLI/ogs.cpp
OlafKolditz/ogs
e33400e1d9503d33ce80509a3441a873962ad675
[ "BSD-4-Clause" ]
1
2021-09-02T14:21:33.000Z
2021-09-02T14:21:33.000Z
Applications/CLI/ogs.cpp
OlafKolditz/ogs
e33400e1d9503d33ce80509a3441a873962ad675
[ "BSD-4-Clause" ]
1
2020-07-15T05:55:55.000Z
2020-07-15T05:55:55.000Z
/** * \date 2014-08-04 * \brief Implementation of OpenGeoSys simulation application * * \copyright * Copyright (c) 2012-2020, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license * */ #include <tclap/CmdLine.h> #include <chrono> #ifndef _WIN32 #ifdef __APPLE__ #include <xmmintrin.h> #else #include <cfenv> #endif // __APPLE__ #endif // _WIN32 #ifdef USE_PETSC #include <vtkMPIController.h> #include <vtkSmartPointer.h> #endif // BaseLib #include "BaseLib/ConfigTreeUtil.h" #include "BaseLib/DateTools.h" #include "BaseLib/FileTools.h" #include "BaseLib/RunTime.h" #include "BaseLib/TemplateLogogFormatterSuppressedGCC.h" #include "Applications/ApplicationsLib/LinearSolverLibrarySetup.h" #include "Applications/ApplicationsLib/LogogSetup.h" #include "Applications/ApplicationsLib/ProjectData.h" #include "Applications/ApplicationsLib/TestDefinition.h" #include "Applications/InSituLib/Adaptor.h" #include "InfoLib/CMakeInfo.h" #include "InfoLib/GitInfo.h" #include "ProcessLib/TimeLoop.h" #include "NumLib/NumericsConfig.h" #ifdef OGS_USE_PYTHON #include "ogs_embedded_python.h" #endif int main(int argc, char* argv[]) { // Parse CLI arguments. TCLAP::CmdLine cmd( "OpenGeoSys-6 software.\n" "Copyright (c) 2012-2020, OpenGeoSys Community " "(http://www.opengeosys.org) " "Distributed under a Modified BSD License. " "See accompanying file LICENSE.txt or " "http://www.opengeosys.org/project/license\n" "version: " + GitInfoLib::GitInfo::ogs_version + "\n" + "CMake arguments: " + CMakeInfoLib::CMakeInfo::cmake_args, ' ', GitInfoLib::GitInfo::ogs_version); TCLAP::ValueArg<std::string> reference_path_arg( "r", "reference", "Run output result comparison after successful simulation comparing to " "all files in the given path.", false, "", "PATH"); cmd.add(reference_path_arg); TCLAP::UnlabeledValueArg<std::string> project_arg( "project-file", "Path to the ogs6 project file.", true, "", "PROJECT_FILE"); cmd.add(project_arg); TCLAP::ValueArg<std::string> outdir_arg("o", "output-directory", "the output directory to write to", false, "", "PATH"); cmd.add(outdir_arg); TCLAP::ValueArg<std::string> log_level_arg("l", "log-level", "the verbosity of logging " "messages: none, error, warn, " "info, debug, all", false, #ifdef NDEBUG "info", #else "all", #endif "LOG_LEVEL"); cmd.add(log_level_arg); TCLAP::SwitchArg nonfatal_arg("", "config-warnings-nonfatal", "warnings from parsing the configuration " "file will not trigger program abortion"); cmd.add(nonfatal_arg); TCLAP::SwitchArg unbuffered_cout_arg("", "unbuffered-std-out", "use unbuffered standard output"); cmd.add(unbuffered_cout_arg); #ifndef _WIN32 // TODO: On windows floating point exceptions are not handled // currently TCLAP::SwitchArg enable_fpe_arg("", "enable-fpe", "enables floating point exceptions"); cmd.add(enable_fpe_arg); #endif // _WIN32 cmd.parse(argc, argv); // deactivate buffer for standard output if specified if (unbuffered_cout_arg.isSet()) { std::cout.setf(std::ios::unitbuf); } ApplicationsLib::LogogSetup logog_setup; logog_setup.setLevel(log_level_arg.getValue()); INFO("This is OpenGeoSys-6 version %s.", GitInfoLib::GitInfo::ogs_version.c_str()); #ifndef _WIN32 // On windows this command line option is not present. // Enable floating point exceptions if (enable_fpe_arg.isSet()) { #ifdef __APPLE__ _MM_SET_EXCEPTION_MASK(_MM_GET_EXCEPTION_MASK() & ~_MM_MASK_INVALID); #else feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW); #endif // __APPLE__ } #endif // _WIN32 #ifdef OGS_USE_PYTHON pybind11::scoped_interpreter guard = ApplicationsLib::setupEmbeddedPython(); (void)guard; #endif BaseLib::RunTime run_time; { auto const start_time = std::chrono::system_clock::now(); auto const time_str = BaseLib::formatDate(start_time); INFO("OGS started on %s.", time_str.c_str()); } std::unique_ptr<ApplicationsLib::TestDefinition> test_definition; auto ogs_status = EXIT_SUCCESS; try { bool solver_succeeded = false; { ApplicationsLib::LinearSolverLibrarySetup linear_solver_library_setup(argc, argv); #if defined(USE_PETSC) vtkSmartPointer<vtkMPIController> controller = vtkSmartPointer<vtkMPIController>::New(); controller->Initialize(&argc, &argv, 1); vtkMPIController::SetGlobalController(controller); logog_setup.setFormatter( std::make_unique<BaseLib::TemplateLogogFormatterSuppressedGCC< TOPIC_LEVEL_FLAG | TOPIC_FILE_NAME_FLAG | TOPIC_LINE_NUMBER_FLAG>>()); #endif run_time.start(); auto project_config = BaseLib::makeConfigTree( project_arg.getValue(), !nonfatal_arg.getValue(), "OpenGeoSysProject"); BaseLib::setProjectDirectory( BaseLib::extractPath(project_arg.getValue())); ProjectData project(*project_config, BaseLib::getProjectDirectory(), outdir_arg.getValue()); if (!reference_path_arg.isSet()) { // Ignore the test_definition section. project_config->ignoreConfigParameter("test_definition"); } else { test_definition = std::make_unique<ApplicationsLib::TestDefinition>( //! \ogs_file_param{prj__test_definition} project_config->getConfigSubtree("test_definition"), reference_path_arg.getValue(), outdir_arg.getValue()); INFO("Cleanup possible output files before running ogs."); BaseLib::removeFiles(test_definition->getOutputFiles()); } #ifdef USE_INSITU auto isInsituConfigured = false; //! \ogs_file_param{prj__insitu} if (auto t = project_config->getConfigSubtreeOptional("insitu")) { InSituLib::Initialize( //! \ogs_file_param{prj__insitu__scripts} t->getConfigSubtree("scripts"), BaseLib::extractPath(project_arg.getValue())); isInsituConfigured = true; } #else project_config->ignoreConfigParameter("insitu"); #endif INFO("Initialize processes."); for (auto& p : project.getProcesses()) { p->initialize(); } // Check intermediately that config parsing went fine. project_config.checkAndInvalidate(); BaseLib::ConfigTree::assertNoSwallowedErrors(); BaseLib::ConfigTree::assertNoSwallowedErrors(); BaseLib::ConfigTree::assertNoSwallowedErrors(); INFO("Solve processes."); auto& time_loop = project.getTimeLoop(); time_loop.initialize(); solver_succeeded = time_loop.loop(); #ifdef USE_INSITU if (isInsituConfigured) InSituLib::Finalize(); #endif INFO("[time] Execution took %g s.", run_time.elapsed()); #if defined(USE_PETSC) controller->Finalize(1); #endif } // This nested scope ensures that everything that could possibly // possess a ConfigTree is destructed before the final check below is // done. BaseLib::ConfigTree::assertNoSwallowedErrors(); ogs_status = solver_succeeded ? EXIT_SUCCESS : EXIT_FAILURE; } catch (std::exception& e) { ERR(e.what()); ogs_status = EXIT_FAILURE; } { auto const end_time = std::chrono::system_clock::now(); auto const time_str = BaseLib::formatDate(end_time); INFO("OGS terminated on %s.", time_str.c_str()); } if (ogs_status == EXIT_FAILURE) { ERR("OGS terminated with error."); return EXIT_FAILURE; } if (test_definition == nullptr) { // There are no tests, so just exit; return ogs_status; } INFO(""); INFO("##########################################"); INFO("# Running tests #"); INFO("##########################################"); INFO(""); if (!test_definition->runTests()) { ERR("One of the tests failed."); return EXIT_FAILURE; } return EXIT_SUCCESS; }
32.462585
80
0.576907
OlafKolditz
a77df707c2889771045e50b016329560b5f64f4d
2,289
cpp
C++
src/defaultroleweight.cpp
Alatun-Rom/Dwarf-Therapist
99b8e0783ec4fa21359f7b148524fec574c1fba1
[ "MIT" ]
362
2017-09-30T09:35:01.000Z
2022-02-24T14:45:48.000Z
src/defaultroleweight.cpp
Alatun-Rom/Dwarf-Therapist
99b8e0783ec4fa21359f7b148524fec574c1fba1
[ "MIT" ]
170
2017-09-18T16:11:23.000Z
2022-03-31T21:36:21.000Z
src/defaultroleweight.cpp
Alatun-Rom/Dwarf-Therapist
99b8e0783ec4fa21359f7b148524fec574c1fba1
[ "MIT" ]
54
2017-09-20T08:30:21.000Z
2022-03-29T02:55:24.000Z
/* Dwarf Therapist Copyright (c) 2018 Clement Vuchener 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 "defaultroleweight.h" #include "standardpaths.h" DefaultRoleWeight DefaultRoleWeight::attributes("attributes", 0.25); DefaultRoleWeight DefaultRoleWeight::skills("skills", 1.0); DefaultRoleWeight DefaultRoleWeight::facets("traits", 0.20); DefaultRoleWeight DefaultRoleWeight::beliefs("beliefs", 0.20); DefaultRoleWeight DefaultRoleWeight::goals("goals", 0.10); DefaultRoleWeight DefaultRoleWeight::needs("needs", 0.10); DefaultRoleWeight DefaultRoleWeight::preferences("prefs", 0.15); DefaultRoleWeight::DefaultRoleWeight(const char *key, float default_value) : m_value_key(QString("options/default_%1_weight").arg(key)) , m_overwrite_key(QString("options/overwrite_default_%1_weight").arg(key)) , m_default_value(default_value) , m_value(default_value) { } void DefaultRoleWeight::update() { auto s = StandardPaths::settings(); m_overwrite = s->value(m_overwrite_key, s->contains(m_value_key)).toBool(); m_value = s->value(m_value_key, m_default_value).toFloat(); } void DefaultRoleWeight::update_all() { attributes.update(); skills.update(); facets.update(); beliefs.update(); goals.update(); needs.update(); preferences.update(); }
36.919355
79
0.771953
Alatun-Rom
a7809b99d206bc39ac2a402fd7f708d07dd1c1e0
4,989
cpp
C++
src/execution/operator/set/physical_recursive_cte.cpp
kimmolinna/duckdb
f46c5e5d2162ac3163e76985a01fb6a049eb170f
[ "MIT" ]
1
2022-01-06T17:44:07.000Z
2022-01-06T17:44:07.000Z
src/execution/operator/set/physical_recursive_cte.cpp
kimmolinna/duckdb
f46c5e5d2162ac3163e76985a01fb6a049eb170f
[ "MIT" ]
32
2021-09-24T23:50:09.000Z
2022-03-29T09:37:26.000Z
src/execution/operator/set/physical_recursive_cte.cpp
kimmolinna/duckdb
f46c5e5d2162ac3163e76985a01fb6a049eb170f
[ "MIT" ]
null
null
null
#include "duckdb/execution/operator/set/physical_recursive_cte.hpp" #include "duckdb/common/vector_operations/vector_operations.hpp" #include "duckdb/common/types/chunk_collection.hpp" #include "duckdb/execution/aggregate_hashtable.hpp" #include "duckdb/parallel/pipeline.hpp" #include "duckdb/storage/buffer_manager.hpp" #include "duckdb/parallel/task_scheduler.hpp" #include "duckdb/execution/executor.hpp" #include "duckdb/parallel/event.hpp" namespace duckdb { PhysicalRecursiveCTE::PhysicalRecursiveCTE(vector<LogicalType> types, bool union_all, unique_ptr<PhysicalOperator> top, unique_ptr<PhysicalOperator> bottom, idx_t estimated_cardinality) : PhysicalOperator(PhysicalOperatorType::RECURSIVE_CTE, move(types), estimated_cardinality), union_all(union_all) { children.push_back(move(top)); children.push_back(move(bottom)); } PhysicalRecursiveCTE::~PhysicalRecursiveCTE() { } //===--------------------------------------------------------------------===// // Sink //===--------------------------------------------------------------------===// class RecursiveCTEState : public GlobalSinkState { public: explicit RecursiveCTEState(ClientContext &context, const PhysicalRecursiveCTE &op) : new_groups(STANDARD_VECTOR_SIZE) { ht = make_unique<GroupedAggregateHashTable>(BufferManager::GetBufferManager(context), op.types, vector<LogicalType>(), vector<BoundAggregateExpression *>()); } unique_ptr<GroupedAggregateHashTable> ht; bool intermediate_empty = true; ChunkCollection intermediate_table; idx_t chunk_idx = 0; SelectionVector new_groups; }; unique_ptr<GlobalSinkState> PhysicalRecursiveCTE::GetGlobalSinkState(ClientContext &context) const { return make_unique<RecursiveCTEState>(context, *this); } idx_t PhysicalRecursiveCTE::ProbeHT(DataChunk &chunk, RecursiveCTEState &state) const { Vector dummy_addresses(LogicalType::POINTER); // Use the HT to eliminate duplicate rows idx_t new_group_count = state.ht->FindOrCreateGroups(chunk, dummy_addresses, state.new_groups); // we only return entries we have not seen before (i.e. new groups) chunk.Slice(state.new_groups, new_group_count); return new_group_count; } SinkResultType PhysicalRecursiveCTE::Sink(ExecutionContext &context, GlobalSinkState &state, LocalSinkState &lstate, DataChunk &input) const { auto &gstate = (RecursiveCTEState &)state; if (!union_all) { idx_t match_count = ProbeHT(input, gstate); if (match_count > 0) { gstate.intermediate_table.Append(input); } } else { gstate.intermediate_table.Append(input); } return SinkResultType::NEED_MORE_INPUT; } //===--------------------------------------------------------------------===// // Source //===--------------------------------------------------------------------===// void PhysicalRecursiveCTE::GetData(ExecutionContext &context, DataChunk &chunk, GlobalSourceState &gstate_p, LocalSourceState &lstate) const { auto &gstate = (RecursiveCTEState &)*sink_state; while (chunk.size() == 0) { if (gstate.chunk_idx < gstate.intermediate_table.ChunkCount()) { // scan any chunks we have collected so far chunk.Reference(gstate.intermediate_table.GetChunk(gstate.chunk_idx)); gstate.chunk_idx++; break; } else { // we have run out of chunks // now we need to recurse // we set up the working table as the data we gathered in this iteration of the recursion working_table->Reset(); working_table->Merge(gstate.intermediate_table); // and we clear the intermediate table gstate.intermediate_table.Reset(); gstate.chunk_idx = 0; // now we need to re-execute all of the pipelines that depend on the recursion ExecuteRecursivePipelines(context); // check if we obtained any results // if not, we are done if (gstate.intermediate_table.Count() == 0) { break; } } } } void PhysicalRecursiveCTE::ExecuteRecursivePipelines(ExecutionContext &context) const { if (pipelines.empty()) { throw InternalException("Missing pipelines for recursive CTE"); } for (auto &pipeline : pipelines) { auto sink = pipeline->GetSink(); if (sink != this) { // reset the sink state for any intermediate sinks sink->sink_state = sink->GetGlobalSinkState(context.client); } for (auto &op : pipeline->GetOperators()) { if (op) { op->op_state = op->GetGlobalOperatorState(context.client); } } pipeline->Reset(); } auto &executor = pipelines[0]->executor; vector<shared_ptr<Event>> events; executor.ReschedulePipelines(pipelines, events); while (true) { executor.WorkOnTasks(); if (executor.HasError()) { executor.ThrowException(); } bool finished = true; for (auto &event : events) { if (!event->IsFinished()) { finished = false; break; } } if (finished) { // all pipelines finished: done! break; } } } } // namespace duckdb
33.26
119
0.676889
kimmolinna
a782c7e4694aa5e8f9c94f0a891038ca5f6f0422
13,904
hpp
C++
zeccup/zeccup/military/desert/medical.hpp
LISTINGS09/ZECCUP
e0ad1fae580dde6e5d90903b1295fecc41684f63
[ "Naumen", "Condor-1.1", "MS-PL" ]
3
2016-08-29T09:23:49.000Z
2019-06-13T20:29:28.000Z
zeccup/zeccup/military/desert/medical.hpp
LISTINGS09/ZECCUP
e0ad1fae580dde6e5d90903b1295fecc41684f63
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
zeccup/zeccup/military/desert/medical.hpp
LISTINGS09/ZECCUP
e0ad1fae580dde6e5d90903b1295fecc41684f63
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
class MedicalLarge { name = $STR_ZECCUP_MedicalLarge; // EAST class Hospital_CUP_O_TK { name = $STR_ZECCUP_MilitaryDesert_MedicalLarge_Hospital_CUP_O_TK; // Credit: 2600K icon = "\ca\data\flag_rus_co.paa"; side = 8; class Object0 {side = 8; vehicle = "TK_WarfareBFieldhHospital_Base_EP1"; rank = ""; position[] = {0.195923,-5.93896,0}; dir = 210;}; class Object1 {side = 8; vehicle = "Land_CamoNetVar_EAST_EP1"; rank = ""; position[] = {-11.6127,-2.72363,0}; dir = 90;}; class Object2 {side = 8; vehicle = "Land_HBarrier5"; rank = ""; position[] = {-15.3256,-8.50635,0}; dir = 270;}; class Object3 {side = 8; vehicle = "Land_fort_bagfence_corner"; rank = ""; position[] = {-6.59546,-8.46338,0}; dir = 270;}; class Object4 {side = 8; vehicle = "Land_HBarrier3"; rank = ""; position[] = {-15.5317,-9.78564,0}; dir = 0;}; class Object5 {side = 8; vehicle = "Land_HBarrier3"; rank = ""; position[] = {-9.46423,-11.7817,0}; dir = 270;}; class Object7 {side = 8; vehicle = "FoldTable"; rank = ""; position[] = {-9.75,-3.375,0}; dir = 30;}; class Object8 {side = 8; vehicle = "Land_WaterBarrel_F"; rank = ""; position[] = {-4.96875,-8.81641,0}; dir = 112.818;}; class Object9 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {-10.4955,-3.6665,0}; dir = 240;}; class Object10 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {-9.75452,-4.38281,0}; dir = 315;}; class Object11 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {-9.93164,-2.69141,0}; dir = 15;}; class Object12 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {-9.00452,-3.0835,0}; dir = 45;}; class Object13 {side = 8; vehicle = "Body"; rank = ""; position[] = {-0.707642,-3.521,0}; dir = 315;}; // Z: 0.0999999 class Object14 {side = 8; vehicle = "Barrel4"; rank = ""; position[] = {-13.25,-8.625,0}; dir = 0;}; class Object15 {side = 8; vehicle = "Barrel4"; rank = ""; position[] = {-13.9216,-7.93555,0}; dir = 0;}; class Object16 {side = 8; vehicle = "Barrel4"; rank = ""; position[] = {-14.0197,-8.65381,0}; dir = 105;}; class Object17 {side = 8; vehicle = "Land_HBarrier5"; rank = ""; position[] = {-15.3256,0.368652,0}; dir = 270;}; class Object18 {side = 8; vehicle = "Land_fort_bagfence_corner"; rank = ""; position[] = {-2.52954,8.83838,0}; dir = 90;}; class Object19 {side = 8; vehicle = "Land_fort_bagfence_long"; rank = ""; position[] = {-13.3904,6.23584,0}; dir = 0;}; class Object20 {side = 8; vehicle = "Land_fort_bagfence_long"; rank = ""; position[] = {-5.14038,6.36084,0}; dir = 0;}; class Object21 {side = 8; vehicle = "Land_HBarrier1"; rank = ""; position[] = {-7.11633,6.49658,0}; dir = 0;}; class Object22 {side = 8; vehicle = "Land_HBarrier1"; rank = ""; position[] = {-3.11633,6.37158,0}; dir = 0;}; class Object23 {side = 8; vehicle = "Land_HBarrier1"; rank = ""; position[] = {-11.3663,6.37158,0}; dir = 0;}; class Object24 {side = 8; vehicle = "Land_HBarrier1"; rank = ""; position[] = {-15.2413,6.12158,0}; dir = 0;}; class Object25 {side = 8; vehicle = "Land_FieldToilet_F"; rank = ""; position[] = {-3.375,4.25,0}; dir = 345.002;}; class Object26 {side = 8; vehicle = "AmmoCrates_NoInteractive_Small"; rank = ""; position[] = {-13.8955,1.35156,0}; dir = 90;}; class Object27 {side = 8; vehicle = "FoldTable"; rank = ""; position[] = {-9.29749,2.15967,0}; dir = 120;}; class Object28 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {-10.3053,2.16406,0}; dir = 45;}; class Object29 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {-9.00635,1.41406,0}; dir = 135;}; class Object30 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {-9.58862,2.90527,0}; dir = 330;}; class Object31 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {-8.61414,2.34131,0}; dir = 105;}; class Object32 {side = 8; vehicle = "MetalBarrel_burning_F"; rank = ""; position[] = {-3.75,2.375,0}; dir = 105;}; class Object33 {side = 8; vehicle = "Land_Pallets_F"; rank = ""; position[] = {-4.00256,14.0288,0}; dir = 90;}; class Object34 {side = 8; vehicle = "Land_Pallet_F"; rank = ""; position[] = {-2.61108,15.373,0}; dir = 192.542;}; class Object35 {side = 8; vehicle = "Land_fort_rampart_EP1"; rank = ""; position[] = {8.69763,-11.3872,0}; dir = 300;}; class Object36 {side = 8; vehicle = "Barrel4"; rank = ""; position[] = {8.96472,-9.39063,0}; dir = 330;}; class Object37 {side = 8; vehicle = "Barrel4"; rank = ""; position[] = {8.22583,-9.4541,0}; dir = 330;}; class Object38 {side = 8; vehicle = "Barrel4"; rank = ""; position[] = {8.5,-10.125,0}; dir = 75;}; class Object39 {side = 8; vehicle = "Land_fort_artillery_nest_EP1"; rank = ""; position[] = {18.4866,6.375,0}; dir = 90;}; class Object40 {side = 8; vehicle = "TK_WarfareBFieldhHospital_Base_EP1"; rank = ""; position[] = {4.73523,6.29248,0}; dir = 180;}; class Object41 {side = 8; vehicle = "Land_CamoNetVar_EAST_EP1"; rank = ""; position[] = {14.1373,6.52637,0}; dir = 90;}; class Object42 {side = 8; vehicle = "Land_fort_rampart_EP1"; rank = ""; position[] = {6.125,12.6494,0}; dir = 180;}; class Object43 {side = 8; vehicle = "AmmoCrates_NoInteractive_Large"; rank = ""; position[] = {13.9001,11.2822,0}; dir = 300;}; class Object44 {side = 8; vehicle = "FoldTable"; rank = ""; position[] = {13.8027,7.09961,0}; dir = 330;}; class Object45 {side = 8; vehicle = "Land_WaterBarrel_F"; rank = ""; position[] = {16.8672,3.83154,0}; dir = 123.359;}; class Object46 {side = 8; vehicle = "Body"; rank = ""; position[] = {15.1174,2.87842,0}; dir = 150;}; class Object47 {side = 8; vehicle = "Body"; rank = ""; position[] = {12.2452,1.75684,0}; dir = 180;}; class Object48 {side = 8; vehicle = "Body"; rank = ""; position[] = {13.6187,2.13037,0}; dir = 165;}; class Object49 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {13.6823,6.30811,0}; dir = 180;}; class Object50 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {14.6732,6.5918,0}; dir = 255;}; class Object51 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {13.9232,7.89111,0}; dir = 345;}; class Object52 {side = 8; vehicle = "FoldChair"; rank = ""; position[] = {13.1201,7.28418,0}; dir = 315;}; class Object53 {side = 8; vehicle = "AmmoCrate_NoInteractive_"; rank = ""; position[] = {14.7791,11.0151,0}; dir = 300;}; class Object54 {side = 8; vehicle = "Land_Pallets_stack_F"; rank = ""; position[] = {17.2242,5.30664,0}; dir = 196.374;}; }; // WEST class Hospital_CUP_B_USMC { name = $STR_ZECCUP_MilitaryDesert_MedicalLarge_Hospital_CUP_B_USMC; // Credit: 2600K icon = "\ca\data\flag_usa_co.paa"; side = 8; class Object0 {side = 8; vehicle = "Land_CamoNetVar_NATO_EP1"; rank = ""; position[] = {-7.36267,-7.84863,0}; dir = 90;}; class Object1 {side = 8; vehicle = "Land_HBarrier_large"; rank = ""; position[] = {-1.0127,-13.3354,0}; dir = 0;}; class Object2 {side = 8; vehicle = "Land_HBarrier_large"; rank = ""; position[] = {-9.2627,-13.5854,0}; dir = 0;}; class Object3 {side = 8; vehicle = "Land_HBarrier3"; rank = ""; position[] = {-12.6608,-10.0933,0}; dir = 90;}; class Object4 {side = 8; vehicle = "AmmoCrates_NoInteractive_Large"; rank = ""; position[] = {-8.70935,-11.6304,0}; dir = 0;}; class Object5 {side = 8; vehicle = "Land_HBarrier1"; rank = ""; position[] = {-11.2512,-2.49072,0}; dir = 240;}; class Object6 {side = 8; vehicle = "Land_HBarrier1"; rank = ""; position[] = {-2.61743,-2.36914,0}; dir = 300;}; class Object7 {side = 8; vehicle = "Land_BagFence_Round_F"; rank = ""; position[] = {-12.2045,-3.12598,0}; dir = 135;}; class Object8 {side = 8; vehicle = "Land_BagFence_Long_F"; rank = ""; position[] = {-12.7654,-8.62891,0}; dir = 270;}; class Object9 {side = 8; vehicle = "Land_BagFence_Long_F"; rank = ""; position[] = {-12.7655,-5.75391,0}; dir = 270;}; class Object10 {side = 8; vehicle = "Land_CampingTable_F"; rank = ""; position[] = {-6.875,-4.125,0}; dir = 315.002;}; class Object11 {side = 8; vehicle = "Land_CampingTable_F"; rank = ""; position[] = {-6.12183,-8.74609,0}; dir = 59.392;}; class Object12 {side = 8; vehicle = "Land_CampingTable_F"; rank = ""; position[] = {-6.30188,-4.69873,0}; dir = 134.559;}; class Object13 {side = 8; vehicle = "Land_CampingTable_F"; rank = ""; position[] = {-6.82617,-9.15381,0}; dir = 240.001;}; class Object14 {side = 8; vehicle = "Land_CampingChair_V1_F"; rank = ""; position[] = {-7.58191,-4.03955,0}; dir = 329.971;}; class Object15 {side = 8; vehicle = "Land_CampingChair_V1_F"; rank = ""; position[] = {-6.34473,-5.36133,0}; dir = 119.98;}; class Object16 {side = 8; vehicle = "Land_CampingChair_V1_F"; rank = ""; position[] = {-7.0918,-9.81445,0}; dir = 254.978;}; class Object17 {side = 8; vehicle = "Land_CampingChair_V1_F"; rank = ""; position[] = {-5.49463,-8.96143,0}; dir = 44.9741;}; class Object18 {side = 8; vehicle = "Land_CampingChair_V1_F"; rank = ""; position[] = {-7.50916,-8.9707,0}; dir = 239.966;}; class Object19 {side = 8; vehicle = "Land_CampingChair_V1_F"; rank = ""; position[] = {-5.77698,-7.9707,0}; dir = 89.9435;}; class Object20 {side = 8; vehicle = "Land_CampingChair_V1_F"; rank = ""; position[] = {-5.46082,-4.83203,0}; dir = 164.938;}; class Object21 {side = 8; vehicle = "Land_CampingChair_V1_F"; rank = ""; position[] = {-6.875,-3.41797,0}; dir = 314.957;}; class Object22 {side = 8; vehicle = "AmmoCrates_NoInteractive_Small"; rank = ""; position[] = {-4.35156,-11.6455,0}; dir = 0;}; class Object23 {side = 8; vehicle = "Land_MetalBarrel_F"; rank = ""; position[] = {-5.5,-11.875,0}; dir = 285.016;}; class Object24 {side = 8; vehicle = "Land_MetalBarrel_F"; rank = ""; position[] = {-7.62488,-11.75,0}; dir = 194.982;}; class Object25 {side = 8; vehicle = "B_Slingload_01_Medevac_F"; rank = ""; position[] = {-6,8.25,0}; dir = 300;}; class Object27 {side = 8; vehicle = "Land_HBarrier1"; rank = ""; position[] = {1.7594,11.376,0}; dir = 330;}; class Object28 {side = 8; vehicle = "Land_HBarrier1"; rank = ""; position[] = {2.00574,12.7427,0}; dir = 30;}; class Object29 {side = 8; vehicle = "Land_HBarrier1"; rank = ""; position[] = {-1.36926,13.2573,0}; dir = 285;}; class Object30 {side = 8; vehicle = "Land_PaperBox_open_empty_F"; rank = ""; position[] = {-7.87537,6.875,0}; dir = 300;}; class Object31 {side = 8; vehicle = "Land_PaperBox_closed_F"; rank = ""; position[] = {-6.49158,5.36523,0}; dir = 150;}; class Object32 {side = 8; vehicle = "MetalBarrel_burning_F"; rank = ""; position[] = {-1.5,0.5,0}; dir = 315;}; class Object33 {side = 8; vehicle = "AmmoCrates_NoInteractive_Small"; rank = ""; position[] = {-8.02747,5.28076,0}; dir = 240;}; class Object34 {side = 8; vehicle = "Land_Pallets_stack_F"; rank = ""; position[] = {-6.125,11.125,0}; dir = 194.999;}; class Object35 {side = 8; vehicle = "Land_HBarrier5"; rank = ""; position[] = {4.11865,-13.0493,0}; dir = 6.83019e-006;}; class Object36 {side = 8; vehicle = "Land_HBarrier5"; rank = ""; position[] = {15.4506,-8.49365,0}; dir = 90;}; class Object37 {side = 8; vehicle = "Land_HBarrier5"; rank = ""; position[] = {14.2563,-12.9507,0}; dir = 180;}; class Object38 {side = 8; vehicle = "Body"; rank = ""; position[] = {6.8501,-7.96289,0}; dir = 90;}; // Z: 0.0908942 class Object39 {side = 8; vehicle = "Land_MetalBarrel_F"; rank = ""; position[] = {11.375,-11.75,0}; dir = 285.016;}; class Object40 {side = 8; vehicle = "Land_MetalBarrel_F"; rank = ""; position[] = {10.5001,-11.75,0}; dir = 194.982;}; class Object41 {side = 8; vehicle = "Land_MetalBarrel_F"; rank = ""; position[] = {14.5,-14.125,0}; dir = 285.016;}; class Object42 {side = 8; vehicle = "Land_MetalBarrel_F"; rank = ""; position[] = {13.6251,-14.125,0}; dir = 194.982;}; class Object43 {side = 8; vehicle = "US_WarfareBFieldhHospital_Base_EP1"; rank = ""; position[] = {8.77747,-0.0498047,0}; dir = 0;}; class Object44 {side = 8; vehicle = "Land_HBarrier_large"; rank = ""; position[] = {6.7373,12.0396,0}; dir = 0;}; class Object45 {side = 8; vehicle = "Land_HBarrier5"; rank = ""; position[] = {15.7006,7.75635,0}; dir = 90;}; class Object46 {side = 8; vehicle = "Land_HBarrier5"; rank = ""; position[] = {11.3687,12.3257,0}; dir = 6.83019e-006;}; class Object47 {side = 8; vehicle = "Land_HBarrier5"; rank = ""; position[] = {15.7006,2.13135,0}; dir = 90;}; class Object48 {side = 8; vehicle = "Land_HBarrier3"; rank = ""; position[] = {15.7142,11.0317,0}; dir = 90;}; class Object49 {side = 8; vehicle = "Land_ToiletBox_F"; rank = ""; position[] = {7.12146,9.70947,0}; dir = 30.0776;}; class Object50 {side = 8; vehicle = "Land_WaterTank_F"; rank = ""; position[] = {5.12585,10.2192,0}; dir = 0.0586366;}; class Object51 {side = 8; vehicle = "Land_Sacks_heap_F"; rank = ""; position[] = {14.25,11.125,0}; dir = 195;}; class Object52 {side = 8; vehicle = "Body"; rank = ""; position[] = {9.41858,4.82324,0}; dir = 90.0001;}; // Z: 0.0926261 class Object53 {side = 8; vehicle = "Body"; rank = ""; position[] = {2.86951,0.118652,0}; dir = 75;}; class Object54 {side = 8; vehicle = "Body"; rank = ""; position[] = {2.61707,1.49707,0}; dir = 105;}; class Object55 {side = 8; vehicle = "Land_MetalBarrel_empty_F"; rank = ""; position[] = {11.1964,10.918,0}; dir = 255;}; class Object56 {side = 8; vehicle = "Land_MetalBarrel_F"; rank = ""; position[] = {10.3746,10.7339,0}; dir = 134.965;}; class Object57 {side = 8; vehicle = "Land_MetalBarrel_F"; rank = ""; position[] = {11.0023,10.1938,0}; dir = 105.016;}; class Object58 {side = 8; vehicle = "Land_Sacks_heap_F"; rank = ""; position[] = {14.5,9.75,0}; dir = 270;}; }; }; class MedicalMedium { name = $STR_ZECCUP_MedicalMedium; }; class MedicalSmall { name = $STR_ZECCUP_MedicalSmall; };
101.489051
135
0.610256
LISTINGS09
a78408805c9ef2a4fb93d43a039d7c3ce3294dfe
2,170
cpp
C++
example/19_multi_viewport/19_multi_viewport.cpp
alecnunn/mud
9e204e2dc65f4a8ab52da3d11e6a261ff279d353
[ "Zlib" ]
1
2019-03-28T20:45:32.000Z
2019-03-28T20:45:32.000Z
example/19_multi_viewport/19_multi_viewport.cpp
alecnunn/mud
9e204e2dc65f4a8ab52da3d11e6a261ff279d353
[ "Zlib" ]
null
null
null
example/19_multi_viewport/19_multi_viewport.cpp
alecnunn/mud
9e204e2dc65f4a8ab52da3d11e6a261ff279d353
[ "Zlib" ]
null
null
null
#include <mud/core.h> #include <19_multi_viewport/19_multi_viewport.h> #include <03_materials/03_materials.h> using namespace mud; size_t viewport_mode(Widget& parent) { std::vector<size_t> num_viewer_vals = { 1, 2, 4 }; ui::label(parent, "num viewports : "); static uint32_t choice = 1; ui::radio_switch(parent, carray<cstring, 3>{ "1", "2", "4" }, choice); return num_viewer_vals[choice]; } void ex_19_multi_viewport(Shell& app, Widget& parent, Dockbar& dockbar) { static float time = 0.f; time += 0.01f; bool multiple_scene = false; static size_t num_viewers = 2; if(Widget* dock = ui::dockitem(dockbar, "Game", carray<uint16_t, 1>{ 1U })) num_viewers = viewport_mode(*dock); Widget& layout = ui::layout(parent); Widget& first_split = ui::board(layout); Widget* second_split = num_viewers > 2 ? &ui::board(layout) : nullptr; std::vector<Viewer*> viewers = {}; if(!multiple_scene) { static Scene scene = { app.m_gfx_system }; for(size_t i = 0; i < num_viewers; ++i) viewers.push_back(&ui::viewer(i >= 2 ? *second_split : first_split, scene)); } else { for(size_t i = 0; i < num_viewers; ++i) viewers.push_back(&ui::scene_viewer(i >= 2 ? *second_split : first_split)); } for(Viewer* viewer : viewers) { ui::orbit_controller(*viewer); Gnode& scene = viewer->m_scene->begin(); for(size_t x = 0; x < 11; ++x) for(size_t y = 0; y < 11; ++y) { vec3 angles = { time + x * 0.21f, 0.f, time + y * 0.37f }; vec3 pos = { -15.f + x * 3.f, 0, -15.f + y * 3.f }; float r = ncosf(time + float(x) * 0.21f); float b = nsinf(time + float(y) * 0.37f); float g = ncosf(time); Colour color = { r, g, b }; Gnode& gnode = gfx::node(scene, {}, pos, quat(angles), vec3(1)); gfx::shape(gnode, Cube(), Symbol(color, Colour::None)); } } } #ifdef _19_MULTI_VIEWPORT_EXE void pump(Shell& app) { shell_context(app.m_ui->begin(), app.m_editor); ex_19_multi_viewport(app, *app.m_editor.m_screen, *app.m_editor.m_dockbar); } int main(int argc, char *argv[]) { Shell app(MUD_RESOURCE_PATH, exec_path(argc, argv).c_str()); app.m_gfx_system.init_pipeline(pipeline_minimal); app.run(pump); } #endif
25.529412
79
0.64977
alecnunn
a78490ca22772fbbe23e1b65bd705acf34432e8a
5,922
hpp
C++
src/DataStructures/Tensor/EagerMath/Determinant.hpp
macedo22/spectre
97b2b7ae356cf86830258cb5f689f1191fdb6ddd
[ "MIT" ]
1
2018-10-01T06:07:16.000Z
2018-10-01T06:07:16.000Z
src/DataStructures/Tensor/EagerMath/Determinant.hpp
macedo22/spectre
97b2b7ae356cf86830258cb5f689f1191fdb6ddd
[ "MIT" ]
4
2018-06-04T20:26:40.000Z
2018-07-27T14:54:55.000Z
src/DataStructures/Tensor/EagerMath/Determinant.hpp
macedo22/spectre
97b2b7ae356cf86830258cb5f689f1191fdb6ddd
[ "MIT" ]
null
null
null
// Distributed under the MIT License. // See LICENSE.txt for details. /// \file /// Defines function for taking the determinant of a rank-2 tensor #pragma once #include "DataStructures/Tensor/Tensor.hpp" #include "Utilities/Gsl.hpp" namespace detail { template <typename Symm, typename Index, typename = std::nullptr_t> struct DeterminantImpl; template <typename Symm, typename Index> struct DeterminantImpl<Symm, Index, Requires<Index::dim == 1>> { template <typename T> static typename T::type apply(const T& tensor) noexcept { return get<0, 0>(tensor); } }; template <typename Symm, typename Index> struct DeterminantImpl<Symm, Index, Requires<Index::dim == 2>> { template <typename T> static typename T::type apply(const T& tensor) noexcept { const auto& t00 = get<0, 0>(tensor); const auto& t01 = get<0, 1>(tensor); const auto& t10 = get<1, 0>(tensor); const auto& t11 = get<1, 1>(tensor); return t00 * t11 - t01 * t10; } }; template <typename Index> struct DeterminantImpl<Symmetry<2, 1>, Index, Requires<Index::dim == 3>> { template <typename T> static typename T::type apply(const T& tensor) noexcept { const auto& t00 = get<0, 0>(tensor); const auto& t01 = get<0, 1>(tensor); const auto& t02 = get<0, 2>(tensor); const auto& t10 = get<1, 0>(tensor); const auto& t11 = get<1, 1>(tensor); const auto& t12 = get<1, 2>(tensor); const auto& t20 = get<2, 0>(tensor); const auto& t21 = get<2, 1>(tensor); const auto& t22 = get<2, 2>(tensor); return t00 * (t11 * t22 - t12 * t21) - t01 * (t10 * t22 - t12 * t20) + t02 * (t10 * t21 - t11 * t20); } }; template <typename Index> struct DeterminantImpl<Symmetry<1, 1>, Index, Requires<Index::dim == 3>> { template <typename T> static typename T::type apply(const T& tensor) noexcept { const auto& t00 = get<0, 0>(tensor); const auto& t01 = get<0, 1>(tensor); const auto& t02 = get<0, 2>(tensor); const auto& t11 = get<1, 1>(tensor); const auto& t12 = get<1, 2>(tensor); const auto& t22 = get<2, 2>(tensor); return t00 * (t11 * t22 - t12 * t12) - t01 * (t01 * t22 - t12 * t02) + t02 * (t01 * t12 - t11 * t02); } }; template <typename Index> struct DeterminantImpl<Symmetry<2, 1>, Index, Requires<Index::dim == 4>> { template <typename T> static typename T::type apply(const T& tensor) noexcept { const auto& t00 = get<0, 0>(tensor); const auto& t01 = get<0, 1>(tensor); const auto& t02 = get<0, 2>(tensor); const auto& t03 = get<0, 3>(tensor); const auto& t10 = get<1, 0>(tensor); const auto& t11 = get<1, 1>(tensor); const auto& t12 = get<1, 2>(tensor); const auto& t13 = get<1, 3>(tensor); const auto& t20 = get<2, 0>(tensor); const auto& t21 = get<2, 1>(tensor); const auto& t22 = get<2, 2>(tensor); const auto& t23 = get<2, 3>(tensor); const auto& t30 = get<3, 0>(tensor); const auto& t31 = get<3, 1>(tensor); const auto& t32 = get<3, 2>(tensor); const auto& t33 = get<3, 3>(tensor); const auto minor1 = t22 * t33 - t23 * t32; const auto minor2 = t21 * t33 - t23 * t31; const auto minor3 = t20 * t33 - t23 * t30; const auto minor4 = t21 * t32 - t22 * t31; const auto minor5 = t20 * t32 - t22 * t30; const auto minor6 = t20 * t31 - t21 * t30; return t00 * (t11 * minor1 - t12 * minor2 + t13 * minor4) - t01 * (t10 * minor1 - t12 * minor3 + t13 * minor5) + t02 * (t10 * minor2 - t11 * minor3 + t13 * minor6) - t03 * (t10 * minor4 - t11 * minor5 + t12 * minor6); } }; template <typename Index> struct DeterminantImpl<Symmetry<1, 1>, Index, Requires<Index::dim == 4>> { template <typename T> static typename T::type apply(const T& tensor) noexcept { const auto& t00 = get<0, 0>(tensor); const auto& t01 = get<0, 1>(tensor); const auto& t02 = get<0, 2>(tensor); const auto& t03 = get<0, 3>(tensor); const auto& t11 = get<1, 1>(tensor); const auto& t12 = get<1, 2>(tensor); const auto& t13 = get<1, 3>(tensor); const auto& t22 = get<2, 2>(tensor); const auto& t23 = get<2, 3>(tensor); const auto& t33 = get<3, 3>(tensor); const auto minor1 = t22 * t33 - t23 * t23; const auto minor2 = t12 * t33 - t23 * t13; const auto minor3 = t02 * t33 - t23 * t03; const auto minor4 = t12 * t23 - t22 * t13; const auto minor5 = t02 * t23 - t22 * t03; const auto minor6 = t02 * t13 - t12 * t03; return t00 * (t11 * minor1 - t12 * minor2 + t13 * minor4) - t01 * (t01 * minor1 - t12 * minor3 + t13 * minor5) + t02 * (t01 * minor2 - t11 * minor3 + t13 * minor6) - t03 * (t01 * minor4 - t11 * minor5 + t12 * minor6); } }; } // namespace detail /// @{ /*! * \ingroup TensorGroup * \brief Computes the determinant of a rank-2 Tensor `tensor`. * * \requires That `tensor` be a rank-2 Tensor, with both indices sharing the * same dimension and type. */ template <typename T, typename Symm, typename Index0, typename Index1> void determinant( const gsl::not_null<Scalar<T>*> det_tensor, const Tensor<T, Symm, index_list<Index0, Index1>>& tensor) noexcept { static_assert(Index0::dim == Index1::dim, "Cannot take the determinant of a Tensor whose Indices are not " "of the same dimensionality."); static_assert(Index0::index_type == Index1::index_type, "Taking the determinant of a mixed Spatial and Spacetime index " "Tensor is not allowed since it's not clear what that means."); get(*det_tensor) = detail::DeterminantImpl<Symm, Index0>::apply(tensor); } template <typename T, typename Symm, typename Index0, typename Index1> Scalar<T> determinant( const Tensor<T, Symm, index_list<Index0, Index1>>& tensor) noexcept { Scalar<T> result{}; determinant(make_not_null(&result), tensor); return result; } /// @}
37.245283
80
0.614826
macedo22
a784bc499e303988d8a73b3303a9d4355e58e35f
1,861
cc
C++
books/principles/search/test-search.cc
BONITA-KWKim/algorithm
94a45c929505e574c06d235d18da4625cc243343
[ "Unlicense" ]
1
2020-06-24T07:34:55.000Z
2020-06-24T07:34:55.000Z
books/principles/search/test-search.cc
BONITA-KWKim/algorithm
94a45c929505e574c06d235d18da4625cc243343
[ "Unlicense" ]
null
null
null
books/principles/search/test-search.cc
BONITA-KWKim/algorithm
94a45c929505e574c06d235d18da4625cc243343
[ "Unlicense" ]
null
null
null
#include <iostream> #include <string> #include "gtest/gtest.h" #include "sequential-search.h" #include "binary-search-tree.h" #include "red-black-tree.h" TEST (SEQUENTIAL, TEST_CASE_001) { BaseSearch *search = new SequentialSearch(); EXPECT_EQ(0, 0); } TEST (BINARY_SEARCH_TREE, TEST_CASE_001) { int search_target = 8; std::string tree_elements = ""; BinarySearchTree *bst_tree = new BinarySearchTree(); BSTNode *head = bst_tree->create_node(1); BSTNode *node1 = bst_tree->create_node(2); BSTNode *node2 = bst_tree->create_node(3); BSTNode *node3 = bst_tree->create_node(4); BSTNode *node4 = bst_tree->create_node(5); BSTNode *node5 = bst_tree->create_node(6); BSTNode *node6 = bst_tree->create_node(7); BSTNode *node7 = bst_tree->create_node(8); bst_tree->insert_node(head, node1); bst_tree->insert_node(head, node2); bst_tree->insert_node(head, node3); bst_tree->insert_node(head, node4); bst_tree->insert_node(head, node5); bst_tree->insert_node(head, node6); bst_tree->insert_node(head, node7); bst_tree->inorder_print_tree (&tree_elements, head); EXPECT_STREQ("1 2 3 4 5 6 7 8 ", tree_elements.c_str()); tree_elements = ""; bst_tree->remove_node(head, 2); bst_tree->remove_node(head, 4); bst_tree->remove_node(head, 7); bst_tree->inorder_print_tree (&tree_elements, head); EXPECT_STREQ("1 3 5 6 8 ", tree_elements.c_str()); // test search BSTNode *test_search = bst_tree->search_node(head, search_target); EXPECT_EQ(search_target, test_search->data); } TEST (REDBLACKTREE, TEST_CASE_001) { RedBlackTree *red_black_tree = new RedBlackTree(); red_black_tree->version_info(); EXPECT_EQ(0, 0); } int main (int argc, char *argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
28.630769
70
0.68619
BONITA-KWKim
a786202d692a972fd9b5663ff265857d3848244c
8,040
cpp
C++
src/wolf3d_shaders/ws_deferred.cpp
Daivuk/wolf3d-shaders
0f3c0ab82422d068f6440af6649603774f0543b2
[ "DOC", "Unlicense" ]
5
2019-09-14T14:08:46.000Z
2021-04-27T11:21:43.000Z
src/wolf3d_shaders/ws_deferred.cpp
Daivuk/wolf3d-shaders
0f3c0ab82422d068f6440af6649603774f0543b2
[ "DOC", "Unlicense" ]
null
null
null
src/wolf3d_shaders/ws_deferred.cpp
Daivuk/wolf3d-shaders
0f3c0ab82422d068f6440af6649603774f0543b2
[ "DOC", "Unlicense" ]
1
2019-10-19T04:19:46.000Z
2019-10-19T04:19:46.000Z
#include "ws.h" #include "WL_DEF.H" ws_GBuffer ws_gbuffer; std::vector<ws_PointLight> ws_active_lights; GLuint ws_create_sphere() { GLuint handle; glGenBuffers(1, &handle); glBindBuffer(GL_ARRAY_BUFFER, handle); ws_Vector3 *pVertices = new ws_Vector3[WS_SPHERE_VERT_COUNT]; int hseg = 8; int vseg = 8; auto pVerts = pVertices; { auto cos_h = cosf(1.0f / (float)hseg * (float)M_PI); auto sin_h = sinf(1.0f / (float)hseg * (float)M_PI); for (int j = 1; j < hseg - 1; ++j) { auto cos_h_next = cosf((float)(j + 1) / (float)hseg * (float)M_PI); auto sin_h_next = sinf((float)(j + 1) / (float)hseg * (float)M_PI); auto cos_v = cosf(0.0f); auto sin_v = sinf(0.0f); for (int i = 0; i < vseg; ++i) { auto cos_v_next = cosf((float)(i + 1) / (float)vseg * 2.0f * (float)M_PI); auto sin_v_next = sinf((float)(i + 1) / (float)vseg * 2.0f * (float)M_PI); pVerts->x = cos_v * sin_h; pVerts->y = sin_v * sin_h; pVerts->z = cos_h; ++pVerts; pVerts->x = cos_v * sin_h_next; pVerts->y = sin_v * sin_h_next; pVerts->z = cos_h_next; ++pVerts; pVerts->x = cos_v_next * sin_h_next; pVerts->y = sin_v_next * sin_h_next; pVerts->z = cos_h_next; ++pVerts; pVerts->x = cos_v * sin_h; pVerts->y = sin_v * sin_h; pVerts->z = cos_h; ++pVerts; pVerts->x = cos_v_next * sin_h_next; pVerts->y = sin_v_next * sin_h_next; pVerts->z = cos_h_next; ++pVerts; pVerts->x = cos_v_next * sin_h; pVerts->y = sin_v_next * sin_h; pVerts->z = cos_h; ++pVerts; cos_v = cos_v_next; sin_v = sin_v_next; } cos_h = cos_h_next; sin_h = sin_h_next; } } // Caps { auto cos_h_next = cosf(1.0f / (float)hseg * (float)M_PI); auto sin_h_next = sinf(1.0f / (float)hseg * (float)M_PI); auto cos_v = cosf(0.0f); auto sin_v = sinf(0.0f); for (int i = 0; i < vseg; ++i) { auto cos_v_next = cosf((float)(i + 1) / (float)vseg * 2.0f * (float)M_PI); auto sin_v_next = sinf((float)(i + 1) / (float)vseg * 2.0f * (float)M_PI); pVerts->x = 0.0f; pVerts->y = 0.0f; pVerts->z = 1.0f; ++pVerts; pVerts->x = cos_v * sin_h_next; pVerts->y = sin_v * sin_h_next; pVerts->z = cos_h_next; ++pVerts; pVerts->x = cos_v_next * sin_h_next; pVerts->y = sin_v_next * sin_h_next; pVerts->z = cos_h_next; ++pVerts; pVerts->x = 0.0f; pVerts->y = 0.0f; pVerts->z = -1.0f; ++pVerts; pVerts->x = cos_v_next * sin_h_next; pVerts->y = sin_v_next * sin_h_next; pVerts->z = -cos_h_next; ++pVerts; pVerts->x = cos_v * sin_h_next; pVerts->y = sin_v * sin_h_next; pVerts->z = -cos_h_next; ++pVerts; cos_v = cos_v_next; sin_v = sin_v_next; } } glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 3 * WS_SPHERE_VERT_COUNT, pVertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 3, (float *)(uintptr_t)(0)); delete[] pVertices; return handle; } ws_GBuffer ws_create_gbuffer(int w, int h) { ws_GBuffer gbuffer; glGenFramebuffers(1, &gbuffer.frameBuffer); glBindFramebuffer(GL_FRAMEBUFFER, gbuffer.frameBuffer); glActiveTexture(GL_TEXTURE0); // Albeo { glGenTextures(1, &gbuffer.albeoHandle); glBindTexture(GL_TEXTURE_2D, gbuffer.albeoHandle); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, gbuffer.albeoHandle, 0); } // Normal { glGenTextures(1, &gbuffer.normalHandle); glBindTexture(GL_TEXTURE_2D, gbuffer.normalHandle); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, gbuffer.normalHandle, 0); } // Depth { glGenTextures(1, &gbuffer.depthHandle); glBindTexture(GL_TEXTURE_2D, gbuffer.depthHandle); glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, gbuffer.depthHandle, 0); } // Attach the main depth buffer { glBindRenderbuffer(GL_RENDERBUFFER, ws_resources.mainRT.depth); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, w, h); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, ws_resources.mainRT.depth); } assert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); return gbuffer; } void ws_resize_gbuffer(ws_GBuffer &gbuffer, int w, int h) { glBindFramebuffer(GL_FRAMEBUFFER, gbuffer.frameBuffer); glActiveTexture(GL_TEXTURE0); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, gbuffer.albeoHandle); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glBindTexture(GL_TEXTURE_2D, gbuffer.normalHandle); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glBindTexture(GL_TEXTURE_2D, gbuffer.depthHandle); glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); } void ws_draw_pointlight(const ws_PointLight& pointLight) { // Update uniforms static auto LightPosition_uniform = glGetUniformLocation(ws_resources.programPointlightP, "LightPosition"); static auto LightRadius_uniform = glGetUniformLocation(ws_resources.programPointlightP, "LightRadius"); static auto LightIntensity_uniform = glGetUniformLocation(ws_resources.programPointlightP, "LightIntensity"); static auto LightColor_uniform = glGetUniformLocation(ws_resources.programPointlightP, "LightColor"); ws_Vector3 lpos = {pointLight.position.x, pointLight.position.y, pointLight.position.z}; glUniform3fv(LightPosition_uniform, 1, &lpos.x); glUniform1f(LightRadius_uniform, pointLight.radius); glUniform1f(LightIntensity_uniform, pointLight.intensity); glUniform4fv(LightColor_uniform, 1, &pointLight.color.r); glDrawArrays(GL_TRIANGLES, 0, WS_SPHERE_VERT_COUNT); }
36.545455
124
0.606468
Daivuk
a7875c5e5310c429e73ace7a6f7b1572c6e9ab28
4,155
hpp
C++
native-library/src/native_input_context.hpp
AVSystem/Anjay-java
c8f8c5e0ac5a086db4ca183155eed07374fc6585
[ "Apache-2.0" ]
4
2021-03-03T11:27:57.000Z
2022-03-29T03:42:47.000Z
native-library/src/native_input_context.hpp
AVSystem/Anjay-java
c8f8c5e0ac5a086db4ca183155eed07374fc6585
[ "Apache-2.0" ]
null
null
null
native-library/src/native_input_context.hpp
AVSystem/Anjay-java
c8f8c5e0ac5a086db4ca183155eed07374fc6585
[ "Apache-2.0" ]
3
2020-11-04T13:13:24.000Z
2021-12-06T08:03:48.000Z
/* * Copyright 2020-2021 AVSystem <avsystem@avsystem.com> * * 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. */ #pragma once #include <anjay/anjay.h> #include "./jni_wrapper.hpp" #include "./util_classes/accessor_base.hpp" #include "./util_classes/native_input_context_pointer.hpp" #include "./util_classes/objlnk.hpp" namespace details { template <typename T> struct InputCtx; template <> struct InputCtx<int32_t> { static constexpr auto Name() { return "com/avsystem/anjay/impl/NativeInputContext$IntegerContext"; } }; template <> struct InputCtx<int64_t> { static constexpr auto Name() { return "com/avsystem/anjay/impl/NativeInputContext$LongContext"; } }; template <> struct InputCtx<bool> { static constexpr auto Name() { return "com/avsystem/anjay/impl/NativeInputContext$BooleanContext"; } }; template <> struct InputCtx<float> { static constexpr auto Name() { return "com/avsystem/anjay/impl/NativeInputContext$FloatContext"; } }; template <> struct InputCtx<double> { static constexpr auto Name() { return "com/avsystem/anjay/impl/NativeInputContext$DoubleContext"; } }; template <> struct InputCtx<std::string> { static constexpr auto Name() { return "com/avsystem/anjay/impl/NativeInputContext$StringContext"; } }; template <> struct InputCtx<utils::Objlnk> { static constexpr auto Name() { return "com/avsystem/anjay/impl/NativeInputContext$ObjlnkContext"; } }; template <> struct InputCtx<uint8_t[]> { static constexpr auto Name() { return "com/avsystem/anjay/impl/NativeInputContext$BytesContext"; } }; } // namespace details class NativeInputContext { anjay_input_ctx_t *ctx_; template <typename T, typename Getter> int get_value(jni::JNIEnv &env, jni::Object<details::InputCtx<T>> &ctx, Getter &&getter) { T value; int result = getter(ctx_, &value); if (result) { return result; } auto accessor = utils::AccessorBase<details::InputCtx<T>>{ env, ctx }; accessor.template set_value<T>("value", value); return 0; } NativeInputContext(const NativeInputContext &) = delete; NativeInputContext &operator=(const NativeInputContext &) = delete; NativeInputContext(NativeInputContext &&) = delete; NativeInputContext &operator=(NativeInputContext &&) = delete; public: static constexpr auto Name() { return "com/avsystem/anjay/impl/NativeInputContext"; } static void register_native(jni::JNIEnv &env); NativeInputContext(jni::JNIEnv &env, jni::Object<utils::NativeInputContextPointer> &context); jni::jint get_i32(jni::JNIEnv &env, jni::Object<details::InputCtx<int32_t>> &ctx); jni::jint get_i64(jni::JNIEnv &env, jni::Object<details::InputCtx<int64_t>> &ctx); jni::jint get_bool(jni::JNIEnv &env, jni::Object<details::InputCtx<bool>> &ctx); jni::jint get_float(jni::JNIEnv &env, jni::Object<details::InputCtx<float>> &ctx); jni::jint get_double(jni::JNIEnv &env, jni::Object<details::InputCtx<double>> &ctx); jni::jint get_string(jni::JNIEnv &env, jni::Object<details::InputCtx<std::string>> &ctx); jni::jint get_objlnk(jni::JNIEnv &env, jni::Object<details::InputCtx<utils::Objlnk>> &ctx); jni::jint get_bytes(jni::JNIEnv &env, jni::Object<details::InputCtx<uint8_t[]>> &ctx); };
29.892086
79
0.652708
AVSystem
a7875e99e239cd4ad711fd5d736f2f8b94b57109
23,026
cpp
C++
src/smt/proto_model/proto_model.cpp
flowingcloudbackup/z3
83d84dcedde7b1fd3c7f05da25da8fbfa819c708
[ "MIT" ]
1
2018-06-15T00:27:24.000Z
2018-06-15T00:27:24.000Z
src/smt/proto_model/proto_model.cpp
flowingcloudbackup/z3
83d84dcedde7b1fd3c7f05da25da8fbfa819c708
[ "MIT" ]
null
null
null
src/smt/proto_model/proto_model.cpp
flowingcloudbackup/z3
83d84dcedde7b1fd3c7f05da25da8fbfa819c708
[ "MIT" ]
null
null
null
/*++ Copyright (c) 2006 Microsoft Corporation Module Name: proto_model.cpp Abstract: <abstract> Author: Leonardo de Moura (leonardo) 2007-03-08. Revision History: --*/ #include"proto_model.h" #include"model_params.hpp" #include"ast_pp.h" #include"ast_ll_pp.h" #include"var_subst.h" #include"array_decl_plugin.h" #include"well_sorted.h" #include"used_symbols.h" #include"model_v2_pp.h" proto_model::proto_model(ast_manager & m, params_ref const & p): model_core(m), m_afid(m.mk_family_id(symbol("array"))), m_eval(*this), m_rewrite(m) { register_factory(alloc(basic_factory, m)); m_user_sort_factory = alloc(user_sort_factory, m); register_factory(m_user_sort_factory); m_model_partial = model_params(p).partial(); } void proto_model::register_aux_decl(func_decl * d, func_interp * fi) { model_core::register_decl(d, fi); m_aux_decls.insert(d); } /** \brief Set new_fi as the new interpretation for f. If f_aux != 0, then assign the old interpretation of f to f_aux. If f_aux == 0, then delete the old interpretation of f. f_aux is marked as a auxiliary declaration. */ void proto_model::reregister_decl(func_decl * f, func_interp * new_fi, func_decl * f_aux) { func_interp * fi = get_func_interp(f); if (fi == 0) { register_decl(f, new_fi); } else { if (f_aux != 0) { register_decl(f_aux, fi); m_aux_decls.insert(f_aux); } else { dealloc(fi); } m_finterp.insert(f, new_fi); } } expr * proto_model::mk_some_interp_for(func_decl * d) { SASSERT(!has_interpretation(d)); expr * r = get_some_value(d->get_range()); // if t is a function, then it will be the constant function. if (d->get_arity() == 0) { register_decl(d, r); } else { func_interp * new_fi = alloc(func_interp, m_manager, d->get_arity()); new_fi->set_else(r); register_decl(d, new_fi); } return r; } bool proto_model::is_select_of_model_value(expr* e) const { return is_app_of(e, m_afid, OP_SELECT) && is_as_array(to_app(e)->get_arg(0)) && has_interpretation(array_util(m_manager).get_as_array_func_decl(to_app(to_app(e)->get_arg(0)))); } bool proto_model::eval(expr * e, expr_ref & result, bool model_completion) { m_eval.set_model_completion(model_completion); try { m_eval(e, result); #if 0 std::cout << mk_pp(e, m_manager) << "\n===>\n" << result << "\n"; #endif return true; } catch (model_evaluator_exception & ex) { (void)ex; TRACE("model_evaluator", tout << ex.msg() << "\n";); return false; } } /** \brief Evaluate the expression e in the current model, and store the result in \c result. It returns \c true if succeeded, and false otherwise. If the evaluation fails, then r contains a term that is simplified as much as possible using the interpretations available in the model. When model_completion == true, if the model does not assign an interpretation to a declaration it will build one for it. Moreover, partial functions will also be completed. So, if model_completion == true, the evaluator never fails if it doesn't contain quantifiers. */ /** \brief Replace uninterpreted constants occurring in fi->get_else() by their interpretations. */ void proto_model::cleanup_func_interp(func_interp * fi, func_decl_set & found_aux_fs) { if (fi->is_partial()) return; expr * fi_else = fi->get_else(); TRACE("model_bug", tout << "cleaning up:\n" << mk_pp(fi_else, m_manager) << "\n";); obj_map<expr, expr*> cache; expr_ref_vector trail(m_manager); ptr_buffer<expr, 128> todo; ptr_buffer<expr> args; todo.push_back(fi_else); expr * a; while (!todo.empty()) { a = todo.back(); if (is_uninterp_const(a)) { todo.pop_back(); func_decl * a_decl = to_app(a)->get_decl(); expr * ai = get_const_interp(a_decl); if (ai == 0) { ai = get_some_value(a_decl->get_range()); register_decl(a_decl, ai); } cache.insert(a, ai); } else { switch(a->get_kind()) { case AST_APP: { app * t = to_app(a); bool visited = true; args.reset(); unsigned num_args = t->get_num_args(); for (unsigned i = 0; i < num_args; ++i) { expr * arg = 0; if (!cache.find(t->get_arg(i), arg)) { visited = false; todo.push_back(t->get_arg(i)); } else { args.push_back(arg); } } if (!visited) { continue; } func_decl * f = t->get_decl(); if (m_aux_decls.contains(f)) found_aux_fs.insert(f); expr_ref new_t(m_manager); new_t = m_rewrite.mk_app(f, num_args, args.c_ptr()); if (t != new_t.get()) trail.push_back(new_t); todo.pop_back(); cache.insert(t, new_t); break; } default: SASSERT(a != 0); cache.insert(a, a); todo.pop_back(); break; } } } if (!cache.find(fi_else, a)) { UNREACHABLE(); } fi->set_else(a); } void proto_model::remove_aux_decls_not_in_set(ptr_vector<func_decl> & decls, func_decl_set const & s) { unsigned sz = decls.size(); unsigned i = 0; unsigned j = 0; for (; i < sz; i++) { func_decl * f = decls[i]; if (!m_aux_decls.contains(f) || s.contains(f)) { decls[j] = f; j++; } } decls.shrink(j); } /** \brief Replace uninterpreted constants occurring in the func_interp's get_else() by their interpretations. */ void proto_model::cleanup() { func_decl_set found_aux_fs; decl2finterp::iterator it = m_finterp.begin(); decl2finterp::iterator end = m_finterp.end(); for (; it != end; ++it) { func_interp * fi = (*it).m_value; cleanup_func_interp(fi, found_aux_fs); } // remove auxiliary declarations that are not used. if (found_aux_fs.size() != m_aux_decls.size()) { remove_aux_decls_not_in_set(m_decls, found_aux_fs); remove_aux_decls_not_in_set(m_func_decls, found_aux_fs); func_decl_set::iterator it2 = m_aux_decls.begin(); func_decl_set::iterator end2 = m_aux_decls.end(); for (; it2 != end2; ++it2) { func_decl * faux = *it2; if (!found_aux_fs.contains(faux)) { TRACE("cleanup_bug", tout << "eliminating " << faux->get_name() << "\n";); func_interp * fi = 0; m_finterp.find(faux, fi); SASSERT(fi != 0); m_finterp.erase(faux); m_manager.dec_ref(faux); dealloc(fi); } } m_aux_decls.swap(found_aux_fs); } } value_factory * proto_model::get_factory(family_id fid) { return m_factories.get_plugin(fid); } void proto_model::freeze_universe(sort * s) { SASSERT(m_manager.is_uninterp(s)); m_user_sort_factory->freeze_universe(s); } /** \brief Return the known universe of an uninterpreted sort. */ obj_hashtable<expr> const & proto_model::get_known_universe(sort * s) const { return m_user_sort_factory->get_known_universe(s); } ptr_vector<expr> const & proto_model::get_universe(sort * s) const { ptr_vector<expr> & tmp = const_cast<proto_model*>(this)->m_tmp; tmp.reset(); obj_hashtable<expr> const & u = get_known_universe(s); obj_hashtable<expr>::iterator it = u.begin(); obj_hashtable<expr>::iterator end = u.end(); for (; it != end; ++it) tmp.push_back(*it); return tmp; } unsigned proto_model::get_num_uninterpreted_sorts() const { return m_user_sort_factory->get_num_sorts(); } sort * proto_model::get_uninterpreted_sort(unsigned idx) const { SASSERT(idx < get_num_uninterpreted_sorts()); return m_user_sort_factory->get_sort(idx); } /** \brief Return true if the given sort is uninterpreted and has a finite interpretation in the model. */ bool proto_model::is_finite(sort * s) const { return m_manager.is_uninterp(s) && m_user_sort_factory->is_finite(s); } expr * proto_model::get_some_value(sort * s) { if (m_manager.is_uninterp(s)) { return m_user_sort_factory->get_some_value(s); } else { family_id fid = s->get_family_id(); value_factory * f = get_factory(fid); if (f) return f->get_some_value(s); // there is no factory for the family id, then assume s is uninterpreted. return m_user_sort_factory->get_some_value(s); } } bool proto_model::get_some_values(sort * s, expr_ref & v1, expr_ref & v2) { if (m_manager.is_uninterp(s)) { return m_user_sort_factory->get_some_values(s, v1, v2); } else { family_id fid = s->get_family_id(); value_factory * f = get_factory(fid); if (f) return f->get_some_values(s, v1, v2); else return false; } } expr * proto_model::get_fresh_value(sort * s) { if (m_manager.is_uninterp(s)) { return m_user_sort_factory->get_fresh_value(s); } else { family_id fid = s->get_family_id(); value_factory * f = get_factory(fid); if (f) return f->get_fresh_value(s); else // Use user_sort_factory if the theory has no support for model construnction. // This is needed when dummy theories are used for arithmetic or arrays. return m_user_sort_factory->get_fresh_value(s); } } void proto_model::register_value(expr * n) { sort * s = m_manager.get_sort(n); if (m_manager.is_uninterp(s)) { m_user_sort_factory->register_value(n); } else { family_id fid = s->get_family_id(); value_factory * f = get_factory(fid); if (f) f->register_value(n); } } bool proto_model::is_as_array(expr * v) const { return is_app_of(v, m_afid, OP_AS_ARRAY); } void proto_model::compress() { ptr_vector<func_decl>::iterator it = m_func_decls.begin(); ptr_vector<func_decl>::iterator end = m_func_decls.end(); for (; it != end; ++it) { func_decl * f = *it; func_interp * fi = get_func_interp(f); SASSERT(fi != 0); fi->compress(); } } /** \brief Complete the interpretation fi of f if it is partial. If f does not have an interpretation in the given model, then this is a noop. */ void proto_model::complete_partial_func(func_decl * f) { func_interp * fi = get_func_interp(f); if (fi && fi->is_partial()) { expr * else_value = 0; #if 0 // For UFBV benchmarks, setting the "else" to false is not a good idea. // TODO: find a permanent solution. A possibility is to add another option. if (m_manager.is_bool(f->get_range())) { else_value = m_manager.mk_false(); } else { else_value = fi->get_max_occ_result(); if (else_value == 0) else_value = get_some_value(f->get_range()); } #else else_value = fi->get_max_occ_result(); if (else_value == 0) else_value = get_some_value(f->get_range()); #endif fi->set_else(else_value); } } /** \brief Set the (else) field of function interpretations... */ void proto_model::complete_partial_funcs() { if (m_model_partial) return; // m_func_decls may be "expanded" when we invoke get_some_value. // So, we must not use iterators to traverse it. for (unsigned i = 0; i < m_func_decls.size(); i++) { complete_partial_func(m_func_decls[i]); } } model * proto_model::mk_model() { TRACE("proto_model", tout << "mk_model\n"; model_v2_pp(tout, *this);); model * m = alloc(model, m_manager); decl2expr::iterator it1 = m_interp.begin(); decl2expr::iterator end1 = m_interp.end(); for (; it1 != end1; ++it1) { m->register_decl(it1->m_key, it1->m_value); } decl2finterp::iterator it2 = m_finterp.begin(); decl2finterp::iterator end2 = m_finterp.end(); for (; it2 != end2; ++it2) { m->register_decl(it2->m_key, it2->m_value); m_manager.dec_ref(it2->m_key); } m_finterp.reset(); // m took the ownership of the func_interp's unsigned sz = get_num_uninterpreted_sorts(); for (unsigned i = 0; i < sz; i++) { sort * s = get_uninterpreted_sort(i); TRACE("proto_model", tout << "copying uninterpreted sorts...\n" << mk_pp(s, m_manager) << "\n";); ptr_vector<expr> const& buf = get_universe(s); m->register_usort(s, buf.size(), buf.c_ptr()); } return m; } #if 0 #include"simplifier.h" #include"basic_simplifier_plugin.h" // Auxiliary function for computing fi(args[0], ..., args[fi.get_arity() - 1]). // The result is stored in result. // Return true if succeeded, and false otherwise. // It uses the simplifier s during the computation. bool eval(func_interp & fi, simplifier & s, expr * const * args, expr_ref & result) { bool actuals_are_values = true; if (fi.num_entries() != 0) { for (unsigned i = 0; actuals_are_values && i < fi.get_arity(); i++) { actuals_are_values = fi.m().is_value(args[i]); } } func_entry * entry = fi.get_entry(args); if (entry != 0) { result = entry->get_result(); return true; } TRACE("func_interp", tout << "failed to find entry for: "; for(unsigned i = 0; i < fi.get_arity(); i++) tout << mk_pp(args[i], fi.m()) << " "; tout << "\nis partial: " << fi.is_partial() << "\n";); if (!fi.eval_else(args, result)) { return false; } if (actuals_are_values && fi.args_are_values()) { // cheap case... we are done return true; } // build symbolic result... the actuals may be equal to the args of one of the entries. basic_simplifier_plugin * bs = static_cast<basic_simplifier_plugin*>(s.get_plugin(fi.m().get_basic_family_id())); for (unsigned k = 0; k < fi.num_entries(); k++) { func_entry const * curr = fi.get_entry(k); SASSERT(!curr->eq_args(fi.m(), fi.get_arity(), args)); if (!actuals_are_values || !curr->args_are_values()) { expr_ref_buffer eqs(fi.m()); unsigned i = fi.get_arity(); while (i > 0) { --i; expr_ref new_eq(fi.m()); bs->mk_eq(curr->get_arg(i), args[i], new_eq); eqs.push_back(new_eq); } SASSERT(eqs.size() == fi.get_arity()); expr_ref new_cond(fi.m()); bs->mk_and(eqs.size(), eqs.c_ptr(), new_cond); bs->mk_ite(new_cond, curr->get_result(), result, result); } } return true; } bool proto_model::eval(expr * e, expr_ref & result, bool model_completion) { bool is_ok = true; SASSERT(is_well_sorted(m_manager, e)); TRACE("model_eval", tout << mk_pp(e, m_manager) << "\n"; tout << "sort: " << mk_pp(m_manager.get_sort(e), m_manager) << "\n";); obj_map<expr, expr*> eval_cache; expr_ref_vector trail(m_manager); sbuffer<std::pair<expr*, expr*>, 128> todo; ptr_buffer<expr> args; expr * null = static_cast<expr*>(0); todo.push_back(std::make_pair(e, null)); simplifier m_simplifier(m_manager); expr * a; expr * expanded_a; while (!todo.empty()) { std::pair<expr *, expr *> & p = todo.back(); a = p.first; expanded_a = p.second; if (expanded_a != 0) { expr * r = 0; eval_cache.find(expanded_a, r); SASSERT(r != 0); todo.pop_back(); eval_cache.insert(a, r); TRACE("model_eval", tout << "orig:\n" << mk_pp(a, m_manager) << "\n"; tout << "after beta reduction:\n" << mk_pp(expanded_a, m_manager) << "\n"; tout << "new:\n" << mk_pp(r, m_manager) << "\n";); } else { switch(a->get_kind()) { case AST_APP: { app * t = to_app(a); bool visited = true; args.reset(); unsigned num_args = t->get_num_args(); for (unsigned i = 0; i < num_args; ++i) { expr * arg = 0; if (!eval_cache.find(t->get_arg(i), arg)) { visited = false; todo.push_back(std::make_pair(t->get_arg(i), null)); } else { args.push_back(arg); } } if (!visited) { continue; } SASSERT(args.size() == t->get_num_args()); expr_ref new_t(m_manager); func_decl * f = t->get_decl(); if (!has_interpretation(f)) { // the model does not assign an interpretation to f. SASSERT(new_t.get() == 0); if (f->get_family_id() == null_family_id) { if (model_completion) { // create an interpretation for f. new_t = mk_some_interp_for(f); } else { TRACE("model_eval", tout << f->get_name() << " is uninterpreted\n";); is_ok = false; } } if (new_t.get() == 0) { // t is interpreted or model completion is disabled. m_simplifier.mk_app(f, num_args, args.c_ptr(), new_t); TRACE("model_eval", tout << mk_pp(t, m_manager) << " -> " << new_t << "\n";); trail.push_back(new_t); if (!is_app(new_t) || to_app(new_t)->get_decl() != f || is_select_of_model_value(new_t)) { // if the result is not of the form (f ...), then assume we must simplify it. expr * new_new_t = 0; if (!eval_cache.find(new_t.get(), new_new_t)) { todo.back().second = new_t; todo.push_back(std::make_pair(new_t, null)); continue; } else { new_t = new_new_t; } } } } else { // the model has an interpretaion for f. if (num_args == 0) { // t is a constant new_t = get_const_interp(f); } else { // t is a function application SASSERT(new_t.get() == 0); // try to use function graph first func_interp * fi = get_func_interp(f); SASSERT(fi->get_arity() == num_args); expr_ref r1(m_manager); // fi may be partial... if (!::eval(*fi, m_simplifier, args.c_ptr(), r1)) { SASSERT(fi->is_partial()); // fi->eval only fails when fi is partial. if (model_completion) { expr * r = get_some_value(f->get_range()); fi->set_else(r); SASSERT(!fi->is_partial()); new_t = r; } else { // f is an uninterpreted function, there is no need to use m_simplifier.mk_app new_t = m_manager.mk_app(f, num_args, args.c_ptr()); trail.push_back(new_t); TRACE("model_eval", tout << f->get_name() << " is uninterpreted\n";); is_ok = false; } } else { SASSERT(r1); trail.push_back(r1); TRACE("model_eval", tout << mk_pp(a, m_manager) << "\nevaluates to: " << r1 << "\n";); expr * r2 = 0; if (!eval_cache.find(r1.get(), r2)) { todo.back().second = r1; todo.push_back(std::make_pair(r1, null)); continue; } else { new_t = r2; } } } } TRACE("model_eval", tout << "orig:\n" << mk_pp(t, m_manager) << "\n"; tout << "new:\n" << mk_pp(new_t, m_manager) << "\n";); todo.pop_back(); SASSERT(new_t.get() != 0); eval_cache.insert(t, new_t); break; } case AST_VAR: SASSERT(a != 0); eval_cache.insert(a, a); todo.pop_back(); break; case AST_QUANTIFIER: TRACE("model_eval", tout << "found quantifier\n" << mk_pp(a, m_manager) << "\n";); is_ok = false; // evaluator does not handle quantifiers. SASSERT(a != 0); eval_cache.insert(a, a); todo.pop_back(); break; default: UNREACHABLE(); break; } } } if (!eval_cache.find(e, a)) { TRACE("model_eval", tout << "FAILED e: " << mk_bounded_pp(e, m_manager) << "\n";); UNREACHABLE(); } result = a; std::cout << mk_pp(e, m_manager) << "\n===>\n" << result << "\n"; TRACE("model_eval", ast_ll_pp(tout << "original: ", m_manager, e); ast_ll_pp(tout << "evaluated: ", m_manager, a); ast_ll_pp(tout << "reduced: ", m_manager, result.get()); tout << "sort: " << mk_pp(m_manager.get_sort(e), m_manager) << "\n"; ); SASSERT(is_well_sorted(m_manager, result.get())); return is_ok; } #endif
33.812041
117
0.5228
flowingcloudbackup
a787cfad2602354641b3158814ac74b8f1fc94a7
2,703
cc
C++
remoting/test/app_remoting_service_urls.cc
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
remoting/test/app_remoting_service_urls.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
remoting/test/app_remoting_service_urls.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/test/app_remoting_service_urls.h" #include "base/logging.h" #include "base/strings/stringprintf.h" namespace { // The placeholder is the environment endpoint qualifier. No trailing slash // is added as it will be appended as needed later. const char kAppRemotingTestEndpointBase[] = "https://www-googleapis-test.sandbox.google.com/appremoting/%s"; const char kAppRemotingDevEndpointQualifier[] = "v1beta1_dev"; // Placeholder value is for the Application ID. const char kRunApplicationApi[] = "applications/%s/run"; // First placeholder value is for the Application ID. Second placeholder is for // the Host ID to report the issue for. const char kReportIssueApi[] = "applications/%s/hosts/%s/reportIssue"; } // namespace namespace remoting { namespace test { bool IsSupportedServiceEnvironment(ServiceEnvironment service_environment) { return (service_environment >= 0 && service_environment < kUnknownEnvironment); } std::string GetBaseUrl(ServiceEnvironment service_environment) { std::string base_service_url; if (service_environment == kDeveloperEnvironment) { base_service_url = base::StringPrintf(kAppRemotingTestEndpointBase, kAppRemotingDevEndpointQualifier); } return base_service_url; } std::string GetRunApplicationUrl(const std::string& extension_id, ServiceEnvironment service_environment) { std::string service_url; if (!IsSupportedServiceEnvironment(service_environment)) { return service_url; } service_url = GetBaseUrl(service_environment); if (!service_url.empty()) { std::string api_string = base::StringPrintf(kRunApplicationApi, extension_id.c_str()); service_url = base::StringPrintf("%s/%s", service_url.c_str(), api_string.c_str()); } return service_url; } std::string GetReportIssueUrl(const std::string& extension_id, const std::string& host_id, ServiceEnvironment service_environment) { std::string service_url; if (!IsSupportedServiceEnvironment(service_environment)) { return service_url; } service_url = GetBaseUrl(service_environment); if (!service_url.empty()) { std::string api_string = base::StringPrintf( kReportIssueApi, extension_id.c_str(), host_id.c_str()); service_url = base::StringPrintf("%s/%s", service_url.c_str(), api_string.c_str()); } return service_url; } } // namespace test } // namespace remoting
32.566265
80
0.713651
google-ar
a78e291fec91811edf30eb4e01b9dd7d602b798f
681
cpp
C++
mooslcm/src/test_lcm_publish_moos_double_t.cpp
aspears1935/moos-lcm-bridge
f74218ab2c0c7bbd454b6f20d93db6986ec49c49
[ "MIT" ]
null
null
null
mooslcm/src/test_lcm_publish_moos_double_t.cpp
aspears1935/moos-lcm-bridge
f74218ab2c0c7bbd454b6f20d93db6986ec49c49
[ "MIT" ]
null
null
null
mooslcm/src/test_lcm_publish_moos_double_t.cpp
aspears1935/moos-lcm-bridge
f74218ab2c0c7bbd454b6f20d93db6986ec49c49
[ "MIT" ]
null
null
null
// file: send_message.cpp // // LCM example program. // // compile with: // $ g++ -o send_message send_message.cpp -llcm // // On a system with pkg-config, you can also use: // $ g++ -o send_message send_message.cpp `pkg-config --cflags --libs lcm` #include <ctime> #include <lcm/lcm-cpp.hpp> #include <unistd.h> #include <iostream> #include "moos_double_t.hpp" int main(int argc, char ** argv) { lcm::LCM lcm; if(!lcm.good()) return 1; std::time_t result = std::time(NULL); moos_lcm_bridge_types::moos_double_t msg; msg.timestamp = (long) result; //msg_time; msg.value = 17; lcm.publish("NAV_HEADING", &msg); return 0; }
21.28125
75
0.631424
aspears1935
a78ec63364b2bcdc87c1a7ed8458d904f4065cc0
5,491
cpp
C++
ProcessLib/VectorMatrixAssembler.cpp
yingtaohu/ogs
651ca2f903ee0bf5a8cfb505e8e2fd0562b4ce8e
[ "BSD-4-Clause" ]
null
null
null
ProcessLib/VectorMatrixAssembler.cpp
yingtaohu/ogs
651ca2f903ee0bf5a8cfb505e8e2fd0562b4ce8e
[ "BSD-4-Clause" ]
null
null
null
ProcessLib/VectorMatrixAssembler.cpp
yingtaohu/ogs
651ca2f903ee0bf5a8cfb505e8e2fd0562b4ce8e
[ "BSD-4-Clause" ]
null
null
null
/** * \copyright * Copyright (c) 2012-2017, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license * */ #include "VectorMatrixAssembler.h" #include <cassert> #include "NumLib/DOF/DOFTableUtil.h" #include "MathLib/LinAlg/Eigen/EigenMapTools.h" #include "LocalAssemblerInterface.h" #include "CoupledSolutionsForStaggeredScheme.h" #include "Process.h" namespace ProcessLib { VectorMatrixAssembler::VectorMatrixAssembler( std::unique_ptr<AbstractJacobianAssembler>&& jacobian_assembler) : _jacobian_assembler(std::move(jacobian_assembler)) { } void VectorMatrixAssembler::preAssemble( const std::size_t mesh_item_id, LocalAssemblerInterface& local_assembler, const NumLib::LocalToGlobalIndexMap& dof_table, const double t, const GlobalVector& x) { auto const indices = NumLib::getIndices(mesh_item_id, dof_table); auto const local_x = x.get(indices); local_assembler.preAssemble(t, local_x); } void VectorMatrixAssembler::assemble( const std::size_t mesh_item_id, LocalAssemblerInterface& local_assembler, const NumLib::LocalToGlobalIndexMap& dof_table, const double t, const GlobalVector& x, GlobalMatrix& M, GlobalMatrix& K, GlobalVector& b, const CoupledSolutionsForStaggeredScheme* cpl_xs) { auto const indices = NumLib::getIndices(mesh_item_id, dof_table); _local_M_data.clear(); _local_K_data.clear(); _local_b_data.clear(); if (cpl_xs == nullptr) { auto const local_x = x.get(indices); local_assembler.assemble(t, local_x, _local_M_data, _local_K_data, _local_b_data); } else { auto local_coupled_xs0 = getPreviousLocalSolutions(*cpl_xs, indices); auto local_coupled_xs = getCurrentLocalSolutions(*cpl_xs, indices); ProcessLib::LocalCoupledSolutions local_coupled_solutions( cpl_xs->dt, cpl_xs->process_id, std::move(local_coupled_xs0), std::move(local_coupled_xs)); local_assembler.assembleWithCoupledTerm(t, _local_M_data, _local_K_data, _local_b_data, local_coupled_solutions); } auto const num_r_c = indices.size(); auto const r_c_indices = NumLib::LocalToGlobalIndexMap::RowColumnIndices(indices, indices); if (!_local_M_data.empty()) { auto const local_M = MathLib::toMatrix(_local_M_data, num_r_c, num_r_c); M.add(r_c_indices, local_M); } if (!_local_K_data.empty()) { auto const local_K = MathLib::toMatrix(_local_K_data, num_r_c, num_r_c); K.add(r_c_indices, local_K); } if (!_local_b_data.empty()) { assert(_local_b_data.size() == num_r_c); b.add(indices, _local_b_data); } } void VectorMatrixAssembler::assembleWithJacobian( std::size_t const mesh_item_id, LocalAssemblerInterface& local_assembler, NumLib::LocalToGlobalIndexMap const& dof_table, const double t, GlobalVector const& x, GlobalVector const& xdot, const double dxdot_dx, const double dx_dx, GlobalMatrix& M, GlobalMatrix& K, GlobalVector& b, GlobalMatrix& Jac, const CoupledSolutionsForStaggeredScheme* cpl_xs) { auto const indices = NumLib::getIndices(mesh_item_id, dof_table); auto const local_xdot = xdot.get(indices); _local_M_data.clear(); _local_K_data.clear(); _local_b_data.clear(); _local_Jac_data.clear(); if (cpl_xs == nullptr) { auto const local_x = x.get(indices); _jacobian_assembler->assembleWithJacobian( local_assembler, t, local_x, local_xdot, dxdot_dx, dx_dx, _local_M_data, _local_K_data, _local_b_data, _local_Jac_data); } else { auto local_coupled_xs0 = getPreviousLocalSolutions(*cpl_xs, indices); auto local_coupled_xs = getCurrentLocalSolutions(*cpl_xs, indices); ProcessLib::LocalCoupledSolutions local_coupled_solutions( cpl_xs->dt, cpl_xs->process_id, std::move(local_coupled_xs0), std::move(local_coupled_xs)); _jacobian_assembler->assembleWithJacobianAndCoupling( local_assembler, t, local_xdot, dxdot_dx, dx_dx, _local_M_data, _local_K_data, _local_b_data, _local_Jac_data, local_coupled_solutions); } auto const num_r_c = indices.size(); auto const r_c_indices = NumLib::LocalToGlobalIndexMap::RowColumnIndices(indices, indices); if (!_local_M_data.empty()) { auto const local_M = MathLib::toMatrix(_local_M_data, num_r_c, num_r_c); M.add(r_c_indices, local_M); } if (!_local_K_data.empty()) { auto const local_K = MathLib::toMatrix(_local_K_data, num_r_c, num_r_c); K.add(r_c_indices, local_K); } if (!_local_b_data.empty()) { assert(_local_b_data.size() == num_r_c); b.add(indices, _local_b_data); } if (!_local_Jac_data.empty()) { auto const local_Jac = MathLib::toMatrix(_local_Jac_data, num_r_c, num_r_c); Jac.add(r_c_indices, local_Jac); } else { OGS_FATAL( "No Jacobian has been assembled! This might be due to programming " "errors in the local assembler of the current process."); } } } // namespace ProcessLib
33.481707
80
0.675651
yingtaohu
a78ee03b0d51c1f340eb0cc5f2b81cb4d2292569
7,426
cpp
C++
src/modules/database/resultset_binding.cpp
badlee/TideSDK
fe6f6c93c6cab3395121696f48d3b55d43e1eddd
[ "Apache-2.0" ]
1
2021-09-18T10:10:39.000Z
2021-09-18T10:10:39.000Z
src/modules/database/resultset_binding.cpp
hexmode/TideSDK
2c0276de08d7b760b53416bbd8038d79b8474fc5
[ "Apache-2.0" ]
1
2022-02-08T08:45:29.000Z
2022-02-08T08:45:29.000Z
src/modules/database/resultset_binding.cpp
hexmode/TideSDK
2c0276de08d7b760b53416bbd8038d79b8474fc5
[ "Apache-2.0" ]
null
null
null
/** * Copyright (c) 2012 - 2014 TideSDK contributors * http://www.tidesdk.org * Includes modified sources under the Apache 2 License * Copyright (c) 2008 - 2012 Appcelerator Inc * Refer to LICENSE for details of distribution and use. **/ #include <tide/tide.h> #include "resultset_binding.h" #include <Poco/Data/MetaColumn.h> #include <Poco/DynamicAny.h> using Poco::Data::MetaColumn; namespace ti { ResultSetBinding::ResultSetBinding() : StaticBoundObject("Database.ResultSet"), eof(true) { // no results result set Bind(); } ResultSetBinding::ResultSetBinding(Poco::Data::RecordSet &r) : StaticBoundObject("ResultSet"), eof(false) { rs = new Poco::Data::RecordSet(r); Bind(); } void ResultSetBinding::Bind() { /** * @tiapi(method=True,name=Database.ResultSet.isValidRow,since=0.4) Checks whether you can call data extraction methods * @tiresult(for=Database.ResultSet.isValidRow,type=Boolean) true if the row is valid */ this->SetMethod("isValidRow",&ResultSetBinding::IsValidRow); /** * @tiapi(method=True,name=Database.ResultSet.next,since=0.4) Moves the pointer to the next row of the result set */ this->SetMethod("next",&ResultSetBinding::Next); /** * @tiapi(method=True,name=Database.ResultSet.close,since=0.4) Releases the state associated with the result set */ this->SetMethod("close",&ResultSetBinding::Close); /** * @tiapi(method=True,name=Database.ResultSet.fieldCount,since=0.4) Returns the number of fields of the result set * @tiresult(for=Database.ResultSet.fieldCount,type=Number) the number of fields of the result set */ this->SetMethod("fieldCount",&ResultSetBinding::FieldCount); /** * @tiapi(method=True,name=Database.ResultSet.rowCount,since=0.4) Returns the number of rows of the result set * @tiresult(for=Database.ResultSet.rowCount,type=Number) the number of the rows of the result set */ this->SetMethod("rowCount",&ResultSetBinding::RowCount); /** * @tiapi(method=True,name=Database.ResultSet.fieldName,since=0.4) Returns the name of the specified field in the current result set taken from the SQL statement which was executed * @tiarg(for=Database.ResultSet.fieldName,type=Number,name=fieldIndex) the zero-based index of the desired field * @tiresult(for=Database.ResultSet.fieldName,type=String) The name of the specified field */ this->SetMethod("fieldName",&ResultSetBinding::FieldName); /** * @tiapi(method=True,name=Database.ResultSet.field,since=0.4) Returns the contents of the specified field in the current row * @tiarg(for=Database.ResultSet.field,type=Number,name=fieldIndex) the zero-based index of the desired field * @tiresult(for=Database.ResultSet.field,type=Boolean|String|Number|Bytes) The content of the specified field in the current row */ this->SetMethod("field",&ResultSetBinding::Field); /** * @tiapi(method=True,name=Database.ResultSet.fieldByName,since=0.4) Returns the contents of the specified field in the current row using the name of the field as an identifier * @tiarg(for=Database.ResultSet.fieldByName,type=String,name=name) the name of the desired field * @tiresult(for=Database.ResultSet.fieldByName,type=Boolean|String|Number|Bytes) The content of the specified field in the current row */ this->SetMethod("fieldByName",&ResultSetBinding::FieldByName); } ResultSetBinding::~ResultSetBinding() { } void ResultSetBinding::IsValidRow(const ValueList& args, ValueRef result) { if (rs.isNull()) { result->SetBool(false); } else { result->SetBool(!eof); } } void ResultSetBinding::Next(const ValueList& args, ValueRef result) { if (!rs.isNull() && !eof) { eof = (rs->moveNext() == false); } } void ResultSetBinding::Close(const ValueList& args, ValueRef result) { if (!rs.isNull()) { rs = NULL; } } void ResultSetBinding::RowCount(const ValueList& args, ValueRef result) { if (rs.isNull()) { result->SetInt(0); } else { result->SetInt(rs->rowCount()); } } void ResultSetBinding::FieldCount(const ValueList& args, ValueRef result) { if (rs.isNull()) { result->SetInt(0); } else { result->SetInt(rs->columnCount()); } } void ResultSetBinding::FieldName(const ValueList& args, ValueRef result) { if (rs.isNull()) { result->SetNull(); } else { args.VerifyException("fieldName", "i"); const std::string &str = rs->columnName(args.at(0)->ToInt()); result->SetString(str.c_str()); } } void ResultSetBinding::Field(const ValueList& args, ValueRef result) { if (rs.isNull()) { result->SetNull(); } else { args.VerifyException("field", "i"); TransformValue(args.at(0)->ToInt(),result); } } void ResultSetBinding::FieldByName(const ValueList& args, ValueRef result) { result->SetNull(); if (!rs.isNull()) { args.VerifyException("fieldByName", "s"); std::string name = args.at(0)->ToString(); size_t count = rs->columnCount(); for (size_t i = 0; i<count; i++) { const std::string &str = rs->columnName(i); if (str == name) { TransformValue(i,result); break; } } } } void ResultSetBinding::TransformValue(size_t index, ValueRef result) { MetaColumn::ColumnDataType type = rs->columnType(index); Poco::DynamicAny value = rs->value(index); if (value.isEmpty()) { result->SetNull(); } else if (type == MetaColumn::FDT_STRING) { std::string str; value.convert(str); result->SetString(str); } else if (type == MetaColumn::FDT_BOOL) { bool v = false; value.convert(v); result->SetBool(v); } else if (type == MetaColumn::FDT_FLOAT || type == MetaColumn::FDT_DOUBLE) { float f = 0; value.convert(f); result->SetDouble(f); } else if (type == MetaColumn::FDT_BLOB || type == MetaColumn::FDT_UNKNOWN) { std::string str; value.convert(str); result->SetString(str); } else { // the rest of these are ints: // FDT_INT8, // FDT_UINT8, // FDT_INT16, // FDT_UINT16, // FDT_INT32, // FDT_UINT32, // FDT_INT64, // FDT_UINT64, int i; value.convert(i); result->SetInt(i); } } }
33.004444
188
0.5676
badlee
a78ffce8e4ff64c892ee4e8be84ed153b4e98f48
2,091
cpp
C++
Surface_mesh_topology/examples/Surface_mesh_topology/edgewidth_surface_mesh.cpp
yemaedahrav/cgal
ef771049b173007f2c566375bbd85a691adcee17
[ "CC0-1.0" ]
1
2019-04-08T23:06:26.000Z
2019-04-08T23:06:26.000Z
Surface_mesh_topology/examples/Surface_mesh_topology/edgewidth_surface_mesh.cpp
yemaedahrav/cgal
ef771049b173007f2c566375bbd85a691adcee17
[ "CC0-1.0" ]
1
2021-03-12T14:38:20.000Z
2021-03-12T14:38:20.000Z
Surface_mesh_topology/examples/Surface_mesh_topology/edgewidth_surface_mesh.cpp
szobov/cgal
e7b91b92b8c6949e3b62023bdd1e9f3ad8472626
[ "CC0-1.0" ]
1
2022-03-05T04:18:59.000Z
2022-03-05T04:18:59.000Z
#include <CGAL/Simple_cartesian.h> #include <CGAL/Surface_mesh.h> #include <CGAL/Curves_on_surface_topology.h> #include <CGAL/Path_on_surface.h> #include <CGAL/squared_distance_3.h> #include <CGAL/draw_face_graph_with_paths.h> #include <fstream> using Mesh = CGAL::Surface_mesh<CGAL::Simple_cartesian<double>::Point_3>; using Path_on_surface = CGAL::Surface_mesh_topology::Path_on_surface<Mesh>; double cycle_length(const Mesh& mesh, const Path_on_surface& cycle) { // Compute the length of the given cycle. double res=0; for (std::size_t i=0; i<cycle.length(); ++i) { res+=std::sqrt (CGAL::squared_distance(mesh.point(mesh.vertex(mesh.edge(cycle[i]), 0)), mesh.point(mesh.vertex(mesh.edge(cycle[i]), 1)))); } return res; } void display_cycle_info(const Mesh& mesh, const Path_on_surface& cycle) { // Display information about the given cycle. if (cycle.is_empty()) { std::cout<<"Empty."<<std::endl; return; } std::cout<<"Root: "<<mesh.point(mesh.vertex(mesh.edge(cycle[0]), 0))<<"; " <<"Number of edges: "<<cycle.length()<<"; " <<"Length: "<<cycle_length(mesh, cycle)<<std::endl; } int main(int argc, char* argv[]) { std::string filename(argc==1?"data/3torus.off":argv[1]); bool draw=(argc<3?false:(std::string(argv[2])=="-draw")); Mesh sm; if(!CGAL::read_polygon_mesh(filename, sm)) { std::cout<<"Cannot read file '"<<filename<<"'. Exiting program"<<std::endl; return EXIT_FAILURE; } std::cout<<"File '"<<filename<<"' loaded. Finding edge-width of the mesh..."<<std::endl; CGAL::Surface_mesh_topology::Curves_on_surface_topology<Mesh> cst(sm, true); Path_on_surface cycle1=cst.compute_edge_width(true); CGAL::Surface_mesh_topology::Euclidean_length_weight_functor<Mesh> wf(sm); Path_on_surface cycle2=cst.compute_shortest_non_contractible_cycle(wf, true); std::cout<<"Cycle 1 (pink): "; display_cycle_info(sm, cycle1); std::cout<<"Cycle 2 (green): "; display_cycle_info(sm, cycle2); if (draw) { CGAL::draw(sm, {cycle1, cycle2}); } return EXIT_SUCCESS; }
36.051724
90
0.683405
yemaedahrav