hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
1f53000bf8e6e30c3a82f53ae863bf695939fab9
11,496
cpp
C++
neural_network.cpp
codextension/neuralnetwork
ea3e59c32908a578f0e4cae53b7ae658306922da
[ "Apache-2.0" ]
null
null
null
neural_network.cpp
codextension/neuralnetwork
ea3e59c32908a578f0e4cae53b7ae658306922da
[ "Apache-2.0" ]
null
null
null
neural_network.cpp
codextension/neuralnetwork
ea3e59c32908a578f0e4cae53b7ae658306922da
[ "Apache-2.0" ]
null
null
null
// // Created by elie on 20.10.18. // #include "neural_network.h" namespace cx { neural_network::neural_network(bool with_bias, double learning_rate, method_type meth_type, int input_size, int output_size, vector<int> hidden_layers_data, float accuracy) { this->current_iteration = 0; this->training_data = {}; this->match_range = accuracy; this->meth_type = meth_type; this->learning_rate = learning_rate; current_brain = brain(input_size, output_size, hidden_layers_data, with_bias); } void neural_network::initialize_data(vector<map<value_type, vector<float>>> data) { training_data.clear(); for (map<value_type, vector<float>> instance : data) { data_holder dataHolder; dataHolder.add_input(instance.at(INPUT)); dataHolder.expected_outputs = instance.at(OUTPUT); training_data.push_back(dataHolder); } } long neural_network::think() { return think(LONG_MAX); } long neural_network::think(long max_nb_iterations) { switch (meth_type) { case SGD: return think_sgd(max_nb_iterations); case BATCH: return think_batch(max_nb_iterations); case MINI_BATCH: return think_minibatch(max_nb_iterations); default: return think_sgd(max_nb_iterations); } } void neural_network::guess() { eval_fwd_propagation(); } bool neural_network::not_all_true(vector<bool> states) { bool result = true; for (auto &&state : states) { result &= state; } return !result; } bool neural_network::values_matching(vector<neuron> neurons, vector<float> expected_values) { bool result = true; for (int i = 0; i < neurons.size(); i++) { neuron n = neurons.at(i); result &= (abs(expected_values.at(i) - n.activationValue())) <= match_range; } return result; } long neural_network::think_batch(long max_nb_iterations) { vector<bool> instanceState; for (int u = 0; u < training_data.size(); u++) { instanceState.push_back(false); } while (not_all_true(instanceState) && current_iteration < max_nb_iterations) { current_iteration++; map<string, double> all_deltas; for (int u = 0; u < training_data.size(); u++) { current_brain.load(training_data.at(u)); eval_fwd_propagation(); training_data[u] = current_brain.unload(); map<string, vector<double>> gradients = eval_gradients(); map<string, double> d_weights = delta_weights(gradients); if (all_deltas.empty()) { all_deltas.insert(d_weights.begin(), d_weights.end()); map<string, double>::iterator it; for (it = all_deltas.begin(); it != all_deltas.end(); it++) { it->second = it->second / training_data.size(); } } else { map<string, double>::iterator it; for (it = all_deltas.begin(); it != all_deltas.end(); it++) { it->second += (d_weights.at(it->first) / training_data.size()); } } } for (int u = 0; u < training_data.size(); u++) { current_brain.load(training_data.at(u)); update_weights(all_deltas); // training_data[u] = current_brain.unload(); instanceState[u] = values_matching(current_brain.layers[current_brain.layers.size() - 1], current_brain.expected_output_values); } } return current_iteration; } long neural_network::think_minibatch(long max_nb_iterations) { vector<bool> instanceState; for (int u = 0; u < training_data.size(); u++) { instanceState.push_back(false); } while (not_all_true(instanceState) && current_iteration < max_nb_iterations) { current_iteration++; int counter = 0; while (counter < training_data.size()) { map<string, double> all_deltas; int new_batch_size = batch_size; int upper_limit = counter + new_batch_size; if ((training_data.size() - upper_limit < new_batch_size)) { new_batch_size += (training_data.size() - upper_limit); upper_limit += (training_data.size() - upper_limit); } for (int u = counter; u < upper_limit; u++) { current_brain.load(training_data.at(u)); eval_fwd_propagation(); training_data[u] = current_brain.unload(); map<string, vector<double>> gradients = eval_gradients(); map<string, double> d_weights = delta_weights(gradients); if (all_deltas.empty()) { all_deltas.insert(d_weights.begin(), d_weights.end()); map<string, double>::iterator it; for (it = all_deltas.begin(); it != all_deltas.end(); it++) { it->second = it->second / new_batch_size; } } else { map<string, double>::iterator it; for (it = all_deltas.begin(); it != all_deltas.end(); it++) { it->second += (d_weights.at(it->first) / new_batch_size); } } } for (int u = counter; u < upper_limit; u++) { current_brain.load(training_data.at(u)); update_weights(all_deltas); instanceState[u] = values_matching(current_brain.layers[current_brain.layers.size() - 1], current_brain.expected_output_values); } counter += upper_limit; } } return current_iteration; } long neural_network::think_sgd(long max_nb_iterations) { vector<bool> instanceState; for (int u = 0; u < training_data.size(); u++) { instanceState.push_back(false); } while (not_all_true(instanceState) && current_iteration < max_nb_iterations) { current_iteration++; for (int u = 0; u < training_data.size(); u++) { current_brain.load(training_data.at(u)); eval_fwd_propagation(); map<string, vector<double>> gradients = eval_gradients(); map<string, double> d_weights = delta_weights(gradients); update_weights(d_weights); instanceState[u] = values_matching(current_brain.layers[current_brain.layers.size() - 1], current_brain.expected_output_values); } } return current_iteration; } void neural_network::eval_fwd_propagation() { for (int i = 1; i < current_brain.layers.size(); i++) { for (neuron hidden_neuron : current_brain.layers[i]) { double value = 0.0; if (hidden_neuron.id.find("BN") == string::npos) { for (neuron prev_neuro : current_brain.layers[i - 1]) { vector<synapse> synapses = current_brain.find_by_neuron_id(prev_neuro.id, false, i - 1); for (synapse synapseinstance : synapses) { if (synapseinstance.id.find(hidden_neuron.id) != string::npos) { value += synapseinstance.weight * current_brain.find_by_id(synapseinstance.source_neuron_id).activationValue(); } } } current_brain.update_value(hidden_neuron.id, value); } } } } map<string, double> neural_network::delta_weights(map<string, vector<double>> gradients) { map<string, double> deltasWeight; for (int i = current_brain.layers.size() - 2; i >= 0; i--) { for (int j = 0; j < current_brain.layers[i].size(); j++) { neuron neuron_instance = current_brain.layers[i][j]; vector<double> values = gradients.at("hidden_" + to_string(i + 1)); vector<synapse> outgoing_synapses = current_brain.find_by_neuron_id(neuron_instance.id, false, i); for (int s = 0; s < outgoing_synapses.size(); s++) { synapse synapseinstance = outgoing_synapses[s]; double delta_weight = values[s] * neuron_instance.activationValue(); deltasWeight.insert(pair<string, double>(synapseinstance.id, delta_weight)); } } } return deltasWeight; } void neural_network::update_weights(map<string, double> deltas) { for (int i = current_brain.layers.size() - 2; i >= 0; i--) { for (int j = 0; j < current_brain.layers[i].size(); j++) { neuron neuron_instance = current_brain.layers[i][j]; vector<synapse> outgoing_synapses = current_brain.find_by_neuron_id(neuron_instance.id, false, i); for (auto synapseinstance : outgoing_synapses) { double weight = synapseinstance.weight - (learning_rate * deltas.at(synapseinstance.id)); current_brain.update_synapse(synapseinstance.id, i, weight); } } } } map<string, vector<double>> neural_network::eval_gradients() { map<string, vector<double>> deltas = map<string, vector<double>>(); for (unsigned long i = current_brain.layers.size() - 1; i > 0; i--) { vector<double> deltaHiddenSum = vector<double>(); for (unsigned long z = 0; z < current_brain.layers[i].size(); z++) { neuron neuron_instance = current_brain.layers[i].at(z); if (i == (current_brain.layers.size() - 1)) { deltaHiddenSum.push_back( (neuron_instance.activationValue() - current_brain.expected_output_values[z]) * neuron_instance.activationPrimeValue()); } else { double dhs = 0; vector<synapse> outgoing_synapses = current_brain.find_by_neuron_id(neuron_instance.id, false, i); for (int j = 0; j < outgoing_synapses.size(); j++) { synapse synapseinstance = outgoing_synapses.at(j); dhs += deltas.at("hidden_" + to_string(i + 1))[j] * synapseinstance.weight; } deltaHiddenSum.push_back(dhs * neuron_instance.activationPrimeValue()); } } string label = "hidden_" + to_string(i); deltas.insert(pair<string, vector<double>>(label, deltaHiddenSum)); } return deltas; } neural_network::neural_network() = default; }
42.420664
118
0.534795
[ "vector" ]
1f53bcc3a2d681b3ce08974fd44f272b11dad038
3,793
cpp
C++
src/apps/sudoku/SudokuSolver.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
1,338
2015-01-03T20:06:56.000Z
2022-03-26T13:49:54.000Z
src/apps/sudoku/SudokuSolver.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
15
2015-01-17T22:19:32.000Z
2021-12-20T12:35:00.000Z
src/apps/sudoku/SudokuSolver.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
350
2015-01-08T14:15:27.000Z
2022-03-21T18:14:35.000Z
/* * Copyright 2007, Axel Dörfler, axeld@pinc-software.de. All rights reserved. * Distributed under the terms of the MIT License. */ #include "SudokuSolver.h" #include "SudokuField.h" #include "Stack.h" struct SolutionStep { public: SolutionStep(const SudokuField* field); SolutionStep(const SolutionStep& other); ~SolutionStep(); void ToFirstUnset(); bool ToNextUnset(); void SetSolvedFields(); SudokuField* Field() { return fField; } uint32 X() { return fX; } uint32 Y() { return fY; } private: SudokuField* fField; uint32 fX; uint32 fY; }; typedef std::vector<SolutionStep*> StepList; uint32 bit_count(uint32 value) { uint32 count = 0; while (value > 0) { if (value & 1) count++; value >>= 1; } return count; } // #pragma mark - SolutionStep::SolutionStep(const SudokuField* _field) { fField = new SudokuField(*_field); fX = 0; fY = 0; } SolutionStep::SolutionStep(const SolutionStep& other) { fField = new SudokuField(*other.fField); fX = other.fX; fY = other.fY; } SolutionStep::~SolutionStep() { delete fField; } void SolutionStep::ToFirstUnset() { for (uint32 y = 0; y < fField->Size(); y++) { for (uint32 x = 0; x < fField->Size(); x++) { if (!fField->ValueAt(x, y)) { uint32 validMask = fField->ValidMaskAt(x, y); if (bit_count(validMask) == 1) { // If the chosen value is already solved, we set its // value here and go on - this makes sure the first // unset we return has actually more than one possible // value uint32 value = 0; while ((validMask & (1UL << value)) == 0) { value++; } fField->SetValueAt(x, y, value + 1, true); continue; } fX = x; fY = y; return; } } } } bool SolutionStep::ToNextUnset() { for (uint32 y = fY; y < fField->Size(); y++) { for (uint32 x = 0; x < fField->Size(); x++) { if (y == fY && x == 0) { x = fX; continue; } if (!fField->ValueAt(x, y)) { fX = x; fY = y; return true; } } } return false; } // #pragma mark - SudokuSolver::SudokuSolver(SudokuField* field) : fField(field) { } SudokuSolver::SudokuSolver() : fField(NULL) { } SudokuSolver::~SudokuSolver() { // we don't own the field but the solutions _MakeEmpty(); } void SudokuSolver::_MakeEmpty() { for (uint32 i = 0; i < fSolutions.size(); i++) { delete fSolutions[i]; } } void SudokuSolver::SetTo(SudokuField* field) { fField = field; } void SudokuSolver::ComputeSolutions() { _MakeEmpty(); // We need to check if generating a solution is affordable with a // brute force algorithm like this one uint32 set = 0; for (uint32 y = 0; y < fField->Size(); y++) { for (uint32 x = 0; x < fField->Size(); x++) { if (fField->ValueAt(x, y)) set++; } } if (set < fField->Size() * fField->Size() / 6) return; Stack<SolutionStep*> stack; SolutionStep* step = new SolutionStep(fField); step->ToFirstUnset(); stack.Push(step); uint32 count = 0; // brute force version while (stack.Pop(&step)) { uint32 x = step->X(); uint32 y = step->Y(); uint32 validMask = step->Field()->ValidMaskAt(x, y); count++; if (step->ToNextUnset()) { if (validMask != 0) { // generate further steps for (uint32 i = 0; i < fField->Size(); i++) { if ((validMask & (1UL << i)) == 0) continue; SolutionStep* next = new SolutionStep(*step); next->Field()->SetValueAt(x, y, i + 1, true); stack.Push(next); } } } else if (step->Field()->IsSolved()) fSolutions.push_back(new SudokuField(*step->Field())); delete step; } //printf("evaluated %lu steps\n", count); } uint32 SudokuSolver::CountSolutions() { return fSolutions.size(); } SudokuField* SudokuSolver::SolutionAt(uint32 index) { return fSolutions[index]; }
16.140426
77
0.614553
[ "vector" ]
1f53f6812547249ee33cc5dd424e4ab9d557de41
7,112
cpp
C++
ShaderParser/ShaderSignatureParser.cpp
pocketgems/XLE2
82771e9ab1fc3b12927f1687bbe05d4f7dce8765
[ "MIT" ]
3
2018-05-17T08:39:39.000Z
2020-12-09T13:20:26.000Z
ShaderParser/ShaderSignatureParser.cpp
pocketgems/XLE2
82771e9ab1fc3b12927f1687bbe05d4f7dce8765
[ "MIT" ]
null
null
null
ShaderParser/ShaderSignatureParser.cpp
pocketgems/XLE2
82771e9ab1fc3b12927f1687bbe05d4f7dce8765
[ "MIT" ]
1
2021-11-14T08:50:15.000Z
2021-11-14T08:50:15.000Z
// Distributed under the MIT License (See // accompanying file "LICENSE" or the website // http://www.opensource.org/licenses/mit-license.php) #include "ShaderSignatureParser.h" #include "NodeGraphSignature.h" #include "NodeGraph.h" // (just required for s_resultName) #include "AntlrHelper.h" #include "Grammar/ShaderLexer.h" #include "Grammar/ShaderParser.h" #include "Grammar/ShaderTreeWalk.h" #include "../Utility/StringUtils.h" #include "../Utility/StringFormat.h" #include "../Utility/Streams/Stream.h" #include <assert.h> #include <vector> // #include <iostream> struct SSPFormalArg { StringId _name, _type, _semantic; unsigned _directionFlags; }; struct SSPFunction { StringId _name, _returnType, _returnSemantic; unsigned _firstArg, _lastArg; unsigned _hasImplementation; }; struct SSPParameterStruct { StringId _name; VariableId _firstParameter, _lastParameter; }; namespace ShaderSourceParser { class WorkingInterfaceStructure { public: GraphLanguage::ShaderFragmentSignature _signature; std::vector<std::pair<uint64_t, StringId>> _stringTableToId; std::vector<std::string> _stringTable; std::vector<GraphLanguage::NodeGraphSignature::Parameter> _parameterTable; std::vector<GraphLanguage::UniformBufferSignature::Parameter> _variableTable; std::string GetString(StringId id) const { return id != ~0u ? _stringTable[id] : std::string(); } }; static pANTLR3_BASE_TREE BuildAST(struct ShaderParser_Ctx_struct& parser) { using namespace ShaderSourceParser::AntlrHelper; ExceptionContext exceptionContext; auto result = parser.entrypoint(&parser).tree; if (!exceptionContext._exceptions._errors.empty()) Throw(ShaderSourceParser::Exceptions::ParsingFailure(MakeIteratorRange(exceptionContext._exceptions._errors))); return result; } GraphLanguage::ShaderFragmentSignature ParseHLSL(StringSection<char> sourceCode) { using namespace ShaderSourceParser::AntlrHelper; AntlrPtr<struct ANTLR3_INPUT_STREAM_struct> inputStream = antlr3StringStreamNew( (ANTLR3_UINT8*)sourceCode.begin(), ANTLR3_ENC_8BIT, (unsigned)sourceCode.size(), (ANTLR3_UINT8*)"InputStream"); if (!inputStream) Throw(::Exceptions::BasicLabel("Unable to create the input stream due to malloc() failure\n")); AntlrPtr<struct ShaderLexer_Ctx_struct> lxr = ShaderLexerNew(inputStream); // CLexerNew is generated by ANTLR if (!lxr) Throw(::Exceptions::BasicLabel("Unable to create the lexer due to malloc() failure\n")); AntlrPtr<struct ANTLR3_COMMON_TOKEN_STREAM_struct> tokenStream = antlr3CommonTokenStreamSourceNew(ANTLR3_SIZE_HINT, TOKENSOURCE(lxr)); if (!tokenStream) Throw(::Exceptions::BasicLabel("Out of memory trying to allocate token stream\n")); AntlrPtr<struct ShaderParser_Ctx_struct> psr = ShaderParserNew(tokenStream); // CParserNew is generated by ANTLR3 if (!psr) Throw(::Exceptions::BasicLabel("Out of memory trying to allocate parser\n")); auto* ast = BuildAST(*psr); if (!ast) Throw(::Exceptions::BasicLabel("Could not build AST from shader fragment input")); // StructureDescription(std::cout, ast); auto* strTree = ast->toStringTree(ast); (void)strTree; AntlrPtr<struct ANTLR3_COMMON_TREE_NODE_STREAM_struct> nodes = antlr3CommonTreeNodeStreamNewTree(ast, ANTLR3_SIZE_HINT); AntlrPtr<struct ShaderTreeWalk_Ctx_struct> evalTree = ShaderTreeWalkNew(nodes); ExceptionContext exceptionContext; WorkingInterfaceStructure sig; evalTree->_userData = &sig; evalTree->entrypoint(evalTree); if (!exceptionContext._exceptions._errors.empty()) Throw(ShaderSourceParser::Exceptions::ParsingFailure(MakeIteratorRange(exceptionContext._exceptions._errors))); return sig._signature; } } extern "C" StringId String_Register(const void* ctx, const pANTLR3_BASE_TREE str) { auto* w = (ShaderSourceParser::WorkingInterfaceStructure*)((ShaderTreeWalk_Ctx_struct*)ctx)->_userData; auto s = ShaderSourceParser::AntlrHelper::AsString<char>(str->toString(str)); auto h = Hash64(s); auto existing = LowerBound(w->_stringTableToId, h); if (existing != w->_stringTableToId.end() && existing->first == h) return existing->second; auto result = (StringId)w->_stringTable.size(); w->_stringTable.push_back(s); w->_stringTableToId.insert(existing, {h, result}); return result; } extern "C" FormalArgId FormalArg_Register(const void* ctx, struct SSPFormalArg arg) { auto* w = (ShaderSourceParser::WorkingInterfaceStructure*)((ShaderTreeWalk_Ctx_struct*)ctx)->_userData; auto result = (StringId)w->_parameterTable.size(); const unsigned directionFlagOut = 1<<1; const unsigned directionFlagIn = 1<<0; if (arg._directionFlags & directionFlagIn) w->_parameterTable.push_back( GraphLanguage::NodeGraphSignature::Parameter { w->GetString(arg._type), w->GetString(arg._name), GraphLanguage::ParameterDirection::In, w->GetString(arg._semantic) }); if (arg._directionFlags & directionFlagOut) w->_parameterTable.push_back( GraphLanguage::NodeGraphSignature::Parameter { w->GetString(arg._type), w->GetString(arg._name), GraphLanguage::ParameterDirection::Out, w->GetString(arg._semantic) }); return result; } extern "C" VariableId Variable_Register(const void* ctx, StringId name, StringId type, StringId semantic) { auto* w = (ShaderSourceParser::WorkingInterfaceStructure*)((ShaderTreeWalk_Ctx_struct*)ctx)->_userData; auto result = (StringId)w->_variableTable.size(); w->_variableTable.push_back( GraphLanguage::UniformBufferSignature::Parameter{ w->GetString(name), w->GetString(type), w->GetString(semantic) }); return result; } extern "C" FunctionId Function_Register(const void* ctx, struct SSPFunction* func) { auto* w = (ShaderSourceParser::WorkingInterfaceStructure*)((ShaderTreeWalk_Ctx_struct*)ctx)->_userData; GraphLanguage::NodeGraphSignature result; auto name = w->GetString(func->_name); auto returnType = w->GetString(func->_returnType); if (!returnType.empty() && !XlEqString(returnType, "void")) result.AddParameter( GraphLanguage::NodeGraphSignature::Parameter { returnType, GraphLanguage::s_resultName, GraphLanguage::ParameterDirection::Out, w->GetString(func->_returnSemantic) }); for (unsigned p=func->_firstArg; p<=func->_lastArg; ++p) result.AddParameter(w->_parameterTable[p]); w->_signature._functions.emplace_back(std::make_pair(name, std::move(result))); return (FunctionId)(w->_signature._functions.size()-1); } extern "C" ParameterStructId ParameterStruct_Register(const void* ctx, struct SSPParameterStruct* paramStruct) { auto* w = (ShaderSourceParser::WorkingInterfaceStructure*)((ShaderTreeWalk_Ctx_struct*)ctx)->_userData; GraphLanguage::UniformBufferSignature result; auto name = w->GetString(paramStruct->_name); for (unsigned p=paramStruct->_firstParameter; p<=paramStruct->_lastParameter; ++p) result._parameters.push_back(w->_variableTable[p]); w->_signature._uniformBuffers.emplace_back(std::make_pair(name, std::move(result))); return (ParameterStructId)(w->_signature._uniformBuffers.size()-1); }
39.955056
136
0.759421
[ "vector" ]
1f5f2a0102d31660e7f2b684871501427977f010
11,577
cpp
C++
Sources/Elastos/LibCore/src/elastos/security/AlgorithmParameters.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/LibCore/src/elastos/security/AlgorithmParameters.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/LibCore/src/elastos/security/AlgorithmParameters.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos 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. //========================================================================= #include "AlgorithmParameters.h" #include "CSecurity.h" #include "org/apache/harmony/security/fortress/CEngine.h" using Org::Apache::Harmony::Security::Fortress::CEngine; using Org::Apache::Harmony::Security::Fortress::ISpiAndProvider; namespace Elastos { namespace Security { static AutoPtr<IEngine> InitEngine() { AutoPtr<CEngine> e; CEngine::NewByFriend(String("AlgorithmParameters")/*SERVICE*/, (CEngine**)&e); return e; } const String AlgorithmParameters::SEVICE("AlgorithmParameters"); AutoPtr<IEngine> AlgorithmParameters::ENGINE = InitEngine(); CAR_INTERFACE_IMPL(AlgorithmParameters, Object, IAlgorithmParameters) AlgorithmParameters::AlgorithmParameters( /* [in] */ AlgorithmParametersSpi* algPramSpi, /* [in] */ IProvider* provider, /* [in] */ const String& algorithm) { mProvider = provider; mAlgorithm = algorithm; mSpiImpl = algPramSpi; } /** * Returns a new instance of {@code AlgorithmParameters} for the specified * algorithm. * * @param algorithm * the name of the algorithm to use. * @return a new instance of {@code AlgorithmParameters} for the specified * algorithm. * @throws NoSuchAlgorithmException * if the specified algorithm is not available. * @throws NullPointerException * if {@code algorithm} is {@code NULL}. */ ECode AlgorithmParameters::GetInstance( /* [in] */ const String& algorithm, /* [out] */ IAlgorithmParameters** result) /*throws NoSuchAlgorithmException*/ { VALIDATE_NOT_NULL(result); if (algorithm == NULL) { // throw new NullPointerException("algorithm == NULL"); return E_NULL_POINTER_EXCEPTION; } AutoPtr<ISpiAndProvider> sap; ENGINE->GetInstance(algorithm, NULL, (ISpiAndProvider**)&sap); AutoPtr<IInterface> spi; sap->GetSpi((IInterface**)&spi); AutoPtr<IProvider> p; sap->GetProvider((IProvider**)&p); *result = new AlgorithmParameters((AlgorithmParametersSpi*)IObject::Probe(spi), p, algorithm); REFCOUNT_ADD(*result); return NOERROR; } /** * Returns a new instance of {@code AlgorithmParameters} from the specified * provider for the specified algorithm. * * @param algorithm * the name of the algorithm to use. * @param provider * name of the provider of the {@code AlgorithmParameters}. * @return a new instance of {@code AlgorithmParameters} for the specified * algorithm. * @throws NoSuchAlgorithmException * if the specified algorithm is not available. * @throws NoSuchProviderException * if the specified provider is not available. * @throws IllegalArgumentException if {@code provider == NULL || provider.isEmpty()} * @throws NullPointerException * if {@code algorithm} is {@code NULL}. */ ECode AlgorithmParameters::GetInstance( /* [in] */ const String& algorithm, /* [in] */ const String& provider, /* [out] */ IAlgorithmParameters** result) /*throws NoSuchAlgorithmException, NoSuchProviderException*/ { VALIDATE_NOT_NULL(result); *result = NULL; if (provider == NULL || provider.IsEmpty()) { // throw new IllegalArgumentException("provider == NULL || provider.isEmpty()"); return E_ILLEGAL_ARGUMENT_EXCEPTION; } AutoPtr<ISecurity> security; CSecurity::AcquireSingleton((ISecurity**)&security); AutoPtr<IProvider> p; security->GetProvider(provider, (IProvider**)&p); if (p == NULL) { // throw new NoSuchProviderException(provider); return E_NO_SUCH_PROVIDER_EXCEPTION; } return GetInstance(algorithm, p, result); } /** * Returns a new instance of {@code AlgorithmParameters} from the specified * provider for the specified algorithm. The {@code provider} supplied does * not have to be registered. * * @param algorithm * the name of the algorithm to use. * @param provider * the provider of the {@code AlgorithmParameters}. * @return a new instance of {@code AlgorithmParameters} for the specified * algorithm. * @throws NoSuchAlgorithmException * if the specified algorithm is not available. * @throws NullPointerException * if {@code algorithm} is {@code NULL}. * @throws IllegalArgumentException if {@code provider == NULL} */ ECode AlgorithmParameters::GetInstance( /* [in] */ const String& algorithm, /* [in] */ IProvider* provider, /* [out] */ IAlgorithmParameters** result) /*throws NoSuchAlgorithmException*/ { VALIDATE_NOT_NULL(result); if (provider == NULL) { // throw new IllegalArgumentException("provider == NULL"); return E_ILLEGAL_ARGUMENT_EXCEPTION; } if (algorithm == NULL) { // throw new NullPointerException("algorithm == NULL"); return E_NULL_POINTER_EXCEPTION; } AutoPtr<IInterface> spi; ENGINE->GetInstance(algorithm, provider, NULL, (IInterface**)&spi); *result = new AlgorithmParameters((AlgorithmParametersSpi*)IObject::Probe(spi), provider, algorithm); REFCOUNT_ADD(*result); return NOERROR; } /** * Returns the provider associated with this {@code AlgorithmParameters}. * * @return the provider associated with this {@code AlgorithmParameters}. */ ECode AlgorithmParameters::GetProvider( /* [out] */ IProvider** result) { VALIDATE_NOT_NULL(result); *result = mProvider; REFCOUNT_ADD(*result); return NOERROR; } /** * Returns the name of the algorithm. * * @return the name of the algorithm. */ ECode AlgorithmParameters::GetAlgorithm( /* [out] */ String* algorithm) { VALIDATE_NOT_NULL(algorithm); *algorithm = mAlgorithm; return NOERROR; } /** * Initializes this {@code AlgorithmParameters} with the specified {@code * AlgorithmParameterSpec}. * * @param paramSpec * the parameter specification. * @throws InvalidParameterSpecException * if this {@code AlgorithmParameters} has already been * initialized or the given {@code paramSpec} is not appropriate * for initializing this {@code AlgorithmParameters}. */ ECode AlgorithmParameters::Init( /* [in] */ IAlgorithmParameterSpec* paramSpec) /*throws InvalidParameterSpecException*/ { if (mInitialized) { // throw new InvalidParameterSpecException("Parameter has already been initialized"); return E_INVALIDPARAMETERSPEC_EXCEPTION; } mSpiImpl->EngineInit(paramSpec); mInitialized = TRUE; return NOERROR; } /** * Initializes this {@code AlgorithmParameters} with the specified {@code * byte[]} using the default decoding format for parameters. The default * encoding format is ASN.1. * * @param params * the encoded parameters. * @throws IOException * if this {@code AlgorithmParameters} has already been * initialized, or the parameter could not be encoded. */ ECode AlgorithmParameters::Init( /* [in] */ ArrayOf<Byte>* params) /*throws IOException*/ { if (mInitialized) { // throw new IOException("Parameter has already been initialized"); return E_IO_EXCEPTION; } mSpiImpl->EngineInit(params); mInitialized = TRUE; return NOERROR; } /** * Initializes this {@code AlgorithmParameters} with the specified {@code * byte[]} using the specified decoding format. * * @param params * the encoded parameters. * @param format * the name of the decoding format. * @throws IOException * if this {@code AlgorithmParameters} has already been * initialized, or the parameter could not be encoded. */ ECode AlgorithmParameters::Init( /* [in] */ ArrayOf<Byte>* params, /* [in] */ const String& format) /*throws IOException*/ { if (mInitialized) { // throw new IOException("Parameter has already been initialized"); return E_IO_EXCEPTION; } mSpiImpl->EngineInit(params, format); mInitialized = TRUE; return NOERROR; } /** * Returns the {@code AlgorithmParameterSpec} for this {@code * AlgorithmParameters}. * * @param paramSpec * the type of the parameter specification in which this * parameters should be converted. * @return the {@code AlgorithmParameterSpec} for this {@code * AlgorithmParameters}. * @throws InvalidParameterSpecException * if this {@code AlgorithmParameters} has already been * initialized, or if this parameters could not be converted to * the specified class. */ ECode AlgorithmParameters::GetParameterSpec( /* [in] */ const ClassID& paramSpec, /* [out] */ IInterface** result) /*throws InvalidParameterSpecException*/ { VALIDATE_NOT_NULL(result); if (!mInitialized) { // throw new InvalidParameterSpecException("Parameter has not been initialized"); return E_INVALIDPARAMETERSPEC_EXCEPTION; } return mSpiImpl->EngineGetParameterSpec(paramSpec, result); } /** * Returns this {@code AlgorithmParameters} in their default encoding * format. The default encoding format is ASN.1. * * @return the encoded parameters. * @throws IOException * if this {@code AlgorithmParameters} has already been * initialized, or if this parameters could not be encoded. */ ECode AlgorithmParameters::GetEncoded( /* [out] */ ArrayOf<Byte>** result) /*throws IOException*/ { VALIDATE_NOT_NULL(result); if (!mInitialized) { // throw new IOException("Parameter has not been initialized"); return E_IO_EXCEPTION; } return mSpiImpl->EngineGetEncoded(result); } /** * Returns this {@code AlgorithmParameters} in the specified encoding * format. * * @param format * the name of the encoding format. * @return the encoded parameters. * @throws IOException * if this {@code AlgorithmParameters} has already been * initialized, or if this parameters could not be encoded. */ ECode AlgorithmParameters::GetEncoded( /* [in] */ const String& format, /* [out] */ ArrayOf<Byte>** result) /*throws IOException*/ { VALIDATE_NOT_NULL(result); if (!mInitialized) { // throw new IOException("Parameter has not been initialized"); return E_IO_EXCEPTION; } return mSpiImpl->EngineGetEncoded(format, result); } /** * Returns a string containing a concise, human-readable description of this * {@code AlgorithmParameters}. * * @return a printable representation for this {@code AlgorithmParameters}. */ // @Override ECode AlgorithmParameters::ToString( /* [out] */ String* result) { VALIDATE_NOT_NULL(result); if (!mInitialized) { *result = String(NULL); return NOERROR; } return mSpiImpl->EngineToString(result); } } // namespace Security } // namespace Elastos
33.459538
107
0.672195
[ "object" ]
48f85eb86b8109bf4183517c64ffc753be05f5c0
778
cpp
C++
src/Lucia/Graphics/Text/Simple.cpp
Polynominal/Lucy3D
a55fc331bc509a69ad7fb70a1eda70c409d22271
[ "MIT" ]
1
2017-02-22T23:47:22.000Z
2017-02-22T23:47:22.000Z
src/Lucia/Graphics/Text/Simple.cpp
Polynominal/Lucy3D
a55fc331bc509a69ad7fb70a1eda70c409d22271
[ "MIT" ]
null
null
null
src/Lucia/Graphics/Text/Simple.cpp
Polynominal/Lucy3D
a55fc331bc509a69ad7fb70a1eda70c409d22271
[ "MIT" ]
null
null
null
#include "Lucia/Graphics/Text/Simple.h" using namespace Lucia; using namespace Graphics; void Text::Simple::generate(std::string path_to_font,unsigned int fontSize,float width,float height) { remove(); text = new Graphics::Text(path_to_font); text->generate(); projection = new Maths::Ortho(0.0f, width,0.0f,height, 0.01f, 100.0f); text->setProjection(projection); instance = new Graphics::Text::Instance(text); instance->setSize(fontSize); instance->setWrapWidth(width); print = new Graphics::Text::Render(instance); print->moveTo(0.0f,2.0f - ((fontSize/height)),1.2f); print->generate(); }; void Text::Simple::remove() { delete text;text=nullptr; delete instance;instance=nullptr; delete print; print=nullptr; };
28.814815
100
0.690231
[ "render" ]
48fdad65abd72b097b3783a1d2d4ec8a44ee0ef9
7,860
hpp
C++
include/inekf/state_estimator.hpp
mayataka/invariant-ekf
775d9ab5ac7599fe2fd983b8a907c241c7d3a8e0
[ "BSD-3-Clause" ]
1
2022-03-28T12:38:09.000Z
2022-03-28T12:38:09.000Z
include/inekf/state_estimator.hpp
mayataka/inekf
775d9ab5ac7599fe2fd983b8a907c241c7d3a8e0
[ "BSD-3-Clause" ]
null
null
null
include/inekf/state_estimator.hpp
mayataka/inekf
775d9ab5ac7599fe2fd983b8a907c241c7d3a8e0
[ "BSD-3-Clause" ]
null
null
null
#ifndef INEKF_STATE_ESTIMATOR_HPP_ #define INEKF_STATE_ESTIMATOR_HPP_ #include <string> #include <vector> #include <cstdio> #include <limits> #include "Eigen/Core" #include "Eigen/StdVector" #include "inekf/macros.hpp" #include "inekf/inekf.hpp" #include "inekf/robot_state.hpp" #include "inekf/noise_params.hpp" #include "inekf/observations.hpp" #include "inekf/robot_model.hpp" #include "inekf/contact_estimator.hpp" #include "inekf/low_pass_filter.hpp" #include "inekf/state_estimator_settings.hpp" namespace inekf { class StateEstimator { public: using Vector3d = Eigen::Matrix<double, 3, 1>; using Vector6d = Eigen::Matrix<double, 6, 1>; using Matrix3d = Eigen::Matrix<double, 3, 3>; using Matrix6d = Eigen::Matrix<double, 6, 6>; StateEstimator(const StateEstimatorSettings& settings); StateEstimator(); ~StateEstimator(); INEKF_USE_DEFAULT_COPY_CONSTRUCTOR(StateEstimator); INEKF_USE_DEFAULT_COPY_ASSIGN_OPERATOR(StateEstimator); INEKF_USE_DEFAULT_MOVE_CONSTRUCTOR(StateEstimator); INEKF_USE_DEFAULT_MOVE_ASSIGN_OPERATOR(StateEstimator); void resetParameters(const StateEstimatorSettings& settings); /// /// @brief Initializes the state estimator. /// @param[in] base_pos Base position. /// @param[in] base_quat Base orientation expressed by quaternion (x, y, z, w). /// @param[in] base_lin_vel_world Base linear velocity expressed in the world /// coordinate. Default is Eigen::Vector3d::Zero(). /// @param[in] imu_gyro_bias Initial guess of the IMU gyro bias. Default is /// Eigen::Vector3d::Zero(). /// @param[in] imu_lin_accel_bias Initial guess of the IMU linear acceleration /// bias. Default is Eigen::Vector3d::Zero(). /// void init(const Eigen::Vector3d& base_pos, const Eigen::Vector4d& base_quat, const Eigen::Vector3d& base_lin_vel_world=Eigen::Vector3d::Zero(), const Eigen::Vector3d& imu_gyro_bias=Eigen::Vector3d::Zero(), const Eigen::Vector3d& imu_lin_accel_bias=Eigen::Vector3d::Zero()); /// /// @brief Initializes the state estimator. /// @param[in] base_pos Base position. /// @param[in] base_quat Base orientation expressed by quaternion (x, y, z, w). /// @param[in] qJ Raw measurement of the joint positions. /// @param[in] ground_height Ground height. /// @param[in] base_lin_vel_world Base linear velocity expressed in the world /// coordinate. Default is Eigen::Vector3d::Zero(). /// @param[in] imu_gyro_bias Initial guess of the IMU gyro bias. Default is /// Eigen::Vector3d::Zero(). /// @param[in] imu_lin_accel_bias Initial guess of the IMU linear acceleration /// bias. Default is Eigen::Vector3d::Zero(). /// void init(const Eigen::Vector3d& base_pos, const Eigen::Vector4d& base_quat, const Eigen::VectorXd& qJ, const double ground_height=0, const Eigen::Vector3d& base_lin_vel_world=Eigen::Vector3d::Zero(), const Eigen::Vector3d& imu_gyro_bias=Eigen::Vector3d::Zero(), const Eigen::Vector3d& imu_lin_accel_bias=Eigen::Vector3d::Zero()); /// /// @brief Updates the state estimation. /// @param[in] imu_gyro_raw Raw measurement of the base angular velocity /// expressed in the body local coordinate from IMU gyro sensor. /// @param[in] imu_lin_accel_raw Raw measurement of the base linear /// acceleration expressed in the body local coordinate from IMU accelerometer. /// @param[in] qJ Raw measurement of the joint positions. /// @param[in] dqJ Raw measurement of the joint velocities. /// @param[in] tauJ Raw measurement of the joint torques. /// @param[in] f_raw Raw measurement of the foot force sensor. /// void update(const Eigen::Vector3d& imu_gyro_raw, const Eigen::Vector3d& imu_lin_accel_raw, const Eigen::VectorXd& qJ, const Eigen::VectorXd& dqJ, const Eigen::VectorXd& tauJ, const std::vector<double>& f_raw={}); /// /// @brief Updates the state estimation. /// @param[in] imu_gyro_raw Raw measurement of the base angular velocity /// expressed in the body local coordinate from IMU gyro sensor. /// @param[in] imu_lin_accel_raw Raw measurement of the base linear /// acceleration expressed in the body local coordinate from IMU accelerometer. /// @param[in] qJ Raw measurement of the joint positions. /// @param[in] dqJ Raw measurement of the joint velocities. /// @param[in] ddqJ Raw measurement of the joint accelerations. /// @param[in] tauJ Raw measurement of the joint torques. /// @param[in] f_raw Raw measurement of the foot force sensor. /// void update(const Eigen::Vector3d& imu_gyro_raw, const Eigen::Vector3d& imu_lin_accel_raw, const Eigen::VectorXd& qJ, const Eigen::VectorXd& dqJ, const Eigen::VectorXd& ddqJ, const Eigen::VectorXd& tauJ, const std::vector<double>& f_raw={}); /// /// @return const reference to the base position estimate. /// const Eigen::Block<const Eigen::MatrixXd, 3, 1> getBasePositionEstimate() const; /// /// @return const reference to the base orientation estimate expressed by a /// rotation matrix. /// const Eigen::Block<const Eigen::MatrixXd, 3, 3> getBaseRotationEstimate() const; /// /// @return const reference to the base orientation estimate expressed by /// quaternion. /// Eigen::Vector4d getBaseQuaternionEstimate() const; /// /// @return const reference to the base linear velocity estimate expressed in /// the world frame. /// const Eigen::Block<const Eigen::MatrixXd, 3, 1> getBaseLinearVelocityEstimateWorld() const; /// /// @return const reference to the base linear velocity estimate expressed in /// the body local coordinate. /// const Eigen::Vector3d getBaseLinearVelocityEstimateLocal() const; /// /// @return const reference to the base angular velocity estimate expressed in /// the world frame. /// const Eigen::Vector3d& getBaseAngularVelocityEstimateWorld() const; /// /// @return const reference to the base angular velocity estimate expressed in /// the local frame. /// Eigen::Vector3d getBaseAngularVelocityEstimateLocal() const; /// /// @return const reference to the IMU gyro bias estimate. /// const Eigen::VectorBlock<const Eigen::VectorXd, 3> getIMUGyroBiasEstimate() const; /// /// @return const reference to the IMU linear acceleration bias estimate. /// const Eigen::VectorBlock<const Eigen::VectorXd, 3> getIMULinearAccelerationBiasEstimate() const; /// /// @return const reference to the joint velocity estimates. /// const Eigen::VectorXd& getJointVelocityEstimate() const; /// /// @return const reference to the joint acceleration estimates. /// const Eigen::VectorXd& getJointAccelerationEstimate() const; /// /// @return const reference to the joint torque estimates. /// const Eigen::VectorXd& getJointTorqueEstimate() const; /// /// @return const reference to the conatct force estimates. /// const std::vector<Eigen::Vector3d>& getContactForceEstimate() const; /// /// @return const reference to the conatct probabilities. /// const std::vector<double>& getContactProbability() const; EIGEN_MAKE_ALIGNED_OPERATOR_NEW private: InEKF inekf_; vectorKinematics leg_kinematics_; RobotModel robot_model_; ContactEstimator contact_estimator_; LowPassFilter<double, Eigen::Dynamic> lpf_dqJ_, lpf_ddqJ_, lpf_tauJ_; LowPassFilter<double, 3> lpf_gyro_accel_world_, lpf_lin_accel_world_; double dt_, contact_position_cov_, contact_rotation_cov_; Vector3d imu_gyro_raw_world_, imu_gyro_raw_world_prev_, imu_gyro_accel_world_, imu_gyro_accel_local_, imu_lin_accel_raw_world_, imu_lin_accel_local_; Vector6d imu_raw_; Matrix3d R_; }; } // namespace inekf #endif // INEKF_STATE_ESTIMATOR_HPP_
37.788462
98
0.714377
[ "vector" ]
5b005ce04b284b8242e6c6687b449375c92808bc
11,326
cpp
C++
test/raw_tree.cpp
ghochee/tree
21ee770dd80f71c400a3591f408e15a2dcf4106d
[ "MIT" ]
null
null
null
test/raw_tree.cpp
ghochee/tree
21ee770dd80f71c400a3591f408e15a2dcf4106d
[ "MIT" ]
null
null
null
test/raw_tree.cpp
ghochee/tree
21ee770dd80f71c400a3591f408e15a2dcf4106d
[ "MIT" ]
null
null
null
#include <iostream> #define CATCH_CONFIG_MAIN #include "catch2/catch.hpp" #include <algorithm> #include <functional> #include <iterator> #include <vector> #include "tree/raw_tree.h" #include "raw_tree.h" using namespace detangled; using namespace std; using int_tree = raw_tree<uint32_t>; TEST_CASE("height0", "[integer_tree, raw_tree]") { int_tree t(10); SECTION("accessors") { SECTION("value") { CHECK(*t == 10); *t = 20; CHECK(*t == 20); } SECTION("children") { CHECK(!t.has_parent()); CHECK(!t.has_child<side::left>()); CHECK(!t.has_child<side::right>()); } SECTION("iterator") { CHECK(range_eq(t.inlbegin(), t.inlend(), {10})); } SECTION("size") { CHECK(t.size() == 1); } } SECTION("modifiers") { SECTION("replace") { SECTION("right") { t.replace<side::right>(int_tree(20)); REQUIRE(t.has_child<side::right>()); CHECK(range_eq(t.inlbegin(), t.inlend(), {10, 20})); } SECTION("left") { t.replace<side::left>(int_tree(5)); REQUIRE(t.has_child<side::left>()); CHECK(range_eq(t.inlbegin(), t.inlend(), {5, 10})); } SECTION("both") { t.replace<side::left>(int_tree(5)); t.replace<side::right>(int_tree(20)); CHECK(range_eq(t.inlbegin(), t.inlend(), {5, 10, 20})); } } SECTION("emplace") { SECTION("right") { t.emplace<side::right>(20); REQUIRE(t.has_child<side::right>()); CHECK(range_eq(t.inlbegin(), t.inlend(), {10, 20})); } SECTION("left") { t.emplace<side::left>(5); REQUIRE(t.has_child<side::left>()); CHECK(range_eq(t.inlbegin(), t.inlend(), {5, 10})); } SECTION("both") { t.emplace<side::left>(5); t.emplace<side::right>(20); REQUIRE(t.has_child<side::left>()); REQUIRE(t.has_child<side::right>()); CHECK(range_eq(t.inlbegin(), t.inlend(), {5, 10, 20})); } } } } TEST_CASE("height1", "[integer_tree, raw_tree]") { int_tree t(10); t.emplace<side::left>(5); t.emplace<side::right>(20); SECTION("accessors") { SECTION("value") { CHECK(*t == 10); CHECK(*(t.child<side::left>()) == 5); *(t.child<side::right>()) = 21; CHECK(*(t.child<side::right>()) == 21); } SECTION("children") { CHECK(!t.has_parent()); CHECK(t.has_child<side::left>()); CHECK(t.has_child<side::right>()); CHECK(!t.child<side::left>().has_child<side::left>()); } SECTION("iterator") { CHECK(range_eq(t.inlbegin(), t.inlend(), {5, 10, 20})); } SECTION("size") { CHECK(t.size() == 3); } } SECTION("modifiers") { SECTION("replace") { SECTION("right") { t.replace<side::right>(int_tree(30)); REQUIRE(t.has_child<side::right>()); CHECK(range_eq(t.inlbegin(), t.inlend(), {5, 10, 30})); } SECTION("left") { t.replace<side::left>(int_tree(7)); REQUIRE(t.has_child<side::left>()); CHECK(range_eq(t.inlbegin(), t.inlend(), {7, 10, 20})); } SECTION("both") { t.replace<side::left>(int_tree(8)); t.replace<side::right>(int_tree(21)); CHECK(range_eq(t.inlbegin(), t.inlend(), {8, 10, 21})); } } SECTION("emplace") { SECTION("right") { t.emplace<side::right>(30); REQUIRE(t.has_child<side::right>()); CHECK(range_eq(t.inlbegin(), t.inlend(), {5, 10, 30})); } SECTION("left") { t.emplace<side::left>(7); REQUIRE(t.has_child<side::left>()); CHECK(range_eq(t.inlbegin(), t.inlend(), {7, 10, 20})); } SECTION("both") { t.emplace<side::left>(8); t.emplace<side::right>(21); CHECK(range_eq(t.inlbegin(), t.inlend(), {8, 10, 21})); } } SECTION("reshape") { SECTION("left-left") { t.reshape<side::left, side::left>(); CHECK(range_eq(t.inlbegin(), t.inlend(), {5, 10, 20})); } SECTION("left-right") { t.reshape<side::left, side::right>(); CHECK(range_eq(t.inlbegin(), t.inlend(), {5, 10, 20})); } SECTION("right-left") { t.reshape<side::right, side::left>(); CHECK(range_eq(t.inlbegin(), t.inlend(), {5, 10, 20})); } SECTION("right-right") { t.reshape<side::right, side::right>(); CHECK(range_eq(t.inlbegin(), t.inlend(), {5, 10, 20})); } SECTION("all") { t.reshape<side::left, side::left>(); t.reshape<side::right, side::right>(); t.reshape<side::right, side::left>(); t.reshape<side::left, side::left>(); CHECK(range_eq(t.inlbegin(), t.inlend(), {5, 10, 20})); } } SECTION("detach") { SECTION("left") { auto child = t.detach<side::left>(); CHECK(!t.has_child<side::left>()); CHECK(range_eq(t.inlbegin(), t.inlend(), {10, 20})); CHECK(*child == 5); } SECTION("both") { auto child = t.detach<side::right>(); CHECK(!t.has_child<side::right>()); CHECK(range_eq(t.inlbegin(), t.inlend(), {5, 10})); CHECK(*child == 20); auto left_child = t.detach<side::left>(); CHECK(t.size() == 1); CHECK(range_eq(t.inlbegin(), t.inlend(), {10})); CHECK(*left_child == 5); } } SECTION("move") { int_tree child(t.detach<side::left>()); CHECK(!t.has_child<side::left>()); CHECK(range_eq(t.inlbegin(), t.inlend(), {10, 20})); CHECK(*child == 5); } SECTION("swap") { int_tree t2(15); t2.emplace<side::left>(7); swap(t.child<side::right>(), t2.child<side::left>()); CHECK(range_eq(t.inlbegin(), t.inlend(), {5, 10, 7})); CHECK(range_eq(t2.inlbegin(), t2.inlend(), {20, 15})); } SECTION("flip") { t.flip(); CHECK(range_eq(t.inlbegin(), t.inlend(), {20, 10, 5})); t.detach<side::left>(); t.flip(); CHECK(range_eq(t.inlbegin(), t.inlend(), {5, 10})); t.detach<side::left>(); CHECK(range_eq(t.inlbegin(), t.inlend(), {10})); t.flip(); CHECK(range_eq(t.inlbegin(), t.inlend(), {10})); } } } TEST_CASE("pointed multiple nodes", "[integer_tree, raw_tree]") { int_tree t(10); int_tree l(20); l.replace<side::left>(int_tree(5)); l.replace<side::right>(int_tree(50)); int_tree r(30); r.replace<side::left>(int_tree(35)); r.replace<side::right>(int_tree(20)); t.replace<side::left>(std::move(l)); t.replace<side::right>(std::move(r)); test_tree_invariants(t); std::initializer_list<int_tree::value_type> inl_values = {5, 20, 50, 10, 35, 30, 20}; std::initializer_list<int_tree::value_type> prel_values = {10, 20, 5, 50, 30, 35, 20}; CHECK(*t == 10); SECTION("children") { REQUIRE(t.has_child<side::left>()); REQUIRE(t.has_child<side::right>()); } SECTION("order") { SECTION("in") { CHECK(range_eq(t.inlbegin(), t.inlend(), inl_values)); } SECTION("pre") { CHECK(range_eq(t.prelbegin(), t.prelend(), prel_values)); } } SECTION("rotate and reshape") { t.rotate<side::right>(); test_tree_invariants(t); CHECK(range_eq(t.inlbegin(), t.inlend(), inl_values)); t.rotate<side::left>(); CHECK(range_eq(t.inlbegin(), t.inlend(), inl_values)); CHECK(range_eq(t.prelbegin(), t.prelend(), prel_values)); t.rotate<side::left>(); CHECK(range_eq(t.inlbegin(), t.inlend(), inl_values)); t.reshape<side::right, side::left>(); CHECK(range_eq(t.inlbegin(), t.inlend(), inl_values)); t.reshape<side::right, side::left>(); CHECK(range_eq(t.inlbegin(), t.inlend(), inl_values)); t.reshape<side::left, side::right>(); CHECK(range_eq(t.inlbegin(), t.inlend(), inl_values)); } SECTION("detach") { REQUIRE(t.has_child<side::left>()); t.detach<side::left>(); CHECK(!t.has_child<side::left>()); REQUIRE(t.has_child<side::right>()); t.detach<side::right>(); CHECK(!t.has_child<side::right>()); t.replace<side::left>(int_tree(35)); REQUIRE(t.has_child<side::left>()); CHECK(*t.child<side::left>() == 35); auto b = t.detach<side::left>(); CHECK(*b == 35); CHECK(!b.has_parent()); } /* SECTION("swap") { std::swap(t.child<side::left>(), t.child<side::right>().child<side::left>()); std::copy(t.inlbegin(), t.inlend(), std::ostream_iterator<uint32_t>(std::cout, " ")); std::cout << "\n"; } */ } TEST_CASE("coarse string", "[string_tree, raw_tree]") { raw_tree<string> t("middle"); CHECK(*t == "middle"); t.replace<side::left>(raw_tree<string>("left")); t.child<side::left>().replace<side::left>(raw_tree<string>("far left")); t.child<side::left>().replace<side::right>(raw_tree<string>("left right")); t.replace<side::right>(raw_tree<string>("right")); t.child<side::right>().replace<side::left>(raw_tree<string>("more right")); t.child<side::right>().replace<side::right>(raw_tree<string>("rightmost")); CHECK(t.size() == 7); test_bst_invariants(t); } TEST_CASE("bst", "[integer_tree, raw_tree]") { int_tree t(10); build_bst(t, 3); CHECK(t.size() == (1 << (3 + 1)) - 1); test_bst_invariants(t); *t = 256; build_bst(t, 7); CHECK(t.size() == (1 << (7 + 1)) - 1); test_bst_invariants(t); *t = 1024; build_bst(t, 10); CHECK(t.size() == (1 << (10 + 1)) - 1); CHECK(t.template has_child<side::right>()); SECTION("reshape") { t.reshape<side::left, side::right>(); test_bst_invariants(t); } SECTION("reshape") { t.reshape<side::right, side::left>(); test_bst_invariants(t); } SECTION("reshape") { t.reshape<side::right, side::right>(); test_bst_invariants(t); } }
30.610811
79
0.477485
[ "vector" ]
5b028a1953958570db5761ca8c33903b81296ac5
3,469
hpp
C++
example/json2/json.hpp
sekiguchi-nagisa/Aquarius-cxx
43c029f4e88eafcbf26766da9451539e8426b757
[ "Apache-2.0" ]
null
null
null
example/json2/json.hpp
sekiguchi-nagisa/Aquarius-cxx
43c029f4e88eafcbf26766da9451539e8426b757
[ "Apache-2.0" ]
null
null
null
example/json2/json.hpp
sekiguchi-nagisa/Aquarius-cxx
43c029f4e88eafcbf26766da9451539e8426b757
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2016 Nagisa Sekiguchi * * 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 AQUARIUS_CXX_JSON2_JSON_H #define AQUARIUS_CXX_JSON2_JSON_H #include <string> #include <unordered_map> #include <vector> #include <functional> #include <memory> namespace json { enum class JSONKind { NIL, BOOL, NUMBER, STRING, ARRAY, OBJECT, }; class JSON { private: JSONKind kind_; protected: explicit JSON(JSONKind kind) : kind_(kind) { } public: virtual ~JSON() = default; JSONKind kind() const { return this->kind_; } bool is(JSONKind kind) const { return this->kind_ == kind; } }; class JSONNull : public JSON { public: JSONNull() : JSON(JSONKind::NIL) {} ~JSONNull() override = default; }; class JSONBool : public JSON { private: bool value_; public: JSONBool(bool value) : JSON(JSONKind::BOOL), value_(value) { } //NOLINT ~JSONBool() override = default; bool value() const { return this->value_; } }; class JSONString : public JSON { private: std::string value_; public: JSONString(std::string &&value) : //NOLINT JSON(JSONKind::STRING), value_(std::move(value)) { } ~JSONString() override = default; const std::string &value() const { return this->value_; } }; class JSONNumber : public JSON { private: double value_; public: JSONNumber(double value) : //NOLINT JSON(JSONKind::NUMBER), value_(value) { } ~JSONNumber() override = default; double value() const { return this->value_; } }; class JSONArray : public JSON { private: std::vector<std::unique_ptr<JSON>> values_; public: JSONArray() : JSON(JSONKind::ARRAY), values_() { } ~JSONArray() override = default; std::vector<std::unique_ptr<JSON>> &value() { return this->values_; } const std::vector<std::unique_ptr<JSON>> &value() const { return this->values_; } }; template <typename T, typename ... A> inline std::unique_ptr<T> make_unique(A && ...arg) { return std::unique_ptr<T>(new T(std::forward<A>(arg)...)); } struct KeyComparator { bool operator()(const std::unique_ptr<JSONString> &x, const std::unique_ptr<JSONString> &y) const { return x->value() == y->value(); } }; struct Hash { std::size_t operator()(const std::unique_ptr<JSONString> &x) const { return std::hash<std::string>()(x->value()); } }; class JSONObject : public JSON { public: using map_type = std::unordered_map<std::unique_ptr<JSONString>, std::unique_ptr<JSON>, Hash, KeyComparator>; private: map_type values_; public: JSONObject() : JSON(JSONKind::OBJECT), values_() { } ~JSONObject() override = default; map_type &value() { return this->values_; } const map_type &value() const { return this->values_; } }; } // namespace json #endif //AQUARIUS_CXX_JSON2_JSON_H
20.772455
113
0.64399
[ "object", "vector" ]
5b048b5ab8f480a11c1529e3865b7715545db70b
6,471
cpp
C++
FloatingMeasure/Measure/PreMeasure.cpp
github-baron/FloatingMeasure
1419d95c168bd7c9927854f0fc8e7c3681b93d2d
[ "MIT" ]
1
2020-11-09T07:13:03.000Z
2020-11-09T07:13:03.000Z
FloatingMeasure/Measure/PreMeasure.cpp
github-baron/FloatingMeasure
1419d95c168bd7c9927854f0fc8e7c3681b93d2d
[ "MIT" ]
3
2020-01-27T16:20:50.000Z
2020-01-31T23:13:53.000Z
FloatingMeasure/Measure/PreMeasure.cpp
github-baron/FloatingMeasure
1419d95c168bd7c9927854f0fc8e7c3681b93d2d
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2020 Michael von Mengershausen * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "Measure/PreMeasure.h" CPreMeasure::CPreMeasure() { // allocate vnExp10 vnExp10 = new vector<int>; vdFactor->resize(pmLast+1); vnExp10->resize(pmLast+1); vstrShort->resize(pmLast+1); vstrLong->resize(pmLast+1); (*vdFactor)[pmFemto]=(1e-15); (*vnExp10)[pmFemto]=(-15); (*vstrShort)[pmFemto]=("f"); (*vstrLong)[pmFemto]=("femto"); (*vdFactor)[pmPiko]=(1e-12); (*vnExp10)[pmPiko]=(-12); (*vstrShort)[pmPiko]=("p"); (*vstrLong)[pmPiko]=("piko"); (*vdFactor)[pmNano]=(1e-9); (*vnExp10)[pmNano]=(-9); (*vstrShort)[pmNano]=("n"); (*vstrLong)[pmNano]=("nano"); (*vdFactor)[pmMicro]=(1e-6); (*vnExp10)[pmMicro]=(-6); (*vstrShort)[pmMicro]=(mu); (*vstrLong)[pmMicro]=("micro"); (*vdFactor)[pmMilli]=(1e-3); (*vnExp10)[pmMilli]=(-3); (*vstrShort)[pmMilli]=("m"); (*vstrLong)[pmMilli]=("milli"); (*vdFactor)[pmCenti]=(1e-2); (*vnExp10)[pmCenti]=(-2); (*vstrShort)[pmCenti]=("c"); (*vstrLong)[pmCenti]=("centi"); (*vdFactor)[pmDeci]=(1e-1); (*vnExp10)[pmDeci]=(-1); (*vstrShort)[pmDeci]=("d"); (*vstrLong)[pmDeci]=("deci"); (*vdFactor)[pmIdent]=(1e+0); (*vnExp10)[pmIdent]=(+0); (*vstrShort)[pmIdent]=(""); (*vstrLong)[pmIdent]=(""); (*vdFactor)[pmDeca]=(1e+1); (*vnExp10)[pmDeca]=(+1); (*vstrShort)[pmDeca]=("da"); (*vstrLong)[pmDeca]=("deca"); (*vdFactor)[pmHecto]=(1e+2); (*vnExp10)[pmHecto]=(+2); (*vstrShort)[pmHecto]=("H"); (*vstrLong)[pmHecto]=("hecto"); (*vdFactor)[pmKilo]=(1e+3); (*vnExp10)[pmKilo]=(+3); (*vstrShort)[pmKilo]=("k"); (*vstrLong)[pmKilo]=("kilo"); (*vdFactor)[pmMega]=(1e+6); (*vnExp10)[pmMega]=(+6); (*vstrShort)[pmMega]=("M"); (*vstrLong)[pmMega]=("mega"); (*vdFactor)[pmGiga]=(1e+9); (*vnExp10)[pmGiga]=(+9); (*vstrShort)[pmGiga]=("G"); (*vstrLong)[pmGiga]=("giga"); (*vdFactor)[pmTera]=(1e+12); (*vnExp10)[pmTera]=(+12); (*vstrShort)[pmTera]=("T"); (*vstrLong)[pmTera]=("tera"); (*vdFactor)[pmPeta]=(1e+15); (*vnExp10)[pmPeta]=(+15); (*vstrShort)[pmPeta]=("P"); (*vstrLong)[pmPeta]=("Peta"); (*vdFactor)[pmExa]=(1e+18); (*vnExp10)[pmExa]=(+18); (*vstrShort)[pmExa]=("E"); (*vstrLong)[pmExa]=("Exa"); (*vdFactor)[pmZetta]=(1e+21); (*vnExp10)[pmZetta]=(+21); (*vstrShort)[pmZetta]=("Z"); (*vstrLong)[pmZetta]=("Zetta"); (*vdFactor)[pmYotta]=(1e+24); (*vnExp10)[pmYotta]=(+24); (*vstrShort)[pmYotta]=("Y"); (*vstrLong)[pmYotta]=("Yotta"); (*vdFactor)[pmUnknown]=(nan("1")); (*vnExp10)[pmUnknown]=(INVALID_EXPONENT); (*vstrShort)[pmUnknown]=(UNKNOWN_SHORT); (*vstrLong)[pmUnknown]=(UNKNOWN_LONG); } CPreMeasure::~CPreMeasure() { vnExp10->clear(); SecureDeleteObjectPointer(vnExp10); } ePreMeasure CPreMeasure::GetIDByFactor(const double dPreMeasureFactor) { // handle extreme cases: //dPreMeasureFactor smaller equal than smallest value of PreMeasure factors if(dPreMeasureFactor <= Factor(pmFirst)) return pmFirst; //dPreMeasureFactor bigger equal than biggest value of PreMeasure factors if(dPreMeasureFactor >= Factor(pmLast-1)) return (ePreMeasure)(pmLast-1); // if we come here iterate over all other PreMeasure factors: // stop in case the remaining factor is between 0.1 and 10 ePreMeasure pmOpt = pmUnknown; for(unsigned int idx = 0; idx < vdFactor->size(); idx++) { // set the limits depending of the consecutive and previous measure: // default is a factor 1000 distance: // there are only factors of 1000 or 10 (ideally) double dLowerLimit = 0.099999999; //ideally 0.1 double dUpperLimit = 10.000000001; //ideally 10 if(idx>0) if( (Factor(idx)/Factor(idx-1)) < 100) dLowerLimit = 0.9; if((Factor(idx+1)/Factor(idx)) < 100) dUpperLimit = 1.1; double dRatio = dPreMeasureFactor/Factor(idx); if( (dLowerLimit < dRatio) && (dRatio < dUpperLimit)) { pmOpt = (ePreMeasure)(idx); break; } } return pmOpt; } ePreMeasure CPreMeasure::GetIDByExp10(const int nExp10) { // at this point: find the closest ePreMeasure optPM = pmFirst; int nAbsDiff = abs(nExp10-Exp10(optPM)); for(unsigned int idx = 0; idx < vnExp10->size(); idx++) if( nAbsDiff > (abs(nExp10-Exp10(idx))) ) { nAbsDiff = abs(nExp10 - Exp10(idx)); optPM = (ePreMeasure)idx; } return optPM; } string CPreMeasure::DebugOut(const int nIndex) { return "Factor = " + to_string(Factor(nIndex)) + "\n" + "Short = " + Short(nIndex) + "\n" + "Long = " + Long(nIndex); } string CPreMeasure::DebugOut(const ePreMeasure PreMeasureEnum) { return DebugOut((int)PreMeasureEnum); }
30.380282
81
0.573173
[ "vector" ]
5b0553b5a6e4f71bdab867bec5ea46a901c67143
1,546
cpp
C++
iit/YarpJS/src/YarpJS_Sound.cpp
robotology/dialog-service
de9e08d8f364b49f5b5a545783be8d5a1fb10bc6
[ "BSD-3-Clause" ]
2
2019-07-10T13:55:31.000Z
2020-04-09T17:13:15.000Z
iit/YarpJS/src/YarpJS_Sound.cpp
robotology/dialog-service
de9e08d8f364b49f5b5a545783be8d5a1fb10bc6
[ "BSD-3-Clause" ]
null
null
null
iit/YarpJS/src/YarpJS_Sound.cpp
robotology/dialog-service
de9e08d8f364b49f5b5a545783be8d5a1fb10bc6
[ "BSD-3-Clause" ]
1
2019-07-12T13:51:03.000Z
2019-07-12T13:51:03.000Z
#include <stdio.h> #include <string> #include "YarpJS_Sound.h" #include <yarp/os/NetInt16.h> #define SAMPLE_RATE 16000 // #define NUM_SECONDS 0.1 #define BIT_DEPTH 16 // #define NUM_SAMPLES ((int)(SAMPLE_RATE*NUM_SECONDS)) #define NUM_SAMPLES 16000 unsigned char pulsecode[ NUM_SAMPLES ]; using namespace v8; Nan::Persistent<v8::FunctionTemplate> YarpJS_Sound::constructor; NAN_METHOD(YarpJS_Sound::Copy) { YarpJS_Sound* obj = Nan::ObjectWrap::Unwrap<YarpJS_Sound>(info.This()); YarpJS_Sound* target = Nan::ObjectWrap::Unwrap<YarpJS_Sound>(info[0]->ToObject()); *obj->getYarpObj() = (*(target->getYarpObj())); } NAN_METHOD(YarpJS_Sound::ToBinary) { YarpJS_Sound* obj = Nan::ObjectWrap::Unwrap<YarpJS_Sound>(info.This()); yarp::os::NetInt16 data[NUM_SAMPLES]; for(int i=0; i<NUM_SAMPLES; i++) data[i] = obj->getYarpObj()->get(i); info.GetReturnValue().Set(Nan::CopyBuffer((char *) data, NUM_SAMPLES*sizeof(yarp::os::NetInt16)).ToLocalChecked()); } NAN_METHOD(YarpJS_Sound::FromBinary) { YarpJS_Sound* obj = Nan::ObjectWrap::Unwrap<YarpJS_Sound>(info.This()); Local<Object> bufferObj = info[0]->ToObject(); yarp::os::NetInt16 *data = (yarp::os::NetInt16*) node::Buffer::Data(bufferObj); obj->getYarpObj()->resize(NUM_SAMPLES,1); obj->getYarpObj()->setFrequency(SAMPLE_RATE); for(int i=0; i<NUM_SAMPLES; i++) obj->getYarpObj()->set(data[i],i); } NAN_METHOD(YarpJS_Sound::GetObjType) { info.GetReturnValue().Set(Nan::New("sound").ToLocalChecked()); }
18.188235
121
0.690815
[ "object" ]
5b0b3afcc0486ebeab2a88b637f700ca38495bd7
2,387
hpp
C++
spline-widget/spline.hpp
sheepsskullcity/opentrack
2742eebed2dd5db4dbf187504c95eca70aa624f2
[ "ISC" ]
1
2021-06-14T09:00:47.000Z
2021-06-14T09:00:47.000Z
spline-widget/spline.hpp
sheepsskullcity/opentrack
2742eebed2dd5db4dbf187504c95eca70aa624f2
[ "ISC" ]
null
null
null
spline-widget/spline.hpp
sheepsskullcity/opentrack
2742eebed2dd5db4dbf187504c95eca70aa624f2
[ "ISC" ]
null
null
null
/* Copyright (c) 2012-2016, Stanislaw Halik <sthalik@misaki.pl> * Permission to use, copy, modify, and/or distribute this * software for any purpose with or without fee is hereby granted, * provided that the above copyright notice and this permission * notice appear in all copies. */ #pragma once #include <QObject> #include <QPointF> #include <QString> #include <QMutex> #include <vector> #include <limits> #include <memory> #include "compat/qcopyable-mutex.hpp" #include "options/options.hpp" using namespace options; #ifdef BUILD_spline_widget # define SPLINE_WIDGET_EXPORT Q_DECL_EXPORT #else # define SPLINE_WIDGET_EXPORT Q_DECL_IMPORT #endif class SPLINE_WIDGET_EXPORT spline final { private: struct settings { bundle b; value<QList<QPointF>> points; settings(bundle b) : b(b), points(b, "points", QList<QPointF>()) {} }; ptr<settings> s; std::vector<float> data; using interp_data_t = decltype(data); static constexpr int value_count = 10000; int precision(const QList<QPointF>& points) const; void update_interp_data(); float getValueInternal(int x); void add_lone_point(); static bool sort_fn(const QPointF& one, const QPointF& two); static QPointF ensure_in_bounds(const QList<QPointF>& points, int i); MyMutex _mutex; QPointF last_input_value; qreal max_x, max_y; volatile bool activep; template<typename t, typename u, typename w> static inline auto clamp(t val, u min, w max) -> decltype (val * min * max) { if (val > max) return max; if (val < min) return min; return val; } public: void reload(); void save(QSettings& s); void save(); void set_bundle(bundle b); qreal maxInput() const; qreal maxOutput() const; spline(); spline(qreal maxx, qreal maxy, const QString& name); float getValue(double x); bool getLastPoint(QPointF& point); void removePoint(int i); void removeAllPoints(); void addPoint(QPointF pt); void movePoint(int idx, QPointF pt); QList<QPointF> getPoints() const; void setMaxInput(qreal MaxInput); void setMaxOutput(qreal MaxOutput); void setTrackingActive(bool blnActive); bundle get_bundle() { return s->b; } using points_t = decltype(s->points.get()); };
24.357143
79
0.666527
[ "vector" ]
5b13d207427ab5386fd7f708b251f2a3aa7e60bd
21,037
cpp
C++
Main/TransformBrushFullDemo.cpp
spt2kor/win32_app_DirectX_
6c35a6af8aa7553f17f91db3fd63bbeb670fc71a
[ "Apache-2.0" ]
null
null
null
Main/TransformBrushFullDemo.cpp
spt2kor/win32_app_DirectX_
6c35a6af8aa7553f17f91db3fd63bbeb670fc71a
[ "Apache-2.0" ]
null
null
null
Main/TransformBrushFullDemo.cpp
spt2kor/win32_app_DirectX_
6c35a6af8aa7553f17f91db3fd63bbeb670fc71a
[ "Apache-2.0" ]
null
null
null
//#ifndef UNICODE //#define UNICODE //#endif // //#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers //// Windows Header Files: //#include <windows.h> // //// C RunTime Header Files //#include <stdlib.h> //#include <malloc.h> //#include <memory.h> //#include <wchar.h> //#include <math.h> // //#include <d2d1.h> //#include <d2d1helper.h> //#include <dwrite.h> //#include <wincodec.h> // ///****************************************************************** //* * //* Macros * //* * //******************************************************************/ // //template<class Interface> //inline void //SafeRelease( // Interface **ppInterfaceToRelease // ) //{ // if (*ppInterfaceToRelease != NULL) // { // (*ppInterfaceToRelease)->Release(); // // (*ppInterfaceToRelease) = NULL; // } //} // //#ifndef Assert //#if defined( DEBUG ) || defined( _DEBUG ) //#define Assert(b) do {if (!(b)) {OutputDebugStringA("Assert: " #b "\n");}} while(0) //#else //#define Assert(b) //#endif //DEBUG || _DEBUG //#endif // //#ifndef HINST_THISCOMPONENT //EXTERN_C IMAGE_DOS_HEADER __ImageBase; //#define HINST_THISCOMPONENT ((HINSTANCE)&__ImageBase) //#endif // // ///****************************************************************** //* * //* DemoApp * //* * //******************************************************************/ //class DemoApp //{ //public: // DemoApp(); // ~DemoApp(); // // HRESULT Initialize(); // // void RunMessageLoop(); // //private: // HRESULT CreateDeviceIndependentResources(); // HRESULT CreateDeviceResources(); // void DiscardDeviceResources(); // // HRESULT OnRender(); // // HRESULT LoadResourceBitmap( // ID2D1RenderTarget *pRenderTarget, // IWICImagingFactory *pIWICFactory, // PCWSTR resourceName, // PCWSTR resourceType, // ID2D1Bitmap **ppBitmap // ); // // void OnResize( // UINT width, // UINT height // ); // // static LRESULT CALLBACK WndProc( // HWND hWnd, // UINT message, // WPARAM wParam, // LPARAM lParam // ); // //private: // HWND m_hwnd; // ID2D1Factory *m_pD2DFactory; // // // Declare WIC members. // IWICImagingFactory *m_pWICFactory; // ID2D1Bitmap *m_pBitmap; // ID2D1HwndRenderTarget *m_pRenderTarget; // ID2D1SolidColorBrush *m_pBlackBrush; // ID2D1BitmapBrush *m_pBitmapBrush; // // ID2D1BitmapBrush *m_pGridPatternBitmapBrush; // //}; // // // ///****************************************************************** //* * //* Provides the entry point for the application. * //* * //******************************************************************/ // //int WINAPI WinMain( // HINSTANCE /* hInstance */, // HINSTANCE /* hPrevInstance */, // LPSTR /* lpCmdLine */, // int /* nCmdShow */ // ) //{ // // Ignore the return value because we want to continue running even in the // // unlikely event that HeapSetInformation fails. // HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0); // // if (SUCCEEDED(CoInitialize(NULL))) // { // { // DemoApp app; // // if (SUCCEEDED(app.Initialize())) // { // app.RunMessageLoop(); // } // } // CoUninitialize(); // } // // return 0; //} // ///****************************************************************** //* * //* Initialize members. * //* * //******************************************************************/ // //DemoApp::DemoApp() : // m_hwnd(NULL), // m_pD2DFactory(NULL), // m_pBitmap(NULL), // m_pRenderTarget(NULL), // m_pBitmapBrush(NULL), // m_pBlackBrush(NULL) //{ //} // ///****************************************************************** //* * //* Release resources. * //* * //******************************************************************/ // //DemoApp::~DemoApp() //{ // SafeRelease(&m_pD2DFactory); // SafeRelease(&m_pBitmap); // SafeRelease(&m_pRenderTarget); // SafeRelease(&m_pBitmapBrush); // SafeRelease(&m_pBlackBrush); //} // ///****************************************************************** //* * //* Create theapplication window and device-independent resources. * //* * //******************************************************************/ // //HRESULT DemoApp::Initialize() //{ // HRESULT hr; // // hr = CreateDeviceIndependentResources(); // if (SUCCEEDED(hr)) // { // // Register the window class. // WNDCLASSEX wcex = { sizeof(WNDCLASSEX) }; // wcex.style = CS_HREDRAW | CS_VREDRAW; // wcex.lpfnWndProc = DemoApp::WndProc; // wcex.cbClsExtra = 0; // wcex.cbWndExtra = sizeof(LONG_PTR); // wcex.hInstance = HINST_THISCOMPONENT; // wcex.hbrBackground = NULL; // wcex.lpszMenuName = NULL; // wcex.hCursor = LoadCursor(NULL, IDC_ARROW); // wcex.lpszClassName = L"D2DDemoApp"; // // RegisterClassEx(&wcex); // // // Create the application window. // // // // Because the CreateWindow function takes its size in pixels, we // // obtain the system DPI and use it to scale the window size. // FLOAT dpiX, dpiY; // m_pD2DFactory->GetDesktopDpi(&dpiX, &dpiY); // // m_hwnd = CreateWindow( // L"D2DDemoApp", // L"Direct2D Demo App", // WS_OVERLAPPEDWINDOW, // CW_USEDEFAULT, // CW_USEDEFAULT, // static_cast<UINT>(ceil(640.f * dpiX / 96.f)), // static_cast<UINT>(ceil(480.f * dpiY / 96.f)), // NULL, // NULL, // HINST_THISCOMPONENT, // this // ); // // hr = m_hwnd ? S_OK : E_FAIL; // if (SUCCEEDED(hr)) // { // ShowWindow(m_hwnd, SW_SHOWNORMAL); // // UpdateWindow(m_hwnd); // } // } // // return hr; //} // // ///****************************************************************** //* * //* This method is used to create resources which are not bound * //* to any device. Their lifetime effectively extends for the * //* duration of the app. * //* * //******************************************************************/ //HRESULT DemoApp::CreateDeviceIndependentResources() //{ // HRESULT hr; // // // Create a WIC factory. // hr = CoCreateInstance( // CLSID_WICImagingFactory, // NULL, // CLSCTX_INPROC_SERVER, // IID_PPV_ARGS(&m_pWICFactory) // ); // // if (SUCCEEDED(hr)) // { // // Create a Direct2D factory. // hr = D2D1CreateFactory( // D2D1_FACTORY_TYPE_SINGLE_THREADED, // &m_pD2DFactory // ); // } // // return hr; //} // ///****************************************************************** //* * //* DemoApp::CreateDeviceResources * //* * //* This method creates resources which are bound to a particular * //* D3D device. It's all centralized here, in case the resources * //* need to be recreated in case of D3D device loss (eg. display * //* change, remoting, removal of video card, etc). * //* * //******************************************************************/ //HRESULT DemoApp::CreateDeviceResources() //{ // HRESULT hr = S_OK; // // if (!m_pRenderTarget) // { // RECT rc; // GetClientRect(m_hwnd, &rc); // D2D1_SIZE_U size = D2D1::SizeU( // rc.right - rc.left, // rc.bottom - rc.top // ); // // // Create a Direct2D render target. // hr = m_pD2DFactory->CreateHwndRenderTarget( // D2D1::RenderTargetProperties(), // D2D1::HwndRenderTargetProperties(m_hwnd, size), // &m_pRenderTarget // ); // // if (SUCCEEDED(hr)) // { // hr = m_pRenderTarget->CreateSolidColorBrush( // D2D1::ColorF(D2D1::ColorF::Black), // &m_pBlackBrush // ); // } // // Create the bitmap to be used by the bitmap brush. // if (SUCCEEDED(hr)) // { // // //hr = LoadResourceBitmap( // // m_pRenderTarget, // // m_pWICFactory, // // L"FERN", // // L"Image", // // &m_pBitmap // // ); // ////----------------------------------------------------------------------------------------- // IWICBitmapDecoder *pDecoder = NULL; // IWICBitmapFrameDecode *pSource = NULL; // IWICStream *pStream = NULL; // IWICFormatConverter *pConverter = NULL; // IWICBitmapScaler *pScaler = NULL; // // HRESULT hr = m_pWICFactory->CreateDecoderFromFilename( // L"C:\\Users\\bkoushik\\Desktop\\DXTraningAll\\DX\\D2D\\Main\\koushik.bmp", // NULL, // GENERIC_READ, // WICDecodeMetadataCacheOnLoad, // &pDecoder // ); // ////----------------------------------------------------------------------------------------- // } // // if (SUCCEEDED(hr)) // { // hr = m_pRenderTarget->CreateBitmapBrush( // m_pBitmap, // &m_pBitmapBrush // ); // } // } // return hr; //} // ///****************************************************************** //* * //* Discard device-specific resources which need to be recreated * //* when a Direct3D device is lost. * //* * //******************************************************************/ // //void DemoApp::DiscardDeviceResources() //{ // SafeRelease(&m_pRenderTarget); // SafeRelease(&m_pBlackBrush); // SafeRelease(&m_pBitmapBrush); //} // ///****************************************************************** //* * //* The main window message loop. * //* * //******************************************************************/ // //void DemoApp::RunMessageLoop() //{ // MSG msg; // // while (GetMessage(&msg, NULL, 0, 0)) // { // TranslateMessage(&msg); // DispatchMessage(&msg); // } //} // // // ///****************************************************************** //* * //* Called whenever the application needs to display the client * //* window. * //* * //* Note that this function will automatically discard * //* device-specific resources if the Direct3D device disappears * //* during execution, and will recreate the resources the * //* next time it's invoked. * //* * //******************************************************************/ //HRESULT DemoApp::OnRender() //{ // // HRESULT hr = CreateDeviceResources(); // // if (SUCCEEDED(hr)) // { // m_pRenderTarget->BeginDraw(); // m_pRenderTarget->SetTransform(D2D1::Matrix3x2F::Identity()); // // // // Define the shape of rectangles to be filled with brushes. // D2D1_RECT_F rcBrushRect = D2D1::RectF(5, 0, 150, 150); // D2D1_RECT_F rcTransformedBrushRect = D2D1::RectF(100, 100, 200, 200); // // // // // Start with a white background. // m_pRenderTarget->Clear(D2D1::ColorF(D2D1::ColorF::White)); // // // Use the bitmap brush to paint the rcBrushRect // m_pRenderTarget->FillRectangle(&rcBrushRect, m_pBitmapBrush); // m_pRenderTarget->DrawRectangle(&rcBrushRect, m_pBlackBrush, 1, NULL); // // // Use the bitmap brush to paint the rcTransformedBrushRect // m_pRenderTarget->FillRectangle( // rcTransformedBrushRect, // m_pBitmapBrush // ); // // // Demonstrate the effect of transforming a bitmap brush. // m_pBitmapBrush->SetTransform( // D2D1::Matrix3x2F::Translation(D2D1::SizeF(50,50)) // ); // // // To see the content of the rcTransformedBrushRect, comment // // out this statement. // m_pRenderTarget->FillRectangle( // &rcTransformedBrushRect, // m_pBitmapBrush // ); // // m_pRenderTarget->DrawRectangle(rcTransformedBrushRect, m_pBlackBrush, 1, NULL); // // hr = m_pRenderTarget->EndDraw(); // // if (hr == D2DERR_RECREATE_TARGET) // { // hr = S_OK; // DiscardDeviceResources(); // } // } // // return hr; //} // // ///****************************************************************** //* * //* If the application receives a WM_SIZE message, this method * //* resizes the render target appropriately. * //* * //******************************************************************/ // //void DemoApp::OnResize(UINT width, UINT height) //{ // if (m_pRenderTarget) // { // // Note: This method can fail, but it's okay to ignore the // // error here -- the error will be repeated on the next call to // // EndDraw. // m_pRenderTarget->Resize(D2D1::SizeU(width, height)); // } //} // // ///****************************************************************** //* * //* * //* The window message handler. * //* * //******************************************************************/ // //LRESULT CALLBACK DemoApp::WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) //{ // LRESULT result = 0; // // if (message == WM_CREATE) // { // LPCREATESTRUCT pcs = (LPCREATESTRUCT)lParam; // DemoApp *pDemoApp = (DemoApp *)pcs->lpCreateParams; // // ::SetWindowLongPtrW( // hwnd, // GWLP_USERDATA, // PtrToUlong(pDemoApp) // ); // // result = 1; // } // else // { // DemoApp *pDemoApp = reinterpret_cast<DemoApp *>(static_cast<LONG_PTR>( // ::GetWindowLongPtrW( // hwnd, // GWLP_USERDATA // ))); // // bool wasHandled = false; // // if (pDemoApp) // { // switch (message) // { // case WM_SIZE: // { // UINT width = LOWORD(lParam); // UINT height = HIWORD(lParam); // pDemoApp->OnResize(width, height); // } // result = 0; // wasHandled = true; // break; // // case WM_DISPLAYCHANGE: // { // InvalidateRect(hwnd, NULL, FALSE); // } // wasHandled = true; // result = 0; // break; // // case WM_PAINT: // { // pDemoApp->OnRender(); // // ValidateRect(hwnd, NULL); // } // wasHandled = true; // result = 0; // break; // // case WM_DESTROY: // { // PostQuitMessage(0); // } // result = 1; // wasHandled = true; // break; // } // } // // if (!wasHandled) // { // result = DefWindowProc(hwnd, message, wParam, lParam); // } // } // // return result; //} // // ///****************************************************************** //* * //* * //* This method will create a Direct2D bitmap from a resource in * //* this DLL. * //* * //******************************************************************/ // //HRESULT DemoApp::LoadResourceBitmap( // ID2D1RenderTarget *pRenderTarget, // IWICImagingFactory *pIWICFactory, // PCWSTR resourceName, // PCWSTR resourceType, // ID2D1Bitmap **ppBitmap // ) //{ // HRESULT hr = S_OK; // IWICBitmapDecoder *pDecoder = NULL; // IWICBitmapFrameDecode *pSource = NULL; // IWICStream *pStream = NULL; // IWICFormatConverter *pConverter = NULL; // // HRSRC imageResHandle = NULL; // HGLOBAL imageResDataHandle = NULL; // void *pImageFile = NULL; // DWORD imageFileSize = 0; // // // Locate the resource. // imageResHandle = FindResourceW(HINST_THISCOMPONENT, resourceName, resourceType); // // hr = imageResHandle ? S_OK : E_FAIL; // if (SUCCEEDED(hr)) // { // // Load the resource. // imageResDataHandle = LoadResource(HINST_THISCOMPONENT, imageResHandle); // // hr = imageResDataHandle ? S_OK : E_FAIL; // } // if (SUCCEEDED(hr)) // { // // Lock it to get a system memory pointer. // pImageFile = LockResource(imageResDataHandle); // // hr = pImageFile ? S_OK : E_FAIL; // } // if (SUCCEEDED(hr)) // { // // Calculate the size. // imageFileSize = SizeofResource(HINST_THISCOMPONENT, imageResHandle); // // hr = imageFileSize ? S_OK : E_FAIL; // // } // if (SUCCEEDED(hr)) // { // // Create a WIC stream to map onto the memory. // hr = pIWICFactory->CreateStream(&pStream); // } // if (SUCCEEDED(hr)) // { // // Initialize the stream with the memory pointer and size. // hr = pStream->InitializeFromMemory( // reinterpret_cast<BYTE*>(pImageFile), // imageFileSize // ); // } // if (SUCCEEDED(hr)) // { // // Create a decoder for the stream. // hr = pIWICFactory->CreateDecoderFromStream( // pStream, // NULL, // WICDecodeMetadataCacheOnLoad, // &pDecoder // ); // } // if (SUCCEEDED(hr)) // { // // Create the initial frame. // hr = pDecoder->GetFrame(0, &pSource); // } // if (SUCCEEDED(hr)) // { // // Convert the image format to 32bppPBGRA // // (DXGI_FORMAT_B8G8R8A8_UNORM + D2D1_ALPHA_MODE_PREMULTIPLIED). // hr = pIWICFactory->CreateFormatConverter(&pConverter); // } // if (SUCCEEDED(hr)) // { // hr = pConverter->Initialize( // pSource, // GUID_WICPixelFormat32bppPBGRA, // WICBitmapDitherTypeNone, // NULL, // 0.f, // WICBitmapPaletteTypeMedianCut // ); // } // if (SUCCEEDED(hr)) // { // // Create a Direct2D bitmap from the WIC bitmap. // hr = pRenderTarget->CreateBitmapFromWicBitmap( // pConverter, // NULL, // ppBitmap // ); // } // // SafeRelease(&pDecoder); // SafeRelease(&pSource); // SafeRelease(&pStream); // SafeRelease(&pConverter); // // return hr; //} // // // // // //
31.165926
96
0.411133
[ "render", "shape" ]
5b144b7c03d0f8b6cb66b790f9ebc5c3745b4de8
2,645
cpp
C++
Hard/336_palindromePairs/336_palindromePairs/main.cpp
yangbingjie/Leetcode
2f1e386cfb8b2d7d49cf0e7dcf0bce1c936e1916
[ "MIT" ]
1
2020-10-08T06:15:37.000Z
2020-10-08T06:15:37.000Z
Hard/336_palindromePairs/336_palindromePairs/main.cpp
yangbingjie/Leetcode
2f1e386cfb8b2d7d49cf0e7dcf0bce1c936e1916
[ "MIT" ]
null
null
null
Hard/336_palindromePairs/336_palindromePairs/main.cpp
yangbingjie/Leetcode
2f1e386cfb8b2d7d49cf0e7dcf0bce1c936e1916
[ "MIT" ]
null
null
null
// // main.cpp // 336_palindromePairs // // Created by bella on 2020/8/6. // Copyright © 2020 bella. All rights reserved. // #include <iostream> #include <vector> #include <string> using namespace std; struct Node { Node* children[26]; int ind; Node(int index=-1){ ind = index; memset(children, 0, sizeof(children)); } }; class Solution { public: bool isPalindrome(string& str, int left, int right){ for (int i = 0; left + i < right - i; ++i) { if (str[left + i] != str[right - i]) { return false; } } return true; } void insertWord(Node*root, string str, int ind){ Node* node = root; for (int i = str.size() - 1; i >= 0; --i) { if (node->children[str[i] - 'a'] == NULL) { node->children[str[i] - 'a'] = new Node(); } node = node->children[str[i] - 'a']; } node->ind = ind; } int findWords(Node* root, string &str, int start, int end){ Node* node = root; for (int i = start; i < end; ++i) { if (node->children[str[i] - 'a'] == NULL) { return -1; } node = node->children[str[i] - 'a']; } return node->ind; } vector<vector<int>> palindromePairs(vector<string>& words) { vector<vector<int>> result; Node* root = new Node(); for (int i = 0; i < words.size(); ++i) { insertWord(root, words[i], i); } vector<int>tmp(2); int ind; for (int i = 0; i < words.size(); ++i) { for (int j = 0; j <= words[i].size(); ++j) { if (isPalindrome(words[i], j, words[i].size() - 1)) { ind = findWords(root, words[i], 0, j); if (-1 != ind && ind != i) { tmp[0] = i; tmp[1] = ind; result.push_back(tmp); } } if (j && isPalindrome(words[i], 0, j - 1)) { ind = findWords(root, words[i], j, words[i].size()); if (-1 != ind && ind != i) { tmp[0] = ind; tmp[1] = i; result.push_back(tmp); } } } } return result; } }; int main(int argc, const char * argv[]) { const int LEN = 5; string arr[LEN]={"abcd","dcba","lls","s","sssll"}; vector<string>vec(arr, arr + LEN); Solution s; s.palindromePairs(vec); return 0; }
29.388889
72
0.428733
[ "vector" ]
5b158e080e68b7b8649284527f20baf2b170cd0e
14,684
cpp
C++
src/cpp/ObjectFileGenerator.cpp
davidstelter/wake-compiler
70be860826a402c293565ca6254b1af3f068f1ad
[ "MIT" ]
1
2015-02-16T02:56:13.000Z
2015-02-16T02:56:13.000Z
src/cpp/ObjectFileGenerator.cpp
davidstelter/wake-compiler
70be860826a402c293565ca6254b1af3f068f1ad
[ "MIT" ]
null
null
null
src/cpp/ObjectFileGenerator.cpp
davidstelter/wake-compiler
70be860826a402c293565ca6254b1af3f068f1ad
[ "MIT" ]
null
null
null
#include "ObjectFileGenerator.h" #include <sstream> void ObjectFileGenerator::generate(Node* tree) { if(forceArrayIdentifier && tree->node_type != NT_TYPEDATA) { forceArrayIdentifier = false; } switch(tree->node_type) { case NT_IMPORT: case NT_IMPORTSET: case NT_IMPORTTARGET: case NT_IMPORTPATH: case NT_ABSTRACT_METHOD: case NT_TYPE_ARRAY: case NT_CURRIED: case NT_CASE: case NT_DEFAULTCASE: case NT_IF_THEN_ELSE: case NT_INCREMENT: case NT_DECREMENT: case NT_SWITCH: return; case NT_PROGRAM: { int i; for(i = 0; i < tree->subnodes; i++) generate(tree->node_data.nodes[i]); } break; case NT_RETRIEVALS_STATEMENTS: { int i; for(i = 0; i < tree->subnodes; i++) { generate(tree->node_data.nodes[i]); file << ";"; } } break; case NT_BLOCK: { table.pushScope(); int i; for(i = 0; i < tree->subnodes; i++) generate(tree->node_data.nodes[i]); table.popScope(); } break; case NT_VALUES: case NT_CLASSSET: case NT_EXPRESSIONS: case NT_INHERITANCESET: case NT_PROVISIONS: case NT_INJECTION: case NT_INJECTION_ARGS: case NT_INJECTION_ARG: case NT_CTOR: case NT_PARENT: case NT_LAMBDA_INVOCATION: { int i; for(i = 0; i < tree->subnodes; i++) generate(tree->node_data.nodes[i]); } break; case NT_AUTOBOX: file << "new "; header->addClassUsage(file.tellp(), tree->node_data.nodes[1]->node_data.string); file << "("; generate(tree->node_data.nodes[0]); file << ")"; break; case NT_CAST: generate(tree->node_data.nodes[1]); break; case NT_CLASS: { table.pushScope(); classname = tree->node_data.nodes[0]->node_data.type->typedata._class.classname; header->addClassUsage(file.tellp(), classname); file << "=function("; vector<Type*>* needs = classes->find(classname)->getNeeds(); for(vector<Type*>::iterator it = needs->begin(); it != needs->end(); ++it) { table.add(*it); if(it != needs->begin()) file << ","; file << table.getAddress(*it); } file << "){"; for(vector<Type*>::iterator it = needs->begin(); it != needs->end(); ++it) { file << "this."; header->addPropertyUsage(file.tellp(), table.getNameForType(*it)); file << "=" << table.getAddress(*it) << ";"; } generate(tree->node_data.nodes[1]); if(tree->subnodes > 2) generate(tree->node_data.nodes[2]); file << "};"; table.popScope(); } break; case NT_PROVISION: file << "this."; header->addPropertyUsage(file.tellp(), classes->find(classname)->getProvisionSymbol(tree->node_data.nodes[0]->node_data.type)); file << "=function(){"; if(tree->subnodes == 1) { string provisionname = tree->node_data.nodes[0]->node_data.type->typedata._class.classname; file << "return new "; header->addClassUsage(file.tellp(), provisionname); file << "("; vector<Type*>* needs = classes->find(provisionname)->getNeeds(); for(vector<Type*>::iterator it = needs->begin(); it != needs->end(); ++it) { if(it != needs->begin()) file << ","; file << "this."; header->addPropertyUsage(file.tellp(), classes->find(classname)->getProvisionSymbol(*it)); file << "()"; } file << ");"; } else { if(tree->node_data.nodes[1]->node_type == NT_TYPEDATA) { file << "return this."; header->addPropertyUsage(file.tellp(), classes->find(classname)->getProvisionSymbol(tree->node_data.nodes[1]->node_data.type)); file << "();"; } else if(tree->node_data.nodes[1]->node_type == NT_STRINGLIT || tree->node_data.nodes[1]->node_type == NT_NUMBERLIT || tree->node_data.nodes[1]->node_type == NT_BOOLLIT) { file << "return "; generate(tree->node_data.nodes[1]); } else { generate(tree->node_data.nodes[1]); } } file << "};"; break; case NT_CTOR_ARGS: break; case NT_CLASSBODY: { int i; // Put ctor args in scope for(i = 0; i < tree->subnodes; i++) if(tree->node_data.nodes[i]->node_type == NT_CTOR) generate(tree->node_data.nodes[i]); // Generate properties for(i = 0; i < tree->subnodes; i++) if(tree->node_data.nodes[i]->node_type == NT_PROPERTY) generate(tree->node_data.nodes[i]); // Generate methods & provisions for(i = 0; i < tree->subnodes; i++) if(tree->node_data.nodes[i]->node_type == NT_METHOD_DECLARATION || tree->node_data.nodes[i]->node_type == NT_PROVISIONS) generate(tree->node_data.nodes[i]); // TODO generate ctor body } break; case NT_METHOD_DECLARATION: table.pushScope(); { string name = tree->node_data.nodes[tree->subnodes - 1]->node_data.string; TypeArray* arguments = (*classes->find(classname)->find(name))->typedata.lambda.arguments; int i; //file << "this." << classes->find(classname)->getAddress(name) << "=function("; file << "this."; header->addPropertyUsage(file.tellp(), name); file << "=function("; for(i = 0; i < arguments->typecount; i++) { if(i != 0) file << ","; table.add(arguments->types[i]); file << table.getAddress(arguments->types[i]); } file << "){"; if(tree->subnodes > 0) generate(tree->node_data.nodes[0]); if(tree->subnodes > 1) generate(tree->node_data.nodes[1]); if(tree->subnodes > 2) generate(tree->node_data.nodes[2]); if(tree->subnodes > 3) generate(tree->node_data.nodes[3]); file << "};"; table.popScope(); } break; //case NT_METHOD_RETURN_TYPE: case NT_METHOD_NAME: break; case NT_METHOD_INVOCATION: { generate(tree->node_data.nodes[0]); string methodclass = tree->node_data.nodes[tree->subnodes - 2]->node_data.string; string name = tree->node_data.nodes[tree->subnodes - 1]->node_data.string; //file << "." << classes->find(methodclass)->getAddress(name) << "("; file << "."; header->addPropertyUsage(file.tellp(), name); file << "("; int argnum = 0; int i; for(i = 1; i < tree->node_data.nodes[1]->subnodes; i += 2) { for(int b = 0; b < tree->node_data.nodes[1]->node_data.nodes[i]->subnodes; b++) { if(argnum != 0) file << ","; generate(tree->node_data.nodes[1]->node_data.nodes[i]->node_data.nodes[b]); argnum++; } } file << ")"; } break; case NT_MEMBER_ACCESS: { generate(tree->node_data.nodes[0]); string name = tree->node_data.nodes[tree->subnodes - 1]->node_data.string; file << "."; header->addPropertyUsage(file.tellp(), name); } break; case NT_RETRIEVAL: { generate(tree->node_data.nodes[2]); string providerclass = tree->node_data.nodes[tree->subnodes - 1]->node_data.string; file << "."; header->addPropertyUsage(file.tellp(), classes->find(providerclass)->getProvisionSymbol(tree->node_data.nodes[0]->node_data.type)); file << "()"; } break; case NT_PROPERTY: { file << "this."; string propname = table.getNameForType(tree->node_data.nodes[0]->node_data.nodes[0]->node_data.type); header->addPropertyUsage(file.tellp(), propname); file << "="; generate(tree->node_data.nodes[0]->node_data.nodes[1]); file << ";"; } break; case NT_DECLARATION: table.add(tree->node_data.nodes[0]->node_data.type); file << "var "; // FALL THROUGH case NT_ASSIGNMENT: generate(tree->node_data.nodes[0]); file << "="; generate(tree->node_data.nodes[1]); break; case NT_VALUED_ASSIGNMENT: file << "("; generate(tree->node_data.nodes[0]); file << "="; generate(tree->node_data.nodes[1]); file << ")"; break; case NT_ADD_ASSIGNMENT: file << "("; generate(tree->node_data.nodes[0]); file << "+="; generate(tree->node_data.nodes[1]); file << ")"; break; case NT_SUB_ASSIGNMENT: file << "("; generate(tree->node_data.nodes[0]); file << "-="; generate(tree->node_data.nodes[1]); file << ")"; break; case NT_MULT_ASSIGNMENT: file << "("; generate(tree->node_data.nodes[0]); file << "*="; generate(tree->node_data.nodes[1]); file << ")"; break; case NT_DIV_ASSIGNMENT: file << "("; generate(tree->node_data.nodes[0]); file << "/="; generate(tree->node_data.nodes[1]); file << ")"; break; case NT_ARRAY_DECLARATION: file << "["; if(tree->subnodes) { int i; for(i = 0; i < tree->subnodes; i++) generate(tree->node_data.nodes[i]); } file << "]"; break; case NT_TYPEDATA: { Type* type = copyType(tree->node_data.type); if(forceArrayIdentifier) type->arrayed = 1; file << table.getAddress(type); } break; case NT_ALIAS: { string name = tree->node_data.string; file << table.getAddress(name); } break; case NT_SUBCLASS: { header->addClassUsage(file.tellp(), tree->node_data.nodes[0]->node_data.type->typedata._class.classname); file << ".call(this"; PropertySymbolTable* proptable = classes->findModifiable(tree->node_data.nodes[0]->node_data.type->typedata._class.classname); for(vector<Type*>::iterator it = proptable->getNeeds()->begin(); it != proptable->getNeeds()->end(); ++it) { file << ","; file << table.getAddress(*it); } file << ");"; } break; case NT_ARRAY_ACCESS: file << "("; forceArrayIdentifier = true; generate(tree->node_data.nodes[0]); forceArrayIdentifier = false; file << ")["; generate(tree->node_data.nodes[1]); file << "]"; break; case NT_EXISTS: file << "if("; generate(tree->node_data.nodes[0]); file << "!=null){"; generate(tree->node_data.nodes[1]); file << "}"; if(tree->subnodes > 2) { file << "else{"; generate(tree->node_data.nodes[2]); file << "};"; } break; case NT_IF_ELSE: file << "if("; generate(tree->node_data.nodes[0]); file << "){"; generate(tree->node_data.nodes[1]); if(tree->subnodes > 2) { file << "}else{"; generate(tree->node_data.nodes[2]); } file << "}"; break; case NT_WHILE: file << "while("; generate(tree->node_data.nodes[0]); file << "){"; generate(tree->node_data.nodes[1]); file << "}"; break; case NT_FOR: file << "for("; table.pushScope(); generate(tree->node_data.nodes[0]); file << ";"; generate(tree->node_data.nodes[1]); file << ";"; generate(tree->node_data.nodes[2]); file << "){"; generate(tree->node_data.nodes[3]); table.popScope(); file << "}"; break; case NT_FOREACH: { table.pushScope(); bool iterating_expression = tree->node_data.nodes[0]->node_type != NT_ALIAS && tree->node_data.nodes[0]->node_type != NT_TYPEDATA; std::stringstream valuestorename; if(iterating_expression) { Type* valuestore = MakeType(TYPE_MATCHALL); valuestorename << valuestore; table.add(valuestorename.str(), valuestore); file << "var " << table.getAddress(valuestorename.str()) << "="; generate(tree->node_data.nodes[0]); file << ";"; } Type* indexer = MakeType(TYPE_MATCHALL); Type* lowered = MakeType(TYPE_MATCHALL); std::stringstream indexername; indexername << indexer; table.add(indexername.str(), indexer); table.add(tree->node_data.nodes[2]->node_data.string, lowered); file << "for(var " << table.getAddress(indexername.str()) << "=0;"; file << table.getAddress(indexername.str()) << " < "; if(iterating_expression) file << table.getAddress(valuestorename.str()); else generate(tree->node_data.nodes[0]); file << ".length; " << table.getAddress(indexername.str()) << "++){"; file << "var " << table.getAddress(tree->node_data.nodes[2]->node_data.string) << "="; if(iterating_expression) file << table.getAddress(valuestorename.str()); else generate(tree->node_data.nodes[0]); file << "[" << table.getAddress(indexername.str()) << "];"; generate(tree->node_data.nodes[1]); file << "}"; table.popScope(); } break; case NT_BREAK: file << "break;"; break; case NT_CONTINUE: file << "continue;"; break; case NT_THIS: file << "this"; break; case NT_RETURN: file << "return "; if(tree->subnodes) generate(tree->node_data.nodes[0]); //file << ";"; break; case NT_INVERT: file << "(!"; generate(tree->node_data.nodes[0]); file << ")"; break; case NT_MULTIPLY: file << "("; generate(tree->node_data.nodes[0]); file << "*"; generate(tree->node_data.nodes[1]); file << ")"; break; case NT_DIVIDE: file << "("; generate(tree->node_data.nodes[0]); file << "/"; generate(tree->node_data.nodes[1]); file << ")"; break; case NT_ADD: file << "("; generate(tree->node_data.nodes[0]); file << "+"; generate(tree->node_data.nodes[1]); file << ")"; break; case NT_SUBTRACT: file << "("; generate(tree->node_data.nodes[0]); file << "-"; generate(tree->node_data.nodes[1]); file << ")"; break; case NT_LESSTHAN: file << "("; generate(tree->node_data.nodes[0]); file << "<"; generate(tree->node_data.nodes[1]); file << ")"; break; case NT_GREATERTHAN: file << "("; generate(tree->node_data.nodes[0]); file << ">"; generate(tree->node_data.nodes[1]); file << ")"; break; case NT_LESSTHANEQUAL: file << "("; generate(tree->node_data.nodes[0]); file << "<="; generate(tree->node_data.nodes[1]); file << ")"; break; case NT_GREATERTHANEQUAL: file << "("; generate(tree->node_data.nodes[0]); file << ">="; generate(tree->node_data.nodes[1]); file << ")"; break; case NT_EQUALITY: file << "("; generate(tree->node_data.nodes[0]); file << "=="; generate(tree->node_data.nodes[1]); file << ")"; break; case NT_INEQUALITY: file << "("; generate(tree->node_data.nodes[0]); file << "!="; generate(tree->node_data.nodes[1]); file << ")"; break; case NT_AND: file << "("; generate(tree->node_data.nodes[0]); file << "&"; generate(tree->node_data.nodes[1]); file << ")"; break; case NT_OR: file << "("; generate(tree->node_data.nodes[0]); file << "|"; generate(tree->node_data.nodes[1]); file << ")"; break; case NT_NUMBERLIT: file << tree->node_data.number; break; case NT_BOOLLIT: file << (tree->node_data.number ? "1" : "0"); break; case NT_STRINGLIT: file << '"'; for(int i = 0; i < strlen(tree->node_data.string); i++) { switch(tree->node_data.string[i]) { case '\n': file << "\\n"; break; case '"': file << "\\\""; break; default: file << tree->node_data.string[i]; } } file << '"'; break; case NT_NOTHING: file << "null"; break; } }
25.716287
176
0.599087
[ "vector" ]
5b2bd68e295415c2409fb237e6cf6d6e8b6e0409
82,710
cpp
C++
src/function/TextCodec.cpp
Alexxu1024/Backup_kanzi
441c6f5f05c65df3374009abc08dc418c3b741ab
[ "Apache-2.0" ]
null
null
null
src/function/TextCodec.cpp
Alexxu1024/Backup_kanzi
441c6f5f05c65df3374009abc08dc418c3b741ab
[ "Apache-2.0" ]
null
null
null
src/function/TextCodec.cpp
Alexxu1024/Backup_kanzi
441c6f5f05c65df3374009abc08dc418c3b741ab
[ "Apache-2.0" ]
null
null
null
/* Copyright 2011-2017 Frederic Langlet 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 <algorithm> #include <cstring> #include <stdexcept> #include <sstream> #include "TextCodec.hpp" #include "../Global.hpp" using namespace kanzi; // 1024 of the most common English words with at least 2 chars. // Each char is 6 bit encoded: 0 to 31. Add 32 to a letter starting a word (MSB). // TheBeAndOfInToHaveItThatFor... const byte TextCodec::DICT_EN_1024[] = { byte(0xCC), byte(0x71), byte(0x21), byte(0x12), byte(0x03), byte(0x43), byte(0xB8), byte(0x5A), byte(0x0D), byte(0xCC), byte(0xED), byte(0x88), byte(0x4C), byte(0x7A), byte(0x13), byte(0xCC), byte(0x70), byte(0x13), byte(0x94), byte(0xE4), byte(0x78), byte(0x39), byte(0x49), byte(0xC4), byte(0x9C), byte(0x05), byte(0x44), byte(0xB8), byte(0xDC), byte(0x80), byte(0x20), byte(0x3C), byte(0x80), byte(0x62), byte(0x04), byte(0xE1), byte(0x51), byte(0x3D), byte(0x84), byte(0x85), byte(0x89), byte(0xC0), byte(0x0F), byte(0x31), byte(0xC4), byte(0x62), byte(0x04), byte(0xB6), byte(0x39), byte(0x42), byte(0xC3), byte(0xD8), byte(0x73), byte(0xAE), byte(0x46), byte(0x20), byte(0x0D), byte(0xB0), byte(0x06), byte(0x23), byte(0x3B), byte(0x31), byte(0xC8), byte(0x4B), byte(0x60), byte(0x12), byte(0xA1), byte(0x2B), byte(0x14), byte(0x08), byte(0x78), byte(0x0D), byte(0x62), byte(0x54), byte(0x4E), byte(0x32), byte(0xD3), byte(0x93), byte(0xC8), byte(0x71), byte(0x36), byte(0x1C), byte(0x04), byte(0xF3), byte(0x1C), byte(0x42), byte(0x11), byte(0xD8), byte(0x72), byte(0x02), byte(0x1E), byte(0x61), byte(0x13), byte(0x98), byte(0x85), byte(0x44), byte(0x9C), byte(0x04), byte(0xA0), byte(0x44), byte(0x49), byte(0xC8), byte(0x32), byte(0x71), byte(0x11), byte(0x88), byte(0xE3), byte(0x04), byte(0xB1), byte(0x8B), byte(0x94), byte(0x47), byte(0x61), byte(0x11), byte(0x13), byte(0x62), byte(0x0B), byte(0x2F), byte(0x23), byte(0x8C), byte(0x12), byte(0x11), byte(0x02), byte(0x01), byte(0x44), byte(0x84), byte(0xCC), byte(0x71), byte(0x11), byte(0x13), byte(0x31), byte(0xD1), byte(0x39), byte(0x41), byte(0x87), byte(0xCC), byte(0x42), byte(0xCB), byte(0xD8), byte(0x71), byte(0x0D), byte(0xD8), byte(0xE4), byte(0x4A), byte(0xCC), byte(0x71), byte(0x0C), byte(0xE0), byte(0x44), byte(0xF4), byte(0x3E), byte(0xE5), byte(0x8D), byte(0xB9), byte(0x44), byte(0xE8), byte(0x35), byte(0x33), byte(0xA9), byte(0x51), byte(0x24), byte(0xE2), byte(0x39), byte(0x42), byte(0xC3), byte(0xB9), byte(0x51), byte(0x11), byte(0xB8), byte(0xB0), byte(0xF3), byte(0x1C), byte(0x83), byte(0x4A), byte(0x8C), byte(0x06), byte(0x36), byte(0x01), byte(0x8C), byte(0xC7), byte(0x00), byte(0xDA), byte(0xC8), byte(0x28), byte(0x4B), byte(0x93), byte(0x1C), byte(0x44), byte(0x67), byte(0x39), byte(0x6C), byte(0xC7), byte(0x10), byte(0xDA), byte(0x13), byte(0x4A), byte(0xF1), byte(0x0E), byte(0x3C), byte(0xB1), byte(0x33), byte(0x58), byte(0xEB), byte(0x0E), byte(0x44), byte(0x4C), byte(0xC7), byte(0x11), byte(0x21), byte(0x21), byte(0x10), byte(0x43), byte(0x6D), byte(0x39), byte(0x6D), byte(0x80), byte(0x35), byte(0x39), byte(0x48), byte(0x45), byte(0x24), byte(0xED), byte(0x11), byte(0x6D), byte(0x12), byte(0x13), byte(0x21), byte(0x04), byte(0xCC), byte(0x83), byte(0x04), byte(0xB0), byte(0x03), byte(0x6C), byte(0x00), byte(0xD6), byte(0x33), byte(0x1C), byte(0x83), byte(0x46), byte(0xB0), byte(0x02), byte(0x84), byte(0x9C), byte(0x44), byte(0x44), byte(0xD8), byte(0x42), byte(0xCB), byte(0xB8), byte(0xD2), byte(0xD8), byte(0x9C), byte(0x84), byte(0xB5), byte(0x11), byte(0x16), byte(0x20), byte(0x15), byte(0x31), byte(0x11), byte(0xD8), byte(0x84), byte(0xC7), byte(0x39), byte(0x44), byte(0xE0), byte(0x34), byte(0xE4), byte(0xC7), byte(0x11), byte(0x1B), byte(0x4E), byte(0x80), byte(0xB2), byte(0xE1), byte(0x10), byte(0xB2), byte(0x04), byte(0x54), byte(0x48), byte(0x44), byte(0x14), byte(0xE4), byte(0x44), byte(0xB8), byte(0x51), byte(0x73), byte(0x1C), byte(0xE5), byte(0x06), byte(0x1F), byte(0x23), byte(0xA0), byte(0x18), byte(0x02), byte(0x0D), byte(0x49), byte(0x3D), byte(0x87), byte(0x20), byte(0xB1), byte(0x2B), byte(0x01), byte(0x24), byte(0xF3), byte(0x38), byte(0xE8), byte(0xCE), byte(0x58), byte(0xDC), byte(0xCE), byte(0x0C), byte(0x06), byte(0x32), byte(0x00), byte(0xC1), byte(0x21), byte(0x00), byte(0x22), byte(0xB3), byte(0x00), byte(0xA1), byte(0x24), byte(0x00), byte(0x21), byte(0xE3), byte(0x20), byte(0x51), byte(0x44), byte(0x44), byte(0x43), byte(0x53), byte(0xD8), byte(0x71), byte(0x11), byte(0x12), byte(0x11), byte(0x13), byte(0x58), byte(0x41), byte(0x0D), byte(0xCC), byte(0x73), byte(0x92), byte(0x12), byte(0x45), byte(0x44), byte(0x37), byte(0x21), byte(0x04), byte(0x37), byte(0x43), byte(0x43), byte(0x11), byte(0x18), byte(0x01), byte(0x39), byte(0x44), byte(0xEE), byte(0x34), byte(0x48), byte(0x0B), byte(0x48), byte(0xE9), byte(0x40), byte(0x09), byte(0x3B), byte(0x14), byte(0x49), byte(0x38), byte(0x02), byte(0x4D), byte(0x40), byte(0x0B), byte(0x2D), byte(0x8B), byte(0xD1), byte(0x11), byte(0x51), byte(0x0D), byte(0x4E), byte(0x45), byte(0xCF), byte(0x10), byte(0x24), byte(0xE2), byte(0x38), byte(0xD4), byte(0xC0), byte(0x20), byte(0xD8), byte(0x8E), byte(0x34), byte(0x21), byte(0x11), byte(0x36), byte(0xC1), byte(0x32), byte(0x08), byte(0x73), byte(0x8E), byte(0x2F), byte(0x81), byte(0x00), byte(0x47), byte(0x32), byte(0x0F), byte(0xAC), byte(0x00), byte(0x63), byte(0x50), byte(0x49), byte(0x15), byte(0x11), byte(0x1C), byte(0xCE), byte(0x58), byte(0x04), byte(0x43), byte(0x98), byte(0x84), byte(0x4B), byte(0x94), byte(0x84), byte(0x4C), byte(0x98), byte(0xB0), byte(0x12), byte(0x4A), byte(0x60), byte(0x12), byte(0xA8), byte(0x41), byte(0x0F), byte(0xD8), byte(0xE4), byte(0x4B), byte(0x0F), byte(0x24), byte(0xC8), byte(0x2C), byte(0xBD), byte(0x84), byte(0x35), byte(0x3C), byte(0x87), byte(0x39), byte(0x42), byte(0xC3), byte(0xC8), byte(0xF1), byte(0x0D), byte(0x0F), byte(0x24), byte(0xC0), byte(0x18), byte(0x48), byte(0xCE), byte(0x09), byte(0x33), byte(0x91), byte(0xB0), byte(0x81), byte(0x87), byte(0x4E), byte(0x93), byte(0x81), byte(0x98), byte(0xE8), byte(0x8E), byte(0x35), byte(0x32), byte(0x0D), byte(0x50), byte(0x49), byte(0x15), byte(0x11), byte(0x16), byte(0x0E), byte(0x34), byte(0x4B), byte(0x44), byte(0x54), byte(0x44), byte(0x60), byte(0x35), byte(0x25), byte(0x84), byte(0x46), byte(0x51), byte(0x16), byte(0xB0), byte(0x40), byte(0x0D), byte(0x8C), byte(0x81), byte(0x45), byte(0x11), byte(0x11), byte(0x0D), byte(0x08), byte(0x4C), byte(0xC4), byte(0x34), byte(0x3B), byte(0x44), byte(0x10), byte(0x3A), byte(0xC4), byte(0x01), byte(0x51), byte(0x33), byte(0x45), byte(0x8B), byte(0x48), byte(0x08), byte(0x49), byte(0xCE), byte(0x2C), byte(0x3C), byte(0x8E), byte(0x30), byte(0x44), byte(0xC7), byte(0x20), byte(0xD1), byte(0xA0), byte(0x48), byte(0xAD), byte(0x80), byte(0x44), byte(0xCA), byte(0xC8), byte(0x3E), byte(0x23), byte(0x95), byte(0x11), byte(0x1A), byte(0x12), byte(0x49), byte(0x41), byte(0x27), byte(0x00), byte(0xF3), byte(0xC4), byte(0x37), byte(0x35), byte(0x11), byte(0x36), byte(0xB3), byte(0x8E), byte(0x2B), byte(0x25), byte(0x11), byte(0x12), byte(0x32), byte(0x12), byte(0x08), byte(0xE5), byte(0x44), byte(0x46), byte(0x52), byte(0x06), byte(0x1D), byte(0x3B), byte(0x00), byte(0x0E), byte(0x32), byte(0x11), byte(0x10), byte(0x24), byte(0xC8), byte(0x38), byte(0xD8), byte(0x06), byte(0x44), byte(0x41), byte(0x32), byte(0x38), byte(0xC1), byte(0x0E), byte(0x34), byte(0x49), byte(0x40), byte(0x20), byte(0xBC), byte(0x44), byte(0x48), byte(0xF1), byte(0x02), byte(0x4E), byte(0xD3), byte(0x93), byte(0x20), byte(0x21), byte(0x22), byte(0x1C), byte(0xE2), byte(0x02), byte(0x12), byte(0x11), byte(0x06), byte(0x20), byte(0xDC), byte(0xC7), byte(0x44), byte(0x41), byte(0x32), byte(0x61), byte(0x24), byte(0xC4), byte(0x32), byte(0xB1), byte(0x15), byte(0x10), byte(0xB9), byte(0x44), byte(0x10), byte(0xBB), byte(0x04), byte(0x11), byte(0x38), byte(0x8E), byte(0x30), byte(0xF0), byte(0x0D), byte(0x62), byte(0x13), byte(0x97), byte(0xC8), byte(0x73), byte(0x96), byte(0xBC), byte(0xB0), byte(0x18), byte(0xAC), byte(0x85), byte(0x44), byte(0xAC), byte(0x44), byte(0xD3), byte(0x11), byte(0x19), byte(0x06), byte(0x1A), byte(0xD5), byte(0x0C), byte(0x04), byte(0x44), byte(0x6E), byte(0x3C), byte(0x43), byte(0x6F), byte(0x44), byte(0xE0), byte(0x4B), byte(0x10), byte(0xC9), byte(0x40), byte(0x4E), byte(0x70), byte(0x0D), byte(0x0E), byte(0xC1), byte(0x00), byte(0x49), byte(0x44), byte(0x44), byte(0xC1), byte(0x41), byte(0x12), byte(0x4C), byte(0x83), byte(0x8D), byte(0x88), byte(0x02), byte(0xCB), byte(0xC4), byte(0x43), byte(0x04), byte(0x30), byte(0x11), byte(0x11), byte(0x88), byte(0x44), byte(0x53), byte(0x00), byte(0x83), byte(0x6F), byte(0x51), byte(0x3B), byte(0x44), byte(0x5D), byte(0x38), byte(0x87), byte(0x00), byte(0x84), byte(0x72), byte(0x4C), byte(0x04), byte(0x53), byte(0xC5), byte(0x43), byte(0x71), byte(0x00), byte(0x84), byte(0x84), byte(0x98), byte(0xE0), byte(0x0B), byte(0xC4), byte(0x40), byte(0x0B), byte(0x2D), byte(0x89), byte(0xCE), byte(0x30), byte(0x4C), byte(0xC4), byte(0x02), byte(0x20), byte(0x0D), byte(0x0C), byte(0x80), byte(0xC0), byte(0x4C), byte(0x4B), byte(0x0E), byte(0x34), byte(0x46), byte(0x21), byte(0x51), byte(0x22), byte(0x0D), byte(0x11), byte(0x24), byte(0xB8), byte(0x39), byte(0x43), byte(0x46), byte(0x98), byte(0xE3), byte(0x83), byte(0x88), byte(0xE5), byte(0x11), byte(0x4E), byte(0x52), byte(0x0D), byte(0x0E), byte(0xA3), byte(0x4E), byte(0x5A), byte(0xA2), byte(0x0D), byte(0x0E), byte(0x71), byte(0x0B), byte(0x3E), byte(0xD2), byte(0x06), byte(0x1D), byte(0x38), byte(0x87), byte(0x20), byte(0xB0), byte(0xEB), byte(0x39), byte(0x3E), byte(0x0E), byte(0x51), byte(0x1D), byte(0x12), byte(0x91), byte(0x81), byte(0x38), byte(0x11), byte(0x2D), byte(0x8E), byte(0x44), byte(0x38), byte(0x48), byte(0x4F), byte(0x50), byte(0x0D), byte(0xB0), byte(0xE3), byte(0x53), byte(0x1E), byte(0x70), byte(0x0B), byte(0x16), byte(0xB3), byte(0x96), byte(0xB0), byte(0x82), byte(0xCB), byte(0x20), byte(0xE3), byte(0x67), byte(0x20), byte(0x61), byte(0xEE), byte(0x44), byte(0x60), byte(0x0D), byte(0x21), byte(0x90), byte(0x13), byte(0x20), byte(0xE3), byte(0x71), byte(0x10), byte(0x39), byte(0x91), byte(0x10), byte(0x43), byte(0x61), byte(0x2D), byte(0x41), byte(0x36), byte(0x1C), byte(0x84), byte(0xC4), byte(0x84), byte(0xB0), byte(0x02), byte(0x2B), byte(0x83), byte(0x94), byte(0x45), byte(0x21), byte(0x0B), byte(0x16), byte(0x42), byte(0x06), byte(0x1D), byte(0x38), byte(0x4E), byte(0x4C), byte(0x7A), byte(0xC8), byte(0x4D), byte(0x32), byte(0xC4), byte(0x9C), byte(0xE5), byte(0x12), byte(0x12), byte(0xB1), byte(0x13), byte(0x8C), byte(0x44), byte(0x8F), byte(0x21), byte(0x31), byte(0x2F), byte(0x44), byte(0xE5), byte(0x48), byte(0x0C), byte(0x4C), byte(0x84), byte(0x45), byte(0x52), byte(0x02), byte(0x12), byte(0x72), byte(0x0C), byte(0x48), byte(0x42), byte(0xC5), byte(0x95), byte(0x12), byte(0x04), byte(0x34), byte(0x38), byte(0xC4), byte(0x48), byte(0x24), byte(0x48), byte(0x04), byte(0x49), byte(0x40), byte(0x4C), byte(0x71), byte(0x11), byte(0x8C), byte(0x45), byte(0x44), byte(0x2C), byte(0xE3), byte(0xCC), byte(0x10), byte(0xD4), byte(0xE0), byte(0x58), byte(0x06), byte(0x2A), byte(0x20), byte(0xB2), byte(0xF3), byte(0x44), byte(0x83), byte(0xE7), byte(0x39), byte(0x44), byte(0x66), byte(0x00), byte(0xC1), byte(0x2E), byte(0x15), byte(0x31), byte(0x0D), byte(0xBC), byte(0xB0), byte(0x0D), byte(0x4E), byte(0xF2), byte(0xC0), byte(0x08), byte(0x49), byte(0x0D), byte(0x0E), byte(0x03), byte(0x0E), byte(0x34), byte(0x6C), byte(0x88), byte(0x34), byte(0x21), byte(0x32), byte(0x4C), byte(0x03), byte(0x43), byte(0x8C), byte(0x44), byte(0x88), byte(0x18), byte(0xDB), byte(0xC0), byte(0x45), byte(0x32), byte(0x02), byte(0x50), byte(0xB0), byte(0x11), byte(0xC9), byte(0x40), byte(0xC3), byte(0x10), byte(0xD2), byte(0xD8), byte(0xB0), byte(0x43), byte(0x01), byte(0x11), byte(0x1B), byte(0xC0), byte(0x62), byte(0xB0), byte(0x16), byte(0x84), byte(0xE3), byte(0x8A), byte(0xC8), byte(0x82), byte(0xC4), byte(0x34), byte(0x21), byte(0x20), byte(0x2C), byte(0xC3), byte(0x92), byte(0x4E), byte(0x83), byte(0x42), byte(0x2D), byte(0x40), byte(0xC4), byte(0x80), byte(0x60), byte(0x08), byte(0x36), byte(0x42), byte(0x13), byte(0x1C), byte(0x44), byte(0x73), byte(0x38), byte(0xE2), byte(0xE5), byte(0x21), byte(0x51), byte(0x2E), byte(0x34), byte(0x21), byte(0x2B), byte(0x10), byte(0x04), byte(0x93), byte(0x91), byte(0x73), byte(0xCB), byte(0x00), byte(0x83), byte(0x68), byte(0x0C), byte(0x43), byte(0x53), byte(0x20), byte(0x56), byte(0x34), byte(0x35), byte(0x32), byte(0x0B), byte(0xC8), byte(0x84), byte(0xC4), byte(0xB0), byte(0x83), byte(0x54), byte(0x4C), byte(0x48), byte(0x8E), byte(0x50), byte(0xF2), byte(0xC4), byte(0xD8), byte(0x41), byte(0x0A), byte(0xB0), byte(0x04), byte(0xD3), byte(0x11), byte(0x18), byte(0x51), byte(0x20), byte(0xD1), byte(0xA3), byte(0x11), byte(0x30), byte(0x08), byte(0x2E), byte(0x83), byte(0x45), byte(0x39), byte(0x13), byte(0x00), byte(0x4C), byte(0x83), byte(0x8D), byte(0xB4), byte(0xE4), byte(0xC7), byte(0x20), byte(0xD1), byte(0xA0), byte(0x35), byte(0x84), byte(0xC7), byte(0x20), byte(0xD1), byte(0xA4), byte(0x54), byte(0x44), byte(0x58), byte(0x4C), byte(0x72), byte(0x0D), byte(0x1A), byte(0x01), byte(0x8E), byte(0xAC), byte(0x40), byte(0x03), byte(0xC8), byte(0xE3), byte(0x04), byte(0x4C), byte(0x83), byte(0x04), byte(0x4B), byte(0x43), byte(0x43), byte(0x11), byte(0x14), byte(0x93), byte(0x00), byte(0xD0), byte(0xF6), byte(0x1C), byte(0x44), byte(0xC7), byte(0x11), byte(0x1B), byte(0x40), byte(0x4D), byte(0x44), byte(0x44), byte(0xCC), byte(0xE1), byte(0x84), byte(0x4C), byte(0x71), byte(0x11), byte(0x94), byte(0xE2), byte(0xCB), byte(0x39), byte(0x6B), byte(0xC0), byte(0x44), byte(0x43), byte(0x53), byte(0xC9), byte(0x33), byte(0x8F), byte(0xA0), byte(0xD0), byte(0xC4), byte(0x10), byte(0x38), byte(0xC8), byte(0x14), byte(0x52), byte(0x02), byte(0x50), byte(0xB4), byte(0xEF), byte(0x50), byte(0x12), byte(0xC8), byte(0x0A), byte(0x02), byte(0xD1), byte(0x10), byte(0x00), byte(0xD8), byte(0xC8), byte(0xF1), byte(0x00), byte(0x2A), byte(0xC0), byte(0x08), byte(0x35), byte(0x30), byte(0x08), byte(0x37), byte(0x11), byte(0x0C), byte(0x00), byte(0x83), byte(0x67), byte(0x10), byte(0x04), byte(0x60), byte(0x2C), byte(0xB3), byte(0x96), byte(0xB0), byte(0x40), byte(0xC8), byte(0x02), byte(0xE1), byte(0x45), byte(0x20), byte(0x21), byte(0x21), byte(0x10), byte(0xD1), byte(0x05), byte(0x21), byte(0x38), byte(0xCE), byte(0x39), byte(0x19), byte(0xD4), byte(0x1A), byte(0xF1), byte(0x11), byte(0x48), byte(0xE3), byte(0x6B), byte(0x01), byte(0x31), byte(0x11), byte(0x8D), byte(0x44), byte(0x48), byte(0x34), byte(0x6D), byte(0x80), byte(0x46), byte(0x72), byte(0x12), byte(0x4C), byte(0xE4), byte(0x58), byte(0x81), byte(0x11), byte(0x94), byte(0x13), byte(0x62), byte(0x13), byte(0x1C), byte(0x83), byte(0x72), byte(0x11), byte(0x38), byte(0x11), byte(0x4C), byte(0x80), byte(0x8B), byte(0x13), byte(0x24), byte(0xC0), byte(0x4C), byte(0x83), byte(0x8D), byte(0xB0), byte(0xE4), byte(0x4D), byte(0x20), byte(0xD1), byte(0xB6), byte(0x00), byte(0xB2), byte(0xA4), byte(0x54), byte(0x43), byte(0x53), byte(0xD8), byte(0x83), byte(0x62), byte(0x1C), byte(0xE3), byte(0x92), byte(0x12), byte(0x11), byte(0x07), byte(0x01), byte(0x52), byte(0x0E), byte(0x47), byte(0x21), byte(0xCE), byte(0x39), byte(0x39), byte(0x48), byte(0x44), byte(0x49), byte(0x4E), byte(0x38), byte(0x3C), byte(0xC8), byte(0x4C), byte(0xB1), byte(0x20), byte(0x44), byte(0xE5), byte(0x0D), byte(0x0E), byte(0x02), byte(0x11), byte(0xCC), byte(0x40), byte(0x02), byte(0x1C), byte(0x44), byte(0x66), byte(0x00), byte(0xFC), byte(0x94), byte(0x04), byte(0x91), byte(0x02), byte(0x4E), byte(0x43), byte(0x4E), byte(0x50), byte(0x61), byte(0xEF), byte(0x44), byte(0xE5), byte(0x44), byte(0x80), byte(0x24), byte(0x4E), byte(0x49), byte(0x28), byte(0x0B), byte(0x4C), byte(0x73), byte(0x94), byte(0x18), byte(0x79), byte(0xC4), byte(0x00), byte(0x39), byte(0x4E), byte(0x39), byte(0x3C), byte(0x84), byte(0x08), byte(0xE3), byte(0x43), byte(0x84), byte(0xE6), byte(0x2C), byte(0x00), byte(0x83), byte(0x6B), byte(0x20), byte(0x48), byte(0x01), byte(0x2C), byte(0x48), byte(0x88), byte(0x54), byte(0x82), byte(0xF3), byte(0x00), byte(0x12), byte(0xC4), byte(0xAC), byte(0xE5), byte(0x44), byte(0xBD), byte(0x13), byte(0x82), byte(0x11), byte(0x24), byte(0xAE), byte(0x14), byte(0x51), byte(0x11), byte(0xC9), byte(0x35), byte(0x03), byte(0x10), byte(0xD4), byte(0xE2), byte(0x38), byte(0xD4), byte(0x88), byte(0x0C), byte(0x44), byte(0x60), byte(0x3C), byte(0xF1), byte(0x00), byte(0x47), byte(0x24), byte(0xD4), byte(0x0D), byte(0x88), byte(0x54), byte(0x62), byte(0xD1), byte(0x00), byte(0x44), byte(0xB6), byte(0x27), byte(0x50), byte(0xC0), byte(0x0D), byte(0x91), byte(0x52), byte(0x03), byte(0x10), byte(0xD0), byte(0x84), byte(0xCC), byte(0x45), byte(0xD3), byte(0xB0), byte(0x44), byte(0xC7), byte(0x38), byte(0x3A), byte(0x0D), byte(0x08), byte(0xB5), byte(0x03), byte(0x20), byte(0xD1), byte(0xB2), byte(0x10), byte(0xD0), byte(0xF1), byte(0x10), byte(0x02), byte(0xC8), byte(0x64), byte(0x4C), byte(0x84), byte(0x35), byte(0x21), byte(0x21), byte(0x50), byte(0x82), byte(0xC3), byte(0x88), byte(0xE3), byte(0x53), byte(0x44), byte(0xE2), byte(0xE0), byte(0x50), byte(0x32), byte(0x04), byte(0x34), byte(0x21), byte(0x32), byte(0x11), byte(0x51), byte(0x11), byte(0x00), byte(0xB8), byte(0x94), byte(0x4E), byte(0x23), byte(0x8B), byte(0x2C), byte(0x41), byte(0x84), byte(0xA0), byte(0xD4), byte(0xC4), byte(0x44), byte(0x44), byte(0x93), byte(0xC9), byte(0x40), byte(0x82), byte(0x11), byte(0x24), byte(0xB2), byte(0x3C), byte(0x40), byte(0x88), byte(0x00), byte(0xBC), byte(0x48), byte(0x48), byte(0xA9), byte(0x17), byte(0x3C), byte(0x44), byte(0x48), byte(0x10), byte(0xD0), byte(0x84), byte(0x84), byte(0x41), byte(0xC8), byte(0x34), byte(0x38), byte(0x44), byte(0x4D), byte(0x31), byte(0x11), byte(0xC4), byte(0x44), byte(0x94), byte(0x2D), byte(0x3C), byte(0xD1), byte(0x10), byte(0x04), byte(0xF2), byte(0x21), byte(0x7C), byte(0x44), byte(0x2C), byte(0x04), byte(0xC8), byte(0x38), byte(0xD4), byte(0x87), byte(0x20), byte(0xF8), byte(0x0D), byte(0x20), byte(0xC0), byte(0x0B), byte(0xA0), byte(0xC3), byte(0xD1), byte(0x39), byte(0x51), byte(0x27), byte(0x00), byte(0x84), byte(0x72), byte(0x4C), byte(0x06), byte(0x33), byte(0x38), byte(0xFC), byte(0x44), byte(0x0D), byte(0x40), byte(0x84), byte(0xBC), byte(0x44), byte(0x47), byte(0x00), byte(0xF4), byte(0xAB), byte(0x01), byte(0x31), byte(0x36), byte(0x44), byte(0x84), byte(0xC4), byte(0x46), byte(0xF2), byte(0x02), byte(0x2A), byte(0x42), byte(0xD2), byte(0x13), byte(0x22), byte(0x06), byte(0x34), byte(0x81), byte(0x48), byte(0x08), byte(0x03), byte(0x53), byte(0x88), byte(0x70), byte(0x0D), byte(0x08), byte(0x49), byte(0xCE), byte(0x4C), byte(0x42), byte(0xE6), byte(0x10), byte(0xD1), byte(0x11), byte(0x00), byte(0xBC), byte(0x4E), byte(0x08), byte(0xAC), byte(0x44), byte(0x41), byte(0x42), byte(0x11), byte(0x12), byte(0x02), byte(0xCE), byte(0x34), byte(0x69), byte(0x48), byte(0x4F), byte(0x31), byte(0xC4), byte(0x31), byte(0x21), byte(0x0B), byte(0x54), byte(0x44), byte(0xB1), byte(0x10), byte(0xF3), byte(0x91), byte(0x4E), byte(0x23), byte(0x8D), byte(0x0C), byte(0x84), byte(0xC8), byte(0x38), byte(0xDC), byte(0x44), byte(0x00), byte(0x21), byte(0xF3), byte(0x45), byte(0x44), byte(0xC7), byte(0x90), byte(0x51), byte(0x4E), byte(0x45), byte(0x38), byte(0xC4), byte(0x08), byte(0x80), byte(0xC4), byte(0xC4), byte(0x04), byte(0xC4), byte(0x90), byte(0x35), byte(0x02), byte(0x01), byte(0x32), byte(0x0E), byte(0x36), byte(0x53), byte(0x91), byte(0x08), byte(0x49), byte(0x80), byte(0x44), byte(0x31), byte(0x0D), byte(0x8D), byte(0x15), byte(0x06), byte(0xAC), byte(0x40), byte(0x03), byte(0x11), byte(0x1D), byte(0x4E), byte(0x20), byte(0x21), byte(0x30), byte(0x50), byte(0x84), byte(0xC4), byte(0xD8), byte(0x73), byte(0x8B), byte(0x13), byte(0x21), byte(0x04), byte(0x32), byte(0xC2), byte(0x0D), byte(0x0E), byte(0x52), byte(0x0D), byte(0x00), byte(0xB2), byte(0xD8), byte(0xC8), byte(0x84), byte(0x71), byte(0x11), byte(0x35), byte(0x11), byte(0x36), byte(0x54), byte(0x44), byte(0x13), byte(0x24), byte(0xCE), byte(0x45), byte(0x8C), byte(0x44), byte(0x48), byte(0xF3), byte(0x8D), byte(0x0E), byte(0xF5), byte(0x12), byte(0x1E), byte(0x00), byte(0x82), byte(0x39), byte(0x10), byte(0xC8), byte(0x34), byte(0x68), byte(0x51), byte(0x39), byte(0x31), byte(0xC4), byte(0x46), byte(0xB1), byte(0x00), byte(0x44), byte(0xDC), byte(0x8E), byte(0x36), byte(0x73), byte(0x8F), byte(0x12), byte(0x31), byte(0x15), byte(0x10), byte(0xB3), byte(0x8F), byte(0x94), byte(0x41), byte(0x0B), byte(0x20), byte(0xD1), byte(0xB1), byte(0x10), byte(0x00), byte(0xE2), byte(0x01), byte(0x14), byte(0x58), byte(0x8C), byte(0x84), byte(0x84), byte(0x01), byte(0x21), byte(0x31), byte(0x38), byte(0x00), byte(0xF5), byte(0x01), byte(0x12), byte(0x0E), byte(0x51), byte(0x28), byte(0x40), byte(0x2C), byte(0xB8), byte(0x80), byte(0x48), byte(0x4B), byte(0x8F), byte(0x11), byte(0x10), byte(0x13), byte(0x20), byte(0xE3), byte(0x62), byte(0x2C), byte(0xE4), byte(0x84), byte(0xD4), byte(0x84), byte(0x88), byte(0x4F), byte(0x11), byte(0x02), byte(0x10), byte(0x85), byte(0x44), byte(0x85), byte(0x42), byte(0x0B), byte(0x0C), byte(0x83), byte(0x46), byte(0xD4), byte(0x02), byte(0xD4), byte(0x13), byte(0x11), byte(0x12), byte(0x10), byte(0x04), byte(0x42), byte(0x1E), byte(0x55), byte(0x0B), byte(0x2E), byte(0xC3), byte(0x83), byte(0x10), byte(0xBA), byte(0x4E), byte(0x20), byte(0xDC), byte(0x84), byte(0x01), byte(0x23), byte(0x8D), byte(0xCC), byte(0x05), byte(0xE3), byte(0x21), byte(0x11), byte(0x02), byte(0x4C), byte(0xE4), byte(0x6F), byte(0x39), byte(0x22), byte(0x13), byte(0x20), byte(0xE3), byte(0x6F), byte(0x2C), byte(0x06), byte(0x04), byte(0x47), byte(0x23), byte(0xCE), byte(0x45), byte(0x39), byte(0x11), byte(0x44), byte(0xE4), byte(0x71), byte(0x10), byte(0x23), byte(0x91), byte(0x0F), byte(0x13), byte(0x96), byte(0x8C), byte(0x04), byte(0xC0), byte(0xBC), byte(0x03), byte(0xC4), byte(0x47), byte(0x31), byte(0xC4), byte(0x39), byte(0x16), byte(0x32), byte(0x3C), byte(0x00), byte(0x84), byte(0x91), byte(0x51), byte(0x11), byte(0x62), byte(0x53), byte(0x91), byte(0x33), byte(0x25), byte(0x0F), byte(0x3C), byte(0xE4), byte(0x53), byte(0x80), byte(0x24), byte(0xC8), byte(0x38), byte(0xDB), byte(0x85), byte(0x14), byte(0x80), byte(0x88), byte(0x00), byte(0xBD), byte(0x87), byte(0x39), byte(0x21), byte(0x28), byte(0x0C), byte(0x40), byte(0x27), byte(0x00), byte(0xF3), byte(0xD8), byte(0x9C), byte(0x40), byte(0x11), byte(0x4E), byte(0x11), byte(0x12), byte(0x4F), byte(0x31), byte(0x00), byte(0x32), byte(0xF4), byte(0x4E), byte(0x24), byte(0x40), byte(0x93), byte(0x9C), byte(0x84), byte(0xE1), byte(0x01), byte(0x21), byte(0x31), byte(0x10), byte(0xF4), byte(0x44), byte(0x48), byte(0x43), byte(0x53), byte(0xCC), byte(0xE5), byte(0x8D), byte(0xBD), byte(0x42), byte(0xCB), byte(0x85), byte(0x44), byte(0xAC), byte(0x00), byte(0xF8), byte(0xD1), byte(0x62), byte(0xC3), byte(0x8C), byte(0x88), byte(0x04), byte(0xE3), byte(0x00), byte(0x3C), byte(0x4E), byte(0x38), byte(0xCC), byte(0x8C), byte(0x20), byte(0xB1), byte(0x25), byte(0x20), byte(0x42), byte(0xC3), byte(0xA0), byte(0xC3), byte(0xC0), byte(0x09), byte(0x39), byte(0x54), byte(0x34), byte(0x3A), byte(0xC0), byte(0x44), byte(0x61), byte(0x23), byte(0x38), byte(0x69), byte(0xD4), byte(0x18), byte(0x4B), byte(0xD1), byte(0x10), byte(0xF0), byte(0x11), byte(0x12), byte(0x43), byte(0x55), byte(0x21), byte(0x13), byte(0x8D), byte(0x30), byte(0x43), byte(0x53), byte(0x00), byte(0xBB), byte(0xD1), byte(0x38), byte(0x35), byte(0x02), byte(0x12), byte(0x71), byte(0x11), byte(0x48), byte(0x42), byte(0xC5), byte(0xCC), byte(0x40), byte(0x02), byte(0x1E), byte(0xE2), byte(0x0B), byte(0xC9), byte(0x40), byte(0x87), byte(0xC8), byte(0x84), byte(0xD4), byte(0x01), byte(0x32), byte(0x0E), byte(0x37), byte(0x32), byte(0x04), byte(0x88), byte(0xE4), byte(0x93), byte(0xA0), byte(0xD0), byte(0xD4), byte(0x49), byte(0x34), byte(0x58), byte(0xC8), byte(0xA2), byte(0x0D), byte(0xC9), byte(0x34), byte(0x44), byte(0x11), byte(0x3A), byte(0x0C), byte(0x00), byte(0x61), byte(0x28), byte(0x4D), byte(0x21), byte(0x0B), byte(0x16), byte(0xF1), byte(0xCE), byte(0x34), byte(0x4B), byte(0xD1), byte(0x20), byte(0x21), byte(0x36), byte(0x10), byte(0x04), byte(0x6C), byte(0x39), byte(0x24), byte(0xF2), byte(0x50), byte(0xDC), byte(0x8E), byte(0x38), byte(0xD8), byte(0x8B), byte(0x10), byte(0x04), byte(0x6F), byte(0x44), byte(0x00), byte(0x93), byte(0x20), byte(0x21), byte(0x2F), byte(0x20), byte(0x40), byte(0x84), byte(0xD8), byte(0x02), byte(0x13), byte(0xC4), byte(0x40), byte(0x84), byte(0x35), byte(0x3A), byte(0x0C), byte(0x3C), byte(0xE4), byte(0x53), byte(0x00), byte(0xD4), byte(0xEF), byte(0x44), byte(0xE0), byte(0xD4), byte(0x09), byte(0x3A), byte(0xC4), byte(0x15), byte(0x3D), byte(0x80), byte(0x2C), byte(0xBC), byte(0x84), byte(0x44), byte(0x81), byte(0x12), byte(0xB4), byte(0x45), byte(0x92), byte(0xC8), byte(0x70), byte(0x11), byte(0x12), byte(0xC3), byte(0x95), byte(0x20), byte(0x4A), byte(0x88), byte(0x0E), byte(0xD3), byte(0x91), byte(0xC8), byte(0x83), byte(0x0F), byte(0x2D), byte(0x8D), byte(0x88), byte(0x14), byte(0x4B), byte(0x8D), byte(0x4C), byte(0xE8), byte(0x80), byte(0x4C), byte(0x21), byte(0xEC), byte(0x61), byte(0x21), byte(0x0B), byte(0x16), byte(0x52), byte(0x0D), byte(0x12), byte(0x23), byte(0x8C), byte(0x3D), byte(0x44), byte(0xC4), byte(0x47), byte(0x23), byte(0x8D), byte(0x1A), byte(0x04), byte(0xD3), byte(0x10), byte(0xD4), byte(0xC8), byte(0x38), byte(0xD8), byte(0xD1), byte(0x01), byte(0x69), byte(0x48), byte(0x2C), byte(0xCC), byte(0x44), byte(0x3D), byte(0x40), byte(0x4B), byte(0x20), byte(0x20), byte(0x0D), byte(0xC8), byte(0x40), byte(0x94), byte(0x44), byte(0x84), byte(0xD8), byte(0xC8), byte(0x23), byte(0x91), byte(0x13), byte(0x31), byte(0x12), byte(0x4F), byte(0x24), byte(0xCE), byte(0x08), byte(0xAB), byte(0xCE), byte(0x48), byte(0x84), byte(0xC8), byte(0x54), byte(0x48), byte(0x80), byte(0x51), byte(0x21), byte(0x22), byte(0x10), byte(0xD4), byte(0xD4), byte(0x45), byte(0x8D), byte(0x88), byte(0x34), byte(0x33), byte(0x96), byte(0xB0), byte(0x43), byte(0x0E), byte(0x45), byte(0x89), byte(0x17), byte(0x21), byte(0x24), byte(0xEB), byte(0x21), byte(0x24), byte(0xC4), byte(0x37), byte(0x24), byte(0xD1), byte(0x00), byte(0x81), byte(0x87), byte(0x4E), byte(0x25), byte(0x0B), byte(0x4D), byte(0x44), byte(0x44), byte(0x84), byte(0x82), byte(0xCB), byte(0x20), byte(0xE3), byte(0x65), byte(0x39), byte(0x13), byte(0x04), byte(0x46), byte(0x31), byte(0x02), byte(0x21), byte(0x22), byte(0x0E), byte(0x36), byte(0x43), byte(0x44), byte(0x44), byte(0x66), byte(0x2C), byte(0x39), byte(0x51), byte(0x32), byte(0x50), byte(0xC3), byte(0x04), byte(0x47), byte(0x63), byte(0x8D), byte(0x0C), byte(0x44), byte(0x71), byte(0x10), byte(0xB0), byte(0x13), byte(0x12), byte(0x05), byte(0x40), byte(0x20), byte(0xB0), byte(0x01), byte(0x2C), byte(0x4A), byte(0xC8), byte(0x34), byte(0x4A), byte(0xC8), byte(0x28), byte(0x42), byte(0xD8), byte(0xB9), byte(0x44), byte(0xD2), byte(0x20), byte(0x31), byte(0x32), byte(0x1C), byte(0xE4), byte(0xF2), byte(0x1C), byte(0xE4), byte(0x53), byte(0x88), byte(0xE5), byte(0x0D), byte(0x4D), byte(0x16), byte(0x31), byte(0x38), byte(0xB1), byte(0x20), byte(0x44), byte(0x40), byte(0x32), byte(0x20), byte(0xD1), byte(0x8B), byte(0x13), byte(0x15), byte(0x0B), byte(0x12), byte(0x30), byte(0x14), byte(0x18), byte(0x74), byte(0xC4), byte(0x46), byte(0xC0), byte(0x11), byte(0x28), byte(0x44), byte(0xE8), byte(0x34), byte(0x32), byte(0x02), byte(0x01), byte(0x31), byte(0x2F), byte(0x44), byte(0x44), byte(0x84), byte(0x35), byte(0x3A), byte(0xC0), byte(0x34), byte(0x38), byte(0x80), byte(0x30), byte(0xF0), byte(0x08), byte(0x18), byte(0xDB), byte(0x00), byte(0x4C), byte(0x44), byte(0x48), byte(0x00), byte(0xBB), byte(0xCE), byte(0x3D), byte(0x42), byte(0xC0), byte(0x4C), byte(0x83), byte(0x8D), byte(0x90), byte(0x23), byte(0x8D), byte(0x38), byte(0xC6), byte(0x2C), byte(0x10), byte(0x32), byte(0x02), byte(0x00), byte(0xB9), byte(0xCE), byte(0x48), byte(0xF2), byte(0x13), byte(0x00), byte(0xB8), byte(0x87), byte(0x51), byte(0x10), byte(0x87), byte(0x99), byte(0x13), byte(0x94), byte(0x34), byte(0x3C), byte(0xC7), byte(0x39), byte(0x44), byte(0x80), byte(0x34), byte(0x38), byte(0x14), byte(0x4C), byte(0x73), byte(0x91), byte(0x21), byte(0x36), byte(0x28), byte(0x35), byte(0x24), byte(0xC4), byte(0x00), byte(0x3C), byte(0x44), byte(0x08), byte(0x43), byte(0x53), byte(0x2D), byte(0x89), byte(0x54), byte(0x4D), byte(0x44), byte(0x44), byte(0xD9), byte(0x13), byte(0x8D), byte(0x1A), byte(0x83), byte(0x55), byte(0x38), byte(0xB5), byte(0x44), byte(0xAC), byte(0x81), byte(0x44), byte(0x9C), byte(0x42), byte(0x06), byte(0x1D), byte(0x3A), byte(0x0D), byte(0x09), byte(0x11), byte(0x00), byte(0x48), byte(0x4C), byte(0x48), byte(0x18), byte(0x74), byte(0xE1), byte(0x00), byte(0xD2), byte(0xA2), byte(0x50), byte(0xB4), byte(0xD4), byte(0x44), byte(0x02), byte(0xE2), byte(0x11), byte(0x14), byte(0xC0), byte(0x20), byte(0xD2), byte(0xD8), byte(0xD8), byte(0x44), byte(0x93), byte(0x91), byte(0x71), byte(0x02), byte(0x51), byte(0x32), byte(0x15), byte(0x12), byte(0x13), byte(0x80), byte(0x44), byte(0x3C), byte(0x84), byte(0x10), byte(0xAA), byte(0xCE), byte(0x34), byte(0x6B), byte(0x85), byte(0x14), byte(0x80), byte(0x84), byte(0x47), byte(0x24), byte(0xC0), byte(0x4C), byte(0x43), byte(0x04), byte(0x35), byte(0x3C), byte(0x44), byte(0x49), byte(0x38), byte(0x40), byte(0x62), byte(0x31), byte(0x00), byte(0x2F), byte(0x63), byte(0x91), byte(0x28), byte(0x44), byte(0x71), byte(0x11), byte(0x23), byte(0x94), byte(0x44), byte(0x21), byte(0x33), byte(0x1D), byte(0x13), byte(0x96), byte(0x94), byte(0xE4), byte(0x56), byte(0x01), byte(0x10), byte(0xEF), byte(0x38), byte(0xB2), byte(0x02), byte(0x63), byte(0x20), byte(0x88), byte(0x10), byte(0xD0), byte(0x84), byte(0x91), byte(0x81), byte(0x12), byte(0x84), byte(0x40), byte(0xE8), byte(0x4C), byte(0x43), byte(0x36), byte(0x10), byte(0x03), byte(0xCE), byte(0x36), byte(0x52), byte(0x0B), byte(0x2E), byte(0xF2), byte(0xC0), byte(0x36), byte(0xC2), byte(0x0B), byte(0x21), byte(0x30), byte(0x11), byte(0x62), byte(0x65), byte(0x0D), byte(0x9C), byte(0xE4), byte(0xE7), byte(0x10), byte(0x04), byte(0xE0), byte(0x0C), byte(0x34), byte(0x44), byte(0x49), byte(0x28), byte(0x8E), byte(0x2C), byte(0x39), byte(0x4E), byte(0x09), byte(0x44), byte(0xA5), byte(0x39), byte(0x11), byte(0x08), byte(0x18), byte(0xDC), byte(0xD1), byte(0x10), byte(0x04), byte(0xCC), byte(0x10), byte(0xD4), byte(0xE1), byte(0x2C), byte(0xE3), byte(0x83), byte(0xD0), byte(0xF3), byte(0x8D), byte(0x88), byte(0xE5), byte(0x11), byte(0x48), byte(0x4C), byte(0xC7), byte(0x21), byte(0x10), byte(0xF6), byte(0x01), byte(0x30), byte(0x87), byte(0x80), byte(0x51), byte(0x44), byte(0x09), byte(0x39), byte(0x00), byte(0x44), byte(0xB6), byte(0x32), byte(0x4C), byte(0xE4), byte(0x44), byte(0xCC), byte(0x75), byte(0x12), byte(0xC8), byte(0xE5), byte(0x0D), byte(0x0E), byte(0x45), byte(0x44), byte(0x45), byte(0x85), byte(0x87), byte(0x11), byte(0x11), byte(0x21), byte(0x00), byte(0x16), byte(0x20), byte(0x0C), byte(0xC2), byte(0x0D), byte(0x21), byte(0x24), byte(0xD1), byte(0x01), byte(0x32), byte(0x0E), byte(0x36), byte(0xC3), byte(0x94), byte(0x4C), byte(0x7B), byte(0xC0), byte(0x18), byte(0x49), byte(0x0D), byte(0x4C), byte(0x44), byte(0x6F), byte(0x44), byte(0xE0), byte(0x40), byte(0x04), byte(0xB6), byte(0x2F), byte(0x38), byte(0x83), byte(0x53), byte(0xC8), byte(0x40), byte(0x13), byte(0xB4), byte(0x04), byte(0xD4), byte(0x44), byte(0x02), byte(0xF1), byte(0x00), byte(0x21), byte(0x25), byte(0x01), byte(0x18), byte(0x87), byte(0x00), byte(0xB2), byte(0xC4), byte(0x34), byte(0x61), byte(0x2F), byte(0x01), byte(0x24), byte(0xA0), byte(0x3C), byte(0xF2), byte(0xD8), byte(0xB0), byte(0x02), byte(0x0B), byte(0xD1), byte(0x25), byte(0x00), byte(0x2C), byte(0xB6), byte(0x2C), byte(0x21), byte(0x7C), byte(0xCE), byte(0x50), byte(0x61), byte(0xE2), byte(0x2C), byte(0x40), byte(0x11), byte(0x2D), byte(0x89), byte(0x91), byte(0x39), byte(0x69), byte(0x40), byte(0x09), byte(0x33), byte(0x91), byte(0xC9), byte(0x30), byte(0x13), byte(0x12), byte(0xB3), byte(0x82), byte(0x00), byte(0xB9), byte(0x94), byte(0x62), byte(0x40), byte(0x12), byte(0x4F), byte(0x20), byte(0x15), byte(0x13), byte(0x23), byte(0x94), byte(0x4C), byte(0x7C), byte(0x82), byte(0x10), byte(0xD1), byte(0x2C), byte(0x39), byte(0x31), byte(0xC4), byte(0x46), byte(0x20), byte(0x11), byte(0x10), byte(0x44), byte(0x70), byte(0x50), byte(0x80), byte(0x8A), byte(0x2D), byte(0x88), byte(0x84), byte(0x35), byte(0x34), byte(0x40), byte(0x2E), byte(0x50), byte(0x02), byte(0x12), byte(0x80), byte(0x84), byte(0x80), byte(0x13), byte(0x95), byte(0x12), byte(0x11), byte(0x18), byte(0x38), byte(0xD0), byte(0xEF), byte(0x20), byte(0x24), byte(0xD4), byte(0x44), byte(0x4B), byte(0x44), byte(0x4D), byte(0x63), byte(0x91), byte(0x2A), byte(0xC0), byte(0x0D), byte(0x00), byte(0x61), byte(0x0C), byte(0x10), byte(0xD4), byte(0xE8), byte(0x34), byte(0x32), byte(0x15), byte(0x20), byte(0x35), byte(0x00), byte(0x2E), byte(0x50), byte(0x0D), byte(0xC8), byte(0x86), byte(0x44), byte(0xC8), byte(0xF1), byte(0x04), byte(0x0E), byte(0x15), byte(0x12), byte(0x63), byte(0x21), byte(0x11), byte(0x20), byte(0xE5), byte(0x12), byte(0xB8), byte(0x20), byte(0x94), byte(0x46), byte(0x00), byte(0xC3), byte(0xC4), byte(0x40), byte(0x03), byte(0x63), byte(0x22), byte(0x06), byte(0x36), byte(0x23), byte(0x8B), byte(0x2C), byte(0x40), byte(0x93), byte(0x20), byte(0xE3), byte(0x6B), byte(0x21), byte(0x24), byte(0xE0), byte(0x3C), byte(0xF4), byte(0x4E), byte(0x00), byte(0x21), byte(0xE2), byte(0x1C), byte(0x04), byte(0x46), byte(0x13), byte(0x05), byte(0x00), byte(0x2C), byte(0x84), byte(0xD8), byte(0xBD), byte(0x11), byte(0x12), byte(0x49), byte(0x44), byte(0x44), byte(0xD4), byte(0xE4), byte(0xC4), byte(0xB4), byte(0xE4), byte(0xC4), byte(0xBC), byte(0x04), byte(0x53), byte(0xC4), byte(0x40), byte(0x0B), byte(0xD8), byte(0x40), byte(0x62), byte(0x51), byte(0x14), byte(0x44), byte(0x35), byte(0x38), byte(0xC4), byte(0x4C), byte(0x44), byte(0x4C), byte(0x20), byte(0xD1), byte(0x33), byte(0x45), byte(0x41), byte(0x32), byte(0x00), byte(0x3D), byte(0x87), byte(0x01), byte(0x31), byte(0x15), byte(0x11), byte(0x18), byte(0x51), byte(0x10), byte(0x02), byte(0xB6), byte(0x39), byte(0x14), byte(0x58), byte(0x89), byte(0x43), byte(0xEF), byte(0x01), byte(0x14), byte(0xC8), byte(0x09), byte(0x42), byte(0xC0), byte(0x44), byte(0xB6), byte(0x20), byte(0x30), byte(0xE5), byte(0x0D), byte(0x4E), byte(0x00), byte(0x48), byte(0x2C), byte(0x84), byte(0xD8), byte(0x90), byte(0x04), byte(0xF1), byte(0x10), byte(0x23), byte(0x86), byte(0x34), byte(0x86), byte(0x44), byte(0xC8), byte(0x84), byte(0xE2), byte(0x1C), byte(0x04), byte(0x40), byte(0x09), byte(0x31), byte(0x11), byte(0xC8), byte(0xE3), byte(0x04), byte(0x04), byte(0xE0), byte(0xD8), byte(0xAC), byte(0xE4), byte(0x92), byte(0x8C), byte(0x41), byte(0x91), byte(0x10), byte(0x49), byte(0x05), byte(0x14), byte(0x40), byte(0x93), byte(0x81), byte(0x34), byte(0xC0), byte(0x08), byte(0xAC), byte(0x93), byte(0x00), byte(0x51), byte(0x6C), byte(0x20), byte(0x30), byte(0xCB), byte(0x13), byte(0x31), byte(0x0B), byte(0x11), byte(0x52), byte(0x12), byte(0x20), byte(0xE3), byte(0x76), byte(0x1D), byte(0x8A), byte(0xC4), byte(0x18), byte(0x02), byte(0xE2), byte(0x00), byte(0xF2), byte(0x13), byte(0x00), byte(0xBC), byte(0xD1), byte(0x00), byte(0x31), byte(0x24), byte(0x2C), byte(0x40), byte(0x93), byte(0x20), byte(0xE3), byte(0x64), byte(0x54), byte(0x44), byte(0x58), byte(0x04), byte(0xE0), byte(0xD8), byte(0x8D), byte(0x13), byte(0x8F), byte(0xB0), byte(0x02), byte(0x4E), byte(0x47), byte(0x52), byte(0x04), byte(0x5B), byte(0x24), byte(0xC0), byte(0x34), byte(0x30), byte(0x11), byte(0x0E), byte(0x12), byte(0x0B), byte(0x2E), byte(0x43), byte(0x0F), byte(0x2C), byte(0xE6), byte(0x04), byte(0x12), byte(0x32), byte(0x12), byte(0x09), byte(0x44), byte(0x92), byte(0x20), byte(0xE3), byte(0x6E), byte(0x3C), byte(0xF3), byte(0x91), byte(0x4D), byte(0x43), byte(0x48), byte(0x4D), byte(0x88), byte(0x0D), byte(0x00), byte(0xB6), byte(0x12), byte(0x21), byte(0x2C), byte(0xC4), byte(0x37), byte(0x25), byte(0x06), byte(0x18), byte(0x44), byte(0x93), byte(0xAC), byte(0x05), byte(0x98), byte(0x11), byte(0x19), byte(0xD4), byte(0x48), byte(0x10), byte(0x0D), byte(0x0F), byte(0x21), byte(0x02), byte(0x4C), byte(0x83), byte(0x8D), byte(0x84), byte(0x40), byte(0x8E), byte(0x30), byte(0x4C), byte(0x8A), byte(0x20), byte(0xB2), byte(0xF2), byte(0x21), byte(0x24), byte(0xC4), byte(0x47), byte(0x24), byte(0xD8), byte(0x2C), byte(0x48), byte(0x91), byte(0x20), byte(0xC1), byte(0x2F), byte(0x44), byte(0xE1), byte(0x91), byte(0x00), byte(0xC8), byte(0x8E), byte(0x30), byte(0xF0), byte(0x11), byte(0x12), byte(0x20), byte(0x0F), byte(0xB0), byte(0x84), byte(0x92), byte(0x84), byte(0x00), byte(0xF2), byte(0x39), byte(0x14), byte(0xF3), byte(0x44), byte(0x02), byte(0x0D), byte(0x20), byte(0xD1), byte(0xA4), byte(0x01), byte(0x26), byte(0x2D), byte(0x10), byte(0x04), byte(0x71), byte(0x10), byte(0x62), byte(0x0E), byte(0x37), byte(0x24), byte(0xD1), byte(0x01), byte(0x31), byte(0x06), byte(0x62), byte(0xF5), byte(0x11), byte(0x3C), byte(0xE4), byte(0x84), byte(0xBC), byte(0x44), byte(0x45), byte(0x39), byte(0x13), byte(0x33), byte(0x10), byte(0x21), byte(0xCD), byte(0x38), byte(0xB3), byte(0x86), byte(0x62), byte(0x40), byte(0x8E), byte(0x34), byte(0xE3), byte(0x08), byte(0x0A), byte(0x15), byte(0x03), byte(0x18), byte(0x44), byte(0xE4), byte(0x5C), byte(0x03), byte(0x0F), byte(0x2C), byte(0x48), byte(0x87), byte(0x10), byte(0x22), byte(0xA4), byte(0x35), byte(0x52), byte(0x11), byte(0x38), byte(0xD3), byte(0x04), byte(0x35), byte(0x3A), byte(0xC4), byte(0x1A), byte(0x30), byte(0x11), byte(0x2B), byte(0x31), byte(0x11), byte(0x33), byte(0x10), byte(0x13), byte(0x1C), byte(0x44), byte(0x6B), byte(0x01), byte(0x41), byte(0x87), byte(0x99), byte(0x41), byte(0x12), byte(0x4A), byte(0x20), byte(0x11), byte(0xAC), byte(0xE5), byte(0x84), byte(0x46), byte(0x70), byte(0x0D), byte(0x1A), byte(0xF0), byte(0x12), byte(0x4F), byte(0x23), byte(0x82), byte(0x20), byte(0x02), byte(0xE5), byte(0x39), byte(0x11), byte(0x84), byte(0x4E), byte(0x75), byte(0x0D), byte(0x0D), byte(0x11), byte(0x03), byte(0xC4), byte(0x43), byte(0x0E), byte(0x54), byte(0x4B), byte(0x00), byte(0x34), byte(0x01), byte(0x84), byte(0x46), byte(0x43), byte(0x49), byte(0x39), byte(0x89), byte(0x17), byte(0x00), byte(0x24), byte(0xCB), byte(0x62), byte(0x32), byte(0x04), byte(0x94), byte(0x83), byte(0x40), byte(0x2E), byte(0xC0), byte(0x18), byte(0x04), byte(0x49), byte(0xC4), byte(0x00), byte(0xB4), byte(0xC7), byte(0x94), byte(0xB3), byte(0x8E), byte(0x46), byte(0x21), byte(0xC0), byte(0x34), byte(0x61), byte(0x2B), byte(0x01), byte(0x8B), byte(0xCE), byte(0x39), byte(0x19), byte(0x54), byte(0x36), byte(0x44), byte(0x93), byte(0x00), byte(0x12), byte(0xC8), byte(0x48), byte(0x7C), byte(0xD1), byte(0x20), byte(0x02), byte(0xF2), byte(0x3D), byte(0x12), byte(0x0D), byte(0x1A), byte(0x32), byte(0x0D), byte(0x34), byte(0x44), byte(0x61), byte(0x20), byte(0x6C), byte(0xC7), byte(0x00), byte(0xD2), byte(0xAF), byte(0x44), byte(0xE4), byte(0xC4), byte(0x09), byte(0x38), byte(0x15), byte(0x38), byte(0x80), byte(0xE8), byte(0x30), byte(0x01), byte(0x88), byte(0x34), byte(0x4C), byte(0xCE), byte(0x34), byte(0x81), byte(0x87), byte(0x4F), byte(0x24), byte(0xC0), byte(0x46), byte(0x04), byte(0x4C), byte(0x94), byte(0x83), byte(0x48), byte(0x48), byte(0x7B), byte(0x14), byte(0x48), byte(0x80), byte(0xAE), byte(0x58), byte(0xD1), byte(0x11), byte(0x89), byte(0x16), byte(0x20), byte(0x45), byte(0x3B), byte(0xD1), byte(0x21), byte(0x50), byte(0x13), byte(0x12), byte(0xE4), byte(0xC7), byte(0x11), byte(0x14), byte(0xB2), byte(0x20), byte(0xC3), byte(0xCB), byte(0x12), byte(0xF3), byte(0x8F), byte(0x50), byte(0xB0), byte(0x11), byte(0xC4), byte(0x41), byte(0x4B), byte(0x10), byte(0x24), byte(0xE4), byte(0x48), byte(0xF1), byte(0x02), byte(0x20), byte(0x02), byte(0xCB), byte(0x63), byte(0x23), byte(0x00), byte(0x2C), byte(0xBA), byte(0xC8), byte(0x18), byte(0x74), byte(0xEC), byte(0x11), byte(0x24), byte(0x80), byte(0x18), byte(0x4C), byte(0x93), byte(0x10), byte(0xFA), byte(0x84), byte(0x62), byte(0xF1), byte(0x00), byte(0x08), byte(0x4B), byte(0xD1), byte(0x38), byte(0x64), byte(0x44), byte(0x49), byte(0x28), byte(0x40), byte(0x37), byte(0x22), byte(0x03), byte(0x12), byte(0x64), byte(0x44), byte(0x01), byte(0x39), byte(0x48), byte(0x5E), byte(0x83), byte(0x53), byte(0x11), byte(0x15), byte(0x48), byte(0x11), byte(0x6B), byte(0x00), byte(0x34), byte(0x01), byte(0x84), byte(0xB4), byte(0x04), byte(0xC8), byte(0x38), byte(0xD0), byte(0x0B), byte(0x94), byte(0x84), byte(0x87), byte(0xAC), byte(0xE4), byte(0x84), byte(0x88), byte(0x03), byte(0x04), byte(0x44), byte(0x08), byte(0xC8), byte(0x48), byte(0x25), byte(0x12), byte(0x4A), byte(0x44), byte(0x14), byte(0x00), byte(0xBD), byte(0x84), byte(0x20), byte(0x61), byte(0xD3), byte(0xBC), byte(0x44), byte(0x45), byte(0x39), byte(0x13), byte(0x00), byte(0x34), byte(0x21), byte(0x32), byte(0x11), byte(0x51), byte(0x0D), byte(0xD8), byte(0x04), byte(0xC4), byte(0x46), byte(0xF4), byte(0x4E), byte(0x0D), byte(0x40), byte(0x93), byte(0x20), byte(0xE3), byte(0x6F), byte(0x11), byte(0x14), byte(0x8E), byte(0x34), byte(0x02), byte(0xE2), byte(0x10), byte(0xB2), byte(0xEF), byte(0x39), byte(0x61), byte(0x11), byte(0x91), byte(0x51), byte(0x0D), byte(0x20), byte(0xD1), byte(0xA2), byte(0x38), byte(0xB3), byte(0x91), byte(0xA0), byte(0xD4), byte(0x88), byte(0x0C), byte(0x48), byte(0x40), byte(0x47), byte(0x43), byte(0x48), byte(0x4E), byte(0xB1), byte(0x12), byte(0x4A), byte(0x00), byte(0xD4), byte(0x2D), byte(0x3D), byte(0x88), byte(0x0C), byte(0x4C), byte(0x40), byte(0x34), byte(0x61), byte(0x2C), byte(0x10), byte(0xD4), byte(0xC8), byte(0x38), byte(0xD8), byte(0xC4), byte(0x10), byte(0xF9), byte(0x03), byte(0x18), byte(0x4C), byte(0x93), byte(0x44), byte(0xE3), byte(0x46), byte(0x9C), byte(0x04), byte(0x43), byte(0xCD), byte(0x13), byte(0x94), byte(0x04), byte(0xB1), byte(0x2D), byte(0x10), byte(0x21), byte(0x12), byte(0x48), byte(0x04), byte(0x58), byte(0xC8), byte(0x01), byte(0x44), byte(0x88), byte(0xE3), byte(0x0C), byte(0x38), byte(0xD9), byte(0x44), byte(0x01), byte(0x19), byte(0x40), byte(0x30), byte(0x82), byte(0xD8), byte(0xC8), byte(0x40), byte(0x23), byte(0x44), byte(0x40), byte(0x0C), byte(0x88), byte(0xE3), byte(0x45), byte(0x11), byte(0x11), byte(0x0D), byte(0x08), byte(0x4C), byte(0x44), byte(0x3C), byte(0xB6), byte(0x2F), byte(0x44), byte(0xE3), byte(0xC4), byte(0x45), byte(0x36), byte(0x2C), byte(0x10), byte(0x44), byte(0xC8), byte(0x34), byte(0x68), byte(0x0B), byte(0x58), byte(0x06), byte(0x12), byte(0xC9), byte(0x35), byte(0x05), byte(0x16), byte(0x01), byte(0x84), byte(0x34), byte(0x26), byte(0x23), byte(0x10), byte(0x04), byte(0xC7), byte(0x99), byte(0x13), byte(0x96), byte(0x4C), byte(0x7C), byte(0x84), byte(0x2C), byte(0xBC), byte(0x8E), byte(0x2C), byte(0x32), byte(0x04), byte(0x46), byte(0x00), byte(0x93), byte(0x9C), byte(0x40), byte(0x15), byte(0x63), byte(0x61), byte(0x13), byte(0x84), byte(0x01), byte(0xAC), byte(0x01), byte(0x14), byte(0x48), byte(0x00), byte(0x61), byte(0x23), byte(0x10), byte(0x00), byte(0xF2), byte(0x20), byte(0xD1), byte(0xB1), byte(0x21), byte(0x21), byte(0x23), byte(0x10), byte(0x20), byte(0x03), byte(0x13), byte(0x61), byte(0xCE), byte(0x32), byte(0x52), byte(0x06), byte(0x51), byte(0x11), byte(0x2F), byte(0x38), byte(0xB2), byte(0x02), byte(0x12), byte(0x13), byte(0x83), byte(0x62), byte(0xC0), byte(0x02), byte(0x1C), byte(0x83), byte(0x44), byte(0x88), byte(0x04), byte(0xC4), byte(0x18), byte(0xE4), byte(0x58), byte(0x80), byte(0x71), byte(0x00), byte(0x0E), byte(0x54), byte(0x4E), byte(0x35), byte(0x38), byte(0x80), byte(0x44), byte(0x4B), byte(0x91), byte(0x0C), byte(0x44), byte(0x71), byte(0x10), byte(0x02), byte(0xC8), byte(0x4D), byte(0x8B), byte(0xC0), byte(0x45), byte(0x33), byte(0x44), byte(0x47), byte(0x80), byte(0x11), byte(0x0E), byte(0x11), byte(0x00), byte(0x4F), byte(0x52), byte(0x0E), byte(0x2C), byte(0x43), byte(0x42), byte(0x13), byte(0x33), byte(0x93), byte(0x00), byte(0xB8), byte(0xC4), byte(0x14), byte(0x43), byte(0x52), byte(0x13), byte(0x64), byte(0x48), byte(0x4C), byte(0x48), byte(0x8E), byte(0x35), byte(0x25), byte(0x0C), byte(0x11), byte(0x18), byte(0x84), byte(0x35), byte(0x31), byte(0x11), byte(0x99), byte(0x13), byte(0x94), byte(0x3F), byte(0x31), byte(0xCE), byte(0x50), byte(0x61), byte(0xD3), byte(0xB0), byte(0xE0), byte(0xC4), byte(0x44), byte(0xDC), byte(0xC0), byte(0x48), byte(0xA8), byte(0x8E), byte(0x00), byte(0x21), byte(0xF1), byte(0x10), byte(0x04), byte(0x8E), byte(0x36), byte(0x01), byte(0x84), byte(0x94), byte(0x83), byte(0x46), byte(0x11), byte(0x1C), byte(0x8F), byte(0x10), byte(0x22), byte(0x05), byte(0x20), byte(0x28), byte(0x8E), byte(0x34), byte(0xD1), byte(0x02), byte(0x4C), byte(0x83), byte(0x8D), byte(0xD8), byte(0x84), byte(0x87), byte(0xC4), byte(0x44), byte(0x8F), byte(0x38), byte(0xD4), byte(0x84), byte(0xBD), byte(0x11), byte(0x13), byte(0x4D), byte(0x8B), byte(0x0E), byte(0x54), byte(0x43), byte(0x04), byte(0x35), byte(0x38), byte(0x80), byte(0x44), byte(0x3A), byte(0xCE), byte(0x1A), byte(0xF1), byte(0x0D), byte(0xC9), byte(0x43), byte(0x33), byte(0x44), byte(0x41), byte(0x24), byte(0x35), byte(0x32), byte(0x11), byte(0x12), byte(0x22), byte(0x13), byte(0x21), byte(0x91), byte(0x0D), byte(0xCC), byte(0x74), byte(0x4E), byte(0x50), byte(0x61), byte(0xCE), byte(0x51), byte(0x3B), byte(0xC4), byte(0x4F), byte(0x22), byte(0x0C), byte(0x20), byte(0xB0), byte(0x11), byte(0xD4), byte(0x80), byte(0x93), byte(0x20), byte(0xCB), byte(0x44), byte(0x59), byte(0x23), byte(0xC0), byte(0x3C), byte(0x44), byte(0x73), byte(0x1D), byte(0x11), byte(0x00), byte(0x4E), byte(0x22), byte(0xC0), byte(0x49), byte(0x2C), byte(0x87), byte(0x00), byte(0xA1), byte(0x32), byte(0x39), byte(0x44), byte(0x42), byte(0x12), byte(0x00), byte(0x82), byte(0x39), byte(0x43), byte(0x53), byte(0xBC), byte(0x02), byte(0x0D), byte(0x94), byte(0x02), byte(0xCB), byte(0xC4), byte(0x80), byte(0x87), byte(0xBC), byte(0xE4), byte(0x92), byte(0x20), byte(0x12), byte(0xC4), byte(0x80), byte(0x20), byte(0x84), byte(0x3D), byte(0x3C), byte(0x8E), byte(0x2C), byte(0x80), byte(0xF3), byte(0x44), byte(0x05), byte(0x44), byte(0x2F), byte(0x30), byte(0x0B), byte(0x2B), byte(0x22), byte(0x98), byte(0x89), byte(0x11), byte(0x00), byte(0x4C), byte(0x4B), byte(0x4E), byte(0x34), byte(0x4B), byte(0xCB), byte(0x10), byte(0xD4), byte(0xD8), byte(0xBC), byte(0x44), byte(0x48), byte(0x38), byte(0x38), byte(0xC4), byte(0x14), byte(0x83), byte(0x44), byte(0xB4), byte(0xE4), byte(0x4C), byte(0x00), byte(0xBC), byte(0x44), byte(0x54), byte(0x40), byte(0x0B), byte(0x8D), byte(0x12), byte(0x0D), byte(0x2A), byte(0x05), byte(0x13), byte(0x1C), byte(0xE4), byte(0x72), byte(0x11), byte(0x15), byte(0x44), byte(0xB4), byte(0x03), byte(0x04), byte(0xB0), byte(0xE3), byte(0x04), byte(0x35), byte(0x38), byte(0x06), byte(0x10), byte(0xD4), byte(0xE3), byte(0x38), byte(0x25), byte(0x0C), byte(0x10), byte(0xD4), byte(0xE0), byte(0x09), byte(0x32), byte(0x15), byte(0x21), byte(0x36), byte(0x20), byte(0x35), byte(0x85), byte(0x80), byte(0x62), byte(0x01), byte(0x51), byte(0x00), byte(0x80), byte(0xF3), byte(0x60), byte(0xF1), byte(0x20), byte(0x09), byte(0x32), byte(0x15), byte(0x13), byte(0x34), byte(0x40), byte(0x20), byte(0xDA), byte(0x0D), byte(0x4C), byte(0x44), byte(0x44), byte(0x49), byte(0x32), byte(0x0D), byte(0x1B), byte(0x10), byte(0x03), byte(0x20), byte(0xE8), byte(0xC0), byte(0x34), byte(0x61), byte(0x11), byte(0x98), byte(0x43), byte(0x44), byte(0x44), byte(0x04), byte(0xC8), byte(0x38), byte(0xDA), byte(0xC4), byte(0x00), byte(0x58), byte(0x8E), byte(0x3D), byte(0x8B), byte(0x00), byte(0x4C), byte(0x21), byte(0xE2), byte(0x2C), byte(0x02), byte(0x0C), byte(0x80), byte(0xD6), byte(0x0E), byte(0x34), byte(0x4C), byte(0x8E), byte(0x15), byte(0x35), byte(0x80), byte(0x44), byte(0x4B), byte(0xC0), byte(0x45), byte(0x36), byte(0x23), byte(0x11), byte(0x52), byte(0x02), byte(0x12), byte(0x23), byte(0x83), byte(0x12), byte(0xB0), byte(0x0D), byte(0x19), byte(0x40), byte(0x06), byte(0x12), byte(0xB2), byte(0x0D), byte(0x2A), byte(0x73), byte(0x96), byte(0x11), byte(0x51), byte(0x11), byte(0x88), byte(0xE3), byte(0x45), byte(0x21), byte(0x13), byte(0x22), byte(0x38), byte(0xC3), byte(0x04), byte(0x35), byte(0x38), byte(0x88), byte(0x4D), byte(0x88), byte(0x0D), byte(0x61), byte(0x61), byte(0xC4), byte(0x44), byte(0x4C), byte(0x8E), byte(0x30), byte(0x45), byte(0x87), byte(0x11), byte(0x11), byte(0x23), byte(0x10), byte(0x10), byte(0x13), byte(0x12), byte(0x34), byte(0x48), byte(0x54), byte(0x49), byte(0xC8), byte(0x18), byte(0x71), byte(0x11), byte(0x84), byte(0x40), byte(0x14), byte(0x4C), byte(0x81), byte(0x54), byte(0x2E), byte(0xE3), byte(0x4B), byte(0x20), byte(0xD1), byte(0x36), byte(0x38), byte(0xC0), byte(0x0D), byte(0xBD), byte(0x12), byte(0x0E), byte(0x44), byte(0x84), byte(0xD8), byte(0xCD), byte(0x10), byte(0x03), byte(0x21), byte(0x32), byte(0x0E), byte(0x34), byte(0x02), byte(0xE5), byte(0x39), byte(0x44), byte(0x65), byte(0x20), byte(0xD0), byte(0x0D), byte(0x08), byte(0x80), byte(0x0B), byte(0x79), byte(0xE7), byte(0x9E) }; DictEntry TextCodec::STATIC_DICTIONARY[1024] = {}; const bool* TextCodec::DELIMITER_CHARS = TextCodec::initDelimiterChars(); const bool* TextCodec::TEXT_CHARS = TextCodec::initTextChars(); const int TextCodec::STATIC_DICT_WORDS = TextCodec::createDictionary(TextCodec::unpackDictionary32(DICT_EN_1024, sizeof(DICT_EN_1024)), STATIC_DICTIONARY, 1024, 0); bool* TextCodec::initDelimiterChars() { bool* res = new bool[256]; for (int i = 0; i < 256; i++) { if ((i >= ' ') && (i <= '/')) // [ !"#$%&'()*+,-./] res[i] = true; else if ((i >= ':') && (i <= '?')) // [:;<=>?] res[i] = true; else { switch (i) { case '\n': case '\r': case '\t': case '_': case '|': case '{': case '}': case '[': case ']': res[i] = true; break; default: res[i] = false; } } } return res; } bool* TextCodec::initTextChars() { bool* res = new bool[256]; for (int i = 0; i < 256; i++) { res[i] = isUpperCase(byte(i)) | isLowerCase(byte(i)); } return res; } // Create dictionary from array of words int TextCodec::createDictionary(SliceArray<byte> input, DictEntry dict[], int maxWords, int startWord) { int delimAnchor = 0; int32 h = HASH1; int nbWords = startWord; int dictSize = input._length; byte* words = input._array; for (int i = 0; ((i < dictSize) && (nbWords < maxWords)); i++) { byte cur = words[i]; if (isText(cur)) { h = h * HASH1 ^ int32(cur) * HASH2; continue; } if ((isDelimiter(cur)) && (i >= delimAnchor + 1)) { // At least 2 letters dict[nbWords] = DictEntry(&words[delimAnchor], h, nbWords, i - delimAnchor); nbWords++; } delimAnchor = i + 1; h = HASH1; } return nbWords; } // Unpack dictionary with 32 symbols (all lowercase except first word char) SliceArray<byte> TextCodec::unpackDictionary32(const byte dict[], int dictSize) { byte* buf = new byte[dictSize * 2]; int d = 0; int val = 0; // Unpack 3 bytes into 4 6-bit symbols for (int i = 0; i < dictSize; i++) { val = (val << 8) | (int(dict[i]) & 0xFF); if ((i % 3) == 2) { for (int ii = 18; ii >= 0; ii -= 6) { int c = (val >> ii) & 0x3F; if (c >= 32) buf[d++] = TextCodec::SP; c &= 0x1F; // Ignore padding symbols (> 26 and <= 31) if (c <= 26) buf[d++] = byte(c + 'a'); } val = 0; } } buf[d] = TextCodec::SP; // End byte* res = new byte[d]; memcpy(&res[0], &buf[1], d); delete[] buf; return SliceArray<byte>(res, d, 0); } // return 8-bit status (see MASK flags constants) byte TextCodec::computeStats(byte block[], int count, int32 freqs0[]) { int32 freqs[256][256] = { { 0 } }; int32 f0[256] = { 0 }; int32 f1[256] = { 0 }; int32 f3[256] = { 0 }; int32 f2[256] = { 0 }; uint8* data = (uint8*)&block[0]; uint8 prv = 0; const int count4 = count & -4; // Unroll loop for (int i = 0; i < count4; i += 4) { const uint8 cur0 = data[i]; const uint8 cur1 = data[i + 1]; const uint8 cur2 = data[i + 2]; const uint8 cur3 = data[i + 3]; f0[cur0]++; f1[cur1]++; f2[cur2]++; f3[cur3]++; freqs[prv][cur0]++; freqs[cur0][cur1]++; freqs[cur1][cur2]++; freqs[cur2][cur3]++; prv = cur3; } for (int i = count4; i<count; i++) { freqs0[data[i]]++; freqs[prv][data[i]]++; prv = data[i]; } for (int i = 0; i < 256; i++) { freqs0[i] += (f0[i] + f1[i] + f2[i] + f3[i]); } int nbTextChars = 0; for (int i = 32; i < 128; i++) { if (isText(byte(i)) == true) nbTextChars += freqs0[i]; } // Not text (crude threshold) if (2 * nbTextChars < count) return TextCodec::MASK_NOT_TEXT; int nbBinChars = 0; for (int i = 128; i < 256; i++) nbBinChars += freqs0[i]; // Not text (crude threshold) if ((4 * nbBinChars > count) || (16 * freqs0[32] < count)) return TextCodec::MASK_NOT_TEXT; byte res = byte(0); if (nbBinChars == 0) res |= TextCodec::MASK_FULL_ASCII; else if (nbBinChars <= count / 100) res |= TextCodec::MASK_ALMOST_FULL_ASCII; if (nbBinChars <= count - count / 10) { // Check if likely XML/HTML // Another crude test: check that the frequencies of < and > are similar // and 'high enough'. Also check it is worth to attempt replacing ampersand sequences. // Getting this flag wrong results in a very small compression speed degradation. const int32 f1 = freqs0[60]; // '<' const int32 f2 = freqs0[62]; // '>' const int32 f3 = freqs[38][97] + freqs[38][103] + freqs[38][108] + freqs[38][113]; // '&a', '&g', '&l', '&q' const int32 minFreq = (((count - nbBinChars) >> 9) < 2) ? 2 : (count - nbBinChars) >> 9; if ((f1 >= minFreq) && (f2 >= minFreq) && (f3 > 0)) { if (f1 < f2) { if (f1 >= (f2 - f2 / 100)) res |= TextCodec::MASK_XML_HTML; } else if (f2 < f1) { if (f2 >= (f1 - f1 / 100)) res |= TextCodec::MASK_XML_HTML; } else res |= TextCodec::MASK_XML_HTML; } } // Check CR+LF matches const int cr = int(CR); const int lf = int(LF); if ((freqs0[cr] != 0) && (freqs0[cr] == freqs0[lf])) { res |= TextCodec::MASK_CRLF; for (int i = 0; i < 256; i++) { if ((i != lf) && (freqs[cr][i]) != 0) { res &= ~TextCodec::MASK_CRLF; break; } } } return res; } TextCodec::TextCodec() { _delegate = new TextCodec1(); } TextCodec::TextCodec(Context& ctx) { int encodingType = ctx.getInt("textcodec", 1); _delegate = (encodingType == 1) ? (Function<byte>*) new TextCodec1(ctx) : (Function<byte>*) new TextCodec2(ctx); } bool TextCodec::forward(SliceArray<byte>& input, SliceArray<byte>& output, int count) THROW { if (count == 0) return true; if (!SliceArray<byte>::isValid(input)) throw invalid_argument("Invalid input block"); if (!SliceArray<byte>::isValid(output)) throw invalid_argument("Invalid output block"); if (input._array == output._array) return false; if (count > MAX_BLOCK_SIZE) { // Not a recoverable error: instead of silently fail the transform, // issue a fatal error. stringstream ss; ss << "The max text transform block size is " << MAX_BLOCK_SIZE << ", got " << count; throw invalid_argument(ss.str()); } return _delegate->forward(input, output, count); } bool TextCodec::inverse(SliceArray<byte>& input, SliceArray<byte>& output, int count) THROW { if (count == 0) return true; if (!SliceArray<byte>::isValid(input)) throw invalid_argument("Invalid input block"); if (!SliceArray<byte>::isValid(output)) throw invalid_argument("Invalid output block"); if (input._array == output._array) return false; if (count > MAX_BLOCK_SIZE) { // Not a recoverable error: instead of silently fail the transform, // issue a fatal error. stringstream ss; ss << "The max text transform block size is " << MAX_BLOCK_SIZE << ", got " << count; throw invalid_argument(ss.str()); } return _delegate->inverse(input, output, count); } TextCodec1::TextCodec1() { _logHashSize = TextCodec::LOG_HASHES_SIZE; _dictSize = TextCodec::THRESHOLD2 * 4; _dictMap = nullptr; _dictList = nullptr; _hashMask = (1 << _logHashSize) - 1; _staticDictSize = TextCodec::STATIC_DICT_WORDS; _isCRLF = false; } TextCodec1::TextCodec1(Context& ctx) { // Actual block size int blockSize = 0; int log = 13; int dSize = 1 << 12; if (ctx.has("blockSize")) { blockSize = ctx.getInt("blockSize"); if (blockSize >= 8) log = max(min(Global::log2(blockSize / 8), 26), 13); // Select an appropriate initial dictionary size dSize = 1 << max(min(log - 4, 18), 12); } uint extraMem = 0; if (ctx.has("extra")) { string strExtra = ctx.getString("extra"); extraMem = (strExtra.compare(0, 5, "TRUE") == 0) ? 1 : 0; } _logHashSize = log + extraMem; _dictSize = dSize; _dictMap = nullptr; _dictList = nullptr; _hashMask = (1 << _logHashSize) - 1; _staticDictSize = TextCodec::STATIC_DICT_WORDS; _isCRLF = false; } void TextCodec1::reset() { const int mapSize = 1 << _logHashSize; if (_dictMap == nullptr) _dictMap = new DictEntry*[mapSize]; for (int i = 0; i < mapSize; i++) _dictMap[i] = nullptr; if (_dictList == nullptr) { _dictList = new DictEntry[_dictSize]; const int nbEntries = min(TextCodec::STATIC_DICT_WORDS, _dictSize); memcpy(static_cast<void*>(&_dictList[0]), &TextCodec::STATIC_DICTIONARY[0], nbEntries * sizeof(DictEntry)); // Add special entries at start of map _escapes[0] = TextCodec::ESCAPE_TOKEN2; _escapes[1] = TextCodec::ESCAPE_TOKEN1; const int nbWords = TextCodec::STATIC_DICT_WORDS; _dictList[nbWords] = DictEntry(&_escapes[0], 0, nbWords, 1); _dictList[nbWords + 1] = DictEntry(&_escapes[1], 0, nbWords + 1, 1); _staticDictSize = nbWords + 2; } for (int i = 0; i < _staticDictSize; i++) _dictMap[_dictList[i]._hash & _hashMask] = &_dictList[i]; // Pre-allocate all dictionary entries for (int i = _staticDictSize; i < _dictSize; i++) _dictList[i] = DictEntry(nullptr, 0, i, 0); } bool TextCodec1::forward(SliceArray<byte>& input, SliceArray<byte>& output, int count) { if (output._length - output._index < getMaxEncodedLength(count)) return false; byte* src = &input._array[input._index]; byte* dst = &output._array[output._index]; int srcIdx = 0; int dstIdx = 0; int32 freqs[256] = { 0 }; byte mode = TextCodec::computeStats(&src[srcIdx], count, freqs); // Not text ? if ((mode & TextCodec::MASK_NOT_TEXT) != byte(0)) return false; reset(); const int srcEnd = count; const int dstEnd = getMaxEncodedLength(count); const int dstEnd4 = dstEnd - 4; int emitAnchor = 0; // never less than 0 int words = _staticDictSize; // DOS encoded end of line (CR+LF) ? _isCRLF = int(mode & TextCodec::MASK_CRLF) != 0; dst[dstIdx++] = mode; bool res = true; while ((srcIdx < srcEnd) && (src[srcIdx] == TextCodec::SP)) { dst[dstIdx++] = TextCodec::SP; srcIdx++; emitAnchor++; } int delimAnchor = TextCodec::isText(src[srcIdx]) ? srcIdx - 1 : srcIdx; // previous delimiter while (srcIdx < srcEnd) { if (TextCodec::isText(src[srcIdx])) { srcIdx++; continue; } if ((srcIdx > delimAnchor + 2) && TextCodec::isDelimiter(src[srcIdx])) { // At least 2 letters const byte val = src[delimAnchor + 1]; const int length = srcIdx - delimAnchor - 1; if (length < TextCodec::MAX_WORD_LENGTH) { // Compute hashes // h1 -> hash of word chars // h2 -> hash of word chars with first char case flipped const int32 caseFlag = TextCodec::isUpperCase(val) ? 32 : -32; int32 h1 = TextCodec::HASH1; int32 h2 = TextCodec::HASH1; h1 = h1 * TextCodec::HASH1 ^ int32(val) * TextCodec::HASH2; h2 = h2 * TextCodec::HASH1 ^ (int32(val) + caseFlag) * TextCodec::HASH2; for (int i = delimAnchor + 2; i < srcIdx; i++) { h1 = h1 * TextCodec::HASH1 ^ int32(src[i]) * TextCodec::HASH2; h2 = h2 * TextCodec::HASH1 ^ int32(src[i]) * TextCodec::HASH2; } // Check word in dictionary DictEntry* pe = nullptr; prefetchRead(&_dictMap[h1 & _hashMask]); DictEntry* pe1 = _dictMap[h1 & _hashMask]; // Check for hash collisions if ((pe1 != nullptr) && (pe1->_hash == h1) && ((pe1->_data >> 24) == length)) pe = pe1; if (pe == nullptr) { prefetchRead(&_dictMap[h2 & _hashMask]); DictEntry* pe2 = _dictMap[h2 & _hashMask]; if ((pe2 != nullptr) && (pe2->_hash == h2) && ((pe2->_data >> 24) == length)) pe = pe2; } if (pe != nullptr) { if (!TextCodec::sameWords(pe->_ptr + 1, &src[delimAnchor + 2], length - 1)) pe = nullptr; } if (pe == nullptr) { // Word not found in the dictionary or hash collision. // Replace entry if not in static dictionary if (((length > 3) || ((length > 2) && (words < TextCodec::THRESHOLD2))) && (pe1 == nullptr)) { DictEntry* pe = &_dictList[words]; if ((pe->_data & 0x00FFFFFF) >= _staticDictSize) { // Reuse old entry _dictMap[pe->_hash & _hashMask] = nullptr; pe->_ptr = &src[delimAnchor + 1]; pe->_hash = h1; pe->_data = (length << 24) | words; } // Update hash map _dictMap[h1 & _hashMask] = pe; words++; // Dictionary full ? Expand or reset index to end of static dictionary if (words >= _dictSize) { if (expandDictionary() == false) words = _staticDictSize; } } } else { // Word found in the dictionary // Skip space if only delimiter between 2 word references if ((emitAnchor != delimAnchor) || (src[delimAnchor] != byte(' '))) { int dIdx = emitSymbols(&src[emitAnchor], &dst[dstIdx], delimAnchor + 1 - emitAnchor, dstEnd - dstIdx); if (dIdx < 0) { res = false; break; } dstIdx += dIdx; } if (dstIdx >= dstEnd4){ res = false; break; } dst[dstIdx++] = (pe == pe1) ? TextCodec::ESCAPE_TOKEN1 : TextCodec::ESCAPE_TOKEN2; dstIdx += emitWordIndex(&dst[dstIdx], pe->_data & 0x00FFFFFF); emitAnchor = delimAnchor + 1 + int(pe->_data >> 24); } } } // Reset delimiter position delimAnchor = srcIdx; srcIdx++; } if (res == true) { // Emit last symbols int dIdx = emitSymbols(&src[emitAnchor], &dst[dstIdx], srcEnd - emitAnchor, dstEnd - dstIdx); if (dIdx < 0) res = false; else dstIdx += dIdx; res &= (srcIdx == srcEnd); } output._index += dstIdx; input._index += srcIdx; return res; } bool TextCodec1::expandDictionary() { if (_dictSize >= TextCodec::MAX_DICT_SIZE) return false; DictEntry* newDict = new DictEntry[_dictSize * 2]; memcpy(static_cast<void*>(&newDict[0]), &_dictList[0], sizeof(DictEntry) * _dictSize); for (int i = _dictSize; i < _dictSize * 2; i++) newDict[i] = DictEntry(nullptr, 0, i, 0); delete[] _dictList; _dictList = newDict; // Reset map (values must point to addresses of new DictEntry items) for (int i = 0; i < _dictSize; i++) { _dictMap[_dictList[i]._hash & _hashMask] = &_dictList[i]; } _dictSize <<= 1; return true; } int TextCodec1::emitSymbols(byte src[], byte dst[], const int srcEnd, const int dstEnd) { int dstIdx = 0; for (int i = 0; i < srcEnd; i++) { if (dstIdx >= dstEnd) return -1; const byte cur = src[i]; switch (cur) { case TextCodec::ESCAPE_TOKEN1: case TextCodec::ESCAPE_TOKEN2: { // Emit special word dst[dstIdx++] = TextCodec::ESCAPE_TOKEN1; const int idx = (cur == TextCodec::ESCAPE_TOKEN1) ? _staticDictSize - 1 : _staticDictSize - 2; int lenIdx = 1; if (idx >= TextCodec::THRESHOLD1) lenIdx = (idx >= TextCodec::THRESHOLD2) ? 3 : 2; if (dstIdx + lenIdx >= dstEnd) return -1; dstIdx += emitWordIndex(&dst[dstIdx], idx); break; } case TextCodec::CR: if (_isCRLF == false) dst[dstIdx++] = cur; break; default: dst[dstIdx++] = cur; } } return dstIdx; } int TextCodec1::emitWordIndex(byte dst[], int val) { // Emit word index (varint 5 bits + 7 bits + 7 bits) if (val >= TextCodec::THRESHOLD1) { int dstIdx = 0; if (val >= TextCodec::THRESHOLD2) dst[dstIdx++] = byte(0xE0 | (val >> 14)); dst[dstIdx] = byte(0x80 | (val >> 7)); dst[dstIdx + 1] = byte(0x7F & val); return dstIdx + 2; } dst[0] = byte(val); return 1; } bool TextCodec1::inverse(SliceArray<byte>& input, SliceArray<byte>& output, int count) { byte* src = &input._array[input._index]; byte* dst = &output._array[output._index]; int srcIdx = 0; int dstIdx = 0; reset(); const int srcEnd = count; const int dstEnd = output._length; int delimAnchor = TextCodec::isText(src[srcIdx]) ? srcIdx - 1 : srcIdx; // previous delimiter int words = _staticDictSize; bool wordRun = false; _isCRLF = int(src[srcIdx++] & TextCodec::MASK_CRLF) != 0; while ((srcIdx < srcEnd) && (dstIdx < dstEnd)) { byte cur = src[srcIdx]; if (TextCodec::isText(cur)) { dst[dstIdx] = cur; srcIdx++; dstIdx++; continue; } if ((srcIdx > delimAnchor + 2) && TextCodec::isDelimiter(cur)) { const int length = srcIdx - delimAnchor - 1; if (length < TextCodec::MAX_WORD_LENGTH) { int32 h1 = TextCodec::HASH1; for (int i = delimAnchor + 1; i < srcIdx; i++) h1 = h1 * TextCodec::HASH1 ^ int32(src[i]) * TextCodec::HASH2; // Lookup word in dictionary DictEntry* pe = nullptr; DictEntry* pe1 = _dictMap[h1 & _hashMask]; // Check for hash collisions if ((pe1 != nullptr) && (pe1->_hash == h1) && ((pe1->_data >> 24) == length)) { if (TextCodec::sameWords(pe1->_ptr + 1, &src[delimAnchor + 2], length - 1)) pe = pe1; } if (pe == nullptr) { // Word not found in the dictionary or hash collision. // Replace entry if not in static dictionary if (((length > 3) || ((length > 2) && (words < TextCodec::THRESHOLD2))) && (pe1 == nullptr)) { DictEntry& e = _dictList[words]; if ((e._data & 0x00FFFFFF) >= _staticDictSize) { // Reuse old entry _dictMap[e._hash & _hashMask] = nullptr; e._ptr = &src[delimAnchor + 1]; e._hash = h1; e._data = (length << 24) | words; } _dictMap[h1 & _hashMask] = &e; words++; // Dictionary full ? Expand or reset index to end of static dictionary if (words >= _dictSize) { if (expandDictionary() == false) words = _staticDictSize; } } } } } srcIdx++; if ((cur == TextCodec::ESCAPE_TOKEN1) || (cur == TextCodec::ESCAPE_TOKEN2)) { // Word in dictionary // Read word index (varint 5 bits + 7 bits + 7 bits) int idx = int(src[srcIdx++]) & 0xFF; if ((idx & 0x80) != 0) { idx &= 0x7F; int idx2 = int(src[srcIdx++]); if ((idx2 & 0x80) != 0) { idx = ((idx & 0x1F) << 7) | (idx2 & 0x7F); idx2 = int(src[srcIdx++]); } idx = (idx << 7) | (idx2 & 0x7F); if (idx >= _dictSize) break; } const DictEntry& e = _dictList[idx]; const int length = e._data >> 24; const byte* buf = e._ptr; // Sanity check if ((buf == nullptr) || (dstIdx + length >= dstEnd)) break; // Add space if only delimiter between 2 words (not an escaped delimiter) if ((wordRun == true) && (length > 1)) dst[dstIdx++] = TextCodec::SP; // Emit word if (cur != TextCodec::ESCAPE_TOKEN2) { dst[dstIdx] = *buf; } else { // Flip case of first character dst[dstIdx] = TextCodec::isUpperCase(buf[0]) ? byte(uint8(buf[0]) + 32) : byte(uint8(buf[0]) - 32); } if (length > 1) { memcpy(&dst[dstIdx+1], &buf[1], length-1); // Regular word entry wordRun = true; delimAnchor = srcIdx; } else { // Escape entry wordRun = false; delimAnchor = srcIdx - 1; } dstIdx += length; } else { wordRun = false; delimAnchor = srcIdx - 1; if ((_isCRLF == true) && (cur == TextCodec::LF)) dst[dstIdx++] = TextCodec::CR; dst[dstIdx++] = cur; } } output._index += dstIdx; input._index += srcIdx; return srcIdx == srcEnd; } TextCodec2::TextCodec2() { _logHashSize = TextCodec::LOG_HASHES_SIZE; _dictSize = TextCodec::THRESHOLD2 * 4; _dictMap = nullptr; _dictList = nullptr; _hashMask = (1 << _logHashSize) - 1; _staticDictSize = TextCodec::STATIC_DICT_WORDS; _isCRLF = false; } TextCodec2::TextCodec2(Context& ctx) { // Actual block size int blockSize = 0; int log = 13; int dSize = 1 << 12; if (ctx.has("blockSize")) { blockSize = ctx.getInt("blockSize"); if (blockSize >= 8) log = max(min(Global::log2(blockSize / 8), 26), 13); // Select an appropriate initial dictionary size dSize = 1 << max(min(log - 4, 18), 12); } uint extraMem = 0; if (ctx.has("extra")) { string strExtra = ctx.getString("extra"); extraMem = (strExtra.compare(0, 5, "TRUE") == 0) ? 1 : 0; } _logHashSize = log + extraMem; _dictSize = dSize; _dictMap = nullptr; _dictList = nullptr; _hashMask = (1 << _logHashSize) - 1; _staticDictSize = TextCodec::STATIC_DICT_WORDS; _isCRLF = false; } void TextCodec2::reset() { const int mapSize = 1 << _logHashSize; if (_dictMap == nullptr) _dictMap = new DictEntry*[mapSize]; for (int i = 0; i < mapSize; i++) _dictMap[i] = nullptr; if (_dictList == nullptr) { _dictList = new DictEntry[_dictSize]; const int nbEntries = min(TextCodec::STATIC_DICT_WORDS, _dictSize); memcpy(static_cast<void*>(&_dictList[0]), &TextCodec::STATIC_DICTIONARY[0], nbEntries * sizeof(DictEntry)); } for (int i = 0; i < _staticDictSize; i++) _dictMap[_dictList[i]._hash & _hashMask] = &_dictList[i]; // Pre-allocate all dictionary entries for (int i = _staticDictSize; i < _dictSize; i++) _dictList[i] = DictEntry(nullptr, 0, i, 0); } bool TextCodec2::forward(SliceArray<byte>& input, SliceArray<byte>& output, int count) { if (output._length - output._index < getMaxEncodedLength(count)) return false; byte* src = &input._array[input._index]; byte* dst = &output._array[output._index]; int srcIdx = 0; int dstIdx = 0; int32 freqs[256]= { 0 }; byte mode = TextCodec::computeStats(&src[srcIdx], count, freqs); // Not text ? if ((mode & TextCodec::MASK_NOT_TEXT) != byte(0)) return false; reset(); const int srcEnd = count; const int dstEnd = getMaxEncodedLength(count); const int dstEnd3 = dstEnd - 3; int emitAnchor = 0; // never less than 0 int words = _staticDictSize; // DOS encoded end of line (CR+LF) ? _isCRLF = (mode & TextCodec::MASK_CRLF) != byte(0); dst[dstIdx++] = mode; bool res = true; while ((srcIdx < srcEnd) && (src[srcIdx] == TextCodec::SP)) { dst[dstIdx++] = TextCodec::SP; srcIdx++; emitAnchor++; } int delimAnchor = TextCodec::isText(src[srcIdx]) ? srcIdx - 1 : srcIdx; // previous delimiter while (srcIdx < srcEnd) { if (TextCodec::isText(src[srcIdx])) { srcIdx++; continue; } if ((srcIdx > delimAnchor + 2) && TextCodec::isDelimiter(src[srcIdx])) { const byte val = src[delimAnchor + 1]; const int length = srcIdx - delimAnchor - 1; if (length < TextCodec::MAX_WORD_LENGTH) { // Compute hashes // h1 -> hash of word chars // h2 -> hash of word chars with first char case flipped const int32 caseFlag = TextCodec::isUpperCase(val) ? 32 : -32; int32 h1 = TextCodec::HASH1; int32 h2 = TextCodec::HASH1; h1 = h1 * TextCodec::HASH1 ^ int32(val) * TextCodec::HASH2; h2 = h2 * TextCodec::HASH1 ^ (int32(val) + caseFlag) * TextCodec::HASH2; for (int i = delimAnchor + 2; i < srcIdx; i++) { h1 = h1 * TextCodec::HASH1 ^ int32(src[i]) * TextCodec::HASH2; h2 = h2 * TextCodec::HASH1 ^ int32(src[i]) * TextCodec::HASH2; } // Check word in dictionary DictEntry* pe = nullptr; prefetchRead(&_dictMap[h1 & _hashMask]); DictEntry* pe1 = _dictMap[h1 & _hashMask]; // Check for hash collisions if ((pe1 != nullptr) && (pe1->_hash == h1) && ((pe1->_data >> 24) == length)) pe = pe1; if (pe == nullptr) { prefetchRead(&_dictMap[h2 & _hashMask]); DictEntry* pe2 = _dictMap[h2 & _hashMask]; if ((pe2 != nullptr) && (pe2->_hash == h2) && ((pe2->_data >> 24) == length)) pe = pe2; } if (pe != nullptr) { if (!TextCodec::sameWords(pe->_ptr + 1, &src[delimAnchor + 2], length - 1)) pe = nullptr; } if (pe == nullptr) { // Word not found in the dictionary or hash collision. // Replace entry if not in static dictionary if (((length > 3) || ((length > 2) && (words < TextCodec::THRESHOLD2))) && (pe1 == nullptr)) { DictEntry* pe = &_dictList[words]; if ((pe->_data & 0x00FFFFFF) >= _staticDictSize) { // Reuse old entry _dictMap[pe->_hash & _hashMask] = nullptr; pe->_ptr = &src[delimAnchor + 1]; pe->_hash = h1; pe->_data = (length << 24) | words; } // Update hash map _dictMap[h1 & _hashMask] = pe; words++; // Dictionary full ? Expand or reset index to end of static dictionary if (words >= _dictSize) { if (expandDictionary() == false) words = _staticDictSize; } } } else { // Word found in the dictionary // Skip space if only delimiter between 2 word references if ((emitAnchor != delimAnchor) || (src[delimAnchor] != TextCodec::SP)) { int dIdx = emitSymbols(&src[emitAnchor], &dst[dstIdx], delimAnchor + 1 - emitAnchor, dstEnd - dstIdx); if (dIdx < 0) { res = false; break; } dstIdx += dIdx; } if (dstIdx >= dstEnd3){ res = false; break; } dstIdx += emitWordIndex(&dst[dstIdx], pe->_data & 0x00FFFFFF, (pe == pe1) ? 0 : 32); emitAnchor = delimAnchor + 1 + int(pe->_data >> 24); } } } // Reset delimiter position delimAnchor = srcIdx; srcIdx++; } if (res == true) { // Emit last symbols int dIdx = emitSymbols(&src[emitAnchor], &dst[dstIdx], srcEnd - emitAnchor, dstEnd - dstIdx); if (dIdx < 0) res = false; else dstIdx += dIdx; res &= (srcIdx == srcEnd); } output._index += dstIdx; input._index += srcIdx; return res; } bool TextCodec2::expandDictionary() { if (_dictSize >= TextCodec::MAX_DICT_SIZE) return false; DictEntry* newDict = new DictEntry[_dictSize * 2]; memcpy(static_cast<void*>(&newDict[0]), &_dictList[0], sizeof(DictEntry) * _dictSize); for (int i = _dictSize; i < _dictSize * 2; i++) newDict[i] = DictEntry(nullptr, 0, i, 0); delete[] _dictList; _dictList = newDict; // Reset map (values must point to addresses of new DictEntry items) for (int i = 0; i < _dictSize; i++) { _dictMap[_dictList[i]._hash & _hashMask] = &_dictList[i]; } _dictSize <<= 1; return true; } int TextCodec2::emitSymbols(byte src[], byte dst[], const int srcEnd, const int dstEnd) { int dstIdx = 0; if (2 * srcEnd < dstEnd) { for (int i = 0; i < srcEnd; i++) { const byte cur = src[i]; switch (cur) { case TextCodec::ESCAPE_TOKEN1: dst[dstIdx++] = TextCodec::ESCAPE_TOKEN1; dst[dstIdx++] = TextCodec::ESCAPE_TOKEN1; break; case TextCodec::CR: if (_isCRLF == false) dst[dstIdx++] = cur; break; default: if ((cur & TextCodec::MASK_80) != byte(0)) dst[dstIdx++] = TextCodec::ESCAPE_TOKEN1; dst[dstIdx++] = cur; } } } else { for (int i = 0; i < srcEnd; i++) { const byte cur = src[i]; switch (cur) { case TextCodec::ESCAPE_TOKEN1: if (dstIdx >= dstEnd - 1) return -1; dst[dstIdx++] = TextCodec::ESCAPE_TOKEN1; dst[dstIdx++] = TextCodec::ESCAPE_TOKEN1; break; case TextCodec::CR: if (_isCRLF == false) { if (dstIdx >= dstEnd) return -1; dst[dstIdx++] = cur; } break; default: if ((cur & TextCodec::MASK_80) != byte(0)) { if (dstIdx >= dstEnd) return -1; dst[dstIdx++] = TextCodec::ESCAPE_TOKEN1; } if (dstIdx >= dstEnd) return -1; dst[dstIdx++] = cur; } } } return dstIdx; } int TextCodec2::emitWordIndex(byte dst[], int val, int mask) { // Emit word index (varint 5 bits + 7 bits + 7 bits) // 1st byte: 0x80 => word idx, 0x40 => more bytes, 0x20 => toggle case 1st symbol // 2nd byte: 0x80 => 1 more byte if (val >= TextCodec::THRESHOLD3) { if (val >= TextCodec::THRESHOLD4) { // 5 + 7 + 7 => 2^19 dst[0] = byte(0xC0 | mask | ((val >> 14) & 0x1F)); dst[1] = byte(0x80 | ((val >> 7) & 0x7F)); dst[2] = byte(val & 0x7F); return 3; } // 5 + 7 => 2^12 = 32*128 dst[0] = byte(0xC0 | mask | ((val >> 7) & 0x1F)); dst[1] = byte(val & 0x7F); return 2; } // 5 => 32 dst[0] = byte(0x80 | mask | val); return 1; } bool TextCodec2::inverse(SliceArray<byte>& input, SliceArray<byte>& output, int count) { byte* src = &input._array[input._index]; byte* dst = &output._array[output._index]; int srcIdx = 0; int dstIdx = 0; reset(); const int srcEnd = count; const int dstEnd = output._length; int delimAnchor = TextCodec::isText(src[srcIdx]) ? srcIdx - 1 : srcIdx; // previous delimiter int words = _staticDictSize; bool wordRun = false; _isCRLF = (src[srcIdx++] & TextCodec::MASK_CRLF) != byte(0); while ((srcIdx < srcEnd) && (dstIdx < dstEnd)) { byte cur = src[srcIdx]; if (TextCodec::isText(cur)) { dst[dstIdx] = cur; srcIdx++; dstIdx++; continue; } if ((srcIdx > delimAnchor + 2) && TextCodec::isDelimiter(cur)) { const int length = srcIdx - delimAnchor - 1; if (length < TextCodec::MAX_WORD_LENGTH) { int32 h1 = TextCodec::HASH1; for (int i = delimAnchor + 1; i < srcIdx; i++) h1 = h1 * TextCodec::HASH1 ^ int32(src[i]) * TextCodec::HASH2; // Lookup word in dictionary DictEntry* pe = nullptr; DictEntry* pe1 = _dictMap[h1 & _hashMask]; // Check for hash collisions if ((pe1 != nullptr) && (pe1->_hash == h1) && ((pe1->_data >> 24) == length)) { if (TextCodec::sameWords(pe1->_ptr + 1, &src[delimAnchor + 2], length - 1)) pe = pe1; } if (pe == nullptr) { // Word not found in the dictionary or hash collision. // Replace entry if not in static dictionary if (((length > 3) || ((length > 2) && (words < TextCodec::THRESHOLD2))) && (pe1 == nullptr)) { DictEntry& e = _dictList[words]; if ((e._data & 0x00FFFFFF) >= _staticDictSize) { // Reuse old entry _dictMap[e._hash & _hashMask] = nullptr; e._ptr = &src[delimAnchor + 1]; e._hash = h1; e._data = (length << 24) | words; } _dictMap[h1 & _hashMask] = &e; words++; // Dictionary full ? Expand or reset index to end of static dictionary if (words >= _dictSize) { if (expandDictionary() == false) words = _staticDictSize; } } } } } srcIdx++; if ((cur & TextCodec::MASK_80) != byte(0)) { // Word in dictionary // Read word index (varint 5 bits + 7 bits + 7 bits) int idx = int(cur & TextCodec::MASK_1F); if ((cur & TextCodec::MASK_40) != byte(0)) { int idx2 = int(src[srcIdx++]); if ((idx2 & 0x80) != 0) { idx = (idx << 7) | (idx2 & 0x7F); idx2 = int(src[srcIdx++]); } idx = (idx << 7) | (idx2 & 0x7F); if (idx >= _dictSize) break; } const DictEntry& e = _dictList[idx]; const int length = e._data >> 24; const byte* buf = e._ptr; // Sanity check if ((buf == nullptr) || (dstIdx + length >= dstEnd)) break; // Add space if only delimiter between 2 words (not an escaped delimiter) if ((wordRun == true) && (length > 1)) dst[dstIdx++] = TextCodec::SP; // Emit word if ((cur & TextCodec::MASK_20) == byte(0)) { dst[dstIdx] = *buf; } else { // Flip case of first character dst[dstIdx] = TextCodec::isUpperCase(buf[0]) ? byte(uint8(buf[0]) + 32) : byte(uint8(buf[0]) - 32); } if (length > 1) { memcpy(&dst[dstIdx+1], &buf[1], length-1); // Regular word entry wordRun = true; delimAnchor = srcIdx; } else { // Escape entry wordRun = false; delimAnchor = srcIdx - 1; } dstIdx += length; } else { // Escape token followed by symbol > 0x80 ? if (cur == TextCodec::ESCAPE_TOKEN1) { dst[dstIdx++] = src[srcIdx++]; } else { if ((_isCRLF == true) && (cur == TextCodec::LF)) dst[dstIdx++] = TextCodec::CR; dst[dstIdx++] = cur; } wordRun = false; delimAnchor = srcIdx - 1; } } output._index += dstIdx; input._index += srcIdx; return srcIdx == srcEnd; }
46.362108
164
0.631943
[ "transform" ]
5b327d40ac69d6e1b07a4acf689c5c5ccb613911
23,082
cpp
C++
core/jni/android_hardware_SensorManager.cpp
rio-31/android_frameworks_base-1
091a068a3288d27d77636708679dde58b7b7fd25
[ "Apache-2.0" ]
164
2015-01-05T16:49:11.000Z
2022-03-29T20:40:27.000Z
core/jni/android_hardware_SensorManager.cpp
rio-31/android_frameworks_base-1
091a068a3288d27d77636708679dde58b7b7fd25
[ "Apache-2.0" ]
127
2015-01-12T12:02:32.000Z
2021-11-28T08:46:25.000Z
core/jni/android_hardware_SensorManager.cpp
rio-31/android_frameworks_base-1
091a068a3288d27d77636708679dde58b7b7fd25
[ "Apache-2.0" ]
1,141
2015-01-01T22:54:40.000Z
2022-02-09T22:08:26.000Z
/* * Copyright 2008, 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. */ #define LOG_TAG "SensorManager" #include <nativehelper/JNIHelp.h> #include "android_os_MessageQueue.h" #include "core_jni_helpers.h" #include "jni.h" #include <nativehelper/ScopedUtfChars.h> #include <nativehelper/ScopedLocalRef.h> #include <android_runtime/AndroidRuntime.h> #include <android_runtime/android_hardware_HardwareBuffer.h> #include <vndk/hardware_buffer.h> #include <sensor/Sensor.h> #include <sensor/SensorEventQueue.h> #include <sensor/SensorManager.h> #include <cutils/native_handle.h> #include <utils/Log.h> #include <utils/Looper.h> #include <utils/Vector.h> #include <map> namespace { using namespace android; struct { jclass clazz; jmethodID dispatchSensorEvent; jmethodID dispatchFlushCompleteEvent; jmethodID dispatchAdditionalInfoEvent; } gBaseEventQueueClassInfo; struct SensorOffsets { jclass clazz; //fields jfieldID name; jfieldID vendor; jfieldID version; jfieldID handle; jfieldID range; jfieldID resolution; jfieldID power; jfieldID minDelay; jfieldID fifoReservedEventCount; jfieldID fifoMaxEventCount; jfieldID stringType; jfieldID requiredPermission; jfieldID maxDelay; jfieldID flags; //methods jmethodID setType; jmethodID setUuid; jmethodID init; } gSensorOffsets; struct ListOffsets { jclass clazz; jmethodID add; } gListOffsets; struct StringOffsets { jclass clazz; jmethodID intern; jstring emptyString; } gStringOffsets; /* * nativeClassInit is not inteneded to be thread-safe. It should be called before other native... * functions (except nativeCreate). */ static void nativeClassInit (JNIEnv *_env, jclass _this) { //android.hardware.Sensor SensorOffsets& sensorOffsets = gSensorOffsets; jclass sensorClass = (jclass) MakeGlobalRefOrDie(_env, FindClassOrDie(_env, "android/hardware/Sensor")); sensorOffsets.clazz = sensorClass; sensorOffsets.name = GetFieldIDOrDie(_env, sensorClass, "mName", "Ljava/lang/String;"); sensorOffsets.vendor = GetFieldIDOrDie(_env, sensorClass, "mVendor", "Ljava/lang/String;"); sensorOffsets.version = GetFieldIDOrDie(_env, sensorClass, "mVersion", "I"); sensorOffsets.handle = GetFieldIDOrDie(_env, sensorClass, "mHandle", "I"); sensorOffsets.range = GetFieldIDOrDie(_env, sensorClass, "mMaxRange", "F"); sensorOffsets.resolution = GetFieldIDOrDie(_env, sensorClass, "mResolution","F"); sensorOffsets.power = GetFieldIDOrDie(_env, sensorClass, "mPower", "F"); sensorOffsets.minDelay = GetFieldIDOrDie(_env, sensorClass, "mMinDelay", "I"); sensorOffsets.fifoReservedEventCount = GetFieldIDOrDie(_env,sensorClass, "mFifoReservedEventCount", "I"); sensorOffsets.fifoMaxEventCount = GetFieldIDOrDie(_env,sensorClass, "mFifoMaxEventCount", "I"); sensorOffsets.stringType = GetFieldIDOrDie(_env,sensorClass, "mStringType", "Ljava/lang/String;"); sensorOffsets.requiredPermission = GetFieldIDOrDie(_env,sensorClass, "mRequiredPermission", "Ljava/lang/String;"); sensorOffsets.maxDelay = GetFieldIDOrDie(_env,sensorClass, "mMaxDelay", "I"); sensorOffsets.flags = GetFieldIDOrDie(_env,sensorClass, "mFlags", "I"); sensorOffsets.setType = GetMethodIDOrDie(_env,sensorClass, "setType", "(I)Z"); sensorOffsets.setUuid = GetMethodIDOrDie(_env,sensorClass, "setUuid", "(JJ)V"); sensorOffsets.init = GetMethodIDOrDie(_env,sensorClass, "<init>", "()V"); // java.util.List; ListOffsets& listOffsets = gListOffsets; jclass listClass = (jclass) MakeGlobalRefOrDie(_env, FindClassOrDie(_env, "java/util/List")); listOffsets.clazz = listClass; listOffsets.add = GetMethodIDOrDie(_env,listClass, "add", "(Ljava/lang/Object;)Z"); // initialize java.lang.String and empty string intern StringOffsets& stringOffsets = gStringOffsets; stringOffsets.clazz = MakeGlobalRefOrDie(_env, FindClassOrDie(_env, "java/lang/String")); stringOffsets.intern = GetMethodIDOrDie(_env, stringOffsets.clazz, "intern", "()Ljava/lang/String;"); ScopedLocalRef<jstring> empty(_env, _env->NewStringUTF("")); stringOffsets.emptyString = (jstring) MakeGlobalRefOrDie(_env, _env->CallObjectMethod(empty.get(), stringOffsets.intern)); } static jstring getJavaInternedString(JNIEnv *env, const String8 &string) { if (string == "") { return gStringOffsets.emptyString; } ScopedLocalRef<jstring> javaString(env, env->NewStringUTF(string.string())); jstring internedString = (jstring) env->CallObjectMethod(javaString.get(), gStringOffsets.intern); return internedString; } static jlong nativeCreate (JNIEnv *env, jclass clazz, jstring opPackageName) { ScopedUtfChars opPackageNameUtf(env, opPackageName); return (jlong) &SensorManager::getInstanceForPackage(String16(opPackageNameUtf.c_str())); } static jobject translateNativeSensorToJavaSensor(JNIEnv *env, jobject sensor, const Sensor& nativeSensor) { const SensorOffsets& sensorOffsets(gSensorOffsets); if (sensor == NULL) { // Sensor sensor = new Sensor(); sensor = env->NewObject(sensorOffsets.clazz, sensorOffsets.init, ""); } if (sensor != NULL) { jstring name = getJavaInternedString(env, nativeSensor.getName()); jstring vendor = getJavaInternedString(env, nativeSensor.getVendor()); jstring requiredPermission = getJavaInternedString(env, nativeSensor.getRequiredPermission()); env->SetObjectField(sensor, sensorOffsets.name, name); env->SetObjectField(sensor, sensorOffsets.vendor, vendor); env->SetIntField(sensor, sensorOffsets.version, nativeSensor.getVersion()); env->SetIntField(sensor, sensorOffsets.handle, nativeSensor.getHandle()); env->SetFloatField(sensor, sensorOffsets.range, nativeSensor.getMaxValue()); env->SetFloatField(sensor, sensorOffsets.resolution, nativeSensor.getResolution()); env->SetFloatField(sensor, sensorOffsets.power, nativeSensor.getPowerUsage()); env->SetIntField(sensor, sensorOffsets.minDelay, nativeSensor.getMinDelay()); env->SetIntField(sensor, sensorOffsets.fifoReservedEventCount, nativeSensor.getFifoReservedEventCount()); env->SetIntField(sensor, sensorOffsets.fifoMaxEventCount, nativeSensor.getFifoMaxEventCount()); env->SetObjectField(sensor, sensorOffsets.requiredPermission, requiredPermission); env->SetIntField(sensor, sensorOffsets.maxDelay, nativeSensor.getMaxDelay()); env->SetIntField(sensor, sensorOffsets.flags, nativeSensor.getFlags()); if (env->CallBooleanMethod(sensor, sensorOffsets.setType, nativeSensor.getType()) == JNI_FALSE) { jstring stringType = getJavaInternedString(env, nativeSensor.getStringType()); env->SetObjectField(sensor, sensorOffsets.stringType, stringType); } // TODO(b/29547335): Rename "setUuid" method to "setId". int64_t id = nativeSensor.getId(); env->CallVoidMethod(sensor, sensorOffsets.setUuid, id, 0); } return sensor; } static jboolean nativeGetSensorAtIndex(JNIEnv *env, jclass clazz, jlong sensorManager, jobject sensor, jint index) { SensorManager* mgr = reinterpret_cast<SensorManager*>(sensorManager); Sensor const* const* sensorList; ssize_t count = mgr->getSensorList(&sensorList); if (ssize_t(index) >= count) { return false; } return translateNativeSensorToJavaSensor(env, sensor, *sensorList[index]) != NULL; } static void nativeGetDynamicSensors(JNIEnv *env, jclass clazz, jlong sensorManager, jobject sensorList) { SensorManager* mgr = reinterpret_cast<SensorManager*>(sensorManager); const ListOffsets& listOffsets(gListOffsets); Vector<Sensor> nativeList; mgr->getDynamicSensorList(nativeList); ALOGI("DYNS native SensorManager.getDynamicSensorList return %zu sensors", nativeList.size()); for (size_t i = 0; i < nativeList.size(); ++i) { jobject sensor = translateNativeSensorToJavaSensor(env, NULL, nativeList[i]); // add to list env->CallBooleanMethod(sensorList, listOffsets.add, sensor); } } static jboolean nativeIsDataInjectionEnabled(JNIEnv *_env, jclass _this, jlong sensorManager) { SensorManager* mgr = reinterpret_cast<SensorManager*>(sensorManager); return mgr->isDataInjectionEnabled(); } static jint nativeCreateDirectChannel(JNIEnv *_env, jclass _this, jlong sensorManager, jlong size, jint channelType, jint fd, jobject hardwareBufferObj) { const native_handle_t *nativeHandle = nullptr; NATIVE_HANDLE_DECLARE_STORAGE(ashmemHandle, 1, 0); if (channelType == SENSOR_DIRECT_MEM_TYPE_ASHMEM) { native_handle_t *handle = native_handle_init(ashmemHandle, 1, 0); handle->data[0] = fd; nativeHandle = handle; } else if (channelType == SENSOR_DIRECT_MEM_TYPE_GRALLOC) { AHardwareBuffer *hardwareBuffer = android_hardware_HardwareBuffer_getNativeHardwareBuffer(_env, hardwareBufferObj); if (hardwareBuffer != nullptr) { nativeHandle = AHardwareBuffer_getNativeHandle(hardwareBuffer); } } if (nativeHandle == nullptr) { return BAD_VALUE; } SensorManager* mgr = reinterpret_cast<SensorManager*>(sensorManager); return mgr->createDirectChannel(size, channelType, nativeHandle); } static void nativeDestroyDirectChannel(JNIEnv *_env, jclass _this, jlong sensorManager, jint channelHandle) { SensorManager* mgr = reinterpret_cast<SensorManager*>(sensorManager); mgr->destroyDirectChannel(channelHandle); } static jint nativeConfigDirectChannel(JNIEnv *_env, jclass _this, jlong sensorManager, jint channelHandle, jint sensorHandle, jint rate) { SensorManager* mgr = reinterpret_cast<SensorManager*>(sensorManager); return mgr->configureDirectChannel(channelHandle, sensorHandle, rate); } static jint nativeSetOperationParameter(JNIEnv *_env, jclass _this, jlong sensorManager, jint handle, jint type, jfloatArray floats, jintArray ints) { SensorManager* mgr = reinterpret_cast<SensorManager*>(sensorManager); Vector<float> floatVector; Vector<int32_t> int32Vector; if (floats != nullptr) { floatVector.resize(_env->GetArrayLength(floats)); _env->GetFloatArrayRegion(floats, 0, _env->GetArrayLength(floats), floatVector.editArray()); } if (ints != nullptr) { int32Vector.resize(_env->GetArrayLength(ints)); _env->GetIntArrayRegion(ints, 0, _env->GetArrayLength(ints), int32Vector.editArray()); } return mgr->setOperationParameter(handle, type, floatVector, int32Vector); } //---------------------------------------------------------------------------- class Receiver : public LooperCallback { sp<SensorEventQueue> mSensorQueue; sp<MessageQueue> mMessageQueue; jobject mReceiverWeakGlobal; jfloatArray mFloatScratch; jintArray mIntScratch; public: Receiver(const sp<SensorEventQueue>& sensorQueue, const sp<MessageQueue>& messageQueue, jobject receiverWeak) { JNIEnv* env = AndroidRuntime::getJNIEnv(); mSensorQueue = sensorQueue; mMessageQueue = messageQueue; mReceiverWeakGlobal = env->NewGlobalRef(receiverWeak); mIntScratch = (jintArray) env->NewGlobalRef(env->NewIntArray(16)); mFloatScratch = (jfloatArray) env->NewGlobalRef(env->NewFloatArray(16)); } ~Receiver() { JNIEnv* env = AndroidRuntime::getJNIEnv(); env->DeleteGlobalRef(mReceiverWeakGlobal); env->DeleteGlobalRef(mFloatScratch); env->DeleteGlobalRef(mIntScratch); } sp<SensorEventQueue> getSensorEventQueue() const { return mSensorQueue; } void destroy() { mMessageQueue->getLooper()->removeFd( mSensorQueue->getFd() ); } private: virtual void onFirstRef() { LooperCallback::onFirstRef(); mMessageQueue->getLooper()->addFd(mSensorQueue->getFd(), 0, ALOOPER_EVENT_INPUT, this, mSensorQueue.get()); } virtual int handleEvent(int fd, int events, void* data) { JNIEnv* env = AndroidRuntime::getJNIEnv(); sp<SensorEventQueue> q = reinterpret_cast<SensorEventQueue *>(data); ScopedLocalRef<jobject> receiverObj(env, jniGetReferent(env, mReceiverWeakGlobal)); ssize_t n; ASensorEvent buffer[16]; while ((n = q->read(buffer, 16)) > 0) { for (int i=0 ; i<n ; i++) { if (buffer[i].type == SENSOR_TYPE_STEP_COUNTER) { // step-counter returns a uint64, but the java API only deals with floats float value = float(buffer[i].u64.step_counter); env->SetFloatArrayRegion(mFloatScratch, 0, 1, &value); } else if (buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) { float value[2]; value[0] = buffer[i].dynamic_sensor_meta.connected ? 1.f: 0.f; value[1] = float(buffer[i].dynamic_sensor_meta.handle); env->SetFloatArrayRegion(mFloatScratch, 0, 2, value); } else if (buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) { env->SetIntArrayRegion(mIntScratch, 0, 14, buffer[i].additional_info.data_int32); env->SetFloatArrayRegion(mFloatScratch, 0, 14, buffer[i].additional_info.data_float); } else { env->SetFloatArrayRegion(mFloatScratch, 0, 16, buffer[i].data); } if (buffer[i].type == SENSOR_TYPE_META_DATA) { // This is a flush complete sensor event. Call dispatchFlushCompleteEvent // method. if (receiverObj.get()) { env->CallVoidMethod(receiverObj.get(), gBaseEventQueueClassInfo.dispatchFlushCompleteEvent, buffer[i].meta_data.sensor); } } else if (buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) { // This is a flush complete sensor event. Call dispatchAdditionalInfoEvent // method. if (receiverObj.get()) { int type = buffer[i].additional_info.type; int serial = buffer[i].additional_info.serial; env->CallVoidMethod(receiverObj.get(), gBaseEventQueueClassInfo.dispatchAdditionalInfoEvent, buffer[i].sensor, type, serial, mFloatScratch, mIntScratch, buffer[i].timestamp); } }else { int8_t status; switch (buffer[i].type) { case SENSOR_TYPE_ORIENTATION: case SENSOR_TYPE_MAGNETIC_FIELD: case SENSOR_TYPE_ACCELEROMETER: case SENSOR_TYPE_GYROSCOPE: case SENSOR_TYPE_GRAVITY: case SENSOR_TYPE_LINEAR_ACCELERATION: status = buffer[i].vector.status; break; case SENSOR_TYPE_HEART_RATE: status = buffer[i].heart_rate.status; break; default: status = SENSOR_STATUS_ACCURACY_HIGH; break; } if (receiverObj.get()) { env->CallVoidMethod(receiverObj.get(), gBaseEventQueueClassInfo.dispatchSensorEvent, buffer[i].sensor, mFloatScratch, status, buffer[i].timestamp); } } if (env->ExceptionCheck()) { mSensorQueue->sendAck(buffer, n); ALOGE("Exception dispatching input event."); return 1; } } mSensorQueue->sendAck(buffer, n); } if (n<0 && n != -EAGAIN) { // FIXME: error receiving events, what to do in this case? } return 1; } }; static jlong nativeInitSensorEventQueue(JNIEnv *env, jclass clazz, jlong sensorManager, jobject eventQWeak, jobject msgQ, jstring packageName, jint mode) { SensorManager* mgr = reinterpret_cast<SensorManager*>(sensorManager); ScopedUtfChars packageUtf(env, packageName); String8 clientName(packageUtf.c_str()); sp<SensorEventQueue> queue(mgr->createEventQueue(clientName, mode)); if (queue == NULL) { jniThrowRuntimeException(env, "Cannot construct native SensorEventQueue."); return 0; } sp<MessageQueue> messageQueue = android_os_MessageQueue_getMessageQueue(env, msgQ); if (messageQueue == NULL) { jniThrowRuntimeException(env, "MessageQueue is not initialized."); return 0; } sp<Receiver> receiver = new Receiver(queue, messageQueue, eventQWeak); receiver->incStrong((void*)nativeInitSensorEventQueue); return jlong(receiver.get()); } static jint nativeEnableSensor(JNIEnv *env, jclass clazz, jlong eventQ, jint handle, jint rate_us, jint maxBatchReportLatency) { sp<Receiver> receiver(reinterpret_cast<Receiver *>(eventQ)); return receiver->getSensorEventQueue()->enableSensor(handle, rate_us, maxBatchReportLatency, 0); } static jint nativeDisableSensor(JNIEnv *env, jclass clazz, jlong eventQ, jint handle) { sp<Receiver> receiver(reinterpret_cast<Receiver *>(eventQ)); return receiver->getSensorEventQueue()->disableSensor(handle); } static void nativeDestroySensorEventQueue(JNIEnv *env, jclass clazz, jlong eventQ) { sp<Receiver> receiver(reinterpret_cast<Receiver *>(eventQ)); receiver->destroy(); receiver->decStrong((void*)nativeInitSensorEventQueue); } static jint nativeFlushSensor(JNIEnv *env, jclass clazz, jlong eventQ) { sp<Receiver> receiver(reinterpret_cast<Receiver *>(eventQ)); return receiver->getSensorEventQueue()->flush(); } static jint nativeInjectSensorData(JNIEnv *env, jclass clazz, jlong eventQ, jint handle, jfloatArray values, jint accuracy, jlong timestamp) { sp<Receiver> receiver(reinterpret_cast<Receiver *>(eventQ)); // Create a sensor_event from the above data which can be injected into the HAL. ASensorEvent sensor_event; memset(&sensor_event, 0, sizeof(sensor_event)); sensor_event.sensor = handle; sensor_event.timestamp = timestamp; env->GetFloatArrayRegion(values, 0, env->GetArrayLength(values), sensor_event.data); return receiver->getSensorEventQueue()->injectSensorEvent(sensor_event); } //---------------------------------------------------------------------------- static const JNINativeMethod gSystemSensorManagerMethods[] = { {"nativeClassInit", "()V", (void*)nativeClassInit }, {"nativeCreate", "(Ljava/lang/String;)J", (void*)nativeCreate }, {"nativeGetSensorAtIndex", "(JLandroid/hardware/Sensor;I)Z", (void*)nativeGetSensorAtIndex }, {"nativeGetDynamicSensors", "(JLjava/util/List;)V", (void*)nativeGetDynamicSensors }, {"nativeIsDataInjectionEnabled", "(J)Z", (void*)nativeIsDataInjectionEnabled }, {"nativeCreateDirectChannel", "(JJIILandroid/hardware/HardwareBuffer;)I", (void*)nativeCreateDirectChannel }, {"nativeDestroyDirectChannel", "(JI)V", (void*)nativeDestroyDirectChannel }, {"nativeConfigDirectChannel", "(JIII)I", (void*)nativeConfigDirectChannel }, {"nativeSetOperationParameter", "(JII[F[I)I", (void*)nativeSetOperationParameter }, }; static const JNINativeMethod gBaseEventQueueMethods[] = { {"nativeInitBaseEventQueue", "(JLjava/lang/ref/WeakReference;Landroid/os/MessageQueue;Ljava/lang/String;ILjava/lang/String;)J", (void*)nativeInitSensorEventQueue }, {"nativeEnableSensor", "(JIII)I", (void*)nativeEnableSensor }, {"nativeDisableSensor", "(JI)I", (void*)nativeDisableSensor }, {"nativeDestroySensorEventQueue", "(J)V", (void*)nativeDestroySensorEventQueue }, {"nativeFlushSensor", "(J)I", (void*)nativeFlushSensor }, {"nativeInjectSensorData", "(JI[FIJ)I", (void*)nativeInjectSensorData }, }; } //unnamed namespace int register_android_hardware_SensorManager(JNIEnv *env) { RegisterMethodsOrDie(env, "android/hardware/SystemSensorManager", gSystemSensorManagerMethods, NELEM(gSystemSensorManagerMethods)); RegisterMethodsOrDie(env, "android/hardware/SystemSensorManager$BaseEventQueue", gBaseEventQueueMethods, NELEM(gBaseEventQueueMethods)); gBaseEventQueueClassInfo.clazz = FindClassOrDie(env, "android/hardware/SystemSensorManager$BaseEventQueue"); gBaseEventQueueClassInfo.dispatchSensorEvent = GetMethodIDOrDie(env, gBaseEventQueueClassInfo.clazz, "dispatchSensorEvent", "(I[FIJ)V"); gBaseEventQueueClassInfo.dispatchFlushCompleteEvent = GetMethodIDOrDie(env, gBaseEventQueueClassInfo.clazz, "dispatchFlushCompleteEvent", "(I)V"); gBaseEventQueueClassInfo.dispatchAdditionalInfoEvent = GetMethodIDOrDie(env, gBaseEventQueueClassInfo.clazz, "dispatchAdditionalInfoEvent", "(III[F[I)V"); return 0; }
40.565905
111
0.645611
[ "object", "vector" ]
5b3ba3ff08b1312603c4175c0e1cab07585a935e
7,890
cpp
C++
libredex/SourceBlockConsistencyCheck.cpp
kami-lang/madex-redex
90ae1bc46c6e20a0aed2c128183b9f289cecee34
[ "MIT" ]
null
null
null
libredex/SourceBlockConsistencyCheck.cpp
kami-lang/madex-redex
90ae1bc46c6e20a0aed2c128183b9f289cecee34
[ "MIT" ]
null
null
null
libredex/SourceBlockConsistencyCheck.cpp
kami-lang/madex-redex
90ae1bc46c6e20a0aed2c128183b9f289cecee34
[ "MIT" ]
null
null
null
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "SourceBlockConsistencyCheck.h" #include "ControlFlow.h" #include "Debug.h" #include "DexClass.h" #include "IRCode.h" #include "InteractiveDebugging.h" #include "ScopedCFG.h" #include "Show.h" #include "SourceBlocks.h" #include "Trace.h" #include "Walkers.h" #include <algorithm> #include <iterator> #include <map> #include <set> #include <tuple> #include <unordered_map> #include <utility> #include <vector> namespace source_blocks { bool operator<(const SourceBlockInfo& l, const SourceBlockInfo& r) { if (l.original_dex_method != r.original_dex_method) { return compare_dexstrings(l.original_dex_method, r.original_dex_method); } return l.id < r.id; } bool operator==(const SourceBlockInfo& l, const SourceBlockInfo& r) { return std::tie(l.original_dex_method, l.id) == std::tie(r.original_dex_method, r.id); } SourceBlockDomInfo::SourceBlockDomInfo(const cfg::ControlFlowGraph& cfg, uint32_t num_src_blks) : m_dom_tree(cfg, num_src_blks) {} std::vector<SourceBlockInfo> SourceBlockDomInfo::get_removeable_src_blks() { return std::vector<SourceBlockInfo>{m_dom_tree.leaves().begin(), m_dom_tree.leaves().end()}; } void SourceBlockDomInfo::remove_src_blk(const SourceBlockInfo& sb_info) { m_dom_tree.remove_src_blk(sb_info); } void SourceBlockConsistencyCheck::initialize(const Scope& scope) { always_assert(!this->is_initialized()); this->m_is_initialized = true; // Preallocate slots in the map, so we can get // at them when multithreaded without needing synchronization walk::methods(scope, [this](DexMethod* dex_method) { this->m_context_map.insert({dex_method, SBConsistencyContext{}}); }); walk::parallel::methods(scope, [this](DexMethod* dex_method) { auto it = this->m_context_map.find(dex_method); if (it == this->m_context_map.end()) { return; } IRCode* code = dex_method->get_code(); if (code == nullptr) { return; } cfg::ScopedCFG scfg(code); cfg::ControlFlowGraph& cfg = code->cfg(); cfg.calculate_exit_block(); this->rebuild_sbdi(dex_method, cfg); }); } void SourceBlockConsistencyCheck::rebuild_sbdi(DexMethod* dex_method, const ControlFlowGraph& cfg) { auto it = this->m_context_map.find(dex_method); if (it == this->m_context_map.end()) { return; } auto& sbcc = it->second; sbcc.m_source_blocks.clear(); for (auto* b : cfg.blocks()) { source_blocks::foreach_source_block(b, [&sbcc](auto& sb) { sbcc.m_source_blocks.insert(SourceBlockInfo{sb->src, sb->id}); }); } sbcc.m_sbdi = SourceBlockDomInfo{ cfg, static_cast<uint32_t>(sbcc.m_source_blocks.size())}; } template <class T> struct merge_vecs { void operator()(const T& addend, T* accumulator) const { accumulator->insert(accumulator->end(), addend.begin(), addend.end()); } }; size_t SourceBlockConsistencyCheck::run(const Scope& scope) { struct Failure { DexMethod* dex_method = nullptr; std::vector<SourceBlockInfo> src_blks; }; auto res = walk::parallel::methods<std::vector<Failure>, merge_vecs<std::vector<Failure>>>( scope, [this](DexMethod* dex_method) -> std::vector<Failure> { auto it = this->m_context_map.find(dex_method); if (it == this->m_context_map.end()) { return {}; } auto& sbcc = it->second; auto& [source_blocks, known_missing_source_blocks, sbdi] = sbcc; IRCode* code = dex_method->get_code(); if (code == nullptr) { return {}; } cfg::ScopedCFG scfg(code); const cfg::ControlFlowGraph& cfg = code->cfg(); std::set<SourceBlockInfo> source_blocks_in_ir; for (cfg::Block* block : cfg.blocks()) { source_blocks::foreach_source_block( block, [&source_blocks_in_ir](auto& sb) { source_blocks_in_ir.insert({sb->src, sb->id}); }); } std::vector<SourceBlockInfo> missing; std::set_difference(source_blocks.begin(), source_blocks.end(), source_blocks_in_ir.begin(), source_blocks_in_ir.end(), std::back_inserter(missing)); missing.erase(std::remove_if( missing.begin(), missing.end(), [&sbcc](const auto& s) { return sbcc.m_known_missing_source_blocks.find(s) != sbcc.m_known_missing_source_blocks.end(); }), missing.end()); if (missing.empty()) { return {}; } known_missing_source_blocks.insert(missing.begin(), missing.end()); std::sort(missing.begin(), missing.end()); for (bool changed = true; changed;) { changed = false; auto removeable_blks = sbdi.get_removeable_src_blks(); std::sort(removeable_blks.begin(), removeable_blks.end()); std::vector<SourceBlockInfo> blks_to_remove; std::set_intersection(removeable_blks.begin(), removeable_blks.end(), missing.begin(), missing.end(), std::back_inserter(blks_to_remove)); if (!blks_to_remove.empty()) { changed = true; missing.erase(std::remove_if(missing.begin(), missing.end(), [&blks_to_remove](auto& m) { auto it_blks_to_remove = std::lower_bound( blks_to_remove.begin(), blks_to_remove.end(), m); return it_blks_to_remove != blks_to_remove.end() && *it_blks_to_remove == m; }), missing.end()); for (const auto& sb_info : blks_to_remove) { sbdi.remove_src_blk(sb_info); } } } if (missing.empty()) { return {}; } return std::vector<Failure>{{dex_method, std::move(missing)}}; }); if (!res.empty()) { int num_missing_blks = std::accumulate( res.begin(), res.end(), 0, [](const auto& l, const auto& r) { return l + r.src_blks.size(); }); TRACE(SBCC, 2, "Pass introduced %d missing source blocks across %zu methods.", num_missing_blks, res.size()); for (const auto& [dex_method, src_blks] : res) { always_assert(!src_blks.empty()); std::map<const DexString*, std::vector<uint32_t>, dexstrings_comparator> methodRefToSrcBlockIds; for (const auto& [src, id] : src_blks) { methodRefToSrcBlockIds[src].push_back(id); } TRACE(SBCC, 2, " Missing source blocks in method, %s", show_deobfuscated(dex_method).c_str()); for (const auto& [src, ids] : methodRefToSrcBlockIds) { std::string idListStr = std::accumulate( ids.begin() + 1, ids.end(), std::to_string(ids.front()), [](const auto& l, const auto& r) { return l + ", " + std::to_string(r); }); TRACE(SBCC, 2, " %s:\n %s", src->c_str(), idListStr.c_str()); } } return num_missing_blks; } return 0; } } // namespace source_blocks
31.814516
80
0.570342
[ "vector" ]
5b3bd00d78abc80c5d65780fa9b65b975540b6b2
3,843
cpp
C++
src/workspace/track.cpp
jbruggem/jingles-impro
a20ebcd6272e39413eea33711d0e3d4785472f18
[ "Apache-2.0" ]
1
2015-11-04T14:38:13.000Z
2015-11-04T14:38:13.000Z
src/workspace/track.cpp
jbruggem/jingles-impro
a20ebcd6272e39413eea33711d0e3d4785472f18
[ "Apache-2.0" ]
null
null
null
src/workspace/track.cpp
jbruggem/jingles-impro
a20ebcd6272e39413eea33711d0e3d4785472f18
[ "Apache-2.0" ]
null
null
null
#include "track.h" //xxx do we want the copy constructor to use a new fileRef or just copy the other object's pointer? Track::Track(const Track& track): QObject(track.parent()), fileInfo(track.fileInfo), loopEnabled(track.loopEnabled), startTime(track.startTime), endTime(track.endTime), fadeInDuration(track.fadeInDuration), fadeOutDuration(track.fadeOutDuration) //, //fileRef(track.fileRef) { QLOG_TRACE() << "Building Track from other track"; } Track::Track(const QString &url, bool loop, long startTime, long endTime, int fadeInDuration, int fadeOutDuration,bool showFilename,QObject *parent) : QObject(parent), //path(url), loopEnabled(loop), startTime(startTime), endTime(endTime), fadeInDuration(fadeInDuration), fadeOutDuration(fadeOutDuration), showFilename(showFilename) { QLOG_TRACE() << "Building Track with full params"; this->extractFilename(url); // conversion of QString to const char * according to // http://qt-project.org/faq/answer/how_can_i_convert_a_qstring_to_char_and_vice_versa //QByteArray temp = url.toLocal8Bit(); //fileRef = new TagLib::FileRef(temp.data()); } Track::Track(const QString &url,QObject *parent) : QObject(parent), //path(url), loopEnabled(false), startTime(0), endTime(0), fadeInDuration(0), fadeOutDuration(0), showFilename(false) { QLOG_TRACE() << "Building Track from URL"; this->extractFilename(url); // conversion of QString to const char * according to // http://qt-project.org/faq/answer/how_can_i_convert_a_qstring_to_char_and_vice_versa //QByteArray temp = url.toLocal8Bit(); //fileRef = new TagLib::FileRef(temp.data()); } void Track::extractFilename(const QString &url){ fileInfo = QFileInfo(url); } QString Track::getDisplayName() const{ if(this->getTitle()->length() > 0 && !this->shouldShowFilename()){ return title; }else{ return getFilename(); } } QString Track::getPath() const{ return fileInfo.absoluteFilePath(); } QString Track::getFilename() const{ return fileInfo.baseName(); } int Track::compare(const Track &a, const Track &b) { int returnValue = QString::localeAwareCompare(a.fileInfo.canonicalFilePath(), b.fileInfo.canonicalFilePath()); // if the strings are different, we stop the comparison if (returnValue) {return returnValue;} returnValue = a.startTime - b.startTime; // if the times are different, we stop the comparison if (returnValue) {return returnValue;} returnValue = a.endTime - b.endTime; if (returnValue) {return returnValue;} returnValue = a.fadeInDuration - b.fadeInDuration; if (returnValue) {return returnValue;} returnValue = a.fadeOutDuration - b.fadeOutDuration; if (returnValue) {return returnValue;} returnValue = a.loopEnabled - b.loopEnabled; if (returnValue) {return returnValue;} // additional checks can be added here return 0; } bool Track::operator<(const Track &other) const { return compare(*this, other) < 0; } void Track::setArtist(const QString * artist) { //QLOG_TRACE() << this << "Track's artist updated."; this->artist = *artist; emit tagUpdated(); emit tagArtistUpdate(); } void Track::setTitle(const QString * title) { //QLOG_TRACE() << this << "Track's title updated."; this->title = *title; emit tagUpdated(); emit tagTitleUpdate(); } void Track::print() const { QLOG_INFO() << "Track::print()"; QLOG_INFO() << "path: " << this->getPath(); QLOG_INFO() << "startTime: " << startTime; QLOG_INFO() << "endTime: " << endTime; QLOG_INFO() << "fadeInDuration: " << fadeInDuration; QLOG_INFO() << "fadeOutDuration:" << fadeOutDuration; QLOG_INFO() << "loopEnabled: " << loopEnabled; //QLOG_INFO() << "isValid?: " << isValid(); }
30.744
150
0.68306
[ "object" ]
5b3c7bc77a67f6f04af3d16ef69c5dfdebd73069
73,279
cxx
C++
opal-3.16.2/src/opal/manager.cxx
wwl33695/myopal
d302113c8ad8156b3392ce514cde491cf42d51af
[ "MIT" ]
null
null
null
opal-3.16.2/src/opal/manager.cxx
wwl33695/myopal
d302113c8ad8156b3392ce514cde491cf42d51af
[ "MIT" ]
null
null
null
opal-3.16.2/src/opal/manager.cxx
wwl33695/myopal
d302113c8ad8156b3392ce514cde491cf42d51af
[ "MIT" ]
null
null
null
/* * manager.cxx * * Media channels abstraction * * Open Phone Abstraction Library (OPAL) * Formally known as the Open H323 project. * * Copyright (c) 2001 Equivalence Pty. Ltd. * * The contents of this file are subject to the Mozilla Public License * Version 1.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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See * the License for the specific language governing rights and limitations * under the License. * * The Original Code is Open Phone Abstraction Library. * * The Initial Developer of the Original Code is Equivalence Pty. Ltd. * * Contributor(s): ______________________________________. * * $Revision: 34680 $ * $Author: rjongbloed $ * $Date: 2016-03-14 09:47:03 +0000 (Mon, 14 Mar 2016) $ */ #include <ptlib.h> #ifdef __GNUC__ #pragma implementation "manager.h" #endif #include <opal_config.h> #include <opal/manager.h> #include <opal/endpoint.h> #include <opal/call.h> #include <opal/patch.h> #include <opal/mediastrm.h> #include <codec/g711codec.h> #include <codec/vidcodec.h> #include <codec/rfc4175.h> #include <codec/rfc2435.h> #include <codec/opalpluginmgr.h> #include <im/im_ep.h> #include <ep/opalmixer.h> #if OPAL_HAS_H281 #include <h224/h281.h> #endif #include <ptclib/random.h> #include <ptclib/url.h> #include <ptclib/mime.h> #include <ptclib/pssl.h> #include "../../version.h" #include "../../revision.h" static const char * const DefaultMediaFormatOrder[] = { OPAL_G7222, OPAL_G7221_32K, OPAL_G7221_24K, OPAL_G722, OPAL_GSMAMR, OPAL_G7231_6k3, OPAL_G729B, OPAL_G729AB, OPAL_G729, OPAL_G729A, OPAL_iLBC, OPAL_GSM0610, OPAL_G728, OPAL_G726_40K, OPAL_G726_32K, OPAL_G726_24K, OPAL_G726_16K, OPAL_G711_ULAW_64K, OPAL_G711_ALAW_64K, #if OPAL_VIDEO OPAL_H264_High, // High profile OPAL_H264_MODE1, // Packetisation mode 1 OPAL_H264_MODE0, // Packetisation mode 0 OPAL_VP8, OPAL_MPEG4, OPAL_H263plus OPAL_H263, OPAL_H261, #endif #if OPAL_HAS_SIPIM OPAL_SIPIM, #endif #if OPAL_HAS_RFC4103 OPAL_T140, #endif #if OPAL_HAS_MSRP OPAL_MSRP #endif }; static const char * const DefaultMediaFormatMask[] = { OPAL_iLBC"-13k3", OPAL_iLBC"-15k2", #if OPAL_RFC4175 OPAL_RFC4175_YCbCr420, OPAL_RFC4175_RGB, #endif #if OPAL_HAS_MSRP OPAL_MSRP, #endif OPAL_H264_High // Do not include by default, interop issues. }; // G.711 is *always* available // Yes, it would make more sense for this to be in g711codec.cxx, but on // Linux it would not get loaded due to static initialisation optimisation OPAL_REGISTER_G711(); // Same deal for RC4175 video #if OPAL_RFC4175 OPAL_REGISTER_RFC4175(); #endif // Same deal for RC2435 video #if OPAL_RFC2435 OPAL_REGISTER_RFC2435_JPEG(); #endif #define new PNEW #define PTraceModule() "OpalMan" ///////////////////////////////////////////////////////////////////////////// ostream & operator<<(ostream & strm, OpalConferenceState::ChangeType type) { static const char * const Names[] = { "Created", "Destroyed", "UserAdded", "UserRemoved" }; if (type >= 0 && type < PARRAYSIZE(Names)) strm << Names[type]; else strm << '<' << (unsigned)type << '>'; return strm; } ///////////////////////////////////////////////////////////////////////////// PString OpalGetVersion() { #define AlphaCode "alpha" #define BetaCode "beta" #define ReleaseCode "." return psprintf("%u.%u%s%u (svn:%u)", MAJOR_VERSION, MINOR_VERSION, BUILD_TYPE, BUILD_NUMBER, SVN_REVISION); } unsigned OpalGetMajorVersion() { return MAJOR_VERSION; } unsigned OpalGetMinorVersion() { return MINOR_VERSION; } unsigned OpalGetBuildNumber() { return BUILD_NUMBER; } OpalProductInfo::OpalProductInfo() : t35CountryCode(0) , t35Extension(0) , manufacturerCode(0) { } OpalProductInfo::OpalProductInfo(const char * vend, const char * nam, const char * ver, BYTE country, WORD manufacturer, const char * o) : vendor(vend) , name(nam) , version(ver) , t35CountryCode(country) , t35Extension(0) , manufacturerCode(manufacturer) , oid(o) { // Sanitise the product name to be compatible with SIP User-Agent rules name.Replace(' ', '-', true); PINDEX pos; while ((pos = name.FindSpan("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-.!%*_+`'~")) != P_MAX_INDEX) name.Delete(pos, 1); } const OpalProductInfo & OpalProductInfo::Default() { static OpalProductInfo instance(PProcess::Current().GetManufacturer(), PProcess::Current().GetName(), PProcess::Current().GetVersion(), 9, // Country code for Australia 61, // Allocated by Australian Communications Authority, Oct 2000 NULL); return instance; } PCaselessString OpalProductInfo::AsString() const { PStringStream str; str << *this; return str; } void OpalProductInfo::operator=(const OpalProductInfo & other) { name = other.name; version = other.version; comments = other.comments; t35CountryCode = other.t35CountryCode; t35Extension = other.t35Extension; manufacturerCode = other.manufacturerCode; // Look for special case of vendor being numeric "<manufacturer>,<country>[,<ext>]" if (other.vendor.FindSpan("0123456789,") == P_MAX_INDEX) { PStringArray fields = other.vendor.Tokenise(','); switch (fields.GetSize()) { default : break; case 3: t35Extension = (BYTE)fields[2].AsUnsigned(); case 2 : manufacturerCode = (WORD)fields[1].AsUnsigned(); t35CountryCode = (BYTE)fields[0].AsUnsigned(); vendor.MakeEmpty(); return; } } vendor = other.vendor; } bool OpalProductInfo::operator==(const OpalProductInfo & other) const { if (name != other.name) return false; if (!other.version.IsEmpty() && version != other.version) return false; if (vendor != other.vendor) return false; if (!vendor.IsEmpty()) return true; return t35CountryCode == other.t35CountryCode || t35CountryCode != other.t35CountryCode || manufacturerCode == other.manufacturerCode; } ostream & operator<<(ostream & strm, const OpalProductInfo & info) { if (info.name.IsEmpty() && info.version.IsEmpty() && info.vendor.IsEmpty() && info.t35CountryCode == 0 && info.manufacturerCode == 0) return strm; strm << info.name << '\t' << info.version << '\t'; if (info.t35CountryCode != 0 && info.manufacturerCode != 0) { strm << (unsigned)info.t35CountryCode; if (info.t35Extension != 0) strm << '.' << (unsigned)info.t35Extension; strm << '/' << info.manufacturerCode; } strm << '\t' << info.vendor; return strm; } ///////////////////////////////////////////////////////////////////////////// OpalManager::OpalManager() : productInfo(OpalProductInfo::Default()) , defaultUserName(PProcess::Current().GetUserName()) , defaultDisplayName(defaultUserName) , rtpPayloadSizeMax(1400) // RFC879 recommends 576 bytes, but that is ancient history, 99.999% of the time 1400+ bytes is used. , rtpPacketSizeMax(10*1024) , mediaFormatOrder(PARRAYSIZE(DefaultMediaFormatOrder), DefaultMediaFormatOrder) , mediaFormatMask(PARRAYSIZE(DefaultMediaFormatMask), DefaultMediaFormatMask) , disableDetectInBandDTMF(false) , m_noMediaTimeout(0, 0, 5) // Minutes , m_txMediaTimeout(0, 10) // Seconds , m_signalingTimeout(0, 10) // Seconds , m_transportIdleTime(0, 0, 1) // Minute , m_natKeepAliveTime(0, 30) // Seconds #if OPAL_ICE , m_iceTimeout(0, 5) // Seconds #endif , m_staleReceiverTimeout(0,0,1) // Minutes #if OPAL_SRTP , m_dtlsTimeout(0, 3) // Seconds #endif , m_rtpIpPorts(5000, 5999) #if OPAL_PTLIB_SSL , m_caFiles(PProcess::Current().GetHomeDirectory() + "certificates") , m_certificateFile(PProcess::Current().GetHomeDirectory() + "opal_certificate.pem") , m_privateKeyFile(PProcess::Current().GetHomeDirectory() + "opal_private_key.pem") , m_autoCreateCertificate(true) #endif #if OPAL_PTLIB_NAT , m_natMethods(new PNatMethods(true)) , m_onInterfaceChange(PCREATE_InterfaceNotifier(OnInterfaceChange)) #endif , lastCallTokenID(0) , P_DISABLE_MSVC_WARNINGS(4355, activeCalls(*this)) , m_clearingAllCallsCount(0) , m_garbageCollector(NULL) , m_garbageCollectSkip(false) , m_decoupledEventPool(5, 0, "Event Pool") #if OPAL_SCRIPT , m_script(NULL) #endif { m_mediaQoS[OpalMediaType::Audio()].m_type = PIPSocket::VoiceQoS; #if OPAL_VIDEO m_mediaQoS[OpalMediaType::Video()].m_type = PIPSocket::VideoQoS; for (OpalVideoFormat::ContentRole role = OpalVideoFormat::BeginContentRole; role < OpalVideoFormat::EndContentRole; ++role) m_videoInputDevice[role].deviceName = m_videoPreviewDevice[role].deviceName = m_videoOutputDevice[role].deviceName = P_NULL_VIDEO_DEVICE; PStringArray devices = PVideoInputDevice::GetDriversDeviceNames("*"); // Get all devices on all drivers PINDEX i; for (i = 0; i < devices.GetSize(); ++i) { PCaselessString dev = devices[i]; if (dev[0] != '*' && dev.NumCompare(P_FAKE_VIDEO_PREFIX) != EqualTo) { PTRACE(3, "Default video grabber set to \"" << dev << '"'); m_videoInputDevice[OpalVideoFormat::eNoRole].deviceName = m_videoInputDevice[OpalVideoFormat::eMainRole].deviceName = dev; SetAutoStartTransmitVideo(true); #if PTRACING static unsigned const Level = 3; if (PTrace::CanTrace(Level)) { ostream & trace = PTRACE_BEGIN(Level); trace << "Default video input device set to \"" << dev << '"'; PVideoInputDevice::Capabilities caps; if (PVideoInputDevice::GetDeviceCapabilities(dev, &caps)) trace << '\n' << caps; else trace << " - no capabilities."; trace << PTrace::End; } #endif break; } } devices = PVideoOutputDevice::GetDriversDeviceNames("*"); // Get all devices on all drivers for (i = 0; i < devices.GetSize(); ++i) { PCaselessString dev = devices[i]; if (dev[0] != '*' && dev != P_NULL_VIDEO_DEVICE) { PTRACE(3, "Default video display set to \"" << dev << '"'); for (OpalVideoFormat::ContentRole role = OpalVideoFormat::BeginContentRole; role < OpalVideoFormat::EndContentRole; ++role) m_videoOutputDevice[role].deviceName = dev; m_videoPreviewDevice[OpalVideoFormat::eNoRole] = m_videoOutputDevice[OpalVideoFormat::eNoRole]; SetAutoStartReceiveVideo(true); PTRACE(3, "Default video output/preview device set to \"" << devices[i] << '"'); break; } } #endif #if OPAL_PTLIB_NAT PInterfaceMonitor::GetInstance().AddNotifier(m_onInterfaceChange); #endif PTRACE(4, "Created manager, OPAL version " << OpalGetVersion()); } OpalManager::~OpalManager() { ShutDownEndpoints(); #if OPAL_SCRIPT delete m_script; #endif // Shut down the cleaner thread if (m_garbageCollector != NULL) { m_garbageCollectExit.Signal(); m_garbageCollector->WaitForTermination(); delete m_garbageCollector; } // Clean up any calls that the cleaner thread missed on the way out GarbageCollection(); #if OPAL_PTLIB_NAT PInterfaceMonitor::GetInstance().RemoveNotifier(m_onInterfaceChange); delete m_natMethods; #endif PTRACE(4, "Deleted manager."); } PList<OpalEndPoint> OpalManager::GetEndPoints() const { PList<OpalEndPoint> list; list.AllowDeleteObjects(false); PReadWaitAndSignal mutex(endpointsMutex); for (PList<OpalEndPoint>::const_iterator it = endpointList.begin(); it != endpointList.end(); ++it) list.Append((OpalEndPoint *)&*it); return list; } PStringList OpalManager::GetPrefixNames(const OpalEndPoint * endpoint) const { PStringList list; PReadWaitAndSignal mutex(endpointsMutex); for (std::map<PString, OpalEndPoint *>::const_iterator it = endpointMap.begin(); it != endpointMap.end(); ++it) { if (endpoint == NULL || it->second == endpoint) list += it->first; } return list; } void OpalManager::ShutDownEndpoints() { PTRACE(3, "Shutting down manager."); // Clear any pending calls, set flag so no calls can be received before endpoints removed InternalClearAllCalls(OpalConnection::EndedByLocalUser, true, m_clearingAllCallsCount++ == 0); #if OPAL_HAS_PRESENCE // Remove (and unsubscribe) all the presentities PTRACE(4, "Shutting down all presentities"); for (PSafePtr<OpalPresentity> presentity(m_presentities, PSafeReference); presentity != NULL; ++presentity) presentity->Close(); m_presentities.RemoveAll(); #endif // OPAL_HAS_PRESENCE PTRACE(4, "Shutting down endpoints."); // Deregister the endpoints endpointsMutex.StartRead(); for (PList<OpalEndPoint>::iterator ep = endpointList.begin(); ep != endpointList.end(); ++ep) ep->ShutDown(); endpointsMutex.EndRead(); endpointsMutex.StartWrite(); endpointMap.clear(); endpointList.RemoveAll(); endpointsMutex.EndWrite(); --m_clearingAllCallsCount; // Allow for endpoints to be added again. #if OPAL_SCRIPT if (m_script != NULL) m_script->Call("OnShutdown"); #endif } void OpalManager::AttachEndPoint(OpalEndPoint * endpoint, const PString & prefix) { if (PAssertNULL(endpoint) == NULL) return; PString thePrefix = prefix.IsEmpty() ? endpoint->GetPrefixName() : prefix; PWriteWaitAndSignal mutex(endpointsMutex); std::map<PString, OpalEndPoint *>::iterator it = endpointMap.find(thePrefix); if (it != endpointMap.end()) { PTRACE_IF(1, it->second != endpoint, "An endpoint is already attached to prefix " << thePrefix); return; } if (endpointList.GetObjectsIndex(endpoint) == P_MAX_INDEX) endpointList.Append(endpoint); endpointMap[thePrefix] = endpoint; /* Avoid strange race condition caused when garbage collection occurs on the endpoint instance which has not completed construction. This is an ulgly hack and relies on the ctors taking less than one second. */ m_garbageCollectSkip = true; // Have something which requires garbage collections, so start it up if (m_garbageCollector == NULL) m_garbageCollector = PThread::Create(PCREATE_NOTIFIER(GarbageMain), "Opal Garbage"); PTRACE(3, "Attached endpoint with prefix " << thePrefix); } void OpalManager::DetachEndPoint(OpalEndPoint * endpoint) { if (PAssertNULL(endpoint) == NULL) return; endpoint->ShutDown(); endpointsMutex.StartWrite(); if (endpointList.Remove(endpoint)) { // Was in list, remove from map too std::map<PString, OpalEndPoint *>::iterator it = endpointMap.begin(); while (it != endpointMap.end()) { if (it->second != endpoint) ++it; else { endpointMap.erase(it); it = endpointMap.begin(); } } } endpointsMutex.EndWrite(); } void OpalManager::DetachEndPoint(const PString & prefix) { PReadWaitAndSignal mutex(endpointsMutex); std::map<PString, OpalEndPoint *>::iterator it = endpointMap.find(prefix); if (it == endpointMap.end()) return; OpalEndPoint * endpoint = it->second; endpointsMutex.StartWrite(); endpointMap.erase(it); endpointsMutex.EndWrite(); // See if other references for (it = endpointMap.begin(); it != endpointMap.end(); ++it) { if (it->second == endpoint) return; // Still a reference to it } // Last copy, delete it now DetachEndPoint(endpoint); } OpalEndPoint * OpalManager::FindEndPoint(const PString & prefix) const { PReadWaitAndSignal mutex(endpointsMutex); std::map<PString, OpalEndPoint *>::const_iterator it = endpointMap.find(prefix); return it != endpointMap.end() ? it->second : NULL; } PBoolean OpalManager::SetUpCall(const PString & partyA, const PString & partyB, PString & token, void * userData, unsigned int options, OpalConnection::StringOptions * stringOptions) { token.MakeEmpty(); PSafePtr<OpalCall> call = SetUpCall(partyA, partyB, userData, options, stringOptions); if (call == NULL) return false; token = call->GetToken(); return true; } #if OPAL_HAS_MIXER bool OpalManager::SetUpConference(OpalCall & call, const char * mixerURI, const char * localURI) { PString confURI(mixerURI); if (confURI.IsEmpty()) confURI = OPAL_MIXER_PREFIX":local-conference"; PString mixerPrefix, mixerNode; if (!confURI.Split(':', mixerPrefix, mixerNode)) { mixerPrefix = OPAL_MIXER_PREFIX; mixerNode = confURI; confURI.Splice(OPAL_MIXER_PREFIX":", 0); } OpalMixerEndPoint * mixerEP = FindEndPointAs<OpalMixerEndPoint>(mixerPrefix); if (mixerEP == NULL) { PTRACE(2, "No mixer endpoint using prefix \"" << mixerPrefix << '"'); return false; } PSafePtr<OpalLocalConnection> connection = call.GetConnectionAs<OpalLocalConnection>(); if (connection == NULL) { PTRACE(2, "Cannot conference gateway call " << call); return false; } PSafePtr<OpalMixerNode> node = mixerEP->FindNode(mixerNode); if (node == NULL) { node = mixerEP->AddNode(new OpalMixerNodeInfo(mixerNode)); PTRACE(3, "Created mixer node \"" << mixerNode << '"'); } if (!call.Transfer(confURI, connection)) { PTRACE(2, "Could not add call " << call << " to conference \"" << confURI << '"'); return false; } call.Retrieve(); // Make sure is not still on hold PTRACE(3, &call, "Added call " << call << " to conference \"" << confURI << '"'); PString uri = localURI != NULL ? localURI : "pc:*"; if (uri.IsEmpty() || node->GetConnectionCount() > 1) return true; #if OPAL_VIDEO /* If after adding the above to conference, it's the only one there, and we have a local URI specified (typically pc:*) then we add that too. */ if (connection->GetMediaStream(OpalMediaType::Video(), true) == NULL) uri += ";" OPAL_URL_PARAM_PREFIX OPAL_OPT_AUTO_START "=video:no"; #endif PSafePtr<OpalCall> localCall = SetUpCall(uri + ";" OPAL_URL_PARAM_PREFIX OPAL_OPT_CONF_OWNER "=yes", confURI); if (localCall != NULL) { PTRACE(3, localCall, "Added local call \"" << uri << "\" to conference \"" << confURI << '"'); return true; } PTRACE(2, "Could not start local call into conference"); return false; } #endif // OPAL_HAS_MIXER static void SynchCallSetUp(PSafePtr<OpalConnection> connection) { if (connection->SetUpConnection()) return; PTRACE(2, "Could not set up connection on " << *connection); if (connection->GetCallEndReason() == OpalConnection::NumCallEndReasons) connection->Release(OpalConnection::EndedByTemporaryFailure); } static void AsynchCallSetUp(PSafePtr<OpalConnection> connection) { PTRACE_CONTEXT_ID_PUSH_THREAD(connection); if (connection.SetSafetyMode(PSafeReadWrite)) SynchCallSetUp(connection); } PSafePtr<OpalCall> OpalManager::SetUpCall(const PString & partyA, const PString & partyB, void * userData, unsigned int options, OpalConnection::StringOptions * stringOptions) { PTRACE(3, "Set up call from " << partyA << " to " << partyB); OpalCall * call = InternalCreateCall(userData); if (call == NULL) return NULL; PTRACE_CONTEXT_ID_PUSH_THREAD(call); call->SetPartyB(partyB.Trim()); // If we are the A-party then need to initiate a call now in this thread and // go through the routing engine via OnIncomingConnection. If we were the // B-Party then SetUpConnection() gets called in the context of the A-party // thread. PSafePtr<OpalConnection> connection = MakeConnection(*call, partyA.Trim(), userData, options, stringOptions); if (connection != NULL) { if ((options & OpalConnection::SynchronousSetUp) != 0) SynchCallSetUp(connection); else { PTRACE(4, "SetUpCall started, call=" << *call); new PThread1Arg< PSafePtr<OpalConnection> >(connection, AsynchCallSetUp, true, "SetUpCall"); } return call; } PTRACE(2, "Could not create connection for \"" << partyA << '"'); OpalConnection::CallEndReason endReason = call->GetCallEndReason(); if (endReason == OpalConnection::NumCallEndReasons) endReason = OpalConnection::EndedByTemporaryFailure; call->Clear(endReason); return NULL; } bool OpalManager::OnLocalIncomingCall(OpalLocalConnection &) { return true; } bool OpalManager::OnLocalOutgoingCall(const OpalLocalConnection &) { return true; } #if OPAL_SCRIPT void OpalManager::OnEstablishedCall(OpalCall & call) { if (m_script != NULL) m_script->Call("OnEstablished", "s", (const char *)call.GetToken()); } #else void OpalManager::OnEstablishedCall(OpalCall & /*call*/) { } #endif PBoolean OpalManager::IsCallEstablished(const PString & token) { PSafePtr<OpalCall> call = activeCalls.FindWithLock(token, PSafeReadOnly); if (call == NULL) return false; return call->IsEstablished(); } PBoolean OpalManager::ClearCall(const PString & token, OpalConnection::CallEndReason reason, PSyncPoint * sync) { /*The hugely multi-threaded nature of the OpalCall objects means that to avoid many forms of race condition, a call is cleared by moving it from the "active" call dictionary to a list of calls to be cleared that will be processed by a background thread specifically for the purpose of cleaning up cleared calls. So that is all that this function actually does. The real work is done in the OpalGarbageCollector thread. */ // Find the call by token, callid or conferenceid PSafePtr<OpalCall> call = activeCalls.FindWithLock(token, PSafeReference); if (call == NULL) { PTRACE(2, "Could not find/lock call token \"" << token << '"'); return false; } call->Clear(reason, sync); return true; } PBoolean OpalManager::ClearCallSynchronous(const PString & token, OpalConnection::CallEndReason reason) { PSyncPoint wait; if (!ClearCall(token, reason, &wait)) return false; wait.Wait(); return false; } void OpalManager::ClearAllCalls(OpalConnection::CallEndReason reason, PBoolean wait) { InternalClearAllCalls(reason, wait, m_clearingAllCallsCount++ == 0); --m_clearingAllCallsCount; } void OpalManager::InternalClearAllCalls(OpalConnection::CallEndReason reason, bool wait, bool firstThread) { if (m_garbageCollector == NULL) return; PTRACE(3, "Clearing all calls " << (wait ? "and waiting" : "asynchronously") << ", " << (firstThread ? "primary" : "secondary") << " thread."); if (firstThread) { // Clear all the currentyl active calls for (PSafePtr<OpalCall> call = activeCalls; call != NULL; ++call) call->Clear(reason); } if (wait) { /* This is done this way as PSyncPoint only works for one thread at a time, all subsequent threads will wait on the mutex for the first one to be released from the PSyncPoint wait. */ m_clearingAllCallsMutex.Wait(); if (firstThread) PAssert(m_allCallsCleared.Wait(PTimeInterval(0,activeCalls.GetSize()*2,1)), "All calls not cleared in a timely manner"); m_clearingAllCallsMutex.Signal(); } PTRACE(3, "All calls cleared."); } void OpalManager::OnClearedCall(OpalCall & PTRACE_PARAM(call)) { PTRACE(3, "OnClearedCall " << call << " from \"" << call.GetPartyA() << "\" to \"" << call.GetPartyB() << '"'); } OpalCall * OpalManager::InternalCreateCall(void * userData) { if (m_clearingAllCallsCount != 0) { PTRACE(2, "Create call not performed as currently clearing all calls."); return NULL; } return CreateCall(userData); } OpalCall * OpalManager::CreateCall(void * /*userData*/) { return new OpalCall(*this); } void OpalManager::DestroyCall(OpalCall * call) { delete call; } PString OpalManager::GetNextToken(char prefix) { return psprintf("%c%08x%u", prefix, PRandom::Number(), ++lastCallTokenID); } PSafePtr<OpalConnection> OpalManager::MakeConnection(OpalCall & call, const PString & remoteParty, void * userData, unsigned int options, OpalConnection::StringOptions * stringOptions) { PTRACE(3, "Set up connection to \"" << remoteParty << '"'); PReadWaitAndSignal mutex(endpointsMutex); PCaselessString epname = PURL::ExtractScheme(remoteParty); OpalEndPoint * ep = FindEndPoint(epname); if (ep != NULL) return ep->MakeConnection(call, remoteParty, userData, options, stringOptions); PTRACE(1, "Could not find endpoint for protocol \"" << epname << '"'); return NULL; } PBoolean OpalManager::OnIncomingConnection(OpalConnection & connection, unsigned options, OpalConnection::StringOptions * stringOptions) { PTRACE(3, "OnIncoming connection " << connection); connection.OnApplyStringOptions(); // See if we already have a B-Party in the call. If not, make one. if (connection.GetOtherPartyConnection() != NULL) return true; OpalCall & call = connection.GetCall(); PTRACE_CONTEXT_ID_PUSH_THREAD(call); // See if have pre-allocated B party address, otherwise // get destination from incoming connection PString destination = call.GetPartyB(); if (destination.IsEmpty()) { destination = connection.GetDestinationAddress(); if (destination.IsEmpty()) { PTRACE(3, "Cannot complete call, no destination address from connection " << connection); return false; } } OpalConnection::StringOptions mergedOptions = connection.GetStringOptions(); if (stringOptions != NULL) { for (PStringToString::iterator it = stringOptions->begin(); it != stringOptions->end(); ++it) mergedOptions.SetAt(it->first, it->second); } #if OPAL_HAS_IM /* If A-Party is not "im" and it only has im media formats, then direct connect to the "im" endpoint without going throught routing engine. */ if (connection.IsNetworkConnection()) { OpalIMEndPoint * imEP = FindEndPointAs<OpalIMEndPoint>(OpalIMEndPoint::Prefix()); if (imEP != NULL) { OpalMediaFormatList formats = imEP->GetMediaFormats(); connection.AdjustMediaFormats(true, NULL, formats); if (!formats.IsEmpty()) { OpalMediaFormatList formats = connection.GetMediaFormats(); if (!formats.IsEmpty()) { PStringStream autoStart; OpalMediaFormatList::iterator it; for (it = formats.begin(); it != formats.end(); ++it) { static const char prefix[] = OPAL_IM_MEDIA_TYPE_PREFIX; if (it->GetMediaType().compare(0, sizeof(prefix)-1, prefix) != 0) break; autoStart << it->GetMediaType() << ":sendrecv\n"; } if (it == formats.end()) { mergedOptions.SetAt(OPAL_OPT_AUTO_START, autoStart); return imEP->MakeConnection(call, OpalIMEndPoint::Prefix() + ":*", NULL, options, &mergedOptions); } } } } } #endif // OPAL_HAS_IM #if OPAL_SCRIPT if (m_script != NULL) { PScriptLanguage::Signature sig; sig.m_arguments.resize(5); sig.m_arguments[0].SetDynamicString(call.GetToken()); sig.m_arguments[1].SetDynamicString(connection.GetToken()); sig.m_arguments[2].SetDynamicString(connection.GetRemotePartyURL()); sig.m_arguments[3].SetDynamicString(connection.GetLocalPartyURL()); sig.m_arguments[4].SetDynamicString(destination); if (m_script->Call("OnIncoming", sig) && !sig.m_results.empty()) destination = sig.m_results[0].AsString(); } #endif // Use a routing algorithm to figure out who the B-Party is, and make second connection PStringSet routesTried; return OnRouteConnection(routesTried, connection.GetRemotePartyURL(), destination, call, options, &mergedOptions); } bool OpalManager::OnRouteConnection(PStringSet & routesTried, const PString & a_party, const PString & b_party, OpalCall & call, unsigned options, OpalConnection::StringOptions * stringOptions) { PINDEX tableEntry = 0; for (;;) { PString route = ApplyRouteTable(a_party, b_party, tableEntry); if (route.IsEmpty()) { if (a_party == b_party) { PTRACE(3, "Circular route a=b=\"" << a_party << "\", call=" << call); return false; } // Check for if B-Party is an explicit address PCaselessString scheme = PURL::ExtractScheme(b_party); if (FindEndPoint(scheme) != NULL) return MakeConnection(call, b_party, NULL, options, stringOptions) != NULL; if (scheme.IsEmpty()) { for (PList<OpalEndPoint>::iterator it = endpointList.begin(); it != endpointList.end(); ++it) { if (it->HasAttribute(OpalEndPoint::IsNetworkEndPoint) == (call.GetConnectionCount() > 0)) return MakeConnection(call, it->GetPrefixName() + ':' + b_party, NULL, options, stringOptions) != NULL; } } PTRACE(3, "Could not route a=\"" << a_party << "\", b=\"" << b_party << "\", call=" << call); return false; } // See if already tried, keep searching if this route has already failed if (routesTried[route]) continue; routesTried += route; // See if this route can be connected if (MakeConnection(call, route, NULL, options, stringOptions) != NULL) return true; if (call.GetConnection(0)->IsReleased()) return false; // Recursively call with translated route if (OnRouteConnection(routesTried, a_party, route, call, options, stringOptions)) return true; } } void OpalManager::OnProceeding(OpalConnection & connection) { PTRACE(3, "OnProceeding " << connection); connection.GetCall().OnProceeding(connection); #if OPAL_SCRIPT if (m_script != NULL) m_script->Call("OnProceeding", "ss", (const char *)connection.GetCall().GetToken(), (const char *)connection.GetToken()); #endif } void OpalManager::OnAlerting(OpalConnection & connection, bool withMedia) { PTRACE(3, "OnAlerting " << connection << (withMedia ? " with media" : " normal")); connection.GetCall().OnAlerting(connection, withMedia); #if OPAL_SCRIPT if (m_script != NULL) m_script->Call("OnAlerting", "ssb", (const char *)connection.GetCall().GetToken(), (const char *)connection.GetToken(), withMedia); #endif } void OpalManager::OnAlerting(OpalConnection & connection) { connection.GetCall().OnAlerting(connection); } OpalConnection::AnswerCallResponse OpalManager::OnAnswerCall(OpalConnection & connection, const PString & caller) { return connection.GetCall().OnAnswerCall(connection, caller); } void OpalManager::OnConnected(OpalConnection & connection) { PTRACE(3, "OnConnected " << connection); #if OPAL_SCRIPT if (m_script != NULL) m_script->Call("OnConnected", "ss", (const char *)connection.GetCall().GetToken(), (const char *)connection.GetToken()); #endif connection.GetCall().OnConnected(connection); } void OpalManager::OnEstablished(OpalConnection & connection) { PTRACE(3, "OnEstablished " << connection); connection.GetCall().OnEstablished(connection); } void OpalManager::OnReleased(OpalConnection & connection) { PTRACE(3, "OnReleased " << connection); connection.GetCall().OnReleased(connection); } void OpalManager::OnHold(OpalConnection & connection, bool PTRACE_PARAM(fromRemote), bool PTRACE_PARAM(onHold)) { PTRACE(3, (onHold ? "On" : "Off") << " Hold " << (fromRemote ? "from remote" : "request succeeded") << " on " << connection); connection.GetEndPoint().OnHold(connection); } void OpalManager::OnHold(OpalConnection & /*connection*/) { } PBoolean OpalManager::OnForwarded(OpalConnection & PTRACE_PARAM(connection), const PString & /*forwardParty*/) { PTRACE(4, "OnForwarded " << connection); return true; } bool OpalManager::OnTransferNotify(OpalConnection & PTRACE_PARAM(connection), const PStringToString & info) { PTRACE(4, "OnTransferNotify for " << connection << '\n' << info); return info["result"] != "success"; } OpalMediaFormatList OpalManager::GetCommonMediaFormats(bool transportable, bool pcmAudio) const { OpalMediaFormatList formats; if (transportable) { OpalMediaFormatList allFormats = OpalMediaFormat::GetAllRegisteredMediaFormats(); for (OpalMediaFormatList::iterator iter = allFormats.begin(); iter != allFormats.end(); ++iter) { if (iter->IsTransportable()) formats += *iter; } } if (pcmAudio) { // Sound cards can only do 16 bit PCM, but at various sample rates // The following will be in order of preference, so lets do wideband first formats += OpalPCM16S_48KHZ; formats += OpalPCM16S_32KHZ; formats += OpalPCM16S_16KHZ; formats += OpalPCM16_48KHZ; formats += OpalPCM16_32KHZ; formats += OpalPCM16_16KHZ; formats += OpalPCM16; formats += OpalRFC2833; #if OPAL_T38_CAPABILITY formats += OpalCiscoNSE; #endif } #if OPAL_VIDEO if (!GetVideoInputDevice().deviceName.IsEmpty()) formats += OpalYUV420P; #endif #if OPAL_HAS_MSRP formats += OpalMSRP; #endif #if OPAL_HAS_SIPIM formats += OpalSIPIM; #endif #if OPAL_HAS_RFC4103 formats += OpalT140; #endif #if OPAL_HAS_H281 formats += OpalFECC_RTP; formats += OpalFECC_HDLC; #endif return formats; } void OpalManager::AdjustMediaFormats(bool local, const OpalConnection & connection, OpalMediaFormatList & mediaFormats) const { mediaFormats.Remove(mediaFormatMask); // Don't do the reorder done if acting as gateway, use other network endpoints ordering if (local) { bool reorder = true; if (connection.IsNetworkConnection()) { PSafePtr<OpalConnection> otherConnection = connection.GetOtherPartyConnection(); if (otherConnection != NULL && otherConnection->IsNetworkConnection()) reorder = false; } if (reorder) mediaFormats.Reorder(mediaFormatOrder); } connection.GetCall().AdjustMediaFormats(local, connection, mediaFormats); } OpalManager::MediaTransferMode OpalManager::GetMediaTransferMode(const OpalConnection & /*provider*/, const OpalConnection & /*consumer*/, const OpalMediaType & /*mediaType*/) const { return MediaTransferForward; } bool OpalManager::GetMediaTransportAddresses(const OpalConnection & provider, const OpalConnection & consumer, unsigned PTRACE_PARAM(sessionId), const OpalMediaType & mediaType, OpalTransportAddressArray &) const { if (!provider.IsNetworkConnection() || !consumer.IsNetworkConnection()) return false; MediaTransferMode mode = GetMediaTransferMode(provider, consumer, mediaType); PTRACE(3, "Media transfer mode set to " << mode << " for " << mediaType << " session " << sessionId << ", from " << provider << " to " << consumer); return mode == OpalManager::MediaTransferBypass; } PBoolean OpalManager::OnOpenMediaStream(OpalConnection & PTRACE_PARAM(connection), OpalMediaStream & PTRACE_PARAM(stream)) { PTRACE(3, "OnOpenMediaStream " << connection << ',' << stream); return true; } bool OpalManager::OnLocalRTP(OpalConnection & PTRACE_PARAM(connection1), OpalConnection & PTRACE_PARAM(connection2), unsigned PTRACE_PARAM(sessionID), bool PTRACE_PARAM(started)) const { PTRACE(3, "OnLocalRTP(" << connection1 << ',' << connection2 << ',' << sessionID << ',' << started); return false; } static bool PassOneThrough(OpalMediaStreamPtr source, OpalMediaStreamPtr sink, bool bypass) { if (source == NULL) { PTRACE(2, "SetMediaPassThrough could not complete as source stream does not exist"); return false; } if (sink == NULL) { PTRACE(2, "SetMediaPassThrough could not complete as sink stream does not exist"); return false; } // Note SetBypassPatch() will do PTRACE() on status. return source->SetMediaPassThrough(*sink, bypass); } bool OpalManager::SetMediaPassThrough(OpalConnection & connection1, OpalConnection & connection2, bool bypass, unsigned sessionID) { bool gotOne = false; if (sessionID != 0) { // Do not use || as McCarthy will not execute the second bypass if (PassOneThrough(connection1.GetMediaStream(sessionID, true), connection2.GetMediaStream(sessionID, false), bypass)) gotOne = true; if (PassOneThrough(connection2.GetMediaStream(sessionID, true), connection1.GetMediaStream(sessionID, false), bypass)) gotOne = true; } else { OpalMediaStreamPtr stream; while ((stream = connection1.GetMediaStream(OpalMediaType(), true , stream)) != NULL) { if (PassOneThrough(stream, connection2.GetMediaStream(stream->GetSessionID(), false), bypass)) gotOne = true; } while ((stream = connection2.GetMediaStream(OpalMediaType(), true, stream)) != NULL) { if (PassOneThrough(stream, connection1.GetMediaStream(stream->GetSessionID(), false), bypass)) gotOne = true; } } return gotOne; } bool OpalManager::SetMediaPassThrough(const PString & token1, const PString & token2, bool bypass, unsigned sessionID, bool network) { PSafePtr<OpalCall> call1 = FindCallWithLock(token1); PSafePtr<OpalCall> call2 = FindCallWithLock(token2); if (call1 == NULL || call2 == NULL) { PTRACE(2, "SetMediaPassThrough could not complete as one call does not exist"); return false; } PSafePtr<OpalConnection> connection1 = call1->GetConnection(0, PSafeReadOnly); while (connection1 != NULL && connection1->IsNetworkConnection() == network) ++connection1; PSafePtr<OpalConnection> connection2 = call2->GetConnection(0, PSafeReadOnly); while (connection2 != NULL && connection2->IsNetworkConnection() == network) ++connection2; if (connection1 == NULL || connection2 == NULL) { PTRACE(2, "SetMediaPassThrough could not complete as network connection not present in calls"); return false; } return OpalManager::SetMediaPassThrough(*connection1, *connection2, bypass, sessionID); } void OpalManager::OnClosedMediaStream(const OpalMediaStream & PTRACE_PARAM(channel)) { PTRACE(5, "OnClosedMediaStream " << channel); } void OpalManager::OnFailedMediaStream(OpalConnection & PTRACE_PARAM(connection), bool PTRACE_PARAM(fromRemote), const PString & PTRACE_PARAM(reason)) { PTRACE(3, "OnFailedMediaStream \"" << reason << "\" " << (fromRemote ? "from remote" : "by local") << ' ' << connection); } #if OPAL_VIDEO PBoolean OpalManager::CreateVideoInputDevice(const OpalConnection & connection, const OpalMediaFormat & mediaFormat, PVideoInputDevice * & device, PBoolean & autoDelete) { // Make copy so we can adjust the size OpalVideoFormat::ContentRole role = mediaFormat.GetOptionEnum(OpalVideoFormat::ContentRoleOption(), OpalVideoFormat::eNoRole); PVideoDevice::OpenArgs args = m_videoInputDevice[role]; PTRACE(3, "Using " << role << " video device \"" << args.deviceName << "\" for " << *this); mediaFormat.AdjustVideoArgs(args); return CreateVideoInputDevice(connection, args, device, autoDelete); } PBoolean OpalManager::CreateVideoInputDevice(const OpalConnection & /*connection*/, const PVideoDevice::OpenArgs & args, PVideoInputDevice * & device, PBoolean & autoDelete) { autoDelete = true; device = PVideoInputDevice::CreateOpenedDevice(args, false); PTRACE_IF(3, device == NULL, "Could not open video input device \"" << args.deviceName << '"'); return device != NULL; } PBoolean OpalManager::CreateVideoOutputDevice(const OpalConnection & connection, const OpalMediaFormat & mediaFormat, PBoolean preview, PVideoOutputDevice * & device, PBoolean & autoDelete) { // Make copy so we can adjust the size OpalVideoFormat::ContentRole role = mediaFormat.GetOptionEnum(OpalVideoFormat::ContentRoleOption(), OpalVideoFormat::eNoRole); PVideoDevice::OpenArgs args = preview ? m_videoPreviewDevice[role] : m_videoOutputDevice[role]; if (args.deviceName.IsEmpty() && args.driverName.IsEmpty()) { PTRACE(4, "No video " << (preview ? "preview" : "output") << " device specified for " << role); return false; // Disabled } mediaFormat.AdjustVideoArgs(args); if (preview) { static PConstString const LocalPreview("TITLE=\"Local Preview\""); args.deviceName.Replace("TITLE=\"Video Output\"", LocalPreview); } else { PINDEX start = args.deviceName.Find("TITLE=\""); if (start != P_MAX_INDEX) { start += 7; PINDEX end = args.deviceName.Find('"', start + 7) - 1; if (start == end) args.deviceName.Splice(connection.GetRemotePartyName(), start, 0); else if (args.deviceName(start, end) == "Video Output") args.deviceName.Splice(connection.GetRemotePartyName(), start, 13); else if ((start = args.deviceName.Find("%REMOTE%")) < end) args.deviceName.Splice(connection.GetRemotePartyName(), start, 8); } } return CreateVideoOutputDevice(connection, args, device, autoDelete); } bool OpalManager::CreateVideoOutputDevice(const OpalConnection & /*connection*/, const PVideoDevice::OpenArgs & args, PVideoOutputDevice * & device, PBoolean & autoDelete) { autoDelete = true; device = PVideoOutputDevice::CreateOpenedDevice(args, false); PTRACE_IF(4, device == NULL, "Could not open video output device \"" << args.deviceName << '"'); return device != NULL; } #endif // OPAL_VIDEO OpalMediaPatch * OpalManager::CreateMediaPatch(OpalMediaStream & source, PBoolean requiresPatchThread) { if (requiresPatchThread) return new OpalMediaPatch(source); else return new OpalPassiveMediaPatch(source); } #if OPAL_SCRIPT static void OnStartStopMediaPatch(PScriptLanguage * script, const char * fn, OpalConnection & connection, OpalMediaPatch & patch) { if (script == NULL) return; OpalMediaFormat mediaFormat = patch.GetSource().GetMediaFormat(); script->Call(fn, "sss", (const char *)connection.GetCall().GetToken(), (const char *)patch.GetSource().GetID(), (const char *)mediaFormat.GetName()); } #endif // OPAL_SCRIPT #if OPAL_SCRIPT void OpalManager::OnStartMediaPatch(OpalConnection & connection, OpalMediaPatch & patch) { OnStartStopMediaPatch(m_script, "OnStartMedia", connection, patch); #else void OpalManager::OnStartMediaPatch(OpalConnection & PTRACE_PARAM(connection), OpalMediaPatch & PTRACE_PARAM(patch)) { #endif PTRACE(3, "OnStartMediaPatch " << patch << " on " << connection); if (&patch.GetSource().GetConnection() == &connection) { PSafePtr<OpalConnection> other = connection.GetOtherPartyConnection(); if (other != NULL) other->OnStartMediaPatch(patch); } } void OpalManager::OnStopMediaPatch(OpalConnection & connection, OpalMediaPatch & patch) { PTRACE(3, "OnStopMediaPatch " << patch << " on " << connection); #if OPAL_SCRIPT OnStartStopMediaPatch(m_script, "OnStopMedia", connection, patch); #endif } bool OpalManager::OnMediaFailed(OpalConnection & connection, unsigned) { if (connection.AllMediaFailed()) { PTRACE(2, "All media failed, releasing " << connection); connection.Release(OpalConnection::EndedByMediaFailed); } return true; } void OpalManager::OnUserInputString(OpalConnection & connection, const PString & value) { connection.GetCall().OnUserInputString(connection, value); } void OpalManager::OnUserInputTone(OpalConnection & connection, char tone, int duration) { connection.GetCall().OnUserInputTone(connection, tone, duration); } PString OpalManager::ReadUserInput(OpalConnection & connection, const char * terminators, unsigned lastDigitTimeout, unsigned firstDigitTimeout) { PTRACE(3, "ReadUserInput from " << connection); connection.PromptUserInput(true); PString digit = connection.GetUserInput(firstDigitTimeout); connection.PromptUserInput(false); if (digit.IsEmpty()) { PTRACE(2, "ReadUserInput first character timeout (" << firstDigitTimeout << " seconds) on " << *this); return PString::Empty(); } PString input; while (digit.FindOneOf(terminators) == P_MAX_INDEX) { input += digit; digit = connection.GetUserInput(lastDigitTimeout); if (digit.IsEmpty()) { PTRACE(2, "ReadUserInput last character timeout (" << lastDigitTimeout << " seconds) on " << *this); return input; // Input so far will have to do } } return input.IsEmpty() ? digit : input; } void OpalManager::OnMWIReceived(const PString & PTRACE_PARAM(party), MessageWaitingType PTRACE_PARAM(type), const PString & PTRACE_PARAM(extraInfo)) { PTRACE(3, "OnMWIReceived(" << party << ',' << type << ',' << extraInfo << ')'); } bool OpalManager::GetConferenceStates(OpalConferenceStates & states, const PString & name) const { PReadWaitAndSignal mutex(endpointsMutex); for (PList<OpalEndPoint>::const_iterator ep = endpointList.begin(); ep != endpointList.end(); ++ep) { if (ep->GetConferenceStates(states, name)) return true; } return false; } void OpalManager::OnConferenceStatusChanged(OpalEndPoint & endpoint, const PString & uri, OpalConferenceState::ChangeType change) { PTRACE(4, "OnConferenceStatusChanged(" << endpoint << ",\"" << uri << "\"," << change << ')'); PReadWaitAndSignal mutex(endpointsMutex); for (PList<OpalEndPoint>::iterator ep = endpointList.begin(); ep != endpointList.end(); ++ep) { if (&endpoint != &*ep) ep->OnConferenceStatusChanged(endpoint, uri, change); } } bool OpalManager::OnChangedPresentationRole(OpalConnection & PTRACE_PARAM(connection), const PString & PTRACE_PARAM(newChairURI), bool) { PTRACE(3, "OnChangedPresentationRole to " << newChairURI << " on " << connection); return true; } PStringList OpalManager::GetNetworkURIs(const PString & name) const { PStringList list; PReadWaitAndSignal mutex(endpointsMutex); for (PList<OpalEndPoint>::const_iterator ep = endpointList.begin(); ep != endpointList.end(); ++ep) list += ep->GetNetworkURIs(name); return list; } OpalManager::RouteEntry::RouteEntry(const PString & partyA, const PString & partyB, const PString & dest) : m_partyA(partyA) , m_partyB(partyB) , m_destination(dest) { CompileRegEx(); } OpalManager::RouteEntry::RouteEntry(const PString & spec) { // Make sure we test for backward compatibility format(s) PINDEX equal = spec.Find('='); if (equal == P_MAX_INDEX) return; // Must have m_destination = spec.Mid(equal+1).Trim(); PINDEX colon = spec.Find(':'); if (colon == 0) return; // No scheme? PINDEX tab = spec.Find('\t'); if (tab == P_MAX_INDEX) tab = spec.Find("\\t"); if (tab == 0) return; // No source? if (tab < equal) { m_partyA = spec.Left(tab).Trim(); m_partyB = spec(tab+(spec[tab]=='\t'?1:2), equal-1).Trim(); } else if (colon < equal) { m_partyA = spec.Left(colon+1)+".*"; m_partyB = spec(colon+1, equal-1).Trim(); } else m_partyA = spec.Left(equal).Trim(); if (m_partyB.IsEmpty()) m_partyB = ".*"; CompileRegEx(); } void OpalManager::RouteEntry::CompileRegEx() { PStringStream pattern; pattern << "^(" << m_partyA << ")\t(" << m_partyB << ")$"; if (!m_regex.Compile(pattern, PRegularExpression::IgnoreCase|PRegularExpression::Extended)) { PTRACE(1, "Could not compile route regular expression \"" << pattern << '"'); } } void OpalManager::RouteEntry::PrintOn(ostream & strm) const { strm << m_partyA << "\\t" << m_partyB << '=' << m_destination; } bool OpalManager::RouteEntry::IsValid() const { return !m_destination.IsEmpty() && m_regex.GetErrorCode() == PRegularExpression::NoError; } bool OpalManager::RouteEntry::IsMatch(const PString & search) const { PINDEX dummy; bool ok = m_regex.Execute(search, dummy); PTRACE(4, (ok ? "Matched" : "Did not match") << " regex \"" << m_regex.GetPattern() << "\" (" << *this << ')'); return ok; } PBoolean OpalManager::AddRouteEntry(const PString & spec) { if (spec[0] == '#') // Comment return false; if (spec[0] == '@') { // Load from file PTextFile file; if (!file.Open(spec.Mid(1), PFile::ReadOnly)) { PTRACE(1, "Could not open route file \"" << file.GetFilePath() << '"'); return false; } PTRACE(4, "Adding routes from file \"" << file.GetFilePath() << '"'); PBoolean ok = false; PString line; while (file.good()) { file >> line; if (AddRouteEntry(line)) ok = true; } return ok; } RouteEntry * entry = new RouteEntry(spec); if (!entry->IsValid()) { PTRACE(2, "Illegal specification for route table entry: \"" << spec << '"'); delete entry; return false; } PTRACE(4, "Added route \"" << *entry << '"'); m_routeMutex.Wait(); m_routeTable.Append(entry); m_routeMutex.Signal(); return true; } PBoolean OpalManager::SetRouteTable(const PStringArray & specs) { PBoolean ok = false; m_routeMutex.Wait(); m_routeTable.RemoveAll(); for (PINDEX i = 0; i < specs.GetSize(); i++) { if (AddRouteEntry(specs[i].Trim())) ok = true; } m_routeMutex.Signal(); return ok; } void OpalManager::SetRouteTable(const RouteTable & table) { m_routeMutex.Wait(); m_routeTable = table; m_routeTable.MakeUnique(); m_routeMutex.Signal(); } PString OpalManager::ApplyRouteTable(const PString & a_party, const PString & b_party, PINDEX & routeIndex) { PString destination; { PWaitAndSignal mutex(m_routeMutex); if (m_routeTable.IsEmpty()) return routeIndex++ == 0 ? b_party : PString::Empty(); PString search = a_party + '\t' + b_party; PTRACE(4, "Searching for route \"" << search << '"'); /* Examples: Call from UI pc:USB Audio Device\USB Audio Device sip:fred@boggs.com pc:USB Audio Device\USB Audio Device h323:fred@boggs.com pc:USB Audio Device\USB Audio Device fred Call from handset pots:TigerJet:USB Audio Device 123 Call from SIP sip:me@here.net sip:you@there.com sip:me@here.net:5061 sip:you@there.com Call from H.323 h323:me@here.net h323:there.com h323:me@here.net:1721 h323:fred Table: .*:# = ivr: pots:.*\\*.*\\*.* = sip:<dn2ip> pots:.* = sip:<da> pc:.* = sip:<da> h323:.* = pots:<dn> sip:.* = pots:<dn> h323:.* = pc: sip:.* = pc: */ while (routeIndex < m_routeTable.GetSize()) { RouteEntry & entry = m_routeTable[routeIndex++]; if (entry.IsMatch(search)) { search = entry.GetDestination(); if (search.NumCompare("label:") != EqualTo) { destination = search; break; } // restart search in table using label. routeIndex = 0; } } } // No route found if (destination.IsEmpty()) return PString::Empty(); // See if B-Party a parsable URL PURL b_url(b_party, NULL); // We are backward compatibility mode and the supplied address can be called if (destination.Find("<da>") != P_MAX_INDEX) { if (b_url.IsEmpty()) { PINDEX colon = b_party.Find(':'); if (colon != P_MAX_INDEX && FindEndPoint(b_party.Left(colon)) != NULL) return b_party; } else { if (FindEndPoint(b_url.GetScheme()) != NULL) return b_party; } } PString user, nonUser, digits, nonDigits; if (b_url.IsEmpty()) { PINDEX colon = b_party.Find(':'); if (colon == P_MAX_INDEX) colon = 0; else ++colon; PINDEX at = b_party.Find('@', colon); user = b_party(colon, at-1); nonUser = b_party.Mid('@'); if (nonUser.IsEmpty() && PIPSocket::IsLocalHost(user.Left(user.Find(':')))) { nonUser = user; user.MakeEmpty(); } PINDEX nonDigitPos = b_party.FindSpan("0123456789*#-.()", colon + (b_party[colon] == '+')); digits = b_party(colon, nonDigitPos-1); nonDigits = b_party.Mid(nonDigitPos); } else { user = b_url.GetUserName(); nonUser = b_url.GetHostPort() + b_url.AsString(PURL::RelativeOnly); if (OpalIsE164(user)) { digits = user; nonDigits = nonUser; } else nonDigits = b_party; } // This hack is to avoid double '@' if (nonUser.Find('@') != P_MAX_INDEX) { PINDEX at = destination.Find('@'); if (at != P_MAX_INDEX) { PINDEX du = destination.Find("<!du>", at); if (du != P_MAX_INDEX) destination.Delete(at, du-at); } } // Substute from source(s) to destination destination.Replace("<da>", b_party, true); destination.Replace("<db>", b_party, true); destination.Replace("<du>", user, true); destination.Replace("<!du>", nonUser, true); destination.Replace("<cu>", a_party(a_party.Find(':') + 1, a_party.Find('@') - 1), true); destination.Replace("<dn>", digits, true); destination.Replace("<!dn>", nonDigits, true); PINDEX pos; static PRegularExpression const DNx("<dn[1-9]>"); while (DNx.Execute(destination, pos)) destination.Splice(digits.Mid(destination[pos+3]-'0'), pos, 5); // Do meta character substitutions while ((pos = destination.Find("<dn2ip>")) != P_MAX_INDEX) { PStringStream route; PStringArray stars = digits.Tokenise('*'); switch (stars.GetSize()) { case 0 : case 1 : case 2 : case 3 : route << digits; break; case 4 : route << stars[0] << '.' << stars[1] << '.'<< stars[2] << '.'<< stars[3]; break; case 5 : route << stars[0] << '@' << stars[1] << '.' << stars[2] << '.'<< stars[3] << '.'<< stars[4]; break; default : route << stars[0] << '@' << stars[1] << '.' << stars[2] << '.'<< stars[3] << '.'<< stars[4] << ':' << stars[5]; break; } destination.Splice(route, pos, 7); } return destination; } void OpalManager::SetProductInfo(const OpalProductInfo & info, bool updateAll) { productInfo = info; if (updateAll) { endpointsMutex.StartWrite(); for (PList<OpalEndPoint>::iterator ep = endpointList.begin(); ep != endpointList.end(); ++ep) ep->SetProductInfo(info); endpointsMutex.EndWrite(); } } void OpalManager::SetDefaultUserName(const PString & name, bool updateAll) { defaultUserName = name; if (updateAll) { endpointsMutex.StartWrite(); for (PList<OpalEndPoint>::iterator ep = endpointList.begin(); ep != endpointList.end(); ++ep) ep->SetDefaultLocalPartyName(name); endpointsMutex.EndWrite(); } } void OpalManager::SetDefaultDisplayName(const PString & name, bool updateAll) { defaultDisplayName = name; if (updateAll) { endpointsMutex.StartWrite(); for (PList<OpalEndPoint>::iterator ep = endpointList.begin(); ep != endpointList.end(); ++ep) ep->SetDefaultDisplayName(name); endpointsMutex.EndWrite(); } } #if OPAL_PTLIB_SSL bool OpalManager::ApplySSLCredentials(const OpalEndPoint & /*ep*/, PSSLContext & context, bool create) const { return context.SetCredentials(m_caFiles, m_certificateFile, m_privateKeyFile, create && m_autoCreateCertificate); } #endif PBoolean OpalManager::IsLocalAddress(const PIPSocket::Address & ip) const { #if OPAL_PTLIB_NAT return m_natMethods->IsLocalAddress(ip); #else /* Check if the remote address is a private IP, broadcast, or us */ return ip.IsAny() || ip.IsBroadcast() || ip.IsRFC1918() || PIPSocket::IsLocalHost(ip); #endif } PBoolean OpalManager::IsRTPNATEnabled(OpalConnection & /*conn*/, const PIPSocket::Address & localAddr, const PIPSocket::Address & peerAddr, const PIPSocket::Address & sigAddr, PBoolean PTRACE_PARAM(incoming)) { PTRACE(4, "Checking " << (incoming ? "incoming" : "outgoing") << " call for NAT: local=" << localAddr << ", peer=" << peerAddr << ", sig=" << sigAddr); /* The peer endpoint may be on a public address, the local network (LAN) or NATed. If the last, it either knows it is behind the NAT or is blissfully unaware of it. If the remote is public or on a LAN/VPN then no special treatment of RTP is needed. We do make the assumption that the remote will indicate correct addresses everywhere, in SETUP/OLC and INVITE/SDP. Now if the endpoint is NATed and knows it is behind a NAT, and is doing it correctly, it is indistinguishable from being on a public address. If the remote endpoint is unaware of it's NAT status then there will be a discrepency between the physical address of the connection and the signaling adddress indicated in the protocol, the H.323 SETUP sourceCallSignalAddress or SIP "Contact" field. So this is the first test to make: if those addresses the same, we will assume the other guy is public or LAN/VPN and either no NAT is involved, or we leave them in charge of any NAT traversal as he has the ability to do it. In either case we don't do anything. */ if (peerAddr == sigAddr) return false; /* Next test is to see if BOTH addresses are "public", non RFC1918. There are some cases with proxies, particularly with SIP, where this is possible. We will assume that NAT never occurs between two public addresses though it could occur between two private addresses */ if (!peerAddr.IsRFC1918() && !sigAddr.IsRFC1918()) return false; /* So now we have a remote that is confused in some way, so needs help. Our next test is for cases of where we are on a multi-homed machine and we ended up with a call from interface to another. No NAT needed. */ if (PIPSocket::IsLocalHost(peerAddr)) return false; /* So, call is from a remote host somewhere and is still confused. We now need to check if we are actually ABLE to help. We test if the local end of the connection is public, i.e. no NAT at this end so we can help. */ if (!localAddr.IsRFC1918()) return true; /* Another test for if we can help, we are behind a NAT too, but the user has provided information so we can compensate for it, i.e. we "know" about the NAT. We determine this by translating the localAddr and seing if it gets changed to the NAT router address. If so, we can help. */ PIPSocket::Address natAddr = localAddr; if (TranslateIPAddress(natAddr, peerAddr)) return true; /* This looks for seriously confused systems were NAT is between two private networks. Unfortunately, we don't have a netmask so we can only guess based on the IP address class. */ if ( peerAddr.IsRFC1918() && sigAddr.IsRFC1918() && !peerAddr.IsSubNet(sigAddr, PIPAddress::GetAny(peerAddr.GetVersion()))) return true; /* If we get here, we appear to be in a situation which, if we tried to do the NAT translation, we could end up in a staring match as the NAT traversal technique does not send anything till it receives something. If both side do that then ..... So, we do nothing and hope for the best. This means that either the call gets no media, or there is some other magic entity (smart router, proxy, etc) between the two endpoints we know nothing about that will do NAT translations for us. Are there any other cases? */ return false; } PBoolean OpalManager::TranslateIPAddress(PIPSocket::Address & localAddress, const PIPSocket::Address & remoteAddress) { if (!IsLocalAddress(localAddress)) return false; // Is already translated if (IsLocalAddress(remoteAddress)) return false; // Does not need to be translated #if OPAL_PTLIB_NAT PNatMethod * natMethod = m_natMethods->GetMethod(localAddress); if (natMethod != NULL) return natMethod->GetExternalAddress(localAddress); // Translate it! #endif return false; // Have nothing to translate it to } #if OPAL_PTLIB_NAT bool OpalManager::SetNATServer(const PString & method, const PString & server, bool activate, unsigned priority) { PNatMethod * natMethod = m_natMethods->GetMethodByName(method); if (natMethod == NULL) { PTRACE(2, "Unknown NAT method \"" << method << '"'); return false; } natMethod->Activate(activate); m_natMethods->SetMethodPriority(method, priority); natMethod->SetPortRanges(GetUDPPortRange().GetBase(), GetUDPPortRange().GetMax(), GetRtpIpPortRange().GetBase(), GetRtpIpPortRange().GetMax()); if (!natMethod->SetServer(server)) { PTRACE(2, "Invalid server \"" << server << " for " << method << " NAT method"); return false; } if (!natMethod->Open(PIPSocket::GetDefaultIpAny())) { PTRACE(2, "Could not open server \"" << server << " for " << method << " NAT method"); return false; } PTRACE(3, "NAT " << *natMethod); return true; } PString OpalManager::GetNATServer(const PString & method) const { PNatMethod * natMethod = m_natMethods->GetMethodByName(method); return natMethod == NULL ? PString::Empty() : natMethod->GetServer(); } #endif // OPAL_PTLIB_NAT void OpalManager::SetTCPPorts(unsigned tcpBase, unsigned tcpMax) { m_tcpPorts.Set(tcpBase, tcpMax, 49, 0); } void OpalManager::SetUDPPorts(unsigned udpBase, unsigned udpMax) { m_udpPorts.Set(udpBase, udpMax, 99, 0); #if OPAL_PTLIB_NAT GetNatMethods().SetPortRanges(GetUDPPortRange().GetBase(), GetUDPPortRange().GetMax(), GetRtpIpPortRange().GetBase(), GetRtpIpPortRange().GetMax()); #endif } void OpalManager::SetRtpIpPorts(unsigned rtpIpBase, unsigned rtpIpMax) { m_rtpIpPorts.Set(rtpIpBase&0xfffe, rtpIpMax&0xfffe, 198, 5000); #if OPAL_PTLIB_NAT GetNatMethods().SetPortRanges(GetUDPPortRange().GetBase(), GetUDPPortRange().GetMax(), GetRtpIpPortRange().GetBase(), GetRtpIpPortRange().GetMax()); #endif } const PIPSocket::QoS & OpalManager::GetMediaQoS(const OpalMediaType & type) const { return m_mediaQoS[type]; } void OpalManager::SetMediaQoS(const OpalMediaType & type, const PIPSocket::QoS & qos) { m_mediaQoS[type] = qos; } BYTE OpalManager::GetMediaTypeOfService(const OpalMediaType & type) const { return (BYTE)(m_mediaQoS[type].m_dscp << 2); } void OpalManager::SetMediaTypeOfService(const OpalMediaType & type, unsigned tos) { m_mediaQoS[type].m_dscp = (tos>>2)&0x3f; } BYTE OpalManager::GetMediaTypeOfService() const { return (BYTE)(m_mediaQoS[OpalMediaType::Audio()].m_dscp << 2); } void OpalManager::SetMediaTypeOfService(unsigned tos) { for (MediaQoSMap::iterator it = m_mediaQoS.begin(); it != m_mediaQoS.end(); ++it) it->second.m_dscp = (tos>>2)&0x3f; } void OpalManager::SetAudioJitterDelay(unsigned minDelay, unsigned maxDelay) { if (minDelay == 0) { // Disable jitter buffer completely if minimum is zero. m_jitterParams.m_minJitterDelay = m_jitterParams.m_maxJitterDelay = 0; return; } PAssert(minDelay <= 10000 && maxDelay <= 10000, PInvalidParameter); if (minDelay < 10) minDelay = 10; m_jitterParams.m_minJitterDelay = minDelay; if (maxDelay < minDelay) maxDelay = minDelay; m_jitterParams.m_maxJitterDelay = maxDelay; } void OpalManager::SetMediaFormatOrder(const PStringArray & order) { mediaFormatOrder = order; PTRACE(3, "SetMediaFormatOrder(" << setfill(',') << order << ')'); } void OpalManager::SetMediaFormatMask(const PStringArray & mask) { mediaFormatMask = mask; PTRACE(3, "SetMediaFormatMask(" << setfill(',') << mask << ')'); } #if OPAL_VIDEO bool OpalManager::SetVideoInputDevice(const PVideoDevice::OpenArgs & args, OpalVideoFormat::ContentRole role) { return args.Validate<PVideoInputDevice>(m_videoInputDevice[role]); } PBoolean OpalManager::SetVideoPreviewDevice(const PVideoDevice::OpenArgs & args, OpalVideoFormat::ContentRole role) { return args.Validate<PVideoOutputDevice>(m_videoPreviewDevice[role]); } PBoolean OpalManager::SetVideoOutputDevice(const PVideoDevice::OpenArgs & args, OpalVideoFormat::ContentRole role) { return args.Validate<PVideoOutputDevice>(m_videoOutputDevice[role]); } #endif // OPAL_VIDEO void OpalManager::GarbageCollection() { #if OPAL_HAS_PRESENCE m_presentities.DeleteObjectsToBeRemoved(); #endif // OPAL_HAS_PRESENCE bool allCleared = activeCalls.DeleteObjectsToBeRemoved(); endpointsMutex.StartRead(); if (m_garbageCollectSkip) m_garbageCollectSkip = false; else { for (PList<OpalEndPoint>::iterator ep = endpointList.begin(); ep != endpointList.end(); ++ep) { if (!ep->GarbageCollection()) allCleared = false; } } endpointsMutex.EndRead(); if (allCleared && m_clearingAllCallsCount != 0) m_allCallsCleared.Signal(); } void OpalManager::CallDict::DeleteObject(PObject * object) const { manager.DestroyCall(PDownCast(OpalCall, object)); } void OpalManager::GarbageMain(PThread &, P_INT_PTR) { while (!m_garbageCollectExit.Wait(1000)) GarbageCollection(); } void OpalManager::OnNewConnection(OpalConnection & /*conn*/) { } #if OPAL_HAS_MIXER bool OpalManager::StartRecording(const PString & callToken, const PFilePath & fn, const OpalRecordManager::Options & options) { PSafePtr<OpalCall> call = activeCalls.FindWithLock(callToken, PSafeReadWrite); if (call == NULL) return false; return call->StartRecording(fn, options); } bool OpalManager::IsRecording(const PString & callToken) { PSafePtr<OpalCall> call = FindCallWithLock(callToken, PSafeReadWrite); return call != NULL && call->IsRecording(); } bool OpalManager::StopRecording(const PString & callToken) { PSafePtr<OpalCall> call = activeCalls.FindWithLock(callToken, PSafeReadWrite); if (call == NULL) return false; call->StopRecording(); return true; } #endif void OpalManager::OnApplyStringOptions(OpalConnection &, OpalConnection::StringOptions & stringOptions) { for (OpalConnection::StringOptions::iterator it = m_defaultConnectionOptions.begin(); it != m_defaultConnectionOptions.end(); ++it) { if (!stringOptions.Contains(it->first)) stringOptions.SetAt(it->first, it->second); } } #if OPAL_HAS_PRESENCE PSafePtr<OpalPresentity> OpalManager::AddPresentity(const PString & presentity) { if (presentity.IsEmpty()) return NULL; PSafePtr<OpalPresentity> oldPresentity = m_presentities.FindWithLock(presentity, PSafeReadWrite); if (oldPresentity != NULL) return oldPresentity; OpalPresentity * newPresentity = OpalPresentity::Create(*this, presentity); if (newPresentity == NULL) return NULL; PTRACE(4, "Added presentity for " << *newPresentity); m_presentities.SetAt(presentity, newPresentity); return PSafePtr<OpalPresentity>(newPresentity, PSafeReadWrite); } PSafePtr<OpalPresentity> OpalManager::GetPresentity(const PString & presentity, PSafetyMode mode) { return m_presentities.FindWithLock(presentity, mode); } PStringList OpalManager::GetPresentities() const { PStringList presentities; for (PSafePtr<OpalPresentity> presentity(m_presentities, PSafeReference); presentity != NULL; ++presentity) presentities += presentity->GetAOR().AsString(); return presentities; } bool OpalManager::RemovePresentity(const PString & presentity) { PTRACE(4, "Removing presentity for " << presentity); return m_presentities.RemoveAt(presentity); } #endif // OPAL_HAS_PRESENCE #if OPAL_HAS_IM void OpalManager::OnConversation(const OpalIMContext::ConversationInfo &) { } PBoolean OpalManager::Message(const PString & to, const PString & body) { OpalIM message; message.m_to = to; message.m_bodies.SetAt(PMIMEInfo::TextPlain(), body); return Message(message); } PBoolean OpalManager::Message(const PURL & to, const PString & type, const PString & body, PURL & from, PString & conversationId) { OpalIM message; message.m_to = to; message.m_from = from; message.m_conversationId = conversationId; message.m_bodies.SetAt(type, body); bool stat = Message(message); from = message.m_from; conversationId = message.m_conversationId; return stat; } bool OpalManager::Message(OpalIM & message) { OpalIMEndPoint * ep = FindEndPointAs<OpalIMEndPoint>(OpalIMEndPoint::Prefix()); if (ep == NULL) { return false; } PSafePtr<OpalIMContext> context = ep->FindContextForMessageWithLock(message); if (context == NULL) { context = ep->CreateContext(message.m_from, message.m_to); if (context == NULL) return false; message.m_conversationId = context->GetID(); } return context->Send(message.CloneAs<OpalIM>()) < OpalIMContext::DispositionErrors; } #if OPAL_HAS_PRESENCE void OpalManager::OnMessageReceived(const OpalIM & message) { // find a presentity to give the message to for (PSafePtr<OpalPresentity> presentity(m_presentities, PSafeReference); presentity != NULL; ++presentity) { if (message.m_to == presentity->GetAOR()) { presentity->OnReceivedMessage(message); break; } } } #else void OpalManager::OnMessageReceived(const OpalIM &) { } #endif // OPAL_HAS_PRESENCE void OpalManager::OnMessageDisposition(const OpalIMContext::DispositionInfo & ) { } void OpalManager::OnCompositionIndication(const OpalIMContext::CompositionInfo &) { } #endif // OPAL_HAS_IM #if OPAL_SCRIPT bool OpalManager::RunScript(const PString & script, const char * language) { delete m_script; m_script = PFactory<PScriptLanguage>::CreateInstance(language); if (m_script == NULL) return false; if (!m_script->Load(script)) { delete m_script; m_script = NULL; return false; } m_script->CreateComposite(OPAL_SCRIPT_CALL_TABLE_NAME); return m_script->Run(); } #endif // OPAL_SCRIPT ///////////////////////////////////////////////////////////////////////////// #if OPAL_PTLIB_NAT void OpalManager::OnInterfaceChange(PInterfaceMonitor &, PInterfaceMonitor::InterfaceChange entry) { PIPSocket::Address addr; for (PNatMethods::iterator nat = m_natMethods->begin(); nat != m_natMethods->end(); ++nat) { if (entry.m_added) { if (!nat->GetInterfaceAddress(addr) || entry.GetAddress() != addr) nat->Open(entry.GetAddress()); } else { if (nat->GetInterfaceAddress(addr) && entry.GetAddress() == addr) nat->Close(); } } } #endif // OPAL_PTLIB_NAT /////////////////////////////////////////////////////////////////////////////
29.679627
153
0.653188
[ "object" ]
5b46f9da9b5521c51ae9a62ab934cbbfb6557b9e
3,651
hpp
C++
include/libp2p/network/cares/cares.hpp
vvarma/cpp-libp2p
4953f30bc087de42637640eef929acfd102ef895
[ "Apache-2.0", "MIT" ]
null
null
null
include/libp2p/network/cares/cares.hpp
vvarma/cpp-libp2p
4953f30bc087de42637640eef929acfd102ef895
[ "Apache-2.0", "MIT" ]
null
null
null
include/libp2p/network/cares/cares.hpp
vvarma/cpp-libp2p
4953f30bc087de42637640eef929acfd102ef895
[ "Apache-2.0", "MIT" ]
null
null
null
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef LIBP2P_INCLUDE_LIBP2P_NETWORK_CARES_CARES_HPP #define LIBP2P_INCLUDE_LIBP2P_NETWORK_CARES_CARES_HPP #include <atomic> #include <functional> #include <list> #include <map> #include <memory> #include <string> #include <vector> #include <ares.h> #include <arpa/nameser.h> #include <sys/select.h> #include <boost/asio.hpp> #include <boost/optional.hpp> #include <libp2p/common/logger.hpp> #include <libp2p/outcome/outcome.hpp> namespace libp2p::network::c_ares { /** * * Only one instance is allowed to exist. * Has to be initialized prior any threads spawn. * Designed for use only via Boost injector passing by a reference. */ class Ares final { public: using TxtCallback = std::function<void(outcome::result<std::vector<std::string>>)>; enum class Error { NOT_INITIALIZED = 1, CHANNEL_INIT_FAILURE, THREAD_FAILED, // the following are the codes returned to callback by ::ares_query E_NO_DATA, E_BAD_QUERY, E_SERVER_FAIL, E_NOT_FOUND, E_SERVER_NOTIMP, E_REFUSED, E_BAD_NAME, E_QUERY_TIMEOUT, E_NS_CONN_REFUSED, E_NO_MEM, E_CANCELLED, E_CHANNEL_DESTROYED, E_BAD_RESPONSE, }; static inline const std::map<int, Ares::Error> kQueryErrors = { {ARES_ENODATA, Error::E_NO_DATA}, {ARES_EFORMERR, Error::E_BAD_QUERY}, {ARES_ESERVFAIL, Error::E_SERVER_FAIL}, {ARES_ENOTFOUND, Error::E_NOT_FOUND}, {ARES_ENOTIMP, Error::E_SERVER_NOTIMP}, {ARES_EREFUSED, Error::E_REFUSED}, {ARES_EBADNAME, Error::E_BAD_NAME}, {ARES_ETIMEOUT, Error::E_QUERY_TIMEOUT}, {ARES_ECONNREFUSED, Error::E_NS_CONN_REFUSED}, {ARES_ENOMEM, Error::E_NO_MEM}, {ARES_ECANCELLED, Error::E_CANCELLED}, {ARES_EDESTRUCTION, Error::E_CHANNEL_DESTROYED}, {ARES_EBADRESP, Error::E_BAD_RESPONSE}, }; Ares(); ~Ares(); // make it non-copyable Ares(const Ares &) = delete; Ares(Ares &&) = delete; void operator=(const Ares &) = delete; void operator=(Ares &&) = delete; static void resolveTxt( const std::string &uri, const std::weak_ptr<boost::asio::io_context> &io_context, TxtCallback callback); private: struct RequestContext { std::weak_ptr<boost::asio::io_context> io_context; std::string uri; TxtCallback callback; RequestContext(std::weak_ptr<boost::asio::io_context> io_context_, std::string uri_, TxtCallback callback_) : io_context{std::move(io_context_)}, uri{std::move(uri_)}, callback{std::move(callback_)} {} }; /// schedules to user's io_context the call of callback with specified error static void reportError( const std::weak_ptr<boost::asio::io_context> &io_context, TxtCallback callback, Error error); static void txtCallback(void *arg, int status, int timeouts, unsigned char *abuf, int alen); /// does ares sockets processing for the channel, to be in a separate thread static void waitAresChannel(::ares_channel channel); static void removeRequest(RequestContext *request_ptr); static std::atomic_bool initialized_; static std::list<std::shared_ptr<RequestContext>> requests_; static common::Logger log_; }; } // namespace libp2p::network::c_ares OUTCOME_HPP_DECLARE_ERROR(libp2p::network::c_ares, Ares::Error); #endif // LIBP2P_INCLUDE_LIBP2P_NETWORK_CARES_CARES_HPP
29.443548
80
0.668858
[ "vector" ]
5b47209362c2a7f24368819d9567e9419ed0bc5a
2,546
cpp
C++
app/deriqt/main.cpp
xiaoqiyu/DERIQT
57c20c40a692a4f877296a39ed91aeab8e4c6d66
[ "Apache-2.0" ]
2
2021-04-21T09:18:10.000Z
2021-05-12T08:53:22.000Z
app/deriqt/main.cpp
xiaoqiyu/DERIQT
57c20c40a692a4f877296a39ed91aeab8e4c6d66
[ "Apache-2.0" ]
null
null
null
app/deriqt/main.cpp
xiaoqiyu/DERIQT
57c20c40a692a4f877296a39ed91aeab8e4c6d66
[ "Apache-2.0" ]
null
null
null
#include "CTPTraderHandler.h" #include "CTPMdHandler.h" #include "INIReader.h" #include "UserStruct.h" #include <iostream> #include <unistd.h> #include <stdio.h> #include <vector> #include <unordered_map> #include <sstream> #include <string> #include <sys/types.h> #include "TickToKlineHelper.h" #include "DataStrategy.h" #include "TStrategy.h" #include <algorithm> #include <glog/logging.h> int nRequestID = 0; int DEBUG = 0; int main(int argc, char *argv[]) { // google::InitGoogleLogging(argv[0]); // FLAGS_log_dir = std::string("./log/"); std::string _conf_file_name; std::string _instrument_id; std::string mode = "0"; std::string _strategy_name = "data_strategy"; std::vector<std::string> v_instrumentID; if (argc <= 1) { LOG(ERROR) << "Please enter a config name" ; _conf_file_name = "/home/kiki/projects/DERIQT/test.ini"; v_instrumentID.push_back("rb2110"); _strategy_name = "data_strategy"; } else { _conf_file_name = argv[3]; _instrument_id = argv[2]; mode = argv[1]; std::stringstream sstr(_instrument_id); std::string token; while (getline(sstr, token, ',')) { v_instrumentID.push_back(token); } } QTStrategyBase *p_strategy = nullptr; std::string _shm_name = _strategy_name+_instrument_id; if (_strategy_name == "data_strategy") { p_strategy = new DataStrategy("data_strategy", std::stoi(mode),_shm_name.c_str(), 65536); } else if (_strategy_name == "t_strategy") { p_strategy = new TStrategy("t_strategy", std::stoi(mode), _strategy_name.c_str(), 65536); } p_strategy->init(v_instrumentID, _conf_file_name); sleep(5); std::string _user_id = "105600687"; std::string _broker_id = "9040"; LOG(INFO)<< "Before query investor position"; std::vector<CThostFtdcInvestorPositionField *> ret_pos = p_strategy->get_investor_position(_user_id, _broker_id); sleep(5); LOG(INFO)<< "After query investor position"; // int ret_trades = p_strategy->req_trade(_user_id, _broker_id); // sleep(5); std::vector<CThostFtdcTradingAccountField*> ret_account = p_strategy->get_account(_user_id, _broker_id); sleep(5); // int ret_pos_detail = p_strategy->get_position_details(_user_id, _broker_id); sleep(5); LOG(INFO)<< "After query investor account"; p_strategy->start(); p_strategy->stop(); p_strategy->release(); return 0; }
25.979592
118
0.648075
[ "vector" ]
5b47d521909ed1d5137fec609829e8ff39f1ff89
3,773
cpp
C++
src/fastcd/mesh_extension.cpp
InterDigitalInc/ObjectRemovalDetection
14ccff9792e2ab006377dc02b8260897465db988
[ "Apache-2.0" ]
1
2021-08-10T21:06:46.000Z
2021-08-10T21:06:46.000Z
src/fastcd/mesh_extension.cpp
InterDigitalInc/ObjectRemovalDetection
14ccff9792e2ab006377dc02b8260897465db988
[ "Apache-2.0" ]
null
null
null
src/fastcd/mesh_extension.cpp
InterDigitalInc/ObjectRemovalDetection
14ccff9792e2ab006377dc02b8260897465db988
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2021 InterDigital * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * License is avaiable on the root under license.txt and 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. */ #ifndef NOLIVIER #include "fastcd/mesh.h" #include <glow/ScopedBinder.h> void Mesh::initialize(const std::vector<Vertex>& verts, const std::vector<Triangle>& faces, const std::vector<Material>& materials) { if (verts.size() == 0) return; std::vector<Vertex> vertices = verts; if (std::abs(length(vertices[0].normal) - 1.0f) > 0.01) { // assume, no normals given: for (auto face : faces) { Eigen::Vector3f v0 = toEigen(vertices[face.vertices[0]].position); Eigen::Vector3f v1 = toEigen(vertices[face.vertices[1]].position); Eigen::Vector3f v2 = toEigen(vertices[face.vertices[2]].position); Eigen::Vector3f n = ((v1 - v0).cross(v2 - v0)).normalized(); for (uint32_t i = 0; i < 3; ++i) { vertices[face.vertices[i]].normal.x = n.x(); vertices[face.vertices[i]].normal.y = n.y(); vertices[face.vertices[i]].normal.z = n.z(); } } } std::vector<std::vector<uint32_t> > tris(std::max((int)materials.size(), 1)); for (uint32_t i = 0; i < faces.size(); ++i) { assert(faces[i].material < tris.size()); tris[faces[i].material].push_back(faces[i].vertices[0]); tris[faces[i].material].push_back(faces[i].vertices[1]); tris[faces[i].material].push_back(faces[i].vertices[2]); } // copying the data. vertices_.assign(vertices); for (uint32_t i = 0; i < reordered_tris.size(); ++i) { glow::GlBuffer<uint32_t> buf(glow::BufferTarget::ELEMENT_ARRAY_BUFFER, glow::BufferUsage::STATIC_DRAW); buf.assign(reordered_tris[i]); triangles_.push_back(buf); } // setting the vaos. for (uint32_t i = 0; i < reordered_tris.size(); ++i) { vaos_.push_back(glow::GlVertexArray()); vaos_[i].bind(); vaos_[i].setVertexAttribute(0, vertices_, 4, glow::AttributeType::FLOAT, false, sizeof(Vertex), (GLvoid*)0); vaos_[i].setVertexAttribute(1, vertices_, 4, glow::AttributeType::FLOAT, false, sizeof(Vertex), (GLvoid*)offsetof(Vertex, normal)); vaos_[i].setVertexAttribute(2, vertices_, 2, glow::AttributeType::FLOAT, false, sizeof(Vertex), (GLvoid*)offsetof(Vertex, texture)); vaos_[i].enableVertexAttribute(0); vaos_[i].enableVertexAttribute(1); vaos_[i].enableVertexAttribute(2); triangles_[i].bind(); vaos_[i].release(); triangles_[i].release(); // release only afterwards CheckGlError(); } } void Mesh::saveObj(const std::string& filename) const { std::ofstream out(filename.c_str()); if (!out.is_open()) throw std::runtime_error("Failed to open obj-file."); for (auto vertex : vertices_) { out << 'v' << vertex.position; /*for (auto vertex : triangle.vertices) out << ' ' << vertex << '/' << vertex << '/' << vertex;*/ out << std::endl; } /*for (auto triangle : triangles_) { out << 'f'; for (auto vertex : triangle.vertices) out << ' ' << vertex << '/' << vertex << '/' << vertex; out << std::endl; } out << "# End of File" << std::flush; out.close(); }*/ #endif //NOLIVIER
34.935185
79
0.606149
[ "mesh", "vector" ]
5b4f8d9e7486ce1563b1b292d0c08ca136b306c3
17,010
cpp
C++
vts-libs/vts/nodeinfo.cpp
melowntech/vts-libs
ffbf889b6603a8f95d3c12a2602232ff9c5d2236
[ "BSD-2-Clause" ]
2
2020-04-20T01:44:46.000Z
2021-01-15T06:54:51.000Z
vts-libs/vts/nodeinfo.cpp
melowntech/vts-libs
ffbf889b6603a8f95d3c12a2602232ff9c5d2236
[ "BSD-2-Clause" ]
2
2020-01-29T16:30:49.000Z
2020-06-03T15:21:29.000Z
vts-libs/vts/nodeinfo.cpp
melowntech/vts-libs
ffbf889b6603a8f95d3c12a2602232ff9c5d2236
[ "BSD-2-Clause" ]
1
2019-09-25T05:10:07.000Z
2019-09-25T05:10:07.000Z
/** * Copyright (c) 2017 Melown Technologies SE * * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <algorithm> #include <boost/thread/tss.hpp> #include "dbglog/dbglog.hpp" #include "nodeinfo.hpp" #include "tileop.hpp" #include "csconvertor.hpp" namespace vtslibs { namespace vts { namespace { math::Extents2 makeExtents(const RFNode &rootNode, const RFNode::Id &nodeId) { // determine tile extents auto lid(local(rootNode.id.lod, nodeId)); auto tc(tileCount(lid.lod)); auto rs(size(rootNode.extents)); math::Size2f ts(rs.width / tc, rs.height / tc); return math::Extents2 (rootNode.extents.ll(0) + lid.x * ts.width , rootNode.extents.ur(1) - (lid.y + 1) * ts.height , rootNode.extents.ll(0) + (lid.x + 1) * ts.width , rootNode.extents.ur(1) - lid.y * ts.height); } RFNode makeNode(const RFNode &subtreeRoot , const TileId &tileId) { // clone root auto node(subtreeRoot); // set id node.id = tileId; // change extents for productive nodes only if (subtreeRoot.real()) { // set extents node.extents = makeExtents(subtreeRoot, tileId); } return node; } bool checkPartial(const RFTreeSubtree &subtree, RFNode &node , bool invalidateWhenMasked = true) { auto valid(subtree.valid(node)); if (valid) { return false; } else if (!valid && invalidateWhenMasked) { // masked node -> invalidate if allowed node.invalidate(); return false; } // indeterminate -> valid but partial return true; } const RFNode invalidNode(RFNode::Id(~Lod(0), 0, 0) , registry::PartitioningMode::none); const RFNode& findSubtreeRoot(const registry::ReferenceFrame &referenceFrame , const TileId &tileId) { const auto *node(referenceFrame.findSubtreeRoot(tileId, std::nothrow)); if (!node) { // cannot find root for this node -> return invalid node return invalidNode; } return *node; } } // namespace inline NodeInfo::NodeInfo(const registry::ReferenceFrame &referenceFrame , const RFNode &node , const registry::Registry &reg) : referenceFrame_(&referenceFrame) , subtree_(node, reg), node_(node) , partial_(checkPartial(subtree_, node_)) {} NodeInfo::NodeInfo(const registry::ReferenceFrame &referenceFrame , const TileId &tileId, bool invalidateWhenMasked , const registry::Registry &reg) : referenceFrame_(&referenceFrame) , subtree_(findSubtreeRoot(*referenceFrame_, tileId), reg) , node_(makeNode(subtree_.root(), tileId)) , partial_(checkPartial(subtree_, node_, invalidateWhenMasked)) {} NodeInfo::list NodeInfo::nodes(const registry::ReferenceFrame &referenceFrame , const registry::Registry &reg) { NodeInfo::list nodes; for (const auto &item : referenceFrame.division.nodes) { if (item.second.real()) { nodes.push_back(NodeInfo(referenceFrame, item.second, reg)); } } return nodes; } NodeInfo::list NodeInfo::leaves(const registry::ReferenceFrame &referenceFrame , const registry::Registry &reg) { NodeInfo::list nodes; for (const auto &item : referenceFrame.division.nodes) { if (!item.second.real() || item.second.structure.children) { // not real node nor leaf continue; } nodes.push_back(NodeInfo(referenceFrame, item.second, reg)); } return nodes; } NodeInfo NodeInfo::child(Child childDef) const { if (!node_.valid()) { LOGTHROW(err2, storage::Error) << "Node " << node_.id << " has no children."; } // build child id from this node and index RFNode::Id childId(node_.id); ++childId.lod; childId.x <<= 1; childId.y <<= 1; switch (childDef.index) { case 0: // upper-left break; case 1: // upper-right ++childId.x; break; case 2: // lower-left ++childId.y; break; case 3: // lower-right ++childId.x; ++childId.y; break; default: LOGTHROW(err2, storage::Error) << "Invalid child number (" << childDef.index << ")."; break; } // check for child validity if ((childId.lod != childDef.lod) || (childId.x != childDef.x) || (childId.y != childDef.y)) { LOGTHROW(err2, storage::Error) << "Node " << childId << " is not a child of " << node_.id << "."; } if (node_.structure.children) { // manual or barren node -> check for validity if (node_.structure.children & (1 << childDef.index)) { // yes, path exists, replace return { *referenceFrame_, referenceFrame_->find(childId) , subtree_.registry() }; } // non-existent node -> invalid return { *referenceFrame_ , RFNode(childId, registry::PartitioningMode::none) , subtree_.registry()}; } // divide current node's extents in half in both directions NodeInfo child(*this); child.node_.id = childId; // size of extents auto es(size(node_.extents)); // and halve it es.width /= 2.0; es.height /= 2.0; // no need to check childNum since it was checked above auto &extents(child.node_.extents); switch (childDef.index) { case 0: // upper-left extents.ur(0) -= es.width; extents.ll(1) += es.height; break; case 1: // upper-right extents.ll(0) += es.width; extents.ll(1) += es.height; break; case 2: // lower-left extents.ur(0) -= es.width; extents.ur(1) -= es.height; break; case 3: // lower-right extents.ll(0) += es.width; extents.ur(1) -= es.height; break; } // partiality is inherited from parent -> only partial node needs to be // re-checked if (child.partial_) { child.partial_ = checkPartial(child.subtree_, child.node_); } // done return child; } NodeInfo NodeInfo::child(const TileId &childId) const { NodeInfo child(*this); child.node_.id = childId; child.node_.extents = makeExtents(node_, childId); // partiality is inherited from parent -> only partial node needs to be // re-checked if (child.partial_) { child.partial_ = checkPartial(child.subtree_, child.node_); } return child; } class RFTreeSubtree::Sampler : boost::noncopyable { public: Sampler(const RFNode &root, const registry::Registry &reg) : root_(root), reg_(reg), extents_(root.constraints->extents) {} class ThreadLocal { public: ThreadLocal(const CsConvertor &conv , const math::Extents2 &extents) : conv_(conv), extents_(extents) {} math::Point2 sample(const math::Point2 &p) const { return conv_(p); } bool inside(const math::Point2 &p) const { return math::inside(extents_, sample(p)); } private: const CsConvertor &conv_; const math::Extents2 &extents_; }; math::Point2 sample(const math::Point2 &p) const { return conv()(p); } bool inside(const math::Point2 &p) const { return math::inside(extents_, sample(p)); } ThreadLocal get() const { return ThreadLocal(conv(), extents_); }; private: const CsConvertor& conv() const { if (!conv_.get()) { conv_.reset(new CsConvertor (root_.srs, root_.constraints->extentsSrs, reg_)); } return *conv_; } const RFNode &root_; const registry::Registry &reg_; mutable boost::thread_specific_ptr<CsConvertor> conv_; math::Extents2 extents_; }; bool RFTreeSubtree::initSampler() const { if (!root_->constraints) { return false; } if (!sampler_) { sampler_ = std::make_shared<Sampler>(*root_, *registry_); } return true; } boost::tribool RFTreeSubtree::valid(const RFNode &node) const { // try to init sampler if (!initSampler()) { // sampler cannot be initialized because there are no extra constraints if (!root_->valid()) { // invalid node -> invalid return false; } if (!root_->real()) { // not a real node, we have no idea... return boost::indeterminate; } // valid return true; } class Checker { public: Checker(const Sampler::ThreadLocal &sampler) : sampler_(sampler), inside_(false), outside_(false) {} bool operator()(const math::Point2 &p) { if (sampler_.inside(p)) { inside_ = true; } else { outside_ = true; } return (inside_ && outside_); } boost::tribool result() const { // both inside and outside -> indeterminate if (inside_ && outside_) { return boost::indeterminate; } if (inside_) { return true; } return false; } private: Sampler::ThreadLocal sampler_; bool inside_; bool outside_; }; Checker check(sampler_->get()); // check tile corners first if (check(ll(node.extents)) || check(ur(node.extents)) || check(ul(node.extents)) || check(lr(node.extents))) { return check.result(); } // calculate center of tile auto c(math::center(node.extents)); // check center of tile if (check(c)) { return check.result(); } // check centers of tile borders if (check({ node.extents.ll(0), c(1) }) // left border || check({ node.extents.ur(0), c(1) }) // right border || check({ c(0), node.extents.ll(1) } ) // bottom border || check({ c(0), node.extents.ur(1) } )) // top border { return check.result(); } // done return check.result(); } bool RFTreeSubtree::inside(const math::Point2 &point) const { // try to init sampler; if sampler cannot be initialized, we are fully // inside if (!initSampler()) { return true; } return sampler_->inside(point); } NodeInfo::CoverageMask NodeInfo::coverageMask(CoverageType type, const math::Size2 &size , unsigned int dilation) const { if (!valid()) { return CoverageMask(size, CoverageMask::InitMode::EMPTY); } if (!partial_) { return CoverageMask(size, CoverageMask::InitMode::FULL); } return subtree_.coverageMask(type, size, dilation, node_); } RFTreeSubtree::CoverageMask RFTreeSubtree::coverageMask(CoverageType type, const math::Size2 &size , int dilation, const RFNode &node) const { if (!initSampler()) { // no sampler -> no constraints -> full mask return CoverageMask(size, CoverageMask::InitMode::FULL); } // extents to process const auto grid([&]() -> math::Extents2 { // grid coordinates: leave extents if (type == CoverageType::grid) { return node.extents; } // pixel coordinates: move one half pixel inside auto grid(node.extents); auto s(math::size(node.extents)); math::Size2f hps(s.width / (2.0 * size.width) , s.height / (2.0 * size.height)); grid.ll(0) += hps.width; grid.ll(1) += hps.height; grid.ur(0) -= hps.width; grid.ur(1) -= hps.height; return grid; }()); // get grid size and calculate pixel size (i.e. step) const auto gs(math::size(grid)); math::Size2f ps(gs.width / (size.width - 1) , gs.height / (size.height - 1)); const auto ref(ul(grid)); // NB: we cannot use OpenCV here, this is core lib functionality std::vector<std::uint8_t> pane(area(size), false); auto clip([](int v, int limit) -> int { if (v < 0) { return 0; } if (v > limit) { return limit; } return v; }); // sample tile in grid const auto &sampler(*sampler_); for (int j(-dilation), je(size.height + dilation), gp(0); j < je; ++j) { double y(ref(1) - j * ps.height); for (int i(-dilation), ie(size.width + dilation); i < ie; ++i, ++gp) { double x(ref(0) + i * ps.width); if (sampler.inside(math::Point2(x, y))) { if (!dilation) { pane[gp] = true; } // some dilation -> apply for (int jj(clip(j - dilation, size.height - 1)) , jje(clip(j + dilation, size.height - 1)) , gy(jj * size.width); jj <= jje; ++jj, gy += size.width) { for (int ii(clip(i - dilation, size.width - 1)) , iie(clip(i + dilation, size.width - 1)); ii <= iie; ++ii) { pane[gy + ii] = true; } } } } } CoverageMask mask(size, CoverageMask::InitMode::EMPTY); for (int j(0), gp(0); j < size.height; ++j) { for (int i(0); i < size.width; ++i, ++gp) { if (pane[gp]) { mask.set(i, j, true); } } } return mask; } bool NodeInfo::inside(const math::Point2 &point) const { // outside -> not inside if (!math::inside(node_.extents, point)) { return false; } // inside and not partial -> inside if (!partial_) { return true; } // OK, check // check for validty return subtree_.inside(point); } const geo::SrsDefinition& NodeInfo::srsDef() const { return subtree_.registry().srs(node_.srs).srsDef; } NodeInfo::CoveredArea NodeInfo::checkMask(const CoverageMask &mask , CoverageType type , unsigned int dilation) const { if (mask.empty() || !valid()) { // nothing at all return CoveredArea::none; } // full node -> result is based on mask content if (!partial()) { return mask.full() ? CoveredArea::whole : CoveredArea::some; } // partial node: subtract mask from node's mask; if anything is left then // mask doesn't cover all pixels in node valid area and therefore coverage // is partial; otherwise we have full coverage, i.e. watertight file // generate node mask auto nm(coverageMask(type, mask.size(), dilation)); auto total(nm.count()); // subtract provide mask from node mask nm.subtract(mask); // empty resukt -> all valid pixels in node are also valid in mask -> whole // valid are is covered if (nm.empty()) { return CoveredArea::whole; } // some pixels are left if (nm.count() == total) { // nothing in node's mask is in the mask -> nothing covered return CoveredArea::none; } // something in the mask covers valid node mask -> there is something return CoveredArea::some; } #ifdef GEO_HAS_GDAL registry::Srs NodeInfo::navsds() const { const auto &reg(subtree_.registry()); // clone navigation system (with all info) auto srs(reg.srs(referenceFrame_->model.navigationSrs)); // update its SRS by merging node's horizontal system with navigation // vertical system srs.srsDef = geo::merge(reg.srs(node_.srs).srsDef, srs.srsDef); return srs; } #endif // GEO_HAS_GDAL } } // namespace vtslibs::vts
29.176672
79
0.582951
[ "vector", "model" ]
5b52e0982aa778c6da3dae40eca2230ab4361eba
955
hpp
C++
FRST/WorkForce/include/WorkForce/Job.hpp
SamDeakin/FRST
3b0499e6b5899e46b61ec4bb9ce6806b39fc2b33
[ "MIT" ]
null
null
null
FRST/WorkForce/include/WorkForce/Job.hpp
SamDeakin/FRST
3b0499e6b5899e46b61ec4bb9ce6806b39fc2b33
[ "MIT" ]
null
null
null
FRST/WorkForce/include/WorkForce/Job.hpp
SamDeakin/FRST
3b0499e6b5899e46b61ec4bb9ce6806b39fc2b33
[ "MIT" ]
null
null
null
#pragma once #include "WorkForce/JobResult.hpp" #include <string> #include <vector> namespace FRST { namespace WorkForce { class Job { public: /** * A Job is an action that is called once per-frame. */ Job(); ~Job(); /** * The api used for job ordering. * It will be ensured that every result asked for by consumes() will be passed into * execute(), and every result declared by produces() MUST be returned by execute. * * This will only be called once, at job queue time. They should not be dependent upon previous frame data. */ virtual const std::vector<const std::string>* produces() const = 0; virtual const std::vector<const std::string>* consumes() const = 0; /** * The work that will be performed per-frame. * inputs: An array of inputs of the same length and order as returned from consumes() */ virtual const JobResult* execute(const JobResult* inputs) = 0; }; } }
27.285714
110
0.662827
[ "vector" ]
5b56ace0821c0e347b29a38e9556b83f9d2cc3d5
16,974
cpp
C++
3es-core/shapes/3esmeshshape.cpp
data61/3es-core
597f25aa604cb446dcc1f08b9d3bc8f89f3043b9
[ "Zlib" ]
2
2020-06-11T04:16:08.000Z
2020-06-20T19:57:10.000Z
3es-core/shapes/3esmeshshape.cpp
csiro-robotics/3es-core
597f25aa604cb446dcc1f08b9d3bc8f89f3043b9
[ "Zlib" ]
null
null
null
3es-core/shapes/3esmeshshape.cpp
csiro-robotics/3es-core
597f25aa604cb446dcc1f08b9d3bc8f89f3043b9
[ "Zlib" ]
null
null
null
// // author: Kazys Stepanas // #include "3esmeshshape.h" #include "3esmeshresource.h" #include "3esmeshset.h" #include <3escoreutil.h> #include <3espacketwriter.h> #include <algorithm> using namespace tes; namespace { // Helper for automating data sending. struct DataPhase { // The SendDataType. uint16_t type; // Number of things to send. May be zero. unsigned itemCount; // Data pointer. May be null with zero itemCount. const uint8_t *dataSrc; // Byte stride between elements. size_t dataStrideBytes; // Base data item size, requiring endian swap. // See tupleSize. size_t dataSizeByte; // Number of data items in each stride. tupleSize * dataSizeBytes must be <= dataStrideBytes. // // Usage by example. // For a Vector3 data type of 3 packed floats: // - tupleSize = 3 // - dataSizeBytes = sizeof(float) // - dataStrideBytes = tupleSize * dataSizeBytes = 12 // // For a Vector3 data type aligned to 16 bytes (3 floats): // - tupleSize = 3 // - dataSizeBytes = sizeof(float) // - dataStrideBytes = 16 unsigned tupleSize; }; unsigned readElements(PacketReader &stream, unsigned offset, unsigned itemCount, uint8_t *dstPtr, size_t elementSizeBytes, unsigned elementCount, unsigned tupleSize = 1) { if (offset > elementCount) { return ~0u; } if (itemCount == 0) { return offset + itemCount; } if (offset + itemCount > elementCount) { itemCount = elementCount - itemCount; } offset *= tupleSize; itemCount *= tupleSize; uint8_t *dst = const_cast<uint8_t *>(dstPtr); dst += offset * elementSizeBytes; size_t readCount = stream.readArray(dst, elementSizeBytes, itemCount); if (readCount != itemCount) { return ~0u; } return unsigned((readCount + offset) / tupleSize); } } // namespace MeshShape::~MeshShape() { releaseArrays(); } MeshShape &MeshShape::setNormals(const float *normals, size_t normalByteSize) { if (_ownNormals) { delete[] _normals; } _ownNormals = false; _normals = normals; _normalsStride = unsigned(normalByteSize / sizeof(*_normals)); _normalsCount = _normals ? _vertexCount : 0; if (_ownPointers) { // Pointers are owned. Need to copy the normals. float *newNormals = nullptr; _normalsStride = 3; if (_normalsCount) { newNormals = new float[3 * _normalsCount]; if (normalByteSize == sizeof(*_normals) * _normalsStride) { memcpy(newNormals, normals, normalByteSize * _normalsCount); } else { const size_t elementStride = normalByteSize / sizeof(*normals); for (size_t i = 0; i < _normalsCount; ++i) { newNormals[i * 3 + 0] = normals[0]; newNormals[i * 3 + 1] = normals[1]; newNormals[i * 3 + 2] = normals[2]; normals += elementStride; } } } _normals = newNormals; _ownNormals = true; setCalculateNormals(false); } return *this; } MeshShape &MeshShape::setUniformNormal(const Vector3f &normal) { if (_ownNormals) { delete[] _normals; } float *normals = new float[3 * 1]; _normalsCount = 1; _normals = normals; _ownNormals = true; normals[0] = normal[0]; normals[1] = normal[1]; normals[2] = normal[2]; setCalculateNormals(false); return *this; } MeshShape &MeshShape::setColours(const uint32_t *colours) { setColourByHeight(false); if (_ownPointers) { if (colours) { if (vertexCount()) { delete _colours; uint32_t *newColours = new uint32_t[vertexCount()]; _colours = newColours; memcpy(newColours, colours, sizeof(*colours) * vertexCount()); } } else { delete _colours; _colours = nullptr; } } else { _colours = colours; } return *this; } MeshShape &MeshShape::expandVertices() { if (!_indices && !_indexCount) { return duplicateArrays(); } // We unpack all vertices and stop indexing. float *verts = new float[3 * _indexCount]; float *dst = verts; for (unsigned i = 0; i < _indexCount; ++i) { *dst++ = _vertices[_indices[i] * _vertexStride + 0]; *dst++ = _vertices[_indices[i] * _vertexStride + 1]; *dst++ = _vertices[_indices[i] * _vertexStride + 2]; } float *normals = nullptr; if (_normals && _normalsCount == _vertexCount) { normals = new float[3 * _indexCount]; dst = normals; for (unsigned i = 0; i < _indexCount; ++i) { *dst++ = _normals[_indices[i] * _normalsStride + 0]; *dst++ = _normals[_indices[i] * _normalsStride + 1]; *dst++ = _normals[_indices[i] * _normalsStride + 2]; } } uint32_t *colours = nullptr; if (_colours) { colours = new uint32_t[_indexCount]; uint32_t *dst = colours; for (unsigned i = 0; i < _indexCount; ++i) { *dst++ = _colours[_indices[i]]; } } releaseArrays(); _vertices = verts; _vertexCount = _indexCount; _vertexStride = 3; _normals = normals; _normalsCount = (_normals) ? _indexCount : 0; _normalsStride = 3; _colours = colours; _indices = nullptr; _indexCount = 0; _ownPointers = true; _ownNormals = normals != nullptr; return *this; } MeshShape &MeshShape::duplicateArrays() { if (!_ownPointers) { float *vertices = nullptr; unsigned *indices = nullptr; uint32_t *colours = nullptr; if (_vertexCount) { vertices = new float[3 * _vertexCount]; if (_vertexStride == 3) { memcpy(vertices, _vertices, sizeof(*vertices) * 3 * _vertexCount); } else { float *dst = vertices; const float *src = _vertices; for (unsigned i = 0; i < _vertexCount; ++i, dst += 3, src += _vertexStride) { dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; } } } if (_indices && _indexCount) { indices = new uint32_t[_indexCount]; memcpy(indices, _indices, sizeof(*indices) * _indexCount); } if (_colours && _vertexStride) { colours = new uint32_t[_vertexCount]; memcpy(colours, _colours, sizeof(*colours) * _vertexCount); } _vertices = vertices; _vertexStride = 3; _indices = indices; _colours = colours; _ownPointers = true; } if (!_ownNormals && _normals) { float *normals = nullptr; if (_normalsCount) { normals = new float[3 * _normalsCount]; if (_vertexStride == 3) { memcpy(normals, _normals, sizeof(*normals) * 3 * _normalsCount); } else { float *dst = normals; const float *src = _normals; for (unsigned i = 0; i < _normalsCount; ++i, dst += 3, src += _vertexStride) { dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; } } } _normals = normals; _normalsStride = 3; _ownNormals = true; } return *this; } bool MeshShape::writeCreate(PacketWriter &stream) const { bool ok = Shape::writeCreate(stream); uint32_t count = _vertexCount; ok = stream.writeElement(count) == sizeof(count) && ok; count = _indexCount; ok = stream.writeElement(count) == sizeof(count) && ok; uint8_t drawType = _drawType; ok = stream.writeElement(drawType) == sizeof(drawType) && ok; ok = stream.writeElement(_drawScale) == sizeof(_drawScale) && ok; return ok; } int MeshShape::writeData(PacketWriter &stream, unsigned &progressMarker) const { bool ok = true; DataMessage msg; // Local byte overhead needs to account for the size of sendType, offset and itemCount. // Use a larger value as I haven't got the edge cases quite right yet. const size_t localByteOverhead = 100; msg.id = _data.id; stream.reset(routingId(), DataMessage::MessageId); ok = msg.write(stream); // Send vertices or indices? uint32_t offset; uint32_t itemCount; uint16_t sendType; // Resolve what we are currently sending. unsigned phaseIndex = 0; unsigned previousPhaseOffset = 0; // Order to send data in and information required to automate sending. const uint16_t normalsSendType = (_normalsCount == 1) ? SDT_UniformNormal : SDT_Normals; const DataPhase phases[] = { { normalsSendType, _normalsCount, (const uint8_t *)_normals, _normalsStride * sizeof(*_normals), sizeof(*_normals), 3 }, { SDT_Colours, (_colours) ? _vertexCount : 0, (const uint8_t *)_colours, sizeof(*_colours), sizeof(*_colours), 1 }, { SDT_Vertices, _vertexCount, (const uint8_t *)_vertices, _vertexStride * sizeof(*_vertices), sizeof(*_vertices), 3 }, { SDT_Indices, _indexCount, (const uint8_t *)_indices, sizeof(*_indices), sizeof(*_indices), 1 } }; // While progressMarker is greater than or equal to the sum of the previous phase counts and the current phase count. // Also terminate of out of phases. while (phaseIndex < sizeof(phases) / sizeof(phases[0]) && progressMarker >= previousPhaseOffset + phases[phaseIndex].itemCount) { previousPhaseOffset += phases[phaseIndex].itemCount; ++phaseIndex; } bool done = false; // Check if we have anything to send. if (phaseIndex < sizeof(phases) / sizeof(phases[0])) { const DataPhase &phase = phases[phaseIndex]; // Send part of current phase. const unsigned maxItemCout = MeshResource::estimateTransferCount(phase.dataSizeByte * phase.tupleSize, 0, sizeof(DataMessage) + localByteOverhead); offset = progressMarker - previousPhaseOffset; itemCount = uint32_t(std::min<uint32_t>(phase.itemCount - offset, maxItemCout)); sendType = phase.type | SDT_ExpectEnd; ok = stream.writeElement(sendType) == sizeof(sendType) && ok; ok = stream.writeElement(offset) == sizeof(offset) && ok; ok = stream.writeElement(itemCount) == sizeof(itemCount) && ok; const uint8_t *src = phase.dataSrc + offset * phase.dataStrideBytes; if (phase.dataStrideBytes == phase.dataSizeByte * phase.tupleSize) { ok = stream.writeArray(src, phase.dataSizeByte, itemCount * phase.tupleSize) == itemCount * phase.tupleSize && ok; } else { for (unsigned i = 0; i < itemCount; ++i, src += phase.dataStrideBytes) { ok = stream.writeArray(src, phase.dataSizeByte, phase.tupleSize) == phase.tupleSize && ok; } } progressMarker += itemCount; } else { // Either all done or no data to send. // In the latter case, we need to populate the message anyway. offset = itemCount = 0; sendType = SDT_ExpectEnd | SDT_End; ok = stream.writeElement(sendType) == sizeof(sendType) && ok; ok = stream.writeElement(offset) == sizeof(offset) && ok; ok = stream.writeElement(itemCount) == sizeof(itemCount) && ok; done = true; } if (!ok) { return -1; } // Return 1 while there is more data to process. return (!done) ? 1 : 0; } bool MeshShape::readCreate(PacketReader &stream) { if (!Shape::readCreate(stream)) { return false; } uint32_t vertexCount = 0; uint32_t indexCount = 0; uint8_t drawType = 0; bool ok = true; ok = ok && stream.readElement(vertexCount) == sizeof(vertexCount); ok = ok && stream.readElement(indexCount) == sizeof(indexCount); if (ok) { if (!_ownPointers) { _vertices = nullptr; _indices = nullptr; _colours = nullptr; _vertexCount = _indexCount = 0; } _ownPointers = true; if (_vertexCount < vertexCount || _vertexStride != 3) { delete[] _vertices; _vertices = new float[3 * vertexCount]; _vertexStride = 3; } if (_indexCount < indexCount) { delete[] _indices; _indices = new unsigned[indexCount]; } _vertexCount = vertexCount; _indexCount = indexCount; } if (_ownNormals) { delete[] _normals; } // Normals may or may not come. We find out in writeData(). // _normalCount will either be 1 (uniform normals) or match _vertexCount. // Depends on SendDataType in readData() _normals = nullptr; _normalsCount = 0; _ownNormals = false; ok = ok && stream.readElement(drawType) == sizeof(drawType); _drawType = (DrawType)drawType; // Legacy support. if (stream.versionMajor() > 0 || stream.versionMajor() == 0 && stream.versionMinor() >= 2) { ok = ok && stream.readElement(_drawScale) == sizeof(_drawScale); } else { _drawScale = 0.0f; } return ok; } bool MeshShape::readData(PacketReader &stream) { DataMessage msg; uint32_t offset = 0; uint32_t itemCount = 0; uint16_t dataType = 0; bool ok = true; ok = ok && msg.read(stream); ok = ok && stream.readElement(dataType) == sizeof(dataType); ok = ok && stream.readElement(offset) == sizeof(offset); ok = ok && stream.readElement(itemCount) == sizeof(itemCount); // Record and mask out end flags. uint16_t endFlags = (dataType & (SDT_ExpectEnd | SDT_End)); dataType = uint16_t(dataType & ~endFlags); // Can only read if we own the pointers. if (!_ownPointers) { return false; } // FIXME: resolve the 'const' pointer casting. Reading was a retrofit. bool complete = false; unsigned endReadCount = 0; switch (dataType) { case SDT_Vertices: endReadCount = readElements(stream, offset, itemCount, (uint8_t *)_vertices, sizeof(*_vertices), _vertexCount, 3); ok = ok && endReadCount != ~0u; // Expect end marker. if (endFlags & SDT_End) { // Done. complete = true; } // Check for completion. if (!(endFlags & SDT_ExpectEnd)) { complete = endReadCount == _vertexCount; } break; case SDT_Indices: endReadCount = readElements(stream, offset, itemCount, (uint8_t *)_indices, sizeof(*_indices), _indexCount); ok = ok && endReadCount != ~0u; break; // Normals handled together. case SDT_Normals: case SDT_UniformNormal: if (!_normals) { _normalsCount = (dataType == SDT_Normals) ? _vertexCount : 1; _normalsStride = 3; if (_normalsCount) { _normals = new float[3 * _normalsCount]; _ownNormals = true; } } endReadCount = readElements(stream, offset, itemCount, (uint8_t *)_normals, sizeof(*_normals), _normalsCount, 3); ok = ok && endReadCount != ~0u; break; case SDT_Colours: if (!_colours && _vertexCount) { _colours = new uint32_t[_vertexCount]; } endReadCount = readElements(stream, offset, itemCount, (uint8_t *)_colours, sizeof(*_colours), _vertexCount); ok = ok && endReadCount != ~0u; break; default: // Unknown data type. ok = false; break; } if (complete) { // Nothing in the test code. } return ok; } Shape *MeshShape::clone() const { MeshShape *triangles = new MeshShape(); onClone(triangles); triangles->_data = _data; return triangles; } void MeshShape::onClone(MeshShape *copy) const { Shape::onClone(copy); copy->_vertices = nullptr; copy->_indices = nullptr; copy->_normals = nullptr; copy->_colours = nullptr; copy->_vertexCount = _vertexCount; copy->_normalsCount = _normalsCount; copy->_indexCount = _indexCount; copy->_vertexStride = 3; copy->_normalsStride = 3; copy->_drawType = _drawType; copy->_ownPointers = true; copy->_ownNormals = true; if (_vertexCount) { float *vertices = new float[3 * _vertexCount]; if (_vertexStride == 3) { memcpy(vertices, _vertices, sizeof(*vertices) * _vertexCount * 3); } else { const float *src = _vertices; float *dst = vertices; for (unsigned i = 0; i < _vertexCount; ++i) { dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; src += _vertexStride; dst += 3; } } copy->_vertices = vertices; } if (_indexCount) { unsigned *indices = new unsigned[_indexCount]; memcpy(indices, _indices, sizeof(*indices) * _indexCount); copy->_indices = indices; } if (_normalsCount) { float *normals = new float[3 * _normalsCount]; if (_normalsStride == 3) { memcpy(normals, _normals, sizeof(*normals) * _normalsCount * 3); } else { const float *src = _normals; float *dst = normals; for (unsigned i = 0; i < _normalsCount; ++i) { dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; src += _normalsStride; dst += 3; } } copy->_normals = normals; } if (_colours && _vertexCount) { uint32_t *colours = new uint32_t[_vertexCount]; memcpy(colours, _colours, sizeof(*_colours) * _vertexCount); copy->_colours = colours; } } void MeshShape::releaseArrays() { if (_ownNormals) { delete[] _normals; _normals = nullptr; } if (_ownPointers) { delete[] _vertices; _vertices = nullptr; delete[] _indices; _indices = nullptr; delete[] _colours; _colours = nullptr; } }
24.387931
120
0.626193
[ "shape" ]
5b5bfb266d71effa6ddd66e5020210e33a11a8a6
1,184
cpp
C++
Problem 1.cpp
abhishekezzy/Favourite-Interview-Problems
0a94e7fd9278b6728be41cd92a4f0ba70409740e
[ "MIT" ]
null
null
null
Problem 1.cpp
abhishekezzy/Favourite-Interview-Problems
0a94e7fd9278b6728be41cd92a4f0ba70409740e
[ "MIT" ]
null
null
null
Problem 1.cpp
abhishekezzy/Favourite-Interview-Problems
0a94e7fd9278b6728be41cd92a4f0ba70409740e
[ "MIT" ]
null
null
null
/* The below algorithm is a modification of Boyer–Moore majority vote algorithm Start with two empty candidate slots and two counters set to 0. for each item: if it is equal to either candidate, increment the corresponding count else if there is an empty slot (i.e. a slot with count 0), put it in that slot and set the count to 1 else reduce both counters by 1 At the end, make a second pass over the array to check whether the candidates really do have the required count. */ int Solution::repeatedNumber(const vector<int> &A) { int c1 = 0, c2 = 0; int a, b, n = A.size(); for(int i: A) { if(i != b && (c1 == 0 || i == a) ) { c1++; a = i; } else if(i != a && (c2 == 0 || i == b) ) { c2++; b = i; } else { c1--; c2--; } } c1 = 0, c2 = 0; for(int i: A) { if(i == a) c1++; else if(i == b) c2++; } if(c1 > n/3) return a; else if(c2 > n/3) return b; else return -1; }
24.163265
113
0.464527
[ "vector" ]
5b5f14c97c7cda00afbd893fec749b10df978c29
5,355
cxx
C++
PWGCF/FEMTOSCOPY/AliFemtoUser/AliFemtoCorrFctn3DPRF.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
114
2017-03-03T09:12:23.000Z
2022-03-03T20:29:42.000Z
PWGCF/FEMTOSCOPY/AliFemtoUser/AliFemtoCorrFctn3DPRF.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
19,637
2017-01-16T12:34:41.000Z
2022-03-31T22:02:40.000Z
PWGCF/FEMTOSCOPY/AliFemtoUser/AliFemtoCorrFctn3DPRF.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
1,021
2016-07-14T22:41:16.000Z
2022-03-31T05:15:51.000Z
/////////////////////////////////////////////////////////////////////////// // // // AliFemtoCorrFctn3DPRF: a class to calculate 3D correlation // // for pairs of particles. // // In analysis the function should be first created in a macro, then // // added to the analysis, and at the end of the macro the procedure to // // write out histograms should be called. // // // /////////////////////////////////////////////////////////////////////////// #include "AliFemtoCorrFctn3DPRF.h" #include <cstdio> #ifdef __ROOT__ ClassImp(AliFemtoCorrFctn3DPRF) #endif //____________________________ AliFemtoCorrFctn3DPRF::AliFemtoCorrFctn3DPRF(const char* title, const int& nbins, const float& QHi) : AliFemtoCorrFctn(), fNumerator(0), fDenominator(0), fNumeratorW(0), fDenominatorW(0) { // Basic constructor // set up numerator char tTitNum[101] = "Num"; strncat(tTitNum,title, 100); fNumerator = new TH3F(tTitNum,title,nbins,-QHi,QHi,nbins,-QHi,QHi,nbins,-QHi,QHi); // set up denominator char tTitDen[101] = "Den"; strncat(tTitDen,title, 100); fDenominator = new TH3F(tTitDen,title,nbins,-QHi,QHi,nbins,-QHi,QHi,nbins,-QHi,QHi); //Weighted by qinv histos // set up numerator char tTitNumW[101] = "NumWqinv"; strncat(tTitNumW,title, 100); fNumeratorW = new TH3F(tTitNumW,title,nbins,-QHi,QHi,nbins,-QHi,QHi,nbins,-QHi,QHi); // set up denominator char tTitDenW[101] = "DenWqinv"; strncat(tTitDenW,title, 100); fDenominatorW = new TH3F(tTitDenW,title,nbins,-QHi,QHi,nbins,-QHi,QHi,nbins,-QHi,QHi); // to enable error bar calculation... fNumerator->Sumw2(); fDenominator->Sumw2(); fNumeratorW->Sumw2(); fDenominatorW->Sumw2(); } AliFemtoCorrFctn3DPRF::AliFemtoCorrFctn3DPRF(const AliFemtoCorrFctn3DPRF& aCorrFctn) : AliFemtoCorrFctn(aCorrFctn), fNumerator(0), fDenominator(0), fNumeratorW(0), fDenominatorW(0) { // Copy constructor fNumerator = new TH3F(*aCorrFctn.fNumerator); fDenominator = new TH3F(*aCorrFctn.fDenominator); fNumeratorW = new TH3F(*aCorrFctn.fNumeratorW); fDenominatorW = new TH3F(*aCorrFctn.fDenominatorW); } //____________________________ AliFemtoCorrFctn3DPRF::~AliFemtoCorrFctn3DPRF(){ // Destructor delete fNumerator; delete fDenominator; delete fNumeratorW; delete fDenominatorW; } //_________________________ AliFemtoCorrFctn3DPRF& AliFemtoCorrFctn3DPRF::operator=(const AliFemtoCorrFctn3DPRF& aCorrFctn) { // assignment operator if (this == &aCorrFctn) return *this; if (fNumerator) delete fNumerator; fNumerator = new TH3F(*aCorrFctn.fNumerator); if (fDenominator) delete fDenominator; fDenominator = new TH3F(*aCorrFctn.fDenominator); if (fNumeratorW) delete fNumeratorW; fNumeratorW = new TH3F(*aCorrFctn.fNumeratorW); if (fDenominatorW) delete fDenominatorW; fDenominatorW = new TH3F(*aCorrFctn.fDenominatorW); return *this; } //_________________________ void AliFemtoCorrFctn3DPRF::WriteOutHistos(){ // Write out all histograms to file fNumerator->Write(); fDenominator->Write(); //fNumeratorW->Write(); //fDenominatorW->Write(); } //______________________________ TList* AliFemtoCorrFctn3DPRF::GetOutputList() { // Prepare the list of objects to be written to the output TList *tOutputList = new TList(); tOutputList->Add(fNumerator); tOutputList->Add(fDenominator); //tOutputList->Add(fNumeratorW); //tOutputList->Add(fDenominatorW); return tOutputList; } //_________________________ void AliFemtoCorrFctn3DPRF::Finish(){ // here is where we should normalize, fit, etc... } //____________________________ AliFemtoString AliFemtoCorrFctn3DPRF::Report(){ // Construct the report string stemp = "PRF 3D Correlation Function Report:\n"; char ctemp[100]; snprintf(ctemp , 100, "Number of entries in numerator:\t%E\n",fNumerator->GetEntries()); stemp += ctemp; snprintf(ctemp , 100, "Number of entries in denominator:\t%E\n",fDenominator->GetEntries()); stemp += ctemp; if (fPairCut){ snprintf(ctemp , 100, "Here is the PairCut specific to this CorrFctn\n"); stemp += ctemp; stemp += fPairCut->Report(); } else{ snprintf(ctemp , 100, "No PairCut specific to this CorrFctn\n"); stemp += ctemp; } // AliFemtoString returnThis = stemp; return returnThis; } //____________________________ void AliFemtoCorrFctn3DPRF::AddRealPair( AliFemtoPair* pair){ // perform operations on real pairs if (fPairCut && !fPairCut->Pass(pair)) { return; } double kOut = (pair->KOut()); double kSide = (pair->KSide()); double kLong = (pair->KLong()); //double qqinv = (pair->QInv()); fNumerator->Fill(kOut,kSide,kLong); //fNumeratorW->Fill(qOut,qSide,qLong,qqinv); } //____________________________ void AliFemtoCorrFctn3DPRF::AddMixedPair( AliFemtoPair* pair){ // perform operations on mixed pairs if (fPairCut && !fPairCut->Pass(pair)) { return; } double kOut = (pair->KOut()); double kSide = (pair->KSide()); double kLong = (pair->KLong()); //double qqinv = (pair->QInv()); fDenominator->Fill(kOut,kSide,kLong,1.0); //fDenominatorW->Fill(qOut,qSide,qLong,qqqinv); }
29.585635
99
0.666853
[ "3d" ]
5b65e7899246896371aa925cb3f81c257024dac9
6,142
cc
C++
src/pairhmm/common_pairHMM.cc
ruoshuiwyl/biocpp
4cf0918b528f0268892be39bc5a02b0120821f7f
[ "MIT" ]
null
null
null
src/pairhmm/common_pairHMM.cc
ruoshuiwyl/biocpp
4cf0918b528f0268892be39bc5a02b0120821f7f
[ "MIT" ]
null
null
null
src/pairhmm/common_pairHMM.cc
ruoshuiwyl/biocpp
4cf0918b528f0268892be39bc5a02b0120821f7f
[ "MIT" ]
null
null
null
// // Created by ruoshui on 7/24/16. // #include "common_pairHMM.h" #include "../util/util.h" CommonPairHMM::CommonPairHMM(std::vector<std::vector<char>> &haplotypes, std::vector<Read> &reads): PairHMM(haplotypes, reads) { } void CommonPairHMM::Initialization() { PairHMM::Initialization(); kInitalConstant = ldexp(1, 1020); kLog10InitalConstant = log10(kInitalConstant); match_matrix_.resize(pad_max_read_length_ * pad_max_haplotype_length_, 0.0); insert_matrix_.resize(pad_max_read_length_ * pad_max_haplotype_length_, 0.0); delete_matrix_.resize(pad_max_read_length_ * pad_max_haplotype_length_, 0.0); } int CommonPairHMM::ComputeLikeliHood(std::vector<double> &result) { Initialization(); result.resize(reads_.size() * haplotypes_.size(), 0.0); for ( int i = 0; i < reads_.size(); ++i ) { std::vector<char> &read_bases = reads_[i].GetReadBases(); std::vector<char> &read_quals = reads_[i].GetReadBaseQualities(); std::vector<char> &read_insert_quals = reads_[i].GetReadInsertQualities(); std::vector<char> &read_delete_quals = reads_[i].GetReadDeleteQualities(); std::vector<char> &read_gcp_quals = reads_[i].GetReadGCPQualities(); PairHMM::prev_haplotype_bases_.clear(); QualToTransProb(read_insert_quals, read_delete_quals, read_gcp_quals); int next_haplotype_index = 0; for( int j = 0; j < haplotypes_.size(); ++j){ std::vector<char> &haplotype_bases = haplotypes_[j]; next_haplotype_index = prev_haplotype_bases_.empty() || prev_haplotype_bases_.size() != haplotype_bases.size() ? 0 : PairHMM::FoundNextHaplotypeIndex(prev_haplotype_bases_, haplotype_bases); double lk = subComputeReadLikelihoodGivenHaplotype(haplotype_bases, read_bases, read_quals, read_insert_quals, read_delete_quals, read_gcp_quals, next_haplotype_index); result[GetMatrixIndex(j, i, reads_.size())] = lk; prev_haplotype_bases_ = haplotypes_[j]; } } return result.size(); } void CommonPairHMM::QualToTransProb(const std::vector<char> &read_insert_quals, const std::vector<char> &read_delete_quals, const std::vector<char> &read_gcp_quals) { int read_length = read_insert_quals.size(); for( int i = 0; i != read_length; ++i ){ transition_[kMatchToMatch][i+1] = 1.0 - (Quality::ProbError(read_insert_quals[i]) + Quality::ProbError(read_delete_quals[i])); // transition_[kMatchToMatch][i+1] = 1.0 - pow(10.0, MathUtils::ApproximateLog10SumLog10(-0.1 *read_insert_quals[i], -0.1 * read_delete_quals[i] )); transition_[kMatchToInsert][i+1] = Quality::ProbError(read_insert_quals[i]); transition_[kMatchToDelete][i+1] = Quality::ProbError(read_delete_quals[i]); transition_[kIndelToMatch][i+1] = 1.0 - Quality::ProbError(read_gcp_quals[i]); transition_[kInsertToInsert][i+1]= Quality::ProbError(read_gcp_quals[i]); transition_[kDeleteToDelete][i+1]= Quality::ProbError(read_gcp_quals[i]); } } double CommonPairHMM::subComputeReadLikelihoodGivenHaplotype(const std::vector<char> &haplotype_bases, const std::vector<char> &read_bases, const std::vector<char> &read_quals, const std::vector<char> &read_insert_quals, const std::vector<char> &read_delete_quals, const std::vector<char> &read_gcp_quals, const int32_t hap_start_index) { for (int i = 0; i < read_bases.size(); ++i) { const char rbase = read_bases[i]; const char qual = read_quals[i]; for (int j = 0; j < haplotype_bases.size(); ++j) { const char hbase = haplotype_bases[j]; prior_[GetMatrixIndex(i + 1, j + 1)] = ( rbase == hbase || rbase == 'N' || hbase == 'N' ) ? Quality::Prob(qual) : Quality::ProbError(qual) / 3.0; } } pad_haplotype_length_ = haplotype_bases.size() + 1; if (prev_haplotype_bases_.empty() || prev_haplotype_bases_.size() != haplotype_bases.size()) { const double delete_initial_value = kInitalConstant/ haplotype_bases.size(); for (int i = 0; i < pad_haplotype_length_; ++i) { delete_matrix_[GetMatrixIndex(0, i)] = delete_initial_value; } } pad_read_length_ = read_bases.size() + 1; for (int i = 1; i < pad_read_length_; ++i) { for (int j = hap_start_index + 1; j < pad_haplotype_length_; ++j) { match_matrix_[GetMatrixIndex(i, j)] = prior_[GetMatrixIndex(i, j)] * ( match_matrix_[GetMatrixIndex(i-1,j-1)] * transition_[kMatchToMatch][i] + insert_matrix_[GetMatrixIndex(i-1, j-1)] * transition_[kIndelToMatch][i] + delete_matrix_[GetMatrixIndex(i-1, j-1)] * transition_[kIndelToMatch][i] ); insert_matrix_[GetMatrixIndex(i, j)] = ( match_matrix_[GetMatrixIndex(i-1, j)] * transition_[kMatchToInsert][i] + insert_matrix_[GetMatrixIndex(i-1,j)] * transition_[kInsertToInsert][i] ); delete_matrix_[GetMatrixIndex(i, j)] = ( match_matrix_[GetMatrixIndex(i, j-1)] * transition_[kMatchToDelete][i], delete_matrix_[GetMatrixIndex(i, j-1)] * transition_[kDeleteToDelete][i] ); } } const int32_t endI = pad_read_length_ - 1; double final_sum_prob = 0.0 ; for( int i = 1; i < pad_haplotype_length_; ++i) { final_sum_prob += (match_matrix_[GetMatrixIndex(endI, i)] + insert_matrix_[GetMatrixIndex(endI, i)]); } return log10(final_sum_prob) - kLog10InitalConstant; }
54.353982
155
0.602898
[ "vector" ]
5b676a26241872d1f92d22ae8e2669619c6a5f55
39,734
cpp
C++
src/splitPairs.cpp
BaiLab/Read-Split-Fly
40ac90c4777afc4b1b97c0cf7418d54c25c0d2f6
[ "Apache-2.0" ]
null
null
null
src/splitPairs.cpp
BaiLab/Read-Split-Fly
40ac90c4777afc4b1b97c0cf7418d54c25c0d2f6
[ "Apache-2.0" ]
null
null
null
src/splitPairs.cpp
BaiLab/Read-Split-Fly
40ac90c4777afc4b1b97c0cf7418d54c25c0d2f6
[ "Apache-2.0" ]
null
null
null
/* File: splitPairs.cpp Copyright 2016 Jeff Kinne, Yongsheng Bai, Brandon Donham, Aaron Cox, Feng Jiang. Author: Jeff Kinne, jkinne@cs.indstate.edu Contents: Program to take alignments of pieces of unaligned reads and determine which could be "split" or "matched" pairs - indicating that the unaligned read resulted from a splice. Also, determine which matched pairs support each other (resulted from the same splice junction). To compile: g++ splitPairs.cpp -o sp -O4 -std=c++11 To run: ./sp options.txt Where options.txt is an options file. If the program is run with no command-line arguments it by default processes RSW_test.txt with the same parameters as the scripts downloaded from Yongsheng Bai's website. When you run the program it prints which files output is written to. See readOptionsFromFile function for the order of the parameters in the options file. Modification history... 3/17/2016 - update the algorithm for selecting supporting reads to be more memory-efficient. This includes writing to the results files as the program runs. Also, update the .splitPairs format to take up less space. 1/6/2016 - bug fixes in a few of the .c files that were not allocating enough space for filenames, causing pipeline to crash sometimes. Replace a few more %i with %li in .c(pp) files to get rid of compile warnings. 11/24/2015 - Modify RSW.h and this file to print out the actual sequence for split pairs. This will appear in the output in the .results files. - Update comments in this file and RSW.h. Replace %i with %li where required for 64 bit systems (when printing results of time(NULL) or vector.size()) 8/15/2015 - version 1.0.0 of RSR on github. * sp4 - 7/30/2015 * 7/30/2015 - fix bug in computing supporting reads that appeared in sp3. * 7/30/2015 - fixed bug where compare_data was being used in main loop that computes matched pairs; compare_data was written to be used in sorting, but was being used looking for exact match between lines. Just stopped using it in the main loop and put in the if tests there (to avoid repeating this mistake in the future). * 7/30/2015 - had been working on using openmp to parallelize the main loops. was getting seg fault for unknown reason, so commented out all #pragma lines that were part of that effort. * sp3 - 7/29/2015 * 7/29/2015 - Jeff Kinne - fixed bug that was reporting the number of supporting reads as one two small for each junction. * 7/9/2015 - Jeff Kinne - store strings in stringTable to avoid duplicating the strings. Should save memory and speed up (because compare string pointers rather than strcmp). * 7/8/2015 - started tracking mod history... */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <iostream> #include <limits.h> #include <vector> #include <algorithm> #include <unordered_map> #include <unordered_set> #include <time.h> #include <sys/resource.h> //#include <omp.h> using namespace std; #include "RSW.h" // parameters input from options file int maxDistance; // max difference in aligned pieces to be considered matched pair // this field no longer used, software automatically detects read length for each read in an earlier part of the pipeline //int sampleLength; // length of reads in this data set int minSpliceLength; // minimum size of splice to consider int supportPosTolerance; // "buffer boundary" parameter for determining supporting reads int minSupportingReads; // only output junctions with at least this many supporting reads char const *sampleDataFile; // input file name char const *refFlatFile; // refFlat file of gene locations char const *refFlatBoundaryFile; // refFlat file of known intron/extron boundaries char const *resultsBaseName; // base file name used for output file names char buff[MAX_STR_LEN]; char options[MAX_STR_LEN]; time_t beginTime, endTime; // for keeping track of running time of program // string table is used to reduce memory usage of program. for any string // we need we store it in the string table and then only use the pointer to the // string any time we need it. So two records from the input file with the same // read id won't take up twice as much memory. See reading of data file for // how this works. unordered_set<string> stringTable; // used in printing of results to avoid printing multiple junction sites // multiple times //unordered_set<const char *> readIdsReported; // data read into the program vector<struct RSW> data; // from input file of alignments of pieces of unaligned reads vector<struct RSW_Known> data_known; // from refFlat vector<struct RSW_Boundaries> data_boundaries; // from refFlat intron/extron boundaries unordered_map<const char *, RSW_half_data> data_halves; // stores information about max/min length seen from each half of an id string halfStatsString=""; // computed once all data is read in, then printed later. const char unfound_string[100] = "UNFOUND_"; // gene name of any junction outside of genes vector<RSW_splice *> data_splice; // used to store possible jucntions, see RSW.h for RSW_splice definition int numDifferentReads; // counter... // function not currently used int compute_hash(RSW *d) { int h = 1, i; for(i=0; d->id[i] != '\0'; i++) h = h * d->id[i] % SHRT_MAX; for(i=0; d->chromosome[i] != '\0'; i++) h = h * d->chromosome[i] % SHRT_MAX; h = h * d->direction % SHRT_MAX; return h; } char sLine[MAX_LINE+1]; char temp[MAX_LINE+1]; /* Function: read_data, read in data file into data vector Parameters: filename - file to open and read Note: if file is .gz or .lrz then attempt to unzip before reading. This will only work if gunzip and/or lrunzip can be run from the current directory. */ void read_data(const char *filename) { // open file for reading (from pipe if trying to unzip) FILE *f; int len = strlen(filename); if (len > 3 && strcmp(filename+len-3,".gz")==0) { sprintf(temp,"gunzip -c %s", filename); f = popen(temp, "r"); } else if (len > 4 && strcmp(filename+len-4,".lrz")==0) { sprintf(temp,"cat %s | ./lrunzip", filename); f = popen(temp, "r"); } else f = fopen(filename, "r"); if (f == NULL) {printf("Error reading from file %s\n", filename); exit(0); } // read data file one line at a time. int result=1; while (result > 0) { int i; char dir; RSW *r = new RSW; result = get_line(f, sLine, MAX_LINE); if (result < 0) { printf("Error reading data file %s, line exceeded %i characters.\n", filename, MAX_LINE); delete r; break; } // break line into fields, separated by tab char *tempA = strtok(sLine, "\t"); i=0; while (tempA != NULL) { string temp = tempA; temp.shrink_to_fit(); pair<unordered_set<string>::iterator,bool> result; switch (i) { case 0: // id of read // put into string table and store pointer to string. note // that insert just returns a pointer if the string already was in the string table. result = stringTable.insert(temp); r->id = (result.first)->c_str(); break; case 1: // side r->side = temp[0]; break; case 2: // length of piece r->length = atoi(temp.c_str()); break; case 3: // total length of read this piece is in r->totalReadLength = atoi(temp.c_str()); break; case 4: // direction r->direction = temp[0]; break; case 5: // chromosome result = stringTable.insert(temp); r->chromosome = (result.first)->c_str(); break; case 6: // position r->position = atol(temp.c_str()); break; case 9: // count, unused currently r->count = atoi(temp.c_str()); break; } i++; tempA = strtok(NULL,"\t"); if (tempA == NULL) break; } if (i < 10) { delete r; break; } r->hash = compute_hash(r); // not currently used // update RSW_half information ... // look to see if we've seen this id and half before. // id is pointer to string with id + which side. pair<unordered_set<string>::iterator,bool> res; string temp; temp = r->id; temp += r->side; temp.shrink_to_fit(); res = stringTable.insert(temp); const char * key = (res.first)->c_str(); temp = r->id; temp += toupper(r->side) == 'L' ? 'R' : 'L'; res = stringTable.insert(temp); const char * otherKey = (res.first)->c_str(); auto h_find = data_halves.find(key); if (h_find == data_halves.end()) { // if new, insert RSW_half_data hd; hd.minLength = hd.maxLength = r->length; data_halves.insert({key, hd}); } else { // if not new, update as appropriate if (r->length < h_find->second.minLength) { h_find->second.minLength = r->length; } if (r->length > h_find->second.maxLength) { h_find->second.maxLength = r->length; } } r->halfKey = key; r->otherHalfKey = otherKey; // what position on this would be at the split if (r->side == 'L' && r->direction == '+' || r->side == 'R' && r->direction == '-') { r->splitPos = r->position + r->length; } else { r->splitPos = r->position; } data.push_back(*r); // save into vector delete r; //if (data.size() >= 15000000) break; // cut off early, for debugging to prevent program from running for too long. } fclose(f); } /* Function: read_knownGene, similar to read_data but read the format of the refFlat file of gene locations */ void read_knownGene(const char *filename) { FILE * f = fopen(filename, "r"); if (f == NULL) {printf("Error reading from file %s\n", filename); exit(0); } int result=1; while (result > 0) { int i; char dir; RSW_Known * rk = new RSW_Known; result = get_line(f, sLine, MAX_LINE); if (result < 0) { printf("Error reading data file %s, line exceeded %i characters.\n", filename, MAX_LINE); delete rk; break; } char *tempA = strtok(sLine, "\t"); i=0; while (tempA != NULL) { string temp= tempA; temp.shrink_to_fit(); pair<unordered_set<string>::iterator,bool> result; switch (i) { case 0: result = stringTable.insert(temp); rk->id1 = (result.first)->c_str(); break; case 1: result = stringTable.insert(temp); rk->id2 = (result.first)->c_str(); break; case 2: result = stringTable.insert(temp); rk->chromosome = (result.first)->c_str(); break; case 3: rk->direction = temp[0]; break; case 4: rk->position1 = atol(temp.c_str()); break; case 5: rk->position2 = atol(temp.c_str()); break; } i++; tempA = strtok(NULL,"\t"); if (tempA == NULL) break; } if (i < 11) {delete rk; break;} if (rk->position1 > rk->position2) { int t = rk->position1; rk->position1 = rk->position2; rk->position2 = t; } data_known.push_back(*rk); delete rk; } fclose(f); } /* Function: read_boundaries, similar to read_data but read the format of the refFlat file of intron/extron boundaries. */ void read_boundaries(const char *filename) { FILE * f = fopen(filename, "r"); if (f == NULL) {printf("Error reading from file %s\n", filename); exit(0); } int result=1; while (result > 0) { int i; char dir; RSW_Boundaries * rk = new RSW_Boundaries; result = get_line(f, sLine, MAX_LINE); if (result < 0) { printf("Error reading data file %s, line exceeded %i characters.\n", filename, MAX_LINE); delete rk; break; } char *tempA = strtok(sLine, "\t"); i=0; while (tempA != NULL) { string temp = tempA; temp.shrink_to_fit(); pair<unordered_set<string>::iterator,bool> result; switch (i) { case 0: result = stringTable.insert(temp); rk->id1 = (result.first)->c_str(); break; case 1: result = stringTable.insert(temp); rk->id2 = (result.first)->c_str(); break; case 2: result = stringTable.insert(temp); rk->chromosome = (result.first)->c_str(); break; case 3: rk->direction = temp[0]; break; case 11: rk->length = atoi(temp.c_str()); break; case 12: char *tempB = (char *) malloc(sizeof(char)* (temp.size()+1)); strcpy(tempB,temp.c_str()); char *temp1 = strstr(tempB, "--"); if (temp1 == NULL) { rk->position1 = rk->position2 = 0; } else { temp1[0] = '\0'; rk->position1 = atol(tempB); rk->position2 = atol(temp1+2); } free(tempB); break; } i++; tempA = strtok(NULL,"\t"); if (tempA == NULL) break; } if (i < 13) {delete rk; break;} data_boundaries.push_back(*rk); delete rk; } fclose(f); } /* Function: compare_dataById, used for sorting input data Sorts based on id, direction, chromosome, position */ bool compare_dataById(RSW const &aa, RSW const &bb) { int temp = aa.id-bb.id; if (temp < 0) return true; else if (temp > 0) return false; if (aa.direction < bb.direction) return true; else if (bb.direction < aa.direction) return false; temp = aa.chromosome-bb.chromosome; if (temp < 0) return true; else if (temp > 0) return false; if (aa.position < bb.position) return true; else return false; } /* Function: compare_dataToSort, used for sorting input data Sorts based on chromosome, position, id */ bool compare_dataByChromPos(RSW const &aa, RSW const &bb) { int temp = aa.chromosome - bb.chromosome; if (temp < 0) return true; else if (temp > 0) return false; int position = aa.splitPos - bb.splitPos; if (position < 0) return true; else if (position > 0) return false; return false; } /* Function: compare_data_known, used for sorting results from refFlat file Sort based on chromosome and position. */ bool compare_data_known(RSW_Known const &aa, RSW_Known const &bb) { int temp = aa.chromosome-bb.chromosome; if (temp < 0) return true; else if (temp > 0) return false; return aa.position1 < bb.position1; } /* Function: compare_spliceByChromPos, used for sorting junctions Sorts based on chromosome, position, splice length - used in sorting before computing supporting reads. */ bool compare_spliceByChromPos(RSW_splice *aa, RSW_splice *bb) { int temp = aa->chromosome-bb->chromosome; if (temp < 0) return true; else if (temp > 0) return false; if (aa->positionSmaller < bb->positionSmaller) return true; else if (aa->positionSmaller > bb->positionSmaller) return false; return false; } /* Function: readOptionsFromFile, reads parameters for program Options assumed to be one per line in a predefined order. */ void readOptionsFromFile(const char *filename) { FILE * fOptions = fopen(filename, "r"); if (fOptions == NULL) { printf("Error opening file %s\n", filename); exit(0); } int pos = 0; int count = 0; char *fields[9]; fields[0] = &options[0]; int ch; while ((ch = fgetc(fOptions)) != EOF) { if (pos >= MAX_STR_LEN) { printf("Options file %s is more than the max of %i bytes.\n", filename, MAX_STR_LEN); exit(0); } if (ch == '\n') { options[pos++] = '\0'; count++; if (count < 9) fields[count] = &options[pos]; else break; } else options[pos++] = ch; } fclose(fOptions); if (count < 9) { printf("Not enough lines in options file.\n"); exit(0); } sampleDataFile = fields[0]; maxDistance = atoi(fields[1]); //sampleLength = atoi(fields[2]); // this field no longer used, software automatically detects read length for each read in an earlier part of the pipeline refFlatFile = fields[3]; refFlatBoundaryFile = fields[4]; minSpliceLength = atoi(fields[5]); supportPosTolerance = atoi(fields[6]); resultsBaseName = fields[7]; minSupportingReads = atoi(fields[8]); } /* Function: setDefaultOptions, sets some default options if now options file is given on the command-line. Useful for debugging - set the default options to be whatever you are testing, so don't have to type in name of options file each time you run the program. */ void setDefaultOptions() { sampleDataFile = "RSW_test.txt"; maxDistance = 40000; //sampleLength = 33; refFlatFile = "refFlat.txt"; refFlatBoundaryFile = "refFlat.txt.intronBoundary.exonsgaps"; minSpliceLength = 2; supportPosTolerance = 5; resultsBaseName = "RSW_tst"; minSupportingReads = 2; printf("Not enough arguments given, using default values.\n"); printf("Usage is to load options from file: ./splitPairs optionsFile.txt \n"); printf("And make sure options file has options in order, each on their own line with no extra lines.\n"); } /* Function: printCurrentOptions, print options to given file pointer. Print to file pointer, so can print the options that were used to stdout and/or to output files with results. */ void printCurrentOptions(FILE *f) { fprintf(f, "Running with options...\n" " file with read data %s\n" " max distance between matches %i\n" " length of samples variable, auto-detect\n" " refFlat file %s\n" " refFlat intron boundary file %s\n" " minimum splice length %i\n" " tolerance of difference in position for supporting reads %i\n" " base of file name for writing results %s\n" " minimum number of supporting reads %i\n\n", sampleDataFile, maxDistance, /*sampleLength,*/ refFlatFile, refFlatBoundaryFile, minSpliceLength, supportPosTolerance, resultsBaseName, minSupportingReads); if (strlen(sampleDataFile) > MAX_STR_LEN - 100) { fprintf(f,"Error, filename %s is too long.\n", sampleDataFile); exit(0); } fflush(f); } // files we will write out to FILE * fKnown, *fUnknown, //*fKnownFull, *fUnknownFull, *fSplitPairs; // open output files to be ready to write out to them. void openOutputFiles() { sprintf(buff,"%s.results", resultsBaseName); fKnown = fopen(buff, "w"); if (fKnown == NULL) { printf("Error opening file %s for writing.\n", buff); exit(0); } printf("Will write summary results that match in known genes to file\n" " %s\n", buff); /*sprintf(buff,"%s.results.full", resultsBaseName); fKnownFull = fopen(buff, "w"); if (fKnownFull == NULL) { printf("Error opening file %s for writing.\n", buff); exit(0); } printf("Will write full results that match in known genes to file\n" " %s\n", buff);*/ sprintf(buff,"%s.results.unknown", resultsBaseName); fUnknown = fopen(buff, "w"); if (fUnknown == NULL) { printf("Error opening file %s for writing.\n", buff); exit(0); } printf("Will write summary results that do NOT match in known genes to file\n" " %s\n", buff); /* sprintf(buff,"%s.results.unknown.full", resultsBaseName); fUnknownFull = fopen(buff, "w"); if (fUnknownFull == NULL) { printf("Error opening file %s for writing.\n", buff); exit(0); } printf("Will write full results that do NOT match in known genes to file\n" " %s\n", buff);*/ sprintf(buff,"%s.results.splitPairs", resultsBaseName); fSplitPairs = fopen(buff, "w"); if (fSplitPairs == NULL) { printf("Error opening file %s for writing.\n", buff); exit(0); } printf("Will write split pairs to file\n" " %s\n", buff); } /* Function: printSplice, print a given junction to the given opened file Commenting this out and printing out one that is more comparable to the old output - Aaron */ /*void printSplice(FILE *f, RSW_splice *sp) { fprintf(f, "%s\t%s\t%li\t%li\t%li\t%li\t%li--%li\t%li--%li\t%s", sp->geneName, sp->chromosome, sp->numSupport, sp->numSupportHalves, sp->numSupportTotal, sp->positionLarger-sp->positionSmaller, sp->positionSmaller,sp->positionLarger, sp->minSmallSupport,sp->maxLargeSupport, sp->novel ? "Novel" : "*" ); } */ void printSplice(FILE *f, RSW_splice *sp) { fprintf(f, "%s\t%s\t%li\t%li\t%li\t%li\t%li--%li\t%s", sp->geneName, sp->chromosome, sp->numSupport, //full support sp->numSupportHalves, //half support sp->numSupportTotal, //"total" support sp->positionLarger - sp->positionSmaller, //splice length sp->minSmallSupport,sp->maxLargeSupport, //range of indices jnctn occrs sp->novel ? "Novel" : "*" ); } string getHalfStats() { char s[10000]; int halfCount = 0; int minMax = -1, minMin = -1, maxMax = -1, maxMin = -1, minTotal = 0, maxTotal = 0; for(auto it=data_halves.begin(); it != data_halves.end(); it++) { halfCount++; int min = it->second.minLength, max = it->second.maxLength; minTotal += min; maxTotal += max; if (minMax == -1 || min > minMax) minMax = min; if (minMin == -1 || min < minMin) minMin = min; if (maxMax == -1 || max > maxMax) maxMax = max; if (maxMin == -1 || max < maxMin) maxMin = max; } sprintf(s, "Half lengths: min %lf avg, range %li-%li; max %lf avg, range %li-%li", (double) minTotal / halfCount, minMin, minMax, (double) maxTotal / halfCount, maxMin, maxMax); return s; } /* Function: printStats, prints statistics gathered so far to the opened file - useful for debugging to see some partial information as each phase of the program finishes. */ void printStats(FILE *f) { FILE *fStatus = fopen("/proc/self/status","r"); char s[1000], mem[20]="", units[20]=""; while (fscanf(fStatus,"%999s",s) == 1) { if (strcmp(s,"VmRSS:") == 0) { int result = fscanf(fStatus,"%19s %19s",mem, units); break; } } fclose(fStatus); endTime = time(NULL); fprintf(f, "Finished processing data, results written to files.\n"); fprintf(f, "Number of entries in data file: %li\n", data.size()); fprintf(f, "Number of different reads: %i\n", numDifferentReads); fprintf(f, "Number of entries in refFlat file: %li\n", data_known.size()); fprintf(f, "Number of entries in refFlat boundary file: %li\n", data_boundaries.size()); fprintf(f, "Number of matches: %li\n", data_splice.size()); fprintf(f, "String table size: %li\n", stringTable.size()); fprintf(f, "VmRSS, memory resident set size: %s %s\n", mem, units); fprintf(f, "Total time to process: %li seconds\n", endTime-beginTime); // statistics for halves... fprintf(f, "%s", halfStatsString.c_str()); fprintf(f, "\n"); fflush(f); // force write to disk } /* Check a half in data against a splice in data_splice, in particular check data_splice[sp1] against data[i_data]. Return: 1 if they are a match 0 if not a match -1 if should break out of loop back in main (stop incrementing i_data because past data_splice[sp1] in data) */ int checkHalf(int sp1, int i_data, bool smallEnd) { int c = data_splice[sp1]->chromosome - data[i_data].chromosome; // if not same chromosome, either wait for sp1 to catch up, or let i_data catch up if (c < 0) return -1; else if (c == 0) { int p; if (smallEnd) p = data_splice[sp1]->positionSmaller - data[i_data].splitPos; else p = data_splice[sp1]->positionLarger - data[i_data].splitPos; if ( p < 0) return -1; else if (p == 0) { // a match auto fOther = data_halves.find(data[i_data].otherHalfKey); if (data_splice[sp1]->direction == data[i_data].direction && (fOther == data_halves.end() || fOther->second.maxLength < data[i_data].totalReadLength - data[i_data].length)) { // then this is a half that is at the right position and doesn't have a matching // other half (presumably because of being in the max file) that is long enough so let's count it. return 1; } } else // p > 0 return 0; } else // c > 0 return 0; } int main(int argc, char *argv[]) { setpriority(0, 0, 20); // so other processes get priority over this one beginTime = time(NULL); // read options, from file or default options if (argc > 1) readOptionsFromFile(argv[1]); else setDefaultOptions(); // write out options to all output files and stdout openOutputFiles(); printCurrentOptions(stdout); printCurrentOptions(fKnown); // printCurrentOptions(fKnownFull); printCurrentOptions(fUnknown); // printCurrentOptions(fUnknownFull); printCurrentOptions(fSplitPairs); // read from refFlat file into data_known array, read_knownGene(refFlatFile); sort(data_known.begin(), data_known.end(), compare_data_known); printf("Done reading/sorting refFlat, total time elapsed %li seconds\n", time(NULL)-beginTime); printStats(stdout); // read from refFlat boundary file into data_boundaries array, read_boundaries(refFlatBoundaryFile); printf("Done reading refFlat intron/exon boundaries, total time elapsed %li seconds\n", time(NULL)-beginTime); printStats(stdout); // read the read data read_data(sampleDataFile); halfStatsString = getHalfStats(); printf("Done reading read data, total time elapsed %li seconds\n", time(NULL)-beginTime); printStats(stdout); // sort the read data sort(data.begin(), data.end(), compare_dataById); printf("Done sorting read data, total time elapsed %li seconds\n", time(NULL)-beginTime); printStats(stdout); // look at all pairs of read segments, looking for matches numDifferentReads = 0; const int inputSize = data.size(); for(int left=0; left < inputSize; left++) { int right; if (left == 0 || (data[left].id != data[left-1].id) ) { numDifferentReads++; } for(right=left+1; right < inputSize; right++) { // read segments are ordered by id/chromosome/strand, so if // there isn't a match we can skip the rest of the read segments // for "right", and go to the next iteration of the "left" loop if (data[left].id != data[right].id || data[left].direction != data[right].direction || data[left].chromosome != data[right].chromosome) { break; } if (data[right].position - data[left].position > maxDistance) { break; } // want it to be from two sides of the same segment if (data[left].side == data[right].side) { continue; } // total length should be correct if (data[left].length + data[right].length != data[left].totalReadLength) { continue; } // calculate the end of the segments, since what is given // in the data is the beginning of the segments int endSmaller, endLarger; // splice is between endSmaller and endLarger int first, second; if (data[left].side == 'L' && data[left].direction == '+' || data[left].side == 'R' && data[left].direction == '-') { first = left; second = right; } else { first = right; second = left; } endSmaller = data[first].position + data[first].length; endLarger = data[second].position; // splice length, and check that it is within specified bounds int spliceLength = endLarger - endSmaller; if (spliceLength > maxDistance) continue; if (spliceLength < minSpliceLength) continue; // check if we already have this splice from this read... int i; for(i=0; i < data_splice.size(); i++) { if (data_splice[i]->positionSmaller != endSmaller || data_splice[i]->positionLarger != endLarger || data_splice[i]->id != data[left].id || data_splice[i]->chromosome != data[left].chromosome) { continue; } break; } // if already have this exact splice for this chromosome from this read, don't include it again. if (i < data_splice.size()) continue; // note: could print this match here, step 5 done. // look for this in the known gene... int k; int foundInGene = 0; for(k=0; k < data_known.size(); k++) { if ((((data[left].chromosome == data_known[k].chromosome) && (data[left].position >= data_known[k].position1 && data[right].position >= data_known[k].position1) && (data[left].position <= data_known[k].position2 && data[right].position <= data_known[k].position2)))) { if (foundInGene) ;//printf("DUPLICATE_"); // duplicate //TODO: remove this? -aaron foundInGene = 1; break; // just cut off search, don't look for duplicates } } int geneIndex = k; // make a new splice record and put into vector of splices RSW_splice *sp = new RSW_splice; if (sp == NULL) { printf("ERROR, new in C++ failed, maybe out of memory.\n"); exit(0); } sp; if (foundInGene) { sp->geneName = data_known[geneIndex].id1; sp->geneUnknown = 0; } else { sp->geneName = unfound_string; sp->geneUnknown = 1; } sp->id = data[left].id; sp->chromosome = data[left].chromosome; sp->direction = data[left].direction; sp->positionSmaller = sp->minSmallSupport = endSmaller; sp->positionLarger = sp->maxLargeSupport = endLarger; sp->alreadyReported = false; sp->print = false; sp->numSupport = sp->numSupportHalves = sp->numSupportTotal = 0; sp->leftLength = data[left].length; data_splice.push_back(sp); } } printf("Done finding matched pairs, total time elapsed %li seconds\n", time(NULL)-beginTime); printStats(stdout); // re-sort input data by chromosome and position sort(data.begin(), data.end(), compare_dataByChromPos); printf("Done resorting input data by chromosome and position, total time elapsed %li seconds\n", time(NULL)-beginTime); printStats(stdout); // sort splices by chromosome and position sort(data_splice.begin(), data_splice.end(), compare_spliceByChromPos); printf("Done sorting matched pairs, total time elapsed %li seconds\n", time(NULL)-beginTime); printStats(stdout); int i_lastEndSmaller = 0, i_lastEndLarger = 0; // compute supporting reads, print them out on the fly. for(int sp1=0; sp1 < data_splice.size(); sp1++) { int sp2; if (data_splice[sp1]->alreadyReported) continue; unordered_set <const char *> supported_read_ids; // list of supporting reads unordered_set <const char *> supported_read_ids_halves; // list of supporting reads unordered_set <const char *> supported_read_ids_both; // list of supporting reads unordered_set <RSW_splice *> supported_splices; //unordered_set <int> supported_halves; // int is the index into data - note that only works as long as data is not resorted supported_read_ids.insert(data_splice[sp1]->id); supported_read_ids_both.insert(data_splice[sp1]->id); supported_splices.insert(data_splice[sp1]); // scan through the following reads ... for(sp2=sp1; sp2 < data_splice.size(); sp2++) { // see if these reads support each other // if not same chromosome, no support. if (data_splice[sp1]->chromosome != data_splice[sp2]->chromosome) { break; } // only need to go up to supportPosTolerance away in position, then break if (data_splice[sp2]->positionSmaller > data_splice[sp1]->positionSmaller + supportPosTolerance) { break; } if (abs(data_splice[sp1]->positionLarger - data_splice[sp1]->positionSmaller) != abs(data_splice[sp2]->positionLarger - data_splice[sp2]->positionSmaller)) { continue; // splice length must be the same } // note: if id already if (data_splice[sp2]->id == data_splice[sp1]->id) { // if report sp1, then shouldn't report other splices for sp1 that are close supported_splices.insert(data_splice[sp2]); continue; } // they are matches for each other supported_read_ids.insert(data_splice[sp2]->id); supported_read_ids_both.insert(data_splice[sp2]->id); supported_splices.insert(data_splice[sp2]); if (data_splice[sp2]->positionSmaller < data_splice[sp1]->minSmallSupport) { data_splice[sp1]->minSmallSupport = data_splice[sp2]->positionSmaller; } if (data_splice[sp2]->positionLarger > data_splice[sp1]->maxLargeSupport) { data_splice[sp1]->maxLargeSupport = data_splice[sp2]->positionLarger; } } // scan also through read data, looking for halves that // match up but don't have the other half because it is probably // in the max file. for(; ; i_lastEndSmaller++) { int result = checkHalf(sp1, i_lastEndSmaller, true); if (result < 0) { break; } else if (result > 0) { // then this is a half that is at the right position and doesn't have a matching // other half (presumably because of being int he max file), so let's count it. supported_read_ids_halves.insert(data[i_lastEndSmaller].id); supported_read_ids_both.insert(data[i_lastEndSmaller].id); } } // and similarly, check the larger half of the split. for(int i_data = i_lastEndSmaller; ; i_data++) { int result = checkHalf(sp1, i_data, false); if (result < 0) break; else if (result > 0) { // then this is a half that is at the right position and doesn't have a matching // other half (presumably because of being int he max file), so let's count it. supported_read_ids_halves.insert(data[i_data].id); supported_read_ids_both.insert(data[i_data].id); } } if (supported_read_ids_both.size() >= minSupportingReads) { data_splice[sp1]->print = true; data_splice[sp1]->alreadyReported = true; data_splice[sp1]->numSupport = supported_read_ids.size(); data_splice[sp1]->numSupportHalves = supported_read_ids_halves.size(); data_splice[sp1]->numSupportTotal = supported_read_ids_both.size(); for(const auto& x: supported_splices) { x->alreadyReported = true; } } } printf("Done computing supporting reads, total time elapsed %li seconds\n", time(NULL)-beginTime); printStats(stdout); // sort splices by chromosome and length, and # supporting reads //sort(data_splice.begin(), data_splice.end(), compare_spliceByChromLen); //printf("Done sorting matched pairs again, total time elapsed %li seconds\n", time(NULL)-beginTime); //printStats(stdout); //printf("Done filtering matched pairs, total time elapsed %li seconds\n", time(NULL)-beginTime); //printStats(stdout); endTime = time(NULL); printf("Done calculating/filtering supporting reads, total time elapsed %li seconds\n", time(NULL)-beginTime); printStats(stdout); // print the splice results. start with the statistics printStats(stdout); printStats(fKnown); // printStats(fKnownFull); printStats(fUnknown); // printStats(fUnknownFull); printStats(fSplitPairs); int k; // save all the splices, and reads that support each one into .splitPairs file - this is // the full results, with many duplicates of splices. The file also can be HUGE, so // generally this file will often get deleted unless needed for debugging. fprintf(fSplitPairs, "Id\tGene\tChr\t# Supporting reads\t# Supporting halves\t# Supporting total\tLength\tSplice region\tSupporting splice range\tLeft side length\n"); int i_data=0; for(k=0; k < data_splice.size() && i_data < data.size();) { if (i_data == data.size() || data_splice[k]->chromosome < data[i_data].chromosome || (data_splice[k]->chromosome == data[i_data].chromosome && data_splice[k]->positionSmaller < data[i_data].splitPos)) { // print a splice fprintf(fSplitPairs, "%s\t%s\t%s\t%li\t%li\t%li\t%li\t%li-%li\t%li-%li\t%li\n", data_splice[k]->id, data_splice[k]->geneName, data_splice[k]->chromosome, data_splice[k]->numSupport, data_splice[k]->numSupportHalves, data_splice[k]->numSupportTotal, data_splice[k]->positionLarger-data_splice[k]->positionSmaller, data_splice[k]->positionSmaller,data_splice[k]->positionLarger, data_splice[k]->minSmallSupport,data_splice[k]->maxLargeSupport, data_splice[k]->leftLength ); k++; } else { // print a half that doesn't have a matching other half that is big enough auto fOther = data_halves.find(data[i_data].otherHalfKey); if (fOther == data_halves.end() || fOther->second.maxLength < data[i_data].totalReadLength - data[i_data].length) { fprintf(fSplitPairs, "%s\t%s\t%s\t%li\t%li\t%li\t%li\t%li-%li\t%li-%li\t%li %c %c\n", data[i_data].id, "???", data[i_data].chromosome, 0,0,0, 0, data[i_data].position,data[i_data].splitPos, 0,0, data[i_data].length, data[i_data].side, data[i_data].direction ); } i_data++; } } // save the tabulated results. the fKnown file is the only one normally looked at. // fKnownFull has the same information as fKnown, but also has the list of supporting reads for each junction. // fUnknown and fUnknownFull are for junctions not within genes. fprintf(fKnown, "GeneName\tChromosome\t# supporting reads\t# supporting halves\t# supporting total\tsplice length\trange of supporting reads\tNovel or not (*)\n"); fprintf(fUnknown, "GeneName\tChromosome\t# supporting reads\t# supporting halves\t# supporting total\tsplice length\trange of supporting reads\tNovel or not (*)\n"); FILE * f;//, *fFull; for(k=0; k < data_splice.size(); k++) { // already decided if we should print this one or not if (! data_splice[k]->print) continue; // check if novel or not. int j; data_splice[k]->novel = true; for(j=0; j < data_boundaries.size(); j++) { if (data_splice[k]->positionLarger-data_splice[k]->positionSmaller != data_boundaries[j].length) { continue; } if (abs(data_splice[k]->minSmallSupport-data_boundaries[j].position1) <= supportPosTolerance && abs(data_splice[k]->maxLargeSupport-data_boundaries[j].position2) <= supportPosTolerance) { break; } } if (j < data_boundaries.size()) { // if found in the boundaries data, not novel data_splice[k]->novel = false; } // going into known file or unknown if (data_splice[k]->geneUnknown) { f = fUnknown; //fFull = fUnknownFull; } else { f = fKnown; //fFull = fKnownFull; } // print out results printSplice(f, data_splice[k]); fprintf(f, "\n"); } fclose(fKnown); //fclose(fKnownFull); fclose(fUnknown); //fclose(fUnknownFull); fclose(fSplitPairs); printf("Done saving results, total time elapsed %li seconds\n", time(NULL)-beginTime); printStats(stdout); // free memory. good to do so we can run a memory checker and verify // we don't have any memory leaks. while (data_splice.size() > 0) { delete data_splice.back(); data_splice.pop_back(); } return 0; }
35.287744
217
0.64061
[ "vector" ]
5b68b772a9804f1951c25e2962b8e88e36870a8c
925
hpp
C++
oop_observer.hpp
zht043/inter-thread-publisher-subscriber-cpp
c9862a438ae71ac3004daf4f6f7465184a1ee938
[ "MIT" ]
null
null
null
oop_observer.hpp
zht043/inter-thread-publisher-subscriber-cpp
c9862a438ae71ac3004daf4f6f7465184a1ee938
[ "MIT" ]
null
null
null
oop_observer.hpp
zht043/inter-thread-publisher-subscriber-cpp
c9862a438ae71ac3004daf4f6f7465184a1ee938
[ "MIT" ]
null
null
null
/* * An Observer Pattern C++ implementation using boost library */ #pragma once #include <iostream> #include <string> #include <unordered_map> #include <boost/asio.hpp> #include <boost/bind.hpp> #include <boost/thread/thread.hpp> #include <boost/signals2.hpp> /* This implementation is not multithreaded-safe, * for multithreaded-safe one, use the function pointer * version of observer pattern in inter_thread_pubsub.hpp * */ template<class Data> class Observer { public: virtual void on_update(Data data) = 0; // pure virtual }; template<class Data> class Subject { public: void add_observer(Observer<Data>& obs) { observers.push_back(&obs); } void notify_observers(Data data) { for(auto& obs : observers) { obs->on_update(data); } } protected: std::vector< Observer<Data>* > observers; };
19.680851
62
0.64
[ "vector" ]
5b6a08e0bdb341643a73a467f2cd6bef550e0d90
1,354
cpp
C++
Algorithms/Find Pivot Index/solution.cpp
MishaVernik/LeetCode
5f4823706f472b59fbc0c936524477dc039a46ee
[ "MIT" ]
null
null
null
Algorithms/Find Pivot Index/solution.cpp
MishaVernik/LeetCode
5f4823706f472b59fbc0c936524477dc039a46ee
[ "MIT" ]
null
null
null
Algorithms/Find Pivot Index/solution.cpp
MishaVernik/LeetCode
5f4823706f472b59fbc0c936524477dc039a46ee
[ "MIT" ]
null
null
null
/* Given an array of integers nums, write a method that returns the "pivot" index of this array. We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index. If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index. Example 1: Input: nums = [1, 7, 3, 6, 5, 6] Output: 3 Explanation: The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3. Also, 3 is the first index where this occurs. Example 2: Input: nums = [1, 2, 3] Output: -1 Explanation: There is no index that satisfies the conditions in the problem statement. Note: The length of nums will be in the range [0, 10000]. Each element nums[i] will be an integer in the range [-1000, 1000]. */ class Solution { public: int pivotIndex(vector<int>& nums) { int pivot = 0; int a = 1; int sum = 0; for (auto el : nums){ sum += el; } int sum1 = 0; for (auto el : nums){ sum1 += el; if (sum - sum1 == sum1 - el) return pivot; pivot++; } return -1; } };
24.618182
154
0.583456
[ "vector" ]
5b7193326b49ec46a04ea1aa96002748f4c17a1c
1,400
cpp
C++
src/_leetcode/leet_629.cpp
turesnake/leetPractice
a87b9b90eb8016038d7e5d3ad8e50e4ceb54d69b
[ "MIT" ]
null
null
null
src/_leetcode/leet_629.cpp
turesnake/leetPractice
a87b9b90eb8016038d7e5d3ad8e50e4ceb54d69b
[ "MIT" ]
null
null
null
src/_leetcode/leet_629.cpp
turesnake/leetPractice
a87b9b90eb8016038d7e5d3ad8e50e4ceb54d69b
[ "MIT" ]
null
null
null
/* * ===================== leet_629.cpp ========================== * -- tpr -- * CREATE -- 2020.06.16 * MODIFY -- * ---------------------------------------------------------- * 692. 前K个高频单词 */ #include "innLeet.h" namespace leet_629 {//~ // 66% 75% class S{ struct Elem{ int num {}; const std::string *strp {nullptr}; }; struct ElemLess{ bool operator()( Elem a, Elem b ){ if( a.num==b.num ){ return (*a.strp) > (*b.strp); } return a.num < b.num; } }; public: // 1<= k <= len std::vector<std::string> topKFrequent( std::vector<std::string>& words, int k ){ std::unordered_map<std::string,int> umap {}; for( const auto &word : words ){ umap[word]++; } //---// std::priority_queue<Elem,std::vector<Elem>,ElemLess> maxHeap {}; for( auto &[s,n] : umap ){ maxHeap.push(Elem{ n, &s }); } //---// std::vector<std::string> outs {}; for( int i=0; i<k; i++ ){ outs.push_back( *maxHeap.top().strp ); maxHeap.pop(); } return outs; } }; //=========================================================// void main_(){ debug::log( "\n~~~~ leet: 629 :end ~~~~\n" ); } }//~
19.71831
84
0.371429
[ "vector" ]
ac8a04f02a06dccdb545f26ffcf07b0a9d0bf4df
2,722
cc
C++
solutions/kattis/minorsetback.cc
zwliew/ctci
871f4fc957be96c6d0749d205549b7b35dc53d9e
[ "MIT" ]
4
2020-11-07T14:38:02.000Z
2022-01-03T19:02:36.000Z
solutions/kattis/minorsetback.cc
zwliew/ctci
871f4fc957be96c6d0749d205549b7b35dc53d9e
[ "MIT" ]
1
2019-04-17T06:55:14.000Z
2019-04-17T06:55:14.000Z
solutions/kattis/minorsetback.cc
zwliew/ctci
871f4fc957be96c6d0749d205549b7b35dc53d9e
[ "MIT" ]
null
null
null
#include <algorithm> #include <array> #include <bitset> #include <chrono> #include <climits> #include <cmath> #include <cstring> #include <deque> #include <ext/pb_ds/assoc_container.hpp> #include <fstream> #include <iomanip> #include <iostream> #include <iterator> #include <map> #include <numeric> #include <queue> #include <set> #include <stack> #include <string> #include <unordered_map> #include <unordered_set> #include <vector> using namespace std; #ifdef LOCAL #include "../../_library/cc/debug.h" #define FILE "test" #else #define debug(...) 0 #define FILE "" #endif int main() { cin.tie(nullptr)->sync_with_stdio(false); if (fopen(FILE ".in", "r")) { freopen(FILE ".in", "r", stdin); freopen(FILE ".out", "w", stdout); } unordered_map<int, string> freqToPitch = { {44000, "A"}, {46616, "A#"}, {49388, "B"}, {52325, "C"}, {55437, "C#"}, {58733, "D"}, {62225, "D#"}, {65926, "E"}, {69846, "F"}, {73999, "F#"}, {78399, "G"}, {83061, "G#"}, }; unordered_map<string, unordered_set<string>> keyToPitch = { {"G major", {"G", "A", "B", "C", "D", "E", "F#"}}, {"C major", {"C", "D", "E", "F", "G", "A", "B"}}, {"Eb major", {"D#", "F", "G", "G#", "A#", "C", "D"}}, {"F# minor", {"F#", "G#", "A", "B", "C#", "D", "E"}}, {"G minor", {"G", "A", "A#", "C", "D", "D#", "F"}}, {"Eb major", {"D#", "F", "G", "G#", "A#", "C", "D"}}, }; unordered_map<string, string> altPitch = { {"A#", "Bb"}, {"C#", "Db"}, {"D#", "Eb"}, {"F#", "Gb"}, {"G#", "Ab"}, }; unordered_map<string, unordered_set<string>> keyReps = { {"Eb major", {"D#", "G#", "A#"}}, {"G minor", {"A#", "D#"}}, }; int n; cin >> n; vector<string> pitches; unordered_set<string> uniquePitches; while (n--) { double x; cin >> x; while (x > 850) { x /= 2; } while (x < 420) { x *= 2; } int origFreq = x * 100; int freq; for (freq = origFreq - 1; freq <= origFreq + 1 && !freqToPitch.count(freq); ++freq) ; pitches.push_back(freqToPitch[freq]); uniquePitches.insert(freqToPitch[freq]); } vector<string> possibleKeys; for (auto& [key, allowedPitches] : keyToPitch) { bool ok = true; for (auto& x : uniquePitches) { if (!allowedPitches.count(x)) { ok = false; break; } } if (ok) { possibleKeys.push_back(key); } } if (possibleKeys.size() != 1) { cout << "cannot determine key"; return 0; } cout << possibleKeys[0] << "\n"; for (int i = 0; i < pitches.size(); ++i) { if (keyReps[possibleKeys[0]].count(pitches[i])) { pitches[i] = altPitch[pitches[i]]; } cout << pitches[i] << "\n"; } }
24.522523
79
0.515062
[ "vector" ]
ac8cd306bdc552f89fea800ba467ea643bdf09ae
891
cpp
C++
verify/verify-yuki/yuki-1269.test.cpp
NachiaVivias/library
73091ddbb00bc59328509c8f6e662fea2b772994
[ "CC0-1.0" ]
69
2020-11-06T05:21:42.000Z
2022-03-29T03:38:35.000Z
verify/verify-yuki/yuki-1269.test.cpp
NachiaVivias/library
73091ddbb00bc59328509c8f6e662fea2b772994
[ "CC0-1.0" ]
21
2020-07-25T04:47:12.000Z
2022-02-01T14:39:29.000Z
verify/verify-yuki/yuki-1269.test.cpp
NachiaVivias/library
73091ddbb00bc59328509c8f6e662fea2b772994
[ "CC0-1.0" ]
9
2020-11-06T11:55:10.000Z
2022-03-20T04:45:31.000Z
#define PROBLEM "https://yukicoder.me/problems/no/1269" // #include "../../template/template.hpp" // #include "../../modint/montgomery-modint.hpp" #include "../../string/aho-corasick.hpp" using mint = LazyMontgomeryModInt<1000000007>; using vm = vector<mint>; void Nyaan::solve() { inl(N, L, R); vl fs; { ll f = 1; ll g = 1; while (g <= R) { if (L <= g) fs.push_back(g); swap(f += g, g); } } vs ss; each(x, fs) ss.push_back(to_string(x)); AhoCorasick<10, '0'> aho; rep(i, sz(ss)) aho.add(ss[i], i); aho.build(false); vm dp(aho.size()); dp[0] = 1; rep(_, N) { vm nx(aho.size()); rep(i, sz(aho)) { if (aho.count(i)) continue; rep(j, 10) { auto n = aho.next(i, j); nx[n] += dp[i]; } } swap(dp, nx); } mint ans = 0; rep(i, sz(aho)) if (!aho.count(i)) ans += dp[i]; out(ans - 1); }
19.369565
55
0.516274
[ "vector" ]
ac8e0b0a8199cfa23d2690bb34defed1c703b288
1,689
cpp
C++
DigDug/RockState.cpp
keangdavidTouch/C-GameEngine
e276e7cc7c840ca41b005c0cf844cd8d5580200a
[ "MIT" ]
2
2021-03-19T13:29:36.000Z
2021-04-13T23:37:10.000Z
DigDug/RockState.cpp
keangdavidTouch/C-GameEngine
e276e7cc7c840ca41b005c0cf844cd8d5580200a
[ "MIT" ]
null
null
null
DigDug/RockState.cpp
keangdavidTouch/C-GameEngine
e276e7cc7c840ca41b005c0cf844cd8d5580200a
[ "MIT" ]
null
null
null
#include "pch.h" #include "Time.h" #include "DigDugGame.h" #include "RockState.h" #include "RockBehaviour.h" #include "TaizoBehaviour.h" #include "SpriteComponent.h" kd::BaseState* kd::RockIdleState::Update(GameObject* object) { if (object->GetComponent<RockBehaviour>()->ShouldFall()) { if(m_Sprite) m_Sprite->SetCurrentClip(RockBehaviour::Animation::Shake); m_RockCrackElapsedSec += Time::GetInstance().DeltaTime(); } if (m_RockCrackElapsedSec >= 1.5f) return new RockCrackState(); return nullptr; } void kd::RockIdleState::Enter(GameObject* object) { m_Sprite = object->GetComponent<SpriteComponent>(); std::cout << "Enter Rock-IdleState" << std::endl; } void kd::RockIdleState::Exit(GameObject* object) { object->GetComponent<RockBehaviour>()->SetFalling(true); } kd::BaseState* kd::RockCrackState::Update(GameObject* object) { auto pos = object->GetTransform().GetPosition(); pos.y += m_FallSpeed * Time::GetInstance().DeltaTime(); m_Behaviour->SetFalling(true); if(m_Behaviour->ShouldFall()) { object->GetTransform().SetPosition(pos.x, pos.y, pos.z); } else { m_CrackElapedSec += Time::GetInstance().DeltaTime(); if(m_CrackElapedSec > m_CrackDuration) { SceneManager::GetInstance().GetActiveScene()->RemoveGameObject(object); return nullptr; } if(!m_Sprite->SetCurrentClip(RockBehaviour::Animation::Crack)) { m_Sprite->SetPause(true); } } return nullptr; } void kd::RockCrackState::Enter(GameObject* object) { m_Behaviour = object->GetComponent<RockBehaviour>(); m_Sprite = object->GetComponent<SpriteComponent>(); std::cout << "Enter Rock-Crack State" << std::endl; } void kd::RockCrackState::Exit(GameObject*){}
23.136986
74
0.719361
[ "object" ]
ac940a3d1966de779179efb42bf6aaa87799e008
2,086
cpp
C++
persistence/changequeue.cpp
czpwpq/hotel
2e003b019cf6b21349228740a8dae6c639945510
[ "MIT" ]
7
2017-04-05T20:06:30.000Z
2022-01-01T00:14:42.000Z
persistence/changequeue.cpp
czpwpq/hotel
2e003b019cf6b21349228740a8dae6c639945510
[ "MIT" ]
1
2017-01-06T13:47:45.000Z
2017-01-06T13:49:47.000Z
persistence/changequeue.cpp
decden/hotel
1d7d16ad0a97c9a24f8e54b9b180fcd3166d0c89
[ "MIT" ]
4
2017-04-05T20:06:31.000Z
2020-10-29T14:50:12.000Z
#include "persistence/changequeue.h" #include <algorithm> namespace persistence { void ChangeQueue::addStream(std::shared_ptr<DataStream> dataStream) { _dataStreams.push_back(std::move(dataStream)); } bool ChangeQueue::hasUninitializedStreams() const { return std::any_of(_dataStreams.begin(), _dataStreams.end(), [](const std::shared_ptr<DataStream>& stream) { return !stream->isInitialized(); }); } void ChangeQueue::applyStreamChanges() { // Remove invalid streams (streams which no longer have a listener) _dataStreams.erase( std::remove_if(_dataStreams.begin(), _dataStreams.end(), [](auto& stream) { return !stream->isValid(); }), _dataStreams.end()); // Apply all of the strema changes std::vector<DataStreamDifferential> changes; std::unique_lock<std::mutex> lock(_streamChangesMutex); std::swap(_changeList.streamChanges, changes); lock.unlock(); for (auto& change : changes) { auto it = std::find_if(_dataStreams.begin(), _dataStreams.end(), [&](std::shared_ptr<DataStream>& ds) { return ds->streamId() == change.streamId; }); if (it != _dataStreams.end()) (*it)->applyChange(change.change); } } void ChangeQueue::addChanges(ChangeList list) { if (!list.streamChanges.empty()) { std::unique_lock<std::mutex> lock(_streamChangesMutex); std::move(list.streamChanges.begin(), list.streamChanges.end(), std::back_inserter(_changeList.streamChanges)); lock.unlock(); _streamChangesAvailableSignal(); } } void ChangeQueue::addStreamChange(int streamId, DataStreamChange change) { std::unique_lock<std::mutex> lock(_streamChangesMutex); _changeList.streamChanges.push_back({streamId, std::move(change)}); lock.unlock(); _streamChangesAvailableSignal(); } boost::signals2::connection ChangeQueue::connectToStreamChangesAvailableSignal(boost::signals2::slot<void()> slot) { return _streamChangesAvailableSignal.connect(slot); } } // namespace persistence
33.645161
120
0.682646
[ "vector" ]
ac97938b62012c66dbc5b781c6a9622e0cd83b24
886
cpp
C++
LeetCode/Explore/September-LeetCoding-Challenge-2021/#Day#22_MaximumLengthOfAConcatenatedStringWithUniqueCharacters_sol2_bit_manipulation_O(LN2^N)_time_O(1)_extra_space_52ms_8MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
1
2022-01-26T14:50:07.000Z
2022-01-26T14:50:07.000Z
LeetCode/Problems/Algorithms/#1239_MaximumLengthOfAConcatenatedStringWithUniqueCharacters_sol2_bit_manipulation_O(LN2^N)_time_O(1)_extra_space_52ms_8MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
LeetCode/Problems/Algorithms/#1239_MaximumLengthOfAConcatenatedStringWithUniqueCharacters_sol2_bit_manipulation_O(LN2^N)_time_O(1)_extra_space_52ms_8MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
class Solution { public: int maxLength(vector<string>& arr) { const int N = arr.size(); const int FULL_MASK = (1 << N) - 1; int maxLen = 0; for(int mask = 1; mask <= FULL_MASK; ++mask){ bool isValid = true; int len = 0; int visMask = 0; for(int bit = 0; isValid && bit < N; ++bit){ if((mask >> bit) & 1){ for(char c: arr[bit]){ if((visMask >> (c - 'a')) & 1){ isValid = false; } len += 1; visMask |= (1 << (c - 'a')); } } } if(isValid){ maxLen = max(maxLen, len); } } return maxLen; } };
29.533333
57
0.31377
[ "vector" ]
ac9e10998336f8e141e9fbab094f236b4f6d4268
3,313
cpp
C++
Algorithms/1222.QueensThatCanAttackTheKing/solution.cpp
stdstring/leetcode
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
[ "MIT" ]
null
null
null
Algorithms/1222.QueensThatCanAttackTheKing/solution.cpp
stdstring/leetcode
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
[ "MIT" ]
null
null
null
Algorithms/1222.QueensThatCanAttackTheKing/solution.cpp
stdstring/leetcode
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
[ "MIT" ]
null
null
null
#include <unordered_map> #include <vector> #include "gtest/gtest.h" namespace { enum class Direction {Unknown, N, W, E, S, NW, NE, SW, SE}; class Solution { public: std::vector<std::vector<int>> queensAttacktheKing(std::vector<std::vector<int>> const &queens, std::vector<int> const &king) const { std::unordered_map<Direction, std::vector<int>> attackingQueens; for (std::vector<int> const &queen : queens) { Direction direction = calcQueenDirection(queen, king); switch (direction) { case Direction::N: case Direction::NW: case Direction::NE: if (attackingQueens.count(direction) == 0 || (king[0] - queen[0]) < (king[0] - attackingQueens[direction][0])) attackingQueens[direction] = queen; break; case Direction::S: case Direction::SW: case Direction::SE: if (attackingQueens.count(direction) == 0 || (queen[0] - king[0]) < (attackingQueens[direction][0] - king[0])) attackingQueens[direction] = queen; break; case Direction::W: if (attackingQueens.count(direction) == 0 || (king[1] - queen[1]) < (king[1] - attackingQueens[direction][1])) attackingQueens[direction] = queen; break; case Direction::E: if (attackingQueens.count(direction) == 0 || (queen[1] - king[1]) < (attackingQueens[direction][1] - king[1])) attackingQueens[direction] = queen; break; case Direction::Unknown: break; } } std::vector<std::vector<int>> result; for (Direction direction : {Direction::NW, Direction::N, Direction::NE, Direction::E, Direction::SE, Direction::S, Direction::SW, Direction::W}) { if (attackingQueens.count(direction) == 1) result.push_back(attackingQueens[direction]); } return result; } private: Direction calcQueenDirection(std::vector<int> const &queen, std::vector<int> const &king) const { if (queen[0] == king[0]) return queen[1] < king[1] ? Direction::W : Direction::E; if (queen[1] == king[1]) return queen[0] < king[0] ? Direction::N : Direction::S; // straight diagonal if ((queen[0] - queen[1]) == (king[0] - king[1])) return queen[0] < king[0] ? Direction::NW : Direction::SE; // reverse diagonal if ((queen[0] + queen[1]) == (king[0] + king[1])) return queen[0] < king[0] ? Direction::NE : Direction::SW; return Direction::Unknown; } }; } namespace QueensThatCanAttackTheKingTask { TEST(QueensThatCanAttackTheKingTaskTests, Examples) { const Solution solution; ASSERT_EQ(std::vector<std::vector<int>>({{0, 1}, {3, 3}, {1, 0}}), solution.queensAttacktheKing({{0, 1}, {1, 0}, {4, 0}, {0, 4}, {3, 3}, {2, 4}}, {0, 0})); ASSERT_EQ(std::vector<std::vector<int>>({{2, 2}, {3, 4}, {4, 4}}), solution.queensAttacktheKing({{0, 0}, {1, 1}, {2, 2}, {3, 4}, {3, 5}, {4, 4}, {4, 5}}, {3, 3})); } }
39.440476
167
0.53275
[ "vector" ]
aca4bcfafbcf4f91d909b3ec88a3c3a8379f46f8
5,702
cpp
C++
IMS_Panel.cpp
TheNewBob/IMS2
572dcfd4c3621458f01278713437c2aca526d2e6
[ "MIT" ]
2
2018-01-28T20:07:52.000Z
2018-03-01T22:41:39.000Z
IMS_Panel.cpp
TheNewBob/IMS2
572dcfd4c3621458f01278713437c2aca526d2e6
[ "MIT" ]
6
2017-08-26T10:24:48.000Z
2018-01-28T13:45:34.000Z
IMS_Panel.cpp
TheNewBob/IMS2
572dcfd4c3621458f01278713437c2aca526d2e6
[ "MIT" ]
null
null
null
#include "Common.h" #include "GUI_Common.h" #include "GUIentity.h" #include "GUImanager.h" #include "Events.h" #include "IMS.h" #include "GUI_Surface_Base.h" #include "GUI_Surface.h" #include "GUI_BaseElement.h" #include "GUI_Page.h" #include "IMS_RootPage.h" #include "GUI_MainDisplay.h" #include "LayoutElement.h" #include "GUI_Layout.h" #include "GUI_Panel.h" #include "IMS_EngineeringPanel.h" bool IMS2::clbkLoadPanel2D(int id, PANELHANDLE hPanel, DWORD viewW, DWORD viewH) { // ReleaseSurfaces(); switch (id) { case FLIGHTPANEL: DefineMainPanel (hPanel); SetPanelScale (hPanel, viewW, viewH); oapiSetPanelNeighbours (-1, -1, -1, 1); // register areas for panel 0 here SetCameraDefaultDirection (_V(0,0,1)); // forward oapiCameraSetCockpitDir (0,0); // look forward //redraw areas GUI->SetCurPanelId(id); GUI->RedrawCurrentPanel(); break; default: GUI->LoadPanel(id, hPanel); break; } return true; } void IMS2::DefineMainPanel(PANELHANDLE hPanel) { static MESHHANDLE hPanelMesh = NULL; static DWORD panelW = 1280; static DWORD panelH = 800; float fpanelW = (float)panelW; float fpanelH = (float)panelH; static DWORD texW = 2048; static DWORD texH = 1024; float ftexW = (float)texW; float ftexH = (float)texH; static NTVERTEX VTX[4] = { { 0, 0,0, 0,0,0, 0.0f,1.0f-fpanelH/ftexH}, { 0,fpanelH,0, 0,0,0, 0.0f,1.0f}, {fpanelW,fpanelH,0, 0,0,0, fpanelW/ftexW,1.0f}, {fpanelW, 0,0, 0,0,0, fpanelW/ftexW,1.0f-fpanelH/ftexH} }; static WORD IDX[6] = { 0,2,1, 2,0,3 }; if (hPanelMesh) oapiDeleteMesh (hPanelMesh); hPanelMesh = oapiCreateMesh (0,0); MESHGROUP grp = {VTX, IDX, 4, 6, 0, 0, 0, 0, 0}; oapiAddMeshGroup (hPanelMesh, &grp); SetPanelBackground (hPanel, &pilotPanelBG, 1, hPanelMesh, panelW, panelH, 0, PANEL_ATTACH_BOTTOM | PANEL_MOVEOUT_BOTTOM | PANEL_MOVEOUT_TOP); } void IMS2::DefineEngPanel(PANELHANDLE hPanel, DWORD width, DWORD height) { float fpanelW = (float)width; float fpanelH = (float)height; static DWORD texW = width; static DWORD texH = height; float ftexW = (float)texW; float ftexH = (float)texH; static NTVERTEX VTX[4] = { { 0, 0,0, 0,0,0, 0.0f,0.0f}, { 0,fpanelH,0, 0,0,0, 0.0f,fpanelH/ftexH}, {fpanelW,fpanelH,0, 0,0,0, fpanelW/ftexW,fpanelH/ftexH}, {fpanelW, 0,0, 0,0,0, fpanelW/ftexW,0.0f} }; static WORD IDX[6] = { 0,2,1, 2,0,3 }; /* if (hPanelMesh) oapiDeleteMesh (hPanelMesh); hPanelMesh = oapiCreateMesh (0,0); MESHGROUP grp = {VTX, IDX, 4, 6, 0, 0, 0, 0, 0}; oapiAddMeshGroup (hPanelMesh, &grp); SetPanelBackground (hPanel, &engPanelBG, 1, hPanelMesh, width, height, 0, PANEL_ATTACH_BOTTOM | PANEL_MOVEOUT_BOTTOM | PANEL_MOVEOUT_TOP); //register GUI_Surface with Orbiter GUI->RegisterSurfaceWithOrbiter(mainDispSurface, hPanel, engPanelBG); // TODO: method has changed object. Check if this still needs to be executed. //mainDispSurface->UpdateDockedVesselsList(dockedVesselsList);*/ } void IMS2::SetPanelScale (PANELHANDLE hPanel, DWORD viewW, DWORD viewH) { double defscale = (double)viewW/1680; double extscale = max (defscale, 1.0); SetPanelScaling (hPanel, defscale, extscale); } bool IMS2::clbkPanelRedrawEvent (int id, int event, SURFHANDLE surf, void *context) { if (context) { GUI_Surface* cursurf = (GUI_Surface*)context; cursurf->Redraw2D(surf); return true; } return false; } bool IMS2::clbkPanelMouseEvent (int id, int event, int mx, int my, void *context) { if (oapiGetFocusInterface() != this) return false; //if element is triggered while this vessel is not focused, ignore if (context) { GUI_Surface *cursurf = (GUI_Surface*)context; return cursurf->ProcessMouse2D (GUI->GetEvent(event), mx, my); } return false; } void IMS2::InitialiseGUI() { //initalising GUI for vessel // hPanelMesh = NULL; GUI = new GUImanager(this); DWORD screenWidth, screenHeight, depth; oapiGetViewportSize(&screenWidth, &screenHeight, &depth); //create panel backgrounds if they are not yet initialised IMS_EngineeringPanel *engpanel = new IMS_EngineeringPanel(120, 64, screenWidth, screenHeight, this, GUI); GUI->RegisterGUIPanel(engpanel); /* if (engPanelBG == NULL) { engPanelBG = oapiCreateSurfaceEx(screenWidth, screenHeight, OAPISURFACE_TEXTURE); GUI_ElementStyle *defaultstyle = GUI->GetStyle("default"); oapiColourFill(engPanelBG, oapiGetColour(defaultstyle->FillColor().r, defaultstyle->FillColor().g, defaultstyle->FillColor().b), 0, 0, screenWidth, screenHeight); }*/ if (pilotPanelBG == NULL) { pilotPanelBG = oapiCreateSurfaceEx(1680, 1050, OAPISURFACE_TEXTURE); GUI_ElementStyle *defaultstyle = GUI->GetStyle("default"); oapiColourFill(pilotPanelBG, oapiGetColour(defaultstyle->FillColor().r, defaultstyle->FillColor().g, defaultstyle->FillColor().b), 0, 0, 1680, 1050); } //create SwingShot panel elements /* RECT maindisplayrect = _R(screenWidth * 0.7, screenHeight * 0.4, screenWidth * 0.997, screenHeight * 0.997); //RECT maindisplayrect = _R(1176, 428, 1676, 1046); GUI_MainDisplay *maindisplay = new GUI_MainDisplay(this, _R(0, 0, maindisplayrect.right - maindisplayrect.left, maindisplayrect.bottom - maindisplayrect.top), GUI->GetStyle(STYLE_PAGE)); mainDispSurface = new GUI_Surface(this, ENGINEERINGPANEL, GUI, maindisplay); GUI->RegisterGUISurface(mainDispSurface, GUI_MAIN_DISPLAY, maindisplayrect);*/ } void IMS2::DestroyGUI() { // if (hPanelMesh) oapiDeleteMesh (hPanelMesh); delete GUI; } void IMS2::updateGui() { GUI->Update(); }
28.08867
187
0.691512
[ "object" ]
aca4c0d9c1971530e9c006a01b1ed91099e1119a
4,454
cpp
C++
src/sdm/utils/linear_algebra/hyperplane/oalpha.cpp
SDMStudio/sdms
43a86973081ffd86c091aed69b332f0087f59361
[ "MIT" ]
null
null
null
src/sdm/utils/linear_algebra/hyperplane/oalpha.cpp
SDMStudio/sdms
43a86973081ffd86c091aed69b332f0087f59361
[ "MIT" ]
null
null
null
src/sdm/utils/linear_algebra/hyperplane/oalpha.cpp
SDMStudio/sdms
43a86973081ffd86c091aed69b332f0087f59361
[ "MIT" ]
null
null
null
#include <sdm/utils/linear_algebra/hyperplane/oalpha.hpp> namespace sdm { oAlpha::oAlpha(double default_value) : AlphaVector(default_value) { } bool oAlpha::isDominated(const Hyperplane &other) const { for (const auto &o_balpha : this->repr) { for (const auto &x_value : o_balpha.second) { if (x_value.second > other.getValueAt(x_value.first, o_balpha.first)) return false; } } return true; } double oAlpha::getValueAt(const std::shared_ptr<State> &x, const std::shared_ptr<HistoryInterface> &o) const { auto iter = this->repr.find(o); if (iter == this->repr.end()) return this->default_value; else return iter->second.getValueAt(x); } void oAlpha::setValueAt(const std::shared_ptr<State> &x, const std::shared_ptr<HistoryInterface> &o, double value) { auto iter = this->repr.find(o); if (iter == this->repr.end()) { this->repr.emplace(o, MappedVector<std::shared_ptr<State>, double>(default_value)); } this->repr.at(o).setValueAt(x, value); } double oAlpha::getBetaValueAt(const std::shared_ptr<State> &x, const std::shared_ptr<HistoryInterface> &o, const std::shared_ptr<Action> &u, const std::shared_ptr<POMDPInterface> &pomdp, number t) { // Compute \beta_t(x,o,u) = R(x,u) + \gamma \sum_{y, z} p^{uz}_{xy} \alpha_{t+1}(y, (o,u,z)) double next_expected_value = 0.0; // Go over all hidden state reachable next state for (const auto &y : pomdp->getReachableStates(x, u, t)) { // Go over all observation reachable observation for (const auto &z : pomdp->getReachableObservations(x, u, y, t)) { // Determine the best next hyperplan for the next belief and compute the dynamics and probability of this best next hyperplan next_expected_value += this->getValueAt(y, o->expand(z)) * pomdp->getDynamics(x, u, y, z, t); } } auto res = pomdp->getReward(x, u, t) + pomdp->getDiscount(t) * next_expected_value; return res; } size_t oAlpha::hash(double precision) const { if (precision < 0) precision = oAlpha::PRECISION; size_t seed = 0; std::map<std::shared_ptr<HistoryInterface>, MappedVector<std::shared_ptr<State>, double>> ordered(this->repr.begin(), this->repr.end()); for (const auto &v : ordered) { // Combine the hash of the current vector with the hashes of the previous ones sdm::hash_combine(seed, v.first); sdm::hash_combine(seed, std::hash<MappedVector<std::shared_ptr<State>, double>>()(v.second, precision)); } return seed; } bool oAlpha::isEqual(const oAlpha &other, double precision) const { if (other.size() > this->size()) { return other.isEqual(*this, precision); } if (precision < 0) precision = oAlpha::PRECISION; for (const auto &o_balpha : this->repr) { for (const auto &x_value : o_balpha.second) { if (std::abs(x_value.second - other.getValueAt(x_value.first, o_balpha.first)) > precision) { return false; } } } return true; } bool oAlpha::isEqual(const std::shared_ptr<Hyperplane> &other, double precision) const { auto other_oalpha = std::static_pointer_cast<oAlpha>(other); if (other_oalpha == nullptr) return false; else return this->isEqual(*other_oalpha, precision); } size_t oAlpha::size() const { return this->repr.size(); } std::string oAlpha::str() const { std::ostringstream res; res << "<plan>" << std::endl; for (const auto &hist_belief : this->repr) { res << "\t<" << hist_belief.first->short_str() << ">" << std::endl; for (const auto &b_value : hist_belief.second) { res << "\t\t" << b_value.first->str() << " : " << b_value.second << std::endl; } res << "\t</>" << std::endl; } res << "</plan>" << std::endl; return res.str(); } } // namespace sdm
33.238806
200
0.555456
[ "vector" ]
aca4c57245aba6738be7769dc2bc3ec7c4339360
69,157
cpp
C++
multimedia/dshow/filters/lin21dec2/l21ddraw.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
multimedia/dshow/filters/lin21dec2/l21ddraw.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
multimedia/dshow/filters/lin21dec2/l21ddraw.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
// Copyright (c) 2000 Microsoft Corporation. All Rights Reserved. // // DirectShow Line 21 Decoder 2 Filter: drawing-related base class code // #include <streams.h> #include <windowsx.h> #include <initguid.h> #ifdef FILTER_DLL DEFINE_GUID(IID_IDirectDraw7, 0x15e65ec0,0x3b9c,0x11d2,0xb9,0x2f,0x00,0x60,0x97,0x97,0xea,0x5b); #endif #include <IL21Dec.h> #include "L21DBase.h" #include "L21DDraw.h" #include "L21Decod.h" // // CLine21DecDraw: class for drawing details to output caption text to bitmap // CLine21DecDraw::CLine21DecDraw(void) { DbgLog((LOG_TRACE, 5, TEXT("CLine21DecDraw::CLine21DecDraw()"))) ; // Init some of the members m_pDDrawObjUnk = NULL ; m_lpDDSOutput = NULL ; m_lpDDSNormalFontCache = NULL ; m_lpDDSItalicFontCache = NULL ; m_lpDDSSpecialFontCache = NULL ; m_lpDDSScratch = NULL ; m_lpBMIOut = NULL ; m_uBMIOutSize = 0 ; m_lpBMIIn = NULL ; m_uBMIInSize = 0 ; m_lpBltList = NULL ; m_iPixelOffset = 0 ; // Create an initial input BITMAPINFO struct to start with InitBMIData() ; // Init the width and height based on prelim size so that we can compare // any size changes later if (m_lpBMIIn) // InitBMIData() succeeded as it should { m_lWidth = m_lpBMIIn->bmiHeader.biWidth ; m_lHeight = m_lpBMIIn->bmiHeader.biHeight ; } else // InitBMIData() failed!!! { m_lWidth = 640 ; m_lHeight = 480 ; } // check if Lucida Console is available (the callback sets the m_bUseTTFont flag) CheckTTFont() ; // m_bUseTTFont is set inside this function // // We are not supposed to use the 10% of the border on the top/bottom and left/right. // But leaving 10% on each side for a 320x240 image when we are using a non-TT font, // like "Terminal", leaves very little room for showing captions. So I leave only 5% // on each side with non-TT font. // By doing this I am violating the spec, but it's a necessary evil. // When TT font (Lucida Console) is available, we leave 10% border on every side. // if ( IsTTFont() ) m_iBorderPercent = 20 ; else m_iBorderPercent = 10 ; // Set the border amounts based on output size and font type (TT or not) m_iHorzOffset = m_lWidth * m_iBorderPercent / 200 ; // default m_iVertOffset = m_lHeight * m_iBorderPercent / 200 ; // default // Use char size appropriate for the output bitmap size if (! CharSizeFromOutputSize(m_lWidth, m_lHeight, &m_iCharWidth, &m_iCharHeight) ) { DbgLog((LOG_TRACE, 1, TEXT("CharSizeFromOutputSize(%ld,%ld,,) failed. Using default char size."), m_lWidth, m_lHeight)) ; ASSERT(!TEXT("Char size selection failed")) ; // Use dafult char size m_iCharWidth = DEFAULT_CHAR_WIDTH ; m_iCharHeight = DEFAULT_CHAR_HEIGHT ; } ASSERT(m_iCharWidth * (MAX_CAPTION_COLUMNS + 2) <= m_lWidth) ; ASSERT(m_iCharHeight * MAX_CAPTION_ROWS <= m_lHeight) ; m_iScrollStep = CalcScrollStepFromCharHeight() ; // Flags to know if output should be turn on/off and/or sent down m_bOutputClear = TRUE ; // output buffer is clear on start m_bNewOutBuffer = TRUE ; // output buffer is new to start with // // Init the COLORREF array of 7 foreground colors as just RGB values // m_acrFGColors[0] = RGB(0xFF, 0xFF, 0xFF) ; // white m_acrFGColors[1] = RGB( 0x0, 0xFF, 0x0) ; // green m_acrFGColors[2] = RGB( 0x0, 0x0, 0xFF) ; // blue m_acrFGColors[3] = RGB( 0x0, 0xFF, 0xFF) ; // cyan m_acrFGColors[4] = RGB(0xFF, 0x0, 0x0) ; // red m_acrFGColors[5] = RGB(0xFF, 0xFF, 0x0) ; // yellow m_acrFGColors[6] = RGB(0xFF, 0x0, 0xFF) ; // magenta m_idxFGColors[0] = 0x0F; // white m_idxFGColors[1] = 0x0A; // green m_idxFGColors[2] = 0x0C; // blue m_idxFGColors[3] = 0x0E; // cyan m_idxFGColors[4] = 0x09; // red m_idxFGColors[5] = 0x0B; // yellow m_idxFGColors[6] = 0x0D; // magenta // Init text color (FG, BG, opacity), last CC char printed etc. InitColorNLastChar() ; // Init the list of caption chars InitCharSet() ; // Font cache needs to be built before any output SetFontUpdate(true) ; } CLine21DecDraw::~CLine21DecDraw(void) { DbgLog((LOG_TRACE, 5, TEXT("CLine21DecDraw::~CLine21DecDraw()"))) ; // Delete the cached fonts if (m_lpDDSNormalFontCache) { m_lpDDSNormalFontCache->Release() ; m_lpDDSNormalFontCache = NULL ; } if (m_lpDDSItalicFontCache ) { m_lpDDSItalicFontCache->Release() ; m_lpDDSItalicFontCache = NULL ; } if (m_lpDDSSpecialFontCache) { m_lpDDSSpecialFontCache->Release() ; m_lpDDSSpecialFontCache = NULL ; } if (m_lpDDSScratch) { m_lpDDSScratch->Release() ; m_lpDDSScratch = NULL ; } // release BMI data pointer if (m_lpBMIOut) delete m_lpBMIOut ; m_uBMIOutSize = 0 ; if (m_lpBMIIn) delete m_lpBMIIn ; m_uBMIInSize = 0 ; } int CALLBACK CLine21DecDraw::EnumFontProc(ENUMLOGFONTEX *lpELFE, NEWTEXTMETRIC *lpNTM, int iFontType, LPARAM lParam) { DbgLog((LOG_TRACE, 5, TEXT("CLine21DecDraw::EnumFontProc(0x%lx, 0x%lx, %d, %ld)"), lpELFE, lpNTM, iFontType, lParam)) ; // Just verify that we got a valid TT font if ( !(lpELFE->elfLogFont.lfCharSet & 0xFFFFFF00) && !(lpELFE->elfLogFont.lfPitchAndFamily & 0xFFFFFF00) && !(iFontType & 0xFFFF0000) ) { ASSERT(lpELFE->elfLogFont.lfPitchAndFamily & (FIXED_PITCH | FF_MODERN)) ; ((CLine21DecDraw *) (LPVOID) lParam)->m_lfChar = lpELFE->elfLogFont ; ((CLine21DecDraw *) (LPVOID) lParam)->m_bUseTTFont = TRUE ; return 1 ; } ASSERT(FALSE) ; // Weird!!! We should know about it. return 0 ; } void CLine21DecDraw::CheckTTFont(void) { DbgLog((LOG_TRACE, 5, TEXT("CLine21DecDraw::CheckTTFont()"))) ; CAutoLock Lock(&m_csL21DDraw) ; m_bUseTTFont = FALSE ; // assume not available ZeroMemory(&m_lfChar, sizeof(LOGFONT)) ; lstrcpy(m_lfChar.lfFaceName, TEXT("Lucida Console")) ; m_lfChar.lfCharSet = ANSI_CHARSET ; m_lfChar.lfPitchAndFamily = 0 ; HDC hDC = CreateDC(TEXT("Display"),NULL, NULL, NULL) ; // a temp DC on the desktop if (NULL == hDC) { DbgLog((LOG_TRACE, 1, TEXT("ERROR: Couldn't create DC for font enum"))) ; ASSERT(hDC) ; return ; } EnumFontFamiliesEx(hDC, &m_lfChar, (FONTENUMPROC) EnumFontProc, (LPARAM)(LPVOID)this, 0) ; DeleteDC(hDC) ; // done with temp DC } void CLine21DecDraw::InitColorNLastChar(void) { DbgLog((LOG_TRACE, 5, TEXT("CLine21DecDraw::InitColorNLastChar()"))) ; CAutoLock Lock(&m_csL21DDraw) ; // Last caption char init m_ccLast.SetChar(0) ; m_ccLast.SetEffect(0) ; m_ccLast.SetColor(AM_L21_FGCOLOR_WHITE) ; // By default we use white text on a black opaque background m_uColorIndex = AM_L21_FGCOLOR_WHITE ; // For now assume an opaque background m_bOpaque = TRUE ; m_dwBackground = 0x80000000 ; // 0xFF000000 // We go back to white chars with normal style ChangeFont(AM_L21_FGCOLOR_WHITE, FALSE, FALSE) ; } void CLine21DecDraw::InitCharSet(void) { DbgLog((LOG_TRACE, 5, TEXT("CLine21DecDraw::InitCharSet()"))) ; CAutoLock Lock(&m_csL21DDraw) ; // First init with the worst case chars -- last 8 spaces blanked out // 1 2 3 4 5 6 7 8 9 10 11 12 // 01 23456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 TCHAR *lpszChars = TEXT(" !\"#$%&'()A+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[E]IOUabcdefghijklmnopqrstuvwxyzC NN A EAEIOU ") ; for (int i = 0 ; i < 120 ; i++) { m_lpwCharSet[i] = MAKECCCHAR(0, lpszChars[i]) ; } m_lpwCharSet[120] = MAKECCCHAR(0, 0) ; // Change a few special chars embedded in the standard char range m_lpwCharSet[ 10] = 0x00e1 ; // 'a' with an acute accent m_lpwCharSet[ 60] = 0x00e9 ; // 'e' with an acute accent m_lpwCharSet[ 62] = 0x00ed ; // 'i' with an acute accent m_lpwCharSet[ 63] = 0x00f3 ; // 'o' with an acute accent m_lpwCharSet[ 64] = 0x00fa ; // 'u' with an acute accent m_lpwCharSet[ 91] = 0x00e7 ; // 'c' with cedilla m_lpwCharSet[ 92] = 0x00f7 ; // division sign m_lpwCharSet[ 93] = 0x00d1 ; // 'N' with tilde m_lpwCharSet[ 94] = 0x00f1 ; // 'n' with tilde m_lpwCharSet[ 95] = 0x2588 ; // solid block // Then fill in the range of real special chars m_lpwCharSet[ 96] = 0x00ae ; // 30h m_lpwCharSet[ 97] = 0x00b0 ; // 31h m_lpwCharSet[ 98] = 0x00bd ; // 32h m_lpwCharSet[ 99] = 0x00bf ; // 33h m_lpwCharSet[100] = 0x2122 ; // 34h m_lpwCharSet[101] = 0x00a2 ; // 35h m_lpwCharSet[102] = 0x00a3 ; // 36h m_lpwCharSet[103] = 0x266b ; // 37h m_lpwCharSet[104] = 0x00e0 ; // 38h m_lpwCharSet[105] = 0x0000 ; // 39h m_lpwCharSet[106] = 0x00e8 ; // 3ah m_lpwCharSet[107] = 0x00e2 ; // 3bh m_lpwCharSet[108] = 0x00ea ; // 3ch m_lpwCharSet[109] = 0x00ee ; // 3dh m_lpwCharSet[110] = 0x00f4 ; // 3eh m_lpwCharSet[111] = 0x00fb ; // 3fh } bool CLine21DecDraw::InitBMIData(void) { DbgLog((LOG_TRACE, 5, TEXT("CLine21DecDraw::InitBMIData()"))) ; CAutoLock Lock(&m_csL21DDraw) ; HDC hDCTemp = GetDC(NULL) ; if (NULL == hDCTemp) { ASSERT(!TEXT("GetDC(NULL) failed")) ; return false ; } WORD wPlanes = (WORD)GetDeviceCaps(hDCTemp, PLANES) ; WORD wBitCount = (WORD)GetDeviceCaps(hDCTemp, BITSPIXEL) ; ReleaseDC(NULL, hDCTemp) ; wPlanes = 1 ; wBitCount = wBitCount ; m_uBMIInSize = sizeof(BITMAPINFOHEADER) ; // at least // Increase BITMAPINFO struct size based of bpp value if (8 == wBitCount) // palettized mode m_uBMIInSize += 256 * sizeof(RGBQUAD) ; // for palette entries else m_uBMIInSize += 3 * sizeof(RGBQUAD) ; // space for bitmasks, if needed m_lpBMIIn = (LPBITMAPINFO) new BYTE[m_uBMIInSize] ; if (NULL == m_lpBMIIn) { ASSERT(!TEXT("Out of memory for BMIIn buffer")) ; return false ; } m_lpBMIIn->bmiHeader.biSize = sizeof(BITMAPINFOHEADER) ; m_lpBMIIn->bmiHeader.biWidth = CAPTION_OUTPUT_WIDTH ; m_lpBMIIn->bmiHeader.biHeight = CAPTION_OUTPUT_HEIGHT ; m_lpBMIIn->bmiHeader.biPlanes = wPlanes ; m_lpBMIIn->bmiHeader.biBitCount = wBitCount ; if (16 == m_lpBMIIn->bmiHeader.biBitCount) // assume 565 m_lpBMIIn->bmiHeader.biCompression = BI_BITFIELDS ; else m_lpBMIIn->bmiHeader.biCompression = BI_RGB ; m_lpBMIIn->bmiHeader.biSizeImage = DIBSIZE(m_lpBMIIn->bmiHeader) ; m_lpBMIIn->bmiHeader.biXPelsPerMeter = 0 ; m_lpBMIIn->bmiHeader.biYPelsPerMeter = 0 ; m_lpBMIIn->bmiHeader.biClrUsed = 0 ; m_lpBMIIn->bmiHeader.biClrImportant = 0 ; // // If we are in bitfield mode, set the bmiColors values too. // If we are in palettized mode, pickthe system palette. // DWORD *pdw = (DWORD *) m_lpBMIIn->bmiColors ; switch (m_lpBMIIn->bmiHeader.biBitCount) { case 8: // GetPaletteForFormat((LPBITMAPINFOHEADER) m_lpBMIIn) ; ASSERT(8 != m_lpBMIIn->bmiHeader.biBitCount) ; return false ; // break ; case 16: // by deafult 565 if (m_lpBMIIn->bmiHeader.biCompression == BI_BITFIELDS) // 565 { pdw[iRED] = bits565[iRED] ; pdw[iGREEN] = bits565[iGREEN] ; pdw[iBLUE] = bits565[iBLUE] ; } else // BI_RGB: 555 { pdw[iRED] = bits555[iRED] ; pdw[iGREEN] = bits555[iGREEN] ; pdw[iBLUE] = bits555[iBLUE] ; } break ; case 24: // clear all... pdw[iRED] = pdw[iGREEN] = pdw[iBLUE] = 0 ; break ; case 32: // set the masks if (m_lpBMIIn->bmiHeader.biCompression == BI_BITFIELDS) { pdw[iRED] = bits888[iRED] ; pdw[iGREEN] = bits888[iGREEN] ; pdw[iBLUE] = bits888[iBLUE] ; } else // BI_RGB { pdw[iRED] = pdw[iGREEN] = pdw[iBLUE] = 0 ; } break ; default: // don't care ASSERT(!TEXT("Bad biBitCount!!")) ; break ; } return true ; } BOOL CLine21DecDraw::SetBackgroundColor(DWORD dwBGColor) { DbgLog((LOG_TRACE, 5, TEXT("CLine21DecDraw::SetBackgroundColor(0x%lx)"), dwBGColor)) ; CAutoLock Lock(&m_csL21DDraw) ; BOOL bResult = TRUE ; if (m_dwBackground != dwBGColor) { m_dwBackground = dwBGColor ; SetFontUpdate(true) ; // need to rebuild font caches for new BG color } return true ; // bResult ; } // Create normal, italic and special (color, U or I+U) font caches bool CLine21DecDraw::InitFont(void) { DbgLog((LOG_TRACE, 5, TEXT("CLine21DecDraw::InitFont()"))) ; CAutoLock Lock(&m_csL21DDraw) ; // Create a normal font to find out the char size etc. HFONT hFont = CreateCCFont(0, m_iCharHeight, FALSE, FALSE) ; if (NULL == hFont) // font creation failed { return false ; } // // The following magic is necessary to get GDI to rasterize // the font with anti-aliasing switched on when we later use // the font in a DDraw Surface. The doc's say that this is only // necessary in Win9X - but Win2K seems to require it too. // SIZE size ; LPCTSTR lpszStr = TEXT("ABCDEFGHIJKLMNOPQRSTUVWXYZ") ; HDC hdcWin = GetDC(NULL) ; HFONT hFontOld = (HFONT)SelectObject(hdcWin, hFont) ; // select new font GetTextExtentPoint32(hdcWin, lpszStr, lstrlen(lpszStr), &size) ; size.cx /= lstrlen(lpszStr) ; // get per char width // Restore font to original and delete font now hFont = (HFONT)SelectObject(hdcWin, hFontOld) ; DeleteObject(hFont) ; // // Make sure that the font doesn't get too big. // if (size.cx * FONTCACHELINELENGTH > 1024) { DbgLog((LOG_TRACE, 1, TEXT("WARNING: Text size (%d) is too big. Can't create font."), size.cx)) ; ReleaseDC(NULL, hdcWin) ; // release new DC created here return false ; } // Set the char size m_iCharWidth = size.cx ; // iMaxWidth ; m_iCharHeight = size.cy ; // Also re-calc scroll step value now m_iScrollStep = CalcScrollStepFromCharHeight() ; // Calculate the horizontal offset and vertical offset of the CC area within // the output DDraw surface int iCCRectWidth = m_iCharWidth * (MAX_CAPTION_COLUMNS + 2) ; // +2 for leading and trailing space iCCRectWidth = DWORDALIGN(iCCRectWidth) ; // make sure to DWORD align it m_iHorzOffset = min((long)(m_lHeight * m_iBorderPercent / 200), // border % is for 2 sides (m_lWidth - iCCRectWidth) / 2) ; // iCCRectHeight = m_iCharHeight * MAX_CAPTION_LINES ; // max 4 lines of caption shown // Vertically we want to leave 10% of the height or leave just enough space // to accomodate all the caption lines m_iVertOffset = min((long)(m_lHeight * m_iBorderPercent / 200), // border % is for 2 sides (m_lHeight - (long)(m_iCharHeight * MAX_CAPTION_ROWS)) / 2) ; // Create white color normal and italic font caches now bool bResult = true ; DWORD dwTextColor = m_uColorIndex ; DWORD dwBGColor = 0xFF000000 ; // m_dwBackground ; DWORD dwOpacity = m_bOpaque ? OPAQUE : 0 ; if (m_lpDDSScratch) { m_lpDDSScratch->Release() ; m_lpDDSScratch = NULL ; } if (m_lpDDSNormalFontCache) { m_lpDDSNormalFontCache->Release() ; m_lpDDSNormalFontCache = NULL ; } if (m_lpDDSItalicFontCache) { m_lpDDSItalicFontCache->Release() ; m_lpDDSItalicFontCache = NULL ; } bResult &= CreateScratchFontCache(&m_lpDDSScratch) ; bResult &= CreateFontCache(&m_lpDDSNormalFontCache, dwTextColor, dwBGColor, dwOpacity, FALSE, FALSE) ; bResult &= CreateFontCache(&m_lpDDSItalicFontCache, dwTextColor, dwBGColor, dwOpacity, TRUE, FALSE) ; // We don't create any special font cache, because we don't what will be // required. So we just reset it here. if (m_lpDDSSpecialFontCache) { m_lpDDSSpecialFontCache->Release() ; m_lpDDSSpecialFontCache = NULL ; } // // We set the current font cache to the normal font cache by default // m_lpBltList = m_lpDDSNormalFontCache ; // // Now release the resources acquired locally // ReleaseDC(NULL, hdcWin) ; // release the locally created DC // DeleteObject(hFont) ; // delete font // If we successfully (re-)inited the font cache, reset the flag if (bResult) { SetFontUpdate(false) ; } return bResult ; // return status } HFONT CLine21DecDraw::CreateCCFont(int iFontWidth, int iFontHeight, BOOL bItalic, BOOL bUnderline) { DbgLog((LOG_TRACE, 5, TEXT("CLine21DecDraw::CreateCCFont(%d, %d, %s, %s)"), iFontWidth, iFontHeight, bItalic ? TEXT("T") : TEXT("F"), bUnderline ? TEXT("T") : TEXT("F"))) ; // // Initialize LOGFONT structure to create an "anti-aliased" Lucida Console font // LOGFONT lfChar ; ZeroMemory(&lfChar, sizeof(lfChar)) ; // Init a LOGFONT struct in m_lfChar if (IsTTFont()) { DbgLog((LOG_TRACE, 5, TEXT("Got Lucida Console TT Font"))) ; lstrcpy(lfChar.lfFaceName, TEXT("Lucida Console")) ; if (0 == iFontWidth) { lfChar.lfHeight = -iFontHeight ; } else { lfChar.lfHeight = iFontHeight ; lfChar.lfWidth = iFontWidth ; } // m_lfChar.lfCharSet set in CheckTTFont() // m_lfChar.lfPitchAndFamily set in CheckTTFont() lfChar.lfCharSet = m_lfChar.lfCharSet ; lfChar.lfPitchAndFamily = m_lfChar.lfPitchAndFamily ; } else // no Lucida Console; use 8x12 Terminal font { DbgLog((LOG_TRACE, 1, TEXT("Did NOT get Lucida Console TT Font. Will use Terminal"))) ; lfChar.lfHeight = iFontHeight ; lfChar.lfWidth = iFontWidth ; lfChar.lfCharSet = ANSI_CHARSET ; lfChar.lfPitchAndFamily = FIXED_PITCH | FF_MODERN ; lstrcpy(lfChar.lfFaceName, TEXT("Terminal")) ; } lfChar.lfWeight = FW_NORMAL ; lfChar.lfItalic = bItalic ? TRUE : FALSE ; lfChar.lfUnderline = bUnderline ? TRUE : FALSE ; lfChar.lfOutPrecision = OUT_STRING_PRECIS ; lfChar.lfClipPrecision = CLIP_STROKE_PRECIS ; lfChar.lfQuality = ANTIALIASED_QUALITY ; HFONT hFont = CreateFontIndirect(&lfChar) ; if ( !hFont ) { DbgLog((LOG_ERROR, 1, TEXT("WARNING: CreateFontIndirect('Lucida Console') failed (Error %ld)"), GetLastError())) ; return NULL ; } return hFont ; } bool CLine21DecDraw::CreateScratchFontCache(LPDIRECTDRAWSURFACE7* lplpDDSFontCache) { DbgLog((LOG_TRACE, 5, TEXT("CLine21DecDraw::CreateScratchFontCache(0x%lx)"), lplpDDSFontCache)) ; CAutoLock Lock(&m_csL21DDraw) ; // // Create the DDraw ARGB32/ARGB4444 surface in "system" memory to be used as // a scratch font cache, where the chars will be drawn; then the alpha value // will be set and the resulting bits will be written into the final // destination font cache. This will speed up font cache creation a lot, as // it avoid the read-modify-write cycle on VRAM font caches. // HRESULT hr = DDrawARGBSurfaceInit(lplpDDSFontCache, TRUE /* use SysMem */, FALSE /* Texture */, FONTCACHELINELENGTH * (m_iCharWidth + INTERCHAR_SPACE), FONTCACHENUMLINES * m_iCharHeight) ; if (FAILED(hr)) { DbgLog((LOG_TRACE, 1, TEXT("DDrawARGBSurfaceInit() failed for scratch (Error 0x%lx)"), hr)) ; return false ; } // Clear the scratch surface before drawing the chars on it DDBLTFX ddFX ; ZeroMemory(&ddFX, sizeof(ddFX)) ; ddFX.dwSize = sizeof(ddFX) ; ddFX.dwFillColor = 0x00000000 ; hr = (*lplpDDSFontCache)->Blt(NULL, NULL, NULL, DDBLT_COLORFILL, &ddFX) ; if (FAILED(hr)) { DbgLog((LOG_TRACE, 1, TEXT("Blt() to clear scratch font cache failed (Error 0x%lx)"), hr)) ; return false ; } return true ; } bool CLine21DecDraw::CreateFontCache(LPDIRECTDRAWSURFACE7* lplpDDSFontCache, DWORD dwTextColor, DWORD dwBGColor, DWORD dwOpacity, BOOL bItalic, BOOL bUnderline) { DbgLog((LOG_TRACE, 5, TEXT("CLine21DecDraw::CreateFontCache(0x%lx, 0x%lx, 0x%lx, 0x%lx, %s, %s)"), lplpDDSFontCache, dwTextColor, dwBGColor, dwOpacity, bItalic ? TEXT("T") : TEXT("F"), bUnderline ? TEXT("T") : TEXT("F"))) ; CAutoLock Lock(&m_csL21DDraw) ; HRESULT hr ; // // First make sure the scratch font cache exists; otherwise try to create it. // if (NULL == m_lpDDSScratch) { bool bResult = CreateScratchFontCache(&m_lpDDSScratch) ; if (! bResult ) { return false ; } } // // Delete the old font cache // if (*lplpDDSFontCache) { (*lplpDDSFontCache)->Release() ; *lplpDDSFontCache = NULL ; } // // Create the DDraw ARGB32/ARGB4444 surface in "video" memory to be used as // font cache // hr = DDrawARGBSurfaceInit(lplpDDSFontCache, FALSE /* use VRAM */, TRUE /* Texture */, FONTCACHELINELENGTH * (m_iCharWidth + INTERCHAR_SPACE), FONTCACHENUMLINES * m_iCharHeight) ; if (FAILED(hr)) { DbgLog((LOG_TRACE, 1, TEXT("DDrawARGBSurfaceInit() failed (Error 0x%lx)"), hr)) ; return false ; } // Get the DC for the scratch font cache (DDraw surface) HDC hdcDest ; m_lpDDSScratch->GetDC(&hdcDest) ; // Create a normal font to find out the char size etc. HFONT hFont ; if (bItalic) { hFont = CreateCCFont(m_iCharWidth - INTERCHAR_SPACE_EXTRA, m_iCharHeight, bItalic, bUnderline) ; SetTextCharacterExtra(hdcDest, INTERCHAR_SPACE + INTERCHAR_SPACE_EXTRA) ; // add 6 inter-char spaces } else { hFont = CreateCCFont(0, m_iCharHeight, bItalic, bUnderline) ; SetTextCharacterExtra(hdcDest, INTERCHAR_SPACE) ; // add 4 inter-char spaces } if (NULL == hFont) // font creation failed { return false ; } // // Select the font into the DDraw surface and draw the characters // hFont = (HFONT)SelectObject(hdcDest, hFont) ; SetTextColor(hdcDest, m_acrFGColors[dwTextColor]) ; SetBkColor(hdcDest, dwBGColor) ; SetBkMode(hdcDest, dwOpacity) ; int iRow ; for (iRow = 0 ; iRow < FONTCACHENUMLINES ; iRow++) { ExtTextOutW(hdcDest, 0, iRow * m_iCharHeight, ETO_OPAQUE, NULL, m_lpwCharSet + iRow * FONTCACHELINELENGTH, FONTCACHELINELENGTH, NULL) ; } // Restore original font in DC and let go of them hFont = (HFONT)SelectObject(hdcDest, hFont) ; m_lpDDSScratch->ReleaseDC(hdcDest) ; DeleteObject(hFont) ; // Read each pixel data, set the alpha value, and then write to the VRAM font cache SetFontCacheAlpha(m_lpDDSScratch, *lplpDDSFontCache, m_idxFGColors[dwTextColor]) ; return true ; // success } // We return a 32bit alpha value, which gets trimmed to 16bit by the caller, if needed DWORD CLine21DecDraw::GetAlphaFromBGColor(int iBitDepth) { DWORD dwAlpha = 0 ; switch (iBitDepth) { case 8: dwAlpha = 0x80; break ; case 16: dwAlpha = (m_dwBackground & 0xF0000000) >> 16 ; break ; case 32: dwAlpha = (m_dwBackground & 0xFF000000) ; break ; default: DbgLog((LOG_TRACE, 1, TEXT("WARNING: GetAlphaFromBGColor(%d) called"), iBitDepth)) ; break ; } return dwAlpha ; } // We return a 32bit color value, which gets trimmed to 16bit by the caller, if needed DWORD CLine21DecDraw::GetColorBitsFromBGColor(int iBitDepth) { DWORD dwColorBits = 0 ; switch (iBitDepth) { case 16: dwColorBits = ((m_dwBackground & 0x00F00000) >> 12) | ((m_dwBackground & 0x0000F000) >> 8) | ((m_dwBackground & 0x000000F0) >> 4) ; break ; case 32: dwColorBits = (m_dwBackground & 0x00FFFFFF) ; break ; default: DbgLog((LOG_TRACE, 1, TEXT("WARNING: GetColorBitsFromBGColor(%d) called"), iBitDepth)) ; break ; } return dwColorBits ; } void CLine21DecDraw::SetFontCacheAlpha(LPDIRECTDRAWSURFACE7 lpDDSFontCacheSrc, LPDIRECTDRAWSURFACE7 lpDDSFontCacheDest, BYTE bFGClr ) { DbgLog((LOG_TRACE, 5, TEXT("CLine21DecDraw::SetFontCacheAlpha(0x%lx, 0x%lx)"), lpDDSFontCacheSrc, lpDDSFontCacheDest)) ; CAutoLock Lock(&m_csL21DDraw) ; // // We set the alpha values by hand here. This is done on every pixel of the // font cache, but it happens only when the cache is created. // It gets us better font smoothing too. // HRESULT hr ; DDSURFACEDESC2 sdSrc, sdDest ; ZeroMemory(&sdSrc, sizeof(sdSrc)) ; sdSrc.dwSize = sizeof(sdSrc) ; hr = lpDDSFontCacheSrc->Lock(NULL, &sdSrc, DDLOCK_WAIT, NULL) ; if (DD_OK != hr) { DbgLog((LOG_TRACE, 1, TEXT("Source font cache surface Lock() failed (Error 0x%lx)"), hr)) ; ASSERT(DD_OK == hr) ; return ; } ZeroMemory(&sdDest, sizeof(sdDest)) ; sdDest.dwSize = sizeof(sdDest) ; hr = lpDDSFontCacheDest->Lock(NULL, &sdDest, DDLOCK_WAIT, NULL) ; if (DD_OK != hr) { DbgLog((LOG_TRACE, 1, TEXT("Dest font cache surface Lock() failed (Error 0x%lx)"), hr)) ; ASSERT(DD_OK == hr) ; lpDDSFontCacheSrc->Unlock(NULL) ; return ; } // Now we set the alpha based on the bitdepth at which we are outputting switch (sdDest.ddpfPixelFormat.dwRGBBitCount) { case 8: { DbgLog((LOG_TRACE, 5, TEXT("CC is being output at AI44"))) ; LPDWORD lpwSrc = (LPDWORD) sdSrc.lpSurface ; LPBYTE lpwDest = (LPBYTE) sdDest.lpSurface ; LPBYTE lpb ; BYTE wPel ; BYTE bAlpha = (BYTE) GetAlphaFromBGColor(8) ; for (int iRow = 0 ; iRow < FONTCACHENUMLINES * m_iCharHeight ; iRow++) { LPDWORD lpwS = lpwSrc ; LPBYTE lpwD = lpwDest ; for (int iCol = 0 ; iCol < FONTCACHELINELENGTH * (m_iCharWidth + INTERCHAR_SPACE) ; iCol++) { BYTE bPel = (BYTE)(*lpwS & 0xF0); if (bPel) { bPel |= bFGClr; } else { bPel = bAlpha ; // | dwColorBits ; // turn on alpha partially } *lpwD++ = bPel ; lpwS++ ; } lpwSrc += (sdSrc.lPitch / sizeof(DWORD)) ; lpwDest += sdDest.lPitch; } break; } case 16: { DbgLog((LOG_TRACE, 5, TEXT("CC is being output at ARGB4444"))) ; LPWORD lpwSrc = (LPWORD) sdSrc.lpSurface ; LPWORD lpwDest = (LPWORD) sdDest.lpSurface ; WORD wRed, wGreen, wBlue ; LPBYTE lpb ; WORD wPel ; WORD wAlpha = (WORD) GetAlphaFromBGColor(16) ; WORD wColorBits = (WORD) GetColorBitsFromBGColor(16) ; for (int iRow = 0 ; iRow < FONTCACHENUMLINES * m_iCharHeight ; iRow++) { LPWORD lpwS = lpwSrc ; LPWORD lpwD = lpwDest ; for (int iCol = 0 ; iCol < FONTCACHELINELENGTH * (m_iCharWidth + INTERCHAR_SPACE) ; iCol++) { wRed = 0, wGreen = 0, wBlue = 0 ; // , wAlpha = 0 ; lpb = (LPBYTE)lpwS ; wPel = MAKEWORD(lpb[0], lpb[1]) ; if (wPel) { wRed = (wPel & 0xF000) >> 4 ; wGreen = (wPel & 0x0780) >> 3 ; wBlue = (wPel & 0x001E) >> 1 ; // wAlpha = 0xF000 ; // turn on alpha fully wPel = 0xF000 | wRed | wGreen | wBlue ; } else { wPel = wAlpha ; // | wColorBits ; } *lpwD++ = wPel ; lpwS++ ; } lpwSrc += (sdSrc.lPitch / sizeof(WORD)) ; lpwDest += (sdDest.lPitch / sizeof(WORD)) ; } break ; } case 32: { DbgLog((LOG_TRACE, 5, TEXT("CC is being output at ARGB32"))) ; LPDWORD lpdwSrc = (LPDWORD) sdSrc.lpSurface ; LPDWORD lpdwDst = (LPDWORD) sdDest.lpSurface ; DWORD dwAlpha = GetAlphaFromBGColor(32) ; DWORD dwColorBits = GetColorBitsFromBGColor(32) ; for (int iRow = 0 ; iRow < FONTCACHENUMLINES * m_iCharHeight ; iRow++) { LPDWORD lpdw = lpdwDst ; LPDWORD lpdwS = lpdwSrc ; for (int iCol = 0 ; iCol < FONTCACHELINELENGTH * (m_iCharWidth + INTERCHAR_SPACE) ; iCol++) { DWORD dwPel = *lpdwS ; if (dwPel) { dwPel |= 0xFF000000 ; // turn on alpha fully } else { dwPel = dwAlpha ; // | dwColorBits ; // turn on alpha partially } *lpdw++ = dwPel ; lpdwS++; } lpdwSrc += (sdSrc.lPitch / sizeof(DWORD)) ; lpdwDst += (sdDest.lPitch / sizeof(DWORD)) ; } break ; } default: DbgLog((LOG_TRACE, 1, TEXT("WARNING: Bad display bitdepth (%d) mode"), sdDest.ddpfPixelFormat.dwRGBBitCount)) ; break ; } // end of switch () // Done with everything lpDDSFontCacheSrc->Unlock(NULL) ; lpDDSFontCacheDest->Unlock(NULL) ; } HRESULT CLine21DecDraw::DDrawARGBSurfaceInit(LPDIRECTDRAWSURFACE7* lplpDDSFontCache, BOOL bUseSysMem, BOOL bTexture, DWORD cx, DWORD cy) { DbgLog((LOG_TRACE, 5, TEXT("CLine21DecDraw::DDrawARGBSurfaceInit(0x%lx, %s, %lu, %lu)"), lplpDDSFontCache, (TRUE == bUseSysMem) ? TEXT("T") : TEXT("F"), (TRUE == bTexture) ? TEXT("T") : TEXT("F"), cx, cy)) ; CAutoLock Lock(&m_csL21DDraw) ; // Just to be sure that the cached DDraw object is valid... if (NULL == m_pDDrawObjUnk) { DbgLog((LOG_TRACE, 1, TEXT("DDrawARGBSurfaceInit(): m_pDDrawObjUnk is not yet set. Skipping the rest."))) ; ASSERT(m_pDDrawObjUnk) ; return E_UNEXPECTED ; } DDSURFACEDESC2 ddsd ; HRESULT hRet ; *lplpDDSFontCache = NULL ; ZeroMemory(&ddsd, sizeof(ddsd)) ; ddsd.dwSize = sizeof(ddsd) ; LPBITMAPINFOHEADER lpbmih = (m_lpBMIOut ? LPBMIHEADER(m_lpBMIOut) : LPBMIHEADER(m_lpBMIIn)) ; // Set the DDPIXELFORMAT part ddsd.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT) ; ddsd.ddpfPixelFormat.dwFlags = DDPF_RGB ; if (bTexture || !bUseSysMem) // for VRAM surface { if (8 != lpbmih->biBitCount) { ddsd.ddpfPixelFormat.dwFlags |= DDPF_ALPHAPIXELS ; } } ddsd.ddpfPixelFormat.dwRGBBitCount = lpbmih->biBitCount ; if (8 == lpbmih->biBitCount) { if (bUseSysMem) { // scratch surface RGB32 ddsd.ddpfPixelFormat.dwRGBBitCount = 32; ddsd.ddpfPixelFormat.dwRBitMask = 0x00FF0000 ; ddsd.ddpfPixelFormat.dwGBitMask = 0x0000FF00 ; ddsd.ddpfPixelFormat.dwBBitMask = 0x000000FF ; ddsd.ddpfPixelFormat.dwRGBAlphaBitMask = 0x00000000 ; // to be sure } else { // VRAM surface -- AI44 ddsd.ddpfPixelFormat.dwFourCC = '44IA'; } } else if (16 == lpbmih->biBitCount) { if (bUseSysMem) // scratch surface -- RGB565 { ddsd.ddpfPixelFormat.dwRBitMask = 0xF800 ; ddsd.ddpfPixelFormat.dwGBitMask = 0x07E0 ; ddsd.ddpfPixelFormat.dwBBitMask = 0x001F ; ddsd.ddpfPixelFormat.dwRGBAlphaBitMask = 0x0000 ; } else // VRAM surface -- ARGB4444 { ddsd.ddpfPixelFormat.dwRBitMask = 0x0F00 ; ddsd.ddpfPixelFormat.dwGBitMask = 0x00F0 ; ddsd.ddpfPixelFormat.dwBBitMask = 0x000F ; if (bTexture) ddsd.ddpfPixelFormat.dwRGBAlphaBitMask = 0xF000 ; else ddsd.ddpfPixelFormat.dwRGBAlphaBitMask = 0x0000 ; // to be sure } } else { ddsd.ddpfPixelFormat.dwRBitMask = 0x00FF0000 ; ddsd.ddpfPixelFormat.dwGBitMask = 0x0000FF00 ; ddsd.ddpfPixelFormat.dwBBitMask = 0x000000FF ; if (bTexture) ddsd.ddpfPixelFormat.dwRGBAlphaBitMask = 0xFF000000 ; else ddsd.ddpfPixelFormat.dwRGBAlphaBitMask = 0x00000000 ; // to be sure } // Create the Caps bits DWORD dwCaps = 0 ; if (bUseSysMem) { dwCaps |= DDSCAPS_SYSTEMMEMORY ; } else { dwCaps |= DDSCAPS_VIDEOMEMORY ; } if (bTexture) { dwCaps |= DDSCAPS_TEXTURE ; } else { dwCaps |= DDSCAPS_OFFSCREENPLAIN ; } ddsd.ddsCaps.dwCaps = dwCaps ; // Now flags and other fields... ddsd.dwFlags = DDSD_WIDTH | DDSD_HEIGHT | DDSD_CAPS | DDSD_PIXELFORMAT ; ddsd.dwBackBufferCount = 0 ; if (bTexture) { for (ddsd.dwWidth = 1 ; cx > ddsd.dwWidth ; ddsd.dwWidth <<= 1) ; for (ddsd.dwHeight = 1 ; cy > ddsd.dwHeight ; ddsd.dwHeight <<= 1) ; } else { ddsd.dwWidth = cx ; ddsd.dwHeight = cy ; } // Create the surface with these settings LPDIRECTDRAW7 lpDDObj ; hRet = m_pDDrawObjUnk->QueryInterface(IID_IDirectDraw7, (LPVOID *) &lpDDObj) ; if (SUCCEEDED(hRet)) { hRet = lpDDObj->CreateSurface(&ddsd, lplpDDSFontCache, NULL) ; lpDDObj->Release() ; // done with the interface } return hRet ; } bool CLine21DecDraw::CharSizeFromOutputSize(LONG lOutWidth, LONG lOutHeight, int *piCharWidth, int *piCharHeight) { DbgLog((LOG_TRACE, 5, TEXT("CLine21DecDraw::CharSizeFromOutputSize(%ld, %ld, 0x%lx, 0x%lx)"), lOutWidth, lOutHeight, piCharWidth, piCharHeight)) ; CAutoLock Lock(&m_csL21DDraw) ; // We only care about the absolute value here lOutWidth = ABS(lOutWidth) ; lOutHeight = ABS(lOutHeight) ; if ( IsTTFont() ) // TT font { if (! ISDWORDALIGNED(lOutWidth) ) // must have DWORD-aligned width return false ; *piCharWidth = (int)(lOutWidth * (100 - m_iBorderPercent) / 100) ; // 80-90% of width *piCharWidth += MAX_CAPTION_COLUMNS / 2 + 1 ; // max_col / 2 for rounding *piCharWidth /= (MAX_CAPTION_COLUMNS + 2) ; // space per column *piCharHeight = (int)(lOutHeight * (100 - m_iBorderPercent) / 100) ; // 80-90% of width *piCharHeight += (MAX_CAPTION_ROWS / 2) ; // max_row / 2 for rounding *piCharHeight /= MAX_CAPTION_ROWS ; // space per row return true ; // acceptable } else // non-TT font (Terminal) -- only 320x240 or 640x480 { if (640 == lOutWidth && 480 == lOutHeight) { *piCharWidth = 16 ; *piCharHeight = 24 ; return true ; // acceptable } else if (320 == lOutWidth && 240 == lOutHeight) { *piCharWidth = 8 ; *piCharHeight = 12 ; return true ; // acceptable } else return false ; // can't handle size for non-TT font } } bool CLine21DecDraw::SetOutputSize(LONG lWidth, LONG lHeight) { DbgLog((LOG_TRACE, 5, TEXT("CLine21DecDraw::SetOutputSize(%ld, %ld)"), lWidth, lHeight)) ; CAutoLock Lock(&m_csL21DDraw) ; // If a output format is specified by downstream filter, use it; else use upstream's LPBITMAPINFOHEADER lpbmih = (m_lpBMIOut ? LPBMIHEADER(m_lpBMIOut) : LPBMIHEADER(m_lpBMIIn)) ; // Now we want to use the ABS()-ed values for calculating the char sizes lWidth = ABS(lWidth) ; lHeight = ABS(lHeight) ; if (lpbmih) { // Check if current output bitmap size is the same or not. // This also includes height changing from +ve to -ve and vice-versa if (lWidth == m_lWidth && lHeight == m_lHeight) return false ; // same size; nothing changed // Store the width and height now so that we can compare any size // change and/or -ve/+ve height thing later. // m_lWidth = lWidth ; // m_lHeight = lHeight ; } // Create new DIB section with new sizes (leaving borders) int iCharWidth ; int iCharHeight ; if (! CharSizeFromOutputSize(lWidth, lHeight, &iCharWidth, &iCharHeight) ) { DbgLog((LOG_ERROR, 0, TEXT("ERROR: CharSizeFromOutputSize() failed for %ld x %ld output"), lWidth, lHeight)) ; ASSERT(!TEXT("CharSizeFromOutputSize() failed")) ; return false ; // failure } // Store the image and char width and height now so that we can compare any // size change and/or -ve/+ve height thing later. m_lWidth = lWidth ; m_lHeight = lHeight ; m_iCharWidth = iCharWidth ; m_iCharHeight = iCharHeight ; m_iScrollStep = CalcScrollStepFromCharHeight() ; // Re-calculate the horizonal and vertical offsets too m_iHorzOffset = m_lWidth * m_iBorderPercent / 200 ; m_iVertOffset = m_lHeight * m_iBorderPercent / 200 ; // The font caches need to be rebuilt for new sizes (and DDraw object/surface) SetFontUpdate(true) ; return true ; } HRESULT CLine21DecDraw::SetOutputOutFormat(LPBITMAPINFO lpbmi) { DbgLog((LOG_TRACE, 5, TEXT("CLine21DecDraw::SetOutputOutFormat(0x%lx)"), lpbmi)) ; CAutoLock Lock(&m_csL21DDraw) ; // // NULL param means output format not available from downstream filter // if (NULL == lpbmi) { if (m_lpBMIOut) delete m_lpBMIOut ; m_lpBMIOut = NULL ; m_uBMIOutSize = 0 ; // In this case, go back to the default output format specified by // upstream filter if (m_lpBMIIn) { SetOutputSize(m_lpBMIIn->bmiHeader.biWidth, m_lpBMIIn->bmiHeader.biHeight) ; } else { DbgLog((LOG_ERROR, 1, TEXT("How did we not have a default output format?"))) ; } return NOERROR ; } // Just paranoid... if (IsBadReadPtr(lpbmi, sizeof(BITMAPINFOHEADER))) { DbgLog((LOG_ERROR, 0, TEXT("Invalid output format (out) data pointer"))) ; return E_INVALIDARG ; } // Make sure we can handle this output size if (! IsSizeOK(&lpbmi->bmiHeader) ) return E_INVALIDARG ; // The beginning of the VIDEOINFOHEADER struct and we don't want it UINT uSize = 0; switch (((LPBITMAPINFOHEADER)lpbmi)->biCompression) { case BI_RGB: case BI_BITFIELDS: uSize = GetBitmapFormatSize((LPBITMAPINFOHEADER) lpbmi) - SIZE_PREHEADER ; break; default: // AI44 case uSize = ((LPBITMAPINFOHEADER)lpbmi)->biSize; break; } if (NULL == m_lpBMIOut) // If we didn't have one before then allocate space for one { m_lpBMIOut = (LPBITMAPINFO) new BYTE [uSize] ; if (NULL == m_lpBMIOut) { DbgLog((LOG_ERROR, 0, TEXT("Out of memory for output format info from downstream"))) ; return E_OUTOFMEMORY ; } m_uBMIOutSize = uSize ; // new size } else // we have an existing out format, but ... { // ... check if new data is bigger than the current space we have if (m_uBMIOutSize < uSize) { delete m_lpBMIOut ; m_lpBMIOut = (LPBITMAPINFO) new BYTE[uSize] ; if (NULL == m_lpBMIOut) { DbgLog((LOG_ERROR, 1, TEXT("Out of memory for out format BMI from downstream"))) ; m_uBMIOutSize = 0 ; return E_OUTOFMEMORY ; } m_uBMIOutSize = uSize ; } } // Make sure the output size specified by the format is such that // each scanline is DWORD aligned lpbmi->bmiHeader.biWidth = DWORDALIGN(lpbmi->bmiHeader.biWidth) ; lpbmi->bmiHeader.biSizeImage = DIBSIZE(lpbmi->bmiHeader) ; // Now copy the specified format data CopyMemory(m_lpBMIOut, lpbmi, uSize) ; // Check if the output size is changing and update all the related vars SetOutputSize(m_lpBMIOut->bmiHeader.biWidth, m_lpBMIOut->bmiHeader.biHeight) ; return NOERROR ; } HRESULT CLine21DecDraw::SetOutputInFormat(LPBITMAPINFO lpbmi) { DbgLog((LOG_TRACE, 5, TEXT("CLine21DecDraw::SetOutputInFormat(0x%lx)"), lpbmi)) ; CAutoLock Lock(&m_csL21DDraw) ; // // NULL param means no output format from upstream filter // if (NULL == lpbmi) { #if 0 if (m_lpBMIOut) { // // BTW this can happen when the graph is torn down at the end of // playback. We can ignore this error in that case. // DbgLog((LOG_ERROR, 3, TEXT("Can't delete Output format from upstream w/o downstream specifying it"))) ; return E_INVALIDARG ; } #endif // #if 0 if (m_lpBMIIn) delete m_lpBMIIn ; m_lpBMIIn = NULL ; m_uBMIInSize = 0 ; // // Initialize the default output format from upstream filter // InitBMIData() ; // return NOERROR ; } else // non-NULL format specified { // The beginning of the VIDEOINFOHEADER struct and we don't want it UINT uSize = GetBitmapFormatSize((LPBITMAPINFOHEADER) lpbmi) - SIZE_PREHEADER ; if (IsBadReadPtr(lpbmi, uSize)) // just paranoid... { DbgLog((LOG_ERROR, 1, TEXT("WARNING: Not enough output format (in) data pointer"))) ; ASSERT(FALSE) ; return E_INVALIDARG ; } // Make sure we can handle this output size if (! IsSizeOK(&lpbmi->bmiHeader) ) return E_INVALIDARG ; if (NULL == m_lpBMIIn) // If we didn't have one before then allocate space for one { m_lpBMIIn = (LPBITMAPINFO) new BYTE [uSize] ; if (NULL == m_lpBMIIn) { DbgLog((LOG_ERROR, 0, TEXT("Out of memory for output format info from upstream"))) ; return E_OUTOFMEMORY ; } } else // we have an existing out format, but ... { // ... check if new data is bigger than the current space we have if (m_uBMIInSize < uSize) { delete m_lpBMIIn ; m_lpBMIIn = (LPBITMAPINFO) new BYTE[uSize] ; if (NULL == m_lpBMIIn) { DbgLog((LOG_ERROR, 1, TEXT("Out of memory for out format BMI from upstream"))) ; m_uBMIInSize = 0 ; return E_OUTOFMEMORY ; } m_uBMIInSize = uSize ; } } // Make sure the output size specified by the format is such that // each scanline is DWORD aligned lpbmi->bmiHeader.biWidth = DWORDALIGN(lpbmi->bmiHeader.biWidth) ; lpbmi->bmiHeader.biSizeImage = DIBSIZE(lpbmi->bmiHeader) ; // Now copy the specified format data CopyMemory(m_lpBMIIn, lpbmi, uSize) ; } // end of else of if (lpbmi) // If we don't have a output format specified by downstream then we'll // use this output format and resize the output accordingly if (NULL == m_lpBMIOut) { // Check if output size is changing and update all the related vars SetOutputSize(m_lpBMIIn->bmiHeader.biWidth, m_lpBMIIn->bmiHeader.biHeight) ; } return NOERROR ; } void CLine21DecDraw::FillOutputBuffer(void) { DbgLog((LOG_TRACE, 5, TEXT("CLine21DecDraw::FillOutputBuffer()"))) ; CAutoLock Lock(&m_csL21DDraw) ; // First check if the output DDraw surface is valid (it's NOT valid during // start-up, when the style, service etc. get set). We should skip the rest // of the code as it's not necessary at that stage anyway. if (NULL == m_lpDDSOutput) { DbgLog((LOG_TRACE, 5, TEXT("Output DDraw surface is not valid. Skip it silently..."))) ; return ; } DDBLTFX ddFX ; ZeroMemory(&ddFX, sizeof(ddFX)) ; ddFX.dwSize = sizeof(ddFX) ; ddFX.dwFillColor = 0x00000000 ; HRESULT hr = m_lpDDSOutput->Blt(NULL, NULL, NULL, DDBLT_COLORFILL, &ddFX) ; if (SUCCEEDED(hr)) { m_bOutputClear = TRUE ; // output buffer is totally clear } else { DbgLog((LOG_TRACE, 3, TEXT("WARNING: CC output clearing failed (Blt() Error 0x%lx)"), hr)) ; } } // // This method is required only to generate the default format block in case // the upstream filter doesn't specify FORMAT_VideoInfo type. // HRESULT CLine21DecDraw::GetDefaultFormatInfo(LPBITMAPINFO lpbmi, DWORD *pdwSize) { DbgLog((LOG_TRACE, 5, TEXT("CLine21DecDraw::GetDefaultFormatInfo(0x%lx, 0x%lx)"), lpbmi, pdwSize)) ; CAutoLock Lock(&m_csL21DDraw) ; if (NULL == pdwSize || IsBadWritePtr(pdwSize, sizeof(DWORD))) { return E_INVALIDARG ; } LPBITMAPINFO lpbmiCurr = (m_lpBMIOut ? m_lpBMIOut : m_lpBMIIn) ; UINT dwCurrSize = (m_lpBMIOut ? m_uBMIOutSize : m_uBMIInSize) ; ASSERT(dwCurrSize) ; // just a check if (NULL == lpbmi) // wants just the format data size { *pdwSize = dwCurrSize ; return NOERROR ; } if (IsBadWritePtr(lpbmi, *pdwSize)) // not enough space in out-param return E_INVALIDARG ; *pdwSize = min(*pdwSize, dwCurrSize) ; // minm of actual and given CopyMemory(lpbmi, lpbmiCurr, *pdwSize) ; return NOERROR ; // success } HRESULT CLine21DecDraw::GetOutputFormat(LPBITMAPINFOHEADER lpbmih) { DbgLog((LOG_TRACE, 5, TEXT("CLine21DecDraw::GetOutputFormat(0x%lx)"), lpbmih)) ; CAutoLock Lock(&m_csL21DDraw) ; if (IsBadWritePtr(lpbmih, sizeof(BITMAPINFOHEADER))) // not enough space in out-param return E_INVALIDARG ; ZeroMemory(lpbmih, sizeof(BITMAPINFOHEADER)) ; // just to keep it clear LPBITMAPINFOHEADER lpbmihCurr = (m_lpBMIOut ? LPBMIHEADER(m_lpBMIOut) : LPBMIHEADER(m_lpBMIIn)) ; if (NULL == lpbmihCurr) // no output format specified by downstream return S_FALSE ; CopyMemory(lpbmih, lpbmihCurr, sizeof(BITMAPINFOHEADER)) ; return S_OK ; // success } HRESULT CLine21DecDraw::GetOutputOutFormat(LPBITMAPINFOHEADER lpbmih) { DbgLog((LOG_TRACE, 5, TEXT("CLine21DecDraw::GetOutputOutFormat(0x%lx)"), lpbmih)) ; CAutoLock Lock(&m_csL21DDraw) ; if (IsBadWritePtr(lpbmih, sizeof(BITMAPINFOHEADER))) { DbgLog((LOG_ERROR, 0, TEXT("GetOutputOutFormat(): Bad in param"))) ; return E_INVALIDARG ; } if (m_lpBMIOut) { CopyMemory(lpbmih, m_lpBMIOut, sizeof(BITMAPINFOHEADER)) ; return S_OK ; } else { DbgLog((LOG_TRACE, 3, TEXT("GetOutputOutFormat(): No output format specified by downstream filter"))) ; return S_FALSE ; } } BOOL CLine21DecDraw::IsSizeOK(LPBITMAPINFOHEADER lpbmih) { DbgLog((LOG_TRACE, 5, TEXT("CLine21DecDraw::IsSizeOK(0x%lx)"), lpbmih)) ; CAutoLock Lock(&m_csL21DDraw) ; return ((IsTTFont() && ISDWORDALIGNED(lpbmih->biWidth)) || // TT font and DWORD-aligned width or (!IsTTFont() && // non-TT font and ... ((320 == ABS(lpbmih->biWidth) && 240 == ABS(lpbmih->biHeight)) || // 320x240 output or (640 == ABS(lpbmih->biWidth) && 480 == ABS(lpbmih->biHeight))))) ; // 640x480 output } bool CLine21DecDraw::SetDDrawSurface(LPDIRECTDRAWSURFACE7 lpDDSurf) { DbgLog((LOG_TRACE, 5, TEXT("CLine21DecDraw::SetDDrawSurface(0x%lx)"), lpDDSurf)) ; CAutoLock Lock(&m_csL21DDraw) ; // The passed in DDraw surface pointer may be NULL when the pin connection // is broken. In that case, we skip almost everything else. if (NULL == lpDDSurf) { // Save the new DDraw surface pointer m_bNewOutBuffer = m_lpDDSOutput != lpDDSurf ; // has it changed? m_lpDDSOutput = NULL ; // no DDraw surface to cache SetDDrawObject(NULL) ; // ... and no DDraw object either return true ; // it's OK } bool bResult = true ; // First check if the DDraw objects are the same IUnknown *pDDObj ; HRESULT hr = lpDDSurf->GetDDInterface((LPVOID*)&pDDObj) ; if (SUCCEEDED(hr) && pDDObj) { // If the DDraw object changed (probably window shifted to different // monitor or display res changed etc), we need to re-do a whole // bunch of stuff now. if (GetDDrawObject() && IsEqualObject(pDDObj, GetDDrawObject())) { DbgLog((LOG_TRACE, 5, TEXT("Same DDraw object is being used."))) ; } else // new DDraw object { DbgLog((LOG_TRACE, 3, TEXT("DDraw object has changed. Pass it down..."))) ; SetDDrawObject(pDDObj) ; // Need to re-init the font caches for the new DDraw object and surface SetFontUpdate(true) ; } // Now let go of all the interfaces pDDObj->Release() ; } // Save the new DDraw surface pointer m_bNewOutBuffer = m_lpDDSOutput != lpDDSurf ; // has it changed? m_lpDDSOutput = lpDDSurf ; // In case the font cache needs to be updated, do it now. if (! IsFontReady() ) { bResult = InitFont() ; ASSERT(bResult && TEXT("SetDDrawSurface(): InitFont() failed.")) ; } return bResult ; } void CLine21DecDraw::ChangeFont(DWORD dwTextColor, BOOL bItalic, BOOL bUnderline) { DbgLog((LOG_TRACE, 5, TEXT("CLine21DecDraw::ChangeFont(%lu, %s, %s)"), dwTextColor, bItalic ? TEXT("T") : TEXT("F"), bUnderline ? TEXT("T") : TEXT("F"))) ; CAutoLock Lock(&m_csL21DDraw) ; // // If the current font style & color and the new font style & color happen // to be the same, just ignore this one and return. // if (m_bFontItalic == bItalic && m_bFontUnderline == bUnderline && m_dwTextColor == dwTextColor) return ; // don't have to do anything at all // // For Italic chars we Blt the char rect from 2 pixels to the right, // but for normal chars we don't do that. // if (bItalic) m_iPixelOffset = 1 ; else m_iPixelOffset = 0 ; // Update the current font color and style info -- will revert on problem m_dwTextColor = dwTextColor ; m_bFontItalic = bItalic ; m_bFontUnderline = bUnderline ; // // If the text color is white and the font style is not underlined, we'll // just point to the normal or Italic font cache as appropriate. // if (!bUnderline && AM_L21_FGCOLOR_WHITE == dwTextColor) { if (bItalic) // need Italic style { m_lpBltList = m_lpDDSItalicFontCache ; } else // need normal style { m_lpBltList = m_lpDDSNormalFontCache ; } return ; } // // Looks like we need a non-white text color and/or underlined style. For // that we have to create the special font cache and point to that. // if (m_lpDDSSpecialFontCache) { m_lpDDSSpecialFontCache->Release() ; m_lpDDSSpecialFontCache = NULL ; } DWORD dwBGColor = 0xFF000000 ; // m_dwBackground ; DWORD dwOpacity = m_bOpaque ? OPAQUE : 0 ; bool bResult = true ; if (NULL == m_lpDDSScratch) // if no scratch surface, create it now { ASSERT(!TEXT("No scratch font cache!!")) ; bResult &= CreateScratchFontCache(&m_lpDDSScratch) ; ASSERT(bResult) ; } bResult &= CreateFontCache(&m_lpDDSSpecialFontCache, dwTextColor, dwBGColor, dwOpacity, bItalic, bUnderline) ; if (bResult) { m_lpBltList = m_lpDDSSpecialFontCache ; } else // if we can't create any special font, we fallback to normal white { DbgLog((LOG_TRACE, 1, TEXT("Failed creating special font (ColorId=%d, , , %s, %s). Using normal font."), dwTextColor, bItalic ? TEXT("I") : TEXT("non-I"), bUnderline ? TEXT("U") : TEXT("non-U"))) ; m_lpBltList = m_lpDDSNormalFontCache ; // Due to some problem, we are still using the white normal font m_dwTextColor = AM_L21_FGCOLOR_WHITE ; m_bFontItalic = FALSE ; m_bFontUnderline = FALSE ; } } void CLine21DecDraw::GetSrcNDestRects(int iLine, int iCol, UINT16 wChar, int iSrcCrop, int iDestOffset, RECT *prectSrc, RECT *prectDest) { DbgLog((LOG_TRACE, 5, TEXT("CLine21DecDraw::GetSrcNDestRects(%d,%d,,,,,)"), iLine, iCol)) ; CAutoLock Lock(&m_csL21DDraw) ; // if (m_bOpaque) // opaque the next char's position { prectDest->left = (iCol+1) * m_iCharWidth + m_iHorzOffset ; prectDest->right = prectDest->left + m_iCharWidth ; // Row numbers are from 1 to 15. The rect top should start from top of // a row's rect. That's why we subtract 1 from the row number below. prectDest->top = (iLine-1) * m_iCharHeight + m_iVertOffset + iDestOffset ; // fix dest top prectDest->bottom = prectDest->top + m_iCharHeight - ABS(iSrcCrop) ; // fix dest size } MapCharToRect(wChar, prectSrc) ; // Adjust Src rect: +ve iSrcCrop => skip the top part; -ve iSrcCrop => skip the bottom if (iSrcCrop < 0) // crop out bottom part of Src rect { prectSrc->bottom += iSrcCrop ; // adding a -ve reduces the bottom } else if (iSrcCrop > 0) // crop out top part of Src rect { prectSrc->top += iSrcCrop ; // adding a +ve skips the top } // Otherwise no rect adjustment is needed } void CLine21DecDraw::DrawLeadingTrailingSpace(int iLine, int iCol, int iSrcCrop, int iDestOffset) { DbgLog((LOG_TRACE, 5, TEXT("CLine21DecDraw::DrawLeadingTrailingSpace(%d, %d, %d, %d)"), iLine, iCol, iSrcCrop, iDestOffset)) ; CAutoLock Lock(&m_csL21DDraw) ; if (NULL == m_lpDDSOutput) { DbgLog((LOG_TRACE, 5, TEXT("Output DDraw surface is not valid. Skip it silently..."))) ; return ; } if (! m_bOpaque ) // doesn't matter for transparent background return ; UINT16 wActual ; UINT16 wBGSpace = MAKECCCHAR(0, ' ') ; wActual = MAKECCCHAR(0, ' ') ; // use space // Leading space is drawn using a blank space with normal style ChangeFont(AM_L21_FGCOLOR_WHITE, FALSE, FALSE) ; // Get appropriate source and destination rectangles RECT RectSrc ; RECT RectDest ; GetSrcNDestRects(iLine, iCol, wActual, iSrcCrop, iDestOffset, &RectSrc, &RectDest) ; // Now Blt the src rect to the dest rect for the required char HRESULT hr = m_lpDDSOutput->Blt(&RectDest, m_lpBltList, &RectSrc, DDBLT_WAIT, NULL) ; if (SUCCEEDED(hr)) { m_bOutputClear = FALSE ; // output buffer is cleared by ClearOutputBuffer() } else { DbgLog((LOG_TRACE, 3, TEXT("WARNING: CC lead/trail space output failed (Blt() Error 0x%lx)"), hr)) ; } // Now restore prev font (color, italics, underline) ChangeFont(m_ccLast.GetColor(), m_ccLast.IsItalicized(), m_ccLast.IsUnderLined()) ; } void CLine21DecDraw::WriteChar(int iLine, int iCol, CCaptionChar& cc, int iSrcCrop, int iDestOffset) { DbgLog((LOG_TRACE, 5, TEXT("CLine21DecDraw::WriteChar(%d, %d, char=0x%x, %d, %d)"), iLine, iCol, cc.GetChar(), iSrcCrop, iDestOffset)) ; CAutoLock Lock(&m_csL21DDraw) ; if (NULL == m_lpDDSOutput) { DbgLog((LOG_TRACE, 5, TEXT("Output DDraw surface is not valid. Skip it silently..."))) ; return ; } UINT16 wActual ; UINT16 wBGSpace = MAKECCCHAR(0, ' ') ; UINT uColor = cc.GetColor() ; UINT uEffect = cc.GetEffect() ; // Do we need some status checks tp make sure that we should output CC chars? if (cc.IsMidRowCode()) // if it's a mid row code wActual = MAKECCCHAR(0, ' ') ; // use space else // otherwise wActual = cc.GetChar() ; // use the char itself if (0 == wActual) // this one is supposed to be skipped -- I am not sure { DbgLog((LOG_TRACE, 3, TEXT("Should we skip NULL char at (%d, %d)??"), iLine, iCol)) ; // return ; } // In case the color or style has changed, we have to change the pointer to // the font cache, and may have to even build a new one (for non-white colors) if (uColor != m_ccLast.GetColor() || uEffect != m_ccLast.GetEffect()) ChangeFont(uColor, cc.IsItalicized(), cc.IsUnderLined()) ; // Get appropriate source and destination rectangles RECT RectSrc ; RECT RectDest ; GetSrcNDestRects(iLine, iCol, wActual, iSrcCrop, iDestOffset, &RectSrc, &RectDest) ; // Now Blt the src rect to the dest rect for the required char HRESULT hr = m_lpDDSOutput->Blt(&RectDest, m_lpBltList, &RectSrc, DDBLT_WAIT, NULL) ; if (SUCCEEDED(hr)) { if (0 != wActual) // if this char is non-null { m_bOutputClear = FALSE ; // output buffer is cleared by ClearOutputBuffer() } } else { DbgLog((LOG_TRACE, 1, TEXT("WARNING: CC char output failed (Blt() Error 0x%lx)"), hr)) ; } m_ccLast = cc ; } void CLine21DecDraw::WriteBlankCharRepeat(int iLine, int iCol, int iRepeat, int iSrcCrop, int iDestOffset) { DbgLog((LOG_TRACE, 5, TEXT("CLine21DecDraw::WriteBlankCharRepeat(%d,%d,%d,%d,%d)"), iLine, iCol, iRepeat, iSrcCrop, iDestOffset)) ; CAutoLock Lock(&m_csL21DDraw) ; if (NULL == m_lpDDSOutput) { DbgLog((LOG_TRACE, 5, TEXT("Output DDraw surface is not valid. Skip it silently..."))) ; return ; } if (! m_bOpaque ) // doesn't matter for transparent background return ; UINT16 wActual = MAKECCCHAR(0, ' ') ; // use space; // UINT16 wBGSpace = MAKECCCHAR(0, ' ') ; // Leading space is drawn using a blank space with normal style // ChangeFont(AM_L21_FGCOLOR_WHITE, FALSE, FALSE) ; // Get appropriate source and destination rectangles RECT RectSrc ; RECT RectDest ; GetSrcNDestRects(iLine, iCol, wActual, iSrcCrop, iDestOffset, &RectSrc, &RectDest) ; RectDest.right = RectDest.left + m_iCharWidth * iRepeat ; // stretch Dest rect // Now Blt the src rect to the dest rect for the required char HRESULT hr ; hr = m_lpDDSOutput->Blt(&RectDest, m_lpBltList, &RectSrc, DDBLT_WAIT, NULL) ; if (SUCCEEDED(hr)) { m_bOutputClear = FALSE ; // output buffer is cleared by ClearOutputBuffer() } else { DbgLog((LOG_TRACE, 3, TEXT("WARNING: CC line filler output failed (Blt() Error 0x%lx)"), hr)) ; // ASSERT(SUCCEEDED(hr)) ; } // Now restore prev font (color, italics, underline) // ChangeFont(m_ccLast.GetColor(), m_ccLast.IsItalicized(), m_ccLast.IsUnderLined()) ; } // Special Chars like TM, R, musical note etc. etc. // 0x00ae, 0x00b0, 0x00bd, 0x00bf, 0x2122, 0x00a2, 0x00a3, 0x266b, // 30h, 31h, 32h, 33h, 34h, 35h, 36h, 37h, // 0x00e0, 0x0000, 0x00e8, 0x00e2, 0x00ea, 0x00ee, 0x00f4, 0x00fb // 38h, 39h, 3Ah, 3Bh, 3Ch, 3Dh, 3Eh, 3Fh void CLine21DecDraw::MapCharToRect(UINT16 wChar, RECT *pRect) { DbgLog((LOG_TRACE, 5, TEXT("CLine21DecDraw::MapCharToRect(%d, %lx)"), (int)wChar, pRect)) ; int iLine ; int iCol ; int iIndex = 0 ; if (wChar >= MAKECCCHAR(0, 0x20) && wChar <= MAKECCCHAR(0, 0x29)) { iIndex = (BYTE)wChar - 0x20 ; } else if (wChar >= MAKECCCHAR(0, 0x2B) && wChar <= MAKECCCHAR(0, 0x5B)) { iIndex = (BYTE)wChar - 0x20 ; } else if (wChar == MAKECCCHAR(0, 0x5D)) // ']' char (standing alone!!) { iIndex = (BYTE)wChar - 0x20 ; } else if (wChar >= MAKECCCHAR(0, 0x61) && wChar <= MAKECCCHAR(0, 0x7A)) { iIndex = (BYTE)wChar - 0x20 ; } else // special chars that have random values { switch (wChar) { case 0x00e1: // m_lpwCharSet[ 10]: 'a' with acute accent iIndex = 10 ; break ; case 0x00e9: // m_lpwCharSet[ 60]: 'e' with acute accent iIndex = 60 ; break ; case 0x00ed: // m_lpwCharSet[ 62]: 'i' with an acute accent iIndex = 62 ; break ; case 0x00f3: // m_lpwCharSet[ 63]: 'o' with an acute accent iIndex = 63 ; break ; case 0x00fa: // m_lpwCharSet[ 64]: 'u' with an acute accent iIndex = 64 ; break ; case 0x00e7: // m_lpwCharSet[ 91]: 'c' with cedilla iIndex = 91 ; break ; case 0x00f7: // m_lpwCharSet[ 92]: division sign iIndex = 92 ; break ; case 0x00d1: // m_lpwCharSet[ 93]: 'N' with tilde iIndex = 93 ; break ; case 0x00f1: // m_lpwCharSet[ 94]: 'n' with tilde iIndex = 94 ; break ; case 0x2588: // m_lpwCharSet[ 95]: solid block iIndex = 95 ; break ; case 0x00ae: // m_lpwCharSet[ 96]: 30h -- registered mark symbol iIndex = 96 ; break ; case 0x00b0: // m_lpwCharSet[ 97]: 31h -- degree sign iIndex = 97 ; break ; case 0x00bd: // m_lpwCharSet[ 98]: 32h -- '1/2' iIndex = 98 ; break ; case 0x00bf: // m_lpwCharSet[ 99]: 33h -- inverse query iIndex = 99 ; break ; case 0x2122: // m_lpwCharSet[100]: 34h -- trademark symbol iIndex = 100 ; break ; case 0x00a2: // m_lpwCharSet[101]: 35h -- cents sign iIndex = 101 ; break ; case 0x00a3: // m_lpwCharSet[102]: 36h -- Pounds Sterling sign iIndex = 102 ; break ; case 0x266b: // m_lpwCharSet[103]: 37h -- music note iIndex = 103 ; break ; case 0x00e0: // m_lpwCharSet[104]: 38h -- 'a' with grave accent iIndex = 104 ; break ; case 0x0000: // m_lpwCharSet[105]: 39h -- transparent space iIndex = 105 ; break ; case 0x00e8: // m_lpwCharSet[106]: 3ah -- 'e' with grave accent iIndex = 106 ; break ; case 0x00e2: // m_lpwCharSet[107]: 3bh -- 'a' with circumflex iIndex = 107 ; break ; case 0x00ea: // m_lpwCharSet[108]: 3ch -- 'e' with circumflex iIndex = 108 ; break ; case 0x00ee: // m_lpwCharSet[109]: 3dh -- 'i' with circumflex iIndex = 109 ; break ; case 0x00f4: // m_lpwCharSet[110]: 3eh -- 'o' with circumflex iIndex = 110 ; break ; case 0x00fb: // m_lpwCharSet[111]: 3fh -- 'u' with circumflex iIndex = 111 ; break ; default: iIndex = 0 ; DbgLog((LOG_TRACE, 1, TEXT("WARNING: Unknown char (%d) received and ignored"), (int)wChar)) ; break ; } // end of switch (wChar) } // end of else of if (wChar...) // Now convert iIndex to (iLine, iCol) pair iLine = iIndex / FONTCACHELINELENGTH ; // line of cache based on array index iCol = iIndex % FONTCACHELINELENGTH ; // actual col of a particular line of cache // Create source rect based on line and col values // HACK: There is a little bit of hack to work around the over/underhang // problem we were having for the Italic chars -- we skip one column of // pixels from the left (based on our observation) to avoid the overhang // occurance. pRect->left = iCol * (m_iCharWidth + INTERCHAR_SPACE) + m_iPixelOffset ; pRect->top = iLine * m_iCharHeight ; pRect->right = pRect->left + m_iCharWidth ; pRect->bottom = pRect->top + m_iCharHeight ; } void CLine21DecDraw::GetOutputLines(int iDestLine, RECT *prectLine) { DbgLog((LOG_TRACE, 5, TEXT("CLine21DecDraw::GetOutputLines(%d, 0x%lx)"), iDestLine, prectLine)) ; CAutoLock Lock(&m_csL21DDraw) ; if (IsBadWritePtr(prectLine, sizeof(*prectLine))) { DbgLog((LOG_ERROR, 0, TEXT("ERROR: prectOut is a bad pointer!!!"))) ; return ; } SetRect(prectLine, 0 /* m_iHorzOffset */, 0, // to stop BPC's CC wobbling m_iHorzOffset + m_iCharWidth * (MAX_CAPTION_COLUMNS+2), 0) ; // Output is inverted in Windows bitmap sense int iLineStart ; iLineStart = (iDestLine - 1) * m_iCharHeight + m_iVertOffset ; prectLine->top = iLineStart ; prectLine->bottom = iLineStart + m_iCharHeight ; }
34.69995
155
0.570528
[ "object", "solid" ]
acb4ce56ad131f8abc847539357a4765279bf455
746
cpp
C++
konkurs-przedobozowy-2018/gra.cpp
Aleshkev/algoritmika
fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189
[ "MIT" ]
2
2019-05-04T09:37:09.000Z
2019-05-22T18:07:28.000Z
konkurs-przedobozowy-2018/gra.cpp
Aleshkev/algoritmika
fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189
[ "MIT" ]
null
null
null
konkurs-przedobozowy-2018/gra.cpp
Aleshkev/algoritmika
fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef int32_t I; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); I n, m; cin >> n >> m; vector<I> t(n); for (I i = 0; i < n; ++i) cin >> t[i]; sort(t.begin(), t.end()); I max_s = 0; for (I i = 0; i < n - 2; ++i) { for (I j = i + 1; j < n - 1; ++j) { I k = (upper_bound(t.begin() + j + 1, t.end(), m - t[i] - t[j]) - t.begin() - 1); I s; if (k > j && (s = t[i] + t[j] + t[k]) <= m) { // cout << i << ' ' << j << ' ' << k << ": " << s << endl; max_s = max(max_s, s); } } } cout << max_s << '\n'; #ifdef __MINGW32__ cout.flush(); system("pause"); #endif return 0; }
18.65
71
0.426273
[ "vector" ]
acbb9476a42c9ad876d5ea606e4bf90f2acf6b65
12,101
cc
C++
src/io/RootImporter.cc
vrpascuzzi/celeritas
6a8ffc5e6551371fab7cdb5bbb55c60e65f0439f
[ "Apache-2.0", "MIT" ]
null
null
null
src/io/RootImporter.cc
vrpascuzzi/celeritas
6a8ffc5e6551371fab7cdb5bbb55c60e65f0439f
[ "Apache-2.0", "MIT" ]
null
null
null
src/io/RootImporter.cc
vrpascuzzi/celeritas
6a8ffc5e6551371fab7cdb5bbb55c60e65f0439f
[ "Apache-2.0", "MIT" ]
null
null
null
//----------------------------------*-C++-*----------------------------------// // Copyright 2020 UT-Battelle, LLC, and other Celeritas developers. // See the top-level COPYRIGHT file for details. // SPDX-License-Identifier: (Apache-2.0 OR MIT) //---------------------------------------------------------------------------// //! \file RootImporter.cc //---------------------------------------------------------------------------// #include "RootImporter.hh" #include <cstdlib> #include <iomanip> #include <tuple> #include <TFile.h> #include <TTree.h> #include <TBranch.h> #include <TLeaf.h> #include "base/Assert.hh" #include "base/Range.hh" #include "comm/Logger.hh" #include "physics/base/Units.hh" #include "ImportParticle.hh" namespace celeritas { namespace { //---------------------------------------------------------------------------// // HELPER FUNCTIONS //---------------------------------------------------------------------------// /*! * Safely switch between MatterState [MaterialParams.hh] and * ImportMaterialState [ImportMaterial.hh]. */ MatterState to_matter_state(const ImportMaterialState state) { switch (state) { case ImportMaterialState::not_defined: return MatterState::unspecified; case ImportMaterialState::solid: return MatterState::solid; case ImportMaterialState::liquid: return MatterState::liquid; case ImportMaterialState::gas: return MatterState::gas; } CELER_ASSERT_UNREACHABLE(); } } // namespace //---------------------------------------------------------------------------// /*! * Construct from path to ROOT file. */ RootImporter::RootImporter(const char* filename) { CELER_LOG(status) << "Opening ROOT file"; root_input_.reset(TFile::Open(filename, "read")); CELER_ENSURE(root_input_ && !root_input_->IsZombie()); } //---------------------------------------------------------------------------// //! Default destructor RootImporter::~RootImporter() = default; //---------------------------------------------------------------------------// /*! * Load all data from the input file. */ RootImporter::result_type RootImporter::operator()() { result_type geant_data; geant_data.particle_params = this->load_particle_data(); geant_data.processes = this->load_processes(); geant_data.geometry = this->load_geometry_data(); geant_data.material_params = this->load_material_data(); geant_data.cutoff_params = this->load_cutoff_data(); // Sort processes based on particle def IDs, process types, etc. { const ParticleParams& particles = *geant_data.particle_params; auto to_process_key = [&particles](const ImportProcess& ip) { return std::make_tuple(particles.find(PDGNumber{ip.particle_pdg}), ip.process_class); }; std::sort(geant_data.processes.begin(), geant_data.processes.end(), [&to_process_key](const ImportProcess& left, const ImportProcess& right) { return to_process_key(left) < to_process_key(right); }); } CELER_ENSURE(geant_data.particle_params); CELER_ENSURE(geant_data.geometry); CELER_ENSURE(geant_data.material_params); CELER_ENSURE(geant_data.cutoff_params); return geant_data; } //---------------------------------------------------------------------------// /*! * Load all ImportParticle objects from the ROOT file as ParticleParams. */ std::shared_ptr<ParticleParams> RootImporter::load_particle_data() { // Open the 'particles' branch and reserve size for the converted data std::unique_ptr<TTree> tree_particles( root_input_->Get<TTree>("particles")); CELER_ASSERT(tree_particles); ParticleParams::Input defs(tree_particles->GetEntries()); CELER_ASSERT(!defs.empty()); // Load the particle data ImportParticle particle; ImportParticle* temp_particle_ptr = &particle; int err_code = tree_particles->SetBranchAddress("ImportParticle", &temp_particle_ptr); CELER_ASSERT(err_code >= 0); for (auto i : range(defs.size())) { // Load a single entry into particle particle.name.clear(); tree_particles->GetEntry(i); CELER_ASSERT(!particle.name.empty()); // Convert metadata defs[i].name = particle.name; defs[i].pdg_code = PDGNumber{particle.pdg}; CELER_ASSERT(defs[i].pdg_code); // Convert data defs[i].mass = units::MevMass{particle.mass}; defs[i].charge = units::ElementaryCharge{particle.charge}; defs[i].decay_constant = (particle.is_stable ? ParticleDef::stable_decay_constant() : 1. / particle.lifetime); } // Sort by increasing mass, then by PDG code (positive before negative of // the same absolute value). Placing lighter particles // (more likely to be created by various processes, so more "light // particle" tracks) together at the beginning of the list will make it // easier to human-read the particles while debugging, and having them // at adjacent memory locations could improve cacheing. auto to_particle_key = [](const auto& inp) { int pdg = inp.pdg_code.get(); return std::make_tuple(inp.mass, std::abs(pdg), pdg < 0); }; std::sort(defs.begin(), defs.end(), [to_particle_key](const auto& lhs, const auto& rhs) { return to_particle_key(lhs) < to_particle_key(rhs); }); // Construct ParticleParams from the definitions return std::make_shared<ParticleParams>(std::move(defs)); } //---------------------------------------------------------------------------// /*! * Load all ImportProcess objects from the ROOT file as a vector. */ std::vector<ImportProcess> RootImporter::load_processes() { std::unique_ptr<TTree> tree_processes( root_input_->Get<TTree>("processes")); CELER_ASSERT(tree_processes); CELER_ASSERT(tree_processes->GetEntries()); // Load branch ImportProcess process; ImportProcess* process_ptr = &process; int err_code = tree_processes->SetBranchAddress("ImportProcess", &process_ptr); CELER_ASSERT(err_code >= 0); std::vector<ImportProcess> processes; // Populate physics process vector for (size_type i : range(tree_processes->GetEntries())) { tree_processes->GetEntry(i); processes.push_back(process); } return processes; } //---------------------------------------------------------------------------// /*! * [TEMPORARY] Load GdmlGeometryMap object from the ROOT file. * * For fully testing the loaded geometry information only. * * It will be removed as soon as we can load both MATERIAL and VOLUME * information into host/device classes. */ std::shared_ptr<GdmlGeometryMap> RootImporter::load_geometry_data() { // Open geometry branch std::unique_ptr<TTree> tree_geometry(root_input_->Get<TTree>("geometry")); CELER_ASSERT(tree_geometry); CELER_ASSERT(tree_geometry->GetEntries() == 1); // Load branch and fetch data GdmlGeometryMap geometry; GdmlGeometryMap* geometry_ptr = &geometry; int err_code = tree_geometry->SetBranchAddress("GdmlGeometryMap", &geometry_ptr); CELER_ASSERT(err_code >= 0); tree_geometry->GetEntry(0); return std::make_shared<GdmlGeometryMap>(std::move(geometry)); } //---------------------------------------------------------------------------// /*! * Load GdmlGeometryMap from the ROOT file and populate MaterialParams. */ std::shared_ptr<MaterialParams> RootImporter::load_material_data() { // Open geometry branch std::unique_ptr<TTree> tree_geometry(root_input_->Get<TTree>("geometry")); CELER_ASSERT(tree_geometry); CELER_ASSERT(tree_geometry->GetEntries() == 1); // Load branch and fetch data GdmlGeometryMap geometry; GdmlGeometryMap* geometry_ptr = &geometry; int err_code = tree_geometry->SetBranchAddress("GdmlGeometryMap", &geometry_ptr); CELER_ASSERT(err_code >= 0); tree_geometry->GetEntry(0); // Create MaterialParams input for its constructor MaterialParams::Input input; // Populate input.elements for (const auto& elem_key : geometry.elemid_to_element_map()) { MaterialParams::ElementInput element_params; element_params.atomic_number = elem_key.second.atomic_number; element_params.atomic_mass = units::AmuMass{elem_key.second.atomic_mass}; element_params.name = elem_key.second.name; input.elements.push_back(element_params); } // Populate input.materials for (const auto& mat_key : geometry.matid_to_material_map()) { MaterialParams::MaterialInput material_params; material_params.name = mat_key.second.name; material_params.temperature = mat_key.second.temperature; material_params.number_density = mat_key.second.number_density; material_params.matter_state = to_matter_state(mat_key.second.state); for (const auto& elem_key : mat_key.second.elements_num_fractions) { ElementId elem_def_id{elem_key.first}; // Populate MaterialParams number fractions material_params.elements_fractions.push_back( {elem_def_id, elem_key.second}); } input.materials.push_back(material_params); } // Construct MaterialParams and return it as a shared_ptr MaterialParams materials(input); return std::make_shared<MaterialParams>(std::move(materials)); } //---------------------------------------------------------------------------// /*! * Load Cutoff information from the ROOT file and populate CutoffParams. */ std::shared_ptr<CutoffParams> RootImporter::load_cutoff_data() { CutoffParams::Input input; input.materials = this->load_material_data(); input.particles = this->load_particle_data(); CELER_ENSURE(input.materials); CELER_ENSURE(input.particles); // Load geometry tree to access cutoff data std::unique_ptr<TTree> tree_geometry(root_input_->Get<TTree>("geometry")); CELER_ASSERT(tree_geometry); CELER_ASSERT(tree_geometry->GetEntries() == 1); // Load branch data GdmlGeometryMap geometry; GdmlGeometryMap* geometry_ptr = &geometry; int err_code = tree_geometry->SetBranchAddress("GdmlGeometryMap", &geometry_ptr); CELER_ASSERT(err_code >= 0); tree_geometry->GetEntry(0); for (auto pid : range(ParticleId{input.particles->size()})) { CutoffParams::MaterialCutoffs m_cutoffs; const auto pdg = input.particles->id_to_pdg(pid); const auto& geometry_matid_material = geometry.matid_to_material_map(); for (auto matid : range(MaterialId{input.materials->size()})) { const auto& material = geometry_matid_material.find(matid.get())->second; const auto& iter = material.pdg_cutoff.find(pdg.get()); ParticleCutoff p_cutoff; if (iter != material.pdg_cutoff.end()) { // Is a particle type with assigned cutoff values p_cutoff.energy = units::MevEnergy{iter->second.energy}; p_cutoff.range = iter->second.range; } else { // Set cutoffs to zero p_cutoff.energy = units::MevEnergy{zero_quantity()}; p_cutoff.range = 0; } m_cutoffs.push_back(p_cutoff); } input.cutoffs.insert({pdg, m_cutoffs}); } CutoffParams cutoffs(input); return std::make_shared<CutoffParams>(std::move(cutoffs)); } //---------------------------------------------------------------------------// } // namespace celeritas
34.973988
79
0.598711
[ "geometry", "object", "vector", "solid" ]
acbe9de845d69d7e66eda23feda2aa822903b230
73,985
cpp
C++
dev/Basic/shared/entities/TrainController.cpp
gusugusu1018/simmobility-prod
d30a5ba353673f8fd35f4868c26994a0206a40b6
[ "MIT" ]
50
2018-12-21T08:21:38.000Z
2022-01-24T09:47:59.000Z
dev/Basic/shared/entities/TrainController.cpp
gusugusu1018/simmobility-prod
d30a5ba353673f8fd35f4868c26994a0206a40b6
[ "MIT" ]
2
2018-12-19T13:42:47.000Z
2019-05-13T04:11:45.000Z
dev/Basic/shared/entities/TrainController.cpp
gusugusu1018/simmobility-prod
d30a5ba353673f8fd35f4868c26994a0206a40b6
[ "MIT" ]
27
2018-11-28T07:30:34.000Z
2022-02-05T02:22:26.000Z
/* * TrainController.cpp * * Created on: Feb 11, 2016 * Author: zhang huai peng */ #include <boost/algorithm/string/erase.hpp> #include <boost/algorithm/string.hpp> #include "conf/ConfigManager.hpp" #include "conf/ConfigParams.hpp" #include "logging/Log.hpp" #include "message/MessageBus.hpp" #include "event/SystemEvents.hpp" #include "event/args/ReRouteEventArgs.hpp" #include "util/Profiler.hpp" #include "util/CSVReader.hpp" #ifndef _CLASS_TRAIN_CONTROLLER_FUNCTIONS #include "entities/TrainController.hpp" #else namespace { const double MILLISECS_CONVERT_UNIT = 1000.0; } namespace sim_mob { template<typename PERSON> TrainController<PERSON>* TrainController<PERSON>::pInstance=nullptr; template<typename PERSON> boost::unordered_map<const Station*, Agent*> TrainController<PERSON>::allStationAgents; template<typename PERSON> TrainController<PERSON>::TrainController(int id, const MutexStrategy& mtxStrat):Agent(mtxStrat, id),disruptionParam(nullptr) { } template<typename PERSON> TrainController<PERSON>::~TrainController() { for (std::map<std::string, Platform*>::iterator it = mapOfIdvsPlatforms.begin(); it != mapOfIdvsPlatforms.end(); it++) { delete it->second; } for (std::map<unsigned int, Block*>::iterator it = mapOfIdvsBlocks.begin(); it != mapOfIdvsBlocks.end(); it++) { delete it->second; } for (std::map<unsigned int, PolyLine*>::iterator it = mapOfIdvsPolylines.begin(); it != mapOfIdvsPolylines.end(); it++) { delete it->second; } if(pInstance) { delete pInstance; } } template<typename PERSON> void TrainController<PERSON>::setDisruptionParams(std::string startStation,std::string endStation,std::string time) { disruptionEntity.startStation=startStation; disruptionEntity.endStation=endStation; disruptionEntity.disruptionTime=time; } template<typename PERSON> void TrainController<PERSON>::performDisruption(std::string startStation,std::string endStation,timeslice now,std::string disruptionTime) { DailyTime currentTime=ConfigManager::GetInstance().FullConfig().simStartTime()+DailyTime(now.ms()); DailyTime nextInterval=ConfigManager::GetInstance().FullConfig().simStartTime()+DailyTime(now.ms()+5000); std::string currentTimeStr=currentTime.getStrRepr(); std::string nextIntervalStr=nextInterval.getStrRepr(); if((boost::iequals(currentTimeStr,disruptionTime)||nextIntervalStr>disruptionTime)&&disruptionPerformed==false) { std::vector<std::string> platforms=getPlatformsBetweenStations("NE_1",startStation,endStation); disruptedPlatformsNamesMap_ServiceController["NE_1"]=std::vector<std::string>(); disruptedPlatformsNamesMap_ServiceController["NE_1"].insert(disruptedPlatformsNamesMap_ServiceController["NE_1"].end(),platforms.begin(),platforms.end()); platforms=getPlatformsBetweenStations("NE_2",endStation,startStation); disruptedPlatformsNamesMap_ServiceController["NE_2"]=std::vector<std::string>(); disruptedPlatformsNamesMap_ServiceController["NE_2"].insert(disruptedPlatformsNamesMap_ServiceController["NE_2"].end(),platforms.begin(),platforms.end()); disruptionPerformed=true; } } template<typename PERSON> void TrainController<PERSON>::loadOppositeLines() { const ConfigParams& configParams = ConfigManager::GetInstance().FullConfig(); const std::map<std::string, std::string>& storedProcs = configParams.getDatabaseProcMappings().procedureMappings; std::map<std::string, std::string>::const_iterator spIt = storedProcs.find("pt_opposite_lines"); if(spIt == storedProcs.end()) { Print() << "missing stored procedure for pt_opposite_lines" << std::endl; return; } soci::session sql_(soci::postgresql, configParams.getDatabaseConnectionString(false)); soci::rowset<soci::row> rs = (sql_.prepare << "select * from " + spIt->second); for (soci::rowset<soci::row>::const_iterator it=rs.begin(); it!=rs.end(); ++it) { const soci::row& r = (*it); std::string lineId = r.get<std::string>(0); std::string opp_lineId = r.get<std::string>(1); mapOfOppositeLines[lineId]=opp_lineId; } } template<typename PERSON> void TrainController<PERSON>::loadUTurnPlatforms() { const ConfigParams& configParams = ConfigManager::GetInstance().FullConfig(); const std::map<std::string, std::string>& storedProcs = configParams.getDatabaseProcMappings().procedureMappings; std::map<std::string, std::string>::const_iterator spIt = storedProcs.find("get_uturn_platforms"); if(spIt == storedProcs.end()) { Print() << "missing stored procedure for get_uturn_platforms" << std::endl; return; } soci::session sql_(soci::postgresql, configParams.getDatabaseConnectionString(false)); soci::rowset<soci::row> rs = (sql_.prepare << "select * from " + spIt->second); for (soci::rowset<soci::row>::const_iterator it=rs.begin(); it!=rs.end(); ++it) { const soci::row& r = (*it); std::string platformNo = r.get<std::string>(0); std::string lineId = r.get<std::string>(1); mapOfUturnPlatformsLines[lineId].push_back(platformNo); } } template<typename PERSON> void TrainController<PERSON>::loadTrainAvailabilities() { const ConfigParams& configParams = ConfigManager::GetInstance().FullConfig(); const std::map<std::string, std::string>& storedProcs = configParams.getDatabaseProcMappings().procedureMappings; std::map<std::string, std::string>::const_iterator spIt = storedProcs.find("get_train_fleet"); if(spIt == storedProcs.end()) { Print() << "missing stored procedure for get_train_fleet" << std::endl; return; } soci::session sql_(soci::postgresql, configParams.getDatabaseConnectionString(false)); soci::rowset<soci::row> rs = (sql_.prepare << "select * from " + spIt->second); for (soci::rowset<soci::row>::const_iterator it=rs.begin(); it!=rs.end(); ++it) { const soci::row& r = (*it); std::string lineId = r.get<std::string>(0); int min_id = r.get<int>(1); int max_id = r.get<int>(2); std::list<int> trainIdsRange; trainIdsRange.push_back(min_id); trainIdsRange.push_back(max_id); mapOfTrainMaxMinIds[lineId]=trainIdsRange; } } template<typename PERSON> void TrainController<PERSON>::loadWalkingTimeParams() { std::string filename = "walkingTimeParams.csv"; CSV_Reader variablesReader(filename, true); boost::unordered_map<std::string, std::string> variableRow; variablesReader.getNextRow(variableRow, false); while (!variableRow.empty()) { try { WalkingTimeParams walkingParams; walkingParams.stationName = variableRow.at("name"); walkingParams.alpha = boost::lexical_cast<double>(variableRow.at("alpha")); walkingParams.beta = boost::lexical_cast<double>(variableRow.at("beta")); walkingTimeAtStation[walkingParams.stationName] = walkingParams; } catch (const std::out_of_range& oor) { throw std::runtime_error("Header mis-match while reading walking Time params csv"); } catch (boost::bad_lexical_cast const&) { throw std::runtime_error("Invalid value found in walking time csv"); } variableRow.clear(); variablesReader.getNextRow(variableRow, false); } } template<typename PERSON> void TrainController<PERSON>::setDisruptedPlatforms(std::string startStation,std::string endStation,std::string lineID) { std::vector<std::string> platforms=getPlatformsBetweenStations(lineID,startStation,endStation); disruptedPlatformsNamesMap_ServiceController[lineID] = std::vector<std::string>(); disruptedPlatformsNamesMap_ServiceController[lineID].insert(disruptedPlatformsNamesMap_ServiceController[lineID].end(),platforms.begin(),platforms.end()); } template<typename PERSON> void TrainController<PERSON>::clearDisruption(std::string lineID) { disruptedPlatformsNamesMap_ServiceController[lineID].erase(disruptedPlatformsNamesMap_ServiceController[lineID].begin(),disruptedPlatformsNamesMap_ServiceController[lineID].end()); disruptedPlatformsNamesMap_ServiceController.erase(lineID); } template<typename PERSON> Entity::UpdateStatus TrainController<PERSON>::frame_tick(timeslice now) { if(disruptionParam.get()) { unsigned int baseGran = ConfigManager::GetInstance().FullConfig().baseGranMS(); DailyTime duration = disruptionParam->duration; if(duration.getValue()>baseGran) { disruptionParam->duration = DailyTime(duration.offsetMS_From(DailyTime(baseGran))); } else { disruptionParam.reset(); } } std::map<std::string,std::vector<TrainTrip*>>::iterator unscheduledTripItr; for(unscheduledTripItr = mapOfIdvsUnsheduledTrips.begin(); unscheduledTripItr != mapOfIdvsUnsheduledTrips.end(); unscheduledTripItr++) { std::vector<TrainTrip*>& trainTrips = unscheduledTripItr->second; std::vector<TrainTrip*>::iterator trItr = trainTrips.begin(); int starttime = (*trItr)->getStartTime(); while(!trainTrips.empty()&&(*trItr)->getStartTime()<=now.ms()) { const ConfigParams& config = ConfigManager::GetInstance().FullConfig(); PERSON* person = new PERSON("TrainController", config.mutexStategy()); std::vector<TripChainItem*> tripChain; TrainTrip* top = *trItr; std::string lineId = top->getLineId(); if(!isServiceTerminated(lineId)) { int trainId = getTrainId(lineId); if(trainId != -1) { if(disruptionParam.get()) { changeTrainTrip(top, disruptionParam.get()); } top->setTrainId(trainId); tripChain.push_back(top); person->setTripChain(tripChain); person->setStartTime(top->getStartTime()); trainTrips.erase(trItr); this->currWorkerProvider->scheduleForBred(person); } else { break; } } else { break; } trItr = trainTrips.begin(); } } std::map<std::string, TripStartTimePriorityQueue>::iterator it; for(it = mapOfIdvsTrip.begin(); it != mapOfIdvsTrip.end(); it++) { TripStartTimePriorityQueue& trainTrips = it->second; std::string lineId = it->first; while(!trainTrips.empty() && trainTrips.top()->getStartTime()<=now.ms()) { const ConfigParams& config = ConfigManager::GetInstance().FullConfig(); PERSON* person = new PERSON("TrainController", config.mutexStategy()); std::vector<TripChainItem*> tripChain; TrainTrip* top = trainTrips.top(); std::string lineId = top->getLineId(); if(!isServiceTerminated(lineId)) //This can be checked before { int trainId = getTrainId(lineId); if(trainId != -1) { if(disruptionParam.get()) { changeTrainTrip(top, disruptionParam.get()); } top->setTrainId(trainId); tripChain.push_back(top); person->setTripChain(tripChain); person->setStartTime(top->getStartTime()); trainTrips.pop(); this->currWorkerProvider->scheduleForBred(person); } else { break; } } else { break; } } } return Entity::UpdateStatus::Continue; } template<typename PERSON> void TrainController<PERSON>::changeTrainTrip(sim_mob::TrainTrip* trip, sim_mob::DisruptionParams* params) { std::map<std::string, std::vector<std::string>> platformsInline; for(size_t i=0; i<params->platformNames.size(); i++) { platformsInline[params->platformLineIds[i]].push_back(params->platformNames[i]); } std::string lineId = trip->getLineId(); std::map<std::string, std::vector<std::string>>::iterator it; it = platformsInline.find(lineId); if(it!=platformsInline.end()) { trip->removeTrainRoute(it->second); } } template<typename PERSON> int TrainController<PERSON>::getTrainId(const std::string& lineID) { int trainId = 0; trainId=deleteTrainFromActivePool(lineID); if(trainId == -1) { return -1; } return trainId; } template<typename PERSON> const WalkingTimeParams* TrainController<PERSON>::getWalkingTimeParams(const std::string& station) const { const WalkingTimeParams* res = nullptr; auto it = walkingTimeAtStation.find(station); if(it!=walkingTimeAtStation.end()) { res = &it->second; } return res; } template<typename PERSON> void TrainController<PERSON>::addToListOfActiveTrainsInLine(std::string lineId,Role<PERSON> *driver) { activeTrainsListLock.lock(); mapOfLineAndTrainDrivers[lineId].push_back(driver); activeTrainsListLock.unlock(); } template<typename PERSON> double TrainController<PERSON>::getMaximumDwellTime(std::string lineId) const { const ConfigParams& config = ConfigManager::GetInstance().FullConfig(); const std::map<const std::string,TrainProperties> &trainLinePropertiesMap = config.trainController.trainLinePropertiesMap; const TrainProperties &trainProperties = trainLinePropertiesMap.find(lineId)->second; return trainProperties.dwellTimeInfo.maxDwellTime; } template<typename PERSON> void TrainController<PERSON>::removeFromListOfActiveTrainsInLine(std::string lineId,Role<PERSON> *driver) { activeTrainsListLock.lock(); if(mapOfLineAndTrainDrivers.find(lineId) != mapOfLineAndTrainDrivers.end()) { std::vector <Role<PERSON>*> &vect = mapOfLineAndTrainDrivers[lineId]; typename std::vector <sim_mob::Role<PERSON>*>::iterator it = vect.begin(); it = find(vect.begin(),vect.end(),driver); if(it != vect.end()) { vect.erase(it); } } activeTrainsListLock.unlock(); } template<typename PERSON> typename std::vector <Role<PERSON>*> TrainController<PERSON>::getActiveTrainsForALine(std::string lineID) { activeTrainsListLock.lock(); std::vector <Role<PERSON>*> activeTrains = mapOfLineAndTrainDrivers[lineID]; activeTrainsListLock.unlock(); return activeTrains; } template<typename PERSON> Entity::UpdateStatus TrainController<PERSON>::frame_init(timeslice now) { messaging::MessageBus::SubscribeEvent(event::EVT_CORE_MRT_DISRUPTION, this); return Entity::UpdateStatus::Continue; } template<typename PERSON> std::string TrainController<PERSON>::getOppositeLineId(std::string lineId) { std::map<std::string,std::string>::iterator it = mapOfOppositeLines.find(lineId); if(it != mapOfOppositeLines.end()) { return it->second; } } template<typename PERSON> void TrainController<PERSON>::frame_output(timeslice now) { } template<typename PERSON> bool TrainController<PERSON>::isNonspatial() { return true; } template<typename PERSON> bool TrainController<PERSON>::getTrainRoute(const std::string& lineId, std::vector<Block*>& route) const { bool res = true; std::map<std::string, std::vector<TrainRoute>>::const_iterator it = mapOfIdvsTrainRoutes.find(lineId); if(it == mapOfIdvsTrainRoutes.end()) { res = false; } else { const std::vector<TrainRoute>& trainRoute = it->second; for(std::vector<TrainRoute>::const_iterator i = trainRoute.begin();i!=trainRoute.end();i++) { std::map<unsigned int, Block*>::const_iterator iBlock = mapOfIdvsBlocks.find(i->blockId); if(iBlock == mapOfIdvsBlocks.end()) { res = false; break; } else { route.push_back(iBlock->second); } } } return res; } template<typename PERSON> bool TrainController<PERSON>::getTrainPlatforms(const std::string& lineId, std::vector<Platform*>& platforms) const { bool res = true; std::map<std::string, std::vector<TrainPlatform>>::const_iterator it = mapOfIdvsTrainPlatforms.find(lineId); if(it == mapOfIdvsTrainPlatforms.end()) { res = false; } else { const std::vector<TrainPlatform>& trainPlatform = it->second; for(std::vector<TrainPlatform>::const_iterator i = trainPlatform.begin();i!=trainPlatform.end();i++) { std::map<std::string, Platform*>::const_iterator iPlatform = mapOfIdvsPlatforms.find(i->platformNo); if(iPlatform == mapOfIdvsPlatforms.end()) { res = false; break; } else { platforms.push_back(iPlatform->second); } } } return res; } template<typename PERSON> void TrainController<PERSON>::initTrainController() { loadPlatforms(); loadUTurnPlatforms(); loadBlocks(); loadOppositeLines(); loadTrainAvailabilities(); loadTrainRoutes(); loadTrainPlatform(); loadTransferedTimes(); loadBlockPolylines(); composeBlocksAndPolyline(); loadSchedules(); composeTrainTrips(); loadTrainLineProperties(); } //Initialize Train ids function template<typename PERSON> void TrainController<PERSON>::InitializeTrainIds(std::string lineId) { std::list<int> &listOfTrainMaxMinIds = mapOfTrainMaxMinIds[lineId]; std::list<int>::iterator itr = listOfTrainMaxMinIds.begin(); int minId = *itr; int maxId = (*(++itr)); int count = 0; std::vector<int> trainIds = std::vector<int>(); for(int i = minId; i<=maxId; i++) { trainIds.push_back(i); count++; } recycleTrainId[lineId] = trainIds; mapOfNoAvailableTrains[lineId] = count; } template<typename PERSON> void TrainController<PERSON>::composeBlocksAndPolyline() { for (std::map<unsigned int, Block*>::iterator it = mapOfIdvsBlocks.begin();it != mapOfIdvsBlocks.end(); it++) { std::map<unsigned int, PolyLine*>::iterator itLine = mapOfIdvsPolylines.find(it->first); if (itLine != mapOfIdvsPolylines.end()) { it->second->setPloyLine((*itLine).second); } else { Print()<< "Block not find polyline:"<<it->first<<std::endl; } } for(std::map<std::string, Platform*>::iterator it = mapOfIdvsPlatforms.begin(); it != mapOfIdvsPlatforms.end(); it++) { std::map<unsigned int, Block*>::iterator itBlock = mapOfIdvsBlocks.find(it->second->getAttachedBlockId()); if(itBlock != mapOfIdvsBlocks.end()) { itBlock->second->setAttachedPlatform(it->second); } else { Print()<< "Platform not find corresponding block:"<<it->first<<std::endl; } } } template<typename PERSON> TrainController<PERSON>* TrainController<PERSON>::getInstance() { if(!pInstance) { pInstance = new TrainController<PERSON>(); } return pInstance; } template<typename PERSON> bool TrainController<PERSON>::HasTrainController() { return (pInstance!=nullptr); } template<typename PERSON> void TrainController<PERSON>::loadPlatforms() { const ConfigParams& configParams = ConfigManager::GetInstance().FullConfig(); const std::map<std::string, std::string>& storedProcs = configParams.getDatabaseProcMappings().procedureMappings; std::map<std::string, std::string>::const_iterator spIt = storedProcs.find("pt_platform"); if(spIt == storedProcs.end()) { Print() << "missing stored procedure for pt_platform" << std::endl; return; } soci::session sql_(soci::postgresql, configParams.getDatabaseConnectionString(false)); soci::rowset<soci::row> rs = (sql_.prepare << "select * from " + spIt->second); for (soci::rowset<soci::row>::const_iterator it=rs.begin(); it!=rs.end(); ++it) { const soci::row& r = (*it); std::string platformNo = r.get<std::string>(0); std::string stationNo = r.get<std::string>(1); Platform* platform = new Platform(); platform->setPlatformNo(platformNo); platform->setStationNo(stationNo); platform->setLineId(r.get<std::string>(2)); platform->setCapactiy(r.get<int>(3)); platform->setType(PlatformType(r.get<int>(4))); platform->setAttachedBlockId(r.get<int>(5)); platform->setOffset(r.get<double>(6)); platform->setLength(r.get<double>(7)); mapOfIdvsPlatforms[platformNo] = platform; if(mapOfIdvsStations.find(stationNo)==mapOfIdvsStations.end()) { mapOfIdvsStations[stationNo] = new Station(stationNo); } Station* station = mapOfIdvsStations[stationNo]; station->addPlatform(platform->getLineId(), platform); } } template<typename PERSON> double TrainController<PERSON>::getMinDwellTime(std::string stationNo,std::string lineId) const { const ConfigParams& config = ConfigManager::GetInstance().FullConfig(); const std::map<const std::string,TrainProperties> &trainLinePropertiesMap = config.trainController.trainLinePropertiesMap; const TrainProperties &trainProperties = trainLinePropertiesMap.find(lineId)->second; double minDwellTime = trainProperties.dwellTimeInfo.dwellTimeAtNormalStation; if(stationNo.find("/")!= std::string::npos) { minDwellTime = trainProperties.dwellTimeInfo.dwellTimeAtInterchanges; } std::map<std::string, std::vector<TrainPlatform>>::const_iterator it = mapOfIdvsTrainPlatforms.find(lineId); const std::vector<TrainPlatform> TrainPlatforms = it->second; std::vector<TrainPlatform>::const_iterator itTrainPlatforms = TrainPlatforms.begin(); Platform *platform = mapOfIdvsPlatforms.find((*itTrainPlatforms).platformNo)->second; if(boost::iequals(platform->getStationNo(),stationNo)) { minDwellTime = trainProperties.dwellTimeInfo.dwellTimeAtTerminalStaions; } else { std::vector<TrainPlatform>::const_iterator itTrainPlatforms = TrainPlatforms.end()-1; Platform *platform = mapOfIdvsPlatforms.find((*itTrainPlatforms).platformNo)->second; if(boost::iequals(platform->getStationNo(),stationNo)) { minDwellTime = trainProperties.dwellTimeInfo.dwellTimeAtTerminalStaions; } } return minDwellTime; } template<typename PERSON> bool TrainController<PERSON>::isFirstStation(std::string lineId,Platform *platform) const { std::map<std::string, std::vector<TrainPlatform>>::const_iterator it = mapOfIdvsTrainPlatforms.find(lineId); if(it != mapOfIdvsTrainPlatforms.end()) { const std::vector<TrainPlatform> TrainPlatforms = it->second; std::vector<TrainPlatform>::const_iterator itTrainPlatforms = TrainPlatforms.begin(); if(boost::iequals((*itTrainPlatforms).platformNo,platform->getPlatformNo())) { return true; } } return false; } template<typename PERSON> void TrainController<PERSON>::loadSchedules() { const ConfigParams& configParams = ConfigManager::GetInstance().FullConfig(); const std::map<std::string, std::string>& storedProcs = configParams.getDatabaseProcMappings().procedureMappings; std::map<std::string, std::string>::const_iterator spIt = storedProcs.find("pt_mrt_dispatch_freq"); if(spIt == storedProcs.end()) { Print() << "missing stored procedure for pt_mrt_dispatch_freq" << std::endl; return; } soci::session sql_(soci::postgresql, configParams.getDatabaseConnectionString(false)); soci::rowset<soci::row> rs = (sql_.prepare << "select * from " + spIt->second); for (soci::rowset<soci::row>::const_iterator it=rs.begin(); it!=rs.end(); ++it) { const soci::row& r = (*it); std::string lineId = r.get<std::string>(1); TrainSchedule schedule; schedule.lineId = lineId; schedule.scheduleId = r.get<std::string>(0); schedule.startTime = r.get<std::string>(2); schedule.endTime = r.get<std::string>(3); schedule.headwaySec = r.get<int>(4); if(mapOfIdvsSchedules.find(lineId) == mapOfIdvsSchedules.end()) { mapOfIdvsSchedules[lineId] = std::vector<TrainSchedule>(); } mapOfIdvsSchedules[lineId].push_back(schedule); } } template<typename PERSON> void TrainController<PERSON>::composeTrainTrips() { int tripId = 1; std::map<std::string, std::vector<TrainSchedule>>::const_iterator it; for(it = mapOfIdvsSchedules.begin(); it != mapOfIdvsSchedules.end(); it++) { std::string lineId = it->first; boost::algorithm::erase_all(lineId, " "); std::vector<TrainSchedule>::const_iterator iSchedule; const std::vector<TrainSchedule>& schedules = it->second; std::vector<Block*> route; std::vector<Platform*> platforms; getTrainRoute(lineId, route); getTrainPlatforms(lineId, platforms); for(iSchedule=schedules.begin(); iSchedule!=schedules.end(); iSchedule++) { DailyTime startTime(iSchedule->startTime); DailyTime endTime(iSchedule->endTime); DailyTime advance(iSchedule->headwaySec*MILLISECS_CONVERT_UNIT); for(DailyTime time = startTime; time.isBeforeEqual(endTime); time += advance) { TrainTrip* trainTrip = new TrainTrip(); trainTrip->setTrainRoute(route); trainTrip->setTrainPlatform(platforms); trainTrip->setLineId(lineId); trainTrip->setTripId(tripId++); DailyTime start(time.offsetMS_From(ConfigManager::GetInstance().FullConfig().simStartTime())); trainTrip->setStartTime(start); trainTrip->itemType = TripChainItem::IT_TRAINTRIP; if(mapOfIdvsTrip.find(lineId) == mapOfIdvsTrip.end()) { mapOfIdvsTrip[lineId] = TripStartTimePriorityQueue(); } mapOfIdvsTrip[lineId].push(trainTrip); } } } maxTripId=tripId; } template<typename PERSON> void TrainController<PERSON>::composeTrainTripUnScheduled(std::string lineId,std::string startTime,std::string startStation) { TrainTrip* trainTrip = new TrainTrip(); trainTrip->SetScheduledStatus(true); std::vector<Block*> route; getTrainRoute(lineId, route); trainTrip->setLineId(lineId); int tripId = ++maxTripId; trainTrip->setTripId(tripId); trainTrip->setTrainRoute(route); std::vector<Platform*> platforms = getPlatforms(lineId,startStation); trainTrip->setTrainPlatform(platforms); DailyTime start(startTime); DailyTime offset(start.offsetMS_From(ConfigManager::GetInstance().FullConfig().simStartTime())); trainTrip->setStartTime(offset); trainTrip->itemType = TripChainItem::IT_TRAINTRIP; if(mapOfIdvsUnsheduledTrips.find(lineId) == mapOfIdvsUnsheduledTrips.end()) { mapOfIdvsUnsheduledTrips[lineId] = std::vector<TrainTrip*>(); } std::vector<TrainTrip*>::iterator it = mapOfIdvsUnsheduledTrips[lineId].begin(); bool flag = false; while(it != mapOfIdvsUnsheduledTrips[lineId].end()) { int startTime = (*it)->getStartTime(); if(startTime > trainTrip->getStartTime()) { mapOfIdvsUnsheduledTrips[lineId].insert(it,trainTrip); flag=true; break; } it++; } if(flag==false) { mapOfIdvsUnsheduledTrips[lineId].push_back(trainTrip); } } template<typename PERSON> std::vector<Platform*> TrainController<PERSON>::getPlatforms(std::string lineId,std::string startStation) { std::vector<Platform*> platforms; if(mapOfIdvsStations.find(startStation) != mapOfIdvsStations.end()) { Station *station = mapOfIdvsStations[startStation]; if(station) { const Platform *platform = station->getPlatform(lineId); if(mapOfIdvsTrainPlatforms.find(lineId) != mapOfIdvsTrainPlatforms.end() ) { std::vector<TrainPlatform>& trainPlatforms = mapOfIdvsTrainPlatforms[lineId]; std::vector<TrainPlatform>::const_iterator it = trainPlatforms.begin(); if(it != trainPlatforms.end()) { bool foundStartPlatform = false; while(it != trainPlatforms.end()) { std::string platformNo=(*it).platformNo; if(boost::iequals(platformNo,platform->getPlatformNo())) { foundStartPlatform = true; } if(foundStartPlatform) { if(mapOfIdvsPlatforms.find(platformNo) != mapOfIdvsPlatforms.end()) { Platform *plt = mapOfIdvsPlatforms[platformNo]; platforms.push_back(plt); } else { platforms.erase(platforms.begin(),platforms.end()); break; } } it++; } } } } } return platforms; } template<typename PERSON> void TrainController<PERSON>::loadBlocks() { const ConfigParams& configParams = ConfigManager::GetInstance().FullConfig(); const std::map<std::string, std::string>& storedProcs = configParams.getDatabaseProcMappings().procedureMappings; std::map<std::string, std::string>::const_iterator spIt = storedProcs.find("pt_mrt_block"); if(spIt == storedProcs.end()) { Print() << "missing stored procedure for pt_mrt_block" << std::endl; return; } soci::session sql_(soci::postgresql, configParams.getDatabaseConnectionString(false)); soci::rowset<soci::row> rs = (sql_.prepare << "select * from " + spIt->second); for (soci::rowset<soci::row>::const_iterator it = rs.begin(); it != rs.end(); ++it) { const soci::row& r = (*it); int blockId = r.get<int>(0); Block* block = new Block(); block->setBlockId(blockId); block->setSpeedLimit(r.get<double>(1)); block->setAccelerateRate(r.get<double>(2)); block->setDecelerateRate(r.get<double>(3)); block->setLength(r.get<double>(4)); mapOfIdvsBlocks[blockId] = block; } } template<typename PERSON> TrainPlatform TrainController<PERSON>::getNextPlatform(std::string platformNo,std::string lineID) { std::vector<TrainPlatform>& trainPlatforms = mapOfIdvsTrainPlatforms[lineID]; typename std::vector<TrainPlatform>::const_iterator it = trainPlatforms.begin(); while(it != trainPlatforms.end()) { if(boost::iequals((*it).platformNo,platformNo)) { break; } it++; } if(it!=trainPlatforms.end()) { it++; if(it != trainPlatforms.end()) { return (*it); } } } template<typename PERSON> bool TrainController<PERSON>::isTerminalPlatform(std::string platformNo,std::string lineID) { if(mapOfIdvsTrainPlatforms.find(lineID) == mapOfIdvsTrainPlatforms.end()) { return false; } std::vector<TrainPlatform>& trainPlatforms = mapOfIdvsTrainPlatforms[lineID]; TrainPlatform endPlt = *(trainPlatforms.end()-1); if(boost::iequals(platformNo,endPlt.platformNo) == true) { return true; } return false; } template<typename PERSON> Platform* TrainController<PERSON>::getPlatformFromId(std::string platformNo) { if(mapOfIdvsPlatforms.find(platformNo)!=mapOfIdvsPlatforms.end()) { return mapOfIdvsPlatforms[platformNo]; } else { return nullptr; } } template<typename PERSON> std::vector<Block*> TrainController<PERSON>::getBlocks(std::string lineId) { std::map<std::string, std::vector<TrainRoute>>::const_iterator it = mapOfIdvsTrainRoutes.find(lineId); std::vector<Block*> blockVector; if(it==mapOfIdvsTrainRoutes.end()) { //res = false; } else { const std::vector<TrainRoute>& trainRoute = it->second; for(std::vector<TrainRoute>::const_iterator i = trainRoute.begin(); i != trainRoute.end(); i++) { std::map<unsigned int, Block*>::iterator iBlock = mapOfIdvsBlocks.find(i->blockId); blockVector.push_back(iBlock->second); } } return blockVector; } template<typename PERSON> Block* TrainController<PERSON>::getBlock(int blockId) { std::map<unsigned int, Block*>::iterator iBlock = mapOfIdvsBlocks.find(blockId); return iBlock->second; } template<typename PERSON> std::vector<std::string> TrainController<PERSON>::getLinesBetweenTwoStations(std::string src,std::string dest) { typename std::map<std::string, std::vector<TrainRoute>>::const_iterator it = mapOfIdvsTrainRoutes.begin(); std::vector<std::string> lines; while(it != mapOfIdvsTrainRoutes.end()) { const std::vector<TrainRoute>& route = it->second; std::vector<TrainRoute> ::const_iterator tritr = route.begin(); bool originFound=false; while(tritr != route.end()) { int blockId = (*tritr).blockId; typename std::map<unsigned int, Block*>::const_iterator iBlock = mapOfIdvsBlocks.find(blockId); Block *block = (iBlock)->second; Platform *plt = block->getAttachedPlatform(); if(plt) { std::string stationNo = plt->getStationNo(); if(boost::iequals(stationNo, src)) { originFound=true; } else if(boost::iequals(stationNo, dest)&&originFound==true) { lines.push_back((*tritr).lineId); break; } } } it++; } return lines; } template<typename PERSON> void TrainController<PERSON>::loadTrainRoutes() { const ConfigParams& configParams = ConfigManager::GetInstance().FullConfig(); const std::map<std::string, std::string>& storedProcs = configParams.getDatabaseProcMappings().procedureMappings; std::map<std::string, std::string>::const_iterator spIt = storedProcs.find("pt_mrt_route"); if(spIt == storedProcs.end()) { Print() << "missing stored procedure for pt_mrt_route" << std::endl; return; } soci::session sql_(soci::postgresql, configParams.getDatabaseConnectionString(false)); soci::rowset<soci::row> rs = (sql_.prepare << "select * from " + spIt->second); for (soci::rowset<soci::row>::const_iterator it = rs.begin(); it != rs.end(); ++it) { const soci::row& r = (*it); std::string lineId = r.get<std::string>(0); TrainRoute route; route.lineId = lineId; route.blockId = r.get<int>(1); route.sequenceNo = r.get<int>(2); if(mapOfIdvsTrainRoutes.find(lineId) == mapOfIdvsTrainRoutes.end()) { mapOfIdvsTrainRoutes[lineId] = std::vector<TrainRoute>(); } mapOfIdvsTrainRoutes[lineId].push_back(route); mapOfTrainServiceTerminated[lineId]=false; InitializeTrainIds(lineId); } } template<typename PERSON> void TrainController<PERSON>::loadTrainPlatform() { const ConfigParams& configParams = ConfigManager::GetInstance().FullConfig(); const std::map<std::string, std::string>& storedProcs = configParams.getDatabaseProcMappings().procedureMappings; std::map<std::string, std::string>::const_iterator spIt = storedProcs.find("pt_mrt_platform"); if(spIt == storedProcs.end()) { Print() << "missing stored procedure for pt_mrt_platform" << std::endl; return; } soci::session sql_(soci::postgresql, configParams.getDatabaseConnectionString(false)); soci::rowset<soci::row> rs = (sql_.prepare << "select * from " + spIt->second); for (soci::rowset<soci::row>::const_iterator it=rs.begin(); it!=rs.end(); ++it) { const soci::row& r = (*it); std::string lineId = r.get<std::string>(0); TrainPlatform platform; platform.lineId = lineId; platform.platformNo = r.get<std::string>(1); platform.sequenceNo = r.get<int>(2); if(mapOfIdvsTrainPlatforms.find(lineId)==mapOfIdvsTrainPlatforms.end()) { mapOfIdvsTrainPlatforms[lineId] = std::vector<TrainPlatform>(); } mapOfIdvsTrainPlatforms[lineId].push_back(platform); } } template<typename PERSON> void TrainController<PERSON>::loadTransferedTimes() { } template<typename PERSON> std::vector<std::string> TrainController<PERSON>::getPlatformsBetweenStations(std::string lineId,std::string startStation,std::string endStation) { std::vector<std::string> platforms; if(mapOfIdvsStations.find(startStation) == mapOfIdvsStations.end() || mapOfIdvsStations.find(endStation) == mapOfIdvsStations.end()) { return platforms; } Station *station = mapOfIdvsStations[startStation]; Station *eStation = mapOfIdvsStations[endStation]; if(station&&eStation) { Platform *platform = station->getPlatform(lineId); Platform *endPlatform = eStation->getPlatform(lineId); if(mapOfIdvsTrainPlatforms.find(lineId) != mapOfIdvsTrainPlatforms.end()) { std::vector<TrainPlatform> &trainPlatforms = mapOfIdvsTrainPlatforms[lineId]; std::vector<TrainPlatform>::const_iterator it = trainPlatforms.begin(); if(it != trainPlatforms.end()) { bool foundStartPlatform = false; while(it != trainPlatforms.end()) { std::string platformNo = (*it).platformNo; if(boost::iequals(platformNo,platform->getPlatformNo())) { foundStartPlatform = true; } if(foundStartPlatform) { Platform *plt = mapOfIdvsPlatforms.find(platformNo)->second; platforms.push_back(plt->getPlatformNo()); } if(boost::iequals(platformNo,endPlatform->getPlatformNo())) { break; } it++; } } } } return platforms; } template<typename PERSON> void TrainController<PERSON>::loadBlockPolylines() { const ConfigParams& configParams = ConfigManager::GetInstance().FullConfig(); const std::map<std::string, std::string>& storedProcs = configParams.getDatabaseProcMappings().procedureMappings; std::map<std::string, std::string>::const_iterator spIt = storedProcs.find("pt_mrt_block_polyline"); if(spIt == storedProcs.end()) { Print() << "missing stored procedure for pt_mrt_block_polyline" << std::endl; return; } soci::session sql_(soci::postgresql, configParams.getDatabaseConnectionString(false)); soci::rowset<soci::row> rs = (sql_.prepare << "select * from " + spIt->second); for (soci::rowset<soci::row>::const_iterator it=rs.begin(); it!=rs.end(); ++it) { const soci::row& r = (*it); int polylineId = r.get<int>(0); PolyPoint point; point.setPolyLineId(polylineId); point.setX(r.get<double>(1)); point.setY(r.get<double>(2)); point.setZ(r.get<double>(3)); point.setSequenceNumber(r.get<int>(4)); if(mapOfIdvsPolylines.find(polylineId) == mapOfIdvsPolylines.end()) { mapOfIdvsPolylines[polylineId] = new PolyLine(); mapOfIdvsPolylines[polylineId]->setPolyLineId(polylineId); } mapOfIdvsPolylines[polylineId]->addPoint(point); } } template<typename PERSON> void TrainController<PERSON>::printBlocks(std::ofstream& out) const { std::stringstream outStream; outStream << std::setprecision(8); outStream << "Print train network(blocks)" << std::endl; for (std::map<unsigned int, Block*>::const_iterator it = mapOfIdvsBlocks.begin();it != mapOfIdvsBlocks.end(); it++) { outStream << "(\"block\", " << it->second->getBlockId() << ", {"; outStream << "\"length\":\"" << it->second->getLength() << "\","; outStream << "\"speedlimit\":\"" << it->second->getSpeedLimit() << "\","; outStream << "\"acceleration\":\"" << it->second->getAccelerateRate() << "\","; outStream << "\"deceleration\":\"" << it->second->getDecelerateRate() << "\","; outStream << "\"points\":\"["; const PolyLine *polyLine = it->second->getPolyLine(); for (std::vector<PolyPoint>::const_iterator itPts = polyLine->getPoints().begin(); itPts != polyLine->getPoints().end(); ++itPts) { outStream << "(" << itPts->getX() << "," << itPts->getY() << "),"; } outStream << "]\","; outStream << "})\n"; } out << outStream.str() << std::endl; } template<typename PERSON> void TrainController<PERSON>::printPlatforms(std::ofstream& out) const { std::stringstream outStream; outStream << std::setprecision(8); outStream << "Print train network(platforms)" << std::endl; for(std::map<std::string, Platform*>::const_iterator it = mapOfIdvsPlatforms.begin(); it != mapOfIdvsPlatforms.end(); it++) { const Platform *platform = it->second; outStream << "(\"platform\", " << platform->getPlatformNo() << ", {"; outStream << "\"station\":\"" << platform->getStationNo() << "\","; outStream << "\"lineId\":\"" << platform->getLineId() << "\","; outStream << "\"block\":\"" << platform->getAttachedBlockId() << "\","; outStream << "\"length\":\"" << platform->getLength() << "\","; outStream << "\"offset\":\"" << platform->getOffset() << "\","; outStream << "})\n"; } out << outStream.str() << std::endl; } template<typename PERSON> void TrainController<PERSON>::printTrainNetwork(const std::string& outFileName) const { std::ofstream out(outFileName.c_str()); printBlocks(out); printPlatforms(out); } template<typename PERSON> void TrainController<PERSON>::assignTrainTripToPerson(std::set<Entity*>& activeAgents) { } template<typename PERSON> void TrainController<PERSON>::unregisterChild(Entity* child) { } template<typename PERSON> Agent* TrainController<PERSON>::getAgentFromStation(const std::string& nameStation) { const std::map<std::string, Station*>& mapOfIdvsStations = getInstance()->mapOfIdvsStations; std::map<std::string, Station*>::const_iterator it = mapOfIdvsStations.find(nameStation); if(it!=mapOfIdvsStations.end()) { if(allStationAgents.find(it->second) != allStationAgents.end()) { return allStationAgents[it->second]; } } return nullptr; } template<typename PERSON> Platform* TrainController<PERSON>::getPlatform(const std::string& lineId, const std::string& stationName) { Platform* platform = nullptr; std::map<std::string, Station*>& mapOfIdvsStations = getInstance()->mapOfIdvsStations; std::map<std::string, Station*>::const_iterator it = mapOfIdvsStations.find(stationName); if(it!=mapOfIdvsStations.end()) { Station* station = it->second; platform = station->getPlatform(lineId); } return platform; } template<typename PERSON> bool TrainController<PERSON>::isUturnPlatform(std::string platformName,std::string lineId) { std::vector<std::string> uTurnPlatforms = mapOfUturnPlatformsLines[lineId]; if(disruptedPlatformsNamesMap_ServiceController.find(lineId) != disruptedPlatformsNamesMap_ServiceController.end()) { std::vector<std::string> platformNames = disruptedPlatformsNamesMap_ServiceController[lineId]; if(std::find(platformNames.begin(),platformNames.end(),platformName) != platformNames.end()) { return false; } } if(std::find(uTurnPlatforms.begin(),uTurnPlatforms.end(),platformName) != uTurnPlatforms.end()) { return true; } return false; } template<typename PERSON> bool TrainController<PERSON>::isDisruptedPlatform(std::string platformName,std::string lineId) { std::vector<std::string> disruptedplatforms = disruptedPlatformsNamesMap_ServiceController[lineId]; if(std::find(disruptedplatforms.begin(),disruptedplatforms.end(),platformName) != disruptedplatforms.end()) { return true; } return false; } template<typename PERSON> Platform* TrainController<PERSON>::getPrePlatform(const std::string& lineId, const std::string& curPlatform) { Platform* platform = nullptr; TrainController<PERSON>* self = TrainController<PERSON>::getInstance(); std::vector<Platform*> platforms; if(self->getTrainPlatforms(lineId, platforms)) { std::vector<Platform*>::const_iterator it = platforms.begin(); Platform* prev = nullptr; while(it!=platforms.end()) { if((*it)->getPlatformNo() == curPlatform) { platform = (*it); break; } prev = *it; it++; } if(platform) { platform = prev; } } return platform; } template<typename PERSON> bool TrainController<PERSON>::isPlatformBeforeAnother(std::string firstPlatfrom ,std::string secondPlatform,std::string lineId) { std::vector<Platform*> platforms; getTrainPlatforms(lineId, platforms); bool foundFirstPlatfrom = false; std::vector<Platform*>::const_iterator it = platforms.begin(); while(it != platforms.end()) { if((*it)->getPlatformNo() == firstPlatfrom) { foundFirstPlatfrom = true; it++; continue; } if((*it)->getPlatformNo() == secondPlatform) { if(foundFirstPlatfrom == true) { return true; } return false; } it++; } return false; } template<typename PERSON> std::map<std::string,std::vector<std::string>> TrainController<PERSON>::getDisruptedPlatforms_ServiceController() { return disruptedPlatformsNamesMap_ServiceController; } template<typename PERSON> std::map<std::string,std::vector<std::string>>& TrainController<PERSON>::getUturnPlatforms() { return mapOfUturnPlatformsLines; } template<typename PERSON> bool TrainController<PERSON>::checkPlatformIsExisted(const Agent* stationAgent, const std::string& platformNo) { bool res = false; boost::unordered_map<const Station*, Agent*>::const_iterator it; for(it = allStationAgents.begin(); it!=allStationAgents.end(); it++) { if((*it).second == stationAgent) { const std::map<std::string, Platform*>& platforms = (*it).first->getPlatforms(); std::map<std::string, Platform*>::const_iterator ii; for(ii = platforms.begin(); ii!=platforms.end(); ii++) { if((*ii).second->getPlatformNo() == platformNo) { res = true; break; } } break; } } return res; } template<typename PERSON> void TrainController<PERSON>::registerStationAgent(const std::string& nameStation, Agent* stationAgent) { std::map<std::string, Station*>& mapOfIdvsStations = getInstance()->mapOfIdvsStations; std::map<std::string, Station*>::const_iterator it = mapOfIdvsStations.find(nameStation); if(it!=mapOfIdvsStations.end()) { allStationAgents[it->second] = stationAgent; } } template<typename PERSON> Station *TrainController<PERSON>::getStationFromId(std::string stationId) { Station *station=nullptr; if(mapOfIdvsStations.find(stationId) != mapOfIdvsStations.end()) { station = mapOfIdvsStations[stationId]; } return station; } template<typename PERSON> void TrainController<PERSON>::terminateTrainService(std::string lineId) { terminatedTrainServiceLock.lock(); mapOfTrainServiceTerminated[lineId] = true; terminatedTrainServiceLock.unlock(); } template<typename PERSON> bool TrainController<PERSON>::isServiceTerminated(std::string lineId) { bool isTerminated=false; terminatedTrainServiceLock.lock(); isTerminated = mapOfTrainServiceTerminated[lineId]; terminatedTrainServiceLock.unlock(); return isTerminated; } template<typename PERSON> void TrainController<PERSON>::pushTrainIntoInActivePool(int trainId,std::string lineId) { trainId = deleteTrainFromActivePool(lineId); if(trainId != -1) { addTrainToInActivePool(lineId, trainId); } } template<typename PERSON> int TrainController<PERSON>::deleteTrainFromInActivePool(std::string lineID) { inActivePoolLock.lock(); int trainId=-1; std::map<std::string, std::vector<int>>::iterator it; it = mapOfInActivePoolInLine.find(lineID); if(it != mapOfInActivePoolInLine.end()) { std::vector<int>& trainIds = it->second; if(trainIds.size() >0) { //getting the train Id trainId = trainIds[0]; trainIds.erase(trainIds.begin()); } inActivePoolLock.unlock(); return trainId; } } template<typename PERSON> int TrainController<PERSON>::deleteTrainFromActivePool(std::string lineID) { activePoolLock.lock(); int trainId = -1; std::map<std::string, std::vector<int>>::iterator it; it = recycleTrainId.find(lineID); if(it != recycleTrainId.end()) { std::vector<int>& trainIds = it->second; if(trainIds.size() >0) { if(mapOfNoAvailableTrains[lineID]>0) { trainId = trainIds[0]; trainIds.erase(trainIds.begin()); mapOfNoAvailableTrains[lineID] = mapOfNoAvailableTrains[lineID]-1; activePoolLock.unlock(); sim_mob::BasicLogger& ptMRTMoveLogger = sim_mob::Logger::log("pulledTrainId.csv"); ptMRTMoveLogger<<trainId<<","<<lineID<<std::endl; return trainId; } } } activePoolLock.unlock(); return trainId; } template<typename PERSON> void TrainController<PERSON>::addTrainToActivePool(std::string lineId,int trainId) { activePoolLock.lock(); std::map<std::string, std::vector<int>>::iterator it; it = recycleTrainId.find(lineId); if(it == recycleTrainId.end()) { recycleTrainId[lineId] = std::vector<int>(); } recycleTrainId[lineId].push_back(trainId); mapOfNoAvailableTrains[lineId] = mapOfNoAvailableTrains[lineId]+1; activePoolLock.unlock(); sim_mob::BasicLogger& ptMRTMoveLogger = sim_mob::Logger::log("returnedTrainId.csv"); ptMRTMoveLogger<<trainId<<","<<lineId<<std::endl; } template<typename PERSON> void TrainController<PERSON>::addTrainToInActivePool(std::string lineID,int trainId) { inActivePoolLock.lock(); std::map<std::string, std::vector<int>>::iterator it; it = mapOfInActivePoolInLine.find(lineID); if(it == mapOfInActivePoolInLine.end()) { mapOfInActivePoolInLine[lineID] = std::vector<int>(); } mapOfInActivePoolInLine[lineID].push_back(trainId); inActivePoolLock.unlock(); } template<typename PERSON> int TrainController<PERSON>::pullOutTrainFromInActivePool( std::string lineID) { int trainId = -1; trainId = deleteTrainFromInActivePool(lineID); if(trainId != -1) { addTrainToActivePool(lineID,trainId); } return trainId; } template<typename PERSON> void TrainController<PERSON>::pushToInactivePoolAfterTripCompletion(int trainId,std::string lineId) { trainsToBePushedToInactivePoolAfterTripCompletion[lineId].push_back(trainId); } template<typename PERSON> void TrainController<PERSON>::handleTrainReturnAfterTripCompletition(PERSON *person) { if(person) { const std::vector<TripChainItem *>& tripChain = person->getTripChain(); TrainTrip* front = dynamic_cast<TrainTrip*>(tripChain.front()); if(front) { int trainId = front->getTrainId(); std::string lineId = front->getLineId(); std::string oppLineId = getOppositeLineId(lineId); std::map<std::string,std::vector<int>>::iterator itr=trainsToBePushedToInactivePoolAfterTripCompletion.find(lineId); if(itr != trainsToBePushedToInactivePoolAfterTripCompletion.end()) { std::vector<int> &trainIds = trainsToBePushedToInactivePoolAfterTripCompletion[lineId]; std::vector<int>::iterator it=std::find(trainIds.begin(), trainIds.end(), trainId); if(it != trainIds.end()) { trainIds.erase(it); addTrainToInActivePool(oppLineId, trainId); } else { addTrainToActivePool(oppLineId, trainId); } } else { addTrainToActivePool(oppLineId, trainId); } } } } template<typename PERSON> void TrainController<PERSON>::HandleMessage(messaging::Message::MessageType type, const messaging::Message& message) { switch (type) { case MSG_TRAIN_BACK_DEPOT: { //sending the train back to depot const TrainMessage& msg = MSG_CAST(TrainMessage, message); PERSON* person = dynamic_cast<PERSON*>(msg.trainAgent); if(person) { const std::vector<TripChainItem *>& tripChain = person->getTripChain(); TrainTrip* front = dynamic_cast<TrainTrip*>(tripChain.front()); if(front) { int trainId = front->getTrainId(); std::string lineId = front->getLineId(); std::string oppLineId = getOppositeLineId(lineId); std::map<std::string,std::vector<int>>::iterator itr=trainsToBePushedToInactivePoolAfterTripCompletion.find(lineId); if(itr != trainsToBePushedToInactivePoolAfterTripCompletion.end()) { std::vector<int> &trainIds = trainsToBePushedToInactivePoolAfterTripCompletion[lineId]; std::vector<int>::iterator it=std::find(trainIds.begin(), trainIds.end(), trainId); if(it != trainIds.end()) { trainIds.erase(it); addTrainToInActivePool(oppLineId, trainId); } else { addTrainToActivePool(oppLineId, trainId); } } else { addTrainToActivePool(oppLineId, trainId); } } } break; } } } template<typename PERSON> void TrainController<PERSON>::assignResetBlockSpeeds(ResetBlockSpeeds resetSpeedBlocksEntity) { resetSpeedBlocks.push_back(resetSpeedBlocksEntity); } template<typename PERSON> void TrainController<PERSON>::resetBlockSpeeds(DailyTime now) { std::vector<ResetBlockSpeeds>::iterator it; DailyTime currentTime = now; //mention 5000 as one frame tick DailyTime nextFrameTickTime = now + DailyTime(5000); int count=-1; for(it = resetSpeedBlocks.begin() ; it < resetSpeedBlocks.end(); ) { count++; if((*it).startTime>=currentTime.getStrRepr() && (*it).startTime < nextFrameTickTime.getStrRepr() && (*it).speedReset == false) { std::string startStation = (*it).startStation; std::string endStation = (*it).endStation; std::string lineId = (*it).line; double speedLimit = (*it).speedLimit; std::vector<Platform*> platforms; getTrainPlatforms(lineId,platforms); bool startSeq = false; std::vector<Platform *>::iterator itpl; for(itpl = platforms.begin() ; itpl < platforms.end(); itpl++) { if(boost::iequals((*itpl)->getStationNo(), startStation)) { startSeq=true; } else if (boost::iequals((*itpl)->getStationNo(), endStation)) { if(!isTerminalPlatform((*itpl)->getPlatformNo(),lineId)) { break; } } if(startSeq == true) { int blockId = (*itpl)->getAttachedBlockId(); std::map<unsigned int, Block*>::iterator iBlock = mapOfIdvsBlocks.find(blockId); Block *block = iBlock->second; blockIdSpeed[(*itpl)->getLineId()][blockId] = block->getSpeedLimit(); block->setSpeedLimit(speedLimit); resetSpeedBlocks[count].speedReset = true; } } } else if((*it).endTime <= currentTime.getStrRepr()) { std::vector<Platform *>::iterator itpl; std::string startStation = (*it).startStation; std::string endStation = (*it).endStation; std::string lineId = (*it).line; std::vector<Platform*> platforms; getTrainPlatforms(lineId,platforms); bool startSeq = false; for(itpl = platforms.begin() ; itpl < platforms.end(); itpl++) { if(boost::iequals((*itpl)->getStationNo(), startStation)) { startSeq = true; } else if (boost::iequals((*itpl)->getStationNo(), endStation)) { if(!isTerminalPlatform((*itpl)->getPlatformNo(),lineId)) { break; } } if(startSeq == true) { int blockId = (*itpl)->getAttachedBlockId(); std::map<unsigned int, Block*>::iterator iBlock = mapOfIdvsBlocks.find(blockId); Block *block = iBlock->second; double defaultSpeed = blockIdSpeed[(*itpl)->getLineId()][block->getBlockId()]; block->setSpeedLimit(defaultSpeed); } } resetSpeedBlocks.erase(it); continue; } it++; } } template<typename PERSON> void TrainController<PERSON>::assignResetBlockAccelerations(ResetBlockAccelerations resetAccelerationBlocksEntity) { resetAccelerationBlocks.push_back(resetAccelerationBlocksEntity); } template<typename PERSON> void TrainController<PERSON>::loadTrainLineProperties() { const ConfigParams& configParams = ConfigManager::GetInstance().FullConfig(); const std::map<std::string, std::string>& storedProcs = configParams.getDatabaseProcMappings().procedureMappings; std::map<std::string, std::string>::const_iterator spIt = storedProcs.find("get_train_line_properties"); if(spIt == storedProcs.end()) { Print() << "missing stored procedure for get_train_line_properties" << std::endl; return; } soci::session sql_(soci::postgresql, configParams.getDatabaseConnectionString(false)); soci::rowset<soci::row> rs = (sql_.prepare << "select * from " + spIt->second); for (soci::rowset<soci::row>::const_iterator it=rs.begin(); it!=rs.end(); ++it) { TrainProperties trainProperties; TrainDwellTimeInfo dwellTimeInfo; const soci::row& r = (*it); const std::string lineId = r.get<std::string>(0); dwellTimeInfo.dwellTimeAtNormalStation = r.get<double>(1); dwellTimeInfo.dwellTimeAtTerminalStaions = r.get<double>(2); dwellTimeInfo.dwellTimeAtInterchanges = r.get<double>(3); dwellTimeInfo.maxDwellTime = r.get<double>(4); dwellTimeInfo.firstCoeff = r.get<double>(5); dwellTimeInfo.secondCoeff = r.get<double>(6); dwellTimeInfo.thirdCoeff = r.get<double>(7); dwellTimeInfo.fourthCoeff = r.get<double>(8); trainProperties.safeDistance = r.get<double>(9); trainProperties.safeHeadway = r.get<double>(10); trainProperties.minDistanceTrainBehindForUnscheduledTrain = r.get<double>(11); trainProperties.trainLength = r.get<double>(12); trainProperties.maxCapacity = r.get<int>(13); trainProperties.dwellTimeInfo = dwellTimeInfo; ConfigParams& config = ConfigManager::GetInstanceRW().FullConfig(); config.trainController.trainLinePropertiesMap[lineId] = trainProperties; } } template<typename PERSON> void TrainController<PERSON>::resetBlockAccelerations(DailyTime now) { std::vector<ResetBlockAccelerations>::iterator it; DailyTime currentTime=now; DailyTime nextFrameTickTime=now+DailyTime(5000); int count=-1; for(it=resetAccelerationBlocks.begin() ; it < resetAccelerationBlocks.end(); ) { count++; if((*it).startTime>=currentTime.getStrRepr() && (*it).startTime<nextFrameTickTime.getStrRepr() && (*it).accelerationReset == false) { std::string startStation = (*it).startStation; std::string endStation = (*it).endStation; std::string lineId = (*it).line; double accLimit = (*it).accLimit; std::vector<Platform*> platforms; getTrainPlatforms(lineId,platforms); bool startSeq=false; std::vector<Platform *>::iterator itpl; for(itpl=platforms.begin() ; itpl < platforms.end(); itpl++) { if(boost::iequals((*itpl)->getStationNo(), startStation)) { startSeq=true; } else if (boost::iequals((*itpl)->getStationNo(), endStation)) { break; } if(startSeq==true) { int blockId = (*itpl)->getAttachedBlockId(); std::map<unsigned int, Block*>::iterator iBlock = mapOfIdvsBlocks.find(blockId); Block *block=iBlock->second; blockIdAcceleration[(*itpl)->getLineId()][blockId]=block->getAccelerateRate(); block->setAccelerateRate(accLimit); block->setDecelerateRate(accLimit); resetAccelerationBlocks[count].accelerationReset = true; } } } else if((*it).endTime<=currentTime.getStrRepr()) { std::vector<Platform *>::iterator itpl; std::string startStation = (*it).startStation; std::string endStation = (*it).endStation; std::string lineId = (*it).line; std::vector<Platform*> platforms; getTrainPlatforms(lineId,platforms); bool startSeq=false; for(itpl=platforms.begin() ; itpl < platforms.end(); itpl++) { if(boost::iequals((*itpl)->getStationNo(), startStation)) { startSeq=true; } else if (boost::iequals((*itpl)->getStationNo(), endStation)) { break; } if(startSeq==true) { int blockId=(*itpl)->getAttachedBlockId(); std::map<unsigned int, Block*>::iterator iBlock = mapOfIdvsBlocks.find(blockId); Block *block=iBlock->second; double defaultAcceleration = blockIdAcceleration[(*itpl)->getLineId()][block->getBlockId()]; block->setAccelerateRate(defaultAcceleration); block->setDecelerateRate(defaultAcceleration); } } resetAccelerationBlocks.erase(it); continue; } it++; } } template<typename PERSON> void TrainController<PERSON>::onEvent(event::EventId eventId, sim_mob::event::Context ctxId, event::EventPublisher* sender, const event::EventArgs& args) { switch(eventId) { case event::EVT_CORE_MRT_DISRUPTION: { const event::DisruptionEventArgs& exArgs = MSG_CAST(event::DisruptionEventArgs, args); const DisruptionParams& disruption = exArgs.getDisruption(); disruptionParam.reset(new DisruptionParams(disruption)); break; } } } template<typename PERSON> void TrainController<PERSON>::changeNumberOfPersonsCoefficients(std::string stationName,std::string platformName,double coefficientA,double coefficientB,double coefficientC) { std::map<std::string, Platform*>::const_iterator itr = mapOfIdvsPlatforms.find(platformName); if(itr != mapOfIdvsPlatforms.end()) { const Platform *platform = itr->second; const std::string stationNo = platform->getStationNo(); std::map<std::string, Station*>::const_iterator it = mapOfIdvsStations.find(stationNo); if(it != mapOfIdvsStations.end()) { std::vector<double> vectorOfCoefficients; vectorOfCoefficients.push_back(coefficientA); vectorOfCoefficients.push_back(coefficientB); vectorOfCoefficients.push_back(coefficientC); mapOfCoefficientsOfNumberOfPersons[it->second][itr->second] = vectorOfCoefficients; } } } template<typename PERSON> const std::vector<double> TrainController<PERSON>::getNumberOfPersonsCoefficients(const Station *station,const Platform *platform) const { std::map<const Station*,std::map<const Platform*,std::vector<double>>>::const_iterator itr = mapOfCoefficientsOfNumberOfPersons.find(station); if(itr != mapOfCoefficientsOfNumberOfPersons.end()) { const std::map<const Platform*,std::vector<double>> &mapOfPlatformVsCoefficients = itr->second; std::map<const Platform*,std::vector<double>>::const_iterator it = mapOfPlatformVsCoefficients.find(platform); if(it != mapOfPlatformVsCoefficients.end()) { return it->second; } } return std::vector<double>(); } } /* namespace sim_mob */ #endif
41.194321
188
0.568494
[ "vector" ]
acc1bdd92dec38727e018741d835e7dad449fce5
2,276
cxx
C++
dreco-engine/src/game_objects/game_base.cxx
GloryOfNight/dreco-engine
1d29b747dc9277cbc5952b31833403a65a4d9c71
[ "MIT" ]
1
2020-02-27T13:29:15.000Z
2020-02-27T13:29:15.000Z
dreco-engine/src/game_objects/game_base.cxx
GloryOfNight/dreco-engine
1d29b747dc9277cbc5952b31833403a65a4d9c71
[ "MIT" ]
null
null
null
dreco-engine/src/game_objects/game_base.cxx
GloryOfNight/dreco-engine
1d29b747dc9277cbc5952b31833403a65a4d9c71
[ "MIT" ]
null
null
null
#include "game_base.hxx" #include "camera_base.hxx" #include "core/engine.hxx" #include "game_objects/game_object.hxx" #include "game_objects/game_world.hxx" #include "game_objects/mesh_object.hxx" #include "utils/math_utils.hxx" using namespace dreco; game_base::game_base(engine& _e) : game_engine(&_e) { } game_base::~game_base() { if (current_world) delete current_world; } void game_base::Tick(const float& DeltaTime) { if (current_world) { current_world->Tick(DeltaTime); } } engine* game_base::GetEngine() const { return game_engine; } void game_base::OnWindowResize() { if (const game_world* world = GetCurrentWorld(); world) { world->GetPlayerCamera()->OnScreenSizeUpdate(); } } void game_base::GetViewSize(int& _w, int& _h) const { SDL_GetWindowSize(GetEngine()->GetWindow(), &_w, &_h); } game_world* game_base::GetCurrentWorld() const { return current_world; } void game_base::SetCurrentWorld(game_world* _w) { current_world = _w; } vec2 game_base::GetWindowSize() const { int x; int y; SDL_GetWindowSize(game_engine->GetWindow(), &x, &y); return vec2(x, y); } bool game_base::IsWindowInFocus() const { return SDL_GetMouseFocus() == game_engine->GetWindow(); } vec2 game_base::GetMouseScreenPos() const { int x; int y; SDL_GetMouseState(&x, &y); return vec2(x, y); } vec2 game_base::ScreenToWorld(const vec2& _screen_coor) const { const vec2 window_size = GetWindowSize(); const mat2x3 proj_mat = GetCurrentWorld()->GetPlayerCamera()->GetProjectionMatrix(); return math_utils::UnProject(_screen_coor, window_size, GetCurrentWorld()->GetPlayerCamera()->GetViewMatrix(), proj_mat); } game_object* game_base::TryGetObectFromScreen(const vec2& _screen_coor) { if (current_world) { const auto objects = current_world->GetWorldObjectsRef(); const vec2 world_coor = ScreenToWorld(_screen_coor); for (auto obj : objects) { mesh_object* mesh = dynamic_cast<mesh_object*>(obj.second); if (mesh && mesh->GetIsRendered() && mesh->GetIsPointInBounds(world_coor)) { return mesh; } } } return nullptr; } resource_manager* game_base::GetResourceManager() const { return GetEngine()->GetResourceManager(); } audio_manager* game_base::GetAudioManager() const { return GetEngine()->GetAudioManager(); }
19.964912
85
0.733304
[ "mesh" ]
acce0afa1b144eb602544bc3dfcfbe168ac0d2e3
2,182
cpp
C++
src/main.cpp
SeanMott/CGen
221472746a8b35335af7a51d1b195ecda374dbd6
[ "MIT" ]
1
2020-11-24T10:01:39.000Z
2020-11-24T10:01:39.000Z
src/main.cpp
SeanMott/CGen
221472746a8b35335af7a51d1b195ecda374dbd6
[ "MIT" ]
null
null
null
src/main.cpp
SeanMott/CGen
221472746a8b35335af7a51d1b195ecda374dbd6
[ "MIT" ]
null
null
null
/* CGen allows for C code to be produced and then compiled. CGen comes as a lib this main file is just to test Tokens into C code. For right now it uses Clang and a path has to be given to were Clang is. If no Clang is provided it will use a version that comes with CGen. Github Link: Created by Sean R. Mott || 09/14/2020 */ #include "Compile.h" #include "CWriter.h" #include "ArgEngine.h" #include <stdio.h> #include <iostream> using namespace std; int main(int args, char* argv[]) { //call Arg engine and pass arguments const char* arguments[] = { "-name", "HelloCGen", "-out", "exe", "-run", "true" }; CGen::ArgEngine::Init(6, arguments); //pass tokens for testing vector<CGen::Token> tokens = { //includes {CGen::TokenType::IncludeBracket, "stdio.h"}, //holds the hello CGen string {CGen::TokenType::DataType, "char*"}, {CGen::TokenType::Indentifier, "text"}, {CGen::TokenType::Space, ""}, {CGen::TokenType::Operator, "="}, {CGen::TokenType::Space, ""}, {CGen::TokenType::StringData, "Hello CGen!\\nThis is a string made with CGen!\\n"}, {CGen::TokenType::Operator, ";"}, //makes the main function {CGen::TokenType::DataType, "int"}, {CGen::TokenType::Indentifier, "main"}, {CGen::TokenType::Operator, "("}, {CGen::TokenType::DataType, "int"}, {CGen::TokenType::Indentifier, "args"}, {CGen::TokenType::Operator, ","}, {CGen::TokenType::DataType, "char*"}, {CGen::TokenType::Indentifier, "argv[]"}, {CGen::TokenType::Operator, ")"}, {CGen::TokenType::NewLine, ""}, {CGen::TokenType::Operator, "{"}, //makes a call to the built in print function {CGen::TokenType::Indentifier, "printf"}, {CGen::TokenType::Operator, "("}, {CGen::TokenType::StringData, "%s\\n"}, {CGen::TokenType::Operator, ","}, {CGen::TokenType::Indentifier, "text"}, {CGen::TokenType::Operator, ")"}, {CGen::TokenType::Operator, ";"}, //returns 0 {CGen::TokenType::ControlFlow, "return"}, {CGen::TokenType::NumberData, "0"}, {CGen::TokenType::Operator, ";"}, //finishs main {CGen::TokenType::Operator, "}"} }; //parse Tokens into C code and compile CGen::Compile(CGen::CGen(tokens)); cin.get(); return 0; }
27.275
85
0.649863
[ "vector" ]
acd777806f82d804ae4d201145ec35d0cbefddec
553
cpp
C++
Society2.0/Society2.0/CLSuggestion.cpp
simsim314/Society2.0
a95e42122e2541b7544dd641247681996f1e625a
[ "Unlicense" ]
1
2019-07-11T13:10:43.000Z
2019-07-11T13:10:43.000Z
Society2.0/Society2.0/CLSuggestion.cpp
mdheller/Society2.0
a95e42122e2541b7544dd641247681996f1e625a
[ "Unlicense" ]
1
2019-02-19T12:32:52.000Z
2019-03-07T20:49:50.000Z
Society2.0/Society2.0/CLSuggestion.cpp
mdheller/Society2.0
a95e42122e2541b7544dd641247681996f1e625a
[ "Unlicense" ]
1
2020-01-10T12:37:30.000Z
2020-01-10T12:37:30.000Z
#include "CLSuggestion.h" #include <iostream> void CLSuggestion::Show() { vector<string> current = navigator->children_hash; cout << navigator->Title() << "\n"; for (int i = 0; i < current.size(); i++) { cout << "Choose " << i << " : " << navigator->children_names[current[i]] << "\n"; } } int CLSuggestion::UserResponse() { int idx; cin >> idx; next_navigator = navigator->NavigateToChild(navigator->children_hash[idx]); return -1; } CLSuggestion::CLSuggestion() { } CLSuggestion::~CLSuggestion() { }
16.757576
84
0.607595
[ "vector" ]
acd80abe265e04dabeda9bf7c37e16b5063251a9
1,741
hpp
C++
src/ECS/Entity.hpp
MajorArkwolf/ICT398-Project-Red
953f047507356aafdea856ff28f49de5b97b66cc
[ "MIT" ]
2
2021-04-18T09:49:36.000Z
2021-06-08T03:19:18.000Z
src/ECS/Entity.hpp
MajorArkwolf/ICT398-Project-Red
953f047507356aafdea856ff28f49de5b97b66cc
[ "MIT" ]
null
null
null
src/ECS/Entity.hpp
MajorArkwolf/ICT398-Project-Red
953f047507356aafdea856ff28f49de5b97b66cc
[ "MIT" ]
1
2022-03-14T06:06:07.000Z
2022-03-14T06:06:07.000Z
#pragma once #include <entt/entt.hpp> #include "ECS/ECS.hpp" class Entity { public: /** * Default Constructor */ Entity() = default; /** * Creates an entity * @param entity_id the id for the entity being created. * @param ecs_object the entity object system. */ Entity(entt::entity entity_id, ECS *ecs_object); /** * Add a component to an entity. * @tparam T the type * @tparam Args the arguments to construct it. * @param args the arguments * @return reference to the object. */ template<typename T, typename... Args> T &AddComponent(Args &&... args) { return ecs_->registry_.emplace<T>(this->entity_handle_, std::forward<Args>(args)...); } /** * Returns a reference to a component. * @tparam T type of object to return. * @return the component of the given type. */ template<typename T> T &GetComponent() { return ecs_->registry_.get<T>(this->entity_handle_); } /** * Checks if the component exists. * @tparam T the component your checking for. * @return true or false. */ template<typename T> bool HasComponent() { return ecs_->registry_.has<T>(this->entity_handle_); } /** * Removes a component. * @tparam T the component to remove. */ template<typename T> void RemoveComponent() { ecs_->registry_.remove<T>(this->entity_handle_); } entt::entity GetID() const { return entity_handle_; } private: /// The id of the given reference. entt::entity entity_handle_ = entt::entity{0}; /// The ecs system that it refers to. Passed in by reference. ECS *ecs_ = nullptr; };
24.871429
93
0.602527
[ "object" ]
ace72b76df858443e57d90737c7fcd3ca0652771
7,635
cpp
C++
src/main.cpp
ThingsFlare/switch-esp8266
53972651e07df1176ba46399b1b26381523ec999
[ "MIT" ]
null
null
null
src/main.cpp
ThingsFlare/switch-esp8266
53972651e07df1176ba46399b1b26381523ec999
[ "MIT" ]
null
null
null
src/main.cpp
ThingsFlare/switch-esp8266
53972651e07df1176ba46399b1b26381523ec999
[ "MIT" ]
null
null
null
#include <FS.h> #include <ThingsBoard.h> #include <ESP8266WiFi.h> #include <ArduinoJson.h> #include <ESPAsyncWebServer.h> #include <ESPAsyncWiFiManager.h> //https://github.com/tzapu/WiFiManager // #include "SoftwareSerial.h" // See https://thingsboard.io/docs/getting-started-guides/helloworld/ // to understand how to obtain an access token // // Baud rate for serial debug // #define SERIAL_DEBUG_BAUD 9600 // // Baud rate for communicating with ESP chip // #define SERIAL_ESP8266_BAUD 9600 // Serial driver for ESP // SoftwareSerial soft(2, 3); // RX, TX // Initialize the Ethernet client object // WiFiEspClient espClient; // Initialize ThingsBoard instance #define VALUE_KEY "value" #define COUNT_OF(x) ((sizeof(x) / sizeof(0 [x])) / ((size_t)(!(sizeof(x) % sizeof(0 [x]))))) #define SWITCH_PIN 5 #define DEVICE_ID "Motor-Relay-01" class CustomLogger { public: static void log(const char *msg) { Serial.print("[Serial Logger] "); Serial.println(msg); } }; WiFiClient wifiClient; ThingsBoardSized<128, 32, CustomLogger> tb(wifiClient); AsyncWebServer server(80); DNSServer dns; bool subscribed = false; bool lastValue = false; void updateValueTelemetry(bool value) { Serial.println("Sending telemetry data..."); const int data_items = 1; Telemetry data[data_items] = { {"value", value}}; // // Uploads new telemetry to ThingsBoard using MQTT. // // See https://thingsboard.io/docs/reference/mqtt-api/#telemetry-upload-api // // for more details tb.sendTelemetry(data, data_items); } RPC_Response setValue(const RPC_Data &data) { bool enabled = data[VALUE_KEY]; lastValue = enabled; Serial.println("Received rpc request,"); Serial.print("value:"); Serial.print(enabled); updateValueTelemetry(enabled); digitalWrite(SWITCH_PIN, enabled); return RPC_Response(VALUE_KEY, lastValue); } RPC_Response getValue(const RPC_Data &data) { return RPC_Response(VALUE_KEY, lastValue); } RPC_Callback callbacks[] = { {"setValue", setValue}, {"getValue", getValue}, }; void subscribeToRPC() { // Subscribe for RPC, if needed if (!subscribed) { Serial.println("Subscribing for RPC..."); // Perform a subscription. All consequent data processing will happen in // callbacks as denoted by callbacks[] array. if (!tb.RPC_Subscribe(callbacks, COUNT_OF(callbacks))) { Serial.println("Failed to subscribe for RPC"); return; } Serial.println("Subscribed with "); Serial.print(COUNT_OF(callbacks)); Serial.print(" callbacks"); Serial.println("Subscribe done"); subscribed = true; } } char tb_server[100]; char tb_token[34] = "YOUR_DEVICE_TOKEN"; //flag for saving data bool shouldSaveConfig = false; //callback notifying us of the need to save config void saveConfigCallback() { Serial.println("Should save config"); shouldSaveConfig = true; } void saveConfig(DynamicJsonDocument &json) { Serial.println("saving config"); File configFile = SPIFFS.open("/config.json", "w"); if (!configFile) { Serial.println("failed to open config file for writing"); } serializeJson(json, Serial); serializeJson(json, configFile); configFile.close(); } void setup() { // put your setup code here, to run once: Serial.begin(115200); Serial.println(); pinMode(SWITCH_PIN, OUTPUT); //clean FS, for testing //SPIFFS.format(); //read configuration from FS json Serial.println("mounting FS..."); if (SPIFFS.begin()) { Serial.println("mounted file system"); if (SPIFFS.exists("/config.json")) { //file exists, reading and loading Serial.println("reading config file"); File configFile = SPIFFS.open("/config.json", "r"); if (configFile) { Serial.println("opened config file"); size_t size = configFile.size(); // Allocate a buffer to store contents of the file. std::unique_ptr<char[]> buf(new char[size]); configFile.readBytes(buf.get(), size); DynamicJsonDocument json(1024); DeserializationError error = deserializeJson(json, buf.get()); serializeJson(json, Serial); if (error) { Serial.println("failed to load json config"); } else { Serial.println("\nparsed json"); strcpy(tb_server, json["tb_server"]); strcpy(tb_token, json["tb_token"]); } } } } else { Serial.println("failed to mount FS"); } //end read // The extra parameters to be configured (can be either global or just in the setup) // After connecting, parameter.getValue() will get you the configured value // id/name placeholder/prompt default length AsyncWiFiManagerParameter custom_tb_server("server", "Thingsboard server", tb_server, 100); AsyncWiFiManagerParameter custom_tb_token("token", "Access Token", tb_token, 32); //WiFiManager //Local intialization. Once its business is done, there is no need to keep it around AsyncWiFiManager wifiManager(&server, &dns); //set config save notify callback wifiManager.setSaveConfigCallback(saveConfigCallback); //set static ip // wifiManager.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); //add all your parameters here wifiManager.addParameter(&custom_tb_server); wifiManager.addParameter(&custom_tb_token); //reset settings - for testing // wifiManager.resetSettings(); //set minimu quality of signal so it ignores AP's under that quality //defaults to 8% //wifiManager.setMinimumSignalQuality(); //sets timeout until configuration portal gets turned off //useful to make it all retry or go to sleep //in seconds //wifiManager.setTimeout(120); //fetches ssid and pass and tries to connect //if it does not connect it starts an access point with the specified name //here "AutoConnectAP" //and goes into a blocking loop awaiting configuration if (!wifiManager.autoConnect(DEVICE_ID)) { Serial.println("failed to connect and hit timeout"); delay(3000); //reset and try again, or maybe put it to deep sleep ESP.reset(); delay(5000); } //if you get here you have connected to the WiFi Serial.println("connected...yeey :)"); //read updated parameters strcpy(tb_server, custom_tb_server.getValue()); strcpy(tb_token, custom_tb_token.getValue()); //save the custom parameters to FS if (shouldSaveConfig) { Serial.println("saving config"); DynamicJsonDocument json(1024); json["tb_server"] = tb_server; json["tb_token"] = tb_token; saveConfig(json); } Serial.println("local ip"); Serial.println(WiFi.localIP()); } void loop() { delay(1000); if (!tb.connected()) { // Connect to the ThingsBoard Serial.print("Connecting to: "); Serial.print(tb_server); Serial.print(" with token "); Serial.println(tb_token); if (tb.connect(tb_server, tb_token)) { // setting the motor swith to off when the device restarts updateValueTelemetry(false); } Serial.println("Failed to connect, retrying ..."); return; } subscribeToRPC(); Serial.println("Sending attributes data..."); const int attribute_items = 3; Attribute attributes[attribute_items] = { {"device_type", "switch"}, {"active", true}, {"isOn", lastValue}, }; // Publish attribute update to ThingsBoard using MQTT. // See https://thingsboard.io/docs/reference/mqtt-api/#publish-attribute-update-to-the-server // for more details tb.sendAttributes(attributes, attribute_items); tb.loop(); }
25.969388
107
0.682384
[ "object" ]
acfebbffca003b0495077db466dcf6793c2b467c
1,580
cpp
C++
Inchworm/src/string_util.cpp
tomas-pluskal/trinityrnaseq
1d079c12c29b7c2257b5e859f830f88ccb479af5
[ "BSD-3-Clause" ]
4
2019-01-16T12:05:05.000Z
2021-11-17T08:38:21.000Z
Inchworm/src/string_util.cpp
tomas-pluskal/trinityrnaseq
1d079c12c29b7c2257b5e859f830f88ccb479af5
[ "BSD-3-Clause" ]
1
2021-11-27T03:36:45.000Z
2021-11-29T14:13:14.000Z
Inchworm/src/string_util.cpp
tomas-pluskal/trinityrnaseq
1d079c12c29b7c2257b5e859f830f88ccb479af5
[ "BSD-3-Clause" ]
7
2015-03-24T14:23:58.000Z
2020-01-15T16:54:10.000Z
#include "string_util.hpp" namespace string_util { void tokenize(const string& str, vector<string>& tokens, const string& delimiters) { /* ************************************************************************************/ /* from: http://oopweb.com/CPP/Documents/CPPHOWTO/Volume/C++Programming-HOWTO-7.html **/ /**************************************************************************************/ // Skip delimiters at beginning. string::size_type lastPos = str.find_first_not_of(delimiters, 0); // Find first "non-delimiter". string::size_type pos = str.find_first_of(delimiters, lastPos); while (string::npos != pos || string::npos != lastPos) { // Found a token, add it to the vector. tokens.push_back(str.substr(lastPos, pos - lastPos)); // Skip delimiters. Note the "not_of" lastPos = str.find_first_not_of(delimiters, pos); // Find next "non-delimiter" pos = str.find_first_of(delimiters, lastPos); } return; } /* rest is my stuff */ string join(const vector<string>& tokens, const string& delimiter) { string concat = ""; for (unsigned int i = 0; i < tokens.size(); i++) { concat = concat + tokens[i]; if (i != tokens.size()-1) { concat = concat + delimiter; } } return(concat); } } // end of string_util namespace
30.384615
96
0.474684
[ "vector" ]
4a02e79b2ebbd330c6df33436f7d1730896914e0
3,370
hpp
C++
src/car2ell.hpp
xanthospap/ngpt
fa445c5c21e657dda8c47bbbe0a6f1bf1aa45867
[ "WTFPL" ]
null
null
null
src/car2ell.hpp
xanthospap/ngpt
fa445c5c21e657dda8c47bbbe0a6f1bf1aa45867
[ "WTFPL" ]
2
2016-01-19T13:42:14.000Z
2016-01-29T19:00:05.000Z
src/car2ell.hpp
xanthospap/ngpt
fa445c5c21e657dda8c47bbbe0a6f1bf1aa45867
[ "WTFPL" ]
3
2019-06-01T03:53:41.000Z
2020-09-21T10:48:08.000Z
#ifndef __CARTESIAN_TO_ELLIPSOIDAL__ #define __CARTESIAN_TO_ELLIPSOIDAL__ #include <cmath> #include "ellipsoid.hpp" #include "geoconst.hpp" #if __cplusplus > 201103L #define CONSTEXPR constexpr #else #define CONSTEXPR #endif namespace ngpt { /** \details Transform Cartesian, geocentric coordinates to ellipsoidal (i.e. * latitude, longtitude, ellispoidal height). This is a template * function, depending on the ellipsoid parameter; see ellipsoid.hpp * * \param[in] x Cartesian, x-component, meters. * \param[in] y Cartesian, y-component, meters. * \param[in] z Cartesian, z-component, meters. * \param[out] phi Ellipsoidal latitude, radians. * \param[out] lambda Ellipsoidal longtitude, radians. * \param[out] h Ellipsoidal height, meters. * * \throw Does not throw. * * Reference: Fukushima, T., "Transformation from Cartesian to geodetic * coordinates accelerated by Halley's method", J. Geodesy (2006), * 79(12): 689-693 */ template<ellipsoid E> void car2ell(double x, double y, double z, double& phi, double& lambda, double& h) noexcept { CONSTEXPR double a { ellipsoid_traits<E>::a }; CONSTEXPR double f { ellipsoid_traits<E>::f }; // Functions of ellipsoid parameters. CONSTEXPR double aeps2 { a*a*1e-32 }; CONSTEXPR double e2 { (2.0e0-f)*f }; CONSTEXPR double e4t { e2*e2*1.5e0 }; CONSTEXPR double ep2 { 1.0e0-e2 }; CONSTEXPR double ep { std::sqrt(ep2) }; CONSTEXPR double aep { a*ep }; /* --------------------------------------------------------- * Compute Coefficients of (Modified) Quartic Equation * * Remark: Coefficients are rescaled by dividing by 'a' * ---------------------------------------------------------*/ // Compute distance from polar axis squared. double p2 { x*x + y*y }; // Compute longitude lambda. if (p2) { lambda = std::atan2(y,x); } else { lambda = .0e0; } // Ensure that Z-coordinate is unsigned. double absz { std::abs(z) }; if (p2 > aeps2) { // Continue unless at the poles // Compute distance from polar axis. double p { std::sqrt(p2) }; // Normalize. double s0 { absz/a }; double pn { p/a }; double zp { ep*s0 }; // Prepare Newton correction factors. double c0 { ep*pn }; double c02 { c0*c0 }; double c03 { c02*c0 }; double s02 { s0*s0 }; double s03 { s02*s0 }; double a02 { c02+s02 }; double a0 { std::sqrt(a02) }; double a03 { a02*a0 }; double d0 { zp*a03 + e2*s03 }; double f0 { pn*a03 - e2*c03 }; // Prepare Halley correction factor. double b0 { e4t*s02*c02*pn*(a0-ep) }; double s1 { d0*f0 - b0*s0 }; double cp { ep*(f0*f0-b0*c0) }; // Evaluate latitude and height. phi = ::atan(s1/cp); double s12 { s1*s1 }; double cp2 { cp*cp }; h = (p*cp+absz*s1-a*std::sqrt(ep2*s12+cp2)) /std::sqrt(s12+cp2); } else { // Special case: pole. phi = ngpt::DPI / 2e0; h = absz - aep; } // Restore sign of latitude. if (z < 0.e0) { phi = -phi; } // Finished. return; } } // end namespace #endif
28.803419
79
0.553412
[ "transform" ]
4a05b705acbeb843fb6e254423effb819e811d12
11,542
cpp
C++
tests/unit/plugins/dist_matrixops/dist_constant_4_loc.cpp
NanmiaoWu/phylanx
295b5f82cc39925a0d53e77ba3b6d02a65204535
[ "BSL-1.0" ]
83
2017-08-27T15:09:13.000Z
2022-01-18T17:03:41.000Z
tests/unit/plugins/dist_matrixops/dist_constant_4_loc.cpp
NanmiaoWu/phylanx
295b5f82cc39925a0d53e77ba3b6d02a65204535
[ "BSL-1.0" ]
808
2017-08-27T15:35:01.000Z
2021-12-14T17:30:50.000Z
tests/unit/plugins/dist_matrixops/dist_constant_4_loc.cpp
NanmiaoWu/phylanx
295b5f82cc39925a0d53e77ba3b6d02a65204535
[ "BSL-1.0" ]
55
2017-08-27T15:09:22.000Z
2022-03-25T12:07:34.000Z
// Copyright (c) 2020 Hartmut Kaiser // Copyright (c) 2020 Bita Hasheminezhad // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <phylanx/phylanx.hpp> #include <hpx/hpx_init.hpp> #include <hpx/iostream.hpp> #include <hpx/include/lcos.hpp> #include <hpx/modules/testing.hpp> #include <string> #include <utility> #include <vector> /////////////////////////////////////////////////////////////////////////////// phylanx::execution_tree::primitive_argument_type compile_and_run( std::string const& name, std::string const& codestr) { phylanx::execution_tree::compiler::function_list snippets; phylanx::execution_tree::compiler::environment env = phylanx::execution_tree::compiler::default_environment(); auto const& code = phylanx::execution_tree::compile(name, codestr, snippets, env); return code.run().arg_; } void test_constant_d_operation(std::string const& name, std::string const& code, std::string const& expected_str) { phylanx::execution_tree::primitive_argument_type result = compile_and_run(name, code); phylanx::execution_tree::primitive_argument_type comparison = compile_and_run(name, expected_str); HPX_TEST_EQ(hpx::cout, result, comparison); } /////////////////////////////////////////////////////////////////////////////// void test_constant_4loc_1d_0() { if (hpx::get_locality_id() == 0) { test_constant_d_operation("test_constant_4loc1d_0", R"( constant_d(42, list(13), 0, 4) )", R"( annotate_d([42.0, 42.0, 42.0, 42.0], "full_array_1", list("args", list("locality", 0, 4), list("tile", list("columns", 0, 4)))) )"); } else if (hpx::get_locality_id() == 1) { test_constant_d_operation("test_constant_4loc1d_0", R"( constant_d(42, list(13), 1, 4) )", R"( annotate_d([42.0, 42.0, 42.0], "full_array_1", list("args", list("locality", 1, 4), list("tile", list("columns", 4, 7)))) )"); } else if (hpx::get_locality_id() == 2) { test_constant_d_operation("test_constant_4loc1d_0", R"( constant_d(42, list(13), 2, 4) )", R"( annotate_d([42.0, 42.0, 42.0], "full_array_1", list("args", list("locality", 2, 4), list("tile", list("columns", 7, 10)))) )"); } else if (hpx::get_locality_id() == 3) { test_constant_d_operation("test_constant_4loc1d_0", R"( constant_d(42, list(13), 3, 4) )", R"( annotate_d([42.0, 42.0, 42.0], "full_array_1", list("args", list("locality", 3, 4), list("tile", list("columns", 10, 13)))) )"); } } /////////////////////////////////////////////////////////////////////////////// void test_constant_4loc_2d_0() { if (hpx::get_locality_id() == 0) { test_constant_d_operation("test_constant_4loc2d_0", R"( constant_d(42, list(4, 7), 0, 4) )", R"( annotate_d([[42.0, 42.0, 42.0, 42.0], [42.0, 42.0, 42.0, 42.0]], "full_array_2", list("args", list("locality", 0, 4), list("tile", list("columns", 0, 4), list("rows", 0, 2)))) )"); } else if (hpx::get_locality_id() == 1) { test_constant_d_operation("test_constant_4loc2d_0", R"( constant_d(42, list(4, 7), 1, 4) )", R"( annotate_d([[42.0, 42.0, 42.0], [42.0, 42.0, 42.0]], "full_array_2", list("args", list("locality", 1, 4), list("tile", list("columns", 4, 7), list("rows", 0, 2)))) )"); } else if (hpx::get_locality_id() == 2) { test_constant_d_operation("test_constant_4loc2d_0", R"( constant_d(42, list(4, 7), 2, 4) )", R"( annotate_d([[42.0, 42.0, 42.0, 42.0], [42.0, 42.0, 42.0, 42.0]], "full_array_2", list("args", list("locality", 2, 4), list("tile", list("columns", 0, 4), list("rows", 2, 4)))) )"); } else if (hpx::get_locality_id() == 3) { test_constant_d_operation("test_constant_4loc2d_0", R"( constant_d(42, list(4, 7), 3, 4) )", R"( annotate_d([[42.0, 42.0, 42.0], [42.0, 42.0, 42.0]], "full_array_2", list("args", list("locality", 3, 4), list("tile", list("columns", 4, 7), list("rows", 2, 4)))) )"); } } void test_constant_4loc_2d_1() { if (hpx::get_locality_id() == 0) { test_constant_d_operation("test_constant_4loc2d_1", R"( constant_d(42, list(3, 9), 0, 4, "", "column") )", R"( annotate_d([[42.0, 42.0, 42.0], [42.0, 42.0, 42.0], [42.0, 42.0, 42.0]], "full_array_3", list("args", list("locality", 0, 4), list("tile", list("columns", 0, 3), list("rows", 0, 3)))) )"); } else if (hpx::get_locality_id() == 1) { test_constant_d_operation("test_constant_4loc2d_1", R"( constant_d(42, list(3, 9), 1, 4, "", "column") )", R"( annotate_d([[42.0, 42.0], [42.0, 42.0], [42.0, 42.0]], "full_array_3", list("args", list("locality", 1, 4), list("tile", list("columns", 3, 5), list("rows", 0, 3)))) )"); } else if (hpx::get_locality_id() == 2) { test_constant_d_operation("test_constant_4loc2d_1", R"( constant_d(42, list(3, 9), 2, 4, "", "column") )", R"( annotate_d([[42.0, 42.0], [42.0, 42.0], [42.0, 42.0]], "full_array_3", list("args", list("locality", 2, 4), list("tile", list("columns", 5, 7), list("rows", 0, 3)))) )"); } else if (hpx::get_locality_id() == 3) { test_constant_d_operation("test_constant_4loc2d_1", R"( constant_d(42, list(3, 9), 3, 4, "", "column") )", R"( annotate_d([[42.0, 42.0], [42.0, 42.0], [42.0, 42.0]], "full_array_3", list("args", list("locality", 3, 4), list("tile", list("columns", 7, 9), list("rows", 0, 3)))) )"); } } void test_constant_4loc_2d_2() { if (hpx::get_locality_id() == 0) { test_constant_d_operation("test_constant_4loc2d_2", R"( constant_d(42, list(4, 9), 0, 4, "tiled_matrix_1", "row") )", R"( annotate_d([[42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0]], "tiled_matrix_1", list("args", list("locality", 0, 4), list("tile", list("columns", 0, 9), list("rows", 0, 1)))) )"); } else if (hpx::get_locality_id() == 1) { test_constant_d_operation("test_constant_4loc2d_2", R"( constant_d(42, list(4, 9), 1, 4, "tiled_matrix_1", "row") )", R"( annotate_d([[42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0]], "tiled_matrix_1", list("args", list("locality", 1, 4), list("tile", list("columns", 0, 9), list("rows", 1, 2)))) )"); } else if (hpx::get_locality_id() == 2) { test_constant_d_operation("test_constant_4loc2d_2", R"( constant_d(42, list(4, 9), 2, 4, "tiled_matrix_1", "row") )", R"( annotate_d([[42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0]], "tiled_matrix_1", list("args", list("locality", 2, 4), list("tile", list("columns", 0, 9), list("rows", 2, 3)))) )"); } else if (hpx::get_locality_id() == 3) { test_constant_d_operation("test_constant_4loc2d_2", R"( constant_d(42, list(4, 9), 3, 4, "tiled_matrix_1", "row") )", R"( annotate_d([[42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0, 42.0]], "tiled_matrix_1", list("args", list("locality", 3, 4), list("tile", list("columns", 0, 9), list("rows", 3, 4)))) )"); } } /////////////////////////////////////////////////////////////////////////////// void test_constant_4loc_3d_0() { if (hpx::get_locality_id() == 0) { test_constant_d_operation("test_constant_4loc3d_0", R"( constant_d(42, list(3, 4, 5), nil, nil, "const3d", "row") )", R"( annotate_d([[[42.0, 42.0, 42.0, 42.0, 42.0]], [[42.0, 42.0, 42.0, 42.0, 42.0]], [[42.0, 42.0, 42.0, 42.0, 42.0]]], "const3d", list("tile", list("pages", 0, 3), list("columns", 0, 5), list("rows", 0, 1))) )"); } else if (hpx::get_locality_id() == 1) { test_constant_d_operation("test_constant_4loc3d_0", R"( constant_d(42, list(3, 4, 5), nil, nil, "const3d", "row") )", R"( annotate_d([[[42.0, 42.0, 42.0, 42.0, 42.0]], [[42.0, 42.0, 42.0, 42.0, 42.0]], [[42.0, 42.0, 42.0, 42.0, 42.0]]], "const3d", list("tile", list("pages", 0, 3), list("columns", 0, 5), list("rows", 1, 2))) )"); } else if (hpx::get_locality_id() == 2) { test_constant_d_operation("test_constant_4loc3d_0", R"( constant_d(42, list(3, 4, 5), nil, nil, "const3d", "row") )", R"( annotate_d([[[42.0, 42.0, 42.0, 42.0, 42.0]], [[42.0, 42.0, 42.0, 42.0, 42.0]], [[42.0, 42.0, 42.0, 42.0, 42.0]]], "const3d", list("tile", list("pages", 0, 3), list("columns", 0, 5), list("rows", 2, 3))) )"); } else if (hpx::get_locality_id() == 3) { test_constant_d_operation("test_constant_4loc3d_0", R"( constant_d(42, list(3, 4, 5), nil, nil, "const3d", "row") )", R"( annotate_d([[[42.0, 42.0, 42.0, 42.0, 42.0]], [[42.0, 42.0, 42.0, 42.0, 42.0]], [[42.0, 42.0, 42.0, 42.0, 42.0]]], "const3d", list("tile", list("pages", 0, 3), list("columns", 0, 5), list("rows", 3, 4))) )"); } } /////////////////////////////////////////////////////////////////////////////// int hpx_main(int argc, char* argv[]) { test_constant_4loc_1d_0(); test_constant_4loc_2d_0(); test_constant_4loc_2d_1(); test_constant_4loc_2d_2(); test_constant_4loc_3d_0(); hpx::finalize(); return hpx::util::report_errors(); } int main(int argc, char* argv[]) { std::vector<std::string> cfg = { "hpx.run_hpx_main!=1" }; hpx::init_params params; params.cfg = std::move(cfg); return hpx::init(argc, argv, params); }
34.76506
80
0.457806
[ "vector" ]
4a097b702da7b7638537bd2c762471b6d139c58f
4,838
cpp
C++
copasi/elementaryFluxModes/CTableauMatrix.cpp
SzVarga/COPASI
00451b1a67eeec8272c73791ca861da754a7c4c4
[ "Artistic-2.0" ]
64
2015-03-14T14:06:18.000Z
2022-02-04T23:19:08.000Z
copasi/elementaryFluxModes/CTableauMatrix.cpp
SzVarga/COPASI
00451b1a67eeec8272c73791ca861da754a7c4c4
[ "Artistic-2.0" ]
4
2017-08-16T10:26:46.000Z
2020-01-08T12:05:54.000Z
copasi/elementaryFluxModes/CTableauMatrix.cpp
SzVarga/COPASI
00451b1a67eeec8272c73791ca861da754a7c4c4
[ "Artistic-2.0" ]
28
2015-04-16T14:14:59.000Z
2022-03-28T12:04:14.000Z
// Copyright (C) 2019 by Pedro Mendes, Rector and Visitors of the // University of Virginia, University of Heidelberg, and University // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and University of // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. // Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2002 - 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. /** * CTableauMatrix class. * Used to calculate elementary flux modes * * Created for Copasi by Stefan Hoops 2002-05-08 * (C) Stefan Hoops 2002 */ #include <iostream> #include "copasi/copasi.h" #include "CTableauMatrix.h" CTableauMatrix::CTableauMatrix(): mLine(), mFirstIrreversible(mLine.end()) {} CTableauMatrix::CTableauMatrix(const std::vector< std::vector< C_FLOAT64 > > & stoi, const size_t & reversibleNumber): mLine(), mFirstIrreversible(mLine.end()) { size_t ReactionCounter = 0; size_t ReactionNumber = stoi.size(); for (std::vector< std::vector< C_FLOAT64 > >::const_iterator Reaction = stoi.begin(); Reaction < stoi.end(); Reaction++, ReactionCounter++) { mLine.push_back(new CTableauLine(*Reaction, (ReactionCounter < reversibleNumber) ? true : false, ReactionCounter, ReactionNumber)); if (ReactionCounter == reversibleNumber) { mFirstIrreversible--; } } } CTableauMatrix::~CTableauMatrix() { for (std::list< const CTableauLine * >::iterator i = mLine.begin(); i != mLine.end(); i++) pdelete(*i); } size_t CTableauMatrix::size() const {return mLine.size();} std::list< const CTableauLine * >::iterator CTableauMatrix::begin() { return mLine.begin(); } std::list< const CTableauLine * >::const_iterator CTableauMatrix::begin() const { return mLine.begin(); } std::list< const CTableauLine * >::iterator CTableauMatrix::end() { return mLine.end(); } std::list< const CTableauLine * >::const_iterator CTableauMatrix::end() const { return mLine.end(); } void CTableauMatrix::addLine(const CTableauLine * src, const bool & check) { /* First we check whether we have a valid new flux mode */ if (!check || isValid(src)) { if (src->isReversible()) { mFirstIrreversible = mLine.insert(mFirstIrreversible, src); mFirstIrreversible++; } else if (mFirstIrreversible == mLine.end()) { mFirstIrreversible = mLine.insert(mFirstIrreversible, src); } else { mLine.push_back(src); } } else pdelete(src); } void CTableauMatrix::removeLine(const std::list< const CTableauLine * >::iterator line) { if (line == mFirstIrreversible && mFirstIrreversible == mLine.begin()) { mLine.pop_front(); mFirstIrreversible = mLine.begin(); } else if (line == mFirstIrreversible) { mFirstIrreversible--; mLine.erase(line); mFirstIrreversible++; } else { mLine.erase(line); } } bool CTableauMatrix::isValid(const CTableauLine * src) { std::list< const CTableauLine * >::iterator i; std::list< const CTableauLine * >::iterator tmp; /* Check whether we have already better lines */ for (i = mLine.begin(); i != mLine.end(); i++) if ((*i)->getScore() < src->getScore()) return false; i = mLine.begin(); /* Check whether the new line scores better than existing lines */ /* If so the existing lines are removed */ for (i = mLine.begin(); i != mLine.end();) if (src->getScore() < (*i)->getScore()) { if (i == mLine.begin()) { removeLine(i); i = mLine.begin(); } else { tmp = i; tmp--; removeLine(i); i = tmp; i++; } } else i++; return true; } std::ostream & operator << (std::ostream & os, const CTableauMatrix & m) { os << "Tableau Matrix: Number of Lines = " << m.mLine.size() << std::endl; std::list< const CTableauLine * >::const_iterator i; for (i = m.mLine.begin(); i != m.mLine.end(); i++) { os << (**i); } return os; }
25.463158
91
0.605415
[ "vector" ]
4a13035875e6ee8faee733d36b9ecd623e0bdf99
947
cpp
C++
linked_list/is_palindrome.cpp
lordstone/shua_codes
cf4e0d5488ccd8e46e0cfe0fabaaadf7894bf8f3
[ "MIT" ]
1
2016-09-14T00:54:52.000Z
2016-09-14T00:54:52.000Z
linked_list/is_palindrome.cpp
lordstone/shua_codes
cf4e0d5488ccd8e46e0cfe0fabaaadf7894bf8f3
[ "MIT" ]
null
null
null
linked_list/is_palindrome.cpp
lordstone/shua_codes
cf4e0d5488ccd8e46e0cfe0fabaaadf7894bf8f3
[ "MIT" ]
null
null
null
#include "linked_list.h" using namespace std; int findLength(lnode * head){ int count = 0; while(head){ count ++; head = head -> next; } return count; } bool isPalindrome(lnode * head){ int length = findLength(head); vector<lnode*> q; if(length < 2) return true; for(int i = 0; i < length / 2; ++i){ q.push_back(head); head = head -> next; } if(length % 2 == 1){ head = head -> next; } while(!q.empty()){ char chr = q[q.size() - 1]->val; q.pop_back(); if(chr == head -> val){ head = head -> next; }else{ return false; } } return true; } int main(int argc, char* argv[]){ string s = "abcdefghic"; if(argc > 1){ s = argv[1]; } lnode * testList = createLList(s); cout << "The input is: " << s << endl; displayLList(testList); if(isPalindrome(testList)) cout << "This is a palindrome list" << endl; else cout << "This is NOT a palindrome list" << endl; deleteLList(testList); return 0; }
17.218182
50
0.594509
[ "vector" ]
4a1fc527ba1d0a423d6dbc5cfc65bf2a6a79adb3
15,642
cpp
C++
src/encoder/media_flv_encoder.cpp
anjisuan783/media_server
443fdbda8a778c7302020ea16f4fb25cd3fd8dae
[ "MIT" ]
null
null
null
src/encoder/media_flv_encoder.cpp
anjisuan783/media_server
443fdbda8a778c7302020ea16f4fb25cd3fd8dae
[ "MIT" ]
null
null
null
src/encoder/media_flv_encoder.cpp
anjisuan783/media_server
443fdbda8a778c7302020ea16f4fb25cd3fd8dae
[ "MIT" ]
null
null
null
// // Copyright (c) 2013-2021 Winlin // // SPDX-License-Identifier: MIT // // This file is borrowed from srs with some modifications. #include "media_flv_encoder.h" #include "common/media_kernel_error.h" #include "utils/media_kernel_buffer.h" #include "common/media_io.h" #include "encoder/media_codec.h" #include "utils/media_kernel_buffer.h" namespace ma { #define __OPTIMIZE__ #define SRS_FLV_TAG_HEADER_SIZE 11 #define SRS_FLV_PREVIOUS_TAG_SIZE 4 // Transmux RTMP packets to FLV stream. class SrsFlvTransmuxer final { public: SrsFlvTransmuxer(); ~SrsFlvTransmuxer(); // Initialize the underlayer file stream. // @remark user can initialize multiple times to encode multiple flv files. // @remark, user must free the @param fw, flv encoder never close/free it. srs_error_t initialize(ISrsWriter* fw); // Write flv header. // Write following: // 1. E.2 The FLV header // 2. PreviousTagSize0 UI32 Always 0 // that is, 9+4=13bytes. srs_error_t write_header(bool has_video = true, bool has_audio = true); srs_error_t write_header(char flv_header[9]); // Write flv metadata. // @param type, the type of data, or other message type. // @see SrsFrameType // @param data, the amf0 metadata which serialize from: // AMF0 string: onMetaData, // AMF0 object: the metadata object. // @remark assert data is not NULL. srs_error_t write_metadata(char type, char* data, int size); // Write audio/video packet. // @remark assert data is not NULL. srs_error_t write_audio(int64_t timestamp, char* data, int size); srs_error_t write_video(int64_t timestamp, char* data, int size); // Get the tag size, // including the tag header, body, and 4bytes previous tag size. // @remark assert data_size is not negative. static int size_tag(int data_size); // Write the tags in a time. srs_error_t write_tags(std::vector<std::shared_ptr<MediaMessage>>& msgs); private: void cache_metadata(char type, char* data, int size, char* cache); void cache_audio(int64_t timestamp, char* data, int size, char* cache); void cache_video(int64_t timestamp, char* data, int size, char* cache); void cache_pts(int size, char* cache); srs_error_t write_tag(char* header, int header_size, char* tag, int tag_size); private: char tag_header[SRS_FLV_TAG_HEADER_SIZE]; // The cache tag header. int nb_tag_headers; char* tag_headers; // The cache pps(previous tag size) int nb_ppts; char* ppts; // The cache iovss. int nb_iovss_cache; iovec* iovss_cache; ISrsWriter* writer{nullptr}; }; SrsFlvTransmuxer::SrsFlvTransmuxer() { writer = NULL; nb_tag_headers = 0; tag_headers = NULL; nb_iovss_cache = 0; iovss_cache = NULL; nb_ppts = 0; ppts = NULL; } SrsFlvTransmuxer::~SrsFlvTransmuxer() { srs_freepa(tag_headers); srs_freepa(iovss_cache); srs_freepa(ppts); } srs_error_t SrsFlvTransmuxer::initialize(ISrsWriter* fw) { srs_assert(fw); writer = fw; return srs_success; } srs_error_t SrsFlvTransmuxer::write_header(bool has_video, bool has_audio) { srs_error_t err = srs_success; uint8_t av_flag = 0; av_flag += (has_audio? 4:0); av_flag += (has_video? 1:0); // 9bytes header and 4bytes first previous-tag-size char flv_header[] = { 'F', 'L', 'V', // Signatures "FLV" (char)0x01, // File version (for example, 0x01 for FLV version 1) (char)av_flag, // 4, audio; 1, video; 5 audio+video. (char)0x00, (char)0x00, (char)0x00, (char)0x09 // DataOffset UI32 The length of this header in bytes }; // flv specification should set the audio and video flag, // actually in practise, application generally ignore this flag, // so we generally set the audio/video to 0. // write 9bytes header. if ((err = write_header(flv_header)) != srs_success) { return srs_error_wrap(err, "write header"); } return err; } srs_error_t SrsFlvTransmuxer::write_header(char flv_header[9]) { srs_error_t err = srs_success; // write data. if ((err = writer->write((void*)flv_header, 9, NULL)) != srs_success) { return srs_error_wrap(err, "write flv header failed"); } // previous tag size. char pts[] = { (char)0x00, (char)0x00, (char)0x00, (char)0x00 }; if ((err = writer->write(pts, 4, NULL)) != srs_success) { return srs_error_wrap(err, "write pts"); } return err; } srs_error_t SrsFlvTransmuxer::write_metadata(char type, char* data, int size) { srs_error_t err = srs_success; if (size > 0) { cache_metadata(type, data, size, tag_header); } if ((err = write_tag(tag_header, sizeof(tag_header), data, size)) != srs_success) { return srs_error_wrap(err, "write tag"); } return err; } srs_error_t SrsFlvTransmuxer::write_audio(int64_t timestamp, char* data, int size) { srs_error_t err = srs_success; if (size > 0) { cache_audio(timestamp, data, size, tag_header); } if ((err = write_tag(tag_header, sizeof(tag_header), data, size)) != srs_success) { return srs_error_wrap(err, "write tag"); } return err; } srs_error_t SrsFlvTransmuxer::write_video(int64_t timestamp, char* data, int size) { srs_error_t err = srs_success; if (size > 0) { cache_video(timestamp, data, size, tag_header); } if ((err = write_tag(tag_header, sizeof(tag_header), data, size)) != srs_success) { return srs_error_wrap(err, "write flv video tag failed"); } return err; } int SrsFlvTransmuxer::size_tag(int data_size) { srs_assert(data_size >= 0); return SRS_FLV_TAG_HEADER_SIZE + data_size + SRS_FLV_PREVIOUS_TAG_SIZE; } srs_error_t SrsFlvTransmuxer::write_tags(std::vector<std::shared_ptr<MediaMessage>>& msgs) { int count = (int)msgs.size(); srs_error_t err = srs_success; // realloc the tag headers. char* cache = tag_headers; if (nb_tag_headers < count) { srs_freepa(tag_headers); nb_tag_headers = count; cache = tag_headers = new char[SRS_FLV_TAG_HEADER_SIZE * count]; } // realloc the pts. char* pts = ppts; if (nb_ppts < count) { srs_freepa(ppts); nb_ppts = count; pts = ppts = new char[SRS_FLV_PREVIOUS_TAG_SIZE * count]; } #ifndef __OPTIMIZE__ // realloc the iovss. int nb_iovss = 3 * count; iovec* iovss = iovss_cache; if (nb_iovss_cache < nb_iovss) { srs_freepa(iovss_cache); nb_iovss_cache = nb_iovss; iovss = iovss_cache = new iovec[nb_iovss]; } //TOD need optimizing std::vector<std::string> data_buffer; // the cache is ok, write each messages. iovec* iovs = iovss; for (int i = 0; i < count; i++) { auto& msg = msgs[i]; data_buffer.emplace_back(std::move(msg->payload_->FlattenChained())); // cache all flv header. if (msg->is_audio()) { cache_audio(msg->timestamp_, nullptr, msg->size_, cache); } else if (msg->is_video()) { cache_video(msg->timestamp_, nullptr, msg->size_, cache); } else { cache_metadata(SrsFrameTypeScript, nullptr, msg->size_, cache); } // cache all pts. cache_pts(SRS_FLV_TAG_HEADER_SIZE + msg->size_, pts); // all ioves. iovs[0].iov_base = cache; iovs[0].iov_len = SRS_FLV_TAG_HEADER_SIZE; iovs[1].iov_base = const_cast<char*>(data_buffer[i].c_str()); iovs[1].iov_len = msg->size_; iovs[2].iov_base = pts; iovs[2].iov_len = SRS_FLV_PREVIOUS_TAG_SIZE; // move next. cache += SRS_FLV_TAG_HEADER_SIZE; pts += SRS_FLV_PREVIOUS_TAG_SIZE; iovs += 3; } if ((err = writer->writev(iovss, nb_iovss, NULL)) != srs_success) { return srs_error_wrap(err, "write flv tags failed"); } #else int n_msg = 3 * count; std::vector<MessageChain> tmp_msgs; tmp_msgs.reserve(n_msg); int tmp_msgs_idx = 0; for (auto& msg : msgs) { // cache all flv header. if (msg->is_audio()) { cache_audio(msg->timestamp_, nullptr, msg->size_, cache); } else if (msg->is_video()) { cache_video(msg->timestamp_, nullptr, msg->size_, cache); } else { cache_metadata(SrsFrameTypeScript, nullptr, msg->size_, cache); } // cache all pts. cache_pts(SRS_FLV_TAG_HEADER_SIZE + msg->size_, pts); // all ioves. tmp_msgs.emplace_back(SRS_FLV_TAG_HEADER_SIZE, cache, MessageChain::DONT_DELETE, SRS_FLV_TAG_HEADER_SIZE); assert(msg->payload_->GetNext() == nullptr); tmp_msgs.emplace_back(*(msg->payload_)); tmp_msgs.emplace_back(SRS_FLV_PREVIOUS_TAG_SIZE, pts, MessageChain::DONT_DELETE, SRS_FLV_PREVIOUS_TAG_SIZE); tmp_msgs[tmp_msgs_idx].Append(&tmp_msgs[tmp_msgs_idx+1]); tmp_msgs[tmp_msgs_idx+1].Append(&tmp_msgs[tmp_msgs_idx+2]); if (tmp_msgs_idx != 0) { tmp_msgs[tmp_msgs_idx - 1].Append(&tmp_msgs[tmp_msgs_idx]); } // move next. cache += SRS_FLV_TAG_HEADER_SIZE; pts += SRS_FLV_PREVIOUS_TAG_SIZE; tmp_msgs_idx += 3; } if ((err = writer->write(&tmp_msgs[0], nullptr)) != srs_success) { return srs_error_wrap(err, "write flv tags failed"); } #endif return err; } void SrsFlvTransmuxer::cache_metadata(char type, char*, int size, char* cache) { // 11 bytes tag header /*char tag_header[] = { (char)type, // TagType UB [5], 18 = script data (char)0x00, (char)0x00, (char)0x00, // DataSize UI24 Length of the message. (char)0x00, (char)0x00, (char)0x00, // Timestamp UI24 Time in milliseconds at which the data in this tag applies. (char)0x00, // TimestampExtended UI8 (char)0x00, (char)0x00, (char)0x00, // StreamID UI24 Always 0. };*/ SrsBuffer tag_stream(cache, 11); // write data size. tag_stream.write_1bytes(type); tag_stream.write_3bytes(size); tag_stream.write_3bytes(0x00); tag_stream.write_1bytes(0x00); tag_stream.write_3bytes(0x00); } void SrsFlvTransmuxer::cache_audio(int64_t timestamp, char*, int size, char* cache) { timestamp &= 0x7fffffff; // 11bytes tag header /*char tag_header[] = { (char)SrsFrameTypeAudio, // TagType UB [5], 8 = audio (char)0x00, (char)0x00, (char)0x00, // DataSize UI24 Length of the message. (char)0x00, (char)0x00, (char)0x00, // Timestamp UI24 Time in milliseconds at which the data in this tag applies. (char)0x00, // TimestampExtended UI8 (char)0x00, (char)0x00, (char)0x00, // StreamID UI24 Always 0. };*/ SrsBuffer tag_stream(cache, 11); // write data size. tag_stream.write_1bytes(SrsFrameTypeAudio); tag_stream.write_3bytes(size); tag_stream.write_3bytes((int32_t)timestamp); // default to little-endian tag_stream.write_1bytes((timestamp >> 24) & 0xFF); tag_stream.write_3bytes(0x00); } void SrsFlvTransmuxer::cache_video(int64_t timestamp, char*, int size, char* cache) { timestamp &= 0x7fffffff; // 11bytes tag header /*char tag_header[] = { (char)SrsFrameTypeVideo, // TagType UB [5], 9 = video (char)0x00, (char)0x00, (char)0x00, // DataSize UI24 Length of the message. (char)0x00, (char)0x00, (char)0x00, // Timestamp UI24 Time in milliseconds at which the data in this tag applies. (char)0x00, // TimestampExtended UI8 (char)0x00, (char)0x00, (char)0x00, // StreamID UI24 Always 0. };*/ SrsBuffer tag_stream(cache, 11); // write data size. tag_stream.write_1bytes(SrsFrameTypeVideo); tag_stream.write_3bytes(size); tag_stream.write_3bytes((int32_t)timestamp); // default to little-endian tag_stream.write_1bytes((timestamp >> 24) & 0xFF); tag_stream.write_3bytes(0x00); } void SrsFlvTransmuxer::cache_pts(int size, char* cache) { SrsBuffer tag_stream(cache, 11); tag_stream.write_4bytes(size); } srs_error_t SrsFlvTransmuxer::write_tag(char* header, int header_size, char* tag, int tag_size) { srs_error_t err = srs_success; // PreviousTagSizeN UI32 Size of last tag, including its header, in bytes. char pre_size[SRS_FLV_PREVIOUS_TAG_SIZE]; cache_pts(tag_size + header_size, pre_size); #ifndef __OPTIMIZE__ iovec iovs[3]; iovs[0].iov_base = header; iovs[0].iov_len = header_size; iovs[1].iov_base = tag; iovs[1].iov_len = tag_size; iovs[2].iov_base = pre_size; iovs[2].iov_len = SRS_FLV_PREVIOUS_TAG_SIZE; if ((err = writer->writev(iovs, 3, NULL)) != srs_success) { return srs_error_wrap(err, "write flv tag failed"); } #else MessageChain p1{(uint32_t)header_size, header, MessageChain::DONT_DELETE, (uint32_t)header_size}; MessageChain p2{(uint32_t)tag_size, tag, MessageChain::DONT_DELETE, (uint32_t)tag_size}; MessageChain p3{SRS_FLV_PREVIOUS_TAG_SIZE, pre_size, MessageChain::DONT_DELETE, SRS_FLV_PREVIOUS_TAG_SIZE}; p1.Append(&p2); p2.Append(&p3); if ((err = writer->write(&p1, NULL)) != srs_success) { return srs_error_wrap(err, "write flv tag failed"); } #endif return err; } MDEFINE_LOGGER(SrsFlvStreamEncoder, "SrsFlvStreamEncoder"); SrsFlvStreamEncoder::SrsFlvStreamEncoder() : enc{std::make_unique<SrsFlvTransmuxer>()} { } SrsFlvStreamEncoder::~SrsFlvStreamEncoder() = default; srs_error_t SrsFlvStreamEncoder::initialize(SrsFileWriter* w, SrsBufferCache* /*c*/) { srs_error_t err = srs_success; if ((err = enc->initialize(w)) != srs_success) { return srs_error_wrap(err, "init encoder"); } return err; } srs_error_t SrsFlvStreamEncoder::write_audio(int64_t timestamp, char* data, int size) { srs_error_t err = srs_success; if ((err = write_header()) != srs_success) { return srs_error_wrap(err, "write header"); } return enc->write_audio(timestamp, data, size); } srs_error_t SrsFlvStreamEncoder::write_video(int64_t timestamp, char* data, int size) { srs_error_t err = srs_success; if ((err = write_header()) != srs_success) { return srs_error_wrap(err, "write header"); } return enc->write_video(timestamp, data, size); } srs_error_t SrsFlvStreamEncoder::write_metadata(int64_t timestamp, char* data, int size) { srs_error_t err = srs_success; if ((err = write_header()) != srs_success) { return srs_error_wrap(err, "write header"); } return enc->write_metadata(SrsFrameTypeScript, data, size); } bool SrsFlvStreamEncoder::has_cache() { // for flv stream, use gop cache of SrsLiveSource is ok. return false; } srs_error_t SrsFlvStreamEncoder::dump_cache(MediaConsumer*, JitterAlgorithm) { // for flv stream, ignore cache. return srs_success; } srs_error_t SrsFlvStreamEncoder::write_tags(std::vector<std::shared_ptr<MediaMessage>>& msgs) { int count = (int)msgs.size(); srs_error_t err = srs_success; // For https://github.com/ossrs/srs/issues/939 if (!header_written) { bool has_video = false; bool has_audio = false; for (int i = 0; i < count && (!has_video || !has_audio); i++) { auto& msg = msgs[i]; if (msg->is_video()) { has_video = true; } else if (msg->is_audio()) { has_audio = true; } } // Drop data if no A+V. if (!has_video && !has_audio) { return err; } if ((err = write_header(has_video, has_audio)) != srs_success) { return srs_error_wrap(err, "write header"); } } return enc->write_tags(msgs); } srs_error_t SrsFlvStreamEncoder::write_header(bool has_video, bool has_audio) { srs_error_t err = srs_success; if (!header_written) { header_written = true; if ((err = enc->write_header(has_video, has_audio)) != srs_success) { return srs_error_wrap(err, "write header"); } MLOG_CTRACE("FLV: write header audio=%d, video=%d", has_audio, has_video); } return err; } }
29.347092
116
0.677599
[ "object", "vector" ]
4a255b0b3bc088b6c98ba2d623e16ce9dee264f2
3,890
cpp
C++
wpd/WpdServiceSampleDriver/WpdService.cpp
ixjf/Windows-driver-samples
38985ba91feb685095754775e101389ad90c2aa6
[ "MS-PL" ]
3,084
2015-03-18T04:40:32.000Z
2019-05-06T17:14:33.000Z
wpd/WpdServiceSampleDriver/WpdService.cpp
ixjf/Windows-driver-samples
38985ba91feb685095754775e101389ad90c2aa6
[ "MS-PL" ]
275
2015-03-19T18:44:41.000Z
2019-05-06T14:13:26.000Z
wpd/WpdServiceSampleDriver/WpdService.cpp
ixjf/Windows-driver-samples
38985ba91feb685095754775e101389ad90c2aa6
[ "MS-PL" ]
3,091
2015-03-19T00:08:54.000Z
2019-05-06T16:42:01.000Z
#include "stdafx.h" #include "WpdService.tmh" WpdService::WpdService() : m_pContactsService(NULL) { } WpdService::~WpdService() { } HRESULT WpdService::Initialize(_In_ FakeDevice* pDevice) { if (pDevice == NULL) { return E_POINTER; } m_pContactsService = pDevice->GetContactsService(); m_ServiceMethods.Initialize(m_pContactsService); m_ServiceCapabilities.Initialize(m_pContactsService); return S_OK; } HRESULT WpdService::DispatchWpdMessage( _In_ REFPROPERTYKEY Command, _In_ IPortableDeviceValues* pParams, _In_ IPortableDeviceValues* pResults) { HRESULT hr = S_OK; LPWSTR pszRequestFilename = NULL; // Get the request filename to process the service message hr = pParams->GetStringValue(PRIVATE_SAMPLE_DRIVER_REQUEST_FILENAME, &pszRequestFilename); if (FAILED(hr)) { hr = E_INVALIDARG; CHECK_HR(hr, "Failed to get the required requested filename"); } if (hr == S_OK) { hr = CheckRequestFilename(pszRequestFilename); CHECK_HR(hr, "Unknown request filename %ws received", pszRequestFilename); } if (hr == S_OK) { if (Command.fmtid == WPD_CATEGORY_SERVICE_CAPABILITIES) { hr = m_ServiceCapabilities.DispatchWpdMessage(Command, pParams, pResults); } else if (IsEqualPropertyKey(Command, WPD_COMMAND_SERVICE_METHODS_START_INVOKE)) { hr = m_ServiceMethods.OnStartInvoke(pParams, pResults); } else if (IsEqualPropertyKey(Command, WPD_COMMAND_SERVICE_METHODS_END_INVOKE)) { hr = m_ServiceMethods.OnEndInvoke(pParams, pResults); } else if (IsEqualPropertyKey(Command, WPD_COMMAND_SERVICE_METHODS_CANCEL_INVOKE)) { hr = m_ServiceMethods.OnCancelInvoke(pParams, pResults); } else if (IsEqualPropertyKey(Command, WPD_COMMAND_SERVICE_COMMON_GET_SERVICE_OBJECT_ID)) { hr = OnGetServiceObjectID(pszRequestFilename, pParams, pResults); } else { hr = E_NOTIMPL; CHECK_HR(hr, "Unknown command %ws.%d received",CComBSTR(Command.fmtid), Command.pid); } } CoTaskMemFree(pszRequestFilename); return hr; } /** * This method is called when we receive a WPD_COMMAND_SERVICE_COMMON_GET_SERVICE_OBJECT_ID * command. * * The parameters sent to us are: * None * * The driver should: * - Return the objectID associated with the filename. * */ HRESULT WpdService::OnGetServiceObjectID( _In_ LPCWSTR pszRequestFilename, _In_ IPortableDeviceValues* pParams, _In_ IPortableDeviceValues* pResults) { HRESULT hr = S_OK; if((pParams == NULL) || (pResults == NULL)) { hr = E_POINTER; CHECK_HR(hr, "Cannot have NULL parameter"); return hr; } // For simplicity, the request filename is the same as the service object ID hr = pResults->SetStringValue(WPD_PROPERTY_SERVICE_OBJECT_ID, pszRequestFilename); CHECK_HR(hr, "Failed to set WPD_PROPERTY_COMMON_OBJECT_IDS"); return hr; } HRESULT WpdService::CheckRequestFilename( _In_ LPCWSTR pszRequestFilename) { HRESULT hr = HRESULT_FROM_WIN32(ERROR_NOT_FOUND); CAtlStringW strRequestFilename = pszRequestFilename; // For simplicity, the request filename happens to be the same as the service object ID if (strRequestFilename.CompareNoCase(m_pContactsService->GetRequestFilename()) == 0) { hr = S_OK; } else { CHECK_HR(hr, "Unknown request filename %ws received", pszRequestFilename); } return hr; }
29.24812
99
0.63419
[ "object" ]
4a31e872791bd49bf48a27e40f989fb3cf51028d
3,827
cpp
C++
auto_completion.cpp
xmil9/ccon
c8dd9fe2d0d9c89bb6cbb53a1cb745234ea3c47a
[ "MIT" ]
null
null
null
auto_completion.cpp
xmil9/ccon
c8dd9fe2d0d9c89bb6cbb53a1cb745234ea3c47a
[ "MIT" ]
null
null
null
auto_completion.cpp
xmil9/ccon
c8dd9fe2d0d9c89bb6cbb53a1cb745234ea3c47a
[ "MIT" ]
null
null
null
// // ccon // // Jun-2019, Michael Lindner // MIT license // #include "auto_completion.h" #include "cmd_spec.h" #include "console_util.h" #include "essentutils/string_util.h" #include <set> namespace { /////////////////// std::vector<std::string> autoCompleteCmdName(const std::string& input, const std::set<ccon::CmdSpec>& cmds) { std::vector<std::string> candidates; for (const ccon::CmdSpec& spec : cmds) if (sutil::startsWith(spec.name(), input)) candidates.push_back(spec.name()); return candidates; } std::vector<std::string> autoCompleteCmdArg(const std::string& cmdName, const std::string& inputArg, const std::set<ccon::CmdSpec>& cmds) { const std::string inputLabel = ccon::stripArgSeparators(inputArg); const std::string strippedSeps = inputArg.substr(0, inputArg.size() - inputLabel.size()); std::vector<std::string> candidates; for (const ccon::CmdSpec& cmdSpec : cmds) { if (cmdSpec.matchesName(cmdName)) { for (const ccon::ArgSpec& argSpec : cmdSpec) { if (argSpec.hasLabel() && sutil::startsWith(argSpec.label(), inputLabel)) candidates.push_back(strippedSeps + argSpec.label()); } break; } } return candidates; } std::vector<std::string> autoComplete(const std::string& input, const std::set<ccon::CmdSpec>& cmds) { std::vector<std::string> cmdPieces = sutil::split(input, " "); if (cmdPieces.empty()) return {}; if (cmdPieces.size() == 1) { return autoCompleteCmdName(sutil::lowercase(cmdPieces[0]), cmds); } else { const std::vector<std::string> argCompletions = autoCompleteCmdArg( sutil::lowercase(cmdPieces[0]), sutil::lowercase(*cmdPieces.rbegin()), cmds); const std::string inputFront = sutil::join(cmdPieces.begin(), (cmdPieces.rbegin() + 1).base(), " ") + ' '; std::vector<std::string> inputCompletions; for (const std::string& completedArg : argCompletions) inputCompletions.push_back(inputFront + completedArg); return inputCompletions; } } } // namespace namespace ccon { /////////////////// void AutoCompletion::setCmds(const std::set<CmdSpec>& cmds) { m_cmds = cmds; } std::string AutoCompletion::next(const std::string& pattern) { completeIfNecessary(pattern); return next(); } std::vector<std::string> AutoCompletion::all(const std::string& pattern) { completeIfNecessary(pattern); return m_completions; } void AutoCompletion::reset() { m_completedPattern = {}; m_completions.clear(); m_next = m_completions.end(); } void AutoCompletion::complete(const std::string& pattern) { m_completedPattern = pattern; m_completions = autoComplete(pattern, m_cmds); m_next = m_completions.begin(); } void AutoCompletion::completeIfNecessary(const std::string& pattern) { // Check if the completions got reset and we need to calculate new // ones. Note that the passed pattern might be different from // the completed pattern but we still don't want to re-calculate // the completions because the pattern can be a previously returned // completion itself that gets passed back as new pattern into this // function! That's the reason why we need an explicit reset call // with which client code can control when a pattern reset should // happen. if (m_completedPattern.empty() && !pattern.empty()) complete(pattern); } std::string AutoCompletion::next() { if (m_next == m_completions.end()) m_next = m_completions.begin(); return (m_next != m_completions.end()) ? *m_next++ : ""; } } // namespace ccon
25.513333
86
0.634962
[ "vector" ]
4a33f1630e93ad0a24e00f8b782410bff8a8ea71
23,579
cpp
C++
Submodules/Peano/src/peano/grid/tests/UnrolledAscendDescendLevelEnumeratorTest.cpp
linusseelinger/ExaHyPE-Tsunami
92a6e14926862e1584ef1e935874c91d252e8112
[ "BSD-3-Clause" ]
2
2019-08-14T22:41:26.000Z
2020-02-04T19:30:24.000Z
Submodules/Peano/src/peano/grid/tests/UnrolledAscendDescendLevelEnumeratorTest.cpp
linusseelinger/ExaHyPE-Tsunami
92a6e14926862e1584ef1e935874c91d252e8112
[ "BSD-3-Clause" ]
null
null
null
Submodules/Peano/src/peano/grid/tests/UnrolledAscendDescendLevelEnumeratorTest.cpp
linusseelinger/ExaHyPE-Tsunami
92a6e14926862e1584ef1e935874c91d252e8112
[ "BSD-3-Clause" ]
3
2019-07-22T10:27:36.000Z
2020-05-11T12:25:29.000Z
#include "peano/grid/tests/UnrolledAscendDescendLevelEnumeratorTest.h" #include "peano/utils/Globals.h" #include "peano/grid/UnrolledLevelEnumerator.h" #include "peano/grid/UnrolledAscendDescendLevelEnumerator.h" #include "tarch/tests/TestCaseFactory.h" registerTest(peano::grid::tests::UnrolledAscendDescendLevelEnumeratorTest) #ifdef UseTestSpecificCompilerSettings #pragma optimize("",off) #endif tarch::logging::Log peano::grid::tests::UnrolledAscendDescendLevelEnumeratorTest::_log( "peano::grid::tests::UnrolledAscendDescendLevelEnumeratorTest" ); peano::grid::tests::UnrolledAscendDescendLevelEnumeratorTest::UnrolledAscendDescendLevelEnumeratorTest(): tarch::tests::TestCase( "peano::grid::tests::UnrolledAscendDescendLevelEnumeratorTest" ) { } peano::grid::tests::UnrolledAscendDescendLevelEnumeratorTest::~UnrolledAscendDescendLevelEnumeratorTest() { } void peano::grid::tests::UnrolledAscendDescendLevelEnumeratorTest::run() { logTraceIn( "run() "); testMethod( testLevel1 ); testMethod( testLevel2 ); logTraceOut( "run() "); } void peano::grid::tests::UnrolledAscendDescendLevelEnumeratorTest::setUp() { } void peano::grid::tests::UnrolledAscendDescendLevelEnumeratorTest::testLevel1() { #ifdef Dim2 peano::grid::UnrolledLevelEnumerator::Vector coarsestGridCellSize; peano::grid::UnrolledLevelEnumerator::Vector domainOffset; tarch::la::assignList( coarsestGridCellSize ) = 1.0/9.0, 1.0/9.0; tarch::la::assignList( domainOffset ) = 4.0/9.0, 6.0/9.0; peano::grid::UnrolledLevelEnumerator coarseEnumerator( coarsestGridCellSize, domainOffset, 3, 1, 0 ); peano::grid::UnrolledLevelEnumerator fineEnumerator( coarsestGridCellSize, domainOffset, 3, 1, 1 ); peano::grid::UnrolledAscendDescendLevelEnumerator fineUnrolledEnumerator(fineEnumerator); peano::grid::UnrolledLevelEnumerator::Vector v; peano::grid::UnrolledLevelEnumerator::LocalVertexIntegerIndex p; validateEqualsWithParams3( coarseEnumerator.getLevel(), 3, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateEqualsWithParams3( fineEnumerator.getLevel(), 4, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateEqualsWithParams3( fineUnrolledEnumerator.getLevel(), 4, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateEqualsWithParams3( coarseEnumerator(0), 0, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateEqualsWithParams3( fineEnumerator(0), 0, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateEqualsWithParams3( fineUnrolledEnumerator(0), 0, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 0,0; tarch::la::assignList( v ) = 4.0/9.0, 6.0/9.0; validateEqualsWithParams3( coarseEnumerator(p), 0, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateEqualsWithParams3( fineEnumerator(p), 0, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateEqualsWithParams3( fineUnrolledEnumerator(p), 0, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateNumericalVectorEquals( coarseEnumerator.getVertexPosition(p), v ); validateNumericalVectorEquals( fineEnumerator.getVertexPosition(p), v ); validateNumericalVectorEquals( fineUnrolledEnumerator.getVertexPosition(p), v ); tarch::la::assignList( p ) = 1,0; validateEqualsWithParams3( coarseEnumerator(p), 1, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateEqualsWithParams3( fineEnumerator(p), 1, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateEqualsWithParams3( fineUnrolledEnumerator(p), 1, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( v ) = (4.0+1.0)/9.0, 6.0/9.0; validateNumericalVectorEquals( coarseEnumerator.getVertexPosition(p), v ); tarch::la::assignList( v ) = (4.0*3.0+1.0)/(9.0*3.0), (6.0*3.0+0.0)/(9.0*3.0); validateNumericalVectorEqualsWithParams3( fineEnumerator.getVertexPosition(p), v, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateNumericalVectorEqualsWithParams3( fineUnrolledEnumerator.getVertexPosition(p), v, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 2,0; validateEqualsWithParams3( fineUnrolledEnumerator(p), 2, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( v ) = (4.0*3.0+2.0)/(9.0*3.0), (6.0*3.0+0.0)/(9.0*3.0); validateNumericalVectorEqualsWithParams3( fineUnrolledEnumerator.getVertexPosition(p), v, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 3,0; validateEqualsWithParams3( fineUnrolledEnumerator(p), 3, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( v ) = (4.0*3.0+3.0)/(9.0*3.0), (6.0*3.0+0.0)/(9.0*3.0); validateNumericalVectorEqualsWithParams3( fineUnrolledEnumerator.getVertexPosition(p), v, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 0,1; validateEqualsWithParams3( coarseEnumerator(p), 2, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateEqualsWithParams3( fineEnumerator(p), 4, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateEqualsWithParams3( fineUnrolledEnumerator(p), 4, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( v ) = (4.0*3.0+0.0)/(9.0*3.0), (6.0*3.0+1.0)/(9.0*3.0); validateNumericalVectorEqualsWithParams3( fineUnrolledEnumerator.getVertexPosition(p), v, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 1,1; validateEqualsWithParams3( coarseEnumerator(p), 3, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateEqualsWithParams3( fineEnumerator(p), 5, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateEqualsWithParams3( fineUnrolledEnumerator(p), 5, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( v ) = (4.0*3.0+1.0)/(9.0*3.0), (6.0*3.0+1.0)/(9.0*3.0); validateNumericalVectorEqualsWithParams3( fineUnrolledEnumerator.getVertexPosition(p), v, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 2,1; validateEqualsWithParams3( fineUnrolledEnumerator(p), 6, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( v ) = (4.0*3.0+2.0)/(9.0*3.0), (6.0*3.0+1.0)/(9.0*3.0); validateNumericalVectorEqualsWithParams3( fineUnrolledEnumerator.getVertexPosition(p), v, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 3,1; validateEqualsWithParams3( fineUnrolledEnumerator(p), 7, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( v ) = (4.0*3.0+3.0)/(9.0*3.0), (6.0*3.0+1.0)/(9.0*3.0); validateNumericalVectorEqualsWithParams3( fineUnrolledEnumerator.getVertexPosition(p), v, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 0,0; validateEqualsWithParams3( fineUnrolledEnumerator.cell(p), 0, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 1,0; validateEqualsWithParams3( fineUnrolledEnumerator.cell(p), 1, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 2,0; validateEqualsWithParams3( fineUnrolledEnumerator.cell(p), 2, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 0,1; validateEqualsWithParams3( fineUnrolledEnumerator.cell(p), 3, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 1,1; validateEqualsWithParams3( fineUnrolledEnumerator.cell(p), 4, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); #endif } void peano::grid::tests::UnrolledAscendDescendLevelEnumeratorTest::testLevel2() { #ifdef Dim2 peano::grid::UnrolledLevelEnumerator::Vector coarsestGridCellSize; peano::grid::UnrolledLevelEnumerator::Vector domainOffset; tarch::la::assignList( coarsestGridCellSize ) = 1.0/9.0, 1.0/9.0; tarch::la::assignList( domainOffset ) = 4.0/9.0, 6.0/9.0; peano::grid::UnrolledLevelEnumerator coarseEnumerator( coarsestGridCellSize, domainOffset, 3, 2, 1 ); peano::grid::UnrolledLevelEnumerator fineEnumerator( coarsestGridCellSize, domainOffset, 3, 2, 2 ); peano::grid::UnrolledAscendDescendLevelEnumerator fineUnrolledEnumerator(fineEnumerator); peano::grid::UnrolledLevelEnumerator::Vector v; peano::grid::UnrolledLevelEnumerator::LocalVertexIntegerIndex p; validateEqualsWithParams3( coarseEnumerator.getLevel(), 4, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateEqualsWithParams3( fineEnumerator.getLevel(), 5, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateEqualsWithParams3( fineUnrolledEnumerator.getLevel(), 5, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateEqualsWithParams3( coarseEnumerator(0), 0, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateEqualsWithParams3( fineEnumerator(0), 0, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateEqualsWithParams3( fineUnrolledEnumerator(0), 0, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 0,0; tarch::la::assignList( v ) = 4.0/9.0, 6.0/9.0; validateEqualsWithParams3( coarseEnumerator(p), 0, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateEqualsWithParams3( fineEnumerator(p), 0, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateEqualsWithParams3( fineUnrolledEnumerator(p), 0, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateNumericalVectorEquals( coarseEnumerator.getVertexPosition(p), v ); validateNumericalVectorEquals( fineEnumerator.getVertexPosition(p), v ); validateNumericalVectorEquals( fineUnrolledEnumerator.getVertexPosition(p), v ); tarch::la::assignList( p ) = 1,0; validateEqualsWithParams3( coarseEnumerator(p), 1, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateEqualsWithParams3( fineEnumerator(p), 1, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateEqualsWithParams3( fineUnrolledEnumerator(p), 1, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( v ) = 4.0/9.0 + 1.0/27.0, 6.0/9.0; validateNumericalVectorEquals( coarseEnumerator.getVertexPosition(p), v ); tarch::la::assignList( v ) = 4.0/9.0 + 1.0/81.0, 6.0/9.0 + 0.0/81.0; validateNumericalVectorEqualsWithParams3( fineEnumerator.getVertexPosition(p), v, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateNumericalVectorEqualsWithParams3( fineUnrolledEnumerator.getVertexPosition(p), v, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 2,0; validateEqualsWithParams3( fineUnrolledEnumerator(p), 2, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( v ) = 4.0/9.0 + 2.0/81.0, 6.0/9.0 + 0.0/81.0; validateNumericalVectorEqualsWithParams3( fineUnrolledEnumerator.getVertexPosition(p), v, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 3,0; validateEqualsWithParams3( fineUnrolledEnumerator(p), 3, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( v ) = 4.0/9.0 + 3.0/81.0, 6.0/9.0 + 0.0/81.0; validateNumericalVectorEqualsWithParams3( fineUnrolledEnumerator.getVertexPosition(p), v, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 0,1; validateEqualsWithParams3( coarseEnumerator(p), 4, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateEqualsWithParams3( fineEnumerator(p), 10, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateEqualsWithParams3( fineUnrolledEnumerator(p), 10, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( v ) = 4.0/9.0 + 0.0/81.0, 6.0/9.0 + 1.0/81.0; validateNumericalVectorEqualsWithParams3( fineUnrolledEnumerator.getVertexPosition(p), v, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 1,1; validateEqualsWithParams3( coarseEnumerator(p), 5, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateEqualsWithParams3( fineEnumerator(p), 11, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateEqualsWithParams3( fineUnrolledEnumerator(p), 11, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( v ) = 4.0/9.0 + 1.0/81.0, 6.0/9.0 + 1.0/81.0; validateNumericalVectorEqualsWithParams3( fineUnrolledEnumerator.getVertexPosition(p), v, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 2,1; validateEqualsWithParams3( fineUnrolledEnumerator(p), 12, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( v ) = 4.0/9.0 + 2.0/81.0, 6.0/9.0 + 1.0/81.0; validateNumericalVectorEqualsWithParams3( fineUnrolledEnumerator.getVertexPosition(p), v, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 3,1; validateEqualsWithParams3( fineUnrolledEnumerator(p), 13, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( v ) = 4.0/9.0 + 3.0/81.0, 6.0/9.0 + 1.0/81.0; validateNumericalVectorEqualsWithParams3( fineUnrolledEnumerator.getVertexPosition(p), v, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 0,0; validateEqualsWithParams3( fineUnrolledEnumerator.cell(p), 0, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 1,0; validateEqualsWithParams3( fineUnrolledEnumerator.cell(p), 1, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 2,0; validateEqualsWithParams3( fineUnrolledEnumerator.cell(p), 2, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 0,1; validateEqualsWithParams3( fineUnrolledEnumerator.cell(p), 9, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 1,1; validateEqualsWithParams3( fineUnrolledEnumerator.cell(p), 10, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 1,0; coarseEnumerator.setOffset(p); fineUnrolledEnumerator.setOffset(p*3); validateEqualsWithParams3( coarseEnumerator.getLevel(), 4, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateEqualsWithParams3( fineEnumerator.getLevel(), 5, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateEqualsWithParams3( fineUnrolledEnumerator.getLevel(), 5, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateEqualsWithParams3( coarseEnumerator(0), 1, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateEqualsWithParams3( fineUnrolledEnumerator(0), 3, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 0,0; validateEqualsWithParams3( coarseEnumerator(p), 1, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateEqualsWithParams3( fineUnrolledEnumerator(p), 3, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( v ) = 4.0/9.0 + 1.0/27.0, 6.0/9.0; validateNumericalVectorEquals( coarseEnumerator.getVertexPosition(p), v ); validateNumericalVectorEquals( fineUnrolledEnumerator.getVertexPosition(p), v ); tarch::la::assignList( p ) = 1,0; validateEqualsWithParams3( coarseEnumerator(p), 2, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateEqualsWithParams3( fineUnrolledEnumerator(p), 4, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( v ) = 4.0/9.0 + 2.0/27.0, 6.0/9.0; validateNumericalVectorEquals( coarseEnumerator.getVertexPosition(p), v ); tarch::la::assignList( v ) = 4.0/9.0 + 1.0/27.0 + 1.0/81.0, 6.0/9.0 + 0.0/81.0; validateNumericalVectorEqualsWithParams3( fineUnrolledEnumerator.getVertexPosition(p), v, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 2,0; validateEqualsWithParams3( fineUnrolledEnumerator(p), 5, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( v ) = 4.0/9.0 + 1.0/27.0 + 2.0/81.0, 6.0/9.0 + 0.0/81.0; validateNumericalVectorEqualsWithParams3( fineUnrolledEnumerator.getVertexPosition(p), v, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 3,0; validateEqualsWithParams3( fineUnrolledEnumerator(p), 6, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( v ) = 4.0/9.0 + 1.0/27.0 + 3.0/81.0, 6.0/9.0 + 0.0/81.0; validateNumericalVectorEqualsWithParams3( fineUnrolledEnumerator.getVertexPosition(p), v, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 0,1; validateEqualsWithParams3( coarseEnumerator(p), 5, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateEqualsWithParams3( fineUnrolledEnumerator(p), 13, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( v ) = 4.0/9.0 + 1.0/27.0 + 0.0/81.0, 6.0/9.0 + 0.0/27.0 + 1.0/81.0; validateNumericalVectorEqualsWithParams3( fineUnrolledEnumerator.getVertexPosition(p), v, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 1,1; validateEqualsWithParams3( coarseEnumerator(p), 6, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); validateEqualsWithParams3( fineUnrolledEnumerator(p), 14, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( v ) = 4.0/9.0 + 1.0/27.0 + 1.0/81.0, 6.0/9.0 + 0.0/27.0 + 1.0/81.0; validateNumericalVectorEqualsWithParams3( fineUnrolledEnumerator.getVertexPosition(p), v, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 2,1; validateEqualsWithParams3( fineUnrolledEnumerator(p), 15, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( v ) = 4.0/9.0 + 1.0/27.0 + 2.0/81.0, 6.0/9.0 + 0.0/27.0 + 1.0/81.0; validateNumericalVectorEqualsWithParams3( fineUnrolledEnumerator.getVertexPosition(p), v, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 3,1; validateEqualsWithParams3( fineUnrolledEnumerator(p), 16, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( v ) = 4.0/9.0 + 1.0/27.0 + 3.0/81.0, 6.0/9.0 + 0.0/27.0 + 1.0/81.0; validateNumericalVectorEqualsWithParams3( fineUnrolledEnumerator.getVertexPosition(p), v, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 0,0; validateEqualsWithParams3( fineUnrolledEnumerator.cell(p), 3, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 1,0; validateEqualsWithParams3( fineUnrolledEnumerator.cell(p), 4, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 2,0; validateEqualsWithParams3( fineUnrolledEnumerator.cell(p), 5, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 0,1; validateEqualsWithParams3( fineUnrolledEnumerator.cell(p), 12, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); tarch::la::assignList( p ) = 1,1; validateEqualsWithParams3( fineUnrolledEnumerator.cell(p), 13, coarseEnumerator.toString(), fineEnumerator.toString(), fineUnrolledEnumerator.toString() ); #endif } #ifdef UseTestSpecificCompilerSettings #pragma optimize("",on) #endif
69.35
184
0.754485
[ "vector" ]
4a358c8ff1f4dd5614dcdd55aabbc7441258116b
9,675
cc
C++
MagneticField/ParametrizedEngine/src/poly2d_base.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
MagneticField/ParametrizedEngine/src/poly2d_base.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
MagneticField/ParametrizedEngine/src/poly2d_base.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
#include "poly2d_base.h" using namespace magfieldparam; ///////////////////////////////////////////////////////////////////////////////// // // // The "poly2d_term" represent a term of a polynomial of 2 variables. // // // ///////////////////////////////////////////////////////////////////////////////// //_______________________________________________________________________________ void poly2d_term::Print(std::ostream &out, bool first_term) { if (first_term) out << coeff; else if (coeff > 0.) out << " + " << coeff; else out << " - " << -coeff; if (np[0] != 0) { out << "*r"; if (np[0] != 1) out << "^" << np[0]; } if (np[1] != 0) { out << "*z"; if (np[1] != 1) out << "^" << np[1]; } } ///////////////////////////////////////////////////////////////////////////////// // // // Base class that represent a polynomial of 2 variables. It isn't supposed // // to be used directly and provides no way of setting coefficients directly. // // Such methods must be defined in derived classes. // // // ///////////////////////////////////////////////////////////////////////////////// //_______________________________________________________________________________ double poly2d_base::rval = 0.; //Last values of r and z used double poly2d_base::zval = 0.; double **poly2d_base::rz_pow = 0; //table with calculated r^n*z^m values unsigned poly2d_base::NTab = 0; //rz_pow table size unsigned poly2d_base::NPwr = 0; //max power in use by CLASS bool poly2d_base::rz_set = false; const double poly2d_base::MIN_COEFF = DBL_EPSILON; //Thresh. for coeff == 0 std::set<poly2d_base*> poly2d_base::poly2d_base_set; //_______________________________________________________________________________ poly2d_base::~poly2d_base() { poly2d_base_set.erase(poly2d_base_set.find(this)); if(poly2d_base_set.size()) { //some objects left if (max_pwr >= NPwr) NPwr = GetMaxPow(); } else { if (rz_pow) { delete [] rz_pow[0]; //deleting the last instance -> memory cleanup delete [] rz_pow; } rz_pow = 0; rval = zval = 0.; NPwr = 0; NTab = 0; rz_set = false; // poly2d_base_set.resize(0); } } //_______________________________________________________________________________ void poly2d_base::SetTabSize(const unsigned N) { if (N <= NTab) return; if (rz_pow) { delete [] rz_pow[0]; delete [] rz_pow; } rz_pow = new double* [N]; unsigned jr, dN = N*(N+1)/2; rz_pow[0] = new double [dN]; memset(rz_pow[0], 0, dN*sizeof(double)); rz_pow[0][0] = 1.; for (jr = 1, dN = N; jr < N; ++jr, --dN) { rz_pow[jr] = rz_pow[jr-1] + dN; } rval = zval = 0.; NTab = N; } //_______________________________________________________________________________ void poly2d_base::FillTable(const double r, const double z) { if (!rz_pow) return; unsigned jr, jz; for (jz = 1; jz <= NPwr; ++jz) rz_pow[0][jz] = z*rz_pow[0][jz-1]; for (jr = 1; jr <= NPwr; ++jr) { for (jz = 0; jz <= (NPwr - jr); ++jz) { rz_pow[jr][jz] = r*rz_pow[jr-1][jz]; } } } //_______________________________________________________________________________ int poly2d_base::GetMaxPow() { int curp, maxp = 0; std::set<poly2d_base*>::iterator it; for (it = poly2d_base_set.begin(); it != poly2d_base_set.end(); ++it) { curp = (*it)->max_pwr; if (curp > maxp) maxp = curp; } return maxp; } //_______________________________________________________________________________ void poly2d_base::AdjustTab() { NPwr = GetMaxPow(); if (NPwr >= NTab) SetTabSize(NPwr+1); } //_______________________________________________________________________________ void poly2d_base::PrintTab(std::ostream &out, const std::streamsize prec) { out << "poly2d_base table size NTab = " << NTab << "\tmax. power NPwr = " << NPwr << std::endl; if (rz_pow) { if (NPwr < NTab) { std::streamsize old_prec = out.precision(), wdt = prec+7; out.precision(prec); out << "Table content:" << std::endl; unsigned jr, jz; for (jr = 0; jr <= NPwr; ++jr) { for (jz = 0; jz <= (NPwr-jr); ++jz) { out << std::setw(wdt) << std::left << rz_pow[jr][jz]; } out << "|" << std::endl; } out.precision(old_prec); } else { out << "\tTable size is not adjusted." << std::endl; } } else { out << "\tTable is not allocated." << std::endl; } } //_______________________________________________________________________________ void poly2d_base::SetPoint(const double r, const double z) { if (!Count()) return; if (NPwr >= NTab) { SetTabSize(NPwr+1); FillTable(r, z);} else if ((r != rval) || (z != zval)) FillTable(r, z); rz_set = true; } //_______________________________________________________________________________ double poly2d_base::Eval() { double S = 0.; for (unsigned j = 0; j < data.size(); ++j) S += data[j].coeff*rz_pow[data[j].np[0]][data[j].np[1]]; return S; } //_______________________________________________________________________________ void poly2d_base::Collect() { if (!(data.size())) return; unsigned j1, j2, rpow, zpow, noff = 0, jend = data.size(); double C; std::vector<bool> mask(jend, false); max_pwr = 0; for (j1 = 0; j1 < jend; ++j1) { if (mask[j1]) continue; C = data[j1].coeff; rpow = data[j1].np[0]; zpow = data[j1].np[1]; for (j2 = j1+1; j2 < jend; ++j2) { if (mask[j2]) continue; if ((rpow == data[j2].np[0]) && (zpow == data[j2].np[1])) { C += data[j2].coeff; mask[j2] = true; ++noff; } } if (fabs(C) > MIN_COEFF) { data[j1].coeff = C; if ((rpow = rpow+zpow) > max_pwr) max_pwr = rpow; } else { mask[j1] = true; ++noff; } } std::vector<poly2d_term> newdata; newdata.reserve(jend - noff); for (j1 = 0; j1 < jend; ++j1) { if (!(mask[j1])) newdata.push_back(data[j1]); } data.swap(newdata); } //_______________________________________________________________________________ void poly2d_base::Print(std::ostream &out, const std::streamsize prec) { if (!data.size()) { out << "\"poly2d_base\" object contains no terms." << std::endl; return; } out << data.size() << " terms; max. degree = " << max_pwr << ":" << std::endl; std::streamsize old_prec = out.precision(); out.precision(prec); data[0].Print(out); for (unsigned it = 1; it < data.size(); ++it) { data[it].Print(out, false); } out << std::endl; out.precision(old_prec); } //_______________________________________________________________________________ void poly2d_base::Diff(int nvar) { //differentiate the polynomial by variable nvar. // poly2d_term v3; std::vector<poly2d_term> newdata; newdata.reserve(data.size()); unsigned cur_pwr = 0, maxp = 0, oldp = max_pwr; for (unsigned it = 0; it < data.size(); ++it) { v3 = data[it]; v3.coeff *= v3.np[nvar]; if (v3.coeff != 0.) { --v3.np[nvar]; newdata.push_back(v3); if ((cur_pwr = v3.np[0] + v3.np[1]) > maxp) maxp = cur_pwr; } } newdata.resize(newdata.size()); max_pwr = maxp; data.swap(newdata); if (oldp >= NPwr) NPwr = GetMaxPow(); } //_______________________________________________________________________________ void poly2d_base::Int(int nvar) { //Integrate the polynomial by variable# nvar. Doesn't remove terms //with zero coefficients; if you suspect they can appear, use Compress() //after the integration. // for (unsigned it = 0; it < data.size(); ++it) { data[it].coeff /= ++data[it].np[nvar]; } ++max_pwr; if (max_pwr > NPwr) NPwr = GetMaxPow(); } //_______________________________________________________________________________ void poly2d_base::IncPow(int nvar) { //Multiply the polynomial by variable# nvar // for (unsigned it = 0; it < data.size(); ++it) { ++data[it].np[nvar]; } ++max_pwr; if (max_pwr > NPwr) NPwr = GetMaxPow(); } //_______________________________________________________________________________ void poly2d_base::DecPow(int nvar) { //Divide the polynomial by variable# nvar. Remove terms with zero coefficients //and also terms where the initial power of nvar is equal zero // poly2d_term v3; std::vector<poly2d_term> newdata; newdata.reserve(data.size()); unsigned cur_pwr = 0, maxp = 0, oldp = max_pwr; for (unsigned it = 0; it < data.size(); ++it) { v3 = data[it]; if ((v3.coeff != 0.) && (v3.np[nvar] > 0)) { --v3.np[nvar]; newdata.push_back(v3); if ((cur_pwr = v3.np[0] + v3.np[1]) > maxp) maxp = cur_pwr; } } newdata.resize(newdata.size()); max_pwr = maxp; data.swap(newdata); if (oldp >= NPwr) NPwr = GetMaxPow(); } //_______________________________________________________________________________ void poly2d_base::Scale(const double C) { //Multiply the polynomial by a constant. // if (C != 0.) { for (unsigned it = 0; it < data.size(); ++it) { data[it].coeff *= C; } } else data.resize(0); }
31.514658
81
0.57261
[ "object", "vector" ]
4a3ab4a17cd312240d0e5ee443ce4c385398a30c
45,555
cpp
C++
app/WebView2APISample/AppWindow.cpp
h2floh/WebChatBotInteractingWithApp
def63a3a323c55eed318e1b95855c59a2c8483ca
[ "MIT" ]
null
null
null
app/WebView2APISample/AppWindow.cpp
h2floh/WebChatBotInteractingWithApp
def63a3a323c55eed318e1b95855c59a2c8483ca
[ "MIT" ]
null
null
null
app/WebView2APISample/AppWindow.cpp
h2floh/WebChatBotInteractingWithApp
def63a3a323c55eed318e1b95855c59a2c8483ca
[ "MIT" ]
null
null
null
// Copyright (C) Microsoft Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "stdafx.h" #include "AppWindow.h" #include <DispatcherQueue.h> #include <functional> #include <regex> #include <string> #include <vector> #include <ShObjIdl_core.h> #include <Shellapi.h> #include <ShlObj_core.h> #include <winrt/windows.system.h> #include "App.h" #include "AppStartPage.h" #include "CheckFailure.h" #include "ControlComponent.h" #include "DpiUtil.h" #include "FileComponent.h" #include "ProcessComponent.h" #include "Resource.h" #include "ScenarioAddHostObject.h" #include "ScenarioAuthentication.h" #include "ScenarioCookieManagement.h" #include "ScenarioDOMContentLoaded.h" #include "ScenarioNavigateWithWebResourceRequest.h" #include "ScenarioWebMessage.h" #include "ScenarioWebViewEventMonitor.h" #include "ScriptComponent.h" #include "SettingsComponent.h" #include "TextInputDialog.h" #include "ViewComponent.h" using namespace Microsoft::WRL; static constexpr size_t s_maxLoadString = 100; static constexpr UINT s_runAsyncWindowMessage = WM_APP; static thread_local size_t s_appInstances = 0; // The minimum height and width for Window Features. // See https://developer.mozilla.org/docs/Web/API/Window/open#Size static constexpr int s_minNewWindowSize = 100; // Run Download and Install in another thread so we don't block the UI thread DWORD WINAPI DownloadAndInstallWV2RT(_In_ LPVOID lpParameter) { AppWindow* appWindow = (AppWindow*) lpParameter; int returnCode = 2; // Download failed // Use fwlink to download WebView2 Bootstrapper at runtime and invoke installation // Broken/Invalid Https Certificate will fail to download // Use of the download link below is governed by the below terms. You may acquire the link for your use at https://developer.microsoft.com/microsoft-edge/webview2/. // Microsoft owns all legal right, title, and interest in and to the // WebView2 Runtime Bootstrapper ("Software") and related documentation, // including any intellectual property in the Software. You must acquire all // code, including any code obtained from a Microsoft URL, under a separate // license directly from Microsoft, including a Microsoft download site // (e.g., https://developer.microsoft.com/microsoft-edge/webview2/). HRESULT hr = URLDownloadToFile(NULL, L"https://go.microsoft.com/fwlink/p/?LinkId=2124703", L".\\MicrosoftEdgeWebview2Setup.exe", 0, 0); if (hr == S_OK) { // Either Package the WebView2 Bootstrapper with your app or download it using fwlink // Then invoke install at Runtime. SHELLEXECUTEINFO shExInfo = {0}; shExInfo.cbSize = sizeof(shExInfo); shExInfo.fMask = SEE_MASK_NOASYNC; shExInfo.hwnd = 0; shExInfo.lpVerb = L"runas"; shExInfo.lpFile = L"MicrosoftEdgeWebview2Setup.exe"; shExInfo.lpParameters = L" /silent /install"; shExInfo.lpDirectory = 0; shExInfo.nShow = 0; shExInfo.hInstApp = 0; if (ShellExecuteEx(&shExInfo)) { returnCode = 0; // Install successfull } else { returnCode = 1; // Install failed } } appWindow->InstallComplete(returnCode); appWindow->Release(); return returnCode; } // Creates a new window which is a copy of the entire app, but on the same thread. AppWindow::AppWindow( UINT creationModeId, std::wstring initialUri, bool isMainWindow, std::function<void()> webviewCreatedCallback, bool customWindowRect, RECT windowRect, bool shouldHaveToolbar) : m_creationModeId(creationModeId), m_initialUri(initialUri), m_onWebViewFirstInitialized(webviewCreatedCallback) { // Initialize COM as STA. CHECK_FAILURE(OleInitialize(NULL)); ++s_appInstances; WCHAR szTitle[s_maxLoadString]; // The title bar text LoadStringW(g_hInstance, IDS_APP_TITLE, szTitle, s_maxLoadString); if (customWindowRect) { m_mainWindow = CreateWindowExW( WS_EX_CONTROLPARENT, GetWindowClass(), szTitle, WS_OVERLAPPEDWINDOW, windowRect.left, windowRect.top, windowRect.right-windowRect.left, windowRect.bottom-windowRect.top, nullptr, nullptr, g_hInstance, nullptr); } else { m_mainWindow = CreateWindowExW( WS_EX_CONTROLPARENT, GetWindowClass(), szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, g_hInstance, nullptr); } m_appBackgroundImageHandle = (HBITMAP)LoadImage( NULL, L"AppBackground.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE); GetObject(m_appBackgroundImageHandle, sizeof(m_appBackgroundImage), &m_appBackgroundImage); m_memHdc = CreateCompatibleDC(GetDC(m_mainWindow)); SelectObject(m_memHdc, m_appBackgroundImageHandle); SetWindowLongPtr(m_mainWindow, GWLP_USERDATA, (LONG_PTR)this); #ifdef USE_WEBVIEW2_WIN10 //! [TextScaleChanged1] if (winrt::try_get_activation_factory<winrt::Windows::UI::ViewManagement::UISettings>()) { m_uiSettings = winrt::Windows::UI::ViewManagement::UISettings(); m_uiSettings.TextScaleFactorChanged({ this, &AppWindow::OnTextScaleChanged }); } //! [TextScaleChanged1] #endif if (shouldHaveToolbar) { m_toolbar.Initialize(this); } UpdateCreationModeMenu(); ShowWindow(m_mainWindow, g_nCmdShow); UpdateWindow(m_mainWindow); // If no WebVieRuntime installed, create new thread to do install/download. // Otherwise just initialize webview. wil::unique_cotaskmem_string version_info; HRESULT hr = GetAvailableCoreWebView2BrowserVersionString(nullptr, &version_info); if (hr == S_OK && version_info != nullptr) { RunAsync([this] { InitializeWebView(); }); } else { if (isMainWindow) { AddRef(); CreateThread(0, 0, DownloadAndInstallWV2RT, (void*) this, 0, 0); } else { MessageBox(m_mainWindow, L"WebView Runtime not installed", L"WebView Runtime Installation status", MB_OK); } } } // Register the Win32 window class for the app window. PCWSTR AppWindow::GetWindowClass() { // Only do this once static PCWSTR windowClass = [] { static WCHAR windowClass[s_maxLoadString]; LoadStringW(g_hInstance, IDC_WEBVIEW2APISAMPLE, windowClass, s_maxLoadString); WNDCLASSEXW wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProcStatic; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = g_hInstance; wcex.hIcon = LoadIcon(g_hInstance, MAKEINTRESOURCE(IDI_WEBVIEW2APISAMPLE)); wcex.hCursor = LoadCursor(nullptr, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_WEBVIEW2APISAMPLE); wcex.lpszClassName = windowClass; wcex.hIconSm = LoadIcon(g_hInstance, MAKEINTRESOURCE(IDI_SMALL)); RegisterClassExW(&wcex); return windowClass; }(); return windowClass; } LRESULT CALLBACK AppWindow::WndProcStatic(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { if (auto app = (AppWindow*)GetWindowLongPtr(hWnd, GWLP_USERDATA)) { LRESULT result = 0; if (app->HandleWindowMessage(hWnd, message, wParam, lParam, &result)) { return result; } } return DefWindowProc(hWnd, message, wParam, lParam); } // Handle Win32 window messages sent to the main window bool AppWindow::HandleWindowMessage( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam, LRESULT* result) { // Give all components a chance to handle the message first. for (auto& component : m_components) { if (component->HandleWindowMessage(hWnd, message, wParam, lParam, result)) { return true; } } switch (message) { case WM_SIZE: { // Don't resize the app or webview when the app is minimized // let WM_SYSCOMMAND to handle it if (lParam != 0) { ResizeEverything(); return true; } } break; //! [DPIChanged] case WM_DPICHANGED: { m_toolbar.UpdateDpiAndTextScale(); if (auto view = GetComponent<ViewComponent>()) { view->UpdateDpiAndTextScale(); } RECT* const newWindowSize = reinterpret_cast<RECT*>(lParam); SetWindowPos(hWnd, nullptr, newWindowSize->left, newWindowSize->top, newWindowSize->right - newWindowSize->left, newWindowSize->bottom - newWindowSize->top, SWP_NOZORDER | SWP_NOACTIVATE); return true; } break; //! [DPIChanged] case WM_PAINT: { PAINTSTRUCT ps; HDC hdc; RECT mainWindowBounds; RECT webViewBounds = {0}; BeginPaint(hWnd, &ps); hdc = GetDC(hWnd); GetClientRect(hWnd, &mainWindowBounds); if (auto viewComponent = GetComponent<ViewComponent>()) { webViewBounds = viewComponent->GetBounds(); } StretchBlt(hdc, webViewBounds.left, webViewBounds.top, webViewBounds.right, webViewBounds.bottom, m_memHdc, 0, 0, m_appBackgroundImage.bmWidth, m_appBackgroundImage.bmHeight, SRCCOPY); EndPaint(hWnd, &ps); return true; } break; case s_runAsyncWindowMessage: { auto* task = reinterpret_cast<std::function<void()>*>(wParam); (*task)(); delete task; return true; } break; case WM_NCDESTROY: { int retValue = 0; SetWindowLongPtr(hWnd, GWLP_USERDATA, NULL); NotifyClosed(); if (--s_appInstances == 0) { PostQuitMessage(retValue); } DeleteObject(m_appBackgroundImageHandle); DeleteDC(m_memHdc); } break; //! [RestartManager] case WM_QUERYENDSESSION: { // yes, we can shut down // Register how we might be restarted RegisterApplicationRestart(L"--restore", RESTART_NO_CRASH | RESTART_NO_HANG); *result = TRUE; return true; } break; case WM_ENDSESSION: { if (wParam == TRUE) { // save app state and exit. PostQuitMessage(0); return true; } } break; //! [RestartManager] case WM_KEYDOWN: { // If bit 30 is set, it means the WM_KEYDOWN message is autorepeated. // We want to ignore it in that case. if (!(lParam & (1 << 30))) { if (auto action = GetAcceleratorKeyFunction((UINT)wParam)) { action(); return true; } } } break; case WM_COMMAND: { return ExecuteWebViewCommands(wParam, lParam) || ExecuteAppCommands(wParam, lParam); } break; } return false; } // Handle commands related to the WebView. // This will do nothing if the WebView is not initialized. bool AppWindow::ExecuteWebViewCommands(WPARAM wParam, LPARAM lParam) { if (!m_webView) return false; switch (LOWORD(wParam)) { case IDM_GET_BROWSER_VERSION_AFTER_CREATION: { //! [GetBrowserVersionString] wil::unique_cotaskmem_string version_info; m_webViewEnvironment->get_BrowserVersionString(&version_info); MessageBox( m_mainWindow, version_info.get(), L"Browser Version Info After WebView Creation", MB_OK); //! [GetBrowserVersionString] return true; } case IDM_CLOSE_WEBVIEW: { CloseWebView(); return true; } case IDM_CLOSE_WEBVIEW_CLEANUP: { CloseWebView(true); return true; } case IDM_SCENARIO_POST_WEB_MESSAGE: { NewComponent<ScenarioWebMessage>(this); return true; } case IDM_SCENARIO_ADD_HOST_OBJECT: { NewComponent<ScenarioAddHostObject>(this); return true; } case IDM_SCENARIO_WEB_VIEW_EVENT_MONITOR: { NewComponent<ScenarioWebViewEventMonitor>(this); return true; } case IDM_SCENARIO_JAVA_SCRIPT: { WCHAR c_scriptPath[] = L"ScenarioJavaScriptDebugIndex.html"; std::wstring m_scriptUri = GetLocalUri(c_scriptPath, false); CHECK_FAILURE(m_webView->Navigate(m_scriptUri.c_str())); return true; } case IDM_SCENARIO_TYPE_SCRIPT: { WCHAR c_scriptPath[] = L"ScenarioTypeScriptDebugIndex.html"; std::wstring m_scriptUri = GetLocalUri(c_scriptPath, false); CHECK_FAILURE(m_webView->Navigate(m_scriptUri.c_str())); return true; } case IDM_SCENARIO_JAVA_SCRIPT_VIRTUAL: { WCHAR c_scriptPath[] = L"ScenarioJavaScriptDebugIndex.html"; std::wstring m_scriptUri = GetLocalUri(c_scriptPath, true); CHECK_FAILURE(m_webView->Navigate(m_scriptUri.c_str())); return true; } case IDM_SCENARIO_TYPE_SCRIPT_VIRTUAL: { WCHAR c_scriptPath[] = L"ScenarioTypeScriptDebugIndex.html"; std::wstring m_scriptUri = GetLocalUri(c_scriptPath, true); CHECK_FAILURE(m_webView->Navigate(m_scriptUri.c_str())); return true; } case IDM_SCENARIO_AUTHENTICATION: { NewComponent<ScenarioAuthentication>(this); return true; } case IDM_SCENARIO_COOKIE_MANAGEMENT: { NewComponent<ScenarioCookieManagement>(this); return true; } case IDM_SCENARIO_DOM_CONTENT_LOADED: { NewComponent<ScenarioDOMContentLoaded>(this); return true; } case IDM_SCENARIO_NAVIGATEWITHWEBRESOURCEREQUEST: { NewComponent<ScenarioNavigateWithWebResourceRequest>(this); return true; } case IDM_SCENARIO_TESTING_FOCUS: { WCHAR testingFocusPath[] = L"ScenarioTestingFocus.html"; std::wstring testingFocusUri = GetLocalUri(testingFocusPath, false); CHECK_FAILURE(m_webView->Navigate(testingFocusUri.c_str())); return true; } } return false; } // Handle commands not related to the WebView, which will work even if the WebView // is not currently initialized. bool AppWindow::ExecuteAppCommands(WPARAM wParam, LPARAM lParam) { switch (LOWORD(wParam)) { case IDM_ABOUT: DialogBox(g_hInstance, MAKEINTRESOURCE(IDD_ABOUTBOX), m_mainWindow, About); return true; case IDM_GET_BROWSER_VERSION_BEFORE_CREATION: { wil::unique_cotaskmem_string version_info; GetAvailableCoreWebView2BrowserVersionString( nullptr, &version_info); MessageBox( m_mainWindow, version_info.get(), L"Browser Version Info Before WebView Creation", MB_OK); return true; } case IDM_EXIT: CloseAppWindow(); return true; case IDM_CREATION_MODE_WINDOWED: case IDM_CREATION_MODE_VISUAL_DCOMP: case IDM_CREATION_MODE_TARGET_DCOMP: #ifdef USE_WEBVIEW2_WIN10 case IDM_CREATION_MODE_VISUAL_WINCOMP: #endif m_creationModeId = LOWORD(wParam); UpdateCreationModeMenu(); return true; case IDM_REINIT: InitializeWebView(); return true; case IDM_TOGGLE_FULLSCREEN_ALLOWED: { m_fullScreenAllowed = !m_fullScreenAllowed; MessageBox( nullptr, (std::wstring(L"Fullscreen is now ") + (m_fullScreenAllowed ? L"allowed" : L"disallowed")) .c_str(), L"", MB_OK); return true; } case IDM_NEW_WINDOW: new AppWindow(m_creationModeId); return true; case IDM_NEW_THREAD: CreateNewThread(m_creationModeId); return true; case IDM_SET_LANGUAGE: ChangeLanguage(); return true; case IDM_TOGGLE_AAD_SSO: ToggleAADSSO(); return true; } return false; } // Prompt the user for a new language string void AppWindow::ChangeLanguage() { TextInputDialog dialog( GetMainWindow(), L"Language", L"Language:", L"Enter a language to use for WebView, or leave blank to restore default.", m_language.empty() ? L"zh-cn" : m_language.c_str()); if (dialog.confirmed) { m_language = (dialog.input); } } // Toggle AAD SSO enabled void AppWindow::ToggleAADSSO() { m_AADSSOEnabled = !m_AADSSOEnabled; MessageBox( nullptr, m_AADSSOEnabled ? L"AAD single sign on will be enabled for new WebView " L"created after all webviews are closed." : L"AAD single sign on will be disabled for new WebView" L" created after all webviews are closed.", L"AAD SSO change", MB_OK); } // Message handler for about dialog. INT_PTR CALLBACK AppWindow::About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_INITDIALOG: return (INT_PTR)TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; } // Decide what to do when an accelerator key is pressed. Instead of immediately performing // the action, we hand it to the caller so they can decide whether to run it right away // or running it asynchronously. Will return nullptr if there is no action for the key. std::function<void()> AppWindow::GetAcceleratorKeyFunction(UINT key) { if (GetKeyState(VK_CONTROL) < 0) { switch (key) { case 'N': return [this] { new AppWindow(m_creationModeId); }; case 'Q': return [this] { CloseAppWindow(); }; case 'S': return [this] { if (auto file = GetComponent<FileComponent>()) { file->SaveScreenshot(); } }; case 'T': return [this] { CreateNewThread(m_creationModeId); }; case 'W': return [this] { CloseWebView(); }; } } return nullptr; } //! [CreateCoreWebView2Controller] // Create or recreate the WebView and its environment. void AppWindow::InitializeWebView() { // To ensure browser switches get applied correctly, we need to close // the existing WebView. This will result in a new browser process // getting created which will apply the browser switches. CloseWebView(); m_dcompDevice = nullptr; #ifdef USE_WEBVIEW2_WIN10 m_wincompCompositor = nullptr; #endif LPCWSTR subFolder = nullptr; if (m_creationModeId == IDM_CREATION_MODE_VISUAL_DCOMP || m_creationModeId == IDM_CREATION_MODE_TARGET_DCOMP) { HRESULT hr = DCompositionCreateDevice2(nullptr, IID_PPV_ARGS(&m_dcompDevice)); if (!SUCCEEDED(hr)) { MessageBox( m_mainWindow, L"Attempting to create WebView using DComp Visual is not supported.\r\n" "DComp device creation failed.\r\n" "Current OS may not support DComp.", L"Create with Windowless DComp Visual Failed", MB_OK); return; } } #ifdef USE_WEBVIEW2_WIN10 else if (m_creationModeId == IDM_CREATION_MODE_VISUAL_WINCOMP) { HRESULT hr = TryCreateDispatcherQueue(); if (!SUCCEEDED(hr)) { MessageBox( m_mainWindow, L"Attempting to create WebView using WinComp Visual is not supported.\r\n" "WinComp compositor creation failed.\r\n" "Current OS may not support WinComp.", L"Create with Windowless WinComp Visual Failed", MB_OK); return; } m_wincompCompositor = winrtComp::Compositor(); } #endif //! [CreateCoreWebView2EnvironmentWithOptions] auto options = Microsoft::WRL::Make<CoreWebView2EnvironmentOptions>(); CHECK_FAILURE(options->put_AllowSingleSignOnUsingOSPrimaryAccount( m_AADSSOEnabled ? TRUE : FALSE)); if (!m_language.empty()) CHECK_FAILURE(options->put_Language(m_language.c_str())); HRESULT hr = CreateCoreWebView2EnvironmentWithOptions( subFolder, nullptr, options.Get(), Callback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler>( this, &AppWindow::OnCreateEnvironmentCompleted) .Get()); //! [CreateCoreWebView2EnvironmentWithOptions] if (!SUCCEEDED(hr)) { if (hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)) { MessageBox( m_mainWindow, L"Couldn't find Edge installation. " "Do you have a version installed that's compatible with this " "WebView2 SDK version?", nullptr, MB_OK); } else { ShowFailure(hr, L"Failed to create webview environment"); } } } // This is the callback passed to CreateWebViewEnvironmentWithOptions. // Here we simply create the WebView. HRESULT AppWindow::OnCreateEnvironmentCompleted( HRESULT result, ICoreWebView2Environment* environment) { CHECK_FAILURE(result); m_webViewEnvironment = environment; auto webViewEnvironment3 = m_webViewEnvironment.try_query<ICoreWebView2Environment3>(); #ifdef USE_WEBVIEW2_WIN10 if (webViewEnvironment3 && (m_dcompDevice || m_wincompCompositor)) #else if (webViewEnvironment3 && m_dcompDevice) #endif { CHECK_FAILURE(webViewEnvironment3->CreateCoreWebView2CompositionController( m_mainWindow, Callback< ICoreWebView2CreateCoreWebView2CompositionControllerCompletedHandler>( [this]( HRESULT result, ICoreWebView2CompositionController* compositionController) -> HRESULT { auto controller = wil::com_ptr<ICoreWebView2CompositionController>(compositionController) .query<ICoreWebView2Controller>(); return OnCreateCoreWebView2ControllerCompleted(result, controller.get()); }) .Get())); } else { CHECK_FAILURE(m_webViewEnvironment->CreateCoreWebView2Controller( m_mainWindow, Callback<ICoreWebView2CreateCoreWebView2ControllerCompletedHandler>( this, &AppWindow::OnCreateCoreWebView2ControllerCompleted) .Get())); } return S_OK; } //! [CreateCoreWebView2Controller] // This is the callback passed to CreateCoreWebView2Controller. Here we initialize all WebView-related // state and register most of our event handlers with the WebView. HRESULT AppWindow::OnCreateCoreWebView2ControllerCompleted(HRESULT result, ICoreWebView2Controller* controller) { if (result == S_OK) { m_controller = controller; wil::com_ptr<ICoreWebView2> coreWebView2; CHECK_FAILURE(m_controller->get_CoreWebView2(&coreWebView2)); // We should check for failure here because if this app is using a newer // SDK version compared to the install of the Edge browser, the Edge // browser might not have support for the latest version of the // ICoreWebView2_N interface. coreWebView2.query_to(&m_webView); // Create components. These will be deleted when the WebView is closed. NewComponent<FileComponent>(this); NewComponent<ProcessComponent>(this); NewComponent<ScriptComponent>(this); NewComponent<SettingsComponent>( this, m_webViewEnvironment.get(), m_oldSettingsComponent.get()); m_oldSettingsComponent = nullptr; NewComponent<ViewComponent>( this, m_dcompDevice.get(), #ifdef USE_WEBVIEW2_WIN10 m_wincompCompositor, #endif m_creationModeId == IDM_CREATION_MODE_TARGET_DCOMP); NewComponent<ControlComponent>(this, &m_toolbar); m_webView3 = coreWebView2.try_query<ICoreWebView2_3>(); if (m_webView3) { //! [AddVirtualHostNameToFolderMapping] // Setup host resource mapping for local files. m_webView3->SetVirtualHostNameToFolderMapping( L"appassets.example", L"assets", COREWEBVIEW2_HOST_RESOURCE_ACCESS_KIND_DENY_CORS); //! [AddVirtualHostNameToFolderMapping] } // We have a few of our own event handlers to register here as well RegisterEventHandlers(); // Set the initial size of the WebView ResizeEverything(); if (m_onWebViewFirstInitialized) { m_onWebViewFirstInitialized(); m_onWebViewFirstInitialized = nullptr; } if (m_initialUri.empty()) { // StartPage uses initialized values of the WebView and Environment // so we wait to call StartPage::GetUri until after the WebView is // created. m_initialUri = AppStartPage::GetUri(this); } if (m_initialUri != L"none") { CHECK_FAILURE(m_webView->Navigate(m_initialUri.c_str())); } } else { ShowFailure(result, L"Failed to create webview"); } return S_OK; } void AppWindow::ReinitializeWebView() { // Save the settings component from being deleted when the WebView is closed, so we can // copy its properties to the next settings component. m_oldSettingsComponent = MoveComponent<SettingsComponent>(); InitializeWebView(); } void AppWindow::ReinitializeWebViewWithNewBrowser() { // Save the settings component from being deleted when the WebView is closed, so we can // copy its properties to the next settings component. m_oldSettingsComponent = MoveComponent<SettingsComponent>(); // Use the reference to the web view before we close it UINT webviewProcessId = 0; m_webView->get_BrowserProcessId(&webviewProcessId); // We need to close the current webviews and wait for the browser_process to exit // This is so the new webviews don't use the old browser exe CloseWebView(); // Make sure the browser process inside webview is closed ProcessComponent::EnsureProcessIsClosed(webviewProcessId, 2000); InitializeWebView(); } void AppWindow::RestartApp() { // Use the reference to the web view before we close the app window UINT webviewProcessId = 0; m_webView->get_BrowserProcessId(&webviewProcessId); // To restart the app completely, first we close the current App Window CloseAppWindow(); // Make sure the browser process inside webview is closed ProcessComponent::EnsureProcessIsClosed(webviewProcessId, 2000); // Get the command line arguments used to start this app // so we can re-create the process with them LPWSTR args = GetCommandLineW(); STARTUPINFOW startup_info = {0}; startup_info.cb = sizeof(startup_info); PROCESS_INFORMATION temp_process_info = {}; // Start a new process if (!::CreateProcess( nullptr, args, nullptr, // default process attributes nullptr, // default thread attributes FALSE, // do not inherit handles 0, nullptr, // no environment nullptr, // default current directory &startup_info, &temp_process_info)) { // Log some error information if desired } // Terminate this current process ::exit(0); } void AppWindow::RegisterEventHandlers() { //! [ContainsFullScreenElementChanged] // Register a handler for the ContainsFullScreenChanged event. CHECK_FAILURE(m_webView->add_ContainsFullScreenElementChanged( Callback<ICoreWebView2ContainsFullScreenElementChangedEventHandler>( [this](ICoreWebView2* sender, IUnknown* args) -> HRESULT { if (m_fullScreenAllowed) { CHECK_FAILURE( sender->get_ContainsFullScreenElement(&m_containsFullscreenElement)); if (m_containsFullscreenElement) { EnterFullScreen(); } else { ExitFullScreen(); } } return S_OK; }) .Get(), nullptr)); //! [ContainsFullScreenElementChanged] //! [NewWindowRequested] // Register a handler for the NewWindowRequested event. // This handler will defer the event, create a new app window, and then once the // new window is ready, it'll provide that new window's WebView as the response to // the request. CHECK_FAILURE(m_webView->add_NewWindowRequested( Callback<ICoreWebView2NewWindowRequestedEventHandler>( [this](ICoreWebView2* sender, ICoreWebView2NewWindowRequestedEventArgs* args) { wil::com_ptr<ICoreWebView2Deferral> deferral; CHECK_FAILURE(args->GetDeferral(&deferral)); AppWindow* newAppWindow; wil::com_ptr<ICoreWebView2WindowFeatures> windowFeatures; CHECK_FAILURE(args->get_WindowFeatures(&windowFeatures)); RECT windowRect = {0}; UINT32 left = 0; UINT32 top = 0; UINT32 height = 0; UINT32 width = 0; BOOL shouldHaveToolbar = true; BOOL hasPosition = FALSE; BOOL hasSize = FALSE; CHECK_FAILURE(windowFeatures->get_HasPosition(&hasPosition)); CHECK_FAILURE(windowFeatures->get_HasSize(&hasSize)); bool useDefaultWindow = true; if (!!hasPosition && !!hasSize) { CHECK_FAILURE(windowFeatures->get_Left(&left)); CHECK_FAILURE(windowFeatures->get_Top(&top)); CHECK_FAILURE(windowFeatures->get_Height(&height)); CHECK_FAILURE(windowFeatures->get_Width(&width)); useDefaultWindow = false; } CHECK_FAILURE(windowFeatures->get_ShouldDisplayToolbar(&shouldHaveToolbar)); windowRect.left = left; windowRect.right = left + (width < s_minNewWindowSize ? s_minNewWindowSize : width); windowRect.top = top; windowRect.bottom = top + (height < s_minNewWindowSize ? s_minNewWindowSize : height); // passing "none" as uri as its a noinitialnavigation if (!useDefaultWindow) { newAppWindow = new AppWindow(m_creationModeId, L"none", false, nullptr, true, windowRect, !!shouldHaveToolbar); } else { newAppWindow = new AppWindow(m_creationModeId, L"none"); } newAppWindow->m_isPopupWindow = true; newAppWindow->m_onWebViewFirstInitialized = [args, deferral, newAppWindow]() { CHECK_FAILURE(args->put_NewWindow(newAppWindow->m_webView.get())); CHECK_FAILURE(args->put_Handled(TRUE)); CHECK_FAILURE(deferral->Complete()); }; return S_OK; }) .Get(), nullptr)); //! [NewWindowRequested] //! [WindowCloseRequested] // Register a handler for the WindowCloseRequested event. // This handler will close the app window if it is not the main window. CHECK_FAILURE(m_webView->add_WindowCloseRequested( Callback<ICoreWebView2WindowCloseRequestedEventHandler>([this]( ICoreWebView2* sender, IUnknown* args) { if (m_isPopupWindow) { CloseAppWindow(); } return S_OK; }).Get(), nullptr)); //! [WindowCloseRequested] //! [NewBrowserVersionAvailable] // After the environment is successfully created, // register a handler for the NewBrowserVersionAvailable event. // This handler tells when there is a new Edge version available on the machine. CHECK_FAILURE(m_webViewEnvironment->add_NewBrowserVersionAvailable( Callback<ICoreWebView2NewBrowserVersionAvailableEventHandler>( [this](ICoreWebView2Environment* sender, IUnknown* args) -> HRESULT { std::wstring message = L"We detected there is a new version for the browser."; if (m_webView) { message += L"Do you want to restart the app? \n\n"; message += L"Click No if you only want to re-create the webviews. \n"; message += L"Click Cancel for no action. \n"; } int response = MessageBox( m_mainWindow, message.c_str(), L"New available version", m_webView ? MB_YESNOCANCEL : MB_OK); if (response == IDYES) { RestartApp(); } else if (response == IDNO) { ReinitializeWebViewWithNewBrowser(); } else { // do nothing } return S_OK; }) .Get(), nullptr)); //! [NewBrowserVersionAvailable] } // Updates the sizing and positioning of everything in the window. void AppWindow::ResizeEverything() { RECT availableBounds = {0}; GetClientRect(m_mainWindow, &availableBounds); if (!m_containsFullscreenElement) { availableBounds = m_toolbar.Resize(availableBounds); } if (auto view = GetComponent<ViewComponent>()) { view->SetBounds(availableBounds); } } //! [Close] // Close the WebView and deinitialize related state. This doesn't close the app window. void AppWindow::CloseWebView(bool cleanupUserDataFolder) { DeleteAllComponents(); if (m_controller) { m_controller->Close(); m_controller = nullptr; m_webView = nullptr; m_webView3 = nullptr; } m_webViewEnvironment = nullptr; if (cleanupUserDataFolder) { // For non-UWP apps, the default user data folder {Executable File Name}.WebView2 // is in the same directory next to the app executable. If end // developers specify userDataFolder during WebView environment // creation, they would need to pass in that explicit value here. // For more information about userDataFolder: // https://docs.microsoft.com/microsoft-edge/webview2/reference/win32/webview2-idl#createcorewebview2environmentwithoptions WCHAR userDataFolder[MAX_PATH] = L""; // Obtain the absolute path for relative paths that include "./" or "../" _wfullpath( userDataFolder, GetLocalPath(L".WebView2", true).c_str(), MAX_PATH); std::wstring userDataFolderPath(userDataFolder); std::wstring message = L"Are you sure you want to clean up the user data folder at\n"; message += userDataFolderPath; message += L"\n?\nWarning: This action is not reversible.\n\n"; message += L"Click No if there are other open WebView instances.\n"; if (MessageBox(m_mainWindow, message.c_str(), L"Cleanup User Data Folder", MB_YESNO) == IDYES) { CHECK_FAILURE(DeleteFileRecursive(userDataFolderPath)); } } } //! [Close] HRESULT AppWindow::DeleteFileRecursive(std::wstring path) { wil::com_ptr<IFileOperation> fileOperation; CHECK_FAILURE( CoCreateInstance(CLSID_FileOperation, NULL, CLSCTX_ALL, IID_PPV_ARGS(&fileOperation))); // Turn off all UI from being shown to the user during the operation. CHECK_FAILURE(fileOperation->SetOperationFlags(FOF_NO_UI)); wil::com_ptr<IShellItem> userDataFolder; CHECK_FAILURE( SHCreateItemFromParsingName(path.c_str(), NULL, IID_PPV_ARGS(&userDataFolder))); // Add the operation CHECK_FAILURE(fileOperation->DeleteItem(userDataFolder.get(), NULL)); CHECK_FAILURE(userDataFolder->Release()); // Perform the operation to delete the directory CHECK_FAILURE(fileOperation->PerformOperations()); CHECK_FAILURE(fileOperation->Release()); OleUninitialize(); return S_OK; } void AppWindow::CloseAppWindow() { CloseWebView(); DestroyWindow(m_mainWindow); } void AppWindow::DeleteComponent(ComponentBase* component) { for (auto iter = m_components.begin(); iter != m_components.end(); iter++) { if (iter->get() == component) { m_components.erase(iter); return; } } } void AppWindow::DeleteAllComponents() { // Delete components in reverse order of initialization. while (!m_components.empty()) { m_components.pop_back(); } } template <class ComponentType> std::unique_ptr<ComponentType> AppWindow::MoveComponent() { for (auto iter = m_components.begin(); iter != m_components.end(); iter++) { if (dynamic_cast<ComponentType*>(iter->get())) { auto wanted = reinterpret_cast<std::unique_ptr<ComponentType>&&>(std::move(*iter)); m_components.erase(iter); return std::move(wanted); } } return nullptr; } void AppWindow::SetTitleText(PCWSTR titleText) { SetWindowText(m_mainWindow, titleText); } RECT AppWindow::GetWindowBounds() { RECT hwndBounds = {0}; GetClientRect(m_mainWindow, &hwndBounds); return hwndBounds; } std::wstring AppWindow::GetLocalPath(std::wstring relativePath, bool keep_exe_path) { WCHAR rawPath[MAX_PATH]; GetModuleFileNameW(g_hInstance, rawPath, MAX_PATH); std::wstring path(rawPath); if (keep_exe_path) { path.append(relativePath); } else { std::size_t index = path.find_last_of(L"\\") + 1; path.replace(index, path.length(), relativePath); } return path; } std::wstring AppWindow::GetLocalUri( std::wstring relativePath, bool useVirtualHostName /*= true*/) { if (useVirtualHostName && m_webView3) { //! [LocalUrlUsage] const std::wstring localFileRootUrl = L"https://appassets.example/"; return localFileRootUrl + regex_replace(relativePath, std::wregex(L"\\\\"), L"/"); //! [LocalUrlUsage] } else { std::wstring path = GetLocalPath(L"assets\\" + relativePath, false); wil::com_ptr<IUri> uri; CHECK_FAILURE(CreateUri(path.c_str(), Uri_CREATE_ALLOW_IMPLICIT_FILE_SCHEME, 0, &uri)); wil::unique_bstr uriBstr; CHECK_FAILURE(uri->GetAbsoluteUri(&uriBstr)); return std::wstring(uriBstr.get()); } } void AppWindow::RunAsync(std::function<void()> callback) { auto* task = new std::function<void()>(callback); PostMessage(m_mainWindow, s_runAsyncWindowMessage, reinterpret_cast<WPARAM>(task), 0); } void AppWindow::EnterFullScreen() { DWORD style = GetWindowLong(m_mainWindow, GWL_STYLE); MONITORINFO monitor_info = {sizeof(monitor_info)}; m_hMenu = ::GetMenu(m_mainWindow); ::SetMenu(m_mainWindow, nullptr); if (GetWindowRect(m_mainWindow, &m_previousWindowRect) && GetMonitorInfo( MonitorFromWindow(m_mainWindow, MONITOR_DEFAULTTOPRIMARY), &monitor_info)) { SetWindowLong(m_mainWindow, GWL_STYLE, style & ~WS_OVERLAPPEDWINDOW); SetWindowPos( m_mainWindow, HWND_TOP, monitor_info.rcMonitor.left, monitor_info.rcMonitor.top, monitor_info.rcMonitor.right - monitor_info.rcMonitor.left, monitor_info.rcMonitor.bottom - monitor_info.rcMonitor.top, SWP_NOOWNERZORDER | SWP_FRAMECHANGED); } } void AppWindow::ExitFullScreen() { DWORD style = GetWindowLong(m_mainWindow, GWL_STYLE); ::SetMenu(m_mainWindow, m_hMenu); SetWindowLong(m_mainWindow, GWL_STYLE, style | WS_OVERLAPPEDWINDOW); SetWindowPos( m_mainWindow, NULL, m_previousWindowRect.left, m_previousWindowRect.top, m_previousWindowRect.right - m_previousWindowRect.left, m_previousWindowRect.bottom - m_previousWindowRect.top, SWP_NOOWNERZORDER | SWP_FRAMECHANGED); } // We have our own implementation of DCompositionCreateDevice2 that dynamically // loads dcomp.dll to create the device. Not having a static dependency on dcomp.dll // enables the sample app to run on versions of Windows that don't support dcomp. HRESULT AppWindow::DCompositionCreateDevice2(IUnknown* renderingDevice, REFIID riid, void** ppv) { HRESULT hr = E_FAIL; static decltype(::DCompositionCreateDevice2)* fnCreateDCompDevice2 = nullptr; if (fnCreateDCompDevice2 == nullptr) { HMODULE hmod = ::LoadLibraryEx(L"dcomp.dll", nullptr, 0); if (hmod != nullptr) { fnCreateDCompDevice2 = reinterpret_cast<decltype(::DCompositionCreateDevice2)*>( ::GetProcAddress(hmod, "DCompositionCreateDevice2")); } } if (fnCreateDCompDevice2 != nullptr) { hr = fnCreateDCompDevice2(renderingDevice, riid, ppv); } return hr; } // WinRT APIs cannot run without a DispatcherQueue. This helper function creates a // DispatcherQueueController (which instantiates a DispatcherQueue under the covers) that will // manage tasks for the WinRT APIs. The DispatcherQueue implementation lives in // CoreMessaging.dll Similar to dcomp.dll, we load CoreMessaging.dll dynamically so the sample // app can run on versions of windows that don't have CoreMessaging. HRESULT AppWindow::TryCreateDispatcherQueue() { namespace winSystem = winrt::Windows::System; HRESULT hr = S_OK; thread_local winSystem::DispatcherQueueController dispatcherQueueController{ nullptr }; if (dispatcherQueueController == nullptr) { hr = E_FAIL; static decltype(::CreateDispatcherQueueController)* fnCreateDispatcherQueueController = nullptr; if (fnCreateDispatcherQueueController == nullptr) { HMODULE hmod = ::LoadLibraryEx(L"CoreMessaging.dll", nullptr, 0); if (hmod != nullptr) { fnCreateDispatcherQueueController = reinterpret_cast<decltype(::CreateDispatcherQueueController)*>( ::GetProcAddress(hmod, "CreateDispatcherQueueController")); } } if (fnCreateDispatcherQueueController != nullptr) { winSystem::DispatcherQueueController controller{ nullptr }; DispatcherQueueOptions options { sizeof(DispatcherQueueOptions), DQTYPE_THREAD_CURRENT, DQTAT_COM_STA }; hr = fnCreateDispatcherQueueController( options, reinterpret_cast<ABI::Windows::System::IDispatcherQueueController**>( winrt::put_abi(controller))); dispatcherQueueController = controller; } } return hr; } #ifdef USE_WEBVIEW2_WIN10 //! [TextScaleChanged2] void AppWindow::OnTextScaleChanged( winrt::Windows::UI::ViewManagement::UISettings const& settings, winrt::Windows::Foundation::IInspectable const& args) { RunAsync([this] { m_toolbar.UpdateDpiAndTextScale(); if (auto view = GetComponent<ViewComponent>()) { view->UpdateDpiAndTextScale(); } }); } //! [TextScaleChanged2] #endif void AppWindow::UpdateCreationModeMenu() { HMENU hMenu = GetMenu(m_mainWindow); CheckMenuRadioItem( hMenu, IDM_CREATION_MODE_WINDOWED, #ifdef USE_WEBVIEW2_WIN10 IDM_CREATION_MODE_VISUAL_WINCOMP, #else IDM_CREATION_MODE_TARGET_DCOMP, #endif m_creationModeId, MF_BYCOMMAND); } double AppWindow::GetDpiScale() { return DpiUtil::GetDpiForWindow(m_mainWindow) * 1.0f / USER_DEFAULT_SCREEN_DPI; } double AppWindow::GetTextScale() { #ifdef USE_WEBVIEW2_WIN10 return m_uiSettings ? m_uiSettings.TextScaleFactor() : 1.0f; #else return 1.0f; #endif } void AppWindow::AddRef() { InterlockedIncrement((LONG *)&m_refCount); } void AppWindow::Release() { uint32_t refCount = InterlockedDecrement((LONG *)&m_refCount); if (refCount == 0) { delete this; } } void AppWindow::NotifyClosed() { m_isClosed = true; } void AppWindow::InstallComplete(int return_code) { if (!m_isClosed) { if (return_code == 0) { RunAsync([this] { InitializeWebView(); }); } else if (return_code == 1) { MessageBox(m_mainWindow, L"WebView Runtime failed to Install", L"WebView Runtime Installation status", MB_OK); } else if (return_code == 2) { MessageBox(m_mainWindow, L"WebView Bootstrapper failled to download", L"WebView Bootstrapper Download status", MB_OK); } } }
33.471712
168
0.638196
[ "vector" ]
6654526fe56ab607df440f16a7ee473473c26155
4,515
hpp
C++
example-07/include/internal/sync_api.hpp
joeatodd/SYCL-For-CUDA-Examples
aad6720cf052fb12557a14758d0e7f7adc151f30
[ "Apache-2.0" ]
41
2020-06-02T13:31:03.000Z
2022-02-07T10:46:55.000Z
example-07/include/internal/sync_api.hpp
joeatodd/SYCL-For-CUDA-Examples
aad6720cf052fb12557a14758d0e7f7adc151f30
[ "Apache-2.0" ]
7
2020-06-03T16:21:33.000Z
2021-06-27T14:48:11.000Z
example-07/include/internal/sync_api.hpp
joeatodd/SYCL-For-CUDA-Examples
aad6720cf052fb12557a14758d0e7f7adc151f30
[ "Apache-2.0" ]
12
2020-06-13T10:02:22.000Z
2022-01-08T02:47:27.000Z
#pragma once #include "handle.hpp" #include "common.hpp" #include "../tools/intrinsics.hpp" #include "../tools/sycl_queue_helpers.hpp" #include <type_traits> #include <vector> namespace hash { using namespace usm_smart_ptr; /** * Computes synchronously a hash. * @tparam M Hash method * @param q Queue to run on * @param in Pointer to the input data in any memory accessible by the HOST. Contains an array of data. * @param inlen Size in bytes of one block to hash. * @param out Pointer to the output memory accessible by the HOST * @param n_batch Number of blocks to hash. In and Out pointers must have correct sizes. */ template<method M, typename = std::enable_if_t<M != method::keccak && M != method::sha3 && M != method::blake2b> > inline void compute(sycl::queue &q, const byte *in, dword inlen, byte *out, dword n_batch) { if (is_ptr_usable(in, q) && is_ptr_usable(out, q)) { internal::dispatch_hash<M, 0>(q, sycl::event{}, device_accessible_ptr<byte>(in), device_accessible_ptr<byte>(out), inlen, n_batch, nullptr, 0).wait(); } else { internal::hash_with_data_copy<M, 0>({q, in, out, n_batch, inlen}, nullptr, 0).dev_e_.wait(); } } /** * Computes synchronously a hash. * @tparam M Hash method * @tparam n_outbit Number of bits to output * @param q Queue to run on * @param in Pointer to the input data in any memory accessible by the HOST. Contains an array of data. * @param inlen Size in bytes of one block to hash. * @param out Pointer to the output memory accessible by the HOST * @param n_batch Number of blocks to hash. In and Out pointers must have correct sizes. */ template<method M, int n_outbit, typename = std::enable_if_t<M == method::keccak || M == method::sha3 >> inline void compute(sycl::queue &q, const byte *in, dword inlen, byte *out, dword n_batch) { if (is_ptr_usable(in, q) && is_ptr_usable(out, q)) { internal::dispatch_hash<M, n_outbit>(q, sycl::event{}, device_accessible_ptr<byte>(in), device_accessible_ptr<byte>(out), inlen, n_batch, nullptr, 0).wait(); } else { internal::hash_with_data_copy<M, n_outbit>({q, in, out, n_batch, inlen}, nullptr, 0).dev_e_.wait(); } } /** * Computes synchronously a hash. * @tparam M Hash method * @tparam n_outbit Number of bits to output * @param q Queue to run on * @param in Pointer to the input data in any memory accessible by the HOST. Contains an array of data. * @param inlen Size in bytes of one block to hash. * @param out Pointer to the output memory accessible by the HOST * @param n_batch Number of blocks to hash. In and Out pointers must have correct sizes. */ template<method M, int n_outbit, typename = std::enable_if_t<M == method::blake2b>> inline void compute(sycl::queue &q, const byte *in, dword inlen, byte *out, dword n_batch, byte *key, dword keylen) { if (is_ptr_usable(in, q) && is_ptr_usable(out, q)) { internal::dispatch_hash<M, n_outbit>(q, sycl::event{}, device_accessible_ptr<byte>(in), device_accessible_ptr<byte>(out), inlen, n_batch, key, keylen).wait(); } else { internal::hash_with_data_copy<M, n_outbit>({q, in, out, n_batch, inlen}, key, keylen).dev_e_.wait(); } } #define alias_sync_compute(alias_name, method) \ template <typename... Args> \ auto alias_name(Args&&... args) -> decltype(compute<method>(std::forward<Args>(args)...)) { \ return compute<method>(std::forward<Args>(args)...); \ } #define alias_sync_compute_with_n_outbit(alias_name, method) \ template <int n_outbit, typename... Args> \ auto alias_name(Args&&... args) -> decltype(compute<method, n_outbit>(std::forward<Args>(args)...)) { \ return compute<method, n_outbit>(std::forward<Args>(args)...); \ } alias_sync_compute(compute_md2, hash::method::md2) alias_sync_compute(compute_md5, hash::method::md5) alias_sync_compute(compute_sha1, hash::method::sha1) alias_sync_compute(compute_sha256, hash::method::sha256) alias_sync_compute_with_n_outbit(compute_sha3, hash::method::sha3) alias_sync_compute_with_n_outbit(compute_blake2b, hash::method::blake2b) alias_sync_compute_with_n_outbit(compute_keccak, hash::method::keccak) #undef alias_sync_compute #undef alias_sync_compute_with_n_outbit } //namespace hash::v_1
42.196262
170
0.67021
[ "vector" ]
665699d53efbb132dea54c6e155fd32adab1b7cd
1,141
cc
C++
src/p414.thirdMaximumNumber.cc
magic-akari/leetcode
8ed6af08c9d411461de67de939f88d4d788bbbe3
[ "MIT" ]
null
null
null
src/p414.thirdMaximumNumber.cc
magic-akari/leetcode
8ed6af08c9d411461de67de939f88d4d788bbbe3
[ "MIT" ]
null
null
null
src/p414.thirdMaximumNumber.cc
magic-akari/leetcode
8ed6af08c9d411461de67de939f88d4d788bbbe3
[ "MIT" ]
null
null
null
/* * @lc app=leetcode id=414 lang=cpp * * [414] Third Maximum Number */ #include <algorithm> #include <vector> using namespace std; // @lc code=start class Solution { public: auto thirdMax(vector<int>& nums) -> int { auto first = INT64_MIN; auto second = INT64_MIN; auto third = INT64_MIN; for (decltype(first)&& i : nums) { if (i == first || i == second || i == third) { continue; } if (i > first) { swap(i, first); } if (i > second) { swap(i, second); } if (i > third) { swap(i, third); } } return static_cast<int>(third == INT64_MIN ? first : third); } }; // @lc code=end #include <iostream> auto main(int argc, char const* argv[]) -> int { Solution s; auto* a = new vector<int>{3, 2, 1}; cout << s.thirdMax(*a) << endl; auto* b = new vector<int>{1, 2}; cout << s.thirdMax(*b) << endl; auto* c = new vector<int>{2, 2, 3, 1}; cout << s.thirdMax(*c) << endl; return 0; }
19.338983
68
0.473269
[ "vector" ]
665bf9cb12785ca76be134c8e7cb77c073c5eaae
1,285
cpp
C++
measurement_all.cpp
Sam91/vmc_general
cb2b0cb103a66307a3d78dbf137582a3ad224f8d
[ "MIT" ]
null
null
null
measurement_all.cpp
Sam91/vmc_general
cb2b0cb103a66307a3d78dbf137582a3ad224f8d
[ "MIT" ]
null
null
null
measurement_all.cpp
Sam91/vmc_general
cb2b0cb103a66307a3d78dbf137582a3ad224f8d
[ "MIT" ]
null
null
null
/* * Measurement that can be included in wavefunction::accumulate() * * Implements measurement of the full correlator between all sites (first used for the Kagome lattice Dirac state) * Note that we are averaging over lattice translations here, so wavefunction::average() needs to divide by L2 * * For this measurement, we need NO = Q*Q*L2 */ /* simple nearest-neighbor S.S for (int i1=0; i1<N;i1++){ for(int n=1; n<=alpha->mylattice->links[i1][0][0]; n++) { fj[0] += swap( i1, alpha->mylattice->links[i1][0][n], true ); } } */ //this should be fixed to use linear indices directly int i1r, i2r; for (int l1=0; l1<Q; l1++){ // loop over first label within unit cell for (int l2=0; l2<Q; l2++){ // over second label for (int v1=0; v1<L; v1++){ // loop over vector x-coordinate for (int v2=0; v2<L; v2++){ // loop over vector y-coordinate for (int i1=0; i1<L; i1++){ // loop over site x-coordinate for (int i2=0; i2<L; i2++){ // loop over site y-coordinate i1r = i1+v1; i2r = i2+v2; alpha->mylattice->torus(i1r, i2r); fj[ (Q*l2+l1)*L2+L*v2+v1 ] += swap(Q*(L*i2+i1)+l1, Q*(L*i2r+i1r)+l2, true); } } } } } }
32.948718
114
0.564981
[ "vector" ]
6662d371f104322f0916eb70cb26d3e56daf401b
6,495
cpp
C++
core/src/Graphics/ShaderCompiler/ShaderTranspiler.cpp
GCLemon/Altseed2
89ee75a5a4c8f094989257fcc1cdbd5dee7f34c3
[ "MIT" ]
null
null
null
core/src/Graphics/ShaderCompiler/ShaderTranspiler.cpp
GCLemon/Altseed2
89ee75a5a4c8f094989257fcc1cdbd5dee7f34c3
[ "MIT" ]
null
null
null
core/src/Graphics/ShaderCompiler/ShaderTranspiler.cpp
GCLemon/Altseed2
89ee75a5a4c8f094989257fcc1cdbd5dee7f34c3
[ "MIT" ]
null
null
null
#include "ShaderTranspiler.h" #include <glslang/Include/ResourceLimits.h> #include <glslang/Public/ShaderLang.h> #include <glslang/SPIRV/GlslangToSpv.h> #include <iostream> #include <spirv_cross/spirv_cross.hpp> #include <spirv_cross/spirv_glsl.hpp> #include <spirv_cross/spirv_hlsl.hpp> #include <spirv_cross/spirv_msl.hpp> #include <spirv_cross/spirv_reflect.hpp> #include "../../Common/StringHelper.h" #include "ResourceLimits.h" namespace Altseed { EShLanguage GetGlslangShaderStage(ShaderStageType type) { if (type == ShaderStageType::Vertex) return EShLanguage::EShLangVertex; if (type == ShaderStageType::Pixel) return EShLanguage::EShLangFragment; throw std::string("Unimplemented ShaderStage"); } SPIRV::SPIRV(const std::vector<uint32_t>& data, ShaderStageType shaderStage) : data_(data), shaderStage_(shaderStage) {} SPIRV::SPIRV(const std::string& error) : error_(error) {} ShaderStageType SPIRV::GetStage() const { return shaderStage_; } const std::vector<uint32_t>& SPIRV::GetData() const { return data_; } bool SPIRVTranspiler::Transpile(const std::shared_ptr<SPIRV>& spirv) { return false; } std::string SPIRVTranspiler::GetErrorCode() const { return errorCode_; } std::string SPIRVTranspiler::GetCode() const { return code_; } bool SPIRVToHLSLTranspiler::Transpile(const std::shared_ptr<SPIRV>& spirv) { spirv_cross::CompilerHLSL compiler(spirv->GetData()); spirv_cross::CompilerGLSL::Options options; options.separate_shader_objects = true; compiler.set_common_options(options); spirv_cross::CompilerHLSL::Options targetOptions; compiler.set_hlsl_options(targetOptions); code_ = compiler.compile(); return true; } bool SPIRVToMSLTranspiler::Transpile(const std::shared_ptr<SPIRV>& spirv) { spirv_cross::CompilerMSL compiler(spirv->GetData()); spirv_cross::ShaderResources resources = compiler.get_shader_resources(); spirv_cross::CompilerGLSL::Options options; compiler.set_common_options(options); spirv_cross::CompilerMSL::Options targetOptions; compiler.set_msl_options(targetOptions); code_ = compiler.compile(); return true; } bool SPIRVToGLSLTranspiler::Transpile(const std::shared_ptr<SPIRV>& spirv) { spirv_cross::CompilerGLSL compiler(spirv->GetData()); // to combine a sampler and a texture compiler.build_combined_image_samplers(); spirv_cross::ShaderResources resources = compiler.get_shader_resources(); int32_t binding = 0; if (isVulkanMode_) { binding += 1; } for (auto& resource : resources.sampled_images) { auto i = compiler.get_decoration(resource.id, spv::DecorationLocation); compiler.set_decoration(resource.id, spv::DecorationBinding, binding); binding += 1; } spirv_cross::CompilerGLSL::Options options; options.version = 420; options.enable_420pack_extension = true; compiler.set_common_options(options); code_ = compiler.compile(); return true; } class ReflectionCompiler : public spirv_cross::Compiler { public: ReflectionCompiler(const std::vector<uint32_t>& data) : Compiler(data) {} virtual ~ReflectionCompiler() = default; size_t get_member_count(uint32_t id) const { const spirv_cross::Meta& m = ir.meta.at(id); return m.members.size(); } spirv_cross::SPIRType get_member_type(const spirv_cross::SPIRType& struct_type, uint32_t index) const { return get<spirv_cross::SPIRType>(struct_type.member_types[index]); } }; bool SPIRVReflection::Transpile(const std::shared_ptr<SPIRV>& spirv) { Textures.clear(); Uniforms.clear(); ReflectionCompiler compiler(spirv->GetData()); spirv_cross::ShaderResources resources = compiler.get_shader_resources(); // Texture for (const auto& sampler : resources.separate_images) { ShaderReflectionTexture t; t.Name = utf8_to_utf16(sampler.name); t.Offset = compiler.get_decoration(sampler.id, spv::DecorationBinding); Textures.push_back(t); } // Uniform for (const auto& resource : resources.uniform_buffers) { auto count = compiler.get_member_count(resource.base_type_id); auto spirvType = compiler.get_type(resource.type_id); for (auto i = 0; i < count; i++) { ShaderReflectionUniform u; auto memberType = compiler.get_member_type(spirvType, i); u.Name = utf8_to_utf16(compiler.get_member_name(resource.base_type_id, i)); u.Size = static_cast<int32_t>(compiler.get_declared_struct_member_size(spirvType, i)); u.Offset = compiler.get_member_decoration(resource.base_type_id, i, spv::DecorationOffset); Uniforms.push_back(u); } } return true; } bool SPIRVGenerator::Initialize() { glslang::InitializeProcess(); return true; } void SPIRVGenerator::Terminate() { glslang::FinalizeProcess(); } std::shared_ptr<SPIRV> SPIRVGenerator::Generate(const char* code, ShaderStageType shaderStageType) { std::string codeStr(code); glslang::TProgram program = glslang::TProgram(); TBuiltInResource resources = glslang::DefaultTBuiltInResource; auto shaderStage = GetGlslangShaderStage(shaderStageType); glslang::TShader shader = glslang::TShader(shaderStage); shader.setEnvInput(glslang::EShSourceHlsl, shaderStage, glslang::EShClientOpenGL, glslang::EShTargetOpenGL_450); shader.setEnvClient(glslang::EShClientOpenGL, glslang::EShTargetOpenGL_450); shader.setEnvTarget(glslang::EShTargetSpv, glslang::EShTargetSpv_1_0); const char* shaderStrings[1]; shaderStrings[0] = codeStr.c_str(); shader.setEntryPoint("main"); // shader->setAutoMapBindings(true); // shader->setAutoMapLocations(true); shader.setStrings(shaderStrings, 1); EShMessages messages = (EShMessages)(EShMsgSpvRules | EShMsgVulkanRules); messages = (EShMessages)(messages | EShMsgReadHlsl); messages = (EShMessages)(messages | EShOptFull); int defaultVersion = 110; if (!shader.parse(&resources, defaultVersion, false, messages)) { return std::make_shared<SPIRV>(shader.getInfoLog()); } program.addShader(&shader); if (!program.link(messages)) { return std::make_shared<SPIRV>(program.getInfoLog()); } std::vector<unsigned int> spirv; glslang::GlslangToSpv(*program.getIntermediate(shaderStage), spirv); return std::make_shared<SPIRV>(spirv, shaderStageType); } } // namespace Altseed
33.137755
120
0.721324
[ "vector" ]
666a950d5595dda689192ff056642bc98cc6f23a
3,295
cpp
C++
src/plugins/profiler/ProfilerPoolManager.cpp
EricKTCheung/dmlite
7fe31e16fc18e3c3d8b048a3507f7769ef3f8a9d
[ "Apache-2.0" ]
null
null
null
src/plugins/profiler/ProfilerPoolManager.cpp
EricKTCheung/dmlite
7fe31e16fc18e3c3d8b048a3507f7769ef3f8a9d
[ "Apache-2.0" ]
null
null
null
src/plugins/profiler/ProfilerPoolManager.cpp
EricKTCheung/dmlite
7fe31e16fc18e3c3d8b048a3507f7769ef3f8a9d
[ "Apache-2.0" ]
null
null
null
/// @file ProfilerPoolManager.cpp /// @brief ProfilerPoolManager implementation. /// @author Alejandro Álvarez Ayllón <aalvarez@cern.ch> #include "Profiler.h" #include "XrdXrootdMonData.hh" #include <string.h> using namespace dmlite; ProfilerPoolManager::ProfilerPoolManager(PoolManager* decorates) throw(DmException) { this->decorated_ = decorates; this->decoratedId_ = strdup( decorates->getImplId().c_str() ); Log(Logger::Lvl3, profilerlogmask, profilerlogname, ""); } ProfilerPoolManager::~ProfilerPoolManager() { delete this->decorated_; free(this->decoratedId_); Log(Logger::Lvl3, profilerlogmask, profilerlogname, ""); } std::string ProfilerPoolManager::getImplId() const throw () { std::string implId = "ProfilerPoolManager"; implId += " over "; implId += this->decoratedId_; return implId; } void ProfilerPoolManager::setStackInstance(StackInstance* si) throw (DmException) { BaseInterface::setStackInstance(this->decorated_, si); this->stack_ = si; } void ProfilerPoolManager::setSecurityContext(const SecurityContext* ctx) throw (DmException) { BaseInterface::setSecurityContext(this->decorated_, ctx); } std::vector<Pool> ProfilerPoolManager::getPools(PoolAvailability availability) throw (DmException) { Log(Logger::Lvl4, profilerlogmask, profilerlogname, "availability: " << availability); PROFILE_RETURN(std::vector<Pool>, getPools, availability); } Pool ProfilerPoolManager::getPool(const std::string& poolname) throw (DmException) { Log(Logger::Lvl4, profilerlogmask, profilerlogname, "poolname: " << poolname); PROFILE_RETURN(Pool, getPool, poolname); } void ProfilerPoolManager::newPool(const Pool& pool) throw (DmException) { Log(Logger::Lvl4, profilerlogmask, profilerlogname, "pool: " << pool.name); PROFILE(newPool, pool); } void ProfilerPoolManager::updatePool(const Pool& pool) throw (DmException) { Log(Logger::Lvl4, profilerlogmask, profilerlogname, "pool: " << pool.name); PROFILE(updatePool, pool); } void ProfilerPoolManager::deletePool(const Pool& pool) throw (DmException) { Log(Logger::Lvl4, profilerlogmask, profilerlogname, "pool: " << pool.name); PROFILE(deletePool, pool); } Location ProfilerPoolManager::whereToRead(const std::string& path) throw (DmException) { Log(Logger::Lvl4, profilerlogmask, profilerlogname, "path: " << path); PROFILE_ASSIGN(Location, whereToRead, path); //reportXrdRedirCmd(ret, XROOTD_MON_OPENR); Log(Logger::Lvl3, profilerlogmask, profilerlogname, "return: " << ret.toString()); return ret; } Location ProfilerPoolManager::whereToRead(ino_t inode) throw (DmException) { Log(Logger::Lvl4, profilerlogmask, profilerlogname, "inode: " << inode); PROFILE_RETURN(Location, whereToRead, inode); } Location ProfilerPoolManager::whereToWrite(const std::string& path) throw (DmException) { Log(Logger::Lvl4, profilerlogmask, profilerlogname, "path: " << path); PROFILE_ASSIGN(Location, whereToWrite, path); //reportXrdRedirCmd(ret, XROOTD_MON_OPENW); Log(Logger::Lvl3, profilerlogmask, profilerlogname, "return: " << ret.toString()); return ret; } void ProfilerPoolManager::getDirSpaces(const std::string& path, int64_t &totalfree, int64_t &used) throw (DmException) { PROFILE(getDirSpaces, path, totalfree, used); }
25.152672
118
0.744158
[ "vector" ]
6672e0b96d65e227f689152bdefff44fa61731f8
3,989
cpp
C++
pic2pic/deal_2dpts.cpp
sublimationAC/face_transfer
47460ade0d701b5f930fb5f56a8cc85af5d5a9ed
[ "MIT" ]
null
null
null
pic2pic/deal_2dpts.cpp
sublimationAC/face_transfer
47460ade0d701b5f930fb5f56a8cc85af5d5a9ed
[ "MIT" ]
null
null
null
pic2pic/deal_2dpts.cpp
sublimationAC/face_transfer
47460ade0d701b5f930fb5f56a8cc85af5d5a9ed
[ "MIT" ]
null
null
null
#include "deal_2dpts.hpp" void get_over01_idx(std::string path_over01_idx, Eigen::VectorXi &over01_idx) { puts("get idx z over -0.1"); FILE *fp; fopen_s(&fp, path_over01_idx.c_str(), "r"); int n; fscanf_s(fp, "%d", &n); printf("number of idx: %d\n", n); over01_idx.resize(n); for (int i = 0; i < n; i++) fscanf_s(fp, "%d", &over01_idx(i)); fclose(fp); } void mesh_overlay_pic(std::string pic_path, Eigen::MatrixX2f &mesh2d_vtx) { puts("mesh covering..."); cv::Mat img = cv::imread(pic_path.c_str()); cv::Mat img_ini = img.clone(); for (int i = 0; i < 10; i++) std::cout << mesh2d_vtx.row(i) << "\n"; for (int i = 0; i < mesh2d_vtx.rows(); i++) { /*Point pos( width - 1 - (int)(round((y[i] - mi_y) / (ma_y - mi_y)*(width - 1))), height - 1 - (int)(round((x[i] - mi_x) / (ma_x - mi_x)*(height - 1)))); img.at<Vec3f>(pos) = Vec3f(b[i], g[i], r[i]);*/ cv::Point pos(mesh2d_vtx(i, 0), img.rows - mesh2d_vtx(i, 1)); //printf("%d %.10f %.10f %d %d\n", i, mesh2d_vtx(i, 0), img.rows - mesh2d_vtx(i, 1), img.cols, img.rows); std::cout << pos << "\n"; if (pos.inside(cv::Rect(0, 0, img.cols, img.rows))) img.at<cv::Vec3b>(pos) = cv::Vec3b(133, 180, 250); else printf("%d %.10f %.10f\n", i, mesh2d_vtx(i, 0), img.rows - mesh2d_vtx(i, 1)); } //GaussianBlur(img, img, Size(3, 3), 0, 0); //blur(img, img, Size(10, 10)); cv::imshow("test", img_ini); cv::imshow("result", img); cv::waitKey(0); } void get_face_hull_idx(std::vector<int> &face_hull_idx) { puts("getting face hull index"); for (int i = 0; i < 15; i++) face_hull_idx.push_back(i); face_hull_idx.push_back(15); face_hull_idx.push_back(16); face_hull_idx.push_back(17); face_hull_idx.push_back(23); face_hull_idx.push_back(22); face_hull_idx.push_back(21); } bool bj_fld_fl[1000][1000]; void face_transfer( DataPoint &sc_data, DataPoint &tg_data, Eigen::MatrixX2f &sc_mesh2d_vtx, Eigen::MatrixX2f &tg_mesh2d_vtx, cv::Mat tg_face_hull_mask, cv::Mat ans) { puts("face transferring..."); std::queue<std::pair<int, cv::Point> > que; while (!que.empty()) que.pop(); memset(bj_fld_fl, 0, sizeof(bj_fld_fl)); for (int i_v = 0, sz = tg_mesh2d_vtx.rows(); i_v < sz; i_v++) { printf("fc tf %d\n", i_v); cv::Point pos = cv::Point((int)tg_mesh2d_vtx(i_v, 0), (int)tg_mesh2d_vtx(i_v, 1)); if (tg_face_hull_mask.at<cv::Vec3b>(pos) != cv::Vec3b(255, 255, 255)) continue; ans.at<cv::Vec3b>(pos) = sc_data.image.at<cv::Vec3b>(cv::Point((int)sc_mesh2d_vtx(i_v, 0), (int)sc_mesh2d_vtx(i_v, 1))); que.push(std::make_pair(i_v, cv::Point(0, 0))); bj_fld_fl[pos.x][pos.y] = 1; } puts("fc tf next"); flood_fill(que, sc_data, tg_face_hull_mask, sc_mesh2d_vtx,tg_mesh2d_vtx, sc_data.eye_dis/tg_data.eye_dis, ans); } const int fdfl_dx[8] = { -1,-1,-1,0,0,1,1,1 }; const int fdfl_dy[8] = { -1,0,1,-1,1,-1,0,1 }; void flood_fill( std::queue<std::pair<int, cv::Point> > &que, DataPoint &sc_data, cv::Mat tg_face_hull_mask, Eigen::MatrixX2f &sc_mesh2d_vtx, Eigen::MatrixX2f &tg_mesh2d_vtx, float ratio, cv::Mat ans) { puts("flood filling..."); while (!que.empty()) { int idx = que.front().first; int dx = que.front().second.x, dy = que.front().second.y; que.pop(); if (dx == 2 || dx == -2 || dy == 2 || dy == -2) continue; printf("fdfl %d %d %d\n", idx, dx, dy); for (int i = 0; i < 8; i++) { int du = dx + fdfl_dx[i], dv = dy + fdfl_dy[i]; cv::Point pos = cv::Point((int)tg_mesh2d_vtx(idx, 0) + du, (int)tg_mesh2d_vtx(idx, 1) + dv); if (bj_fld_fl[pos.x][pos.y]) continue; if (tg_face_hull_mask.at<cv::Vec3b>(pos) != cv::Vec3b(255, 255, 255)) continue; int sc_du = (int)(du* ratio + 0.5),sc_dv=(int)(dv*ratio+0.5); ans.at<cv::Vec3b>(pos) = sc_data.image.at<cv::Vec3b>(cv::Point((int)sc_mesh2d_vtx(idx, 0) + sc_du, (int)sc_mesh2d_vtx(idx, 1) + sc_dv)); que.push(std::make_pair(idx,cv::Point(du, dv))); bj_fld_fl[pos.x][pos.y] = 1; } } }
38.728155
123
0.610429
[ "mesh", "vector" ]
66735d8cd028ba800cc962334bd8b7ae4c165393
8,930
cpp
C++
projects/view3d/render/scene.cpp
psryland/rylogic_code
f79e471fe0d6714c5e0cf8385ddc2a88ab2e082b
[ "CNRI-Python" ]
2
2020-11-11T16:19:04.000Z
2021-01-19T01:53:29.000Z
projects/view3d/render/scene.cpp
psryland/rylogic_code
f79e471fe0d6714c5e0cf8385ddc2a88ab2e082b
[ "CNRI-Python" ]
1
2020-07-27T09:00:21.000Z
2020-07-27T10:58:10.000Z
projects/view3d/render/scene.cpp
psryland/rylogic_code
f79e471fe0d6714c5e0cf8385ddc2a88ab2e082b
[ "CNRI-Python" ]
1
2021-04-04T01:39:55.000Z
2021-04-04T01:39:55.000Z
//********************************************* // Renderer // Copyright (c) Rylogic Ltd 2012 //********************************************* #include "pr/view3d/forward.h" #include "pr/view3d/render/scene.h" #include "pr/view3d/render/window.h" #include "pr/view3d/render/renderer.h" #include "pr/view3d/instances/instance.h" #include "pr/view3d/steps/forward_render.h" #include "pr/view3d/steps/gbuffer.h" #include "pr/view3d/steps/dslighting.h" #include "pr/view3d/steps/shadow_map.h" #include "pr/view3d/steps/ray_cast.h" #include "view3d/render/state_stack.h" namespace pr::rdr { // Make a scene Scene::Scene(Window& wnd, std::initializer_list<ERenderStep> rsteps, SceneView const& view) :m_wnd(&wnd) ,m_view(view) ,m_viewport(wnd.RenderTargetSize()) ,m_instances() ,m_render_steps() ,m_ht_immediate() ,m_bkgd_colour() ,m_global_light() ,m_global_envmap() ,m_dsb() ,m_rsb() ,m_bsb() ,m_diag(wnd.rdr()) ,m_eh_resize() { SetRenderSteps(rsteps); // Set default scene render states m_rsb = RSBlock::SolidCullBack(); // Use line antialiasing if multi-sampling is enabled if (wnd.m_multisamp.Count != 1) m_rsb.Set(ERS::MultisampleEnable, TRUE); // Sign up for back buffer resize events m_eh_resize = wnd.m_rdr->BackBufferSizeChanged += std::bind(&Scene::HandleBackBufferSizeChanged, this, _1, _2); } // Access the renderer Renderer& Scene::rdr() const { return m_wnd->rdr(); } Window& Scene::wnd() const { return *m_wnd; } // Set the render steps to use for rendering the scene void Scene::SetRenderSteps(std::initializer_list<ERenderStep> rsteps) { m_render_steps.clear(); for (auto rs : rsteps) { switch (rs) { case ERenderStep::ForwardRender: m_render_steps.emplace_back(new ForwardRender(*this)); break; case ERenderStep::GBuffer: m_render_steps.emplace_back(new GBuffer(*this)); break; case ERenderStep::DSLighting: m_render_steps.emplace_back(new DSLighting(*this)); break; case ERenderStep::ShadowMap: m_render_steps.emplace_back(new ShadowMap(*this, m_global_light)); break; case ERenderStep::RayCast: m_render_steps.emplace_back(new RayCastStep(*this, true)); break; default: throw std::exception("Unknown render step"); } } } // Perform an immediate hit test void Scene::HitTest(HitTestRay const* rays, int count, float snap_distance, EHitTestFlags flags, RayCastStep::Instances instances, RayCastStep::ResultsOut const& results) { if (rays == nullptr || count == 0) return; // Lazy create the ray cast step // Note: I've noticed that with runtime shaders enabled, reusing the same RayCastStep // doesn't seem to work, I never figured out why though. I had to create a new RayCastStep // for each hit test. if (m_ht_immediate == nullptr) m_ht_immediate.reset(new RayCastStep(*this, false)); auto& rs = *m_ht_immediate.get(); // Set the rays to cast rs.SetRays(rays, count, snap_distance, flags, [=](auto) { return true; }); // Create a ray cast render step and populate its draw list. // Note: don't look for and reuse an existing RayCastStep because callers may want // to invoke immediate ray casts without interfering with existing continuous ray casts. if (instances != nullptr) { for (BaseInstance const* inst; (inst = instances()) != nullptr;) rs.AddInstance(*inst); } else { for (auto& inst : m_instances) rs.AddInstance(*inst); } // Render just this step Renderer::Lock lock(m_wnd->rdr()); StateStack ss(lock.ImmediateDC(), *this); rs.Execute(ss); // Read (blocking) the hit test results rs.ReadOutput(results); // Reset ready for next time rs.ClearDrawlist(); } // Set the collection of rays to cast into the scene for continuous hit testing. void Scene::HitTestContinuous(HitTestRay const* rays, int count, float snap_distance, EHitTestFlags flags, RayCastStep::InstFilter const& include) { // Look for an existing RayCast render step if (rays == nullptr || count != 0) { // Ensure there is a ray cast render step, add if not. auto rs = static_cast<RayCastStep*>(FindRStep(ERenderStep::RayCast)); if (rs == nullptr) { // Add the ray cast step first so that 'CopyResource' can happen while we render the rest of the scene RenderStepPtr step(new RayCastStep(*this, true)); auto iter = m_render_steps.insert(begin(m_render_steps), std::move(step)); rs = static_cast<RayCastStep*>(iter->get()); } // Set the rays to cast. // Results will be available in 'm_ht_results' after Render() has been called a few times (due to multi-buffering) rs->SetRays(rays, count, snap_distance, flags, include); } else { // Remove the ray cast step if there are no rays to cast pr::erase_if(m_render_steps, [](auto& rs){ return rs->GetId() == ERenderStep::RayCast; }); } } // Read the hit test results from the continuous ray cast render step void Scene::HitTestGetResults(RayCastStep::ResultsOut const& results) { auto rs = static_cast<RayCastStep*>(FindRStep(ERenderStep::RayCast)); if (rs == nullptr) return; // Read the hit test results rs->ReadOutput(results); } // Find a render step by id RenderStep* Scene::FindRStep(ERenderStep id) const { for (auto& rs : m_render_steps) if (rs->GetId() == id) return rs.get(); return nullptr; } // Access the render step by Id RenderStep& Scene::operator[](ERenderStep id) const { auto rs = FindRStep(id); if (rs) return *rs; throw std::runtime_error(Fmt("RenderStep %s is not part of this scene", Enum<ERenderStep>::ToStringA(id))); } // Enable/Disable shadow casting void Scene::ShadowCasting(bool enable, int shadow_map_size) { if (enable) { // Ensure there is a shadow map render step auto shadow_map_step = FindRStep(ERenderStep::ShadowMap); if (shadow_map_step == nullptr) { RenderStepPtr step(new ShadowMap(*this, m_global_light, shadow_map_size)); // Insert the shadow map step before the main render step auto iter = begin(m_render_steps); for (; iter != end(m_render_steps) && (**iter).GetId() != ERenderStep::ForwardRender && (**iter).GetId() != ERenderStep::DSLighting; ++iter) {} m_render_steps.insert(iter, std::move(step)); } } else { // Remove the shadow map render step pr::erase_if(m_render_steps, [](auto& rs) { return rs->GetId() == ERenderStep::ShadowMap; }); } } // Reset the drawlist for each render step void Scene::ClearDrawlists() { m_instances.clear(); for (auto& rs : m_render_steps) rs->ClearDrawlist(); } // Populate the drawlist for each render step void Scene::UpdateDrawlists() { OnUpdateScene(*this); } // Add an instance. The instance must be resident for the entire time that it is // in the drawlist, i.e. until 'RemoveInstance' or 'ClearDrawlist' is called. // This method will add the instance to all render steps for which the model has appropriate nuggets. // Instances can be added to render steps directly if finer control is needed void Scene::AddInstance(BaseInstance const& inst) { m_instances.push_back(&inst); for (auto& rs : m_render_steps) rs->AddInstance(inst); } // Remove an instance from the scene void Scene::RemoveInstance(BaseInstance const& inst) { auto iter = pr::find(m_instances, &inst); if (iter != std::end(m_instances)) m_instances.erase_fast(iter); for (auto& rs : m_render_steps) rs->RemoveInstance(inst); } // Render the scene void Scene::Render() { Renderer::Lock lock(rdr()); // Don't call 'm_wnd->RestoreRT();' here because we might be rendering to // an off-screen texture. However, if the app contains multiple windows // each window will need to call 'm_wnd->RestoreRT()' before rendering. #if PR_DBG_RDR { // Check a render target has been set // Note: if you've called GetDC() you need to call ReleaseDC() and Window.RestoreRT() or RTV will be null D3DPtr<ID3D11RenderTargetView> rtv; D3DPtr<ID3D11DepthStencilView> dsv; lock.ImmediateDC()->OMGetRenderTargets(1, &rtv.m_ptr, &dsv.m_ptr); PR_ASSERT(PR_DBG_RDR, rtv != nullptr, "Render target is null."); // Ensure RestoreRT has been called PR_ASSERT(PR_DBG_RDR, dsv != nullptr, "Depth buffer is null."); // Ensure RestoreRT has been called } #endif // Invoke each render step in order StateStack ss(lock.ImmediateDC(), *this); for (auto& rs : m_render_steps) rs->Execute(ss); } // Resize the viewport on back buffer resize void Scene::HandleBackBufferSizeChanged(Window& wnd, BackBufferSizeChangedEventArgs const& args) { if (args.m_done && &wnd == m_wnd) { // Only adjust the width/height of the viewport to the new area. // If an application is using a different viewport region they'll // have to adjust it after this (and before the next frame is drawn) m_viewport.Width = float(args.m_area.x); m_viewport.Height = float(args.m_area.y); } } }
32.472727
171
0.694065
[ "render", "model" ]
6674aa7e4b2aaae72dc9d9e360247c5e296512a4
8,987
cc
C++
components/link_header_util/link_header_util_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
components/link_header_util/link_header_util_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
components/link_header_util/link_header_util_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 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 "components/link_header_util/link_header_util.h" #include "base/run_loop.h" #include "testing/gtest/include/gtest/gtest.h" namespace link_header_util { namespace { void SplitLinkHeaderForTesting(const std::string& header, std::vector<std::string>* values) { std::vector<StringIteratorPair> values_iterators = SplitLinkHeader(header); values->clear(); for (const auto& pair : values_iterators) values->push_back(std::string(pair.first, pair.second)); } bool ParseLinkHeaderValueForTesting( std::string value, std::string* url, std::unordered_map<std::string, absl::optional<std::string>>* params) { return ParseLinkHeaderValue(value.begin(), value.end(), url, params); } TEST(LinkHeaderTest, SplitEmpty) { std::vector<std::string> values; SplitLinkHeaderForTesting("", &values); ASSERT_EQ(0u, values.size()); } TEST(LinkHeaderTest, SplitSimple) { std::vector<std::string> values; SplitLinkHeaderForTesting("hello", &values); ASSERT_EQ(1u, values.size()); EXPECT_EQ("hello", values[0]); SplitLinkHeaderForTesting("foo, bar", &values); ASSERT_EQ(2u, values.size()); EXPECT_EQ("foo", values[0]); EXPECT_EQ("bar", values[1]); SplitLinkHeaderForTesting(" 1\t,\t2,3", &values); ASSERT_EQ(3u, values.size()); EXPECT_EQ("1", values[0]); EXPECT_EQ("2", values[1]); EXPECT_EQ("3", values[2]); } TEST(LinkHeaderTest, SplitSkipsEmpty) { std::vector<std::string> values; SplitLinkHeaderForTesting(", foo, , \t, bar", &values); ASSERT_EQ(2u, values.size()); EXPECT_EQ("foo", values[0]); EXPECT_EQ("bar", values[1]); } TEST(LinkHeaderTest, SplitQuotes) { std::vector<std::string> values; SplitLinkHeaderForTesting("\"foo,bar\", 'bar,foo', <hel,lo>", &values); ASSERT_EQ(4u, values.size()); EXPECT_EQ("\"foo,bar\"", values[0]); EXPECT_EQ("'bar", values[1]); EXPECT_EQ("foo'", values[2]); EXPECT_EQ("<hel,lo>", values[3]); } TEST(LinkHeaderTest, SplitEscapedQuotes) { std::vector<std::string> values; SplitLinkHeaderForTesting("\"f\\\"oo,bar\", 'b\\'ar,foo', <hel\\>,lo>", &values); ASSERT_EQ(5u, values.size()); EXPECT_EQ("\"f\\\"oo,bar\"", values[0]); EXPECT_EQ("'b\\'ar", values[1]); EXPECT_EQ("foo'", values[2]); EXPECT_EQ("<hel\\>", values[3]); EXPECT_EQ("lo>", values[4]); } struct SimpleParseTestData { const char* link; bool valid; const char* url; const char* rel; const char* as; }; void PrintTo(const SimpleParseTestData& test, std::ostream* os) { *os << ::testing::PrintToString(test.link); } class SimpleParseTest : public ::testing::TestWithParam<SimpleParseTestData> {}; TEST_P(SimpleParseTest, Simple) { const SimpleParseTestData test = GetParam(); std::string url; std::unordered_map<std::string, absl::optional<std::string>> params; EXPECT_EQ(test.valid, ParseLinkHeaderValueForTesting(test.link, &url, &params)); if (test.valid) { EXPECT_EQ(test.url, url); EXPECT_EQ(test.rel, params["rel"].value_or("")); EXPECT_EQ(test.as, params["as"].value_or("")); } } // Test data mostly copied from blink::LinkHeaderTest. Expectations for a small // subset of test cases are different though. Mostly because blink::LinkHeader // factors in knowledge about semantics of Link headers (parameters that are // required to have a value if they occur, some parameters are auto-lower-cased, // headers with an "anchor" parameter are rejected by base::LinkHeader). // The code this tests purely parses without actually interpreting the data, as // it is expected that another layer on top will do more specific validations. const SimpleParseTestData simple_parse_tests[] = { {"</images/cat.jpg>; rel=prefetch", true, "/images/cat.jpg", "prefetch", ""}, {"</images/cat.jpg>;rel=prefetch", true, "/images/cat.jpg", "prefetch", ""}, {"</images/cat.jpg> ;rel=prefetch", true, "/images/cat.jpg", "prefetch", ""}, {"</images/cat.jpg> ; rel=prefetch", true, "/images/cat.jpg", "prefetch", ""}, {"< /images/cat.jpg> ; rel=prefetch", true, "/images/cat.jpg", "prefetch", ""}, {"</images/cat.jpg > ; rel=prefetch", true, "/images/cat.jpg", "prefetch", ""}, {"</images/cat.jpg wutwut> ; rel=prefetch", true, "/images/cat.jpg wutwut", "prefetch", ""}, {"</images/cat.jpg wutwut \t > ; rel=prefetch", true, "/images/cat.jpg wutwut", "prefetch", ""}, {"</images/cat.jpg>; rel=prefetch ", true, "/images/cat.jpg", "prefetch", ""}, {"</images/cat.jpg>; Rel=prefetch ", true, "/images/cat.jpg", "prefetch", ""}, {"</images/cat.jpg>; Rel=PReFetCh ", true, "/images/cat.jpg", "PReFetCh", ""}, {"</images/cat.jpg>; rel=prefetch; rel=somethingelse", true, "/images/cat.jpg", "prefetch", ""}, {"</images/cat.jpg>\t\t ; \trel=prefetch \t ", true, "/images/cat.jpg", "prefetch", ""}, {"</images/cat.jpg>; rel= prefetch", true, "/images/cat.jpg", "prefetch", ""}, {"<../images/cat.jpg?dog>; rel= prefetch", true, "../images/cat.jpg?dog", "prefetch", ""}, {"</images/cat.jpg>; rel =prefetch", true, "/images/cat.jpg", "prefetch", ""}, {"</images/cat.jpg>; rel pel=prefetch", false}, {"< /images/cat.jpg>", true, "/images/cat.jpg", "", ""}, {"</images/cat.jpg>; wut=sup; rel =prefetch", true, "/images/cat.jpg", "prefetch", ""}, {"</images/cat.jpg>; wut=sup ; rel =prefetch", true, "/images/cat.jpg", "prefetch", ""}, {"</images/cat.jpg>; wut=sup ; rel =prefetch \t ;", true, "/images/cat.jpg", "prefetch", ""}, {"</images/cat.jpg> wut=sup ; rel =prefetch \t ;", false}, {"< /images/cat.jpg", false}, {"< http://wut.com/ sdfsdf ?sd>; rel=dns-prefetch", true, "http://wut.com/ sdfsdf ?sd", "dns-prefetch", ""}, {"< http://wut.com/%20%20%3dsdfsdf?sd>; rel=dns-prefetch", true, "http://wut.com/%20%20%3dsdfsdf?sd", "dns-prefetch", ""}, {"< http://wut.com/dfsdf?sdf=ghj&wer=rty>; rel=prefetch", true, "http://wut.com/dfsdf?sdf=ghj&wer=rty", "prefetch", ""}, {"< http://wut.com/dfsdf?sdf=ghj&wer=rty>;;;;; rel=prefetch", true, "http://wut.com/dfsdf?sdf=ghj&wer=rty", "prefetch", ""}, {"< http://wut.com/%20%20%3dsdfsdf?sd>; rel=preload;as=image", true, "http://wut.com/%20%20%3dsdfsdf?sd", "preload", "image"}, {"< http://wut.com/%20%20%3dsdfsdf?sd>; rel=preload;as=whatever", true, "http://wut.com/%20%20%3dsdfsdf?sd", "preload", "whatever"}, {"</images/cat.jpg>; rel=prefetch;", true, "/images/cat.jpg", "prefetch", ""}, {"</images/cat.jpg>; rel=prefetch ;", true, "/images/cat.jpg", "prefetch", ""}, {"</images/ca,t.jpg>; rel=prefetch ;", true, "/images/ca,t.jpg", "prefetch", ""}, {"<simple.css>; rel=stylesheet; title=\"title with a DQUOTE and " "backslash\"", true, "simple.css", "stylesheet", ""}, {"<simple.css>; rel=stylesheet; title=\"title with a DQUOTE \\\" and " "backslash: \\\"", false}, {"<simple.css>; title=\"title with a DQUOTE \\\" and backslash: \"; " "rel=stylesheet; ", true, "simple.css", "stylesheet", ""}, {"<simple.css>; title=\'title with a DQUOTE \\\' and backslash: \'; " "rel=stylesheet; ", true, "simple.css", "stylesheet", ""}, {"<simple.css>; title=\"title with a DQUOTE \\\" and ;backslash,: \"; " "rel=stylesheet; ", true, "simple.css", "stylesheet", ""}, {"<simple.css>; title=\"title with a DQUOTE \' and ;backslash,: \"; " "rel=stylesheet; ", true, "simple.css", "stylesheet", ""}, {"<simple.css>; title=\"\"; rel=stylesheet; ", true, "simple.css", "stylesheet", ""}, {"<simple.css>; title=\"\"; rel=\"stylesheet\"; ", true, "simple.css", "stylesheet", ""}, {"<simple.css>; rel=stylesheet; title=\"", false}, {"<simple.css>; rel=stylesheet; title=\"\"", true, "simple.css", "stylesheet", ""}, {"<simple.css>; rel=\"stylesheet\"; title=\"", false}, {"<simple.css>; rel=\";style,sheet\"; title=\"", false}, {"<simple.css>; rel=\"bla'sdf\"; title=\"", false}, {"<simple.css>; rel=\"\"; title=\"\"", true, "simple.css", "", ""}, {"<simple.css>; rel=''; title=\"\"", true, "simple.css", "''", ""}, {"<simple.css>; rel=''; bla", true, "simple.css", "''", ""}, {"<simple.css>; rel='prefetch", true, "simple.css", "'prefetch", ""}, {"<simple.css>; rel=\"prefetch", false}, {"<simple.css>; rel=\"", false}, {"simple.css; rel=prefetch", false}, {"<simple.css>; rel=prefetch; rel=foobar", true, "simple.css", "prefetch", ""}, }; INSTANTIATE_TEST_SUITE_P(LinkHeaderTest, SimpleParseTest, testing::ValuesIn(simple_parse_tests)); } // namespace } // namespace link_header_util
40.120536
80
0.60454
[ "vector" ]
6682b92f82e225b96b754357dddc4fb36663435c
13,707
cpp
C++
src/EulerUnsteady2D.cpp
LukeMcCulloch/cfd_solvers_cpp
69a6e8fde0e6b963a4d6d9e94f8241786d9088c5
[ "MIT" ]
5
2019-06-20T11:13:16.000Z
2022-03-30T07:31:12.000Z
src/EulerUnsteady2D.cpp
LukeMcCulloch/cfd_solvers_cpp
69a6e8fde0e6b963a4d6d9e94f8241786d9088c5
[ "MIT" ]
null
null
null
src/EulerUnsteady2D.cpp
LukeMcCulloch/cfd_solvers_cpp
69a6e8fde0e6b963a4d6d9e94f8241786d9088c5
[ "MIT" ]
1
2020-11-25T13:25:55.000Z
2020-11-25T13:25:55.000Z
//******************************************************************************** //* Educationally-Designed Unstructured 2D (EDU2D) Code //* //* //* --- This is EDU2D-Euler-RK2 --- //* //* //* EDU2D-Euler-RK2: An Euler code with //* //* - Node-centered finite-volume discretization //* - 2-stage Runge-Kutta explicit time-stepping scheme (RK2) //* //* //* //* specially set up for a shock-diffraction problem //* //* Wall //* -------------------- //* Post-shock (inflow) | | //* |->Shock | o: Corner node //* | Mach=5.09 | //* .......o |Outflow //* Wall | | //* | | //* | | //* -------------------- //* Outflow //* //* - Node-centered finite-volume method for unstructured grids (quad/tri/mixed) //* - Roe flux with an entropy fix and Rotated-RHLL flux //* - Gradient reconstruction by unweighted least-squares method //* - Van Albada slope limiter to the primitive variable gradients //* - 2-Stage Runge-Kutta global time-stepping towards the final time //* - All quantities are nondimensionalized; velocity and pressure are //* nondimensionalized based on the free stream speed of sound //* (see "I do like CFD, VOL.1", whose PDF can be downloaded at cfdbooks.com). //* //* written by Dr. Katate Masatsuka (info[at]cfdbooks.com), //* translated to c++ by Luke McCulloch, PhD. //* //* //* This is Version 0 (June 2019 translation) //* //* ------------------------------------------------------------------------------ //* Files: There were 3 files (in the fortran version). //* This translated version will differ. //* //* ------------------------------------------ //* - Main driver program file : This reads grid and BC files, and dummy NC/CC programs. //* //* edu2d_euler_rk2_main.f90 (This file), which contains a main driver program //* -- edu2d_euler_rk2 : Main driver code, which an Euler solver //* //* ------------------------------------------ //* - Basic EDU2D package file : Arranged for a 2D Euler code //* //* edu2d_basic_package_euler_rk2.f90, which contains the following modules. //* -- EulerSolver2D : Numerical values defined //* -- _data_type : Grid data types defined //* -- edu2d_main_data : Main grid data and parameters declared //* -- _data : Read/construct/check grid data //* //* ------------------------------------------ //* - Euler solver file : This computes a solution to the shock diffraction problem. //* //* edu2d_euler_rk2_main.f90, which contains a 2D Euler solver with RK2. //* -- edu2d_euler_rk2_solver : Node-centered Explicit Euler solver with RK2 //* //* ------------------------------------------------------------------------------ //* Notes: //* //* The purpose of this code is to give a beginner an opportunity to learn how to //* write an unstructured CFD code. Hence, the focus here is on the simplicity. //* The code is not optimized for efficiency. //* //* This code is set up specifi for a shock diffraction problem. //* It can be modified easily to solve other problems: //* //* 1. Define your own free stream Mach number, M_inf, at the beginning of the main. //* 2. Modify the subroutine, initial_solution_shock_diffraction(), which is in this //* file, to set up an appropriate initial condition for your problem. //* 3. Delete the special treatment at the corner in euler_solver_main.f90 //* (Special treatment is done in two places in that file.) //* //* If the code is not simple enough to understand, please send questions to Hiro //* at sunmasen(at)hotmail.com. I'll greatly appreciate it and revise the code. //* //* If the code helps you understand how to write your own code that is more //* efficient and has more features, it'll have served its purpose. //* //* ------------------------------------------------------------------------------ //* Examples of additional features you might want to add. //* //* 1. Local time-stepping (faster convergence for steady problems) //* 2. Implicit time-stepping (remove CFL restriction) //* 3. More boundary conditions (periodic, symmetry, suction, etc.) //* 4. Other reconstruction (Van Leer's kappa scheme) //* 5. Other limiters (Venkat/Barth limiter,etc.) //* 6. Other flux functions (HLL, LDFSS, AUSM, etc.) //* 7. Local-preconditioning (low-Mach number accuracy and stiffness removal) //* 8. CFL ramping (increase CFL gradually for a stable start-up) //* 9. More output (convergence history, etc.) //* 10. Parallelization (large-scale problems) //* 11. Grid adaptation (h-refinement, steady or unsteady) //* 12. Adjoint capability (aerodynamic design, adaptation, etc.) //* 13. Moving grid (sliding mesh, overset grid, etc.) //* 14. Multigrid (grid-independent convergence) //* ------------------------------------------------------------------------------ //* //* Katate Masatsuka, http://www.cfdbooks.com //******************************************************************************** //******************************************************************************** //* Main program: Node-centered finite-volume Euler code //* //* This code computes an unsteady solution of the Euler equations. //* It is set up to solve a shock diffraction problem. //* So, it is not really (but almost) a general purpose code. //* //* Input ------------------------------------------------------- //* //* project.grid = grid file containing boundary information //* project.bcmap = file that specifies boundary conditions //* //* (Note: See the subroutine "read_grid", which is in this file, //* for the format of these files.) //* //* Parameters to be specified inside the main program: //* //* M_inf = Upstream Mach number //* gamma = Ratio of specific heats (1.4 for air) //* CFL = CFL number (global time step) //* t_final = Final time to stop the calculation //* time_step_max = Max iterations (just a big enough number) //* inviscid_flux = Inviscid flux selection (1 = Roe, 2 = Rotated-RHLL) //* limiter_type = Limiter selection (1=Van Albada limiter, 0=No limiter) //* //* //* Output ------------------------------------------------------ //* //* "project_tecplot.dat" = Tecplot file containing the grid and the solution. //* //* //* NOTE: The variables are nondimensionalized values (compressible scale), //* rho=rho/rho_inf, u=u/a_inf, v=v/a_inf, rho=p/(rho_inf*a_inf^2) //* //* NOTE: Many variables are passed to subroutines via USE statement. //* Each module contains specific data, and they are accessed by USE. //* //* //* Katate Masatsuka, http://www.cfdbooks.com //* Translated to c++ by Luke McCulloch //* //* //* //******************************************************************************** //#define CHECKPT {printf("Checkpoint: .s, line .d\n",__FILE__,__LINE__);\ //fflush(stdout);} #ifdef DEBUG_BUILD # define DEBUG(x) fprintf(stderr, x) #else # define DEBUG(x) do {} while (0) #endif //================================= #include <iostream> // std::cout, std::fixed #include <fstream> // write to file #include <iomanip> // std::setprecision - only works for output :( #include <math.h> // sqrt //================================= #include <cstring> //needed for memset #include <string.h> //====================================== // my simple array class template (type) #include "tests_array.hpp" #include "array_template.hpp" #include "arrayops.hpp" //====================================== // my simple vector class template #include "vector.h" //====================================== // 2D Eiuler approximate Riemann sovler #include "EulerUnsteady2D.h" #include "EulerUnsteady2D_basic_package.h" //====================================== //using namespace std; //====================================== // //namespace EulerSolver2D{ // EulerSolver2D::MainData2D::MainData2D(std::string datafile_grid_in, // std::string datafile_bcmap_in) { EulerSolver2D::MainData2D::MainData2D() { boot_diagnostic("log/out.dat"); cout << "end of grid constructor" << endl; } EulerSolver2D::MainData2D::~MainData2D() { printf("destruct MainData2D"); // seg faults.. delete [] node; //ok delete [] elm; //ok delete [] edge; //ok delete [] bound; //ok // delete [] face; //sf never allocated // invalid pointers // delete node; // delete elm; // delete edge; // delete bound; // delete face; } // EulerSolver2D::Solver::Solver(){} // EulerSolver2D::Solver::~Solver(){ // printf("destruct Solver"); // } // //******************************************************************************** // //******************************************************************************** // //******************************************************************************** // //* Euler solver: Node-Centered Finite-Volume Method (Edge-Based) // //* // //* - Node-centered finite-volume method for unstructured grids(quad/tri/mixed) // //* - Roe flux with an entropy fix and Rotated-RHLL flux // //* - Reconstruction by unweighted least-squares method (2x2 system for gradients) // //* - Van Albada slope limiter to the primitive variable gradients // //* - 2-Stage Runge-Kutta time-stepping // //* // //******************************************************************************** // void EulerSolver2D::Solver::euler_solver_main(){ // } // //******************************************************************************** // // End of program // //******************************************************************************** //namespace EulerSolver2D{ void program_2D_euler_rk2(){ // procedural fortran ends up in this function int i; // euler solver 2D: EulerSolver2D::Solver E2Dsolver; //Set file names, Inout data files std::string datafile_grid_in = "project.grid"; //Grid file std::string datafile_bcmap_in = "project.bcmap"; //Boundary condition file std::string datafile_tec = "project_tecplot.dat"; //Tecplot file for viewing the result. //-------------------------------------------------------------------------------- // Input Parameters // euler main data: //typedef EulerSolver2D::EulerSolver2D 2Ddata; EulerSolver2D::MainData2D E2Ddata; //2Ddata = new EulerSolver2D(); E2Ddata.M_inf = 0.0; // Freestream Mach number to be set in the function // -> "initial_solution_shock_diffraction" // (Specify M_inf here for other problems.) E2Ddata.gamma = 1.4; // Ratio of specific heats E2Ddata.CFL = 0.95; // CFL number E2Ddata.t_final = 0.18; // Final time to stop the calculation. E2Ddata.time_step_max = 5000; // Max time steps (just a big enough number) E2Ddata.inviscid_flux = "rhll"; // = Rotated-RHLL , "roe" = Roe flux E2Ddata.limiter_type = "vanalbada"; // = Van Albada limiter, "none" = No limiter E2Ddata.nq = 4; // The number of equtaions/variables in the target equtaion. E2Ddata.gradient_type = "linear"; // or "quadratic2 for a quadratic LSQ. E2Ddata.gradient_weight = "none"; // or "inverse_distance" E2Ddata.gradient_weight_p = EulerSolver2D::one; // or any other real value //-------------------------------------------------------------------------------- // Solve the Euler equations and write the output datafile. // // // (1) Read grid files E2Ddata.read_grid(datafile_grid_in, datafile_bcmap_in); std::cout << "Allocate arrays" << std::endl; std::cout << "there are " << E2Ddata.nnodes << " nodes " << std::endl; for (size_t i = 0; i < E2Ddata.nnodes; i++) { E2Ddata.node[i].u = new Array2D<real>(E2Ddata.nq,1); E2Ddata.node[i].du = new Array2D<real>(E2Ddata.nq,1); E2Ddata.node[i].w = new Array2D<real>(E2Ddata.nq,1); E2Ddata.node[i].gradw = new Array2D<real>(E2Ddata.nq,2); //<- 2: x and y components. E2Ddata.node[i].res = new Array2D<real>(E2Ddata.nq,1); } std::cout << "E2Ddata.nq, = " << E2Ddata.nq << std::endl; // (2) Construct grid data E2Ddata.construct_grid_data(); // (3) Check the grid data (It is always good to check them before use//) E2Ddata.check_grid_data(); cout << "now in program_2D_euler_rk2" << endl; E2Ddata.write_tecplot_file(E2Ddata.datafile_tria_tec); E2Ddata.write_grid_file(E2Ddata.datafile_tria); // (4) Prepare LSQ gradients E2Dsolver.compute_lsq_coeff_nc(E2Ddata); E2Dsolver.check_lsq_coeff_nc(E2Ddata); // (5) Set initial solution for a shock diffraction problem // (Re-write or replace it by your own subroutine for other problems.) E2Dsolver.initial_solution_shock_diffraction(E2Ddata); // (6) Compute the solution (March in time to the final time) E2Dsolver.euler_solver_main(E2Ddata); // // (7) Write out the tecplot data file (Solutions at nodes) // write_tecplot_file(datafile_tec); } void EulerSolver2D::driverEuler2D(){ program_2D_euler_rk2(); //solver.output(); return; } //} //end namespace EulerSolver2D
39.962099
105
0.545561
[ "mesh", "vector" ]
6690aad022b8756b285b6d5e99464f5e8fc5e2a6
809
cpp
C++
medium/0120minimumTotal.cpp
wanghengg/LeetCode
4f73d7e176c8de5d2d9b87ab2812f7aa80c20a79
[ "Apache-2.0" ]
null
null
null
medium/0120minimumTotal.cpp
wanghengg/LeetCode
4f73d7e176c8de5d2d9b87ab2812f7aa80c20a79
[ "Apache-2.0" ]
null
null
null
medium/0120minimumTotal.cpp
wanghengg/LeetCode
4f73d7e176c8de5d2d9b87ab2812f7aa80c20a79
[ "Apache-2.0" ]
null
null
null
// // Created by wangheng on 2021/6/10. // #include <bits/stdc++.h> using namespace std; class Solution{ public: int minimumTotal(vector<vector<int>>& triangle) { int m = triangle.size(); // int n = triangle.end()->size(); int result = triangle[0][0]; int curPosition = 0; for (int i = 1; i < m; ++i) { if (triangle[i][curPosition] < triangle[i][curPosition+1]) { result += triangle[i][curPosition]; } else { result += triangle[i][curPosition+1]; curPosition += 1; } } return result; } }; int main() { vector<vector<int>> triangle{{2}, {3,4}, {6,5,7}, {4,1,8,3}}; Solution solution; cout << solution.minimumTotal(triangle) << endl; return 0; }
25.28125
72
0.517923
[ "vector" ]
6695e0718fdc17b31e625ae30872573fcca9d3dc
7,361
cpp
C++
tests/LoggerTests.cpp
Andreone/logpp
16fe38e6426803478ca462b84b6752381097ebfc
[ "MIT" ]
null
null
null
tests/LoggerTests.cpp
Andreone/logpp
16fe38e6426803478ca462b84b6752381097ebfc
[ "MIT" ]
null
null
null
tests/LoggerTests.cpp
Andreone/logpp
16fe38e6426803478ca462b84b6752381097ebfc
[ "MIT" ]
null
null
null
#include "logpp/core/LogFieldVisitor.h" #include "logpp/core/Logger.h" #include "logpp/core/Ostream.h" #include "logpp/sinks/Sink.h" #include "logpp/utils/detect.h" #include "gtest/gtest.h" using namespace logpp; struct Field { virtual ~Field() = default; explicit Field(std::string key) : key(std::move(key)) { } std::string key; }; template <typename T> struct TypedField : Field { TypedField(std::string key, T value) : Field(std::move(key)) , value(std::move(value)) { } T value; }; template <> struct TypedField<std::string_view> : Field { TypedField(std::string key, std::string_view value) : Field(std::move(key)) , value(std::string(value)) { } std::string value; }; struct LogEntry { LogEntry(std::string name, LogLevel level, std::string text, std::vector<std::shared_ptr<Field>> fields) : name(std::move(name)) , level(level) , text(std::move(text)) , fields(std::move(fields)) { } std::string name; LogLevel level; std::string text; std::vector<std::shared_ptr<Field>> fields; template <typename T> std::vector<std::shared_ptr<TypedField<T>>> findFields() const { std::vector<std::shared_ptr<TypedField<T>>> res; for (const auto& field : fields) { if (auto typedField = std::dynamic_pointer_cast<TypedField<T>>(field); typedField != nullptr) res.push_back(typedField); } return res; } template <typename T> std::shared_ptr<TypedField<T>> findField(std::string_view key) const { for (const auto& field : fields) { if (field->key != key) continue; if (auto typedField = std::dynamic_pointer_cast<TypedField<T>>(field); typedField != nullptr) return typedField; } return nullptr; } }; class MemorySink : public sink::Sink { public: void activateOptions(const sink::Options&) override { } void sink(std::string_view name, LogLevel level, const EventLogBuffer& buffer) override { fmt::memory_buffer textBuf; buffer.formatText(textBuf); Visitor visitor; buffer.visitFields(visitor); m_entries.emplace_back(std::string(name), level, std::string(textBuf.data(), textBuf.size()), visitor.fields()); } const LogEntry* findEntry(std::string_view text, LogLevel level) const { auto entryIt = std::find_if( std::begin(m_entries), std::end(m_entries), [&](const auto& entry) { return entry.text == text && entry.level == level; }); if (entryIt == std::end(m_entries)) return nullptr; return &*entryIt; } private: class Visitor : public LogFieldVisitor { public: void visitStart(size_t count) override { m_fields.reserve(count); } #define DEFINE_VISIT(ValueType) \ void visit(std::string_view key, ValueType value) override \ { \ onField(key, value); \ } DEFINE_VISIT(std::string_view) DEFINE_VISIT(uint8_t) DEFINE_VISIT(uint16_t) DEFINE_VISIT(uint32_t) DEFINE_VISIT(uint64_t) DEFINE_VISIT(int8_t) DEFINE_VISIT(int16_t) DEFINE_VISIT(int32_t) DEFINE_VISIT(int64_t) DEFINE_VISIT(bool) DEFINE_VISIT(float) DEFINE_VISIT(double) #undef DEFINE_VISIT void visitEnd() override { } template <typename T> void onField(std::string_view key, const T& value) { m_fields.push_back(std::make_shared<TypedField<T>>(std::string(key), value)); } std::vector<std::shared_ptr<Field>> fields() const { return m_fields; } private: std::vector<std::shared_ptr<Field>> m_fields; }; std::vector<LogEntry> m_entries; }; struct LoggerTest : public ::testing::Test { void SetUp() override { sink = std::make_shared<MemorySink>(); logger = createLogger("LoggerTest", LogLevel::Debug); } std::shared_ptr<Logger> createLogger(std::string name, LogLevel level) const { return std::make_shared<Logger>(std::move(name), level, sink); } const LogEntry* findEntry(std::string_view text, LogLevel level) const { return sink->findEntry(text, level); } const LogEntry* checkEntry(std::string_view text, LogLevel level) const { auto* entry = sink->findEntry(text, level); EXPECT_NE(entry, nullptr); return entry; } template <typename T> std::shared_ptr<TypedField<T>> checkField(const LogEntry* entry, std::string_view key, T value) { auto field = entry->findField<T>(key); EXPECT_NE(field, nullptr); EXPECT_EQ(field->key, key); EXPECT_EQ(field->value, value); return field; } std::shared_ptr<MemorySink> sink; std::shared_ptr<Logger> logger; }; TEST_F(LoggerTest, should_log_message_depending_on_log_level) { auto logger = createLogger("LoggerTest", LogLevel::Info); struct TestData { const char* message; LogLevel level; bool shouldBeLogged; } testData[] = { { "This is a trace message", LogLevel::Trace, false }, { "This is a debug message", LogLevel::Debug, false }, { "This is an info message", LogLevel::Info, true }, { "This is a warning message", LogLevel::Warning, true }, { "This is an error message", LogLevel::Error, true } }; for (const auto& data : testData) { logger->log(data.message, data.level); auto* entry = findEntry(data.message, data.level); if (data.shouldBeLogged && !entry) FAIL() << "Message SHOULD have been logged"; if (!data.shouldBeLogged && entry) FAIL() << "Message SHOULD NOT have been logged"; } } TEST_F(LoggerTest, should_log_message_with_fields) { logger->info("Test message", logpp::field("status_code", uint32_t(0xBAD)), logpp::field("status_text", std::string("BAD"))); auto* entry = checkEntry("Test message", LogLevel::Info); checkField(entry, "status_code", uint32_t(0xBAD)); checkField(entry, "status_text", std::string_view("BAD")); ASSERT_EQ(entry->findField<uint16_t>("status_code"), nullptr); } struct TestId { explicit TestId(std::string name, uint32_t id) : name(std::move(name)) , id(id) { } std::string name; uint32_t id; }; std::ostream& operator<<(std::ostream& os, const TestId& id) { os << id.name; os << ':'; os << id.id; return os; } TEST_F(LoggerTest, should_log_message_with_custom_streamable_fields) { TestId id("LoggerTest.should_log_message_with_custom_streamable_fields", 0xABC); logger->info("Test message", logpp::field("test_id", id)); auto* entry = checkEntry("Test message", LogLevel::Info); std::ostringstream oss; oss << id; checkField(entry, "test_id", std::string_view(oss.str())); }
25.295533
120
0.591903
[ "vector" ]
66973779e80bb20957de1144a77b9a94adaa6e12
4,716
cpp
C++
PlanetRendering/SolarSystem.cpp
Gooseguy/PlanetRendering2
2c148f47de6df3d0a0055233f0254218b3b3b677
[ "MIT" ]
15
2017-09-23T22:57:31.000Z
2020-12-19T20:31:06.000Z
PlanetRendering/SolarSystem.cpp
christiancosgrove/PlanetRendering2
2c148f47de6df3d0a0055233f0254218b3b3b677
[ "MIT" ]
1
2015-02-27T00:30:30.000Z
2015-02-27T00:30:30.000Z
PlanetRendering/SolarSystem.cpp
Gooseguy/PlanetRendering2
2c148f47de6df3d0a0055233f0254218b3b3b677
[ "MIT" ]
4
2017-09-27T08:09:53.000Z
2021-01-15T09:40:12.000Z
// // SolarSystem.cpp // PlanetRendering // // Created by Christian Cosgrove on 10/23/14. // Copyright (c) 2014 Christian. All rights reserved. // #include "SolarSystem.h" #include "RandomUtils.h" #include "glm/gtc/type_ptr.hpp" SolarSystem::SolarSystem(Player& _player, GLManager& _glManager, int windowWidth, int windowHeight, const std::string& resourcePath) : player(_player), glManager(_glManager), particleSystem(0), PhysicalSystem(8.,0.001, resourcePath), planets{ new Planet(0,glm::vec3(0,-2,0), 1, 100, RandomUtils::Uniform<vfloat>(-15,25), _player, _glManager, 0.3 + 0*RandomUtils::Uniform<float>(0.05f, 0.8f)), new Planet(1,glm::vec3(0,2, 0), 1, 100, RandomUtils::Uniform<vfloat>(-25,25), _player, _glManager, 0.3 + 0*RandomUtils::Uniform<float>(0.05f, 0.8f)), new Planet(2,glm::vec3(0,20,0), 1, 100, RandomUtils::Uniform<vfloat>(-10,10), _player, _glManager, 0.3 + 0*RandomUtils::Uniform<float>(0.05f, 0.8f))} { #ifdef POSTPROCESSING generateRenderTexture(windowWidth,windowHeight); #endif particleSystem.AppendParticles(objects); for (auto& p : planets) { objects.push_back(p); } planets[0]->Velocity=glm::dvec3(0,0,10); planets[1]->Velocity=glm::dvec3(0,0,-10); planets[2]->Velocity=glm::dvec3(10,0,0); objects.push_back(&player); } void SolarSystem::Update() { PhysicalSystem::Update(); particleSystem.Update(TimeStep); for (Planet* p:planets) { for (PhysicsObject* obj:objects) { if (p==obj || obj==nullptr) continue; p->CheckCollision(obj); } } } void SolarSystem::Draw(int windowWidth, int windowHeight) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glManager.Programs[3].Use(); glManager.Programs[3].SetMatrix4("transformMatrix", glm::value_ptr(player.Camera.GetTransformMatrix())); particleSystem.Draw(); glManager.Programs[0].Use(); #ifdef POSTPROCESSING glBindFramebuffer(GL_FRAMEBUFFER, framebuffer); glViewport(0,0,windowWidth,windowHeight); #endif for (auto p : planets) p->Draw(); #ifdef POSTPROCESSING glBindFramebuffer(GL_FRAMEBUFFER, 0); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glManager.Programs[2].Use(); glBindVertexArray(screenVAO); glDrawArrays(GL_TRIANGLES, 0, 6); glBindVertexArray(0); #endif } SolarSystem::~SolarSystem() { glDeleteFramebuffers(1, &framebuffer); for (auto& p : planets) delete p; } void SolarSystem::addPlanet(Planet *p) { planets.push_back(p); objects.push_back(p); } static const GLfloat g_quad_vertex_buffer_data[] = { -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, }; void SolarSystem::generateRenderTexture(int windowWidth, int windowHeight) { glGenFramebuffers(1, &framebuffer); glBindFramebuffer(GL_FRAMEBUFFER, framebuffer); GLuint texture; GLuint renderBuffer; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, windowWidth,windowHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, texture, 0); glGenRenderbuffers(1, &renderBuffer); glBindRenderbuffer(GL_RENDERBUFFER, renderBuffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, windowWidth,windowHeight); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, renderBuffer); glBindFramebuffer(GL_FRAMEBUFFER, 0); texLocation = glGetUniformLocation( glManager.Programs[2].programID, "renderedTexture"); glGenVertexArrays(1, &screenVAO); glBindVertexArray(screenVAO); glGenBuffers(1, &screenVBO); glBindBuffer(GL_ARRAY_BUFFER, screenVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(g_quad_vertex_buffer_data), g_quad_vertex_buffer_data, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_TRUE, 0, (void*)0); glBindVertexArray(0); glManager.Programs[2].Use(); glManager.Programs[2].SetTexture("renderedTexture", 0); glManager.Programs[2].SetVector2("resolution", glm::vec2(windowWidth,windowHeight)); glUseProgram(0); } void SolarSystem::NextRenderMode() { if (currentRenderMode==Planet::RenderMode::WIRE) currentRenderMode=Planet::RenderMode::SOLID; else currentRenderMode=Planet::RenderMode::WIRE; for (Planet* p : planets) { p->CurrentRenderMode=currentRenderMode; } }
34.173913
193
0.702502
[ "solid" ]
669bb150061758b89dca42e9bb4402ff2d282206
727,197
hpp
C++
adb-20190315/include/alibabacloud/adb_20190315.hpp
aliyun/alibabacloud-cpp-sdk
0e7c0576abcd4ef1aef07d714b92654deb713c36
[ "Apache-2.0" ]
5
2021-02-01T03:20:23.000Z
2022-01-28T02:13:49.000Z
adb-20190315/include/alibabacloud/adb_20190315.hpp
aliyun/alibabacloud-cpp-sdk
0e7c0576abcd4ef1aef07d714b92654deb713c36
[ "Apache-2.0" ]
4
2021-05-03T08:34:12.000Z
2022-01-28T02:13:33.000Z
adb-20190315/include/alibabacloud/adb_20190315.hpp
aliyun/alibabacloud-cpp-sdk
0e7c0576abcd4ef1aef07d714b92654deb713c36
[ "Apache-2.0" ]
5
2021-04-02T02:59:04.000Z
2022-02-24T02:33:44.000Z
// This file is auto-generated, don't edit it. Thanks. #ifndef ALIBABACLOUD_ADB20190315_H_ #define ALIBABACLOUD_ADB20190315_H_ #include <alibabacloud/open_api.hpp> #include <boost/throw_exception.hpp> #include <darabonba/core.hpp> #include <darabonba/util.hpp> #include <iostream> #include <map> #include <vector> using namespace std; namespace Alibabacloud_Adb20190315 { class AllocateClusterPublicConnectionRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> connectionStringPrefix{}; AllocateClusterPublicConnectionRequest() {} explicit AllocateClusterPublicConnectionRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (connectionStringPrefix) { res["ConnectionStringPrefix"] = boost::any(*connectionStringPrefix); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("ConnectionStringPrefix") != m.end() && !m["ConnectionStringPrefix"].empty()) { connectionStringPrefix = make_shared<string>(boost::any_cast<string>(m["ConnectionStringPrefix"])); } } virtual ~AllocateClusterPublicConnectionRequest() = default; }; class AllocateClusterPublicConnectionResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; AllocateClusterPublicConnectionResponseBody() {} explicit AllocateClusterPublicConnectionResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~AllocateClusterPublicConnectionResponseBody() = default; }; class AllocateClusterPublicConnectionResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<AllocateClusterPublicConnectionResponseBody> body{}; AllocateClusterPublicConnectionResponse() {} explicit AllocateClusterPublicConnectionResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { AllocateClusterPublicConnectionResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<AllocateClusterPublicConnectionResponseBody>(model1); } } } virtual ~AllocateClusterPublicConnectionResponse() = default; }; class BindDBResourcePoolWithUserRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> poolName{}; shared_ptr<string> poolUser{}; BindDBResourcePoolWithUserRequest() {} explicit BindDBResourcePoolWithUserRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (poolName) { res["PoolName"] = boost::any(*poolName); } if (poolUser) { res["PoolUser"] = boost::any(*poolUser); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("PoolName") != m.end() && !m["PoolName"].empty()) { poolName = make_shared<string>(boost::any_cast<string>(m["PoolName"])); } if (m.find("PoolUser") != m.end() && !m["PoolUser"].empty()) { poolUser = make_shared<string>(boost::any_cast<string>(m["PoolUser"])); } } virtual ~BindDBResourcePoolWithUserRequest() = default; }; class BindDBResourcePoolWithUserResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; BindDBResourcePoolWithUserResponseBody() {} explicit BindDBResourcePoolWithUserResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~BindDBResourcePoolWithUserResponseBody() = default; }; class BindDBResourcePoolWithUserResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<BindDBResourcePoolWithUserResponseBody> body{}; BindDBResourcePoolWithUserResponse() {} explicit BindDBResourcePoolWithUserResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { BindDBResourcePoolWithUserResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<BindDBResourcePoolWithUserResponseBody>(model1); } } } virtual ~BindDBResourcePoolWithUserResponse() = default; }; class CreateAccountRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> accountName{}; shared_ptr<string> accountPassword{}; shared_ptr<string> accountDescription{}; shared_ptr<string> accountType{}; CreateAccountRequest() {} explicit CreateAccountRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (accountName) { res["AccountName"] = boost::any(*accountName); } if (accountPassword) { res["AccountPassword"] = boost::any(*accountPassword); } if (accountDescription) { res["AccountDescription"] = boost::any(*accountDescription); } if (accountType) { res["AccountType"] = boost::any(*accountType); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("AccountName") != m.end() && !m["AccountName"].empty()) { accountName = make_shared<string>(boost::any_cast<string>(m["AccountName"])); } if (m.find("AccountPassword") != m.end() && !m["AccountPassword"].empty()) { accountPassword = make_shared<string>(boost::any_cast<string>(m["AccountPassword"])); } if (m.find("AccountDescription") != m.end() && !m["AccountDescription"].empty()) { accountDescription = make_shared<string>(boost::any_cast<string>(m["AccountDescription"])); } if (m.find("AccountType") != m.end() && !m["AccountType"].empty()) { accountType = make_shared<string>(boost::any_cast<string>(m["AccountType"])); } } virtual ~CreateAccountRequest() = default; }; class CreateAccountResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; shared_ptr<string> DBClusterId{}; shared_ptr<long> taskId{}; CreateAccountResponseBody() {} explicit CreateAccountResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (taskId) { res["TaskId"] = boost::any(*taskId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("TaskId") != m.end() && !m["TaskId"].empty()) { taskId = make_shared<long>(boost::any_cast<long>(m["TaskId"])); } } virtual ~CreateAccountResponseBody() = default; }; class CreateAccountResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<CreateAccountResponseBody> body{}; CreateAccountResponse() {} explicit CreateAccountResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { CreateAccountResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<CreateAccountResponseBody>(model1); } } } virtual ~CreateAccountResponse() = default; }; class CreateDBClusterRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> regionId{}; shared_ptr<string> zoneId{}; shared_ptr<string> DBClusterVersion{}; shared_ptr<string> DBClusterCategory{}; shared_ptr<string> DBClusterClass{}; shared_ptr<string> DBNodeGroupCount{}; shared_ptr<string> DBNodeStorage{}; shared_ptr<string> DBClusterNetworkType{}; shared_ptr<string> DBClusterDescription{}; shared_ptr<string> payType{}; shared_ptr<string> period{}; shared_ptr<string> usedTime{}; shared_ptr<string> VPCId{}; shared_ptr<string> vSwitchId{}; shared_ptr<string> clientToken{}; shared_ptr<string> executorCount{}; shared_ptr<string> resourceGroupId{}; shared_ptr<string> mode{}; shared_ptr<string> storageResource{}; shared_ptr<string> storageType{}; shared_ptr<string> computeResource{}; shared_ptr<string> restoreType{}; shared_ptr<string> sourceDBInstanceName{}; shared_ptr<string> backupSetID{}; shared_ptr<string> restoreTime{}; shared_ptr<string> elasticIOResource{}; CreateDBClusterRequest() {} explicit CreateDBClusterRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (regionId) { res["RegionId"] = boost::any(*regionId); } if (zoneId) { res["ZoneId"] = boost::any(*zoneId); } if (DBClusterVersion) { res["DBClusterVersion"] = boost::any(*DBClusterVersion); } if (DBClusterCategory) { res["DBClusterCategory"] = boost::any(*DBClusterCategory); } if (DBClusterClass) { res["DBClusterClass"] = boost::any(*DBClusterClass); } if (DBNodeGroupCount) { res["DBNodeGroupCount"] = boost::any(*DBNodeGroupCount); } if (DBNodeStorage) { res["DBNodeStorage"] = boost::any(*DBNodeStorage); } if (DBClusterNetworkType) { res["DBClusterNetworkType"] = boost::any(*DBClusterNetworkType); } if (DBClusterDescription) { res["DBClusterDescription"] = boost::any(*DBClusterDescription); } if (payType) { res["PayType"] = boost::any(*payType); } if (period) { res["Period"] = boost::any(*period); } if (usedTime) { res["UsedTime"] = boost::any(*usedTime); } if (VPCId) { res["VPCId"] = boost::any(*VPCId); } if (vSwitchId) { res["VSwitchId"] = boost::any(*vSwitchId); } if (clientToken) { res["ClientToken"] = boost::any(*clientToken); } if (executorCount) { res["ExecutorCount"] = boost::any(*executorCount); } if (resourceGroupId) { res["ResourceGroupId"] = boost::any(*resourceGroupId); } if (mode) { res["Mode"] = boost::any(*mode); } if (storageResource) { res["StorageResource"] = boost::any(*storageResource); } if (storageType) { res["StorageType"] = boost::any(*storageType); } if (computeResource) { res["ComputeResource"] = boost::any(*computeResource); } if (restoreType) { res["RestoreType"] = boost::any(*restoreType); } if (sourceDBInstanceName) { res["SourceDBInstanceName"] = boost::any(*sourceDBInstanceName); } if (backupSetID) { res["BackupSetID"] = boost::any(*backupSetID); } if (restoreTime) { res["RestoreTime"] = boost::any(*restoreTime); } if (elasticIOResource) { res["ElasticIOResource"] = boost::any(*elasticIOResource); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("RegionId") != m.end() && !m["RegionId"].empty()) { regionId = make_shared<string>(boost::any_cast<string>(m["RegionId"])); } if (m.find("ZoneId") != m.end() && !m["ZoneId"].empty()) { zoneId = make_shared<string>(boost::any_cast<string>(m["ZoneId"])); } if (m.find("DBClusterVersion") != m.end() && !m["DBClusterVersion"].empty()) { DBClusterVersion = make_shared<string>(boost::any_cast<string>(m["DBClusterVersion"])); } if (m.find("DBClusterCategory") != m.end() && !m["DBClusterCategory"].empty()) { DBClusterCategory = make_shared<string>(boost::any_cast<string>(m["DBClusterCategory"])); } if (m.find("DBClusterClass") != m.end() && !m["DBClusterClass"].empty()) { DBClusterClass = make_shared<string>(boost::any_cast<string>(m["DBClusterClass"])); } if (m.find("DBNodeGroupCount") != m.end() && !m["DBNodeGroupCount"].empty()) { DBNodeGroupCount = make_shared<string>(boost::any_cast<string>(m["DBNodeGroupCount"])); } if (m.find("DBNodeStorage") != m.end() && !m["DBNodeStorage"].empty()) { DBNodeStorage = make_shared<string>(boost::any_cast<string>(m["DBNodeStorage"])); } if (m.find("DBClusterNetworkType") != m.end() && !m["DBClusterNetworkType"].empty()) { DBClusterNetworkType = make_shared<string>(boost::any_cast<string>(m["DBClusterNetworkType"])); } if (m.find("DBClusterDescription") != m.end() && !m["DBClusterDescription"].empty()) { DBClusterDescription = make_shared<string>(boost::any_cast<string>(m["DBClusterDescription"])); } if (m.find("PayType") != m.end() && !m["PayType"].empty()) { payType = make_shared<string>(boost::any_cast<string>(m["PayType"])); } if (m.find("Period") != m.end() && !m["Period"].empty()) { period = make_shared<string>(boost::any_cast<string>(m["Period"])); } if (m.find("UsedTime") != m.end() && !m["UsedTime"].empty()) { usedTime = make_shared<string>(boost::any_cast<string>(m["UsedTime"])); } if (m.find("VPCId") != m.end() && !m["VPCId"].empty()) { VPCId = make_shared<string>(boost::any_cast<string>(m["VPCId"])); } if (m.find("VSwitchId") != m.end() && !m["VSwitchId"].empty()) { vSwitchId = make_shared<string>(boost::any_cast<string>(m["VSwitchId"])); } if (m.find("ClientToken") != m.end() && !m["ClientToken"].empty()) { clientToken = make_shared<string>(boost::any_cast<string>(m["ClientToken"])); } if (m.find("ExecutorCount") != m.end() && !m["ExecutorCount"].empty()) { executorCount = make_shared<string>(boost::any_cast<string>(m["ExecutorCount"])); } if (m.find("ResourceGroupId") != m.end() && !m["ResourceGroupId"].empty()) { resourceGroupId = make_shared<string>(boost::any_cast<string>(m["ResourceGroupId"])); } if (m.find("Mode") != m.end() && !m["Mode"].empty()) { mode = make_shared<string>(boost::any_cast<string>(m["Mode"])); } if (m.find("StorageResource") != m.end() && !m["StorageResource"].empty()) { storageResource = make_shared<string>(boost::any_cast<string>(m["StorageResource"])); } if (m.find("StorageType") != m.end() && !m["StorageType"].empty()) { storageType = make_shared<string>(boost::any_cast<string>(m["StorageType"])); } if (m.find("ComputeResource") != m.end() && !m["ComputeResource"].empty()) { computeResource = make_shared<string>(boost::any_cast<string>(m["ComputeResource"])); } if (m.find("RestoreType") != m.end() && !m["RestoreType"].empty()) { restoreType = make_shared<string>(boost::any_cast<string>(m["RestoreType"])); } if (m.find("SourceDBInstanceName") != m.end() && !m["SourceDBInstanceName"].empty()) { sourceDBInstanceName = make_shared<string>(boost::any_cast<string>(m["SourceDBInstanceName"])); } if (m.find("BackupSetID") != m.end() && !m["BackupSetID"].empty()) { backupSetID = make_shared<string>(boost::any_cast<string>(m["BackupSetID"])); } if (m.find("RestoreTime") != m.end() && !m["RestoreTime"].empty()) { restoreTime = make_shared<string>(boost::any_cast<string>(m["RestoreTime"])); } if (m.find("ElasticIOResource") != m.end() && !m["ElasticIOResource"].empty()) { elasticIOResource = make_shared<string>(boost::any_cast<string>(m["ElasticIOResource"])); } } virtual ~CreateDBClusterRequest() = default; }; class CreateDBClusterResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; shared_ptr<string> resourceGroupId{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> orderId{}; CreateDBClusterResponseBody() {} explicit CreateDBClusterResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } if (resourceGroupId) { res["ResourceGroupId"] = boost::any(*resourceGroupId); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (orderId) { res["OrderId"] = boost::any(*orderId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("ResourceGroupId") != m.end() && !m["ResourceGroupId"].empty()) { resourceGroupId = make_shared<string>(boost::any_cast<string>(m["ResourceGroupId"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("OrderId") != m.end() && !m["OrderId"].empty()) { orderId = make_shared<string>(boost::any_cast<string>(m["OrderId"])); } } virtual ~CreateDBClusterResponseBody() = default; }; class CreateDBClusterResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<CreateDBClusterResponseBody> body{}; CreateDBClusterResponse() {} explicit CreateDBClusterResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { CreateDBClusterResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<CreateDBClusterResponseBody>(model1); } } } virtual ~CreateDBClusterResponse() = default; }; class CreateDBResourcePoolRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> poolName{}; shared_ptr<string> queryType{}; shared_ptr<long> nodeNum{}; CreateDBResourcePoolRequest() {} explicit CreateDBResourcePoolRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (poolName) { res["PoolName"] = boost::any(*poolName); } if (queryType) { res["QueryType"] = boost::any(*queryType); } if (nodeNum) { res["NodeNum"] = boost::any(*nodeNum); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("PoolName") != m.end() && !m["PoolName"].empty()) { poolName = make_shared<string>(boost::any_cast<string>(m["PoolName"])); } if (m.find("QueryType") != m.end() && !m["QueryType"].empty()) { queryType = make_shared<string>(boost::any_cast<string>(m["QueryType"])); } if (m.find("NodeNum") != m.end() && !m["NodeNum"].empty()) { nodeNum = make_shared<long>(boost::any_cast<long>(m["NodeNum"])); } } virtual ~CreateDBResourcePoolRequest() = default; }; class CreateDBResourcePoolResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; CreateDBResourcePoolResponseBody() {} explicit CreateDBResourcePoolResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~CreateDBResourcePoolResponseBody() = default; }; class CreateDBResourcePoolResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<CreateDBResourcePoolResponseBody> body{}; CreateDBResourcePoolResponse() {} explicit CreateDBResourcePoolResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { CreateDBResourcePoolResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<CreateDBResourcePoolResponseBody>(model1); } } } virtual ~CreateDBResourcePoolResponse() = default; }; class CreateElasticPlanRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> elasticPlanName{}; shared_ptr<string> resourcePoolName{}; shared_ptr<long> elasticPlanNodeNum{}; shared_ptr<string> elasticPlanTimeStart{}; shared_ptr<string> elasticPlanTimeEnd{}; shared_ptr<string> elasticPlanWeeklyRepeat{}; shared_ptr<string> elasticPlanStartDay{}; shared_ptr<string> elasticPlanEndDay{}; shared_ptr<bool> elasticPlanEnable{}; CreateElasticPlanRequest() {} explicit CreateElasticPlanRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (elasticPlanName) { res["ElasticPlanName"] = boost::any(*elasticPlanName); } if (resourcePoolName) { res["ResourcePoolName"] = boost::any(*resourcePoolName); } if (elasticPlanNodeNum) { res["ElasticPlanNodeNum"] = boost::any(*elasticPlanNodeNum); } if (elasticPlanTimeStart) { res["ElasticPlanTimeStart"] = boost::any(*elasticPlanTimeStart); } if (elasticPlanTimeEnd) { res["ElasticPlanTimeEnd"] = boost::any(*elasticPlanTimeEnd); } if (elasticPlanWeeklyRepeat) { res["ElasticPlanWeeklyRepeat"] = boost::any(*elasticPlanWeeklyRepeat); } if (elasticPlanStartDay) { res["ElasticPlanStartDay"] = boost::any(*elasticPlanStartDay); } if (elasticPlanEndDay) { res["ElasticPlanEndDay"] = boost::any(*elasticPlanEndDay); } if (elasticPlanEnable) { res["ElasticPlanEnable"] = boost::any(*elasticPlanEnable); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("ElasticPlanName") != m.end() && !m["ElasticPlanName"].empty()) { elasticPlanName = make_shared<string>(boost::any_cast<string>(m["ElasticPlanName"])); } if (m.find("ResourcePoolName") != m.end() && !m["ResourcePoolName"].empty()) { resourcePoolName = make_shared<string>(boost::any_cast<string>(m["ResourcePoolName"])); } if (m.find("ElasticPlanNodeNum") != m.end() && !m["ElasticPlanNodeNum"].empty()) { elasticPlanNodeNum = make_shared<long>(boost::any_cast<long>(m["ElasticPlanNodeNum"])); } if (m.find("ElasticPlanTimeStart") != m.end() && !m["ElasticPlanTimeStart"].empty()) { elasticPlanTimeStart = make_shared<string>(boost::any_cast<string>(m["ElasticPlanTimeStart"])); } if (m.find("ElasticPlanTimeEnd") != m.end() && !m["ElasticPlanTimeEnd"].empty()) { elasticPlanTimeEnd = make_shared<string>(boost::any_cast<string>(m["ElasticPlanTimeEnd"])); } if (m.find("ElasticPlanWeeklyRepeat") != m.end() && !m["ElasticPlanWeeklyRepeat"].empty()) { elasticPlanWeeklyRepeat = make_shared<string>(boost::any_cast<string>(m["ElasticPlanWeeklyRepeat"])); } if (m.find("ElasticPlanStartDay") != m.end() && !m["ElasticPlanStartDay"].empty()) { elasticPlanStartDay = make_shared<string>(boost::any_cast<string>(m["ElasticPlanStartDay"])); } if (m.find("ElasticPlanEndDay") != m.end() && !m["ElasticPlanEndDay"].empty()) { elasticPlanEndDay = make_shared<string>(boost::any_cast<string>(m["ElasticPlanEndDay"])); } if (m.find("ElasticPlanEnable") != m.end() && !m["ElasticPlanEnable"].empty()) { elasticPlanEnable = make_shared<bool>(boost::any_cast<bool>(m["ElasticPlanEnable"])); } } virtual ~CreateElasticPlanRequest() = default; }; class CreateElasticPlanResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; CreateElasticPlanResponseBody() {} explicit CreateElasticPlanResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~CreateElasticPlanResponseBody() = default; }; class CreateElasticPlanResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<CreateElasticPlanResponseBody> body{}; CreateElasticPlanResponse() {} explicit CreateElasticPlanResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { CreateElasticPlanResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<CreateElasticPlanResponseBody>(model1); } } } virtual ~CreateElasticPlanResponse() = default; }; class DeleteAccountRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> accountName{}; shared_ptr<string> accountType{}; DeleteAccountRequest() {} explicit DeleteAccountRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (accountName) { res["AccountName"] = boost::any(*accountName); } if (accountType) { res["AccountType"] = boost::any(*accountType); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("AccountName") != m.end() && !m["AccountName"].empty()) { accountName = make_shared<string>(boost::any_cast<string>(m["AccountName"])); } if (m.find("AccountType") != m.end() && !m["AccountType"].empty()) { accountType = make_shared<string>(boost::any_cast<string>(m["AccountType"])); } } virtual ~DeleteAccountRequest() = default; }; class DeleteAccountResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; DeleteAccountResponseBody() {} explicit DeleteAccountResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~DeleteAccountResponseBody() = default; }; class DeleteAccountResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DeleteAccountResponseBody> body{}; DeleteAccountResponse() {} explicit DeleteAccountResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DeleteAccountResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DeleteAccountResponseBody>(model1); } } } virtual ~DeleteAccountResponse() = default; }; class DeleteDBClusterRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; DeleteDBClusterRequest() {} explicit DeleteDBClusterRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } } virtual ~DeleteDBClusterRequest() = default; }; class DeleteDBClusterResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; shared_ptr<string> DBClusterId{}; shared_ptr<long> taskId{}; DeleteDBClusterResponseBody() {} explicit DeleteDBClusterResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (taskId) { res["TaskId"] = boost::any(*taskId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("TaskId") != m.end() && !m["TaskId"].empty()) { taskId = make_shared<long>(boost::any_cast<long>(m["TaskId"])); } } virtual ~DeleteDBClusterResponseBody() = default; }; class DeleteDBClusterResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DeleteDBClusterResponseBody> body{}; DeleteDBClusterResponse() {} explicit DeleteDBClusterResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DeleteDBClusterResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DeleteDBClusterResponseBody>(model1); } } } virtual ~DeleteDBClusterResponse() = default; }; class DeleteDBResourcePoolRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> poolName{}; DeleteDBResourcePoolRequest() {} explicit DeleteDBResourcePoolRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (poolName) { res["PoolName"] = boost::any(*poolName); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("PoolName") != m.end() && !m["PoolName"].empty()) { poolName = make_shared<string>(boost::any_cast<string>(m["PoolName"])); } } virtual ~DeleteDBResourcePoolRequest() = default; }; class DeleteDBResourcePoolResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; DeleteDBResourcePoolResponseBody() {} explicit DeleteDBResourcePoolResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~DeleteDBResourcePoolResponseBody() = default; }; class DeleteDBResourcePoolResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DeleteDBResourcePoolResponseBody> body{}; DeleteDBResourcePoolResponse() {} explicit DeleteDBResourcePoolResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DeleteDBResourcePoolResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DeleteDBResourcePoolResponseBody>(model1); } } } virtual ~DeleteDBResourcePoolResponse() = default; }; class DeleteElasticPlanRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> elasticPlanName{}; DeleteElasticPlanRequest() {} explicit DeleteElasticPlanRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (elasticPlanName) { res["ElasticPlanName"] = boost::any(*elasticPlanName); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("ElasticPlanName") != m.end() && !m["ElasticPlanName"].empty()) { elasticPlanName = make_shared<string>(boost::any_cast<string>(m["ElasticPlanName"])); } } virtual ~DeleteElasticPlanRequest() = default; }; class DeleteElasticPlanResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; DeleteElasticPlanResponseBody() {} explicit DeleteElasticPlanResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~DeleteElasticPlanResponseBody() = default; }; class DeleteElasticPlanResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DeleteElasticPlanResponseBody> body{}; DeleteElasticPlanResponse() {} explicit DeleteElasticPlanResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DeleteElasticPlanResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DeleteElasticPlanResponseBody>(model1); } } } virtual ~DeleteElasticPlanResponse() = default; }; class DescribeAccountsRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> accountName{}; shared_ptr<string> accountType{}; DescribeAccountsRequest() {} explicit DescribeAccountsRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (accountName) { res["AccountName"] = boost::any(*accountName); } if (accountType) { res["AccountType"] = boost::any(*accountType); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("AccountName") != m.end() && !m["AccountName"].empty()) { accountName = make_shared<string>(boost::any_cast<string>(m["AccountName"])); } if (m.find("AccountType") != m.end() && !m["AccountType"].empty()) { accountType = make_shared<string>(boost::any_cast<string>(m["AccountType"])); } } virtual ~DescribeAccountsRequest() = default; }; class DescribeAccountsResponseBodyAccountListDBAccount : public Darabonba::Model { public: shared_ptr<string> accountDescription{}; shared_ptr<string> accountType{}; shared_ptr<string> accountStatus{}; shared_ptr<string> accountName{}; DescribeAccountsResponseBodyAccountListDBAccount() {} explicit DescribeAccountsResponseBodyAccountListDBAccount(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (accountDescription) { res["AccountDescription"] = boost::any(*accountDescription); } if (accountType) { res["AccountType"] = boost::any(*accountType); } if (accountStatus) { res["AccountStatus"] = boost::any(*accountStatus); } if (accountName) { res["AccountName"] = boost::any(*accountName); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("AccountDescription") != m.end() && !m["AccountDescription"].empty()) { accountDescription = make_shared<string>(boost::any_cast<string>(m["AccountDescription"])); } if (m.find("AccountType") != m.end() && !m["AccountType"].empty()) { accountType = make_shared<string>(boost::any_cast<string>(m["AccountType"])); } if (m.find("AccountStatus") != m.end() && !m["AccountStatus"].empty()) { accountStatus = make_shared<string>(boost::any_cast<string>(m["AccountStatus"])); } if (m.find("AccountName") != m.end() && !m["AccountName"].empty()) { accountName = make_shared<string>(boost::any_cast<string>(m["AccountName"])); } } virtual ~DescribeAccountsResponseBodyAccountListDBAccount() = default; }; class DescribeAccountsResponseBodyAccountList : public Darabonba::Model { public: shared_ptr<vector<DescribeAccountsResponseBodyAccountListDBAccount>> DBAccount{}; DescribeAccountsResponseBodyAccountList() {} explicit DescribeAccountsResponseBodyAccountList(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (DBAccount) { vector<boost::any> temp1; for(auto item1:*DBAccount){ temp1.push_back(boost::any(item1.toMap())); } res["DBAccount"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("DBAccount") != m.end() && !m["DBAccount"].empty()) { if (typeid(vector<boost::any>) == m["DBAccount"].type()) { vector<DescribeAccountsResponseBodyAccountListDBAccount> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["DBAccount"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeAccountsResponseBodyAccountListDBAccount model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } DBAccount = make_shared<vector<DescribeAccountsResponseBodyAccountListDBAccount>>(expect1); } } } virtual ~DescribeAccountsResponseBodyAccountList() = default; }; class DescribeAccountsResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; shared_ptr<DescribeAccountsResponseBodyAccountList> accountList{}; DescribeAccountsResponseBody() {} explicit DescribeAccountsResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } if (accountList) { res["AccountList"] = accountList ? boost::any(accountList->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("AccountList") != m.end() && !m["AccountList"].empty()) { if (typeid(map<string, boost::any>) == m["AccountList"].type()) { DescribeAccountsResponseBodyAccountList model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["AccountList"])); accountList = make_shared<DescribeAccountsResponseBodyAccountList>(model1); } } } virtual ~DescribeAccountsResponseBody() = default; }; class DescribeAccountsResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeAccountsResponseBody> body{}; DescribeAccountsResponse() {} explicit DescribeAccountsResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeAccountsResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeAccountsResponseBody>(model1); } } } virtual ~DescribeAccountsResponse() = default; }; class DescribeAllAccountsRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; DescribeAllAccountsRequest() {} explicit DescribeAllAccountsRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } } virtual ~DescribeAllAccountsRequest() = default; }; class DescribeAllAccountsResponseBodyAccountList : public Darabonba::Model { public: shared_ptr<string> user{}; DescribeAllAccountsResponseBodyAccountList() {} explicit DescribeAllAccountsResponseBodyAccountList(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (user) { res["User"] = boost::any(*user); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("User") != m.end() && !m["User"].empty()) { user = make_shared<string>(boost::any_cast<string>(m["User"])); } } virtual ~DescribeAllAccountsResponseBodyAccountList() = default; }; class DescribeAllAccountsResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; shared_ptr<vector<DescribeAllAccountsResponseBodyAccountList>> accountList{}; DescribeAllAccountsResponseBody() {} explicit DescribeAllAccountsResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } if (accountList) { vector<boost::any> temp1; for(auto item1:*accountList){ temp1.push_back(boost::any(item1.toMap())); } res["AccountList"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("AccountList") != m.end() && !m["AccountList"].empty()) { if (typeid(vector<boost::any>) == m["AccountList"].type()) { vector<DescribeAllAccountsResponseBodyAccountList> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["AccountList"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeAllAccountsResponseBodyAccountList model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } accountList = make_shared<vector<DescribeAllAccountsResponseBodyAccountList>>(expect1); } } } virtual ~DescribeAllAccountsResponseBody() = default; }; class DescribeAllAccountsResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeAllAccountsResponseBody> body{}; DescribeAllAccountsResponse() {} explicit DescribeAllAccountsResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeAllAccountsResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeAllAccountsResponseBody>(model1); } } } virtual ~DescribeAllAccountsResponse() = default; }; class DescribeAllDataSourceRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> schemaName{}; shared_ptr<string> tableName{}; DescribeAllDataSourceRequest() {} explicit DescribeAllDataSourceRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (schemaName) { res["SchemaName"] = boost::any(*schemaName); } if (tableName) { res["TableName"] = boost::any(*tableName); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("SchemaName") != m.end() && !m["SchemaName"].empty()) { schemaName = make_shared<string>(boost::any_cast<string>(m["SchemaName"])); } if (m.find("TableName") != m.end() && !m["TableName"].empty()) { tableName = make_shared<string>(boost::any_cast<string>(m["TableName"])); } } virtual ~DescribeAllDataSourceRequest() = default; }; class DescribeAllDataSourceResponseBodySchemasSchema : public Darabonba::Model { public: shared_ptr<string> schemaName{}; shared_ptr<string> DBClusterId{}; DescribeAllDataSourceResponseBodySchemasSchema() {} explicit DescribeAllDataSourceResponseBodySchemasSchema(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (schemaName) { res["SchemaName"] = boost::any(*schemaName); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("SchemaName") != m.end() && !m["SchemaName"].empty()) { schemaName = make_shared<string>(boost::any_cast<string>(m["SchemaName"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } } virtual ~DescribeAllDataSourceResponseBodySchemasSchema() = default; }; class DescribeAllDataSourceResponseBodySchemas : public Darabonba::Model { public: shared_ptr<vector<DescribeAllDataSourceResponseBodySchemasSchema>> schema{}; DescribeAllDataSourceResponseBodySchemas() {} explicit DescribeAllDataSourceResponseBodySchemas(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (schema) { vector<boost::any> temp1; for(auto item1:*schema){ temp1.push_back(boost::any(item1.toMap())); } res["Schema"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Schema") != m.end() && !m["Schema"].empty()) { if (typeid(vector<boost::any>) == m["Schema"].type()) { vector<DescribeAllDataSourceResponseBodySchemasSchema> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["Schema"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeAllDataSourceResponseBodySchemasSchema model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } schema = make_shared<vector<DescribeAllDataSourceResponseBodySchemasSchema>>(expect1); } } } virtual ~DescribeAllDataSourceResponseBodySchemas() = default; }; class DescribeAllDataSourceResponseBodyTablesTable : public Darabonba::Model { public: shared_ptr<string> schemaName{}; shared_ptr<string> tableName{}; shared_ptr<string> DBClusterId{}; DescribeAllDataSourceResponseBodyTablesTable() {} explicit DescribeAllDataSourceResponseBodyTablesTable(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (schemaName) { res["SchemaName"] = boost::any(*schemaName); } if (tableName) { res["TableName"] = boost::any(*tableName); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("SchemaName") != m.end() && !m["SchemaName"].empty()) { schemaName = make_shared<string>(boost::any_cast<string>(m["SchemaName"])); } if (m.find("TableName") != m.end() && !m["TableName"].empty()) { tableName = make_shared<string>(boost::any_cast<string>(m["TableName"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } } virtual ~DescribeAllDataSourceResponseBodyTablesTable() = default; }; class DescribeAllDataSourceResponseBodyTables : public Darabonba::Model { public: shared_ptr<vector<DescribeAllDataSourceResponseBodyTablesTable>> table{}; DescribeAllDataSourceResponseBodyTables() {} explicit DescribeAllDataSourceResponseBodyTables(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (table) { vector<boost::any> temp1; for(auto item1:*table){ temp1.push_back(boost::any(item1.toMap())); } res["Table"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Table") != m.end() && !m["Table"].empty()) { if (typeid(vector<boost::any>) == m["Table"].type()) { vector<DescribeAllDataSourceResponseBodyTablesTable> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["Table"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeAllDataSourceResponseBodyTablesTable model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } table = make_shared<vector<DescribeAllDataSourceResponseBodyTablesTable>>(expect1); } } } virtual ~DescribeAllDataSourceResponseBodyTables() = default; }; class DescribeAllDataSourceResponseBodyColumnsColumn : public Darabonba::Model { public: shared_ptr<string> type{}; shared_ptr<string> columnName{}; shared_ptr<string> tableName{}; shared_ptr<bool> autoIncrementColumn{}; shared_ptr<string> DBClusterId{}; shared_ptr<bool> primaryKey{}; shared_ptr<string> schemaName{}; DescribeAllDataSourceResponseBodyColumnsColumn() {} explicit DescribeAllDataSourceResponseBodyColumnsColumn(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (type) { res["Type"] = boost::any(*type); } if (columnName) { res["ColumnName"] = boost::any(*columnName); } if (tableName) { res["TableName"] = boost::any(*tableName); } if (autoIncrementColumn) { res["AutoIncrementColumn"] = boost::any(*autoIncrementColumn); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (primaryKey) { res["PrimaryKey"] = boost::any(*primaryKey); } if (schemaName) { res["SchemaName"] = boost::any(*schemaName); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Type") != m.end() && !m["Type"].empty()) { type = make_shared<string>(boost::any_cast<string>(m["Type"])); } if (m.find("ColumnName") != m.end() && !m["ColumnName"].empty()) { columnName = make_shared<string>(boost::any_cast<string>(m["ColumnName"])); } if (m.find("TableName") != m.end() && !m["TableName"].empty()) { tableName = make_shared<string>(boost::any_cast<string>(m["TableName"])); } if (m.find("AutoIncrementColumn") != m.end() && !m["AutoIncrementColumn"].empty()) { autoIncrementColumn = make_shared<bool>(boost::any_cast<bool>(m["AutoIncrementColumn"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("PrimaryKey") != m.end() && !m["PrimaryKey"].empty()) { primaryKey = make_shared<bool>(boost::any_cast<bool>(m["PrimaryKey"])); } if (m.find("SchemaName") != m.end() && !m["SchemaName"].empty()) { schemaName = make_shared<string>(boost::any_cast<string>(m["SchemaName"])); } } virtual ~DescribeAllDataSourceResponseBodyColumnsColumn() = default; }; class DescribeAllDataSourceResponseBodyColumns : public Darabonba::Model { public: shared_ptr<vector<DescribeAllDataSourceResponseBodyColumnsColumn>> column{}; DescribeAllDataSourceResponseBodyColumns() {} explicit DescribeAllDataSourceResponseBodyColumns(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (column) { vector<boost::any> temp1; for(auto item1:*column){ temp1.push_back(boost::any(item1.toMap())); } res["Column"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Column") != m.end() && !m["Column"].empty()) { if (typeid(vector<boost::any>) == m["Column"].type()) { vector<DescribeAllDataSourceResponseBodyColumnsColumn> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["Column"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeAllDataSourceResponseBodyColumnsColumn model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } column = make_shared<vector<DescribeAllDataSourceResponseBodyColumnsColumn>>(expect1); } } } virtual ~DescribeAllDataSourceResponseBodyColumns() = default; }; class DescribeAllDataSourceResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; shared_ptr<DescribeAllDataSourceResponseBodySchemas> schemas{}; shared_ptr<DescribeAllDataSourceResponseBodyTables> tables{}; shared_ptr<DescribeAllDataSourceResponseBodyColumns> columns{}; DescribeAllDataSourceResponseBody() {} explicit DescribeAllDataSourceResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } if (schemas) { res["Schemas"] = schemas ? boost::any(schemas->toMap()) : boost::any(map<string,boost::any>({})); } if (tables) { res["Tables"] = tables ? boost::any(tables->toMap()) : boost::any(map<string,boost::any>({})); } if (columns) { res["Columns"] = columns ? boost::any(columns->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("Schemas") != m.end() && !m["Schemas"].empty()) { if (typeid(map<string, boost::any>) == m["Schemas"].type()) { DescribeAllDataSourceResponseBodySchemas model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Schemas"])); schemas = make_shared<DescribeAllDataSourceResponseBodySchemas>(model1); } } if (m.find("Tables") != m.end() && !m["Tables"].empty()) { if (typeid(map<string, boost::any>) == m["Tables"].type()) { DescribeAllDataSourceResponseBodyTables model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Tables"])); tables = make_shared<DescribeAllDataSourceResponseBodyTables>(model1); } } if (m.find("Columns") != m.end() && !m["Columns"].empty()) { if (typeid(map<string, boost::any>) == m["Columns"].type()) { DescribeAllDataSourceResponseBodyColumns model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Columns"])); columns = make_shared<DescribeAllDataSourceResponseBodyColumns>(model1); } } } virtual ~DescribeAllDataSourceResponseBody() = default; }; class DescribeAllDataSourceResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeAllDataSourceResponseBody> body{}; DescribeAllDataSourceResponse() {} explicit DescribeAllDataSourceResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeAllDataSourceResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeAllDataSourceResponseBody>(model1); } } } virtual ~DescribeAllDataSourceResponse() = default; }; class DescribeAuditLogConfigRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> regionId{}; DescribeAuditLogConfigRequest() {} explicit DescribeAuditLogConfigRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (regionId) { res["RegionId"] = boost::any(*regionId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("RegionId") != m.end() && !m["RegionId"].empty()) { regionId = make_shared<string>(boost::any_cast<string>(m["RegionId"])); } } virtual ~DescribeAuditLogConfigRequest() = default; }; class DescribeAuditLogConfigResponseBody : public Darabonba::Model { public: shared_ptr<string> auditLogStatus{}; shared_ptr<string> requestId{}; shared_ptr<string> DBClusterId{}; DescribeAuditLogConfigResponseBody() {} explicit DescribeAuditLogConfigResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (auditLogStatus) { res["AuditLogStatus"] = boost::any(*auditLogStatus); } if (requestId) { res["RequestId"] = boost::any(*requestId); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("AuditLogStatus") != m.end() && !m["AuditLogStatus"].empty()) { auditLogStatus = make_shared<string>(boost::any_cast<string>(m["AuditLogStatus"])); } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } } virtual ~DescribeAuditLogConfigResponseBody() = default; }; class DescribeAuditLogConfigResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeAuditLogConfigResponseBody> body{}; DescribeAuditLogConfigResponse() {} explicit DescribeAuditLogConfigResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeAuditLogConfigResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeAuditLogConfigResponseBody>(model1); } } } virtual ~DescribeAuditLogConfigResponse() = default; }; class DescribeAuditLogRecordsRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> regionId{}; shared_ptr<string> startTime{}; shared_ptr<string> endTime{}; shared_ptr<string> DBName{}; shared_ptr<string> queryKeyword{}; shared_ptr<string> sqlType{}; shared_ptr<string> succeed{}; shared_ptr<string> hostAddress{}; shared_ptr<string> orderType{}; shared_ptr<string> user{}; shared_ptr<long> pageSize{}; shared_ptr<long> pageNumber{}; DescribeAuditLogRecordsRequest() {} explicit DescribeAuditLogRecordsRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (regionId) { res["RegionId"] = boost::any(*regionId); } if (startTime) { res["StartTime"] = boost::any(*startTime); } if (endTime) { res["EndTime"] = boost::any(*endTime); } if (DBName) { res["DBName"] = boost::any(*DBName); } if (queryKeyword) { res["QueryKeyword"] = boost::any(*queryKeyword); } if (sqlType) { res["SqlType"] = boost::any(*sqlType); } if (succeed) { res["Succeed"] = boost::any(*succeed); } if (hostAddress) { res["HostAddress"] = boost::any(*hostAddress); } if (orderType) { res["OrderType"] = boost::any(*orderType); } if (user) { res["User"] = boost::any(*user); } if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("RegionId") != m.end() && !m["RegionId"].empty()) { regionId = make_shared<string>(boost::any_cast<string>(m["RegionId"])); } if (m.find("StartTime") != m.end() && !m["StartTime"].empty()) { startTime = make_shared<string>(boost::any_cast<string>(m["StartTime"])); } if (m.find("EndTime") != m.end() && !m["EndTime"].empty()) { endTime = make_shared<string>(boost::any_cast<string>(m["EndTime"])); } if (m.find("DBName") != m.end() && !m["DBName"].empty()) { DBName = make_shared<string>(boost::any_cast<string>(m["DBName"])); } if (m.find("QueryKeyword") != m.end() && !m["QueryKeyword"].empty()) { queryKeyword = make_shared<string>(boost::any_cast<string>(m["QueryKeyword"])); } if (m.find("SqlType") != m.end() && !m["SqlType"].empty()) { sqlType = make_shared<string>(boost::any_cast<string>(m["SqlType"])); } if (m.find("Succeed") != m.end() && !m["Succeed"].empty()) { succeed = make_shared<string>(boost::any_cast<string>(m["Succeed"])); } if (m.find("HostAddress") != m.end() && !m["HostAddress"].empty()) { hostAddress = make_shared<string>(boost::any_cast<string>(m["HostAddress"])); } if (m.find("OrderType") != m.end() && !m["OrderType"].empty()) { orderType = make_shared<string>(boost::any_cast<string>(m["OrderType"])); } if (m.find("User") != m.end() && !m["User"].empty()) { user = make_shared<string>(boost::any_cast<string>(m["User"])); } if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"])); } if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"])); } } virtual ~DescribeAuditLogRecordsRequest() = default; }; class DescribeAuditLogRecordsResponseBodyItems : public Darabonba::Model { public: shared_ptr<string> hostAddress{}; shared_ptr<string> succeed{}; shared_ptr<string> SQLText{}; shared_ptr<string> totalTime{}; shared_ptr<string> connId{}; shared_ptr<string> DBName{}; shared_ptr<string> SQLType{}; shared_ptr<string> executeTime{}; shared_ptr<string> processID{}; DescribeAuditLogRecordsResponseBodyItems() {} explicit DescribeAuditLogRecordsResponseBodyItems(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (hostAddress) { res["HostAddress"] = boost::any(*hostAddress); } if (succeed) { res["Succeed"] = boost::any(*succeed); } if (SQLText) { res["SQLText"] = boost::any(*SQLText); } if (totalTime) { res["TotalTime"] = boost::any(*totalTime); } if (connId) { res["ConnId"] = boost::any(*connId); } if (DBName) { res["DBName"] = boost::any(*DBName); } if (SQLType) { res["SQLType"] = boost::any(*SQLType); } if (executeTime) { res["ExecuteTime"] = boost::any(*executeTime); } if (processID) { res["ProcessID"] = boost::any(*processID); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("HostAddress") != m.end() && !m["HostAddress"].empty()) { hostAddress = make_shared<string>(boost::any_cast<string>(m["HostAddress"])); } if (m.find("Succeed") != m.end() && !m["Succeed"].empty()) { succeed = make_shared<string>(boost::any_cast<string>(m["Succeed"])); } if (m.find("SQLText") != m.end() && !m["SQLText"].empty()) { SQLText = make_shared<string>(boost::any_cast<string>(m["SQLText"])); } if (m.find("TotalTime") != m.end() && !m["TotalTime"].empty()) { totalTime = make_shared<string>(boost::any_cast<string>(m["TotalTime"])); } if (m.find("ConnId") != m.end() && !m["ConnId"].empty()) { connId = make_shared<string>(boost::any_cast<string>(m["ConnId"])); } if (m.find("DBName") != m.end() && !m["DBName"].empty()) { DBName = make_shared<string>(boost::any_cast<string>(m["DBName"])); } if (m.find("SQLType") != m.end() && !m["SQLType"].empty()) { SQLType = make_shared<string>(boost::any_cast<string>(m["SQLType"])); } if (m.find("ExecuteTime") != m.end() && !m["ExecuteTime"].empty()) { executeTime = make_shared<string>(boost::any_cast<string>(m["ExecuteTime"])); } if (m.find("ProcessID") != m.end() && !m["ProcessID"].empty()) { processID = make_shared<string>(boost::any_cast<string>(m["ProcessID"])); } } virtual ~DescribeAuditLogRecordsResponseBodyItems() = default; }; class DescribeAuditLogRecordsResponseBody : public Darabonba::Model { public: shared_ptr<string> DBClusterId{}; shared_ptr<string> pageSize{}; shared_ptr<string> pageNumber{}; shared_ptr<string> requestId{}; shared_ptr<string> totalCount{}; shared_ptr<vector<DescribeAuditLogRecordsResponseBodyItems>> items{}; DescribeAuditLogRecordsResponseBody() {} explicit DescribeAuditLogRecordsResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } if (requestId) { res["RequestId"] = boost::any(*requestId); } if (totalCount) { res["TotalCount"] = boost::any(*totalCount); } if (items) { vector<boost::any> temp1; for(auto item1:*items){ temp1.push_back(boost::any(item1.toMap())); } res["Items"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<string>(boost::any_cast<string>(m["PageSize"])); } if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<string>(boost::any_cast<string>(m["PageNumber"])); } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("TotalCount") != m.end() && !m["TotalCount"].empty()) { totalCount = make_shared<string>(boost::any_cast<string>(m["TotalCount"])); } if (m.find("Items") != m.end() && !m["Items"].empty()) { if (typeid(vector<boost::any>) == m["Items"].type()) { vector<DescribeAuditLogRecordsResponseBodyItems> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["Items"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeAuditLogRecordsResponseBodyItems model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } items = make_shared<vector<DescribeAuditLogRecordsResponseBodyItems>>(expect1); } } } virtual ~DescribeAuditLogRecordsResponseBody() = default; }; class DescribeAuditLogRecordsResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeAuditLogRecordsResponseBody> body{}; DescribeAuditLogRecordsResponse() {} explicit DescribeAuditLogRecordsResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeAuditLogRecordsResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeAuditLogRecordsResponseBody>(model1); } } } virtual ~DescribeAuditLogRecordsResponse() = default; }; class DescribeAutoRenewAttributeRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> regionId{}; shared_ptr<string> DBClusterIds{}; shared_ptr<long> pageSize{}; shared_ptr<long> pageNumber{}; shared_ptr<string> resourceGroupId{}; DescribeAutoRenewAttributeRequest() {} explicit DescribeAutoRenewAttributeRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (regionId) { res["RegionId"] = boost::any(*regionId); } if (DBClusterIds) { res["DBClusterIds"] = boost::any(*DBClusterIds); } if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } if (resourceGroupId) { res["ResourceGroupId"] = boost::any(*resourceGroupId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("RegionId") != m.end() && !m["RegionId"].empty()) { regionId = make_shared<string>(boost::any_cast<string>(m["RegionId"])); } if (m.find("DBClusterIds") != m.end() && !m["DBClusterIds"].empty()) { DBClusterIds = make_shared<string>(boost::any_cast<string>(m["DBClusterIds"])); } if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"])); } if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"])); } if (m.find("ResourceGroupId") != m.end() && !m["ResourceGroupId"].empty()) { resourceGroupId = make_shared<string>(boost::any_cast<string>(m["ResourceGroupId"])); } } virtual ~DescribeAutoRenewAttributeRequest() = default; }; class DescribeAutoRenewAttributeResponseBodyItemsAutoRenewAttribute : public Darabonba::Model { public: shared_ptr<string> DBClusterId{}; shared_ptr<string> periodUnit{}; shared_ptr<long> duration{}; shared_ptr<string> renewalStatus{}; shared_ptr<bool> autoRenewEnabled{}; shared_ptr<string> regionId{}; DescribeAutoRenewAttributeResponseBodyItemsAutoRenewAttribute() {} explicit DescribeAutoRenewAttributeResponseBodyItemsAutoRenewAttribute(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (periodUnit) { res["PeriodUnit"] = boost::any(*periodUnit); } if (duration) { res["Duration"] = boost::any(*duration); } if (renewalStatus) { res["RenewalStatus"] = boost::any(*renewalStatus); } if (autoRenewEnabled) { res["AutoRenewEnabled"] = boost::any(*autoRenewEnabled); } if (regionId) { res["RegionId"] = boost::any(*regionId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("PeriodUnit") != m.end() && !m["PeriodUnit"].empty()) { periodUnit = make_shared<string>(boost::any_cast<string>(m["PeriodUnit"])); } if (m.find("Duration") != m.end() && !m["Duration"].empty()) { duration = make_shared<long>(boost::any_cast<long>(m["Duration"])); } if (m.find("RenewalStatus") != m.end() && !m["RenewalStatus"].empty()) { renewalStatus = make_shared<string>(boost::any_cast<string>(m["RenewalStatus"])); } if (m.find("AutoRenewEnabled") != m.end() && !m["AutoRenewEnabled"].empty()) { autoRenewEnabled = make_shared<bool>(boost::any_cast<bool>(m["AutoRenewEnabled"])); } if (m.find("RegionId") != m.end() && !m["RegionId"].empty()) { regionId = make_shared<string>(boost::any_cast<string>(m["RegionId"])); } } virtual ~DescribeAutoRenewAttributeResponseBodyItemsAutoRenewAttribute() = default; }; class DescribeAutoRenewAttributeResponseBodyItems : public Darabonba::Model { public: shared_ptr<vector<DescribeAutoRenewAttributeResponseBodyItemsAutoRenewAttribute>> autoRenewAttribute{}; DescribeAutoRenewAttributeResponseBodyItems() {} explicit DescribeAutoRenewAttributeResponseBodyItems(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (autoRenewAttribute) { vector<boost::any> temp1; for(auto item1:*autoRenewAttribute){ temp1.push_back(boost::any(item1.toMap())); } res["AutoRenewAttribute"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("AutoRenewAttribute") != m.end() && !m["AutoRenewAttribute"].empty()) { if (typeid(vector<boost::any>) == m["AutoRenewAttribute"].type()) { vector<DescribeAutoRenewAttributeResponseBodyItemsAutoRenewAttribute> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["AutoRenewAttribute"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeAutoRenewAttributeResponseBodyItemsAutoRenewAttribute model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } autoRenewAttribute = make_shared<vector<DescribeAutoRenewAttributeResponseBodyItemsAutoRenewAttribute>>(expect1); } } } virtual ~DescribeAutoRenewAttributeResponseBodyItems() = default; }; class DescribeAutoRenewAttributeResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; shared_ptr<long> pageNumber{}; shared_ptr<long> pageRecordCount{}; shared_ptr<long> totalRecordCount{}; shared_ptr<DescribeAutoRenewAttributeResponseBodyItems> items{}; DescribeAutoRenewAttributeResponseBody() {} explicit DescribeAutoRenewAttributeResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } if (pageRecordCount) { res["PageRecordCount"] = boost::any(*pageRecordCount); } if (totalRecordCount) { res["TotalRecordCount"] = boost::any(*totalRecordCount); } if (items) { res["Items"] = items ? boost::any(items->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"])); } if (m.find("PageRecordCount") != m.end() && !m["PageRecordCount"].empty()) { pageRecordCount = make_shared<long>(boost::any_cast<long>(m["PageRecordCount"])); } if (m.find("TotalRecordCount") != m.end() && !m["TotalRecordCount"].empty()) { totalRecordCount = make_shared<long>(boost::any_cast<long>(m["TotalRecordCount"])); } if (m.find("Items") != m.end() && !m["Items"].empty()) { if (typeid(map<string, boost::any>) == m["Items"].type()) { DescribeAutoRenewAttributeResponseBodyItems model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Items"])); items = make_shared<DescribeAutoRenewAttributeResponseBodyItems>(model1); } } } virtual ~DescribeAutoRenewAttributeResponseBody() = default; }; class DescribeAutoRenewAttributeResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeAutoRenewAttributeResponseBody> body{}; DescribeAutoRenewAttributeResponse() {} explicit DescribeAutoRenewAttributeResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeAutoRenewAttributeResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeAutoRenewAttributeResponseBody>(model1); } } } virtual ~DescribeAutoRenewAttributeResponse() = default; }; class DescribeAvailableResourceRequest : public Darabonba::Model { public: shared_ptr<string> regionId{}; shared_ptr<string> zoneId{}; shared_ptr<string> chargeType{}; shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> acceptLanguage{}; DescribeAvailableResourceRequest() {} explicit DescribeAvailableResourceRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (regionId) { res["RegionId"] = boost::any(*regionId); } if (zoneId) { res["ZoneId"] = boost::any(*zoneId); } if (chargeType) { res["ChargeType"] = boost::any(*chargeType); } if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (acceptLanguage) { res["AcceptLanguage"] = boost::any(*acceptLanguage); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RegionId") != m.end() && !m["RegionId"].empty()) { regionId = make_shared<string>(boost::any_cast<string>(m["RegionId"])); } if (m.find("ZoneId") != m.end() && !m["ZoneId"].empty()) { zoneId = make_shared<string>(boost::any_cast<string>(m["ZoneId"])); } if (m.find("ChargeType") != m.end() && !m["ChargeType"].empty()) { chargeType = make_shared<string>(boost::any_cast<string>(m["ChargeType"])); } if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("AcceptLanguage") != m.end() && !m["AcceptLanguage"].empty()) { acceptLanguage = make_shared<string>(boost::any_cast<string>(m["AcceptLanguage"])); } } virtual ~DescribeAvailableResourceRequest() = default; }; class DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedFlexibleResourceSupportedElasticIOResource : public Darabonba::Model { public: shared_ptr<string> step{}; shared_ptr<string> minCount{}; shared_ptr<string> maxCount{}; DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedFlexibleResourceSupportedElasticIOResource() {} explicit DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedFlexibleResourceSupportedElasticIOResource(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (step) { res["Step"] = boost::any(*step); } if (minCount) { res["MinCount"] = boost::any(*minCount); } if (maxCount) { res["MaxCount"] = boost::any(*maxCount); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Step") != m.end() && !m["Step"].empty()) { step = make_shared<string>(boost::any_cast<string>(m["Step"])); } if (m.find("MinCount") != m.end() && !m["MinCount"].empty()) { minCount = make_shared<string>(boost::any_cast<string>(m["MinCount"])); } if (m.find("MaxCount") != m.end() && !m["MaxCount"].empty()) { maxCount = make_shared<string>(boost::any_cast<string>(m["MaxCount"])); } } virtual ~DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedFlexibleResourceSupportedElasticIOResource() = default; }; class DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedFlexibleResource : public Darabonba::Model { public: shared_ptr<string> storageType{}; shared_ptr<vector<string>> supportedComputeResource{}; shared_ptr<vector<string>> supportedStorageResource{}; shared_ptr<DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedFlexibleResourceSupportedElasticIOResource> supportedElasticIOResource{}; DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedFlexibleResource() {} explicit DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedFlexibleResource(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (storageType) { res["StorageType"] = boost::any(*storageType); } if (supportedComputeResource) { res["SupportedComputeResource"] = boost::any(*supportedComputeResource); } if (supportedStorageResource) { res["SupportedStorageResource"] = boost::any(*supportedStorageResource); } if (supportedElasticIOResource) { res["SupportedElasticIOResource"] = supportedElasticIOResource ? boost::any(supportedElasticIOResource->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("StorageType") != m.end() && !m["StorageType"].empty()) { storageType = make_shared<string>(boost::any_cast<string>(m["StorageType"])); } if (m.find("SupportedComputeResource") != m.end() && !m["SupportedComputeResource"].empty()) { vector<string> toVec1; if (typeid(vector<boost::any>) == m["SupportedComputeResource"].type()) { vector<boost::any> vec1 = boost::any_cast<vector<boost::any>>(m["SupportedComputeResource"]); for (auto item:vec1) { toVec1.push_back(boost::any_cast<string>(item)); } } supportedComputeResource = make_shared<vector<string>>(toVec1); } if (m.find("SupportedStorageResource") != m.end() && !m["SupportedStorageResource"].empty()) { vector<string> toVec1; if (typeid(vector<boost::any>) == m["SupportedStorageResource"].type()) { vector<boost::any> vec1 = boost::any_cast<vector<boost::any>>(m["SupportedStorageResource"]); for (auto item:vec1) { toVec1.push_back(boost::any_cast<string>(item)); } } supportedStorageResource = make_shared<vector<string>>(toVec1); } if (m.find("SupportedElasticIOResource") != m.end() && !m["SupportedElasticIOResource"].empty()) { if (typeid(map<string, boost::any>) == m["SupportedElasticIOResource"].type()) { DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedFlexibleResourceSupportedElasticIOResource model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["SupportedElasticIOResource"])); supportedElasticIOResource = make_shared<DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedFlexibleResourceSupportedElasticIOResource>(model1); } } } virtual ~DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedFlexibleResource() = default; }; class DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassListSupportedNodeCountListNodeCount : public Darabonba::Model { public: shared_ptr<string> step{}; shared_ptr<string> minCount{}; shared_ptr<string> maxCount{}; DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassListSupportedNodeCountListNodeCount() {} explicit DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassListSupportedNodeCountListNodeCount(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (step) { res["Step"] = boost::any(*step); } if (minCount) { res["MinCount"] = boost::any(*minCount); } if (maxCount) { res["MaxCount"] = boost::any(*maxCount); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Step") != m.end() && !m["Step"].empty()) { step = make_shared<string>(boost::any_cast<string>(m["Step"])); } if (m.find("MinCount") != m.end() && !m["MinCount"].empty()) { minCount = make_shared<string>(boost::any_cast<string>(m["MinCount"])); } if (m.find("MaxCount") != m.end() && !m["MaxCount"].empty()) { maxCount = make_shared<string>(boost::any_cast<string>(m["MaxCount"])); } } virtual ~DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassListSupportedNodeCountListNodeCount() = default; }; class DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassListSupportedNodeCountList : public Darabonba::Model { public: shared_ptr<vector<string>> storageSize{}; shared_ptr<DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassListSupportedNodeCountListNodeCount> nodeCount{}; DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassListSupportedNodeCountList() {} explicit DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassListSupportedNodeCountList(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (storageSize) { res["StorageSize"] = boost::any(*storageSize); } if (nodeCount) { res["NodeCount"] = nodeCount ? boost::any(nodeCount->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("StorageSize") != m.end() && !m["StorageSize"].empty()) { vector<string> toVec1; if (typeid(vector<boost::any>) == m["StorageSize"].type()) { vector<boost::any> vec1 = boost::any_cast<vector<boost::any>>(m["StorageSize"]); for (auto item:vec1) { toVec1.push_back(boost::any_cast<string>(item)); } } storageSize = make_shared<vector<string>>(toVec1); } if (m.find("NodeCount") != m.end() && !m["NodeCount"].empty()) { if (typeid(map<string, boost::any>) == m["NodeCount"].type()) { DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassListSupportedNodeCountListNodeCount model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["NodeCount"])); nodeCount = make_shared<DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassListSupportedNodeCountListNodeCount>(model1); } } } virtual ~DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassListSupportedNodeCountList() = default; }; class DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassListSupportedExecutorListNodeCount : public Darabonba::Model { public: shared_ptr<string> step{}; shared_ptr<string> minCount{}; shared_ptr<string> maxCount{}; DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassListSupportedExecutorListNodeCount() {} explicit DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassListSupportedExecutorListNodeCount(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (step) { res["Step"] = boost::any(*step); } if (minCount) { res["MinCount"] = boost::any(*minCount); } if (maxCount) { res["MaxCount"] = boost::any(*maxCount); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Step") != m.end() && !m["Step"].empty()) { step = make_shared<string>(boost::any_cast<string>(m["Step"])); } if (m.find("MinCount") != m.end() && !m["MinCount"].empty()) { minCount = make_shared<string>(boost::any_cast<string>(m["MinCount"])); } if (m.find("MaxCount") != m.end() && !m["MaxCount"].empty()) { maxCount = make_shared<string>(boost::any_cast<string>(m["MaxCount"])); } } virtual ~DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassListSupportedExecutorListNodeCount() = default; }; class DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassListSupportedExecutorList : public Darabonba::Model { public: shared_ptr<DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassListSupportedExecutorListNodeCount> nodeCount{}; DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassListSupportedExecutorList() {} explicit DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassListSupportedExecutorList(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (nodeCount) { res["NodeCount"] = nodeCount ? boost::any(nodeCount->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("NodeCount") != m.end() && !m["NodeCount"].empty()) { if (typeid(map<string, boost::any>) == m["NodeCount"].type()) { DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassListSupportedExecutorListNodeCount model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["NodeCount"])); nodeCount = make_shared<DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassListSupportedExecutorListNodeCount>(model1); } } } virtual ~DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassListSupportedExecutorList() = default; }; class DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassList : public Darabonba::Model { public: shared_ptr<string> instanceClass{}; shared_ptr<string> tips{}; shared_ptr<vector<DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassListSupportedNodeCountList>> supportedNodeCountList{}; shared_ptr<vector<DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassListSupportedExecutorList>> supportedExecutorList{}; DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassList() {} explicit DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassList(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (instanceClass) { res["InstanceClass"] = boost::any(*instanceClass); } if (tips) { res["Tips"] = boost::any(*tips); } if (supportedNodeCountList) { vector<boost::any> temp1; for(auto item1:*supportedNodeCountList){ temp1.push_back(boost::any(item1.toMap())); } res["SupportedNodeCountList"] = boost::any(temp1); } if (supportedExecutorList) { vector<boost::any> temp1; for(auto item1:*supportedExecutorList){ temp1.push_back(boost::any(item1.toMap())); } res["SupportedExecutorList"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("InstanceClass") != m.end() && !m["InstanceClass"].empty()) { instanceClass = make_shared<string>(boost::any_cast<string>(m["InstanceClass"])); } if (m.find("Tips") != m.end() && !m["Tips"].empty()) { tips = make_shared<string>(boost::any_cast<string>(m["Tips"])); } if (m.find("SupportedNodeCountList") != m.end() && !m["SupportedNodeCountList"].empty()) { if (typeid(vector<boost::any>) == m["SupportedNodeCountList"].type()) { vector<DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassListSupportedNodeCountList> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["SupportedNodeCountList"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassListSupportedNodeCountList model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } supportedNodeCountList = make_shared<vector<DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassListSupportedNodeCountList>>(expect1); } } if (m.find("SupportedExecutorList") != m.end() && !m["SupportedExecutorList"].empty()) { if (typeid(vector<boost::any>) == m["SupportedExecutorList"].type()) { vector<DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassListSupportedExecutorList> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["SupportedExecutorList"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassListSupportedExecutorList model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } supportedExecutorList = make_shared<vector<DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassListSupportedExecutorList>>(expect1); } } } virtual ~DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassList() = default; }; class DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialList : public Darabonba::Model { public: shared_ptr<string> serial{}; shared_ptr<vector<DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedFlexibleResource>> supportedFlexibleResource{}; shared_ptr<vector<DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassList>> supportedInstanceClassList{}; DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialList() {} explicit DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialList(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (serial) { res["Serial"] = boost::any(*serial); } if (supportedFlexibleResource) { vector<boost::any> temp1; for(auto item1:*supportedFlexibleResource){ temp1.push_back(boost::any(item1.toMap())); } res["SupportedFlexibleResource"] = boost::any(temp1); } if (supportedInstanceClassList) { vector<boost::any> temp1; for(auto item1:*supportedInstanceClassList){ temp1.push_back(boost::any(item1.toMap())); } res["SupportedInstanceClassList"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Serial") != m.end() && !m["Serial"].empty()) { serial = make_shared<string>(boost::any_cast<string>(m["Serial"])); } if (m.find("SupportedFlexibleResource") != m.end() && !m["SupportedFlexibleResource"].empty()) { if (typeid(vector<boost::any>) == m["SupportedFlexibleResource"].type()) { vector<DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedFlexibleResource> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["SupportedFlexibleResource"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedFlexibleResource model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } supportedFlexibleResource = make_shared<vector<DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedFlexibleResource>>(expect1); } } if (m.find("SupportedInstanceClassList") != m.end() && !m["SupportedInstanceClassList"].empty()) { if (typeid(vector<boost::any>) == m["SupportedInstanceClassList"].type()) { vector<DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassList> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["SupportedInstanceClassList"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassList model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } supportedInstanceClassList = make_shared<vector<DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialListSupportedInstanceClassList>>(expect1); } } } virtual ~DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialList() = default; }; class DescribeAvailableResourceResponseBodyAvailableZoneListSupportedMode : public Darabonba::Model { public: shared_ptr<string> mode{}; shared_ptr<vector<DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialList>> supportedSerialList{}; DescribeAvailableResourceResponseBodyAvailableZoneListSupportedMode() {} explicit DescribeAvailableResourceResponseBodyAvailableZoneListSupportedMode(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (mode) { res["Mode"] = boost::any(*mode); } if (supportedSerialList) { vector<boost::any> temp1; for(auto item1:*supportedSerialList){ temp1.push_back(boost::any(item1.toMap())); } res["SupportedSerialList"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Mode") != m.end() && !m["Mode"].empty()) { mode = make_shared<string>(boost::any_cast<string>(m["Mode"])); } if (m.find("SupportedSerialList") != m.end() && !m["SupportedSerialList"].empty()) { if (typeid(vector<boost::any>) == m["SupportedSerialList"].type()) { vector<DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialList> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["SupportedSerialList"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialList model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } supportedSerialList = make_shared<vector<DescribeAvailableResourceResponseBodyAvailableZoneListSupportedModeSupportedSerialList>>(expect1); } } } virtual ~DescribeAvailableResourceResponseBodyAvailableZoneListSupportedMode() = default; }; class DescribeAvailableResourceResponseBodyAvailableZoneList : public Darabonba::Model { public: shared_ptr<string> zoneId{}; shared_ptr<vector<DescribeAvailableResourceResponseBodyAvailableZoneListSupportedMode>> supportedMode{}; DescribeAvailableResourceResponseBodyAvailableZoneList() {} explicit DescribeAvailableResourceResponseBodyAvailableZoneList(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (zoneId) { res["ZoneId"] = boost::any(*zoneId); } if (supportedMode) { vector<boost::any> temp1; for(auto item1:*supportedMode){ temp1.push_back(boost::any(item1.toMap())); } res["SupportedMode"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ZoneId") != m.end() && !m["ZoneId"].empty()) { zoneId = make_shared<string>(boost::any_cast<string>(m["ZoneId"])); } if (m.find("SupportedMode") != m.end() && !m["SupportedMode"].empty()) { if (typeid(vector<boost::any>) == m["SupportedMode"].type()) { vector<DescribeAvailableResourceResponseBodyAvailableZoneListSupportedMode> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["SupportedMode"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeAvailableResourceResponseBodyAvailableZoneListSupportedMode model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } supportedMode = make_shared<vector<DescribeAvailableResourceResponseBodyAvailableZoneListSupportedMode>>(expect1); } } } virtual ~DescribeAvailableResourceResponseBodyAvailableZoneList() = default; }; class DescribeAvailableResourceResponseBody : public Darabonba::Model { public: shared_ptr<string> regionId{}; shared_ptr<string> requestId{}; shared_ptr<vector<DescribeAvailableResourceResponseBodyAvailableZoneList>> availableZoneList{}; DescribeAvailableResourceResponseBody() {} explicit DescribeAvailableResourceResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (regionId) { res["RegionId"] = boost::any(*regionId); } if (requestId) { res["RequestId"] = boost::any(*requestId); } if (availableZoneList) { vector<boost::any> temp1; for(auto item1:*availableZoneList){ temp1.push_back(boost::any(item1.toMap())); } res["AvailableZoneList"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RegionId") != m.end() && !m["RegionId"].empty()) { regionId = make_shared<string>(boost::any_cast<string>(m["RegionId"])); } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("AvailableZoneList") != m.end() && !m["AvailableZoneList"].empty()) { if (typeid(vector<boost::any>) == m["AvailableZoneList"].type()) { vector<DescribeAvailableResourceResponseBodyAvailableZoneList> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["AvailableZoneList"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeAvailableResourceResponseBodyAvailableZoneList model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } availableZoneList = make_shared<vector<DescribeAvailableResourceResponseBodyAvailableZoneList>>(expect1); } } } virtual ~DescribeAvailableResourceResponseBody() = default; }; class DescribeAvailableResourceResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeAvailableResourceResponseBody> body{}; DescribeAvailableResourceResponse() {} explicit DescribeAvailableResourceResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeAvailableResourceResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeAvailableResourceResponseBody>(model1); } } } virtual ~DescribeAvailableResourceResponse() = default; }; class DescribeBackupPolicyRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; DescribeBackupPolicyRequest() {} explicit DescribeBackupPolicyRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } } virtual ~DescribeBackupPolicyRequest() = default; }; class DescribeBackupPolicyResponseBody : public Darabonba::Model { public: shared_ptr<long> logBackupRetentionPeriod{}; shared_ptr<long> backupRetentionPeriod{}; shared_ptr<string> requestId{}; shared_ptr<string> preferredBackupPeriod{}; shared_ptr<string> preferredBackupTime{}; shared_ptr<string> enableBackupLog{}; DescribeBackupPolicyResponseBody() {} explicit DescribeBackupPolicyResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (logBackupRetentionPeriod) { res["LogBackupRetentionPeriod"] = boost::any(*logBackupRetentionPeriod); } if (backupRetentionPeriod) { res["BackupRetentionPeriod"] = boost::any(*backupRetentionPeriod); } if (requestId) { res["RequestId"] = boost::any(*requestId); } if (preferredBackupPeriod) { res["PreferredBackupPeriod"] = boost::any(*preferredBackupPeriod); } if (preferredBackupTime) { res["PreferredBackupTime"] = boost::any(*preferredBackupTime); } if (enableBackupLog) { res["EnableBackupLog"] = boost::any(*enableBackupLog); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("LogBackupRetentionPeriod") != m.end() && !m["LogBackupRetentionPeriod"].empty()) { logBackupRetentionPeriod = make_shared<long>(boost::any_cast<long>(m["LogBackupRetentionPeriod"])); } if (m.find("BackupRetentionPeriod") != m.end() && !m["BackupRetentionPeriod"].empty()) { backupRetentionPeriod = make_shared<long>(boost::any_cast<long>(m["BackupRetentionPeriod"])); } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("PreferredBackupPeriod") != m.end() && !m["PreferredBackupPeriod"].empty()) { preferredBackupPeriod = make_shared<string>(boost::any_cast<string>(m["PreferredBackupPeriod"])); } if (m.find("PreferredBackupTime") != m.end() && !m["PreferredBackupTime"].empty()) { preferredBackupTime = make_shared<string>(boost::any_cast<string>(m["PreferredBackupTime"])); } if (m.find("EnableBackupLog") != m.end() && !m["EnableBackupLog"].empty()) { enableBackupLog = make_shared<string>(boost::any_cast<string>(m["EnableBackupLog"])); } } virtual ~DescribeBackupPolicyResponseBody() = default; }; class DescribeBackupPolicyResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeBackupPolicyResponseBody> body{}; DescribeBackupPolicyResponse() {} explicit DescribeBackupPolicyResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeBackupPolicyResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeBackupPolicyResponseBody>(model1); } } } virtual ~DescribeBackupPolicyResponse() = default; }; class DescribeBackupsRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> backupId{}; shared_ptr<string> startTime{}; shared_ptr<string> endTime{}; shared_ptr<long> pageSize{}; shared_ptr<long> pageNumber{}; DescribeBackupsRequest() {} explicit DescribeBackupsRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (backupId) { res["BackupId"] = boost::any(*backupId); } if (startTime) { res["StartTime"] = boost::any(*startTime); } if (endTime) { res["EndTime"] = boost::any(*endTime); } if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("BackupId") != m.end() && !m["BackupId"].empty()) { backupId = make_shared<string>(boost::any_cast<string>(m["BackupId"])); } if (m.find("StartTime") != m.end() && !m["StartTime"].empty()) { startTime = make_shared<string>(boost::any_cast<string>(m["StartTime"])); } if (m.find("EndTime") != m.end() && !m["EndTime"].empty()) { endTime = make_shared<string>(boost::any_cast<string>(m["EndTime"])); } if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"])); } if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"])); } } virtual ~DescribeBackupsRequest() = default; }; class DescribeBackupsResponseBodyItemsBackup : public Darabonba::Model { public: shared_ptr<string> DBClusterId{}; shared_ptr<string> backupType{}; shared_ptr<string> backupStartTime{}; shared_ptr<long> backupSize{}; shared_ptr<string> backupEndTime{}; shared_ptr<string> backupId{}; shared_ptr<string> backupMethod{}; DescribeBackupsResponseBodyItemsBackup() {} explicit DescribeBackupsResponseBodyItemsBackup(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (backupType) { res["BackupType"] = boost::any(*backupType); } if (backupStartTime) { res["BackupStartTime"] = boost::any(*backupStartTime); } if (backupSize) { res["BackupSize"] = boost::any(*backupSize); } if (backupEndTime) { res["BackupEndTime"] = boost::any(*backupEndTime); } if (backupId) { res["BackupId"] = boost::any(*backupId); } if (backupMethod) { res["BackupMethod"] = boost::any(*backupMethod); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("BackupType") != m.end() && !m["BackupType"].empty()) { backupType = make_shared<string>(boost::any_cast<string>(m["BackupType"])); } if (m.find("BackupStartTime") != m.end() && !m["BackupStartTime"].empty()) { backupStartTime = make_shared<string>(boost::any_cast<string>(m["BackupStartTime"])); } if (m.find("BackupSize") != m.end() && !m["BackupSize"].empty()) { backupSize = make_shared<long>(boost::any_cast<long>(m["BackupSize"])); } if (m.find("BackupEndTime") != m.end() && !m["BackupEndTime"].empty()) { backupEndTime = make_shared<string>(boost::any_cast<string>(m["BackupEndTime"])); } if (m.find("BackupId") != m.end() && !m["BackupId"].empty()) { backupId = make_shared<string>(boost::any_cast<string>(m["BackupId"])); } if (m.find("BackupMethod") != m.end() && !m["BackupMethod"].empty()) { backupMethod = make_shared<string>(boost::any_cast<string>(m["BackupMethod"])); } } virtual ~DescribeBackupsResponseBodyItemsBackup() = default; }; class DescribeBackupsResponseBodyItems : public Darabonba::Model { public: shared_ptr<vector<DescribeBackupsResponseBodyItemsBackup>> backup{}; DescribeBackupsResponseBodyItems() {} explicit DescribeBackupsResponseBodyItems(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (backup) { vector<boost::any> temp1; for(auto item1:*backup){ temp1.push_back(boost::any(item1.toMap())); } res["Backup"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Backup") != m.end() && !m["Backup"].empty()) { if (typeid(vector<boost::any>) == m["Backup"].type()) { vector<DescribeBackupsResponseBodyItemsBackup> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["Backup"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeBackupsResponseBodyItemsBackup model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } backup = make_shared<vector<DescribeBackupsResponseBodyItemsBackup>>(expect1); } } } virtual ~DescribeBackupsResponseBodyItems() = default; }; class DescribeBackupsResponseBody : public Darabonba::Model { public: shared_ptr<string> pageSize{}; shared_ptr<string> requestId{}; shared_ptr<string> pageNumber{}; shared_ptr<string> totalCount{}; shared_ptr<DescribeBackupsResponseBodyItems> items{}; DescribeBackupsResponseBody() {} explicit DescribeBackupsResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (requestId) { res["RequestId"] = boost::any(*requestId); } if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } if (totalCount) { res["TotalCount"] = boost::any(*totalCount); } if (items) { res["Items"] = items ? boost::any(items->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<string>(boost::any_cast<string>(m["PageSize"])); } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<string>(boost::any_cast<string>(m["PageNumber"])); } if (m.find("TotalCount") != m.end() && !m["TotalCount"].empty()) { totalCount = make_shared<string>(boost::any_cast<string>(m["TotalCount"])); } if (m.find("Items") != m.end() && !m["Items"].empty()) { if (typeid(map<string, boost::any>) == m["Items"].type()) { DescribeBackupsResponseBodyItems model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Items"])); items = make_shared<DescribeBackupsResponseBodyItems>(model1); } } } virtual ~DescribeBackupsResponseBody() = default; }; class DescribeBackupsResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeBackupsResponseBody> body{}; DescribeBackupsResponse() {} explicit DescribeBackupsResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeBackupsResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeBackupsResponseBody>(model1); } } } virtual ~DescribeBackupsResponse() = default; }; class DescribeColumnsRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> schemaName{}; shared_ptr<string> tableName{}; DescribeColumnsRequest() {} explicit DescribeColumnsRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (schemaName) { res["SchemaName"] = boost::any(*schemaName); } if (tableName) { res["TableName"] = boost::any(*tableName); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("SchemaName") != m.end() && !m["SchemaName"].empty()) { schemaName = make_shared<string>(boost::any_cast<string>(m["SchemaName"])); } if (m.find("TableName") != m.end() && !m["TableName"].empty()) { tableName = make_shared<string>(boost::any_cast<string>(m["TableName"])); } } virtual ~DescribeColumnsRequest() = default; }; class DescribeColumnsResponseBodyItemsColumn : public Darabonba::Model { public: shared_ptr<string> type{}; shared_ptr<string> columnName{}; shared_ptr<string> tableName{}; shared_ptr<bool> autoIncrementColumn{}; shared_ptr<string> DBClusterId{}; shared_ptr<bool> primaryKey{}; shared_ptr<string> schemaName{}; DescribeColumnsResponseBodyItemsColumn() {} explicit DescribeColumnsResponseBodyItemsColumn(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (type) { res["Type"] = boost::any(*type); } if (columnName) { res["ColumnName"] = boost::any(*columnName); } if (tableName) { res["TableName"] = boost::any(*tableName); } if (autoIncrementColumn) { res["AutoIncrementColumn"] = boost::any(*autoIncrementColumn); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (primaryKey) { res["PrimaryKey"] = boost::any(*primaryKey); } if (schemaName) { res["SchemaName"] = boost::any(*schemaName); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Type") != m.end() && !m["Type"].empty()) { type = make_shared<string>(boost::any_cast<string>(m["Type"])); } if (m.find("ColumnName") != m.end() && !m["ColumnName"].empty()) { columnName = make_shared<string>(boost::any_cast<string>(m["ColumnName"])); } if (m.find("TableName") != m.end() && !m["TableName"].empty()) { tableName = make_shared<string>(boost::any_cast<string>(m["TableName"])); } if (m.find("AutoIncrementColumn") != m.end() && !m["AutoIncrementColumn"].empty()) { autoIncrementColumn = make_shared<bool>(boost::any_cast<bool>(m["AutoIncrementColumn"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("PrimaryKey") != m.end() && !m["PrimaryKey"].empty()) { primaryKey = make_shared<bool>(boost::any_cast<bool>(m["PrimaryKey"])); } if (m.find("SchemaName") != m.end() && !m["SchemaName"].empty()) { schemaName = make_shared<string>(boost::any_cast<string>(m["SchemaName"])); } } virtual ~DescribeColumnsResponseBodyItemsColumn() = default; }; class DescribeColumnsResponseBodyItems : public Darabonba::Model { public: shared_ptr<vector<DescribeColumnsResponseBodyItemsColumn>> column{}; DescribeColumnsResponseBodyItems() {} explicit DescribeColumnsResponseBodyItems(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (column) { vector<boost::any> temp1; for(auto item1:*column){ temp1.push_back(boost::any(item1.toMap())); } res["Column"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Column") != m.end() && !m["Column"].empty()) { if (typeid(vector<boost::any>) == m["Column"].type()) { vector<DescribeColumnsResponseBodyItemsColumn> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["Column"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeColumnsResponseBodyItemsColumn model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } column = make_shared<vector<DescribeColumnsResponseBodyItemsColumn>>(expect1); } } } virtual ~DescribeColumnsResponseBodyItems() = default; }; class DescribeColumnsResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; shared_ptr<DescribeColumnsResponseBodyItems> items{}; DescribeColumnsResponseBody() {} explicit DescribeColumnsResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } if (items) { res["Items"] = items ? boost::any(items->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("Items") != m.end() && !m["Items"].empty()) { if (typeid(map<string, boost::any>) == m["Items"].type()) { DescribeColumnsResponseBodyItems model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Items"])); items = make_shared<DescribeColumnsResponseBodyItems>(model1); } } } virtual ~DescribeColumnsResponseBody() = default; }; class DescribeColumnsResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeColumnsResponseBody> body{}; DescribeColumnsResponse() {} explicit DescribeColumnsResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeColumnsResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeColumnsResponseBody>(model1); } } } virtual ~DescribeColumnsResponse() = default; }; class DescribeConnectionCountRecordsRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; DescribeConnectionCountRecordsRequest() {} explicit DescribeConnectionCountRecordsRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } } virtual ~DescribeConnectionCountRecordsRequest() = default; }; class DescribeConnectionCountRecordsResponseBodyAccessIpRecords : public Darabonba::Model { public: shared_ptr<string> accessIp{}; shared_ptr<long> count{}; DescribeConnectionCountRecordsResponseBodyAccessIpRecords() {} explicit DescribeConnectionCountRecordsResponseBodyAccessIpRecords(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (accessIp) { res["AccessIp"] = boost::any(*accessIp); } if (count) { res["Count"] = boost::any(*count); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("AccessIp") != m.end() && !m["AccessIp"].empty()) { accessIp = make_shared<string>(boost::any_cast<string>(m["AccessIp"])); } if (m.find("Count") != m.end() && !m["Count"].empty()) { count = make_shared<long>(boost::any_cast<long>(m["Count"])); } } virtual ~DescribeConnectionCountRecordsResponseBodyAccessIpRecords() = default; }; class DescribeConnectionCountRecordsResponseBodyUserRecords : public Darabonba::Model { public: shared_ptr<string> user{}; shared_ptr<long> count{}; DescribeConnectionCountRecordsResponseBodyUserRecords() {} explicit DescribeConnectionCountRecordsResponseBodyUserRecords(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (user) { res["User"] = boost::any(*user); } if (count) { res["Count"] = boost::any(*count); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("User") != m.end() && !m["User"].empty()) { user = make_shared<string>(boost::any_cast<string>(m["User"])); } if (m.find("Count") != m.end() && !m["Count"].empty()) { count = make_shared<long>(boost::any_cast<long>(m["Count"])); } } virtual ~DescribeConnectionCountRecordsResponseBodyUserRecords() = default; }; class DescribeConnectionCountRecordsResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; shared_ptr<string> DBClusterId{}; shared_ptr<vector<DescribeConnectionCountRecordsResponseBodyAccessIpRecords>> accessIpRecords{}; shared_ptr<vector<DescribeConnectionCountRecordsResponseBodyUserRecords>> userRecords{}; DescribeConnectionCountRecordsResponseBody() {} explicit DescribeConnectionCountRecordsResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (accessIpRecords) { vector<boost::any> temp1; for(auto item1:*accessIpRecords){ temp1.push_back(boost::any(item1.toMap())); } res["AccessIpRecords"] = boost::any(temp1); } if (userRecords) { vector<boost::any> temp1; for(auto item1:*userRecords){ temp1.push_back(boost::any(item1.toMap())); } res["UserRecords"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("AccessIpRecords") != m.end() && !m["AccessIpRecords"].empty()) { if (typeid(vector<boost::any>) == m["AccessIpRecords"].type()) { vector<DescribeConnectionCountRecordsResponseBodyAccessIpRecords> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["AccessIpRecords"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeConnectionCountRecordsResponseBodyAccessIpRecords model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } accessIpRecords = make_shared<vector<DescribeConnectionCountRecordsResponseBodyAccessIpRecords>>(expect1); } } if (m.find("UserRecords") != m.end() && !m["UserRecords"].empty()) { if (typeid(vector<boost::any>) == m["UserRecords"].type()) { vector<DescribeConnectionCountRecordsResponseBodyUserRecords> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["UserRecords"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeConnectionCountRecordsResponseBodyUserRecords model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } userRecords = make_shared<vector<DescribeConnectionCountRecordsResponseBodyUserRecords>>(expect1); } } } virtual ~DescribeConnectionCountRecordsResponseBody() = default; }; class DescribeConnectionCountRecordsResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeConnectionCountRecordsResponseBody> body{}; DescribeConnectionCountRecordsResponse() {} explicit DescribeConnectionCountRecordsResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeConnectionCountRecordsResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeConnectionCountRecordsResponseBody>(model1); } } } virtual ~DescribeConnectionCountRecordsResponse() = default; }; class DescribeDBClusterAccessWhiteListRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; DescribeDBClusterAccessWhiteListRequest() {} explicit DescribeDBClusterAccessWhiteListRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } } virtual ~DescribeDBClusterAccessWhiteListRequest() = default; }; class DescribeDBClusterAccessWhiteListResponseBodyItemsIPArray : public Darabonba::Model { public: shared_ptr<string> DBClusterIPArrayName{}; shared_ptr<string> DBClusterIPArrayAttribute{}; shared_ptr<string> securityIPList{}; DescribeDBClusterAccessWhiteListResponseBodyItemsIPArray() {} explicit DescribeDBClusterAccessWhiteListResponseBodyItemsIPArray(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (DBClusterIPArrayName) { res["DBClusterIPArrayName"] = boost::any(*DBClusterIPArrayName); } if (DBClusterIPArrayAttribute) { res["DBClusterIPArrayAttribute"] = boost::any(*DBClusterIPArrayAttribute); } if (securityIPList) { res["SecurityIPList"] = boost::any(*securityIPList); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("DBClusterIPArrayName") != m.end() && !m["DBClusterIPArrayName"].empty()) { DBClusterIPArrayName = make_shared<string>(boost::any_cast<string>(m["DBClusterIPArrayName"])); } if (m.find("DBClusterIPArrayAttribute") != m.end() && !m["DBClusterIPArrayAttribute"].empty()) { DBClusterIPArrayAttribute = make_shared<string>(boost::any_cast<string>(m["DBClusterIPArrayAttribute"])); } if (m.find("SecurityIPList") != m.end() && !m["SecurityIPList"].empty()) { securityIPList = make_shared<string>(boost::any_cast<string>(m["SecurityIPList"])); } } virtual ~DescribeDBClusterAccessWhiteListResponseBodyItemsIPArray() = default; }; class DescribeDBClusterAccessWhiteListResponseBodyItems : public Darabonba::Model { public: shared_ptr<vector<DescribeDBClusterAccessWhiteListResponseBodyItemsIPArray>> IPArray{}; DescribeDBClusterAccessWhiteListResponseBodyItems() {} explicit DescribeDBClusterAccessWhiteListResponseBodyItems(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (IPArray) { vector<boost::any> temp1; for(auto item1:*IPArray){ temp1.push_back(boost::any(item1.toMap())); } res["IPArray"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("IPArray") != m.end() && !m["IPArray"].empty()) { if (typeid(vector<boost::any>) == m["IPArray"].type()) { vector<DescribeDBClusterAccessWhiteListResponseBodyItemsIPArray> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["IPArray"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeDBClusterAccessWhiteListResponseBodyItemsIPArray model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } IPArray = make_shared<vector<DescribeDBClusterAccessWhiteListResponseBodyItemsIPArray>>(expect1); } } } virtual ~DescribeDBClusterAccessWhiteListResponseBodyItems() = default; }; class DescribeDBClusterAccessWhiteListResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; shared_ptr<DescribeDBClusterAccessWhiteListResponseBodyItems> items{}; DescribeDBClusterAccessWhiteListResponseBody() {} explicit DescribeDBClusterAccessWhiteListResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } if (items) { res["Items"] = items ? boost::any(items->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("Items") != m.end() && !m["Items"].empty()) { if (typeid(map<string, boost::any>) == m["Items"].type()) { DescribeDBClusterAccessWhiteListResponseBodyItems model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Items"])); items = make_shared<DescribeDBClusterAccessWhiteListResponseBodyItems>(model1); } } } virtual ~DescribeDBClusterAccessWhiteListResponseBody() = default; }; class DescribeDBClusterAccessWhiteListResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeDBClusterAccessWhiteListResponseBody> body{}; DescribeDBClusterAccessWhiteListResponse() {} explicit DescribeDBClusterAccessWhiteListResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeDBClusterAccessWhiteListResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeDBClusterAccessWhiteListResponseBody>(model1); } } } virtual ~DescribeDBClusterAccessWhiteListResponse() = default; }; class DescribeDBClusterAttributeRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; DescribeDBClusterAttributeRequest() {} explicit DescribeDBClusterAttributeRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } } virtual ~DescribeDBClusterAttributeRequest() = default; }; class DescribeDBClusterAttributeResponseBodyItemsDBClusterTagsTag : public Darabonba::Model { public: shared_ptr<string> key{}; shared_ptr<string> value{}; DescribeDBClusterAttributeResponseBodyItemsDBClusterTagsTag() {} explicit DescribeDBClusterAttributeResponseBodyItemsDBClusterTagsTag(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (key) { res["Key"] = boost::any(*key); } if (value) { res["Value"] = boost::any(*value); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Key") != m.end() && !m["Key"].empty()) { key = make_shared<string>(boost::any_cast<string>(m["Key"])); } if (m.find("Value") != m.end() && !m["Value"].empty()) { value = make_shared<string>(boost::any_cast<string>(m["Value"])); } } virtual ~DescribeDBClusterAttributeResponseBodyItemsDBClusterTagsTag() = default; }; class DescribeDBClusterAttributeResponseBodyItemsDBClusterTags : public Darabonba::Model { public: shared_ptr<vector<DescribeDBClusterAttributeResponseBodyItemsDBClusterTagsTag>> tag{}; DescribeDBClusterAttributeResponseBodyItemsDBClusterTags() {} explicit DescribeDBClusterAttributeResponseBodyItemsDBClusterTags(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (tag) { vector<boost::any> temp1; for(auto item1:*tag){ temp1.push_back(boost::any(item1.toMap())); } res["Tag"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Tag") != m.end() && !m["Tag"].empty()) { if (typeid(vector<boost::any>) == m["Tag"].type()) { vector<DescribeDBClusterAttributeResponseBodyItemsDBClusterTagsTag> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["Tag"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeDBClusterAttributeResponseBodyItemsDBClusterTagsTag model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } tag = make_shared<vector<DescribeDBClusterAttributeResponseBodyItemsDBClusterTagsTag>>(expect1); } } } virtual ~DescribeDBClusterAttributeResponseBodyItemsDBClusterTags() = default; }; class DescribeDBClusterAttributeResponseBodyItemsDBCluster : public Darabonba::Model { public: shared_ptr<string> creationTime{}; shared_ptr<bool> enableSpark{}; shared_ptr<string> dtsJobId{}; shared_ptr<long> DBNodeCount{}; shared_ptr<string> expired{}; shared_ptr<string> maintainTime{}; shared_ptr<string> payType{}; shared_ptr<string> diskType{}; shared_ptr<DescribeDBClusterAttributeResponseBodyItemsDBClusterTags> tags{}; shared_ptr<string> mode{}; shared_ptr<long> port{}; shared_ptr<string> lockMode{}; shared_ptr<string> engineVersion{}; shared_ptr<bool> enableAirflow{}; shared_ptr<string> executorCount{}; shared_ptr<string> storageResource{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> connectionString{}; shared_ptr<string> rdsInstanceId{}; shared_ptr<string> DBClusterType{}; shared_ptr<string> commodityCode{}; shared_ptr<string> expireTime{}; shared_ptr<long> DBNodeStorage{}; shared_ptr<string> DBNodeClass{}; shared_ptr<string> lockReason{}; shared_ptr<string> VPCId{}; shared_ptr<string> computeResource{}; shared_ptr<string> regionId{}; shared_ptr<long> elasticIOResource{}; shared_ptr<string> vSwitchId{}; shared_ptr<string> DBVersion{}; shared_ptr<string> VPCCloudInstanceId{}; shared_ptr<string> DBClusterStatus{}; shared_ptr<string> resourceGroupId{}; shared_ptr<string> DBClusterNetworkType{}; shared_ptr<string> DBClusterDescription{}; shared_ptr<bool> userENIStatus{}; shared_ptr<string> zoneId{}; shared_ptr<string> category{}; shared_ptr<string> engine{}; shared_ptr<string> kmsId{}; DescribeDBClusterAttributeResponseBodyItemsDBCluster() {} explicit DescribeDBClusterAttributeResponseBodyItemsDBCluster(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (creationTime) { res["CreationTime"] = boost::any(*creationTime); } if (enableSpark) { res["EnableSpark"] = boost::any(*enableSpark); } if (dtsJobId) { res["DtsJobId"] = boost::any(*dtsJobId); } if (DBNodeCount) { res["DBNodeCount"] = boost::any(*DBNodeCount); } if (expired) { res["Expired"] = boost::any(*expired); } if (maintainTime) { res["MaintainTime"] = boost::any(*maintainTime); } if (payType) { res["PayType"] = boost::any(*payType); } if (diskType) { res["DiskType"] = boost::any(*diskType); } if (tags) { res["Tags"] = tags ? boost::any(tags->toMap()) : boost::any(map<string,boost::any>({})); } if (mode) { res["Mode"] = boost::any(*mode); } if (port) { res["Port"] = boost::any(*port); } if (lockMode) { res["LockMode"] = boost::any(*lockMode); } if (engineVersion) { res["EngineVersion"] = boost::any(*engineVersion); } if (enableAirflow) { res["EnableAirflow"] = boost::any(*enableAirflow); } if (executorCount) { res["ExecutorCount"] = boost::any(*executorCount); } if (storageResource) { res["StorageResource"] = boost::any(*storageResource); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (connectionString) { res["ConnectionString"] = boost::any(*connectionString); } if (rdsInstanceId) { res["RdsInstanceId"] = boost::any(*rdsInstanceId); } if (DBClusterType) { res["DBClusterType"] = boost::any(*DBClusterType); } if (commodityCode) { res["CommodityCode"] = boost::any(*commodityCode); } if (expireTime) { res["ExpireTime"] = boost::any(*expireTime); } if (DBNodeStorage) { res["DBNodeStorage"] = boost::any(*DBNodeStorage); } if (DBNodeClass) { res["DBNodeClass"] = boost::any(*DBNodeClass); } if (lockReason) { res["LockReason"] = boost::any(*lockReason); } if (VPCId) { res["VPCId"] = boost::any(*VPCId); } if (computeResource) { res["ComputeResource"] = boost::any(*computeResource); } if (regionId) { res["RegionId"] = boost::any(*regionId); } if (elasticIOResource) { res["ElasticIOResource"] = boost::any(*elasticIOResource); } if (vSwitchId) { res["VSwitchId"] = boost::any(*vSwitchId); } if (DBVersion) { res["DBVersion"] = boost::any(*DBVersion); } if (VPCCloudInstanceId) { res["VPCCloudInstanceId"] = boost::any(*VPCCloudInstanceId); } if (DBClusterStatus) { res["DBClusterStatus"] = boost::any(*DBClusterStatus); } if (resourceGroupId) { res["ResourceGroupId"] = boost::any(*resourceGroupId); } if (DBClusterNetworkType) { res["DBClusterNetworkType"] = boost::any(*DBClusterNetworkType); } if (DBClusterDescription) { res["DBClusterDescription"] = boost::any(*DBClusterDescription); } if (userENIStatus) { res["UserENIStatus"] = boost::any(*userENIStatus); } if (zoneId) { res["ZoneId"] = boost::any(*zoneId); } if (category) { res["Category"] = boost::any(*category); } if (engine) { res["Engine"] = boost::any(*engine); } if (kmsId) { res["KmsId"] = boost::any(*kmsId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("CreationTime") != m.end() && !m["CreationTime"].empty()) { creationTime = make_shared<string>(boost::any_cast<string>(m["CreationTime"])); } if (m.find("EnableSpark") != m.end() && !m["EnableSpark"].empty()) { enableSpark = make_shared<bool>(boost::any_cast<bool>(m["EnableSpark"])); } if (m.find("DtsJobId") != m.end() && !m["DtsJobId"].empty()) { dtsJobId = make_shared<string>(boost::any_cast<string>(m["DtsJobId"])); } if (m.find("DBNodeCount") != m.end() && !m["DBNodeCount"].empty()) { DBNodeCount = make_shared<long>(boost::any_cast<long>(m["DBNodeCount"])); } if (m.find("Expired") != m.end() && !m["Expired"].empty()) { expired = make_shared<string>(boost::any_cast<string>(m["Expired"])); } if (m.find("MaintainTime") != m.end() && !m["MaintainTime"].empty()) { maintainTime = make_shared<string>(boost::any_cast<string>(m["MaintainTime"])); } if (m.find("PayType") != m.end() && !m["PayType"].empty()) { payType = make_shared<string>(boost::any_cast<string>(m["PayType"])); } if (m.find("DiskType") != m.end() && !m["DiskType"].empty()) { diskType = make_shared<string>(boost::any_cast<string>(m["DiskType"])); } if (m.find("Tags") != m.end() && !m["Tags"].empty()) { if (typeid(map<string, boost::any>) == m["Tags"].type()) { DescribeDBClusterAttributeResponseBodyItemsDBClusterTags model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Tags"])); tags = make_shared<DescribeDBClusterAttributeResponseBodyItemsDBClusterTags>(model1); } } if (m.find("Mode") != m.end() && !m["Mode"].empty()) { mode = make_shared<string>(boost::any_cast<string>(m["Mode"])); } if (m.find("Port") != m.end() && !m["Port"].empty()) { port = make_shared<long>(boost::any_cast<long>(m["Port"])); } if (m.find("LockMode") != m.end() && !m["LockMode"].empty()) { lockMode = make_shared<string>(boost::any_cast<string>(m["LockMode"])); } if (m.find("EngineVersion") != m.end() && !m["EngineVersion"].empty()) { engineVersion = make_shared<string>(boost::any_cast<string>(m["EngineVersion"])); } if (m.find("EnableAirflow") != m.end() && !m["EnableAirflow"].empty()) { enableAirflow = make_shared<bool>(boost::any_cast<bool>(m["EnableAirflow"])); } if (m.find("ExecutorCount") != m.end() && !m["ExecutorCount"].empty()) { executorCount = make_shared<string>(boost::any_cast<string>(m["ExecutorCount"])); } if (m.find("StorageResource") != m.end() && !m["StorageResource"].empty()) { storageResource = make_shared<string>(boost::any_cast<string>(m["StorageResource"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("ConnectionString") != m.end() && !m["ConnectionString"].empty()) { connectionString = make_shared<string>(boost::any_cast<string>(m["ConnectionString"])); } if (m.find("RdsInstanceId") != m.end() && !m["RdsInstanceId"].empty()) { rdsInstanceId = make_shared<string>(boost::any_cast<string>(m["RdsInstanceId"])); } if (m.find("DBClusterType") != m.end() && !m["DBClusterType"].empty()) { DBClusterType = make_shared<string>(boost::any_cast<string>(m["DBClusterType"])); } if (m.find("CommodityCode") != m.end() && !m["CommodityCode"].empty()) { commodityCode = make_shared<string>(boost::any_cast<string>(m["CommodityCode"])); } if (m.find("ExpireTime") != m.end() && !m["ExpireTime"].empty()) { expireTime = make_shared<string>(boost::any_cast<string>(m["ExpireTime"])); } if (m.find("DBNodeStorage") != m.end() && !m["DBNodeStorage"].empty()) { DBNodeStorage = make_shared<long>(boost::any_cast<long>(m["DBNodeStorage"])); } if (m.find("DBNodeClass") != m.end() && !m["DBNodeClass"].empty()) { DBNodeClass = make_shared<string>(boost::any_cast<string>(m["DBNodeClass"])); } if (m.find("LockReason") != m.end() && !m["LockReason"].empty()) { lockReason = make_shared<string>(boost::any_cast<string>(m["LockReason"])); } if (m.find("VPCId") != m.end() && !m["VPCId"].empty()) { VPCId = make_shared<string>(boost::any_cast<string>(m["VPCId"])); } if (m.find("ComputeResource") != m.end() && !m["ComputeResource"].empty()) { computeResource = make_shared<string>(boost::any_cast<string>(m["ComputeResource"])); } if (m.find("RegionId") != m.end() && !m["RegionId"].empty()) { regionId = make_shared<string>(boost::any_cast<string>(m["RegionId"])); } if (m.find("ElasticIOResource") != m.end() && !m["ElasticIOResource"].empty()) { elasticIOResource = make_shared<long>(boost::any_cast<long>(m["ElasticIOResource"])); } if (m.find("VSwitchId") != m.end() && !m["VSwitchId"].empty()) { vSwitchId = make_shared<string>(boost::any_cast<string>(m["VSwitchId"])); } if (m.find("DBVersion") != m.end() && !m["DBVersion"].empty()) { DBVersion = make_shared<string>(boost::any_cast<string>(m["DBVersion"])); } if (m.find("VPCCloudInstanceId") != m.end() && !m["VPCCloudInstanceId"].empty()) { VPCCloudInstanceId = make_shared<string>(boost::any_cast<string>(m["VPCCloudInstanceId"])); } if (m.find("DBClusterStatus") != m.end() && !m["DBClusterStatus"].empty()) { DBClusterStatus = make_shared<string>(boost::any_cast<string>(m["DBClusterStatus"])); } if (m.find("ResourceGroupId") != m.end() && !m["ResourceGroupId"].empty()) { resourceGroupId = make_shared<string>(boost::any_cast<string>(m["ResourceGroupId"])); } if (m.find("DBClusterNetworkType") != m.end() && !m["DBClusterNetworkType"].empty()) { DBClusterNetworkType = make_shared<string>(boost::any_cast<string>(m["DBClusterNetworkType"])); } if (m.find("DBClusterDescription") != m.end() && !m["DBClusterDescription"].empty()) { DBClusterDescription = make_shared<string>(boost::any_cast<string>(m["DBClusterDescription"])); } if (m.find("UserENIStatus") != m.end() && !m["UserENIStatus"].empty()) { userENIStatus = make_shared<bool>(boost::any_cast<bool>(m["UserENIStatus"])); } if (m.find("ZoneId") != m.end() && !m["ZoneId"].empty()) { zoneId = make_shared<string>(boost::any_cast<string>(m["ZoneId"])); } if (m.find("Category") != m.end() && !m["Category"].empty()) { category = make_shared<string>(boost::any_cast<string>(m["Category"])); } if (m.find("Engine") != m.end() && !m["Engine"].empty()) { engine = make_shared<string>(boost::any_cast<string>(m["Engine"])); } if (m.find("KmsId") != m.end() && !m["KmsId"].empty()) { kmsId = make_shared<string>(boost::any_cast<string>(m["KmsId"])); } } virtual ~DescribeDBClusterAttributeResponseBodyItemsDBCluster() = default; }; class DescribeDBClusterAttributeResponseBodyItems : public Darabonba::Model { public: shared_ptr<vector<DescribeDBClusterAttributeResponseBodyItemsDBCluster>> DBCluster{}; DescribeDBClusterAttributeResponseBodyItems() {} explicit DescribeDBClusterAttributeResponseBodyItems(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (DBCluster) { vector<boost::any> temp1; for(auto item1:*DBCluster){ temp1.push_back(boost::any(item1.toMap())); } res["DBCluster"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("DBCluster") != m.end() && !m["DBCluster"].empty()) { if (typeid(vector<boost::any>) == m["DBCluster"].type()) { vector<DescribeDBClusterAttributeResponseBodyItemsDBCluster> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["DBCluster"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeDBClusterAttributeResponseBodyItemsDBCluster model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } DBCluster = make_shared<vector<DescribeDBClusterAttributeResponseBodyItemsDBCluster>>(expect1); } } } virtual ~DescribeDBClusterAttributeResponseBodyItems() = default; }; class DescribeDBClusterAttributeResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; shared_ptr<DescribeDBClusterAttributeResponseBodyItems> items{}; DescribeDBClusterAttributeResponseBody() {} explicit DescribeDBClusterAttributeResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } if (items) { res["Items"] = items ? boost::any(items->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("Items") != m.end() && !m["Items"].empty()) { if (typeid(map<string, boost::any>) == m["Items"].type()) { DescribeDBClusterAttributeResponseBodyItems model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Items"])); items = make_shared<DescribeDBClusterAttributeResponseBodyItems>(model1); } } } virtual ~DescribeDBClusterAttributeResponseBody() = default; }; class DescribeDBClusterAttributeResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeDBClusterAttributeResponseBody> body{}; DescribeDBClusterAttributeResponse() {} explicit DescribeDBClusterAttributeResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeDBClusterAttributeResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeDBClusterAttributeResponseBody>(model1); } } } virtual ~DescribeDBClusterAttributeResponse() = default; }; class DescribeDBClusterForecastRequest : public Darabonba::Model { public: shared_ptr<string> startTime{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> regionId{}; shared_ptr<string> metricType{}; DescribeDBClusterForecastRequest() {} explicit DescribeDBClusterForecastRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (startTime) { res["StartTime"] = boost::any(*startTime); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (regionId) { res["RegionId"] = boost::any(*regionId); } if (metricType) { res["MetricType"] = boost::any(*metricType); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("StartTime") != m.end() && !m["StartTime"].empty()) { startTime = make_shared<string>(boost::any_cast<string>(m["StartTime"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("RegionId") != m.end() && !m["RegionId"].empty()) { regionId = make_shared<string>(boost::any_cast<string>(m["RegionId"])); } if (m.find("MetricType") != m.end() && !m["MetricType"].empty()) { metricType = make_shared<string>(boost::any_cast<string>(m["MetricType"])); } } virtual ~DescribeDBClusterForecastRequest() = default; }; class DescribeDBClusterForecastResponseBodyPerformancesSeries : public Darabonba::Model { public: shared_ptr<string> name{}; shared_ptr<string> values{}; DescribeDBClusterForecastResponseBodyPerformancesSeries() {} explicit DescribeDBClusterForecastResponseBodyPerformancesSeries(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (name) { res["Name"] = boost::any(*name); } if (values) { res["Values"] = boost::any(*values); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Name") != m.end() && !m["Name"].empty()) { name = make_shared<string>(boost::any_cast<string>(m["Name"])); } if (m.find("Values") != m.end() && !m["Values"].empty()) { values = make_shared<string>(boost::any_cast<string>(m["Values"])); } } virtual ~DescribeDBClusterForecastResponseBodyPerformancesSeries() = default; }; class DescribeDBClusterForecastResponseBodyPerformances : public Darabonba::Model { public: shared_ptr<string> key{}; shared_ptr<string> unit{}; shared_ptr<vector<DescribeDBClusterForecastResponseBodyPerformancesSeries>> series{}; DescribeDBClusterForecastResponseBodyPerformances() {} explicit DescribeDBClusterForecastResponseBodyPerformances(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (key) { res["Key"] = boost::any(*key); } if (unit) { res["Unit"] = boost::any(*unit); } if (series) { vector<boost::any> temp1; for(auto item1:*series){ temp1.push_back(boost::any(item1.toMap())); } res["Series"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Key") != m.end() && !m["Key"].empty()) { key = make_shared<string>(boost::any_cast<string>(m["Key"])); } if (m.find("Unit") != m.end() && !m["Unit"].empty()) { unit = make_shared<string>(boost::any_cast<string>(m["Unit"])); } if (m.find("Series") != m.end() && !m["Series"].empty()) { if (typeid(vector<boost::any>) == m["Series"].type()) { vector<DescribeDBClusterForecastResponseBodyPerformancesSeries> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["Series"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeDBClusterForecastResponseBodyPerformancesSeries model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } series = make_shared<vector<DescribeDBClusterForecastResponseBodyPerformancesSeries>>(expect1); } } } virtual ~DescribeDBClusterForecastResponseBodyPerformances() = default; }; class DescribeDBClusterForecastResponseBody : public Darabonba::Model { public: shared_ptr<vector<DescribeDBClusterForecastResponseBodyPerformances>> performances{}; shared_ptr<string> requestId{}; DescribeDBClusterForecastResponseBody() {} explicit DescribeDBClusterForecastResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (performances) { vector<boost::any> temp1; for(auto item1:*performances){ temp1.push_back(boost::any(item1.toMap())); } res["Performances"] = boost::any(temp1); } if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Performances") != m.end() && !m["Performances"].empty()) { if (typeid(vector<boost::any>) == m["Performances"].type()) { vector<DescribeDBClusterForecastResponseBodyPerformances> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["Performances"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeDBClusterForecastResponseBodyPerformances model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } performances = make_shared<vector<DescribeDBClusterForecastResponseBodyPerformances>>(expect1); } } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~DescribeDBClusterForecastResponseBody() = default; }; class DescribeDBClusterForecastResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeDBClusterForecastResponseBody> body{}; DescribeDBClusterForecastResponse() {} explicit DescribeDBClusterForecastResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeDBClusterForecastResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeDBClusterForecastResponseBody>(model1); } } } virtual ~DescribeDBClusterForecastResponse() = default; }; class DescribeDBClusterHealthReportRequest : public Darabonba::Model { public: shared_ptr<string> startTime{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> regionId{}; DescribeDBClusterHealthReportRequest() {} explicit DescribeDBClusterHealthReportRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (startTime) { res["StartTime"] = boost::any(*startTime); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (regionId) { res["RegionId"] = boost::any(*regionId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("StartTime") != m.end() && !m["StartTime"].empty()) { startTime = make_shared<string>(boost::any_cast<string>(m["StartTime"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("RegionId") != m.end() && !m["RegionId"].empty()) { regionId = make_shared<string>(boost::any_cast<string>(m["RegionId"])); } } virtual ~DescribeDBClusterHealthReportRequest() = default; }; class DescribeDBClusterHealthReportResponseBodyItems : public Darabonba::Model { public: shared_ptr<string> key{}; shared_ptr<string> max{}; shared_ptr<string> name{}; shared_ptr<string> avg{}; DescribeDBClusterHealthReportResponseBodyItems() {} explicit DescribeDBClusterHealthReportResponseBodyItems(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (key) { res["Key"] = boost::any(*key); } if (max) { res["Max"] = boost::any(*max); } if (name) { res["Name"] = boost::any(*name); } if (avg) { res["Avg"] = boost::any(*avg); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Key") != m.end() && !m["Key"].empty()) { key = make_shared<string>(boost::any_cast<string>(m["Key"])); } if (m.find("Max") != m.end() && !m["Max"].empty()) { max = make_shared<string>(boost::any_cast<string>(m["Max"])); } if (m.find("Name") != m.end() && !m["Name"].empty()) { name = make_shared<string>(boost::any_cast<string>(m["Name"])); } if (m.find("Avg") != m.end() && !m["Avg"].empty()) { avg = make_shared<string>(boost::any_cast<string>(m["Avg"])); } } virtual ~DescribeDBClusterHealthReportResponseBodyItems() = default; }; class DescribeDBClusterHealthReportResponseBody : public Darabonba::Model { public: shared_ptr<vector<DescribeDBClusterHealthReportResponseBodyItems>> items{}; shared_ptr<string> requestId{}; DescribeDBClusterHealthReportResponseBody() {} explicit DescribeDBClusterHealthReportResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (items) { vector<boost::any> temp1; for(auto item1:*items){ temp1.push_back(boost::any(item1.toMap())); } res["Items"] = boost::any(temp1); } if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Items") != m.end() && !m["Items"].empty()) { if (typeid(vector<boost::any>) == m["Items"].type()) { vector<DescribeDBClusterHealthReportResponseBodyItems> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["Items"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeDBClusterHealthReportResponseBodyItems model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } items = make_shared<vector<DescribeDBClusterHealthReportResponseBodyItems>>(expect1); } } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~DescribeDBClusterHealthReportResponseBody() = default; }; class DescribeDBClusterHealthReportResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeDBClusterHealthReportResponseBody> body{}; DescribeDBClusterHealthReportResponse() {} explicit DescribeDBClusterHealthReportResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeDBClusterHealthReportResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeDBClusterHealthReportResponseBody>(model1); } } } virtual ~DescribeDBClusterHealthReportResponse() = default; }; class DescribeDBClusterNetInfoRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; DescribeDBClusterNetInfoRequest() {} explicit DescribeDBClusterNetInfoRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } } virtual ~DescribeDBClusterNetInfoRequest() = default; }; class DescribeDBClusterNetInfoResponseBodyItemsAddress : public Darabonba::Model { public: shared_ptr<string> vSwitchId{}; shared_ptr<string> connectionString{}; shared_ptr<string> netType{}; shared_ptr<string> port{}; shared_ptr<string> VPCId{}; shared_ptr<string> IPAddress{}; shared_ptr<string> connectionStringPrefix{}; DescribeDBClusterNetInfoResponseBodyItemsAddress() {} explicit DescribeDBClusterNetInfoResponseBodyItemsAddress(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (vSwitchId) { res["VSwitchId"] = boost::any(*vSwitchId); } if (connectionString) { res["ConnectionString"] = boost::any(*connectionString); } if (netType) { res["NetType"] = boost::any(*netType); } if (port) { res["Port"] = boost::any(*port); } if (VPCId) { res["VPCId"] = boost::any(*VPCId); } if (IPAddress) { res["IPAddress"] = boost::any(*IPAddress); } if (connectionStringPrefix) { res["ConnectionStringPrefix"] = boost::any(*connectionStringPrefix); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("VSwitchId") != m.end() && !m["VSwitchId"].empty()) { vSwitchId = make_shared<string>(boost::any_cast<string>(m["VSwitchId"])); } if (m.find("ConnectionString") != m.end() && !m["ConnectionString"].empty()) { connectionString = make_shared<string>(boost::any_cast<string>(m["ConnectionString"])); } if (m.find("NetType") != m.end() && !m["NetType"].empty()) { netType = make_shared<string>(boost::any_cast<string>(m["NetType"])); } if (m.find("Port") != m.end() && !m["Port"].empty()) { port = make_shared<string>(boost::any_cast<string>(m["Port"])); } if (m.find("VPCId") != m.end() && !m["VPCId"].empty()) { VPCId = make_shared<string>(boost::any_cast<string>(m["VPCId"])); } if (m.find("IPAddress") != m.end() && !m["IPAddress"].empty()) { IPAddress = make_shared<string>(boost::any_cast<string>(m["IPAddress"])); } if (m.find("ConnectionStringPrefix") != m.end() && !m["ConnectionStringPrefix"].empty()) { connectionStringPrefix = make_shared<string>(boost::any_cast<string>(m["ConnectionStringPrefix"])); } } virtual ~DescribeDBClusterNetInfoResponseBodyItemsAddress() = default; }; class DescribeDBClusterNetInfoResponseBodyItems : public Darabonba::Model { public: shared_ptr<vector<DescribeDBClusterNetInfoResponseBodyItemsAddress>> address{}; DescribeDBClusterNetInfoResponseBodyItems() {} explicit DescribeDBClusterNetInfoResponseBodyItems(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (address) { vector<boost::any> temp1; for(auto item1:*address){ temp1.push_back(boost::any(item1.toMap())); } res["Address"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Address") != m.end() && !m["Address"].empty()) { if (typeid(vector<boost::any>) == m["Address"].type()) { vector<DescribeDBClusterNetInfoResponseBodyItemsAddress> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["Address"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeDBClusterNetInfoResponseBodyItemsAddress model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } address = make_shared<vector<DescribeDBClusterNetInfoResponseBodyItemsAddress>>(expect1); } } } virtual ~DescribeDBClusterNetInfoResponseBodyItems() = default; }; class DescribeDBClusterNetInfoResponseBody : public Darabonba::Model { public: shared_ptr<string> clusterNetworkType{}; shared_ptr<string> requestId{}; shared_ptr<DescribeDBClusterNetInfoResponseBodyItems> items{}; DescribeDBClusterNetInfoResponseBody() {} explicit DescribeDBClusterNetInfoResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (clusterNetworkType) { res["ClusterNetworkType"] = boost::any(*clusterNetworkType); } if (requestId) { res["RequestId"] = boost::any(*requestId); } if (items) { res["Items"] = items ? boost::any(items->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ClusterNetworkType") != m.end() && !m["ClusterNetworkType"].empty()) { clusterNetworkType = make_shared<string>(boost::any_cast<string>(m["ClusterNetworkType"])); } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("Items") != m.end() && !m["Items"].empty()) { if (typeid(map<string, boost::any>) == m["Items"].type()) { DescribeDBClusterNetInfoResponseBodyItems model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Items"])); items = make_shared<DescribeDBClusterNetInfoResponseBodyItems>(model1); } } } virtual ~DescribeDBClusterNetInfoResponseBody() = default; }; class DescribeDBClusterNetInfoResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeDBClusterNetInfoResponseBody> body{}; DescribeDBClusterNetInfoResponse() {} explicit DescribeDBClusterNetInfoResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeDBClusterNetInfoResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeDBClusterNetInfoResponseBody>(model1); } } } virtual ~DescribeDBClusterNetInfoResponse() = default; }; class DescribeDBClusterPerformanceRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> key{}; shared_ptr<string> startTime{}; shared_ptr<string> endTime{}; DescribeDBClusterPerformanceRequest() {} explicit DescribeDBClusterPerformanceRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (key) { res["Key"] = boost::any(*key); } if (startTime) { res["StartTime"] = boost::any(*startTime); } if (endTime) { res["EndTime"] = boost::any(*endTime); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("Key") != m.end() && !m["Key"].empty()) { key = make_shared<string>(boost::any_cast<string>(m["Key"])); } if (m.find("StartTime") != m.end() && !m["StartTime"].empty()) { startTime = make_shared<string>(boost::any_cast<string>(m["StartTime"])); } if (m.find("EndTime") != m.end() && !m["EndTime"].empty()) { endTime = make_shared<string>(boost::any_cast<string>(m["EndTime"])); } } virtual ~DescribeDBClusterPerformanceRequest() = default; }; class DescribeDBClusterPerformanceResponseBodyPerformancesSeries : public Darabonba::Model { public: shared_ptr<vector<string>> values{}; shared_ptr<string> name{}; DescribeDBClusterPerformanceResponseBodyPerformancesSeries() {} explicit DescribeDBClusterPerformanceResponseBodyPerformancesSeries(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (values) { res["Values"] = boost::any(*values); } if (name) { res["Name"] = boost::any(*name); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Values") != m.end() && !m["Values"].empty()) { vector<string> toVec1; if (typeid(vector<boost::any>) == m["Values"].type()) { vector<boost::any> vec1 = boost::any_cast<vector<boost::any>>(m["Values"]); for (auto item:vec1) { toVec1.push_back(boost::any_cast<string>(item)); } } values = make_shared<vector<string>>(toVec1); } if (m.find("Name") != m.end() && !m["Name"].empty()) { name = make_shared<string>(boost::any_cast<string>(m["Name"])); } } virtual ~DescribeDBClusterPerformanceResponseBodyPerformancesSeries() = default; }; class DescribeDBClusterPerformanceResponseBodyPerformances : public Darabonba::Model { public: shared_ptr<string> key{}; shared_ptr<string> unit{}; shared_ptr<vector<DescribeDBClusterPerformanceResponseBodyPerformancesSeries>> series{}; DescribeDBClusterPerformanceResponseBodyPerformances() {} explicit DescribeDBClusterPerformanceResponseBodyPerformances(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (key) { res["Key"] = boost::any(*key); } if (unit) { res["Unit"] = boost::any(*unit); } if (series) { vector<boost::any> temp1; for(auto item1:*series){ temp1.push_back(boost::any(item1.toMap())); } res["Series"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Key") != m.end() && !m["Key"].empty()) { key = make_shared<string>(boost::any_cast<string>(m["Key"])); } if (m.find("Unit") != m.end() && !m["Unit"].empty()) { unit = make_shared<string>(boost::any_cast<string>(m["Unit"])); } if (m.find("Series") != m.end() && !m["Series"].empty()) { if (typeid(vector<boost::any>) == m["Series"].type()) { vector<DescribeDBClusterPerformanceResponseBodyPerformancesSeries> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["Series"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeDBClusterPerformanceResponseBodyPerformancesSeries model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } series = make_shared<vector<DescribeDBClusterPerformanceResponseBodyPerformancesSeries>>(expect1); } } } virtual ~DescribeDBClusterPerformanceResponseBodyPerformances() = default; }; class DescribeDBClusterPerformanceResponseBody : public Darabonba::Model { public: shared_ptr<string> endTime{}; shared_ptr<string> requestId{}; shared_ptr<string> startTime{}; shared_ptr<string> DBClusterId{}; shared_ptr<vector<DescribeDBClusterPerformanceResponseBodyPerformances>> performances{}; DescribeDBClusterPerformanceResponseBody() {} explicit DescribeDBClusterPerformanceResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (endTime) { res["EndTime"] = boost::any(*endTime); } if (requestId) { res["RequestId"] = boost::any(*requestId); } if (startTime) { res["StartTime"] = boost::any(*startTime); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (performances) { vector<boost::any> temp1; for(auto item1:*performances){ temp1.push_back(boost::any(item1.toMap())); } res["Performances"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("EndTime") != m.end() && !m["EndTime"].empty()) { endTime = make_shared<string>(boost::any_cast<string>(m["EndTime"])); } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("StartTime") != m.end() && !m["StartTime"].empty()) { startTime = make_shared<string>(boost::any_cast<string>(m["StartTime"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("Performances") != m.end() && !m["Performances"].empty()) { if (typeid(vector<boost::any>) == m["Performances"].type()) { vector<DescribeDBClusterPerformanceResponseBodyPerformances> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["Performances"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeDBClusterPerformanceResponseBodyPerformances model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } performances = make_shared<vector<DescribeDBClusterPerformanceResponseBodyPerformances>>(expect1); } } } virtual ~DescribeDBClusterPerformanceResponseBody() = default; }; class DescribeDBClusterPerformanceResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeDBClusterPerformanceResponseBody> body{}; DescribeDBClusterPerformanceResponse() {} explicit DescribeDBClusterPerformanceResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeDBClusterPerformanceResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeDBClusterPerformanceResponseBody>(model1); } } } virtual ~DescribeDBClusterPerformanceResponse() = default; }; class DescribeDBClusterResourcePoolPerformanceRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> key{}; shared_ptr<string> resourcePools{}; shared_ptr<string> startTime{}; shared_ptr<string> endTime{}; DescribeDBClusterResourcePoolPerformanceRequest() {} explicit DescribeDBClusterResourcePoolPerformanceRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (key) { res["Key"] = boost::any(*key); } if (resourcePools) { res["ResourcePools"] = boost::any(*resourcePools); } if (startTime) { res["StartTime"] = boost::any(*startTime); } if (endTime) { res["EndTime"] = boost::any(*endTime); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("Key") != m.end() && !m["Key"].empty()) { key = make_shared<string>(boost::any_cast<string>(m["Key"])); } if (m.find("ResourcePools") != m.end() && !m["ResourcePools"].empty()) { resourcePools = make_shared<string>(boost::any_cast<string>(m["ResourcePools"])); } if (m.find("StartTime") != m.end() && !m["StartTime"].empty()) { startTime = make_shared<string>(boost::any_cast<string>(m["StartTime"])); } if (m.find("EndTime") != m.end() && !m["EndTime"].empty()) { endTime = make_shared<string>(boost::any_cast<string>(m["EndTime"])); } } virtual ~DescribeDBClusterResourcePoolPerformanceRequest() = default; }; class DescribeDBClusterResourcePoolPerformanceResponseBodyPerformancesResourcePoolPerformancesResourcePoolSeries : public Darabonba::Model { public: shared_ptr<vector<string>> values{}; shared_ptr<string> name{}; DescribeDBClusterResourcePoolPerformanceResponseBodyPerformancesResourcePoolPerformancesResourcePoolSeries() {} explicit DescribeDBClusterResourcePoolPerformanceResponseBodyPerformancesResourcePoolPerformancesResourcePoolSeries(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (values) { res["Values"] = boost::any(*values); } if (name) { res["Name"] = boost::any(*name); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Values") != m.end() && !m["Values"].empty()) { vector<string> toVec1; if (typeid(vector<boost::any>) == m["Values"].type()) { vector<boost::any> vec1 = boost::any_cast<vector<boost::any>>(m["Values"]); for (auto item:vec1) { toVec1.push_back(boost::any_cast<string>(item)); } } values = make_shared<vector<string>>(toVec1); } if (m.find("Name") != m.end() && !m["Name"].empty()) { name = make_shared<string>(boost::any_cast<string>(m["Name"])); } } virtual ~DescribeDBClusterResourcePoolPerformanceResponseBodyPerformancesResourcePoolPerformancesResourcePoolSeries() = default; }; class DescribeDBClusterResourcePoolPerformanceResponseBodyPerformancesResourcePoolPerformances : public Darabonba::Model { public: shared_ptr<string> resourcePoolName{}; shared_ptr<vector<DescribeDBClusterResourcePoolPerformanceResponseBodyPerformancesResourcePoolPerformancesResourcePoolSeries>> resourcePoolSeries{}; DescribeDBClusterResourcePoolPerformanceResponseBodyPerformancesResourcePoolPerformances() {} explicit DescribeDBClusterResourcePoolPerformanceResponseBodyPerformancesResourcePoolPerformances(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (resourcePoolName) { res["ResourcePoolName"] = boost::any(*resourcePoolName); } if (resourcePoolSeries) { vector<boost::any> temp1; for(auto item1:*resourcePoolSeries){ temp1.push_back(boost::any(item1.toMap())); } res["ResourcePoolSeries"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ResourcePoolName") != m.end() && !m["ResourcePoolName"].empty()) { resourcePoolName = make_shared<string>(boost::any_cast<string>(m["ResourcePoolName"])); } if (m.find("ResourcePoolSeries") != m.end() && !m["ResourcePoolSeries"].empty()) { if (typeid(vector<boost::any>) == m["ResourcePoolSeries"].type()) { vector<DescribeDBClusterResourcePoolPerformanceResponseBodyPerformancesResourcePoolPerformancesResourcePoolSeries> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["ResourcePoolSeries"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeDBClusterResourcePoolPerformanceResponseBodyPerformancesResourcePoolPerformancesResourcePoolSeries model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } resourcePoolSeries = make_shared<vector<DescribeDBClusterResourcePoolPerformanceResponseBodyPerformancesResourcePoolPerformancesResourcePoolSeries>>(expect1); } } } virtual ~DescribeDBClusterResourcePoolPerformanceResponseBodyPerformancesResourcePoolPerformances() = default; }; class DescribeDBClusterResourcePoolPerformanceResponseBodyPerformances : public Darabonba::Model { public: shared_ptr<string> key{}; shared_ptr<string> unit{}; shared_ptr<vector<DescribeDBClusterResourcePoolPerformanceResponseBodyPerformancesResourcePoolPerformances>> resourcePoolPerformances{}; DescribeDBClusterResourcePoolPerformanceResponseBodyPerformances() {} explicit DescribeDBClusterResourcePoolPerformanceResponseBodyPerformances(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (key) { res["Key"] = boost::any(*key); } if (unit) { res["Unit"] = boost::any(*unit); } if (resourcePoolPerformances) { vector<boost::any> temp1; for(auto item1:*resourcePoolPerformances){ temp1.push_back(boost::any(item1.toMap())); } res["ResourcePoolPerformances"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Key") != m.end() && !m["Key"].empty()) { key = make_shared<string>(boost::any_cast<string>(m["Key"])); } if (m.find("Unit") != m.end() && !m["Unit"].empty()) { unit = make_shared<string>(boost::any_cast<string>(m["Unit"])); } if (m.find("ResourcePoolPerformances") != m.end() && !m["ResourcePoolPerformances"].empty()) { if (typeid(vector<boost::any>) == m["ResourcePoolPerformances"].type()) { vector<DescribeDBClusterResourcePoolPerformanceResponseBodyPerformancesResourcePoolPerformances> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["ResourcePoolPerformances"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeDBClusterResourcePoolPerformanceResponseBodyPerformancesResourcePoolPerformances model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } resourcePoolPerformances = make_shared<vector<DescribeDBClusterResourcePoolPerformanceResponseBodyPerformancesResourcePoolPerformances>>(expect1); } } } virtual ~DescribeDBClusterResourcePoolPerformanceResponseBodyPerformances() = default; }; class DescribeDBClusterResourcePoolPerformanceResponseBody : public Darabonba::Model { public: shared_ptr<string> endTime{}; shared_ptr<string> requestId{}; shared_ptr<string> startTime{}; shared_ptr<string> DBClusterId{}; shared_ptr<vector<DescribeDBClusterResourcePoolPerformanceResponseBodyPerformances>> performances{}; DescribeDBClusterResourcePoolPerformanceResponseBody() {} explicit DescribeDBClusterResourcePoolPerformanceResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (endTime) { res["EndTime"] = boost::any(*endTime); } if (requestId) { res["RequestId"] = boost::any(*requestId); } if (startTime) { res["StartTime"] = boost::any(*startTime); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (performances) { vector<boost::any> temp1; for(auto item1:*performances){ temp1.push_back(boost::any(item1.toMap())); } res["Performances"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("EndTime") != m.end() && !m["EndTime"].empty()) { endTime = make_shared<string>(boost::any_cast<string>(m["EndTime"])); } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("StartTime") != m.end() && !m["StartTime"].empty()) { startTime = make_shared<string>(boost::any_cast<string>(m["StartTime"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("Performances") != m.end() && !m["Performances"].empty()) { if (typeid(vector<boost::any>) == m["Performances"].type()) { vector<DescribeDBClusterResourcePoolPerformanceResponseBodyPerformances> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["Performances"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeDBClusterResourcePoolPerformanceResponseBodyPerformances model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } performances = make_shared<vector<DescribeDBClusterResourcePoolPerformanceResponseBodyPerformances>>(expect1); } } } virtual ~DescribeDBClusterResourcePoolPerformanceResponseBody() = default; }; class DescribeDBClusterResourcePoolPerformanceResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeDBClusterResourcePoolPerformanceResponseBody> body{}; DescribeDBClusterResourcePoolPerformanceResponse() {} explicit DescribeDBClusterResourcePoolPerformanceResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeDBClusterResourcePoolPerformanceResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeDBClusterResourcePoolPerformanceResponseBody>(model1); } } } virtual ~DescribeDBClusterResourcePoolPerformanceResponse() = default; }; class DescribeDBClustersRequestTag : public Darabonba::Model { public: shared_ptr<string> key{}; shared_ptr<string> value{}; DescribeDBClustersRequestTag() {} explicit DescribeDBClustersRequestTag(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (key) { res["Key"] = boost::any(*key); } if (value) { res["Value"] = boost::any(*value); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Key") != m.end() && !m["Key"].empty()) { key = make_shared<string>(boost::any_cast<string>(m["Key"])); } if (m.find("Value") != m.end() && !m["Value"].empty()) { value = make_shared<string>(boost::any_cast<string>(m["Value"])); } } virtual ~DescribeDBClustersRequestTag() = default; }; class DescribeDBClustersRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> regionId{}; shared_ptr<string> DBClusterIds{}; shared_ptr<string> DBClusterDescription{}; shared_ptr<string> DBClusterStatus{}; shared_ptr<long> pageSize{}; shared_ptr<long> pageNumber{}; shared_ptr<string> resourceGroupId{}; shared_ptr<vector<DescribeDBClustersRequestTag>> tag{}; DescribeDBClustersRequest() {} explicit DescribeDBClustersRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (regionId) { res["RegionId"] = boost::any(*regionId); } if (DBClusterIds) { res["DBClusterIds"] = boost::any(*DBClusterIds); } if (DBClusterDescription) { res["DBClusterDescription"] = boost::any(*DBClusterDescription); } if (DBClusterStatus) { res["DBClusterStatus"] = boost::any(*DBClusterStatus); } if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } if (resourceGroupId) { res["ResourceGroupId"] = boost::any(*resourceGroupId); } if (tag) { vector<boost::any> temp1; for(auto item1:*tag){ temp1.push_back(boost::any(item1.toMap())); } res["Tag"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("RegionId") != m.end() && !m["RegionId"].empty()) { regionId = make_shared<string>(boost::any_cast<string>(m["RegionId"])); } if (m.find("DBClusterIds") != m.end() && !m["DBClusterIds"].empty()) { DBClusterIds = make_shared<string>(boost::any_cast<string>(m["DBClusterIds"])); } if (m.find("DBClusterDescription") != m.end() && !m["DBClusterDescription"].empty()) { DBClusterDescription = make_shared<string>(boost::any_cast<string>(m["DBClusterDescription"])); } if (m.find("DBClusterStatus") != m.end() && !m["DBClusterStatus"].empty()) { DBClusterStatus = make_shared<string>(boost::any_cast<string>(m["DBClusterStatus"])); } if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"])); } if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"])); } if (m.find("ResourceGroupId") != m.end() && !m["ResourceGroupId"].empty()) { resourceGroupId = make_shared<string>(boost::any_cast<string>(m["ResourceGroupId"])); } if (m.find("Tag") != m.end() && !m["Tag"].empty()) { if (typeid(vector<boost::any>) == m["Tag"].type()) { vector<DescribeDBClustersRequestTag> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["Tag"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeDBClustersRequestTag model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } tag = make_shared<vector<DescribeDBClustersRequestTag>>(expect1); } } } virtual ~DescribeDBClustersRequest() = default; }; class DescribeDBClustersResponseBodyItemsDBClusterTagsTag : public Darabonba::Model { public: shared_ptr<string> key{}; shared_ptr<string> value{}; DescribeDBClustersResponseBodyItemsDBClusterTagsTag() {} explicit DescribeDBClustersResponseBodyItemsDBClusterTagsTag(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (key) { res["Key"] = boost::any(*key); } if (value) { res["Value"] = boost::any(*value); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Key") != m.end() && !m["Key"].empty()) { key = make_shared<string>(boost::any_cast<string>(m["Key"])); } if (m.find("Value") != m.end() && !m["Value"].empty()) { value = make_shared<string>(boost::any_cast<string>(m["Value"])); } } virtual ~DescribeDBClustersResponseBodyItemsDBClusterTagsTag() = default; }; class DescribeDBClustersResponseBodyItemsDBClusterTags : public Darabonba::Model { public: shared_ptr<vector<DescribeDBClustersResponseBodyItemsDBClusterTagsTag>> tag{}; DescribeDBClustersResponseBodyItemsDBClusterTags() {} explicit DescribeDBClustersResponseBodyItemsDBClusterTags(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (tag) { vector<boost::any> temp1; for(auto item1:*tag){ temp1.push_back(boost::any(item1.toMap())); } res["Tag"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Tag") != m.end() && !m["Tag"].empty()) { if (typeid(vector<boost::any>) == m["Tag"].type()) { vector<DescribeDBClustersResponseBodyItemsDBClusterTagsTag> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["Tag"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeDBClustersResponseBodyItemsDBClusterTagsTag model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } tag = make_shared<vector<DescribeDBClustersResponseBodyItemsDBClusterTagsTag>>(expect1); } } } virtual ~DescribeDBClustersResponseBodyItemsDBClusterTags() = default; }; class DescribeDBClustersResponseBodyItemsDBCluster : public Darabonba::Model { public: shared_ptr<string> dtsJobId{}; shared_ptr<long> DBNodeCount{}; shared_ptr<string> expired{}; shared_ptr<string> createTime{}; shared_ptr<string> payType{}; shared_ptr<string> diskType{}; shared_ptr<DescribeDBClustersResponseBodyItemsDBClusterTags> tags{}; shared_ptr<string> mode{}; shared_ptr<string> port{}; shared_ptr<string> lockMode{}; shared_ptr<string> storageResource{}; shared_ptr<string> executorCount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> connectionString{}; shared_ptr<string> rdsInstanceId{}; shared_ptr<string> DBClusterType{}; shared_ptr<string> commodityCode{}; shared_ptr<string> expireTime{}; shared_ptr<long> DBNodeStorage{}; shared_ptr<string> DBNodeClass{}; shared_ptr<string> lockReason{}; shared_ptr<string> VPCId{}; shared_ptr<string> regionId{}; shared_ptr<string> computeResource{}; shared_ptr<long> elasticIOResource{}; shared_ptr<string> vSwitchId{}; shared_ptr<string> DBVersion{}; shared_ptr<string> VPCCloudInstanceId{}; shared_ptr<string> DBClusterStatus{}; shared_ptr<string> resourceGroupId{}; shared_ptr<string> DBClusterNetworkType{}; shared_ptr<string> DBClusterDescription{}; shared_ptr<string> zoneId{}; shared_ptr<string> category{}; shared_ptr<string> engine{}; DescribeDBClustersResponseBodyItemsDBCluster() {} explicit DescribeDBClustersResponseBodyItemsDBCluster(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (dtsJobId) { res["DtsJobId"] = boost::any(*dtsJobId); } if (DBNodeCount) { res["DBNodeCount"] = boost::any(*DBNodeCount); } if (expired) { res["Expired"] = boost::any(*expired); } if (createTime) { res["CreateTime"] = boost::any(*createTime); } if (payType) { res["PayType"] = boost::any(*payType); } if (diskType) { res["DiskType"] = boost::any(*diskType); } if (tags) { res["Tags"] = tags ? boost::any(tags->toMap()) : boost::any(map<string,boost::any>({})); } if (mode) { res["Mode"] = boost::any(*mode); } if (port) { res["Port"] = boost::any(*port); } if (lockMode) { res["LockMode"] = boost::any(*lockMode); } if (storageResource) { res["StorageResource"] = boost::any(*storageResource); } if (executorCount) { res["ExecutorCount"] = boost::any(*executorCount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (connectionString) { res["ConnectionString"] = boost::any(*connectionString); } if (rdsInstanceId) { res["RdsInstanceId"] = boost::any(*rdsInstanceId); } if (DBClusterType) { res["DBClusterType"] = boost::any(*DBClusterType); } if (commodityCode) { res["CommodityCode"] = boost::any(*commodityCode); } if (expireTime) { res["ExpireTime"] = boost::any(*expireTime); } if (DBNodeStorage) { res["DBNodeStorage"] = boost::any(*DBNodeStorage); } if (DBNodeClass) { res["DBNodeClass"] = boost::any(*DBNodeClass); } if (lockReason) { res["LockReason"] = boost::any(*lockReason); } if (VPCId) { res["VPCId"] = boost::any(*VPCId); } if (regionId) { res["RegionId"] = boost::any(*regionId); } if (computeResource) { res["ComputeResource"] = boost::any(*computeResource); } if (elasticIOResource) { res["ElasticIOResource"] = boost::any(*elasticIOResource); } if (vSwitchId) { res["VSwitchId"] = boost::any(*vSwitchId); } if (DBVersion) { res["DBVersion"] = boost::any(*DBVersion); } if (VPCCloudInstanceId) { res["VPCCloudInstanceId"] = boost::any(*VPCCloudInstanceId); } if (DBClusterStatus) { res["DBClusterStatus"] = boost::any(*DBClusterStatus); } if (resourceGroupId) { res["ResourceGroupId"] = boost::any(*resourceGroupId); } if (DBClusterNetworkType) { res["DBClusterNetworkType"] = boost::any(*DBClusterNetworkType); } if (DBClusterDescription) { res["DBClusterDescription"] = boost::any(*DBClusterDescription); } if (zoneId) { res["ZoneId"] = boost::any(*zoneId); } if (category) { res["Category"] = boost::any(*category); } if (engine) { res["Engine"] = boost::any(*engine); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("DtsJobId") != m.end() && !m["DtsJobId"].empty()) { dtsJobId = make_shared<string>(boost::any_cast<string>(m["DtsJobId"])); } if (m.find("DBNodeCount") != m.end() && !m["DBNodeCount"].empty()) { DBNodeCount = make_shared<long>(boost::any_cast<long>(m["DBNodeCount"])); } if (m.find("Expired") != m.end() && !m["Expired"].empty()) { expired = make_shared<string>(boost::any_cast<string>(m["Expired"])); } if (m.find("CreateTime") != m.end() && !m["CreateTime"].empty()) { createTime = make_shared<string>(boost::any_cast<string>(m["CreateTime"])); } if (m.find("PayType") != m.end() && !m["PayType"].empty()) { payType = make_shared<string>(boost::any_cast<string>(m["PayType"])); } if (m.find("DiskType") != m.end() && !m["DiskType"].empty()) { diskType = make_shared<string>(boost::any_cast<string>(m["DiskType"])); } if (m.find("Tags") != m.end() && !m["Tags"].empty()) { if (typeid(map<string, boost::any>) == m["Tags"].type()) { DescribeDBClustersResponseBodyItemsDBClusterTags model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Tags"])); tags = make_shared<DescribeDBClustersResponseBodyItemsDBClusterTags>(model1); } } if (m.find("Mode") != m.end() && !m["Mode"].empty()) { mode = make_shared<string>(boost::any_cast<string>(m["Mode"])); } if (m.find("Port") != m.end() && !m["Port"].empty()) { port = make_shared<string>(boost::any_cast<string>(m["Port"])); } if (m.find("LockMode") != m.end() && !m["LockMode"].empty()) { lockMode = make_shared<string>(boost::any_cast<string>(m["LockMode"])); } if (m.find("StorageResource") != m.end() && !m["StorageResource"].empty()) { storageResource = make_shared<string>(boost::any_cast<string>(m["StorageResource"])); } if (m.find("ExecutorCount") != m.end() && !m["ExecutorCount"].empty()) { executorCount = make_shared<string>(boost::any_cast<string>(m["ExecutorCount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("ConnectionString") != m.end() && !m["ConnectionString"].empty()) { connectionString = make_shared<string>(boost::any_cast<string>(m["ConnectionString"])); } if (m.find("RdsInstanceId") != m.end() && !m["RdsInstanceId"].empty()) { rdsInstanceId = make_shared<string>(boost::any_cast<string>(m["RdsInstanceId"])); } if (m.find("DBClusterType") != m.end() && !m["DBClusterType"].empty()) { DBClusterType = make_shared<string>(boost::any_cast<string>(m["DBClusterType"])); } if (m.find("CommodityCode") != m.end() && !m["CommodityCode"].empty()) { commodityCode = make_shared<string>(boost::any_cast<string>(m["CommodityCode"])); } if (m.find("ExpireTime") != m.end() && !m["ExpireTime"].empty()) { expireTime = make_shared<string>(boost::any_cast<string>(m["ExpireTime"])); } if (m.find("DBNodeStorage") != m.end() && !m["DBNodeStorage"].empty()) { DBNodeStorage = make_shared<long>(boost::any_cast<long>(m["DBNodeStorage"])); } if (m.find("DBNodeClass") != m.end() && !m["DBNodeClass"].empty()) { DBNodeClass = make_shared<string>(boost::any_cast<string>(m["DBNodeClass"])); } if (m.find("LockReason") != m.end() && !m["LockReason"].empty()) { lockReason = make_shared<string>(boost::any_cast<string>(m["LockReason"])); } if (m.find("VPCId") != m.end() && !m["VPCId"].empty()) { VPCId = make_shared<string>(boost::any_cast<string>(m["VPCId"])); } if (m.find("RegionId") != m.end() && !m["RegionId"].empty()) { regionId = make_shared<string>(boost::any_cast<string>(m["RegionId"])); } if (m.find("ComputeResource") != m.end() && !m["ComputeResource"].empty()) { computeResource = make_shared<string>(boost::any_cast<string>(m["ComputeResource"])); } if (m.find("ElasticIOResource") != m.end() && !m["ElasticIOResource"].empty()) { elasticIOResource = make_shared<long>(boost::any_cast<long>(m["ElasticIOResource"])); } if (m.find("VSwitchId") != m.end() && !m["VSwitchId"].empty()) { vSwitchId = make_shared<string>(boost::any_cast<string>(m["VSwitchId"])); } if (m.find("DBVersion") != m.end() && !m["DBVersion"].empty()) { DBVersion = make_shared<string>(boost::any_cast<string>(m["DBVersion"])); } if (m.find("VPCCloudInstanceId") != m.end() && !m["VPCCloudInstanceId"].empty()) { VPCCloudInstanceId = make_shared<string>(boost::any_cast<string>(m["VPCCloudInstanceId"])); } if (m.find("DBClusterStatus") != m.end() && !m["DBClusterStatus"].empty()) { DBClusterStatus = make_shared<string>(boost::any_cast<string>(m["DBClusterStatus"])); } if (m.find("ResourceGroupId") != m.end() && !m["ResourceGroupId"].empty()) { resourceGroupId = make_shared<string>(boost::any_cast<string>(m["ResourceGroupId"])); } if (m.find("DBClusterNetworkType") != m.end() && !m["DBClusterNetworkType"].empty()) { DBClusterNetworkType = make_shared<string>(boost::any_cast<string>(m["DBClusterNetworkType"])); } if (m.find("DBClusterDescription") != m.end() && !m["DBClusterDescription"].empty()) { DBClusterDescription = make_shared<string>(boost::any_cast<string>(m["DBClusterDescription"])); } if (m.find("ZoneId") != m.end() && !m["ZoneId"].empty()) { zoneId = make_shared<string>(boost::any_cast<string>(m["ZoneId"])); } if (m.find("Category") != m.end() && !m["Category"].empty()) { category = make_shared<string>(boost::any_cast<string>(m["Category"])); } if (m.find("Engine") != m.end() && !m["Engine"].empty()) { engine = make_shared<string>(boost::any_cast<string>(m["Engine"])); } } virtual ~DescribeDBClustersResponseBodyItemsDBCluster() = default; }; class DescribeDBClustersResponseBodyItems : public Darabonba::Model { public: shared_ptr<vector<DescribeDBClustersResponseBodyItemsDBCluster>> DBCluster{}; DescribeDBClustersResponseBodyItems() {} explicit DescribeDBClustersResponseBodyItems(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (DBCluster) { vector<boost::any> temp1; for(auto item1:*DBCluster){ temp1.push_back(boost::any(item1.toMap())); } res["DBCluster"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("DBCluster") != m.end() && !m["DBCluster"].empty()) { if (typeid(vector<boost::any>) == m["DBCluster"].type()) { vector<DescribeDBClustersResponseBodyItemsDBCluster> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["DBCluster"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeDBClustersResponseBodyItemsDBCluster model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } DBCluster = make_shared<vector<DescribeDBClustersResponseBodyItemsDBCluster>>(expect1); } } } virtual ~DescribeDBClustersResponseBodyItems() = default; }; class DescribeDBClustersResponseBody : public Darabonba::Model { public: shared_ptr<long> totalCount{}; shared_ptr<long> pageSize{}; shared_ptr<string> requestId{}; shared_ptr<long> pageNumber{}; shared_ptr<DescribeDBClustersResponseBodyItems> items{}; DescribeDBClustersResponseBody() {} explicit DescribeDBClustersResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (totalCount) { res["TotalCount"] = boost::any(*totalCount); } if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (requestId) { res["RequestId"] = boost::any(*requestId); } if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } if (items) { res["Items"] = items ? boost::any(items->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("TotalCount") != m.end() && !m["TotalCount"].empty()) { totalCount = make_shared<long>(boost::any_cast<long>(m["TotalCount"])); } if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"])); } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"])); } if (m.find("Items") != m.end() && !m["Items"].empty()) { if (typeid(map<string, boost::any>) == m["Items"].type()) { DescribeDBClustersResponseBodyItems model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Items"])); items = make_shared<DescribeDBClustersResponseBodyItems>(model1); } } } virtual ~DescribeDBClustersResponseBody() = default; }; class DescribeDBClustersResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeDBClustersResponseBody> body{}; DescribeDBClustersResponse() {} explicit DescribeDBClustersResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeDBClustersResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeDBClustersResponseBody>(model1); } } } virtual ~DescribeDBClustersResponse() = default; }; class DescribeDBResourcePoolRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> poolName{}; DescribeDBResourcePoolRequest() {} explicit DescribeDBResourcePoolRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (poolName) { res["PoolName"] = boost::any(*poolName); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("PoolName") != m.end() && !m["PoolName"].empty()) { poolName = make_shared<string>(boost::any_cast<string>(m["PoolName"])); } } virtual ~DescribeDBResourcePoolRequest() = default; }; class DescribeDBResourcePoolResponseBodyPoolsInfo : public Darabonba::Model { public: shared_ptr<string> queryType{}; shared_ptr<string> updateTime{}; shared_ptr<string> poolName{}; shared_ptr<string> createTime{}; shared_ptr<string> poolUsers{}; shared_ptr<long> nodeNum{}; DescribeDBResourcePoolResponseBodyPoolsInfo() {} explicit DescribeDBResourcePoolResponseBodyPoolsInfo(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (queryType) { res["QueryType"] = boost::any(*queryType); } if (updateTime) { res["UpdateTime"] = boost::any(*updateTime); } if (poolName) { res["PoolName"] = boost::any(*poolName); } if (createTime) { res["CreateTime"] = boost::any(*createTime); } if (poolUsers) { res["PoolUsers"] = boost::any(*poolUsers); } if (nodeNum) { res["NodeNum"] = boost::any(*nodeNum); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("QueryType") != m.end() && !m["QueryType"].empty()) { queryType = make_shared<string>(boost::any_cast<string>(m["QueryType"])); } if (m.find("UpdateTime") != m.end() && !m["UpdateTime"].empty()) { updateTime = make_shared<string>(boost::any_cast<string>(m["UpdateTime"])); } if (m.find("PoolName") != m.end() && !m["PoolName"].empty()) { poolName = make_shared<string>(boost::any_cast<string>(m["PoolName"])); } if (m.find("CreateTime") != m.end() && !m["CreateTime"].empty()) { createTime = make_shared<string>(boost::any_cast<string>(m["CreateTime"])); } if (m.find("PoolUsers") != m.end() && !m["PoolUsers"].empty()) { poolUsers = make_shared<string>(boost::any_cast<string>(m["PoolUsers"])); } if (m.find("NodeNum") != m.end() && !m["NodeNum"].empty()) { nodeNum = make_shared<long>(boost::any_cast<long>(m["NodeNum"])); } } virtual ~DescribeDBResourcePoolResponseBodyPoolsInfo() = default; }; class DescribeDBResourcePoolResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; shared_ptr<vector<DescribeDBResourcePoolResponseBodyPoolsInfo>> poolsInfo{}; DescribeDBResourcePoolResponseBody() {} explicit DescribeDBResourcePoolResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } if (poolsInfo) { vector<boost::any> temp1; for(auto item1:*poolsInfo){ temp1.push_back(boost::any(item1.toMap())); } res["PoolsInfo"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("PoolsInfo") != m.end() && !m["PoolsInfo"].empty()) { if (typeid(vector<boost::any>) == m["PoolsInfo"].type()) { vector<DescribeDBResourcePoolResponseBodyPoolsInfo> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["PoolsInfo"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeDBResourcePoolResponseBodyPoolsInfo model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } poolsInfo = make_shared<vector<DescribeDBResourcePoolResponseBodyPoolsInfo>>(expect1); } } } virtual ~DescribeDBResourcePoolResponseBody() = default; }; class DescribeDBResourcePoolResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeDBResourcePoolResponseBody> body{}; DescribeDBResourcePoolResponse() {} explicit DescribeDBResourcePoolResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeDBResourcePoolResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeDBResourcePoolResponseBody>(model1); } } } virtual ~DescribeDBResourcePoolResponse() = default; }; class DescribeDiagnosisDimensionsRequest : public Darabonba::Model { public: shared_ptr<string> DBClusterId{}; shared_ptr<string> startTime{}; shared_ptr<string> endTime{}; shared_ptr<string> regionId{}; shared_ptr<string> queryCondition{}; shared_ptr<string> lang{}; DescribeDiagnosisDimensionsRequest() {} explicit DescribeDiagnosisDimensionsRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (startTime) { res["StartTime"] = boost::any(*startTime); } if (endTime) { res["EndTime"] = boost::any(*endTime); } if (regionId) { res["RegionId"] = boost::any(*regionId); } if (queryCondition) { res["QueryCondition"] = boost::any(*queryCondition); } if (lang) { res["Lang"] = boost::any(*lang); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("StartTime") != m.end() && !m["StartTime"].empty()) { startTime = make_shared<string>(boost::any_cast<string>(m["StartTime"])); } if (m.find("EndTime") != m.end() && !m["EndTime"].empty()) { endTime = make_shared<string>(boost::any_cast<string>(m["EndTime"])); } if (m.find("RegionId") != m.end() && !m["RegionId"].empty()) { regionId = make_shared<string>(boost::any_cast<string>(m["RegionId"])); } if (m.find("QueryCondition") != m.end() && !m["QueryCondition"].empty()) { queryCondition = make_shared<string>(boost::any_cast<string>(m["QueryCondition"])); } if (m.find("Lang") != m.end() && !m["Lang"].empty()) { lang = make_shared<string>(boost::any_cast<string>(m["Lang"])); } } virtual ~DescribeDiagnosisDimensionsRequest() = default; }; class DescribeDiagnosisDimensionsResponseBody : public Darabonba::Model { public: shared_ptr<vector<string>> clientIps{}; shared_ptr<vector<string>> resourceGroups{}; shared_ptr<vector<string>> userNames{}; shared_ptr<vector<string>> databases{}; shared_ptr<string> requestId{}; DescribeDiagnosisDimensionsResponseBody() {} explicit DescribeDiagnosisDimensionsResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (clientIps) { res["ClientIps"] = boost::any(*clientIps); } if (resourceGroups) { res["ResourceGroups"] = boost::any(*resourceGroups); } if (userNames) { res["UserNames"] = boost::any(*userNames); } if (databases) { res["Databases"] = boost::any(*databases); } if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ClientIps") != m.end() && !m["ClientIps"].empty()) { vector<string> toVec1; if (typeid(vector<boost::any>) == m["ClientIps"].type()) { vector<boost::any> vec1 = boost::any_cast<vector<boost::any>>(m["ClientIps"]); for (auto item:vec1) { toVec1.push_back(boost::any_cast<string>(item)); } } clientIps = make_shared<vector<string>>(toVec1); } if (m.find("ResourceGroups") != m.end() && !m["ResourceGroups"].empty()) { vector<string> toVec1; if (typeid(vector<boost::any>) == m["ResourceGroups"].type()) { vector<boost::any> vec1 = boost::any_cast<vector<boost::any>>(m["ResourceGroups"]); for (auto item:vec1) { toVec1.push_back(boost::any_cast<string>(item)); } } resourceGroups = make_shared<vector<string>>(toVec1); } if (m.find("UserNames") != m.end() && !m["UserNames"].empty()) { vector<string> toVec1; if (typeid(vector<boost::any>) == m["UserNames"].type()) { vector<boost::any> vec1 = boost::any_cast<vector<boost::any>>(m["UserNames"]); for (auto item:vec1) { toVec1.push_back(boost::any_cast<string>(item)); } } userNames = make_shared<vector<string>>(toVec1); } if (m.find("Databases") != m.end() && !m["Databases"].empty()) { vector<string> toVec1; if (typeid(vector<boost::any>) == m["Databases"].type()) { vector<boost::any> vec1 = boost::any_cast<vector<boost::any>>(m["Databases"]); for (auto item:vec1) { toVec1.push_back(boost::any_cast<string>(item)); } } databases = make_shared<vector<string>>(toVec1); } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~DescribeDiagnosisDimensionsResponseBody() = default; }; class DescribeDiagnosisDimensionsResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeDiagnosisDimensionsResponseBody> body{}; DescribeDiagnosisDimensionsResponse() {} explicit DescribeDiagnosisDimensionsResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeDiagnosisDimensionsResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeDiagnosisDimensionsResponseBody>(model1); } } } virtual ~DescribeDiagnosisDimensionsResponse() = default; }; class DescribeDiagnosisRecordsRequest : public Darabonba::Model { public: shared_ptr<string> DBClusterId{}; shared_ptr<string> startTime{}; shared_ptr<string> endTime{}; shared_ptr<string> regionId{}; shared_ptr<string> queryCondition{}; shared_ptr<string> keyword{}; shared_ptr<long> minPeakMemory{}; shared_ptr<long> maxPeakMemory{}; shared_ptr<long> minScanSize{}; shared_ptr<long> maxScanSize{}; shared_ptr<string> resourceGroup{}; shared_ptr<string> userName{}; shared_ptr<string> database{}; shared_ptr<string> clientIp{}; shared_ptr<string> order{}; shared_ptr<long> pageNumber{}; shared_ptr<long> pageSize{}; shared_ptr<string> lang{}; shared_ptr<long> patternId{}; DescribeDiagnosisRecordsRequest() {} explicit DescribeDiagnosisRecordsRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (startTime) { res["StartTime"] = boost::any(*startTime); } if (endTime) { res["EndTime"] = boost::any(*endTime); } if (regionId) { res["RegionId"] = boost::any(*regionId); } if (queryCondition) { res["QueryCondition"] = boost::any(*queryCondition); } if (keyword) { res["Keyword"] = boost::any(*keyword); } if (minPeakMemory) { res["MinPeakMemory"] = boost::any(*minPeakMemory); } if (maxPeakMemory) { res["MaxPeakMemory"] = boost::any(*maxPeakMemory); } if (minScanSize) { res["MinScanSize"] = boost::any(*minScanSize); } if (maxScanSize) { res["MaxScanSize"] = boost::any(*maxScanSize); } if (resourceGroup) { res["ResourceGroup"] = boost::any(*resourceGroup); } if (userName) { res["UserName"] = boost::any(*userName); } if (database) { res["Database"] = boost::any(*database); } if (clientIp) { res["ClientIp"] = boost::any(*clientIp); } if (order) { res["Order"] = boost::any(*order); } if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (lang) { res["Lang"] = boost::any(*lang); } if (patternId) { res["PatternId"] = boost::any(*patternId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("StartTime") != m.end() && !m["StartTime"].empty()) { startTime = make_shared<string>(boost::any_cast<string>(m["StartTime"])); } if (m.find("EndTime") != m.end() && !m["EndTime"].empty()) { endTime = make_shared<string>(boost::any_cast<string>(m["EndTime"])); } if (m.find("RegionId") != m.end() && !m["RegionId"].empty()) { regionId = make_shared<string>(boost::any_cast<string>(m["RegionId"])); } if (m.find("QueryCondition") != m.end() && !m["QueryCondition"].empty()) { queryCondition = make_shared<string>(boost::any_cast<string>(m["QueryCondition"])); } if (m.find("Keyword") != m.end() && !m["Keyword"].empty()) { keyword = make_shared<string>(boost::any_cast<string>(m["Keyword"])); } if (m.find("MinPeakMemory") != m.end() && !m["MinPeakMemory"].empty()) { minPeakMemory = make_shared<long>(boost::any_cast<long>(m["MinPeakMemory"])); } if (m.find("MaxPeakMemory") != m.end() && !m["MaxPeakMemory"].empty()) { maxPeakMemory = make_shared<long>(boost::any_cast<long>(m["MaxPeakMemory"])); } if (m.find("MinScanSize") != m.end() && !m["MinScanSize"].empty()) { minScanSize = make_shared<long>(boost::any_cast<long>(m["MinScanSize"])); } if (m.find("MaxScanSize") != m.end() && !m["MaxScanSize"].empty()) { maxScanSize = make_shared<long>(boost::any_cast<long>(m["MaxScanSize"])); } if (m.find("ResourceGroup") != m.end() && !m["ResourceGroup"].empty()) { resourceGroup = make_shared<string>(boost::any_cast<string>(m["ResourceGroup"])); } if (m.find("UserName") != m.end() && !m["UserName"].empty()) { userName = make_shared<string>(boost::any_cast<string>(m["UserName"])); } if (m.find("Database") != m.end() && !m["Database"].empty()) { database = make_shared<string>(boost::any_cast<string>(m["Database"])); } if (m.find("ClientIp") != m.end() && !m["ClientIp"].empty()) { clientIp = make_shared<string>(boost::any_cast<string>(m["ClientIp"])); } if (m.find("Order") != m.end() && !m["Order"].empty()) { order = make_shared<string>(boost::any_cast<string>(m["Order"])); } if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"])); } if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"])); } if (m.find("Lang") != m.end() && !m["Lang"].empty()) { lang = make_shared<string>(boost::any_cast<string>(m["Lang"])); } if (m.find("PatternId") != m.end() && !m["PatternId"].empty()) { patternId = make_shared<long>(boost::any_cast<long>(m["PatternId"])); } } virtual ~DescribeDiagnosisRecordsRequest() = default; }; class DescribeDiagnosisRecordsResponseBodyQuerys : public Darabonba::Model { public: shared_ptr<string> SQL{}; shared_ptr<long> SQLTruncatedThreshold{}; shared_ptr<string> status{}; shared_ptr<long> outputDataSize{}; shared_ptr<long> cost{}; shared_ptr<long> outputRows{}; shared_ptr<string> rcHost{}; shared_ptr<long> scanSize{}; shared_ptr<string> processId{}; shared_ptr<long> startTime{}; shared_ptr<bool> SQLTruncated{}; shared_ptr<string> database{}; shared_ptr<long> scanRows{}; shared_ptr<long> resourceCostRank{}; shared_ptr<string> clientIp{}; shared_ptr<long> peakMemory{}; shared_ptr<long> queueTime{}; shared_ptr<string> resourceGroup{}; shared_ptr<string> userName{}; shared_ptr<long> executionTime{}; shared_ptr<long> totalPlanningTime{}; shared_ptr<long> etlWriteRows{}; shared_ptr<long> totalStages{}; DescribeDiagnosisRecordsResponseBodyQuerys() {} explicit DescribeDiagnosisRecordsResponseBodyQuerys(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (SQL) { res["SQL"] = boost::any(*SQL); } if (SQLTruncatedThreshold) { res["SQLTruncatedThreshold"] = boost::any(*SQLTruncatedThreshold); } if (status) { res["Status"] = boost::any(*status); } if (outputDataSize) { res["OutputDataSize"] = boost::any(*outputDataSize); } if (cost) { res["Cost"] = boost::any(*cost); } if (outputRows) { res["OutputRows"] = boost::any(*outputRows); } if (rcHost) { res["RcHost"] = boost::any(*rcHost); } if (scanSize) { res["ScanSize"] = boost::any(*scanSize); } if (processId) { res["ProcessId"] = boost::any(*processId); } if (startTime) { res["StartTime"] = boost::any(*startTime); } if (SQLTruncated) { res["SQLTruncated"] = boost::any(*SQLTruncated); } if (database) { res["Database"] = boost::any(*database); } if (scanRows) { res["ScanRows"] = boost::any(*scanRows); } if (resourceCostRank) { res["ResourceCostRank"] = boost::any(*resourceCostRank); } if (clientIp) { res["ClientIp"] = boost::any(*clientIp); } if (peakMemory) { res["PeakMemory"] = boost::any(*peakMemory); } if (queueTime) { res["QueueTime"] = boost::any(*queueTime); } if (resourceGroup) { res["ResourceGroup"] = boost::any(*resourceGroup); } if (userName) { res["UserName"] = boost::any(*userName); } if (executionTime) { res["ExecutionTime"] = boost::any(*executionTime); } if (totalPlanningTime) { res["TotalPlanningTime"] = boost::any(*totalPlanningTime); } if (etlWriteRows) { res["EtlWriteRows"] = boost::any(*etlWriteRows); } if (totalStages) { res["TotalStages"] = boost::any(*totalStages); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("SQL") != m.end() && !m["SQL"].empty()) { SQL = make_shared<string>(boost::any_cast<string>(m["SQL"])); } if (m.find("SQLTruncatedThreshold") != m.end() && !m["SQLTruncatedThreshold"].empty()) { SQLTruncatedThreshold = make_shared<long>(boost::any_cast<long>(m["SQLTruncatedThreshold"])); } if (m.find("Status") != m.end() && !m["Status"].empty()) { status = make_shared<string>(boost::any_cast<string>(m["Status"])); } if (m.find("OutputDataSize") != m.end() && !m["OutputDataSize"].empty()) { outputDataSize = make_shared<long>(boost::any_cast<long>(m["OutputDataSize"])); } if (m.find("Cost") != m.end() && !m["Cost"].empty()) { cost = make_shared<long>(boost::any_cast<long>(m["Cost"])); } if (m.find("OutputRows") != m.end() && !m["OutputRows"].empty()) { outputRows = make_shared<long>(boost::any_cast<long>(m["OutputRows"])); } if (m.find("RcHost") != m.end() && !m["RcHost"].empty()) { rcHost = make_shared<string>(boost::any_cast<string>(m["RcHost"])); } if (m.find("ScanSize") != m.end() && !m["ScanSize"].empty()) { scanSize = make_shared<long>(boost::any_cast<long>(m["ScanSize"])); } if (m.find("ProcessId") != m.end() && !m["ProcessId"].empty()) { processId = make_shared<string>(boost::any_cast<string>(m["ProcessId"])); } if (m.find("StartTime") != m.end() && !m["StartTime"].empty()) { startTime = make_shared<long>(boost::any_cast<long>(m["StartTime"])); } if (m.find("SQLTruncated") != m.end() && !m["SQLTruncated"].empty()) { SQLTruncated = make_shared<bool>(boost::any_cast<bool>(m["SQLTruncated"])); } if (m.find("Database") != m.end() && !m["Database"].empty()) { database = make_shared<string>(boost::any_cast<string>(m["Database"])); } if (m.find("ScanRows") != m.end() && !m["ScanRows"].empty()) { scanRows = make_shared<long>(boost::any_cast<long>(m["ScanRows"])); } if (m.find("ResourceCostRank") != m.end() && !m["ResourceCostRank"].empty()) { resourceCostRank = make_shared<long>(boost::any_cast<long>(m["ResourceCostRank"])); } if (m.find("ClientIp") != m.end() && !m["ClientIp"].empty()) { clientIp = make_shared<string>(boost::any_cast<string>(m["ClientIp"])); } if (m.find("PeakMemory") != m.end() && !m["PeakMemory"].empty()) { peakMemory = make_shared<long>(boost::any_cast<long>(m["PeakMemory"])); } if (m.find("QueueTime") != m.end() && !m["QueueTime"].empty()) { queueTime = make_shared<long>(boost::any_cast<long>(m["QueueTime"])); } if (m.find("ResourceGroup") != m.end() && !m["ResourceGroup"].empty()) { resourceGroup = make_shared<string>(boost::any_cast<string>(m["ResourceGroup"])); } if (m.find("UserName") != m.end() && !m["UserName"].empty()) { userName = make_shared<string>(boost::any_cast<string>(m["UserName"])); } if (m.find("ExecutionTime") != m.end() && !m["ExecutionTime"].empty()) { executionTime = make_shared<long>(boost::any_cast<long>(m["ExecutionTime"])); } if (m.find("TotalPlanningTime") != m.end() && !m["TotalPlanningTime"].empty()) { totalPlanningTime = make_shared<long>(boost::any_cast<long>(m["TotalPlanningTime"])); } if (m.find("EtlWriteRows") != m.end() && !m["EtlWriteRows"].empty()) { etlWriteRows = make_shared<long>(boost::any_cast<long>(m["EtlWriteRows"])); } if (m.find("TotalStages") != m.end() && !m["TotalStages"].empty()) { totalStages = make_shared<long>(boost::any_cast<long>(m["TotalStages"])); } } virtual ~DescribeDiagnosisRecordsResponseBodyQuerys() = default; }; class DescribeDiagnosisRecordsResponseBody : public Darabonba::Model { public: shared_ptr<long> pageNumber{}; shared_ptr<long> pageSize{}; shared_ptr<long> totalCount{}; shared_ptr<vector<DescribeDiagnosisRecordsResponseBodyQuerys>> querys{}; shared_ptr<string> requestId{}; DescribeDiagnosisRecordsResponseBody() {} explicit DescribeDiagnosisRecordsResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (totalCount) { res["TotalCount"] = boost::any(*totalCount); } if (querys) { vector<boost::any> temp1; for(auto item1:*querys){ temp1.push_back(boost::any(item1.toMap())); } res["Querys"] = boost::any(temp1); } if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"])); } if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"])); } if (m.find("TotalCount") != m.end() && !m["TotalCount"].empty()) { totalCount = make_shared<long>(boost::any_cast<long>(m["TotalCount"])); } if (m.find("Querys") != m.end() && !m["Querys"].empty()) { if (typeid(vector<boost::any>) == m["Querys"].type()) { vector<DescribeDiagnosisRecordsResponseBodyQuerys> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["Querys"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeDiagnosisRecordsResponseBodyQuerys model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } querys = make_shared<vector<DescribeDiagnosisRecordsResponseBodyQuerys>>(expect1); } } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~DescribeDiagnosisRecordsResponseBody() = default; }; class DescribeDiagnosisRecordsResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeDiagnosisRecordsResponseBody> body{}; DescribeDiagnosisRecordsResponse() {} explicit DescribeDiagnosisRecordsResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeDiagnosisRecordsResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeDiagnosisRecordsResponseBody>(model1); } } } virtual ~DescribeDiagnosisRecordsResponse() = default; }; class DescribeDiagnosisSQLInfoRequest : public Darabonba::Model { public: shared_ptr<string> DBClusterId{}; shared_ptr<string> regionId{}; shared_ptr<string> processId{}; shared_ptr<long> processStartTime{}; shared_ptr<string> processState{}; shared_ptr<string> lang{}; shared_ptr<string> processRcHost{}; DescribeDiagnosisSQLInfoRequest() {} explicit DescribeDiagnosisSQLInfoRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (regionId) { res["RegionId"] = boost::any(*regionId); } if (processId) { res["ProcessId"] = boost::any(*processId); } if (processStartTime) { res["ProcessStartTime"] = boost::any(*processStartTime); } if (processState) { res["ProcessState"] = boost::any(*processState); } if (lang) { res["Lang"] = boost::any(*lang); } if (processRcHost) { res["ProcessRcHost"] = boost::any(*processRcHost); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("RegionId") != m.end() && !m["RegionId"].empty()) { regionId = make_shared<string>(boost::any_cast<string>(m["RegionId"])); } if (m.find("ProcessId") != m.end() && !m["ProcessId"].empty()) { processId = make_shared<string>(boost::any_cast<string>(m["ProcessId"])); } if (m.find("ProcessStartTime") != m.end() && !m["ProcessStartTime"].empty()) { processStartTime = make_shared<long>(boost::any_cast<long>(m["ProcessStartTime"])); } if (m.find("ProcessState") != m.end() && !m["ProcessState"].empty()) { processState = make_shared<string>(boost::any_cast<string>(m["ProcessState"])); } if (m.find("Lang") != m.end() && !m["Lang"].empty()) { lang = make_shared<string>(boost::any_cast<string>(m["Lang"])); } if (m.find("ProcessRcHost") != m.end() && !m["ProcessRcHost"].empty()) { processRcHost = make_shared<string>(boost::any_cast<string>(m["ProcessRcHost"])); } } virtual ~DescribeDiagnosisSQLInfoRequest() = default; }; class DescribeDiagnosisSQLInfoResponseBody : public Darabonba::Model { public: shared_ptr<string> diagnosisSQLInfo{}; shared_ptr<string> requestId{}; DescribeDiagnosisSQLInfoResponseBody() {} explicit DescribeDiagnosisSQLInfoResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (diagnosisSQLInfo) { res["DiagnosisSQLInfo"] = boost::any(*diagnosisSQLInfo); } if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("DiagnosisSQLInfo") != m.end() && !m["DiagnosisSQLInfo"].empty()) { diagnosisSQLInfo = make_shared<string>(boost::any_cast<string>(m["DiagnosisSQLInfo"])); } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~DescribeDiagnosisSQLInfoResponseBody() = default; }; class DescribeDiagnosisSQLInfoResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeDiagnosisSQLInfoResponseBody> body{}; DescribeDiagnosisSQLInfoResponse() {} explicit DescribeDiagnosisSQLInfoResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeDiagnosisSQLInfoResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeDiagnosisSQLInfoResponseBody>(model1); } } } virtual ~DescribeDiagnosisSQLInfoResponse() = default; }; class DescribeDownloadRecordsRequest : public Darabonba::Model { public: shared_ptr<string> DBClusterId{}; shared_ptr<string> regionId{}; shared_ptr<string> lang{}; DescribeDownloadRecordsRequest() {} explicit DescribeDownloadRecordsRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (regionId) { res["RegionId"] = boost::any(*regionId); } if (lang) { res["Lang"] = boost::any(*lang); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("RegionId") != m.end() && !m["RegionId"].empty()) { regionId = make_shared<string>(boost::any_cast<string>(m["RegionId"])); } if (m.find("Lang") != m.end() && !m["Lang"].empty()) { lang = make_shared<string>(boost::any_cast<string>(m["Lang"])); } } virtual ~DescribeDownloadRecordsRequest() = default; }; class DescribeDownloadRecordsResponseBodyRecords : public Darabonba::Model { public: shared_ptr<string> status{}; shared_ptr<long> downloadId{}; shared_ptr<string> exceptionMsg{}; shared_ptr<string> url{}; shared_ptr<string> fileName{}; DescribeDownloadRecordsResponseBodyRecords() {} explicit DescribeDownloadRecordsResponseBodyRecords(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (status) { res["Status"] = boost::any(*status); } if (downloadId) { res["DownloadId"] = boost::any(*downloadId); } if (exceptionMsg) { res["ExceptionMsg"] = boost::any(*exceptionMsg); } if (url) { res["Url"] = boost::any(*url); } if (fileName) { res["FileName"] = boost::any(*fileName); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Status") != m.end() && !m["Status"].empty()) { status = make_shared<string>(boost::any_cast<string>(m["Status"])); } if (m.find("DownloadId") != m.end() && !m["DownloadId"].empty()) { downloadId = make_shared<long>(boost::any_cast<long>(m["DownloadId"])); } if (m.find("ExceptionMsg") != m.end() && !m["ExceptionMsg"].empty()) { exceptionMsg = make_shared<string>(boost::any_cast<string>(m["ExceptionMsg"])); } if (m.find("Url") != m.end() && !m["Url"].empty()) { url = make_shared<string>(boost::any_cast<string>(m["Url"])); } if (m.find("FileName") != m.end() && !m["FileName"].empty()) { fileName = make_shared<string>(boost::any_cast<string>(m["FileName"])); } } virtual ~DescribeDownloadRecordsResponseBodyRecords() = default; }; class DescribeDownloadRecordsResponseBody : public Darabonba::Model { public: shared_ptr<vector<DescribeDownloadRecordsResponseBodyRecords>> records{}; shared_ptr<string> requestId{}; DescribeDownloadRecordsResponseBody() {} explicit DescribeDownloadRecordsResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (records) { vector<boost::any> temp1; for(auto item1:*records){ temp1.push_back(boost::any(item1.toMap())); } res["Records"] = boost::any(temp1); } if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Records") != m.end() && !m["Records"].empty()) { if (typeid(vector<boost::any>) == m["Records"].type()) { vector<DescribeDownloadRecordsResponseBodyRecords> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["Records"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeDownloadRecordsResponseBodyRecords model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } records = make_shared<vector<DescribeDownloadRecordsResponseBodyRecords>>(expect1); } } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~DescribeDownloadRecordsResponseBody() = default; }; class DescribeDownloadRecordsResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeDownloadRecordsResponseBody> body{}; DescribeDownloadRecordsResponse() {} explicit DescribeDownloadRecordsResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeDownloadRecordsResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeDownloadRecordsResponseBody>(model1); } } } virtual ~DescribeDownloadRecordsResponse() = default; }; class DescribeElasticDailyPlanRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> elasticPlanName{}; shared_ptr<string> resourcePoolName{}; shared_ptr<string> elasticDailyPlanDay{}; shared_ptr<string> elasticDailyPlanStatusList{}; DescribeElasticDailyPlanRequest() {} explicit DescribeElasticDailyPlanRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (elasticPlanName) { res["ElasticPlanName"] = boost::any(*elasticPlanName); } if (resourcePoolName) { res["ResourcePoolName"] = boost::any(*resourcePoolName); } if (elasticDailyPlanDay) { res["ElasticDailyPlanDay"] = boost::any(*elasticDailyPlanDay); } if (elasticDailyPlanStatusList) { res["ElasticDailyPlanStatusList"] = boost::any(*elasticDailyPlanStatusList); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("ElasticPlanName") != m.end() && !m["ElasticPlanName"].empty()) { elasticPlanName = make_shared<string>(boost::any_cast<string>(m["ElasticPlanName"])); } if (m.find("ResourcePoolName") != m.end() && !m["ResourcePoolName"].empty()) { resourcePoolName = make_shared<string>(boost::any_cast<string>(m["ResourcePoolName"])); } if (m.find("ElasticDailyPlanDay") != m.end() && !m["ElasticDailyPlanDay"].empty()) { elasticDailyPlanDay = make_shared<string>(boost::any_cast<string>(m["ElasticDailyPlanDay"])); } if (m.find("ElasticDailyPlanStatusList") != m.end() && !m["ElasticDailyPlanStatusList"].empty()) { elasticDailyPlanStatusList = make_shared<string>(boost::any_cast<string>(m["ElasticDailyPlanStatusList"])); } } virtual ~DescribeElasticDailyPlanRequest() = default; }; class DescribeElasticDailyPlanResponseBodyElasticDailyPlanList : public Darabonba::Model { public: shared_ptr<long> status{}; shared_ptr<string> day{}; shared_ptr<string> resourcePoolName{}; shared_ptr<string> startTs{}; shared_ptr<string> planEndTs{}; shared_ptr<string> planStartTs{}; shared_ptr<long> elasticNodeNum{}; shared_ptr<string> endTs{}; shared_ptr<string> planName{}; DescribeElasticDailyPlanResponseBodyElasticDailyPlanList() {} explicit DescribeElasticDailyPlanResponseBodyElasticDailyPlanList(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (status) { res["Status"] = boost::any(*status); } if (day) { res["Day"] = boost::any(*day); } if (resourcePoolName) { res["ResourcePoolName"] = boost::any(*resourcePoolName); } if (startTs) { res["StartTs"] = boost::any(*startTs); } if (planEndTs) { res["PlanEndTs"] = boost::any(*planEndTs); } if (planStartTs) { res["PlanStartTs"] = boost::any(*planStartTs); } if (elasticNodeNum) { res["ElasticNodeNum"] = boost::any(*elasticNodeNum); } if (endTs) { res["EndTs"] = boost::any(*endTs); } if (planName) { res["PlanName"] = boost::any(*planName); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Status") != m.end() && !m["Status"].empty()) { status = make_shared<long>(boost::any_cast<long>(m["Status"])); } if (m.find("Day") != m.end() && !m["Day"].empty()) { day = make_shared<string>(boost::any_cast<string>(m["Day"])); } if (m.find("ResourcePoolName") != m.end() && !m["ResourcePoolName"].empty()) { resourcePoolName = make_shared<string>(boost::any_cast<string>(m["ResourcePoolName"])); } if (m.find("StartTs") != m.end() && !m["StartTs"].empty()) { startTs = make_shared<string>(boost::any_cast<string>(m["StartTs"])); } if (m.find("PlanEndTs") != m.end() && !m["PlanEndTs"].empty()) { planEndTs = make_shared<string>(boost::any_cast<string>(m["PlanEndTs"])); } if (m.find("PlanStartTs") != m.end() && !m["PlanStartTs"].empty()) { planStartTs = make_shared<string>(boost::any_cast<string>(m["PlanStartTs"])); } if (m.find("ElasticNodeNum") != m.end() && !m["ElasticNodeNum"].empty()) { elasticNodeNum = make_shared<long>(boost::any_cast<long>(m["ElasticNodeNum"])); } if (m.find("EndTs") != m.end() && !m["EndTs"].empty()) { endTs = make_shared<string>(boost::any_cast<string>(m["EndTs"])); } if (m.find("PlanName") != m.end() && !m["PlanName"].empty()) { planName = make_shared<string>(boost::any_cast<string>(m["PlanName"])); } } virtual ~DescribeElasticDailyPlanResponseBodyElasticDailyPlanList() = default; }; class DescribeElasticDailyPlanResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; shared_ptr<vector<DescribeElasticDailyPlanResponseBodyElasticDailyPlanList>> elasticDailyPlanList{}; DescribeElasticDailyPlanResponseBody() {} explicit DescribeElasticDailyPlanResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } if (elasticDailyPlanList) { vector<boost::any> temp1; for(auto item1:*elasticDailyPlanList){ temp1.push_back(boost::any(item1.toMap())); } res["ElasticDailyPlanList"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("ElasticDailyPlanList") != m.end() && !m["ElasticDailyPlanList"].empty()) { if (typeid(vector<boost::any>) == m["ElasticDailyPlanList"].type()) { vector<DescribeElasticDailyPlanResponseBodyElasticDailyPlanList> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["ElasticDailyPlanList"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeElasticDailyPlanResponseBodyElasticDailyPlanList model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } elasticDailyPlanList = make_shared<vector<DescribeElasticDailyPlanResponseBodyElasticDailyPlanList>>(expect1); } } } virtual ~DescribeElasticDailyPlanResponseBody() = default; }; class DescribeElasticDailyPlanResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeElasticDailyPlanResponseBody> body{}; DescribeElasticDailyPlanResponse() {} explicit DescribeElasticDailyPlanResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeElasticDailyPlanResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeElasticDailyPlanResponseBody>(model1); } } } virtual ~DescribeElasticDailyPlanResponse() = default; }; class DescribeElasticPlanRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> elasticPlanName{}; shared_ptr<string> resourcePoolName{}; shared_ptr<bool> elasticPlanEnable{}; DescribeElasticPlanRequest() {} explicit DescribeElasticPlanRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (elasticPlanName) { res["ElasticPlanName"] = boost::any(*elasticPlanName); } if (resourcePoolName) { res["ResourcePoolName"] = boost::any(*resourcePoolName); } if (elasticPlanEnable) { res["ElasticPlanEnable"] = boost::any(*elasticPlanEnable); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("ElasticPlanName") != m.end() && !m["ElasticPlanName"].empty()) { elasticPlanName = make_shared<string>(boost::any_cast<string>(m["ElasticPlanName"])); } if (m.find("ResourcePoolName") != m.end() && !m["ResourcePoolName"].empty()) { resourcePoolName = make_shared<string>(boost::any_cast<string>(m["ResourcePoolName"])); } if (m.find("ElasticPlanEnable") != m.end() && !m["ElasticPlanEnable"].empty()) { elasticPlanEnable = make_shared<bool>(boost::any_cast<bool>(m["ElasticPlanEnable"])); } } virtual ~DescribeElasticPlanRequest() = default; }; class DescribeElasticPlanResponseBodyElasticPlanList : public Darabonba::Model { public: shared_ptr<string> endTime{}; shared_ptr<string> weeklyRepeat{}; shared_ptr<string> startTime{}; shared_ptr<string> resourcePoolName{}; shared_ptr<string> startDay{}; shared_ptr<long> elasticNodeNum{}; shared_ptr<bool> enable{}; shared_ptr<string> endDay{}; shared_ptr<string> planName{}; DescribeElasticPlanResponseBodyElasticPlanList() {} explicit DescribeElasticPlanResponseBodyElasticPlanList(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (endTime) { res["EndTime"] = boost::any(*endTime); } if (weeklyRepeat) { res["WeeklyRepeat"] = boost::any(*weeklyRepeat); } if (startTime) { res["StartTime"] = boost::any(*startTime); } if (resourcePoolName) { res["ResourcePoolName"] = boost::any(*resourcePoolName); } if (startDay) { res["StartDay"] = boost::any(*startDay); } if (elasticNodeNum) { res["ElasticNodeNum"] = boost::any(*elasticNodeNum); } if (enable) { res["Enable"] = boost::any(*enable); } if (endDay) { res["EndDay"] = boost::any(*endDay); } if (planName) { res["PlanName"] = boost::any(*planName); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("EndTime") != m.end() && !m["EndTime"].empty()) { endTime = make_shared<string>(boost::any_cast<string>(m["EndTime"])); } if (m.find("WeeklyRepeat") != m.end() && !m["WeeklyRepeat"].empty()) { weeklyRepeat = make_shared<string>(boost::any_cast<string>(m["WeeklyRepeat"])); } if (m.find("StartTime") != m.end() && !m["StartTime"].empty()) { startTime = make_shared<string>(boost::any_cast<string>(m["StartTime"])); } if (m.find("ResourcePoolName") != m.end() && !m["ResourcePoolName"].empty()) { resourcePoolName = make_shared<string>(boost::any_cast<string>(m["ResourcePoolName"])); } if (m.find("StartDay") != m.end() && !m["StartDay"].empty()) { startDay = make_shared<string>(boost::any_cast<string>(m["StartDay"])); } if (m.find("ElasticNodeNum") != m.end() && !m["ElasticNodeNum"].empty()) { elasticNodeNum = make_shared<long>(boost::any_cast<long>(m["ElasticNodeNum"])); } if (m.find("Enable") != m.end() && !m["Enable"].empty()) { enable = make_shared<bool>(boost::any_cast<bool>(m["Enable"])); } if (m.find("EndDay") != m.end() && !m["EndDay"].empty()) { endDay = make_shared<string>(boost::any_cast<string>(m["EndDay"])); } if (m.find("PlanName") != m.end() && !m["PlanName"].empty()) { planName = make_shared<string>(boost::any_cast<string>(m["PlanName"])); } } virtual ~DescribeElasticPlanResponseBodyElasticPlanList() = default; }; class DescribeElasticPlanResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; shared_ptr<vector<DescribeElasticPlanResponseBodyElasticPlanList>> elasticPlanList{}; DescribeElasticPlanResponseBody() {} explicit DescribeElasticPlanResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } if (elasticPlanList) { vector<boost::any> temp1; for(auto item1:*elasticPlanList){ temp1.push_back(boost::any(item1.toMap())); } res["ElasticPlanList"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("ElasticPlanList") != m.end() && !m["ElasticPlanList"].empty()) { if (typeid(vector<boost::any>) == m["ElasticPlanList"].type()) { vector<DescribeElasticPlanResponseBodyElasticPlanList> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["ElasticPlanList"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeElasticPlanResponseBodyElasticPlanList model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } elasticPlanList = make_shared<vector<DescribeElasticPlanResponseBodyElasticPlanList>>(expect1); } } } virtual ~DescribeElasticPlanResponseBody() = default; }; class DescribeElasticPlanResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeElasticPlanResponseBody> body{}; DescribeElasticPlanResponse() {} explicit DescribeElasticPlanResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeElasticPlanResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeElasticPlanResponseBody>(model1); } } } virtual ~DescribeElasticPlanResponse() = default; }; class DescribeInclinedTablesRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> tableType{}; shared_ptr<string> order{}; shared_ptr<long> pageSize{}; shared_ptr<long> pageNumber{}; DescribeInclinedTablesRequest() {} explicit DescribeInclinedTablesRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (tableType) { res["TableType"] = boost::any(*tableType); } if (order) { res["Order"] = boost::any(*order); } if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("TableType") != m.end() && !m["TableType"].empty()) { tableType = make_shared<string>(boost::any_cast<string>(m["TableType"])); } if (m.find("Order") != m.end() && !m["Order"].empty()) { order = make_shared<string>(boost::any_cast<string>(m["Order"])); } if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"])); } if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"])); } } virtual ~DescribeInclinedTablesRequest() = default; }; class DescribeInclinedTablesResponseBodyItemsTable : public Darabonba::Model { public: shared_ptr<string> type{}; shared_ptr<string> name{}; shared_ptr<string> schema{}; shared_ptr<bool> isIncline{}; shared_ptr<long> size{}; DescribeInclinedTablesResponseBodyItemsTable() {} explicit DescribeInclinedTablesResponseBodyItemsTable(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (type) { res["Type"] = boost::any(*type); } if (name) { res["Name"] = boost::any(*name); } if (schema) { res["Schema"] = boost::any(*schema); } if (isIncline) { res["IsIncline"] = boost::any(*isIncline); } if (size) { res["Size"] = boost::any(*size); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Type") != m.end() && !m["Type"].empty()) { type = make_shared<string>(boost::any_cast<string>(m["Type"])); } if (m.find("Name") != m.end() && !m["Name"].empty()) { name = make_shared<string>(boost::any_cast<string>(m["Name"])); } if (m.find("Schema") != m.end() && !m["Schema"].empty()) { schema = make_shared<string>(boost::any_cast<string>(m["Schema"])); } if (m.find("IsIncline") != m.end() && !m["IsIncline"].empty()) { isIncline = make_shared<bool>(boost::any_cast<bool>(m["IsIncline"])); } if (m.find("Size") != m.end() && !m["Size"].empty()) { size = make_shared<long>(boost::any_cast<long>(m["Size"])); } } virtual ~DescribeInclinedTablesResponseBodyItemsTable() = default; }; class DescribeInclinedTablesResponseBodyItems : public Darabonba::Model { public: shared_ptr<vector<DescribeInclinedTablesResponseBodyItemsTable>> table{}; DescribeInclinedTablesResponseBodyItems() {} explicit DescribeInclinedTablesResponseBodyItems(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (table) { vector<boost::any> temp1; for(auto item1:*table){ temp1.push_back(boost::any(item1.toMap())); } res["Table"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Table") != m.end() && !m["Table"].empty()) { if (typeid(vector<boost::any>) == m["Table"].type()) { vector<DescribeInclinedTablesResponseBodyItemsTable> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["Table"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeInclinedTablesResponseBodyItemsTable model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } table = make_shared<vector<DescribeInclinedTablesResponseBodyItemsTable>>(expect1); } } } virtual ~DescribeInclinedTablesResponseBodyItems() = default; }; class DescribeInclinedTablesResponseBody : public Darabonba::Model { public: shared_ptr<string> pageSize{}; shared_ptr<string> requestId{}; shared_ptr<string> pageNumber{}; shared_ptr<string> totalCount{}; shared_ptr<DescribeInclinedTablesResponseBodyItems> items{}; DescribeInclinedTablesResponseBody() {} explicit DescribeInclinedTablesResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (requestId) { res["RequestId"] = boost::any(*requestId); } if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } if (totalCount) { res["TotalCount"] = boost::any(*totalCount); } if (items) { res["Items"] = items ? boost::any(items->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<string>(boost::any_cast<string>(m["PageSize"])); } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<string>(boost::any_cast<string>(m["PageNumber"])); } if (m.find("TotalCount") != m.end() && !m["TotalCount"].empty()) { totalCount = make_shared<string>(boost::any_cast<string>(m["TotalCount"])); } if (m.find("Items") != m.end() && !m["Items"].empty()) { if (typeid(map<string, boost::any>) == m["Items"].type()) { DescribeInclinedTablesResponseBodyItems model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Items"])); items = make_shared<DescribeInclinedTablesResponseBodyItems>(model1); } } } virtual ~DescribeInclinedTablesResponseBody() = default; }; class DescribeInclinedTablesResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeInclinedTablesResponseBody> body{}; DescribeInclinedTablesResponse() {} explicit DescribeInclinedTablesResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeInclinedTablesResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeInclinedTablesResponseBody>(model1); } } } virtual ~DescribeInclinedTablesResponse() = default; }; class DescribeLoadTasksRecordsRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> startTime{}; shared_ptr<string> endTime{}; shared_ptr<string> DBName{}; shared_ptr<long> pageSize{}; shared_ptr<long> pageNumber{}; shared_ptr<string> order{}; shared_ptr<string> state{}; DescribeLoadTasksRecordsRequest() {} explicit DescribeLoadTasksRecordsRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (startTime) { res["StartTime"] = boost::any(*startTime); } if (endTime) { res["EndTime"] = boost::any(*endTime); } if (DBName) { res["DBName"] = boost::any(*DBName); } if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } if (order) { res["Order"] = boost::any(*order); } if (state) { res["State"] = boost::any(*state); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("StartTime") != m.end() && !m["StartTime"].empty()) { startTime = make_shared<string>(boost::any_cast<string>(m["StartTime"])); } if (m.find("EndTime") != m.end() && !m["EndTime"].empty()) { endTime = make_shared<string>(boost::any_cast<string>(m["EndTime"])); } if (m.find("DBName") != m.end() && !m["DBName"].empty()) { DBName = make_shared<string>(boost::any_cast<string>(m["DBName"])); } if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"])); } if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"])); } if (m.find("Order") != m.end() && !m["Order"].empty()) { order = make_shared<string>(boost::any_cast<string>(m["Order"])); } if (m.find("State") != m.end() && !m["State"].empty()) { state = make_shared<string>(boost::any_cast<string>(m["State"])); } } virtual ~DescribeLoadTasksRecordsRequest() = default; }; class DescribeLoadTasksRecordsResponseBodyLoadTasksRecords : public Darabonba::Model { public: shared_ptr<string> sql{}; shared_ptr<string> state{}; shared_ptr<string> createTime{}; shared_ptr<string> DBName{}; shared_ptr<string> processID{}; shared_ptr<string> updateTime{}; shared_ptr<string> jobName{}; shared_ptr<long> processRows{}; DescribeLoadTasksRecordsResponseBodyLoadTasksRecords() {} explicit DescribeLoadTasksRecordsResponseBodyLoadTasksRecords(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (sql) { res["Sql"] = boost::any(*sql); } if (state) { res["State"] = boost::any(*state); } if (createTime) { res["CreateTime"] = boost::any(*createTime); } if (DBName) { res["DBName"] = boost::any(*DBName); } if (processID) { res["ProcessID"] = boost::any(*processID); } if (updateTime) { res["UpdateTime"] = boost::any(*updateTime); } if (jobName) { res["JobName"] = boost::any(*jobName); } if (processRows) { res["ProcessRows"] = boost::any(*processRows); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Sql") != m.end() && !m["Sql"].empty()) { sql = make_shared<string>(boost::any_cast<string>(m["Sql"])); } if (m.find("State") != m.end() && !m["State"].empty()) { state = make_shared<string>(boost::any_cast<string>(m["State"])); } if (m.find("CreateTime") != m.end() && !m["CreateTime"].empty()) { createTime = make_shared<string>(boost::any_cast<string>(m["CreateTime"])); } if (m.find("DBName") != m.end() && !m["DBName"].empty()) { DBName = make_shared<string>(boost::any_cast<string>(m["DBName"])); } if (m.find("ProcessID") != m.end() && !m["ProcessID"].empty()) { processID = make_shared<string>(boost::any_cast<string>(m["ProcessID"])); } if (m.find("UpdateTime") != m.end() && !m["UpdateTime"].empty()) { updateTime = make_shared<string>(boost::any_cast<string>(m["UpdateTime"])); } if (m.find("JobName") != m.end() && !m["JobName"].empty()) { jobName = make_shared<string>(boost::any_cast<string>(m["JobName"])); } if (m.find("ProcessRows") != m.end() && !m["ProcessRows"].empty()) { processRows = make_shared<long>(boost::any_cast<long>(m["ProcessRows"])); } } virtual ~DescribeLoadTasksRecordsResponseBodyLoadTasksRecords() = default; }; class DescribeLoadTasksRecordsResponseBody : public Darabonba::Model { public: shared_ptr<string> totalCount{}; shared_ptr<string> pageSize{}; shared_ptr<string> requestId{}; shared_ptr<string> pageNumber{}; shared_ptr<string> DBClusterId{}; shared_ptr<vector<DescribeLoadTasksRecordsResponseBodyLoadTasksRecords>> loadTasksRecords{}; DescribeLoadTasksRecordsResponseBody() {} explicit DescribeLoadTasksRecordsResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (totalCount) { res["TotalCount"] = boost::any(*totalCount); } if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (requestId) { res["RequestId"] = boost::any(*requestId); } if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (loadTasksRecords) { vector<boost::any> temp1; for(auto item1:*loadTasksRecords){ temp1.push_back(boost::any(item1.toMap())); } res["LoadTasksRecords"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("TotalCount") != m.end() && !m["TotalCount"].empty()) { totalCount = make_shared<string>(boost::any_cast<string>(m["TotalCount"])); } if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<string>(boost::any_cast<string>(m["PageSize"])); } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<string>(boost::any_cast<string>(m["PageNumber"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("LoadTasksRecords") != m.end() && !m["LoadTasksRecords"].empty()) { if (typeid(vector<boost::any>) == m["LoadTasksRecords"].type()) { vector<DescribeLoadTasksRecordsResponseBodyLoadTasksRecords> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["LoadTasksRecords"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeLoadTasksRecordsResponseBodyLoadTasksRecords model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } loadTasksRecords = make_shared<vector<DescribeLoadTasksRecordsResponseBodyLoadTasksRecords>>(expect1); } } } virtual ~DescribeLoadTasksRecordsResponseBody() = default; }; class DescribeLoadTasksRecordsResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeLoadTasksRecordsResponseBody> body{}; DescribeLoadTasksRecordsResponse() {} explicit DescribeLoadTasksRecordsResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeLoadTasksRecordsResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeLoadTasksRecordsResponseBody>(model1); } } } virtual ~DescribeLoadTasksRecordsResponse() = default; }; class DescribeMaintenanceActionRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> region{}; shared_ptr<string> taskType{}; shared_ptr<long> isHistory{}; shared_ptr<long> pageSize{}; shared_ptr<long> pageNumber{}; shared_ptr<string> regionId{}; DescribeMaintenanceActionRequest() {} explicit DescribeMaintenanceActionRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (region) { res["Region"] = boost::any(*region); } if (taskType) { res["TaskType"] = boost::any(*taskType); } if (isHistory) { res["IsHistory"] = boost::any(*isHistory); } if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } if (regionId) { res["RegionId"] = boost::any(*regionId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("Region") != m.end() && !m["Region"].empty()) { region = make_shared<string>(boost::any_cast<string>(m["Region"])); } if (m.find("TaskType") != m.end() && !m["TaskType"].empty()) { taskType = make_shared<string>(boost::any_cast<string>(m["TaskType"])); } if (m.find("IsHistory") != m.end() && !m["IsHistory"].empty()) { isHistory = make_shared<long>(boost::any_cast<long>(m["IsHistory"])); } if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"])); } if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"])); } if (m.find("RegionId") != m.end() && !m["RegionId"].empty()) { regionId = make_shared<string>(boost::any_cast<string>(m["RegionId"])); } } virtual ~DescribeMaintenanceActionRequest() = default; }; class DescribeMaintenanceActionResponseBodyItems : public Darabonba::Model { public: shared_ptr<string> status{}; shared_ptr<string> deadline{}; shared_ptr<string> prepareInterval{}; shared_ptr<string> DBType{}; shared_ptr<string> startTime{}; shared_ptr<string> taskType{}; shared_ptr<string> DBVersion{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> modifiedTime{}; shared_ptr<string> region{}; shared_ptr<string> resultInfo{}; shared_ptr<string> createdTime{}; shared_ptr<long> id{}; shared_ptr<string> switchTime{}; DescribeMaintenanceActionResponseBodyItems() {} explicit DescribeMaintenanceActionResponseBodyItems(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (status) { res["Status"] = boost::any(*status); } if (deadline) { res["Deadline"] = boost::any(*deadline); } if (prepareInterval) { res["PrepareInterval"] = boost::any(*prepareInterval); } if (DBType) { res["DBType"] = boost::any(*DBType); } if (startTime) { res["StartTime"] = boost::any(*startTime); } if (taskType) { res["TaskType"] = boost::any(*taskType); } if (DBVersion) { res["DBVersion"] = boost::any(*DBVersion); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (modifiedTime) { res["ModifiedTime"] = boost::any(*modifiedTime); } if (region) { res["Region"] = boost::any(*region); } if (resultInfo) { res["ResultInfo"] = boost::any(*resultInfo); } if (createdTime) { res["CreatedTime"] = boost::any(*createdTime); } if (id) { res["Id"] = boost::any(*id); } if (switchTime) { res["SwitchTime"] = boost::any(*switchTime); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Status") != m.end() && !m["Status"].empty()) { status = make_shared<string>(boost::any_cast<string>(m["Status"])); } if (m.find("Deadline") != m.end() && !m["Deadline"].empty()) { deadline = make_shared<string>(boost::any_cast<string>(m["Deadline"])); } if (m.find("PrepareInterval") != m.end() && !m["PrepareInterval"].empty()) { prepareInterval = make_shared<string>(boost::any_cast<string>(m["PrepareInterval"])); } if (m.find("DBType") != m.end() && !m["DBType"].empty()) { DBType = make_shared<string>(boost::any_cast<string>(m["DBType"])); } if (m.find("StartTime") != m.end() && !m["StartTime"].empty()) { startTime = make_shared<string>(boost::any_cast<string>(m["StartTime"])); } if (m.find("TaskType") != m.end() && !m["TaskType"].empty()) { taskType = make_shared<string>(boost::any_cast<string>(m["TaskType"])); } if (m.find("DBVersion") != m.end() && !m["DBVersion"].empty()) { DBVersion = make_shared<string>(boost::any_cast<string>(m["DBVersion"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("ModifiedTime") != m.end() && !m["ModifiedTime"].empty()) { modifiedTime = make_shared<string>(boost::any_cast<string>(m["ModifiedTime"])); } if (m.find("Region") != m.end() && !m["Region"].empty()) { region = make_shared<string>(boost::any_cast<string>(m["Region"])); } if (m.find("ResultInfo") != m.end() && !m["ResultInfo"].empty()) { resultInfo = make_shared<string>(boost::any_cast<string>(m["ResultInfo"])); } if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) { createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"])); } if (m.find("Id") != m.end() && !m["Id"].empty()) { id = make_shared<long>(boost::any_cast<long>(m["Id"])); } if (m.find("SwitchTime") != m.end() && !m["SwitchTime"].empty()) { switchTime = make_shared<string>(boost::any_cast<string>(m["SwitchTime"])); } } virtual ~DescribeMaintenanceActionResponseBodyItems() = default; }; class DescribeMaintenanceActionResponseBody : public Darabonba::Model { public: shared_ptr<long> pageNumber{}; shared_ptr<string> requestId{}; shared_ptr<long> pageSize{}; shared_ptr<long> totalRecordCount{}; shared_ptr<vector<DescribeMaintenanceActionResponseBodyItems>> items{}; DescribeMaintenanceActionResponseBody() {} explicit DescribeMaintenanceActionResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } if (requestId) { res["RequestId"] = boost::any(*requestId); } if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (totalRecordCount) { res["TotalRecordCount"] = boost::any(*totalRecordCount); } if (items) { vector<boost::any> temp1; for(auto item1:*items){ temp1.push_back(boost::any(item1.toMap())); } res["Items"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"])); } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"])); } if (m.find("TotalRecordCount") != m.end() && !m["TotalRecordCount"].empty()) { totalRecordCount = make_shared<long>(boost::any_cast<long>(m["TotalRecordCount"])); } if (m.find("Items") != m.end() && !m["Items"].empty()) { if (typeid(vector<boost::any>) == m["Items"].type()) { vector<DescribeMaintenanceActionResponseBodyItems> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["Items"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeMaintenanceActionResponseBodyItems model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } items = make_shared<vector<DescribeMaintenanceActionResponseBodyItems>>(expect1); } } } virtual ~DescribeMaintenanceActionResponseBody() = default; }; class DescribeMaintenanceActionResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeMaintenanceActionResponseBody> body{}; DescribeMaintenanceActionResponse() {} explicit DescribeMaintenanceActionResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeMaintenanceActionResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeMaintenanceActionResponseBody>(model1); } } } virtual ~DescribeMaintenanceActionResponse() = default; }; class DescribeOperatorPermissionRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; DescribeOperatorPermissionRequest() {} explicit DescribeOperatorPermissionRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } } virtual ~DescribeOperatorPermissionRequest() = default; }; class DescribeOperatorPermissionResponseBody : public Darabonba::Model { public: shared_ptr<string> privileges{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> requestId{}; shared_ptr<string> expiredTime{}; shared_ptr<string> createdTime{}; DescribeOperatorPermissionResponseBody() {} explicit DescribeOperatorPermissionResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (privileges) { res["Privileges"] = boost::any(*privileges); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (requestId) { res["RequestId"] = boost::any(*requestId); } if (expiredTime) { res["ExpiredTime"] = boost::any(*expiredTime); } if (createdTime) { res["CreatedTime"] = boost::any(*createdTime); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Privileges") != m.end() && !m["Privileges"].empty()) { privileges = make_shared<string>(boost::any_cast<string>(m["Privileges"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("ExpiredTime") != m.end() && !m["ExpiredTime"].empty()) { expiredTime = make_shared<string>(boost::any_cast<string>(m["ExpiredTime"])); } if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) { createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"])); } } virtual ~DescribeOperatorPermissionResponseBody() = default; }; class DescribeOperatorPermissionResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeOperatorPermissionResponseBody> body{}; DescribeOperatorPermissionResponse() {} explicit DescribeOperatorPermissionResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeOperatorPermissionResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeOperatorPermissionResponseBody>(model1); } } } virtual ~DescribeOperatorPermissionResponse() = default; }; class DescribePatternPerformanceRequest : public Darabonba::Model { public: shared_ptr<string> DBClusterId{}; shared_ptr<string> startTime{}; shared_ptr<string> endTime{}; shared_ptr<string> regionId{}; shared_ptr<long> patternId{}; shared_ptr<string> key{}; DescribePatternPerformanceRequest() {} explicit DescribePatternPerformanceRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (startTime) { res["StartTime"] = boost::any(*startTime); } if (endTime) { res["EndTime"] = boost::any(*endTime); } if (regionId) { res["RegionId"] = boost::any(*regionId); } if (patternId) { res["PatternId"] = boost::any(*patternId); } if (key) { res["Key"] = boost::any(*key); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("StartTime") != m.end() && !m["StartTime"].empty()) { startTime = make_shared<string>(boost::any_cast<string>(m["StartTime"])); } if (m.find("EndTime") != m.end() && !m["EndTime"].empty()) { endTime = make_shared<string>(boost::any_cast<string>(m["EndTime"])); } if (m.find("RegionId") != m.end() && !m["RegionId"].empty()) { regionId = make_shared<string>(boost::any_cast<string>(m["RegionId"])); } if (m.find("PatternId") != m.end() && !m["PatternId"].empty()) { patternId = make_shared<long>(boost::any_cast<long>(m["PatternId"])); } if (m.find("Key") != m.end() && !m["Key"].empty()) { key = make_shared<string>(boost::any_cast<string>(m["Key"])); } } virtual ~DescribePatternPerformanceRequest() = default; }; class DescribePatternPerformanceResponseBodyPerformancesSeries : public Darabonba::Model { public: shared_ptr<vector<string>> values{}; shared_ptr<string> name{}; DescribePatternPerformanceResponseBodyPerformancesSeries() {} explicit DescribePatternPerformanceResponseBodyPerformancesSeries(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (values) { res["Values"] = boost::any(*values); } if (name) { res["Name"] = boost::any(*name); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Values") != m.end() && !m["Values"].empty()) { vector<string> toVec1; if (typeid(vector<boost::any>) == m["Values"].type()) { vector<boost::any> vec1 = boost::any_cast<vector<boost::any>>(m["Values"]); for (auto item:vec1) { toVec1.push_back(boost::any_cast<string>(item)); } } values = make_shared<vector<string>>(toVec1); } if (m.find("Name") != m.end() && !m["Name"].empty()) { name = make_shared<string>(boost::any_cast<string>(m["Name"])); } } virtual ~DescribePatternPerformanceResponseBodyPerformancesSeries() = default; }; class DescribePatternPerformanceResponseBodyPerformances : public Darabonba::Model { public: shared_ptr<string> key{}; shared_ptr<string> unit{}; shared_ptr<vector<DescribePatternPerformanceResponseBodyPerformancesSeries>> series{}; DescribePatternPerformanceResponseBodyPerformances() {} explicit DescribePatternPerformanceResponseBodyPerformances(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (key) { res["Key"] = boost::any(*key); } if (unit) { res["Unit"] = boost::any(*unit); } if (series) { vector<boost::any> temp1; for(auto item1:*series){ temp1.push_back(boost::any(item1.toMap())); } res["Series"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Key") != m.end() && !m["Key"].empty()) { key = make_shared<string>(boost::any_cast<string>(m["Key"])); } if (m.find("Unit") != m.end() && !m["Unit"].empty()) { unit = make_shared<string>(boost::any_cast<string>(m["Unit"])); } if (m.find("Series") != m.end() && !m["Series"].empty()) { if (typeid(vector<boost::any>) == m["Series"].type()) { vector<DescribePatternPerformanceResponseBodyPerformancesSeries> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["Series"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribePatternPerformanceResponseBodyPerformancesSeries model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } series = make_shared<vector<DescribePatternPerformanceResponseBodyPerformancesSeries>>(expect1); } } } virtual ~DescribePatternPerformanceResponseBodyPerformances() = default; }; class DescribePatternPerformanceResponseBody : public Darabonba::Model { public: shared_ptr<string> endTime{}; shared_ptr<string> requestId{}; shared_ptr<string> startTime{}; shared_ptr<vector<DescribePatternPerformanceResponseBodyPerformances>> performances{}; DescribePatternPerformanceResponseBody() {} explicit DescribePatternPerformanceResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (endTime) { res["EndTime"] = boost::any(*endTime); } if (requestId) { res["RequestId"] = boost::any(*requestId); } if (startTime) { res["StartTime"] = boost::any(*startTime); } if (performances) { vector<boost::any> temp1; for(auto item1:*performances){ temp1.push_back(boost::any(item1.toMap())); } res["Performances"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("EndTime") != m.end() && !m["EndTime"].empty()) { endTime = make_shared<string>(boost::any_cast<string>(m["EndTime"])); } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("StartTime") != m.end() && !m["StartTime"].empty()) { startTime = make_shared<string>(boost::any_cast<string>(m["StartTime"])); } if (m.find("Performances") != m.end() && !m["Performances"].empty()) { if (typeid(vector<boost::any>) == m["Performances"].type()) { vector<DescribePatternPerformanceResponseBodyPerformances> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["Performances"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribePatternPerformanceResponseBodyPerformances model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } performances = make_shared<vector<DescribePatternPerformanceResponseBodyPerformances>>(expect1); } } } virtual ~DescribePatternPerformanceResponseBody() = default; }; class DescribePatternPerformanceResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribePatternPerformanceResponseBody> body{}; DescribePatternPerformanceResponse() {} explicit DescribePatternPerformanceResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribePatternPerformanceResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribePatternPerformanceResponseBody>(model1); } } } virtual ~DescribePatternPerformanceResponse() = default; }; class DescribeProcessListRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<bool> showFull{}; shared_ptr<long> runningTime{}; shared_ptr<string> user{}; shared_ptr<string> keyword{}; shared_ptr<string> order{}; shared_ptr<long> pageSize{}; shared_ptr<long> pageNumber{}; DescribeProcessListRequest() {} explicit DescribeProcessListRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (showFull) { res["ShowFull"] = boost::any(*showFull); } if (runningTime) { res["RunningTime"] = boost::any(*runningTime); } if (user) { res["User"] = boost::any(*user); } if (keyword) { res["Keyword"] = boost::any(*keyword); } if (order) { res["Order"] = boost::any(*order); } if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("ShowFull") != m.end() && !m["ShowFull"].empty()) { showFull = make_shared<bool>(boost::any_cast<bool>(m["ShowFull"])); } if (m.find("RunningTime") != m.end() && !m["RunningTime"].empty()) { runningTime = make_shared<long>(boost::any_cast<long>(m["RunningTime"])); } if (m.find("User") != m.end() && !m["User"].empty()) { user = make_shared<string>(boost::any_cast<string>(m["User"])); } if (m.find("Keyword") != m.end() && !m["Keyword"].empty()) { keyword = make_shared<string>(boost::any_cast<string>(m["Keyword"])); } if (m.find("Order") != m.end() && !m["Order"].empty()) { order = make_shared<string>(boost::any_cast<string>(m["Order"])); } if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"])); } if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"])); } } virtual ~DescribeProcessListRequest() = default; }; class DescribeProcessListResponseBodyItemsProcess : public Darabonba::Model { public: shared_ptr<string> startTime{}; shared_ptr<long> time{}; shared_ptr<string> processId{}; shared_ptr<string> host{}; shared_ptr<string> DB{}; shared_ptr<string> command{}; shared_ptr<string> user{}; shared_ptr<long> id{}; shared_ptr<string> info{}; DescribeProcessListResponseBodyItemsProcess() {} explicit DescribeProcessListResponseBodyItemsProcess(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (startTime) { res["StartTime"] = boost::any(*startTime); } if (time) { res["Time"] = boost::any(*time); } if (processId) { res["ProcessId"] = boost::any(*processId); } if (host) { res["Host"] = boost::any(*host); } if (DB) { res["DB"] = boost::any(*DB); } if (command) { res["Command"] = boost::any(*command); } if (user) { res["User"] = boost::any(*user); } if (id) { res["Id"] = boost::any(*id); } if (info) { res["Info"] = boost::any(*info); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("StartTime") != m.end() && !m["StartTime"].empty()) { startTime = make_shared<string>(boost::any_cast<string>(m["StartTime"])); } if (m.find("Time") != m.end() && !m["Time"].empty()) { time = make_shared<long>(boost::any_cast<long>(m["Time"])); } if (m.find("ProcessId") != m.end() && !m["ProcessId"].empty()) { processId = make_shared<string>(boost::any_cast<string>(m["ProcessId"])); } if (m.find("Host") != m.end() && !m["Host"].empty()) { host = make_shared<string>(boost::any_cast<string>(m["Host"])); } if (m.find("DB") != m.end() && !m["DB"].empty()) { DB = make_shared<string>(boost::any_cast<string>(m["DB"])); } if (m.find("Command") != m.end() && !m["Command"].empty()) { command = make_shared<string>(boost::any_cast<string>(m["Command"])); } if (m.find("User") != m.end() && !m["User"].empty()) { user = make_shared<string>(boost::any_cast<string>(m["User"])); } if (m.find("Id") != m.end() && !m["Id"].empty()) { id = make_shared<long>(boost::any_cast<long>(m["Id"])); } if (m.find("Info") != m.end() && !m["Info"].empty()) { info = make_shared<string>(boost::any_cast<string>(m["Info"])); } } virtual ~DescribeProcessListResponseBodyItemsProcess() = default; }; class DescribeProcessListResponseBodyItems : public Darabonba::Model { public: shared_ptr<vector<DescribeProcessListResponseBodyItemsProcess>> process{}; DescribeProcessListResponseBodyItems() {} explicit DescribeProcessListResponseBodyItems(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (process) { vector<boost::any> temp1; for(auto item1:*process){ temp1.push_back(boost::any(item1.toMap())); } res["Process"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Process") != m.end() && !m["Process"].empty()) { if (typeid(vector<boost::any>) == m["Process"].type()) { vector<DescribeProcessListResponseBodyItemsProcess> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["Process"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeProcessListResponseBodyItemsProcess model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } process = make_shared<vector<DescribeProcessListResponseBodyItemsProcess>>(expect1); } } } virtual ~DescribeProcessListResponseBodyItems() = default; }; class DescribeProcessListResponseBody : public Darabonba::Model { public: shared_ptr<string> pageSize{}; shared_ptr<string> requestId{}; shared_ptr<string> pageNumber{}; shared_ptr<string> totalCount{}; shared_ptr<DescribeProcessListResponseBodyItems> items{}; DescribeProcessListResponseBody() {} explicit DescribeProcessListResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (requestId) { res["RequestId"] = boost::any(*requestId); } if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } if (totalCount) { res["TotalCount"] = boost::any(*totalCount); } if (items) { res["Items"] = items ? boost::any(items->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<string>(boost::any_cast<string>(m["PageSize"])); } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<string>(boost::any_cast<string>(m["PageNumber"])); } if (m.find("TotalCount") != m.end() && !m["TotalCount"].empty()) { totalCount = make_shared<string>(boost::any_cast<string>(m["TotalCount"])); } if (m.find("Items") != m.end() && !m["Items"].empty()) { if (typeid(map<string, boost::any>) == m["Items"].type()) { DescribeProcessListResponseBodyItems model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Items"])); items = make_shared<DescribeProcessListResponseBodyItems>(model1); } } } virtual ~DescribeProcessListResponseBody() = default; }; class DescribeProcessListResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeProcessListResponseBody> body{}; DescribeProcessListResponse() {} explicit DescribeProcessListResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeProcessListResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeProcessListResponseBody>(model1); } } } virtual ~DescribeProcessListResponse() = default; }; class DescribeRegionsRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> acceptLanguage{}; DescribeRegionsRequest() {} explicit DescribeRegionsRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (acceptLanguage) { res["AcceptLanguage"] = boost::any(*acceptLanguage); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("AcceptLanguage") != m.end() && !m["AcceptLanguage"].empty()) { acceptLanguage = make_shared<string>(boost::any_cast<string>(m["AcceptLanguage"])); } } virtual ~DescribeRegionsRequest() = default; }; class DescribeRegionsResponseBodyRegionsRegionZonesZone : public Darabonba::Model { public: shared_ptr<string> zoneId{}; shared_ptr<bool> vpcEnabled{}; shared_ptr<string> localName{}; DescribeRegionsResponseBodyRegionsRegionZonesZone() {} explicit DescribeRegionsResponseBodyRegionsRegionZonesZone(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (zoneId) { res["ZoneId"] = boost::any(*zoneId); } if (vpcEnabled) { res["VpcEnabled"] = boost::any(*vpcEnabled); } if (localName) { res["LocalName"] = boost::any(*localName); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ZoneId") != m.end() && !m["ZoneId"].empty()) { zoneId = make_shared<string>(boost::any_cast<string>(m["ZoneId"])); } if (m.find("VpcEnabled") != m.end() && !m["VpcEnabled"].empty()) { vpcEnabled = make_shared<bool>(boost::any_cast<bool>(m["VpcEnabled"])); } if (m.find("LocalName") != m.end() && !m["LocalName"].empty()) { localName = make_shared<string>(boost::any_cast<string>(m["LocalName"])); } } virtual ~DescribeRegionsResponseBodyRegionsRegionZonesZone() = default; }; class DescribeRegionsResponseBodyRegionsRegionZones : public Darabonba::Model { public: shared_ptr<vector<DescribeRegionsResponseBodyRegionsRegionZonesZone>> zone{}; DescribeRegionsResponseBodyRegionsRegionZones() {} explicit DescribeRegionsResponseBodyRegionsRegionZones(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (zone) { vector<boost::any> temp1; for(auto item1:*zone){ temp1.push_back(boost::any(item1.toMap())); } res["Zone"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Zone") != m.end() && !m["Zone"].empty()) { if (typeid(vector<boost::any>) == m["Zone"].type()) { vector<DescribeRegionsResponseBodyRegionsRegionZonesZone> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["Zone"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeRegionsResponseBodyRegionsRegionZonesZone model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } zone = make_shared<vector<DescribeRegionsResponseBodyRegionsRegionZonesZone>>(expect1); } } } virtual ~DescribeRegionsResponseBodyRegionsRegionZones() = default; }; class DescribeRegionsResponseBodyRegionsRegion : public Darabonba::Model { public: shared_ptr<string> regionEndpoint{}; shared_ptr<string> localName{}; shared_ptr<string> regionId{}; shared_ptr<DescribeRegionsResponseBodyRegionsRegionZones> zones{}; DescribeRegionsResponseBodyRegionsRegion() {} explicit DescribeRegionsResponseBodyRegionsRegion(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (regionEndpoint) { res["RegionEndpoint"] = boost::any(*regionEndpoint); } if (localName) { res["LocalName"] = boost::any(*localName); } if (regionId) { res["RegionId"] = boost::any(*regionId); } if (zones) { res["Zones"] = zones ? boost::any(zones->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RegionEndpoint") != m.end() && !m["RegionEndpoint"].empty()) { regionEndpoint = make_shared<string>(boost::any_cast<string>(m["RegionEndpoint"])); } if (m.find("LocalName") != m.end() && !m["LocalName"].empty()) { localName = make_shared<string>(boost::any_cast<string>(m["LocalName"])); } if (m.find("RegionId") != m.end() && !m["RegionId"].empty()) { regionId = make_shared<string>(boost::any_cast<string>(m["RegionId"])); } if (m.find("Zones") != m.end() && !m["Zones"].empty()) { if (typeid(map<string, boost::any>) == m["Zones"].type()) { DescribeRegionsResponseBodyRegionsRegionZones model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Zones"])); zones = make_shared<DescribeRegionsResponseBodyRegionsRegionZones>(model1); } } } virtual ~DescribeRegionsResponseBodyRegionsRegion() = default; }; class DescribeRegionsResponseBodyRegions : public Darabonba::Model { public: shared_ptr<vector<DescribeRegionsResponseBodyRegionsRegion>> region{}; DescribeRegionsResponseBodyRegions() {} explicit DescribeRegionsResponseBodyRegions(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (region) { vector<boost::any> temp1; for(auto item1:*region){ temp1.push_back(boost::any(item1.toMap())); } res["Region"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Region") != m.end() && !m["Region"].empty()) { if (typeid(vector<boost::any>) == m["Region"].type()) { vector<DescribeRegionsResponseBodyRegionsRegion> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["Region"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeRegionsResponseBodyRegionsRegion model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } region = make_shared<vector<DescribeRegionsResponseBodyRegionsRegion>>(expect1); } } } virtual ~DescribeRegionsResponseBodyRegions() = default; }; class DescribeRegionsResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; shared_ptr<DescribeRegionsResponseBodyRegions> regions{}; DescribeRegionsResponseBody() {} explicit DescribeRegionsResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } if (regions) { res["Regions"] = regions ? boost::any(regions->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("Regions") != m.end() && !m["Regions"].empty()) { if (typeid(map<string, boost::any>) == m["Regions"].type()) { DescribeRegionsResponseBodyRegions model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Regions"])); regions = make_shared<DescribeRegionsResponseBodyRegions>(model1); } } } virtual ~DescribeRegionsResponseBody() = default; }; class DescribeRegionsResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeRegionsResponseBody> body{}; DescribeRegionsResponse() {} explicit DescribeRegionsResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeRegionsResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeRegionsResponseBody>(model1); } } } virtual ~DescribeRegionsResponse() = default; }; class DescribeSchemasRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; DescribeSchemasRequest() {} explicit DescribeSchemasRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } } virtual ~DescribeSchemasRequest() = default; }; class DescribeSchemasResponseBodyItemsSchema : public Darabonba::Model { public: shared_ptr<string> schemaName{}; shared_ptr<string> DBClusterId{}; DescribeSchemasResponseBodyItemsSchema() {} explicit DescribeSchemasResponseBodyItemsSchema(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (schemaName) { res["SchemaName"] = boost::any(*schemaName); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("SchemaName") != m.end() && !m["SchemaName"].empty()) { schemaName = make_shared<string>(boost::any_cast<string>(m["SchemaName"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } } virtual ~DescribeSchemasResponseBodyItemsSchema() = default; }; class DescribeSchemasResponseBodyItems : public Darabonba::Model { public: shared_ptr<vector<DescribeSchemasResponseBodyItemsSchema>> schema{}; DescribeSchemasResponseBodyItems() {} explicit DescribeSchemasResponseBodyItems(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (schema) { vector<boost::any> temp1; for(auto item1:*schema){ temp1.push_back(boost::any(item1.toMap())); } res["Schema"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Schema") != m.end() && !m["Schema"].empty()) { if (typeid(vector<boost::any>) == m["Schema"].type()) { vector<DescribeSchemasResponseBodyItemsSchema> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["Schema"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeSchemasResponseBodyItemsSchema model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } schema = make_shared<vector<DescribeSchemasResponseBodyItemsSchema>>(expect1); } } } virtual ~DescribeSchemasResponseBodyItems() = default; }; class DescribeSchemasResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; shared_ptr<DescribeSchemasResponseBodyItems> items{}; DescribeSchemasResponseBody() {} explicit DescribeSchemasResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } if (items) { res["Items"] = items ? boost::any(items->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("Items") != m.end() && !m["Items"].empty()) { if (typeid(map<string, boost::any>) == m["Items"].type()) { DescribeSchemasResponseBodyItems model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Items"])); items = make_shared<DescribeSchemasResponseBodyItems>(model1); } } } virtual ~DescribeSchemasResponseBody() = default; }; class DescribeSchemasResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeSchemasResponseBody> body{}; DescribeSchemasResponse() {} explicit DescribeSchemasResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeSchemasResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeSchemasResponseBody>(model1); } } } virtual ~DescribeSchemasResponse() = default; }; class DescribeSlowLogRecordsRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> startTime{}; shared_ptr<string> endTime{}; shared_ptr<string> DBName{}; shared_ptr<long> pageSize{}; shared_ptr<long> pageNumber{}; shared_ptr<string> processID{}; shared_ptr<string> order{}; shared_ptr<string> range{}; shared_ptr<string> state{}; DescribeSlowLogRecordsRequest() {} explicit DescribeSlowLogRecordsRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (startTime) { res["StartTime"] = boost::any(*startTime); } if (endTime) { res["EndTime"] = boost::any(*endTime); } if (DBName) { res["DBName"] = boost::any(*DBName); } if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } if (processID) { res["ProcessID"] = boost::any(*processID); } if (order) { res["Order"] = boost::any(*order); } if (range) { res["Range"] = boost::any(*range); } if (state) { res["State"] = boost::any(*state); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("StartTime") != m.end() && !m["StartTime"].empty()) { startTime = make_shared<string>(boost::any_cast<string>(m["StartTime"])); } if (m.find("EndTime") != m.end() && !m["EndTime"].empty()) { endTime = make_shared<string>(boost::any_cast<string>(m["EndTime"])); } if (m.find("DBName") != m.end() && !m["DBName"].empty()) { DBName = make_shared<string>(boost::any_cast<string>(m["DBName"])); } if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"])); } if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"])); } if (m.find("ProcessID") != m.end() && !m["ProcessID"].empty()) { processID = make_shared<string>(boost::any_cast<string>(m["ProcessID"])); } if (m.find("Order") != m.end() && !m["Order"].empty()) { order = make_shared<string>(boost::any_cast<string>(m["Order"])); } if (m.find("Range") != m.end() && !m["Range"].empty()) { range = make_shared<string>(boost::any_cast<string>(m["Range"])); } if (m.find("State") != m.end() && !m["State"].empty()) { state = make_shared<string>(boost::any_cast<string>(m["State"])); } } virtual ~DescribeSlowLogRecordsRequest() = default; }; class DescribeSlowLogRecordsResponseBodyItemsSlowLogRecord : public Darabonba::Model { public: shared_ptr<string> hostAddress{}; shared_ptr<long> scanTime{}; shared_ptr<string> SQLText{}; shared_ptr<string> outputSize{}; shared_ptr<string> peakMemoryUsage{}; shared_ptr<string> state{}; shared_ptr<long> wallTime{}; shared_ptr<string> scanSize{}; shared_ptr<string> executionStartTime{}; shared_ptr<long> queryTime{}; shared_ptr<long> returnRowCounts{}; shared_ptr<long> scanRows{}; shared_ptr<long> parseRowCounts{}; shared_ptr<string> DBName{}; shared_ptr<long> planningTime{}; shared_ptr<long> queueTime{}; shared_ptr<string> userName{}; shared_ptr<string> processID{}; DescribeSlowLogRecordsResponseBodyItemsSlowLogRecord() {} explicit DescribeSlowLogRecordsResponseBodyItemsSlowLogRecord(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (hostAddress) { res["HostAddress"] = boost::any(*hostAddress); } if (scanTime) { res["ScanTime"] = boost::any(*scanTime); } if (SQLText) { res["SQLText"] = boost::any(*SQLText); } if (outputSize) { res["OutputSize"] = boost::any(*outputSize); } if (peakMemoryUsage) { res["PeakMemoryUsage"] = boost::any(*peakMemoryUsage); } if (state) { res["State"] = boost::any(*state); } if (wallTime) { res["WallTime"] = boost::any(*wallTime); } if (scanSize) { res["ScanSize"] = boost::any(*scanSize); } if (executionStartTime) { res["ExecutionStartTime"] = boost::any(*executionStartTime); } if (queryTime) { res["QueryTime"] = boost::any(*queryTime); } if (returnRowCounts) { res["ReturnRowCounts"] = boost::any(*returnRowCounts); } if (scanRows) { res["ScanRows"] = boost::any(*scanRows); } if (parseRowCounts) { res["ParseRowCounts"] = boost::any(*parseRowCounts); } if (DBName) { res["DBName"] = boost::any(*DBName); } if (planningTime) { res["PlanningTime"] = boost::any(*planningTime); } if (queueTime) { res["QueueTime"] = boost::any(*queueTime); } if (userName) { res["UserName"] = boost::any(*userName); } if (processID) { res["ProcessID"] = boost::any(*processID); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("HostAddress") != m.end() && !m["HostAddress"].empty()) { hostAddress = make_shared<string>(boost::any_cast<string>(m["HostAddress"])); } if (m.find("ScanTime") != m.end() && !m["ScanTime"].empty()) { scanTime = make_shared<long>(boost::any_cast<long>(m["ScanTime"])); } if (m.find("SQLText") != m.end() && !m["SQLText"].empty()) { SQLText = make_shared<string>(boost::any_cast<string>(m["SQLText"])); } if (m.find("OutputSize") != m.end() && !m["OutputSize"].empty()) { outputSize = make_shared<string>(boost::any_cast<string>(m["OutputSize"])); } if (m.find("PeakMemoryUsage") != m.end() && !m["PeakMemoryUsage"].empty()) { peakMemoryUsage = make_shared<string>(boost::any_cast<string>(m["PeakMemoryUsage"])); } if (m.find("State") != m.end() && !m["State"].empty()) { state = make_shared<string>(boost::any_cast<string>(m["State"])); } if (m.find("WallTime") != m.end() && !m["WallTime"].empty()) { wallTime = make_shared<long>(boost::any_cast<long>(m["WallTime"])); } if (m.find("ScanSize") != m.end() && !m["ScanSize"].empty()) { scanSize = make_shared<string>(boost::any_cast<string>(m["ScanSize"])); } if (m.find("ExecutionStartTime") != m.end() && !m["ExecutionStartTime"].empty()) { executionStartTime = make_shared<string>(boost::any_cast<string>(m["ExecutionStartTime"])); } if (m.find("QueryTime") != m.end() && !m["QueryTime"].empty()) { queryTime = make_shared<long>(boost::any_cast<long>(m["QueryTime"])); } if (m.find("ReturnRowCounts") != m.end() && !m["ReturnRowCounts"].empty()) { returnRowCounts = make_shared<long>(boost::any_cast<long>(m["ReturnRowCounts"])); } if (m.find("ScanRows") != m.end() && !m["ScanRows"].empty()) { scanRows = make_shared<long>(boost::any_cast<long>(m["ScanRows"])); } if (m.find("ParseRowCounts") != m.end() && !m["ParseRowCounts"].empty()) { parseRowCounts = make_shared<long>(boost::any_cast<long>(m["ParseRowCounts"])); } if (m.find("DBName") != m.end() && !m["DBName"].empty()) { DBName = make_shared<string>(boost::any_cast<string>(m["DBName"])); } if (m.find("PlanningTime") != m.end() && !m["PlanningTime"].empty()) { planningTime = make_shared<long>(boost::any_cast<long>(m["PlanningTime"])); } if (m.find("QueueTime") != m.end() && !m["QueueTime"].empty()) { queueTime = make_shared<long>(boost::any_cast<long>(m["QueueTime"])); } if (m.find("UserName") != m.end() && !m["UserName"].empty()) { userName = make_shared<string>(boost::any_cast<string>(m["UserName"])); } if (m.find("ProcessID") != m.end() && !m["ProcessID"].empty()) { processID = make_shared<string>(boost::any_cast<string>(m["ProcessID"])); } } virtual ~DescribeSlowLogRecordsResponseBodyItemsSlowLogRecord() = default; }; class DescribeSlowLogRecordsResponseBodyItems : public Darabonba::Model { public: shared_ptr<vector<DescribeSlowLogRecordsResponseBodyItemsSlowLogRecord>> slowLogRecord{}; DescribeSlowLogRecordsResponseBodyItems() {} explicit DescribeSlowLogRecordsResponseBodyItems(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (slowLogRecord) { vector<boost::any> temp1; for(auto item1:*slowLogRecord){ temp1.push_back(boost::any(item1.toMap())); } res["SlowLogRecord"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("SlowLogRecord") != m.end() && !m["SlowLogRecord"].empty()) { if (typeid(vector<boost::any>) == m["SlowLogRecord"].type()) { vector<DescribeSlowLogRecordsResponseBodyItemsSlowLogRecord> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["SlowLogRecord"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeSlowLogRecordsResponseBodyItemsSlowLogRecord model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } slowLogRecord = make_shared<vector<DescribeSlowLogRecordsResponseBodyItemsSlowLogRecord>>(expect1); } } } virtual ~DescribeSlowLogRecordsResponseBodyItems() = default; }; class DescribeSlowLogRecordsResponseBody : public Darabonba::Model { public: shared_ptr<string> totalCount{}; shared_ptr<string> pageSize{}; shared_ptr<string> requestId{}; shared_ptr<string> pageNumber{}; shared_ptr<string> DBClusterId{}; shared_ptr<DescribeSlowLogRecordsResponseBodyItems> items{}; DescribeSlowLogRecordsResponseBody() {} explicit DescribeSlowLogRecordsResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (totalCount) { res["TotalCount"] = boost::any(*totalCount); } if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (requestId) { res["RequestId"] = boost::any(*requestId); } if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (items) { res["Items"] = items ? boost::any(items->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("TotalCount") != m.end() && !m["TotalCount"].empty()) { totalCount = make_shared<string>(boost::any_cast<string>(m["TotalCount"])); } if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<string>(boost::any_cast<string>(m["PageSize"])); } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<string>(boost::any_cast<string>(m["PageNumber"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("Items") != m.end() && !m["Items"].empty()) { if (typeid(map<string, boost::any>) == m["Items"].type()) { DescribeSlowLogRecordsResponseBodyItems model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Items"])); items = make_shared<DescribeSlowLogRecordsResponseBodyItems>(model1); } } } virtual ~DescribeSlowLogRecordsResponseBody() = default; }; class DescribeSlowLogRecordsResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeSlowLogRecordsResponseBody> body{}; DescribeSlowLogRecordsResponse() {} explicit DescribeSlowLogRecordsResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeSlowLogRecordsResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeSlowLogRecordsResponseBody>(model1); } } } virtual ~DescribeSlowLogRecordsResponse() = default; }; class DescribeSlowLogTrendRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> startTime{}; shared_ptr<string> endTime{}; shared_ptr<string> DBName{}; DescribeSlowLogTrendRequest() {} explicit DescribeSlowLogTrendRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (startTime) { res["StartTime"] = boost::any(*startTime); } if (endTime) { res["EndTime"] = boost::any(*endTime); } if (DBName) { res["DBName"] = boost::any(*DBName); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("StartTime") != m.end() && !m["StartTime"].empty()) { startTime = make_shared<string>(boost::any_cast<string>(m["StartTime"])); } if (m.find("EndTime") != m.end() && !m["EndTime"].empty()) { endTime = make_shared<string>(boost::any_cast<string>(m["EndTime"])); } if (m.find("DBName") != m.end() && !m["DBName"].empty()) { DBName = make_shared<string>(boost::any_cast<string>(m["DBName"])); } } virtual ~DescribeSlowLogTrendRequest() = default; }; class DescribeSlowLogTrendResponseBodyItemsSlowLogTrendItemSeriesSeriesItem : public Darabonba::Model { public: shared_ptr<string> name{}; shared_ptr<string> values{}; DescribeSlowLogTrendResponseBodyItemsSlowLogTrendItemSeriesSeriesItem() {} explicit DescribeSlowLogTrendResponseBodyItemsSlowLogTrendItemSeriesSeriesItem(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (name) { res["Name"] = boost::any(*name); } if (values) { res["Values"] = boost::any(*values); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Name") != m.end() && !m["Name"].empty()) { name = make_shared<string>(boost::any_cast<string>(m["Name"])); } if (m.find("Values") != m.end() && !m["Values"].empty()) { values = make_shared<string>(boost::any_cast<string>(m["Values"])); } } virtual ~DescribeSlowLogTrendResponseBodyItemsSlowLogTrendItemSeriesSeriesItem() = default; }; class DescribeSlowLogTrendResponseBodyItemsSlowLogTrendItemSeries : public Darabonba::Model { public: shared_ptr<vector<DescribeSlowLogTrendResponseBodyItemsSlowLogTrendItemSeriesSeriesItem>> seriesItem{}; DescribeSlowLogTrendResponseBodyItemsSlowLogTrendItemSeries() {} explicit DescribeSlowLogTrendResponseBodyItemsSlowLogTrendItemSeries(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (seriesItem) { vector<boost::any> temp1; for(auto item1:*seriesItem){ temp1.push_back(boost::any(item1.toMap())); } res["SeriesItem"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("SeriesItem") != m.end() && !m["SeriesItem"].empty()) { if (typeid(vector<boost::any>) == m["SeriesItem"].type()) { vector<DescribeSlowLogTrendResponseBodyItemsSlowLogTrendItemSeriesSeriesItem> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["SeriesItem"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeSlowLogTrendResponseBodyItemsSlowLogTrendItemSeriesSeriesItem model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } seriesItem = make_shared<vector<DescribeSlowLogTrendResponseBodyItemsSlowLogTrendItemSeriesSeriesItem>>(expect1); } } } virtual ~DescribeSlowLogTrendResponseBodyItemsSlowLogTrendItemSeries() = default; }; class DescribeSlowLogTrendResponseBodyItemsSlowLogTrendItem : public Darabonba::Model { public: shared_ptr<string> key{}; shared_ptr<string> unit{}; shared_ptr<DescribeSlowLogTrendResponseBodyItemsSlowLogTrendItemSeries> series{}; DescribeSlowLogTrendResponseBodyItemsSlowLogTrendItem() {} explicit DescribeSlowLogTrendResponseBodyItemsSlowLogTrendItem(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (key) { res["Key"] = boost::any(*key); } if (unit) { res["Unit"] = boost::any(*unit); } if (series) { res["Series"] = series ? boost::any(series->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Key") != m.end() && !m["Key"].empty()) { key = make_shared<string>(boost::any_cast<string>(m["Key"])); } if (m.find("Unit") != m.end() && !m["Unit"].empty()) { unit = make_shared<string>(boost::any_cast<string>(m["Unit"])); } if (m.find("Series") != m.end() && !m["Series"].empty()) { if (typeid(map<string, boost::any>) == m["Series"].type()) { DescribeSlowLogTrendResponseBodyItemsSlowLogTrendItemSeries model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Series"])); series = make_shared<DescribeSlowLogTrendResponseBodyItemsSlowLogTrendItemSeries>(model1); } } } virtual ~DescribeSlowLogTrendResponseBodyItemsSlowLogTrendItem() = default; }; class DescribeSlowLogTrendResponseBodyItems : public Darabonba::Model { public: shared_ptr<vector<DescribeSlowLogTrendResponseBodyItemsSlowLogTrendItem>> slowLogTrendItem{}; DescribeSlowLogTrendResponseBodyItems() {} explicit DescribeSlowLogTrendResponseBodyItems(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (slowLogTrendItem) { vector<boost::any> temp1; for(auto item1:*slowLogTrendItem){ temp1.push_back(boost::any(item1.toMap())); } res["SlowLogTrendItem"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("SlowLogTrendItem") != m.end() && !m["SlowLogTrendItem"].empty()) { if (typeid(vector<boost::any>) == m["SlowLogTrendItem"].type()) { vector<DescribeSlowLogTrendResponseBodyItemsSlowLogTrendItem> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["SlowLogTrendItem"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeSlowLogTrendResponseBodyItemsSlowLogTrendItem model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } slowLogTrendItem = make_shared<vector<DescribeSlowLogTrendResponseBodyItemsSlowLogTrendItem>>(expect1); } } } virtual ~DescribeSlowLogTrendResponseBodyItems() = default; }; class DescribeSlowLogTrendResponseBody : public Darabonba::Model { public: shared_ptr<string> endTime{}; shared_ptr<string> startTime{}; shared_ptr<string> requestId{}; shared_ptr<string> DBClusterId{}; shared_ptr<DescribeSlowLogTrendResponseBodyItems> items{}; DescribeSlowLogTrendResponseBody() {} explicit DescribeSlowLogTrendResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (endTime) { res["EndTime"] = boost::any(*endTime); } if (startTime) { res["StartTime"] = boost::any(*startTime); } if (requestId) { res["RequestId"] = boost::any(*requestId); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (items) { res["Items"] = items ? boost::any(items->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("EndTime") != m.end() && !m["EndTime"].empty()) { endTime = make_shared<string>(boost::any_cast<string>(m["EndTime"])); } if (m.find("StartTime") != m.end() && !m["StartTime"].empty()) { startTime = make_shared<string>(boost::any_cast<string>(m["StartTime"])); } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("Items") != m.end() && !m["Items"].empty()) { if (typeid(map<string, boost::any>) == m["Items"].type()) { DescribeSlowLogTrendResponseBodyItems model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Items"])); items = make_shared<DescribeSlowLogTrendResponseBodyItems>(model1); } } } virtual ~DescribeSlowLogTrendResponseBody() = default; }; class DescribeSlowLogTrendResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeSlowLogTrendResponseBody> body{}; DescribeSlowLogTrendResponse() {} explicit DescribeSlowLogTrendResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeSlowLogTrendResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeSlowLogTrendResponseBody>(model1); } } } virtual ~DescribeSlowLogTrendResponse() = default; }; class DescribeSqlPatternRequest : public Darabonba::Model { public: shared_ptr<string> startTime{}; shared_ptr<string> order{}; shared_ptr<long> pageNumber{}; shared_ptr<string> sqlPattern{}; shared_ptr<string> type{}; shared_ptr<string> DBClusterId{}; shared_ptr<long> pageSize{}; shared_ptr<string> regionId{}; DescribeSqlPatternRequest() {} explicit DescribeSqlPatternRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (startTime) { res["StartTime"] = boost::any(*startTime); } if (order) { res["Order"] = boost::any(*order); } if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } if (sqlPattern) { res["SqlPattern"] = boost::any(*sqlPattern); } if (type) { res["Type"] = boost::any(*type); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (regionId) { res["RegionId"] = boost::any(*regionId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("StartTime") != m.end() && !m["StartTime"].empty()) { startTime = make_shared<string>(boost::any_cast<string>(m["StartTime"])); } if (m.find("Order") != m.end() && !m["Order"].empty()) { order = make_shared<string>(boost::any_cast<string>(m["Order"])); } if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"])); } if (m.find("SqlPattern") != m.end() && !m["SqlPattern"].empty()) { sqlPattern = make_shared<string>(boost::any_cast<string>(m["SqlPattern"])); } if (m.find("Type") != m.end() && !m["Type"].empty()) { type = make_shared<string>(boost::any_cast<string>(m["Type"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"])); } if (m.find("RegionId") != m.end() && !m["RegionId"].empty()) { regionId = make_shared<string>(boost::any_cast<string>(m["RegionId"])); } } virtual ~DescribeSqlPatternRequest() = default; }; class DescribeSqlPatternResponseBodyItems : public Darabonba::Model { public: shared_ptr<string> avgStageCount{}; shared_ptr<string> maxCpuTime{}; shared_ptr<string> accessIP{}; shared_ptr<string> avgScanSize{}; shared_ptr<string> maxScanSize{}; shared_ptr<string> maxPeakMemory{}; shared_ptr<string> avgCpuTime{}; shared_ptr<string> user{}; shared_ptr<string> avgPeakMemory{}; shared_ptr<string> maxStageCount{}; shared_ptr<string> maxTaskCount{}; shared_ptr<string> instanceName{}; shared_ptr<string> queryCount{}; shared_ptr<string> reportDate{}; shared_ptr<string> pattern{}; shared_ptr<string> avgTaskCount{}; DescribeSqlPatternResponseBodyItems() {} explicit DescribeSqlPatternResponseBodyItems(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (avgStageCount) { res["AvgStageCount"] = boost::any(*avgStageCount); } if (maxCpuTime) { res["MaxCpuTime"] = boost::any(*maxCpuTime); } if (accessIP) { res["AccessIP"] = boost::any(*accessIP); } if (avgScanSize) { res["AvgScanSize"] = boost::any(*avgScanSize); } if (maxScanSize) { res["MaxScanSize"] = boost::any(*maxScanSize); } if (maxPeakMemory) { res["MaxPeakMemory"] = boost::any(*maxPeakMemory); } if (avgCpuTime) { res["AvgCpuTime"] = boost::any(*avgCpuTime); } if (user) { res["User"] = boost::any(*user); } if (avgPeakMemory) { res["AvgPeakMemory"] = boost::any(*avgPeakMemory); } if (maxStageCount) { res["MaxStageCount"] = boost::any(*maxStageCount); } if (maxTaskCount) { res["MaxTaskCount"] = boost::any(*maxTaskCount); } if (instanceName) { res["InstanceName"] = boost::any(*instanceName); } if (queryCount) { res["QueryCount"] = boost::any(*queryCount); } if (reportDate) { res["ReportDate"] = boost::any(*reportDate); } if (pattern) { res["Pattern"] = boost::any(*pattern); } if (avgTaskCount) { res["AvgTaskCount"] = boost::any(*avgTaskCount); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("AvgStageCount") != m.end() && !m["AvgStageCount"].empty()) { avgStageCount = make_shared<string>(boost::any_cast<string>(m["AvgStageCount"])); } if (m.find("MaxCpuTime") != m.end() && !m["MaxCpuTime"].empty()) { maxCpuTime = make_shared<string>(boost::any_cast<string>(m["MaxCpuTime"])); } if (m.find("AccessIP") != m.end() && !m["AccessIP"].empty()) { accessIP = make_shared<string>(boost::any_cast<string>(m["AccessIP"])); } if (m.find("AvgScanSize") != m.end() && !m["AvgScanSize"].empty()) { avgScanSize = make_shared<string>(boost::any_cast<string>(m["AvgScanSize"])); } if (m.find("MaxScanSize") != m.end() && !m["MaxScanSize"].empty()) { maxScanSize = make_shared<string>(boost::any_cast<string>(m["MaxScanSize"])); } if (m.find("MaxPeakMemory") != m.end() && !m["MaxPeakMemory"].empty()) { maxPeakMemory = make_shared<string>(boost::any_cast<string>(m["MaxPeakMemory"])); } if (m.find("AvgCpuTime") != m.end() && !m["AvgCpuTime"].empty()) { avgCpuTime = make_shared<string>(boost::any_cast<string>(m["AvgCpuTime"])); } if (m.find("User") != m.end() && !m["User"].empty()) { user = make_shared<string>(boost::any_cast<string>(m["User"])); } if (m.find("AvgPeakMemory") != m.end() && !m["AvgPeakMemory"].empty()) { avgPeakMemory = make_shared<string>(boost::any_cast<string>(m["AvgPeakMemory"])); } if (m.find("MaxStageCount") != m.end() && !m["MaxStageCount"].empty()) { maxStageCount = make_shared<string>(boost::any_cast<string>(m["MaxStageCount"])); } if (m.find("MaxTaskCount") != m.end() && !m["MaxTaskCount"].empty()) { maxTaskCount = make_shared<string>(boost::any_cast<string>(m["MaxTaskCount"])); } if (m.find("InstanceName") != m.end() && !m["InstanceName"].empty()) { instanceName = make_shared<string>(boost::any_cast<string>(m["InstanceName"])); } if (m.find("QueryCount") != m.end() && !m["QueryCount"].empty()) { queryCount = make_shared<string>(boost::any_cast<string>(m["QueryCount"])); } if (m.find("ReportDate") != m.end() && !m["ReportDate"].empty()) { reportDate = make_shared<string>(boost::any_cast<string>(m["ReportDate"])); } if (m.find("Pattern") != m.end() && !m["Pattern"].empty()) { pattern = make_shared<string>(boost::any_cast<string>(m["Pattern"])); } if (m.find("AvgTaskCount") != m.end() && !m["AvgTaskCount"].empty()) { avgTaskCount = make_shared<string>(boost::any_cast<string>(m["AvgTaskCount"])); } } virtual ~DescribeSqlPatternResponseBodyItems() = default; }; class DescribeSqlPatternResponseBody : public Darabonba::Model { public: shared_ptr<long> pageSize{}; shared_ptr<long> pageNumber{}; shared_ptr<long> totalCount{}; shared_ptr<vector<DescribeSqlPatternResponseBodyItems>> items{}; shared_ptr<string> requestId{}; DescribeSqlPatternResponseBody() {} explicit DescribeSqlPatternResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } if (totalCount) { res["TotalCount"] = boost::any(*totalCount); } if (items) { vector<boost::any> temp1; for(auto item1:*items){ temp1.push_back(boost::any(item1.toMap())); } res["Items"] = boost::any(temp1); } if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"])); } if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"])); } if (m.find("TotalCount") != m.end() && !m["TotalCount"].empty()) { totalCount = make_shared<long>(boost::any_cast<long>(m["TotalCount"])); } if (m.find("Items") != m.end() && !m["Items"].empty()) { if (typeid(vector<boost::any>) == m["Items"].type()) { vector<DescribeSqlPatternResponseBodyItems> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["Items"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeSqlPatternResponseBodyItems model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } items = make_shared<vector<DescribeSqlPatternResponseBodyItems>>(expect1); } } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~DescribeSqlPatternResponseBody() = default; }; class DescribeSqlPatternResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeSqlPatternResponseBody> body{}; DescribeSqlPatternResponse() {} explicit DescribeSqlPatternResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeSqlPatternResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeSqlPatternResponseBody>(model1); } } } virtual ~DescribeSqlPatternResponse() = default; }; class DescribeSQLPatternAttributeRequest : public Darabonba::Model { public: shared_ptr<string> DBClusterId{}; shared_ptr<string> startTime{}; shared_ptr<string> endTime{}; shared_ptr<string> regionId{}; shared_ptr<long> patternId{}; shared_ptr<string> lang{}; DescribeSQLPatternAttributeRequest() {} explicit DescribeSQLPatternAttributeRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (startTime) { res["StartTime"] = boost::any(*startTime); } if (endTime) { res["EndTime"] = boost::any(*endTime); } if (regionId) { res["RegionId"] = boost::any(*regionId); } if (patternId) { res["PatternId"] = boost::any(*patternId); } if (lang) { res["Lang"] = boost::any(*lang); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("StartTime") != m.end() && !m["StartTime"].empty()) { startTime = make_shared<string>(boost::any_cast<string>(m["StartTime"])); } if (m.find("EndTime") != m.end() && !m["EndTime"].empty()) { endTime = make_shared<string>(boost::any_cast<string>(m["EndTime"])); } if (m.find("RegionId") != m.end() && !m["RegionId"].empty()) { regionId = make_shared<string>(boost::any_cast<string>(m["RegionId"])); } if (m.find("PatternId") != m.end() && !m["PatternId"].empty()) { patternId = make_shared<long>(boost::any_cast<long>(m["PatternId"])); } if (m.find("Lang") != m.end() && !m["Lang"].empty()) { lang = make_shared<string>(boost::any_cast<string>(m["Lang"])); } } virtual ~DescribeSQLPatternAttributeRequest() = default; }; class DescribeSQLPatternAttributeResponseBodyPatternDetail : public Darabonba::Model { public: shared_ptr<string> SQLPattern{}; shared_ptr<long> queryCount{}; shared_ptr<string> totalQueryTime{}; shared_ptr<string> averageQueryTime{}; shared_ptr<string> averageMemory{}; DescribeSQLPatternAttributeResponseBodyPatternDetail() {} explicit DescribeSQLPatternAttributeResponseBodyPatternDetail(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (SQLPattern) { res["SQLPattern"] = boost::any(*SQLPattern); } if (queryCount) { res["QueryCount"] = boost::any(*queryCount); } if (totalQueryTime) { res["TotalQueryTime"] = boost::any(*totalQueryTime); } if (averageQueryTime) { res["AverageQueryTime"] = boost::any(*averageQueryTime); } if (averageMemory) { res["AverageMemory"] = boost::any(*averageMemory); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("SQLPattern") != m.end() && !m["SQLPattern"].empty()) { SQLPattern = make_shared<string>(boost::any_cast<string>(m["SQLPattern"])); } if (m.find("QueryCount") != m.end() && !m["QueryCount"].empty()) { queryCount = make_shared<long>(boost::any_cast<long>(m["QueryCount"])); } if (m.find("TotalQueryTime") != m.end() && !m["TotalQueryTime"].empty()) { totalQueryTime = make_shared<string>(boost::any_cast<string>(m["TotalQueryTime"])); } if (m.find("AverageQueryTime") != m.end() && !m["AverageQueryTime"].empty()) { averageQueryTime = make_shared<string>(boost::any_cast<string>(m["AverageQueryTime"])); } if (m.find("AverageMemory") != m.end() && !m["AverageMemory"].empty()) { averageMemory = make_shared<string>(boost::any_cast<string>(m["AverageMemory"])); } } virtual ~DescribeSQLPatternAttributeResponseBodyPatternDetail() = default; }; class DescribeSQLPatternAttributeResponseBody : public Darabonba::Model { public: shared_ptr<DescribeSQLPatternAttributeResponseBodyPatternDetail> patternDetail{}; shared_ptr<string> requestId{}; DescribeSQLPatternAttributeResponseBody() {} explicit DescribeSQLPatternAttributeResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (patternDetail) { res["PatternDetail"] = patternDetail ? boost::any(patternDetail->toMap()) : boost::any(map<string,boost::any>({})); } if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("PatternDetail") != m.end() && !m["PatternDetail"].empty()) { if (typeid(map<string, boost::any>) == m["PatternDetail"].type()) { DescribeSQLPatternAttributeResponseBodyPatternDetail model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["PatternDetail"])); patternDetail = make_shared<DescribeSQLPatternAttributeResponseBodyPatternDetail>(model1); } } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~DescribeSQLPatternAttributeResponseBody() = default; }; class DescribeSQLPatternAttributeResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeSQLPatternAttributeResponseBody> body{}; DescribeSQLPatternAttributeResponse() {} explicit DescribeSQLPatternAttributeResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeSQLPatternAttributeResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeSQLPatternAttributeResponseBody>(model1); } } } virtual ~DescribeSQLPatternAttributeResponse() = default; }; class DescribeSQLPatternsRequest : public Darabonba::Model { public: shared_ptr<string> DBClusterId{}; shared_ptr<string> startTime{}; shared_ptr<string> endTime{}; shared_ptr<string> regionId{}; shared_ptr<string> keyword{}; shared_ptr<string> order{}; shared_ptr<long> pageNumber{}; shared_ptr<long> pageSize{}; shared_ptr<string> lang{}; DescribeSQLPatternsRequest() {} explicit DescribeSQLPatternsRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (startTime) { res["StartTime"] = boost::any(*startTime); } if (endTime) { res["EndTime"] = boost::any(*endTime); } if (regionId) { res["RegionId"] = boost::any(*regionId); } if (keyword) { res["Keyword"] = boost::any(*keyword); } if (order) { res["Order"] = boost::any(*order); } if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (lang) { res["Lang"] = boost::any(*lang); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("StartTime") != m.end() && !m["StartTime"].empty()) { startTime = make_shared<string>(boost::any_cast<string>(m["StartTime"])); } if (m.find("EndTime") != m.end() && !m["EndTime"].empty()) { endTime = make_shared<string>(boost::any_cast<string>(m["EndTime"])); } if (m.find("RegionId") != m.end() && !m["RegionId"].empty()) { regionId = make_shared<string>(boost::any_cast<string>(m["RegionId"])); } if (m.find("Keyword") != m.end() && !m["Keyword"].empty()) { keyword = make_shared<string>(boost::any_cast<string>(m["Keyword"])); } if (m.find("Order") != m.end() && !m["Order"].empty()) { order = make_shared<string>(boost::any_cast<string>(m["Order"])); } if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"])); } if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"])); } if (m.find("Lang") != m.end() && !m["Lang"].empty()) { lang = make_shared<string>(boost::any_cast<string>(m["Lang"])); } } virtual ~DescribeSQLPatternsRequest() = default; }; class DescribeSQLPatternsResponseBodyPatternDetails : public Darabonba::Model { public: shared_ptr<string> SQLPattern{}; shared_ptr<string> patternId{}; shared_ptr<string> tables{}; shared_ptr<string> patternCreationDate{}; shared_ptr<string> totalQueryTime{}; shared_ptr<string> averageQueryTime{}; shared_ptr<string> queryTimePercentage{}; shared_ptr<string> averageMemory{}; shared_ptr<string> totalScanSize{}; shared_ptr<string> scanSizePercentage{}; shared_ptr<long> queryCount{}; shared_ptr<long> errorCount{}; shared_ptr<bool> blockable{}; DescribeSQLPatternsResponseBodyPatternDetails() {} explicit DescribeSQLPatternsResponseBodyPatternDetails(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (SQLPattern) { res["SQLPattern"] = boost::any(*SQLPattern); } if (patternId) { res["PatternId"] = boost::any(*patternId); } if (tables) { res["Tables"] = boost::any(*tables); } if (patternCreationDate) { res["PatternCreationDate"] = boost::any(*patternCreationDate); } if (totalQueryTime) { res["TotalQueryTime"] = boost::any(*totalQueryTime); } if (averageQueryTime) { res["AverageQueryTime"] = boost::any(*averageQueryTime); } if (queryTimePercentage) { res["QueryTimePercentage"] = boost::any(*queryTimePercentage); } if (averageMemory) { res["AverageMemory"] = boost::any(*averageMemory); } if (totalScanSize) { res["TotalScanSize"] = boost::any(*totalScanSize); } if (scanSizePercentage) { res["ScanSizePercentage"] = boost::any(*scanSizePercentage); } if (queryCount) { res["QueryCount"] = boost::any(*queryCount); } if (errorCount) { res["ErrorCount"] = boost::any(*errorCount); } if (blockable) { res["Blockable"] = boost::any(*blockable); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("SQLPattern") != m.end() && !m["SQLPattern"].empty()) { SQLPattern = make_shared<string>(boost::any_cast<string>(m["SQLPattern"])); } if (m.find("PatternId") != m.end() && !m["PatternId"].empty()) { patternId = make_shared<string>(boost::any_cast<string>(m["PatternId"])); } if (m.find("Tables") != m.end() && !m["Tables"].empty()) { tables = make_shared<string>(boost::any_cast<string>(m["Tables"])); } if (m.find("PatternCreationDate") != m.end() && !m["PatternCreationDate"].empty()) { patternCreationDate = make_shared<string>(boost::any_cast<string>(m["PatternCreationDate"])); } if (m.find("TotalQueryTime") != m.end() && !m["TotalQueryTime"].empty()) { totalQueryTime = make_shared<string>(boost::any_cast<string>(m["TotalQueryTime"])); } if (m.find("AverageQueryTime") != m.end() && !m["AverageQueryTime"].empty()) { averageQueryTime = make_shared<string>(boost::any_cast<string>(m["AverageQueryTime"])); } if (m.find("QueryTimePercentage") != m.end() && !m["QueryTimePercentage"].empty()) { queryTimePercentage = make_shared<string>(boost::any_cast<string>(m["QueryTimePercentage"])); } if (m.find("AverageMemory") != m.end() && !m["AverageMemory"].empty()) { averageMemory = make_shared<string>(boost::any_cast<string>(m["AverageMemory"])); } if (m.find("TotalScanSize") != m.end() && !m["TotalScanSize"].empty()) { totalScanSize = make_shared<string>(boost::any_cast<string>(m["TotalScanSize"])); } if (m.find("ScanSizePercentage") != m.end() && !m["ScanSizePercentage"].empty()) { scanSizePercentage = make_shared<string>(boost::any_cast<string>(m["ScanSizePercentage"])); } if (m.find("QueryCount") != m.end() && !m["QueryCount"].empty()) { queryCount = make_shared<long>(boost::any_cast<long>(m["QueryCount"])); } if (m.find("ErrorCount") != m.end() && !m["ErrorCount"].empty()) { errorCount = make_shared<long>(boost::any_cast<long>(m["ErrorCount"])); } if (m.find("Blockable") != m.end() && !m["Blockable"].empty()) { blockable = make_shared<bool>(boost::any_cast<bool>(m["Blockable"])); } } virtual ~DescribeSQLPatternsResponseBodyPatternDetails() = default; }; class DescribeSQLPatternsResponseBody : public Darabonba::Model { public: shared_ptr<long> pageNumber{}; shared_ptr<long> pageSize{}; shared_ptr<long> totalCount{}; shared_ptr<vector<DescribeSQLPatternsResponseBodyPatternDetails>> patternDetails{}; shared_ptr<string> requestId{}; DescribeSQLPatternsResponseBody() {} explicit DescribeSQLPatternsResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (totalCount) { res["TotalCount"] = boost::any(*totalCount); } if (patternDetails) { vector<boost::any> temp1; for(auto item1:*patternDetails){ temp1.push_back(boost::any(item1.toMap())); } res["PatternDetails"] = boost::any(temp1); } if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"])); } if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"])); } if (m.find("TotalCount") != m.end() && !m["TotalCount"].empty()) { totalCount = make_shared<long>(boost::any_cast<long>(m["TotalCount"])); } if (m.find("PatternDetails") != m.end() && !m["PatternDetails"].empty()) { if (typeid(vector<boost::any>) == m["PatternDetails"].type()) { vector<DescribeSQLPatternsResponseBodyPatternDetails> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["PatternDetails"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeSQLPatternsResponseBodyPatternDetails model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } patternDetails = make_shared<vector<DescribeSQLPatternsResponseBodyPatternDetails>>(expect1); } } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~DescribeSQLPatternsResponseBody() = default; }; class DescribeSQLPatternsResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeSQLPatternsResponseBody> body{}; DescribeSQLPatternsResponse() {} explicit DescribeSQLPatternsResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeSQLPatternsResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeSQLPatternsResponseBody>(model1); } } } virtual ~DescribeSQLPatternsResponse() = default; }; class DescribeSQLPlanRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> processId{}; DescribeSQLPlanRequest() {} explicit DescribeSQLPlanRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (processId) { res["ProcessId"] = boost::any(*processId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("ProcessId") != m.end() && !m["ProcessId"].empty()) { processId = make_shared<string>(boost::any_cast<string>(m["ProcessId"])); } } virtual ~DescribeSQLPlanRequest() = default; }; class DescribeSQLPlanResponseBodyDetail : public Darabonba::Model { public: shared_ptr<string> SQL{}; shared_ptr<long> outputSize{}; shared_ptr<string> state{}; shared_ptr<long> outputRows{}; shared_ptr<string> user{}; shared_ptr<string> startTime{}; shared_ptr<long> totalStage{}; shared_ptr<long> totalTime{}; shared_ptr<long> queuedTime{}; shared_ptr<string> database{}; shared_ptr<long> totalTask{}; shared_ptr<long> peakMemory{}; shared_ptr<string> clientIP{}; shared_ptr<long> planningTime{}; shared_ptr<long> CPUTime{}; DescribeSQLPlanResponseBodyDetail() {} explicit DescribeSQLPlanResponseBodyDetail(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (SQL) { res["SQL"] = boost::any(*SQL); } if (outputSize) { res["OutputSize"] = boost::any(*outputSize); } if (state) { res["State"] = boost::any(*state); } if (outputRows) { res["OutputRows"] = boost::any(*outputRows); } if (user) { res["User"] = boost::any(*user); } if (startTime) { res["StartTime"] = boost::any(*startTime); } if (totalStage) { res["TotalStage"] = boost::any(*totalStage); } if (totalTime) { res["TotalTime"] = boost::any(*totalTime); } if (queuedTime) { res["QueuedTime"] = boost::any(*queuedTime); } if (database) { res["Database"] = boost::any(*database); } if (totalTask) { res["TotalTask"] = boost::any(*totalTask); } if (peakMemory) { res["PeakMemory"] = boost::any(*peakMemory); } if (clientIP) { res["ClientIP"] = boost::any(*clientIP); } if (planningTime) { res["PlanningTime"] = boost::any(*planningTime); } if (CPUTime) { res["CPUTime"] = boost::any(*CPUTime); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("SQL") != m.end() && !m["SQL"].empty()) { SQL = make_shared<string>(boost::any_cast<string>(m["SQL"])); } if (m.find("OutputSize") != m.end() && !m["OutputSize"].empty()) { outputSize = make_shared<long>(boost::any_cast<long>(m["OutputSize"])); } if (m.find("State") != m.end() && !m["State"].empty()) { state = make_shared<string>(boost::any_cast<string>(m["State"])); } if (m.find("OutputRows") != m.end() && !m["OutputRows"].empty()) { outputRows = make_shared<long>(boost::any_cast<long>(m["OutputRows"])); } if (m.find("User") != m.end() && !m["User"].empty()) { user = make_shared<string>(boost::any_cast<string>(m["User"])); } if (m.find("StartTime") != m.end() && !m["StartTime"].empty()) { startTime = make_shared<string>(boost::any_cast<string>(m["StartTime"])); } if (m.find("TotalStage") != m.end() && !m["TotalStage"].empty()) { totalStage = make_shared<long>(boost::any_cast<long>(m["TotalStage"])); } if (m.find("TotalTime") != m.end() && !m["TotalTime"].empty()) { totalTime = make_shared<long>(boost::any_cast<long>(m["TotalTime"])); } if (m.find("QueuedTime") != m.end() && !m["QueuedTime"].empty()) { queuedTime = make_shared<long>(boost::any_cast<long>(m["QueuedTime"])); } if (m.find("Database") != m.end() && !m["Database"].empty()) { database = make_shared<string>(boost::any_cast<string>(m["Database"])); } if (m.find("TotalTask") != m.end() && !m["TotalTask"].empty()) { totalTask = make_shared<long>(boost::any_cast<long>(m["TotalTask"])); } if (m.find("PeakMemory") != m.end() && !m["PeakMemory"].empty()) { peakMemory = make_shared<long>(boost::any_cast<long>(m["PeakMemory"])); } if (m.find("ClientIP") != m.end() && !m["ClientIP"].empty()) { clientIP = make_shared<string>(boost::any_cast<string>(m["ClientIP"])); } if (m.find("PlanningTime") != m.end() && !m["PlanningTime"].empty()) { planningTime = make_shared<long>(boost::any_cast<long>(m["PlanningTime"])); } if (m.find("CPUTime") != m.end() && !m["CPUTime"].empty()) { CPUTime = make_shared<long>(boost::any_cast<long>(m["CPUTime"])); } } virtual ~DescribeSQLPlanResponseBodyDetail() = default; }; class DescribeSQLPlanResponseBodyStageList : public Darabonba::Model { public: shared_ptr<string> state{}; shared_ptr<long> CPUTimeMax{}; shared_ptr<long> CPUTimeAvg{}; shared_ptr<long> operatorCost{}; shared_ptr<long> scanTimeMax{}; shared_ptr<long> stageId{}; shared_ptr<long> inputSizeMax{}; shared_ptr<long> scanSizeMax{}; shared_ptr<long> CPUTimeMin{}; shared_ptr<long> scanTimeMin{}; shared_ptr<long> scanSizeMin{}; shared_ptr<long> inputSizeMin{}; shared_ptr<long> peakMemory{}; shared_ptr<long> scanTimeAvg{}; shared_ptr<long> scanSizeAvg{}; shared_ptr<long> inputSizeAvg{}; DescribeSQLPlanResponseBodyStageList() {} explicit DescribeSQLPlanResponseBodyStageList(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (state) { res["State"] = boost::any(*state); } if (CPUTimeMax) { res["CPUTimeMax"] = boost::any(*CPUTimeMax); } if (CPUTimeAvg) { res["CPUTimeAvg"] = boost::any(*CPUTimeAvg); } if (operatorCost) { res["OperatorCost"] = boost::any(*operatorCost); } if (scanTimeMax) { res["ScanTimeMax"] = boost::any(*scanTimeMax); } if (stageId) { res["StageId"] = boost::any(*stageId); } if (inputSizeMax) { res["InputSizeMax"] = boost::any(*inputSizeMax); } if (scanSizeMax) { res["ScanSizeMax"] = boost::any(*scanSizeMax); } if (CPUTimeMin) { res["CPUTimeMin"] = boost::any(*CPUTimeMin); } if (scanTimeMin) { res["ScanTimeMin"] = boost::any(*scanTimeMin); } if (scanSizeMin) { res["ScanSizeMin"] = boost::any(*scanSizeMin); } if (inputSizeMin) { res["InputSizeMin"] = boost::any(*inputSizeMin); } if (peakMemory) { res["PeakMemory"] = boost::any(*peakMemory); } if (scanTimeAvg) { res["ScanTimeAvg"] = boost::any(*scanTimeAvg); } if (scanSizeAvg) { res["ScanSizeAvg"] = boost::any(*scanSizeAvg); } if (inputSizeAvg) { res["InputSizeAvg"] = boost::any(*inputSizeAvg); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("State") != m.end() && !m["State"].empty()) { state = make_shared<string>(boost::any_cast<string>(m["State"])); } if (m.find("CPUTimeMax") != m.end() && !m["CPUTimeMax"].empty()) { CPUTimeMax = make_shared<long>(boost::any_cast<long>(m["CPUTimeMax"])); } if (m.find("CPUTimeAvg") != m.end() && !m["CPUTimeAvg"].empty()) { CPUTimeAvg = make_shared<long>(boost::any_cast<long>(m["CPUTimeAvg"])); } if (m.find("OperatorCost") != m.end() && !m["OperatorCost"].empty()) { operatorCost = make_shared<long>(boost::any_cast<long>(m["OperatorCost"])); } if (m.find("ScanTimeMax") != m.end() && !m["ScanTimeMax"].empty()) { scanTimeMax = make_shared<long>(boost::any_cast<long>(m["ScanTimeMax"])); } if (m.find("StageId") != m.end() && !m["StageId"].empty()) { stageId = make_shared<long>(boost::any_cast<long>(m["StageId"])); } if (m.find("InputSizeMax") != m.end() && !m["InputSizeMax"].empty()) { inputSizeMax = make_shared<long>(boost::any_cast<long>(m["InputSizeMax"])); } if (m.find("ScanSizeMax") != m.end() && !m["ScanSizeMax"].empty()) { scanSizeMax = make_shared<long>(boost::any_cast<long>(m["ScanSizeMax"])); } if (m.find("CPUTimeMin") != m.end() && !m["CPUTimeMin"].empty()) { CPUTimeMin = make_shared<long>(boost::any_cast<long>(m["CPUTimeMin"])); } if (m.find("ScanTimeMin") != m.end() && !m["ScanTimeMin"].empty()) { scanTimeMin = make_shared<long>(boost::any_cast<long>(m["ScanTimeMin"])); } if (m.find("ScanSizeMin") != m.end() && !m["ScanSizeMin"].empty()) { scanSizeMin = make_shared<long>(boost::any_cast<long>(m["ScanSizeMin"])); } if (m.find("InputSizeMin") != m.end() && !m["InputSizeMin"].empty()) { inputSizeMin = make_shared<long>(boost::any_cast<long>(m["InputSizeMin"])); } if (m.find("PeakMemory") != m.end() && !m["PeakMemory"].empty()) { peakMemory = make_shared<long>(boost::any_cast<long>(m["PeakMemory"])); } if (m.find("ScanTimeAvg") != m.end() && !m["ScanTimeAvg"].empty()) { scanTimeAvg = make_shared<long>(boost::any_cast<long>(m["ScanTimeAvg"])); } if (m.find("ScanSizeAvg") != m.end() && !m["ScanSizeAvg"].empty()) { scanSizeAvg = make_shared<long>(boost::any_cast<long>(m["ScanSizeAvg"])); } if (m.find("InputSizeAvg") != m.end() && !m["InputSizeAvg"].empty()) { inputSizeAvg = make_shared<long>(boost::any_cast<long>(m["InputSizeAvg"])); } } virtual ~DescribeSQLPlanResponseBodyStageList() = default; }; class DescribeSQLPlanResponseBody : public Darabonba::Model { public: shared_ptr<string> originInfo{}; shared_ptr<string> requestId{}; shared_ptr<DescribeSQLPlanResponseBodyDetail> detail{}; shared_ptr<vector<DescribeSQLPlanResponseBodyStageList>> stageList{}; DescribeSQLPlanResponseBody() {} explicit DescribeSQLPlanResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (originInfo) { res["OriginInfo"] = boost::any(*originInfo); } if (requestId) { res["RequestId"] = boost::any(*requestId); } if (detail) { res["Detail"] = detail ? boost::any(detail->toMap()) : boost::any(map<string,boost::any>({})); } if (stageList) { vector<boost::any> temp1; for(auto item1:*stageList){ temp1.push_back(boost::any(item1.toMap())); } res["StageList"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OriginInfo") != m.end() && !m["OriginInfo"].empty()) { originInfo = make_shared<string>(boost::any_cast<string>(m["OriginInfo"])); } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("Detail") != m.end() && !m["Detail"].empty()) { if (typeid(map<string, boost::any>) == m["Detail"].type()) { DescribeSQLPlanResponseBodyDetail model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Detail"])); detail = make_shared<DescribeSQLPlanResponseBodyDetail>(model1); } } if (m.find("StageList") != m.end() && !m["StageList"].empty()) { if (typeid(vector<boost::any>) == m["StageList"].type()) { vector<DescribeSQLPlanResponseBodyStageList> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["StageList"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeSQLPlanResponseBodyStageList model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } stageList = make_shared<vector<DescribeSQLPlanResponseBodyStageList>>(expect1); } } } virtual ~DescribeSQLPlanResponseBody() = default; }; class DescribeSQLPlanResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeSQLPlanResponseBody> body{}; DescribeSQLPlanResponse() {} explicit DescribeSQLPlanResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeSQLPlanResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeSQLPlanResponseBody>(model1); } } } virtual ~DescribeSQLPlanResponse() = default; }; class DescribeSQLPlanTaskRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> processId{}; shared_ptr<string> stageId{}; DescribeSQLPlanTaskRequest() {} explicit DescribeSQLPlanTaskRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (processId) { res["ProcessId"] = boost::any(*processId); } if (stageId) { res["StageId"] = boost::any(*stageId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("ProcessId") != m.end() && !m["ProcessId"].empty()) { processId = make_shared<string>(boost::any_cast<string>(m["ProcessId"])); } if (m.find("StageId") != m.end() && !m["StageId"].empty()) { stageId = make_shared<string>(boost::any_cast<string>(m["StageId"])); } } virtual ~DescribeSQLPlanTaskRequest() = default; }; class DescribeSQLPlanTaskResponseBodyTaskList : public Darabonba::Model { public: shared_ptr<long> outputSize{}; shared_ptr<long> scanCost{}; shared_ptr<long> inputSize{}; shared_ptr<string> state{}; shared_ptr<long> operatorCost{}; shared_ptr<long> outputRows{}; shared_ptr<long> scanSize{}; shared_ptr<long> elapsedTime{}; shared_ptr<long> scanRows{}; shared_ptr<long> peakMemory{}; shared_ptr<long> taskId{}; shared_ptr<long> inputRows{}; DescribeSQLPlanTaskResponseBodyTaskList() {} explicit DescribeSQLPlanTaskResponseBodyTaskList(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (outputSize) { res["OutputSize"] = boost::any(*outputSize); } if (scanCost) { res["ScanCost"] = boost::any(*scanCost); } if (inputSize) { res["InputSize"] = boost::any(*inputSize); } if (state) { res["State"] = boost::any(*state); } if (operatorCost) { res["OperatorCost"] = boost::any(*operatorCost); } if (outputRows) { res["OutputRows"] = boost::any(*outputRows); } if (scanSize) { res["ScanSize"] = boost::any(*scanSize); } if (elapsedTime) { res["ElapsedTime"] = boost::any(*elapsedTime); } if (scanRows) { res["ScanRows"] = boost::any(*scanRows); } if (peakMemory) { res["PeakMemory"] = boost::any(*peakMemory); } if (taskId) { res["TaskId"] = boost::any(*taskId); } if (inputRows) { res["InputRows"] = boost::any(*inputRows); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OutputSize") != m.end() && !m["OutputSize"].empty()) { outputSize = make_shared<long>(boost::any_cast<long>(m["OutputSize"])); } if (m.find("ScanCost") != m.end() && !m["ScanCost"].empty()) { scanCost = make_shared<long>(boost::any_cast<long>(m["ScanCost"])); } if (m.find("InputSize") != m.end() && !m["InputSize"].empty()) { inputSize = make_shared<long>(boost::any_cast<long>(m["InputSize"])); } if (m.find("State") != m.end() && !m["State"].empty()) { state = make_shared<string>(boost::any_cast<string>(m["State"])); } if (m.find("OperatorCost") != m.end() && !m["OperatorCost"].empty()) { operatorCost = make_shared<long>(boost::any_cast<long>(m["OperatorCost"])); } if (m.find("OutputRows") != m.end() && !m["OutputRows"].empty()) { outputRows = make_shared<long>(boost::any_cast<long>(m["OutputRows"])); } if (m.find("ScanSize") != m.end() && !m["ScanSize"].empty()) { scanSize = make_shared<long>(boost::any_cast<long>(m["ScanSize"])); } if (m.find("ElapsedTime") != m.end() && !m["ElapsedTime"].empty()) { elapsedTime = make_shared<long>(boost::any_cast<long>(m["ElapsedTime"])); } if (m.find("ScanRows") != m.end() && !m["ScanRows"].empty()) { scanRows = make_shared<long>(boost::any_cast<long>(m["ScanRows"])); } if (m.find("PeakMemory") != m.end() && !m["PeakMemory"].empty()) { peakMemory = make_shared<long>(boost::any_cast<long>(m["PeakMemory"])); } if (m.find("TaskId") != m.end() && !m["TaskId"].empty()) { taskId = make_shared<long>(boost::any_cast<long>(m["TaskId"])); } if (m.find("InputRows") != m.end() && !m["InputRows"].empty()) { inputRows = make_shared<long>(boost::any_cast<long>(m["InputRows"])); } } virtual ~DescribeSQLPlanTaskResponseBodyTaskList() = default; }; class DescribeSQLPlanTaskResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; shared_ptr<vector<DescribeSQLPlanTaskResponseBodyTaskList>> taskList{}; DescribeSQLPlanTaskResponseBody() {} explicit DescribeSQLPlanTaskResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } if (taskList) { vector<boost::any> temp1; for(auto item1:*taskList){ temp1.push_back(boost::any(item1.toMap())); } res["TaskList"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("TaskList") != m.end() && !m["TaskList"].empty()) { if (typeid(vector<boost::any>) == m["TaskList"].type()) { vector<DescribeSQLPlanTaskResponseBodyTaskList> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["TaskList"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeSQLPlanTaskResponseBodyTaskList model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } taskList = make_shared<vector<DescribeSQLPlanTaskResponseBodyTaskList>>(expect1); } } } virtual ~DescribeSQLPlanTaskResponseBody() = default; }; class DescribeSQLPlanTaskResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeSQLPlanTaskResponseBody> body{}; DescribeSQLPlanTaskResponse() {} explicit DescribeSQLPlanTaskResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeSQLPlanTaskResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeSQLPlanTaskResponseBody>(model1); } } } virtual ~DescribeSQLPlanTaskResponse() = default; }; class DescribeTableAccessCountRequest : public Darabonba::Model { public: shared_ptr<string> DBClusterId{}; shared_ptr<string> tableName{}; shared_ptr<string> startTime{}; shared_ptr<string> order{}; shared_ptr<long> pageNumber{}; shared_ptr<long> pageSize{}; shared_ptr<string> regionId{}; DescribeTableAccessCountRequest() {} explicit DescribeTableAccessCountRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (tableName) { res["TableName"] = boost::any(*tableName); } if (startTime) { res["StartTime"] = boost::any(*startTime); } if (order) { res["Order"] = boost::any(*order); } if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (regionId) { res["RegionId"] = boost::any(*regionId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("TableName") != m.end() && !m["TableName"].empty()) { tableName = make_shared<string>(boost::any_cast<string>(m["TableName"])); } if (m.find("StartTime") != m.end() && !m["StartTime"].empty()) { startTime = make_shared<string>(boost::any_cast<string>(m["StartTime"])); } if (m.find("Order") != m.end() && !m["Order"].empty()) { order = make_shared<string>(boost::any_cast<string>(m["Order"])); } if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"])); } if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"])); } if (m.find("RegionId") != m.end() && !m["RegionId"].empty()) { regionId = make_shared<string>(boost::any_cast<string>(m["RegionId"])); } } virtual ~DescribeTableAccessCountRequest() = default; }; class DescribeTableAccessCountResponseBodyItems : public Darabonba::Model { public: shared_ptr<string> reportDate{}; shared_ptr<string> tableSchema{}; shared_ptr<string> accessCount{}; shared_ptr<string> tableName{}; shared_ptr<string> instanceName{}; DescribeTableAccessCountResponseBodyItems() {} explicit DescribeTableAccessCountResponseBodyItems(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (reportDate) { res["ReportDate"] = boost::any(*reportDate); } if (tableSchema) { res["TableSchema"] = boost::any(*tableSchema); } if (accessCount) { res["AccessCount"] = boost::any(*accessCount); } if (tableName) { res["TableName"] = boost::any(*tableName); } if (instanceName) { res["InstanceName"] = boost::any(*instanceName); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("ReportDate") != m.end() && !m["ReportDate"].empty()) { reportDate = make_shared<string>(boost::any_cast<string>(m["ReportDate"])); } if (m.find("TableSchema") != m.end() && !m["TableSchema"].empty()) { tableSchema = make_shared<string>(boost::any_cast<string>(m["TableSchema"])); } if (m.find("AccessCount") != m.end() && !m["AccessCount"].empty()) { accessCount = make_shared<string>(boost::any_cast<string>(m["AccessCount"])); } if (m.find("TableName") != m.end() && !m["TableName"].empty()) { tableName = make_shared<string>(boost::any_cast<string>(m["TableName"])); } if (m.find("InstanceName") != m.end() && !m["InstanceName"].empty()) { instanceName = make_shared<string>(boost::any_cast<string>(m["InstanceName"])); } } virtual ~DescribeTableAccessCountResponseBodyItems() = default; }; class DescribeTableAccessCountResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; shared_ptr<long> pageNumber{}; shared_ptr<long> pageSize{}; shared_ptr<long> totalCount{}; shared_ptr<vector<DescribeTableAccessCountResponseBodyItems>> items{}; DescribeTableAccessCountResponseBody() {} explicit DescribeTableAccessCountResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (totalCount) { res["TotalCount"] = boost::any(*totalCount); } if (items) { vector<boost::any> temp1; for(auto item1:*items){ temp1.push_back(boost::any(item1.toMap())); } res["Items"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"])); } if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"])); } if (m.find("TotalCount") != m.end() && !m["TotalCount"].empty()) { totalCount = make_shared<long>(boost::any_cast<long>(m["TotalCount"])); } if (m.find("Items") != m.end() && !m["Items"].empty()) { if (typeid(vector<boost::any>) == m["Items"].type()) { vector<DescribeTableAccessCountResponseBodyItems> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["Items"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeTableAccessCountResponseBodyItems model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } items = make_shared<vector<DescribeTableAccessCountResponseBodyItems>>(expect1); } } } virtual ~DescribeTableAccessCountResponseBody() = default; }; class DescribeTableAccessCountResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeTableAccessCountResponseBody> body{}; DescribeTableAccessCountResponse() {} explicit DescribeTableAccessCountResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeTableAccessCountResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeTableAccessCountResponseBody>(model1); } } } virtual ~DescribeTableAccessCountResponse() = default; }; class DescribeTableDetailRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> schemaName{}; shared_ptr<string> tableName{}; DescribeTableDetailRequest() {} explicit DescribeTableDetailRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (schemaName) { res["SchemaName"] = boost::any(*schemaName); } if (tableName) { res["TableName"] = boost::any(*tableName); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("SchemaName") != m.end() && !m["SchemaName"].empty()) { schemaName = make_shared<string>(boost::any_cast<string>(m["SchemaName"])); } if (m.find("TableName") != m.end() && !m["TableName"].empty()) { tableName = make_shared<string>(boost::any_cast<string>(m["TableName"])); } } virtual ~DescribeTableDetailRequest() = default; }; class DescribeTableDetailResponseBodyItemsShard : public Darabonba::Model { public: shared_ptr<long> size{}; shared_ptr<long> id{}; DescribeTableDetailResponseBodyItemsShard() {} explicit DescribeTableDetailResponseBodyItemsShard(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (size) { res["Size"] = boost::any(*size); } if (id) { res["Id"] = boost::any(*id); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Size") != m.end() && !m["Size"].empty()) { size = make_shared<long>(boost::any_cast<long>(m["Size"])); } if (m.find("Id") != m.end() && !m["Id"].empty()) { id = make_shared<long>(boost::any_cast<long>(m["Id"])); } } virtual ~DescribeTableDetailResponseBodyItemsShard() = default; }; class DescribeTableDetailResponseBodyItems : public Darabonba::Model { public: shared_ptr<vector<DescribeTableDetailResponseBodyItemsShard>> shard{}; DescribeTableDetailResponseBodyItems() {} explicit DescribeTableDetailResponseBodyItems(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (shard) { vector<boost::any> temp1; for(auto item1:*shard){ temp1.push_back(boost::any(item1.toMap())); } res["Shard"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Shard") != m.end() && !m["Shard"].empty()) { if (typeid(vector<boost::any>) == m["Shard"].type()) { vector<DescribeTableDetailResponseBodyItemsShard> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["Shard"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeTableDetailResponseBodyItemsShard model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } shard = make_shared<vector<DescribeTableDetailResponseBodyItemsShard>>(expect1); } } } virtual ~DescribeTableDetailResponseBodyItems() = default; }; class DescribeTableDetailResponseBody : public Darabonba::Model { public: shared_ptr<long> avgSize{}; shared_ptr<string> requestId{}; shared_ptr<DescribeTableDetailResponseBodyItems> items{}; DescribeTableDetailResponseBody() {} explicit DescribeTableDetailResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (avgSize) { res["AvgSize"] = boost::any(*avgSize); } if (requestId) { res["RequestId"] = boost::any(*requestId); } if (items) { res["Items"] = items ? boost::any(items->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("AvgSize") != m.end() && !m["AvgSize"].empty()) { avgSize = make_shared<long>(boost::any_cast<long>(m["AvgSize"])); } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("Items") != m.end() && !m["Items"].empty()) { if (typeid(map<string, boost::any>) == m["Items"].type()) { DescribeTableDetailResponseBodyItems model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Items"])); items = make_shared<DescribeTableDetailResponseBodyItems>(model1); } } } virtual ~DescribeTableDetailResponseBody() = default; }; class DescribeTableDetailResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeTableDetailResponseBody> body{}; DescribeTableDetailResponse() {} explicit DescribeTableDetailResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeTableDetailResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeTableDetailResponseBody>(model1); } } } virtual ~DescribeTableDetailResponse() = default; }; class DescribeTablePartitionDiagnoseRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> regionId{}; shared_ptr<string> DBClusterId{}; shared_ptr<long> pageSize{}; shared_ptr<long> pageNumber{}; DescribeTablePartitionDiagnoseRequest() {} explicit DescribeTablePartitionDiagnoseRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (regionId) { res["RegionId"] = boost::any(*regionId); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("RegionId") != m.end() && !m["RegionId"].empty()) { regionId = make_shared<string>(boost::any_cast<string>(m["RegionId"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"])); } if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"])); } } virtual ~DescribeTablePartitionDiagnoseRequest() = default; }; class DescribeTablePartitionDiagnoseResponseBodyItems : public Darabonba::Model { public: shared_ptr<string> tableName{}; shared_ptr<string> partitionDetail{}; shared_ptr<string> schemaName{}; shared_ptr<long> partitionNumber{}; DescribeTablePartitionDiagnoseResponseBodyItems() {} explicit DescribeTablePartitionDiagnoseResponseBodyItems(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (tableName) { res["TableName"] = boost::any(*tableName); } if (partitionDetail) { res["PartitionDetail"] = boost::any(*partitionDetail); } if (schemaName) { res["SchemaName"] = boost::any(*schemaName); } if (partitionNumber) { res["PartitionNumber"] = boost::any(*partitionNumber); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("TableName") != m.end() && !m["TableName"].empty()) { tableName = make_shared<string>(boost::any_cast<string>(m["TableName"])); } if (m.find("PartitionDetail") != m.end() && !m["PartitionDetail"].empty()) { partitionDetail = make_shared<string>(boost::any_cast<string>(m["PartitionDetail"])); } if (m.find("SchemaName") != m.end() && !m["SchemaName"].empty()) { schemaName = make_shared<string>(boost::any_cast<string>(m["SchemaName"])); } if (m.find("PartitionNumber") != m.end() && !m["PartitionNumber"].empty()) { partitionNumber = make_shared<long>(boost::any_cast<long>(m["PartitionNumber"])); } } virtual ~DescribeTablePartitionDiagnoseResponseBodyItems() = default; }; class DescribeTablePartitionDiagnoseResponseBody : public Darabonba::Model { public: shared_ptr<long> totalCount{}; shared_ptr<string> requestId{}; shared_ptr<long> pageSize{}; shared_ptr<long> pageNumber{}; shared_ptr<string> DBClusterId{}; shared_ptr<long> suggestMaxRecordsPerPartition{}; shared_ptr<long> suggestMinRecordsPerPartition{}; shared_ptr<vector<DescribeTablePartitionDiagnoseResponseBodyItems>> items{}; DescribeTablePartitionDiagnoseResponseBody() {} explicit DescribeTablePartitionDiagnoseResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (totalCount) { res["TotalCount"] = boost::any(*totalCount); } if (requestId) { res["RequestId"] = boost::any(*requestId); } if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (suggestMaxRecordsPerPartition) { res["SuggestMaxRecordsPerPartition"] = boost::any(*suggestMaxRecordsPerPartition); } if (suggestMinRecordsPerPartition) { res["SuggestMinRecordsPerPartition"] = boost::any(*suggestMinRecordsPerPartition); } if (items) { vector<boost::any> temp1; for(auto item1:*items){ temp1.push_back(boost::any(item1.toMap())); } res["Items"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("TotalCount") != m.end() && !m["TotalCount"].empty()) { totalCount = make_shared<long>(boost::any_cast<long>(m["TotalCount"])); } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"])); } if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("SuggestMaxRecordsPerPartition") != m.end() && !m["SuggestMaxRecordsPerPartition"].empty()) { suggestMaxRecordsPerPartition = make_shared<long>(boost::any_cast<long>(m["SuggestMaxRecordsPerPartition"])); } if (m.find("SuggestMinRecordsPerPartition") != m.end() && !m["SuggestMinRecordsPerPartition"].empty()) { suggestMinRecordsPerPartition = make_shared<long>(boost::any_cast<long>(m["SuggestMinRecordsPerPartition"])); } if (m.find("Items") != m.end() && !m["Items"].empty()) { if (typeid(vector<boost::any>) == m["Items"].type()) { vector<DescribeTablePartitionDiagnoseResponseBodyItems> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["Items"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeTablePartitionDiagnoseResponseBodyItems model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } items = make_shared<vector<DescribeTablePartitionDiagnoseResponseBodyItems>>(expect1); } } } virtual ~DescribeTablePartitionDiagnoseResponseBody() = default; }; class DescribeTablePartitionDiagnoseResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeTablePartitionDiagnoseResponseBody> body{}; DescribeTablePartitionDiagnoseResponse() {} explicit DescribeTablePartitionDiagnoseResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeTablePartitionDiagnoseResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeTablePartitionDiagnoseResponseBody>(model1); } } } virtual ~DescribeTablePartitionDiagnoseResponse() = default; }; class DescribeTablesRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> schemaName{}; DescribeTablesRequest() {} explicit DescribeTablesRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (schemaName) { res["SchemaName"] = boost::any(*schemaName); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("SchemaName") != m.end() && !m["SchemaName"].empty()) { schemaName = make_shared<string>(boost::any_cast<string>(m["SchemaName"])); } } virtual ~DescribeTablesRequest() = default; }; class DescribeTablesResponseBodyItemsTable : public Darabonba::Model { public: shared_ptr<string> schemaName{}; shared_ptr<string> tableName{}; shared_ptr<string> DBClusterId{}; DescribeTablesResponseBodyItemsTable() {} explicit DescribeTablesResponseBodyItemsTable(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (schemaName) { res["SchemaName"] = boost::any(*schemaName); } if (tableName) { res["TableName"] = boost::any(*tableName); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("SchemaName") != m.end() && !m["SchemaName"].empty()) { schemaName = make_shared<string>(boost::any_cast<string>(m["SchemaName"])); } if (m.find("TableName") != m.end() && !m["TableName"].empty()) { tableName = make_shared<string>(boost::any_cast<string>(m["TableName"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } } virtual ~DescribeTablesResponseBodyItemsTable() = default; }; class DescribeTablesResponseBodyItems : public Darabonba::Model { public: shared_ptr<vector<DescribeTablesResponseBodyItemsTable>> table{}; DescribeTablesResponseBodyItems() {} explicit DescribeTablesResponseBodyItems(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (table) { vector<boost::any> temp1; for(auto item1:*table){ temp1.push_back(boost::any(item1.toMap())); } res["Table"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Table") != m.end() && !m["Table"].empty()) { if (typeid(vector<boost::any>) == m["Table"].type()) { vector<DescribeTablesResponseBodyItemsTable> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["Table"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeTablesResponseBodyItemsTable model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } table = make_shared<vector<DescribeTablesResponseBodyItemsTable>>(expect1); } } } virtual ~DescribeTablesResponseBodyItems() = default; }; class DescribeTablesResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; shared_ptr<DescribeTablesResponseBodyItems> items{}; DescribeTablesResponseBody() {} explicit DescribeTablesResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } if (items) { res["Items"] = items ? boost::any(items->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("Items") != m.end() && !m["Items"].empty()) { if (typeid(map<string, boost::any>) == m["Items"].type()) { DescribeTablesResponseBodyItems model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Items"])); items = make_shared<DescribeTablesResponseBodyItems>(model1); } } } virtual ~DescribeTablesResponseBody() = default; }; class DescribeTablesResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeTablesResponseBody> body{}; DescribeTablesResponse() {} explicit DescribeTablesResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeTablesResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeTablesResponseBody>(model1); } } } virtual ~DescribeTablesResponse() = default; }; class DescribeTableStatisticsRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<long> pageSize{}; shared_ptr<long> pageNumber{}; shared_ptr<string> order{}; DescribeTableStatisticsRequest() {} explicit DescribeTableStatisticsRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } if (order) { res["Order"] = boost::any(*order); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<long>(boost::any_cast<long>(m["PageSize"])); } if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<long>(boost::any_cast<long>(m["PageNumber"])); } if (m.find("Order") != m.end() && !m["Order"].empty()) { order = make_shared<string>(boost::any_cast<string>(m["Order"])); } } virtual ~DescribeTableStatisticsRequest() = default; }; class DescribeTableStatisticsResponseBodyItemsTableStatisticRecords : public Darabonba::Model { public: shared_ptr<string> schemaName{}; shared_ptr<string> tableName{}; shared_ptr<long> rowCount{}; shared_ptr<long> dataSize{}; shared_ptr<long> indexSize{}; shared_ptr<long> primaryKeyIndexSize{}; shared_ptr<long> partitionCount{}; shared_ptr<long> coldDataSize{}; DescribeTableStatisticsResponseBodyItemsTableStatisticRecords() {} explicit DescribeTableStatisticsResponseBodyItemsTableStatisticRecords(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (schemaName) { res["SchemaName"] = boost::any(*schemaName); } if (tableName) { res["TableName"] = boost::any(*tableName); } if (rowCount) { res["RowCount"] = boost::any(*rowCount); } if (dataSize) { res["DataSize"] = boost::any(*dataSize); } if (indexSize) { res["IndexSize"] = boost::any(*indexSize); } if (primaryKeyIndexSize) { res["PrimaryKeyIndexSize"] = boost::any(*primaryKeyIndexSize); } if (partitionCount) { res["PartitionCount"] = boost::any(*partitionCount); } if (coldDataSize) { res["ColdDataSize"] = boost::any(*coldDataSize); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("SchemaName") != m.end() && !m["SchemaName"].empty()) { schemaName = make_shared<string>(boost::any_cast<string>(m["SchemaName"])); } if (m.find("TableName") != m.end() && !m["TableName"].empty()) { tableName = make_shared<string>(boost::any_cast<string>(m["TableName"])); } if (m.find("RowCount") != m.end() && !m["RowCount"].empty()) { rowCount = make_shared<long>(boost::any_cast<long>(m["RowCount"])); } if (m.find("DataSize") != m.end() && !m["DataSize"].empty()) { dataSize = make_shared<long>(boost::any_cast<long>(m["DataSize"])); } if (m.find("IndexSize") != m.end() && !m["IndexSize"].empty()) { indexSize = make_shared<long>(boost::any_cast<long>(m["IndexSize"])); } if (m.find("PrimaryKeyIndexSize") != m.end() && !m["PrimaryKeyIndexSize"].empty()) { primaryKeyIndexSize = make_shared<long>(boost::any_cast<long>(m["PrimaryKeyIndexSize"])); } if (m.find("PartitionCount") != m.end() && !m["PartitionCount"].empty()) { partitionCount = make_shared<long>(boost::any_cast<long>(m["PartitionCount"])); } if (m.find("ColdDataSize") != m.end() && !m["ColdDataSize"].empty()) { coldDataSize = make_shared<long>(boost::any_cast<long>(m["ColdDataSize"])); } } virtual ~DescribeTableStatisticsResponseBodyItemsTableStatisticRecords() = default; }; class DescribeTableStatisticsResponseBodyItems : public Darabonba::Model { public: shared_ptr<vector<DescribeTableStatisticsResponseBodyItemsTableStatisticRecords>> tableStatisticRecords{}; DescribeTableStatisticsResponseBodyItems() {} explicit DescribeTableStatisticsResponseBodyItems(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (tableStatisticRecords) { vector<boost::any> temp1; for(auto item1:*tableStatisticRecords){ temp1.push_back(boost::any(item1.toMap())); } res["TableStatisticRecords"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("TableStatisticRecords") != m.end() && !m["TableStatisticRecords"].empty()) { if (typeid(vector<boost::any>) == m["TableStatisticRecords"].type()) { vector<DescribeTableStatisticsResponseBodyItemsTableStatisticRecords> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["TableStatisticRecords"])){ if (typeid(map<string, boost::any>) == item1.type()) { DescribeTableStatisticsResponseBodyItemsTableStatisticRecords model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } tableStatisticRecords = make_shared<vector<DescribeTableStatisticsResponseBodyItemsTableStatisticRecords>>(expect1); } } } virtual ~DescribeTableStatisticsResponseBodyItems() = default; }; class DescribeTableStatisticsResponseBody : public Darabonba::Model { public: shared_ptr<string> totalCount{}; shared_ptr<string> pageSize{}; shared_ptr<string> requestId{}; shared_ptr<string> pageNumber{}; shared_ptr<string> DBClusterId{}; shared_ptr<DescribeTableStatisticsResponseBodyItems> items{}; DescribeTableStatisticsResponseBody() {} explicit DescribeTableStatisticsResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (totalCount) { res["TotalCount"] = boost::any(*totalCount); } if (pageSize) { res["PageSize"] = boost::any(*pageSize); } if (requestId) { res["RequestId"] = boost::any(*requestId); } if (pageNumber) { res["PageNumber"] = boost::any(*pageNumber); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (items) { res["Items"] = items ? boost::any(items->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("TotalCount") != m.end() && !m["TotalCount"].empty()) { totalCount = make_shared<string>(boost::any_cast<string>(m["TotalCount"])); } if (m.find("PageSize") != m.end() && !m["PageSize"].empty()) { pageSize = make_shared<string>(boost::any_cast<string>(m["PageSize"])); } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("PageNumber") != m.end() && !m["PageNumber"].empty()) { pageNumber = make_shared<string>(boost::any_cast<string>(m["PageNumber"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("Items") != m.end() && !m["Items"].empty()) { if (typeid(map<string, boost::any>) == m["Items"].type()) { DescribeTableStatisticsResponseBodyItems model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Items"])); items = make_shared<DescribeTableStatisticsResponseBodyItems>(model1); } } } virtual ~DescribeTableStatisticsResponseBody() = default; }; class DescribeTableStatisticsResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeTableStatisticsResponseBody> body{}; DescribeTableStatisticsResponse() {} explicit DescribeTableStatisticsResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeTableStatisticsResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeTableStatisticsResponseBody>(model1); } } } virtual ~DescribeTableStatisticsResponse() = default; }; class DescribeTaskInfoRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<long> taskId{}; DescribeTaskInfoRequest() {} explicit DescribeTaskInfoRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (taskId) { res["TaskId"] = boost::any(*taskId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("TaskId") != m.end() && !m["TaskId"].empty()) { taskId = make_shared<long>(boost::any_cast<long>(m["TaskId"])); } } virtual ~DescribeTaskInfoRequest() = default; }; class DescribeTaskInfoResponseBodyTaskInfo : public Darabonba::Model { public: shared_ptr<string> status{}; shared_ptr<string> finishTime{}; shared_ptr<string> progress{}; shared_ptr<long> taskId{}; shared_ptr<string> beginTime{}; DescribeTaskInfoResponseBodyTaskInfo() {} explicit DescribeTaskInfoResponseBodyTaskInfo(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (status) { res["Status"] = boost::any(*status); } if (finishTime) { res["FinishTime"] = boost::any(*finishTime); } if (progress) { res["Progress"] = boost::any(*progress); } if (taskId) { res["TaskId"] = boost::any(*taskId); } if (beginTime) { res["BeginTime"] = boost::any(*beginTime); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Status") != m.end() && !m["Status"].empty()) { status = make_shared<string>(boost::any_cast<string>(m["Status"])); } if (m.find("FinishTime") != m.end() && !m["FinishTime"].empty()) { finishTime = make_shared<string>(boost::any_cast<string>(m["FinishTime"])); } if (m.find("Progress") != m.end() && !m["Progress"].empty()) { progress = make_shared<string>(boost::any_cast<string>(m["Progress"])); } if (m.find("TaskId") != m.end() && !m["TaskId"].empty()) { taskId = make_shared<long>(boost::any_cast<long>(m["TaskId"])); } if (m.find("BeginTime") != m.end() && !m["BeginTime"].empty()) { beginTime = make_shared<string>(boost::any_cast<string>(m["BeginTime"])); } } virtual ~DescribeTaskInfoResponseBodyTaskInfo() = default; }; class DescribeTaskInfoResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; shared_ptr<DescribeTaskInfoResponseBodyTaskInfo> taskInfo{}; DescribeTaskInfoResponseBody() {} explicit DescribeTaskInfoResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } if (taskInfo) { res["TaskInfo"] = taskInfo ? boost::any(taskInfo->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("TaskInfo") != m.end() && !m["TaskInfo"].empty()) { if (typeid(map<string, boost::any>) == m["TaskInfo"].type()) { DescribeTaskInfoResponseBodyTaskInfo model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["TaskInfo"])); taskInfo = make_shared<DescribeTaskInfoResponseBodyTaskInfo>(model1); } } } virtual ~DescribeTaskInfoResponseBody() = default; }; class DescribeTaskInfoResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DescribeTaskInfoResponseBody> body{}; DescribeTaskInfoResponse() {} explicit DescribeTaskInfoResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DescribeTaskInfoResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DescribeTaskInfoResponseBody>(model1); } } } virtual ~DescribeTaskInfoResponse() = default; }; class DownloadDiagnosisRecordsRequest : public Darabonba::Model { public: shared_ptr<string> DBClusterId{}; shared_ptr<string> startTime{}; shared_ptr<string> endTime{}; shared_ptr<string> regionId{}; shared_ptr<string> queryCondition{}; shared_ptr<string> keyword{}; shared_ptr<long> minPeakMemory{}; shared_ptr<long> maxPeakMemory{}; shared_ptr<long> minScanSize{}; shared_ptr<long> maxScanSize{}; shared_ptr<string> resourceGroup{}; shared_ptr<string> userName{}; shared_ptr<string> database{}; shared_ptr<string> clientIp{}; shared_ptr<string> lang{}; DownloadDiagnosisRecordsRequest() {} explicit DownloadDiagnosisRecordsRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (startTime) { res["StartTime"] = boost::any(*startTime); } if (endTime) { res["EndTime"] = boost::any(*endTime); } if (regionId) { res["RegionId"] = boost::any(*regionId); } if (queryCondition) { res["QueryCondition"] = boost::any(*queryCondition); } if (keyword) { res["Keyword"] = boost::any(*keyword); } if (minPeakMemory) { res["MinPeakMemory"] = boost::any(*minPeakMemory); } if (maxPeakMemory) { res["MaxPeakMemory"] = boost::any(*maxPeakMemory); } if (minScanSize) { res["MinScanSize"] = boost::any(*minScanSize); } if (maxScanSize) { res["MaxScanSize"] = boost::any(*maxScanSize); } if (resourceGroup) { res["ResourceGroup"] = boost::any(*resourceGroup); } if (userName) { res["UserName"] = boost::any(*userName); } if (database) { res["Database"] = boost::any(*database); } if (clientIp) { res["ClientIp"] = boost::any(*clientIp); } if (lang) { res["Lang"] = boost::any(*lang); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("StartTime") != m.end() && !m["StartTime"].empty()) { startTime = make_shared<string>(boost::any_cast<string>(m["StartTime"])); } if (m.find("EndTime") != m.end() && !m["EndTime"].empty()) { endTime = make_shared<string>(boost::any_cast<string>(m["EndTime"])); } if (m.find("RegionId") != m.end() && !m["RegionId"].empty()) { regionId = make_shared<string>(boost::any_cast<string>(m["RegionId"])); } if (m.find("QueryCondition") != m.end() && !m["QueryCondition"].empty()) { queryCondition = make_shared<string>(boost::any_cast<string>(m["QueryCondition"])); } if (m.find("Keyword") != m.end() && !m["Keyword"].empty()) { keyword = make_shared<string>(boost::any_cast<string>(m["Keyword"])); } if (m.find("MinPeakMemory") != m.end() && !m["MinPeakMemory"].empty()) { minPeakMemory = make_shared<long>(boost::any_cast<long>(m["MinPeakMemory"])); } if (m.find("MaxPeakMemory") != m.end() && !m["MaxPeakMemory"].empty()) { maxPeakMemory = make_shared<long>(boost::any_cast<long>(m["MaxPeakMemory"])); } if (m.find("MinScanSize") != m.end() && !m["MinScanSize"].empty()) { minScanSize = make_shared<long>(boost::any_cast<long>(m["MinScanSize"])); } if (m.find("MaxScanSize") != m.end() && !m["MaxScanSize"].empty()) { maxScanSize = make_shared<long>(boost::any_cast<long>(m["MaxScanSize"])); } if (m.find("ResourceGroup") != m.end() && !m["ResourceGroup"].empty()) { resourceGroup = make_shared<string>(boost::any_cast<string>(m["ResourceGroup"])); } if (m.find("UserName") != m.end() && !m["UserName"].empty()) { userName = make_shared<string>(boost::any_cast<string>(m["UserName"])); } if (m.find("Database") != m.end() && !m["Database"].empty()) { database = make_shared<string>(boost::any_cast<string>(m["Database"])); } if (m.find("ClientIp") != m.end() && !m["ClientIp"].empty()) { clientIp = make_shared<string>(boost::any_cast<string>(m["ClientIp"])); } if (m.find("Lang") != m.end() && !m["Lang"].empty()) { lang = make_shared<string>(boost::any_cast<string>(m["Lang"])); } } virtual ~DownloadDiagnosisRecordsRequest() = default; }; class DownloadDiagnosisRecordsResponseBody : public Darabonba::Model { public: shared_ptr<long> downloadId{}; shared_ptr<string> requestId{}; DownloadDiagnosisRecordsResponseBody() {} explicit DownloadDiagnosisRecordsResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (downloadId) { res["DownloadId"] = boost::any(*downloadId); } if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("DownloadId") != m.end() && !m["DownloadId"].empty()) { downloadId = make_shared<long>(boost::any_cast<long>(m["DownloadId"])); } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~DownloadDiagnosisRecordsResponseBody() = default; }; class DownloadDiagnosisRecordsResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<DownloadDiagnosisRecordsResponseBody> body{}; DownloadDiagnosisRecordsResponse() {} explicit DownloadDiagnosisRecordsResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { DownloadDiagnosisRecordsResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<DownloadDiagnosisRecordsResponseBody>(model1); } } } virtual ~DownloadDiagnosisRecordsResponse() = default; }; class GrantOperatorPermissionRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> expiredTime{}; shared_ptr<string> privileges{}; GrantOperatorPermissionRequest() {} explicit GrantOperatorPermissionRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (expiredTime) { res["ExpiredTime"] = boost::any(*expiredTime); } if (privileges) { res["Privileges"] = boost::any(*privileges); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("ExpiredTime") != m.end() && !m["ExpiredTime"].empty()) { expiredTime = make_shared<string>(boost::any_cast<string>(m["ExpiredTime"])); } if (m.find("Privileges") != m.end() && !m["Privileges"].empty()) { privileges = make_shared<string>(boost::any_cast<string>(m["Privileges"])); } } virtual ~GrantOperatorPermissionRequest() = default; }; class GrantOperatorPermissionResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; GrantOperatorPermissionResponseBody() {} explicit GrantOperatorPermissionResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~GrantOperatorPermissionResponseBody() = default; }; class GrantOperatorPermissionResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<GrantOperatorPermissionResponseBody> body{}; GrantOperatorPermissionResponse() {} explicit GrantOperatorPermissionResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { GrantOperatorPermissionResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<GrantOperatorPermissionResponseBody>(model1); } } } virtual ~GrantOperatorPermissionResponse() = default; }; class KillProcessRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> processId{}; KillProcessRequest() {} explicit KillProcessRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (processId) { res["ProcessId"] = boost::any(*processId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("ProcessId") != m.end() && !m["ProcessId"].empty()) { processId = make_shared<string>(boost::any_cast<string>(m["ProcessId"])); } } virtual ~KillProcessRequest() = default; }; class KillProcessResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; KillProcessResponseBody() {} explicit KillProcessResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~KillProcessResponseBody() = default; }; class KillProcessResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<KillProcessResponseBody> body{}; KillProcessResponse() {} explicit KillProcessResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { KillProcessResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<KillProcessResponseBody>(model1); } } } virtual ~KillProcessResponse() = default; }; class ListTagResourcesRequestTag : public Darabonba::Model { public: shared_ptr<string> key{}; shared_ptr<string> value{}; ListTagResourcesRequestTag() {} explicit ListTagResourcesRequestTag(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (key) { res["Key"] = boost::any(*key); } if (value) { res["Value"] = boost::any(*value); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Key") != m.end() && !m["Key"].empty()) { key = make_shared<string>(boost::any_cast<string>(m["Key"])); } if (m.find("Value") != m.end() && !m["Value"].empty()) { value = make_shared<string>(boost::any_cast<string>(m["Value"])); } } virtual ~ListTagResourcesRequestTag() = default; }; class ListTagResourcesRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> regionId{}; shared_ptr<string> resourceType{}; shared_ptr<string> nextToken{}; shared_ptr<vector<string>> resourceId{}; shared_ptr<vector<ListTagResourcesRequestTag>> tag{}; ListTagResourcesRequest() {} explicit ListTagResourcesRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (regionId) { res["RegionId"] = boost::any(*regionId); } if (resourceType) { res["ResourceType"] = boost::any(*resourceType); } if (nextToken) { res["NextToken"] = boost::any(*nextToken); } if (resourceId) { res["ResourceId"] = boost::any(*resourceId); } if (tag) { vector<boost::any> temp1; for(auto item1:*tag){ temp1.push_back(boost::any(item1.toMap())); } res["Tag"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("RegionId") != m.end() && !m["RegionId"].empty()) { regionId = make_shared<string>(boost::any_cast<string>(m["RegionId"])); } if (m.find("ResourceType") != m.end() && !m["ResourceType"].empty()) { resourceType = make_shared<string>(boost::any_cast<string>(m["ResourceType"])); } if (m.find("NextToken") != m.end() && !m["NextToken"].empty()) { nextToken = make_shared<string>(boost::any_cast<string>(m["NextToken"])); } if (m.find("ResourceId") != m.end() && !m["ResourceId"].empty()) { vector<string> toVec1; if (typeid(vector<boost::any>) == m["ResourceId"].type()) { vector<boost::any> vec1 = boost::any_cast<vector<boost::any>>(m["ResourceId"]); for (auto item:vec1) { toVec1.push_back(boost::any_cast<string>(item)); } } resourceId = make_shared<vector<string>>(toVec1); } if (m.find("Tag") != m.end() && !m["Tag"].empty()) { if (typeid(vector<boost::any>) == m["Tag"].type()) { vector<ListTagResourcesRequestTag> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["Tag"])){ if (typeid(map<string, boost::any>) == item1.type()) { ListTagResourcesRequestTag model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } tag = make_shared<vector<ListTagResourcesRequestTag>>(expect1); } } } virtual ~ListTagResourcesRequest() = default; }; class ListTagResourcesResponseBodyTagResourcesTagResource : public Darabonba::Model { public: shared_ptr<string> tagValue{}; shared_ptr<string> resourceType{}; shared_ptr<string> resourceId{}; shared_ptr<string> tagKey{}; ListTagResourcesResponseBodyTagResourcesTagResource() {} explicit ListTagResourcesResponseBodyTagResourcesTagResource(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (tagValue) { res["TagValue"] = boost::any(*tagValue); } if (resourceType) { res["ResourceType"] = boost::any(*resourceType); } if (resourceId) { res["ResourceId"] = boost::any(*resourceId); } if (tagKey) { res["TagKey"] = boost::any(*tagKey); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("TagValue") != m.end() && !m["TagValue"].empty()) { tagValue = make_shared<string>(boost::any_cast<string>(m["TagValue"])); } if (m.find("ResourceType") != m.end() && !m["ResourceType"].empty()) { resourceType = make_shared<string>(boost::any_cast<string>(m["ResourceType"])); } if (m.find("ResourceId") != m.end() && !m["ResourceId"].empty()) { resourceId = make_shared<string>(boost::any_cast<string>(m["ResourceId"])); } if (m.find("TagKey") != m.end() && !m["TagKey"].empty()) { tagKey = make_shared<string>(boost::any_cast<string>(m["TagKey"])); } } virtual ~ListTagResourcesResponseBodyTagResourcesTagResource() = default; }; class ListTagResourcesResponseBodyTagResources : public Darabonba::Model { public: shared_ptr<vector<ListTagResourcesResponseBodyTagResourcesTagResource>> tagResource{}; ListTagResourcesResponseBodyTagResources() {} explicit ListTagResourcesResponseBodyTagResources(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (tagResource) { vector<boost::any> temp1; for(auto item1:*tagResource){ temp1.push_back(boost::any(item1.toMap())); } res["TagResource"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("TagResource") != m.end() && !m["TagResource"].empty()) { if (typeid(vector<boost::any>) == m["TagResource"].type()) { vector<ListTagResourcesResponseBodyTagResourcesTagResource> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["TagResource"])){ if (typeid(map<string, boost::any>) == item1.type()) { ListTagResourcesResponseBodyTagResourcesTagResource model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } tagResource = make_shared<vector<ListTagResourcesResponseBodyTagResourcesTagResource>>(expect1); } } } virtual ~ListTagResourcesResponseBodyTagResources() = default; }; class ListTagResourcesResponseBody : public Darabonba::Model { public: shared_ptr<string> nextToken{}; shared_ptr<string> requestId{}; shared_ptr<ListTagResourcesResponseBodyTagResources> tagResources{}; ListTagResourcesResponseBody() {} explicit ListTagResourcesResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (nextToken) { res["NextToken"] = boost::any(*nextToken); } if (requestId) { res["RequestId"] = boost::any(*requestId); } if (tagResources) { res["TagResources"] = tagResources ? boost::any(tagResources->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("NextToken") != m.end() && !m["NextToken"].empty()) { nextToken = make_shared<string>(boost::any_cast<string>(m["NextToken"])); } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("TagResources") != m.end() && !m["TagResources"].empty()) { if (typeid(map<string, boost::any>) == m["TagResources"].type()) { ListTagResourcesResponseBodyTagResources model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["TagResources"])); tagResources = make_shared<ListTagResourcesResponseBodyTagResources>(model1); } } } virtual ~ListTagResourcesResponseBody() = default; }; class ListTagResourcesResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<ListTagResourcesResponseBody> body{}; ListTagResourcesResponse() {} explicit ListTagResourcesResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { ListTagResourcesResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<ListTagResourcesResponseBody>(model1); } } } virtual ~ListTagResourcesResponse() = default; }; class ModifyAccountDescriptionRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> accountName{}; shared_ptr<string> accountDescription{}; ModifyAccountDescriptionRequest() {} explicit ModifyAccountDescriptionRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (accountName) { res["AccountName"] = boost::any(*accountName); } if (accountDescription) { res["AccountDescription"] = boost::any(*accountDescription); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("AccountName") != m.end() && !m["AccountName"].empty()) { accountName = make_shared<string>(boost::any_cast<string>(m["AccountName"])); } if (m.find("AccountDescription") != m.end() && !m["AccountDescription"].empty()) { accountDescription = make_shared<string>(boost::any_cast<string>(m["AccountDescription"])); } } virtual ~ModifyAccountDescriptionRequest() = default; }; class ModifyAccountDescriptionResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; ModifyAccountDescriptionResponseBody() {} explicit ModifyAccountDescriptionResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~ModifyAccountDescriptionResponseBody() = default; }; class ModifyAccountDescriptionResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<ModifyAccountDescriptionResponseBody> body{}; ModifyAccountDescriptionResponse() {} explicit ModifyAccountDescriptionResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { ModifyAccountDescriptionResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<ModifyAccountDescriptionResponseBody>(model1); } } } virtual ~ModifyAccountDescriptionResponse() = default; }; class ModifyAuditLogConfigRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> regionId{}; shared_ptr<string> auditLogStatus{}; ModifyAuditLogConfigRequest() {} explicit ModifyAuditLogConfigRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (regionId) { res["RegionId"] = boost::any(*regionId); } if (auditLogStatus) { res["AuditLogStatus"] = boost::any(*auditLogStatus); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("RegionId") != m.end() && !m["RegionId"].empty()) { regionId = make_shared<string>(boost::any_cast<string>(m["RegionId"])); } if (m.find("AuditLogStatus") != m.end() && !m["AuditLogStatus"].empty()) { auditLogStatus = make_shared<string>(boost::any_cast<string>(m["AuditLogStatus"])); } } virtual ~ModifyAuditLogConfigRequest() = default; }; class ModifyAuditLogConfigResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; ModifyAuditLogConfigResponseBody() {} explicit ModifyAuditLogConfigResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~ModifyAuditLogConfigResponseBody() = default; }; class ModifyAuditLogConfigResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<ModifyAuditLogConfigResponseBody> body{}; ModifyAuditLogConfigResponse() {} explicit ModifyAuditLogConfigResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { ModifyAuditLogConfigResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<ModifyAuditLogConfigResponseBody>(model1); } } } virtual ~ModifyAuditLogConfigResponse() = default; }; class ModifyAutoRenewAttributeRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> regionId{}; shared_ptr<string> renewalStatus{}; shared_ptr<string> duration{}; shared_ptr<string> periodUnit{}; ModifyAutoRenewAttributeRequest() {} explicit ModifyAutoRenewAttributeRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (regionId) { res["RegionId"] = boost::any(*regionId); } if (renewalStatus) { res["RenewalStatus"] = boost::any(*renewalStatus); } if (duration) { res["Duration"] = boost::any(*duration); } if (periodUnit) { res["PeriodUnit"] = boost::any(*periodUnit); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("RegionId") != m.end() && !m["RegionId"].empty()) { regionId = make_shared<string>(boost::any_cast<string>(m["RegionId"])); } if (m.find("RenewalStatus") != m.end() && !m["RenewalStatus"].empty()) { renewalStatus = make_shared<string>(boost::any_cast<string>(m["RenewalStatus"])); } if (m.find("Duration") != m.end() && !m["Duration"].empty()) { duration = make_shared<string>(boost::any_cast<string>(m["Duration"])); } if (m.find("PeriodUnit") != m.end() && !m["PeriodUnit"].empty()) { periodUnit = make_shared<string>(boost::any_cast<string>(m["PeriodUnit"])); } } virtual ~ModifyAutoRenewAttributeRequest() = default; }; class ModifyAutoRenewAttributeResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; ModifyAutoRenewAttributeResponseBody() {} explicit ModifyAutoRenewAttributeResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~ModifyAutoRenewAttributeResponseBody() = default; }; class ModifyAutoRenewAttributeResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<ModifyAutoRenewAttributeResponseBody> body{}; ModifyAutoRenewAttributeResponse() {} explicit ModifyAutoRenewAttributeResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { ModifyAutoRenewAttributeResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<ModifyAutoRenewAttributeResponseBody>(model1); } } } virtual ~ModifyAutoRenewAttributeResponse() = default; }; class ModifyBackupPolicyRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> preferredBackupTime{}; shared_ptr<string> preferredBackupPeriod{}; shared_ptr<string> backupRetentionPeriod{}; shared_ptr<string> enableBackupLog{}; shared_ptr<long> logBackupRetentionPeriod{}; ModifyBackupPolicyRequest() {} explicit ModifyBackupPolicyRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (preferredBackupTime) { res["PreferredBackupTime"] = boost::any(*preferredBackupTime); } if (preferredBackupPeriod) { res["PreferredBackupPeriod"] = boost::any(*preferredBackupPeriod); } if (backupRetentionPeriod) { res["BackupRetentionPeriod"] = boost::any(*backupRetentionPeriod); } if (enableBackupLog) { res["EnableBackupLog"] = boost::any(*enableBackupLog); } if (logBackupRetentionPeriod) { res["LogBackupRetentionPeriod"] = boost::any(*logBackupRetentionPeriod); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("PreferredBackupTime") != m.end() && !m["PreferredBackupTime"].empty()) { preferredBackupTime = make_shared<string>(boost::any_cast<string>(m["PreferredBackupTime"])); } if (m.find("PreferredBackupPeriod") != m.end() && !m["PreferredBackupPeriod"].empty()) { preferredBackupPeriod = make_shared<string>(boost::any_cast<string>(m["PreferredBackupPeriod"])); } if (m.find("BackupRetentionPeriod") != m.end() && !m["BackupRetentionPeriod"].empty()) { backupRetentionPeriod = make_shared<string>(boost::any_cast<string>(m["BackupRetentionPeriod"])); } if (m.find("EnableBackupLog") != m.end() && !m["EnableBackupLog"].empty()) { enableBackupLog = make_shared<string>(boost::any_cast<string>(m["EnableBackupLog"])); } if (m.find("LogBackupRetentionPeriod") != m.end() && !m["LogBackupRetentionPeriod"].empty()) { logBackupRetentionPeriod = make_shared<long>(boost::any_cast<long>(m["LogBackupRetentionPeriod"])); } } virtual ~ModifyBackupPolicyRequest() = default; }; class ModifyBackupPolicyResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; ModifyBackupPolicyResponseBody() {} explicit ModifyBackupPolicyResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~ModifyBackupPolicyResponseBody() = default; }; class ModifyBackupPolicyResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<ModifyBackupPolicyResponseBody> body{}; ModifyBackupPolicyResponse() {} explicit ModifyBackupPolicyResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { ModifyBackupPolicyResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<ModifyBackupPolicyResponseBody>(model1); } } } virtual ~ModifyBackupPolicyResponse() = default; }; class ModifyClusterConnectionStringRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> connectionStringPrefix{}; shared_ptr<string> currentConnectionString{}; shared_ptr<long> port{}; ModifyClusterConnectionStringRequest() {} explicit ModifyClusterConnectionStringRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (connectionStringPrefix) { res["ConnectionStringPrefix"] = boost::any(*connectionStringPrefix); } if (currentConnectionString) { res["CurrentConnectionString"] = boost::any(*currentConnectionString); } if (port) { res["Port"] = boost::any(*port); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("ConnectionStringPrefix") != m.end() && !m["ConnectionStringPrefix"].empty()) { connectionStringPrefix = make_shared<string>(boost::any_cast<string>(m["ConnectionStringPrefix"])); } if (m.find("CurrentConnectionString") != m.end() && !m["CurrentConnectionString"].empty()) { currentConnectionString = make_shared<string>(boost::any_cast<string>(m["CurrentConnectionString"])); } if (m.find("Port") != m.end() && !m["Port"].empty()) { port = make_shared<long>(boost::any_cast<long>(m["Port"])); } } virtual ~ModifyClusterConnectionStringRequest() = default; }; class ModifyClusterConnectionStringResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; ModifyClusterConnectionStringResponseBody() {} explicit ModifyClusterConnectionStringResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~ModifyClusterConnectionStringResponseBody() = default; }; class ModifyClusterConnectionStringResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<ModifyClusterConnectionStringResponseBody> body{}; ModifyClusterConnectionStringResponse() {} explicit ModifyClusterConnectionStringResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { ModifyClusterConnectionStringResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<ModifyClusterConnectionStringResponseBody>(model1); } } } virtual ~ModifyClusterConnectionStringResponse() = default; }; class ModifyDBClusterRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> DBNodeGroupCount{}; shared_ptr<string> DBNodeStorage{}; shared_ptr<string> DBNodeClass{}; shared_ptr<string> modifyType{}; shared_ptr<string> executorCount{}; shared_ptr<string> regionId{}; shared_ptr<string> storageResource{}; shared_ptr<string> computeResource{}; shared_ptr<long> elasticIOResource{}; shared_ptr<string> DBClusterCategory{}; shared_ptr<string> mode{}; ModifyDBClusterRequest() {} explicit ModifyDBClusterRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (DBNodeGroupCount) { res["DBNodeGroupCount"] = boost::any(*DBNodeGroupCount); } if (DBNodeStorage) { res["DBNodeStorage"] = boost::any(*DBNodeStorage); } if (DBNodeClass) { res["DBNodeClass"] = boost::any(*DBNodeClass); } if (modifyType) { res["ModifyType"] = boost::any(*modifyType); } if (executorCount) { res["ExecutorCount"] = boost::any(*executorCount); } if (regionId) { res["RegionId"] = boost::any(*regionId); } if (storageResource) { res["StorageResource"] = boost::any(*storageResource); } if (computeResource) { res["ComputeResource"] = boost::any(*computeResource); } if (elasticIOResource) { res["ElasticIOResource"] = boost::any(*elasticIOResource); } if (DBClusterCategory) { res["DBClusterCategory"] = boost::any(*DBClusterCategory); } if (mode) { res["Mode"] = boost::any(*mode); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("DBNodeGroupCount") != m.end() && !m["DBNodeGroupCount"].empty()) { DBNodeGroupCount = make_shared<string>(boost::any_cast<string>(m["DBNodeGroupCount"])); } if (m.find("DBNodeStorage") != m.end() && !m["DBNodeStorage"].empty()) { DBNodeStorage = make_shared<string>(boost::any_cast<string>(m["DBNodeStorage"])); } if (m.find("DBNodeClass") != m.end() && !m["DBNodeClass"].empty()) { DBNodeClass = make_shared<string>(boost::any_cast<string>(m["DBNodeClass"])); } if (m.find("ModifyType") != m.end() && !m["ModifyType"].empty()) { modifyType = make_shared<string>(boost::any_cast<string>(m["ModifyType"])); } if (m.find("ExecutorCount") != m.end() && !m["ExecutorCount"].empty()) { executorCount = make_shared<string>(boost::any_cast<string>(m["ExecutorCount"])); } if (m.find("RegionId") != m.end() && !m["RegionId"].empty()) { regionId = make_shared<string>(boost::any_cast<string>(m["RegionId"])); } if (m.find("StorageResource") != m.end() && !m["StorageResource"].empty()) { storageResource = make_shared<string>(boost::any_cast<string>(m["StorageResource"])); } if (m.find("ComputeResource") != m.end() && !m["ComputeResource"].empty()) { computeResource = make_shared<string>(boost::any_cast<string>(m["ComputeResource"])); } if (m.find("ElasticIOResource") != m.end() && !m["ElasticIOResource"].empty()) { elasticIOResource = make_shared<long>(boost::any_cast<long>(m["ElasticIOResource"])); } if (m.find("DBClusterCategory") != m.end() && !m["DBClusterCategory"].empty()) { DBClusterCategory = make_shared<string>(boost::any_cast<string>(m["DBClusterCategory"])); } if (m.find("Mode") != m.end() && !m["Mode"].empty()) { mode = make_shared<string>(boost::any_cast<string>(m["Mode"])); } } virtual ~ModifyDBClusterRequest() = default; }; class ModifyDBClusterResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> orderId{}; ModifyDBClusterResponseBody() {} explicit ModifyDBClusterResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (orderId) { res["OrderId"] = boost::any(*orderId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("OrderId") != m.end() && !m["OrderId"].empty()) { orderId = make_shared<string>(boost::any_cast<string>(m["OrderId"])); } } virtual ~ModifyDBClusterResponseBody() = default; }; class ModifyDBClusterResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<ModifyDBClusterResponseBody> body{}; ModifyDBClusterResponse() {} explicit ModifyDBClusterResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { ModifyDBClusterResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<ModifyDBClusterResponseBody>(model1); } } } virtual ~ModifyDBClusterResponse() = default; }; class ModifyDBClusterAccessWhiteListRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> securityIps{}; shared_ptr<string> DBClusterIPArrayName{}; shared_ptr<string> DBClusterIPArrayAttribute{}; shared_ptr<string> modifyMode{}; ModifyDBClusterAccessWhiteListRequest() {} explicit ModifyDBClusterAccessWhiteListRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (securityIps) { res["SecurityIps"] = boost::any(*securityIps); } if (DBClusterIPArrayName) { res["DBClusterIPArrayName"] = boost::any(*DBClusterIPArrayName); } if (DBClusterIPArrayAttribute) { res["DBClusterIPArrayAttribute"] = boost::any(*DBClusterIPArrayAttribute); } if (modifyMode) { res["ModifyMode"] = boost::any(*modifyMode); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("SecurityIps") != m.end() && !m["SecurityIps"].empty()) { securityIps = make_shared<string>(boost::any_cast<string>(m["SecurityIps"])); } if (m.find("DBClusterIPArrayName") != m.end() && !m["DBClusterIPArrayName"].empty()) { DBClusterIPArrayName = make_shared<string>(boost::any_cast<string>(m["DBClusterIPArrayName"])); } if (m.find("DBClusterIPArrayAttribute") != m.end() && !m["DBClusterIPArrayAttribute"].empty()) { DBClusterIPArrayAttribute = make_shared<string>(boost::any_cast<string>(m["DBClusterIPArrayAttribute"])); } if (m.find("ModifyMode") != m.end() && !m["ModifyMode"].empty()) { modifyMode = make_shared<string>(boost::any_cast<string>(m["ModifyMode"])); } } virtual ~ModifyDBClusterAccessWhiteListRequest() = default; }; class ModifyDBClusterAccessWhiteListResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; shared_ptr<string> DBClusterId{}; shared_ptr<long> taskId{}; ModifyDBClusterAccessWhiteListResponseBody() {} explicit ModifyDBClusterAccessWhiteListResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (taskId) { res["TaskId"] = boost::any(*taskId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("TaskId") != m.end() && !m["TaskId"].empty()) { taskId = make_shared<long>(boost::any_cast<long>(m["TaskId"])); } } virtual ~ModifyDBClusterAccessWhiteListResponseBody() = default; }; class ModifyDBClusterAccessWhiteListResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<ModifyDBClusterAccessWhiteListResponseBody> body{}; ModifyDBClusterAccessWhiteListResponse() {} explicit ModifyDBClusterAccessWhiteListResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { ModifyDBClusterAccessWhiteListResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<ModifyDBClusterAccessWhiteListResponseBody>(model1); } } } virtual ~ModifyDBClusterAccessWhiteListResponse() = default; }; class ModifyDBClusterDescriptionRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> DBClusterDescription{}; ModifyDBClusterDescriptionRequest() {} explicit ModifyDBClusterDescriptionRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (DBClusterDescription) { res["DBClusterDescription"] = boost::any(*DBClusterDescription); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("DBClusterDescription") != m.end() && !m["DBClusterDescription"].empty()) { DBClusterDescription = make_shared<string>(boost::any_cast<string>(m["DBClusterDescription"])); } } virtual ~ModifyDBClusterDescriptionRequest() = default; }; class ModifyDBClusterDescriptionResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; ModifyDBClusterDescriptionResponseBody() {} explicit ModifyDBClusterDescriptionResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~ModifyDBClusterDescriptionResponseBody() = default; }; class ModifyDBClusterDescriptionResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<ModifyDBClusterDescriptionResponseBody> body{}; ModifyDBClusterDescriptionResponse() {} explicit ModifyDBClusterDescriptionResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { ModifyDBClusterDescriptionResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<ModifyDBClusterDescriptionResponseBody>(model1); } } } virtual ~ModifyDBClusterDescriptionResponse() = default; }; class ModifyDBClusterMaintainTimeRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> maintainTime{}; ModifyDBClusterMaintainTimeRequest() {} explicit ModifyDBClusterMaintainTimeRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (maintainTime) { res["MaintainTime"] = boost::any(*maintainTime); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("MaintainTime") != m.end() && !m["MaintainTime"].empty()) { maintainTime = make_shared<string>(boost::any_cast<string>(m["MaintainTime"])); } } virtual ~ModifyDBClusterMaintainTimeRequest() = default; }; class ModifyDBClusterMaintainTimeResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; ModifyDBClusterMaintainTimeResponseBody() {} explicit ModifyDBClusterMaintainTimeResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~ModifyDBClusterMaintainTimeResponseBody() = default; }; class ModifyDBClusterMaintainTimeResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<ModifyDBClusterMaintainTimeResponseBody> body{}; ModifyDBClusterMaintainTimeResponse() {} explicit ModifyDBClusterMaintainTimeResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { ModifyDBClusterMaintainTimeResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<ModifyDBClusterMaintainTimeResponseBody>(model1); } } } virtual ~ModifyDBClusterMaintainTimeResponse() = default; }; class ModifyDBClusterResourceGroupRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> newResourceGroupId{}; ModifyDBClusterResourceGroupRequest() {} explicit ModifyDBClusterResourceGroupRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (newResourceGroupId) { res["NewResourceGroupId"] = boost::any(*newResourceGroupId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("NewResourceGroupId") != m.end() && !m["NewResourceGroupId"].empty()) { newResourceGroupId = make_shared<string>(boost::any_cast<string>(m["NewResourceGroupId"])); } } virtual ~ModifyDBClusterResourceGroupRequest() = default; }; class ModifyDBClusterResourceGroupResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; ModifyDBClusterResourceGroupResponseBody() {} explicit ModifyDBClusterResourceGroupResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~ModifyDBClusterResourceGroupResponseBody() = default; }; class ModifyDBClusterResourceGroupResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<ModifyDBClusterResourceGroupResponseBody> body{}; ModifyDBClusterResourceGroupResponse() {} explicit ModifyDBClusterResourceGroupResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { ModifyDBClusterResourceGroupResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<ModifyDBClusterResourceGroupResponseBody>(model1); } } } virtual ~ModifyDBClusterResourceGroupResponse() = default; }; class ModifyDBResourcePoolRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> poolName{}; shared_ptr<string> queryType{}; shared_ptr<long> nodeNum{}; ModifyDBResourcePoolRequest() {} explicit ModifyDBResourcePoolRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (poolName) { res["PoolName"] = boost::any(*poolName); } if (queryType) { res["QueryType"] = boost::any(*queryType); } if (nodeNum) { res["NodeNum"] = boost::any(*nodeNum); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("PoolName") != m.end() && !m["PoolName"].empty()) { poolName = make_shared<string>(boost::any_cast<string>(m["PoolName"])); } if (m.find("QueryType") != m.end() && !m["QueryType"].empty()) { queryType = make_shared<string>(boost::any_cast<string>(m["QueryType"])); } if (m.find("NodeNum") != m.end() && !m["NodeNum"].empty()) { nodeNum = make_shared<long>(boost::any_cast<long>(m["NodeNum"])); } } virtual ~ModifyDBResourcePoolRequest() = default; }; class ModifyDBResourcePoolResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; ModifyDBResourcePoolResponseBody() {} explicit ModifyDBResourcePoolResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~ModifyDBResourcePoolResponseBody() = default; }; class ModifyDBResourcePoolResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<ModifyDBResourcePoolResponseBody> body{}; ModifyDBResourcePoolResponse() {} explicit ModifyDBResourcePoolResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { ModifyDBResourcePoolResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<ModifyDBResourcePoolResponseBody>(model1); } } } virtual ~ModifyDBResourcePoolResponse() = default; }; class ModifyElasticPlanRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> elasticPlanName{}; shared_ptr<string> resourcePoolName{}; shared_ptr<long> elasticPlanNodeNum{}; shared_ptr<string> elasticPlanTimeStart{}; shared_ptr<string> elasticPlanTimeEnd{}; shared_ptr<string> elasticPlanWeeklyRepeat{}; shared_ptr<string> elasticPlanStartDay{}; shared_ptr<string> elasticPlanEndDay{}; shared_ptr<bool> elasticPlanEnable{}; ModifyElasticPlanRequest() {} explicit ModifyElasticPlanRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (elasticPlanName) { res["ElasticPlanName"] = boost::any(*elasticPlanName); } if (resourcePoolName) { res["ResourcePoolName"] = boost::any(*resourcePoolName); } if (elasticPlanNodeNum) { res["ElasticPlanNodeNum"] = boost::any(*elasticPlanNodeNum); } if (elasticPlanTimeStart) { res["ElasticPlanTimeStart"] = boost::any(*elasticPlanTimeStart); } if (elasticPlanTimeEnd) { res["ElasticPlanTimeEnd"] = boost::any(*elasticPlanTimeEnd); } if (elasticPlanWeeklyRepeat) { res["ElasticPlanWeeklyRepeat"] = boost::any(*elasticPlanWeeklyRepeat); } if (elasticPlanStartDay) { res["ElasticPlanStartDay"] = boost::any(*elasticPlanStartDay); } if (elasticPlanEndDay) { res["ElasticPlanEndDay"] = boost::any(*elasticPlanEndDay); } if (elasticPlanEnable) { res["ElasticPlanEnable"] = boost::any(*elasticPlanEnable); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("ElasticPlanName") != m.end() && !m["ElasticPlanName"].empty()) { elasticPlanName = make_shared<string>(boost::any_cast<string>(m["ElasticPlanName"])); } if (m.find("ResourcePoolName") != m.end() && !m["ResourcePoolName"].empty()) { resourcePoolName = make_shared<string>(boost::any_cast<string>(m["ResourcePoolName"])); } if (m.find("ElasticPlanNodeNum") != m.end() && !m["ElasticPlanNodeNum"].empty()) { elasticPlanNodeNum = make_shared<long>(boost::any_cast<long>(m["ElasticPlanNodeNum"])); } if (m.find("ElasticPlanTimeStart") != m.end() && !m["ElasticPlanTimeStart"].empty()) { elasticPlanTimeStart = make_shared<string>(boost::any_cast<string>(m["ElasticPlanTimeStart"])); } if (m.find("ElasticPlanTimeEnd") != m.end() && !m["ElasticPlanTimeEnd"].empty()) { elasticPlanTimeEnd = make_shared<string>(boost::any_cast<string>(m["ElasticPlanTimeEnd"])); } if (m.find("ElasticPlanWeeklyRepeat") != m.end() && !m["ElasticPlanWeeklyRepeat"].empty()) { elasticPlanWeeklyRepeat = make_shared<string>(boost::any_cast<string>(m["ElasticPlanWeeklyRepeat"])); } if (m.find("ElasticPlanStartDay") != m.end() && !m["ElasticPlanStartDay"].empty()) { elasticPlanStartDay = make_shared<string>(boost::any_cast<string>(m["ElasticPlanStartDay"])); } if (m.find("ElasticPlanEndDay") != m.end() && !m["ElasticPlanEndDay"].empty()) { elasticPlanEndDay = make_shared<string>(boost::any_cast<string>(m["ElasticPlanEndDay"])); } if (m.find("ElasticPlanEnable") != m.end() && !m["ElasticPlanEnable"].empty()) { elasticPlanEnable = make_shared<bool>(boost::any_cast<bool>(m["ElasticPlanEnable"])); } } virtual ~ModifyElasticPlanRequest() = default; }; class ModifyElasticPlanResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; ModifyElasticPlanResponseBody() {} explicit ModifyElasticPlanResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~ModifyElasticPlanResponseBody() = default; }; class ModifyElasticPlanResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<ModifyElasticPlanResponseBody> body{}; ModifyElasticPlanResponse() {} explicit ModifyElasticPlanResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { ModifyElasticPlanResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<ModifyElasticPlanResponseBody>(model1); } } } virtual ~ModifyElasticPlanResponse() = default; }; class ModifyLogBackupPolicyRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> enableBackupLog{}; shared_ptr<string> logBackupRetentionPeriod{}; ModifyLogBackupPolicyRequest() {} explicit ModifyLogBackupPolicyRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (enableBackupLog) { res["EnableBackupLog"] = boost::any(*enableBackupLog); } if (logBackupRetentionPeriod) { res["LogBackupRetentionPeriod"] = boost::any(*logBackupRetentionPeriod); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("EnableBackupLog") != m.end() && !m["EnableBackupLog"].empty()) { enableBackupLog = make_shared<string>(boost::any_cast<string>(m["EnableBackupLog"])); } if (m.find("LogBackupRetentionPeriod") != m.end() && !m["LogBackupRetentionPeriod"].empty()) { logBackupRetentionPeriod = make_shared<string>(boost::any_cast<string>(m["LogBackupRetentionPeriod"])); } } virtual ~ModifyLogBackupPolicyRequest() = default; }; class ModifyLogBackupPolicyResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; ModifyLogBackupPolicyResponseBody() {} explicit ModifyLogBackupPolicyResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~ModifyLogBackupPolicyResponseBody() = default; }; class ModifyLogBackupPolicyResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<ModifyLogBackupPolicyResponseBody> body{}; ModifyLogBackupPolicyResponse() {} explicit ModifyLogBackupPolicyResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { ModifyLogBackupPolicyResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<ModifyLogBackupPolicyResponseBody>(model1); } } } virtual ~ModifyLogBackupPolicyResponse() = default; }; class ModifyMaintenanceActionRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> ids{}; shared_ptr<string> switchTime{}; shared_ptr<string> regionId{}; ModifyMaintenanceActionRequest() {} explicit ModifyMaintenanceActionRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (ids) { res["Ids"] = boost::any(*ids); } if (switchTime) { res["SwitchTime"] = boost::any(*switchTime); } if (regionId) { res["RegionId"] = boost::any(*regionId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("Ids") != m.end() && !m["Ids"].empty()) { ids = make_shared<string>(boost::any_cast<string>(m["Ids"])); } if (m.find("SwitchTime") != m.end() && !m["SwitchTime"].empty()) { switchTime = make_shared<string>(boost::any_cast<string>(m["SwitchTime"])); } if (m.find("RegionId") != m.end() && !m["RegionId"].empty()) { regionId = make_shared<string>(boost::any_cast<string>(m["RegionId"])); } } virtual ~ModifyMaintenanceActionRequest() = default; }; class ModifyMaintenanceActionResponseBody : public Darabonba::Model { public: shared_ptr<string> ids{}; shared_ptr<string> requestId{}; ModifyMaintenanceActionResponseBody() {} explicit ModifyMaintenanceActionResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ids) { res["Ids"] = boost::any(*ids); } if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Ids") != m.end() && !m["Ids"].empty()) { ids = make_shared<string>(boost::any_cast<string>(m["Ids"])); } if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~ModifyMaintenanceActionResponseBody() = default; }; class ModifyMaintenanceActionResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<ModifyMaintenanceActionResponseBody> body{}; ModifyMaintenanceActionResponse() {} explicit ModifyMaintenanceActionResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { ModifyMaintenanceActionResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<ModifyMaintenanceActionResponseBody>(model1); } } } virtual ~ModifyMaintenanceActionResponse() = default; }; class ReleaseClusterPublicConnectionRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; ReleaseClusterPublicConnectionRequest() {} explicit ReleaseClusterPublicConnectionRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } } virtual ~ReleaseClusterPublicConnectionRequest() = default; }; class ReleaseClusterPublicConnectionResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; ReleaseClusterPublicConnectionResponseBody() {} explicit ReleaseClusterPublicConnectionResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~ReleaseClusterPublicConnectionResponseBody() = default; }; class ReleaseClusterPublicConnectionResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<ReleaseClusterPublicConnectionResponseBody> body{}; ReleaseClusterPublicConnectionResponse() {} explicit ReleaseClusterPublicConnectionResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { ReleaseClusterPublicConnectionResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<ReleaseClusterPublicConnectionResponseBody>(model1); } } } virtual ~ReleaseClusterPublicConnectionResponse() = default; }; class ResetAccountPasswordRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> accountName{}; shared_ptr<string> accountPassword{}; shared_ptr<string> accountType{}; ResetAccountPasswordRequest() {} explicit ResetAccountPasswordRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (accountName) { res["AccountName"] = boost::any(*accountName); } if (accountPassword) { res["AccountPassword"] = boost::any(*accountPassword); } if (accountType) { res["AccountType"] = boost::any(*accountType); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("AccountName") != m.end() && !m["AccountName"].empty()) { accountName = make_shared<string>(boost::any_cast<string>(m["AccountName"])); } if (m.find("AccountPassword") != m.end() && !m["AccountPassword"].empty()) { accountPassword = make_shared<string>(boost::any_cast<string>(m["AccountPassword"])); } if (m.find("AccountType") != m.end() && !m["AccountType"].empty()) { accountType = make_shared<string>(boost::any_cast<string>(m["AccountType"])); } } virtual ~ResetAccountPasswordRequest() = default; }; class ResetAccountPasswordResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; shared_ptr<string> DBClusterId{}; shared_ptr<long> taskId{}; ResetAccountPasswordResponseBody() {} explicit ResetAccountPasswordResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (taskId) { res["TaskId"] = boost::any(*taskId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("TaskId") != m.end() && !m["TaskId"].empty()) { taskId = make_shared<long>(boost::any_cast<long>(m["TaskId"])); } } virtual ~ResetAccountPasswordResponseBody() = default; }; class ResetAccountPasswordResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<ResetAccountPasswordResponseBody> body{}; ResetAccountPasswordResponse() {} explicit ResetAccountPasswordResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { ResetAccountPasswordResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<ResetAccountPasswordResponseBody>(model1); } } } virtual ~ResetAccountPasswordResponse() = default; }; class RevokeOperatorPermissionRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; RevokeOperatorPermissionRequest() {} explicit RevokeOperatorPermissionRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } } virtual ~RevokeOperatorPermissionRequest() = default; }; class RevokeOperatorPermissionResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; RevokeOperatorPermissionResponseBody() {} explicit RevokeOperatorPermissionResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~RevokeOperatorPermissionResponseBody() = default; }; class RevokeOperatorPermissionResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<RevokeOperatorPermissionResponseBody> body{}; RevokeOperatorPermissionResponse() {} explicit RevokeOperatorPermissionResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { RevokeOperatorPermissionResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<RevokeOperatorPermissionResponseBody>(model1); } } } virtual ~RevokeOperatorPermissionResponse() = default; }; class TagResourcesRequestTag : public Darabonba::Model { public: shared_ptr<string> key{}; shared_ptr<string> value{}; TagResourcesRequestTag() {} explicit TagResourcesRequestTag(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (key) { res["Key"] = boost::any(*key); } if (value) { res["Value"] = boost::any(*value); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("Key") != m.end() && !m["Key"].empty()) { key = make_shared<string>(boost::any_cast<string>(m["Key"])); } if (m.find("Value") != m.end() && !m["Value"].empty()) { value = make_shared<string>(boost::any_cast<string>(m["Value"])); } } virtual ~TagResourcesRequestTag() = default; }; class TagResourcesRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> regionId{}; shared_ptr<string> resourceType{}; shared_ptr<vector<string>> resourceId{}; shared_ptr<vector<TagResourcesRequestTag>> tag{}; TagResourcesRequest() {} explicit TagResourcesRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (regionId) { res["RegionId"] = boost::any(*regionId); } if (resourceType) { res["ResourceType"] = boost::any(*resourceType); } if (resourceId) { res["ResourceId"] = boost::any(*resourceId); } if (tag) { vector<boost::any> temp1; for(auto item1:*tag){ temp1.push_back(boost::any(item1.toMap())); } res["Tag"] = boost::any(temp1); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("RegionId") != m.end() && !m["RegionId"].empty()) { regionId = make_shared<string>(boost::any_cast<string>(m["RegionId"])); } if (m.find("ResourceType") != m.end() && !m["ResourceType"].empty()) { resourceType = make_shared<string>(boost::any_cast<string>(m["ResourceType"])); } if (m.find("ResourceId") != m.end() && !m["ResourceId"].empty()) { vector<string> toVec1; if (typeid(vector<boost::any>) == m["ResourceId"].type()) { vector<boost::any> vec1 = boost::any_cast<vector<boost::any>>(m["ResourceId"]); for (auto item:vec1) { toVec1.push_back(boost::any_cast<string>(item)); } } resourceId = make_shared<vector<string>>(toVec1); } if (m.find("Tag") != m.end() && !m["Tag"].empty()) { if (typeid(vector<boost::any>) == m["Tag"].type()) { vector<TagResourcesRequestTag> expect1; for(auto item1:boost::any_cast<vector<boost::any>>(m["Tag"])){ if (typeid(map<string, boost::any>) == item1.type()) { TagResourcesRequestTag model2; model2.fromMap(boost::any_cast<map<string, boost::any>>(item1)); expect1.push_back(model2); } } tag = make_shared<vector<TagResourcesRequestTag>>(expect1); } } } virtual ~TagResourcesRequest() = default; }; class TagResourcesResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; TagResourcesResponseBody() {} explicit TagResourcesResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~TagResourcesResponseBody() = default; }; class TagResourcesResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<TagResourcesResponseBody> body{}; TagResourcesResponse() {} explicit TagResourcesResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { TagResourcesResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<TagResourcesResponseBody>(model1); } } } virtual ~TagResourcesResponse() = default; }; class UnbindDBResourcePoolWithUserRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> DBClusterId{}; shared_ptr<string> poolName{}; shared_ptr<string> poolUser{}; UnbindDBResourcePoolWithUserRequest() {} explicit UnbindDBResourcePoolWithUserRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (DBClusterId) { res["DBClusterId"] = boost::any(*DBClusterId); } if (poolName) { res["PoolName"] = boost::any(*poolName); } if (poolUser) { res["PoolUser"] = boost::any(*poolUser); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("DBClusterId") != m.end() && !m["DBClusterId"].empty()) { DBClusterId = make_shared<string>(boost::any_cast<string>(m["DBClusterId"])); } if (m.find("PoolName") != m.end() && !m["PoolName"].empty()) { poolName = make_shared<string>(boost::any_cast<string>(m["PoolName"])); } if (m.find("PoolUser") != m.end() && !m["PoolUser"].empty()) { poolUser = make_shared<string>(boost::any_cast<string>(m["PoolUser"])); } } virtual ~UnbindDBResourcePoolWithUserRequest() = default; }; class UnbindDBResourcePoolWithUserResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; UnbindDBResourcePoolWithUserResponseBody() {} explicit UnbindDBResourcePoolWithUserResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~UnbindDBResourcePoolWithUserResponseBody() = default; }; class UnbindDBResourcePoolWithUserResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<UnbindDBResourcePoolWithUserResponseBody> body{}; UnbindDBResourcePoolWithUserResponse() {} explicit UnbindDBResourcePoolWithUserResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { UnbindDBResourcePoolWithUserResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<UnbindDBResourcePoolWithUserResponseBody>(model1); } } } virtual ~UnbindDBResourcePoolWithUserResponse() = default; }; class UntagResourcesRequest : public Darabonba::Model { public: shared_ptr<long> ownerId{}; shared_ptr<string> resourceOwnerAccount{}; shared_ptr<long> resourceOwnerId{}; shared_ptr<string> ownerAccount{}; shared_ptr<string> regionId{}; shared_ptr<string> resourceType{}; shared_ptr<bool> all{}; shared_ptr<vector<string>> resourceId{}; shared_ptr<vector<string>> tagKey{}; UntagResourcesRequest() {} explicit UntagResourcesRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (ownerId) { res["OwnerId"] = boost::any(*ownerId); } if (resourceOwnerAccount) { res["ResourceOwnerAccount"] = boost::any(*resourceOwnerAccount); } if (resourceOwnerId) { res["ResourceOwnerId"] = boost::any(*resourceOwnerId); } if (ownerAccount) { res["OwnerAccount"] = boost::any(*ownerAccount); } if (regionId) { res["RegionId"] = boost::any(*regionId); } if (resourceType) { res["ResourceType"] = boost::any(*resourceType); } if (all) { res["All"] = boost::any(*all); } if (resourceId) { res["ResourceId"] = boost::any(*resourceId); } if (tagKey) { res["TagKey"] = boost::any(*tagKey); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) { ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"])); } if (m.find("ResourceOwnerAccount") != m.end() && !m["ResourceOwnerAccount"].empty()) { resourceOwnerAccount = make_shared<string>(boost::any_cast<string>(m["ResourceOwnerAccount"])); } if (m.find("ResourceOwnerId") != m.end() && !m["ResourceOwnerId"].empty()) { resourceOwnerId = make_shared<long>(boost::any_cast<long>(m["ResourceOwnerId"])); } if (m.find("OwnerAccount") != m.end() && !m["OwnerAccount"].empty()) { ownerAccount = make_shared<string>(boost::any_cast<string>(m["OwnerAccount"])); } if (m.find("RegionId") != m.end() && !m["RegionId"].empty()) { regionId = make_shared<string>(boost::any_cast<string>(m["RegionId"])); } if (m.find("ResourceType") != m.end() && !m["ResourceType"].empty()) { resourceType = make_shared<string>(boost::any_cast<string>(m["ResourceType"])); } if (m.find("All") != m.end() && !m["All"].empty()) { all = make_shared<bool>(boost::any_cast<bool>(m["All"])); } if (m.find("ResourceId") != m.end() && !m["ResourceId"].empty()) { vector<string> toVec1; if (typeid(vector<boost::any>) == m["ResourceId"].type()) { vector<boost::any> vec1 = boost::any_cast<vector<boost::any>>(m["ResourceId"]); for (auto item:vec1) { toVec1.push_back(boost::any_cast<string>(item)); } } resourceId = make_shared<vector<string>>(toVec1); } if (m.find("TagKey") != m.end() && !m["TagKey"].empty()) { vector<string> toVec1; if (typeid(vector<boost::any>) == m["TagKey"].type()) { vector<boost::any> vec1 = boost::any_cast<vector<boost::any>>(m["TagKey"]); for (auto item:vec1) { toVec1.push_back(boost::any_cast<string>(item)); } } tagKey = make_shared<vector<string>>(toVec1); } } virtual ~UntagResourcesRequest() = default; }; class UntagResourcesResponseBody : public Darabonba::Model { public: shared_ptr<string> requestId{}; UntagResourcesResponseBody() {} explicit UntagResourcesResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override {} map<string, boost::any> toMap() override { map<string, boost::any> res; if (requestId) { res["RequestId"] = boost::any(*requestId); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) { requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"])); } } virtual ~UntagResourcesResponseBody() = default; }; class UntagResourcesResponse : public Darabonba::Model { public: shared_ptr<map<string, string>> headers{}; shared_ptr<UntagResourcesResponseBody> body{}; UntagResourcesResponse() {} explicit UntagResourcesResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) { fromMap(config); }; void validate() override { if (!headers) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required."))); } if (!body) { BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required."))); } } map<string, boost::any> toMap() override { map<string, boost::any> res; if (headers) { res["headers"] = boost::any(*headers); } if (body) { res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({})); } return res; } void fromMap(map<string, boost::any> m) override { if (m.find("headers") != m.end() && !m["headers"].empty()) { map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]); map<string, string> toMap1; for (auto item:map1) { toMap1[item.first] = item.second; } headers = make_shared<map<string, string>>(toMap1); } if (m.find("body") != m.end() && !m["body"].empty()) { if (typeid(map<string, boost::any>) == m["body"].type()) { UntagResourcesResponseBody model1; model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"])); body = make_shared<UntagResourcesResponseBody>(model1); } } } virtual ~UntagResourcesResponse() = default; }; class Client : Alibabacloud_OpenApi::Client { public: explicit Client(const shared_ptr<Alibabacloud_OpenApi::Config>& config); string getEndpoint(shared_ptr<string> productId, shared_ptr<string> regionId, shared_ptr<string> endpointRule, shared_ptr<string> network, shared_ptr<string> suffix, shared_ptr<map<string, string>> endpointMap, shared_ptr<string> endpoint); AllocateClusterPublicConnectionResponse allocateClusterPublicConnectionWithOptions(shared_ptr<AllocateClusterPublicConnectionRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); AllocateClusterPublicConnectionResponse allocateClusterPublicConnection(shared_ptr<AllocateClusterPublicConnectionRequest> request); BindDBResourcePoolWithUserResponse bindDBResourcePoolWithUserWithOptions(shared_ptr<BindDBResourcePoolWithUserRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); BindDBResourcePoolWithUserResponse bindDBResourcePoolWithUser(shared_ptr<BindDBResourcePoolWithUserRequest> request); CreateAccountResponse createAccountWithOptions(shared_ptr<CreateAccountRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); CreateAccountResponse createAccount(shared_ptr<CreateAccountRequest> request); CreateDBClusterResponse createDBClusterWithOptions(shared_ptr<CreateDBClusterRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); CreateDBClusterResponse createDBCluster(shared_ptr<CreateDBClusterRequest> request); CreateDBResourcePoolResponse createDBResourcePoolWithOptions(shared_ptr<CreateDBResourcePoolRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); CreateDBResourcePoolResponse createDBResourcePool(shared_ptr<CreateDBResourcePoolRequest> request); CreateElasticPlanResponse createElasticPlanWithOptions(shared_ptr<CreateElasticPlanRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); CreateElasticPlanResponse createElasticPlan(shared_ptr<CreateElasticPlanRequest> request); DeleteAccountResponse deleteAccountWithOptions(shared_ptr<DeleteAccountRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DeleteAccountResponse deleteAccount(shared_ptr<DeleteAccountRequest> request); DeleteDBClusterResponse deleteDBClusterWithOptions(shared_ptr<DeleteDBClusterRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DeleteDBClusterResponse deleteDBCluster(shared_ptr<DeleteDBClusterRequest> request); DeleteDBResourcePoolResponse deleteDBResourcePoolWithOptions(shared_ptr<DeleteDBResourcePoolRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DeleteDBResourcePoolResponse deleteDBResourcePool(shared_ptr<DeleteDBResourcePoolRequest> request); DeleteElasticPlanResponse deleteElasticPlanWithOptions(shared_ptr<DeleteElasticPlanRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DeleteElasticPlanResponse deleteElasticPlan(shared_ptr<DeleteElasticPlanRequest> request); DescribeAccountsResponse describeAccountsWithOptions(shared_ptr<DescribeAccountsRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeAccountsResponse describeAccounts(shared_ptr<DescribeAccountsRequest> request); DescribeAllAccountsResponse describeAllAccountsWithOptions(shared_ptr<DescribeAllAccountsRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeAllAccountsResponse describeAllAccounts(shared_ptr<DescribeAllAccountsRequest> request); DescribeAllDataSourceResponse describeAllDataSourceWithOptions(shared_ptr<DescribeAllDataSourceRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeAllDataSourceResponse describeAllDataSource(shared_ptr<DescribeAllDataSourceRequest> request); DescribeAuditLogConfigResponse describeAuditLogConfigWithOptions(shared_ptr<DescribeAuditLogConfigRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeAuditLogConfigResponse describeAuditLogConfig(shared_ptr<DescribeAuditLogConfigRequest> request); DescribeAuditLogRecordsResponse describeAuditLogRecordsWithOptions(shared_ptr<DescribeAuditLogRecordsRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeAuditLogRecordsResponse describeAuditLogRecords(shared_ptr<DescribeAuditLogRecordsRequest> request); DescribeAutoRenewAttributeResponse describeAutoRenewAttributeWithOptions(shared_ptr<DescribeAutoRenewAttributeRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeAutoRenewAttributeResponse describeAutoRenewAttribute(shared_ptr<DescribeAutoRenewAttributeRequest> request); DescribeAvailableResourceResponse describeAvailableResourceWithOptions(shared_ptr<DescribeAvailableResourceRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeAvailableResourceResponse describeAvailableResource(shared_ptr<DescribeAvailableResourceRequest> request); DescribeBackupPolicyResponse describeBackupPolicyWithOptions(shared_ptr<DescribeBackupPolicyRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeBackupPolicyResponse describeBackupPolicy(shared_ptr<DescribeBackupPolicyRequest> request); DescribeBackupsResponse describeBackupsWithOptions(shared_ptr<DescribeBackupsRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeBackupsResponse describeBackups(shared_ptr<DescribeBackupsRequest> request); DescribeColumnsResponse describeColumnsWithOptions(shared_ptr<DescribeColumnsRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeColumnsResponse describeColumns(shared_ptr<DescribeColumnsRequest> request); DescribeConnectionCountRecordsResponse describeConnectionCountRecordsWithOptions(shared_ptr<DescribeConnectionCountRecordsRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeConnectionCountRecordsResponse describeConnectionCountRecords(shared_ptr<DescribeConnectionCountRecordsRequest> request); DescribeDBClusterAccessWhiteListResponse describeDBClusterAccessWhiteListWithOptions(shared_ptr<DescribeDBClusterAccessWhiteListRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeDBClusterAccessWhiteListResponse describeDBClusterAccessWhiteList(shared_ptr<DescribeDBClusterAccessWhiteListRequest> request); DescribeDBClusterAttributeResponse describeDBClusterAttributeWithOptions(shared_ptr<DescribeDBClusterAttributeRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeDBClusterAttributeResponse describeDBClusterAttribute(shared_ptr<DescribeDBClusterAttributeRequest> request); DescribeDBClusterForecastResponse describeDBClusterForecastWithOptions(shared_ptr<DescribeDBClusterForecastRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeDBClusterForecastResponse describeDBClusterForecast(shared_ptr<DescribeDBClusterForecastRequest> request); DescribeDBClusterHealthReportResponse describeDBClusterHealthReportWithOptions(shared_ptr<DescribeDBClusterHealthReportRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeDBClusterHealthReportResponse describeDBClusterHealthReport(shared_ptr<DescribeDBClusterHealthReportRequest> request); DescribeDBClusterNetInfoResponse describeDBClusterNetInfoWithOptions(shared_ptr<DescribeDBClusterNetInfoRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeDBClusterNetInfoResponse describeDBClusterNetInfo(shared_ptr<DescribeDBClusterNetInfoRequest> request); DescribeDBClusterPerformanceResponse describeDBClusterPerformanceWithOptions(shared_ptr<DescribeDBClusterPerformanceRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeDBClusterPerformanceResponse describeDBClusterPerformance(shared_ptr<DescribeDBClusterPerformanceRequest> request); DescribeDBClusterResourcePoolPerformanceResponse describeDBClusterResourcePoolPerformanceWithOptions(shared_ptr<DescribeDBClusterResourcePoolPerformanceRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeDBClusterResourcePoolPerformanceResponse describeDBClusterResourcePoolPerformance(shared_ptr<DescribeDBClusterResourcePoolPerformanceRequest> request); DescribeDBClustersResponse describeDBClustersWithOptions(shared_ptr<DescribeDBClustersRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeDBClustersResponse describeDBClusters(shared_ptr<DescribeDBClustersRequest> request); DescribeDBResourcePoolResponse describeDBResourcePoolWithOptions(shared_ptr<DescribeDBResourcePoolRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeDBResourcePoolResponse describeDBResourcePool(shared_ptr<DescribeDBResourcePoolRequest> request); DescribeDiagnosisDimensionsResponse describeDiagnosisDimensionsWithOptions(shared_ptr<DescribeDiagnosisDimensionsRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeDiagnosisDimensionsResponse describeDiagnosisDimensions(shared_ptr<DescribeDiagnosisDimensionsRequest> request); DescribeDiagnosisRecordsResponse describeDiagnosisRecordsWithOptions(shared_ptr<DescribeDiagnosisRecordsRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeDiagnosisRecordsResponse describeDiagnosisRecords(shared_ptr<DescribeDiagnosisRecordsRequest> request); DescribeDiagnosisSQLInfoResponse describeDiagnosisSQLInfoWithOptions(shared_ptr<DescribeDiagnosisSQLInfoRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeDiagnosisSQLInfoResponse describeDiagnosisSQLInfo(shared_ptr<DescribeDiagnosisSQLInfoRequest> request); DescribeDownloadRecordsResponse describeDownloadRecordsWithOptions(shared_ptr<DescribeDownloadRecordsRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeDownloadRecordsResponse describeDownloadRecords(shared_ptr<DescribeDownloadRecordsRequest> request); DescribeElasticDailyPlanResponse describeElasticDailyPlanWithOptions(shared_ptr<DescribeElasticDailyPlanRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeElasticDailyPlanResponse describeElasticDailyPlan(shared_ptr<DescribeElasticDailyPlanRequest> request); DescribeElasticPlanResponse describeElasticPlanWithOptions(shared_ptr<DescribeElasticPlanRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeElasticPlanResponse describeElasticPlan(shared_ptr<DescribeElasticPlanRequest> request); DescribeInclinedTablesResponse describeInclinedTablesWithOptions(shared_ptr<DescribeInclinedTablesRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeInclinedTablesResponse describeInclinedTables(shared_ptr<DescribeInclinedTablesRequest> request); DescribeLoadTasksRecordsResponse describeLoadTasksRecordsWithOptions(shared_ptr<DescribeLoadTasksRecordsRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeLoadTasksRecordsResponse describeLoadTasksRecords(shared_ptr<DescribeLoadTasksRecordsRequest> request); DescribeMaintenanceActionResponse describeMaintenanceActionWithOptions(shared_ptr<DescribeMaintenanceActionRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeMaintenanceActionResponse describeMaintenanceAction(shared_ptr<DescribeMaintenanceActionRequest> request); DescribeOperatorPermissionResponse describeOperatorPermissionWithOptions(shared_ptr<DescribeOperatorPermissionRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeOperatorPermissionResponse describeOperatorPermission(shared_ptr<DescribeOperatorPermissionRequest> request); DescribePatternPerformanceResponse describePatternPerformanceWithOptions(shared_ptr<DescribePatternPerformanceRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribePatternPerformanceResponse describePatternPerformance(shared_ptr<DescribePatternPerformanceRequest> request); DescribeProcessListResponse describeProcessListWithOptions(shared_ptr<DescribeProcessListRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeProcessListResponse describeProcessList(shared_ptr<DescribeProcessListRequest> request); DescribeRegionsResponse describeRegionsWithOptions(shared_ptr<DescribeRegionsRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeRegionsResponse describeRegions(shared_ptr<DescribeRegionsRequest> request); DescribeSchemasResponse describeSchemasWithOptions(shared_ptr<DescribeSchemasRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeSchemasResponse describeSchemas(shared_ptr<DescribeSchemasRequest> request); DescribeSlowLogRecordsResponse describeSlowLogRecordsWithOptions(shared_ptr<DescribeSlowLogRecordsRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeSlowLogRecordsResponse describeSlowLogRecords(shared_ptr<DescribeSlowLogRecordsRequest> request); DescribeSlowLogTrendResponse describeSlowLogTrendWithOptions(shared_ptr<DescribeSlowLogTrendRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeSlowLogTrendResponse describeSlowLogTrend(shared_ptr<DescribeSlowLogTrendRequest> request); DescribeSqlPatternResponse describeSqlPatternWithOptions(shared_ptr<DescribeSqlPatternRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeSqlPatternResponse describeSqlPattern(shared_ptr<DescribeSqlPatternRequest> request); DescribeSQLPatternAttributeResponse describeSQLPatternAttributeWithOptions(shared_ptr<DescribeSQLPatternAttributeRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeSQLPatternAttributeResponse describeSQLPatternAttribute(shared_ptr<DescribeSQLPatternAttributeRequest> request); DescribeSQLPatternsResponse describeSQLPatternsWithOptions(shared_ptr<DescribeSQLPatternsRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeSQLPatternsResponse describeSQLPatterns(shared_ptr<DescribeSQLPatternsRequest> request); DescribeSQLPlanResponse describeSQLPlanWithOptions(shared_ptr<DescribeSQLPlanRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeSQLPlanResponse describeSQLPlan(shared_ptr<DescribeSQLPlanRequest> request); DescribeSQLPlanTaskResponse describeSQLPlanTaskWithOptions(shared_ptr<DescribeSQLPlanTaskRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeSQLPlanTaskResponse describeSQLPlanTask(shared_ptr<DescribeSQLPlanTaskRequest> request); DescribeTableAccessCountResponse describeTableAccessCountWithOptions(shared_ptr<DescribeTableAccessCountRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeTableAccessCountResponse describeTableAccessCount(shared_ptr<DescribeTableAccessCountRequest> request); DescribeTableDetailResponse describeTableDetailWithOptions(shared_ptr<DescribeTableDetailRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeTableDetailResponse describeTableDetail(shared_ptr<DescribeTableDetailRequest> request); DescribeTablePartitionDiagnoseResponse describeTablePartitionDiagnoseWithOptions(shared_ptr<DescribeTablePartitionDiagnoseRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeTablePartitionDiagnoseResponse describeTablePartitionDiagnose(shared_ptr<DescribeTablePartitionDiagnoseRequest> request); DescribeTablesResponse describeTablesWithOptions(shared_ptr<DescribeTablesRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeTablesResponse describeTables(shared_ptr<DescribeTablesRequest> request); DescribeTableStatisticsResponse describeTableStatisticsWithOptions(shared_ptr<DescribeTableStatisticsRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeTableStatisticsResponse describeTableStatistics(shared_ptr<DescribeTableStatisticsRequest> request); DescribeTaskInfoResponse describeTaskInfoWithOptions(shared_ptr<DescribeTaskInfoRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DescribeTaskInfoResponse describeTaskInfo(shared_ptr<DescribeTaskInfoRequest> request); DownloadDiagnosisRecordsResponse downloadDiagnosisRecordsWithOptions(shared_ptr<DownloadDiagnosisRecordsRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); DownloadDiagnosisRecordsResponse downloadDiagnosisRecords(shared_ptr<DownloadDiagnosisRecordsRequest> request); GrantOperatorPermissionResponse grantOperatorPermissionWithOptions(shared_ptr<GrantOperatorPermissionRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); GrantOperatorPermissionResponse grantOperatorPermission(shared_ptr<GrantOperatorPermissionRequest> request); KillProcessResponse killProcessWithOptions(shared_ptr<KillProcessRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); KillProcessResponse killProcess(shared_ptr<KillProcessRequest> request); ListTagResourcesResponse listTagResourcesWithOptions(shared_ptr<ListTagResourcesRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); ListTagResourcesResponse listTagResources(shared_ptr<ListTagResourcesRequest> request); ModifyAccountDescriptionResponse modifyAccountDescriptionWithOptions(shared_ptr<ModifyAccountDescriptionRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); ModifyAccountDescriptionResponse modifyAccountDescription(shared_ptr<ModifyAccountDescriptionRequest> request); ModifyAuditLogConfigResponse modifyAuditLogConfigWithOptions(shared_ptr<ModifyAuditLogConfigRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); ModifyAuditLogConfigResponse modifyAuditLogConfig(shared_ptr<ModifyAuditLogConfigRequest> request); ModifyAutoRenewAttributeResponse modifyAutoRenewAttributeWithOptions(shared_ptr<ModifyAutoRenewAttributeRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); ModifyAutoRenewAttributeResponse modifyAutoRenewAttribute(shared_ptr<ModifyAutoRenewAttributeRequest> request); ModifyBackupPolicyResponse modifyBackupPolicyWithOptions(shared_ptr<ModifyBackupPolicyRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); ModifyBackupPolicyResponse modifyBackupPolicy(shared_ptr<ModifyBackupPolicyRequest> request); ModifyClusterConnectionStringResponse modifyClusterConnectionStringWithOptions(shared_ptr<ModifyClusterConnectionStringRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); ModifyClusterConnectionStringResponse modifyClusterConnectionString(shared_ptr<ModifyClusterConnectionStringRequest> request); ModifyDBClusterResponse modifyDBClusterWithOptions(shared_ptr<ModifyDBClusterRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); ModifyDBClusterResponse modifyDBCluster(shared_ptr<ModifyDBClusterRequest> request); ModifyDBClusterAccessWhiteListResponse modifyDBClusterAccessWhiteListWithOptions(shared_ptr<ModifyDBClusterAccessWhiteListRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); ModifyDBClusterAccessWhiteListResponse modifyDBClusterAccessWhiteList(shared_ptr<ModifyDBClusterAccessWhiteListRequest> request); ModifyDBClusterDescriptionResponse modifyDBClusterDescriptionWithOptions(shared_ptr<ModifyDBClusterDescriptionRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); ModifyDBClusterDescriptionResponse modifyDBClusterDescription(shared_ptr<ModifyDBClusterDescriptionRequest> request); ModifyDBClusterMaintainTimeResponse modifyDBClusterMaintainTimeWithOptions(shared_ptr<ModifyDBClusterMaintainTimeRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); ModifyDBClusterMaintainTimeResponse modifyDBClusterMaintainTime(shared_ptr<ModifyDBClusterMaintainTimeRequest> request); ModifyDBClusterResourceGroupResponse modifyDBClusterResourceGroupWithOptions(shared_ptr<ModifyDBClusterResourceGroupRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); ModifyDBClusterResourceGroupResponse modifyDBClusterResourceGroup(shared_ptr<ModifyDBClusterResourceGroupRequest> request); ModifyDBResourcePoolResponse modifyDBResourcePoolWithOptions(shared_ptr<ModifyDBResourcePoolRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); ModifyDBResourcePoolResponse modifyDBResourcePool(shared_ptr<ModifyDBResourcePoolRequest> request); ModifyElasticPlanResponse modifyElasticPlanWithOptions(shared_ptr<ModifyElasticPlanRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); ModifyElasticPlanResponse modifyElasticPlan(shared_ptr<ModifyElasticPlanRequest> request); ModifyLogBackupPolicyResponse modifyLogBackupPolicyWithOptions(shared_ptr<ModifyLogBackupPolicyRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); ModifyLogBackupPolicyResponse modifyLogBackupPolicy(shared_ptr<ModifyLogBackupPolicyRequest> request); ModifyMaintenanceActionResponse modifyMaintenanceActionWithOptions(shared_ptr<ModifyMaintenanceActionRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); ModifyMaintenanceActionResponse modifyMaintenanceAction(shared_ptr<ModifyMaintenanceActionRequest> request); ReleaseClusterPublicConnectionResponse releaseClusterPublicConnectionWithOptions(shared_ptr<ReleaseClusterPublicConnectionRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); ReleaseClusterPublicConnectionResponse releaseClusterPublicConnection(shared_ptr<ReleaseClusterPublicConnectionRequest> request); ResetAccountPasswordResponse resetAccountPasswordWithOptions(shared_ptr<ResetAccountPasswordRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); ResetAccountPasswordResponse resetAccountPassword(shared_ptr<ResetAccountPasswordRequest> request); RevokeOperatorPermissionResponse revokeOperatorPermissionWithOptions(shared_ptr<RevokeOperatorPermissionRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); RevokeOperatorPermissionResponse revokeOperatorPermission(shared_ptr<RevokeOperatorPermissionRequest> request); TagResourcesResponse tagResourcesWithOptions(shared_ptr<TagResourcesRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); TagResourcesResponse tagResources(shared_ptr<TagResourcesRequest> request); UnbindDBResourcePoolWithUserResponse unbindDBResourcePoolWithUserWithOptions(shared_ptr<UnbindDBResourcePoolWithUserRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); UnbindDBResourcePoolWithUserResponse unbindDBResourcePoolWithUser(shared_ptr<UnbindDBResourcePoolWithUserRequest> request); UntagResourcesResponse untagResourcesWithOptions(shared_ptr<UntagResourcesRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime); UntagResourcesResponse untagResources(shared_ptr<UntagResourcesRequest> request); virtual ~Client() = default; }; } // namespace Alibabacloud_Adb20190315 #endif
35.544113
227
0.645656
[ "vector", "model" ]
66b6bd4b4231c4a37334bd46e0b42ed90476e8a1
4,078
cpp
C++
ps4a/ps4b/main.cpp
Siroibma/Comp4
d873928924d641e4730b6355264f02b9cfd08bb7
[ "MIT" ]
null
null
null
ps4a/ps4b/main.cpp
Siroibma/Comp4
d873928924d641e4730b6355264f02b9cfd08bb7
[ "MIT" ]
null
null
null
ps4a/ps4b/main.cpp
Siroibma/Comp4
d873928924d641e4730b6355264f02b9cfd08bb7
[ "MIT" ]
null
null
null
#include <SFML/Graphics.hpp> #include <SFML/System.hpp> #include <SFML/Audio.hpp> #include <SFML/Window.hpp> #include <math.h> #include <limits.h> #include "RingBuffer.h" #include <math.h> #include <random> #define CONCERT_A 440.0 #define SAMPLES_PER_SEC 44100 class StringSound{ public: explicit StringSound(double frequency); explicit StringSound(std::vector<sf::Int16> init); StringSound (const StringSound &obj) { _time = obj._time; _rb = obj._rb; } //~StringSound(); void pluck(); void tic(); sf::Int16 sample(); int time(); private: RingBuffer _rb; int _time; }; std::vector<sf::Int16> makeSamplesFromString(StringSound gs) { std::vector<sf::Int16> samples; gs.pluck(); int duration = 8; int i; for(i = 0; i < SAMPLES_PER_SEC * duration; i++) { gs.tic(); samples.push_back(gs.sample()); } return samples; } StringSound::StringSound(double frequency){ int string_cap = ceil(44100/frequency); //44,100 divided by given frequency rounded to the highest whole number _rb(string_cap); for(int i = 0; i < string_cap; i++){ _rb.enqueue(0); } _time = 0; //std::cout << (*_rb).capacity() << std::endl; } StringSound::StringSound(std::vector<sf::Int16> init){ int string_cap = init.size(); for(auto i = init.begin(); i < init.end(); i++) { _rb.enqueue((std::int16_t)*i); } //std::cout << (*_rb).capacity(); _time = 0; //std::cout << (*_rb).capacity() << std::endl; } void StringSound::pluck(){ std::default_random_engine generator; std::uniform_int_distribution<int> distribution(-32768,32767); //maintaining int_16t _rb.empty(); // Here we clear the vector while maintaining capctity //Fill the vector with random numbers for(int i = 0; i < _rb.capacity(); ++i) { _rb.enqueue(distribution(generator)); } //std::cout << (*_rb).peek() << std::endl; } void StringSound::tic() { int16_t hold = _rb.dequeue(); //hold is equal to the first value hold = ((hold + _rb.peek())*.5) * .996; // (first value + second value *.5) * .996 _rb.enqueue(hold); _time += 1; // This represents the amount of times we used tic //std::cout << (*_rb).size() << std::endl; } sf::Int16 StringSound::sample(){ return _rb.peek(); } int StringSound::time(){ return _time; } /*StringSound::~StringSound() { std::cout << "Destructor called, deleting memory allocated" << std::endl; delete(_rb); } */ int main() { /* sf::RenderWindow window(sf::VideoMode(300, 200), "SFML Guitar Hero Lite"); sf::Event event; double freq; std::vector<sf::Int16> samples; // we're reusing the freq and samples vars, but // there are separate copies of GuitarString, SoundBuffer, and Sound // for each note // // GuitarString is based on freq // samples are generated from GuitarString // SoundBuffer is loaded from samples // Sound is set to SoundBuffer freq = CONCERT_A; StringSound gs1 = StringSound(freq); sf::Sound sound1; sf::SoundBuffer buf1; samples = makeSamplesFromString(gs1); if (!buf1.loadFromSamples(&samples[0], samples.size(), 2, SAMPLES_PER_SEC)) throw std::runtime_error("sf::SoundBuffer: failed to load from samples."); sound1.setBuffer(buf1); freq = CONCERT_A * pow(2, 3.0/12.0); StringSound gs2 = StringSound(freq); sf::Sound sound2; sf::SoundBuffer buf2; samples = makeSamplesFromString(gs2); if (!buf2.loadFromSamples(&samples[0], samples.size(), 2, SAMPLES_PER_SEC)) throw std::runtime_error("sf::SoundBuffer: failed to load from samples."); sound2.setBuffer(buf2); while (window.isOpen()) { while (window.pollEvent(event)) { switch (event.type) { case sf::Event::Closed: window.close(); break; case sf::Event::KeyPressed: switch (event.key.code) { case sf::Keyboard::A: sound1.play(); break; case sf::Keyboard::C: sound2.play(); break; default: break; } default: break; } window.clear(); window.display(); } }*/ return 0; }
24.715152
113
0.639039
[ "vector" ]
66b9df930dfbfabbc4efa0a3d0f5fbfca284aa02
12,246
hpp
C++
include/GlobalNamespace/MirroredGameNoteController.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/MirroredGameNoteController.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/MirroredGameNoteController.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: MirroredNoteController`1 #include "GlobalNamespace/MirroredNoteController_1.hpp" // Including type: ICubeNoteControllerInitializable`1 #include "GlobalNamespace/ICubeNoteControllerInitializable_1.hpp" // Including type: INoteVisualModifierTypeProvider #include "GlobalNamespace/INoteVisualModifierTypeProvider.hpp" // Including type: INoteMovementProvider #include "GlobalNamespace/INoteMovementProvider.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: GlobalNamespace namespace GlobalNamespace { // Forward declaring type: IGameNoteMirrorable class IGameNoteMirrorable; // Forward declaring type: MaterialPropertyBlockController class MaterialPropertyBlockController; // Forward declaring type: ColorManager class ColorManager; // Forward declaring type: NoteMovement class NoteMovement; // Forward declaring type: NoteVisualModifierType struct NoteVisualModifierType; } // Forward declaring namespace: System namespace System { // Forward declaring type: Action`1<T> template<typename T> class Action_1; } // Completed forward declares // Type namespace: namespace GlobalNamespace { // Forward declaring type: MirroredGameNoteController class MirroredGameNoteController; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::GlobalNamespace::MirroredGameNoteController); DEFINE_IL2CPP_ARG_TYPE(::GlobalNamespace::MirroredGameNoteController*, "", "MirroredGameNoteController"); // Type namespace: namespace GlobalNamespace { // WARNING Size may be invalid! // Autogenerated type: MirroredGameNoteController // [TokenAttribute] Offset: FFFFFFFF class MirroredGameNoteController : public ::GlobalNamespace::MirroredNoteController_1<::GlobalNamespace::IGameNoteMirrorable*>/*, public ::GlobalNamespace::ICubeNoteControllerInitializable_1<::GlobalNamespace::MirroredGameNoteController*>, public ::GlobalNamespace::INoteVisualModifierTypeProvider, public ::GlobalNamespace::INoteMovementProvider*/ { public: // Nested type: ::GlobalNamespace::MirroredGameNoteController::Pool class Pool; #ifdef USE_CODEGEN_FIELDS public: #else #ifdef CODEGEN_FIELD_ACCESSIBILITY CODEGEN_FIELD_ACCESSIBILITY: #else protected: #endif #endif // private MaterialPropertyBlockController _materialPropertyBlockController // Size: 0x8 // Offset: 0x48 ::GlobalNamespace::MaterialPropertyBlockController* materialPropertyBlockController; // Field size check static_assert(sizeof(::GlobalNamespace::MaterialPropertyBlockController*) == 0x8); // [InjectAttribute] Offset: 0x124F170 // private readonly ColorManager _colorManager // Size: 0x8 // Offset: 0x50 ::GlobalNamespace::ColorManager* colorManager; // Field size check static_assert(sizeof(::GlobalNamespace::ColorManager*) == 0x8); // private System.Action`1<MirroredGameNoteController> cubeNoteControllerDidInitEvent // Size: 0x8 // Offset: 0x58 ::System::Action_1<::GlobalNamespace::MirroredGameNoteController*>* cubeNoteControllerDidInitEvent; // Field size check static_assert(sizeof(::System::Action_1<::GlobalNamespace::MirroredGameNoteController*>*) == 0x8); public: // Creating interface conversion operator: operator ::GlobalNamespace::ICubeNoteControllerInitializable_1<::GlobalNamespace::MirroredGameNoteController*> operator ::GlobalNamespace::ICubeNoteControllerInitializable_1<::GlobalNamespace::MirroredGameNoteController*>() noexcept { return *reinterpret_cast<::GlobalNamespace::ICubeNoteControllerInitializable_1<::GlobalNamespace::MirroredGameNoteController*>*>(this); } // Creating interface conversion operator: operator ::GlobalNamespace::INoteVisualModifierTypeProvider operator ::GlobalNamespace::INoteVisualModifierTypeProvider() noexcept { return *reinterpret_cast<::GlobalNamespace::INoteVisualModifierTypeProvider*>(this); } // Creating interface conversion operator: operator ::GlobalNamespace::INoteMovementProvider operator ::GlobalNamespace::INoteMovementProvider() noexcept { return *reinterpret_cast<::GlobalNamespace::INoteMovementProvider*>(this); } // [DoesNotRequireDomainReloadInitAttribute] Offset: 0x124F190 // Get static field: static private readonly System.Int32 _colorId static int _get__colorId(); // Set static field: static private readonly System.Int32 _colorId static void _set__colorId(int value); // Get instance field reference: private MaterialPropertyBlockController _materialPropertyBlockController ::GlobalNamespace::MaterialPropertyBlockController*& dyn__materialPropertyBlockController(); // Get instance field reference: private readonly ColorManager _colorManager ::GlobalNamespace::ColorManager*& dyn__colorManager(); // Get instance field reference: private System.Action`1<MirroredGameNoteController> cubeNoteControllerDidInitEvent ::System::Action_1<::GlobalNamespace::MirroredGameNoteController*>*& dyn_cubeNoteControllerDidInitEvent(); // public NoteMovement get_noteMovement() // Offset: 0x13031AC ::GlobalNamespace::NoteMovement* get_noteMovement(); // public NoteVisualModifierType get_noteVisualModifierType() // Offset: 0x1303268 ::GlobalNamespace::NoteVisualModifierType get_noteVisualModifierType(); // public System.Void add_cubeNoteControllerDidInitEvent(System.Action`1<MirroredGameNoteController> value) // Offset: 0x1303064 void add_cubeNoteControllerDidInitEvent(::System::Action_1<::GlobalNamespace::MirroredGameNoteController*>* value); // public System.Void remove_cubeNoteControllerDidInitEvent(System.Action`1<MirroredGameNoteController> value) // Offset: 0x1303108 void remove_cubeNoteControllerDidInitEvent(::System::Action_1<::GlobalNamespace::MirroredGameNoteController*>* value); // public System.Void Mirror(IGameNoteMirrorable noteController) // Offset: 0x130331C void Mirror(::GlobalNamespace::IGameNoteMirrorable* noteController); // public System.Void .ctor() // Offset: 0x1303470 // Implemented from: MirroredNoteController`1 // Base method: System.Void MirroredNoteController_1::.ctor() // Base method: System.Void NoteControllerBase::.ctor() // Base method: System.Void MonoBehaviour::.ctor() // Base method: System.Void Behaviour::.ctor() // Base method: System.Void Component::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static MirroredGameNoteController* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::GlobalNamespace::MirroredGameNoteController::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<MirroredGameNoteController*, creationType>())); } // static private System.Void .cctor() // Offset: 0x13034C0 // Implemented from: UnityEngine.Object // Base method: System.Void Object::.cctor() static void _cctor(); }; // MirroredGameNoteController // WARNING Not writing size check since size may be invalid! } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: GlobalNamespace::MirroredGameNoteController::get_noteMovement // Il2CppName: get_noteMovement template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::GlobalNamespace::NoteMovement* (GlobalNamespace::MirroredGameNoteController::*)()>(&GlobalNamespace::MirroredGameNoteController::get_noteMovement)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MirroredGameNoteController*), "get_noteMovement", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::MirroredGameNoteController::get_noteVisualModifierType // Il2CppName: get_noteVisualModifierType template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::GlobalNamespace::NoteVisualModifierType (GlobalNamespace::MirroredGameNoteController::*)()>(&GlobalNamespace::MirroredGameNoteController::get_noteVisualModifierType)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MirroredGameNoteController*), "get_noteVisualModifierType", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::MirroredGameNoteController::add_cubeNoteControllerDidInitEvent // Il2CppName: add_cubeNoteControllerDidInitEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MirroredGameNoteController::*)(::System::Action_1<::GlobalNamespace::MirroredGameNoteController*>*)>(&GlobalNamespace::MirroredGameNoteController::add_cubeNoteControllerDidInitEvent)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "MirroredGameNoteController")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MirroredGameNoteController*), "add_cubeNoteControllerDidInitEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::MirroredGameNoteController::remove_cubeNoteControllerDidInitEvent // Il2CppName: remove_cubeNoteControllerDidInitEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MirroredGameNoteController::*)(::System::Action_1<::GlobalNamespace::MirroredGameNoteController*>*)>(&GlobalNamespace::MirroredGameNoteController::remove_cubeNoteControllerDidInitEvent)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "MirroredGameNoteController")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MirroredGameNoteController*), "remove_cubeNoteControllerDidInitEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::MirroredGameNoteController::Mirror // Il2CppName: Mirror template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::MirroredGameNoteController::*)(::GlobalNamespace::IGameNoteMirrorable*)>(&GlobalNamespace::MirroredGameNoteController::Mirror)> { static const MethodInfo* get() { static auto* noteController = &::il2cpp_utils::GetClassFromName("", "IGameNoteMirrorable")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MirroredGameNoteController*), "Mirror", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{noteController}); } }; // Writing MetadataGetter for method: GlobalNamespace::MirroredGameNoteController::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: GlobalNamespace::MirroredGameNoteController::_cctor // Il2CppName: .cctor template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&GlobalNamespace::MirroredGameNoteController::_cctor)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::MirroredGameNoteController*), ".cctor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } };
59.736585
352
0.779112
[ "object", "vector" ]
66c097c3f2853b2ba217c07eae12c260aeffa58e
16,217
c++
C++
bindings/old/pyplasma.c++
Krissmedt/imprunko
94171d0d47171cc4b199cd52f5f29385cbff903e
[ "MIT" ]
5
2018-10-26T07:08:16.000Z
2019-05-10T06:47:37.000Z
bindings/old/pyplasma.c++
Krissmedt/imprunko
94171d0d47171cc4b199cd52f5f29385cbff903e
[ "MIT" ]
9
2018-11-09T08:50:48.000Z
2019-06-06T20:11:12.000Z
bindings/old/pyplasma.c++
Krissmedt/imprunko
94171d0d47171cc4b199cd52f5f29385cbff903e
[ "MIT" ]
null
null
null
#include <pybind11/pybind11.h> #include <pybind11/stl.h> namespace py = pybind11; #include "../definitions.h" #include "../tools/mesh.h" //-------------------------------------------------- // Vlasov module //#include "../vlasov/tile.h" #include "../vlasov/grid.h" #include "../em-fields/tile.h" #include "../em-fields/damping_tile.h" #include "../vlasov/amr/mesh.h" //#include "../vlasov/amr/numerics.h" #include "../vlasov/amr/refiner.h" #include "../vlasov/amr/operators.h" #include "../vlasov/amr_momentum_solver.h" #include "../vlasov/amr_spatial_solver.h" #include "../vlasov/amr_analyzator.h" #include "../vlasov/tasker.h" using Realf = float; // typedef toolbox::AdaptiveMesh<Realf, 1> AM1d; typedef toolbox::AdaptiveMesh<Realf, 3> AM3d; typedef toolbox::Adapter<Realf, 3> Adapter3d; /// trampoline class for VlasovVelocitySolver typedef vlasov::MomentumSolver<Realf,3> momsol; // PYBIND preprocessor macro freaks out // of commas so we hide them with typedef class PyMomentumSolver : public momsol { public: using momsol::MomentumSolver; using momsol::solve; void solve_mesh( AM3d& mesh0, AM3d& mesh1, std::array<Realf, 3>& E, std::array<Realf, 3>& B, Realf qm, Realf dt, Realf cfl ) override { PYBIND11_OVERLOAD_PURE( void, momsol, solve_mesh, mesh0, mesh1, E, B, qm, dt, cfl ); } }; /// trampoline class for VlasovSpatialSolver class PySpatialSolver : public vlasov::SpatialSolver<Realf> { public: void solve( vlasov::VlasovTile& tile, vlasov::Grid& grid ) override { PYBIND11_OVERLOAD_PURE( void, vlasov::SpatialSolver<Realf>, solve, tile, grid ); } }; // generator for Mesh bindings with type T and halo H template<typename T, int H> void declare_mesh( py::module &m, const std::string& pyclass_name) { using Class = toolbox::Mesh<T, H>; py::class_<Class>(m, pyclass_name.c_str()) .def(py::init<size_t, size_t, size_t>()) .def_readwrite("Nx", &Class::Nx) .def_readwrite("Ny", &Class::Ny) .def_readwrite("Nz", &Class::Nz) .def("indx", &Class::indx) .def("__getitem__", [](const Class &s, py::tuple indx) { auto i = indx[0].cast<int>(); auto j = indx[1].cast<int>(); auto k = indx[2].cast<int>(); // NOTE: these are out-of-bounds; not inbound checks if (i < -H) throw py::index_error(); if (j < -H) throw py::index_error(); if (k < -H) throw py::index_error(); if (i >= (int)s.Nx+H) throw py::index_error(); if (j >= (int)s.Ny+H) throw py::index_error(); if (k >= (int)s.Nz+H) throw py::index_error(); return s(i,j,k); }) .def("__setitem__", [](Class &s, py::tuple indx, Realf val) { auto i = indx[0].cast<int>(); auto j = indx[1].cast<int>(); auto k = indx[2].cast<int>(); if (i < -H) throw py::index_error(); if (j < -H) throw py::index_error(); if (k < -H) throw py::index_error(); if (i >= (int)s.Nx+H) throw py::index_error(); if (j >= (int)s.Ny+H) throw py::index_error(); if (k >= (int)s.Nz+H) throw py::index_error(); s(i,j,k) = val; }) .def("clear", &Class::clear); } // generator for damped tile for various directions template<int S> void declare_PlasmaTileDamped( py::module& m, const std::string& pyclass_name) { //using Class = fields::PlasmaTileDamped<S>; // does not function properly; maybe not triggering template? //have to use explicit name instead like this py::class_<fields::PlasmaTileDamped<S>, fields::PlasmaTile, std::shared_ptr<fields::PlasmaTileDamped<S>> >(m, pyclass_name.c_str() ) .def(py::init<size_t, size_t, int, size_t, size_t, size_t, size_t, size_t>()) .def_readwrite("ex_ref", &fields::PlasmaTileDamped<S>::ex_ref, py::return_value_policy::reference) .def_readwrite("ey_ref", &fields::PlasmaTileDamped<S>::ey_ref, py::return_value_policy::reference) .def_readwrite("ez_ref", &fields::PlasmaTileDamped<S>::ez_ref, py::return_value_policy::reference) .def_readwrite("bx_ref", &fields::PlasmaTileDamped<S>::bx_ref, py::return_value_policy::reference) .def_readwrite("by_ref", &fields::PlasmaTileDamped<S>::by_ref, py::return_value_policy::reference) .def_readwrite("bz_ref", &fields::PlasmaTileDamped<S>::bz_ref, py::return_value_policy::reference) .def_readwrite("fld1", &fields::PlasmaTileDamped<S>::fld1) .def_readwrite("fld2", &fields::PlasmaTileDamped<S>::fld2) .def("damp_fields", &fields::PlasmaTileDamped<S>::damp_fields); } //-------------------------------------------------- // python bindings for plasma classes & functions PYBIND11_MODULE(pyplasma, m) { // Loading tile bindings from corgi library py::object corgi_tile = (py::object) py::module::import("pycorgi").attr("Tile"); /// General class for handling Maxwell's equations py::class_<fields::PlasmaTile, corgi::Tile, std::shared_ptr<fields::PlasmaTile> >(m, "PlasmaTile") .def(py::init<size_t, size_t, int, size_t, size_t, size_t, size_t, size_t>()) .def_readwrite("dt", &fields::PlasmaTile::dt) .def_readwrite("dx", &fields::PlasmaTile::dx) .def_readwrite("cfl", &fields::PlasmaTile::cfl) .def("cycle_yee", &fields::PlasmaTile::cycle_yee) .def("cycle_current", &fields::PlasmaTile::cycle_current) .def("cycle_current_2d", &fields::PlasmaTile::cycle_current_2d) .def("push_e", &fields::PlasmaTile::push_e) .def("push_half_b", &fields::PlasmaTile::push_half_b) .def("deposit_current", &fields::PlasmaTile::deposit_current) .def("get_yee", &fields::PlasmaTile::get_yee, py::return_value_policy::reference) .def("get_analysis", &fields::PlasmaTile::get_analysis, py::return_value_policy::reference) .def("add_analysis_species", &fields::PlasmaTile::add_analysis_species) .def("update_boundaries", &fields::PlasmaTile::update_boundaries) .def("update_boundaries_2d",&fields::PlasmaTile::update_boundaries_2d) .def("exchange_currents", &fields::PlasmaTile::exchange_currents) .def("exchange_currents_2d",&fields::PlasmaTile::exchange_currents_2d); declare_PlasmaTileDamped<-1>(m, "PlasmaTileDamped_LX"); declare_PlasmaTileDamped<+1>(m, "PlasmaTileDamped_RX"); declare_PlasmaTileDamped<-2>(m, "PlasmaTileDamped_LY"); declare_PlasmaTileDamped<+2>(m, "PlasmaTileDamped_RY"); // Loading grid bindings from corgi library py::object corgi_node = (py::object) py::module::import("pycorgi").attr("Grid"); py::class_<vlasov::Grid>(m, "Grid", corgi_node) .def(py::init<size_t, size_t>()); py::class_<fields::YeeLattice>(m, "YeeLattice") .def(py::init<size_t, size_t, size_t>()) .def_readwrite("ex", &fields::YeeLattice::ex) .def_readwrite("ey", &fields::YeeLattice::ey) .def_readwrite("ez", &fields::YeeLattice::ez) .def_readwrite("bx", &fields::YeeLattice::bx) .def_readwrite("by", &fields::YeeLattice::by) .def_readwrite("bz", &fields::YeeLattice::bz) .def_readwrite("jx", &fields::YeeLattice::jx) .def_readwrite("jy", &fields::YeeLattice::jy) .def_readwrite("jz", &fields::YeeLattice::jz) .def_readwrite("jx1", &fields::YeeLattice::jx1) .def_readwrite("rho", &fields::YeeLattice::rho); py::class_<fields::PlasmaMomentLattice>(m, "PlasmaMomentLattice") .def(py::init<size_t, size_t, size_t>()) .def_readwrite("rho", &fields::PlasmaMomentLattice::rho) .def_readwrite("mgamma", &fields::PlasmaMomentLattice::mgamma) .def_readwrite("Vx", &fields::PlasmaMomentLattice::Vx) .def_readwrite("Vy", &fields::PlasmaMomentLattice::Vy) .def_readwrite("Vz", &fields::PlasmaMomentLattice::Vz) .def_readwrite("Tx", &fields::PlasmaMomentLattice::Tx) .def_readwrite("Ty", &fields::PlasmaMomentLattice::Ty) .def_readwrite("Tz", &fields::PlasmaMomentLattice::Tz) .def_readwrite("ekin", &fields::PlasmaMomentLattice::ekin); py::class_<vlasov::VlasovTile, fields::PlasmaTile, corgi::Tile, std::shared_ptr<vlasov::VlasovTile> >(m, "VlasovTile") .def(py::init<size_t, size_t, int, size_t, size_t, size_t, size_t>()) .def_readwrite("dt", &vlasov::VlasovTile::dt) .def_readwrite("dx", &vlasov::VlasovTile::dx) .def("get_plasma_species", [](vlasov::VlasovTile& tile, size_t i, size_t s) { return tile.steps.get(i).at(s); }, py::return_value_policy::reference) .def("insert_initial_species", [](vlasov::VlasovTile& c, std::vector<vlasov::PlasmaBlock> species){ // push twice to initialize both time steps (current and future) c.steps.push_back(species); c.steps.push_back(species); c.Nspecies = species.size(); }) .def("clip", &vlasov::VlasovTile::clip) .def("cycle", &vlasov::VlasovTile::cycle); py::class_<AM3d >(m, "AdaptiveMesh3D") .def(py::init<>()) .def_readwrite("length", &AM3d::length) .def_readwrite("maximum_refinement_level", &AM3d::maximum_refinement_level) .def_readwrite("top_refinement_level", &AM3d::top_refinement_level) .def("resize", &AM3d::resize) .def("get_cell_from_indices", &AM3d::get_cell_from_indices) .def("get_indices", &AM3d::get_indices) .def("get_refinement_level", &AM3d::get_refinement_level) .def("get_parent_indices", &AM3d::get_parent_indices) .def("get_parent", &AM3d::get_parent) .def("get_maximum_possible_refinement_level",&AM3d::get_maximum_possible_refinement_level) .def("set_maximum_refinement_level", &AM3d::set_maximum_refinement_level) .def("get_level_0_parent_indices", &AM3d::get_level_0_parent_indices) .def("get_level_0_parent", &AM3d::get_level_0_parent) .def("get_children", &AM3d::get_children) .def("get_siblings", &AM3d::get_siblings) .def("get_cells", &AM3d::get_cells) .def("__getitem__", [](const AM3d &s, py::tuple indx) { auto i = indx[0].cast<uint64_t>(); auto j = indx[1].cast<uint64_t>(); auto k = indx[2].cast<uint64_t>(); auto rfl = indx[3].cast<int>(); uint64_t cid = s.get_cell_from_indices({{i,j,k}}, rfl); if(cid == AM3d::error_cid) {throw py::index_error();} return s.get_from_roots(cid); }) .def("__setitem__", [](AM3d &s, py::tuple indx, Realf v) { auto i = indx[0].cast<uint64_t>(); auto j = indx[1].cast<uint64_t>(); auto k = indx[2].cast<uint64_t>(); auto rfl = indx[3].cast<int>(); uint64_t cid = s.get_cell_from_indices({{i,j,k}}, rfl); if(cid == AM3d::error_cid) {throw py::index_error();} s.set(cid, v); }) .def("clip_cells", &AM3d::clip_cells) .def("is_leaf", &AM3d::is_leaf) .def("set_min", &AM3d::set_min) .def("set_max", &AM3d::set_max) .def("get_size", &AM3d::get_size) .def("get_length", &AM3d::get_length) .def("get_center", &AM3d::get_center) .def("get_level_0_cell_length", &AM3d::get_level_0_cell_length); // -------------------------------------------------- // AMR numerics //m.def("deriv", &toolbox::deriv<Realf, 3>); //m.def("grad", &toolbox::grad<Realf, 3>); //m.def("interp_linear", &toolbox::interp_linear<Realf,3>); //m.def("interp_cubic", &toolbox::interp_cubic<Realf,3>); py::class_<Adapter3d>(m, "Adapter") .def(py::init<>()) .def_readwrite("tolerance", &Adapter3d::tolerance) .def_readwrite("cells_to_refine", &Adapter3d::cells_to_refine) .def_readwrite("cells_to_unrefine", &Adapter3d::cells_to_unrefine) .def_readwrite("cells_created", &Adapter3d::cells_created) .def_readwrite("cells_removed", &Adapter3d::cells_removed) .def("set_maximum_data_value", &Adapter3d::set_maximum_data_value) .def("maximum_value", &Adapter3d::maximum_value) .def("maximum_gradient", &Adapter3d::maximum_gradient) .def("check", &Adapter3d::check) .def("refine", &Adapter3d::refine) .def("unrefine", &Adapter3d::unrefine); // general interface for momentum solvers py::class_<vlasov::MomentumSolver<Realf,3>, PyMomentumSolver > vvsol(m, "MomentumSolver"); vvsol .def(py::init<>()) .def("solve", &vlasov::MomentumSolver<Realf,3>::solve) .def("solve_mesh", &vlasov::MomentumSolver<Realf,3>::solve_mesh); // AMR Lagrangian solver py::class_<vlasov::AmrMomentumLagrangianSolver<Realf,3>>(m, "AmrMomentumLagrangianSolver", vvsol) .def(py::init<>()); py::class_<vlasov::GravityAmrMomentumLagrangianSolver<Realf,3>>(m, "GravityAmrMomentumLagrangianSolver", vvsol) .def(py::init<>()); // general interface for spatial solvers py::class_<vlasov::SpatialSolver<Realf>, PySpatialSolver> vssol(m, "SpatialSolver"); vssol .def(py::init<>()) .def("solve", &vlasov::SpatialSolver<Realf>::solve); // AMR Lagrangian solver py::class_<vlasov::AmrSpatialLagrangianSolver<Realf>>(m, "AmrSpatialLagrangianSolver", vssol) .def(py::init<>()); /// Vlasov tile analyzator py::class_<vlasov::Analyzator<Realf> >(m, "Analyzator") .def(py::init<>()); declare_mesh<Realf, 0>(m, std::string("Mesh0") ); declare_mesh<Realf, 1>(m, std::string("Mesh1") ); declare_mesh<Realf, 3>(m, std::string("Mesh3") ); py::class_<vlasov::PlasmaBlock>(m, "PlasmaBlock") .def(py::init<size_t, size_t, size_t>()) .def_readwrite("Nx", &vlasov::PlasmaBlock::Nx) .def_readwrite("Ny", &vlasov::PlasmaBlock::Ny) .def_readwrite("Nz", &vlasov::PlasmaBlock::Nz) .def_readwrite("qm", &vlasov::PlasmaBlock::qm) .def("__getitem__", [](const vlasov::PlasmaBlock &s, py::tuple indx) { auto i = indx[0].cast<int>(); auto j = indx[1].cast<int>(); auto k = indx[2].cast<int>(); if (i < 0) throw py::index_error(); if (j < 0) throw py::index_error(); if (k < 0) throw py::index_error(); if (i > (int)s.Nx) throw py::index_error(); if (j > (int)s.Ny) throw py::index_error(); if (k > (int)s.Nz) throw py::index_error(); return s.block(i,j,k); }, py::return_value_policy::reference) .def("__setitem__", [](vlasov::PlasmaBlock &s, py::tuple indx, AM3d val) { auto i = indx[0].cast<int>(); auto j = indx[1].cast<int>(); auto k = indx[2].cast<int>(); if (i < 0) throw py::index_error(); if (j < 0) throw py::index_error(); if (k < 0) throw py::index_error(); if (i > (int)s.Nx) throw py::index_error(); if (j > (int)s.Ny) throw py::index_error(); if (k > (int)s.Nz) throw py::index_error(); s.block(i,j,k) = val; }) .def("clear", [](vlasov::PlasmaBlock &s){s.block.clear();}); m.def("initial_step_1d", &vlasov::initial_step<1>); m.def("initial_step", &vlasov::initial_step<3>); m.def("step_location", &vlasov::step_location); m.def("step_velocity_1d", &vlasov::step_velocity<1>); m.def("step_velocity", &vlasov::step_velocity<3>); m.def("step_velocity_with_gravity_1d", &vlasov::step_velocity_with_gravity<1>); m.def("analyze", &vlasov::analyze); m.def("write_yee", &vlasov::write_yee); m.def("write_analysis", &vlasov::write_analysis); m.def("write_mesh", &vlasov::write_mesh); }
36.690045
113
0.605229
[ "mesh", "object", "vector" ]
66c4ae50299b88e2b7d63b3410f4e93e0c0a7130
6,170
cxx
C++
src/operator/rhfaomoints.cxx
susilehtola/aquarius
9160e73bd7e3e0d8d97b10d00d9a4860aee709d2
[ "BSD-3-Clause" ]
18
2015-02-11T15:02:39.000Z
2021-09-24T13:10:12.000Z
src/operator/rhfaomoints.cxx
susilehtola/aquarius
9160e73bd7e3e0d8d97b10d00d9a4860aee709d2
[ "BSD-3-Clause" ]
21
2015-06-23T13:32:29.000Z
2022-02-15T20:14:42.000Z
src/operator/rhfaomoints.cxx
susilehtola/aquarius
9160e73bd7e3e0d8d97b10d00d9a4860aee709d2
[ "BSD-3-Clause" ]
8
2016-01-09T23:36:21.000Z
2019-11-19T14:22:34.000Z
#include "rhfaomoints.hpp" #include "time/time.hpp" using namespace aquarius::scf; using namespace aquarius::tensor; using namespace aquarius::input; using namespace aquarius::integrals; using namespace aquarius::task; using namespace aquarius::symmetry; namespace aquarius { namespace op { template <typename T> RHFAOMOIntegrals<T>::RHFAOMOIntegrals(const string& name, Config& config) : Task(name, config) { vector<Requirement> reqs; reqs += Requirement("occspace", "occ"); reqs += Requirement("vrtspace", "vrt"); reqs += Requirement("Ea", "E"); reqs += Requirement("Fa", "F"); reqs += Requirement("eri", "I"); addProduct("mofock", "f", reqs); addProduct("<Ab|Cd>", "VABCD", reqs); addProduct("<Ab|Ci>", "VABCI", reqs); addProduct("<Ab|Ij>", "VABIJ", reqs); addProduct("<Ai|Bj>", "VAIBJ", reqs); addProduct("<Ai|Jb>", "VAIJB", reqs); addProduct("<Ai|Jk>", "VAIJK", reqs); addProduct("<Ij|Kl>", "VIJKL", reqs); } template <typename T> bool RHFAOMOIntegrals<T>::run(TaskDAG& dag, const Arena& arena) { CTF_Timer_epoch ep("RHFAOMOIntegrals"); ep.begin(); const auto& occ = this->template get<MOSpace<T>>("occ"); const auto& vrt = this->template get<MOSpace<T>>("vrt"); const auto& ints = this->template get<ERI>("I"); const SymmetryBlockedTensor<T>& cA_ = vrt.Calpha; const SymmetryBlockedTensor<T>& cI_ = occ.Calpha; int n = ints.group.getNumIrreps(); const vector<int>& N = occ.nao; const vector<int>& nI = occ.nalpha; const vector<int>& nA = vrt.nalpha; auto& E = this->template get<vector<vector<real_type_t<T>>>>("E"); auto& F = this->template get<SymmetryBlockedTensor<T>>("F"); auto& f = this->put( "f", new OneElectronOperator <T>( "f(AB)", occ, vrt, F, F)); auto& VABCD = this->put("VABCD", new SymmetryBlockedTensor<T>("<Ab|Cd>", arena, occ.group, 4, {nA,nA,nA,nA}, {NS,NS,NS,NS}, false)); auto& VABCI = this->put("VABCI", new SymmetryBlockedTensor<T>("<Ab|Ci>", arena, occ.group, 4, {nA,nA,nA,nI}, {NS,NS,NS,NS}, false)); auto& VABIJ = this->put("VABIJ", new SymmetryBlockedTensor<T>("<Ab|Ij>", arena, occ.group, 4, {nA,nA,nI,nI}, {NS,NS,NS,NS}, false)); auto& VAIBJ = this->put("VAIBJ", new SymmetryBlockedTensor<T>("<Ai|Bj>", arena, occ.group, 4, {nA,nI,nA,nI}, {NS,NS,NS,NS}, false)); auto& VAIJB = this->put("VAIJB", new SymmetryBlockedTensor<T>("<Ai|Jb>", arena, occ.group, 4, {nA,nI,nI,nA}, {NS,NS,NS,NS}, false)); auto& VAIJK = this->put("VAIJK", new SymmetryBlockedTensor<T>("<Ai|Jk>", arena, occ.group, 4, {nA,nI,nI,nI}, {NS,NS,NS,NS}, false)); auto& VIJKL = this->put("VIJKL", new SymmetryBlockedTensor<T>("<Ij|Kl>", arena, occ.group, 4, {nI,nI,nI,nI}, {NS,NS,NS,NS}, false)); vector<vector<T>> cA(n), cI(n); /* * Read transformation coefficients */ for (int i = 0;i < n;i++) { vector<int> irreps = {i,i}; cA_.getAllData(irreps, cA[i]); assert(cA[i].size() == N[i]*nA[i]); cI_.getAllData(irreps, cI[i]); assert(cI[i].size() == N[i]*nI[i]); } /* * Resort integrals so that each node has (pq|r_k s_l) where pq * are dense blocks for each sparse rs pair */ pqrs_integrals<T> pqrs(N, ints); pqrs.collect(true); abrs_integrals<T> PQrs(pqrs, true); /* * First quarter-transformation */ abrs_integrals<T> PArs = PQrs.transform(B, nA, cA); abrs_integrals<T> PIrs = PQrs.transform(B, nI, cI); PQrs.free(); /* * Second quarter-transformation */ abrs_integrals<T> ABrs = PArs.transform(A, nA, cA); PArs.free(); abrs_integrals<T> AIrs = PIrs.transform(A, nA, cA); abrs_integrals<T> IJrs = PIrs.transform(A, nI, cI); PIrs.free(); /* * Make <Ab|Cd> */ pqrs_integrals<T> rsAB(ABrs); rsAB.collect(false); abrs_integrals<T> RSAB(rsAB, true); abrs_integrals<T> RDAB = RSAB.transform(B, nA, cA); RSAB.free(); abrs_integrals<T> CDAB = RDAB.transform(A, nA, cA); RDAB.free(); CDAB.transcribe(VABCD, false, false, NONE); CDAB.free(); /* * Make <Ab|Ci> and <Ab|Ij> */ pqrs_integrals<T> rsAI(AIrs); rsAI.collect(false); abrs_integrals<T> RSAI(rsAI, true); abrs_integrals<T> RCAI = RSAI.transform(B, nA, cA); abrs_integrals<T> RJAI = RSAI.transform(B, nI, cI); RSAI.free(); abrs_integrals<T> BCAI = RCAI.transform(A, nA, cA); RCAI.free(); BCAI.transcribe(VABCI, false, false, NONE); BCAI.free(); abrs_integrals<T> BJAI = RJAI.transform(A, nA, cA); RJAI.free(); BJAI.transcribe(VABIJ, false, false, NONE); BJAI.free(); /* * Make <Ij|Kl>, <Ai|Jk>, and <Ai|Bj> */ pqrs_integrals<T> rsIJ(IJrs); rsIJ.collect(false); abrs_integrals<T> RSIJ(rsIJ, true); abrs_integrals<T> RBIJ = RSIJ.transform(B, nA, cA); abrs_integrals<T> RLIJ = RSIJ.transform(B, nI, cI); RSIJ.free(); abrs_integrals<T> ABIJ = RBIJ.transform(A, nA, cA); RBIJ.free(); ABIJ.transcribe(VAIBJ, false, false, NONE); ABIJ.free(); abrs_integrals<T> AKIJ = RLIJ.transform(A, nA, cA); abrs_integrals<T> KLIJ = RLIJ.transform(A, nI, cI); RLIJ.free(); AKIJ.transcribe(VAIJK, false, false, NONE); AKIJ.free(); KLIJ.transcribe(VIJKL, false, false, NONE); KLIJ.free(); /* * Make <Ai|Jb> = <Ab|Ji> */ VAIJB["AiJb"] = VABIJ["AbJi"]; //this->log(arena) << "AbCd: " << setprecision(15) << VABCD.norm(2) << endl; //this->log(arena) << "AbCi: " << setprecision(15) << VABCI.norm(2) << endl; //this->log(arena) << "AbIj: " << setprecision(15) << VABIJ.norm(2) << endl; //this->log(arena) << "AiBj: " << setprecision(15) << VAIBJ.norm(2) << endl; //this->log(arena) << "AiJb: " << setprecision(15) << VAIJB.norm(2) << endl; //this->log(arena) << "AiJk: " << setprecision(15) << VAIJK.norm(2) << endl; //this->log(arena) << "IjKl: " << setprecision(15) << VIJKL.norm(2) << endl; ep.end(); return true; } } } INSTANTIATE_SPECIALIZATIONS(aquarius::op::RHFAOMOIntegrals); REGISTER_TASK(aquarius::op::RHFAOMOIntegrals<double>,"rhfaomoints");
32.994652
136
0.605673
[ "vector", "transform" ]
66c9cd2c5d321d4be33093ed0398b8b01f800cc8
12,342
cpp
C++
libraries/platform/src/platform/backend/MACOSPlatform.cpp
VRcentral/hifi
d6064b46cfd26af4090ba799db55941c7de21b90
[ "Apache-2.0" ]
1
2019-07-08T06:54:01.000Z
2019-07-08T06:54:01.000Z
libraries/platform/src/platform/backend/MACOSPlatform.cpp
VRcentral/VRcentral
d6064b46cfd26af4090ba799db55941c7de21b90
[ "Apache-2.0" ]
null
null
null
libraries/platform/src/platform/backend/MACOSPlatform.cpp
VRcentral/VRcentral
d6064b46cfd26af4090ba799db55941c7de21b90
[ "Apache-2.0" ]
null
null
null
// // Created by Amer Cerkic 05/02/2019 // Copyright 2019 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "MACOSPlatform.h" #include "../PlatformKeys.h" #include <thread> #include <string> #include <CPUIdent.h> #include <QtCore/QtGlobal> #ifdef Q_OS_MAC #include <unistd.h> #include <cpuid.h> #include <sys/sysctl.h> #include <sstream> #include <regex> #include <CoreFoundation/CoreFoundation.h> #include <ApplicationServices/ApplicationServices.h> #include <QSysInfo> #include <QString> #include <OpenGL/OpenGL.h> #endif using namespace platform; void MACOSInstance::enumerateCpus() { json cpu = {}; cpu[keys::cpu::vendor] = CPUIdent::Vendor(); cpu[keys::cpu::model] = CPUIdent::Brand(); cpu[keys::cpu::numCores] = std::thread::hardware_concurrency(); _cpus.push_back(cpu); } void MACOSInstance::enumerateGpusAndDisplays() { #ifdef Q_OS_MAC // ennumerate the displays first std::vector<GLuint> displayMasks; { uint32_t numDisplays = 0; CGError error = CGGetOnlineDisplayList(0, nullptr, &numDisplays); if (numDisplays <= 0 || error != kCGErrorSuccess) { return; } std::vector<CGDirectDisplayID> onlineDisplayIDs(numDisplays, 0); error = CGGetOnlineDisplayList(onlineDisplayIDs.size(), onlineDisplayIDs.data(), &numDisplays); if (error != kCGErrorSuccess) { return; } for (auto displayID : onlineDisplayIDs) { auto displaySize = CGDisplayScreenSize(displayID); const auto MM_TO_IN = 0.0393701f; auto displaySizeWidthInches = displaySize.width * MM_TO_IN; auto displaySizeHeightInches = displaySize.height * MM_TO_IN; auto displayBounds = CGDisplayBounds(displayID); auto displayMaster =CGDisplayIsMain(displayID); auto displayUnit =CGDisplayUnitNumber(displayID); auto displayModel =CGDisplayModelNumber(displayID); auto displayVendor = CGDisplayVendorNumber(displayID); auto displaySerial = CGDisplaySerialNumber(displayID); auto displayMode = CGDisplayCopyDisplayMode(displayID); auto displayModeWidth = CGDisplayModeGetPixelWidth(displayMode); auto displayModeHeight = CGDisplayModeGetPixelHeight(displayMode); auto displayRefreshrate = CGDisplayModeGetRefreshRate(displayMode); auto ppiH = displayModeWidth / displaySizeWidthInches; auto ppiV = displayModeHeight / displaySizeHeightInches; auto ppiHScaled = displayBounds.size.width / displaySizeWidthInches; auto ppiVScaled = displayBounds.size.height / displaySizeHeightInches; auto glmask = CGDisplayIDToOpenGLDisplayMask(displayID); // Metal device ID is the recommended new way but requires objective c // auto displayDevice = CGDirectDisplayCopyCurrentMetalDevice(displayID); CGDisplayModeRelease(displayMode); json display = {}; // Rect region of the desktop in desktop units display[keys::display::boundsLeft] = displayBounds.origin.x; display[keys::display::boundsRight] = displayBounds.origin.x + displayBounds.size.width; display[keys::display::boundsTop] = displayBounds.origin.y; display[keys::display::boundsBottom] = displayBounds.origin.y + displayBounds.size.height; // PPI & resolution display[keys::display::physicalWidth] = displaySizeWidthInches; display[keys::display::physicalHeight] = displaySizeHeightInches; display[keys::display::modeWidth] = displayModeWidth; display[keys::display::modeHeight] = displayModeHeight; //Average the ppiH and V for the simple ppi display[keys::display::ppi] = std::round(0.5f * (ppiH + ppiV)); display[keys::display::ppiDesktop] = std::round(0.5f * (ppiHScaled + ppiVScaled)); // refreshrate display[keys::display::modeRefreshrate] = displayRefreshrate; // Master display ? display[keys::display::isMaster] = (displayMaster ? true : false); // Macos specific display["macos_unit"] = displayUnit; display["macos_vendor"] = displayVendor; display["macos_model"] = displayModel; display["macos_serial"] = displaySerial; display["macos_glmask"] = glmask; displayMasks.push_back(glmask); _displays.push_back(display); } } // Collect Renderer info as exposed by the CGL layers GLuint cglDisplayMask = -1; // Iterate over all of them. CGLRendererInfoObj rendererInfo; GLint rendererInfoCount; CGLError error = CGLQueryRendererInfo(cglDisplayMask, &rendererInfo, &rendererInfoCount); if (rendererInfoCount <= 0 || 0 != error) { return; } // Iterate over all of the renderers and use the figure for the one with the most VRAM, // on the assumption that this is the one that will actually be used. for (GLint i = 0; i < rendererInfoCount; i++) { struct CGLRendererDesc { int rendererID{0}; int deviceVRAM{0}; int accelerated{0}; int displayMask{0}; } desc; CGLDescribeRenderer(rendererInfo, i, kCGLRPRendererID, &desc.rendererID); CGLDescribeRenderer(rendererInfo, i, kCGLRPVideoMemoryMegabytes, &desc.deviceVRAM); CGLDescribeRenderer(rendererInfo, i, kCGLRPDisplayMask, &desc.displayMask); CGLDescribeRenderer(rendererInfo, i, kCGLRPAccelerated, &desc.accelerated); // If this renderer is not hw accelerated then just skip it in the enumeration if (!desc.accelerated) { continue; } // From the rendererID identify the vendorID // https://github.com/apitrace/apitrace/blob/master/retrace/glws_cocoa.mm GLint vendorID = desc.rendererID & kCGLRendererIDMatchingMask & ~0xfff; const GLint VENDOR_ID_SOFTWARE { 0x00020000 }; const GLint VENDOR_ID_AMD { 0x00021000 }; const GLint VENDOR_ID_NVIDIA { 0x00022000 }; const GLint VENDOR_ID_INTEL { 0x00024000 }; const char* vendorName; switch (vendorID) { case VENDOR_ID_SOFTWARE: // Software renderer then skip it (should already have been caught by hwaccelerated test abve continue; break; case VENDOR_ID_AMD: vendorName = keys::gpu::vendor_AMD; break; case VENDOR_ID_NVIDIA: vendorName = keys::gpu::vendor_NVIDIA; break; case VENDOR_ID_INTEL: vendorName = keys::gpu::vendor_Intel; break; default: vendorName = keys::UNKNOWN; break; } //once we reach this point, the renderer is legit // Start defining the gpu json json gpu = {}; gpu[keys::gpu::vendor] = vendorName; gpu[keys::gpu::videoMemory] = desc.deviceVRAM; gpu["macos_rendererID"] = desc.rendererID; gpu["macos_displayMask"] = desc.displayMask; std::vector<int> displayIndices; for (int d = 0; d < (int) displayMasks.size(); d++) { if (desc.displayMask & displayMasks[d]) { displayIndices.push_back(d); _displays[d][keys::display::gpu] = _gpus.size(); } } gpu[keys::gpu::displays] = displayIndices; _gpus.push_back(gpu); } CGLDestroyRendererInfo(rendererInfo); { //get gpu information from the system profiler that we don't know how to retreive otherwise struct ChipsetModelDesc { std::string model; std::string vendor; int deviceID{0}; int videoMemory{0}; }; std::vector<ChipsetModelDesc> chipsetDescs; FILE* stream = popen("system_profiler SPDisplaysDataType | grep -e Chipset -e VRAM -e Vendor -e \"Device ID\"", "r"); std::ostringstream hostStream; while (!feof(stream) && !ferror(stream)) { char buf[128]; int bytesRead = fread(buf, 1, 128, stream); hostStream.write(buf, bytesRead); } std::string gpuArrayDesc = hostStream.str(); // Find the Chipset model first const std::regex chipsetModelToken("(Chipset Model: )(.*)"); std::smatch found; while (std::regex_search(gpuArrayDesc, found, chipsetModelToken)) { ChipsetModelDesc desc; desc.model = found.str(2); // Find the end of the gpu block gpuArrayDesc = found.suffix(); std::string gpuDesc = gpuArrayDesc; const std::regex endGpuToken("Chipset Model: "); if (std::regex_search(gpuArrayDesc, found, endGpuToken)) { gpuDesc = found.prefix(); } // Find the vendor desc.vendor = findGPUVendorInDescription(desc.model); // Find the memory amount in MB const std::regex memoryToken("(VRAM .*: )(.*)"); if (std::regex_search(gpuDesc, found, memoryToken)) { auto memAmountUnit = found.str(2); std::smatch amount; const std::regex memAmountGBToken("(\\d*) GB"); const std::regex memAmountMBToken("(\\d*) MB"); const int GB_TO_MB { 1024 }; if (std::regex_search(memAmountUnit, amount, memAmountGBToken)) { desc.videoMemory = std::stoi(amount.str(1)) * GB_TO_MB; } else if (std::regex_search(memAmountUnit, amount, memAmountMBToken)) { desc.videoMemory = std::stoi(amount.str(1)); } else { desc.videoMemory = std::stoi(memAmountUnit); } } // Find the Device ID const std::regex deviceIDToken("(Device ID: )(.*)"); if (std::regex_search(gpuDesc, found, deviceIDToken)) { desc.deviceID = std::stoi(found.str(2), 0, 16); } chipsetDescs.push_back(desc); } // GO through the detected gpus in order and complete missing information from ChipsetModelDescs // assuming the order is the same and checking that the vendor and memory amount match as a simple check auto numDescs = (int) std::min(chipsetDescs.size(),_gpus.size()); for (int i = 0; i < numDescs; ++i) { const auto& chipset = chipsetDescs[i]; auto& gpu = _gpus[i]; if ( (chipset.vendor.find( gpu[keys::gpu::vendor]) != std::string::npos) && (chipset.videoMemory == gpu[keys::gpu::videoMemory]) ) { gpu[keys::gpu::model] = chipset.model; gpu["macos_deviceID"] = chipset.deviceID; } } } #endif } void MACOSInstance::enumerateMemory() { json ram = {}; #ifdef Q_OS_MAC long pages = sysconf(_SC_PHYS_PAGES); long page_size = sysconf(_SC_PAGE_SIZE); ram[keys::memory::memTotal] = pages * page_size; #endif _memory = ram; } void MACOSInstance::enumerateComputer(){ _computer[keys::computer::OS] = keys::computer::OS_MACOS; _computer[keys::computer::vendor] = keys::computer::vendor_Apple; #ifdef Q_OS_MAC //get system name size_t len=0; sysctlbyname("hw.model",NULL, &len, NULL, 0); char* model = (char *) malloc(sizeof(char)*len+1); sysctlbyname("hw.model", model, &len, NULL,0); _computer[keys::computer::model]=std::string(model); free(model); auto sysInfo = QSysInfo(); _computer[keys::computer::OSVersion] = sysInfo.kernelVersion().toStdString(); #endif }
37.975385
125
0.597715
[ "vector", "model" ]
66cc930865801386dc73f54199e6ae93f4a279bb
770
hpp
C++
ADFSetup.hpp
will-henderson/genetic-programming
ecff399429b5e71bdbefb3107adbd2441fe5bc69
[ "MIT" ]
null
null
null
ADFSetup.hpp
will-henderson/genetic-programming
ecff399429b5e71bdbefb3107adbd2441fe5bc69
[ "MIT" ]
null
null
null
ADFSetup.hpp
will-henderson/genetic-programming
ecff399429b5e71bdbefb3107adbd2441fe5bc69
[ "MIT" ]
null
null
null
// // ADFSetup.hpp // Genetic Programming // // Created by William Henderson on 19/08/2018. // Copyright © 2018 William Henderson. All rights reserved. // #ifndef ADFSetup_hpp #define ADFSetup_hpp #include <stdio.h> #include "Setup.hpp" class ADFSetup: public Setup{ protected: std::vector<void* > childrenVars; public: ADFSetup(std::vector<std::type_index> types_, std::vector<std::vector<double> > probabilityfvr_, std::vector<std::vector<int> > numberofthis_, int maxInitialLength_, std::type_index returntypeofindividuals_, double crossoverRate_); virtual std::vector<void*> setChildrenVars()=0; double fitness(std::vector<Individual>::iterator begin, std::vector<Individual>::iterator end); }; #endif /* ADFSetup_hpp */
25.666667
235
0.716883
[ "vector" ]
202edf7ae9da5c3c373d9eb01416fa5e111ff984
8,083
hpp
C++
include/tao/config/internal/phase1_erase.hpp
mpoeter/config
9a20b1dde685d42190310fa51ecd271e66d90ea0
[ "MIT" ]
1
2020-03-17T20:47:52.000Z
2020-03-17T20:47:52.000Z
include/tao/config/internal/phase1_erase.hpp
mpoeter/config
9a20b1dde685d42190310fa51ecd271e66d90ea0
[ "MIT" ]
null
null
null
include/tao/config/internal/phase1_erase.hpp
mpoeter/config
9a20b1dde685d42190310fa51ecd271e66d90ea0
[ "MIT" ]
null
null
null
// Copyright (c) 2018-2020 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/config/ #ifndef TAO_CONFIG_INTERNAL_PHASE1_ERASE_HPP #define TAO_CONFIG_INTERNAL_PHASE1_ERASE_HPP #include <stdexcept> #include "../key.hpp" #include "entry.hpp" #include "format.hpp" #include "reverse.hpp" namespace tao::config::internal { inline std::size_t phase1_erase( const pegtl::position& pos, concat& l, const key& p, const part& f ); inline std::size_t phase1_erase_name( const pegtl::position& pos, concat& l, const std::string& k ) { std::size_t r = 0; for( auto& i : l.private_entries() ) { if( !i.is_object() ) { throw pegtl::parse_error( format( __FILE__, __LINE__, "attempt to index non-object with string", { { "string", k }, { "non-object", { &i.position(), i.type() } } } ), pos ); } r += i.get_object().erase( k ); } return r; } inline std::size_t phase1_erase_index( const pegtl::position& pos, concat& l, std::size_t n ) { for( auto& i : l.private_entries() ) { if( !i.is_array() ) { throw pegtl::parse_error( format( __FILE__, __LINE__, "attempt to index non-array with integer", { { "integer", n }, { "non-array", { &i.position(), i.type() } } } ), pos ); } auto& a = i.get_array(); const auto s = a.size(); if( n < s ) { a.erase( n ); return 1; } n -= s; } throw pegtl::parse_error( format( __FILE__, __LINE__, "array index out of range", { { "integer", n }, { "array", { &l.p } } } ), pos ); } inline std::size_t phase1_erase_star( const pegtl::position& pos, concat& l ) { std::size_t r = 0; for( auto& i : l.private_entries() ) { if( i.is_array() ) { r += i.get_array().size(); i.get_array().clear(); continue; } if( i.is_object() ) { r += i.get_object().size(); i.get_object().clear(); continue; } throw pegtl::parse_error( format( __FILE__, __LINE__, "attempt to delete everything from non-container", { { "non-container", { &i.position(), i.type() } } } ), pos ); } return r; } inline std::size_t phase1_erase_minus( const pegtl::position& pos, concat& l ) { for( auto& i : reverse( l.private_entries() ) ) { if( !i.is_array() ) { throw pegtl::parse_error( format( __FILE__, __LINE__, "attempt to delete last element from non-array", { { "non-array", { &i.position(), i.type() } } } ), pos ); } auto& a = i.get_array(); if( !a.empty() ) { a.pop_back(); return 1; } } throw pegtl::parse_error( format( __FILE__, __LINE__, "array has no last element to delete in", { { "array", { &l.p } } } ), pos ); } inline std::size_t phase1_erase( const pegtl::position& pos, concat& l, const part& f ) { switch( f.type() ) { case part::name: return phase1_erase_name( pos, l, f.get_name() ); case part::index: return phase1_erase_index( pos, l, f.get_index() ); case part::star: return phase1_erase_star( pos, l ); case part::minus: return phase1_erase_minus( pos, l ); } assert( false ); } inline std::size_t phase1_erase_name( const pegtl::position& pos, concat& l, const std::string& k, const key& p, const part& f ) { std::size_t r = 0; for( auto& i : reverse( l.private_entries() ) ) { if( !i.is_object() ) { // TODO: Should references be silently ignored (continue)? throw pegtl::parse_error( format( __FILE__, __LINE__, "attempt to index non-object with string", { { "string", k }, { "non-object", { &i.position(), i.type() } } } ), pos ); } if( auto* j = i.get_object().find( k ) ) { r += phase1_erase( pos, j->second, p, f ); } } return r; } inline std::size_t phase1_erase_index( const pegtl::position& pos, concat& l, std::size_t n, const key& p, const part& f ) { for( auto& i : l.private_entries() ) { if( !i.is_array() ) { throw pegtl::parse_error( format( __FILE__, __LINE__, "attempt to index non-array with integer", { { "integer", n }, { "non-array", { &i.position(), i.type() } } } ), pos ); } const auto s = i.get_array().size(); if( n < s ) { auto& j = i.get_array()[ n ]; return phase1_erase( pos, j, p, f ); } n -= s; } throw pegtl::parse_error( format( __FILE__, __LINE__, "array index out of range", { { "integer", n }, { "array", { &l.p } } } ), pos ); } inline std::size_t phase1_erase_star( const pegtl::position& pos, concat& l, const key& p, const part& f ) { std::size_t r = 0; for( auto& i : l.private_entries() ) { if( i.is_array() ) { for( auto& j : i.get_array().private_list() ) { r += phase1_erase( pos, j, p, f ); } continue; } if( i.is_object() ) { for( auto& j : i.get_object().private_map() ) { r += phase1_erase( pos, j.second, p, f ); } continue; } throw pegtl::parse_error( format( __FILE__, __LINE__, "attempt to delete in non-container", { { "non-container", { &i.position(), i.type() } } } ), pos ); } return r; } inline std::size_t phase1_erase_minus( const pegtl::position& pos, concat& l, const key& p, const part& f ) { for( auto& i : reverse( l.private_entries() ) ) { if( !i.is_array() ) { throw pegtl::parse_error( format( __FILE__, __LINE__, "attempt to delete last element from non-array", { { "non-array", { &i.position(), i.type() } } } ), pos ); } if( !i.get_array().empty() ) { return phase1_erase( pos, i.get_array().back(), p, f ); } } throw pegtl::parse_error( format( __FILE__, __LINE__, "array has no last element to delete", { { "array", { &l.p } } } ), pos ); } inline std::size_t phase1_erase( const pegtl::position& pos, concat& l, const part& t, const key& p, const part& f ) { switch( t.type() ) { case part::name: return phase1_erase_name( pos, l, t.get_name(), p, f ); case part::index: return phase1_erase_index( pos, l, t.get_index(), p, f ); case part::star: return phase1_erase_star( pos, l, p, f ); case part::minus: return phase1_erase_minus( pos, l, p, f ); } assert( false ); } inline std::size_t phase1_erase( const pegtl::position& pos, concat& l, const key& p, const part& f ) { if( p.empty() ) { return phase1_erase( pos, l, f ); } else { return phase1_erase( pos, l, p.front(), pop_front( p ), f ); } } inline std::size_t phase1_erase( const pegtl::position& pos, entry_object& o, const std::string& k, const key& p ) { if( p.empty() ) { return o.erase( k ); } if( auto* i = o.find( k ) ) { return phase1_erase( pos, i->second, pop_back( p ), p.back() ); } return 0; } inline std::size_t phase1_erase( const pegtl::position& pos, entry& e, const part& t, const key& p ) { switch( t.type() ) { case part::name: return phase1_erase( pos, e.get_object(), t.get_name(), p ); case part::index: assert( false ); case part::star: assert( false ); case part::minus: assert( false ); } assert( false ); } inline std::size_t phase1_erase( const pegtl::position& pos, entry& e, const key& p ) { assert( !p.empty() ); return phase1_erase( pos, e, p.front(), pop_front( p ) ); } } // namespace tao::config::internal #endif
35.143478
185
0.53495
[ "object" ]
20358350d573f63a61318c45622da17c3e61fbd8
7,664
cpp
C++
groups/bsl/bslmf/bslmf_util.t.cpp
apaprocki/bde
ba252cb776f92fae082d5d422aa2852a9be46849
[ "Apache-2.0" ]
1
2021-04-28T13:51:30.000Z
2021-04-28T13:51:30.000Z
groups/bsl/bslmf/bslmf_util.t.cpp
apaprocki/bde
ba252cb776f92fae082d5d422aa2852a9be46849
[ "Apache-2.0" ]
null
null
null
groups/bsl/bslmf/bslmf_util.t.cpp
apaprocki/bde
ba252cb776f92fae082d5d422aa2852a9be46849
[ "Apache-2.0" ]
1
2019-06-26T13:28:48.000Z
2019-06-26T13:28:48.000Z
// bslmf_util.t.cpp -*-C++-*- #include <bslmf_util.h> #include <bsls_objectbuffer.h> #include <bsls_bsltestutil.h> #include <stdio.h> #include <stdlib.h> #include <new> // required to support use of "placement new" using namespace BloombergLP; //============================================================================= // TEST PLAN //----------------------------------------------------------------------------- // 'bslmf::Util' is a utility class, where each function will be tested in a // separate test case. Any significant test machinery will be tested before // any function whose test case relies upon it. //----------------------------------------------------------------------------- // CLASS METHODS // [ ] template <class T> forward(T&& value) //----------------------------------------------------------------------------- // [1] BREATHING TEST // [ ] USAGE EXAMPLE //----------------------------------------------------------------------------- // ============================================================================ // STANDARD BSL ASSERT TEST FUNCTION // ---------------------------------------------------------------------------- namespace { int testStatus = 0; void aSsErT(bool condition, const char *message, int line) { if (condition) { printf("Error " __FILE__ "(%d): %s (failed)\n", line, message); if (0 <= testStatus && testStatus <= 100) { ++testStatus; } } } } // close unnamed namespace // ============================================================================ // STANDARD BSL TEST DRIVER MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- #define ASSERT BSLS_BSLTESTUTIL_ASSERT #define ASSERTV BSLS_BSLTESTUTIL_ASSERTV #define LOOP_ASSERT BSLS_BSLTESTUTIL_LOOP_ASSERT #define LOOP0_ASSERT BSLS_BSLTESTUTIL_LOOP0_ASSERT #define LOOP1_ASSERT BSLS_BSLTESTUTIL_LOOP1_ASSERT #define LOOP2_ASSERT BSLS_BSLTESTUTIL_LOOP2_ASSERT #define LOOP3_ASSERT BSLS_BSLTESTUTIL_LOOP3_ASSERT #define LOOP4_ASSERT BSLS_BSLTESTUTIL_LOOP4_ASSERT #define LOOP5_ASSERT BSLS_BSLTESTUTIL_LOOP5_ASSERT #define LOOP6_ASSERT BSLS_BSLTESTUTIL_LOOP6_ASSERT #define Q BSLS_BSLTESTUTIL_Q // Quote identifier literally. #define P BSLS_BSLTESTUTIL_P // Print identifier and value. #define P_ BSLS_BSLTESTUTIL_P_ // P(X) without '\n'. #define T_ BSLS_BSLTESTUTIL_T_ // Print a tab (w/o newline). #define L_ BSLS_BSLTESTUTIL_L_ // current Line number //============================================================================= // GLOBAL TYPEDEFS/CONSTANTS FOR TESTING //----------------------------------------------------------------------------- //============================================================================= // GLOBAL HELPER FUNCTIONS FOR TESTING //----------------------------------------------------------------------------- #ifndef BSLS_COMPILERFEATURES_SUPPORT_RVALUE_REFERENCES # define BSLMF_UTIL_FORWARD_REF(T) const T& # define BSLMF_UTIL_FORWARD(T,V) \ ::BloombergLP::bslmf::Util::forward(V) #else # define BSLMF_UTIL_FORWARD_REF(T) T&& # define BSLMF_UTIL_FORWARD(T,V) \ ::BloombergLP::bsls::Util::forward<T>(V) #endif struct CUtil { #if !BSLS_COMPILERFEATURES_SIMULATE_CPP11_FEATURES // $var-args=2 template <class TARGET, class ...Args> static void construct(TARGET *address, Args&&...args) { new (address) TARGET(bslmf::Util::forward<Args>(args)...); } #else template <class TARGET, class Arg1> static void construct(TARGET *address, BSLMF_UTIL_FORWARD_REF(Arg1) a1) { new (address) TARGET(BSLMF_UTIL_FORWARD(Arg1,a1)); } template <class TARGET, class Arg1, class Arg2> static void construct(TARGET *address, BSLMF_UTIL_FORWARD_REF(Arg1) a1, BSLMF_UTIL_FORWARD_REF(Arg2) a2) { new (address) TARGET(BSLMF_UTIL_FORWARD(Arg1,a1), BSLMF_UTIL_FORWARD(Arg2,a2)); } #endif }; class Obj { bool d_copied; bool d_moved; public: Obj() : d_copied(false) , d_moved(false) { } Obj(const Obj&) : d_copied(true) , d_moved(false) { } Obj(bslmf::MovableRef<Obj>) : d_copied(false) , d_moved(true) { } bool copied() const { return d_copied; } bool moved() const { return d_moved; } }; //============================================================================= // MAIN PROGRAM //----------------------------------------------------------------------------- int main(int argc, char *argv[]) { int test = argc > 1 ? atoi(argv[1]) : 0; bool verbose = argc > 2; bool veryVerbose = argc > 3; bool veryVeryVerbose = argc > 4; (void)veryVerbose; (void)veryVeryVerbose; printf("TEST " __FILE__ " CASE %d\n", test); switch (test) { case 0: // Zero is always the leading case. case 1: { // -------------------------------------------------------------------- // BREATHING TEST // This test exercises basic functionality but *tests* *nothing*. // // Concerns: //: 1 That the functions exist with the documented signatures. //: 2 That the basic functionality works as documented. // // Plan: //: 1 Exercise each function in turn and devise an elementary test //: sequence to ensure that the basic functionality is as documented. // // Testing: // BREATHING TEST // -------------------------------------------------------------------- if (verbose) printf("\nBREATHING TEST" "\n==============\n"); Obj mA; const Obj& A = mA; ASSERT(false == A.copied()); ASSERT(false == A.moved()); bsls::ObjectBuffer<Obj> buf; Obj& mX = buf.object(); const Obj& X = mX; CUtil::construct(buf.address(), A); ASSERT( true == X.copied()); ASSERT(false == X.moved()); CUtil::construct(buf.address(), mA); ASSERT( true == X.copied()); ASSERT(false == X.moved()); CUtil::construct(buf.address(), bslmf::MovableRefUtil::move(mA)); ASSERT(false == X.copied()); ASSERT( true == X.moved()); ASSERT(sizeof(bool) == sizeof(bslmf::Util::declval<Obj>().copied())); } break; default: { fprintf(stderr, "WARNING: CASE `%d' NOT FOUND.\n", test); testStatus = -1; } } if (testStatus > 0) { fprintf(stderr, "Error, non-zero test status = %d.\n", testStatus); } return testStatus; } // ---------------------------------------------------------------------------- // Copyright 2016 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
33.911504
79
0.496477
[ "object" ]
2039a4e776144e7daa57b5bf261eedd79ba827a4
9,068
cpp
C++
src/chess_board.cpp
mathiasgredal/NanoGUI-Chess
6bf044a80ada607f9792610b97acfed4ddee242e
[ "MIT" ]
1
2020-02-29T18:00:31.000Z
2020-02-29T18:00:31.000Z
src/chess_board.cpp
mathiasgredal/NanoGUI-Chess
6bf044a80ada607f9792610b97acfed4ddee242e
[ "MIT" ]
null
null
null
src/chess_board.cpp
mathiasgredal/NanoGUI-Chess
6bf044a80ada607f9792610b97acfed4ddee242e
[ "MIT" ]
null
null
null
#include <utility> #include "chess_pieces.h" #include "movegenerator.h" #include <array> Board::Board(array<Chess_Piece, 64> pieces) { chess_pieces = std::move(pieces); } int Board::GetBoardScore() { float sum = 0; for (auto& piece : chess_pieces) { sum += (piece.color != currentPlayer) ? ChessPieceValue(piece.chessType) : ChessPieceValue(piece.chessType) * -1; } //cout << "Board Evaluation: " << sum << endl; return sum; } vector<Chess_Piece> Board::GetPiecesOfColor(Chess_Color color) { vector<Chess_Piece> pieces(18); for (auto& piece : chess_pieces) { if (piece.color == color) pieces.push_back(piece); } pieces.shrink_to_fit(); return pieces; } array<Chess_Piece, 64> Board::Default_Board() { array<Chess_Piece, 64> default_pieces; default_pieces[GetChessPieceIndex(0, 0)] = Chess_Piece(0, 0, Chess_Color::Black, Chess_Type::Rook); default_pieces[GetChessPieceIndex(0, 1)] = Chess_Piece(0, 1, Chess_Color::Black, Chess_Type::Knight); default_pieces[GetChessPieceIndex(0, 2)] = Chess_Piece(0, 2, Chess_Color::Black, Chess_Type::Bishop); default_pieces[GetChessPieceIndex(0, 3)] = Chess_Piece(0, 3, Chess_Color::Black, Chess_Type::Queen); default_pieces[GetChessPieceIndex(0, 4)] = Chess_Piece(0, 4, Chess_Color::Black, Chess_Type::King); default_pieces[GetChessPieceIndex(0, 5)] = Chess_Piece(0, 5, Chess_Color::Black, Chess_Type::Bishop); default_pieces[GetChessPieceIndex(0, 6)] = Chess_Piece(0, 6, Chess_Color::Black, Chess_Type::Knight); default_pieces[GetChessPieceIndex(0, 7)] = Chess_Piece(0, 7, Chess_Color::Black, Chess_Type::Rook); for (int i = 0; i < 8; i++) default_pieces[GetChessPieceIndex(1, i)] = Chess_Piece(1, i, Chess_Color::Black, Chess_Type::Pawn); default_pieces[GetChessPieceIndex(7, 0)] = Chess_Piece(7, 0, Chess_Color::White, Chess_Type::Rook); default_pieces[GetChessPieceIndex(7, 1)] = Chess_Piece(7, 1, Chess_Color::White, Chess_Type::Knight); default_pieces[GetChessPieceIndex(7, 2)] = Chess_Piece(7, 2, Chess_Color::White, Chess_Type::Bishop); default_pieces[GetChessPieceIndex(7, 3)] = Chess_Piece(7, 3, Chess_Color::White, Chess_Type::Queen); default_pieces[GetChessPieceIndex(7, 4)] = Chess_Piece(7, 4, Chess_Color::White, Chess_Type::King); default_pieces[GetChessPieceIndex(7, 5)] = Chess_Piece(7, 5, Chess_Color::White, Chess_Type::Bishop); default_pieces[GetChessPieceIndex(7, 6)] = Chess_Piece(7, 6, Chess_Color::White, Chess_Type::Knight); default_pieces[GetChessPieceIndex(7, 7)] = Chess_Piece(7, 7, Chess_Color::White, Chess_Type::Rook); for (int i = 0; i < 8; i++) default_pieces[GetChessPieceIndex(6, i)] = Chess_Piece(6, i, Chess_Color::White, Chess_Type::Pawn); return default_pieces; } Chess_Piece Board::Get_Piece(int row, int col) { if (row < 8 && col < 8) return chess_pieces[GetChessPieceIndex(row, col)]; else return Chess_Piece(row, col, Chess_Color::Empty, Chess_Type::EMPTY); } void Board::Move_Piece(Move mv) { //bool castlingMove = (Get_Piece(mv.r1, mv.c1)->chess_type == Chess_Type::King && abs(mv.c1 - mv.c2) > 1); // TODO: This method is doing very dangerous things, can potentially crash the program //chess_pieces[mv.r1][mv.c1]->RegisterMove(mv); lastMove = mv; chess_pieces[GetChessPieceIndex(mv.r2, mv.c2)] = chess_pieces[GetChessPieceIndex(mv.r1, mv.c1)]; chess_pieces[GetChessPieceIndex(mv.r1, mv.c1)] = Chess_Piece(mv.r1, mv.c1, Chess_Color::Empty, Chess_Type::EMPTY); chess_pieces[GetChessPieceIndex(mv.r2, mv.c2)].row = mv.r2; chess_pieces[GetChessPieceIndex(mv.r2, mv.c2)].col = mv.c2; chess_pieces[GetChessPieceIndex(mv.r2, mv.c2)].initialMove = false; if (chess_pieces[GetChessPieceIndex(mv.r2, mv.c2)].chessType == Chess_Type::Pawn) { if (chess_pieces[GetChessPieceIndex(mv.r2, mv.c2)].color == Chess_Color::Black && mv.r2 == 7) { chess_pieces[GetChessPieceIndex(mv.r2, mv.c2)].chessType = Chess_Type::Queen; } if (chess_pieces[GetChessPieceIndex(mv.r2, mv.c2)].color == Chess_Color::White && mv.r2 == 0) { chess_pieces[GetChessPieceIndex(mv.r2, mv.c2)].chessType = Chess_Type::Queen; } } /* if (castlingMove && mv.c1 < mv.c2) // King side castling { chess_pieces[mv.r1][7]->RegisterMove(mv); chess_pieces[mv.r1][mv.c2 - 1] = chess_pieces[mv.r1][7]; chess_pieces[mv.r1][7] = nullptr; } if (castlingMove && mv.c1 > mv.c2) { // Queen side castling chess_pieces[mv.r1][0]->RegisterMove(mv); chess_pieces[mv.r1][mv.c2 + 1] = chess_pieces[mv.r1][0]; chess_pieces[mv.r1][0] = nullptr; }*/ // Switch rounds if (currentPlayer == Chess_Color::White) currentPlayer = Chess_Color::Black; else currentPlayer = Chess_Color::White; } vector<Move> PieceValidMoves(Chess_Piece piece, Board& board) { switch (piece.chessType) { case King: return MoveGenerator::KingMoves(board, piece); case Queen: return MoveGenerator::QueenMoves(board, piece); case Bishop: return MoveGenerator::BishopMoves(board, piece); case Knight: return MoveGenerator::KnightMoves(board, piece); case Rook: return MoveGenerator::RookMoves(board, piece); case Pawn: return MoveGenerator::PawnMoves(board, piece); case EMPTY: return {}; } } vector<Move> Board::ValidMoves(int row, int col) { // Get Piece Chess_Piece selectedPiece = Get_Piece(row, col); // Check if the piece is of the correct color if (selectedPiece.color != this->currentPlayer) return {}; Chess_Color opponentPlayer = (this->currentPlayer == Chess_Color::White) ? Chess_Color::Black : Chess_Color::White; vector<Move> validmoves = PieceValidMoves(selectedPiece, *this); // remove invalid moves auto it = validmoves.begin(); while (it != validmoves.end()) { bool invalidMove = false; // Get Piece Chess_Piece destinationPiece = Get_Piece(it->r2, it->c2); // We are not allowed to attack a king if (destinationPiece.chessType == Chess_Type::King) invalidMove = true; // We are not allowed to make a move which exposes the king Board newboard = *this; newboard.Move_Piece(*it); for (auto& piece : newboard.GetPiecesOfColor(opponentPlayer)) { for (auto& possibleMove : PieceValidMoves(piece, newboard)) { if (newboard.Get_Piece(possibleMove.r2, possibleMove.c2).chessType == Chess_Type::King) invalidMove = true; } } if (invalidMove) it = validmoves.erase(it); else ++it; } return validmoves; } bool Board::ValidMove(Move usermove) { vector<Move> validmoves = ValidMoves(usermove.r1, usermove.c1); // TODO: Use STL functions // if(std::find(validmoves.begin(), validmoves.end(), mv) != validmoves.end()) // return true; // else // return false; for (Move& validmove : validmoves) { //validmove.Print_Move(); if (validmove == usermove) return true; } return false; } Chess_Piece Board::GetKing(Chess_Color color) { // Calculate if player is in check vector<Chess_Piece> all_pieces = GetPiecesOfColor(currentPlayer); for (auto& piece : all_pieces) { if (piece.chessType == Chess_Type::King) { return piece; } } return Chess_Piece(0, 0, Chess_Color::Empty, Chess_Type::EMPTY); } bool Board::IsAttacked(int row, int col, Chess_Color color) { if (currentPlayer == Chess_Color::Empty) return false; Chess_Color enemyColor = (color == Chess_Color::White) ? Chess_Color::Black : Chess_Color::White; // Loop all enemy moves, if any of them reach the king, then he is in check vector<Chess_Piece> enemyPieces = GetPiecesOfColor(enemyColor); for (auto& enemypiece : enemyPieces) { if (enemypiece.chessType != Chess_Type::King) { vector<Move> enemyMoves = PieceValidMoves(enemypiece, *this); for (auto& enemyMove : enemyMoves) { if (enemyMove.r2 == row && enemyMove.c2 == col) { return true; } } } } return false; } bool Board::IsCheck() { Chess_Piece kingPiece = GetKing(currentPlayer); return IsAttacked(kingPiece.row, kingPiece.col, currentPlayer); } bool Board::IsCheckMate() { bool isCheckMate = true; // Can only be checkmate if king is in check if (!IsCheck()) { isCheckMate = false; return isCheckMate; } // Here we just check whether we can do any moves. for (int i = 0; i < chess_pieces.size(); i++) { const int c = i % 8; const int r = (i - c) / 8; if (ValidMoves(r, c).size() != 0) isCheckMate = false; } return isCheckMate; }
33.461255
121
0.646118
[ "vector" ]
204312ad37d93f21bfc09af5cc76b1533986adc0
1,796
cpp
C++
srm/756/A.cpp
freedomDR/coding
310a68077de93ef445ccd2929e90ba9c22a9b8eb
[ "MIT" ]
null
null
null
srm/756/A.cpp
freedomDR/coding
310a68077de93ef445ccd2929e90ba9c22a9b8eb
[ "MIT" ]
null
null
null
srm/756/A.cpp
freedomDR/coding
310a68077de93ef445ccd2929e90ba9c22a9b8eb
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; class ClinderellaGirls { public: //O(nlogn) int count(vector<int> t, vector<int> s) { vector<pair<int, int>> ts(t.size(), make_pair(0, 0)); for(int i = 0; i < t.size(); i++) { ts[i].first = t[i]; ts[i].second = s[i]; } sort(ts.begin(), ts.end(), [](auto ts1, auto ts2){return ts1.first < ts2.first || (ts1.first == ts2.first && ts1.second < ts2.second);}); int ans = 0; vector<int> left(ts.size(), INT_MIN), right(ts.size(), INT_MIN); int maxx = INT_MIN, maxx1 = INT_MIN; for(int i = t.size()-2; i >= 0; i--) { maxx = max(maxx, ts[i+1].second); maxx1 = max(maxx1, ts[i+1].first); right[i] = maxx; left[i] = maxx1; } left[t.size()-1] = ts[t.size()-1].first; right[t.size()-1] = ts[t.size()-1].second; for(int i = 0; i < t.size(); i++) { if(left[i] == ts[i].first || right[i] <= ts[i].second) ans++; } return ans; } //o(n^2) int count(vector<int> t, vector<int> s, int temp) { int ans = 0; for(int i = 0; i < t.size(); i++) { for(int j = 0; j < t.size(); j++) { if(i == j) continue; if(t[j] > t[i] && s[j] > s[i]) { ans++; break; } } } return ans; } }; int main() { ClinderellaGirls* app = new ClinderellaGirls(); vector<int> t{46}, s{81}; cout<<app->count(t, s, 1)<<endl; delete app; return 0; }
26.80597
150
0.400891
[ "vector" ]
204730b781d5c17f506f43029c35617589a7bd97
18,114
cpp
C++
src/Loss.cpp
edeforas/BeeDNN
8c5277b7af56b8044c2ddc85d26fa5fd540facad
[ "MIT" ]
14
2019-11-13T05:14:40.000Z
2022-03-13T20:51:22.000Z
src/Loss.cpp
edeforas/BeeDNN
48de7aa5e7ea6a0b2f1d7b713f0a48c4b8b6a7e2
[ "MIT" ]
66
2019-04-20T09:32:53.000Z
2021-12-25T10:35:11.000Z
src/Loss.cpp
edeforas/BeeDNN
8c5277b7af56b8044c2ddc85d26fa5fd540facad
[ "MIT" ]
2
2020-05-03T18:53:08.000Z
2020-06-19T16:36:24.000Z
/* Copyright (c) 2019, Etienne de Foras and the respective contributors All rights reserved. Use of this source code is governed by a MIT-style license that can be found in the LICENSE.txt file. */ #include "Loss.h" #include <cassert> #include <cmath> //////////////////////////////////////////////////////////////// Loss::Loss() { _bClassBalancing = false; } //////////////////////////////////////////////////////////////// Loss::~Loss() { } ////////////////////////////////////////////////////////////////////////////// void Loss::set_class_balancing(const MatrixFloat& mWeight) { _mWeightBalancing = mWeight; _bClassBalancing = _mWeightBalancing.size() != 0; } ////////////////////////////////////////////////////////////////////////////// void Loss::balance_with_weight(const MatrixFloat& mTruth, MatrixFloat& mGradient) const { assert(_bClassBalancing); for (int i = 0; i < mGradient.rows(); i++) { assert(mTruth(i)>=0); assert(mTruth(i)<_mWeightBalancing.size()); mGradient.row(i) *= _mWeightBalancing((int)mTruth(i)); } } ////////////////////////////////////////////////////////////////////////////// class LossMeanSquaredError : public Loss { public: string name() const override { return "MeanSquaredError"; } void compute(const MatrixFloat& mPredicted, const MatrixFloat& mTruth, MatrixFloat& mLoss) const override { assert(mTruth.cols() == mPredicted.cols()); assert(mTruth.rows() == mPredicted.rows()); mLoss= colWiseMean( (mPredicted - mTruth).cwiseAbs2() ); if (_bClassBalancing) balance_with_weight(mTruth, mLoss); } void compute_gradient(const MatrixFloat& mPredicted,const MatrixFloat& mTruth, MatrixFloat& mGradientLoss) const override { assert(mTruth.cols() == mPredicted.cols()); assert(mTruth.rows() == mPredicted.rows()); mGradientLoss = (mPredicted - mTruth)/ (float)mPredicted.cols(); if (_bClassBalancing) balance_with_weight(mTruth, mGradientLoss); } }; ////////////////////////////////////////////////////////////////////////////// //Huber Loss from https://en.wikipedia.org/wiki/Huber_loss #define HUBER_SIGMA (1.f) class LossHuber : public Loss { public: string name() const override { return "Huber"; } void compute(const MatrixFloat& mPredicted, const MatrixFloat& mTruth, MatrixFloat& mLoss) const override { assert(mTruth.cols() == mPredicted.cols()); assert(mTruth.rows() == mPredicted.rows()); MatrixFloat m = (mPredicted - mTruth).cwiseAbs(); for (Index i = 0; i < m.size(); i++) { if (m(i) < HUBER_SIGMA) m(i) = 0.5f*(m(i) * m(i)); else m(i) = HUBER_SIGMA * m(i) - 0.5f*HUBER_SIGMA * HUBER_SIGMA; } mLoss= colWiseMean(m); if (_bClassBalancing) balance_with_weight(mTruth, mLoss); } void compute_gradient(const MatrixFloat& mPredicted, const MatrixFloat& mTruth, MatrixFloat& mGradientLoss) const override { assert(mTruth.cols() == mPredicted.cols()); assert(mTruth.rows() == mPredicted.rows()); mGradientLoss = mPredicted- mTruth; for (Index i = 0; i < mGradientLoss.size(); i++) { if (mGradientLoss(i) > HUBER_SIGMA) mGradientLoss(i) = HUBER_SIGMA; else if (mGradientLoss(i) < -HUBER_SIGMA) mGradientLoss(i) = -HUBER_SIGMA; } if (_bClassBalancing) balance_with_weight(mTruth, mGradientLoss); } }; ////////////////////////////////////////////////////////////////////////////// //PseudoHuber Loss from https://en.wikipedia.org/wiki/Huber_loss #define PSEUDOHUBER_SIGMA (1.f) #define PSEUDOHUBER_SIGMA_2 (PSEUDOHUBER_SIGMA*PSEUDOHUBER_SIGMA) #define PSEUDOHUBER_INV_SIGMA_2 (1.f/PSEUDOHUBER_SIGMA_2) class LossPseudoHuber : public Loss { public: string name() const override { return "PseudoHuber"; } void compute(const MatrixFloat& mPredicted, const MatrixFloat& mTruth, MatrixFloat& mLoss) const override { assert(mTruth.cols() == mPredicted.cols()); assert(mTruth.rows() == mPredicted.rows()); MatrixFloat m = (mPredicted - mTruth).cwiseAbs2(); for (Index i = 0; i < m.size(); i++) m(i) = PSEUDOHUBER_SIGMA_2 * (sqrtf(m(i)*PSEUDOHUBER_INV_SIGMA_2 + 1.f) - 1.f); mLoss = colWiseMean(m); if (_bClassBalancing) balance_with_weight(mTruth, mLoss); } void compute_gradient(const MatrixFloat& mPredicted, const MatrixFloat& mTruth, MatrixFloat& mGradientLoss) const override { assert(mTruth.cols() == mPredicted.cols()); assert(mTruth.rows() == mPredicted.rows()); mGradientLoss = mPredicted - mTruth; for (Index i = 0; i < mGradientLoss.size(); i++) { float x = mGradientLoss(i); mGradientLoss(i) = x / sqrtf(x*x*PSEUDOHUBER_INV_SIGMA_2 + 1.f); } if (_bClassBalancing) balance_with_weight(mTruth, mGradientLoss); } }; ////////////////////////////////////////////////////////////////////////////// class LossMeanCubicError : public Loss { public: string name() const override { return "MeanCubicError"; } void compute(const MatrixFloat& mPredicted, const MatrixFloat& mTruth, MatrixFloat& mLoss) const override { assert(mTruth.cols() == mPredicted.cols()); assert(mTruth.rows() == mPredicted.rows()); mLoss = colWiseMean((mPredicted - mTruth).array().cube().cwiseAbs()); if (_bClassBalancing) balance_with_weight(mTruth, mLoss); } void compute_gradient(const MatrixFloat& mPredicted, const MatrixFloat& mTruth, MatrixFloat& mGradientLoss) const override { assert(mTruth.cols() == mPredicted.cols()); assert(mTruth.rows() == mPredicted.rows()); mGradientLoss = mPredicted - mTruth; //todo vectorize for (Index i = 0; i < mGradientLoss.size(); i++) { float x = mGradientLoss(i); mGradientLoss(i) = 3.f*x*x*(x > 0.f ? 1.f : -1.f); } if (_bClassBalancing) balance_with_weight(mTruth, mGradientLoss); } }; ////////////////////////////////////////////////////////////////////////////// class LossMeanAbsoluteError : public Loss { public: string name() const override { return "MeanAbsoluteError"; } void compute(const MatrixFloat& mPredicted, const MatrixFloat& mTruth, MatrixFloat& mLoss) const override { assert(mTruth.cols() == mPredicted.cols()); assert(mTruth.rows() == mPredicted.rows()); mLoss = colWiseMean((mPredicted - mTruth).cwiseAbs()); if (_bClassBalancing) balance_with_weight(mTruth, mLoss); } void compute_gradient(const MatrixFloat& mPredicted,const MatrixFloat& mTruth, MatrixFloat& mGradientLoss) const override { assert(mTruth.cols() == mPredicted.cols()); assert(mTruth.rows() == mPredicted.rows()); mGradientLoss=(mPredicted - mTruth).array().cwiseSign(); if (_bClassBalancing) balance_with_weight(mTruth, mGradientLoss); } }; ////////////////////////////////////////////////////////////////////////////// // same as MeanSquareError but do not divide by nbSamples // see https://isaacchanghau.github.io/post/loss_functions/ class LossL2 : public Loss { public: string name() const override { return "L2"; } void compute(const MatrixFloat& mPredicted, const MatrixFloat& mTruth, MatrixFloat& mLoss) const override { assert(mTruth.cols() == mPredicted.cols()); assert(mTruth.rows() == mPredicted.rows()); mLoss = colWiseSum((mPredicted - mTruth).cwiseAbs2()); if (_bClassBalancing) balance_with_weight(mTruth, mLoss); } void compute_gradient(const MatrixFloat& mPredicted, const MatrixFloat& mTruth, MatrixFloat& mGradientLoss) const override { assert(mTruth.cols() == mPredicted.cols()); assert(mTruth.rows() == mPredicted.rows()); mGradientLoss = (mPredicted - mTruth); if (_bClassBalancing) balance_with_weight(mTruth, mGradientLoss); } }; ////////////////////////////////////////////////////////////////////////////// // same as MeanAbsoluteError but do not divide by nbSamples // see https://isaacchanghau.github.io/post/loss_functions/ class LossL1 : public Loss { public: string name() const override { return "L1"; } void compute(const MatrixFloat& mPredicted, const MatrixFloat& mTruth, MatrixFloat& mLoss) const override { assert(mTruth.cols() == mPredicted.cols()); assert(mTruth.rows() == mPredicted.rows()); mLoss = colWiseSum((mPredicted - mTruth).cwiseAbs()); if (_bClassBalancing) balance_with_weight(mTruth, mLoss); } void compute_gradient(const MatrixFloat& mPredicted, const MatrixFloat& mTruth, MatrixFloat& mGradientLoss) const override { assert(mTruth.cols() == mPredicted.cols()); assert(mTruth.rows() == mPredicted.rows()); mGradientLoss = (mPredicted - mTruth).cwiseSign() / (float)mPredicted.cols(); if (_bClassBalancing) balance_with_weight(mTruth, mGradientLoss); } }; ////////////////////////////////////////////////////////////////////////////// // same as MeanCubicError but do not divide by nbSamples class LossL3 : public Loss { public: string name() const override { return "L3"; } void compute(const MatrixFloat& mPredicted, const MatrixFloat& mTruth, MatrixFloat& mLoss) const override { assert(mTruth.cols() == mPredicted.cols()); assert(mTruth.rows() == mPredicted.rows()); mLoss = colWiseSum((mPredicted - mTruth).array().cube().cwiseAbs()); if (_bClassBalancing) balance_with_weight(mTruth, mLoss); } void compute_gradient(const MatrixFloat& mPredicted, const MatrixFloat& mTruth, MatrixFloat& mGradientLoss) const override { assert(mTruth.cols() == mPredicted.cols()); assert(mTruth.rows() == mPredicted.rows()); mGradientLoss = mPredicted - mTruth; //todo vectorize for (Index i = 0; i < mGradientLoss.size(); i++) { float x = mGradientLoss(i); mGradientLoss(i) = 3.f*x*x*(x > 0.f ? 1.f:-1.f); } if (_bClassBalancing) balance_with_weight(mTruth, mGradientLoss); } }; ////////////////////////////////////////////////////////////////////////////// class LossLogCosh : public Loss { public: string name() const override { return "LogCosh"; } void compute(const MatrixFloat& mPredicted, const MatrixFloat& mTruth, MatrixFloat& mLoss) const override { assert(mTruth.cols() == mPredicted.cols()); assert(mTruth.rows() == mPredicted.rows()); mLoss = colWiseMean((mPredicted - mTruth).array().cosh().log()); if (_bClassBalancing) balance_with_weight(mTruth, mLoss); } void compute_gradient(const MatrixFloat& mPredicted, const MatrixFloat& mTruth, MatrixFloat& mGradientLoss) const override { assert(mTruth.cols() == mPredicted.cols()); assert(mTruth.rows() == mPredicted.rows()); mGradientLoss = (mPredicted - mTruth).array().tanh(); if (_bClassBalancing) balance_with_weight(mTruth, mGradientLoss); } }; ////////////////////////////////////////////////////////////////////////////// // from https://gombru.github.io/2018/05/23/cross_entropy_loss // and https://sefiks.com/2017/12/17/a-gentle-introduction-to-cross-entropy-loss-function/ // and https://www.tensorflow.org/api_docs/python/tf/keras/losses/CategoricalCrossentropy // no class balancing class LossCategoricalCrossEntropy : public Loss { public: string name() const override { return "CategoricalCrossEntropy"; //truth is one hot encoded } void compute(const MatrixFloat& mPredicted, const MatrixFloat& mTruth, MatrixFloat& mLoss) const override { assert(mTruth.cols() == mPredicted.cols()); assert(mTruth.rows() == mPredicted.rows()); Index r = mPredicted.rows(); Index c = mPredicted.cols(); mLoss.resize(r, 1); for (Index j = 0; j < r; j++) { float fLoss = 0.f; for (int i = 0; i < c; i++) { float t = mTruth(j, i); float p = mPredicted(j, i); float lossTmp = -(t*logf(max(p, 1.e-8f))); fLoss += lossTmp; } mLoss(j, 0) = fLoss; } } void compute_gradient(const MatrixFloat& mPredicted, const MatrixFloat& mTruth, MatrixFloat& mGradientLoss) const override { assert(mTruth.cols() == mPredicted.cols()); assert(mTruth.rows() == mPredicted.rows()); mGradientLoss.resize(mTruth.rows(), mTruth.cols()); for (int i = 0; i < mTruth.size(); i++) { float p = mPredicted(i); float t = mTruth(i); mGradientLoss(i) = -(t / max(p, 1.e-8f))+ (1.f - t)/(max(1.f - p,1.e-8f)); } } }; ////////////////////////////////////////////////////////////////////////////// // and https://www.tensorflow.org/api_docs/python/tf/keras/losses/SparseCategoricalCrossentropy // no class balancing class LossSparseCategoricalCrossEntropy : public Loss { public: string name() const override { return "SparseCategoricalCrossEntropy"; //truth is index encoded } void compute(const MatrixFloat& mPredicted, const MatrixFloat& mTruth, MatrixFloat& mLoss) const override { assert(mTruth.cols() == 1); assert(mTruth.rows() == mPredicted.rows()); Index r = mPredicted.rows(); mLoss.resize(r, 1); for (int i = 0; i< mPredicted.rows(); i++) mLoss(i) =-logf(max(mPredicted(i,(int)mTruth(i)), 1.e-8f)); //computing only when truth=1. } void compute_gradient(const MatrixFloat& mPredicted, const MatrixFloat& mTruth, MatrixFloat& mGradientLoss) const override { //todo optimize all assert(mTruth.cols() == 1); assert(mTruth.rows() == mPredicted.rows()); mGradientLoss=mPredicted; for (int r = 0; r < mGradientLoss.rows(); r++) { int t = (int)mTruth(r); for (int c = 0; c < mGradientLoss.cols(); c++) { float p = mGradientLoss(r, c); if(t==c) mGradientLoss(r,c) = -(1.f / max(p, 1.e-8f)); else mGradientLoss(r,c) = 1.f/(max(1.f - p, 1.e-8f)); } } } }; ////////////////////////////////////////////////////////////////////////////// // from https://math.stackexchange.com/questions/2503428/derivative-of-binary-cross-entropy-why-are-my-signs-not-right // and https://ml-cheatsheet.readthedocs.io/en/latest/loss_functions.html // no class balancing class LossBinaryCrossEntropy : public Loss { public: string name() const override { return "BinaryCrossEntropy"; } void compute(const MatrixFloat& mPredicted, const MatrixFloat& mTruth, MatrixFloat& mLoss) const override { assert(mTruth.cols() == 1); assert(mTruth.cols() == mPredicted.cols()); assert(mTruth.rows() == mPredicted.rows()); Index r= mPredicted.rows(); mLoss.resize(r, 1); for (int i = 0; i < r; i++) { float p = mPredicted(i); float t = mTruth(i); mLoss(i)=-(t*logf(max(p, 1.e-8f)) + (1.f - t)*logf(max(1.f - p,1.e-8f ))); } } void compute_gradient(const MatrixFloat& mPredicted, const MatrixFloat& mTruth, MatrixFloat& mGradientLoss) const override { assert(mTruth.cols() == mPredicted.cols()); assert(mTruth.rows() == mPredicted.rows()); mGradientLoss.resize(mTruth.rows(), mTruth.cols()); for (int i = 0; i < mTruth.size(); i++) { float p = mPredicted(i); float t = mTruth(i); mGradientLoss(i)= -(t / max(p,1.e-8f) - (1.f - t) / max((1.f - p),1.e-8f)); } } }; ////////////////////////////////////////////////////////////////////////////// Loss* create_loss(const string& sLoss) { if(sLoss =="MeanSquaredError") return new LossMeanSquaredError; if(sLoss =="MeanAbsoluteError") return new LossMeanAbsoluteError; if (sLoss == "MeanCubicError") return new LossMeanCubicError; if(sLoss == "L2") return new LossL2; if(sLoss == "L1") return new LossL1; if (sLoss == "L3") return new LossL3; if(sLoss == "LogCosh") return new LossLogCosh; if (sLoss == "Huber") return new LossHuber; if (sLoss == "PseudoHuber") return new LossPseudoHuber; if(sLoss =="CategoricalCrossEntropy") return new LossCategoricalCrossEntropy; if(sLoss =="SparseCategoricalCrossEntropy") return new LossSparseCategoricalCrossEntropy; if(sLoss == "BinaryCrossEntropy") return new LossBinaryCrossEntropy; return nullptr; } ////////////////////////////////////////////////////////////////////////////// void list_loss_available(vector<string>& vsLoss) { vsLoss.clear(); vsLoss.push_back("MeanSquaredError"); vsLoss.push_back("MeanAbsoluteError"); vsLoss.push_back("MeanCubicError"); vsLoss.push_back("L2"); vsLoss.push_back("L1"); vsLoss.push_back("L3"); vsLoss.push_back("Huber"); vsLoss.push_back("PseudoHuber"); vsLoss.push_back("LogCosh"); vsLoss.push_back("CategoricalCrossEntropy"); vsLoss.push_back("SparseCategoricalCrossEntropy"); vsLoss.push_back("BinaryCrossEntropy"); } //////////////////////////////////////////////////////////////////////////////
32.117021
126
0.566468
[ "vector" ]
204a5ba16f0ed27a5c5223830c7ff7d26a133817
12,768
cpp
C++
oadrive/src/oadrive_missioncontrol/ManeuverList.cpp
fzi-forschungszentrum-informatik/aadc2016
b00149f84f91be07d98f3be0ac79daebb732025b
[ "BSD-2-Clause" ]
11
2016-04-30T14:55:20.000Z
2020-06-04T21:13:31.000Z
oadrive/src/oadrive_missioncontrol/ManeuverList.cpp
fzi-forschungszentrum-informatik/aadc2016
b00149f84f91be07d98f3be0ac79daebb732025b
[ "BSD-2-Clause" ]
null
null
null
oadrive/src/oadrive_missioncontrol/ManeuverList.cpp
fzi-forschungszentrum-informatik/aadc2016
b00149f84f91be07d98f3be0ac79daebb732025b
[ "BSD-2-Clause" ]
8
2016-04-30T14:58:18.000Z
2019-12-27T10:37:53.000Z
// this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*- // -- BEGIN LICENSE BLOCK ---------------------------------------------- // Copyright (c) 2016, FZI Forschungszentrum Informatik // 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. // // 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. // -- END LICENSE BLOCK ------------------------------------------------ //---------------------------------------------------------------------- /*!\file * * \author Vitali Kaiser <vitali.kaiser@live.de> * \date 2016-01-08 * */ //---------------------------------------------------------------------- #include "ManeuverList.h" #include <boost/foreach.hpp> #include <boost/lexical_cast.hpp> #include <exception> #include <algorithm> #include <iostream> #include "mcLogging.h" #include "ManeuverListLive.h" using icl_core::logging::endl; using icl_core::logging::flush; using namespace boost; namespace oadrive{ namespace missioncontrol{ map<string, enumManeuver> ManeuverList::maneuverMap = map_list_of ("left", MANEUVER_LEFT) ("right", MANEUVER_RIGHT) ("straight", MANEUVER_STRAIGHT) ("parallel_parking", MANEUVER_PARKING_PARALLEL) ("cross_parking", MANEUVER_PARKING_CROSS) ("pull_out_left", MANEUVER_PULLOUT_LEFT) ("pull_out_right", MANEUVER_PULLOUT_RIGHT); ManeuverList::ManeuverList() { this->currentManeuverPos = 0; this->currentSectorPos = 0; this->currentDaManeuver = 0; dummy = true; } boost::shared_ptr<IManeuverList> ManeuverList::getDummy() { boost::shared_ptr<ManeuverList> result(new ManeuverList()); //Always add a last "Finished Sector" shared_ptr<AADC_Sector> finSec(new AADC_Sector(INT32_MAX)); shared_ptr<AADC_Maneuver> finMan(new AADC_Maneuver(INT32_MAX, MANEUVER_FINISHED,finSec)); result->daManeuver.push_back(finMan); finSec->maneuvers.push_back(finMan); result->sectors.push_back(finSec); return static_pointer_cast<IManeuverList>(result); } boost::shared_ptr<IManeuverList> ManeuverList::parse(string input) { return parse(input,0); } //! parses the maneuver list from an xml string. Throws an exception if input string can not be parsed. boost::shared_ptr<IManeuverList> ManeuverList::parse(string input, IMC2Man* mc) { using boost::lexical_cast; //for parsing string to int using boost::bad_lexical_cast; // Create an empty property tree object using boost::property_tree::ptree; ptree pt; // Read the XML config string into the property tree. Catch any exception stringstream ss; ss << input; read_xml(ss, pt); boost::shared_ptr<ManeuverList> result(new ManeuverList()); result->mc = mc; try { result->desc = pt.get_child("AADC-Maneuver-List.<xmlattr>.description").data(); } catch (std::exception& e) { LOGGING_WARNING( mcLogger, "WARNING: description not defined!" << e.what() << endl ); } BOOST_FOREACH(const ptree::value_type & v, pt.get_child("AADC-Maneuver-List")){ if(v.first == "AADC-Sector") { int id = 0; // Try to get id... works even with out but gives a warning try { id = lexical_cast<int>(v.second.get_child("<xmlattr>.id").data()); } catch(const bad_lexical_cast &) { LOGGING_WARNING( mcLogger, "WARNING: Could not parse sector id!" << endl ); } catch(std::exception& e) { LOGGING_WARNING( mcLogger, "WARNING: Could not parse sector id!" << e.what() << endl ); } shared_ptr<AADC_Sector> newSector(new AADC_Sector(id)); BOOST_FOREACH(const ptree::value_type & vv, v.second){ if(vv.first == "AADC-Maneuver") { int id = 0; try { id = lexical_cast<int>(vv.second.get_child("<xmlattr>.id").data()); } catch(const bad_lexical_cast &) { LOGGING_WARNING( mcLogger, "WARNING: Could not parse maneuver id!" << endl ); } catch(std::exception& e) { LOGGING_WARNING( mcLogger, "WARNING: Could not parse maneuver id!" << endl << e.what() << endl ); } string action = ""; action = vv.second.get_child("<xmlattr>.action").data(); std::transform(action.begin(), action.end(), action.begin(), ::tolower); //transform to lower case for better comparison //TODO: vertrauen wir dem File oder auch hier Fehlerbehebung? //FUN mode for the Kür if(action == "fun") { LOGGING_INFO( mcLogger, "Found 'fun' command in maneuver list. Starting live mode!" << endl ); // Create a live maneuver list which listenes to a broker for live commands: boost::shared_ptr<ManeuverListLive> temp(new ManeuverListLive()); temp->mc = mc; // Return the maneuver list: return static_pointer_cast<IManeuverList>(temp); } shared_ptr<AADC_Maneuver> newManeuver(new AADC_Maneuver(id, maneuverMap[action], newSector)); newSector->maneuvers.push_back(newManeuver); result->daManeuver.push_back(newManeuver); } } result->sectors.push_back(newSector); } } //Always add a last "Finished Sector" shared_ptr<AADC_Sector> finSec(new AADC_Sector(INT32_MAX)); shared_ptr<AADC_Maneuver> finMan(new AADC_Maneuver(INT32_MAX, MANEUVER_FINISHED,finSec)); result->daManeuver.push_back(finMan); finSec->maneuvers.push_back(finMan); result->sectors.push_back(finSec); result->dummy = false; LOGGING_INFO(mcLogger, "ManList parsed: daManSize: " << result->daManeuver.size() << "sectorSize: " << result->sectors.size()<<endl); return static_pointer_cast<IManeuverList>(result); } bool ManeuverList::isDummy() { return dummy; } enumManeuver ManeuverList::getAbsoluteManeuver(int shift) { if(shift == 0) { //shortcut return daManeuver[0]->action; } int temp = shift; const int size = daManeuver.size() -1; temp = max(0,temp); temp = min(temp, size); return daManeuver[temp]->action; } enumManeuver ManeuverList::getCurrentManeuver() { return getRelativeManeuver(0); } unsigned int ManeuverList::getCurrentSector() { return currentSectorPos; } enumManeuver ManeuverList::getNextManeuver() { return getRelativeManeuver(1); } enumManeuver ManeuverList::getPreviosManeuver() { return getRelativeManeuver(-1); } void ManeuverList::increase() { LOGGING_INFO(mcLogger, "ManeuverList::increase()"<<endl); if(sectors.size() == 0 || daManeuver.size() == 0) { LOGGING_ERROR(mcLogger, "ManeuverList size is somehow zero... should never happen!"<<endl); return; } if(currentSectorPos >= sectors.size() || currentDaManeuver >= daManeuver.size()) { LOGGING_ERROR(mcLogger, "ManeuverList size is corrupt. Why?"<<endl); return; } boost::shared_ptr<AADC_Sector> currentSector = sectors[currentSectorPos]; unsigned int manSize = currentSector->maneuvers.size(); if(currentManeuverPos +1 < manSize) { currentManeuverPos++; } else { if((currentSectorPos +1) < sectors.size()) { //increase sector currentSectorPos++; currentManeuverPos = 0; } } if(currentDaManeuver +1 < daManeuver.size()) { currentDaManeuver++; } if(!mc) { LOGGING_INFO(mcLogger, "ManList: no access to mission control and cannot communicate with jury" <<endl); return; } if(currentDaManeuver == daManeuver.size() -1) { //parcour finished //mc->eventParcourFinished(); //TODO check of setJuryState in Statemachine is needed! mc->setJuryState(stateCar_COMPLETE, daManeuver[currentDaManeuver-1]->id); //one less because the last one is finished LOGGING_INFO(mcLogger, "ManList: Parcour finished. Sending complete with manID: " << daManeuver[currentDaManeuver]->id <<endl); } else { LOGGING_INFO(mcLogger, "ManList: Send Running with manID: " << daManeuver[currentDaManeuver]->id <<endl); mc->setJuryState(stateCar_RUNNING, daManeuver[currentDaManeuver]->id); } // if(daManeuver[currentDaManeuver]->action == MANEUVER_PARKING_PARALLEL || daManeuver[currentDaManeuver]->action == MANEUVER_PARKING_CROSS) { //parcour finished // mc->eventSearchParking(); // LOGGING_INFO(mcLogger, "ManList: search for a parking lot! "<<endl); // } //LOGGING_INFO(mcLogger, " Current Maneuver: " << currentDaManeuver <<endl); } enumManeuver ManeuverList::getRelativeManeuver(int shift) { if(shift == 0) { //shortcut return daManeuver[currentDaManeuver]->action; } int temp = currentDaManeuver + shift; const int size = daManeuver.size() -1; temp = max(0,temp); temp = min(temp, size); return daManeuver[temp]->action; } string ManeuverList::getDescription() { return desc; } bool ManeuverList::setManeuverId(int manID) { LOGGING_INFO(mcLogger, " [ManList] try to set current maneuver to id: "<< manID <<endl); unsigned int max = daManeuver.size(); unsigned int i = 0; unsigned int iRM = 0; unsigned int iRS = 0; while(i < max) { if(daManeuver[i]->id == manID) { LOGGING_INFO(mcLogger, " [ManList] setting current maneuver to currentDaManeuver: "<< i << " currentManeuverPos: " << iRM << " currentSectorPos: " << iRS <<endl); currentDaManeuver = i; currentManeuverPos = iRM; currentSectorPos = iRS; return true; } i++; if(iRM < sectors[iRS]->maneuvers.size()) { iRM++; } else { iRS++; iRM = 0; } } if(manID == 0) { LOGGING_INFO(mcLogger, "[ManList] could not find manID 0, but we set current maneuver to the first in the list." <<endl); currentDaManeuver = 0; currentManeuverPos = 0; currentSectorPos = 0; } LOGGING_INFO(mcLogger, "[ManList] unable to set to manID: " <<manID <<endl); return false; } std::string ManeuverList::toString() { std::stringstream sstr; sstr << std::endl << "ManeuverList: " << std::endl; // Iterate over all sectors: for( size_t secID = 0; secID < sectors.size(); secID ++ ) { boost::shared_ptr<AADC_Sector> sec = sectors[secID]; sstr << "Sector: " << sec->id << std::endl; // Iterate over all maneuvers in the sector: for( size_t manID = 0; manID < sec->maneuvers.size(); manID ++ ) { boost::shared_ptr<AADC_Maneuver> man = sec->maneuvers[manID]; // get maneuver name as string: sstr << "\t" << man->id << ": " << man->action << " " << maneuverAsString( man->action ); // Mark the current action: if( currentSectorPos == secID && currentManeuverPos == manID ) sstr << "\t<---"; sstr << std::endl; } } return sstr.str(); } std::string ManeuverList::maneuverAsString( enumManeuver man ) { switch( man ) { case MANEUVER_LEFT: return "left"; case MANEUVER_RIGHT: return "right"; case MANEUVER_STRAIGHT: return "straight"; case MANEUVER_PARKING_PARALLEL: return "parking_parallel"; case MANEUVER_PARKING_CROSS: return "parking_cross"; case MANEUVER_PULLOUT_LEFT: return "pullout_left"; case MANEUVER_PULLOUT_RIGHT: return "pullout_right"; case MANEUVER_FINISHED: return "finished"; } return ""; } bool ManeuverList::isFinished() { if( getCurrentManeuver() == MANEUVER_FINISHED ) return true; // Just in case, do other checks: if( currentSectorPos >= sectors.size() ) // past last sector? return true; if( currentSectorPos == sectors.size() - 1 ) // last sector? if( currentManeuverPos == sectors.back()->maneuvers.size() - 1 ) // last maneuver? return true; return false; } } // namespace } // namespace
31.141463
322
0.663847
[ "object", "transform" ]
205a2ccccd02d9596fab09d4320ea113f64c3808
12,233
cc
C++
src/parser.cc
ktsitsi/sigmod_contest_2018
de9b1b94a4cf718b95305db0c5011f87f838adfd
[ "MIT" ]
6
2018-04-09T12:03:06.000Z
2019-11-25T06:41:51.000Z
src/parser.cc
ktsitsi/sigmod_contest_2018
de9b1b94a4cf718b95305db0c5011f87f838adfd
[ "MIT" ]
null
null
null
src/parser.cc
ktsitsi/sigmod_contest_2018
de9b1b94a4cf718b95305db0c5011f87f838adfd
[ "MIT" ]
null
null
null
#include <cassert> #include <iostream> #include <utility> #include <map> #include <sstream> #include "include/parser.h" //--------------------------------------------------------------------------- using namespace std; //--------------------------------------------------------------------------- const char *SelectInfo::delimiterSQL=", "; const char *PredicateInfo::delimiterSQL=" and "; const char *FilterInfo::delimiterSQL=" and "; static void splitString(string& line,vector<unsigned>& result,const char delimiter) // Split a line into numbers { stringstream ss(line); string token; while (getline(ss,token,delimiter)) { result.push_back(stoul(token)); } } //--------------------------------------------------------------------------- static void splitString(string& line,vector<string>& result,const char delimiter) // Parse a line into strings { stringstream ss(line); string token; while (getline(ss,token,delimiter)) { result.push_back(token); } } //--------------------------------------------------------------------------- static void splitPredicates(string& line,vector<string>& result) // Split a line into predicate strings { // Determine predicate type for (auto cT : comparisonTypes) { if (line.find(cT)!=string::npos) { splitString(line,result,cT); break; } } } //--------------------------------------------------------------------------- void QueryInfo::parseRelationIds(string& rawRelations) // Parse a string of relation ids { splitString(rawRelations,relationIds,' '); } //--------------------------------------------------------------------------- static SelectInfo parseRelColPair(string& raw) { vector<unsigned> ids; splitString(raw,ids,'.'); return SelectInfo(0,ids[0],ids[1]); } //--------------------------------------------------------------------------- inline static bool isConstant(string& raw) { return raw.find('.')==string::npos; } //--------------------------------------------------------------------------- void QueryInfo::parsePredicate(string& rawPredicate) // Parse a single predicate: join "r1Id.col1Id=r2Id.col2Id" or "r1Id.col1Id=constant" filter { vector<string> relCols; splitPredicates(rawPredicate,relCols); //assert(relCols.size()==2); //assert(!isConstant(relCols[0])&&"left side of a predicate is always a SelectInfo"); auto leftSelect=parseRelColPair(relCols[0]); if (isConstant(relCols[1])) { uint64_t constant=stoul(relCols[1]); char compType=rawPredicate[relCols[0].size()]; filters.emplace_back(leftSelect,constant,FilterInfo::Comparison(compType)); } else { predicates.emplace_back(leftSelect,parseRelColPair(relCols[1])); } } //--------------------------------------------------------------------------- void QueryInfo::parsePredicates(string& text) // Parse predicates { vector<string> predicateStrings; splitString(text,predicateStrings,'&'); for (auto& rawPredicate : predicateStrings) { parsePredicate(rawPredicate); } } //--------------------------------------------------------------------------- void QueryInfo::parseSelections(string& rawSelections) // Parse selections { vector<string> selectionStrings; splitString(rawSelections,selectionStrings,' '); for (auto& rawSelect : selectionStrings) { selections.emplace_back(parseRelColPair(rawSelect)); } } //--------------------------------------------------------------------------- static void resolveIds(vector<unsigned>& relationIds,SelectInfo& selectInfo) // Resolve relation id { selectInfo.relId=relationIds[selectInfo.binding]; } //--------------------------------------------------------------------------- void QueryInfo::resolveRelationIds() // Resolve relation ids { // Selections for (auto& sInfo : selections) { resolveIds(relationIds,sInfo); } // Predicates for (auto& pInfo : predicates) { resolveIds(relationIds,pInfo.left); resolveIds(relationIds,pInfo.right); } // Filters for (auto& fInfo : filters) { resolveIds(relationIds,fInfo.filterColumn); } } //--------------------------------------------------------------------------- void QueryInfo::parseQuery(string& rawQuery) // Parse query [RELATIONS]|[PREDICATES]|[SELECTS] { clear(); vector<string> queryParts; splitString(rawQuery,queryParts,'|'); assert(queryParts.size()==3); parseRelationIds(queryParts[0]); parsePredicates(queryParts[1]); parseSelections(queryParts[2]); resolveRelationIds(); } //--------------------------------------------------------------------------- void QueryInfo::clear() // Reset query info { relationIds.clear(); predicates.clear(); filters.clear(); selections.clear(); } //--------------------------------------------------------------------------- static string wrapRelationName(uint64_t id) // Wraps relation id into quotes to be a SQL compliant string { return "\""+to_string(id)+"\""; } //--------------------------------------------------------------------------- string SelectInfo::dumpSQL(bool addSUM) // Appends a selection info to the stream { auto innerPart=wrapRelationName(binding)+".c"+to_string(colId); return addSUM?"SUM("+innerPart+")":innerPart; } //--------------------------------------------------------------------------- string SelectInfo::dumpText() // Dump text format { return to_string(binding)+"."+to_string(colId); } //--------------------------------------------------------------------------- string FilterInfo::dumpText() // Dump text format { return filterColumn.dumpText()+static_cast<char>(comparison)+to_string(constant); } //--------------------------------------------------------------------------- string FilterInfo::dumpSQL() // Dump text format { return filterColumn.dumpSQL()+static_cast<char>(comparison)+to_string(constant); } //--------------------------------------------------------------------------- string PredicateInfo::dumpText() // Dump text format { return left.dumpText()+'='+right.dumpText(); } //--------------------------------------------------------------------------- string PredicateInfo::dumpSQL() // Dump text format { return left.dumpSQL()+'='+right.dumpSQL(); } //--------------------------------------------------------------------------- template <typename T> static void dumpPart(stringstream& ss,vector<T> elements) { for (unsigned i=0;i<elements.size();++i) { ss << elements[i].dumpText(); if (i<elements.size()-1) ss << T::delimiter; } } //--------------------------------------------------------------------------- template <typename T> static void dumpPartSQL(stringstream& ss,vector<T> elements) { for (unsigned i=0;i<elements.size();++i) { ss << elements[i].dumpSQL(); if (i<elements.size()-1) ss << T::delimiterSQL; } } //--------------------------------------------------------------------------- string QueryInfo::dumpText() // Dump text format { stringstream text; // Relations for (unsigned i=0;i<relationIds.size();++i) { text << relationIds[i]; if (i<relationIds.size()-1) text << " "; } text << "|"; dumpPart(text,predicates); if (predicates.size()&&filters.size()) text << PredicateInfo::delimiter; dumpPart(text,filters); text << "|"; dumpPart(text,selections); return text.str(); } //--------------------------------------------------------------------------- string QueryInfo::dumpSQL() // Dump SQL { stringstream sql; sql << "SELECT "; for (unsigned i=0;i<selections.size();++i) { sql << selections[i].dumpSQL(true); if (i<selections.size()-1) sql << ", "; } sql << " FROM "; for (unsigned i=0;i<relationIds.size();++i) { sql << "r" << relationIds[i] << " " << wrapRelationName(i); if (i<relationIds.size()-1) sql << ", "; } sql << " WHERE "; dumpPartSQL(sql,predicates); if (predicates.size()&&filters.size()) sql << " and "; dumpPartSQL(sql,filters); sql << ";"; return sql.str(); } //--------------------------------------------------------------------------- QueryInfo::QueryInfo(string rawQuery) { parseQuery(rawQuery); } //--------------------------------------------------------------------------- void QueryInfo::rewriteQuery(QueryInfo& source) { relationIds = source.relationIds; /// The predicates predicates = source.predicates; std::map<pair<unsigned, unsigned>, int> aliasing; std::map<int, pair<unsigned, unsigned> > r_index; std::map<int, int> hierarchy; uint64_t cnt1 = 0; //std::cout << "create mappings" << std::endl; /*create mappings*/ for (int i = 0; i < source.predicates.size(); i++) { std::pair<unsigned, unsigned> p1 (source.predicates[i].left.binding, source.predicates[i].left.colId); std::pair<unsigned, unsigned> p2 (source.predicates[i].right.binding, source.predicates[i].right.colId); if (aliasing.find(p1) == aliasing.end()) { aliasing[p1] = cnt1; r_index[cnt1] = p1; hierarchy[cnt1] = -1; cnt1++; } //std::cout << source.predicates[i].left.binding << ":" << source.predicates[i].left.colId // << ":" << aliasing[p1]; if (aliasing.find(p2) == aliasing.end()) { aliasing[p2] = cnt1; r_index[cnt1] = p2; hierarchy[cnt1] = -1; cnt1++; } //std::cout << " " << source.predicates[i].right.binding << ":" << source.predicates[i].right.colId // << ":" << aliasing[p2] << std::endl; } //std::cout << "union-find" << std::endl; /*union-find*/ for (int i = 0; i < source.predicates.size(); i++) { std::pair<unsigned, unsigned> p1 (source.predicates[i].left.binding, source.predicates[i].left.colId); std::pair<unsigned, unsigned> p2 (source.predicates[i].right.binding, source.predicates[i].right.colId); int val1 = aliasing[p1]; int val2 = aliasing[p2]; int head1 = val1; while (hierarchy[head1] != -1) head1 = hierarchy[head1]; int head2 = val2; while (hierarchy[head2] != -1) head2 = hierarchy[head2]; if (head1 != head2) hierarchy[head1] = head2; } /// The filters filters = source.filters; /// The selections //selections = source.selections; selections.clear(); results.clear(); uint64_t cnt = 0; std::map<pair<unsigned, unsigned>, unsigned> distinct_results; std::map<int, unsigned> representative; //std::cout << "create selections" << std::endl; for (int i = 0; i < source.selections.size(); i++) { std::pair<unsigned, unsigned> p (source.selections[i].binding, source.selections[i].colId); if (distinct_results.find(p) == distinct_results.end()) { //std::cout << "not added yet" << std::endl; if (aliasing.find(p) == aliasing.end()) { //std::cout << "not in aliasing" << std::endl; distinct_results[p] = cnt; selections.push_back(source.selections[i]); results.push_back(cnt); cnt++; } else { //std::cout << "in aliasing" << std::endl; int head = aliasing[p]; while (hierarchy[head] != -1) { head = hierarchy[head]; } //std::cout << "check if representative in prints" << std::endl; if (representative.find(head) == representative.end()) { representative[head] = cnt; distinct_results[p] = cnt; selections.push_back(source.selections[i]); results.push_back(cnt); cnt++; } else { //std::cout << aliasing[p] << " pruned2 " << head << " " << representative[head] << std::endl; results.push_back(representative[head]); } } } else { //std::cout << "pruned1" << std::endl; results.push_back(distinct_results[p]); } } //std::cout << selections.size() << std::endl; }
32.448276
114
0.512712
[ "vector" ]
2060c5aaff22b083f99550d091f36e6e3d781fd6
12,405
cpp
C++
src/frameworks/native/services/surfaceflinger/CompositionEngine/tests/OutputLayerTest.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
null
null
null
src/frameworks/native/services/surfaceflinger/CompositionEngine/tests/OutputLayerTest.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
null
null
null
src/frameworks/native/services/surfaceflinger/CompositionEngine/tests/OutputLayerTest.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019 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. */ #include <compositionengine/impl/OutputLayer.h> #include <compositionengine/mock/CompositionEngine.h> #include <compositionengine/mock/Layer.h> #include <compositionengine/mock/LayerFE.h> #include <compositionengine/mock/Output.h> #include <gtest/gtest.h> #include "MockHWC2.h" #include "MockHWComposer.h" #include "RectMatcher.h" namespace android::compositionengine { namespace { using testing::_; using testing::Return; using testing::ReturnRef; using testing::StrictMock; constexpr DisplayId DEFAULT_DISPLAY_ID = DisplayId{42}; constexpr auto TR_IDENT = 0u; constexpr auto TR_FLP_H = HAL_TRANSFORM_FLIP_H; constexpr auto TR_FLP_V = HAL_TRANSFORM_FLIP_V; constexpr auto TR_ROT_90 = HAL_TRANSFORM_ROT_90; constexpr auto TR_ROT_180 = TR_FLP_H | TR_FLP_V; constexpr auto TR_ROT_270 = TR_ROT_90 | TR_ROT_180; const std::string kOutputName{"Test Output"}; class OutputLayerTest : public testing::Test { public: OutputLayerTest() { EXPECT_CALL(*mLayerFE, getDebugName()).WillRepeatedly(Return("Test LayerFE")); EXPECT_CALL(mOutput, getName()).WillRepeatedly(ReturnRef(kOutputName)); EXPECT_CALL(*mLayer, getState()).WillRepeatedly(ReturnRef(mLayerState)); EXPECT_CALL(mOutput, getState()).WillRepeatedly(ReturnRef(mOutputState)); } ~OutputLayerTest() override = default; compositionengine::mock::Output mOutput; std::shared_ptr<compositionengine::mock::Layer> mLayer{ new StrictMock<compositionengine::mock::Layer>()}; sp<compositionengine::mock::LayerFE> mLayerFE{ new StrictMock<compositionengine::mock::LayerFE>()}; impl::OutputLayer mOutputLayer{mOutput, mLayer, mLayerFE}; impl::LayerCompositionState mLayerState; impl::OutputCompositionState mOutputState; }; /* * Basic construction */ TEST_F(OutputLayerTest, canInstantiateOutputLayer) {} /* * OutputLayer::initialize() */ TEST_F(OutputLayerTest, initializingOutputLayerWithoutHwcDoesNothingInteresting) { StrictMock<compositionengine::mock::CompositionEngine> compositionEngine; mOutputLayer.initialize(compositionEngine, std::nullopt); EXPECT_FALSE(mOutputLayer.getState().hwc); } TEST_F(OutputLayerTest, initializingOutputLayerWithHwcDisplayCreatesHwcLayer) { StrictMock<compositionengine::mock::CompositionEngine> compositionEngine; StrictMock<android::mock::HWComposer> hwc; StrictMock<HWC2::mock::Layer> hwcLayer; EXPECT_CALL(compositionEngine, getHwComposer()).WillOnce(ReturnRef(hwc)); EXPECT_CALL(hwc, createLayer(DEFAULT_DISPLAY_ID)).WillOnce(Return(&hwcLayer)); mOutputLayer.initialize(compositionEngine, DEFAULT_DISPLAY_ID); const auto& outputLayerState = mOutputLayer.getState(); ASSERT_TRUE(outputLayerState.hwc); const auto& hwcState = *outputLayerState.hwc; EXPECT_EQ(&hwcLayer, hwcState.hwcLayer.get()); EXPECT_CALL(hwc, destroyLayer(DEFAULT_DISPLAY_ID, &hwcLayer)); mOutputLayer.editState().hwc.reset(); } /* * OutputLayer::calculateOutputDisplayFrame() */ struct OutputLayerDisplayFrameTest : public OutputLayerTest { OutputLayerDisplayFrameTest() { // Set reasonable default values for a simple case. Each test will // set one specific value to something different. mLayerState.frontEnd.geomActiveTransparentRegion = Region{}; mLayerState.frontEnd.geomLayerTransform = ui::Transform{TR_IDENT}; mLayerState.frontEnd.geomBufferSize = Rect{0, 0, 1920, 1080}; mLayerState.frontEnd.geomBufferUsesDisplayInverseTransform = false; mLayerState.frontEnd.geomCrop = Rect{0, 0, 1920, 1080}; mLayerState.frontEnd.geomLayerBounds = FloatRect{0.f, 0.f, 1920.f, 1080.f}; mOutputState.viewport = Rect{0, 0, 1920, 1080}; mOutputState.transform = ui::Transform{TR_IDENT}; } Rect calculateOutputDisplayFrame() { mLayerState.frontEnd.geomInverseLayerTransform = mLayerState.frontEnd.geomLayerTransform.inverse(); return mOutputLayer.calculateOutputDisplayFrame(); } }; TEST_F(OutputLayerDisplayFrameTest, correctForSimpleDefaultCase) { const Rect expected{0, 0, 1920, 1080}; EXPECT_THAT(calculateOutputDisplayFrame(), RectEq(expected)); } TEST_F(OutputLayerDisplayFrameTest, fullActiveTransparentRegionReturnsEmptyFrame) { mLayerState.frontEnd.geomActiveTransparentRegion = Region{Rect{0, 0, 1920, 1080}}; const Rect expected{0, 0, 0, 0}; EXPECT_THAT(calculateOutputDisplayFrame(), RectEq(expected)); } TEST_F(OutputLayerDisplayFrameTest, cropAffectsDisplayFrame) { mLayerState.frontEnd.geomCrop = Rect{100, 200, 300, 500}; const Rect expected{100, 200, 300, 500}; EXPECT_THAT(calculateOutputDisplayFrame(), RectEq(expected)); } TEST_F(OutputLayerDisplayFrameTest, cropAffectsDisplayFrameRotated) { mLayerState.frontEnd.geomCrop = Rect{100, 200, 300, 500}; mLayerState.frontEnd.geomLayerTransform.set(HAL_TRANSFORM_ROT_90, 1920, 1080); const Rect expected{1420, 100, 1720, 300}; EXPECT_THAT(calculateOutputDisplayFrame(), RectEq(expected)); } TEST_F(OutputLayerDisplayFrameTest, emptyGeomCropIsNotUsedToComputeFrame) { mLayerState.frontEnd.geomCrop = Rect{}; const Rect expected{0, 0, 1920, 1080}; EXPECT_THAT(calculateOutputDisplayFrame(), RectEq(expected)); } TEST_F(OutputLayerDisplayFrameTest, geomLayerSnapToBoundsAffectsFrame) { mLayerState.frontEnd.geomLayerBounds = FloatRect{0.f, 0.f, 960.f, 540.f}; const Rect expected{0, 0, 960, 540}; EXPECT_THAT(calculateOutputDisplayFrame(), RectEq(expected)); } TEST_F(OutputLayerDisplayFrameTest, viewportAffectsFrame) { mOutputState.viewport = Rect{0, 0, 960, 540}; const Rect expected{0, 0, 960, 540}; EXPECT_THAT(calculateOutputDisplayFrame(), RectEq(expected)); } TEST_F(OutputLayerDisplayFrameTest, outputTransformAffectsDisplayFrame) { mOutputState.transform = ui::Transform{HAL_TRANSFORM_ROT_90}; const Rect expected{-1080, 0, 0, 1920}; EXPECT_THAT(calculateOutputDisplayFrame(), RectEq(expected)); } /* * OutputLayer::calculateOutputRelativeBufferTransform() */ TEST_F(OutputLayerTest, calculateOutputRelativeBufferTransformTestsNeeded) { mLayerState.frontEnd.geomBufferUsesDisplayInverseTransform = false; struct Entry { uint32_t layer; uint32_t buffer; uint32_t display; uint32_t expected; }; // Not an exhaustive list of cases, but hopefully enough. const std::array<Entry, 24> testData = { // clang-format off // layer buffer display expected /* 0 */ Entry{TR_IDENT, TR_IDENT, TR_IDENT, TR_IDENT}, /* 1 */ Entry{TR_IDENT, TR_IDENT, TR_ROT_90, TR_ROT_90}, /* 2 */ Entry{TR_IDENT, TR_IDENT, TR_ROT_180, TR_ROT_180}, /* 3 */ Entry{TR_IDENT, TR_IDENT, TR_ROT_270, TR_ROT_270}, /* 4 */ Entry{TR_IDENT, TR_FLP_H, TR_IDENT, TR_FLP_H ^ TR_IDENT}, /* 5 */ Entry{TR_IDENT, TR_FLP_H, TR_ROT_90, TR_FLP_H ^ TR_ROT_90}, /* 6 */ Entry{TR_IDENT, TR_FLP_H, TR_ROT_180, TR_FLP_H ^ TR_ROT_180}, /* 7 */ Entry{TR_IDENT, TR_FLP_H, TR_ROT_270, TR_FLP_H ^ TR_ROT_270}, /* 8 */ Entry{TR_IDENT, TR_FLP_V, TR_IDENT, TR_FLP_V}, /* 9 */ Entry{TR_IDENT, TR_ROT_90, TR_ROT_90, TR_ROT_180}, /* 10 */ Entry{TR_IDENT, TR_ROT_180, TR_ROT_180, TR_IDENT}, /* 11 */ Entry{TR_IDENT, TR_ROT_270, TR_ROT_270, TR_ROT_180}, /* 12 */ Entry{TR_ROT_90, TR_IDENT, TR_IDENT, TR_IDENT ^ TR_ROT_90}, /* 13 */ Entry{TR_ROT_90, TR_FLP_H, TR_ROT_90, TR_FLP_H ^ TR_ROT_180}, /* 14 */ Entry{TR_ROT_90, TR_IDENT, TR_ROT_180, TR_IDENT ^ TR_ROT_270}, /* 15 */ Entry{TR_ROT_90, TR_FLP_H, TR_ROT_270, TR_FLP_H ^ TR_IDENT}, /* 16 */ Entry{TR_ROT_180, TR_FLP_H, TR_IDENT, TR_FLP_H ^ TR_ROT_180}, /* 17 */ Entry{TR_ROT_180, TR_IDENT, TR_ROT_90, TR_IDENT ^ TR_ROT_270}, /* 18 */ Entry{TR_ROT_180, TR_FLP_H, TR_ROT_180, TR_FLP_H ^ TR_IDENT}, /* 19 */ Entry{TR_ROT_180, TR_IDENT, TR_ROT_270, TR_IDENT ^ TR_ROT_90}, /* 20 */ Entry{TR_ROT_270, TR_IDENT, TR_IDENT, TR_IDENT ^ TR_ROT_270}, /* 21 */ Entry{TR_ROT_270, TR_FLP_H, TR_ROT_90, TR_FLP_H ^ TR_IDENT}, /* 22 */ Entry{TR_ROT_270, TR_FLP_H, TR_ROT_180, TR_FLP_H ^ TR_ROT_90}, /* 23 */ Entry{TR_ROT_270, TR_IDENT, TR_ROT_270, TR_IDENT ^ TR_ROT_180}, // clang-format on }; for (size_t i = 0; i < testData.size(); i++) { const auto& entry = testData[i]; mLayerState.frontEnd.geomLayerTransform.set(entry.layer, 1920, 1080); mLayerState.frontEnd.geomBufferTransform = entry.buffer; mOutputState.orientation = entry.display; auto actual = mOutputLayer.calculateOutputRelativeBufferTransform(); EXPECT_EQ(entry.expected, actual) << "entry " << i; } } /* * OutputLayer::writeStateToHWC() */ struct OutputLayerWriteStateToHWCTest : public OutputLayerTest { static constexpr HWC2::Error kError = HWC2::Error::Unsupported; static constexpr FloatRect kSourceCrop{11.f, 12.f, 13.f, 14.f}; static constexpr uint32_t kZOrder = 21u; static constexpr Hwc2::Transform kBufferTransform = static_cast<Hwc2::Transform>(31); static constexpr Hwc2::IComposerClient::BlendMode kBlendMode = static_cast<Hwc2::IComposerClient::BlendMode>(41); static constexpr float kAlpha = 51.f; static constexpr uint32_t kType = 61u; static constexpr uint32_t kAppId = 62u; static const Rect kDisplayFrame; OutputLayerWriteStateToHWCTest() { auto& outputLayerState = mOutputLayer.editState(); outputLayerState.hwc = impl::OutputLayerCompositionState::Hwc(mHwcLayer); outputLayerState.displayFrame = kDisplayFrame; outputLayerState.sourceCrop = kSourceCrop; outputLayerState.z = kZOrder; outputLayerState.bufferTransform = static_cast<Hwc2::Transform>(kBufferTransform); mLayerState.frontEnd.blendMode = kBlendMode; mLayerState.frontEnd.alpha = kAlpha; mLayerState.frontEnd.type = kType; mLayerState.frontEnd.appId = kAppId; } void expectGeometryCommonCalls() { EXPECT_CALL(*mHwcLayer, setDisplayFrame(kDisplayFrame)).WillOnce(Return(kError)); EXPECT_CALL(*mHwcLayer, setSourceCrop(kSourceCrop)).WillOnce(Return(kError)); EXPECT_CALL(*mHwcLayer, setZOrder(kZOrder)).WillOnce(Return(kError)); EXPECT_CALL(*mHwcLayer, setTransform(static_cast<HWC2::Transform>(kBufferTransform))) .WillOnce(Return(kError)); EXPECT_CALL(*mHwcLayer, setBlendMode(static_cast<HWC2::BlendMode>(kBlendMode))) .WillOnce(Return(kError)); EXPECT_CALL(*mHwcLayer, setPlaneAlpha(kAlpha)).WillOnce(Return(kError)); EXPECT_CALL(*mHwcLayer, setInfo(kType, kAppId)).WillOnce(Return(kError)); } std::shared_ptr<HWC2::mock::Layer> mHwcLayer{std::make_shared<StrictMock<HWC2::mock::Layer>>()}; }; const Rect OutputLayerWriteStateToHWCTest::kDisplayFrame{1001, 1002, 1003, 10044}; TEST_F(OutputLayerWriteStateToHWCTest, doesNothingIfNoHWCState) { mOutputLayer.editState().hwc.reset(); mOutputLayer.writeStateToHWC(true); } TEST_F(OutputLayerWriteStateToHWCTest, doesNothingIfNoHWCLayer) { mOutputLayer.editState().hwc = impl::OutputLayerCompositionState::Hwc(nullptr); mOutputLayer.writeStateToHWC(true); } TEST_F(OutputLayerWriteStateToHWCTest, canSetsAllState) { expectGeometryCommonCalls(); mOutputLayer.writeStateToHWC(true); } } // namespace } // namespace android::compositionengine
39.380952
100
0.710278
[ "transform" ]
2066002cfcddddad27c4c901e59bb28f1d8eb122
5,793
cpp
C++
YeOlde/cpp/Aquarians/aqlib/Exception.cpp
aquarians/Public
ac79b1502fe62eee2c84e1e4b8d32e6c303bdfd4
[ "MIT" ]
null
null
null
YeOlde/cpp/Aquarians/aqlib/Exception.cpp
aquarians/Public
ac79b1502fe62eee2c84e1e4b8d32e6c303bdfd4
[ "MIT" ]
null
null
null
YeOlde/cpp/Aquarians/aqlib/Exception.cpp
aquarians/Public
ac79b1502fe62eee2c84e1e4b8d32e6c303bdfd4
[ "MIT" ]
null
null
null
#include "Exception.hpp" #include <execinfo.h> #include <unistd.h> #include <bfd.h> #include <vector> #include <stdexcept> #include <sstream> #include <stdlib.h> #include <stdio.h> #include <cxxabi.h> namespace aqlib { log4cxx::LoggerPtr Exception::logger(log4cxx::Logger::getLogger("aqlib.Exception")); const std::string Exception::CLASS_NAME("Exception"); const int Exception::MAX_STACKTRACE_DEPTH = 100; Exception::BfdData* Exception::gBfdData = NULL; struct Exception::BfdData { bfd *abfd; std::vector<char> syms; asection *text; BfdData() { char ename[1024]; int l = readlink("/proc/self/exe", ename, sizeof(ename)); if (l == -1) { throw std::runtime_error("readlink('/proc/self/exe') failed"); } ename[l] = 0; bfd_init(); abfd = bfd_openr(ename, NULL); if (NULL == abfd) { throw std::runtime_error("bfd_openr failed"); } // Oddly, this is required for it to work... bfd_check_format(abfd, bfd_object); int storage_needed = bfd_get_symtab_upper_bound(abfd); if (storage_needed < 0) { throw std::runtime_error("bfd_get_symtab_upper_bound failed"); } syms.resize(storage_needed); int scount = bfd_canonicalize_symtab(abfd, (asymbol **)(&syms[0])); if (scount < 0) { throw std::runtime_error("bfd_canonicalize_symtab failed"); } text = bfd_get_section_by_name(abfd, ".text"); } bool resolve(Exception::Frame &frame) { char *frmAdr = (char *) frame.addr; char *txtAdr = (char *) text->vma; if (frmAdr < txtAdr) { return false; } // http://sourceware.org/ml/binutils/2005-07/msg00285.html // A bfd_vma is defined as whatever C type can hold an unsigned 64-bit value. // Thus on a 32-bit host it will be a "unsigned long long" and on a 64-bit host it will be an "unsigned long". // Either way a bfd_vma is a 64-bit unsigned value. bfd_vma offset = frmAdr - txtAdr; const char *file = NULL; const char *func = NULL; unsigned line; if (!bfd_find_nearest_line(abfd, text, (asymbol **)(&syms[0]), offset, &file, &func, &line)) { return false; } if ((NULL == file) || (NULL == func)) { return false; } frame.file = file; if (frame.func.size() == 0) frame.func = func; frame.line = line; return true; } }; void Exception::staticInit() { gBfdData = new BfdData(); } Exception::Frame::Frame() { addr = NULL; line = -1; } Exception::Exception(const std::string &message) { // Get the backtrace std::vector<void *> addresses(MAX_STACKTRACE_DEPTH); int depth = backtrace(&addresses[0], addresses.size()); // Get the frames mFrames.resize(depth); char **syms = backtrace_symbols(&addresses[0], depth); for (int i = 0; i < depth; ++i) { Frame &frame = mFrames[i]; // Raw data frame.addr = addresses[i]; frame.sym = syms[i]; // Module and function parseBacktraceSymbol(frame); // File and line if (NULL != gBfdData) { gBfdData->resolve(frame); } // Demangle function name int demangleStatus = 0; char *demangledFunc = abi::__cxa_demangle(frame.func.c_str(), NULL, NULL, &demangleStatus); if (NULL != demangledFunc) { frame.func = demangledFunc; free(demangledFunc); } } free(syms); mMessage = message; mWhat = Exception::toString(); } // Expect the form: "module(function+0xOFFSET) [0xADDR]" or "module() [0xADDR]" void Exception::parseBacktraceSymbol(Frame &frame) { std::size_t startPos = frame.sym.find("("); if (std::string::npos == startPos) { return; } frame.module = frame.sym.substr(0, startPos); startPos++; std::size_t endPos = frame.sym.find("+0x", startPos); if (std::string::npos == endPos) { return; } frame.func = frame.sym.substr(startPos, endPos - startPos); } const std::string& Exception::getClassName() const { return CLASS_NAME; } const std::string& Exception::getMessage() const { return mMessage; } int Exception::getFrameCount() const { return mFrames.size(); } const Exception::Frame& Exception::getFrame(int index) const { return mFrames[index]; } std::string Exception::toString() const { std::stringstream strm; strm << getClassName() << ": " << mMessage; std::string module; for (int i = 0; i < getFrameCount(); ++i) { const Frame &frame = getFrame(i); // Ignore first frame as it's the Exception() constructor, where backtrace() is called if (0 == i) { continue; } // Last frame seems to be just the module name if ((getFrameCount() - 1 == i) && (0 == frame.func.size())) { continue; } strm << std::endl; if (module != frame.module) { module = frame.module; strm << " in " << module << std::endl; } strm << " at " << frame.func; if (frame.file.size()) { strm << "(" << frame.file; if (frame.line) strm << ": " << frame.line; strm << ")"; } } return strm.str(); } const char* Exception::what() const throw() { return mWhat.c_str(); } } // namespace aqlib
24.037344
118
0.547385
[ "vector" ]
206da0cf18efa44a3cb4086c092105f21fea5761
3,506
cpp
C++
src/AdventOfCode2020/Day11-SeatingSystem/SeatingSimulator.cpp
dbartok/advent-of-code-cpp
c8c2df7a21980f8f3e42128f7bc5df8288f18490
[ "MIT" ]
null
null
null
src/AdventOfCode2020/Day11-SeatingSystem/SeatingSimulator.cpp
dbartok/advent-of-code-cpp
c8c2df7a21980f8f3e42128f7bc5df8288f18490
[ "MIT" ]
null
null
null
src/AdventOfCode2020/Day11-SeatingSystem/SeatingSimulator.cpp
dbartok/advent-of-code-cpp
c8c2df7a21980f8f3e42128f7bc5df8288f18490
[ "MIT" ]
null
null
null
#include "SeatingSimulator.h" #include <AdventOfCodeCommon/DisableLibraryWarningsMacros.h> __BEGIN_LIBRARIES_DISABLE_WARNINGS __END_LIBRARIES_DISABLE_WARNINGS namespace AdventOfCode { namespace Year2020 { namespace Day11 { SeatingSimulator::SeatingSimulator(std::vector<std::string> seatLayoutLines, size_t visionRange, size_t numVisibleOccupiedSeatsThreshold) : m_seatLayout{std::move(seatLayoutLines)} , m_visionRange{visionRange} , m_numVisibleOccupiedSeatsThreshold{numVisibleOccupiedSeatsThreshold} , m_width{m_seatLayout.at(0).size()} , m_height{m_seatLayout.size()} { } void SeatingSimulator::simulateUntilStable() { while (true) { SeatLayout nextLayout = getNextLayout(); if (nextLayout == m_seatLayout) { break; } m_seatLayout = std::move(nextLayout); } } int SeatingSimulator::getNumOccupiedSeats() const { int numOccupiedSeats = 0; for (int j = 0; j < m_height; ++j) { for (int i = 0; i < m_width; ++i) { if (m_seatLayout.at(j).at(i) == OCCUPIED_SEAT) { ++numOccupiedSeats; } } } return numOccupiedSeats; } SeatLayout SeatingSimulator::getNextLayout() const { auto nextLayout{m_seatLayout}; for (int j = 0; j < m_height; ++j) { for (int i = 0; i < m_width; ++i) { nextLayout.at(j).at(i) = getNextStateAt(i, j); } } return nextLayout; } SeatState SeatingSimulator::getNextStateAt(int x, int y) const { const SeatState currentState = m_seatLayout.at(y).at(x); if (currentState == FLOOR) { return FLOOR; } const int numOccupiedVisibleSeats = getNumVisibleOccupiedSeatsFrom(x, y); if (currentState == EMPTY_SEAT && numOccupiedVisibleSeats == 0) { return OCCUPIED_SEAT; } if (currentState == OCCUPIED_SEAT && numOccupiedVisibleSeats >= m_numVisibleOccupiedSeatsThreshold) { return EMPTY_SEAT; } return currentState; } int SeatingSimulator::getNumVisibleOccupiedSeatsFrom(int x, int y) const { int numOccupiedNeighbors = 0; for (const auto& directionVector : getAllDirectionVectors()) { if (isOccupiedSeatVisibleInGivenDirectionFrom(x, y, directionVector)) { ++numOccupiedNeighbors; } } return numOccupiedNeighbors; } bool SeatingSimulator::isOccupiedSeatVisibleInGivenDirectionFrom(int x, int y, const Vector2D& directionVector) const { Vector2D positionVector{x, y}; for (size_t i = 0; i < m_visionRange; ++i) { positionVector += directionVector; if (isOutOfBounds(positionVector[0], positionVector[1])) { return false; } if (m_seatLayout.at(positionVector[1]).at(positionVector[0]) == OCCUPIED_SEAT) { return true; } if (m_seatLayout.at(positionVector[1]).at(positionVector[0]) == EMPTY_SEAT) { return false; } } return false; } bool SeatingSimulator::isOutOfBounds(int x, int y) const { return x < 0 || x >= m_width || y < 0 || y >= m_height; } std::vector<Vector2D> SeatingSimulator::getAllDirectionVectors() { return std::vector<Vector2D> { Vector2D{1, 0}, Vector2D{-1, 0}, Vector2D{0, 1}, Vector2D{0, -1}, Vector2D{1, 1}, Vector2D{-1, 1}, Vector2D{-1, -1}, Vector2D{1, -1}, }; } } } }
22.050314
137
0.623217
[ "vector" ]
206fde0a7a450fc35561341c34d07c732b7fa8f5
15,975
cpp
C++
libfma/src/fma/core/Array.cpp
BenjaminSchulte/fma
df2aa5b0644c75dd34a92defeff9beaa4a32ffea
[ "MIT" ]
14
2018-01-25T10:31:05.000Z
2022-02-19T13:08:11.000Z
libfma/src/fma/core/Array.cpp
BenjaminSchulte/fma
df2aa5b0644c75dd34a92defeff9beaa4a32ffea
[ "MIT" ]
1
2020-12-24T10:10:28.000Z
2020-12-24T10:10:28.000Z
libfma/src/fma/core/Array.cpp
BenjaminSchulte/fma
df2aa5b0644c75dd34a92defeff9beaa4a32ffea
[ "MIT" ]
null
null
null
#include <fma/core/Class.hpp> #include <fma/core/Array.hpp> #include <fma/core/Boolean.hpp> #include <fma/core/Nil.hpp> #include <fma/core/Number.hpp> #include <fma/core/String.hpp> #include <fma/types/InternalValue.hpp> #include <fma/types/Object.hpp> #include <fma/types/Undefined.hpp> #include <fma/types/ClassPrototype.hpp> #include <fma/interpret/BaseContext.hpp> #include <fma/interpret/Result.hpp> #include <fma/interpret/Parameter.hpp> #include <fma/interpret/ParameterList.hpp> #include <fma/interpret/ObjectContext.hpp> #include <fma/serialize/SerializeObject.hpp> #include <fma/Project.hpp> using namespace FMA; using namespace FMA::core; using namespace FMA::types; using namespace FMA::interpret; using namespace FMA::serialize; #include <iostream> #include <sstream> #include <cmath> TypeList __emptyList; // ---------------------------------------------------------------------------- ClassPtr ArrayClass::create(const RootModulePtr &root, const ClassPtr &ClassObject) { ClassPtr klass = ClassPtr(new Class("Array", "Array")); klass->extends(ClassObject); klass->setMember("@FMA_TYPE_ID", TypePtr(new InternalNumberValue(TYPE_ARRAY))); ClassPrototypePtr proto(klass->getPrototype()); proto->setMember("dup", TypePtr(new InternalFunctionValue("dup", ArrayClass::dup))); proto->setMember("count", TypePtr(new InternalFunctionValue("count", ArrayClass::count))); proto->setMember("each", TypePtr(new InternalFunctionValue("each", ArrayClass::each))); proto->setMember("empty?", TypePtr(new InternalFunctionValue("empty?", ArrayClass::empty_qm))); proto->setMember("first", TypePtr(new InternalFunctionValue("first", ArrayClass::first))); proto->setMember("include?", TypePtr(new InternalFunctionValue("include?", ArrayClass::include_qm))); proto->setMember("index", TypePtr(new InternalFunctionValue("index", ArrayClass::index))); proto->setMember("initialize", TypePtr(new InternalFunctionValue("initialize", ArrayClass::initialize))); proto->setMember("last", TypePtr(new InternalFunctionValue("last", ArrayClass::last))); proto->setMember("length", TypePtr(new InternalFunctionValue("length", ArrayClass::count))); proto->setMember("pop", TypePtr(new InternalFunctionValue("pop", ArrayClass::pop))); proto->setMember("size", TypePtr(new InternalFunctionValue("size", ArrayClass::count))); proto->setMember("map", TypePtr(new InternalFunctionValue("map", ArrayClass::map))); proto->setMember("to_s", TypePtr(new InternalFunctionValue("to_s", ArrayClass::to_s))); proto->setMember("join", TypePtr(new InternalFunctionValue("join", ArrayClass::join))); proto->setMember("+", TypePtr(new InternalFunctionValue("+", ArrayClass::op_add))); proto->setMember("<<", TypePtr(new InternalFunctionValue("<<", ArrayClass::op_lshift))); proto->setMember("==", TypePtr(new InternalFunctionValue("==", ArrayClass::op_eq))); proto->setMember("[]", TypePtr(new InternalFunctionValue("[]", ArrayClass::op_index))); proto->setMember("[]=", TypePtr(new InternalFunctionValue("[]=", ArrayClass::op_index_set))); root->setMember("Array", klass); return klass; } // ---------------------------------------------------------------------------- ResultPtr ArrayClass::createInstance(const ContextPtr &context, const TypeList &value) { // Resolve a ClassPtr number = context->getRootLevelContext()->resolve("Array")->asClass(); if (!number) { return ResultPtr(new Result()); } GroupedParameterList parameters; parameters.push_back(TypePtr(new InternalArrayValue(value))); return Result::executed(context, number->createInstance(context, parameters)); } // ---------------------------------------------------------------------------- ResultPtr ArrayClass::count(const ContextPtr &context, const GroupedParameterList&) { const TypeList &items = values(context); return NumberClass::createInstance(context, items.size()); } // ---------------------------------------------------------------------------- ResultPtr ArrayClass::dup(const ContextPtr &context, const GroupedParameterList&) { const TypeList &items = values(context); return ArrayClass::createInstance(context, items); } // ---------------------------------------------------------------------------- ResultPtr ArrayClass::pop(const ContextPtr &context, const GroupedParameterList&) { TypeList &items = values(context); if (!items.size()) { return NilClass::createInstance(context); } TypePtr last = items.back(); items.pop_back(); return Result::executed(context, last); } // ---------------------------------------------------------------------------- ResultPtr ArrayClass::each(const ContextPtr &context, const GroupedParameterList &parameter) { const TypeList &blocks = parameter.only_blocks(); if (!blocks.size()) { return ResultPtr(new Result()); } ResultPtr result(new Result()); const TypePtr &block = blocks.front(); const TypeList &items = context->self()->convertToArray(context); uint64_t index=0; for (auto &item : items) { GroupedParameterList yieldParams; yieldParams.push_back(Parameter(item)); yieldParams.push_back(NumberClass::createInstance(context, index++)->get()); result = block->call(context, yieldParams); } return result; } // ---------------------------------------------------------------------------- ResultPtr ArrayClass::map(const ContextPtr &context, const GroupedParameterList &parameter) { const TypeList &blocks = parameter.only_blocks(); if (!blocks.size()) { return ResultPtr(new Result()); } const TypePtr &block = blocks.front(); const TypeList &items = context->self()->convertToArray(context); TypeList resultList; uint64_t index=0; for (auto &item : items) { GroupedParameterList yieldParams; yieldParams.push_back(Parameter(item)); yieldParams.push_back(NumberClass::createInstance(context, index++)->get()); resultList.push_back(block->call(context, yieldParams)->get()); } return createInstance(context, resultList); } // ---------------------------------------------------------------------------- ResultPtr ArrayClass::empty_qm(const ContextPtr &context, const GroupedParameterList &) { return BooleanClass::createInstance(context, values(context).size() == 0); } // ---------------------------------------------------------------------------- ResultPtr ArrayClass::first(const ContextPtr &context, const GroupedParameterList &) { const TypeList &items = values(context); if (!items.size()) { return ResultPtr(new Result()); } return ResultPtr(new Result(context, items.front())); } // ---------------------------------------------------------------------------- ResultPtr ArrayClass::include_qm(const ContextPtr &context, const GroupedParameterList &parameter) { const TypeList &args = parameter.only_args(); if (args.size() < 1) { return BooleanClass::createInstance(context, false); } const TypePtr &self = args.front(); ContextPtr callContext(new ObjectContext(context->getInterpreter(), self)); const TypePtr &eq = self->getMember("=="); const TypeList &items = values(context); for (auto &item : items) { GroupedParameterList params; params.push_back(item); ResultPtr testResult = eq->call(callContext, params); if (testResult->get()->convertToBoolean(context)) { return testResult; } } return BooleanClass::createInstance(context, false); } // ---------------------------------------------------------------------------- ResultPtr ArrayClass::index(const ContextPtr &context, const GroupedParameterList &parameter) { const TypeList &args = parameter.only_args(); if (args.size() < 1) { return BooleanClass::createInstance(context, false); } const TypePtr &self = args.front(); ContextPtr callContext(new ObjectContext(context->getInterpreter(), self)); const TypePtr &eq = self->getMember("=="); const TypeList &items = values(context); uint32_t index = 0; for (auto &item : items) { GroupedParameterList params; params.push_back(item); ResultPtr testResult = eq->call(callContext, params); if (testResult->get()->convertToBoolean(context)) { return NumberClass::createInstance(context, index); } index++; } return NilClass::createInstance(context); } // ---------------------------------------------------------------------------- ResultPtr ArrayClass::initialize(const ContextPtr &context, const GroupedParameterList &parameter) { const TypeList &args = parameter.only_args(); switch (args.size()) { case 0: context->self()->setMember("__value", TypePtr(new InternalArrayValue())); break; case 1: default: context->self()->setMember("__value", args.front()); break; } return Result::executed(context, context->self()); } // ---------------------------------------------------------------------------- ResultPtr ArrayClass::last(const ContextPtr &context, const GroupedParameterList &) { const TypeList &items = values(context); if (!items.size()) { return ResultPtr(new Result()); } return ResultPtr(new Result(context, items.back())); } // ---------------------------------------------------------------------------- ResultPtr ArrayClass::op_eq(const ContextPtr &context, const GroupedParameterList &params) { const TypeList &args = params.only_args(); if (args.size() < 1) { return BooleanClass::createInstance(context, false); } InternalArrayValue *otherObject = internalArray(context, args.front()); if (!otherObject) { return BooleanClass::createInstance(context, false); } const TypeList &self = values(context); const TypeList &other = otherObject->getValue(); if (self.size() != other.size()) { return BooleanClass::createInstance(context, false); } for ( TypeList::const_iterator itSelf = self.begin(), itOther = other.begin(); itSelf != self.end() && itOther != other.end(); itSelf++, itOther++ ) { const TypePtr &left = *itSelf; const TypePtr &right = *itOther; GroupedParameterList params; params.push_back(right); ContextPtr callContext(new ObjectContext(context->getInterpreter(), left)); if (!left->getMember("==")->call(callContext, params)->get()->convertToBoolean(context)) { return BooleanClass::createInstance(context, false); } } return BooleanClass::createInstance(context, true); } // ---------------------------------------------------------------------------- ResultPtr ArrayClass::op_index(const ContextPtr &context, const GroupedParameterList &params) { const TypeList &args = params.only_args(); if (args.size() < 1) { return ResultPtr(new Result()); } int64_t index = args.front()->convertToNumber(context); const TypeList &items = values(context); if (index < 0) { index = items.size() + index; if (index < 0) { return NilClass::createInstance(context); } } ResultPtr result; if (index >= (int64_t)items.size()) { result = NilClass::createInstance(context); } else { result = ResultPtr(new Result(context, items[index])); } result->makeAssignable( ContextPtr(new ObjectContext(context->getInterpreter(), context->self())), std::to_string(index) ); return result; } // ---------------------------------------------------------------------------- ResultPtr ArrayClass::op_index_set(const ContextPtr &context, const GroupedParameterList &params) { const TypeList &args = params.only_args(); if (args.size() < 2) { return ResultPtr(new Result()); } TypeList &items = values(context); int64_t index = args.front()->convertToNumber(context); uint64_t size = items.size(); if (index < 0) { return ResultPtr(new Result()); } while ((uint64_t)index >= size) { items.push_back(TypePtr(new Undefined())); size++; } const TypePtr &item = args.at(1); items[index] = item; return ResultPtr(new Result(context, item)); } // ---------------------------------------------------------------------------- ResultPtr ArrayClass::op_lshift(const ContextPtr &context, const GroupedParameterList &params) { const TypeList &args = params.only_args(); TypeList &items = values(context); for (auto &item : args) { items.push_back(item); } return ResultPtr(new Result(context, context->self())); } // ---------------------------------------------------------------------------- ResultPtr ArrayClass::op_add(const ContextPtr &context, const GroupedParameterList &params) { const TypeList &args = params.only_args(); TypeList newArray = values(context); for (auto &arg : args) { for (auto &item : arg->convertToArray(context)) { newArray.push_back(item); } } return createInstance(context, newArray); } // ---------------------------------------------------------------------------- ResultPtr ArrayClass::to_s(const ContextPtr &context, const GroupedParameterList&) { std::ostringstream os; bool first=true; os << "["; for (auto &item : values(context)) { if (first) { first = false; } else { os << ", "; } os << item->convertToString(context); } os << "]"; return StringClass::createInstance(context, os.str()); } // ---------------------------------------------------------------------------- ResultPtr ArrayClass::join(const ContextPtr &context, const GroupedParameterList &parameter) { std::string joinUsing = ","; const TypeList &args = parameter.only_args(); if (args.size()) { joinUsing = args.front()->convertToString(context); } std::ostringstream os; bool first=true; for (auto &item : values(context)) { if (first) { first = false; } else { os << joinUsing; } os << item->convertToString(context); } return StringClass::createInstance(context, os.str()); } // ---------------------------------------------------------------------------- InternalArrayValue *ArrayClass::internalArray(const interpret::ContextPtr &context) { return internalArray(context, context->self()); } // ---------------------------------------------------------------------------- InternalArrayValue *ArrayClass::internalArray(const interpret::ContextPtr &context, const TypePtr &self) { if (!self->isObjectOfType("Array")) { return NULL; } TypePtr valueObject = self->getMember("__value"); if (!valueObject->isInternalObjectOfType("Array")) { context->log().error() << self->asString() << " is not not an array"; return NULL; } return dynamic_cast<InternalArrayValue*>(valueObject.get()); } // ---------------------------------------------------------------------------- std::vector<types::TypePtr> &ArrayClass::values(const interpret::ContextPtr &context) { InternalArrayValue *array = internalArray(context); if (array == NULL) { return __emptyList; } return array->getValue(); } // ---------------------------------------------------------------------------- void ArrayClass::serializeObject(const TypePtr &type, const serialize::SerializeObjectPtr &object) { uint32_t numItems = 0; InternalArrayValue *array = internalArray(object->getContext(), type); if (array == NULL) { object->write(&numItems, sizeof(numItems)); return; } const auto &values = array->getValue(); numItems = values.size(); object->write(&numItems, sizeof(numItems)); for (const auto &item : values) { object->write(item); } } // ---------------------------------------------------------------------------- bool ArrayClass::deserializeObject(const serialize::DeserializeObjectPtr &object) { uint32_t numItems = 0; TypePtr result = createInstance(object->getContext(), TypeList())->get(); TypeList &list = internalArray(object->getContext(), result)->getValue(); object->store(result); object->read(&numItems, sizeof(numItems)); for (uint32_t i=0; i<numItems; i++) { list.push_back(object->readObject()); } return true; }
33.420502
107
0.615211
[ "object", "vector" ]
2070e71c98488bec1966412e77d33ef4e43fddda
14,118
cpp
C++
TestC_21_Crab Pong/game.cpp
liuyuwang2016/OpenGL-Tutorial-by-Yvan-Liu
9309df734ade3e26e95aabfd33eaeabe5e7d701d
[ "MIT" ]
null
null
null
TestC_21_Crab Pong/game.cpp
liuyuwang2016/OpenGL-Tutorial-by-Yvan-Liu
9309df734ade3e26e95aabfd33eaeabe5e7d701d
[ "MIT" ]
null
null
null
TestC_21_Crab Pong/game.cpp
liuyuwang2016/OpenGL-Tutorial-by-Yvan-Liu
9309df734ade3e26e95aabfd33eaeabe5e7d701d
[ "MIT" ]
null
null
null
/* Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above notice and this permission notice shall be included in all copies * or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /* File for "A Sample Game: Crab Pong" lesson of the OpenGL tutorial on * www.videotutorialsrock.com */ #include <cmath> #include <cstdlib> #include <math.h> #include <vector> #include "game.h" using namespace std; namespace { const float PI = 3.1415926535f; //The amount of time by which the state of the crab is advanced in each call //to a crab's step() method const float CRAB_STEP_TIME = 0.01f; //The amount of time it takes for a crab to accelerate from no speed to its //maximum speed const float TIME_TO_MAXIMUM_SPEED = 0.18f; //The maximum angle formed by the direction at which a ball is hit off of a //crab and the normal direction for the crab const float MAX_CRAB_BOUNCE_ANGLE_OFFSET = 0.85f * PI / 2; //The maximum speed of the human-controlled crab const float PLAYER_MAXIMUM_SPEED = 2.2f; //The amount of time it takes for a ball to fade into play const float BALL_FADE_IN_TIME = 0.5f; //The amount of time it takes for a ball to fade out of play const float BALL_FADE_OUT_TIME = 0.5f; //The radius of the balls const float BALL_RADIUS = 0.04f; //The speed of the balls const float BALL_SPEED = 1.0f; //The ideal number of balls in play const int NUM_BALLS = 2; //The amount of time by which the state of the game is advanced in each call //to the game's step() method const float GAME_STEP_TIME = 0.01f; //Returns a random float from 0 to < 1 float randomFloat() { return (float)rand() / ((float)RAND_MAX + 1); } } Crab::Crab(float maximumSpeed1) { maximumSpeed = maximumSpeed1; pos0 = 0.5f; dir0 = 0; speed0 = 0; timeUntilNextStep = 0; } void Crab::step() { //Accelerate the crab float ds = CRAB_STEP_TIME * acceleration(); if (dir0 != 0) { speed0 += dir0 * ds; if (speed0 > maximumSpeed) { speed0 = maximumSpeed; } else if (speed0 < -maximumSpeed) { speed0 = -maximumSpeed; } } else { float s = abs(speed0); s -= ds; if (s < 0) { s = 0; } if (speed0 > 0) { speed0 = s; } else { speed0 = -s; } } //Move the crab pos0 += CRAB_STEP_TIME * speed0; if (pos0 < BARRIER_SIZE + CRAB_LENGTH / 2) { pos0 = BARRIER_SIZE + CRAB_LENGTH / 2; speed0 = 0; } else if (pos0 > 1 - BARRIER_SIZE - CRAB_LENGTH / 2) { pos0 = 1 - BARRIER_SIZE - CRAB_LENGTH / 2; speed0 = 0; } } float Crab::pos() { return pos0; } int Crab::dir() { return dir0; } float Crab::speed() { return speed0; } float Crab::acceleration() { return maximumSpeed / TIME_TO_MAXIMUM_SPEED; } void Crab::setDir(int dir1) { if (dir1 < 0) { dir0 = -1; } else if (dir1 > 0) { dir0 = 1; } else { dir0 = 0; } } void Crab::advance(float dt) { while (dt > 0) { if (timeUntilNextStep < dt) { dt -= timeUntilNextStep; step(); timeUntilNextStep = CRAB_STEP_TIME; } else { timeUntilNextStep -= dt; dt = 0; } } } Ball::Ball(float radius1, float x1, float z1, float angle1) { r = radius1; x0 = x1; z0 = z1; angle0 = angle1; fadeAmount0 = 0; isFadingOut0 = false; } float Ball::radius() { return r; } float Ball::x() { return x0; } float Ball::z() { return z0; } float Ball::angle() { return angle0; } void Ball::setAngle(float angle1) { angle0 = angle1; } float Ball::fadeAmount() { return fadeAmount0; } void Ball::fadeOut() { isFadingOut0 = true; } bool Ball::isFadingOut() { return isFadingOut0; } void Ball::advance(float dt) { if (isFadingOut0) { //Fade out fadeAmount0 -= dt / BALL_FADE_OUT_TIME; if (fadeAmount0 < 0) { fadeAmount0 = 0; } } else if (fadeAmount0 < 1) { //Fade in fadeAmount0 += dt / BALL_FADE_IN_TIME; if (fadeAmount0 > 1) { dt = (fadeAmount0 - 1) * BALL_FADE_IN_TIME; fadeAmount0 = 1; } else { dt = 0; } } if (dt <= 0) { return; } //Advance the position of the ball x0 += dt * cos(angle0) * BALL_SPEED; z0 += dt * sin(angle0) * BALL_SPEED; } Game::Game(float maximumSpeedForOpponents, int startingScore) { if (startingScore > 0) { crabs0[0] = new Crab(PLAYER_MAXIMUM_SPEED); for(int i = 1; i < 4; i++) { crabs0[i] = new Crab(maximumSpeedForOpponents); } } else { for(int i = 0; i < 4; i++) { crabs0[i] = NULL; } } for(int i = 0; i < 4; i++) { scores[i] = startingScore; } timeUntilNextStep = 0; } Game::~Game() { for(int i = 0; i < 4; i++) { if (crabs0[i] != NULL) { delete crabs0[i]; } } for(unsigned int i = 0; i < balls0.size(); i++) { delete balls0[i]; } } namespace { //Returns whether the point (dx, dz) lies within r units of (0, 0) bool intersectsCircle(float dx, float dz, float r) { return dx * dx + dz * dz < r * r; } //Returns whether a ball is colliding with a circle that is dx units to the //right and dz units inward from it, where r is the sum of the radius of the //ball and the radius of the circle and (vx, vz) is the velocity of the ball bool collisionWithCircle(float dx, float dz, float r, float vx, float vz) { return intersectsCircle(dx, dz, r) && vx * dx + vz * dz > 0; } //Returns the resultant angle when an object traveling at an angle of angle //bounces off of a wall whose normal is at an angle of normal. The returned //angle will be between 0 and 2 * PI. An angle of 0 indicates the positive //x direction, and an angle of PI / 2 indicates the positive z direction. float reflect(float angle, float normal) { angle = 2 * normal - PI - angle; while (angle < 0) { angle += 2 * PI; } while (angle > 2 * PI) { angle -= 2 * PI; } return angle; } //Adjusts the ball's angle in response to a collision with a circle at the //specified position void collideWithCircle(Ball* ball, float x, float z) { if (ball->fadeAmount() < 1) { return; } float dx = x - ball->x(); float dz = z - ball->z(); float normal = atan2(-dz, -dx); float newBallAngle = reflect(ball->angle(), normal); if (newBallAngle < 0) { newBallAngle += 2 * PI; } else if (newBallAngle > 2 * PI) { newBallAngle -= 2 * PI; } ball->setAngle(newBallAngle); } //Returns whether a crab at the indicated position has intercepted a ball at //the indicated position, where the positions are measured parallel to the //direction in which the crab moves bool collisionWithCrab(float crabPos, float ballPos) { return abs(crabPos - ballPos) < CRAB_LENGTH / 2; } //Adjusts the ball's angle in response to a collision with a crab. The //positions are measured parallel to the direction in which the crab moves, //and the crab's position is its distance from its center to the corner to //its right. void collideWithCrab(Ball* ball, int crabIndex, float crabPos, float ballPos) { float angle = (1 - crabIndex) * PI / 2 + MAX_CRAB_BOUNCE_ANGLE_OFFSET * (crabPos - ballPos) / (CRAB_LENGTH / 2); while (angle < 0) { angle += 2 * PI; } while (angle >= 2 * PI) { angle -= 2 * PI; } ball->setAngle(angle); } } void Game::handleCollisions() { for(unsigned int i = 0; i < balls0.size(); i++) { Ball* ball = balls0[i]; if (ball->fadeAmount() < 1 || ball->isFadingOut()) { continue; } //Ball-barrier collisions for(float z = 0; z < 2; z += 1) { for(float x = 0; x < 2; x += 1) { if (collisionWithCircle(x - ball->x(), z - ball->z(), ball->radius() + BARRIER_SIZE, BALL_SPEED * cos(ball->angle()), BALL_SPEED * sin(ball->angle()))) { collideWithCircle(ball, x, z); } } } //Ball-ball collisions for(unsigned int j = i + 1; j < balls0.size(); j++) { Ball* ball2 = balls0[j]; if (collisionWithCircle(ball2->x() - ball->x(), ball2->z() - ball->z(), ball->radius() + ball2->radius(), BALL_SPEED * (cos(ball->angle()) - cos(ball2->angle())), BALL_SPEED * (sin(ball->angle()) - sin(ball2->angle())))) { collideWithCircle(ball, ball2->x(), ball2->z()); collideWithCircle(ball2, ball->x(), ball->z()); } } //Ball-crab (and ball-pole) collisions int crabIndex; float ballPos; if (ball->z() < ball->radius()) { crabIndex = 0; ballPos = ball->x(); } else if (ball->x() < ball->radius()) { crabIndex = 1; ballPos = 1 - ball->z(); } else if (ball->z() > 1 - ball->radius()) { crabIndex = 2; ballPos = 1 - ball->x(); } else if (ball->x() > 1 - ball->radius()) { crabIndex = 3; ballPos = ball->z(); } else { crabIndex = -1; ballPos = 0; } if (crabIndex >= 0) { if (crabs0[crabIndex] != NULL) { float crabPos = crabs0[crabIndex]->pos(); if (collisionWithCrab(crabPos, ballPos)) { collideWithCrab(ball, crabIndex, crabPos, ballPos); } } else { float normal = (1 - crabIndex) * PI / 2; float newAngle = reflect(ball->angle(), normal); ball->setAngle(newAngle); } } } } namespace { //Returns the position at which the specified crab will stop if it //immediately starts decelerating float stopPos(Crab* crab) { float d = crab->speed() * crab->speed() / crab->acceleration(); if (crab->speed() > 0) { return crab->pos() + d; } else { return crab->pos() - d; } } } void Game::doAI() { for(int i = 1; i < 4; i++) { Crab* crab = crabs0[i]; if (crab == NULL) { continue; } //Find the position of the ball that is nearest the crab's side, and //store the result in targetPos float closestBallDist = 100; float targetPos = 0.5f; for(unsigned int j = 0; j < balls0.size(); j++) { Ball* ball = balls0[j]; float ballDist; float ballPos; switch(i) { case 1: ballDist = ball->x() - ball->radius(); ballPos = 1 - ball->z(); break; case 2: ballDist = 1 - ball->z() - ball->radius(); ballPos = 1 - ball->x(); break; case 3: ballDist = 1 - ball->x() - ball->radius(); ballPos = ball->z(); break; } if (ballDist < closestBallDist) { targetPos = ballPos; closestBallDist = ballDist; } } //Move toward targetPos. Stop so that the ball is in the middle 70% of //the crab. if (abs(stopPos(crab) - targetPos) < 0.7f * (CRAB_LENGTH / 2)) { crab->setDir(0); } else if (targetPos < crab->pos()) { crab->setDir(-1); } else { crab->setDir(1); } } } void Game::step() { //Advance the crabs for(int i = 0; i < 4; i++) { Crab* crab = crabs0[i]; if (crab != NULL) { crab->advance(GAME_STEP_TIME); } } //Advance the balls for(unsigned int i = 0; i < balls0.size(); i++) { balls0[i]->advance(GAME_STEP_TIME); } //Handle collisions handleCollisions(); //Check for balls that have scored on a player vector<Ball*> newBalls; for(unsigned int i = 0; i < balls0.size(); i++) { Ball* ball = balls0[i]; if (ball->fadeAmount() == 1 && !ball->isFadingOut()) { newBalls.push_back(ball); int scoredOn; if (ball->z() < ball->radius() && (ball->angle() > PI)) { scoredOn = 0; } else if (ball->x() < ball->radius() && (ball->angle() > PI / 2 && ball->angle() < 3 * PI / 2)) { scoredOn = 1; } else if (ball->z() > 1 - ball->radius() && (ball->angle() < PI)) { scoredOn = 2; } else if (ball->x() > 1 - ball->radius() && (ball->angle() < PI / 2 || ball->angle() > 3 * PI / 2)) { scoredOn = 3; } else { scoredOn = -1; } if (scoredOn >= 0 && crabs0[scoredOn] != NULL) { scores[scoredOn]--; if (scores[scoredOn] == 0) { delete crabs0[scoredOn]; crabs0[scoredOn] = NULL; } ball->fadeOut(); } } else if (ball->fadeAmount() > 0 || !ball->isFadingOut()) { newBalls.push_back(ball); } else { delete ball; } } balls0 = newBalls; //Check whether the game is over bool isGameOver; if (crabs0[0] != NULL) { isGameOver = true; for(int i = 1; i < 4; i++) { if (crabs0[i] != NULL) { isGameOver = false; } } } else { isGameOver = true; } if (!isGameOver) { //Try to get to NUM_BALLS balls while (balls0.size() < (unsigned int)NUM_BALLS) { //Try to place a ball at the center of the board bool ballFits = true; for(unsigned int i = 0; i < balls0.size(); i++) { Ball* ball = balls0[i]; if (intersectsCircle(ball->x() - 0.5f, ball->z() - 0.5f, 2 * BALL_RADIUS)) { ballFits = false; break; } } if (ballFits) { Ball* ball = new Ball(BALL_RADIUS, 0.5f, 0.5f, 2 * PI * randomFloat()); balls0.push_back(ball); } else { break; } } } else { for(unsigned int i = 0; i < balls0.size(); i++) { balls0[i]->fadeOut(); } } //Run the AI for the computer-controlled crabs doAI(); } void Game::setPlayerCrabDir(int dir) { if (crabs0[0] != NULL) { crabs0[0]->setDir(dir); } } int Game::score(int crabNum) { return scores[crabNum]; } void Game::advance(float dt) { while (dt > 0) { if (timeUntilNextStep < dt) { dt -= timeUntilNextStep; step(); timeUntilNextStep = CRAB_STEP_TIME; } else { timeUntilNextStep -= dt; dt = 0; } } } Crab** Game::crabs() { return crabs0; } vector<Ball*> Game::balls() { return balls0; }
22.37401
80
0.610993
[ "object", "vector" ]
20733be961edfbd10a103e6f19371751a1b886cc
3,401
cpp
C++
gym/102433/A.cpp
albexl/codeforces-gym-submissions
2a51905c50fcf5d7f417af81c4c49ca5217d0753
[ "MIT" ]
1
2021-07-16T19:59:39.000Z
2021-07-16T19:59:39.000Z
gym/102433/A.cpp
albexl/codeforces-gym-submissions
2a51905c50fcf5d7f417af81c4c49ca5217d0753
[ "MIT" ]
null
null
null
gym/102433/A.cpp
albexl/codeforces-gym-submissions
2a51905c50fcf5d7f417af81c4c49ca5217d0753
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #include <random> #include <chrono> using namespace std; using namespace __gnu_pbds; #define endl '\n' typedef long long ll; typedef pair<int, int> pii; //typedef tree<int,null_type,less<int>,rb_tree_tag, tree_order_statistics_node_update> indexed_set; const ll oo = 1e16; const int maxn = 1e5 + 5; struct segment_tree{ vector<ll> st, lazy; segment_tree(int n) : st(4 * n), lazy(4 * n){ } void add_lazy(int node, int b, int e, ll x){ lazy[node] += x; st[node] += 1ll * x * (e - b + 1); } void push(int node, int b, int e){ if(!lazy[node] || b == e) return; int m = (b + e) >> 1; int l = node << 1; int r = l | 1; add_lazy(l, b, m, lazy[node]); add_lazy(r, m + 1, e, lazy[node]); lazy[node] = 0; } ll query(int node, int b, int e, int i, int j){ if(b >= i && e <= j) return st[node]; if(b > j || e < i) return 0; push(node, b, e); int m = (b + e) >> 1; int l = node << 1; int r = l | 1; ll L = query(l, b, m, i, j); ll R = query(r, m + 1, e, i, j); return L + R; } void update(int node, int b, int e, int i, int j, ll x){ if(b >= i && e <= j){ add_lazy(node, b, e, x); return; } if(b > j || e < i) return; push(node, b, e); int m = (b + e) >> 1; int l = node << 1; int r = l | 1; update(l, b, m, i, j, x); update(r, m + 1, e, i, j, x); st[node] = st[l] + st[r]; } }; vector<pair<int, ll>> g[maxn]; ll dst[maxn], A[maxn], B[maxn], T[maxn], dp_down[maxn], dp_up[maxn], sum[maxn], total = 0; int lo[maxn], hi[maxn], inv[maxn], t = 1, n; void dfs1(int u, int p){ for(auto &e : g[u]){ int v = e.first; ll c = e.second; if(v != p){ dfs1(v, u); dp_down[u] += dp_down[v]; dp_down[u] += sum[v] * c; sum[u] += sum[v]; } } sum[u] += T[u]; } void dfs2(int u, int p, ll w){ if(p){ ll x = dp_up[p] + dp_down[p]; x -= sum[u] * w; x -= dp_down[u]; dp_up[u] = x + (total - sum[u]) * w; } for(auto &e : g[u]){ int v = e.first; ll c = e.second; if(v != p){ dfs2(v, u, c); } } } void dfs(int u, int p){ lo[u] = t; inv[t] = u; t++; for(auto &e : g[u]){ int v = e.first; ll c = e.second; if(v != p){ dst[v] = dst[u] + c; dfs(v, u); } } hi[u] = t - 1; } void solve(int u, int p, segment_tree &st){ A[u] = st.query(1, 1, n, 1, n) * T[u]; for(auto &e : g[u]){ int v = e.first; ll c = e.second; if(v != p){ st.update(1, 1, n, 1, n, c); st.update(1, 1, n, lo[v], hi[v], -2ll * c); solve(v, u, st); st.update(1, 1, n, lo[v], hi[v], 2ll * c); st.update(1, 1, n, 1, n, -c); } } } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); //freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); //mt19937 rng(5); //srand(time(0)); cin >> n; for(int i = 1; i <= n; i++){ cin >> T[i]; total += T[i]; } for(int i = 1; i < n; ++i){ int a, b; ll c; cin >> a >> b >> c; g[a].push_back({b, c}); g[b].push_back({a, c}); } segment_tree st(n); dfs(1, 0); for(int i = 1; i <= n; i++) st.update(1, 1, n, i, i, dst[i]); solve(1, 0, st); //cerr << "here" << endl; dfs1(1, 0); //cerr << "here" << endl; dfs2(1, 0, 0); for(int i = 1; i <= n; i++) cout << A[i] + dp_down[i] + dp_up[i] << endl; return 0; }
16.590244
99
0.490444
[ "vector" ]
207811f6375e6b6457342390b9dc276175d50bb5
1,581
cc
C++
tensorstore/internal/string_like_test.cc
stuarteberg/tensorstore
2c22a3c9f798b0fbf023031633c58cc7c644235d
[ "Apache-2.0" ]
null
null
null
tensorstore/internal/string_like_test.cc
stuarteberg/tensorstore
2c22a3c9f798b0fbf023031633c58cc7c644235d
[ "Apache-2.0" ]
null
null
null
tensorstore/internal/string_like_test.cc
stuarteberg/tensorstore
2c22a3c9f798b0fbf023031633c58cc7c644235d
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 The TensorStore Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "tensorstore/internal/string_like.h" #include <string> #include <vector> #include <gtest/gtest.h> #include "absl/strings/string_view.h" namespace { using tensorstore::internal::StringLikeSpan; TEST(StringLikeSpan, Default) { StringLikeSpan x; EXPECT_EQ(0, x.size()); } TEST(StringLikeSpan, CStrings) { std::vector<const char*> c_strings{"a", "b", "c"}; StringLikeSpan x(c_strings); EXPECT_EQ(3, x.size()); EXPECT_EQ("a", x[0]); EXPECT_EQ("b", x[1]); EXPECT_EQ("c", x[2]); } TEST(StringLikeSpan, StdStrings) { std::vector<std::string> std_strings{"a", "b", "c"}; StringLikeSpan x(std_strings); EXPECT_EQ(3, x.size()); EXPECT_EQ("a", x[0]); EXPECT_EQ("b", x[1]); EXPECT_EQ("c", x[2]); } TEST(StringLikeSpan, StringViews) { std::vector<absl::string_view> string_views{"a", "b", "c"}; StringLikeSpan x(string_views); EXPECT_EQ(3, x.size()); EXPECT_EQ("a", x[0]); EXPECT_EQ("b", x[1]); EXPECT_EQ("c", x[2]); } } // namespace
26.35
75
0.68754
[ "vector" ]
208add2d4665cb77d54ee3a843175b5f5575bf15
26,975
cp
C++
Std/Mod/Coder.cp
romiras/Blackbox-fw-playground
6de94dc65513e657a9b86c1772e2c07742b608a8
[ "BSD-2-Clause" ]
1
2016-03-17T08:27:05.000Z
2016-03-17T08:27:05.000Z
Std/Mod/Coder.cps
Spirit-of-Oberon/LightBox
8a45ed11dcc02ae97e86f264dcee3e07c910ff9d
[ "BSD-2-Clause" ]
null
null
null
Std/Mod/Coder.cps
Spirit-of-Oberon/LightBox
8a45ed11dcc02ae97e86f264dcee3e07c910ff9d
[ "BSD-2-Clause" ]
1
2018-03-14T17:53:27.000Z
2018-03-14T17:53:27.000Z
MODULE StdCoder; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = "" issues = "" **) IMPORT Kernel, Files, Converters, Stores, Views, Controllers, Dialog, Documents, Windows, TextModels, TextViews, TextControllers, TextMappers, StdCmds; CONST N = 16384; LineLength = 74; OldVersion = 0; ThisVersion = 1; Tag = "StdCoder.Decode"; (* first letter of Tag must not to appear within Tag again *) Separator = "/"; View = 1; File = 2; List = 3; TYPE FileList = POINTER TO RECORD next: FileList; file: Files.File; type: Files.Type; name:Dialog.String END; ParList* = RECORD list*: Dialog.Selection; storeAs*: Dialog.String; files: FileList END; VAR par*: ParList; code: ARRAY 64 OF CHAR; revCode: ARRAY 256 OF BYTE; table: ARRAY N OF BYTE; stdDocuType: Files.Type; PROCEDURE NofSelections(IN list: Dialog.Selection): INTEGER; VAR i, n: INTEGER; BEGIN i := 0; n := 0; WHILE i # list.len DO IF list.In(i) THEN INC(n) END; INC(i) END; RETURN n END NofSelections; PROCEDURE ShowError(n: INTEGER; par: ARRAY OF CHAR); BEGIN Dialog.Beep; CASE n OF 1: Dialog.ShowParamMsg("#Std:bad characters", par, "", "") | 2: Dialog.ShowParamMsg("#Std:checksum error", par, "", "") | 3: Dialog.ShowParamMsg("#Std:incompatible version", par, "", "") | 4: Dialog.ShowParamMsg("#Std:filing error", par, "", "") | 5: Dialog.ShowParamMsg("#Std:directory ^0 not found", par, "", "") | 6: Dialog.ShowParamMsg("#Std:file ^0 not found", par, "", "") | 7: Dialog.ShowParamMsg("#Std:illegal path", par, "", "") | 8: Dialog.ShowParamMsg("#Std:no tag", par, "", "") | 9: Dialog.ShowParamMsg("#Std:disk write protected", par, "", "") | 10: Dialog.ShowParamMsg("#Std:io error", par, "", "") END END ShowError; PROCEDURE ShowSizeMsg(x: INTEGER); VAR i, j: INTEGER; ch: CHAR; s: ARRAY 20 OF CHAR; BEGIN ASSERT(x >= 0, 20); i := 0; REPEAT s[i] := CHR(ORD("0") + x MOD 10); INC(i); x := x DIV 10 UNTIL x = 0; s[i] := 0X; DEC(i); j := 0; WHILE j < i DO ch := s[j]; s[j] := s[i]; s[i] := ch; INC(j); DEC(i) END; Dialog.ShowParamStatus("#Std:^0 characters coded", s, "", "") END ShowSizeMsg; PROCEDURE Write(dest: TextModels.Writer; x: INTEGER; VAR n: INTEGER); BEGIN dest.WriteChar(code[x]); INC(n); IF n = LineLength THEN dest.WriteChar(0DX); dest.WriteChar(" "); n := 0 END END Write; PROCEDURE WriteHeader(dest: TextModels.Writer; VAR n: INTEGER; name: ARRAY OF CHAR; type: BYTE ); VAR byte, bit, i: INTEGER; ch: CHAR; tag: ARRAY 16 OF CHAR; BEGIN tag := Tag; i := 0; ch := tag[0]; WHILE ch # 0X DO dest.WriteChar(ch); INC(n); INC(i); ch := tag[i] END; dest.WriteChar(" "); INC(n); bit := 0; byte := 0; i := 0; REPEAT ch := name[i]; INC(byte, ASH(ORD(ch), bit)); INC(bit, 8); WHILE bit >= 6 DO Write(dest, byte MOD 64, n); byte := byte DIV 64; DEC(bit, 6) END; INC(i) UNTIL ch = 0X; IF bit # 0 THEN Write(dest, byte, n) END; Write(dest, ThisVersion, n); Write(dest, type, n) END WriteHeader; PROCEDURE WriteFileType(dest: TextModels.Writer; VAR n: INTEGER; t: Files.Type); VAR byte, bit, i: INTEGER; ch: CHAR; BEGIN IF t = Kernel.docType THEN t := stdDocuType END; bit := 0; byte := 0; i := 0; dest.WriteChar(" "); REPEAT ch := t[i]; INC(byte, ASH(ORD(ch), bit)); INC(bit, 8); WHILE bit >= 6 DO Write(dest, byte MOD 64, n); byte := byte DIV 64; DEC(bit, 6) END; INC(i) UNTIL ch = 0X; IF bit # 0 THEN Write(dest, byte, n) END END WriteFileType; PROCEDURE WriteFile(dest: TextModels.Writer; VAR n: INTEGER; f: Files.File); VAR hash, byte, bit, i, j, sum, len: INTEGER; src: Files.Reader; b: BYTE; BEGIN len := f.Length(); j := len; i := 6; WHILE i # 0 DO Write(dest, j MOD 64, n); j := j DIV 64; DEC(i) END; i := 0; REPEAT table[i] := 0; INC(i) UNTIL i = N; hash := 0; bit := 0; byte := 0; sum := 0; src := f.NewReader(NIL); WHILE len # 0 DO src.ReadByte(b); DEC(len); sum := (sum + b MOD 256) MOD (16 * 1024); IF table[hash] = b THEN INC(bit) (* 0 bit for correct prediction *) ELSE (* Incorrect prediction -> 1'xxxx'xxxx bits *) table[hash] := b; INC(byte, ASH(1, bit)); INC(bit); INC(byte, ASH(b MOD 256, bit)); INC(bit, 8) END; WHILE bit >= 6 DO Write(dest, byte MOD 64, n); byte := byte DIV 64; DEC(bit, 6) END; hash := (16 * hash + b MOD 256) MOD N END; IF bit # 0 THEN Write(dest, byte, n) END; i := 6; WHILE i # 0 DO Write(dest, sum MOD 64, n); sum := sum DIV 64; DEC(i) END; IF n # 0 THEN dest.WriteChar(0DX); n := 0 END END WriteFile; PROCEDURE Read(src: TextModels.Reader; VAR x: INTEGER; VAR res: INTEGER); VAR ch: CHAR; BEGIN IF res = 0 THEN REPEAT src.ReadChar(ch); x := revCode[ORD(ch)] UNTIL (x >= 0) OR src.eot; IF src.eot THEN res := 1 END END; IF res # 0 THEN x := 0 END END Read; PROCEDURE ReadHeader(src: TextModels.Reader; VAR res: INTEGER; VAR name: ARRAY OF CHAR; VAR type: BYTE ); VAR x, bit, i, j: INTEGER; ch: CHAR; tag: ARRAY 16 OF CHAR; BEGIN tag := Tag; i := 0; WHILE ~src.eot & (tag[i] # 0X) DO src.ReadChar(ch); IF ch = tag[i] THEN INC(i) ELSIF ch = tag[0] THEN i := 1 ELSE i := 0 END END; IF ~src.eot THEN res := 0; i := 0; bit := 0; x := 0; REPEAT WHILE (res = 0) & (bit < 8) DO Read(src, j, res); INC(x, ASH(j, bit)); INC(bit, 6) END; IF res = 0 THEN ch := CHR(x MOD 256); x := x DIV 256; DEC(bit, 8); name[i] := ch; INC(i) END UNTIL (res # 0) OR (ch = 0X); Read(src, j, res); IF res = 0 THEN IF (j = ThisVersion) OR (j = OldVersion) THEN Read(src, j, res); type := SHORT(SHORT(j)) ELSE res := 3 END END ELSE res := 8 END END ReadHeader; PROCEDURE ReadFileType(src: TextModels.Reader; VAR res: INTEGER; VAR ftype: Files.Type); VAR x, bit, i, j: INTEGER; ch: CHAR; BEGIN res := 0; i := 0; bit := 0; x := 0; REPEAT WHILE (res = 0) & (bit < 8) DO Read(src, j, res); INC(x, ASH(j, bit)); INC(bit, 6) END; IF res = 0 THEN ch := CHR(x MOD 256); x := x DIV 256; DEC(bit, 8); ftype[i] := ch; INC(i) END UNTIL (res # 0) OR (ch = 0X); IF ftype = stdDocuType THEN ftype := Kernel.docType END END ReadFileType; PROCEDURE ReadFile(src: TextModels.Reader; VAR res: INTEGER; f: Files.File); VAR hash, x, bit, i, j, len, sum, s: INTEGER; byte: BYTE; dest: Files.Writer; BEGIN res := 0; i := 0; len := 0; REPEAT Read(src, x, res); len := len + ASH(x, 6 * i); INC(i) UNTIL (res # 0) OR (i = 6); i := 0; REPEAT table[i] := 0; INC(i) UNTIL i = N; bit := 0; hash := 0; sum := 0; dest := f.NewWriter(NIL); WHILE (res = 0) & (len # 0) DO IF bit = 0 THEN Read(src, x, res); bit := 6 END; IF ODD(x) THEN (* Incorrect prediction -> 1'xxxx'xxxx *) x := x DIV 2; DEC(bit); WHILE (res = 0) & (bit < 8) DO Read(src, j, res); INC(x, ASH(j, bit)); INC(bit, 6) END; i := x MOD 256; IF i > MAX(BYTE) THEN i := i - 256 END; byte := SHORT(SHORT(i)); x := x DIV 256; DEC(bit, 8); table[hash] := byte ELSE byte := table[hash]; x := x DIV 2; DEC(bit) (* correct prediction *) END; hash := (16 * hash + byte MOD 256) MOD N; dest.WriteByte(byte); sum := (sum + byte MOD 256) MOD (16 * 1024); DEC(len) END; IF res = 0 THEN i := 0; s := 0; REPEAT Read(src, x, res); s := s + ASH(x, 6 * i); INC(i) UNTIL (res # 0) OR (i = 6); IF (res = 0) & (s # sum) THEN res := 2 END END END ReadFile; PROCEDURE ShowText (t: TextModels.Model); VAR l: INTEGER; v: Views.View; wr: TextMappers.Formatter; conv: Converters.Converter; BEGIN l := t.Length(); wr.ConnectTo(t); wr.SetPos(l); wr.WriteString(" --- end of encoding ---"); ShowSizeMsg(l); v := TextViews.dir.New(t); conv := Converters.list; WHILE (conv # NIL) & (conv.imp # "HostTextConv.ImportText") DO conv := conv.next END; Views.Open(v, NIL, "", conv); Views.SetDirty(v) END ShowText; PROCEDURE EncodedView*(v: Views.View): TextModels.Model; VAR n: INTEGER; f: Files.File; wrs: Stores.Writer; t: TextModels.Model; wr: TextModels.Writer; BEGIN f := Files.dir.Temp(); wrs.ConnectTo(f); Views.WriteView(wrs, v); t := TextModels.dir.New(); wr := t.NewWriter(NIL); n := 0; WriteHeader(wr, n, "", View); WriteFileType(wr, n, f.type); WriteFile(wr, n, f); RETURN t END EncodedView; PROCEDURE EncodeDocument*; VAR v: Views.View; w: Windows.Window; BEGIN w := Windows.dir.First(); IF w # NIL THEN v := w.doc.OriginalView(); IF (v.context # NIL) & (v.context IS Documents.Context) THEN v := v.context(Documents.Context).ThisDoc() END; IF v # NIL THEN ShowText(EncodedView(v)) END END END EncodeDocument; PROCEDURE EncodeFocus*; VAR v: Views.View; BEGIN v := Controllers.FocusView(); IF v # NIL THEN ShowText(EncodedView(v)) END END EncodeFocus; PROCEDURE EncodeSelection*; VAR beg, end: INTEGER; t: TextModels.Model; c: TextControllers.Controller; BEGIN c := TextControllers.Focus(); IF (c # NIL) & c.HasSelection() THEN c.GetSelection(beg, end); t := TextModels.CloneOf(c.text); t.InsertCopy(0, c.text, beg, end); ShowText(EncodedView(TextViews.dir.New(t))) END END EncodeSelection; PROCEDURE EncodeFile*; VAR n: INTEGER; loc: Files.Locator; name: Files.Name; f: Files.File; t: TextModels.Model; wr: TextModels.Writer; BEGIN Dialog.GetIntSpec("", loc, name); IF loc # NIL THEN f := Files.dir.Old(loc, name, TRUE); IF f # NIL THEN t := TextModels.dir.New(); wr := t.NewWriter(NIL); n := 0; WriteHeader(wr, n, name, File); WriteFileType(wr, n, f.type); WriteFile(wr, n, f); ShowText(t) END END END EncodeFile; PROCEDURE GetFile(VAR path: ARRAY OF CHAR; VAR loc: Files.Locator; VAR name: Files.Name); VAR i, j: INTEGER; ch: CHAR; BEGIN i := 0; ch := path[0]; loc := Files.dir.This(""); WHILE (ch # 0X) & (loc # NIL) DO j := 0; WHILE (ch # 0X) & (ch # Separator) DO name[j] := ch; INC(j); INC(i); ch := path[i] END; name[j] := 0X; IF ch = Separator THEN loc := loc.This(name); INC(i); ch := path[i] END; IF loc.res # 0 THEN loc := NIL END END; path[i] := 0X END GetFile; PROCEDURE ReadPath(rd: TextModels.Reader; VAR path: ARRAY OF CHAR; VAR len: INTEGER); VAR i, l: INTEGER; ch: CHAR; BEGIN i := 0; l := LEN(path) - 1; REPEAT rd.ReadChar(ch) UNTIL rd.eot OR (ch > " "); WHILE ~rd.eot & (ch > " ") & (i < l) DO path[i] := ch; INC(i); rd.ReadChar(ch) END; path[i] := 0X; len := i END ReadPath; PROCEDURE WriteString(w: Files.Writer; IN str: ARRAY OF CHAR; len: INTEGER); VAR i: INTEGER; BEGIN i := 0; WHILE i < len DO IF ORD(str[i]) > MAX(BYTE) THEN w.WriteByte(SHORT(SHORT(ORD(str[i]) - 256))) ELSE w.WriteByte(SHORT(SHORT(ORD(str[i])))) END; INC(i) END END WriteString; PROCEDURE EncodeFileList*; TYPE FileList = POINTER TO RECORD next: FileList; f: Files.File END; VAR beg, end, i, j, n: INTEGER; err: BOOLEAN; files, last: FileList; list, f: Files.File; w: Files.Writer; loc: Files.Locator; rd: TextModels.Reader; wr: TextModels.Writer; t: TextModels.Model; c: TextControllers.Controller; name: Files.Name; path, next: ARRAY 2048 OF CHAR; BEGIN c := TextControllers.Focus(); IF (c # NIL) & c.HasSelection() THEN c.GetSelection(beg, end); rd := c.text.NewReader(NIL); rd.SetPos(beg); err := FALSE; list := Files.dir.Temp(); w := list.NewWriter(NIL); files := NIL; last := NIL; ReadPath(rd, path, i); WHILE (path # "") & (rd.Pos() - i < end) & ~err DO GetFile(path, loc, name); IF loc # NIL THEN f := Files.dir.Old(loc, name, TRUE); err := f = NIL; IF ~err THEN IF last = NIL THEN NEW(last); files := last ELSE NEW(last.next); last := last.next END; last.f := f; ReadPath(rd, next, j); IF (next = "=>") & (rd.Pos() - j < end) THEN ReadPath(rd, next, j); IF next # "" THEN WriteString(w, next, j + 1); ReadPath(rd, next, j) ELSE err := TRUE END ELSE WriteString(w, path, i + 1) END; path := next; i := j END ELSE err := TRUE END END; IF ~err & (files # NIL) THEN t := TextModels.dir.New(); wr := t.NewWriter(NIL); n := 0; WriteHeader(wr, n, "", List); WriteFileType(wr, n, list.type); WriteFile(wr, n, list); WHILE files # NIL DO WriteFileType(wr, n, files.f.type); WriteFile(wr, n, files.f); files := files.next END; ShowText(t) ELSIF err THEN IF path = "" THEN ShowError(7, path) ELSIF loc # NIL THEN ShowError(6, path) ELSE ShowError(5, path) END END END END EncodeFileList; PROCEDURE DecodeView(rd: TextModels.Reader; name: Files.Name); VAR res: INTEGER; f: Files.File; ftype: Files.Type; rds: Stores.Reader; v: Views.View; BEGIN ReadFileType(rd, res, ftype); IF res = 0 THEN f := Files.dir.Temp(); ReadFile(rd, res, f); IF res = 0 THEN rds.ConnectTo(f); Views.ReadView(rds, v); Views.Open(v, NIL, name, NIL); Views.SetDirty(v) ELSE ShowError(res, "") END ELSE ShowError(res, "") END END DecodeView; PROCEDURE DecodeFile(rd: TextModels.Reader; name: Files.Name); VAR res: INTEGER; ftype: Files.Type; loc: Files.Locator; f: Files.File; BEGIN ReadFileType(rd, res, ftype); IF res = 0 THEN Dialog.GetExtSpec(name, ftype, loc, name); IF loc # NIL THEN f := Files.dir.New(loc, Files.ask); IF f # NIL THEN ReadFile(rd, res, f); IF res = 0 THEN f.Register(name, ftype, Files.ask, res); IF res # 0 THEN ShowError(4, "") END ELSE ShowError(res, "") END ELSIF loc.res = 4 THEN ShowError(9, "") ELSIF loc.res = 5 THEN ShowError(10, "") END END ELSE ShowError(res, "") END END DecodeFile; PROCEDURE DecodeFileList (rd: TextModels.Reader; VAR files: FileList; VAR len, res: INTEGER); VAR i, n: INTEGER; b: BYTE; p: FileList; ftype: Files.Type; f: Files.File; frd: Files.Reader; path: Dialog.String; BEGIN ReadFileType(rd, res, ftype); IF res = 0 THEN f := Files.dir.Temp(); ReadFile(rd, res, f); IF res = 0 THEN files := NIL; p := NIL; n := 0; frd := f.NewReader(NIL); frd.ReadByte(b); WHILE ~frd.eof & (res = 0) DO INC(n); i := 0; WHILE ~frd.eof & (b # 0) DO path[i] := CHR(b MOD 256); INC(i); frd.ReadByte(b) END; IF (i > 4) & (path[i - 4] = ".") & (CAP(path[i - 3]) = "O") & (CAP(path[i - 2]) = "D") & (CAP(path[i - 1]) = "C") THEN path[i - 4] := 0X ELSE path[i] := 0X END; IF ~frd.eof THEN IF p = NIL THEN NEW(p); files := p ELSE NEW(p.next); p := p.next END; p.name := path; frd.ReadByte(b) ELSE res := 1 END END; p := files; len := n; WHILE (res = 0) & (p # NIL) DO ReadFileType(rd, res, p.type); IF res = 0 THEN p.file := Files.dir.Temp(); ReadFile(rd, res, p.file) END; p := p.next END END END END DecodeFileList; PROCEDURE OpenDialog(files: FileList; len: INTEGER); VAR i: INTEGER; p: FileList; BEGIN par.files := files; par.list.SetLen(len); p := files; i := 0; WHILE p # NIL DO par.list.SetItem(i, p.name); INC(i); p := p.next END; par.storeAs := ""; Dialog.Update(par); Dialog.UpdateList(par.list); StdCmds.OpenAuxDialog("Std/Rsrc/Coder", "Decode") END OpenDialog; PROCEDURE CloseDialog*; BEGIN par.files := NIL; par.list.SetLen(0); par.storeAs := ""; Dialog.UpdateList(par.list); Dialog.Update(par) END CloseDialog; PROCEDURE Select*(op, from, to: INTEGER); VAR p: FileList; i: INTEGER; BEGIN IF (op = Dialog.included) OR (op = Dialog.excluded) OR (op = Dialog.set) THEN IF NofSelections(par.list) = 1 THEN i := 0; p := par.files; WHILE ~par.list.In(i) DO INC(i); p := p.next END; par.storeAs := p.name ELSE par.storeAs := "" END; Dialog.Update(par) END END Select; PROCEDURE CopyFile(from: Files.File; loc: Files.Locator; name: Files.Name; type: Files.Type); CONST BufSize = 4096; VAR res, k, l: INTEGER; f: Files.File; r: Files.Reader; w: Files.Writer; buf: ARRAY BufSize OF BYTE; BEGIN f := Files.dir.New(loc, Files.ask); IF f # NIL THEN r := from.NewReader(NIL); w := f.NewWriter(NIL); l := from.Length(); WHILE l # 0 DO IF l <= BufSize THEN k := l ELSE k := BufSize END; r.ReadBytes(buf, 0, k); w.WriteBytes(buf, 0, k); l := l - k END; f.Register(name, type, Files.ask, res); IF res # 0 THEN ShowError(4, "") END ELSIF loc.res = 4 THEN ShowError(9, "") ELSIF loc.res = 5 THEN ShowError(10, "") END END CopyFile; PROCEDURE StoreSelection*; VAR i, n: INTEGER; p: FileList; loc: Files.Locator; name: Files.Name; BEGIN n := NofSelections(par.list); IF n > 1 THEN i := 0; p := par.files; WHILE n # 0 DO WHILE ~par.list.In(i) DO INC(i); p := p.next END; GetFile(p.name, loc, name); CopyFile(p.file, loc, name, p.type); DEC(n); INC(i); p := p.next END ELSIF (n = 1) & (par.storeAs # "") THEN i := 0; p := par.files; WHILE ~par.list.In(i) DO INC(i); p := p.next END; GetFile(par.storeAs, loc, name); CopyFile(p.file, loc, name, p.type) END END StoreSelection; PROCEDURE StoreSelectionGuard*(VAR p: Dialog.Par); VAR n: INTEGER; BEGIN n := NofSelections(par.list); p.disabled := (n = 0) OR ((n = 1) & (par.storeAs = "")) END StoreSelectionGuard; PROCEDURE StoreSingle*; VAR i: INTEGER; p: FileList; loc: Files.Locator; name: Files.Name; BEGIN IF NofSelections(par.list) = 1 THEN i := 0; p := par.files; WHILE ~par.list.In(i) DO INC(i); p := p.next END; GetFile(p.name, loc, name); Dialog.GetExtSpec(name, p.type, loc, name); IF loc # NIL THEN CopyFile(p.file, loc, name, p.type) END END END StoreSingle; PROCEDURE StoreSingleGuard*(VAR p: Dialog.Par); BEGIN p.disabled := NofSelections(par.list) # 1 END StoreSingleGuard; PROCEDURE StoreAllFiles(files: FileList); VAR loc: Files.Locator; name: Files.Name; BEGIN WHILE files # NIL DO GetFile(files.name, loc, name); CopyFile(files.file, loc, name, files.type); files := files.next END END StoreAllFiles; PROCEDURE StoreAll*; BEGIN StoreAllFiles(par.files) END StoreAll; PROCEDURE DecodeAllFromText*(text: TextModels.Model; beg: INTEGER; ask: BOOLEAN); VAR res, i: INTEGER; type: BYTE; name: Files.Name; rd: TextModels.Reader; files: FileList; BEGIN CloseDialog; rd := text.NewReader(NIL); rd.SetPos(beg); ReadHeader(rd, res, name, type); i := 0; WHILE name[i] # 0X DO INC(i) END; IF (i > 4) & (name[i - 4] = ".") & (CAP(name[i - 3]) = "O") & (CAP(name[i - 2]) = "D") & (CAP(name[i - 1]) = "C") THEN name[i - 4] := 0X END; IF res = 0 THEN IF type = View THEN DecodeView(rd, name) ELSIF type = File THEN DecodeFile(rd, name) ELSIF type = List THEN DecodeFileList(rd, files, i, res); IF res = 0 THEN IF ask THEN OpenDialog(files, i) ELSE StoreAllFiles(files) END ELSE ShowError(res, "") END ELSE ShowError(3, "") END ELSE ShowError(res, "") END END DecodeAllFromText; PROCEDURE Decode*; VAR beg, end: INTEGER; c: TextControllers.Controller; BEGIN CloseDialog; c := TextControllers.Focus(); IF c # NIL THEN IF c.HasSelection() THEN c.GetSelection(beg, end) ELSE beg := 0 END; DecodeAllFromText(c.text, beg, TRUE) END END Decode; PROCEDURE ListFiles(rd: TextModels.Reader; VAR wr: TextMappers.Formatter); VAR i, n, res: INTEGER; b: BYTE; ftype: Files.Type; f: Files.File; frd: Files.Reader; path: Dialog.String; BEGIN ReadFileType(rd, res, ftype); IF res = 0 THEN f := Files.dir.Temp(); ReadFile(rd, res, f); IF res = 0 THEN n := 0; frd := f.NewReader(NIL); frd.ReadByte(b); WHILE ~frd.eof & (res = 0) DO INC(n); i := 0; WHILE ~frd.eof & (b # 0) DO path[i] := CHR(b MOD 256); INC(i); frd.ReadByte(b) END; IF (i > 4) & (path[i - 4] = ".") & (CAP(path[i - 3]) = "O") & (CAP(path[i - 2]) = "D") & (CAP(path[i - 1]) = "C") THEN path[i - 4] := 0X ELSE path[i] := 0X END; IF ~frd.eof THEN wr.WriteString(path); wr.WriteLn; frd.ReadByte(b) ELSE res := 1 END END ELSE ShowError(res, "") END ELSE ShowError(res, "") END END ListFiles; PROCEDURE ListSingleton(type, name: ARRAY OF CHAR; VAR wr: TextMappers.Formatter); BEGIN wr.WriteString(type); IF name # "" THEN wr.WriteString(": '"); wr.WriteString(name); wr.WriteChar("'") END; wr.WriteLn END ListSingleton; PROCEDURE EncodedInText*(text: TextModels.Model; beg: INTEGER): TextModels.Model; VAR res, i: INTEGER; type: BYTE; name: Files.Name; rd: TextModels.Reader; report: TextModels.Model; wr: TextMappers.Formatter; BEGIN report := TextModels.dir.New(); wr.ConnectTo(report); rd := text.NewReader(NIL); rd.SetPos(beg); ReadHeader(rd, res, name, type); i := 0; WHILE name[i] # 0X DO INC(i) END; IF (i > 4) & (name[i - 4] = ".") & (CAP(name[i - 3]) = "O") & (CAP(name[i - 2]) = "D") & (CAP(name[i - 1]) = "C") THEN name[i - 4] := 0X END; IF res = 0 THEN IF type = View THEN ListSingleton("View", name, wr) ELSIF type = File THEN ListSingleton("File", name, wr) ELSIF type = List THEN ListFiles(rd, wr) ELSE ShowError(3, "") END ELSE ShowError(res, "") END; RETURN report END EncodedInText; PROCEDURE ListEncodedMaterial*; VAR beg, end: INTEGER; c: TextControllers.Controller; BEGIN c := TextControllers.Focus(); IF c # NIL THEN IF c.HasSelection() THEN c.GetSelection(beg, end) ELSE beg := 0 END; Views.OpenView(TextViews.dir.New(EncodedInText(c.text, beg))) END END ListEncodedMaterial; PROCEDURE InitCodes; VAR i: BYTE; j: INTEGER; BEGIN j := 0; WHILE j # 256 DO revCode[j] := -1; INC(j) END; code[0] := "."; revCode[ORD(".")] := 0; code[1] := ","; revCode[ORD(",")] := 1; i := 2; j := ORD("0"); WHILE j <= ORD("9") DO code[i] := CHR(j); revCode[j] := i; INC(i); INC(j) END; j := ORD("A"); WHILE j <= ORD("Z") DO code[i] := CHR(j); revCode[j] := i; INC(i); INC(j) END; j := ORD("a"); WHILE j <= ORD("z") DO code[i] := CHR(j); revCode[j] := i; INC(i); INC(j) END; ASSERT(i = 64, 60) END InitCodes; BEGIN InitCodes; stdDocuType[0] := 3X; stdDocuType[1] := 3X; stdDocuType[2] := 3X; stdDocuType[3] := 0X END StdCoder.
39.037627
111
0.501131
[ "model" ]
208fbad0aa36cca2b20eecd8c8323130bbd0cc7d
2,777
cpp
C++
src/hed/libs/message/SecAttr.cpp
davidgcameron/arc
9813ef5f45e5089507953239de8fa2248f5ad32c
[ "Apache-2.0" ]
null
null
null
src/hed/libs/message/SecAttr.cpp
davidgcameron/arc
9813ef5f45e5089507953239de8fa2248f5ad32c
[ "Apache-2.0" ]
null
null
null
src/hed/libs/message/SecAttr.cpp
davidgcameron/arc
9813ef5f45e5089507953239de8fa2248f5ad32c
[ "Apache-2.0" ]
null
null
null
#ifdef HAVE_CONFIG_H #include <config.h> #endif #include "SecAttr.h" namespace Arc { SecAttrFormat SecAttr::UNDEFINED; SecAttrFormat SecAttr::ARCAuth("arc"); SecAttrFormat SecAttr::XACML("xacml"); SecAttrFormat SecAttr::SAML("saml"); SecAttrFormat SecAttr::GACL("gacl"); bool SecAttr::equal(const SecAttr&) const { return false; } SecAttr::operator bool() const { return false; } bool SecAttr::Export(SecAttrFormat format,std::string &val) const { NS ns; XMLNode x(ns, ""); if(!Export(format,x)) return false; x.GetXML(val); return true; } bool SecAttr::Export(SecAttrFormat, XMLNode&) const { return false; } bool SecAttr::Import(SecAttrFormat format,const std::string &val) { XMLNode x(val); if(!x) return false; return Import(format,x); } bool SecAttr::Import(SecAttrFormat, XMLNode) { return false; } std::string SecAttr::get(const std::string&) const { return std::string(); } std::list<std::string> SecAttr::getAll(const std::string& id) const { std::list<std::string> items; std::string item = get(id); if(!item.empty()) items.push_back(item); return items; } MultiSecAttr::~MultiSecAttr() { for(std::list<SecAttr*>::iterator attr = attrs_.begin(); attr != attrs_.end(); ++attr) { delete *attr; } } MultiSecAttr::operator bool() const { return !attrs_.empty(); } bool MultiSecAttr::Export(SecAttrFormat format,XMLNode &val) const { // Name of created node to be replaced by inheriting class if(!val) { NS ns; XMLNode(ns,"MultiSecAttr").New(val); } else { val.Name("MultiSecAttr"); }; for(std::list<SecAttr*>::const_iterator a = attrs_.begin(); a!=attrs_.end();++a) { NS ns; XMLNode x(ns,""); if(!((*a)->Export(format,x))) return false; val.NewChild(x); } return true; } bool MultiSecAttr::Import(SecAttrFormat format,XMLNode val) { XMLNode x = val.Child(0); for(;(bool)x;x=x[1]) { if(!Add(format,x)) return false; } return true; } // This method to be implemented in inheriting classes // or there must be an automatic detection of registered // object types implemented. bool MultiSecAttr::Add(SecAttrFormat, XMLNode&) { return false; } // This implemention assumes odrered lists of attributes bool MultiSecAttr::equal(const SecAttr &b) const { try { const MultiSecAttr& b_ = dynamic_cast<const MultiSecAttr&>(b); std::list<SecAttr*>::const_iterator i_a = attrs_.begin(); std::list<SecAttr*>::const_iterator i_b = b_.attrs_.begin(); for(;;) { if((i_a == attrs_.end()) && (i_b == b_.attrs_.end())) break; if(i_a == attrs_.end()) return false; if(i_b == b_.attrs_.end()) return false; if((**i_a) != (**i_b)) return false; } return true; } catch(std::exception&) { }; return false; } }
23.533898
91
0.661865
[ "object" ]
2090ecf6afef1d94bcc3a7752da660cf1a3f5607
19,082
cpp
C++
src/DroneFlyPro/Map.cpp
Marmiya/MarinaioDrone
a98490f946c0b45460e4525fc05f2ac14f9a4e09
[ "MIT" ]
null
null
null
src/DroneFlyPro/Map.cpp
Marmiya/MarinaioDrone
a98490f946c0b45460e4525fc05f2ac14f9a4e09
[ "MIT" ]
null
null
null
src/DroneFlyPro/Map.cpp
Marmiya/MarinaioDrone
a98490f946c0b45460e4525fc05f2ac14f9a4e09
[ "MIT" ]
null
null
null
#include "Map.h" namespace map { GTEnvironment::GTEnvironment(json args) { } Mapper::Mapper(json args):args(args) { obj = modeltools::load_obj(args["objModelPath"]); CGAL::IO::read_point_set(args["plyModelPath"], pts); } // // plyMapper::plyMapper(const json& args) :m_args(args) { // CGAL::Point_set_3<Point_3, Vector_3> pointCloud; // string modelPath{ args["plyModelPath"].get<string>() }; // auto RPS = CGAL::IO::read_point_set(modelPath, pointCloud, pointCloud.parameters().use_binary_mode(true)); // // CGAL::Point_set_3<Point_3, Vector_3>::Property_map<int> cluster_map = pointCloud.add_property_map<int>("cluster", -1).first; // // vector < pair<size_t, size_t>> adjacencies; // // size_t nb_clusters = CGAL::cluster_point_set(pointCloud, cluster_map, // pointCloud.parameters().neighbor_radius(args["cluster_radius"].get<double>()).adjacencies(back_inserter(adjacencies))); // // buildings.resize(nb_clusters); // //#ifdef MMAP_TEST // cout << "mMap.cpp: " << "The number of buildings is " << nb_clusters << endl; //#endif // MMAP_TEST // // CGAL::Point_set_3<Point_3, Vector_3>::Property_map<unsigned char>red = pointCloud.add_property_map<unsigned char>("red", 0).first; // CGAL::Point_set_3<Point_3, Vector_3>::Property_map<unsigned char>green = pointCloud.add_property_map<unsigned char>("green", 0).first; // CGAL::Point_set_3<Point_3, Vector_3>::Property_map<unsigned char>blue = pointCloud.add_property_map<unsigned char>("blue", 0).first; // // for (CGAL::Point_set_3<Point_3, Vector_3>::Index idx : pointCloud) { // int clusterID = cluster_map[idx]; // CGAL::Random rand(clusterID); // red[idx] = rand.get_int(64, 192); // green[idx] = rand.get_int(64, 192); // blue[idx] = rand.get_int(64, 192); // // auto& currentBuilding = buildings.at(clusterID); // currentBuilding.points_world_space.insert(pointCloud.point(idx)); // } // // for (size_t i = 0; i < buildings.size(); ++i) { // buildings.at(i).bounding_box_3d = // get_bounding_box_rotated(buildings.at(i).points_world_space); // //cout << buildings.at(i).points_world_space.size() << endl; // buildings.at(i).boxes.push_back(buildings.at(i).bounding_box_3d); // buildings.at(i).viz_num = 99; // } // // } // // bool plyMapper::readjust() // { // for (auto& i : buildings) { // auto t = std::make_pair(i, false); // reBuildings.push_back(t); // } // return true; // } // // bool plyMapper::nextTarget(std::pair<BDG::Building, bool>& n) // { // for (auto& i :reBuildings) { // if (!i.second) { // n = i; // return true; // } // } // return false; // } // // objMapper::objMapper(const json& args, bool partial) :m_args(args) // { // string modelPath{ args["objModelPath"].get<string>() }; // obj = MODELTOOLS::load_obj(modelPath, true, ""); // // if (partial) { // get<1>(obj).erase(get<1>(obj).begin() + 2); // } // auto vertices = get<0>(obj).vertices; // auto shape = get<1>(obj); // demarcation = shape.size(); // // std::vector<building> t; // // for (int i = 0; i < shape.size(); i++) { // // auto indice = shape.at(i).mesh.indices; // std::set<CGALTOOLS::Point3> pts; // // for (auto j = indice.begin() + 1; j != indice.end() - 1; j++) { // double x, y, z; // x = vertices.at((*j).vertex_index * 3); // y = vertices.at((*j).vertex_index * 3 + 1); // z = vertices.at((*j).vertex_index * 3 + 2); // Point3 cur(x, y, z); // if (pts.find(cur) == pts.end()) { // pts.insert(cur); // } // } // // CGALTOOLS::cuboid cuboid(pts); // //#ifdef MMAP_TEST // cout << "--------------" << endl; // auto tt = cuboid.getVer(); // for (const auto& i : tt) { // cout << i << endl; // } // cout << "--------------" << endl; //#endif // MMAP_TEST // // t.push_back(std::make_pair(SHP::shape(shape.at(i), 0), cuboid )); // } // shapes = make_shared<std::vector<building>>(t); // //#ifdef MMAP_TEST // // std::printf("# of vertices = %d\n", (int)(get<0>(obj).vertices.size()) / 3); // std::printf("# of normals = %d\n", (int)(get<0>(obj).normals.size()) / 3); // std::printf("# of texcoords = %d\n", (int)(get<0>(obj).texcoords.size()) / 2); // std::printf("# of materials = %d\n", (int)(get<2>(obj).size())); // std::printf("# of shapes = %d\n", (int)(get<1>(obj).size())); // // VER::objDrawFromMem(get<0>(obj), get<1>(obj), get<2>(obj), 0 , get<1>(obj).size()); //#endif // MMAP_TEST // // } // // // bool objMapper::buildingClustering() // { // int targetID = 1; // for (auto i = shapes->begin(); i != shapes->end();i++) { // if (i->first.getTargetID() == 0) { // i->first.setTargetID(targetID); // // for (auto j = shapes->begin(); j != shapes->end(); j++) { // double dis = CGALTOOLS::squaredDistanceCuboid(i->second, j->second); //#ifdef MMAP_TEST // cout << "The distance is " << dis << endl; //#endif // MMAP_TEST // // if (dis < std::powf(2 * m_args["safe_distance"].get<double>(), 2)) { // if (j->first.getTargetID() == 0) { // j->first.setTargetID(targetID); // } // else { // i->first.setTargetID(j->first.getTargetID()); // } // } // } // } // //#ifdef MMAP_TEST // cout << "Finish cluster " << targetID << endl; //#endif // MMAP_TEST // targetID += 1; // int cl = 0; // for (auto k = shapes->begin(); k != shapes->end(); k++) { // if (k->first.getTargetID() != 0) { // cl += 1; // } // } // if (cl == shapes->size()) { // break; // } // } // // clusterNum = static_cast<size_t> (targetID - 1); // //#ifdef MMAP_TEST // cout << "Targets' number: " << targets->size() << endl; // cout << "The details are below:" << endl; // for (const auto& i : *shapes) { // cout << i.first.getTargetID() << endl; // } // std::cout << std::endl; // //#endif // MMAP_TEST // // return true; // } // // bool objMapper::targetsGeneration() // { // targets = make_shared<std::vector<targetIndexSet>>(); // // for (size_t j = 1; j <= clusterNum; j++) { // targetIndexSet t; // for (size_t i = 0; i != shapes->size(); i++) { // if (shapes->at(i).first.getTargetID() == j) { // t.insert(i); // } // } // targets->push_back(t); // } // return true; // } // // targetIndexSet objMapper::nextTarget() // { // // return targets->front(); // } // // // TJT::trajectory objMapper::trajectoryGeneration(targetIndexSet tis) { // // using namespace TJT; // // auto vertices = get<0>(obj).vertices; // CGALTOOLS::pointSet3 trajectory; // auto [ifkp, suc] = trajectory.add_property_map<bool>("ifKeyPoint", false); // CGALTOOLS::pointSet3 intermediate; // auto [ifk, succ] = intermediate.add_property_map<bool>("ifKeyPoint", false); // TJT::trajectory tjty; // // If the target is combined by only one building // if (tis.size() == 0) { // std::cout<< "empty target set!" << std::endl; // } // if (tis.size() == 1) { // auto bottomSegs = shapes->at(*tis.begin()).second.getBottomSegs(); // // double height = shapes->at(*tis.begin()).second.getVer().at(4).z() - // bottomSegs->getSeg().vertex(0).z(); // // double safeDis = m_args["safe_distance"].get<double>(); // // auto [expasion, length, width] = // MODELTOOLS::safeExpansion(bottomSegs, safeDis); // // double bottom = expasion->getSeg().vertex(0).z(); // // double // hFoV = m_args["horizontal_fov"].get<double>(), // vFoV = m_args["vertical_fov"].get<double>(), // hOverlap = m_args["horizontal_overlap"].get<double>(), // vOverlap = m_args["vertical_overlap"].get<double>(); // Intervals' distance // double // hInterval = (1 - hOverlap) * 2 * safeDis * std::tan((hFoV / 2) * (M_PI / 180.0)), // proportionOfLength = hInterval / length, // proportionOfWidth = hInterval / width, // vInterval = (1 - vOverlap) * safeDis * std::tan(vFoV * (M_PI / 180.0)), // ProportionOfV = vInterval / height; // // size_t numLI = length / hInterval, numWI = width / hInterval, numVI = height / vInterval; // // for (int i = 0; i < 4; i++) { // Vector3 side = expasion->getSeg().to_vector(); // Point3 base = expasion->getSeg().vertex(0); // if (i == 0 || i == 2) { // intermediate.insert(base); // ifk[*(intermediate.end() - 1)] = true; // for (size_t li = 1; li <= numLI; li++) { // intermediate.insert(base + li * side * proportionOfLength); // } // } // else { // intermediate.insert(base); // ifk[*(intermediate.end() - 1)] = true; // for (size_t wi = 1; wi <= numWI; wi++) { // intermediate.insert(base + wi * side * proportionOfWidth); // } // } // // expasion = expasion->getNext(); // } // // for (size_t vi = 1; vi <= numVI; vi++) { // double z = bottom + vi * ProportionOfV * height; // for (auto j = intermediate.begin(); j != intermediate.end(); j++) { // if (ifk[*j] == true) { // trajectory.insert(Point3(intermediate.point(*j).x(), intermediate.point(*j).y(), z)); // ifkp[*(intermediate.end() - 1)] = true; // } // else { // trajectory.insert(Point3(intermediate.point(*j).x(), intermediate.point(*j).y(), z)); // } // } // } // // } // // else { // Point_set outerVerticesSequence; // std::vector<CGALTOOLS::segmentLN> shps; // double maxHeight = .0; // double groundHeight = shapes->at(0).second.getVer().at(0).z(); // // for (auto i : tis) { // double height = shapes->at(i).second.getVer().at(4).z() - shapes->at(i).second.getVer().at(0).z(); // if (height > maxHeight) { // maxHeight = height; // } // shps.push_back(*(shapes->at(i).second.getBottomSegs())); // } // // auto [profile, sideSize] = CGALTOOLS::makeProfile(shps); // auto [profile, it] = CGALTOOLS::makeProfileInterval(shps); // auto profile = MODELTOOLS::safeExpansionAny(shps, m_args["safe_distance"].get<double>()); // // double safeDis = m_args["safe_distance"]; // // double // hFoV = m_args["horizontal_fov"].get<double>(), // vFoV = m_args["vertical_fov"].get<double>(), // hOverlap = m_args["horizontal_overlap"].get<double>(), // vOverlap = m_args["vertical_overlap"].get<double>(); // double // hInterval = (1 - hOverlap) * 2 * safeDis * std::tan((hFoV / 2) * (M_PI / 180.0)), // vInterval = (1 - vOverlap) * safeDis * std::tan(vFoV * (M_PI / 180.0)), // ProportionOfV = vInterval / maxHeight, numVI = maxHeight / vInterval; // // // for (auto p = profile.edges_begin(); p != profile.edges_end(); p++) { // double edgeLength = std::sqrt(p->squared_length()); // double proportionOfLength = hInterval / edgeLength; // size_t numLI = edgeLength / hInterval; // Point3 base(p->vertex(0).x(), p->vertex(0).y(), groundHeight); // for (int i = 0; i <= numLI; i++) { // intermediate.insert( // base + i * proportionOfLength * Vector3(p->to_vector().x(), p->to_vector().y(), groundHeight)); // } // } // for (size_t vi = 1; vi <= numVI; vi++) { // double z = groundHeight + vi * ProportionOfV * maxHeight; // for (size_t j = 0; j != intermediate.size(); j++) { // trajectory.insert(Point3(intermediate.point(j).x(), intermediate.point(j).y(), z)); // } // } // } // tjty.setpts(trajectory); // return tjty; // } // // void objMapper::completeTraGen() // { // for (auto i : *targets) { // // trajectory.join(trajectoryGeneration(i)); // } // // } // // // parMapper::parMapper(const json& args) // { // m_args = args; // obj = MODELTOOLS::load_obj(m_args["objModelPath"], true, ""); // gtobj = obj; // // double // gsX = m_args["groundStartX"], // gsY = m_args["groundStartY"], // geX = m_args["groundEndX"], // geY = m_args["groundEndY"], // gZ = m_args["groundZ"]; // // size_t numX = (geX - gsX) / 50.0, // numY = (geY - gsY) / 50.0; // // auto& gvertices = get<0>(gtobj).vertices; // auto& gshapes = get<1>(gtobj); // size_t originalSize = gvertices.size() / 3; // for (size_t i = 0; i <= numX; i++) { // for (size_t j = 0; j <= numY; j++) { // gvertices.push_back(gsX + i * 50); // gvertices.push_back(gsY + j * 50); // gvertices.push_back(gZ); // } // } // tinyobj::shape_t newShape; // for (size_t i = 0; i < numX; i++) { // for (size_t j = 0; j < numY; j++) { // tinyobj::index_t f, s, t; // f.normal_index = -1; // f.texcoord_index = -1; // s.normal_index = -1; // s.texcoord_index = -1; // t.normal_index = -1; // t.texcoord_index = -1; // f.vertex_index = originalSize + (i + 1) * (numY + 1) + j + 1; // s.vertex_index = originalSize + i * (numY + 1) + j + 1; // t.vertex_index = originalSize + (i + 1) * (numY + 1) + j; // newShape.mesh.indices.push_back(f); // newShape.mesh.indices.push_back(s); // newShape.mesh.indices.push_back(t); // newShape.mesh.num_face_vertices.push_back(3); // newShape.mesh.material_ids.push_back(-1); // f.vertex_index = originalSize + i * (numY + 1) + j; // s.vertex_index = originalSize + i * (numY + 1) + j + 1; // t.vertex_index = originalSize + (i + 1) * (numY + 1) + j; // newShape.mesh.indices.push_back(f); // newShape.mesh.indices.push_back(s); // newShape.mesh.indices.push_back(t); // newShape.mesh.num_face_vertices.push_back(3); // newShape.mesh.material_ids.push_back(-1); // } // } // gshapes.push_back(newShape); // demarcation = gshapes.size(); // // get<1>(obj).erase(get<1>(obj).begin()); // // auto vertices = get<0>(obj).vertices; // auto shape = get<1>(obj); // // std::vector<building> t; // // for (int i = 0; i < shape.size(); i++) { // // auto indice = shape.at(i).mesh.indices; // std::set<CGALTOOLS::Point3> pts; // // for (auto j = indice.begin() + 1; j != indice.end() - 1; j++) { // double x, y, z; // x = vertices.at((*j).vertex_index * 3); // y = vertices.at((*j).vertex_index * 3 + 1); // z = vertices.at((*j).vertex_index * 3 + 2); // Point3 cur(x, y, z); // if (pts.find(cur) == pts.end()) { // pts.insert(cur); // } // } // // CGALTOOLS::cuboid cuboid(pts); // //#ifdef MMAP_TEST // cout << "--------------" << endl; // auto tt = cuboid.getVer(); // for (const auto& i : tt) { // cout << i << endl; // } // cout << "--------------" << endl; //#endif // MMAP_TEST // // t.push_back(std::make_pair(SHP::shape(shape.at(i), 0), cuboid)); // } // shapes = make_shared<std::vector<building>>(t); // } // // void parMapper::grVis() // { // auto tobj = gtobj; // for (const auto& i : trajectory) { // CGALTOOLS::pointVisualization(tobj, trajectory.point(i), m_args["cameraRadius"]); // } // VER::dynamicDraw(tobj, demarcation, 10); // } // // void parMapper::run() // { // // double // positionX = m_args["startX"], // positionY = m_args["startY"], // positionZ = m_args["startZ"], // cameraX = m_args["cameraX"], // cameraY = m_args["cameraY"], // cameraZ = m_args["cameraZ"]; // // double viewDis = m_args["viewDistance"]; // double safeDis = m_args["safe_distance"]; // bool exploating = true; // bool reconstructing = false; // bool finished = false; // // Point3 UAVPosition(cameraX, cameraY, cameraZ); // targetIndexSet target; // Point_set estimatedTrajectoty; // // Get gt sides. Just for experiments // std::vector<CGALTOOLS::cuboid> gtcuboids; // for (const auto& i : *shapes) { // gtcuboids.push_back(i.second); // } // auto gtSides = CGALTOOLS::getsides(gtcuboids); // // while (!finished) { // // while (exploating) { // // buildingClustering(); // targetsGeneration(); // target = nextTarget(); // estimatedTrajectoty = trajectoryGeneration(target); // trajectory.join(MODELTOOLS::CCPP(UAVPosition, estimatedTrajectoty.point(0))); // exploating = false; // reconstructing = true; // } // // while (reconstructing) { // std::vector<CGALTOOLS::cuboid> cuboids; // for (const auto& i : target) { // cuboids.push_back(shapes->at(i).second); // } // auto sides = CGALTOOLS::getsides(cuboids); // for (auto i = estimatedTrajectoty.begin(); i != estimatedTrajectoty.end(); i++) { // UAVPosition = estimatedTrajectoty.point(*i); // auto nextPosition = estimatedTrajectoty.point(*(i + 1)); // // Collision detection // CGALTOOLS::segment view(UAVPosition, nextPosition); // Vector3 vec = viewDis * (view.direction().to_vector() / std::sqrt(view.squared_length())); // // Eigen::AngleAxisd rightRotation(M_PI * (11.0 / 6.0), Eigen::Vector3d(0, 0, 1)); // Eigen::AngleAxisd leftRotation(M_PI * (1.0 / 6.0), Eigen::Vector3d(0, 0, 1)); // Eigen::Vector3d viewEigen(vec.x(), vec.y(), vec.z()); // Eigen::Vector3d rightViewEigen = rightRotation * viewEigen; // Eigen::Vector3d leftViewEigen = leftRotation * viewEigen; // // view = CGALTOOLS::segment(UAVPosition, UAVPosition + vec); // CGALTOOLS::segment rightView(UAVPosition, UAVPosition + Vector3(rightViewEigen.x(), rightViewEigen.y(), rightViewEigen.z())); // CGALTOOLS::segment leftView(UAVPosition, UAVPosition + Vector3(leftViewEigen.x(), leftViewEigen.y(), leftViewEigen.z())); // cout << "View length: " << view.squared_length() << " " << leftView.squared_length() << " " << rightView.squared_length() << endl; // // bool leftC = false, rightC = false, midC = false; // // for (const auto& i : gtSides) { // double height = i.first->getLast()->getSeg().vertex(0).z(); // if (view.vertex(1).z() < height) { // auto leftCollosion = CGAL::intersection(leftView, i.second); // if (leftCollosion) { // leftC = true; // } // auto rightCollosion = CGAL::intersection(rightView, i.second); // if (rightCollosion) { // rightC = true; // } // auto midCollosion = CGAL::intersection(view, i.second); // if (midCollosion) { // midC = true; // } // } // } // Collision detection End // // If no collision // if (!leftC && !rightC && !midC) { // Eigen::AngleAxisd constructingRotation(M_PI_2, Eigen::Vector3d(0, 0, 1)); // Eigen::Vector3d constructingViewEigen = constructingRotation * viewEigen; // CGALTOOLS::segment constructingView( // UAVPosition, UAVPosition + Vector3(constructingViewEigen.x(), constructingViewEigen.y(), constructingViewEigen.z())); // // Point3 nearestIstn; // double nearestDis = 100.0; // for (const auto& i : gtSides) { // double height = i.first->getLast()->getSeg().vertex(0).z(); // if (UAVPosition.z() < height) { // auto constructingCollosion = CGAL::intersection(constructingView, i.second); // if (constructingCollosion) { // Point3 pt = *(boost::get<Point3>(&*constructingCollosion)); // double dis = std::sqrt(CGAL::squared_distance(pt, UAVPosition)); // if (dis < nearestDis) { // nearestDis = dis; // nearestIstn = pt; // } // } // } // } // if (nearestDis > 2 * safeDis) { // // } // else if (nearestDis > safeDis) { // // } // else { // // } // } // else { // // } // // // // // } // } // } // } };
32.178752
138
0.579918
[ "mesh", "shape", "vector" ]
2097f2c126432b77f8bd30f80cea8ba14d6cdfc5
676
hpp
C++
Loader/Loader.hpp
acaos/nwnxee-unified
0e4c318ede64028c1825319f39c012e168e0482c
[ "MIT" ]
1
2019-06-04T04:30:24.000Z
2019-06-04T04:30:24.000Z
Loader/Loader.hpp
presscad/nwnee
0f36b281524e0b7e9796bcf30f924792bf9b8a38
[ "MIT" ]
null
null
null
Loader/Loader.hpp
presscad/nwnee
0f36b281524e0b7e9796bcf30f924792bf9b8a38
[ "MIT" ]
1
2019-10-20T07:54:45.000Z
2019-10-20T07:54:45.000Z
#pragma once #include <windows.h> #include <functional> #include <memory> #include <string> #include <vector> namespace Loader { struct StartupArgs { std::string loaderPath; std::string fileName; std::string fileArgs; std::string dllName; }; class Loader { public: Loader(const StartupArgs& args); ~Loader(); bool processRunning() const; private: void startRemoteProcess(); void injectDllIntoRemoteProcess(); std::string getWindowsPath(const std::string& path, const size_t bufferSize); std::unique_ptr<PROCESS_INFORMATION, std::function<void(PROCESS_INFORMATION*)>> m_processInfo; const StartupArgs m_startupArgs; }; }
17.789474
98
0.714497
[ "vector" ]
209a6f127821df05aa4148ef80208b1d0b4084f1
33,013
cpp
C++
dlls/pitdrone.cpp
Admer456/halflife-dnf01
a3cacddb5ff3dedfea2d157c72711ba1df429dac
[ "Unlicense" ]
null
null
null
dlls/pitdrone.cpp
Admer456/halflife-dnf01
a3cacddb5ff3dedfea2d157c72711ba1df429dac
[ "Unlicense" ]
null
null
null
dlls/pitdrone.cpp
Admer456/halflife-dnf01
a3cacddb5ff3dedfea2d157c72711ba1df429dac
[ "Unlicense" ]
null
null
null
/*** * * Copyright (c) 1996-2001, Valve LLC. All rights reserved. * * This product contains software technology licensed from Id * Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. * All Rights Reserved. * * This source code contains proprietary and confidential information of * Valve LLC and its suppliers. Access to this code is restricted to * persons who have executed a written SDK license with Valve. Any access, * use or distribution of this code by or to any unlicensed person is illegal. * ****/ //========================================================= // pit drone - medium sized, fires sharp teeth like spikes and swipes with sharp appendages //========================================================= #include "extdll.h" #include "util.h" #include "cbase.h" #include "monsters.h" #include "schedule.h" #include "nodes.h" #include "effects.h" #include "decals.h" #include "soundent.h" #include "game.h" #define SQUID_SPRINT_DIST 256 // how close the squid has to get before starting to sprint and refusing to swerve int iSpikeTrail; int iPitdroneSpitSprite; //========================================================= // monster-specific schedule types //========================================================= enum { SCHED_PITDRONE_HURTHOP = LAST_COMMON_SCHEDULE + 1, SCHED_PITDRONE_SMELLFOOD, SCHED_PITDRONE_EAT, SCHED_PITDRONE_SNIFF_AND_EAT, SCHED_PITDRONE_WALLOW, SCHED_PITDRONE_COVER_AND_RELOAD, SCHED_PITDRONE_WAIT_FACE_ENEMY, SCHED_PITDRONE_TAKECOVER_FAILED, }; //========================================================= // monster-specific tasks //========================================================= enum { TASK_PITDRONE_HOPTURN = LAST_COMMON_TASK + 1, }; //========================================================= // Bullsquid's spit projectile //========================================================= class CPitdroneSpike : public CBaseEntity { public: void Precache() override; void Spawn( void ); int Classify() override { return CLASS_NONE; } static void Shoot( entvars_t *pevOwner, Vector vecStart, Vector vecVelocity, Vector vecAngles ); void EXPORT SpikeTouch( CBaseEntity *pOther ); void EXPORT StartTrail(); virtual int Save( CSave &save ); virtual int Restore( CRestore &restore ); static TYPEDESCRIPTION m_SaveData[]; int m_maxFrame; }; LINK_ENTITY_TO_CLASS( pitdronespike, CPitdroneSpike ); TYPEDESCRIPTION CPitdroneSpike::m_SaveData[] = { DEFINE_FIELD( CPitdroneSpike, m_maxFrame, FIELD_INTEGER ), }; IMPLEMENT_SAVERESTORE( CPitdroneSpike, CBaseEntity ); void CPitdroneSpike::Precache() { PRECACHE_MODEL( "models/pit_drone_spike.mdl" ); PRECACHE_SOUND( "weapons/xbow_hitbod1.wav" ); PRECACHE_SOUND( "weapons/xbox_hit1.wav" ); iSpikeTrail = PRECACHE_MODEL( "sprites/spike_trail.spr" ); } void CPitdroneSpike:: Spawn( void ) { pev->movetype = MOVETYPE_FLY; pev->classname = MAKE_STRING( "pitdronespike" ); pev->solid = SOLID_BBOX; pev->takedamage = DAMAGE_YES; pev->flags |= FL_MONSTER; pev->health = 1; SET_MODEL(ENT(pev), "models/pit_drone_spike.mdl"); pev->frame = 0; pev->scale = 0.5; UTIL_SetSize( pev, Vector( -4, -4, -4 ), Vector( 4, 4, 4 ) ); m_maxFrame = (float) MODEL_FRAMES( pev->modelindex ) - 1; } void CPitdroneSpike::Shoot( entvars_t *pevOwner, Vector vecStart, Vector vecVelocity, Vector vecAngles ) { CPitdroneSpike *pSpit = GetClassPtr( ( CPitdroneSpike *)NULL ); pSpit->pev->angles = vecAngles; UTIL_SetOrigin( pSpit->pev, vecStart ); pSpit->Spawn(); pSpit->pev->velocity = vecVelocity; pSpit->pev->owner = ENT(pevOwner); pSpit->SetThink ( &CPitdroneSpike::StartTrail ); pSpit->pev->nextthink = gpGlobals->time + 0.1; } void CPitdroneSpike::SpikeTouch( CBaseEntity *pOther ) { // splat sound int iPitch = RANDOM_FLOAT( 120, 140 ); if( !pOther->pev->takedamage ) { EMIT_SOUND_DYN( edict(), CHAN_VOICE, "weapons/xbow_hit1.wav", VOL_NORM, ATTN_NORM, 0, iPitch ); } else { pOther->TakeDamage( pev, pev, gSkillData.pitdroneDmgSpit, DMG_GENERIC ); EMIT_SOUND_DYN( edict(), CHAN_VOICE, "weapons/xbow_hitbod1.wav", VOL_NORM, ATTN_NORM, 0, iPitch ); } SetTouch( nullptr ); //Stick it in the world for a bit //TODO: maybe stick it on any entity that reports FL_WORLDBRUSH too? if( !strcmp( "worldspawn", STRING( pOther->pev->classname ) ) ) { const auto vecDir = pev->velocity.Normalize(); const auto vecOrigin = pev->origin - vecDir * 6; UTIL_SetOrigin( pev, vecOrigin ); auto v41 = UTIL_VecToAngles( vecDir ); pev->angles = UTIL_VecToAngles( vecDir ); pev->solid = SOLID_NOT; pev->movetype = MOVETYPE_FLY; pev->angles.z = RANDOM_LONG( 0, 360 ); pev->velocity = g_vecZero; pev->avelocity = g_vecZero; SetThink( &CBaseEntity::SUB_FadeOut ); pev->nextthink = gpGlobals->time + 90.0; } else { //Hit something else, remove SetThink( &CBaseEntity::SUB_Remove ); pev->nextthink = gpGlobals->time + 0.1; } } void CPitdroneSpike::StartTrail() { MESSAGE_BEGIN( MSG_BROADCAST, SVC_TEMPENTITY ); WRITE_BYTE( TE_BEAMFOLLOW ); WRITE_SHORT( entindex() ); WRITE_SHORT( iSpikeTrail ); WRITE_BYTE( 2 ); WRITE_BYTE( 1 ); WRITE_BYTE( 197 ); WRITE_BYTE( 194 ); WRITE_BYTE( 11 ); WRITE_BYTE( 192 ); MESSAGE_END(); SetTouch( &CPitdroneSpike::SpikeTouch ); SetThink( nullptr ); } //========================================================= // Monster's Anim Events Go Here //========================================================= #define PITDRONE_AE_SPIT ( 1 ) #define PITDRONE_AE_BITE ( 2 ) #define PITDRONE_AE_TAILWHIP ( 4 ) #define PITDRONE_AE_HOP ( 5 ) #define PITDRONE_AE_THROW ( 6 ) #define PITDRONE_AE_RELOAD 7 namespace PitdroneBodygroup { enum PitdroneBodygroup { Weapons = 1 }; } namespace PitdroneWeapon { enum PitdroneWeapon { Empty = 0, Full, Two = 6, One = 7 }; } class CPitdrone : public CBaseMonster { public: void Spawn( void ); void Precache( void ); void SetYawSpeed( void ); int ISoundMask( void ); int Classify ( void ); void HandleAnimEvent( MonsterEvent_t *pEvent ); void IdleSound( void ); void PainSound( void ); void AlertSound ( void ); void StartTask ( Task_t *pTask ); void RunTask ( Task_t *pTask ); BOOL CheckMeleeAttack1 ( float flDot, float flDist ); BOOL CheckMeleeAttack2 ( float flDot, float flDist ); BOOL CheckRangeAttack1 ( float flDot, float flDist ); void RunAI( void ); BOOL FValidateHintType ( short sHint ); Schedule_t *GetSchedule( void ); Schedule_t *GetScheduleOfType ( int Type ); int IRelationship ( CBaseEntity *pTarget ); int IgnoreConditions ( void ); void CheckAmmo() override; void GibMonster() override; void KeyValue( KeyValueData* pkvd ) override; int Save( CSave &save ); int Restore( CRestore &restore ); CUSTOM_SCHEDULES; static TYPEDESCRIPTION m_SaveData[]; float m_flLastHurtTime;// we keep track of this, because if something hurts a squid, it will forget about its love of headcrabs for a while. float m_flNextSpikeTime;// last time the pit drone used the spike attack. int m_iInitialAmmo; float m_flNextEatTime; }; LINK_ENTITY_TO_CLASS( monster_pitdrone, CPitdrone ); TYPEDESCRIPTION CPitdrone::m_SaveData[] = { DEFINE_FIELD( CPitdrone, m_flLastHurtTime, FIELD_TIME ), DEFINE_FIELD( CPitdrone, m_flNextSpikeTime, FIELD_TIME ), DEFINE_FIELD( CPitdrone, m_flNextEatTime, FIELD_TIME ), }; IMPLEMENT_SAVERESTORE( CPitdrone, CBaseMonster ); //========================================================= // IgnoreConditions //========================================================= int CPitdrone::IgnoreConditions ( void ) { int iIgnore = CBaseMonster::IgnoreConditions(); if ( gpGlobals->time - m_flLastHurtTime <= 20 ) { // haven't been hurt in 20 seconds, so let the drone care about stink. iIgnore = bits_COND_SMELL | bits_COND_SMELL_FOOD; } return iIgnore; } int CPitdrone::IRelationship ( CBaseEntity *pTarget ) { //Always mark pit drones as allies if ( FClassnameIs ( pTarget->pev, "monster_pitdrone" ) ) { return R_AL; } return CBaseMonster :: IRelationship ( pTarget ); } //========================================================= // CheckRangeAttack1 //========================================================= BOOL CPitdrone :: CheckRangeAttack1 ( float flDot, float flDist ) { if ( m_iInitialAmmo == -1 || GetBodygroup( PitdroneBodygroup::Weapons ) == PitdroneWeapon::Empty || ( IsMoving() && flDist >= 512 ) ) { // squid will far too far behind if he stops running to spit at this distance from the enemy. return FALSE; } if ( flDist > 128 && flDist <= 784 && flDot >= 0.5 && gpGlobals->time >= m_flNextSpikeTime ) { if ( m_hEnemy != NULL ) { if ( fabs( pev->origin.z - m_hEnemy->pev->origin.z ) > 256 ) { // don't try to spit at someone up really high or down really low. return FALSE; } } if ( IsMoving() ) { // don't spit again for a long time, resume chasing enemy. m_flNextSpikeTime = gpGlobals->time + 5; } else { // not moving, so spit again pretty soon. m_flNextSpikeTime = gpGlobals->time + 0.5; } return TRUE; } return FALSE; } BOOL CPitdrone :: CheckMeleeAttack1 ( float flDot, float flDist ) { if ( flDist <= 64 && flDot >= 0.7 ) { return RANDOM_LONG( 0, 3 ) == 0; } return FALSE; } BOOL CPitdrone :: CheckMeleeAttack2 ( float flDot, float flDist ) { if ( flDist <= 64 && flDot >= 0.7 && !HasConditions( bits_COND_CAN_MELEE_ATTACK1 ) ) { return TRUE; } return FALSE; } //========================================================= // FValidateHintType //========================================================= BOOL CPitdrone :: FValidateHintType ( short sHint ) { int i; static short sSquidHints[] = { HINT_WORLD_HUMAN_BLOOD, }; for ( i = 0 ; i < ARRAYSIZE ( sSquidHints ) ; i++ ) { if ( sSquidHints[ i ] == sHint ) { return TRUE; } } ALERT ( at_aiconsole, "Couldn't validate hint type" ); return FALSE; } //========================================================= // ISoundMask - returns a bit mask indicating which types // of sounds this monster regards. In the base class implementation, // monsters care about all sounds, but no scents. //========================================================= int CPitdrone :: ISoundMask ( void ) { return bits_SOUND_WORLD | bits_SOUND_COMBAT | bits_SOUND_CARCASS | bits_SOUND_MEAT | bits_SOUND_GARBAGE | bits_SOUND_PLAYER; } //========================================================= // Classify - indicates this monster's place in the // relationship table. //========================================================= int CPitdrone :: Classify ( void ) { return CLASS_ALIEN_PREDATOR; } //========================================================= // IdleSound //========================================================= void CPitdrone :: IdleSound ( void ) { } //========================================================= // PainSound //========================================================= void CPitdrone :: PainSound ( void ) { int iPitch = RANDOM_LONG( 85, 120 ); switch ( RANDOM_LONG(0,3) ) { case 0: EMIT_SOUND_DYN( ENT(pev), CHAN_VOICE, "pitdrone/pit_drone_pain1.wav", 1, ATTN_NORM, 0, iPitch ); break; case 1: EMIT_SOUND_DYN( ENT(pev), CHAN_VOICE, "pitdrone/pit_drone_pain2.wav", 1, ATTN_NORM, 0, iPitch ); break; case 2: EMIT_SOUND_DYN( ENT(pev), CHAN_VOICE, "pitdrone/pit_drone_pain3.wav", 1, ATTN_NORM, 0, iPitch ); break; case 3: EMIT_SOUND_DYN( ENT(pev), CHAN_VOICE, "pitdrone/pit_drone_pain4.wav", 1, ATTN_NORM, 0, iPitch ); break; } } //========================================================= // AlertSound //========================================================= void CPitdrone :: AlertSound ( void ) { int iPitch = RANDOM_LONG( 140, 160 ); //TODO: the random was never adjusted to match the newly added sound switch ( RANDOM_LONG ( 0, 1 ) ) { case 0: EMIT_SOUND_DYN( ENT(pev), CHAN_VOICE, "pitdrone/pit_drone_alert1.wav", 1, ATTN_NORM, 0, iPitch ); break; case 1: EMIT_SOUND_DYN( ENT(pev), CHAN_VOICE, "pitdrone/pit_drone_alert2.wav", 1, ATTN_NORM, 0, iPitch ); break; case 2: EMIT_SOUND_DYN( ENT( pev ), CHAN_VOICE, "pitdrone/pit_drone_alert3.wav", 1, ATTN_NORM, 0, iPitch ); break; } } //========================================================= // SetYawSpeed - allows each sequence to have a different // turn rate associated with it. //========================================================= void CPitdrone :: SetYawSpeed ( void ) { int ys; ys = 0; switch ( m_Activity ) { case ACT_WALK: ys = 90; break; case ACT_RUN: ys = 90; break; case ACT_IDLE: ys = 90; break; case ACT_RANGE_ATTACK1: ys = 90; break; default: ys = 90; break; } pev->yaw_speed = ys; } //========================================================= // HandleAnimEvent - catches the monster-specific messages // that occur when tagged animation frames are played. //========================================================= void CPitdrone :: HandleAnimEvent( MonsterEvent_t *pEvent ) { switch( pEvent->event ) { case PITDRONE_AE_SPIT: { if( m_iInitialAmmo != -1 && GetBodygroup( PitdroneBodygroup::Weapons ) != PitdroneWeapon::Empty ) { Vector vecSpitOffset; Vector vecSpitDir; UTIL_MakeVectors( pev->angles ); // !!!HACKHACK - the spot at which the spit originates (in front of the mouth) was measured in 3ds and hardcoded here. // we should be able to read the position of bones at runtime for this info. vecSpitOffset = ( gpGlobals->v_forward * 15 + gpGlobals->v_up * 36 ); vecSpitOffset = ( pev->origin + vecSpitOffset ); vecSpitDir = ( ( m_hEnemy->pev->origin + m_hEnemy->pev->view_ofs ) - vecSpitOffset ).Normalize(); vecSpitDir.x += RANDOM_FLOAT( -0.05, 0.05 ); vecSpitDir.y += RANDOM_FLOAT( -0.05, 0.05 ); vecSpitDir.z += RANDOM_FLOAT( -0.05, 0 ); // spew the spittle temporary ents. MESSAGE_BEGIN( MSG_PVS, SVC_TEMPENTITY, vecSpitOffset ); WRITE_BYTE( TE_SPRITE_SPRAY ); WRITE_COORD( vecSpitOffset.x ); // pos WRITE_COORD( vecSpitOffset.y ); WRITE_COORD( vecSpitOffset.z ); WRITE_COORD( vecSpitDir.x ); // dir WRITE_COORD( vecSpitDir.y ); WRITE_COORD( vecSpitDir.z ); WRITE_SHORT( iPitdroneSpitSprite ); // model WRITE_BYTE( 10 ); // count WRITE_BYTE( 110 ); // speed WRITE_BYTE( 25 ); // noise ( client will divide by 100 ) MESSAGE_END(); CPitdroneSpike::Shoot( pev, vecSpitOffset, vecSpitDir * 900, UTIL_VecToAngles( vecSpitDir ) ); auto ammoSubModel = GetBodygroup( PitdroneBodygroup::Weapons ); //TODO: needs to be fixed so all spikes can be fired? if( ammoSubModel == PitdroneWeapon::Two ) { ammoSubModel = PitdroneWeapon::Empty; } else { ++ammoSubModel; } SetBodygroup( PitdroneBodygroup::Weapons, ammoSubModel ); --m_cAmmoLoaded; } } break; case PITDRONE_AE_BITE: { // SOUND HERE! CBaseEntity *pHurt = CheckTraceHullAttack( 70, gSkillData.pitdroneDmgBite, DMG_SLASH ); if ( pHurt ) { //pHurt->pev->punchangle.z = -15; //pHurt->pev->punchangle.x = -45; pHurt->pev->velocity = pHurt->pev->velocity - gpGlobals->v_forward * 100; pHurt->pev->velocity = pHurt->pev->velocity + gpGlobals->v_up * 100; } } break; case PITDRONE_AE_TAILWHIP: { CBaseEntity *pHurt = CheckTraceHullAttack( 70, gSkillData.pitdroneDmgWhip, DMG_CLUB | DMG_ALWAYSGIB ); if ( pHurt ) { pHurt->pev->punchangle.z = -20; pHurt->pev->punchangle.x = 20; pHurt->pev->velocity = pHurt->pev->velocity + gpGlobals->v_right * 200; pHurt->pev->velocity = pHurt->pev->velocity + gpGlobals->v_up * 100; } } break; case PITDRONE_AE_HOP: { float flGravity = g_psv_gravity->value; // throw the squid up into the air on this frame. if ( FBitSet ( pev->flags, FL_ONGROUND ) ) { pev->flags -= FL_ONGROUND; } // jump into air for 0.8 (24/30) seconds // pev->velocity.z += (0.875 * flGravity) * 0.5; pev->velocity.z += (0.625 * flGravity) * 0.5; } break; case PITDRONE_AE_THROW: { int iPitch; // squid throws its prey IF the prey is a client. CBaseEntity *pHurt = CheckTraceHullAttack( 70, 0, 0 ); if ( pHurt ) { // croonchy bite sound iPitch = RANDOM_FLOAT( 90, 110 ); switch ( RANDOM_LONG( 0, 1 ) ) { case 0: EMIT_SOUND_DYN( ENT(pev), CHAN_WEAPON, "bullchicken/bc_bite2.wav", 1, ATTN_NORM, 0, iPitch ); break; case 1: EMIT_SOUND_DYN( ENT(pev), CHAN_WEAPON, "bullchicken/bc_bite3.wav", 1, ATTN_NORM, 0, iPitch ); break; } //pHurt->pev->punchangle.x = RANDOM_LONG(0,34) - 5; //pHurt->pev->punchangle.z = RANDOM_LONG(0,49) - 25; //pHurt->pev->punchangle.y = RANDOM_LONG(0,89) - 45; // screeshake transforms the viewmodel as well as the viewangle. No problems with seeing the ends of the viewmodels. UTIL_ScreenShake( pHurt->pev->origin, 25.0, 1.5, 0.7, 2 ); if ( pHurt->IsPlayer() ) { UTIL_MakeVectors( pev->angles ); pHurt->pev->velocity = pHurt->pev->velocity + gpGlobals->v_forward * 300 + gpGlobals->v_up * 300; } } } break; case PITDRONE_AE_RELOAD: { if( m_iInitialAmmo == -1 ) { m_cAmmoLoaded = 0; } else { SetBodygroup( PitdroneBodygroup::Weapons, PitdroneWeapon::Full ); m_cAmmoLoaded = 6; } ClearConditions( bits_COND_NO_AMMO_LOADED ); } break; default: CBaseMonster::HandleAnimEvent( pEvent ); } } //========================================================= // Spawn //========================================================= void CPitdrone :: Spawn() { Precache( ); SET_MODEL(ENT(pev), "models/pit_drone.mdl"); UTIL_SetSize( pev, Vector( -16, -16, 0 ), Vector( 16, 16, 48 ) ); pev->solid = SOLID_SLIDEBOX; pev->movetype = MOVETYPE_STEP; m_bloodColor = BLOOD_COLOR_GREEN; pev->effects = 0; pev->health = gSkillData.pitdroneHealth; m_flFieldOfView = VIEW_FIELD_WIDE;// indicates the width of this monster's forward view cone ( as a dotproduct result ) m_MonsterState = MONSTERSTATE_NONE; m_flNextSpikeTime = gpGlobals->time; if( m_iInitialAmmo == -1 ) { SetBodygroup( PitdroneBodygroup::Weapons, PitdroneWeapon::Full ); } else if( m_iInitialAmmo <= 0 ) { m_iInitialAmmo = -1; SetBodygroup( PitdroneBodygroup::Weapons, PitdroneWeapon::Empty ); } else { SetBodygroup( PitdroneBodygroup::Weapons, PitdroneWeapon::One - m_iInitialAmmo ); } if( m_iInitialAmmo == -1 ) m_iInitialAmmo = 0; m_cAmmoLoaded = m_iInitialAmmo; m_flNextEatTime = gpGlobals->time; MonsterInit(); } //========================================================= // Precache - precaches all resources this monster needs //========================================================= void CPitdrone :: Precache() { PRECACHE_MODEL("models/pit_drone.mdl"); PRECACHE_MODEL( "models/pit_drone_gibs.mdl" ); UTIL_PrecacheOther( "pitdronespike" ); iPitdroneSpitSprite = PRECACHE_MODEL("sprites/tinyspit.spr");// client side spittle. PRECACHE_SOUND("zombie/claw_miss2.wav");// because we use the basemonster SWIPE animation event PRECACHE_SOUND( "pitdrone/pit_drone_alert1.wav" ); PRECACHE_SOUND( "pitdrone/pit_drone_alert2.wav" ); PRECACHE_SOUND( "pitdrone/pit_drone_alert3.wav" ); PRECACHE_SOUND( "pitdrone/pit_drone_attack_spike1.wav" ); PRECACHE_SOUND( "pitdrone/pit_drone_attack_spike2.wav" ); PRECACHE_SOUND( "pitdrone/pit_drone_communicate1.wav" ); PRECACHE_SOUND( "pitdrone/pit_drone_communicate2.wav" ); PRECACHE_SOUND( "pitdrone/pit_drone_communicate3.wav" ); PRECACHE_SOUND( "pitdrone/pit_drone_communicate4.wav" ); PRECACHE_SOUND( "pitdrone/pit_drone_die1.wav" ); PRECACHE_SOUND( "pitdrone/pit_drone_die2.wav" ); PRECACHE_SOUND( "pitdrone/pit_drone_die3.wav" ); PRECACHE_SOUND( "pitdrone/pit_drone_hunt1.wav" ); PRECACHE_SOUND( "pitdrone/pit_drone_hunt2.wav" ); PRECACHE_SOUND( "pitdrone/pit_drone_hunt3.wav" ); PRECACHE_SOUND( "pitdrone/pit_drone_idle1.wav" ); PRECACHE_SOUND( "pitdrone/pit_drone_idle2.wav" ); PRECACHE_SOUND( "pitdrone/pit_drone_idle3.wav" ); PRECACHE_SOUND( "pitdrone/pit_drone_melee_attack1.wav" ); PRECACHE_SOUND( "pitdrone/pit_drone_melee_attack2.wav" ); PRECACHE_SOUND( "pitdrone/pit_drone_pain1.wav" ); PRECACHE_SOUND( "pitdrone/pit_drone_pain2.wav" ); PRECACHE_SOUND( "pitdrone/pit_drone_pain3.wav" ); PRECACHE_SOUND( "pitdrone/pit_drone_pain4.wav" ); PRECACHE_SOUND( "pitdrone/pit_drone_run_on_grate.wav" ); PRECACHE_SOUND( "bullchicken/bc_bite2.wav" ); PRECACHE_SOUND( "bullchicken/bc_bite3.wav" ); } //======================================================== // RunAI - overridden for bullsquid because there are things // that need to be checked every think. //======================================================== void CPitdrone :: RunAI ( void ) { // first, do base class stuff CBaseMonster :: RunAI(); if ( m_hEnemy != NULL && m_Activity == ACT_RUN ) { // chasing enemy. Sprint for last bit if ( (pev->origin - m_hEnemy->pev->origin).Length2D() < SQUID_SPRINT_DIST ) { pev->framerate = 1.25; } } } //======================================================== // AI Schedules Specific to this monster //========================================================= // primary range attack Task_t tlPitdroneRangeAttack1[] = { { TASK_STOP_MOVING, 0 }, { TASK_FACE_IDEAL, (float)0 }, { TASK_RANGE_ATTACK1, (float)0 }, { TASK_SET_ACTIVITY, (float)ACT_IDLE }, }; Schedule_t slPitdroneRangeAttack1[] = { { tlPitdroneRangeAttack1, ARRAYSIZE ( tlPitdroneRangeAttack1 ), bits_COND_NEW_ENEMY | bits_COND_ENEMY_DEAD | bits_COND_HEAVY_DAMAGE | bits_COND_ENEMY_OCCLUDED | bits_COND_NO_AMMO_LOADED, 0, "Squid Range Attack1" }, }; // Chase enemy schedule Task_t tlPitdroneChaseEnemy1[] = { { TASK_SET_FAIL_SCHEDULE, (float)SCHED_RANGE_ATTACK1 },// !!!OEM - this will stop nasty squid oscillation. { TASK_GET_PATH_TO_ENEMY, (float)0 }, { TASK_RUN_PATH, (float)0 }, { TASK_WAIT_FOR_MOVEMENT, (float)0 }, }; Schedule_t slPitdroneChaseEnemy[] = { { tlPitdroneChaseEnemy1, ARRAYSIZE ( tlPitdroneChaseEnemy1 ), bits_COND_NEW_ENEMY | bits_COND_ENEMY_DEAD | bits_COND_SMELL_FOOD | bits_COND_CAN_RANGE_ATTACK1 | bits_COND_CAN_MELEE_ATTACK1 | bits_COND_CAN_MELEE_ATTACK2 | bits_COND_TASK_FAILED | bits_COND_HEAR_SOUND, bits_SOUND_DANGER | bits_SOUND_MEAT, "Squid Chase Enemy" }, }; Task_t tlPitdroneHurtHop[] = { { TASK_STOP_MOVING, (float)0 }, { TASK_SOUND_WAKE, (float)0 }, { TASK_PITDRONE_HOPTURN, (float)0 }, { TASK_FACE_ENEMY, (float)0 },// in case squid didn't turn all the way in the air. }; Schedule_t slPitdroneHurtHop[] = { { tlPitdroneHurtHop, ARRAYSIZE ( tlPitdroneHurtHop ), 0, 0, "SquidHurtHop" } }; // squid walks to something tasty and eats it. Task_t tlPitdroneEat[] = { { TASK_STOP_MOVING, (float)0 }, { TASK_EAT, (float)10 },// this is in case the squid can't get to the food { TASK_STORE_LASTPOSITION, (float)0 }, { TASK_GET_PATH_TO_BESTSCENT, (float)0 }, { TASK_WALK_PATH, (float)0 }, { TASK_WAIT_FOR_MOVEMENT, (float)0 }, { TASK_PLAY_SEQUENCE, (float)ACT_EAT }, { TASK_PLAY_SEQUENCE, (float)ACT_EAT }, { TASK_PLAY_SEQUENCE, (float)ACT_EAT }, { TASK_EAT, (float)50 }, { TASK_GET_PATH_TO_LASTPOSITION,(float)0 }, { TASK_WALK_PATH, (float)0 }, { TASK_WAIT_FOR_MOVEMENT, (float)0 }, { TASK_CLEAR_LASTPOSITION, (float)0 }, }; Schedule_t slPitdroneEat[] = { { tlPitdroneEat, ARRAYSIZE( tlPitdroneEat ), bits_COND_LIGHT_DAMAGE | bits_COND_HEAVY_DAMAGE | bits_COND_NEW_ENEMY , // even though HEAR_SOUND/SMELL FOOD doesn't break this schedule, we need this mask // here or the monster won't detect these sounds at ALL while running this schedule. bits_SOUND_MEAT | bits_SOUND_CARCASS, "SquidEat" } }; // this is a bit different than just Eat. We use this schedule when the food is far away, occluded, or behind // the squid. This schedule plays a sniff animation before going to the source of food. Task_t tlPitdroneSniffAndEat[] = { { TASK_STOP_MOVING, (float)0 }, { TASK_EAT, (float)10 },// this is in case the squid can't get to the food { TASK_PLAY_SEQUENCE, (float)ACT_DETECT_SCENT }, { TASK_STORE_LASTPOSITION, (float)0 }, { TASK_GET_PATH_TO_BESTSCENT, (float)0 }, { TASK_WALK_PATH, (float)0 }, { TASK_WAIT_FOR_MOVEMENT, (float)0 }, { TASK_PLAY_SEQUENCE, (float)ACT_EAT }, { TASK_PLAY_SEQUENCE, (float)ACT_EAT }, { TASK_PLAY_SEQUENCE, (float)ACT_EAT }, { TASK_EAT, (float)50 }, { TASK_GET_PATH_TO_LASTPOSITION,(float)0 }, { TASK_WALK_PATH, (float)0 }, { TASK_WAIT_FOR_MOVEMENT, (float)0 }, { TASK_CLEAR_LASTPOSITION, (float)0 }, }; Schedule_t slPitdroneSniffAndEat[] = { { tlPitdroneSniffAndEat, ARRAYSIZE( tlPitdroneSniffAndEat ), bits_COND_LIGHT_DAMAGE | bits_COND_HEAVY_DAMAGE | bits_COND_NEW_ENEMY , // even though HEAR_SOUND/SMELL FOOD doesn't break this schedule, we need this mask // here or the monster won't detect these sounds at ALL while running this schedule. bits_SOUND_MEAT | bits_SOUND_CARCASS, "SquidSniffAndEat" } }; // squid does this to stinky things. Task_t tlPitdroneWallow[] = { { TASK_STOP_MOVING, (float)0 }, { TASK_EAT, (float)10 },// this is in case the squid can't get to the stinkiness { TASK_STORE_LASTPOSITION, (float)0 }, { TASK_GET_PATH_TO_BESTSCENT, (float)0 }, { TASK_WALK_PATH, (float)0 }, { TASK_WAIT_FOR_MOVEMENT, (float)0 }, { TASK_PLAY_SEQUENCE, (float)ACT_INSPECT_FLOOR}, { TASK_EAT, (float)50 },// keeps squid from eating or sniffing anything else for a while. { TASK_GET_PATH_TO_LASTPOSITION,(float)0 }, { TASK_WALK_PATH, (float)0 }, { TASK_WAIT_FOR_MOVEMENT, (float)0 }, { TASK_CLEAR_LASTPOSITION, (float)0 }, }; Schedule_t slPitdroneWallow[] = { { tlPitdroneWallow, ARRAYSIZE( tlPitdroneWallow ), bits_COND_LIGHT_DAMAGE | bits_COND_HEAVY_DAMAGE | bits_COND_NEW_ENEMY , // even though HEAR_SOUND/SMELL FOOD doesn't break this schedule, we need this mask // here or the monster won't detect these sounds at ALL while running this schedule. bits_SOUND_GARBAGE, "SquidWallow" } }; Task_t tlPitdroneHideReload[] = { { TASK_STOP_MOVING, ( float ) 0 }, { TASK_SET_FAIL_SCHEDULE, ACT_MELEE_ATTACK1 }, { TASK_FIND_COVER_FROM_ENEMY, 0 }, { TASK_RUN_PATH, 0 }, { TASK_WAIT_FOR_MOVEMENT, 0 }, { TASK_REMEMBER, bits_MEMORY_INCOVER }, { TASK_FACE_ENEMY, 0 }, { TASK_PLAY_SEQUENCE, ACT_RELOAD }, }; Schedule_t slPitdroneHideReload[] = { { tlPitdroneHideReload, ARRAYSIZE( tlPitdroneHideReload ), bits_COND_HEAVY_DAMAGE | bits_COND_HEAR_SOUND, bits_SOUND_DANGER, "PitdroneHideReload" } }; Task_t tlPitdroneWaitInCover[] = { { TASK_STOP_MOVING, ( float ) 0 }, { TASK_SET_ACTIVITY, ACT_IDLE }, { TASK_WAIT_FACE_ENEMY, 1 }, }; Schedule_t slPitdroneWaitInCover[] = { { tlPitdroneWaitInCover, ARRAYSIZE( tlPitdroneWaitInCover ), bits_COND_CAN_RANGE_ATTACK1 | bits_COND_CAN_MELEE_ATTACK1 | bits_COND_CAN_RANGE_ATTACK2 | bits_COND_CAN_MELEE_ATTACK2 | bits_COND_NEW_ENEMY | bits_COND_HEAR_SOUND, bits_SOUND_DANGER, "PitdroneWaitInCover" } }; DEFINE_CUSTOM_SCHEDULES( CPitdrone ) { slPitdroneRangeAttack1, slPitdroneChaseEnemy, slPitdroneHurtHop, slPitdroneEat, slPitdroneSniffAndEat, slPitdroneWallow, slPitdroneHideReload, slPitdroneWaitInCover }; IMPLEMENT_CUSTOM_SCHEDULES( CPitdrone, CBaseMonster ); //========================================================= // GetSchedule //========================================================= Schedule_t *CPitdrone :: GetSchedule( void ) { switch ( m_MonsterState ) { case MONSTERSTATE_ALERT: { if ( HasConditions(bits_COND_LIGHT_DAMAGE | bits_COND_HEAVY_DAMAGE) ) { return GetScheduleOfType ( SCHED_PITDRONE_HURTHOP ); } if( m_flNextEatTime <= gpGlobals->time ) { if( HasConditions( bits_COND_SMELL_FOOD ) ) { CSound *pSound; pSound = PBestScent(); if( pSound && ( !FInViewCone( &pSound->m_vecOrigin ) || !FVisible( pSound->m_vecOrigin ) ) ) { m_flNextEatTime = gpGlobals->time + 90; // scent is behind or occluded return GetScheduleOfType( SCHED_PITDRONE_SNIFF_AND_EAT ); } m_flNextEatTime = gpGlobals->time + 90; // food is right out in the open. Just go get it. return GetScheduleOfType( SCHED_PITDRONE_EAT ); } if( HasConditions( bits_COND_SMELL ) ) { // there's something stinky. CSound *pSound; pSound = PBestScent(); if( pSound ) { m_flNextEatTime = gpGlobals->time + 90; return GetScheduleOfType( SCHED_PITDRONE_WALLOW ); } } } break; } case MONSTERSTATE_COMBAT: { // dead enemy if ( HasConditions( bits_COND_ENEMY_DEAD ) ) { // call base class, all code to handle dead enemies is centralized there. return CBaseMonster :: GetSchedule(); } if ( HasConditions(bits_COND_NEW_ENEMY) ) { return GetScheduleOfType ( SCHED_WAKE_ANGRY ); } if( HasConditions( bits_COND_SEE_HATE ) && m_iInitialAmmo != -1 ) { return GetScheduleOfType( SCHED_PITDRONE_COVER_AND_RELOAD ); } if ( HasConditions( bits_COND_CAN_RANGE_ATTACK1 ) ) { return GetScheduleOfType ( SCHED_RANGE_ATTACK1 ); } if ( HasConditions( bits_COND_CAN_MELEE_ATTACK1 ) ) { return GetScheduleOfType ( SCHED_MELEE_ATTACK1 ); } if ( HasConditions( bits_COND_CAN_MELEE_ATTACK2 ) ) { return GetScheduleOfType ( SCHED_MELEE_ATTACK2 ); } return GetScheduleOfType ( SCHED_CHASE_ENEMY ); break; } } return CBaseMonster :: GetSchedule(); } //========================================================= // GetScheduleOfType //========================================================= Schedule_t* CPitdrone :: GetScheduleOfType ( int Type ) { switch ( Type ) { case SCHED_RANGE_ATTACK1: return &slPitdroneRangeAttack1[ 0 ]; break; case SCHED_PITDRONE_HURTHOP: return &slPitdroneHurtHop[ 0 ]; break; case SCHED_PITDRONE_EAT: return &slPitdroneEat[ 0 ]; break; case SCHED_PITDRONE_SNIFF_AND_EAT: return &slPitdroneSniffAndEat[ 0 ]; break; case SCHED_PITDRONE_WALLOW: return &slPitdroneWallow[ 0 ]; break; case SCHED_CHASE_ENEMY: return &slPitdroneChaseEnemy[ 0 ]; break; case SCHED_PITDRONE_COVER_AND_RELOAD: return &slPitdroneHideReload[ 0 ]; break; case SCHED_PITDRONE_WAIT_FACE_ENEMY: return &slPitdroneWaitInCover[ 0 ]; break; } return CBaseMonster :: GetScheduleOfType ( Type ); } //========================================================= // Start task - selects the correct activity and performs // any necessary calculations to start the next task on the // schedule. //========================================================= void CPitdrone :: StartTask ( Task_t *pTask ) { m_iTaskStatus = TASKSTATUS_RUNNING; switch ( pTask->iTask ) { case TASK_PITDRONE_HOPTURN: { SetActivity ( ACT_HOP ); MakeIdealYaw ( m_vecEnemyLKP ); break; } case TASK_GET_PATH_TO_ENEMY: { if ( BuildRoute ( m_hEnemy->pev->origin, bits_MF_TO_ENEMY, m_hEnemy ) ) { m_iTaskStatus = TASKSTATUS_COMPLETE; } else { ALERT ( at_aiconsole, "GetPathToEnemy failed!!\n" ); TaskFail(); } break; } default: { CBaseMonster :: StartTask ( pTask ); break; } } } //========================================================= // RunTask //========================================================= void CPitdrone :: RunTask ( Task_t *pTask ) { switch ( pTask->iTask ) { case TASK_PITDRONE_HOPTURN: { MakeIdealYaw( m_vecEnemyLKP ); ChangeYaw( pev->yaw_speed ); if ( m_fSequenceFinished ) { m_iTaskStatus = TASKSTATUS_COMPLETE; } break; } default: { CBaseMonster :: RunTask( pTask ); break; } } } void CPitdrone::CheckAmmo() { if( m_iInitialAmmo != -1 && m_cAmmoLoaded <= 0 ) { SetConditions( bits_COND_NO_AMMO_LOADED ); } } const GibData PitDroneGibs = { "models/pit_drone_gibs.mdl", 0, 7 }; void CPitdrone::GibMonster() { EMIT_SOUND( ENT( pev ), CHAN_WEAPON, "common/bodysplat.wav", 1, ATTN_NORM ); if( CVAR_GET_FLOAT( "violence_agibs" ) != 0 ) // Should never get here, but someone might call it directly { //Note: the original doesn't check for German censorship CGib::SpawnRandomGibs( pev, 6, PitDroneGibs ); // Throw alien gibs } // don't remove players! SetThink( &CBaseMonster::SUB_Remove ); pev->nextthink = gpGlobals->time; } void CPitdrone::KeyValue( KeyValueData* pkvd ) { if( FStrEq( "initammo", pkvd->szKeyName ) ) { m_iInitialAmmo = atoi( pkvd->szValue ); pkvd->fHandled = true; } else CBaseMonster::KeyValue( pkvd ); }
26.516466
141
0.635719
[ "vector", "model", "solid" ]
20b248ebc53d2e91012353ac0301a332242dcafa
1,617
hpp
C++
pythran/pythonic/numpy/rot90.hpp
Pikalchemist/Pythran
17d4108b56b3b365e089a4e1b01a09eb7e12942b
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/numpy/rot90.hpp
Pikalchemist/Pythran
17d4108b56b3b365e089a4e1b01a09eb7e12942b
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/numpy/rot90.hpp
Pikalchemist/Pythran
17d4108b56b3b365e089a4e1b01a09eb7e12942b
[ "BSD-3-Clause" ]
1
2017-03-12T20:32:36.000Z
2017-03-12T20:32:36.000Z
#ifndef PYTHONIC_NUMPY_ROT90_HPP #define PYTHONIC_NUMPY_ROT90_HPP #include "pythonic/utils/proxy.hpp" #include "pythonic/utils/numpy_conversion.hpp" #include "pythonic/types/ndarray.hpp" #include "pythonic/numpy/copy.hpp" namespace pythonic { namespace numpy { template<class T, size_t N> types::ndarray<T,N> rot90(types::ndarray<T,N> const& expr, int k=1) { if(k%4==0) return copy(expr); types::array<long, N> shape; std::copy(expr.shape.begin(), expr.shape.end(), shape.begin()); if(k%4!=2) std::swap(shape[0], shape[1]); types::ndarray<T,N> out(shape, __builtin__::None); if(k%4==1) { for(int i=0; i<out.shape[1]; ++i) for(int j=0; j<out.shape[0]; ++j) out[out.shape[0]-1-j][i] = expr[i][j]; } else if(k%4==2) { for(int i=0; i<out.shape[1]; ++i) for(int j=0; j<out.shape[0]; ++j) out[out.shape[0]-1-j][out.shape[1]-1-i] = expr[j][i]; } else { for(int i=0; i<out.shape[1]; ++i) for(int j=0; j<out.shape[0]; ++j) out[j][out.shape[1]-1-i] = expr[i][j]; } return out; } NUMPY_EXPR_TO_NDARRAY0(rot90) PROXY(pythonic::numpy, rot90); } } #endif
31.096154
81
0.429808
[ "shape" ]
20b3890df868930a17d36fb044b058a24c5f5b9c
2,204
cpp
C++
src/pow/test/test_pow_server.cpp
datavetaren/prologcoin
8583db7d99a8007f634210aefdfb92bf45596fd3
[ "MIT" ]
38
2017-06-14T07:13:10.000Z
2022-02-16T15:41:25.000Z
src/pow/test/test_pow_server.cpp
datavetaren/prologcoin
8583db7d99a8007f634210aefdfb92bf45596fd3
[ "MIT" ]
10
2017-07-01T11:13:10.000Z
2021-02-27T05:40:30.000Z
src/pow/test/test_pow_server.cpp
datavetaren/prologcoin
8583db7d99a8007f634210aefdfb92bf45596fd3
[ "MIT" ]
7
2017-07-05T20:38:51.000Z
2021-08-02T04:30:46.000Z
#include <assert.h> #include <iostream> #include <boost/filesystem.hpp> #ifdef _WIN32 #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0501 #endif #endif #include "../pow_server.hpp" #include "../observatory.hpp" #include "../pow_verifier.hpp" #include "../../common/test/test_home_dir.hpp" using namespace prologcoin::pow; static void header( const std::string &str ) { std::cout << "\n"; std::cout << "--- [" + str + "] " + std::string(60 - str.length(), '-') << "\n"; std::cout << "\n"; } static void run_server() { const std::string home_dir = find_home_dir(); // auto dir = boost::filesystem::path(home_dir); std::string pow_dir = (boost::filesystem::path(home_dir) / "src" / "pow" / "test").string(); header("Running server at port 8080"); pow_server server("localhost", "8080", pow_dir); server.run(); } static void run_scan() { header("run_scan"); char msg[8] = "hello42"; siphash_keys keys(msg, strlen(msg)); observatory<8,double> obs(keys); obs.status(); uint32_t nonce_sum = 0; for (size_t proof_number = 0; proof_number < 32; proof_number++) { uint64_t nonce_offset = static_cast<uint64_t>(nonce_sum) << 32; std::vector<projected_star> found; projected_star first_visible; uint32_t nonce = 0; if (obs.scan(nonce_offset, first_visible, found, nonce)) { std::cout << "Found dipper for proof_number=" << proof_number << " at nonce=" << nonce; uint32_t star_ids[7]; size_t i = 0; for (auto &f : found) { star_ids[i++] = f.id(); if (i == 7) break; // Extra safety } if (i == 7 && verify_dipper(obs.keys(), 8, proof_number, nonce, star_ids)) { std::cout << ": Verified! OK" << std::endl; nonce_sum += nonce + 1; } else { std::cout << ": ERROR - failed to verify!" << std::endl; break; } } } } int main(int argc, char *argv[]) { find_home_dir(argv[0]); if (argc == 1) { std::cout << "Running tests. If you want to run the server interactively, pass --server" << std::endl; } else if (argc == 2) { if (strcmp(argv[1], "--server") == 0) { run_server(); } if (strcmp(argv[1], "--scan") == 0) { run_scan(); } } return 0; }
24.21978
103
0.603902
[ "vector" ]