hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count 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 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 77k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count 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 7 1.05M | avg_line_length float64 1.21 653k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e5e9918171f8610da10971bf5ef47eacc1d9275c | 5,711 | cpp | C++ | CookieEngine/src/Render/Drawers/MiniMapDrawer.cpp | qbleuse/Cookie-Engine | 705d19d9e4c79e935e32244759ab63523dfbe6c4 | [
"CC-BY-4.0"
] | null | null | null | CookieEngine/src/Render/Drawers/MiniMapDrawer.cpp | qbleuse/Cookie-Engine | 705d19d9e4c79e935e32244759ab63523dfbe6c4 | [
"CC-BY-4.0"
] | null | null | null | CookieEngine/src/Render/Drawers/MiniMapDrawer.cpp | qbleuse/Cookie-Engine | 705d19d9e4c79e935e32244759ab63523dfbe6c4 | [
"CC-BY-4.0"
] | null | null | null | #include "Core/Math/Mat4.hpp"
#include "Render/D3D11Helper.hpp"
#include "Resources/Mesh.hpp"
#include "Resources/Texture.hpp"
#include "Core/Primitives.hpp"
#include "Resources/Map.hpp"
#include "Render/DrawDataHandler.hpp"
#include "Render/Drawers/MiniMapDrawer.hpp"
#include "Render/Camera.hpp"
using namespace Cookie::Core::Math;
using namespace Cookie::Render;
struct VS_CONSTANT_BUFFER
{
Mat4 model;
Vec4 tileNb;
};
/*======================= CONSTRUCTORS/DESTRUCTORS =======================*/
MiniMapDrawer::MiniMapDrawer():
mapMesh{Core::Primitives::CreateCube()},
quadColor{ std::make_unique<Resources::Texture>("White", Vec4(MINI_MAP_QUAD_COLOR)) }
{
InitShader();
/* creating a quad that works with line strips */
std::vector<float> vertices = { -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f,
0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f,
0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.0f, 0.0f, -1.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, -1.0f };
std::vector<unsigned int> indices = { 0 , 1, 2, 3 , 0 };
quad = std::make_unique<Resources::Mesh>("lineQuad", vertices, indices, 5);
}
MiniMapDrawer::~MiniMapDrawer()
{
if (VShader)
{
VShader->Release();
}
if (PShader)
{
PShader->Release();
}
if (VCBuffer)
{
VCBuffer->Release();
}
if (ILayout)
{
ILayout->Release();
}
}
/*======================= INIT METHODS =======================*/
void MiniMapDrawer::InitShader()
{
ID3DBlob* blob = nullptr;
std::string source = (const char*)R"(#line 27
struct VOut
{
float4 position : SV_POSITION;
float2 uv : UV;
};
cbuffer MODEL_CONSTANT : register(b0)
{
float4x4 model;
float2 tileNb;
};
cbuffer CAM_CONSTANT : register(b1)
{
float4x4 proj;
float4x4 view;
};
VOut main(float3 position : POSITION, float2 uv : UV, float3 normal : NORMAL)
{
VOut output;
output.position = mul(mul(mul(float4(position,1.0),model),view), proj);
output.uv = uv * tileNb;
return output;
}
)";
Render::CompileVertex(source, &blob, &VShader);
source = (const char*)R"(#line 83
Texture2D albedoTex : register(t0);
SamplerState WrapSampler : register(s0);
float4 main(float4 position : SV_POSITION, float2 uv : UV) : SV_TARGET
{
return float4(albedoTex.Sample(WrapSampler,uv).rgb,1.0);
})";
struct Vertex
{
Core::Math::Vec3 position;
Core::Math::Vec2 uv;
Core::Math::Vec3 normal;
};
// create the input layout object
D3D11_INPUT_ELEMENT_DESC ied[] =
{
{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, offsetof(Vertex,position), D3D11_INPUT_PER_VERTEX_DATA, 0},
{"UV", 0, DXGI_FORMAT_R32G32_FLOAT, 0, offsetof(Vertex, uv), D3D11_INPUT_PER_VERTEX_DATA, 0},
{"NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, offsetof(Vertex, normal), D3D11_INPUT_PER_VERTEX_DATA, 0},
};
Render::CreateLayout(&blob, ied, 3, &ILayout);
Render::CompilePixel(source, &PShader);
VS_CONSTANT_BUFFER vbuffer = {};
Render::CreateBuffer(&vbuffer, sizeof(VS_CONSTANT_BUFFER), &VCBuffer);
blob->Release();
}
/*======================= REALTIME METHODS =======================*/
void MiniMapDrawer::Set(const Camera& cam, const Resources::Map& map)
{
mapAlbedo = map.model.albedo;
mapTrs = map.trs.TRS;
tileNb = map.tilesNb;
Vec3 middle = cam.ScreenPointToWorldDir({ { 0.0f,0.0f } });
//Vec3 UpperRight = cam.ScreenPointToWorldDir({ { 1.0f,1.0f } });
//Vec3 DownLeft = cam.ScreenPointToWorldDir({ { -1.0f,-1.0f } });
//
float t = (-cam.pos.y) / middle.y;
middle = cam.pos + middle * t;
//t = (-cam.pos.y) / UpperRight.y;
//UpperRight = cam.pos + UpperRight * t;
//t = (-cam.pos.y) / DownLeft.y;
//DownLeft = cam.pos + DownLeft * t;
quadTrs = Mat4::Scale({ 10.0f,1.0f,10.0f }) * Mat4::Translate(middle);
}
void MiniMapDrawer::Draw()
{
/* set shader */
RendererRemote::context->VSSetShader(VShader, nullptr, 0);
RendererRemote::context->PSSetShader(PShader, nullptr, 0);
RendererRemote::context->IASetInputLayout(ILayout);
/* filling constant buffer with map info */
VS_CONSTANT_BUFFER vbuffer = {};
vbuffer.model = mapTrs;
vbuffer.tileNb = { tileNb.x,tileNb.y,0.0f,0.0f };
RendererRemote::context->VSSetConstantBuffers(0, 1, &VCBuffer);
WriteBuffer(&vbuffer, sizeof(vbuffer), 0, &VCBuffer);;
/* map texture */
if (mapAlbedo)
mapAlbedo->Set(0);
/* then draw the map */
mapMesh->Set();
mapMesh->Draw();
/* drawing the quad of view of the cam */
RendererRemote::context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP);
/* removing depth buffer */
ID3D11RenderTargetView* rtv = nullptr;
Render::RendererRemote::context->OMGetRenderTargets(1, &rtv, nullptr);
Render::RendererRemote::context->OMSetRenderTargets(1, &rtv, nullptr);
/* we can use the same shader as it is pretty close put matrix in vbuffer */
vbuffer.model = quadTrs;
WriteBuffer(&vbuffer, sizeof(vbuffer), 0, &VCBuffer);
/* set a white texture and draw */
quadColor->Set();
quad->Set();
quad->Draw();
/* when you use Getter in dx11 it adds a ref in the object,
* so we release it*/
rtv->Release();
RendererRemote::context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
} | 28.133005 | 120 | 0.596568 |
e5ec6bfd9225a596f2111ae906a938b3348f3bd1 | 2,495 | hpp | C++ | inc/dirac_op.hpp | lkeegan/canonical | 9380e8026f637e50b6354eaf9aeb6728b28bac3c | [
"MIT"
] | null | null | null | inc/dirac_op.hpp | lkeegan/canonical | 9380e8026f637e50b6354eaf9aeb6728b28bac3c | [
"MIT"
] | null | null | null | inc/dirac_op.hpp | lkeegan/canonical | 9380e8026f637e50b6354eaf9aeb6728b28bac3c | [
"MIT"
] | null | null | null | #ifndef LKEEGAN_CANONICAL_DIRAC_OP_H
#define LKEEGAN_CANONICAL_DIRAC_OP_H
#include <random>
#include "4d.hpp"
#include "Eigen3/Eigen/Eigenvalues"
#include "omp.h"
#include "su3.hpp"
// staggered space-dependent gamma matrices
// for now stored as 5x doubles per site but they are just +/- signs, and g[0]
// is just + everywhere g[4] is gamma_5
class gamma_matrices {
private:
double g_[5];
public:
double& operator[](int i) { return g_[i]; }
double operator[](int i) const { return g_[i]; }
};
// Staggered dirac operator
class dirac_op {
private:
// Construct staggered eta (gamma) matrices
void construct_eta(field<gamma_matrices>& eta, const lattice& grid);
public:
std::ranlux48 rng;
double mass;
double mu_I;
field<gamma_matrices> eta;
bool ANTI_PERIODIC_BCS = true;
bool GAUGE_LINKS_INCLUDE_ETA_BCS = false;
dirac_op(const lattice& grid, double mass, double mu_I = 0.0);
explicit dirac_op(const lattice& grid) : dirac_op::dirac_op(grid, 0.0, 0.0) {}
void apbcs_in_time(field<gauge>& U) const;
// Applies eta matrices and apbcs in time to the gauge links U
// Required before and after using EO versions of dirac op
// Toggles flag GAUGE_LINKS_INCLUDE_ETA_BCS
void apply_eta_bcs_to_U(field<gauge>& U);
void remove_eta_bcs_from_U(field<gauge>& U);
// Axial gauge: all timelike links 1 except at T-1 boundary
void gauge_fix_axial(field<gauge>& U) const;
void gaussian_P(field<gauge>& P);
void random_U(field<gauge>& U, double eps);
// Returns eigenvalues of Dirac op
// Explicitly constructs dense (3*VOL)x(3*VOL) matrix Dirac op and finds all
// eigenvalues
Eigen::MatrixXcd D_eigenvalues(field<gauge>& U);
// Same for DDdagger, but much faster since we can use a hermitian solver.
Eigen::MatrixXcd DDdagger_eigenvalues(field<gauge>& U);
// explicitly construct dirac op as dense (3*VOL)x(3*VOL) matrix
Eigen::MatrixXcd D_dense_matrix(field<gauge>& U);
// explicitly construct dense (2x3xVOL3)x(2x3xVOL3) matrix P
// diagonalise and return all eigenvalues
// NOTE: also gauge fixes U to axial gauge
// NOTE2: also multiplies single gauge link U[T-1,ix3=0] by exp(i theta)
Eigen::MatrixXcd P_eigenvalues(field<gauge>& U, double theta = 0.0);
// explicitly construct dense (2x3xVOL3)x(2x3xVOL3) matrix
// B at timeslice it, using normalisation D = 2m + U..
// MUST be lexi grid layout for U!
Eigen::MatrixXcd B_dense_matrix(field<gauge>& U, int it);
};
#endif // LKEEGAN_CANONICAL_DIRAC_OP_H | 32.828947 | 80 | 0.726653 |
e5ec74faa22ac5c889e31f6c93ef137cdb41447a | 5,108 | cc | C++ | src/tim/vx/ops/rnn_cell.cc | gdh1995/TIM-VX | 242a6bd05ae9153a6b563c39e6f6de16568812df | [
"MIT"
] | null | null | null | src/tim/vx/ops/rnn_cell.cc | gdh1995/TIM-VX | 242a6bd05ae9153a6b563c39e6f6de16568812df | [
"MIT"
] | null | null | null | src/tim/vx/ops/rnn_cell.cc | gdh1995/TIM-VX | 242a6bd05ae9153a6b563c39e6f6de16568812df | [
"MIT"
] | null | null | null | /****************************************************************************
*
* Copyright (c) 2021 Vivante Corporation
*
* 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 "tim/vx/ops.h"
#include "vsi_nn_pub.h"
#include "op_impl.h"
#include <array>
namespace tim {
namespace vx {
namespace ops {
class RNNCellImpl : public OpImpl {
public:
enum {
// signature
FULLY_CONNECTED_0_IN = 0,
FULLY_CONNECTED_0_WEIGHT = 1,
FULLY_CONNECTED_0_BIAS = 2,
FULLY_CONNECTED_1_WEIGHT = 3,
FULLY_CONNECTED_1_STATE_IN = 4,
INPUT_CNT,
OUT = 0,
STATE_OUT,
OUT_CNT,
// signature end
};
RNNCellImpl(Graph* graph, int input_cnt, int output_cnt,
DataLayout layout = DataLayout::ANY)
: OpImpl(graph, -1, input_cnt, output_cnt, layout) {
fc0_ = graph->CreateOperation<tim::vx::ops::FullyConnected>(0, 4);
fc1_ = graph->CreateOperation<tim::vx::ops::FullyConnected>(0, 4);
add_ = graph->CreateOperation<tim::vx::ops::Add>();
tanh_ = graph->CreateOperation<tim::vx::ops::Tanh>();
data_convert_ = graph->CreateOperation<tim::vx::ops::DataConvert>();
}
~RNNCellImpl() {}
RNNCellImpl& BindInput(const std::shared_ptr<Tensor>& tensor) override {
in_tensors_[input_tensor_index] = tensor;
if (this->input_tensor_index == INPUT_CNT - 1) {
// Get all input tensor
tim::vx::ShapeType shape = {0, 0};
tim::vx::TensorSpec FC0_spec(tim::vx::DataType::FLOAT32, shape,
tim::vx::TensorAttribute::TRANSIENT);
tim::vx::TensorSpec FC1_spec(tim::vx::DataType::FLOAT32, shape,
tim::vx::TensorAttribute::TRANSIENT);
tim::vx::TensorSpec add_spec(tim::vx::DataType::FLOAT32, shape,
tim::vx::TensorAttribute::TRANSIENT);
auto FC0_tensor = graph_->CreateTensor(FC0_spec);
auto FC1_tensor = graph_->CreateTensor(FC1_spec);
auto add_tensor = graph_->CreateTensor(add_spec);
fc0_->BindInput(in_tensors_[FULLY_CONNECTED_0_IN]);
fc0_->BindInput(in_tensors_[FULLY_CONNECTED_0_WEIGHT]);
fc0_->BindInput(in_tensors_[FULLY_CONNECTED_0_BIAS]);
fc0_->BindOutput(FC0_tensor);
fc1_->BindInput(in_tensors_[FULLY_CONNECTED_1_WEIGHT]);
fc1_->BindInput(in_tensors_[FULLY_CONNECTED_1_STATE_IN]);
fc1_->BindOutput(FC1_tensor);
add_->BindInput(FC0_tensor);
add_->BindInput(FC1_tensor);
add_->BindOutput(add_tensor);
tanh_->BindInput(add_tensor);
}
this->input_tensor_index++;
return *this;
}
RNNCellImpl& BindOutput(const std::shared_ptr<Tensor>& tensor) override {
out_tensors_[output_tensor_index] = tensor;
tanh_->BindOutput(out_tensors_[OUT]);
data_convert_->BindInput(out_tensors_[OUT]);
if (this->output_tensor_index == OUT_CNT - 1) {
data_convert_->BindOutput(out_tensors_[STATE_OUT]);
}
this->output_tensor_index++;
return *this;
}
vsi_nn_node_t* node() override { return nullptr; }
std::vector<std::shared_ptr<Tensor>> InputsTensor() override {
return inputs_tensor_;
}
std::vector<std::shared_ptr<Tensor>> OutputsTensor() override {
return outputs_tensor_;
}
private:
std::shared_ptr<tim::vx::Operation> fc0_;
std::shared_ptr<tim::vx::Operation> fc1_;
std::shared_ptr<tim::vx::Operation> add_;
std::shared_ptr<tim::vx::Operation> tanh_;
std::shared_ptr<tim::vx::Operation> data_convert_;
std::array<std::shared_ptr<tim::vx::Tensor>, INPUT_CNT> in_tensors_;
std::array<std::shared_ptr<tim::vx::Tensor>, OUT_CNT> out_tensors_;
};
RNNCell::RNNCell(Graph* graph, ActivationType activation)
: activation_(activation) {
impl_ = std::make_unique<RNNCellImpl>(graph, 0, 0, DataLayout::ANY);
}
std::shared_ptr<Operation> RNNCell::Clone(std::shared_ptr<Graph>& graph) const {
return graph->CreateOperation<RNNCell>(this->activation_);
}
} // namespace ops
} // namespace vx
} // namespace tim
| 35.72028 | 80 | 0.669538 |
e5f27ff62e3c8fe8f15130737b095fadf08dec16 | 3,670 | cpp | C++ | src/coinbase_pro/parser.cpp | olned/ssc2ce-cpp | 306188fa66322773721f71a8b52ea107ff2288cd | [
"BSL-1.0"
] | null | null | null | src/coinbase_pro/parser.cpp | olned/ssc2ce-cpp | 306188fa66322773721f71a8b52ea107ff2288cd | [
"BSL-1.0"
] | null | null | null | src/coinbase_pro/parser.cpp | olned/ssc2ce-cpp | 306188fa66322773721f71a8b52ea107ff2288cd | [
"BSL-1.0"
] | null | null | null | // Copyright Oleg Nedbaylo 2020.
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE
// or copy at http://www.boost.org/LICENSE_1_0.txt
#include "parser.hpp"
#include <cstdlib>
#include <fmt/format.h>
#include <iostream>
#include <rapidjson/document.h>
namespace ssc2ce {
CoinbaseParser::CoinbaseParser()
{
}
bool CoinbaseParser::parse(const char *message)
{
if (message[0] == char(0)) {
last_error_msg_ = "Empty string.";
return false;
}
last_error_msg_.clear();
using namespace rapidjson;
rapidjson::Document doc;
doc.Parse(message);
if (doc.IsNull()) {
last_error_msg_ = "Unable to parse the message, probably the wrong JSON format.";
return false;
}
bool processed = false;
if (doc.HasMember("type")) {
const char *message_type = doc["type"].GetString();
switch (message_type[0]) {
case 'a':
// activate
break;
case 'c':
// change
break;
case 'd':
// done
break;
case 'h':
// heartbeat
break;
case 'l':
// l2update
processed = handle_l2update(doc);
case 'm':
// match
break;
case 'o':
// open
break;
case 'r':
// received
break;
case 's':
switch (message_type[1]) {
case 'n':
processed = handle_snapshot(doc);
case 't':
// status
break;
default:
// subscribe
break;
}
break;
case 't':
// ticker
break;
default:
break;
}
if (!processed) {
last_error_msg_ = fmt::format("CoinbaseParser Unsupported: {} in message: {}", message_type, message);
}
} // namespace ssc2ce
else {
last_error_msg_ = fmt::format("CoinbaseParser Unknown message format: {}", message);
}
return processed;
} // namespace ssc2ce
bool CoinbaseParser::handle_snapshot(const rapidjson::Value &data)
{
auto &book = find_or_create_book(data["product_id"].GetString());
book.clear();
for (const auto &item : data["bids"].GetArray()) {
auto price = std::atof(item[0].GetString());
auto size = std::atof(item[1].GetString());
book.add_bid(price, size);
}
for (const auto &item : data["asks"].GetArray()) {
auto price = std::atof(item[0].GetString());
auto size = std::atof(item[1].GetString());
book.add_ask(price, size);
}
if (on_book_setup_)
on_book_setup_(&book);
return true;
}
bool CoinbaseParser::handle_l2update(const rapidjson::Value &data)
{
auto &book = find_or_create_book(data["product_id"].GetString());
book.set_time(data["time"].GetString());
for (const auto &item : data["changes"].GetArray()) {
if (item[0].GetString()[0] == 's') // sell
{
const auto price = std::atof(item[1].GetString());
const auto size = std::atof(item[2].GetString());
book.update_ask(price, size);
} else {
const auto price = std::atof(item[1].GetString());
const auto size = std::atof(item[2].GetString());
book.update_bid(price, size);
}
}
if (on_book_update_)
on_book_update_(&book);
return true;
}
CoinbaseBookL2 &CoinbaseParser::find_or_create_book(const std::string_view &instrumnet)
{
const auto key = std::hash<std::string_view>{}(instrumnet);
if (auto p = books_.find(key); p != books_.end()) {
return p->second;
} else {
auto [x, ok] = books_.emplace(key, CoinbaseBookL2(std::string(instrumnet)));
return x->second;
}
};
BookL2 const *CoinbaseParser::get_book(const std::string_view &instrument)
{
BookL2 const *book = &find_or_create_book(instrument);
return book;
}
} // namespace ssc2ce | 22.9375 | 108 | 0.617984 |
e5fa02c892e73170ede5a8caa420d2099b86323e | 1,006 | cpp | C++ | Projects/Demo/source/Common/ControledLightComponent.cpp | NeroBurner/ETEngine | 3fe039ff65cd1355957bcfce3f851fa411a86d94 | [
"MIT"
] | null | null | null | Projects/Demo/source/Common/ControledLightComponent.cpp | NeroBurner/ETEngine | 3fe039ff65cd1355957bcfce3f851fa411a86d94 | [
"MIT"
] | null | null | null | Projects/Demo/source/Common/ControledLightComponent.cpp | NeroBurner/ETEngine | 3fe039ff65cd1355957bcfce3f851fa411a86d94 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "ControledLightComponent.h"
#include <EtCore/Reflection/Registration.h>
namespace et {
namespace demo {
// reflection
//------------
RTTR_REGISTRATION
{
rttr::registration::class_<ControledLightComponent>("controled light component");
BEGIN_REGISTER_POLYMORPHIC_CLASS(ControledLightComponentDesc, "controled light comp desc")
END_REGISTER_POLYMORPHIC_CLASS(ControledLightComponentDesc, fw::I_ComponentDescriptor);
}
DEFINE_FORCED_LINKING(ControledLightComponentDesc) // force the linker to include this unit
ECS_REGISTER_COMPONENT(ControledLightComponent);
//======================================
// Controled Light Component Descriptor
//======================================
//---------------------------------------
// ControledLightComponentDesc::MakeData
//
// Create a spawn component from a descriptor
//
ControledLightComponent* ControledLightComponentDesc::MakeData()
{
return new ControledLightComponent();
}
} // namespace demo
} // namespace et
| 22.863636 | 91 | 0.698807 |
e5fa89f24b53ada66750cbf7e14b96d67cba0025 | 2,386 | hpp | C++ | docker/private/priority_queue.hpp | Better-Idea/Mix-C | 71f34a5fc8c17a516cf99bc397289d046364a82e | [
"Apache-2.0"
] | 41 | 2019-09-24T02:17:34.000Z | 2022-01-18T03:14:46.000Z | docker/private/priority_queue.hpp | Better-Idea/Mix-C | 71f34a5fc8c17a516cf99bc397289d046364a82e | [
"Apache-2.0"
] | 2 | 2019-11-04T09:01:40.000Z | 2020-06-23T03:03:38.000Z | docker/private/priority_queue.hpp | Better-Idea/Mix-C | 71f34a5fc8c17a516cf99bc397289d046364a82e | [
"Apache-2.0"
] | 8 | 2019-09-24T02:17:35.000Z | 2021-09-11T00:21:03.000Z | #ifndef xpack_docker_priority_queue
#define xpack_docker_priority_queue
#pragma push_macro("xuser")
#undef xuser
#define xuser mixc::docker_priority_queue::inc
#include"algo/heap_root.hpp"
#include"define/base_type.hpp"
#include"docker/shared_array.hpp"
#include"docker/transmitter.hpp"
#include"dumb/mirror.hpp"
#include"macro/xexport.hpp"
#include"macro/xis_nullptr.hpp"
#include"macro/xref.hpp"
#include"macro/xstruct.hpp"
#include"memop/cast.hpp"
#pragma pop_macro("xuser")
namespace mixc::docker_priority_queue {
template<class final_t, class item_t>
xstruct(
xtmpl(priority_queue, final_t, item_t),
xprif(m_items, inc::shared_array<item_t>)
)
using mirror = inc::shared_array<inc::mirror<item_t>>;
priority_queue(){}
template<class finalx_t >
priority_queue(priority_queue<finalx_t, item_t> const & object) :
m_items((inc::shared_array<item_t> &)object.m_items){}
priority_queue(::length initial_capacity) :
m_items(initial_capacity){}
void clear() {
the_t{}.m_items.swap(xref(m_items));
}
void push(item_t const & value) {
// 本次 push 无需拷贝构造
inc::cast<mirror>(m_items).push(inc::mirror<item_t>{});
// 本次 push 默认内部拷贝构造
inc::heap_root::push(m_items, m_items.length() - 1, value);
}
inc::transmitter<item_t> pop() {
auto length = m_items.length();
inc::transmitter<item_t> r = m_items[0];
inc::heap_root::pop(m_items, length, m_items[length - 1]);
inc::cast<mirror>(m_items).pop();
return r;
}
void swap(the_t * object){
m_items.swap(object);
}
final_t & operator= (decltype(nullptr)){
m_items = nullptr;
return thex;
}
final_t & operator= (the_t const & object){
m_items = object.m_items;
return thex;
}
xpubgetx(root, inc::transmitter<item_t>){
return m_items[0];
}
xpubgetx(length, uxx){
return m_items.length();
}
xpubgetx(is_empty, bool){
return m_items.length() == 0;
}
xis_nullptr(
m_items == nullptr
)
};
}
#endif
#define xusing_docker_name ::mixc::docker_priority_queue
| 26.808989 | 74 | 0.594719 |
e5fce778a67f3c86688c7648a8bc5fde7458882f | 2,127 | cpp | C++ | UCF HSPT Documents/2011/Solutions/genetics.cpp | p473lr/i-urge-mafia-gear | ae19efb1af2e85ed8bcbbcc3d12ae0f024f3565e | [
"Apache-2.0"
] | null | null | null | UCF HSPT Documents/2011/Solutions/genetics.cpp | p473lr/i-urge-mafia-gear | ae19efb1af2e85ed8bcbbcc3d12ae0f024f3565e | [
"Apache-2.0"
] | null | null | null | UCF HSPT Documents/2011/Solutions/genetics.cpp | p473lr/i-urge-mafia-gear | ae19efb1af2e85ed8bcbbcc3d12ae0f024f3565e | [
"Apache-2.0"
] | null | null | null | #include<iostream>
#include<fstream>
#include<cctype>
#include<cstdlib>
using namespace std;
char input[16]; //variable to store each line of input
/*
Array to manipulate the integer to genetic character conversion.
For any character its array index is the corresponding value. For example 'G' has value of 2
For for any integer the corresponding character at that integer is the genetic character.
*/
char base4chars[5] = "ACGT";
/*
A linear search to find the corresponding integer value. just search through the array base4chars for the index.
*/
int getbase4charvalue(char ch){
for(int i=0;i<4;++i){
if(base4chars[i]==ch){
return i;
}
}
return -1; //this line will never be executed
}
/*
recursively printing the base 4 representation of the integer.
*/
void base10to4(int n){
if(n==0) return;
base10to4(n/4); //before printing the last digit we need to print the bese-4 representation of n/4
cout<<base4chars[n%4];
}
/*
base 4 to base 10 conversion.
*/
int base4to10(char input[]){
int ret = 0;
for(int i=0;input[i];++i){
ret*=4;
ret+=getbase4charvalue(input[i]);
}
return ret;
}
int main(){
//Added to make the program read from file
ifstream inputFile("E:\genetics.in");
int test_cases;
//cin>>test_cases;
inputFile>>test_cases;
for(int sequence = 1 ; sequence <= test_cases ; ++sequence){
//cin>>input;
inputFile>>input;
cout<<"Sequence #"<<sequence<<": ";
/*
If the first symbol is a digit then the input is given as a base 10 integer.
*/
if(isdigit(input[0])){
int value = atoi(input); //converting the input string to an integer
base10to4(value); //outputting the base-10 input to base-4 recursively
cout<<endl;
}
/*
If the first symbol is not a digit then the input is given in base 4.
*/
else{
cout<<base4to10(input)<<endl;
}
}
return 0;
}
| 25.321429 | 113 | 0.597555 |
f90046ff57205cdeb4834d4efff9cbd713a8c33e | 2,328 | cc | C++ | cms/src/model/DeleteNotifyPolicyRequest.cc | sdk-team/aliyun-openapi-cpp-sdk | d0e92f6f33126dcdc7e40f60582304faf2c229b7 | [
"Apache-2.0"
] | 3 | 2020-01-06T08:23:14.000Z | 2022-01-22T04:41:35.000Z | cms/src/model/DeleteNotifyPolicyRequest.cc | sdk-team/aliyun-openapi-cpp-sdk | d0e92f6f33126dcdc7e40f60582304faf2c229b7 | [
"Apache-2.0"
] | null | null | null | cms/src/model/DeleteNotifyPolicyRequest.cc | sdk-team/aliyun-openapi-cpp-sdk | d0e92f6f33126dcdc7e40f60582304faf2c229b7 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/cms/model/DeleteNotifyPolicyRequest.h>
using AlibabaCloud::Cms::Model::DeleteNotifyPolicyRequest;
DeleteNotifyPolicyRequest::DeleteNotifyPolicyRequest() :
RpcServiceRequest("cms", "2018-03-08", "DeleteNotifyPolicy")
{}
DeleteNotifyPolicyRequest::~DeleteNotifyPolicyRequest()
{}
std::string DeleteNotifyPolicyRequest::getPolicyType()const
{
return policyType_;
}
void DeleteNotifyPolicyRequest::setPolicyType(const std::string& policyType)
{
policyType_ = policyType;
setParameter("PolicyType", policyType);
}
std::string DeleteNotifyPolicyRequest::getAlertName()const
{
return alertName_;
}
void DeleteNotifyPolicyRequest::setAlertName(const std::string& alertName)
{
alertName_ = alertName;
setParameter("AlertName", alertName);
}
std::string DeleteNotifyPolicyRequest::getGroupId()const
{
return groupId_;
}
void DeleteNotifyPolicyRequest::setGroupId(const std::string& groupId)
{
groupId_ = groupId;
setParameter("GroupId", groupId);
}
std::string DeleteNotifyPolicyRequest::getId()const
{
return id_;
}
void DeleteNotifyPolicyRequest::setId(const std::string& id)
{
id_ = id;
setParameter("Id", id);
}
std::string DeleteNotifyPolicyRequest::getDimensions()const
{
return dimensions_;
}
void DeleteNotifyPolicyRequest::setDimensions(const std::string& dimensions)
{
dimensions_ = dimensions;
setParameter("Dimensions", dimensions);
}
std::string DeleteNotifyPolicyRequest::getAccessKeyId()const
{
return accessKeyId_;
}
void DeleteNotifyPolicyRequest::setAccessKeyId(const std::string& accessKeyId)
{
accessKeyId_ = accessKeyId;
setParameter("AccessKeyId", accessKeyId);
}
| 24.765957 | 79 | 0.752148 |
f9024c35e6b29e9f8d8c30463ab7097cd9a2108d | 624 | cpp | C++ | src/Math.cpp | mmha/efiraytracer | bd14e70db1e5390080e47c2e619a8a20d2e75ca6 | [
"BSL-1.0"
] | 8 | 2018-03-02T17:42:15.000Z | 2021-09-14T21:59:19.000Z | src/Math.cpp | mmha/efiraytracer | bd14e70db1e5390080e47c2e619a8a20d2e75ca6 | [
"BSL-1.0"
] | null | null | null | src/Math.cpp | mmha/efiraytracer | bd14e70db1e5390080e47c2e619a8a20d2e75ca6 | [
"BSL-1.0"
] | null | null | null | #include <cstdint>
// TODO Use SSE
// http://www.myreckonings.com/Dead_Reckoning/Online/Materials/Fast_Approximation_of_Elementary_Functions.pdf
extern "C" float tanf(float x) {
float tan;
__asm__("FPTAN;" : "=t"(tan) : "0"(x));
return tan;
}
extern "C" double sqrt(double x) {
__asm__("sqrtsd %1, %0" : "+x"(x) : "x"(x), "x"(x));
return x;
}
// http://martin.ankerl.com/2012/01/25/optimized-approximative-pow-in-c-and-cpp/
extern "C" double pow(double a, double b) {
union {
double d;
int32_t x[2];
} u = {a};
u.x[1] = static_cast<int32_t>(b * (u.x[1] - 1072632447) + 1072632447);
u.x[0] = 0;
return u.d;
} | 24.96 | 109 | 0.641026 |
f9055ee5a4b61ca351341a9eff91ee855516a200 | 1,930 | cpp | C++ | Practicum_Homeworks_2021/04_Practice/main.cpp | NaskoVasilev/OOP-FMI | 00443be9ef1931beae1e06f40fbb76ea09a46d1a | [
"MIT"
] | 4 | 2020-11-14T11:22:39.000Z | 2021-11-02T08:35:24.000Z | Practicum_Homeworks_2021/04_Practice/main.cpp | NaskoVasilev/OOP-FMI | 00443be9ef1931beae1e06f40fbb76ea09a46d1a | [
"MIT"
] | null | null | null | Practicum_Homeworks_2021/04_Practice/main.cpp | NaskoVasilev/OOP-FMI | 00443be9ef1931beae1e06f40fbb76ea09a46d1a | [
"MIT"
] | 6 | 2020-11-08T12:55:25.000Z | 2022-01-23T17:33:47.000Z | #include "card.hpp"
#include "duelist.hpp"
#include <iostream>
using namespace std;
int main() {
MonsterCard *dragon = new MonsterCard("Blue-Eyes White Dragon",
"This legendary dragon is a powerful engine of destruction.", 3000, 2500, 10);
MonsterCard *magician = new MonsterCard("Dark Magician", "The ultimate wizard.", 2500, 2100, 15);
MagicCard *swords = new MagicCard("Swords of Revealing Light", "Your opponent's monsters cannot declare an attack.",
CardType::spell, 20);
MagicCard *cylinder = new MagicCard("Magic Cylinder", "Inflict damage to your opponent equal to its ATK.",
CardType::trap, 7);
PendulumCard *timegazer = new PendulumCard("Timegazer Magician", "Your opponent cannot activate Trap Magic Cards",
1200, 600, CardType::spell, 8, 5);
Duelist firstDuelist("Ivan Ivanov");
firstDuelist.getDeck().setName("Magician Deck");
firstDuelist.getDeck().addCard(dragon);
firstDuelist.getDeck().addCard(swords);
firstDuelist.getDeck().addCard(magician);
firstDuelist.getDeck().addCard(cylinder);
firstDuelist.getDeck().addCard(timegazer);
cout << "Initial deck" << endl;
firstDuelist.display();
cout << endl;
firstDuelist.loadDeck("magician_deck.txt");
cout << "The deck after loading five new cards" << endl;
firstDuelist.display();
cout << endl;
firstDuelist.saveDeck("double_deck.txt");
Duelist duelist("Atanas");
duelist.loadDeck("double_deck.txt");
MagicCard *box = new MagicCard("Mystic Box", "Destroy one monster.", CardType::spell, 5);
duelist.getDeck().setCard(5, box);
cout << "Result after changing Swords of Revealing Light with Mystic Box" << endl;
duelist.display();
cout << endl;
cout << firstDuelist.duel(duelist);
}
| 39.387755 | 120 | 0.638342 |
f905d68556ea6891fbacf9aa7d32580665bbd957 | 2,194 | cc | C++ | src/hlib/libcpp/os.cc | hascal/llvm | f9893068ec2cff12889d2a8c3f935bccda8769e3 | [
"MIT"
] | null | null | null | src/hlib/libcpp/os.cc | hascal/llvm | f9893068ec2cff12889d2a8c3f935bccda8769e3 | [
"MIT"
] | null | null | null | src/hlib/libcpp/os.cc | hascal/llvm | f9893068ec2cff12889d2a8c3f935bccda8769e3 | [
"MIT"
] | null | null | null | string os_name()
{
#ifdef _WIN32
return "win32";
#elif _WIN64
return "win64";
#elif __APPLE__ || __MACH__ || macintosh || Macintosh
return "macos";
#elif __linux__
return "linux";
#elif __FreeBSD__
return "freebsd";
#elif __unix || __unix__
return "unix";
#elif __ANDROID__
return "android";
#elif AMIGA
return "amiga";
#elif __FreeBSD__ || __OpenBSD__ || __NetBSD__ || __DragonFly__
return "bsd";
#elif __CYGWIN__
return "cygwin";
#elif __minix
return "minix";
#elif __MSDOS__
return "msdos";
#elif __sun
return "solaris";
#elif __SYMBIAN32__
return "symbian";
#elif __MVS__
return "zvm";
#else
return "unknown";
#endif
}
int system(string cmd)
{
return system(cmd.c_str());
}
bool is_x86(){
if(sizeof(void*) == 4)
return true;
else
return false;
}
bool is_64(){
return !is_x86();
}
string compiler_name(){
#ifdef __clang__
return "clang";
#elif __GNUC__
return "gcc";
#elif _MSC_VER
return "msvc";
#elif __BORLANDC__
return "bcc";
#elif __DMC__
return "dmc";
#elif __INTEL_COMPILER
return "icc";
#else
return "unknown";
#endif
}
// refernce: https://sourceforge.net/p/predef/wiki/Architectures/
string arch()
{
string comname = compiler_name();
if(comname == "msvc"){
#ifdef _M_AMD64
return "AMD64";
#elif _M_IX86
return "intel32";
#elif _M_IA64
return "ia64"; // also supports by intel c++ : __itanium__
#elif _M_PPC
return "powerpc";
#else
return "unknown";
#endif
}else if(comname == "gcc"){
#ifdef __amd64__ || __amd64
return "AMD64";
#elif __arm__
return "arm";
#elif __i386__ || __i486__ || __i586__ || __i686__
return "intel32";
#elif __ia64__
return "ia64";
#elif __mips__
return "mips";
#elif __powerpc__ || __powerpc64__
return "powerpc";
#else
return "unknown";
#endif
}
// todo : support intel c++
return "unknown";
} | 20.12844 | 67 | 0.568368 |
f90bd9d71cd5d5659b11dbb985099333744bbc32 | 3,714 | hpp | C++ | rmvmathtest/profile/Profiler.hpp | vitali-kurlovich/RMMath | a982b89e5db08e9cd16cb08e92839a315b6198dc | [
"MIT"
] | null | null | null | rmvmathtest/profile/Profiler.hpp | vitali-kurlovich/RMMath | a982b89e5db08e9cd16cb08e92839a315b6198dc | [
"MIT"
] | null | null | null | rmvmathtest/profile/Profiler.hpp | vitali-kurlovich/RMMath | a982b89e5db08e9cd16cb08e92839a315b6198dc | [
"MIT"
] | null | null | null | //
// Created by Vitali Kurlovich on 3/22/16.
//
#ifndef RMVECTORMATH_PROFILER_HPP
#define RMVECTORMATH_PROFILER_HPP
#include <vector>
#include <stack>
#include <chrono>
#include "ProfileCase.hpp"
#include <profiler/MathStatistic.hpp>
namespace profiler {
class Profiler {
protected:
std::vector<const ProfileCase*> profileCases;
std::stack<std::chrono::steady_clock::time_point> timestack;
bool _blockCout{false};
public:
void addProfileCases(const ProfileCase* profileCase ) {
profileCases.push_back(profileCase);
}
void run() {
std::cout << "Start profiling..." << std::endl;
std::vector<const ProfileCase*>::iterator i;
_blockCout = true;
for (u_int32_t iter = 0; iter < 10; iter++) {
for (i = profileCases.begin(); i != profileCases.end(); ++i) {
rmmath::MathStatistic::instance().resetAll();
(*i)->run();
}
}
_blockCout = false;
for (i = profileCases.begin(); i!= profileCases.end(); ++i) {
printProfileCaseHeader(*i);
rmmath::MathStatistic::instance().resetAll();
(*i)->run();
}
}
public:
void beginProfileCase(const char* casename) {
if (_blockCout)
return;
printBeginProfileCase(casename);
rmmath::MathStatistic::instance().resetAll();
auto now = std::chrono::steady_clock::now();
timestack.push(now);
}
void endProfileCase(const char* casename) {
if (_blockCout)
return;
auto now = std::chrono::steady_clock::now();
auto begintime = timestack.top();
timestack.pop();
std::cout << "Duration: " << std::chrono::duration_cast<std::chrono::milliseconds>(now - begintime).count() << "ms" << std::endl;
printMathStatistic();
}
protected:
void printProfileCaseHeader(const ProfileCase* profileCase) {
std::cout << "[--- " << profileCase->getName() << " ---]" << std::endl;
}
void printMathStatistic() {
bool show = false;
auto mul = rmmath::MathStatistic::instance().mul();
show |= (mul > 0);
auto div = rmmath::MathStatistic::instance().div();
show |= (div > 0);
auto sum = rmmath::MathStatistic::instance().sum();
show |= (sum > 0);
auto sub = rmmath::MathStatistic::instance().sub();
show |= (sub > 0);
auto sqrt = rmmath::MathStatistic::instance().sqrt();
show |= (sqrt > 0);
if (!show)
return;
std::cout << "[ Math Statistic ]" << std::endl;
if (sum > 0) {
std::cout << " Sum: " << sum <<std::endl;
}
if (sub > 0) {
std::cout << " Sub: " << sub <<std::endl;
}
if (mul > 0) {
std::cout << " Mul: " << mul <<std::endl;
}
if (div > 0) {
std::cout << " Div: " << div <<std::endl;
}
if (sqrt > 0) {
std::cout << " Sqrt: " << sqrt <<std::endl;
}
std::cout << "[ -------------- ]" << std::endl;
}
void printBeginProfileCase(const char* casename) {
std::cout << "+++ " << casename << " +++" << std::endl;
}
};
}
#endif //RMVECTORMATH_PROFILER_HPP
| 27.511111 | 142 | 0.469575 |
f90e466b4b041fdce6f38dfc35d3732befd0a0d3 | 1,476 | cpp | C++ | Source/source/mob_types/ship_type.cpp | Neocraftz1553/Pikifen | e10e1f9f28d4e5229db64c291a8b2ccbb013b7e2 | [
"MIT"
] | null | null | null | Source/source/mob_types/ship_type.cpp | Neocraftz1553/Pikifen | e10e1f9f28d4e5229db64c291a8b2ccbb013b7e2 | [
"MIT"
] | null | null | null | Source/source/mob_types/ship_type.cpp | Neocraftz1553/Pikifen | e10e1f9f28d4e5229db64c291a8b2ccbb013b7e2 | [
"MIT"
] | null | null | null | /*
* Copyright (c) Andre 'Espyo' Silva 2013.
* The following source file belongs to the open-source project Pikifen.
* Please read the included README and LICENSE files for more information.
* Pikmin is copyright (c) Nintendo.
*
* === FILE DESCRIPTION ===
* Ship type class and ship type-related functions.
*/
#include "ship_type.h"
#include "../functions.h"
#include "../mob_fsms/ship_fsm.h"
#include "../mobs/ship.h"
#include "../utils/string_utils.h"
/* ----------------------------------------------------------------------------
* Creates a type of ship.
*/
ship_type::ship_type() :
mob_type(MOB_CATEGORY_SHIPS),
can_heal(false),
beam_radius(0.0f) {
target_type = MOB_TARGET_TYPE_NONE;
ship_fsm::create_fsm(this);
}
/* ----------------------------------------------------------------------------
* Returns the vector of animation conversions.
*/
anim_conversion_vector ship_type::get_anim_conversions() const {
anim_conversion_vector v;
v.push_back(std::make_pair(SHIP_ANIM_IDLING, "idling"));
return v;
}
/* ----------------------------------------------------------------------------
* Loads properties from a data file.
* file:
* File to read from.
*/
void ship_type::load_properties(data_node* file) {
reader_setter rs(file);
rs.set("beam_offset_x", beam_offset.x);
rs.set("beam_offset_y", beam_offset.y);
rs.set("beam_radius", beam_radius);
rs.set("can_heal", can_heal);
}
| 26.357143 | 79 | 0.576558 |
f90ecaadb121feefac9c6a25b033eb5aded3fce0 | 3,012 | cpp | C++ | recommendation/pytorch/negative_sampling_cpp/negative_sampling.cpp | mengkai94/training | 2a0aa29e700a33e9d3bf2645d13d89fb525e29fc | [
"Apache-2.0"
] | 567 | 2018-09-13T05:07:49.000Z | 2020-11-23T11:52:11.000Z | recommendation/pytorch/negative_sampling_cpp/negative_sampling.cpp | mengkai94/training | 2a0aa29e700a33e9d3bf2645d13d89fb525e29fc | [
"Apache-2.0"
] | 222 | 2018-09-14T10:15:39.000Z | 2020-11-20T22:21:09.000Z | recommendation/pytorch/negative_sampling_cpp/negative_sampling.cpp | mengkai94/training | 2a0aa29e700a33e9d3bf2645d13d89fb525e29fc | [
"Apache-2.0"
] | 279 | 2018-09-16T12:40:29.000Z | 2020-11-17T14:22:52.000Z | #include <torch/torch.h>
#include <vector>
#include <iostream>
#include <algorithm>
#include <random>
#include <cstdint>
struct NegativeSampler {
NegativeSampler(at::Tensor positives, int n_user, int n_item) :
positives_lists(n_user)
{
std::cout << "C++ PyTorch extension for negative sampling created." << std::endl;
n_user_ = n_user;
n_item_ = n_item;
n_positives_ = positives.size(0);
preprocessPositives(positives);
}
void preprocessPositives(at::Tensor positives) {
auto positives_accessor = positives.accessor<int64_t, 2>();
for (int i = 0; i != positives.size(0); ++i) {
int user = positives_accessor[i][0];
int item = positives_accessor[i][1];
positives_lists[user].push_back(item);
}
}
at::Tensor generate_test_part(int num_negatives, int chunk_size, int user_offset) {
at::Tensor negatives = torch::empty({num_negatives * chunk_size, 2},
torch::CPU(torch::kInt64));
int i = 0;
for (int u = 0; u != chunk_size; ++u) {
int user = user_offset + u;
for (int ni = 0; ni != num_negatives; ++ni) {
bool is_positive = true;
// repeat until a negative is found
int item = -1;
while (is_positive) {
item = static_cast<int>(at::randint(0, n_item_ - 1, {1}, torch::kInt64).data<int64_t>()[0]);
// check if the sampled number is a positive
is_positive = std::binary_search(positives_lists[user].begin(), positives_lists[user].end(), item);
}
negatives[i][0] = user;
negatives[i][1] = item;
++i;
}
}
return negatives;
}
at::Tensor generate_train(int num_negatives) {
at::Tensor negatives = torch::empty({num_negatives * n_positives_, 2}, torch::CPU(torch::kInt64));
int i = 0;
for (int u = 0; u != n_user_; ++u) {
// sample num_negatives for each positives for each user
for (int ni = 0; ni != num_negatives; ++ni) {
for (int pi = 0; pi != positives_lists[u].size(); ++pi) {
bool is_positive = true;
// repeat until a negative is found
int item = -1;
while (is_positive) {
item = static_cast<int>(at::randint(0, n_item_ - 1, {1}, torch::kInt64).data<int64_t>()[0]);
// check if the sampled number is a positive
is_positive = std::binary_search(positives_lists[u].begin(),
positives_lists[u].end(), item);
}
negatives[i][0] = u;
negatives[i][1] = item;
++i;
}
}
}
return negatives;
}
private:
std::vector<std::vector<int>> positives_lists;
int n_user_;
int n_item_;
int n_positives_;
};
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
py::class_<NegativeSampler>(m, "NegativeSampler")
.def(py::init<at::Tensor, int, int>())
.def("generate_train", &NegativeSampler::generate_train)
.def("generate_test_part", &NegativeSampler::generate_test_part);
}
| 31.051546 | 109 | 0.598274 |
f90f03929ab2a10aa560ce06d4d83ad7f016ada4 | 1,214 | cpp | C++ | catboost/libs/model/formula_evaluator.cpp | smokarizadeh/catboost | 81848d19d3469d9d5345120bb3c365298a4a9b38 | [
"Apache-2.0"
] | null | null | null | catboost/libs/model/formula_evaluator.cpp | smokarizadeh/catboost | 81848d19d3469d9d5345120bb3c365298a4a9b38 | [
"Apache-2.0"
] | null | null | null | catboost/libs/model/formula_evaluator.cpp | smokarizadeh/catboost | 81848d19d3469d9d5345120bb3c365298a4a9b38 | [
"Apache-2.0"
] | 1 | 2018-08-06T14:13:12.000Z | 2018-08-06T14:13:12.000Z | #include "formula_evaluator.h"
void TFeatureCachedTreeEvaluator::Calc(size_t treeStart, size_t treeEnd, TArrayRef<double> results) const {
CB_ENSURE(results.size() == DocCount * Model.ObliviousTrees.ApproxDimension);
Fill(results.begin(), results.end(), 0.0);
TVector<TCalcerIndexType> indexesVec(BlockSize);
int id = 0;
for (size_t blockStart = 0; blockStart < DocCount; blockStart += BlockSize) {
const auto docCountInBlock = Min(BlockSize, DocCount - blockStart);
if (Model.ObliviousTrees.ApproxDimension == 1) {
CalcTrees<true, false>(
Model,
blockStart,
BinFeatures[id],
docCountInBlock,
indexesVec,
treeStart,
treeEnd,
results
);
} else {
CalcTrees<false, false>(
Model,
blockStart,
BinFeatures[id],
docCountInBlock,
indexesVec,
treeStart,
treeEnd,
results
);
}
++id;
}
}
| 31.128205 | 107 | 0.490939 |
f9104cde9716dac9c7aa4f972ebd0fdc73f1234d | 989 | cc | C++ | src/blockchain.cc | olistic/simplechainpp | 23bbd7836d7a18d0ecfda2e2953a85eded88cc07 | [
"MIT"
] | 2 | 2018-04-04T18:15:06.000Z | 2018-05-22T09:04:20.000Z | src/blockchain.cc | olistic/simplechainpp | 23bbd7836d7a18d0ecfda2e2953a85eded88cc07 | [
"MIT"
] | null | null | null | src/blockchain.cc | olistic/simplechainpp | 23bbd7836d7a18d0ecfda2e2953a85eded88cc07 | [
"MIT"
] | 1 | 2020-11-01T02:54:08.000Z | 2020-11-01T02:54:08.000Z | #include "blockchain.h"
#include "block.h"
namespace simplechain {
Blockchain::Blockchain(int difficulty) {
difficulty_ = difficulty;
last_block_ = genesis_block_;
}
int Blockchain::difficulty() const { return difficulty_; }
Block* Blockchain::last_block() const { return last_block_; }
void Blockchain::AddBlock(Block* block) {
if (block->previous_block() == last_block_ && block->IsValid()) {
last_block_ = block;
}
}
bool Blockchain::IsValid() const {
if (!last_block_) {
return false;
}
Block* block = last_block_;
while (block->previous_block()) {
if (!block->IsValid()) {
return false;
}
block = block->previous_block();
}
if (block != genesis_block_) {
return false;
}
return true;
}
// TODO: Adjust nonce to meet difficulty.
Block* Blockchain::genesis_block_ = new Block(
nullptr, "Everything should be made as simple as possible, but not simpler",
kDifficulty, 1509926400, 0);
} // namespace simplechain
| 20.183673 | 80 | 0.677452 |
f910671bb18dacb21a3fee701ad67ffed76d4d38 | 5,037 | cpp | C++ | Source/SIMPLib/Common/INamedObject.cpp | mhitzem/SIMPL | cd8a58f8d955d232ea039121cc5286cc9545c7a6 | [
"NRL"
] | 3 | 2018-01-18T18:27:02.000Z | 2021-06-13T06:10:52.000Z | Source/SIMPLib/Common/INamedObject.cpp | mhitzem/SIMPL | cd8a58f8d955d232ea039121cc5286cc9545c7a6 | [
"NRL"
] | 211 | 2016-07-27T12:18:16.000Z | 2021-11-02T13:42:11.000Z | Source/SIMPLib/Common/INamedObject.cpp | mhitzem/SIMPL | cd8a58f8d955d232ea039121cc5286cc9545c7a6 | [
"NRL"
] | 23 | 2016-02-15T21:23:47.000Z | 2021-08-11T15:35:24.000Z | /* ============================================================================
* Copyright (c) 2019 BlueQuartz Software, LLC
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* Neither the names of any of the BlueQuartz Software contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
#include "INamedObject.h"
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
INamedObject::HashType INamedObject::CreateHash(const QString& string)
{
return std::hash<std::string>()(string.toStdString());
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
INamedObject::INamedObject(const QString& name)
: m_Name(name)
, m_NameHash(CreateHash(name))
{
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
INamedObject::~INamedObject()
{
ParentCollectionType collections = getParentCollections();
for(const auto& collection : collections)
{
collection->erase(getName());
}
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
QString INamedObject::getName() const
{
return m_Name;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
bool INamedObject::setName(const QString& name)
{
for(const auto& collection : m_ParentCollctions)
{
// If collection does not exist, something has else gone wrong and requires attention.
if(collection->contains(name))
{
return false;
}
}
m_NameHash = CreateHash(name);
m_Name = name;
return true;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
INamedObject::HashType INamedObject::getNameHash() const
{
return m_NameHash;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
INamedObject::ParentCollectionType INamedObject::getParentCollections() const
{
return m_ParentCollctions;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void INamedObject::addToCollection(INamedCollection* collection)
{
m_ParentCollctions.insert(collection);
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void INamedObject::removeFromCollection(INamedCollection* collection)
{
m_ParentCollctions.erase(collection);
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
bool INamedObject::operator<(const INamedObject& other) const
{
return getNameHash() < other.getNameHash();
}
bool INamedObject::operator==(const INamedObject& other) const
{
return getNameHash() == other.getNameHash();
}
// -----------------------------------------------------------------------------
INamedObject::Pointer INamedObject::NullPointer()
{
return Pointer(static_cast<Self*>(nullptr));
}
| 35.723404 | 90 | 0.475084 |
f911468765228b7d1ecd797f927a2b1e5ad48ac8 | 3,102 | hpp | C++ | drivers/inc/reg.hpp | scatty101/imxrt1062 | 4fb991c138d16e02ed8ea58b096be2034c9e5063 | [
"MIT"
] | 2 | 2021-02-01T21:21:52.000Z | 2021-02-07T07:19:18.000Z | drivers/inc/reg.hpp | scatty101/imxrt1062 | 4fb991c138d16e02ed8ea58b096be2034c9e5063 | [
"MIT"
] | null | null | null | drivers/inc/reg.hpp | scatty101/imxrt1062 | 4fb991c138d16e02ed8ea58b096be2034c9e5063 | [
"MIT"
] | 1 | 2021-02-01T21:25:19.000Z | 2021-02-01T21:25:19.000Z | #ifndef IMXRT_DRIVERS_REG_HPP_
#define IMXRT_DRIVERS_REG_HPP_
#include <imxrt1062/hardware.hpp>
namespace imxdrivers
{
/**
* @brief DSB
*
*/
static inline void data_sync()
{
__DSB();
}
/**
* @brief Sometimes IRQ are executed so fast, that irq flag isn't cleared until leave of irq. This function solves this problem.
*
*/
static inline void irq_save_exit()
{
data_sync();
}
/**
* @brief Performs OR operation.
*
* @tparam reg_t
* @tparam value_t
* @param reg
* @param value
*/
template <typename reg_t, typename value_t>
static inline constexpr void reg_set(reg_t ®, const value_t &value = static_cast<value_t>(0))
{
reg |= static_cast<reg_t>(value);
}
/**
* @brief Performs write operation.
*
* @tparam reg_t
* @tparam value_t
* @param reg
* @param value
*/
template <typename reg_t, typename value_t>
static inline constexpr void reg_write(reg_t ®, const value_t &value = static_cast<value_t>(0))
{
reg = static_cast<reg_t>(value);
}
/**
* @brief Peforms AND NOT operation
*
* @tparam reg_t
* @tparam value_t
* @param reg
* @param value
*/
template <typename reg_t, typename value_t>
static inline constexpr void reg_clear(reg_t ®, const value_t &value = static_cast<value_t>(0))
{
reg &= static_cast<reg_t>(~value);
}
/**
* @brief Performs read operation
*
* @tparam reg_t
* @param reg
* @return constexpr reg_t
*/
template <typename reg_t>
static inline constexpr reg_t reg_get(const reg_t ®)
{
return reg;
}
template <typename reg_t, typename mask_t, typename shift_t, typename value_t>
static inline constexpr void reg_manipulate(reg_t ®, const mask_t &mask, const shift_t &shift, const value_t &value)
{
auto reg_temp = reg_get(reg);
reg_clear(reg_temp, mask);
reg_set(reg_temp, (value << shift) & mask);
reg_write(reg, reg_temp);
}
template <typename reg_t, typename bit_pos_t>
static inline bool reg_get_bit(const reg_t ®, const bit_pos_t &bit_pos)
{
return (reg_get(reg) >> bit_pos) & 0x1;
}
template <typename reg_t, typename bit_pos_t>
static inline constexpr void reg_clear_bit(reg_t ®, const bit_pos_t &bit_pos)
{
reg_clear(reg, 1 << bit_pos);
}
template <typename reg_t, typename bit_pos_t>
static inline constexpr void reg_set_bit(reg_t ®, const bit_pos_t &bit_pos)
{
reg_set(reg, 1 << bit_pos);
}
template <typename reg_t, typename bit_pos_t>
static inline constexpr void reg_manipulate_bit(reg_t ®, const bit_pos_t &bit_pos, const bool &value)
{
if (value)
{
reg_set_bit(reg, bit_pos);
}
else
{
reg_clear_bit(reg, bit_pos);
}
}
} // namespace imxdrivers
#endif // IMXRT_DRIVERS_REG_HPP_ | 25.636364 | 132 | 0.60735 |
f9132d69cfb73a32a1efd2339e5e329a8960138a | 3,396 | cpp | C++ | 2_shuffleDataSet.cpp | junteudjio/TrafficSignsRecognitionOpenCv | 6c3b617fc4ee0b427b4570fb43371e66029e08a4 | [
"Unlicense"
] | 4 | 2018-05-07T01:08:23.000Z | 2021-12-16T01:12:11.000Z | 2_shuffleDataSet.cpp | junteudjio/TrafficSignsRecognitionOpenCv | 6c3b617fc4ee0b427b4570fb43371e66029e08a4 | [
"Unlicense"
] | 1 | 2016-02-29T09:34:26.000Z | 2016-02-29T09:34:26.000Z | 2_shuffleDataSet.cpp | junteudjio/TrafficSignsRecognitionOpenCv | 6c3b617fc4ee0b427b4570fb43371e66029e08a4 | [
"Unlicense"
] | 2 | 2016-02-20T03:03:27.000Z | 2016-06-02T05:16:39.000Z | #include <stdlib.h>
#include "opencv2/opencv.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <string.h>
#include <fstream>
#include <iostream>
using namespace std;
using namespace cv;
#define RESIZED_IMG_DIM 4800
#define RAW_DATA_SET_4800 "dataset4800.txt"
#define SHUFFLE_DATA_SET_FILE_4800 "dataSetShuffle4800.yml"
#define SHUFFLE_DATA_SET_4800 "dataSetShuffle4800"
/* _______author_______
@author : TEUDJIO MBATIVOU Junior (Aspiring Data Scientist)
@mail : teudjiombativou@gmail.com
@linkedin : ma.linkedin.com/pub/junior-teudjio/8a/25b/3a1
*/
/* _______project tutor______
@tutor : ABDELHAK Ezzine ( Professor at ENSA Tanger)
@mail : ezzine.abdelhak@gmail.com
*/
/* _______DataSet Citation_______
@Ref to the dataSet : http://benchmark.ini.rub.de/?section=gtsrb&subsection=dataset
J. Stallkamp, M. Schlipsing, J. Salmen, and C. Igel. The German Traffic Sign Recognition Benchmark: A multi-class classification competition.
In Proceedings of the IEEE International Joint Conference on Neural Networks, pages 1453–1460. 2011.
@inproceedings{Stallkamp-IJCNN-2011,
author = {Johannes Stallkamp and Marc Schlipsing and Jan Salmen and Christian Igel},
booktitle = {IEEE International Joint Conference on Neural Networks},
title = {The {G}erman {T}raffic {S}ign {R}ecognition {B}enchmark: A multi-class classification competition},
year = {2011},
pages = {1453--1460}
}
*/
/* ________code utility_______
this code is used to shuffle the dataSet
*/
// convert image Vector to image 3D matrix
void convert(cv::Mat &img,int pixelArray[])
{
Mat_<cv::Vec3b>::iterator it = img.begin<cv::Vec3b>() ;
Mat_<Vec3b>::iterator itend = img.end<Vec3b>() ;
int k=0;
for(int i = 0; i < img.rows; i++)
{
for(int j = 0; j < img.cols; j++)
{
img.at<Vec3b>(i, j)[0] = pixelArray[k];
k++;
}
}
for(int i = 0; i < img.rows; i++)
{
for(int j = 0; j < img.cols; j++)
{
img.at<Vec3b>(i, j)[1] = pixelArray[k];
k++;
}
}
for(int i = 0; i < img.rows; i++)
{
for(int j = 0; j < img.cols; j++)
{
img.at<Vec3b>(i, j)[2] = pixelArray[k];
k++;
}
}
}
int main ()
{
// raw dataset file 8729(rows) * 4800(cols) not yet shuffle
std::ifstream file(RAW_DATA_SET_4800);
std::string line;
Mat dataSet;
int ligne =0;
// vector of vector containing each line of the dataset file = each image pixels (1*4800)
vector< vector<double> > vv;
// iterates through the file to construct the vector vv
while (std::getline(file, line))
{
std::istringstream iss(line);
double n;
int k = 0;
double tab[ RESIZED_IMG_DIM +1 ];
vector<double> v;
while (iss >> n)
{
if( k == RESIZED_IMG_DIM +1) break;
//tab[k] = n;
v.push_back(n);
k++;
}
//Mat img(1,RESIZED_IMG_DIM +1,CV_64F,tab);
//dataSet.push_back(img);
vv.push_back(v);
ligne ++ ;
}
// finaly we can randomly shuffle the dataSet
random_shuffle(vv.begin(), vv.end());
// save the randomized dataSet back to a file
for( int i=0; i < vv.size(); i++)
{
double* tab = &vv[i][0];
Mat img(1,RESIZED_IMG_DIM +1,CV_64F,tab);
dataSet.push_back(img);
}
FileStorage fs(SHUFFLE_DATA_SET_FILE_4800,FileStorage::WRITE);
fs<< SHUFFLE_DATA_SET_4800 << dataSet;
fs.release();
}
| 19.859649 | 145 | 0.651649 |
f9161a0c7752ad4996b90dd7c9ff0793a01177b3 | 319,755 | hpp | C++ | include/alibabacloud/pai_plugin_20220112.hpp | alibabacloud-sdk-cpp/paiplugin-20220112 | 350e03cc56139f270d6ef0eb75b474a79d9ded8d | [
"Apache-2.0"
] | null | null | null | include/alibabacloud/pai_plugin_20220112.hpp | alibabacloud-sdk-cpp/paiplugin-20220112 | 350e03cc56139f270d6ef0eb75b474a79d9ded8d | [
"Apache-2.0"
] | null | null | null | include/alibabacloud/pai_plugin_20220112.hpp | alibabacloud-sdk-cpp/paiplugin-20220112 | 350e03cc56139f270d6ef0eb75b474a79d9ded8d | [
"Apache-2.0"
] | null | null | null | // This file is auto-generated, don't edit it. Thanks.
#ifndef ALIBABACLOUD_PAIPLUGIN20220112_H_
#define ALIBABACLOUD_PAIPLUGIN20220112_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_PaiPlugin20220112 {
class CreateCampaignRequest : public Darabonba::Model {
public:
shared_ptr<string> name{};
shared_ptr<string> remark{};
CreateCampaignRequest() {}
explicit CreateCampaignRequest(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 (remark) {
res["Remark"] = boost::any(*remark);
}
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("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
}
virtual ~CreateCampaignRequest() = default;
};
class CreateCampaignResponseBodyData : public Darabonba::Model {
public:
shared_ptr<string> createdTime{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<string> remark{};
shared_ptr<string> updatedTime{};
CreateCampaignResponseBodyData() {}
explicit CreateCampaignResponseBodyData(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 (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
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<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
}
virtual ~CreateCampaignResponseBodyData() = default;
};
class CreateCampaignResponseBody : public Darabonba::Model {
public:
shared_ptr<CreateCampaignResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
CreateCampaignResponseBody() {}
explicit CreateCampaignResponseBody(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 (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
CreateCampaignResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<CreateCampaignResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~CreateCampaignResponseBody() = default;
};
class CreateCampaignResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<CreateCampaignResponseBody> body{};
CreateCampaignResponse() {}
explicit CreateCampaignResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
CreateCampaignResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<CreateCampaignResponseBody>(model1);
}
}
}
virtual ~CreateCampaignResponse() = default;
};
class CreateGroupRequest : public Darabonba::Model {
public:
shared_ptr<string> algorithm{};
shared_ptr<string> column{};
shared_ptr<string> filter{};
shared_ptr<string> inferenceJobId{};
shared_ptr<string> name{};
shared_ptr<bool> phoneNumber{};
shared_ptr<string> project{};
shared_ptr<string> remark{};
shared_ptr<long> source{};
shared_ptr<string> table{};
shared_ptr<string> text{};
shared_ptr<string> uri{};
CreateGroupRequest() {}
explicit CreateGroupRequest(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 (algorithm) {
res["Algorithm"] = boost::any(*algorithm);
}
if (column) {
res["Column"] = boost::any(*column);
}
if (filter) {
res["Filter"] = boost::any(*filter);
}
if (inferenceJobId) {
res["InferenceJobId"] = boost::any(*inferenceJobId);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (phoneNumber) {
res["PhoneNumber"] = boost::any(*phoneNumber);
}
if (project) {
res["Project"] = boost::any(*project);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (source) {
res["Source"] = boost::any(*source);
}
if (table) {
res["Table"] = boost::any(*table);
}
if (text) {
res["Text"] = boost::any(*text);
}
if (uri) {
res["Uri"] = boost::any(*uri);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Algorithm") != m.end() && !m["Algorithm"].empty()) {
algorithm = make_shared<string>(boost::any_cast<string>(m["Algorithm"]));
}
if (m.find("Column") != m.end() && !m["Column"].empty()) {
column = make_shared<string>(boost::any_cast<string>(m["Column"]));
}
if (m.find("Filter") != m.end() && !m["Filter"].empty()) {
filter = make_shared<string>(boost::any_cast<string>(m["Filter"]));
}
if (m.find("InferenceJobId") != m.end() && !m["InferenceJobId"].empty()) {
inferenceJobId = make_shared<string>(boost::any_cast<string>(m["InferenceJobId"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("PhoneNumber") != m.end() && !m["PhoneNumber"].empty()) {
phoneNumber = make_shared<bool>(boost::any_cast<bool>(m["PhoneNumber"]));
}
if (m.find("Project") != m.end() && !m["Project"].empty()) {
project = make_shared<string>(boost::any_cast<string>(m["Project"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("Source") != m.end() && !m["Source"].empty()) {
source = make_shared<long>(boost::any_cast<long>(m["Source"]));
}
if (m.find("Table") != m.end() && !m["Table"].empty()) {
table = make_shared<string>(boost::any_cast<string>(m["Table"]));
}
if (m.find("Text") != m.end() && !m["Text"].empty()) {
text = make_shared<string>(boost::any_cast<string>(m["Text"]));
}
if (m.find("Uri") != m.end() && !m["Uri"].empty()) {
uri = make_shared<string>(boost::any_cast<string>(m["Uri"]));
}
}
virtual ~CreateGroupRequest() = default;
};
class CreateGroupResponseBodyData : public Darabonba::Model {
public:
shared_ptr<string> algorithm{};
shared_ptr<long> amount{};
shared_ptr<string> column{};
shared_ptr<string> createdTime{};
shared_ptr<string> filter{};
shared_ptr<string> id{};
shared_ptr<string> inferenceJobId{};
shared_ptr<string> name{};
shared_ptr<bool> phoneNumber{};
shared_ptr<string> project{};
shared_ptr<string> remark{};
shared_ptr<long> source{};
shared_ptr<long> status{};
shared_ptr<string> table{};
shared_ptr<string> text{};
shared_ptr<string> updatedTime{};
shared_ptr<string> uri{};
CreateGroupResponseBodyData() {}
explicit CreateGroupResponseBodyData(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 (algorithm) {
res["Algorithm"] = boost::any(*algorithm);
}
if (amount) {
res["Amount"] = boost::any(*amount);
}
if (column) {
res["Column"] = boost::any(*column);
}
if (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (filter) {
res["Filter"] = boost::any(*filter);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (inferenceJobId) {
res["InferenceJobId"] = boost::any(*inferenceJobId);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (phoneNumber) {
res["PhoneNumber"] = boost::any(*phoneNumber);
}
if (project) {
res["Project"] = boost::any(*project);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (source) {
res["Source"] = boost::any(*source);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (table) {
res["Table"] = boost::any(*table);
}
if (text) {
res["Text"] = boost::any(*text);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
if (uri) {
res["Uri"] = boost::any(*uri);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Algorithm") != m.end() && !m["Algorithm"].empty()) {
algorithm = make_shared<string>(boost::any_cast<string>(m["Algorithm"]));
}
if (m.find("Amount") != m.end() && !m["Amount"].empty()) {
amount = make_shared<long>(boost::any_cast<long>(m["Amount"]));
}
if (m.find("Column") != m.end() && !m["Column"].empty()) {
column = make_shared<string>(boost::any_cast<string>(m["Column"]));
}
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("Filter") != m.end() && !m["Filter"].empty()) {
filter = make_shared<string>(boost::any_cast<string>(m["Filter"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("InferenceJobId") != m.end() && !m["InferenceJobId"].empty()) {
inferenceJobId = make_shared<string>(boost::any_cast<string>(m["InferenceJobId"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("PhoneNumber") != m.end() && !m["PhoneNumber"].empty()) {
phoneNumber = make_shared<bool>(boost::any_cast<bool>(m["PhoneNumber"]));
}
if (m.find("Project") != m.end() && !m["Project"].empty()) {
project = make_shared<string>(boost::any_cast<string>(m["Project"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("Source") != m.end() && !m["Source"].empty()) {
source = make_shared<long>(boost::any_cast<long>(m["Source"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("Table") != m.end() && !m["Table"].empty()) {
table = make_shared<string>(boost::any_cast<string>(m["Table"]));
}
if (m.find("Text") != m.end() && !m["Text"].empty()) {
text = make_shared<string>(boost::any_cast<string>(m["Text"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
if (m.find("Uri") != m.end() && !m["Uri"].empty()) {
uri = make_shared<string>(boost::any_cast<string>(m["Uri"]));
}
}
virtual ~CreateGroupResponseBodyData() = default;
};
class CreateGroupResponseBody : public Darabonba::Model {
public:
shared_ptr<CreateGroupResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
CreateGroupResponseBody() {}
explicit CreateGroupResponseBody(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 (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
CreateGroupResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<CreateGroupResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~CreateGroupResponseBody() = default;
};
class CreateGroupResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<CreateGroupResponseBody> body{};
CreateGroupResponse() {}
explicit CreateGroupResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
CreateGroupResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<CreateGroupResponseBody>(model1);
}
}
}
virtual ~CreateGroupResponse() = default;
};
class CreateInferenceJobRequest : public Darabonba::Model {
public:
shared_ptr<string> algorithm{};
shared_ptr<string> campaignId{};
shared_ptr<string> dataPath{};
shared_ptr<string> name{};
shared_ptr<string> remark{};
shared_ptr<string> targetPath{};
shared_ptr<string> trainingJobId{};
shared_ptr<string> userConfig{};
CreateInferenceJobRequest() {}
explicit CreateInferenceJobRequest(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 (algorithm) {
res["Algorithm"] = boost::any(*algorithm);
}
if (campaignId) {
res["CampaignId"] = boost::any(*campaignId);
}
if (dataPath) {
res["DataPath"] = boost::any(*dataPath);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (targetPath) {
res["TargetPath"] = boost::any(*targetPath);
}
if (trainingJobId) {
res["TrainingJobId"] = boost::any(*trainingJobId);
}
if (userConfig) {
res["UserConfig"] = boost::any(*userConfig);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Algorithm") != m.end() && !m["Algorithm"].empty()) {
algorithm = make_shared<string>(boost::any_cast<string>(m["Algorithm"]));
}
if (m.find("CampaignId") != m.end() && !m["CampaignId"].empty()) {
campaignId = make_shared<string>(boost::any_cast<string>(m["CampaignId"]));
}
if (m.find("DataPath") != m.end() && !m["DataPath"].empty()) {
dataPath = make_shared<string>(boost::any_cast<string>(m["DataPath"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("TargetPath") != m.end() && !m["TargetPath"].empty()) {
targetPath = make_shared<string>(boost::any_cast<string>(m["TargetPath"]));
}
if (m.find("TrainingJobId") != m.end() && !m["TrainingJobId"].empty()) {
trainingJobId = make_shared<string>(boost::any_cast<string>(m["TrainingJobId"]));
}
if (m.find("UserConfig") != m.end() && !m["UserConfig"].empty()) {
userConfig = make_shared<string>(boost::any_cast<string>(m["UserConfig"]));
}
}
virtual ~CreateInferenceJobRequest() = default;
};
class CreateInferenceJobResponseBodyData : public Darabonba::Model {
public:
shared_ptr<string> algorithm{};
shared_ptr<string> campaignId{};
shared_ptr<string> createdTime{};
shared_ptr<string> dataPath{};
shared_ptr<string> groupId{};
shared_ptr<string> history{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<string> remark{};
shared_ptr<long> status{};
shared_ptr<string> targetPath{};
shared_ptr<string> trainingJobId{};
shared_ptr<string> updatedTime{};
shared_ptr<string> userConfig{};
CreateInferenceJobResponseBodyData() {}
explicit CreateInferenceJobResponseBodyData(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 (algorithm) {
res["Algorithm"] = boost::any(*algorithm);
}
if (campaignId) {
res["CampaignId"] = boost::any(*campaignId);
}
if (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (dataPath) {
res["DataPath"] = boost::any(*dataPath);
}
if (groupId) {
res["GroupId"] = boost::any(*groupId);
}
if (history) {
res["History"] = boost::any(*history);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (targetPath) {
res["TargetPath"] = boost::any(*targetPath);
}
if (trainingJobId) {
res["TrainingJobId"] = boost::any(*trainingJobId);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
if (userConfig) {
res["UserConfig"] = boost::any(*userConfig);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Algorithm") != m.end() && !m["Algorithm"].empty()) {
algorithm = make_shared<string>(boost::any_cast<string>(m["Algorithm"]));
}
if (m.find("CampaignId") != m.end() && !m["CampaignId"].empty()) {
campaignId = make_shared<string>(boost::any_cast<string>(m["CampaignId"]));
}
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("DataPath") != m.end() && !m["DataPath"].empty()) {
dataPath = make_shared<string>(boost::any_cast<string>(m["DataPath"]));
}
if (m.find("GroupId") != m.end() && !m["GroupId"].empty()) {
groupId = make_shared<string>(boost::any_cast<string>(m["GroupId"]));
}
if (m.find("History") != m.end() && !m["History"].empty()) {
history = make_shared<string>(boost::any_cast<string>(m["History"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("TargetPath") != m.end() && !m["TargetPath"].empty()) {
targetPath = make_shared<string>(boost::any_cast<string>(m["TargetPath"]));
}
if (m.find("TrainingJobId") != m.end() && !m["TrainingJobId"].empty()) {
trainingJobId = make_shared<string>(boost::any_cast<string>(m["TrainingJobId"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
if (m.find("UserConfig") != m.end() && !m["UserConfig"].empty()) {
userConfig = make_shared<string>(boost::any_cast<string>(m["UserConfig"]));
}
}
virtual ~CreateInferenceJobResponseBodyData() = default;
};
class CreateInferenceJobResponseBody : public Darabonba::Model {
public:
shared_ptr<CreateInferenceJobResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
CreateInferenceJobResponseBody() {}
explicit CreateInferenceJobResponseBody(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 (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
CreateInferenceJobResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<CreateInferenceJobResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~CreateInferenceJobResponseBody() = default;
};
class CreateInferenceJobResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<CreateInferenceJobResponseBody> body{};
CreateInferenceJobResponse() {}
explicit CreateInferenceJobResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
CreateInferenceJobResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<CreateInferenceJobResponseBody>(model1);
}
}
}
virtual ~CreateInferenceJobResponse() = default;
};
class CreateScheduleRequest : public Darabonba::Model {
public:
shared_ptr<long> endTime{};
shared_ptr<string> executeTime{};
shared_ptr<string> groupId{};
shared_ptr<string> name{};
shared_ptr<long> repeatCycle{};
shared_ptr<long> repeatCycleUnit{};
shared_ptr<long> repeatTimes{};
shared_ptr<string> signName{};
shared_ptr<string> signatureId{};
shared_ptr<string> templateCode{};
shared_ptr<string> templateId{};
CreateScheduleRequest() {}
explicit CreateScheduleRequest(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 (executeTime) {
res["ExecuteTime"] = boost::any(*executeTime);
}
if (groupId) {
res["GroupId"] = boost::any(*groupId);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (repeatCycle) {
res["RepeatCycle"] = boost::any(*repeatCycle);
}
if (repeatCycleUnit) {
res["RepeatCycleUnit"] = boost::any(*repeatCycleUnit);
}
if (repeatTimes) {
res["RepeatTimes"] = boost::any(*repeatTimes);
}
if (signName) {
res["SignName"] = boost::any(*signName);
}
if (signatureId) {
res["SignatureId"] = boost::any(*signatureId);
}
if (templateCode) {
res["TemplateCode"] = boost::any(*templateCode);
}
if (templateId) {
res["TemplateId"] = boost::any(*templateId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("EndTime") != m.end() && !m["EndTime"].empty()) {
endTime = make_shared<long>(boost::any_cast<long>(m["EndTime"]));
}
if (m.find("ExecuteTime") != m.end() && !m["ExecuteTime"].empty()) {
executeTime = make_shared<string>(boost::any_cast<string>(m["ExecuteTime"]));
}
if (m.find("GroupId") != m.end() && !m["GroupId"].empty()) {
groupId = make_shared<string>(boost::any_cast<string>(m["GroupId"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("RepeatCycle") != m.end() && !m["RepeatCycle"].empty()) {
repeatCycle = make_shared<long>(boost::any_cast<long>(m["RepeatCycle"]));
}
if (m.find("RepeatCycleUnit") != m.end() && !m["RepeatCycleUnit"].empty()) {
repeatCycleUnit = make_shared<long>(boost::any_cast<long>(m["RepeatCycleUnit"]));
}
if (m.find("RepeatTimes") != m.end() && !m["RepeatTimes"].empty()) {
repeatTimes = make_shared<long>(boost::any_cast<long>(m["RepeatTimes"]));
}
if (m.find("SignName") != m.end() && !m["SignName"].empty()) {
signName = make_shared<string>(boost::any_cast<string>(m["SignName"]));
}
if (m.find("SignatureId") != m.end() && !m["SignatureId"].empty()) {
signatureId = make_shared<string>(boost::any_cast<string>(m["SignatureId"]));
}
if (m.find("TemplateCode") != m.end() && !m["TemplateCode"].empty()) {
templateCode = make_shared<string>(boost::any_cast<string>(m["TemplateCode"]));
}
if (m.find("TemplateId") != m.end() && !m["TemplateId"].empty()) {
templateId = make_shared<string>(boost::any_cast<string>(m["TemplateId"]));
}
}
virtual ~CreateScheduleRequest() = default;
};
class CreateScheduleResponseBodyData : public Darabonba::Model {
public:
shared_ptr<string> createdTime{};
shared_ptr<long> endTime{};
shared_ptr<string> executeTime{};
shared_ptr<string> groupId{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<long> repeatCycle{};
shared_ptr<long> repeatCycleUnit{};
shared_ptr<long> repeatTimes{};
shared_ptr<string> signName{};
shared_ptr<string> signatureId{};
shared_ptr<long> status{};
shared_ptr<string> templateCode{};
shared_ptr<string> templateId{};
shared_ptr<string> updatedTime{};
CreateScheduleResponseBodyData() {}
explicit CreateScheduleResponseBodyData(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 (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (endTime) {
res["EndTime"] = boost::any(*endTime);
}
if (executeTime) {
res["ExecuteTime"] = boost::any(*executeTime);
}
if (groupId) {
res["GroupId"] = boost::any(*groupId);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (repeatCycle) {
res["RepeatCycle"] = boost::any(*repeatCycle);
}
if (repeatCycleUnit) {
res["RepeatCycleUnit"] = boost::any(*repeatCycleUnit);
}
if (repeatTimes) {
res["RepeatTimes"] = boost::any(*repeatTimes);
}
if (signName) {
res["SignName"] = boost::any(*signName);
}
if (signatureId) {
res["SignatureId"] = boost::any(*signatureId);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (templateCode) {
res["TemplateCode"] = boost::any(*templateCode);
}
if (templateId) {
res["TemplateId"] = boost::any(*templateId);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("EndTime") != m.end() && !m["EndTime"].empty()) {
endTime = make_shared<long>(boost::any_cast<long>(m["EndTime"]));
}
if (m.find("ExecuteTime") != m.end() && !m["ExecuteTime"].empty()) {
executeTime = make_shared<string>(boost::any_cast<string>(m["ExecuteTime"]));
}
if (m.find("GroupId") != m.end() && !m["GroupId"].empty()) {
groupId = make_shared<string>(boost::any_cast<string>(m["GroupId"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("RepeatCycle") != m.end() && !m["RepeatCycle"].empty()) {
repeatCycle = make_shared<long>(boost::any_cast<long>(m["RepeatCycle"]));
}
if (m.find("RepeatCycleUnit") != m.end() && !m["RepeatCycleUnit"].empty()) {
repeatCycleUnit = make_shared<long>(boost::any_cast<long>(m["RepeatCycleUnit"]));
}
if (m.find("RepeatTimes") != m.end() && !m["RepeatTimes"].empty()) {
repeatTimes = make_shared<long>(boost::any_cast<long>(m["RepeatTimes"]));
}
if (m.find("SignName") != m.end() && !m["SignName"].empty()) {
signName = make_shared<string>(boost::any_cast<string>(m["SignName"]));
}
if (m.find("SignatureId") != m.end() && !m["SignatureId"].empty()) {
signatureId = make_shared<string>(boost::any_cast<string>(m["SignatureId"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("TemplateCode") != m.end() && !m["TemplateCode"].empty()) {
templateCode = make_shared<string>(boost::any_cast<string>(m["TemplateCode"]));
}
if (m.find("TemplateId") != m.end() && !m["TemplateId"].empty()) {
templateId = make_shared<string>(boost::any_cast<string>(m["TemplateId"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
}
virtual ~CreateScheduleResponseBodyData() = default;
};
class CreateScheduleResponseBody : public Darabonba::Model {
public:
shared_ptr<CreateScheduleResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
CreateScheduleResponseBody() {}
explicit CreateScheduleResponseBody(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 (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
CreateScheduleResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<CreateScheduleResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~CreateScheduleResponseBody() = default;
};
class CreateScheduleResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<CreateScheduleResponseBody> body{};
CreateScheduleResponse() {}
explicit CreateScheduleResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
CreateScheduleResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<CreateScheduleResponseBody>(model1);
}
}
}
virtual ~CreateScheduleResponse() = default;
};
class CreateSignatureRequest : public Darabonba::Model {
public:
shared_ptr<string> description{};
shared_ptr<string> name{};
CreateSignatureRequest() {}
explicit CreateSignatureRequest(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 (description) {
res["Description"] = boost::any(*description);
}
if (name) {
res["Name"] = boost::any(*name);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Description") != m.end() && !m["Description"].empty()) {
description = make_shared<string>(boost::any_cast<string>(m["Description"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
}
virtual ~CreateSignatureRequest() = default;
};
class CreateSignatureResponseBodyData : public Darabonba::Model {
public:
shared_ptr<string> createdTime{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<long> status{};
shared_ptr<string> updatedTime{};
CreateSignatureResponseBodyData() {}
explicit CreateSignatureResponseBodyData(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 (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
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<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
}
virtual ~CreateSignatureResponseBodyData() = default;
};
class CreateSignatureResponseBody : public Darabonba::Model {
public:
shared_ptr<CreateSignatureResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
CreateSignatureResponseBody() {}
explicit CreateSignatureResponseBody(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 (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
CreateSignatureResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<CreateSignatureResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~CreateSignatureResponseBody() = default;
};
class CreateSignatureResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<CreateSignatureResponseBody> body{};
CreateSignatureResponse() {}
explicit CreateSignatureResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
CreateSignatureResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<CreateSignatureResponseBody>(model1);
}
}
}
virtual ~CreateSignatureResponse() = default;
};
class CreateTemplateRequest : public Darabonba::Model {
public:
shared_ptr<string> content{};
shared_ptr<string> description{};
shared_ptr<string> name{};
shared_ptr<string> signature{};
shared_ptr<string> signatureId{};
shared_ptr<long> type{};
CreateTemplateRequest() {}
explicit CreateTemplateRequest(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 (content) {
res["Content"] = boost::any(*content);
}
if (description) {
res["Description"] = boost::any(*description);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (signature) {
res["Signature"] = boost::any(*signature);
}
if (signatureId) {
res["SignatureId"] = boost::any(*signatureId);
}
if (type) {
res["Type"] = boost::any(*type);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Content") != m.end() && !m["Content"].empty()) {
content = make_shared<string>(boost::any_cast<string>(m["Content"]));
}
if (m.find("Description") != m.end() && !m["Description"].empty()) {
description = make_shared<string>(boost::any_cast<string>(m["Description"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Signature") != m.end() && !m["Signature"].empty()) {
signature = make_shared<string>(boost::any_cast<string>(m["Signature"]));
}
if (m.find("SignatureId") != m.end() && !m["SignatureId"].empty()) {
signatureId = make_shared<string>(boost::any_cast<string>(m["SignatureId"]));
}
if (m.find("Type") != m.end() && !m["Type"].empty()) {
type = make_shared<long>(boost::any_cast<long>(m["Type"]));
}
}
virtual ~CreateTemplateRequest() = default;
};
class CreateTemplateResponseBodyData : public Darabonba::Model {
public:
shared_ptr<string> content{};
shared_ptr<string> createdTime{};
shared_ptr<string> description{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<string> reason{};
shared_ptr<string> signatureId{};
shared_ptr<long> status{};
shared_ptr<string> templateCode{};
shared_ptr<long> type{};
shared_ptr<string> updatedTime{};
CreateTemplateResponseBodyData() {}
explicit CreateTemplateResponseBodyData(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 (content) {
res["Content"] = boost::any(*content);
}
if (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (description) {
res["Description"] = boost::any(*description);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (reason) {
res["Reason"] = boost::any(*reason);
}
if (signatureId) {
res["SignatureId"] = boost::any(*signatureId);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (templateCode) {
res["TemplateCode"] = boost::any(*templateCode);
}
if (type) {
res["Type"] = boost::any(*type);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Content") != m.end() && !m["Content"].empty()) {
content = make_shared<string>(boost::any_cast<string>(m["Content"]));
}
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("Description") != m.end() && !m["Description"].empty()) {
description = make_shared<string>(boost::any_cast<string>(m["Description"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Reason") != m.end() && !m["Reason"].empty()) {
reason = make_shared<string>(boost::any_cast<string>(m["Reason"]));
}
if (m.find("SignatureId") != m.end() && !m["SignatureId"].empty()) {
signatureId = make_shared<string>(boost::any_cast<string>(m["SignatureId"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("TemplateCode") != m.end() && !m["TemplateCode"].empty()) {
templateCode = make_shared<string>(boost::any_cast<string>(m["TemplateCode"]));
}
if (m.find("Type") != m.end() && !m["Type"].empty()) {
type = make_shared<long>(boost::any_cast<long>(m["Type"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
}
virtual ~CreateTemplateResponseBodyData() = default;
};
class CreateTemplateResponseBody : public Darabonba::Model {
public:
shared_ptr<CreateTemplateResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
CreateTemplateResponseBody() {}
explicit CreateTemplateResponseBody(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 (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
CreateTemplateResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<CreateTemplateResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~CreateTemplateResponseBody() = default;
};
class CreateTemplateResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<CreateTemplateResponseBody> body{};
CreateTemplateResponse() {}
explicit CreateTemplateResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
CreateTemplateResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<CreateTemplateResponseBody>(model1);
}
}
}
virtual ~CreateTemplateResponse() = default;
};
class CreateTrainingJobRequest : public Darabonba::Model {
public:
shared_ptr<string> algorithm{};
shared_ptr<string> campaignId{};
shared_ptr<string> dataPath{};
shared_ptr<string> name{};
shared_ptr<string> remark{};
shared_ptr<string> userConfig{};
CreateTrainingJobRequest() {}
explicit CreateTrainingJobRequest(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 (algorithm) {
res["Algorithm"] = boost::any(*algorithm);
}
if (campaignId) {
res["CampaignId"] = boost::any(*campaignId);
}
if (dataPath) {
res["DataPath"] = boost::any(*dataPath);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (userConfig) {
res["UserConfig"] = boost::any(*userConfig);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Algorithm") != m.end() && !m["Algorithm"].empty()) {
algorithm = make_shared<string>(boost::any_cast<string>(m["Algorithm"]));
}
if (m.find("CampaignId") != m.end() && !m["CampaignId"].empty()) {
campaignId = make_shared<string>(boost::any_cast<string>(m["CampaignId"]));
}
if (m.find("DataPath") != m.end() && !m["DataPath"].empty()) {
dataPath = make_shared<string>(boost::any_cast<string>(m["DataPath"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("UserConfig") != m.end() && !m["UserConfig"].empty()) {
userConfig = make_shared<string>(boost::any_cast<string>(m["UserConfig"]));
}
}
virtual ~CreateTrainingJobRequest() = default;
};
class CreateTrainingJobResponseBodyData : public Darabonba::Model {
public:
shared_ptr<string> algorithm{};
shared_ptr<string> campaignId{};
shared_ptr<string> createdTime{};
shared_ptr<string> dataPath{};
shared_ptr<string> history{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<string> remark{};
shared_ptr<long> status{};
shared_ptr<string> updatedTime{};
shared_ptr<string> userConfig{};
CreateTrainingJobResponseBodyData() {}
explicit CreateTrainingJobResponseBodyData(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 (algorithm) {
res["Algorithm"] = boost::any(*algorithm);
}
if (campaignId) {
res["CampaignId"] = boost::any(*campaignId);
}
if (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (dataPath) {
res["DataPath"] = boost::any(*dataPath);
}
if (history) {
res["History"] = boost::any(*history);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
if (userConfig) {
res["UserConfig"] = boost::any(*userConfig);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Algorithm") != m.end() && !m["Algorithm"].empty()) {
algorithm = make_shared<string>(boost::any_cast<string>(m["Algorithm"]));
}
if (m.find("CampaignId") != m.end() && !m["CampaignId"].empty()) {
campaignId = make_shared<string>(boost::any_cast<string>(m["CampaignId"]));
}
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("DataPath") != m.end() && !m["DataPath"].empty()) {
dataPath = make_shared<string>(boost::any_cast<string>(m["DataPath"]));
}
if (m.find("History") != m.end() && !m["History"].empty()) {
history = make_shared<string>(boost::any_cast<string>(m["History"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
if (m.find("UserConfig") != m.end() && !m["UserConfig"].empty()) {
userConfig = make_shared<string>(boost::any_cast<string>(m["UserConfig"]));
}
}
virtual ~CreateTrainingJobResponseBodyData() = default;
};
class CreateTrainingJobResponseBody : public Darabonba::Model {
public:
shared_ptr<CreateTrainingJobResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
CreateTrainingJobResponseBody() {}
explicit CreateTrainingJobResponseBody(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 (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
CreateTrainingJobResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<CreateTrainingJobResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~CreateTrainingJobResponseBody() = default;
};
class CreateTrainingJobResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<CreateTrainingJobResponseBody> body{};
CreateTrainingJobResponse() {}
explicit CreateTrainingJobResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
CreateTrainingJobResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<CreateTrainingJobResponseBody>(model1);
}
}
}
virtual ~CreateTrainingJobResponse() = default;
};
class DeleteCampaignResponseBody : public Darabonba::Model {
public:
shared_ptr<string> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
DeleteCampaignResponseBody() {}
explicit DeleteCampaignResponseBody(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 (data) {
res["Data"] = boost::any(*data);
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
data = make_shared<string>(boost::any_cast<string>(m["Data"]));
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~DeleteCampaignResponseBody() = default;
};
class DeleteCampaignResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<DeleteCampaignResponseBody> body{};
DeleteCampaignResponse() {}
explicit DeleteCampaignResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
DeleteCampaignResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<DeleteCampaignResponseBody>(model1);
}
}
}
virtual ~DeleteCampaignResponse() = default;
};
class DeleteGroupResponseBody : public Darabonba::Model {
public:
shared_ptr<string> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
DeleteGroupResponseBody() {}
explicit DeleteGroupResponseBody(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 (data) {
res["Data"] = boost::any(*data);
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
data = make_shared<string>(boost::any_cast<string>(m["Data"]));
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~DeleteGroupResponseBody() = default;
};
class DeleteGroupResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<DeleteGroupResponseBody> body{};
DeleteGroupResponse() {}
explicit DeleteGroupResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
DeleteGroupResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<DeleteGroupResponseBody>(model1);
}
}
}
virtual ~DeleteGroupResponse() = default;
};
class DeleteInferenceJobResponseBody : public Darabonba::Model {
public:
shared_ptr<string> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
DeleteInferenceJobResponseBody() {}
explicit DeleteInferenceJobResponseBody(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 (data) {
res["Data"] = boost::any(*data);
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
data = make_shared<string>(boost::any_cast<string>(m["Data"]));
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~DeleteInferenceJobResponseBody() = default;
};
class DeleteInferenceJobResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<DeleteInferenceJobResponseBody> body{};
DeleteInferenceJobResponse() {}
explicit DeleteInferenceJobResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
DeleteInferenceJobResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<DeleteInferenceJobResponseBody>(model1);
}
}
}
virtual ~DeleteInferenceJobResponse() = default;
};
class DeleteScheduleResponseBody : public Darabonba::Model {
public:
shared_ptr<string> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
DeleteScheduleResponseBody() {}
explicit DeleteScheduleResponseBody(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 (data) {
res["Data"] = boost::any(*data);
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
data = make_shared<string>(boost::any_cast<string>(m["Data"]));
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~DeleteScheduleResponseBody() = default;
};
class DeleteScheduleResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<DeleteScheduleResponseBody> body{};
DeleteScheduleResponse() {}
explicit DeleteScheduleResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
DeleteScheduleResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<DeleteScheduleResponseBody>(model1);
}
}
}
virtual ~DeleteScheduleResponse() = default;
};
class DeleteSignatureResponseBody : public Darabonba::Model {
public:
shared_ptr<string> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
DeleteSignatureResponseBody() {}
explicit DeleteSignatureResponseBody(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 (data) {
res["Data"] = boost::any(*data);
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
data = make_shared<string>(boost::any_cast<string>(m["Data"]));
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~DeleteSignatureResponseBody() = default;
};
class DeleteSignatureResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<DeleteSignatureResponseBody> body{};
DeleteSignatureResponse() {}
explicit DeleteSignatureResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
DeleteSignatureResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<DeleteSignatureResponseBody>(model1);
}
}
}
virtual ~DeleteSignatureResponse() = default;
};
class DeleteTemplateResponseBody : public Darabonba::Model {
public:
shared_ptr<string> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
DeleteTemplateResponseBody() {}
explicit DeleteTemplateResponseBody(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 (data) {
res["Data"] = boost::any(*data);
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
data = make_shared<string>(boost::any_cast<string>(m["Data"]));
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~DeleteTemplateResponseBody() = default;
};
class DeleteTemplateResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<DeleteTemplateResponseBody> body{};
DeleteTemplateResponse() {}
explicit DeleteTemplateResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
DeleteTemplateResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<DeleteTemplateResponseBody>(model1);
}
}
}
virtual ~DeleteTemplateResponse() = default;
};
class DeleteTrainingJobResponseBody : public Darabonba::Model {
public:
shared_ptr<string> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
DeleteTrainingJobResponseBody() {}
explicit DeleteTrainingJobResponseBody(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 (data) {
res["Data"] = boost::any(*data);
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
data = make_shared<string>(boost::any_cast<string>(m["Data"]));
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~DeleteTrainingJobResponseBody() = default;
};
class DeleteTrainingJobResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<DeleteTrainingJobResponseBody> body{};
DeleteTrainingJobResponse() {}
explicit DeleteTrainingJobResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
DeleteTrainingJobResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<DeleteTrainingJobResponseBody>(model1);
}
}
}
virtual ~DeleteTrainingJobResponse() = default;
};
class GetAlgorithmResponseBodyData : public Darabonba::Model {
public:
shared_ptr<string> description{};
shared_ptr<string> id{};
shared_ptr<string> inferUserConfigMap{};
shared_ptr<string> name{};
shared_ptr<string> trainUserConfigMap{};
GetAlgorithmResponseBodyData() {}
explicit GetAlgorithmResponseBodyData(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 (description) {
res["Description"] = boost::any(*description);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (inferUserConfigMap) {
res["InferUserConfigMap"] = boost::any(*inferUserConfigMap);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (trainUserConfigMap) {
res["TrainUserConfigMap"] = boost::any(*trainUserConfigMap);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Description") != m.end() && !m["Description"].empty()) {
description = make_shared<string>(boost::any_cast<string>(m["Description"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("InferUserConfigMap") != m.end() && !m["InferUserConfigMap"].empty()) {
inferUserConfigMap = make_shared<string>(boost::any_cast<string>(m["InferUserConfigMap"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("TrainUserConfigMap") != m.end() && !m["TrainUserConfigMap"].empty()) {
trainUserConfigMap = make_shared<string>(boost::any_cast<string>(m["TrainUserConfigMap"]));
}
}
virtual ~GetAlgorithmResponseBodyData() = default;
};
class GetAlgorithmResponseBody : public Darabonba::Model {
public:
shared_ptr<GetAlgorithmResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
GetAlgorithmResponseBody() {}
explicit GetAlgorithmResponseBody(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 (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
GetAlgorithmResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<GetAlgorithmResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~GetAlgorithmResponseBody() = default;
};
class GetAlgorithmResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<GetAlgorithmResponseBody> body{};
GetAlgorithmResponse() {}
explicit GetAlgorithmResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
GetAlgorithmResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<GetAlgorithmResponseBody>(model1);
}
}
}
virtual ~GetAlgorithmResponse() = default;
};
class GetCampaignResponseBodyData : public Darabonba::Model {
public:
shared_ptr<string> createdTime{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<string> remark{};
shared_ptr<string> updatedTime{};
GetCampaignResponseBodyData() {}
explicit GetCampaignResponseBodyData(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 (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
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<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
}
virtual ~GetCampaignResponseBodyData() = default;
};
class GetCampaignResponseBody : public Darabonba::Model {
public:
shared_ptr<GetCampaignResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
GetCampaignResponseBody() {}
explicit GetCampaignResponseBody(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 (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
GetCampaignResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<GetCampaignResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~GetCampaignResponseBody() = default;
};
class GetCampaignResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<GetCampaignResponseBody> body{};
GetCampaignResponse() {}
explicit GetCampaignResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
GetCampaignResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<GetCampaignResponseBody>(model1);
}
}
}
virtual ~GetCampaignResponse() = default;
};
class GetGroupResponseBodyData : public Darabonba::Model {
public:
shared_ptr<string> algorithm{};
shared_ptr<long> amount{};
shared_ptr<string> column{};
shared_ptr<string> createdTime{};
shared_ptr<string> filter{};
shared_ptr<string> id{};
shared_ptr<string> inferenceJobId{};
shared_ptr<string> name{};
shared_ptr<bool> phoneNumber{};
shared_ptr<string> project{};
shared_ptr<string> remark{};
shared_ptr<long> source{};
shared_ptr<long> status{};
shared_ptr<string> table{};
shared_ptr<string> text{};
shared_ptr<string> updatedTime{};
shared_ptr<string> uri{};
GetGroupResponseBodyData() {}
explicit GetGroupResponseBodyData(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 (algorithm) {
res["Algorithm"] = boost::any(*algorithm);
}
if (amount) {
res["Amount"] = boost::any(*amount);
}
if (column) {
res["Column"] = boost::any(*column);
}
if (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (filter) {
res["Filter"] = boost::any(*filter);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (inferenceJobId) {
res["InferenceJobId"] = boost::any(*inferenceJobId);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (phoneNumber) {
res["PhoneNumber"] = boost::any(*phoneNumber);
}
if (project) {
res["Project"] = boost::any(*project);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (source) {
res["Source"] = boost::any(*source);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (table) {
res["Table"] = boost::any(*table);
}
if (text) {
res["Text"] = boost::any(*text);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
if (uri) {
res["Uri"] = boost::any(*uri);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Algorithm") != m.end() && !m["Algorithm"].empty()) {
algorithm = make_shared<string>(boost::any_cast<string>(m["Algorithm"]));
}
if (m.find("Amount") != m.end() && !m["Amount"].empty()) {
amount = make_shared<long>(boost::any_cast<long>(m["Amount"]));
}
if (m.find("Column") != m.end() && !m["Column"].empty()) {
column = make_shared<string>(boost::any_cast<string>(m["Column"]));
}
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("Filter") != m.end() && !m["Filter"].empty()) {
filter = make_shared<string>(boost::any_cast<string>(m["Filter"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("InferenceJobId") != m.end() && !m["InferenceJobId"].empty()) {
inferenceJobId = make_shared<string>(boost::any_cast<string>(m["InferenceJobId"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("PhoneNumber") != m.end() && !m["PhoneNumber"].empty()) {
phoneNumber = make_shared<bool>(boost::any_cast<bool>(m["PhoneNumber"]));
}
if (m.find("Project") != m.end() && !m["Project"].empty()) {
project = make_shared<string>(boost::any_cast<string>(m["Project"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("Source") != m.end() && !m["Source"].empty()) {
source = make_shared<long>(boost::any_cast<long>(m["Source"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("Table") != m.end() && !m["Table"].empty()) {
table = make_shared<string>(boost::any_cast<string>(m["Table"]));
}
if (m.find("Text") != m.end() && !m["Text"].empty()) {
text = make_shared<string>(boost::any_cast<string>(m["Text"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
if (m.find("Uri") != m.end() && !m["Uri"].empty()) {
uri = make_shared<string>(boost::any_cast<string>(m["Uri"]));
}
}
virtual ~GetGroupResponseBodyData() = default;
};
class GetGroupResponseBody : public Darabonba::Model {
public:
shared_ptr<GetGroupResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
GetGroupResponseBody() {}
explicit GetGroupResponseBody(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 (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
GetGroupResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<GetGroupResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~GetGroupResponseBody() = default;
};
class GetGroupResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<GetGroupResponseBody> body{};
GetGroupResponse() {}
explicit GetGroupResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
GetGroupResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<GetGroupResponseBody>(model1);
}
}
}
virtual ~GetGroupResponse() = default;
};
class GetInferenceJobResponseBodyData : public Darabonba::Model {
public:
shared_ptr<string> algorithm{};
shared_ptr<string> campaignId{};
shared_ptr<string> createdTime{};
shared_ptr<string> dataPath{};
shared_ptr<string> groupId{};
shared_ptr<string> history{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<string> remark{};
shared_ptr<long> status{};
shared_ptr<string> targetPath{};
shared_ptr<string> trainingJobId{};
shared_ptr<string> updatedTime{};
shared_ptr<string> userConfig{};
GetInferenceJobResponseBodyData() {}
explicit GetInferenceJobResponseBodyData(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 (algorithm) {
res["Algorithm"] = boost::any(*algorithm);
}
if (campaignId) {
res["CampaignId"] = boost::any(*campaignId);
}
if (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (dataPath) {
res["DataPath"] = boost::any(*dataPath);
}
if (groupId) {
res["GroupId"] = boost::any(*groupId);
}
if (history) {
res["History"] = boost::any(*history);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (targetPath) {
res["TargetPath"] = boost::any(*targetPath);
}
if (trainingJobId) {
res["TrainingJobId"] = boost::any(*trainingJobId);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
if (userConfig) {
res["UserConfig"] = boost::any(*userConfig);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Algorithm") != m.end() && !m["Algorithm"].empty()) {
algorithm = make_shared<string>(boost::any_cast<string>(m["Algorithm"]));
}
if (m.find("CampaignId") != m.end() && !m["CampaignId"].empty()) {
campaignId = make_shared<string>(boost::any_cast<string>(m["CampaignId"]));
}
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("DataPath") != m.end() && !m["DataPath"].empty()) {
dataPath = make_shared<string>(boost::any_cast<string>(m["DataPath"]));
}
if (m.find("GroupId") != m.end() && !m["GroupId"].empty()) {
groupId = make_shared<string>(boost::any_cast<string>(m["GroupId"]));
}
if (m.find("History") != m.end() && !m["History"].empty()) {
history = make_shared<string>(boost::any_cast<string>(m["History"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("TargetPath") != m.end() && !m["TargetPath"].empty()) {
targetPath = make_shared<string>(boost::any_cast<string>(m["TargetPath"]));
}
if (m.find("TrainingJobId") != m.end() && !m["TrainingJobId"].empty()) {
trainingJobId = make_shared<string>(boost::any_cast<string>(m["TrainingJobId"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
if (m.find("UserConfig") != m.end() && !m["UserConfig"].empty()) {
userConfig = make_shared<string>(boost::any_cast<string>(m["UserConfig"]));
}
}
virtual ~GetInferenceJobResponseBodyData() = default;
};
class GetInferenceJobResponseBody : public Darabonba::Model {
public:
shared_ptr<GetInferenceJobResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
GetInferenceJobResponseBody() {}
explicit GetInferenceJobResponseBody(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 (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
GetInferenceJobResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<GetInferenceJobResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~GetInferenceJobResponseBody() = default;
};
class GetInferenceJobResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<GetInferenceJobResponseBody> body{};
GetInferenceJobResponse() {}
explicit GetInferenceJobResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
GetInferenceJobResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<GetInferenceJobResponseBody>(model1);
}
}
}
virtual ~GetInferenceJobResponse() = default;
};
class GetMessageConfigResponseBodyData : public Darabonba::Model {
public:
shared_ptr<string> smsReportUrl{};
shared_ptr<string> smsUpUrl{};
GetMessageConfigResponseBodyData() {}
explicit GetMessageConfigResponseBodyData(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 (smsReportUrl) {
res["SmsReportUrl"] = boost::any(*smsReportUrl);
}
if (smsUpUrl) {
res["SmsUpUrl"] = boost::any(*smsUpUrl);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("SmsReportUrl") != m.end() && !m["SmsReportUrl"].empty()) {
smsReportUrl = make_shared<string>(boost::any_cast<string>(m["SmsReportUrl"]));
}
if (m.find("SmsUpUrl") != m.end() && !m["SmsUpUrl"].empty()) {
smsUpUrl = make_shared<string>(boost::any_cast<string>(m["SmsUpUrl"]));
}
}
virtual ~GetMessageConfigResponseBodyData() = default;
};
class GetMessageConfigResponseBody : public Darabonba::Model {
public:
shared_ptr<GetMessageConfigResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
GetMessageConfigResponseBody() {}
explicit GetMessageConfigResponseBody(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 (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
GetMessageConfigResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<GetMessageConfigResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~GetMessageConfigResponseBody() = default;
};
class GetMessageConfigResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<GetMessageConfigResponseBody> body{};
GetMessageConfigResponse() {}
explicit GetMessageConfigResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
GetMessageConfigResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<GetMessageConfigResponseBody>(model1);
}
}
}
virtual ~GetMessageConfigResponse() = default;
};
class GetScheduleResponseBodyData : public Darabonba::Model {
public:
shared_ptr<string> createdTime{};
shared_ptr<long> endTime{};
shared_ptr<string> executeTime{};
shared_ptr<string> groupId{};
shared_ptr<string> history{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<long> repeatCycle{};
shared_ptr<long> repeatCycleUnit{};
shared_ptr<long> repeatTimes{};
shared_ptr<string> signName{};
shared_ptr<string> signatureId{};
shared_ptr<long> status{};
shared_ptr<string> templateCode{};
shared_ptr<string> templateId{};
shared_ptr<string> updatedTime{};
GetScheduleResponseBodyData() {}
explicit GetScheduleResponseBodyData(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 (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (endTime) {
res["EndTime"] = boost::any(*endTime);
}
if (executeTime) {
res["ExecuteTime"] = boost::any(*executeTime);
}
if (groupId) {
res["GroupId"] = boost::any(*groupId);
}
if (history) {
res["History"] = boost::any(*history);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (repeatCycle) {
res["RepeatCycle"] = boost::any(*repeatCycle);
}
if (repeatCycleUnit) {
res["RepeatCycleUnit"] = boost::any(*repeatCycleUnit);
}
if (repeatTimes) {
res["RepeatTimes"] = boost::any(*repeatTimes);
}
if (signName) {
res["SignName"] = boost::any(*signName);
}
if (signatureId) {
res["SignatureId"] = boost::any(*signatureId);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (templateCode) {
res["TemplateCode"] = boost::any(*templateCode);
}
if (templateId) {
res["TemplateId"] = boost::any(*templateId);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("EndTime") != m.end() && !m["EndTime"].empty()) {
endTime = make_shared<long>(boost::any_cast<long>(m["EndTime"]));
}
if (m.find("ExecuteTime") != m.end() && !m["ExecuteTime"].empty()) {
executeTime = make_shared<string>(boost::any_cast<string>(m["ExecuteTime"]));
}
if (m.find("GroupId") != m.end() && !m["GroupId"].empty()) {
groupId = make_shared<string>(boost::any_cast<string>(m["GroupId"]));
}
if (m.find("History") != m.end() && !m["History"].empty()) {
history = make_shared<string>(boost::any_cast<string>(m["History"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("RepeatCycle") != m.end() && !m["RepeatCycle"].empty()) {
repeatCycle = make_shared<long>(boost::any_cast<long>(m["RepeatCycle"]));
}
if (m.find("RepeatCycleUnit") != m.end() && !m["RepeatCycleUnit"].empty()) {
repeatCycleUnit = make_shared<long>(boost::any_cast<long>(m["RepeatCycleUnit"]));
}
if (m.find("RepeatTimes") != m.end() && !m["RepeatTimes"].empty()) {
repeatTimes = make_shared<long>(boost::any_cast<long>(m["RepeatTimes"]));
}
if (m.find("SignName") != m.end() && !m["SignName"].empty()) {
signName = make_shared<string>(boost::any_cast<string>(m["SignName"]));
}
if (m.find("SignatureId") != m.end() && !m["SignatureId"].empty()) {
signatureId = make_shared<string>(boost::any_cast<string>(m["SignatureId"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("TemplateCode") != m.end() && !m["TemplateCode"].empty()) {
templateCode = make_shared<string>(boost::any_cast<string>(m["TemplateCode"]));
}
if (m.find("TemplateId") != m.end() && !m["TemplateId"].empty()) {
templateId = make_shared<string>(boost::any_cast<string>(m["TemplateId"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
}
virtual ~GetScheduleResponseBodyData() = default;
};
class GetScheduleResponseBody : public Darabonba::Model {
public:
shared_ptr<GetScheduleResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
GetScheduleResponseBody() {}
explicit GetScheduleResponseBody(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 (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
GetScheduleResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<GetScheduleResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~GetScheduleResponseBody() = default;
};
class GetScheduleResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<GetScheduleResponseBody> body{};
GetScheduleResponse() {}
explicit GetScheduleResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
GetScheduleResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<GetScheduleResponseBody>(model1);
}
}
}
virtual ~GetScheduleResponse() = default;
};
class GetSignatureResponseBodyData : public Darabonba::Model {
public:
shared_ptr<string> createdTime{};
shared_ptr<string> description{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<string> reason{};
shared_ptr<long> status{};
shared_ptr<string> updatedTime{};
GetSignatureResponseBodyData() {}
explicit GetSignatureResponseBodyData(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 (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (description) {
res["Description"] = boost::any(*description);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (reason) {
res["Reason"] = boost::any(*reason);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("Description") != m.end() && !m["Description"].empty()) {
description = make_shared<string>(boost::any_cast<string>(m["Description"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Reason") != m.end() && !m["Reason"].empty()) {
reason = make_shared<string>(boost::any_cast<string>(m["Reason"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
}
virtual ~GetSignatureResponseBodyData() = default;
};
class GetSignatureResponseBody : public Darabonba::Model {
public:
shared_ptr<GetSignatureResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
GetSignatureResponseBody() {}
explicit GetSignatureResponseBody(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 (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
GetSignatureResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<GetSignatureResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~GetSignatureResponseBody() = default;
};
class GetSignatureResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<GetSignatureResponseBody> body{};
GetSignatureResponse() {}
explicit GetSignatureResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
GetSignatureResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<GetSignatureResponseBody>(model1);
}
}
}
virtual ~GetSignatureResponse() = default;
};
class GetTemplateResponseBodyData : public Darabonba::Model {
public:
shared_ptr<string> content{};
shared_ptr<string> createdTime{};
shared_ptr<string> description{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<string> reason{};
shared_ptr<string> signatureId{};
shared_ptr<long> status{};
shared_ptr<string> templateCode{};
shared_ptr<long> type{};
shared_ptr<string> updatedTime{};
GetTemplateResponseBodyData() {}
explicit GetTemplateResponseBodyData(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 (content) {
res["Content"] = boost::any(*content);
}
if (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (description) {
res["Description"] = boost::any(*description);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (reason) {
res["Reason"] = boost::any(*reason);
}
if (signatureId) {
res["SignatureId"] = boost::any(*signatureId);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (templateCode) {
res["TemplateCode"] = boost::any(*templateCode);
}
if (type) {
res["Type"] = boost::any(*type);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Content") != m.end() && !m["Content"].empty()) {
content = make_shared<string>(boost::any_cast<string>(m["Content"]));
}
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("Description") != m.end() && !m["Description"].empty()) {
description = make_shared<string>(boost::any_cast<string>(m["Description"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Reason") != m.end() && !m["Reason"].empty()) {
reason = make_shared<string>(boost::any_cast<string>(m["Reason"]));
}
if (m.find("SignatureId") != m.end() && !m["SignatureId"].empty()) {
signatureId = make_shared<string>(boost::any_cast<string>(m["SignatureId"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("TemplateCode") != m.end() && !m["TemplateCode"].empty()) {
templateCode = make_shared<string>(boost::any_cast<string>(m["TemplateCode"]));
}
if (m.find("Type") != m.end() && !m["Type"].empty()) {
type = make_shared<long>(boost::any_cast<long>(m["Type"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
}
virtual ~GetTemplateResponseBodyData() = default;
};
class GetTemplateResponseBody : public Darabonba::Model {
public:
shared_ptr<GetTemplateResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
GetTemplateResponseBody() {}
explicit GetTemplateResponseBody(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 (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
GetTemplateResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<GetTemplateResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~GetTemplateResponseBody() = default;
};
class GetTemplateResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<GetTemplateResponseBody> body{};
GetTemplateResponse() {}
explicit GetTemplateResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
GetTemplateResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<GetTemplateResponseBody>(model1);
}
}
}
virtual ~GetTemplateResponse() = default;
};
class GetTrainingJobResponseBodyData : public Darabonba::Model {
public:
shared_ptr<string> algorithm{};
shared_ptr<string> campaignId{};
shared_ptr<string> createdTime{};
shared_ptr<string> dataPath{};
shared_ptr<string> history{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<string> remark{};
shared_ptr<long> status{};
shared_ptr<string> updatedTime{};
shared_ptr<string> userConfig{};
GetTrainingJobResponseBodyData() {}
explicit GetTrainingJobResponseBodyData(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 (algorithm) {
res["Algorithm"] = boost::any(*algorithm);
}
if (campaignId) {
res["CampaignId"] = boost::any(*campaignId);
}
if (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (dataPath) {
res["DataPath"] = boost::any(*dataPath);
}
if (history) {
res["History"] = boost::any(*history);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
if (userConfig) {
res["UserConfig"] = boost::any(*userConfig);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Algorithm") != m.end() && !m["Algorithm"].empty()) {
algorithm = make_shared<string>(boost::any_cast<string>(m["Algorithm"]));
}
if (m.find("CampaignId") != m.end() && !m["CampaignId"].empty()) {
campaignId = make_shared<string>(boost::any_cast<string>(m["CampaignId"]));
}
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("DataPath") != m.end() && !m["DataPath"].empty()) {
dataPath = make_shared<string>(boost::any_cast<string>(m["DataPath"]));
}
if (m.find("History") != m.end() && !m["History"].empty()) {
history = make_shared<string>(boost::any_cast<string>(m["History"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
if (m.find("UserConfig") != m.end() && !m["UserConfig"].empty()) {
userConfig = make_shared<string>(boost::any_cast<string>(m["UserConfig"]));
}
}
virtual ~GetTrainingJobResponseBodyData() = default;
};
class GetTrainingJobResponseBody : public Darabonba::Model {
public:
shared_ptr<GetTrainingJobResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
GetTrainingJobResponseBody() {}
explicit GetTrainingJobResponseBody(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 (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
GetTrainingJobResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<GetTrainingJobResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~GetTrainingJobResponseBody() = default;
};
class GetTrainingJobResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<GetTrainingJobResponseBody> body{};
GetTrainingJobResponse() {}
explicit GetTrainingJobResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
GetTrainingJobResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<GetTrainingJobResponseBody>(model1);
}
}
}
virtual ~GetTrainingJobResponse() = default;
};
class GetUserResponseBodyData : public Darabonba::Model {
public:
shared_ptr<long> accountStatus{};
GetUserResponseBodyData() {}
explicit GetUserResponseBodyData(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 (accountStatus) {
res["AccountStatus"] = boost::any(*accountStatus);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("AccountStatus") != m.end() && !m["AccountStatus"].empty()) {
accountStatus = make_shared<long>(boost::any_cast<long>(m["AccountStatus"]));
}
}
virtual ~GetUserResponseBodyData() = default;
};
class GetUserResponseBody : public Darabonba::Model {
public:
shared_ptr<GetUserResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
GetUserResponseBody() {}
explicit GetUserResponseBody(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 (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
GetUserResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<GetUserResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~GetUserResponseBody() = default;
};
class GetUserResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<GetUserResponseBody> body{};
GetUserResponse() {}
explicit GetUserResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
GetUserResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<GetUserResponseBody>(model1);
}
}
}
virtual ~GetUserResponse() = default;
};
class ListAlgorithmsRequest : public Darabonba::Model {
public:
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
ListAlgorithmsRequest() {}
explicit ListAlgorithmsRequest(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 (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
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"]));
}
}
virtual ~ListAlgorithmsRequest() = default;
};
class ListAlgorithmsResponseBodyDataAlgorithms : public Darabonba::Model {
public:
shared_ptr<string> id{};
shared_ptr<string> name{};
ListAlgorithmsResponseBodyDataAlgorithms() {}
explicit ListAlgorithmsResponseBodyDataAlgorithms(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 (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
}
virtual ~ListAlgorithmsResponseBodyDataAlgorithms() = default;
};
class ListAlgorithmsResponseBodyData : public Darabonba::Model {
public:
shared_ptr<vector<ListAlgorithmsResponseBodyDataAlgorithms>> algorithms{};
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<long> totalCount{};
ListAlgorithmsResponseBodyData() {}
explicit ListAlgorithmsResponseBodyData(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 (algorithms) {
vector<boost::any> temp1;
for(auto item1:*algorithms){
temp1.push_back(boost::any(item1.toMap()));
}
res["Algorithms"] = boost::any(temp1);
}
if (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
if (totalCount) {
res["TotalCount"] = boost::any(*totalCount);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Algorithms") != m.end() && !m["Algorithms"].empty()) {
if (typeid(vector<boost::any>) == m["Algorithms"].type()) {
vector<ListAlgorithmsResponseBodyDataAlgorithms> expect1;
for(auto item1:boost::any_cast<vector<boost::any>>(m["Algorithms"])){
if (typeid(map<string, boost::any>) == item1.type()) {
ListAlgorithmsResponseBodyDataAlgorithms model2;
model2.fromMap(boost::any_cast<map<string, boost::any>>(item1));
expect1.push_back(model2);
}
}
algorithms = make_shared<vector<ListAlgorithmsResponseBodyDataAlgorithms>>(expect1);
}
}
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"]));
}
}
virtual ~ListAlgorithmsResponseBodyData() = default;
};
class ListAlgorithmsResponseBody : public Darabonba::Model {
public:
shared_ptr<ListAlgorithmsResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
ListAlgorithmsResponseBody() {}
explicit ListAlgorithmsResponseBody(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 (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
ListAlgorithmsResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<ListAlgorithmsResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~ListAlgorithmsResponseBody() = default;
};
class ListAlgorithmsResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<ListAlgorithmsResponseBody> body{};
ListAlgorithmsResponse() {}
explicit ListAlgorithmsResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
ListAlgorithmsResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<ListAlgorithmsResponseBody>(model1);
}
}
}
virtual ~ListAlgorithmsResponse() = default;
};
class ListCampaignsRequest : public Darabonba::Model {
public:
shared_ptr<string> name{};
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<string> remark{};
ListCampaignsRequest() {}
explicit ListCampaignsRequest(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 (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
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("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("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
}
virtual ~ListCampaignsRequest() = default;
};
class ListCampaignsResponseBodyDataCampaigns : public Darabonba::Model {
public:
shared_ptr<string> createdTime{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<string> remark{};
shared_ptr<string> updatedTime{};
ListCampaignsResponseBodyDataCampaigns() {}
explicit ListCampaignsResponseBodyDataCampaigns(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 (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
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<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
}
virtual ~ListCampaignsResponseBodyDataCampaigns() = default;
};
class ListCampaignsResponseBodyData : public Darabonba::Model {
public:
shared_ptr<vector<ListCampaignsResponseBodyDataCampaigns>> campaigns{};
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<long> totalCount{};
ListCampaignsResponseBodyData() {}
explicit ListCampaignsResponseBodyData(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 (campaigns) {
vector<boost::any> temp1;
for(auto item1:*campaigns){
temp1.push_back(boost::any(item1.toMap()));
}
res["Campaigns"] = boost::any(temp1);
}
if (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
if (totalCount) {
res["TotalCount"] = boost::any(*totalCount);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Campaigns") != m.end() && !m["Campaigns"].empty()) {
if (typeid(vector<boost::any>) == m["Campaigns"].type()) {
vector<ListCampaignsResponseBodyDataCampaigns> expect1;
for(auto item1:boost::any_cast<vector<boost::any>>(m["Campaigns"])){
if (typeid(map<string, boost::any>) == item1.type()) {
ListCampaignsResponseBodyDataCampaigns model2;
model2.fromMap(boost::any_cast<map<string, boost::any>>(item1));
expect1.push_back(model2);
}
}
campaigns = make_shared<vector<ListCampaignsResponseBodyDataCampaigns>>(expect1);
}
}
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"]));
}
}
virtual ~ListCampaignsResponseBodyData() = default;
};
class ListCampaignsResponseBody : public Darabonba::Model {
public:
shared_ptr<ListCampaignsResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
ListCampaignsResponseBody() {}
explicit ListCampaignsResponseBody(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 (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
ListCampaignsResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<ListCampaignsResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~ListCampaignsResponseBody() = default;
};
class ListCampaignsResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<ListCampaignsResponseBody> body{};
ListCampaignsResponse() {}
explicit ListCampaignsResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
ListCampaignsResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<ListCampaignsResponseBody>(model1);
}
}
}
virtual ~ListCampaignsResponse() = default;
};
class ListGroupsRequest : public Darabonba::Model {
public:
shared_ptr<string> name{};
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<bool> phoneNumber{};
shared_ptr<string> remark{};
shared_ptr<long> source{};
shared_ptr<long> status{};
ListGroupsRequest() {}
explicit ListGroupsRequest(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 (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
if (phoneNumber) {
res["PhoneNumber"] = boost::any(*phoneNumber);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (source) {
res["Source"] = boost::any(*source);
}
if (status) {
res["Status"] = boost::any(*status);
}
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("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("PhoneNumber") != m.end() && !m["PhoneNumber"].empty()) {
phoneNumber = make_shared<bool>(boost::any_cast<bool>(m["PhoneNumber"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("Source") != m.end() && !m["Source"].empty()) {
source = make_shared<long>(boost::any_cast<long>(m["Source"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
}
virtual ~ListGroupsRequest() = default;
};
class ListGroupsResponseBodyDataGroups : public Darabonba::Model {
public:
shared_ptr<string> algorithm{};
shared_ptr<long> amount{};
shared_ptr<string> column{};
shared_ptr<string> createdTime{};
shared_ptr<string> filter{};
shared_ptr<string> id{};
shared_ptr<string> inferenceJobId{};
shared_ptr<string> name{};
shared_ptr<bool> phoneNumber{};
shared_ptr<string> project{};
shared_ptr<string> remark{};
shared_ptr<long> source{};
shared_ptr<long> status{};
shared_ptr<string> table{};
shared_ptr<string> text{};
shared_ptr<string> updatedTime{};
shared_ptr<string> uri{};
ListGroupsResponseBodyDataGroups() {}
explicit ListGroupsResponseBodyDataGroups(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 (algorithm) {
res["Algorithm"] = boost::any(*algorithm);
}
if (amount) {
res["Amount"] = boost::any(*amount);
}
if (column) {
res["Column"] = boost::any(*column);
}
if (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (filter) {
res["Filter"] = boost::any(*filter);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (inferenceJobId) {
res["InferenceJobId"] = boost::any(*inferenceJobId);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (phoneNumber) {
res["PhoneNumber"] = boost::any(*phoneNumber);
}
if (project) {
res["Project"] = boost::any(*project);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (source) {
res["Source"] = boost::any(*source);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (table) {
res["Table"] = boost::any(*table);
}
if (text) {
res["Text"] = boost::any(*text);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
if (uri) {
res["Uri"] = boost::any(*uri);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Algorithm") != m.end() && !m["Algorithm"].empty()) {
algorithm = make_shared<string>(boost::any_cast<string>(m["Algorithm"]));
}
if (m.find("Amount") != m.end() && !m["Amount"].empty()) {
amount = make_shared<long>(boost::any_cast<long>(m["Amount"]));
}
if (m.find("Column") != m.end() && !m["Column"].empty()) {
column = make_shared<string>(boost::any_cast<string>(m["Column"]));
}
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("Filter") != m.end() && !m["Filter"].empty()) {
filter = make_shared<string>(boost::any_cast<string>(m["Filter"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("InferenceJobId") != m.end() && !m["InferenceJobId"].empty()) {
inferenceJobId = make_shared<string>(boost::any_cast<string>(m["InferenceJobId"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("PhoneNumber") != m.end() && !m["PhoneNumber"].empty()) {
phoneNumber = make_shared<bool>(boost::any_cast<bool>(m["PhoneNumber"]));
}
if (m.find("Project") != m.end() && !m["Project"].empty()) {
project = make_shared<string>(boost::any_cast<string>(m["Project"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("Source") != m.end() && !m["Source"].empty()) {
source = make_shared<long>(boost::any_cast<long>(m["Source"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("Table") != m.end() && !m["Table"].empty()) {
table = make_shared<string>(boost::any_cast<string>(m["Table"]));
}
if (m.find("Text") != m.end() && !m["Text"].empty()) {
text = make_shared<string>(boost::any_cast<string>(m["Text"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
if (m.find("Uri") != m.end() && !m["Uri"].empty()) {
uri = make_shared<string>(boost::any_cast<string>(m["Uri"]));
}
}
virtual ~ListGroupsResponseBodyDataGroups() = default;
};
class ListGroupsResponseBodyData : public Darabonba::Model {
public:
shared_ptr<vector<ListGroupsResponseBodyDataGroups>> groups{};
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<long> totalCount{};
ListGroupsResponseBodyData() {}
explicit ListGroupsResponseBodyData(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 (groups) {
vector<boost::any> temp1;
for(auto item1:*groups){
temp1.push_back(boost::any(item1.toMap()));
}
res["Groups"] = boost::any(temp1);
}
if (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
if (totalCount) {
res["TotalCount"] = boost::any(*totalCount);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Groups") != m.end() && !m["Groups"].empty()) {
if (typeid(vector<boost::any>) == m["Groups"].type()) {
vector<ListGroupsResponseBodyDataGroups> expect1;
for(auto item1:boost::any_cast<vector<boost::any>>(m["Groups"])){
if (typeid(map<string, boost::any>) == item1.type()) {
ListGroupsResponseBodyDataGroups model2;
model2.fromMap(boost::any_cast<map<string, boost::any>>(item1));
expect1.push_back(model2);
}
}
groups = make_shared<vector<ListGroupsResponseBodyDataGroups>>(expect1);
}
}
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"]));
}
}
virtual ~ListGroupsResponseBodyData() = default;
};
class ListGroupsResponseBody : public Darabonba::Model {
public:
shared_ptr<ListGroupsResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
ListGroupsResponseBody() {}
explicit ListGroupsResponseBody(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 (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
ListGroupsResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<ListGroupsResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~ListGroupsResponseBody() = default;
};
class ListGroupsResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<ListGroupsResponseBody> body{};
ListGroupsResponse() {}
explicit ListGroupsResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
ListGroupsResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<ListGroupsResponseBody>(model1);
}
}
}
virtual ~ListGroupsResponse() = default;
};
class ListInferenceJobsRequest : public Darabonba::Model {
public:
shared_ptr<string> campaignId{};
shared_ptr<string> name{};
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<string> remark{};
shared_ptr<long> status{};
ListInferenceJobsRequest() {}
explicit ListInferenceJobsRequest(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 (campaignId) {
res["CampaignId"] = boost::any(*campaignId);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (status) {
res["Status"] = boost::any(*status);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("CampaignId") != m.end() && !m["CampaignId"].empty()) {
campaignId = make_shared<string>(boost::any_cast<string>(m["CampaignId"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
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("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
}
virtual ~ListInferenceJobsRequest() = default;
};
class ListInferenceJobsResponseBodyDataInferenceJobs : public Darabonba::Model {
public:
shared_ptr<string> algorithm{};
shared_ptr<string> campaignId{};
shared_ptr<string> createdTime{};
shared_ptr<string> dataPath{};
shared_ptr<string> groupId{};
shared_ptr<string> history{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<string> remark{};
shared_ptr<long> status{};
shared_ptr<string> targetPath{};
shared_ptr<string> trainingJobId{};
shared_ptr<string> updatedTime{};
shared_ptr<string> userConfig{};
ListInferenceJobsResponseBodyDataInferenceJobs() {}
explicit ListInferenceJobsResponseBodyDataInferenceJobs(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 (algorithm) {
res["Algorithm"] = boost::any(*algorithm);
}
if (campaignId) {
res["CampaignId"] = boost::any(*campaignId);
}
if (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (dataPath) {
res["DataPath"] = boost::any(*dataPath);
}
if (groupId) {
res["GroupId"] = boost::any(*groupId);
}
if (history) {
res["History"] = boost::any(*history);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (targetPath) {
res["TargetPath"] = boost::any(*targetPath);
}
if (trainingJobId) {
res["TrainingJobId"] = boost::any(*trainingJobId);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
if (userConfig) {
res["UserConfig"] = boost::any(*userConfig);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Algorithm") != m.end() && !m["Algorithm"].empty()) {
algorithm = make_shared<string>(boost::any_cast<string>(m["Algorithm"]));
}
if (m.find("CampaignId") != m.end() && !m["CampaignId"].empty()) {
campaignId = make_shared<string>(boost::any_cast<string>(m["CampaignId"]));
}
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("DataPath") != m.end() && !m["DataPath"].empty()) {
dataPath = make_shared<string>(boost::any_cast<string>(m["DataPath"]));
}
if (m.find("GroupId") != m.end() && !m["GroupId"].empty()) {
groupId = make_shared<string>(boost::any_cast<string>(m["GroupId"]));
}
if (m.find("History") != m.end() && !m["History"].empty()) {
history = make_shared<string>(boost::any_cast<string>(m["History"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("TargetPath") != m.end() && !m["TargetPath"].empty()) {
targetPath = make_shared<string>(boost::any_cast<string>(m["TargetPath"]));
}
if (m.find("TrainingJobId") != m.end() && !m["TrainingJobId"].empty()) {
trainingJobId = make_shared<string>(boost::any_cast<string>(m["TrainingJobId"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
if (m.find("UserConfig") != m.end() && !m["UserConfig"].empty()) {
userConfig = make_shared<string>(boost::any_cast<string>(m["UserConfig"]));
}
}
virtual ~ListInferenceJobsResponseBodyDataInferenceJobs() = default;
};
class ListInferenceJobsResponseBodyData : public Darabonba::Model {
public:
shared_ptr<vector<ListInferenceJobsResponseBodyDataInferenceJobs>> inferenceJobs{};
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<long> totalCount{};
ListInferenceJobsResponseBodyData() {}
explicit ListInferenceJobsResponseBodyData(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 (inferenceJobs) {
vector<boost::any> temp1;
for(auto item1:*inferenceJobs){
temp1.push_back(boost::any(item1.toMap()));
}
res["InferenceJobs"] = boost::any(temp1);
}
if (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
if (totalCount) {
res["TotalCount"] = boost::any(*totalCount);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("InferenceJobs") != m.end() && !m["InferenceJobs"].empty()) {
if (typeid(vector<boost::any>) == m["InferenceJobs"].type()) {
vector<ListInferenceJobsResponseBodyDataInferenceJobs> expect1;
for(auto item1:boost::any_cast<vector<boost::any>>(m["InferenceJobs"])){
if (typeid(map<string, boost::any>) == item1.type()) {
ListInferenceJobsResponseBodyDataInferenceJobs model2;
model2.fromMap(boost::any_cast<map<string, boost::any>>(item1));
expect1.push_back(model2);
}
}
inferenceJobs = make_shared<vector<ListInferenceJobsResponseBodyDataInferenceJobs>>(expect1);
}
}
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"]));
}
}
virtual ~ListInferenceJobsResponseBodyData() = default;
};
class ListInferenceJobsResponseBody : public Darabonba::Model {
public:
shared_ptr<ListInferenceJobsResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
ListInferenceJobsResponseBody() {}
explicit ListInferenceJobsResponseBody(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 (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
ListInferenceJobsResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<ListInferenceJobsResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~ListInferenceJobsResponseBody() = default;
};
class ListInferenceJobsResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<ListInferenceJobsResponseBody> body{};
ListInferenceJobsResponse() {}
explicit ListInferenceJobsResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
ListInferenceJobsResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<ListInferenceJobsResponseBody>(model1);
}
}
}
virtual ~ListInferenceJobsResponse() = default;
};
class ListMessageMetricsRequest : public Darabonba::Model {
public:
shared_ptr<string> endDate{};
shared_ptr<string> groupId{};
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<string> scheduleId{};
shared_ptr<string> signature{};
shared_ptr<string> signatureId{};
shared_ptr<string> startDate{};
shared_ptr<string> templateCode{};
shared_ptr<string> templateId{};
shared_ptr<long> templateType{};
ListMessageMetricsRequest() {}
explicit ListMessageMetricsRequest(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 (endDate) {
res["EndDate"] = boost::any(*endDate);
}
if (groupId) {
res["GroupId"] = boost::any(*groupId);
}
if (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
if (scheduleId) {
res["ScheduleId"] = boost::any(*scheduleId);
}
if (signature) {
res["Signature"] = boost::any(*signature);
}
if (signatureId) {
res["SignatureId"] = boost::any(*signatureId);
}
if (startDate) {
res["StartDate"] = boost::any(*startDate);
}
if (templateCode) {
res["TemplateCode"] = boost::any(*templateCode);
}
if (templateId) {
res["TemplateId"] = boost::any(*templateId);
}
if (templateType) {
res["TemplateType"] = boost::any(*templateType);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("EndDate") != m.end() && !m["EndDate"].empty()) {
endDate = make_shared<string>(boost::any_cast<string>(m["EndDate"]));
}
if (m.find("GroupId") != m.end() && !m["GroupId"].empty()) {
groupId = make_shared<string>(boost::any_cast<string>(m["GroupId"]));
}
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("ScheduleId") != m.end() && !m["ScheduleId"].empty()) {
scheduleId = make_shared<string>(boost::any_cast<string>(m["ScheduleId"]));
}
if (m.find("Signature") != m.end() && !m["Signature"].empty()) {
signature = make_shared<string>(boost::any_cast<string>(m["Signature"]));
}
if (m.find("SignatureId") != m.end() && !m["SignatureId"].empty()) {
signatureId = make_shared<string>(boost::any_cast<string>(m["SignatureId"]));
}
if (m.find("StartDate") != m.end() && !m["StartDate"].empty()) {
startDate = make_shared<string>(boost::any_cast<string>(m["StartDate"]));
}
if (m.find("TemplateCode") != m.end() && !m["TemplateCode"].empty()) {
templateCode = make_shared<string>(boost::any_cast<string>(m["TemplateCode"]));
}
if (m.find("TemplateId") != m.end() && !m["TemplateId"].empty()) {
templateId = make_shared<string>(boost::any_cast<string>(m["TemplateId"]));
}
if (m.find("TemplateType") != m.end() && !m["TemplateType"].empty()) {
templateType = make_shared<long>(boost::any_cast<long>(m["TemplateType"]));
}
}
virtual ~ListMessageMetricsRequest() = default;
};
class ListMessageMetricsResponseBodyDataMetrics : public Darabonba::Model {
public:
shared_ptr<string> date{};
shared_ptr<long> fail{};
shared_ptr<long> pending{};
shared_ptr<double> rate{};
shared_ptr<long> success{};
shared_ptr<long> total{};
ListMessageMetricsResponseBodyDataMetrics() {}
explicit ListMessageMetricsResponseBodyDataMetrics(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 (date) {
res["Date"] = boost::any(*date);
}
if (fail) {
res["Fail"] = boost::any(*fail);
}
if (pending) {
res["Pending"] = boost::any(*pending);
}
if (rate) {
res["Rate"] = boost::any(*rate);
}
if (success) {
res["Success"] = boost::any(*success);
}
if (total) {
res["Total"] = boost::any(*total);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Date") != m.end() && !m["Date"].empty()) {
date = make_shared<string>(boost::any_cast<string>(m["Date"]));
}
if (m.find("Fail") != m.end() && !m["Fail"].empty()) {
fail = make_shared<long>(boost::any_cast<long>(m["Fail"]));
}
if (m.find("Pending") != m.end() && !m["Pending"].empty()) {
pending = make_shared<long>(boost::any_cast<long>(m["Pending"]));
}
if (m.find("Rate") != m.end() && !m["Rate"].empty()) {
rate = make_shared<double>(boost::any_cast<double>(m["Rate"]));
}
if (m.find("Success") != m.end() && !m["Success"].empty()) {
success = make_shared<long>(boost::any_cast<long>(m["Success"]));
}
if (m.find("Total") != m.end() && !m["Total"].empty()) {
total = make_shared<long>(boost::any_cast<long>(m["Total"]));
}
}
virtual ~ListMessageMetricsResponseBodyDataMetrics() = default;
};
class ListMessageMetricsResponseBodyData : public Darabonba::Model {
public:
shared_ptr<vector<ListMessageMetricsResponseBodyDataMetrics>> metrics{};
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<long> totalCount{};
ListMessageMetricsResponseBodyData() {}
explicit ListMessageMetricsResponseBodyData(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 (metrics) {
vector<boost::any> temp1;
for(auto item1:*metrics){
temp1.push_back(boost::any(item1.toMap()));
}
res["Metrics"] = boost::any(temp1);
}
if (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
if (totalCount) {
res["TotalCount"] = boost::any(*totalCount);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Metrics") != m.end() && !m["Metrics"].empty()) {
if (typeid(vector<boost::any>) == m["Metrics"].type()) {
vector<ListMessageMetricsResponseBodyDataMetrics> expect1;
for(auto item1:boost::any_cast<vector<boost::any>>(m["Metrics"])){
if (typeid(map<string, boost::any>) == item1.type()) {
ListMessageMetricsResponseBodyDataMetrics model2;
model2.fromMap(boost::any_cast<map<string, boost::any>>(item1));
expect1.push_back(model2);
}
}
metrics = make_shared<vector<ListMessageMetricsResponseBodyDataMetrics>>(expect1);
}
}
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"]));
}
}
virtual ~ListMessageMetricsResponseBodyData() = default;
};
class ListMessageMetricsResponseBody : public Darabonba::Model {
public:
shared_ptr<ListMessageMetricsResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
ListMessageMetricsResponseBody() {}
explicit ListMessageMetricsResponseBody(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 (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
ListMessageMetricsResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<ListMessageMetricsResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~ListMessageMetricsResponseBody() = default;
};
class ListMessageMetricsResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<ListMessageMetricsResponseBody> body{};
ListMessageMetricsResponse() {}
explicit ListMessageMetricsResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
ListMessageMetricsResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<ListMessageMetricsResponseBody>(model1);
}
}
}
virtual ~ListMessageMetricsResponse() = default;
};
class ListMessagesRequest : public Darabonba::Model {
public:
shared_ptr<string> datetime{};
shared_ptr<string> errorCode{};
shared_ptr<string> groupId{};
shared_ptr<string> messageId{};
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<string> phoneNumber{};
shared_ptr<string> requestId{};
shared_ptr<string> scheduleId{};
shared_ptr<string> signature{};
shared_ptr<string> signatureId{};
shared_ptr<long> status{};
shared_ptr<string> templateCode{};
shared_ptr<string> templateId{};
shared_ptr<long> templateType{};
ListMessagesRequest() {}
explicit ListMessagesRequest(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 (datetime) {
res["Datetime"] = boost::any(*datetime);
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (groupId) {
res["GroupId"] = boost::any(*groupId);
}
if (messageId) {
res["MessageId"] = boost::any(*messageId);
}
if (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
if (phoneNumber) {
res["PhoneNumber"] = boost::any(*phoneNumber);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
if (scheduleId) {
res["ScheduleId"] = boost::any(*scheduleId);
}
if (signature) {
res["Signature"] = boost::any(*signature);
}
if (signatureId) {
res["SignatureId"] = boost::any(*signatureId);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (templateCode) {
res["TemplateCode"] = boost::any(*templateCode);
}
if (templateId) {
res["TemplateId"] = boost::any(*templateId);
}
if (templateType) {
res["TemplateType"] = boost::any(*templateType);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Datetime") != m.end() && !m["Datetime"].empty()) {
datetime = make_shared<string>(boost::any_cast<string>(m["Datetime"]));
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<string>(boost::any_cast<string>(m["ErrorCode"]));
}
if (m.find("GroupId") != m.end() && !m["GroupId"].empty()) {
groupId = make_shared<string>(boost::any_cast<string>(m["GroupId"]));
}
if (m.find("MessageId") != m.end() && !m["MessageId"].empty()) {
messageId = make_shared<string>(boost::any_cast<string>(m["MessageId"]));
}
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("PhoneNumber") != m.end() && !m["PhoneNumber"].empty()) {
phoneNumber = make_shared<string>(boost::any_cast<string>(m["PhoneNumber"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
if (m.find("ScheduleId") != m.end() && !m["ScheduleId"].empty()) {
scheduleId = make_shared<string>(boost::any_cast<string>(m["ScheduleId"]));
}
if (m.find("Signature") != m.end() && !m["Signature"].empty()) {
signature = make_shared<string>(boost::any_cast<string>(m["Signature"]));
}
if (m.find("SignatureId") != m.end() && !m["SignatureId"].empty()) {
signatureId = make_shared<string>(boost::any_cast<string>(m["SignatureId"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("TemplateCode") != m.end() && !m["TemplateCode"].empty()) {
templateCode = make_shared<string>(boost::any_cast<string>(m["TemplateCode"]));
}
if (m.find("TemplateId") != m.end() && !m["TemplateId"].empty()) {
templateId = make_shared<string>(boost::any_cast<string>(m["TemplateId"]));
}
if (m.find("TemplateType") != m.end() && !m["TemplateType"].empty()) {
templateType = make_shared<long>(boost::any_cast<long>(m["TemplateType"]));
}
}
virtual ~ListMessagesRequest() = default;
};
class ListMessagesResponseBodyDataMessages : public Darabonba::Model {
public:
shared_ptr<string> errorCode{};
shared_ptr<string> groupId{};
shared_ptr<string> id{};
shared_ptr<string> outId{};
shared_ptr<string> phoneNumber{};
shared_ptr<string> scheduleId{};
shared_ptr<string> signature{};
shared_ptr<long> status{};
shared_ptr<string> templateCode{};
shared_ptr<string> templateParams{};
shared_ptr<long> templateType{};
ListMessagesResponseBodyDataMessages() {}
explicit ListMessagesResponseBodyDataMessages(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 (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (groupId) {
res["GroupId"] = boost::any(*groupId);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (outId) {
res["OutId"] = boost::any(*outId);
}
if (phoneNumber) {
res["PhoneNumber"] = boost::any(*phoneNumber);
}
if (scheduleId) {
res["ScheduleId"] = boost::any(*scheduleId);
}
if (signature) {
res["Signature"] = boost::any(*signature);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (templateCode) {
res["TemplateCode"] = boost::any(*templateCode);
}
if (templateParams) {
res["TemplateParams"] = boost::any(*templateParams);
}
if (templateType) {
res["TemplateType"] = boost::any(*templateType);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<string>(boost::any_cast<string>(m["ErrorCode"]));
}
if (m.find("GroupId") != m.end() && !m["GroupId"].empty()) {
groupId = make_shared<string>(boost::any_cast<string>(m["GroupId"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("OutId") != m.end() && !m["OutId"].empty()) {
outId = make_shared<string>(boost::any_cast<string>(m["OutId"]));
}
if (m.find("PhoneNumber") != m.end() && !m["PhoneNumber"].empty()) {
phoneNumber = make_shared<string>(boost::any_cast<string>(m["PhoneNumber"]));
}
if (m.find("ScheduleId") != m.end() && !m["ScheduleId"].empty()) {
scheduleId = make_shared<string>(boost::any_cast<string>(m["ScheduleId"]));
}
if (m.find("Signature") != m.end() && !m["Signature"].empty()) {
signature = make_shared<string>(boost::any_cast<string>(m["Signature"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("TemplateCode") != m.end() && !m["TemplateCode"].empty()) {
templateCode = make_shared<string>(boost::any_cast<string>(m["TemplateCode"]));
}
if (m.find("TemplateParams") != m.end() && !m["TemplateParams"].empty()) {
templateParams = make_shared<string>(boost::any_cast<string>(m["TemplateParams"]));
}
if (m.find("TemplateType") != m.end() && !m["TemplateType"].empty()) {
templateType = make_shared<long>(boost::any_cast<long>(m["TemplateType"]));
}
}
virtual ~ListMessagesResponseBodyDataMessages() = default;
};
class ListMessagesResponseBodyData : public Darabonba::Model {
public:
shared_ptr<vector<ListMessagesResponseBodyDataMessages>> messages{};
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<long> totalCount{};
ListMessagesResponseBodyData() {}
explicit ListMessagesResponseBodyData(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 (messages) {
vector<boost::any> temp1;
for(auto item1:*messages){
temp1.push_back(boost::any(item1.toMap()));
}
res["Messages"] = boost::any(temp1);
}
if (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
if (totalCount) {
res["TotalCount"] = boost::any(*totalCount);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Messages") != m.end() && !m["Messages"].empty()) {
if (typeid(vector<boost::any>) == m["Messages"].type()) {
vector<ListMessagesResponseBodyDataMessages> expect1;
for(auto item1:boost::any_cast<vector<boost::any>>(m["Messages"])){
if (typeid(map<string, boost::any>) == item1.type()) {
ListMessagesResponseBodyDataMessages model2;
model2.fromMap(boost::any_cast<map<string, boost::any>>(item1));
expect1.push_back(model2);
}
}
messages = make_shared<vector<ListMessagesResponseBodyDataMessages>>(expect1);
}
}
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"]));
}
}
virtual ~ListMessagesResponseBodyData() = default;
};
class ListMessagesResponseBody : public Darabonba::Model {
public:
shared_ptr<ListMessagesResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
ListMessagesResponseBody() {}
explicit ListMessagesResponseBody(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 (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
ListMessagesResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<ListMessagesResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~ListMessagesResponseBody() = default;
};
class ListMessagesResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<ListMessagesResponseBody> body{};
ListMessagesResponse() {}
explicit ListMessagesResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
ListMessagesResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<ListMessagesResponseBody>(model1);
}
}
}
virtual ~ListMessagesResponse() = default;
};
class ListSchedulesRequest : public Darabonba::Model {
public:
shared_ptr<string> name{};
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<long> status{};
ListSchedulesRequest() {}
explicit ListSchedulesRequest(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 (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
if (status) {
res["Status"] = boost::any(*status);
}
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("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("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
}
virtual ~ListSchedulesRequest() = default;
};
class ListSchedulesResponseBodyDataSchedules : public Darabonba::Model {
public:
shared_ptr<string> createdTime{};
shared_ptr<long> endTime{};
shared_ptr<string> executeTime{};
shared_ptr<string> groupId{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<long> repeatCycle{};
shared_ptr<long> repeatCycleUnit{};
shared_ptr<long> repeatTimes{};
shared_ptr<string> signName{};
shared_ptr<string> signatureId{};
shared_ptr<long> status{};
shared_ptr<string> templateCode{};
shared_ptr<string> templateId{};
shared_ptr<string> updatedTime{};
ListSchedulesResponseBodyDataSchedules() {}
explicit ListSchedulesResponseBodyDataSchedules(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 (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (endTime) {
res["EndTime"] = boost::any(*endTime);
}
if (executeTime) {
res["ExecuteTime"] = boost::any(*executeTime);
}
if (groupId) {
res["GroupId"] = boost::any(*groupId);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (repeatCycle) {
res["RepeatCycle"] = boost::any(*repeatCycle);
}
if (repeatCycleUnit) {
res["RepeatCycleUnit"] = boost::any(*repeatCycleUnit);
}
if (repeatTimes) {
res["RepeatTimes"] = boost::any(*repeatTimes);
}
if (signName) {
res["SignName"] = boost::any(*signName);
}
if (signatureId) {
res["SignatureId"] = boost::any(*signatureId);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (templateCode) {
res["TemplateCode"] = boost::any(*templateCode);
}
if (templateId) {
res["TemplateId"] = boost::any(*templateId);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("EndTime") != m.end() && !m["EndTime"].empty()) {
endTime = make_shared<long>(boost::any_cast<long>(m["EndTime"]));
}
if (m.find("ExecuteTime") != m.end() && !m["ExecuteTime"].empty()) {
executeTime = make_shared<string>(boost::any_cast<string>(m["ExecuteTime"]));
}
if (m.find("GroupId") != m.end() && !m["GroupId"].empty()) {
groupId = make_shared<string>(boost::any_cast<string>(m["GroupId"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("RepeatCycle") != m.end() && !m["RepeatCycle"].empty()) {
repeatCycle = make_shared<long>(boost::any_cast<long>(m["RepeatCycle"]));
}
if (m.find("RepeatCycleUnit") != m.end() && !m["RepeatCycleUnit"].empty()) {
repeatCycleUnit = make_shared<long>(boost::any_cast<long>(m["RepeatCycleUnit"]));
}
if (m.find("RepeatTimes") != m.end() && !m["RepeatTimes"].empty()) {
repeatTimes = make_shared<long>(boost::any_cast<long>(m["RepeatTimes"]));
}
if (m.find("SignName") != m.end() && !m["SignName"].empty()) {
signName = make_shared<string>(boost::any_cast<string>(m["SignName"]));
}
if (m.find("SignatureId") != m.end() && !m["SignatureId"].empty()) {
signatureId = make_shared<string>(boost::any_cast<string>(m["SignatureId"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("TemplateCode") != m.end() && !m["TemplateCode"].empty()) {
templateCode = make_shared<string>(boost::any_cast<string>(m["TemplateCode"]));
}
if (m.find("TemplateId") != m.end() && !m["TemplateId"].empty()) {
templateId = make_shared<string>(boost::any_cast<string>(m["TemplateId"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
}
virtual ~ListSchedulesResponseBodyDataSchedules() = default;
};
class ListSchedulesResponseBodyData : public Darabonba::Model {
public:
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<vector<ListSchedulesResponseBodyDataSchedules>> schedules{};
shared_ptr<long> totalCount{};
ListSchedulesResponseBodyData() {}
explicit ListSchedulesResponseBodyData(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 (schedules) {
vector<boost::any> temp1;
for(auto item1:*schedules){
temp1.push_back(boost::any(item1.toMap()));
}
res["Schedules"] = boost::any(temp1);
}
if (totalCount) {
res["TotalCount"] = boost::any(*totalCount);
}
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("Schedules") != m.end() && !m["Schedules"].empty()) {
if (typeid(vector<boost::any>) == m["Schedules"].type()) {
vector<ListSchedulesResponseBodyDataSchedules> expect1;
for(auto item1:boost::any_cast<vector<boost::any>>(m["Schedules"])){
if (typeid(map<string, boost::any>) == item1.type()) {
ListSchedulesResponseBodyDataSchedules model2;
model2.fromMap(boost::any_cast<map<string, boost::any>>(item1));
expect1.push_back(model2);
}
}
schedules = make_shared<vector<ListSchedulesResponseBodyDataSchedules>>(expect1);
}
}
if (m.find("TotalCount") != m.end() && !m["TotalCount"].empty()) {
totalCount = make_shared<long>(boost::any_cast<long>(m["TotalCount"]));
}
}
virtual ~ListSchedulesResponseBodyData() = default;
};
class ListSchedulesResponseBody : public Darabonba::Model {
public:
shared_ptr<ListSchedulesResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
ListSchedulesResponseBody() {}
explicit ListSchedulesResponseBody(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 (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
ListSchedulesResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<ListSchedulesResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~ListSchedulesResponseBody() = default;
};
class ListSchedulesResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<ListSchedulesResponseBody> body{};
ListSchedulesResponse() {}
explicit ListSchedulesResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
ListSchedulesResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<ListSchedulesResponseBody>(model1);
}
}
}
virtual ~ListSchedulesResponse() = default;
};
class ListSignaturesRequest : public Darabonba::Model {
public:
shared_ptr<string> name{};
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<long> status{};
ListSignaturesRequest() {}
explicit ListSignaturesRequest(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 (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
if (status) {
res["Status"] = boost::any(*status);
}
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("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("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
}
virtual ~ListSignaturesRequest() = default;
};
class ListSignaturesResponseBodyDataSignatures : public Darabonba::Model {
public:
shared_ptr<string> createdTime{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<long> status{};
shared_ptr<string> updatedTime{};
ListSignaturesResponseBodyDataSignatures() {}
explicit ListSignaturesResponseBodyDataSignatures(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 (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
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<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
}
virtual ~ListSignaturesResponseBodyDataSignatures() = default;
};
class ListSignaturesResponseBodyData : public Darabonba::Model {
public:
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<vector<ListSignaturesResponseBodyDataSignatures>> signatures{};
shared_ptr<long> totalCount{};
ListSignaturesResponseBodyData() {}
explicit ListSignaturesResponseBodyData(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 (signatures) {
vector<boost::any> temp1;
for(auto item1:*signatures){
temp1.push_back(boost::any(item1.toMap()));
}
res["Signatures"] = boost::any(temp1);
}
if (totalCount) {
res["TotalCount"] = boost::any(*totalCount);
}
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("Signatures") != m.end() && !m["Signatures"].empty()) {
if (typeid(vector<boost::any>) == m["Signatures"].type()) {
vector<ListSignaturesResponseBodyDataSignatures> expect1;
for(auto item1:boost::any_cast<vector<boost::any>>(m["Signatures"])){
if (typeid(map<string, boost::any>) == item1.type()) {
ListSignaturesResponseBodyDataSignatures model2;
model2.fromMap(boost::any_cast<map<string, boost::any>>(item1));
expect1.push_back(model2);
}
}
signatures = make_shared<vector<ListSignaturesResponseBodyDataSignatures>>(expect1);
}
}
if (m.find("TotalCount") != m.end() && !m["TotalCount"].empty()) {
totalCount = make_shared<long>(boost::any_cast<long>(m["TotalCount"]));
}
}
virtual ~ListSignaturesResponseBodyData() = default;
};
class ListSignaturesResponseBody : public Darabonba::Model {
public:
shared_ptr<ListSignaturesResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
ListSignaturesResponseBody() {}
explicit ListSignaturesResponseBody(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 (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
ListSignaturesResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<ListSignaturesResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~ListSignaturesResponseBody() = default;
};
class ListSignaturesResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<ListSignaturesResponseBody> body{};
ListSignaturesResponse() {}
explicit ListSignaturesResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
ListSignaturesResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<ListSignaturesResponseBody>(model1);
}
}
}
virtual ~ListSignaturesResponse() = default;
};
class ListTemplatesRequest : public Darabonba::Model {
public:
shared_ptr<string> content{};
shared_ptr<string> name{};
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<long> status{};
shared_ptr<long> type{};
ListTemplatesRequest() {}
explicit ListTemplatesRequest(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 (content) {
res["Content"] = boost::any(*content);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (type) {
res["Type"] = boost::any(*type);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Content") != m.end() && !m["Content"].empty()) {
content = make_shared<string>(boost::any_cast<string>(m["Content"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
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("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("Type") != m.end() && !m["Type"].empty()) {
type = make_shared<long>(boost::any_cast<long>(m["Type"]));
}
}
virtual ~ListTemplatesRequest() = default;
};
class ListTemplatesResponseBodyDataTemplates : public Darabonba::Model {
public:
shared_ptr<string> content{};
shared_ptr<string> createdTime{};
shared_ptr<string> description{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<string> reason{};
shared_ptr<string> signatureId{};
shared_ptr<long> status{};
shared_ptr<string> templateCode{};
shared_ptr<long> type{};
shared_ptr<string> updatedTime{};
ListTemplatesResponseBodyDataTemplates() {}
explicit ListTemplatesResponseBodyDataTemplates(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 (content) {
res["Content"] = boost::any(*content);
}
if (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (description) {
res["Description"] = boost::any(*description);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (reason) {
res["Reason"] = boost::any(*reason);
}
if (signatureId) {
res["SignatureId"] = boost::any(*signatureId);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (templateCode) {
res["TemplateCode"] = boost::any(*templateCode);
}
if (type) {
res["Type"] = boost::any(*type);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Content") != m.end() && !m["Content"].empty()) {
content = make_shared<string>(boost::any_cast<string>(m["Content"]));
}
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("Description") != m.end() && !m["Description"].empty()) {
description = make_shared<string>(boost::any_cast<string>(m["Description"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Reason") != m.end() && !m["Reason"].empty()) {
reason = make_shared<string>(boost::any_cast<string>(m["Reason"]));
}
if (m.find("SignatureId") != m.end() && !m["SignatureId"].empty()) {
signatureId = make_shared<string>(boost::any_cast<string>(m["SignatureId"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("TemplateCode") != m.end() && !m["TemplateCode"].empty()) {
templateCode = make_shared<string>(boost::any_cast<string>(m["TemplateCode"]));
}
if (m.find("Type") != m.end() && !m["Type"].empty()) {
type = make_shared<long>(boost::any_cast<long>(m["Type"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
}
virtual ~ListTemplatesResponseBodyDataTemplates() = default;
};
class ListTemplatesResponseBodyData : public Darabonba::Model {
public:
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<vector<ListTemplatesResponseBodyDataTemplates>> templates{};
shared_ptr<long> totalCount{};
ListTemplatesResponseBodyData() {}
explicit ListTemplatesResponseBodyData(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 (templates) {
vector<boost::any> temp1;
for(auto item1:*templates){
temp1.push_back(boost::any(item1.toMap()));
}
res["Templates"] = boost::any(temp1);
}
if (totalCount) {
res["TotalCount"] = boost::any(*totalCount);
}
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("Templates") != m.end() && !m["Templates"].empty()) {
if (typeid(vector<boost::any>) == m["Templates"].type()) {
vector<ListTemplatesResponseBodyDataTemplates> expect1;
for(auto item1:boost::any_cast<vector<boost::any>>(m["Templates"])){
if (typeid(map<string, boost::any>) == item1.type()) {
ListTemplatesResponseBodyDataTemplates model2;
model2.fromMap(boost::any_cast<map<string, boost::any>>(item1));
expect1.push_back(model2);
}
}
templates = make_shared<vector<ListTemplatesResponseBodyDataTemplates>>(expect1);
}
}
if (m.find("TotalCount") != m.end() && !m["TotalCount"].empty()) {
totalCount = make_shared<long>(boost::any_cast<long>(m["TotalCount"]));
}
}
virtual ~ListTemplatesResponseBodyData() = default;
};
class ListTemplatesResponseBody : public Darabonba::Model {
public:
shared_ptr<ListTemplatesResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
ListTemplatesResponseBody() {}
explicit ListTemplatesResponseBody(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 (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
ListTemplatesResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<ListTemplatesResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~ListTemplatesResponseBody() = default;
};
class ListTemplatesResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<ListTemplatesResponseBody> body{};
ListTemplatesResponse() {}
explicit ListTemplatesResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
ListTemplatesResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<ListTemplatesResponseBody>(model1);
}
}
}
virtual ~ListTemplatesResponse() = default;
};
class ListTrainingJobsRequest : public Darabonba::Model {
public:
shared_ptr<string> campaignId{};
shared_ptr<string> name{};
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<string> remark{};
shared_ptr<long> status{};
ListTrainingJobsRequest() {}
explicit ListTrainingJobsRequest(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 (campaignId) {
res["CampaignId"] = boost::any(*campaignId);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (pageNumber) {
res["PageNumber"] = boost::any(*pageNumber);
}
if (pageSize) {
res["PageSize"] = boost::any(*pageSize);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (status) {
res["Status"] = boost::any(*status);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("CampaignId") != m.end() && !m["CampaignId"].empty()) {
campaignId = make_shared<string>(boost::any_cast<string>(m["CampaignId"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
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("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
}
virtual ~ListTrainingJobsRequest() = default;
};
class ListTrainingJobsResponseBodyDataTrainingJobs : public Darabonba::Model {
public:
shared_ptr<string> algorithm{};
shared_ptr<string> campaignId{};
shared_ptr<string> createdTime{};
shared_ptr<string> dataPath{};
shared_ptr<string> history{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<string> remark{};
shared_ptr<long> status{};
shared_ptr<string> updatedTime{};
shared_ptr<string> userConfig{};
ListTrainingJobsResponseBodyDataTrainingJobs() {}
explicit ListTrainingJobsResponseBodyDataTrainingJobs(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 (algorithm) {
res["Algorithm"] = boost::any(*algorithm);
}
if (campaignId) {
res["CampaignId"] = boost::any(*campaignId);
}
if (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (dataPath) {
res["DataPath"] = boost::any(*dataPath);
}
if (history) {
res["History"] = boost::any(*history);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (status) {
res["Status"] = boost::any(*status);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
if (userConfig) {
res["UserConfig"] = boost::any(*userConfig);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Algorithm") != m.end() && !m["Algorithm"].empty()) {
algorithm = make_shared<string>(boost::any_cast<string>(m["Algorithm"]));
}
if (m.find("CampaignId") != m.end() && !m["CampaignId"].empty()) {
campaignId = make_shared<string>(boost::any_cast<string>(m["CampaignId"]));
}
if (m.find("CreatedTime") != m.end() && !m["CreatedTime"].empty()) {
createdTime = make_shared<string>(boost::any_cast<string>(m["CreatedTime"]));
}
if (m.find("DataPath") != m.end() && !m["DataPath"].empty()) {
dataPath = make_shared<string>(boost::any_cast<string>(m["DataPath"]));
}
if (m.find("History") != m.end() && !m["History"].empty()) {
history = make_shared<string>(boost::any_cast<string>(m["History"]));
}
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("Status") != m.end() && !m["Status"].empty()) {
status = make_shared<long>(boost::any_cast<long>(m["Status"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
if (m.find("UserConfig") != m.end() && !m["UserConfig"].empty()) {
userConfig = make_shared<string>(boost::any_cast<string>(m["UserConfig"]));
}
}
virtual ~ListTrainingJobsResponseBodyDataTrainingJobs() = default;
};
class ListTrainingJobsResponseBodyData : public Darabonba::Model {
public:
shared_ptr<long> pageNumber{};
shared_ptr<long> pageSize{};
shared_ptr<long> totalCount{};
shared_ptr<vector<ListTrainingJobsResponseBodyDataTrainingJobs>> trainingJobs{};
ListTrainingJobsResponseBodyData() {}
explicit ListTrainingJobsResponseBodyData(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 (trainingJobs) {
vector<boost::any> temp1;
for(auto item1:*trainingJobs){
temp1.push_back(boost::any(item1.toMap()));
}
res["TrainingJobs"] = 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("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("TrainingJobs") != m.end() && !m["TrainingJobs"].empty()) {
if (typeid(vector<boost::any>) == m["TrainingJobs"].type()) {
vector<ListTrainingJobsResponseBodyDataTrainingJobs> expect1;
for(auto item1:boost::any_cast<vector<boost::any>>(m["TrainingJobs"])){
if (typeid(map<string, boost::any>) == item1.type()) {
ListTrainingJobsResponseBodyDataTrainingJobs model2;
model2.fromMap(boost::any_cast<map<string, boost::any>>(item1));
expect1.push_back(model2);
}
}
trainingJobs = make_shared<vector<ListTrainingJobsResponseBodyDataTrainingJobs>>(expect1);
}
}
}
virtual ~ListTrainingJobsResponseBodyData() = default;
};
class ListTrainingJobsResponseBody : public Darabonba::Model {
public:
shared_ptr<ListTrainingJobsResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
ListTrainingJobsResponseBody() {}
explicit ListTrainingJobsResponseBody(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 (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
ListTrainingJobsResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<ListTrainingJobsResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~ListTrainingJobsResponseBody() = default;
};
class ListTrainingJobsResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<ListTrainingJobsResponseBody> body{};
ListTrainingJobsResponse() {}
explicit ListTrainingJobsResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
ListTrainingJobsResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<ListTrainingJobsResponseBody>(model1);
}
}
}
virtual ~ListTrainingJobsResponse() = default;
};
class SendMessageRequest : public Darabonba::Model {
public:
shared_ptr<string> groupId{};
shared_ptr<vector<string>> outIds{};
shared_ptr<vector<string>> phoneNumbers{};
shared_ptr<string> scheduleId{};
shared_ptr<string> signName{};
shared_ptr<string> signatureId{};
shared_ptr<vector<string>> smsUpExtendCodes{};
shared_ptr<string> templateCode{};
shared_ptr<string> templateId{};
shared_ptr<vector<string>> templateParams{};
SendMessageRequest() {}
explicit SendMessageRequest(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 (groupId) {
res["GroupId"] = boost::any(*groupId);
}
if (outIds) {
res["OutIds"] = boost::any(*outIds);
}
if (phoneNumbers) {
res["PhoneNumbers"] = boost::any(*phoneNumbers);
}
if (scheduleId) {
res["ScheduleId"] = boost::any(*scheduleId);
}
if (signName) {
res["SignName"] = boost::any(*signName);
}
if (signatureId) {
res["SignatureId"] = boost::any(*signatureId);
}
if (smsUpExtendCodes) {
res["SmsUpExtendCodes"] = boost::any(*smsUpExtendCodes);
}
if (templateCode) {
res["TemplateCode"] = boost::any(*templateCode);
}
if (templateId) {
res["TemplateId"] = boost::any(*templateId);
}
if (templateParams) {
res["TemplateParams"] = boost::any(*templateParams);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("GroupId") != m.end() && !m["GroupId"].empty()) {
groupId = make_shared<string>(boost::any_cast<string>(m["GroupId"]));
}
if (m.find("OutIds") != m.end() && !m["OutIds"].empty()) {
vector<string> toVec1;
if (typeid(vector<boost::any>) == m["OutIds"].type()) {
vector<boost::any> vec1 = boost::any_cast<vector<boost::any>>(m["OutIds"]);
for (auto item:vec1) {
toVec1.push_back(boost::any_cast<string>(item));
}
}
outIds = make_shared<vector<string>>(toVec1);
}
if (m.find("PhoneNumbers") != m.end() && !m["PhoneNumbers"].empty()) {
vector<string> toVec1;
if (typeid(vector<boost::any>) == m["PhoneNumbers"].type()) {
vector<boost::any> vec1 = boost::any_cast<vector<boost::any>>(m["PhoneNumbers"]);
for (auto item:vec1) {
toVec1.push_back(boost::any_cast<string>(item));
}
}
phoneNumbers = make_shared<vector<string>>(toVec1);
}
if (m.find("ScheduleId") != m.end() && !m["ScheduleId"].empty()) {
scheduleId = make_shared<string>(boost::any_cast<string>(m["ScheduleId"]));
}
if (m.find("SignName") != m.end() && !m["SignName"].empty()) {
signName = make_shared<string>(boost::any_cast<string>(m["SignName"]));
}
if (m.find("SignatureId") != m.end() && !m["SignatureId"].empty()) {
signatureId = make_shared<string>(boost::any_cast<string>(m["SignatureId"]));
}
if (m.find("SmsUpExtendCodes") != m.end() && !m["SmsUpExtendCodes"].empty()) {
vector<string> toVec1;
if (typeid(vector<boost::any>) == m["SmsUpExtendCodes"].type()) {
vector<boost::any> vec1 = boost::any_cast<vector<boost::any>>(m["SmsUpExtendCodes"]);
for (auto item:vec1) {
toVec1.push_back(boost::any_cast<string>(item));
}
}
smsUpExtendCodes = make_shared<vector<string>>(toVec1);
}
if (m.find("TemplateCode") != m.end() && !m["TemplateCode"].empty()) {
templateCode = make_shared<string>(boost::any_cast<string>(m["TemplateCode"]));
}
if (m.find("TemplateId") != m.end() && !m["TemplateId"].empty()) {
templateId = make_shared<string>(boost::any_cast<string>(m["TemplateId"]));
}
if (m.find("TemplateParams") != m.end() && !m["TemplateParams"].empty()) {
vector<string> toVec1;
if (typeid(vector<boost::any>) == m["TemplateParams"].type()) {
vector<boost::any> vec1 = boost::any_cast<vector<boost::any>>(m["TemplateParams"]);
for (auto item:vec1) {
toVec1.push_back(boost::any_cast<string>(item));
}
}
templateParams = make_shared<vector<string>>(toVec1);
}
}
virtual ~SendMessageRequest() = default;
};
class SendMessageResponseBodyDataMessages : public Darabonba::Model {
public:
shared_ptr<string> id{};
shared_ptr<string> phoneNumber{};
SendMessageResponseBodyDataMessages() {}
explicit SendMessageResponseBodyDataMessages(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 (id) {
res["Id"] = boost::any(*id);
}
if (phoneNumber) {
res["PhoneNumber"] = boost::any(*phoneNumber);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Id") != m.end() && !m["Id"].empty()) {
id = make_shared<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("PhoneNumber") != m.end() && !m["PhoneNumber"].empty()) {
phoneNumber = make_shared<string>(boost::any_cast<string>(m["PhoneNumber"]));
}
}
virtual ~SendMessageResponseBodyDataMessages() = default;
};
class SendMessageResponseBodyData : public Darabonba::Model {
public:
shared_ptr<vector<SendMessageResponseBodyDataMessages>> messages{};
shared_ptr<string> requestId{};
SendMessageResponseBodyData() {}
explicit SendMessageResponseBodyData(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 (messages) {
vector<boost::any> temp1;
for(auto item1:*messages){
temp1.push_back(boost::any(item1.toMap()));
}
res["Messages"] = boost::any(temp1);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Messages") != m.end() && !m["Messages"].empty()) {
if (typeid(vector<boost::any>) == m["Messages"].type()) {
vector<SendMessageResponseBodyDataMessages> expect1;
for(auto item1:boost::any_cast<vector<boost::any>>(m["Messages"])){
if (typeid(map<string, boost::any>) == item1.type()) {
SendMessageResponseBodyDataMessages model2;
model2.fromMap(boost::any_cast<map<string, boost::any>>(item1));
expect1.push_back(model2);
}
}
messages = make_shared<vector<SendMessageResponseBodyDataMessages>>(expect1);
}
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~SendMessageResponseBodyData() = default;
};
class SendMessageResponseBody : public Darabonba::Model {
public:
shared_ptr<SendMessageResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
SendMessageResponseBody() {}
explicit SendMessageResponseBody(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 (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
SendMessageResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<SendMessageResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~SendMessageResponseBody() = default;
};
class SendMessageResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<SendMessageResponseBody> body{};
SendMessageResponse() {}
explicit SendMessageResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
SendMessageResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<SendMessageResponseBody>(model1);
}
}
}
virtual ~SendMessageResponse() = default;
};
class SmsReportRequestBody : public Darabonba::Model {
public:
shared_ptr<string> bizId{};
shared_ptr<string> errCode{};
shared_ptr<string> errMsg{};
shared_ptr<string> messageId{};
shared_ptr<string> outId{};
shared_ptr<string> phoneNumber{};
shared_ptr<string> reportTime{};
shared_ptr<string> requestId{};
shared_ptr<string> sendTime{};
shared_ptr<string> signName{};
shared_ptr<string> smsSize{};
shared_ptr<bool> success{};
shared_ptr<string> templateCode{};
SmsReportRequestBody() {}
explicit SmsReportRequestBody(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 (bizId) {
res["biz_id"] = boost::any(*bizId);
}
if (errCode) {
res["err_code"] = boost::any(*errCode);
}
if (errMsg) {
res["err_msg"] = boost::any(*errMsg);
}
if (messageId) {
res["message_id"] = boost::any(*messageId);
}
if (outId) {
res["out_id"] = boost::any(*outId);
}
if (phoneNumber) {
res["phone_number"] = boost::any(*phoneNumber);
}
if (reportTime) {
res["report_time"] = boost::any(*reportTime);
}
if (requestId) {
res["request_id"] = boost::any(*requestId);
}
if (sendTime) {
res["send_time"] = boost::any(*sendTime);
}
if (signName) {
res["sign_name"] = boost::any(*signName);
}
if (smsSize) {
res["sms_size"] = boost::any(*smsSize);
}
if (success) {
res["success"] = boost::any(*success);
}
if (templateCode) {
res["template_code"] = boost::any(*templateCode);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("biz_id") != m.end() && !m["biz_id"].empty()) {
bizId = make_shared<string>(boost::any_cast<string>(m["biz_id"]));
}
if (m.find("err_code") != m.end() && !m["err_code"].empty()) {
errCode = make_shared<string>(boost::any_cast<string>(m["err_code"]));
}
if (m.find("err_msg") != m.end() && !m["err_msg"].empty()) {
errMsg = make_shared<string>(boost::any_cast<string>(m["err_msg"]));
}
if (m.find("message_id") != m.end() && !m["message_id"].empty()) {
messageId = make_shared<string>(boost::any_cast<string>(m["message_id"]));
}
if (m.find("out_id") != m.end() && !m["out_id"].empty()) {
outId = make_shared<string>(boost::any_cast<string>(m["out_id"]));
}
if (m.find("phone_number") != m.end() && !m["phone_number"].empty()) {
phoneNumber = make_shared<string>(boost::any_cast<string>(m["phone_number"]));
}
if (m.find("report_time") != m.end() && !m["report_time"].empty()) {
reportTime = make_shared<string>(boost::any_cast<string>(m["report_time"]));
}
if (m.find("request_id") != m.end() && !m["request_id"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["request_id"]));
}
if (m.find("send_time") != m.end() && !m["send_time"].empty()) {
sendTime = make_shared<string>(boost::any_cast<string>(m["send_time"]));
}
if (m.find("sign_name") != m.end() && !m["sign_name"].empty()) {
signName = make_shared<string>(boost::any_cast<string>(m["sign_name"]));
}
if (m.find("sms_size") != m.end() && !m["sms_size"].empty()) {
smsSize = make_shared<string>(boost::any_cast<string>(m["sms_size"]));
}
if (m.find("success") != m.end() && !m["success"].empty()) {
success = make_shared<bool>(boost::any_cast<bool>(m["success"]));
}
if (m.find("template_code") != m.end() && !m["template_code"].empty()) {
templateCode = make_shared<string>(boost::any_cast<string>(m["template_code"]));
}
}
virtual ~SmsReportRequestBody() = default;
};
class SmsReportRequest : public Darabonba::Model {
public:
shared_ptr<vector<SmsReportRequestBody>> body{};
SmsReportRequest() {}
explicit SmsReportRequest(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 (body) {
vector<boost::any> temp1;
for(auto item1:*body){
temp1.push_back(boost::any(item1.toMap()));
}
res["body"] = boost::any(temp1);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(vector<boost::any>) == m["body"].type()) {
vector<SmsReportRequestBody> expect1;
for(auto item1:boost::any_cast<vector<boost::any>>(m["body"])){
if (typeid(map<string, boost::any>) == item1.type()) {
SmsReportRequestBody model2;
model2.fromMap(boost::any_cast<map<string, boost::any>>(item1));
expect1.push_back(model2);
}
}
body = make_shared<vector<SmsReportRequestBody>>(expect1);
}
}
}
virtual ~SmsReportRequest() = default;
};
class SmsReportResponseBody : public Darabonba::Model {
public:
shared_ptr<long> code{};
shared_ptr<string> msg{};
SmsReportResponseBody() {}
explicit SmsReportResponseBody(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 (code) {
res["code"] = boost::any(*code);
}
if (msg) {
res["msg"] = boost::any(*msg);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("code") != m.end() && !m["code"].empty()) {
code = make_shared<long>(boost::any_cast<long>(m["code"]));
}
if (m.find("msg") != m.end() && !m["msg"].empty()) {
msg = make_shared<string>(boost::any_cast<string>(m["msg"]));
}
}
virtual ~SmsReportResponseBody() = default;
};
class SmsReportResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<SmsReportResponseBody> body{};
SmsReportResponse() {}
explicit SmsReportResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
SmsReportResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<SmsReportResponseBody>(model1);
}
}
}
virtual ~SmsReportResponse() = default;
};
class SmsUpRequestBody : public Darabonba::Model {
public:
shared_ptr<string> content{};
shared_ptr<string> destCode{};
shared_ptr<string> phoneNumber{};
shared_ptr<string> sendTime{};
shared_ptr<long> sequenceId{};
shared_ptr<string> signName{};
SmsUpRequestBody() {}
explicit SmsUpRequestBody(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 (content) {
res["content"] = boost::any(*content);
}
if (destCode) {
res["dest_code"] = boost::any(*destCode);
}
if (phoneNumber) {
res["phone_number"] = boost::any(*phoneNumber);
}
if (sendTime) {
res["send_time"] = boost::any(*sendTime);
}
if (sequenceId) {
res["sequence_id"] = boost::any(*sequenceId);
}
if (signName) {
res["sign_name"] = boost::any(*signName);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("content") != m.end() && !m["content"].empty()) {
content = make_shared<string>(boost::any_cast<string>(m["content"]));
}
if (m.find("dest_code") != m.end() && !m["dest_code"].empty()) {
destCode = make_shared<string>(boost::any_cast<string>(m["dest_code"]));
}
if (m.find("phone_number") != m.end() && !m["phone_number"].empty()) {
phoneNumber = make_shared<string>(boost::any_cast<string>(m["phone_number"]));
}
if (m.find("send_time") != m.end() && !m["send_time"].empty()) {
sendTime = make_shared<string>(boost::any_cast<string>(m["send_time"]));
}
if (m.find("sequence_id") != m.end() && !m["sequence_id"].empty()) {
sequenceId = make_shared<long>(boost::any_cast<long>(m["sequence_id"]));
}
if (m.find("sign_name") != m.end() && !m["sign_name"].empty()) {
signName = make_shared<string>(boost::any_cast<string>(m["sign_name"]));
}
}
virtual ~SmsUpRequestBody() = default;
};
class SmsUpRequest : public Darabonba::Model {
public:
shared_ptr<vector<SmsUpRequestBody>> body{};
SmsUpRequest() {}
explicit SmsUpRequest(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 (body) {
vector<boost::any> temp1;
for(auto item1:*body){
temp1.push_back(boost::any(item1.toMap()));
}
res["body"] = boost::any(temp1);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(vector<boost::any>) == m["body"].type()) {
vector<SmsUpRequestBody> expect1;
for(auto item1:boost::any_cast<vector<boost::any>>(m["body"])){
if (typeid(map<string, boost::any>) == item1.type()) {
SmsUpRequestBody model2;
model2.fromMap(boost::any_cast<map<string, boost::any>>(item1));
expect1.push_back(model2);
}
}
body = make_shared<vector<SmsUpRequestBody>>(expect1);
}
}
}
virtual ~SmsUpRequest() = default;
};
class SmsUpResponseBody : public Darabonba::Model {
public:
shared_ptr<long> code{};
shared_ptr<string> msg{};
SmsUpResponseBody() {}
explicit SmsUpResponseBody(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 (code) {
res["code"] = boost::any(*code);
}
if (msg) {
res["msg"] = boost::any(*msg);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("code") != m.end() && !m["code"].empty()) {
code = make_shared<long>(boost::any_cast<long>(m["code"]));
}
if (m.find("msg") != m.end() && !m["msg"].empty()) {
msg = make_shared<string>(boost::any_cast<string>(m["msg"]));
}
}
virtual ~SmsUpResponseBody() = default;
};
class SmsUpResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<SmsUpResponseBody> body{};
SmsUpResponse() {}
explicit SmsUpResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
SmsUpResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<SmsUpResponseBody>(model1);
}
}
}
virtual ~SmsUpResponse() = default;
};
class UpdateCampaignRequest : public Darabonba::Model {
public:
shared_ptr<string> name{};
shared_ptr<string> remark{};
UpdateCampaignRequest() {}
explicit UpdateCampaignRequest(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 (remark) {
res["Remark"] = boost::any(*remark);
}
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("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
}
virtual ~UpdateCampaignRequest() = default;
};
class UpdateCampaignResponseBodyData : public Darabonba::Model {
public:
shared_ptr<string> createdTime{};
shared_ptr<string> id{};
shared_ptr<string> name{};
shared_ptr<string> remark{};
shared_ptr<string> updatedTime{};
UpdateCampaignResponseBodyData() {}
explicit UpdateCampaignResponseBodyData(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 (createdTime) {
res["CreatedTime"] = boost::any(*createdTime);
}
if (id) {
res["Id"] = boost::any(*id);
}
if (name) {
res["Name"] = boost::any(*name);
}
if (remark) {
res["Remark"] = boost::any(*remark);
}
if (updatedTime) {
res["UpdatedTime"] = boost::any(*updatedTime);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
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<string>(boost::any_cast<string>(m["Id"]));
}
if (m.find("Name") != m.end() && !m["Name"].empty()) {
name = make_shared<string>(boost::any_cast<string>(m["Name"]));
}
if (m.find("Remark") != m.end() && !m["Remark"].empty()) {
remark = make_shared<string>(boost::any_cast<string>(m["Remark"]));
}
if (m.find("UpdatedTime") != m.end() && !m["UpdatedTime"].empty()) {
updatedTime = make_shared<string>(boost::any_cast<string>(m["UpdatedTime"]));
}
}
virtual ~UpdateCampaignResponseBodyData() = default;
};
class UpdateCampaignResponseBody : public Darabonba::Model {
public:
shared_ptr<UpdateCampaignResponseBodyData> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
UpdateCampaignResponseBody() {}
explicit UpdateCampaignResponseBody(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 (data) {
res["Data"] = data ? boost::any(data->toMap()) : boost::any(map<string,boost::any>({}));
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
if (typeid(map<string, boost::any>) == m["Data"].type()) {
UpdateCampaignResponseBodyData model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["Data"]));
data = make_shared<UpdateCampaignResponseBodyData>(model1);
}
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~UpdateCampaignResponseBody() = default;
};
class UpdateCampaignResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<UpdateCampaignResponseBody> body{};
UpdateCampaignResponse() {}
explicit UpdateCampaignResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
UpdateCampaignResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<UpdateCampaignResponseBody>(model1);
}
}
}
virtual ~UpdateCampaignResponse() = default;
};
class UpdateReportUrlRequest : public Darabonba::Model {
public:
shared_ptr<string> url{};
UpdateReportUrlRequest() {}
explicit UpdateReportUrlRequest(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 (url) {
res["Url"] = boost::any(*url);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Url") != m.end() && !m["Url"].empty()) {
url = make_shared<string>(boost::any_cast<string>(m["Url"]));
}
}
virtual ~UpdateReportUrlRequest() = default;
};
class UpdateReportUrlResponseBody : public Darabonba::Model {
public:
shared_ptr<string> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
UpdateReportUrlResponseBody() {}
explicit UpdateReportUrlResponseBody(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 (data) {
res["Data"] = boost::any(*data);
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
data = make_shared<string>(boost::any_cast<string>(m["Data"]));
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~UpdateReportUrlResponseBody() = default;
};
class UpdateReportUrlResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<UpdateReportUrlResponseBody> body{};
UpdateReportUrlResponse() {}
explicit UpdateReportUrlResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
UpdateReportUrlResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<UpdateReportUrlResponseBody>(model1);
}
}
}
virtual ~UpdateReportUrlResponse() = default;
};
class UpdateUploadUrlRequest : public Darabonba::Model {
public:
shared_ptr<string> url{};
UpdateUploadUrlRequest() {}
explicit UpdateUploadUrlRequest(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 (url) {
res["Url"] = boost::any(*url);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Url") != m.end() && !m["Url"].empty()) {
url = make_shared<string>(boost::any_cast<string>(m["Url"]));
}
}
virtual ~UpdateUploadUrlRequest() = default;
};
class UpdateUploadUrlResponseBody : public Darabonba::Model {
public:
shared_ptr<string> data{};
shared_ptr<long> errorCode{};
shared_ptr<string> errorMessage{};
shared_ptr<string> requestId{};
UpdateUploadUrlResponseBody() {}
explicit UpdateUploadUrlResponseBody(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 (data) {
res["Data"] = boost::any(*data);
}
if (errorCode) {
res["ErrorCode"] = boost::any(*errorCode);
}
if (errorMessage) {
res["ErrorMessage"] = boost::any(*errorMessage);
}
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("Data") != m.end() && !m["Data"].empty()) {
data = make_shared<string>(boost::any_cast<string>(m["Data"]));
}
if (m.find("ErrorCode") != m.end() && !m["ErrorCode"].empty()) {
errorCode = make_shared<long>(boost::any_cast<long>(m["ErrorCode"]));
}
if (m.find("ErrorMessage") != m.end() && !m["ErrorMessage"].empty()) {
errorMessage = make_shared<string>(boost::any_cast<string>(m["ErrorMessage"]));
}
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
}
virtual ~UpdateUploadUrlResponseBody() = default;
};
class UpdateUploadUrlResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<long> statusCode{};
shared_ptr<UpdateUploadUrlResponseBody> body{};
UpdateUploadUrlResponse() {}
explicit UpdateUploadUrlResponse(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 (!statusCode) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("statusCode 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 (statusCode) {
res["statusCode"] = boost::any(*statusCode);
}
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("statusCode") != m.end() && !m["statusCode"].empty()) {
statusCode = make_shared<long>(boost::any_cast<long>(m["statusCode"]));
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
UpdateUploadUrlResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<UpdateUploadUrlResponseBody>(model1);
}
}
}
virtual ~UpdateUploadUrlResponse() = 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);
CreateCampaignResponse createCampaign(shared_ptr<CreateCampaignRequest> request);
CreateCampaignResponse createCampaignWithOptions(shared_ptr<CreateCampaignRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
CreateGroupResponse createGroup(shared_ptr<CreateGroupRequest> request);
CreateGroupResponse createGroupWithOptions(shared_ptr<CreateGroupRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
CreateInferenceJobResponse createInferenceJob(shared_ptr<CreateInferenceJobRequest> request);
CreateInferenceJobResponse createInferenceJobWithOptions(shared_ptr<CreateInferenceJobRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
CreateScheduleResponse createSchedule(shared_ptr<CreateScheduleRequest> request);
CreateScheduleResponse createScheduleWithOptions(shared_ptr<CreateScheduleRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
CreateSignatureResponse createSignature(shared_ptr<CreateSignatureRequest> request);
CreateSignatureResponse createSignatureWithOptions(shared_ptr<CreateSignatureRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
CreateTemplateResponse createTemplate(shared_ptr<CreateTemplateRequest> request);
CreateTemplateResponse createTemplateWithOptions(shared_ptr<CreateTemplateRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
CreateTrainingJobResponse createTrainingJob(shared_ptr<CreateTrainingJobRequest> request);
CreateTrainingJobResponse createTrainingJobWithOptions(shared_ptr<CreateTrainingJobRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
DeleteCampaignResponse deleteCampaign(shared_ptr<string> Id);
DeleteCampaignResponse deleteCampaignWithOptions(shared_ptr<string> Id, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
DeleteGroupResponse deleteGroup(shared_ptr<string> Id);
DeleteGroupResponse deleteGroupWithOptions(shared_ptr<string> Id, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
DeleteInferenceJobResponse deleteInferenceJob(shared_ptr<string> Id);
DeleteInferenceJobResponse deleteInferenceJobWithOptions(shared_ptr<string> Id, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
DeleteScheduleResponse deleteSchedule(shared_ptr<string> Id);
DeleteScheduleResponse deleteScheduleWithOptions(shared_ptr<string> Id, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
DeleteSignatureResponse deleteSignature(shared_ptr<string> Id);
DeleteSignatureResponse deleteSignatureWithOptions(shared_ptr<string> Id, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
DeleteTemplateResponse deleteTemplate(shared_ptr<string> Id);
DeleteTemplateResponse deleteTemplateWithOptions(shared_ptr<string> Id, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
DeleteTrainingJobResponse deleteTrainingJob(shared_ptr<string> Id);
DeleteTrainingJobResponse deleteTrainingJobWithOptions(shared_ptr<string> Id, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
GetAlgorithmResponse getAlgorithm(shared_ptr<string> Id);
GetAlgorithmResponse getAlgorithmWithOptions(shared_ptr<string> Id, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
GetCampaignResponse getCampaign(shared_ptr<string> Id);
GetCampaignResponse getCampaignWithOptions(shared_ptr<string> Id, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
GetGroupResponse getGroup(shared_ptr<string> Id);
GetGroupResponse getGroupWithOptions(shared_ptr<string> Id, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
GetInferenceJobResponse getInferenceJob(shared_ptr<string> Id);
GetInferenceJobResponse getInferenceJobWithOptions(shared_ptr<string> Id, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
GetMessageConfigResponse getMessageConfig();
GetMessageConfigResponse getMessageConfigWithOptions(shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
GetScheduleResponse getSchedule(shared_ptr<string> Id);
GetScheduleResponse getScheduleWithOptions(shared_ptr<string> Id, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
GetSignatureResponse getSignature(shared_ptr<string> Id);
GetSignatureResponse getSignatureWithOptions(shared_ptr<string> Id, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
GetTemplateResponse getTemplate(shared_ptr<string> Id);
GetTemplateResponse getTemplateWithOptions(shared_ptr<string> Id, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
GetTrainingJobResponse getTrainingJob(shared_ptr<string> Id);
GetTrainingJobResponse getTrainingJobWithOptions(shared_ptr<string> Id, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
GetUserResponse getUser();
GetUserResponse getUserWithOptions(shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
ListAlgorithmsResponse listAlgorithms(shared_ptr<ListAlgorithmsRequest> request);
ListAlgorithmsResponse listAlgorithmsWithOptions(shared_ptr<ListAlgorithmsRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
ListCampaignsResponse listCampaigns(shared_ptr<ListCampaignsRequest> request);
ListCampaignsResponse listCampaignsWithOptions(shared_ptr<ListCampaignsRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
ListGroupsResponse listGroups(shared_ptr<ListGroupsRequest> request);
ListGroupsResponse listGroupsWithOptions(shared_ptr<ListGroupsRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
ListInferenceJobsResponse listInferenceJobs(shared_ptr<ListInferenceJobsRequest> request);
ListInferenceJobsResponse listInferenceJobsWithOptions(shared_ptr<ListInferenceJobsRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
ListMessageMetricsResponse listMessageMetrics(shared_ptr<ListMessageMetricsRequest> request);
ListMessageMetricsResponse listMessageMetricsWithOptions(shared_ptr<ListMessageMetricsRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
ListMessagesResponse listMessages(shared_ptr<ListMessagesRequest> request);
ListMessagesResponse listMessagesWithOptions(shared_ptr<ListMessagesRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
ListSchedulesResponse listSchedules(shared_ptr<ListSchedulesRequest> request);
ListSchedulesResponse listSchedulesWithOptions(shared_ptr<ListSchedulesRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
ListSignaturesResponse listSignatures(shared_ptr<ListSignaturesRequest> request);
ListSignaturesResponse listSignaturesWithOptions(shared_ptr<ListSignaturesRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
ListTemplatesResponse listTemplates(shared_ptr<ListTemplatesRequest> request);
ListTemplatesResponse listTemplatesWithOptions(shared_ptr<ListTemplatesRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
ListTrainingJobsResponse listTrainingJobs(shared_ptr<ListTrainingJobsRequest> request);
ListTrainingJobsResponse listTrainingJobsWithOptions(shared_ptr<ListTrainingJobsRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
SendMessageResponse sendMessage(shared_ptr<SendMessageRequest> request);
SendMessageResponse sendMessageWithOptions(shared_ptr<SendMessageRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
SmsReportResponse smsReport(shared_ptr<SmsReportRequest> request);
SmsReportResponse smsReportWithOptions(shared_ptr<SmsReportRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
SmsUpResponse smsUp(shared_ptr<SmsUpRequest> request);
SmsUpResponse smsUpWithOptions(shared_ptr<SmsUpRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
UpdateCampaignResponse updateCampaign(shared_ptr<string> Id, shared_ptr<UpdateCampaignRequest> request);
UpdateCampaignResponse updateCampaignWithOptions(shared_ptr<string> Id,
shared_ptr<UpdateCampaignRequest> request,
shared_ptr<map<string, string>> headers,
shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
UpdateReportUrlResponse updateReportUrl(shared_ptr<UpdateReportUrlRequest> request);
UpdateReportUrlResponse updateReportUrlWithOptions(shared_ptr<UpdateReportUrlRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
UpdateUploadUrlResponse updateUploadUrl(shared_ptr<UpdateUploadUrlRequest> request);
UpdateUploadUrlResponse updateUploadUrlWithOptions(shared_ptr<UpdateUploadUrlRequest> request, shared_ptr<map<string, string>> headers, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
virtual ~Client() = default;
};
} // namespace Alibabacloud_PaiPlugin20220112
#endif
| 33.454175 | 199 | 0.615746 |
f916613855148acf4ddb6053fd02d8472bba92ea | 1,924 | cpp | C++ | kdl/schema/resource_type/resource_field.cpp | EvocationGames/libKDL | 90eb2ce71a1545f6e33164230f0e5d6ece0acaa7 | [
"MIT"
] | null | null | null | kdl/schema/resource_type/resource_field.cpp | EvocationGames/libKDL | 90eb2ce71a1545f6e33164230f0e5d6ece0acaa7 | [
"MIT"
] | null | null | null | kdl/schema/resource_type/resource_field.cpp | EvocationGames/libKDL | 90eb2ce71a1545f6e33164230f0e5d6ece0acaa7 | [
"MIT"
] | null | null | null | // Copyright (c) 2021 Tom Hancocks
//
// 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 <kdl/schema/resource_type/resource_field.hpp>
#include <kdl/schema/resource_type/resource_field_value.hpp>
// MARK: - Constructor
kdl::lib::resource_field::resource_field(const std::string& name)
: m_name(name)
{
}
kdl::lib::resource_field::resource_field(const std::shared_ptr<struct resource_field_value>& field)
: m_name(field->name()), m_values({ field })
{
}
// MARK: - Accessor
auto kdl::lib::resource_field::name() const -> std::string
{
return m_name;
}
// MARK: - Field Value Management
auto kdl::lib::resource_field::add_value(const std::shared_ptr<struct resource_field_value> &value) -> void
{
m_values.emplace_back(value);
}
auto kdl::lib::resource_field::values() const -> const std::vector<std::shared_ptr<struct resource_field_value>> &
{
return m_values;
}
| 34.357143 | 114 | 0.748441 |
f922029c60842453b1aff0f88adab5004227c320 | 2,135 | cpp | C++ | plugins/notifications/notifier.cpp | boomt1337/nitroshare-desktop | 3ab9eb4075f78cbf2ee0fb82cea66814406a2248 | [
"MIT"
] | 1,460 | 2015-01-31T14:09:18.000Z | 2022-03-24T09:43:19.000Z | plugins/notifications/notifier.cpp | boomt1337/nitroshare-desktop | 3ab9eb4075f78cbf2ee0fb82cea66814406a2248 | [
"MIT"
] | 254 | 2015-01-29T19:58:28.000Z | 2022-03-30T01:00:38.000Z | plugins/notifications/notifier.cpp | boomt1337/nitroshare-desktop | 3ab9eb4075f78cbf2ee0fb82cea66814406a2248 | [
"MIT"
] | 245 | 2015-02-18T16:40:52.000Z | 2022-03-29T18:38:45.000Z | /*
* The MIT License (MIT)
*
* Copyright (c) 2018 Nathan Osman
*
* 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 <nitroshare/action.h>
#include <nitroshare/actionregistry.h>
#include <nitroshare/application.h>
#include <nitroshare/logger.h>
#include <nitroshare/message.h>
#include "notifier.h"
const QString MessageTag = "mdns";
const QString ShowTrayNotificationAction = "showtraynotification";
Notifier::Notifier(Application *application)
: mApplication(application)
{
}
void Notifier::showNotification(const QString &actionName, const QString &title, const QString &message)
{
// Find the action for showing the tray notification
Action *action = mApplication->actionRegistry()->find(actionName);
if (!action) {
mApplication->logger()->log(new Message(
Message::Warning,
MessageTag,
QString("\"%1\" action was not found").arg(actionName)
));
return;
}
// Invoke the action to show the notification
action->invoke(QVariantMap{
{ "title", title },
{ "message", message }
});
}
| 35 | 104 | 0.717564 |
f9240d7d91ab4d35253d601837acf6a1707a1799 | 500 | cpp | C++ | lib/stringManipulation/src/string_manipulation.cpp | Xav83/AdventOfCode | 7e305b89abe0a497efdab0f1a3bfe2bfc24b36d5 | [
"MIT"
] | 2 | 2019-11-14T18:11:02.000Z | 2020-01-20T22:40:31.000Z | lib/stringManipulation/src/string_manipulation.cpp | Xav83/AdventOfCode | 7e305b89abe0a497efdab0f1a3bfe2bfc24b36d5 | [
"MIT"
] | null | null | null | lib/stringManipulation/src/string_manipulation.cpp | Xav83/AdventOfCode | 7e305b89abe0a497efdab0f1a3bfe2bfc24b36d5 | [
"MIT"
] | null | null | null | #include <functional>
#include <sstream>
void foreachElementsInStringDelimitedBy(
const std::string &input, const char delimiter,
std::function<void(const std::string &)> callback) {
std::stringstream ss(input);
std::string token;
while (std::getline(ss, token, delimiter)) {
callback(token);
}
}
void foreachLineIn(const std::string &input,
std::function<void(const std::string &)> callback) {
foreachElementsInStringDelimitedBy(input, '\n', callback);
}
| 26.315789 | 71 | 0.688 |
f924414c965b39dcf3af5eabf4ac9a247dbad819 | 31,268 | cpp | C++ | unittests/test.cpp | attcs/TreeNode | 1728cc3a1c605e17c328a27c12de5aa685f80fc1 | [
"MIT"
] | null | null | null | unittests/test.cpp | attcs/TreeNode | 1728cc3a1c605e17c328a27c12de5aa685f80fc1 | [
"MIT"
] | null | null | null | unittests/test.cpp | attcs/TreeNode | 1728cc3a1c605e17c328a27c12de5aa685f80fc1 | [
"MIT"
] | null | null | null | #include "pch.h"
#include <memory>
#include "../treenode.h"
#include <vector>
#if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L)
#include <execution>
#endif
struct DbEntity
{
int val = 0;
};
bool operator==(DbEntity const& l, DbEntity const& r)
{
return l.val == r.val;
}
namespace TreeNodeTests
{
using namespace std;
TEST(TreeNode, add_child_parent_eq)
{
TreeNode<DbEntity> root;
auto const node = root.add_child(DbEntity{ 1 });
EXPECT_EQ(&root, node->parent());
}
TEST(TreeNode, get_1)
{
TreeNode<DbEntity> root;
auto const node = root.add_child(DbEntity{ 1 });
EXPECT_EQ(1, node->get().val);
}
TEST(TreeNode, add_child_1child_PrevIsNull)
{
TreeNode<DbEntity> root;
auto const node = root.add_child(DbEntity{ 1 });
EXPECT_EQ(nullptr, node->prev());
}
TEST(TreeNode, add_child_1child_NextIsNull)
{
TreeNode<DbEntity> root;
auto const node = root.add_child(DbEntity{ 1 });
EXPECT_EQ(nullptr, node->next());
}
TEST(TreeNode, add_child_1child_next_bfsIsNullAndNode)
{
TreeNode<DbEntity> root;
auto const node = root.add_child(DbEntity{ 1 });
EXPECT_EQ(nullptr, node->next_bfs());
EXPECT_EQ(node, root.next_bfs());
}
TEST(TreeNode, add_child_2child_PrevNextParent)
{
TreeNode<DbEntity> root;
auto const node1 = root.add_child(DbEntity{ 1 });
auto const node2 = root.add_child(DbEntity{ 2 });
EXPECT_EQ(1, node1->get().val);
EXPECT_EQ(2, node2->get().val);
EXPECT_EQ(&root, node1->parent());
EXPECT_EQ(&root, node2->parent());
EXPECT_EQ(nullptr, node1->prev());
EXPECT_EQ(node2, node1->next());
EXPECT_EQ(nullptr, node2->next());
}
TEST(TreeNode, add_child_2child_parentIsRoot)
{
TreeNode<DbEntity> root;
auto const node1 = root.add_child(DbEntity{ 1 });
auto const node2 = root.add_child(DbEntity{ 2 });
EXPECT_EQ(&root, node1->parent());
EXPECT_EQ(&root, node2->parent());
}
TEST(TreeNode, add_child_2child_valsAreOk)
{
TreeNode<DbEntity> root;
auto const node1 = root.add_child(DbEntity{ 1 });
auto const node2 = root.add_child(DbEntity{ 2 });
EXPECT_EQ(1, node1->get().val);
EXPECT_EQ(2, node2->get().val);
}
TEST(TreeNode, add_child_2child_prevAndnextAreOk)
{
TreeNode<DbEntity> root;
auto const node1 = root.add_child(DbEntity{ 1 });
auto const node2 = root.add_child(DbEntity{ 2 });
EXPECT_EQ(nullptr, node1->prev());
EXPECT_EQ(node2, node1->next());
EXPECT_EQ(nullptr, node2->next());
}
TEST(TreeNode, add_child_2child_next_bfsIsOk)
{
TreeNode<DbEntity> root;
auto const node1 = root.add_child(DbEntity{ 1 });
auto const node2 = root.add_child(DbEntity{ 2 });
EXPECT_EQ(node1, root.next_bfs());
EXPECT_EQ(node2, node1->next_bfs());
EXPECT_EQ(nullptr, node2->next_bfs());
}
TEST(TreeNode, add_child_2child1grandchild1_bfsOk)
{
TreeNode<DbEntity> root;
auto child1 = root.add_child(DbEntity{ 1 });
auto child2 = root.add_child(DbEntity{ 2 });
auto grandchild11 = child1->add_child(DbEntity{ 11 });
EXPECT_EQ(child2, child1->next_bfs());
EXPECT_EQ(grandchild11, child2->next_bfs());
EXPECT_EQ(nullptr, grandchild11->next_bfs());
}
TEST(TreeNode, add_child_2child1grandchild2_bfsOk)
{
TreeNode<DbEntity> root;
auto child1 = root.add_child(DbEntity{ 1 });
auto child2 = root.add_child(DbEntity{ 2 });
auto grandchild21 = child2->add_child(DbEntity{ 21 });
EXPECT_EQ(child2, child1->next_bfs());
EXPECT_EQ(grandchild21, child2->next_bfs());
EXPECT_EQ(nullptr, grandchild21->next_bfs());
}
TEST(TreeNode, add_child_2child2grandchildInOrder_bfsOk)
{
TreeNode<DbEntity> root;
auto child1 = root.add_child(DbEntity{ 1 });
auto child2 = root.add_child(DbEntity{ 2 });
auto grandchild11 = child1->add_child(DbEntity{ 11 });
auto grandchild21 = child2->add_child(DbEntity{ 21 });
EXPECT_EQ(child2, child1->next_bfs());
EXPECT_EQ(grandchild11, child2->next_bfs());
EXPECT_EQ(grandchild21, grandchild11->next_bfs());
EXPECT_EQ(nullptr, grandchild21->next_bfs());
}
TEST(TreeNode, add_child_2child2grandchildInReverseOrder_bfsOk)
{
TreeNode<DbEntity> root;
auto child1 = root.add_child(DbEntity{ 1 });
auto child2 = root.add_child(DbEntity{ 2 });
auto grandchild21 = child2->add_child(DbEntity{ 21 });
auto grandchild11 = child1->add_child(DbEntity{ 11 });
EXPECT_EQ(child2, child1->next_bfs());
EXPECT_EQ(grandchild11, child2->next_bfs());
EXPECT_EQ(grandchild21, grandchild11->next_bfs());
EXPECT_EQ(nullptr, grandchild21->next_bfs());
}
TEST(TreeNode, add_child_3child2grandchildInOrder_bfsOk)
{
TreeNode<DbEntity> root;
auto child1 = root.add_child(DbEntity{ 1 });
auto child2 = root.add_child(DbEntity{ 2 });
auto child3 = root.add_child(DbEntity{ 3 });
auto grandchild11 = child1->add_child(DbEntity{ 11 });
auto grandchild31 = child3->add_child(DbEntity{ 31 });
EXPECT_EQ(child2, child1->next_bfs());
EXPECT_EQ(child3, child2->next_bfs());
EXPECT_EQ(grandchild11, child3->next_bfs());
EXPECT_EQ(grandchild31, grandchild11->next_bfs());
EXPECT_EQ(nullptr, grandchild31->next_bfs());
EXPECT_EQ(6, root.size());
EXPECT_EQ(2, child3->size());
}
TEST(TreeNode, add_child_3child2grandchild3Atlast_bfsOk)
{
TreeNode<DbEntity> root;
auto child1 = root.add_child(DbEntity{ 1 });
auto child2 = root.add_child(DbEntity{ 2 });
auto grandchild11 = child1->add_child(DbEntity{ 11 });
auto child3 = root.add_child(DbEntity{ 3 });
auto grandchild31 = child3->add_child(DbEntity{ 31 });
EXPECT_EQ(child2, child1->next_bfs());
EXPECT_EQ(child3, child2->next_bfs());
EXPECT_EQ(grandchild11, child3->next_bfs());
EXPECT_EQ(grandchild31, grandchild11->next_bfs());
EXPECT_EQ(nullptr, grandchild31->next_bfs());
}
TEST(TreeNode, add_child_3child3grandchild_bfsOk)
{
TreeNode<DbEntity> root;
auto child1 = root.add_child(DbEntity{ 1 });
auto child2 = root.add_child(DbEntity{ 2 });
auto child3 = root.add_child(DbEntity{ 3 });
auto grandchild11 = child1->add_child(DbEntity{ 11 });
auto grandchild12 = child1->add_child(DbEntity{ 12 });
auto grandchild31 = child3->add_child(DbEntity{ 31 });
EXPECT_EQ(child2, child1->next_bfs());
EXPECT_EQ(child3, child2->next_bfs());
EXPECT_EQ(grandchild11, child3->next_bfs());
EXPECT_EQ(grandchild12, grandchild11->next_bfs());
EXPECT_EQ(grandchild31, grandchild12->next_bfs());
EXPECT_EQ(nullptr, grandchild31->next_bfs());
EXPECT_EQ(7, root.size());
EXPECT_EQ(3, child1->size());
}
TEST(TreeNode, add_child_3child3grandchild3Atlast_bfsOk)
{
TreeNode<DbEntity> root;
auto child1 = root.add_child(DbEntity{ 1 });
auto child2 = root.add_child(DbEntity{ 2 });
auto grandchild11 = child1->add_child(DbEntity{ 11 });
auto grandchild12 = child1->add_child(DbEntity{ 12 });
auto child3 = root.add_child(DbEntity{ 3 });
auto grandchild31 = child3->add_child(DbEntity{ 31 });
EXPECT_EQ(child2, child1->next_bfs());
EXPECT_EQ(child3, child2->next_bfs());
EXPECT_EQ(grandchild11, child3->next_bfs());
EXPECT_EQ(grandchild12, grandchild11->next_bfs());
EXPECT_EQ(grandchild31, grandchild12->next_bfs());
EXPECT_EQ(nullptr, grandchild31->next_bfs());
}
TEST(TreeNode, add_child_3_3_1_111_bfsOk)
{
TreeNode<DbEntity> root;
auto c1 = root.add_child(DbEntity{ 1 });
auto c2 = root.add_child(DbEntity{ 2 });
auto c3 = root.add_child(DbEntity{ 3 });
auto c11 = c1->add_child(DbEntity{ 11 });
auto c12 = c1->add_child(DbEntity{ 12 });
auto c31 = c3->add_child(DbEntity{ 31 });
auto c111 = c11->add_child(DbEntity{ 111 });
EXPECT_EQ(c2, c1->next_bfs());
EXPECT_EQ(c3, c2->next_bfs());
EXPECT_EQ(c11, c3->next_bfs());
EXPECT_EQ(c12, c11->next_bfs());
EXPECT_EQ(c31, c12->next_bfs());
EXPECT_EQ(c111, c31->next_bfs());
EXPECT_EQ(nullptr, c111->next_bfs());
}
TEST(TreeNode, add_child_3_3_1_111_r_bfsOk)
{
TreeNode<DbEntity> root;
auto c1 = root.add_child(DbEntity{ 1 });
auto c2 = root.add_child(DbEntity{ 2 });
auto c11 = c1->add_child(DbEntity{ 11 });
auto c12 = c1->add_child(DbEntity{ 12 });
auto c111 = c11->add_child(DbEntity{ 111 });
auto c3 = root.add_child(DbEntity{ 3 });
auto c31 = c3->add_child(DbEntity{ 31 });
EXPECT_EQ(c2, c1->next_bfs());
EXPECT_EQ(c3, c2->next_bfs());
EXPECT_EQ(c11, c3->next_bfs());
EXPECT_EQ(c12, c11->next_bfs());
EXPECT_EQ(c31, c12->next_bfs());
EXPECT_EQ(c111, c31->next_bfs());
EXPECT_EQ(nullptr, c111->next_bfs());
}
TEST(TreeNode, add_child_3_3_1_121_bfsOk)
{
TreeNode<DbEntity> root;
auto c1 = root.add_child(DbEntity{ 1 });
auto c2 = root.add_child(DbEntity{ 2 });
auto c3 = root.add_child(DbEntity{ 3 });
auto c11 = c1->add_child(DbEntity{ 11 });
auto c12 = c1->add_child(DbEntity{ 12 });
auto c31 = c3->add_child(DbEntity{ 31 });
auto c121 = c12->add_child(DbEntity{ 121 });
EXPECT_EQ(c2, c1->next_bfs());
EXPECT_EQ(c3, c2->next_bfs());
EXPECT_EQ(c11, c3->next_bfs());
EXPECT_EQ(c12, c11->next_bfs());
EXPECT_EQ(c31, c12->next_bfs());
EXPECT_EQ(c121, c31->next_bfs());
EXPECT_EQ(nullptr, c121->next_bfs());
}
TEST(TreeNode, add_child_3_3_1_121_r_bfsOk)
{
TreeNode<DbEntity> root;
auto c1 = root.add_child(DbEntity{ 1 });
auto c2 = root.add_child(DbEntity{ 2 });
auto c3 = root.add_child(DbEntity{ 3 });
auto c11 = c1->add_child(DbEntity{ 11 });
auto c12 = c1->add_child(DbEntity{ 12 });
auto c121 = c12->add_child(DbEntity{ 121 });
auto c31 = c3->add_child(DbEntity{ 31 });
EXPECT_EQ(c2, c1->next_bfs());
EXPECT_EQ(c3, c2->next_bfs());
EXPECT_EQ(c11, c3->next_bfs());
EXPECT_EQ(c12, c11->next_bfs());
EXPECT_EQ(c31, c12->next_bfs());
EXPECT_EQ(c121, c31->next_bfs());
EXPECT_EQ(nullptr, c121->next_bfs());
}
TEST(TreeNode, add_child_3_3_1_131_bfsOk)
{
TreeNode<DbEntity> root;
auto c1 = root.add_child(DbEntity{ 1 });
auto c2 = root.add_child(DbEntity{ 2 });
auto c3 = root.add_child(DbEntity{ 3 });
auto c11 = c1->add_child(DbEntity{ 11 });
auto c12 = c1->add_child(DbEntity{ 12 });
auto c31 = c3->add_child(DbEntity{ 31 });
auto c131 = c31->add_child(DbEntity{ 131 });
EXPECT_EQ(c2, c1->next_bfs());
EXPECT_EQ(c3, c2->next_bfs());
EXPECT_EQ(c11, c3->next_bfs());
EXPECT_EQ(c12, c11->next_bfs());
EXPECT_EQ(c31, c12->next_bfs());
EXPECT_EQ(c131, c31->next_bfs());
EXPECT_EQ(nullptr, c131->next_bfs());
}
TEST(TreeNode, add_child_3_3_1_211_131_bfsOk)
{
TreeNode<DbEntity> root;
auto c1 = root.add_child(DbEntity{ 1 });
auto c2 = root.add_child(DbEntity{ 2 });
auto c21 = c2->add_child(DbEntity{ 21 });
auto c211 = c21->add_child(DbEntity{ 211 });
auto c212 = c21->add_child(DbEntity{ 212 });
auto c3 = root.add_child(DbEntity{ 3 });
auto c11 = c1->add_child(DbEntity{ 11 });
auto c12 = c1->add_child(DbEntity{ 12 });
auto c31 = c3->add_child(DbEntity{ 31 });
auto c131 = c31->add_child(DbEntity{ 131 });
EXPECT_EQ(c2, c1->next_bfs());
EXPECT_EQ(c3, c2->next_bfs());
EXPECT_EQ(c11, c3->next_bfs());
EXPECT_EQ(c12, c11->next_bfs());
EXPECT_EQ(c21, c12->next_bfs());
EXPECT_EQ(c31, c21->next_bfs());
EXPECT_EQ(c211, c31->next_bfs());
EXPECT_EQ(c212, c211->next_bfs());
EXPECT_EQ(c131, c212->next_bfs());
EXPECT_EQ(nullptr, c131->next_bfs());
EXPECT_EQ(11, root.size());
EXPECT_EQ(3, c3->size());
EXPECT_EQ(1, c3->size_segment());
}
TEST(TreeNode, child_begin_in_depth__empty__0__root)
{
TreeNode<int> root(0);
auto node = root.child_begin_in_depth(0);
EXPECT_EQ(&root, node);
}
TEST(TreeNode, child_begin_in_depth__2level__0__root)
{
TreeNode<int> root(0);
auto c1 = root.add_child(1);
auto c2 = root.add_child(2);
auto c11 = c1->add_child(11);
auto node = root.child_begin_in_depth(0);
EXPECT_EQ(&root, node);
}
TEST(TreeNode, child_begin_in_depth__2level__1__c1)
{
TreeNode<int> root(0);
auto c1 = root.add_child(1);
auto c2 = root.add_child(2);
auto c11 = c1->add_child(11);
auto node = root.child_begin_in_depth(1);
EXPECT_EQ(c1, node);
}
TEST(TreeNode, child_begin_in_depth__2level__2__c11)
{
TreeNode<int> root(0);
auto c1 = root.add_child(1);
auto c2 = root.add_child(2);
auto c11 = c1->add_child(11);
auto node = root.child_begin_in_depth(2);
EXPECT_EQ(c11, node);
}
TEST(TreeNode, child_begin_in_depth__2level__2__c21)
{
TreeNode<int> root(0);
auto c1 = root.add_child(1);
auto c2 = root.add_child(2);
auto c21 = c2->add_child(21);
auto node = root.child_begin_in_depth(2);
EXPECT_EQ(c21, node);
}
TEST(TreeNode, child_begin_in_depth__3level__3__c211)
{
TreeNode<int> root(0);
auto c1 = root.add_child(1);
auto c2 = root.add_child(2);
auto c21 = c2->add_child(21);
auto c211 = c21->add_child(211);
auto node = root.child_begin_in_depth(3);
EXPECT_EQ(c211, node);
}
TEST(TreeNode, child_begin_in_depth__3level__4__null)
{
TreeNode<int> root(0);
auto c1 = root.add_child(1);
auto c2 = root.add_child(2);
auto c21 = c2->add_child(21);
auto c211 = c21->add_child(211);
auto node = root.child_begin_in_depth(4);
EXPECT_EQ(nullptr, node);
}
TEST(TreeNode, child_end_in_depth__empty__0__null)
{
TreeNode<int> root(0);
auto node = root.child_end_in_depth(0);
EXPECT_EQ(nullptr, node);
}
TEST(TreeNode, child_end_in_depth__2level__0__c1)
{
TreeNode<int> root(0);
auto c1 = root.add_child(1);
auto c2 = root.add_child(2);
auto c11 = c1->add_child(11);
auto node = root.child_end_in_depth(0);
EXPECT_EQ(c1, node);
}
TEST(TreeNode, child_end_in_depth__2level__1__c11)
{
TreeNode<int> root(0);
auto c1 = root.add_child(1);
auto c2 = root.add_child(2);
auto c11 = c1->add_child(11);
auto node = root.child_end_in_depth(1);
EXPECT_EQ(c11, node);
}
TEST(TreeNode, child_end_in_depth__2level11__2__null)
{
TreeNode<int> root(0);
auto c1 = root.add_child(1);
auto c2 = root.add_child(2);
auto c11 = c1->add_child(11);
auto node = root.child_end_in_depth(2);
EXPECT_EQ(nullptr, node);
}
TEST(TreeNode, child_end_in_depth__2level21__2__null)
{
TreeNode<int> root(0);
auto c1 = root.add_child(1);
auto c2 = root.add_child(2);
auto c21 = c2->add_child(21);
auto node = root.child_end_in_depth(2);
EXPECT_EQ(nullptr, node);
}
TEST(TreeNode, child_end_in_depth__3level__2__c211)
{
TreeNode<int> root(0);
auto c1 = root.add_child(1);
auto c2 = root.add_child(2);
auto c21 = c2->add_child(21);
auto c211 = c21->add_child(211);
auto node = root.child_end_in_depth(2);
EXPECT_EQ(c211, node);
}
TEST(TreeNode, child_end_in_depth__3level__4__null)
{
TreeNode<int> root(0);
auto c1 = root.add_child(1);
auto c2 = root.add_child(2);
auto c21 = c2->add_child(21);
auto c211 = c21->add_child(211);
auto node = root.child_end_in_depth(4);
EXPECT_EQ(nullptr, node);
}
TEST(TreeNode, clear_root_DoesNothing)
{
TreeNode<int> root(0);
root.clear();
EXPECT_EQ(0, root.get());
EXPECT_EQ(nullptr, root.child_first());
EXPECT_EQ(nullptr, root.next());
}
TEST(TreeNode, clear_root_ChildsAreNull)
{
TreeNode<int> root(0);
root.add_child(1)->add_child(11);
root.add_child(2);
root.add_child(3);
root.clear();
EXPECT_EQ(nullptr, root.child_first());
EXPECT_EQ(nullptr, root.child_last());
EXPECT_EQ(1, root.size());
}
TEST(TreeNode, clear_c21_complex)
{
TreeNode<int> root(0);
auto c1 = root.add_child(1);
c1->add_child(11)
->add_child(111)
->parent()
->add_child(112)
->parent()
->add_child(113)
->add_child(1131)
->add_child(11311);
auto c21 = root.add_child(2)
->add_child(21);
c21->add_child(211)
->add_child(2111);
c21->add_child(212)
->add_child(2121);
c21->add_child(213)
->add_child(2131);
root.add_child(3);
vector<int> vals_before;
copy(root.begin(), root.end(), back_inserter(vals_before));
vector<int> const expected_before = { 0, 1, 2, 3, 11, 21, 111, 112, 113, 211, 212, 213, 1131, 2111, 2121, 2131, 11311 };
EXPECT_EQ(expected_before, vals_before);
c21->clear();
vector<int> vals_after;
copy(root.begin(), root.end(), back_inserter(vals_after));
vector<int> const expected_after = { 0, 1, 2, 3, 11, 21, 111, 112, 113, 1131, 11311 };
EXPECT_EQ(expected_after, vals_after);
EXPECT_EQ(11, root.size());
EXPECT_EQ(7, c1->size());
}
TEST(TreeNode, remove_c21_1level)
{
TreeNode<int> root(0);
root.add_child(1);
auto c2 = root.add_child(2);
root.add_child(3);
c2->remove();
vector<int> vals;
copy(root.begin(), root.end(), back_inserter(vals));
vector<int> expected = { 0, 1, 3 };
EXPECT_EQ(expected, vals);
EXPECT_EQ(3, root.size());
}
TEST(TreeNode, remove_c21_complex)
{
TreeNode<int> root(0);
root.add_child(1)
->add_child(11)
->add_child(111)
->parent()
->add_child(112)
->parent()
->add_child(113)
->add_child(1131)
->add_child(11311);
auto c2 = root.add_child(2);
auto c21 = c2->add_child(21);
c21->add_child(211)
->add_child(2111);
c21->add_child(212)
->add_child(2121);
c21->add_child(213)
->add_child(2131);
root.add_child(3);
vector<int> vals_before;
copy(root.begin(), root.end(), back_inserter(vals_before));
vector<int> const expected_before = { 0, 1, 2, 3, 11, 21, 111, 112, 113, 211, 212, 213, 1131, 2111, 2121, 2131, 11311 };
EXPECT_EQ(expected_before, vals_before);
c21->remove();
vector<int> vals_after;
copy(root.begin(), root.end(), back_inserter(vals_after));
vector<int> const expected_after = { 0, 1, 2, 3, 11, 111, 112, 113, 1131, 11311 };
EXPECT_EQ(expected_after, vals_after);
EXPECT_EQ(10, root.size());
EXPECT_EQ(1, c2->size());
}
TEST(TreeNode, begin_segment_const_ShouldCompile)
{
TreeNode<int> const root;
root.begin_segment();
}
TEST(TreeNode, end_segment_const_ShouldCompile)
{
TreeNode<int> const root;
root.end_segment();
}
TEST(TreeNode, begin_segment_nodeptr_const_ShouldCompile)
{
TreeNode<int> const root;
root.begin_segment<TreeNode<int> const*>();
}
TEST(TreeNode, end_segment_nodeptr_const_ShouldCompile)
{
TreeNode<int> const root;
root.end_segment<TreeNode<int> const*>();
}
TEST(TreeNode, begin_dfs_const_ShouldCompile)
{
TreeNode<int> const root;
root.begin_dfs();
}
TEST(TreeNode, end_dfs_const_ShouldCompile)
{
TreeNode<int> const root;
root.end_dfs();
}
TEST(TreeNode, begin_dfs_nodeptr_const_ShouldCompile)
{
TreeNode<int> const root;
root.begin_dfs<TreeNode<int> const*>();
}
TEST(TreeNode, end_dfs_nodeptr_const_ShouldCompile)
{
TreeNode<int> const root;
root.end_dfs<TreeNode<int> const*>();
}
TEST(TreeNode, begin_bfs_const_ShouldCompile)
{
TreeNode<int> const root;
root.begin_bfs();
}
TEST(TreeNode, end_bfs_const_ShouldCompile)
{
TreeNode<int> const root;
root.end_bfs();
}
TEST(TreeNode, begin_bfs_nodeptr_const_ShouldCompile)
{
TreeNode<int> const root;
root.begin_bfs<TreeNode<int> const*>();
}
TEST(TreeNode, end_bfs_nodeptr_const_ShouldCompile)
{
TreeNode<int> const root;
root.end_bfs<TreeNode<int> const*>();
}
TEST(TreeNode, begin_const_ShouldCompile)
{
TreeNode<int> const root;
root.begin();
}
TEST(TreeNode, end_const_ShouldCompile)
{
TreeNode<int> const root;
root.end();
}
TEST(TreeNode, copyctor)
{
TreeNode<int> root(0);
auto c11o = root.add_child(1)->add_child(11);
root.add_child(2);
root.add_child(3);
auto root_copied(root);
EXPECT_EQ(0, root_copied.get());
auto c1 = root_copied.next_bfs();
EXPECT_EQ(1, c1->get());
auto c2 = c1->next_bfs();
EXPECT_EQ(2, c2->get());
auto c3 = c2->next_bfs();
EXPECT_EQ(3, c3->get());
auto c11 = c3->next_bfs();
EXPECT_EQ(11, c11->get());
EXPECT_EQ(c11, c1->child_first());
EXPECT_NE(c11, c11o);
}
TEST(TreeNode, initializerlist)
{
TreeNode<int> root = { 0, 1, 2, 3};
EXPECT_EQ(0, root.get());
auto c1 = root.next_bfs();
EXPECT_EQ(1, c1->get());
auto c2 = c1->next_bfs();
EXPECT_EQ(2, c2->get());
auto c3 = c2->next_bfs();
EXPECT_EQ(3, c3->get());
}
TEST(TreeNode, foreach)
{
TreeNode<int> root = { 0, 1, 2, 3 };
auto c11 = root.child_first()->add_child(4);
c11->add_child(5);
int i = 0;
for (auto v : root)
EXPECT_EQ(i++, v);
}
}
namespace IteratorSegmentTests
{
using namespace std;
TEST(IteratorSegment, begin_segment_RootEmptySg_Null)
{
TreeNode<DbEntity> root;
EXPECT_EQ(IteratorSegment<DbEntity>(nullptr), root.begin_segment());
}
TEST(IteratorSegment, end_segment_RootEmptySg_Null)
{
TreeNode<DbEntity> root;
EXPECT_EQ(IteratorSegment<DbEntity>(nullptr), root.end_segment());
}
TEST(IteratorSegment, begin_segment_1Child_Is1)
{
TreeNode<DbEntity> root;
auto const node = root.add_child(DbEntity{ 1 });
EXPECT_EQ(node->get().val, (*root.begin_segment()).val);
}
TEST(IteratorSegment, end_segment_1Child_IsNull)
{
TreeNode<DbEntity> root;
auto const node = root.add_child(DbEntity{ 1 });
EXPECT_EQ(IteratorSegment<DbEntity>(nullptr), root.end_segment());
}
TEST(IteratorSegment, pointer_operator_T)
{
TreeNode<DbEntity> root;
auto const node = root.add_child(DbEntity{ 1 });
EXPECT_EQ(node->get().val, root.begin_segment()->val);
}
TEST(IteratorSegment, usability_copy_value123)
{
TreeNode<DbEntity> root;
root.add_child(DbEntity{ 1 });
root.add_child(DbEntity{ 2 });
root.add_child(DbEntity{ 3 });
vector<DbEntity> vals;
copy(root.begin_segment(), root.end_segment(), back_inserter(vals));
auto const expected = vector<DbEntity>{ DbEntity{1}, DbEntity{2}, DbEntity{3} };
EXPECT_EQ(expected, vals);
}
TEST(IteratorSegment, usability_copy_node123)
{
TreeNode<DbEntity> root;
auto node1 = root.add_child(DbEntity{ 1 });
auto node2 = root.add_child(DbEntity{ 2 });
auto node3 = root.add_child(DbEntity{ 3 });
vector<TreeNode<DbEntity>*> vals;
copy(root.begin_segment<TreeNode<DbEntity>*>(), root.end_segment<TreeNode<DbEntity>*>(), back_inserter(vals));
auto const expected = vector<TreeNode<DbEntity>*>{ node1, node2, node3 };
EXPECT_EQ(expected, vals);
}
#if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L)
TEST(IteratorSegment, usability_copy_par_val10)
{
constexpr int n = 10;
TreeNode<DbEntity> root;
vector<DbEntity> expected;
for (int i = 0; i < n; ++i)
root.add_child(expected.emplace_back(DbEntity{ i + 1 }));
vector<DbEntity> vals(n);
copy(execution::par_unseq, root.begin_segment(), root.end_segment(), vals.begin());
EXPECT_EQ(expected, vals);
}
#endif
}
namespace IteratorDepthFirstSearchTests
{
using namespace std;
TEST(IteratorDfs, order_copy_value0)
{
TreeNode<int> root(0);
vector<int> vals;
copy(root.begin_dfs(), root.end_dfs(), back_inserter(vals));
auto const expected = vector<int>{ 0 };
EXPECT_EQ(expected, vals);
}
TEST(IteratorDfs, order_copy_value0123)
{
TreeNode<int> root;
root.add_child(1);
root.add_child(2);
root.add_child(3);
vector<int> vals;
copy(root.begin_dfs(), root.end_dfs(), back_inserter(vals));
auto const expected = vector<int>{ 0, 1, 2, 3};
EXPECT_EQ(expected, vals);
}
TEST(IteratorDfs, order_copy_value011123)
{
TreeNode<int> root;
auto n1 = root.add_child(1);
auto n2 = root.add_child(2);
auto n3 = root.add_child(3);
n1->add_child(11);
vector<int> vals;
copy(root.begin_dfs(), root.end_dfs(), back_inserter(vals));
auto const expected = vector<int>{ 0, 1, 11, 2, 3 };
EXPECT_EQ(expected, vals);
}
TEST(IteratorDfs, order_copy_value012213)
{
TreeNode<int> root;
root.add_child(1);
root.add_child(2)
->add_child(21);
root.add_child(3);
vector<int> vals;
copy(root.begin_dfs(), root.end_dfs(), back_inserter(vals));
auto const expected = vector<int>{ 0, 1, 2, 21, 3 };
EXPECT_EQ(expected, vals);
}
TEST(IteratorDfs, order_copy_value012331)
{
TreeNode<int> root;
root.add_child(1);
root.add_child(2);
root.add_child(3)
->add_child(31);
vector<int> vals;
copy(root.begin_dfs(), root.end_dfs(), back_inserter(vals));
auto const expected = vector<int>{ 0, 1, 2, 3, 31 };
EXPECT_EQ(expected, vals);
}
TEST(IteratorDfs, order_copy_value01112331)
{
TreeNode<int> root;
root.add_child(1)
->add_child(11);
root.add_child(2);
root.add_child(3)
->add_child(31);
vector<int> vals;
copy(root.begin_dfs(), root.end_dfs(), back_inserter(vals));
auto const expected = vector<int>{ 0, 1, 11, 2, 3, 31 };
EXPECT_EQ(expected, vals);
}
TEST(IteratorDfs, order_copy_value011111123)
{
TreeNode<int> root;
root.add_child(1)
->add_child(11)
->add_child(111);
root.add_child(2);
root.add_child(3);
vector<int> vals;
copy(root.begin_dfs(), root.end_dfs(), back_inserter(vals));
auto const expected = vector<int>{ 0, 1, 11, 111, 2, 3 };
EXPECT_EQ(expected, vals);
}
TEST(IteratorDfs, order_copy_value01111112212113)
{
TreeNode<int> root;
root.add_child(1)
->add_child(11)
->add_child(111);
auto n2 = root.add_child(2)
->add_child(21)
->add_child(211);
auto n3 = root.add_child(3);
vector<int> vals;
copy(root.begin_dfs(), root.end_dfs(), back_inserter(vals));
auto const expected = vector<int>{ 0, 1, 11, 111, 2, 21, 211, 3 };
EXPECT_EQ(expected, vals);
}
TEST(StepManagerDfs, next_1_null)
{
TreeNode<int> root;
TreeNode<int>* node = &root;
StepManagerDfs::next<TreeNode<int>>(node);
EXPECT_EQ(nullptr, node);
}
TEST(StepManagerDfs, prev_1_null)
{
TreeNode<int> root;
TreeNode<int>* node = &root;
StepManagerDfs::prev<TreeNode<int>>(node);
EXPECT_EQ(nullptr, node);
}
TEST(StepManagerDfs, next_parent_child)
{
TreeNode<int> root(0);
auto node = &root;
auto ch = root.add_child(1);
StepManagerDfs::next<TreeNode<int>>(node);
EXPECT_EQ(ch, node);
}
TEST(StepManagerDfs, prev_parent_child)
{
TreeNode<int> root(0);
auto c1 = root.add_child(1);
auto node = c1;
StepManagerDfs::prev<TreeNode<int>>(node);
EXPECT_EQ(&root, node);
}
TEST(StepManagerDfs, next_neighbour)
{
TreeNode<int> root(0);
auto c1 = root.add_child(1);
auto c2 = root.add_child(2);
auto node = c1;
StepManagerDfs::next<TreeNode<int>>(node);
EXPECT_EQ(c2, node);
}
TEST(StepManagerDfs, prev_neighbour)
{
TreeNode<int> root(0);
auto c1 = root.add_child(1);
auto c2 = root.add_child(2);
auto node = c2;
StepManagerDfs::prev<TreeNode<int>>(node);
EXPECT_EQ(c1, node);
}
TEST(StepManagerDfs, next_c1111_to_c2)
{
TreeNode<int> root(0);
auto c1111 = root.add_child(1)
->add_child(11)
->add_child(111)
->add_child(1111);
auto c2 = root.add_child(2);
auto node = c1111;
StepManagerDfs::next<TreeNode<int>>(node);
EXPECT_EQ(c2, node);
}
TEST(StepManagerDfs, prev_c2_to_c1111)
{
TreeNode<int> root(0);
auto c1111 = root.add_child(1)
->add_child(11)
->add_child(111)
->add_child(1111);
auto c2 = root.add_child(2);
auto node = c2;
StepManagerDfs::prev<TreeNode<int>>(node);
EXPECT_EQ(c1111, node);
}
TEST(StepManagerDfs, next_c1111_null)
{
TreeNode<int> root(0);
auto c1111 = root.add_child(1)
->add_child(11)
->add_child(111)
->add_child(1111);
auto node = c1111;
StepManagerDfs::next<TreeNode<int>>(node);
EXPECT_EQ(nullptr, node);
}
TEST(StepManagerDfs, prev_c1111_c111)
{
TreeNode<int> root(0);
auto c111 = root.add_child(1)
->add_child(11)
->add_child(111);
auto c1111 = c111->add_child(1111);
auto node = c1111;
StepManagerDfs::prev<TreeNode<int>>(node);
EXPECT_EQ(c111, node);
}
}
namespace IteratorBreadthFirstSearchTests
{
using namespace std;
TEST(IteratorBfs, order_copy_value0)
{
TreeNode<int> root(0);
vector<int> vals;
copy(root.begin_bfs(), root.end_bfs(), back_inserter(vals));
auto const expected = vector<int>{ 0 };
EXPECT_EQ(expected, vals);
}
TEST(IteratorBfs, order_copy_value0123)
{
TreeNode<int> root;
root.add_child(1);
root.add_child(2);
root.add_child(3);
vector<int> vals;
copy(root.begin_bfs(), root.end_bfs(), back_inserter(vals));
auto const expected = vector<int>{ 0, 1, 2, 3 };
EXPECT_EQ(expected, vals);
}
TEST(IteratorBfs, order_copy_value012311212231111311)
{
TreeNode<int> root;
root.add_child(1)
->add_child(11)
->add_child(111);
auto node2 = root.add_child(2);
node2->add_child(21);
root.add_child(3)
->add_child(31)
->add_child(311);
node2->add_child(22);
vector<int> vals;
copy(root.begin_bfs(), root.end_bfs(), back_inserter(vals));
auto const expected = vector<int>{ 0, 1, 2, 3, 11, 21, 22, 31, 111, 311 };
EXPECT_EQ(expected, vals);
}
TEST(IteratorBfs, order_inrange_level23_copy_value11212231111311)
{
TreeNode<int> root;
root.add_child(1)
->add_child(11)
->add_child(111);
auto node2 = root.add_child(2);
node2->add_child(21);
root.add_child(3)
->add_child(31)
->add_child(311)
->add_child(3111);
node2->add_child(22);
vector<int> vals;
copy(root.begin_bfs(2), root.end_bfs(3), back_inserter(vals));
auto const expected = vector<int>{ 11, 21, 22, 31, 111, 311 };
EXPECT_EQ(expected, vals);
}
TEST(IteratorBfs, begin_end_const_ShouldCompile)
{
TreeNode<int> root;
root.add_child(1)
->add_child(11)
->add_child(111);
auto node2 = root.add_child(2);
node2->add_child(21);
root.add_child(3)
->add_child(31)
->add_child(311);
node2->add_child(22);
auto const& root_const = root;
vector<int> vals;
copy(root_const.begin(), root_const.end(), back_inserter(vals));
auto const expected = vector<int>{ 0, 1, 2, 3, 11, 21, 22, 31, 111, 311 };
EXPECT_EQ(expected, vals);
}
} | 24.428125 | 124 | 0.646444 |
f9244945ecec1e566af7c4149db1742b7f2ee1f7 | 469 | cpp | C++ | lcm.cpp | shu736/First | 034d0326def08fb6b104411dd3b37eb6c1e03eda | [
"MIT"
] | null | null | null | lcm.cpp | shu736/First | 034d0326def08fb6b104411dd3b37eb6c1e03eda | [
"MIT"
] | null | null | null | lcm.cpp | shu736/First | 034d0326def08fb6b104411dd3b37eb6c1e03eda | [
"MIT"
] | null | null | null | #include <stdio.h>
int lcm(int, int);
int main()
{
int a, b, result;
int prime[100];
printf("Enter two numbers: ");
scanf("%d%d", &a, &b);
result = lcm(a, b);
printf("The LCM of %d and %d is %d\n", a, b, result);
return 0;
}
int lcm(int a, int b)
{
static int common = 1;
if (common % a == 0 && common % b == 0)
{
return common;
}
common++;
lcm(a, b);
return common;
}
| 16.75 | 58 | 0.460554 |
234d42fdfc563de21241340a582b66d85721babd | 28,425 | cpp | C++ | src/j_plot.cpp | tsyw/JoSIM | c1dc2a127787a5f5f6750ef84768f30abee8dcae | [
"MIT"
] | 1 | 2020-07-25T12:15:30.000Z | 2020-07-25T12:15:30.000Z | src/j_plot.cpp | tsyw/JoSIM | c1dc2a127787a5f5f6750ef84768f30abee8dcae | [
"MIT"
] | null | null | null | src/j_plot.cpp | tsyw/JoSIM | c1dc2a127787a5f5f6750ef84768f30abee8dcae | [
"MIT"
] | null | null | null | // Copyright (c) 2018 Johannes Delport
// This code is licensed under MIT license (see LICENSE for details)
#include "j_plot.hpp"
#ifdef USING_MATPLOTLIB
namespace plt = matplotlibcpp;
#endif
/*
Determine traces to plot from the control part of the main circuit
*/
void traces_to_plot(InputFile& iFile, std::vector<std::string> controlPart, std::vector<std::string>& traceLabel, std::vector<std::vector<double>>& traceData) {
std::vector<std::string> tokens, labeltokens, nodesTokens;
std::vector<double> trace;
std::map<std::string, std::vector<double>> traces;
std::string columnLabel1, columnLabel2, label, nodesToPlot;
int index1 = -1;
int index2 = -1;
for (const auto &string : controlPart) {
/****************************************************/
/* PRINT */
/****************************************************/
if (string.find("PRINT") != std::string::npos) {
tokens = tokenize_space(string);
/* Print the identified node voltage */
/*****************************************************************************************************/
if (tokens[1] == "NODEV") {
/* If more than one node is specified */
if (tokens.size() == 4) {
/* If second node is ground */
if(tokens[3] == "0" || tokens[3] == "GND") {
label = "NODE VOLTAGE " + tokens[2];
if (tokens[2][0] == 'X') {
labeltokens = tokenize_delimeter(tokens[2], "_");
std::rotate(labeltokens.begin(), labeltokens.end() - 1, labeltokens.end());
tokens[2] = labeltokens[0];
for (int n = 1; n < labeltokens.size(); n++) {
tokens[2] = tokens[2] + "_" + labeltokens[n];
}
}
columnLabel1 = "C_NV" + tokens[2];
if (std::find(iFile.matA.columnNames.begin(), iFile.matA.columnNames.end(), columnLabel1) != iFile.matA.columnNames.end()) {
index1 = index_of(iFile.matA.columnNames, columnLabel1);
traceLabel.push_back(label);
traceData.push_back(xVect[index1]);
}
else {
/* Error this node was not found and can therefore not be printed */
plotting_errors(NO_SUCH_NODE_FOUND, tokens[2]);
}
}
/* If first node is ground */
else if (tokens[2] == "0" || tokens[3] == "GND") {
label = "NODE VOLTAGE " + tokens[3];
if (tokens[3][0] == 'X') {
labeltokens = tokenize_delimeter(tokens[3], "_");
std::rotate(labeltokens.begin(), labeltokens.end() - 1, labeltokens.end());
tokens[3] = labeltokens[0];
for (int n = 1; n < labeltokens.size(); n++) {
tokens[3] = tokens[3] + "_" + labeltokens[n];
}
}
columnLabel1 = "C_NV" + tokens[3];
if (std::find(iFile.matA.columnNames.begin(), iFile.matA.columnNames.end(), columnLabel1) != iFile.matA.columnNames.end()) {
index1 = index_of(iFile.matA.columnNames, columnLabel1);
trace.clear();
trace = xVect[index1];
std::fill(trace.begin(), trace.end(), 0.0);
std::transform(trace.begin(), trace.end(), xVect[index1].begin(), trace.begin(), std::minus<double>());
traceLabel.push_back(label);
traceData.push_back(trace);
}
else {
/* Error this node was not found and can therefore not be printed */
plotting_errors(NO_SUCH_NODE_FOUND, tokens[3]);
}
}
/* If neither are ground*/
else {
label = "NODE VOLTAGE " + tokens[2] + " to " + tokens[3];
columnLabel1 = "C_NV" + tokens[2];
columnLabel2 = "C_NV" + tokens[3];
if (tokens[2][0] == 'X') {
labeltokens = tokenize_delimeter(tokens[2], "_");
std::rotate(labeltokens.begin(), labeltokens.end() - 1, labeltokens.end());
tokens[2] = labeltokens[0];
for (int n = 1; n < labeltokens.size(); n++) {
tokens[2] = tokens[2] + "_" + labeltokens[n];
}
}
if (tokens[3][0] == 'X') {
labeltokens = tokenize_delimeter(tokens[3], "_");
std::rotate(labeltokens.begin(), labeltokens.end() - 1, labeltokens.end());
tokens[3] = labeltokens[0];
for (int n = 1; n < labeltokens.size(); n++) {
tokens[3] = tokens[3] + "_" + labeltokens[n];
}
}
if (std::find(iFile.matA.columnNames.begin(), iFile.matA.columnNames.end(), columnLabel1) != iFile.matA.columnNames.end()) {
index1 = index_of(iFile.matA.columnNames, columnLabel1);
trace.clear();
trace = xVect[index1];
if (std::find(iFile.matA.columnNames.begin(), iFile.matA.columnNames.end(), columnLabel2) != iFile.matA.columnNames.end()) {
index2 = index_of(iFile.matA.columnNames, columnLabel2);
std::transform(xVect[index1].begin(), xVect[index1].end(), xVect[index2].begin(), trace.begin(), std::minus<double>());
traceLabel.push_back(label);
traceData.push_back(trace);
}
else {
/* Error this node was not found and can therefore not be printed */
plotting_errors(NO_SUCH_NODE_FOUND, tokens[3]);
}
}
else {
/* Error this node was not found and can therefore not be printed */
plotting_errors(NO_SUCH_NODE_FOUND, tokens[2]);
}
}
}
/* If only one node is specified */
else {
label = "NODE VOLTAGE " + tokens[2];
columnLabel1 = "C_NV" + tokens[2];
if (std::find(iFile.matA.columnNames.begin(), iFile.matA.columnNames.end(), columnLabel1) != iFile.matA.columnNames.end()) {
index1 = index_of(iFile.matA.columnNames, columnLabel1);
traceLabel.push_back(label);
traceData.push_back(xVect[index1]);
}
else {
/* Error this node was not found and can therefore not be printed */
}
}
}
/* Print the identified junction phase */
/*****************************************************************************************************/
else if (tokens[1] == "PHASE") {
label = "PHASE " + tokens[2];
if (tokens[2][0] == 'X') {
labeltokens = tokenize_delimeter(tokens[2], "_");
std::rotate(labeltokens.begin(), labeltokens.end() - 1, labeltokens.end());
tokens[2] = labeltokens[0];
for (int n = 1; n < labeltokens.size(); n++) {
tokens[2] = tokens[2] + "_" + labeltokens[n];
}
}
columnLabel1 = "C_P" + tokens[2];
if (std::find(iFile.matA.columnNames.begin(), iFile.matA.columnNames.end(), columnLabel1) != iFile.matA.columnNames.end()) {
index1 = index_of(iFile.matA.columnNames, columnLabel1);
traceLabel.push_back(label);
traceData.push_back(xVect[index1]);
}
else {
/* Error this node was not found and can therefore not be printed */
plotting_errors(NO_SUCH_DEVICE_FOUND, tokens[2]);
}
}
/* Print the identified device voltage */
/*****************************************************************************************************/
else if (tokens[1] == "DEVV") {
label = "NOTHING";
if (tokens[2][0] == 'X') {
labeltokens = tokenize_delimeter(tokens[2], "_");
std::rotate(labeltokens.begin(), labeltokens.end() - 1, labeltokens.end());
tokens[2] = labeltokens[0];
for (int n = 1; n < labeltokens.size(); n++) {
tokens[2] = tokens[2] + "_" + labeltokens[n];
}
}
for (auto i : iFile.matA.elements) {
if (i.label == tokens[2]) {
trace.clear();
if (i.VPindex == -1) trace = xVect[i.VNindex];
else if (i.VNindex == -1) trace = xVect[i.VPindex];
else {
trace = xVect[i.VPindex];
std::transform(xVect[i.VPindex].begin(), xVect[i.VPindex].end(), xVect[i.VNindex].begin(), trace.begin(), std::minus<double>());
}
label = "DEVICE VOLTAGE " + i.label;
traceLabel.push_back(label);
traceData.push_back(trace);
}
}
if (label == "NOTHING") {
if (VERBOSE) plotting_errors(NO_SUCH_DEVICE_FOUND, tokens[2]);
}
}
/* Print the identified device current */
/*****************************************************************************************************/
else if (tokens[1] == "DEVI") {
label = "NOTHING";
if (tokens[2][0] == 'X') {
labeltokens = tokenize_delimeter(tokens[2], "_");
std::rotate(labeltokens.begin(), labeltokens.end() - 1, labeltokens.end());
tokens[2] = labeltokens[0];
for (int n = 1; n < labeltokens.size(); n++) {
tokens[2] = tokens[2] + "_" + labeltokens[n];
}
}
std::vector<double> trace;
for (auto i : iFile.matA.elements) {
if (i.label == tokens[2]) {
if (tokens[2][0] == 'R') {
if (i.VPindex == -1) trace = xVect[i.VNindex];
else if (i.VNindex == -1) trace = xVect[i.VPindex];
else std::transform(xVect[i.VPindex].begin(), xVect[i.VPindex].end(), xVect[i.VNindex].begin(), trace.begin(), std::minus<double>());
std::transform(trace.begin(), trace.end(), trace.begin(), std::bind(std::multiplies<double>(), std::placeholders::_1, (1/i.value)));
label = "DEVICE CURRENT " + i.label;
traceLabel.push_back(label);
traceData.push_back(trace);
}
else if (tokens[2][0] == 'C') {
}
else if (tokens[2][0] == 'L') {
if (i.CURindex == -1) simulation_errors(INDUCTOR_CURRENT_NOT_FOUND, i.label);
else trace = xVect[i.CURindex];
label = "DEVICE CURRENT " + i.label;
traceLabel.push_back(label);
traceData.push_back(trace);
}
else if (tokens[2][0] == 'I') {
label = "DEVICE CURRENT " + i.label;
traceLabel.push_back(label);
traceData.push_back(iFile.matA.sources[i.label]);
}
else if (tokens[2][0] == 'V') {
if (VERBOSE) simulation_errors(CURRENT_THROUGH_VOLTAGE_SOURCE, i.label);
}
else if (tokens[2][0] == 'B') {
trace = junctionCurrents["R_" + i.label];
label = "DEVICE CURRENT " + i.label;
traceLabel.push_back(label);
traceData.push_back(trace);
}
else plotting_errors(NO_SUCH_DEVICE_FOUND, tokens[2]);
}
}
if (label == "NOTHING") {
plotting_errors(NO_SUCH_DEVICE_FOUND, tokens[2]);
}
}
/* No such print command error thrown */
else {
if (VERBOSE) plotting_errors(NO_SUCH_PLOT_TYPE, tokens[1]);
}
}
/****************************************************/
/* PLOT */
/****************************************************/
else if (string.find("PLOT") != std::string::npos) {
tokens = tokenize_space(string);
for (int k = 1; k < tokens.size(); k++) {
/* If plotting voltage */
if(tokens[k][0] == 'V') {
/* Identify part between brackets */
nodesToPlot = tokens[k].substr(2);
nodesToPlot = nodesToPlot.substr(0, nodesToPlot.size() - 1);
/* If multiple arguments are specified for V */
if (nodesToPlot.find(',') != std::string::npos) {
nodesTokens = tokenize_delimeter(nodesToPlot, ",");
if(nodesTokens.size() > 2) {
plotting_errors(TOO_MANY_NODES, string);
}
/* Ensure node 1 is not ground */
if(nodesTokens[0] == "0" || nodesTokens[0] == "GND") {
if(nodesTokens[1] == "0" || nodesTokens[1] == "GND") {
plotting_errors(BOTH_ZERO, string);
}
else {
if (nodesTokens[1][0] == 'X') {
labeltokens = tokenize_delimeter(tokens[1], "_");
std::rotate(labeltokens.begin(), labeltokens.end() - 1, labeltokens.end());
nodesTokens[1] = labeltokens[0];
for (int n = 1; n < labeltokens.size(); n++) {
nodesTokens[1] = nodesTokens[1] + "_" + labeltokens[n];
}
}
columnLabel1 = "C_NV" + nodesTokens[1];
/* If this is a node voltage */
if (std::find(iFile.matA.columnNames.begin(), iFile.matA.columnNames.end(), columnLabel1) != iFile.matA.columnNames.end()) {
index1 = index_of(iFile.matA.columnNames, columnLabel1);
trace.clear();
trace = xVect[index1];
std::fill(trace.begin(), trace.end(), 0.0);
std::transform(trace.begin(), trace.end(), xVect[index1].begin(), trace.begin(), std::minus<double>());
traceLabel.push_back(label);
traceData.push_back(trace);
}
/* Else node not found */
else {
plotting_errors(NO_SUCH_NODE_FOUND, string);
}
}
}
/* Check if node 2 is ground */
else {
if(tokens[1] == "0" || tokens[1] == "GND") {
if (tokens[0][0] == 'X') {
labeltokens = tokenize_delimeter(tokens[0], "_");
std::rotate(labeltokens.begin(), labeltokens.end() - 1, labeltokens.end());
tokens[0] = labeltokens[0];
for (int n = 1; n < labeltokens.size(); n++) {
tokens[0] = tokens[0] + "_" + labeltokens[n];
}
}
columnLabel1 = "C_NV" + tokens[0];
if (std::find(iFile.matA.columnNames.begin(), iFile.matA.columnNames.end(), columnLabel1) != iFile.matA.columnNames.end()) {
index1 = index_of(iFile.matA.columnNames, columnLabel1);
traceLabel.push_back(label);
traceData.push_back(xVect[index1]);
}
else {
plotting_errors(NO_SUCH_NODE_FOUND, string);
}
}
/* Neither nodes are ground */
else {
label = "NODE VOLTAGE " + nodesTokens[0] + " to " + nodesTokens[1];
columnLabel1 = "C_NV" + nodesTokens[0];
columnLabel2 = "C_NV" + nodesTokens[1];
if (nodesTokens[0][0] == 'X') {
labeltokens = tokenize_delimeter(nodesTokens[0], "_");
std::rotate(labeltokens.begin(), labeltokens.end() - 1, labeltokens.end());
nodesTokens[0] = labeltokens[0];
for (int n = 1; n < labeltokens.size(); n++) {
nodesTokens[0] = nodesTokens[0] + "_" + labeltokens[n];
}
}
if (nodesTokens[1][0] == 'X') {
labeltokens = tokenize_delimeter(nodesTokens[1], "_");
std::rotate(labeltokens.begin(), labeltokens.end() - 1, labeltokens.end());
nodesTokens[1] = labeltokens[0];
for (int n = 1; n < labeltokens.size(); n++) {
nodesTokens[1] = nodesTokens[1] + "_" + labeltokens[n];
}
}
if (std::find(iFile.matA.columnNames.begin(), iFile.matA.columnNames.end(), columnLabel1) != iFile.matA.columnNames.end()) {
index1 = index_of(iFile.matA.columnNames, columnLabel1);
trace.clear();
trace = xVect[index1];
if (std::find(iFile.matA.columnNames.begin(), iFile.matA.columnNames.end(), columnLabel2) != iFile.matA.columnNames.end()) {
index2 = index_of(iFile.matA.columnNames, columnLabel2);
std::transform(xVect[index1].begin(), xVect[index1].end(), xVect[index2].begin(), trace.begin(), std::minus<double>());
traceLabel.push_back(label);
traceData.push_back(trace);
}
else {
/* Error this node was not found and can therefore not be printed */
plotting_errors(NO_SUCH_NODE_FOUND, string);
}
}
}
}
}
/* If only one argument is specified for V */
else {
/* Ensure node is not ground */
if(nodesToPlot != "0" || nodesToPlot != "GND") {
if (nodesToPlot[0] == 'X') {
labeltokens = tokenize_delimeter(nodesToPlot, "_");
std::rotate(labeltokens.begin(), labeltokens.end() - 1, labeltokens.end());
nodesToPlot = labeltokens[0];
for (int n = 1; n < labeltokens.size(); n++) {
nodesToPlot = nodesToPlot + "_" + labeltokens[n];
}
}
label = "C_NV" + nodesToPlot;
/* If this is a node voltage */
if (std::find(iFile.matA.columnNames.begin(), iFile.matA.columnNames.end(), label) != iFile.matA.columnNames.end()) {
index1 = index_of(iFile.matA.columnNames, label);
label = "NODE VOLTAGE " + nodesToPlot;
traceLabel.push_back(label);
traceData.push_back(xVect[index1]);
}
/* Else it might be device voltage */
else {
label = "NOTHING";
for (auto i : iFile.matA.elements) {
if (i.label == nodesToPlot) {
trace.clear();
if (i.VPindex == -1) trace = xVect[i.VNindex];
else if (i.VNindex == -1) trace = xVect[i.VPindex];
else {
trace = xVect[i.VPindex];
std::transform(xVect[i.VPindex].begin(), xVect[i.VPindex].end(), xVect[i.VNindex].begin(), trace.begin(), std::minus<double>());
}
label = "DEVICE VOLTAGE " + i.label;
traceLabel.push_back(label);
traceData.push_back(trace);
}
}
if (label == "NOTHING") {
if (VERBOSE) plotting_errors(NO_SUCH_DEVICE_FOUND, nodesToPlot);
}
}
}
}
}
else if (tokens[k][0] == 'I') {
/* Identify part between brackets */
nodesToPlot = tokens[k].substr(2);
nodesToPlot = nodesToPlot.substr(0, nodesToPlot.size() - 1);
label = "NOTHING";
if (nodesToPlot[0] == 'X') {
labeltokens = tokenize_delimeter(nodesToPlot, "_");
std::rotate(labeltokens.begin(), labeltokens.end() - 1, labeltokens.end());
nodesToPlot = labeltokens[0];
for (int n = 1; n < labeltokens.size(); n++) {
nodesToPlot = nodesToPlot + "_" + labeltokens[n];
}
}
std::vector<double> trace;
for (auto i : iFile.matA.elements) {
if (i.label == nodesToPlot) {
if (nodesToPlot[0] == 'R') {
if (i.VPindex == -1) trace = xVect[i.VNindex];
else if (i.VNindex == -1) trace = xVect[i.VPindex];
else std::transform(xVect[i.VPindex].begin(), xVect[i.VPindex].end(), xVect[i.VNindex].begin(), trace.begin(), std::minus<double>());
std::transform(trace.begin(), trace.end(), trace.begin(), std::bind(std::multiplies<double>(), std::placeholders::_1, (1/i.value)));
label = "DEVICE CURRENT " + i.label;
traceLabel.push_back(label);
traceData.push_back(trace);
}
else if (nodesToPlot[0] == 'C') {
}
else if (nodesToPlot[0] == 'L') {
if (i.CURindex == -1) simulation_errors(INDUCTOR_CURRENT_NOT_FOUND, i.label);
else trace = xVect[i.CURindex];
label = "DEVICE CURRENT " + i.label;
traceLabel.push_back(label);
traceData.push_back(trace);
}
else if (nodesToPlot[0] == 'I') {
label = "DEVICE CURRENT " + i.label;
traceLabel.push_back(label);
traceData.push_back(iFile.matA.sources[i.label]);
}
else if (nodesToPlot[0] == 'V') {
if (VERBOSE) simulation_errors(CURRENT_THROUGH_VOLTAGE_SOURCE, i.label);
}
else if (nodesToPlot[0] == 'B') {
trace = junctionCurrents["R_" + i.label];
label = "DEVICE CURRENT " + i.label;
traceLabel.push_back(label);
traceData.push_back(trace);
}
else plotting_errors(NO_SUCH_DEVICE_FOUND, string);
}
}
if (label == "NOTHING") {
plotting_errors(NO_SUCH_DEVICE_FOUND, string);
}
}
else if (tokens[k][0] == 'P') {
/* Identify part between brackets */
nodesToPlot = tokens[k].substr(2);
nodesToPlot = nodesToPlot.substr(0, nodesToPlot.size() - 1);
label = "PHASE " + nodesToPlot;
if (nodesToPlot[0] == 'X') {
labeltokens = tokenize_delimeter(nodesToPlot, "_");
std::rotate(labeltokens.begin(), labeltokens.end() - 1, labeltokens.end());
nodesToPlot = labeltokens[0];
for (int n = 1; n < labeltokens.size(); n++) {
nodesToPlot = nodesToPlot + "_" + labeltokens[n];
}
}
columnLabel1 = "C_P" + nodesToPlot;
if (std::find(iFile.matA.columnNames.begin(), iFile.matA.columnNames.end(), columnLabel1) != iFile.matA.columnNames.end()) {
index1 = index_of(iFile.matA.columnNames, columnLabel1);
traceLabel.push_back(label);
traceData.push_back(xVect[index1]);
}
else {
/* Error this node was not found and can therefore not be printed */
plotting_errors(NO_SUCH_DEVICE_FOUND, nodesToPlot);
}
}
}
}
/****************************************************/
/* SAVE */
/****************************************************/
else if (string.find("SAVE") != std::string::npos) {
tokens = tokenize_space(string);
for (int k = 1; k < tokens.size(); k++) {
index1 = tokens[k].find("@");
if(index1 != std::string::npos) tokens[k] = tokens[k].substr(0, index1) + tokens[k].substr(index1+1);
index1 = tokens[k].find("[");
if(index1 != std::string::npos) tokens[k] = tokens[k].substr(0, index1);
index1 = tokens[k].find(".");
if(index1 != std::string::npos) {
tokens[k] = tokens[k].substr(0, index1) + "_" + tokens[k].substr(index1+1);
}
/* If this is a current source */
if (iFile.matA.sources.find(tokens[k]) != iFile.matA.sources.end()) {
label = "CURRENT " + tokens[k];
traceLabel.push_back(label);
traceData.push_back(iFile.matA.sources[tokens[k]]);
}
}
}
}
}
/*
Function that creates a plotting window with all available traces to plot
*/
int plot_all_traces(InputFile& iFile) {
#ifdef USING_FLTK
Fl_Window * win = new Fl_Window(1240, 768);
Fl_Scroll * scroll = new Fl_Scroll(0, 0, win->w(), win->h());
std::vector<Fl_Chart *> Charts;
std::string label;
int counter = 0;
for (auto i : iFile.matA.columnNames) {
label = substring_after(i, "C_");
Charts.push_back(new Fl_Chart(20, 20 + (counter * (scroll->h() / 3)), scroll->w() - 40, (scroll->h()/3 - 20)));
Charts[counter]->type(FL_LINE_CHART);
for (int j = 0; j < xVect[counter].size(); j++) {
Charts[counter]->add(xVect[counter][j]);
}
Charts[counter]->color(FL_WHITE);
Charts[counter]->align(FL_ALIGN_INSIDE|FL_ALIGN_CENTER|FL_ALIGN_TOP);
Charts[counter]->copy_label(label.c_str());
counter++;
}
win->resizable(scroll);
win->label(INPUT_FILE.c_str());
win->show();
return(Fl::run());
#elif USING_MATPLOTLIB
int counter = 0;
if (iFile.matA.columnNames.size() <= 3) {
plt::figure();
//plt::figure_size(800, 600);
for (auto i : iFile.matA.columnNames) {
plt::subplot(iFile.matA.columnNames.size(), 1, counter + 1);
plt::grid(true);
plt::plot(timeAxis, xVect[counter]);
plt::title(substring_after(i, "C_"));
if(substring_after(i, "C_")[0] == 'N') plt::ylabel("Voltage (V)");
else if (substring_after(i, "C_")[0] == 'I') plt::ylabel("Current (A)");
else if (substring_after(i, "C_")[0] == 'P') plt::ylabel("Phase (rads)");
counter++;
}
plt::xlabel("Time (s)");
plt::tight_layout();
plt::show();
}
else {
for (int j = 0; j < iFile.matA.columnNames.size(); j = j + 3) {
counter = j;
//plt::figure_size(800, 600);
plt::figure();
while((counter < iFile.matA.columnNames.size()) && (counter < j + 3)) {
plt::subplot(3, 1, (counter - j) + 1);
plt::grid(true);
plt::plot(timeAxis, xVect[counter]);
plt::title(substring_after(iFile.matA.columnNames[counter], "C_"));
if(substring_after(iFile.matA.columnNames[counter], "C_")[0] == 'N') plt::ylabel("Voltage (V)");
else if (substring_after(iFile.matA.columnNames[counter], "C_")[0] == 'I') plt::ylabel("Current (A)");
else if (substring_after(iFile.matA.columnNames[counter], "C_")[0] == 'P') plt::ylabel("Phase (rads)");
counter++;
}
plt::xlabel("Time (s)");
plt::tight_layout();
plt::show(false);
}
plt::show();
}
return 0;
#endif
return 0;
}
/*
Function that creates a plotting window only for the specified plots in the simulation
*/
int plot_traces(InputFile& iFile) {
#ifdef USING_FLTK
std::vector<std::string> traceLabel;
std::vector<std::vector<double>> traceData;
traces_to_plot(iFile.controlPart, traceLabel, traceData);
Fl_Window * win = new Fl_Window(1240, 768);
Fl_Scroll * scroll = new Fl_Scroll(0, 0, win->w(), win->h());
std::vector<Fl_Chart *> Charts;
if(traceLabel.size() > 0) {
for (int i = 0; i < traceLabel.size(); i++) {
Charts.push_back(new Fl_Chart(20, 20 + (i * (scroll->h() / 3)), scroll->w() - 40, (scroll->h() / 3 - 20)));
Charts[i]->type(FL_LINE_CHART);
for (int j = 0; j < traceData[i].size(); j++) {
Charts[i]->add(traceData[i][j]);
}
Charts[i]->color(FL_WHITE);
Charts[i]->align(FL_ALIGN_INSIDE | FL_ALIGN_CENTER | FL_ALIGN_TOP);
Charts[i]->copy_label(traceLabel[i].c_str());
}
}
else if (traceLabel.size() == 0) {
std::cout << "W: Plotting requested but no plot/print/save commands found." << std::endl;
std::cout << "W: Plotting all the node voltages by default." << std::endl;
int j = 0;
std::string label;
for (int i = 0; i < iFile.matA.columnNames.size(); i++) {
label = substring_after(iFile.matA.columnNames[i], "C_");
if(label[0] == 'N') {
Charts.push_back(new Fl_Chart(20, 20 + (j * (scroll->h() / 3)), scroll->w() - 40, (scroll->h() / 3 - 20)));
Charts[j]->type(FL_LINE_CHART);
for (int k = 0; k < xVect[i].size(); k++) {
Charts[j]->add(xVect[i][k]);
}
Charts[j]->color(FL_WHITE);
Charts[j]->align(FL_ALIGN_INSIDE | FL_ALIGN_CENTER | FL_ALIGN_TOP);
Charts[j]->copy_label(label.c_str());
j++;
}
}
}
win->resizable(win);
win->label(INPUT_FILE.c_str());
win->show();
return(Fl::run());
#elif USING_MATPLOTLIB
std::vector<std::string> traceLabel;
std::vector<std::vector<double>> traceData;
traces_to_plot(iFile, iFile.controlPart, traceLabel, traceData);
if(traceLabel.size() > 0) {
if (traceLabel.size() <= 3) {
//plt::figure_size(800, 600);
plt::figure();
for (int i = 0; i < traceLabel.size(); i++) {
plt::subplot(traceLabel.size(), 1, i + 1);
plt::grid(true);
plt::plot(timeAxis, traceData[i]);
plt::title(traceLabel[i].c_str());
if(traceLabel[i].find("VOLTAGE") != std::string::npos) plt::ylabel("Voltage (V)");
else if (traceLabel[i].find("CURRENT") != std::string::npos) plt::ylabel("Current (A)");
else if (traceLabel[i].find("PHASE") != std::string::npos) plt::ylabel("Phase (rads)");
}
plt::xlabel("Time (s)");
plt::tight_layout();
plt::show();
}
else {
for (int j = 0; j < traceLabel.size(); j = j + 3) {
int i = j;
//plt::figure_size(800, 600);
plt::figure();
while((i < traceLabel.size()) && (i < j + 3)) {
plt::subplot(3, 1, (i - j) + 1);
plt::grid(true);
plt::plot(timeAxis, traceData[i]);
plt::title(traceLabel[i].c_str());
if(traceLabel[i].find("VOLTAGE") != std::string::npos) { plt::ylabel("Voltage (V)"); }
else if (traceLabel[i].find("CURRENT") != std::string::npos) { plt::ylabel("Current (A)"); }
else if (traceLabel[i].find("PHASE") != std::string::npos) { plt::ylabel("Phase (rads)"); }
i++;
}
plt::xlabel("Time (s)");
plt::tight_layout();
plt::show(false);
}
plt::show();
}
}
else if(traceLabel.size() == 0) {
std::cout << "W: Plotting requested but no plot/print/save commands found." << std::endl;
std::cout << "W: Plotting all the node voltages by default." << std::endl;
// Find all the NV column indices
std::vector<int> nvIndices;
for(int i = 0; i < iFile.matA.columnNames.size(); i++) if(iFile.matA.columnNames[i][2] == 'N') nvIndices.push_back(i);
for (int j = 0; j < nvIndices.size(); j = j + 3) {
int i = j;
plt::figure_size(800, 600);
while((i < nvIndices.size()) && (i < j + 3)) {
plt::subplot(3, 1, (i - j) + 1);
plt::grid(true);
plt::plot(timeAxis, xVect[nvIndices[i]]);
plt::title(substring_after(iFile.matA.columnNames[nvIndices[i]], "C_").c_str());
plt::ylabel("Voltage (V)");
i++;
}
plt::xlabel("Time (s)");
plt::tight_layout();
plt::show(false);
}
plt::show();
}
return 0;
#endif
return 0;
}
| 41.07659 | 161 | 0.552366 |
234fdceea4773f1e33084b230737b0ffba9d8adf | 4,431 | cpp | C++ | src/cui-1.0.4/MBA/MBA.cpp | MaiReo/crass | 11579527090faecab27f98b1e221172822928f57 | [
"BSD-3-Clause"
] | 1 | 2021-07-21T00:58:45.000Z | 2021-07-21T00:58:45.000Z | src/cui-1.0.4/MBA/MBA.cpp | MaiReo/crass | 11579527090faecab27f98b1e221172822928f57 | [
"BSD-3-Clause"
] | null | null | null | src/cui-1.0.4/MBA/MBA.cpp | MaiReo/crass | 11579527090faecab27f98b1e221172822928f57 | [
"BSD-3-Clause"
] | null | null | null | #include <windows.h>
#include <tchar.h>
#include <crass_types.h>
#include <acui.h>
#include <cui.h>
#include <package.h>
#include <resource.h>
#include <cui_error.h>
#include <stdio.h>
/* 接口数据结构: 表示cui插件的一般信息 */
struct acui_information MBA_cui_information = {
_T("飛翔システム"), /* copyright */
_T(""), /* system */
_T(".gdp"), /* package */
_T("1.0.1"), /* revision */
_T("痴漢公賊"), /* author */
_T("2009-3-18 20:35"), /* date */
NULL, /* notion */
ACUI_ATTRIBUTE_LEVEL_STABLE
};
/* 所有的封包特定的数据结构都要放在这个#pragma段里 */
#pragma pack (1)
typedef struct {
u32 index_entries;
} gdp_header_t;
typedef struct {
s8 name[260];
u32 length;
u32 offset;
} gdp_entry_t;
#pragma pack ()
/********************* gdp *********************/
static int MBA_gdp_extract_directory(struct package *pkg,
struct package_directory *pkg_dir);
/* 封包匹配回调函数 */
static int MBA_gdp_match(struct package *pkg)
{
if (pkg->pio->open(pkg, IO_READONLY))
return -CUI_EOPEN;
struct package_directory pkg_dir;
int ret = MBA_gdp_extract_directory(pkg, &pkg_dir);
if (!ret)
delete [] pkg_dir.directory;
return ret;
}
/* 封包索引目录提取函数 */
static int MBA_gdp_extract_directory(struct package *pkg,
struct package_directory *pkg_dir)
{
if (pkg->pio->readvec(pkg, &pkg_dir->index_entries, 4, 0, IO_SEEK_SET))
return -CUI_EREADVEC;
DWORD index_buffer_length = pkg_dir->index_entries * sizeof(gdp_entry_t);
gdp_entry_t *index_buffer = new gdp_entry_t[pkg_dir->index_entries];
if (!index_buffer)
return -CUI_EMEM;
if (pkg->pio->read(pkg, index_buffer, index_buffer_length)) {
delete [] index_buffer;
return -CUI_EREAD;
}
pkg_dir->directory = index_buffer;
pkg_dir->directory_length = index_buffer_length;
pkg_dir->index_entry_length = sizeof(gdp_entry_t);
return 0;
}
/* 封包索引项解析函数 */
static int MBA_gdp_parse_resource_info(struct package *pkg,
struct package_resource *pkg_res)
{
gdp_entry_t *gdp_entry;
gdp_entry = (gdp_entry_t *)pkg_res->actual_index_entry;
strcpy(pkg_res->name, gdp_entry->name);
pkg_res->name_length = -1; /* -1表示名称以NULL结尾 */
pkg_res->raw_data_length = gdp_entry->length;
pkg_res->actual_data_length = 0; /* 数据都是明文 */
pkg_res->offset = gdp_entry->offset;
return 0;
}
/* 封包资源提取函数 */
static int MBA_gdp_extract_resource(struct package *pkg,
struct package_resource *pkg_res)
{
BYTE *raw = new BYTE[pkg_res->raw_data_length];
if (!raw)
return -CUI_EMEM;
if (pkg->pio->readvec(pkg, raw, pkg_res->raw_data_length,
pkg_res->offset, IO_SEEK_SET)) {
delete [] raw;
return -CUI_EREADVEC;
}
pkg_res->raw_data = raw;
return 0;
}
/* 资源保存函数 */
static int MBA_gdp_save_resource(struct resource *res,
struct package_resource *pkg_res)
{
if (res->rio->create(res))
return -CUI_ECREATE;
if (pkg_res->actual_data && pkg_res->actual_data_length) {
if (res->rio->write(res, pkg_res->actual_data, pkg_res->actual_data_length)) {
res->rio->close(res);
return -CUI_EWRITE;
}
} else if (pkg_res->raw_data && pkg_res->raw_data_length) {
if (res->rio->write(res, pkg_res->raw_data, pkg_res->raw_data_length)) {
res->rio->close(res);
return -CUI_EWRITE;
}
}
res->rio->close(res);
return 0;
}
/* 封包资源释放函数 */
static void MBA_gdp_release_resource(struct package *pkg,
struct package_resource *pkg_res)
{
if (pkg_res->actual_data) {
delete [] pkg_res->actual_data;
pkg_res->actual_data = NULL;
}
if (pkg_res->raw_data) {
delete [] pkg_res->raw_data;
pkg_res->raw_data = NULL;
}
}
/* 封包卸载函数 */
static void MBA_gdp_release(struct package *pkg,
struct package_directory *pkg_dir)
{
if (pkg_dir->directory) {
delete [] pkg_dir->directory;
pkg_dir->directory = NULL;
}
pkg->pio->close(pkg);
}
/* 封包处理回调函数集合 */
static cui_ext_operation MBA_gdp_operation = {
MBA_gdp_match, /* match */
MBA_gdp_extract_directory, /* extract_directory */
MBA_gdp_parse_resource_info, /* parse_resource_info */
MBA_gdp_extract_resource, /* extract_resource */
MBA_gdp_save_resource, /* save_resource */
MBA_gdp_release_resource, /* release_resource */
MBA_gdp_release /* release */
};
/* 接口函数: 向cui_core注册支持的封包类型 */
int CALLBACK MBA_register_cui(struct cui_register_callback *callback)
{
if (callback->add_extension(callback->cui, _T(".gdp"), NULL,
NULL, &MBA_gdp_operation, CUI_EXT_FLAG_PKG | CUI_EXT_FLAG_DIR
| CUI_EXT_FLAG_WEAK_MAGIC))
return -1;
return 0;
}
}
| 23.822581 | 80 | 0.693297 |
23517d313abc400a073f8b524b70ab131eb930f0 | 2,585 | cpp | C++ | PLUTO/Src/Chombo/AMRLevelPlutoFactory.cpp | Mixpap/JetCloudSim | bc44ca3eb3956b87a4390428d897099a92a8b9b2 | [
"MIT"
] | 1 | 2018-11-21T20:32:36.000Z | 2018-11-21T20:32:36.000Z | PLUTO/Src/Chombo/AMRLevelPlutoFactory.cpp | Mixpap/JetCloudSim | bc44ca3eb3956b87a4390428d897099a92a8b9b2 | [
"MIT"
] | 3 | 2018-10-08T22:20:49.000Z | 2018-10-19T14:00:44.000Z | PLUTO/Src/Chombo/AMRLevelPlutoFactory.cpp | Mixpap/JetCloudSim | bc44ca3eb3956b87a4390428d897099a92a8b9b2 | [
"MIT"
] | 1 | 2019-06-26T05:37:43.000Z | 2019-06-26T05:37:43.000Z | #ifdef CH_LANG_CC
/*
* _______ __
* / ___/ / ___ __ _ / / ___
* / /__/ _ \/ _ \/ V \/ _ \/ _ \
* \___/_//_/\___/_/_/_/_.__/\___/
* Please refer to Copyright.txt, in Chombo's root directory.
*/
#endif
#include "AMRLevelPlutoFactory.H"
#include "NamespaceHeader.H"
AMRLevelPlutoFactory::AMRLevelPlutoFactory()
{
m_patchPluto = NULL;
m_isDefined = false;
}
AMRLevelPlutoFactory::~AMRLevelPlutoFactory()
{
if (m_patchPluto != NULL)
{
delete m_patchPluto;
m_patchPluto = NULL;
}
m_isDefined = false;
}
void AMRLevelPlutoFactory::define(const Real& a_cfl,
const Real& a_domainLength,
const int& a_verbosity,
const Real& a_refineThresh,
const int& a_tagBufferSize,
const Real& a_initialDtMultiplier,
const PatchPluto* const a_patchPluto)
{
// Store the CFL number
m_cfl = a_cfl;
// Store the physical dimension of the longest side of the domain
m_domainLength = a_domainLength;
// Store the verbosity of the object
m_verbosity = a_verbosity;
// Store the refinement threshold for gradient
m_refineThresh = a_refineThresh;
// Store the tag buffer size
m_tagBufferSize = a_tagBufferSize;
// Store the initial dt multiplier
m_initialDtMultiplier = a_initialDtMultiplier;
// Delete any existing physics object
if (m_patchPluto != NULL)
{
delete m_patchPluto;
m_patchPluto = NULL;
}
// Store the object that supplies the physics needed by the integrator
// (used as a factory)
m_patchPluto = a_patchPluto->new_patchPluto();
// The object is defined
m_isDefined = true;
}
AMRLevel* AMRLevelPlutoFactory::new_amrlevel() const
{
// Make sure everything is defined
CH_assert(isDefined());
// Create a new AMRLevelPluto
AMRLevelPluto* amrGodPtr = new AMRLevelPluto();
// Set up new object
amrGodPtr->defineParams(m_cfl,
m_domainLength,
m_verbosity,
m_refineThresh,
m_tagBufferSize,
m_initialDtMultiplier,
m_patchPluto);
// Return it
return (static_cast <AMRLevel*> (amrGodPtr));
}
// Check that everything is defined
bool AMRLevelPlutoFactory::isDefined() const
{
return m_isDefined;
}
#include "NamespaceFooter.H"
| 25.594059 | 81 | 0.591876 |
2351dd801afdf4dd24e9dec216d419dd3d8c8b83 | 11,486 | cpp | C++ | src/stacker_system.cpp | scullion/stacker | ba9241c85962f210ea37784ebee3072dac63df46 | [
"MIT"
] | null | null | null | src/stacker_system.cpp | scullion/stacker | ba9241c85962f210ea37784ebee3072dac63df46 | [
"MIT"
] | null | null | null | src/stacker_system.cpp | scullion/stacker | ba9241c85962f210ea37784ebee3072dac63df46 | [
"MIT"
] | null | null | null | #include "stacker_system.h"
#include "stacker_shared.h"
#include "stacker_attribute_buffer.h"
#include "stacker_util.h"
#include "stacker_platform.h"
#include "stacker_document.h"
#include "stacker_layer.h"
namespace stkr {
static void make_font_descriptor(LogicalFont *descriptor, const char *face,
unsigned size, unsigned flags)
{
if (face != NULL) {
strncpy(descriptor->face, face, sizeof(descriptor->face));
descriptor->face[sizeof(descriptor->face) - 1] = '\0';
} else {
descriptor->face[0] = '\0';
}
descriptor->font_size = size;
descriptor->flags = (uint16_t)flags;
}
static void initialize_font_cache(System *system)
{
system->default_font_id = INVALID_FONT_ID;
system->font_cache_entries = 0;
make_font_descriptor(&system->default_font_descriptor,
DEFAULT_FONT_FACE, DEFAULT_FONT_SIZE, DEFAULT_FONT_FLAGS);
system->default_font_id = get_font_id(system,
&system->default_font_descriptor);
ensure(system->default_font_id != INVALID_FONT_ID);
system->debug_label_font_id = INVALID_FONT_ID;
}
/* Returns a key uniquely identifying a font specification. */
static uint32_t make_font_key(const LogicalFont *logfont)
{
uint32_t seed = logfont->font_size | (logfont->flags << 16);
return murmur3_32(logfont->face, strlen(logfont->face), seed);
}
/* Precalculates numbers needed for typesetting from the system font metrics. */
static void calculate_derived_font_metrics(FontMetrics *metrics)
{
/* w = (1/3)em, y = (1/6)em, z = (1/9)em */
static const int ONE_THIRD = (1 << TEXT_METRIC_PRECISION) / 3;
static const int ONE_SIXTH = (1 << TEXT_METRIC_PRECISION) / 6;
static const int ONE_NINTH = (1 << TEXT_METRIC_PRECISION) / 9;
metrics->space_width = fixed_multiply(metrics->em_width, ONE_THIRD, TEXT_METRIC_PRECISION);
metrics->space_stretch = fixed_multiply(metrics->em_width, ONE_SIXTH, TEXT_METRIC_PRECISION);
metrics->space_shrink = fixed_multiply(metrics->em_width, ONE_NINTH, TEXT_METRIC_PRECISION);
metrics->paragraph_indent_width = metrics->em_width;
}
/* Returns the ID of a font from the font cache, creating it if necessary. */
int16_t get_font_id(System *system, const LogicalFont *logfont)
{
uint32_t key = make_font_key(logfont);
for (unsigned i = 0; i < system->font_cache_entries; ++i)
if (system->font_cache[i].key == key)
return (int16_t)i;
if (system->font_cache_entries == MAX_CACHED_FONTS)
return 0;
void *handle = platform_match_font(system->back_end, logfont);
if (handle == NULL)
return system->default_font_id;
CachedFont *cf = system->font_cache + system->font_cache_entries;
cf->key = key;
cf->handle = handle;
cf->descriptor = *logfont;
platform_font_metrics(system->back_end, handle, &cf->metrics);
calculate_derived_font_metrics(&cf->metrics);
return int16_t(system->font_cache_entries++);
}
/* Returns the system handle for a cached font. */
void *get_font_handle(System *system, int16_t font_id)
{
assertb(unsigned(font_id) < system->font_cache_entries);
return system->font_cache[font_id].handle;
}
/* Returns the logical font used to create a font ID. */
const LogicalFont *get_font_descriptor(System *system, int16_t font_id)
{
if (font_id != INVALID_FONT_ID) {
assertb(unsigned(font_id) < system->font_cache_entries);
return &system->font_cache[font_id].descriptor;
}
return &system->default_font_descriptor;
}
const FontMetrics *get_font_metrics(System *system, int16_t font_id)
{
assertb(unsigned(font_id) < system->font_cache_entries);
return &system->font_cache[font_id].metrics;
}
unsigned measure_text(System *system, int16_t font_id, const void *text,
unsigned length, unsigned *advances)
{
void *font_handle = get_font_handle(system, font_id);
return platform_measure_text(system->back_end, font_handle,
text, length, advances);
}
/* A convenience function to determine the size of a string's bounding
* rectangle. Optionally returns the temporary heap-allocated advances array
* used, for which the caller takes responsibility. */
unsigned measure_text_rectangle(System *system, int16_t font_id,
const void *text, unsigned length, unsigned *out_width,
unsigned *out_height, unsigned **out_advances)
{
unsigned *advances = new unsigned[length];
unsigned num_characters = measure_text(system, font_id, text,
length, advances);
if (out_width != NULL) {
*out_width = 0;
for (unsigned i = 0; i < num_characters; ++i)
*out_width += advances[i];
*out_width = round_fixed_to_int(*out_width, TEXT_METRIC_PRECISION);
}
if (out_height != NULL) {
const FontMetrics *metrics = get_font_metrics(system, font_id);
*out_height = round_fixed_to_int(metrics->height, TEXT_METRIC_PRECISION);
}
if (out_advances != NULL) {
*out_advances = advances;
} else {
delete [] out_advances;
}
return num_characters;
}
/* Precomputes hashed rule names for tag tokens and pseudo classes. */
static void make_built_in_rule_names(System *system)
{
system->rule_name_all = murmur3_64_cstr("*");
system->rule_name_active = murmur3_64_cstr(":active");
system->rule_name_highlighted = murmur3_64_cstr(":highlighted");
for (unsigned i = 0; i < NUM_KEYWORDS; ++i) {
system->token_rule_names[i] = murmur3_64_cstr(
TOKEN_STRINGS[TOKEN_KEYWORD_FIRST + i]);
}
}
static unsigned add_font_assignments(AttributeAssignment *attributes,
unsigned count, const char *face, unsigned size, unsigned flags)
{
attributes[count++] = make_assignment(TOKEN_FONT, face);
attributes[count++] = make_assignment(TOKEN_FONT_SIZE, size);
attributes[count++] = make_assignment(TOKEN_BOLD, (flags & STYLE_BOLD) != 0, VSEM_BOOLEAN);
attributes[count++] = make_assignment(TOKEN_ITALIC, (flags & TOKEN_ITALIC) != 0, VSEM_BOOLEAN);
attributes[count++] = make_assignment(TOKEN_UNDERLINE, (flags & STYLE_UNDERLINE) != 0, VSEM_BOOLEAN);
return count;
}
static void add_default_rules(System *system)
{
static const unsigned MAX_ROOT_ATTRIBUTES = 32;
AttributeAssignment attributes[MAX_ROOT_ATTRIBUTES];
unsigned count = 0;
attributes[count++] = make_assignment(TOKEN_COLOR, DEFAULT_TEXT_COLOR, VSEM_COLOR);
attributes[count++] = make_assignment(TOKEN_JUSTIFY, TOKEN_LEFT, VSEM_TOKEN);
attributes[count++] = make_assignment(TOKEN_WRAP, TOKEN_WORD_WRAP, VSEM_TOKEN);
attributes[count++] = make_assignment(TOKEN_LEADING, TOKEN_AUTO, VSEM_TOKEN);
attributes[count++] = make_assignment(TOKEN_WHITE_SPACE, TOKEN_NORMAL, VSEM_TOKEN);
count = add_font_assignments(attributes, count, DEFAULT_FONT_FACE, DEFAULT_FONT_SIZE, DEFAULT_FONT_FLAGS);
add_rule(NULL, system, NULL, "document", -1, attributes, count, RFLAG_ENABLED | RFLAG_GLOBAL, RULE_PRIORITY_LOWEST);
count = 0;
attributes[count++] = make_assignment(TOKEN_WIDTH, TOKEN_GROW, VSEM_TOKEN);
attributes[count++] = make_assignment(TOKEN_JUSTIFY, TOKEN_FLUSH, VSEM_TOKEN);
attributes[count++] = make_assignment(TOKEN_INDENT, TOKEN_AUTO, VSEM_TOKEN);
add_rule(NULL, system, NULL, "p", -1, attributes, count, RFLAG_ENABLED | RFLAG_GLOBAL, RULE_PRIORITY_LOWEST);
count = 0;
attributes[count++] = make_assignment(TOKEN_CURSOR, TOKEN_CURSOR_HAND, VSEM_TOKEN);
attributes[count++] = make_assignment(TOKEN_UNDERLINE, true, VSEM_BOOLEAN);
attributes[count++] = make_assignment(TOKEN_COLOR, DEFAULT_LINK_COLOR, VSEM_COLOR);
add_rule(NULL, system, NULL, "a", -1, attributes, count, RFLAG_ENABLED | RFLAG_GLOBAL, RULE_PRIORITY_LOWEST);
count = 0;
attributes[count++] = make_assignment(TOKEN_COLOR, DEFAULT_HIGHLIGHTED_LINK_COLOR, VSEM_COLOR);
add_rule(NULL, system, NULL, "a:highlighted", -1, attributes, count, RFLAG_ENABLED | RFLAG_GLOBAL, RULE_PRIORITY_LOWEST);
count = 0;
attributes[count++] = make_assignment(TOKEN_COLOR, DEFAULT_ACTIVE_LINK_COLOR, VSEM_COLOR);
add_rule(NULL, system, NULL, "a:active", -1, attributes, count, RFLAG_ENABLED | RFLAG_GLOBAL, RULE_PRIORITY_LOWEST);
count = 0;
attributes[count++] = make_assignment(TOKEN_WIDTH, TOKEN_GROW, VSEM_TOKEN);
attributes[count++] = make_assignment(TOKEN_FONT_SIZE, 2.5f, VSEM_NONE, AOP_MULTIPLY);
attributes[count++] = make_assignment(TOKEN_BOLD, true, VSEM_BOOLEAN);
add_rule(NULL, system, NULL, "h1", -1, attributes, count, RFLAG_ENABLED | RFLAG_GLOBAL, RULE_PRIORITY_LOWEST);
count = 0;
attributes[count++] = make_assignment(TOKEN_WIDTH, TOKEN_GROW, VSEM_TOKEN);
attributes[count++] = make_assignment(TOKEN_FONT_SIZE, 2.0f, VSEM_NONE, AOP_MULTIPLY);
attributes[count++] = make_assignment(TOKEN_BOLD, true, VSEM_BOOLEAN);
add_rule(NULL, system, NULL, "h2", -1, attributes, count, RFLAG_ENABLED | RFLAG_GLOBAL, RULE_PRIORITY_LOWEST);
count = 0;
attributes[count++] = make_assignment(TOKEN_WIDTH, TOKEN_GROW, VSEM_TOKEN);
attributes[count++] = make_assignment(TOKEN_FONT_SIZE, 1.5f, VSEM_NONE, AOP_MULTIPLY);
attributes[count++] = make_assignment(TOKEN_BOLD, true, VSEM_BOOLEAN);
add_rule(NULL, system, NULL, "h3", -1, attributes, count, RFLAG_ENABLED | RFLAG_GLOBAL, RULE_PRIORITY_LOWEST);
count = 0;
attributes[count++] = make_assignment(TOKEN_WHITE_SPACE, TOKEN_PRESERVE, VSEM_TOKEN);
count = add_font_assignments(attributes, count, DEFAULT_FIXED_FONT_FACE, DEFAULT_FIXED_FONT_SIZE, DEFAULT_FIXED_FONT_FLAGS);
add_rule(NULL, system, NULL, "code", -1, attributes, count, RFLAG_ENABLED | RFLAG_GLOBAL, RULE_PRIORITY_LOWEST);
}
static void initialize_url_notifications(System *system, UrlCache *url_cache)
{
if (url_cache != NULL) {
system->image_layer_notify_id = url_cache->add_notify_sink(
(urlcache::NotifyCallback)&image_layer_notify_callback, system);
system->document_notify_id = url_cache->add_notify_sink(
(urlcache::NotifyCallback)&document_fetch_notify_callback, system);
} else {
system->image_layer_notify_id = urlcache::INVALID_NOTIFY_SINK_ID;
}
}
static void deinitialize_url_notifications(System *system, UrlCache *url_cache)
{
if (url_cache != NULL) {
url_cache->remove_notify_sink(system->image_layer_notify_id);
url_cache->remove_notify_sink(system->document_notify_id);
}
}
int16_t get_debug_label_font_id(System *system)
{
if (system->debug_label_font_id == INVALID_FONT_ID) {
LogicalFont descriptor;
make_font_descriptor(&descriptor, DEBUG_LABEL_FONT_FACE,
DEBUG_LABEL_FONT_SIZE, DEBUG_LABEL_FONT_FLAGS);
system->debug_label_font_id = get_font_id(system, &descriptor);
}
return system->debug_label_font_id;
}
System *create_system(unsigned flags, BackEnd *back_end, UrlCache *url_cache,
TextEncoding encoding, TextEncoding message_encoding)
{
System *system = new System();
system->flags = flags;
system->encoding = encoding;
system->message_encoding = message_encoding;
system->back_end = back_end;
system->url_cache = url_cache;
system->rule_table_revision = 0;
system->rule_revision_counter = 0;
system->total_boxes = 0;
system->total_nodes = 0;
initialize_font_cache(system);
make_built_in_rule_names(system);
initialize_url_notifications(system, url_cache);
add_default_rules(system);
return system;
}
void destroy_system(System *system)
{
assertb(system->total_nodes == 0);
assertb(system->total_boxes == 0);
clear_rule_table(&system->global_rules);
for (unsigned i = 0; i < system->font_cache_entries; ++i)
platform_release_font(system->back_end, system->font_cache[i].handle);
deinitialize_url_notifications(system, system->url_cache);
delete system;
}
BackEnd *get_back_end(System *system)
{
return system->back_end;
}
unsigned get_total_nodes(const System *system)
{
return system->total_nodes;
}
unsigned get_total_boxes(const System *system)
{
return system->total_boxes;
}
} // namespace stkr
| 38.673401 | 125 | 0.765715 |
2355492847a974f82b3e39e3ad68c1326d4c7bdf | 407 | cpp | C++ | src/format.cpp | nalinraut/System-Monitor | cd51a040455bad43d835606fb3013b35a40f4fc4 | [
"MIT"
] | null | null | null | src/format.cpp | nalinraut/System-Monitor | cd51a040455bad43d835606fb3013b35a40f4fc4 | [
"MIT"
] | null | null | null | src/format.cpp | nalinraut/System-Monitor | cd51a040455bad43d835606fb3013b35a40f4fc4 | [
"MIT"
] | null | null | null | #include <string>
#include "format.h"
using std::string;
string Format::ElapsedTime(long int seconds) {
long int HH{seconds/3600};
long int H_re{seconds%3600};
long int MM{H_re/60};
long int SS{H_re%60};
string HH_str{std::to_string(HH)};
string MM_str{std::to_string(MM)};
string SS_str{std::to_string(SS)};
string time{HH_str+':'+MM_str+':'+SS_str};
return time;
} | 23.941176 | 47 | 0.653563 |
235572b54424b5bf201c86257542fb05e43cff74 | 4,134 | cpp | C++ | 19f/qual/prime/prime.cpp | willzhang05/icpc-practice | 42f1fde0e7e26ba44d433688393db71e02b043b7 | [
"MIT"
] | null | null | null | 19f/qual/prime/prime.cpp | willzhang05/icpc-practice | 42f1fde0e7e26ba44d433688393db71e02b043b7 | [
"MIT"
] | null | null | null | 19f/qual/prime/prime.cpp | willzhang05/icpc-practice | 42f1fde0e7e26ba44d433688393db71e02b043b7 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <iostream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
std::unordered_set<int> PRIMES = {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53,
59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131,
137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223,
227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311,
313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409,
419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,
509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613,
617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719,
727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827,
829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941,
947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049,
1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163,
1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283,
1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423};
int PRIMES_LIST[224] = {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53,
59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131,
137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223,
227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311,
313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409,
419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,
509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613,
617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719,
727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827,
829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941,
947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049,
1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163,
1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283,
1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423};
std::unordered_map<int, std::unordered_set<int>> NONPRIME;
int find_nonprime(int val, std::unordered_set<int> *temp_seen) {
// if (result.count(val) != 0 || temp_seen->count(val) != 0){
// return 0;
//}
if (temp_seen->count(val) != 0) {
return 0;
}
if (NONPRIME.count(val) != 0) {
std::set_union(temp_seen->begin(), temp_seen->end(), NONPRIME[val].begin(),
NONPRIME[val].end(), std::inserter(*temp_seen, temp_seen->begin()));
return 0;
}
temp_seen->insert(val);
int count = 0;
for (int p = 0; p < 224; p++) {
// std::cout << val << ":" << PRIMES_LIST[p] << "\n";
if (val % PRIMES_LIST[p] == 0) {
count += find_nonprime(val / PRIMES_LIST[p], temp_seen);
}
}
return 0;
}
int main() {
int q;
std::cin >> q;
for (int j = 0; j < q; j++) {
int i;
std::cin >> i;
std::unordered_set<int> temp_seen;
int count = find_nonprime(i, &temp_seen);
std::cout << temp_seen.size() << "\n";
NONPRIME.insert(std::make_pair(i, temp_seen));
temp_seen.clear();
}
return 0;
}
| 52.329114 | 100 | 0.516933 |
2355c6b669e088ed141f637d36ec5804b5e750df | 1,510 | hh | C++ | Archive/Stroika_FINAL_for_STERL_1992/Library/User/Headers/EnableView.hh | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 28 | 2015-09-22T21:43:32.000Z | 2022-02-28T01:35:01.000Z | Archive/Stroika_FINAL_for_STERL_1992/Library/User/Headers/EnableView.hh | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 98 | 2015-01-22T03:21:27.000Z | 2022-03-02T01:47:00.000Z | Archive/Stroika_FINAL_for_STERL_1992/Library/User/Headers/EnableView.hh | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 4 | 2019-02-21T16:45:25.000Z | 2022-02-18T13:40:04.000Z | /* Copyright(c) Sophist Solutions Inc. 1990-1992. All rights reserved */
#ifndef __EnableView__
#define __EnableView__
/*
* $Header: /fuji/lewis/RCS/EnableView.hh,v 1.1 1992/06/20 17:33:49 lewis Exp $
*
* Description:
*
*
* TODO:
*
*
* Notes:
*
* Changes:
* $Log: EnableView.hh,v $
* Revision 1.1 1992/06/20 17:33:49 lewis
* Initial revision
*
* Revision 1.2 1992/03/26 09:24:26 lewis
* Got rid of oldLive first argument to EffectiveLiveChanged () method.
*
* Revision 1.1 1992/03/13 16:00:55 lewis
* Initial revision
*
*
*
*/
#include "EnableItem.hh"
#include "View.hh"
#if qCanFreelyUseVirtualBaseClasses
class EnableView : public virtual EnableItem, public virtual View {
#else
class EnableView : public EnableItem, public View {
#endif
protected:
EnableView (Boolean enabled = kEnabled);
public:
override Boolean GetLive () const;
protected:
override void EffectiveLiveChanged (Boolean newLive, UpdateMode updateMode);
override Boolean GetEnabled_ () const;
override void SetEnabled_ (Boolean enabled, UpdateMode updateMode);
private:
Boolean fEnabled;
};
/*
********************************************************************************
************************************ InLines ***********************************
********************************************************************************
*/
// For gnuemacs:
// Local Variables: ***
// mode:C++ ***
// tab-width:4 ***
// End: ***
#endif /*__EnableView__*/
| 19.358974 | 81 | 0.570861 |
2355c6bae8ee711ddb14deac4d4970de16e1fc9e | 2,686 | cpp | C++ | problemes/probleme2xx/probleme280.cpp | ZongoForSpeed/ProjectEuler | 2e2d45f984d48a1da8275886c976f909a0de94ce | [
"MIT"
] | 6 | 2015-10-13T17:07:21.000Z | 2018-05-08T11:50:22.000Z | problemes/probleme2xx/probleme280.cpp | ZongoForSpeed/ProjectEuler | 2e2d45f984d48a1da8275886c976f909a0de94ce | [
"MIT"
] | null | null | null | problemes/probleme2xx/probleme280.cpp | ZongoForSpeed/ProjectEuler | 2e2d45f984d48a1da8275886c976f909a0de94ce | [
"MIT"
] | null | null | null | #include "problemes.h"
#include "arithmetique.h"
#include "matrice.h"
#include <bitset>
typedef unsigned long long nombre;
typedef std::vector<nombre> vecteur;
namespace {
long double algorithme(size_t sx, size_t sy, const std::bitset<5> &haut, const std::bitset<5> &bas) {
static std::map<std::tuple<size_t, size_t, size_t, size_t>, long double> cache;
auto clef = std::make_tuple(sx, sy, haut.to_ulong(), bas.to_ulong());
if (auto it = cache.find(clef);it != cache.end())
return it->second;
matrice::matrice<long double> A(25, 25, 0);
matrice::vecteur<long double> b(25, 0);
for (size_t x = 0; x < 5; ++x)
for (size_t y = 0; y < 5; ++y) {
size_t p = x + 5 * y;
A(p, p) = 1;
if (y == 0 && bas.test(x)) {
if (haut.none())
continue;
auto _bas = bas;
_bas.reset(x);
b(p) = algorithme(x, 4 - y, _bas, haut);
continue;
}
size_t t = 0;
if (x < 4) ++t;
if (x > 0) ++t;
if (y < 4) ++t;
if (y > 0) ++t;
long double f = 1.0L / t;
b(p) = 1;
if (x < 4) A(p, x + 1 + y * 5) = -f;
if (x > 0) A(p, x - 1 + y * 5) = -f;
if (y < 4) A(p, x + y * 5 + 5) = -f;
if (y > 0) A(p, x + y * 5 - 5) = -f;
}
matrice::vecteur<long double> c(25, 0);
// Résolution système A.c = b
matrice::resolutionLU(A, b, c);
long double resultat = c(sx + sy * 5);
cache[clef] = resultat;
return resultat;
}
}
ENREGISTRER_PROBLEME(280, "Ant and seeds") {
// A laborious ant walks randomly on a 5x5 grid. The walk starts from the central square. At each step, the ant
// moves to an adjacent square at random, without leaving the grid; thus there are 2, 3 or 4 possible moves at each
// step depending on the ant's position.
//
// At the start of the walk, a seed is placed on each square of the bas row.
// When the ant isn't carrying a seed and reaches a square of the bas row containing a seed, it will start to carry
// the seed. The ant will drop the seed on the first empty square of the haut row it eventually reaches.
//
// What's the expected number of steps until all seeds have been dropped in the top row?
//
// Give your answer rounded to 6 decimal places.
long double resultat = algorithme(2, 2, 31, 31);
return std::to_fixed(resultat, 6);
}
| 34.435897 | 119 | 0.513403 |
235d71dcfee4547fcfa496000990df23095f64fe | 3,345 | cpp | C++ | RhythmGame/src/main/cpp/Game.cpp | Jacks0N23/trying_Google_Oboe | 999b2a3656daec2626be5ac253f0e4f002a401f5 | [
"Apache-2.0"
] | null | null | null | RhythmGame/src/main/cpp/Game.cpp | Jacks0N23/trying_Google_Oboe | 999b2a3656daec2626be5ac253f0e4f002a401f5 | [
"Apache-2.0"
] | null | null | null | RhythmGame/src/main/cpp/Game.cpp | Jacks0N23/trying_Google_Oboe | 999b2a3656daec2626be5ac253f0e4f002a401f5 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2018 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 <utils/logging.h>
#include <thread>
#include "Game.h"
Game::Game(AAssetManager *assetManager): mAssetManager(assetManager) {
}
void Game::start() {
mClap = SoundRecording::loadFromAssets(mAssetManager, "CLAP.raw");
mBackingTrack = SoundRecording::loadFromAssets(mAssetManager, "FUNKY_HOUSE.raw" );
mBackingTrack->setPlaying(true);
mBackingTrack->setLooping(true);
mMixer.addTrack(mClap);
mMixer.addTrack(mBackingTrack);
mClapEvents.push(0);
mClapEvents.push(24000);
mClapEvents.push(48000);
mClapWindows.push(96000);
mClapWindows.push(120000);
mClapWindows.push(144000);
AudioStreamBuilder builder;
builder.setFormat(AudioFormat::I16);
builder.setChannelCount(2);
builder.setSampleRate(48000);
builder.setCallback(this);
builder.setPerformanceMode(PerformanceMode::LowLatency);
builder.setSharingMode(SharingMode::Exclusive);
// Open the stream
Result result = builder.openStream(&mAudioStream);
if (result != Result::OK){
LOGE("Failed to open stream. Error: %s", convertToText(result));
}
mAudioStream->setBufferSizeInFrames(mAudioStream->getFramesPerBurst() * 2);
// Start the stream
result = mAudioStream->requestStart();
if (result != Result::OK){
LOGE("Failed to start stream. Error: %s", convertToText(result));
}
}
void Game::tap(int64_t eventTimeAsUptime) {
mClap->setPlaying(true);
int64_t nextClapWindowFrame;
if (mClapWindows.pop(nextClapWindowFrame)){
int64_t frameDelta = nextClapWindowFrame - mCurrentFrame;
int64_t timeDelta = convertFramesToMillis(frameDelta, kSampleRateHz);
int64_t windowTime = mLastUpdateTime + timeDelta;
TapResult result = getTapResult(eventTimeAsUptime, windowTime);
mUiEvents.push(result);
}
}
void Game::tick(){
TapResult r;
if (mUiEvents.pop(r)) {
renderEvent(r);
} else {
SetGLScreenColor(kScreenBackgroundColor);
}
}
void Game::onSurfaceCreated() {
SetGLScreenColor(kScreenBackgroundColor);
}
void Game::onSurfaceChanged(int widthInPixels, int heightInPixels) {
}
void Game::onSurfaceDestroyed() {
}
DataCallbackResult Game::onAudioReady(AudioStream *oboeStream, void *audioData, int32_t numFrames) {
int64_t nextClapEvent;
for (int i = 0; i < numFrames; ++i) {
if (mClapEvents.peek(nextClapEvent) && mCurrentFrame == nextClapEvent){
mClap->setPlaying(true);
mClapEvents.pop(nextClapEvent);
}
mMixer.renderAudio(static_cast<int16_t*>(audioData)+(kChannelCount*i), 1);
mCurrentFrame++;
}
mLastUpdateTime = nowUptimeMillis();
return DataCallbackResult::Continue;
}
| 30.688073 | 100 | 0.703139 |
235d7868e431534664a820838212d93d28440767 | 7,370 | cpp | C++ | PhysicsEngine/ModulePhysics.cpp | bielrabasa/PhysicsEngine | ef3bc64c419a6da4ae234873e3d9da8c196197ec | [
"MIT"
] | 1 | 2021-12-27T15:12:27.000Z | 2021-12-27T15:12:27.000Z | PhysicsEngine/ModulePhysics.cpp | bielrabasa/PhysicsEngine | ef3bc64c419a6da4ae234873e3d9da8c196197ec | [
"MIT"
] | null | null | null | PhysicsEngine/ModulePhysics.cpp | bielrabasa/PhysicsEngine | ef3bc64c419a6da4ae234873e3d9da8c196197ec | [
"MIT"
] | null | null | null | #include "Globals.h"
#include "Application.h"
#include "ModulePhysics.h"
#include "math.h"
ModulePhysics::ModulePhysics(Application* app, bool start_enabled) : Module(app, start_enabled)
{
debug = true;
}
ModulePhysics::~ModulePhysics()
{
}
bool ModulePhysics::Start()
{
LOG("Creating Physics 2D environment");
cannon_ball_texture = App->textures->Load("Assets/cannon_ball.png");
return true;
}
update_status ModulePhysics::PreUpdate()
{
return UPDATE_CONTINUE;
}
update_status ModulePhysics::Update()
{
return UPDATE_CONTINUE;
}
update_status ModulePhysics::PostUpdate()
{
p2List_item<Ball*>* current_ball = balls.getFirst();
while (current_ball != NULL) {
if (current_ball->data->physics_enabled) {
ResetForces(current_ball->data);
ComputeForces(current_ball->data);
NewtonsLaw(current_ball->data);
Integrator(current_ball->data);
CollisionSolver(current_ball->data);
}
current_ball = current_ball->next;
}
//DeleteBalls();
DrawBalls();
DrawColliders();
//Debug
if(App->input->GetKey(SDL_SCANCODE_F1) == KEY_DOWN)
debug = !debug;
if(!debug)
return UPDATE_CONTINUE;
//Debug options (mode debug activated)
return UPDATE_CONTINUE;
}
bool ModulePhysics::CleanUp()
{
LOG("Destroying physics world");
return true;
}
void ModulePhysics::ResetForces(Ball* ball) {
ball->fx = ball->fy = 0.0;
ball->ax = ball->ay = 0.0;
}
void ModulePhysics::ComputeForces(Ball* ball) {
//Apply Gravity
ball->fgx = ball->mass * GRAVITY_X;
ball->fgy = ball->mass * GRAVITY_Y;
ball->fx += ball->fgx;
ball->fy += ball->fgy;
//Apply Aerodinamic lift / drag
}
void ModulePhysics::NewtonsLaw(Ball* ball) {
//ForceSum = m * a
ball->ax = ball->fx / ball->mass;
ball->ay = ball->fy / ball->mass;
}
void ModulePhysics::Integrator(Ball* ball) {
if (integrator_type == integrators::VERLET) {
ball->x += ball->vx * dt + 0.5 * ball->ax * dt * dt;
ball->y += ball->vy * dt + 0.5 * ball->ay * dt * dt;
ball->vx += ball->ax * dt;
ball->vy += ball->ay * dt;
}
if (integrator_type == integrators::EULER_BACK) {
}
if (integrator_type == integrators::EULER_FORW) {
}
}
void ModulePhysics::CollisionSolver(Ball* ball) {
p2List_item<Collider*>* current_collider = colliders.getFirst();
while (current_collider != NULL) {
if (current_collider->data->rectangle) {
if ((ball->x + ball->radius > current_collider->data->rect.x) &&
(ball->x - ball->radius < current_collider->data->rect.x + current_collider->data->rect.w) &&
(ball->y + ball->radius > current_collider->data->rect.y) &&
(ball->y - ball->radius < current_collider->data->rect.y + current_collider->data->rect.h)) {
if ((ball->x + ball->radius > current_collider->data->rect.x) &&
(ball->x - ball->radius < current_collider->data->rect.x + current_collider->data->rect.w) &&
(ball->y + ball->radius - ball->vy > current_collider->data->rect.y) &&
(ball->y - ball->radius - ball->vy < current_collider->data->rect.y + current_collider->data->rect.h)) { //Horizontal Colision
if (ball->vx > 0) { //Right colision
ball->x -= 2 * (ball->x - (current_collider->data->rect.x - ball->radius));
}
else { //Left colision
ball->x += 2 * (-ball->x + (current_collider->data->rect.x + current_collider->data->rect.w + ball->radius));
}
ball->vy = ball->vy * ball->cr;
ball->vx = -ball->vx * ball->cr;
}
else if ((ball->x + ball->radius - ball->vx > current_collider->data->rect.x) &&
(ball->x - ball->radius - ball->vx < current_collider->data->rect.x + current_collider->data->rect.w) &&
(ball->y + ball->radius > current_collider->data->rect.y) &&
(ball->y - ball->radius < current_collider->data->rect.y + current_collider->data->rect.h)) { //Vertical Colision
if (ball->vy > 0) { //Floor colision
ball->y -= 2*(ball->y - (current_collider->data->rect.y - ball->radius));
}
else { //Ceiling colision
ball->y = current_collider->data->rect.y + (-ball->y + (current_collider->data->rect.y + current_collider->data->rect.h));
}
ball->vy = -ball->vy * ball->cr;
ball->vx = ball->vx * ball->cr;
}
else {//diagonal colision FUYM
if (ball->vy > 0) { //floor colision
ball->y = current_collider->data->rect.y - ball->radius;
}
else { //ceiling colision
ball->y = current_collider->data->rect.y + current_collider->data->rect.h + ball->radius;
}
ball->vy = -ball->vy * ball->cr;
ball->vx = -ball->vx * ball->cr;
}
}
}
else { //CIRCLE
double vecX = ball->x - current_collider->data->rect.x;
double vecY = ball->y - current_collider->data->rect.y;
double distance = sqrt(vecX * vecX + vecY * vecY);
if (current_collider->data->r + ball->radius > distance) { //Ball colliding ARREGLAR
//unitary vector
vecX = vecX / distance;
vecY = vecY / distance;
//tp out
ball->x = current_collider->data->rect.x + vecX * (current_collider->data->r + ball->radius);
ball->y = current_collider->data->rect.y + vecY * (current_collider->data->r + ball->radius);
//solver
double vector[2] = { ball->x - current_collider->data->rect.x,
ball->y - current_collider->data->rect.y };
double dotProduct = (ball->vx * vector[0]) + (ball->vy * vector[1]);
double vectorModule = sqrt((vector[0] * vector[0]) + (vector[1] * vector[1]));
ball->vx += -2 * (dotProduct / (vectorModule * vectorModule)) * vector[0] * ball->cr;
ball->vy += -2 * (dotProduct / (vectorModule * vectorModule)) * vector[1] * ball->cr;
}
}
current_collider = current_collider->next;
}
}
void ModulePhysics::DeleteBalls() {
p2List_item<Ball*>* current_ball = balls.getFirst();
while (current_ball != NULL) {
if (current_ball->data->y > 700) {
Ball* b = current_ball->data;
current_ball = current_ball->next;
balls.del(balls.findNode(b));
delete b;
}
else {
current_ball = current_ball->next;
}
}
}
void ModulePhysics::DeleteAllBalls() {
p2List_item<Ball*>* current_ball = balls.getFirst();
while (current_ball != NULL) {
Ball* b = current_ball->data;
current_ball = current_ball->next;
balls.del(balls.findNode(b));
delete b;
}
}
void ModulePhysics::DisableEnablePhysics() {
p2List_item<Ball*>* current_ball = balls.getFirst();
while (current_ball != NULL) {
current_ball->data->physics_enabled = !current_ball->data->physics_enabled;
current_ball = current_ball->next;
}
}
void ModulePhysics::DrawBalls() {
p2List_item<Ball*>* current_ball = balls.getFirst();
while (current_ball != NULL) {
//App->renderer->Blit(cannon_ball_texture, current_ball->data->x - 16, current_ball->data->y - 16, NULL, 2);
App->renderer->DrawCircle(current_ball->data->x, current_ball->data->y, current_ball->data->radius, 250, 250, 250);
current_ball = current_ball->next;
}
}
void ModulePhysics::DrawColliders() {
p2List_item<Collider*>* current_collider = colliders.getFirst();
while (current_collider != NULL) {
if (current_collider->data->rectangle) { //RECTANGLE
App->renderer->DrawQuad(current_collider->data->rect, 100, 100, 100, 255, false);
}
else { //CIRCLE
App->renderer->DrawCircle(current_collider->data->rect.x,
current_collider->data->rect.y, current_collider->data->r, 100, 100, 100);
}
current_collider = current_collider->next;
}
}
| 30.580913 | 131 | 0.650204 |
235e62563051f8d69068c588855edf82d894b371 | 1,186 | cpp | C++ | graph-theory/diameter_tree.cpp | Swaraj-Deep/data-structures-algorithms | 0ffef6806a3e0348b56e685c73857c99341a39d8 | [
"MIT"
] | 2 | 2020-03-27T13:39:52.000Z | 2020-03-29T00:14:27.000Z | graph-theory/diameter_tree.cpp | Swaraj-Deep/data-structures | 0ffef6806a3e0348b56e685c73857c99341a39d8 | [
"MIT"
] | null | null | null | graph-theory/diameter_tree.cpp | Swaraj-Deep/data-structures | 0ffef6806a3e0348b56e685c73857c99341a39d8 | [
"MIT"
] | null | null | null | /*
***************************
* *
* Author: Swaraj Deep *
* *
***************************
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void dfs_search(vector<vector<int>> &tree, vector<bool> &visited, int vertex, int dist, int &max_dist, int &max_node)
{
visited[vertex] = true;
if (dist > max_dist)
{
max_dist = dist;
max_node = vertex;
}
for (int child : tree[vertex])
{
if (!visited[child])
{
dfs_search(tree, visited, child, dist + 1, max_dist, max_node);
}
}
}
// To get maximum distance we have to make two dfs calls
// 1 -> call to get the node with maxm distance from the passed root and in the
// 2 -> call we get the required diameter
int max_distance(vector<vector<int>> &tree, vector<bool> &visited, int vertex, int dist)
{
int max_dist = -1;
int max_node = -1;
dfs_search(tree, visited, vertex, dist, max_dist, max_node);
replace(visited.begin(), visited.end(), true, false);
max_dist = -1;
dfs_search(tree, visited, max_node, 0, max_dist, max_node);
return max_dist;
}
| 26.355556 | 117 | 0.572513 |
2360490613d578811f9ae04a22cea2c5c4490d44 | 5,267 | cxx | C++ | src/core/SessionWatchdogContext.cxx | Dynatrace/openkit-native | e072599196ea9086a2f9cfe67bae701d7d470fc0 | [
"Apache-2.0"
] | 8 | 2018-09-18T15:33:51.000Z | 2022-02-20T12:19:03.000Z | src/core/SessionWatchdogContext.cxx | Dynatrace/openkit-native | e072599196ea9086a2f9cfe67bae701d7d470fc0 | [
"Apache-2.0"
] | 2 | 2018-09-19T07:15:36.000Z | 2019-03-14T17:16:19.000Z | src/core/SessionWatchdogContext.cxx | Dynatrace/openkit-native | e072599196ea9086a2f9cfe67bae701d7d470fc0 | [
"Apache-2.0"
] | 15 | 2018-09-17T07:37:06.000Z | 2020-10-02T11:47:47.000Z | /**
* Copyright 2018-2021 Dynatrace LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "SessionWatchdogContext.h"
#include <algorithm>
#include <list>
using namespace core;
static const std::chrono::milliseconds DEFAULT_SLEEP_TIME_MILLISECONDS = std::chrono::seconds(5);
SessionWatchdogContext::SessionWatchdogContext(std::shared_ptr<providers::ITimingProvider> timingProvider,
std::shared_ptr<core::util::IInterruptibleThreadSuspender> threadSuspender)
: mIsShutdown(false)
, mTimingProvider(timingProvider)
, mThreadSuspender(threadSuspender)
, mSessionsToClose()
, mSessionsToSplitByTimeout()
{
}
const std::chrono::milliseconds& SessionWatchdogContext::getDefaultSleepTime()
{
return DEFAULT_SLEEP_TIME_MILLISECONDS;
}
void SessionWatchdogContext::execute()
{
auto durationToNextCloseInMillis = closeExpiredSessions();
auto durationToNextSplitInMillis = splitTimedOutSessions();
mThreadSuspender->sleep(std::min(durationToNextCloseInMillis, durationToNextSplitInMillis));
}
void SessionWatchdogContext::requestShutdown()
{
mIsShutdown = true;
mThreadSuspender->wakeup();
}
bool SessionWatchdogContext::isShutdownRequested()
{
return mIsShutdown;
}
void SessionWatchdogContext::closeOrEnqueueForClosing(std::shared_ptr<core::objects::SessionInternals> session, int64_t closeGracePeriodInMillis)
{
if (session->tryEnd())
{
return;
}
auto closeTime = mTimingProvider->provideTimestampInMilliseconds() + closeGracePeriodInMillis;
session->setSplitByEventsGracePeriodEndTimeInMillis(closeTime);
mSessionsToClose.put(session);
}
void SessionWatchdogContext::dequeueFromClosing(std::shared_ptr<core::objects::SessionInternals> session)
{
mSessionsToClose.remove(session);
}
void SessionWatchdogContext::addToSplitByTimeout(std::shared_ptr<core::objects::ISessionProxy> sessionProxy)
{
if (sessionProxy->isFinished())
{
return;
}
mSessionsToSplitByTimeout.put(sessionProxy);
}
void SessionWatchdogContext::removeFromSplitByTimeout(std::shared_ptr<core::objects::ISessionProxy> sessionProxy)
{
mSessionsToSplitByTimeout.remove(sessionProxy);
}
std::vector<std::shared_ptr<core::objects::SessionInternals>> SessionWatchdogContext::getSessionsToClose()
{
return mSessionsToClose.toStdVector();
}
std::vector<std::shared_ptr<core::objects::ISessionProxy>> SessionWatchdogContext::getSessionsToSplitByTimeout()
{
return mSessionsToSplitByTimeout.toStdVector();
}
int64_t SessionWatchdogContext::closeExpiredSessions()
{
auto sleepTimeInMillis = DEFAULT_SLEEP_TIME_MILLISECONDS.count();
auto allSessions = mSessionsToClose.toStdVector();
std::list<std::shared_ptr<core::objects::SessionInternals>> closableSessions;
// first iteration - get all closeable sessions
for (auto& session : allSessions)
{
auto nowInMillis = mTimingProvider->provideTimestampInMilliseconds();
auto gracePeriodEndTimeInMillis = session->getSplitByEventsGracePeriodEndTimeInMillis();
auto isGracePeriodExpired = gracePeriodEndTimeInMillis <= nowInMillis;
if (isGracePeriodExpired)
{
closableSessions.push_back(session);
continue;
}
auto sleepTimeToGracePeriodEndInMillis = gracePeriodEndTimeInMillis - nowInMillis;
sleepTimeInMillis = std::min(sleepTimeInMillis, sleepTimeToGracePeriodEndInMillis);
}
// remove the sessions
for (auto& session : closableSessions)
{
mSessionsToClose.remove(session);
session->end(false);
}
return sleepTimeInMillis;
}
int64_t SessionWatchdogContext::splitTimedOutSessions()
{
auto sleepTimeInMillis = DEFAULT_SLEEP_TIME_MILLISECONDS.count();
auto sessionProxiesToRemove = std::list<std::shared_ptr<core::objects::ISessionProxy>>();
auto allSessionProxies = mSessionsToSplitByTimeout.toStdVector();
// first iteration - get all session proxies that can be removed
for(auto& sessionProxy : allSessionProxies)
{
auto nextSessionSplitInMillis = sessionProxy->splitSessionByTime();
if (nextSessionSplitInMillis < 0)
{
sessionProxiesToRemove.push_back(sessionProxy);
continue;
}
auto nowInMillis = mTimingProvider->provideTimestampInMilliseconds();
auto durationToNextSplit = nextSessionSplitInMillis - nowInMillis;
if (durationToNextSplit < 0)
{
continue;
}
sleepTimeInMillis = std::min(sleepTimeInMillis, durationToNextSplit);
}
// remove previously identified session proxies
for(auto& sessionProxy : sessionProxiesToRemove)
{
mSessionsToSplitByTimeout.remove(sessionProxy);
}
return sleepTimeInMillis;
} | 31.538922 | 145 | 0.748813 |
236052da1cee9c60bc77d7d85ec7c9de2059bfe4 | 880 | hpp | C++ | src/Structures/SymbolBBox.hpp | Werni2A/O2CP | a20c0102e1c5aca35874cc6bc89f083c66dfeb0e | [
"MIT"
] | 5 | 2021-10-01T06:48:21.000Z | 2021-12-23T11:14:41.000Z | src/Structures/SymbolBBox.hpp | Werni2A/O2CP | a20c0102e1c5aca35874cc6bc89f083c66dfeb0e | [
"MIT"
] | 7 | 2021-09-26T19:53:53.000Z | 2022-01-06T13:04:03.000Z | src/Structures/SymbolBBox.hpp | Werni2A/O2CP | a20c0102e1c5aca35874cc6bc89f083c66dfeb0e | [
"MIT"
] | 1 | 2022-01-05T19:24:58.000Z | 2022-01-05T19:24:58.000Z | #ifndef SYMBOLBBOX_H
#define SYMBOLBBOX_H
#include <cstdint>
#include <iostream>
#include <ostream>
#include <string>
#include "../General.hpp"
struct SymbolBBox
{
int32_t x1;
int32_t y1;
int32_t x2;
int32_t y2;
};
[[maybe_unused]]
static std::string to_string(const SymbolBBox& aObj)
{
std::string str;
str += std::string(nameof::nameof_type<decltype(aObj)>()) + ":" + newLine();
str += indent(1) + "x1 = " + std::to_string(aObj.x1) + newLine();
str += indent(1) + "y1 = " + std::to_string(aObj.y1) + newLine();
str += indent(1) + "x2 = " + std::to_string(aObj.x2) + newLine();
str += indent(1) + "y2 = " + std::to_string(aObj.y2) + newLine();
return str;
}
[[maybe_unused]]
static std::ostream& operator<<(std::ostream& aOs, const SymbolBBox& aVal)
{
aOs << to_string(aVal);
return aOs;
}
#endif // SYMBOLBBOX_H | 18.723404 | 80 | 0.617045 |
23609737f9842ba0dbf84900221ba099a8bcf25a | 7,913 | cpp | C++ | src/kvstore/StatisticStore.cpp | MMyheart/nebula1.0 | e39fa11b88d5495e4d13cae3c14f39456b7b0629 | [
"Apache-2.0"
] | null | null | null | src/kvstore/StatisticStore.cpp | MMyheart/nebula1.0 | e39fa11b88d5495e4d13cae3c14f39456b7b0629 | [
"Apache-2.0"
] | null | null | null | src/kvstore/StatisticStore.cpp | MMyheart/nebula1.0 | e39fa11b88d5495e4d13cae3c14f39456b7b0629 | [
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2021 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License,
* attached with Common Clause Condition 1.0, found in the LICENSES directory.
*/
#include "kvstore/StatisticStore.h"
#include <rocksdb/convenience.h>
#include "base/Base.h"
#include "fs/FileUtils.h"
#include "kvstore/RocksEngine.h"
#include "kvstore/RocksEngineConfig.h"
namespace nebula {
namespace kvstore {
StatisticStore::~StatisticStore() {
dbs_.clear();
LOG(INFO) << "~StatisticStore()";
}
bool StatisticStore::init() {
auto rootPath = folly::stringPrintf("%s/nebula", dataPath_.c_str());
auto dirs = fs::FileUtils::listAllDirsInDir(rootPath.c_str());
for (auto& dir : dirs) {
GraphSpaceID spaceId;
try {
spaceId = folly::to<GraphSpaceID>(dir);
} catch (const std::exception& ex) {
LOG(ERROR) << "Data path invalid: " << ex.what();
return false;
}
std::string statisticPath =
folly::stringPrintf("%s/nebula/%d/statistic/data", dataPath_.c_str(), spaceId);
if (fs::FileUtils::fileType(statisticPath.c_str()) == fs::FileType::NOTEXIST) {
LOG(INFO) << "spaceID " << spaceId << " need not to statistic";
continue;
}
if (fs::FileUtils::fileType(statisticPath.c_str()) != fs::FileType::DIRECTORY) {
LOG(FATAL) << statisticPath << " is not directory";
}
dbs_[spaceId].reset(newDB(statisticPath));
}
return true;
}
void StatisticStore::stop() {
for (const auto& db : dbs_) {
rocksdb::CancelAllBackgroundWork(db.second.get(), true);
}
}
rocksdb::DB* StatisticStore::newDB(const std::string& path) {
rocksdb::Options options;
rocksdb::DB* db = nullptr;
rocksdb::Status status = initRocksdbOptions(options);
CHECK(status.ok());
status = rocksdb::DB::Open(options, path, &db);
if (status.IsNoSpace()) {
LOG(WARNING) << status.ToString();
} else {
CHECK(status.ok()) << status.ToString();
}
return db;
}
void StatisticStore::addStatistic(GraphSpaceID spaceId) {
folly::RWSpinLock::WriteHolder wh(&lock_);
if (this->dbs_.find(spaceId) != this->dbs_.end()) {
LOG(INFO) << "Space " << spaceId << " has statistic!";
return;
}
std::string statisticPath =
folly::stringPrintf("%s/nebula/%d/statistic/data", dataPath_.c_str(), spaceId);
if (!fs::FileUtils::makeDir(statisticPath)) {
LOG(FATAL) << "makeDir " << statisticPath << " failed";
}
LOG(INFO) << "Create statistic for space " << spaceId << ", dataPath=" << statisticPath;
dbs_[spaceId].reset(newDB(statisticPath));
}
ResultCode StatisticStore::setOption(GraphSpaceID spaceId,
const std::string& configKey,
const std::string& configValue) {
std::unordered_map<std::string, std::string> configOptions = {{configKey, configValue}};
rocksdb::Status status = dbs_[spaceId]->SetOptions(configOptions);
if (status.ok()) {
LOG(INFO) << "SetOption Succeeded: " << configKey << ":" << configValue;
return ResultCode::SUCCEEDED;
} else {
LOG(ERROR) << "SetOption Failed: " << configKey << ":" << configValue;
return ResultCode::ERR_INVALID_ARGUMENT;
}
}
ResultCode StatisticStore::setDBOption(GraphSpaceID spaceId,
const std::string& configKey,
const std::string& configValue) {
std::unordered_map<std::string, std::string> configOptions = {{configKey, configValue}};
rocksdb::Status status = dbs_[spaceId]->SetDBOptions(configOptions);
if (status.ok()) {
LOG(INFO) << "SetDBOption Succeeded: " << configKey << ":" << configValue;
return ResultCode::SUCCEEDED;
} else {
LOG(ERROR) << "SetDBOption Failed: " << configKey << ":" << configValue;
return ResultCode::ERR_INVALID_ARGUMENT;
}
}
ResultCode StatisticStore::compact(GraphSpaceID spaceId) {
rocksdb::CompactRangeOptions options;
rocksdb::Status status = dbs_[spaceId]->CompactRange(options, nullptr, nullptr);
if (status.ok()) {
return ResultCode::SUCCEEDED;
} else {
LOG(ERROR) << "CompactAll Failed: " << status.ToString();
return ResultCode::ERR_UNKNOWN;
}
}
ResultCode StatisticStore::flush(GraphSpaceID spaceId) {
rocksdb::FlushOptions options;
rocksdb::Status status = dbs_[spaceId]->Flush(options);
if (status.ok()) {
return ResultCode::SUCCEEDED;
} else {
LOG(ERROR) << "Flush Failed: " << status.ToString();
return ResultCode::ERR_UNKNOWN;
}
}
ResultCode StatisticStore::multiRemove(GraphSpaceID spaceId, std::vector<std::string> keys) {
rocksdb::WriteBatch deletes(100000);
for (size_t i = 0; i < keys.size(); i++) {
deletes.Delete(keys[i]);
}
rocksdb::WriteOptions options;
rocksdb::Status status = dbs_[spaceId]->Write(options, &deletes);
if (status.ok()) {
return ResultCode::SUCCEEDED;
} else {
VLOG(3) << "MultiRemove Failed: " << status.ToString();
return ResultCode::ERR_UNKNOWN;
}
}
ResultCode StatisticStore::multiPut(GraphSpaceID spaceId, std::vector<KV> kvs) {
rocksdb::WriteBatch updates(100000);
for (size_t i = 0; i < kvs.size(); i++) {
updates.Put(kvs[i].first, kvs[i].second);
}
rocksdb::WriteOptions options;
rocksdb::Status status = dbs_[spaceId]->Write(options, &updates);
if (status.ok()) {
return ResultCode::SUCCEEDED;
} else {
VLOG(3) << "MultiPut Failed: " << status.ToString();
return ResultCode::ERR_UNKNOWN;
}
}
ResultCode StatisticStore::put(GraphSpaceID spaceId, KV kv) {
rocksdb::WriteOptions options;
rocksdb::Status status = dbs_[spaceId]->Put(options, kv.first, kv.second);
if (status.ok()) {
return ResultCode::SUCCEEDED;
} else {
VLOG(3) << "Put Failed: " << kv.first << status.ToString();
return ResultCode::ERR_UNKNOWN;
}
}
ResultCode StatisticStore::get(GraphSpaceID spaceId, std::string key, std::string* value) {
rocksdb::ReadOptions options;
rocksdb::Status status = dbs_[spaceId]->Get(options, rocksdb::Slice(key), value);
if (status.ok()) {
return ResultCode::SUCCEEDED;
} else if (status.IsNotFound()) {
VLOG(3) << "Get: " << key << " Not Found";
return ResultCode::ERR_KEY_NOT_FOUND;
} else {
VLOG(3) << "Get Failed: " << key << " " << status.ToString();
return ResultCode::ERR_UNKNOWN;
}
}
ResultCode StatisticStore::multiGet(GraphSpaceID spaceId,
const std::vector<std::string>& keys,
std::vector<std::string>* values) {
rocksdb::ReadOptions options;
std::vector<rocksdb::Slice> slices;
for (size_t index = 0; index < keys.size(); index++) {
slices.emplace_back(keys[index]);
}
auto status = dbs_[spaceId]->MultiGet(options, slices, values);
auto allExist = std::all_of(status.begin(), status.end(), [](const auto& s) { return s.ok(); });
if (allExist) {
return ResultCode::SUCCEEDED;
} else {
return ResultCode::ERR_PARTIAL_RESULT;
}
}
ResultCode StatisticStore::prefix(GraphSpaceID spaceId,
const std::string& prefix,
std::unique_ptr<KVIterator>* storageIter) {
rocksdb::ReadOptions options;
options.prefix_same_as_start = true;
rocksdb::Iterator* iter = dbs_[spaceId]->NewIterator(options);
if (iter) {
iter->Seek(rocksdb::Slice(prefix));
}
*storageIter = std::make_unique<RocksPrefixIter>(iter, prefix);
return ResultCode::SUCCEEDED;
}
} // namespace kvstore
} // namespace nebula
| 35.80543 | 100 | 0.614558 |
23625249e60afe425625fa27e472e0f1fd16cf6e | 6,196 | cpp | C++ | ui-qt/Pretreatment/GrayHistogram/Roi/LabelGrayHistogram.cpp | qianyongjun123/FPGA-Industrial-Smart-Camera | 54b3e2c2661cf7f6774a7fb4d6ae637fa73cba32 | [
"MIT"
] | 1 | 2017-12-28T08:08:02.000Z | 2017-12-28T08:08:02.000Z | ui-qt/Pretreatment/GrayHistogram/Roi/LabelGrayHistogram.cpp | qianyongjun123/FPGA-Industrial-Smart-Camera | 54b3e2c2661cf7f6774a7fb4d6ae637fa73cba32 | [
"MIT"
] | null | null | null | ui-qt/Pretreatment/GrayHistogram/Roi/LabelGrayHistogram.cpp | qianyongjun123/FPGA-Industrial-Smart-Camera | 54b3e2c2661cf7f6774a7fb4d6ae637fa73cba32 | [
"MIT"
] | 3 | 2017-12-28T08:08:05.000Z | 2021-11-12T07:59:13.000Z |
#include "LabelGrayHistogram.h"
#include <qdebug.h>
#include <QPen>
#if _MSC_VER >= 1600
#pragma execution_character_set("utf-8")
#endif
#define LINEWIDTH 30
LabelGrayHistogram::LabelGrayHistogram(QWidget *parent) : QLabel(parent)
{
m_max =100;
m_mode = -1;
for(int i=0; i<2560;i++)
{
m_grade[i] = 0;
}
}
void LabelGrayHistogram::mousePressEvent(QMouseEvent *e)
{
QLabel::mousePressEvent(e);
}
void LabelGrayHistogram::mouseMoveEvent(QMouseEvent *e)
{
QLabel::mouseMoveEvent(e);
}
void LabelGrayHistogram::mouseReleaseEvent(QMouseEvent *e)
{
QLabel::mouseReleaseEvent(e);
}
void LabelGrayHistogram::PaintGray(QPainter *painter)
{
painter->drawLine(100,400,610,400);//x轴
painter->drawLine(600,390,610,400);
painter->drawLine(600,410,610,400);
painter->drawLine(100,400,100,100);//y轴
painter->drawLine(90,110,100,100);
painter->drawLine(110,110,100,100);
painter->drawText(90,420,"0");
painter->drawText(610,420,"255");
int i = 0;
for(i= 1; i< 15;i++)
{
painter->drawLine(100+i*34,400,100+i*34,395);
painter->drawText(100+i*34-5,420,QString::number(15+16*(i-1)));
}
int iGrade = this->m_max/10;
//painter->drawText(60,100+5,QString::number(m_max));
//painter->drawText(100,100,QString::number(m_max));
for(i = 1;i<10;i++)
{
painter->drawLine(100,100+i*30,105,100+i*30);
//painter->drawText(60,100+i*30+5,QString::number(m_max-iGrade*i));
/*QString strTemp = QString::number(10-i);
strTemp +="/10";
painter->drawText(60,100+i*30+5,strTemp);*/
}
float fScale = 0.0;
fScale = 300.0/m_max*1.0;
int iMax = m_grade[0];
int iIndex = 0;
for(i = 0; i<255;i++)
{
if(m_grade[i] > iMax)
{
iMax = m_grade[i];
iIndex = i;
}
painter->drawLine(100+i*2,400-m_grade[i]*fScale,100+i*2+1,400-m_grade[i+1]*fScale);
}
painter->drawText(100+iIndex*2,400-m_grade[iIndex]*fScale,QString::number(m_max));
}
void LabelGrayHistogram::PaintByColoum(QPainter *painter)
{
painter->drawLine(0,400,640,400);//x轴
painter->drawLine(630,390,640,400);
painter->drawLine(630,410,640,400);
painter->drawLine(0,400,0,100);//y轴
painter->drawLine(-10,110,0,100);
painter->drawLine(10,110,0,100);
painter->drawText(3,420,"0");
painter->drawText(610,420,"640");
int i = 0;
for(i= 1; i< 15;i++)
{
painter->drawLine(i*42,400,i*42,395);
painter->drawText(i*42-8,420,QString::number(42+42*(i-1)));
}
int iGrade = this->m_max/10;
//painter->drawText(0,100+5,QString::number(m_max));
//painter->drawText(0,100,QString::number(m_max));
for(i = 1;i<10;i++)
{
painter->drawLine(0,100+i*30,5,100+i*30);
//painter->drawText(5,100+i*30+10,QString::number(m_max-iGrade*i));
/*QString strTemp = QString::number(10-i);
strTemp +="/10";
painter->drawText(5,100+i*30+5,strTemp);*/
}
float fScale = 0.0;
fScale = 300.0/m_max*1.0;
int iMax = m_grade[0];
int iIndex = 0;
for(i = 0; i<639;i++)
{
if(m_times == 4)
painter->drawLine(i,400-m_grade[i*4]*fScale,i+1,400-m_grade[i*4+4]*fScale);
else if(m_times == 2)
painter->drawLine(i,400-m_grade[i*2]*fScale,i+1,400-m_grade[i*2+2]*fScale);
else if(m_times == 1)
painter->drawLine(i,400-m_grade[i]*fScale,i+1,400-m_grade[i+1]*fScale);
if(m_grade[i*m_times] > iMax)
{
iMax = m_grade[i*m_times];
iIndex = i;
}
}
painter->drawText(iIndex,400-m_grade[iIndex*m_times]*fScale,QString::number(m_max));
}
void LabelGrayHistogram::PaintByRow(QPainter *painter)
{
painter->drawLine(100,400,580,400);//x轴
painter->drawLine(570,390,580,400);
painter->drawLine(570,410,580,400);
painter->drawLine(100,400,100,100);//y轴
painter->drawLine(90,110,100,100);
painter->drawLine(110,110,100,100);
painter->drawText(90,420,"0");
painter->drawText(580,420,"480");
int i = 0;
for(i= 1; i< 15;i++)
{
painter->drawLine(100+i*32,400,100+i*32,395);
painter->drawText(100+i*32-5,420,QString::number(32+32*(i-1)));
}
int iGrade = this->m_max/10;
//painter->drawText(60,100+5,QString::number(m_max));
//painter->drawText(100,100,QString::number(m_max));
for(i = 1;i<10;i++)
{
painter->drawLine(100,100+i*30,105,100+i*30);
//painter->drawText(60,100+i*30+5,QString::number(m_max-iGrade*i));
/*QString strTemp = QString::number(10-i);
strTemp += "/10";
painter->drawText(60,100+i*30+5,strTemp);*/
}
float fScale = 0.0;
fScale = 300.0/m_max*1.0;
int iMax = m_grade[0];
int iIndex = 0;
for(i = 0; i<479;i++)
{
if(m_times == 1)
painter->drawLine(100+i,400-m_grade[i]*fScale,100+i+1,400-m_grade[i+1]*fScale);
else if(m_times == 2)
painter->drawLine(100+i,400-m_grade[i*2]*fScale,100+i+1,400-m_grade[i*2+2]*fScale);
else if(m_times == 4)
painter->drawLine(100+i,400-m_grade[i*4]*fScale,100+i+1,400-m_grade[i*4+4]*fScale);
if(m_grade[i*m_times] > iMax)
{
iMax = m_grade[i*m_times];
iIndex = i;
}
}
painter->drawText(100+iIndex,400-m_grade[iIndex*m_times]*fScale,QString::number(m_max));
}
void LabelGrayHistogram::paintEvent(QPaintEvent *e)
{
QLabel::paintEvent(e);
QPainter painter(this);
QPen pen;
pen.setColor(Qt::red);
pen.setWidth(1);
painter.setPen(pen);
if(m_mode == 0)
{
PaintGray(&painter);
}else if(m_mode == 1) //列
{
PaintByColoum(&painter);
}else if(m_mode == 2) //行
{
PaintByRow(&painter);
}
}
void LabelGrayHistogram::SetGrade(unsigned int *gradeArr, int size, int mode,int times)
{
this->m_size = size;
this->m_mode = mode;
m_times = times;
m_max = gradeArr[0];
for(int i = 0;i<size;i++)
{
this->m_grade[i] = gradeArr[i];
if(gradeArr[i] > m_max)
{
m_max = gradeArr[i];
}
}
update();
}
| 27.784753 | 95 | 0.589413 |
2367f31d4ca3bf43363e4d2c5415ded954b3c0b7 | 21,908 | cxx | C++ | StRoot/Stl3Util/gl3/gl3Conductor.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | 2 | 2018-12-24T19:37:00.000Z | 2022-02-28T06:57:20.000Z | StRoot/Stl3Util/gl3/gl3Conductor.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | StRoot/Stl3Util/gl3/gl3Conductor.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | //:>------------------------------------------------------------------
//: FILE: gl3Conductor.cc
//: HISTORY:
//: 1 feb 2000 version 1.00
//: 6 jul 2000 add St_l3_Coordinate_Transformer
//: 27 jul 2000 add print timing
//:<------------------------------------------------------------------
#include "Stl3Util/gl3/gl3Conductor.h"
#include "Stl3Util/base/L3swap.h"
#include "Stl3Util/base/realcc.h"
#include "Stl3Util/base/FtfLog.h"
#include <time.h>
#include <errno.h>
#include <netinet/in.h>
#include <unistd.h>
#ifdef GL3ONLINE
#include <sys/types.h>
#include <sys/socket.h>
#include <fcntl.h>
#endif
//VP extern int errno;
//####################################################################
//
//####################################################################
gl3Conductor::gl3Conductor (void){
unsigned int start = realcc();
sleep(1);
unsigned int stop = realcc();
ccPerMs = (double)(stop-start)/1000.;
//ftfLog("gl3Conductor: estimated CPU freq: %7.3f MHz\n", ccPerMs/1000.);
nAlgorithms = 0;
}
//####################################################################
//
//####################################################################
gl3Conductor::~gl3Conductor ( ) {
if ( event != NULL ) delete[] event ;
clearAlgorithms();
if ( algorithm != NULL ) delete algorithm;
if ( summary != NULL ) delete[] summary ;
if ( summaryData != NULL ) free (summaryData) ;
delete []tokenIndex ;
}
//####################################################################
//
//####################################################################
int gl3Conductor::configure (L3_CFG *cfg)
{
clearAlgorithms();
if(cfg == NULL || cfg == (L3_CFG *)-1) {
ftfLog("gl3Conductor::configure: No configuration information found.\n");
return 1;
}
L3_ALGORITHMS *algos = cfg->l3_setup.gl3_algorithms;
for (int i=0; i<GL3_ALG_MAX_NUM; i++) {
if(ntohl(algos[i].alg_id) != 0) {
gl3Algorithm *algo =
gl3InstantiateAlgorithm(ntohl(algos[i].alg_id));
if (algo == NULL) {
ftfLog("gl3Conductor::configure: Instantiation of algorithm #%d failed.\n", i);
return 1;
}
algo->setScaling(ntohl(algos[i].preScale),
ntohl(algos[i].postScale));
if (algo->setParameters(ntohl(algos[i].GI1),
ntohl(algos[i].GI2),
ntohl(algos[i].GI3),
ntohl(algos[i].GI4),
ntohl(algos[i].GI5),
fswap(algos[i].GF1),
fswap(algos[i].GF2),
fswap(algos[i].GF3),
fswap(algos[i].GF4),
fswap(algos[i].GF5))) {
ftfLog("gl3Conductor::configure: Invalid parameters for algorithm %s (ID %d)", algo->getAlgorithmName(), algo->getAlgorithmID());
return 1;
}
if(add(algo) != 0) {
ftfLog("gl3Conductor::configure: Appending algorithm %s (ID %i) to list failed.\n",
algo->getAlgorithmName(), algo->getAlgorithmID());
return 1;
}
algo->showConfiguration();
}
}
//ftfLog("gl3Conductor::configure: Done.\n");
return 0;
}
//####################################################################
//
//####################################################################
int gl3Conductor::add( gl3Algorithm* module ) {
if ( nAlgorithms >= maxAlgorithms ) {
ftfLog ( "gl3Conductor::add: Max. number of algorithms reached\n" ) ;
return 1;
}
algorithm[nAlgorithms] = module ;
nAlgorithms++ ;
return 0 ;
}
//####################################################################
//
//####################################################################
void gl3Conductor::clearAlgorithms()
{
for (int i =0; i<nAlgorithms; i++) {
if(algorithm[i]) {
delete algorithm[i];
algorithm[i] = NULL;
}
}
nAlgorithms = 0;
}
//####################################################################
//
//####################################################################
int gl3Conductor::checkHistoRequest ( ) {
#ifdef GL3ONLINE
struct sockaddr_in remoteAddress; /* connector's address information */
socklen_t sin_size = sizeof(struct sockaddr_in);
if ((remoteSocket = accept(socketFd, (struct sockaddr *)&remoteAddress,
&sin_size)) == -1) {
return 0;
}
const int maxBytes = 100000 ;
char* buffer = new char[maxBytes];
int nBytes = writeHistos ( maxBytes, buffer ) ;
if ( nBytes < 0 ) {
ftfLog ( "gl3Conductor::checkHistoRequest: buffer too small \n " ) ;
return 1 ;
}
int nSend = send(remoteSocket, buffer, nBytes, 0 ) ;
ftfLog ( "gl3Conductor: %d out of %d bytes sent\n ", nSend, nBytes ) ;
if ( nSend == -1) {
perror("send");
return 1 ;
}
delete []buffer ;
#endif
return 0 ;
}
//####################################################################
//
//####################################################################
int gl3Conductor::end ( ){
#ifdef GL3ONLINE
close ( socketFd ) ;
#endif
for ( int i = 0 ; i < nAlgorithms ; i++ ) {
algorithm[i]->end( );
}
return 0 ;
}
//####################################################################
//
//####################################################################
gl3Event* gl3Conductor::getEvent ( int token ) {
int index = getTokenIndex(token) ;
if (index < 0)
return NULL;
else
return &(event[index]) ;
}
//####################################################################
//
//####################################################################
int gl3Conductor::init ( ){
ftfLog("gl3Conductor::init: %d algos\n", nAlgorithms);
#ifdef GL3ONLINE
l3Rates = new gl3Histo("l3rates",
"L3 trigger rates",
nAlgorithms+2, -2.5, (double)nAlgorithms-0.5);
histoList.push_back(l3Rates);
allocateTimingHistos();
#endif
for ( int i = 0 ; i < nAlgorithms ; i++ ) {
algorithm[i]->init();
}
nReco = 0;
return 0 ;
}
//####################################################################
//
//####################################################################
int gl3Conductor::processEvent(EventDescriptor *desc,
L3_P* l3data,
TrgSumData* trgSum,
RawTrgDet* trgRaw)
{
resetTimer();
// If we get a EventDescriptor, it should be for the right token
if ( desc && desc->token != l3data->bh.token ) {
ftfLog ("gl3Conductor::readEvent: token mismatch (%d and %d)\n",
desc->token, l3data->bh.token);
return -1;
}
int token = l3data->bh.token;
if ( token < 0 || token > maxTokens ){
ftfLog ("gl3Conductor::readEvent: %d token out of bounds\n", token );
return -1;
}
// Look for a free event container
int index = getFreeEventIndex();
if ( index < 0 ) {
ftfLog ( "gl3Conductor::readEvent: No free event container \n" ) ;
return -1;
}
tokenIndex[token] = index;
// Read Event and check if errors occured
if (event[index].readEventDescriptor(desc) != 0) {
ftfLog ( "gl3Conductor::processEvent: error reading EventDescriptor\n" ) ;
return -1;
}
if ( event[index].getTrgCmd() == 0 ||
event[index].getTrgCmd() == 1 ||
event[index].getTrgCmd() == 2 ||
event[index].getTrgCmd() == 3 ) {
ftfLog ("gl3Conductor::processEvent: Trigger Command 0,1,2 or 3 received\n");
return 2; // hard trigger
}
if ( event[index].getTrgCmd() == 5 ||
event[index].getTrgCmd() == 6 ||
event[index].getTrgCmd() == 7 ) {
ftfLog ("gl3Conductor::processEvent: Trigger Command 5,6 or 7 received - unknown physics run type\n");
// continue reading data and running algorithms
}
// Read L3 data
if ( event[index].readL3Data(l3data) != 0 ) {
ftfLog ( "gl3Conductor::processEvent: error reading L3 data\n" ) ;
return -1;
}
// Do not ontinue (run algorithms) if we have a laser or pulser event.
// Return decision = 1 to ensure the event is built.
if ( event[index].getTrgCmd() >= 8 ) {
// Laser trigger
return 2; // hard trigger
}
timingMark(); // step 1
if ( event[index].readTrgData(trgSum, trgRaw) != 0 ) {
ftfLog ( "gl3Conductor::processEvent: error reading TRG data\n" ) ;
return -1;
}
timingMark(); // step 2
// The preparation is done, now let's run the algorithms.
int decision = 0;
for ( int i = 0 ; i < nAlgorithms ; i++ ) {
int alg_decision = algorithm[i]->process( &(event[index]));
if (alg_decision > decision) {
decision = alg_decision;
}
timingMark(); // step 3...2+nAlgorithms
}
// Now increment the counters for the algorithms. Can't be done
// earlier, because if an event crashes, we do not want to have
// any counters incremented
nReco++;
for ( int i = 0 ; i < nAlgorithms ; i++ ) {
algorithm[i]->incrementCounters();
}
collectSummary(token);
timingMark(); // step 4+nAlgorithms
fillTimingHistos();
#ifdef GL3ONLINE
l3Rates->Fill(-2); // event was processed
if (decision) {
l3Rates->Fill(-1); // event was triggered for any reason
for (int i=0; i<nAlgorithms;i++) {
if (summaryData[index].alg[i].accept)
l3Rates->Fill(i); // accepted because of algorithm #i
// cout << "alg #" << i << ": "
// << summaryData[index].alg[i].accept
// << " histo: " << l3Rates->GetY(i+2)
// << endl;
}
}
if ( communicationsFlag ) {
checkHistoRequest();
}
#endif
if (nAlgorithms == 0) decision=1; // no algs -> trigger everything
return decision ;
}
//####################################################################
// Copy the previously filled summary data to the requested locations
//####################################################################
int gl3Conductor::fillSummary(int token,
struct L3_summary* summaryDest,
struct L3_SUMD *summaryDataDest)
{
int index = getTokenIndex(token);
if (index < 0) return 1;
memcpy(summaryDest, &summary[index], sizeof(L3_summary));
memcpy(summaryDataDest, &summaryData[index],
summaryData[index].bh.length*4);
return 0;
}
//####################################################################
// Fill summary information for a given token
//####################################################################
int gl3Conductor::collectSummary(int token)
{
int index = tokenIndex[token];
if (index < 0) return 1;
sprintf(summaryData->bh.bank_type, CHAR_L3_SUMD);
summaryData[index].bh.length =
(sizeof(L3_SUMD) + (nAlgorithms-1)*sizeof(algorithm_data))/4;
summaryData[index].bh.bank_id = 0;
summaryData[index].bh.format_ver = 0;
summaryData[index].bh.byte_order = DAQ_RAW_FORMAT_ORDER;
summaryData[index].bh.format_number = 0;
summaryData[index].bh.token = token;
summaryData[index].bh.w9 = DAQ_RAW_FORMAT_WORD9;
summaryData[index].bh.crc = 0;
summaryData[index].nProcessed = 0;
summaryData[index].nReconstructed = nReco;
summaryData[index].nAlg = nAlgorithms;
summary[index].accept = 0;
summary[index].build = 0;
summary[index].on = 0;
for (int i = 0; i < nAlgorithms; i++) {
algorithm[i]->fillSummary(&summaryData[index].alg[i]);
if(summaryData[index].alg[i].on)
summary[index].on |= 1<<i;
if(summaryData[index].alg[i].accept)
summary[index].accept |= 1<<i;
if(summaryData[index].alg[i].build)
summary[index].build |= 1<<i;
}
summary[index].nTracks = event[index].getNTracks();
return 0;
}
//####################################################################
//
//####################################################################
int gl3Conductor::releaseToken ( int token ) {
int index = getTokenIndex(token);
if (index < 0) return 1;
event[index].resetEvent();
return 0;
}
//####################################################################
//
//####################################################################
int gl3Conductor::resetHistos ( ) {
list<gl3Histo*>::iterator histo;
for(histo=histoList.begin(); histo!=histoList.end(); histo++) {
(*histo)->Reset();
}
return 0 ;
}//####################################################################
//
//####################################################################
int gl3Conductor::runStart ( int _runNumber ) {
runNumber = _runNumber ;
for ( int i = 0 ; i < nAlgorithms ; i++ ) {
algorithm[i]->init();
}
nReco = 0;
return resetHistos ( ) ;
}
//####################################################################
//
//####################################################################
int gl3Conductor::runEnd ( ) {
for ( int i = 0 ; i < nAlgorithms ; i++ ) {
algorithm[i]->end( );
}
return 0 ;
}
//####################################################################
//
//####################################################################
int gl3Conductor::setCommunications ( ){
//
#ifdef GL3ONLINE
struct sockaddr_in gl3Address; /* my address information */
gl3Port = 3333 ;
int backLog = 5 ; // how many pending connections will hold
if ((socketFd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
ftfLog("setCommunications socket: %s",strerror(errno) );
return -1;
}
fcntl(socketFd, F_SETFL, O_NONBLOCK);
gl3Address.sin_family = AF_INET; /* host byte order */
gl3Address.sin_port = htons(gl3Port); /* short, network byte order */
gl3Address.sin_addr.s_addr = INADDR_ANY;/* automatically fill with my IP */
bzero(&(gl3Address.sin_zero), 8); /* zero the rest of the struct */
if (bind(socketFd, (struct sockaddr *)&gl3Address,
sizeof(struct sockaddr)) == -1) {
ftfLog("setCommunications bind: %s",strerror(errno) );
return -1;
}
if (listen(socketFd, backLog) == -1) {
ftfLog("setCommunications listen: %s",strerror(errno) );
return -1;
}
#endif
return 0 ;
}
//####################################################################
//
//####################################################################
void gl3Conductor::setBField ( float bField ){
for ( int i = 0 ; i < maxEvents ; i++ ) {
event[i].setBField ( bField ) ;
}
}
//####################################################################
//
//####################################################################
void gl3Conductor::setHitProcessing ( int hitPro ){
hitProcessing = hitPro ;
for ( int i = 0 ; i < maxEvents ; i++ ) {
event[i].setHitProcessing ( hitPro ) ;
}
}
//####################################################################
//
//####################################################################
void gl3Conductor::setMaxSectorNForTrackMerging ( int _maxSectorNForTrackMerging ){
maxSectorNForTrackMerging = _maxSectorNForTrackMerging ;
for ( int i = 0 ; i < maxEvents ; i++ ) {
event[i].setMaxSectorNForTrackMerging ( _maxSectorNForTrackMerging ) ;
}
}
//####################################################################
//
//####################################################################
int gl3Conductor::setup ( St_l3_Coordinate_Transformer* _trans,
int maxEventsIn, int maxAlgorithmsIn ) {
//
communicationsFlag = 1 ;
event = 0 ;
algorithm = 0 ;
runNumber = 0 ;
maxTokens = 4096 ;
tokenIndex = new int[maxTokens+1];
maxEvents = maxEventsIn ;
maxAlgorithms = maxAlgorithmsIn ;
event = new gl3Event[maxEvents] ;
summary = new L3_summary[maxEvents];
summaryData = (L3_SUMD*) malloc( maxEvents * (sizeof(L3_SUMD) +
(maxAlgorithms-1)*sizeof(algorithm_data)));
algorithm = new pGl3Algorithm[maxAlgorithms] ;
for (int i=0; i<maxAlgorithms;i++) algorithm[i]=NULL;
nEvents = 0 ;
nAlgorithms = 0 ;
//
for ( int i = 0 ; i < maxTokens ; i++ ) tokenIndex[i] = 0 ;
//
// Setup communications
//
#ifdef GL3ONLINE
if ( communicationsFlag ){
if(setCommunications() )
return -1;
}
#endif
hitProcessing = 0 ;
for ( int i = 0 ; i < maxEvents ; i++ ) {
event[i].setHitProcessing ( hitProcessing ) ;
event[i].setCoordinateTransformer ( _trans ) ;
}
ftfLog("analysis framework set up\n");
return 0 ;
}
//####################################################################
//
//####################################################################
int gl3Conductor::writeHistos ( int maxBytes, char *buffer )
{
gl3HistoContainer* container = (gl3HistoContainer *)buffer ;
ftfLog ( "nHistos %d \n", histoList.size() ) ;
container->runNumber = runNumber ;
container->nHistos = histoList.size();
char* pointer = (char *)&(container->buffer) ;
char* endBuffer = buffer + maxBytes ;
int nBytes ;
int nTotalBytes = 6; // offset coming from gl3HistoContainer
//gl3Histo hTest ;
list<gl3Histo*>::iterator histo;
for(histo=histoList.begin(); histo!=histoList.end(); histo++) {
nBytes = (*histo)->Write ( endBuffer-pointer, pointer ) ;
if ( nBytes <= 0 ) {
ftfLog ( "gl3Container::writeHistos %d byte long buffer is too short \n", maxBytes ) ;
return 0 ;
}
// ftfLog ( "nBytes written %d pointer %x \n", nBytes, pointer ) ;
nTotalBytes += nBytes ;
if ( nTotalBytes > maxBytes ) {
ftfLog ( "gl3Conductor::writeHistos: nTotalBytes %d max %d\n", nTotalBytes, maxBytes ) ;
return -1 ;
}
pointer += nBytes * sizeof(char) ;
}
container->nBytes = nTotalBytes ;
ftfLog ( "gl3Conductor::writeHistos: histos %d Bytes %d \n",
histoList.size(), nTotalBytes ) ;
return nTotalBytes ;
}
//####################################################################
//
//####################################################################
int gl3Conductor::getFreeEventIndex()
{
int freeEventIndex = -1 ;
for ( int i = 0 ; i < maxEvents ; i++ ) {
if ( !(event[i].getBusy() ) ) {
freeEventIndex = i ;
nEvents++ ;
break ;
}
}
return freeEventIndex;
}
//####################################################################
//
//####################################################################
int gl3Conductor::getTokenIndex(int token)
{
if (token < 0 || token > 4096) {
ftfLog("gl3Conductor: token [%d] out of bounds \n", token );
return -1;
}
int index = tokenIndex[token];
if (index < 0 || index >= maxTokens) {
ftfLog("gl3Conductor: event index %d out of bounds \n", token );
return -2;
}
return index;
};
//####################################################################
//
//####################################################################
void gl3Conductor::resetTimer()
{
lastTimeEntry=0;
cpuTimes.clear();
realTimes.clear();
cpuTimes.reserve(5+nAlgorithms);
realTimes.reserve(5+nAlgorithms);
timingMark();
}
void gl3Conductor::timingMark()
{
cpuTimes[lastTimeEntry] = clock();
realTimes[lastTimeEntry] = realcc();
lastTimeEntry++;
}
void gl3Conductor::allocateTimingHistos()
{
#ifdef GL3ONLINE
timingHistos.resize(3+nAlgorithms);
timingHistos[0] = new gl3Histo("time_read_l3",
"Timing: read L3 data",
50,0,300);
timingHistos[1] = new gl3Histo("time_read_trg",
"Timing: read TRG data",
50,0,100);
char hid[30], htitle[100];
for(int i=0; i<nAlgorithms;i++) {
sprintf(hid, "time_alg_%d", i);
sprintf(htitle, "Timing: algorithms %d", i);
timingHistos[2+i] = new gl3Histo(hid, htitle,
60,0,30);
}
timingHistos[2+nAlgorithms] = new gl3Histo("time_total",
"Timing: total",
50,0,300);
for(int i=0;i<timingHistos.size();i++) {
histoList.push_back(timingHistos[i]);
}
#endif
}
void gl3Conductor::fillTimingHistos()
{
#ifdef GL3ONLINE
timingHistos[0]->Fill(double(realTimes[1] - realTimes[0])/ccPerMs);
timingHistos[1]->Fill(double(realTimes[2] - realTimes[1])/ccPerMs);
for(int i=0; i<nAlgorithms;i++) {
timingHistos[2+i]->Fill(double(realTimes[3+i] - realTimes[2+i])/ccPerMs);
}
timingHistos[2+nAlgorithms]->
Fill(double(realTimes[lastTimeEntry-1] - realTimes[0])/ccPerMs);
ftfLog("total time: %f\n",
double(realTimes[lastTimeEntry-1] - realTimes[0])/ccPerMs);
#endif
}
void gl3Conductor::printTiming()
{
for (int i=1; i<lastTimeEntry;i++) {
ftfLog("gl3Conductor: timing step %2d: CPU: %8f real: %8f\n",
i, (double)cpuTimes[i]-cpuTimes[i-1]/CLOCKS_PER_SEC,
(double)(realTimes[i]-realTimes[i-1])/ccPerMs);
}
}
//####################################################################
//
//####################################################################
// void gl3Conductor::printTiming ( ){
// ftfLog ( "********************************\n" ) ;
// ftfLog ( "* gl3 timing *\n" ) ;
// ftfLog ( "* Total: Real %5.0f (ms) \n", 1000.*totalRealTime ) ;
// ftfLog ( "* CPu %5.0f (ms) \n", 1000.*totalCpuTime ) ;
// ftfLog ( "* Algorithm Real Cpu *\n" ) ;
// ftfLog ( "* ( ) ( ) *\n" ) ;
// for ( int i = 0 ; i < nAlgorithms ; i++ ) {
// ftfLog ( "* %d %7.1f %7.1f *\n",
// i, 100.*algorithmRealTime[i]/totalRealTime,
// 100.*algorithmCpuTime[i]/totalCpuTime ) ;
// }
// ftfLog ( "********************************\n" ) ;
// }
| 28.195624 | 131 | 0.486169 |
236ad59187e5f3802e205398aece605a869c9eb4 | 530 | cpp | C++ | cpp/src/library.cpp | vibhatha/mycythonlib | 38db78636646b5a14c605556ae561261dc425c8e | [
"Apache-2.0"
] | null | null | null | cpp/src/library.cpp | vibhatha/mycythonlib | 38db78636646b5a14c605556ae561261dc425c8e | [
"Apache-2.0"
] | null | null | null | cpp/src/library.cpp | vibhatha/mycythonlib | 38db78636646b5a14c605556ae561261dc425c8e | [
"Apache-2.0"
] | null | null | null | //
// Created by vibhatha on 3/19/20.
//
#include "../include/library.h"
#include "iostream"
using namespace std;
Library::Library() {
}
void Library::c_multiply(double *array, double multiplier, int m) {
int i, j ;
int index = 0 ;
for (i = 0; i < m; i++) {
array[index] = array[index] * multiplier ;
index ++;
}
return ;
}
void Library::printArray(double *array, int length) {
for (int i = 0; i < length; ++i) {
cout << array[i] << " ";
}
cout << endl;
}
| 16.060606 | 67 | 0.532075 |
236ae6d7f99c44649c72258be304280ce3c1dadb | 2,025 | cpp | C++ | SAEEngineCore/submodules/object/tests/build_test/test.cpp | SAEEngine/SAEEngineCore | bede6c973caf7c4526ac5539ec2c9917139f2067 | [
"MIT"
] | 2 | 2020-10-31T09:59:36.000Z | 2020-11-01T04:22:56.000Z | SAEEngineCore/submodules/object/tests/build_test/test.cpp | SAEEngine/SAEEngineCore | bede6c973caf7c4526ac5539ec2c9917139f2067 | [
"MIT"
] | null | null | null | SAEEngineCore/submodules/object/tests/build_test/test.cpp | SAEEngine/SAEEngineCore | bede6c973caf7c4526ac5539ec2c9917139f2067 | [
"MIT"
] | null | null | null | /*
Return GOOD_TEST (0) if the test was passed.
Return anything other than GOOD_TEST (0) if the test was failed.
*/
// Common standard library headers
#include <cassert>
/**
* @brief Return this from main if the test was passsed.
*/
constexpr static inline int GOOD_TEST = 0;
// Include the headers you need for testing here
#include <SAEEngineCore_Object.h>
#include <SAEEngineCore_Environment.h>
#include <SAEEngineCore_glObject.h>
#include <chrono>
#include <thread>
#include <fstream>
#include <sstream>
#include <string>
#include <array>
#include <iostream>
#include <cmath>
using namespace sae::engine::core;
class ElementList : public GFXView
{
public:
void refresh() override
{
if (this->child_count() == 0)
return;
auto _x = this->bounds().left();
auto _w = this->bounds().width();
auto _eachWidth = (_w - ((this->child_count() - 1) * this->margin_)) / (this->child_count());
for (auto& o : this->children())
{
auto& _b = o->bounds();
_b.left() = _x;
_b.right() = _b.left() + _eachWidth;
_b.top() = this->bounds().top();
_b.bottom() = this->bounds().bottom();
_x += _eachWidth + this->margin_;
};
};
ElementList(GFXContext* _context, Rect _r, pixels_t _margin = 5_px) :
GFXView{ _context, _r }, margin_{ _margin }
{};
private:
pixels_t margin_ = 0;
};
int main(int argc, char* argv[], char* envp[])
{
GFXContext _context{ nullptr, Rect{{ 0_px, 0_px}, { 1600_px, 900_px } } };
auto _listB = _context.bounds();
auto _listPtr = new ElementList{ &_context, _listB, 0_px };
_listPtr->emplace(new GFXObject{ {} });
_listPtr->emplace(new GFXObject{ {} });
_listPtr->emplace(new GFXObject{ {} });
_listPtr->emplace(new GFXObject{ {} });
_context.emplace(_listPtr);
_context.refresh();
_listB.right() = _listB.left() + 600_px;
auto _list2Ptr = new ElementList{ &_context, _listB, 0_px };
_list2Ptr->emplace(new GFXObject{ {} });
_list2Ptr->emplace(new GFXObject{ {} });
_context.emplace(_list2Ptr);
_context.refresh();
return GOOD_TEST;
}; | 22.252747 | 95 | 0.669136 |
2370c744e4e0262381f18133e5f777dfa220f054 | 12,069 | cpp | C++ | classes/CSocket.cpp | clockworkengineer/Antikythera_mechanism | 572dc5c83303548134adf8325f77c795c02481f2 | [
"MIT"
] | 1 | 2021-03-04T07:04:50.000Z | 2021-03-04T07:04:50.000Z | classes/CSocket.cpp | clockworkengineer/Antikythera_mechanism | 572dc5c83303548134adf8325f77c795c02481f2 | [
"MIT"
] | null | null | null | classes/CSocket.cpp | clockworkengineer/Antikythera_mechanism | 572dc5c83303548134adf8325f77c795c02481f2 | [
"MIT"
] | 1 | 2021-11-29T08:24:52.000Z | 2021-11-29T08:24:52.000Z | //
// Class: CSocket
//
// Description: Class for connecting to / listening for connections from remote peers
// and the reading/writing of data using sockets. It supports both plain and TLS/SSL
// connections and is implemented using BOOST:ASIO synchronous API calls. At present it
// only has basic TLS/SSL support and is geared more towards client support but this may
// change in future.
//
// Dependencies: C20++ - Language standard features used.
// BOOST ASIO - Used to talk to FTP server.
//
// =================
// CLASS DEFINITIONS
// =================
#include "CSocket.hpp"
// ====================
// CLASS IMPLEMENTATION
// ====================
//
// C++ STL
//
#include <iostream>
#include <fstream>
// =======
// IMPORTS
// =======
// =========
// NAMESPACE
// =========
namespace Antik::Network
{
// ===========================
// PRIVATE TYPES AND CONSTANTS
// ===========================
// ==========================
// PUBLIC TYPES AND CONSTANTS
// ==========================
// ========================
// PRIVATE STATIC VARIABLES
// ========================
// =======================
// PUBLIC STATIC VARIABLES
// =======================
// ===============
// PRIVATE METHODS
// ===============
//
// Socket listener thread method for incoming connections. At present it listens
// on a random port but sets m_hostPort to its value. The connected socket is created
// local and moved to m_socket on success.
//
void CSocket::connectionListener()
{
try
{
boost::asio::ip::tcp::acceptor acceptor(m_ioService, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 0));
m_hostPort = std::to_string(acceptor.local_endpoint().port());
m_isListenThreadRunning = true;
std::unique_ptr<SSLSocket> socket = std::make_unique<SSLSocket>(m_ioService, *m_sslContext);
if (!socket)
{
throw std::runtime_error("Could not create socket.");
}
acceptor.accept(socket->next_layer(), m_socketError);
if (m_socketError)
{
throw std::runtime_error(m_socketError.message());
}
m_socket = std::move(socket);
}
catch (const std::exception &e)
{
m_thrownException = std::current_exception();
}
m_isListenThreadRunning = false;
}
// ==============
// PUBLIC METHODS
// ==============
//
// Cleanup after socket connection. This includes stopping any unused listener
// thread and closing the socket if still open. Note: if the thread is still waiting
// for a connect it is woken up with a fake connect.
//
void CSocket::cleanup()
{
try
{
if (m_isListenThreadRunning && m_socketListenThread)
{
m_isListenThreadRunning = false;
try
{
boost::asio::ip::tcp::socket socket{m_ioService};
boost::asio::ip::tcp::resolver::query query(m_hostAddress, m_hostPort);
boost::asio::connect(socket, m_ioQueryResolver.resolve(query));
socket.close();
}
catch (std::exception &e)
{
throw std::runtime_error("Could not wake listener thread with fake connect.");
}
m_socketListenThread->join();
}
close();
}
catch (const std::exception &e)
{
throw Exception(e.what());
}
}
//
// Listen for connections
//
void CSocket::listenForConnection()
{
try
{
// Start connection listener thread and wait until its listening
m_socketListenThread = std::make_unique<std::thread>(&CSocket::connectionListener, this);
while (!m_isListenThreadRunning)
{
continue;
}
if (m_thrownException)
{
std::rethrow_exception(m_thrownException);
}
}
catch (const std::exception &e)
{
throw Exception(e.what());
}
}
//
// Wait until a socket is connected.
//
void CSocket::waitUntilConnected()
{
try
{
// Listener thread is running (wait for it to finish)
if (m_socketListenThread)
{
m_socketListenThread->join();
}
// TLS handshake if SSL enabled
tlsHandshake();
}
catch (const std::exception &e)
{
throw Exception(e.what());
}
}
//
// Connect to a given host and port.The connecting socket is created
// local and moved to m_socket on success.
//
void CSocket::connect()
{
try
{
std::unique_ptr<SSLSocket> socket = std::make_unique<SSLSocket>(m_ioService, *m_sslContext);
if (!socket)
{
throw std::runtime_error("Could not create socket.");
}
boost::asio::ip::tcp::resolver::query query{m_hostAddress, m_hostPort};
socket->next_layer().connect(*m_ioQueryResolver.resolve(query), m_socketError);
if (m_socketError)
{
throw std::runtime_error(m_socketError.message());
}
m_socket = std::move(socket);
}
catch (const std::exception &e)
{
throw Exception(e.what());
}
}
//
// Read data from socket into buffer
//
size_t CSocket::read(char *readBuffer, size_t bufferLength)
{
try
{
size_t bytesRead{0};
// No socket present
if (!m_socket)
{
throw std::logic_error("No socket present.");
}
// Read data
if (m_sslActive)
{
bytesRead = m_socket->read_some(boost::asio::buffer(readBuffer, bufferLength), m_socketError);
}
else
{
bytesRead = m_socket->next_layer().read_some(boost::asio::buffer(readBuffer, bufferLength), m_socketError);
}
// Signal any non end of file error
if (m_socketError && m_socketError != boost::asio::error::eof)
{
throw std::runtime_error(m_socketError.message());
}
return (bytesRead);
}
catch (const std::exception &e)
{
throw Exception(e.what());
}
}
//
// Write data to socket
//
size_t CSocket::write(const char *writeBuffer, size_t writeLength)
{
try
{
size_t bytesWritten{0};
// No socket present
if (!m_socket)
{
throw std::logic_error("No socket present.");
}
// Write data
if (m_sslActive)
{
bytesWritten = m_socket->write_some(boost::asio::buffer(writeBuffer, writeLength), m_socketError);
}
else
{
bytesWritten = m_socket->next_layer().write_some(boost::asio::buffer(writeBuffer, writeLength), m_socketError);
}
// Signal any non end of file error
if (m_socketError && m_socketError != boost::asio::error::eof)
{
throw std::runtime_error(m_socketError.message());
}
return (bytesWritten);
}
catch (const std::exception &e)
{
throw Exception(e.what());
}
}
//
// Perform TLS handshake if SSL enabled
//
void CSocket::tlsHandshake()
{
try
{
// If SSL not enabled return
if (!m_sslEnabled)
{
return;
}
// No socket present
if (!m_socket)
{
throw std::logic_error("No socket present.");
}
m_socket->handshake(SSLSocket::client, m_socketError);
if (m_socketError)
{
throw std::runtime_error(m_socketError.message());
}
m_sslActive = true;
}
catch (const std::exception &e)
{
throw Exception(e.what());
}
}
//
// Closedown any running SSL and close socket. Move m_socket to local
// socket and close it down.
//
void CSocket::close()
{
try
{
std::unique_ptr<SSLSocket> socket{std::move(m_socket)};
// Socket exists and is open
if (socket && socket->next_layer().is_open())
{
// Shutdown TLS
if (m_sslActive)
{
m_sslActive = false;
socket->shutdown(m_socketError);
}
// Close socket
socket->next_layer().close(m_socketError);
if (m_socketError)
{
throw std::runtime_error(m_socketError.message());
}
}
// Remove any listen thread
if (m_socketListenThread)
{
m_socketListenThread.reset();
}
}
catch (const std::exception &e)
{
throw Exception(e.what());
}
}
//
// Set SSL context for the TLS version se
//
void CSocket::setTLSVersion(TLSVerion version)
{
m_tlsVersion = version;
switch (m_tlsVersion)
{
case TLSVerion::v1_0:
m_sslContext = std::make_unique<boost::asio::ssl::context>(boost::asio::ssl::context::tlsv1);
break;
case TLSVerion::v1_1:
m_sslContext = std::make_unique<boost::asio::ssl::context>(boost::asio::ssl::context::tlsv11);
break;
case TLSVerion::v1_2:
m_sslContext = std::make_unique<boost::asio::ssl::context>(boost::asio::ssl::context::tlsv12);
break;
}
}
//
// Work out ip address for local machine. This is quite difficult to achieve but
// this is the best code i have seen for doing it. It just tries to connect to
// google.com with a udp connect to get the local socket endpoint.
// Note: Fall back of localhost on failure.
//
std::string CSocket::localIPAddress()
{
static std::string localIPAddress;
if (localIPAddress.empty())
{
try
{
boost::asio::io_service ioService;
boost::asio::ip::udp::resolver resolver(ioService);
boost::asio::ip::udp::resolver::query query(boost::asio::ip::udp::v4(), "google.com", "");
boost::asio::ip::udp::socket socket(ioService);
socket.connect(*resolver.resolve(query));
localIPAddress = socket.local_endpoint().address().to_string();
socket.close();
}
catch (std::exception &e)
{
return ("127.0.0.1");
}
}
return (localIPAddress);
}
// ============================
// CLASS PRIVATE DATA ACCESSORS
// ============================
void CSocket::setSslEnabled(bool sslEnabled)
{
m_sslEnabled = sslEnabled;
}
bool CSocket::isSslEnabled() const
{
return m_sslEnabled;
}
void CSocket::setHostAddress(std::string hostAddress)
{
m_hostAddress = hostAddress;
}
std::string CSocket::getHostAddress() const
{
return m_hostAddress;
}
void CSocket::setHostPort(std::string hostPort)
{
m_hostPort = hostPort;
}
std::string CSocket::getHostPort() const
{
return m_hostPort;
}
} // namespace Antik::Network
| 30.946154 | 128 | 0.50029 |
2372772d8a2edf2c0a7646a0368031bad79ae542 | 3,752 | cpp | C++ | SCLT/Objects/Material/MaterialBRDF.cpp | chicio/Multispectral-Ray-tracing | ea5b399770eddd1927aae8a8ae4640dead42c48c | [
"MIT"
] | 95 | 2016-05-05T10:46:49.000Z | 2021-12-20T12:51:41.000Z | SCLT/Objects/Material/MaterialBRDF.cpp | chicio/Multispectral-Ray-tracing | ea5b399770eddd1927aae8a8ae4640dead42c48c | [
"MIT"
] | 1 | 2021-12-06T03:21:32.000Z | 2021-12-06T03:21:32.000Z | SCLT/Objects/Material/MaterialBRDF.cpp | chicio/Multispectral-Ray-tracing | ea5b399770eddd1927aae8a8ae4640dead42c48c | [
"MIT"
] | 8 | 2017-03-12T03:04:08.000Z | 2022-03-17T01:27:41.000Z | //
// MaterialBRDF.cpp
// Spectral Clara Lux tracer
//
// Created by Fabrizio Duroni on 23/11/15.
// Copyright © 2015 Fabrizio Duroni. All rights reserved.
//
#include "pch.h"
#include "MaterialBRDF.hpp"
#include "Illuminant.hpp"
Spectrum<constant::spectrumSamples> MaterialBRDF::f(const Vector3D& wi,
const Vector3D& wo,
const Intersection& intersection) const {
Spectrum<constant::spectrumSamples> f(0.0f);
for(std::vector<BRDF *>::size_type i = 0; i != brdfs.size(); i++) {
f = f + brdfs[i]->f(wi, wo, intersection);
}
return f;
}
Spectrum<constant::spectrumSamples> MaterialBRDF::samplef(Vector3D* wi,
const Vector3D& wo,
const Intersection& intersection,
const BRDFType type) const {
Spectrum<constant::spectrumSamples> f(0.0f);
for(std::vector<BRDF *>::size_type i = 0; i != brdfs.size(); i++) {
if(brdfs[i]->brdfType == type) {
f = f + brdfs[i]->samplef(wi, wo, intersection);
}
}
return f;
}
float MaterialBRDF::pdf(const Vector3D& wi,
const Vector3D& wo,
const Intersection& intersection,
const BRDFType type) const {
for(std::vector<BRDF *>::size_type i = 0; i != brdfs.size(); i++) {
if(brdfs[i]->brdfType == type) {
return brdfs[i]->pdf(wi, wo, intersection);
}
}
return 0.0F;
}
Material* MaterialBRDF::emissiveMaterial(Spectrum<constant::spectrumSamples> illuminant) {
MaterialBRDF* emissiveMaterial = new MaterialBRDF();
emissiveMaterial->le = illuminant;
emissiveMaterial->brdfs.push_back(new Lambertian(Spectrum<constant::spectrumSamples>(0.0f)));
return emissiveMaterial;
}
Material* MaterialBRDF::matteMaterial(Spectrum<constant::spectrumSamples> spectrum) {
//Matte material.
MaterialBRDF* matteMaterial = new MaterialBRDF();
matteMaterial->brdfs.push_back(new Lambertian(spectrum));
return matteMaterial;
}
Material* MaterialBRDF::matteMaterial(Spectrum<constant::spectrumSamples> spectrum, float degree) {
//Matte material.
MaterialBRDF* matteMaterial = new MaterialBRDF();
matteMaterial->brdfs.push_back(new OrenNayar (spectrum, degree));
return matteMaterial;
}
Material* MaterialBRDF::plasticMaterial(Spectrum<constant::spectrumSamples> spectrumDiffuse,
Spectrum<constant::spectrumSamples> spectrumSpecular,
float roughness) {
//Plastic material.
MaterialBRDF* plasticMaterial = new MaterialBRDF();
plasticMaterial->brdfs.push_back(new Lambertian (spectrumDiffuse));
plasticMaterial->brdfs.push_back(new TorranceSparrow(spectrumSpecular, 1.5, roughness));
return plasticMaterial;
}
Material* MaterialBRDF::glassMaterial() {
MaterialBRDF* mirrorMaterial = new MaterialBRDF();
mirrorMaterial->brdfs.push_back(new SpecularReflection(Spectrum<constant::spectrumSamples>(1.0f), 1.5));
mirrorMaterial->brdfs.push_back(new SpecularTransmission(Spectrum<constant::spectrumSamples>(1.0f), 1.5));
return mirrorMaterial;
}
Material* MaterialBRDF::measuredMaterial(const char *filename, bool interpolated) {
MaterialBRDF* measuredMaterial = new MaterialBRDF();
measuredMaterial->brdfs.push_back(new Measured(filename, interpolated));
return measuredMaterial;
}
| 32.344828 | 110 | 0.611141 |
2373bfefa0e0944e7f73099ae42a8648da18b3b6 | 2,085 | cpp | C++ | src/Log.cpp | wibbe/zum-cpp | 0fc753cac5f577eb56eaa9e8330f466b2cdaa38c | [
"MIT"
] | null | null | null | src/Log.cpp | wibbe/zum-cpp | 0fc753cac5f577eb56eaa9e8330f466b2cdaa38c | [
"MIT"
] | null | null | null | src/Log.cpp | wibbe/zum-cpp | 0fc753cac5f577eb56eaa9e8330f466b2cdaa38c | [
"MIT"
] | null | null | null |
#include "Log.h"
#include "bx/platform.h"
#include <cstdlib>
#include <cstdio>
static std::string logFile()
{
#if BX_PLATFORM_LINUX || BX_PLATFORM_OSX
static const std::string LOG_FILE = "/.zumlog";
const char * home = getenv("HOME");
if (home)
return std::string(home) + LOG_FILE;
else
return "~" + LOG_FILE;
#else
return "log.txt";
#endif
}
void clearLog()
{
FILE * file = fopen(logFile().c_str(), "w");
fclose(file);
}
void _logValue(FILE * file, char value)
{
fprintf(file, "%c", value);
fprintf(stderr, "%c", value);
}
void _logValue(FILE * file, int value)
{
fprintf(file, "%d", value);
fprintf(stderr, "%d", value);
}
void _logValue(FILE * file, uint32_t value)
{
fprintf(file, "%d", value);
fprintf(stderr, "%d", value);
}
void _logValue(FILE * file, long value)
{
fprintf(file, "%ld", value);
fprintf(stderr, "%ld", value);
}
void _logValue(FILE * file, long long int value)
{
fprintf(file, "%lld", value);
fprintf(stderr, "%lld", value);
}
void _logValue(FILE * file, float value)
{
fprintf(file, "%f", value);
fprintf(stderr, "%f", value);
}
void _logValue(FILE * file, double value)
{
fprintf(file, "%f", value);
fprintf(stderr, "%f", value);
}
void _logValue(FILE * file, const char * value)
{
fprintf(file, "%s", value);
fprintf(stderr, "%s", value);
}
void _logValue(FILE * file, Str const& value)
{
fprintf(file, "%s", value.utf8().c_str());
fprintf(stderr, "%s", value.utf8().c_str());
}
void _logValue(FILE * file, std::string const& value)
{
fprintf(file, "%s", value.c_str());
fprintf(stderr, "%s", value.c_str());
}
FILE * _logBegin()
{
return fopen(logFile().c_str(), "at");
}
void _logEnd(FILE * file)
{
_logValue(file, "\n");
fclose(file);
fflush(stderr);
}
void logInfo(Str const& message)
{
FILE * file = fopen(logFile().c_str(), "at");
fprintf(file, "INFO: %s\n", message.utf8().c_str());
fclose(file);
}
void logError(Str const& message)
{
FILE * file = fopen(logFile().c_str(), "at");
fprintf(file, "ERROR: %s\n", message.utf8().c_str());
fclose(file);
}
| 18.289474 | 55 | 0.62446 |
2374eece4b5cb807686524d494c2f570d888704c | 7,577 | hpp | C++ | include/yamail/resource_pool/async/detail/queue.hpp | JonasProgrammer/resource_pool | 5b8e0d542e40805b187af7b94770e95f292379c9 | [
"MIT"
] | 17 | 2018-12-02T10:16:37.000Z | 2022-02-25T22:58:35.000Z | include/yamail/resource_pool/async/detail/queue.hpp | JonasProgrammer/resource_pool | 5b8e0d542e40805b187af7b94770e95f292379c9 | [
"MIT"
] | 27 | 2017-12-25T14:54:38.000Z | 2021-01-28T12:30:10.000Z | include/yamail/resource_pool/async/detail/queue.hpp | JonasProgrammer/resource_pool | 5b8e0d542e40805b187af7b94770e95f292379c9 | [
"MIT"
] | 5 | 2017-12-25T14:41:52.000Z | 2022-03-26T06:22:22.000Z | #ifndef YAMAIL_RESOURCE_POOL_ASYNC_DETAIL_QUEUE_HPP
#define YAMAIL_RESOURCE_POOL_ASYNC_DETAIL_QUEUE_HPP
#include <yamail/resource_pool/error.hpp>
#include <yamail/resource_pool/time_traits.hpp>
#include <boost/asio/executor.hpp>
#include <boost/asio/post.hpp>
#include <algorithm>
#include <list>
#include <map>
#include <mutex>
#include <unordered_map>
namespace yamail {
namespace resource_pool {
namespace async {
namespace asio = boost::asio;
namespace detail {
using clock = std::chrono::steady_clock;
template <class Handler>
class expired_handler {
Handler handler;
public:
using executor_type = std::decay_t<decltype(asio::get_associated_executor(handler))>;
expired_handler() = default;
template <class HandlerT>
explicit expired_handler(HandlerT&& handler,
std::enable_if_t<!std::is_same_v<std::decay_t<HandlerT>, expired_handler>, void*> = nullptr)
: handler(std::forward<HandlerT>(handler)) {
static_assert(std::is_same_v<std::decay_t<HandlerT>, Handler>, "HandlerT is not Handler");
}
void operator ()() {
handler(make_error_code(error::get_resource_timeout));
}
void operator ()() const {
handler(make_error_code(error::get_resource_timeout));
}
auto get_executor() const noexcept {
return asio::get_associated_executor(handler);
}
};
template <class Handler>
expired_handler(Handler&&) -> expired_handler<std::decay_t<Handler>>;
template <class Value, class IoContext>
struct queued_value {
Value request;
IoContext& io_context;
};
template <class Value, class Mutex, class IoContext, class Timer>
class queue : public std::enable_shared_from_this<queue<Value, Mutex, IoContext, Timer>> {
public:
using value_type = Value;
using io_context_t = IoContext;
using timer_t = Timer;
using queued_value_t = queued_value<value_type, io_context_t>;
queue(std::size_t capacity) : _capacity(capacity) {}
queue(const queue&) = delete;
queue(queue&&) = delete;
std::size_t capacity() const noexcept { return _capacity; }
std::size_t size() const noexcept;
bool empty() const noexcept;
const timer_t& timer(io_context_t& io_context);
bool push(io_context_t& io_context, time_traits::duration wait_duration, value_type&& request);
boost::optional<queued_value_t> pop();
private:
using mutex_t = Mutex;
using lock_guard = std::lock_guard<mutex_t>;
struct expiring_request {
using list = std::list<expiring_request>;
using list_it = typename list::iterator;
using multimap = std::multimap<time_traits::time_point, expiring_request*>;
using multimap_it = typename multimap::iterator;
io_context_t* io_context;
queue::value_type request;
list_it order_it;
multimap_it expires_at_it;
expiring_request() = default;
};
using request_multimap_value = typename expiring_request::multimap::value_type;
using timers_map = typename std::unordered_map<const io_context_t*, timer_t>;
const std::size_t _capacity;
mutable mutex_t _mutex;
typename expiring_request::list _ordered_requests_pool;
typename expiring_request::list _ordered_requests;
typename expiring_request::multimap _expires_at_requests;
timers_map _timers;
bool fit_capacity() const { return _expires_at_requests.size() < _capacity; }
void cancel(boost::system::error_code ec, time_traits::time_point expires_at);
void update_timer();
timer_t& get_timer(io_context_t& io_context);
};
template <class V, class M, class I, class T>
std::size_t queue<V, M, I, T>::size() const noexcept {
const lock_guard lock(_mutex);
return _expires_at_requests.size();
}
template <class V, class M, class I, class T>
bool queue<V, M, I, T>::empty() const noexcept {
const lock_guard lock(_mutex);
return _ordered_requests.empty();
}
template <class V, class M, class I, class T>
const typename queue<V, M, I, T>::timer_t& queue<V, M, I, T>::timer(io_context_t& io_context) {
const lock_guard lock(_mutex);
return get_timer(io_context);
}
template <class V, class M, class I, class T>
bool queue<V, M, I, T>::push(io_context_t& io_context, time_traits::duration wait_duration, value_type&& request) {
const lock_guard lock(_mutex);
if (!fit_capacity()) {
return false;
}
if (_ordered_requests_pool.empty()) {
_ordered_requests_pool.emplace_back();
}
const auto order_it = _ordered_requests_pool.begin();
_ordered_requests.splice(_ordered_requests.end(), _ordered_requests_pool, order_it);
expiring_request& req = *order_it;
req.io_context = std::addressof(io_context);
req.request = std::move(request);
req.order_it = order_it;
const auto expires_at = time_traits::add(time_traits::now(), wait_duration);
req.expires_at_it = _expires_at_requests.insert(std::make_pair(expires_at, &req));
update_timer();
return true;
}
template <class V, class M, class I, class T>
boost::optional<typename queue<V, M, I, T>::queued_value_t> queue<V, M, I, T>::pop() {
const lock_guard lock(_mutex);
if (_ordered_requests.empty()) {
return {};
}
const auto ordered_it = _ordered_requests.begin();
expiring_request& req = *ordered_it;
queued_value_t result {std::move(req.request), *req.io_context};
_expires_at_requests.erase(req.expires_at_it);
_ordered_requests_pool.splice(_ordered_requests_pool.begin(), _ordered_requests, ordered_it);
update_timer();
return { std::move(result) };
}
template <class V, class M, class I, class T>
void queue<V, M, I, T>::cancel(boost::system::error_code ec, time_traits::time_point expires_at) {
if (ec) {
return;
}
const lock_guard lock(_mutex);
const auto begin = _expires_at_requests.begin();
const auto end = _expires_at_requests.upper_bound(expires_at);
std::for_each(begin, end, [&] (request_multimap_value& v) {
const auto req = v.second;
asio::post(*req->io_context, expired_handler(std::move(req->request)));
_ordered_requests_pool.splice(_ordered_requests_pool.begin(), _ordered_requests, req->order_it);
});
_expires_at_requests.erase(_expires_at_requests.begin(), end);
update_timer();
}
template <class V, class M, class I, class T>
void queue<V, M, I, T>::update_timer() {
using timers_map_value = typename timers_map::value_type;
if (_expires_at_requests.empty()) {
std::for_each(_timers.begin(), _timers.end(), [] (timers_map_value& v) { v.second.cancel(); });
_timers.clear();
return;
}
const auto earliest_expire = _expires_at_requests.begin();
const auto expires_at = earliest_expire->first;
auto& timer = get_timer(*earliest_expire->second->io_context);
timer.expires_at(expires_at);
std::weak_ptr<queue> weak(this->shared_from_this());
timer.async_wait([weak, expires_at] (boost::system::error_code ec) {
if (const auto locked = weak.lock()) {
locked->cancel(ec, expires_at);
}
});
}
template <class V, class M, class I, class T>
typename queue<V, M, I, T>::timer_t& queue<V, M, I, T>::get_timer(io_context_t& io_context) {
auto it = _timers.find(&io_context);
if (it != _timers.end()) {
return it->second;
}
return _timers.emplace(&io_context, timer_t(io_context)).first->second;
}
} // namespace detail
} // namespace async
} // namespace resource_pool
} // namespace yamail
#endif // YAMAIL_RESOURCE_POOL_ASYNC_DETAIL_QUEUE_HPP
| 33.526549 | 115 | 0.700937 |
2378fd7fec6d7510bbff013b9a0ea4b2b7f215bd | 268 | cpp | C++ | src/portaudiohandler.cpp | aparks5/synthcastle | ebb542d014c87a11a83b9e212668eca75a333fbf | [
"MIT"
] | 2 | 2021-12-20T03:20:05.000Z | 2021-12-28T16:15:20.000Z | src/portaudiohandler.cpp | aparks5/synthcastle | ebb542d014c87a11a83b9e212668eca75a333fbf | [
"MIT"
] | 69 | 2021-08-30T13:09:01.000Z | 2022-01-15T17:41:40.000Z | src/portaudiohandler.cpp | aparks5/synthcastle | ebb542d014c87a11a83b9e212668eca75a333fbf | [
"MIT"
] | null | null | null | /// Copyright(c) 2021. Anthony Parks. All rights reserved.
#include "portaudiohandler.h"
PortAudioHandler::PortAudioHandler()
: m_result(Pa_Initialize())
{
}
PortAudioHandler::~PortAudioHandler()
{
if (m_result == paNoError)
{
Pa_Terminate();
}
} | 17.866667 | 59 | 0.682836 |
2379857d0af4607a620b76853af3c51e2d41dcac | 1,173 | cpp | C++ | Source/Trickery/Test.cpp | D4rk1n/ModernProblemsModernSolutions | bb8f96f9701fe3eee3b5a513b42575a3d0075bb4 | [
"Apache-2.0"
] | null | null | null | Source/Trickery/Test.cpp | D4rk1n/ModernProblemsModernSolutions | bb8f96f9701fe3eee3b5a513b42575a3d0075bb4 | [
"Apache-2.0"
] | null | null | null | Source/Trickery/Test.cpp | D4rk1n/ModernProblemsModernSolutions | bb8f96f9701fe3eee3b5a513b42575a3d0075bb4 | [
"Apache-2.0"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "Test.h"
// Sets default values for this component's properties
UTest::UTest()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = true;
// ...
}
// Called when the game starts
void UTest::BeginPlay()
{
Super::BeginPlay();
Owner = GetOwner();
POpen = GetWorld()->GetFirstPlayerController()->GetPawn();
// ...
}
// Called every frame
void UTest::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
if (AOpen&&PPlate)
{
//UE_LOG(LogTemp, Warning, TEXT("lol "));
if (PPlate->IsOverlappingActor(AOpen)) {
UE_LOG(LogTemp, Warning, TEXT("Actor that opens "))
FRotator r(0, -50, 0);
Owner->SetActorRotation(r);
}
if (PPlate->IsOverlappingActor(POpen)) {
UE_LOG(LogTemp, Warning, TEXT("Pawn that opens "))
FRotator r(0, -50, 0);
Owner->SetActorRotation(r);
}
}
// ...
}
| 24.4375 | 121 | 0.700767 |
237cc3acae3061fd145e90a3004595c0a35619b0 | 354 | hpp | C++ | include/toy/gadget/IntToHexChar.hpp | ToyAuthor/ToyBox | f517a64d00e00ccaedd76e33ed5897edc6fde55e | [
"Unlicense"
] | 4 | 2017-07-06T22:18:41.000Z | 2021-05-24T21:28:37.000Z | include/toy/gadget/IntToHexChar.hpp | ToyAuthor/ToyBox | f517a64d00e00ccaedd76e33ed5897edc6fde55e | [
"Unlicense"
] | null | null | null | include/toy/gadget/IntToHexChar.hpp | ToyAuthor/ToyBox | f517a64d00e00ccaedd76e33ed5897edc6fde55e | [
"Unlicense"
] | 1 | 2020-08-02T13:00:38.000Z | 2020-08-02T13:00:38.000Z |
#pragma once
#include "toy/Standard.hpp"
#include "toy/gadget/Export.hpp"
namespace toy{
namespace gadget{
// 1 -> '1'
// 2 -> '2'
// 11 -> 'b'
// 15 -> 'f'
// 16 -> [error]
TOY_API_GADGET extern char IntToHexChar(int);
// 1 -> '1'
// 2 -> '2'
// 11 -> 'B'
// 15 -> 'F'
// 16 -> [error]
TOY_API_GADGET extern char IntToHexChar_Capital(int);
}}
| 14.16 | 53 | 0.573446 |
237fc3ac31b5b7e05509b8d16e2810e96459d81d | 278 | hpp | C++ | package/config/config/config_config.hpp | mambaru/wfc_core | 0c3e7fba82a9bb1580582968efae02ef7fabc87a | [
"MIT"
] | null | null | null | package/config/config/config_config.hpp | mambaru/wfc_core | 0c3e7fba82a9bb1580582968efae02ef7fabc87a | [
"MIT"
] | 5 | 2019-12-06T01:01:01.000Z | 2021-04-20T21:16:34.000Z | package/config/config/config_config.hpp | mambaru/wfc_core | 0c3e7fba82a9bb1580582968efae02ef7fabc87a | [
"MIT"
] | null | null | null | //
// Author: Vladimir Migashko <migashko@gmail.com>, (C) 2013-2018
//
// Copyright: See COPYING file that comes with this distribution
//
#pragma once
namespace wfc{ namespace core{
struct config_config
{
bool reload_sighup = false;
time_t reload_changed_ms = 0;
};
}}
| 15.444444 | 64 | 0.715827 |
23814363269462e69bd0dc675502639a6f45b87f | 6,427 | cc | C++ | chrome/browser/sync/engine/build_commit_command.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | 11 | 2015-03-20T04:08:08.000Z | 2021-11-15T15:51:36.000Z | chrome/browser/sync/engine/build_commit_command.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | null | null | null | chrome/browser/sync/engine/build_commit_command.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync/engine/build_commit_command.h"
#include <set>
#include <string>
#include <vector>
#include "chrome/browser/sync/engine/syncer_proto_util.h"
#include "chrome/browser/sync/engine/syncer_util.h"
#include "chrome/browser/sync/sessions/sync_session.h"
#include "chrome/browser/sync/syncable/syncable.h"
#include "chrome/browser/sync/syncable/syncable_changes_version.h"
#include "chrome/browser/sync/util/sync_types.h"
using std::set;
using std::string;
using std::vector;
using syncable::ExtendedAttribute;
using syncable::Id;
using syncable::MutableEntry;
namespace browser_sync {
using sessions::SyncSession;
BuildCommitCommand::BuildCommitCommand() {}
BuildCommitCommand::~BuildCommitCommand() {}
void BuildCommitCommand::AddExtensionsActivityToMessage(
SyncSession* session, CommitMessage* message) {
const ExtensionsActivityMonitor::Records& records =
session->extensions_activity();
for (ExtensionsActivityMonitor::Records::const_iterator it = records.begin();
it != records.end(); ++it) {
sync_pb::CommitMessage_ChromiumExtensionsActivity* activity_message =
message->add_extensions_activity();
activity_message->set_extension_id(it->second.extension_id);
activity_message->set_bookmark_writes_since_last_commit(
it->second.bookmark_write_count);
}
}
void BuildCommitCommand::ExecuteImpl(SyncSession* session) {
ClientToServerMessage message;
message.set_share(session->context()->account_name());
message.set_message_contents(ClientToServerMessage::COMMIT);
CommitMessage* commit_message = message.mutable_commit();
commit_message->set_cache_guid(
session->write_transaction()->directory()->cache_guid());
AddExtensionsActivityToMessage(session, commit_message);
const vector<Id>& commit_ids = session->status_controller()->commit_ids();
for (size_t i = 0; i < commit_ids.size(); i++) {
Id id = commit_ids[i];
SyncEntity* sync_entry =
static_cast<SyncEntity*>(commit_message->add_entries());
sync_entry->set_id(id);
MutableEntry meta_entry(session->write_transaction(),
syncable::GET_BY_ID,
id);
CHECK(meta_entry.good());
// This is the only change we make to the entry in this function.
meta_entry.Put(syncable::SYNCING, true);
string name = meta_entry.Get(syncable::NON_UNIQUE_NAME);
CHECK(!name.empty()); // Make sure this isn't an update.
sync_entry->set_name(name);
// Set the non_unique_name. If we do, the server ignores
// the |name| value (using |non_unique_name| instead), and will return
// in the CommitResponse a unique name if one is generated.
// We send both because it may aid in logging.
sync_entry->set_non_unique_name(name);
// Deleted items with negative parent ids can be a problem so we set the
// parent to 0. (TODO(sync): Still true in protocol?).
Id new_parent_id;
if (meta_entry.Get(syncable::IS_DEL) &&
!meta_entry.Get(syncable::PARENT_ID).ServerKnows()) {
new_parent_id = session->write_transaction()->root_id();
} else {
new_parent_id = meta_entry.Get(syncable::PARENT_ID);
}
sync_entry->set_parent_id(new_parent_id);
// TODO(sync): Investigate all places that think transactional commits
// actually exist.
//
// This is the only logic we'll need when transactional commits are moved
// to the server. If our parent has changes, send up the old one so the
// server can correctly deal with multiple parents.
if (new_parent_id != meta_entry.Get(syncable::SERVER_PARENT_ID) &&
0 != meta_entry.Get(syncable::BASE_VERSION) &&
syncable::CHANGES_VERSION != meta_entry.Get(syncable::BASE_VERSION)) {
sync_entry->set_old_parent_id(meta_entry.Get(syncable::SERVER_PARENT_ID));
}
int64 version = meta_entry.Get(syncable::BASE_VERSION);
if (syncable::CHANGES_VERSION == version || 0 == version) {
// If this CHECK triggers during unit testing, check that we haven't
// altered an item that's an unapplied update.
CHECK(!id.ServerKnows()) << meta_entry;
sync_entry->set_version(0);
} else {
CHECK(id.ServerKnows()) << meta_entry;
sync_entry->set_version(meta_entry.Get(syncable::BASE_VERSION));
}
sync_entry->set_ctime(ClientTimeToServerTime(
meta_entry.Get(syncable::CTIME)));
sync_entry->set_mtime(ClientTimeToServerTime(
meta_entry.Get(syncable::MTIME)));
set<ExtendedAttribute> extended_attributes;
meta_entry.GetAllExtendedAttributes(
session->write_transaction(), &extended_attributes);
set<ExtendedAttribute>::iterator iter;
sync_pb::ExtendedAttributes* mutable_extended_attributes =
sync_entry->mutable_extended_attributes();
for (iter = extended_attributes.begin(); iter != extended_attributes.end();
++iter) {
sync_pb::ExtendedAttributes_ExtendedAttribute *extended_attribute =
mutable_extended_attributes->add_extendedattribute();
extended_attribute->set_key(iter->key());
SyncerProtoUtil::CopyBlobIntoProtoBytes(iter->value(),
extended_attribute->mutable_value());
}
// Deletion is final on the server, let's move things and then delete them.
if (meta_entry.Get(syncable::IS_DEL)) {
sync_entry->set_deleted(true);
} else if (meta_entry.Get(syncable::IS_BOOKMARK_OBJECT)) {
sync_pb::SyncEntity_BookmarkData* bookmark =
sync_entry->mutable_bookmarkdata();
bookmark->set_bookmark_folder(meta_entry.Get(syncable::IS_DIR));
const Id& prev_id = meta_entry.Get(syncable::PREV_ID);
string prev_string = prev_id.IsRoot() ? string() : prev_id.GetServerId();
sync_entry->set_insert_after_item_id(prev_string);
if (!meta_entry.Get(syncable::IS_DIR)) {
string bookmark_url = meta_entry.Get(syncable::BOOKMARK_URL);
bookmark->set_bookmark_url(bookmark_url);
SyncerProtoUtil::CopyBlobIntoProtoBytes(
meta_entry.Get(syncable::BOOKMARK_FAVICON),
bookmark->mutable_bookmark_favicon());
}
}
}
session->status_controller()->mutable_commit_message()->CopyFrom(message);
}
} // namespace browser_sync
| 41.464516 | 80 | 0.715419 |
238147189c29475ac43a113d5e97782feee7d072 | 345 | cpp | C++ | OOP Lab/Lab9/LE/LE9_9.cpp | HANS-2002/Jab-sab-aapki-le-rahe-ho-tab-aap-bhi-kuch-lelo | 8a9d67153797e9a6d438151c70f6726a50079df4 | [
"MIT"
] | 2 | 2021-09-18T10:50:20.000Z | 2021-11-12T13:19:45.000Z | OOP Lab/Lab9/LE/LE9_9.cpp | HANS-2002/Jab-sab-aapki-le-rahe-ho-tab-aap-bhi-kuch-lelo | 8a9d67153797e9a6d438151c70f6726a50079df4 | [
"MIT"
] | null | null | null | OOP Lab/Lab9/LE/LE9_9.cpp | HANS-2002/Jab-sab-aapki-le-rahe-ho-tab-aap-bhi-kuch-lelo | 8a9d67153797e9a6d438151c70f6726a50079df4 | [
"MIT"
] | 3 | 2021-09-10T14:08:12.000Z | 2021-09-18T10:52:09.000Z | // (Class Template) Write a program to explain class template by creating a template T for a class
// named pair having two data members of type T which are inputted by a constructor and a
// member function get-max() return the greatest of two numbers to main. Note: the value of T
// depends upon the data type specified during object creation | 86.25 | 98 | 0.776812 |
2384b259525d7b7da51ab90093316c169352b226 | 15,767 | cpp | C++ | newbase/NFmiRect.cpp | fmidev/smartmet-library-newbase | 12d93660c06e3c66a039ea75530bd9ca5daf7ab8 | [
"MIT"
] | null | null | null | newbase/NFmiRect.cpp | fmidev/smartmet-library-newbase | 12d93660c06e3c66a039ea75530bd9ca5daf7ab8 | [
"MIT"
] | 7 | 2017-01-17T10:46:33.000Z | 2019-11-21T07:50:17.000Z | newbase/NFmiRect.cpp | fmidev/smartmet-library-newbase | 12d93660c06e3c66a039ea75530bd9ca5daf7ab8 | [
"MIT"
] | 2 | 2017-01-17T07:33:28.000Z | 2018-04-26T07:10:23.000Z | // ======================================================================
/*!
* \file NFmiRect.cpp
* \brief Implementation of class NFmiRect
*/
// ======================================================================
/*!
* \class NFmiRect
*
* Undocumented
*
*/
// ======================================================================
#include "NFmiRect.h"
#include <boost/functional/hash.hpp>
#include <macgyver/Exception.h>
#include <algorithm>
#include <fstream>
// ----------------------------------------------------------------------
/*!
* Constructor
*
* \param firstCorner Undocumented
* \param oppositeCorner Undocumented
*/
// ----------------------------------------------------------------------
NFmiRect::NFmiRect(const NFmiPoint &firstCorner, const NFmiPoint &oppositeCorner)
: itsPlace(std::min(firstCorner.X(), oppositeCorner.X()),
std::min(firstCorner.Y(), oppositeCorner.Y())),
itsSize(NFmiPoint(std::max(firstCorner.X(), oppositeCorner.X()),
std::max(firstCorner.Y(), oppositeCorner.Y())) -
itsPlace)
{
}
// ----------------------------------------------------------------------
/*!
* Constructor
*
* \param left Undocumented
* \param top Undocumented
* \param right Undocumented
* \param bottom Undocumented
*/
// ----------------------------------------------------------------------
NFmiRect::NFmiRect(double left, double top, double right, double bottom)
: itsPlace(std::min(left, right), std::min(top, bottom)),
itsSize(NFmiPoint(std::max(left, right), std::max(top, bottom)) - itsPlace)
{
}
// ----------------------------------------------------------------------
/*!
* \param theValue Undocumented
*/
// ----------------------------------------------------------------------
void NFmiRect::Inflate(double theValue)
{
try
{
itsSize += NFmiPoint(2 * theValue, 2 * theValue);
itsPlace -= NFmiPoint(theValue, theValue);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \param theXValue Undocumented
* \param theYValue Undocumented
*/
// ----------------------------------------------------------------------
void NFmiRect::Inflate(double theXValue, double theYValue)
{
try
{
itsSize += NFmiPoint(2 * theXValue, 2 * theYValue);
itsPlace -= NFmiPoint(theXValue, theYValue);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \param theValue Undocumented
*/
// ----------------------------------------------------------------------
void NFmiRect::Inflate(const NFmiPoint &theValue)
{
try
{
NFmiPoint theSizingValue(theValue);
theSizingValue += theValue;
itsSize += theSizingValue;
itsPlace -= theValue;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \param thePoint Undocumented
* \return Undocumented
*/
// ----------------------------------------------------------------------
const NFmiPoint NFmiRect::NearestCorner(const NFmiPoint &thePoint) const
{
try
{
double dLeftTop = TopLeft().Distance(thePoint);
double dRightTop = TopRight().Distance(thePoint);
double dLeftBottom = BottomLeft().Distance(thePoint);
double dRightBottom = BottomRight().Distance(thePoint);
if (dLeftTop <= dRightTop)
{
if (dLeftTop <= dLeftBottom)
return TopLeft();
else
return BottomLeft();
}
else
{
if (dRightTop <= dRightBottom)
return TopRight();
else
return BottomRight();
}
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \param theRatioXperY Undocumented
* \param fKeepX Undocumented
* \param theDirection Undocumented
* \return Undocumented
*/
// ----------------------------------------------------------------------
// Säätää rectin aspect ration halutuksi. fKeepX ollessa tosi ei muuteta
// x:n arvoja. Korjaukset tehdään halutun nurkan ('theDirection') suhteen
// eli valittu nurkka "pysyy paikallaan". Jos muutos on mahdoton (esim.
// aspectratio=0), palauttaa funktio false:n muuten true:n.
bool NFmiRect::AdjustAspectRatio(double theRatioXperY, bool fKeepX, FmiDirection theDirection)
{
try
{
if (theRatioXperY == 0.)
return false;
NFmiRect originalRect(itsPlace, itsPlace + itsSize); // 9.9.99/EL
if (fKeepX)
Size(NFmiPoint(Width(), Width() / theRatioXperY));
else
Size(NFmiPoint(theRatioXperY * Height(), Height()));
double newWidth = Width();
double newHeight = Height();
// Origona on nurkka 'kTopLeft' missä (X,Y) = TopLeft()
// X kasvaa "vasemmalta oikealle"
// Y kasvaa "ylhäältä alas"
switch (theDirection)
{
case kTopLeft:
return true; // Nurkka on origossa - Place() pysyy paikallaan
case kTopRight:
Place(NFmiPoint(originalRect.TopRight().X() - newWidth, TopRight().Y()));
return true;
case kBottomLeft:
Place(NFmiPoint(originalRect.BottomLeft().X(), originalRect.BottomLeft().Y() - newHeight));
return true;
case kBottomRight:
Place(NFmiPoint(originalRect.BottomRight().X() - newWidth,
originalRect.BottomRight().Y() - newHeight));
return true;
case kCenter:
Center(originalRect.Center());
return true;
default:
return false;
}
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* Projisoi annetun maailma koordinaatin siten että jos piste on rectin
* sisällä, palautettu rect saa arvon 0,0 - 1,1 sen mukaan miten se rectin
* sisään osui. Origo on top-left ja 1,1 on bottom-right kulma. Jos se on
* ruudun ulkona, tulee mukaan mahdolliset negatiiviset ja 1:stä suuremmat arvot.
*
* \param thePoint The relative world point that is projected to rect dimensions.
* \return The given point in rect's world coordinates.
*/
// ----------------------------------------------------------------------
const NFmiPoint NFmiRect::Project(const NFmiPoint &thePlace) const
{
try
{
NFmiPoint newPoint = thePlace - TopLeft();
return NFmiPoint(newPoint.X() / Width(), newPoint.Y() / Height());
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* Assignment operator
*
* \param thePoint The other object being assigned
* \return The assigned object
*/
// ----------------------------------------------------------------------
NFmiRect &NFmiRect::operator+=(const NFmiPoint &thePoint)
{
try
{
itsPlace += thePoint;
return *this;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* Substraction operator
*
* \param thePoint The coordinates being substracted
* \return The resulting rectangle
*/
// ----------------------------------------------------------------------
NFmiRect &NFmiRect::operator-=(const NFmiPoint &thePoint)
{
try
{
itsPlace -= thePoint;
return *this;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* Addition operator
*
* \param theRect The rectangle being added
* \return The resulting rectangle
*/
// ----------------------------------------------------------------------
NFmiRect &NFmiRect::operator+=(const NFmiRect &theRect)
{
try
{
itsPlace = NFmiPoint(Left() < theRect.Left() ? Left() : theRect.Left(),
Top() < theRect.Top() ? Top() : theRect.Top());
itsSize = NFmiPoint(Right() > theRect.Right() ? Right() : theRect.Right(),
Bottom() > theRect.Bottom() ? Bottom() : theRect.Bottom()) -
itsPlace;
return *this;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* Substraction operator
*
* \param theRect The rectangle being substracted
* \result The resulting rectangle
*/
// ----------------------------------------------------------------------
NFmiRect &NFmiRect::operator-=(const NFmiRect &theRect)
{
try
{
itsPlace = NFmiPoint(Left() > theRect.Left() ? Left() : theRect.Left(),
Top() > theRect.Top() ? Top() : theRect.Top());
itsSize = NFmiPoint(Right() < theRect.Right() ? Right() : theRect.Right(),
Bottom() < theRect.Bottom() ? Bottom() : theRect.Bottom()) -
itsPlace;
return *this;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \param newCenter Undocumented
*/
// ----------------------------------------------------------------------
void NFmiRect::Center(const NFmiPoint &newCenter)
{
try
{
Place(NFmiPoint(newCenter.X() - (Width() / 2.), newCenter.Y() - (Height() / 2.)));
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* Palauttaa kahta rectiä ympäröivän rectin.
* \param theRect Undocumented
* \result Undocumented
*/
// ----------------------------------------------------------------------
const NFmiRect NFmiRect::SmallestEnclosing(const NFmiRect &theRect) const
{
try
{
double left = Left() < theRect.Left() ? Left() : theRect.Left();
double top = Top() < theRect.Top() ? Top() : theRect.Top();
double right = Right() > theRect.Right() ? Right() : theRect.Right();
double bottom = Bottom() > theRect.Bottom() ? Bottom() : theRect.Bottom();
return NFmiRect(left, top, right, bottom);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* Palauttaa pienimmän rect:in, mikä pitää sisällään this-rect:in ja
* parametrina annetun rect:in eli leikkaus.
* \param theRect Undocumented
* \result Undocumented
*/
// ----------------------------------------------------------------------
const NFmiRect NFmiRect::Intersection(const NFmiRect &theRect) const
{
try
{
double left = Left() > theRect.Left() ? Left() : theRect.Left();
double top = Top() > theRect.Top() ? Top() : theRect.Top();
double right = Right() < theRect.Right() ? Right() : theRect.Right();
double bottom = Bottom() < theRect.Bottom() ? Bottom() : theRect.Bottom();
return NFmiRect(left, top, right, bottom);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* Write the rectangle to the given output stream
*
* \param file The output stream to write to
* \result The output stream written to
*/
// ----------------------------------------------------------------------
std::ostream &NFmiRect::Write(std::ostream &file) const
{
try
{
file << itsPlace;
file << itsSize;
return file;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* Read new rectangle definition from the given input stream
*
* \param file The input stream to read from
* \return The input stream read from
*/
// ----------------------------------------------------------------------
std::istream &NFmiRect::Read(std::istream &file)
{
try
{
file >> itsPlace;
file >> itsSize;
return file;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* Addition of a point and a rectangle
*
* \param leftPoint Undocumented
* \param rightRect Undocumented
* \return Undocumemted
*/
// ----------------------------------------------------------------------
NFmiRect operator+(const NFmiPoint &leftPoint, const NFmiRect &rightRect)
{
try
{
return NFmiRect(
NFmiPoint(leftPoint.X() + rightRect.Left(), leftPoint.Y() + rightRect.Top()),
NFmiPoint(leftPoint.X() + rightRect.Right(), leftPoint.Y() + rightRect.Bottom()));
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* Substraction of a point and a rectangle
*
* \param leftPoint Undocumented
* \param rightRect Undocumented
* \return Undocumemted
*/
// ----------------------------------------------------------------------
NFmiRect operator-(const NFmiPoint &leftPoint, const NFmiRect &rightRect)
{
try
{
return NFmiRect(
NFmiPoint(leftPoint.X() - rightRect.Left(), leftPoint.Y() - rightRect.Top()),
NFmiPoint(leftPoint.X() - rightRect.Right(), leftPoint.Y() - rightRect.Bottom()));
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* Addition of a point and a rectangle
*
* \param leftRect Undocumented
* \param rightPoint Undocumented
* \result Undocumented
*/
// ----------------------------------------------------------------------
NFmiRect operator+(const NFmiRect &leftRect, const NFmiPoint &rightPoint)
{
try
{
return NFmiRect(
NFmiPoint(rightPoint.X() + leftRect.Left(), rightPoint.Y() + leftRect.Top()),
NFmiPoint(rightPoint.X() + leftRect.Right(), rightPoint.Y() + leftRect.Bottom()));
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* Substraction of a rectangle and a point
*
* \param leftRect Undocumented
* \param rightPoint Undocumented
* \result Undocumented
*/
// ----------------------------------------------------------------------
NFmiRect operator-(const NFmiRect &leftRect, const NFmiPoint &rightPoint)
{
try
{
return NFmiRect(
NFmiPoint(rightPoint.X() - leftRect.Left(), rightPoint.Y() - leftRect.Top()),
NFmiPoint(rightPoint.X() - leftRect.Right(), rightPoint.Y() - leftRect.Bottom()));
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
bool NFmiRect::Intersect(const NFmiRect &theRect) const
{
try
{
if (this->Left() < theRect.Right() && this->Right() > theRect.Left() &&
this->Top() < theRect.Bottom() && this->Bottom() > theRect.Top())
return true;
else
return false;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Return hash value for the rectangle
*/
// ----------------------------------------------------------------------
std::size_t NFmiRect::HashValue() const
{
try
{
std::size_t hash = itsPlace.HashValue();
boost::hash_combine(hash, itsSize.HashValue());
return hash;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ======================================================================
| 26.814626 | 99 | 0.490328 |
2385728ed6e584fa445b30a6a16b3161dcf5820b | 3,542 | cpp | C++ | scaffold/Setting.cpp | taozhijiang/roo | bea672b9274f91f4002a9742e096152b0d62f122 | [
"BSD-3-Clause"
] | null | null | null | scaffold/Setting.cpp | taozhijiang/roo | bea672b9274f91f4002a9742e096152b0d62f122 | [
"BSD-3-Clause"
] | null | null | null | scaffold/Setting.cpp | taozhijiang/roo | bea672b9274f91f4002a9742e096152b0d62f122 | [
"BSD-3-Clause"
] | 2 | 2019-08-23T02:31:42.000Z | 2020-05-02T00:12:36.000Z | /*-
* Copyright (c) 2019 TAO Zhijiang<taozhijiang@gmail.com>
*
* Licensed under the BSD-3-Clause license, see LICENSE for full information.
*
*/
#include <sstream>
#include <iostream>
#include <scaffold/Setting.h>
#include <scaffold/Status.h>
namespace roo {
bool Setting::init(std::string file) {
cfg_file_ = file;
setting_ptr_.reset( new libconfig::Config() );
if (!setting_ptr_) {
log_err("create libconfig failed.");
return false;
}
// try load and explain the cfg_file first.
try {
setting_ptr_->readFile(file.c_str());
} catch(libconfig::FileIOException &fioex) {
fprintf(stderr, "I/O error while reading file: %s.", file.c_str());
log_err( "I/O error while reading file: %s.", file.c_str());
setting_ptr_.reset();
} catch(libconfig::ParseException &pex) {
fprintf(stderr, "Parse error at %d - %s", pex.getLine(), pex.getError());
log_err( "Parse error at %d - %s", pex.getLine(), pex.getError());
setting_ptr_.reset();
}
// when init, parse conf failed was critical.
if (!setting_ptr_) {
return false;
}
return true;
}
int Setting::update_runtime_setting() {
if (cfg_file_.empty()) {
log_err("param cfg_file is not set, may not initialized ???");
return -1;
}
std::lock_guard<std::mutex> lock(lock_);
if (in_process_) {
log_err("!!! already in process, please try again later!");
return 0;
}
auto setting = load_cfg_file();
if (!setting) {
in_process_ = false;
log_err("load config file %s failed.", cfg_file_.c_str());
return false;
}
// 重新读取配置并且解析成功之后,才更新这个指针
std::swap(setting, setting_ptr_);
last_update_time_ = ::time(NULL);
int ret = 0;
for (auto it = calls_.begin(); it != calls_.end(); ++it) {
ret += (it->second)(*setting_ptr_); // call it!
}
log_warning("Setting::update_runtime_conf total callback return: %d", ret);
in_process_ = false;
return ret;
}
int Setting::attach_runtime_callback(const std::string& name, SettingUpdateCallable func) {
if (name.empty() || !func){
log_err("invalid name or func param.");
return -1;
}
std::lock_guard<std::mutex> lock(lock_);
calls_.push_back({name, func});
log_info("register runtime for %s success.", name.c_str());
return 0;
}
int Setting::module_status(std::string& module, std::string& name, std::string& val) {
module = "roo";
name = "Setting";
std::stringstream ss;
ss << "attached runtime update: " << std::endl;
std::lock_guard<std::mutex> lock(lock_);
int i = 1;
for (auto it = calls_.begin(); it != calls_.end(); ++it) {
ss << "\t" << i++ << ". "<< it->first << std::endl;
}
val = ss.str();
return 0;
}
std::shared_ptr<libconfig::Config> Setting::load_cfg_file() {
std::shared_ptr<libconfig::Config> setting = std::make_shared<libconfig::Config>();
if (!setting) {
log_err("create libconfig::Config instance failed!");
return setting; // nullptr
}
try {
setting->readFile(cfg_file_.c_str());
} catch (libconfig::FileIOException& fioex) {
log_err("I/O error while reading file: %s.", cfg_file_.c_str());
setting.reset();
} catch (libconfig::ParseException& pex) {
log_err("Parse error at %d - %s", pex.getLine(), pex.getError());
setting.reset();
}
return setting;
}
} // end namespace roo
| 25.120567 | 91 | 0.601073 |
23875d96f499e5a6f87d8a846965a7aab0aeabaa | 1,736 | cxx | C++ | HTRunInfo/HTDAQStackInfo.cxx | dellaquilamaster/RIBbit2 | 5e792724676a7b84e19e9512b2d6295287f81a4e | [
"Unlicense"
] | null | null | null | HTRunInfo/HTDAQStackInfo.cxx | dellaquilamaster/RIBbit2 | 5e792724676a7b84e19e9512b2d6295287f81a4e | [
"Unlicense"
] | null | null | null | HTRunInfo/HTDAQStackInfo.cxx | dellaquilamaster/RIBbit2 | 5e792724676a7b84e19e9512b2d6295287f81a4e | [
"Unlicense"
] | 1 | 2019-05-03T17:50:21.000Z | 2019-05-03T17:50:21.000Z | #include <HTDAQStackInfo.h>
//________________________________________________
HTDAQStackInfo::HTDAQStackInfo(const char * name, int stackID) :
fNModules(0),
fStackName(name),
fStackID(stackID)
{}
//________________________________________________
HTDAQStackInfo::~HTDAQStackInfo()
{
Clear();
}
//________________________________________________
void HTDAQStackInfo::Clear()
{
for(int i=0; i<fNModules; i++) {
if(fModuleInStack[i]) {
delete fModuleInStack[i];
}
}
fModuleInStack.clear();
fNModules=0;
}
//________________________________________________
int HTDAQStackInfo::GetNModules() const
{
return fNModules;
}
//________________________________________________
RBElectronics * HTDAQStackInfo::GetModule(int n_module) const
{
return fModuleInStack[n_module]->GetModule();
}
//________________________________________________
const char * HTDAQStackInfo::GetModuleType(int n_module) const
{
return fModuleInStack[n_module]->GetModuleType();
}
//________________________________________________
int HTDAQStackInfo::GetModuleVSN(int n_module) const
{
return fModuleInStack[n_module]->GetVSN();
}
//________________________________________________
int HTDAQStackInfo::GetStackID() const
{
return fStackID;
}
//________________________________________________
const char * HTDAQStackInfo::GetStackName() const
{
return fStackName.c_str();
}
//________________________________________________
HTModuleInfo * HTDAQStackInfo::GetModuleInfo(int n_module) const
{
return fModuleInStack[n_module];
}
//________________________________________________
void HTDAQStackInfo::AddModuleInfo(HTModuleInfo * new_module_info)
{
fNModules++;
fModuleInStack.push_back(new_module_info);
return;
}
| 22.545455 | 66 | 0.801843 |
238de8358cb0938b34eacfe1305a0bb6b5442982 | 3,202 | cpp | C++ | unit_tests/core/math/euler_angles/src/unit_euler_angles.cpp | ricortiz/OpenTissue | f8c8ebc5137325b77ba90bed897f6be2795bd6fb | [
"Zlib"
] | 76 | 2018-02-20T11:30:52.000Z | 2022-03-31T12:45:06.000Z | unit_tests/core/math/euler_angles/src/unit_euler_angles.cpp | ricortiz/OpenTissue | f8c8ebc5137325b77ba90bed897f6be2795bd6fb | [
"Zlib"
] | 27 | 2018-11-20T14:32:49.000Z | 2021-11-24T15:26:45.000Z | unit_tests/core/math/euler_angles/src/unit_euler_angles.cpp | ricortiz/OpenTissue | f8c8ebc5137325b77ba90bed897f6be2795bd6fb | [
"Zlib"
] | 24 | 2018-02-21T01:45:26.000Z | 2022-03-07T07:06:49.000Z | //
// OpenTissue, A toolbox for physical based simulation and animation.
// Copyright (C) 2007 Department of Computer Science, University of Copenhagen
//
#include <OpenTissue/configuration.h>
#include <OpenTissue/core/math/math_euler_angles.h>
#define BOOST_AUTO_TEST_MAIN
#include <OpenTissue/utility/utility_push_boost_filter.h>
#include <boost/test/auto_unit_test.hpp>
#include <boost/test/unit_test_suite.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <boost/test/test_tools.hpp>
#include <OpenTissue/utility/utility_pop_boost_filter.h>
using namespace OpenTissue;
void do_test( double const & phi_in, double const & psi_in, double const & theta_in)
{
OpenTissue::math::Quaternion<double> Q_in;
OpenTissue::math::Quaternion<double> Q_out;
OpenTissue::math::Quaternion<double> identity;
OpenTissue::math::Quaternion<double> Qz1;
OpenTissue::math::Quaternion<double> Qy;
OpenTissue::math::Quaternion<double> Qz2;
double const too_small = 10e-7;
double phi_out = 0.0;
double psi_out = 0.0;
double theta_out = 0.0;
Qz1.Rz(theta_in);
Qy.Ry(psi_in);
Qz2.Rz(phi_in);
Q_in = OpenTissue::math::prod( Qz2 , OpenTissue::math::prod( Qy , Qz1) );
OpenTissue::math::ZYZ_euler_angles(Q_in,phi_out,psi_out,theta_out);
if(psi_in > 0.0)
{
// we only want to do this if we are not in a gimbal lock
Qz1.Rz(theta_out);
Qy.Ry(psi_out);
Qz2.Rz(phi_out);
Q_out = OpenTissue::math::prod( Qz2 , OpenTissue::math::prod( Qy , Qz1) );
identity = OpenTissue::math::prod( OpenTissue::math::conj(Q_out), Q_in );
double const s = fabs( fabs(identity.s()) - 1.0 );
double const v0 = fabs(identity.v()(0));
double const v1 = fabs(identity.v()(1));
double const v2 = fabs(identity.v()(2));
BOOST_CHECK( s < too_small);
BOOST_CHECK( v0 < too_small);
BOOST_CHECK( v1 < too_small);
BOOST_CHECK( v2 < too_small);
double const dphi = fabs(phi_in - phi_out);
double const dpsi = fabs(psi_in - psi_out);
double const dtheta = fabs(theta_in - theta_out);
BOOST_CHECK( dphi < too_small);
BOOST_CHECK( dpsi < too_small);
BOOST_CHECK( dtheta < too_small);
}
else
{
// In gimbal lock phi and theta behaves strangely
BOOST_CHECK_CLOSE( 0.0, theta_out, 0.01);
double const dpsi = fabs(psi_out);
BOOST_CHECK( dpsi < too_small);
double new_phi = phi_in + theta_in;
double const pi = 3.1415926535897932384626433832795;
double const two_pi = 2.0*pi;
while(new_phi>pi) new_phi -= two_pi;
while(new_phi<-pi) new_phi += two_pi;
double const dphi = fabs(new_phi - phi_out);
BOOST_CHECK( dphi < too_small);
}
}
BOOST_AUTO_TEST_SUITE(opentissue_math_euler_angles);
BOOST_AUTO_TEST_CASE(ZYZ)
{
size_t N = 15;
double const pi = 3.1415926535897932384626433832795;
double const two_pi = 2.0*pi;
double const delta = (two_pi)/(N-1);
double phi = -pi+delta;
for(;phi<pi;)
{
double psi = 0.0;
for(;psi<pi;)
{
double theta = -pi+delta;
for(;theta<pi;)
{
do_test( phi, psi, theta );
theta += delta;
}
psi += delta;
}
phi += delta;
}
}
BOOST_AUTO_TEST_SUITE_END();
| 27.367521 | 84 | 0.67614 |
2390b9de6c1a931be7e506b913688dfde1b290ed | 902 | cpp | C++ | Recover Binary Search Tree.cpp | Subhash3/Algorithms-For-Software-Developers | 2e0ac4f51d379a2b10a40fca7fa82a8501d3db94 | [
"BSD-2-Clause"
] | 2 | 2021-10-01T04:20:04.000Z | 2021-10-01T04:20:06.000Z | Recover Binary Search Tree.cpp | Subhash3/Algorithms-For-Software-Developers | 2e0ac4f51d379a2b10a40fca7fa82a8501d3db94 | [
"BSD-2-Clause"
] | 1 | 2021-10-01T18:00:09.000Z | 2021-10-01T18:00:09.000Z | Recover Binary Search Tree.cpp | Subhash3/Algorithms-For-Software-Developers | 2e0ac4f51d379a2b10a40fca7fa82a8501d3db94 | [
"BSD-2-Clause"
] | 8 | 2021-10-01T04:20:38.000Z | 2022-03-19T17:05:05.000Z | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* first=0;
TreeNode* sec=0;
TreeNode* prev=new TreeNode(INT_MIN);
void inorder(TreeNode* root){
if(!root)
return;
inorder(root->left);
if(!first&&root->val<prev->val)
first=prev;
if(first&&root->val<prev->val)
sec=root;
prev=root;
inorder(root->right);
}
void recoverTree(TreeNode* root) {
inorder(root);
int temp=first->val;
first->val=sec->val;
sec->val=temp;
}
};
| 25.771429 | 93 | 0.543237 |
2390ce9b12915def58828d146a76a85e540b6710 | 136,156 | cc | C++ | firmware/src/shared/Menu.cc | togetherPeter/Sailfish-G3Firmware3 | af5ffb1648825e03563c3c488c4d45685b957960 | [
"AAL"
] | null | null | null | firmware/src/shared/Menu.cc | togetherPeter/Sailfish-G3Firmware3 | af5ffb1648825e03563c3c488c4d45685b957960 | [
"AAL"
] | null | null | null | firmware/src/shared/Menu.cc | togetherPeter/Sailfish-G3Firmware3 | af5ffb1648825e03563c3c488c4d45685b957960 | [
"AAL"
] | null | null | null | // Future things that could be consolidated into 1 to save code space when required:
//
// Combined lcd.clear() and lcd.setCursor(0, 0) -> lcd.clearHomeCursor(): savings 184 bytes
// lcd.setCursor(0, r) --> lcd.setRow(r): savings 162 bytes
//
// ValueSetScreen
// BuzzerSetRepeatsMode
// ABPCopiesSetScreen
#include "Configuration.hh"
// TODO: Kill this, should be hanlded by build system.
#ifdef HAS_INTERFACE_BOARD
#include "Menu.hh"
#include "StepperAccel.hh"
#include "Steppers.hh"
#include "Commands.hh"
#include "Errors.hh"
#include "Tool.hh"
#include "Host.hh"
#include "Timeout.hh"
#include "InterfaceBoard.hh"
#include "Interface.hh"
#include "Motherboard.hh"
#include "Version.hh"
#include <util/delay.h>
#include <stdlib.h>
#include "SDCard.hh"
#include "EepromMap.hh"
#include "Eeprom.hh"
#include "EepromDefaults.hh"
#include <avr/eeprom.h>
#include "ExtruderControl.hh"
#include "Main.hh"
#include "locale.h"
#include "lib_sd/sd_raw_err.h"
// Maximum length of an SD card file
#define SD_MAXFILELEN 64
#define HOST_PACKET_TIMEOUT_MS 20
#define HOST_PACKET_TIMEOUT_MICROS (1000L*HOST_PACKET_TIMEOUT_MS)
#define HOST_TOOL_RESPONSE_TIMEOUT_MS 50
#define HOST_TOOL_RESPONSE_TIMEOUT_MICROS (1000L*HOST_TOOL_RESPONSE_TIMEOUT_MS)
#define MAX_ITEMS_PER_SCREEN 4
#define LCD_TYPE_CHANGE_BUTTON_HOLD_TIME 10.0
int16_t overrideExtrudeSeconds = 0;
int8_t autoPause;
Point homePosition;
static uint16_t genericOnOff_offset;
static uint8_t genericOnOff_default;
static const prog_uchar *genericOnOff_msg1;
static const prog_uchar *genericOnOff_msg2;
static const prog_uchar *genericOnOff_msg3;
static const prog_uchar *genericOnOff_msg4;
static const PROGMEM prog_uchar eof_msg1[] = "Extruder Hold:";
static const PROGMEM prog_uchar generic_off[] = "Off";
static const PROGMEM prog_uchar generic_on[] = "On";
static const PROGMEM prog_uchar updnset_msg[] = "Up/Dn/Ent to Set";
static const PROGMEM prog_uchar unknown_temp[] = "XXX";
static const PROGMEM prog_uchar aof_msg1[] = "Accelerated";
static const PROGMEM prog_uchar aof_msg2[] = "Printing:";
static const PROGMEM prog_uchar ts_msg1[] = "Toolhead offset";
static const PROGMEM prog_uchar ts_msg2[] = "system:";
static const PROGMEM prog_uchar ts_old[] = "Old";
static const PROGMEM prog_uchar ts_new[] = "New";
static const PROGMEM prog_uchar dp_msg1[] = "Ditto Printing:";
static const PROGMEM prog_uchar ogct_msg1[] = "Override GCode";
static const PROGMEM prog_uchar ogct_msg2[] = "Temperature:";
static const PROGMEM prog_uchar sdcrc_msg1[] = "Perform SD card";
static const PROGMEM prog_uchar sdcrc_msg2[] = "error checking:";
#ifdef PSTOP_SUPPORT
static const PROGMEM prog_uchar pstop_msg1[] = "P-Stop:";
#endif
//Macros to expand SVN revision macro into a str
#define STR_EXPAND(x) #x //Surround the supplied macro by double quotes
#define STR(x) STR_EXPAND(x)
const static PROGMEM prog_uchar units_mm[] = "mm";
static const char dumpFilename[] = "eeprom_dump.bin";
static void timedMessage(LiquidCrystal& lcd, uint8_t which);
void VersionMode::reset() {
}
// Assumes room for up to 7 + NUL
static void formatTime(char *buf, uint32_t val)
{
bool hasdigit = false;
uint8_t idx = 0;
uint8_t radidx = 0;
const uint8_t radixcount = 5;
const uint8_t houridx = 2;
const uint8_t minuteidx = 4;
uint32_t radixes[radixcount] = {360000, 36000, 3600, 600, 60};
if (val >= 3600000)
val %= 3600000;
for (radidx = 0; radidx < radixcount; radidx++) {
char digit = '0';
uint8_t bit = 8;
uint32_t radshift = radixes[radidx] << 3;
for (; bit > 0; bit >>= 1, radshift >>= 1) {
if (val > radshift) {
val -= radshift;
digit += bit;
}
}
if (hasdigit || digit != '0' || radidx >= houridx) {
buf[idx++] = digit;
hasdigit = true;
} else
buf[idx++] = ' ';
if (radidx == houridx)
buf[idx++] = 'h';
else if (radidx == minuteidx)
buf[idx++] = 'm';
}
buf[idx] = '\0';
}
// Assumes at least 3 spare bytes
static void digits3(char *buf, uint8_t val)
{
uint8_t v;
if ( val >= 100 )
{
v = val / 100;
buf[0] = v + '0';
val -= v * 100;
}
else
buf[0] = ' ';
if ( val >= 10 || buf[0] != ' ')
{
v = val / 10;
buf[1] = v + '0';
val -= v * 10;
}
else
buf[1] = ' ';
buf[2] = val + '0';
buf[3] = '\0';
}
void SplashScreen::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar splash1[] = " Sailfish v" VERSION_STR " ";
#if defined(__AVR_ATmega2560__)
const static PROGMEM prog_uchar splash2[] = "- ATmega 2560 - ";
#else
const static PROGMEM prog_uchar splash2[] = "- ATmega 1280 - ";
#endif
const static PROGMEM prog_uchar splash3[] = " Thing 32084 ";
const static PROGMEM prog_uchar splash4[] = " r" SVN_VERSION_STR " " DATE_STR;
if (forceRedraw) {
lcd.homeCursor();
lcd.writeFromPgmspace(LOCALIZE(splash1));
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(splash2));
lcd.setRow(2);
lcd.writeFromPgmspace(LOCALIZE(splash3));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(splash4));
#ifdef MENU_L10N_H_
lcd.setCursor(9,3);
lcd.writeString((char *)SVN_VERSION_STR);
#endif
}
else {
// The machine has started, so we're done!
interface::popScreen();
}
}
void SplashScreen::notifyButtonPressed(ButtonArray::ButtonName button) {
// We can't really do anything, since the machine is still loading, so ignore.
}
void SplashScreen::reset() {
}
UserViewMenu::UserViewMenu() {
itemCount = 4;
reset();
}
void UserViewMenu::resetState() {
uint8_t jogModeSettings = eeprom::getEeprom8(eeprom::JOG_MODE_SETTINGS, EEPROM_DEFAULT_JOG_MODE_SETTINGS);
if ( jogModeSettings & 0x01 ) itemIndex = 3;
else itemIndex = 2;
firstItemIndex = 2;
}
void UserViewMenu::drawItem(uint8_t index, LiquidCrystal& lcd) {
const static PROGMEM prog_uchar uv_msg[] = "X/Y Direction:";
const static PROGMEM prog_uchar uv_model[]= "Model View";
const static PROGMEM prog_uchar uv_user[] = "User View";
const prog_uchar *msg;
switch (index) {
case 0:
msg = LOCALIZE(uv_msg);
break;
default:
case 1:
return;
case 2:
msg = LOCALIZE(uv_model);
break;
case 3:
msg = LOCALIZE(uv_user);
break;
}
lcd.writeFromPgmspace(msg);
}
void UserViewMenu::handleSelect(uint8_t index) {
uint8_t jogModeSettings = eeprom::getEeprom8(eeprom::JOG_MODE_SETTINGS, EEPROM_DEFAULT_JOG_MODE_SETTINGS);
switch (index) {
default:
return;
case 2:
// Model View
jogModeSettings &= (uint8_t)0xFE;
break;
case 3:
// User View
jogModeSettings |= (uint8_t)0x01;
break;
}
eeprom_write_byte((uint8_t *)eeprom::JOG_MODE_SETTINGS,
jogModeSettings);
interface::popScreen();
}
void JoggerMenu::jog(ButtonArray::ButtonName direction, bool pauseModeJog) {
int32_t interval = 1000;
float speed = 1.5; //In mm's
if ( pauseModeJog ) jogDistance = DISTANCE_CONT;
else {
switch(jogDistance) {
case DISTANCE_0_1MM:
speed = 0.1; //0.1mm
break;
case DISTANCE_1MM:
speed = 1.0; //1mm
break;
case DISTANCE_CONT:
speed = 1.5; //1.5mm
break;
}
}
//Reverse direction of X and Y if we're in User View Mode and
//not model mode
int32_t vMode = 1;
if ( userViewMode ) vMode = -1;
float stepsPerSecond;
enum AxisEnum axisIndex = X_AXIS;
uint16_t eepromLocation = eeprom::HOMING_FEED_RATE_X;
uint8_t activeToolhead;
Point position = steppers::getStepperPosition(&activeToolhead);
switch(direction) {
case ButtonArray::XMINUS:
position[0] -= vMode * stepperAxisMMToSteps(speed,X_AXIS);
eepromLocation = eeprom::HOMING_FEED_RATE_X; axisIndex = X_AXIS;
break;
case ButtonArray::XPLUS:
position[0] += vMode * stepperAxisMMToSteps(speed,X_AXIS);
eepromLocation = eeprom::HOMING_FEED_RATE_X; axisIndex = X_AXIS;
break;
case ButtonArray::YMINUS:
position[1] -= vMode * stepperAxisMMToSteps(speed,Y_AXIS);
eepromLocation = eeprom::HOMING_FEED_RATE_Y; axisIndex = Y_AXIS;
break;
case ButtonArray::YPLUS:
position[1] += vMode * stepperAxisMMToSteps(speed,Y_AXIS);
eepromLocation = eeprom::HOMING_FEED_RATE_Y; axisIndex = Y_AXIS;
break;
case ButtonArray::ZMINUS:
position[2] -= stepperAxisMMToSteps(speed,Z_AXIS);
eepromLocation = eeprom::HOMING_FEED_RATE_Z; axisIndex = Z_AXIS;
break;
case ButtonArray::ZPLUS:
position[2] += stepperAxisMMToSteps(speed,Z_AXIS);
eepromLocation = eeprom::HOMING_FEED_RATE_Z; axisIndex = Z_AXIS;
break;
case ButtonArray::CANCEL:
break;
case ButtonArray::OK:
case ButtonArray::ZERO:
if ( ! pauseModeJog ) break;
eepromLocation = 0;
float mms = (float)eeprom::getEeprom8(eeprom::EXTRUDE_MMS, EEPROM_DEFAULT_EXTRUDE_MMS);
stepsPerSecond = mms * stepperAxisStepsPerMM(A_AXIS);
interval = (int32_t)(1000000.0 / stepsPerSecond);
//Handle reverse
if ( direction == ButtonArray::OK ) stepsPerSecond *= -1;
if ( ! ACCELERATION_EXTRUDE_WHEN_NEGATIVE_A ) stepsPerSecond *= -1;
//Extrude for 0.5 seconds
position[activeToolhead + A_AXIS] += (int32_t)(0.5 * stepsPerSecond);
break;
}
if ( jogDistance == DISTANCE_CONT ) lastDirectionButtonPressed = direction;
else lastDirectionButtonPressed = (ButtonArray::ButtonName)0;
if ( eepromLocation != 0 ) {
//60.0, because feed rate is in mm/min units, we convert to seconds
float feedRate = (float)eeprom::getEepromUInt32(eepromLocation, 500) / 60.0;
stepsPerSecond = feedRate * (float)stepperAxisStepsPerMM(axisIndex);
interval = (int32_t)(1000000.0 / stepsPerSecond);
}
steppers::setTarget(position, interval);
}
bool MessageScreen::screenWaiting(void){
return (timeout.isActive() || incomplete);
}
void MessageScreen::addMessage(CircularBuffer& buf) {
char c = buf.pop();
while (c != '\0' && buf.getLength() > 0) {
if ( cursor < BUF_SIZE ) message[cursor++] = c;
c = buf.pop();
}
// ensure that message is always null-terminated
if (cursor >= BUF_SIZE) {
message[BUF_SIZE-1] = '\0';
} else {
message[cursor] = '\0';
}
}
void MessageScreen::addMessage(const prog_uchar msg[]) {
if ( cursor >= BUF_SIZE )
return;
cursor += strlcpy_P(message + cursor, (const prog_char *)msg,
BUF_SIZE - cursor);
// ensure that message is always null-terminated
if (cursor >= BUF_SIZE) {
message[BUF_SIZE-1] = '\0';
} else {
message[cursor] = '\0';
}
}
void MessageScreen::clearMessage() {
x = y = 0;
message[0] = '\0';
cursor = 0;
needsRedraw = false;
timeout = Timeout();
incomplete = false;
}
void MessageScreen::setTimeout(uint8_t seconds) {
timeout.start((micros_t)seconds * (micros_t)1000 * (micros_t)1000);
}
void MessageScreen::refreshScreen(){
needsRedraw = true;
}
void MessageScreen::update(LiquidCrystal& lcd, bool forceRedraw) {
char* b = message;
int ycursor = y, xcursor = x;
if (timeout.hasElapsed()) {
InterfaceBoard& ib = Motherboard::getBoard().getInterfaceBoard();
ib.hideMessageScreen();
return;
}
if (forceRedraw || needsRedraw) {
needsRedraw = false;
lcd.clear();
lcd.setCursor(xcursor, ycursor);
while (*b != '\0') {
if (( *b == '\n' ) || ( xcursor >= lcd.getDisplayWidth() )) {
xcursor = 0;
ycursor++;
lcd.setCursor(xcursor, ycursor);
}
if ( *b != '\n' ) {
lcd.write(*b);
xcursor ++;
}
b ++;
}
}
}
void MessageScreen::reset() {
timeout = Timeout();
buttonsDisabled = false;
}
void MessageScreen::notifyButtonPressed(ButtonArray::ButtonName button) {
if ( buttonsDisabled ) return;
}
void JogMode::reset() {
uint8_t jogModeSettings = eeprom::getEeprom8(eeprom::JOG_MODE_SETTINGS, EEPROM_DEFAULT_JOG_MODE_SETTINGS);
jogDistance = (enum distance_t)((jogModeSettings >> 1 ) & 0x07);
if ( jogDistance > DISTANCE_CONT ) jogDistance = DISTANCE_0_1MM;
distanceChanged = false;
lastDirectionButtonPressed = (ButtonArray::ButtonName)0;
userViewMode = jogModeSettings & 0x01;
userViewModeChanged = false;
steppers::setSegmentAccelState(true);
}
void JogMode::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar j_jog1[] = "Jog mode: ";
const static PROGMEM prog_uchar j_jog2[] = " Y+ Z+";
const static PROGMEM prog_uchar j_jog3[] = "X- V X+ (mode)";
const static PROGMEM prog_uchar j_jog4[] = " Y- Z-";
const static PROGMEM prog_uchar j_jog2_user[] = " Y Z+";
const static PROGMEM prog_uchar j_jog3_user[] = "X V X (mode)";
const static PROGMEM prog_uchar j_jog4_user[] = " Y Z-";
const static PROGMEM prog_uchar j_distance0_1mm[] = ".1mm";
const static PROGMEM prog_uchar j_distance1mm[] = "1mm";
const static PROGMEM prog_uchar j_distanceCont[] = "Cont..";
if ( userViewModeChanged ) userViewMode = eeprom::getEeprom8(eeprom::JOG_MODE_SETTINGS, EEPROM_DEFAULT_JOG_MODE_SETTINGS) & 0x01;
if (forceRedraw || distanceChanged || userViewModeChanged) {
lcd.clearHomeCursor();
lcd.writeFromPgmspace(LOCALIZE(j_jog1));
switch (jogDistance) {
case DISTANCE_0_1MM:
lcd.write(0xF3); //Write tilde
lcd.writeFromPgmspace(LOCALIZE(j_distance0_1mm));
break;
case DISTANCE_1MM:
lcd.write(0xF3); //Write tilde
lcd.writeFromPgmspace(LOCALIZE(j_distance1mm));
break;
case DISTANCE_CONT:
lcd.writeFromPgmspace(LOCALIZE(j_distanceCont));
break;
}
lcd.setRow(1);
lcd.writeFromPgmspace(userViewMode ? LOCALIZE(j_jog2_user) : LOCALIZE(j_jog2));
lcd.setRow(2);
lcd.writeFromPgmspace(userViewMode ? LOCALIZE(j_jog3_user) : LOCALIZE(j_jog3));
lcd.setRow(3);
lcd.writeFromPgmspace(userViewMode ? LOCALIZE(j_jog4_user) : LOCALIZE(j_jog4));
distanceChanged = false;
userViewModeChanged = false;
}
if ( jogDistance == DISTANCE_CONT ) {
if ( lastDirectionButtonPressed ) {
if (!interface::isButtonPressed(lastDirectionButtonPressed)) {
lastDirectionButtonPressed = (ButtonArray::ButtonName)0;
steppers::abort();
}
}
}
}
void JogMode::notifyButtonPressed(ButtonArray::ButtonName button) {
switch (button) {
case ButtonArray::ZERO:
userViewModeChanged = true;
interface::pushScreen(&userViewMenu);
break;
case ButtonArray::OK:
switch(jogDistance)
{
case DISTANCE_0_1MM:
jogDistance = DISTANCE_1MM;
break;
case DISTANCE_1MM:
jogDistance = DISTANCE_CONT;
break;
case DISTANCE_CONT:
jogDistance = DISTANCE_0_1MM;
break;
}
distanceChanged = true;
eeprom_write_byte((uint8_t *)eeprom::JOG_MODE_SETTINGS, userViewMode | (jogDistance << 1));
break;
default:
if (( lastDirectionButtonPressed ) && (lastDirectionButtonPressed != button ))
steppers::abort();
jog(button, false);
break;
case ButtonArray::CANCEL:
steppers::abort();
steppers::enableAxis(0, false);
steppers::enableAxis(1, false);
steppers::enableAxis(2, false);
interface::popScreen();
steppers::setSegmentAccelState(true);
break;
}
}
void ExtruderMode::reset() {
extrudeSeconds = (enum extrudeSeconds)eeprom::getEeprom8(eeprom::EXTRUDE_DURATION, EEPROM_DEFAULT_EXTRUDE_DURATION);
updatePhase = 0;
timeChanged = false;
lastDirection = 1;
overrideExtrudeSeconds = 0;
steppers::setSegmentAccelState(false);
}
void ExtruderMode::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar e_extrude1[] = "Extrude: ";
const static PROGMEM prog_uchar e_extrude2[] = "(set mm/s) Fwd";
const static PROGMEM prog_uchar e_extrude3[] = " (stop) (dur)";
const static PROGMEM prog_uchar e_extrude4[] = "---/---C Rev";
const static PROGMEM prog_uchar e_secs[] = "SECS";
const static PROGMEM prog_uchar e_blank[] = " ";
if (overrideExtrudeSeconds) extrude((int32_t)overrideExtrudeSeconds, true);
if (forceRedraw) {
lcd.clearHomeCursor();
lcd.writeFromPgmspace(LOCALIZE(e_extrude1));
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(e_extrude2));
lcd.setRow(2);
lcd.writeFromPgmspace(LOCALIZE(e_extrude3));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(e_extrude4));
}
if ((forceRedraw) || (timeChanged)) {
lcd.setCursor(9,0);
lcd.writeFromPgmspace(LOCALIZE(e_blank));
lcd.setCursor(9,0);
lcd.writeFloat((float)extrudeSeconds, 0);
lcd.writeFromPgmspace(LOCALIZE(e_secs));
timeChanged = false;
}
OutPacket responsePacket;
Point position;
uint8_t activeToolhead;
// Redraw tool info
steppers::getStepperPosition(&activeToolhead);
switch (updatePhase) {
case 0:
lcd.setRow(3);
if (extruderControl(activeToolhead, SLAVE_CMD_GET_TEMP, EXTDR_CMD_GET, responsePacket, 0)) {
uint16_t data = responsePacket.read16(1);
lcd.writeInt(data, 3);
} else {
lcd.writeFromPgmspace(unknown_temp);
}
break;
case 1:
lcd.setCursor(4,3);
if (extruderControl(activeToolhead, SLAVE_CMD_GET_SP, EXTDR_CMD_GET, responsePacket, 0)) {
uint16_t data = responsePacket.read16(1);
lcd.writeInt(data, 3);
} else {
lcd.writeFromPgmspace(unknown_temp);
}
break;
}
updatePhase++;
if (updatePhase > 1) {
updatePhase = 0;
}
}
void ExtruderMode::extrude(int32_t seconds, bool overrideTempCheck) {
uint8_t activeToolhead;
Point position = steppers::getStepperPosition(&activeToolhead);
//Check we're hot enough
if ( ! overrideTempCheck )
{
OutPacket responsePacket;
if (extruderControl(activeToolhead, SLAVE_CMD_IS_TOOL_READY, EXTDR_CMD_GET, responsePacket, 0)) {
uint8_t data = responsePacket.read8(1);
if ( ! data )
{
overrideExtrudeSeconds = seconds;
interface::pushScreen(&extruderTooColdMenu);
return;
}
}
}
float mms = (float)eeprom::getEeprom8(eeprom::EXTRUDE_MMS, EEPROM_DEFAULT_EXTRUDE_MMS);
float stepsPerSecond = mms * stepperAxisStepsPerMM(A_AXIS);
int32_t interval = (int32_t)(1000000.0 / stepsPerSecond);
//Handle 5D
float direction = 1.0;
if ( ACCELERATION_EXTRUDE_WHEN_NEGATIVE_A ) direction = -1.0;
if ( seconds == 0 ) steppers::abort();
else {
position[A_AXIS + activeToolhead] += direction * seconds * stepsPerSecond;
steppers::setTarget(position, interval);
}
if (overrideTempCheck) overrideExtrudeSeconds = 0;
}
void ExtruderMode::notifyButtonPressed(ButtonArray::ButtonName button) {
static const PROGMEM prog_uchar e_message1[] = "Extruder speed:";
static const PROGMEM prog_uchar e_units[] = " mm/s ";
switch (button) {
case ButtonArray::OK:
switch(extrudeSeconds) {
case EXTRUDE_SECS_1S:
extrudeSeconds = EXTRUDE_SECS_2S;
break;
case EXTRUDE_SECS_2S:
extrudeSeconds = EXTRUDE_SECS_5S;
break;
case EXTRUDE_SECS_5S:
extrudeSeconds = EXTRUDE_SECS_10S;
break;
case EXTRUDE_SECS_10S:
extrudeSeconds = EXTRUDE_SECS_30S;
break;
case EXTRUDE_SECS_30S:
extrudeSeconds = EXTRUDE_SECS_60S;
break;
case EXTRUDE_SECS_60S:
extrudeSeconds = EXTRUDE_SECS_90S;
break;
case EXTRUDE_SECS_90S:
extrudeSeconds = EXTRUDE_SECS_120S;
break;
case EXTRUDE_SECS_120S:
extrudeSeconds = EXTRUDE_SECS_240S;
break;
case EXTRUDE_SECS_240S:
extrudeSeconds = EXTRUDE_SECS_1S;
break;
default:
extrudeSeconds = EXTRUDE_SECS_1S;
break;
}
eeprom_write_byte((uint8_t *)eeprom::EXTRUDE_DURATION, (uint8_t)extrudeSeconds);
//If we're already extruding, change the time running
if (steppers::isRunning())
extrude((int32_t)(lastDirection * extrudeSeconds), false);
timeChanged = true;
break;
case ButtonArray::YPLUS:
// Show Extruder MMS Setting Screen
extruderSetMMSScreen.location = eeprom::EXTRUDE_MMS;
extruderSetMMSScreen.default_value = EEPROM_DEFAULT_EXTRUDE_MMS;
extruderSetMMSScreen.message1 = LOCALIZE(e_message1);
extruderSetMMSScreen.units = LOCALIZE(e_units);
interface::pushScreen(&extruderSetMMSScreen);
break;
case ButtonArray::ZERO:
case ButtonArray::YMINUS:
case ButtonArray::XMINUS:
case ButtonArray::XPLUS:
extrude((int32_t)EXTRUDE_SECS_CANCEL, true);
break;
case ButtonArray::ZMINUS:
case ButtonArray::ZPLUS:
if ( button == ButtonArray::ZPLUS ) lastDirection = 1;
else lastDirection = -1;
extrude((int32_t)(lastDirection * extrudeSeconds), false);
break;
case ButtonArray::CANCEL:
steppers::abort();
steppers::enableAxis(3, false);
interface::popScreen();
steppers::setSegmentAccelState(true);
steppers::enableAxis(3, false);
break;
}
}
ExtruderTooColdMenu::ExtruderTooColdMenu() {
itemCount = 4;
reset();
}
void ExtruderTooColdMenu::resetState() {
itemIndex = 2;
firstItemIndex = 2;
}
void ExtruderTooColdMenu::drawItem(uint8_t index, LiquidCrystal& lcd) {
const static PROGMEM prog_uchar etc_warning[] = "Tool0 too cold!";
const static PROGMEM prog_uchar etc_cancel[] = "Cancel";
const static PROGMEM prog_uchar etc_override[] = "Override";
const prog_uchar *msg;
switch (index) {
case 0:
msg = LOCALIZE(etc_warning);
break;
default:
return;
case 2:
msg = LOCALIZE(etc_cancel);
break;
case 3:
msg = LOCALIZE(etc_override);
break;
}
lcd.writeFromPgmspace(msg);
}
void ExtruderTooColdMenu::handleCancel() {
overrideExtrudeSeconds = 0;
interface::popScreen();
}
void ExtruderTooColdMenu::handleSelect(uint8_t index) {
switch (index) {
default :
return;
case 2:
// Cancel extrude
overrideExtrudeSeconds = 0;
break;
case 3:
// Override and extrude
break;
}
interface::popScreen();
}
void MoodLightMode::reset() {
updatePhase = 0;
scriptId = eeprom_read_byte((uint8_t *)eeprom::MOOD_LIGHT_SCRIPT);
}
void MoodLightMode::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar ml_mood1[] = "Mood: ";
const static PROGMEM prog_uchar ml_mood3_1[] = "(set RGB)";
const static PROGMEM prog_uchar ml_blank[] = " ";
const static PROGMEM prog_uchar ml_moodNotPresent1[] = "Mood Light not";
const static PROGMEM prog_uchar ml_moodNotPresent2[] = "present!!";
const static PROGMEM prog_uchar ml_moodNotPresent3[] = "See Thingiverse";
const static PROGMEM prog_uchar ml_moodNotPresent4[] = " thing:15347";
//If we have no mood light, point to thingiverse to make one
if ( ! interface::moodLightController().blinkM.blinkMIsPresent ) {
//Try once more to restart the mood light controller
if ( ! interface::moodLightController().start() ) {
if ( forceRedraw ) {
lcd.clearHomeCursor();
lcd.writeFromPgmspace(LOCALIZE(ml_moodNotPresent1));
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(ml_moodNotPresent2));
lcd.setRow(2);
lcd.writeFromPgmspace(LOCALIZE(ml_moodNotPresent3));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(ml_moodNotPresent4));
}
return;
}
}
if (forceRedraw) {
lcd.clearHomeCursor();
lcd.writeFromPgmspace(LOCALIZE(ml_mood1));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(updnset_msg));
}
//Redraw tool info
switch (updatePhase) {
case 0:
lcd.setCursor(6, 0);
lcd.writeFromPgmspace(LOCALIZE(ml_blank));
lcd.setCursor(6, 0);
lcd.writeFromPgmspace(interface::moodLightController().scriptIdToStr(scriptId));
break;
case 1:
lcd.setRow(2);
lcd.writeFromPgmspace((scriptId == 1) ? LOCALIZE(ml_mood3_1) : LOCALIZE(ml_blank));
break;
}
if (++updatePhase > 1)
updatePhase = 0;
}
void MoodLightMode::notifyButtonPressed(ButtonArray::ButtonName button) {
if ( ! interface::moodLightController().blinkM.blinkMIsPresent )
interface::popScreen();
uint8_t i;
switch (button) {
case ButtonArray::OK:
eeprom_write_byte((uint8_t *)eeprom::MOOD_LIGHT_SCRIPT,
scriptId);
interface::popScreen();
break;
case ButtonArray::ZERO:
if ( scriptId == 1 )
//Set RGB Values
interface::pushScreen(&moodLightSetRGBScreen);
break;
case ButtonArray::ZPLUS:
// increment more
for ( i = 0; i < 5; i ++ )
scriptId = interface::moodLightController().nextScriptId(scriptId);
interface::moodLightController().playScript(scriptId);
break;
case ButtonArray::ZMINUS:
// decrement more
for ( i = 0; i < 5; i ++ )
scriptId = interface::moodLightController().prevScriptId(scriptId);
interface::moodLightController().playScript(scriptId);
break;
case ButtonArray::YPLUS:
// increment less
scriptId = interface::moodLightController().nextScriptId(scriptId);
interface::moodLightController().playScript(scriptId);
break;
case ButtonArray::YMINUS:
// decrement less
scriptId = interface::moodLightController().prevScriptId(scriptId);
interface::moodLightController().playScript(scriptId);
break;
default:
break;
case ButtonArray::CANCEL:
scriptId = eeprom_read_byte((uint8_t *)eeprom::MOOD_LIGHT_SCRIPT);
interface::moodLightController().playScript(scriptId);
interface::popScreen();
break;
}
}
void MoodLightSetRGBScreen::reset() {
inputMode = 0; //Red
redrawScreen = false;
red = eeprom::getEeprom8(eeprom::MOOD_LIGHT_CUSTOM_RED, EEPROM_DEFAULT_MOOD_LIGHT_CUSTOM_RED);;
green = eeprom::getEeprom8(eeprom::MOOD_LIGHT_CUSTOM_GREEN, EEPROM_DEFAULT_MOOD_LIGHT_CUSTOM_GREEN);;
blue = eeprom::getEeprom8(eeprom::MOOD_LIGHT_CUSTOM_BLUE, EEPROM_DEFAULT_MOOD_LIGHT_CUSTOM_BLUE);;
}
void MoodLightSetRGBScreen::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar mlsrgb_message1_red[] = "Red:";
const static PROGMEM prog_uchar mlsrgb_message1_green[] = "Green:";
const static PROGMEM prog_uchar mlsrgb_message1_blue[] = "Blue:";
if ((forceRedraw) || (redrawScreen)) {
lcd.clearHomeCursor();
if ( inputMode == 0 ) lcd.writeFromPgmspace(LOCALIZE(mlsrgb_message1_red));
else if ( inputMode == 1 ) lcd.writeFromPgmspace(LOCALIZE(mlsrgb_message1_green));
else if ( inputMode == 2 ) lcd.writeFromPgmspace(LOCALIZE(mlsrgb_message1_blue));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(updnset_msg));
redrawScreen = false;
}
// Redraw tool info
lcd.setRow(1);
if ( inputMode == 0 ) lcd.writeInt(red, 3);
else if ( inputMode == 1 ) lcd.writeInt(green,3);
else if ( inputMode == 2 ) lcd.writeInt(blue, 3);
}
void MoodLightSetRGBScreen::notifyButtonPressed(ButtonArray::ButtonName button) {
uint8_t *value = &red;
if ( inputMode == 1 ) value = &green;
else if ( inputMode == 2 ) value = &blue;
switch (button) {
case ButtonArray::CANCEL:
interface::popScreen();
break;
case ButtonArray::ZERO:
break;
case ButtonArray::OK:
if ( inputMode < 2 ) {
inputMode ++;
redrawScreen = true;
} else {
eeprom_write_byte((uint8_t*)eeprom::MOOD_LIGHT_CUSTOM_RED, red);
eeprom_write_byte((uint8_t*)eeprom::MOOD_LIGHT_CUSTOM_GREEN,green);
eeprom_write_byte((uint8_t*)eeprom::MOOD_LIGHT_CUSTOM_BLUE, blue);
//Set the color
interface::moodLightController().playScript(1);
interface::popScreen();
}
break;
case ButtonArray::ZPLUS:
// increment more
if (*value <= 245) *value += 10;
break;
case ButtonArray::ZMINUS:
// decrement more
if (*value >= 10) *value -= 10;
break;
case ButtonArray::YPLUS:
// increment less
if (*value <= 254) *value += 1;
break;
case ButtonArray::YMINUS:
// decrement less
if (*value >= 1) *value -= 1;
break;
case ButtonArray::XMINUS:
case ButtonArray::XPLUS:
break;
}
}
void MonitorMode::reset() {
updatePhase = UPDATE_PHASE_FIRST;
buildTimePhase = BUILD_TIME_PHASE_FIRST;
lastBuildTimePhase = BUILD_TIME_PHASE_FIRST;
lastElapsedSeconds = 0.0;
pausePushLockout = false;
autoPause = 0;
buildCompleteBuzzPlayed = false;
overrideForceRedraw = false;
flashingTool = false;
flashingPlatform = false;
}
void MonitorMode::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar mon_extruder_temp[] = "Tool ---/---\001";
const static PROGMEM prog_uchar mon_platform_temp[] = "Bed ---/---\001";
const static PROGMEM prog_uchar mon_elapsed_time[] = "Elapsed: 0h00m";
const static PROGMEM prog_uchar mon_completed_percent[] = "Completed: 0% ";
const static PROGMEM prog_uchar mon_time_left[] = "TimeLeft: 0h00m";
const static PROGMEM prog_uchar mon_time_left_secs[] = "secs";
const static PROGMEM prog_uchar mon_time_left_none[] = " none";
const static PROGMEM prog_uchar mon_zpos[] = "ZPos: ";
const static PROGMEM prog_uchar mon_speed[] = "Acc: ";
const static PROGMEM prog_uchar mon_filament[] = "Filament:0.00m ";
const static PROGMEM prog_uchar mon_copies[] = "Copy: ";
const static PROGMEM prog_uchar mon_of[] = " of ";
const static PROGMEM prog_uchar mon_error[] = "error!";
char buf[17];
if ( command::isPaused() ) {
if ( ! pausePushLockout ) {
pausePushLockout = true;
autoPause = 1;
interface::pushScreen(&pauseMode);
return;
}
} else pausePushLockout = false;
//Check for a build complete, and if we have more than one copy
//to print, setup another one
if ( host::isBuildComplete() ) {
if ( command::copiesToPrint > 1 ) {
if ( command::copiesPrinted < (command::copiesToPrint - 1)) {
command::copiesPrinted ++;
overrideForceRedraw = true;
command::buildAnotherCopy();
}
}
}
if ((forceRedraw) || (overrideForceRedraw)) {
lcd.clearHomeCursor();
switch(host::getHostState()) {
case host::HOST_STATE_READY:
lcd.writeString(host::getMachineName());
break;
case host::HOST_STATE_BUILDING:
case host::HOST_STATE_BUILDING_FROM_SD:
lcd.writeString(host::getBuildName());
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(mon_completed_percent));
break;
case host::HOST_STATE_ERROR:
lcd.writeFromPgmspace(LOCALIZE(mon_error));
break;
case host::HOST_STATE_CANCEL_BUILD :
break;
}
lcd.setRow(2);
lcd.writeFromPgmspace(LOCALIZE(mon_extruder_temp));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(mon_platform_temp));
lcd.setCursor(15,3);
lcd.write((command::getPauseAtZPos() == 0) ? ' ' : '*');
}
overrideForceRedraw = false;
//Flash the temperature indicators
toggleHeating ^= true;
if ( flashingTool ) {
lcd.setCursor(5,2);
lcd.write(toggleHeating ? LCD_CUSTOM_CHAR_EXTRUDER_NORMAL : LCD_CUSTOM_CHAR_EXTRUDER_HEATING);
}
if ( flashingPlatform ) {
lcd.setCursor(5,3);
lcd.write(toggleHeating ? LCD_CUSTOM_CHAR_PLATFORM_NORMAL : LCD_CUSTOM_CHAR_PLATFORM_HEATING);
}
OutPacket responsePacket;
uint8_t activeToolhead;
steppers::getStepperPosition(&activeToolhead);
// Redraw tool info
switch (updatePhase) {
case UPDATE_PHASE_TOOL_TEMP:
lcd.setCursor(7,2);
if (extruderControl(activeToolhead, SLAVE_CMD_GET_TEMP, EXTDR_CMD_GET, responsePacket, 0)) {
uint16_t data = responsePacket.read16(1);
lcd.writeInt(data, 3);
} else {
lcd.writeFromPgmspace(unknown_temp);
}
break;
case UPDATE_PHASE_TOOL_TEMP_SET_POINT:
lcd.setCursor(11,2);
uint16_t data;
data = 0;
if (extruderControl(activeToolhead, SLAVE_CMD_GET_SP, EXTDR_CMD_GET, responsePacket, 0)) {
data = responsePacket.read16(1);
lcd.writeInt(data, 3);
} else {
lcd.writeFromPgmspace(unknown_temp);
}
lcd.setCursor(5,2);
if (extruderControl(activeToolhead, SLAVE_CMD_IS_TOOL_READY, EXTDR_CMD_GET, responsePacket, 0)) {
flashingTool = false;
uint8_t ready = responsePacket.read8(1);
if ( data != 0 ) {
if ( ready ) lcd.write(LCD_CUSTOM_CHAR_EXTRUDER_HEATING);
else flashingTool = true;
}
else lcd.write(LCD_CUSTOM_CHAR_EXTRUDER_NORMAL);
}
break;
case UPDATE_PHASE_PLATFORM_TEMP:
lcd.setCursor(7,3);
if (extruderControl(0, SLAVE_CMD_GET_PLATFORM_TEMP, EXTDR_CMD_GET, responsePacket, 0)) {
uint16_t data = responsePacket.read16(1);
lcd.writeInt(data, 3);
} else {
lcd.writeFromPgmspace(unknown_temp);
}
break;
case UPDATE_PHASE_PLATFORM_SET_POINT:
lcd.setCursor(11,3);
data = 0;
if (extruderControl(0, SLAVE_CMD_GET_PLATFORM_SP, EXTDR_CMD_GET, responsePacket, 0)) {
data = responsePacket.read16(1);
lcd.writeInt(data, 3);
} else {
lcd.writeFromPgmspace(unknown_temp);
}
lcd.setCursor(5,3);
if (extruderControl(0, SLAVE_CMD_IS_PLATFORM_READY, EXTDR_CMD_GET, responsePacket, 0)) {
flashingPlatform = false;
uint8_t ready = responsePacket.read8(1);
if ( data != 0 ) {
if ( ready ) lcd.write(LCD_CUSTOM_CHAR_PLATFORM_HEATING);
else flashingPlatform = true;
}
else lcd.write(LCD_CUSTOM_CHAR_PLATFORM_NORMAL);
}
lcd.setCursor(15,3);
lcd.write((command::getPauseAtZPos() == 0) ? ' ' : '*');
break;
case UPDATE_PHASE_LAST:
break;
case UPDATE_PHASE_BUILD_PHASE_SCROLLER:
enum host::HostState hostState = host::getHostState();
if ( (hostState != host::HOST_STATE_BUILDING ) && ( hostState != host::HOST_STATE_BUILDING_FROM_SD )) break;
//Signal buzzer if we're complete
if (( ! buildCompleteBuzzPlayed ) && ( sdcard::getPercentPlayed() >= 100.0 )) {
buildCompleteBuzzPlayed = true;
Motherboard::getBoard().buzz(2, 3, eeprom::getEeprom8(eeprom::BUZZER_REPEATS, EEPROM_DEFAULT_BUZZER_REPEATS));
}
bool okButtonHeld = interface::isButtonPressed(ButtonArray::OK);
//Holding the ok button stops rotation
if ( okButtonHeld ) buildTimePhase = lastBuildTimePhase;
float secs;
int32_t tsecs;
Point position;
uint8_t precision;
uint8_t completedPercent;
float filamentUsed;
switch (buildTimePhase) {
case BUILD_TIME_PHASE_COMPLETED_PERCENT:
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(mon_completed_percent));
lcd.setCursor(11,1);
completedPercent = command::getBuildPercentage();
if ( completedPercent > 100 )
// displaying 101% confuses some people
completedPercent = 0;
digits3(buf, (uint8_t)completedPercent);
lcd.writeString(buf);
lcd.write('%');
break;
case BUILD_TIME_PHASE_ELAPSED_TIME:
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(mon_elapsed_time));
lcd.setCursor(9,1);
if ( host::isBuildComplete() ) secs = lastElapsedSeconds; //We stop counting elapsed seconds when we are done
else {
lastElapsedSeconds = Motherboard::getBoard().getCurrentSeconds();
secs = lastElapsedSeconds;
}
formatTime(buf, (uint32_t)secs);
lcd.writeString(buf);
break;
case BUILD_TIME_PHASE_TIME_LEFT:
tsecs = command::estimatedTimeLeftInSeconds();
if ( tsecs > 0 ) {
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(mon_time_left));
lcd.setCursor(9,1);
if ((tsecs > 0 ) && (tsecs < 60) && ( host::isBuildComplete() ) ) {
digits3(buf, (uint8_t)tsecs);
lcd.writeString(buf);
lcd.writeFromPgmspace(LOCALIZE(mon_time_left_secs));
} else if (( tsecs <= 0) || ( host::isBuildComplete()) ) {
#ifdef HAS_FILAMENT_COUNTER
command::addFilamentUsed();
#endif
lcd.writeFromPgmspace(LOCALIZE(mon_time_left_none));
} else {
formatTime(buf, (uint32_t)tsecs);
lcd.writeString(buf);
}
break;
}
//We can't display the time left, so we drop into ZPosition instead
else buildTimePhase = (enum BuildTimePhase)((uint8_t)buildTimePhase + 1);
case BUILD_TIME_PHASE_ZPOS:
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(mon_zpos));
lcd.setCursor(6,1);
position = steppers::getStepperPosition();
//Divide by the axis steps to mm's
lcd.writeFloat(stepperAxisStepsToMM(position[2], Z_AXIS), 3);
lcd.writeFromPgmspace(LOCALIZE(units_mm));
break;
case BUILD_TIME_PHASE_FILAMENT:
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(mon_filament));
lcd.setCursor(9,1);
filamentUsed =
stepperAxisStepsToMM(command::getLastFilamentLength(0) + command::getLastFilamentLength(1), A_AXIS) +
stepperAxisStepsToMM((command::getFilamentLength(0) + command::getFilamentLength(1)), A_AXIS);
filamentUsed /= 1000.0; //convert to meters
if ( filamentUsed < 0.1 ) {
filamentUsed *= 1000.0; //Back to mm's
precision = 1;
}
else if ( filamentUsed < 10.0 ) precision = 4;
else if ( filamentUsed < 100.0 ) precision = 3;
else precision = 2;
lcd.writeFloat(filamentUsed, precision);
if ( precision == 1 ) lcd.write('m');
lcd.write('m');
break;
case BUILD_TIME_PHASE_COPIES_PRINTED:
if ( command::copiesToPrint ) {
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(mon_copies));
lcd.setCursor(7,1);
lcd.writeFloat((float)(command::copiesPrinted + 1), 0);
lcd.writeFromPgmspace(LOCALIZE(mon_of));
lcd.writeFloat((float)command::copiesToPrint, 0);
}
break;
case BUILD_TIME_PHASE_LAST:
break;
case BUILD_TIME_PHASE_ACCEL_STATS:
float minSpeed, avgSpeed, maxSpeed;
accelStatsGet(&minSpeed, &avgSpeed, &maxSpeed);
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(mon_speed));
lcd.setCursor(4,1);
if ( minSpeed < 100.0 ) lcd.write(' '); //If we have space, pad out a bit
lcd.writeFloat(minSpeed,0);
lcd.write('/');
lcd.writeFloat(avgSpeed,0);
lcd.write('/');
lcd.writeFloat(maxSpeed,0);
lcd.write(' ');
break;
}
if ( ! okButtonHeld ) {
//Advance buildTimePhase and wrap around
lastBuildTimePhase = buildTimePhase;
buildTimePhase = (enum BuildTimePhase)((uint8_t)buildTimePhase + 1);
//If we're setup to print more than one copy, then show that build phase,
//otherwise skip it
if ( buildTimePhase == BUILD_TIME_PHASE_COPIES_PRINTED ) {
uint8_t totalCopies = eeprom::getEeprom8(eeprom::ABP_COPIES, EEPROM_DEFAULT_ABP_COPIES);
if ( totalCopies <= 1 )
buildTimePhase = (enum BuildTimePhase)((uint8_t)buildTimePhase + 1);
}
if ( buildTimePhase >= BUILD_TIME_PHASE_LAST )
buildTimePhase = BUILD_TIME_PHASE_FIRST;
}
break;
}
//Advance updatePhase and wrap around
updatePhase = (enum UpdatePhase)((uint8_t)updatePhase + 1);
if (updatePhase >= UPDATE_PHASE_LAST)
updatePhase = UPDATE_PHASE_FIRST;
#ifdef DEBUG_ONSCREEN
lcd.homeCursor();
lcd.writeString((char *)"DOS1: ");
lcd.writeFloat(debug_onscreen1, 3);
lcd.writeString((char *)" ");
lcd.setRow(1);
lcd.writeString((char *)"DOS2: ");
lcd.writeFloat(debug_onscreen2, 3);
lcd.writeString((char *)" ");
#endif
}
void MonitorMode::notifyButtonPressed(ButtonArray::ButtonName button) {
switch (button) {
case ButtonArray::CANCEL:
switch(host::getHostState()) {
case host::HOST_STATE_BUILDING:
case host::HOST_STATE_BUILDING_FROM_SD:
interface::pushScreen(&cancelBuildMenu);
break;
default:
interface::popScreen();
break;
}
case ButtonArray::ZPLUS:
if ( host::getHostState() == host::HOST_STATE_BUILDING_FROM_SD )
updatePhase = UPDATE_PHASE_BUILD_PHASE_SCROLLER;
break;
default:
break;
}
}
void VersionMode::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar v_version1[] = "Motherboard _._";
const static PROGMEM prog_uchar v_version2[] = " Extruder _._";
const static PROGMEM prog_uchar v_version3[] = " Revision " SVN_VERSION_STR;
const static PROGMEM prog_uchar v_version4[] = "Free SRAM ";
if (forceRedraw) {
lcd.clearHomeCursor();
lcd.writeFromPgmspace(LOCALIZE(v_version1));
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(v_version2));
lcd.setRow(2);
lcd.writeFromPgmspace(LOCALIZE(v_version3));
//Display the motherboard version
lcd.setCursor(13, 0);
lcd.writeInt(firmware_version / 100, 1);
lcd.setCursor(15, 0);
lcd.writeInt(firmware_version % 100, 1);
//Display the extruder version
OutPacket responsePacket;
if (extruderControl(0, SLAVE_CMD_VERSION, EXTDR_CMD_GET, responsePacket, 0)) {
uint16_t extruderVersion = responsePacket.read16(1);
lcd.setCursor(13, 1);
lcd.writeInt(extruderVersion / 100, 1);
lcd.setCursor(15, 1);
lcd.writeInt(extruderVersion % 100, 1);
} else {
lcd.setCursor(13, 1);
lcd.writeString((char *)"X.X");
}
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(v_version4));
lcd.writeFloat((float)StackCount(),0);
} else {
}
}
void VersionMode::notifyButtonPressed(ButtonArray::ButtonName button) {
interface::popScreen();
}
void Menu::update(LiquidCrystal& lcd, bool forceRedraw) {
uint8_t height = lcd.getDisplayHeight();
// Do we need to redraw the whole menu?
if ((itemIndex/height) != (lastDrawIndex/height)
|| forceRedraw ) {
// Redraw the whole menu
lcd.clear();
for (uint8_t i = 0; i < height; i++) {
// Instead of using lcd.clear(), clear one line at a time so there
// is less screen flickr.
if (i+(itemIndex/height)*height +1 > itemCount) {
break;
}
lcd.setCursor(1,i);
// Draw one page of items at a time
drawItem(i+(itemIndex/height)*height, lcd);
}
}
else {
// Only need to clear the previous cursor
lcd.setRow(lastDrawIndex%height);
lcd.write(' ');
}
lcd.setRow(itemIndex%height);
lcd.write(LCD_CUSTOM_CHAR_ARROW);
lastDrawIndex = itemIndex;
}
void Menu::reset() {
firstItemIndex = 0;
itemIndex = 0;
lastDrawIndex = 255;
resetState();
}
void Menu::resetState() {
}
void Menu::handleSelect(uint8_t index) {
}
void Menu::handleCancel() {
// Remove ourselves from the menu list
interface::popScreen();
}
void Menu::notifyButtonPressed(ButtonArray::ButtonName button) {
uint8_t steps = MAX_ITEMS_PER_SCREEN;
switch (button) {
case ButtonArray::ZERO:
case ButtonArray::OK:
handleSelect(itemIndex);
break;
case ButtonArray::CANCEL:
handleCancel();
break;
case ButtonArray::YMINUS:
steps = 1;
case ButtonArray::ZMINUS:
// increment index
if (itemIndex < itemCount - steps)
itemIndex+=steps;
else if (itemIndex==itemCount-1)
itemIndex=firstItemIndex;
else itemIndex=itemCount-1;
break;
case ButtonArray::YPLUS:
steps = 1;
case ButtonArray::ZPLUS:
// decrement index
if (itemIndex-steps > firstItemIndex)
itemIndex-=steps;
else if (itemIndex==firstItemIndex)
itemIndex=itemCount - 1;
else itemIndex=firstItemIndex;
break;
case ButtonArray::XMINUS:
case ButtonArray::XPLUS:
break;
}
}
CancelBuildMenu::CancelBuildMenu() :
pauseDisabled(false) {
itemCount = 7;
autoPause = 0;
reset();
if (( steppers::isHoming() ) || (sdcard::getPercentPlayed() >= 100.0)) pauseDisabled = true;
if ( host::isBuildComplete() )
printAnotherEnabled = true;
else printAnotherEnabled = false;
}
void CancelBuildMenu::resetState() {
autoPause = 0;
pauseDisabled = false;
if (( steppers::isHoming() ) || (sdcard::getPercentPlayed() >= 100.0)) pauseDisabled = true;
if ( host::isBuildComplete() )
printAnotherEnabled = true;
else printAnotherEnabled = false;
if ( pauseDisabled ) {
itemIndex = 2;
itemCount = 3;
} else {
itemIndex = 1;
itemCount = 9;
}
if ( printAnotherEnabled )
itemCount++;
#if 0
if ( printAnotherEnabled ) {
itemIndex = 1;
}
#endif
firstItemIndex = 1;
}
void CancelBuildMenu::update(LiquidCrystal& lcd, bool forceRedraw) {
if ( command::isPaused() ) interface::popScreen();
else Menu::update(lcd, forceRedraw);
}
void CancelBuildMenu::drawItem(uint8_t index, LiquidCrystal& lcd) {
// --- first screen ---
const static PROGMEM prog_uchar cb_choose[] = "Please Choose:";
const static PROGMEM prog_uchar cb_abort[] = "Abort Print";
const static PROGMEM prog_uchar cb_pause[] = "Pause";
const static PROGMEM prog_uchar cb_pauseZ[] = "Pause at ZPos";
// --- second screen ---
const static PROGMEM prog_uchar cb_pauseHBPHeat[] = "Pause, HBP on";
const static PROGMEM prog_uchar cb_pauseNoHeat[] = "Pause, No Heat";
const static PROGMEM prog_uchar cb_speed[] = "Change Speed";
const static PROGMEM prog_uchar cb_temp[] = "Change Temp";
// --- third screen ---
const static PROGMEM prog_uchar cb_printAnother[] = "Print Another";
const static PROGMEM prog_uchar cb_cont[] = "Continue Build";
const static PROGMEM prog_uchar cb_back[] = "Return to Menu";
if (( steppers::isHoming() ) || (sdcard::getPercentPlayed() >= 100.0)) pauseDisabled = true;
//Implement variable length menu
uint8_t lind = 0;
// ---- first screen ----
if ( index == lind ) lcd.writeFromPgmspace(LOCALIZE(cb_choose));
lind ++;
// skip abort if paused...
if (( pauseDisabled ) && ( ! printAnotherEnabled )) lind ++;
if ( index == lind) lcd.writeFromPgmspace(LOCALIZE(cb_abort));
lind ++;
if ( ! pauseDisabled ) {
if ( index == lind ) lcd.writeFromPgmspace(LOCALIZE(cb_pause));
lind ++;
}
if ( ! pauseDisabled ) {
if ( index == lind ) lcd.writeFromPgmspace(LOCALIZE(cb_pauseZ));
lind ++;
}
// ---- second screen ----
if ( ! pauseDisabled ) {
if ( index == lind ) lcd.writeFromPgmspace(LOCALIZE(cb_pauseHBPHeat));
lind ++;
}
if ( ! pauseDisabled ) {
if ( index == lind ) lcd.writeFromPgmspace(LOCALIZE(cb_pauseNoHeat));
lind ++;
}
if ( ! pauseDisabled ) {
if ( index == lind ) lcd.writeFromPgmspace(LOCALIZE(cb_speed));
lind ++;
}
if ( ! pauseDisabled ) {
if ( index == lind ) lcd.writeFromPgmspace(LOCALIZE(cb_temp));
lind ++;
}
// ---- third screen ----
if ( printAnotherEnabled ) {
if ( index == lind ) lcd.writeFromPgmspace(LOCALIZE(cb_printAnother));
lind ++;
}
if ( index == lind ) {
if ( printAnotherEnabled ) lcd.writeFromPgmspace(LOCALIZE(cb_back));
else lcd.writeFromPgmspace(LOCALIZE(cb_cont));
}
}
void CancelBuildMenu::handleSelect(uint8_t index) {
//Implement variable length menu
uint8_t lind = 0;
if (( pauseDisabled ) && ( ! printAnotherEnabled )) lind ++;
lind ++;
if ( index == lind ) {
#ifdef HAS_FILAMENT_COUNTER
command::addFilamentUsed();
#endif
// Cancel build, returning to whatever menu came before monitor mode.
// TODO: Cancel build.
interface::popScreen();
host::stopBuild();
return;
}
lind ++;
if ( ! pauseDisabled ) {
if ( index == lind ) {
command::pause(true, PAUSE_HEAT_ON); // pause, all heaters left on
autoPause = 0;
interface::pushScreen(&pauseMode);
return;
}
lind ++;
}
if ( ! pauseDisabled ) {
if ( index == lind ) {
interface::pushScreen(&pauseAtZPosScreen);
return;
}
lind ++;
}
// ---- second screen ----
if ( ! pauseDisabled ) {
if ( index == lind ) {
command::pause(true, PAUSE_EXT_OFF); // pause, HBP left on
autoPause = 0;
interface::pushScreen(&pauseMode);
return;
}
lind ++;
}
if ( ! pauseDisabled ) {
if ( index == lind ) {
command::pause(true, PAUSE_EXT_OFF | PAUSE_HBP_OFF); // pause no heat
autoPause = 0;
interface::pushScreen(&pauseMode);
}
lind ++;
}
if ( ! pauseDisabled ) {
if ( index == lind )
{
interface::pushScreen(&changeSpeedScreen);
return;
}
lind ++;
}
if ( ! pauseDisabled ) {
if ( index == lind )
{
interface::pushScreen(&changeTempScreen);
return;
}
lind ++;
}
// ---- third screen ----
if ( printAnotherEnabled ) {
if ( index == lind ) {
command::buildAnotherCopy();
interface::popScreen();
return;
}
lind ++;
}
if ( index == lind ) {
// Don't cancel print, just close dialog.
interface::popScreen();
}
}
MainMenu::MainMenu() {
itemCount = 20;
#ifdef EEPROM_MENU_ENABLE
itemCount ++;
#endif
reset();
lcdTypeChangeTimer = 0.0;
}
void MainMenu::drawItem(uint8_t index, LiquidCrystal& lcd) {
const static PROGMEM prog_uchar main_monitor[] = "Monitor";
const static PROGMEM prog_uchar main_build[] = "Build from SD";
const static PROGMEM prog_uchar main_jog[] = "Jog";
const static PROGMEM prog_uchar main_preheat[] = "Preheat";
const static PROGMEM prog_uchar main_extruder[] = "Extrude";
const static PROGMEM prog_uchar main_homeAxis[] = "Home Axis";
const static PROGMEM prog_uchar main_advanceABP[] = "Advance ABP";
const static PROGMEM prog_uchar main_steppersS[] = "Steppers";
const static PROGMEM prog_uchar main_moodlight[] = "Mood Light";
const static PROGMEM prog_uchar main_buzzer[] = "Buzzer";
const static PROGMEM prog_uchar main_buildSettings[] = "Build Settings";
const static PROGMEM prog_uchar main_profiles[] = "Profiles";
const static PROGMEM prog_uchar main_extruderFan[] = "Extruder Fan";
const static PROGMEM prog_uchar main_calibrate[] = "Calibrate";
const static PROGMEM prog_uchar main_homeOffsets[] = "Home Offsets";
const static PROGMEM prog_uchar main_filamentUsed[] = "Filament Used";
const static PROGMEM prog_uchar main_currentPosition[] = "Position";
const static PROGMEM prog_uchar main_endStops[] = "Test End Stops";
const static PROGMEM prog_uchar main_homingRates[] = "Homing Rates";
const static PROGMEM prog_uchar main_versions[] = "Version";
#ifdef EEPROM_MENU_ENABLE
const static PROGMEM prog_uchar main_eeprom[] = "Eeprom";
#endif
const static prog_uchar *messages[20
#ifdef EEPROM_MENU_ENABLE
+1
#endif
] = { LOCALIZE(main_monitor), // 0
LOCALIZE(main_build), // 1
LOCALIZE(main_preheat), // 2
LOCALIZE(main_extruder), // 3
LOCALIZE(main_buildSettings), // 4
LOCALIZE(main_homeAxis), // 5
LOCALIZE(main_jog), // 6
LOCALIZE(main_filamentUsed), // 7
LOCALIZE(main_advanceABP), // 8
LOCALIZE(main_steppersS), // 9
LOCALIZE(main_moodlight), // 10
LOCALIZE(main_buzzer), // 11
LOCALIZE(main_profiles), // 12
LOCALIZE(main_calibrate), // 13
LOCALIZE(main_homeOffsets), // 14
LOCALIZE(main_homingRates), // 15
LOCALIZE(main_extruderFan), // 16
LOCALIZE(main_endStops), // 17
LOCALIZE(main_currentPosition), // 18
LOCALIZE(main_versions), // 19
#ifdef EEPROM_MENU_ENABLE
LOCALIZE(main_eeprom), // 20
#endif
};
if ( index < sizeof(messages)/sizeof(prog_uchar *) )
lcd.writeFromPgmspace(messages[index]);
}
void MainMenu::handleSelect(uint8_t index) {
switch (index) {
case 0:
interface::pushScreen(&monitorMode);
break;
case 1:
interface::pushScreen(&sdMenu);
break;
case 2:
interface::pushScreen(&preheatMenu);
preheatMenu.fetchTargetTemps();
break;
case 3:
interface::pushScreen(&extruderMenu);
break;
case 4:
interface::pushScreen(&buildSettingsMenu);
break;
case 5:
interface::pushScreen(&homeAxisMode);
break;
case 6:
interface::pushScreen(&jogger);
break;
case 7:
interface::pushScreen(&filamentUsedMode);
break;
case 8:
interface::pushScreen(&advanceABPMode);
break;
case 9:
interface::pushScreen(&steppersMenu);
break;
case 10:
interface::pushScreen(&moodLightMode);
break;
case 11:
interface::pushScreen(&buzzerSetRepeats);
break;
case 12:
interface::pushScreen(&profilesMenu);
break;
case 13:
interface::pushScreen(&calibrateMode);
break;
case 14:
interface::pushScreen(&homeOffsetsMode);
break;
case 15:
interface::pushScreen(&homingFeedRatesMode);
break;
case 16:
interface::pushScreen(&extruderFanMenu);
break;
case 17:
interface::pushScreen(&testEndStopsMode);
break;
case 18:
interface::pushScreen(¤tPositionMode);
break;
case 19:
interface::pushScreen(&versionMode);
break;
#ifdef EEPROM_MENU_ENABLE
case 20:
interface::pushScreen(&eepromMenu);
break;
#endif
}
}
void MainMenu::update(LiquidCrystal& lcd, bool forceRedraw) {
Menu::update(lcd, forceRedraw);
if (interface::isButtonPressed(ButtonArray::XMINUS)) {
if (( lcdTypeChangeTimer != -1.0 ) && ( lcdTypeChangeTimer + LCD_TYPE_CHANGE_BUTTON_HOLD_TIME ) <= Motherboard::getBoard().getCurrentSeconds()) {
Motherboard::getBoard().buzz(1, 1, 1);
lcdTypeChangeTimer = -1.0;
lcd.nextLcdType();
lcd.reloadDisplayType();
host::stopBuildNow();
}
} else lcdTypeChangeTimer = Motherboard::getBoard().getCurrentSeconds();
}
SDMenu::SDMenu() :
updatePhase(0),
drawItemLockout(false),
selectable(false),
folderStackIndex(-1) {
reset();
}
void SDMenu::resetState() {
itemCount = countFiles();
if ( !itemCount ) {
folderStackIndex = -1;
itemCount = 1;
selectable = false;
}
else selectable = true;
updatePhase = 0;
lastItemIndex = 0;
drawItemLockout = false;
}
// Count the number of files on the SD card
static uint8_t fileCount;
uint8_t SDMenu::countFiles() {
fileCount = 0;
// First, reset the directory index
if ( sdcard::directoryReset() != sdcard::SD_SUCCESS )
// TODO: Report
return 0;
char fnbuf[3];
// Count the files
do {
bool isdir;
sdcard::directoryNextEntry(fnbuf,sizeof(fnbuf),&isdir);
if ( fnbuf[0] == 0 )
return fileCount;
// Count .. and anyfile which doesn't begin with .
else if ( (fnbuf[0] != '.') ||
( isdir && fnbuf[1] == '.' && fnbuf[2] == 0) )
fileCount++;
} while (true);
// Never reached
return fileCount;
}
bool SDMenu::getFilename(uint8_t index, char buffer[], uint8_t buffer_size, bool *isdir) {
*isdir = false;
// First, reset the directory list
if ( sdcard::directoryReset() != sdcard::SD_SUCCESS )
return false;
bool my_isdir;
#ifdef REVERSE_SD_FILES
// Reverse order the files in hopes of listing the newer files first
// HOWEVER, with wrap around on the LCD menu, this isn't too useful
index = (fileCount - 1) - index;
#endif
for(uint8_t i = 0; i < index+1; i++) {
do {
sdcard::directoryNextEntry(buffer, buffer_size, &my_isdir);
if ( buffer[0] == 0 )
// No more files
return false;
// Count only .. and any file not beginning with .
if ( (buffer[0] != '.' ) ||
( my_isdir && buffer[1] == '.' && buffer[2] == 0) )
break;
} while (true);
}
*isdir = my_isdir;
return true;
}
void SDMenu::drawItem(uint8_t index, LiquidCrystal& lcd) {
uint8_t idx, filenameLength;
uint8_t longFilenameOffset = 0;
uint8_t displayWidth = lcd.getDisplayWidth() - 1;
uint8_t offset = 1;
char fnbuf[SD_MAXFILELEN+2]; // extra +1 as we may precede the name with a folder indicator
bool isdir;
if ( !selectable || index > itemCount - 1 )
return;
if ( !getFilename(index, fnbuf + 1, sizeof(fnbuf) - 1, &isdir) ) {
selectable = false;
return;
}
if ( isdir )
{
fnbuf[0] = ( fnbuf[1] == '.' && fnbuf[2] == '.' ) ? LCD_CUSTOM_CHAR_RETURN : LCD_CUSTOM_CHAR_FOLDER;
offset = 0;
}
//Figure out length of filename
for (filenameLength = 0; (filenameLength < sizeof(fnbuf)) && (fnbuf[offset+filenameLength] != 0); filenameLength++) ;
//Support scrolling filenames that are longer than the lcd screen
if (filenameLength >= displayWidth) longFilenameOffset = updatePhase % (filenameLength - displayWidth + 1);
for (idx = 0; (idx < displayWidth) && ((longFilenameOffset + idx) < sizeof(fnbuf)) &&
(fnbuf[offset+longFilenameOffset + idx] != 0); idx++)
lcd.write(fnbuf[offset+longFilenameOffset + idx]);
//Clear out the rest of the line
while ( idx < displayWidth ) {
lcd.write(' ');
idx ++;
}
return;
}
void SDMenu::update(LiquidCrystal& lcd, bool forceRedraw) {
uint8_t height = lcd.getDisplayHeight();
if (( ! forceRedraw ) && ( ! drawItemLockout )) {
//Redraw the last item if we have changed
if (((itemIndex/height) == (lastDrawIndex/height)) &&
( itemIndex != lastItemIndex )) {
lcd.setCursor(1,lastItemIndex % height);
drawItem(lastItemIndex, lcd);
}
lastItemIndex = itemIndex;
lcd.setCursor(1,itemIndex % height);
drawItem(itemIndex, lcd);
}
if ( selectable ) {
Menu::update(lcd, forceRedraw);
updatePhase ++;
}
else {
// This was actually triggered in drawItem() but popping a screen
// from there is not a good idea
timedMessage(lcd, 0);
interface::popScreen();
}
}
void SDMenu::notifyButtonPressed(ButtonArray::ButtonName button) {
if ( button == ButtonArray::XMINUS && folderStackIndex >= 0 )
SDMenu::handleSelect(0);
else {
updatePhase = 0;
Menu::notifyButtonPressed(button);
}
}
void SDMenu::handleSelect(uint8_t index) {
if (host::getHostState() != host::HOST_STATE_READY || !selectable)
// TODO: report error
return;
drawItemLockout = true;
char fnbuf[SD_MAXFILELEN+1];
bool isdir;
if ( !getFilename(index, fnbuf, sizeof(fnbuf), &isdir) )
goto badness;
if ( isdir ) {
// Attempt to change the directory
if ( !sdcard::changeDirectory(fnbuf) )
goto badness;
// Find our way around this folder
// Doing a resetState() will determine the new itemCount
resetState();
itemIndex = 0;
// If we're not selectable, don't bother
if ( selectable ) {
// Recall last itemIndex in this folder if we popped up
if ( fnbuf[0] != '.' || fnbuf[1] != '.' || fnbuf[2] != 0 ) {
// We've moved down into a child folder
if ( folderStackIndex < (int8_t)(sizeof(folderStack) - 1) )
folderStack[++folderStackIndex] = index;
}
else {
// We've moved up into our parent folder
if ( folderStackIndex >= 0 ) {
itemIndex = folderStack[folderStackIndex--];
if (itemIndex >= itemCount) {
// Something is wrong; invalidate the entire stack
itemIndex = 0;
folderStackIndex = -1;
}
}
}
}
// Repaint the display
// Really ensure that the entire screen is wiped
lastDrawIndex = index; // so that the old cursor can be cleared
Menu::update(Motherboard::getBoard().getInterfaceBoard().lcd, true);
return;
}
if ( host::startBuildFromSD(fnbuf) == sdcard::SD_SUCCESS )
return;
badness:
// TODO: report error
interface::pushScreen(&unableToOpenFileMenu);
}
void ValueSetScreen::reset() {
value = eeprom::getEeprom8(location, default_value);
}
void ValueSetScreen::update(LiquidCrystal& lcd, bool forceRedraw) {
if (forceRedraw) {
lcd.clearHomeCursor();
lcd.writeFromPgmspace(message1);
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(updnset_msg));
}
// Redraw tool info
lcd.setRow(1);
lcd.writeInt(value,3);
if ( units ) lcd.writeFromPgmspace(units);
}
void ValueSetScreen::notifyButtonPressed(ButtonArray::ButtonName button) {
switch (button) {
case ButtonArray::CANCEL:
interface::popScreen();
break;
case ButtonArray::ZERO:
break;
case ButtonArray::OK:
eeprom_write_byte((uint8_t*)location,value);
interface::popScreen();
break;
case ButtonArray::ZPLUS:
// increment more
if (value <= 249) {
value += 5;
}
break;
case ButtonArray::ZMINUS:
// decrement more
if (value >= 6) {
value -= 5;
}
break;
case ButtonArray::YPLUS:
// increment less
if (value <= 253) {
value += 1;
}
break;
case ButtonArray::YMINUS:
// decrement less
if (value >= 2) {
value -= 1;
}
break;
case ButtonArray::XMINUS:
case ButtonArray::XPLUS:
break;
}
}
PreheatMenu::PreheatMenu() {
itemCount = 4;
reset();
}
void PreheatMenu::fetchTargetTemps() {
OutPacket responsePacket;
uint8_t activeToolhead;
steppers::getStepperPosition(&activeToolhead);
if (extruderControl(activeToolhead, SLAVE_CMD_GET_SP, EXTDR_CMD_GET, responsePacket, 0)) {
tool0Temp = responsePacket.read16(1);
}
if (extruderControl(activeToolhead, SLAVE_CMD_GET_PLATFORM_SP, EXTDR_CMD_GET, responsePacket, 0)) {
platformTemp = responsePacket.read16(1);
}
}
void PreheatMenu::drawItem(uint8_t index, LiquidCrystal& lcd) {
const static PROGMEM prog_uchar ph_heat[] = "Heat ";
const static PROGMEM prog_uchar ph_cool[] = "Cool ";
const static PROGMEM prog_uchar ph_tool0[] = "Tool0";
const static PROGMEM prog_uchar ph_platform[] = "Bed";
const static PROGMEM prog_uchar ph_tool0set[] = "Set Tool0 Temp";
const static PROGMEM prog_uchar ph_platset[] = "Set Bed Temp";
switch (index) {
case 0:
fetchTargetTemps();
if (tool0Temp > 0) {
lcd.writeFromPgmspace(LOCALIZE(ph_cool));
} else {
lcd.writeFromPgmspace(LOCALIZE(ph_heat));
}
lcd.writeFromPgmspace(LOCALIZE(ph_tool0));
break;
case 1:
if (platformTemp > 0) {
lcd.writeFromPgmspace(LOCALIZE(ph_cool));
} else {
lcd.writeFromPgmspace(LOCALIZE(ph_heat));
}
lcd.writeFromPgmspace(LOCALIZE(ph_platform));
break;
case 2:
lcd.writeFromPgmspace(LOCALIZE(ph_tool0set));
break;
case 3:
lcd.writeFromPgmspace(LOCALIZE(ph_platset));
break;
}
}
void PreheatMenu::handleSelect(uint8_t index) {
static const PROGMEM prog_uchar ph_message1[] = "Tool0 Targ Temp:";
const static PROGMEM prog_uchar ph_message2[] = "Bed Target Temp:";
uint8_t activeToolhead;
steppers::getStepperPosition(&activeToolhead);
OutPacket responsePacket;
switch (index) {
case 0:
// Toggle Extruder heater on/off
if (tool0Temp > 0) {
extruderControl(activeToolhead, SLAVE_CMD_SET_TEMP, EXTDR_CMD_SET, responsePacket, 0);
} else {
uint8_t value = eeprom::getEeprom8(eeprom::TOOL0_TEMP, EEPROM_DEFAULT_TOOL0_TEMP);
extruderControl(activeToolhead, SLAVE_CMD_SET_TEMP, EXTDR_CMD_SET, responsePacket, (uint16_t)value);
}
fetchTargetTemps();
lastDrawIndex = 255; // forces redraw.
break;
case 1:
// Toggle Platform heater on/off
if (platformTemp > 0) {
extruderControl(0, SLAVE_CMD_SET_PLATFORM_TEMP, EXTDR_CMD_SET, responsePacket, 0);
} else {
uint8_t value = eeprom::getEeprom8(eeprom::PLATFORM_TEMP, EEPROM_DEFAULT_PLATFORM_TEMP);
extruderControl(0, SLAVE_CMD_SET_PLATFORM_TEMP, EXTDR_CMD_SET, responsePacket, (uint16_t)value);
}
fetchTargetTemps();
lastDrawIndex = 255; // forces redraw.
break;
case 2:
// Show Extruder Temperature Setting Screen
heaterTempSetScreen.location = eeprom::TOOL0_TEMP;
heaterTempSetScreen.default_value = EEPROM_DEFAULT_TOOL0_TEMP;
heaterTempSetScreen.message1 = LOCALIZE(ph_message1);
heaterTempSetScreen.units = NULL;
interface::pushScreen(&heaterTempSetScreen);
break;
case 3:
// Show Platform Temperature Setting Screen
heaterTempSetScreen.location = eeprom::PLATFORM_TEMP;
heaterTempSetScreen.default_value = EEPROM_DEFAULT_PLATFORM_TEMP;
heaterTempSetScreen.message1 = LOCALIZE(ph_message2);
heaterTempSetScreen.units = NULL;
interface::pushScreen(&heaterTempSetScreen);
break;
}
}
void HomeAxisMode::reset() {
}
void HomeAxisMode::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar ha_home1[] = "Home Axis: ";
const static PROGMEM prog_uchar ha_home2[] = " Y Z";
const static PROGMEM prog_uchar ha_home3[] = "X X (endstops)";
const static PROGMEM prog_uchar ha_home4[] = " Y Z";
if (forceRedraw) {
lcd.clearHomeCursor();
lcd.writeFromPgmspace(LOCALIZE(ha_home1));
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(ha_home2));
lcd.setRow(2);
lcd.writeFromPgmspace(LOCALIZE(ha_home3));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(ha_home4));
}
}
void HomeAxisMode::home(ButtonArray::ButtonName direction) {
uint8_t axis = 0, axisIndex = 0;
bool maximums = false;
uint8_t endstops = eeprom::getEeprom8(eeprom::ENDSTOPS_USED, EEPROM_DEFAULT_ENDSTOPS_USED);
switch(direction) {
case ButtonArray::XMINUS:
case ButtonArray::XPLUS:
axis = 0x01;
if ( endstops & 0x02 ) maximums = true;
if ( endstops & 0x01 ) maximums = false;
axisIndex = 0;
break;
case ButtonArray::YMINUS:
case ButtonArray::YPLUS:
axis = 0x02;
if ( endstops & 0x08 ) maximums = true;
if ( endstops & 0x04 ) maximums = false;
axisIndex = 1;
break;
case ButtonArray::ZMINUS:
case ButtonArray::ZPLUS:
axis = 0x04;
if ( endstops & 0x20 ) maximums = true;
if ( endstops & 0x10 ) maximums = false;
axisIndex = 2;
break;
default:
break;
}
//60.0, because feed rate is in mm/min units, we convert to seconds
float feedRate = (float)eeprom::getEepromUInt32(eeprom::HOMING_FEED_RATE_X + (axisIndex * sizeof(uint32_t)), 500) / 60.0;
float stepsPerSecond = feedRate * (float)stepperAxisMMToSteps(1.0, (enum AxisEnum)axisIndex);
int32_t interval = (int32_t)(1000000.0 / stepsPerSecond);
steppers::startHoming(maximums, axis, (uint32_t)interval);
}
void HomeAxisMode::notifyButtonPressed(ButtonArray::ButtonName button) {
switch (button) {
#if 0
case ButtonArray::YMINUS:
case ButtonArray::ZMINUS:
case ButtonArray::YPLUS:
case ButtonArray::ZPLUS:
case ButtonArray::XMINUS:
case ButtonArray::XPLUS:
#else
default:
#endif
home(button);
break;
case ButtonArray::ZERO:
case ButtonArray::OK:
interface::pushScreen(&endStopConfigScreen);
break;
case ButtonArray::CANCEL:
steppers::abort();
steppers::enableAxis(0, false);
steppers::enableAxis(1, false);
steppers::enableAxis(2, false);
interface::popScreen();
break;
}
}
EnabledDisabledMenu::EnabledDisabledMenu() {
itemCount = 4;
reset();
}
void EnabledDisabledMenu::resetState() {
setupTitle();
if ( isEnabled() ) itemIndex = 3;
else itemIndex = 2;
firstItemIndex = 2;
}
void EnabledDisabledMenu::drawItem(uint8_t index, LiquidCrystal& lcd) {
const prog_uchar *msg;
switch (index) {
default: return;
case 0: msg = msg1; break;
case 1: msg = msg2; break;
case 2: msg = LOCALIZE(generic_off); break;
case 3: msg = LOCALIZE(generic_on); break;
}
if (msg) lcd.writeFromPgmspace(msg);
}
void EnabledDisabledMenu::handleSelect(uint8_t index) {
if ( index == 2 ) enable(false);
if ( index == 3 ) enable(true);
interface::popScreen();
}
bool SteppersMenu::isEnabled() {
for ( uint8_t j = 0; j < STEPPER_COUNT; j++ )
if ( stepperAxisIsEnabled(j) )
return true;
return false;
}
void SteppersMenu::enable(bool enabled) {
for ( uint8_t j = 0; j < STEPPER_COUNT; j++ )
steppers::enableAxis(j, enabled);
}
void SteppersMenu::setupTitle() {
const static PROGMEM prog_uchar step_msg1[] = "Stepper Motors:";
msg1 = LOCALIZE(step_msg1);
msg2 = 0;
}
void TestEndStopsMode::reset() {
#ifdef PSTOP_SUPPORT
pstop = eeprom::getEeprom8(eeprom::PSTOP_ENABLE,
EEPROM_DEFAULT_PSTOP_ENABLE);
#endif
}
void TestEndStopsMode::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar tes_test1[] = "Test End Stops: ";
const static PROGMEM prog_uchar tes_test2[] = "XMin:N XMax:N";
#ifdef PSTOP_SUPPORT
const static PROGMEM prog_uchar tes_test2a[] = "XMin:N PStop:N";
#endif
const static PROGMEM prog_uchar tes_test3[] = "YMin:N YMax:N";
const static PROGMEM prog_uchar tes_test4[] = "ZMin:N ZMax:N";
const static PROGMEM prog_uchar tes_strY[] = "Y";
const static PROGMEM prog_uchar tes_strN[] = "N";
if (forceRedraw) {
lcd.clearHomeCursor();
lcd.writeFromPgmspace(LOCALIZE(tes_test1));
lcd.setRow(1);
#ifdef PSTOP_SUPPORT
lcd.writeFromPgmspace(pstop ? LOCALIZE(tes_test2a) : LOCALIZE(tes_test2));
#else
lcd.writeFromPgmspace(LOCALIZE(tes_test2));
#endif
lcd.setRow(2);
lcd.writeFromPgmspace(LOCALIZE(tes_test3));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(tes_test4));
}
lcd.setCursor(5, 1);
if ( stepperAxisIsAtMinimum(0) ) lcd.writeFromPgmspace(LOCALIZE(tes_strY));
else lcd.writeFromPgmspace(LOCALIZE(tes_strN));
lcd.setCursor(15, 1);
#ifdef PSTOP_SUPPORT
if ( (pstop && (PSTOP_PORT.getValue() == 0)) || (!pstop && stepperAxisIsAtMaximum(0)) )
lcd.writeFromPgmspace(LOCALIZE(tes_strY));
#else
if ( stepperAxisIsAtMaximum(0) ) lcd.writeFromPgmspace(LOCALIZE(tes_strY));
#endif
else lcd.writeFromPgmspace(LOCALIZE(tes_strN));
lcd.setCursor(5, 2);
if ( stepperAxisIsAtMinimum(1) ) lcd.writeFromPgmspace(LOCALIZE(tes_strY));
else lcd.writeFromPgmspace(LOCALIZE(tes_strN));
lcd.setCursor(15, 2);
if ( stepperAxisIsAtMaximum(1) ) lcd.writeFromPgmspace(LOCALIZE(tes_strY));
else lcd.writeFromPgmspace(LOCALIZE(tes_strN));
lcd.setCursor(5, 3);
if ( stepperAxisIsAtMinimum(2) ) lcd.writeFromPgmspace(LOCALIZE(tes_strY));
else lcd.writeFromPgmspace(LOCALIZE(tes_strN));
lcd.setCursor(15, 3);
if ( stepperAxisIsAtMaximum(2) ) lcd.writeFromPgmspace(LOCALIZE(tes_strY));
else lcd.writeFromPgmspace(LOCALIZE(tes_strN));
}
void TestEndStopsMode::notifyButtonPressed(ButtonArray::ButtonName button) {
// That above list is exhaustive
interface::popScreen();
}
void PauseMode::reset() {
lastDirectionButtonPressed = (ButtonArray::ButtonName)0;
lastPauseState = PAUSE_STATE_NONE;
userViewMode = eeprom::getEeprom8(eeprom::JOG_MODE_SETTINGS, EEPROM_DEFAULT_JOG_MODE_SETTINGS) & 0x01;
}
void PauseMode::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar p_waitForCurrentCommand[] = "Entering pause..";
const static PROGMEM prog_uchar p_retractFilament[] = "Retract filament";
const static PROGMEM prog_uchar p_clearingBuild[] = "Clearing build..";
const static PROGMEM prog_uchar p_heating[] = "Heating... ";
const static PROGMEM prog_uchar p_leavingPaused[] = "Leaving pause...";
const static PROGMEM prog_uchar p_paused1[] = "Paused(";
const static PROGMEM prog_uchar p_paused2[] = " Y+ Z+";
const static PROGMEM prog_uchar p_paused3[] = "X- Rev X+ (Fwd)";
const static PROGMEM prog_uchar p_paused4[] = " Y- Z-";
const static PROGMEM prog_uchar p_close[] = "):";
const static PROGMEM prog_uchar p_cancel1[] = "SD card error";
const static PROGMEM prog_uchar p_cancel2[] = "Build cancelled";
const static PROGMEM prog_uchar p_cancel3[] = "Press any button";
const static PROGMEM prog_uchar p_cancel4[] = "to continue ";
enum PauseState pauseState = command::pauseState();
if ( forceRedraw || ( lastPauseState != pauseState) )
lcd.clear();
OutPacket responsePacket;
lcd.homeCursor();
bool foo = false;
switch ( pauseState ) {
case PAUSE_STATE_ENTER_START_PIPELINE_DRAIN:
case PAUSE_STATE_ENTER_WAIT_PIPELINE_DRAIN:
lcd.writeFromPgmspace(LOCALIZE(p_waitForCurrentCommand));
foo = true;
break;
case PAUSE_STATE_ENTER_START_RETRACT_FILAMENT:
case PAUSE_STATE_ENTER_WAIT_RETRACT_FILAMENT:
lcd.writeFromPgmspace(LOCALIZE(p_retractFilament));
foo = true;
break;
case PAUSE_STATE_ENTER_START_CLEARING_PLATFORM:
case PAUSE_STATE_ENTER_WAIT_CLEARING_PLATFORM:
lcd.writeFromPgmspace(LOCALIZE(p_clearingBuild));
foo = true;
break;
case PAUSE_STATE_PAUSED:
lcd.writeFromPgmspace(LOCALIZE(p_paused1));
lcd.writeFloat(stepperAxisStepsToMM(command::getPausedPosition()[Z_AXIS], Z_AXIS), 3);
lcd.writeFromPgmspace(LOCALIZE(p_close));
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(p_paused2));
lcd.setRow(2);
lcd.writeFromPgmspace(LOCALIZE(p_paused3));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(p_paused4));
break;
case PAUSE_STATE_EXIT_START_HEATERS:
case PAUSE_STATE_EXIT_WAIT_FOR_HEATERS:
lcd.writeFromPgmspace(LOCALIZE(p_heating));
break;
case PAUSE_STATE_EXIT_START_RETURNING_PLATFORM:
case PAUSE_STATE_EXIT_WAIT_RETURNING_PLATFORM:
case PAUSE_STATE_EXIT_START_UNRETRACT_FILAMENT:
case PAUSE_STATE_EXIT_WAIT_UNRETRACT_FILAMENT:
lcd.writeFromPgmspace(LOCALIZE(p_leavingPaused));
break;
case PAUSE_STATE_ERROR:
{
const prog_uchar *msg = command::pauseGetErrorMessage();
if ( !msg ) msg = LOCALIZE(p_cancel1);
lcd.writeFromPgmspace(msg);
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(p_cancel2));
lcd.setRow(2);
lcd.writeFromPgmspace(LOCALIZE(p_cancel3));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(p_cancel4));
break;
}
case PAUSE_STATE_NONE:
//Pop off the pause screen and the menu underneath to return to the monitor screen
interface::popScreen();
if ( autoPause == 1 ) interface::popScreen();
if ( autoPause == 2 ) interface::popScreen();
break;
}
if ( foo ) {
const prog_uchar *msg = command::pauseGetErrorMessage();
if ( msg ) {
lcd.setRow(1);
lcd.writeFromPgmspace(msg);
}
}
if ( lastDirectionButtonPressed ) {
if ( interface::isButtonPressed(lastDirectionButtonPressed) )
jog(lastDirectionButtonPressed, true);
else {
lastDirectionButtonPressed = (ButtonArray::ButtonName)0;
steppers::abort();
}
}
lastPauseState = pauseState;
}
void PauseMode::notifyButtonPressed(ButtonArray::ButtonName button) {
enum PauseState ps = command::pauseState();
if ( ps == PAUSE_STATE_PAUSED ) {
if ( button == ButtonArray::CANCEL )
// setting for second argument doesn't matter here as this cancels a pause
host::pauseBuild(false, 0);
else
jog(button, true);
}
else if ( ps == PAUSE_STATE_ERROR ) {
autoPause = 2;
command::pauseClearError(); // changes pause state to PAUSE_STATE_NONE
}
}
void PauseAtZPosScreen::reset() {
int32_t currentPause = command::getPauseAtZPos();
if ( currentPause == 0 ) {
Point position = steppers::getPlannerPosition();
pauseAtZPos = stepperAxisStepsToMM(position[2], Z_AXIS);
} else pauseAtZPos = stepperAxisStepsToMM(currentPause, Z_AXIS);
}
void PauseAtZPosScreen::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar pz_message1[] = "Pause at ZPos:";
const static PROGMEM prog_uchar pz_mm[] = "mm ";
if (forceRedraw) {
lcd.clearHomeCursor();
lcd.writeFromPgmspace(LOCALIZE(pz_message1));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(updnset_msg));
}
// Redraw tool info
lcd.setRow(1);
lcd.writeFloat((float)pauseAtZPos, 3);
lcd.writeFromPgmspace(LOCALIZE(pz_mm));
}
void PauseAtZPosScreen::notifyButtonPressed(ButtonArray::ButtonName button) {
switch (button) {
default :
return;
case ButtonArray::OK:
//Set the pause
command::pauseAtZPos(stepperAxisMMToSteps(pauseAtZPos, Z_AXIS));
// FALL THROUGH
case ButtonArray::CANCEL:
interface::popScreen();
interface::popScreen();
break;
case ButtonArray::ZPLUS:
// increment more
if (pauseAtZPos <= 250) pauseAtZPos += 1.0;
break;
case ButtonArray::ZMINUS:
// decrement more
if (pauseAtZPos >= 1.0) pauseAtZPos -= 1.0;
else pauseAtZPos = 0.0;
break;
case ButtonArray::YPLUS:
// increment less
if (pauseAtZPos <= 254) pauseAtZPos += 0.05;
break;
case ButtonArray::YMINUS:
// decrement less
if (pauseAtZPos >= 0.05) pauseAtZPos -= 0.05;
else pauseAtZPos = 0.0;
break;
}
if ( pauseAtZPos < 0.001 ) pauseAtZPos = 0.0;
}
void ChangeTempScreen::reset() {
// Make getTemp() think that a toolhead change has occurred
activeToolhead = 255;
altTemp = 0;
getTemp();
}
void ChangeTempScreen::getTemp() {
uint8_t at;
steppers::getStepperPosition(&at);
if ( at != activeToolhead ) {
activeToolhead = at;
altTemp = command::altTemp[activeToolhead];
if ( altTemp == 0 ) {
// Get the current set point
OutPacket responsePacket;
if ( extruderControl(activeToolhead, SLAVE_CMD_GET_SP, EXTDR_CMD_GET, responsePacket, 0) ) {
altTemp = responsePacket.read16(1);
}
else {
// Cannot get the current set point.... Use pre-heat temp?
if ( activeToolhead == 0 )
altTemp = (uint16_t)eeprom::getEeprom8(eeprom::TOOL0_TEMP, EEPROM_DEFAULT_TOOL0_TEMP);
else
altTemp = (uint16_t)eeprom::getEeprom8(eeprom::TOOL1_TEMP, EEPROM_DEFAULT_TOOL1_TEMP);
}
}
if ( altTemp > (uint16_t)MAX_TEMP ) altTemp = MAX_TEMP;
}
}
void ChangeTempScreen::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar ct_message1[] = "Extruder temp:";
if (forceRedraw) {
lcd.clearHomeCursor();
lcd.writeFromPgmspace(LOCALIZE(ct_message1));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(updnset_msg));
}
// Since the print is still running, the active tool head may have changed
getTemp();
// Redraw tool info
lcd.setRow(1);
lcd.writeInt(altTemp, 3);
lcd.write('C');
}
void ChangeTempScreen::notifyButtonPressed(ButtonArray::ButtonName button) {
// We change the actual steppers::speedFactor so that
// the user can see the change dynamically (after making it through
// the queue of planned blocks)
int16_t temp = (int16_t)(0x7fff & altTemp);
switch (button) {
case ButtonArray::OK:
{
OutPacket responsePacket;
// Set the temp
command::altTemp[activeToolhead] = altTemp;
// Only set the temp if the heater is active
if ( extruderControl(activeToolhead, SLAVE_CMD_GET_SP, EXTDR_CMD_GET, responsePacket, 0) ) {
uint16_t data = responsePacket.read16(1);
if ( data != 0 )
extruderControl(activeToolhead, SLAVE_CMD_SET_TEMP, EXTDR_CMD_SET, responsePacket, (uint16_t)altTemp);
}
#ifdef DITTO_PRINT
if ( command::dittoPrinting ) {
uint8_t otherToolhead = activeToolhead ? 0 : 1;
command::altTemp[otherToolhead] = altTemp;
if ( extruderControl(otherToolhead, SLAVE_CMD_GET_SP, EXTDR_CMD_GET, responsePacket, 0) ) {
uint16_t data = responsePacket.read16(1);
if ( data != 0 )
extruderControl(otherToolhead, SLAVE_CMD_SET_TEMP, EXTDR_CMD_SET, responsePacket, (uint16_t)altTemp);
}
}
#endif
}
// FALL THROUGH
case ButtonArray::CANCEL:
interface::popScreen();
interface::popScreen();
return;
case ButtonArray::ZPLUS:
// increment more
temp += 5;
break;
case ButtonArray::ZMINUS:
// decrement more
temp -= 5;
break;
case ButtonArray::YPLUS:
// increment less
temp += 1;
break;
case ButtonArray::YMINUS:
// decrement less
temp -= 1;
break;
default :
return;
}
if (temp > MAX_TEMP ) altTemp = MAX_TEMP;
else if ( temp < 0 ) altTemp = 0;
else altTemp = (uint16_t)(0x7fff & temp);
}
void ChangeSpeedScreen::reset() {
// So that we can restore the speed in case of a CANCEL
speedFactor = steppers::speedFactor;
alterSpeed = steppers::alterSpeed;
}
void ChangeSpeedScreen::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar cs_message1[] = "Increase speed:";
if (forceRedraw) {
lcd.clearHomeCursor();
lcd.writeFromPgmspace(LOCALIZE(cs_message1));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(updnset_msg));
}
// Redraw tool info
lcd.setRow(1);
lcd.write('x');
lcd.writeFloat(FPTOF(steppers::speedFactor), 2);
}
void ChangeSpeedScreen::notifyButtonPressed(ButtonArray::ButtonName button) {
// We change the actual steppers::speedFactor so that
// the user can see the change dynamically (after making it through
// the queue of planned blocks)
FPTYPE sf = steppers::speedFactor;
switch (button) {
case ButtonArray::CANCEL:
// restore the original
steppers::alterSpeed = alterSpeed;
steppers::speedFactor = speedFactor;
// FALL THROUGH
case ButtonArray::OK:
interface::popScreen();
interface::popScreen();
return;
case ButtonArray::ZPLUS:
// increment more
sf += KCONSTANT_0_25;
break;
case ButtonArray::ZMINUS:
// decrement more
sf -= KCONSTANT_0_25;
break;
case ButtonArray::YPLUS:
// increment less
sf += KCONSTANT_0_05;
break;
case ButtonArray::YMINUS:
// decrement less
sf -= KCONSTANT_0_05;
break;
default :
return;
}
if ( sf > KCONSTANT_5 ) sf = KCONSTANT_5;
else if ( sf < KCONSTANT_0_1 ) sf = KCONSTANT_0_1;
// If sf == 1 then disable speedup
steppers::alterSpeed = (sf == KCONSTANT_1) ? 0x00 : 0x80;
steppers::speedFactor = sf;
}
void AdvanceABPMode::reset() {
abpForwarding = false;
}
void AdvanceABPMode::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar abp_msg1[] = "Advance ABP:";
const static PROGMEM prog_uchar abp_msg2[] = "hold key...";
const static PROGMEM prog_uchar abp_msg3[] = " (fwd)";
if (forceRedraw) {
lcd.clearHomeCursor();
lcd.writeFromPgmspace(LOCALIZE(abp_msg1));
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(abp_msg2));
lcd.setRow(2);
lcd.writeFromPgmspace(LOCALIZE(abp_msg3));
}
if (( abpForwarding ) && ( ! interface::isButtonPressed(ButtonArray::OK) )) {
OutPacket responsePacket;
abpForwarding = false;
extruderControl(0, SLAVE_CMD_TOGGLE_ABP, EXTDR_CMD_SET8, responsePacket, (uint16_t)0);
}
}
void AdvanceABPMode::notifyButtonPressed(ButtonArray::ButtonName button) {
OutPacket responsePacket;
switch (button) {
case ButtonArray::OK:
abpForwarding = true;
extruderControl(0, SLAVE_CMD_TOGGLE_ABP, EXTDR_CMD_SET8, responsePacket, (uint16_t)1);
break;
default :
interface::popScreen();
break;
}
}
void CalibrateMode::reset() {
//Disable stepps on axis 0, 1, 2, 3, 4
steppers::enableAxis(0, false);
steppers::enableAxis(1, false);
steppers::enableAxis(2, false);
steppers::enableAxis(3, false);
steppers::enableAxis(4, false);
lastCalibrationState = CS_NONE;
calibrationState = CS_START1;
}
void CalibrateMode::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar c_calib1[] = "Calibrate: Move ";
const static PROGMEM prog_uchar c_calib2[] = "build platform";
const static PROGMEM prog_uchar c_calib3[] = "until nozzle...";
const static PROGMEM prog_uchar c_calib4[] = " (cont)";
const static PROGMEM prog_uchar c_calib5[] = "lies in center,";
const static PROGMEM prog_uchar c_calib6[] = "turn threaded";
const static PROGMEM prog_uchar c_calib7[] = "rod until...";
const static PROGMEM prog_uchar c_calib8[] = "nozzle just";
const static PROGMEM prog_uchar c_calib9[] = "touches.";
const static PROGMEM prog_uchar c_homeZ[] = "Homing Z...";
const static PROGMEM prog_uchar c_homeY[] = "Homing Y...";
const static PROGMEM prog_uchar c_homeX[] = "Homing X...";
const static PROGMEM prog_uchar c_done[] = "! Calibrated !";
const static PROGMEM prog_uchar c_regen[] = "Regenerate gcode";
const static PROGMEM prog_uchar c_reset[] = " (reset)";
if ((forceRedraw) || (calibrationState != lastCalibrationState)) {
lcd.clearHomeCursor();
switch(calibrationState) {
case CS_START1:
lcd.writeFromPgmspace(LOCALIZE(c_calib1));
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(c_calib2));
lcd.setRow(2);
lcd.writeFromPgmspace(LOCALIZE(c_calib3));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(c_calib4));
break;
case CS_START2:
lcd.writeFromPgmspace(LOCALIZE(c_calib5));
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(c_calib6));
lcd.setRow(2);
lcd.writeFromPgmspace(LOCALIZE(c_calib7));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(c_calib4));
break;
case CS_PROMPT_MOVE:
lcd.writeFromPgmspace(LOCALIZE(c_calib8));
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(c_calib9));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(c_calib4));
break;
case CS_HOME_Z:
case CS_HOME_Z_WAIT:
lcd.writeFromPgmspace(LOCALIZE(c_homeZ));
break;
case CS_HOME_Y:
case CS_HOME_Y_WAIT:
lcd.writeFromPgmspace(LOCALIZE(c_homeY));
break;
case CS_HOME_X:
case CS_HOME_X_WAIT:
lcd.writeFromPgmspace(LOCALIZE(c_homeX));
break;
case CS_PROMPT_CALIBRATED:
lcd.writeFromPgmspace(LOCALIZE(c_done));
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(c_regen));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(c_reset));
break;
default:
break;
}
}
lastCalibrationState = calibrationState;
//Change the state
//Some states are changed when a button is pressed via notifyButton
//Some states are changed when something completes, in which case we do it here
float interval = 2000.0;
bool maximums = false;
uint8_t endstops = eeprom::getEeprom8(eeprom::ENDSTOPS_USED, EEPROM_DEFAULT_ENDSTOPS_USED);
float feedRate, stepsPerSecond;
switch(calibrationState) {
case CS_HOME_Z:
//Declare current position to be x=0, y=0, z=0, a=0, b=0
steppers::definePosition(Point(0,0,0,0,0), false);
interval *= stepperAxisStepsToMM((int32_t)200.0, Z_AXIS); //Use ToM as baseline
if ( endstops & 0x20 ) maximums = true;
if ( endstops & 0x10 ) maximums = false;
feedRate = (float)eeprom::getEepromUInt32(eeprom::HOMING_FEED_RATE_Z, EEPROM_DEFAULT_HOMING_FEED_RATE_Z) / 60.0;
stepsPerSecond = feedRate * (float)stepperAxisMMToSteps(1.0, Z_AXIS);
interval = 1000000.0 / stepsPerSecond;
steppers::startHoming(maximums, 0x04, (uint32_t)interval);
calibrationState = CS_HOME_Z_WAIT;
break;
case CS_HOME_Z_WAIT:
if ( ! steppers::isHoming() ) calibrationState = CS_HOME_Y;
break;
case CS_HOME_Y:
interval *= stepperAxisStepsToMM((int32_t)47.06, Y_AXIS); //Use ToM as baseline
if ( endstops & 0x08 ) maximums = true;
if ( endstops & 0x04 ) maximums = false;
feedRate = (float)eeprom::getEepromUInt32(eeprom::HOMING_FEED_RATE_Y, EEPROM_DEFAULT_HOMING_FEED_RATE_Y) / 60.0;
stepsPerSecond = feedRate * (float)stepperAxisMMToSteps(1.0, Y_AXIS);
interval = 1000000.0 / stepsPerSecond;
steppers::startHoming(maximums, 0x02, (uint32_t)interval);
calibrationState = CS_HOME_Y_WAIT;
break;
case CS_HOME_Y_WAIT:
if ( ! steppers::isHoming() ) calibrationState = CS_HOME_X;
break;
case CS_HOME_X:
interval *= stepperAxisStepsToMM((int32_t)47.06, X_AXIS); //Use ToM as baseline
if ( endstops & 0x02 ) maximums = true;
if ( endstops & 0x01 ) maximums = false;
feedRate = (float)eeprom::getEepromUInt32(eeprom::HOMING_FEED_RATE_X, EEPROM_DEFAULT_HOMING_FEED_RATE_X) / 60.0;
stepsPerSecond = feedRate * (float)stepperAxisMMToSteps(1.0, X_AXIS);
interval = 1000000.0 / stepsPerSecond;
steppers::startHoming(maximums, 0x01, (uint32_t)interval);
calibrationState = CS_HOME_X_WAIT;
break;
case CS_HOME_X_WAIT:
if ( ! steppers::isHoming() ) {
//Record current X, Y, Z, A, B co-ordinates to the motherboard
for (uint8_t i = 0; i < STEPPER_COUNT; i++) {
uint16_t offset = eeprom::AXIS_HOME_POSITIONS + 4*i;
uint32_t position = steppers::getStepperPosition()[i];
cli();
eeprom_write_block(&position, (void*) offset, 4);
sei();
}
//Disable stepps on axis 0, 1, 2, 3, 4
steppers::enableAxis(0, false);
steppers::enableAxis(1, false);
steppers::enableAxis(2, false);
steppers::enableAxis(3, false);
steppers::enableAxis(4, false);
calibrationState = CS_PROMPT_CALIBRATED;
}
break;
default:
break;
}
}
void CalibrateMode::notifyButtonPressed(ButtonArray::ButtonName button) {
if ( calibrationState == CS_PROMPT_CALIBRATED ) {
host::stopBuildNow();
return;
}
switch (button) {
default:
if (( calibrationState == CS_START1 ) || ( calibrationState == CS_START2 ) ||
(calibrationState == CS_PROMPT_MOVE )) calibrationState = (enum calibrateState)((uint8_t)calibrationState + 1);
break;
case ButtonArray::CANCEL:
interface::popScreen();
break;
}
}
void HomeOffsetsMode::reset() {
homePosition = steppers::getStepperPosition();
for (uint8_t i = 0; i < STEPPER_COUNT; i++) {
uint16_t offset = eeprom::AXIS_HOME_POSITIONS + 4*i;
cli();
eeprom_read_block(&(homePosition[i]), (void*) offset, 4);
sei();
}
lastHomeOffsetState = HOS_NONE;
homeOffsetState = HOS_OFFSET_X;
}
void HomeOffsetsMode::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar ho_message1x[] = "X Offset:";
const static PROGMEM prog_uchar ho_message1y[] = "Y Offset:";
const static PROGMEM prog_uchar ho_message1z[] = "Z Offset:";
if ( homeOffsetState != lastHomeOffsetState ) forceRedraw = true;
if (forceRedraw) {
lcd.clearHomeCursor();
switch(homeOffsetState) {
case HOS_OFFSET_X:
lcd.writeFromPgmspace(LOCALIZE(ho_message1x));
break;
case HOS_OFFSET_Y:
lcd.writeFromPgmspace(LOCALIZE(ho_message1y));
break;
case HOS_OFFSET_Z:
lcd.writeFromPgmspace(LOCALIZE(ho_message1z));
break;
default:
break;
}
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(updnset_msg));
}
float position = 0.0;
switch(homeOffsetState) {
case HOS_OFFSET_X:
position = stepperAxisStepsToMM(homePosition[0], X_AXIS);
break;
case HOS_OFFSET_Y:
position = stepperAxisStepsToMM(homePosition[1], Y_AXIS);
break;
case HOS_OFFSET_Z:
position = stepperAxisStepsToMM(homePosition[2], Z_AXIS);
break;
default:
break;
}
lcd.setRow(1);
lcd.writeFloat((float)position, 3);
lcd.writeFromPgmspace(LOCALIZE(units_mm));
lastHomeOffsetState = homeOffsetState;
}
void HomeOffsetsMode::notifyButtonPressed(ButtonArray::ButtonName button) {
if (( homeOffsetState == HOS_OFFSET_Z ) && (button == ButtonArray::OK )) {
//Write the new home positions
for (uint8_t i = 0; i < STEPPER_COUNT; i++) {
uint16_t offset = eeprom::AXIS_HOME_POSITIONS + 4*i;
uint32_t position = homePosition[i];
cli();
eeprom_write_block(&position, (void*) offset, 4);
sei();
}
host::stopBuildNow();
return;
}
uint8_t currentIndex = homeOffsetState - HOS_OFFSET_X;
switch (button) {
case ButtonArray::CANCEL:
interface::popScreen();
break;
case ButtonArray::ZERO:
break;
case ButtonArray::OK:
if ( homeOffsetState == HOS_OFFSET_X ) homeOffsetState = HOS_OFFSET_Y;
else if ( homeOffsetState == HOS_OFFSET_Y ) homeOffsetState = HOS_OFFSET_Z;
break;
case ButtonArray::ZPLUS:
// increment more
homePosition[currentIndex] += 20;
break;
case ButtonArray::ZMINUS:
// decrement more
homePosition[currentIndex] -= 20;
break;
case ButtonArray::YPLUS:
// increment less
homePosition[currentIndex] += 1;
break;
case ButtonArray::YMINUS:
// decrement less
homePosition[currentIndex] -= 1;
break;
case ButtonArray::XMINUS:
case ButtonArray::XPLUS:
break;
}
}
void BuzzerSetRepeatsMode::reset() {
repeats = eeprom::getEeprom8(eeprom::BUZZER_REPEATS, EEPROM_DEFAULT_BUZZER_REPEATS);
}
void BuzzerSetRepeatsMode::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar bsr_message1[] = "Repeat Buzzer:";
const static PROGMEM prog_uchar bsr_message2[] = "(0=Buzzer Off)";
const static PROGMEM prog_uchar bsr_times[] = " times ";
if (forceRedraw) {
lcd.clearHomeCursor();
lcd.writeFromPgmspace(LOCALIZE(bsr_message1));
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(bsr_message2));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(updnset_msg));
}
// Redraw tool info
lcd.setRow(2);
lcd.writeInt(repeats, 3);
lcd.writeFromPgmspace(LOCALIZE(bsr_times));
}
void BuzzerSetRepeatsMode::notifyButtonPressed(ButtonArray::ButtonName button) {
switch (button) {
case ButtonArray::CANCEL:
interface::popScreen();
break;
case ButtonArray::ZERO:
break;
case ButtonArray::OK:
eeprom_write_byte((uint8_t *)eeprom::BUZZER_REPEATS, repeats);
interface::popScreen();
break;
case ButtonArray::ZPLUS:
// increment more
if (repeats <= 249) repeats += 5;
break;
case ButtonArray::ZMINUS:
// decrement more
if (repeats >= 5) repeats -= 5;
break;
case ButtonArray::YPLUS:
// increment less
if (repeats <= 253) repeats += 1;
break;
case ButtonArray::YMINUS:
// decrement less
if (repeats >= 1) repeats -= 1;
break;
case ButtonArray::XMINUS:
case ButtonArray::XPLUS:
break;
}
}
bool ExtruderFanMenu::isEnabled() {
//Should really check the current status of the fan here
return false;
}
void ExtruderFanMenu::enable(bool enabled) {
OutPacket responsePacket;
extruderControl(0, SLAVE_CMD_TOGGLE_FAN, EXTDR_CMD_SET, responsePacket, (uint16_t)((enabled)?1:0));
}
void ExtruderFanMenu::setupTitle() {
static const PROGMEM prog_uchar ext_msg1[] = "Extruder Fan:";
static const PROGMEM prog_uchar ext_msg2[] = "";
msg1 = LOCALIZE(ext_msg1);
msg2 = LOCALIZE(ext_msg2);
}
FilamentUsedResetMenu::FilamentUsedResetMenu() {
itemCount = 4;
reset();
}
void FilamentUsedResetMenu::resetState() {
itemIndex = 2;
firstItemIndex = 2;
}
void FilamentUsedResetMenu::drawItem(uint8_t index, LiquidCrystal& lcd) {
const static PROGMEM prog_uchar fur_msg[] = "Reset To Zero?";
const static PROGMEM prog_uchar fur_no[] = "No";
const static PROGMEM prog_uchar fur_yes[] = "Yes";
switch (index) {
case 0:
lcd.writeFromPgmspace(LOCALIZE(fur_msg));
break;
case 1:
break;
case 2:
lcd.writeFromPgmspace(LOCALIZE(fur_no));
break;
case 3:
lcd.writeFromPgmspace(LOCALIZE(fur_yes));
break;
}
}
void FilamentUsedResetMenu::handleSelect(uint8_t index) {
switch (index) {
case 3:
//Reset to zero
eeprom::putEepromInt64(eeprom::FILAMENT_LIFETIME_A, EEPROM_DEFAULT_FILAMENT_LIFETIME);
eeprom::putEepromInt64(eeprom::FILAMENT_LIFETIME_B, EEPROM_DEFAULT_FILAMENT_LIFETIME);
eeprom::putEepromInt64(eeprom::FILAMENT_TRIP_A, EEPROM_DEFAULT_FILAMENT_TRIP);
eeprom::putEepromInt64(eeprom::FILAMENT_TRIP_B, EEPROM_DEFAULT_FILAMENT_TRIP);
case 2:
interface::popScreen();
interface::popScreen();
break;
}
}
void FilamentUsedMode::reset() {
lifetimeDisplay = true;
overrideForceRedraw = false;
}
void FilamentUsedMode::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar fu_lifetime[] = "Lifetime Odo.:";
const static PROGMEM prog_uchar fu_trip[] = "Trip Odometer:";
const static PROGMEM prog_uchar fu_but_life[] = "(trip) (reset)";
const static PROGMEM prog_uchar fu_but_trip[] = "(life) (reset)";
if ((forceRedraw) || (overrideForceRedraw)) {
lcd.clearHomeCursor();
if ( lifetimeDisplay ) lcd.writeFromPgmspace(LOCALIZE(fu_lifetime));
else lcd.writeFromPgmspace(LOCALIZE(fu_trip));
int64_t filamentUsedA = eeprom::getEepromInt64(eeprom::FILAMENT_LIFETIME_A, EEPROM_DEFAULT_FILAMENT_LIFETIME);
int64_t filamentUsedB = eeprom::getEepromInt64(eeprom::FILAMENT_LIFETIME_B, EEPROM_DEFAULT_FILAMENT_LIFETIME);
if ( ! lifetimeDisplay ) {
int64_t tripA = eeprom::getEepromInt64(eeprom::FILAMENT_TRIP_A, EEPROM_DEFAULT_FILAMENT_TRIP);
int64_t tripB = eeprom::getEepromInt64(eeprom::FILAMENT_TRIP_B, EEPROM_DEFAULT_FILAMENT_TRIP);
filamentUsedA = filamentUsedA - tripA;
filamentUsedB = filamentUsedB - tripB;
}
float filamentUsedMMA = stepperAxisStepsToMM(filamentUsedA, A_AXIS);
#if EXTRUDERS > 1
float filamentUsedMMB = stepperAxisStepsToMM(filamentUsedB, B_AXIS);
#else
float filamentUsedMMB = 0.0f;
#endif
float filamentUsedMM = filamentUsedMMA + filamentUsedMMB;
lcd.setRow(1);
lcd.writeFloat(filamentUsedMM / 1000.0, 4);
lcd.write('m');
lcd.setRow(2);
if ( lifetimeDisplay ) lcd.writeFromPgmspace(LOCALIZE(fu_but_life));
else lcd.writeFromPgmspace(LOCALIZE(fu_but_trip));
lcd.setRow(3);
lcd.writeFloat(((filamentUsedMM / 25.4) / 12.0), 4);
lcd.writeString((char *)"ft");
overrideForceRedraw = false;
}
}
void FilamentUsedMode::notifyButtonPressed(ButtonArray::ButtonName button) {
switch (button) {
case ButtonArray::CANCEL:
interface::popScreen();
break;
case ButtonArray::ZERO:
lifetimeDisplay ^= true;
overrideForceRedraw = true;
break;
case ButtonArray::OK:
if ( lifetimeDisplay )
interface::pushScreen(&filamentUsedResetMenu);
else {
eeprom::putEepromInt64(eeprom::FILAMENT_TRIP_A, eeprom::getEepromInt64(eeprom::FILAMENT_LIFETIME_A, EEPROM_DEFAULT_FILAMENT_LIFETIME));
eeprom::putEepromInt64(eeprom::FILAMENT_TRIP_B, eeprom::getEepromInt64(eeprom::FILAMENT_LIFETIME_B, EEPROM_DEFAULT_FILAMENT_LIFETIME));
interface::popScreen();
}
break;
default:
break;
}
}
BuildSettingsMenu::BuildSettingsMenu() {
itemCount = 5;
reset();
}
void BuildSettingsMenu::resetState() {
acceleration = 1 == (eeprom::getEeprom8(eeprom::ACCELERATION_ON, EEPROM_DEFAULT_ACCELERATION_ON) & 0x01);
itemCount = acceleration ? 8 : 7;
#ifdef PSTOP_SUPPORT
itemCount++;
#endif
itemIndex = 0;
firstItemIndex = 0;
genericOnOff_msg1 = 0;
genericOnOff_msg2 = 0;
genericOnOff_msg3 = LOCALIZE(generic_off);
genericOnOff_msg4 = LOCALIZE(generic_on);
}
void BuildSettingsMenu::drawItem(uint8_t index, LiquidCrystal& lcd) {
const static PROGMEM prog_uchar bs_item0[] = "Override Temp";
const static PROGMEM prog_uchar bs_item1[] = "Ditto Print";
const static PROGMEM prog_uchar bs_item2[] = "Accel. On/Off";
const static PROGMEM prog_uchar bs_item3[] = "Accel. Settings";
const static PROGMEM prog_uchar bs_item4[] = "Extruder Hold";
const static PROGMEM prog_uchar bs_item5[] = "Toolhead System";
const static PROGMEM prog_uchar bs_item6[] = "SD Err Checking";
const static PROGMEM prog_uchar bs_item7[] = "ABP Copies (SD)";
const static PROGMEM prog_uchar bs_item8[] = "Pause Stop";
if ( !acceleration && index > 2 ) ++index;
const prog_uchar *msg;
switch (index) {
default:
return;
case 0:
msg = LOCALIZE(bs_item0);
break;
case 1:
msg = LOCALIZE(bs_item1);
break;
case 2:
msg = LOCALIZE(bs_item2);
break;
case 3:
msg = LOCALIZE(bs_item3);
break;
case 4:
msg = LOCALIZE(bs_item4);
break;
case 5:
msg = LOCALIZE(bs_item5);
break;
case 6:
msg = LOCALIZE(bs_item6);
break;
case 7:
msg = LOCALIZE(bs_item7);
break;
#ifdef PSTOP_SUPPORT
case 8:
msg = LOCALIZE(bs_item8);
break;
#endif
}
lcd.writeFromPgmspace(msg);
}
void BuildSettingsMenu::handleSelect(uint8_t index) {
OutPacket responsePacket;
if ( !acceleration && index > 2 ) ++index;
genericOnOff_msg2 = 0;
genericOnOff_msg3 = LOCALIZE(generic_off);
genericOnOff_msg4 = LOCALIZE(generic_on);
switch (index) {
case 0:
//Override the gcode temperature
genericOnOff_offset = eeprom::OVERRIDE_GCODE_TEMP;
genericOnOff_default = EEPROM_DEFAULT_OVERRIDE_GCODE_TEMP;
genericOnOff_msg1 = LOCALIZE(ogct_msg1);
genericOnOff_msg2 = LOCALIZE(ogct_msg2);
break;
case 1:
//Ditto Print
genericOnOff_offset = eeprom::DITTO_PRINT_ENABLED;
genericOnOff_default = EEPROM_DEFAULT_DITTO_PRINT_ENABLED;
genericOnOff_msg1 = LOCALIZE(dp_msg1);
break;
case 2:
//Acceleraton On/Off Menu
genericOnOff_offset = eeprom::ACCELERATION_ON;
genericOnOff_default = EEPROM_DEFAULT_ACCELERATION_ON;
genericOnOff_msg1 = LOCALIZE(aof_msg1);
genericOnOff_msg2 = LOCALIZE(aof_msg2);
break;
case 3:
interface::pushScreen(&acceleratedSettingsMode);
return;
case 4:
//Extruder Hold
genericOnOff_offset = eeprom::EXTRUDER_HOLD;
genericOnOff_default = EEPROM_DEFAULT_EXTRUDER_HOLD;
genericOnOff_msg1 = LOCALIZE(eof_msg1);
break;
case 5:
//Toolhead System
genericOnOff_offset = eeprom::TOOLHEAD_OFFSET_SYSTEM;
genericOnOff_default = EEPROM_DEFAULT_TOOLHEAD_OFFSET_SYSTEM;
genericOnOff_msg1 = LOCALIZE(ts_msg1);
genericOnOff_msg2 = LOCALIZE(ts_msg2);
genericOnOff_msg3 = LOCALIZE(ts_old);
genericOnOff_msg4 = LOCALIZE(ts_new);
break;
case 6:
// SD card error checking
genericOnOff_offset = eeprom::SD_USE_CRC;
genericOnOff_default = EEPROM_DEFAULT_SD_USE_CRC;
genericOnOff_msg1 = LOCALIZE(sdcrc_msg1);
genericOnOff_msg2 = LOCALIZE(sdcrc_msg2);
break;
case 7:
//Change number of ABP copies
interface::pushScreen(&abpCopiesSetScreen);
return;
#ifdef PSTOP_SUPPORT
case 8:
// Enable|disable the P-Stop
genericOnOff_offset = eeprom::PSTOP_ENABLE;
genericOnOff_default = EEPROM_DEFAULT_PSTOP_ENABLE;
genericOnOff_msg1 = LOCALIZE(pstop_msg1);
break;
#endif
}
interface::pushScreen(&genericOnOffMenu);
}
void ABPCopiesSetScreen::reset() {
value = eeprom::getEeprom8(eeprom::ABP_COPIES, EEPROM_DEFAULT_ABP_COPIES);
if ( value < 1 ) {
eeprom_write_byte((uint8_t*)eeprom::ABP_COPIES,EEPROM_DEFAULT_ABP_COPIES);
value = eeprom::getEeprom8(eeprom::ABP_COPIES, EEPROM_DEFAULT_ABP_COPIES); //Just in case
}
}
void ABPCopiesSetScreen::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar abp_message1[] = "ABP Copies (SD):";
if (forceRedraw) {
lcd.clearHomeCursor();
lcd.writeFromPgmspace(LOCALIZE(abp_message1));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(updnset_msg));
}
// Redraw tool info
lcd.setRow(1);
lcd.writeInt(value,3);
}
void ABPCopiesSetScreen::notifyButtonPressed(ButtonArray::ButtonName button) {
switch (button) {
case ButtonArray::CANCEL:
interface::popScreen();
break;
case ButtonArray::ZERO:
break;
case ButtonArray::OK:
eeprom_write_byte((uint8_t*)eeprom::ABP_COPIES,value);
interface::popScreen();
interface::popScreen();
break;
case ButtonArray::ZPLUS:
// increment more
if (value <= 249) {
value += 5;
}
break;
case ButtonArray::ZMINUS:
// decrement more
if (value >= 6) {
value -= 5;
}
break;
case ButtonArray::YPLUS:
// increment less
if (value <= 253) {
value += 1;
}
break;
case ButtonArray::YMINUS:
// decrement less
if (value >= 2) {
value -= 1;
}
break;
default:
break;
}
}
GenericOnOffMenu::GenericOnOffMenu() {
itemCount = 4;
reset();
}
void GenericOnOffMenu::resetState() {
uint8_t val = eeprom::getEeprom8(genericOnOff_offset, genericOnOff_default);
bool state = (genericOnOff_offset == eeprom::SD_USE_CRC) ? (val == 1) : (val != 0);
itemIndex = state ? 3 : 2;
firstItemIndex = 2;
}
void GenericOnOffMenu::drawItem(uint8_t index, LiquidCrystal& lcd) {
const prog_uchar *msg;
switch (index) {
default :
return;
case 0:
msg = genericOnOff_msg1;
break;
case 1:
msg = genericOnOff_msg2;
break;
case 2:
msg = genericOnOff_msg3;
break;
case 3:
msg = genericOnOff_msg4;
break;
}
if (msg) lcd.writeFromPgmspace(msg);
}
void GenericOnOffMenu::handleSelect(uint8_t index) {
uint8_t oldValue = (eeprom::getEeprom8(genericOnOff_offset, genericOnOff_default)) != 0;
uint8_t newValue = oldValue;
switch (index) {
default:
return;
case 2:
newValue = 0x00;
break;
case 3:
newValue = 0x01;
break;
}
interface::popScreen();
//If the value has changed, do a reset
if ( newValue != oldValue ) {
cli();
eeprom_write_byte((uint8_t*)genericOnOff_offset, newValue);
sei();
//Reset
#ifndef BROKEN_SD
if ( genericOnOff_offset == eeprom::SD_USE_CRC )
sdcard::mustReinit = true;
else
#endif
host::stopBuildNow();
}
}
#define NUM_PROFILES 4
#define PROFILES_SAVED_AXIS 3
void writeProfileToEeprom(uint8_t pIndex, uint8_t *pName, int32_t homeX,
int32_t homeY, int32_t homeZ, uint8_t hbpTemp,
uint8_t tool0Temp, uint8_t tool1Temp, uint8_t extruderMMS) {
uint16_t offset = eeprom::PROFILE_BASE + (uint16_t)pIndex * PROFILE_NEXT_OFFSET;
cli();
//Write profile name
if ( pName ) eeprom_write_block(pName,(uint8_t*)offset, PROFILE_NAME_LENGTH);
offset += PROFILE_NAME_LENGTH;
//Write home axis
eeprom_write_block(&homeX, (void*) offset, 4); offset += 4;
eeprom_write_block(&homeY, (void*) offset, 4); offset += 4;
eeprom_write_block(&homeZ, (void*) offset, 4); offset += 4;
//Write temps and extruder MMS
eeprom_write_byte((uint8_t *)offset, hbpTemp); offset += 1;
eeprom_write_byte((uint8_t *)offset, tool0Temp); offset += 1;
eeprom_write_byte((uint8_t *)offset, tool1Temp); offset += 1;
eeprom_write_byte((uint8_t *)offset, extruderMMS); offset += 1;
sei();
}
void readProfileFromEeprom(uint8_t pIndex, uint8_t *pName, int32_t *homeX,
int32_t *homeY, int32_t *homeZ, uint8_t *hbpTemp,
uint8_t *tool0Temp, uint8_t *tool1Temp, uint8_t *extruderMMS) {
uint16_t offset = eeprom::PROFILE_BASE + (uint16_t)pIndex * PROFILE_NEXT_OFFSET;
cli();
//Read profile name
if ( pName ) eeprom_read_block(pName,(uint8_t*)offset, PROFILE_NAME_LENGTH);
offset += PROFILE_NAME_LENGTH;
//Write home axis
eeprom_read_block(homeX, (void*) offset, 4); offset += 4;
eeprom_read_block(homeY, (void*) offset, 4); offset += 4;
eeprom_read_block(homeZ, (void*) offset, 4); offset += 4;
//Write temps and extruder MMS
*hbpTemp = eeprom_read_byte((uint8_t *)offset); offset += 1;
*tool0Temp = eeprom_read_byte((uint8_t *)offset); offset += 1;
*tool1Temp = eeprom_read_byte((uint8_t *)offset); offset += 1;
*extruderMMS = eeprom_read_byte((uint8_t *)offset); offset += 1;
sei();
}
//buf should have length PROFILE_NAME_LENGTH + 1
void getProfileName(uint8_t pIndex, uint8_t *buf) {
uint16_t offset = eeprom::PROFILE_BASE + PROFILE_NEXT_OFFSET * (uint16_t)pIndex;
cli();
eeprom_read_block(buf,(void *)offset,PROFILE_NAME_LENGTH);
sei();
buf[PROFILE_NAME_LENGTH] = '\0';
}
#define NAME_CHAR_LOWER_LIMIT 32
#define NAME_CHAR_UPPER_LIMIT 126
bool isValidProfileName(uint8_t pIndex) {
uint8_t buf[PROFILE_NAME_LENGTH + 1];
getProfileName(pIndex, buf);
for ( uint8_t i = 0; i < PROFILE_NAME_LENGTH; i ++ ) {
if (( buf[i] < NAME_CHAR_LOWER_LIMIT ) || ( buf[i] > NAME_CHAR_UPPER_LIMIT ) || ( buf[i] == 0xff )) return false;
}
return true;
}
ProfilesMenu::ProfilesMenu() {
itemCount = NUM_PROFILES;
reset();
//Setup defaults if required
//If the value is 0xff, write the profile number
uint8_t buf[PROFILE_NAME_LENGTH+1];
const static PROGMEM prog_uchar pro_defaultProfile[] = "Profile?";
//Get the home axis positions, we may need this to write the defaults
homePosition = steppers::getStepperPosition();
for (uint8_t i = 0; i < PROFILES_SAVED_AXIS; i++) {
uint16_t offset = eeprom::AXIS_HOME_POSITIONS + 4*(uint16_t)i;
cli();
eeprom_read_block(&homePosition[i], (void*)offset, 4);
sei();
}
for (int p = 0; p < NUM_PROFILES; p ++ ) {
if ( ! isValidProfileName(p)) {
//Create the default profile name
for( uint8_t i = 0; i < PROFILE_NAME_LENGTH; i ++ )
buf[i] = pgm_read_byte_near(pro_defaultProfile+i);
buf[PROFILE_NAME_LENGTH - 1] = '1' + p;
//Write the defaults
writeProfileToEeprom(p, buf, homePosition[0], homePosition[1], homePosition[2],
100, 210, 210, 19);
}
}
}
void ProfilesMenu::resetState() {
firstItemIndex = 0;
itemIndex = 0;
}
void ProfilesMenu::drawItem(uint8_t index, LiquidCrystal& lcd) {
uint8_t buf[PROFILE_NAME_LENGTH + 1];
getProfileName(index, buf);
lcd.writeString((char *)buf);
}
void ProfilesMenu::handleSelect(uint8_t index) {
profileSubMenu.profileIndex = index;
interface::pushScreen(&profileSubMenu);
}
ProfileSubMenu::ProfileSubMenu() {
itemCount = 4;
reset();
}
void ProfileSubMenu::resetState() {
itemIndex = 0;
firstItemIndex = 0;
}
void ProfileSubMenu::drawItem(uint8_t index, LiquidCrystal& lcd) {
const static PROGMEM prog_uchar ps_msg1[] = "Restore";
const static PROGMEM prog_uchar ps_msg2[] = "Display Config";
const static PROGMEM prog_uchar ps_msg3[] = "Change Name";
const static PROGMEM prog_uchar ps_msg4[] = "Save To Profile";
switch (index) {
case 0:
lcd.writeFromPgmspace(LOCALIZE(ps_msg1));
break;
case 1:
lcd.writeFromPgmspace(LOCALIZE(ps_msg2));
break;
case 2:
lcd.writeFromPgmspace(LOCALIZE(ps_msg3));
break;
case 3:
lcd.writeFromPgmspace(LOCALIZE(ps_msg4));
break;
}
}
void ProfileSubMenu::handleSelect(uint8_t index) {
uint8_t hbpTemp, tool0Temp, tool1Temp, extruderMMS;
switch (index) {
case 0:
//Restore
//Read settings from eeprom
readProfileFromEeprom(profileIndex, NULL, &homePosition[0], &homePosition[1], &homePosition[2],
&hbpTemp, &tool0Temp, &tool1Temp, &extruderMMS);
//Write out the home offsets
for (uint8_t i = 0; i < PROFILES_SAVED_AXIS; i++) {
uint16_t offset = eeprom::AXIS_HOME_POSITIONS + 4*(uint16_t)i;
cli();
eeprom_write_block(&homePosition[i], (void*)offset, 4);
sei();
}
cli();
eeprom_write_byte((uint8_t *)eeprom::PLATFORM_TEMP, hbpTemp);
eeprom_write_byte((uint8_t *)eeprom::TOOL0_TEMP, tool0Temp);
eeprom_write_byte((uint8_t *)eeprom::TOOL1_TEMP, tool1Temp);
eeprom_write_byte((uint8_t *)eeprom::EXTRUDE_MMS, extruderMMS);
sei();
interface::popScreen();
interface::popScreen();
//Reset
host::stopBuildNow();
break;
case 1:
//Display settings
profileDisplaySettingsMenu.profileIndex = profileIndex;
interface::pushScreen(&profileDisplaySettingsMenu);
break;
case 2:
//Change Profile Name
profileChangeNameMode.profileIndex = profileIndex;
interface::pushScreen(&profileChangeNameMode);
break;
case 3: //Save To Profile
//Get the home axis positions
homePosition = steppers::getStepperPosition();
for (uint8_t i = 0; i < PROFILES_SAVED_AXIS; i++) {
uint16_t offset = eeprom::AXIS_HOME_POSITIONS + 4*(uint16_t)i;
cli();
eeprom_read_block(&homePosition[i], (void*)offset, 4);
sei();
}
hbpTemp = eeprom::getEeprom8(eeprom::PLATFORM_TEMP, EEPROM_DEFAULT_PLATFORM_TEMP);
tool0Temp = eeprom::getEeprom8(eeprom::TOOL0_TEMP, EEPROM_DEFAULT_TOOL0_TEMP);
tool1Temp = eeprom::getEeprom8(eeprom::TOOL1_TEMP, EEPROM_DEFAULT_TOOL1_TEMP);
extruderMMS = eeprom::getEeprom8(eeprom::EXTRUDE_MMS, EEPROM_DEFAULT_EXTRUDE_MMS);
writeProfileToEeprom(profileIndex, NULL, homePosition[0], homePosition[1], homePosition[2],
hbpTemp, tool0Temp, tool1Temp, extruderMMS);
interface::popScreen();
break;
}
}
void ProfileChangeNameMode::reset() {
cursorLocation = 0;
getProfileName(profileIndex, profileName);
}
void ProfileChangeNameMode::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar pcn_message1[] = "Profile Name:";
const static PROGMEM prog_uchar pcn_blank[] = " ";
if (forceRedraw) {
lcd.clearHomeCursor();
lcd.writeFromPgmspace(LOCALIZE(pcn_message1));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(updnset_msg));
}
lcd.setRow(1);
lcd.writeString((char *)profileName);
//Draw the cursor
lcd.setCursor(cursorLocation,2);
lcd.write('^');
//Write a blank before and after the cursor if we're not at the ends
if ( cursorLocation >= 1 ) {
lcd.setCursor(cursorLocation-1, 2);
lcd.writeFromPgmspace(LOCALIZE(pcn_blank));
}
if ( cursorLocation < PROFILE_NAME_LENGTH ) {
lcd.setCursor(cursorLocation+1, 2);
lcd.writeFromPgmspace(LOCALIZE(pcn_blank));
}
}
void ProfileChangeNameMode::notifyButtonPressed(ButtonArray::ButtonName button) {
uint16_t offset;
switch (button) {
case ButtonArray::CANCEL:
interface::popScreen();
break;
case ButtonArray::ZERO:
break;
case ButtonArray::OK:
//Write the profile name
offset = eeprom::PROFILE_BASE + (uint16_t)profileIndex * PROFILE_NEXT_OFFSET;
cli();
eeprom_write_block(profileName,(uint8_t*)offset, PROFILE_NAME_LENGTH);
sei();
interface::popScreen();
break;
case ButtonArray::YPLUS:
profileName[cursorLocation] += 1;
break;
case ButtonArray::ZPLUS:
profileName[cursorLocation] += 5;
break;
case ButtonArray::YMINUS:
profileName[cursorLocation] -= 1;
break;
case ButtonArray::ZMINUS:
profileName[cursorLocation] -= 5;
break;
case ButtonArray::XMINUS:
if ( cursorLocation > 0 ) cursorLocation --;
break;
case ButtonArray::XPLUS:
if ( cursorLocation < (PROFILE_NAME_LENGTH-1) ) cursorLocation ++;
break;
}
//Hard limits
if ( profileName[cursorLocation] < NAME_CHAR_LOWER_LIMIT ) profileName[cursorLocation] = NAME_CHAR_LOWER_LIMIT;
if ( profileName[cursorLocation] > NAME_CHAR_UPPER_LIMIT ) profileName[cursorLocation] = NAME_CHAR_UPPER_LIMIT;
}
ProfileDisplaySettingsMenu::ProfileDisplaySettingsMenu() {
itemCount = 8;
reset();
}
void ProfileDisplaySettingsMenu::resetState() {
readProfileFromEeprom(profileIndex, profileName, &homeX, &homeY, &homeZ,
&hbpTemp, &tool0Temp, &tool1Temp, &extruderMMS);
itemIndex = 2;
firstItemIndex = 2;
}
void ProfileDisplaySettingsMenu::drawItem(uint8_t index, LiquidCrystal& lcd) {
const static PROGMEM prog_uchar pds_xOffset[] = "XOff: ";
const static PROGMEM prog_uchar pds_yOffset[] = "YOff: ";
const static PROGMEM prog_uchar pds_zOffset[] = "ZOff: ";
const static PROGMEM prog_uchar pds_hbp[] = "HBP Temp: ";
const static PROGMEM prog_uchar pds_tool0[] = "Tool0 Temp: ";
const static PROGMEM prog_uchar pds_extruder[] = "ExtrdrMM/s: ";
switch (index) {
case 0:
lcd.writeString((char *)profileName);
break;
case 2:
lcd.writeFromPgmspace(LOCALIZE(pds_xOffset));
lcd.writeFloat(stepperAxisStepsToMM(homeX, X_AXIS), 3);
break;
case 3:
lcd.writeFromPgmspace(LOCALIZE(pds_yOffset));
lcd.writeFloat(stepperAxisStepsToMM(homeY, Y_AXIS), 3);
break;
case 4:
lcd.writeFromPgmspace(LOCALIZE(pds_zOffset));
lcd.writeFloat(stepperAxisStepsToMM(homeZ, Z_AXIS), 3);
break;
case 5:
lcd.writeFromPgmspace(LOCALIZE(pds_hbp));
lcd.writeFloat((float)hbpTemp, 0);
break;
case 6:
lcd.writeFromPgmspace(LOCALIZE(pds_tool0));
lcd.writeFloat((float)tool0Temp, 0);
break;
case 7:
lcd.writeFromPgmspace(LOCALIZE(pds_extruder));
lcd.writeFloat((float)extruderMMS, 0);
break;
}
}
void ProfileDisplaySettingsMenu::handleSelect(uint8_t index) {
}
void CurrentPositionMode::reset() {
}
void CurrentPositionMode::update(LiquidCrystal& lcd, bool forceRedraw) {
uint8_t active_toolhead;
Point position = steppers::getStepperPosition(&active_toolhead);
if (forceRedraw) {
lcd.clearHomeCursor();
lcd.write('X');
lcd.setRow(1);
lcd.write('Y');
lcd.setRow(2);
lcd.write('Z');
lcd.setRow(3);
lcd.write('A' + active_toolhead);
}
lcd.write(':');
lcd.setCursor(3, 0);
lcd.writeFloat(stepperAxisStepsToMM(position[0], X_AXIS), 3);
lcd.writeFromPgmspace(LOCALIZE(units_mm));
lcd.setCursor(3, 1);
lcd.writeFloat(stepperAxisStepsToMM(position[1], Y_AXIS), 3);
lcd.writeFromPgmspace(LOCALIZE(units_mm));
lcd.setCursor(3, 2);
lcd.writeFloat(stepperAxisStepsToMM(position[2], Z_AXIS), 3);
lcd.writeFromPgmspace(LOCALIZE(units_mm));
lcd.setCursor(3, 3);
lcd.writeFloat(stepperAxisStepsToMM(position[3 + active_toolhead], A_AXIS + active_toolhead), 3);
lcd.writeFromPgmspace(LOCALIZE(units_mm));
}
void CurrentPositionMode::notifyButtonPressed(ButtonArray::ButtonName button) {
interface::popScreen();
}
//Unable to open file, filename too long?
UnableToOpenFileMenu::UnableToOpenFileMenu() {
itemCount = 4;
reset();
}
void UnableToOpenFileMenu::resetState() {
itemIndex = 3;
firstItemIndex = 3;
}
void UnableToOpenFileMenu::drawItem(uint8_t index, LiquidCrystal& lcd) {
const static PROGMEM prog_uchar utof_msg1[] = "Failed to open";
const static PROGMEM prog_uchar utof_msg2[] = "file or folder.";
const static PROGMEM prog_uchar utof_msg3[] = "Name too long?";
const static PROGMEM prog_uchar utof_cont[] = "Continue";
switch (index) {
case 0:
lcd.writeFromPgmspace(LOCALIZE(utof_msg1));
break;
case 1:
lcd.writeFromPgmspace(LOCALIZE(utof_msg2));
break;
case 2:
lcd.writeFromPgmspace(LOCALIZE(utof_msg3));
break;
case 3:
lcd.writeFromPgmspace(LOCALIZE(utof_cont));
break;
}
}
void UnableToOpenFileMenu::handleSelect(uint8_t index) {
interface::popScreen();
}
void AcceleratedSettingsMode::reset() {
cli();
values[0] = eeprom::getEepromUInt32(eeprom::ACCEL_MAX_ACCELERATION_X, EEPROM_DEFAULT_ACCEL_MAX_ACCELERATION_X);
values[1] = eeprom::getEepromUInt32(eeprom::ACCEL_MAX_ACCELERATION_Y, EEPROM_DEFAULT_ACCEL_MAX_ACCELERATION_Y);
values[2] = eeprom::getEepromUInt32(eeprom::ACCEL_MAX_ACCELERATION_Z, EEPROM_DEFAULT_ACCEL_MAX_ACCELERATION_Z);
values[3] = eeprom::getEepromUInt32(eeprom::ACCEL_MAX_ACCELERATION_A, EEPROM_DEFAULT_ACCEL_MAX_ACCELERATION_A);
values[4] = eeprom::getEepromUInt32(eeprom::ACCEL_MAX_ACCELERATION_B, EEPROM_DEFAULT_ACCEL_MAX_ACCELERATION_B);
// values[5] = eeprom::getEepromUInt32(eeprom::ACCEL_MAX_EXTRUDER_NORM, EEPROM_DEFAULT_ACCEL_MAX_EXTRUDER_NORM);
// values[6] = eeprom::getEepromUInt32(eeprom::ACCEL_MAX_EXTRUDER_RETRACT, EEPROM_DEFAULT_ACCEL_MAX_EXTRUDER_RETRACT);
values[5] = eeprom::getEepromUInt32(eeprom::ACCEL_ADVANCE_K, EEPROM_DEFAULT_ACCEL_ADVANCE_K);
values[6] = eeprom::getEepromUInt32(eeprom::ACCEL_ADVANCE_K2, EEPROM_DEFAULT_ACCEL_ADVANCE_K2);
values[7] = eeprom::getEepromUInt32(eeprom::ACCEL_EXTRUDER_DEPRIME_A, EEPROM_DEFAULT_ACCEL_EXTRUDER_DEPRIME_A);
values[8] = eeprom::getEepromUInt32(eeprom::ACCEL_EXTRUDER_DEPRIME_B, EEPROM_DEFAULT_ACCEL_EXTRUDER_DEPRIME_B);
values[9] = (uint32_t)(eeprom::getEeprom8(eeprom::ACCEL_SLOWDOWN_FLAG, EEPROM_DEFAULT_ACCEL_SLOWDOWN_FLAG)) ? 1 : 0;
values[10] = eeprom::getEepromUInt32(eeprom::ACCEL_MAX_SPEED_CHANGE_X, EEPROM_DEFAULT_ACCEL_MAX_SPEED_CHANGE_X);
values[11] = eeprom::getEepromUInt32(eeprom::ACCEL_MAX_SPEED_CHANGE_Y, EEPROM_DEFAULT_ACCEL_MAX_SPEED_CHANGE_Y);
values[12] = eeprom::getEepromUInt32(eeprom::ACCEL_MAX_SPEED_CHANGE_Z, EEPROM_DEFAULT_ACCEL_MAX_SPEED_CHANGE_Z);
values[13] = eeprom::getEepromUInt32(eeprom::ACCEL_MAX_SPEED_CHANGE_A, EEPROM_DEFAULT_ACCEL_MAX_SPEED_CHANGE_A);
values[14] = eeprom::getEepromUInt32(eeprom::ACCEL_MAX_SPEED_CHANGE_B, EEPROM_DEFAULT_ACCEL_MAX_SPEED_CHANGE_B);
sei();
lastAccelerateSettingsState= AS_NONE;
accelerateSettingsState= AS_MAX_ACCELERATION_X;
}
void AcceleratedSettingsMode::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar as_message1xMaxAccelRate[] = "X Max Accel:";
const static PROGMEM prog_uchar as_message1yMaxAccelRate[] = "Y Max Accel:";
const static PROGMEM prog_uchar as_message1zMaxAccelRate[] = "Z Max Accel:";
const static PROGMEM prog_uchar as_message1aMaxAccelRate[] = "Right Max Accel:";
const static PROGMEM prog_uchar as_message1bMaxAccelRate[] = "Left Max Accel:";
// const static PROGMEM prog_uchar as_message1ExtruderNorm[] = "Max Accel:";
// const static PROGMEM prog_uchar as_message1ExtruderRetract[] = "Max Accel Extdr:";
const static PROGMEM prog_uchar as_message1AdvanceK[] = "JKN Advance K:";
const static PROGMEM prog_uchar as_message1AdvanceK2[] = "JKN Advance K2:";
const static PROGMEM prog_uchar as_message1ExtruderDeprimeA[] = "Extdr.DeprimeR:";
const static PROGMEM prog_uchar as_message1ExtruderDeprimeB[] = "Extdr.DeprimeL:";
const static PROGMEM prog_uchar as_message1SlowdownLimit[] = "SlowdownEnabled:";
const static PROGMEM prog_uchar as_message1MaxSpeedChangeX[] = "MaxSpeedChangeX:";
const static PROGMEM prog_uchar as_message1MaxSpeedChangeY[] = "MaxSpeedChangeY:";
const static PROGMEM prog_uchar as_message1MaxSpeedChangeZ[] = "MaxSpeedChangeZ:";
const static PROGMEM prog_uchar as_message1MaxSpeedChangeA[] = "MaxSpeedChangeR:";
const static PROGMEM prog_uchar as_message1MaxSpeedChangeB[] = "MaxSpeedChangeL:";
const static PROGMEM prog_uchar as_blank[] = " ";
if ( accelerateSettingsState != lastAccelerateSettingsState ) forceRedraw = true;
if (forceRedraw) {
lcd.clearHomeCursor();
const prog_uchar *msg;
switch(accelerateSettingsState) {
case AS_MAX_ACCELERATION_X:
msg = LOCALIZE(as_message1xMaxAccelRate);
break;
case AS_MAX_ACCELERATION_Y:
msg = LOCALIZE(as_message1yMaxAccelRate);
break;
case AS_MAX_ACCELERATION_Z:
msg = LOCALIZE(as_message1zMaxAccelRate);
break;
case AS_MAX_ACCELERATION_A:
msg = LOCALIZE(as_message1aMaxAccelRate);
break;
case AS_MAX_ACCELERATION_B:
msg = LOCALIZE(as_message1bMaxAccelRate);
break;
// case AS_MAX_EXTRUDER_NORM:
// msg = LOCALIZE(as_message1ExtruderNorm);
// break;
// case AS_MAX_EXTRUDER_RETRACT:
// msg = LOCALIZE(as_message1ExtruderRetract);
// break;
case AS_ADVANCE_K:
msg = LOCALIZE(as_message1AdvanceK);
break;
case AS_ADVANCE_K2:
msg = LOCALIZE(as_message1AdvanceK2);
break;
case AS_EXTRUDER_DEPRIME_A:
msg = LOCALIZE(as_message1ExtruderDeprimeA);
break;
case AS_EXTRUDER_DEPRIME_B:
msg = LOCALIZE(as_message1ExtruderDeprimeB);
break;
case AS_SLOWDOWN_FLAG:
msg = LOCALIZE(as_message1SlowdownLimit);
break;
case AS_MAX_SPEED_CHANGE_X:
msg = LOCALIZE(as_message1MaxSpeedChangeX);
break;
case AS_MAX_SPEED_CHANGE_Y:
msg = LOCALIZE(as_message1MaxSpeedChangeY);
break;
case AS_MAX_SPEED_CHANGE_Z:
msg = LOCALIZE(as_message1MaxSpeedChangeZ);
break;
case AS_MAX_SPEED_CHANGE_A:
msg = LOCALIZE(as_message1MaxSpeedChangeA);
break;
case AS_MAX_SPEED_CHANGE_B:
msg = LOCALIZE(as_message1MaxSpeedChangeB);
break;
default:
msg = 0;
break;
}
if ( msg ) lcd.writeFromPgmspace(msg);
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(updnset_msg));
}
uint32_t value = 0;
uint8_t currentIndex = accelerateSettingsState - AS_MAX_ACCELERATION_X;
value = values[currentIndex];
lcd.setRow(1);
switch(accelerateSettingsState) {
case AS_MAX_SPEED_CHANGE_X:
case AS_MAX_SPEED_CHANGE_Y:
case AS_MAX_SPEED_CHANGE_Z:
case AS_MAX_SPEED_CHANGE_A:
case AS_MAX_SPEED_CHANGE_B:
lcd.writeFloat((float)value / 10.0, 1);
break;
case AS_ADVANCE_K:
case AS_ADVANCE_K2:
lcd.writeFloat((float)value / 100000.0, 5);
break;
default:
lcd.writeFloat((float)value, 0);
break;
}
lcd.writeFromPgmspace(LOCALIZE(as_blank));
lastAccelerateSettingsState = accelerateSettingsState;
}
void AcceleratedSettingsMode::notifyButtonPressed(ButtonArray::ButtonName button) {
if (( accelerateSettingsState == AS_LAST_ENTRY ) && (button == ButtonArray::OK )) {
//Write the data
cli();
eeprom::putEepromUInt32(eeprom::ACCEL_MAX_ACCELERATION_X, values[0]);
eeprom::putEepromUInt32(eeprom::ACCEL_MAX_ACCELERATION_Y, values[1]);
eeprom::putEepromUInt32(eeprom::ACCEL_MAX_ACCELERATION_Z, values[2]);
eeprom::putEepromUInt32(eeprom::ACCEL_MAX_ACCELERATION_A, values[3]);
eeprom::putEepromUInt32(eeprom::ACCEL_MAX_ACCELERATION_B, values[4]);
// eeprom::putEepromUInt32(eeprom::ACCEL_MAX_EXTRUDER_NORM, values[5]);
// eeprom::putEepromUInt32(eeprom::ACCEL_MAX_EXTRUDER_RETRACT, values[6]);
eeprom::putEepromUInt32(eeprom::ACCEL_ADVANCE_K, values[5]);
eeprom::putEepromUInt32(eeprom::ACCEL_ADVANCE_K2, values[6]);
eeprom::putEepromUInt32(eeprom::ACCEL_EXTRUDER_DEPRIME_A, values[7]);
eeprom::putEepromUInt32(eeprom::ACCEL_EXTRUDER_DEPRIME_B, values[8]);
eeprom_write_byte((uint8_t*)eeprom::ACCEL_SLOWDOWN_FLAG,(uint8_t)values[9]);
eeprom::putEepromUInt32(eeprom::ACCEL_MAX_SPEED_CHANGE_X, values[10]);
eeprom::putEepromUInt32(eeprom::ACCEL_MAX_SPEED_CHANGE_Y, values[11]);
eeprom::putEepromUInt32(eeprom::ACCEL_MAX_SPEED_CHANGE_Z, values[12]);
eeprom::putEepromUInt32(eeprom::ACCEL_MAX_SPEED_CHANGE_A, values[13]);
eeprom::putEepromUInt32(eeprom::ACCEL_MAX_SPEED_CHANGE_B, values[14]);
sei();
host::stopBuildNow();
return;
}
uint8_t currentIndex = accelerateSettingsState - AS_MAX_ACCELERATION_X;
switch (button) {
case ButtonArray::CANCEL:
interface::popScreen();
break;
case ButtonArray::ZERO:
break;
case ButtonArray::OK:
accelerateSettingsState = (enum accelerateSettingsState)((uint8_t)accelerateSettingsState + 1);
return;
break;
case ButtonArray::ZPLUS:
// increment more
values[currentIndex] += 100;
break;
case ButtonArray::ZMINUS:
// decrement more
values[currentIndex] -= 100;
break;
case ButtonArray::YPLUS:
// increment less
values[currentIndex] += 1;
break;
case ButtonArray::YMINUS:
// decrement less
values[currentIndex] -= 1;
break;
default:
break;
}
//Settings that allow a zero value
if (!(
( accelerateSettingsState == AS_ADVANCE_K ) || ( accelerateSettingsState == AS_ADVANCE_K2 ) ||
( accelerateSettingsState == AS_EXTRUDER_DEPRIME_A ) || ( accelerateSettingsState == AS_EXTRUDER_DEPRIME_B ) ||
( accelerateSettingsState == AS_SLOWDOWN_FLAG ))) {
if ( values[currentIndex] < 1 ) values[currentIndex] = 1;
}
if ( values[currentIndex] > 200000 ) values[currentIndex] = 1;
//Settings that have a maximum value
if (( accelerateSettingsState == AS_SLOWDOWN_FLAG ) && ( values[currentIndex] > 1))
values[currentIndex] = 1;
}
void EndStopConfigScreen::reset() {
endstops = eeprom::getEeprom8(eeprom::ENDSTOPS_USED, EEPROM_DEFAULT_ENDSTOPS_USED);
}
void EndStopConfigScreen::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar esc_message1[] = "EndstopsPresent:";
const static PROGMEM prog_uchar esc_blank[] = " ";
if (forceRedraw) {
lcd.clearHomeCursor();
lcd.writeFromPgmspace(LOCALIZE(esc_message1));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(updnset_msg));
}
// Redraw tool info
lcd.setRow(1);
lcd.writeFloat((float)endstops, 0);
lcd.writeFromPgmspace(LOCALIZE(esc_blank));
}
void EndStopConfigScreen::notifyButtonPressed(ButtonArray::ButtonName button) {
switch (button) {
case ButtonArray::CANCEL:
interface::popScreen();
break;
case ButtonArray::ZERO:
break;
case ButtonArray::OK:
eeprom_write_byte((uint8_t *)eeprom::ENDSTOPS_USED, endstops);
interface::popScreen();
break;
case ButtonArray::ZPLUS:
// increment more
if (endstops <= 122) endstops += 5;
break;
case ButtonArray::ZMINUS:
// decrement more
if (endstops >= 5) endstops -= 5;
break;
case ButtonArray::YPLUS:
// increment less
if (endstops <= 126) endstops += 1;
break;
case ButtonArray::YMINUS:
// decrement less
if (endstops >= 1) endstops -= 1;
break;
default:
break;
}
}
void HomingFeedRatesMode::reset() {
cli();
homingFeedRate[0] = eeprom::getEepromUInt32(eeprom::HOMING_FEED_RATE_X, EEPROM_DEFAULT_HOMING_FEED_RATE_X);
homingFeedRate[1] = eeprom::getEepromUInt32(eeprom::HOMING_FEED_RATE_Y, EEPROM_DEFAULT_HOMING_FEED_RATE_Y);
homingFeedRate[2] = eeprom::getEepromUInt32(eeprom::HOMING_FEED_RATE_Z, EEPROM_DEFAULT_HOMING_FEED_RATE_Z);
sei();
lastHomingFeedRateState = HFRS_NONE;
homingFeedRateState = HFRS_OFFSET_X;
}
void HomingFeedRatesMode::update(LiquidCrystal& lcd, bool forceRedraw) {
const static PROGMEM prog_uchar hfr_message1x[] = "X Home Feedrate:";
const static PROGMEM prog_uchar hfr_message1y[] = "Y Home Feedrate:";
const static PROGMEM prog_uchar hfr_message1z[] = "Z Home Feedrate:";
const static PROGMEM prog_uchar hfr_mm[] = "mm/min ";
if ( homingFeedRateState != lastHomingFeedRateState ) forceRedraw = true;
if (forceRedraw) {
lcd.clearHomeCursor();
switch(homingFeedRateState) {
case HFRS_OFFSET_X:
lcd.writeFromPgmspace(LOCALIZE(hfr_message1x));
break;
case HFRS_OFFSET_Y:
lcd.writeFromPgmspace(LOCALIZE(hfr_message1y));
break;
case HFRS_OFFSET_Z:
lcd.writeFromPgmspace(LOCALIZE(hfr_message1z));
break;
default:
break;
}
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(updnset_msg));
}
float feedRate = 0.0;
switch(homingFeedRateState) {
case HFRS_OFFSET_X:
feedRate = homingFeedRate[0];
break;
case HFRS_OFFSET_Y:
feedRate = homingFeedRate[1];
break;
case HFRS_OFFSET_Z:
feedRate = homingFeedRate[2];
break;
default:
break;
}
lcd.setRow(1);
lcd.writeFloat((float)feedRate, 0);
lcd.writeFromPgmspace(LOCALIZE(hfr_mm));
lastHomingFeedRateState = homingFeedRateState;
}
void HomingFeedRatesMode::notifyButtonPressed(ButtonArray::ButtonName button) {
if (( homingFeedRateState == HFRS_OFFSET_Z ) && (button == ButtonArray::OK )) {
//Write the new homing feed rates
cli();
eeprom::putEepromUInt32(eeprom::HOMING_FEED_RATE_X, homingFeedRate[0]);
eeprom::putEepromUInt32(eeprom::HOMING_FEED_RATE_Y, homingFeedRate[1]);
eeprom::putEepromUInt32(eeprom::HOMING_FEED_RATE_Z, homingFeedRate[2]);
sei();
interface::popScreen();
}
uint8_t currentIndex = homingFeedRateState - HFRS_OFFSET_X;
switch (button) {
case ButtonArray::CANCEL:
interface::popScreen();
break;
case ButtonArray::ZERO:
break;
case ButtonArray::OK:
if ( homingFeedRateState == HFRS_OFFSET_X ) homingFeedRateState = HFRS_OFFSET_Y;
else if ( homingFeedRateState == HFRS_OFFSET_Y ) homingFeedRateState = HFRS_OFFSET_Z;
break;
case ButtonArray::ZPLUS:
// increment more
homingFeedRate[currentIndex] += 20;
break;
case ButtonArray::ZMINUS:
// decrement more
if ( homingFeedRate[currentIndex] >= 21 )
homingFeedRate[currentIndex] -= 20;
break;
case ButtonArray::YPLUS:
// increment less
homingFeedRate[currentIndex] += 1;
break;
case ButtonArray::YMINUS:
// decrement less
if ( homingFeedRate[currentIndex] >= 2 )
homingFeedRate[currentIndex] -= 1;
break;
default:
break;
}
if (( homingFeedRate[currentIndex] < 1 ) || ( homingFeedRate[currentIndex] > 2000 ))
homingFeedRate[currentIndex] = 1;
}
#ifdef EEPROM_MENU_ENABLE
EepromMenu::EepromMenu() {
itemCount = 3;
reset();
}
void EepromMenu::resetState() {
itemIndex = 0;
firstItemIndex = 0;
safetyGuard = 0;
itemSelected = -1;
warningScreen = true;
}
void EepromMenu::update(LiquidCrystal& lcd, bool forceRedraw) {
if ( warningScreen ) {
if ( forceRedraw ) {
const static PROGMEM prog_uchar eeprom_msg1[] = "This menu can";
const static PROGMEM prog_uchar eeprom_msg2[] = "make your bot";
const static PROGMEM prog_uchar eeprom_msg3[] = "inoperable.";
const static PROGMEM prog_uchar eeprom_msg4[] = "Press Y+ to cont";
lcd.homeCursor();
lcd.writeFromPgmspace(LOCALIZE(eeprom_msg1));
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(eeprom_msg2));
lcd.setRow(2);
lcd.writeFromPgmspace(LOCALIZE(eeprom_msg3));
lcd.setRow(3);
lcd.writeFromPgmspace(LOCALIZE(eeprom_msg4));
}
}
else {
if ( itemSelected != -1 )
lcd.clearHomeCursor();
const static PROGMEM prog_uchar eeprom_message_dump[] = "Saving...";
const static PROGMEM prog_uchar eeprom_message_restore[] = "Restoring...";
switch ( itemSelected ) {
case 0: //Dump
//sdcard::forceReinit(); // to force return to / directory
if ( ! sdcard::fileExists(dumpFilename) ) {
lcd.writeFromPgmspace(LOCALIZE(eeprom_message_dump));
if ( ! eeprom::saveToSDFile(dumpFilename) )
timedMessage(lcd, 1);
} else
timedMessage(lcd, 2);
interface::popScreen();
break;
case 1: //Restore
//sdcard::forceReinit(); // to return to root
if ( sdcard::fileExists(dumpFilename) ) {
lcd.writeFromPgmspace(LOCALIZE(eeprom_message_restore));
if ( ! eeprom::restoreFromSDFile(dumpFilename) )
timedMessage(lcd, 3);
host::stopBuildNow();
} else {
timedMessage(lcd, 4);
interface::popScreen();
}
break;
case 2: //Erase
timedMessage(lcd, 5);
eeprom::erase();
interface::popScreen();
host::stopBuildNow();
break;
default:
Menu::update(lcd, forceRedraw);
break;
}
lcd.setRow(3);
if ( safetyGuard >= 1 ) {
const static PROGMEM prog_uchar eeprom_msg9[] = "* Press ";
const static PROGMEM prog_uchar eeprom_msg10[] = "x more!";
lcd.writeFromPgmspace(LOCALIZE(eeprom_msg9));
lcd.writeInt((uint16_t)(4-safetyGuard),1);
lcd.writeFromPgmspace(LOCALIZE(eeprom_msg10));
} else {
const static PROGMEM prog_uchar eeprom_blank[] = " ";
lcd.writeFromPgmspace(LOCALIZE(eeprom_blank));
}
itemSelected = -1;
}
}
void EepromMenu::drawItem(uint8_t index, LiquidCrystal& lcd) {
const static PROGMEM prog_uchar e_message_dump[] = "EEPROM -> SD";
const static PROGMEM prog_uchar e_message_restore[] = "SD -> EEPROM";
const static PROGMEM prog_uchar e_message_erase[] = "Erase EEPROM";
switch (index)
{
case 0:
lcd.writeFromPgmspace(LOCALIZE(e_message_dump));
break;
case 1:
lcd.writeFromPgmspace(LOCALIZE(e_message_restore));
break;
case 2:
lcd.writeFromPgmspace(LOCALIZE(e_message_erase));
break;
}
}
void EepromMenu::handleSelect(uint8_t index) {
switch (index)
{
case 0:
//Dump
safetyGuard = 0;
itemSelected = 0;
break;
case 1:
//Restore
safetyGuard ++;
if ( safetyGuard > 3 ) {
safetyGuard = 0;
itemSelected = 1;
}
break;
case 2:
//Erase
safetyGuard ++;
if ( safetyGuard > 3 ) {
safetyGuard = 0;
itemSelected = 2;
}
break;
}
}
void EepromMenu::notifyButtonPressed(ButtonArray::ButtonName button) {
if ( warningScreen ) {
if ( button == ButtonArray::YPLUS )
warningScreen = false;
else
Menu::notifyButtonPressed(ButtonArray::CANCEL);
return;
}
if ( button == ButtonArray::YMINUS || button == ButtonArray::ZMINUS ||
button == ButtonArray::YPLUS || button == ButtonArray::ZPLUS )
safetyGuard = 0;
Menu::notifyButtonPressed(button);
}
#endif
// Clear the screen, display a message, and then count down from 5 to 0 seconds
// with a countdown timer to let folks know what's up
static void timedMessage(LiquidCrystal& lcd, uint8_t which)
{
const static PROGMEM prog_uchar sderr_badcard[] = "SD card error";
const static PROGMEM prog_uchar sderr_nofiles[] = "No files found";
const static PROGMEM prog_uchar sderr_nocard[] = "No SD card";
const static PROGMEM prog_uchar sderr_initfail[] = "Card init failed";
const static PROGMEM prog_uchar sderr_partition[] = "Bad partition";
const static PROGMEM prog_uchar sderr_filesys[] = "Is it FAT-16?";
const static PROGMEM prog_uchar sderr_noroot[] = "No root folder";
const static PROGMEM prog_uchar sderr_locked[] = "Read locked";
const static PROGMEM prog_uchar sderr_fnf[] = "File not found";
const static PROGMEM prog_uchar sderr_toobig[] = "Too big";
const static PROGMEM prog_uchar sderr_crcerr[] = "CRC error";
const static PROGMEM prog_uchar sderr_comms[] = "Comms failure";
const static PROGMEM prog_uchar eeprom_msg11[] = "Write Failed!";
const static PROGMEM prog_uchar eeprom_msg12[] = "File exists!";
const static PROGMEM prog_uchar eeprom_msg5[] = "Read Failed!";
const static PROGMEM prog_uchar eeprom_msg6[] = "EEPROM may be";
const static PROGMEM prog_uchar eeprom_msg7[] = "corrupt";
const static PROGMEM prog_uchar eeprom_msg8[] = "File not found!";
const static PROGMEM prog_uchar eeprom_message_erase[] = "Erasing...";
const static PROGMEM prog_uchar eeprom_message_error[] = "Error";
const static PROGMEM prog_uchar timed_message_clock[] = "00:00";
lcd.clearHomeCursor();
switch(which) {
case 0:
{
lcd.writeFromPgmspace(LOCALIZE(sderr_badcard));
const prog_uchar *msg = 0;
if ( sdcard::sdErrno == SDR_ERR_BADRESPONSE ||
sdcard::sdErrno == SDR_ERR_COMMS ||
sdcard::sdErrno == SDR_ERR_PATTERN ||
sdcard::sdErrno == SDR_ERR_VOLTAGE )
msg = LOCALIZE(sderr_comms);
else {
switch (sdcard::sdAvailable) {
case sdcard::SD_SUCCESS: msg = LOCALIZE(sderr_nofiles); break;
case sdcard::SD_ERR_NO_CARD_PRESENT: msg = LOCALIZE(sderr_nocard); break;
case sdcard::SD_ERR_INIT_FAILED: msg = LOCALIZE(sderr_initfail); break;
case sdcard::SD_ERR_PARTITION_READ: msg = LOCALIZE(sderr_partition); break;
case sdcard::SD_ERR_OPEN_FILESYSTEM: msg = LOCALIZE(sderr_filesys); break;
case sdcard::SD_ERR_NO_ROOT: msg = LOCALIZE(sderr_noroot); break;
case sdcard::SD_ERR_CARD_LOCKED: msg = LOCALIZE(sderr_locked); break;
case sdcard::SD_ERR_FILE_NOT_FOUND: msg = LOCALIZE(sderr_fnf); break;
case sdcard::SD_ERR_VOLUME_TOO_BIG: msg = LOCALIZE(sderr_toobig); break;
case sdcard::SD_ERR_CRC: msg = LOCALIZE(sderr_crcerr); break;
default:
case sdcard::SD_ERR_GENERIC:
break;
}
}
if ( msg ) {
lcd.setRow(1);
lcd.writeFromPgmspace(msg);
}
break;
}
case 1:
lcd.writeFromPgmspace(LOCALIZE(eeprom_msg11));
break;
case 2:
lcd.writeFromPgmspace(LOCALIZE(eeprom_message_error));
lcd.setRow(1);
lcd.writeString((char *)dumpFilename);
lcd.setRow(2);
lcd.writeFromPgmspace(LOCALIZE(eeprom_msg12));
break;
case 3:
lcd.writeFromPgmspace(LOCALIZE(eeprom_msg5));
lcd.setRow(1);
lcd.writeFromPgmspace(LOCALIZE(eeprom_msg6));
lcd.setRow(2);
lcd.writeFromPgmspace(LOCALIZE(eeprom_msg7));
break;
case 4:
lcd.writeFromPgmspace(LOCALIZE(eeprom_message_error));
lcd.setRow(1);
lcd.writeString((char *)dumpFilename);
lcd.setRow(2);
lcd.writeFromPgmspace(LOCALIZE(eeprom_msg8));
break;
case 5:
lcd.writeFromPgmspace(LOCALIZE(eeprom_message_erase));
break;
}
lcd.setRow(3);
lcd.writeFromPgmspace(timed_message_clock);
for (uint8_t i = 0; i < 5; i++)
{
lcd.setCursor(4, 3);
lcd.write('5' - (char)i);
_delay_us(1000000);
}
}
#endif
| 28.864957 | 153 | 0.699448 |
2391143015ee1a186b38b61808b1634761594d42 | 405 | cpp | C++ | Palindrome.cpp | nishijjain/cpp-codes | 4b179e0531fcd91161486e0157596b8727ad562d | [
"MIT"
] | null | null | null | Palindrome.cpp | nishijjain/cpp-codes | 4b179e0531fcd91161486e0157596b8727ad562d | [
"MIT"
] | null | null | null | Palindrome.cpp | nishijjain/cpp-codes | 4b179e0531fcd91161486e0157596b8727ad562d | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main() {
int n, num, digit,r=0;
cout<<"Enter the number : ";
cin>>num;
n = num;
while(num != 0) {
digit = num%10;
r = (r*10) + digit;
num = num/10;
}
if(n == r)
cout<<"The given number is a palindrome number";
else
cout<<"The given number is not a palindrome number";
return 0;
} | 21.315789 | 60 | 0.516049 |
23930b18119937fc7644d72e096d087022e91ab1 | 864 | cpp | C++ | src/gfxtk/Buffer.cpp | NostalgicGhoul/gfxtk | 6662d6d1b285e20806ecfef3cdcb620d6605e478 | [
"BSD-2-Clause"
] | null | null | null | src/gfxtk/Buffer.cpp | NostalgicGhoul/gfxtk | 6662d6d1b285e20806ecfef3cdcb620d6605e478 | [
"BSD-2-Clause"
] | null | null | null | src/gfxtk/Buffer.cpp | NostalgicGhoul/gfxtk | 6662d6d1b285e20806ecfef3cdcb620d6605e478 | [
"BSD-2-Clause"
] | null | null | null | #include "Buffer.hpp"
#ifdef GFXTK_GRAPHICS_BACKEND_VULKAN
#include <gfxtk/backend/vulkan/Buffer.hpp>
#elif GFXTK_GRAPHICS_BACKEND_METAL
#include <gfxtk/backend/metal/Buffer.hpp>
#else
#error target OS is not supported by any existing graphics backend!
#endif
gfxtk::Buffer gfxtk::Buffer::create(
std::shared_ptr<backend::Device> const& backendDevice,
size_t size,
gfxtk::BufferUsageFlags bufferUsageFlags,
gfxtk::MemoryUsage memoryUsage
) {
return Buffer(backend::Buffer::create(backendDevice, size, bufferUsageFlags, memoryUsage));
}
gfxtk::Buffer::Buffer(std::shared_ptr<backend::Buffer> backendBuffer)
: _backendBuffer(std::move(backendBuffer)) {}
gfxtk::Buffer::~Buffer() = default;
void* gfxtk::Buffer::map() {
return _backendBuffer->map();
}
void gfxtk::Buffer::unmap() {
_backendBuffer->unmap();
}
| 27 | 95 | 0.726852 |
2393d38d4a5a137d14b49a994ed5ea0b6f9fe7fa | 2,091 | hpp | C++ | obs-studio/UI/window-basic-main-outputs.hpp | noelemahcz/libobspp | 029472b973e5a1985f883242f249848385df83a3 | [
"MIT"
] | null | null | null | obs-studio/UI/window-basic-main-outputs.hpp | noelemahcz/libobspp | 029472b973e5a1985f883242f249848385df83a3 | [
"MIT"
] | null | null | null | obs-studio/UI/window-basic-main-outputs.hpp | noelemahcz/libobspp | 029472b973e5a1985f883242f249848385df83a3 | [
"MIT"
] | null | null | null | #pragma once
#include <string>
class OBSBasic;
struct BasicOutputHandler {
OBSOutputAutoRelease fileOutput;
OBSOutputAutoRelease streamOutput;
OBSOutputAutoRelease replayBuffer;
OBSOutputAutoRelease virtualCam;
bool streamingActive = false;
bool recordingActive = false;
bool delayActive = false;
bool replayBufferActive = false;
bool virtualCamActive = false;
OBSBasic *main;
std::string outputType;
std::string lastError;
std::string lastRecordingPath;
OBSSignal startRecording;
OBSSignal stopRecording;
OBSSignal startReplayBuffer;
OBSSignal stopReplayBuffer;
OBSSignal startStreaming;
OBSSignal stopStreaming;
OBSSignal startVirtualCam;
OBSSignal stopVirtualCam;
OBSSignal streamDelayStarting;
OBSSignal streamStopping;
OBSSignal recordStopping;
OBSSignal replayBufferStopping;
OBSSignal replayBufferSaved;
inline BasicOutputHandler(OBSBasic *main_);
virtual ~BasicOutputHandler(){};
virtual bool SetupStreaming(obs_service_t *service) = 0;
virtual bool StartStreaming(obs_service_t *service) = 0;
virtual bool StartRecording() = 0;
virtual bool StartReplayBuffer() { return false; }
virtual bool StartVirtualCam();
virtual void StopStreaming(bool force = false) = 0;
virtual void StopRecording(bool force = false) = 0;
virtual void StopReplayBuffer(bool force = false) { (void)force; }
virtual void StopVirtualCam();
virtual bool StreamingActive() const = 0;
virtual bool RecordingActive() const = 0;
virtual bool ReplayBufferActive() const { return false; }
virtual bool VirtualCamActive() const;
virtual void Update() = 0;
virtual void SetupOutputs() = 0;
inline bool Active() const
{
return streamingActive || recordingActive || delayActive ||
replayBufferActive || virtualCamActive;
}
protected:
void SetupAutoRemux(const char *&ext);
std::string GetRecordingFilename(const char *path, const char *ext,
bool noSpace, bool overwrite,
const char *format, bool ffmpeg);
};
BasicOutputHandler *CreateSimpleOutputHandler(OBSBasic *main);
BasicOutputHandler *CreateAdvancedOutputHandler(OBSBasic *main);
| 28.256757 | 68 | 0.780966 |
239529e3a0656005ba014a4ca0e76a86b1b2136a | 646 | cpp | C++ | mrJudge/problems/countfishes (197)/countfishes.cpp | object-oriented-human/competitive | 9e761020e887d8980a39a64eeaeaa39af0ecd777 | [
"MIT"
] | 1 | 2022-02-21T15:43:01.000Z | 2022-02-21T15:43:01.000Z | mrJudge/problems/countfishes (197)/countfishes.cpp | foooop/competitive | 9e761020e887d8980a39a64eeaeaa39af0ecd777 | [
"MIT"
] | null | null | null | mrJudge/problems/countfishes (197)/countfishes.cpp | foooop/competitive | 9e761020e887d8980a39a64eeaeaa39af0ecd777 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false); cin.tie(0);
int tc, inf=1000001; cin >> tc;
vector<int> isprime(inf, 1), prefix(inf);
for (int i = 2; i*i < inf; i++) {
if (isprime[i]) {
for (int j = i*i; j < inf; j+= i) {
isprime[j] = 0;
}
}
}
prefix[0] = 0, prefix[1] = 0;
for (int i = 2; i < inf; i++) {
prefix[i] = prefix[i-1];
if (isprime[i]) {
prefix[i]++;
}
}
while (tc--) {
int p, q; cin >> p >> q;
cout << prefix[q] - prefix[p-1] << '\n';
}
} | 21.533333 | 48 | 0.410217 |
239935d93d4706e23409398c03caf909a98d3cea | 879 | cpp | C++ | atcoder/abc147c.cpp | sogapalag/problems | 0ea7d65448e1177f8b3f81124a82d187980d659c | [
"MIT"
] | 1 | 2020-04-04T14:56:12.000Z | 2020-04-04T14:56:12.000Z | atcoder/abc147c.cpp | sogapalag/problems | 0ea7d65448e1177f8b3f81124a82d187980d659c | [
"MIT"
] | null | null | null | atcoder/abc147c.cpp | sogapalag/problems | 0ea7d65448e1177f8b3f81124a82d187980d659c | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
void solve() {
int n; cin >> n;
vector<vector<pair<int,int>>> g(n);
for (int i = 0; i < n; i++) {
int m; cin >> m;
for (int _ = 0; _ < m; _++) {
int x, y;
cin >> x >> y;
x--;
g[i].emplace_back(x,y);
}
}
const int MSK = 1<<n;
int res = 0;
for (int msk = 0; msk < MSK; msk++) {
for (int i = 0; i < n; i++) {
if (msk & (1<<i)) {
for (auto& _: g[i]) {
int j, y;
tie(j, y) = _;
if (((msk>>j)&1) != y) goto end;
}
}
}
res = max(res, __builtin_popcount(msk));
end:;
}
cout << res;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
solve();
cout << endl;
}
| 20.44186 | 52 | 0.366325 |
2399e24ba2dbf07647952ce82ee88f98e7b1095d | 6,547 | cpp | C++ | src/structs.cpp | Algorithms-and-Data-Structures-2021/classwork-02-cpp-basics-demo | dccf30fd03a7ed4e8e68f85c395f786a643ea3db | [
"MIT"
] | null | null | null | src/structs.cpp | Algorithms-and-Data-Structures-2021/classwork-02-cpp-basics-demo | dccf30fd03a7ed4e8e68f85c395f786a643ea3db | [
"MIT"
] | null | null | null | src/structs.cpp | Algorithms-and-Data-Structures-2021/classwork-02-cpp-basics-demo | dccf30fd03a7ed4e8e68f85c395f786a643ea3db | [
"MIT"
] | 3 | 2021-03-10T06:20:27.000Z | 2021-03-17T05:53:36.000Z | #include <iostream> // cout
// Подключаем свой заголовочный файл -
// целью заголовочных файлов является удобное хранение набора объявлений
// для их последующего использования в других программах.
// поиск заголовочного файла осуществляется в папках проекта (а не в системных директориях)
#include "structs.hpp"
// директива #pragma once (см. заголовочный файл) не позволит повторно подключить заголовочный файл
// поэтому, повторный include просто не сработает
#include "structs.hpp"
using namespace std;
int main() {
{
Student student; // { id = <мусор>, age = <мусор>, name = "", avg_score = <мусор> }
// инициализация структуры (aggregate initialization)
student = {0, 24, "Ramil Safin", 92.6};
// доступ к полям (оператор .)
const double avg_score = student.avg_score; // чтение
student.avg_score = avg_score - 0.3; // запись
// копирование
Student const student_copy = student; // { id = 0, age = 24, name = "Ramil Safin", avg_score = 92.3 }
// student_copy.name = ""; // <- ошибка компиляции
// указатель и ссылка
Student *ptr_to_student = &student;
// оператор обращения к полям структуры через указатель (->)
ptr_to_student->age = 32; // эквивалентно (*ptr_to_student).age = 32;
update_score(ptr_to_student, 86);
Student &ref_to_student = student;
// оператор обращения к полям . (точка)
ref_to_student.age += 1;
update_score(ref_to_student, 90);
print_details(ref_to_student /* ссылка на const */);
}
{ // конструкторы и деструкторы
{ // вошли в новую область видимости
University u1; // конструктор по-умолчанию (объект создается на стеке)
u1.~University(); // ручной вызов деструктора (объект НЕ удаляется со стека)
// здесь мы ещё можем продолжать использовать u1
} // вышли из области видимости => автоматический вызов деструктора u1
University u2("KFU"); // explicit конструктор по name
// University u2_str = string("KFU"); // <- ошибка компиляции (неявное приведение типа string к University)
University u2_str = static_cast<University>(string("KFU")); // явное приведение типа
University u3(1); // НЕ explicit конструктор по ranking
University u3_int = 1; // ОК, вызов конструктора с ranking (неявное преобразование типа int в University)
University u4("KFU", 1); // конструктор по name и ranking
}
{ // приватные/публичные поля и методы структуры
University uni; // вызов конструктора по-умолчанию (создание объекта класса uni)
// uni.name_ = ""; // <- ошибка компиляции (поле name_ приватное)
// для получения доступа к приватным полям используются публичные методы
string name = uni.GetName(); // копия поля name_
string &name_ref = uni.GetNameRef(); // ссылка на поле name_
name_ref = ""; // ОК, теперь uni.name_ = ""
uni.SetName("MSU");
string const &name_const_ref = uni.GetNameConstRef(); // ссылка на неизменяемое поле name_
// name_const_ref = ""; // <- ошибка компиляции
// вызов приватных функций - невозможен
// uni.private_function(); // <- ошибка компиляции
}
{ // неявный указатель this
University uni;
auto &this_ref = uni.GetThisRef();
// компилятор записывает строку кода выше примерно следующим образом:
// GetThisRef(&uni) - т.е. компилятор передает указатель на объект неявным аргументом
// Ex.: Python: self (явный), Java: this (неявный)
}
{ // статические методы и поля
int ID = University::ID; // получение значения статического поля структуры (объект не обязательно создавать)
int curr_id = University::CurrentID(); // вызов статического метода структуры
// можно получить доступ к публичному статическому полю и через объект
University u;
curr_id = u.ID;
}
{ // создание объектов структуры на куче, деструктор
auto *u_ptr = new University("KFU", 1);
string name = u_ptr->GetName();
delete u_ptr; // ручной вызов деструктора и освобождение памяти
} // при выходе из области видимости деструктор не вызовется (высвободится лишь память под указатель u_ptr)
return 0;
}
// определение функций, объявленных в заголовочном файле structs.hpp
void update_score(Student &student, double new_score) {
student.avg_score = new_score;
}
void update_score(Student *student, double new_score) {
student->avg_score = new_score;
}
void print_details(Student const &student) {
// student нужен только для чтения данных: id и пр.
std::cout << "Student: " << "ID = " << student.id << "\tName: " << student.name << endl;
}
// определение методов University из заголовочного файла
// <название структуры>::<название метода>(<параметры>) : <список инициализации полей> { <тело метода> }
// :: - оператор разрешение области, используется для идентификации и устранения неоднозначности идентификаторов
University::University(const string &name, int ranking) : name_{name}, ranking_{ranking} {
// генерация идентификатора на базе статического поля структуры
id_ = ID++; // эквивалентно: id_ = ID и ID += 1
}
int University::GetId() const {
// id_ = 0; // <- ошибка компиляции
return id_;
}
std::string University::GetName() const {
return name_;
}
int University::GetRanking() const {
return ranking_;
}
std::string &University::GetNameRef() /* const - нельзя, нет гарантии, что name_ не изменится */ {
// ranking_ = 0; // можно изменять поля объекта, но не стоит, это плохой код
return name_; // по ссылке можно будет изменять поле name_ у объекта типа University
}
std::string const &University::GetNameConstRef() const /* const - уже есть гарантии неизменности name_ */ {
// private_function(); // <- ошибка компиляции
private_const_function();
return name_;
}
University &University::GetThisRef() {
// std::string name = this->name_;
// эквивалентно: std::string name = name_;
return *this; // разыменуем указатель и получаем адрес объекта в памяти
// который можем вернуть как ссылку (можно и указатель вернуть)
}
void University::SetRanking(int ranking) {
ranking_ = ranking;
}
void University::SetName(const string &name) {
name_ = name;
}
void University::private_function() {
// блок кода
}
void University::private_const_function() const {
// блок кода
}
University::University(const std::string &name) : University(name, 0) {
std::cout << "explicit University(name)" << std::endl;
}
//University::University(const string &name)
| 31.781553 | 113 | 0.685352 |
239da9ca7eca15f56272f96c2085795d5c53472d | 308 | cpp | C++ | cpp/other/terminal_input.cpp | danyfang/SourceCode | 8168f6058648f2a330a7354daf3a73a4d8a4e730 | [
"MIT"
] | null | null | null | cpp/other/terminal_input.cpp | danyfang/SourceCode | 8168f6058648f2a330a7354daf3a73a4d8a4e730 | [
"MIT"
] | null | null | null | cpp/other/terminal_input.cpp | danyfang/SourceCode | 8168f6058648f2a330a7354daf3a73a4d8a4e730 | [
"MIT"
] | null | null | null | #include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main(){
string mystr;
float price;
cout << "enter price :" << endl;
getline(cin,mystr);
//cin.getline(mystr);
stringstream (mystr) >> price;
cout << "the price is:" << price << endl;
return 0;
} | 22 | 45 | 0.607143 |
239dfe62dd54c7c176526a8d355e463822fe0611 | 32,683 | cpp | C++ | sam/sam2016.cpp | leandrohga/cs4298_MacNCheese | 89e6b381341c5b647c98a0d84af6f71c57a4e147 | [
"Apache-2.0"
] | null | null | null | sam/sam2016.cpp | leandrohga/cs4298_MacNCheese | 89e6b381341c5b647c98a0d84af6f71c57a4e147 | [
"Apache-2.0"
] | null | null | null | sam/sam2016.cpp | leandrohga/cs4298_MacNCheese | 89e6b381341c5b647c98a0d84af6f71c57a4e147 | [
"Apache-2.0"
] | null | null | null | /* ____________________________________________________________________________
S A M 2 0 0 7
An Assembler for the MACC2 Virtual Computer
James L. Richards
Last Update: August 28, 2007
Last Update: January 2, 2016
by Marty J. Wolf
____________________________________________________________________________
*/
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string.h>
#include <vector>
#include <ctime>
#include <cstdlib>
#include <sstream>
#include <algorithm>
using namespace std;
const int MAXINT = 32767;
typedef unsigned char Byte;
typedef unsigned short Word;
enum OpKind {OIN, IA, IS, IM, IDENT, FN, FA, FS, FM, FD,
BI, BO, BA, IC, FC, JSR, BKT, LD, STO, LDA,
FLT, FIX, J, SR, SL, SRD, SLD, RD, WR, TRNG,
HALT, NOP, CLR, REALDIR, STRINGDIR, INTDIR,
SKIPDIR, LABELDIR};
enum ErrorKind {NO_ERROR, UNKNOWN_OP_NAME, BAD_REG_ADDR, BAD_GEN_ADDR,
BAD_INTEGER, BAD_REAL, BAD_STR, BAD_NAME, ILL_REG_ADDR,
ILL_MED_ADDR, BAD_SHFT_AMT, BAD_STRING, INVALID_NAME};
enum WarnKind {LONG_NAME, MISSING_R, MISSING_NUM, MISSING_RP,
MISSING_COMMA, NAME_DEFINED, BAD_SKIP, ESC_TOO_SHORT,
STR_TOO_SHORT, TEXT_FOLLOWS};
struct SymRec;
typedef SymRec* SymPtr;
struct SymRec
{
string id;
SymPtr left, right;
short patch, loc;
};
// GLOBAL VARIABLES
// ----------------
Word
Inop, Iaop, Isop, Imop, Idop, Fnop, Faop, Fsop, Fmop, Fdop,
Biop, Boop, Baop, Icop, Fcop, Jsrop, Bktop, Ldop, Stoop, Ldaop,
Fltop, Fixop, Jop, Srop, Slop, Rdop, Wrop, Trngop, Haltop;
string Source;
ifstream InFile;
ofstream ListFile;
bool Saved; // Flag for one character lookahead
char Ch; // Current character from the input
vector<Byte> Mem; // Memory Image being created
Word Lc; // Location Counter
ofstream MemFile; // File for the memory image
SymPtr Symbols;
int Line; // Number of the current input line
ErrorKind Error;
bool Errs;
bool Warning;
bool Morewarn;
WarnKind Warns[11];
int Windex;
string Arg,
Memfname,
Srcfname;
const Word BYTE_MASK = 0x00FF;
void WordToBytes(Word w, Byte& hiByte, Byte& loByte)
//
// Converts a word to two bytes.
//
{
loByte = Byte(w & BYTE_MASK);
hiByte = Byte((w >> 8) & BYTE_MASK);
}
void BytesToWord(Byte hiByte, Byte loByte, Word& w)
//
// Converts two bytes to a word.
{
w = (Word(hiByte) << 8) | Word(loByte);
}
void InsertMem(Word w)
//
// Puts one word into memory with the high byte first.
//
{
Byte loByte, hiByte;
WordToBytes(w, hiByte, loByte);
Mem.push_back(hiByte);
Mem.push_back(loByte);
Lc += 2;
}
void CheckTab(SymPtr cur)
//
// Checks for undefined symbols in the symbol table.
//
{
if (cur != NULL)
{
CheckTab(cur->left);
if (cur->loc < 0)
{
Warning = true;
ListFile << " WARNING -- " << cur->id << " Undefined"
<< endl;
cout << " WARNING -- " << cur->id << " Undefined"
<< endl;
}
CheckTab(cur->right);
}
}
void Warn(WarnKind w)
//
// Adds a warning to the list of warnings.
//
{
if (!Morewarn)
Windex = 1;
Morewarn = true;
Warns[Windex] = w;
Windex++;
}
void PrintWarn()
//
// Prints warning messages.
//
{
ListFile << "\n WARNING -- ";
cout << "\n WARNING -- ";
switch (Warns[1])
{
case TEXT_FOLLOWS:
ListFile << "Text follows instruction";
cout << "Text follows instruction";
break;
case ESC_TOO_SHORT:
ListFile <<
"Need 3 digits to specify an unprintable character";
cout << "Need 3 digits to specify an unprintable character";
break;
case STR_TOO_SHORT:
ListFile << "Missing \" in string";
cout << "Missing \" in string";
break;
case BAD_SKIP:
ListFile <<
"Skip value must be positive, skip directive ignored";
cout << "Skip value must be positive, skip directive ignored";
break;
case NAME_DEFINED:
ListFile <<
"Name already defined, earlier definition lost";
cout << "Name already defined, earlier definition lost";
break;
case LONG_NAME:
ListFile << "Name too long, only 7 characters used";
cout << "Name too long, only 7 characters used";
break;
case MISSING_R:
ListFile << "Missing R in Register Address";
cout << "Missing R in Register Address";
break;
case MISSING_NUM:
ListFile <<
"Missing Number in Register Address (0 assumed)";
cout << "Missing Number in Register Address (0 assumed)";
break;
case MISSING_RP:
ListFile << "Missing "" in Indexed Address";
cout << "Missing "" in Indexed Address";
break;
case MISSING_COMMA:
ListFile << "Missing ","";
cout << "Missing ","";
break;
default:;
}
ListFile << " on line " << Line << endl;
cout << " on line " << Line << endl;
for (int i = 2; i < Windex; i++)
Warns[i - 1] = Warns[i];
Windex--;
if (Windex <= 1)
Morewarn = false;
}
void InRegAddr (Word& w, int reg, int hbit)
//
// Insert a register address into a word
//
{
Word mask1 = 0xFFFF,
mask2 = 0xFFFF,
wreg;
wreg = Word(reg);
wreg <<= hbit - 3;
w &= ((mask1 << (hbit+1)) | (mask2 >> (19-hbit)));
w |= wreg;
}
bool Eoln(istream& in)
//
// Returns true iff the next in stream character is a new line
// character.
//
{
return (in.peek() == '\n');
}
void GetCh()
//
// Get a character from the input -- character may have been saved
//
{
if (!Saved)
{
if (InFile.eof())
Ch = '%';
else if (!Eoln(InFile))
{
do
{
InFile.get(Ch);
ListFile << Ch;
} while((Ch == ' ' || Ch == '\t') && !Eoln(InFile));
if (Ch == '%') // skip remainder of line
{
while (!Eoln(InFile))
{
InFile.get(Ch);
ListFile << Ch;
}
Ch = '%';
}
}
else
Ch = '%';
}
else
Saved = false;
}
void ScanName (string& id)
//
// Builds a label.
//
{
id = "";
while (id.length() < 7 && ((Ch >= 'A' && Ch <= 'Z')|| isdigit(Ch)))
{
id += Ch;
GetCh();
}
if ((Ch >= 'A' && Ch <= 'Z') || isdigit(Ch))
{
Warn(LONG_NAME);
while ((Ch >= 'A' && Ch <= 'Z') || isdigit(Ch))
GetCh();
}
Saved = true;
}
SymPtr FindName (const string& id)
//
// Returns a pointer to the symbol table record containing id
// or returns NULL pointer if id is not in the symbol table.
//
{
SymPtr temp;
bool found;
temp = Symbols;
found = false;
while (!found && (temp != NULL))
if (temp->id == id)
found = true;
else if (temp->id > id)
temp = temp->left;
else
temp = temp->right;
return temp;
}
SymPtr InName (const string& id)
//
// Inserts id into the symbol table and returns a pointer
// to its symbol table record.
//
{
SymPtr cur, prev;
cur = Symbols;
prev = NULL;
while (cur != NULL)
{
prev = cur;
if (cur->id > id)
cur = cur->left;
else
cur = cur->right;
}
cur = new SymRec;
cur->left = NULL;
cur->right = NULL;
cur->id = id;
if (prev == NULL)
Symbols = cur;
else if (prev->id > id)
prev->left = cur;
else
prev->right = cur;
return cur;
}
void ScanStr()
//
// Gets a quoted string from the input stream.
//
{
bool one;
int ival;
Byte byte1, byte2;
Word wf;
one = true;
GetCh();
if (Ch == '"')
{
if (!Eoln(InFile))
{
InFile.get(Ch);
ListFile << Ch;
}
while (Ch != '"' && !Eoln(InFile))
{
if (Ch == ':')
{
if (!Eoln(InFile))
{
InFile.get(Ch);
ListFile << Ch;
if (isdigit(Ch))
{
ival = int(Ch) - int('0');
if (!Eoln(InFile))
{
InFile.get(Ch);
ListFile << Ch;
if (isdigit(Ch))
{
ival = ival * 10
+ int(Ch) - int('0');
if (!Eoln(InFile))
{
InFile.get(Ch);
ListFile << Ch;
if (isdigit(Ch))
ival = ival * 10
+ int(Ch) - int('0');
else
Warn(ESC_TOO_SHORT);
}
else
Warn(ESC_TOO_SHORT);
}
else
Warn(ESC_TOO_SHORT);
}
else
Warn(ESC_TOO_SHORT);
Ch = char(ival);
}
}
else
Warn(ESC_TOO_SHORT);
}
if (one)
{
one = false;
byte1 = Byte(Ch);
}
else
{
one = true;
byte2 = Byte(Ch);
BytesToWord(byte1, byte2, wf);
InsertMem(wf);
}
if (!Eoln(InFile))
{
InFile.get(Ch);
ListFile << Ch;
}
}
if (one)
byte1 = Byte(0);
else
byte2 = Byte(0);
BytesToWord(byte1, byte2, wf);
InsertMem(wf);
if (Ch != '"')
Warn(STR_TOO_SHORT);
}
else
Error = BAD_STR;
}
void ScanReal (Word& w1, Word& w2)
//
// Gets a real number from the input stream.
//
{
union FloatRec
{
Byte b[4];
float rf;
};
FloatRec real;
float dval = 10.0f, rf = 0.0f;
bool neg = false;
real.rf = 0.0;
GetCh();
if (Ch == '-' || Ch == '+')
{
if (Ch == '-') neg = true;
GetCh();
}
while (isdigit(Ch))
{
real.rf = real.rf * 10 + int(Ch) - int('0');
GetCh();
}
if (Ch == '.')
{
GetCh();
while (isdigit(Ch))
{
real.rf = real.rf + (int(Ch) - int('0')) / dval;
dval = dval * 10.0f;
GetCh();
}
}
else
Saved = true;
if (neg) real.rf = -real.rf;
BytesToWord(real.b[3], real.b[2], w1);
BytesToWord(real.b[1], real.b[0], w2);
}
void ScanInt (Word& w)
//
// Gets an integer from the input stream.
//
{
int temp;
bool neg;
neg = false;
temp = 0;
GetCh();
if (Ch == '-' || Ch == '+')
{
if (Ch == '-')
neg = true;
GetCh();
}
while (isdigit(Ch))
{
temp = temp * 10 + int(Ch) - int('0');
GetCh();
}
Saved = true; // Note the lookahead.
if (neg)
temp = -temp;
if (temp > MAXINT || temp < -MAXINT-1)
Error = BAD_INTEGER;
else
w = Word(temp);
}
int GetRegAddr()
//
// Get a register address from the input stream.
//
{
int temp;
GetCh();
if (Ch == 'R')
GetCh();
else
Warn(MISSING_R);
if (isdigit(Ch))
{
temp = int(Ch) - int('0');
GetCh();
if (isdigit(Ch)) // check for two digits
temp = temp * 10 + int(Ch) - int('0');
else
Saved = true;
if (temp > 15)
Error = BAD_REG_ADDR;
}
else
Warn(MISSING_NUM);
return temp;
}
void GetGenAddr(OpKind op, Word& w1, Word& w2, bool& flag)
//
// Sets an addressing mode.
//
{
int reg;
string id;
SymPtr idrec;
flag = false;
GetCh();
if (Ch == '*')
{
w1 = w1 | 0x0040; // [6]
GetCh();
}
if (Ch >= 'A' && Ch <= 'Z' && Ch != 'R')
{
flag = true;
ScanName(id);
idrec = FindName(id);
if (idrec == NULL)
{
idrec = InName(id);
idrec->loc = -1;
idrec->patch = Lc + 2;
w2 = Word(-1);
}
else if (idrec->loc == -1)
{
w2 = Word(idrec->patch);
idrec->patch = Lc + 2;
}
else
w2 = Word(idrec->loc);
GetCh();
if (Ch == '(')
{
w1 = w1 | 0x0020; // [5]
reg = GetRegAddr();
if (Error == NO_ERROR)
{
InRegAddr(w1, reg, 3);
GetCh();
if (Ch != ')')
Warn(MISSING_RP);
}
}
else // Ch != ')'
w1 = w1 | 0x0010; // [4]
}
else if (isdigit(Ch))
{
Saved = true;
w1 = w1 | 0x0010; // [4]
flag = true;
ScanInt(w2);
}
else
switch (Ch)
{
case 'R': // direct register
flag = false;
Saved = true;
reg = GetRegAddr();
InRegAddr(w1, reg, 3);
if ((op == JSR || op == BKT || op == LDA || op == J)
&& !(w1 & 0x0040))
Error = ILL_REG_ADDR;
break;
case '#': // immediate
flag = true;
if (w1 & 0x0040)
Error = BAD_GEN_ADDR;
else if (op == FN || op == FA || op == FS|| op == FM
|| op == FD || op == FC || op == FIX
|| op == JSR || op == BKT || op == STO
|| op == J || op == RD || op == TRNG)
Error = ILL_MED_ADDR;
else if (w1 == (Wrop | 0x0080))
Error = ILL_MED_ADDR;
else if (w1 == (Wrop | 0x0480))
Error = ILL_MED_ADDR;
else
{
w1 = w1 | 0x0030; // [4, 5]
ScanInt(w2);
}
break;
case '-': case '+': // indexed
w1 = w1 | 0x0020; // [5]
flag = true;
if (Ch == '-')
Saved = true;
ScanInt(w2);
GetCh();
if (Ch == '(')
{
reg = GetRegAddr();
if (Error == NO_ERROR)
{
InRegAddr(w1, reg, 3);
GetCh();
if (Ch != ')')
Warn(MISSING_RP);
}
}
else // Ch != '('
Error = BAD_GEN_ADDR;
break;
case '&':
flag = true;
if (w1 & 0x0040) // [6]
Error = BAD_GEN_ADDR;
else
{
w1 = w1 | 0x0070; // [4, 5, 6]
ScanInt(w2);
}
break;
default:
Error = BAD_GEN_ADDR;
}
}
void GetBop (OpKind& op, Word& wd)
//
// Get an operator or directive name that begins with 'B'.
//
{
GetCh();
switch (Ch)
{
case 'A':
op = BA;
wd = Baop;
break;
case 'I':
op = BI;
wd = Biop;
break;
case 'K':
GetCh();
if (Ch == 'T')
{
op = BKT;
wd = Bktop;
}
else
Error = UNKNOWN_OP_NAME;
break;
case 'O':
op = BO;
wd = Boop;
break;
default:
// character does not legally follow `B'
Error = UNKNOWN_OP_NAME;
}
}
void GetFop (OpKind& op, Word& wd)
//
// Get an operator or directive name that begins with 'F'.
//
{
GetCh();
switch (Ch)
{
case 'A':
op = FA;
wd = Faop;
break;
case 'C':
op = FC;
wd = Fcop;
break;
case 'D':
op = FD;
wd = Fdop;
break;
case 'I':
GetCh();
if (Ch == 'X')
{
op = FIX;
wd = Fixop;
}
else
Error = UNKNOWN_OP_NAME;
break;
case 'L':
GetCh();
if (Ch == 'T')
{
op = FLT;
wd = Fltop;
}
else
Error = UNKNOWN_OP_NAME;
break;
case 'M':
op = FM;
wd = Fmop;
break;
case 'N':
op = FN;
wd = Fnop;
break;
case 'S':
op = FS;
wd = Fsop;
break;
default: // character does not legally follow `F'
Error = UNKNOWN_OP_NAME;
}
}
void GetIop (OpKind& op, Word& wd)
//
// Get an operator or directive name that begins with 'I'.
//
{
GetCh();
switch (Ch)
{
case 'A':
op = IA;
wd = Iaop;
break;
case 'C':
op = IC;
wd = Icop;
break;
case 'D':
op = IDENT;
wd = Idop;
break;
case 'M':
op = IM;
wd = Imop;
break;
case 'N':
GetCh();
if (Ch == 'T')
op = INTDIR;
else
{
op = OIN;
wd = Inop;
Saved = true;
}
break;
case 'S':
op = IS;
wd = Isop;
break;
default:
// character does not legally follow `I'
Error = UNKNOWN_OP_NAME;
}
}
void GetJop (OpKind& op, Word& wd)
//
// Get an operator or directive name that begins with 'J'.
//
{
GetCh();
op = J; // most are simple jumps--except JSR!!
switch (Ch)
{
case 'E':
GetCh();
if (Ch == 'Q')
wd = Jop | 0x0180; // [7, 8]
else
Error = UNKNOWN_OP_NAME;
break;
case 'G':
GetCh();
if (Ch == 'E')
wd = Jop | 0x0280; // [7, 9]
else if (Ch == 'T')
wd = Jop | 0x0300; // [8, 9]
else
Error = UNKNOWN_OP_NAME;
break;
case 'L':
GetCh();
if (Ch == 'E')
wd = Jop | 0x0100; // [8]
else if (Ch == 'T')
wd = Jop | 0x0080; // [7]
else
Error = UNKNOWN_OP_NAME;
break;
case 'M':
GetCh();
if (Ch == 'P')
wd = Jop;
else
Error = UNKNOWN_OP_NAME;
break;
case 'N':
GetCh();
if (Ch == 'E')
wd = Jop | 0x0200; // [9]
else
Error = UNKNOWN_OP_NAME;
break;
case 'S':
GetCh();
if (Ch == 'R')
{
op = JSR;
wd = Jsrop;
}
else
Error = UNKNOWN_OP_NAME;
break;
default:
//Ch not in ['E','G',...] }
Error = UNKNOWN_OP_NAME;
}
}
void GetLop(OpKind& op, Word& wd)
//
// Get an operator or directive name that begins with 'L'.
//
{
GetCh();
switch (Ch)
{
case 'A':
GetCh();
if (Ch == 'B')
{
GetCh();
if (Ch == 'E')
{
GetCh();
if (Ch == 'L')
op = LABELDIR;
else
Error = UNKNOWN_OP_NAME;
}
else
Error = UNKNOWN_OP_NAME;
}
else
Error = UNKNOWN_OP_NAME;
break;
case 'D':
GetCh();
if (Ch == 'A')
{
op = LDA;
wd = Ldaop;
}
else
{
op = LD;
wd = Ldop;
Saved = true;
}
break;
default:
Error = UNKNOWN_OP_NAME;
}
}
void GetRop (OpKind& op, Word& wd)
//
// Get an operator or directive name that begins with 'R'.
//
{
GetCh();
if (Ch == 'D')
{
op = RD;
GetCh();
switch (Ch)
{
case 'B':
GetCh();
if (Ch == 'D')
wd = Rdop | 0x0100; // [8]
else if (Ch == 'W')
wd = Rdop | 0x0180; // [7, 8]
else
Error = UNKNOWN_OP_NAME;
break;
case 'C':
GetCh();
if (Ch == 'H')
wd = Rdop | 0x0400; // [10]
else
Error = UNKNOWN_OP_NAME;
break;
case 'F':
wd = Rdop | 0x0080; // [7]
break;
case 'H':
GetCh();
if (Ch == 'D')
wd = Rdop | 0x0300; // [8, 9]
else if (Ch == 'W')
wd = Rdop | 0x0380; // [7, 8, 9]
else
Error = UNKNOWN_OP_NAME;
break;
case 'I':
wd = Rdop;
break;
case 'N':
GetCh();
if (Ch == 'L')
wd = Rdop | 0x0580; // [7, 8, 10]
else
Error = UNKNOWN_OP_NAME;
break;
case 'O':
GetCh();
if (Ch == 'D')
wd = Rdop | 0x0200; // [9]
else if (Ch == 'W')
wd = Rdop | 0x0280; // [7, 10]
else
Error = UNKNOWN_OP_NAME;
break;
case 'S':
GetCh();
if (Ch == 'T')
wd = Rdop | 0x0480; // [7, 10]
else
Error = UNKNOWN_OP_NAME;
break;
default:
// Ch not in ['B','C',...] }
Error = UNKNOWN_OP_NAME;
}
}
else if (Ch == 'E')
{
GetCh();
if (Ch == 'A')
{
GetCh();
if (Ch == 'L')
op = REALDIR;
else
Error = UNKNOWN_OP_NAME;
}
else // Ch != 'A'
Error = UNKNOWN_OP_NAME;
}
else // Ch != 'E'
Error = UNKNOWN_OP_NAME;
}
void GetSop (OpKind& op, Word& wd)
//
// Get an operator or directive name that begins with 'S'.
//
{
GetCh();
switch (Ch)
{
case 'K':
GetCh();
if (Ch == 'I')
{
GetCh();
if (Ch == 'P')
op = SKIPDIR;
else
Error = UNKNOWN_OP_NAME;
}
else // Ch != 'I'
Error = UNKNOWN_OP_NAME;
break;
case 'L':
GetCh();
op = SL;
switch (Ch)
{
case 'D':
GetCh();
op = SLD;
switch (Ch)
{
case 'C':
wd = Slop | 0x0070; // [4, 5, 6]
break;
case 'E':
wd = Slop | 0x0060; // [5, 6]
break;
case 'O':
wd = Slop | 0x0050; // [4, 6]
break;
case 'Z':
wd = Slop | 0x0040; // [6]
break;
default:
Error = UNKNOWN_OP_NAME;
}
break;
case 'C':
wd = Slop | 0x0030; // [4, 5]
break;
case 'E':
wd = Slop | 0x0020; // [5]
break;
case 'O':
wd = Slop | 0x0010; // [4]
break;
case 'Z':
wd = Slop;
break;
default:
Error = UNKNOWN_OP_NAME;
}
break;
case 'R':
GetCh();
op = SR;
switch (Ch)
{
case 'D':
GetCh();
op = SRD;
switch (Ch)
{
case 'C':
wd = Srop | 0x0070; // [4, 5, 6]
break;
case 'E':
wd = Srop | 0x0060; // [5, 6]
break;
case 'O':
wd = Srop | 0x0050; // [4, 6]
break;
case 'Z':
wd = Srop | 0x0040; // [6]
break;
default:
Error = UNKNOWN_OP_NAME;
}
break;
case 'C':
wd = Srop | 0x0030; // [4, 5]
break;
case 'E':
wd = Srop | 0x0020; // [5]
break;
case 'O':
wd = Srop | 0x0010; // [4]
break;
case 'Z':
wd = Srop;
break;
default:
Error = UNKNOWN_OP_NAME;
}
break;
case 'T':
GetCh();
if (Ch == 'O')
{
op = STO;
wd = Stoop;
}
else if (Ch == 'R')
{
GetCh();
if (Ch == 'I')
{
GetCh();
if (Ch == 'N')
{
GetCh();
if (Ch == 'G')
op = STRINGDIR;
else
Error = UNKNOWN_OP_NAME;
}
else // Ch != 'N'
Error = UNKNOWN_OP_NAME;
}
else // Ch != 'I'
Error = UNKNOWN_OP_NAME;
}
else // Ch != 'R'
Error = UNKNOWN_OP_NAME;
break;
default:
Error = UNKNOWN_OP_NAME;
}
}
void GetWop (OpKind& op, Word& wd)
//
// Get an operator or directive name that begins with 'W'.
//
{
GetCh();
if (Ch == 'R')
{
op = WR;
GetCh();
switch (Ch)
{
case 'B':
GetCh();
if (Ch == 'D')
wd = Wrop | 0x0100; // WRBD
else if (Ch == 'W')
wd = Wrop | 0x0180; // WRBW
else
Error = UNKNOWN_OP_NAME;
break;
case 'C':
GetCh();
if (Ch == 'H')
wd = Wrop | 0x0400; // WRCH
else
Error = UNKNOWN_OP_NAME;
break;;
case 'F':
wd = Wrop | 0x0080; // WRF
break;
case 'H':
GetCh();
if (Ch == 'D')
wd = Wrop | 0x0300; // WRHD
else if (Ch == 'W')
wd = Wrop | 0x0380; // WRHW
else
Error = UNKNOWN_OP_NAME;
break;
case 'I': // WRI
wd = Wrop;
break;
case 'N':
GetCh();
if (Ch == 'L')
wd = Wrop | 0x0580; // WRNL
else
Error = UNKNOWN_OP_NAME;
break;
case 'O':
GetCh();
if (Ch == 'D')
wd = Wrop | 0x0200; // WROD
else if (Ch == 'W')
wd = Wrop | 0x0280; // WROW
else
Error = UNKNOWN_OP_NAME;
break;
case 'S':
GetCh();
if (Ch == 'T')
wd = Wrop | 0x0480; // WRST
else
Error = UNKNOWN_OP_NAME;
break;
default:
Error = UNKNOWN_OP_NAME;
}
}
else // Ch != 'R'
Error = UNKNOWN_OP_NAME;
}
void ProLine()
//
// Process the current line of input.
//
{
Word wd = 0, wd2;
Byte b1, b2;
OpKind op;
int reg;
bool twowds;
short i1, i2;
string id;
SymPtr idrec;
twowds = false;
Error = NO_ERROR;
switch (Ch)
{
case 'B':
GetBop(op, wd);
break;
case 'C':
GetCh();
if (Ch == 'L')
{
GetCh();
if (Ch == 'R')
{
op = CLR;
wd = Srop;
}
else // Ch != 'R'
Error = UNKNOWN_OP_NAME;
}
else // Ch != 'L'
Error = UNKNOWN_OP_NAME;
break;
case 'F':
GetFop(op, wd);
break;
case 'H':
GetCh();
if (Ch == 'A')
{
GetCh();
if (Ch == 'L')
{
GetCh();
if (Ch == 'T')
{
op = HALT;
wd = Haltop;
}
else // Ch != 'T'
Error = UNKNOWN_OP_NAME;
}
else // Ch != 'L'
Error = UNKNOWN_OP_NAME;
}
else // Ch != 'A'
Error = UNKNOWN_OP_NAME;
break;
case 'I':
GetIop(op, wd);
break;
case 'J':
GetJop(op, wd);
break;
case 'L':
GetLop(op, wd);
break;
case 'N':
GetCh();
if (Ch == 'O')
{
GetCh();
if (Ch == 'P')
{
op = NOP;
wd = Jop | 0x0380; // [7, 8, 9]
}
else // Ch != 'P'
Error = UNKNOWN_OP_NAME;
}
else // Ch != 'O'
Error = UNKNOWN_OP_NAME;
break;
case 'R':
GetRop(op, wd);
break;
case 'S':
GetSop(op, wd);
break;
case 'T':
GetCh();
if (Ch == 'R')
{
GetCh();
if (Ch == 'N')
{
GetCh();
if (Ch == 'G')
{
op = TRNG;
wd = Trngop;
}
else // Ch != 'G'
Error = UNKNOWN_OP_NAME;
}
else // Ch != 'N'
Error = UNKNOWN_OP_NAME;
}
else // Ch != 'R'
Error = UNKNOWN_OP_NAME;
break;
case 'W':
GetWop(op, wd);
break;
default:
Error = UNKNOWN_OP_NAME;
}
if (Error == NO_ERROR)
{
switch (op)
{
case CLR:
// need to find a reg address }
reg = GetRegAddr();
if (Error == NO_ERROR)
{
InRegAddr(wd, reg, 10);
InsertMem (wd);
}
break;
case SL:
case SR:
case SLD:
case SRD:
reg = GetRegAddr();
if (Error == NO_ERROR)
InRegAddr(wd, reg, 10);
GetCh();
if (Ch != ',')
{
Warn(MISSING_COMMA);
Saved = true;
}
ScanInt(wd2);
if (Error == NO_ERROR)
{
reg = short(wd2) ;
if (reg == 16)
reg = 0;
if ((reg < 16) && (reg >= 0))
{
InRegAddr(wd, reg, 3);
InsertMem (wd);
}
else
Error = BAD_SHFT_AMT;
}
break;
case OIN:
case IA:
case IS:
case IM:
case IDENT:
case FN:
case FA:
case FS:
case FM:
case FD:
case BI:
case BO:
case BA:
case IC:
case FC:
case JSR:
case BKT:
case LD:
case STO:
case LDA:
case FLT:
case FIX:
case TRNG:
reg = GetRegAddr();
if (Error == NO_ERROR)
{
InRegAddr(wd, reg, 10);
GetCh();
if (Ch != ',')
{
Warn(MISSING_COMMA);
Saved = true;
}
GetGenAddr(op, wd, wd2, twowds);
if (Error == NO_ERROR)
if (twowds)
{
InsertMem (wd);
InsertMem (wd2);
}
else
InsertMem (wd);
}
break;
case J:
GetGenAddr(op, wd, wd2, twowds);
if (Error == NO_ERROR)
if (twowds)
{
InsertMem (wd);
InsertMem (wd2);
}
else
InsertMem (wd);
break;
case RD:
case WR:
twowds = false;
if (!((0x0400 & wd)&&(0x0100 & wd)))
GetGenAddr(op, wd, wd2, twowds);
if (Error == NO_ERROR)
if (twowds)
{
InsertMem (wd);
InsertMem (wd2);
}
else
InsertMem (wd);
break;
case NOP:
case HALT:
InsertMem(wd);
break;
case INTDIR:
ScanInt(wd);
InsertMem(wd);
break;
case REALDIR:
ScanReal(wd, wd2);
InsertMem(wd);
InsertMem(wd2);
break;
case SKIPDIR:
ScanInt(wd);
i1 = int(wd);
if (i1 < 0)
Warn(BAD_SKIP);
else
{
Lc = Lc + i1;
for (int i = 1; i <= i1; i++)
Mem.push_back(Byte(0));
}
break;
case STRINGDIR:
ScanStr();
break;
case LABELDIR:
GetCh();
if ((Ch >= 'A' && Ch <= 'Q') || (Ch >= 'S' && Ch <= 'Z'))
{
ScanName(id);
idrec = FindName(id);
if (idrec == NULL)
idrec = InName(id);
else
{
if (idrec->loc >= 0)
Warn(NAME_DEFINED);
i1 = idrec->patch;
wd = Word(Lc);
WordToBytes(wd, b1, b2);
while (i1 >= 0)
{
BytesToWord(Mem[i1], Mem[i1+1], wd);
i2 = int(wd);
Mem[i1] = b1;
Mem[i1+1] = b2;
i1 = i2;
}
}
idrec->patch = -1;
idrec->loc = Lc;
}
else
Error = INVALID_NAME;
}
} // if Error = NO_ERROR
}
void InitOpcodes()
//
// Initalize all the opcodes.0
//
{
Inop = 0x0000; // 00000
Iaop = 0x0800; // 00001
Isop = 0x1000; // 00010
Imop = 0x1800; // 00011
Idop = 0x2000; // 00100
Fnop = 0x2800; // 00101
Faop = 0x3000; // 00110
Fsop = 0x3800; // 00111
Fmop = 0x4000; // 01000
Fdop = 0x4800; // 01001
Biop = 0x5000; // 01010
Boop = 0x5800; // 01011
Baop = 0x6000; // 01100
Icop = 0x6800; // 01101
Fcop = 0x7000; // 01110
Jsrop = 0x7800; // 01111
Bktop = 0x8000; // 10000
Ldop = 0x8800; // 10001
Stoop = 0x9000; // 10010
Ldaop = 0x9800; // 10011
Fltop = 0xA000; // 10100
Fixop = 0xA800; // 10101
Jop = 0xB000; // 10110
Srop = 0xB800; // 10111
Slop = 0xC000; // 11000
Rdop = 0xC800; // 11001
Wrop = 0xD000; // 11010
Trngop = 0xD800; // 11011
Haltop = 0xF800; // 11111
}
//---------------------------------------------------------------------
string Date()
{
const string MONTH[] =
{ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November",
"December" };
/*
char theDate[10];
int moNumber;
_strdate_s(theDate);
string strDate(theDate, theDate+8);
moNumber = 10 * (theDate[0] - '0') + theDate[1] - '0' - 1;
return MONTH[moNumber] + ' '
+ ((strDate[3] == '0') ? strDate.substr(4,1)
: strDate.substr(3,2))
+ ", 20" + strDate.substr(6,3);
*/
time_t now = time(0);
tm *ltm = localtime(&now);
return MONTH[ltm->tm_mon] + " " +
static_cast<ostringstream*>(
&(ostringstream() << ltm->tm_mday) )->str()
+ ", " +
static_cast<ostringstream*>(
&(ostringstream() << 1900 + ltm->tm_year) )->str();
}
string Time()
{
const string HOUR[]
= { "12", "1", "2", "3", "4", "5", "6",
"7", "8", "9", "10", "11" };
int hrNumber;
string suffix;
string pad = "";
time_t now = time(0);
tm *ltm = localtime(&now);
hrNumber = ltm->tm_hour;
if (ltm->tm_hour < 12)
suffix = " A.M.";
else
{
suffix = " P.M.";
hrNumber -= 12;
}
if ( ltm->tm_min < 10)
pad = "0";
return HOUR[hrNumber] + ':' + pad +
static_cast<ostringstream*>(
&(ostringstream() << ltm->tm_min) )->str()
+ suffix;
}
int main(int argc, char *argv[])
{
cout << "SAM 2016 ASSEMBLER\n" << endl;
if (argc > 1) {
if (strcmp(argv[1], "help") == 0) {
cout << "Usage: ./sam [sourceFile]\n ./sam help";
} else {
Source = argv[1];
Source = Source.substr(0, Source.find(".asm"));
cout << "SAM source file name: " << Source << ".asm" << endl;
}
} else {
cout << "SAM source file name: ";
getline(cin, Source);
}
InFile.open((Source + ".asm").data());
if(!InFile.is_open())
{
cout << "\nFile \"" << Source + ".asm" << "\" not found!"
<< "\nAssembly aborted.\n" << endl;
cin.get();
exit(1);
}
ListFile.open((Source+".lis").data());
ListFile << endl;
ListFile << " SAM 2016 Assembler Listing\n" << endl;
ListFile << " " + Date() << " at " << Time() << endl;
ListFile << " SOURCE FILE: " + Source + ".asm" << endl;
Symbols = NULL;
InitOpcodes();
Line = 0;
Lc = 0;
Errs = false;
Warning = false;
Saved = false;
InFile.peek();
if (!InFile.eof())
{
ListFile << endl;
ListFile << setw(10) << "LN" << setw(6) << "LC" << endl;
ListFile << setw(10) << Line
<< setw(6) << hex << uppercase << Lc
<< dec << ": ";
}
else
{
InFile.close();
ListFile.close();
cout << "\nFile is empty.\n" << endl;
exit(1);
}
InFile.peek();
while (!InFile.eof())
{
GetCh();
InFile.peek();
while (!InFile.eof() && (Ch == '%'))
{
InFile.ignore(256, '\n');
InFile.peek();
if (!InFile.eof())
{
ListFile << endl << flush;
ListFile << setw(10) << ++Line
<< setw(6) << hex << uppercase << Lc
<< dec << ": ";
GetCh();
}
}
if (Eoln(InFile)){//skip over blank lines in input file
GetCh();
continue;
}
if (!InFile.eof())
{ // instruction processing
Error = NO_ERROR;
Morewarn = false;
ProLine();
GetCh();
if (Ch != '%' && !isspace(Ch))
{ // skip text after instruction
Warn(TEXT_FOLLOWS);
do
{
InFile.get(Ch);
ListFile << Ch;
} while (Ch != '\n');
}
if (Error != NO_ERROR)
{
ListFile << endl;
Errs = true;
ListFile << " ERROR -- ";
switch (Error)
{
case INVALID_NAME:
ListFile <<
"Invalid Name in Label Directive";
break;
case UNKNOWN_OP_NAME:
ListFile <<
"Unknown Operation or Directive Name";
break;
case BAD_STR:
ListFile <<
"Improper String Directive -- Missing \"";
break;
case BAD_GEN_ADDR:
ListFile <<
"Improperly Formed General Address";
break;
case BAD_REG_ADDR:
ListFile <<
"Register Address Out of Range";
break;
case BAD_INTEGER:
ListFile <<
"Improperly Formed Integer Constant";
break;
case BAD_REAL:
ListFile <<
"Improperly Formed Real Constant";
break;
case BAD_STRING:
ListFile <<
"Improperly Formed String Constant";
break;
case BAD_NAME:
ListFile <<
"Improperly Formed Name";
break;
case ILL_REG_ADDR:
ListFile <<
"Direct Register Address not Permitted";
break;
case ILL_MED_ADDR:
ListFile <<
"Immediate Address not Permitted";
break;
case BAD_SHFT_AMT:
ListFile <<
"Shift Amount not in Range";
break;
default:;
}
ListFile << " detected on line " << Line << endl;
}
while (Morewarn)
PrintWarn();
}
}
ListFile << endl << endl;
CheckTab(Symbols);
if (!Errs && !Warning)
{
MemFile.open((Source+".obj").data(), ios_base::binary);
ListFile << "\nMACC Memory Hexadecimal Dump\n" << endl;
ListFile << " ADDR |";
for (int i = 0; i < 16; i++) ListFile << setw(4) << hex << i;
ListFile << endl;
ListFile << "------+";
for (int i = 0; i < 16; i++) ListFile << "----";
for (int i = 0; i < Lc; i++)
{
MemFile.put(Mem[i]);
if (i % 16 == 0) ListFile << endl << setw(5) << i << " |";
ListFile << " ";
if (Mem[i] < 16) ListFile << "0";
ListFile << hex << short(Mem[i]);
}
ListFile << endl << endl;
MemFile.close();
cout << " SUCCESSFUL ASSEMBLY." << endl;
cout << " OBJECT CODE FILE: "+ Source + ".obj" << endl;
}
else
{
cout << " ERRORS/WARNINGS IN ASSEMBLY CODE." << endl;
cout << " NO OBJECT CODE FILE WAS GENERATED." << endl;
ListFile.close();
InFile.close();
exit(1);
}
ListFile.close();
InFile.close();
//cin.ignore(256, '\n');
//cin.get(); // wait for Enter
return 0;
}
| 17.165441 | 79 | 0.504207 |
23a16754db0186edec4777a29ab424dbede84267 | 40,226 | cpp | C++ | multimedia/directx/dmusic/dmscript/dmscript.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | multimedia/directx/dmusic/dmscript/dmscript.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | multimedia/directx/dmusic/dmscript/dmscript.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //
// Copyright (c) 1999-2001 Microsoft Corporation. All rights reserved.
//
// Implementation of CDirectMusicScript.
//
#include "stdinc.h"
#include "dll.h"
#include "dmscript.h"
#include "oleaut.h"
#include "globaldisp.h"
#include "activescript.h"
#include "sourcetext.h"
//////////////////////////////////////////////////////////////////////
// Creation
CDirectMusicScript::CDirectMusicScript()
: m_cRef(0),
m_fZombie(false),
m_fCriticalSectionInitialized(false),
m_pPerformance8(NULL),
m_pLoader8P(NULL),
m_pDispPerformance(NULL),
m_pComposer8(NULL),
m_fUseOleAut(true),
m_pScriptManager(NULL),
m_pContainerDispatch(NULL),
m_pGlobalDispatch(NULL),
m_fInitError(false)
{
LockModule(true);
InitializeCriticalSection(&m_CriticalSection);
// Note: on pre-Blackcomb OS's, this call can raise an exception; if it
// ever pops in stress, we can add an exception handler and retry loop.
m_fCriticalSectionInitialized = TRUE;
m_info.fLoaded = false;
m_vDirectMusicVersion.dwVersionMS = 0;
m_vDirectMusicVersion.dwVersionLS = 0;
Zero(&m_iohead);
ZeroAndSize(&m_InitErrorInfo);
}
void CDirectMusicScript::ReleaseObjects()
{
if (m_pScriptManager)
{
m_pScriptManager->Close();
SafeRelease(m_pScriptManager);
}
SafeRelease(m_pPerformance8);
SafeRelease(m_pDispPerformance);
if (m_pLoader8P)
{
m_pLoader8P->ReleaseP();
m_pLoader8P = NULL;
}
SafeRelease(m_pComposer8);
delete m_pContainerDispatch;
m_pContainerDispatch = NULL;
delete m_pGlobalDispatch;
m_pGlobalDispatch = NULL;
}
HRESULT CDirectMusicScript::CreateInstance(
IUnknown* pUnknownOuter,
const IID& iid,
void** ppv)
{
*ppv = NULL;
if (pUnknownOuter)
return CLASS_E_NOAGGREGATION;
CDirectMusicScript *pInst = new CDirectMusicScript;
if (pInst == NULL)
return E_OUTOFMEMORY;
return pInst->QueryInterface(iid, ppv);
}
//////////////////////////////////////////////////////////////////////
// IUnknown
STDMETHODIMP
CDirectMusicScript::QueryInterface(const IID &iid, void **ppv)
{
V_INAME(CDirectMusicScript::QueryInterface);
V_PTRPTR_WRITE(ppv);
V_REFGUID(iid);
if (iid == IID_IUnknown || iid == IID_IDirectMusicScript)
{
*ppv = static_cast<IDirectMusicScript*>(this);
}
else if (iid == IID_IDirectMusicScriptPrivate)
{
*ppv = static_cast<IDirectMusicScriptPrivate*>(this);
}
else if (iid == IID_IDirectMusicObject)
{
*ppv = static_cast<IDirectMusicObject*>(this);
}
else if (iid == IID_IDirectMusicObjectP)
{
*ppv = static_cast<IDirectMusicObjectP*>(this);
}
else if (iid == IID_IPersistStream)
{
*ppv = static_cast<IPersistStream*>(this);
}
else if (iid == IID_IPersist)
{
*ppv = static_cast<IPersist*>(this);
}
else if (iid == IID_IDispatch)
{
*ppv = static_cast<IDispatch*>(this);
}
else
{
*ppv = NULL;
return E_NOINTERFACE;
}
reinterpret_cast<IUnknown*>(this)->AddRef();
return S_OK;
}
STDMETHODIMP_(ULONG)
CDirectMusicScript::AddRef()
{
return InterlockedIncrement(&m_cRef);
}
STDMETHODIMP_(ULONG)
CDirectMusicScript::Release()
{
if (!InterlockedDecrement(&m_cRef))
{
this->Zombie();
DeleteCriticalSection(&m_CriticalSection);
delete this;
LockModule(false);
return 0;
}
return m_cRef;
}
//////////////////////////////////////////////////////////////////////
// IPersistStream
STDMETHODIMP
CDirectMusicScript::Load(IStream* pStream)
{
V_INAME(CDirectMusicScript::Load);
V_INTERFACE(pStream);
if (m_fZombie)
{
Trace(1, "Error: Call of IDirectMusicScript::Load after the script has been garbage collected. "
"It is invalid to continue using a script after releasing it from the loader (ReleaseObject/ReleaseObjectByUnknown) "
"and then calling CollectGarbage or Release on the loader.");
return DMUS_S_GARBAGE_COLLECTED;
}
HRESULT hr = S_OK;
SmartRef::CritSec CS(&m_CriticalSection);
// Clear any old info
this->ReleaseObjects();
m_info.fLoaded = false;
m_info.oinfo.Clear();
m_vDirectMusicVersion.dwVersionMS = 0;
m_vDirectMusicVersion.dwVersionLS = 0;
m_wstrLanguage = NULL;
m_fInitError = false;
// Get the loader from stream
IDirectMusicGetLoader *pIDMGetLoader = NULL;
SmartRef::ComPtr<IDirectMusicLoader> scomLoader;
hr = pStream->QueryInterface(IID_IDirectMusicGetLoader, reinterpret_cast<void **>(&pIDMGetLoader));
if (FAILED(hr))
{
Trace(1, "Error: unable to load script from a stream because it doesn't support the IDirectMusicGetLoader interface.\n");
return DMUS_E_UNSUPPORTED_STREAM;
}
hr = pIDMGetLoader->GetLoader(&scomLoader);
pIDMGetLoader->Release();
if (FAILED(hr))
return hr;
hr = scomLoader->QueryInterface(IID_IDirectMusicLoader8P, reinterpret_cast<void **>(&m_pLoader8P)); // OK if this fails -- just means the scripts won't be garbage collected
if (SUCCEEDED(hr))
{
// Hold only a private ref on the loader. See IDirectMusicLoader8P::AddRefP for more info.
m_pLoader8P->AddRefP();
m_pLoader8P->Release(); // offset the QI
}
// Read the script's header information
SmartRef::RiffIter riForm(pStream);
if (!riForm)
{
#ifdef DBG
if (SUCCEEDED(riForm.hr()))
{
Trace(1, "Error: Unable to load script: Unexpected end of file.\n");
}
#endif
return SUCCEEDED(riForm.hr()) ? DMUS_E_SCRIPT_INVALID_FILE : riForm.hr();
}
hr = riForm.FindRequired(SmartRef::RiffIter::Riff, DMUS_FOURCC_SCRIPT_FORM, DMUS_E_SCRIPT_INVALID_FILE);
if (FAILED(hr))
{
#ifdef DBG
if (hr == DMUS_E_SCRIPT_INVALID_FILE)
{
Trace(1, "Error: Unable to load script: Form 'DMSC' not found.\n");
}
#endif
return hr;
}
SmartRef::RiffIter ri = riForm.Descend();
if (!ri)
return ri.hr();
hr = ri.FindRequired(SmartRef::RiffIter::Chunk, DMUS_FOURCC_SCRIPT_CHUNK, DMUS_E_SCRIPT_INVALID_FILE);
if (FAILED(hr))
{
#ifdef DBG
if (hr == DMUS_E_SCRIPT_INVALID_FILE)
{
Trace(1, "Error: Unable to load script: Chunk 'schd' not found.\n");
}
#endif
return hr;
}
hr = SmartRef::RiffIterReadChunk(ri, &m_iohead);
if (FAILED(hr))
return hr;
hr = ri.LoadObjectInfo(&m_info.oinfo, SmartRef::RiffIter::Chunk, DMUS_FOURCC_SCRIPTVERSION_CHUNK);
if (FAILED(hr))
return hr;
hr = SmartRef::RiffIterReadChunk(ri, &m_vDirectMusicVersion);
if (FAILED(hr))
return hr;
// Read the script's embedded container
IDirectMusicContainer *pContainer = NULL;
hr = ri.FindAndGetEmbeddedObject(
SmartRef::RiffIter::Riff,
DMUS_FOURCC_CONTAINER_FORM,
DMUS_E_SCRIPT_INVALID_FILE,
scomLoader,
CLSID_DirectMusicContainer,
IID_IDirectMusicContainer,
reinterpret_cast<void**>(&pContainer));
if (FAILED(hr))
{
#ifdef DBG
if (hr == DMUS_E_SCRIPT_INVALID_FILE)
{
Trace(1, "Error: Unable to load script: Form 'DMCN' no found.\n");
}
#endif
return hr;
}
// Build the container object that will represent the items in the container to the script
m_pContainerDispatch = new CContainerDispatch(pContainer, scomLoader, m_iohead.dwFlags, &hr);
pContainer->Release();
if (!m_pContainerDispatch)
return E_OUTOFMEMORY;
if (FAILED(hr))
return hr;
// Create the global dispatch object
m_pGlobalDispatch = new CGlobalDispatch(this);
if (!m_pGlobalDispatch)
return E_OUTOFMEMORY;
// Get the script's language
hr = ri.FindRequired(SmartRef::RiffIter::Chunk, DMUS_FOURCC_SCRIPTLANGUAGE_CHUNK, DMUS_E_SCRIPT_INVALID_FILE);
if (FAILED(hr))
{
#ifdef DBG
if (hr == DMUS_E_SCRIPT_INVALID_FILE)
{
Trace(1, "Error: Unable to load script: Chunk 'scla' no found.\n");
}
#endif
return hr;
}
hr = ri.ReadText(&m_wstrLanguage);
if (FAILED(hr))
{
#ifdef DBG
if (hr == E_FAIL)
{
Trace(1, "Error: Unable to load script: Problem reading 'scla' chunk.\n");
}
#endif
return hr == E_FAIL ? DMUS_E_SCRIPT_INVALID_FILE : hr;
}
// Get the script's source code
SmartRef::WString wstrSource;
for (++ri; ;++ri)
{
if (!ri)
{
Trace(1, "Error: Unable to load script: Expected chunk 'scsr' or list 'DMRF'.\n");
return DMUS_E_SCRIPT_INVALID_FILE;
}
SmartRef::RiffIter::RiffType type = ri.type();
FOURCC id = ri.id();
if (type == SmartRef::RiffIter::Chunk)
{
if (id == DMUS_FOURCC_SCRIPTSOURCE_CHUNK)
{
hr = ri.ReadText(&wstrSource);
if (FAILED(hr))
{
#ifdef DBG
if (hr == E_FAIL)
{
Trace(1, "Error: Unable to load script: Problem reading 'scsr' chunk.\n");
}
#endif
return hr == E_FAIL ? DMUS_E_SCRIPT_INVALID_FILE : hr;
}
}
break;
}
else if (type == SmartRef::RiffIter::List)
{
if (id == DMUS_FOURCC_REF_LIST)
{
DMUS_OBJECTDESC desc;
hr = ri.ReadReference(&desc);
if (FAILED(hr))
return hr;
// The resulting desc shouldn't have a name or GUID (the plain text file can't hold name/GUID info)
// and it should have a clsid should be GUID_NULL, which we'll replace with the clsid of our private
// source helper object.
if (desc.dwValidData & (DMUS_OBJ_NAME | DMUS_OBJ_OBJECT) ||
!(desc.dwValidData & DMUS_OBJ_CLASS) || desc.guidClass != GUID_NULL)
{
#ifdef DBG
if (desc.dwValidData & (DMUS_OBJ_NAME | DMUS_OBJ_OBJECT))
{
Trace(1, "Error: Unable to load script: 'DMRF' list must have dwValidData with DMUS_OBJ_CLASS and guidClassID of GUID_NULL.\n");
}
else
{
Trace(1, "Error: Unable to load script: 'DMRF' list cannot have dwValidData with DMUS_OBJ_NAME or DMUS_OBJ_OBJECT.\n");
}
#endif
return DMUS_E_SCRIPT_INVALID_FILE;
}
desc.guidClass = CLSID_DirectMusicSourceText;
IDirectMusicSourceText *pISource = NULL;
hr = scomLoader->EnableCache(CLSID_DirectMusicSourceText, false); // This is a private object we just use temporarily. Don't want these guys hanging around in the cache.
if (FAILED(hr))
return hr;
hr = scomLoader->GetObject(&desc, IID_IDirectMusicSourceText, reinterpret_cast<void**>(&pISource));
if (FAILED(hr))
return hr;
DWORD cwchSourceBufferSize = 0;
pISource->GetTextLength(&cwchSourceBufferSize);
WCHAR *pwszSource = new WCHAR[cwchSourceBufferSize];
if (!pwszSource)
return E_OUTOFMEMORY;
pISource->GetText(pwszSource);
*&wstrSource = pwszSource;
pISource->Release();
}
break;
}
}
m_info.fLoaded = true;
// Now that we are loaded and initialized, we can start active scripting
// See if we're dealing with a custom DirectMusic scripting engine. Such engines are marked with the key DMScript. They can be
// called on multiple threads and they don't use oleaut32. Ordinary active scripting engines are marked with the key OLEScript.
SmartRef::HKey shkeyLanguage;
SmartRef::HKey shkeyMark;
SmartRef::AString astrLanguage = m_wstrLanguage;
if (ERROR_SUCCESS != ::RegOpenKeyEx(HKEY_CLASSES_ROOT, astrLanguage, 0, KEY_QUERY_VALUE, &shkeyLanguage) || !shkeyLanguage)
{
Trace(1, "Error: Unable to load script: Scripting engine for language %s does not exist or is not registered.\n", astrLanguage);
return DMUS_E_SCRIPT_LANGUAGE_INCOMPATIBLE;
}
bool fCustomScriptEngine = ERROR_SUCCESS == ::RegOpenKeyEx(shkeyLanguage, "DMScript", 0, KEY_QUERY_VALUE, &shkeyMark) && shkeyMark;
if (!fCustomScriptEngine)
{
if (ERROR_SUCCESS != ::RegOpenKeyEx(shkeyLanguage, "OLEScript", 0, KEY_QUERY_VALUE, &shkeyMark) || !shkeyMark)
{
Trace(1, "Error: Unable to load script: Language %s refers to a COM object that is not registered as a scripting engine (OLEScript key).\n", astrLanguage);
return DMUS_E_SCRIPT_LANGUAGE_INCOMPATIBLE;
}
}
m_fUseOleAut = !fCustomScriptEngine;
if (fCustomScriptEngine)
{
m_pScriptManager = new CActiveScriptManager(
m_fUseOleAut,
m_wstrLanguage,
wstrSource,
this,
&hr,
&m_InitErrorInfo);
}
else
{
m_pScriptManager = new CSingleThreadedScriptManager(
m_fUseOleAut,
m_wstrLanguage,
wstrSource,
this,
&hr,
&m_InitErrorInfo);
}
if (!m_pScriptManager)
return E_OUTOFMEMORY;
if (FAILED(hr))
{
SafeRelease(m_pScriptManager);
}
if (hr == DMUS_E_SCRIPT_ERROR_IN_SCRIPT)
{
// If we fail here, load would fail and client would never be able to get the
// error information. Instead, return S_OK and save the error to return from Init.
m_fInitError = true;
hr = S_OK;
}
return hr;
}
//////////////////////////////////////////////////////////////////////
// IDirectMusicObject
STDMETHODIMP
CDirectMusicScript::GetDescriptor(LPDMUS_OBJECTDESC pDesc)
{
V_INAME(CDirectMusicScript::GetDescriptor);
V_PTR_WRITE(pDesc, DMUS_OBJECTDESC);
ZeroMemory(pDesc, sizeof(DMUS_OBJECTDESC));
pDesc->dwSize = sizeof(DMUS_OBJECTDESC);
if (m_fZombie)
{
Trace(1, "Error: Call of IDirectMusicScript::GetDescriptor after the script has been garbage collected. "
"It is invalid to continue using a script after releasing it from the loader (ReleaseObject/ReleaseObjectByUnknown) "
"and then calling CollectGarbage or Release on the loader.");
return DMUS_S_GARBAGE_COLLECTED;
}
if (wcslen(m_info.oinfo.wszName) > 0)
{
pDesc->dwValidData |= DMUS_OBJ_NAME;
wcsncpy(pDesc->wszName, m_info.oinfo.wszName, DMUS_MAX_NAME);
pDesc->wszName[DMUS_MAX_NAME-1] = L'\0';
}
if (GUID_NULL != m_info.oinfo.guid)
{
pDesc->guidObject = m_info.oinfo.guid;
pDesc->dwValidData |= DMUS_OBJ_OBJECT;
}
pDesc->vVersion = m_info.oinfo.vVersion;
pDesc->dwValidData |= DMUS_OBJ_VERSION;
pDesc->guidClass = CLSID_DirectMusicScript;
pDesc->dwValidData |= DMUS_OBJ_CLASS;
if (m_info.wstrFilename)
{
wcsncpy(pDesc->wszFileName, m_info.wstrFilename, DMUS_MAX_FILENAME);
pDesc->wszFileName[DMUS_MAX_FILENAME-1] = L'\0';
pDesc->dwValidData |= DMUS_OBJ_FILENAME;
}
if (m_info.fLoaded)
{
pDesc->dwValidData |= DMUS_OBJ_LOADED;
}
return S_OK;
}
STDMETHODIMP
CDirectMusicScript::SetDescriptor(LPDMUS_OBJECTDESC pDesc)
{
V_INAME(CDirectMusicScript::SetDescriptor);
V_STRUCTPTR_READ(pDesc, DMUS_OBJECTDESC);
if (m_fZombie)
{
Trace(1, "Error: Call of IDirectMusicScript::SetDescriptor after the script has been garbage collected. "
"It is invalid to continue using a script after releasing it from the loader (ReleaseObject/ReleaseObjectByUnknown) "
"and then calling CollectGarbage or Release on the loader.");
return DMUS_S_GARBAGE_COLLECTED;
}
DWORD dwTemp = pDesc->dwValidData;
if (pDesc->dwValidData & DMUS_OBJ_OBJECT)
{
m_info.oinfo.guid = pDesc->guidObject;
}
if (pDesc->dwValidData & DMUS_OBJ_CLASS)
{
pDesc->dwValidData &= ~DMUS_OBJ_CLASS;
}
if (pDesc->dwValidData & DMUS_OBJ_NAME)
{
wcsncpy(m_info.oinfo.wszName, pDesc->wszName, DMUS_MAX_NAME);
m_info.oinfo.wszName[DMUS_MAX_NAME-1] = L'\0';
}
if (pDesc->dwValidData & DMUS_OBJ_CATEGORY)
{
pDesc->dwValidData &= ~DMUS_OBJ_CATEGORY;
}
if (pDesc->dwValidData & DMUS_OBJ_FILENAME)
{
m_info.wstrFilename = pDesc->wszFileName;
}
if (pDesc->dwValidData & DMUS_OBJ_FULLPATH)
{
pDesc->dwValidData &= ~DMUS_OBJ_FULLPATH;
}
if (pDesc->dwValidData & DMUS_OBJ_URL)
{
pDesc->dwValidData &= ~DMUS_OBJ_URL;
}
if (pDesc->dwValidData & DMUS_OBJ_VERSION)
{
m_info.oinfo.vVersion = pDesc->vVersion;
}
if (pDesc->dwValidData & DMUS_OBJ_DATE)
{
pDesc->dwValidData &= ~DMUS_OBJ_DATE;
}
if (pDesc->dwValidData & DMUS_OBJ_LOADED)
{
pDesc->dwValidData &= ~DMUS_OBJ_LOADED;
}
return dwTemp == pDesc->dwValidData ? S_OK : S_FALSE;
}
STDMETHODIMP
CDirectMusicScript::ParseDescriptor(LPSTREAM pStream, LPDMUS_OBJECTDESC pDesc)
{
V_INAME(CDirectMusicScript::ParseDescriptor);
V_INTERFACE(pStream);
V_PTR_WRITE(pDesc, DMUS_OBJECTDESC);
ZeroMemory(pDesc, sizeof(DMUS_OBJECTDESC));
pDesc->dwSize = sizeof(DMUS_OBJECTDESC);
if (m_fZombie)
{
Trace(1, "Error: Call of IDirectMusicScript::ParseDescriptor after the script has been garbage collected. "
"It is invalid to continue using a script after releasing it from the loader (ReleaseObject/ReleaseObjectByUnknown) "
"and then calling CollectGarbage or Release on the loader.");
return DMUS_S_GARBAGE_COLLECTED;
}
SmartRef::CritSec CS(&m_CriticalSection);
// Read the script's header information
SmartRef::RiffIter riForm(pStream);
if (!riForm)
{
#ifdef DBG
if (SUCCEEDED(riForm.hr()))
{
Trace(2, "Error: ParseDescriptor on a script failed: Unexpected end of file. "
"(Note that this may be OK, such as when ScanDirectory is used to parse a set of unknown files, some of which are not scripts.)\n");
}
#endif
return SUCCEEDED(riForm.hr()) ? DMUS_E_SCRIPT_INVALID_FILE : riForm.hr();
}
HRESULT hr = riForm.FindRequired(SmartRef::RiffIter::Riff, DMUS_FOURCC_SCRIPT_FORM, DMUS_E_SCRIPT_INVALID_FILE);
if (FAILED(hr))
{
#ifdef DBG
if (hr == DMUS_E_SCRIPT_INVALID_FILE)
{
Trace(1, "Error: ParseDescriptor on a script failed: Form 'DMSC' not found. "
"(Note that this may be OK, such as when ScanDirectory is used to parse a set of unknown files, some of which are not scripts.)\n");
}
#endif
return hr;
}
SmartRef::RiffIter ri = riForm.Descend();
if (!ri)
return ri.hr();
hr = ri.LoadObjectInfo(&m_info.oinfo, SmartRef::RiffIter::Chunk, DMUS_FOURCC_SCRIPTVERSION_CHUNK);
if (FAILED(hr))
return hr;
hr = this->GetDescriptor(pDesc);
return hr;
}
STDMETHODIMP_(void)
CDirectMusicScript::Zombie()
{
m_fZombie = true;
this->ReleaseObjects();
}
//////////////////////////////////////////////////////////////////////
// IDirectMusicScript
STDMETHODIMP
CDirectMusicScript::Init(IDirectMusicPerformance *pPerformance, DMUS_SCRIPT_ERRORINFO *pErrorInfo)
{
V_INAME(CDirectMusicScript::Init);
V_INTERFACE(pPerformance);
V_PTR_WRITE_OPT(pErrorInfo, DMUS_SCRIPT_ERRORINFO);
if (m_fZombie)
{
Trace(1, "Error: Call of IDirectMusicScript::Init after the script has been garbage collected. "
"It is invalid to continue using a script after releasing it from the loader (ReleaseObject/ReleaseObjectByUnknown) "
"and then calling CollectGarbage or Release on the loader.");
return DMUS_S_GARBAGE_COLLECTED;
}
SmartRef::ComPtr<IDirectMusicPerformance8> scomPerformance8;
HRESULT hr = pPerformance->QueryInterface(IID_IDirectMusicPerformance8, reinterpret_cast<void **>(&scomPerformance8));
if (FAILED(hr))
return hr;
// Don't take the critical section if the script is already initialized.
// For example, this is necessary in the following situation:
// - The critical section has already been taken by CallRoutine.
// - The routine played a segment with a script track referencing this script.
// - The script track calls Init (from a different thread) to make sure the script
// is initialized.
if (m_pPerformance8)
{
// Additional calls to Init are ignored.
// First call wins. Return S_FALSE if performance doesn't match.
if (m_pPerformance8 == scomPerformance8)
return S_OK;
else
return S_FALSE;
}
SmartRef::CritSec CS(&m_CriticalSection);
if (m_fInitError)
{
if (pErrorInfo)
{
// Syntax errors in a script occur as it is loaded, before SetDescriptor gives a script
// its filename. We'll have it after the load (before init is called) so can add it
// back in here.
if (m_InitErrorInfo.wszSourceFile[0] == L'\0' && m_info.wstrFilename)
wcsTruncatedCopy(m_InitErrorInfo.wszSourceFile, m_info.wstrFilename, DMUS_MAX_FILENAME);
CopySizedStruct(pErrorInfo, &m_InitErrorInfo);
}
return DMUS_E_SCRIPT_ERROR_IN_SCRIPT;
}
if (!m_info.fLoaded)
{
Trace(1, "Error: IDirectMusicScript::Init called before the script has been loaded.\n");
return DMUS_E_NOT_LOADED;
}
// Get the dispatch interface for the performance
SmartRef::ComPtr<IDispatch> scomDispPerformance = NULL;
hr = pPerformance->QueryInterface(IID_IDispatch, reinterpret_cast<void **>(&scomDispPerformance));
if (FAILED(hr))
return hr;
// Get a composer object
hr = CoCreateInstance(CLSID_DirectMusicComposer, NULL, CLSCTX_INPROC_SERVER, IID_IDirectMusicComposer8, reinterpret_cast<void **>(&m_pComposer8));
if (FAILED(hr))
return hr;
m_pDispPerformance = scomDispPerformance.disown();
m_pPerformance8 = scomPerformance8.disown();
hr = m_pScriptManager->Start(pErrorInfo);
if (FAILED(hr))
return hr;
hr = m_pContainerDispatch->OnScriptInit(m_pPerformance8);
return hr;
}
// Returns DMUS_E_SCRIPT_ROUTINE_NOT_FOUND if routine doesn't exist in the script.
STDMETHODIMP
CDirectMusicScript::CallRoutine(WCHAR *pwszRoutineName, DMUS_SCRIPT_ERRORINFO *pErrorInfo)
{
V_INAME(CDirectMusicScript::CallRoutine);
V_BUFPTR_READ(pwszRoutineName, 2);
V_PTR_WRITE_OPT(pErrorInfo, DMUS_SCRIPT_ERRORINFO);
if (m_fZombie)
{
Trace(1, "Error: Call of IDirectMusicScript::CallRoutine after the script has been garbage collected. "
"It is invalid to continue using a script after releasing it from the loader (ReleaseObject/ReleaseObjectByUnknown) "
"and then calling CollectGarbage or Release on the loader.");
return DMUS_S_GARBAGE_COLLECTED;
}
SmartRef::CritSec CS(&m_CriticalSection);
if (!m_pScriptManager || !m_pPerformance8)
{
Trace(1, "Error: IDirectMusicScript::Init must be called before IDirectMusicScript::CallRoutine.\n");
return DMUS_E_NOT_INIT;
}
return m_pScriptManager->CallRoutine(pwszRoutineName, pErrorInfo);
}
// Returns DMUS_E_SCRIPT_VARIABLE_NOT_FOUND if variable doesn't exist in the script.
STDMETHODIMP
CDirectMusicScript::SetVariableVariant(
WCHAR *pwszVariableName,
VARIANT varValue,
BOOL fSetRef,
DMUS_SCRIPT_ERRORINFO *pErrorInfo)
{
V_INAME(CDirectMusicScript::SetVariableVariant);
V_BUFPTR_READ(pwszVariableName, 2);
V_PTR_WRITE_OPT(pErrorInfo, DMUS_SCRIPT_ERRORINFO);
switch (varValue.vt)
{
case VT_BSTR:
V_BUFPTR_READ_OPT(varValue.bstrVal, sizeof(OLECHAR));
// We could be more thorough and verify each character until we hit the terminator but
// that would be inefficient. We could also use the length preceding a BSTR pointer,
// but that would be cheating COM's functions that encapsulate BSTRs and could lead to
// problems in future versions of windows such as 64 bit if the BSTR format changes.
break;
case VT_UNKNOWN:
V_INTERFACE_OPT(varValue.punkVal);
break;
case VT_DISPATCH:
V_INTERFACE_OPT(varValue.pdispVal);
break;
}
if (m_fZombie)
{
Trace(1, "Error: Call of IDirectMusicScript::SetVariableObject/SetVariableNumber/SetVariableVariant after the script has been garbage collected. "
"It is invalid to continue using a script after releasing it from the loader (ReleaseObject/ReleaseObjectByUnknown) "
"and then calling CollectGarbage or Release on the loader.");
return DMUS_S_GARBAGE_COLLECTED;
}
SmartRef::CritSec CS(&m_CriticalSection);
if (!m_pScriptManager || !m_pPerformance8)
{
Trace(1, "Error: IDirectMusicScript::Init must be called before IDirectMusicScript::SetVariableVariant.\n");
return DMUS_E_NOT_INIT;
}
HRESULT hr = m_pScriptManager->SetVariable(pwszVariableName, varValue, !!fSetRef, pErrorInfo);
if (hr == DMUS_E_SCRIPT_VARIABLE_NOT_FOUND)
{
// There are also items in the script's container that the m_pScriptManager object isn't available.
// If that's the case, we should return a more specific error message.
IUnknown *punk = NULL;
hr = m_pContainerDispatch->GetVariableObject(pwszVariableName, &punk);
if (SUCCEEDED(hr))
{
// We don't actually need the object--it can't be set. Just needed to find out if it's there
// in order to return a more specific error message.
punk->Release();
return DMUS_E_SCRIPT_CONTENT_READONLY;
}
}
return hr;
}
// Returns DMUS_E_SCRIPT_VARIABLE_NOT_FOUND and empty value if variable doesn't exist in the script.
// Certain varient types such as BSTRs and interface pointers must be freed/released according to the standards for VARIANTS.
// If unsure, use VariantClear (requires oleaut32).
STDMETHODIMP
CDirectMusicScript::GetVariableVariant(WCHAR *pwszVariableName, VARIANT *pvarValue, DMUS_SCRIPT_ERRORINFO *pErrorInfo)
{
V_INAME(CDirectMusicScript::GetVariableVariant);
V_BUFPTR_READ(pwszVariableName, 2);
V_PTR_WRITE(pvarValue, VARIANT);
V_PTR_WRITE_OPT(pErrorInfo, DMUS_SCRIPT_ERRORINFO);
DMS_VariantInit(m_fUseOleAut, pvarValue);
if (m_fZombie)
{
Trace(1, "Error: Call of IDirectMusicScript::GetVariableObject/GetVariableNumber/GetVariableVariant after the script has been garbage collected. "
"It is invalid to continue using a script after releasing it from the loader (ReleaseObject/ReleaseObjectByUnknown) "
"and then calling CollectGarbage or Release on the loader.");
return DMUS_S_GARBAGE_COLLECTED;
}
SmartRef::CritSec CS(&m_CriticalSection);
if (!m_pScriptManager || !m_pPerformance8)
{
Trace(1, "Error: IDirectMusicScript::Init must be called before IDirectMusicScript::GetVariableVariant.\n");
return DMUS_E_NOT_INIT;
}
HRESULT hr = m_pScriptManager->GetVariable(pwszVariableName, pvarValue, pErrorInfo);
if (hr == DMUS_E_SCRIPT_VARIABLE_NOT_FOUND)
{
// There are also items in the script's container that we need to return.
// This is implemented by the container, which returns the IUnknown pointer directly rather than through a variant.
IUnknown *punk = NULL;
hr = m_pContainerDispatch->GetVariableObject(pwszVariableName, &punk);
if (SUCCEEDED(hr))
{
pvarValue->vt = VT_UNKNOWN;
pvarValue->punkVal = punk;
}
}
#ifdef DBG
if (hr == DMUS_E_SCRIPT_VARIABLE_NOT_FOUND)
{
Trace(1, "Error: Attempt to get variable '%S' that is not defined in the script.\n", pwszVariableName);
}
#endif
if (!m_fUseOleAut && pvarValue->vt == VT_BSTR)
{
// m_fUseOleAut is false when we're using our own custom scripting engine that avoids
// depending on oleaut32.dll. But in this case we're returning a BSTR variant to the
// caller. We have to allocate this string with SysAllocString (from oleaut32)
// because the caller is going to free it with SysFreeString--the standard thing to
// do with a variant BSTR.
BSTR bstrOle = DMS_SysAllocString(true, pvarValue->bstrVal); // allocate a copy with oleaut
DMS_SysFreeString(false, pvarValue->bstrVal); // free the previous value (allocated without oleaut)
pvarValue->bstrVal = bstrOle; // return the oleaut string to the user
if (!bstrOle)
hr = E_OUTOFMEMORY;
}
return hr;
}
// Returns DMUS_E_SCRIPT_VARIABLE_NOT_FOUND if variable doesn't exist in the script.
STDMETHODIMP
CDirectMusicScript::SetVariableNumber(WCHAR *pwszVariableName, LONG lValue, DMUS_SCRIPT_ERRORINFO *pErrorInfo)
{
VARIANT var;
var.vt = VT_I4;
var.lVal = lValue;
return this->SetVariableVariant(pwszVariableName, var, false, pErrorInfo);
}
// Returns DMUS_E_SCRIPT_VARIABLE_NOT_FOUND and 0 if variable doesn't exist in the script.
// Returns DISP_E_TYPEMISMATCH if variable's datatype cannot be converted to LONG.
STDMETHODIMP
CDirectMusicScript::GetVariableNumber(WCHAR *pwszVariableName, LONG *plValue, DMUS_SCRIPT_ERRORINFO *pErrorInfo)
{
V_INAME(CDirectMusicScript::GetVariableNumber);
V_PTR_WRITE(plValue, LONG);
*plValue = 0;
VARIANT var;
HRESULT hr = this->GetVariableVariant(pwszVariableName, &var, pErrorInfo);
if (FAILED(hr) || hr == S_FALSE || hr == DMUS_S_GARBAGE_COLLECTED)
return hr;
hr = DMS_VariantChangeType(m_fUseOleAut, &var, &var, 0, VT_I4);
if (SUCCEEDED(hr))
*plValue = var.lVal;
// GetVariableVariant forces a BSTR to be allocated with SysAllocString;
// so if we allocated a BSTR there, we need to free it with SysAllocString here.
bool fUseOleAut = m_fUseOleAut;
if (!m_fUseOleAut && var.vt == VT_BSTR)
{
fUseOleAut = true;
}
DMS_VariantClear(fUseOleAut, &var);
return hr;
}
// Returns DMUS_E_SCRIPT_VARIABLE_NOT_FOUND if variable doesn't exist in the script.
STDMETHODIMP
CDirectMusicScript::SetVariableObject(WCHAR *pwszVariableName, IUnknown *punkValue, DMUS_SCRIPT_ERRORINFO *pErrorInfo)
{
VARIANT var;
var.vt = VT_UNKNOWN;
var.punkVal = punkValue;
return this->SetVariableVariant(pwszVariableName, var, true, pErrorInfo);
}
// Returns DMUS_E_SCRIPT_VARIABLE_NOT_FOUND and NULL if variable doesn't exist in the script.
// Returns DISP_E_TYPEMISMATCH if variable's datatype cannot be converted to IUnknown.
STDMETHODIMP
CDirectMusicScript::GetVariableObject(WCHAR *pwszVariableName, REFIID riid, LPVOID FAR *ppv, DMUS_SCRIPT_ERRORINFO *pErrorInfo)
{
V_INAME(CDirectMusicScript::GetVariableObject);
V_PTR_WRITE(ppv, IUnknown *);
*ppv = NULL;
VARIANT var;
HRESULT hr = this->GetVariableVariant(pwszVariableName, &var, pErrorInfo);
if (FAILED(hr) || hr == DMUS_S_GARBAGE_COLLECTED)
return hr;
hr = DMS_VariantChangeType(m_fUseOleAut, &var, &var, 0, VT_UNKNOWN);
if (SUCCEEDED(hr))
hr = var.punkVal->QueryInterface(riid, ppv);
DMS_VariantClear(m_fUseOleAut, &var);
return hr;
}
STDMETHODIMP
CDirectMusicScript::EnumRoutine(DWORD dwIndex, WCHAR *pwszName)
{
V_INAME(CDirectMusicScript::EnumRoutine);
V_BUFPTR_WRITE(pwszName, MAX_PATH);
*pwszName = L'\0';
if (m_fZombie)
{
Trace(1, "Error: Call of IDirectMusicScript::EnumRoutine after the script has been garbage collected. "
"It is invalid to continue using a script after releasing it from the loader (ReleaseObject/ReleaseObjectByUnknown) "
"and then calling CollectGarbage or Release on the loader.");
return DMUS_S_GARBAGE_COLLECTED;
}
if (!m_pScriptManager || !m_pPerformance8)
{
Trace(1, "Error: IDirectMusicScript::Init must be called before IDirectMusicScript::EnumRoutine.\n");
return DMUS_E_NOT_INIT;
}
return m_pScriptManager->EnumItem(true, dwIndex, pwszName, NULL);
}
STDMETHODIMP
CDirectMusicScript::EnumVariable(DWORD dwIndex, WCHAR *pwszName)
{
V_INAME(CDirectMusicScript::EnumRoutine);
V_BUFPTR_WRITE(pwszName, MAX_PATH);
*pwszName = L'\0';
if (m_fZombie)
{
Trace(1, "Error: Call of IDirectMusicScript::EnumVariable after the script has been garbage collected. "
"It is invalid to continue using a script after releasing it from the loader (ReleaseObject/ReleaseObjectByUnknown) "
"and then calling CollectGarbage or Release on the loader.");
return DMUS_S_GARBAGE_COLLECTED;
}
if (!m_pScriptManager || !m_pPerformance8)
{
Trace(1, "Error: IDirectMusicScript::Init must be called before IDirectMusicScript::EnumVariable.\n");
return DMUS_E_NOT_INIT;
}
int cScriptItems = 0;
HRESULT hr = m_pScriptManager->EnumItem(false, dwIndex, pwszName, &cScriptItems);
if (FAILED(hr))
return hr;
if (hr == S_FALSE)
{
// There are also items in the script's container that we need to report.
assert(dwIndex >= cScriptItems);
hr = m_pContainerDispatch->EnumItem(dwIndex - cScriptItems, pwszName);
}
return hr;
}
STDMETHODIMP
CDirectMusicScript::ScriptTrackCallRoutine(
WCHAR *pwszRoutineName,
IDirectMusicSegmentState *pSegSt,
DWORD dwVirtualTrackID,
bool fErrorPMsgsEnabled,
__int64 i64IntendedStartTime,
DWORD dwIntendedStartTimeFlags)
{
V_INAME(CDirectMusicScript::CallRoutine);
V_BUFPTR_READ(pwszRoutineName, 2);
V_INTERFACE(pSegSt);
if (m_fZombie)
{
Trace(1, "Error: Script track attempted to call a routine after the script has been garbage collected. "
"It is invalid to continue using a script after releasing it from the loader (ReleaseObject/ReleaseObjectByUnknown) "
"and then calling CollectGarbage or Release on the loader.");
return DMUS_S_GARBAGE_COLLECTED;
}
SmartRef::CritSec CS(&m_CriticalSection);
if (!m_pScriptManager || !m_pPerformance8)
{
Trace(1, "Error: Unitialized Script elements in an attempt to call a Script Routine.\n");
return DMUS_E_NOT_INIT;
}
return m_pScriptManager->ScriptTrackCallRoutine(
pwszRoutineName,
pSegSt,
dwVirtualTrackID,
fErrorPMsgsEnabled,
i64IntendedStartTime,
dwIntendedStartTimeFlags);
}
STDMETHODIMP
CDirectMusicScript::GetTypeInfoCount(UINT *pctinfo)
{
V_INAME(CDirectMusicScript::GetTypeInfoCount);
V_PTR_WRITE(pctinfo, UINT);
*pctinfo = 0;
if (m_fZombie)
{
Trace(1, "Error: Call of IDirectMusicScript::GetTypeInfoCount after the script has been garbage collected. "
"It is invalid to continue using a script after releasing it from the loader (ReleaseObject/ReleaseObjectByUnknown) "
"and then calling CollectGarbage or Release on the loader.");
return DMUS_S_GARBAGE_COLLECTED;
}
return S_OK;
}
STDMETHODIMP
CDirectMusicScript::GetTypeInfo(UINT iTInfo, LCID lcid, ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo)
{
*ppTInfo = NULL;
return E_NOTIMPL;
}
STDMETHODIMP
CDirectMusicScript::GetIDsOfNames(
REFIID riid,
LPOLESTR __RPC_FAR *rgszNames,
UINT cNames,
LCID lcid,
DISPID __RPC_FAR *rgDispId)
{
if (m_fZombie)
{
if (rgDispId)
{
for (int i = 0; i < cNames; ++i)
{
rgDispId[i] = DISPID_UNKNOWN;
}
}
Trace(1, "Error: Call of GetIDsOfNames after a script has been garbage collected. "
"It is invalid to continue using a script after releasing it from the loader (ReleaseObject/ReleaseObjectByUnknown) "
"and then calling CollectGarbage or Release on the loader.");
return DMUS_S_GARBAGE_COLLECTED;
}
if (!m_pScriptManager || !m_pPerformance8)
{
Trace(1, "Error: IDirectMusicScript::Init must be called before GetIDsOfNames.\n");
return DMUS_E_NOT_INIT;
}
return m_pScriptManager->DispGetIDsOfNames(riid, rgszNames, cNames, lcid, rgDispId);
}
STDMETHODIMP
CDirectMusicScript::Invoke(
DISPID dispIdMember,
REFIID riid,
LCID lcid,
WORD wFlags,
DISPPARAMS __RPC_FAR *pDispParams,
VARIANT __RPC_FAR *pVarResult,
EXCEPINFO __RPC_FAR *pExcepInfo,
UINT __RPC_FAR *puArgErr)
{
if (m_fZombie)
{
if (pVarResult)
DMS_VariantInit(m_fUseOleAut, pVarResult);
Trace(1, "Error: Call of Invoke after the script has been garbage collected. "
"It is invalid to continue using a script after releasing it from the loader (ReleaseObject/ReleaseObjectByUnknown) "
"and then calling CollectGarbage or Release on the loader.");
return DMUS_S_GARBAGE_COLLECTED;
}
if (!m_pScriptManager || !m_pPerformance8)
{
Trace(1, "Error: IDirectMusicScript::Init must be called before Invoke.\n");
return DMUS_E_NOT_INIT;
}
return m_pScriptManager->DispInvoke(dispIdMember, riid, lcid, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr);
}
//////////////////////////////////////////////////////////////////////
// Methods that allow CActiveScriptManager access to private script interfaces
IDispatch *CDirectMusicScript::GetGlobalDispatch()
{
assert(m_pGlobalDispatch);
return m_pGlobalDispatch;
}
| 34.6179 | 186 | 0.621861 |
23a3eef99bb03be101e5c678edd9f254ac18b11c | 617 | cpp | C++ | Coraza.cpp | ErickMartinez2/Lab7P3_ErickMartinez | b6f045979bd3b09e9b89f2bd97c51d031db0978b | [
"MIT"
] | null | null | null | Coraza.cpp | ErickMartinez2/Lab7P3_ErickMartinez | b6f045979bd3b09e9b89f2bd97c51d031db0978b | [
"MIT"
] | null | null | null | Coraza.cpp | ErickMartinez2/Lab7P3_ErickMartinez | b6f045979bd3b09e9b89f2bd97c51d031db0978b | [
"MIT"
] | null | null | null | #include "Coraza.h"
Coraza::Coraza() {
}
Coraza::Coraza(int pdureza, int pcantidad) {
dureza = pdureza;
cantidad = pcantidad;;
}
Coraza::Coraza(string pnombre, string pciudad, int pedad, int pdureza, int pcantidad): Soldado(pnombre, pciudad, pedad) {
dureza = pdureza;
cantidad = pcantidad;
}
int Coraza::getDureza() {
return dureza;
}
void Coraza::setDureza(int pdureza) {
dureza = pdureza;
}
int Coraza::getCantidad() {
return cantidad;
}
void Coraza::setCantidad(int pcantidad) {
cantidad = pcantidad;
}
double Coraza::ataque() {
return cantidad;
}
double Coraza::defensa() {
return dureza;
}
| 15.04878 | 121 | 0.701783 |
23a4241af81aa23c0da2f9375699cb1983670347 | 1,153 | cpp | C++ | src/RuleTimer.cpp | d3wy/pool-controller | 182d8c67638abf56d8e5126103b5995006c06b42 | [
"MIT"
] | 12 | 2020-03-04T18:43:43.000Z | 2022-01-30T22:59:27.000Z | src/RuleTimer.cpp | d3wy/pool-controller | 182d8c67638abf56d8e5126103b5995006c06b42 | [
"MIT"
] | 17 | 2019-05-20T20:22:09.000Z | 2022-01-11T16:55:26.000Z | src/RuleTimer.cpp | d3wy/pool-controller | 182d8c67638abf56d8e5126103b5995006c06b42 | [
"MIT"
] | 6 | 2020-06-05T18:17:13.000Z | 2022-03-19T20:13:58.000Z |
#include "RuleTimer.hpp"
/**
*
*/
RuleTimer::RuleTimer(RelayModuleNode* solarRelay, RelayModuleNode* poolRelay) {
_solarRelay = solarRelay;
_poolRelay = poolRelay;
}
/**
*
*/
void RuleTimer::loop() {
Homie.getLogger() << cIndent << F("§ RuleTimer: loop") << endl;
_poolRelay->setSwitch(checkPoolPumpTimer());
if (_solarRelay->getSwitch()) {
_solarRelay->setSwitch(false);
}
}
/**
*
*/
bool RuleTimer::checkPoolPumpTimer() {
Homie.getLogger() << F("↕ checkPoolPumpTimer") << endl;
tm time = getCurrentDateTime();
bool retval;
tm startTime = getStartTime(getTimerSetting());
tm endTime = getEndTime(getTimerSetting());
Homie.getLogger() << cIndent << F("time= ") << asctime(&time);
Homie.getLogger() << cIndent << F("startTime= ") << asctime(&startTime);
Homie.getLogger() << cIndent << F("endTime= ") << asctime(&endTime);
if (difftime(mktime(&time), mktime(&startTime)) >= 0
&& difftime(mktime(&time), mktime(&endTime)) <= 0) {
retval = true;
} else {
retval = false;
}
Homie.getLogger() << cIndent << F("checkPoolPumpTimer = ") << retval << endl;
return retval;
}
| 20.589286 | 79 | 0.626193 |
23a5e0323c44ab4bf0478d745ace3cbaa9fecd1d | 743 | cpp | C++ | sessions/session-3/src/histogram_equalisation.cpp | iitmcvg/learn2c | 7d55064ebd8dbb335a353b198e9f1154df4f594e | [
"MIT"
] | null | null | null | sessions/session-3/src/histogram_equalisation.cpp | iitmcvg/learn2c | 7d55064ebd8dbb335a353b198e9f1154df4f594e | [
"MIT"
] | null | null | null | sessions/session-3/src/histogram_equalisation.cpp | iitmcvg/learn2c | 7d55064ebd8dbb335a353b198e9f1154df4f594e | [
"MIT"
] | null | null | null | #include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
using namespace cv;
using namespace std;
int main( int argc, char** argv ) {
Mat src, dst;
char* source_window = "Source image";
char* equalized_window = "Equalized Image";
/// Load image
src = imread( argv[1], 1 );
/// Convert to grayscale
cvtColor( src, src, CV_BGR2GRAY );
/// Apply Histogram Equalization
equalizeHist( src, dst );
/// Display results
namedWindow( source_window, CV_WINDOW_AUTOSIZE );
namedWindow( equalized_window, CV_WINDOW_AUTOSIZE );
imshow( source_window, src );
imshow( equalized_window, dst );
/// Wait until user exits the program
waitKey(0);
return 0;
} | 21.228571 | 54 | 0.697174 |
23ae7e5ac53ac779985446beb4d8c74dbbeccd09 | 572 | cpp | C++ | Source/Musa/GameObject/DemoGameObjects/OrbitingObject.cpp | frobro98/Musa | 6e7dcd5d828ca123ce8f43d531948a6486428a3d | [
"MIT"
] | null | null | null | Source/Musa/GameObject/DemoGameObjects/OrbitingObject.cpp | frobro98/Musa | 6e7dcd5d828ca123ce8f43d531948a6486428a3d | [
"MIT"
] | null | null | null | Source/Musa/GameObject/DemoGameObjects/OrbitingObject.cpp | frobro98/Musa | 6e7dcd5d828ca123ce8f43d531948a6486428a3d | [
"MIT"
] | null | null | null | #include "OrbitingObject.hpp"
#include "Math/Matrix4.hpp"
#include "Math/Quat.hpp"
OrbitingObject::OrbitingObject(const Vector4& orbitAxis, const Vector4& orbitPos)
: axis(orbitAxis),
orbitLocation(orbitPos)
{
}
void OrbitingObject::Update(float /*tick*/)
{
// constexpr float angleOffsetDeg = .005f;
// Matrix4 trans(TRANS, orbitLocation);
// Quat rot(ROT_AXIS_ANGLE, axis, angleOffsetDeg * tick);
// Matrix4 negTrans(TRANS, -orbitLocation);
//
// Matrix4 orbitTrans = negTrans * rot * trans;
//
// position *= orbitTrans;
//
// GameObject::Update(tick);
}
| 23.833333 | 81 | 0.713287 |
23b0372f4e2172c56569014cd64d3ee64537cd34 | 3,343 | cpp | C++ | Classes/transitScene.cpp | alchemz/Campuspedia | 0d686a346f67e0f54087fc307ef5fc65d334b935 | [
"MIT"
] | 1 | 2015-03-21T17:55:17.000Z | 2015-03-21T17:55:17.000Z | Classes/transitScene.cpp | alchemz/Campuspedia | 0d686a346f67e0f54087fc307ef5fc65d334b935 | [
"MIT"
] | null | null | null | Classes/transitScene.cpp | alchemz/Campuspedia | 0d686a346f67e0f54087fc307ef5fc65d334b935 | [
"MIT"
] | null | null | null | #include "TransitScene.h"
using namespace cocos2d::ui;
USING_NS_CC;
Scene* Transit::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::create();
// 'layer' is an autorelease object
auto layer = Transit::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool Transit::init()
{
//////////////////////////////
// 1. super init first
if ( !Layer::init() )
{
return false;
}
ini=60;
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
stopFrame=false;
scene=UserDefault::getInstance()->getIntegerForKey("Scene");
auto label=Label::createWithTTF("", "fonts/Calibri.ttf", 120);
label->setPosition(Vec2(origin.x+visibleSize.width/2,origin.y+visibleSize.height/2));
this->addChild(label,1);
if (scene==_DORM) {
int dorm=UserDefault::getInstance()->getIntegerForKey("Dorm");
if (dorm==_POLLOCK) {
label->setString("POLLOCK DORM AREA");
}
else if(dorm==_EAST){
label->setString("EAST DORM AREA");
}
else if(dorm==_WEST){
label->setString("WEST DORM AREA");
}
else if(dorm==_SOUTH){
label->setString("SOUTH DORM AREA");
}
else if(dorm==_NORTH){
label->setString("NORTH DORM AREA");
}
}
else if(scene==_HUB){
label->setString("HUB AREA");
}
else if(scene==_OLDMAIN){
label->setString("OLD MAIN AREA");
}
else if(scene==_LIFESC){
label->setString("LIFE SCIENCE AREA");
}
else if(scene==_PATTEE){
label->setString("PATTEE LIBRARY AREA");
}
else if(scene==_IST){
label->setString("IST AREA");
}
else if(scene==_ARENA){
label->setString("ARENA");
auto ist_bg=Sprite::create("transit/ist.png");
ist_bg->setPosition(Vec2(origin.x+visibleSize.width/2,origin.y+visibleSize.height/2));
this->addChild(ist_bg,0);
}
this->scheduleUpdate();
return true;
}
void Transit::update(float dt) {
if (stopFrame==false) {
if (ini!=0) {
ini--;
}
else{
stopFrame=true;
if (scene!=_ARENA) {
auto Scene=Game::createScene();
Director::getInstance()->replaceScene(TransitionFade::create(0.5, Scene, Color3B(0,0,0)));
}
else{
auto arenaScene=Arena::createScene();
Director::getInstance()->replaceScene(TransitionFade::create(0.5, arenaScene, Color3B(0,0,0)));
}
}
}
}
void Transit::menuCloseCallback(Ref* pSender)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
MessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
return;
#endif
Director::getInstance()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
}
| 29.069565 | 111 | 0.548908 |
23b6267156ba30d4212a91e8925ca4c296c927a0 | 5,285 | hpp | C++ | packages/monte_carlo/estimator/native/src/MonteCarlo_CellPulseHeightEstimator.hpp | lkersting/SCR-2123 | 06ae3d92998664a520dc6a271809a5aeffe18f72 | [
"BSD-3-Clause"
] | null | null | null | packages/monte_carlo/estimator/native/src/MonteCarlo_CellPulseHeightEstimator.hpp | lkersting/SCR-2123 | 06ae3d92998664a520dc6a271809a5aeffe18f72 | [
"BSD-3-Clause"
] | null | null | null | packages/monte_carlo/estimator/native/src/MonteCarlo_CellPulseHeightEstimator.hpp | lkersting/SCR-2123 | 06ae3d92998664a520dc6a271809a5aeffe18f72 | [
"BSD-3-Clause"
] | null | null | null | //---------------------------------------------------------------------------//
//!
//! \file MonteCarlo_CellPulseHeightEstimator.hpp
//! \author Alex Robinson
//! \brief Cell pulse height estimator class declaration
//!
//---------------------------------------------------------------------------//
#ifndef FACEMC_CELL_PULSE_HEIGHT_ESTIMATOR_HPP
#define FACEMC_CELL_PULSE_HEIGHT_ESTIMATOR_HPP
// Boost Includes
#include <boost/unordered_set.hpp>
#include <boost/mpl/vector.hpp>
// FRENSIE Includes
#include "MonteCarlo_EntityEstimator.hpp"
#include "MonteCarlo_EstimatorContributionMultiplierPolicy.hpp"
#include "MonteCarlo_ParticleEnteringCellEventObserver.hpp"
#include "MonteCarlo_ParticleLeavingCellEventObserver.hpp"
#include "Geometry_ModuleTraits.hpp"
namespace MonteCarlo{
/*! The pulse height entity estimator class
* \details This class has been set up to get correct results with multiple
* threads. However, the commitHistoryContribution member function call
* should only appear within an omp critical block. Use the enable thread
* support member function to set up an instance of this class for the
* requested number of threads. The classes default initialization is for
* a single thread.
*/
template<typename ContributionMultiplierPolicy = WeightMultiplier>
class CellPulseHeightEstimator : public EntityEstimator<Geometry::ModuleTraits::InternalCellHandle>,
public ParticleEnteringCellEventObserver,
public ParticleLeavingCellEventObserver
{
private:
// Typedef for the serial update tracker
typedef boost::unordered_map<Geometry::ModuleTraits::InternalCellHandle,
double>
SerialUpdateTracker;
// Typedef for the parallel update tracker
typedef Teuchos::Array<SerialUpdateTracker>
ParallelUpdateTracker;
public:
//! Typedef for the cell id type
typedef Geometry::ModuleTraits::InternalCellHandle cellIdType;
//! Typedef for event tags used for quick dispatcher registering
typedef boost::mpl::vector<ParticleEnteringCellEventObserver::EventTag,
ParticleLeavingCellEventObserver::EventTag>
EventTags;
//! Constructor
CellPulseHeightEstimator( const Estimator::idType id,
const double multiplier,
const Teuchos::Array<cellIdType>& entity_ids );
//! Destructor
~CellPulseHeightEstimator()
{ /* ... */ }
//! Set the response functions
void setResponseFunctions(
const Teuchos::Array<Teuchos::RCP<ResponseFunction> >& response_functions );
//! Set the particle types that can contribute to the estimator
void setParticleTypes( const Teuchos::Array<ParticleType>& particle_types );
//! Add current history estimator contribution
void updateFromParticleEnteringCellEvent( const ParticleState& particle,
const cellIdType cell_entering );
//! Add current history estimator contribution
void updateFromParticleLeavingCellEvent( const ParticleState& particle,
const cellIdType cell_leaving );
//! Commit the contribution from the current history to the estimator
void commitHistoryContribution();
//! Print the estimator data
void print( std::ostream& os ) const;
//! Enable support for multiple threads
void enableThreadSupport( const unsigned num_threads );
//! Reset the estimator data
void resetData();
//! Export the estimator data
void exportData( EstimatorHDF5FileHandler& hdf5_file,
const bool process_data ) const;
private:
// Assign bin boundaries to an estimator dimension
void assignBinBoundaries(
const Teuchos::RCP<EstimatorDimensionDiscretization>& bin_boundaries );
// Calculate the estimator contribution from the entire history
double calculateHistoryContribution( const double energy_deposition,
WeightMultiplier );
// Calculate the estimator contribution from the entire history
double calculateHistoryContribution( const double energy_deposition,
WeightAndEnergyMultiplier );
// Add info to update tracker
void addInfoToUpdateTracker( const unsigned thread_id,
const cellIdType cell_id,
const double contribution );
// Get the entity iterators from the update tracker
void getCellIteratorFromUpdateTracker(
const unsigned thread_id,
typename SerialUpdateTracker::const_iterator& start_cell,
typename SerialUpdateTracker::const_iterator& end_cell ) const;
// Reset the update tracker
void resetUpdateTracker( const unsigned thread_id );
// The entities that have been updated
ParallelUpdateTracker d_update_tracker;
// The generic particle state map (avoids having to make a new map for cont.)
Teuchos::Array<Estimator::DimensionValueMap> d_dimension_values;
};
} // end MonteCarlo namespace
//---------------------------------------------------------------------------//
// Template Includes
//---------------------------------------------------------------------------//
#include "MonteCarlo_CellPulseHeightEstimator_def.hpp"
//---------------------------------------------------------------------------//
#endif // end FACEMC_CELL_PULSE_HEIGHT_ESTIMATOR_HPP
//---------------------------------------------------------------------------//
// end MonteCarlo_CellPulseHeightEstimator.hpp
//---------------------------------------------------------------------------//
| 35.233333 | 101 | 0.693661 |
23b6b5a280f6b6b9fc6621a21ebcdf8dd9977483 | 5,206 | cpp | C++ | src/formats/RareSnesInstr.cpp | ValleyBell/vgmtrans | fc7ad99857450d3a943d8201a05331837e5db938 | [
"Zlib"
] | 2 | 2021-01-18T05:47:48.000Z | 2022-03-15T18:27:41.000Z | src/formats/RareSnesInstr.cpp | ValleyBell/vgmtrans | fc7ad99857450d3a943d8201a05331837e5db938 | [
"Zlib"
] | null | null | null | src/formats/RareSnesInstr.cpp | ValleyBell/vgmtrans | fc7ad99857450d3a943d8201a05331837e5db938 | [
"Zlib"
] | null | null | null | #include "stdafx.h"
#include "RareSnesInstr.h"
#include "Format.h"
#include "SNESDSP.h"
#include "RareSnesFormat.h"
// ****************
// RareSnesInstrSet
// ****************
RareSnesInstrSet::RareSnesInstrSet(RawFile* file, uint32_t offset, uint32_t spcDirAddr, const std::wstring & name) :
VGMInstrSet(RareSnesFormat::name, file, offset, 0, name),
spcDirAddr(spcDirAddr),
maxSRCNValue(255)
{
Initialize();
}
RareSnesInstrSet::RareSnesInstrSet(RawFile* file, uint32_t offset, uint32_t spcDirAddr,
const std::map<uint8_t, int8_t> & instrUnityKeyHints, const std::map<uint8_t, int16_t> & instrPitchHints, const std::map<uint8_t, uint16_t> & instrADSRHints,
const std::wstring & name) :
VGMInstrSet(RareSnesFormat::name, file, offset, 0, name),
spcDirAddr(spcDirAddr),
maxSRCNValue(255),
instrUnityKeyHints(instrUnityKeyHints),
instrPitchHints(instrPitchHints),
instrADSRHints(instrADSRHints)
{
Initialize();
}
RareSnesInstrSet::~RareSnesInstrSet()
{
}
void RareSnesInstrSet::Initialize()
{
for (uint32_t srcn = 0; srcn < 256; srcn++)
{
uint32_t offDirEnt = spcDirAddr + (srcn * 4);
if (offDirEnt + 4 > 0x10000)
{
maxSRCNValue = srcn - 1;
break;
}
if (GetShort(offDirEnt) == 0)
{
maxSRCNValue = srcn - 1;
break;
}
}
unLength = 0x100;
if (dwOffset + unLength > GetRawFile()->size())
{
unLength = GetRawFile()->size() - dwOffset;
}
ScanAvailableInstruments();
}
void RareSnesInstrSet::ScanAvailableInstruments()
{
availInstruments.clear();
bool firstZero = true;
for (uint32_t inst = 0; inst < unLength; inst++)
{
uint8_t srcn = GetByte(dwOffset + inst);
if (srcn == 0 && !firstZero)
{
continue;
}
if (srcn == 0)
{
firstZero = false;
}
uint32_t offDirEnt = spcDirAddr + (srcn * 4);
if (offDirEnt + 4 > 0x10000)
{
continue;
}
if (srcn > maxSRCNValue)
{
continue;
}
uint16_t addrSampStart = GetShort(offDirEnt);
uint16_t addrSampLoop = GetShort(offDirEnt + 2);
// valid loop?
if (addrSampStart > addrSampLoop)
{
continue;
}
// not in DIR table
if (addrSampStart < spcDirAddr + (128 * 4))
{
continue;
}
// address 0 is probably legit, but it should not be used
if (addrSampStart == 0)
{
continue;
}
// Rare engine does not break the following rule... perhaps
if (addrSampStart < spcDirAddr)
{
continue;
}
availInstruments.push_back(inst);
}
}
bool RareSnesInstrSet::GetHeaderInfo()
{
return true;
}
bool RareSnesInstrSet::GetInstrPointers()
{
for (std::vector<uint8_t>::iterator itr = availInstruments.begin(); itr != availInstruments.end(); ++itr)
{
uint8_t inst = (*itr);
uint8_t srcn = GetByte(dwOffset + inst);
int8_t transpose = 0;
std::map<uint8_t, int8_t>::iterator itrKey;
itrKey = this->instrUnityKeyHints.find(inst);
if (itrKey != instrUnityKeyHints.end())
{
transpose = itrKey->second;
}
int16_t pitch = 0;
std::map<uint8_t, int16_t>::iterator itrPitch;
itrPitch = this->instrPitchHints.find(inst);
if (itrPitch != instrPitchHints.end())
{
pitch = itrPitch->second;
}
uint16_t adsr = 0x8FE0;
std::map<uint8_t, uint16_t>::iterator itrADSR;
itrADSR = this->instrADSRHints.find(inst);
if (itrADSR != instrADSRHints.end())
{
adsr = itrADSR->second;
}
std::wostringstream instrName;
instrName << L"Instrument " << inst;
RareSnesInstr * newInstr = new RareSnesInstr(this, dwOffset + inst, inst >> 7, inst & 0x7f, spcDirAddr, transpose, pitch, adsr, instrName.str());
aInstrs.push_back(newInstr);
}
return aInstrs.size() != 0;
}
const std::vector<uint8_t>& RareSnesInstrSet::GetAvailableInstruments()
{
return availInstruments;
}
// *************
// RareSnesInstr
// *************
RareSnesInstr::RareSnesInstr(VGMInstrSet* instrSet, uint32_t offset, uint32_t theBank, uint32_t theInstrNum, uint32_t spcDirAddr, int8_t transpose, int16_t pitch, uint16_t adsr, const std::wstring& name) :
VGMInstr(instrSet, offset, 1, theBank, theInstrNum, name),
spcDirAddr(spcDirAddr),
transpose(transpose),
pitch(pitch),
adsr(adsr)
{
}
RareSnesInstr::~RareSnesInstr()
{
}
bool RareSnesInstr::LoadInstr()
{
uint8_t srcn = GetByte(dwOffset);
uint32_t offDirEnt = spcDirAddr + (srcn * 4);
if (offDirEnt + 4 > 0x10000)
{
return false;
}
uint16_t addrSampStart = GetShort(offDirEnt);
RareSnesRgn * rgn = new RareSnesRgn(this, dwOffset, transpose, pitch, adsr);
rgn->sampOffset = addrSampStart - spcDirAddr;
aRgns.push_back(rgn);
return true;
}
// ***********
// RareSnesRgn
// ***********
RareSnesRgn::RareSnesRgn(RareSnesInstr* instr, uint32_t offset, int8_t transpose, int16_t pitch, uint16_t adsr) :
VGMRgn(instr, offset, 1),
transpose(transpose),
pitch(pitch),
adsr(adsr)
{
// normalize (it is needed especially since SF2 pitch correction is signed 8-bit)
int16_t pitchKeyShift = (pitch / 100);
int8_t realTranspose = transpose + pitchKeyShift;
int16_t realPitch = pitch - (pitchKeyShift * 100);
// NOTE_PITCH_TABLE[73] == 0x1000
// 0x80 + (73 - 36) = 0xA5
SetUnityKey(36 + 36 - realTranspose);
SetFineTune(realPitch);
SNESConvADSR<VGMRgn>(this, adsr >> 8, adsr & 0xff, 0);
}
RareSnesRgn::~RareSnesRgn()
{
}
bool RareSnesRgn::LoadRgn()
{
return true;
}
| 22.634783 | 205 | 0.684595 |
23b8430bc6dc45bb0fa1a18df8d033da62315651 | 6,716 | cpp | C++ | src/model.cpp | akitsu-sanae/phylan | bf949de7b5a91dfd965c3fcc4868b76b4b577375 | [
"BSL-1.0"
] | null | null | null | src/model.cpp | akitsu-sanae/phylan | bf949de7b5a91dfd965c3fcc4868b76b4b577375 | [
"BSL-1.0"
] | null | null | null | src/model.cpp | akitsu-sanae/phylan | bf949de7b5a91dfd965c3fcc4868b76b4b577375 | [
"BSL-1.0"
] | null | null | null | /*============================================================================
Copyright (C) 2016 akitsu sanae
https://github.com/akitsu-sanae/phylan
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
============================================================================*/
#include <GLFW/glfw3.h>
#include "model.hpp"
#include "world.hpp"
#include "ast.hpp"
#include "rope.hpp"
ph::Model::Model(ph::World& world, std::istream& input) :
m_world(world)
{
m_ast = ph::Element::load(input);
m_ast->regist(world);
m_ropes = ph::Rope::set(m_ast.get(), *world.world_info());
m_ropes.push_back(std::make_shared<Rope>(*m_ast, *world.world_info()));
for (auto&& rope : m_ropes)
rope->regist(world);
m_selected_element = m_ast.get();
}
ph::Model::~Model() {
for (auto&& rope : m_ropes)
rope->remove(m_world);
m_ast->remove(m_world);
}
void ph::Model::draw() const {
m_ast->draw(m_selected_element);
for (auto const& rope : m_ropes)
rope->draw();
}
void ph::Model::save() const {
m_ast->save();
}
void ph::Model::move(ph::Model::Move move) {
Element* tmp = nullptr;
switch (move) {
case Move::Next:
tmp = m_selected_element->next();
break;
case Move::Prev:
tmp = m_selected_element->prev();
break;
case Move::Parent:
tmp = m_selected_element->parent();
break;
}
if (tmp)
m_selected_element = tmp;
}
void add_element(
std::unique_ptr<ph::Element>& ast,
ph::Element* selected,
std::unique_ptr<ph::Element>& e) {
if (auto mult = ph::node_cast<ph::NodeType::Mult>(ast.get())) {
if (mult->lhs.get() == selected) {
mult->lhs = std::move(e);
mult->lhs->parent(mult);
} else
add_element(mult->lhs, selected, e);
if (mult->rhs.get() == selected) {
mult->rhs = std::move(e);
mult->rhs->parent(mult);
} else
add_element(mult->rhs, selected, e);
} else if (auto plus = ph::node_cast<ph::NodeType::Plus>(ast.get())) {
if (plus->lhs.get() == selected) {
plus->lhs = std::move(e);
plus->lhs->parent(plus);
} else
add_element(plus->lhs, selected, e);
if (plus->rhs.get() == selected) {
plus->rhs = std::move(e);
plus->rhs->parent(plus);
} else
add_element(plus->rhs, selected, e);
} else if (auto print = ph::node_cast<ph::NodeType::Print>(ast.get())) {
if (print->val.get() == selected) {
print->val = std::move(e);
print->val->parent(print);
} else
add_element(print->val, selected, e);
} else if (auto if_ = ph::node_cast<ph::NodeType::If>(ast.get())) {
if (if_->cond.get() == selected) {
if_->cond = std::move(e);
if_->cond->parent(if_);
} else
add_element(if_->cond, selected, e);
if (if_->true_.get() == selected) {
if_->true_ = std::move(e);
if_->true_->parent(if_);
} else
add_element(if_->true_, selected, e);
if (if_->false_.get() == selected) {
if_->false_ = std::move(e);
if_->false_->parent(if_);
} else
add_element(if_->false_, selected, e);
}
}
std::unique_ptr<ph::Element> make_node(ph::Element const* selected) {
std::string type = "";
while (true) {
std::cout << "what type? (plus, mult, print, number)" << std::endl;
std::cin >> type;
if (type == "plus")
break;
if (type == "mult")
break;
if (type == "print")
break;
if (type == "if")
break;
if (type == "number")
break;
}
std::unique_ptr<ph::Element> element;
if (type == "plus") {
auto pos = ph::Point::from_vec(selected->position());
auto plus = std::make_unique<ph::Node<ph::NodeType::Plus>>(pos);
plus->lhs = std::make_unique<ph::Undefined>(pos);
plus->rhs = std::make_unique<ph::Undefined>(pos);
plus->lhs->parent(plus.get());
plus->rhs->parent(plus.get());
element = std::move(plus);
} else if (type == "mult") {
auto pos = ph::Point::from_vec(selected->position());
auto mult = std::make_unique<ph::Node<ph::NodeType::Mult>>(pos);
mult->lhs = std::make_unique<ph::Undefined>(pos);
mult->rhs = std::make_unique<ph::Undefined>(pos);
mult->lhs->parent(mult.get());
mult->rhs->parent(mult.get());
element = std::move(mult);
} else if (type == "if") {
auto pos = ph::Point::from_vec(selected->position());
auto if_ = std::make_unique<ph::Node<ph::NodeType::If>>(pos);
if_->cond = std::make_unique<ph::Undefined>(pos);
if_->true_ = std::make_unique<ph::Undefined>(pos);
if_->false_ = std::make_unique<ph::Undefined>(pos);
if_->cond->parent(if_.get());
if_->true_->parent(if_.get());
if_->false_->parent(if_.get());
element = std::move(if_);
} else if (type == "print") {
auto pos = ph::Point::from_vec(selected->position());
auto print = std::make_unique<ph::Node<ph::NodeType::Print>>(pos);
print->val = std::make_unique<ph::Undefined>(pos);
print->val->parent(print.get());
element = std::move(print);
} else if (type == "number") {
std::cout << "value: ";
int n;
std::cin >> n;
element = std::make_unique<ph::Literal>(ph::Point::from_vec(selected->position()), n);
}
return element;
}
void ph::Model::edit() {
if (m_selected_element == m_ast.get()) {
std::cerr << "you cen not edit the root node!" << std::endl;
return;
}
std::unique_ptr<Element> element;
if (!dynamic_cast<ph::Undefined*>(m_selected_element))
element = std::make_unique<Undefined>(Point::from_vec(m_selected_element->position()));
else
element = make_node(m_selected_element);
for (auto&& rope : m_ropes)
rope->remove(m_world);
m_ast->remove(m_world);
// swap element and m_selected_element
add_element(m_ast, m_selected_element, element);
m_ropes.clear();
m_ropes = ph::Rope::set(m_ast.get(), *m_world.world_info());
m_ropes.push_back(std::make_shared<Rope>(*m_ast, *m_world.world_info()));
m_ast->regist(m_world);
for (auto&& rope : m_ropes)
rope->regist(m_world);
m_selected_element = m_ast.get();
}
int ph::Model::eval() const {
return m_ast->value();
}
| 33.247525 | 95 | 0.544818 |
23bacc4836a2719609c6d5f7e06370e32f250472 | 3,953 | cpp | C++ | test/fence_counting.cpp | mdsudara/percy | b593922b98c9c20fe0a3e4726e50401e54b9cb09 | [
"MIT"
] | 14 | 2018-03-10T21:50:20.000Z | 2021-11-22T04:09:09.000Z | test/fence_counting.cpp | mdsudara/percy | b593922b98c9c20fe0a3e4726e50401e54b9cb09 | [
"MIT"
] | 3 | 2018-06-12T15:17:22.000Z | 2019-06-20T12:00:45.000Z | test/fence_counting.cpp | mdsudara/percy | b593922b98c9c20fe0a3e4726e50401e54b9cb09 | [
"MIT"
] | 12 | 2018-03-10T17:02:07.000Z | 2022-01-09T16:04:56.000Z | #include <percy/percy.hpp>
#include <cassert>
#include <cstdio>
#include <vector>
using namespace percy;
using std::vector;
/*******************************************************************************
Counts and prints all fences up to and including F_5 and ensures that the
number is correct.
*******************************************************************************/
int main(void)
{
fence f;
auto total_expected_fences = 0u;
for (unsigned k = 1; k <= 5; k++) {
printf("F_%u\n", k);
for (unsigned l = 1; l <= k; l++) {
printf("F(%u, %u)\n", k, l);
partition_generator g(k, l);
auto nfences = 0u;
while (g.next_fence(f)) {
nfences++;
print_fence(f);
printf("\n");
}
const auto expected_fences = binomial_coeff(k-1, l-1);
assert(nfences == expected_fences);
total_expected_fences += nfences;
}
auto nfences = 0u;
family_generator g(k);
auto expected_fences = 0u;
for (auto l = 1u; l <= k; l++) {
expected_fences += binomial_coeff(k-1, l-1);
}
while (g.next_fence(f)) {
nfences++;
}
assert(nfences == (unsigned)expected_fences);
}
unbounded_generator g;
auto nfences = 0u;
while (true) {
g.next_fence(f);
if (g.get_nnodes() >= 6) {
break;
}
nfences++;
}
assert(nfences == total_expected_fences);
rec_fence_generator recgen;
recgen.set_po_filter(false);
for (unsigned k = 1; k <= 5; k++) {
printf("F_%u\n", k);
auto total_nr_fences = 0u;
for (unsigned l = 1; l <= k; l++) {
printf("F(%u, %u)\n", k, l);
recgen.reset(k, l);
vector<fence> fences;
recgen.generate_fences(fences);
const auto nfences = fences.size();
for (auto& f : fences) {
print_fence(f);
printf("\n");
}
const auto expected_fences = binomial_coeff(k-1, l-1);
assert(nfences == expected_fences);
total_nr_fences += nfences;
}
auto fences = generate_fences(k, false);
assert(fences.size() == total_nr_fences);
}
// Count the maximum number of fences needed to synthesize all 5-input
// functions.
auto global_total = 0u;
recgen.set_po_filter(true);
vector<fence> po_fences;
for (unsigned k = 1; k <= 12; k++) {
auto total_nr_fences = 0u;
for (unsigned l = 1; l <= k; l++) {
recgen.reset(k, l);
total_nr_fences += recgen.count_fences();
}
generate_fences(po_fences, k);
global_total += total_nr_fences;
printf("Number of fences in F_%d = %d\n", k, total_nr_fences);
}
assert(po_fences.size() == global_total);
for (unsigned k = 13; k <= 15; k++) {
auto total_nr_fences = 0u;
for (unsigned l = 1; l <= k; l++) {
recgen.reset(k, l);
total_nr_fences += recgen.count_fences();
}
printf("Number of fences in F_%u = %d\n", k, total_nr_fences);
}
printf("Nr. of fences relevant to 5-input single-output synthesis is %d\n",
global_total);
// Count the number of fence relevant to synthesizing single-output chains
// with 3-input operators
global_total = 0;
recgen.set_po_filter(true);
po_fences.clear();
for (unsigned k = 1; k <= 15; k++) {
auto total_nr_fences = 0;
for (unsigned l = 1; l <= k; l++) {
recgen.reset(k, l, 1, 3);
total_nr_fences += recgen.count_fences();
}
generate_fences(po_fences, k);
global_total += total_nr_fences;
printf("Number of fences in F_%u = %u (3-input gates)\n", k, total_nr_fences);
}
return 0;
}
| 31.125984 | 86 | 0.510751 |
23bcd21af6406c7041ba801dab6dcc72689b9dd5 | 2,240 | hpp | C++ | src/base/include/structs.hpp | N4G170/generic | 29c8be184b1420b811e2a3db087f9bd6b76ed8bf | [
"MIT"
] | null | null | null | src/base/include/structs.hpp | N4G170/generic | 29c8be184b1420b811e2a3db087f9bd6b76ed8bf | [
"MIT"
] | null | null | null | src/base/include/structs.hpp | N4G170/generic | 29c8be184b1420b811e2a3db087f9bd6b76ed8bf | [
"MIT"
] | null | null | null | #ifndef STRUCTS_HPP
#define STRUCTS_HPP
#include <type_traits>
#include <string>
#include "vector3.hpp"
#include "enums.hpp"
#include "SDL.h"
template<typename T>
struct Bounds
{
//check if we initialize the vector with the right values
static_assert(std::is_integral<T>::value || std::is_floating_point<T>::value, "Bounds template can only integrals of floating point types");
T min_x{0}, min_y{0}, min_z{0}, max_x{0}, max_y{0}, max_z{0};
Bounds(): min_x{0}, min_y{0}, min_z{0}, max_x{0}, max_y{0}, max_z{0} {};
Bounds(T minx, T miny, T minz, T maxx, T maxy, T maxz): min_x{minx}, min_y{miny}, min_z{minz}, max_x{maxx}, max_y{maxy}, max_z{maxz} {};
Bounds(const Vector3<T>& position, const Vector3<T>& size): min_x{position.X()}, min_y{position.Y()}, min_z{position.Z()},
max_x{position.X() + size.X()}, max_y{position.Y() + size.Y()}, max_z{position.Z() + size.Z()} {}
Vector3<T> Size(){ return {max_x - min_x, max_y - min_y, max_z - min_z}; }
Vector3<T> PointPosition(BoundsPositions bounds_position = BoundsPositions::Front_Top_Left)
{
switch (bounds_position)
{
case BoundsPositions::Front_Top_Left: return {min_x, min_y, min_z}; break;
case BoundsPositions::Front_Top_Right: return {max_x, min_y, min_z}; break;
case BoundsPositions::Front_Bottom_Left: return {min_x, max_y, min_z}; break;
case BoundsPositions::Front_Bottom_Right: return {max_x, max_y, min_z}; break;
case BoundsPositions::Back_Top_Left: return {min_x, min_y, max_z}; break;
case BoundsPositions::Back_Top_Right: return {max_x, min_y, max_z}; break;
case BoundsPositions::Back_Bottom_Left: return {min_x, max_y, max_z}; break;
case BoundsPositions::Back_Bottom_Right: return {max_x, max_y, max_z}; break;
default: return {min_x, min_y, min_z};
}
}
};
struct BasicFrame
{
std::string image_path{};
bool has_src_rect{false};
SDL_Rect source_rect{0,0,0,0};
BasicFrame(const std::string& path, bool has_rect, const SDL_Rect& src_rect) : image_path{path}, has_src_rect{has_rect}, source_rect{src_rect} {}
};
#endif //STRUCTS_HPP
| 42.264151 | 149 | 0.658036 |
23bf3d4e2e7fccc5f011f98b95a9fa02783391b3 | 1,604 | cpp | C++ | src/type.cpp | robey/nolove | d83e5ba34e5e53dbef066f4da2f22c6cc2d0572c | [
"Apache-2.0"
] | 1 | 2015-11-05T12:17:23.000Z | 2015-11-05T12:17:23.000Z | src/type.cpp | robey/nolove | d83e5ba34e5e53dbef066f4da2f22c6cc2d0572c | [
"Apache-2.0"
] | null | null | null | src/type.cpp | robey/nolove | d83e5ba34e5e53dbef066f4da2f22c6cc2d0572c | [
"Apache-2.0"
] | null | null | null | #include "llvm/Support/raw_ostream.h"
#include "type.h"
using namespace v8;
// ----- LType
NodeProto<LType> LType::proto("Type");
void LType::init() {
proto.addMethod("isDoubleType", <ype::isDoubleType);
proto.addMethod("isFunctionType", <ype::isFunctionType);
proto.addMethod("toString", <ype::toString);
}
Handle<Value> LType::isDoubleType(const Arguments& args) {
return Boolean::New(type()->isDoubleTy());
}
Handle<Value> LType::isFunctionType(const Arguments& args) {
return Boolean::New(type()->isFunctionTy());
}
Handle<Value> LType::toString(const Arguments& args) {
std::string s("<Type ");
llvm::raw_string_ostream os(s);
type()->print(os);
os << ">";
return String::New(os.str().c_str());
}
// ----- LFunctionType
NodeProto<LFunctionType> LFunctionType::proto("FunctionType");
void LFunctionType::init() {
proto.inherit(LType::proto);
proto.addMethod("isVarArg", &LFunctionType::isVarArg);
proto.addMethod("getNumParams", &LFunctionType::getNumParams);
proto.addMethod("getParamType", &LFunctionType::getParamType);
}
Handle<Value> LFunctionType::isVarArg(const Arguments& args) {
return Boolean::New(functionType()->isVarArg());
}
Handle<Value> LFunctionType::getNumParams(const Arguments& args) {
return Integer::New(functionType()->getNumParams());
}
Handle<Value> LFunctionType::getParamType(const Arguments& args) {
CHECK_ARG_COUNT("getParamType", 1, 1, "index: Number");
CHECK_ARG_NUMBER(0);
unsigned int index = (unsigned int) args[0]->ToNumber()->Value();
return LType::create(functionType()->getParamType(index))->handle_;
}
| 28.140351 | 69 | 0.714464 |
23bf978e1a5d09fea9cb909b5ec53ef5d141c86e | 1,564 | cpp | C++ | gui/NativeWindow.cpp | razaqq/PotatoAlert | 4dfb54a7841ca71d8dbf58620173f2a9fc1886f2 | [
"MIT"
] | 20 | 2020-06-16T01:30:29.000Z | 2022-03-08T14:54:30.000Z | gui/NativeWindow.cpp | razaqq/PotatoAlert | 4dfb54a7841ca71d8dbf58620173f2a9fc1886f2 | [
"MIT"
] | 26 | 2019-07-15T10:49:47.000Z | 2022-02-16T19:25:48.000Z | gui/NativeWindow.cpp | razaqq/PotatoAlert | 4dfb54a7841ca71d8dbf58620173f2a9fc1886f2 | [
"MIT"
] | 5 | 2020-06-16T01:31:03.000Z | 2022-01-22T19:43:48.000Z | // Copyright 2020 <github.com/razaqq>
#include <QWidget>
#include <QVBoxLayout>
#include <QMainWindow>
#include <QWindow>
#include "NativeWindow.hpp"
#include "TitleBar.hpp"
#include "Config.hpp"
#include "FramelessWindowsManager.hpp"
using PotatoAlert::NativeWindow;
NativeWindow::NativeWindow(QMainWindow* mainWindow) : QWidget()
{
this->mainWindow = mainWindow;
this->mainWindow->setParent(this);
this->init();
}
void NativeWindow::closeEvent(QCloseEvent* event)
{
PotatoConfig().set<int>("window_height", this->height());
PotatoConfig().set<int>("window_width", this->width());
PotatoConfig().set<int>("window_x", this->x());
PotatoConfig().set<int>("window_y", this->y());
QWidget::closeEvent(event);
}
void NativeWindow::init()
{
this->createWinId();
QWindow* w = this->windowHandle();
this->titleBar->setFixedHeight(23);
for (auto& o : this->titleBar->getIgnores())
FramelessWindowsManager::addIgnoreObject(w, o);
FramelessWindowsManager::addWindow(w);
FramelessWindowsManager::setBorderWidth(w, borderWidth);
FramelessWindowsManager::setBorderHeight(w, borderWidth);
FramelessWindowsManager::setTitleBarHeight(w, this->titleBar->height());
auto layout = new QVBoxLayout;
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(0);
layout->addWidget(this->titleBar);
layout->addWidget(this->mainWindow);
this->setLayout(layout);
this->resize(PotatoConfig().get<int>("window_width"), PotatoConfig().get<int>("window_height"));
this->move(PotatoConfig().get<int>("window_x"), PotatoConfig().get<int>("window_y"));
}
| 26.508475 | 97 | 0.734655 |
23c3004cf0c9368068db9a38c09ea79a4e2a8414 | 1,558 | cpp | C++ | basic/tree/print_all_ancestors.cpp | sanjosh/smallprogs | 8acf7a357080b9154b55565be7c7667db0d4049b | [
"Apache-2.0"
] | 7 | 2017-02-28T06:33:43.000Z | 2021-12-17T04:58:19.000Z | basic/tree/print_all_ancestors.cpp | sanjosh/smallprogs | 8acf7a357080b9154b55565be7c7667db0d4049b | [
"Apache-2.0"
] | null | null | null | basic/tree/print_all_ancestors.cpp | sanjosh/smallprogs | 8acf7a357080b9154b55565be7c7667db0d4049b | [
"Apache-2.0"
] | 3 | 2017-02-28T06:33:30.000Z | 2021-02-25T09:42:31.000Z |
/*
http://en.wikipedia.org/wiki/Level_ancestor_problem
Given a Binary Tree and a key, write a function that prints all the ancestors of the key in the given binary tree.
For example, if the given tree is following Binary Tree and key is 7, then your function should print 4, 2 and 1.
1
/ \
2 3
/ \
4 5
/
7
Thanks to Mike , Sambasiva and wgpshashank for their contribution.
*/
#include <iostream>
#include <stdlib.h>
using namespace std;
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct Node
{
int data;
Node* left = nullptr;
Node* right = nullptr;
Node(int d) : data(d) { }
};
struct Algo
{
int data;
Algo(int d) : data(d) {}
bool predicate(const Node* n)
{
return (n->data == this->data);
}
void postProcess(const Node* p)
{
cout << p->data << endl;
}
};
bool preorder(const Node* current, Algo& a)
{
if (current == nullptr)
{
return false;
}
if (a.predicate(current))
{
return true;
}
auto x = preorder(current->left, a);
auto y = preorder(current->right, a);
if (x || y) {
a.postProcess(current);
}
return x || y;
}
int main()
{
Algo a(4);
Node *root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->left->left->left = new Node(7);
preorder(root, a);
}
| 17.120879 | 114 | 0.560334 |
23c9ace5e859445761efa5495bdc621173051908 | 20,355 | cpp | C++ | src/client/vhsm_admin/vhsm_admin.cpp | OSLL/vhsm | a06820919438f11be25df05978dcb679615f5b0b | [
"MIT"
] | 8 | 2015-09-27T01:31:25.000Z | 2020-10-29T17:05:12.000Z | src/client/vhsm_admin/vhsm_admin.cpp | OSLL/vhsm | a06820919438f11be25df05978dcb679615f5b0b | [
"MIT"
] | null | null | null | src/client/vhsm_admin/vhsm_admin.cpp | OSLL/vhsm | a06820919438f11be25df05978dcb679615f5b0b | [
"MIT"
] | 2 | 2015-05-20T18:54:14.000Z | 2021-11-04T19:40:18.000Z | #include <iostream>
#include <fstream>
#include <cstring>
#include <cstdlib>
#include <ctime>
#include "vhsm_api_prototype/common.h"
#include "vhsm_api_prototype/key_mgmt.h"
#include "vhsm_api_prototype/mac.h"
#include "vhsm_api_prototype/digest.h"
#define BUF_SIZE 4096
#define BUF_TIME_SIZE 256
#define HELP_BASE 1
#define HELP_GENERATE 2
#define HELP_IMPORT 4
#define HELP_KEYINFO 8
#define HELP_DELETE 16
#define HELP_HMAC 32
#define EXIT_OK 0
#define EXIT_BAD_ARGS 1
#define EXIT_VHSM_ERR 2
#define CMD_UNKNOWN 0
#define CMD_HELP 1
#define CMD_GENERATE 2
#define CMD_IMPORT 3
#define CMD_KEYINFO 4
#define CMD_DELETE 5
#define CMD_HMAC 6
//------------------------------------------------------------------------------
void showHelp(int sections) {
std::cout << "VHSM administration tool" << std::endl;
if(sections & HELP_BASE) {
std::cout << "List of available commands. Use 'vhsm_admin <command> help' for details." << std::endl;
std::cout << "generate - generates key with the given key length and optional key purpose" << std::endl;
std::cout << " and key id; returns the key id" << std::endl;
std::cout << "import - imports key or key-file with the given key length and optional" << std::endl;
std::cout << " key purpose and key id; returns the key id" << std::endl;
std::cout << "delete - deletes key with the given key id" << std::endl;
std::cout << "keyinfo - prints information about user keys" << std::endl;
std::cout << "hmac - computes hmac of the given file with the specified vhsm-key" << std::endl;
}
if(sections & HELP_GENERATE) {
std::cout << "vhsm_admin generate <user> <password> <key length> [--purpose=value] [--keyid=id]" << std::endl;
std::cout << "Generates key with the given key length." << std::endl;
std::cout << "Options:" << std::endl;
std::cout << "purpose - integer key purpose; default value: 0;" << std::endl;
std::cout << "keyid - user-defined id for the new key;" << std::endl;
std::cout << "VHSM generates key id if it's not specified. Returns id of the newly generated key" << std::endl;
}
if(sections & HELP_IMPORT) {
std::cout << "vhsm_admin import <user> <password> <--file=path> [--purpose=value] [--keyid=id]" << std::endl;
std::cout << "vhsm_admin import <user> <password> <--key=key> [--purpose=value] [--keyid=id]" << std::endl;
std::cout << "Imports specified key or key-file." << std::endl;
std::cout << "Options:" << std::endl;
std::cout << "purpose - key purpose; default value: 0;" << std::endl;
std::cout << "keyid - user-defined id for the new key;" << std::endl;
std::cout << "VHSM generates key id if it's not specified. Returns id of the imported key" << std::endl;
}
if(sections & HELP_KEYINFO) {
std::cout << "vhsm_admin keyinfo <user> <password> [ids...]" << std::endl;
std::cout << "Prints information about keys for the specified user." << std::endl;
std::cout << "Options:" << std::endl;
std::cout << "ids - return information only for the specified list of key ids" << std::endl;
}
if(sections & HELP_DELETE) {
std::cout << "vhsm_admin delete <user> <password> <keyid>" << std::endl;
std::cout << "Deletes key with the given key id" << std::endl;;
}
if(sections & HELP_HMAC) {
std::cout << "vhsm_admin hmac <user> <password> <--file=path> <--keyid=id> [--md=sha1] [-b|-h]" << std::endl;
std::cout << "Computes hmac for the specified file using specified key stored in vhsm" << std::endl;
std::cout << "Options:" << std::endl;
std::cout << "file - path to the file" << std::endl;
std::cout << "keyid - id of the key to use in hmac" << std::endl;
std::cout << "md - digest algorithm to use in hmac. Only SHA1 is currently supported" << std::endl;
std::cout << "-b - output in binary format" << std::endl;
std::cout << "-h - output in hex format (default)" << std::endl;
std::cout << "Prints hmac digest of the file in hex or binary format" << std::endl;
}
}
//------------------------------------------------------------------------------
/*
void create_user(int argc, char ** argv) {
if (3 != argc) {
show_help();
return;
}
VhsmStorage storage(argv[0]);
if(storage.createUser(argv[1], argv[2])) {
std::cout << "Unable to create user" << std::endl;
}
}
void init_root(int argc, char ** argv) {
if (1 != argc) {
show_help();
return;
}
std::string path = argv[0];
mkdir(path.c_str(), 0777);
std::cout << "Initializing database at: " << path << std::endl;
VhsmStorage storage(path);
if(!storage.initDatabase()) {
std::cout << "Unable to init database" << std::endl;
}
}
*/
//------------------------------------------------------------------------------
static int commandId(const std::string &str) {
if(str == "help" || str == "--help" || str == "-h") return CMD_HELP;
if(str == "generate") return CMD_GENERATE;
if(str == "import") return CMD_IMPORT;
if(str == "keyinfo") return CMD_KEYINFO;
if(str == "delete") return CMD_DELETE;
if(str == "hmac") return CMD_HMAC;
return CMD_UNKNOWN;
}
//------------------------------------------------------------------------------
static bool vhsmEnter(vhsm_session &s, const std::string &username, const std::string &password) {
if(vhsm_start_session(&s) != VHSM_RV_OK) {
std::cout << "Error: unable to start vhsm session" << std::endl;
return false;
}
vhsm_credentials user;
memset(user.username, 0, sizeof(user.username));
memset(user.password, 0, sizeof(user.password));
strncpy(user.username, username.c_str(), std::min(username.size(), sizeof(user.username)));
strncpy(user.password, password.c_str(), std::min(password.size(), sizeof(user.password)));
if(vhsm_login(s, user) != VHSM_RV_OK) {
std::cout << "Error: unable to login user" << std::endl;
vhsm_end_session(s);
return false;
}
return true;
}
static void vhsmExit(vhsm_session &s) {
vhsm_logout(s);
vhsm_end_session(s);
}
static vhsm_key_id vhsmGetKeyID(const std::string &keyID) {
vhsm_key_id id;
memset(id.id, 0, sizeof(id.id));
if(!keyID.empty()) strncpy((char*)id.id, keyID.c_str(), std::min(keyID.size(), sizeof(id.id)));
return id;
}
static std::string vhsmErrorCode(int ec) {
switch(ec) {
case VHSM_RV_OK: return "no error";
case VHSM_RV_KEY_ID_OCCUPIED: return "key id occupied";
case VHSM_RV_KEY_NOT_FOUND: return "key id not found";
case VHSM_RV_BAD_BUFFER_SIZE: return "bad buffer size";
case VHSM_RV_BAD_SESSION: return "bad session";
case VHSM_RV_NOT_AUTHORIZED: return "user is not authorized";
case VHSM_RV_BAD_CREDENTIALS: return "bad username or password";
case VHSM_RV_BAD_DIGEST_METHOD: return "unsupported digest method requested";
case VHSM_RV_MAC_INIT_ERR: return "unable to init mac";
case VHSM_RV_BAD_MAC_METHOD: return "unsupported mac method requested";
case VHSM_RV_MAC_NOT_INITIALIZED: return "mac context is not initialized";
case VHSM_RV_BAD_ARGUMENTS: return "bad arguments";
default: return "unknown error";
}
}
//------------------------------------------------------------------------------
static int generateKey(int argc, char **argv) {
if(argc < 3 || argc > 5) {
showHelp(HELP_GENERATE);
return EXIT_BAD_ARGS;
}
int keyLength = std::strtol(argv[2], NULL, 10);
int keyPurpose = 0;
std::string keyID = "";
for(int i = 3; i < argc; ++i) {
std::string arg(argv[i]);
size_t vpos = arg.find('=');
if(vpos == std::string::npos && arg.at(0) == '-') {
std::cout << "Error: value for option \'" << arg << "\' is not specified" << std::endl;
return EXIT_BAD_ARGS;
} else if(vpos == std::string::npos) {
std::cout << "Error: unknown option: " << argv[i] << std::endl;
return EXIT_BAD_ARGS;
}
if(arg.find("--purpose=") == 0) keyPurpose = std::strtol(argv[i] + vpos + 1, NULL, 10);
else if(arg.find("--keyid=") == 0) keyID = arg.substr(vpos + 1);
else {
std::cout << "Error: unknown option: " << argv[i] << std::endl;
showHelp(HELP_GENERATE);
return EXIT_BAD_ARGS;
}
}
vhsm_key_id kid = vhsmGetKeyID(keyID);
vhsm_session s;
if(!vhsmEnter(s, argv[0], argv[1])) return EXIT_VHSM_ERR;
int exitCode = EXIT_OK;
int res = vhsm_key_mgmt_generate_key(s, &kid, keyLength, keyPurpose);
if(res != VHSM_RV_OK) {
std::cout << "Error: unable to generate key: " << vhsmErrorCode(res) << std::endl;
exitCode = EXIT_VHSM_ERR;
} else {
std::cout << kid.id << std::endl;
}
vhsmExit(s);
return exitCode;
}
//------------------------------------------------------------------------------
static int importKey(int argc, char **argv) {
if(argc < 3 || argc > 5) {
showHelp(HELP_IMPORT);
return EXIT_BAD_ARGS;
}
int keyPurpose = 0;
std::string keyID = "";
std::string realKey = "";
std::string keyPath = "";
for(int i = 2; i < argc; ++i) {
std::string arg(argv[i]);
size_t vpos = arg.find('=');
if(vpos == std::string::npos && arg.at(0) == '-') {
std::cout << "Error: value for option \'" << arg << "\' is not specified" << std::endl;
return EXIT_BAD_ARGS;
} else if(vpos == std::string::npos) {
std::cout << "Error: unknown option: " << argv[i] << std::endl;
return EXIT_BAD_ARGS;
}
if(arg.find("--purpose=") == 0) keyPurpose = std::strtol(argv[i] + vpos + 1, NULL, 10);
else if(arg.find("--keyid=") == 0) keyID = arg.substr(vpos + 1);
else if(arg.find("--key=") == 0) realKey = arg.substr(vpos + 1);
else if(arg.find("--file=") == 0) keyPath = arg.substr(vpos + 1);
else {
std::cout << "Error: unknown argument: " << argv[i] << std::endl;
showHelp(HELP_IMPORT);
return EXIT_BAD_ARGS;
}
}
if((!realKey.empty() && !keyPath.empty()) || (realKey.empty() && keyPath.empty())) {
std::cout << "Error: bad arguments" << std::endl;
showHelp(HELP_IMPORT);
return EXIT_BAD_ARGS;
}
if(!keyPath.empty()) {
std::ifstream keyIn(keyPath.c_str(), std::ifstream::in | std::ifstream::binary);
if(!keyIn.is_open()) {
std::cout << "Error: unable to open key file: " << keyPath.c_str() << std::endl;
return EXIT_BAD_ARGS;
}
char buf[BUF_SIZE];
while(!keyIn.eof()) {
size_t ln = keyIn.readsome(buf, BUF_SIZE);
if(ln == 0) break;
realKey.append(std::string(buf, ln));
}
keyIn.close();
}
if(realKey.size() > VHSM_MAX_DATA_LENGTH) {
std::cout << "Error: unsupported key length; current max key length: " << VHSM_MAX_DATA_LENGTH << " bytes" << std::endl;
return EXIT_BAD_ARGS;
}
vhsm_session s;
if(!vhsmEnter(s, argv[0], argv[1])) return EXIT_VHSM_ERR;
vhsm_key key;
vhsm_key_id newKeyID;
key.id = vhsmGetKeyID(keyID);
key.key_data = const_cast<char*>(realKey.data());
key.data_size = realKey.size();
int exitCode = EXIT_OK;
int res = vhsm_key_mgmt_create_key(s, key, &newKeyID, keyPurpose);
if(res != VHSM_RV_OK) {
std::cout << "Error: unable to generate key: " << vhsmErrorCode(res) << std::endl;
exitCode = EXIT_VHSM_ERR;
} else {
std::cout << newKeyID.id << std::endl;
}
vhsmExit(s);
return exitCode;
}
//------------------------------------------------------------------------------
static std::string timeToString(uint64_t secs) {
tm *rawTime = gmtime((time_t*)&secs);
char timeBuf[BUF_TIME_SIZE];
size_t ln = std::strftime(timeBuf, BUF_TIME_SIZE, "%FT%T%z", rawTime);
return std::string(timeBuf, ln);
}
static int getKeyInfo(int argc, char **argv) {
if(argc < 2) {
showHelp(HELP_KEYINFO);
return EXIT_BAD_ARGS;
}
vhsm_session s;
if(!vhsmEnter(s, argv[0], argv[1])) return EXIT_VHSM_ERR;
vhsm_key_info *keyInfo = 0;
unsigned int keyCount = 0;
int exitCode = EXIT_VHSM_ERR;
if(argc == 2) {
int res = vhsm_key_mgmt_get_key_info(s, NULL, &keyCount);
if(res != VHSM_RV_OK) {
std::cout << "Error: unable to get key count: " << vhsmErrorCode(res) << std::endl;
goto vhsm_exit;
}
if(keyCount == 0) {
std::cout << "No keys found for user: " << argv[0] << std::endl;
goto vhsm_exit;
}
keyInfo = new vhsm_key_info[keyCount];
res = vhsm_key_mgmt_get_key_info(s, keyInfo, &keyCount);
if(res != VHSM_RV_OK) {
std::cout << "Error: unable to get key info: " << vhsmErrorCode(res) << std::endl;
keyCount = 0;
} else {
exitCode = EXIT_OK;
}
} else {
keyCount = argc - 2;
keyInfo = new vhsm_key_info[keyCount];
unsigned int realKeyCount = 0;
for(unsigned int i = 0; i < keyCount; ++i) {
vhsm_key_id keyID;
memset(keyID.id, 0, sizeof(keyID.id));
strncpy((char*)keyID.id, argv[i + 2], std::min(strlen(argv[i + 2]), sizeof(keyID.id)));
if(vhsm_key_mgmt_get_key_info(s, keyID, &keyInfo[realKeyCount]) != VHSM_RV_OK) {
std::cout << "Error: key with id \'" << keyID.id << "\' not found" << std::endl;
} else {
realKeyCount++;
}
}
keyCount = realKeyCount;
}
if(keyCount > 0) std::cout << "Key ID\t\t\tLength\tPurpose\tImport date" << std::endl;
for(unsigned int i = 0; i < keyCount; ++i) {
std::cout << keyInfo[i].key_id.id << "\t";
size_t idLength = strlen((char*)keyInfo[i].key_id.id);
if(idLength < 16) std::cout << "\t";
if(idLength < 8) std::cout << "\t";
std::cout << keyInfo[i].length << "\t";
std::cout << keyInfo[i].purpose << "\t";
std::cout << timeToString(keyInfo[i].import_date) << std::endl;
}
delete[] keyInfo;
vhsm_exit:
vhsmExit(s);
return exitCode;
}
//------------------------------------------------------------------------------
static int deleteKey(int argc, char **argv) {
if(argc != 3) {
showHelp(HELP_DELETE);
return EXIT_BAD_ARGS;
}
vhsm_session s;
if(!vhsmEnter(s, argv[0], argv[1])) return EXIT_VHSM_ERR;
vhsm_key_id keyId = vhsmGetKeyID(argv[2]);
int exitCode = EXIT_OK;
int res = vhsm_key_mgmt_delete_key(s, keyId);
if(res != VHSM_RV_OK) {
std::cout << "Key with id '" << argv[2] << "' not found" << std::endl;
exitCode = EXIT_VHSM_ERR;
} else {
std::cout << "Key with id '" << argv[2] << "' was successfully deleted" << std::endl;
}
vhsmExit(s);
return exitCode;
}
//------------------------------------------------------------------------------
static bool setDigest(vhsm_mac_method &mac, const std::string &digestName) {
if(digestName == "sha1") {
vhsm_digest_method *dm = new vhsm_digest_method;
dm->digest_method = VHSM_DIGEST_SHA1;
dm->method_params = NULL;
mac.method_params = dm;
return true;
}
return false;
}
static void freeDigest(vhsm_mac_method &mac, const std::string &digestName) {
if(digestName == "sha1") {
delete (vhsm_digest_method*)mac.method_params;
}
}
static int computeHMAC(int argc, char **argv) {
if(argc < 4 || argc > 6) {
showHelp(HELP_HMAC);
return EXIT_BAD_ARGS;
}
std::string keyID = "";
std::string filePath = "";
std::string mdAlgName = "sha1";
bool binOutput = false;
for(int i = 2; i < argc; ++i) {
std::string arg(argv[i]);
if(arg == "-b") {
binOutput = true;
continue;
} else if(arg == "-h") {
binOutput = false;
continue;
}
size_t vpos = arg.find('=');
if(vpos == std::string::npos && arg.at(0) == '-') {
std::cout << "Error: value for option \'" << arg << "\' is not specified" << std::endl;
return EXIT_BAD_ARGS;
} else if(vpos == std::string::npos) {
std::cout << "Error: unknown option: " << arg << std::endl;
return EXIT_BAD_ARGS;
}
if(arg.find("--keyid=") == 0) keyID = arg.substr(vpos + 1);
else if(arg.find("--file=") == 0) filePath = arg.substr(vpos + 1);
else if(arg.find("--md=") == 0) mdAlgName = arg.substr(vpos + 1);
else {
std::cout << "Error: unknown argument: " << argv[i] << std::endl;
return EXIT_BAD_ARGS;
}
}
if(filePath.empty() || keyID.empty()) {
std::cout << "Error one of the required arguments is not specified" << std::endl;
return EXIT_BAD_ARGS;
}
vhsm_key_id vkid = vhsmGetKeyID(keyID);
vhsm_mac_method macMethod = {VHSM_MAC_HMAC, 0, vkid};
if(!setDigest(macMethod, mdAlgName)) {
std::cout << "Error: unsupported digest method: " << mdAlgName << std::endl;
return EXIT_BAD_ARGS;
}
vhsm_session s;
if(!vhsmEnter(s, argv[0], argv[1])) {
freeDigest(macMethod, mdAlgName);
return EXIT_VHSM_ERR;
}
std::ifstream fileIn;
unsigned int md_size = 0;
unsigned char *md = NULL;
int exitCode = EXIT_VHSM_ERR;
int res = vhsm_mac_init(s, macMethod);
if(res != VHSM_RV_OK) {
std::cout << "Error: unable to init mac: " << vhsmErrorCode(res) << std::endl;
goto cleanup;
}
fileIn.open(filePath.c_str(), std::ifstream::in | std::ifstream::binary);
if(!fileIn.is_open()) {
std::cout << "Error: unable to open file: " << filePath << std::endl;
exitCode = EXIT_BAD_ARGS;
goto cleanup;
}
char buf[VHSM_MAX_DATA_LENGTH];
while(!fileIn.eof()) {
size_t ln = fileIn.readsome(buf, VHSM_MAX_DATA_LENGTH);
if(ln == 0) break;
res = vhsm_mac_update(s, (unsigned char*)buf, ln);
if(res != VHSM_RV_OK) {
std::cout << "Error: vhsm_mac_update: " << vhsmErrorCode(res) << std::endl;
fileIn.close();
goto cleanup;
}
}
fileIn.close();
res = vhsm_mac_end(s, NULL, &md_size);
if(res != VHSM_RV_BAD_BUFFER_SIZE) {
std::cout << "Error: failed to obtain mac size" << std::endl;
goto cleanup;
}
md = new unsigned char[md_size];
res = vhsm_mac_end(s, md, &md_size);
if(res != VHSM_RV_OK) {
std::cout << "Error: failed to obtain mac: " << vhsmErrorCode(res) << std::endl;
delete[] md;
goto cleanup;
}
if(binOutput) {
for(unsigned int i = 0; i < md_size; ++i) std::cout << md[i];
} else {
std::cout << "0x" << std::hex;
for(unsigned int i = 0; i < md_size; ++i) std::cout << (int)md[i];
std::cout << std::dec;
}
std::cout << std::endl;
delete[] md;
exitCode = EXIT_OK;
cleanup:
freeDigest(macMethod, mdAlgName);
vhsmExit(s);
return exitCode;
}
//------------------------------------------------------------------------------
int main(int argc, char **argv) {
if(argc < 3) {
showHelp(HELP_BASE);
return EXIT_BAD_ARGS;
}
switch(commandId(argv[1])) {
case CMD_HELP:
showHelp(HELP_BASE);
break;
case CMD_GENERATE:
return generateKey(argc - 2, argv + 2);
case CMD_IMPORT:
return importKey(argc - 2, argv + 2);
case CMD_DELETE:
return deleteKey(argc - 2, argv + 2);
case CMD_KEYINFO:
return getKeyInfo(argc - 2, argv + 2);
case CMD_HMAC:
return computeHMAC(argc - 2, argv + 2);
default:
std::cout << "Unknown command: " << argv[1] << std::endl;
showHelp(HELP_BASE);
}
return EXIT_OK;
}
| 34.794872 | 128 | 0.552837 |
23cb33ca493b6d2d59fc46ba0968a4adb2718e58 | 1,922 | cpp | C++ | 584 Bowling.cpp | zihadboss/UVA-Solutions | 020fdcb09da79dc0a0411b04026ce3617c09cd27 | [
"Apache-2.0"
] | 86 | 2016-01-20T11:36:50.000Z | 2022-03-06T19:43:14.000Z | 584 Bowling.cpp | Mehedishihab/UVA-Solutions | 474fe3d9d9ba574b97fd40ca5abb22ada95654a1 | [
"Apache-2.0"
] | null | null | null | 584 Bowling.cpp | Mehedishihab/UVA-Solutions | 474fe3d9d9ba574b97fd40ca5abb22ada95654a1 | [
"Apache-2.0"
] | 113 | 2015-12-04T06:40:57.000Z | 2022-02-11T02:14:28.000Z | #include <cstdio>
int handle(char current, char previous, char twoPrevious, bool addOwnScore)
{
int baseScore(0);
int score = 0;
if (current == 'X')
{
baseScore = 10;
}
else if (current == '/')
{
baseScore = 10 - (previous - '0');
}
else
{
baseScore = current - '0';
}
if (addOwnScore)
score = baseScore;
if (previous == '/' || previous == 'X')
score += baseScore;
if (twoPrevious == 'X')
score += baseScore;
return score;
}
const int countedThrows = 20;
int main()
{
char first;
while (scanf(" %c", &first), first != 'G')
{
char current = first, previous = ' ', twoPrevious = ' ';
int score;
score = handle(current, previous, twoPrevious, true);
previous = current;
int bonusThrows = 0;
for (int i = (current == 'X') ? 2 : 1; i < countedThrows; ++i)
{
scanf(" %c", ¤t);
score += handle(current, previous, twoPrevious, true);
twoPrevious = previous;
previous = current;
if (current == 'X')
{
if (i == 18) // First throw of the last round
bonusThrows = 2;
++i;
}
if (current == '/' && i == 19)
bonusThrows = 1;
}
for (int i = 0; i < bonusThrows; ++i)
{
scanf(" %c", ¤t);
score += handle(current, previous, twoPrevious, false);
twoPrevious = previous;
previous = current; // The just thrown ball does not improve score
if (previous == 'X')
previous = ' ';
}
printf("%d\n", score);
}
} | 22.091954 | 78 | 0.426639 |
23cd22431b7eedfa78296fb3cadd0a30e4363843 | 1,071 | cpp | C++ | dynamic_progrmmaing/coursera_primitive_calculator.cpp | BackAged/100_days_of_problem_solving | 2e24efad6d46804c4b31f415dbd69d7b80703a4f | [
"Apache-2.0"
] | 3 | 2020-06-15T10:39:34.000Z | 2021-01-17T14:03:37.000Z | dynamic_progrmmaing/coursera_primitive_calculator.cpp | BackAged/100_days_of_problem_solving | 2e24efad6d46804c4b31f415dbd69d7b80703a4f | [
"Apache-2.0"
] | null | null | null | dynamic_progrmmaing/coursera_primitive_calculator.cpp | BackAged/100_days_of_problem_solving | 2e24efad6d46804c4b31f415dbd69d7b80703a4f | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int choice[1000000];
int visited[1000000];
int optimal_sequence(int n) {
visited[0] = 0;
visited[1] = 0;
for (int i = 2; i <= n; i++) {
int ans = INT32_MAX;
int t1 = 1 + visited[i - 1];
if (t1 < ans) {
ans = t1;
choice[i] = i - 1;
}
if (i % 2 == 0) {
int t2 = 1 + visited[i/2];
if (t2 < ans) {
ans = t2;
choice[i] = i / 2;
}
}
if (i % 3 == 0) {
int t3 = 1 + visited[i/3];
if (t3 < ans) {
ans = t3;
choice[i] = i / 3;
}
}
visited[i] = min(ans, visited[i]);
}
return visited[n];
}
void printOptimalSolution(int n) {
if (n == 1) {
cout << 1 << " ";
return;
}
printOptimalSolution(choice[n]);
cout << n << " ";
}
int main() {
int n;
cin >> n;
fill_n(visited, 1000005, INT32_MAX);
int sequence = optimal_sequence(n);
cout << sequence << endl;
printOptimalSolution(n);
} | 18.789474 | 40 | 0.46592 |
23d0fb391b788e8e2f6eee11162b4c14efde0691 | 4,155 | cpp | C++ | kernel/system_tree/system_tree_root.cpp | martin-hughes/project_azalea | 28aa0183cde350073cf0167df3f51435ea409c8b | [
"MIT"
] | 13 | 2017-12-20T00:02:38.000Z | 2022-01-07T11:18:36.000Z | kernel/system_tree/system_tree_root.cpp | martin-hughes/project_azalea | 28aa0183cde350073cf0167df3f51435ea409c8b | [
"MIT"
] | 21 | 2016-09-21T16:50:39.000Z | 2020-04-12T12:58:19.000Z | kernel/system_tree/system_tree_root.cpp | martin-hughes/project_azalea | 28aa0183cde350073cf0167df3f51435ea409c8b | [
"MIT"
] | 6 | 2017-12-20T00:02:27.000Z | 2019-03-21T16:28:24.000Z | /// @file
/// @brief Implement `system_tree_root`, which handles the very root of the System Tree.
#include "klib/klib.h"
#include "system_tree/system_tree_root.h"
uint32_t system_tree_root::number_of_instances = 0;
system_tree_root::system_tree_root()
{
KL_TRC_ENTRY;
ASSERT(system_tree_root::number_of_instances == 0);
system_tree_root::number_of_instances++;
root = std::make_shared<system_tree_simple_branch>();
KL_TRC_EXIT;
}
system_tree_root::~system_tree_root()
{
KL_TRC_ENTRY;
// In some ways it'd be better if this destructor simply panic'd - but that'd confuse the test scripts. We need to be
// able to destroy the system tree in order to demonstrate that no memory is leaked.
KL_TRC_TRACE(TRC_LVL::ERROR, "System tree is being destroyed! Shouldn't occur\n");
system_tree_root::number_of_instances--;
KL_TRC_EXIT;
}
ERR_CODE system_tree_root::get_child(const std::string &name, std::shared_ptr<ISystemTreeLeaf> &child)
{
ERR_CODE result;
KL_TRC_ENTRY;
KL_TRC_TRACE(TRC_LVL::FLOW, "Look for name: ", name, "\n");
if (name[0] != '\\')
{
KL_TRC_TRACE(TRC_LVL::FLOW, "Incomplete path\n");
result = ERR_CODE::NOT_FOUND;
}
else if (name == "\\")
{
KL_TRC_TRACE(TRC_LVL::FLOW, "Return root element\n");
result = ERR_CODE::NO_ERROR;
child = root;
}
else
{
KL_TRC_TRACE(TRC_LVL::FLOW, "Find in rest of tree\n");
std::string remainder = name.substr(1);
result = root->get_child(remainder, child);
}
KL_TRC_TRACE(TRC_LVL::EXTRA, "Result: ", result, "\n");
KL_TRC_EXIT;
return result;
}
ERR_CODE system_tree_root::add_child(const std::string &name, std::shared_ptr<ISystemTreeLeaf> child)
{
ERR_CODE result;
KL_TRC_ENTRY;
if (name[0] != '\\')
{
KL_TRC_TRACE(TRC_LVL::FLOW, "Incomplete path\n");
result = ERR_CODE::INVALID_OP;
}
else
{
KL_TRC_TRACE(TRC_LVL::FLOW, "Add somewhere in rest of tree\n");
std::string remainder = name.substr(1);
result = root->add_child(remainder, child);
}
KL_TRC_TRACE(TRC_LVL::EXTRA, "Result: ", result, "\n");
KL_TRC_EXIT;
return result;
}
ERR_CODE system_tree_root::create_child(const std::string &name, std::shared_ptr<ISystemTreeLeaf> &child)
{
ERR_CODE result;
KL_TRC_ENTRY;
if (name[0] != '\\')
{
KL_TRC_TRACE(TRC_LVL::FLOW, "Incomplete path\n");
result = ERR_CODE::NOT_FOUND;
}
else
{
KL_TRC_TRACE(TRC_LVL::FLOW, "Find in rest of tree\n");
std::string remainder = name.substr(1);
result = root->create_child(remainder, child);
}
KL_TRC_TRACE(TRC_LVL::EXTRA, "Result: ", result, "\n");
KL_TRC_EXIT;
return result;
}
ERR_CODE system_tree_root::rename_child(const std::string &old_name, const std::string &new_name)
{
ERR_CODE result;
KL_TRC_ENTRY;
if ((old_name[0] != '\\') || (new_name[0] != '\\'))
{
KL_TRC_TRACE(TRC_LVL::FLOW, "Incomplete path\n");
result = ERR_CODE::NOT_FOUND;
}
else
{
KL_TRC_TRACE(TRC_LVL::FLOW, "Rename in rest of tree\n");
std::string old_remainder = old_name.substr(1);
std::string new_remainder = new_name.substr(1);
result = root->rename_child(old_remainder, new_remainder);
}
KL_TRC_TRACE(TRC_LVL::EXTRA, "Result: ", result, "\n");
KL_TRC_EXIT;
return result;
}
ERR_CODE system_tree_root::delete_child(const std::string &name)
{
ERR_CODE result;
KL_TRC_ENTRY;
if (name[0] != '\\')
{
KL_TRC_TRACE(TRC_LVL::FLOW, "Incomplete path\n");
result = ERR_CODE::NOT_FOUND;
}
else if (name == "\\")
{
KL_TRC_TRACE(TRC_LVL::FLOW, "Delete root element??\n");
result = ERR_CODE::INVALID_OP;
}
else
{
KL_TRC_TRACE(TRC_LVL::FLOW, "Find in rest of tree\n");
std::string remainder = name.substr(1);
result = root->delete_child(remainder);
}
KL_TRC_TRACE(TRC_LVL::EXTRA, "Result: ", result, "\n");
KL_TRC_EXIT;
return result;
}
std::pair<ERR_CODE, uint64_t> system_tree_root::num_children()
{
return root->num_children();
}
std::pair<ERR_CODE, std::vector<std::string>>
system_tree_root::enum_children(std::string start_from, uint64_t max_count)
{
return root->enum_children(start_from, max_count);
}
| 24.156977 | 119 | 0.681829 |
23d20a928719cc1b369db802f3439e83766f11f7 | 608 | cpp | C++ | cpp_models/libsrc/RLLib/visualization/RLLibViz/Framebuffer.cpp | akangasr/sdirl | b8b2bf34fea1b1f0c2f9961a9ad9c1ad34396f5b | [
"MIT"
] | null | null | null | cpp_models/libsrc/RLLib/visualization/RLLibViz/Framebuffer.cpp | akangasr/sdirl | b8b2bf34fea1b1f0c2f9961a9ad9c1ad34396f5b | [
"MIT"
] | null | null | null | cpp_models/libsrc/RLLib/visualization/RLLibViz/Framebuffer.cpp | akangasr/sdirl | b8b2bf34fea1b1f0c2f9961a9ad9c1ad34396f5b | [
"MIT"
] | null | null | null | /*
* Framebuffer.cpp
*
* Created on: Oct 12, 2013
* Author: sam
*/
#include "Framebuffer.h"
#include <cassert>
using namespace RLLibViz;
Framebuffer::Framebuffer()
{
}
Framebuffer::~Framebuffer()
{
}
void Framebuffer::draw(QPainter& painter)
{
if (points.empty() || points.size() < 1)
return;
QPainterPath path;
for (int i = 1; i < points.size(); i++)
{
path.moveTo(points.at(i-1));
path.lineTo(points.at(i));
}
painter.drawPath(path);
}
void Framebuffer::clear()
{
points.clear();
}
void Framebuffer::add(const Vec& p)
{
points.push_back(QPoint(p.x, p.y));
}
| 13.511111 | 42 | 0.626645 |
23d438cc7f53933fdb5f6abb578da26c5bf0b5ec | 10,552 | cpp | C++ | src/modules/dvb/dvb.cpp | ivanmurashko/kalinka | 58a3f774c414dfc408aa06f560dde455c2271c6b | [
"MIT"
] | null | null | null | src/modules/dvb/dvb.cpp | ivanmurashko/kalinka | 58a3f774c414dfc408aa06f560dde455c2271c6b | [
"MIT"
] | null | null | null | src/modules/dvb/dvb.cpp | ivanmurashko/kalinka | 58a3f774c414dfc408aa06f560dde455c2271c6b | [
"MIT"
] | null | null | null | /**
@file dvb.cpp
@brief This file is part of Kalinka mediaserver.
@author ipp <ivan.murashko@gmail.com>
Copyright (c) 2007-2012 Kalinka Team
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.
CHANGE HISTORY
@date
- 2008/07/26 created by ipp (Ivan Murashko)
- 2009/08/02 header was changed by header.py script
- 2010/01/06 header was changed by header.py script
- 2011/01/01 header was changed by header.py script
- 2012/02/03 header was changed by header.py script
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include "dvb.h"
#include "dvbdev.h"
#include "common.h"
#include "log.h"
#include "defines.h"
#include "infocommand.h"
#include "resourcecommand.h"
#include "traps.h"
#include "utils.h"
#include "exception.h"
#include "messages.h"
#include "snmp/factory.h"
#include "snmp/scalar.h"
#include "snmp/table.h"
using namespace klk;
using namespace klk::dvb;
/**
Module factory function
each module lib should define it
*/
IModulePtr klk_module_get(IFactory *factory)
{
return IModulePtr(new DVB(factory));
}
//
// DVB
//
// Constructor
// @param[in] factory the module factory
DVB::DVB(IFactory *factory) :
ModuleWithDB(factory, MODID),
m_processor(new Processor(factory))
{
BOOST_ASSERT(m_processor);
}
// Destructor
DVB::~DVB()
{
}
// Gets a human readable module name
const std::string DVB::getName() const throw()
{
return MODNAME;
}
// Does pre actions before start main loop
void DVB::preMainLoop()
{
// preparation staff
ModuleWithDB::preMainLoop();
m_processor->clean();
}
// Does post actions after main loop
void DVB::postMainLoop() throw()
{
m_processor->clean();
ModuleWithDB::postMainLoop();
}
// Register all processors
void DVB::registerProcessors()
{
ModuleWithDB::registerProcessors();
// processors
registerSync(
msg::id::DVBSTART,
boost::bind(&Processor::doStart, m_processor, _1, _2));
registerASync(
msg::id::DVBSTOP,
boost::bind(&Processor::doStop, m_processor, _1));
registerCLI(cli::ICommandPtr(new SetSourceCommand()));
registerCLI(cli::ICommandPtr(new InfoCommand()));
// register actions in a separate threads
registerTimer(boost::bind(&DVB::checkDVBDevs, this),
CHECKINTERVAL);
registerSNMP(boost::bind(&DVB::processSNMP, this, _1), MODID);
}
// Process changes at the DB
// @param[in] msg - the input message
void DVB::processDB(const IMessagePtr& msg)
{
BOOST_ASSERT(msg);
// update DVB devs info from DB
IDevList devs =
getFactory()->getResources()->getResourceByType(dev::DVB_ALL);
std::for_each(devs.begin(), devs.end(),
boost::bind(&IDev::update, _1));
}
// Checks DVB devs state
void DVB::checkDVBDevs()
{
IDevList devs =
getFactory()->getResources()->getResourceByType(dev::DVB_ALL);
std::for_each(devs.begin(), devs.end(),
boost::bind(&DVB::checkDVBDev, this, _1));
}
// Checks a DVB dev state
void DVB::checkDVBDev(const IDevPtr& dev)
{
BOOST_ASSERT(dev);
// check last update time
bool old = (static_cast<u_long>(time(NULL)) >
dev->getLastUpdateTime() + CHECKINTERVAL);
// first of all to clear lost lock flag
// to be able to use the dev
// dont update last update time
dev->setParam(dev::LOSTLOCK, 0, true);
if (dev->getState() == dev::IDLE)
{
// just clear lost lock flag
return;
}
// check update time
if (old)
{
getFactory()->getSNMP()->sendTrap(
TRAP_TIMEOUT,
dev->getStringParam(dev::UUID));
klk_log(KLKLOG_ERROR,
"Cannot retrive DVB device state within %d seconds. "
"Device UUID: '%s'", CHECKINTERVAL,
dev->getStringParam(dev::UUID).c_str());
// signal lost
m_processor->doSignalLost(dev);
return;
}
// check has lock
if (dev->getIntParam(dev::HASLOCK) == 0)
{
getFactory()->getSNMP()->sendTrap(
TRAP_NOSIGNAL,
dev->getStringParam(dev::UUID));
klk_log(KLKLOG_ERROR,
"DVB dev does not get a lock "
"Device name: '%s'",
dev->getStringParam(dev::NAME).c_str());
// signal lost
m_processor->doSignalLost(dev);
return;
}
// check signal
if (dev->getIntParam(dev::SIGNAL) < SIGNAL_THRESHOLD)
{
getFactory()->getSNMP()->sendTrap(
TRAP_BADSIGNAL,
dev->getStringParam(dev::UUID));
klk_log(KLKLOG_ERROR,
"Bad signal strength: Failed %d < %d. "
"Device name: '%s'",
signal, SIGNAL_THRESHOLD,
dev->getStringParam(dev::NAME).c_str());
#if 0 //FIXME!!! sometime can really have signal
if (signal == 0)
{
// signal lost
m_processor->doSignalLost(dev);
}
#endif
}
// check snr
int snr = dev->getIntParam(dev::SNR);
if (snr < SNR_THRESHOLD)
{
getFactory()->getSNMP()->sendTrap(
TRAP_BADSNR,
dev->getStringParam(dev::UUID));
klk_log(KLKLOG_ERROR,
"Bad SNR: %d < %d. "
"Device name: '%s'",
snr, SNR_THRESHOLD,
dev->getStringParam(dev::NAME).c_str());
}
// check ber
int ber = dev->getIntParam(dev::BER);
if (ber > BER_THRESHOLD)
{
getFactory()->getSNMP()->sendTrap(
TRAP_BADBER,
dev->getStringParam(dev::UUID));
klk_log(KLKLOG_ERROR,
"Bad BER: %d > %d. "
"Device name: '%s'",
ber, BER_THRESHOLD,
dev->getStringParam(dev::NAME).c_str());
}
// check unc
int unc = dev->getIntParam(dev::UNC);
if (unc > UNC_THRESHOLD)
{
getFactory()->getSNMP()->sendTrap(
TRAP_BADUNC,
dev->getStringParam(dev::UUID));
klk_log(KLKLOG_ERROR,
"Bad UNC: %d > %d. "
"Device name: '%s'",
unc, UNC_THRESHOLD,
dev->getStringParam(dev::NAME).c_str());
}
}
// Processes SNMP request
const snmp::IDataPtr DVB::processSNMP(const snmp::IDataPtr& req)
{
BOOST_ASSERT(req);
snmp::ScalarPtr reqreal =
boost::dynamic_pointer_cast<snmp::Scalar, snmp::IData>(req);
BOOST_ASSERT(reqreal);
const std::string reqstr = reqreal->getValue().toString();
// support only snmp::GETSTATUSTABLE
if (reqstr != snmp::GETSTATUSTABLE)
{
throw Exception(__FILE__, __LINE__,
"Unknown SNMP request: " + reqstr);
}
// create the response
// table with data
snmp::TablePtr table(new snmp::Table());
IDevList devs =
getFactory()->getResources()->getResourceByType(dev::DVB_ALL);
u_int count = 0;
for (IDevList::iterator dev = devs.begin(); dev != devs.end();
dev++, count++)
{
// klkIndex Counter32
// klkCardName DisplayString,
// klkCardType DisplayString,
// klkAdapter Integer32,
// klkFrontend Integer32,
// klkHasLock TruthValue,
// klkSignal Integer32,
// klkSNR Integer32,
// klkBER Integer32,
// klkUNC Counter32,
// klkRate Counter32
snmp::TableRow row;
try
{
row.push_back(count);
row.push_back((*dev)->getStringParam(dev::NAME));
const std::string type = (*dev)->getStringParam(dev::TYPE);
if (type == dev::DVB_S)
{
row.push_back(DVB_S_NAME);
}
else if (type == dev::DVB_T)
{
row.push_back(DVB_T_NAME);
}
else if (type == dev::DVB_C)
{
row.push_back(DVB_C_NAME);
}
else
{
row.push_back(NOTAVAILABLE);
}
row.push_back((*dev)->getIntParam(dev::ADAPTER));
row.push_back((*dev)->getIntParam(dev::FRONTEND));
if ((*dev)->hasParam(dev::HASLOCK))
{
row.push_back((*dev)->getIntParam(dev::HASLOCK));
row.push_back((*dev)->getIntParam(dev::SIGNAL));
row.push_back((*dev)->getIntParam(dev::SNR));
row.push_back((*dev)->getIntParam(dev::BER));
row.push_back((*dev)->getIntParam(dev::UNC));
}
else
{
row.push_back(0);
row.push_back(0);
row.push_back(0);
row.push_back(0);
row.push_back(0);
}
if ((*dev)->hasParam(dev::RATE))
row.push_back((*dev)->getIntParam(dev::RATE));
else
row.push_back(0);
}
catch(...)
{
row.clear();
row.push_back(count);
row.push_back(NOTAVAILABLE);
row.push_back(NOTAVAILABLE);
row.push_back(0);
row.push_back(0);
row.push_back(0);
row.push_back(0);
row.push_back(0);
row.push_back(0);
row.push_back(0);
row.push_back(0);
}
table->addRow(row);
}
return table;
}
| 27.479167 | 74 | 0.574204 |
23d6a587da9f98f0302567c4cba9190e4c1da9c8 | 5,196 | cpp | C++ | source/main.cpp | Matr1X22/Shannon-Fano_and_Huffman_data_compression | ea52ace4c5158531a498877c51bd034dec8e0e7f | [
"Apache-2.0"
] | null | null | null | source/main.cpp | Matr1X22/Shannon-Fano_and_Huffman_data_compression | ea52ace4c5158531a498877c51bd034dec8e0e7f | [
"Apache-2.0"
] | null | null | null | source/main.cpp | Matr1X22/Shannon-Fano_and_Huffman_data_compression | ea52ace4c5158531a498877c51bd034dec8e0e7f | [
"Apache-2.0"
] | 1 | 2022-03-19T21:05:09.000Z | 2022-03-19T21:05:09.000Z | #include <bits/stdc++.h>
#include <windows.h>
using namespace std;
HANDLE hOUTPUT = GetStdHandle(STD_OUTPUT_HANDLE);
void yellow(){SetConsoleTextAttribute(hOUTPUT, FOREGROUND_RED | FOREGROUND_GREEN);}
void white(){SetConsoleTextAttribute(hOUTPUT, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);}
void red(){SetConsoleTextAttribute(hOUTPUT, FOREGROUND_RED);}
void green(){SetConsoleTextAttribute(hOUTPUT, FOREGROUND_GREEN);}
struct Code
{
char a;
int p;
string q;
};
bool comp(Code a, Code b){return a.p > b.p;}
bool stcomp(pair <int, string> a, pair <int, string> b){return a.first > b.first;}
vector <Code> arr;
vector < pair <bool, int> > used(1000);
string first_s;
void text(string s)
{
yellow();
cout << s;
white();
}
void clear()
{
arr.clear();
for(int i = 0; i < used.size(); i++)
{
used[i].first = false;
used[i].second = 0;
}
}
void input1()
{
cin.ignore(256, '\n');
getline(cin, first_s);
for(int i = 0; i < first_s.size(); i++)
{
if(used[first_s[i] + 'a'].first == false)
{
used[first_s[i] + 'a'].first = true;
if(!arr.empty())
used[first_s[i] + 'a'].second = arr.size();
arr.push_back({first_s[i], 1, ""}); // a p q
}
else
arr[used[first_s[i] + 'a'].second].p++;
}
sort(arr.begin(), arr.end(), comp);
for(int i = 0; i < arr.size(); i++)
used[arr[i].a + 'a'].second = i;
}
void haffman_makebit()
{
vector < pair <int, string> > st;
for(int i = 0; i < arr.size(); i++)
{
string s = "";
s += arr[i].a;
st.push_back({arr[i].p, s});
}
sort(st.begin(), st.end(), stcomp);
if(st.size() == 1)
arr[0].q += '0';
while(st.size() != 1)
{
int minsum = 99999999, l, r;
for(int i = st.size() - 1; i > 0; i--)
{
if(st[i].first + st[i - 1].first < minsum)
{
minsum = st[i].first + st[i - 1].first;
l = i - 1, r = i;
if(minsum == 0) break;
}
}
for(int i = 0; i < st[l].second.size(); i++)
for(int j = 0; j < arr.size(); j++)
if(arr[j].a == st[l].second[i])
{
arr[j].q += '1';
break;
}
for(int i = 0; i < st[r].second.size(); i++)
for(int j = 0; j < arr.size(); j++)
if(arr[j].a == st[r].second[i])
{
arr[j].q += '0';
break;
}
st[l].second += st[r].second;
st[l].first += st[r].first;
st.erase(st.begin() + r);
}
for(int i = 0; i < arr.size(); i++)
reverse(arr[i].q.begin(), arr[i].q.end());
}
void fano_makebit(int begin, int end)
{
if(end - begin == 1)
return;
int minabs = -1, minpos = -1;
int left = 0, right = 0;
for(int i = begin; i < end; i++)
right += arr[i].p;
for(int i = begin; i < end; i++)
{
if(abs(left - right) < minabs || minabs == -1)
{
minabs = abs(left - right);
minpos = i;
}
left += arr[i].p;
right -= arr[i].p;
}
for(int i = minpos; i < end; i++)
arr[i].q += '0';
for(int i = minpos - 1; i >= begin; i--)
arr[i].q += '1';
if(end - begin <= 2)
return;
fano_makebit(minpos, end);
fano_makebit(begin, minpos);
}
void mainout()
{
text("\nLine length - ");
cout << first_s.size() << '\n';
text("Number of symbols - ");
cout << arr.size() << '\n';
text("Print \"P\"? Yes/No\n");
string inp;
cin >> inp;
bool flag = true;
if(inp == "No" || inp == "no" || inp == "2")
flag = false;
int sumbits = 0;
if(flag)
{
green();
cout << "A P Q\n";
white();
for(int i = 0; i < arr.size(); i++)
{
sumbits += arr[i].p * arr[i].q.size();
cout << arr[i].a << ' ' << arr[i].p << ' ' << arr[i].q << '\n';
}
}
else
{
green();
cout << "A Q\n";
white();
for(int i = 0; i < arr.size(); i++)
{
sumbits += arr[i].p * arr[i].q.size();
cout << arr[i].a << ' ' << arr[i].q << '\n';
}
}
cout << '\n';
text("Sum of bits - ");
cout << sumbits << '\n';
text("Bit`s cost - ");
cout << double(sumbits) / first_s.size() << '\n';
red();
for(int i = 0; i < first_s.size(); i++)
cout << arr[used[first_s[i] + 'a'].second].q;
cout << '\n';
green();
cout << "\nComplete!\n";
white();
cout << '\n';
}
void decrypt(string scripted)
{
red();
string pref = "";
for(int i = 0; i < scripted.size(); i++)
{
pref += scripted[i];
for(int j = 0; j < arr.size(); j++)
{
if(pref == arr[j].q)
{
cout << arr[j].a;
pref = "";
break;
}
}
}
}
signed main()
{
while(true)
{
text("1) Encrypt FANO 2) Encrypt HAFFMAN 3) Decrypt 4) Clear cmd 5) Stop\n");
char input;
cin >> input;
input -= '0';
if(input == 1)
{
text("Write a line\n");
input1();
fano_makebit(0, arr.size());
mainout();
}
else if(input == 2)
{
text("Write a line\n");
input1();
haffman_makebit();
mainout();
}
else if(input == 3)
{
text("Write the symbols with their codes\nWrite \"Stop\" when you end\n");
string s;
cin.ignore(256, '\n');
while(1)
{
getline(cin, s);
if(s == "Stop" || s == "stop")
break;
Code x;
x.a = s[0];
s.erase(s.begin(), s.begin() + 2);
x.q = s;
arr.push_back(x);
}
text("Write a binary line to decrypt\n");
cin >> first_s;
decrypt(first_s);
cout << "\n\n";
}
else if(input == 4)
system("cls");
else
{
red();
cout << "Stopped";
break;
}
clear();
}
return 0;
}
| 17.092105 | 100 | 0.518861 |
23da43ce423b5fbde6f832112ee703b5218515ca | 1,311 | cpp | C++ | src/process.cpp | hyper-make/SystemMonitor | ccc06c95b98475f18055b551cd45f39fbd96c0a8 | [
"MIT"
] | null | null | null | src/process.cpp | hyper-make/SystemMonitor | ccc06c95b98475f18055b551cd45f39fbd96c0a8 | [
"MIT"
] | null | null | null | src/process.cpp | hyper-make/SystemMonitor | ccc06c95b98475f18055b551cd45f39fbd96c0a8 | [
"MIT"
] | null | null | null | #include <unistd.h>
#include <cctype>
#include <sstream>
#include <string>
#include <vector>
#include "linux_parser.h"
#include "process.h"
using std::string;
using std::to_string;
using std::vector;
Process::Process(int p)
: pid(p),
user(LinuxParser::User(p)),
command(LinuxParser::Command(p)),
cpuUtilization(LinuxParser::CpuUtilization(p)),
ram(LinuxParser::Ram(p)),
upTime(LinuxParser::UpTime(p)){};
// TODO: Return this process's ID
int Process::Pid() { return pid; }
// TODO: Return this process's CPU utilization
float Process::CpuUtilization() { return cpuUtilization; }
// TODO: Return the command that generated this process
string Process::Command() { return command; }
// TODO: Return this process's memory utilization
string Process::Ram() { return ram; }
// TODO: Return the user (name) that generated this process
string Process::User() { return user; }
// TODO: Return the age of this process (in seconds)
long int Process::UpTime() { return upTime; }
// TODO: Overload the "less than" comparison operator for Process objects
// REMOVE: [[maybe_unused]] once you define the function
bool Process::operator<(Process const& a) const {
float x = a.ram.empty() ? 0 : std::stof(a.ram);
float y = ram.empty() ? 0 : std::stof(ram);
return x < y;
}
| 27.3125 | 73 | 0.690313 |
23deb62f8d3ee6616e5b5fe1e3f59b55af069ade | 2,464 | cpp | C++ | src/Base/DoubleSpinBox.cpp | roto5296/choreonoid | ffe12df8db71e32aea18833afb80dffc42c373d0 | [
"MIT"
] | 66 | 2020-03-11T14:06:01.000Z | 2022-03-23T23:18:27.000Z | src/Base/DoubleSpinBox.cpp | roto5296/choreonoid | ffe12df8db71e32aea18833afb80dffc42c373d0 | [
"MIT"
] | 12 | 2020-07-23T06:13:11.000Z | 2022-01-13T14:25:01.000Z | src/Base/DoubleSpinBox.cpp | roto5296/choreonoid | ffe12df8db71e32aea18833afb80dffc42c373d0 | [
"MIT"
] | 18 | 2020-07-17T15:57:54.000Z | 2022-03-29T13:18:59.000Z | #include "DoubleSpinBox.h"
#include <QKeyEvent>
using namespace cnoid;
DoubleSpinBox::DoubleSpinBox(QWidget* parent)
: QDoubleSpinBox(parent)
{
setKeyboardTracking(false);
isSettingValueInternally = false;
isUndoRedoKeyInputEnabled_ = false;
valueChangedByLastUserInput = false;
}
void DoubleSpinBox::setUndoRedoKeyInputEnabled(bool on)
{
isUndoRedoKeyInputEnabled_ = on;
if(on){
// Activate signal handlers
sigValueChanged();
sigEditingFinished();
}
}
void DoubleSpinBox::setValue(double val)
{
isSettingValueInternally = true;
QDoubleSpinBox::setValue(val);
isSettingValueInternally = false;
}
SignalProxy<void(double)> DoubleSpinBox::sigValueChanged()
{
if(!sigValueChanged_){
stdx::emplace(sigValueChanged_);
connect(this, (void(QDoubleSpinBox::*)(double)) &QDoubleSpinBox::valueChanged,
[this](double value){ onValueChanged(value); });
}
return *sigValueChanged_;
}
SignalProxy<void()> DoubleSpinBox::sigEditingFinished()
{
if(!sigEditingFinished_){
stdx::emplace(sigEditingFinished_);
connect(this, &QDoubleSpinBox::editingFinished,
[this](){ onEditingFinished(); });
}
return *sigEditingFinished_;
}
SignalProxy<void()> DoubleSpinBox::sigEditingFinishedWithValueChange()
{
if(!sigEditingFinishedWithValueChange_){
stdx::emplace(sigEditingFinishedWithValueChange_);
sigEditingFinished();
}
return *sigEditingFinishedWithValueChange_;
}
void DoubleSpinBox::onValueChanged(double value)
{
if(!isSettingValueInternally){
valueChangedByLastUserInput = true;
}
(*sigValueChanged_)(value);
}
void DoubleSpinBox::onEditingFinished()
{
(*sigEditingFinished_)();
if(sigEditingFinishedWithValueChange_){
if(valueChangedByLastUserInput){
(*sigEditingFinishedWithValueChange_)();
}
}
valueChangedByLastUserInput = false;
}
void DoubleSpinBox::keyPressEvent(QKeyEvent* event)
{
bool isUndoOrRedoKey = false;
if(isUndoRedoKeyInputEnabled_){
if(event->key() == Qt::Key_Z && event->modifiers() & Qt::ControlModifier){
isUndoOrRedoKey = true;
}
}
if(isUndoOrRedoKey){
if(valueChangedByLastUserInput){
onEditingFinished();
}
QWidget::keyPressEvent(event);
} else {
QDoubleSpinBox::keyPressEvent(event);
}
}
| 22.814815 | 86 | 0.676948 |
23e60ab5fbae97a04f5642bcb8bc617f26084126 | 51 | cpp | C++ | src/LoginInfo.cpp | NoSuchBoyException/QT-PureMVC | cc84e68ddc2666941af6970a4fab364ab74f5190 | [
"Apache-2.0"
] | 40 | 2016-06-20T12:22:42.000Z | 2022-03-10T03:20:00.000Z | src/LoginInfo.cpp | NoSuchBoyException/PureMVC_QT | cc84e68ddc2666941af6970a4fab364ab74f5190 | [
"Apache-2.0"
] | null | null | null | src/LoginInfo.cpp | NoSuchBoyException/PureMVC_QT | cc84e68ddc2666941af6970a4fab364ab74f5190 | [
"Apache-2.0"
] | 24 | 2017-01-03T13:18:04.000Z | 2022-03-20T01:24:41.000Z | #include "LoginInfo.h"
LoginInfo::LoginInfo()
{
}
| 8.5 | 22 | 0.686275 |
23ea38bae9e49e20a987deab48c375b42aa64b46 | 7,474 | cpp | C++ | src/bin/balanceHandler.cpp | D7ry/valhallaCombat | 07929d29a48401c2878a1ed5993b7bba14743c6f | [
"MIT"
] | 1 | 2022-01-19T07:13:48.000Z | 2022-01-19T07:13:48.000Z | src/bin/balanceHandler.cpp | D7ry/valhallaCombat | 07929d29a48401c2878a1ed5993b7bba14743c6f | [
"MIT"
] | null | null | null | src/bin/balanceHandler.cpp | D7ry/valhallaCombat | 07929d29a48401c2878a1ed5993b7bba14743c6f | [
"MIT"
] | 1 | 2022-01-19T07:13:52.000Z | 2022-01-19T07:13:52.000Z | #include "include/balanceHandler.h"
#include "include/reactionHandler.h"
#include "include/offsets.h"
#include "include/Utils.h"
inline const float balanceRegenTime = 6;//time it takes for balance to regen, in seconds.
void balanceHandler::update() {
//DEBUG("update");
/*if (garbageCollectionQueued) {
collectGarbage();
garbageCollectionQueued = false;
}*/
mtx_balanceBrokenActors.lock();
if (balanceBrokenActors.empty()) {//stop updating when there is 0 actor need to regen balance.
mtx_balanceBrokenActors.unlock();
//DEBUG("no balance broken actors, stop update");
ValhallaCombat::GetSingleton()->deactivateUpdate(ValhallaCombat::HANDLER::balanceHandler);
return;
}
//DEBUG("non-empty balance map");
//regenerate balance for all balance broken actors.
auto it = balanceBrokenActors.begin();
mtx_actorBalanceMap.lock();
while (it != balanceBrokenActors.end()) {
if (!actorBalanceMap.contains(*it)) { //edge case: actor's balance broken but no longer tracked on actor balance map.
//DEBUG("edge case");
it = balanceBrokenActors.erase(it);
continue;
}
//regen a single actor's balance.
auto* balanceData = &actorBalanceMap.find(*it)->second;
float regenVal = balanceData->first * *RE::Offset::g_deltaTime * 1 / balanceRegenTime;
//DEBUG(regenVal);
//DEBUG(a_balanceData.second);
//DEBUG(a_balanceData.first);
if (balanceData->second + regenVal >= balanceData->first) {//this regen exceeds actor's max balance.
//DEBUG("{}'s balance has recovered", (*it)->GetName());
balanceData->second = balanceData->first;//reset balance.
debuffHandler::GetSingleton()->quickStopStaminaDebuff(*it);
it = balanceBrokenActors.erase(it);
continue;
}
else {
//DEBUG("normal regen");
balanceData->second += regenVal;
}
it++;
}
mtx_actorBalanceMap.unlock();
mtx_balanceBrokenActors.unlock();
}
void balanceHandler::queueGarbageCollection() {
garbageCollectionQueued = true;
}
float balanceHandler::calculateMaxBalance(RE::Actor* a_actor) {
return a_actor->GetPermanentActorValue(RE::ActorValue::kHealth);
}
void balanceHandler::trackBalance(RE::Actor* a_actor) {
float maxBalance = calculateMaxBalance(a_actor);
mtx_actorBalanceMap.lock();
actorBalanceMap.emplace(a_actor, std::pair<float, float> {maxBalance, maxBalance});
mtx_actorBalanceMap.unlock();
}
void balanceHandler::untrackBalance(RE::Actor* a_actor) {
mtx_actorBalanceMap.lock();
actorBalanceMap.erase(a_actor);
mtx_actorBalanceMap.unlock();
}
void balanceHandler::collectGarbage() {
INFO("Cleaning up balance map...");
int ct = 0;
mtx_actorBalanceMap.lock();
auto it_balanceMap = actorBalanceMap.begin();
while (it_balanceMap != actorBalanceMap.end()) {
auto a_actor = it_balanceMap->first;
if (!a_actor || !a_actor->currentProcess || !a_actor->currentProcess->InHighProcess()) {
safeErase_BalanceBrokenActors(a_actor);
it_balanceMap = actorBalanceMap.erase(it_balanceMap);
ct++;
continue;
}
it_balanceMap++;
}
mtx_actorBalanceMap.unlock();
INFO("...done; cleaned up {} inactive actors.", ct);
}
void balanceHandler::reset() {
INFO("Reset all balance...");
mtx_actorBalanceMap.lock();
actorBalanceMap.clear();
mtx_actorBalanceMap.unlock();
mtx_balanceBrokenActors.lock();
balanceBrokenActors.clear();
mtx_balanceBrokenActors.unlock();
INFO("..done");
}
bool balanceHandler::isBalanceBroken(RE::Actor* a_actor) {
mtx_balanceBrokenActors.lock();
if (balanceBrokenActors.contains(a_actor)) {
mtx_balanceBrokenActors.unlock();
return true;
}
else {
mtx_balanceBrokenActors.unlock();
return false;
}
}
void balanceHandler::damageBalance(DMGSOURCE dmgSource, RE::Actor* a_aggressor, RE::Actor* a_victim, float damage) {
//DEBUG("damaging balance: aggressor: {}, victim: {}, damage: {}", aggressor->GetName(), victim->GetName(), damage);
mtx_actorBalanceMap.lock();
if (!actorBalanceMap.contains(a_victim)) {
mtx_actorBalanceMap.unlock();
trackBalance(a_victim);
damageBalance(dmgSource, a_aggressor, a_victim, damage);
return;
}
#define a_balanceData actorBalanceMap.find(a_victim)->second
//DEBUG("curr balance: {}", a_balanceData.second);
if (a_balanceData.second - damage <= 0) { //balance broken, ouch!
a_balanceData.second = 0;
mtx_actorBalanceMap.unlock();
mtx_balanceBrokenActors.lock();
if (!balanceBrokenActors.contains(a_victim)) {//if not balance broken already
//DEBUG("{}'s balance has broken", victim->GetName());
balanceBrokenActors.insert(a_victim);
if (dmgSource == DMGSOURCE::parry) {
reactionHandler::triggerStagger(a_aggressor, a_victim, reactionHandler::kLarge);
}
ValhallaCombat::GetSingleton()->activateUpdate(ValhallaCombat::HANDLER::balanceHandler);
}
else {//balance already broken, yet broken again, ouch!
//DEBUG("{}'s balance double broken", victim->GetName());
reactionHandler::triggerContinuousStagger(a_aggressor, a_victim, reactionHandler::kLarge);
}
mtx_balanceBrokenActors.unlock();
}
else {
//DEBUG("normal balance damage.");
a_balanceData.second -= damage;
mtx_actorBalanceMap.unlock();
mtx_balanceBrokenActors.lock();
if (balanceBrokenActors.contains(a_victim)) {
if (dmgSource == DMGSOURCE::powerAttack) {
reactionHandler::triggerStagger(a_aggressor, a_victim, reactionHandler::reactionType::kKnockBack);
}
else {
reactionHandler::triggerContinuousStagger(a_aggressor, a_victim, reactionHandler::kLarge);
}
}//if balance broken, trigger stagger.
else if (dmgSource == DMGSOURCE::powerAttack
&& !debuffHandler::GetSingleton()->isInDebuff(a_aggressor)) //or if is power attack and not in debuff
{
reactionHandler::triggerContinuousStagger(a_aggressor, a_victim, reactionHandler::kLarge);
}
mtx_balanceBrokenActors.unlock();
}
}
void balanceHandler::recoverBalance(RE::Actor* a_actor, float recovery) {
mtx_actorBalanceMap.lock();
if (!actorBalanceMap.contains(a_actor)) {
mtx_actorBalanceMap.unlock();
return;
}
float attempedRecovery = actorBalanceMap[a_actor].second + recovery;
if (attempedRecovery >= actorBalanceMap[a_actor].first) {//balance fully recovered.
actorBalanceMap[a_actor].second = actorBalanceMap[a_actor].first;
mtx_actorBalanceMap.unlock();
if (isBalanceBroken(a_actor)) {
safeErase_BalanceBrokenActors(a_actor);
debuffHandler::GetSingleton()->quickStopStaminaDebuff(a_actor);
}
}
else {
actorBalanceMap[a_actor].second = attempedRecovery;
mtx_actorBalanceMap.unlock();
}
}
void balanceHandler::processBalanceDamage(DMGSOURCE dmgSource, RE::TESObjectWEAP* weapon, RE::Actor* aggressor, RE::Actor* victim, float baseDamage) {
if (!settings::bBalanceToggle) {
return;
}
baseDamage *= 2;
if (isBalanceBroken(victim) && dmgSource < DMGSOURCE::bash) {
recoverBalance(victim, baseDamage * 1);
baseDamage = 0;
}
else {
if (debuffHandler::GetSingleton()->isInDebuff(victim)) {
baseDamage *= 1.5;
}
if (dmgSource == DMGSOURCE::parry) {
baseDamage *= 1.5;
}
if (victim->IsRangedAttacking() || ValhallaUtils::isCasting(victim)) {
baseDamage * 2.25;
}
}
damageBalance(dmgSource, aggressor, victim, baseDamage);
}
void balanceHandler::safeErase_ActorBalanceMap(RE::Actor* a_actor) {
mtx_actorBalanceMap.lock();
actorBalanceMap.erase(a_actor);
mtx_actorBalanceMap.unlock();
}
void balanceHandler::safeErase_BalanceBrokenActors(RE::Actor* a_actor) {
mtx_balanceBrokenActors.lock();
balanceBrokenActors.erase(a_actor);
mtx_balanceBrokenActors.unlock();
} | 32.637555 | 150 | 0.737624 |
23eae08214ee1ecabf369ec840d1dcb03d36ba1e | 1,138 | cpp | C++ | pbr/Mesh.cpp | chuxu1793/pbr-1 | c77d9bcc2c19637ab79382cbef3fc0e2a31b6560 | [
"MIT"
] | 51 | 2016-04-03T20:37:57.000Z | 2022-03-31T00:38:11.000Z | pbr/Mesh.cpp | chuxu1793/pbr-1 | c77d9bcc2c19637ab79382cbef3fc0e2a31b6560 | [
"MIT"
] | 2 | 2016-11-14T21:14:10.000Z | 2016-11-16T15:01:47.000Z | pbr/Mesh.cpp | chuxu1793/pbr-1 | c77d9bcc2c19637ab79382cbef3fc0e2a31b6560 | [
"MIT"
] | 9 | 2016-06-02T03:46:23.000Z | 2020-10-16T23:30:16.000Z | #include "Mesh.h"
#include <glbinding/gl/gl.h>
void Mesh::draw()
{
glBindVertexArray(m_VAO);
glDrawElements(GL_TRIANGLES, m_IndicesCount * 3, GL_UNSIGNED_INT, nullptr);
glBindVertexArray(0);
}
void Mesh::initialize(const std::vector<Vertex>& vertices, const std::vector<Triangle>& indices)
{
m_IndicesCount = indices.size();
glGenVertexArrays(1, &m_VAO);
glBindVertexArray(m_VAO);
{
glGenBuffers(1, &m_VBO);
glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), vertices.data(), GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), nullptr);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_TRUE, sizeof(Vertex), (void*)(sizeof(glm::vec3)));
glVertexAttribPointer(2, 2, GL_FLOAT, GL_TRUE, sizeof(Vertex), (void*)(2 * sizeof(glm::vec3)));
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
glGenBuffers(1, &m_EBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(Triangle), indices.data(), GL_STATIC_DRAW);
}
glBindVertexArray(0);
} | 31.611111 | 107 | 0.748682 |
23eb4c38cc7c876ace8bc06e105f134921e3f8b7 | 1,130 | cpp | C++ | src/CursATE/Curses/Field/detail/resizePadded.cpp | qiagen/LogATE | aa43595c89bf3bcaa302d8406e5ad789efc0e035 | [
"BSD-2-Clause"
] | null | null | null | src/CursATE/Curses/Field/detail/resizePadded.cpp | qiagen/LogATE | aa43595c89bf3bcaa302d8406e5ad789efc0e035 | [
"BSD-2-Clause"
] | null | null | null | src/CursATE/Curses/Field/detail/resizePadded.cpp | qiagen/LogATE | aa43595c89bf3bcaa302d8406e5ad789efc0e035 | [
"BSD-2-Clause"
] | 3 | 2021-01-12T18:52:49.000Z | 2021-01-19T17:48:50.000Z | #include "CursATE/Curses/Field/detail/resizePadded.hpp"
#include <But/assert.hpp>
namespace CursATE::Curses::Field::detail
{
VisibleSize resizePaddedVisibleSize(std::string const& in, size_t maxSize, size_t selectedElement)
{
if( in.size() <= maxSize )
return {0, selectedElement, in.size()};
if( selectedElement > in.size() )
BUT_THROW(SelectionOutOfRange, "requested element " << selectedElement << " in a string of length " << in.size());
const auto half = maxSize / 2;
auto start = 0u;
if( selectedElement > half )
start = selectedElement - half;
if( in.size() - start < maxSize )
start = in.size() - maxSize;
const auto offset = selectedElement - start;
BUT_ASSERT( offset <= maxSize && "offset it outside of display window" );
return {start, offset, maxSize};
}
std::string resizePadded(std::string const& in, const size_t maxSize, const size_t selectedElement)
{
if( in.size() <= maxSize )
{
auto tmp = in;
tmp.resize(maxSize, ' ');
return tmp;
}
const auto vs = resizePaddedVisibleSize(in, maxSize, selectedElement);
return in.substr(vs.start_, vs.count_);
}
}
| 29.736842 | 118 | 0.685841 |
6710cae5db7291a10684008a748246fc5eeec215 | 1,483 | cpp | C++ | Pearly/src/Pearly/Math/Math.cpp | JumpyLionnn/Pearly | 2dce5f54144980cecd998a325422e56bff6c4c83 | [
"Apache-2.0"
] | null | null | null | Pearly/src/Pearly/Math/Math.cpp | JumpyLionnn/Pearly | 2dce5f54144980cecd998a325422e56bff6c4c83 | [
"Apache-2.0"
] | null | null | null | Pearly/src/Pearly/Math/Math.cpp | JumpyLionnn/Pearly | 2dce5f54144980cecd998a325422e56bff6c4c83 | [
"Apache-2.0"
] | null | null | null | #include "prpch.h"
#include "Math.h"
namespace Pearly {
bool Math::DecomposeTransform(const glm::mat4& transform, glm::vec3& position, float& rotation, glm::vec2& scale)
{
glm::mat4 localMatrix(transform);
// Normalize the matrix.
if (glm::epsilonEqual(localMatrix[3][3], static_cast<float>(0), glm::epsilon<float>()))
return false;
// First, isolate perspective. floathis is the messiest.
if (
glm::epsilonNotEqual(localMatrix[0][3], static_cast<float>(0), glm::epsilon<float>()) ||
glm::epsilonNotEqual(localMatrix[1][3], static_cast<float>(0), glm::epsilon<float>()) ||
glm::epsilonNotEqual(localMatrix[2][3], static_cast<float>(0), glm::epsilon<float>()))
{
// Clear the perspective partition
localMatrix[0][3] = localMatrix[1][3] = localMatrix[2][3] = static_cast<float>(0);
localMatrix[3][3] = static_cast<float>(1);
}
// Next take care of translation (easy).
position = glm::vec3(localMatrix[3]);
localMatrix[3] = glm::vec4(0, 0, 0, localMatrix[3].w);
glm::vec3 row[3];
// Now get scale and shear.
for (glm::length_t i = 0; i < 3; ++i)
for (glm::length_t j = 0; j < 3; ++j)
row[i][j] = localMatrix[i][j];
// Compute X scale factor and normalize first row.
scale.x = glm::length(row[0]);
row[0] = glm::detail::scale(row[0], static_cast<float>(1));
scale.y = glm::length(row[1]);
row[1] = glm::detail::scale(row[1], static_cast<float>(1));
rotation = atan2(row[0][1], row[0][0]);
return true;
}
} | 32.23913 | 114 | 0.646662 |
6711ec4603bd0025df95902abfec0d44315c7bae | 2,149 | cc | C++ | device/device_rom.cc | CompaqDisc/zippy | e8c3b67ea59adbbdf9881e1bc34f0eab0eab6abe | [
"MIT"
] | null | null | null | device/device_rom.cc | CompaqDisc/zippy | e8c3b67ea59adbbdf9881e1bc34f0eab0eab6abe | [
"MIT"
] | null | null | null | device/device_rom.cc | CompaqDisc/zippy | e8c3b67ea59adbbdf9881e1bc34f0eab0eab6abe | [
"MIT"
] | null | null | null | #include "device_rom.h"
#include <iostream>
#include <fstream>
#include <string>
#include <cerrno>
DeviceROM::DeviceROM(uint16_t address_start, size_t region_length) {
address_start_ = address_start;
region_length_ = region_length;
buffer_contents_ = (uint8_t*) malloc(region_length_ * sizeof(uint8_t));
}
DeviceROM::DeviceROM(uint16_t address_start, size_t region_length,
std::string file_path
) {
address_start_ = address_start;
region_length_ = region_length;
buffer_contents_ = (uint8_t*) malloc(region_length_ * sizeof(uint8_t));
std::ifstream f(file_path);
// Bail if file wasn't found.
if (!f.good()) {
std::cout
<< "[FATL] [device_rom.cc] Specified file does not exist!"
<< std::endl;
exit(ENOENT);
}
f.seekg(0, f.end);
size_t file_length = f.tellg();
f.seekg(0, f.beg);
/*
Check that file length <= buffer space.
If not, only read until buffer is filled.
*/
if (file_length > region_length_) {
// Warn that we will truncate the read.
std::cout
<< "[WARN] [device_rom.cc] Specified romfile is too long for virtual ROM!"
<< "Truncating read!" << std::endl;
// Warn how large the file was.
printf(
"[WARN] [device_rom.cc] "
"Attempting to load %s (%li bytes), into virtual ROM with size of %li bytes!\n",
file_path.c_str(), file_length, region_length_
);
// Truncate read.
file_length = sizeof(buffer_contents_);
} else {
printf(
"[INFO] [device_rom.cc] "
"Loaded %s (%li bytes), into virtual ROM with size of %li bytes\n",
file_path.c_str(), file_length, region_length_
);
}
// Read the file into our buffer.
f.read((char*) buffer_contents_, file_length);
}
DeviceROM::~DeviceROM() {
free(buffer_contents_);
}
void DeviceROM::Clock() {
if (bus_->MemoryRequestActive()) {
if (bus_->ReadRequestActive()) {
if (bus_->Address() >= address_start_ &&
bus_->Address() < (address_start_ + region_length_))
{
printf("[INFO] [device_rom.cc] /RD request made for 0x%04x\n",
bus_->Address());
bus_->PushData(
buffer_contents_[bus_->Address() - address_start_]);
}
}
}
}
void DeviceROM::BindToBus(Bus* bus) {
bus_ = bus;
}
| 23.615385 | 83 | 0.676128 |
671579f43f756cf8cdfde950e4ef720c4f5b80c4 | 1,197 | cpp | C++ | cxx/test/test_binheap.cpp | EQt/graphidx | 9716488cf29f6235072fc920fa1a473bf88e954f | [
"MIT"
] | 4 | 2020-04-03T15:18:30.000Z | 2022-01-06T15:22:48.000Z | cxx/test/test_binheap.cpp | EQt/graphidx | 9716488cf29f6235072fc920fa1a473bf88e954f | [
"MIT"
] | null | null | null | cxx/test/test_binheap.cpp | EQt/graphidx | 9716488cf29f6235072fc920fa1a473bf88e954f | [
"MIT"
] | null | null | null | #include <doctest/doctest.h>
#include <graphidx/heap/binheap.hpp>
#include <graphidx/heap/quadheap.hpp>
TEST_CASE_TEMPLATE_DEFINE("heap basic", Heap, test_heap_basics)
{
constexpr size_t N = 6;
Heap h(N);
REQUIRE(h.empty());
REQUIRE_EQ(h.size(), 0);
for (size_t i = 0; i < N; i++) {
REQUIRE(!h.contains(i));
}
h.push(5, 0.2f);
REQUIRE(!h.empty());
REQUIRE(h.contains(5));
REQUIRE(!h.contains(3));
REQUIRE_EQ(h.size(), 1);
REQUIRE_EQ(h[5], 0.2f);
REQUIRE_EQ(h.top(), 5);
h.push(3, -1.0f);
REQUIRE(!h.empty());
REQUIRE_EQ(h.size(), 2);
REQUIRE(h.contains(5));
REQUIRE(h.contains(3));
REQUIRE_EQ(h[5], 0.2f);
REQUIRE_EQ(h[3], -1.0f);
REQUIRE_EQ(h.top(), 3);
h.pop();
REQUIRE(!h.empty());
REQUIRE(h.contains(5));
REQUIRE(!h.contains(3));
REQUIRE_EQ(h.size(), 1);
REQUIRE_EQ(h[5], 0.2f);
h.push(3, 1.0f);
h.push(1, 0.1f);
REQUIRE_EQ(h.size(), 3);
REQUIRE_EQ(h.top(), 1);
h.decrease(5, -2.0f);
REQUIRE(!h.empty());
REQUIRE_EQ(h.top(), 5);
}
TEST_CASE_TEMPLATE_INVOKE(
test_heap_basics, gidx::BinaryHeap<int, float>, gidx::QuadHeap<int, float>);
| 22.166667 | 80 | 0.578112 |
671afcda2345039279bc47492c4f1a66cbd14d83 | 328 | cpp | C++ | Zerojudge/d111.cpp | w181496/OJ | 67d1d32770376865eba8a9dd1767e97dae68989a | [
"MIT"
] | 9 | 2017-10-08T16:22:03.000Z | 2021-08-20T09:32:17.000Z | Zerojudge/d111.cpp | w181496/OJ | 67d1d32770376865eba8a9dd1767e97dae68989a | [
"MIT"
] | null | null | null | Zerojudge/d111.cpp | w181496/OJ | 67d1d32770376865eba8a9dd1767e97dae68989a | [
"MIT"
] | 2 | 2018-01-15T16:35:44.000Z | 2019-03-21T18:30:04.000Z | #include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int main()
{
long long int n;
while(cin >> n)
{
if(n==0)break;
long long int t=sqrt(n);
if(t*t==n)
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
}
return 0;
}
| 15.619048 | 33 | 0.45122 |
671b8a4c8d8a666826e1265b4102ce0f9a0e1f3b | 2,268 | hpp | C++ | include/P2P.hpp | Sygmei/IsenCoin | 91668cf056704da950a6c1f55e7a5b573b685ca7 | [
"MIT"
] | 7 | 2018-05-31T14:16:48.000Z | 2022-02-24T18:54:06.000Z | include/P2P.hpp | Sygmei/IsenCoin | 91668cf056704da950a6c1f55e7a5b573b685ca7 | [
"MIT"
] | null | null | null | include/P2P.hpp | Sygmei/IsenCoin | 91668cf056704da950a6c1f55e7a5b573b685ca7 | [
"MIT"
] | null | null | null | #pragma once
#include <Logger.hpp>
#include <functional>
#include <optional>
#include <msgpack11/msgpack11.hpp>
#include <tacopie/network/tcp_socket.hpp>
#include "base58/base58.hpp"
namespace tacopie
{
int init();
void close();
}
namespace ic::p2p
{
namespace mp = msgpack11;
std::string msgpack_type_to_string(mp::MsgPack::Type type);
using additional_check_t = std::function<bool(const mp::MsgPack&)>;
struct Requirement
{
std::string name;
mp::MsgPack::Type type;
std::optional<additional_check_t> check;
bool has_check() const;
bool check_if_needed(const mp::MsgPack& msg);
Requirement(const std::string& name, mp::MsgPack::Type type);
Requirement(const std::string& name, mp::MsgPack::Type type, additional_check_t check);
};
using Requirements = std::vector<Requirement>;
mp::MsgPack string_to_msgpack(const std::string& msg);
mp::MsgPack bytearray_to_msgpack(const std::vector<char>& msg);
std::vector<char> string_to_bytearray(const std::string& msg);
bool is_msgpack_valid(const mp::MsgPack& msg);
bool is_msgpack_valid_type(const mp::MsgPack& msg, const std::string& type);
using success_callback_t = const std::function<void(const mp::MsgPack&)>;
using failure_callback_t = const std::function<void()>;
bool check_requirement(const std::string& name, const mp::MsgPack& msg, Requirement req);
void use_msg(
const mp::MsgPack& msg,
const std::string& type,
success_callback_t& on_success,
failure_callback_t& on_failure,
Requirements requirements = {}
);
mp::MsgPack build_msg(const std::string& type, mp::MsgPack::object fields = {});
void send_msg(tacopie::tcp_socket& socket, const mp::MsgPack& msg);
mp::MsgPack recv_msg(tacopie::tcp_socket& socket, size_t max_size);
template <size_t N>
void decode_b58(const std::string& message, std::array<unsigned char, N>& tarray);
template <size_t N>
void decode_b58(const std::string& message, std::array<unsigned char, N>& tarray)
{
std::vector<unsigned char> buffer;
base58::decode(message.c_str(), buffer);
std::copy(buffer.begin(), buffer.end(), tarray.begin());
}
} | 36 | 95 | 0.679894 |
671c60ceccc5a70d03b40fce21ce4617c071e989 | 1,420 | cpp | C++ | compiler/angkor/src/ADT/tensor/LexicalLayout.cpp | periannath/ONE | 61e0bdf2bcd0bc146faef42b85d469440e162886 | [
"Apache-2.0"
] | 255 | 2020-05-22T07:45:29.000Z | 2022-03-29T23:58:22.000Z | compiler/angkor/src/ADT/tensor/LexicalLayout.cpp | periannath/ONE | 61e0bdf2bcd0bc146faef42b85d469440e162886 | [
"Apache-2.0"
] | 5,102 | 2020-05-22T07:48:33.000Z | 2022-03-31T23:43:39.000Z | compiler/angkor/src/ADT/tensor/LexicalLayout.cpp | periannath/ONE | 61e0bdf2bcd0bc146faef42b85d469440e162886 | [
"Apache-2.0"
] | 120 | 2020-05-22T07:51:08.000Z | 2022-02-16T19:08:05.000Z | /*
* Copyright (c) 2018 Samsung Electronics Co., Ltd. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "nncc/core/ADT/tensor/LexicalLayout.h"
#include <cassert>
using nncc::core::ADT::tensor::Shape;
using nncc::core::ADT::tensor::Index;
// NOTE This forward declaration is introduced to minimize code diff
static uint32_t lexical_offset(const Shape &shape, const Index &index)
{
assert(shape.rank() > 0);
assert(shape.rank() == index.rank());
const uint32_t rank = shape.rank();
uint32_t res = index.at(0);
for (uint32_t axis = 1; axis < rank; ++axis)
{
res *= shape.dim(axis);
res += index.at(axis);
}
return res;
}
namespace nncc
{
namespace core
{
namespace ADT
{
namespace tensor
{
LexicalLayout::LexicalLayout() : Layout(lexical_offset)
{
// DO NOTHING
}
} // namespace tensor
} // namespace ADT
} // namespace core
} // namespace nncc
| 23.278689 | 75 | 0.705634 |