text
string
size
int64
token_count
int64
//==-------------- allowlist.cpp - SYCL_DEVICE_ALLOWLIST -------------------==// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include <detail/allowlist.hpp> #include <detail/config.hpp> #include <detail/device_impl.hpp> #include <detail/platform_info.hpp> #include <algorithm> #include <regex> __SYCL_INLINE_NAMESPACE(cl) { namespace sycl { namespace detail { constexpr char BackendNameKeyName[] = "BackendName"; constexpr char DeviceTypeKeyName[] = "DeviceType"; constexpr char DeviceVendorIdKeyName[] = "DeviceVendorId"; constexpr char DriverVersionKeyName[] = "DriverVersion"; constexpr char PlatformVersionKeyName[] = "PlatformVersion"; constexpr char DeviceNameKeyName[] = "DeviceName"; constexpr char PlatformNameKeyName[] = "PlatformName"; constexpr std::array<const char *, 7> SupportedAllowListKeyNames{ BackendNameKeyName, DeviceTypeKeyName, DeviceVendorIdKeyName, DriverVersionKeyName, PlatformVersionKeyName, DeviceNameKeyName, PlatformNameKeyName}; // Parsing and validating SYCL_DEVICE_ALLOWLIST variable value. // // The value has the following form: // DeviceDesc1|DeviceDesc2|<...>|DeviceDescN // DeviceDescN is the set of descriptions for the device which should be // allowed. The sets of device descriptions are separated by '|' symbol. The set // of descriptions has the following structure: // DeviceDescN = Key1:Value1,Key2:Value2,...,KeyN:ValueN // Device descriptions are separated by ',' symbol. // Key and value of a device description are separated by ":" symbol. // KeyN is the key of a device description, it could be one of the following // from SupportedAllowListKeyNames vector above. // DeviceName and PlatformName device descriptions are deprecated and will be // removed in one of the future releases. // ValueN is the value of a device description, it could be regex and some fixed // string. // Function should return parsed SYCL_DEVICE_ALLOWLIST variable value as // AllowListParsedT type (vector of maps), e.g.: // {{Key1: Value1, Key2: Value2}, ..., {Key1: Value1, ..., KeyN: ValueN}} AllowListParsedT parseAllowList(const std::string &AllowListRaw) { if (AllowListRaw.empty()) return {}; AllowListParsedT AllowListParsed; AllowListParsed.emplace_back(); constexpr std::array<const char *, 3> SupportedKeyNamesHaveFixedValue{ BackendNameKeyName, DeviceTypeKeyName, DeviceVendorIdKeyName}; constexpr std::array<const char *, 4> SupportedKeyNamesRequireRegexValue{ DriverVersionKeyName, PlatformVersionKeyName, DeviceNameKeyName, PlatformNameKeyName}; size_t KeyStart = 0, KeyEnd = 0, ValueStart = 0, ValueEnd = 0, DeviceDescIndex = 0; const char DelimiterBtwKeyAndValue = ':'; const char DelimiterBtwItemsInDeviceDesc = ','; const char DelimiterBtwDeviceDescs = '|'; if (AllowListRaw.find(DelimiterBtwKeyAndValue, KeyStart) == std::string::npos) throw sycl::runtime_error("SYCL_DEVICE_ALLOWLIST has incorrect format. For " "details, please refer to " "https://github.com/intel/llvm/blob/sycl/sycl/" "doc/EnvironmentVariables.md", PI_INVALID_VALUE); while ((KeyEnd = AllowListRaw.find(DelimiterBtwKeyAndValue, KeyStart)) != std::string::npos) { if ((ValueStart = AllowListRaw.find_first_not_of( DelimiterBtwKeyAndValue, KeyEnd)) == std::string::npos) break; const std::string &Key = AllowListRaw.substr(KeyStart, KeyEnd - KeyStart); // check that provided key is supported if (std::find(SupportedAllowListKeyNames.begin(), SupportedAllowListKeyNames.end(), Key) == SupportedAllowListKeyNames.end()) { throw sycl::runtime_error( "Unrecognized key in SYCL_DEVICE_ALLOWLIST. For details, please " "refer to " "https://github.com/intel/llvm/blob/sycl/sycl/doc/" "EnvironmentVariables.md", PI_INVALID_VALUE); } bool ShouldAllocateNewDeviceDescMap = false; std::string Value; auto &DeviceDescMap = AllowListParsed[DeviceDescIndex]; // check if Key is not already defined in DeviceDescMap, e.g., caused by the // following invalid syntax: Key1:Value1,Key2:Value2,Key1:Value3 if (DeviceDescMap.find(Key) == DeviceDescMap.end()) { // calculate and validate value which has fixed format if (std::find(SupportedKeyNamesHaveFixedValue.begin(), SupportedKeyNamesHaveFixedValue.end(), Key) != SupportedKeyNamesHaveFixedValue.end()) { ValueEnd = AllowListRaw.find(DelimiterBtwItemsInDeviceDesc, ValueStart); // check if it is the last Key:Value pair in the device description, and // correct end position of that value if (size_t ValueEndCand = AllowListRaw.find(DelimiterBtwDeviceDescs, ValueStart); (ValueEndCand != std::string::npos) && (ValueEndCand < ValueEnd)) { ValueEnd = ValueEndCand; ShouldAllocateNewDeviceDescMap = true; } if (ValueEnd == std::string::npos) ValueEnd = AllowListRaw.length(); Value = AllowListRaw.substr(ValueStart, ValueEnd - ValueStart); // post-processing checks for some values auto ValidateEnumValues = [&](std::string CheckingKeyName, auto SourceOfSupportedValues) { if (Key == CheckingKeyName) { bool ValueIsValid = false; for (const auto &Item : SourceOfSupportedValues) if (Value == Item.first) { ValueIsValid = true; break; } if (!ValueIsValid) throw sycl::runtime_error( "Value " + Value + " for key " + Key + " is not valid in " "SYCL_DEVICE_ALLOWLIST. For details, please refer to " "https://github.com/intel/llvm/blob/sycl/sycl/doc/" "EnvironmentVariables.md", PI_INVALID_VALUE); } }; // check that values of keys, which should have some fixed format, are // valid. E.g., for BackendName key, the allowed values are only ones // described in SyclBeMap ValidateEnumValues(BackendNameKeyName, getSyclBeMap()); ValidateEnumValues(DeviceTypeKeyName, getSyclDeviceTypeMap()); if (Key == DeviceVendorIdKeyName) { // DeviceVendorId should have hex format if (!std::regex_match(Value, std::regex("0[xX][0-9a-fA-F]+"))) { throw sycl::runtime_error( "Value " + Value + " for key " + Key + " is not valid in " "SYCL_DEVICE_ALLOWLIST. It should have the hex format. For " "details, please refer to " "https://github.com/intel/llvm/blob/sycl/sycl/doc/" "EnvironmentVariables.md", PI_INVALID_VALUE); } } } // calculate and validate value which has regex format else if (std::find(SupportedKeyNamesRequireRegexValue.begin(), SupportedKeyNamesRequireRegexValue.end(), Key) != SupportedKeyNamesRequireRegexValue.end()) { const std::string Prefix("{{"); // TODO: can be changed to string_view::starts_with after switching // DPC++ RT to C++20 if (Prefix != AllowListRaw.substr(ValueStart, Prefix.length())) { throw sycl::runtime_error("Key " + Key + " of SYCL_DEVICE_ALLOWLIST should have " "value which starts with " + Prefix, PI_INVALID_VALUE); } // cut off prefix from the value ValueStart += Prefix.length(); ValueEnd = ValueStart; const std::string Postfix("}}"); for (; ValueEnd < AllowListRaw.length() - Postfix.length() + 1; ++ValueEnd) { if (Postfix == AllowListRaw.substr(ValueEnd, Postfix.length())) break; // if it is the last iteration and next 2 symbols are not a postfix, // throw exception if (ValueEnd == AllowListRaw.length() - Postfix.length()) throw sycl::runtime_error( "Key " + Key + " of SYCL_DEVICE_ALLOWLIST should have " "value which ends with " + Postfix, PI_INVALID_VALUE); } size_t NextExpectedDelimiterPos = ValueEnd + Postfix.length(); // if it is not the end of the string, check that symbol next to a // postfix is a delimiter (, or ;) if ((AllowListRaw.length() != NextExpectedDelimiterPos) && (AllowListRaw[NextExpectedDelimiterPos] != DelimiterBtwItemsInDeviceDesc) && (AllowListRaw[NextExpectedDelimiterPos] != DelimiterBtwDeviceDescs)) throw sycl::runtime_error( "Unexpected symbol on position " + std::to_string(NextExpectedDelimiterPos) + ": " + AllowListRaw[NextExpectedDelimiterPos] + ". Should be either " + DelimiterBtwItemsInDeviceDesc + " or " + DelimiterBtwDeviceDescs, PI_INVALID_VALUE); if (AllowListRaw[NextExpectedDelimiterPos] == DelimiterBtwDeviceDescs) ShouldAllocateNewDeviceDescMap = true; Value = AllowListRaw.substr(ValueStart, ValueEnd - ValueStart); ValueEnd += Postfix.length(); } else assert(false && "Key should be either in SupportedKeyNamesHaveFixedValue " "or SupportedKeyNamesRequireRegexValue"); // add key and value to the map DeviceDescMap.emplace(Key, Value); } else throw sycl::runtime_error("Re-definition of key " + Key + " is not allowed in " "SYCL_DEVICE_ALLOWLIST", PI_INVALID_VALUE); KeyStart = ValueEnd; if (KeyStart != std::string::npos) ++KeyStart; if (ShouldAllocateNewDeviceDescMap) { ++DeviceDescIndex; AllowListParsed.emplace_back(); } } return AllowListParsed; } // Checking if we can allow device with device description DeviceDesc bool deviceIsAllowed(const DeviceDescT &DeviceDesc, const AllowListParsedT &AllowListParsed) { assert(std::all_of(SupportedAllowListKeyNames.begin(), SupportedAllowListKeyNames.end(), [&DeviceDesc](const auto &SupportedKeyName) { return DeviceDesc.find(SupportedKeyName) != DeviceDesc.end(); }) && "DeviceDesc map should have all supported keys for " "SYCL_DEVICE_ALLOWLIST."); auto EqualityComp = [&](const std::string &KeyName, const DeviceDescT &AllowListDeviceDesc) { // change to map::contains after switching DPC++ RT to C++20 if (AllowListDeviceDesc.find(KeyName) != AllowListDeviceDesc.end()) if (AllowListDeviceDesc.at(KeyName) != DeviceDesc.at(KeyName)) return false; return true; }; auto RegexComp = [&](const std::string &KeyName, const DeviceDescT &AllowListDeviceDesc) { if (AllowListDeviceDesc.find(KeyName) != AllowListDeviceDesc.end()) if (!std::regex_match(DeviceDesc.at(KeyName), std::regex(AllowListDeviceDesc.at(KeyName)))) return false; return true; }; bool ShouldDeviceBeAllowed = false; for (const auto &AllowListDeviceDesc : AllowListParsed) { if (!EqualityComp(BackendNameKeyName, AllowListDeviceDesc)) continue; if (!EqualityComp(DeviceTypeKeyName, AllowListDeviceDesc)) continue; if (!EqualityComp(DeviceVendorIdKeyName, AllowListDeviceDesc)) continue; if (!RegexComp(DriverVersionKeyName, AllowListDeviceDesc)) continue; if (!RegexComp(PlatformVersionKeyName, AllowListDeviceDesc)) continue; if (!RegexComp(DeviceNameKeyName, AllowListDeviceDesc)) continue; if (!RegexComp(PlatformNameKeyName, AllowListDeviceDesc)) continue; // no any continue was called on this iteration, so all parameters matched // successfully, so allow this device to use ShouldDeviceBeAllowed = true; break; } return ShouldDeviceBeAllowed; } void applyAllowList(std::vector<RT::PiDevice> &PiDevices, RT::PiPlatform PiPlatform, const plugin &Plugin) { AllowListParsedT AllowListParsed = parseAllowList(SYCLConfig<SYCL_DEVICE_ALLOWLIST>::get()); if (AllowListParsed.empty()) return; DeviceDescT DeviceDesc; // get BackendName value and put it to DeviceDesc sycl::backend Backend = Plugin.getBackend(); for (const auto &SyclBe : getSyclBeMap()) { if (SyclBe.second == Backend) { DeviceDesc.emplace(BackendNameKeyName, SyclBe.first); break; } } // get PlatformVersion value and put it to DeviceDesc DeviceDesc.emplace( PlatformVersionKeyName, sycl::detail::get_platform_info<std::string, info::platform::version>::get(PiPlatform, Plugin)); // get PlatformName value and put it to DeviceDesc DeviceDesc.emplace( PlatformNameKeyName, sycl::detail::get_platform_info<std::string, info::platform::name>::get( PiPlatform, Plugin)); int InsertIDx = 0; for (RT::PiDevice Device : PiDevices) { // get DeviceType value and put it to DeviceDesc RT::PiDeviceType PiDevType; Plugin.call<PiApiKind::piDeviceGetInfo>(Device, PI_DEVICE_INFO_TYPE, sizeof(RT::PiDeviceType), &PiDevType, nullptr); sycl::info::device_type DeviceType = pi::cast<info::device_type>(PiDevType); for (const auto &SyclDeviceType : getSyclDeviceTypeMap()) { if (SyclDeviceType.second == DeviceType) { const auto &DeviceTypeValue = SyclDeviceType.first; DeviceDesc[DeviceTypeKeyName] = DeviceTypeValue; break; } } // get DeviceVendorId value and put it to DeviceDesc uint32_t DeviceVendorIdUInt = sycl::detail::get_device_info<uint32_t, info::device::vendor_id>::get( Device, Plugin); std::stringstream DeviceVendorIdHexStringStream; DeviceVendorIdHexStringStream << "0x" << std::hex << DeviceVendorIdUInt; const auto &DeviceVendorIdValue = DeviceVendorIdHexStringStream.str(); DeviceDesc[DeviceVendorIdKeyName] = DeviceVendorIdValue; // get DriverVersion value and put it to DeviceDesc const auto &DriverVersionValue = sycl::detail::get_device_info< std::string, info::device::driver_version>::get(Device, Plugin); DeviceDesc[DriverVersionKeyName] = DriverVersionValue; // get DeviceName value and put it to DeviceDesc const auto &DeviceNameValue = sycl::detail::get_device_info<std::string, info::device::name>::get( Device, Plugin); DeviceDesc[DeviceNameKeyName] = DeviceNameValue; // check if we can allow device with such device description DeviceDesc if (deviceIsAllowed(DeviceDesc, AllowListParsed)) { PiDevices[InsertIDx++] = Device; } } PiDevices.resize(InsertIDx); } } // namespace detail } // namespace sycl } // __SYCL_INLINE_NAMESPACE(cl)
15,911
4,512
#include <torch/extension.h> #include <tuple> std::tuple<torch::Tensor, torch::Tensor> imputer_loss_op(const torch::Tensor &log_probs, const torch::Tensor &targets, const torch::Tensor &force_emits, at::IntArrayRef input_lengths, at::IntArrayRef target_lengths, int64_t BLANK, bool zero_infinity); torch::Tensor imputer_loss_backward_op( const torch::Tensor &grad, const torch::Tensor &log_probs, const torch::Tensor &targets, const torch::Tensor &force_emits, at::IntArrayRef input_lengths, at::IntArrayRef target_lengths, const torch::Tensor &neg_log_likelihood, const torch::Tensor &log_alpha, int64_t BLANK, bool zero_infinity); std::tuple<torch::Tensor, torch::Tensor, torch::Tensor> best_alignment_op(const torch::Tensor &log_probs, const torch::Tensor &targets, at::IntArrayRef input_lengths, at::IntArrayRef target_lengths, int64_t BLANK, bool zero_infinity); std::tuple<torch::Tensor, torch::Tensor> imputer_loss( const torch::Tensor &log_probs, const torch::Tensor &targets, const torch::Tensor &force_emits, const torch::Tensor &input_lengths, const torch::Tensor &target_lengths, int64_t BLANK, bool zero_infinity) { torch::Tensor ilc = input_lengths.to(at::Device(at::kCPU), at::kLong).contiguous(); torch::Tensor tlc = target_lengths.to(at::Device(at::kCPU), at::kLong).contiguous(); at::IntArrayRef il(ilc.data_ptr<int64_t>(), ilc.numel()); at::IntArrayRef tl(tlc.data_ptr<int64_t>(), tlc.numel()); auto res = imputer_loss_op(log_probs, targets.to(log_probs.device(), at::kLong), force_emits.to(log_probs.device(), at::kLong), il, tl, BLANK, zero_infinity); return res; } torch::Tensor imputer_loss_backward( const torch::Tensor &grad, const torch::Tensor &log_probs, const torch::Tensor &targets, const torch::Tensor &force_emits, const torch::Tensor &input_lengths, const torch::Tensor &target_lengths, const torch::Tensor &neg_log_likelihood, const torch::Tensor &log_alpha, int64_t BLANK, bool zero_infinity) { torch::Tensor ilc = input_lengths.to(at::Device(at::kCPU), at::kLong).contiguous(); torch::Tensor tlc = target_lengths.to(at::Device(at::kCPU), at::kLong).contiguous(); at::IntArrayRef il(ilc.data_ptr<int64_t>(), ilc.numel()); at::IntArrayRef tl(tlc.data_ptr<int64_t>(), tlc.numel()); torch::Tensor res; res = imputer_loss_backward_op( grad, log_probs, targets.to(log_probs.device(), at::kLong), force_emits.to(log_probs.device(), at::kLong), il, tl, neg_log_likelihood, log_alpha, BLANK, zero_infinity); return res; } std::tuple<torch::Tensor, torch::Tensor, torch::Tensor> best_alignment(const torch::Tensor &log_probs, const torch::Tensor &targets, const torch::Tensor &input_lengths, const torch::Tensor &target_lengths, int64_t BLANK, bool zero_infinity) { torch::Tensor ilc = input_lengths.to(at::Device(at::kCPU), at::kLong).contiguous(); torch::Tensor tlc = target_lengths.to(at::Device(at::kCPU), at::kLong).contiguous(); at::IntArrayRef il(ilc.data_ptr<int64_t>(), ilc.numel()); at::IntArrayRef tl(tlc.data_ptr<int64_t>(), tlc.numel()); auto res = best_alignment_op(log_probs, targets.to(log_probs.device(), at::kLong), il, tl, BLANK, zero_infinity); return res; } PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("imputer_loss", &imputer_loss, "calculate imputer loss"); m.def("imputer_loss_backward", &imputer_loss_backward, "calculate imputer loss gradient"); m.def("best_alignment", &best_alignment, "get best alignments for ctc"); }
3,759
1,479
class Solution { public: bool isHappy(int n) { unordered_set<int> visited{n}; while (n != 1) { int temp = n; n = 0; while (temp) { int i = temp % 10; n += i * i; temp /= 10; } if (visited.count(n)) { return false; } visited.insert(n); } return true; } };
452
137
#include <ymj.h> #include <array> #include <cstring> #include <cstdio> using Hand = std::array<uint8_t, YMJ_HAND_SIZE>; void callback(const ymj_state *state) { std::printf("(%2d)", state->head); for (int i = 0; i < 4; i++) { std::printf("(%c %d)", state->mentu[i].is_kotu ? 'k' : 's', state->mentu[i].start); } std::putchar('\n'); } void create_state(ymj_state *state, const Hand &hand) { std::memset(state, 0, sizeof(*state)); for (const auto &hai : hand) { state->hai_count[hai]++; } } int main() { ymj_state state; Hand hand {1,1,1,2,2,2,3,3,3,4,4,4,5,5}; create_state(&state, hand); int ret = ymj_for_each_hora(&state, callback); std::printf("ymj_for_each_hora(): %d\n", ret); return 0; }
722
339
// 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 "chromeos/services/libassistant/settings_controller.h" #include "base/test/mock_callback.h" #include "base/test/task_environment.h" #include "chromeos/assistant/internal/test_support/fake_assistant_manager.h" #include "chromeos/assistant/internal/test_support/fake_assistant_manager_internal.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/icu/source/common/unicode/locid.h" namespace chromeos { namespace libassistant { namespace { #define EXPECT_NO_CALLS(args...) EXPECT_CALL(args).Times(0); #define IGNORE_CALLS(args...) EXPECT_CALL(args).Times(testing::AnyNumber()); // The auth tokens are pairs of <user, token> using AuthTokens = std::vector<std::pair<std::string, std::string>>; std::vector<mojom::AuthenticationTokenPtr> ToVector( mojom::AuthenticationTokenPtr token) { std::vector<mojom::AuthenticationTokenPtr> result; result.push_back(std::move(token)); return result; } class AssistantManagerInternalMock : public assistant::FakeAssistantManagerInternal { public: AssistantManagerInternalMock() = default; AssistantManagerInternalMock(const AssistantManagerInternalMock&) = delete; AssistantManagerInternalMock& operator=(const AssistantManagerInternalMock&) = delete; ~AssistantManagerInternalMock() override = default; // assistant::FakeAssistantManagerInternal implementation: MOCK_METHOD(void, SetLocaleOverride, (const std::string& locale)); MOCK_METHOD(void, SetOptions, (const assistant_client::InternalOptions& options, assistant_client::SuccessCallbackInternal on_done)); MOCK_METHOD(void, SendUpdateSettingsUiRequest, (const std::string& s3_request_update_settings_ui_request_proto, const std::string& user_id, assistant_client::VoicelessResponseCallback on_done)); }; class AssistantManagerMock : public assistant::FakeAssistantManager { public: AssistantManagerMock() = default; AssistantManagerMock(const AssistantManagerMock&) = delete; AssistantManagerMock& operator=(const AssistantManagerMock&) = delete; ~AssistantManagerMock() override = default; // assistant::FakeAssistantManager implementation: MOCK_METHOD(void, EnableListening, (bool value)); MOCK_METHOD(void, SetAuthTokens, (const AuthTokens&)); }; } // namespace class AssistantSettingsControllerTest : public testing::Test { public: AssistantSettingsControllerTest() : assistant_manager_(std::make_unique<AssistantManagerMock>()), assistant_manager_internal_( std::make_unique< testing::StrictMock<AssistantManagerInternalMock>>()) {} AssistantSettingsControllerTest(const AssistantSettingsControllerTest&) = delete; AssistantSettingsControllerTest& operator=( const AssistantSettingsControllerTest&) = delete; ~AssistantSettingsControllerTest() override = default; SettingsController& controller() { return controller_; } void CreateLibassistant() { controller().OnAssistantManagerCreated(assistant_manager_.get(), assistant_manager_internal_.get()); } void StartLibassistant() { controller().OnAssistantManagerStarted(assistant_manager_.get(), assistant_manager_internal_.get()); } void DestroyLibassistant() { controller().OnDestroyingAssistantManager( assistant_manager_.get(), assistant_manager_internal_.get()); assistant_manager_ = nullptr; assistant_manager_internal_ = nullptr; assistant_manager_ = std::make_unique<AssistantManagerMock>(); assistant_manager_internal_ = std::make_unique<testing::StrictMock<AssistantManagerInternalMock>>(); } void CreateAndStartLibassistant() { CreateLibassistant(); StartLibassistant(); } AssistantManagerInternalMock& assistant_manager_internal_mock() { return *assistant_manager_internal_; } AssistantManagerMock& assistant_manager_mock() { return *assistant_manager_; } private: base::test::SingleThreadTaskEnvironment environment_; SettingsController controller_; std::unique_ptr<AssistantManagerMock> assistant_manager_; std::unique_ptr<AssistantManagerInternalMock> assistant_manager_internal_; }; TEST_F(AssistantSettingsControllerTest, ShouldNotCrashIfLibassistantIsNotCreated) { controller().SetAuthenticationTokens({}); controller().SetHotwordEnabled(true); controller().SetListeningEnabled(true); controller().SetLocale("locale"); controller().SetSpokenFeedbackEnabled(true); } TEST_F(AssistantSettingsControllerTest, ShouldNotCrashAfterDestroyingLibassistant) { CreateAndStartLibassistant(); DestroyLibassistant(); controller().SetAuthenticationTokens({}); controller().SetHotwordEnabled(true); controller().SetListeningEnabled(true); controller().SetLocale("locale"); controller().SetSpokenFeedbackEnabled(true); } TEST_F(AssistantSettingsControllerTest, ShouldResetAllValuesWhenLibassistantIsDestroyed) { controller().SetAuthenticationTokens({}); controller().SetHotwordEnabled(true); controller().SetLocale("locale"); controller().SetSpokenFeedbackEnabled(true); DestroyLibassistant(); // After destroying Libassistant, the settings should be cleared. // We test this by ensuring they are not applied when Libassistant starts. EXPECT_NO_CALLS(assistant_manager_internal_mock(), SetLocaleOverride); EXPECT_NO_CALLS(assistant_manager_internal_mock(), SetOptions); EXPECT_NO_CALLS(assistant_manager_internal_mock(), SendUpdateSettingsUiRequest); EXPECT_NO_CALLS(assistant_manager_mock(), SetAuthTokens); CreateAndStartLibassistant(); } TEST_F(AssistantSettingsControllerTest, ShouldSetLocale) { CreateLibassistant(); EXPECT_CALL(assistant_manager_internal_mock(), SetLocaleOverride("locale")); controller().SetLocale("locale"); } TEST_F(AssistantSettingsControllerTest, ShouldUseDefaultLocaleIfSettingToEmptyString) { const std::string default_locale = icu::Locale::getDefault().getName(); CreateLibassistant(); EXPECT_CALL(assistant_manager_internal_mock(), SetLocaleOverride(default_locale)); controller().SetLocale(""); } TEST_F(AssistantSettingsControllerTest, ShouldNotSetInternalOptionsWhenLocaleIsNotSet) { CreateLibassistant(); EXPECT_NO_CALLS(assistant_manager_internal_mock(), SetOptions); controller().SetSpokenFeedbackEnabled(true); } TEST_F(AssistantSettingsControllerTest, ShouldNotSetInternalOptionsWhenSpokenFeedbackEnabledIsNotSet) { IGNORE_CALLS(assistant_manager_internal_mock(), SetLocaleOverride); CreateLibassistant(); EXPECT_NO_CALLS(assistant_manager_internal_mock(), SetOptions); controller().SetLocale("locale"); } TEST_F(AssistantSettingsControllerTest, ShouldSetInternalOptionsWhenLocaleIsUpdated) { IGNORE_CALLS(assistant_manager_internal_mock(), SetLocaleOverride); controller().SetSpokenFeedbackEnabled(true); CreateLibassistant(); EXPECT_CALL(assistant_manager_internal_mock(), SetOptions); controller().SetLocale("locale"); } TEST_F(AssistantSettingsControllerTest, ShouldSetInternalOptionsWhenSpokenFeedbackEnabledIsUpdated) { IGNORE_CALLS(assistant_manager_internal_mock(), SetLocaleOverride); controller().SetLocale("locale"); CreateLibassistant(); EXPECT_CALL(assistant_manager_internal_mock(), SetOptions); controller().SetSpokenFeedbackEnabled(true); } TEST_F(AssistantSettingsControllerTest, ShouldSetInternalOptionsAndLocaleWhenLibassistantIsCreated) { controller().SetLocale("locale"); controller().SetSpokenFeedbackEnabled(true); EXPECT_CALL(assistant_manager_internal_mock(), SetLocaleOverride); EXPECT_CALL(assistant_manager_internal_mock(), SetOptions); CreateLibassistant(); } TEST_F(AssistantSettingsControllerTest, ShouldNotSetDeviceOptionsWhenLocaleIsNotSet) { IGNORE_CALLS(assistant_manager_internal_mock(), SetLocaleOverride); CreateAndStartLibassistant(); EXPECT_NO_CALLS(assistant_manager_internal_mock(), SendUpdateSettingsUiRequest); controller().SetHotwordEnabled(true); } TEST_F(AssistantSettingsControllerTest, ShouldNotSetDeviceOptionsWhenHotwordEnabledIsNotSet) { IGNORE_CALLS(assistant_manager_internal_mock(), SetLocaleOverride); CreateAndStartLibassistant(); EXPECT_NO_CALLS(assistant_manager_internal_mock(), SendUpdateSettingsUiRequest); controller().SetLocale("locale"); } TEST_F(AssistantSettingsControllerTest, ShouldSetDeviceOptionsWhenLocaleIsUpdated) { IGNORE_CALLS(assistant_manager_internal_mock(), SetLocaleOverride); CreateAndStartLibassistant(); controller().SetHotwordEnabled(true); EXPECT_CALL(assistant_manager_internal_mock(), SendUpdateSettingsUiRequest); controller().SetLocale("locale"); } TEST_F(AssistantSettingsControllerTest, ShouldSetDeviceOptionsWhenHotwordEnabledIsUpdated) { IGNORE_CALLS(assistant_manager_internal_mock(), SetLocaleOverride); CreateAndStartLibassistant(); controller().SetLocale("locale"); EXPECT_CALL(assistant_manager_internal_mock(), SendUpdateSettingsUiRequest); controller().SetHotwordEnabled(true); } TEST_F(AssistantSettingsControllerTest, ShouldSetDeviceOptionsWhenLibassistantIsStarted) { IGNORE_CALLS(assistant_manager_internal_mock(), SetLocaleOverride); CreateLibassistant(); controller().SetLocale("locale"); controller().SetHotwordEnabled(true); EXPECT_CALL(assistant_manager_internal_mock(), SendUpdateSettingsUiRequest); StartLibassistant(); } TEST_F(AssistantSettingsControllerTest, ShouldSetAuthenticationTokens) { const AuthTokens expected = {{"user", "token"}}; CreateLibassistant(); EXPECT_CALL(assistant_manager_mock(), SetAuthTokens(expected)); controller().SetAuthenticationTokens( ToVector(mojom::AuthenticationToken::New("user", "token"))); } TEST_F(AssistantSettingsControllerTest, ShouldSetAuthenticationTokensWhenLibassistantIsCreated) { const AuthTokens expected = {{"user", "token"}}; controller().SetAuthenticationTokens( ToVector(mojom::AuthenticationToken::New("user", "token"))); EXPECT_CALL(assistant_manager_mock(), SetAuthTokens(expected)); CreateLibassistant(); } TEST_F(AssistantSettingsControllerTest, ShouldSupportEmptyAuthenticationTokenList) { CreateLibassistant(); const AuthTokens expected = {}; EXPECT_CALL(assistant_manager_mock(), SetAuthTokens(expected)); controller().SetAuthenticationTokens({}); } TEST_F(AssistantSettingsControllerTest, ShouldSetListeningEnabled) { CreateLibassistant(); EXPECT_CALL(assistant_manager_mock(), EnableListening(true)); controller().SetListeningEnabled(true); } TEST_F(AssistantSettingsControllerTest, ShouldSetListeningEnabledWhenLibassistantIsCreated) { controller().SetListeningEnabled(false); EXPECT_CALL(assistant_manager_mock(), EnableListening(false)); CreateLibassistant(); } TEST_F(AssistantSettingsControllerTest, GetSettingsShouldCallCallbackEvenIfLibassistantIsNotStarted) { base::MockCallback<SettingsController::GetSettingsCallback> callback; EXPECT_CALL(callback, Run(std::string{})); controller().GetSettings("selector", callback.Get()); } TEST_F(AssistantSettingsControllerTest, GetSettingsShouldCallCallbackIfLibassistantIsStopped) { CreateAndStartLibassistant(); base::MockCallback<SettingsController::GetSettingsCallback> callback; controller().GetSettings("selector", callback.Get()); EXPECT_CALL(callback, Run(std::string{})); DestroyLibassistant(); } TEST_F(AssistantSettingsControllerTest, UpdateSettingsShouldCallCallbackEvenIfLibassistantIsNotStarted) { base::MockCallback<SettingsController::UpdateSettingsCallback> callback; EXPECT_CALL(callback, Run(std::string{})); controller().UpdateSettings("selector", callback.Get()); } TEST_F(AssistantSettingsControllerTest, UpdateSettingsShouldCallCallbackIfLibassistantIsStopped) { IGNORE_CALLS(assistant_manager_internal_mock(), SendUpdateSettingsUiRequest); CreateAndStartLibassistant(); base::MockCallback<SettingsController::UpdateSettingsCallback> callback; controller().UpdateSettings("selector", callback.Get()); EXPECT_CALL(callback, Run(std::string{})); DestroyLibassistant(); } } // namespace libassistant } // namespace chromeos
12,637
3,732
/* Copyright (C) GridGain Systems. 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. */ /* _________ _____ __________________ _____ * __ ____/___________(_)______ /__ ____/______ ____(_)_______ * _ / __ __ ___/__ / _ __ / _ / __ _ __ `/__ / __ __ \ * / /_/ / _ / _ / / /_/ / / /_/ / / /_/ / _ / _ / / / * \____/ /_/ /_/ \_,__/ \____/ \__,_/ /_/ /_/ /_/ */ #ifndef GRID_CLIENT_COMPUTE_PROJECTION_IMP_HPP #define GRID_CLIENT_COMPUTE_PROJECTION_IMP_HPP #include "gridgain/gridclientcompute.hpp" #include "gridgain/impl/gridclientprojection.hpp" #include "gridgain/impl/utils/gridthreadpool.hpp" class GridTopologyRequestCommand; /** * Implementation of GridClientCompute. */ class GridClientComputeProjectionImpl : public GridClientCompute, public GridClientProjectionImpl { public: /** * Constructor. * * @param data Shared data. * @param prjLsnr Projection listener. * @param pFilter Node filter (may be omitted). */ GridClientComputeProjectionImpl(TGridClientSharedDataPtr data, GridClientProjectionListener& prjLsnr, TGridClientNodePredicatePtr pFilter, TGridClientLoadBalancerPtr balancer, TGridThreadPoolPtr& threadPool); /** * Creates a projection that will communicate only with specified remote node. * <p> * If current projection is dynamic projection, then this method will check is passed node is in topology. * If any filters were specified in current topology, this method will check if passed node is accepted by * the filter. If current projection was restricted to any subset of nodes, this method will check if * passed node is in that subset. If any of the checks fails an exception will be thrown. * * @param node Single node to which this projection will be restricted. * @return Resulting static projection that is bound to a given node. * @throw GridClientException If resulting projection is empty. */ virtual TGridClientComputePtr projection(const GridClientNode& node); /** * Creates a projection that will communicate only with specified remote nodes. For any particular call * a node to communicate will be selected with passed balancer.. * <p> * If current projection is dynamic projection, then this method will check is passed nodes are in topology. * If any filters were specified in current topology, this method will check if passed nodes are accepted by * the filter. If current projection was restricted to any subset of nodes, this method will check if * passed nodes are in that subset (i.e. calculate the intersection of two collections). * If any of the checks fails an exception will be thrown. * * @param nodes Collection of nodes to which this projection will be restricted. * @param balancer Balancer that will select nodes in resulting projection. * @return Resulting static projection that is bound to a given nodes. * @throw GridClientException If resulting projection is empty. */ virtual TGridClientComputePtr projection(const TGridClientNodeList& nodes); /** * Creates a projection that will communicate only with nodes that are accepted by the passed filter. * <p> * If current projection is dynamic projection, then filter will be applied to the most relevant * topology snapshot every time a node to communicate is selected. If current projection is a static projection, * then resulting projection will only be restricted to nodes that were in parent projection and were * accepted by the passed filter. If any of the checks fails an exception will be thrown. * * @param filter Filter that will select nodes for projection. * @return Resulting projection (static or dynamic, depending in parent projection type). * @throws GridClientException If resulting projection is empty. */ virtual TGridClientComputePtr projection(TGridClientNodePredicatePtr filter); /** * Creates a projection that will communicate only with nodes that are accepted by the passed filter. * <p> * If current projection is dynamic projection, then filter will be applied to the most relevant * topology snapshot every time a node to communicate is selected. If current projection is a static projection, * then resulting projection will only be restricted to nodes that were in parent projection and were * accepted by the passed filter. If any of the checks fails an exception will be thrown. * * @param filter Filter that will select nodes for projection. * @return Resulting projection (static or dynamic, depending in parent projection type). * @throws GridClientException If resulting projection is empty. */ virtual TGridClientComputePtr projection(std::function<bool (const GridClientNode&)> & filter); /** * Creates a projection that will communicate only with nodes that are accepted by the passed filter. The * balancer passed will override default balancer specified in configuration. * <p> * If current projection is dynamic projection, then filter will be applied to the most relevant * topology snapshot every time a node to communicate is selected. If current projection is a static projection, * then resulting projection will only be restricted to nodes that were in parent projection and were * accepted by the passed filter. If any of the checks fails an exception will be thrown. * * @param filter Filter that will select nodes for projection. * @param balancer Balancer that will select balanced node in resulting projection. * @return Resulting projection (static or dynamic, depending in parent projection type). * @throws GridClientException If resulting projection is empty. */ virtual TGridClientComputePtr projection(TGridClientNodePredicatePtr filter, TGridClientLoadBalancerPtr balancer); /** * Creates a projection that will communicate only with nodes that are accepted by the passed filter. The * balancer passed will override default balancer specified in configuration. * <p> * If current projection is dynamic projection, then filter will be applied to the most relevant * topology snapshot every time a node to communicate is selected. If current projection is a static projection, * then resulting projection will only be restricted to nodes that were in parent projection and were * accepted by the passed filter. If any of the checks fails an exception will be thrown. * * @param filter Filter that will select nodes for projection. * @param balancer Balancer that will select balanced node in resulting projection. * @return Resulting projection (static or dynamic, depending in parent projection type). * @throws GridClientException If resulting projection is empty. */ virtual TGridClientComputePtr projection(std::function<bool (const GridClientNode&)> & filter, TGridClientLoadBalancerPtr balancer); /** * Creates a projection that will communicate only with specified remote nodes. For any particular call * a node to communicate will be selected with passed balancer.. * <p> * If current projection is dynamic projection, then this method will check is passed nodes are in topology. * If any filters were specified in current topology, this method will check if passed nodes are accepted by * the filter. If current projection was restricted to any subset of nodes, this method will check if * passed nodes are in that subset (i.e. calculate the intersection of two collections). * If any of the checks fails an exception will be thrown. * * @param nodes Collection of nodes to which this projection will be restricted. * @param balancer Balancer that will select nodes in resulting projection. * @return Resulting static projection that is bound to a given nodes. * @throws GridClientException If resulting projection is empty. */ virtual TGridClientComputePtr projection(const TGridClientNodeList& nodes, TGridClientLoadBalancerPtr balancer); /** * Gets balancer used by projection. * * @return Instance of {@link GridClientLoadBalancer}. */ virtual TGridClientLoadBalancerPtr balancer() const; /** * Executes task. * * @param taskName Task name or task class name. * @param taskArg Optional task argument. * @return Task execution result. * @throw GridClientException In case of error. * @throw GridServerUnreachableException If none of the servers can be reached. * @throw GridClientClosedException If client was closed manually. */ virtual GridClientVariant execute(const std::string& taskName, const GridClientVariant& taskArg); /** * Asynchronously executes task. * * @param taskName Task name or task class name. * @param taskArg Optional task argument. * @return Future. */ virtual TGridClientFutureVariant executeAsync(const std::string& taskName, const GridClientVariant& taskArg); /** * Executes task using cache affinity key for routing. This way the task will start executing * exactly on the node where this affinity key is cached. * * @param taskName Task name or task class name. * @param cacheName Name of the cache on which affinity should be calculated. * @param affKey Affinity key. * @param taskArg Optional task argument. * @return Task execution result. * @throw GridClientException In case of error. * @throw GridServerUnreachableException If none of the servers can be reached. * @throw GridClientClosedException If client was closed manually. */ virtual GridClientVariant affinityExecute(const std::string& taskName, const std::string& cacheName, const GridClientVariant& affKey, const GridClientVariant& taskArg); /** * Asynchronously executes task using cache affinity key for routing. This way * the task will start executing exactly on the node where this affinity key is cached. * * @param taskName Task name or task class name. * @param cacheName Name of the cache on which affinity should be calculated. * @param affKey Affinity key. * @param taskArg Optional task argument. * @return Future. */ virtual TGridClientFutureVariant affinityExecuteAsync(const std::string& taskName, const std::string& cacheName, const GridClientVariant& affKey, const GridClientVariant& taskArg); /** * Gets node with given id from most recently refreshed topology. * * @param id Node ID. * @return Node for given ID or <tt>null</tt> if node with given id was not found. */ virtual TGridClientNodePtr node(const GridClientUuid& id) const; /** * Gets nodes that pass the filter. If this compute instance is a projection, then only * nodes that pass projection criteria will be passed to the filter. * * @param filter Node filter. * @return Collection of nodes that satisfy provided filter. */ virtual TGridClientNodeList nodes(TGridClientNodePredicatePtr filter) const; /** * Gets nodes that pass the filter. If this compute instance is a projection, then only * nodes that pass projection criteria will be passed to the filter. * * @param filter Node filter. * @return Collection of nodes that satisfy provided filter. */ virtual TGridClientNodeList nodes(std::function<bool (const GridClientNode&)> & filter) const; /** * Gets all nodes in the projection. * * @param filter Node filter. * @return Collection of nodes that satisfy provided filter. */ virtual TGridClientNodeList nodes() const; /** * Gets nodes that passes the filter. If this compute instance is a projection, then only * nodes that passes projection criteria will be passed to the filter. * * @param filter Node filter. * @return Collection of nodes that satisfy provided filter. */ virtual TGridClientNodeList nodes(const std::vector<GridClientUuid>& ids) const; /** * Gets node by its ID. * * @param id Node ID. * @param includeAttrs Whether to include node attributes. * @param includeMetrics Whether to include node metrics. * @return Node descriptor or <tt>null</tt> if node doesn't exist. * @throw GridClientException In case of error. * @throw GridServerUnreachableException If none of the servers can be reached. * @throw GridClientClosedException If client was closed manually. */ virtual TGridClientNodePtr refreshNode(const GridClientUuid& id, bool includeAttrs, bool includeMetrics); /** * Asynchronously gets node by its ID. * * @param id Node ID. * @param includeAttrs Whether to include node attributes. * @param includeMetrics Whether to include node metrics. * @return Future. */ virtual TGridClientNodeFuturePtr refreshNodeAsync(const GridClientUuid& id, bool includeAttrs, bool includeMetrics); /** * Gets node by IP address. * * @param ip IP address. * @param includeAttrs Whether to include node attributes. * @param includeMetrics Whether to include node metrics. * @return Node descriptor or <tt>null</tt> if node doesn't exist. * @throw GridClientException In case of error. * @throw GridServerUnreachableException If none of the servers can be reached. * @throw GridClientClosedException If client was closed manually. */ virtual TGridClientNodePtr refreshNode(const std::string& ip, bool includeAttrs, bool includeMetrics); /** * Asynchronously gets node by IP address. * * @param ip IP address. * @param includeAttrs Whether to include node attributes. * @param includeMetrics Whether to include node metrics. * @return Future. */ virtual TGridClientNodeFuturePtr refreshNodeAsync(const std::string& ip, bool includeAttrs, bool includeMetrics); /** * Gets current topology. * * @param includeAttrs Whether to include node attributes. * @param includeMetrics Whether to include node metrics. * @return Node descriptors. * @throw GridClientException In case of error. * @throw GridServerUnreachableException If none of the servers can be reached. * @throw GridClientClosedException If client was closed manually. */ virtual TGridClientNodeList refreshTopology(bool includeAttrs, bool includeMetrics); /** * Asynchronously gets current topology. * * @param includeAttrs Whether to include node attributes. * @param includeMetrics Whether to include node metrics. * @return Future. */ virtual TGridClientNodeFutureList refreshTopologyAsync(bool includeAttrs, bool includeMetrics); /** * Gets contents of default log file (<tt>GRIDGAIN_HOME/work/log/gridgain.log</tt>). * * @param lineFrom Index of line from which log is get, inclusive (starting from 0). * @param lineTo Index of line to which log is get, inclusive (starting from 0). * @return Log contents. * @throw GridClientException In case of error. * @throw GridServerUnreachableException If none of the servers can be reached. * @throw GridClientClosedException If client was closed manually. */ virtual std::vector<std::string> log(int lineFrom, int lineTo); /** * Asynchronously gets contents of default log file * (<tt>GRIDGAIN_HOME/work/log/gridgain.log</tt>). * * @param lineFrom Index of line from which log is get, inclusive (starting from 0). * @param lineTo Index of line to which log is get, inclusive (starting from 0). * @return Future. */ virtual TGridFutureStringList logAsync(int lineFrom, int lineTo); /** * Gets contents of custom log file. * * @param path Log file path. Can be absolute or relative to GRIDGAIN_HOME. * @param lineFrom Index of line from which log is get, inclusive (starting from 0). * @param lineTo Index of line to which log is get, inclusive (starting from 0). * @return Log contents. * @throw GridClientException In case of error. * @throw GridServerUnreachableException If none of the servers can be reached. * @throw GridClientClosedException If client was closed manually. */ virtual std::vector<std::string> log(const std::string& path, int lineFrom, int lineTo); /** * Asynchronously gets contents of custom log file. * * @param path Log file path. Can be absolute or relative to GRIDGAIN_HOME. * @param lineFrom Index of line from which log is get, inclusive (starting from 0). * @param lineTo Index of line to which log is get, inclusive (starting from 0). * @return Future. */ virtual TGridFutureStringList logAsync(const std::string& path, int lineFrom, int lineTo); /** * Invalidates this data instance. This is done by the client to indicate * that is has been stopped. After this call, all interface methods * will throw GridClientClosedException. */ void invalidate(); protected: /** * Creates subprojection based on node filter and balancer. * * @param filter Node filter. * @param balancer Load balancer. */ TGridClientComputePtr makeProjection(TGridClientNodePredicatePtr filter, TGridClientLoadBalancerPtr balancer); private: /** * Internal refresh topology command. * * @param cmd Topology command to execute. * @return Refreshed nodes. */ TGridClientNodeList refreshTopology(GridTopologyRequestCommand& cmd); /** List of current subprojections. */ std::vector< std::shared_ptr<GridClientCompute> > subProjections; /** Invalidated flag. */ TGridAtomicBool invalidated; /** Thread pool for running async operations. */ TGridThreadPoolPtr threadPool; }; #endif
18,727
4,763
#ifndef __EIGEN_INCLUDER_HPP__ #define __EIGEN_INCLUDER_HPP__ #include <eigen3/Eigen/Core> #include <eigen3/Eigen/Dense> #include <eigen3/Eigen/Sparse> #include <eigen3/Eigen/SparseCholesky> #include <eigen3/Eigen/SparseQR> #include <eigen3/Eigen/LU> #include <eigen3/Eigen/Cholesky> #include <eigen3/Eigen/Geometry> #include <eigen3/Eigen/OrderingMethods> using Eigen::SimplicialLLT; using Eigen::SimplicialLDLT; using Eigen::COLAMDOrdering; using Eigen::LDLT; using Eigen::LLT; using Eigen::PartialPivLU; using Eigen::Matrix; using Eigen::MatrixXd; using Eigen::Matrix2d; using Eigen::Matrix3d; using Eigen::VectorXd; using Vector6d = Eigen::Vector<double, 6>; using Eigen::Vector3d; using Eigen::Vector2d; using Eigen::MatrixXi; using Eigen::SparseMatrix; using Eigen::SparseVector; using Eigen::SparseQR; using Eigen::Map; using Eigen::Quaterniond; using Eigen::Triplet; using Eigen::ArrayXd; using Eigen::placeholders::all; typedef Eigen::Array<bool,Eigen::Dynamic,1> ArrayXb; template <typename Type, int Size> using Vector = Matrix<Type, Size, 1>; #endif
1,066
442
#include "SettingsLoader.h" #include "../Core/Engine.h" namespace Eunoia { void SettingsLoader::WriteSettingsToFile(const String& path, const EunoiaSettings& settings) { FILE* file = fopen(path.C_Str(), "wb"); if (!file) return; fwrite(&settings, sizeof(EunoiaSettings), 1, file); fclose(file); } void SettingsLoader::LoadSettingsFromFile(const String& path, b32 applySettings) { FILE* file = fopen(path.C_Str(), "rb"); if (!file) return; EunoiaSettings settings; fread(&settings, sizeof(EunoiaSettings), 1, file); fclose(file); if (applySettings) ApplySettings(settings); } void SettingsLoader::ApplySettings(const EunoiaSettings& settings) { Renderer2D* r2D = Engine::GetRenderer()->GetRenderer2D(); Renderer3D* r3D = Engine::GetRenderer()->GetRenderer3D(); r2D->SetProjection(settings.settings2D.projection); r2D->SetSpritePosOrigin(settings.settings2D.origin); r3D->SetAmbient(settings.settings3D.ambient); r3D->SetBloomThreshold(settings.settings3D.bloomThreshold); r3D->SetBloomBlurIterationCount(settings.settings3D.bloomBlurIterCount); } }
1,109
428
/** * Copyright (c) 2017-present, Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include "logdevice/test/utils/NodesConfigurationFileUpdater.h" #include "logdevice/common/configuration/nodes/NodesConfigurationCodec.h" namespace facebook { namespace logdevice { namespace IntegrationTestUtils { namespace { constexpr std::chrono::seconds kPollingInterval{1}; } NodesConfigurationFileUpdater::NodesConfigurationFileUpdater( std::shared_ptr<UpdateableNodesConfiguration> updateable_nodes_config, std::unique_ptr<configuration::nodes::NodesConfigurationStore> store) : updateable_nodes_config_(std::move(updateable_nodes_config)), store_(std::move(store)) {} NodesConfigurationFileUpdater::~NodesConfigurationFileUpdater() { shutdown_signaled = true; polling_thread_.join(); } void NodesConfigurationFileUpdater::start() { polling_thread_ = std::thread(&NodesConfigurationFileUpdater::pollingLoop, this); } void NodesConfigurationFileUpdater::pollingLoop() { while (!shutdown_signaled.load()) { folly::Optional<membership::MembershipVersion::Type> current_version; if (auto current_nc = updateable_nodes_config_->get(); current_nc != nullptr) { current_version = current_nc->getVersion(); } std::string serialized_nc; auto status = store_->getConfigSync(&serialized_nc, current_version); if (status == Status::OK) { auto new_nc = configuration::nodes::NodesConfigurationCodec::deserialize( std::move(serialized_nc)); ld_check(new_nc); updateable_nodes_config_->update(std::move(new_nc)); } else if (status == Status::UPTODATE) { // Do nothing } else { ld_error("Failed reading the nodes configuration from the store: %s", error_name(status)); } std::this_thread::sleep_for(kPollingInterval); } } }}} // namespace facebook::logdevice::IntegrationTestUtils
2,059
613
#include "editremotedialog.h" #include "mainwindow.h" #include "ui_mainwindow.h" #include <QDesktopServices> #include <QSettings> #include <dialogmaster.h> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), model(new MountModel(this)), sortModel(new QSortFilterProxyModel(this)), trayIco(new QSystemTrayIcon(windowIcon(), this)) { ui->setupUi(this); ui->treeView->setParent(this); centralWidget()->deleteLater(); setCentralWidget(ui->treeView); sortModel->setSourceModel(model); ui->treeView->setModel(sortModel); auto s = new QAction(this); s->setSeparator(true); ui->treeView->addActions({ ui->actionMount, ui->actionOpen_Folder, s, ui->actionEdit_Host, ui->actionRemove_Host }); trayIco->setToolTip(QApplication::applicationDisplayName()); auto menu = new QMenu(this); menu->addAction(QIcon::fromTheme(QStringLiteral("window-new")), tr("Show main window"), this, &MainWindow::show); menu->addMenu(model->createMountMenu(menu)); menu->addAction(ui->action_Reload_Mounts); menu->addSeparator(); auto runAction = menu->addAction(QIcon::fromTheme(QStringLiteral("games-config-options")), tr("Keep running"), qApp, [](bool triggered){ QApplication::setQuitOnLastWindowClosed(!triggered); }); runAction->setCheckable(true); auto startAction = menu->addAction(QIcon::fromTheme(QStringLiteral("system-run")), tr("Autostart"), this, &MainWindow::updateAutostart); startAction->setCheckable(true); menu->addAction(QIcon::fromTheme(QStringLiteral("gtk-quit")), tr("Quit"), qApp, &QApplication::quit); trayIco->setContextMenu(menu); trayIco->setVisible(true); QSettings settings; settings.beginGroup(QStringLiteral("gui")); restoreGeometry(settings.value(QStringLiteral("geom")).toByteArray()); restoreState(settings.value(QStringLiteral("state")).toByteArray()); ui->treeView->header()->restoreState(settings.value(QStringLiteral("header")).toByteArray()); runAction->setChecked(settings.value(QStringLiteral("background"), true).toBool()); startAction->setChecked(isAutostart()); QApplication::setQuitOnLastWindowClosed(!runAction->isChecked()); settings.endGroup(); connect(ui->actionExit, &QAction::triggered, qApp, &QApplication::quit); connect(ui->actionAbout_Qt, &QAction::triggered, qApp, &QApplication::aboutQt); connect(ui->action_Reload_Mounts, &QAction::triggered, model, &MountModel::reload); connect(model, &MountModel::modelReset, this, [this](){ reloadCurrent(QModelIndex()); }); connect(ui->treeView->selectionModel(), &QItemSelectionModel::currentChanged, this, &MainWindow::reloadCurrent); connect(model->controller(), &MountController::mountError, this, &MainWindow::mountError); connect(qApp, &QApplication::commitDataRequest, this, &MainWindow::commitShutdown); connect(qApp, &QApplication::saveStateRequest, this, &MainWindow::commitShutdown); } MainWindow::~MainWindow() { QSettings settings; settings.beginGroup(QStringLiteral("gui")); settings.setValue(QStringLiteral("geom"), saveGeometry()); settings.setValue(QStringLiteral("state"), saveState()); settings.setValue(QStringLiteral("header"), ui->treeView->header()->saveState()); settings.setValue(QStringLiteral("background"), !QApplication::quitOnLastWindowClosed()); settings.endGroup(); delete ui; } void MainWindow::mountError(const QString &name, const QString &errorLog, int exitCode) { reloadCurrent(ui->treeView->currentIndex()); auto conf = DialogMaster::createCritical(tr("Failed to mount/unmount %1").arg(name)); conf.parent = isVisible() ? this : nullptr; conf.title = conf.text; if(exitCode == -1){ conf.text = tr("The mount or unmount operation failed! Check the details for the " "generated error log"); } else { conf.text = tr("The mount or unmount operation failed with exit code %1! Check the details for the " "generated error log") .arg(exitCode); } conf.details = errorLog; DialogMaster::messageBox(conf); } void MainWindow::reloadCurrent(const QModelIndex &uiIndex) { auto index = sortModel->mapToSource(uiIndex); ui->actionMount->setEnabled(index.isValid()); if(index.isValid()) { auto mounted = model->isMounted(index); ui->actionEdit_Host->setEnabled(!mounted); ui->actionRemove_Host->setEnabled(!mounted); ui->actionMount->setChecked(mounted); } else { ui->actionEdit_Host->setEnabled(false); ui->actionRemove_Host->setEnabled(false); ui->actionMount->setChecked(false); } } void MainWindow::updateAutostart(bool checked) { auto resPath = QStringLiteral("%1/autostart/%2.sh") .arg(QStandardPaths::writableLocation(QStandardPaths::ConfigLocation)) .arg(QCoreApplication::applicationName()); if(checked) { QFile file(resPath); if(file.open(QIODevice::WriteOnly | QIODevice::Text)) { file.write(QStringLiteral("#!/bin/sh\n%1 --hidden") .arg(QCoreApplication::applicationName()) .toUtf8()); file.close(); file.setPermissions(file.permissions() | QFileDevice::ExeUser); } } else QFile::remove(resPath); } void MainWindow::commitShutdown(QSessionManager &sm) { auto args = sm.restartCommand(); if(!isVisible()) { if(!args.contains(QStringLiteral("--hidden"))) args.append(QStringLiteral("--hidden")); } else args.removeAll(QStringLiteral("--hidden")); sm.setRestartCommand(args); sm.setRestartHint(QSessionManager::RestartIfRunning); } void MainWindow::on_actionAdd_Host_triggered() { auto info = EditRemoteDialog::editInfo({}, this); if(info.isValid()) model->addMountInfo(info); } void MainWindow::on_actionEdit_Host_triggered() { auto index = sortModel->mapToSource(ui->treeView->currentIndex()); if(index.isValid()) { auto info = EditRemoteDialog::editInfo(model->mountInfo(index), this); if(info.isValid()) model->updateMountInfo(index, info); } } void MainWindow::on_actionRemove_Host_triggered() { auto index = sortModel->mapToSource(ui->treeView->currentIndex()); if(index.isValid()) { if(DialogMaster::question(this, tr("Do you really want to remove the selected mount?"))) model->removeMountInfo(index); } } void MainWindow::on_actionMount_triggered(bool checked) { auto index = sortModel->mapToSource(ui->treeView->currentIndex()); if(index.isValid()) { if(checked) model->mount(index); else model->unmount(index); } } void MainWindow::on_actionOpen_Folder_triggered() { auto index = sortModel->mapToSource(ui->treeView->currentIndex()); if(index.isValid()) { auto info = model->mountInfo(index); QDesktopServices::openUrl(QUrl::fromLocalFile(info.localPath)); } } void MainWindow::on_actionAbout_triggered() { DialogMaster::about(this, tr("A gui wrapper around sshfs"), true, QUrl(QStringLiteral("https://github.com/Skycoder42"))); } bool MainWindow::isAutostart() { auto resPath = QStringLiteral("%1/autostart/%2.sh") .arg(QStandardPaths::writableLocation(QStandardPaths::ConfigLocation)) .arg(QCoreApplication::applicationName()); return QFile::exists(resPath); } void MainWindow::on_treeView_activated(const QModelIndex &index) { auto srcIndex = sortModel->mapToSource(index); if(srcIndex.isValid()) { if(!model->isMounted(srcIndex)) model->mount(srcIndex); else { auto info = model->mountInfo(srcIndex); QDesktopServices::openUrl(QUrl::fromLocalFile(info.localPath)); } } }
7,410
2,658
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2008, Willow Garage, Inc. * 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 Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. ********************************************************************/ #include "rosbag/stream.h" #include "rosbag/chunked_file.h" //#include <ros/ros.h> using boost::shared_ptr; namespace rosbag { // StreamFactory StreamFactory::StreamFactory(ChunkedFile* file) : uncompressed_stream_(new UncompressedStream(file)), bz2_stream_ (new BZ2Stream(file)), lz4_stream_ (new LZ4Stream(file)) { } shared_ptr<Stream> StreamFactory::getStream(CompressionType type) const { switch (type) { case compression::Uncompressed: return uncompressed_stream_; case compression::BZ2: return bz2_stream_; case compression::LZ4: return lz4_stream_; default: return shared_ptr<Stream>(); } } // Stream Stream::Stream(ChunkedFile* file) : file_(file) { } Stream::~Stream() { } void Stream::startWrite() { } void Stream::stopWrite() { } void Stream::startRead() { } void Stream::stopRead() { } FILE* Stream::getFilePointer() { return file_->file_; } uint64_t Stream::getCompressedIn() { return file_->compressed_in_; } void Stream::setCompressedIn(uint64_t nbytes) { file_->compressed_in_ = nbytes; } void Stream::advanceOffset(uint64_t nbytes) { file_->offset_ += nbytes; } char* Stream::getUnused() { return file_->unused_; } int Stream::getUnusedLength() { return file_->nUnused_; } void Stream::setUnused(char* unused) { file_->unused_ = unused; } void Stream::setUnusedLength(int nUnused) { file_->nUnused_ = nUnused; } void Stream::clearUnused() { file_->clearUnused(); } } // namespace rosbag
3,491
1,129
#include <iostream> #include "array.h" using namespace std; int SetName(char list[][10], char names[]){ int lastIndex = Count(list); int lastChar = Count(names); for (int i = 0; i < lastChar; i++){ list[lastIndex][i] = names[i]; } return 0; } int ShowName(char names[][10], int index){ int count = Count(names[index]); for (int i = 0; i < count; i++){ cout << names[index][i]; } return 0; } int SetValue(int scores[][2], int score){ int count = Count(scores); scores[count][0] = score; scores[count][1] = count; return 0; } int Swap(int scores[][2], int pos0, int pos1){ int temp = scores[pos0][0]; scores[pos0][0] = scores[pos1][0]; scores[pos1][0] = temp; temp = scores[pos0][1]; scores[pos0][1] = scores[pos1][1]; scores[pos1][1] = temp; return 0; } int BubbleSort(int scores[][2]){ int count = Count(scores); bool hasSwapped; for (int i = 0; i < count; i++){ hasSwapped = false; for (int j = 1; j < count; j++){ if (scores[j - 1][0] < scores[j][0]) { Swap(scores, j - 1, j); hasSwapped = true; } } if (!hasSwapped) break; } return 0; } int ShowLeaderboard(int scores[][2], char names[][10], int numOfParticipants){ int tempScore = 0; int rank = 0; int tempRank = rank; for (int i = 0; i < numOfParticipants; i++) { rank++; if (tempScore == scores[i][0]) { cout << tempRank << "\t"; ShowName(names, scores[i][1]); }else { cout << rank << "\t" ; ShowName(names, scores[i][1]); tempRank = rank; } tempScore = scores[i][0]; cout << "\t" << scores[i][0] << endl; } return 0; } int main(){ int numOfPeople = 5; int scores[numOfPeople][2]; char names[numOfPeople][10]; names[0][0] = '0';//when init a char[], it sets char[0][1] to 'p', bypassing my check //Input int tempScore = 0; char tempName[10]; cout << "Please input amountOfPeople: "; cin >> numOfPeople; for (int i = 0; i < numOfPeople; i++){ cout << "Please input score between 1->100: "; cin >> tempScore; if (0 < tempScore && tempScore <= 100){ cout << "Please set name: "; cin >> tempName; SetValue(scores, tempScore); SetName(names, tempName); cout << "Name added!" << endl; }else { cout << "Score not within range. Please try again." << endl; i--; } } /* //Set scores (score cannot be 0) SetValue(scores, 87); SetValue(scores, 98); SetValue(scores, 50); SetValue(scores, 98); SetValue(scores, 75); //Set names SetName(names, "happy"); // cout << Count(names) << endl; SetName(names, "box"); // cout << Count(names) << endl; SetName(names, "card"); // cout << Count(names) << endl; // ShowName(names, 0); // ShowName(names, 2); // ShowName(names, 0); SetName(names, "eli"); SetName(names, "pox"); */ BubbleSort(scores); cout << "Rank\tName\tScore" << endl; ShowLeaderboard(scores, names, numOfPeople); return 0; }
3,295
1,196
#include "CrossPlatformGUI.h" bool CrossPlatformGUI::performGUIPass() { ImGui::NewFrame(); static bool isConnected = false; bool open = true; ImGui::SetNextWindowPos({ 0,0 }); { //TODO: Figure out how to get rid of the Windows window, make everything transparent, and just use ImGui for everything. //TODO: ImGuiWindowFlags_AlwaysAutoResize causes some flickering. Figure out how to stop it ImGui::Begin("Sony Headphones", &open, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar); //Legal disclaimer ImGui::Text("! This product is not affiliated with Sony. Use at your own risk. !"); ImGui::Text("Source: https://github.com/Plutoberth/SonyHeadphonesClient"); ImGui::Spacing(); this->_drawErrors(); this->_drawDeviceDiscovery(); if (this->_bt.isConnected()) { ImGui::Spacing(); this->_drawASMControls(); } } ImGui::End(); ImGui::Render(); return open; } void CrossPlatformGUI::_drawErrors() { //There's a slight race condition here but I don't care, it'd only be for one frame. if (this->_mq.begin() != this->_mq.end()) { ImGui::Text("Errors"); ImGui::Text("----------------------------"); for (auto&& message : this->_mq) { ImGui::Text(message.message.c_str()); } //TODO: add a better ending separator ImGui::Text("----------------------------"); } } void CrossPlatformGUI::_drawDeviceDiscovery() { if (ImGui::CollapsingHeader("Device Discovery ", ImGuiTreeNodeFlags_DefaultOpen)) { static std::vector<BluetoothDevice> connectedDevices; static int selectedDevice = -1; if (this->_bt.isConnected()) { ImGui::Text("Connected to %s", this->_connectedDevice.name.c_str()); if (ImGui::Button("Disconnect")) { selectedDevice = -1; this->_bt.disconnect(); } } else { ImGui::Text("Select from one of the available devices: "); int temp = 0; for (auto device : connectedDevices) { ImGui::RadioButton(device.name.c_str(), &selectedDevice, temp++); } ImGui::Spacing(); if (this->_connectFuture.valid()) { if (this->_connectFuture.ready()) { try { this->_connectFuture.get(); } catch (const RecoverableException& exc) { if (exc.shouldDisconnect) { this->_bt.disconnect(); } this->_mq.addMessage(exc.what()); } } else { ImGui::Text("Connecting %c", "|/-\\"[(int)(ImGui::GetTime() / 0.05f) & 3]); } } else { if (ImGui::Button("Connect")) { if (selectedDevice != -1) { this->_connectedDevice = connectedDevices[selectedDevice]; this->_connectFuture.setFromAsync([this]() { this->_bt.connect(this->_connectedDevice.mac); }); } } } ImGui::SameLine(); if (this->_connectedDevicesFuture.valid()) { if (this->_connectedDevicesFuture.ready()) { try { connectedDevices = this->_connectedDevicesFuture.get(); } catch (const RecoverableException& exc) { if (exc.shouldDisconnect) { this->_bt.disconnect(); } this->_mq.addMessage(exc.what()); } } else { ImGui::Text("Discovering Devices %c", "|/-\\"[(int)(ImGui::GetTime() / 0.05f) & 3]); } } else { if (ImGui::Button("Refresh devices")) { selectedDevice = -1; this->_connectedDevicesFuture.setFromAsync([this]() { return this->_bt.getConnectedDevices(); }); } } } } } void CrossPlatformGUI::_drawASMControls() { static bool focusOnVoice = false; static bool sentFocusOnVoice = focusOnVoice; static int asmLevel = 0; static int sentAsmLevel = asmLevel; //Don't show if the command only takes a few frames to send static int commandLinger = 0; if (ImGui::CollapsingHeader("Ambient Sound Mode ", ImGuiTreeNodeFlags_DefaultOpen)) { ImGui::Text("Control ambient sound for your %ss", this->_connectedDevice.name.c_str()); ImGui::SliderInt("Ambient Sound Level", &asmLevel, 0, 19); bool sliderActive = ImGui::IsItemActive(); if (asmLevel >= MINIMUM_VOICE_FOCUS_STEP) { ImGui::Checkbox("Focus on Voice", &focusOnVoice); } else { ImGui::Text("Focus on Voice isn't enabled on this level."); } if (this->_sendCommandFuture.ready()) { commandLinger = 0; try { this->_sendCommandFuture.get(); } catch (const RecoverableException& exc) { std::string excString; //We kinda have to do it here and not in the wrapper, due to async causing timing issues. To fix it, the messagequeue can be made //static, but I'm not sure if I wanna do that. if (exc.shouldDisconnect) { this->_bt.disconnect(); excString = "Disconnected due to: "; } this->_mq.addMessage(excString + exc.what()); } } //This means that we're waiting else if (this->_sendCommandFuture.valid()) { if (commandLinger++ > FPS / 10) { ImGui::Text("Sending command %c", "|/-\\"[(int)(ImGui::GetTime() / 0.05f) & 3]); } } //We're not waiting, and there's no command in the air, so we can evaluate sending a new command else if (sentAsmLevel != asmLevel || sentFocusOnVoice != focusOnVoice) { auto ncAsmEffect = sliderActive ? NC_ASM_EFFECT::ADJUSTMENT_IN_PROGRESS : NC_ASM_EFFECT::ADJUSTMENT_COMPLETION; auto asmId = focusOnVoice ? ASM_ID::VOICE : ASM_ID::NORMAL; this->_sendCommandFuture.setFromAsync([=]() { return this->_bt.sendCommand(CommandSerializer::serializeNcAndAsmSetting( ncAsmEffect, NC_ASM_SETTING_TYPE::LEVEL_ADJUSTMENT, ASM_SETTING_TYPE::LEVEL_ADJUSTMENT, asmId, asmLevel )); }); sentAsmLevel = asmLevel; sentFocusOnVoice = focusOnVoice; } } } CrossPlatformGUI::CrossPlatformGUI(BluetoothWrapper bt) : _bt(std::move(bt)) { // Setup Dear ImGui style ImGui::StyleColorsDark(); ImGuiIO& io = ImGui::GetIO(); this->_mq = TimedMessageQueue(GUI_MAX_MESSAGES); this->_connectedDevicesFuture.setFromAsync([this]() { return this->_bt.getConnectedDevices(); }); io.IniFilename = nullptr; io.WantSaveIniSettings = false; //AddFontFromMemory will own the pointer, so there's no leak char* fileData = new char[sizeof(CascadiaCodeTTF)]; memcpy(fileData, CascadiaCodeTTF, sizeof(CascadiaCodeTTF)); ImFont* font = io.Fonts->AddFontFromMemoryTTF(reinterpret_cast<void*>(fileData), sizeof(CascadiaCodeTTF), 15.0f); IM_ASSERT(font != NULL); }
6,361
2,683
#ifndef MATRIX_HPP #define MATRIX_HPP #include "fraction.hpp" #include <cassert> #include <iostream> using namespace std; struct Matrix{ int row_size, col_size; Fraction **rows; // Constructors Matrix(int n); Matrix(int m, int n); // Copy Constructor Matrix(const Matrix &M); // Destructor ~Matrix(); // Operater Overloading Fraction*& operator [] (const int &i); Fraction* operator [] (const int &i) const; // access-only Matrix operator - () const; // unary minus Matrix operator + (const Matrix &M); Matrix operator - (const Matrix &M); Matrix operator * (const Matrix &M); Matrix operator * (const int &x); // scalar multiplication Matrix& operator = (const Matrix &M); // Tranpose Matrix transpose(void) const; }; ostream& operator << (ostream &os, const Matrix &M); #endif
818
287
///////////////////////////////////////////////////////////////////////////////// // // Thor C++ Library // Copyright (c) 2011-2014 Jan Haller // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // ///////////////////////////////////////////////////////////////////////////////// #include <Thor/Particles/Particle.hpp> namespace thor { Particle::Particle(sf::Time totalLifetime) : position() , velocity() , rotation() , rotationSpeed() , scale(1.f, 1.f) , color(255, 255, 255) , textureIndex(0) , totalLifetime(totalLifetime) , passedLifetime(sf::Time::Zero) { } sf::Time getElapsedLifetime(const Particle& particle) { return particle.passedLifetime; } sf::Time getTotalLifetime(const Particle& particle) { return particle.totalLifetime; } sf::Time getRemainingLifetime(const Particle& particle) { return getTotalLifetime(particle) - getElapsedLifetime(particle); } float getElapsedRatio(const Particle& particle) { return getElapsedLifetime(particle) / getTotalLifetime(particle); } float getRemainingRatio(const Particle& particle) { return getRemainingLifetime(particle) / getTotalLifetime(particle); } } // namespace thor
2,034
614
/** * @file unit_test_fnd_memory_addressof.cpp * * @brief addressof のテスト * * @author myoukaku */ #include <bksge/fnd/memory/addressof.hpp> #include <bksge/fnd/config.hpp> #include <gtest/gtest.h> #include "constexpr_test.hpp" namespace bksge_memory_test { namespace addressof_test { struct UselessType {}; // operator&がオーバーロードされていないクラス struct A { }; // operator&がオーバーロードされているクラス struct B { BKSGE_CONSTEXPR UselessType operator&(void) const { return UselessType(); } }; // operator&がグローバル関数としてオーバーロードされているクラス struct C { }; BKSGE_CONSTEXPR UselessType operator&(C const&) { return UselessType(); } BKSGE_CONSTEXPR int func(UselessType) { return 0; } BKSGE_CONSTEXPR int func(A const*) { return 1; } BKSGE_CONSTEXPR int func(B const*) { return 2; } BKSGE_CONSTEXPR int func(C const*) { return 3; } GTEST_TEST(MemoryTest, AddressofTest) { { BKSGE_CONSTEXPR int n1 = 0; BKSGE_CONSTEXPR const int n2 = 0; volatile int n3 = 0; const volatile int n4 = 0; BKSGE_CONSTEXPR_EXPECT_TRUE(&n1 == bksge::addressof(n1)); BKSGE_CONSTEXPR_EXPECT_TRUE(&n2 == bksge::addressof(n2)); EXPECT_TRUE(&n3 == bksge::addressof(n3)); EXPECT_TRUE(&n4 == bksge::addressof(n4)); } { BKSGE_CONSTEXPR A a {}; BKSGE_CONSTEXPR_EXPECT_EQ(1, func(&a)); BKSGE_CONSTEXPR_EXPECT_EQ(1, func(bksge::addressof(a))); } { BKSGE_CONSTEXPR B b {}; BKSGE_CXX17_CONSTEXPR_EXPECT_EQ(0, func(&b)); #if defined(BKSGE_APPLE_CLANG) EXPECT_EQ(2, func(bksge::addressof(b))); #else BKSGE_CXX17_CONSTEXPR_EXPECT_EQ(2, func(bksge::addressof(b))); #endif } { BKSGE_CONSTEXPR C c {}; BKSGE_CXX17_CONSTEXPR_EXPECT_EQ(0, func(&c)); #if defined(BKSGE_APPLE_CLANG) EXPECT_EQ(3, func(bksge::addressof(c))); #else BKSGE_CXX17_CONSTEXPR_EXPECT_EQ(3, func(bksge::addressof(c))); #endif } } } // namespace addressof_test } // namespace bksge_memory_test
2,104
1,024
#include <iostream> #include "../common/common.h" int main() { auto inputs = read_inputs(); auto values = split(inputs, "\n"); // Part 1 auto depth = 0; auto horizontal = 0; for (size_t i = 0; i < values.size(); i++) { auto input = values[i]; auto instructions = split(input, " "); if (instructions[0] == "forward") horizontal += stoi(instructions[1]); else if (instructions[0] == "down") depth += stoi(instructions[1]); else if (instructions[0] == "up") depth -= stoi(instructions[1]); } std::cout << "Part 1: " << horizontal * depth << std::endl; // Part 2 depth = 0; horizontal = 0; auto aim = 0; for (size_t i = 0; i < values.size(); i++) { auto input = values[i]; auto instructions = split(input, " "); if (instructions[0] == "forward") { horizontal += stoi(instructions[1]); depth += aim * stoi(instructions[1]); } else if (instructions[0] == "down") aim += stoi(instructions[1]); else if (instructions[0] == "up") aim -= stoi(instructions[1]); } std::cout << "Part 2: " << horizontal * depth << std::endl; }
1,241
413
/* Copyright 2020 Victor Santos Reis 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 "../pch.h" #include "CarenD2D1DCRenderTarget.h" //Destruidor. CarenD2D1DCRenderTarget::~CarenD2D1DCRenderTarget() { //Define que a classe foi descartada Prop_DisposedClasse = true; } //Construtor. CarenD2D1DCRenderTarget::CarenD2D1DCRenderTarget() { //INICIALIZA SEM NENHUM PONTEIRO VINCULADO. } // Métodos da interface ICaren /// <summary> /// (QueryInterface) - Consulta o objeto COM atual para um ponteiro para uma de suas interfaces; identificando a interface por uma /// referência ao identificador de interface (IID). Se o objeto COM implementar a interface, o método retorna um ponteiro para essa /// interface depois de adicionar uma nova referência(AddRef). /// </summary> /// <param name="Param_Guid">O IID(Identificador de Interface) ou GUID para a interface desejada.</param> /// <param name="Param_InterfaceSolicitada">A interface que vai receber o ponteiro nativo. O usuário deve inicializar a interface antes de chamar o método. Libere a interface quando não for mais usá-la.</param> CarenResult CarenD2D1DCRenderTarget::ConsultarInterface(String^ Param_Guid, ICaren^ Param_InterfaceSolicitada) { //Variavel que vai retornar o resultado. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM HRESULT Hr = E_FAIL; //Variaveis a serem utilizadas GUID GuidInterface = GUID_NULL; wchar_t* DadosGuid = NULL; LPVOID* pInterfaceSolcitada = NULL; //Setor onde será criado o GUID para realizar a operação. { //Context Marshal. marshal_context ctx; //Lagrura da string int LarguraString = 0; //Variavel que vai conter os dados da String para o tipo não gerenciado. const char* DadosConvertidos = NULL; //Verifica se a string é valida. if (!String::IsNullOrEmpty(Param_Guid)) { //Obtém a largura da String. LarguraString = Param_Guid->Length + 1; //Converte os dados para um buffer de char. //O Proprio marshal_context destroi o buffer. DadosConvertidos = ctx.marshal_as<const char*>(Param_Guid); //Aloca memoria para o Dados do Guid. DadosGuid = new wchar_t[LarguraString]; //Copia os dados para o OLECHAR. mbstowcs_s(NULL, DadosGuid, LarguraString, DadosConvertidos, LarguraString - 1); //Chama o método que vai criar o CLSID adequado a aparti do guid Hr = CLSIDFromString(DadosGuid, (LPCLSID)&GuidInterface); } else { //Falhou ao criar o GUID Resultado.AdicionarCodigo(ResultCode::ER_GUID_INVALIDO, false); //A string não é valida goto Done; } } //Verifica se o guid foi criado com sucesso. if (GuidInterface == GUID_NULL) { //Falhou ao criar o GUID Resultado.AdicionarCodigo(ResultCode::ER_GUID_INVALIDO, false); //Sai do método goto Done; } //Chama o método para realizara operação Hr = PonteiroTrabalho->QueryInterface(GuidInterface, (LPVOID*)&pInterfaceSolcitada); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Define o ponteiro na interface solicitada. //A interface deve ter sido incializada pelo usuário. Resultado = Param_InterfaceSolicitada->AdicionarPonteiro(pInterfaceSolcitada); //Verifica o resultado da operação. if (Resultado.StatusCode != ResultCode::SS_OK) { //Libera a referência obtida a parti do QueryInterface. ((IUnknown*)pInterfaceSolcitada)->Release(); pInterfaceSolcitada = NULL; } Done:; //Verifica se o OLECHAR é valido e destroi if (ObjetoValido(DadosGuid)) { //Libera os dados. delete[] DadosGuid; } //Retorna o resultado return Resultado; } /// <summary> /// Método responsável por adicionar um novo ponteiro nativo a classe atual. /// Este método não é responsável por adicionar uma nova referência ao objeto COM. /// </summary> /// <param name="Param_PonteiroNativo">Variável (GERENCIADA) para o ponteiro nativo a ser adicionado.</param> CarenResult CarenD2D1DCRenderTarget::AdicionarPonteiro(IntPtr Param_PonteiroNativo) { //Variavel que vai retornar o resultado. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Verifica se o objeto é valido if (Param_PonteiroNativo == IntPtr::Zero) { //O objeto não é valido Resultado.AdicionarCodigo(ResultCode::ER_E_POINTER, false); //Sai do método. goto Done; } //Converte o ponteiro para o tipo especifico da classe. PonteiroTrabalho = reinterpret_cast<ID2D1DCRenderTarget*>(Param_PonteiroNativo.ToPointer()); //Verifica o ponteiro if (ObjetoValido(PonteiroTrabalho)) { //Define que o ponteiro foi definido com sucesso. Resultado.AdicionarCodigo(ResultCode::SS_OK, true); } else { //Define falha na operação Resultado.AdicionarCodigo(ResultCode::ER_E_POINTER, false); } Done:; //Retornao resultado return Resultado; } /// <summary> /// Método responsável por adicionar um novo ponteiro nativo a classe atual. /// Este método não é responsável por adicionar uma nova referência ao objeto COM. /// </summary> /// <param name="Param_PonteiroNativo">Variável (NATIVA) para o ponteiro nativo a ser adicionado.</param> CarenResult CarenD2D1DCRenderTarget::AdicionarPonteiro(LPVOID Param_PonteiroNativo) { //Variavel que vai retornar o resultado. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Verifica se o objeto é valido if (!ObjetoValido(Param_PonteiroNativo)) { //O objeto não é valido Resultado.AdicionarCodigo(ResultCode::ER_E_POINTER, false); //Sai do método goto Done; } //Converte o ponteiro para o tipo especifico da classe. PonteiroTrabalho = reinterpret_cast<ID2D1DCRenderTarget*>(Param_PonteiroNativo); //Verifica se o ponteiro é valido if (ObjetoValido(PonteiroTrabalho)) { //Ponteiro convertido com sucesso! //Define sucesso na operação Resultado.AdicionarCodigo(ResultCode::SS_OK, true); } else { //Falhou ao converter o ponteiro vazio para sua real representação. //Define falha no ponteiro Resultado.AdicionarCodigo(ResultCode::ER_E_POINTER, false); } Done:; //Retornao resultado return Resultado; } /// <summary> /// Método responsável por recuperar o ponteiro atual da classe. Se o ponteiro não for valido, o método retornar ResultCode::ER_PONTEIRO. /// Este método não é responsável por adicionar uma nova referência ao objeto COM. /// </summary> /// <param name="Param_Out_PonteiroNativo">Variável (GERENCIADA) que vai receber o ponteiro nativo.</param> CarenResult CarenD2D1DCRenderTarget::RecuperarPonteiro([Out] IntPtr% Param_Out_PonteiroNativo) { //Variavel que vai retornar o resultado. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Verifica se o ponteiro é valido if (!ObjetoValido(PonteiroTrabalho)) { //O ponteiro de trabalho é invalido. Resultado.AdicionarCodigo(ResultCode::ER_E_POINTER, false); //Sai do método goto Done; } //Cria e define o ponteiro gerenciado no parametro de saida. Param_Out_PonteiroNativo = IntPtr((LPVOID)PonteiroTrabalho); //Define o resultado Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Retorna o resultado return Resultado; } /// <summary> /// Método responsável por recuperar o ponteiro atual da classe. Se o ponteiro não for valido, o método retornar ResultCode::ER_PONTEIRO. /// Este método não é responsável por adicionar uma nova referência ao objeto COM. /// </summary> /// <param name="Param_Out_PonteiroNativo">Variável (NATIVA) que vai receber o ponteiro nativo.</param> CarenResult CarenD2D1DCRenderTarget::RecuperarPonteiro(LPVOID* Param_Out_PonteiroNativo) { //Variavel que vai retornar o resultado. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Verifica se o ponteiro é valido if (!ObjetoValido(PonteiroTrabalho)) { //O ponteiro de trabalho é invalido. Resultado.AdicionarCodigo(ResultCode::ER_E_POINTER, false); //Sai do método goto Done; } //Define o ponteiro de trabalho no parametro de saida. *Param_Out_PonteiroNativo = PonteiroTrabalho; //Define o resultado Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Retorna o resultado return Resultado; } /// <summary> /// Método responsável por retornar a quantidade de referências do objeto COM atual. /// </summary> /// <param name="Param_Out_Referencias">Variável que vai receber a quantidade de referências do objeto.</param> CarenResult CarenD2D1DCRenderTarget::RecuperarReferencias([Out] UInt64% Param_Out_Referencias) { //Variavel que vai retornar o resultado. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Verifica se o ponteiro é valido if (!ObjetoValido(PonteiroTrabalho)) { //O ponteiro de trabalho é invalido. Resultado.AdicionarCodigo(ResultCode::ER_E_POINTER, false); //Sai do método goto Done; } //Adiciona uma referência ao ponteiro ULONG CountRefs = PonteiroTrabalho->AddRef(); //Libera a referência adicional PonteiroTrabalho->Release(); //Decrementa o valor da quantidade de referência retornada em (-1) e define no parametro de saida. Param_Out_Referencias = static_cast<UInt64>(CountRefs - 1); //Define o resultado Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Retorna o resultado return Resultado; } /// <summary> /// Método responsável por indicar se o ponteiro COM atual é válido. /// </summary> CarenResult CarenD2D1DCRenderTarget::StatusPonteiro() { return (ObjetoValido(PonteiroTrabalho) ? CarenResult(ResultCode::SS_OK, true) : CarenResult(ResultCode::ER_E_POINTER, false)); } /// <summary> /// Método responsável por retornar a variável que armazena o último código de erro desconhecido ou não documentado gerado pela classe. /// Esse método não chama o método nativo (GetLastError), apenas retorna o código de erro que foi armazenado na classe. /// </summary> Int32 CarenD2D1DCRenderTarget::ObterCodigoErro() { return Var_Glob_LAST_HRESULT; } /// <summary> /// (AddRef) - Incrementa a contagem de referência para o ponteiro do objeto COM atual. Você deve chamar este método sempre que /// você fazer uma cópia de um ponteiro de interface. /// </summary> void CarenD2D1DCRenderTarget::AdicionarReferencia() { //Adiciona uma referência ao ponteiro PonteiroTrabalho->AddRef(); } /// <summary> /// (Release) - 'Decrementa' a contagem de referência do objeto COM atual. /// </summary> void CarenD2D1DCRenderTarget::LiberarReferencia() { //Libera a referência e obtém a quantidade atual. ULONG RefCount = PonteiroTrabalho->Release(); //Verifica se a quantidade é zero e se o ponteiro ainda é valido. //Se sim, vai deletar o ponteiro. if (RefCount == 0 && ObjetoValido(PonteiroTrabalho)) { //NULA o ponteiro vazio. PonteiroTrabalho = NULL; } } /// <summary> /// Método responsável por chamar o finalizador da interface para realizar a limpeza e descarte de dados pendentes. /// Este método pode ser escrito de forma diferente para cada interface. /// </summary> void CarenD2D1DCRenderTarget::Finalizar() { ////////////////////// //Código de descarte// ////////////////////// //Informa ao GC que a classe já foi limpa e pode ser descartada. GC::SuppressFinalize(this); //Nula o ponteiro de trabalho da classe. PonteiroTrabalho = Nulo; //Chama o finalizador da classe this->~CarenD2D1DCRenderTarget(); } // Métodos da interface proprietária(ICarenD2D1DCRenderTarget) /// <summary> /// Vincula o alvo de renderização ao contexto do dispositivo ao qual ele emite comandos de desenho. /// Antes de renderizar com o alvo de renderização DC, você deve usar seu método BindDC para associá-lo a um GDI DC. Você faz isso cada vez que usa um DC diferente, ou o tamanho da área /// que deseja desenhar para mudanças. /// </summary> /// <param name="Param_Hdc">O contexto do dispositivo para o qual o alvo de renderização emite comandos de desenho.</param> /// <param name="Param_SubRect">As dimensões da Handle(Param_Hdc) para um contexto de dispositivo (HDC) a que o alvo de renderização está vinculado.</param> CarenResult CarenD2D1DCRenderTarget::BindDC( IntPtr Param_Hdc, CA_RECT^ Param_SubRect) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; RECT* pRect = NULL; HDC pHdc = NULL; //Converte a estrutura. pRect = Util.ConverterRECTManagedToUnmanaged(Param_SubRect); //Obtém o HDC(IntPtr) pHdc = Util.ConverterIntPtrTo<HDC>(Param_Hdc); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->BindDC(pHdc, pRect); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pRect); //Retorna o resultado. return Resultado; } // Métodos da interface proprietária(ICarenD2D1RenderTarget) /// <summary> /// Inicia o desenho deste alvo de renderização. /// </summary> void CarenD2D1DCRenderTarget::BeginDraw() { //Chama o método para realizar a operação. PonteiroTrabalho->BeginDraw(); } /// <summary> /// Limpa a área de desenho para a cor especificada. /// </summary> /// <param name="Param_ClearColor"></param> void CarenD2D1DCRenderTarget::Clear(CA_D2D1_COLOR_F^ Param_ClearColor) { //Variaveis a serem utilizadas. Utilidades Util; D2D1_COLOR_F* pColorF = NULL; //Converte a estrutura gerenciada para a nativa. pColorF = Util.ConverterD2D1_COLOR_FManagedToUnmanaged(Param_ClearColor); //Chama o método para realizar a operação. PonteiroTrabalho->Clear(pColorF); //Libera a memória para a estrutura. DeletarEstruturaSafe(&pColorF); } /// <summary> /// Cria um bitmap do Direct2D de um ponteiro para dados de origem na memória. /// </summary> /// <param name="Param_Size">As dimensões em pixels do bitmap a ser criado.</param> /// <param name="Param_DadosOrigem">Um ponteiro para a localização da memória dos dados da imagem ou NULO para criar um bitmap não inicializado.</param> /// <param name="Param_Pitch">A contagem de bytes de cada linha de varredura, que é igual a (a largura da imagem em pixels × o número de bytes por pixel) + preenchimento de memória. Se (Param_DadosOrigem) é NULO, este valor é ignorado. (Note que o tom também é às vezes chamado de pitch.)</param> /// <param name="Param_PropriedadesBitmap">O formato de pixel e pontos por polegada (DPI) do bitmap a ser criado.</param> /// <param name="Param_Out_Bitmap">Retorna a interface (ICarenD2D1Bitmap) que contém um ponteiro para o novo bitmap.</param> CarenResult CarenD2D1DCRenderTarget::CreateBitmap( CA_D2D1_SIZE_U^ Param_Size, ICarenBuffer^ Param_DadosOrigem, UInt32 Param_Pitch, CA_D2D1_BITMAP_PROPERTIES^ Param_PropriedadesBitmap, [Out] ICarenD2D1Bitmap^% Param_Out_Bitmap) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_SIZE_U* pSizeU = NULL; D2D1_BITMAP_PROPERTIES* pBitmapProps = NULL; IntPtr pBufferOrigem = IntPtr::Zero; ID2D1Bitmap* pOutBitmap = NULL; //Converte as estruturas gerenciadas para as nativas. pSizeU = Util.ConverterD2D1_SIZE_UManagedToUnmanaged(Param_Size); pBitmapProps = Util.ConverterD2D1_BITMAP_PROPERTIESManagedToUnmanaged(Param_PropriedadesBitmap); //Obtém o ponteiro para a memória de origem. Resultado = Param_DadosOrigem->GetInternalPointer(pBufferOrigem); //Verifica se não falhou. if (!CarenSucesso(Resultado)) { //Falhou ao recupera o ponteiro. //Sai do método Sair; } //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateBitmap(*pSizeU, pBufferOrigem.ToPointer(), Param_Pitch, pBitmapProps, &pOutBitmap); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface que será retornada Param_Out_Bitmap = gcnew CarenD2D1Bitmap(); //Define o ponteiro na interface de saida. Resultado = Param_Out_Bitmap->AdicionarPonteiro(pOutBitmap); //Verifica se houve erro. if (!CarenSucesso(Resultado)) { //Falhou ao definir o ponteiro. //Libera o ponteiro pOutBitmap->Release(); pOutBitmap = NULL; Param_Out_Bitmap->Finalizar(); Param_Out_Bitmap = nullptr; } Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pSizeU); DeletarEstruturaSafe(&pBitmapProps); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um bitmap do Direct2D não inicializado. /// </summary> /// <param name="Param_Size">As dimensões em pixels do bitmap a ser criado.</param> /// <param name="Param_PropriedadesBitmap">O formato de pixel e pontos por polegada (DPI) do bitmap a ser criado.</param> /// <param name="Param_Out_Bitmap">Retorna a interface (ICarenD2D1Bitmap) que contém um ponteiro para o novo bitmap.</param> CarenResult CarenD2D1DCRenderTarget::CreateBitmap( CA_D2D1_SIZE_U^ Param_Size, CA_D2D1_BITMAP_PROPERTIES^ Param_PropriedadesBitmap, [Out] ICarenD2D1Bitmap^% Param_Out_Bitmap) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_SIZE_U* pSizeU = NULL; D2D1_BITMAP_PROPERTIES* pBitmapProps = NULL; ID2D1Bitmap* pOutBitmap = NULL; //Converte as estruturas gerenciadas para as nativas. pSizeU = Util.ConverterD2D1_SIZE_UManagedToUnmanaged(Param_Size); pBitmapProps = Util.ConverterD2D1_BITMAP_PROPERTIESManagedToUnmanaged(Param_PropriedadesBitmap); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateBitmap(*pSizeU, *pBitmapProps, &pOutBitmap); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface que será retornada Param_Out_Bitmap = gcnew CarenD2D1Bitmap(); //Define o ponteiro na interface de saida. Resultado = Param_Out_Bitmap->AdicionarPonteiro(pOutBitmap); //Verifica se houve erro. if (!CarenSucesso(Resultado)) { //Falhou ao definir o ponteiro. //Libera o ponteiro pOutBitmap->Release(); pOutBitmap = NULL; Param_Out_Bitmap->Finalizar(); Param_Out_Bitmap = nullptr; } Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pSizeU); DeletarEstruturaSafe(&pBitmapProps); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um ICarenD2D1BitmapBrush a partir do bitmap especificado. /// </summary> /// <param name="Param_Bitmap">O conteúdo do bitmap do novo pincel(Brush).</param> /// <param name="Param_PropriedadesBitmapBrush">Os modos de extensão e o modo de interpolação do novo pincel, ou NULO. Se você definir este parâmetro como NULO,a escova padrão para o D2D1_EXTEND_MODE_CLAMP /// modos de extensão horizontal e vertical e o modo de interpolação D2D1_BITMAP_INTERPOLATION_MODE_LINEAR.</param> /// <param name="Param_PropriedadesBrush">Uma estrutura que contenha a opacidade e a transformação do novo pincel, ou NULO. Se você definir este parâmetro como NULO,o pincel define o membro da opacidade /// para 1.0F e o membro de transformação para a matriz de identidade.</param> /// <param name="Param_Out_BitmapBrush">Retorna a interface (ICarenD2D1BitmapBrush) que contém um ponteiro para o novo pincel(Brush).</param> CarenResult CarenD2D1DCRenderTarget::CreateBitmapBrush( ICarenD2D1Bitmap^ Param_Bitmap, CA_D2D1_BITMAP_BRUSH_PROPERTIES^ Param_PropriedadesBitmapBrush, CA_D2D1_BRUSH_PROPERTIES^ Param_PropriedadesBrush, [Out] ICarenD2D1BitmapBrush^% Param_Out_BitmapBrush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; ID2D1Bitmap* pBitmap = NULL; D2D1_BITMAP_BRUSH_PROPERTIES* pBitmapBrushProps = NULL; //Pode ser NULO. D2D1_BRUSH_PROPERTIES* pBrushProps = NULL; //Pode ser NULO. ID2D1BitmapBrush* pOutBrush = NULL; //Recupera o ponteiro para o bitmap. Resultado = Param_Bitmap->RecuperarPonteiro((LPVOID*)&pBitmap); //Verifica se não houve erro. if (!CarenSucesso(Resultado)) { //Falhou. O ponteiro é invalido. //Sai do método Sair; } //Converte as estruturas gerenciadas para a nativa se validas. pBitmapBrushProps = ObjetoGerenciadoValido(Param_PropriedadesBitmapBrush) ? Util.ConverterD2D1_BITMAP_BRUSH_PROPERTIESManagedToUnmanaged(Param_PropriedadesBitmapBrush) : NULL; pBrushProps = ObjetoGerenciadoValido(Param_PropriedadesBrush) ? Util.ConverterD2D1_BRUSH_PROPERTIESManagedToUnmanaged(Param_PropriedadesBrush) : NULL; //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateBitmapBrush(pBitmap, pBitmapBrushProps, pBrushProps, &pOutBrush); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a classe a ser retornada. Param_Out_BitmapBrush = gcnew CarenD2D1BitmapBrush(); //Define o ponteiro da interface. Resultado = Param_Out_BitmapBrush->AdicionarPonteiro(pOutBrush); //Verifica se não houve erro if (!CarenSucesso(Resultado)) { //Falhou ao definir o ponteiro. //Libera os dados. pOutBrush->Release(); pOutBrush = NULL; Param_Out_BitmapBrush->Finalizar(); Param_Out_BitmapBrush = nullptr; } Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pBitmapBrushProps); DeletarEstruturaSafe(&pBrushProps); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um ICarenD2D1BitmapBrush a partir do bitmap especificado. O pincel usa os valores padrão para seu modo de extensão, modo de interpolação, opacidade e transformação. /// </summary> /// <param name="Param_Bitmap">O conteúdo do bitmap do novo pincel.</param> /// <param name="Param_Out_BitmapBrush">Retorna a interface (ICarenD2D1BitmapBrush) que contém um ponteiro para o novo pincel(Brush).</param> CarenResult CarenD2D1DCRenderTarget::CreateBitmapBrush( ICarenD2D1Bitmap^ Param_Bitmap, [Out] ICarenD2D1BitmapBrush^% Param_Out_BitmapBrush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. ID2D1Bitmap* pBitmap = NULL; ID2D1BitmapBrush* pOutBrush = NULL; //Recupera o ponteiro para o bitmap. Resultado = Param_Bitmap->RecuperarPonteiro((LPVOID*)&pBitmap); //Verifica se não houve erro. if (!CarenSucesso(Resultado)) { //Falhou. O ponteiro é invalido. //Sai do método Sair; } //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateBitmapBrush(pBitmap, &pOutBrush); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a classe a ser retornada. Param_Out_BitmapBrush = gcnew CarenD2D1BitmapBrush(); //Define o ponteiro da interface. Resultado = Param_Out_BitmapBrush->AdicionarPonteiro(pOutBrush); //Verifica se não houve erro if (!CarenSucesso(Resultado)) { //Falhou ao definir o ponteiro. //Libera os dados. pOutBrush->Release(); pOutBrush = NULL; Param_Out_BitmapBrush->Finalizar(); Param_Out_BitmapBrush = nullptr; } Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Cria um ID2D1BitmapBrush a partir do bitmap especificado. O pincel usa os valores padrão para sua opacidade e transformação. /// O Brush bitmap criado por este método tem uma opacidade de 1.0f e a matriz de identidade como sua transformação. /// </summary> /// <param name="Param_Bitmap">O conteúdo do bitmap do novo pincel.</param> /// <param name="Param_PropriedadesBitmapBrush">Os modos de extensão e o modo de interpolação do novo pincel.</param> /// <param name="Param_Out_BitmapBrush">Retorna a interface (ICarenD2D1BitmapBrush) que contém um ponteiro para o novo pincel(Brush).</param> CarenResult CarenD2D1DCRenderTarget::CreateBitmapBrush( ICarenD2D1Bitmap^ Param_Bitmap, CA_D2D1_BITMAP_BRUSH_PROPERTIES^ Param_PropriedadesBitmapBrush, [Out] ICarenD2D1BitmapBrush^% Param_Out_BitmapBrush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; ID2D1Bitmap* pBitmap = NULL; ID2D1BitmapBrush* pOutBrush = NULL; D2D1_BITMAP_BRUSH_PROPERTIES* pBitmapBrushProps = NULL; //Recupera o ponteiro para o bitmap. Resultado = Param_Bitmap->RecuperarPonteiro((LPVOID*)&pBitmap); //Verifica se não houve erro. if (!CarenSucesso(Resultado)) { //Falhou. O ponteiro é invalido. //Sai do método Sair; } //Converte as estruturas gerenciadas para a nativa se validas. pBitmapBrushProps = Util.ConverterD2D1_BITMAP_BRUSH_PROPERTIESManagedToUnmanaged(Param_PropriedadesBitmapBrush); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateBitmapBrush(pBitmap, *pBitmapBrushProps, &pOutBrush); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a classe a ser retornada. Param_Out_BitmapBrush = gcnew CarenD2D1BitmapBrush(); //Define o ponteiro da interface. Resultado = Param_Out_BitmapBrush->AdicionarPonteiro(pOutBrush); //Verifica se não houve erro if (!CarenSucesso(Resultado)) { //Falhou ao definir o ponteiro. //Libera os dados. pOutBrush->Release(); pOutBrush = NULL; Param_Out_BitmapBrush->Finalizar(); Param_Out_BitmapBrush = nullptr; } Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pBitmapBrushProps); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um ICarenD2D1Bitmap copiando o bitmap especificado do Microsoft Windows Imaging Component (WIC). /// </summary> /// <param name="Param_WicBitmapSource">Uma interface ICarenWICBitmapSource que contém os dados a serem copiados.</param> /// <param name="Param_PropriedadesBitmap">O formato de pixel e DPI do bitmap para criar. O formato pixel deve corresponder ao formato de pixel do wicBitmapSource, ou o método falhará. Para evitar uma /// incompatibilidade, você pode passar NULO ou passar o valor obtido ligando para a função de ajudante D2D1::PixelFormat sem especificar nenhum valor de parâmetro. Se o dpiX e o dpiY forem 0,0f, o /// DPI padrão, 96, será usado. As informações de DPI incorporadas no (Param_WicBitmapSource) são ignoradas.</param> /// <param name="Param_Out_Bitmap">Retorna a interface ICarenD2D1Bitmap que contém um ponteiro para o novo bitmap.</param> CarenResult CarenD2D1DCRenderTarget::CreateBitmapFromWicBitmap( ICaren^ Param_WicBitmapSource, CA_D2D1_BITMAP_PROPERTIES^ Param_PropriedadesBitmap, [Out] ICarenD2D1Bitmap^% Param_Out_Bitmap) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; IWICBitmapSource* pWicBitmapSource = NULL; D2D1_BITMAP_PROPERTIES* pBitmapProps = NULL; //Pode ser NULO. ID2D1Bitmap* pOutBitmap = NULL; //Recupera o ponteiro para o bitmap. Resultado = Param_WicBitmapSource->RecuperarPonteiro((LPVOID*)&pWicBitmapSource); //Verifica se não houve erro. if (!CarenSucesso(Resultado)) { //Falhou. O ponteiro é invalido. //Sai do método Sair; } //Converte a estrutura gerenciada para a nativa se valida. pBitmapProps = ObjetoGerenciadoValido(Param_PropriedadesBitmap) ? Util.ConverterD2D1_BITMAP_PROPERTIESManagedToUnmanaged(Param_PropriedadesBitmap) : NULL; //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateBitmapFromWicBitmap(pWicBitmapSource, pBitmapProps, &pOutBitmap); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a classe a ser retornada. Param_Out_Bitmap = gcnew CarenD2D1Bitmap(); //Define o ponteiro da interface. Resultado = Param_Out_Bitmap->AdicionarPonteiro(pOutBitmap); //Verifica se não houve erro if (!CarenSucesso(Resultado)) { //Falhou ao definir o ponteiro. //Libera os dados. pOutBitmap->Release(); pOutBitmap = NULL; Param_Out_Bitmap->Finalizar(); Param_Out_Bitmap = nullptr; } Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pBitmapProps); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um ID2D1Bitmap copiando o bitmap especificado do Microsoft Windows Imaging Component (WIC). /// </summary> /// <param name="Param_WicBitmapSource">Uma interface ICarenWICBitmapSource que contém os dados a serem copiados.</param> /// <param name="Param_Out_Bitmap">Retorna a interface ICarenD2D1Bitmap que contém um ponteiro para o novo bitmap.</param> CarenResult CarenD2D1DCRenderTarget::CreateBitmapFromWicBitmap( ICaren^ Param_WicBitmapSource, [Out] ICarenD2D1Bitmap^% Param_Out_Bitmap) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. IWICBitmapSource* pWicBitmapSource = NULL; ID2D1Bitmap* pOutBitmap = NULL; //Recupera o ponteiro para o bitmap. Resultado = Param_WicBitmapSource->RecuperarPonteiro((LPVOID*)&pWicBitmapSource); //Verifica se não houve erro. if (!CarenSucesso(Resultado)) { //Falhou. O ponteiro é invalido. //Sai do método Sair; } //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateBitmapFromWicBitmap(pWicBitmapSource, &pOutBitmap); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a classe a ser retornada. Param_Out_Bitmap = gcnew CarenD2D1Bitmap(); //Define o ponteiro da interface. Resultado = Param_Out_Bitmap->AdicionarPonteiro(pOutBitmap); //Verifica se não houve erro if (!CarenSucesso(Resultado)) { //Falhou ao definir o ponteiro. //Libera os dados. pOutBitmap->Release(); pOutBitmap = NULL; Param_Out_Bitmap->Finalizar(); Param_Out_Bitmap = nullptr; } Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Cria um alvo de renderização bitmap para uso durante o desenho offscreen intermediário compatível com o alvo de renderização atual. /// </summary> /// <param name="Param_DesiredSize">O tamanho desejado do novo alvo de renderização (em pixels independentes do dispositivo), se ele deve ser diferente do alvo de renderização original.</param> /// <param name="Param_DesiredPixelSize">O tamanho desejado do novo alvo de renderização em pixels se ele deve ser diferente do alvo de renderização original.</param> /// <param name="DesiredFormat">O formato de pixel desejado e o modo alfa do novo alvo de renderização. Se o formato do pixel for definido para DXGI_FORMAT_UNKNOWN, o novo alvo de renderização usará /// o mesmo formato de pixel que o alvo original da renderização. Se o modo alfa estiver D2D1_ALPHA_MODE_UNKNOWN,o modo alfa do novo destino renderizante padrão para D2D1_ALPHA_MODE_PREMULTIPLIED.</param> /// <param name="Param_Opcoes">Um valor que especifica se o novo alvo de renderização deve ser compatível com o GDI.</param> /// <param name="Param_Out_BitmapRenderTarget">Retorna a interface (ICarenD2D1BitmapRenderTarget) que contém um ponteiro para um novo alvo de renderização bitmap. O usuário deve inicializar a interface antes de chamar este método.</param> CarenResult CarenD2D1DCRenderTarget::CreateCompatibleRenderTarget( CA_D2D1_SIZE_F^ Param_DesiredSize, CA_D2D1_SIZE_U^ Param_DesiredPixelSize, CA_D2D1_PIXEL_FORMAT^ DesiredFormat, CA_D2D1_COMPATIBLE_RENDER_TARGET_OPTIONS Param_Opcoes, ICaren^ Param_Out_BitmapRenderTarget) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_SIZE_F* pSizeF = NULL; D2D1_SIZE_U* pSizeU = NULL; D2D1_PIXEL_FORMAT* pPixelFormat = NULL; D2D1_COMPATIBLE_RENDER_TARGET_OPTIONS OptonsRender = static_cast<D2D1_COMPATIBLE_RENDER_TARGET_OPTIONS>(Param_Opcoes); ID2D1BitmapRenderTarget* pOutRenderTarget = NULL; //Converte as estruturas. pSizeF = Util.ConverterD2D1_SIZE_FManagedToUnmanaged(Param_DesiredSize); pSizeU = Util.ConverterD2D1_SIZE_UManagedToUnmanaged(Param_DesiredPixelSize); pPixelFormat = Util.ConverterD2D1_PIXEL_FORMATManagedToUnmanaged(DesiredFormat); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateCompatibleRenderTarget(*pSizeF, *pSizeU, *pPixelFormat, &pOutRenderTarget); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Define o ponteiro da interface inicializada pelo usuário. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutRenderTarget, Param_Out_BitmapRenderTarget, true)); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pSizeF); DeletarEstruturaSafe(&pSizeU); DeletarEstruturaSafe(&pPixelFormat); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um novo alvo de renderização bitmap para uso durante o desenho offscreen intermediário que é compatível com o alvo de renderização atual e tem o mesmo tamanho, DPI e formato de pixel /// (mas não o modo alfa) como o alvo de renderização atual. /// O alvo de renderização bitmap criado por este método não é compatível com o GDI, e tem um modo alfa de D2D1_ALPHA_MODE_PREMULTIPLIED. /// </summary> /// <param name="Param_Out_BitmapRenderTarget">Retorna a interface (ICarenD2D1BitmapRenderTarget) que contém um ponteiro para um novo alvo de renderização bitmap. O usuário deve inicializar a interface antes de chamar este método.</param> CarenResult CarenD2D1DCRenderTarget::CreateCompatibleRenderTarget(ICaren^ Param_Out_BitmapRenderTarget) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. ID2D1BitmapRenderTarget* pOutRenderTarget = NULL; //Chama o método para realizar a operação. PonteiroTrabalho->CreateCompatibleRenderTarget(&pOutRenderTarget); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Define o ponteiro da interface inicializada pelo usuário. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutRenderTarget, Param_Out_BitmapRenderTarget, true)); Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Cria um alvo de renderização bitmap para uso durante o desenho offscreen intermediário compatível com o alvo de renderização atual. /// O alvo de renderização bitmap criado por este método não é compatível com o GDI. /// </summary> /// <param name="Param_DesiredSize">O tamanho desejado do novo destino de renderização em pixels independentes do dispositivo. O tamanho do pixel é calculado a partir do tamanho desejado usando o DPI pai de destino. /// Se o tamanho desejado for mapeado para um tamanho de pixel inteiro, o DPI do destino de renderização compatível será o mesmo que o DPI pai do destino. Se o Tamanho desejado é mapeado para um tamanho de pixel /// fracionário, o tamanho do pixel é arredondado para o número inteiro mais próximo e o DPI para o destino de renderização compatível é um pouco maior que o DPI do destino de renderização pai. Em todos os casos, /// a coordenada (Param_DesiredSize.width, Param_DesiredSize.height) é mapeada para o canto inferior direito do destino de renderização compatível.</param> /// <param name="Param_Out_BitmapRenderTarget">Retorna a interface (ICarenD2D1BitmapRenderTarget) que contém um ponteiro para um novo alvo de renderização bitmap. O usuário deve inicializar a interface antes de chamar este método.</param> CarenResult CarenD2D1DCRenderTarget::CreateCompatibleRenderTarget( CA_D2D1_SIZE_F^ Param_DesiredSize, ICaren^ Param_Out_BitmapRenderTarget) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_SIZE_F* pSizeF = NULL; ID2D1BitmapRenderTarget* pOutRenderTarget = NULL; //Converte a estrutura. pSizeF = Util.ConverterD2D1_SIZE_FManagedToUnmanaged(Param_DesiredSize); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateCompatibleRenderTarget(*pSizeF, &pOutRenderTarget); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Define o ponteiro da interface inicializada pelo usuário. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutRenderTarget, Param_Out_BitmapRenderTarget)); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pSizeF); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um alvo de renderização bitmap para uso durante o desenho offscreen intermediário compatível com o alvo de renderização atual. /// </summary> /// <param name="Param_DesiredSize">O tamanho desejado do novo alvo de renderização (em pixels independentes do dispositivo), se ele deve ser diferente do alvo de renderização original.</param> /// <param name="Param_DesiredPixelSize">O tamanho desejado do novo alvo de renderização em pixels se ele deve ser diferente do alvo de renderização original.</param> /// <param name="Param_Out_BitmapRenderTarget">Retorna a interface (ICarenD2D1BitmapRenderTarget) que contém um ponteiro para um novo alvo de renderização bitmap. O usuário deve inicializar a interface antes de chamar este método.</param> CarenResult CarenD2D1DCRenderTarget::CreateCompatibleRenderTarget( CA_D2D1_SIZE_F^ Param_DesiredSize, CA_D2D1_SIZE_U^ Param_DesiredPixelSize, ICaren^ Param_Out_BitmapRenderTarget) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_SIZE_F* pSizeF = NULL; D2D1_SIZE_U* pSizeU = NULL; ID2D1BitmapRenderTarget* pOutRenderTarget = NULL; //Converte as estruturas. pSizeF = Util.ConverterD2D1_SIZE_FManagedToUnmanaged(Param_DesiredSize); pSizeU = Util.ConverterD2D1_SIZE_UManagedToUnmanaged(Param_DesiredPixelSize); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateCompatibleRenderTarget(*pSizeF, *pSizeU, &pOutRenderTarget); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Define o ponteiro da interface inicializada pelo usuário. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutRenderTarget, Param_Out_BitmapRenderTarget)); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pSizeF); DeletarEstruturaSafe(&pSizeU); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um alvo de renderização bitmap para uso durante o desenho offscreen intermediário compatível com o alvo de renderização atual. /// </summary> /// <param name="Param_DesiredSize">O tamanho desejado do novo alvo de renderização (em pixels independentes do dispositivo), se ele deve ser diferente do alvo de renderização original.</param> /// <param name="Param_DesiredPixelSize">O tamanho desejado do novo alvo de renderização em pixels se ele deve ser diferente do alvo de renderização original.</param> /// <param name="DesiredFormat">O formato de pixel desejado e o modo alfa do novo alvo de renderização. Se o formato do pixel for definido para DXGI_FORMAT_UNKNOWN, o novo alvo de renderização usará o mesmo formato de pixel que o alvo original da renderização. Se o modo alfa estiver D2D1_ALPHA_MODE_UNKNOWN,o modo alfa do novo destino renderizante padrão para D2D1_ALPHA_MODE_PREMULTIPLIED.</param> /// <param name="Param_Out_BitmapRenderTarget">Retorna a interface (ICarenD2D1BitmapRenderTarget) que contém um ponteiro para um novo alvo de renderização bitmap. O usuário deve inicializar a interface antes de chamar este método.</param> CarenResult CarenD2D1DCRenderTarget::CreateCompatibleRenderTarget( CA_D2D1_SIZE_F^ Param_DesiredSize, CA_D2D1_SIZE_U^ Param_DesiredPixelSize, CA_D2D1_PIXEL_FORMAT^ DesiredFormat, ICaren^ Param_Out_BitmapRenderTarget) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_SIZE_F* pSizeF = NULL; D2D1_SIZE_U* pSizeU = NULL; D2D1_PIXEL_FORMAT* pPixelFormat = NULL; ID2D1BitmapRenderTarget* pOutRenderTarget = NULL; //Converte as estruturas. pSizeF = Util.ConverterD2D1_SIZE_FManagedToUnmanaged(Param_DesiredSize); pSizeU = Util.ConverterD2D1_SIZE_UManagedToUnmanaged(Param_DesiredPixelSize); pPixelFormat = Util.ConverterD2D1_PIXEL_FORMATManagedToUnmanaged(DesiredFormat); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateCompatibleRenderTarget(*pSizeF, *pSizeU, *pPixelFormat, &pOutRenderTarget); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Define o ponteiro da interface inicializada pelo usuário. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutRenderTarget, Param_Out_BitmapRenderTarget)); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pSizeF); DeletarEstruturaSafe(&pSizeU); DeletarEstruturaSafe(&pPixelFormat); //Retorna o resultado. return Resultado; } /// <summary> /// Cria uma interface de coleção ICarenD2D1GradientStop a partir do conjunto especificado de estruturas CA_D2D1_GRADIENT_STOP. /// </summary> /// <param name="Param_MatrizGraientStops">Uma matriz de estruturas CA_D2D1_GRADIENT_STOP.</param> /// <param name="Param_QuantidadeGradientes">Um valor maior ou igual a 1 que especifica o número de estruturas(CA_D2D1_GRADIENT_STOP) na matriz (Param_MatrizGraientStops).</param> /// <param name="Param_ColorInterpolationGamma">O espaço em que a interpolação de cores entre as paradas gradientes é realizada.</param> /// <param name="Param_ModoExtendido">O comportamento do gradiente fora da faixa [0,1] normalizada.</param> /// <param name="Param_Out_GradientStopCollection">Retorna a interface ICarenD2D1GradientStopCollection que contém um ponteiro para a nova GradientStopCollection.</param> CarenResult CarenD2D1DCRenderTarget::CreateGradientStopCollection( cli::array<CA_D2D1_GRADIENT_STOP^>^ Param_MatrizGraientStops, UInt32 Param_QuantidadeGradientes, CA_D2D1_GAMMA Param_ColorInterpolationGamma, CA_D2D1_EXTEND_MODE Param_ModoExtendido, [Out] ICarenD2D1GradientStopCollection^% Param_Out_GradientStopCollection) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. D2D1_GRADIENT_STOP* pMatrizGradientes = CriarMatrizEstruturas<D2D1_GRADIENT_STOP>(Param_QuantidadeGradientes); D2D1_GAMMA Gamma = static_cast<D2D1_GAMMA>(Param_ColorInterpolationGamma); D2D1_EXTEND_MODE ExtendMode = static_cast<D2D1_EXTEND_MODE>(Param_ModoExtendido); ID2D1GradientStopCollection* pOutGradientCollection = NULL; //Copia os dados da matriz gerenciada para a nativa. for (UInt32 i = 0; i < Param_QuantidadeGradientes; i++) { //Inicializa a estrutura no index especifico. ZeroMemory(&pMatrizGradientes[i], sizeof(D2D1_GRADIENT_STOP)); //Define os dados. pMatrizGradientes[i].position = Param_MatrizGraientStops[i]->position; //Define os dados ARGB. pMatrizGradientes->color.a = Param_MatrizGraientStops[i]->color->a; pMatrizGradientes->color.r = Param_MatrizGraientStops[i]->color->r; pMatrizGradientes->color.g = Param_MatrizGraientStops[i]->color->g; pMatrizGradientes->color.b = Param_MatrizGraientStops[i]->color->b; } //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateGradientStopCollection(pMatrizGradientes, Param_QuantidadeGradientes, Gamma, ExtendMode, &pOutGradientCollection); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_GradientStopCollection = gcnew CarenD2D1GradientStopCollection(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutGradientCollection, Param_Out_GradientStopCollection)); Done:; //Libera a memória para a matriz de estruturas. DeletarMatrizEstruturasSafe(&pMatrizGradientes); //Retorna o resultado. return Resultado; } /// <summary> /// Cria uma interface de coleção ICarenD2D1GradientStop a partir das estruturas GradientStops especificadas que usa o gama de interpolação de cores D2D1_GAMMA_2_2 e o modo de extensão do Clamp. /// </summary> /// <param name="Param_MatrizGraientStops">Uma matriz de estruturas CA_D2D1_GRADIENT_STOP.</param> /// <param name="Param_QuantidadeGradientes">Um valor maior ou igual a 1 que especifica o número de estruturas(CA_D2D1_GRADIENT_STOP) na matriz (Param_MatrizGraientStops).</param> /// <param name="Param_Out_GradientStopCollection">Retorna a interface ICarenD2D1GradientStopCollection que contém um ponteiro para a nova GradientStopCollection.</param> CarenResult CarenD2D1DCRenderTarget::CreateGradientStopCollection( cli::array<CA_D2D1_GRADIENT_STOP^>^ Param_MatrizGraientStops, UInt32 Param_QuantidadeGradientes, [Out] ICarenD2D1GradientStopCollection^% Param_Out_GradientStopCollection) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_GRADIENT_STOP* pMatrizGradientes = CriarMatrizEstruturas<D2D1_GRADIENT_STOP>(Param_QuantidadeGradientes); ID2D1GradientStopCollection* pOutGradientCollection = NULL; //Copia os dados da matriz gerenciada para a nativa. for (UInt32 i = 0; i < Param_QuantidadeGradientes; i++) { //Inicializa a estrutura no index especifico. ZeroMemory(&pMatrizGradientes[i], sizeof(D2D1_GRADIENT_STOP)); //Define os dados. pMatrizGradientes[i].position = Param_MatrizGraientStops[i]->position; //Define os dados ARGB. pMatrizGradientes->color.a = Param_MatrizGraientStops[i]->color->a; pMatrizGradientes->color.r = Param_MatrizGraientStops[i]->color->r; pMatrizGradientes->color.g = Param_MatrizGraientStops[i]->color->g; pMatrizGradientes->color.b = Param_MatrizGraientStops[i]->color->b; } //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateGradientStopCollection(pMatrizGradientes, Param_QuantidadeGradientes, &pOutGradientCollection); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_GradientStopCollection = gcnew CarenD2D1GradientStopCollection(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutGradientCollection, Param_Out_GradientStopCollection)); Done:; //Libera a memória para a matriz de estruturas. DeletarMatrizEstruturasSafe(&pMatrizGradientes); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um recurso de camada que pode ser usado com este alvo de renderização e seus alvos de renderização compatíveis. /// </summary> /// <param name="Param_Size">Se (0, 0) for especificado, nenhuma loja de backup será criada por trás do recurso de camada. O recurso de camada é alocado para o tamanho mínimo quando o PushLayer é chamado.</param> /// <param name="Param_Out_Layer">Retorna a interface ICarenD2D1Layer que contém um ponteiro para a nova camada(Layer).</param> CarenResult CarenD2D1DCRenderTarget::CreateLayer( CA_D2D1_SIZE_F^ Param_Size, [Out] ICarenD2D1Layer^% Param_Out_Layer) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_SIZE_F* pSizeF = NULL; ID2D1Layer* pOutLayer = NULL; //Converte a estrutura. pSizeF = Util.ConverterD2D1_SIZE_FManagedToUnmanaged(Param_Size); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateLayer(pSizeF, &pOutLayer); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_Layer = gcnew CarenD2D1Layer(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutLayer, Param_Out_Layer)); Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pSizeF); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um recurso de camada que pode ser usado com este alvo de renderização e seus alvos de renderização compatíveis. /// </summary> /// <param name="Param_Out_Layer">Retorna a interface ICarenD2D1Layer que contém um ponteiro para a nova camada(Layer).</param> CarenResult CarenD2D1DCRenderTarget::CreateLayer([Out] ICarenD2D1Layer^% Param_Out_Layer) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. ID2D1Layer* pOutLayer = NULL; //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateLayer(&pOutLayer); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_Layer = gcnew CarenD2D1Layer(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutLayer, Param_Out_Layer)); Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Cria um ICarenD2D1LinearGradientBrush que contém as GradientStops especificadas e tem a opacidade de transformação e base especificada. /// </summary> /// <param name="Param_PropriedadesLinerarGradientBrush">Os pontos de partida e fim do gradiente.</param> /// <param name="Param_PropriedadesBrush">A opacidade de transformação e base do novo pincel.</param> /// <param name="Param_GradientStopCollection">Uma interface que contém uma coleção de estruturas D2D1_GRADIENT_STOP que descrevem as cores no Brush Gradient e suas localizações ao longo da linha gradiente.</param> /// <param name="Param_Out_LinearGradientBrush">Retorna uma interface ICarenD2D1LinearGradientBrush que contém um ponteiro para o novo Pincel(Brush).</param> CarenResult CarenD2D1DCRenderTarget::CreateLinearGradientBrush( CA_D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES^ Param_PropriedadesLinerarGradientBrush, CA_D2D1_BRUSH_PROPERTIES^ Param_PropriedadesBrush, ICarenD2D1GradientStopCollection^ Param_GradientStopCollection, [Out] ICarenD2D1LinearGradientBrush^% Param_Out_LinearGradientBrush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES* pLinearGradientProps = NULL; D2D1_BRUSH_PROPERTIES* pBrushProps = NULL; ID2D1GradientStopCollection* pGradientStopCollection = NULL; ID2D1LinearGradientBrush* pOutLinearGradientBrush = NULL; //Converte as estruturas. pLinearGradientProps = Util.ConverterD2D1_LINEAR_GRADIENT_BRUSH_PROPERTIESManagedToUnmanaged(Param_PropriedadesLinerarGradientBrush); pBrushProps = Util.ConverterD2D1_BRUSH_PROPERTIESManagedToUnmanaged(Param_PropriedadesBrush); //Recupera o ponteiro para a coleção de gradientes. Resultado = RecuperarPonteiroCaren(Param_GradientStopCollection, &pGradientStopCollection); //Sai do método em caso de erro SairOnError(Resultado); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateLinearGradientBrush(pLinearGradientProps, pBrushProps, pGradientStopCollection, &pOutLinearGradientBrush); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_LinearGradientBrush = gcnew CarenD2D1LinearGradientBrush(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutLinearGradientBrush, Param_Out_LinearGradientBrush)); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pLinearGradientProps); DeletarEstruturaSafe(&pBrushProps); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um ICarenD2D1LinearGradientBrush que contém os GradientStops especificados, não tem transformação e tem uma opacidade base de 1.0. /// </summary> /// <param name="Param_PropriedadesLinerarGradientBrush">Os pontos de partida e fim do gradiente.</param> /// <param name="Param_GradientStopCollection">Uma interface que contém uma coleção de estruturas D2D1_GRADIENT_STOP que descrevem as cores no Brush Gradient e suas localizações ao longo da linha gradiente.</param> /// <param name="Param_Out_LinearGradientBrush">Retorna uma interface ICarenD2D1LinearGradientBrush que contém um ponteiro para o novo Pincel(Brush).</param> CarenResult CarenD2D1DCRenderTarget::CreateLinearGradientBrush( CA_D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES^ Param_PropriedadesLinerarGradientBrush, ICarenD2D1GradientStopCollection^ Param_GradientStopCollection, [Out] ICarenD2D1LinearGradientBrush^% Param_Out_LinearGradientBrush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES* pLinearGradientProps = NULL; ID2D1GradientStopCollection* pGradientStopCollection = NULL; ID2D1LinearGradientBrush* pOutLinearGradientBrush = NULL; //Converte a estrutura. pLinearGradientProps = Util.ConverterD2D1_LINEAR_GRADIENT_BRUSH_PROPERTIESManagedToUnmanaged(Param_PropriedadesLinerarGradientBrush); //Recupera o ponteiro para a coleção de gradientes. Resultado = RecuperarPonteiroCaren(Param_GradientStopCollection, &pGradientStopCollection); //Sai do método em caso de erro SairOnError(Resultado); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateLinearGradientBrush(*pLinearGradientProps, pGradientStopCollection, &pOutLinearGradientBrush); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_LinearGradientBrush = gcnew CarenD2D1LinearGradientBrush(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutLinearGradientBrush, Param_Out_LinearGradientBrush)); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pLinearGradientProps); //Retorna o resultado. return Resultado; } /// <summary> /// Crie uma malha(Mesh) que usa triângulos para descrever uma forma. /// </summary> /// <param name="Param_Out_Mesh">Retorna uma interface ICarenD2D1Mesh que contém um ponteiro para a nova malha(Mesh).</param> CarenResult CarenD2D1DCRenderTarget::CreateMesh([Out] ICarenD2D1Mesh^% Param_Out_Mesh) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. ID2D1Mesh* pOutMesh = NULL; //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateMesh(&pOutMesh); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_Mesh = gcnew CarenD2D1Mesh(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutMesh, Param_Out_Mesh)); Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Cria um ICarenD2D1RadialGradientBrush que contém os GradientStops especificados e tem a opacidade de transformação e base especificada. /// </summary> /// <param name="Param_PropriedadesRadialGradientBrush">O centro, a origem gradiente compensada, e raio x e raio y do gradiente do Brush.</param> /// <param name="Param_PropriedadesBrush">A opacidade de transformação e base do novo pincel(Brush).</param> /// <param name="Param_GradientStopCollection">Uma interface que contém uma coleção de estruturas D2D1_GRADIENT_STOP que descrevem as cores no Brush Gradient e suas localizações ao longo do gradiente.</param> /// <param name="Param_Out_RadialGradientBrush">Retorna uma interface ICarenD2D1RadialGradientBrush que contém um ponteiro para o novo Pincel(Brush).</param> CarenResult CarenD2D1DCRenderTarget::CreateRadialGradientBrush( CA_D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES^ Param_PropriedadesRadialGradientBrush, CA_D2D1_BRUSH_PROPERTIES^ Param_PropriedadesBrush, ICarenD2D1GradientStopCollection^ Param_GradientStopCollection, [Out] ICarenD2D1RadialGradientBrush^% Param_Out_RadialGradientBrush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES* pRadialGradientProps = NULL; D2D1_BRUSH_PROPERTIES* pBrushProps = NULL; ID2D1GradientStopCollection* pGradientStopCollection = NULL; ID2D1RadialGradientBrush* pOutRadialGradientBrush = NULL; //Converte as estruturas. pRadialGradientProps = Util.ConverterD2D1_RADIAL_GRADIENT_BRUSH_PROPERTIESManagedToUnmanaged(Param_PropriedadesRadialGradientBrush); pBrushProps = Util.ConverterD2D1_BRUSH_PROPERTIESManagedToUnmanaged(Param_PropriedadesBrush); //Recupera o ponteiro para a coleção de gradientes. Resultado = RecuperarPonteiroCaren(Param_GradientStopCollection, &pGradientStopCollection); //Sai do método em caso de erro SairOnError(Resultado); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateRadialGradientBrush(pRadialGradientProps, pBrushProps, pGradientStopCollection, &pOutRadialGradientBrush); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_RadialGradientBrush = gcnew CarenD2D1RadialGradientBrush(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutRadialGradientBrush, Param_Out_RadialGradientBrush)); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pRadialGradientProps); DeletarEstruturaSafe(&pBrushProps); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um ICarenD2D1RadialGradientBrush que contém os GradientStops especificados, não tem transformação e tem uma opacidade base de 1.0. /// </summary> /// <param name="Param_PropriedadesRadialGradientBrush">O centro, a origem gradiente compensada, e raio x e raio y do gradiente do Brush.</param> /// <param name="Param_GradientStopCollection">Uma interface que contém uma coleção de estruturas D2D1_GRADIENT_STOP que descrevem as cores no Brush Gradient e suas localizações ao longo do gradiente.</param> /// <param name="Param_Out_RadialGradientBrush">Retorna uma interface ICarenD2D1RadialGradientBrush que contém um ponteiro para o novo Pincel(Brush).</param> CarenResult CarenD2D1DCRenderTarget::CreateRadialGradientBrush( CA_D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES^ Param_PropriedadesRadialGradientBrush, ICarenD2D1GradientStopCollection^ Param_GradientStopCollection, [Out] ICarenD2D1RadialGradientBrush^% Param_Out_RadialGradientBrush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES* pRadialGradientProps = NULL; ID2D1GradientStopCollection* pGradientStopCollection = NULL; ID2D1RadialGradientBrush* pOutRadialGradientBrush = NULL; //Converte a estrutura. pRadialGradientProps = Util.ConverterD2D1_RADIAL_GRADIENT_BRUSH_PROPERTIESManagedToUnmanaged(Param_PropriedadesRadialGradientBrush); //Recupera o ponteiro para a coleção de gradientes. Resultado = RecuperarPonteiroCaren(Param_GradientStopCollection, &pGradientStopCollection); //Sai do método em caso de erro SairOnError(Resultado); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateRadialGradientBrush(*pRadialGradientProps, pGradientStopCollection, &pOutRadialGradientBrush); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_RadialGradientBrush = gcnew CarenD2D1RadialGradientBrush(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutRadialGradientBrush, Param_Out_RadialGradientBrush)); Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Cria um ICarenD2D1Bitmap cujos dados são compartilhados com outro recurso. /// </summary> /// <param name="Param_Riid">O ID de interface do objeto que fornece os dados de origem.</param> /// <param name="Param_InterfaceDados">Uma ICarenD2D1Bitmap, ICarenDXGISurface ou uma ICarenWICBitmapLock que contém os dados para compartilhar com o novo ICarenD2D1Bitmap. </param> /// <param name="Param_PropriedadesBitmap">O formato de pixel e DPI do bitmap para criar. A DXGI_FORMAT parte do formato pixel deve corresponder à DXGI_FORMAT de dados ou o método falhará, mas os modos alfa /// não precisam coincidir. Para evitar uma incompatibilidade, você pode passar NULO ou o valor obtido da função auxiliar D2D1::PixelFormat. As configurações de DPI não têm que coincidir com as dos dados. /// Se o dpiX e o dpiY forem 0,0f, o DPI do alvo de renderização será usado.</param> /// <param name="Param_Out_Bitmap">Retorna uma interface ICarenD2D1Bitmap que contém um ponteiro para o novo bitmap.</param> CarenResult CarenD2D1DCRenderTarget::CreateSharedBitmap( String^ Param_Riid, ICaren^ Param_InterfaceDados, CA_D2D1_BITMAP_PROPERTIES^ Param_PropriedadesBitmap, [Out] ICarenD2D1Bitmap^% Param_Out_Bitmap) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; GUID Riid = GUID_NULL; PVOID pInterfaceDados = NULL; D2D1_BITMAP_PROPERTIES* pBitmapProps = NULL; //Poder ser NULO. ID2D1Bitmap* pOutBitmap = NULL; //Cria e converte os dados necessários. Riid = Util.CreateGuidFromString(Param_Riid); pBitmapProps = ObjetoGerenciadoValido(Param_PropriedadesBitmap) ? Util.ConverterD2D1_BITMAP_PROPERTIESManagedToUnmanaged(Param_PropriedadesBitmap) : NULL; //Recupera o ponteiro para a interface de dados. Resultado = RecuperarPonteiroCaren(Param_InterfaceDados, &pInterfaceDados); //Sai do método em caso de erro. SairOnError(Resultado); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateSharedBitmap(Riid, pInterfaceDados, pBitmapProps, &pOutBitmap); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_Bitmap = gcnew CarenD2D1Bitmap(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutBitmap, Param_Out_Bitmap)); Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pBitmapProps); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um novo ICarenD2D1SolidColorBrush que tem a cor e a opacidade especificados. /// </summary> /// <param name="Param_Cor">Os valores vermelho, verde, azul e alfa da cor do pincel.</param> /// <param name="Param_PropriedadesBrush">A opacidade base do pincel.</param> /// <param name="Param_Out_SolidColorBrush">Retorna uma interface ICarenD2D1Bitmap que contém um ponteiro para o novo pincel(Brush).</param> CarenResult CarenD2D1DCRenderTarget::CreateSolidColorBrush( CA_D2D1_COLOR_F^ Param_Cor, CA_D2D1_BRUSH_PROPERTIES^ Param_PropriedadesBrush, [Out] ICarenD2D1SolidColorBrush^% Param_Out_SolidColorBrush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_COLOR_F* pColorF = NULL; D2D1_BRUSH_PROPERTIES* pBrushProps = NULL; ID2D1SolidColorBrush* pOutSolidColorBrush = NULL; //Converte as estruturas. pColorF = Util.ConverterD2D1_COLOR_FManagedToUnmanaged(Param_Cor); pBrushProps = Util.ConverterD2D1_BRUSH_PROPERTIESManagedToUnmanaged(Param_PropriedadesBrush); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateSolidColorBrush(pColorF, pBrushProps, &pOutSolidColorBrush); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_SolidColorBrush = gcnew CarenD2D1SolidColorBrush(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutSolidColorBrush, Param_Out_SolidColorBrush)); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pColorF); DeletarEstruturaSafe(&pBrushProps); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um novo ICarenD2D1SolidColorBrush que tem a cor especificada e uma opacidade base de 1.0f. /// </summary> /// <param name="Param_Cor">Os valores vermelho, verde, azul e alfa da cor do pincel(Brush).</param> /// <param name="Param_Out_SolidColorBrush">Retorna uma interface ICarenD2D1Bitmap que contém um ponteiro para o novo pincel(Brush).</param> CarenResult CarenD2D1DCRenderTarget::CreateSolidColorBrush( CA_D2D1_COLOR_F^ Param_Cor, [Out] ICarenD2D1SolidColorBrush^% Param_Out_SolidColorBrush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_COLOR_F* pColorF = NULL; ID2D1SolidColorBrush* pOutSolidColorBrush = NULL; //Converte a estrutura. pColorF = Util.ConverterD2D1_COLOR_FManagedToUnmanaged(Param_Cor); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateSolidColorBrush(*pColorF, &pOutSolidColorBrush); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_SolidColorBrush = gcnew CarenD2D1SolidColorBrush(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutSolidColorBrush, Param_Out_SolidColorBrush)); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pColorF); //Retorna o resultado. return Resultado; } /// <summary> /// Desenha o bitmap especificado depois de dimensioná-lo para o tamanho do retângulo especificado. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como DrawBitmap) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Bitmap">O bitmap para renderizar.</param> /// <param name="Param_RetanguloDestino">O tamanho e a posição, em pixels independentes do dispositivo no espaço de coordenadas do alvo de renderização, da área para a qual o bitmap é desenhado. /// Se o retângulo não for bem ordenado, nada é desenhado, mas o alvo de renderização não entra em um estado de erro.</param> /// <param name="Param_Opacidade">Um valor entre 0,0f e 1,0f, inclusive, que especifica um valor de opacidade para aplicar ao bitmap; este valor é multiplicado em relação aos valores alfa do /// conteúdo do bitmap.</param> /// <param name="Param_InterpolationMode">O modo de interpolação a ser usado se o bitmap for dimensionado ou girado pela operação de desenho.</param> /// <param name="Param_RetanguloOrigem">O tamanho e a posição, em pixels independentes do dispositivo no espaço de coordenadas do bitmap, da área dentro do bitmap para desenhar.</param> CarenResult CarenD2D1DCRenderTarget::DrawBitmap( ICarenD2D1Bitmap^ Param_Bitmap, CA_D2D1_RECT_F^ Param_RetanguloDestino, float Param_Opacidade, CA_D2D1_BITMAP_INTERPOLATION_MODE Param_InterpolationMode, CA_D2D1_RECT_F^ Param_RetanguloOrigem) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; ID2D1Bitmap* pBitmapRender = NULL; D2D1_RECT_F* pRectDestinoF = NULL; D2D1_RECT_F* pRectOrigemF = NULL; D2D1_BITMAP_INTERPOLATION_MODE BitmapInterpolationMode = static_cast<D2D1_BITMAP_INTERPOLATION_MODE>(Param_InterpolationMode); //Recupera o ponteiro para o bitmap Resultado = RecuperarPonteiroCaren(Param_Bitmap, &pBitmapRender); //Sai do método em caso de erro SairOnError(Resultado); //Converte as estruturas. pRectDestinoF = Util.ConverterD2D1_RECT_FManagedToUnmanaged(Param_RetanguloDestino); pRectOrigemF = Util.ConverterD2D1_RECT_FManagedToUnmanaged(Param_RetanguloOrigem); //Chama o método para realizar a operação. PonteiroTrabalho->DrawBitmap(pBitmapRender, pRectDestinoF, Param_Opacidade, BitmapInterpolationMode, pRectOrigemF); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pRectDestinoF); DeletarEstruturaSafe(&pRectOrigemF); //Retorna o resultado. return Resultado; } /// <summary> /// Desenha o contorno(Outline) da elipse especificada usando o estilo de traçado especificado. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como DrawEllipse) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Ellipse">A posição e o raio da elipse para desenhar, em pixels independentes do dispositivo.</param> /// <param name="Param_Brush">O pincel(Brush) usado para pintar o contorno da elipse.</param> /// <param name="Param_StrokeWidth">A largura do Stroke, em pixels independentes do dispositivo. O valor deve ser maior ou igual a 0,0f. Se este parâmetro não for especificado, ele será padrão /// para 1.0f. O golpe está centrado na linha.</param> /// <param name="Param_StrokeStyle">O estilo do Stroke para aplicar ao contorno(Outline) da elipse, ou NULO para pintar um traço sólido.</param> CarenResult CarenD2D1DCRenderTarget::DrawEllipse( CA_D2D1_ELLIPSE^ Param_Ellipse, ICarenD2D1Brush^ Param_Brush, float Param_StrokeWidth, ICarenD2D1StrokeStyle^ Param_StrokeStyle) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_ELLIPSE* pEllipse = NULL; ID2D1Brush* pBrush = NULL; ID2D1StrokeStyle* pStrokeStyle = NULL; //Pode ser NULO. //Recupera o ponteiro para o Brush. Resultado = RecuperarPonteiroCaren(Param_Brush, &pBrush); //Sai do método em caso de erro. SairOnError(Resultado); //Recupera o ponteiro para o Stroke se informado. if (ObjetoGerenciadoValido(Param_StrokeStyle)) { //Recupera o ponteiro. RecuperarPonteiroCaren(Param_StrokeStyle, &pStrokeStyle); } //Converte a estrutura. pEllipse = Util.ConverterD2D1_ELLIPSEManagedToUnmanaged(Param_Ellipse); //Chama o método para realizar a operação. PonteiroTrabalho->DrawEllipse(pEllipse, pBrush, Param_StrokeWidth, pStrokeStyle); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pEllipse); //Retorna o resultado. return Resultado; } /// <summary> /// Desenha o contorno da geometria especificada usando o estilo de traçado especificado. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como DrawGeometry) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Geometria">A geometria para desenhar.</param> /// <param name="Param_Brush">O pincel(Brush) para pintar o traço(Stroke) da geometria.</param> /// <param name="Param_StrokeWidth">A largura do traçado, em pixels independentes do dispositivo. O valor deve ser maior ou igual a 0,0f. Se este parâmetro não for especificado, ele será padrão /// para 1.0f. O golpe está centrado na linha.</param> /// <param name="Param_StrokeStyle">O estilo de traçado(Stroke) para aplicar ao contorno(Outline) da geometria, ou NULO para pintar um traço(Stroke) sólido.</param> CarenResult CarenD2D1DCRenderTarget::DrawGeometry( ICarenD2D1Geometry^ Param_Geometria, ICarenD2D1Brush^ Param_Brush, float Param_StrokeWidth, ICarenD2D1StrokeStyle^ Param_StrokeStyle) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; ID2D1Geometry* pGeometryRender = NULL; ID2D1Brush* pBrush = NULL; ID2D1StrokeStyle* pStrokeStyle = NULL; //Pode ser NULO. //Recupera o ponteiro para a gemetria. Resultado = RecuperarPonteiroCaren(Param_Geometria, &pGeometryRender); //Sai do método em caso de erro. SairOnError(Resultado); //Recupera o ponteiro para o Brush. Resultado = RecuperarPonteiroCaren(Param_Brush, &pBrush); //Sai do método em caso de erro. SairOnError(Resultado); //Recupera o ponteiro para o Stroke se informado. if (ObjetoGerenciadoValido(Param_StrokeStyle)) { //Recupera o ponteiro. RecuperarPonteiroCaren(Param_StrokeStyle, &pStrokeStyle); } //Chama o método para realizar a operação. PonteiroTrabalho->DrawGeometry(pGeometryRender, pBrush, Param_StrokeWidth, pStrokeStyle); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Desenha os glifos(Glyph) especificados. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como DrawGlyphRun) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_BaseLineOrigin">A origem, em pixels independentes de dispositivos, da linha de base dos glifos(Glyph).</param> /// <param name="Param_GlyphRun">Os glifos(Glyph) para renderizar.</param> /// <param name="Param_ForegroundBrush">O pincel(Brush) usado para pintar os glifos(Glyph) especificados.</param> /// <param name="Param_MeasuringMode">Um valor que indica como as métricas do glifo(Glyph) são usadas para medir o texto quando ele é formatado. O valor padrão é DWRITE_MEASURING_MODE_NATURAL.</param> CarenResult CarenD2D1DCRenderTarget::DrawGlyphRun( CA_D2D1_POINT_2F^ Param_BaseLineOrigin, CA_DWRITE_GLYPH_RUN^ Param_GlyphRun, ICarenD2D1Brush^ Param_ForegroundBrush, CA_DWRITE_MEASURING_MODE Param_MeasuringMode) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_POINT_2F* pPoint = NULL; DWRITE_GLYPH_RUN* pGlyphRun = NULL; ID2D1Brush* pBrush = NULL; DWRITE_MEASURING_MODE DWriteMeasuringMode = static_cast<DWRITE_MEASURING_MODE>(Param_MeasuringMode); //Converte as estruturas. pPoint = Util.ConverterD2D1_POINT_2FManagedToUnmanaged(Param_BaseLineOrigin); pGlyphRun = Util.ConverterDWRITE_GLYPH_RUNManagedToUnmanaged(Param_GlyphRun); //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_ForegroundBrush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Chama o método para realizar a operação. PonteiroTrabalho->DrawGlyphRun(*pPoint, pGlyphRun, pBrush, DWriteMeasuringMode); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para as matrizes. DeletarEstruturaSafe(&pPoint); if (ObjetoValido(pGlyphRun)) { //Libera as matrizes internas da estrutura. DeletarMatrizUnidimensionalSafe(&pGlyphRun->glyphIndices); DeletarMatrizUnidimensionalSafe(&pGlyphRun->glyphAdvances); DeletarMatrizEstruturasSafe(&pGlyphRun->glyphOffsets); } DeletarEstruturaSafe(&pGlyphRun); //Retorna o resultado. return Resultado; } /// <summary> /// Desenha uma linha entre os pontos especificados usando o estilo de traçado especificado. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como DrawLine) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Point0">O ponto de partida da linha, em pixels independentes de dispositivos.</param> /// <param name="Param_Point1">O ponto final da linha, em pixels independentes de dispositivos.</param> /// <param name="Param_Brush">O pincel(Brush) para pintar o traço da linha.</param> /// <param name="Param_StrokeWidth">A largura do Stroke, em pixels independentes do dispositivo.O valor deve ser maior ou igual a 0, 0f.Se esse parâmetro não for especificado, o padrão será 1.0f. /// O Stroke é centralizado na linha.</param> /// <param name="Param_StrokeStyle">O estilo de Stroke para pintar, ou NULO para pintar uma linha sólida.</param> CarenResult CarenD2D1DCRenderTarget::DrawLine( CA_D2D1_POINT_2F^ Param_Point0, CA_D2D1_POINT_2F^ Param_Point1, ICarenD2D1Brush^ Param_Brush, float Param_StrokeWidth, ICarenD2D1StrokeStyle^ Param_StrokeStyle) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_POINT_2F* pPoint0 = NULL; D2D1_POINT_2F* pPoint1 = NULL; ID2D1Brush* pBrush = NULL; ID2D1StrokeStyle* pStrokeStyle = NULL; //Converte as estruturas. pPoint0 = Util.ConverterD2D1_POINT_2FManagedToUnmanaged(Param_Point0); pPoint1 = Util.ConverterD2D1_POINT_2FManagedToUnmanaged(Param_Point1); //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_Brush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Recupera o ponteiro para o Stroke se informado. if (ObjetoGerenciadoValido(Param_StrokeStyle)) { //Recupera o ponteiro. RecuperarPonteiroCaren(Param_StrokeStyle, &pStrokeStyle); } //Chama o método para realizar a operação. PonteiroTrabalho->DrawLine(*pPoint0, *pPoint1, pBrush, Param_StrokeWidth, pStrokeStyle); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pPoint0); DeletarEstruturaSafe(&pPoint1); //Retorna o resultado. return Resultado; } /// <summary> /// Desenha o contorno(Outline) de um retângulo que tem as dimensões especificadas e o estilo de traçado. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como DrawRectangle) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Rect">As dimensões do retângulo para desenhar, em pixels independentes do dispositivo.</param> /// <param name="Param_Brush">O pincel(Brush) usado para pintar o curso do retângulo.</param> /// <param name="Param_StrokeWidth">A largura do traçado(Stroke), em pixels independentes do dispositivo. O valor deve ser maior ou igual a 0,0f. Se esse parâmetro não for especificado, /// o padrão será 1.0f. O traço(Stroke) é centralizado na linha.</param> /// <param name="Param_StrokeStyle">O estilo do traço(Stroke) para pintar ou NULO para pintar um traçado sólido.</param> CarenResult CarenD2D1DCRenderTarget::DrawRectangle( CA_D2D1_RECT_F^ Param_Rect, ICarenD2D1Brush^ Param_Brush, float Param_StrokeWidth, ICarenD2D1StrokeStyle^ Param_StrokeStyle) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_RECT_F* pRectF = NULL; ID2D1Brush* pBrush = NULL; ID2D1StrokeStyle* pStrokeStyle = NULL; //Converte a estrutura. pRectF = Util.ConverterD2D1_RECT_FManagedToUnmanaged(Param_Rect); //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_Brush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Recupera o ponteiro para o Stroke se informado. if (ObjetoGerenciadoValido(Param_StrokeStyle)) { //Recupera o ponteiro. RecuperarPonteiroCaren(Param_StrokeStyle, &pStrokeStyle); } //Chama o método para realizar a operação. PonteiroTrabalho->DrawRectangle(pRectF, pBrush, Param_StrokeWidth, pStrokeStyle); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pRectF); //Retorna o resultado. return Resultado; } /// <summary> /// Desenha o contorno(Outline) do retângulo arredondado especificado usando o estilo de traçado especificado. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como DrawRoundedRectangle) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_RoundedRect">As dimensões do retângulo arredondado para desenhar, em pixels independentes do dispositivo.</param> /// <param name="Param_Brush">O pincel(Brush) usado para pintar o contorno do retângulo arredondado.</param> /// <param name="Param_StrokeWidth">A largura do traçado(Stroke), em pixels independentes do dispositivo. O valor deve ser maior ou igual a 0,0f. Se esse parâmetro não for especificado, o padrão /// será 1.0f. O traço(Stroke) é centralizado na linha.</param> /// <param name="Param_StrokeStyle">O estilo do traçado do retângulo arredondado, ou NULO para pintar um traço sólido. O valor padrão é NULO.</param> CarenResult CarenD2D1DCRenderTarget::DrawRoundedRectangle( CA_D2D1_ROUNDED_RECT^ Param_RoundedRect, ICarenD2D1Brush^ Param_Brush, float Param_StrokeWidth, ICarenD2D1StrokeStyle^ Param_StrokeStyle) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_ROUNDED_RECT* pRoundedRect = NULL; ID2D1Brush* pBrush = NULL; ID2D1StrokeStyle* pStrokeStyle = NULL; //Converte a estrutura. pRoundedRect = Util.ConverterD2D1_ROUNDED_RECTManagedToUnmanaged(Param_RoundedRect); //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_Brush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Recupera o ponteiro para o Stroke se informado. if (ObjetoGerenciadoValido(Param_StrokeStyle)) { //Recupera o ponteiro. RecuperarPonteiroCaren(Param_StrokeStyle, &pStrokeStyle); } //Chama o método para realizar a operação. PonteiroTrabalho->DrawRoundedRectangle(pRoundedRect, pBrush, Param_StrokeWidth, pStrokeStyle); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pRoundedRect); //Retorna o resultado. return Resultado; } /// <summary> /// Desenha o texto especificado usando as informações de formato fornecidas por um objeto ICarenDWriteTextFormat. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como DrawText) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Texto">Uma string de caracteres Unicode para desenhar.</param> /// <param name="Param_TamanhoTexto">O número de caracteres em (Param_Texto).</param> /// <param name="Param_TextFormat">Uma interface(ICarenDWriteTextFormat) que descreve a formatação de detalhes do texto para desenhar, como a fonte, o tamanho da fonte e a direção do fluxo.</param> /// <param name="Param_LayoutRect">O tamanho e a posição da área em que o texto é desenhado.</param> /// <param name="Param_DefaultFillBrush">O pincel(Brush) usado para pintar o texto.</param> /// <param name="Param_Opcoes">Um valor que indica se o texto deve ser encaixado nos limites do pixel e se o texto deve ser cortado no retângulo de layout. O valor padrão é D2D1_DRAW_TEXT_OPTIONS_NONE, /// o que indica que o texto deve ser encaixado nos limites do pixel e não deve ser cortado para o retângulo de layout.</param> /// <param name="Param_MeasuringMode">Um valor que indica como as métricas do glifo(Glyph) são usadas para medir o texto quando ele é formatado. O valor padrão é DWRITE_MEASURING_MODE_NATURAL.</param> CarenResult CarenD2D1DCRenderTarget::DrawText( String^ Param_Texto, UInt32 Param_TamanhoTexto, ICaren^ Param_TextFormat, CA_D2D1_RECT_F^ Param_LayoutRect, ICarenD2D1Brush^ Param_DefaultFillBrush, CA_D2D1_DRAW_TEXT_OPTIONS Param_Opcoes, CA_DWRITE_MEASURING_MODE Param_MeasuringMode) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; PWCHAR pTexto = NULL; IDWriteTextFormat* pTextFormat = NULL; D2D1_RECT_F* pLayoutRectF = NULL; ID2D1Brush* pBrush = NULL; D2D1_DRAW_TEXT_OPTIONS DrawTextOptions = static_cast<D2D1_DRAW_TEXT_OPTIONS>(Param_Opcoes); DWRITE_MEASURING_MODE MeasuringMode = static_cast<DWRITE_MEASURING_MODE>(Param_MeasuringMode); //Verifica se a string é valida if (!ObjetoGerenciadoValido(Param_Texto)) throw gcnew NullReferenceException("O texto a ser desenhado não pode ser NULO!"); //Converte a string para wchar pTexto = Util.ConverterStringToWCHAR(Param_Texto); //Recupera o ponteiro para a interface de formato do texto. Resultado = RecuperarPonteiroCaren(Param_TextFormat, &pTextFormat); //Sai do método em caso de erro SairOnError(Resultado); //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_DefaultFillBrush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Converte a estrutura. pLayoutRectF = Util.ConverterD2D1_RECT_FManagedToUnmanaged(Param_LayoutRect); //Chama o método para realizar a operação. PonteiroTrabalho->DrawText(pTexto, Param_TamanhoTexto, pTextFormat, pLayoutRectF, pBrush, DrawTextOptions, MeasuringMode); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para os dados. DeletarStringAllocatedSafe(&pTexto); DeletarEstruturaSafe(&pLayoutRectF); //Retorna o resultado. return Resultado; } /// <summary> /// Desenha o texto formatado descrito pelo objeto ICarenDWriteTextLayout especificado. /// Ao desenhar o mesmo texto repetidamente, o uso do método DrawTextLayout é mais eficiente do que usar o método DrawText porque o texto não precisa ser formatado e o layout processado a cada chamada. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como DrawTextLayout) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Origem">O ponto, descrito em pixels independentes do dispositivo, no qual o canto superior esquerdo do texto descrito pelo (Param_TextLayout) é desenhado.</param> /// <param name="Param_TextLayout">Uma interface(ICarenDWriteTextLayout) com o texto formatado para desenhar. Quaisquer efeitos de desenho que não herdem do ID2D1Resource são ignorados. Se houver /// efeitos de desenho que herdam do ICarenD2D1Resource que não são pincéis, este método falhará e o alvo de renderização é colocado em um estado de erro.</param> /// <param name="Param_DefaultFillBrush">O pincel(Brush) usado para pintar qualquer texto no (Param_TextLayout) que ainda não tenha um pincel associado a ele como efeito de desenho (especificado pelo /// método ICarenDWriteTextLayout::SetDrawingEffect).</param> /// <param name="Param_Opcoes">Um valor que indica se o texto deve ser encaixado nos limites do pixel e se o texto deve ser cortado no retângulo de layout. O valor padrão é D2D1_DRAW_TEXT_OPTIONS_NONE, /// o que indica que o texto deve ser encaixado nos limites do pixel e não deve ser cortado para o retângulo de layout.</param> CarenResult CarenD2D1DCRenderTarget::DrawTextLayout( CA_D2D1_POINT_2F^ Param_Origem, ICaren^ Param_TextLayout, ICarenD2D1Brush^ Param_DefaultFillBrush, CA_D2D1_DRAW_TEXT_OPTIONS Param_Opcoes) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Variaveis a serem utilizadas. Utilidades Util; D2D1_POINT_2F* pPointOrigem = NULL; IDWriteTextLayout* pDwriterTextLayout = NULL; ID2D1Brush* pBrush = NULL; D2D1_DRAW_TEXT_OPTIONS DrawTextOptions = static_cast<D2D1_DRAW_TEXT_OPTIONS>(Param_Opcoes); //Recupera o ponteiro para a interface de formato do texto. Resultado = RecuperarPonteiroCaren(Param_TextLayout, &pDwriterTextLayout); //Sai do método em caso de erro SairOnError(Resultado); //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_DefaultFillBrush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Converte a estrutura. pPointOrigem = Util.ConverterD2D1_POINT_2FManagedToUnmanaged(Param_Origem); //Chama o método para realizar a operação. PonteiroTrabalho->DrawTextLayout(*pPointOrigem, pDwriterTextLayout, pBrush, DrawTextOptions); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pPointOrigem); //Retorna o resultado. return Resultado; } /// <summary> /// Termina as operações de desenho no alvo de renderização e indica o estado de erro atual e as tags associadas. /// </summary> /// <param name="Param_Out_Tag1">Quando este método retorna, contém a tag para operações de desenho que causaram erros ou 0 se não houver erros.</param> /// <param name="Param_Out_Tag2">Quando este método retorna, contém a tag para operações de desenho que causaram erros ou 0 se não houver erros.</param> CarenResult CarenD2D1DCRenderTarget::EndDraw( [Out] UInt64% Param_Out_Tag1, [Out] UInt64% Param_Out_Tag2) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. UINT64 OutTag1 = 0; UINT64 OutTag2 = 0; //Chama o método para realizar a operação. Hr = PonteiroTrabalho->EndDraw(&OutTag1, &OutTag2); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Define os valores nos parametros de saida. Param_Out_Tag1 = OutTag1; Param_Out_Tag2 = OutTag2; Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Pinta o interior da elipse especificada. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como FillEllipse) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Ellipse">A posição e o raio, em pixels independentes do dispositivo, da elipse para pintar.</param> /// <param name="Param_Brush">O pincel(Brush) usado para pintar o interior da elipse.</param> CarenResult CarenD2D1DCRenderTarget::FillEllipse( CA_D2D1_ELLIPSE^ Param_Ellipse, ICarenD2D1Brush^ Param_Brush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Variaveis a serem utilizadas. Utilidades Util; D2D1_ELLIPSE* pEllipse = NULL; ID2D1Brush* pBrush = NULL; //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_Brush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Converte a estrutura. pEllipse = Util.ConverterD2D1_ELLIPSEManagedToUnmanaged(Param_Ellipse); //Chama o método para realizar a operação. PonteiroTrabalho->FillEllipse(pEllipse, pBrush); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pEllipse); //Retorna o resultado. return Resultado; } /// <summary> /// Pinta o interior da geometria especificada. /// Se o parâmetro (Param_OpacityBrush) não for NULO, o valor alfa de cada pixel da opacidade mapeadaBrush é usado para determinar a opacidade resultante de cada pixel correspondente da geometria. /// Apenas o valor alfa de cada cor no Brush é usado para este processamento; todas as outras informações de cores são ignoradas. /// O valor alfa especificado pelo Brush é multiplicado pelo valor alfa da geometria após a geometria ter sido pintada pelo Brush. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como FillGeometry) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Geometria">A geometria para pintar.</param> /// <param name="Param_Brush">O pincel(Brush) para pintar o interior da geometria.</param> /// <param name="Param_OpacityBrush">A máscara de opacidade para aplicar à geometria, ou NULO para nenhuma máscara de opacidade. Se uma máscara de opacidade (o parâmetro Param_OpacityBrush) for especificada, /// o (Param_Brush) deve ser um ICarenD2D1BitmapBrush que tem seus modos x e y-extend definidos para D2D1_EXTEND_MODE_CLAMP.</param> CarenResult CarenD2D1DCRenderTarget::FillGeometry( ICarenD2D1Geometry^ Param_Geometria, ICarenD2D1Brush^ Param_Brush, ICarenD2D1Brush^ Param_OpacityBrush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Variaveis a serem utilizadas. ID2D1Geometry* pGeometry = NULL; ID2D1Brush* pBrush = NULL; ID2D1Brush* pOpacityBrush = NULL; //Pode ser NULO. //Recupera o ponteiro para a interface de Geometria. Resultado = RecuperarPonteiroCaren(Param_Geometria, &pGeometry); //Sai do método em caso de erro SairOnError(Resultado); //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_Brush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Verifica se forneceu o Brush de opacidade if (ObjetoGerenciadoValido(Param_OpacityBrush)) { //Recupera o ponteiro para a interface do Brush de opacidade. RecuperarPonteiroCaren(Param_OpacityBrush, &pOpacityBrush); } //Chama o método para realizar a operação. PonteiroTrabalho->FillGeometry(pGeometry, pBrush, pOpacityBrush); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Pinta o interior da malha especificada. /// O modo antialias atual do alvo de renderização deve ser D2D1_ANTIALIAS_MODE_ALIASED quando FillMesh é chamado. Para alterar o modo antialias do alvo de renderização, use o método SetAntialiasMode. /// FillMesh não espera uma ordem de enrolamento específica para os triângulos no ID2D1Mesh; tanto no sentido horário quanto no sentido anti-horário funcionará. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como FillMesh) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Mesh">A malha para pintar.</param> /// <param name="Param_Brush">O pincel(Brush) para pintar a malha.</param> CarenResult CarenD2D1DCRenderTarget::FillMesh( ICarenD2D1Mesh^ Param_Mesh, ICarenD2D1Brush^ Param_Brush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Variaveis a serem utilizadas. ID2D1Mesh* pMesh = NULL; ID2D1Brush* pBrush = NULL; //Recupera o ponteiro para a interface do Mesh Resultado = RecuperarPonteiroCaren(Param_Mesh, &pMesh); //Sai do método em caso de erro SairOnError(Resultado); //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_Brush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Chama o método para realizar a operação. PonteiroTrabalho->FillMesh(pMesh, pBrush); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Aplica a máscara de opacidade descrita pelo bitmap especificado em um pincel e usa esse pincel para pintar uma região do alvo de renderização. /// Para que este método funcione corretamente, o alvo de renderização deve estar usando o modo D2D1_ANTIALIAS_MODE_ALIASED antialiasing. Você pode definir o modo antialiasing chamando o método /// ICarenD2D1RenderTarget::SetAntialiasMode método. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como FillOpacityMask) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_OpacityMask">A máscara de opacidade para aplicar no pincel. O valor alfa de cada pixel na região especificado pelo (Param_RetanguloOrigem) é multiplicado com o valor alfa do /// Brush após o pincel(Brush) ter sido mapeado para a área definida pelo (Param_RetanguloDestino).</param> /// <param name="Param_Brush">O pincel(Brush) usado para pintar a região do alvo de render especificado pelo (Param_RetanguloDestino).</param> /// <param name="Param_Content">O tipo de conteúdo que a máscara de opacidade contém. O valor é usado para determinar o espaço de cor no qual a máscara de opacidade é misturada. /// A partir do Windows 8, o D2D1_OPACITY_MASK_CONTENT não é necessário. Consulte o método ICarenD2D1DeviceContext::FillOpacityMask, que não tem parâmetro D2D1_OPACITY_MASK_CONTENT.</param> /// <param name="Param_RetanguloDestino">A região do alvo de renderização para pintar, em pixels independentes do dispositivo.</param> /// <param name="Param_RetanguloOrigem">A região do bitmap para usar como máscara de opacidade, em pixels independentes de dispositivos.</param> CarenResult CarenD2D1DCRenderTarget::FillOpacityMask( ICarenD2D1Bitmap^ Param_OpacityMask, ICarenD2D1Brush^ Param_Brush, CA_D2D1_OPACITY_MASK_CONTENT Param_Content, CA_D2D1_RECT_F^ Param_RetanguloDestino, CA_D2D1_RECT_F^ Param_RetanguloOrigem) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Variaveis a serem utilizadas. Utilidades Util; ID2D1Bitmap* pOpacityMaskBitmap = NULL; ID2D1Brush* pBrush = NULL; D2D1_OPACITY_MASK_CONTENT OpacityMask = static_cast<D2D1_OPACITY_MASK_CONTENT>(Param_Content); D2D1_RECT_F* pRectDestinoF = NULL; D2D1_RECT_F* pRectOrigemF = NULL; //Recupera o ponteiro para a interface do Opacity Mask Resultado = RecuperarPonteiroCaren(Param_OpacityMask, &pOpacityMaskBitmap); //Sai do método em caso de erro SairOnError(Resultado); //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_Brush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Converte as estruturas. pRectDestinoF = Util.ConverterD2D1_RECT_FManagedToUnmanaged(Param_RetanguloDestino); pRectOrigemF = Util.ConverterD2D1_RECT_FManagedToUnmanaged(Param_RetanguloOrigem); //Chama o método para realizar a operação. PonteiroTrabalho->FillOpacityMask(pOpacityMaskBitmap, pBrush, OpacityMask, pRectDestinoF, pRectOrigemF); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pRectDestinoF); DeletarEstruturaSafe(&pRectOrigemF); //Retorna o resultado. return Resultado; } /// <summary> /// Pinta o interior do retângulo especificado. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como FillRectangle) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Rect">A dimensão do retângulo para pintar, em pixels independentes do dispositivo.</param> /// <param name="Param_Brush">O pincel(Brush) usado para pintar o interior do retângulo.</param> CarenResult CarenD2D1DCRenderTarget::FillRectangle( CA_D2D1_RECT_F^ Param_Rect, ICarenD2D1Brush^ Param_Brush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Variaveis a serem utilizadas. Utilidades Util; D2D1_RECT_F* pRectF = NULL; ID2D1Brush* pBrush = NULL; //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_Brush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Converte a estrutura. pRectF = Util.ConverterD2D1_RECT_FManagedToUnmanaged(Param_Rect); //Chama o método para realizar a operação. PonteiroTrabalho->FillRectangle(pRectF, pBrush); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pRectF); //Retorna o resultado. return Resultado; } /// <summary> /// Pinta o interior do retângulo arredondado especificado. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como FillRoundedRectangle) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Rect">As dimensões do retângulo arredondado para pintar, em pixels independentes do dispositivo.</param> /// <param name="Param_Brush">O pincel(Brush) usado para pintar o interior do retângulo arredondado.</param> CarenResult CarenD2D1DCRenderTarget::FillRoundedRectangle( CA_D2D1_ROUNDED_RECT^ Param_Rect, ICarenD2D1Brush^ Param_Brush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Variaveis a serem utilizadas. Utilidades Util; D2D1_ROUNDED_RECT* pRoundedRectF = NULL; ID2D1Brush* pBrush = NULL; //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_Brush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Converte a estrutura. pRoundedRectF = Util.ConverterD2D1_ROUNDED_RECTManagedToUnmanaged(Param_Rect); //Chama o método para realizar a operação. PonteiroTrabalho->FillRoundedRectangle(pRoundedRectF, pBrush); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pRoundedRectF); //Retorna o resultado. return Resultado; } /// <summary> /// Executa todos os comandos de desenho pendentes. /// Este comando não libera o contexto do dispositivo Direct3D que está associado ao alvo de renderização. /// Chamar este método redefine o estado de erro do alvo de renderização. /// Se o método for bem sucedido, ele retorna SS_OK. Caso contrário, ele retorna um código de erro HRESULT e define Tag1 e Tag2 para as tags que estavam ativas quando o erro ocorreu. Se não ocorreu nenhum erro, /// este método define o estado de Tags de erro (0,0). /// </summary> /// <param name="Param_Out_Tag1">Quando este método retorna, contém a tag para operações de desenho que causaram erros ou 0 se não houver erros.</param> /// <param name="Param_Out_Tag2">Quando este método retorna, contém a tag para operações de desenho que causaram erros ou 0 se não houver erros.</param> CarenResult CarenD2D1DCRenderTarget::Flush( [Out] UInt64% Param_Out_Tag1, [Out] UInt64% Param_Out_Tag2) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. UINT64 OutTag1 = 0; UINT64 OutTag2 = 0; //Chama o método para realizar a operação. Hr = PonteiroTrabalho->Flush(&OutTag1, &OutTag2); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Define os valores nos parametros de saida. Param_Out_Tag1 = OutTag1; Param_Out_Tag2 = OutTag2; Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Recupera o modo antialiasing atual para operações de desenho sem texto. /// </summary> /// <param name="Param_Out_AntialiasMode">Retorna o modo antialiasing atual para operações de desenho sem texto.</param> void CarenD2D1DCRenderTarget::GetAntialiasMode([Out] CA_D2D1_ANTIALIAS_MODE% Param_Out_AntialiasMode) { //Variaveis a serem utilizadas. D2D1_ANTIALIAS_MODE OutAliasMode; //Chama o método para realizar a operação. OutAliasMode = PonteiroTrabalho->GetAntialiasMode(); //Define no parametro de saida. Param_Out_AntialiasMode = static_cast<CA_D2D1_ANTIALIAS_MODE>(OutAliasMode); } /// <summary> /// Retorne os pontos do alvo de renderização por polegada (DPI). /// </summary> /// <param name="Param_Out_DpiX">Retorna o DPI horizontal do alvo de renderização.</param> /// <param name="Param_Out_DpiY">Retorna o DPI vertical do alvo de renderização. </param> void CarenD2D1DCRenderTarget::GetDpi( [Out] float% Param_Out_DpiX, [Out] float% Param_Out_DpiY) { //Variaveis a serem utilizadas. FLOAT OutDpiX; FLOAT OutDpiY; //Chama o método para realizar a operação. PonteiroTrabalho->GetDpi(&OutDpiX, &OutDpiY); //Define nos parametros de saida. Param_Out_DpiX = OutDpiX; Param_Out_DpiY = OutDpiY; } /// <summary> /// Obtém o tamanho máximo, em unidades dependentes de dispositivos (pixels), de qualquer dimensão de bitmap suportada pelo alvo de renderização. /// Este método retorna o tamanho máximo da textura do dispositivo Direct3D. /// O renderizador de software e os dispositivos WARP retornam o valor de 16 megapixels (16* 1024 * 1024). Você pode criar uma textura Direct2D que é deste tamanho, mas não uma textura Direct3D que /// é deste tamanho. /// </summary> /// <param name="Param_Out_MaximumSize">Retorna o tamanho máximo, em pixels, de qualquer dimensão de bitmap suportada pelo alvo de renderização.</param> void CarenD2D1DCRenderTarget::GetMaximumBitmapSize([Out] UInt32% Param_Out_MaximumSize) { //Chama o método para realizar a operação. Param_Out_MaximumSize = PonteiroTrabalho->GetMaximumBitmapSize(); } /// <summary> /// Recupera o formato de pixel e o modo alfa do alvo de renderização. /// </summary> /// <param name="Param_Out_PixelFormat">Retorna o formato pixel e o modo alfa do alvo de renderização.</param> void CarenD2D1DCRenderTarget::GetPixelFormat([Out] CA_D2D1_PIXEL_FORMAT^% Param_Out_PixelFormat) { //Variaveis a serem utilizadas. Utilidades Util; D2D1_PIXEL_FORMAT OutPixelFormat; //Chama o método para realizar a operação. OutPixelFormat = PonteiroTrabalho->GetPixelFormat(); //Converte e define no parametro de saida. Param_Out_PixelFormat = Util.ConverterD2D1_PIXEL_FORMATUnmanagedToManaged(&OutPixelFormat); } /// <summary> /// Retorna o tamanho do alvo de renderização em pixels do dispositivo. /// </summary> /// <param name="Param_Out_PixelSize">Retorna tamanho do alvo de renderização em pixels do dispositivo.</param> void CarenD2D1DCRenderTarget::GetPixelSize([Out] CA_D2D1_SIZE_U^% Param_Out_PixelSize) { //Variaveis a serem utilizadas. Utilidades Util; D2D1_SIZE_U OutSizeU; //Chama o método para realizar a operação. OutSizeU = PonteiroTrabalho->GetPixelSize(); //Converte e define no parametro de saida. Param_Out_PixelSize = Util.ConverterD2D1_SIZE_UUnmanagedToManaged(&OutSizeU); } /// <summary> /// Retorna o tamanho do alvo de renderização em pixels independentes do dispositivo. /// </summary> /// <param name="Param_Out_Size">Retorna tamanho atual do alvo de renderização em pixels independentes do dispositivo.</param> void CarenD2D1DCRenderTarget::GetSize([Out] CA_D2D1_SIZE_F^% Param_Out_Size) { //Variaveis a serem utilizadas. Utilidades Util; D2D1_SIZE_F OutSizeF; //Chama o método para realizar a operação. OutSizeF = PonteiroTrabalho->GetSize(); //Converte e define no parametro de saida. Param_Out_Size = Util.ConverterD2D1_SIZE_FUnmanagedToManaged(&OutSizeF); } /// <summary> /// Obtém o rótulo(Tags) para operações de desenho subsequentes. /// </summary> /// <param name="Param_Out_Tag1">Retorna o primeiro rótulo para operações de desenho subsequentes.</param> /// <param name="Param_Out_Tag2">Retorna o segundo rótulo para operações de desenho subsequentes.</param> void CarenD2D1DCRenderTarget::GetTags( [Out] UInt64% Param_Out_Tag1, [Out] UInt64% Param_Out_Tag2) { //Variaveis a serem utilizadas. UINT64 OutTag1; UINT64 OutTag2; //Chama o método para realizar a operação. PonteiroTrabalho->GetTags(&OutTag1, &OutTag2); //Define nos parametros de saida. Param_Out_Tag1 = OutTag1; Param_Out_Tag2 = OutTag2; } /// <summary> /// Obtém o modo antialiasing atual para operações de desenho de texto e glifo(Glyph). /// </summary> /// <param name="Param_Out_TextAntialiasMode">Retorna o modo antialiasing atual para operações de desenho de texto e glifo(Glyph).</param> void CarenD2D1DCRenderTarget::GetTextAntialiasMode([Out] CA_D2D1_TEXT_ANTIALIAS_MODE% Param_Out_TextAntialiasMode) { //Variaveis a serem utilizadas. D2D1_TEXT_ANTIALIAS_MODE OutTextAliasMode; //Chama o método para realizar a operação. OutTextAliasMode = PonteiroTrabalho->GetTextAntialiasMode(); //Converte e define no parametro de saida. Param_Out_TextAntialiasMode = static_cast<CA_D2D1_TEXT_ANTIALIAS_MODE>(OutTextAliasMode); } /// <summary> /// Recupera as opções de renderização de texto atual do alvo. /// </summary> /// <param name="Param_Out_TextRenderingParams">Retorna a interface (IDWriteRenderingParams) que contém um ponteiro para as opções de renderização de texto atuais do destino. O usuário deve inicializar a interface antes de chamar este método.</param> void CarenD2D1DCRenderTarget::GetTextRenderingParams(ICaren^ Param_Out_TextRenderingParams) { //Variaveis a serem utilizadas. IDWriteRenderingParams* pDWriteRendParams = NULL; //Chama o método para realizar a operação. PonteiroTrabalho->GetTextRenderingParams(&pDWriteRendParams); //Define na interface de destino no parametro. Param_Out_TextRenderingParams->AdicionarPonteiro(pDWriteRendParams); } /// <summary> /// Obtém a transformação atual do alvo render. /// </summary> /// <param name="Param_Out_Transform">Retorna a transformação atual do alvo de renderização.</param> void CarenD2D1DCRenderTarget::GetTransform([Out] CA_D2D1_MATRIX_3X2_F^% Param_Out_Transform) { //Variaveis a serem utilizadas. Utilidades Util; D2D1_MATRIX_3X2_F OutMatrix = { }; //Chama o método para realizar a operação. PonteiroTrabalho->GetTransform(&OutMatrix); //Converte e define no parametro de saida. Param_Out_Transform = Util.ConverterD2D1_MATRIX_3X2_FUnmanagedToManaged(&OutMatrix); } /// <summary> /// Indica se o alvo de renderização suporta as propriedades especificadas. /// Este método não avalia as configurações de DPI especificadas pelo parâmetro (Param_ProppriedadesRenderTarget). /// </summary> /// <param name="Param_ProppriedadesRenderTarget">As propriedades de destino de renderização para testar.</param> /// <param name="Param_Out_Suporta">Retorna um valor Booleano TRUE se as propriedades de destino de renderização especificadas forem suportadas por este alvo de renderização; caso contrário, FALSO.</param> void CarenD2D1DCRenderTarget::IsSupported( CA_D2D1_RENDER_TARGET_PROPERTIES^ Param_ProppriedadesRenderTarget, [Out] Boolean% Param_Out_Suporta) { //Variaveis a serem utilizadas. Utilidades Util; D2D1_RENDER_TARGET_PROPERTIES* pRenderTargetProps = NULL; BOOL IsSuported = FALSE; //Converte a estrutura. pRenderTargetProps = Util.ConverterD2D1_RENDER_TARGET_PROPERTIESManagedToUnmanaged(Param_ProppriedadesRenderTarget); //Chama o método para realizar a operação. IsSuported = PonteiroTrabalho->IsSupported(pRenderTargetProps); //Define no parametro de saida. Param_Out_Suporta = IsSuported ? true : false; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pRenderTargetProps); } /// <summary> /// Remove o último clipe alinhado ao eixo do alvo de renderização. Depois que este método é chamado, o clipe não é mais aplicado às operações de desenho subsequentes. /// PopAxisAlignedClip deve ser chamado uma vez para cada chamada para PushAxisAlignedClip. /// Um par PushAxisAlignedClip/PopAxisAlignedClip pode ocorrer ao redor ou dentro de um par PushLayer/PopLayer, mas pode não se sobrepor. Por exemplo, uma sequência PushAxisAlignedClip, PushLayer, PopLayer, /// PopAxisAlignedClip é válida, mas uma sequência PushAxisAlignedClip, PushLayer, PopAxisAlignedClip, PopLayer não é. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como PopAxisAlignedClip) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> void CarenD2D1DCRenderTarget::PopAxisAlignedClip() { //Chama o método para realizar a operação. PonteiroTrabalho->PopAxisAlignedClip(); } /// <summary> /// Interrompe o redirecionamento das operações de desenho para a camada especificada pela última chamada do PushLayer. /// Um PopLayer deve corresponder a uma chamada pushlayer anterior. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como PopLayer) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> void CarenD2D1DCRenderTarget::PopLayer() { //Chama o método para realizar a operação. PonteiroTrabalho->PopLayer(); } /// <summary> /// Especifica um retângulo ao qual todas as operações de desenho subsequentes são cortadas. /// O PushAxisAlignedClip e o PopAxisAlignedClip devem coincidir. Caso contrário, o estado de erro está definido. Para que o alvo de renderização continue recebendo novos comandos, você pode chamar /// Flush para limpar o erro. /// Um par PushAxisAlignedClip e PopAxisAlignedClip pode ocorrer em torno ou dentro de um PushLayer e PopLayer, mas não pode se sobrepor. Por exemplo, a sequência de PushAxisAlignedClip, PushLayer, /// PopLayer, PopAxisAlignedClip é válida, mas a sequência de PushAxisAlignedClip, PushLayer, PopAxisAlignedClip, PopLayer é inválida. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como PushAxisAlignedClip) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_ClipRect">O tamanho e a posição da área de recorte, em pixels independentes do dispositivo.</param> /// <param name="Param_AntialiasMode">O modo antialiasing que é usado para desenhar as bordas das retagens de clipe que têm limites de subpixel, e para misturar o clipe com o conteúdo da cena. A mistura /// é realizada uma vez quando o método PopAxisAlignedClip é chamado, e não se aplica a cada primitivo dentro da camada.</param> void CarenD2D1DCRenderTarget::PushAxisAlignedClip( CA_D2D1_RECT_F^ Param_ClipRect, CA_D2D1_ANTIALIAS_MODE Param_AntialiasMode) { //Variaveis a serem utilizadas. Utilidades Util; D2D1_RECT_F* pClipRect = NULL; D2D1_ANTIALIAS_MODE AliasMode = static_cast<D2D1_ANTIALIAS_MODE>(Param_AntialiasMode); //Converte a estrutura. pClipRect = Util.ConverterD2D1_RECT_FManagedToUnmanaged(Param_ClipRect); //Chama o método para realizar a operação. PonteiroTrabalho->PushAxisAlignedClip(pClipRect, AliasMode); //Libera a memória para a estrutura. DeletarEstruturaSafe(&pClipRect); } /// <summary> /// Adicione a camada especificada ao destino renderização para que ela receba todas as operações de desenho subsequentes até que o PopLayer seja chamado. /// O método PushLayer permite que um chamador comece a redirecionar a renderização para uma camada. Todas as operações de renderização são válidas em uma camada. A localização da camada é afetada /// pela transformação mundial definida na meta de renderização. /// Cada PushLayer deve ter uma chamada PopLayer correspondente. Se houver mais chamadas do PopLayer do que chamadas PushLayer, o alvo de renderização será colocado em um estado de erro. Se flush /// for chamado antes de todas as camadas pendentes serem estouradas, o alvo de renderização será colocado em um estado de erro e um erro será retornado. O estado de erro pode ser liberado por uma chamada para EndDraw. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como PushLayer) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_ParametrosLayer">Os limites de conteúdo, máscara geométrica, opacidade, máscara de opções de opções de opções antialiasing para a camada.</param> /// <param name="Param_Layer">A camada que recebe operações de desenho subsequentes. Começando pelo Windows 8, este parâmetro é opcional. Se uma camada não for especificada, o Direct2D gerencia /// automaticamente o recurso de camada.</param> void CarenD2D1DCRenderTarget::PushLayer( CA_D2D1_LAYER_PARAMETERS^ Param_ParametrosLayer, ICarenD2D1Layer^ Param_Layer) { //Variaveis a serem utilizadas. Utilidades Util; D2D1_LAYER_PARAMETERS* pLayerParams = NULL; ID2D1Layer* pLayer = NULL; //Pode ser NULO. //Converte a estrutura. pLayerParams = Util.ConverterD2D1_LAYER_PARAMETERSManagedToUnmanaged(Param_ParametrosLayer); //Verifica se forneceu a camada if (ObjetoGerenciadoValido(Param_Layer)) { //Recupera o ponteiro para a interface da Layer RecuperarPonteiroCaren(Param_Layer, &pLayer); } //Chama o método para realizar a operação. PonteiroTrabalho->PushLayer(pLayerParams, pLayer); //Libera a memória para a estrutura. DeletarEstruturaSafe(&pLayerParams); } /// <summary> /// Define o estado de desenho do alvo de renderização ao do ID2D1DrawingStateBlock especificado. /// </summary> /// <param name="Param_DrawingStateBlock">O novo estado de desenho do alvo render.</param> CarenResult CarenD2D1DCRenderTarget::RestoreDrawingState(ICarenD2D1DrawingStateBlock^ Param_DrawingStateBlock) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. ID2D1DrawingStateBlock* pStateBlock = NULL; //Recupera o ponteiro para a interface da StateBlock Resultado = RecuperarPonteiroCaren(Param_DrawingStateBlock, &pStateBlock); //Sai do método em caso de erro SairOnError(Resultado); //Chama o método para realizar a operação. PonteiroTrabalho->RestoreDrawingState(pStateBlock); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Salva o estado de desenho atual para o ID2D1DrawingStateBlock especificado. /// </summary> /// <param name="Param_DrawingStateBlock">Retorna uma interface para o estado de desenho atual do alvo de renderização. Este parâmetro deve ser inicializado antes de passá-lo para o método.</param> CarenResult CarenD2D1DCRenderTarget::SaveDrawingState(ICarenD2D1DrawingStateBlock^ Param_DrawingStateBlock) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. ID2D1DrawingStateBlock* pStateBlock = NULL; //Recupera o ponteiro para a interface da StateBlock Resultado = RecuperarPonteiroCaren(Param_DrawingStateBlock, &pStateBlock); //Sai do método em caso de erro SairOnError(Resultado); //Chama o método para realizar a operação. PonteiroTrabalho->SaveDrawingState(pStateBlock); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Define o modo de antialiasing do alvo de renderização. O modo antialiasing aplica-se a todas as operações de desenho subsequentes, excluindo as operações de desenho de texto e glifo(Glyph). /// Para especificar o modo antialiasing para operações de texto e glifos(Glyph), use o método SetTextAntialiasMode. /// </summary> /// <param name="Param_AntialiasMode">O modo antialiasing para futuras operações de desenho.</param> void CarenD2D1DCRenderTarget::SetAntialiasMode(CA_D2D1_ANTIALIAS_MODE Param_AntialiasMode) { //Chama o método para realizar a operação. PonteiroTrabalho->SetAntialiasMode(static_cast<D2D1_ANTIALIAS_MODE>(Param_AntialiasMode)); } /// <summary> /// Define os pontos por polegada (DPI) do alvo de renderização. /// Este método especifica o mapeamento do espaço pixel para o espaço independente do dispositivo para o alvo de renderização. Se tanto o DpiX quanto o DpiY forem 0, o DPI do sistema de leitura /// de fábrica será escolhido. Se um parâmetro for zero e o outro não especificado, o DPI não será alterado. /// Para ICarenD2D1HwndRenderTarget, o DPI é padrão para o DPI mais recentemente do sistema de leitura de fábrica. O valor padrão para todas as outras metas de renderização é de 96 DPI. /// </summary> /// <param name="Param_DpiX">Um valor maior ou igual a zero que especifica o DPI horizontal do alvo de renderização.</param> /// <param name="Param_DpiY">Um valor maior ou igual a zero que especifica o DPI vertical do alvo de renderização.</param> void CarenD2D1DCRenderTarget::SetDpi( float Param_DpiX, float Param_DpiY) { //Chama o método para realizar a operação. PonteiroTrabalho->SetDpi(Param_DpiX, Param_DpiY); } /// <summary> /// Especifica um rótulo(Tag) para operações de desenho subsequentes. /// As etiquetas(Tags) especificadas por este método são impressas por mensagens de erro depuração. Se nenhuma tag for definida, o valor padrão de cada tag é 0. /// </summary> /// <param name="Param_Tag1">Um rótulo para aplicar às operações de desenho subsequentes.</param> /// <param name="Param_Tag2">Um rótulo para aplicar às operações de desenho subsequentes.</param> void CarenD2D1DCRenderTarget::SetTags( UInt64 Param_Tag1, UInt64 Param_Tag2) { //Chama o método para realizar a operação. PonteiroTrabalho->SetTags(Param_Tag1, Param_Tag2); } /// <summary> /// Especifica o modo antialiasing a ser usado para operações subsequentes de desenho de texto e glifo(Glyph). /// </summary> /// <param name="Param_TextAntialiasMode">O modo antialiasing para usar para operações subsequentes de desenho de texto e glifo(Glyph).</param> void CarenD2D1DCRenderTarget::SetTextAntialiasMode(CA_D2D1_TEXT_ANTIALIAS_MODE Param_TextAntialiasMode) { //Chama o método para realizar a operação. PonteiroTrabalho->SetTextAntialiasMode(static_cast<D2D1_TEXT_ANTIALIAS_MODE>(Param_TextAntialiasMode)); } /// <summary> /// Especifica as opções de renderização de texto a serem aplicadas a todas as operações subsequentes de desenho de texto e glifo(Glyph). /// Se as configurações especificadas por textRenderingParams forem incompatíveis com o modo antialiasing de texto do alvo de renderização (especificado por SetTextAntialiasMode), as operações /// subsequentes de desenho de texto e glifo(Glyph) falharão e colocarão o alvo de renderização em um estado de erro. /// </summary> /// <param name="Param_TextRenderingParams">Uma interface(IDWriteRenderingParams) para as opções de renderização de texto a serem aplicadas a todas as operações subsequentes de desenho /// de texto e glifoGlyph); NULO para limpar as opções atuais de renderização de texto.</param> CarenResult CarenD2D1DCRenderTarget::SetTextRenderingParams(ICaren^ Param_TextRenderingParams) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Variaveis a serem utilizadas. IDWriteRenderingParams* pDwriteParams = NULL; //Recupera o ponteiro para a interface da StateBlock Resultado = RecuperarPonteiroCaren(Param_TextRenderingParams, &pDwriteParams); //Sai do método em caso de erro SairOnError(Resultado); //Chama o método para realizar a operação. PonteiroTrabalho->SetTextRenderingParams(pDwriteParams); Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Aplica a transformação especificada ao alvo de renderização, substituindo a transformação existente. Todas as operações subsequentes de desenho ocorrem no espaço transformado. /// </summary> /// <param name="Param_Transform">A transformação para aplicar ao alvo de renderização.</param> void CarenD2D1DCRenderTarget::SetTransform(CA_D2D1_MATRIX_3X2_F^ Param_Transform) { //Variaveis a serem utilizadas. Utilidades Util; D2D1_MATRIX_3X2_F* pMatrix = NULL; //Converte a estrutura. pMatrix = Util.ConverterD2D1_MATRIX_3X2_FManagedToUnmanaged(Param_Transform); //Chama o método para realizar a operação. PonteiroTrabalho->SetTransform(pMatrix); //Libera a memória para a estrutura DeletarEstruturaSafe(&pMatrix); } // Métodos da interface proprietária(ICarenD2D1Resource) /// <summary> /// Recupera a fábrica associada a este recurso. /// </summary> /// <param name="Param_Out_Factory">Retorna uma interface(ICarenD2D1Factory) que contém um ponteiro para a fabrica que criou esse recurso. O usuário deve inicializar a interface antes de chamar este método.</param> void CarenD2D1DCRenderTarget::GetFactory(ICaren^ Param_Out_Factory) { //Variaveis a serem utilizadas. ID2D1Factory* pFactory = NULL; //Variavel de resultados. CarenResult Resultado; //Chama o método para realizar a operação. PonteiroTrabalho->GetFactory(&pFactory); //Verifica se o ponteiro é válido if (!ObjetoValido(pFactory)) Sair; //Adiciona o ponteiro na interface informada. Resultado = Param_Out_Factory->AdicionarPonteiro(pFactory); //Verifica o resultado da operação. if (Resultado.StatusCode != ResultCode::SS_OK) { //Libera o ponteiro recuperado anteriormente. pFactory->Release(); pFactory = NULL; //Chama uma execeção para indicar o erro. throw gcnew Exception(String::Format("Ocorreu uma falha ao definir o ponteiro nativo na interface gerenciada. Código de erro > {0}", Resultado.StatusCode)); } Done:; }
132,136
48,706
/* ============================================================================== This file contains the basic framework code for a JUCE plugin editor. ============================================================================== */ #include "PluginProcessor.h" #include "PluginEditor.h" //============================================================================== DiodeAmplifierAudioProcessorEditor::DiodeAmplifierAudioProcessorEditor (DiodeAmplifierAudioProcessor& p) : AudioProcessorEditor (&p), audioProcessor (p) { shadowProperties.radius = 24; shadowProperties.offset = juce::Point<int> (-1, 12); shadowProperties.colour = juce::Colours::black.withAlpha(0.25f); dialShadow.setShadowProperties (shadowProperties); sliders.reserve(6); sliders = { &inputSlider, &driveSlider, &lowSlider, &midSlider, &highSlider, &outputSlider }; labels.reserve(6); labels = { &inputLabel, &driveLabel, &lowLabel, &midLabel, &highLabel, &outputLabel }; labelTexts.reserve(6); labelTexts = { inputSliderLabelText, driveSliderLabelText, lowSliderLabelText, midSliderLabelText, highSliderLabelText, outputSliderLabelText }; inputSlider.setLookAndFeel(&customDial); driveSlider.setLookAndFeel(&customDial); outputSlider.setLookAndFeel(&customDial); lowSlider.setLookAndFeel(&customDial2); midSlider.setLookAndFeel(&customDial2); highSlider.setLookAndFeel(&customDial2); for (auto i = 0; i < sliders.size(); i++) { addAndMakeVisible(sliders[i]); sliders[i]->setSliderStyle(juce::Slider::SliderStyle::RotaryVerticalDrag); sliders[i]->setTextBoxStyle(juce::Slider::TextBoxBelow, false, 64, 32); sliders[i]->setColour(0x1001400, juce::Colour::fromFloatRGBA(1, 1, 1, 0.5f)); sliders[i]->setColour(0x1001700, juce::Colour::fromFloatRGBA(1, 1, 1, 0.0f)); sliders[i]->setColour(0x1001500, juce::Colour::fromFloatRGBA(0, 0, 0, 0.25f)); sliders[i]->setComponentEffect(&dialShadow); sliders[i]->setRange(-24.0, 24.0, 0.25); sliders[i]->setDoubleClickReturnValue(true, 0.0); } driveSlider.setRange(0.0, 10.0, 0.25); lowSlider.setRange(-6.0, 6.0, 0.25); midSlider.setRange(-6.0, 6.0, 0.25); highSlider.setRange(-6.0, 6.0, 0.25); inputSliderAttach = std::make_unique<juce::AudioProcessorValueTreeState::SliderAttachment>(audioProcessor.treeState, inputGainSliderId, inputSlider); driveSliderAttach = std::make_unique<juce::AudioProcessorValueTreeState::SliderAttachment>(audioProcessor.treeState, driveSliderId, driveSlider); lowSliderAttach = std::make_unique<juce::AudioProcessorValueTreeState::SliderAttachment>(audioProcessor.treeState, lowSliderId, lowSlider); midSliderAttach = std::make_unique<juce::AudioProcessorValueTreeState::SliderAttachment>(audioProcessor.treeState, midSliderId, midSlider); highSliderAttach = std::make_unique<juce::AudioProcessorValueTreeState::SliderAttachment>(audioProcessor.treeState, highSliderId, highSlider); outputSliderAttach = std::make_unique<juce::AudioProcessorValueTreeState::SliderAttachment>(audioProcessor.treeState, outputGainSliderId, outputSlider); for (auto i = 0; i < labels.size(); i++) { addAndMakeVisible(labels[i]); labels[i]->setText(labelTexts[i], juce::dontSendNotification); labels[i]->setJustificationType(juce::Justification::centred); labels[i]->setColour(0x1000281, juce::Colour::fromFloatRGBA(1, 1, 1, 0.25f)); labels[i]->attachToComponent(sliders[i], false); } addAndMakeVisible(windowBorder); windowBorder.setText("Ignorant Diode Amplifier"); windowBorder.setColour(0x1005400, juce::Colour::fromFloatRGBA(1, 1, 1, 0.25f)); windowBorder.setColour(0x1005410, juce::Colour::fromFloatRGBA(1, 1, 1, 0.25f)); addAndMakeVisible(&brightButton); brightButton.setButtonText("Bright"); brightButton.setClickingTogglesState(true); brightButtonAttach = std::make_unique<juce::AudioProcessorValueTreeState::ButtonAttachment>(audioProcessor.treeState, brightId, brightButton); brightButton.setColour(0x1000100, juce::Colours::whitesmoke.darker(1.0).withAlpha(1.0f)); brightButton.setColour(0x1000c00, juce::Colour::fromFloatRGBA(0, 0, 0, 0)); brightButton.setColour(0x1000101, juce::Colours::lightgoldenrodyellow.darker(0.2f)); brightButton.setColour(0x1000102, juce::Colours::black.brighter(0.1)); brightButton.setColour(0x1000103, juce::Colours::black.brighter(0.1)); addAndMakeVisible(&cabButton); cabButton.setButtonText("Load IR"); cabButton.setColour(0x1000100, juce::Colours::whitesmoke.darker(1.0).withAlpha(1.0f)); cabButton.setColour(0x1000c00, juce::Colour::fromFloatRGBA(0, 0, 0, 0)); cabButton.setColour(0x1000101, juce::Colours::lightgoldenrodyellow.darker(0.2f)); cabButton.setColour(0x1000102, juce::Colours::black.brighter(0.1)); cabButton.setColour(0x1000103, juce::Colours::black.brighter(0.1)); addAndMakeVisible(&cabToggleButton); cabToggleButton.setClickingTogglesState(true); cabToggleButton.setToggleState(true, juce::dontSendNotification); cabToggleButton.setButtonText("Cab On"); cabToggleAttach = std::make_unique<juce::AudioProcessorValueTreeState::ButtonAttachment>(audioProcessor.treeState, cabId, cabToggleButton); cabToggleButton.setColour(0x1000100, juce::Colours::whitesmoke.darker(1.0).withAlpha(1.0f)); cabToggleButton.setColour(0x1000c00, juce::Colour::fromFloatRGBA(0, 0, 0, 0)); cabToggleButton.setColour(0x1000101, juce::Colours::lightgoldenrodyellow.darker(0.2f)); cabToggleButton.setColour(0x1000102, juce::Colours::black.brighter(0.1)); cabToggleButton.setColour(0x1000103, juce::Colours::black.brighter(0.1)); addAndMakeVisible(&resetIRButton); resetIRButton.setButtonText("Reset IR"); resetIRButton.setColour(0x1000100, juce::Colours::whitesmoke.darker(1.0).withAlpha(1.0f)); resetIRButton.setColour(0x1000c00, juce::Colour::fromFloatRGBA(0, 0, 0, 0)); resetIRButton.setColour(0x1000101, juce::Colours::lightgoldenrodyellow.darker(0.2f)); resetIRButton.setColour(0x1000102, juce::Colours::black.brighter(0.1)); resetIRButton.setColour(0x1000103, juce::Colours::black.brighter(0.1)); setCabButtonProps(); setSize (711, 500); } DiodeAmplifierAudioProcessorEditor::~DiodeAmplifierAudioProcessorEditor() { inputSlider.setLookAndFeel(nullptr); driveSlider.setLookAndFeel(nullptr); lowSlider.setLookAndFeel(nullptr); midSlider.setLookAndFeel(nullptr); highSlider.setLookAndFeel(nullptr); outputSlider.setLookAndFeel(nullptr); } //============================================================================== void DiodeAmplifierAudioProcessorEditor::paint (juce::Graphics& g) { //Image layer from Illustrator pluginBackground = juce::ImageCache::getFromMemory(BinaryData::PluginBackground1_png, BinaryData::PluginBackground1_pngSize); g.drawImageWithin(pluginBackground, 0, 0, AudioProcessorEditor::getWidth(), AudioProcessorEditor::getHeight(), juce::RectanglePlacement::stretchToFit); // Background dark-maker // juce::Rectangle<float> backgroundDarker; // backgroundDarker.setBounds(0, 0, AudioProcessorEditor::getWidth(), AudioProcessorEditor::getHeight()); // g.setColour(juce::Colour::fromFloatRGBA(0.09f, 0.10f, 0.12f, 0.65f)); // g.fillRect(backgroundDarker); // Header rectangle juce::Rectangle<float> header; header.setBounds(0, 0, AudioProcessorEditor::getWidth(), AudioProcessorEditor::getHeight() * 0.13f); g.setColour(juce::Colours::black.withAlpha(0.5f)); g.fillRect(header); // Set header text g.setFont (16.0f); g.setColour (juce::Colours::white.withAlpha(0.25f)); g.drawFittedText ("Algorithms by Landon Viator", 12, AudioProcessorEditor::getHeight() * 0.05, AudioProcessorEditor::getWidth(), AudioProcessorEditor::getHeight(), juce::Justification::topLeft, 1); // Logo mLogo = juce::ImageCache::getFromMemory(BinaryData::landon5504_png, BinaryData::landon5504_pngSize); g.drawImageWithin(mLogo, AudioProcessorEditor::getWidth() * 0.4f, AudioProcessorEditor::getHeight() * 0.025, AudioProcessorEditor::getHeight() * 0.08f * 4.58, AudioProcessorEditor::getHeight() * 0.08f, juce::RectanglePlacement::centred); } void DiodeAmplifierAudioProcessorEditor::resized() { //Master bounds object juce::Rectangle<int> bounds = getLocalBounds(); auto sliderSize {3.5}; //first column of gui juce::FlexBox flexboxColumnOne; flexboxColumnOne.flexDirection = juce::FlexBox::Direction::row; flexboxColumnOne.flexWrap = juce::FlexBox::Wrap::noWrap; flexboxColumnOne.alignContent = juce::FlexBox::AlignContent::center; juce::Array<juce::FlexItem> itemArrayColumnOne; itemArrayColumnOne.add(juce::FlexItem(bounds.getWidth() / sliderSize, bounds.getHeight() / sliderSize, inputSlider).withMargin(juce::FlexItem::Margin(0, 0, 0, 0))); itemArrayColumnOne.add(juce::FlexItem(bounds.getWidth() / sliderSize, bounds.getHeight() / sliderSize, driveSlider).withMargin(juce::FlexItem::Margin(0, 0, 0, 0))); itemArrayColumnOne.add(juce::FlexItem(bounds.getWidth() / sliderSize, bounds.getHeight() / sliderSize, outputSlider).withMargin(juce::FlexItem::Margin(0, 0, 0, 0))); flexboxColumnOne.items = itemArrayColumnOne; flexboxColumnOne.performLayout(bounds.removeFromTop(bounds.getHeight() - 72)); /* ============================================================================ */ lowSlider.setBounds(inputSlider.getX(), inputSlider.getY() + inputSlider.getHeight() + 32, inputSlider.getWidth(), inputSlider.getHeight()); midSlider.setBounds(driveSlider.getX(), driveSlider.getY() + driveSlider.getHeight() + 32, driveSlider.getWidth(), driveSlider.getHeight()); highSlider.setBounds(outputSlider.getX(), outputSlider.getY() + outputSlider.getHeight() + 32, outputSlider.getWidth(), outputSlider.getHeight()); brightButton.setBounds(outputSlider.getX() + outputSlider.getWidth() - 24, outputSlider.getY() * 1.5, 72, 32); cabButton.setBounds(brightButton.getX(), brightButton.getY() + brightButton.getHeight(), 72, 32); cabToggleButton.setBounds(cabButton.getX(), cabButton.getY() + cabButton.getHeight(), 72, 32); resetIRButton.setBounds(cabToggleButton.getX(), cabToggleButton.getY() + cabToggleButton.getHeight(), 72, 32); // Window border bounds windowBorder.setBounds ( 16, AudioProcessorEditor::getHeight() * 0.16, AudioProcessorEditor::getWidth() * 0.95, AudioProcessorEditor::getHeight() * .8 ); }
11,062
3,913
#include<iostream> #include <ctime> #include<string> using namespace std; void encrypt( char [ ] ); // prototypes of functions used in the code void decrypt( char * ePtr ); int i=1; // for nodeNumber (unique incremental integral value) // structure of node struct node { string data; // information int nodeNumber; // unique incremental value unint32_t nodeId; // 32 bit id uniquely identifies a node struct node* referenceNodeId; // address of parent node vector<string> childReferenceNodeId; // containing all child nodes string genesisReferenceNodeId; // root node address string HashValue; // hash of complete structure time_t now; // current date/time based on current system }; struct Node* new_node(string key, unint32_t uni_id) { struct Node* temp = new node; // creating new node //filling all parameters temp->data = key; temp->referenceNodeId = NULL; // initially keep the parent node null temp->nodeNumber = i+1; // serial no. (unique incremental value) fill(temp->childReferenceNodeId.begin(), temp->childReferenceNodeId.end(), ""); // initially keep all child node as NULL temp->nodeId = uni_id; temp->now = time(0); temp->HashValue = myhash(node const& s); return temp; }; // function for computing hash of complete structure (used in boost) std::size_t myhash(node const& s) { std::size_t res = 0; hash_combine(res,s.now); hash_combine(res,s.data); hash_combine(res,s.nodeNumber); hash_combine(res,s.nodeId); hash_combine(res,s.referenceNodeId); hash_combine(res,s.childReferenceNodeId); hash_combine(res,s.genesisReferenceNodeId); return res; } int main() { node obj; uint32_t id = reinterpret_cast<uint32_t>(&obj); //32 bit id uniquely identifies a node int owner_id; // assuming owner id to be within integer range i.e -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647 string name,info,all; float val; cout<<"Enter owner id"; cin>>owner_id; cout<<"Enter value in floating point integer fixed upto 2 decimal places"; // assuming the value entered will be upto 2 decimal places only otherwise can use setprecision function cin>>val; cout<<"Enter owner name"; getline(cin,name); all = name + to_string(owner_id) + to_string(val); // to_string defined in <string> headerfile. converts an integer into string info = encrypt(all); struct node* np = new_node(info,id); // calling new_node } //for encrypting data void encrypt (char e[] ) { for( int i=0; e[i] != '\0'; ++i ) ++e[i]; } //for decrypting data void decrypt( char * ePtr ) { for( ; * ePtr != '\0'; ==* ePtr ) --(* ePtr); }
2,679
883
//:: pd_prefix = "p4_pd_" + p4_prefix + "_" //:: api_prefix = p4_prefix + "_" #include "p4_prefix.h" #include <iostream> #include <string.h> #include "pd/pd.h" #include <list> #include <map> #include <mutex> #include <thread> #include <condition_variable> #include <future> using namespace ::p4_pd_rpc; using namespace ::res_pd_rpc; namespace { __attribute__ ((unused)) void bytes_meter_spec_thrift_to_pd( const ${api_prefix}bytes_meter_spec_t &meter_spec, p4_pd_bytes_meter_spec_t *pd_meter_spec) { pd_meter_spec->cir_kbps = meter_spec.cir_kbps; pd_meter_spec->cburst_kbits = meter_spec.cburst_kbits; pd_meter_spec->pir_kbps = meter_spec.pir_kbps; pd_meter_spec->pburst_kbits = meter_spec.pburst_kbits; pd_meter_spec->meter_type = meter_spec.color_aware ? PD_METER_TYPE_COLOR_AWARE : PD_METER_TYPE_COLOR_UNAWARE; } __attribute__ ((unused)) void packets_meter_spec_thrift_to_pd( const ${api_prefix}packets_meter_spec_t &meter_spec, p4_pd_packets_meter_spec_t *pd_meter_spec) { pd_meter_spec->cir_pps = meter_spec.cir_pps; pd_meter_spec->cburst_pkts = meter_spec.cburst_pkts; pd_meter_spec->pir_pps = meter_spec.pir_pps; pd_meter_spec->pburst_pkts = meter_spec.pburst_pkts; pd_meter_spec->meter_type = meter_spec.color_aware ? PD_METER_TYPE_COLOR_AWARE : PD_METER_TYPE_COLOR_UNAWARE; } __attribute__ ((unused)) void bytes_meter_spec_pd_to_thrift( const p4_pd_bytes_meter_spec_t &pd_meter_spec, ${api_prefix}bytes_meter_spec_t *meter_spec) { meter_spec->cir_kbps = pd_meter_spec.cir_kbps; meter_spec->cburst_kbits = pd_meter_spec.cburst_kbits; meter_spec->pir_kbps = pd_meter_spec.pir_kbps; meter_spec->pburst_kbits = pd_meter_spec.pburst_kbits; meter_spec->color_aware = (pd_meter_spec.meter_type == PD_METER_TYPE_COLOR_AWARE); } __attribute__ ((unused)) void packets_meter_spec_pd_to_thrift( const p4_pd_packets_meter_spec_t &pd_meter_spec, ${api_prefix}packets_meter_spec_t *meter_spec) { meter_spec->cir_pps = pd_meter_spec.cir_pps; meter_spec->cburst_pkts = pd_meter_spec.cburst_pkts; meter_spec->pir_pps = pd_meter_spec.pir_pps; meter_spec->pburst_pkts = pd_meter_spec.pburst_pkts; meter_spec->color_aware = (pd_meter_spec.meter_type == PD_METER_TYPE_COLOR_AWARE); } } // namespace //:: def get_direct_parameter_specs(t, api_prefix): //:: specs = [] //:: if t.direct_meters: //:: m = t.direct_meters //:: if m.unit == m.MeterUnit.PACKETS: //:: specs += ["const " + api_prefix + "packets_meter_spec_t &" + m.name + "_spec"] //:: else: //:: specs += ["const " + api_prefix + "bytes_meter_spec_t &" + m.name + "_spec"] //:: #endif //:: #endif //:: return specs //:: #enddef class ${p4_prefix}Handler : virtual public ${p4_prefix}If { private: class CbWrap { CbWrap() {} int wait() { std::unique_lock<std::mutex> lock(cb_mutex); while(cb_status == 0) { cb_condvar.wait(lock); } return 0; } void notify() { std::unique_lock<std::mutex> lock(cb_mutex); assert(cb_status == 0); cb_status = 1; cb_condvar.notify_one(); } static void cb_fn(int device_id, void *cookie) { (void) device_id; CbWrap *inst = static_cast<CbWrap *>(cookie); inst->notify(); } CbWrap(const CbWrap &other) = delete; CbWrap &operator=(const CbWrap &other) = delete; CbWrap(CbWrap &&other) = delete; CbWrap &operator=(CbWrap &&other) = delete; private: std::mutex cb_mutex{}; std::condition_variable cb_condvar{}; int cb_status{0}; }; public: ${p4_prefix}Handler() { } // Table entry add functions //:: for t_name, t in tables.items(): //:: t_type = t.type_ //:: if t_type != TableType.SIMPLE: continue //:: t_name = get_c_name(t_name) //:: match_type = t.match_type //:: has_match_spec = len(t.key) > 0 //:: for a_name, a in t.actions.items(): //:: a_name = get_c_name(a_name) //:: has_action_spec = len(a.runtime_data) > 0 //:: params = ["const SessionHandle_t sess_hdl", //:: "const DevTarget_t &dev_tgt"] //:: if has_match_spec: //:: params += ["const " + api_prefix + t_name + "_match_spec_t &match_spec"] //:: #endif //:: if match_type in {MatchType.TERNARY, MatchType.RANGE}: //:: params += ["const int32_t priority"] //:: #endif //:: if has_action_spec: //:: params += ["const " + api_prefix + a_name + "_action_spec_t &action_spec"] //:: #endif //:: if t.support_timeout: //:: params += ["const int32_t ttl"] //:: #endif //:: params += get_direct_parameter_specs(t, api_prefix) //:: param_str = ", ".join(params) //:: name = t_name + "_table_add_with_" + a_name //:: pd_name = pd_prefix + name EntryHandle_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; //:: if has_match_spec: ${pd_prefix}${t_name}_match_spec_t pd_match_spec; //:: match_params = gen_match_params(t.key) //:: for name, width in match_params: //:: name = get_c_name(name) //:: if width <= 4: pd_match_spec.${name} = match_spec.${name}; //:: else: memcpy(pd_match_spec.${name}, match_spec.${name}.c_str(), ${width}); //:: #endif //:: #endfor //:: #endif //:: if has_action_spec: ${pd_prefix}${a_name}_action_spec_t pd_action_spec; //:: action_params = gen_action_params(a.runtime_data) //:: for name, _, width in action_params: //:: name = get_c_name(name) //:: if width <= 4: pd_action_spec.${name} = action_spec.${name}; //:: else: memcpy(pd_action_spec.${name}, action_spec.${name}.c_str(), ${width}); //:: #endif //:: #endfor //:: #endif p4_pd_entry_hdl_t pd_entry; //:: pd_params = ["sess_hdl", "pd_dev_tgt"] //:: if has_match_spec: //:: pd_params += ["&pd_match_spec"] //:: #endif //:: if match_type in {MatchType.TERNARY, MatchType.RANGE}: //:: pd_params += ["priority"] //:: #endif //:: if has_action_spec: //:: pd_params += ["&pd_action_spec"] //:: #endif //:: if t.support_timeout: //:: pd_params += ["(uint32_t)ttl"] //:: #endif //:: # direct parameter specs //:: if t.direct_meters: //:: m = t.direct_meters //:: unit_name = MeterUnit.to_str(m.unit) p4_pd_${unit_name}_meter_spec_t pd_${m.name}_spec; ${unit_name}_meter_spec_thrift_to_pd(${m.name}_spec, &pd_${m.name}_spec); //:: pd_params += ["&pd_" + m.name + "_spec"] //:: #endif //:: pd_params += ["&pd_entry"] //:: pd_param_str = ", ".join(pd_params) ${pd_name}(${pd_param_str}); return pd_entry; } //:: #endfor //:: #endfor // Table entry modify functions //:: for t_name, t in tables.items(): //:: t_type = t.type_ //:: if t_type != TableType.SIMPLE: continue //:: t_name = get_c_name(t_name) //:: for a_name, a in t.actions.items(): //:: a_name = get_c_name(a_name) //:: has_action_spec = len(a.runtime_data) > 0 //:: params = ["const SessionHandle_t sess_hdl", //:: "const int8_t dev_id", //:: "const EntryHandle_t entry"] //:: if has_action_spec: //:: params += ["const " + api_prefix + a_name + "_action_spec_t &action_spec"] //:: #endif //:: params += get_direct_parameter_specs(t, api_prefix) //:: param_str = ", ".join(params) //:: name = t_name + "_table_modify_with_" + a_name //:: pd_name = pd_prefix + name EntryHandle_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; //:: if has_action_spec: ${pd_prefix}${a_name}_action_spec_t pd_action_spec; //:: action_params = gen_action_params(a.runtime_data) //:: for name, _, width in action_params: //:: name = get_c_name(name) //:: if width <= 4: pd_action_spec.${name} = action_spec.${name}; //:: else: memcpy(pd_action_spec.${name}, action_spec.${name}.c_str(), ${width}); //:: #endif //:: #endfor //:: #endif //:: pd_params = ["sess_hdl", "dev_id", "entry"] //:: if has_action_spec: //:: pd_params += ["&pd_action_spec"] //:: #endif //:: # direct parameter specs //:: if t.direct_meters: //:: m = t.direct_meters //:: unit_name = MeterUnit.to_str(m.unit) p4_pd_${unit_name}_meter_spec_t pd_${m.name}_spec; ${unit_name}_meter_spec_thrift_to_pd(${m.name}_spec, &pd_${m.name}_spec); //:: pd_params += ["&pd_" + m.name + "_spec"] //:: #endif //:: pd_param_str = ", ".join(pd_params) return ${pd_name}(${pd_param_str}); } //:: #endfor //:: #endfor // Table entry delete functions //:: for t_name, t in tables.items(): //:: t_type = t.type_ //:: t_name = get_c_name(t_name) //:: name = t_name + "_table_delete" //:: pd_name = pd_prefix + name //:: params = ["const SessionHandle_t sess_hdl", //:: "const int8_t dev_id", //:: "const EntryHandle_t entry"] //:: param_str = ", ".join(params) int32_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; return ${pd_name}(sess_hdl, dev_id, entry); } //:: #endfor // set default action //:: for t_name, t in tables.items(): //:: t_type = t.type_ //:: if t_type != TableType.SIMPLE: continue //:: t_name = get_c_name(t_name) //:: for a_name, a in t.actions.items(): //:: a_name = get_c_name(a_name) //:: has_action_spec = len(a.runtime_data) > 0 //:: params = ["const SessionHandle_t sess_hdl", //:: "const DevTarget_t &dev_tgt"] //:: if has_action_spec: //:: params += ["const " + api_prefix + a_name + "_action_spec_t &action_spec"] //:: #endif //:: params += get_direct_parameter_specs(t, api_prefix) //:: param_str = ", ".join(params) //:: name = t_name + "_set_default_action_" + a_name //:: pd_name = pd_prefix + name int32_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; //:: if has_action_spec: ${pd_prefix}${a_name}_action_spec_t pd_action_spec; //:: action_params = gen_action_params(a.runtime_data) //:: for name, _, width in action_params: //:: name = get_c_name(name) //:: if width <= 4: pd_action_spec.${name} = action_spec.${name}; //:: else: memcpy(pd_action_spec.${name}, action_spec.${name}.c_str(), ${width}); //:: #endif //:: #endfor //:: #endif p4_pd_entry_hdl_t pd_entry; //:: pd_params = ["sess_hdl", "pd_dev_tgt"] //:: if has_action_spec: //:: pd_params += ["&pd_action_spec"] //:: #endif //:: # direct parameter specs //:: if t.direct_meters: //:: m = t.direct_meters //:: unit_name = MeterUnit.to_str(m.unit) p4_pd_${unit_name}_meter_spec_t pd_${m.name}_spec; ${unit_name}_meter_spec_thrift_to_pd(${m.name}_spec, &pd_${m.name}_spec); //:: pd_params += ["&pd_" + m.name + "_spec"] //:: #endif //:: pd_params += ["&pd_entry"] //:: pd_param_str = ", ".join(pd_params) return ${pd_name}(${pd_param_str}); // return pd_entry; } //:: #endfor //:: #endfor //:: name = "clean_all" //:: pd_name = pd_prefix + name int32_t ${name}(const SessionHandle_t sess_hdl, const DevTarget_t &dev_tgt) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; return ${pd_name}(sess_hdl, pd_dev_tgt); } // INDIRECT ACTION DATA AND MATCH SELECT //:: for act_prof_name, act_prof in act_profs.items(): //:: act_prof_name = get_c_name(act_prof_name) //:: for a_name, a in act_prof.actions.items(): //:: a_name = get_c_name(a_name) //:: has_action_spec = len(a.runtime_data) > 0 //:: params = ["const SessionHandle_t sess_hdl", //:: "const DevTarget_t &dev_tgt"] //:: if has_action_spec: //:: params += ["const " + api_prefix + a_name + "_action_spec_t &action_spec"] //:: #endif //:: param_str = ", ".join(params) //:: name = act_prof_name + "_add_member_with_" + a_name //:: pd_name = pd_prefix + name EntryHandle_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; //:: if has_action_spec: ${pd_prefix}${a_name}_action_spec_t pd_action_spec; //:: action_params = gen_action_params(a.runtime_data) //:: for name, _, width in action_params: //:: name = get_c_name(name) //:: if width <= 4: pd_action_spec.${name} = action_spec.${name}; //:: else: memcpy(pd_action_spec.${name}, action_spec.${name}.c_str(), ${width}); //:: #endif //:: #endfor //:: #endif p4_pd_mbr_hdl_t pd_mbr_hdl; //:: pd_params = ["sess_hdl", "pd_dev_tgt"] //:: if has_action_spec: //:: pd_params += ["&pd_action_spec"] //:: #endif //:: pd_params += ["&pd_mbr_hdl"] //:: pd_param_str = ", ".join(pd_params) ${pd_name}(${pd_param_str}); return pd_mbr_hdl; } //:: params = ["const SessionHandle_t sess_hdl", //:: "const int8_t dev_id", //:: "const MemberHandle_t mbr"] //:: if has_action_spec: //:: params += ["const " + api_prefix + a_name + "_action_spec_t &action_spec"] //:: #endif //:: param_str = ", ".join(params) //:: name = act_prof_name + "_modify_member_with_" + a_name //:: pd_name = pd_prefix + name EntryHandle_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; //:: if has_action_spec: ${pd_prefix}${a_name}_action_spec_t pd_action_spec; //:: action_params = gen_action_params(a.runtime_data) //:: for name, _, width in action_params: //:: name = get_c_name(name) //:: if width <= 4: pd_action_spec.${name} = action_spec.${name}; //:: else: memcpy(pd_action_spec.${name}, action_spec.${name}.c_str(), ${width}); //:: #endif //:: #endfor //:: #endif //:: pd_params = ["sess_hdl", "dev_id", "mbr"] //:: if has_action_spec: //:: pd_params += ["&pd_action_spec"] //:: #endif //:: pd_param_str = ", ".join(pd_params) return ${pd_name}(${pd_param_str}); } //:: #endfor //:: params = ["const SessionHandle_t sess_hdl", //:: "const int8_t dev_id", //:: "const MemberHandle_t mbr"] //:: param_str = ", ".join(params) //:: name = act_prof_name + "_del_member" //:: pd_name = pd_prefix + name int32_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; return ${pd_name}(sess_hdl, dev_id, mbr); } //:: if not act_prof.with_selector: continue //:: //:: params = ["const SessionHandle_t sess_hdl", //:: "const DevTarget_t &dev_tgt", //:: "const int16_t max_grp_size"] //:: param_str = ", ".join(params) //:: name = act_prof_name + "_create_group" //:: pd_name = pd_prefix + name GroupHandle_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; p4_pd_grp_hdl_t pd_grp_hdl; ${pd_name}(sess_hdl, pd_dev_tgt, max_grp_size, &pd_grp_hdl); return pd_grp_hdl; } //:: params = ["const SessionHandle_t sess_hdl", //:: "const int8_t dev_id", //:: "const GroupHandle_t grp"] //:: param_str = ", ".join(params) //:: name = act_prof_name + "_del_group" //:: pd_name = pd_prefix + name int32_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; return ${pd_name}(sess_hdl, dev_id, grp); } //:: params = ["const SessionHandle_t sess_hdl", //:: "const int8_t dev_id", //:: "const GroupHandle_t grp", //:: "const MemberHandle_t mbr"] //:: param_str = ", ".join(params) //:: name = act_prof_name + "_add_member_to_group" //:: pd_name = pd_prefix + name int32_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; return ${pd_name}(sess_hdl, dev_id, grp, mbr); } //:: params = ["const SessionHandle_t sess_hdl", //:: "const int8_t dev_id", //:: "const GroupHandle_t grp", //:: "const MemberHandle_t mbr"] //:: param_str = ", ".join(params) //:: name = act_prof_name + "_del_member_from_group" //:: pd_name = pd_prefix + name int32_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; return ${pd_name}(sess_hdl, dev_id, grp, mbr); } //:: params = ["const SessionHandle_t sess_hdl", //:: "const int8_t dev_id", //:: "const GroupHandle_t grp", //:: "const MemberHandle_t mbr"] //:: param_str = ", ".join(params) //:: name = act_prof_name + "_deactivate_group_member" //:: pd_name = pd_prefix + name int32_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; return 0; } //:: params = ["const SessionHandle_t sess_hdl", //:: "const int8_t dev_id", //:: "const GroupHandle_t grp", //:: "const MemberHandle_t mbr"] //:: param_str = ", ".join(params) //:: name = act_prof_name + "_reactivate_group_member" //:: pd_name = pd_prefix + name int32_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; return 0; } //:: #endfor //:: for t_name, t in tables.items(): //:: t_type = t.type_ //:: if t_type == TableType.SIMPLE: continue //:: t_name = get_c_name(t_name) //:: match_type = t.match_type //:: has_match_spec = len(t.key) > 0 //:: params = ["const SessionHandle_t sess_hdl", //:: "const DevTarget_t &dev_tgt"] //:: if has_match_spec: //:: params += ["const " + api_prefix + t_name + "_match_spec_t &match_spec"] //:: #endif //:: if match_type in {MatchType.TERNARY, MatchType.RANGE}: //:: params += ["const int32_t priority"] //:: #endif //:: params_wo = params + ["const MemberHandle_t mbr"] //:: param_str = ", ".join(params_wo) //:: name = t_name + "_add_entry" //:: pd_name = pd_prefix + name EntryHandle_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; //:: if has_match_spec: ${pd_prefix}${t_name}_match_spec_t pd_match_spec; //:: match_params = gen_match_params(t.key) //:: for name, width in match_params: //:: name = get_c_name(name) //:: if width <= 4: pd_match_spec.${name} = match_spec.${name}; //:: else: memcpy(pd_match_spec.${name}, match_spec.${name}.c_str(), ${width}); //:: #endif //:: #endfor //:: #endif p4_pd_entry_hdl_t pd_entry; //:: pd_params = ["sess_hdl", "pd_dev_tgt"] //:: if has_match_spec: //:: pd_params += ["&pd_match_spec"] //:: #endif //:: if match_type in {MatchType.TERNARY, MatchType.RANGE}: //:: pd_params += ["priority"] //:: #endif //:: pd_params += ["mbr", "&pd_entry"] //:: pd_param_str = ", ".join(pd_params) ${pd_name}(${pd_param_str}); return pd_entry; } //:: if t_type != TableType.INDIRECT_WS: continue //:: params_w = params + ["const GroupHandle_t grp"] //:: param_str = ", ".join(params_w) //:: name = t_name + "_add_entry_with_selector" //:: pd_name = pd_prefix + name EntryHandle_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; //:: if has_match_spec: ${pd_prefix}${t_name}_match_spec_t pd_match_spec; //:: match_params = gen_match_params(t.key) //:: for name, width in match_params: //:: name = get_c_name(name) //:: if width <= 4: pd_match_spec.${name} = match_spec.${name}; //:: else: memcpy(pd_match_spec.${name}, match_spec.${name}.c_str(), ${width}); //:: #endif //:: #endfor //:: #endif p4_pd_entry_hdl_t pd_entry; //:: pd_params = ["sess_hdl", "pd_dev_tgt"] //:: if has_match_spec: //:: pd_params += ["&pd_match_spec"] //:: #endif //:: if match_type in {MatchType.TERNARY, MatchType.RANGE}: //:: pd_params += ["priority"] //:: #endif //:: pd_params += ["grp", "&pd_entry"] //:: pd_param_str = ", ".join(pd_params) ${pd_name}(${pd_param_str}); return pd_entry; } //:: #endfor //:: for t_name, t in tables.items(): //:: t_type = t.type_ //:: if t_type == TableType.SIMPLE: continue //:: t_name = get_c_name(t_name) //:: params = ["const SessionHandle_t sess_hdl", //:: "const DevTarget_t &dev_tgt"] //:: params_wo = params + ["const MemberHandle_t mbr"] //:: param_str = ", ".join(params_wo) //:: name = t_name + "_set_default_entry" //:: pd_name = pd_prefix + name int32_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; p4_pd_entry_hdl_t pd_entry; //:: pd_params = ["sess_hdl", "pd_dev_tgt"] //:: pd_params += ["mbr", "&pd_entry"] //:: pd_param_str = ", ".join(pd_params) ${pd_name}(${pd_param_str}); return pd_entry; } //:: if t_type != TableType.INDIRECT_WS: continue //:: params_w = params + ["const GroupHandle_t grp"] //:: param_str = ", ".join(params_w) //:: name = t_name + "_set_default_entry_with_selector" //:: pd_name = pd_prefix + name int32_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; p4_pd_entry_hdl_t pd_entry; //:: pd_params = ["sess_hdl", "pd_dev_tgt"] //:: pd_params += ["grp", "&pd_entry"] //:: pd_param_str = ", ".join(pd_params) ${pd_name}(${pd_param_str}); return pd_entry; } //:: #endfor // COUNTERS //:: for ca_name, ca in counter_arrays.items(): //:: if ca.is_direct: //:: name = "counter_read_" + ca_name //:: pd_name = pd_prefix + name void ${name}(${api_prefix}counter_value_t &counter_value, const SessionHandle_t sess_hdl, const DevTarget_t &dev_tgt, const EntryHandle_t entry, const ${api_prefix}counter_flags_t &flags) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; int pd_flags = 0; if(flags.read_hw_sync) pd_flags |= COUNTER_READ_HW_SYNC; p4_pd_counter_value_t value = ${pd_name}(sess_hdl, pd_dev_tgt, entry, pd_flags); counter_value.packets = value.packets; counter_value.bytes = value.bytes; } //:: name = "counter_write_" + ca_name //:: pd_name = pd_prefix + name int32_t ${name}(const SessionHandle_t sess_hdl, const DevTarget_t &dev_tgt, const EntryHandle_t entry, const ${api_prefix}counter_value_t &counter_value) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; p4_pd_counter_value_t value; value.packets = counter_value.packets; value.bytes = counter_value.bytes; return ${pd_name}(sess_hdl, pd_dev_tgt, entry, value); } //:: else: //:: name = "counter_read_" + ca_name //:: pd_name = pd_prefix + name void ${name}(${api_prefix}counter_value_t &counter_value, const SessionHandle_t sess_hdl, const DevTarget_t &dev_tgt, const int32_t index, const ${api_prefix}counter_flags_t &flags) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; int pd_flags = 0; if(flags.read_hw_sync) pd_flags |= COUNTER_READ_HW_SYNC; p4_pd_counter_value_t value = ${pd_name}(sess_hdl, pd_dev_tgt, index, pd_flags); counter_value.packets = value.packets; counter_value.bytes = value.bytes; } //:: name = "counter_write_" + ca_name //:: pd_name = pd_prefix + name int32_t ${name}(const SessionHandle_t sess_hdl, const DevTarget_t &dev_tgt, const int32_t index, const ${api_prefix}counter_value_t &counter_value) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; p4_pd_counter_value_t value; value.packets = counter_value.packets; value.bytes = counter_value.bytes; return ${pd_name}(sess_hdl, pd_dev_tgt, index, value); } //:: #endif //:: #endfor //:: for ca_name, ca in counter_arrays.items(): //:: name = "counter_hw_sync_" + ca_name //:: pd_name = pd_prefix + name int32_t ${name}(const SessionHandle_t sess_hdl, const DevTarget_t &dev_tgt) { p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; std::promise<void> promise; auto future = promise.get_future(); struct HwSync { HwSync(std::promise<void> &promise) : promise(promise) { } std::promise<void> &promise; }; // lambda does not capture, so can be used as function pointer auto cb = [](int device_id, void *cookie) { static_cast<HwSync *>(cookie)->promise.set_value(); }; HwSync h(promise); ${pd_name}(sess_hdl, pd_dev_tgt, cb, static_cast<void *>(&h)); future.wait(); return 0; } //:: #endfor // METERS //:: for ma_name, ma in meter_arrays.items(): //:: params = ["const SessionHandle_t sess_hdl", //:: "const DevTarget_t &dev_tgt"] //:: pd_params = ["sess_hdl", "pd_dev_tgt"] //:: if ma.is_direct: //:: params += ["const EntryHandle_t entry"] //:: pd_params += ["entry"] //:: else: //:: params += ["const int32_t index"] //:: pd_params += ["index"] //:: #endif //:: if ma.unit == MeterUnit.PACKETS: //:: params += ["const " + api_prefix + "packets_meter_spec_t &meter_spec"] //:: else: //:: params += ["const " + api_prefix + "bytes_meter_spec_t &meter_spec"] //:: #endif //:: pd_params += ["&pd_meter_spec"] //:: param_str = ", ".join(params) //:: //:: pd_param_str = ", ".join(pd_params) //:: //:: name = "meter_set_" + ma_name //:: pd_name = pd_prefix + name int32_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; //:: if ma.unit == MeterUnit.PACKETS: p4_pd_packets_meter_spec_t pd_meter_spec; packets_meter_spec_thrift_to_pd(meter_spec, &pd_meter_spec); //:: else: p4_pd_bytes_meter_spec_t pd_meter_spec; bytes_meter_spec_thrift_to_pd(meter_spec, &pd_meter_spec); //:: #endif return ${pd_name}(${pd_param_str}); } //:: if ma.unit == MeterUnit.PACKETS: //:: params = [api_prefix + "packets_meter_spec_t &meter_spec"] //:: else: //:: params = [api_prefix + "bytes_meter_spec_t &meter_spec"] //:: #endif //:: params += ["const SessionHandle_t sess_hdl", //:: "const DevTarget_t &dev_tgt"] //:: pd_params = ["sess_hdl", "pd_dev_tgt"] //:: if ma.is_direct: //:: params += ["const EntryHandle_t entry"] //:: pd_params += ["entry"] //:: else: //:: params += ["const int32_t index"] //:: pd_params += ["index"] //:: #endif //:: pd_params += ["&pd_meter_spec"] //:: param_str = ", ".join(params) //:: //:: pd_param_str = ", ".join(pd_params) //:: //:: name = "meter_read_" + ma_name //:: pd_name = pd_prefix + name void ${name}(${param_str}) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; //:: if ma.unit == MeterUnit.PACKETS: p4_pd_packets_meter_spec_t pd_meter_spec; //:: else: p4_pd_bytes_meter_spec_t pd_meter_spec; //:: #endif p4_pd_status_t status = ${pd_name}(${pd_param_str}); if (status) return; //:: if ma.unit == MeterUnit.PACKETS: packets_meter_spec_pd_to_thrift(pd_meter_spec, &meter_spec); //:: else: bytes_meter_spec_pd_to_thrift(pd_meter_spec, &meter_spec); //:: #endif } //:: #endfor };
29,001
11,494
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ash/login/screens/wrong_hwid_screen.h" #include "chrome/browser/ash/login/wizard_controller.h" #include "chrome/browser/ui/webui/chromeos/login/wrong_hwid_screen_handler.h" namespace ash { namespace { constexpr char kUserActionSkip[] = "skip-screen"; } // namespace WrongHWIDScreen::WrongHWIDScreen(WrongHWIDScreenView* view, const base::RepeatingClosure& exit_callback) : BaseScreen(WrongHWIDScreenView::kScreenId, OobeScreenPriority::SCREEN_HARDWARE_ERROR), view_(view), exit_callback_(exit_callback) { DCHECK(view_); if (view_) view_->Bind(this); } WrongHWIDScreen::~WrongHWIDScreen() { if (view_) view_->Unbind(); } void WrongHWIDScreen::OnExit() { if (is_hidden()) return; exit_callback_.Run(); } void WrongHWIDScreen::OnViewDestroyed(WrongHWIDScreenView* view) { if (view_ == view) view_ = nullptr; } void WrongHWIDScreen::ShowImpl() { if (view_) view_->Show(); } void WrongHWIDScreen::HideImpl() { if (view_) view_->Hide(); } void WrongHWIDScreen::OnUserAction(const std::string& action_id) { if (action_id == kUserActionSkip) { OnExit(); } else { BaseScreen::OnUserAction(action_id); } } } // namespace ash
1,444
523
go_bandit([]() { describe("adiar/bdd/apply.cpp", []() { node_file bdd_F; node_file bdd_T; { // Garbage collect writers to free write-lock node_writer nw_F(bdd_F); nw_F << create_sink(false); node_writer nw_T(bdd_T); nw_T << create_sink(true); } ptr_t sink_T = create_sink_ptr(true); ptr_t sink_F = create_sink_ptr(false); node_file bdd_x0; node_file bdd_not_x0; node_file bdd_x1; node_file bdd_x2; { // Garbage collect writers early node_writer nw_x0(bdd_x0); nw_x0 << create_node(0,MAX_ID, sink_F, sink_T); node_writer nw_not_x0(bdd_not_x0); nw_not_x0 << create_node(0,MAX_ID, sink_T, sink_F); node_writer nw_x1(bdd_x1); nw_x1 << create_node(1,MAX_ID, sink_F, sink_T); node_writer nw_x2(bdd_x2); nw_x2 << create_node(2,MAX_ID, sink_F, sink_T); } node_file bdd_1; /* 1 ---- x0 / \ | 2 ---- x1 |/ \ 3 4 ---- x2 / \ / \ F T T 5 ---- x3 / \ F T */ node_t n1_5 = create_node(3,MAX_ID, sink_F, sink_T); node_t n1_4 = create_node(2,MAX_ID, sink_T, n1_5.uid); node_t n1_3 = create_node(2,MAX_ID-1, sink_F, sink_T); node_t n1_2 = create_node(1,MAX_ID, n1_3.uid, n1_4.uid); node_t n1_1 = create_node(0,MAX_ID, n1_3.uid, n1_2.uid); { // Garbage collect early and free write-lock node_writer nw_1(bdd_1); nw_1 << n1_5 << n1_4 << n1_3 << n1_2 << n1_1; } node_file bdd_2; /* ---- x0 1 ---- x1 / \ | T ---- x2 | 2 ---- x3 / \ T F */ node_t n2_2 = create_node(3,MAX_ID, sink_T, sink_F); node_t n2_1 = create_node(1,MAX_ID, n2_2.uid, sink_T); { // Garbage collect early and free write-lock node_writer nw_2(bdd_2); nw_2 << n2_2 << n2_1; } node_file bdd_3; /* 1 ---- x0 / \ 2 3 ---- x1 _/ X \_ | _/ \_ | X X / \ / \ 4 5 6 7 ---- x2 / \/ \/ \/ \ F T 8 T F ---- x3 / \ F T */ node_t n3_8 = create_node(3,MAX_ID, sink_F, sink_T); node_t n3_7 = create_node(2,MAX_ID, sink_T, sink_F); node_t n3_6 = create_node(2,MAX_ID - 1, n3_8.uid, sink_T); node_t n3_5 = create_node(2,MAX_ID - 2, sink_T, n3_8.uid); node_t n3_4 = create_node(2,MAX_ID - 3, sink_F, sink_T); node_t n3_3 = create_node(1,MAX_ID, n3_4.uid, n3_6.uid); node_t n3_2 = create_node(1,MAX_ID - 1, n3_5.uid, n3_7.uid); node_t n3_1 = create_node(0,MAX_ID, n3_2.uid, n3_3.uid); { // Garbage collect early and free write-lock node_writer nw_3(bdd_3); nw_3 << n3_8 << n3_7 << n3_6 << n3_5 << n3_4 << n3_3 << n3_2 << n3_1; } /* The product construction of bbd_1 and bdd_2 above is as follows in sorted order. (1,1) ---- x0 \_ _/ _X_ // Match in fst, but not coordinatewise / \ (3,1) (2,1) ---- x1 / \_ _/ \ / X \ /_______/ \ \ | \ \ (3,2) (3,T) (4,T) ---- x2 \ \ / \ / \ \ \ (F,T) (T,T) / \ \________ ___________/ \________ X________ X_________\ _______ / \ \ / \ \ (5,T) (F,2) (T,2) ---- x3 / \ / \ / \ (F,T) (T,T) (F,T)(F,F) (T,T)(T,F) */ describe("bdd_and(f,g)", [&]() { it("should resolve F /\\ T sink-only BDDs", [&]() { __bdd out = bdd_and(bdd_F, bdd_T); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should resolve T /\\ T sink-only BDDs", [&]() { __bdd out = bdd_and(bdd_T, bdd_T); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should shortcut on irrelevance on x0 /\\ T", [&]() { __bdd out = bdd_and(bdd_x0, bdd_T); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(bdd_x0._file_ptr)); AssertThat(out.negate, Is().False()); }); it("should shortcut F /\\ x0", [&]() { __bdd out = bdd_and(bdd_F, bdd_x0); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should x0 and !x0", [&]() { /* 1 ---- x0 / \ F F */ __bdd out = bdd_and(bdd_x0, bdd_not_x0); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().False()); }); it("should shortcut F /\\ [2]", [&]() { __bdd out = bdd_and(bdd_F, bdd_2); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should compute (and shortcut) BBD 1 /\\ [2]", [&]() { /* 1 ---- x0 X / \ 2 3 ---- x1 / \ / \ / X \ /___/ \ \ / | \ 4 5 6 ---- x2 / \ / \_ _/ \ F 7 F T 8 ---- x3 / \ / \ T F F T */ __bdd out = bdd_and(bdd_1, bdd_2); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(1,0) })); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(1,1) })); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), create_node_ptr(2,0) })); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,1), create_node_ptr(2,0) })); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,1)), create_node_ptr(2,1) })); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), create_node_ptr(2,2) })); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,2)), create_node_ptr(3,0) })); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,0)), create_node_ptr(3,1) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,1), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,1)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,2), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,1), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,1)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,2u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(2,3u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(3,2u))); AssertThat(level_info.can_pull(), Is().False()); }); it("should return input on being given the same BDD twice", [&]() { __bdd out = bdd_and(bdd_1, bdd_1); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(bdd_1._file_ptr)); AssertThat(out.negate, Is().False()); }); it("should group all recursion requests together", [&]() { // This is a counter-example to the prior "break ties on fst() with // snd()" approach. Here we will have three requests to the level of // x2, but in the following order: // // [((2,0),(2,1)), ((2,1),(2,0)), ((2,0),(2,1))] // // which all are tied, and hence the prior version would create // three nodes on this level rather than just two. /* 1 ---- x0 / \ 2 | ---- x1 / \| 3 4 ---- x2 / \\/ \ T F T */ // The second version is the same but has the nodes 3 and 4 mirrored // and the T sinks are replaced with an arc to a node for x3. node_file bdd_group_1, bdd_group_2; { // Garbage collect writers to free write-lock node_writer w1(bdd_group_1); w1 << create_node(2,1, create_sink_ptr(false), create_sink_ptr(true)) << create_node(2,0, create_sink_ptr(true), create_sink_ptr(false)) << create_node(1,0, create_node_ptr(2,0), create_node_ptr(2,1)) << create_node(0,1, create_node_ptr(1,0), create_node_ptr(2,1)); node_writer w2(bdd_group_2); w2 << create_node(3,0, create_sink_ptr(false), create_sink_ptr(true)) << create_node(2,1, create_node_ptr(3,0), create_sink_ptr(false)) << create_node(2,0, create_sink_ptr(false), create_node_ptr(3,0)) << create_node(1,0, create_node_ptr(2,1), create_node_ptr(2,0)) << create_node(0,1, create_node_ptr(1,0), create_node_ptr(2,0)); } __bdd out = bdd_and(bdd_group_1, bdd_group_2); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); // (2,2) AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(1,0) })); AssertThat(node_arcs.can_pull(), Is().True()); // (3,4) AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), create_node_ptr(2,0) })); AssertThat(node_arcs.can_pull(), Is().True()); // (4,3) AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(2,1) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), create_node_ptr(2,1) })); AssertThat(node_arcs.can_pull(), Is().True()); // (T,5) i.e. the added node AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,0), create_node_ptr(3,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,1)), create_node_ptr(3,0) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,0)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,1), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(2,2u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(3,1u))); AssertThat(level_info.can_pull(), Is().False()); }); }); describe("bdd_nand(f,g)", [&]() { it("should shortcut on negating on T and x0", [&]() { __bdd out = bdd_nand(bdd_x0, bdd_T); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(bdd_x0._file_ptr)); AssertThat(out.negate, Is().True()); }); it("should shortcut on negating on T and x0", [&]() { __bdd out = bdd_nand(bdd_x0, bdd_T); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(bdd_x0._file_ptr)); AssertThat(out.negate, Is().True()); }); it("should collapse on the same BDD twice, where one is negated [1]", [&]() { __bdd out = bdd_nand(bdd_2, bdd_not(bdd_2)); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); }); describe("bdd_or(f,g)", [&]() { it("should resolve T \\/ F sink-only BDDs", [&]() { __bdd out = bdd_or(bdd_T, bdd_F); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should resolve T \\/ F sink-only BDDs", [&]() { __bdd out = bdd_or(bdd_F, bdd_F); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should shortcut on irrelevance on x0 \\/ F", [&]() { __bdd out = bdd_or(bdd_x0, bdd_F); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(bdd_x0._file_ptr)); AssertThat(out.negate, Is().False()); }); it("should OR shortcut on irrelevance F \\/ x0", [&]() { __bdd out = bdd_or(bdd_F, bdd_x0); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(bdd_x0._file_ptr)); AssertThat(out.negate, Is().False()); }); it("should shortcut on x0 \\/ x2", [&]() { /* 1 ---- x0 / \ | T | 2 ---- x2 / \ F T */ __bdd out = bdd_or(bdd_x0, bdd_x2); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(2,0) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(2,1u))); AssertThat(level_info.can_pull(), Is().False()); }); it("should shortcut [1] \\/ T", [&]() { __bdd out = bdd_or(bdd_1, bdd_T); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should compute (and shortcut) [2] \\/ T", [&]() { __bdd out = bdd_or(bdd_2, bdd_T); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should compute (and shortcut) [1] \\/ [2]", [&]() { /* 1 ---- x0 / \ 2 3 ---- x1 / \ / \ | T | T \_ _/ 4 ---- x2 / \ 5 T ---- x3 / \ T F */ __bdd out = bdd_or(bdd_1, bdd_2); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(1,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(1,1) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), create_node_ptr(2,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,1), create_node_ptr(2,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,0), create_node_ptr(3,0) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,1)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,0), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,0)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,2u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(2,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(3,1u))); AssertThat(level_info.can_pull(), Is().False()); }); }); describe("bdd_nor(f,g)", [&]() { it("should collapse on the same BDD twice to a sink, where one is negated [2]", [&]() { __bdd out = bdd_nor(bdd_not(bdd_3), bdd_3); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); }); describe("bdd_xor(f,g)", [&]() { it("should resolve F ^ T sink-only BDDs", [&]() { __bdd out = bdd_xor(bdd_F, bdd_T); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should resolve T ^ T sink-only BDDs", [&]() { __bdd out = bdd_xor(bdd_T, bdd_T); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()) ; AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should shortcut on negating on x0 ^ T", [&]() { __bdd out = bdd_xor(bdd_x0, bdd_T); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(bdd_x0._file_ptr)); AssertThat(out.negate, Is().True()); }); it("should shortcut on negating on T ^ x0", [&]() { __bdd out = bdd_xor(bdd_x0, bdd_T); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(bdd_x0._file_ptr)); AssertThat(out.negate, Is().True()); }); it("should compute x0 ^ x1", [&]() { /* The order on the leaves are due to the sorting of sink requests after evaluating x0 1 ---- x0 / \ 2 3 ---- x1 / \ / \ F T T F */ __bdd out = bdd_xor(bdd_x0, bdd_x1); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(1,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(1,1) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,1), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,1)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,2u))); AssertThat(level_info.can_pull(), Is().False()); }); it("should compute [2] ^ x2", [&]() { /* ---- x0 (1,1) ---- x1 / \ (2,1) (T,1) ---- x2 / \ / \ / \ T F | | (2,F) (2,T) ---- x3 / \ / \ T F F T */ __bdd out = bdd_xor(bdd_2, bdd_x2); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), create_node_ptr(2,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), create_node_ptr(2,1) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,0), create_node_ptr(3,0) })); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,0)), create_node_ptr(3,1) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,1), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,1)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,0), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,0)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,1), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,1)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(2,2u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(3,2u))); AssertThat(level_info.can_pull(), Is().False()); }); it("should compute [1] ^ [2]", [&]() { /* There is no shortcutting possible on an XOR, so see the product construction above. */ __bdd out = bdd_xor(bdd_1, bdd_2); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(1,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(1,1) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), create_node_ptr(2,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,1), create_node_ptr(2,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,1)), create_node_ptr(2,1) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), create_node_ptr(2,2) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,2)), create_node_ptr(3,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,0), create_node_ptr(3,1) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,0)), create_node_ptr(3,2) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,1), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,1)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,2), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,0), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,0)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,1), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,1)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,2), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,2)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,2u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(2,3u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(3,3u))); AssertThat(level_info.can_pull(), Is().False()); }); it("should compute [3] ^ [1]", [&]() { /* The queue appD_data is used to forward data across the level. When [1] and 3 are combined, this is needed The product between the [3] and [1] then is (1,1) ---- x0 ________/ \_______ / \ (2,3) (3,2) ---- x1 / \_________ ________/ \ | X | // (5,3) (7,3) (4,3) (6,4) \__ _________/ \__________ / // min: 0 0 0 1 ___X___ X // max: 1 3 0 2 / \ _____/ \ // coord: 2 3 1 4 / \ / \ (4,3) (5,3) (6,4) (7,3) ---- x2 / \ / \ / \ / \ (F,F) (T,T) (T,F) | / \ (T,F) (F,T) | / \ | / | |/ | (8,T) (T,5) ---- x3 / \ / \ (F,T) (T,T) (T,F) (T,T) */ __bdd out = bdd_xor(bdd_3, bdd_1); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); // (2,3) AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(1,0) })); AssertThat(node_arcs.can_pull(), Is().True()); // (3,2) AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(1,1) })); AssertThat(node_arcs.can_pull(), Is().True()); // (4,3) AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,1), create_node_ptr(2,0) })); AssertThat(node_arcs.can_pull(), Is().True()); // (5,3) AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), create_node_ptr(2,1) })); AssertThat(node_arcs.can_pull(), Is().True()); // (6,4) AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,1)), create_node_ptr(2,2) })); AssertThat(node_arcs.can_pull(), Is().True()); // (7,3) AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), create_node_ptr(2,3) })); AssertThat(node_arcs.can_pull(), Is().True()); // (8,T) AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,1)), create_node_ptr(3,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,2), create_node_ptr(3,0) })); AssertThat(node_arcs.can_pull(), Is().True()); // (T,5) AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,2)), create_node_ptr(3,1) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,0)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,1), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,3), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,3)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,0), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,0)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,1), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,1)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,2u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(2,4u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(3,2u))); AssertThat(level_info.can_pull(), Is().False()); }); it("should collapse on the same BDD twice", [&]() { __bdd out = bdd_xor(bdd_1, bdd_1); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should collapse on the same BDD twice to a sink, when both are negated", [&]() { __bdd out = bdd_xor(bdd_not(bdd_1), bdd_not(bdd_1)); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); }); describe("bdd_xnor(f,g)", [&]() { // TODO }); describe("bdd_imp(f,g)", [&]() { it("should resolve F -> T sink-only BDDs", [&]() { __bdd out = bdd_imp(bdd_F, bdd_T); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should resolve T -> F sink-only BDDs", [&]() { __bdd out = bdd_imp(bdd_T, bdd_F); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should resolve T -> T sink-only BDDs", [&]() { __bdd out = bdd_imp(bdd_T, bdd_T); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should shortcut on irrelevance on T -> x0", [&]() { __bdd out = bdd_imp(bdd_T, bdd_x0); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(bdd_x0._file_ptr)); AssertThat(out.negate, Is().False()); }); it("should shortcut on x0 -> x1", [&]() { /* The order on the leaves are due to the sorting of sink requests after evaluating x0 1 ---- x0 / \ T 2 ---- x1 / \ F T */ __bdd out = bdd_imp(bdd_x0, bdd_x1); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(1,0) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,1u))); AssertThat(level_info.can_pull(), Is().False()); }); it("should shortcut F -> [1]", [&]() { __bdd out = bdd_imp(bdd_F, bdd_1); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should return the input when given the same BDD twice, where one is negated [1]", [&]() { __bdd out = bdd_imp(bdd_not(bdd_2), bdd_2); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(bdd_2._file_ptr)); AssertThat(out.negate, Is().False()); // negated the already negated input doubly-negating }); it("should return input when given the same BDD twice, where one is negated [2]", [&]() { __bdd out = bdd_imp(bdd_2, bdd_not(bdd_2)); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(bdd_2._file_ptr)); AssertThat(out.negate, Is().True()); // negated the first of the two }); }); describe("bdd_invimp(f,g)", [&]() { // TODO }); describe("bdd_equiv(f,g)", [&]() { // TODO }); describe("bdd_diff(f,g)", [&]() { // TODO }); describe("bdd_less(f,g)", [&]() { // TODO }); }); });
44,007
15,755
#include "ComponentLight.h" #include "GameObject.h" #include "ComponentTransform.h" #include "ModuleScene.h" #include "Application.h" #include "debugdraw.h" #include "JSONManager.h" ComponentLight::ComponentLight(GameObject * my_go) { this->my_go = my_go; this->type = LIGHT; if (App->scene->mainLight == nullptr) App->scene->mainLight = this; } ComponentLight::~ComponentLight() { my_go = nullptr; } update_status ComponentLight::Update() { position = my_go->transform->globalPosition; //direction = (my_go->transform->rotation * initialDirection).Normalized(); colorLight_Intensity = float3(colorLight.x * intensity, colorLight.y * intensity, colorLight.z * intensity); const ddVec3 boxColor = { 0.f, 0.6f, 0.8f }; dd::sphere(position, boxColor, 0.4 * App->GameScale); return UPDATE_CONTINUE; } void ComponentLight::Reset() { colorLight = { 0.5f, 0.5f, 0.5f }; intensity = 1.f; } void ComponentLight::Save(JSON_Value* componentsJSON) { JSON_Value* componentJSON = componentsJSON->createValue(); componentJSON->addInt("Type", type); componentJSON->addVector3("colorLight", colorLight); componentJSON->addFloat("Intensity", intensity); componentsJSON->addValue("Light", componentJSON); } void ComponentLight::Load(JSON_Value* componentJSON) { colorLight = componentJSON->getVector3("colorLight"); intensity = componentJSON->getFloat("Intensity"); }
1,382
476
// Copyright 2016 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 "quiche/http2/test_tools/http2_frame_decoder_listener_test_util.h" #include "quiche/http2/decoder/http2_frame_decoder_listener.h" #include "quiche/http2/http2_constants.h" #include "quiche/http2/http2_structures.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { FailingHttp2FrameDecoderListener::FailingHttp2FrameDecoderListener() = default; FailingHttp2FrameDecoderListener::~FailingHttp2FrameDecoderListener() = default; bool FailingHttp2FrameDecoderListener::OnFrameHeader( const Http2FrameHeader& header) { ADD_FAILURE() << "OnFrameHeader: " << header; return false; } void FailingHttp2FrameDecoderListener::OnDataStart( const Http2FrameHeader& header) { FAIL() << "OnDataStart: " << header; } void FailingHttp2FrameDecoderListener::OnDataPayload(const char* /*data*/, size_t len) { FAIL() << "OnDataPayload: len=" << len; } void FailingHttp2FrameDecoderListener::OnDataEnd() { FAIL() << "OnDataEnd"; } void FailingHttp2FrameDecoderListener::OnHeadersStart( const Http2FrameHeader& header) { FAIL() << "OnHeadersStart: " << header; } void FailingHttp2FrameDecoderListener::OnHeadersPriority( const Http2PriorityFields& priority) { FAIL() << "OnHeadersPriority: " << priority; } void FailingHttp2FrameDecoderListener::OnHpackFragment(const char* /*data*/, size_t len) { FAIL() << "OnHpackFragment: len=" << len; } void FailingHttp2FrameDecoderListener::OnHeadersEnd() { FAIL() << "OnHeadersEnd"; } void FailingHttp2FrameDecoderListener::OnPriorityFrame( const Http2FrameHeader& header, const Http2PriorityFields& priority) { FAIL() << "OnPriorityFrame: " << header << "; priority: " << priority; } void FailingHttp2FrameDecoderListener::OnContinuationStart( const Http2FrameHeader& header) { FAIL() << "OnContinuationStart: " << header; } void FailingHttp2FrameDecoderListener::OnContinuationEnd() { FAIL() << "OnContinuationEnd"; } void FailingHttp2FrameDecoderListener::OnPadLength(size_t trailing_length) { FAIL() << "OnPadLength: trailing_length=" << trailing_length; } void FailingHttp2FrameDecoderListener::OnPadding(const char* /*padding*/, size_t skipped_length) { FAIL() << "OnPadding: skipped_length=" << skipped_length; } void FailingHttp2FrameDecoderListener::OnRstStream( const Http2FrameHeader& header, Http2ErrorCode error_code) { FAIL() << "OnRstStream: " << header << "; code=" << error_code; } void FailingHttp2FrameDecoderListener::OnSettingsStart( const Http2FrameHeader& header) { FAIL() << "OnSettingsStart: " << header; } void FailingHttp2FrameDecoderListener::OnSetting( const Http2SettingFields& setting_fields) { FAIL() << "OnSetting: " << setting_fields; } void FailingHttp2FrameDecoderListener::OnSettingsEnd() { FAIL() << "OnSettingsEnd"; } void FailingHttp2FrameDecoderListener::OnSettingsAck( const Http2FrameHeader& header) { FAIL() << "OnSettingsAck: " << header; } void FailingHttp2FrameDecoderListener::OnPushPromiseStart( const Http2FrameHeader& header, const Http2PushPromiseFields& promise, size_t total_padding_length) { FAIL() << "OnPushPromiseStart: " << header << "; promise: " << promise << "; total_padding_length: " << total_padding_length; } void FailingHttp2FrameDecoderListener::OnPushPromiseEnd() { FAIL() << "OnPushPromiseEnd"; } void FailingHttp2FrameDecoderListener::OnPing(const Http2FrameHeader& header, const Http2PingFields& ping) { FAIL() << "OnPing: " << header << "; ping: " << ping; } void FailingHttp2FrameDecoderListener::OnPingAck(const Http2FrameHeader& header, const Http2PingFields& ping) { FAIL() << "OnPingAck: " << header << "; ping: " << ping; } void FailingHttp2FrameDecoderListener::OnGoAwayStart( const Http2FrameHeader& header, const Http2GoAwayFields& goaway) { FAIL() << "OnGoAwayStart: " << header << "; goaway: " << goaway; } void FailingHttp2FrameDecoderListener::OnGoAwayOpaqueData(const char* /*data*/, size_t len) { FAIL() << "OnGoAwayOpaqueData: len=" << len; } void FailingHttp2FrameDecoderListener::OnGoAwayEnd() { FAIL() << "OnGoAwayEnd"; } void FailingHttp2FrameDecoderListener::OnWindowUpdate( const Http2FrameHeader& header, uint32_t increment) { FAIL() << "OnWindowUpdate: " << header << "; increment=" << increment; } void FailingHttp2FrameDecoderListener::OnAltSvcStart( const Http2FrameHeader& header, size_t origin_length, size_t value_length) { FAIL() << "OnAltSvcStart: " << header << "; origin_length: " << origin_length << "; value_length: " << value_length; } void FailingHttp2FrameDecoderListener::OnAltSvcOriginData(const char* /*data*/, size_t len) { FAIL() << "OnAltSvcOriginData: len=" << len; } void FailingHttp2FrameDecoderListener::OnAltSvcValueData(const char* /*data*/, size_t len) { FAIL() << "OnAltSvcValueData: len=" << len; } void FailingHttp2FrameDecoderListener::OnAltSvcEnd() { FAIL() << "OnAltSvcEnd"; } void FailingHttp2FrameDecoderListener::OnPriorityUpdateStart( const Http2FrameHeader& header, const Http2PriorityUpdateFields& priority_update) { FAIL() << "OnPriorityUpdateStart: " << header << "; prioritized_stream_id: " << priority_update.prioritized_stream_id; } void FailingHttp2FrameDecoderListener::OnPriorityUpdatePayload( const char* /*data*/, size_t len) { FAIL() << "OnPriorityUpdatePayload: len=" << len; } void FailingHttp2FrameDecoderListener::OnPriorityUpdateEnd() { FAIL() << "OnPriorityUpdateEnd"; } void FailingHttp2FrameDecoderListener::OnUnknownStart( const Http2FrameHeader& header) { FAIL() << "OnUnknownStart: " << header; } void FailingHttp2FrameDecoderListener::OnUnknownPayload(const char* /*data*/, size_t len) { FAIL() << "OnUnknownPayload: len=" << len; } void FailingHttp2FrameDecoderListener::OnUnknownEnd() { FAIL() << "OnUnknownEnd"; } void FailingHttp2FrameDecoderListener::OnPaddingTooLong( const Http2FrameHeader& header, size_t missing_length) { FAIL() << "OnPaddingTooLong: " << header << "; missing_length: " << missing_length; } void FailingHttp2FrameDecoderListener::OnFrameSizeError( const Http2FrameHeader& header) { FAIL() << "OnFrameSizeError: " << header; } LoggingHttp2FrameDecoderListener::LoggingHttp2FrameDecoderListener() : wrapped_(nullptr) {} LoggingHttp2FrameDecoderListener::LoggingHttp2FrameDecoderListener( Http2FrameDecoderListener* wrapped) : wrapped_(wrapped) {} LoggingHttp2FrameDecoderListener::~LoggingHttp2FrameDecoderListener() = default; bool LoggingHttp2FrameDecoderListener::OnFrameHeader( const Http2FrameHeader& header) { QUICHE_VLOG(1) << "OnFrameHeader: " << header; if (wrapped_ != nullptr) { return wrapped_->OnFrameHeader(header); } return true; } void LoggingHttp2FrameDecoderListener::OnDataStart( const Http2FrameHeader& header) { QUICHE_VLOG(1) << "OnDataStart: " << header; if (wrapped_ != nullptr) { wrapped_->OnDataStart(header); } } void LoggingHttp2FrameDecoderListener::OnDataPayload(const char* data, size_t len) { QUICHE_VLOG(1) << "OnDataPayload: len=" << len; if (wrapped_ != nullptr) { wrapped_->OnDataPayload(data, len); } } void LoggingHttp2FrameDecoderListener::OnDataEnd() { QUICHE_VLOG(1) << "OnDataEnd"; if (wrapped_ != nullptr) { wrapped_->OnDataEnd(); } } void LoggingHttp2FrameDecoderListener::OnHeadersStart( const Http2FrameHeader& header) { QUICHE_VLOG(1) << "OnHeadersStart: " << header; if (wrapped_ != nullptr) { wrapped_->OnHeadersStart(header); } } void LoggingHttp2FrameDecoderListener::OnHeadersPriority( const Http2PriorityFields& priority) { QUICHE_VLOG(1) << "OnHeadersPriority: " << priority; if (wrapped_ != nullptr) { wrapped_->OnHeadersPriority(priority); } } void LoggingHttp2FrameDecoderListener::OnHpackFragment(const char* data, size_t len) { QUICHE_VLOG(1) << "OnHpackFragment: len=" << len; if (wrapped_ != nullptr) { wrapped_->OnHpackFragment(data, len); } } void LoggingHttp2FrameDecoderListener::OnHeadersEnd() { QUICHE_VLOG(1) << "OnHeadersEnd"; if (wrapped_ != nullptr) { wrapped_->OnHeadersEnd(); } } void LoggingHttp2FrameDecoderListener::OnPriorityFrame( const Http2FrameHeader& header, const Http2PriorityFields& priority) { QUICHE_VLOG(1) << "OnPriorityFrame: " << header << "; priority: " << priority; if (wrapped_ != nullptr) { wrapped_->OnPriorityFrame(header, priority); } } void LoggingHttp2FrameDecoderListener::OnContinuationStart( const Http2FrameHeader& header) { QUICHE_VLOG(1) << "OnContinuationStart: " << header; if (wrapped_ != nullptr) { wrapped_->OnContinuationStart(header); } } void LoggingHttp2FrameDecoderListener::OnContinuationEnd() { QUICHE_VLOG(1) << "OnContinuationEnd"; if (wrapped_ != nullptr) { wrapped_->OnContinuationEnd(); } } void LoggingHttp2FrameDecoderListener::OnPadLength(size_t trailing_length) { QUICHE_VLOG(1) << "OnPadLength: trailing_length=" << trailing_length; if (wrapped_ != nullptr) { wrapped_->OnPadLength(trailing_length); } } void LoggingHttp2FrameDecoderListener::OnPadding(const char* padding, size_t skipped_length) { QUICHE_VLOG(1) << "OnPadding: skipped_length=" << skipped_length; if (wrapped_ != nullptr) { wrapped_->OnPadding(padding, skipped_length); } } void LoggingHttp2FrameDecoderListener::OnRstStream( const Http2FrameHeader& header, Http2ErrorCode error_code) { QUICHE_VLOG(1) << "OnRstStream: " << header << "; code=" << error_code; if (wrapped_ != nullptr) { wrapped_->OnRstStream(header, error_code); } } void LoggingHttp2FrameDecoderListener::OnSettingsStart( const Http2FrameHeader& header) { QUICHE_VLOG(1) << "OnSettingsStart: " << header; if (wrapped_ != nullptr) { wrapped_->OnSettingsStart(header); } } void LoggingHttp2FrameDecoderListener::OnSetting( const Http2SettingFields& setting_fields) { QUICHE_VLOG(1) << "OnSetting: " << setting_fields; if (wrapped_ != nullptr) { wrapped_->OnSetting(setting_fields); } } void LoggingHttp2FrameDecoderListener::OnSettingsEnd() { QUICHE_VLOG(1) << "OnSettingsEnd"; if (wrapped_ != nullptr) { wrapped_->OnSettingsEnd(); } } void LoggingHttp2FrameDecoderListener::OnSettingsAck( const Http2FrameHeader& header) { QUICHE_VLOG(1) << "OnSettingsAck: " << header; if (wrapped_ != nullptr) { wrapped_->OnSettingsAck(header); } } void LoggingHttp2FrameDecoderListener::OnPushPromiseStart( const Http2FrameHeader& header, const Http2PushPromiseFields& promise, size_t total_padding_length) { QUICHE_VLOG(1) << "OnPushPromiseStart: " << header << "; promise: " << promise << "; total_padding_length: " << total_padding_length; if (wrapped_ != nullptr) { wrapped_->OnPushPromiseStart(header, promise, total_padding_length); } } void LoggingHttp2FrameDecoderListener::OnPushPromiseEnd() { QUICHE_VLOG(1) << "OnPushPromiseEnd"; if (wrapped_ != nullptr) { wrapped_->OnPushPromiseEnd(); } } void LoggingHttp2FrameDecoderListener::OnPing(const Http2FrameHeader& header, const Http2PingFields& ping) { QUICHE_VLOG(1) << "OnPing: " << header << "; ping: " << ping; if (wrapped_ != nullptr) { wrapped_->OnPing(header, ping); } } void LoggingHttp2FrameDecoderListener::OnPingAck(const Http2FrameHeader& header, const Http2PingFields& ping) { QUICHE_VLOG(1) << "OnPingAck: " << header << "; ping: " << ping; if (wrapped_ != nullptr) { wrapped_->OnPingAck(header, ping); } } void LoggingHttp2FrameDecoderListener::OnGoAwayStart( const Http2FrameHeader& header, const Http2GoAwayFields& goaway) { QUICHE_VLOG(1) << "OnGoAwayStart: " << header << "; goaway: " << goaway; if (wrapped_ != nullptr) { wrapped_->OnGoAwayStart(header, goaway); } } void LoggingHttp2FrameDecoderListener::OnGoAwayOpaqueData(const char* data, size_t len) { QUICHE_VLOG(1) << "OnGoAwayOpaqueData: len=" << len; if (wrapped_ != nullptr) { wrapped_->OnGoAwayOpaqueData(data, len); } } void LoggingHttp2FrameDecoderListener::OnGoAwayEnd() { QUICHE_VLOG(1) << "OnGoAwayEnd"; if (wrapped_ != nullptr) { wrapped_->OnGoAwayEnd(); } } void LoggingHttp2FrameDecoderListener::OnWindowUpdate( const Http2FrameHeader& header, uint32_t increment) { QUICHE_VLOG(1) << "OnWindowUpdate: " << header << "; increment=" << increment; if (wrapped_ != nullptr) { wrapped_->OnWindowUpdate(header, increment); } } void LoggingHttp2FrameDecoderListener::OnAltSvcStart( const Http2FrameHeader& header, size_t origin_length, size_t value_length) { QUICHE_VLOG(1) << "OnAltSvcStart: " << header << "; origin_length: " << origin_length << "; value_length: " << value_length; if (wrapped_ != nullptr) { wrapped_->OnAltSvcStart(header, origin_length, value_length); } } void LoggingHttp2FrameDecoderListener::OnAltSvcOriginData(const char* data, size_t len) { QUICHE_VLOG(1) << "OnAltSvcOriginData: len=" << len; if (wrapped_ != nullptr) { wrapped_->OnAltSvcOriginData(data, len); } } void LoggingHttp2FrameDecoderListener::OnAltSvcValueData(const char* data, size_t len) { QUICHE_VLOG(1) << "OnAltSvcValueData: len=" << len; if (wrapped_ != nullptr) { wrapped_->OnAltSvcValueData(data, len); } } void LoggingHttp2FrameDecoderListener::OnAltSvcEnd() { QUICHE_VLOG(1) << "OnAltSvcEnd"; if (wrapped_ != nullptr) { wrapped_->OnAltSvcEnd(); } } void LoggingHttp2FrameDecoderListener::OnPriorityUpdateStart( const Http2FrameHeader& header, const Http2PriorityUpdateFields& priority_update) { QUICHE_VLOG(1) << "OnPriorityUpdateStart"; if (wrapped_ != nullptr) { wrapped_->OnPriorityUpdateStart(header, priority_update); } } void LoggingHttp2FrameDecoderListener::OnPriorityUpdatePayload(const char* data, size_t len) { QUICHE_VLOG(1) << "OnPriorityUpdatePayload"; if (wrapped_ != nullptr) { wrapped_->OnPriorityUpdatePayload(data, len); } } void LoggingHttp2FrameDecoderListener::OnPriorityUpdateEnd() { QUICHE_VLOG(1) << "OnPriorityUpdateEnd"; if (wrapped_ != nullptr) { wrapped_->OnPriorityUpdateEnd(); } } void LoggingHttp2FrameDecoderListener::OnUnknownStart( const Http2FrameHeader& header) { QUICHE_VLOG(1) << "OnUnknownStart: " << header; if (wrapped_ != nullptr) { wrapped_->OnUnknownStart(header); } } void LoggingHttp2FrameDecoderListener::OnUnknownPayload(const char* data, size_t len) { QUICHE_VLOG(1) << "OnUnknownPayload: len=" << len; if (wrapped_ != nullptr) { wrapped_->OnUnknownPayload(data, len); } } void LoggingHttp2FrameDecoderListener::OnUnknownEnd() { QUICHE_VLOG(1) << "OnUnknownEnd"; if (wrapped_ != nullptr) { wrapped_->OnUnknownEnd(); } } void LoggingHttp2FrameDecoderListener::OnPaddingTooLong( const Http2FrameHeader& header, size_t missing_length) { QUICHE_VLOG(1) << "OnPaddingTooLong: " << header << "; missing_length: " << missing_length; if (wrapped_ != nullptr) { wrapped_->OnPaddingTooLong(header, missing_length); } } void LoggingHttp2FrameDecoderListener::OnFrameSizeError( const Http2FrameHeader& header) { QUICHE_VLOG(1) << "OnFrameSizeError: " << header; if (wrapped_ != nullptr) { wrapped_->OnFrameSizeError(header); } } } // namespace http2
16,573
5,602
// Copyright 2017 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 "components/offline_pages/core/prefetch/tasks/metrics_finalization_task.h" #include <memory> #include <set> #include <vector> #include "base/test/metrics/histogram_tester.h" #include "base/time/time.h" #include "components/offline_pages/core/prefetch/mock_prefetch_item_generator.h" #include "components/offline_pages/core/prefetch/prefetch_item.h" #include "components/offline_pages/core/prefetch/prefetch_types.h" #include "components/offline_pages/core/prefetch/store/prefetch_store_test_util.h" #include "components/offline_pages/core/prefetch/tasks/prefetch_task_test_base.h" #include "components/offline_pages/core/test_scoped_offline_clock.h" #include "testing/gtest/include/gtest/gtest.h" namespace offline_pages { class MetricsFinalizationTaskTest : public PrefetchTaskTestBase { public: MetricsFinalizationTaskTest() = default; ~MetricsFinalizationTaskTest() override = default; void SetUp() override; void TearDown() override; protected: std::unique_ptr<MetricsFinalizationTask> metrics_finalization_task_; }; void MetricsFinalizationTaskTest::SetUp() { PrefetchTaskTestBase::SetUp(); metrics_finalization_task_ = std::make_unique<MetricsFinalizationTask>(store()); } void MetricsFinalizationTaskTest::TearDown() { metrics_finalization_task_.reset(); PrefetchTaskTestBase::TearDown(); } TEST_F(MetricsFinalizationTaskTest, StoreFailure) { store_util()->SimulateInitializationError(); // Execute the metrics task. RunTask(metrics_finalization_task_.get()); } // Tests that the task works correctly with an empty database. TEST_F(MetricsFinalizationTaskTest, EmptyRun) { EXPECT_EQ(0, store_util()->CountPrefetchItems()); // Execute the metrics task. RunTask(metrics_finalization_task_.get()); EXPECT_EQ(0, store_util()->CountPrefetchItems()); } TEST_F(MetricsFinalizationTaskTest, LeavesOtherStatesAlone) { std::vector<PrefetchItemState> all_states_but_finished = GetAllStatesExcept({PrefetchItemState::FINISHED}); for (auto& state : all_states_but_finished) { PrefetchItem item = item_generator()->CreateItem(state); EXPECT_TRUE(store_util()->InsertPrefetchItem(item)) << "Failed inserting item with state " << static_cast<int>(state); } std::set<PrefetchItem> all_inserted_items; EXPECT_EQ(10U, store_util()->GetAllItems(&all_inserted_items)); // Execute the task. RunTask(metrics_finalization_task_.get()); std::set<PrefetchItem> all_items_after_task; EXPECT_EQ(10U, store_util()->GetAllItems(&all_items_after_task)); EXPECT_EQ(all_inserted_items, all_items_after_task); } TEST_F(MetricsFinalizationTaskTest, FinalizesMultipleItems) { base::Time before_insert_time = base::Time::Now(); std::set<PrefetchItem> finished_items = { item_generator()->CreateItem(PrefetchItemState::FINISHED), item_generator()->CreateItem(PrefetchItemState::FINISHED), item_generator()->CreateItem(PrefetchItemState::FINISHED)}; for (auto& item : finished_items) { ASSERT_TRUE(store_util()->InsertPrefetchItem(item)); // Confirms that ItemGenerator did set |freshness_time| with Time::Now(). ASSERT_LE(before_insert_time, item.freshness_time); } PrefetchItem unfinished_item = item_generator()->CreateItem(PrefetchItemState::NEW_REQUEST); ASSERT_TRUE(store_util()->InsertPrefetchItem(unfinished_item)); // Overrides the offline clock and set a current time in the future. TestScopedOfflineClock clock; clock.SetNow(before_insert_time + base::Hours(1)); // Execute the metrics task. RunTask(metrics_finalization_task_.get()); // The finished ones should all have become zombies and the new request should // be untouched. std::set<PrefetchItem> all_items; EXPECT_EQ(4U, store_util()->GetAllItems(&all_items)); EXPECT_EQ(0U, FilterByState(all_items, PrefetchItemState::FINISHED).size()); std::set<PrefetchItem> zombie_items = FilterByState(all_items, PrefetchItemState::ZOMBIE); EXPECT_EQ(3U, zombie_items.size()); for (const PrefetchItem& zombie_item : zombie_items) { EXPECT_EQ(clock.Now(), zombie_item.freshness_time) << "Incorrect freshness_time (not updated?) for item " << zombie_item.client_id; } std::set<PrefetchItem> items_in_new_request_state = FilterByState(all_items, PrefetchItemState::NEW_REQUEST); EXPECT_EQ(1U, items_in_new_request_state.count(unfinished_item)); } TEST_F(MetricsFinalizationTaskTest, MetricsAreReported) { PrefetchItem successful_item = item_generator()->CreateItem(PrefetchItemState::FINISHED); successful_item.generate_bundle_attempts = 1; successful_item.get_operation_attempts = 1; successful_item.download_initiation_attempts = 1; ASSERT_TRUE(store_util()->InsertPrefetchItem(successful_item)); PrefetchItem failed_item = item_generator()->CreateItem(PrefetchItemState::RECEIVED_GCM); failed_item.state = PrefetchItemState::FINISHED; failed_item.error_code = PrefetchItemErrorCode::ARCHIVING_FAILED; ASSERT_TRUE(store_util()->InsertPrefetchItem(failed_item)); PrefetchItem unfinished_item = item_generator()->CreateItem(PrefetchItemState::NEW_REQUEST); ASSERT_TRUE(store_util()->InsertPrefetchItem(unfinished_item)); // Execute the metrics task. base::HistogramTester histogram_tester; RunTask(metrics_finalization_task_.get()); std::set<PrefetchItem> all_items; EXPECT_EQ(3U, store_util()->GetAllItems(&all_items)); EXPECT_EQ(2U, FilterByState(all_items, PrefetchItemState::ZOMBIE).size()); EXPECT_EQ(1U, FilterByState(all_items, PrefetchItemState::NEW_REQUEST).size()); // One successful and one failed samples. histogram_tester.ExpectUniqueSample( "OfflinePages.Prefetching.ItemLifetime.Successful", 0, 1); histogram_tester.ExpectUniqueSample( "OfflinePages.Prefetching.ItemLifetime.Failed", 0, 1); // One sample for each_error code value. histogram_tester.ExpectTotalCount( "OfflinePages.Prefetching.FinishedItemErrorCode", 2); histogram_tester.ExpectBucketCount( "OfflinePages.Prefetching.FinishedItemErrorCode", static_cast<int>(PrefetchItemErrorCode::SUCCESS), 1); histogram_tester.ExpectBucketCount( "OfflinePages.Prefetching.FinishedItemErrorCode", static_cast<int>(PrefetchItemErrorCode::ARCHIVING_FAILED), 1); // Attempt values match what was set above (non set values default to 0). histogram_tester.ExpectTotalCount( "OfflinePages.Prefetching.ActionAttempts.GeneratePageBundle", 2); histogram_tester.ExpectBucketCount( "OfflinePages.Prefetching.ActionAttempts.GeneratePageBundle", 0, 1); histogram_tester.ExpectBucketCount( "OfflinePages.Prefetching.ActionAttempts.GeneratePageBundle", 1, 1); histogram_tester.ExpectTotalCount( "OfflinePages.Prefetching.ActionAttempts.GetOperation", 2); histogram_tester.ExpectBucketCount( "OfflinePages.Prefetching.ActionAttempts.GetOperation", 0, 1); histogram_tester.ExpectBucketCount( "OfflinePages.Prefetching.ActionAttempts.GetOperation", 1, 1); histogram_tester.ExpectTotalCount( "OfflinePages.Prefetching.ActionAttempts.DownloadInitiation", 2); histogram_tester.ExpectBucketCount( "OfflinePages.Prefetching.ActionAttempts.DownloadInitiation", 0, 1); histogram_tester.ExpectBucketCount( "OfflinePages.Prefetching.ActionAttempts.DownloadInitiation", 1, 1); } // Verifies that items from all states are counted properly. TEST_F(MetricsFinalizationTaskTest, CountsItemsInEachStateMetricReportedCorectly) { // Insert a different number of items for each state. for (size_t i = 0; i < kOrderedPrefetchItemStates.size(); ++i) { PrefetchItemState state = kOrderedPrefetchItemStates[i]; for (size_t j = 0; j < i + 1; ++j) { PrefetchItem item = item_generator()->CreateItem(state); EXPECT_TRUE(store_util()->InsertPrefetchItem(item)) << "Failed inserting item with state " << static_cast<int>(state); } } // Execute the task. base::HistogramTester histogram_tester; RunTask(metrics_finalization_task_.get()); histogram_tester.ExpectTotalCount("OfflinePages.Prefetching.StateCounts", 66); // Check that histogram was recorded correctly for items in each state. for (size_t i = 0; i < kOrderedPrefetchItemStates.size(); ++i) { histogram_tester.ExpectBucketCount( "OfflinePages.Prefetching.StateCounts", static_cast<int>(kOrderedPrefetchItemStates[i]), i + 1); } } } // namespace offline_pages
8,646
3,022
/*############################################################################## HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®. 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 "platform.h" #include <algorithm> #include "limits.h" #include "jlib.hpp" #include "jbuff.hpp" #include "jsecrets.hpp" #include "dasess.hpp" #include "dautils.hpp" #include "portlist.h" #include "dacoven.hpp" #include "daclient.hpp" #include "dasds.hpp" #include "dasess.hpp" #include "daqueue.hpp" #include "workunit.hpp" #include "wujobq.hpp" #include "securesocket.hpp" #ifndef _CONTAINERIZED #include "environment.hpp" #endif #ifdef _MSC_VER #pragma warning (disable : 4355) #endif #if 0 JobQueues JobQueue @name= @count= @state=active|paused|stopped Edition <num> Client @session= @connected= @waiting= -- connections and waiting can be > 1 (multiple threads) Item* @wuid @owner @node @port @priority @session #endif class CJobQueueItem: implements IJobQueueItem, public CInterface { int priority; StringAttr wu; StringAttr owner; SessionId sessid; SocketEndpoint ep; unsigned port; CDateTime enqueuedt; public: IMPLEMENT_IINTERFACE; CJobQueueItem(MemoryBuffer &src) { deserialize(src); } CJobQueueItem(const char *_wu) : wu(_wu) { priority = 0; ep = queryMyNode()->endpoint(); port = 0; sessid = myProcessSession(); } CJobQueueItem(IPropertyTree *item) { const char * wuid = item->queryProp("@wuid"); if (*wuid=='~') wuid++; wu.set(wuid); owner.set(item->queryProp("@owner")); sessid = (SessionId)item->getPropInt64("@session"); priority = item->getPropInt("@priority"); ep.set(item->queryProp("@node")); port = (unsigned)item->getPropInt("@port"); StringBuffer dts; if (item->getProp("@enqueuedt",dts)) enqueuedt.setString(dts.str()); } static void assignBranch(IPropertyTree *item,IJobQueueItem *qi) { item->setPropInt64("@session",qi->getSessionId()); item->setPropInt("@priority",qi->getPriority()); item->setPropInt("@port",qi->getPort()); item->setProp("@wuid",qi->queryWUID()); item->setProp("@owner",qi->queryOwner()); StringBuffer eps; qi->queryEndpoint().getUrlStr(eps); item->setProp("@node",eps.str()); StringBuffer dts; qi->queryEnqueuedTime().getString(dts); if (dts.length()==0) { CDateTime dt; dt.setNow(); dt.getString(dts); qi->setEnqueuedTime(dt); } item->setProp("@enqueuedt",dts.str()); } const char *queryWUID() { return wu.get(); } int getPriority() { return priority; } unsigned getPort() { return port; } SessionId getSessionId() { return sessid; } SocketEndpoint &queryEndpoint() { return ep; } const char *queryOwner() { return owner.get(); } bool equals(IJobQueueItem *other) { // work unit is primary key return strcmp(wu.get(),other->queryWUID())==0; } CDateTime &queryEnqueuedTime() { return enqueuedt; } void setEnqueuedTime(const CDateTime &dt) { enqueuedt.set(dt); } void serialize(MemoryBuffer &tgt) { tgt.append(priority).append(port).append(wu).append(sessid); ep.serialize(tgt); StringBuffer dts; enqueuedt.getString(dts); tgt.append(owner).append(dts); } void deserialize(MemoryBuffer &src) { src.read(priority).read(port).read(wu).read(sessid); ep.deserialize(src); StringBuffer dts; src.read(owner).read(dts); enqueuedt.setString(dts.str()); } IJobQueueItem* clone() { IJobQueueItem* ret = new CJobQueueItem(wu); ret->setPriority(priority); ret->setPriority(port); ret->setEndpoint(ep); ret->setSessionId(sessid); return ret; } void setPriority(int _priority) { priority = _priority; } void setPort(unsigned _port) { port = _port; } void setEndpoint(const SocketEndpoint &_ep) { ep = _ep; } void setSessionId(SessionId _id) { if (_id) sessid = _id; else sessid = myProcessSession(); } void setOwner(const char *_owner) { owner.set(_owner); } bool isValidSession() { Owned<INode> node = createINode(ep); return (querySessionManager().lookupProcessSession(node)==sessid); } }; class CJobQueueIterator: implements IJobQueueIterator, public CInterface { public: CJobQueueContents &items; unsigned idx; IMPLEMENT_IINTERFACE; CJobQueueIterator(CJobQueueContents &_items) : items(_items) { idx = 0; } bool isValid() { return idx<items.ordinality(); } bool first() { idx = 0; return isValid(); } bool next() { idx++; return isValid(); } IJobQueueItem & query() { return items.item(idx); } }; IJobQueueIterator *CJobQueueContents::getIterator() { return new CJobQueueIterator(*this); } IJobQueueItem *createJobQueueItem(const char *wuid) { if (!wuid||!*wuid) throw MakeStringException(-1,"createJobQueueItem empty WUID"); return new CJobQueueItem(wuid);; } IJobQueueItem *deserializeJobQueueItem(MemoryBuffer &mb) { return new CJobQueueItem(mb); } #define ForEachQueue(qd) for (sQueueData *qd = qdata; qd!=NULL; qd=qd->next) #define ForEachQueueIn(parent,qd) for (sQueueData *qd = parent.qdata; qd!=NULL; qd=qd->next) struct sQueueData { sQueueData *next; IRemoteConnection *conn; StringAttr qname; IPropertyTree *root; SubscriptionId subscriberid; unsigned lastWaitEdition; }; class CJobQueueBase: implements IJobQueueConst, public CInterface { class cOrderedIterator { CJobQueueBase &parent; unsigned numqueues; unsigned *queueidx; sQueueData **queues; IPropertyTree **queuet; MemoryAttr ma; unsigned current; public: cOrderedIterator(CJobQueueBase&_parent) : parent(_parent) { numqueues=0; ForEachQueueIn(parent,qd1) if (qd1->root) numqueues++; queueidx = (unsigned *)ma.allocate(numqueues*(sizeof(unsigned)+sizeof(sQueueData *)+sizeof(IPropertyTree *))); queues = (sQueueData **)(queueidx+numqueues); queuet = (IPropertyTree **)(queues+numqueues); unsigned i = 0; ForEachQueueIn(parent,qd2) { if (qd2->root) queues[i++] = qd2; } current = (unsigned)-1; } bool first() { StringBuffer path; parent.getItemPath(path,0U); current = (unsigned)-1; for (unsigned i = 0; i<numqueues;i++) { queueidx[i] = 0; queuet[i] = queues[i]->root->queryPropTree(path.str()); if (queuet[i]) if ((current==(unsigned)-1)||parent.itemOlder(queuet[i],queuet[current])) current = i; } return current!=(unsigned)-1; } bool next() { if (current==(unsigned)-1) return false; queueidx[current]++; StringBuffer path; parent.getItemPath(path,queueidx[current]); queuet[current] = queues[current]->root->queryPropTree(path.str()); current = (unsigned)-1; for (unsigned i = 0; i<numqueues;i++) { if (queuet[i]) if ((current==(unsigned)-1)||parent.itemOlder(queuet[i],queuet[current])) current = i; } return current!=(unsigned)-1; } bool isValid() { return current!=(unsigned)-1; } void item(sQueueData *&qd, IPropertyTree *&t,unsigned &idx) { assertex(current!=(unsigned)-1); qd = queues[current]; t = queuet[current]; idx = queueidx[current]; } sQueueData &queryQueue() { assertex(current!=(unsigned)-1); return *queues[current]; } IPropertyTree &queryTree() { assertex(current!=(unsigned)-1); return *queuet[current]; } }; protected: bool doGetLastDequeuedInfo(sQueueData *qd, StringAttr &wuid, CDateTime &enqueuedt, int &priority) { priority = 0; if (!qd) return false; const char *w = qd->root->queryProp("@prevwuid"); if (!w||!*w) return false; wuid.set(w); StringBuffer dts; if (qd->root->getProp("@prevenqueuedt",dts)) enqueuedt.setString(dts.str()); priority = qd->root->getPropInt("@prevpriority"); return true; } public: sQueueData *qdata; Semaphore notifysem; CriticalSection crit; IMPLEMENT_IINTERFACE; CJobQueueBase(const char *_qname) { StringArray qlist; qlist.appendListUniq(_qname, ","); sQueueData *last = NULL; ForEachItemIn(i,qlist) { sQueueData *qd = new sQueueData; qd->next = NULL; qd->qname.set(qlist.item(i)); qd->conn = NULL; qd->root = NULL; qd->lastWaitEdition = 0; qd->subscriberid = 0; if (last) last->next = qd; else qdata = qd; last = qd; } }; virtual ~CJobQueueBase() { while (qdata) { sQueueData * next = qdata->next; delete qdata; qdata = next; } } StringBuffer &getItemPath(StringBuffer &path,const char *wuid) { if (!wuid||!*wuid) return getItemPath(path,0U); return path.appendf("Item[@wuid=\"%s\"]",wuid); } StringBuffer &getItemPath(StringBuffer &path,unsigned idx) { path.appendf("Item[@num=\"%d\"]",idx+1); return path; } IPropertyTree *queryClientRootIndex(sQueueData &qd, unsigned idx) { VStringBuffer path("Client[%d]", idx+1); return qd.root->queryPropTree(path); } bool itemOlder(IPropertyTree *qt1, IPropertyTree *qt2) { // if this ever becomes time critical thne could cache enqueued values StringBuffer d1s; if (qt1) qt1->getProp("@enqueuedt",d1s); StringBuffer d2s; if (qt2) qt2->getProp("@enqueuedt",d2s); return (strcmp(d1s.str(),d2s.str())<0); } IJobQueueItem *doGetItem(sQueueData &qd,unsigned idx) { if (idx==(unsigned)-1) { idx = qd.root->getPropInt("@count"); if (!idx) return NULL; idx--; } StringBuffer path; IPropertyTree *item = qd.root->queryPropTree(getItemPath(path,idx).str()); if (!item) return NULL; return new CJobQueueItem(item); } IJobQueueItem *getItem(sQueueData &qd,unsigned idx) { return doGetItem(qd, idx); } IJobQueueItem *getHead(sQueueData &qd) { return getItem(qd,0); } unsigned doFindRank(sQueueData &qd,const char *wuid) { StringBuffer path; IPropertyTree *item = qd.root->queryPropTree(getItemPath(path,wuid).str()); if (!item) return (unsigned)-1; return item->getPropInt("@num")-1; } unsigned findRank(sQueueData &qd,const char *wuid) { return doFindRank(qd,wuid); } IJobQueueItem *find(sQueueData &qd,const char *wuid) { StringBuffer path; IPropertyTree *item = qd.root->queryPropTree(getItemPath(path,wuid).str()); if (!item) return NULL; bool cached = item->getPropInt("@num",0)<=0; if (wuid&&cached) return NULL; // don't want cached value unless explicit return new CJobQueueItem(item); } unsigned copyItemsImpl(sQueueData &qd,CJobQueueContents &dest) { unsigned ret=0; StringBuffer path; for (unsigned i=0;;i++) { IPropertyTree *item = qd.root->queryPropTree(getItemPath(path.clear(),i).str()); if (!item) break; ret++; dest.append(*new CJobQueueItem(item)); } return ret; } virtual void copyItemsAndState(CJobQueueContents& contents, StringBuffer& state, StringBuffer& stateDetails) { assertex(qdata); assertex(qdata->root); copyItemsImpl(*qdata,contents); const char *st = qdata->root->queryProp("@state"); if (st&&*st) state.set(st); if (st && (strieq(st, "paused") || strieq(st, "stopped"))) { const char *stDetails = qdata->root->queryProp("@stateDetails"); if (stDetails&&*stDetails) stateDetails.set(stDetails); } } sQueueData *findQD(const char *wuid) { if (wuid&&*wuid) { ForEachQueue(qd) { unsigned idx = doFindRank(*qd,wuid); if (idx!=(unsigned)-1) return qd; } } return NULL; } virtual unsigned waiting() { unsigned ret = 0; ForEachQueue(qd) { for (unsigned i=0;;i++) { IPropertyTree *croot = queryClientRootIndex(*qd,i); if (!croot) break; ret += croot->getPropInt("@waiting"); } } return ret; } virtual unsigned findRank(const char *wuid) { assertex(qdata); if (!qdata->next) return findRank(*qdata,wuid); cOrderedIterator it(*this); unsigned i = 0; ForEach(it) { const char *twuid = it.queryTree().queryProp("@wuid"); if (twuid&&(strcmp(twuid,wuid)==0)) return i; i++; } return (unsigned)-1; } virtual unsigned copyItems(CJobQueueContents &dest) { assertex(qdata); if (!qdata->next) return copyItemsImpl(*qdata,dest); cOrderedIterator it(*this); unsigned ret = 0; ForEach(it) { dest.append(*new CJobQueueItem(&it.queryTree())); ret++; } return ret; } virtual IJobQueueItem *getItem(unsigned idx) { if (!qdata) return NULL; if (!qdata->next) return getItem(*qdata,idx); cOrderedIterator it(*this); unsigned i = 0; IPropertyTree *ret = NULL; ForEach(it) { if (i==idx) { ret = &it.queryTree(); break; } else if (idx==(unsigned)-1) // -1 means return last ret = &it.queryTree(); i++; } if (ret) return new CJobQueueItem(ret); return NULL; } virtual IJobQueueItem *getHead() { if (!qdata) return NULL; if (!qdata->next) return getHead(*qdata); return getItem(0); } virtual IJobQueueItem *getTail() { if (!qdata) return NULL; if (!qdata->next) return getHead(*qdata); return getItem((unsigned)-1); } virtual IJobQueueItem *find(const char *wuid) { if (!qdata) return NULL; sQueueData *qd = qdata->next?findQD(wuid):qdata; if (!qd) return NULL; return find(*qd,wuid); } virtual bool paused() { // true if all paused ForEachQueue(qd) { if (qd->root) { const char *state = qd->root->queryProp("@state"); if (state&&(strcmp(state,"paused")!=0)) return false; } } return true; } virtual bool paused(StringBuffer& info) { // true if all paused ForEachQueue(qd) { if (qd->root) { const char *state = qd->root->queryProp("@state"); if (state&&(strcmp(state,"paused")!=0)) return false; if (state&&!info.length()) { const char *stateDetails = qd->root->queryProp("@stateDetails"); if (stateDetails && *stateDetails) info.set(stateDetails); } } } return true; } virtual bool stopped() { // true if all stopped ForEachQueue(qd) { if (qd->root) { const char *state = qd->root->queryProp("@state"); if (state&&(strcmp(state,"stopped")!=0)) return false; } } return true; } virtual bool stopped(StringBuffer& info) { // true if all stopped ForEachQueue(qd) { if (qd->root) { const char *state = qd->root->queryProp("@state"); if (state&&(strcmp(state,"stopped")!=0)) return false; if (state&&!info.length()) { const char *stateDetails = qd->root->queryProp("@stateDetails"); if (stateDetails && *stateDetails) info.set(stateDetails); } } } return true; } virtual unsigned ordinality() { unsigned ret = 0; ForEachQueue(qd) { if (qd->root) ret += qd->root->getPropInt("@count"); } return ret; } virtual bool getLastDequeuedInfo(StringAttr &wuid, CDateTime &enqueuedt, int &priority) { return doGetLastDequeuedInfo(qdata, wuid, enqueuedt, priority); } //Similar to copyItemsAndState(), this method returns the state information for one queue. virtual void getState(StringBuffer& state, StringBuffer& stateDetails) { if (!qdata->root) return; const char *st = qdata->root->queryProp("@state"); if (!st || !*st) return; state.set(st); if ((strieq(st, "paused") || strieq(st, "stopped"))) stateDetails.set(qdata->root->queryProp("@stateDetails")); } }; class CJobQueueConst: public CJobQueueBase { Owned<IPropertyTree> jobQueueSnapshot; public: CJobQueueConst(const char *_qname, IPropertyTree* _jobQueueSnapshot) : CJobQueueBase(_qname) { if (!_jobQueueSnapshot) throw MakeStringException(-1, "No job queue snapshot"); jobQueueSnapshot.setown(_jobQueueSnapshot); ForEachQueue(qd) { VStringBuffer path("Queue[@name=\"%s\"]", qd->qname.get()); qd->root = jobQueueSnapshot->queryPropTree(path.str()); if (!qd->root) throw MakeStringException(-1, "No job queue found for %s", qd->qname.get()); } }; }; class CJobQueue: public CJobQueueBase, implements IJobQueue { public: sQueueData *activeq; SessionId sessionid; unsigned locknest; bool writemode; bool connected; Owned<IConversation> initiateconv; StringAttr initiatewu; bool dequeuestop; bool cancelwaiting; bool validateitemsessions; class csubs: implements ISDSSubscription, public CInterface { CJobQueue *parent; public: IMPLEMENT_IINTERFACE; csubs(CJobQueue *_parent) { parent = _parent; } void notify(SubscriptionId id, const char *xpath, SDSNotifyFlags flags, unsigned valueLen, const void *valueData) { CriticalBlock block(parent->crit); parent->notifysem.signal(); } } subs; IMPLEMENT_IINTERFACE; CJobQueue(const char *_qname) : CJobQueueBase(_qname), subs(this) { activeq = qdata; sessionid = myProcessSession(); validateitemsessions = false; writemode = false; locknest = 0; connected = false; dequeuestop = false; cancelwaiting = false; Cconnlockblock block(this,false); // this just checks queue exists } virtual ~CJobQueue() { try { while (locknest) connunlock(true); // auto rollback if (connected) disconnect(); } catch (IException *e) { // server error EXCLOG(e, "~CJobQueue"); e->Release(); } try { // must attempt to remove subscription before object destroyed. dounsubscribe(); } catch (IException *e) { EXCLOG(e, "~CJobQueue calling dounsubscribe"); e->Release(); } } void connlock(bool exclusive) { // must be in sect if (locknest++==0) { unsigned wait = qdata&&qdata->next?5000:INFINITE; ForEachQueue(qd) { for (;;) { StringBuffer path; path.appendf("/JobQueues/Queue[@name=\"%s\"]",qd->qname.get()); bool timeout; for (;;) { timeout=false; try { qd->conn = querySDS().connect(path.str(),myProcessSession(),exclusive?RTM_LOCK_WRITE:RTM_LOCK_READ,wait); if (qd->conn) break; } catch (ISDSException *e) { if (SDSExcpt_LockTimeout != e->errorCode()) throw; e->Release(); timeout = true; } // create queue Owned<IRemoteConnection> pconn; try { pconn.setown(querySDS().connect("/JobQueues",myProcessSession(),RTM_LOCK_WRITE|RTM_CREATE_QUERY,wait)); if (!pconn) throw MakeStringException(-1,"CJobQueue could not create JobQueues"); IPropertyTree *proot = pconn->queryRoot(); StringBuffer cpath; cpath.appendf("Queue[@name=\"%s\"]",qd->qname.get()); if (!proot->hasProp(cpath.str())) { IPropertyTree *pt = proot->addPropTree("Queue"); pt->setProp("@name",qd->qname.get()); pt->setProp("@state","active"); pt->setPropInt("@count", 0); pt->setPropInt("Edition", 1); } } catch (ISDSException *e) { if (SDSExcpt_LockTimeout != e->errorCode()) throw; e->Release(); timeout = true; } } if (!timeout) break; sQueueData *qd2 = qdata; do { ::Release(qd2->conn); qd2->conn = NULL; qd2->root = NULL; } while (qd2!=qd); PROGLOG("Job Queue contention - delaying before retrying"); Sleep(getRandom()%5000); // dining philosopher delay wait = getRandom()%4000+3000; // try and prevent sync qd = qdata; } qd->root = qd->conn->queryRoot(); } writemode = exclusive; } else { if (exclusive&&!writemode) { ForEachQueue(qd) { assertex(qd->conn); writemode = exclusive; bool lockreleased; safeChangeModeWrite(qd->conn,qd->qname.get(),lockreleased); qd->root = qd->conn->queryRoot(); } } } } void connunlock(bool rollback=false) { // should be in sect if (--locknest==0) { ForEachQueue(qd) { if (qd->conn) { // can occur if connection to dali threw exception if (writemode) { if (rollback) qd->conn->rollback(); else { qd->root->setPropInt("Edition",qd->root->getPropInt("Edition")+1); qd->conn->commit(); } } qd->conn->Release(); qd->conn = NULL; } qd->root = NULL; } writemode = false; } } void conncommit() // doesn't set edition { // called within sect if (writemode) { ForEachQueue(qd) { if (qd->conn) qd->conn->commit(); } } } class Cconnlockblock: public CriticalBlock { CJobQueue *parent; bool rollback; public: Cconnlockblock(CJobQueue *_parent,bool exclusive) : CriticalBlock(_parent->crit) { parent = _parent; parent->connlock(exclusive); rollback = false; } ~Cconnlockblock() { parent->connunlock(rollback); } void setRollback(bool set=true) { rollback = set; } void commit() { parent->conncommit(); } }; void removeItem(sQueueData &qd,IPropertyTree *item, bool cache) { // does not adjust or use @count unsigned n = item->getPropInt("@num"); if (!n) return; if (cache) { StringBuffer s; item->getProp("@wuid",s.clear()); qd.root->setProp("@prevwuid",s.str()); item->getProp("@enqueuedt",s.clear()); qd.root->setProp("@prevenqueuedt",s.str()); qd.root->setPropInt("@prevpriority",item->getPropInt("@priority")); } item->setPropInt("@num",-1); StringBuffer path; for (;;) { IPropertyTree *item2 = qd.root->queryPropTree(getItemPath(path.clear(),n).str()); if (!item2) break; item2->setPropInt("@num",n); n++; } qd.root->removeTree(item); } IPropertyTree *addItem(sQueueData &qd,IPropertyTree *item,unsigned idx,unsigned count) { // does not set any values other than num StringBuffer path; // first move following up unsigned n=count; while (n>idx) { n--; qd.root->queryPropTree(getItemPath(path.clear(),n).str())->setPropInt("@num",n+2); } item->setPropInt("@num",idx+1); return qd.root->addPropTree("Item",item); } void dosubscribe() { // called in crit section ForEachQueue(qd) { if (qd->subscriberid) { querySDS().unsubscribe(qd->subscriberid); qd->subscriberid = 0; } StringBuffer path; path.appendf("/JobQueues/Queue[@name=\"%s\"]/Edition",qd->qname.get()); qd->subscriberid = querySDS().subscribe(path.str(), subs, false); } } bool haschanged() // returns if any changed { bool changed = false; ForEachQueue(qd) { if (!qd->subscriberid) { StringBuffer path; path.appendf("/JobQueues/Queue[@name=\"%s\"]/Edition",qd->qname.get()); qd->subscriberid = querySDS().subscribe(path.str(), subs, false); } unsigned e = (unsigned)qd->root->getPropInt("Edition", 1); if (e!=qd->lastWaitEdition) { qd->lastWaitEdition = e; changed = true; break; } } return changed; } void dounsubscribe() { // called in crit section ForEachQueue(qd) { if (qd->subscriberid) { querySDS().unsubscribe(qd->subscriberid); qd->subscriberid = 0; } } } IPropertyTree *queryClientRootSession(sQueueData &qd) { VStringBuffer path("Client[@session=\"%" I64F "d\"]", sessionid); IPropertyTree *ret = qd.root->queryPropTree(path.str()); if (!ret) { ret = qd.root->addPropTree("Client"); ret->setPropInt64("@session",sessionid); StringBuffer eps; ret->setProp("@node",queryMyNode()->endpoint().getUrlStr(eps).str()); } return ret; } void connect(bool _validateitemsessions) { Cconnlockblock block(this,true); validateitemsessions = _validateitemsessions; if (connected) disconnect(); dosubscribe(); ForEachQueue(qd) { if (validateitemsessions) { unsigned connected; unsigned waiting; unsigned count; getStats(*qd,connected,waiting,count); // clear any duff clients } IPropertyTree *croot = queryClientRootSession(*qd); croot->setPropInt64("@connected",croot->getPropInt64("@connected",0)+1); } connected = true; } void disconnect() // signal no longer wil be dequeing (optional - done automatically on release) { Cconnlockblock block(this,true); if (connected) { dounsubscribe(); ForEachQueue(qd) { IPropertyTree *croot = queryClientRootSession(*qd); croot->setPropInt64("@connected",croot->getPropInt64("@connected",0)-1); } connected = false; } } sQueueData *findbestqueue(bool useprev,int minprio,unsigned numqueues,sQueueData **queues) { if (numqueues==0) return NULL; if (numqueues==1) return *queues; sQueueData *best = NULL; IPropertyTree *bestt = NULL; for (unsigned i=0;i<numqueues;i++) { sQueueData *qd = queues[i]; unsigned count = qd->root->getPropInt("@count"); if (count) { int mpr = useprev?std::max(qd->root->getPropInt("@prevpriority"),minprio):minprio; if (count&&((minprio==INT_MIN)||checkprio(*qd,mpr))) { StringBuffer path; IPropertyTree *item = qd->root->queryPropTree(getItemPath(path,0U).str()); if (!item) continue; if (item->getPropInt("@num",0)<=0) continue; CDateTime dt; StringBuffer enqueued; if (!best||itemOlder(item,bestt)) { best = qd; bestt = item; } } } } return best; } void setWaiting(unsigned numqueues,sQueueData **queues, bool set) { for (unsigned i=0; i<numqueues; i++) { IPropertyTree *croot = queryClientRootSession(*queues[i]); croot->setPropInt64("@waiting",croot->getPropInt64("@waiting",0)+(set?1:-1)); } } // 'simple' queuing IJobQueueItem *dodequeue(int minprio,unsigned timeout=INFINITE, bool useprev=false, bool *timedout=NULL) { bool hasminprio=(minprio!=INT_MIN); if (timedout) *timedout = false; IJobQueueItem *ret=NULL; bool waitingset = false; while (!dequeuestop) { unsigned t = 0; if (timeout!=(unsigned)INFINITE) t = msTick(); { Cconnlockblock block(this,true); block.setRollback(true); // assume not going to update // now cycle through queues looking at state unsigned total = 0; unsigned stopped = 0; PointerArray active; ForEachQueue(qd) { total++; const char *state = qd->root->queryProp("@state"); if (state) { if (strcmp(state,"stopped")==0) stopped++; else if (strcmp(state,"paused")!=0) active.append(qd); } else active.append(qd); } if (stopped==total) return NULL; // all stopped sQueueData **activeqds = (sQueueData **)active.getArray(); unsigned activenum = active.ordinality(); if (activenum) { sQueueData *bestqd = findbestqueue(useprev,minprio,activenum,activeqds); unsigned count = bestqd?bestqd->root->getPropInt("@count"):0; // load minp from cache if (count) { int mpr = useprev?std::max(bestqd->root->getPropInt("@prevpriority"),minprio):minprio; if (!hasminprio||checkprio(*bestqd,mpr)) { block.setRollback(false); ret = dotake(*bestqd,NULL,true,hasminprio,mpr); if (ret) // think it must be! timeout = 0; // so mark that done else if (!hasminprio) { WARNLOG("Resetting queue %s",bestqd->qname.get()); clear(*bestqd); // reset queue as seems to have become out of sync } } } if (timeout!=0) { // more to do if (!connected) { // if connect already done non-zero connect(validateitemsessions); block.setRollback(false); } if (!waitingset) { setWaiting(activenum,activeqds,true); block.commit(); waitingset = true; } } } if (timeout==0) { if (waitingset) { setWaiting(activenum,activeqds,false); block.commit(); } if (timedout) *timedout = (ret==NULL); break; } } unsigned to = 5*60*1000; // check every 5 mins independant of notify (in case subscription lost for some reason) if (to>timeout) to = timeout; notifysem.wait(to); if (timeout!=(unsigned)INFINITE) { t = msTick()-t; if (t<timeout) timeout -= t; else timeout = 0; } } return ret; } IJobQueueItem *dequeue(unsigned timeout=INFINITE) { return dodequeue(INT_MIN,timeout); } IJobQueueItem *prioDequeue(int minprio,unsigned timeout=INFINITE) // minprio == MAX_INT - used cache priority { return dodequeue(minprio,timeout); } void placeonqueue(sQueueData &qd, IJobQueueItem *qitem,unsigned idx) // takes ownership of qitem { Owned<IJobQueueItem> qi = qitem; remove(qi->queryWUID()); // just in case trying to put on twice! int priority = qi->getPriority(); unsigned count = qd.root->getPropInt("@count"); StringBuffer path; if (count&&(idx!=(unsigned)-1)) { // need to check before and after if (idx) { IPropertyTree *pt = qd.root->queryPropTree(getItemPath(path.clear(),idx-1).str()); if (pt) { int pp = pt->getPropInt("@priority"); if (priority>pp) { qi->setPriority(pp); priority = pp; } } else // what happened here? idx = (unsigned)-1; } if (idx<count) { IPropertyTree *pt = qd.root->queryPropTree(getItemPath(path.clear(),idx).str()); if (pt) { int pp = pt->getPropInt("@priority"); if (priority<pp) { qi->setPriority(pp); priority = pp; } } else // what happened here? idx = (unsigned)-1; } } if (idx==(unsigned)-1) { idx = count; while (idx) { IPropertyTree *previtem = qd.root->queryPropTree(getItemPath(path.clear(),idx-1).str()); if (previtem) { if (previtem->getPropInt("@priority")>=priority) { break; } } else count--; // how did that happen? idx--; } } CJobQueueItem::assignBranch(addItem(qd,createPTree("Item"),idx,count),qi); qd.root->setPropInt("@count",count+1); } void enqueue(sQueueData &qd,IJobQueueItem *qitem) // takes ownership of qitem { Cconnlockblock block(this,true); placeonqueue(qd,qitem,(unsigned)-1); } void enqueueBefore(sQueueData &qd,IJobQueueItem *qitem,const char *wuid) { Cconnlockblock block(this,true); placeonqueue(qd,qitem,doFindRank(qd,wuid)); } void enqueueAfter(sQueueData &qd,IJobQueueItem *qitem,const char *wuid) { Cconnlockblock block(this,true); unsigned idx = doFindRank(qd,wuid); if (idx!=(unsigned)-1) idx++; placeonqueue(qd,qitem,idx); } void enqueueTail(sQueueData &qd,IJobQueueItem *qitem) { Cconnlockblock block(this,true); Owned<IJobQueueItem> qi = getTail(qd); if (qi) enqueueAfter(qd,qitem,qi->queryWUID()); else enqueue(qd,qitem); } void enqueueHead(sQueueData &qd,IJobQueueItem *qitem) { Cconnlockblock block(this,true); Owned<IJobQueueItem> qi = doGetItem(qd, 0); if (qi) enqueueBefore(qd,qitem,qi->queryWUID()); else enqueue(qd,qitem); } unsigned ordinality(sQueueData &qd) { Cconnlockblock block(this,false); return qd.root->getPropInt("@count"); } IJobQueueItem *getTail(sQueueData &qd) { return doGetItem(qd,(unsigned)-1); } IJobQueueItem *loadItem(sQueueData &qd,IJobQueueItem *qi) { Cconnlockblock block(this,false); StringBuffer path; IPropertyTree *item = qd.root->queryPropTree(getItemPath(path,qi->queryWUID()).str()); if (!item) return NULL; bool cached = item->getPropInt("@num",0)<=0; if (cached) return NULL; // don't want cached value return new CJobQueueItem(item); } bool checkprio(sQueueData &qd,int minprio=0) { StringBuffer path; IPropertyTree *item = qd.root->queryPropTree(getItemPath(path,0U).str()); if (!item) return false; return (item->getPropInt("@priority")>=minprio); } IJobQueueItem *dotake(sQueueData &qd,const char *wuid,bool saveitem,bool hasminprio=false,int minprio=0) { StringBuffer path; IPropertyTree *item = qd.root->queryPropTree(getItemPath(path,wuid).str()); if (!item) return NULL; if (item->getPropInt("@num",0)<=0) return NULL; // don't want (old) cached value if (hasminprio&&(item->getPropInt("@priority")<minprio)) return NULL; IJobQueueItem *ret = new CJobQueueItem(item); removeItem(qd,item,saveitem); unsigned count = qd.root->getPropInt("@count"); assertex(count); qd.root->setPropInt("@count",count-1); return ret; } IJobQueueItem *take(sQueueData &qd,const char *wuid) { Cconnlockblock block(this,true); return dotake(qd,wuid,false); } unsigned takeItems(sQueueData &qd,CJobQueueContents &dest) { Cconnlockblock block(this,true); unsigned ret = copyItemsImpl(qd,dest); clear(qd); return ret; } void enqueueItems(sQueueData &qd,CJobQueueContents &items) { unsigned n=items.ordinality(); if (n) { Cconnlockblock block(this,true); for (unsigned i=0;i<n;i++) enqueue(qd,items.item(i).clone()); } } void enqueueBefore(IJobQueueItem *qitem,const char *wuid) { Cconnlockblock block(this,true); sQueueData *qd = qdata->next?findQD(wuid):qdata; enqueueBefore(*qd,qitem,wuid); } void enqueueAfter(IJobQueueItem *qitem,const char *wuid) { Cconnlockblock block(this,true); sQueueData *qd = qdata->next?findQD(wuid):qdata; enqueueAfter(*qd,qitem,wuid); } bool moveBefore(const char *wuid,const char *nextwuid) { if (!qdata) return false; Cconnlockblock block(this,true); sQueueData *qd = qdata->next?findQD(wuid):qdata; if (!qd) return false; IJobQueueItem *qi=take(*qd,wuid); if (!qi) return false; sQueueData *qdd = NULL; if (qdata->next) qdd = findQD(nextwuid); if (!qdd) qdd = qd; enqueueBefore(*qdd,qi,nextwuid); return true; } bool moveAfter(const char *wuid,const char *prevwuid) { if (!qdata) return false; Cconnlockblock block(this,true); sQueueData *qd = qdata->next?findQD(wuid):qdata; if (!qd) return false; IJobQueueItem *qi=take(*qd,wuid); if (!qi) return false; sQueueData *qdd = NULL; if (qdata->next) qdd = findQD(prevwuid); if (!qdd) qdd = qd; enqueueAfter(*qdd,qi,prevwuid); return true; } bool moveToHead(const char *wuid) { if (!qdata) return false; Cconnlockblock block(this,true); sQueueData *qd = qdata->next?findQD(wuid):qdata; if (!qd) return false; IJobQueueItem *qi=take(*qd,wuid); if (!qi) return false; enqueueHead(*qd,qi); return true; } bool moveToTail(const char *wuid) { if (!qdata) return false; Cconnlockblock block(this,true); sQueueData *qd = qdata->next?findQD(wuid):qdata; if (!qd) return false; IJobQueueItem *qi=take(*qd,wuid); if (!qi) return false; enqueueTail(*qd,qi); return true; } bool remove(const char *wuid) { if (!qdata) return false; Cconnlockblock block(this,true); sQueueData *qd = qdata->next?findQD(wuid):qdata; if (!qd) return false; StringBuffer path; IPropertyTree *item = qd->root->queryPropTree(getItemPath(path,wuid).str()); if (!item) return false; bool cached = item->getPropInt("@num",0)<=0; // old cached (bwd compat) removeItem(*qd,item,false); if (!cached) { unsigned count = qd->root->getPropInt("@count"); assertex(count); qd->root->setPropInt("@count",count-1); } return true; } bool changePriority(const char *wuid,int value) { if (!qdata) return false; Cconnlockblock block(this,true); sQueueData *qd = qdata->next?findQD(wuid):qdata; if (!qd) return false; IJobQueueItem *qi=take(*qd,wuid); if (!qi) { StringBuffer ws("~"); // change cached item ws.append(wuid); StringBuffer path; IPropertyTree *item = qd->root->queryPropTree(getItemPath(path,ws.str()).str()); if (item) { item->setPropInt("@priority",value); return true; } return false; } qi->setPriority(value); enqueue(*qd,qi); return true; } void clear(sQueueData &qd) { Cconnlockblock block(this,true); qd.root->setPropInt("@count",0); for (;;) { IPropertyTree *item = qd.root->queryPropTree("Item[1]"); if (!item) break; qd.root->removeTree(item); } } void lock() { connlock(false); // sub functions will change to exclusive if needed } void unlock(bool rollback=false) { connunlock(rollback); } void pause(sQueueData &qd) { Cconnlockblock block(this,true); qd.root->setProp("@state","paused"); } void resume(sQueueData &qd) { Cconnlockblock block(this,true); qd.root->setProp("@state","active"); } bool paused(sQueueData &qd) { Cconnlockblock block(this,false); const char *state = qd.root->queryProp("@state"); return (state&&(strcmp(state,"paused")==0)); } void stop(sQueueData &qd) { Cconnlockblock block(this,true); qd.root->setProp("@state","stopped"); } bool stopped(sQueueData &qd) { Cconnlockblock block(this,false); const char *state = qd.root->queryProp("@state"); return (state&&(strcmp(state,"stopped")==0)); } void doGetStats(sQueueData &qd,unsigned &connected,unsigned &waiting,unsigned &enqueued) { Cconnlockblock block(this,false); connected = 0; waiting = 0; unsigned i=0; for (;;) { IPropertyTree *croot = queryClientRootIndex(qd,i); if (!croot) break; if (validateitemsessions && !validSession(croot)) { Cconnlockblock block(this,true); qd.root->removeTree(croot); } else { waiting += croot->getPropInt("@waiting"); connected += croot->getPropInt("@connected"); i++; } } // now remove any duff queue items unsigned count = qd.root->getPropInt("@count"); if (!validateitemsessions) { enqueued = count; return; } i=0; StringBuffer path; for (;;) { IPropertyTree *item = qd.root->queryPropTree(getItemPath(path.clear(),i).str()); if (!item) break; if (!validSession(item)) { Cconnlockblock block(this,true); item = qd.root->queryPropTree(path.str()); if (!item) break; // PROGLOG("WUJOBQ: Removing %s as session %" I64F "x not active",item->queryProp("@wuid"),item->getPropInt64("@session")); removeItem(qd,item,false); } else i++; } if (count!=i) { Cconnlockblock block(this,true); qd.root->setPropInt("@count",i); } enqueued = i; } void getStats(sQueueData &qd,unsigned &connected,unsigned &waiting,unsigned &enqueued) { Cconnlockblock block(this,false); doGetStats(qd,connected,waiting,enqueued); } void getStats(unsigned &connected,unsigned &waiting,unsigned &enqueued) { // multi queue Cconnlockblock block(this,false); connected=0; waiting=0; enqueued=0; ForEachQueue(qd) { unsigned c; unsigned w; unsigned e; doGetStats(*qd,c,w,e); connected+=c; waiting+=w; enqueued+=e; } } IJobQueueItem *take(const char *wuid) { assertex(qdata); if (!qdata->next) return take(*qdata,wuid); Cconnlockblock block(this,true); ForEachQueue(qd) { IJobQueueItem *ret = dotake(*qd,wuid,false); if (ret) return ret; } return NULL; } unsigned takeItems(CJobQueueContents &dest) { assertex(qdata); if (!qdata->next) return takeItems(*qdata,dest); Cconnlockblock block(this,true); unsigned ret = 0; ForEachQueue(qd) { ret += copyItemsImpl(*qd,dest); clear(*qd); } return ret; } void enqueueItems(CJobQueueContents &items) { // enqueues to firs sub-queue (not sure that useful) assertex(qdata); return enqueueItems(*qdata,items); } void clear() { ForEachQueue(qd) { clear(*qd); } } bool validSession(IPropertyTree *item) { Owned<INode> node = createINode(item->queryProp("@node"),DALI_SERVER_PORT); // port should always be present return (querySessionManager().lookupProcessSession(node)==(SessionId)item->getPropInt64("@session")); } IConversation *initiateConversation(sQueueData &qd,IJobQueueItem *item) { CriticalBlock block(crit); assertex(!initiateconv.get()); SocketEndpoint ep = item->queryEndpoint(); unsigned short port = (unsigned short)item->getPort(); #if defined(_USE_OPENSSL) if (queryMtls()) initiateconv.setown(createSingletonSecureSocketConnection(port)); else #endif initiateconv.setown(createSingletonSocketConnection(port)); if (!port) item->setPort(initiateconv->setRandomPort(WUJOBQ_BASE_PORT,WUJOBQ_PORT_NUM)); initiatewu.set(item->queryWUID()); enqueue(qd,item); bool ok; { CriticalUnblock unblock(crit); ok = initiateconv->accept(INFINITE); } if (!ok) initiateconv.clear(); return initiateconv.getClear(); } IConversation *acceptConversation(IJobQueueItem *&retitem, unsigned prioritytransitiondelay,IDynamicPriority *maxp) { CriticalBlock block(crit); retitem = NULL; assertex(connected); // must be connected int curmp = maxp?maxp->get():0; int nextmp = curmp; for (;;) { bool timedout = false; Owned<IJobQueueItem> item; { CriticalUnblock unblock(crit); // this is a bit complicated with multi-thor if (prioritytransitiondelay||maxp) { item.setown(dodequeue((std::max(curmp,nextmp)/10)*10, // round down to multiple of 10 prioritytransitiondelay?prioritytransitiondelay:60000,prioritytransitiondelay>0,&timedout)); // if dynamic priority check every minute if (!prioritytransitiondelay) { curmp = nextmp; // using max above is a bit devious to allow transition nextmp = maxp->get(); } } else item.setown(dequeue(INFINITE)); } if (item.get()) { if (item->isValidSession()) { SocketEndpoint ep = item->queryEndpoint(); ep.port = item->getPort(); Owned<IConversation> acceptconv; #if defined(_USE_OPENSSL) if (queryMtls()) acceptconv.setown(createSingletonSecureSocketConnection(ep.port,&ep)); else #endif acceptconv.setown(createSingletonSocketConnection(ep.port,&ep)); if (acceptconv->connect(3*60*1000)) { // shouldn't need that long retitem = item.getClear(); return acceptconv.getClear(); } } } else if (prioritytransitiondelay) prioritytransitiondelay = 0; else if (!timedout) break; } return NULL; } void cancelInitiateConversation(sQueueData &qd) { CriticalBlock block(crit); if (initiatewu.get()) remove(initiatewu); if (initiateconv.get()) initiateconv->cancel(); } void cancelAcceptConversation() { CriticalBlock block(crit); dequeuestop = true; notifysem.signal(); } bool cancelInitiateConversation(sQueueData &qd,const char *wuid) { Cconnlockblock block(this,true); for (;;) { Owned<IJobQueueItem> item = dotake(qd,wuid,false); if (!item.get()) break; if (item->isValidSession()) { SocketEndpoint ep = item->queryEndpoint(); ep.port = item->getPort(); Owned<IConversation> acceptconv; #if defined(_USE_OPENSSL) if (queryMtls()) acceptconv.setown(createSingletonSecureSocketConnection(ep.port,&ep)); else #endif acceptconv.setown(createSingletonSocketConnection(ep.port,&ep)); acceptconv->connect(3*60*1000); // connect then close should close other end return true; } } return false; } bool waitStatsChange(unsigned timeout) { assertex(!connected); // not allowed to call this while connected cancelwaiting = false; while(!cancelwaiting) { { Cconnlockblock block(this,false); if (haschanged()) return true; } if (!notifysem.wait(timeout)) break; } return false; } void cancelWaitStatsChange() { CriticalBlock block(crit); cancelwaiting = true; notifysem.signal(); } virtual void enqueue(IJobQueueItem *qitem) { enqueue(*activeq,qitem); } void enqueueHead(IJobQueueItem *qitem) { enqueueHead(*activeq,qitem); } void enqueueTail(IJobQueueItem *qitem) { enqueueTail(*activeq,qitem); } void pause() { Cconnlockblock block(this,true); ForEachQueue(qd) { if (qd->root) qd->root->setProp("@state","paused"); } } void pause(const char* info) { Cconnlockblock block(this,true); ForEachQueue(qd) { if (qd->root) { qd->root->setProp("@state","paused"); if (info && *info) qd->root->setProp("@stateDetails",info); } } } void stop() { Cconnlockblock block(this,true); ForEachQueue(qd) { if (qd->root) qd->root->setProp("@state","stopped"); } } void stop(const char* info) { Cconnlockblock block(this,true); ForEachQueue(qd) { if (qd->root) { qd->root->setProp("@state","stopped"); if (info && *info) qd->root->setProp("@stateDetails",info); } } } void resume() { Cconnlockblock block(this,true); ForEachQueue(qd) { if (qd->root) qd->root->setProp("@state","active"); } } void resume(const char* info) { Cconnlockblock block(this,true); ForEachQueue(qd) { if (qd->root) { qd->root->setProp("@state","active"); if (info && *info) qd->root->setProp("@stateDetails",info); } } } IConversation *initiateConversation(IJobQueueItem *item) { return initiateConversation(*activeq,item); } void cancelInitiateConversation() { return cancelInitiateConversation(*activeq); } bool cancelInitiateConversation(const char *wuid) { return cancelInitiateConversation(*activeq,wuid); } const char * queryActiveQueueName() { return activeq->qname; } void setActiveQueue(const char *name) { ForEachQueue(qd) { if (!name||(strcmp(qd->qname.get(),name)==0)) { activeq = qd; return; } } if (name) throw MakeStringException (-1,"queue %s not found",name); } const char *nextQueueName(const char *last) { ForEachQueue(qd) { if (!last||(strcmp(qd->qname.get(),last)==0)) { if (qd->next) return qd->next->qname.get(); break; } } return NULL; } virtual bool paused() { Cconnlockblock block(this,false); return CJobQueueBase::paused(); } virtual bool paused(StringBuffer& info) { Cconnlockblock block(this,false); return CJobQueueBase::paused(info); } virtual bool stopped() { Cconnlockblock block(this,false); return CJobQueueBase::stopped(); } virtual bool stopped(StringBuffer& info) { Cconnlockblock block(this,false); return CJobQueueBase::stopped(info); } virtual unsigned ordinality() { Cconnlockblock block(this,false); return CJobQueueBase::ordinality(); } virtual unsigned waiting() { Cconnlockblock block(this,false); return CJobQueueBase::waiting(); } virtual IJobQueueItem *getItem(unsigned idx) { Cconnlockblock block(this,false); return CJobQueueBase::getItem(idx); } virtual IJobQueueItem *getHead() { Cconnlockblock block(this,false); return CJobQueueBase::getHead(); } virtual IJobQueueItem *getTail() { Cconnlockblock block(this,false); return CJobQueueBase::getTail(); } virtual IJobQueueItem *find(const char *wuid) { Cconnlockblock block(this,false); return CJobQueueBase::find(wuid); } virtual unsigned findRank(const char *wuid) { Cconnlockblock block(this,false); return CJobQueueBase::findRank(wuid); } virtual unsigned copyItems(CJobQueueContents &dest) { Cconnlockblock block(this,false); return CJobQueueBase::copyItems(dest); } virtual bool getLastDequeuedInfo(StringAttr &wuid, CDateTime &enqueuedt, int &priority) { Cconnlockblock block(this,false); return CJobQueueBase::doGetLastDequeuedInfo(activeq, wuid, enqueuedt, priority); } virtual void copyItemsAndState(CJobQueueContents& contents, StringBuffer& state, StringBuffer& stateDetails) { Cconnlockblock block(this,false); CJobQueueBase::copyItemsAndState(contents, state, stateDetails); } virtual void getState(StringBuffer& state, StringBuffer& stateDetails) { Cconnlockblock block(this,false); CJobQueueBase::getState(state, stateDetails); } }; class CJQSnapshot : public CInterface, implements IJQSnapshot { Owned<IPropertyTree> jobQueueInfo; public: IMPLEMENT_IINTERFACE; CJQSnapshot() { Owned<IRemoteConnection> connJobQueues = querySDS().connect("/JobQueues", myProcessSession(), RTM_LOCK_READ, 30000); if (!connJobQueues) throw MakeStringException(-1, "CJQSnapshot::CJQSnapshot: /JobQueues not found"); jobQueueInfo.setown(createPTreeFromIPT(connJobQueues->queryRoot())); } IJobQueueConst* getJobQueue(const char *name) { if (!jobQueueInfo) return NULL; return new CJobQueueConst(name, jobQueueInfo.getLink()); } }; IJQSnapshot *createJQSnapshot() { return new CJQSnapshot(); } IJobQueue *createJobQueue(const char *name) { if (!name||!*name) throw MakeStringException(-1,"createJobQueue empty name"); return new CJobQueue(name); } extern bool WORKUNIT_API runWorkUnit(const char *wuid, const char *queueName) { #ifdef _CONTAINERIZED StringBuffer agentQueue; getClusterEclAgentQueueName(agentQueue, queueName); #else //NB: In the non-container system the name of the roxie agent queue does not follow the convention for the containerized system Owned<IConstWUClusterInfo> clusterInfo = getTargetClusterInfo(queueName); if (!clusterInfo.get()) return false; SCMStringBuffer agentQueue; clusterInfo->getAgentQueue(agentQueue); if (!agentQueue.length()) return false; #endif Owned<IJobQueue> queue = createJobQueue(agentQueue.str()); if (!queue.get()) throw MakeStringException(-1, "Could not create workunit queue"); IJobQueueItem *item = createJobQueueItem(wuid); queue->enqueue(item); PROGLOG("Agent request '%s' enqueued on '%s'", wuid, agentQueue.str()); return true; } extern bool WORKUNIT_API runWorkUnit(const char *wuid) { Owned<IWorkUnitFactory> factory = getWorkUnitFactory(); Owned<IConstWorkUnit> w = factory->openWorkUnit(wuid); if (w) { StringAttr clusterName = (w->queryClusterName()); w.clear(); return runWorkUnit(wuid, clusterName.str()); } else return false; } extern WORKUNIT_API StringBuffer &getQueuesContainingWorkUnit(const char *wuid, StringBuffer &queueList) { Owned<IRemoteConnection> conn = querySDS().connect("/JobQueues", myProcessSession(), RTM_LOCK_READ, 5000); if (!conn) return queueList; VStringBuffer xpath("Queue[Item/@wuid='%s']", wuid); Owned<IPropertyTreeIterator> it = conn->getElements(xpath.str()); ForEach(*it) { if (queueList.length()) queueList.append(','); queueList.append(it->query().queryProp("@name")); } return queueList; } extern void WORKUNIT_API removeWorkUnitFromAllQueues(const char *wuid) { StringBuffer queueList; if (!getQueuesContainingWorkUnit(wuid, queueList).length()) return; Owned<IJobQueue> q = createJobQueue(queueList.str()); if (q) while(q->remove(wuid)); } extern bool WORKUNIT_API switchWorkUnitQueue(IWorkUnit* wu, const char *cluster) { if (!wu) return false; class cQswitcher: public CInterface, implements IQueueSwitcher { public: IMPLEMENT_IINTERFACE; void * getQ(const char * qname, const char * wuid) { Owned<IJobQueue> q = createJobQueue(qname); return q->take(wuid); } void putQ(const char * qname, const char * wuid, void * qitem) { Owned<IJobQueue> q = createJobQueue(qname); q->enqueue((IJobQueueItem *)qitem); } bool isAuto() { return false; } } switcher; return wu->switchThorQueue(cluster, &switcher); }
64,956
19,447
/* * Copyright (c) 2020 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // CLASS HEADER #include <dali-toolkit/public-api/controls/scrollable/scroll-view/scroll-view.h> // EXTERNAL INCLUDES #include <dali/integration-api/debug.h> // INTERNAL INCLUDES #include <dali-toolkit/internal/controls/scrollable/scroll-view/scroll-view-impl.h> #include <dali-toolkit/public-api/controls/scrollable/scrollable.h> using namespace Dali; namespace Dali { namespace Toolkit { /////////////////////////////////////////////////////////////////////////////////////////////////// // RulerDomain /////////////////////////////////////////////////////////////////////////////////////////////////// RulerDomain::RulerDomain(float min, float max, bool enabled) : min(min), max(max), enabled(enabled) { } float RulerDomain::Clamp(float x, float length, float scale) const { ClampState clamped; return Clamp(x, length, scale, clamped); } float RulerDomain::Clamp(float x, float length, float scale, ClampState& clamped) const { if(!enabled) { clamped = NOT_CLAMPED; return x; } const float minExtent = min * scale; const float maxExtent = max * scale - length; if(x < minExtent) { clamped = CLAMPED_TO_MIN; return minExtent; } else if(x > maxExtent) { clamped = CLAMPED_TO_MAX; return maxExtent; } clamped = NOT_CLAMPED; return x; } float RulerDomain::GetSize() const { return max - min; } /////////////////////////////////////////////////////////////////////////////////////////////////// // Ruler /////////////////////////////////////////////////////////////////////////////////////////////////// Ruler::Ruler() : mType(FREE), mEnabled(true), mDomain(RulerDomain(0.0f, 1.0f, false)) { } Ruler::~Ruler() { } Ruler::RulerType Ruler::GetType() const { return mType; } bool Ruler::IsEnabled() const { return mEnabled; } void Ruler::Enable() { mEnabled = true; } void Ruler::Disable() { mEnabled = false; } void Ruler::SetDomain(RulerDomain domain) { mDomain = domain; } const RulerDomain& Ruler::GetDomain() const { return mDomain; } void Ruler::DisableDomain() { mDomain = RulerDomain(0.0f, 1.0f, false); } float Ruler::Clamp(float x, float length, float scale) const { return mDomain.Clamp(x, length, scale); } float Ruler::Clamp(float x, float length, float scale, ClampState& clamped) const { return mDomain.Clamp(x, length, scale, clamped); } float Ruler::SnapAndClamp(float x, float bias, float length, float scale) const { return Clamp(Snap(x, bias), length, scale); } float Ruler::SnapAndClamp(float x, float bias, float length, float scale, ClampState& clamped) const { return Clamp(Snap(x, bias), length, scale, clamped); } /////////////////////////////////////////////////////////////////////////////////////////////////// // DefaultRuler /////////////////////////////////////////////////////////////////////////////////////////////////// DefaultRuler::DefaultRuler() { mType = FREE; } float DefaultRuler::Snap(float x, float bias) const { return x; } float DefaultRuler::GetPositionFromPage(unsigned int page, unsigned int& volume, bool wrap) const { volume = 0; return 0.0f; } unsigned int DefaultRuler::GetPageFromPosition(float position, bool wrap) const { return 0; } unsigned int DefaultRuler::GetTotalPages() const { return 1; } /////////////////////////////////////////////////////////////////////////////////////////////////// // FixedRuler /////////////////////////////////////////////////////////////////////////////////////////////////// FixedRuler::FixedRuler(float spacing) : mSpacing(spacing) { if(fabsf(mSpacing) <= Math::MACHINE_EPSILON_1) { DALI_LOG_ERROR("Page spacing too small (%f).\n", double(spacing)); mSpacing = spacing >= 0.0f ? Math::MACHINE_EPSILON_1 : -Math::MACHINE_EPSILON_1; } mType = FIXED; } float FixedRuler::Snap(float x, float bias) const { return floor(x / mSpacing + bias) * mSpacing; } float FixedRuler::GetPositionFromPage(unsigned int page, unsigned int& volume, bool wrap) const { float position = mDomain.min; volume = 0; // spacing must be present. if(mEnabled) { unsigned int column = page; // In carry mode, a volume (carry) is produced when page exceeds limit within domain if(wrap) { unsigned int pagesPerVolume = mDomain.GetSize() / mSpacing; if(pagesPerVolume > 0) { column += pagesPerVolume; column %= pagesPerVolume; volume = page / pagesPerVolume; } } position = mDomain.min + column * mSpacing; } else // Domain (or Spacing) is not present, carry page to volume. { if(wrap) { volume = page; } } return position; } unsigned int FixedRuler::GetPageFromPosition(float position, bool wrap) const { unsigned int page = 0; // spacing must be present. if(mEnabled) { if(wrap) { position = WrapInDomain(position, mDomain.min, mDomain.max); } page = std::max(static_cast<double>(0.0f), static_cast<double>(floor((position - mDomain.min) / mSpacing + 0.5f))); if(wrap) { unsigned int pagesPerVolume = mDomain.GetSize() / mSpacing; // Defensive check to avoid a divide by zero below when the ruler is in an invalid state (entire domain smaller than spacing between pages of it): if(pagesPerVolume < 1u) { pagesPerVolume = 1u; DALI_LOG_ERROR("Ruler domain(%f) is smaller than its spacing(%f).\n", mDomain.GetSize() * 1.0, mSpacing * 1.0); } page %= pagesPerVolume; } } return page; } unsigned int FixedRuler::GetTotalPages() const { unsigned int pagesPerVolume = 1; // spacing must be present. if(mEnabled) { pagesPerVolume = mDomain.GetSize() / mSpacing; } return pagesPerVolume; } /////////////////////////////////////////////////////////////////////////////////////////////////// // ScrollView /////////////////////////////////////////////////////////////////////////////////////////////////// ScrollView::ScrollView() { } ScrollView::ScrollView(Internal::ScrollView& implementation) : Scrollable(implementation) { } ScrollView::ScrollView(Dali::Internal::CustomActor* internal) : Scrollable(internal) { VerifyCustomActorPointer<Internal::ScrollView>(internal); } ScrollView::ScrollView(const ScrollView& handle) = default; ScrollView::ScrollView(ScrollView&& rhs) = default; ScrollView& ScrollView::operator=(const ScrollView& handle) = default; ScrollView& ScrollView::operator=(ScrollView&& rhs) = default; ScrollView ScrollView::New() { return Internal::ScrollView::New(); } ScrollView::~ScrollView() { } ScrollView ScrollView::DownCast(BaseHandle handle) { return Control::DownCast<ScrollView, Internal::ScrollView>(handle); } AlphaFunction ScrollView::GetScrollSnapAlphaFunction() const { return GetImpl(*this).GetScrollSnapAlphaFunction(); } void ScrollView::SetScrollSnapAlphaFunction(AlphaFunction alpha) { GetImpl(*this).SetScrollSnapAlphaFunction(alpha); } AlphaFunction ScrollView::GetScrollFlickAlphaFunction() const { return GetImpl(*this).GetScrollFlickAlphaFunction(); } void ScrollView::SetScrollFlickAlphaFunction(AlphaFunction alpha) { GetImpl(*this).SetScrollFlickAlphaFunction(alpha); } float ScrollView::GetScrollSnapDuration() const { return GetImpl(*this).GetScrollSnapDuration(); } void ScrollView::SetScrollSnapDuration(float time) { GetImpl(*this).SetScrollSnapDuration(time); } float ScrollView::GetScrollFlickDuration() const { return GetImpl(*this).GetScrollFlickDuration(); } void ScrollView::SetScrollFlickDuration(float time) { GetImpl(*this).SetScrollFlickDuration(time); } void ScrollView::SetRulerX(RulerPtr ruler) { GetImpl(*this).SetRulerX(ruler); } void ScrollView::SetRulerY(RulerPtr ruler) { GetImpl(*this).SetRulerY(ruler); } void ScrollView::SetScrollSensitive(bool sensitive) { GetImpl(*this).SetScrollSensitive(sensitive); } void ScrollView::SetMaxOvershoot(float overshootX, float overshootY) { GetImpl(*this).SetMaxOvershoot(overshootX, overshootY); } void ScrollView::SetSnapOvershootAlphaFunction(AlphaFunction alpha) { GetImpl(*this).SetSnapOvershootAlphaFunction(alpha); } void ScrollView::SetSnapOvershootDuration(float duration) { GetImpl(*this).SetSnapOvershootDuration(duration); } void ScrollView::SetActorAutoSnap(bool enable) { GetImpl(*this).SetActorAutoSnap(enable); } void ScrollView::SetWrapMode(bool enable) { GetImpl(*this).SetWrapMode(enable); } int ScrollView::GetScrollUpdateDistance() const { return GetImpl(*this).GetScrollUpdateDistance(); } void ScrollView::SetScrollUpdateDistance(int distance) { GetImpl(*this).SetScrollUpdateDistance(distance); } bool ScrollView::GetAxisAutoLock() const { return GetImpl(*this).GetAxisAutoLock(); } void ScrollView::SetAxisAutoLock(bool enable) { GetImpl(*this).SetAxisAutoLock(enable); } float ScrollView::GetAxisAutoLockGradient() const { return GetImpl(*this).GetAxisAutoLockGradient(); } void ScrollView::SetAxisAutoLockGradient(float gradient) { GetImpl(*this).SetAxisAutoLockGradient(gradient); } float ScrollView::GetFrictionCoefficient() const { return GetImpl(*this).GetFrictionCoefficient(); } void ScrollView::SetFrictionCoefficient(float friction) { GetImpl(*this).SetFrictionCoefficient(friction); } float ScrollView::GetFlickSpeedCoefficient() const { return GetImpl(*this).GetFlickSpeedCoefficient(); } void ScrollView::SetFlickSpeedCoefficient(float speed) { GetImpl(*this).SetFlickSpeedCoefficient(speed); } Vector2 ScrollView::GetMinimumDistanceForFlick() const { return GetImpl(*this).GetMinimumDistanceForFlick(); } void ScrollView::SetMinimumDistanceForFlick(const Vector2& distance) { GetImpl(*this).SetMinimumDistanceForFlick(distance); } float ScrollView::GetMinimumSpeedForFlick() const { return GetImpl(*this).GetMinimumSpeedForFlick(); } void ScrollView::SetMinimumSpeedForFlick(float speed) { GetImpl(*this).SetMinimumSpeedForFlick(speed); } float ScrollView::GetMaxFlickSpeed() const { return GetImpl(*this).GetMaxFlickSpeed(); } void ScrollView::SetMaxFlickSpeed(float speed) { GetImpl(*this).SetMaxFlickSpeed(speed); } Vector2 ScrollView::GetWheelScrollDistanceStep() const { return GetImpl(*this).GetWheelScrollDistanceStep(); } void ScrollView::SetWheelScrollDistanceStep(Vector2 step) { GetImpl(*this).SetWheelScrollDistanceStep(step); } Vector2 ScrollView::GetCurrentScrollPosition() const { return GetImpl(*this).GetCurrentScrollPosition(); } unsigned int ScrollView::GetCurrentPage() const { return GetImpl(*this).GetCurrentPage(); } void ScrollView::ScrollTo(const Vector2& position) { GetImpl(*this).ScrollTo(position); } void ScrollView::ScrollTo(const Vector2& position, float duration) { GetImpl(*this).ScrollTo(position, duration); } void ScrollView::ScrollTo(const Vector2& position, float duration, AlphaFunction alpha) { GetImpl(*this).ScrollTo(position, duration, alpha); } void ScrollView::ScrollTo(const Vector2& position, float duration, DirectionBias horizontalBias, DirectionBias verticalBias) { GetImpl(*this).ScrollTo(position, duration, horizontalBias, verticalBias); } void ScrollView::ScrollTo(const Vector2& position, float duration, AlphaFunction alpha, DirectionBias horizontalBias, DirectionBias verticalBias) { GetImpl(*this).ScrollTo(position, duration, alpha, horizontalBias, verticalBias); } void ScrollView::ScrollTo(unsigned int page) { GetImpl(*this).ScrollTo(page); } void ScrollView::ScrollTo(unsigned int page, float duration) { GetImpl(*this).ScrollTo(page, duration); } void ScrollView::ScrollTo(unsigned int page, float duration, DirectionBias bias) { GetImpl(*this).ScrollTo(page, duration, bias); } void ScrollView::ScrollTo(Actor& actor) { GetImpl(*this).ScrollTo(actor); } void ScrollView::ScrollTo(Actor& actor, float duration) { GetImpl(*this).ScrollTo(actor, duration); } bool ScrollView::ScrollToSnapPoint() { return GetImpl(*this).ScrollToSnapPoint(); } void ScrollView::ApplyConstraintToChildren(Constraint constraint) { GetImpl(*this).ApplyConstraintToChildren(constraint); } void ScrollView::RemoveConstraintsFromChildren() { GetImpl(*this).RemoveConstraintsFromChildren(); } void ScrollView::ApplyEffect(ScrollViewEffect effect) { GetImpl(*this).ApplyEffect(effect); } void ScrollView::RemoveEffect(ScrollViewEffect effect) { GetImpl(*this).RemoveEffect(effect); } void ScrollView::RemoveAllEffects() { GetImpl(*this).RemoveAllEffects(); } void ScrollView::BindActor(Actor child) { GetImpl(*this).BindActor(child); } void ScrollView::UnbindActor(Actor child) { GetImpl(*this).UnbindActor(child); } ScrollView::SnapStartedSignalType& ScrollView::SnapStartedSignal() { return GetImpl(*this).SnapStartedSignal(); } void ScrollView::SetScrollingDirection(Radian direction, Radian threshold) { GetImpl(*this).SetScrollingDirection(direction, threshold); } void ScrollView::RemoveScrollingDirection(Radian direction) { GetImpl(*this).RemoveScrollingDirection(direction); } } // namespace Toolkit } // namespace Dali
13,657
4,322
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/renderer/media/crypto/content_decryption_module_factory.h" #include "base/logging.h" #include "content/renderer/media/crypto/key_systems.h" #include "media/cdm/aes_decryptor.h" #if defined(ENABLE_PEPPER_CDMS) #include "content/renderer/media/crypto/ppapi_decryptor.h" #include "content/renderer/pepper/pepper_plugin_instance_impl.h" #include "content/renderer/pepper/pepper_webplugin_impl.h" #include "third_party/WebKit/public/platform/WebMediaPlayerClient.h" #include "third_party/WebKit/public/platform/WebString.h" #include "third_party/WebKit/public/web/WebFrame.h" #elif defined(OS_ANDROID) #include "content/renderer/media/android/proxy_media_keys.h" #include "content/renderer/media/android/renderer_media_player_manager.h" #endif // defined(ENABLE_PEPPER_CDMS) namespace content { #if defined(ENABLE_PEPPER_CDMS) // Returns the PepperPluginInstanceImpl associated with the Helper Plugin. // If a non-NULL pointer is returned, the caller must call // closeHelperPluginSoon() when the Helper Plugin is no longer needed. static scoped_refptr<PepperPluginInstanceImpl> CreateHelperPlugin( const std::string& plugin_type, blink::WebMediaPlayerClient* web_media_player_client, blink::WebFrame* web_frame) { DCHECK(web_media_player_client); DCHECK(web_frame); blink::WebPlugin* web_plugin = web_media_player_client->createHelperPlugin( blink::WebString::fromUTF8(plugin_type), web_frame); if (!web_plugin) return NULL; DCHECK(!web_plugin->isPlaceholder()); // Prevented by Blink. // Only Pepper plugins are supported, so it must be a ppapi object. PepperWebPluginImpl* ppapi_plugin = static_cast<PepperWebPluginImpl*>(web_plugin); return ppapi_plugin->instance(); } static scoped_ptr<media::MediaKeys> CreatePpapiDecryptor( const std::string& key_system, const media::SessionCreatedCB& session_created_cb, const media::SessionMessageCB& session_message_cb, const media::SessionReadyCB& session_ready_cb, const media::SessionClosedCB& session_closed_cb, const media::SessionErrorCB& session_error_cb, const base::Closure& destroy_plugin_cb, blink::WebMediaPlayerClient* web_media_player_client, blink::WebFrame* web_frame) { DCHECK(web_media_player_client); DCHECK(web_frame); std::string plugin_type = GetPepperType(key_system); DCHECK(!plugin_type.empty()); const scoped_refptr<PepperPluginInstanceImpl>& plugin_instance = CreateHelperPlugin(plugin_type, web_media_player_client, web_frame); if (!plugin_instance.get()) { DLOG(ERROR) << "Plugin instance creation failed."; return scoped_ptr<media::MediaKeys>(); } scoped_ptr<PpapiDecryptor> decryptor = PpapiDecryptor::Create(key_system, plugin_instance, session_created_cb, session_message_cb, session_ready_cb, session_closed_cb, session_error_cb, destroy_plugin_cb); if (!decryptor) destroy_plugin_cb.Run(); // Else the new object will call destroy_plugin_cb to destroy Helper Plugin. return scoped_ptr<media::MediaKeys>(decryptor.Pass()); } void ContentDecryptionModuleFactory::DestroyHelperPlugin( blink::WebMediaPlayerClient* web_media_player_client, blink::WebFrame* web_frame) { web_media_player_client->closeHelperPluginSoon(web_frame); } #endif // defined(ENABLE_PEPPER_CDMS) scoped_ptr<media::MediaKeys> ContentDecryptionModuleFactory::Create( const std::string& key_system, #if defined(ENABLE_PEPPER_CDMS) blink::WebMediaPlayerClient* web_media_player_client, blink::WebFrame* web_frame, const base::Closure& destroy_plugin_cb, #elif defined(OS_ANDROID) RendererMediaPlayerManager* manager, int media_keys_id, const GURL& frame_url, #endif // defined(ENABLE_PEPPER_CDMS) const media::SessionCreatedCB& session_created_cb, const media::SessionMessageCB& session_message_cb, const media::SessionReadyCB& session_ready_cb, const media::SessionClosedCB& session_closed_cb, const media::SessionErrorCB& session_error_cb) { if (CanUseAesDecryptor(key_system)) { return scoped_ptr<media::MediaKeys>( new media::AesDecryptor(session_created_cb, session_message_cb, session_ready_cb, session_closed_cb, session_error_cb)); } #if defined(ENABLE_PEPPER_CDMS) // TODO(ddorwin): Remove when the WD API implementation supports loading // Pepper-based CDMs: http://crbug.com/250049 if (!web_media_player_client) return scoped_ptr<media::MediaKeys>(); return CreatePpapiDecryptor(key_system, session_created_cb, session_message_cb, session_ready_cb, session_closed_cb, session_error_cb, destroy_plugin_cb, web_media_player_client, web_frame); #elif defined(OS_ANDROID) scoped_ptr<ProxyMediaKeys> proxy_media_keys( new ProxyMediaKeys(manager, media_keys_id, session_created_cb, session_message_cb, session_ready_cb, session_closed_cb, session_error_cb)); proxy_media_keys->InitializeCDM(key_system, frame_url); return proxy_media_keys.PassAs<media::MediaKeys>(); #else return scoped_ptr<media::MediaKeys>(); #endif // defined(ENABLE_PEPPER_CDMS) } } // namespace content
5,972
1,833
#include "territory.h" Territory::Territory(Board *parent) : QObject(parent) { bp = parent; size = 0.4; show = false; for ( int i = 0; i < bp->Xsize; i++ ) for ( int j = 0; j < bp->Ysize; j++ ) gi.append( -1 ); // -1 == undetermined territory, not yet in a group update(); } void Territory::setScene( BoardScene *scp ) { scene = scp; } /** * @brief Territory::clear - erase existing territory objects * in preparation for a new computation and possible display */ void Territory::clear() { clearDisplay(); foreach( TerritorySquare *tp, squareList ) delete tp; squareList.clear(); foreach( TerritoryGroup *gp, groupList ) delete gp; groupList.clear(); for ( int i = 0; i < bp->Xsize; i++ ) for ( int j = 0; j < bp->Ysize; j++ ) gi.replace( i + j * bp->Xsize, -1 ); } /** * @brief Territory::update - floodfill all empty grid points * and determine their current territory status: black, white or undetermined. */ void Territory::update() { clear(); // Determine how many territory groups there are, and what coordinates they each cover for ( int i = 0; i < bp->Xsize; i++ ) for ( int j = 0; j < bp->Ysize; j++ ) if ( gi.at( i + j * bp->Xsize ) == -1 ) { tFill( i, j, groupList.size() ); groupList.append( new TerritoryGroup(this) ); } // Fill the territory groups with square objects for ( int k = 0; k < groupList.size(); k++ ) { TerritoryGroup *tp = groupList.at(k); for ( int i = 0; i < bp->Xsize; i++ ) for ( int j = 0; j < bp->Ysize; j++ ) { if ( gi.at( i + j * bp->Xsize ) == k ) { TerritorySquare *ts = new TerritorySquare(this); ts->x = i; ts->y = j; ts->g = k; ts->c = -2; // Undetermined, at this time squareList.append(ts); tp->group.append(ts); } } } // Determine the color of each territory group for ( int k = 0; k < groupList.size(); k++ ) { TerritoryGroup *tp = groupList.at(k); int tc = -2; // -2 undeterminmed, -1 determined to be disputed, 0 black, 1 white bool done = ( groupList.size() <= 0 ) || ( tp->group.size() == 0 ); int i = 0; while( !done ) { TerritorySquare *ts = tp->group.at(i); if ( ts->x > 0 ) done |= territoryColor( ts->x-1, ts->y, &tc ); if ( ts->x < (bp->Xsize - 1) ) done |= territoryColor( ts->x+1, ts->y, &tc ); if ( ts->y > 0 ) done |= territoryColor( ts->x, ts->y-1, &tc ); if ( ts->y < (bp->Ysize - 1) ) done |= territoryColor( ts->x, ts->y+1, &tc ); if ( ++i >= tp->group.size() ) done = true; } groupList.at(k)->c = tc; foreach ( TerritorySquare *ts, tp->group ) ts->c = tc; } updateDisplay(); } /** * @brief Territory::territoryColor - judging adjacent squares to a territory and the current color determination * determine the continuing color evaluation of the territory * @param x - coordinate to evaluate * @param y - coordinate to evaluate * @param tc - current color assignment * @return true if the current color assignment has become disputed */ bool Territory::territoryColor( int x, int y, int *tc ) { int ii = x + bp->Xsize * y; if ( bp->board.size() <= ii ) return true; Stone *sp = bp->board.at( ii ); if ( sp == nullptr ) return false; // No info here if ( *tc == -1 ) return true; // Done before we start if ( *tc == -2 ) { *tc = sp->c; return false; } if ( *tc == sp->c ) return false; // Continuing the trend *tc = -1; // Contrasting neighbor found, territory is in dispute return true; } /** * @brief Territory::tFill - floodfill unclaimed territory with group index g * @param x - coordinate to look for unfilled neighbors from * @param y - coordinate to look for unfilled neighbors from * @param g - group index to fill this territory with */ void Territory::tFill( int x, int y, int g ) { int ii = x + y * bp->Xsize; if ( bp->board.size() <= ii ) return; if ( bp->board.at( ii ) != nullptr ) { gi.replace( ii, -2 - bp->board.at( ii )->c ); // -2 for blackstone, -3 for whitestone return; // floodfill search does not pass a stone } gi.replace( ii, g ); if ( x > 0 ) tCheck( x-1, y, g ); if ( x < ( bp->Xsize - 1 ) ) tCheck( x+1, y, g ); if ( y > 0 ) tCheck( x, y-1, g ); if ( y < ( bp->Ysize - 1 ) ) tCheck( x, y+1, g ); } /** * @brief Territory::tCheck * @param x - coordinate to check for stone * @param y - coordinate to check for stone * @param g - group index to mark this territory with */ void Territory::tCheck( int x, int y, int g ) { int ii = x + y * bp->Xsize; if ( bp->board.size() <= ii ) return; // Board is not ready yet, happens at first initialization if ( gi.size() < ii ) { qDebug( "ERROR: gi not ready yet" ); return; } if ( gi.at( ii ) != -1 ) { if (( gi.at( ii ) > -1 ) && ( gi.at( ii ) != g )) { QString msg = QString( "ERROR: tCheck @(%1,%2,%3) encountered another territory index %4" ).arg(x).arg(y).arg(g).arg(gi.at( ii ) ); qDebug( qPrintable( msg ) ); } return; // already marked } if ( bp->board.at( ii ) != nullptr ) { gi.replace( ii, -2 - bp->board.at( ii )->c ); // -2 for blackstone, -3 for whitestone return; // floodfill search does not pass a stone } tFill( x, y, g ); // Continue the floodfill search } /** * @brief Territory::clearDisplay - just clear the displayed * squares' graphics items, not the underlying data objects. */ void Territory::clearDisplay() { if ( scene == nullptr ) return; foreach( TerritorySquare *tp, squareList ) { if ( tp->ri != nullptr ) { tp->ri->setVisible( false ); scene->removeMyItem( tp->ri ); delete( tp->ri ); tp->ri = nullptr; } } } /** * @brief Territory::updateDisplay - just update the display * graphics items, not recalculating territory data objects. */ void Territory::updateDisplay() { clearDisplay(); if ( !show ) return; QPen tPen; QBrush tBrush; foreach( TerritorySquare *tp, squareList ) { // tp->ri == nullptr, done in clearDisplay if ( tp->c < 0 ) { tPen = scene->linePen; tBrush = scene->backBrush; } else if ( tp->c == 0 ) { tPen = Qt::NoPen; tBrush = scene->blackBrush; } else if ( tp->c == 1 ) { tPen = Qt::NoPen; tBrush = scene->whiteBrush; } else { tPen = Qt::NoPen; tBrush = scene->backBrush; qDebug( "Territory::updateDisplay() unknown color" ); } tp->ri = scene->addRect( (qreal)tp->x - size*0.5, (qreal)tp->y - size*0.5, size, size, tPen, tBrush ); // TODO: correct pen and brush for territory color } }
7,029
2,445
// ***************************************************************************** /*! \file tests/unit/Base/TestTimer.cpp \copyright 2012-2015 J. Bakosi, 2016-2018 Los Alamos National Security, LLC., 2019 Triad National Security, LLC. All rights reserved. See the LICENSE file for details. \brief Unit tests for tk::Timer \details Unit tests for tk::Timer */ // ***************************************************************************** #include <unistd.h> #include "NoWarning/tut.hpp" #include "TUTConfig.hpp" #include "Timer.hpp" #include "ContainerUtil.hpp" #include "NoWarning/tutsuite.decl.h" namespace unittest { extern CProxy_TUTSuite g_suiteProxy; } // unittest:: #ifndef DOXYGEN_GENERATING_OUTPUT namespace tut { //! All tests in group inherited from this base struct Timer_common { // cppcheck-suppress unusedStructMember double precision = 1.0e-3; // required precision in seconds for timings }; //! Test group shortcuts using Timer_group = test_group< Timer_common, MAX_TESTS_IN_GROUP >; using Timer_object = Timer_group::object; //! Define test group static Timer_group Timer( "Base/Timer" ); //! Test definitions for group //! Test timing a 0.1s duration as float with given precision template<> template<> void Timer_object::test< 1 >() { double prec = 1.0e-1; // only for this single test (to pass on Mac OS) set_test_name( "measure 0.1s using dsec() with " + std::to_string(prec) + "s prec" ); tk::Timer timer; usleep( 100000 ); // in micro-seconds, sleep for 0.1 second // test if time measured with at least 1/10th of a millisecond prec ensure_equals( "time 0.1s elapsed as float", timer.dsec(), 0.1, prec ); } //! Test timing a 1.0 duration as h:m:s with given precision template<> template<> void Timer_object::test< 2 >() { set_test_name( "measure 1.0s using hms() with " + std::to_string(precision) + "s prec" ); tk::Timer timer; usleep( 1000000 ); // in micro-seconds, sleep for 1.0 second const auto stamp = timer.hms(); // test if time measured with at least 1/10th of a millisecond precision ensure_equals( "time 1.0s elapsed as hrs", static_cast<tk::real>(stamp.hrs.count()), 0.0, precision ); ensure_equals( "time 1.0s elapsed as min", static_cast<tk::real>(stamp.min.count()), 0.0, precision ); ensure_equals( "time 1.0s elapsed as sec", static_cast<tk::real>(stamp.sec.count()), 1.0, precision ); } //! Test estimated time elapsed and to accomplishment triggered by term template<> template<> void Timer_object::test< 3 >() { set_test_name( "ETE and ETA triggered by terminate time" ); // Setup a duration case tk::real term = 5.0; // time at which to terminate time stepping tk::real time = 1.0; // current time uint64_t nstep = 1000; // max number of time steps to take (large) uint64_t it = 1; // current iteration tk::Timer timer; usleep( 1000000 ); // in micro-seconds, sleep for 1.0 second tk::Timer::Watch ete, eta; timer.eta( term, time, nstep, it, ete, eta ); // test estimated time elapsed with given precision ensure_equals( "estimated time elapsed in hrs", static_cast<tk::real>(ete.hrs.count()), 0.0, precision ); ensure_equals( "estimated time elapsed in min", static_cast<tk::real>(ete.min.count()), 0.0, precision ); ensure_equals( "estimated time elapsed in sec", static_cast<tk::real>(ete.sec.count()), 1.0, precision ); // test estimated time to accomplishment with given precision ensure_equals( "estimated time to accomplishment in hrs", static_cast<tk::real>(eta.hrs.count()), 0.0, precision ); ensure_equals( "estimated time to accomplishment in min", static_cast<tk::real>(eta.min.count()), 0.0, precision ); ensure_equals( "estimated time to accomplishment in sec", static_cast<tk::real>(eta.sec.count()), 4.0, precision ); } //! Test estimated time elapsed and to accomplishment triggered by nstep template<> template<> void Timer_object::test< 4 >() { set_test_name( "ETE and ETA triggered by max number of steps" ); // Setup a duration case tk::real term = 500.0; // time at which to terminate time stepping (large) tk::real time = 1.0; // current time uint64_t nstep = 100; // max number of time steps to take uint64_t it = 1; // current iteration tk::Timer timer; usleep( 1000000 ); // in micro-seconds, sleep for 1.0 second tk::Timer::Watch ete, eta; timer.eta( term, time, nstep, it, ete, eta ); // test estimated time elapsed with given precision ensure_equals( "estimated time elapsed in hrs", static_cast<tk::real>(ete.hrs.count()), 0.0, precision ); ensure_equals( "estimated time elapsed in min", static_cast<tk::real>(ete.min.count()), 0.0, precision ); ensure_equals( "estimated time elapsed in sec", static_cast<tk::real>(ete.sec.count()), 1.0, precision ); // test estimated time to accomplishment with given precision ensure_equals( "estimated time to accomplishment in hrs", static_cast<tk::real>(eta.hrs.count()), 0.0, precision ); ensure_equals( "estimated time to accomplishment in min", static_cast<tk::real>(eta.min.count()), 1.0, precision ); ensure_equals( "estimated time to accomplishment in sec", static_cast<tk::real>(eta.sec.count()), 39.0, precision ); } //! Test converting a 1.0s duration timed as a float to Timer::Watch template<> template<> void Timer_object::test< 5 >() { set_test_name( "convert time stamp in float to Watch" ); tk::Timer timer; usleep( 1000000 ); // in micro-seconds, sleep for 1.0 second // convert time stamp in float to Timer::Watch const auto w = tk::hms( timer.dsec() ); // test if time measured with at least 1/10th of a millisecond precision ensure_equals( "time 1.0s elapsed as float represented as Timer::Watch in hrs", static_cast<tk::real>(w.hrs.count()), 0.0, precision ); ensure_equals( "time 1.0s elapsed as float represented as Timer::Watch in min", static_cast<tk::real>(w.min.count()), 0.0, precision ); ensure_equals( "time 1.0s elapsed as float represented as Timer::Watch in sec", static_cast<tk::real>(w.sec.count()), 1.0, precision ); } //! Charm chare having a tk::Timer object class CharmTimer : public CBase_CharmTimer { public: explicit CharmTimer( const tk::Timer& timer ) { // Create test result struct, assume test is ok tut::test_result tr( "Base/Timer", 7, "Charm:migrate tk::Timer 2", tut::test_result::result_type::ok ); // Evaluate test: The incoming timer's time point is queried here that // includes the time elapsed before the Charm++ chare has been created + the // migration time, so tested with a somewhat lose precision that includes // the approximate (guessed) migration time. try { ensure( "timer different after migrated: ", timer.dsec() > 1.0 ); } catch ( const failure& ex ) { tr.result = ex.result(); tr.exception_typeid = ex.type(); tr.message = ex.what(); } // Send back a new test result, with tag "2", signaling the second part. unittest::g_suiteProxy.evaluate( { tr.group, tr.name, std::to_string(tr.result), tr.message, tr.exception_typeid } ); } }; //! Test Charm++ migration of a tk::Timer object across the network //! \details Every Charm++ migration test, such as this one, consists of two //! unit tests: one for send and one for receive. Both triggers a TUT test, //! but the receive side is created manually, i.e., without the awareness of //! the TUT library. Unfortunately thus, there is no good way to count up //! these additional tests, and thus if a test such as this is added to the //! suite this number must be updated in UnitTest/TUTSuite.h in //! unittest::TUTSuite::m_migrations. template<> template<> void Timer_object::test< 6 >() { // This test spawns a new Charm++ chare. The "1" at the end of the test name // signals that this is only the first part of this test: the part up to // firing up an asynchronous Charm++ chare. The second part creates a new test // result, sending it back to the suite if successful. If that chare never // executes, the suite will hang waiting for that chare to call back. set_test_name( "Charm:migrate tk::Timer 1" ); tk::Timer timer; usleep( 1000000 ); // in micro-seconds, sleep for 1.0 second CProxy_CharmTimer::ckNew( timer ); // fire up Charm++ chare } //! Test querying a timer from a std::map template<> template<> void Timer_object::test< 7 >() { double prec = 1.0e-2; // only for this single test (to pass on Mac OS) set_test_name( "query timer from map" ); std::map< std::string, tk::Timer > timer; timer[ "some timer" ];// start timing, assign to label usleep( 1000000 ); // in micro-seconds, sleep for 1.0 second const auto t = tk::ref_find( timer, "some timer" ); ensure_equals( "timer different", t.dsec(), 1.0, prec ); } //! Test that querying timer from a map throws with garbage key template<> template<> void Timer_object::test< 8 >() { set_test_name( "query throws with non-existent key" ); try { std::map< std::string, tk::Timer > timer; timer[ "some timer" ];// start timing, assign to label tk::cref_find( timer, std::string("some non-existent timer") ); fail( "should throw exception" ); } catch ( tk::Exception& ) { // exception thrown, test ok } } } // tut:: #endif // DOXYGEN_GENERATING_OUTPUT #include "NoWarning/charmtimer.def.h"
9,826
3,151
/* * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ #ifndef SHARE_VM_PRIMS_UNIVERSALUPCALLHANDLER_HPP #define SHARE_VM_PRIMS_UNIVERSALUPCALLHANDLER_HPP #include "asm/codeBuffer.hpp" #include "prims/foreign_globals.hpp" class JavaThread; class ProgrammableUpcallHandler { private: static constexpr CodeBuffer::csize_t upcall_stub_size = 1024; struct UpcallMethod { Klass* klass; Symbol* name; Symbol* sig; } upcall_method; ProgrammableUpcallHandler(); static const ProgrammableUpcallHandler& instance(); static void upcall_helper(JavaThread* thread, jobject rec, address buff); static void attach_thread_and_do_upcall(jobject rec, address buff); static void handle_uncaught_exception(oop exception); static Thread* maybe_attach_and_get_thread(bool* should_detach); static void detach_thread(Thread* thread); public: static address generate_optimized_upcall_stub(jobject mh, Method* entry, jobject jabi, jobject jconv); static address generate_upcall_stub(jobject rec, jobject abi, jobject buffer_layout); static bool supports_optimized_upcalls(); }; #endif // SHARE_VM_PRIMS_UNIVERSALUPCALLHANDLER_HPP
2,148
711
// Description: C++18 Table Object implementation for CFInt. /* * org.msscf.msscf.CFInt * * Copyright (c) 2020 Mark Stephen Sobkow * * MSS Code Factory CFInt 2.13 Internet Essentials * * Copyright 2020-2021 Mark Stephen Sobkow * * This file is part of MSS Code Factory. * * MSS Code Factory is available under dual commercial license from Mark Stephen * Sobkow, or under the terms of the GNU General Public License, Version 3 * or later. * * MSS Code Factory is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MSS Code Factory is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MSS Code Factory. If not, see <https://www.gnu.org/licenses/>. * * Donations to support MSS Code Factory can be made at * https://www.paypal.com/paypalme2/MarkSobkow * * Please contact Mark Stephen Sobkow at mark.sobkow@gmail.com for commercial licensing. * * Manufactured by MSS Code Factory 2.12 */ #include <cflib/ICFLibPublic.hpp> using namespace std; #include <cfint/ICFIntPublic.hpp> #include <cfintobj/ICFIntObjPublic.hpp> #include <cfintobj/CFIntClusterObj.hpp> #include <cfintobj/CFIntHostNodeObj.hpp> #include <cfintobj/CFIntISOCcyObj.hpp> #include <cfintobj/CFIntISOCtryObj.hpp> #include <cfintobj/CFIntISOCtryCcyObj.hpp> #include <cfintobj/CFIntISOCtryLangObj.hpp> #include <cfintobj/CFIntISOLangObj.hpp> #include <cfintobj/CFIntISOTZoneObj.hpp> #include <cfintobj/CFIntLicenseObj.hpp> #include <cfintobj/CFIntMajorVersionObj.hpp> #include <cfintobj/CFIntMimeTypeObj.hpp> #include <cfintobj/CFIntMinorVersionObj.hpp> #include <cfintobj/CFIntSecAppObj.hpp> #include <cfintobj/CFIntSecDeviceObj.hpp> #include <cfintobj/CFIntSecFormObj.hpp> #include <cfintobj/CFIntSecGroupObj.hpp> #include <cfintobj/CFIntSecGroupFormObj.hpp> #include <cfintobj/CFIntSecGrpIncObj.hpp> #include <cfintobj/CFIntSecGrpMembObj.hpp> #include <cfintobj/CFIntSecSessionObj.hpp> #include <cfintobj/CFIntSecUserObj.hpp> #include <cfintobj/CFIntServiceObj.hpp> #include <cfintobj/CFIntServiceTypeObj.hpp> #include <cfintobj/CFIntSubProjectObj.hpp> #include <cfintobj/CFIntSysClusterObj.hpp> #include <cfintobj/CFIntTSecGroupObj.hpp> #include <cfintobj/CFIntTSecGrpIncObj.hpp> #include <cfintobj/CFIntTSecGrpMembObj.hpp> #include <cfintobj/CFIntTenantObj.hpp> #include <cfintobj/CFIntTldObj.hpp> #include <cfintobj/CFIntTopDomainObj.hpp> #include <cfintobj/CFIntTopProjectObj.hpp> #include <cfintobj/CFIntURLProtocolObj.hpp> #include <cfintobj/CFIntClusterEditObj.hpp> #include <cfintobj/CFIntHostNodeEditObj.hpp> #include <cfintobj/CFIntISOCcyEditObj.hpp> #include <cfintobj/CFIntISOCtryEditObj.hpp> #include <cfintobj/CFIntISOCtryCcyEditObj.hpp> #include <cfintobj/CFIntISOCtryLangEditObj.hpp> #include <cfintobj/CFIntISOLangEditObj.hpp> #include <cfintobj/CFIntISOTZoneEditObj.hpp> #include <cfintobj/CFIntLicenseEditObj.hpp> #include <cfintobj/CFIntMajorVersionEditObj.hpp> #include <cfintobj/CFIntMimeTypeEditObj.hpp> #include <cfintobj/CFIntMinorVersionEditObj.hpp> #include <cfintobj/CFIntSecAppEditObj.hpp> #include <cfintobj/CFIntSecDeviceEditObj.hpp> #include <cfintobj/CFIntSecFormEditObj.hpp> #include <cfintobj/CFIntSecGroupEditObj.hpp> #include <cfintobj/CFIntSecGroupFormEditObj.hpp> #include <cfintobj/CFIntSecGrpIncEditObj.hpp> #include <cfintobj/CFIntSecGrpMembEditObj.hpp> #include <cfintobj/CFIntSecSessionEditObj.hpp> #include <cfintobj/CFIntSecUserEditObj.hpp> #include <cfintobj/CFIntServiceEditObj.hpp> #include <cfintobj/CFIntServiceTypeEditObj.hpp> #include <cfintobj/CFIntSubProjectEditObj.hpp> #include <cfintobj/CFIntSysClusterEditObj.hpp> #include <cfintobj/CFIntTSecGroupEditObj.hpp> #include <cfintobj/CFIntTSecGrpIncEditObj.hpp> #include <cfintobj/CFIntTSecGrpMembEditObj.hpp> #include <cfintobj/CFIntTenantEditObj.hpp> #include <cfintobj/CFIntTldEditObj.hpp> #include <cfintobj/CFIntTopDomainEditObj.hpp> #include <cfintobj/CFIntTopProjectEditObj.hpp> #include <cfintobj/CFIntURLProtocolEditObj.hpp> #include <cfintobj/CFIntClusterTableObj.hpp> #include <cfintobj/CFIntHostNodeTableObj.hpp> #include <cfintobj/CFIntISOCcyTableObj.hpp> #include <cfintobj/CFIntISOCtryTableObj.hpp> #include <cfintobj/CFIntISOCtryCcyTableObj.hpp> #include <cfintobj/CFIntISOCtryLangTableObj.hpp> #include <cfintobj/CFIntISOLangTableObj.hpp> #include <cfintobj/CFIntISOTZoneTableObj.hpp> #include <cfintobj/CFIntLicenseTableObj.hpp> #include <cfintobj/CFIntMajorVersionTableObj.hpp> #include <cfintobj/CFIntMimeTypeTableObj.hpp> #include <cfintobj/CFIntMinorVersionTableObj.hpp> #include <cfintobj/CFIntSecAppTableObj.hpp> #include <cfintobj/CFIntSecDeviceTableObj.hpp> #include <cfintobj/CFIntSecFormTableObj.hpp> #include <cfintobj/CFIntSecGroupTableObj.hpp> #include <cfintobj/CFIntSecGroupFormTableObj.hpp> #include <cfintobj/CFIntSecGrpIncTableObj.hpp> #include <cfintobj/CFIntSecGrpMembTableObj.hpp> #include <cfintobj/CFIntSecSessionTableObj.hpp> #include <cfintobj/CFIntSecUserTableObj.hpp> #include <cfintobj/CFIntServiceTableObj.hpp> #include <cfintobj/CFIntServiceTypeTableObj.hpp> #include <cfintobj/CFIntSubProjectTableObj.hpp> #include <cfintobj/CFIntSysClusterTableObj.hpp> #include <cfintobj/CFIntTSecGroupTableObj.hpp> #include <cfintobj/CFIntTSecGrpIncTableObj.hpp> #include <cfintobj/CFIntTSecGrpMembTableObj.hpp> #include <cfintobj/CFIntTenantTableObj.hpp> #include <cfintobj/CFIntTldTableObj.hpp> #include <cfintobj/CFIntTopDomainTableObj.hpp> #include <cfintobj/CFIntTopProjectTableObj.hpp> #include <cfintobj/CFIntURLProtocolTableObj.hpp> namespace cfint { const std::string CFIntMimeTypeTableObj::CLASS_NAME( "CFIntMimeTypeTableObj" ); const std::string CFIntMimeTypeTableObj::TABLE_NAME( "MimeType" ); const std::string CFIntMimeTypeTableObj::TABLE_DBNAME( "MimeType" ); CFIntMimeTypeTableObj::CFIntMimeTypeTableObj() { schema = NULL; members = new std::map<cfint::CFIntMimeTypePKey, cfint::ICFIntMimeTypeObj*>(); allMimeType = NULL; indexByUNameIdx = new std::map< cfint::CFIntMimeTypeByUNameIdxKey, cfint::ICFIntMimeTypeObj*>(); } CFIntMimeTypeTableObj::CFIntMimeTypeTableObj( cfint::ICFIntSchemaObj* argSchema ) { schema = dynamic_cast<cfint::ICFIntSchemaObj*>( argSchema ); members = new std::map<cfint::CFIntMimeTypePKey, cfint::ICFIntMimeTypeObj*>(); allMimeType = NULL; indexByUNameIdx = new std::map< cfint::CFIntMimeTypeByUNameIdxKey, cfint::ICFIntMimeTypeObj*>(); } CFIntMimeTypeTableObj::~CFIntMimeTypeTableObj() { minimizeMemory(); if( indexByUNameIdx != NULL ) { delete indexByUNameIdx; indexByUNameIdx = NULL; } if( members != NULL ) { cfint::ICFIntMimeTypeObj* curMember; auto membersIter = members->begin(); while( membersIter != members->end() ) { curMember = membersIter->second; if( curMember != NULL ) { delete curMember; } members->erase( membersIter ); membersIter = members->begin(); } delete members; members = NULL; } } cfint::ICFIntSchemaObj* CFIntMimeTypeTableObj::getSchema() { return( schema ); } void CFIntMimeTypeTableObj::setSchema( cfint::ICFIntSchemaObj* value ) { schema = dynamic_cast<cfint::ICFIntSchemaObj*>( value ); } const std::string CFIntMimeTypeTableObj::getTableName() { return( TABLE_NAME ); } const std::string CFIntMimeTypeTableObj::getTableDbName() { return( TABLE_DBNAME ); } const classcode_t* CFIntMimeTypeTableObj::getObjQualifyingClassCode() { return( NULL ); } void CFIntMimeTypeTableObj::minimizeMemory() { if( allMimeType != NULL ) { allMimeType->clear(); delete allMimeType; allMimeType = NULL; } if( indexByUNameIdx != NULL ) { indexByUNameIdx->clear(); } if( members != NULL ) { cfint::ICFIntMimeTypeObj* cur = NULL; cfint::ICFIntMimeTypeEditObj* edit = NULL; auto iter = members->begin(); auto end = members->end(); while( iter != end ) { cur = iter->second; if( cur != NULL ) { iter->second = NULL; edit = cur->getEdit(); if( edit != NULL ) { edit->endEdit(); edit = NULL; } delete cur; cur = NULL; } iter ++; } members->clear(); } } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::newInstance() { cfint::ICFIntMimeTypeObj* inst = dynamic_cast<cfint::ICFIntMimeTypeObj*>( new CFIntMimeTypeObj( schema ) ); return( inst ); } cfint::ICFIntMimeTypeEditObj* CFIntMimeTypeTableObj::newEditInstance( cfint::ICFIntMimeTypeObj* orig ) { cfint::ICFIntMimeTypeEditObj* edit = dynamic_cast<cfint::ICFIntMimeTypeEditObj*>( new CFIntMimeTypeEditObj( orig )); return( edit ); } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::realizeMimeType( cfint::ICFIntMimeTypeObj* Obj ) { static const std::string S_ProcName( "realizeMimeType" ); static const std::string S_ExistingObj( "existingObj" ); static const std::string S_KeepObj( "keepObj" ); static const std::string S_Obj( "Obj" ); if( Obj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 1, S_Obj ); } cfint::ICFIntMimeTypeObj* obj = Obj; cfint::ICFIntMimeTypeObj* existingObj = NULL; cfint::CFIntMimeTypePKey* pkey = obj->getPKey(); cfint::ICFIntMimeTypeObj* keepObj = NULL; auto searchMembers = members->find( *pkey ); if( searchMembers != members->end() ) { existingObj = searchMembers->second; if( existingObj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_ExistingObj ); } keepObj = existingObj; pkey = keepObj->getPKey(); /* * We always rebind the data because if we're being called, some index may have been * updated and is refreshing it's data, which may require binding a different lookup key */ // Detach object from alternate and duplicate indexes, leave PKey alone if( indexByUNameIdx != NULL ) { cfint::CFIntMimeTypeByUNameIdxKey keyUNameIdx; keyUNameIdx.setRequiredName( keepObj->getRequiredName() ); auto removalProbe = indexByUNameIdx->find( keyUNameIdx ); if( removalProbe != indexByUNameIdx->end() ) { indexByUNameIdx->erase( removalProbe ); } } keepObj->setBuff( dynamic_cast<cfint::CFIntMimeTypeBuff*>( Obj->getBuff()->clone() ) ); // Attach new object to alternate and duplicate indexes -- PKey stays stable if( indexByUNameIdx != NULL ) { static const std::string S_AUNameIdxObj( "aUNameIdxObj" ); cfint::ICFIntMimeTypeObj* aUNameIdxObj = dynamic_cast<cfint::ICFIntMimeTypeObj*>( keepObj ); if( aUNameIdxObj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_AUNameIdxObj ); } cfint::CFIntMimeTypeByUNameIdxKey keyUNameIdx; keyUNameIdx.setRequiredName( keepObj->getRequiredName() ); indexByUNameIdx->insert( std::map< cfint::CFIntMimeTypeByUNameIdxKey, cfint::ICFIntMimeTypeObj* >::value_type( keyUNameIdx, aUNameIdxObj ) ); } if( allMimeType != NULL ) { allMimeType->insert( std::map< cfint::CFIntMimeTypePKey, cfint::ICFIntMimeTypeObj* >::value_type( *(keepObj->getPKey()), keepObj ) ); } } else { keepObj = obj; keepObj->setIsNew( false ); pkey = keepObj->getPKey(); // Attach new object to PKey, all, alternate, and duplicate indexes members->insert( std::map< cfint::CFIntMimeTypePKey, cfint::ICFIntMimeTypeObj* >::value_type( *(keepObj->getPKey()), keepObj ) ); // Attach new object to alternate and duplicate indexes -- PKey stay stable if( indexByUNameIdx != NULL ) { static const std::string S_AUNameIdxObj( "aUNameIdxObj" ); cfint::ICFIntMimeTypeObj* aUNameIdxObj = dynamic_cast<cfint::ICFIntMimeTypeObj*>( keepObj ); if( aUNameIdxObj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_AUNameIdxObj ); } cfint::CFIntMimeTypeByUNameIdxKey keyUNameIdx; keyUNameIdx.setRequiredName( keepObj->getRequiredName() ); indexByUNameIdx->insert( std::map< cfint::CFIntMimeTypeByUNameIdxKey, cfint::ICFIntMimeTypeObj* >::value_type( keyUNameIdx, aUNameIdxObj ) ); } if( allMimeType != NULL ) { allMimeType->insert( std::map< cfint::CFIntMimeTypePKey, cfint::ICFIntMimeTypeObj* >::value_type( *(keepObj->getPKey()), keepObj ) ); } } if( keepObj != obj ) { delete obj; obj = NULL; } // Something is leaking, so I've added this paranoid check if( ( keepObj != existingObj ) && ( existingObj != NULL ) ) { delete existingObj; existingObj = NULL; } return( keepObj ); } void CFIntMimeTypeTableObj::deepDisposeByIdIdx( const int32_t MimeTypeId ) { static const std::string S_ProcName( "deepDisposeByIdIdx" ); std::vector<cfint::ICFIntMimeTypeObj*> list; cfint::ICFIntMimeTypeObj* existingObj = readCachedMimeTypeByIdIdx( MimeTypeId ); if( existingObj != NULL ) { list.push_back( existingObj ); } cfint::ICFIntMimeTypeObj* cur = NULL; classcode_t classCode; auto listIter = list.begin(); auto listEnd = list.end(); while( listIter != listEnd ) { cur = *listIter; if( cur != NULL ) { classCode = cur->getClassCode(); if( classCode == cfint::CFIntMimeTypeBuff::CLASS_CODE ) { dynamic_cast<cfint::CFIntMimeTypeTableObj*>( schema->getMimeTypeTableObj() )->reallyDeepDisposeMimeType( dynamic_cast<cfint::ICFIntMimeTypeObj*>( cur ) ); } } listIter ++; } } void CFIntMimeTypeTableObj::deepDisposeByUNameIdx( const std::string& Name ) { static const std::string S_ProcName( "deepDisposeByUNameIdx" ); std::vector<cfint::ICFIntMimeTypeObj*> list; cfint::ICFIntMimeTypeObj* existingObj = readCachedMimeTypeByUNameIdx( Name ); if( existingObj != NULL ) { list.push_back( existingObj ); } cfint::ICFIntMimeTypeObj* cur = NULL; classcode_t classCode; auto listIter = list.begin(); auto listEnd = list.end(); while( listIter != listEnd ) { cur = *listIter; if( cur != NULL ) { classCode = cur->getClassCode(); if( classCode == cfint::CFIntMimeTypeBuff::CLASS_CODE ) { dynamic_cast<cfint::CFIntMimeTypeTableObj*>( schema->getMimeTypeTableObj() )->reallyDeepDisposeMimeType( dynamic_cast<cfint::ICFIntMimeTypeObj*>( cur ) ); } } listIter ++; } } void CFIntMimeTypeTableObj::reallyDeepDisposeMimeType( cfint::ICFIntMimeTypeObj* Obj ) { static const std::string S_ProcName( "reallyDeepDisposeMimeType" ); if( Obj == NULL ) { return; } cfint::ICFIntMimeTypeObj* obj = Obj; classcode_t classCode = obj->getClassCode(); if( classCode == cfint::CFIntMimeTypeBuff::CLASS_CODE ) { dynamic_cast<cfint::CFIntMimeTypeTableObj*>( schema->getMimeTypeTableObj() )->reallyDetachFromIndexesMimeType( dynamic_cast<cfint::ICFIntMimeTypeObj*>( obj ) ); } if( obj->getEdit() != NULL ) { obj->endEdit(); } delete obj; obj = NULL; } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::createMimeType( cfint::ICFIntMimeTypeEditObj* Obj ) { static const std::string S_ProcName( "createMimeType" ); static const std::string S_Obj( "obj" ); static const std::string S_Cloneable( "cloneable" ); static const std::string S_ClonedBuff( "clonedbuff" ); CFLIB_EXCEPTION_DECLINFO cfint::ICFIntMimeTypeObj* obj = dynamic_cast<cfint::ICFIntMimeTypeObj*>( Obj->getOrig() ); try { cfint::CFIntMimeTypeBuff* buff = dynamic_cast<cfint::CFIntMimeTypeBuff*>( Obj->getBuff()->clone() ); // C++18 version of create returns a new buffer instance and takes over ownership of the passed-in buffer // MSS TODO WORKING The xmsg client will need to return the buffer instance created by processing // the response message, while xmsg rqst will have to delete the backing store instance // it receives after preparing the reply message so that memory doesn't leak on every request. cflib::ICFLibCloneableObj* cloneable = dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMimeType()->createMimeType( schema->getAuthorization(), buff ); if( cloneable == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Cloneable ); } Obj->endEdit(); obj->setBuff( dynamic_cast<cfint::CFIntMimeTypeBuff*>( cloneable ) ); obj = dynamic_cast<cfint::ICFIntMimeTypeObj*>( obj->realize() ); if( obj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Obj ); } } CFLIB_EXCEPTION_CATCH_FALLTHROUGH if( ! CFLIB_EXCEPTION_EMPTY ) { if( obj->getEdit() != NULL ) { obj->endEdit(); } if( obj->getIsNew() ) { delete obj; obj = NULL; } CFLIB_EXCEPTION_RETHROW_CFLIBEXCEPTION } return( obj ); } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::readMimeType( cfint::CFIntMimeTypePKey* pkey, bool forceRead ) { static const std::string S_Obj( "obj" ); static const std::string S_Realized( "realized" ); static const std::string S_ProcName( "readMimeType" ); cfint::ICFIntMimeTypeObj* obj = NULL; cfint::ICFIntMimeTypeObj* realized = NULL; if( ! forceRead ) { auto searchMembers = members->find( *pkey ); if( searchMembers != members->end() ) { // obj could be NULL if cache misses is enabled obj = searchMembers->second; realized = obj; } } if( forceRead || ( obj == NULL ) ) { cfint::CFIntMimeTypeBuff* readBuff = dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMimeType()->readDerivedByIdIdx( schema->getAuthorization(), pkey->getRequiredMimeTypeId() ); if( readBuff != NULL ) { obj = dynamic_cast<cfint::CFIntMimeTypeTableObj*>( schema->getMimeTypeTableObj() )->newInstance(); obj->setBuff( readBuff ); realized = dynamic_cast<cfint::ICFIntMimeTypeObj*>( obj->realize() ); if( realized == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Realized ); } // No need to delete obj -- realize() auto-destructs the instance it decided to discard obj = NULL; } } return( realized ); } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::lockMimeType( cfint::CFIntMimeTypePKey* pkey ) { static const std::string S_ProcName( "lockMimeType" ); cfint::ICFIntMimeTypeObj* locked = NULL; cfint::CFIntMimeTypeBuff* lockBuff = dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMimeType()->lockDerived( schema->getAuthorization(), pkey ); if( lockBuff != NULL ) { locked = dynamic_cast<cfint::CFIntMimeTypeTableObj*>( schema->getMimeTypeTableObj() )->newInstance(); locked->setBuff( lockBuff ); locked = dynamic_cast<cfint::ICFIntMimeTypeObj*>( locked->realize() ); } else { return( NULL ); } return( locked ); } std::vector<cfint::ICFIntMimeTypeObj*> CFIntMimeTypeTableObj::readAllMimeType( bool forceRead ) { static const std::string S_ProcName( "readAllMimeType" ); static const std::string S_Idx( "idx" ); static const std::string S_Realized( "realized" ); CFLIB_EXCEPTION_DECLINFO cfint::ICFIntMimeTypeObj* realized = NULL; if( forceRead || ( allMimeType == NULL ) ) { std::map<cfint::CFIntMimeTypePKey, cfint::ICFIntMimeTypeObj*>* map = new std::map<cfint::CFIntMimeTypePKey,cfint::ICFIntMimeTypeObj*>(); allMimeType = map; std::TCFLibOwningVector<cfint::CFIntMimeTypeBuff*> buffList = dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMimeType()->readAllDerived( schema->getAuthorization() ); cfint::CFIntMimeTypeBuff* buff = NULL; cfint::ICFIntMimeTypeObj* obj = NULL; try { for( size_t idx = 0; idx < buffList.size(); idx ++ ) { buff = buffList[ idx ]; buffList[ idx ] = NULL; obj = newInstance(); obj->setBuff( buff ); realized = dynamic_cast<cfint::ICFIntMimeTypeObj*>( obj->realize() ); if( realized == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Realized ); } allMimeType->insert( std::map< cfint::CFIntMimeTypePKey, cfint::ICFIntMimeTypeObj* >::value_type( *(realized->getPKey()), realized ) ); // No need to delete obj -- realize() auto-destructs the instance it decided to discard obj = NULL; } } CFLIB_EXCEPTION_CATCH_FALLTHROUGH if( ( obj != NULL ) && obj->getIsNew() ) { delete obj; obj = NULL; } CFLIB_EXCEPTION_RETHROW_CFLIBEXCEPTION } size_t len = allMimeType->size(); std::vector<cfint::ICFIntMimeTypeObj*> arr; auto valIter = allMimeType->begin(); size_t idx = 0; while( valIter != allMimeType->end() ) { arr.push_back( valIter->second ); valIter ++; } return( arr ); } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::readMimeTypeByIdIdx( const int32_t MimeTypeId, bool forceRead ) { static const std::string S_ProcName( "readMimeTypeByIdIdx" ); static const std::string S_Realized( "realized" ); cfint::CFIntMimeTypePKey pkey; pkey.setRequiredMimeTypeId( MimeTypeId ); cfint::ICFIntMimeTypeObj* obj = readMimeType( &pkey, forceRead ); return( obj ); } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::readMimeTypeByUNameIdx( const std::string& Name, bool forceRead ) { static const std::string S_ProcName( "readMimeTypeByUNameIdx" ); static const std::string S_Realized( "realized" ); if( indexByUNameIdx == NULL ) { indexByUNameIdx = new std::map< cfint::CFIntMimeTypeByUNameIdxKey, cfint::ICFIntMimeTypeObj*>(); } cfint::CFIntMimeTypeByUNameIdxKey key; key.setRequiredName( Name ); cfint::ICFIntMimeTypeObj* obj = NULL; cfint::ICFIntMimeTypeObj* realized = NULL; if( ! forceRead ) { auto searchIndexByUNameIdx = indexByUNameIdx->find( key ); if( searchIndexByUNameIdx != indexByUNameIdx->end() ) { // Note: obj may be null if cache misses is enabled obj = searchIndexByUNameIdx->second; realized = obj; } } if( forceRead || ( obj == NULL ) ) { cfint::CFIntMimeTypeBuff* buff = dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMimeType()->readDerivedByUNameIdx( schema->getAuthorization(), Name ); if( buff != NULL ) { obj = dynamic_cast<cfint::CFIntMimeTypeTableObj*>( schema->getMimeTypeTableObj() )->newInstance(); obj->setBuff( buff ); realized = dynamic_cast<cfint::ICFIntMimeTypeObj*>( obj->realize() ); if( realized == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Realized ); } indexByUNameIdx->insert( std::map< cfint::CFIntMimeTypeByUNameIdxKey, cfint::ICFIntMimeTypeObj*>::value_type( key, dynamic_cast<cfint::ICFIntMimeTypeObj*>( realized ) ) ); // No need to delete obj -- realize() auto-destructs the instance it decided to discard obj = realized; } } return( obj ); } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::readMimeTypeByLookupUNameIdx( const std::string& Name, bool forceRead ) { static const std::string S_Realized( "realized" ); static const std::string S_Obj( "obj" ); static const std::string S_ProcName( "readMimeTypeByLookupUNameIdx" ); if( indexByUNameIdx == NULL ) { indexByUNameIdx = new std::map< cfint::CFIntMimeTypeByUNameIdxKey, cfint::ICFIntMimeTypeObj*>(); } cfint::CFIntMimeTypeByUNameIdxKey key; key.setRequiredName( Name ); cfint::ICFIntMimeTypeObj* obj = NULL; cfint::ICFIntMimeTypeObj* realized = NULL; if( ! forceRead ) { auto searchIndexByUNameIdx = indexByUNameIdx->find( key ); if( searchIndexByUNameIdx != indexByUNameIdx->end() ) { obj = searchIndexByUNameIdx->second; } } if( forceRead || ( obj == NULL ) ) { cfint::CFIntMimeTypeBuff* buff = dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMimeType()->readDerivedByLookupUNameIdx( schema->getAuthorization(), Name ); if( buff != NULL ) { obj = dynamic_cast<cfint::ICFIntMimeTypeObj*>( dynamic_cast<cfint::CFIntMimeTypeTableObj*>( schema->getMimeTypeTableObj() )->newInstance() ); obj->setBuff( buff ); realized = dynamic_cast<cfint::ICFIntMimeTypeObj*>( obj->realize() ); if( realized == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Realized ); } indexByUNameIdx->insert( std::map< cfint::CFIntMimeTypeByUNameIdxKey, cfint::ICFIntMimeTypeObj*>::value_type( key, dynamic_cast<cfint::ICFIntMimeTypeObj*>( realized ) ) ); // No need to delete obj -- realize() auto-destructs the instance it decided to discard obj = realized; } } return( obj ); } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::readCachedMimeType( cfint::CFIntMimeTypePKey* pkey ) { static const std::string S_Obj( "obj" ); static const std::string S_Realized( "realized" ); static const std::string S_ProcName( "readMimeType" ); cfint::ICFIntMimeTypeObj* obj = NULL; cfint::ICFIntMimeTypeObj* realized = NULL; auto searchMembers = members->find( *pkey ); if( searchMembers != members->end() ) { // obj could be NULL if cache misses is enabled obj = searchMembers->second; realized = obj; } return( realized ); } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::readCachedMimeTypeByIdIdx( const int32_t MimeTypeId ) { static const std::string S_ProcName( "readCachedMimeTypeByIdIdx" ); static const std::string S_Realized( "realized" ); cfint::CFIntMimeTypePKey pkey; pkey.setRequiredMimeTypeId( MimeTypeId ); cfint::ICFIntMimeTypeObj* obj = readCachedMimeType( &pkey ); return( obj ); } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::readCachedMimeTypeByUNameIdx( const std::string& Name ) { static const std::string S_ProcName( "readCachedMimeTypeByUNameIdx" ); static const std::string S_Realized( "realized" ); if( indexByUNameIdx == NULL ) { indexByUNameIdx = new std::map< cfint::CFIntMimeTypeByUNameIdxKey, cfint::ICFIntMimeTypeObj*>(); } cfint::CFIntMimeTypeByUNameIdxKey key; key.setRequiredName( Name ); cfint::ICFIntMimeTypeObj* obj = NULL; auto searchIndexByUNameIdx = indexByUNameIdx->find( key ); if( searchIndexByUNameIdx != indexByUNameIdx->end() ) { // Note: obj may be null if cache misses is enabled obj = searchIndexByUNameIdx->second; } else { for( auto iterMembers = members->begin(); ( obj == NULL ) && ( iterMembers != members->end() ); iterMembers ++ ) { obj = iterMembers->second; if( obj != NULL ) { if( *(dynamic_cast<cfint::CFIntMimeTypeBuff*>( obj->getBuff() ) ) != key ) { obj = NULL; } } } } return( obj ); } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::readCachedMimeTypeByLookupUNameIdx( const std::string& Name ) { static const std::string S_Realized( "realized" ); static const std::string S_Obj( "obj" ); static const std::string S_ProcName( "readCachedMimeTypeByLookupUNameIdx" ); if( indexByUNameIdx == NULL ) { indexByUNameIdx = new std::map< cfint::CFIntMimeTypeByUNameIdxKey, cfint::ICFIntMimeTypeObj*>(); } cfint::CFIntMimeTypeByUNameIdxKey key; key.setRequiredName( Name ); cfint::ICFIntMimeTypeObj* obj = NULL; cfint::ICFIntMimeTypeObj* realized = NULL; auto searchIndexByUNameIdx = indexByUNameIdx->find( key ); if( searchIndexByUNameIdx != indexByUNameIdx->end() ) { obj = searchIndexByUNameIdx->second; } else { for( auto iterMembers = members->begin(); ( obj == NULL ) && ( iterMembers != members->end() ); iterMembers ++ ) { obj = iterMembers->second; if( obj != NULL ) { if( *(dynamic_cast<cfint::CFIntMimeTypeBuff*>( obj->getBuff() ) ) != key ) { obj = NULL; } } } } return( obj ); } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::updateMimeType( cfint::ICFIntMimeTypeEditObj* Obj ) { static const std::string S_ProcName( "updateMimeType" ); static const std::string S_Obj( "obj" ); static const std::string S_Updated( "updated" ); CFLIB_EXCEPTION_DECLINFO cfint::ICFIntMimeTypeObj* obj = dynamic_cast<cfint::ICFIntMimeTypeObj*>( Obj->getOrig() ); try { cfint::CFIntMimeTypeBuff* updated = dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMimeType()->updateMimeType( schema->getAuthorization(), dynamic_cast<cfint::CFIntMimeTypeBuff*>( Obj->getMimeTypeBuff()->clone() ) ); if( updated == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Updated ); } obj = dynamic_cast<cfint::ICFIntMimeTypeObj*>( dynamic_cast<cfint::CFIntMimeTypeTableObj*>( schema->getMimeTypeTableObj() )->newInstance() ); obj->setBuff( updated ); obj = dynamic_cast<cfint::ICFIntMimeTypeObj*>( obj->realize() ); if( obj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Obj ); } if( obj->getEdit() != NULL ) { obj->endEdit(); } } CFLIB_EXCEPTION_CATCH_FALLTHROUGH if( ! CFLIB_EXCEPTION_EMPTY ) { if( obj->getEdit() != NULL ) { obj->endEdit(); } CFLIB_EXCEPTION_RETHROW_CFLIBEXCEPTION } return( obj ); } void CFIntMimeTypeTableObj::deleteMimeType( cfint::ICFIntMimeTypeEditObj* Obj ) { cfint::ICFIntMimeTypeObj* obj = Obj; dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMimeType()->deleteMimeType( schema->getAuthorization(), obj->getMimeTypeBuff() ); deepDisposeByIdIdx( obj->getRequiredMimeTypeId() ); } void CFIntMimeTypeTableObj::deleteMimeTypeByIdIdx( const int32_t MimeTypeId ) { cfint::CFIntMimeTypePKey pkey; pkey.setRequiredMimeTypeId( MimeTypeId ); cfint::ICFIntMimeTypeObj* obj = readMimeType( &pkey, true ); if( obj != NULL ) { cfint::ICFIntMimeTypeEditObj* editObj = dynamic_cast<cfint::ICFIntMimeTypeEditObj*>( obj->getEdit() ); if( editObj == NULL ) { editObj = dynamic_cast<cfint::ICFIntMimeTypeEditObj*>( obj->beginEdit() ); } if( editObj != NULL ) { editObj->deleteInstance(); editObj = NULL; } } } void CFIntMimeTypeTableObj::deleteMimeTypeByUNameIdx( const std::string& Name ) { if( indexByUNameIdx == NULL ) { indexByUNameIdx = new std::map< cfint::CFIntMimeTypeByUNameIdxKey, cfint::ICFIntMimeTypeObj*>(); } cfint::CFIntMimeTypeByUNameIdxKey key; key.setRequiredName( Name ); cfint::ICFIntMimeTypeObj* obj = NULL; auto searchIndexByUNameIdx = indexByUNameIdx->find( key ); if( searchIndexByUNameIdx != indexByUNameIdx->end() ) { dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMimeType()->deleteMimeTypeByUNameIdx( schema->getAuthorization(), Name ); } else { dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMimeType()->deleteMimeTypeByUNameIdx( schema->getAuthorization(), Name ); } deepDisposeByUNameIdx( Name ); } void CFIntMimeTypeTableObj::reallyDetachFromIndexesMimeType( cfint::ICFIntMimeTypeObj* Obj ) { static const std::string S_ProcName( "reallyDetachFromIndexesMimeType" ); static const std::string S_Obj( "Obj" ); static const std::string S_ExistingObj( "ExistingObj" ); if( Obj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 1, S_Obj ); } cfint::ICFIntMimeTypeObj* obj = Obj; cfint::CFIntMimeTypePKey* pkey = obj->getPKey(); auto searchMembers = members->find( *pkey ); if( searchMembers != members->end() ) { cfint::ICFIntMimeTypeObj* existingObj = searchMembers->second; if( existingObj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_ExistingObj ); } if( indexByUNameIdx != NULL ) { cfint::CFIntMimeTypeByUNameIdxKey keyUNameIdx; keyUNameIdx.setRequiredName( obj->getRequiredName() ); auto removalProbe = indexByUNameIdx->find( keyUNameIdx ); if( removalProbe != indexByUNameIdx->end() ) { indexByUNameIdx->erase( removalProbe ); } } members->erase( searchMembers ); } } }
32,005
13,346
/* +----------------------------------------------------------------------+ | Swoole | +----------------------------------------------------------------------+ | This source file is subject to version 2.0 of the Apache license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.apache.org/licenses/LICENSE-2.0.html | | If you did not receive a copy of the Apache2.0 license and are unable| | to obtain it through the world-wide-web, please send a note to | | license@swoole.com so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Tianfeng Han <mikan.tenny@gmail.com> | +----------------------------------------------------------------------+ */ #include "swoole.h" #include "heap.h" #define left(i) ((i) << 1) #define right(i) (((i) << 1) + 1) #define parent(i) ((i) >> 1) static void swHeap_bubble_up(swHeap *heap, uint32_t i); static uint32_t swHeap_maxchild(swHeap *heap, uint32_t i); static void swHeap_percolate_down(swHeap *heap, uint32_t i); swHeap *swHeap_new(size_t n, uint8_t type) { swHeap *heap = (swHeap *) sw_malloc(sizeof(swHeap)); if (!heap) { return nullptr; } if (!(heap->nodes = (swHeap_node **) sw_malloc((n + 1) * sizeof(void *)))) { sw_free(heap); return nullptr; } heap->num = 1; heap->size = (n + 1); heap->type = type; return heap; } void swHeap_free(swHeap *heap) { sw_free(heap->nodes); sw_free(heap); } static sw_inline int swHeap_compare(uint8_t type, uint64_t a, uint64_t b) { if (type == SW_MIN_HEAP) { return a > b; } else { return a < b; } } uint32_t swHeap_size(swHeap *q) { return (q->num - 1); } static uint32_t swHeap_maxchild(swHeap *heap, uint32_t i) { uint32_t child_i = left(i); if (child_i >= heap->num) { return 0; } swHeap_node *child_node = heap->nodes[child_i]; if ((child_i + 1) < heap->num && swHeap_compare(heap->type, child_node->priority, heap->nodes[child_i + 1]->priority)) { child_i++; } return child_i; } static void swHeap_bubble_up(swHeap *heap, uint32_t i) { swHeap_node *moving_node = heap->nodes[i]; uint32_t parent_i; for (parent_i = parent(i); (i > 1) && swHeap_compare(heap->type, heap->nodes[parent_i]->priority, moving_node->priority); i = parent_i, parent_i = parent(i)) { heap->nodes[i] = heap->nodes[parent_i]; heap->nodes[i]->position = i; } heap->nodes[i] = moving_node; moving_node->position = i; } static void swHeap_percolate_down(swHeap *heap, uint32_t i) { uint32_t child_i; swHeap_node *moving_node = heap->nodes[i]; while ((child_i = swHeap_maxchild(heap, i)) && swHeap_compare(heap->type, moving_node->priority, heap->nodes[child_i]->priority)) { heap->nodes[i] = heap->nodes[child_i]; heap->nodes[i]->position = i; i = child_i; } heap->nodes[i] = moving_node; moving_node->position = i; } swHeap_node *swHeap_push(swHeap *heap, uint64_t priority, void *data) { void *tmp; uint32_t i; uint32_t newsize; if (heap->num >= heap->size) { newsize = heap->size * 2; if (!(tmp = sw_realloc(heap->nodes, sizeof(void *) * newsize))) { return nullptr; } heap->nodes = (swHeap_node **) tmp; heap->size = newsize; } swHeap_node *node = (swHeap_node *) sw_malloc(sizeof(swHeap_node)); if (!node) { return nullptr; } node->priority = priority; node->data = data; i = heap->num++; heap->nodes[i] = node; swHeap_bubble_up(heap, i); return node; } void swHeap_change_priority(swHeap *heap, uint64_t new_priority, void *ptr) { swHeap_node *node = (swHeap_node *) ptr; uint32_t pos = node->position; uint64_t old_pri = node->priority; node->priority = new_priority; if (swHeap_compare(heap->type, old_pri, new_priority)) { swHeap_bubble_up(heap, pos); } else { swHeap_percolate_down(heap, pos); } } void swHeap_remove(swHeap *heap, swHeap_node *node) { uint32_t pos = node->position; heap->nodes[pos] = heap->nodes[--heap->num]; if (swHeap_compare(heap->type, node->priority, heap->nodes[pos]->priority)) { swHeap_bubble_up(heap, pos); } else { swHeap_percolate_down(heap, pos); } } void *swHeap_pop(swHeap *heap) { swHeap_node *head; if (!heap || heap->num == 1) { return nullptr; } head = heap->nodes[1]; heap->nodes[1] = heap->nodes[--heap->num]; swHeap_percolate_down(heap, 1); void *data = head->data; sw_free(head); return data; } void *swHeap_peek(swHeap *heap) { if (heap->num == 1) { return nullptr; } swHeap_node *node = heap->nodes[1]; if (!node) { return nullptr; } return node->data; } void swHeap_print(swHeap *heap) { for (uint32_t i = 1; i < heap->num; i++) { printf("#%d\tpriority=%ld, data=%p\n", i, (long) heap->nodes[i]->priority, heap->nodes[i]->data); } }
5,352
2,018
#include "parse.h" #include "util.h" int parse_child(FILE *fp, int unquoted, int *line_n, char *buff, char **b, group *g, group *prev_g, int depth, parse_error *er) { g->countable = 1; //until proven otherwise int n_chars = 0; while(buff[n_chars] != '\0') n_chars++; size_t line_buff_len = max_read_line_len; char *s = *b; while(g->type == GROUP_TYPE_NULL) { if(*s == '\0') { n_chars = getline(&buff, &line_buff_len, fp); *line_n = *line_n+1; if(n_chars <= 0) { *buff = '\0'; er->error = ERROR_EOF; safe_sprintf(er->txt,"ERROR: EOF\nline %d\n",*line_n); return 0; } s = buff; } while(*s == ' ' || *s == '\t') s++; if(*s == '<' ) { g->type = GROUP_TYPE_SEQUENCE; s++; } else if(*s == '{' ) { g->type = GROUP_TYPE_OPTION; s++; } else if(*s == '(' ) { g->type = GROUP_TYPE_PERMUTE; s++; } else if(*s == '"' ) { g->type = GROUP_TYPE_CHARS; s++; } else if(*s == '[' ) { g->type = GROUP_TYPE_MODIFICATION; s++; } else if(*s == '#' ) { g->type = GROUP_TYPE_NULL; s++; *s = '\0'; } else if(*s == '\n') { g->type = GROUP_TYPE_NULL; s++; *s = '\0'; } else if(*s == '\0') { g->type = GROUP_TYPE_NULL; s++; *s = '\0'; } else if(*s == '-') { char *c; g->type = GROUP_TYPE_CHARS; g->n = 0; g->chars = (char *)safe_malloc(sizeof(char)*g->n+1); c = g->chars; s++; *c = '\0'; *b = s; return 1; } else if(unquoted && *s != '>' && *s != '}' && *s != ')' && *s != ']') { char *c; g->type = GROUP_TYPE_CHARS; if(*s == '\\') s++; g->n = 1; g->chars = (char *)safe_malloc(sizeof(char)*g->n+1); c = g->chars; *c = *s; c++; s++; *c = '\0'; *b = s; return 1; } else { *b = s; er->error = ERROR_INVALID_LINE; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; safe_sprintf(er->txt,"ERROR: Invalid line\nline %d ( %s )\n",*line_n,buff); return 0; } if(g->type != GROUP_TYPE_CHARS) { while(*s == ' ' || *s == '\t') s++; } char *c; if(g->type == GROUP_TYPE_OPTION) g->countable = 0; //TODO: this limitation renders "countability" a farce switch(g->type) { case GROUP_TYPE_SEQUENCE: case GROUP_TYPE_OPTION: case GROUP_TYPE_PERMUTE: g->n = 0; *b = s; if(g->type == GROUP_TYPE_SEQUENCE) { if(!parse_tag(fp, line_n, buff, b, &g->tag_u, 1, er)) return 0; if(!parse_tag(fp, line_n, buff, b, &g->tag_g, 0, er)) return 0; if(g->tag_u) g->countable = 0; if(g->tag_g) g->countable = 0; } return parse_childs(fp, unquoted, line_n, buff, b, g, depth+1, er); break; case GROUP_TYPE_CHARS: c = s; while(*c != '"' && *c != '\n' && *c != '\0') { if(*c == '\\') c++; c++; } if(*c == '"') { g->n = (c-s); g->chars = (char *)safe_malloc(sizeof(char)*g->n+1); c = g->chars; while(*s != '"' && *s != '\n' && *s != '\0') { if(*s == '\\') { s++; g->n--; } *c = *s; c++; s++; } if(*s != '"') { er->error = ERROR_UNTERMINATED_STRING; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; safe_sprintf(er->txt,"ERROR: Unterminated string\nline %d ( %s )\n",*line_n,buff); return 0; } s++; *c = '\0'; } else { er->error = ERROR_INVALID_STRING; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; safe_sprintf(er->txt,"ERROR: Invalid characters after begining string\nline %d ( %s )\n",*line_n,buff); return 0; } break; case GROUP_TYPE_MODIFICATION: //special case if(!prev_g) { er->error = ERROR_UNPARENTED_MODIFICATION; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; safe_sprintf(er->txt,"ERROR: Modification with no previous group\nline %d ( %s )\n",*line_n,buff); return 0; } *b = s; return parse_modifications(fp, line_n, buff, b, prev_g, er); break; case GROUP_TYPE_NULL: ; break; default: //appease compiler break; } } *b = s; return 1; } int parse_tag(FILE *fp, int *line_n, char *buff, char **b, tag *t, int u, parse_error *er) { assert(!*t); int n_chars = 0; while(buff[n_chars] != '\0') n_chars++; size_t line_buff_len = max_read_line_len; char *s = *b; while(1) { if(*s == '\0') { n_chars = getline(&buff, &line_buff_len, fp); *line_n = *line_n+1; if(n_chars <= 0) { *buff = '\0'; er->error = ERROR_BADEOF; safe_sprintf(er->txt,"ERROR: EOF parsing tag\nline %d\n",*line_n); return 0; } s = buff; } else if(*s == ' ' || *s == '\t') s++; else break; } int parsed = 0; int d; if((u && *s == 'U') || (!u && *s == 'G')) { s++; while((d = parse_number(s,&parsed)) != -1) { if(parsed < 1 || parsed >= max_tag_count) { er->error = ERROR_TAG_RANGE; if(u) safe_sprintf(er->txt,"ERROR: unique tag outside of valid range [1-%d]\nline %d\n",max_tag_count-1,*line_n); else safe_sprintf(er->txt,"ERROR: group tag outside of valid range [1-%d]\nline %d\n",max_tag_count-1,*line_n); return 0; } s += d; *t |= 1 << (parsed-1); if(*s == ',') s++; } if(!*t) { er->error = ERROR_TAG_SPECIFY; if(u) safe_sprintf(er->txt,"ERROR: unique tag not specified\nline %d\n",*line_n); else safe_sprintf(er->txt,"ERROR: group tag not specified\nline %d\n",*line_n); return 0; } } *b = s; return 1; } int parse_modification(FILE *fp, int *line_n, char *buff, char **b, modification *m, parse_error *er) { int n_chars = 0; while(buff[n_chars] != '\0') n_chars++; size_t line_buff_len = max_read_line_len; char *s = *b; int found = 0; while(!found) { if(*s == '\0') { n_chars = getline(&buff, &line_buff_len, fp); *line_n = *line_n+1; if(n_chars <= 0) { *buff = '\0'; er->error = ERROR_BADEOF; safe_sprintf(er->txt,"ERROR: EOF parsing modification\nline %d\n",*line_n); return 0; } s = buff; } int d = 1; while(d > 0) { while(*s == ' ' || *s == '\t') s++; if(*s == 'c' ) { s++; d = parse_number(s,&m->n_copys); m->n_copys -= 1; } //m->n_copys = 0 means "just do it once" (ie default) else if(*s == 'd' ) { s++; d = parse_number(s,&m->n_deletions); } else if(*s == 's' ) { s++; d = parse_number(s,&m->n_substitutions); } else if(*s == 'i' ) { s++; d = parse_number(s,&m->n_injections); } else if(*s == 'm' ) { s++; d = parse_number(s,&m->n_smart_substitutions); } else if(*s == '-' ) { s++; *b = s; if(m->n_injections+m->n_smart_substitutions+m->n_substitutions+m->n_deletions+m->n_copys == 0) return 1; else d = -1; } else break; if(d < 0) { er->error = ERROR_INVALID_NULL_MODIFICATION; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; safe_sprintf(er->txt,"ERROR: Invalid null modification\nline %d ( %s )\n",*line_n,buff); return 0; } else { s += d; found = 1; } } if(!found) { if(*s == '#' ) { s++; *s = '\0'; } else if(*s == '\n') { s++; *s = '\0'; } else if(*s == '\0') { s++; *s = '\0'; } else { *b = s; er->error = ERROR_INVALID_MODIFICATION; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; safe_sprintf(er->txt,"ERROR: Invalid line in modification\nline %d ( %s )\n",*line_n,buff); return 0; } } else { if(*s == '#' ) { s++; *s = '\0'; } else if(*s == '\n') { s++; *s = '\0'; } else if(*s == '\0') { s++; *s = '\0'; } else if(*s == '"' ) //get chars { s++; char *c = s; while(*c != '"' && *c != '\n' && *c != '\0') { if(*c == '\\') c++; c++; } if(*c == '"') { m->n = (c-s); m->chars = (char *)safe_malloc(sizeof(char)*m->n+1); c = m->chars; while(*s != '"' && *s != '\n' && *s != '\0') { if(*s == '\\') { s++; m->n--; } *c = *s; c++; s++; } if(*s != '"') { er->error = ERROR_UNTERMINATED_STRING; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; safe_sprintf(er->txt,"ERROR: Unterminated modification gamut\nline %d ( %s )\n",*line_n,buff); return 0; } s++; *c = '\0'; } else { er->error = ERROR_INVALID_STRING; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; safe_sprintf(er->txt,"ERROR: Invalid characters after begining gamut\nline %d ( %s )\n",*line_n,buff); return 0; } } } if(m->n_substitutions+m->n_injections > 0 && !m->n) { er->error = ERROR_MODIFICATION_EMPTY_GAMUT; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; safe_sprintf(er->txt,"ERROR: gamut required with substitution or injection\nline %d ( %s )\n",*line_n,buff); return 0; } } *b = s; return 1; } int parse_modifications(FILE *fp, int *line_n, char *buff, char **b, group *g, parse_error *er) { char *s; int valid_modification = 1; modification *m = (modification *)safe_malloc(sizeof(modification)); while(valid_modification) { zero_modification(m); valid_modification = parse_modification(fp,line_n,buff,b,m,er); if(valid_modification) { if(m->n_smart_substitutions) g->countable = 0; g->n_mods++; if(g->n_mods == 1) g->mods = (modification *)safe_malloc(sizeof(modification)); else g->mods = (modification *)safe_realloc(g->mods,sizeof(modification)*g->n_mods); g->mods[g->n_mods-1] = *m; } } free(m); if(er->error == ERROR_BADEOF) return 0; //close everything if(er->error != ERROR_INVALID_MODIFICATION) return 0; //let "invalid modification" attempt parse as "end modification" if(er->force) return 0; //if error force, don't allow passthrough ("unexpected parse" should only bubble up one level) s = *b; if(*s != ']') { //er->error; //retain error from stack int n_chars = 0; while(buff[n_chars] != '\0') n_chars++; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; safe_sprintf(er->txt,"ERROR: Invalid characters within modifiers\nline %d ( %s )\n",*line_n,buff); er->force = 1; return 0; } s++; *b = s; return 1; } int parse_childs(FILE *fp, int unquoted, int *line_n, char *buff, char **b, group *g, int depth, parse_error *er) { char *s; int valid_kid = 1; group *prev_c = 0; group *c = (group *)safe_malloc(sizeof(group)); while(valid_kid) { zero_group(c); valid_kid = parse_child(fp, unquoted, line_n, buff, b, c, prev_c, depth+1, er); if(valid_kid) { if(c->type == GROUP_TYPE_MODIFICATION) { //ok } else if(c->type == GROUP_TYPE_NULL) { er->error = ERROR_NULL_CHILD; int n_chars = 0; while(buff[n_chars] != '\0') n_chars++; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; safe_sprintf(er->txt,"Null child type found\nline %d ( %s )\n",*line_n,buff); } else { g->n++; if(g->n == 1) g->childs = (group *)safe_malloc(sizeof(group)); else g->childs = (group *)safe_realloc(g->childs,sizeof(group)*g->n); g->childs[g->n-1] = *c; prev_c = &g->childs[g->n-1]; } } } free(c); if(er->error == ERROR_EOF) { if(depth == 0) return 1; //close everything else { er->error = ERROR_BADEOF; //upgrade error switch(g->type) { case GROUP_TYPE_SEQUENCE: safe_sprintf(er->txt,"ERROR: EOF unclosed sequence\nline %d\n",*line_n); break; case GROUP_TYPE_OPTION: safe_sprintf(er->txt,"ERROR: EOF unclosed option\nline %d\n",*line_n); break; case GROUP_TYPE_PERMUTE: safe_sprintf(er->txt,"ERROR: EOF unclosed permute\nline %d\n",*line_n); break; default: break; //appease compiler } return 0; } } if(er->error != ERROR_INVALID_LINE) return 0; //let "invalid line" attempt parse as "end line" if(er->force) return 0; //if error force, don't allow passthrough ("unexpected parse" should only bubble up one level) s = *b; if(*s == '>' && g->type == GROUP_TYPE_SEQUENCE) s++; //great else if(*s == '}' && g->type == GROUP_TYPE_OPTION) s++; //great else if(*s == ')' && g->type == GROUP_TYPE_PERMUTE) s++; //great else { //er->error; //retain error from stack int n_chars = 0; while(buff[n_chars] != '\0') n_chars++; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; if(g->type == GROUP_TYPE_SEQUENCE) safe_sprintf(er->txt,"ERROR: Invalid characters within sequence\nline %d ( %s )\n",*line_n,buff); if(g->type == GROUP_TYPE_OPTION) safe_sprintf(er->txt,"ERROR: Invalid characters within option\nline %d ( %s )\n",*line_n,buff); if(g->type == GROUP_TYPE_PERMUTE) safe_sprintf(er->txt,"ERROR: Invalid characters within permute\nline %d ( %s )\n",*line_n,buff); er->force = 1; return 0; } *b = s; return 1; } group *parse(FILE *fp, int unquoted) { char *buff; buff = (char *)safe_malloc(sizeof(char)*max_read_line_len); parse_error er; er.error = ERROR_NULL; er.force = 0; er.txt = (char *)safe_malloc(sizeof(char)*max_sprintf_len); int line_n = 0; group *g = (group *)safe_malloc(sizeof(group)); zero_group(g); g->type = GROUP_TYPE_SEQUENCE; char *b = buff; *b = '\0'; if(!parse_childs(fp, unquoted, &line_n, buff, &b, g, 0, &er)) { fprintf(stderr, "%s", er.txt); exit(1); } while(g->n == 1 && g->n_mods == 0 && (g->type == GROUP_TYPE_SEQUENCE || g->type == GROUP_TYPE_OPTION || g->type == GROUP_TYPE_PERMUTE)) { group *og = g->childs; *g = g->childs[0]; free(og); } free(buff); free(er.txt); return g; }
14,666
5,886
// record_stack.cc - Fundamental stack arrangement. // // ##Copyright## // // Copyright 2000-2016 Peter Robinson (pjr@itee.uq.edu.au) // // 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.00 // // 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. // // ##Copyright## // // $Id: record_stack.cc,v 1.3 2001/06/07 05:18:12 qp Exp $ #include "area_offsets.h" #include "defs.h" #include "record_stack.h" #include "stack_qp.h"
871
307
// This file is part of Wintermute Engine // For conditions of distribution and use, see copyright notice in license.txt #include "Wme.h" #include "Timer.h" namespace Wme { ////////////////////////////////////////////////////////////////////////// Timer::Timer() { m_OgreTimer = new Ogre::Timer(); Reset(); } ////////////////////////////////////////////////////////////////////////// Timer::~Timer() { SAFE_DELETE(m_OgreTimer); } ////////////////////////////////////////////////////////////////////////// void Timer::Reset() { m_CurrentTime = m_PrevTime = m_ElapsedTime = 0; m_IsFrozen = false; m_Multiplier = 1.0; } ////////////////////////////////////////////////////////////////////////// unsigned long Timer::Update() { if (m_IsFrozen) { m_ElapsedTime = 0; return m_CurrentTime; } unsigned long currentTime = m_OgreTimer->getMilliseconds(); unsigned long delta = currentTime - m_PrevTime; if (delta > 1000) delta = 1000; delta = (unsigned long)((float)delta * m_Multiplier); m_CurrentTime += delta; m_PrevTime = currentTime; m_ElapsedTime = delta; return m_CurrentTime; } ////////////////////////////////////////////////////////////////////////// void Timer::Freeze() { m_IsFrozen = true; } ////////////////////////////////////////////////////////////////////////// void Timer::Unfreeze() { m_IsFrozen = false; } } // namespace Wme
1,445
456
#pragma once #include "avr/io/detail/type_traits/enable_if.hpp" namespace avr { namespace io { namespace detail { template<typename Bit, typename... Rest> struct all_state_representation_at_compiletime { constexpr static bool value = all_state_representation_at_compiletime<Bit>::value && all_state_representation_at_compiletime<Rest...>::value; }; template<typename Bit> struct all_state_representation_at_compiletime<Bit> { constexpr static bool value = !Bit::representation_at_runtime; }; template<typename... Bits> using enable_if_state_representation_at_runtime = enable_if_t< !all_state_representation_at_compiletime<Bits...>::value>; template<typename... Bits> using enable_if_state_representation_at_compiletime = enable_if_t< all_state_representation_at_compiletime<Bits...>::value>; }}}
833
261
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_SPRITE_GEOMETRY_DETAIL_FILL_TEXTURE_COORDINATES_HPP_INCLUDED #define SGE_SPRITE_GEOMETRY_DETAIL_FILL_TEXTURE_COORDINATES_HPP_INCLUDED #include <sge/renderer/lock_rect_to_coords.hpp> #include <sge/renderer/texture/planar.hpp> #include <sge/sprite/object_impl.hpp> #include <sge/sprite/detail/config/has_normal_size.hpp> #include <sge/sprite/detail/config/has_repetition.hpp> #include <sge/sprite/detail/config/has_texture_coordinates.hpp> #include <sge/sprite/geometry/detail/convert_texture_rect.hpp> #include <sge/sprite/geometry/detail/fill_texture_coordinates_rect.hpp> #include <sge/texture/area_texc.hpp> #include <sge/texture/part.hpp> #include <fcppt/config/external_begin.hpp> #include <type_traits> #include <fcppt/config/external_end.hpp> namespace sge::sprite::geometry::detail { template <typename Level, typename Iterator, typename Choices> inline std::enable_if_t< std::conjunction_v< sge::sprite::detail::config::has_texture_coordinates<Choices>, sge::sprite::detail::config::has_normal_size<Choices>>, void> fill_texture_coordinates( Level const &, Iterator const &_iterator, sge::sprite::object<Choices> const &_sprite, sge::texture::part const &) { sge::sprite::geometry::detail::fill_texture_coordinates_rect<Level, Choices>( _iterator, _sprite.template texture_coordinates_level<Level::value>()); } template <typename Level, typename Iterator, typename Choices> inline std::enable_if_t< std::conjunction_v< sge::sprite::detail::config::has_repetition<Choices>, sge::sprite::detail::config::has_normal_size<Choices>>, void> fill_texture_coordinates( Level const &, Iterator const &_iterator, sge::sprite::object<Choices> const &_sprite, sge::texture::part const &_texture) { sge::sprite::geometry::detail::fill_texture_coordinates_rect<Level, Choices>( _iterator, sge::sprite::geometry::detail::convert_texture_rect<Choices>( sge::texture::area_texc<typename Choices::type_choices::float_type>( _texture, _sprite.repetition()))); } template <typename Level, typename Iterator, typename Choices> inline std::enable_if_t< std::conjunction_v< sge::sprite::detail::config::has_normal_size<Choices>, std::negation<std::disjunction< sge::sprite::detail::config::has_repetition<Choices>, sge::sprite::detail::config::has_texture_coordinates<Choices>>>>, void> fill_texture_coordinates( Level const &, Iterator const &_iterator, sge::sprite::object<Choices> const &, sge::texture::part const &_texture) { sge::sprite::geometry::detail::fill_texture_coordinates_rect<Level, Choices>( _iterator, sge::sprite::geometry::detail::convert_texture_rect<Choices>( sge::renderer::lock_rect_to_coords<typename Choices::type_choices::float_type>( _texture.area(), _texture.texture().size()))); } } #endif
3,173
1,148
#include <iostream> #include <fstream> using namespace std; const long long int del = 1000000007; long long int binpow (long long int a, long long int n) { long long int res = 1; while (n) { if (n & 1) { res *= a; res = res % del; } a *= a; a = a%del; n >>= 1; } return res; } int main() { ifstream f1("nim.in"); ofstream f2("nim.out"); long long int n,m,otv(0); f1>>n>>m; long long int g1 = 0, g2 = 0, maxm = binpow(2, m), gnext(0); long long int vch = ((maxm - 1)*(maxm - 2))%del, next = maxm - 3; for (int i = 3; i<=n; i++) { gnext = vch - g1 - ((i-1)*(maxm-1-(i-2))%del)*g2; if (gnext < 0) { gnext = gnext + ((-gnext)/del)*del; gnext = (del + gnext)%del; } vch *= next; vch %= del; next--; g2 = g1; g1 = gnext; } if (n == 1) { gnext = maxm - 1; } else { gnext = vch - gnext; if (gnext < 0) { gnext = gnext + ((-gnext)/del)*del; gnext = (del + gnext)%del; } } f2 << gnext; f1.close(); f2.close(); return 0; }
1,027
524
// 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 "garnet/lib/ui/gfx/tests/session_handler_test.h" namespace scenic_impl { namespace gfx { namespace test { void SessionHandlerTest::SetUp() { InitializeScenic(); InitializeDisplayManager(); InitializeEngine(); InitializeSessionHandler(); } void SessionHandlerTest::TearDown() { command_dispatcher_.reset(); engine_.reset(); command_buffer_sequencer_.reset(); display_manager_.reset(); scenic_.reset(); app_context_.reset(); events_.clear(); } void SessionHandlerTest::InitializeScenic() { // TODO(SCN-720): Wrap Create using ::gtest::Environment // instead of this hack. This code has the chance to break non-ScenicTests. app_context_ = sys::ComponentContext::Create(); scenic_ = std::make_unique<Scenic>(app_context_.get(), inspect::Object(), [] {}); } void SessionHandlerTest::InitializeSessionHandler() { auto session_context = engine_->session_context(); auto session_manager = session_context.session_manager; auto session_id = SessionId(1); InitializeScenicSession(session_id); command_dispatcher_ = session_manager->CreateCommandDispatcher( CommandDispatcherContext(scenic_.get(), scenic_session_.get()), std::move(session_context)); } void SessionHandlerTest::InitializeDisplayManager() { display_manager_ = std::make_unique<DisplayManager>(); display_manager_->SetDefaultDisplayForTests(std::make_unique<Display>( /*id*/ 0, /*px-width*/ 0, /*px-height*/ 0)); } void SessionHandlerTest::InitializeEngine() { command_buffer_sequencer_ = std::make_unique<escher::impl::CommandBufferSequencer>(); auto mock_release_fence_signaller = std::make_unique<ReleaseFenceSignallerForTest>( command_buffer_sequencer_.get()); engine_ = std::make_unique<EngineForTest>( app_context_.get(), display_manager_.get(), std::move(mock_release_fence_signaller), /*event reporter*/ this, this->error_reporter()); } void SessionHandlerTest::InitializeScenicSession(SessionId session_id) { fidl::InterfaceHandle<fuchsia::ui::scenic::SessionListener> listener; scenic_session_ = std::make_unique<scenic_impl::Session>(session_id, std::move(listener)); } void SessionHandlerTest::EnqueueEvent(fuchsia::ui::gfx::Event event) { fuchsia::ui::scenic::Event scenic_event; scenic_event.set_gfx(std::move(event)); events_.push_back(std::move(scenic_event)); } void SessionHandlerTest::EnqueueEvent(fuchsia::ui::input::InputEvent event) { fuchsia::ui::scenic::Event scenic_event; scenic_event.set_input(std::move(event)); events_.push_back(std::move(scenic_event)); } void SessionHandlerTest::EnqueueEvent(fuchsia::ui::scenic::Command unhandled) { fuchsia::ui::scenic::Event scenic_event; scenic_event.set_unhandled(std::move(unhandled)); events_.push_back(std::move(scenic_event)); } } // namespace test } // namespace gfx } // namespace scenic_impl
3,059
989
// // Created by Dawid Drozd aka Gelldur on 03.12.17. // #include "Bezier.h" //////////////////////////////////
114
46
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "ngraph/op/util/elementwise_args.hpp" #include "ngraph/op/util/binary_elementwise_arithmetic.hpp" using namespace ngraph; std::tuple<element::Type, PartialShape> ngraph::op::util::validate_and_infer_elementwise_args( Node* node, const op::AutoBroadcastSpec& autob) { NGRAPH_CHECK(node != nullptr, "nGraph node is empty! Cannot validate eltwise arguments."); element::Type element_type = node->get_input_element_type(0); PartialShape pshape = node->get_input_partial_shape(0); if (node->get_input_size() > 1) { for (size_t i = 1; i < node->get_input_size(); ++i) { NODE_VALIDATION_CHECK(node, element::Type::merge(element_type, element_type, node->get_input_element_type(i)), "Argument element types are inconsistent."); if (autob.m_type == op::AutoBroadcastType::NONE) { NODE_VALIDATION_CHECK(node, PartialShape::merge_into(pshape, node->get_input_partial_shape(i)), "Argument shapes are inconsistent."); } else if (autob.m_type == op::AutoBroadcastType::NUMPY || autob.m_type == op::AutoBroadcastType::PDPD) { NODE_VALIDATION_CHECK( node, PartialShape::broadcast_merge_into(pshape, node->get_input_partial_shape(i), autob), "Argument shapes are inconsistent."); } else { NODE_VALIDATION_CHECK(node, false, "Unsupported auto broadcast specification"); } } } return std::make_tuple(element_type, pshape); }
1,769
546
class Solution { public: int trap(vector<int>& height) { int n = height.size(), h; int* l = new int[n]; int* r = new int[n]; h = 0; for (int i = 0; i < n; i++) { h = max(h, height[i]); l[i] = h; } h = 0; for (int i = n-1; i >= 0; i--) { h = max(h, height[i]); r[i] = h; } int ans = 0; for (int i = 0; i < n; i++) ans += min(l[i], r[i]) - height[i]; delete l; delete r; return ans; } };
457
265
#include <iostream> #include <fstream> #include <sstream> #include <regex> #include <map> #include "lmpBaseReader.hpp" #include "debug.hpp" using namespace std; void lmpBaseReader::goToSection(ifstream &f, string section_title) { f.seekg(0,ios::beg); //return to top of file regex sectionRE(section_title+".*",regex::extended); string line; while (getline(f,line)) { if (regex_search(line,sectionRE)) { getline(f,line);// blank line break; } } } map<string,float> lmpBaseReader::readHeader(ifstream &f) { f.seekg(0,ios::beg); //return to top of file if (not f.good()) { cout << "file.bad(): " << boolalpha << f.bad() << endl; cout << "file.fail(): " << boolalpha << f.fail() << endl; cout << "file.eof(): " << boolalpha << f.eof() << endl; LOC(); exit(EXIT_FAILURE); } regex natoms("(.*) atoms",regex::extended); regex nbonds("(.*) bonds",regex::extended); regex nangles("(.*) angles",regex::extended); regex ndih("(.*) dihedrals",regex::extended); regex nimp("(.*) impropers",regex::extended); regex ntypes("(.*) atom types",regex::extended); regex nbtypes("(.*) bond types",regex::extended); regex natypes("(.*) angle types",regex::extended); regex ndtypes("(.*) dihedral types",regex::extended); regex nitypes("(.*) improper types",regex::extended); regex boxx("(.*) (.*) xlo xhi",regex::extended); regex boxy("(.*) (.*) ylo yhi",regex::extended); regex boxz("(.*) (.*) zlo zhi",regex::extended); map<string,float> headerData; smatch m; string line; float temp1,temp2; int lineNo=0; int maxHeaderSize = 50; while (getline(f,line)) { if (regex_search(line,m,boxz)) { istringstream (m[1].str()) >> temp1; istringstream (m[2].str()) >> temp2; headerData["zlo"] = temp1; headerData["zhi"] = temp2; headerData["lz"] = temp2 - temp1; } else if (regex_search(line,m,boxy)) { istringstream (m[1].str()) >> temp1; istringstream (m[2].str()) >> temp2; headerData["ylo"] = temp1; headerData["yhi"] = temp2; headerData["ly"] = temp2 - temp1; } else if (regex_search(line,m,boxx)) { istringstream (m[1].str()) >> temp1; istringstream (m[2].str()) >> temp2; headerData["xlo"] = temp1; headerData["xhi"] = temp2; headerData["lx"] = temp2 - temp1; } else if (regex_search(line,m,nitypes)) { istringstream (m[1].str()) >> temp1; headerData["nimpropertypes"] = temp1; } else if (regex_search(line,m,ndtypes)) { istringstream (m[1].str()) >> temp1; headerData["ndihedraltypes"] = temp1; } else if (regex_search(line,m,natypes)) { istringstream (m[1].str()) >> temp1; headerData["nangletypes"] = temp1; } else if (regex_search(line,m,nbtypes)) { istringstream (m[1].str()) >> temp1; headerData["nbondtypes"] = temp1; } else if (regex_search(line,m,ntypes)) { istringstream (m[1].str()) >> temp1; headerData["natomtypes"] = temp1; } else if (regex_search(line,m,nimp)) { istringstream (m[1].str()) >> temp1; headerData["nimpropers"] = temp1; } else if (regex_search(line,m,ndih)) { istringstream (m[1].str()) >> temp1; headerData["ndihedrals"] = temp1; } else if (regex_search(line,m,nangles)) { istringstream (m[1].str()) >> temp1; headerData["nangles"] = temp1; } else if (regex_search(line,m,nbonds)) { istringstream (m[1].str()) >> temp1; headerData["nbonds"] = temp1; } else if (regex_search(line,m,natoms)) { istringstream (m[1].str()) >> temp1; headerData["natoms"] = temp1; } if (lineNo>maxHeaderSize) break; lineNo++; } // nead to clear eofbit and failbit in case the end of the file was reached f.clear(); return headerData; }
3,818
1,419
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/cognito-sync/model/IdentityUsage.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace CognitoSync { namespace Model { IdentityUsage::IdentityUsage() : m_identityIdHasBeenSet(false), m_identityPoolIdHasBeenSet(false), m_lastModifiedDateHasBeenSet(false), m_datasetCount(0), m_datasetCountHasBeenSet(false), m_dataStorage(0), m_dataStorageHasBeenSet(false) { } IdentityUsage::IdentityUsage(const JsonValue& jsonValue) : m_identityIdHasBeenSet(false), m_identityPoolIdHasBeenSet(false), m_lastModifiedDateHasBeenSet(false), m_datasetCount(0), m_datasetCountHasBeenSet(false), m_dataStorage(0), m_dataStorageHasBeenSet(false) { *this = jsonValue; } IdentityUsage& IdentityUsage::operator =(const JsonValue& jsonValue) { if(jsonValue.ValueExists("IdentityId")) { m_identityId = jsonValue.GetString("IdentityId"); m_identityIdHasBeenSet = true; } if(jsonValue.ValueExists("IdentityPoolId")) { m_identityPoolId = jsonValue.GetString("IdentityPoolId"); m_identityPoolIdHasBeenSet = true; } if(jsonValue.ValueExists("LastModifiedDate")) { m_lastModifiedDate = jsonValue.GetDouble("LastModifiedDate"); m_lastModifiedDateHasBeenSet = true; } if(jsonValue.ValueExists("DatasetCount")) { m_datasetCount = jsonValue.GetInteger("DatasetCount"); m_datasetCountHasBeenSet = true; } if(jsonValue.ValueExists("DataStorage")) { m_dataStorage = jsonValue.GetInt64("DataStorage"); m_dataStorageHasBeenSet = true; } return *this; } JsonValue IdentityUsage::Jsonize() const { JsonValue payload; if(m_identityIdHasBeenSet) { payload.WithString("IdentityId", m_identityId); } if(m_identityPoolIdHasBeenSet) { payload.WithString("IdentityPoolId", m_identityPoolId); } if(m_lastModifiedDateHasBeenSet) { payload.WithDouble("LastModifiedDate", m_lastModifiedDate.SecondsWithMSPrecision()); } if(m_datasetCountHasBeenSet) { payload.WithInteger("DatasetCount", m_datasetCount); } if(m_dataStorageHasBeenSet) { payload.WithInt64("DataStorage", m_dataStorage); } return payload; } } // namespace Model } // namespace CognitoSync } // namespace Aws
2,914
1,017
#include<iostream> using namespace std; class Kitty{ public: void nyan(){cout << "Kitty on your lap\n";} }; class Di_Gi_Gharat : public Kitty{ public: void nyo(){cout << "Di Gi Gharat\n";} } obj; int main(){ obj.nyo(); obj.nyan(); return 0; }
266
111
class Baz {}; class Qux { Baz Foo; /* Test 1 */ // CHECK: Baz Bar; public: Qux(); }; Qux::Qux() : Foo() /* Test 2 */ {} // CHECK: Qux::Qux() : Bar() /* Test 2 */ {} // Test 1. // RUN: clang-rename -offset=33 -new-name=Bar %s -- | sed 's,//.*,,' | FileCheck %s // Test 2. // RUN: clang-rename -offset=118 -new-name=Bar %s -- | sed 's,//.*,,' | FileCheck %s // To find offsets after modifying the file, use: // grep -Ubo 'Foo.*' <file>
461
194
#include "testUtils.h" using namespace irr; using namespace core; using namespace io; static bool testgetAbsoluteFilename(io::IFileSystem* fs) { bool result=true; io::path apath = fs->getAbsolutePath("media"); io::path cwd = fs->getWorkingDirectory(); if (apath!=(cwd+"/media")) { logTestString("getAbsolutePath failed on existing dir %s\n", apath.c_str()); result = false; } apath = fs->getAbsolutePath("../media/"); core::deletePathFromPath(cwd, 1); if (apath!=(cwd+"media/")) { logTestString("getAbsolutePath failed on dir with postfix / %s\n", apath.c_str()); result = false; } apath = fs->getAbsolutePath ("../nothere.txt"); // file does not exist if (apath!=(cwd+"nothere.txt")) { logTestString("getAbsolutePath failed on non-existing file %s\n", apath.c_str()); result = false; } return result; } static bool testFlattenFilename(io::IFileSystem* fs) { bool result=true; io::path tmpString="../tmp"; io::path refString="../tmp/"; fs->flattenFilename(tmpString); if (tmpString != refString) { logTestString("flattening destroys path.\n%s!=%s\n", tmpString.c_str(),refString.c_str()); result = false; } tmpString="tmp/tmp/../"; refString="tmp/"; fs->flattenFilename(tmpString); if (tmpString != refString) { logTestString("flattening destroys path.\n%s!=%s\n", tmpString.c_str(),refString.c_str()); result = false; } tmpString="tmp/tmp/.."; fs->flattenFilename(tmpString); if (tmpString != refString) { logTestString("flattening destroys path.\n%s!=%s\n", tmpString.c_str(),refString.c_str()); result = false; } tmpString="tmp/next/../third"; refString="tmp/third/"; fs->flattenFilename(tmpString); if (tmpString != refString) { logTestString("flattening destroys path.\n%s!=%s\n", tmpString.c_str(),refString.c_str()); result = false; } tmpString="this/tmp/next/../../my/fourth"; refString="this/my/fourth/"; fs->flattenFilename(tmpString); if (tmpString != refString) { logTestString("flattening destroys path.\n%s!=%s\n", tmpString.c_str(),refString.c_str()); result = false; } tmpString="this/is/../../../a/fifth/test/"; refString="../a/fifth/test/"; fs->flattenFilename(tmpString); if (tmpString != refString) { logTestString("flattening destroys path.\n%s!=%s\n", tmpString.c_str(),refString.c_str()); result = false; } tmpString="this/../is/../../a/sixth/test/"; refString="../a/sixth/test/"; fs->flattenFilename(tmpString); if (tmpString != refString) { logTestString("flattening destroys path.\n%s!=%s\n", tmpString.c_str(),refString.c_str()); result = false; } return result; } static bool testgetRelativeFilename(io::IFileSystem* fs) { bool result=true; io::path apath = fs->getAbsolutePath("media"); io::path cwd = fs->getWorkingDirectory(); if (fs->getRelativeFilename(apath, cwd) != "media") { logTestString("getRelativePath failed on %s\n", apath.c_str()); result = false; } apath = fs->getAbsolutePath("../media/"); if (fs->getRelativeFilename(apath, cwd) != "../media/") { logTestString("getRelativePath failed on %s\n", apath.c_str()); result = false; } return result; } bool filesystem(void) { IrrlichtDevice * device = irr::createDevice(video::EDT_NULL, dimension2d<u32>(1, 1)); assert_log(device); if(!device) return false; io::IFileSystem * fs = device->getFileSystem (); if ( !fs ) return false; bool result = true; io::path workingDir = device->getFileSystem()->getWorkingDirectory(); io::path empty; if ( fs->existFile(empty) ) { logTestString("Empty filename should not exist.\n"); result = false; } io::path newWd = workingDir + "/media"; bool changed = device->getFileSystem()->changeWorkingDirectoryTo(newWd); assert_log(changed); if ( fs->existFile(empty) ) { logTestString("Empty filename should not exist even in another workingdirectory.\n"); result = false; } // The working directory must be restored for the other tests to work. changed = device->getFileSystem()->changeWorkingDirectoryTo(workingDir.c_str()); assert_log(changed); // adding a folder archive which just should not really change anything device->getFileSystem()->addFileArchive( "./" ); if ( fs->existFile(empty) ) { logTestString("Empty filename should not exist in folder file archive.\n"); result = false; } // remove it again to not affect other tests device->getFileSystem()->removeFileArchive( device->getFileSystem()->getFileArchiveCount() ); result &= testFlattenFilename(fs); result &= testgetAbsoluteFilename(fs); result &= testgetRelativeFilename(fs); device->closeDevice(); device->run(); device->drop(); return result; }
4,824
1,803
#include "Resource.h" #define PREFETCH_SIZE 128*1024 using namespace Filesystem; HashMap<String, Resource*> Resource::pool; const Resource& Resource::request(StringRef path) { Resource* resource; auto iter = pool.find(path); if(iter != pool.end()) { resource = iter->second; } else { resource = new Resource(path); pool.emplace(path, resource); } return *resource; } void Resource::drop(StringRef path) { auto it = pool.find(path); if (it != pool.end()) { delete it->second; pool.erase(it); } } Resource::Resource(const File& file) : file(file) { } Resource::~Resource() { } void Resource::compile() { } const File& Resource::getFile() const { return file; }
795
262
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; for(int a0 = 0; a0 < t; a0++){ int n; cin >> n; int min = 1001, max = 0; for(int x_i = 0; x_i < n; x_i++){ int x; cin >> x; if (x < min) min = x; if (x > max) max = x; } cout << max-min << endl; } return 0; }
435
167
// // Generated file. Do not edit. // // clang-format off #include "generated_plugin_registrant.h" #include <flutter_audio_capture/flutter_audio_capture_plugin.h> void fl_register_plugins(FlPluginRegistry* registry) { g_autoptr(FlPluginRegistrar) flutter_audio_capture_registrar = fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterAudioCapturePlugin"); flutter_audio_capture_plugin_register_with_registrar(flutter_audio_capture_registrar); }
469
160
#ifndef _WIN32 #include <sys/types.h> #include <signal.h> #include <sys/socket.h> #include <sys/un.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/file.h> #include <fcntl.h> #include <unistd.h> #include <algorithm> #include <netinet/in.h> #include <sys/time.h> #if defined(__APPLE__) || defined(BSD) #include <sys/wait.h> #else #include <sys/signalfd.h> #include <wait.h> #endif #include <poll.h> #include <errno.h> #include "../io/Reader.hh" #include "socket_serve.hh" #include "../../vp8/util/memory.hh" #include <set> static char hex_nibble(uint8_t val) { if (val < 10) return val + '0'; return val - 10 + 'a'; } static const char last_prefix[] = "/tmp/"; static const char last_postfix[]=".uport"; static const char zlast_postfix[]=".z0"; static char socket_name[sizeof((struct sockaddr_un*)0)->sun_path] = {}; static char zsocket_name[sizeof((struct sockaddr_un*)0)->sun_path] = {}; static const char lock_ext[]=".lock"; bool random_name = false; static char socket_lock[sizeof((struct sockaddr_un*)0)->sun_path + sizeof(lock_ext)]; int lock_file = -1; bool is_parent_process = true; static void name_socket(FILE * dev_random) { random_name = true; char random_data[16] = {0}; auto retval = fread(random_data, 1, sizeof(random_data), dev_random); (void)retval;// dev random should yield reasonable results memcpy(socket_name, last_prefix, strlen(last_prefix)); memcpy(zsocket_name, last_prefix, strlen(last_prefix)); size_t offset = strlen(last_prefix); for (size_t i = 0; i < sizeof(random_data); ++i) { always_assert(offset + 3 + sizeof(last_postfix) < sizeof(socket_name)); always_assert(offset + 3 + sizeof(zlast_postfix) < sizeof(zsocket_name)); uint8_t hex = random_data[i]; socket_name[offset] = hex_nibble(hex>> 4); socket_name[offset + 1] = hex_nibble(hex & 0xf); zsocket_name[offset] = hex_nibble(hex>> 4); zsocket_name[offset + 1] = hex_nibble(hex & 0xf); offset += 2; if (i == 4 || i == 6 || i == 8 || i == 14) { socket_name[offset] = '-'; zsocket_name[offset] = '-'; ++offset; } } always_assert(offset + sizeof(last_postfix) < sizeof(socket_name)); always_assert(offset + sizeof(zlast_postfix) < sizeof(zsocket_name)); always_assert(offset + sizeof(lock_ext) < sizeof(socket_lock)); memcpy(socket_name+offset, last_postfix, sizeof(last_postfix)); memcpy(zsocket_name+offset, zlast_postfix, sizeof(zlast_postfix)); memcpy(socket_lock, socket_name, offset); memcpy(socket_lock+offset, lock_ext, sizeof(lock_ext)); } static void cleanup_socket(int) { if (is_parent_process) { unlink(socket_name); unlink(zsocket_name); if (socket_lock[0] && random_name) { unlink(socket_lock); } exit(0); return; } custom_exit(ExitCode::SUCCESS); } static void nop(int){} pid_t accept_new_connection(int active_connection, const SocketServeWorkFunction& work, uint32_t global_max_length, int lock_fd, bool force_zlib) { pid_t serve_file = fork(); if (serve_file == 0) { is_parent_process = false; while (close(1) < 0 && errno == EINTR){ // close stdout } if (lock_fd >= 0) { while (close(lock_fd) < 0 && errno == EINTR){ // close socket lock so future servers may reacquire the lock } } IOUtil::FileReader reader(active_connection, global_max_length, true); IOUtil::FileWriter writer(active_connection, false, true); work(&reader, &writer, global_max_length, force_zlib); custom_exit(ExitCode::SUCCESS); } else { while (close(active_connection) < 0 && errno == EINTR){ // close the Unix Domain Socket } } return serve_file; } int should_wait_bitmask(size_t children_size, uint32_t max_children) { if (max_children && children_size >= max_children) { return 0; } return WNOHANG; } int make_sigchld_fd() { int fd = -1; #if !(defined(__APPLE__) || defined(BSD)) sigset_t sigset; int err = sigemptyset(&sigset); always_assert(err == 0); err = sigaddset(&sigset, SIGCHLD); always_assert(err == 0); // the signalfd will only receive SIG_BLOCK'd signals err = sigprocmask(SIG_BLOCK, &sigset, NULL); always_assert(err == 0); fd = signalfd(-1, &sigset, 0); always_assert(fd != -1); #endif return fd; } void write_num_children(size_t num_children) { if (num_children > 0xff) { num_children = 0xff; } // lets just keep a byte of state about the number of children if (lock_file != -1) { int err; while((err = lseek(lock_file, 0, SEEK_SET)) < 0 && errno == EINTR){ } uint8_t num_children_byte = (uint8_t)num_children; while((err = write(lock_file, &num_children_byte, sizeof(num_children_byte))) < 0 && errno == EINTR) { } } } void serving_loop(int unix_domain_socket_server, int unix_domain_socket_server_zlib, int tcp_socket_server, int tcp_socket_server_zlib, const SocketServeWorkFunction& work, uint32_t global_max_length, uint32_t max_children, bool do_cleanup_socket, int lock_fd) { int sigchild_fd = make_sigchld_fd(); int num_fds = 0; struct pollfd fds[5]; if (sigchild_fd != -1) { fds[0].fd = sigchild_fd; fds[0].events = POLLIN | POLLERR | POLLHUP; num_fds+= 1; } if (unix_domain_socket_server_zlib != -1) { fds[num_fds].fd = unix_domain_socket_server_zlib; ++num_fds; } if (tcp_socket_server_zlib != -1) { fds[num_fds].fd = tcp_socket_server_zlib; ++num_fds; } if (unix_domain_socket_server != -1) { fds[num_fds].fd = unix_domain_socket_server; ++num_fds; } if (tcp_socket_server != -1) { fds[num_fds].fd = tcp_socket_server; ++num_fds; } for (int i = 0; i < num_fds; ++i) { int err; while ((err = fcntl(fds[i].fd, F_SETFL, O_NONBLOCK)) == -1 && errno == EINTR) {} always_assert(err == 0); fds[i].events = POLLIN; } std::set<pid_t> children; int status; while(true) { write_num_children(children.size()); for (pid_t term_pid = 0; (term_pid = waitpid(-1, &status, should_wait_bitmask(children.size(), max_children))) > 0;) { std::set<pid_t>::iterator where = children.find(term_pid); if (where != children.end()) { children.erase(where); } else { fprintf(stderr, "Pid %d not found as child of this\n", term_pid); assert(false && "pid msut be in child\n"); } if (WIFEXITED(status)) { fprintf(stderr, "Child %d exited with code %d\n", term_pid, WEXITSTATUS(status)); } else if (WIFSIGNALED(status)) { fprintf(stderr, "Child %d exited with signal %d\n", term_pid, WTERMSIG(status)); } else { fprintf(stderr, "Child %d exited with another cause: %d\n", term_pid, status); } fflush(stderr); write_num_children(children.size()); } int ret = poll(fds, num_fds, sigchild_fd == -1 ? 60 : -1); // need a timeout (30 ms) in case a SIGCHLD was missed between the waitpid and the poll if (ret == 0) { // no events ready, just timed out, check for missed SIGCHLD continue; } if (ret < 0 && errno == EINTR) { continue; } for (int i = 0; i < num_fds; ++i) { if (fds[i].revents & POLLIN) { fds[i].revents = 0; if (fds[i].fd == sigchild_fd) { #if !(defined(__APPLE__) || defined(BSD)) struct signalfd_siginfo info; ssize_t ignore = read(fds[i].fd, &info, sizeof(info)); (void)ignore; #endif continue; // we can't receive on this } struct sockaddr_un client; socklen_t len = sizeof(client); int active_connection = accept(fds[i].fd, (sockaddr*)&client, &len); if (active_connection >= 0) { int flags; while ((flags = fcntl(active_connection, F_GETFL, 0)) == -1 && errno == EINTR){} always_assert(flags != -1); if (flags & O_NONBLOCK) { flags &= ~O_NONBLOCK; // inheritance of nonblocking flag not specified across systems while (fcntl(active_connection, F_SETFL, flags) == -1 && errno == EINTR){} } children.insert(accept_new_connection(active_connection, work, global_max_length, lock_fd, fds[i].fd == unix_domain_socket_server_zlib || fds[i].fd == tcp_socket_server_zlib)); } else { if (errno != EINTR && errno != EWOULDBLOCK && errno != EAGAIN) { fprintf(stderr, "Error accepting connection: %s", strerror(errno)); cleanup_socket(0); } } } } } } int setup_tcp_socket(int port, int listen_backlog) { int socket_fd = socket(AF_INET, SOCK_STREAM, 0); always_assert(socket_fd > 0); struct sockaddr_in serv_addr; memset(&serv_addr, 0, sizeof(struct sockaddr_in)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(port); int optval = 1; setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); if (bind(socket_fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) { custom_exit(ExitCode::COULD_NOT_BIND_PORT); } int err = listen(socket_fd, listen_backlog); always_assert(err == 0); return socket_fd; } int setup_socket(const char *file_name, int listen_backlog) { int err; int socket_fd = socket(PF_UNIX, SOCK_STREAM, 0); always_assert(socket_fd > 0); struct sockaddr_un address; memset(&address, 0, sizeof(struct sockaddr_un)); address.sun_family = AF_UNIX; memcpy(address.sun_path, file_name, std::min(strlen(file_name), sizeof(address.sun_path))); err = bind(socket_fd, (struct sockaddr*)&address, sizeof(address)); always_assert(err == 0); err = listen(socket_fd, listen_backlog); int ret = chmod(file_name, 0666); (void)ret; always_assert(err == 0); return socket_fd; } void socket_serve(const SocketServeWorkFunction &work_fn, uint32_t global_max_length, const ServiceInfo &service_info) { bool do_cleanup_socket = true; int lock_fd = -1; if (service_info.uds != NULL) { do_cleanup_socket = false; size_t len = strlen(service_info.uds); if (len + 1 < sizeof(socket_name)) { memcpy(socket_name, service_info.uds, len); socket_name[len] = '\0'; } else { fprintf(stderr, "Path too long for %s\n", service_info.uds); always_assert(false && "input file name too long\n"); } memcpy(socket_lock, socket_name, sizeof(socket_name)); memcpy(zsocket_name, socket_name, sizeof(socket_name)); memcpy(socket_lock + strlen(socket_lock), lock_ext, sizeof(lock_ext)); memcpy(zsocket_name + strlen(zsocket_name), zlast_postfix, sizeof(zlast_postfix)); do { lock_file = open(socket_lock, O_RDWR|O_CREAT|O_TRUNC, S_IRUSR | S_IRGRP | S_IROTH | S_IWUSR); } while(lock_file < 0 && errno == EINTR); if (lock_file >= 0) { lock_fd = lock_file; int err = 0; do { err = ::flock(lock_file, LOCK_EX|LOCK_NB); } while(err < 0 && errno == EINTR); if (err == 0) { do { err = remove(socket_name); }while (err < 0 && errno == EINTR); do { err = remove(zsocket_name); }while (err < 0 && errno == EINTR); signal(SIGINT, &cleanup_socket); // if we have the lock we can clean it up signal(SIGQUIT, &cleanup_socket); signal(SIGTERM, &cleanup_socket); do_cleanup_socket = true; } } } else { FILE* dev_random = fopen("/dev/urandom", "rb"); name_socket(dev_random); int fret = fclose(dev_random); always_assert(fret == 0); do { lock_file = open(socket_lock, O_RDWR|O_CREAT|O_TRUNC, S_IRUSR | S_IRGRP | S_IROTH | S_IWUSR); } while(lock_file < 0 && errno == EINTR); signal(SIGINT, &cleanup_socket); signal(SIGQUIT, &cleanup_socket); signal(SIGTERM, &cleanup_socket); } signal(SIGCHLD, &nop); // listen int socket_fd = -1; int zsocket_fd = -1; int socket_tcp = -1; int zsocket_tcp = -1; if (service_info.listen_uds) { socket_fd = setup_socket(socket_name, service_info.listen_backlog); zsocket_fd = setup_socket(zsocket_name, service_info.listen_backlog); } if (service_info.listen_tcp) { socket_tcp = setup_tcp_socket(service_info.port, service_info.listen_backlog); zsocket_tcp = setup_tcp_socket(service_info.zlib_port, service_info.listen_backlog); } fprintf(stdout, "%s\n", socket_name); fflush(stdout); serving_loop(socket_fd, zsocket_fd, socket_tcp, zsocket_tcp, work_fn, global_max_length, service_info.max_children, do_cleanup_socket, lock_fd); } #endif
14,651
4,878
#include <libgraphic/Painter.h> #include <libwidget/elements/IconElement.h> namespace Widget { IconElement::IconElement(Ref<Graphic::Icon> icon, Graphic::IconSize size) : _icon{icon}, _icon_size{size} { } void IconElement::paint(Graphic::Painter &painter, const Math::Recti &) { if (!_icon) { return; } Math::Recti destination = _icon->bound(_icon_size).centered_within(bound()); painter.blit( *_icon, _icon_size, destination, color(THEME_FOREGROUND)); } Math::Vec2i IconElement::size() { if (_icon) { return _icon->bound(_icon_size).size(); } else { return bound().size(); } } } // namespace Widget
711
253
/* * AttrPlotPluginWrapper.cpp * * Created on: 28 Feb 2017 * Author: Blaz Kranjc */ #include "AttrPlotPluginWrapper.h" AttrPlotPluginWrapper::AttrPlotPluginWrapper(const std::string& port, int max_attributes, int cache_size, int max_selected, const std::string& in_port, int in_addr) : NDPluginAttrPlot(port.c_str(), max_attributes, cache_size, max_selected, in_port.c_str(), in_addr, 1000, 0, 0, 0), AsynPortClientContainer(port) { } AttrPlotPluginWrapper::~AttrPlotPluginWrapper () { cleanup(); }
550
201
/* Copyright (c) 2005-2020, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Oxford 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. */ #ifndef TESTCARDIACSIMULATION_HPP_ #define TESTCARDIACSIMULATION_HPP_ #include <cxxtest/TestSuite.h> #include <string> #include <vector> #include <sstream> #include "AbstractCardiacProblem.hpp" #include "MonodomainProblem.hpp" #include "CardiacSimulation.hpp" #include "OutputFileHandler.hpp" #include "CompareHdf5ResultsFiles.hpp" #include "FileFinder.hpp" #include "PetscTools.hpp" #include "HeartEventHandler.hpp" #include "AbstractCardiacCellInterface.hpp" #include "DistributedVectorFactory.hpp" #include "Warnings.hpp" #include "CellMLToSharedLibraryConverter.hpp" #include "PetscSetupAndFinalize.hpp" class TestCardiacSimulation : public CxxTest::TestSuite { void setUp() { HeartEventHandler::Reset(); } // // void CreateOptionsFile(const OutputFileHandler& rHandler, // const std::string& rModelName, // const std::vector<std::string>& rArgs, // const std::string& rExtraXml="") // { // if (PetscTools::AmMaster()) // { // out_stream p_optfile = rHandler.OpenOutputFile(rModelName + "-conf.xml"); // (*p_optfile) << "<?xml version='1.0'?>" << std::endl // << "<pycml_config>" << std::endl // << "<command_line_args>" << std::endl; // for (unsigned i=0; i<rArgs.size(); i++) // { // (*p_optfile) << "<arg>" << rArgs[i] << "</arg>" << std::endl; // } // (*p_optfile) << "</command_line_args>" << std::endl // << rExtraXml // << "</pycml_config>" << std::endl; // p_optfile->close(); // } // PetscTools::Barrier("CreateOptionsFile"); // } public: void TestMono1dSmall() { if (PetscTools::GetNumProcs() > 3u) { TS_TRACE("This test is not suitable for more than 3 processes."); return; } // Fox2002BackwardEuler cell model CardiacSimulation simulation("heart/test/data/xml/monodomain1d_small.xml", true); TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "mono_1d_small", false, "SaveMono1D", "SimulationResults", true, 1e-6)); /* If the above fails, and you are happy the new results are correct, uncomment the following line, * run the test, and then do cp /tmp/$USER/testoutput/SaveMono1D/SimulationResults.h5 heart/test/data/cardiac_simulations/mono_1d_small.h5 */ //assert(0); CardiacSimulation simulation2("heart/test/data/xml/monodomain1d_resume.xml", true); } void TestMono2dSmall() { if (PetscTools::GetNumProcs() > 3u) { TS_TRACE("This test is not suitable for more than 3 processes."); return; } //Clear any warnings from previous tests Warnings::QuietDestroy(); { CardiacSimulation simulation("heart/test/data/xml/monodomain2d_small.xml", false, true); boost::shared_ptr<AbstractUntemplatedCardiacProblem> p_problem = simulation.GetSavedProblem(); TS_ASSERT(p_problem); MonodomainProblem<2,2>* p_mono_problem = dynamic_cast<MonodomainProblem<2,2>*>(p_problem.get()); TS_ASSERT(p_mono_problem != NULL); DistributedVectorFactory* p_vector_factory = p_mono_problem->rGetMesh().GetDistributedVectorFactory(); for (unsigned node_global_index = p_vector_factory->GetLow(); node_global_index < p_vector_factory->GetHigh(); node_global_index++) { AbstractCardiacCellInterface* p_cell = p_mono_problem->GetTissue()->GetCardiacCell(node_global_index); TS_ASSERT_DELTA(p_cell->GetParameter("membrane_fast_sodium_current_conductance"), 23 * 0.99937539038101175, 1e-6); TS_ASSERT_DELTA(p_cell->GetParameter("membrane_rapid_delayed_rectifier_potassium_current_conductance"), 0.282/3.0, 1e-6); } if (p_vector_factory->GetLocalOwnership() > 0) { TS_ASSERT_EQUALS(Warnings::Instance()->GetNumWarnings(), p_vector_factory->GetLocalOwnership()); std::stringstream msg; msg << "Cannot apply drug to cell at node " << p_vector_factory->GetLow() << " as it has no parameter named 'not_a_current_conductance'."; TS_ASSERT_EQUALS(Warnings::Instance()->GetNextWarningMessage(), msg.str()); } else { //There is now a warning on the top processes about the fact that no cells were assigned TS_ASSERT_EQUALS(Warnings::Instance()->GetNumWarnings(), 1u); std::stringstream msg; msg << "No cells were assigned to process "<< PetscTools::GetMyRank(); msg << " in AbstractCardiacTissue constructor. Advice: Make total number of processors no greater than number of nodes in the mesh"; TS_ASSERT_EQUALS(Warnings::Instance()->GetNextWarningMessage(), msg.str()); } } //Check that the post-processed file is there and remove it FileFinder pseudoecg("SaveMono2D/output/PseudoEcgFromElectrodeAt_0.05_0.05_0.dat", RelativeTo::ChasteTestOutput); if (PetscTools::AmMaster()) { TS_ASSERT(pseudoecg.Exists()); // Only master tests. This prevents master from removing file before other processes have seen it pseudoecg.Remove(); TS_ASSERT(pseudoecg.Exists() == false); } //Check that archive which has just been produced can be read CardiacSimulation simulation2("heart/test/data/xml/monodomain2d_resume.xml"); //Check that the post-processed file is back after the simulation has been restarted TS_ASSERT(pseudoecg.Exists()); // (Should check that it's bigger than the one we deleted) Warnings::QuietDestroy(); } /* Do the same as before but ask for post-processing after the simulation has been run and checkpointed. */ void TestMono2dSmallAddPostprocessingOnResume() { if (PetscTools::GetNumProcs() > 3u) { TS_TRACE("This test is not suitable for more than 3 processes."); return; } //Clear any warnings from previous tests Warnings::QuietDestroy(); { CardiacSimulation simulation("heart/test/data/xml/monodomain2d_small2.xml", false, true); } //Check that the post-processed file is not produced in the original simulation FileFinder pseudoecg("SaveMono2D2/output/PseudoEcgFromElectrodeAt_0.05_0.05_0.dat", RelativeTo::ChasteTestOutput); TS_ASSERT(pseudoecg.Exists() == false); //Check that archive which has just been produced can be read CardiacSimulation simulation2("heart/test/data/xml/monodomain2d_resume2.xml"); //Check that the post-processed file is present after the simulation has been restarted TS_ASSERT(pseudoecg.Exists()); // (Should check that it's bigger than the one we deleted) Warnings::QuietDestroy(); } void TestMono3dSmall() { if (PetscTools::GetNumProcs() > 3u) { TS_TRACE("This test is not suitable for more than 3 processes."); return; } CardiacSimulation simulation("heart/test/data/xml/monodomain3d_small.xml"); //Check that archive which has just been produced can be read CardiacSimulation simulation2("heart/test/data/xml/monodomain3d_resume.xml"); } void TestMono1dSodiumBlockBySettingNamedParameter() { CardiacSimulation simulation("heart/test/data/xml/monodomain1d_sodium_block.xml"); TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "mono_1d_sodium_block", false, "Mono1dSodiumBlock", "SimulationResults", true, 2.5e-3)); // Test exception TS_ASSERT_THROWS_THIS(CardiacSimulation bad_param("heart/test/data/xml/bad_cell_parameter.xml"), "No parameter named 'missing-parameter'."); } void TestMonoStimUsingEllipsoids() { if (PetscTools::GetNumProcs() > 3u) { TS_TRACE("This test is not suitable for more than 3 processes."); return; } // Fox2002BackwardEuler cell model CardiacSimulation simulation("heart/test/data/xml/monodomain1d_stim_using_ellipsoid.xml", true); TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "monodomain1d_stim_using_ellipsoid", false, "Mono1DStimUsingEllipsoid", "SimulationResults", true, 1e-6)); } void TestBi1dSmall() { if (PetscTools::GetNumProcs() > 3u) { TS_TRACE("This test is not suitable for more than 3 processes."); return; } { CardiacSimulation simulation("heart/test/data/xml/bidomain1d_small.xml"); } { CardiacSimulation simulation2("heart/test/data/xml/bidomain1d_resume.xml"); } { // The default resume file specifies a simulation duration of zero. // In reality the user should edit the file to specify something sensible... FileFinder resume_xml("SaveBi1D_checkpoints/0.1ms/ResumeParameters.xml", RelativeTo::ChasteTestOutput); TS_ASSERT_THROWS_THIS(CardiacSimulation simulation(resume_xml.GetAbsolutePath()), "The simulation duration must be positive, not -0.1"); } } void TestBi2dSmall() { if (PetscTools::GetNumProcs() > 3u) { TS_TRACE("This test is not suitable for more than 3 processes."); return; } CardiacSimulation simulation("heart/test/data/xml/bidomain2d_small.xml"); //Check that archive which has just been produced can be read CardiacSimulation simulation2("heart/test/data/xml/bidomain2d_resume.xml"); } void TestBi3dSmall() { if (PetscTools::GetNumProcs() > 3u) { TS_TRACE("This test is not suitable for more than 3 processes."); return; } CardiacSimulation simulation("heart/test/data/xml/bidomain3d_small.xml"); //Check that archive which has just been produced can be read CardiacSimulation simulation2("heart/test/data/xml/bidomain3d_resume.xml"); } void TestBiWithBath1dSmall() { { CardiacSimulation simulation("heart/test/data/xml/bidomain_with_bath1d_small.xml"); } { CardiacSimulation simulation2("heart/test/data/xml/bidomain_with_bath1d_resume.xml"); } { // The default resume file specifies a simulation duration of zero. // In reality the user should edit the file to specify something sensible... FileFinder resume_xml("SaveBiWithBath1D_checkpoints/0.1ms/ResumeParameters.xml", RelativeTo::ChasteTestOutput); TS_ASSERT_THROWS_THIS(CardiacSimulation simulation(resume_xml.GetAbsolutePath()), "The simulation duration must be positive, not -0.1"); } } void TestBiWithBath2dSmall() { CardiacSimulation simulation("heart/test/data/xml/bidomain_with_bath2d_small.xml"); CardiacSimulation simulation2("heart/test/data/xml/bidomain_with_bath2d_resume.xml"); } void TestBiWithBath3dSmall() { CardiacSimulation simulation("heart/test/data/xml/bidomain_with_bath3d_small.xml"); CardiacSimulation simulation2("heart/test/data/xml/bidomain_with_bath3d_resume.xml"); } void TestBiWith2dHeterogeneousConductivities() { CardiacSimulation simulation("heart/test/data/xml/bidomain2d_heterogeneous.xml", true); } void TestCardiacSimulationBasicBidomainShort() { // Fox2002BackwardEuler cell model // run a bidomain_with_bath simulation CardiacSimulation simulation("heart/test/data/xml/base_bidomain_short.xml"); // compare the files, using the CompareFilesViaHdf5DataReader() method TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "base_bidomain_short_results", false, "BaseBidomainShort", "SimulationResults", true, 1e-6)); } void TestCardiacSimulationBasicMonodomainShort() { // Fox2002BackwardEuler cell model // run a bidomain simulation CardiacSimulation simulation("heart/test/data/xml/base_monodomain_short.xml"); // compare the files, using the CompareFilesViaHdf5DataReader() method TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "base_monodomain_short_results", false, "BaseMonodomainShort", "SimulationResults", true, 1e-6)); } void TestCardiacSimulationPostprocessMonodomain() { // Fox2002BackwardEuler cell model // run a bidomain simulation CardiacSimulation simulation("heart/test/data/xml/postprocess_monodomain_short.xml"); std::string foldername = "PostprocessMonodomainShort"; // compare the files, using the CompareFilesViaHdf5DataReader() method TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "postprocess_monodomain_short_results", false, foldername, "SimulationResults", true, 1e-6)); { // look for the existence of post-processing files TS_ASSERT(FileFinder(foldername + "/output/Apd_90_minus_30_Map.dat", RelativeTo::ChasteTestOutput).Exists()); TS_ASSERT(FileFinder(foldername + "/output/ConductionVelocityFromNode10.dat", RelativeTo::ChasteTestOutput).Exists()); TS_ASSERT(FileFinder(foldername + "/output/ConductionVelocityFromNode20.dat", RelativeTo::ChasteTestOutput).Exists()); TS_ASSERT(FileFinder(foldername + "/output/MaxUpstrokeVelocityMap_minus_30.dat", RelativeTo::ChasteTestOutput).Exists()); TS_ASSERT(FileFinder(foldername + "/output/UpstrokeTimeMap_minus_30.dat", RelativeTo::ChasteTestOutput).Exists()); TS_ASSERT(FileFinder(foldername + "/output/PseudoEcgFromElectrodeAt_0.05_0.05_0.dat", RelativeTo::ChasteTestOutput).Exists()); } } void TestCardiacSimulationArchiveBidomain() { // Fox2002BackwardEuler cell model // run a bidomain simulation CardiacSimulation simulation("heart/test/data/xml/save_bidomain_short.xml"); std::string foldername = "SaveBidomainShort"; // compare the files, using the CompareFilesViaHdf5DataReader() method TS_ASSERT(CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "save_bidomain_short_results", false, foldername, "SimulationResults", true, 1e-5)); FileFinder file(foldername + "_checkpoints/0.2ms/" + foldername + "_0.2ms/archive.arch.0", RelativeTo::ChasteTestOutput); TS_ASSERT(file.Exists()); /* If you want to update the .h5 results for this test for any reason, you need to stop the following test adding to them. * So uncomment the assert(), run the test, and then do: cp /tmp/chaste/testoutput/SaveBidomainShort/SimulationResults.h5 heart/test/data/cardiac_simulations/save_bidomain_short_results.h5 */ //assert(0); } // requires TestCardiacSimulationArchiveBidomain() to have been run void TestCardiacSimulationResumeBidomain() { // run a bidomain simulation HeartConfig::Instance()->SetSpaceDimension(1); FileFinder resume_xml("heart/test/data/xml/resume_bidomain_short.xml", RelativeTo::ChasteSourceRoot); OutputFileHandler checkpoint_dir("SaveBidomainShort_checkpoints/0.2ms", false); FileFinder copied_xml = checkpoint_dir.CopyFileTo(resume_xml); CardiacSimulation simulation(copied_xml.GetAbsolutePath()); std::string foldername = "SaveBidomainShort"; // compare the files, using the CompareFilesViaHdf5DataReader() method TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "resume_bidomain_short_results", false, foldername, "SimulationResults", true, 1e-5)); //assert(0); } void TestCardiacSimulationArchiveMonodomain() { // Fox2002BackwardEuler cell model // run a bidomain simulation CardiacSimulation simulation("heart/test/data/xml/save_monodomain_short.xml"); std::string foldername = "SaveMonodomainShort"; // compare the files, using the CompareFilesViaHdf5DataReader() method TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "save_monodomain_short_results", false, foldername, "SimulationResults", true, 1e-6)); FileFinder file(foldername + "_checkpoints/0.2ms/" + foldername + "_0.2ms/archive.arch.0", RelativeTo::ChasteTestOutput); TS_ASSERT(file.Exists()); /* If you want to update the .h5 results for this test for any reason, you need to stop the following test adding to them. * So uncomment the assert(), run the test, and then do: cp /tmp/chaste/testoutput/SaveMonodomainShort/SimulationResults.h5 heart/test/data/cardiac_simulations/save_monodomain_short_results.h5 */ //assert(0); } // requires TestCardiacSimulationArchiveMonodomain() to have been run void TestCardiacSimulationResumeMonodomain() { // run a monodomain simulation HeartConfig::Instance()->SetSpaceDimension(1); CardiacSimulation simulation("heart/test/data/xml/resume_monodomain_short.xml"); std::string foldername = "SaveMonodomainShort"; // compare the files, using the CompareFilesViaHdf5DataReader() method TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "resume_monodomain_short_results", false, foldername, "SimulationResults", true, 1e-6)); } void TestCardiacSimulationArchiveDynamic() { #ifdef CHASTE_CAN_CHECKPOINT_DLLS // run a monodomain simulation { CardiacSimulation simulation("heart/test/data/xml/save_monodomain_dynamic.xml"); } std::string foldername = "SaveMonodomainDynamic"; // compare the files, using the CompareFilesViaHdf5DataReader() method TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "save_monodomain_dynamic", false, foldername, "SimulationResults", true)); FileFinder file(foldername + "_checkpoints/0.2ms/" + foldername + "_0.2ms/archive.arch.0", RelativeTo::ChasteTestOutput); TS_ASSERT(file.Exists()); /* If you want to update the .h5 results for this test for any reason, you need to stop the following lines adding to them. * So uncomment the assert(), run the test, and then do: cp /tmp/chaste/testoutput/SaveMonodomainDynamic/SimulationResults.h5 heart/test/data/cardiac_simulations/save_monodomain_dynamic.h5 */ //assert(0); //resume the simulation { CardiacSimulation simulation("heart/test/data/xml/resume_monodomain_dynamic.xml"); } // compare the files, using the CompareFilesViaHdf5DataReader() method TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "resume_monodomain_dynamic", false, foldername, "SimulationResults", true)); #endif // CHASTE_CAN_CHECKPOINT_DLLS } /** * Note: from Chaste release 3.1 onward we no longer support Boost 1.33. * The earliest version of Boost supported is 1.34 * Run TestCardiacSimulationArchiveBidomain on 4 processors to create the archive for this test, * and copy it to the repository using: * scons build=GccOpt_hostconfig,boost=1-34_4 test_suite=heart/test/TestCardiacSimulation.hpp cp -r /tmp/$USER/testoutput/SaveBidomainShort_checkpoints/0.2ms heart/test/data/checkpoint_migration_via_xml/ rm -f heart/test/data/checkpoint_migration_via_xml/0.2ms/SaveBidomainShort/progress_status.txt rm -f heart/test/data/checkpoint_migration_via_xml/0.2ms/SaveBidomainShort_0.2ms/mesh.ncl rm -f heart/test/data/checkpoint_migration_via_xml/0.2ms/SaveBidomainShort_0.2ms/ChasteParameters_?_?xsd rm -rf heart/test/data/checkpoint_migration_via_xml/0.2ms/SaveBidomainShort/output */ void TestCardiacSimulationResumeMigration() { // We can only load simulations from CHASTE_TEST_OUTPUT, so copy the archives there std::string source_directory = "heart/test/data/checkpoint_migration_via_xml/0.2ms/"; std::string folder_1 = "SaveBidomainShort"; std::string folder_2 = "SaveBidomainShort_0.2ms"; FileFinder to_directory1(OutputFileHandler::GetChasteTestOutputDirectory() + folder_1, RelativeTo::Absolute); FileFinder to_directory2(OutputFileHandler::GetChasteTestOutputDirectory() + folder_2, RelativeTo::Absolute); FileFinder from_directory1(source_directory + folder_1, RelativeTo::ChasteSourceRoot); FileFinder from_directory2(source_directory + folder_2, RelativeTo::ChasteSourceRoot); TRY_IF_MASTER( to_directory1.Remove(); to_directory2.Remove(); TS_ASSERT_EQUALS(to_directory1.Exists(), false); TS_ASSERT_EQUALS(to_directory2.Exists(), false); from_directory1.CopyTo(to_directory1); from_directory2.CopyTo(to_directory2); ); // Resume CardiacSimulation simulation("heart/test/data/xml/resume_migration.xml"); // Compare results TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "resume_bidomain_short_results", false, "SaveBidomainShort", "SimulationResults", true, 1e-5)); } void runSimulation(const std::string& rParametersFileName) { CardiacSimulation simulation(rParametersFileName); } void checkParameter(AbstractCardiacCellInterface* pCell, unsigned globalIndex) { // Check one of the parameters has been set in the central region TS_ASSERT_EQUALS(pCell->GetNumberOfParameters(), 3u); double expected_value; if (globalIndex <= 4 || globalIndex >= 16) { expected_value = 23.0; } else { expected_value = 0.0; } TS_ASSERT_DELTA(pCell->GetParameter("membrane_fast_sodium_current_conductance"), expected_value, 1e-12); TS_ASSERT_DELTA(pCell->GetParameter("membrane_rapid_delayed_rectifier_potassium_current_conductance"), 0.282, 1e-12); TS_ASSERT_DELTA(pCell->GetParameter("membrane_L_type_calcium_current_conductance"), 0.09, 1e-12); // Check stimulus has been replaced. It started as 0-1ms at x<=0.02, and should now be 600-601ms at x<=0.02 if (globalIndex < 3) { TS_ASSERT_EQUALS(pCell->GetStimulus(0.0), 0.0); TS_ASSERT_EQUALS(pCell->GetStimulus(0.5), 0.0); TS_ASSERT_EQUALS(pCell->GetStimulus(1.0), 0.0); TS_ASSERT_EQUALS(pCell->GetStimulus(599.9), 0.0); TS_ASSERT_EQUALS(pCell->GetStimulus(600.0), -200000.0); TS_ASSERT_EQUALS(pCell->GetStimulus(600.5), -200000.0); TS_ASSERT_EQUALS(pCell->GetStimulus(601.0), -200000.0); TS_ASSERT_EQUALS(pCell->GetStimulus(601.1), 0.0); } else { // Always zero... TS_ASSERT_EQUALS(pCell->GetStimulus(0.0), 0.0); TS_ASSERT_EQUALS(pCell->GetStimulus(0.5), 0.0); TS_ASSERT_EQUALS(pCell->GetStimulus(600.5), 0.0); TS_ASSERT_EQUALS(pCell->GetStimulus(10.0), 0.0); } } void doTestResumeChangingSettings(const std::string& rParametersFileName) { std::string foldername = "SaveMonodomainWithParameter"; // Save runSimulation(rParametersFileName); // Just check that the checkpoint exists FileFinder archive(foldername + "_checkpoints/1ms/" + foldername + "_1ms/archive.arch.0", RelativeTo::ChasteTestOutput); TS_ASSERT(archive.Exists()); { // Load CardiacSimulation simulation("heart/test/data/xml/resume_monodomain_changing_parameter.xml", false, true); boost::shared_ptr<AbstractUntemplatedCardiacProblem> p_problem = simulation.GetSavedProblem(); TS_ASSERT(p_problem); MonodomainProblem<1,1>* p_mono_problem = dynamic_cast<MonodomainProblem<1,1>*>(p_problem.get()); TS_ASSERT(p_mono_problem != NULL); DistributedVectorFactory* p_vector_factory = p_mono_problem->rGetMesh().GetDistributedVectorFactory(); for (unsigned node_global_index = p_vector_factory->GetLow(); node_global_index < p_vector_factory->GetHigh(); node_global_index++) { AbstractCardiacCellInterface* p_cell = p_mono_problem->GetTissue()->GetCardiacCell(node_global_index); checkParameter(p_cell, node_global_index); } // compare the files, using the CompareFilesViaHdf5DataReader() method TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "resume_monodomain_changing_parameter_results", false, foldername, "SimulationResults", true)); } } void TestResumeChangingSettings() { doTestResumeChangingSettings("heart/test/data/xml/save_monodomain_with_parameter.xml"); doTestResumeChangingSettings("heart/test/data/xml/save_monodomain_with_parameter_append.xml"); } void TestCardiacSimulationPatchwork() { OutputFileHandler handler("DynamicallyLoadedModel"); FileFinder cellml_file("heart/dynamic/luo_rudy_1991_dyn.cellml", RelativeTo::ChasteSourceRoot); handler.CopyFileTo(cellml_file); CardiacSimulation simulation("heart/test/data/xml/base_monodomain_patchwork.xml"); std::string foldername = "Patchwork"; // compare the files, using the CompareFilesViaHdf5DataReader() method TS_ASSERT(CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "patchwork_results", false, foldername, "SimulationResults", true, 1e-5)); } void TestCardiacSimulationKirsten() { if (PetscTools::GetNumProcs() > 2u) { // There are only 2 layers of nodes in this simulation -- z length is equal to space step. TS_TRACE("This test is not suitable for more than 2 processes."); return; } CardiacSimulation simulation("heart/test/data/xml/base_monodomain_tt06_region.xml"); std::string foldername = "Kirsten"; TS_ASSERT(CompareFilesViaHdf5DataReaderGlobalNorm("heart/test/data/cardiac_simulations", "Kirsten", false, foldername, "SimulationResults", true, 5e-4)); // lower tolerance as comparing with non-backward-euler results. } void TestTransmuralCellularheterogeneities() { CardiacSimulation simulation("heart/test/data/xml/ChasteParametersCellHeterogeneities.xml"); std::string foldername = "ChasteResults_heterogeneities"; TS_ASSERT( CompareFilesViaHdf5DataReaderGlobalNorm("heart/test/data/cardiac_simulations", "transmural_heterogeneities_results", false, foldername, "SimulationResults", true)); } void TestElectrodes() { CardiacSimulation simulation("heart/test/data/xml/bidomain_with_bath2d_electrodes.xml"); std::string foldername = "ChasteResults_electrodes"; TS_ASSERT( CompareFilesViaHdf5DataReaderGlobalNorm("heart/test/data/cardiac_simulations", "electrodes_results", false, foldername, "SimulationResults", true, 1e-4)); } void TestExceptions() { TS_ASSERT_THROWS_THIS(CardiacSimulation simulation("heart/test/data/xml/monodomain8d_small.xml"), "Space dimension not supported: should be 1, 2 or 3"); TS_ASSERT_THROWS_THIS(CardiacSimulation simulation("heart/test/data/xml/bidomain8d_small.xml"), "Space dimension not supported: should be 1, 2 or 3"); #ifndef __APPLE__ ///\todo Passing error is fatal on Mac OSX TS_ASSERT_THROWS_THIS(CardiacSimulation simulation("heart/test/data/xml/base_monodomain_frankenstein.xml"), "XML parsing error in configuration file: heart/test/data/xml/base_monodomain_frankenstein.xml"); #endif TS_ASSERT_THROWS_THIS(CardiacSimulation simulation("no file"), "Missing file parsing configuration file: no file"); TS_ASSERT_THROWS_THIS(CardiacSimulation simulation(""), "No XML file name given"); #ifdef __APPLE__ FileFinder model("file_does_not_exist.dylib", RelativeTo::ChasteSourceRoot); #else FileFinder model("file_does_not_exist.so", RelativeTo::ChasteSourceRoot); #endif TS_ASSERT_THROWS_THIS(CardiacSimulation simulation("heart/test/data/xml/missing_dynamic_model.xml"), "Dynamically loadable cell model '" + model.GetAbsolutePath() + "' does not exist."); TS_ASSERT_THROWS_THIS(CardiacSimulation simulation("heart/test/data/xml/bidomain_with_bath2d_noelectrodes.xml"), "Simulation needs a stimulus (either <Stimuli> or <Electrodes>)."); #ifndef CHASTE_CAN_CHECKPOINT_DLLS TS_ASSERT_THROWS_THIS(CardiacSimulation simulation("heart/test/data/xml/dynamic_checkpoint.xml"), "Checkpointing is not compatible with dynamically loaded cell models on Mac OS X."); #endif } void TestDynamicallyLoadingCvodeCell() { // Coverage - using native CVODE cells should no longer throw #ifdef CHASTE_CVODE OutputFileHandler handler_cvode("DynamicallyLoadedModelCvode"); FileFinder cellml_file("heart/dynamic/luo_rudy_1991_dyn.cellml", RelativeTo::ChasteSourceRoot); handler_cvode.CopyFileTo(cellml_file); std::vector<std::string> args; args.push_back("--cvode"); CellMLToSharedLibraryConverter::CreateOptionsFile(handler_cvode, "luo_rudy_1991_dyn", args); CardiacSimulation simulation("heart/test/data/xml/dynamic_cvode_model.xml"); #else std::cout << "CVODE is not enabled.\n"; #endif } }; #endif /*TESTCARDIACSIMULATION_HPP_*/
32,954
10,381
// RUN: %clang_cc1 -triple x86_64-linux -O1 -disable-llvm-passes %s \ // RUN: -emit-llvm -o - | FileCheck %s -check-prefixes=CHECK,OLD-PATH // RUN: %clang_cc1 -triple x86_64-linux -O1 -disable-llvm-passes %s \ // RUN: -emit-llvm -new-struct-path-tbaa -o - | FileCheck %s -check-prefixes=CHECK,NEW-PATH // // Check that we generate correct TBAA information for lvalues constructed // with use of casts. struct V { unsigned n; }; struct S { char bytes[4]; }; void foo(S *p) { // CHECK-LABEL: _Z3fooP1S // CHECK: store i32 5, {{.*}}, !tbaa [[TAG_V_n:!.*]] ((V*)p->bytes)->n = 5; } // OLD-PATH-DAG: [[TAG_V_n]] = !{[[TYPE_V:!.*]], [[TYPE_int:!.*]], i64 0} // OLD-PATH-DAG: [[TYPE_V]] = !{!"_ZTS1V", !{{.*}}, i64 0} // OLD-PATH-DAG: [[TYPE_int]] = !{!"int", !{{.*}}, i64 0} // NEW-PATH-DAG: [[TAG_V_n]] = !{[[TYPE_V:!.*]], [[TYPE_int:!.*]], i64 0, i64 4} // NEW-PATH-DAG: [[TYPE_V]] = !{[[TYPE_char:!.*]], i64 4, !"_ZTS1V", [[TYPE_int]], i64 0, i64 4} // NEW-PATH-DAG: [[TYPE_int]] = !{[[TYPE_char]], i64 4, !"int"}
1,029
505
/* * DummyThreads.hh * * Copyright 2002, LifeLine Networks BV (www.lifeline.nl). All rights reserved. * Copyright 2002, Bastiaan Bakker. All rights reserved. * * See the COPYING file for the terms of usage and distribution. */ #ifndef _LOG4CPP_THREADING_DUMMYTHREADS_HH #define _LOG4CPP_THREADING_DUMMYTHREADS_HH #include <log4cpp/Portability.hh> #include <stdio.h> #include <string> namespace log4cpp { namespace threading { std::string getThreadId(); /** * Return an identifier for the current thread. What these * identifiers look like is completely up to the underlying * thread library. OmniThreads returns the POSIX thread Id. * * @param buffer Character buffer of at least 16 in size * @return buffer */ char* getThreadId(char* buffer); /** Dummy type 'int' for Mutex. Yes, this adds a bit of overhead in the for of extra memory, but unfortunately 'void' is illegal. **/ typedef int Mutex; /** Dummy type 'int' defintion of ScopedLock; **/ typedef int ScopedLock; template<typename T> class ThreadLocalDataHolder { public: typedef T data_type; inline ThreadLocalDataHolder() {}; inline ~ThreadLocalDataHolder() { if (_data) delete _data; }; inline T* get() const { return _data; }; inline T* operator->() const { return get(); }; inline T& operator*() const { return *get(); }; inline T* release() { T* result = _data; _data = NULL; return result; }; inline void reset(T* p = NULL) { if (_data) delete _data; _data = p; }; private: T* _data; }; } } #endif
2,015
565
#include "mqtt_api.h" #include <iostream> #include <functional> #include <boost/date_time/time_duration.hpp> namespace wavplayeralsa { MqttApi::MqttApi(boost::asio::io_service &io_service) : io_service_(io_service), reconnect_timer_(io_service) { } void MqttApi::Initialize(std::shared_ptr<spdlog::logger> logger, const std::string &mqtt_host, uint16_t mqtt_port) { // set class members logger_ = logger; const char *mqtt_client_id = "wavplayeralsa"; logger_->info("creating mqtt connection to host {} on port {} with client id {}", mqtt_host, mqtt_port, mqtt_client_id); logger_->info("will publish current song updates on topic {}", CURRENT_SONG_TOPIC); mqtt_client_ = mqtt::make_sync_client(io_service_, mqtt_host, mqtt_port); mqtt_client_->set_client_id(mqtt_client_id); mqtt_client_->set_clean_session(true); mqtt_client_->set_error_handler(std::bind(&MqttApi::OnError, this, std::placeholders::_1)); mqtt_client_->set_close_handler(std::bind(&MqttApi::OnClose, this)); mqtt_client_->set_connack_handler(std::bind(&MqttApi::OnConnAck, this, std::placeholders::_1, std::placeholders::_2)); mqtt_client_->connect(); } void MqttApi::ReportCurrentSong(const std::string &json_str) { last_status_msg_ = json_str; PublishCurrentSong(); } void MqttApi::OnError(boost::system::error_code ec) { logger_->error("client disconnected from mqtt server. will try reconnect in {} ms", RECONNECT_WAIT_MS); reconnect_timer_.expires_from_now(boost::posix_time::milliseconds(RECONNECT_WAIT_MS)); reconnect_timer_.async_wait( [this] (boost::system::error_code ec) { if (ec != boost::asio::error::operation_aborted) { mqtt_client_->connect(); } }); } void MqttApi::OnClose() { logger_->error("client connection to mqtt server is closed"); } bool MqttApi::OnConnAck(bool session_present, std::uint8_t connack_return_code) { logger_->info("connack handler called. clean session: {}. coonack rerturn code: {}", session_present, mqtt::connect_return_code_to_str(connack_return_code)); PublishCurrentSong(); return true; } void MqttApi::PublishCurrentSong() { if(!this->mqtt_client_) return; if(last_status_msg_.empty()) return; this->mqtt_client_->publish_exactly_once(CURRENT_SONG_TOPIC, last_status_msg_, true); } }
2,341
951
/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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. */ /* * Copyright (C) 2016 ScyllaDB */ #include <seastar/core/prometheus.hh> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream_impl_lite.h> #include "proto/metrics2.pb.h" #include <sstream> #include <seastar/core/scollectd_api.hh> #include "core/scollectd-impl.hh" #include <seastar/core/metrics_api.hh> #include <seastar/http/function_handlers.hh> #include <boost/algorithm/string/replace.hpp> #include <boost/range/algorithm_ext/erase.hpp> #include <boost/algorithm/string.hpp> #include <boost/range/algorithm.hpp> #include <boost/range/combine.hpp> #include <seastar/core/thread.hh> #include <seastar/core/loop.hh> namespace seastar { extern seastar::logger seastar_logger; namespace prometheus { namespace pm = io::prometheus::client; namespace mi = metrics::impl; /** * Taken from an answer in stackoverflow: * http://stackoverflow.com/questions/2340730/are-there-c-equivalents-for-the-protocol-buffers-delimited-i-o-functions-in-ja */ static bool write_delimited_to(const google::protobuf::MessageLite& message, google::protobuf::io::ZeroCopyOutputStream* rawOutput) { google::protobuf::io::CodedOutputStream output(rawOutput); #if GOOGLE_PROTOBUF_VERSION >= 3004000 const size_t size = message.ByteSizeLong(); output.WriteVarint64(size); #else const int size = message.ByteSize(); output.WriteVarint32(size); #endif uint8_t* buffer = output.GetDirectBufferForNBytesAndAdvance(size); if (buffer != nullptr) { message.SerializeWithCachedSizesToArray(buffer); } else { message.SerializeWithCachedSizes(&output); if (output.HadError()) { return false; } } return true; } static pm::Metric* add_label(pm::Metric* mt, const metrics::impl::metric_id & id, const config& ctx) { mt->mutable_label()->Reserve(id.labels().size() + 1); if (ctx.label) { auto label = mt->add_label(); label->set_name(ctx.label->key()); label->set_value(ctx.label->value()); } for (auto &&i : id.labels()) { auto label = mt->add_label(); label->set_name(i.first); label->set_value(i.second); } return mt; } static void fill_metric(pm::MetricFamily& mf, const metrics::impl::metric_value& c, const metrics::impl::metric_id & id, const config& ctx) { switch (c.type()) { case scollectd::data_type::DERIVE: add_label(mf.add_metric(), id, ctx)->mutable_counter()->set_value(c.i()); mf.set_type(pm::MetricType::COUNTER); break; case scollectd::data_type::GAUGE: add_label(mf.add_metric(), id, ctx)->mutable_gauge()->set_value(c.d()); mf.set_type(pm::MetricType::GAUGE); break; case scollectd::data_type::HISTOGRAM: { auto h = c.get_histogram(); auto mh = add_label(mf.add_metric(), id,ctx)->mutable_histogram(); mh->set_sample_count(h.sample_count); mh->set_sample_sum(h.sample_sum); for (auto b : h.buckets) { auto bc = mh->add_bucket(); bc->set_cumulative_count(b.count); bc->set_upper_bound(b.upper_bound); } mf.set_type(pm::MetricType::HISTOGRAM); break; } default: add_label(mf.add_metric(), id, ctx)->mutable_counter()->set_value(c.ui()); mf.set_type(pm::MetricType::COUNTER); break; } } static std::string to_str(seastar::metrics::impl::data_type dt) { switch (dt) { case seastar::metrics::impl::data_type::GAUGE: return "gauge"; case seastar::metrics::impl::data_type::COUNTER: return "counter"; case seastar::metrics::impl::data_type::HISTOGRAM: return "histogram"; case seastar::metrics::impl::data_type::DERIVE: // Prometheus server does not respect derive parameters // So we report them as counter return "counter"; default: break; } return "untyped"; } static std::string to_str(const seastar::metrics::impl::metric_value& v) { switch (v.type()) { case seastar::metrics::impl::data_type::GAUGE: return std::to_string(v.d()); case seastar::metrics::impl::data_type::COUNTER: return std::to_string(v.i()); case seastar::metrics::impl::data_type::DERIVE: return std::to_string(v.ui()); default: break; } return ""; // we should never get here but it makes the compiler happy } static void add_name(std::ostream& s, const sstring& name, const std::map<sstring, sstring>& labels, const config& ctx) { s << name << "{"; const char* delimiter = ""; if (ctx.label) { s << ctx.label->key() << "=\"" << ctx.label->value() << '"'; delimiter = ","; } if (!labels.empty()) { for (auto l : labels) { s << delimiter; s << l.first << "=\"" << l.second << '"'; delimiter = ","; } } s << "} "; } /*! * \brief iterator for metric family * * In prometheus, a single shard collecct all the data from the other * shards and report it. * * Each shard returns a value_copy struct that has a vector of vector values (a vector per metric family) * and a vector of metadata (and insdie it a vector of metric metadata) * * The metrics are sorted by the metric family name. * * In prometheus, all the metrics that belongs to the same metric family are reported together. * * For efficiency the results from the metrics layer are kept in a vector. * * So we have a vector of shards of a vector of metric families of a vector of values. * * To produce the result, we use the metric_family_iterator that is created by metric_family_range. * * When iterating over the metrics we use two helper structure. * * 1. A map between metric family name and the total number of values (combine on all shards) and * pointer to the metric family metadata. * 2. A vector of positions to the current metric family for each shard. * * The metric_family_range returns a metric_family_iterator that goes over all the families. * * The iterator returns a metric_family object, that can report the metric_family name, the size (how many * metrics in total belongs to the metric family) and a a foreach_metric method. * * The foreach_metric method can be used to perform an action on each of the metric that belongs to * that metric family * * Iterating over the metrics is done: * - go over each of the shard and each of the entry in the position vector: * - if the current family (the metric family that we get from the shard and position) has the current name: * - iterate over each of the metrics belong to that metric family: * * for example, if m is a metric_family_range * * for (auto&& i : m) { * std::cout << i.name() << std::endl; * i.foreach_metric([](const mi::metric_value& value, const mi::metric_info& value_info) { * std::cout << value_info.id.labels().size() <<std::cout; * }); * } * * Will print all the metric family names followed by the number of labels each metric has. */ class metric_family_iterator; class metric_family_range; class metrics_families_per_shard { using metrics_family_per_shard_data_container = std::vector<foreign_ptr<mi::values_reference>>; metrics_family_per_shard_data_container _data; using comp_function = std::function<bool(const sstring&, const mi::metric_family_metadata&)>; /*! * \brief find the last item in a range of metric family based on a comparator function * */ metric_family_iterator find_bound(const sstring& family_name, comp_function comp) const; public: using const_iterator = metrics_family_per_shard_data_container::const_iterator; using iterator = metrics_family_per_shard_data_container::iterator; using reference = metrics_family_per_shard_data_container::reference; using const_reference = metrics_family_per_shard_data_container::const_reference; /*! * \brief find the first item following a metric family range. * metric family are sorted, this will return the first item that is outside * of the range */ metric_family_iterator upper_bound(const sstring& family_name) const; /*! * \brief find the first item in a range of metric family. * metric family are sorted, the first item, is the first to match the * criteria. */ metric_family_iterator lower_bound(const sstring& family_name) const; /** * \defgroup Variables Global variables */ /* * @defgroup Vector properties * The following methods making metrics_families_per_shard act as * a vector of foreign_ptr<mi::values_reference> * @{ * * */ iterator begin() { return _data.begin(); } iterator end() { return _data.end(); } const_iterator begin() const { return _data.begin(); } const_iterator end() const { return _data.end(); } void resize(size_t new_size) { _data.resize(new_size); } reference& operator[](size_t n) { return _data[n]; } const_reference& operator[](size_t n) const { return _data[n]; } /** @} */ }; static future<> get_map_value(metrics_families_per_shard& vec) { vec.resize(smp::count); return parallel_for_each(boost::irange(0u, smp::count), [&vec] (auto cpu) { return smp::submit_to(cpu, [] { return mi::get_values(); }).then([&vec, cpu] (auto res) { vec[cpu] = std::move(res); }); }); } /*! * \brief a facade class for metric family */ class metric_family { const sstring* _name = nullptr; uint32_t _size = 0; const mi::metric_family_info* _family_info = nullptr; metric_family_iterator& _iterator_state; metric_family(metric_family_iterator& state) : _iterator_state(state) { } metric_family(const sstring* name , uint32_t size, const mi::metric_family_info* family_info, metric_family_iterator& state) : _name(name), _size(size), _family_info(family_info), _iterator_state(state) { } metric_family(const metric_family& info, metric_family_iterator& state) : metric_family(info._name, info._size, info._family_info, state) { } public: metric_family(const metric_family&) = delete; metric_family(metric_family&&) = delete; const sstring& name() const { return *_name; } const uint32_t size() const { return _size; } const mi::metric_family_info& metadata() const { return *_family_info; } void foreach_metric(std::function<void(const mi::metric_value&, const mi::metric_info&)>&& f); bool end() const { return !_name || !_family_info; } friend class metric_family_iterator; }; class metric_family_iterator { const metrics_families_per_shard& _families; std::vector<size_t> _positions; metric_family _info; void next() { if (_positions.empty()) { return; } const sstring *new_name = nullptr; const mi::metric_family_info* new_family_info = nullptr; _info._size = 0; for (auto&& i : boost::combine(_positions, _families)) { auto& pos_in_metric_per_shard = boost::get<0>(i); auto& metric_family = boost::get<1>(i); if (_info._name && pos_in_metric_per_shard < metric_family->metadata->size() && metric_family->metadata->at(pos_in_metric_per_shard).mf.name.compare(*_info._name) <= 0) { pos_in_metric_per_shard++; } if (pos_in_metric_per_shard >= metric_family->metadata->size()) { // no more metric family in this shard continue; } auto& metadata = metric_family->metadata->at(pos_in_metric_per_shard); int cmp = (!new_name) ? -1 : metadata.mf.name.compare(*new_name); if (cmp < 0) { new_name = &metadata.mf.name; new_family_info = &metadata.mf; _info._size = 0; } if (cmp <= 0) { _info._size += metadata.metrics.size(); } } _info._name = new_name; _info._family_info = new_family_info; } public: metric_family_iterator() = delete; metric_family_iterator(const metric_family_iterator& o) : _families(o._families), _positions(o._positions), _info(*this) { next(); } metric_family_iterator(metric_family_iterator&& o) : _families(o._families), _positions(std::move(o._positions)), _info(*this) { next(); } metric_family_iterator(const metrics_families_per_shard& families, unsigned shards) : _families(families), _positions(shards, 0), _info(*this) { next(); } metric_family_iterator(const metrics_families_per_shard& families, std::vector<size_t>&& positions) : _families(families), _positions(std::move(positions)), _info(*this) { next(); } metric_family_iterator& operator++() { next(); return *this; } metric_family_iterator operator++(int) { metric_family_iterator previous(*this); next(); return previous; } bool operator!=(const metric_family_iterator& o) const { return !(*this == o); } bool operator==(const metric_family_iterator& o) const { if (end()) { return o.end(); } if (o.end()) { return false; } return name() == o.name(); } metric_family& operator*() { return _info; } metric_family* operator->() { return &_info; } const sstring& name() const { return *_info._name; } const uint32_t size() const { return _info._size; } const mi::metric_family_info& metadata() const { return *_info._family_info; } bool end() const { return _positions.empty() || _info.end(); } void foreach_metric(std::function<void(const mi::metric_value&, const mi::metric_info&)>&& f) { // iterating over the shard vector and the position vector for (auto&& i : boost::combine(_positions, _families)) { auto& pos_in_metric_per_shard = boost::get<0>(i); auto& metric_family = boost::get<1>(i); if (pos_in_metric_per_shard >= metric_family->metadata->size()) { // no more metric family in this shard continue; } auto& metadata = metric_family->metadata->at(pos_in_metric_per_shard); // the the name is different, that means that on this shard, the metric family // does not exist, because everything is sorted by metric family name, this is fine. if (metadata.mf.name == name()) { const mi::value_vector& values = metric_family->values[pos_in_metric_per_shard]; const mi::metric_metadata_vector& metrics_metadata = metadata.metrics; for (auto&& vm : boost::combine(values, metrics_metadata)) { auto& value = boost::get<0>(vm); auto& metric_metadata = boost::get<1>(vm); f(value, metric_metadata); } } } } }; void metric_family::foreach_metric(std::function<void(const mi::metric_value&, const mi::metric_info&)>&& f) { _iterator_state.foreach_metric(std::move(f)); } class metric_family_range { metric_family_iterator _begin; metric_family_iterator _end; public: metric_family_range(const metrics_families_per_shard& families) : _begin(families, smp::count), _end(metric_family_iterator(families, 0)) { } metric_family_range(const metric_family_iterator& b, const metric_family_iterator& e) : _begin(b), _end(e) { } metric_family_iterator begin() const { return _begin; } metric_family_iterator end() const { return _end; } }; metric_family_iterator metrics_families_per_shard::find_bound(const sstring& family_name, comp_function comp) const { std::vector<size_t> positions; positions.reserve(smp::count); for (auto& shard_info : _data) { std::vector<mi::metric_family_metadata>& metadata = *(shard_info->metadata); std::vector<mi::metric_family_metadata>::iterator it_b = boost::range::upper_bound(metadata, family_name, comp); positions.emplace_back(it_b - metadata.begin()); } return metric_family_iterator(*this, std::move(positions)); } metric_family_iterator metrics_families_per_shard::lower_bound(const sstring& family_name) const { return find_bound(family_name, [](const sstring& a, const mi::metric_family_metadata& b) { //sstring doesn't have a <= operator return a < b.mf.name || a == b.mf.name; }); } metric_family_iterator metrics_families_per_shard::upper_bound(const sstring& family_name) const { return find_bound(family_name, [](const sstring& a, const mi::metric_family_metadata& b) { return a < b.mf.name; }); } /*! * \brief a helper function to get metric family range * if metric_family_name is empty will return everything, if not, it will return * the range of metric family that match the metric_family_name. * * if prefix is true the match will be based on prefix */ metric_family_range get_range(const metrics_families_per_shard& mf, const sstring& metric_family_name, bool prefix) { if (metric_family_name == "") { return metric_family_range(mf); } auto upper_bount_prefix = metric_family_name; ++upper_bount_prefix.back(); if (prefix) { return metric_family_range(mf.lower_bound(metric_family_name), mf.lower_bound(upper_bount_prefix)); } auto lb = mf.lower_bound(metric_family_name); if (lb.end() || lb->name() != metric_family_name) { return metric_family_range(lb, lb); // just return an empty range } auto up = lb; ++up; return metric_family_range(lb, up); } future<> write_text_representation(output_stream<char>& out, const config& ctx, const metric_family_range& m) { return seastar::async([&ctx, &out, &m] () mutable { bool found = false; for (metric_family& metric_family : m) { auto name = ctx.prefix + "_" + metric_family.name(); found = false; metric_family.foreach_metric([&out, &ctx, &found, &name, &metric_family](auto value, auto value_info) mutable { std::stringstream s; if (!found) { if (metric_family.metadata().d.str() != "") { s << "# HELP " << name << " " << metric_family.metadata().d.str() << "\n"; } s << "# TYPE " << name << " " << to_str(metric_family.metadata().type) << "\n"; found = true; } if (value.type() == mi::data_type::HISTOGRAM) { auto&& h = value.get_histogram(); std::map<sstring, sstring> labels = value_info.id.labels(); add_name(s, name + "_sum", labels, ctx); s << h.sample_sum; s << "\n"; add_name(s, name + "_count", labels, ctx); s << h.sample_count; s << "\n"; auto& le = labels["le"]; auto bucket = name + "_bucket"; for (auto i : h.buckets) { le = std::to_string(i.upper_bound); add_name(s, bucket, labels, ctx); s << i.count; s << "\n"; } labels["le"] = "+Inf"; add_name(s, bucket, labels, ctx); s << h.sample_count; s << "\n"; } else { add_name(s, name, value_info.id.labels(), ctx); s << to_str(value); s << "\n"; } out.write(s.str()).get(); thread::maybe_yield(); }); } }); } future<> write_protobuf_representation(output_stream<char>& out, const config& ctx, metric_family_range& m) { return do_for_each(m, [&ctx, &out](metric_family& metric_family) mutable { std::string s; google::protobuf::io::StringOutputStream os(&s); auto& name = metric_family.name(); pm::MetricFamily mtf; mtf.set_name(ctx.prefix + "_" + name); mtf.mutable_metric()->Reserve(metric_family.size()); metric_family.foreach_metric([&mtf, &ctx](auto value, auto value_info) { fill_metric(mtf, value, value_info.id, ctx); }); if (!write_delimited_to(mtf, &os)) { seastar_logger.warn("Failed to write protobuf metrics"); } return out.write(s); }); } bool is_accept_text(const std::string& accept) { std::vector<std::string> strs; boost::split(strs, accept, boost::is_any_of(",")); for (auto i : strs) { boost::trim(i); if (boost::starts_with(i, "application/vnd.google.protobuf;")) { return false; } } return true; } class metrics_handler : public handler_base { sstring _prefix; config _ctx; /*! * \brief tries to trim an asterisk from the end of the string * return true if an asterisk exists. */ bool trim_asterisk(sstring& name) { if (name.size() && name.back() == '*') { name.resize(name.length() - 1); return true; } // Prometheus uses url encoding for the path so '*' is encoded as '%2A' if (boost::algorithm::ends_with(name, "%2A")) { // This assert is obviously true. It is in here just to // silence a bogus gcc warning: // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=89337 assert(name.length() >= 3); name.resize(name.length() - 3); return true; } return false; } public: metrics_handler(config ctx) : _ctx(ctx) {} future<std::unique_ptr<httpd::reply>> handle(const sstring& path, std::unique_ptr<httpd::request> req, std::unique_ptr<httpd::reply> rep) override { auto text = is_accept_text(req->get_header("Accept")); sstring metric_family_name = req->get_query_param("name"); bool prefix = trim_asterisk(metric_family_name); rep->write_body((text) ? "txt" : "proto", [this, text, metric_family_name, prefix] (output_stream<char>&& s) { return do_with(metrics_families_per_shard(), output_stream<char>(std::move(s)), [this, text, prefix, &metric_family_name] (metrics_families_per_shard& families, output_stream<char>& s) mutable { return get_map_value(families).then([&s, &families, this, text, prefix, &metric_family_name]() mutable { return do_with(get_range(families, metric_family_name, prefix), [&s, this, text](metric_family_range& m) { return (text) ? write_text_representation(s, _ctx, m) : write_protobuf_representation(s, _ctx, m); }); }).finally([&s] () mutable { return s.close(); }); }); }); return make_ready_future<std::unique_ptr<httpd::reply>>(std::move(rep)); } }; future<> add_prometheus_routes(http_server& server, config ctx) { server._routes.put(GET, "/metrics", new metrics_handler(ctx)); return make_ready_future<>(); } future<> add_prometheus_routes(distributed<http_server>& server, config ctx) { return server.invoke_on_all([ctx](http_server& s) { return add_prometheus_routes(s, ctx); }); } future<> start(httpd::http_server_control& http_server, config ctx) { return add_prometheus_routes(http_server.server(), ctx); } } }
24,867
7,741
#include "amuse/Submix.hpp" namespace amuse { Submix::Submix(Engine& engine) : m_root(engine) {} EffectChorus& Submix::makeChorus(uint32_t baseDelay, uint32_t variation, uint32_t period) { return makeEffect<EffectChorus>(baseDelay, variation, period); } EffectChorus& Submix::makeChorus(const EffectChorusInfo& info) { return makeEffect<EffectChorus>(info); } EffectDelay& Submix::makeDelay(uint32_t initDelay, uint32_t initFeedback, uint32_t initOutput) { return makeEffect<EffectDelay>(initDelay, initFeedback, initOutput); } EffectDelay& Submix::makeDelay(const EffectDelayInfo& info) { return makeEffect<EffectDelay>(info); } EffectReverbStd& Submix::makeReverbStd(float coloration, float mix, float time, float damping, float preDelay) { return makeEffect<EffectReverbStd>(coloration, mix, time, damping, preDelay); } EffectReverbStd& Submix::makeReverbStd(const EffectReverbStdInfo& info) { return makeEffect<EffectReverbStd>(info); } EffectReverbHi& Submix::makeReverbHi(float coloration, float mix, float time, float damping, float preDelay, float crosstalk) { return makeEffect<EffectReverbHi>(coloration, mix, time, damping, preDelay, crosstalk); } EffectReverbHi& Submix::makeReverbHi(const EffectReverbHiInfo& info) { return makeEffect<EffectReverbHi>(info); } void Submix::applyEffect(int16_t* audio, size_t frameCount, const ChannelMap& chanMap) const { for (const std::unique_ptr<EffectBaseTypeless>& effect : m_effectStack) ((EffectBase<int16_t>&)*effect).applyEffect(audio, frameCount, chanMap); } void Submix::applyEffect(int32_t* audio, size_t frameCount, const ChannelMap& chanMap) const { for (const std::unique_ptr<EffectBaseTypeless>& effect : m_effectStack) ((EffectBase<int32_t>&)*effect).applyEffect(audio, frameCount, chanMap); } void Submix::applyEffect(float* audio, size_t frameCount, const ChannelMap& chanMap) const { for (const std::unique_ptr<EffectBaseTypeless>& effect : m_effectStack) ((EffectBase<float>&)*effect).applyEffect(audio, frameCount, chanMap); } void Submix::resetOutputSampleRate(double sampleRate) { for (const std::unique_ptr<EffectBaseTypeless>& effect : m_effectStack) effect->resetOutputSampleRate(sampleRate); } } // namespace amuse
2,272
740
// license:BSD-3-Clause // copyright-holders:Curt Coder /********************************************************************** TIKI-100 expansion bus emulation **********************************************************************/ #include "emu.h" #include "exp.h" //************************************************************************** // DEVICE DEFINITIONS //************************************************************************** DEFINE_DEVICE_TYPE(TIKI100_BUS, tiki100_bus_device, "tiki100bus", "TIKI-100 expansion bus") DEFINE_DEVICE_TYPE(TIKI100_BUS_SLOT, tiki100_bus_slot_device, "tiki100bus_slot", "TIKI-100 expansion bus slot") //************************************************************************** // LIVE DEVICE //************************************************************************** //------------------------------------------------- // tiki100_bus_slot_device - constructor //------------------------------------------------- tiki100_bus_slot_device::tiki100_bus_slot_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : device_t(mconfig, TIKI100_BUS_SLOT, tag, owner, clock), device_single_card_slot_interface<device_tiki100bus_card_interface>(mconfig, *this), device_z80daisy_interface(mconfig, *this), m_bus(*this, finder_base::DUMMY_TAG), m_card(nullptr) { } //------------------------------------------------- // device_start - device-specific startup //------------------------------------------------- void tiki100_bus_slot_device::device_start() { m_card = get_card_device(); if (m_card) m_bus->add_card(*m_card); } //------------------------------------------------- // tiki100_bus_device - constructor //------------------------------------------------- tiki100_bus_device::tiki100_bus_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : device_t(mconfig, TIKI100_BUS, tag, owner, clock), m_irq_cb(*this), m_nmi_cb(*this), m_busrq_cb(*this), m_in_mrq_cb(*this), m_out_mrq_cb(*this) { } //------------------------------------------------- // device_start - device-specific startup //------------------------------------------------- void tiki100_bus_device::device_start() { // resolve callbacks m_irq_cb.resolve_safe(); m_nmi_cb.resolve_safe(); m_busrq_cb.resolve_safe(); m_in_mrq_cb.resolve(); m_out_mrq_cb.resolve(); } //------------------------------------------------- // add_card - add card //------------------------------------------------- void tiki100_bus_device::add_card(device_tiki100bus_card_interface &card) { m_device_list.append(card); card.m_bus = this; } //------------------------------------------------- // mrq_r - memory read //------------------------------------------------- uint8_t tiki100_bus_device::mrq_r(offs_t offset, uint8_t data, bool &mdis) { device_tiki100bus_card_interface *entry = m_device_list.first(); while (entry) { data &= entry->mrq_r(offset, data, mdis); entry = entry->next(); } return data; } //------------------------------------------------- // mrq_w - memory write //------------------------------------------------- void tiki100_bus_device::mrq_w(offs_t offset, uint8_t data) { device_tiki100bus_card_interface *entry = m_device_list.first(); while (entry) { entry->mrq_w(offset, data); entry = entry->next(); } } //------------------------------------------------- // iorq_r - I/O read //------------------------------------------------- uint8_t tiki100_bus_device::iorq_r(offs_t offset, uint8_t data) { device_tiki100bus_card_interface *entry = m_device_list.first(); while (entry) { data &= entry->iorq_r(offset, data); entry = entry->next(); } return data; } //------------------------------------------------- // iorq_w - I/O write //------------------------------------------------- void tiki100_bus_device::iorq_w(offs_t offset, uint8_t data) { device_tiki100bus_card_interface *entry = m_device_list.first(); while (entry) { entry->iorq_w(offset, data); entry = entry->next(); } } //------------------------------------------------- // busak_w - bus acknowledge write //------------------------------------------------- WRITE_LINE_MEMBER( tiki100_bus_device::busak_w ) { device_tiki100bus_card_interface *entry = m_device_list.first(); while (entry) { entry->busak_w(state); entry = entry->next(); } } //************************************************************************** // DEVICE TIKI-100 BUS CARD INTERFACE //************************************************************************** //------------------------------------------------- // device_tiki100bus_card_interface - constructor //------------------------------------------------- device_tiki100bus_card_interface::device_tiki100bus_card_interface(const machine_config &mconfig, device_t &device) : device_interface(device, "tiki100bus"), m_bus(nullptr), m_busak(CLEAR_LINE), m_next(nullptr) { m_slot = dynamic_cast<tiki100_bus_slot_device *>(device.owner()); } void device_tiki100bus_card_interface::interface_pre_start() { if (!m_bus) throw device_missing_dependencies(); } //------------------------------------------------- // SLOT_INTERFACE( tiki100_cards ) //------------------------------------------------- // slot devices #include "8088.h" #include "hdc.h" void tiki100_cards(device_slot_interface &device) { device.option_add("8088", TIKI100_8088); device.option_add("hdc", TIKI100_HDC); }
5,513
1,877
#include "Sobol.hpp" constexpr uint32_t kMaxDimension = 64; constexpr VkDeviceSize kBufferSize = (kMaxDimension + 1) * sizeof(uint32_t); /*void Sobol::Next(float *out) { uint8_t c = get_first_zero_bit(m_index++); //uint8_t c = glm::findLSB(~(m_index ++)); for (unsigned j = 0; j < m_dim; ++j) out[j] = (float) ((m_x[j] ^= kMatrices[j][c]) / 4294967296.0); }*/ void Sobol::Initialize(const std::shared_ptr<myvk::Device> &device) { m_descriptor_pool = myvk::DescriptorPool::Create(device, 1, {{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}}); { VkDescriptorSetLayoutBinding sobol_binding = {}; sobol_binding.binding = 0; sobol_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; sobol_binding.descriptorCount = 1; sobol_binding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT | VK_SHADER_STAGE_FRAGMENT_BIT; m_descriptor_set_layout = myvk::DescriptorSetLayout::Create(device, {sobol_binding}); } m_descriptor_set = myvk::DescriptorSet::Create(m_descriptor_pool, m_descriptor_set_layout); m_sobol_buffer = myvk::Buffer::Create(device, kBufferSize, VMA_MEMORY_USAGE_GPU_ONLY, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT); m_descriptor_set->UpdateStorageBuffer(m_sobol_buffer, 0); m_staging_buffer = myvk::Buffer::CreateStaging(device, kBufferSize); { uint32_t *data = (uint32_t *)m_staging_buffer->Map(); std::fill(data, data + kMaxDimension + 1, 0u); m_staging_buffer->Unmap(); } m_pipeline_layout = myvk::PipelineLayout::Create(device, {m_descriptor_set_layout}, {{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(uint32_t)}}); { constexpr uint32_t kSobolCompSpv[] = { #include "spirv/sobol.comp.u32" }; std::shared_ptr<myvk::ShaderModule> sobol_shader_module = myvk::ShaderModule::Create(device, kSobolCompSpv, sizeof(kSobolCompSpv)); m_compute_pipeline = myvk::ComputePipeline::Create(m_pipeline_layout, sobol_shader_module); } } void Sobol::CmdNext(const std::shared_ptr<myvk::CommandBuffer> &command_buffer) { command_buffer->CmdBindDescriptorSets({m_descriptor_set}, m_pipeline_layout, VK_PIPELINE_BIND_POINT_COMPUTE, {}); command_buffer->CmdPushConstants(m_pipeline_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(uint32_t), &m_dimension); command_buffer->CmdBindPipeline(m_compute_pipeline); command_buffer->CmdDispatch(1, 1, 1); } void Sobol::Reset(const std::shared_ptr<myvk::CommandPool> &command_pool, uint32_t dimension) { m_dimension = dimension; std::shared_ptr<myvk::Fence> fence = myvk::Fence::Create(command_pool->GetDevicePtr()); std::shared_ptr<myvk::CommandBuffer> command_buffer = myvk::CommandBuffer::Create(command_pool); command_buffer->Begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT); command_buffer->CmdCopy(m_staging_buffer, m_sobol_buffer, {{0, 0, kBufferSize}}); command_buffer->End(); command_buffer->Submit(fence); fence->Wait(); }
2,946
1,210
#include "..\common.h" #include <iostream> #include <memory> using namespace cv; using namespace std; int main(int argc, char** argv) { int retVal = 0; if (argc == 3) { Mat inputImage = imread(argv[1], IMREAD_COLOR); if (!inputImage.data) { printf("ERROR: No input image data."); retVal = -1; } else { if (inputImage.type() != CV_8UC3) { printf("Invalid input image mat"); retVal = -1; } else { cout << "Saving descriptors.." << endl; int result = SaveDescriptors(inputImage.ptr(), inputImage.cols, inputImage.rows); cout << result << endl; Mat testImage = imread(argv[2], IMREAD_COLOR); if (!testImage.data) { printf("ERROR: No test image data."); retVal = -1; } else { if (inputImage.type() != CV_8UC3) { printf("Invalid test image mat"); retVal = -1; } else { cout << "Matching descriptors.." << endl; shared_ptr<int> boundingRect(new int[4], default_delete<int[]>()); int result = MatchDescriptors(testImage.ptr(), testImage.cols, testImage.rows, boundingRect.get()); cout << result << endl; if (result == 1) { int* boundingRectPtr = boundingRect.get(); cout << "Boundary = " << boundingRectPtr[0] << " " << boundingRectPtr[1] << " " << boundingRectPtr[2] << " " << boundingRectPtr[3] << endl; } } } } } } else { printf("ERROR: Input & Test Image paths were not passed in."); retVal = -1; } return retVal; }
2,139
564
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isBalanced(TreeNode* root) { if(root==NULL) { return true; } int maxDepthLeft=maxDepth(root->left) ; int maxDepthRight=maxDepth(root->right) ; if(abs(maxDepthLeft-maxDepthRight)>1) { return false; } return isBalanced(root->left) && isBalanced(root->right); } int maxDepth(TreeNode* root) { if (!root) return 0; return 1 + max(maxDepth(root->left), maxDepth(root->right)); } };
786
263
#include "muscle.h" #include "msa.h" #include "profile.h" #include "objscore.h" #if DOUBLE_AFFINE #define TRACE 0 #define TEST_SPFAST 0 static SCORE GapPenalty(unsigned uLength, bool Term, SCORE g, SCORE e) { //if (Term) // { // switch (g_TermGap) // { // case TERMGAP_Full: // return g + (uLength - 1)*e; // case TERMGAP_Half: // return g/2 + (uLength - 1)*e; // case TERMGAP_Ext: // return uLength*e; // } // Quit("Bad termgap"); // } //else // return g + (uLength - 1)*e; //return MINUS_INFINITY; return g + (uLength - 1)*e; } static SCORE GapPenalty(unsigned uLength, bool Term) { SCORE s1 = GapPenalty(uLength, Term, g_scoreGapOpen, g_scoreGapExtend); #if DOUBLE_AFFINE SCORE s2 = GapPenalty(uLength, Term, g_scoreGapOpen2, g_scoreGapExtend2); if (s1 > s2) return s1; return s2; #else return s1; #endif } static const MSA *g_ptrMSA1; static const MSA *g_ptrMSA2; static unsigned g_uSeqIndex1; static unsigned g_uSeqIndex2; static void LogGap(unsigned uStart, unsigned uEnd, unsigned uGapLength, bool bNTerm, bool bCTerm) { Log("%16.16s ", ""); for (unsigned i = 0; i < uStart; ++i) Log(" "); unsigned uMyLength = 0; for (unsigned i = uStart; i <= uEnd; ++i) { bool bGap1 = g_ptrMSA1->IsGap(g_uSeqIndex1, i); bool bGap2 = g_ptrMSA2->IsGap(g_uSeqIndex2, i); if (!bGap1 && !bGap2) Quit("Error -- neither gapping"); if (bGap1 && bGap2) Log("."); else { ++uMyLength; Log("-"); } } SCORE s = GapPenalty(uGapLength, bNTerm || bCTerm); Log(" L=%d N%d C%d s=%.3g", uGapLength, bNTerm, bCTerm, s); Log("\n"); if (uMyLength != uGapLength) Quit("Lengths differ"); } static SCORE ScoreSeqPair(const MSA &msa1, unsigned uSeqIndex1, const MSA &msa2, unsigned uSeqIndex2, SCORE *ptrLetters, SCORE *ptrGaps) { g_ptrMSA1 = &msa1; g_ptrMSA2 = &msa2; g_uSeqIndex1 = uSeqIndex1; g_uSeqIndex2 = uSeqIndex2; const unsigned uColCount = msa1.GetColCount(); const unsigned uColCount2 = msa2.GetColCount(); if (uColCount != uColCount2) Quit("ScoreSeqPair, different lengths"); #if TRACE Log("ScoreSeqPair\n"); Log("%16.16s ", msa1.GetSeqName(uSeqIndex1)); for (unsigned i = 0; i < uColCount; ++i) Log("%c", msa1.GetChar(uSeqIndex1, i)); Log("\n"); Log("%16.16s ", msa2.GetSeqName(uSeqIndex2)); for (unsigned i = 0; i < uColCount; ++i) Log("%c", msa1.GetChar(uSeqIndex2, i)); Log("\n"); #endif SCORE scoreTotal = 0; // Substitution scores unsigned uFirstLetter1 = uInsane; unsigned uFirstLetter2 = uInsane; unsigned uLastLetter1 = uInsane; unsigned uLastLetter2 = uInsane; for (unsigned uColIndex = 0; uColIndex < uColCount; ++uColIndex) { bool bGap1 = msa1.IsGap(uSeqIndex1, uColIndex); bool bGap2 = msa2.IsGap(uSeqIndex2, uColIndex); bool bWildcard1 = msa1.IsWildcard(uSeqIndex1, uColIndex); bool bWildcard2 = msa2.IsWildcard(uSeqIndex2, uColIndex); if (!bGap1) { if (uInsane == uFirstLetter1) uFirstLetter1 = uColIndex; uLastLetter1 = uColIndex; } if (!bGap2) { if (uInsane == uFirstLetter2) uFirstLetter2 = uColIndex; uLastLetter2 = uColIndex; } if (bGap1 || bGap2 || bWildcard1 || bWildcard2) continue; unsigned uLetter1 = msa1.GetLetter(uSeqIndex1, uColIndex); unsigned uLetter2 = msa2.GetLetter(uSeqIndex2, uColIndex); SCORE scoreMatch = (*g_ptrScoreMatrix)[uLetter1][uLetter2]; scoreTotal += scoreMatch; #if TRACE Log("%c <-> %c = %7.1f %10.1f\n", msa1.GetChar(uSeqIndex1, uColIndex), msa2.GetChar(uSeqIndex2, uColIndex), scoreMatch, scoreTotal); #endif } *ptrLetters = scoreTotal; // Gap penalties unsigned uGapLength = uInsane; unsigned uGapStartCol = uInsane; bool bGapping1 = false; bool bGapping2 = false; for (unsigned uColIndex = 0; uColIndex < uColCount; ++uColIndex) { bool bGap1 = msa1.IsGap(uSeqIndex1, uColIndex); bool bGap2 = msa2.IsGap(uSeqIndex2, uColIndex); if (bGap1 && bGap2) continue; if (bGapping1) { if (bGap1) ++uGapLength; else { bGapping1 = false; bool bNTerm = (uFirstLetter2 == uGapStartCol); bool bCTerm = (uLastLetter2 + 1 == uColIndex); SCORE scoreGap = GapPenalty(uGapLength, bNTerm || bCTerm); scoreTotal += scoreGap; #if TRACE LogGap(uGapStartCol, uColIndex - 1, uGapLength, bNTerm, bCTerm); Log("GAP %7.1f %10.1f\n", scoreGap, scoreTotal); #endif } continue; } else { if (bGap1) { uGapStartCol = uColIndex; bGapping1 = true; uGapLength = 1; continue; } } if (bGapping2) { if (bGap2) ++uGapLength; else { bGapping2 = false; bool bNTerm = (uFirstLetter1 == uGapStartCol); bool bCTerm = (uLastLetter1 + 1 == uColIndex); SCORE scoreGap = GapPenalty(uGapLength, bNTerm || bCTerm); scoreTotal += scoreGap; #if TRACE LogGap(uGapStartCol, uColIndex - 1, uGapLength, bNTerm, bCTerm); Log("GAP %7.1f %10.1f\n", scoreGap, scoreTotal); #endif } } else { if (bGap2) { uGapStartCol = uColIndex; bGapping2 = true; uGapLength = 1; } } } if (bGapping1 || bGapping2) { SCORE scoreGap = GapPenalty(uGapLength, true); scoreTotal += scoreGap; #if TRACE LogGap(uGapStartCol, uColCount - 1, uGapLength, false, true); Log("GAP %7.1f %10.1f\n", scoreGap, scoreTotal); #endif } *ptrGaps = scoreTotal - *ptrLetters; return scoreTotal; } // The usual sum-of-pairs objective score: sum the score // of the alignment of each pair of sequences. SCORE ObjScoreDA(const MSA &msa, SCORE *ptrLetters, SCORE *ptrGaps) { const unsigned uSeqCount = msa.GetSeqCount(); SCORE scoreTotal = 0; unsigned uPairCount = 0; #if TRACE msa.LogMe(); Log(" Score Weight Weight Total\n"); Log("---------- ------ ------ ----------\n"); #endif SCORE TotalLetters = 0; SCORE TotalGaps = 0; for (unsigned uSeqIndex1 = 0; uSeqIndex1 < uSeqCount; ++uSeqIndex1) { const WEIGHT w1 = msa.GetSeqWeight(uSeqIndex1); for (unsigned uSeqIndex2 = uSeqIndex1 + 1; uSeqIndex2 < uSeqCount; ++uSeqIndex2) { const WEIGHT w2 = msa.GetSeqWeight(uSeqIndex2); const WEIGHT w = w1*w2; SCORE Letters; SCORE Gaps; SCORE scorePair = ScoreSeqPair(msa, uSeqIndex1, msa, uSeqIndex2, &Letters, &Gaps); scoreTotal += w1*w2*scorePair; TotalLetters += w1*w2*Letters; TotalGaps += w1*w2*Gaps; ++uPairCount; #if TRACE Log("%10.2f %6.3f %6.3f %10.2f %d=%s %d=%s\n", scorePair, w1, w2, scorePair*w1*w2, uSeqIndex1, msa.GetSeqName(uSeqIndex1), uSeqIndex2, msa.GetSeqName(uSeqIndex2)); #endif } } *ptrLetters = TotalLetters; *ptrGaps = TotalGaps; return scoreTotal; } #endif // DOUBLE_AFFINE
6,734
3,349
#include "Line2D.hpp" #include <core/GodotGlobal.hpp> #include <core/CoreTypes.hpp> #include <core/Ref.hpp> #include <core/Godot.hpp> #include "__icalls.hpp" #include "Curve.hpp" #include "Gradient.hpp" #include "Texture.hpp" namespace godot { Line2D::___method_bindings Line2D::___mb = {}; void Line2D::___init_method_bindings() { ___mb.mb__curve_changed = godot::api->godot_method_bind_get_method("Line2D", "_curve_changed"); ___mb.mb__gradient_changed = godot::api->godot_method_bind_get_method("Line2D", "_gradient_changed"); ___mb.mb_add_point = godot::api->godot_method_bind_get_method("Line2D", "add_point"); ___mb.mb_clear_points = godot::api->godot_method_bind_get_method("Line2D", "clear_points"); ___mb.mb_get_antialiased = godot::api->godot_method_bind_get_method("Line2D", "get_antialiased"); ___mb.mb_get_begin_cap_mode = godot::api->godot_method_bind_get_method("Line2D", "get_begin_cap_mode"); ___mb.mb_get_curve = godot::api->godot_method_bind_get_method("Line2D", "get_curve"); ___mb.mb_get_default_color = godot::api->godot_method_bind_get_method("Line2D", "get_default_color"); ___mb.mb_get_end_cap_mode = godot::api->godot_method_bind_get_method("Line2D", "get_end_cap_mode"); ___mb.mb_get_gradient = godot::api->godot_method_bind_get_method("Line2D", "get_gradient"); ___mb.mb_get_joint_mode = godot::api->godot_method_bind_get_method("Line2D", "get_joint_mode"); ___mb.mb_get_point_count = godot::api->godot_method_bind_get_method("Line2D", "get_point_count"); ___mb.mb_get_point_position = godot::api->godot_method_bind_get_method("Line2D", "get_point_position"); ___mb.mb_get_points = godot::api->godot_method_bind_get_method("Line2D", "get_points"); ___mb.mb_get_round_precision = godot::api->godot_method_bind_get_method("Line2D", "get_round_precision"); ___mb.mb_get_sharp_limit = godot::api->godot_method_bind_get_method("Line2D", "get_sharp_limit"); ___mb.mb_get_texture = godot::api->godot_method_bind_get_method("Line2D", "get_texture"); ___mb.mb_get_texture_mode = godot::api->godot_method_bind_get_method("Line2D", "get_texture_mode"); ___mb.mb_get_width = godot::api->godot_method_bind_get_method("Line2D", "get_width"); ___mb.mb_remove_point = godot::api->godot_method_bind_get_method("Line2D", "remove_point"); ___mb.mb_set_antialiased = godot::api->godot_method_bind_get_method("Line2D", "set_antialiased"); ___mb.mb_set_begin_cap_mode = godot::api->godot_method_bind_get_method("Line2D", "set_begin_cap_mode"); ___mb.mb_set_curve = godot::api->godot_method_bind_get_method("Line2D", "set_curve"); ___mb.mb_set_default_color = godot::api->godot_method_bind_get_method("Line2D", "set_default_color"); ___mb.mb_set_end_cap_mode = godot::api->godot_method_bind_get_method("Line2D", "set_end_cap_mode"); ___mb.mb_set_gradient = godot::api->godot_method_bind_get_method("Line2D", "set_gradient"); ___mb.mb_set_joint_mode = godot::api->godot_method_bind_get_method("Line2D", "set_joint_mode"); ___mb.mb_set_point_position = godot::api->godot_method_bind_get_method("Line2D", "set_point_position"); ___mb.mb_set_points = godot::api->godot_method_bind_get_method("Line2D", "set_points"); ___mb.mb_set_round_precision = godot::api->godot_method_bind_get_method("Line2D", "set_round_precision"); ___mb.mb_set_sharp_limit = godot::api->godot_method_bind_get_method("Line2D", "set_sharp_limit"); ___mb.mb_set_texture = godot::api->godot_method_bind_get_method("Line2D", "set_texture"); ___mb.mb_set_texture_mode = godot::api->godot_method_bind_get_method("Line2D", "set_texture_mode"); ___mb.mb_set_width = godot::api->godot_method_bind_get_method("Line2D", "set_width"); } Line2D *Line2D::_new() { return (Line2D *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, godot::api->godot_get_class_constructor((char *)"Line2D")()); } void Line2D::_curve_changed() { ___godot_icall_void(___mb.mb__curve_changed, (const Object *) this); } void Line2D::_gradient_changed() { ___godot_icall_void(___mb.mb__gradient_changed, (const Object *) this); } void Line2D::add_point(const Vector2 position, const int64_t at_position) { ___godot_icall_void_Vector2_int(___mb.mb_add_point, (const Object *) this, position, at_position); } void Line2D::clear_points() { ___godot_icall_void(___mb.mb_clear_points, (const Object *) this); } bool Line2D::get_antialiased() const { return ___godot_icall_bool(___mb.mb_get_antialiased, (const Object *) this); } Line2D::LineCapMode Line2D::get_begin_cap_mode() const { return (Line2D::LineCapMode) ___godot_icall_int(___mb.mb_get_begin_cap_mode, (const Object *) this); } Ref<Curve> Line2D::get_curve() const { return Ref<Curve>::__internal_constructor(___godot_icall_Object(___mb.mb_get_curve, (const Object *) this)); } Color Line2D::get_default_color() const { return ___godot_icall_Color(___mb.mb_get_default_color, (const Object *) this); } Line2D::LineCapMode Line2D::get_end_cap_mode() const { return (Line2D::LineCapMode) ___godot_icall_int(___mb.mb_get_end_cap_mode, (const Object *) this); } Ref<Gradient> Line2D::get_gradient() const { return Ref<Gradient>::__internal_constructor(___godot_icall_Object(___mb.mb_get_gradient, (const Object *) this)); } Line2D::LineJointMode Line2D::get_joint_mode() const { return (Line2D::LineJointMode) ___godot_icall_int(___mb.mb_get_joint_mode, (const Object *) this); } int64_t Line2D::get_point_count() const { return ___godot_icall_int(___mb.mb_get_point_count, (const Object *) this); } Vector2 Line2D::get_point_position(const int64_t i) const { return ___godot_icall_Vector2_int(___mb.mb_get_point_position, (const Object *) this, i); } PoolVector2Array Line2D::get_points() const { return ___godot_icall_PoolVector2Array(___mb.mb_get_points, (const Object *) this); } int64_t Line2D::get_round_precision() const { return ___godot_icall_int(___mb.mb_get_round_precision, (const Object *) this); } real_t Line2D::get_sharp_limit() const { return ___godot_icall_float(___mb.mb_get_sharp_limit, (const Object *) this); } Ref<Texture> Line2D::get_texture() const { return Ref<Texture>::__internal_constructor(___godot_icall_Object(___mb.mb_get_texture, (const Object *) this)); } Line2D::LineTextureMode Line2D::get_texture_mode() const { return (Line2D::LineTextureMode) ___godot_icall_int(___mb.mb_get_texture_mode, (const Object *) this); } real_t Line2D::get_width() const { return ___godot_icall_float(___mb.mb_get_width, (const Object *) this); } void Line2D::remove_point(const int64_t i) { ___godot_icall_void_int(___mb.mb_remove_point, (const Object *) this, i); } void Line2D::set_antialiased(const bool antialiased) { ___godot_icall_void_bool(___mb.mb_set_antialiased, (const Object *) this, antialiased); } void Line2D::set_begin_cap_mode(const int64_t mode) { ___godot_icall_void_int(___mb.mb_set_begin_cap_mode, (const Object *) this, mode); } void Line2D::set_curve(const Ref<Curve> curve) { ___godot_icall_void_Object(___mb.mb_set_curve, (const Object *) this, curve.ptr()); } void Line2D::set_default_color(const Color color) { ___godot_icall_void_Color(___mb.mb_set_default_color, (const Object *) this, color); } void Line2D::set_end_cap_mode(const int64_t mode) { ___godot_icall_void_int(___mb.mb_set_end_cap_mode, (const Object *) this, mode); } void Line2D::set_gradient(const Ref<Gradient> color) { ___godot_icall_void_Object(___mb.mb_set_gradient, (const Object *) this, color.ptr()); } void Line2D::set_joint_mode(const int64_t mode) { ___godot_icall_void_int(___mb.mb_set_joint_mode, (const Object *) this, mode); } void Line2D::set_point_position(const int64_t i, const Vector2 position) { ___godot_icall_void_int_Vector2(___mb.mb_set_point_position, (const Object *) this, i, position); } void Line2D::set_points(const PoolVector2Array points) { ___godot_icall_void_PoolVector2Array(___mb.mb_set_points, (const Object *) this, points); } void Line2D::set_round_precision(const int64_t precision) { ___godot_icall_void_int(___mb.mb_set_round_precision, (const Object *) this, precision); } void Line2D::set_sharp_limit(const real_t limit) { ___godot_icall_void_float(___mb.mb_set_sharp_limit, (const Object *) this, limit); } void Line2D::set_texture(const Ref<Texture> texture) { ___godot_icall_void_Object(___mb.mb_set_texture, (const Object *) this, texture.ptr()); } void Line2D::set_texture_mode(const int64_t mode) { ___godot_icall_void_int(___mb.mb_set_texture_mode, (const Object *) this, mode); } void Line2D::set_width(const real_t width) { ___godot_icall_void_float(___mb.mb_set_width, (const Object *) this, width); } }
8,637
3,425
#include "LyricDecoder.h" #include "zlib/zconf.h" #include "zlib/zlib.h" #include "stdio.h" #include "QQMusicDES/des.h" #include <sys/stat.h> #include <malloc.h> #include <stdlib.h> #include <assert.h> #include<string.h> const unsigned char key[] = { 64, 71, 97, 119, 94, 50, 116, 71, 81, 54, 49, 45, 206, 210, 110, 105 }; //unsigned char QQKey[] = "!@#)(*$%123ZXC!@!@#)(NHL"; const unsigned char QQKey[] = { 0x21, 0x40, 0x23, 0x29, 0x28, 0x2A, 0x24, 0x25, 0x31, 0x32, 0x33, 0x5A, 0x58, 0x43, 0x21, 0x40, 0x21, 0x40, 0x23, 0x29, 0x28, 0x4E, 0x48, 0x4C }; // Deflate from the src buffer. The returned memory is allocated using malloc, and the caller is responsible for freeing it. // A trailing '\0' is added to the decompress result // Returns NULL on failure. unsigned char* deflate_memory(Bytef* src, unsigned src_len) { int ret = Z_STREAM_ERROR; z_stream strm; size_t dest_len = 262144; // 256k chunk size as suggested by zlib doc Bytef* dest = (Bytef*)malloc(dest_len); if (!dest) return NULL; // allocate inflate state strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.next_in = src; strm.avail_in = src_len; strm.next_out = dest; strm.avail_out = dest_len; if (inflateInit(&strm) != Z_OK) { free(dest); return NULL; } for (;;) { if (!strm.avail_in) break; ret = inflate(&strm, Z_NO_FLUSH); assert(ret != Z_STREAM_ERROR); // state not clobbered switch (ret) { case Z_NEED_DICT: case Z_DATA_ERROR: case Z_MEM_ERROR: inflateEnd(&strm); free(dest); return NULL; } if (strm.avail_out || ret == Z_STREAM_END) break; else { // double the size of output buffer Bytef* dest_new = (Bytef*)realloc(dest, 2 * dest_len); if (dest_new) { dest = dest_new; strm.next_out = dest + dest_len; strm.avail_out = dest_len; dest_len *= 2; } else { inflateEnd(&strm); free(dest); return NULL; } } } // clean up and return inflateEnd(&strm); if (ret != Z_STREAM_END) { free(dest); return NULL; } dest_len -= strm.avail_out; unsigned char* dest_new = (unsigned char*)realloc(dest, dest_len + 1); if (dest_new) dest = dest_new; else { free(dest); return NULL; } dest[dest_len] = 0; return dest; } char *krcdecode(char *src,int src_len){ if (src_len < 4 || memcmp(src, "krc1", 4) != 0) return nullptr; for (int i = 4; i < src_len; i++) { src[i] = src[i] ^ key[(i-4) % 16]; } return (char*)deflate_memory((Bytef*)src + 4, src_len - 4); } char *qrcdecode(char *src, int src_len) { if (src_len < 10 || memcmp(src, "[offset:0]", 10) != 0) return nullptr; BYTE schedule[3][16][6]; three_des_key_setup(QQKey, schedule, DES_DECRYPT); for (int i = 11; i < src_len; i += 8) three_des_crypt(reinterpret_cast<BYTE*>(src) + i, reinterpret_cast<BYTE*>(src) + i, schedule); return (char*)deflate_memory((Bytef*)src + 11, src_len - 11); }
2,880
1,437
/********************************************************************** * Copyright (c) 2008-2016, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #include "CoilWaterHeatingAirToWaterHeatPump.hpp" #include "CoilWaterHeatingAirToWaterHeatPump_Impl.hpp" #include "Model.hpp" #include "Model_Impl.hpp" #include "Curve.hpp" #include "Curve_Impl.hpp" #include "CurveBiquadratic.hpp" #include "CurveBiquadratic_Impl.hpp" #include "CurveQuadratic.hpp" #include "CurveQuadratic_Impl.hpp" #include <utilities/idd/IddFactory.hxx> #include <utilities/idd/OS_Coil_WaterHeating_AirToWaterHeatPump_FieldEnums.hxx> #include "../utilities/units/Unit.hpp" #include "../utilities/core/Assert.hpp" namespace openstudio { namespace model { namespace detail { CoilWaterHeatingAirToWaterHeatPump_Impl::CoilWaterHeatingAirToWaterHeatPump_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle) : HVACComponent_Impl(idfObject,model,keepHandle) { OS_ASSERT(idfObject.iddObject().type() == CoilWaterHeatingAirToWaterHeatPump::iddObjectType()); } CoilWaterHeatingAirToWaterHeatPump_Impl::CoilWaterHeatingAirToWaterHeatPump_Impl(const openstudio::detail::WorkspaceObject_Impl& other, Model_Impl* model, bool keepHandle) : HVACComponent_Impl(other,model,keepHandle) { OS_ASSERT(other.iddObject().type() == CoilWaterHeatingAirToWaterHeatPump::iddObjectType()); } CoilWaterHeatingAirToWaterHeatPump_Impl::CoilWaterHeatingAirToWaterHeatPump_Impl(const CoilWaterHeatingAirToWaterHeatPump_Impl& other, Model_Impl* model, bool keepHandle) : HVACComponent_Impl(other,model,keepHandle) {} const std::vector<std::string>& CoilWaterHeatingAirToWaterHeatPump_Impl::outputVariableNames() const { static std::vector<std::string> result; if (result.empty()){ } return result; } IddObjectType CoilWaterHeatingAirToWaterHeatPump_Impl::iddObjectType() const { return CoilWaterHeatingAirToWaterHeatPump::iddObjectType(); } double CoilWaterHeatingAirToWaterHeatPump_Impl::ratedHeatingCapacity() const { boost::optional<double> value = getDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedHeatingCapacity,true); OS_ASSERT(value); return value.get(); } double CoilWaterHeatingAirToWaterHeatPump_Impl::ratedCOP() const { boost::optional<double> value = getDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedCOP,true); OS_ASSERT(value); return value.get(); } double CoilWaterHeatingAirToWaterHeatPump_Impl::ratedSensibleHeatRatio() const { boost::optional<double> value = getDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedSensibleHeatRatio,true); OS_ASSERT(value); return value.get(); } double CoilWaterHeatingAirToWaterHeatPump_Impl::ratedEvaporatorInletAirDryBulbTemperature() const { boost::optional<double> value = getDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedEvaporatorInletAirDryBulbTemperature,true); OS_ASSERT(value); return value.get(); } double CoilWaterHeatingAirToWaterHeatPump_Impl::ratedEvaporatorInletAirWetBulbTemperature() const { boost::optional<double> value = getDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedEvaporatorInletAirWetBulbTemperature,true); OS_ASSERT(value); return value.get(); } double CoilWaterHeatingAirToWaterHeatPump_Impl::ratedCondenserInletWaterTemperature() const { boost::optional<double> value = getDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedCondenserInletWaterTemperature,true); OS_ASSERT(value); return value.get(); } boost::optional<double> CoilWaterHeatingAirToWaterHeatPump_Impl::ratedEvaporatorAirFlowRate() const { return getDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedEvaporatorAirFlowRate,true); } bool CoilWaterHeatingAirToWaterHeatPump_Impl::isRatedEvaporatorAirFlowRateAutosized() const { bool result = false; boost::optional<std::string> value = getString(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedEvaporatorAirFlowRate, true); if (value) { result = openstudio::istringEqual(value.get(), "autosize"); } return result; } boost::optional<double> CoilWaterHeatingAirToWaterHeatPump_Impl::ratedCondenserWaterFlowRate() const { return getDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedCondenserWaterFlowRate,true); } bool CoilWaterHeatingAirToWaterHeatPump_Impl::isRatedCondenserWaterFlowRateAutosized() const { bool result = false; boost::optional<std::string> value = getString(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedCondenserWaterFlowRate, true); if (value) { result = openstudio::istringEqual(value.get(), "autosize"); } return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::evaporatorFanPowerIncludedinRatedCOP() const { boost::optional<std::string> value = getString(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::EvaporatorFanPowerIncludedinRatedCOP,true); OS_ASSERT(value); return openstudio::istringEqual(value.get(), "Yes"); } bool CoilWaterHeatingAirToWaterHeatPump_Impl::condenserPumpPowerIncludedinRatedCOP() const { boost::optional<std::string> value = getString(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::CondenserPumpPowerIncludedinRatedCOP,true); OS_ASSERT(value); return openstudio::istringEqual(value.get(), "Yes"); } bool CoilWaterHeatingAirToWaterHeatPump_Impl::condenserPumpHeatIncludedinRatedHeatingCapacityandRatedCOP() const { boost::optional<std::string> value = getString(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::CondenserPumpHeatIncludedinRatedHeatingCapacityandRatedCOP,true); OS_ASSERT(value); return openstudio::istringEqual(value.get(), "Yes"); } double CoilWaterHeatingAirToWaterHeatPump_Impl::condenserWaterPumpPower() const { boost::optional<double> value = getDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::CondenserWaterPumpPower,true); OS_ASSERT(value); return value.get(); } double CoilWaterHeatingAirToWaterHeatPump_Impl::fractionofCondenserPumpHeattoWater() const { boost::optional<double> value = getDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::FractionofCondenserPumpHeattoWater,true); OS_ASSERT(value); return value.get(); } double CoilWaterHeatingAirToWaterHeatPump_Impl::crankcaseHeaterCapacity() const { boost::optional<double> value = getDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::CrankcaseHeaterCapacity,true); OS_ASSERT(value); return value.get(); } double CoilWaterHeatingAirToWaterHeatPump_Impl::maximumAmbientTemperatureforCrankcaseHeaterOperation() const { boost::optional<double> value = getDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::MaximumAmbientTemperatureforCrankcaseHeaterOperation,true); OS_ASSERT(value); return value.get(); } std::string CoilWaterHeatingAirToWaterHeatPump_Impl::evaporatorAirTemperatureTypeforCurveObjects() const { boost::optional<std::string> value = getString(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::EvaporatorAirTemperatureTypeforCurveObjects,true); OS_ASSERT(value); return value.get(); } Curve CoilWaterHeatingAirToWaterHeatPump_Impl::heatingCapacityFunctionofTemperatureCurve() const { boost::optional<Curve> value = optionalHeatingCapacityFunctionofTemperatureCurve(); if (!value) { LOG_AND_THROW(briefDescription() << " does not have an Heating Capacity Functionof Temperature Curve attached."); } return value.get(); } Curve CoilWaterHeatingAirToWaterHeatPump_Impl::heatingCapacityFunctionofAirFlowFractionCurve() const { boost::optional<Curve> value = optionalHeatingCapacityFunctionofAirFlowFractionCurve(); if (!value) { LOG_AND_THROW(briefDescription() << " does not have an Heating Capacity Functionof Air Flow Fraction Curve attached."); } return value.get(); } Curve CoilWaterHeatingAirToWaterHeatPump_Impl::heatingCapacityFunctionofWaterFlowFractionCurve() const { boost::optional<Curve> value = optionalHeatingCapacityFunctionofWaterFlowFractionCurve(); if (!value) { LOG_AND_THROW(briefDescription() << " does not have an Heating Capacity Functionof Water Flow Fraction Curve attached."); } return value.get(); } Curve CoilWaterHeatingAirToWaterHeatPump_Impl::heatingCOPFunctionofTemperatureCurve() const { boost::optional<Curve> value = optionalHeatingCOPFunctionofTemperatureCurve(); if (!value) { LOG_AND_THROW(briefDescription() << " does not have an Heating COPFunctionof Temperature Curve attached."); } return value.get(); } Curve CoilWaterHeatingAirToWaterHeatPump_Impl::heatingCOPFunctionofAirFlowFractionCurve() const { boost::optional<Curve> value = optionalHeatingCOPFunctionofAirFlowFractionCurve(); if (!value) { LOG_AND_THROW(briefDescription() << " does not have an Heating COPFunctionof Air Flow Fraction Curve attached."); } return value.get(); } Curve CoilWaterHeatingAirToWaterHeatPump_Impl::heatingCOPFunctionofWaterFlowFractionCurve() const { boost::optional<Curve> value = optionalHeatingCOPFunctionofWaterFlowFractionCurve(); if (!value) { LOG_AND_THROW(briefDescription() << " does not have an Heating COPFunctionof Water Flow Fraction Curve attached."); } return value.get(); } Curve CoilWaterHeatingAirToWaterHeatPump_Impl::partLoadFractionCorrelationCurve() const { boost::optional<Curve> value = optionalPartLoadFractionCorrelationCurve(); if (!value) { LOG_AND_THROW(briefDescription() << " does not have an Part Load Fraction Correlation Curve attached."); } return value.get(); } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setRatedHeatingCapacity(double ratedHeatingCapacity) { bool result = setDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedHeatingCapacity, ratedHeatingCapacity); return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setRatedCOP(double ratedCOP) { bool result = setDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedCOP, ratedCOP); return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setRatedSensibleHeatRatio(double ratedSensibleHeatRatio) { bool result = setDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedSensibleHeatRatio, ratedSensibleHeatRatio); return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setRatedEvaporatorInletAirDryBulbTemperature(double ratedEvaporatorInletAirDryBulbTemperature) { bool result = setDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedEvaporatorInletAirDryBulbTemperature, ratedEvaporatorInletAirDryBulbTemperature); return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setRatedEvaporatorInletAirWetBulbTemperature(double ratedEvaporatorInletAirWetBulbTemperature) { bool result = setDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedEvaporatorInletAirWetBulbTemperature, ratedEvaporatorInletAirWetBulbTemperature); return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setRatedCondenserInletWaterTemperature(double ratedCondenserInletWaterTemperature) { bool result = setDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedCondenserInletWaterTemperature, ratedCondenserInletWaterTemperature); return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setRatedEvaporatorAirFlowRate(boost::optional<double> ratedEvaporatorAirFlowRate) { bool result(false); if (ratedEvaporatorAirFlowRate) { result = setDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedEvaporatorAirFlowRate, ratedEvaporatorAirFlowRate.get()); } return result; } void CoilWaterHeatingAirToWaterHeatPump_Impl::autosizeRatedEvaporatorAirFlowRate() { bool result = setString(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedEvaporatorAirFlowRate, "autosize"); OS_ASSERT(result); } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setRatedCondenserWaterFlowRate(boost::optional<double> ratedCondenserWaterFlowRate) { bool result(false); if (ratedCondenserWaterFlowRate) { result = setDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedCondenserWaterFlowRate, ratedCondenserWaterFlowRate.get()); } return result; } void CoilWaterHeatingAirToWaterHeatPump_Impl::autosizeRatedCondenserWaterFlowRate() { bool result = setString(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedCondenserWaterFlowRate, "autosize"); OS_ASSERT(result); } void CoilWaterHeatingAirToWaterHeatPump_Impl::setEvaporatorFanPowerIncludedinRatedCOP(bool evaporatorFanPowerIncludedinRatedCOP) { setBooleanFieldValue(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::EvaporatorFanPowerIncludedinRatedCOP, evaporatorFanPowerIncludedinRatedCOP); } void CoilWaterHeatingAirToWaterHeatPump_Impl::setCondenserPumpPowerIncludedinRatedCOP(bool condenserPumpPowerIncludedinRatedCOP) { setBooleanFieldValue(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::CondenserPumpPowerIncludedinRatedCOP, condenserPumpPowerIncludedinRatedCOP); } void CoilWaterHeatingAirToWaterHeatPump_Impl::setCondenserPumpHeatIncludedinRatedHeatingCapacityandRatedCOP(bool condenserPumpHeatIncludedinRatedHeatingCapacityandRatedCOP) { setBooleanFieldValue(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::CondenserPumpHeatIncludedinRatedHeatingCapacityandRatedCOP, condenserPumpHeatIncludedinRatedHeatingCapacityandRatedCOP); } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setCondenserWaterPumpPower(double condenserWaterPumpPower) { bool result = setDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::CondenserWaterPumpPower, condenserWaterPumpPower); return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setFractionofCondenserPumpHeattoWater(double fractionofCondenserPumpHeattoWater) { bool result = setDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::FractionofCondenserPumpHeattoWater, fractionofCondenserPumpHeattoWater); return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setCrankcaseHeaterCapacity(double crankcaseHeaterCapacity) { bool result = setDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::CrankcaseHeaterCapacity, crankcaseHeaterCapacity); return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setMaximumAmbientTemperatureforCrankcaseHeaterOperation(double maximumAmbientTemperatureforCrankcaseHeaterOperation) { bool result = setDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::MaximumAmbientTemperatureforCrankcaseHeaterOperation, maximumAmbientTemperatureforCrankcaseHeaterOperation); return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setEvaporatorAirTemperatureTypeforCurveObjects(std::string evaporatorAirTemperatureTypeforCurveObjects) { bool result = setString(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::EvaporatorAirTemperatureTypeforCurveObjects, evaporatorAirTemperatureTypeforCurveObjects); return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setHeatingCapacityFunctionofTemperatureCurve(const Curve& curve) { bool result = setPointer(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::HeatingCapacityFunctionofTemperatureCurve, curve.handle()); return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setHeatingCapacityFunctionofAirFlowFractionCurve(const Curve& curve) { bool result = setPointer(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::HeatingCapacityFunctionofAirFlowFractionCurve, curve.handle()); return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setHeatingCapacityFunctionofWaterFlowFractionCurve(const Curve& curve) { bool result = setPointer(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::HeatingCapacityFunctionofWaterFlowFractionCurve, curve.handle()); return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setHeatingCOPFunctionofTemperatureCurve(const Curve& curve) { bool result = setPointer(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::HeatingCOPFunctionofTemperatureCurve, curve.handle()); return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setHeatingCOPFunctionofAirFlowFractionCurve(const Curve& curve) { bool result = setPointer(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::HeatingCOPFunctionofAirFlowFractionCurve, curve.handle()); return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setHeatingCOPFunctionofWaterFlowFractionCurve(const Curve& curve) { bool result = setPointer(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::HeatingCOPFunctionofWaterFlowFractionCurve, curve.handle()); return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setPartLoadFractionCorrelationCurve(const Curve& curve) { bool result = setPointer(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::PartLoadFractionCorrelationCurve, curve.handle()); return result; } boost::optional<Curve> CoilWaterHeatingAirToWaterHeatPump_Impl::optionalHeatingCapacityFunctionofTemperatureCurve() const { return getObject<ModelObject>().getModelObjectTarget<Curve>(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::HeatingCapacityFunctionofTemperatureCurve); } boost::optional<Curve> CoilWaterHeatingAirToWaterHeatPump_Impl::optionalHeatingCapacityFunctionofAirFlowFractionCurve() const { return getObject<ModelObject>().getModelObjectTarget<Curve>(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::HeatingCapacityFunctionofAirFlowFractionCurve); } boost::optional<Curve> CoilWaterHeatingAirToWaterHeatPump_Impl::optionalHeatingCapacityFunctionofWaterFlowFractionCurve() const { return getObject<ModelObject>().getModelObjectTarget<Curve>(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::HeatingCapacityFunctionofWaterFlowFractionCurve); } boost::optional<Curve> CoilWaterHeatingAirToWaterHeatPump_Impl::optionalHeatingCOPFunctionofTemperatureCurve() const { return getObject<ModelObject>().getModelObjectTarget<Curve>(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::HeatingCOPFunctionofTemperatureCurve); } boost::optional<Curve> CoilWaterHeatingAirToWaterHeatPump_Impl::optionalHeatingCOPFunctionofAirFlowFractionCurve() const { return getObject<ModelObject>().getModelObjectTarget<Curve>(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::HeatingCOPFunctionofAirFlowFractionCurve); } boost::optional<Curve> CoilWaterHeatingAirToWaterHeatPump_Impl::optionalHeatingCOPFunctionofWaterFlowFractionCurve() const { return getObject<ModelObject>().getModelObjectTarget<Curve>(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::HeatingCOPFunctionofWaterFlowFractionCurve); } boost::optional<Curve> CoilWaterHeatingAirToWaterHeatPump_Impl::optionalPartLoadFractionCorrelationCurve() const { return getObject<ModelObject>().getModelObjectTarget<Curve>(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::PartLoadFractionCorrelationCurve); } ModelObject CoilWaterHeatingAirToWaterHeatPump_Impl::clone(Model model) const { auto newCoil = ModelObject_Impl::clone(model).cast<CoilWaterHeatingAirToWaterHeatPump>(); return newCoil; } std::vector<ModelObject> CoilWaterHeatingAirToWaterHeatPump_Impl::children() const { std::vector<ModelObject> result; result.push_back(heatingCapacityFunctionofTemperatureCurve()); result.push_back(heatingCapacityFunctionofAirFlowFractionCurve()); result.push_back(heatingCapacityFunctionofWaterFlowFractionCurve()); result.push_back(heatingCOPFunctionofTemperatureCurve()); result.push_back(heatingCOPFunctionofAirFlowFractionCurve()); result.push_back(heatingCOPFunctionofWaterFlowFractionCurve()); result.push_back(partLoadFractionCorrelationCurve()); return result; } } // detail CoilWaterHeatingAirToWaterHeatPump::CoilWaterHeatingAirToWaterHeatPump(const Model& model) : HVACComponent(CoilWaterHeatingAirToWaterHeatPump::iddObjectType(),model) { OS_ASSERT(getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()); setRatedHeatingCapacity(4000.0); setRatedCOP(3.2); setRatedSensibleHeatRatio(0.6956); setRatedEvaporatorInletAirDryBulbTemperature(29.44); setRatedEvaporatorInletAirWetBulbTemperature(22.22); setRatedCondenserInletWaterTemperature(55.72); autosizeRatedEvaporatorAirFlowRate(); autosizeRatedCondenserWaterFlowRate(); setEvaporatorFanPowerIncludedinRatedCOP(false); setCondenserPumpPowerIncludedinRatedCOP(false); setCondenserPumpHeatIncludedinRatedHeatingCapacityandRatedCOP(false); setCondenserWaterPumpPower(150.0); setFractionofCondenserPumpHeattoWater(0.1); setCrankcaseHeaterCapacity(100.0); setMaximumAmbientTemperatureforCrankcaseHeaterOperation(5.0); setEvaporatorAirTemperatureTypeforCurveObjects("WetBulbTemperature"); { CurveBiquadratic curve(model); curve.setCoefficient1Constant(0.369827); curve.setCoefficient2x(0.043341); curve.setCoefficient3xPOW2(-0.00023); curve.setCoefficient4y(0.000466); curve.setCoefficient5yPOW2(0.000026); curve.setCoefficient6xTIMESY(-0.00027); curve.setMinimumValueofx(0.0); curve.setMaximumValueofx(40.0); curve.setMinimumValueofy(20.0); curve.setMaximumValueofy(90.0); curve.setInputUnitTypeforX("Temperature"); curve.setInputUnitTypeforY("Temperature"); curve.setOutputUnitType("Dimensionless"); setHeatingCapacityFunctionofTemperatureCurve(curve); } { CurveQuadratic curve(model); curve.setCoefficient1Constant(1.0); curve.setCoefficient2x(0.0); curve.setCoefficient3xPOW2(0.0); curve.setMinimumValueofx(0.0); curve.setMaximumValueofx(1.0); setHeatingCapacityFunctionofAirFlowFractionCurve(curve); } { CurveQuadratic curve(model); curve.setCoefficient1Constant(1.0); curve.setCoefficient2x(0.0); curve.setCoefficient3xPOW2(0.0); curve.setMinimumValueofx(0.0); curve.setMaximumValueofx(1.0); setHeatingCapacityFunctionofWaterFlowFractionCurve(curve); } { CurveBiquadratic curve(model); curve.setCoefficient1Constant(1.19713); curve.setCoefficient2x(0.077849); curve.setCoefficient3xPOW2(-0.0000016); curve.setCoefficient4y(-0.02675); curve.setCoefficient5yPOW2(0.000296); curve.setCoefficient6xTIMESY(-0.00112); curve.setMinimumValueofx(0.0); curve.setMaximumValueofx(40.0); curve.setMinimumValueofy(20.0); curve.setMaximumValueofy(90.0); curve.setInputUnitTypeforX("Temperature"); curve.setInputUnitTypeforY("Temperature"); curve.setOutputUnitType("Dimensionless"); setHeatingCOPFunctionofTemperatureCurve(curve); } { CurveQuadratic curve(model); curve.setCoefficient1Constant(1.0); curve.setCoefficient2x(0.0); curve.setCoefficient3xPOW2(0.0); curve.setMinimumValueofx(0.0); curve.setMaximumValueofx(1.0); setHeatingCOPFunctionofAirFlowFractionCurve(curve); } { CurveQuadratic curve(model); curve.setCoefficient1Constant(1.0); curve.setCoefficient2x(0.0); curve.setCoefficient3xPOW2(0.0); curve.setMinimumValueofx(0.0); curve.setMaximumValueofx(1.0); setHeatingCOPFunctionofWaterFlowFractionCurve(curve); } { CurveQuadratic curve(model); curve.setCoefficient1Constant(0.75); curve.setCoefficient2x(0.25); curve.setCoefficient3xPOW2(0.0); curve.setMinimumValueofx(0.0); curve.setMaximumValueofx(1.0); setPartLoadFractionCorrelationCurve(curve); } } CoilWaterHeatingAirToWaterHeatPump::CoilWaterHeatingAirToWaterHeatPump(const Model& model, Curve & heatingCapacityFunctionofTemperatureCurve, Curve & heatingCapacityFunctionofAirFlowFractionCurve, Curve & heatingCapacityFunctionofWaterFlowFractionCurve, Curve & heatingCOPFunctionofTemperatureCurve, Curve & heatingCOPFunctionofAirFlowFractionCurve, Curve & heatingCOPFunctionofWaterFlowFractionCurve, Curve & partLoadFractionCorrelationCurve) : HVACComponent(CoilWaterHeatingAirToWaterHeatPump::iddObjectType(),model) { OS_ASSERT(getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()); setRatedHeatingCapacity(4000.0); setRatedCOP(3.2); setRatedSensibleHeatRatio(0.6956); setRatedEvaporatorInletAirDryBulbTemperature(29.44); setRatedEvaporatorInletAirWetBulbTemperature(22.22); setRatedCondenserInletWaterTemperature(55.72); autosizeRatedEvaporatorAirFlowRate(); autosizeRatedCondenserWaterFlowRate(); setEvaporatorFanPowerIncludedinRatedCOP(false); setCondenserPumpPowerIncludedinRatedCOP(false); setCondenserPumpHeatIncludedinRatedHeatingCapacityandRatedCOP(false); setCondenserWaterPumpPower(150.0); setFractionofCondenserPumpHeattoWater(0.1); setCrankcaseHeaterCapacity(100.0); setMaximumAmbientTemperatureforCrankcaseHeaterOperation(5.0); setEvaporatorAirTemperatureTypeforCurveObjects("WetBulbTemperature"); setHeatingCapacityFunctionofTemperatureCurve(heatingCapacityFunctionofTemperatureCurve); setHeatingCapacityFunctionofAirFlowFractionCurve(heatingCapacityFunctionofAirFlowFractionCurve); setHeatingCapacityFunctionofWaterFlowFractionCurve(heatingCapacityFunctionofWaterFlowFractionCurve); setHeatingCOPFunctionofTemperatureCurve(heatingCOPFunctionofTemperatureCurve); setHeatingCOPFunctionofAirFlowFractionCurve(heatingCOPFunctionofAirFlowFractionCurve); setHeatingCOPFunctionofWaterFlowFractionCurve(heatingCOPFunctionofWaterFlowFractionCurve); setPartLoadFractionCorrelationCurve(partLoadFractionCorrelationCurve); } IddObjectType CoilWaterHeatingAirToWaterHeatPump::iddObjectType() { return IddObjectType(IddObjectType::OS_Coil_WaterHeating_AirToWaterHeatPump); } std::vector<std::string> CoilWaterHeatingAirToWaterHeatPump::evaporatorAirTemperatureTypeforCurveObjectsValues() { return getIddKeyNames(IddFactory::instance().getObject(iddObjectType()).get(), OS_Coil_WaterHeating_AirToWaterHeatPumpFields::EvaporatorAirTemperatureTypeforCurveObjects); } double CoilWaterHeatingAirToWaterHeatPump::ratedHeatingCapacity() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->ratedHeatingCapacity(); } double CoilWaterHeatingAirToWaterHeatPump::ratedCOP() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->ratedCOP(); } double CoilWaterHeatingAirToWaterHeatPump::ratedSensibleHeatRatio() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->ratedSensibleHeatRatio(); } double CoilWaterHeatingAirToWaterHeatPump::ratedEvaporatorInletAirDryBulbTemperature() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->ratedEvaporatorInletAirDryBulbTemperature(); } double CoilWaterHeatingAirToWaterHeatPump::ratedEvaporatorInletAirWetBulbTemperature() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->ratedEvaporatorInletAirWetBulbTemperature(); } double CoilWaterHeatingAirToWaterHeatPump::ratedCondenserInletWaterTemperature() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->ratedCondenserInletWaterTemperature(); } boost::optional<double> CoilWaterHeatingAirToWaterHeatPump::ratedEvaporatorAirFlowRate() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->ratedEvaporatorAirFlowRate(); } bool CoilWaterHeatingAirToWaterHeatPump::isRatedEvaporatorAirFlowRateAutosized() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->isRatedEvaporatorAirFlowRateAutosized(); } boost::optional<double> CoilWaterHeatingAirToWaterHeatPump::ratedCondenserWaterFlowRate() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->ratedCondenserWaterFlowRate(); } bool CoilWaterHeatingAirToWaterHeatPump::isRatedCondenserWaterFlowRateAutosized() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->isRatedCondenserWaterFlowRateAutosized(); } bool CoilWaterHeatingAirToWaterHeatPump::evaporatorFanPowerIncludedinRatedCOP() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->evaporatorFanPowerIncludedinRatedCOP(); } bool CoilWaterHeatingAirToWaterHeatPump::condenserPumpPowerIncludedinRatedCOP() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->condenserPumpPowerIncludedinRatedCOP(); } bool CoilWaterHeatingAirToWaterHeatPump::condenserPumpHeatIncludedinRatedHeatingCapacityandRatedCOP() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->condenserPumpHeatIncludedinRatedHeatingCapacityandRatedCOP(); } double CoilWaterHeatingAirToWaterHeatPump::condenserWaterPumpPower() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->condenserWaterPumpPower(); } double CoilWaterHeatingAirToWaterHeatPump::fractionofCondenserPumpHeattoWater() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->fractionofCondenserPumpHeattoWater(); } double CoilWaterHeatingAirToWaterHeatPump::crankcaseHeaterCapacity() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->crankcaseHeaterCapacity(); } double CoilWaterHeatingAirToWaterHeatPump::maximumAmbientTemperatureforCrankcaseHeaterOperation() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->maximumAmbientTemperatureforCrankcaseHeaterOperation(); } std::string CoilWaterHeatingAirToWaterHeatPump::evaporatorAirTemperatureTypeforCurveObjects() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->evaporatorAirTemperatureTypeforCurveObjects(); } Curve CoilWaterHeatingAirToWaterHeatPump::heatingCapacityFunctionofTemperatureCurve() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->heatingCapacityFunctionofTemperatureCurve(); } Curve CoilWaterHeatingAirToWaterHeatPump::heatingCapacityFunctionofAirFlowFractionCurve() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->heatingCapacityFunctionofAirFlowFractionCurve(); } Curve CoilWaterHeatingAirToWaterHeatPump::heatingCapacityFunctionofWaterFlowFractionCurve() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->heatingCapacityFunctionofWaterFlowFractionCurve(); } Curve CoilWaterHeatingAirToWaterHeatPump::heatingCOPFunctionofTemperatureCurve() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->heatingCOPFunctionofTemperatureCurve(); } Curve CoilWaterHeatingAirToWaterHeatPump::heatingCOPFunctionofAirFlowFractionCurve() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->heatingCOPFunctionofAirFlowFractionCurve(); } Curve CoilWaterHeatingAirToWaterHeatPump::heatingCOPFunctionofWaterFlowFractionCurve() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->heatingCOPFunctionofWaterFlowFractionCurve(); } Curve CoilWaterHeatingAirToWaterHeatPump::partLoadFractionCorrelationCurve() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->partLoadFractionCorrelationCurve(); } bool CoilWaterHeatingAirToWaterHeatPump::setRatedHeatingCapacity(double ratedHeatingCapacity) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setRatedHeatingCapacity(ratedHeatingCapacity); } bool CoilWaterHeatingAirToWaterHeatPump::setRatedCOP(double ratedCOP) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setRatedCOP(ratedCOP); } bool CoilWaterHeatingAirToWaterHeatPump::setRatedSensibleHeatRatio(double ratedSensibleHeatRatio) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setRatedSensibleHeatRatio(ratedSensibleHeatRatio); } bool CoilWaterHeatingAirToWaterHeatPump::setRatedEvaporatorInletAirDryBulbTemperature(double ratedEvaporatorInletAirDryBulbTemperature) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setRatedEvaporatorInletAirDryBulbTemperature(ratedEvaporatorInletAirDryBulbTemperature); } bool CoilWaterHeatingAirToWaterHeatPump::setRatedEvaporatorInletAirWetBulbTemperature(double ratedEvaporatorInletAirWetBulbTemperature) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setRatedEvaporatorInletAirWetBulbTemperature(ratedEvaporatorInletAirWetBulbTemperature); } bool CoilWaterHeatingAirToWaterHeatPump::setRatedCondenserInletWaterTemperature(double ratedCondenserInletWaterTemperature) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setRatedCondenserInletWaterTemperature(ratedCondenserInletWaterTemperature); } bool CoilWaterHeatingAirToWaterHeatPump::setRatedEvaporatorAirFlowRate(double ratedEvaporatorAirFlowRate) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setRatedEvaporatorAirFlowRate(ratedEvaporatorAirFlowRate); } void CoilWaterHeatingAirToWaterHeatPump::autosizeRatedEvaporatorAirFlowRate() { getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->autosizeRatedEvaporatorAirFlowRate(); } bool CoilWaterHeatingAirToWaterHeatPump::setRatedCondenserWaterFlowRate(double ratedCondenserWaterFlowRate) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setRatedCondenserWaterFlowRate(ratedCondenserWaterFlowRate); } void CoilWaterHeatingAirToWaterHeatPump::autosizeRatedCondenserWaterFlowRate() { getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->autosizeRatedCondenserWaterFlowRate(); } void CoilWaterHeatingAirToWaterHeatPump::setEvaporatorFanPowerIncludedinRatedCOP(bool evaporatorFanPowerIncludedinRatedCOP) { getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setEvaporatorFanPowerIncludedinRatedCOP(evaporatorFanPowerIncludedinRatedCOP); } void CoilWaterHeatingAirToWaterHeatPump::setCondenserPumpPowerIncludedinRatedCOP(bool condenserPumpPowerIncludedinRatedCOP) { getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setCondenserPumpPowerIncludedinRatedCOP(condenserPumpPowerIncludedinRatedCOP); } void CoilWaterHeatingAirToWaterHeatPump::setCondenserPumpHeatIncludedinRatedHeatingCapacityandRatedCOP(bool condenserPumpHeatIncludedinRatedHeatingCapacityandRatedCOP) { getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setCondenserPumpHeatIncludedinRatedHeatingCapacityandRatedCOP(condenserPumpHeatIncludedinRatedHeatingCapacityandRatedCOP); } bool CoilWaterHeatingAirToWaterHeatPump::setCondenserWaterPumpPower(double condenserWaterPumpPower) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setCondenserWaterPumpPower(condenserWaterPumpPower); } bool CoilWaterHeatingAirToWaterHeatPump::setFractionofCondenserPumpHeattoWater(double fractionofCondenserPumpHeattoWater) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setFractionofCondenserPumpHeattoWater(fractionofCondenserPumpHeattoWater); } bool CoilWaterHeatingAirToWaterHeatPump::setCrankcaseHeaterCapacity(double crankcaseHeaterCapacity) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setCrankcaseHeaterCapacity(crankcaseHeaterCapacity); } bool CoilWaterHeatingAirToWaterHeatPump::setMaximumAmbientTemperatureforCrankcaseHeaterOperation(double maximumAmbientTemperatureforCrankcaseHeaterOperation) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setMaximumAmbientTemperatureforCrankcaseHeaterOperation(maximumAmbientTemperatureforCrankcaseHeaterOperation); } bool CoilWaterHeatingAirToWaterHeatPump::setEvaporatorAirTemperatureTypeforCurveObjects(std::string evaporatorAirTemperatureTypeforCurveObjects) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setEvaporatorAirTemperatureTypeforCurveObjects(evaporatorAirTemperatureTypeforCurveObjects); } bool CoilWaterHeatingAirToWaterHeatPump::setHeatingCapacityFunctionofTemperatureCurve(const Curve& curve) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setHeatingCapacityFunctionofTemperatureCurve(curve); } bool CoilWaterHeatingAirToWaterHeatPump::setHeatingCapacityFunctionofAirFlowFractionCurve(const Curve& curve) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setHeatingCapacityFunctionofAirFlowFractionCurve(curve); } bool CoilWaterHeatingAirToWaterHeatPump::setHeatingCapacityFunctionofWaterFlowFractionCurve(const Curve& curve) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setHeatingCapacityFunctionofWaterFlowFractionCurve(curve); } bool CoilWaterHeatingAirToWaterHeatPump::setHeatingCOPFunctionofTemperatureCurve(const Curve& curve) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setHeatingCOPFunctionofTemperatureCurve(curve); } bool CoilWaterHeatingAirToWaterHeatPump::setHeatingCOPFunctionofAirFlowFractionCurve(const Curve& curve) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setHeatingCOPFunctionofAirFlowFractionCurve(curve); } bool CoilWaterHeatingAirToWaterHeatPump::setHeatingCOPFunctionofWaterFlowFractionCurve(const Curve& curve) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setHeatingCOPFunctionofWaterFlowFractionCurve(curve); } bool CoilWaterHeatingAirToWaterHeatPump::setPartLoadFractionCorrelationCurve(const Curve& curve) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setPartLoadFractionCorrelationCurve(curve); } /// @cond CoilWaterHeatingAirToWaterHeatPump::CoilWaterHeatingAirToWaterHeatPump(std::shared_ptr<detail::CoilWaterHeatingAirToWaterHeatPump_Impl> impl) : HVACComponent(impl) {} /// @endcond } // model } // openstudio
38,751
14,238
#include <string> #include <sstream> #include <iostream> #include "log.h" using std::string; using std::stringstream; void log::info(string message) { std::cout << "\e[0;32m[INFO]\e[0m - " << message << std::endl; } void log::error(string name, string message) { std::cerr << "\e[0;31m" << name << ":\e[0m " << message << std::endl; } void log::fatal(string name, string message) { stringstream err_name; err_name << "Fatal - " << name; log::error(err_name.str(), message); exit(1); } void log::missing_argument(string command, string parameter) { stringstream message; message << "Command `" << command << "' expects an argument of `" << parameter << "'."; log::fatal("Missing Argument", message.str()); }
723
256
// $Id: ngt.cpp 245 2009-04-02 14:05:40Z fabio_brugnara $ /****************************************************************************** IrstLM: IRST Language Model Toolkit Copyright (C) 2006 Marcello Federico, ITC-irst Trento, Italy This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ******************************************************************************/ // ngt // by M. Federico // Copyright Marcello Federico, ITC-irst, 1998 #include <iostream> #include <sstream> #include <cmath> #include "util.h" #include "cmd.h" #include "mfstream.h" #include "mempool.h" #include "htable.h" #include "dictionary.h" #include "n_gram.h" #include "ngramtable.h" using namespace std; void print_help(int TypeFlag=0){ std::cerr << std::endl << "ngt - collects n-grams" << std::endl; std::cerr << std::endl << "USAGE:" << std::endl; std::cerr << " ngt -i=<inputfile> [options]" << std::endl; std::cerr << std::endl << "OPTIONS:" << std::endl; FullPrintParams(TypeFlag, 0, 1, stderr); } void usage(const char *msg = 0) { if (msg){ std::cerr << msg << std::endl; } else{ print_help(); } } int main(int argc, char **argv) { char *inp=NULL; char *out=NULL; char *dic=NULL; // dictionary filename char *subdic=NULL; // subdictionary filename char *filterdict=NULL; // subdictionary filename char *filtertable=NULL; // ngramtable filename char *iknfile=NULL; // filename to save IKN statistics double filter_hit_rate=1.0; // minimum hit rate of filter char *aug=NULL; // augmentation data char *hmask=NULL; // historymask bool inputgoogleformat=false; //reads ngrams in Google format bool outputgoogleformat=false; //print ngrams in Google format int ngsz=0; // n-gram default size int dstco=0; // compute distance co-occurrences bool bin=false; bool ss=false; //generate single table bool LMflag=false; //work with LM table int inplen=0; //input length for mask generation bool tlm=false; //test lm table char* ftlm=NULL; //file to test LM table bool memuse=false; bool help=false; DeclareParams((char*) "Dictionary", CMDSTRINGTYPE|CMDMSG, &dic, "dictionary filename", "d", CMDSTRINGTYPE|CMDMSG, &dic, "dictionary filename", "NgramSize", CMDSUBRANGETYPE|CMDMSG, &ngsz, 1, MAX_NGRAM, "n-gram default size; default is 0", "n", CMDSUBRANGETYPE|CMDMSG, &ngsz, 1, MAX_NGRAM, "n-gram default size; default is 0", "InputFile", CMDSTRINGTYPE|CMDMSG, &inp, "input file", "i", CMDSTRINGTYPE|CMDMSG, &inp, "input file", "OutputFile", CMDSTRINGTYPE|CMDMSG, &out, "output file", "o", CMDSTRINGTYPE|CMDMSG, &out, "output file", "InputGoogleFormat", CMDBOOLTYPE|CMDMSG, &inputgoogleformat, "the input file contains data in the n-gram Google format; default is false", "gooinp", CMDBOOLTYPE|CMDMSG, &inputgoogleformat, "the input file contains data in the n-gram Google format; default is false", "OutputGoogleFormat", CMDBOOLTYPE|CMDMSG, &outputgoogleformat, "the output file contains data in the n-gram Google format; default is false", "gooout", CMDBOOLTYPE|CMDMSG, &outputgoogleformat, "the output file contains data in the n-gram Google format; default is false", "SaveBinaryTable", CMDBOOLTYPE|CMDMSG, &bin, "saves into binary format; default is false", "b", CMDBOOLTYPE|CMDMSG, &bin, "saves into binary format; default is false", "LmTable", CMDBOOLTYPE|CMDMSG, &LMflag, "works with LM table; default is false", "lm", CMDBOOLTYPE|CMDMSG, &LMflag, "works with LM table; default is false", "DistCo", CMDINTTYPE|CMDMSG, &dstco, "computes distance co-occurrences at the specified distance; default is 0", "dc", CMDINTTYPE|CMDMSG, &dstco, "computes distance co-occurrences at the specified distance; default is 0", "AugmentFile", CMDSTRINGTYPE|CMDMSG, &aug, "augmentation data", "aug", CMDSTRINGTYPE|CMDMSG, &aug, "augmentation data", "SaveSingle", CMDBOOLTYPE|CMDMSG, &ss, "generates single table; default is false", "ss", CMDBOOLTYPE|CMDMSG, &ss, "generates single table; default is false", "SubDict", CMDSTRINGTYPE|CMDMSG, &subdic, "subdictionary", "sd", CMDSTRINGTYPE|CMDMSG, &subdic, "subdictionary", "FilterDict", CMDSTRINGTYPE|CMDMSG, &filterdict, "filter dictionary", "fd", CMDSTRINGTYPE|CMDMSG, &filterdict, "filter dictionary", "ConvDict", CMDSTRINGTYPE|CMDMSG, &subdic, "subdictionary", "cd", CMDSTRINGTYPE|CMDMSG, &subdic, "subdictionary", "FilterTable", CMDSTRINGTYPE|CMDMSG, &filtertable, "ngramtable filename", "ftr", CMDDOUBLETYPE|CMDMSG, &filter_hit_rate, "ngramtable filename", "FilterTableRate", CMDDOUBLETYPE|CMDMSG, &filter_hit_rate, "minimum hit rate of filter; default is 1.0", "ft", CMDSTRINGTYPE|CMDMSG, &filtertable, "minimum hit rate of filter; default is 1.0", "HistoMask",CMDSTRINGTYPE|CMDMSG, &hmask, "history mask", "hm",CMDSTRINGTYPE|CMDMSG, &hmask, "history mask", "InpLen",CMDINTTYPE|CMDMSG, &inplen, "input length for mask generation; default is 0", "il",CMDINTTYPE|CMDMSG, &inplen, "input length for mask generation; default is 0", "tlm", CMDBOOLTYPE|CMDMSG, &tlm, "test LM table; default is false", "ftlm", CMDSTRINGTYPE|CMDMSG, &ftlm, "file to test LM table", "memuse", CMDBOOLTYPE|CMDMSG, &memuse, "default is false", "iknstat", CMDSTRINGTYPE|CMDMSG, &iknfile, "filename to save IKN statistics", "Help", CMDBOOLTYPE|CMDMSG, &help, "print this help", "h", CMDBOOLTYPE|CMDMSG, &help, "print this help", (char *)NULL ); if (argc == 1){ usage(); exit_error(IRSTLM_NO_ERROR); } GetParams(&argc, &argv, (char*) NULL); if (help){ usage(); exit_error(IRSTLM_NO_ERROR); } if (inp==NULL) { usage(); exit_error(IRSTLM_ERROR_DATA,"Warning: no input file specified"); }; if (out==NULL) { cerr << "Warning: no output file specified!\n"; } TABLETYPE table_type=COUNT; if (LMflag) { cerr << "Working with LM table\n"; table_type=LEAFPROB; } // check word order of subdictionary if (filtertable) { { ngramtable ngt(filtertable,1,NULL,NULL,NULL,0,0,NULL,0,table_type); mfstream inpstream(inp,ios::in); //google input table mfstream outstream(out,ios::out); //google output table cerr << "Filtering table " << inp << " assumed to be in Google Format with size " << ngsz << "\n"; cerr << "with table " << filtertable << " of size " << ngt.maxlevel() << "\n"; cerr << "with hit rate " << filter_hit_rate << "\n"; //order of filter table must be smaller than that of input n-grams assert(ngt.maxlevel() <= ngsz); //read input googletable of ngrams of size ngsz //output entries made of at least X% n-grams contained in filtertable //<unk> words are not accepted ngram ng(ngt.dict), ng2(ng.dict); double hits=0; double maxhits=(double)(ngsz-ngt.maxlevel()+1); long c=0; while(inpstream >> ng) { if (ng.size>= ngt.maxlevel()) { //need to make a copy ng2=ng; ng2.size=ngt.maxlevel(); //cerr << "check if " << ng2 << " is contained: "; hits+=(ngt.get(ng2)?1:0); } if (ng.size==ngsz) { if (!(++c % 1000000)) cerr << "."; //cerr << ng << " -> " << is_included << "\n"; //you reached the last word before freq inpstream >> ng.freq; //consistency check of n-gram if (((hits/maxhits)>=filter_hit_rate) && (!ng.containsWord(ngt.dict->OOV(),ng.size)) ) outstream << ng << "\n"; hits=0; ng.size=0; } } outstream.flush(); inpstream.flush(); } exit_error(IRSTLM_NO_ERROR); } //ngramtable* ngt=new ngramtable(inp,ngsz,NULL,dic,dstco,hmask,inplen,table_type); ngramtable* ngt=new ngramtable(inp,ngsz,NULL,NULL,filterdict,inputgoogleformat,dstco,hmask,inplen,table_type); if (aug) { ngt->dict->incflag(1); // ngramtable ngt2(aug,ngsz,isym,NULL,0,NULL,0,table_type); ngramtable ngt2(aug,ngsz,NULL,NULL,NULL,0,0,NULL,0,table_type); ngt->augment(&ngt2); ngt->dict->incflag(0); } if (subdic) { ngramtable *ngt2=new ngramtable(NULL,ngsz,NULL,NULL,NULL,0,0,NULL,0,table_type); // enforce the subdict to follow the same word order of the main dictionary dictionary tmpdict(subdic); ngt2->dict->incflag(1); for (int j=0; j<ngt->dict->size(); j++) { if (tmpdict.encode(ngt->dict->decode(j)) != tmpdict.oovcode()) { ngt2->dict->encode(ngt->dict->decode(j)); } } ngt2->dict->incflag(0); ngt2->dict->cleanfreq(); //possibly include standard symbols if (ngt->dict->encode(ngt->dict->EoS())!=ngt->dict->oovcode()) { ngt2->dict->incflag(1); ngt2->dict->encode(ngt2->dict->EoS()); ngt2->dict->incflag(0); } if (ngt->dict->encode(ngt->dict->BoS())!=ngt->dict->oovcode()) { ngt2->dict->incflag(1); ngt2->dict->encode(ngt2->dict->BoS()); ngt2->dict->incflag(0); } ngram ng(ngt->dict); ngram ng2(ngt2->dict); ngt->scan(ng,INIT,ngsz); long c=0; while (ngt->scan(ng,CONT,ngsz)) { ng2.trans(ng); ngt2->put(ng2); if (!(++c % 1000000)) cerr << "."; } //makes ngt2 aware of oov code int oov=ngt2->dict->getcode(ngt2->dict->OOV()); if(oov>=0) ngt2->dict->oovcode(oov); for (int j=0; j<ngt->dict->size(); j++) { ngt2->dict->incfreq(ngt2->dict->encode(ngt->dict->decode(j)), ngt->dict->freq(j)); } cerr <<" oov: " << ngt2->dict->freq(ngt2->dict->oovcode()) << "\n"; delete ngt; ngt=ngt2; } if (ngsz < ngt->maxlevel() && hmask) { cerr << "start projection of ngramtable " << inp << " according to hmask\n"; int selmask[MAX_NGRAM]; memset(selmask, 0, sizeof(int)*MAX_NGRAM); //parse hmask selmask[0]=1; int i=1; for (size_t c=0; c<strlen(hmask); c++) { cerr << hmask[c] << "\n"; if (hmask[c] == '1'){ selmask[i]=c+2; i++; } } if (i!= ngsz) { std::stringstream ss_msg; ss_msg << "wrong mask: 1 bits=" << i << " maxlev=" << ngsz; exit_error(IRSTLM_ERROR_DATA, ss_msg.str()); } if (selmask[ngsz-1] > ngt->maxlevel()) { std::stringstream ss_msg; ss_msg << "wrong mask: farest bits=" << selmask[ngsz-1] << " maxlev=" << ngt->maxlevel() << "\n"; exit_error(IRSTLM_ERROR_DATA, ss_msg.str()); } //ngramtable* ngt2=new ngramtable(NULL,ngsz,NULL,NULL,0,NULL,0,table_type); ngramtable* ngt2=new ngramtable(NULL,ngsz,NULL,NULL,NULL,0,0,NULL,0,table_type); ngt2->dict->incflag(1); ngram ng(ngt->dict); ngram png(ngt->dict,ngsz); ngram ng2(ngt2->dict,ngsz); ngt->scan(ng,INIT,ngt->maxlevel()); long c=0; while (ngt->scan(ng,CONT,ngt->maxlevel())) { //projection for (int j=0; j<ngsz; j++) *png.wordp(j+1)=*ng.wordp(selmask[j]); png.freq=ng.freq; //transfer ng2.trans(png); ngt2->put(ng2); if (!(++c % 1000000)) cerr << "."; } char info[100]; sprintf(info,"hm%s",hmask); ngt2->ngtype(info); //makes ngt2 aware of oov code int oov=ngt2->dict->getcode(ngt2->dict->OOV()); if(oov>=0) ngt2->dict->oovcode(oov); for (int j=0; j<ngt->dict->size(); j++) { ngt2->dict->incfreq(ngt2->dict->encode(ngt->dict->decode(j)), ngt->dict->freq(j)); } cerr <<" oov: " << ngt2->dict->freq(ngt2->dict->oovcode()) << "\n"; delete ngt; ngt=ngt2; } if (tlm && table_type==LEAFPROB) { ngram ng(ngt->dict); cout.setf(ios::scientific); cout << "> "; while(cin >> ng) { ngt->bo_state(0); if (ng.size>=ngsz) { cout << ng << " p= " << log(ngt->prob(ng)); cout << " bo= " << ngt->bo_state() << "\n"; } else cout << ng << " p= NULL\n"; cout << "> "; } } if (ftlm && table_type==LEAFPROB) { ngram ng(ngt->dict); cout.setf(ios::fixed); cout.precision(2); mfstream inptxt(ftlm,ios::in); int Nbo=0,Nw=0,Noov=0; float logPr=0,PP=0,PPwp=0; int bos=ng.dict->encode(ng.dict->BoS()); while(inptxt >> ng) { // reset ngram at begin of sentence if (*ng.wordp(1)==bos) { ng.size=1; continue; } ngt->bo_state(0); if (ng.size>=1) { logPr+=log(ngt->prob(ng)); if (*ng.wordp(1) == ngt->dict->oovcode()) Noov++; Nw++; if (ngt->bo_state()) Nbo++; } } PP=exp(-logPr/Nw); PPwp= PP * exp(Noov * log(10000000.0-ngt->dict->size())/Nw); cout << "%%% NGT TEST OF SMT LM\n"; cout << "%% LM=" << inp << " SIZE="<< ngt->maxlevel(); cout << " TestFile="<< ftlm << "\n"; cout << "%% OOV PENALTY = 1/" << 10000000.0-ngt->dict->size() << "\n"; cout << "%% Nw=" << Nw << " PP=" << PP << " PPwp=" << PPwp << " Nbo=" << Nbo << " Noov=" << Noov << " OOV=" << (float)Noov/Nw * 100.0 << "%\n"; } if (memuse) ngt->stat(0); if (iknfile) { //compute and save statistics of Improved Kneser Ney smoothing ngram ng(ngt->dict); int n1,n2,n3,n4; int unover3=0; mfstream iknstat(iknfile,ios::out); //output of ikn statistics for (int l=1; l<=ngt->maxlevel(); l++) { cerr << "level " << l << "\n"; iknstat << "level: " << l << " "; cerr << "computing statistics\n"; n1=0; n2=0; n3=0,n4=0; ngt->scan(ng,INIT,l); while(ngt->scan(ng,CONT,l)) { //skip ngrams containing _OOV if (l>1 && ng.containsWord(ngt->dict->OOV(),l)) { //cerr << "skp ngram" << ng << "\n"; continue; } //skip n-grams containing </s> in context if (l>1 && ng.containsWord(ngt->dict->EoS(),l-1)) { //cerr << "skp ngram" << ng << "\n"; continue; } //skip 1-grams containing <s> if (l==1 && ng.containsWord(ngt->dict->BoS(),l)) { //cerr << "skp ngram" << ng << "\n"; continue; } if (ng.freq==1) n1++; else if (ng.freq==2) n2++; else if (ng.freq==3) n3++; else if (ng.freq==4) n4++; if (l==1 && ng.freq >=3) unover3++; } cerr << " n1: " << n1 << " n2: " << n2 << " n3: " << n3 << " n4: " << n4 << "\n"; iknstat << " n1: " << n1 << " n2: " << n2 << " n3: " << n3 << " n4: " << n4 << " unover3: " << unover3 << "\n"; } } if (out) bin?ngt->savebin(out,ngsz): ngt->savetxt(out,ngsz,outputgoogleformat); }
15,885
6,068
#ifndef STAN_MATH_FWD_SCAL_FUN_TRUNC_HPP #define STAN_MATH_FWD_SCAL_FUN_TRUNC_HPP #include <stan/math/fwd/core.hpp> #include <stan/math/prim/scal/fun/trunc.hpp> namespace stan { namespace math { /** * Return the nearest integral value that is not larger in * magnitude than the specified argument. * * @tparam T Scalar type of autodiff variable. * @param[in] x Argument. * @return The truncated argument. */ template <typename T> inline fvar<T> trunc(const fvar<T>& x) { return fvar<T>(trunc(x.val_), 0); } } } #endif
583
223
#include "tests_runner.h" #include "../compact_vector.h" std::string test_string = "hello_world_hello_world_hello_world_hello_world"; COMPACT_VECTOR_TEST(constructor_1) { compact_vector<uint8_t> vector(10); } COMPACT_VECTOR_TEST(constructor_2) { compact_vector<uint8_t> vector(100); } COMPACT_VECTOR_TEST(constructor_3) { uint8_t default_value = 100; size_t size = 10; compact_vector<uint8_t> vector(size, default_value); COMPACT_VECTOR_ASSERT(vector.size() == size); for (int i = 0; i < vector.size(); i++) COMPACT_VECTOR_ASSERT(vector.at(i) == default_value); } COMPACT_VECTOR_TEST(constructor_4) { uint8_t default_value = 100; size_t size = 100; compact_vector<uint8_t> vector(size, default_value); auto t = vector.size(); COMPACT_VECTOR_ASSERT(vector.size() == size); for (int i = 0; i < vector.size(); i++) COMPACT_VECTOR_ASSERT(vector.at(i) == default_value); } COMPACT_VECTOR_TEST(constructor_5) { compact_vector<std::string, 10> vector(10); } COMPACT_VECTOR_TEST(constructor_6) { compact_vector<std::string, 10> vector(100); } COMPACT_VECTOR_TEST(constructor_7) { size_t size = 10; compact_vector<std::string, 10> vector(size, test_string); COMPACT_VECTOR_ASSERT(vector.size() == size); for (int i = 0; i < vector.size(); i++) COMPACT_VECTOR_ASSERT(vector.at(i) == test_string); } COMPACT_VECTOR_TEST(constructor_8) { size_t size = 100; compact_vector<std::string, 10> vector(size, test_string); auto t = vector.size(); COMPACT_VECTOR_ASSERT(vector.size() == size); for (int i = 0; i < vector.size(); i++) COMPACT_VECTOR_ASSERT(vector.at(i) == test_string); } COMPACT_VECTOR_TEST(constructor_end) { throw new std::exception(); }
1,684
732
/* * Auto-Generated File. Changes will be destroyed. */ #include "squid.h" #include "auth/CredentialState.h" namespace Auth { const char *CredentialState_str[] = { "Unchecked", "Ok", "Pending", "Handshake", "Failed" }; }; // namespace Auth
248
93
/* Copyright (c) <2003-2021> <Julio Jerez, Newton Game Dynamics> * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. */ #include "dCoreStdafx.h" #include "ndCollisionStdafx.h" #include "ndShapeInstance.h" #include "ndContactSolver.h" #include "ndCollisionStdafx.h" #include "ndShapeStaticMesh.h" D_CLASS_REFLECTION_IMPLEMENT_LOADER(ndShapeStaticMesh) void ndPolygonMeshDesc::SortFaceArray() { dInt32 stride = 8; if (m_faceCount >= 8) { dInt32 stack[D_MAX_COLLIDING_FACES][2]; stack[0][0] = 0; stack[0][1] = m_faceCount - 1; dInt32 stackIndex = 1; while (stackIndex) { stackIndex--; dInt32 lo = stack[stackIndex][0]; dInt32 hi = stack[stackIndex][1]; if ((hi - lo) > stride) { dInt32 i = lo; dInt32 j = hi; dFloat32 dist = m_hitDistance[(lo + hi) >> 1]; do { while (m_hitDistance[i] < dist) i++; while (m_hitDistance[j] > dist) j--; if (i <= j) { dSwap(m_hitDistance[i], m_hitDistance[j]); dSwap(m_faceIndexStart[i], m_faceIndexStart[j]); dSwap(m_faceIndexCount[i], m_faceIndexCount[j]); i++; j--; } } while (i <= j); if (i < hi) { stack[stackIndex][0] = i; stack[stackIndex][1] = hi; stackIndex++; } if (lo < j) { stack[stackIndex][0] = lo; stack[stackIndex][1] = j; stackIndex++; } dAssert(stackIndex < dInt32(sizeof(stack) / (2 * sizeof(stack[0][0])))); } } } stride = stride * 2; if (m_faceCount < stride) { stride = m_faceCount; } for (dInt32 i = 1; i < stride; i++) { if (m_hitDistance[i] < m_hitDistance[0]) { dSwap(m_hitDistance[i], m_hitDistance[0]); dSwap(m_faceIndexStart[i], m_faceIndexStart[0]); dSwap(m_faceIndexCount[i], m_faceIndexCount[0]); } } for (dInt32 i = 1; i < m_faceCount; i++) { dInt32 j = i; dInt32 ptr = m_faceIndexStart[i]; dInt32 count = m_faceIndexCount[i]; dFloat32 dist = m_hitDistance[i]; for (; dist < m_hitDistance[j - 1]; j--) { dAssert(j > 0); m_hitDistance[j] = m_hitDistance[j - 1]; m_faceIndexStart[j] = m_faceIndexStart[j - 1]; m_faceIndexCount[j] = m_faceIndexCount[j - 1]; } m_hitDistance[j] = dist; m_faceIndexStart[j] = ptr; m_faceIndexCount[j] = count; } #ifdef _DEBUG for (dInt32 i = 0; i < m_faceCount - 1; i++) { dAssert(m_hitDistance[i] <= m_hitDistance[i + 1]); } #endif } ndPolygonMeshDesc::ndPolygonMeshDesc(ndContactSolver& proxy, bool ccdMode) :dFastAabb() ,m_boxDistanceTravelInMeshSpace(dVector::m_zero) ,m_faceCount(0) ,m_vertexStrideInBytes(0) ,m_skinThickness(proxy.m_skinThickness) ,m_convexInstance(&proxy.m_instance0) ,m_polySoupInstance(&proxy.m_instance1) ,m_vertex(nullptr) ,m_faceIndexCount(nullptr) ,m_faceVertexIndex(nullptr) ,m_faceIndexStart(nullptr) ,m_hitDistance(nullptr) ,m_maxT(dFloat32 (1.0f)) ,m_doContinuesCollisionTest(ccdMode) { const dMatrix& hullMatrix = m_convexInstance->GetGlobalMatrix(); const dMatrix& soupMatrix = m_polySoupInstance->GetGlobalMatrix(); dMatrix& matrix = *this; matrix = hullMatrix * soupMatrix.Inverse(); dMatrix convexMatrix (dGetIdentityMatrix()); switch (m_polySoupInstance->GetScaleType()) { case ndShapeInstance::m_unit: { break; } case ndShapeInstance::m_uniform: { const dVector& invScale = m_polySoupInstance->GetInvScale(); convexMatrix[0][0] = invScale.GetScalar(); convexMatrix[1][1] = invScale.GetScalar(); convexMatrix[2][2] = invScale.GetScalar(); matrix.m_posit = matrix.m_posit * (invScale | dVector::m_wOne); break; } case ndShapeInstance::m_nonUniform: { const dVector& invScale = m_polySoupInstance->GetInvScale(); dMatrix tmp (matrix[0] * invScale, matrix[1] * invScale, matrix[2] * invScale, dVector::m_wOne); convexMatrix = tmp * matrix.Inverse(); convexMatrix.m_posit = dVector::m_wOne; matrix.m_posit = matrix.m_posit * (invScale | dVector::m_wOne); break; } case ndShapeInstance::m_global: default: { dAssert (0); } } dMatrix fullMatrix (convexMatrix * matrix); m_convexInstance->CalculateAabb(fullMatrix, m_p0, m_p1); dVector p0; dVector p1; SetTransposeAbsMatrix(matrix); m_convexInstance->CalculateAabb(convexMatrix, p0, p1); m_size = dVector::m_half * (p1 - p0); m_posit = matrix.TransformVector(dVector::m_half * (p1 + p0)); dAssert (m_posit.m_w == dFloat32 (1.0f)); } ndShapeStaticMesh::ndShapeStaticMesh(ndShapeID id) :ndShape(id) { } ndShapeStaticMesh::ndShapeStaticMesh(const dLoadSaveBase::dLoadDescriptor&) :ndShape(m_staticMesh) { } ndShapeStaticMesh::~ndShapeStaticMesh() { } void ndShapeStaticMesh::CalculateAabb(const dMatrix& matrix, dVector &p0, dVector &p1) const { dVector origin(matrix.TransformVector(m_boxOrigin)); dVector size(matrix.m_front.Abs().Scale(m_boxSize.m_x) + matrix.m_up.Abs().Scale(m_boxSize.m_y) + matrix.m_right.Abs().Scale(m_boxSize.m_z)); p0 = (origin - size) & dVector::m_triplexMask; p1 = (origin + size) & dVector::m_triplexMask; } //dInt32 ndShapeStaticMesh::CalculatePlaneIntersection(const dFloat32* const vertex, const dInt32* const index, dInt32 indexCount, dInt32 stride, const dPlane& localPlane, dVector* const contactsOut) const dInt32 ndShapeStaticMesh::CalculatePlaneIntersection(const dFloat32* const, const dInt32* const, dInt32, dInt32, const dPlane&, dVector* const) const { dAssert(0); return 0; //dInt32 count = 0; //dInt32 j = index[indexCount - 1] * stride; //dVector p0(&vertex[j]); //p0 = p0 & dVector::m_triplexMask; //dFloat32 side0 = localPlane.Evalue(p0); //for (dInt32 i = 0; i < indexCount; i++) { // j = index[i] * stride; // dVector p1(&vertex[j]); // p1 = p1 & dVector::m_triplexMask; // dFloat32 side1 = localPlane.Evalue(p1); // // if (side0 < dFloat32(0.0f)) { // if (side1 >= dFloat32(0.0f)) { // dVector dp(p1 - p0); // dAssert(dp.m_w == dFloat32(0.0f)); // dFloat32 t = localPlane.DotProduct(dp).GetScalar(); // dAssert(dgAbs(t) >= dFloat32(0.0f)); // if (dgAbs(t) < dFloat32(1.0e-8f)) { // t = dgSign(t) * dFloat32(1.0e-8f); // } // dAssert(0); // contactsOut[count] = p0 - dp.Scale(side0 / t); // count++; // // } // } // else if (side1 <= dFloat32(0.0f)) { // dVector dp(p1 - p0); // dAssert(dp.m_w == dFloat32(0.0f)); // dFloat32 t = localPlane.DotProduct(dp).GetScalar(); // dAssert(dgAbs(t) >= dFloat32(0.0f)); // if (dgAbs(t) < dFloat32(1.0e-8f)) { // t = dgSign(t) * dFloat32(1.0e-8f); // } // dAssert(0); // contactsOut[count] = p0 - dp.Scale(side0 / t); // count++; // } // // side0 = side1; // p0 = p1; //} // //return count; } void ndShapeStaticMesh::Save(const dLoadSaveBase::dSaveDescriptor& desc) const { nd::TiXmlElement* const childNode = new nd::TiXmlElement(ClassName()); desc.m_rootNode->LinkEndChild(childNode); childNode->SetAttribute("hashId", desc.m_nodeNodeHash); ndShape::Save(dLoadSaveBase::dSaveDescriptor(desc, childNode)); }
7,713
3,471
class LRG_ModuleVehicleCam: Module_F { scope = 2; displayName = "Add Vehicle Camera"; icon = "\z\LRG Fundamentals\addons\media\images\icons\Camera.paa"; category = "LRG_CommandCentre"; function = "LR_fnc_moduleVehicleCam"; functionPriority = 4; isGlobal = 0; isTriggerActivated = 0; isDisposable = 0; is3DEN = 0; class Attributes: AttributesBase { class ModuleDescription: ModuleDescription{}; }; class ModuleDescription: ModuleDescription { description[] = { "Synched vehicle can be viewed from the Command Center screens.", "You can sync as many vehicles to this module as you like." }; position = 0; // Position is taken into effect direction = 0; // Direction is taken into effect optional = 0; // Synced entity is optional duplicate = 1; // Multiple entities of this type can be synced }; };
836
292
/* Copyright 2001, 2019 IBM Corporation * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the * following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TTIMER_CLASS_H #define TTIMER_CLASS_H // typedef int bool; #include <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include <sys/time.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/dir.h> #include <fcntl.h> #include <assert.h> #include <sys/mman.h> #include <Ttypes.hpp> #include <Tdefs.hpp> #include <Tlib.hpp> class TTimer { public: TTimer(); ~TTimer(); void Start(); void Stop(); void DisplayDuration(char* Text); private: LTime StartTime; LTime StopTime; LTime Duration; }; #endif
1,944
730
/*Implement Insertion Sort*/ #include <iostream> using namespace std; void print(int a[],int n) { for(int i=0;i<n;i++) cout<<a[i]<<" "; } void Insertion_Sort(int a[],int n) { int key; for(int i=1;i<n;i++) { key=a[i]; int j=i-1; while(j>=0 && key<a[j]) { a[j+1]=a[j]; j--; } a[j+1]=key; } } int main() { int n; cout<<"Enter the size of Array:"; cin>>n; int a[n]; cout<<"Enter the values in Array"<<endl; for(int i=0;i<n;i++) cin>>a[i]; Insertion_Sort(a,n); print(a,n); return 0; }
540
283
#include "asuka.hpp" int main(void) { cout<<"starting up"<<endl; AT::Resource::Manager t; t.accept("/usr/lib/asuka/resource"); for(int i=0; i<10; i++) { AT::Field image = t.input("a24bit.tga"); cout<<"=["<<i<<"]============================"<<endl; cout<<"width: "<<image["header"]["width"]<<endl; cout<<"height: "<<image["header"]["height"]<<endl; cout<<"bpp: "<<image["header"]["bpp"]<<endl; t.release(image); } exit(0); }
469
192
#include <pcv/utils/benchmark_common.h> #include <cmath> namespace pcv { BenchmarkStats::BenchmarkStats(size_t LOOKUP_CNT, size_t real_rule_cnt, size_t trace_cnt, std::ostream &out) : LOOKUP_CNT(LOOKUP_CNT), out(out), construction_timer(nullptr), lookup_timer( nullptr), real_rule_cnt(real_rule_cnt), number_of_tries_or_tables( -1), ns_per_packet(trace_cnt) { std::fill(ns_per_packet.begin(), ns_per_packet.end(), 0); } void BenchmarkStats::construction_start() { construction_timer = new DebugTimer(); } void BenchmarkStats::construction_stop() { construction_timer->stop(); } void BenchmarkStats::lookup_packet_start() { actual_packet_start = std::chrono::high_resolution_clock::now(); } void BenchmarkStats::lookup_packet_stop(size_t p_id) { auto finish = std::chrono::high_resolution_clock::now(); std::chrono::duration<uint64_t, std::nano> t = finish - actual_packet_start; ns_per_packet[p_id] += t.count(); } void BenchmarkStats::lookup_start() { lookup_timer = new DebugTimer(); } void BenchmarkStats::lookup_stop() { lookup_timer->stop(); } void BenchmarkStats::set_number_of_tries_or_tables( int number_of_tries_or_tables) { this->number_of_tries_or_tables = number_of_tries_or_tables; } void BenchmarkStats::dump(std::function<void(std::ostream&)> json_extra, std::function<void(std::ostream&)> text_extra) { uint64_t lookup_time_from_packets = 0; for (auto t : ns_per_packet) lookup_time_from_packets += t; double lookup_speed; if (lookup_time_from_packets == 0) { // the packet time was not used at all lookup_speed = (double(LOOKUP_CNT) / lookup_timer->us()); } else { lookup_speed = ((LOOKUP_CNT / double(lookup_time_from_packets)) * 1000.0); } //out << lookup_time_from_packets << " " << lookup_timer->us() * 1000 << std::endl; //auto lookup_speed = (LOOKUP_CNT / double(lookup_timer->us())); if (std::isinf(lookup_speed)) lookup_speed = 0.0; // time can be lower than 1us and json can not contain inf out << "{ \"lookup_speed\":" << lookup_speed << "," << std::endl; // Mpkt/s auto overhead = (lookup_timer->us() * 1000 / double(lookup_time_from_packets)); if (std::isinf(overhead)) overhead = 0.0; out << "\"minimal_benchmark_overhead\":" << overhead << "," << std::endl; // (1 = zero overhead caused by precise timers) out << "\"construction_time\":" << uint64_t(construction_timer->us()) << "," // us << std::endl; out << "\"real_rule_cnt\":" << real_rule_cnt << "," << std::endl; out << "\"number_of_tries_or_tables\":" << number_of_tries_or_tables; bool all_zeros = true; for (auto t : ns_per_packet) { if (t != 0) { all_zeros = false; break; } } if (!all_zeros) { out << "," << std::endl << "\"packet_lookup_times\": [" << std::endl; for (size_t i = 0; i < ns_per_packet.size(); i++) { auto t = ns_per_packet[i]; out << t; // ns if (i != ns_per_packet.size() - 1) { out << ", "; } if ((i + 1) % 1024 == 0) out << std::endl; } out << "]" << std::endl; } json_extra(out); out << "}"; } BenchmarkStats::~BenchmarkStats() { delete construction_timer; delete lookup_timer; } }
3,122
1,279
#include <StftPitchShift/StftPitchShift.h> #include <StftPitchShift/FFT.h> #include <StftPitchShift/RFFT.h> #include <StftPitchShift/STFT.h> #include <StftPitchShift/StftPitchShiftCore.h> using namespace stftpitchshift; StftPitchShift::StftPitchShift( const size_t framesize, const size_t hopsize, const double samplerate, const bool normalization, const bool chronometry) : fft(std::make_shared<RFFT>()), framesize(framesize), hopsize(hopsize), samplerate(samplerate), normalization(normalization), chronometry(chronometry) { } StftPitchShift::StftPitchShift( const std::shared_ptr<FFT> fft, const size_t framesize, const size_t hopsize, const double samplerate, const bool normalization, const bool chronometry) : fft(fft), framesize(framesize), hopsize(hopsize), samplerate(samplerate), normalization(normalization), chronometry(chronometry) { } void StftPitchShift::shiftpitch( const std::vector<float>& input, std::vector<float>& output, const double factor, const double quefrency) { const std::vector<double> factors = { factor }; shiftpitch( input.size(), input.data(), output.data(), factors, quefrency); } void StftPitchShift::shiftpitch( const std::vector<double>& input, std::vector<double>& output, const double factor, const double quefrency) { const std::vector<double> factors = { factor }; shiftpitch( input.size(), input.data(), output.data(), factors, quefrency); } void StftPitchShift::shiftpitch( const size_t size, const float* input, float* const output, const double factor, const double quefrency) { const std::vector<double> factors = { factor }; shiftpitch( size, input, output, factors, quefrency); } void StftPitchShift::shiftpitch( const size_t size, const double* input, double* const output, const double factor, const double quefrency) { const std::vector<double> factors = { factor }; shiftpitch( size, input, output, factors, quefrency); } void StftPitchShift::shiftpitch( const std::vector<float>& input, std::vector<float>& output, const std::vector<double>& factors, const double quefrency) { shiftpitch( input.size(), input.data(), output.data(), factors, quefrency); } void StftPitchShift::shiftpitch( const std::vector<double>& input, std::vector<double>& output, const std::vector<double>& factors, const double quefrency) { shiftpitch( input.size(), input.data(), output.data(), factors, quefrency); } void StftPitchShift::shiftpitch( const size_t size, const float* input, float* const output, const std::vector<double>& factors, const double quefrency) { STFT<float> stft(fft, framesize, hopsize, chronometry); StftPitchShiftCore<float> core(fft, framesize, hopsize, samplerate); core.factors(factors); core.quefrency(quefrency); core.normalization(normalization); stft(size, input, output, [&](std::vector<std::complex<float>>& dft) { core.shiftpitch(dft); }); } void StftPitchShift::shiftpitch( const size_t size, const double* input, double* const output, const std::vector<double>& factors, const double quefrency) { STFT<double> stft(fft, framesize, hopsize, chronometry); StftPitchShiftCore<double> core(fft, framesize, hopsize, samplerate); core.factors(factors); core.quefrency(quefrency); core.normalization(normalization); stft(size, input, output, [&](std::vector<std::complex<double>>& dft) { core.shiftpitch(dft); }); }
3,597
1,302
/** * Copyright (C) 2012 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. */ #include "mongo/s/type_tags.h" #include "mongo/unittest/unittest.h" namespace { using std::string; using mongo::BSONObj; using mongo::TagsType; TEST(Validity, Valid) { TagsType tag; BSONObj obj = BSON(TagsType::ns("test.mycol") << TagsType::tag("tag") << TagsType::min(BSON("a" << 10)) << TagsType::max(BSON("a" << 20))); string errMsg; ASSERT(tag.parseBSON(obj, &errMsg)); ASSERT_EQUALS(errMsg, ""); ASSERT_TRUE(tag.isValid(NULL)); ASSERT_EQUALS(tag.getNS(), "test.mycol"); ASSERT_EQUALS(tag.getTag(), "tag"); ASSERT_EQUALS(tag.getMin(), BSON("a" << 10)); ASSERT_EQUALS(tag.getMax(), BSON("a" << 20)); } TEST(Validity, MissingFields) { TagsType tag; BSONObj objModNS = BSON(TagsType::tag("tag") << TagsType::min(BSON("a" << 10)) << TagsType::max(BSON("a" << 20))); string errMsg; ASSERT(tag.parseBSON(objModNS, &errMsg)); ASSERT_EQUALS(errMsg, ""); ASSERT_FALSE(tag.isValid(NULL)); BSONObj objModName = BSON(TagsType::ns("test.mycol") << TagsType::min(BSON("a" << 10)) << TagsType::max(BSON("a" << 20))); ASSERT(tag.parseBSON(objModName, &errMsg)); ASSERT_EQUALS(errMsg, ""); ASSERT_FALSE(tag.isValid(NULL)); BSONObj objModKeys = BSON(TagsType::ns("test.mycol") << TagsType::tag("tag")); ASSERT(tag.parseBSON(objModKeys, &errMsg)); ASSERT_EQUALS(errMsg, ""); ASSERT_FALSE(tag.isValid(NULL)); } TEST(MinMaxValidity, DifferentNumberOfColumns) { TagsType tag; BSONObj obj = BSON(TagsType::tag("tag") << TagsType::ns("test.mycol") << TagsType::min(BSON("a" << 10 << "b" << 10)) << TagsType::max(BSON("a" << 20))); string errMsg; ASSERT(tag.parseBSON(obj, &errMsg)); ASSERT_EQUALS(errMsg, ""); ASSERT_FALSE(tag.isValid(NULL)); } TEST(MinMaxValidity, DifferentColumns) { TagsType tag; BSONObj obj = BSON(TagsType::tag("tag") << TagsType::ns("test.mycol") << TagsType::min(BSON("a" << 10)) << TagsType::max(BSON("b" << 20))); string errMsg; ASSERT(tag.parseBSON(obj, &errMsg)); ASSERT_EQUALS(errMsg, ""); ASSERT_FALSE(tag.isValid(NULL)); } TEST(MinMaxValidity, NotAscending) { TagsType tag; BSONObj obj = BSON(TagsType::tag("tag") << TagsType::ns("test.mycol") << TagsType::min(BSON("a" << 20)) << TagsType::max(BSON("a" << 10))); string errMsg; ASSERT(tag.parseBSON(obj, &errMsg)); ASSERT_EQUALS(errMsg, ""); ASSERT_FALSE(tag.isValid(NULL)); } TEST(Validity, BadType) { TagsType tag; BSONObj obj = BSON(TagsType::tag() << 0); string errMsg; ASSERT((!tag.parseBSON(obj, &errMsg)) && (errMsg != "")); } } // unnamed namespace
4,852
1,575
#include <cstdio> #include <vector> #include <algorithm> typedef long long ll; bool check(const std::vector<ll> &sv, ll med, const ll budget){ ll left(0), right(0), sum(0); for(ll p = 0; p < sv.size(); p++){ if(sv[p].first < m){++left; sum += (sv[p].second > m) ? sv[p].second : m;} if(sv[p].first < m){++left; sum += (sv[p].second > m) ? sv[p].second : m;} } return ( } int main(){ ll t; scanf("%lld", &t); while(t--){ ll n, s; scanf("%lld %lld", &n, &s); std::vector<ll> vl(n), vr(n); std::vector<std::pair<ll, ll> > v(n); for(ll p = 0; p < n; p++){scanf("%lld %lld", &v[p].first, &v[p].second); vl[p] = v[p].first; vr[p] = v[p].second;} sort(vl.begin(), vl.end()); sort(vr.begin(), vr.end()); ll left(vl[n / 2]), right(vr[n / 2]); ll res(left); while(left <= right){ ll mid = (left + right) / 2; if(check(v, mid)){res = mid; left = mid + 1;} else{right = mid - 1;} } printf("%lld\n", res); } return 0; }
1,090
445
#include "node.hpp" int main() { //(20.0 + -10.0 ) * 0.1 node * p1 = new NumNode(20.0); node * p2 = new NumNode(-10.0); node * p3 = new AddNode(p1,p2); node * p4 = new NumNode(0.1); node * p5 = new MultNode(p3,p4); double x = p5->calc(); std::cout << x<<std::endl; delete p5; }
287
146
version https://git-lfs.github.com/spec/v1 oid sha256:03df42f0f44ce261f51089ffca63fb7aa5ce59ad275f40e295e6d8801e5a4d03 size 19831
130
90
// Copyright 2010-2018, Google Inc. // 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 Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "testing/base/public/googletest.h" #include "testing/base/public/gunit.h" #include "win32/ime/ime_types.h" #include "win32/ime/ime_ui_visibility_tracker.h" namespace mozc { namespace win32 { TEST(ImeUIVisibilityTrackerTest, BasicTest) { UIVisibilityTracker tracker; tracker.Initialize(); // At first, no window is visible because IME does not have input focus. EXPECT_FALSE(tracker.IsAnyWindowVisible()); // Notify the tracker that the IME is getting input focus. tracker.OnFocus(); // Suggest window is visible by default when the IME has input focus. EXPECT_TRUE(tracker.IsSuggestWindowVisible()); // Candidate window is not visible by default when the IME has input focus. EXPECT_FALSE(tracker.IsCandidateWindowVisible()); // Composition window is not visible by default when the IME has input focus. EXPECT_FALSE(tracker.IsCompositionWindowVisible()); // Notify the tracker of the UI visibility bits passed from the application // as lParam of WM_IME_SETCONTEXT. These bits update the visibility for // each UI component. // ISC_SHOWUIALL means that the application allows the IME to show all the UI // components. const ShowUIAttributes ui_attributes(ISC_SHOWUIALL); tracker.OnSetContext(ui_attributes); // WM_IME_SETCONTEXT/ISC_SHOWUIALL do not change the UI visibilities. EXPECT_TRUE(tracker.IsSuggestWindowVisible()); EXPECT_FALSE(tracker.IsCandidateWindowVisible()); EXPECT_FALSE(tracker.IsCompositionWindowVisible()); } // When a user changes the input method by the LangBar, WM_IME_SETCONTEXT will // not be sent. Even in this case, the suggest window should be visible by // default. TEST(ImeUIVisibilityTrackerTest, SuggestWindowShouldBeVisibleWhenImeIsChangedByLangBar) { UIVisibilityTracker tracker; tracker.Initialize(); // At first, no window is visible because IME does not have input focus. EXPECT_FALSE(tracker.IsAnyWindowVisible()); // Even when the input context has already got focus, |OnFocus| will be // called from ImeSelect. tracker.OnFocus(); // Suggest window is visible just after the IME is changed by the LangBar. EXPECT_TRUE(tracker.IsSuggestWindowVisible()); } // When a user changes the input method by the LangBar, WM_IME_SETCONTEXT will // not be sent. Even in this case, the composition window can be visible, // without any focus change, which finally invokes ImeSetActiveContext. TEST(ImeUIVisibilityTrackerTest, CompositionWindowCanBeShownWhenImeIsChangedByLangBar) { UIVisibilityTracker tracker; tracker.Initialize(); // At first, no window is visible because IME does not have input focus. EXPECT_FALSE(tracker.IsAnyWindowVisible()); // Even when the input context has already got focus, |OnFocus| will be // called from ImeSelect. tracker.OnFocus(); // Composition window is not visible by default after the IME is changed by // the LangBar. EXPECT_FALSE(tracker.IsCompositionWindowVisible()); // WM_IME_STARTCOMPOSITION should be marked as a visibility-test-message by // BeginVisibilityTestForCompositionWindow. EXPECT_TRUE( UIVisibilityTracker::IsVisibilityTestMessageForComposiwionWindow( WM_IME_STARTCOMPOSITION, 0, 0)); // Since WM_IME_STARTCOMPOSITION is a visibility-test-message, the IME calls // BeginVisibilityTestForCompositionWindow the message is posted. tracker.BeginVisibilityTestForCompositionWindow(); // If WM_IME_STARTCOMPOSITION is passed to the IME UI Window, the IME is // responsible to draw the composition window. tracker.OnStartComposition(); EXPECT_TRUE(tracker.IsCompositionWindowVisible()); } // When a user changes the input method by the LangBar, WM_IME_SETCONTEXT will // not be sent. Even in this case, the candiate window can be visible, // without any focus change, which finally invokes ImeSetActiveContext. TEST(ImeUIVisibilityTrackerTest, CandidateWindowCanBeShownWhenImeIsChangedByLangBar) { UIVisibilityTracker tracker; tracker.Initialize(); // At first, no window is visible because IME does not have input focus. EXPECT_FALSE(tracker.IsAnyWindowVisible()); // Even when the input context has already got focus, |OnFocus| will be // called from ImeSelect. tracker.OnFocus(); // Candidate window is not visible by default after the IME is changed by the // LangBar. EXPECT_FALSE(tracker.IsCandidateWindowVisible()); // Since WM_IME_NOTIFY/IMN_OPENCANDIDATE is a visibility-test-message, the // IME calls BeginVisibilityTestForCandidateWindow the message is // posted. tracker.BeginVisibilityTestForCandidateWindow(); // BeginVisibilityTestForCandidateWindow changes the visibility bit for // candidate window. However, it does not change the visibility bit for // suggestion window. EXPECT_FALSE(tracker.IsCandidateWindowVisible()); // If WM_IME_NOTIFY/IMN_OPENCANDIDATE is passed to the IME UI Window, the IME // is responsible to draw the candidate window. tracker.OnNotify(IMN_OPENCANDIDATE, 1); EXPECT_TRUE(tracker.IsCandidateWindowVisible()); } TEST(ImeUIVisibilityTrackerTest, HideSuggestWindowBySetInputContext) { UIVisibilityTracker tracker; tracker.Initialize(); // At first, no window is visible because IME does not have input focus. EXPECT_FALSE(tracker.IsAnyWindowVisible()); // Notify the tracker that the IME is getting input focus. tracker.OnFocus(); // Suggest window is visible by default when the IME has input focus. EXPECT_TRUE(tracker.IsSuggestWindowVisible()); // Candidate window is not visible by default when the IME has input focus. EXPECT_FALSE(tracker.IsCandidateWindowVisible()); // Composition window is not visible by default when the IME has input focus. EXPECT_FALSE(tracker.IsCompositionWindowVisible()); // Suggest window should be visible if all the candidate windows are visible. // You may see this situation in Chrome, as reported in b/3002445. tracker.OnSetContext(ShowUIAttributes(ISC_SHOWUIALLCANDIDATEWINDOW)); // Suggest window should be visible. EXPECT_TRUE(tracker.IsSuggestWindowVisible()); // Suggest window should be invisible if none of the bits in // ISC_SHOWUIALLCANDIDATEWINDOW is cleared, where ISC_SHOWUICANDIDATEWINDOW // means that the first candidate window can be shown but the others must be // invisible. tracker.OnSetContext(ShowUIAttributes(ISC_SHOWUICANDIDATEWINDOW)); // Suggest window should be invisible. EXPECT_FALSE(tracker.IsSuggestWindowVisible()); } TEST(ImeUIVisibilityTrackerTest, CompositionIsDrawnByIME) { UIVisibilityTracker tracker; tracker.Initialize(); // Notify the tracker that the IME is getting input focus. tracker.OnFocus(); // Notify the tracker of the UI visibility bits passed from the application // as lParam of WM_IME_SETCONTEXT. These bits update the visibility for // each UI component. const ShowUIAttributes ui_attributes(ISC_SHOWUIALL); tracker.OnSetContext(ui_attributes); // WM_IME_STARTCOMPOSITION should be marked as a visibility-test-message by // BeginVisibilityTestForCompositionWindow. EXPECT_TRUE( UIVisibilityTracker::IsVisibilityTestMessageForComposiwionWindow( WM_IME_STARTCOMPOSITION, 0, 0)); // Since WM_IME_STARTCOMPOSITION is a visibility-test-message, the IME calls // BeginVisibilityTestForCompositionWindow the message is posted. tracker.BeginVisibilityTestForCompositionWindow(); // BeginVisibilityTestForCompositionWindow changes the visibility bit for // composition window. EXPECT_FALSE(tracker.IsCompositionWindowVisible()); // If WM_IME_STARTCOMPOSITION is passed to the IME UI Window, the IME is // responsible to draw the composition window. tracker.OnStartComposition(); EXPECT_TRUE(tracker.IsCompositionWindowVisible()); // UIVisibilityTracker ignores these bits though. const DWORD kCompositionUpdateBits = (GCS_COMPREADSTR | GCS_COMPREADATTR | GCS_COMPREADCLAUSE | GCS_COMPSTR | GCS_COMPATTR | GCS_COMPCLAUSE | GCS_CURSORPOS | GCS_DELTASTART); // WM_IME_COMPOSITION should be marked as a visibility-test-message by // BeginVisibilityTestForCompositionWindow. EXPECT_TRUE( UIVisibilityTracker::IsVisibilityTestMessageForComposiwionWindow( WM_IME_COMPOSITION, 0, kCompositionUpdateBits)); // Since WM_IME_COMPOSITION is a visibility-test-message, the IME calls // BeginVisibilityTestForCompositionWindow the message is posted. tracker.BeginVisibilityTestForCompositionWindow(); // BeginVisibilityTestForCompositionWindow changes the visibility bit for // composition window. EXPECT_FALSE(tracker.IsCompositionWindowVisible()); // If the IME UI Window receives WM_IME_COMPOSITION, the IME is responsible // to draw the composition window. tracker.OnComposition(); EXPECT_TRUE(tracker.IsCompositionWindowVisible()); // WM_IME_ENDCOMPOSITION should be marked as a visibility-test-message by // BeginVisibilityTestForCompositionWindow. EXPECT_TRUE( UIVisibilityTracker::IsVisibilityTestMessageForComposiwionWindow( WM_IME_ENDCOMPOSITION, 0, 0)); // Since WM_IME_ENDCOMPOSITION is a visibility-test-message, the IME calls // BeginVisibilityTestForCompositionWindow the message is posted. tracker.BeginVisibilityTestForCompositionWindow(); // BeginVisibilityTestForCompositionWindow changes the visibility bit for // composition window. EXPECT_FALSE(tracker.IsCompositionWindowVisible()); // WM_IME_ENDCOMPOSITION makes the composition window invisible either way. tracker.OnEndComposition(); EXPECT_FALSE(tracker.IsCompositionWindowVisible()); } TEST(ImeUIVisibilityTrackerTest, CompositionIsDrawnByApplication) { UIVisibilityTracker tracker; tracker.Initialize(); // Notify the tracker that the IME is getting input focus. tracker.OnFocus(); // Notify the tracker of the UI visibility bits passed from the application // as lParam of WM_IME_SETCONTEXT. These bits update the visibility for // each UI component. // Some applications such as GTK applications or OOo does not clear the UI // visibility bits even though they draw their own composition windows. // We conform with those applications. const ShowUIAttributes ui_attributes(ISC_SHOWUIALL); tracker.OnSetContext(ui_attributes); // WM_IME_STARTCOMPOSITION should be marked as a visibility-test-message by // BeginVisibilityTestForCompositionWindow. EXPECT_TRUE( UIVisibilityTracker::IsVisibilityTestMessageForComposiwionWindow( WM_IME_STARTCOMPOSITION, 0, 0)); // Since WM_IME_STARTCOMPOSITION is a visibility-test-message, the IME calls // BeginVisibilityTestForCompositionWindow the message is posted. tracker.BeginVisibilityTestForCompositionWindow(); // BeginVisibilityTestForCompositionWindow changes the visibility bit for // composition window. // If WM_IME_STARTCOMPOSITION is not passed to the IME UI Window, the // application is responsible to draw the composition window. EXPECT_FALSE(tracker.IsCompositionWindowVisible()); // UIVisibilityTracker ignores these bits though. const DWORD kCompositionUpdateBits = (GCS_COMPREADSTR | GCS_COMPREADATTR | GCS_COMPREADCLAUSE | GCS_COMPSTR | GCS_COMPATTR | GCS_COMPCLAUSE | GCS_CURSORPOS | GCS_DELTASTART); // WM_IME_COMPOSITION should be marked as a visibility-test-message by // BeginVisibilityTestForCompositionWindow. EXPECT_TRUE( UIVisibilityTracker::IsVisibilityTestMessageForComposiwionWindow( WM_IME_COMPOSITION, 0, kCompositionUpdateBits)); // Since WM_IME_COMPOSITION is a visibility-test-message, the IME calls // BeginVisibilityTestForCompositionWindow the message is posted. tracker.BeginVisibilityTestForCompositionWindow(); // BeginVisibilityTestForCompositionWindow changes the visibility bit for // composition window. // If WM_IME_COMPOSITION is not passed to the IME UI Window, the application // is responsible to draw the composition window. EXPECT_FALSE(tracker.IsCompositionWindowVisible()); // WM_IME_ENDCOMPOSITION should be marked as a visibility-test-message by // BeginVisibilityTestForCompositionWindow. EXPECT_TRUE( UIVisibilityTracker::IsVisibilityTestMessageForComposiwionWindow( WM_IME_ENDCOMPOSITION, 0, 0)); // Since WM_IME_ENDCOMPOSITION is a visibility-test-message, the IME calls // BeginVisibilityTestForCompositionWindow the message is posted. tracker.BeginVisibilityTestForCompositionWindow(); // BeginVisibilityTestForCompositionWindow changes the visibility bit for // composition window. // WM_IME_ENDCOMPOSITION makes the composition window invisible either way. EXPECT_FALSE(tracker.IsCompositionWindowVisible()); } TEST(ImeUIVisibilityTrackerTest, CandidateIsDrawnByIME) { UIVisibilityTracker tracker; tracker.Initialize(); // Notify the tracker that the IME is getting input focus. tracker.OnFocus(); // Notify the tracker of the UI visibility bits passed from the application // as lParam of WM_IME_SETCONTEXT. These bits update the visibility for // each UI component. const ShowUIAttributes ui_attributes(ISC_SHOWUIALL); tracker.OnSetContext(ui_attributes); // IMN_OPENCANDIDATE should be marked as a visibility-test-message by // IsVisibilityTestMessageForCandidateWindow. EXPECT_TRUE( UIVisibilityTracker::IsVisibilityTestMessageForCandidateWindow( WM_IME_NOTIFY, IMN_OPENCANDIDATE, 1)); // Since WM_IME_NOTIFY/IMN_OPENCANDIDATE is a visibility-test-message, the // IME calls BeginVisibilityTestForCandidateWindow the message is // posted. tracker.BeginVisibilityTestForCandidateWindow(); // BeginVisibilityTestForCandidateWindow changes the visibility bit for // candidate window. However, it does not change the visibility bit for // suggestion window. EXPECT_FALSE(tracker.IsCandidateWindowVisible()); EXPECT_TRUE(tracker.IsSuggestWindowVisible()); // If WM_IME_NOTIFY/IMN_OPENCANDIDATE is passed to the IME UI Window, the IME // is responsible to draw the candidate window. tracker.OnNotify(IMN_OPENCANDIDATE, 1); EXPECT_TRUE(tracker.IsCandidateWindowVisible()); // WM_IME_NOTIFY/IMN_CHANGECANDIDATE is not marked as a visibility-test- // message by IsVisibilityTestMessageForCandidateWindow. EXPECT_FALSE( UIVisibilityTracker::IsVisibilityTestMessageForCandidateWindow( WM_IME_NOTIFY, IMN_CHANGECANDIDATE, 1)); // WM_IME_NOTIFY/IMN_CLOSECANDIDATE is not marked as a visibility-test- // message by IsVisibilityTestMessageForCandidateWindow. EXPECT_TRUE( UIVisibilityTracker::IsVisibilityTestMessageForCandidateWindow( WM_IME_NOTIFY, IMN_CLOSECANDIDATE, 1)); // Since WM_IME_NOTIFY/IMN_CLOSECANDIDATE is a visibility-test-message, the // IME calls BeginVisibilityTestForCandidateWindow the message is // posted. tracker.BeginVisibilityTestForCandidateWindow(); // BeginVisibilityTestForCandidateWindow changes the visibility bit for // candidate window. EXPECT_FALSE(tracker.IsCandidateWindowVisible()); // WM_IME_NOTIFY/IMN_CLOSECANDIDATE makes the candidate window invisible // either way. tracker.OnNotify(IMN_CLOSECANDIDATE, 1); EXPECT_FALSE(tracker.IsCandidateWindowVisible()); } TEST(ImeUIVisibilityTrackerTest, CandidateIsDrawnByApplication) { UIVisibilityTracker tracker; tracker.Initialize(); // Notify the tracker that the IME is getting input focus. tracker.OnFocus(); // Notify the tracker of the UI visibility bits passed from the application // as lParam of WM_IME_SETCONTEXT. These bits update the visibility for // each UI component. // Some game applications might not clear the UI visibility bits even though // they draw their own candidate windows. // We conform with those applications. const ShowUIAttributes ui_attributes(ISC_SHOWUIALL); tracker.OnSetContext(ui_attributes); // IMN_OPENCANDIDATE should be marked as a visibility-test-message by // IsVisibilityTestMessageForCandidateWindow. EXPECT_TRUE( UIVisibilityTracker::IsVisibilityTestMessageForCandidateWindow( WM_IME_NOTIFY, IMN_OPENCANDIDATE, 1)); // Since WM_IME_NOTIFY/IMN_OPENCANDIDATE is a visibility-test-message, the // IME calls BeginVisibilityTestForCandidateWindow before the message is // posted. tracker.BeginVisibilityTestForCandidateWindow(); // BeginVisibilityTestForCandidateWindow changes the visibility bit for // candidate window. However, it does not change the visibility bit for // suggestion window. // If WM_IME_NOTIFY/IMN_OPENCANDIDATE is not passed to the IME UI Window, the // application is responsible to draw the candidate window. EXPECT_FALSE(tracker.IsCandidateWindowVisible()); EXPECT_TRUE(tracker.IsSuggestWindowVisible()); // WM_IME_NOTIFY/IMN_CHANGECANDIDATE is not marked as a visibility-test- // message by IsVisibilityTestMessageForCandidateWindow. EXPECT_FALSE( UIVisibilityTracker::IsVisibilityTestMessageForCandidateWindow( WM_IME_NOTIFY, IMN_CHANGECANDIDATE, 1)); // WM_IME_NOTIFY/IMN_CLOSECANDIDATE is not marked as a visibility-test- // message by IsVisibilityTestMessageForCandidateWindow. EXPECT_TRUE( UIVisibilityTracker::IsVisibilityTestMessageForCandidateWindow( WM_IME_NOTIFY, IMN_CLOSECANDIDATE, 1)); // Since WM_IME_NOTIFY/IMN_CLOSECANDIDATE is a visibility-test-message, the // IME calls BeginVisibilityTestForCandidateWindow before the message is // posted. // WM_IME_NOTIFY/IMN_CLOSECANDIDATE makes the candidate window invisible // either way. tracker.BeginVisibilityTestForCandidateWindow(); EXPECT_FALSE(tracker.IsCandidateWindowVisible()); } // Some applications such as gvim 7.3.55, Notepad++ 5.8.4 (Scintilla 2.22), // EmEditor 10.0.4, do not pass WM_IME_COMPOSITION message to ::DefWindowProc // when |lParam| contains GCS_RESULTSTR flag. (b/3223935) TEST(ImeUIVisibilityTrackerTest, Issue3223935_WM_IME_COMPOSITION_IsEatenIfItContainsResultString) { UIVisibilityTracker tracker; tracker.Initialize(); // Notify the tracker that the IME is getting input focus. tracker.OnFocus(); // Notify the tracker of the UI visibility bits passed from the application // as lParam of WM_IME_SETCONTEXT. These bits update the visibility for // each UI component. // Some game applications might not clear the UI visibility bits even though // they draw their own candidate windows. // We conform with those applications. const ShowUIAttributes ui_attributes(ISC_SHOWUIALL); tracker.OnSetContext(ui_attributes); // WM_IME_STARTCOMPOSITION should be marked as a visibility-test-message by // BeginVisibilityTestForCompositionWindow. EXPECT_TRUE( UIVisibilityTracker::IsVisibilityTestMessageForComposiwionWindow( WM_IME_STARTCOMPOSITION, 0, 0)); // Since WM_IME_STARTCOMPOSITION is a visibility-test-message, the IME calls // BeginVisibilityTestForCompositionWindow the message is posted. tracker.BeginVisibilityTestForCompositionWindow(); // If WM_IME_STARTCOMPOSITION is passed to the IME UI Window, the IME is // responsible to draw the composition window. tracker.OnStartComposition(); EXPECT_TRUE(tracker.IsCompositionWindowVisible()); // |lParam| contains GCS_RESULTSTR. Do not use WM_IME_COMPOSITION as a // visibility-test-message in this case. EXPECT_FALSE( UIVisibilityTracker::IsVisibilityTestMessageForCandidateWindow( WM_IME_COMPOSITION, 0, GCS_RESULTSTR)); // |lParam| contains GCS_RESULTSTR. Do not use WM_IME_COMPOSITION as a // visibility-test-message in this case. EXPECT_FALSE( UIVisibilityTracker::IsVisibilityTestMessageForCandidateWindow( WM_IME_COMPOSITION, 0, GCS_COMPSTR | GCS_RESULTSTR)); // Composition Window should be visible. EXPECT_TRUE(tracker.IsCompositionWindowVisible()); } } // namespace win32 } // namespace mozc
21,460
6,605
/*++ Copyright (c) 2005 Microsoft Corporation All rights reserved. THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. File Name: bkflt.cpp Abstract: Booklet filter implementation. This class derives from the Xps filter class and implements the necessary part handlers to support booklet printing. The booklet filter is responsible for re-ordering pages and re-uses the NUp filter to provide 2-up and offset support. --*/ #include "precomp.h" #include "debug.h" #include "globals.h" #include "xdstring.h" #include "xdexcept.h" #include "pthndlr.h" #include "bkflt.h" #include "bksax.h" #include "bkpthndlr.h" using XDPrintSchema::Binding::BindingData; /*++ Routine Name: CBookletFilter::CBookletFilter Routine Description: Default constructor for the booklet filter which initialises the filter to sensible default values Arguments: None Return Value: None --*/ CBookletFilter::CBookletFilter() : m_bSendAllDocs(TRUE), m_bookScope(CBkPTProperties::None) { } /*++ Routine Name: CBookletFilter::~CBookletFilter Routine Description: Default destructor for the booklet filter Arguments: None Return Value: None --*/ CBookletFilter::~CBookletFilter() { } /*++ Routine Name: CNUpFilter::ProcessPart Routine Description: Method for processing each fixed document sequence part in a container Arguments: pFDS - Pointer to the fixed document sequence to process Return Value: HRESULT S_OK - On success E_* - On error --*/ HRESULT CBookletFilter::ProcessPart( _Inout_ IFixedDocumentSequence* pFDS ) { VERBOSE("Processing Fixed Document Sequence part with booklet filter handler\n"); HRESULT hr = S_OK; if (SUCCEEDED(hr = CHECK_POINTER(pFDS, E_POINTER))) { // // Get the PT manager to return the FixedDocumentSequence ticket. // IXMLDOMDocument2* pPT = NULL; if (SUCCEEDED(hr = m_ptManager.SetTicket(pFDS)) && SUCCEEDED(hr = m_ptManager.GetTicket(kPTJobScope, &pPT))) { // // Set the binding scope from the PrintTicket // hr = SetBindingScope(pPT); } } if (SUCCEEDED(hr)) { hr = m_pXDWriter->SendFixedDocumentSequence(pFDS); } ERR_ON_HR(hr); return hr; } /*++ Routine Name: CBookletFilter::ProcessPart Routine Description: Method for processing each fixed document part in a container Arguments: pFD - Pointer to the fixed document to process Return Value: HRESULT S_OK - On success S_FALSE - When not enabled in the PT E_* - On error --*/ HRESULT CBookletFilter::ProcessPart( _Inout_ IFixedDocument* pFD ) { VERBOSE("Processing Fixed Document part with booklet filter handler\n"); HRESULT hr = S_OK; if (SUCCEEDED(hr = CHECK_POINTER(pFD, E_POINTER)) && SUCCEEDED(hr = m_ptManager.SetTicket(pFD))) { // // If we are in a JobBook session we want to maintain the current // JobBook settings // if (m_bookScope != CBkPTProperties::Job) { // // Flush any outstanding pages in case we have just completed a // DocNUp sequence // hr = FlushCache(); // // Get the PT manager to return the FixedDocument ticket. // IXMLDOMDocument2* pPT = NULL; if (SUCCEEDED(hr) && SUCCEEDED(hr = m_ptManager.GetTicket(kPTDocumentScope, &pPT))) { // // Set the binding scope from the PrintTicket // hr = SetBindingScope(pPT); } } } if (SUCCEEDED(hr) && m_bSendAllDocs) { hr = m_pXDWriter->SendFixedDocument(pFD); // // If we are JobBindAllDocuments we only ever send one doc - now we have // sent the first document we can test to see if we need to send all of them // if (m_bookScope == CBkPTProperties::Job) { m_bSendAllDocs = FALSE; } } ERR_ON_HR(hr); return hr; } /*++ Routine Name: CBookletFilter::ProcessPart Routine Description: Method for processing each fixed page part in a container Arguments: pFP - Pointer to the fixed page to process Return Value: HRESULT S_OK - On success E_* - On error --*/ HRESULT CBookletFilter::ProcessPart( _Inout_ IFixedPage* pFP ) { ASSERTMSG(m_pXDWriter != NULL, "XD writer is not initialised.\n"); VERBOSE("Processing Fixed Page with booklet filter handler\n"); HRESULT hr = S_OK; if (SUCCEEDED(hr = CHECK_POINTER(pFP, E_POINTER)) && SUCCEEDED(hr = CHECK_POINTER(m_pXDWriter, E_PENDING))) { // // Check if we are processing a booklet job // if (m_bookScope != CBkPTProperties::None) { // // Cache pages for reordering // try { m_cacheFP.push_back(pFP); } catch (exception& DBG_ONLY(e)) { ERR(e.what()); hr = E_FAIL; } } else { hr = m_pXDWriter->SendFixedPage(pFP); } } ERR_ON_HR(hr); return hr; } /*++ Routine Name: CBookletFilter::Finalize Routine Description: Method to flush the cache of pages as the last action of the filter Arguments: None Return Value: HRESULT S_OK - On success E_* - On error --*/ HRESULT CBookletFilter::Finalize( VOID ) { // // Just flush the cache of pages // return FlushCache(); } /*++ Routine Name: CBookletFilter::FlushCache Routine Description: Method to send the cached collection of pages in the correct order back Arguments: None Return Value: HRESULT S_OK - On success E_* - On error --*/ HRESULT CBookletFilter::FlushCache( VOID ) { HRESULT hr = S_OK; if (m_pXDWriter == NULL) { hr = E_PENDING; } size_t cPages = m_cacheFP.size(); if (SUCCEEDED(hr) && cPages > 0 && m_bookScope != CBkPTProperties::None) { // // We may need to add a pad page if the page count is odd // CComPtr<IFixedPage> pNewFP(NULL); if (cPages%2 == 1 && SUCCEEDED(hr = CreatePadPage(&pNewFP))) { // // We successfully created our pad page; add it to the cache // try { m_cacheFP.push_back(pNewFP); } catch (exception& DBG_ONLY(e)) { ERR(e.what()); hr = E_FAIL; } cPages++; } if (SUCCEEDED(hr)) { try { // // Re-order pages in the cache // map<size_t, IFixedPage*> reorderedPages; size_t newIndex = 0; size_t pageIndex = 0; for (pageIndex = 0; pageIndex < cPages/2; pageIndex++) { reorderedPages[newIndex] = m_cacheFP[pageIndex]; newIndex += 2; } newIndex = cPages - 1; for (pageIndex = cPages/2; pageIndex < cPages; pageIndex++) { reorderedPages[newIndex] = m_cacheFP[pageIndex]; newIndex -= 2; } // // Write out reordered pages // for (pageIndex = 0; pageIndex < cPages && SUCCEEDED(hr); pageIndex++) { hr = m_pXDWriter->SendFixedPage(reorderedPages[pageIndex]); } // // Clean out the cache // m_cacheFP.clear(); } catch (exception& DBG_ONLY(e)) { ERR(e.what()); hr = E_FAIL; } } } ERR_ON_HR(hr); return hr; } /*++ Routine Name: CBookletFilter::CreatePadPage Routine Description: Method to create a pad page which is required for odd page counts to ensure pages are correctly ordered for presentation as a booklet Arguments: ppNewPage - Pointer to a pointer to the newly created fixed page Return Value: HRESULT S_OK - On success E_* - On error --*/ HRESULT CBookletFilter::CreatePadPage( _Outptr_ IFixedPage** ppNewPage ) { HRESULT hr = S_OK; // // Validate parameters and members before proceeding // if (SUCCEEDED(hr = CHECK_POINTER(ppNewPage, E_POINTER)) && SUCCEEDED(hr = CHECK_POINTER(m_pXDWriter, E_PENDING))) { *ppNewPage = NULL; PCWSTR pszPageName = NULL; try { // // Create a unique name for the pad page for this print session // CStringXDW szNewPageName; szNewPageName.Format(L"/Pad_page_%u.xaml", GetUniqueNumber()); pszPageName = szNewPageName.GetBuffer(); // // Create a new empty page and retrieve a writer. Also get a // reader from the first page so we can copy the FixedPage root // element. This ensures the page sizes match. // CComPtr<IPrintWriteStream> pWriter(NULL); CComPtr<ISAXXMLReader> pSaxRdr(NULL); if (SUCCEEDED(hr) && SUCCEEDED(hr = m_pXDWriter->GetNewEmptyPart(pszPageName, IID_IFixedPage, reinterpret_cast<PVOID*>(ppNewPage), &pWriter)) && SUCCEEDED(hr = pSaxRdr.CoCreateInstance(CLSID_SAXXMLReader60))) { // // We use a simple SAX handler which copies only the root // element and discards all other content. // CBkSaxHandler bkSaxHndlr(pWriter); CComPtr<IPrintReadStream> pReader(NULL); IFixedPage* pFP = NULL; pFP = m_cacheFP[0]; if (SUCCEEDED(hr) && SUCCEEDED(hr = pSaxRdr->putContentHandler(&bkSaxHndlr)) && SUCCEEDED(hr = pFP->GetStream(&pReader))) { CComPtr<ISequentialStream> pReadStreamToSeq(NULL); pReadStreamToSeq.Attach(new(std::nothrow) pfp::PrintReadStreamToSeqStream(pReader)); if (SUCCEEDED(hr = CHECK_POINTER(pReadStreamToSeq, E_OUTOFMEMORY))) { hr = pSaxRdr->parse(CComVariant(static_cast<ISequentialStream*>(pReadStreamToSeq))); } } pWriter->Close(); } } catch (CXDException& e) { hr = e; } } ERR_ON_HR(hr); return hr; } /*++ Routine Name: CBookletFilter::SetBindingScope Routine Description: Method to retrieve the binding scope from a PrintTicket Arguments: pPT - Pointer to the PrintTicket to retrieve the scope from Return Value: HRESULT S_OK - On success S_FALSE - Booklet settings not present in the PT E_* - On error --*/ HRESULT CBookletFilter::SetBindingScope( _In_ IXMLDOMDocument2* pPT ) { HRESULT hr = S_OK; if (SUCCEEDED(hr = CHECK_POINTER(pPT, E_POINTER))) { try { BindingData bindingData; CBookPTHandler bkPTHandler(pPT); // // Retrieve the booklet properties from the ticket via the handler // if (SUCCEEDED(hr) && SUCCEEDED(hr = bkPTHandler.GetData(&bindingData))) { CBkPTProperties bookletPTProps(bindingData); // // Retrieve the booklet scope // hr = bookletPTProps.GetScope(&m_bookScope); } else if (hr == E_ELEMENT_NOT_FOUND) { // // Booklet PT settings are not present - reset hr to S_FALSE and proceed // hr = S_FALSE; } } catch (CXDException& e) { hr = e; } } return hr; }
13,406
4,429
//---------------------------------Spheral++----------------------------------// // ArtificialViscosity -- The base class for all ArtificialViscosities in // Spheral++. //----------------------------------------------------------------------------// #include "FileIO/FileIO.hh" #include "Hydro/HydroFieldNames.hh" #include "Boundary/Boundary.hh" #include "Kernel/TableKernel.hh" #include "NodeList/FluidNodeList.hh" #include "DataBase/State.hh" #include "DataBase/StateDerivatives.hh" #include "Neighbor/ConnectivityMap.hh" #include "Utilities/rotationMatrix.hh" #include "Utilities/GeometricUtilities.hh" #include "RK/RKFieldNames.hh" #include "RK/gradientRK.hh" #include "TensorCRKSPHViscosity.hh" #include <algorithm> using std::vector; using std::string; using std::pair; using std::make_pair; using std::cout; using std::cerr; using std::endl; using std::min; using std::max; using std::abs; namespace Spheral { //------------------------------------------------------------------------------ // Construct with the given value for the linear and quadratic coefficients. //------------------------------------------------------------------------------ template<typename Dimension> TensorCRKSPHViscosity<Dimension>:: TensorCRKSPHViscosity(Scalar Clinear, Scalar Cquadratic): TensorMonaghanGingoldViscosity<Dimension>(Clinear, Cquadratic), mGradVel(FieldStorageType::CopyFields){ } //------------------------------------------------------------------------------ // Destructor. //------------------------------------------------------------------------------ template<typename Dimension> TensorCRKSPHViscosity<Dimension>:: ~TensorCRKSPHViscosity() { } //------------------------------------------------------------------------------ // Method to apply the viscous acceleration, work, and pressure, to the derivatives // all in one step (efficiency and all). //------------------------------------------------------------------------------ template<typename Dimension> pair<typename Dimension::Tensor, typename Dimension::Tensor> TensorCRKSPHViscosity<Dimension>:: Piij(const unsigned nodeListi, const unsigned i, const unsigned nodeListj, const unsigned j, const Vector& xi, const Vector& etai, const Vector& vi, const Scalar rhoi, const Scalar csi, const SymTensor& /*Hi*/, const Vector& xj, const Vector& etaj, const Vector& vj, const Scalar rhoj, const Scalar csj, const SymTensor& /*Hj*/) const { // Estimate the velocity difference. Vector vij = vi - vj; const Vector xij = xi - xj; const Tensor& DvDxi = mGradVel(nodeListi, i); const Tensor& DvDxj = mGradVel(nodeListj, j); const Vector vi1 = vi - 0.5*(DvDxi.dot(xij)); const Vector vj1 = vj + 0.5*(DvDxj.dot(xij)); const Vector vij1 = vi1 - vj1; if (((vi1 - vj).dot(vij) > 0.0) and ((vi - vj1).dot(vij) > 0.0) and (vij1.dot(vij) > 0.0)) { const Vector vijhat = vij.unitVector(); // const bool barf = (vij.magnitude() > 1.0e-5); // if (barf) cerr << "Cutting vij from " << vij << " to "; vij = min(vij.magnitude(), vij1.magnitude())*vijhat; // if (barf) cerr << vij << endl; } // If the nodes are not closing, then skip the rest and the Q is zero. if (vij.dot(xij) < 0.0) { const double tiny = 1.0e-20; double Cl = this->mClinear; double Cq = this->mCquadratic; const double eps2 = this->mEpsilon2; //const bool balsara = this->mBalsaraShearCorrection; const bool limiter = this->mLimiterSwitch; // Grab the FieldLists scaling the coefficients. // These incorporate things like the Balsara shearing switch or Morris & Monaghan time evolved // coefficients. const Scalar fCli = this->mClMultiplier(nodeListi, i); const Scalar fCqi = this->mCqMultiplier(nodeListi, i); const Scalar fClj = this->mClMultiplier(nodeListj, j); const Scalar fCqj = this->mCqMultiplier(nodeListj, j); const Scalar fshear = std::max(this->mShearCorrection(nodeListi, i), this->mShearCorrection(nodeListj, j)); Cl *= 0.5*(fCli + fClj)*fshear; Cq *= 0.5*(fCqi + fCqj)*fshear; // Some more geometry. const Scalar xij2 = xij.magnitude2(); const Vector xijUnit = xij.unitVector(); const Scalar hi2 = xij2/(etai.magnitude2() + tiny); const Scalar hj2 = xij2/(etaj.magnitude2() + tiny); const Scalar hi = sqrt(hi2); const Scalar hj = sqrt(hj2); // BOOGA! const Tensor& _sigmai = this->mSigma(nodeListi, i); const Tensor& _sigmaj = this->mSigma(nodeListj, j); Tensor sigmai = _sigmai; Tensor sigmaj = _sigmaj; { const Tensor R = rotationMatrix(xijUnit); const Tensor Rinverse = R.Transpose(); const Vector thpt1 = sqrt(xij2)*(R*vij); const Vector deltaSigmai = thpt1/(xij2 + eps2*hi2); const Vector deltaSigmaj = thpt1/(xij2 + eps2*hj2); sigmai.rotationalTransform(R); sigmaj.rotationalTransform(R); sigmai.setColumn(0, deltaSigmai); sigmaj.setColumn(0, deltaSigmaj); sigmai.rotationalTransform(Rinverse); sigmaj.rotationalTransform(Rinverse); } // BOOGA! // Calculate the tensor viscous internal energy. const Tensor mui = hi*sigmai; Tensor Qepsi = -Cl*csi*mui.Transpose() + Cq*mui*mui; if (limiter) Qepsi = this->calculateLimiter(vi, vj, csi, csj, hi, hj, nodeListi, i)*Qepsi; const Tensor muj = hj*sigmaj; Tensor Qepsj = -Cl*csj*muj.Transpose() + Cq*muj*muj; if (limiter) Qepsj = this->calculateLimiter(vj, vi, csj, csi, hj, hi, nodeListj, j)*Qepsj; // We now have enough to compute Pi! const Tensor QPii = Qepsi/rhoi; const Tensor QPij = Qepsj/rhoj; return make_pair(QPii, QPij); } else { return make_pair(Tensor::zero, Tensor::zero); } } //------------------------------------------------------------------------------ // Compute the internal background sigma and grad-div-v fields. //------------------------------------------------------------------------------ template<typename Dimension> void TensorCRKSPHViscosity<Dimension>:: calculateSigmaAndGradDivV(const DataBase<Dimension>& dataBase, const State<Dimension>& state, const StateDerivatives<Dimension>& /*derivs*/, const TableKernel<Dimension>& /*W*/, typename TensorCRKSPHViscosity<Dimension>::ConstBoundaryIterator boundaryBegin, typename TensorCRKSPHViscosity<Dimension>::ConstBoundaryIterator boundaryEnd) { const auto order = ArtificialViscosity<Dimension>::QcorrectionOrder(); auto& sigma = ArtificialViscosity<Dimension>::mSigma; auto& gradDivVelocity = ArtificialViscosity<Dimension>::mGradDivVelocity; // Get the necessary state. const auto mass = state.fields(HydroFieldNames::mass, 0.0); const auto position = state.fields(HydroFieldNames::position, Vector::zero); const auto velocity = state.fields(HydroFieldNames::velocity, Vector::zero); const auto rho = state.fields(HydroFieldNames::massDensity, 0.0); const auto H = state.fields(HydroFieldNames::H, SymTensor::zero); const auto WR = state.template getAny<ReproducingKernel<Dimension>>(RKFieldNames::reproducingKernel(order)); const auto corrections = state.fields(RKFieldNames::rkCorrections(order), RKCoefficients<Dimension>()); const auto& connectivityMap = dataBase.connectivityMap(); const auto numNodeLists = dataBase.numFluidNodeLists(); // Compute the basic velocity gradient. const auto vol = mass/rho; mGradVel = gradientRK(velocity, position, vol, H, connectivityMap, WR, corrections, NodeCoupling()); sigma = mGradVel; sigma.copyFields(); // Compute sigma and build the velocity divergence. auto divVel = dataBase.newFluidFieldList(0.0, "velocity divergence"); for (auto nodeListi = 0u; nodeListi != numNodeLists; ++nodeListi) { for (auto iItr = connectivityMap.begin(nodeListi); iItr < connectivityMap.end(nodeListi); ++iItr) { const auto i = *iItr; auto& sigmai = sigma(nodeListi, i); // Update the velocity divergence. divVel(nodeListi, i) = sigmai.Trace(); // Now limit to just negative eigen-values. This is 'cause we only // care about convergent geometries for the Q. const auto sigmai_s = sigmai.Symmetric(); const auto sigmai_a = sigmai.SkewSymmetric(); auto eigeni = sigmai_s.eigenVectors(); sigmai = constructTensorWithMinDiagonal(eigeni.eigenValues, 0.0); sigmai.rotationalTransform(eigeni.eigenVectors); // sigmai += sigmai_a; } } // Apply boundary conditions. for (auto boundItr = boundaryBegin; boundItr < boundaryEnd; ++boundItr) (*boundItr)->applyFieldListGhostBoundary(divVel); for (auto boundItr = boundaryBegin; boundItr < boundaryEnd; ++boundItr) (*boundItr)->finalizeGhostBoundary(); // Compute the gradient of div vel. gradDivVelocity = gradientRK(divVel, position, vol, H, connectivityMap, WR, corrections, NodeCoupling()); // Apply boundary conditions. for (auto boundItr = boundaryBegin; boundItr < boundaryEnd; ++boundItr) { (*boundItr)->applyFieldListGhostBoundary(sigma); (*boundItr)->applyFieldListGhostBoundary(gradDivVelocity); (*boundItr)->applyFieldListGhostBoundary(mGradVel); } // for (typename ArtificialViscosity<Dimension>::ConstBoundaryIterator boundItr = boundaryBegin; // boundItr != boundaryEnd; // ++boundItr) { // (*boundItr)->finalizeGhostBoundary(); // } } }
9,495
3,212
/*------------------------------------------------------------------------- * drawElements Quality Program OpenGL ES 2.0 Module * ------------------------------------------------- * * Copyright 2014 The Android Open Source Project * * 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. * *//*! * \file * \brief Texture size tests. *//*--------------------------------------------------------------------*/ #include "es2fTextureSizeTests.hpp" #include "glsTextureTestUtil.hpp" #include "gluTexture.hpp" #include "gluStrUtil.hpp" #include "gluTextureUtil.hpp" #include "gluPixelTransfer.hpp" #include "tcuTestLog.hpp" #include "tcuTextureUtil.hpp" #include "glwEnums.hpp" #include "glwFunctions.hpp" namespace deqp { namespace gles2 { namespace Functional { using tcu::TestLog; using std::vector; using std::string; using tcu::Sampler; using namespace glu; using namespace gls::TextureTestUtil; using namespace glu::TextureTestUtil; class Texture2DSizeCase : public tcu::TestCase { public: Texture2DSizeCase (tcu::TestContext& testCtx, glu::RenderContext& renderCtx, const char* name, const char* description, deUint32 format, deUint32 dataType, int width, int height, bool mipmaps); ~Texture2DSizeCase (void); void init (void); void deinit (void); IterateResult iterate (void); private: Texture2DSizeCase (const Texture2DSizeCase& other); Texture2DSizeCase& operator= (const Texture2DSizeCase& other); glu::RenderContext& m_renderCtx; deUint32 m_format; deUint32 m_dataType; int m_width; int m_height; bool m_useMipmaps; glu::Texture2D* m_texture; TextureRenderer m_renderer; }; Texture2DSizeCase::Texture2DSizeCase (tcu::TestContext& testCtx, glu::RenderContext& renderCtx, const char* name, const char* description, deUint32 format, deUint32 dataType, int width, int height, bool mipmaps) : TestCase (testCtx, name, description) , m_renderCtx (renderCtx) , m_format (format) , m_dataType (dataType) , m_width (width) , m_height (height) , m_useMipmaps (mipmaps) , m_texture (DE_NULL) , m_renderer (renderCtx, testCtx.getLog(), glu::GLSL_VERSION_100_ES, glu::PRECISION_MEDIUMP) { } Texture2DSizeCase::~Texture2DSizeCase (void) { Texture2DSizeCase::deinit(); } void Texture2DSizeCase::init (void) { DE_ASSERT(!m_texture); m_texture = new Texture2D(m_renderCtx, m_format, m_dataType, m_width, m_height); int numLevels = m_useMipmaps ? deLog2Floor32(de::max(m_width, m_height))+1 : 1; // Fill levels. for (int levelNdx = 0; levelNdx < numLevels; levelNdx++) { m_texture->getRefTexture().allocLevel(levelNdx); tcu::fillWithComponentGradients(m_texture->getRefTexture().getLevel(levelNdx), tcu::Vec4(-1.0f, -1.0f, -1.0f, 2.0f), tcu::Vec4(1.0f, 1.0f, 1.0f, 0.0f)); } } void Texture2DSizeCase::deinit (void) { delete m_texture; m_texture = DE_NULL; m_renderer.clear(); } Texture2DSizeCase::IterateResult Texture2DSizeCase::iterate (void) { const glw::Functions& gl = m_renderCtx.getFunctions(); TestLog& log = m_testCtx.getLog(); RandomViewport viewport (m_renderCtx.getRenderTarget(), 128, 128, deStringHash(getName())); tcu::Surface renderedFrame (viewport.width, viewport.height); tcu::Surface referenceFrame (viewport.width, viewport.height); tcu::RGBA threshold = m_renderCtx.getRenderTarget().getPixelFormat().getColorThreshold() + tcu::RGBA(7,7,7,7); deUint32 wrapS = GL_CLAMP_TO_EDGE; deUint32 wrapT = GL_CLAMP_TO_EDGE; // Do not minify with GL_NEAREST. A large POT texture with a small POT render target will produce // indeterminate results. deUint32 minFilter = m_useMipmaps ? GL_NEAREST_MIPMAP_NEAREST : GL_LINEAR; deUint32 magFilter = GL_NEAREST; vector<float> texCoord; computeQuadTexCoord2D(texCoord, tcu::Vec2(0.0f, 0.0f), tcu::Vec2(1.0f, 1.0f)); // Setup base viewport. gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height); // Upload texture data to GL. m_texture->upload(); // Bind to unit 0. gl.activeTexture(GL_TEXTURE0); gl.bindTexture(GL_TEXTURE_2D, m_texture->getGLTexture()); gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapS); gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapT); gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter); gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilter); GLU_EXPECT_NO_ERROR(gl.getError(), "Set texturing state"); // Draw. m_renderer.renderQuad(0, &texCoord[0], TEXTURETYPE_2D); glu::readPixels(m_renderCtx, viewport.x, viewport.y, renderedFrame.getAccess()); // Compute reference. sampleTexture(tcu::SurfaceAccess(referenceFrame, m_renderCtx.getRenderTarget().getPixelFormat()), m_texture->getRefTexture(), &texCoord[0], ReferenceParams(TEXTURETYPE_2D, mapGLSampler(wrapS, wrapT, minFilter, magFilter))); // Compare and log. bool isOk = compareImages(log, referenceFrame, renderedFrame, threshold); m_testCtx.setTestResult(isOk ? QP_TEST_RESULT_PASS : QP_TEST_RESULT_FAIL, isOk ? "Pass" : "Image comparison failed"); return STOP; } class TextureCubeSizeCase : public tcu::TestCase { public: TextureCubeSizeCase (tcu::TestContext& testCtx, glu::RenderContext& renderCtx, const char* name, const char* description, deUint32 format, deUint32 dataType, int width, int height, bool mipmaps); ~TextureCubeSizeCase (void); void init (void); void deinit (void); IterateResult iterate (void); private: TextureCubeSizeCase (const TextureCubeSizeCase& other); TextureCubeSizeCase& operator= (const TextureCubeSizeCase& other); bool testFace (tcu::CubeFace face); glu::RenderContext& m_renderCtx; deUint32 m_format; deUint32 m_dataType; int m_width; int m_height; bool m_useMipmaps; glu::TextureCube* m_texture; TextureRenderer m_renderer; int m_curFace; bool m_isOk; }; TextureCubeSizeCase::TextureCubeSizeCase (tcu::TestContext& testCtx, glu::RenderContext& renderCtx, const char* name, const char* description, deUint32 format, deUint32 dataType, int width, int height, bool mipmaps) : TestCase (testCtx, name, description) , m_renderCtx (renderCtx) , m_format (format) , m_dataType (dataType) , m_width (width) , m_height (height) , m_useMipmaps (mipmaps) , m_texture (DE_NULL) , m_renderer (renderCtx, testCtx.getLog(), glu::GLSL_VERSION_100_ES, glu::PRECISION_MEDIUMP) , m_curFace (0) , m_isOk (false) { } TextureCubeSizeCase::~TextureCubeSizeCase (void) { TextureCubeSizeCase::deinit(); } void TextureCubeSizeCase::init (void) { DE_ASSERT(!m_texture); DE_ASSERT(m_width == m_height); m_texture = new TextureCube(m_renderCtx, m_format, m_dataType, m_width); static const tcu::Vec4 gradients[tcu::CUBEFACE_LAST][2] = { { tcu::Vec4(-1.0f, -1.0f, -1.0f, 2.0f), tcu::Vec4(1.0f, 1.0f, 1.0f, 0.0f) }, // negative x { tcu::Vec4( 0.0f, -1.0f, -1.0f, 2.0f), tcu::Vec4(1.0f, 1.0f, 1.0f, 0.0f) }, // positive x { tcu::Vec4(-1.0f, 0.0f, -1.0f, 2.0f), tcu::Vec4(1.0f, 1.0f, 1.0f, 0.0f) }, // negative y { tcu::Vec4(-1.0f, -1.0f, 0.0f, 2.0f), tcu::Vec4(1.0f, 1.0f, 1.0f, 0.0f) }, // positive y { tcu::Vec4(-1.0f, -1.0f, -1.0f, 0.0f), tcu::Vec4(1.0f, 1.0f, 1.0f, 1.0f) }, // negative z { tcu::Vec4( 0.0f, 0.0f, 0.0f, 2.0f), tcu::Vec4(1.0f, 1.0f, 1.0f, 0.0f) } // positive z }; int numLevels = m_useMipmaps ? deLog2Floor32(de::max(m_width, m_height))+1 : 1; // Fill levels. for (int levelNdx = 0; levelNdx < numLevels; levelNdx++) { for (int face = 0; face < tcu::CUBEFACE_LAST; face++) { m_texture->getRefTexture().allocLevel((tcu::CubeFace)face, levelNdx); fillWithComponentGradients(m_texture->getRefTexture().getLevelFace(levelNdx, (tcu::CubeFace)face), gradients[face][0], gradients[face][1]); } } // Upload texture data to GL. m_texture->upload(); // Initialize iteration state. m_curFace = 0; m_isOk = true; } void TextureCubeSizeCase::deinit (void) { delete m_texture; m_texture = DE_NULL; m_renderer.clear(); } bool TextureCubeSizeCase::testFace (tcu::CubeFace face) { const glw::Functions& gl = m_renderCtx.getFunctions(); TestLog& log = m_testCtx.getLog(); RandomViewport viewport (m_renderCtx.getRenderTarget(), 128, 128, deStringHash(getName())+(deUint32)face); tcu::Surface renderedFrame (viewport.width, viewport.height); tcu::Surface referenceFrame (viewport.width, viewport.height); tcu::RGBA threshold = m_renderCtx.getRenderTarget().getPixelFormat().getColorThreshold() + tcu::RGBA(7,7,7,7); deUint32 wrapS = GL_CLAMP_TO_EDGE; deUint32 wrapT = GL_CLAMP_TO_EDGE; // Do not minify with GL_NEAREST. A large POT texture with a small POT render target will produce // indeterminate results. deUint32 minFilter = m_useMipmaps ? GL_NEAREST_MIPMAP_NEAREST : GL_LINEAR; deUint32 magFilter = GL_NEAREST; vector<float> texCoord; computeQuadTexCoordCube(texCoord, face); // \todo [2011-10-28 pyry] Image set name / section? log << TestLog::Message << face << TestLog::EndMessage; // Setup base viewport. gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height); // Bind to unit 0. gl.activeTexture(GL_TEXTURE0); gl.bindTexture(GL_TEXTURE_CUBE_MAP, m_texture->getGLTexture()); gl.texParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, wrapS); gl.texParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, wrapT); gl.texParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, minFilter); gl.texParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, magFilter); GLU_EXPECT_NO_ERROR(gl.getError(), "Set texturing state"); m_renderer.renderQuad(0, &texCoord[0], TEXTURETYPE_CUBE); glu::readPixels(m_renderCtx, viewport.x, viewport.y, renderedFrame.getAccess()); // Compute reference. Sampler sampler = mapGLSampler(wrapS, wrapT, minFilter, magFilter); sampler.seamlessCubeMap = false; sampleTexture(tcu::SurfaceAccess(referenceFrame, m_renderCtx.getRenderTarget().getPixelFormat()), m_texture->getRefTexture(), &texCoord[0], ReferenceParams(TEXTURETYPE_CUBE, sampler)); // Compare and log. return compareImages(log, referenceFrame, renderedFrame, threshold); } TextureCubeSizeCase::IterateResult TextureCubeSizeCase::iterate (void) { // Execute test for all faces. if (!testFace((tcu::CubeFace)m_curFace)) m_isOk = false; m_curFace += 1; if (m_curFace == tcu::CUBEFACE_LAST) { m_testCtx.setTestResult(m_isOk ? QP_TEST_RESULT_PASS : QP_TEST_RESULT_FAIL, m_isOk ? "Pass" : "Image comparison failed"); return STOP; } else return CONTINUE; } TextureSizeTests::TextureSizeTests (Context& context) : TestCaseGroup(context, "size", "Texture Size Tests") { } TextureSizeTests::~TextureSizeTests (void) { } void TextureSizeTests::init (void) { struct { int width; int height; } sizes2D[] = { { 64, 64 }, // Spec-mandated minimum. { 65, 63 }, { 512, 512 }, { 1024, 1024 }, { 2048, 2048 } }; struct { int width; int height; } sizesCube[] = { { 15, 15 }, { 16, 16 }, // Spec-mandated minimum { 64, 64 }, { 128, 128 }, { 256, 256 }, { 512, 512 } }; struct { const char* name; deUint32 format; deUint32 dataType; } formats[] = { { "l8", GL_LUMINANCE, GL_UNSIGNED_BYTE }, { "rgba4444", GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4 }, { "rgb888", GL_RGB, GL_UNSIGNED_BYTE }, { "rgba8888", GL_RGBA, GL_UNSIGNED_BYTE } }; // 2D cases. tcu::TestCaseGroup* group2D = new tcu::TestCaseGroup(m_testCtx, "2d", "2D Texture Size Tests"); addChild(group2D); for (int sizeNdx = 0; sizeNdx < DE_LENGTH_OF_ARRAY(sizes2D); sizeNdx++) { int width = sizes2D[sizeNdx].width; int height = sizes2D[sizeNdx].height; bool isPOT = deIsPowerOfTwo32(width) && deIsPowerOfTwo32(height); for (int formatNdx = 0; formatNdx < DE_LENGTH_OF_ARRAY(formats); formatNdx++) { for (int mipmap = 0; mipmap < (isPOT ? 2 : 1); mipmap++) { std::ostringstream name; name << width << "x" << height << "_" << formats[formatNdx].name << (mipmap ? "_mipmap" : ""); group2D->addChild(new Texture2DSizeCase(m_testCtx, m_context.getRenderContext(), name.str().c_str(), "", formats[formatNdx].format, formats[formatNdx].dataType, width, height, mipmap != 0)); } } } // Cubemap cases. tcu::TestCaseGroup* groupCube = new tcu::TestCaseGroup(m_testCtx, "cube", "Cubemap Texture Size Tests"); addChild(groupCube); for (int sizeNdx = 0; sizeNdx < DE_LENGTH_OF_ARRAY(sizesCube); sizeNdx++) { int width = sizesCube[sizeNdx].width; int height = sizesCube[sizeNdx].height; bool isPOT = deIsPowerOfTwo32(width) && deIsPowerOfTwo32(height); for (int formatNdx = 0; formatNdx < DE_LENGTH_OF_ARRAY(formats); formatNdx++) { for (int mipmap = 0; mipmap < (isPOT ? 2 : 1); mipmap++) { std::ostringstream name; name << width << "x" << height << "_" << formats[formatNdx].name << (mipmap ? "_mipmap" : ""); groupCube->addChild(new TextureCubeSizeCase(m_testCtx, m_context.getRenderContext(), name.str().c_str(), "", formats[formatNdx].format, formats[formatNdx].dataType, width, height, mipmap != 0)); } } } } } // Functional } // gles2 } // deqp
13,732
6,135
// Copyright 2018 Bernardo Heynemann <heynemann@gmail.com> // Backstage Renderer #pragma once #include <string> namespace backstage { namespace renderer { class CliRoot { public: bool help = false; bool version = false; std::string host = "localhost"; int port = 8888; int workers = 8; int logLevel = 0; std::string configFile = "config.yaml"; std::string templatePath = "./templates"; CliRoot() {} void ParseArgs(int argc, char *argv[]); void PrintUsage(int major, int minor, int revision); void PrintVersion(int major, int minor, int revision); }; } // namespace renderer } // namespace backstage
655
209
#include <Ref_Constituant_Avec_Vitesse.h> #include <Constituant_Avec_Vitesse.h> Implemente_ref(Constituant_Avec_Vitesse);
122
55
//============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk 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 3.0 of the License, or // any later version. // // The GPSTk 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 GPSTk; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ //============================================================================ // //This software developed by Applied Research Laboratories at the University of //Texas at Austin, under contract to an agency or agencies within the U.S. //Department of Defense. The U.S. Government retains all rights to use, //duplicate, distribute, disclose, or release this software. // //Pursuant to DoD Directive 523024 // // DISTRIBUTION STATEMENT A: This software has been approved for public // release, distribution is unlimited. // //============================================================================= #include "BinexData.hpp" #include "TestUtil.hpp" using namespace std; using namespace gpstk; //============================================================================= // Class declarations //============================================================================= class BinexAttrs_T { public: // constructor BinexAttrs_T() : verboseLevel(0) { init(); }; // destructor virtual ~BinexAttrs_T() {}; // initialize tests void init(); // test methods // @return number of failures, i.e., 0=PASS, !0=FAIL int doIsDataTests(); int doRecordFlagsTests(); int doRecordIdTests(); int doMessageCapacityTests(); int doMessageLengthTests(); unsigned verboseLevel; // amount to display during tests, 0 = least }; // class BinexAttrs_T //============================================================ // Initialize Test Data Filenames and Values //============================================================ void BinexAttrs_T :: init( void ) { // empty } int BinexAttrs_T :: doIsDataTests() { TUDEF("BinexData", "isData"); BinexData rec; TUASSERT(rec.isData()); TURETURN(); } int BinexAttrs_T :: doRecordFlagsTests() { TUDEF("BinexData", "getRecordFlags"); BinexData rec; TUASSERTE(BinexData::SyncByte, BinexData::DEFAULT_RECORD_FLAGS, rec.getRecordFlags()); TUCSM("setRecordFlags"); rec.setRecordFlags(0); TUASSERTE(BinexData::SyncByte, 0, rec.getRecordFlags()); rec.setRecordFlags(0xFF); TUASSERTE(BinexData::SyncByte, BinexData::VALID_RECORD_FLAGS, rec.getRecordFlags()); TURETURN(); } int BinexAttrs_T :: doRecordIdTests() { TUDEF("BinexData", "getRecordID"); BinexData recA; TUASSERTE(BinexData::RecordID, BinexData::INVALID_RECORD_ID, recA.getRecordID()); BinexData recB(123); TUASSERTE(BinexData::RecordID, 123, recB.getRecordID()); TUCSM("setRecordID"); recB.setRecordID(456); TUASSERTE(BinexData::RecordID, 456, recB.getRecordID()); TURETURN(); } int BinexAttrs_T :: doMessageLengthTests() { TUDEF("BinexData", "getMessageLength"); BinexData rec(1); // a record id is required TUASSERTE(size_t, 0, rec.getMessageLength()); TUCSM("getHeadLength"); TUASSERTE(size_t, 3, rec.getHeadLength()); TUCSM("getTailLength"); TUASSERTE(size_t, 1, rec.getTailLength()); TUCSM("getRecordSize"); TUASSERTE(size_t, 4, rec.getRecordSize()); std::string s("1"); size_t offset = 0; rec.updateMessageData(offset, s, s.size()); TUCSM("getMessageLength"); TUASSERTE(size_t, 1, rec.getMessageLength()); TUCSM("getHeadLength"); TUASSERTE(size_t, 3, rec.getHeadLength()); TUCSM("getTailLength"); TUASSERTE(size_t, 1, rec.getTailLength()); TUCSM("getRecordSize"); TUASSERTE(size_t, 5, rec.getRecordSize()); s.assign(199, '2'); rec.updateMessageData(offset, s, s.size()); TUCSM("getMessageLength"); TUASSERTE(size_t, 200, rec.getMessageLength()); TUCSM("getHeadLength"); TUASSERTE(size_t, 4, rec.getHeadLength()); TUCSM("getTailLength"); TUASSERTE(size_t, 2, rec.getTailLength()); TUCSM("getRecordSize"); TUASSERTE(size_t, 206, rec.getRecordSize()); s.assign(17000, '3'); rec.updateMessageData(offset, s, s.size()); TUCSM("getMessageLength"); TUASSERTE(size_t, 17200, rec.getMessageLength()); TUCSM("getHeadLength"); TUASSERTE(size_t, 5, rec.getHeadLength()); TUCSM("getTailLength"); TUASSERTE(size_t, 4, rec.getTailLength()); TUCSM("getRecordSize"); TUASSERTE(size_t, 17209, rec.getRecordSize()); s.assign(2100800, '4'); rec.updateMessageData(offset, s, s.size()); TUCSM("getMessageLength"); TUASSERTE(size_t, 2118000, rec.getMessageLength()); TUCSM("getHeadLength"); TUASSERTE(size_t, 6, rec.getHeadLength()); TUCSM("getTailLength"); TUASSERTE(size_t, 16, rec.getTailLength()); TUCSM("getRecordSize"); TUASSERTE(size_t, 2118022, rec.getRecordSize()); TURETURN(); } int BinexAttrs_T :: doMessageCapacityTests() { TUDEF("BinexData", "getMessageCapacity"); BinexData rec; BinexData::UBNXI u; size_t offset = 0; rec.updateMessageData(offset, u); TUASSERT(rec.getMessageData().capacity() >= 1); TUCSM("ensureMessageCapacity"); rec.ensureMessageCapacity(1024); TUASSERT(rec.getMessageData().capacity() >= 1024); rec.ensureMessageCapacity(2048); TUASSERT(rec.getMessageData().capacity() >= 2048); TURETURN(); } /** Run the program. * * @return Total error count for all tests */ int main(int argc, char *argv[]) { int errorTotal = 0; BinexAttrs_T testClass; // test data is loaded here errorTotal += testClass.doIsDataTests(); errorTotal += testClass.doRecordFlagsTests(); errorTotal += testClass.doRecordIdTests(); errorTotal += testClass.doMessageCapacityTests(); errorTotal += testClass.doMessageLengthTests(); return( errorTotal ); } // main()
6,575
2,362
/* * Copyright (c) 2018 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <queue> #include "api/transport/goog_cc_factory.h" #include "test/field_trial.h" #include "test/gtest.h" #include "test/scenario/scenario.h" namespace webrtc { namespace test { namespace { // Count dips from a constant high bandwidth level within a short window. int CountBandwidthDips(std::queue<DataRate> bandwidth_history, DataRate threshold) { if (bandwidth_history.empty()) return true; DataRate first = bandwidth_history.front(); bandwidth_history.pop(); int dips = 0; bool state_high = true; while (!bandwidth_history.empty()) { if (bandwidth_history.front() + threshold < first && state_high) { ++dips; state_high = false; } else if (bandwidth_history.front() == first) { state_high = true; } else if (bandwidth_history.front() > first) { // If this is toggling we will catch it later when front becomes first. state_high = false; } bandwidth_history.pop(); } return dips; } } // namespace TEST(GoogCcNetworkControllerTest, MaintainsLowRateInSafeResetTrial) { const DataRate kLinkCapacity = DataRate::kbps(200); const DataRate kStartRate = DataRate::kbps(300); ScopedFieldTrials trial("WebRTC-Bwe-SafeResetOnRouteChange/Enabled/"); Scenario s("googcc_unit/safe_reset_low", true); auto* send_net = s.CreateSimulationNode([&](NetworkNodeConfig* c) { c->simulation.bandwidth = kLinkCapacity; c->simulation.delay = TimeDelta::ms(10); }); // TODO(srte): replace with SimulatedTimeClient when it supports probing. auto* client = s.CreateClient("send", [&](CallClientConfig* c) { c->transport.cc = TransportControllerConfig::CongestionController::kGoogCc; c->transport.rates.start_rate = kStartRate; }); auto* route = s.CreateRoutes(client, {send_net}, s.CreateClient("return", CallClientConfig()), {s.CreateSimulationNode(NetworkNodeConfig())}); s.CreateVideoStream(route->forward(), VideoStreamConfig()); // Allow the controller to stabilize. s.RunFor(TimeDelta::ms(500)); EXPECT_NEAR(client->send_bandwidth().kbps(), kLinkCapacity.kbps(), 50); s.ChangeRoute(route->forward(), {send_net}); // Allow new settings to propagate. s.RunFor(TimeDelta::ms(100)); // Under the trial, the target should be unchanged for low rates. EXPECT_NEAR(client->send_bandwidth().kbps(), kLinkCapacity.kbps(), 50); } TEST(GoogCcNetworkControllerTest, CutsHighRateInSafeResetTrial) { const DataRate kLinkCapacity = DataRate::kbps(1000); const DataRate kStartRate = DataRate::kbps(300); ScopedFieldTrials trial("WebRTC-Bwe-SafeResetOnRouteChange/Enabled/"); Scenario s("googcc_unit/safe_reset_high_cut", true); auto send_net = s.CreateSimulationNode([&](NetworkNodeConfig* c) { c->simulation.bandwidth = kLinkCapacity; c->simulation.delay = TimeDelta::ms(50); }); // TODO(srte): replace with SimulatedTimeClient when it supports probing. auto* client = s.CreateClient("send", [&](CallClientConfig* c) { c->transport.cc = TransportControllerConfig::CongestionController::kGoogCc; c->transport.rates.start_rate = kStartRate; }); auto* route = s.CreateRoutes(client, {send_net}, s.CreateClient("return", CallClientConfig()), {s.CreateSimulationNode(NetworkNodeConfig())}); s.CreateVideoStream(route->forward(), VideoStreamConfig()); // Allow the controller to stabilize. s.RunFor(TimeDelta::ms(500)); EXPECT_NEAR(client->send_bandwidth().kbps(), kLinkCapacity.kbps(), 300); s.ChangeRoute(route->forward(), {send_net}); // Allow new settings to propagate. s.RunFor(TimeDelta::ms(50)); // Under the trial, the target should be reset from high values. EXPECT_NEAR(client->send_bandwidth().kbps(), kStartRate.kbps(), 30); } TEST(GoogCcNetworkControllerTest, DetectsHighRateInSafeResetTrial) { ScopedFieldTrials trial( "WebRTC-Bwe-SafeResetOnRouteChange/Enabled,ack/" "WebRTC-Bwe-ProbeRateFallback/Enabled/"); const DataRate kInitialLinkCapacity = DataRate::kbps(200); const DataRate kNewLinkCapacity = DataRate::kbps(800); const DataRate kStartRate = DataRate::kbps(300); Scenario s("googcc_unit/safe_reset_high_detect", true); auto* initial_net = s.CreateSimulationNode([&](NetworkNodeConfig* c) { c->simulation.bandwidth = kInitialLinkCapacity; c->simulation.delay = TimeDelta::ms(50); }); auto* new_net = s.CreateSimulationNode([&](NetworkNodeConfig* c) { c->simulation.bandwidth = kNewLinkCapacity; c->simulation.delay = TimeDelta::ms(50); }); // TODO(srte): replace with SimulatedTimeClient when it supports probing. auto* client = s.CreateClient("send", [&](CallClientConfig* c) { c->transport.cc = TransportControllerConfig::CongestionController::kGoogCc; c->transport.rates.start_rate = kStartRate; }); auto* route = s.CreateRoutes(client, {initial_net}, s.CreateClient("return", CallClientConfig()), {s.CreateSimulationNode(NetworkNodeConfig())}); s.CreateVideoStream(route->forward(), VideoStreamConfig()); // Allow the controller to stabilize. s.RunFor(TimeDelta::ms(1000)); EXPECT_NEAR(client->send_bandwidth().kbps(), kInitialLinkCapacity.kbps(), 50); s.ChangeRoute(route->forward(), {new_net}); // Allow new settings to propagate, but not probes to be received. s.RunFor(TimeDelta::ms(50)); // Under the field trial, the target rate should be unchanged since it's lower // than the starting rate. EXPECT_NEAR(client->send_bandwidth().kbps(), kInitialLinkCapacity.kbps(), 50); // However, probing should have made us detect the higher rate. s.RunFor(TimeDelta::ms(2000)); EXPECT_GT(client->send_bandwidth().kbps(), kNewLinkCapacity.kbps() - 300); } TEST(GoogCcNetworkControllerTest, TargetRateReducedOnPacingBufferBuildupInTrial) { // Configure strict pacing to ensure build-up. ScopedFieldTrials trial( "WebRTC-CongestionWindowPushback/Enabled/WebRTC-CwndExperiment/" "Enabled-100/WebRTC-Video-Pacing/factor:1.0/" "WebRTC-AddPacingToCongestionWindowPushback/Enabled/"); const DataRate kLinkCapacity = DataRate::kbps(1000); const DataRate kStartRate = DataRate::kbps(1000); Scenario s("googcc_unit/pacing_buffer_buildup", true); auto* net = s.CreateSimulationNode([&](NetworkNodeConfig* c) { c->simulation.bandwidth = kLinkCapacity; c->simulation.delay = TimeDelta::ms(50); }); // TODO(srte): replace with SimulatedTimeClient when it supports pacing. auto* client = s.CreateClient("send", [&](CallClientConfig* c) { c->transport.cc = TransportControllerConfig::CongestionController::kGoogCc; c->transport.rates.start_rate = kStartRate; }); auto* route = s.CreateRoutes(client, {net}, s.CreateClient("return", CallClientConfig()), {s.CreateSimulationNode(NetworkNodeConfig())}); s.CreateVideoStream(route->forward(), VideoStreamConfig()); // Allow some time for the buffer to build up. s.RunFor(TimeDelta::seconds(5)); // Without trial, pacer delay reaches ~250 ms. EXPECT_LT(client->GetStats().pacer_delay_ms, 150); } TEST(GoogCcNetworkControllerTest, NoBandwidthTogglingInLossControlTrial) { ScopedFieldTrials trial("WebRTC-Bwe-LossBasedControl/Enabled/"); Scenario s("googcc_unit/no_toggling", true); auto* send_net = s.CreateSimulationNode([&](NetworkNodeConfig* c) { c->simulation.bandwidth = DataRate::kbps(2000); c->simulation.loss_rate = 0.2; c->simulation.delay = TimeDelta::ms(10); }); // TODO(srte): replace with SimulatedTimeClient when it supports probing. auto* client = s.CreateClient("send", [&](CallClientConfig* c) { c->transport.cc = TransportControllerConfig::CongestionController::kGoogCc; c->transport.rates.start_rate = DataRate::kbps(300); }); auto* route = s.CreateRoutes(client, {send_net}, s.CreateClient("return", CallClientConfig()), {s.CreateSimulationNode(NetworkNodeConfig())}); s.CreateVideoStream(route->forward(), VideoStreamConfig()); // Allow the controller to initialize. s.RunFor(TimeDelta::ms(250)); std::queue<DataRate> bandwidth_history; const TimeDelta step = TimeDelta::ms(50); for (TimeDelta time = TimeDelta::Zero(); time < TimeDelta::ms(2000); time += step) { s.RunFor(step); const TimeDelta window = TimeDelta::ms(500); if (bandwidth_history.size() >= window / step) bandwidth_history.pop(); bandwidth_history.push(client->send_bandwidth()); EXPECT_LT(CountBandwidthDips(bandwidth_history, DataRate::kbps(100)), 2); } } TEST(GoogCcNetworkControllerTest, NoRttBackoffCollapseWhenVideoStops) { ScopedFieldTrials trial("WebRTC-Bwe-MaxRttLimit/limit:2s/"); Scenario s("googcc_unit/rttbackoff_video_stop", true); auto* send_net = s.CreateSimulationNode([&](NetworkNodeConfig* c) { c->simulation.bandwidth = DataRate::kbps(2000); c->simulation.delay = TimeDelta::ms(100); }); auto* client = s.CreateClient("send", [&](CallClientConfig* c) { c->transport.cc = TransportControllerConfig::CongestionController::kGoogCc; c->transport.rates.start_rate = DataRate::kbps(1000); }); auto* route = s.CreateRoutes(client, {send_net}, s.CreateClient("return", CallClientConfig()), {s.CreateSimulationNode(NetworkNodeConfig())}); auto* video = s.CreateVideoStream(route->forward(), VideoStreamConfig()); // Allow the controller to initialize, then stop video. s.RunFor(TimeDelta::seconds(1)); video->send()->Stop(); s.RunFor(TimeDelta::seconds(4)); EXPECT_GT(client->send_bandwidth().kbps(), 1000); } } // namespace test } // namespace webrtc
10,260
3,404
// Copyright 2016 The Chromium OS 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 "power_manager/powerd/system/dbus_wrapper.h" #include <memory> #include <utility> #include <base/bind.h> #include <base/check.h> #include <base/logging.h> #include <base/memory/ptr_util.h> #include <chromeos/dbus/service_constants.h> #include <dbus/bus.h> #include <dbus/message.h> #include <google/protobuf/message_lite.h> #include "power_manager/common/power_constants.h" namespace power_manager { namespace system { namespace { // Handles the result of an attempt to connect to a D-Bus signal, logging an // error on failure. void HandleSignalConnected(const std::string& interface, const std::string& signal, bool success) { if (!success) LOG(ERROR) << "Failed to connect to signal " << interface << "." << signal; } } // namespace DBusWrapper::DBusWrapper(scoped_refptr<dbus::Bus> bus, dbus::ExportedObject* exported_object) : bus_(bus), exported_object_(exported_object), weak_ptr_factory_(this) { // Listen for NameOwnerChanged signals from the bus itself. dbus::ObjectProxy* bus_proxy = bus->GetObjectProxy(kBusServiceName, dbus::ObjectPath(kBusServicePath)); bus_proxy->ConnectToSignal( kBusInterface, kBusNameOwnerChangedSignal, base::Bind(&DBusWrapper::HandleNameOwnerChangedSignal, weak_ptr_factory_.GetWeakPtr()), base::Bind(&HandleSignalConnected)); } DBusWrapper::~DBusWrapper() = default; // static std::unique_ptr<DBusWrapper> DBusWrapper::Create() { dbus::Bus::Options options; options.bus_type = dbus::Bus::SYSTEM; scoped_refptr<dbus::Bus> bus(new dbus::Bus(options)); if (!bus->Connect()) { LOG(ERROR) << "Failed to connect to system bus"; return nullptr; } dbus::ExportedObject* exported_object = bus->GetExportedObject(dbus::ObjectPath(kPowerManagerServicePath)); if (!exported_object) { LOG(ERROR) << "Failed to export " << kPowerManagerServicePath << " object"; return nullptr; } return base::WrapUnique(new DBusWrapper(bus, exported_object)); } void DBusWrapper::AddObserver(Observer* observer) { DCHECK(observer); observers_.AddObserver(observer); } void DBusWrapper::RemoveObserver(Observer* observer) { DCHECK(observer); observers_.RemoveObserver(observer); } scoped_refptr<dbus::Bus> DBusWrapper::GetBus() { return bus_; } dbus::ObjectProxy* DBusWrapper::GetObjectProxy(const std::string& service_name, const std::string& object_path) { return bus_->GetObjectProxy(service_name, dbus::ObjectPath(object_path)); } void DBusWrapper::RegisterForServiceAvailability( dbus::ObjectProxy* proxy, dbus::ObjectProxy::WaitForServiceToBeAvailableCallback callback) { DCHECK(proxy); proxy->WaitForServiceToBeAvailable(std::move(callback)); } void DBusWrapper::RegisterForSignal( dbus::ObjectProxy* proxy, const std::string& interface_name, const std::string& signal_name, dbus::ObjectProxy::SignalCallback callback) { DCHECK(proxy); proxy->ConnectToSignal(interface_name, signal_name, callback, base::Bind(&HandleSignalConnected)); } void DBusWrapper::ExportMethod( const std::string& method_name, dbus::ExportedObject::MethodCallCallback callback) { CHECK(exported_object_->ExportMethodAndBlock(kPowerManagerInterface, method_name, callback)); } bool DBusWrapper::PublishService() { return bus_->RequestOwnershipAndBlock(kPowerManagerServiceName, dbus::Bus::REQUIRE_PRIMARY); } void DBusWrapper::EmitSignal(dbus::Signal* signal) { DCHECK(exported_object_); DCHECK(signal); exported_object_->SendSignal(signal); } void DBusWrapper::EmitBareSignal(const std::string& signal_name) { dbus::Signal signal(kPowerManagerInterface, signal_name); EmitSignal(&signal); } void DBusWrapper::EmitSignalWithProtocolBuffer( const std::string& signal_name, const google::protobuf::MessageLite& protobuf) { dbus::Signal signal(kPowerManagerInterface, signal_name); dbus::MessageWriter writer(&signal); writer.AppendProtoAsArrayOfBytes(protobuf); EmitSignal(&signal); } std::unique_ptr<dbus::Response> DBusWrapper::CallMethodSync( dbus::ObjectProxy* proxy, dbus::MethodCall* method_call, base::TimeDelta timeout) { DCHECK(proxy); DCHECK(method_call); return std::unique_ptr<dbus::Response>( proxy->CallMethodAndBlock(method_call, timeout.InMilliseconds())); } void DBusWrapper::CallMethodAsync( dbus::ObjectProxy* proxy, dbus::MethodCall* method_call, base::TimeDelta timeout, dbus::ObjectProxy::ResponseCallback callback) { DCHECK(proxy); DCHECK(method_call); proxy->CallMethod(method_call, timeout.InMilliseconds(), std::move(callback)); } void DBusWrapper::HandleNameOwnerChangedSignal(dbus::Signal* signal) { DCHECK(signal); dbus::MessageReader reader(signal); std::string name, old_owner, new_owner; if (!reader.PopString(&name) || !reader.PopString(&old_owner) || !reader.PopString(&new_owner)) { LOG(ERROR) << "Unable to parse " << kBusNameOwnerChangedSignal << " signal"; return; } for (DBusWrapper::Observer& observer : observers_) observer.OnDBusNameOwnerChanged(name, old_owner, new_owner); } } // namespace system } // namespace power_manager
5,557
1,763
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/glue/model/LongColumnStatisticsData.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace Glue { namespace Model { LongColumnStatisticsData::LongColumnStatisticsData() : m_minimumValue(0), m_minimumValueHasBeenSet(false), m_maximumValue(0), m_maximumValueHasBeenSet(false), m_numberOfNulls(0), m_numberOfNullsHasBeenSet(false), m_numberOfDistinctValues(0), m_numberOfDistinctValuesHasBeenSet(false) { } LongColumnStatisticsData::LongColumnStatisticsData(JsonView jsonValue) : m_minimumValue(0), m_minimumValueHasBeenSet(false), m_maximumValue(0), m_maximumValueHasBeenSet(false), m_numberOfNulls(0), m_numberOfNullsHasBeenSet(false), m_numberOfDistinctValues(0), m_numberOfDistinctValuesHasBeenSet(false) { *this = jsonValue; } LongColumnStatisticsData& LongColumnStatisticsData::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("MinimumValue")) { m_minimumValue = jsonValue.GetInt64("MinimumValue"); m_minimumValueHasBeenSet = true; } if(jsonValue.ValueExists("MaximumValue")) { m_maximumValue = jsonValue.GetInt64("MaximumValue"); m_maximumValueHasBeenSet = true; } if(jsonValue.ValueExists("NumberOfNulls")) { m_numberOfNulls = jsonValue.GetInt64("NumberOfNulls"); m_numberOfNullsHasBeenSet = true; } if(jsonValue.ValueExists("NumberOfDistinctValues")) { m_numberOfDistinctValues = jsonValue.GetInt64("NumberOfDistinctValues"); m_numberOfDistinctValuesHasBeenSet = true; } return *this; } JsonValue LongColumnStatisticsData::Jsonize() const { JsonValue payload; if(m_minimumValueHasBeenSet) { payload.WithInt64("MinimumValue", m_minimumValue); } if(m_maximumValueHasBeenSet) { payload.WithInt64("MaximumValue", m_maximumValue); } if(m_numberOfNullsHasBeenSet) { payload.WithInt64("NumberOfNulls", m_numberOfNulls); } if(m_numberOfDistinctValuesHasBeenSet) { payload.WithInt64("NumberOfDistinctValues", m_numberOfDistinctValues); } return payload; } } // namespace Model } // namespace Glue } // namespace Aws
2,350
873
#include <iostream> #include <mutex> #include <condition_variable> #include <unistd.h> #include <thread> using namespace std; int main() { cout << "Hello world!"<< endl; return 0; }
201
69
#ifndef ICHARACTER_HPP #define ICHARACTER_HPP #include <string> class AMateria; class ICharacter { public: virtual ~ICharacter() {}; virtual std::string const & getName() const = 0; virtual void equip(AMateria* m) = 0; virtual void unequip(int idx) = 0; virtual void use(int idx, ICharacter& target) = 0; }; #endif
363
126
#include "sx_serie_cronologia.h" #include "form_serie_mese.h" #include <QtSql> #include <iostream> using namespace std; sx_serie_cronologia::sx_serie_cronologia(QWidget *parent) : QWidget(parent) { lay=new QVBoxLayout(this); tit=new QLabel("Cronologia serie",this); tit->setFont(QFont("Times",15)); area=new QScrollArea(this); QWidget *bg=new QWidget(this); QVBoxLayout *lbg=new QVBoxLayout(this); bg->setLayout(lbg); int altezza=0,numero=0; QSqlQuery q; q.exec("select min(datainizio),max(datafine) from visionestagione;"); q.next(); QDate curr=QDate::fromString(q.value(1).toString(),"yyyy-MM-dd"); QDate fine=QDate::fromString(q.value(0).toString(),"yyyy-MM-dd"); while(curr>=fine){ Form_serie_mese *fo=new Form_serie_mese(this); numero+=fo->settamese(curr); lbg->addWidget(fo); altezza++; curr=curr.addMonths(-1); } tit->setText(QString("Cronologia serie [visioni: ")+QString::number(numero)+QString("]")); bg->setMinimumSize(770,altezza*200); area->setWidget(bg); lay->addWidget(tit); lay->addWidget(area); setLayout(lay); }
1,144
448
/** * @file methods/kmeans/kmeans_main.cpp * @author Ryan Curtin * * Executable for running K-Means. * * mlpack is free software; you may redistribute it and/or modify it under the * terms of the 3-clause BSD license. You should have received a copy of the * 3-clause BSD license along with mlpack. If not, see * http://www.opensource.org/licenses/BSD-3-Clause for more information. */ #include <mlpack/prereqs.hpp> #include <mlpack/core/util/io.hpp> #ifdef BINDING_NAME #undef BINDING_NAME #endif #define BINDING_NAME kmeans #include <mlpack/core/util/mlpack_main.hpp> #include "kmeans.hpp" #include "allow_empty_clusters.hpp" #include "kill_empty_clusters.hpp" #include "refined_start.hpp" #include "kmeans_plus_plus_initialization.hpp" #include "elkan_kmeans.hpp" #include "hamerly_kmeans.hpp" #include "pelleg_moore_kmeans.hpp" #include "dual_tree_kmeans.hpp" using namespace mlpack; using namespace mlpack::kmeans; using namespace mlpack::util; using namespace std; // Program Name. BINDING_USER_NAME("K-Means Clustering"); // Short description. BINDING_SHORT_DESC( "An implementation of several strategies for efficient k-means clustering. " "Given a dataset and a value of k, this computes and returns a k-means " "clustering on that data."); // Long description. BINDING_LONG_DESC( "This program performs K-Means clustering on the given dataset. It can " "return the learned cluster assignments, and the centroids of the clusters." " Empty clusters are not allowed by default; when a cluster becomes empty," " the point furthest from the centroid of the cluster with maximum variance" " is taken to fill that cluster." "\n\n" "Optionally, the strategy to choose initial centroids can be specified. " "The k-means++ algorithm can be used to choose initial centroids with " "the " + PRINT_PARAM_STRING("kmeans_plus_plus") + " parameter. The " "Bradley and Fayyad approach (\"Refining initial points for k-means " "clustering\", 1998) can be used to select initial points by specifying " "the " + PRINT_PARAM_STRING("refined_start") + " parameter. This approach " "works by taking random samplings of the dataset; to specify the number of " "samplings, the " + PRINT_PARAM_STRING("samplings") + " parameter is used, " "and to specify the percentage of the dataset to be used in each sample, " "the " + PRINT_PARAM_STRING("percentage") + " parameter is used (it should " "be a value between 0.0 and 1.0)." "\n\n" "There are several options available for the algorithm used for each Lloyd " "iteration, specified with the " + PRINT_PARAM_STRING("algorithm") + " " " option. The standard O(kN) approach can be used ('naive'). Other " "options include the Pelleg-Moore tree-based algorithm ('pelleg-moore'), " "Elkan's triangle-inequality based algorithm ('elkan'), Hamerly's " "modification to Elkan's algorithm ('hamerly'), the dual-tree k-means " "algorithm ('dualtree'), and the dual-tree k-means algorithm using the " "cover tree ('dualtree-covertree')." "\n\n" "The behavior for when an empty cluster is encountered can be modified with" " the " + PRINT_PARAM_STRING("allow_empty_clusters") + " option. When " "this option is specified and there is a cluster owning no points at the " "end of an iteration, that cluster's centroid will simply remain in its " "position from the previous iteration. If the " + PRINT_PARAM_STRING("kill_empty_clusters") + " option is specified, then " "when a cluster owns no points at the end of an iteration, the cluster " "centroid is simply filled with DBL_MAX, killing it and effectively " "reducing k for the rest of the computation. Note that the default option " "when neither empty cluster option is specified can be time-consuming to " "calculate; therefore, specifying either of these parameters will often " "accelerate runtime." "\n\n" "Initial clustering assignments may be specified using the " + PRINT_PARAM_STRING("initial_centroids") + " parameter, and the maximum " "number of iterations may be specified with the " + PRINT_PARAM_STRING("max_iterations") + " parameter."); // Example. BINDING_EXAMPLE( "As an example, to use Hamerly's algorithm to perform k-means clustering " "with k=10 on the dataset " + PRINT_DATASET("data") + ", saving the " "centroids to " + PRINT_DATASET("centroids") + " and the assignments for " "each point to " + PRINT_DATASET("assignments") + ", the following " "command could be used:" "\n\n" + PRINT_CALL("kmeans", "input", "data", "clusters", 10, "output", "assignments", "centroid", "centroids") + "\n\n" "To run k-means on that same dataset with initial centroids specified in " + PRINT_DATASET("initial") + " with a maximum of 500 iterations, " "storing the output centroids in " + PRINT_DATASET("final") + " the " "following command may be used:" "\n\n" + PRINT_CALL("kmeans", "input", "data", "initial_centroids", "initial", "clusters", 10, "max_iterations", 500, "centroid", "final")); // See also... BINDING_SEE_ALSO("K-Means tutorial", "@doxygen/kmtutorial.html"); BINDING_SEE_ALSO("@dbscan", "#dbscan"); BINDING_SEE_ALSO("k-means++", "https://en.wikipedia.org/wiki/K-means%2B%2B"); BINDING_SEE_ALSO("Using the triangle inequality to accelerate k-means (pdf)", "http://www.aaai.org/Papers/ICML/2003/ICML03-022.pdf"); BINDING_SEE_ALSO("Making k-means even faster (pdf)", "http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.586.2554" "&rep=rep1&type=pdf"); BINDING_SEE_ALSO("Accelerating exact k-means algorithms with geometric" " reasoning (pdf)", "http://reports-archive.adm.cs.cmu.edu/anon/anon" "/usr/ftp/usr0/ftp/2000/CMU-CS-00-105.pdf"); BINDING_SEE_ALSO("A dual-tree algorithm for fast k-means clustering with large " "k (pdf)", "http://www.ratml.org/pub/pdf/2017dual.pdf"); BINDING_SEE_ALSO("mlpack::kmeans::KMeans class documentation", "@doxygen/classmlpack_1_1kmeans_1_1KMeans.html"); // Required options. PARAM_MATRIX_IN_REQ("input", "Input dataset to perform clustering on.", "i"); PARAM_INT_IN_REQ("clusters", "Number of clusters to find (0 autodetects from " "initial centroids).", "c"); // Output options. PARAM_FLAG("in_place", "If specified, a column containing the learned cluster " "assignments will be added to the input dataset file. In this case, " "--output_file is overridden. (Do not use in Python.)", "P"); PARAM_MATRIX_OUT("output", "Matrix to store output labels or labeled data to.", "o"); PARAM_MATRIX_OUT("centroid", "If specified, the centroids of each cluster will " " be written to the given file.", "C"); // k-means configuration options. PARAM_FLAG("allow_empty_clusters", "Allow empty clusters to be persist.", "e"); PARAM_FLAG("kill_empty_clusters", "Remove empty clusters when they occur.", "E"); PARAM_FLAG("labels_only", "Only output labels into output file.", "l"); PARAM_INT_IN("max_iterations", "Maximum number of iterations before k-means " "terminates.", "m", 1000); PARAM_INT_IN("seed", "Random seed. If 0, 'std::time(NULL)' is used.", "s", 0); PARAM_MATRIX_IN("initial_centroids", "Start with the specified initial " "centroids.", "I"); // Parameters for "refined start" k-means. PARAM_FLAG("refined_start", "Use the refined initial point strategy by Bradley " "and Fayyad to choose initial points.", "r"); PARAM_INT_IN("samplings", "Number of samplings to perform for refined start " "(use when --refined_start is specified).", "S", 100); PARAM_DOUBLE_IN("percentage", "Percentage of dataset to use for each refined " "start sampling (use when --refined_start is specified).", "p", 0.02); PARAM_FLAG("kmeans_plus_plus", "Use the k-means++ initialization strategy to " "choose initial points.", "K"); PARAM_STRING_IN("algorithm", "Algorithm to use for the Lloyd iteration " "('naive', 'pelleg-moore', 'elkan', 'hamerly', 'dualtree', or " "'dualtree-covertree').", "a", "naive"); // Given the type of initial partition policy, figure out the empty cluster // policy and run k-means. template<typename InitialPartitionPolicy> void FindEmptyClusterPolicy(util::Params& params, util::Timers& timers, const InitialPartitionPolicy& ipp); // Given the initial partitionining policy and empty cluster policy, figure out // the Lloyd iteration step type and run k-means. template<typename InitialPartitionPolicy, typename EmptyClusterPolicy> void FindLloydStepType(util::Params& params, util::Timers& timers, const InitialPartitionPolicy& ipp); // Given the template parameters, sanitize/load input and run k-means. template<typename InitialPartitionPolicy, typename EmptyClusterPolicy, template<class, class> class LloydStepType> void RunKMeans(util::Params& params, util::Timers& timers, const InitialPartitionPolicy& ipp); void BINDING_FUNCTION(util::Params& params, util::Timers& timers) { // Initialize random seed. if (params.Get<int>("seed") != 0) math::RandomSeed((size_t) params.Get<int>("seed")); else math::RandomSeed((size_t) std::time(NULL)); RequireOnlyOnePassed(params, { "refined_start", "kmeans_plus_plus" }, true, "Only one initialization strategy can be specified!", true); // Now, start building the KMeans type that we'll be using. Start with the // initial partition policy. The call to FindEmptyClusterPolicy<> results in // a call to RunKMeans<> and the algorithm is completed. if (params.Has("refined_start")) { RequireParamValue<int>(params, "samplings", [](int x) { return x > 0; }, true, "number of samplings must be positive"); const int samplings = params.Get<int>("samplings"); RequireParamValue<double>(params, "percentage", [](double x) { return x > 0.0 && x <= 1.0; }, true, "percentage to " "sample must be greater than 0.0 and less than or equal to 1.0"); const double percentage = params.Get<double>("percentage"); FindEmptyClusterPolicy<RefinedStart>(params, timers, RefinedStart(samplings, percentage)); } else if (params.Has("kmeans_plus_plus")) { FindEmptyClusterPolicy<KMeansPlusPlusInitialization>(params, timers, KMeansPlusPlusInitialization()); } else { FindEmptyClusterPolicy<SampleInitialization>(params, timers, SampleInitialization()); } } // Given the type of initial partition policy, figure out the empty cluster // policy and run k-means. template<typename InitialPartitionPolicy> void FindEmptyClusterPolicy(util::Params& params, util::Timers& timers, const InitialPartitionPolicy& ipp) { if (params.Has("allow_empty_clusters") || params.Has("kill_empty_clusters")) { RequireOnlyOnePassed(params, { "allow_empty_clusters", "kill_empty_clusters" }, true); } if (params.Has("allow_empty_clusters")) { FindLloydStepType<InitialPartitionPolicy, AllowEmptyClusters>(params, timers, ipp); } else if (params.Has("kill_empty_clusters")) { FindLloydStepType<InitialPartitionPolicy, KillEmptyClusters>(params, timers, ipp); } else { FindLloydStepType<InitialPartitionPolicy, MaxVarianceNewCluster>(params, timers, ipp); } } // Given the initial partitionining policy and empty cluster policy, figure out // the Lloyd iteration step type and run k-means. template<typename InitialPartitionPolicy, typename EmptyClusterPolicy> void FindLloydStepType(util::Params& params, util::Timers& timers, const InitialPartitionPolicy& ipp) { RequireParamInSet<string>(params, "algorithm", { "elkan", "hamerly", "pelleg-moore", "dualtree", "dualtree-covertree", "naive" }, true, "unknown k-means algorithm"); const string algorithm = params.Get<string>("algorithm"); if (algorithm == "elkan") { RunKMeans<InitialPartitionPolicy, EmptyClusterPolicy, ElkanKMeans>(params, timers, ipp); } else if (algorithm == "hamerly") { RunKMeans<InitialPartitionPolicy, EmptyClusterPolicy, HamerlyKMeans>( params, timers, ipp); } else if (algorithm == "pelleg-moore") { RunKMeans<InitialPartitionPolicy, EmptyClusterPolicy, PellegMooreKMeans>(params, timers, ipp); } else if (algorithm == "dualtree") { RunKMeans<InitialPartitionPolicy, EmptyClusterPolicy, DefaultDualTreeKMeans>(params, timers, ipp); } else if (algorithm == "dualtree-covertree") { RunKMeans<InitialPartitionPolicy, EmptyClusterPolicy, CoverTreeDualTreeKMeans>(params, timers, ipp); } else if (algorithm == "naive") { RunKMeans<InitialPartitionPolicy, EmptyClusterPolicy, NaiveKMeans>(params, timers, ipp); } } // Given the template parameters, sanitize/load input and run k-means. template<typename InitialPartitionPolicy, typename EmptyClusterPolicy, template<class, class> class LloydStepType> void RunKMeans(util::Params& params, util::Timers& timers, const InitialPartitionPolicy& ipp) { // Now, do validation of input options. if (!params.Has("initial_centroids")) { RequireParamValue<int>(params, "clusters", [](int x) { return x > 0; }, true, "number of clusters must be positive"); } else { ReportIgnoredParam(params, {{ "initial_centroids", true }}, "clusters"); } int clusters = params.Get<int>("clusters"); if (clusters == 0 && params.Has("initial_centroids")) { Log::Info << "Detecting number of clusters automatically from input " << "centroids." << endl; } RequireParamValue<int>(params, "max_iterations", [](int x) { return x >= 0; }, true, "maximum iterations must be positive or 0 (for no limit)"); const int maxIterations = params.Get<int>("max_iterations"); // Make sure we have an output file if we're not doing the work in-place. RequireOnlyOnePassed(params, { "in_place", "output", "centroid" }, false, "no results will be saved"); arma::mat dataset = params.Get<arma::mat>("input"); // Load our dataset. arma::mat centroids; const bool initialCentroidGuess = params.Has("initial_centroids"); // Load initial centroids if the user asked for it. if (initialCentroidGuess) { centroids = std::move(params.Get<arma::mat>("initial_centroids")); if (clusters == 0) clusters = centroids.n_cols; ReportIgnoredParam(params, {{ "refined_start", true }}, "initial_centroids"); if (!params.Has("refined_start")) Log::Info << "Using initial centroid guesses." << endl; } timers.Start("clustering"); KMeans<metric::EuclideanDistance, InitialPartitionPolicy, EmptyClusterPolicy, LloydStepType> kmeans(maxIterations, metric::EuclideanDistance(), ipp); if (params.Has("output") || params.Has("in_place")) { // We need to get the assignments. arma::Row<size_t> assignments; kmeans.Cluster(dataset, clusters, assignments, centroids, false, initialCentroidGuess); timers.Stop("clustering"); // Now figure out what to do with our results. if (params.Has("in_place")) { // Add the column of assignments to the dataset; but we have to convert // them to type double first. arma::rowvec converted(assignments.n_elem); for (size_t i = 0; i < assignments.n_elem; ++i) converted(i) = (double) assignments(i); dataset.insert_rows(dataset.n_rows, converted); // Save the dataset. params.MakeInPlaceCopy("output", "input"); params.Get<arma::mat>("output") = std::move(dataset); } else { if (params.Has("labels_only")) { // Save only the labels. TODO: figure out how to get this to output an // arma::Mat<size_t> instead of an arma::mat. params.Get<arma::mat>("output") = arma::conv_to<arma::mat>::from(assignments); } else { // Convert the assignments to doubles. arma::rowvec converted(assignments.n_elem); for (size_t i = 0; i < assignments.n_elem; ++i) converted(i) = (double) assignments(i); dataset.insert_rows(dataset.n_rows, converted); // Now save, in the different file. params.Get<arma::mat>("output") = std::move(dataset); } } } else { // Just save the centroids. kmeans.Cluster(dataset, clusters, centroids, initialCentroidGuess); timers.Stop("clustering"); } // Should we write the centroids to a file? if (params.Has("centroid")) params.Get<arma::mat>("centroid") = std::move(centroids); }
16,907
5,481
#include "Newton6DOFConstraint.h" #include "NewtonPhysicsWorld.h" #include "UrhoNewtonConversions.h" #include "dCustomSixdof.h" #include "Urho3D/Core/Context.h" namespace Urho3D { NewtonSixDofConstraint::NewtonSixDofConstraint(Context* context) : NewtonConstraint(context) { } NewtonSixDofConstraint::~NewtonSixDofConstraint() { } void NewtonSixDofConstraint::RegisterObject(Context* context) { context->RegisterFactory<NewtonSixDofConstraint>(DEF_PHYSICS_CATEGORY.c_str()); URHO3D_COPY_BASE_ATTRIBUTES(NewtonConstraint); } void NewtonSixDofConstraint::SetPitchLimits(float minLimit, float maxLimit) { if (pitchLimits_ != Vector2(minLimit, maxLimit)) { pitchLimits_.x_ = minLimit; pitchLimits_.y_ = maxLimit; if (newtonJoint_) { static_cast<dCustomSixdof*>(newtonJoint_)->SetPitchLimits(pitchLimits_.x_, pitchLimits_.y_); } else MarkDirty(); } } void NewtonSixDofConstraint::SetPitchLimits(const Vector3& limits) { SetPitchLimits(limits.x_, limits.y_); } void NewtonSixDofConstraint::SetYawLimits(float minLimit, float maxLimit) { if (yawLimits_ != Vector2(minLimit, maxLimit)) { yawLimits_.x_ = minLimit; yawLimits_.y_ = maxLimit; if (newtonJoint_) { static_cast<dCustomSixdof*>(newtonJoint_)->SetYawLimits(yawLimits_.x_, yawLimits_.y_); } else MarkDirty(); } } void NewtonSixDofConstraint::SetYawLimits(const Vector3& limits) { SetYawLimits(limits.x_, limits.y_); } void NewtonSixDofConstraint::SetRollLimits(float minLimit, float maxLimit) { if (rollLimits_ != Vector2(minLimit, maxLimit)) { rollLimits_.x_ = minLimit; rollLimits_.y_ = maxLimit; if (newtonJoint_) { static_cast<dCustomSixdof*>(newtonJoint_)->SetRollLimits(rollLimits_.x_, rollLimits_.y_); } else MarkDirty(); } } void NewtonSixDofConstraint::SetRollLimits(const Vector3& limits) { SetRollLimits(limits.x_, limits.y_); } void NewtonSixDofConstraint::DrawDebugGeometry(DebugRenderer* debug, bool depthTest) { NewtonConstraint::DrawDebugGeometry(debug, depthTest); } void NewtonSixDofConstraint::buildConstraint() { newtonJoint_ = new dCustomSixdof(UrhoToNewton(GetOwnBuildWorldFrame()), UrhoToNewton(GetOtherBuildWorldFrame()), GetOwnNewtonBody(), GetOtherNewtonBody()); } bool NewtonSixDofConstraint::applyAllJointParams() { if (!NewtonConstraint::applyAllJointParams()) return false; static_cast<dCustomSixdof*>(newtonJoint_)->SetLinearLimits(dVector(M_LARGE_VALUE, M_LARGE_VALUE, M_LARGE_VALUE)*-1.0f, dVector(M_LARGE_VALUE, M_LARGE_VALUE, M_LARGE_VALUE)); static_cast<dCustomSixdof*>(newtonJoint_)->SetPitchLimits(pitchLimits_.x_ * dDegreeToRad, pitchLimits_.y_* dDegreeToRad); static_cast<dCustomSixdof*>(newtonJoint_)->SetYawLimits(yawLimits_.x_* dDegreeToRad, yawLimits_.y_* dDegreeToRad); static_cast<dCustomSixdof*>(newtonJoint_)->SetRollLimits(rollLimits_.x_* dDegreeToRad, rollLimits_.y_* dDegreeToRad); return true; } }
3,450
1,246