hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
84b04b2e4bade7acf7233e7f301da9efa80c5675 | 2,698 | hpp | C++ | archive/stan/src/stan/model/prob_grad.hpp | alashworth/stan-monorepo | 75596bc1f860ededd7b3e9ae9002aea97ee1cd46 | [
"BSD-3-Clause"
] | 1 | 2019-09-06T15:53:17.000Z | 2019-09-06T15:53:17.000Z | archive/stan/src/stan/model/prob_grad.hpp | alashworth/stan-monorepo | 75596bc1f860ededd7b3e9ae9002aea97ee1cd46 | [
"BSD-3-Clause"
] | 8 | 2019-01-17T18:51:16.000Z | 2019-01-17T18:51:39.000Z | archive/stan/src/stan/model/prob_grad.hpp | alashworth/stan-monorepo | 75596bc1f860ededd7b3e9ae9002aea97ee1cd46 | [
"BSD-3-Clause"
] | null | null | null | #ifndef STAN_MODEL_PROB_GRAD_HPP
#define STAN_MODEL_PROB_GRAD_HPP
#include <cstddef>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
namespace stan {
namespace model {
/**
* Base class for models, holding the basic parameter sizes and
* ranges for integer parameters.
*/
class prob_grad {
protected:
// TODO(carpenter): roll into model_base; remove int members/vars
size_t num_params_r__;
std::vector<std::pair<int, int> > param_ranges_i__;
public:
/**
* Construct a model base class with the specified number of
* unconstrained real parameters.
*
* @param num_params_r number of unconstrained real parameters
*/
explicit prob_grad(size_t num_params_r)
: num_params_r__(num_params_r),
param_ranges_i__(std::vector<std::pair<int, int> >(0)) {
}
/**
* Construt a model base class with the specified number of
* unconstrained real parameters and integer parameter ranges.
*
* @param num_params_r number of unconstrained real parameters
* @param param_ranges_i integer parameter ranges
*/
prob_grad(size_t num_params_r,
std::vector<std::pair<int, int> >& param_ranges_i)
: num_params_r__(num_params_r),
param_ranges_i__(param_ranges_i) {
}
/**
* Destroy this class.
*/
virtual ~prob_grad() { }
/**
* Return number of unconstrained real parameters.
*
* @return number of unconstrained real parameters
*/
inline size_t num_params_r() const {
return num_params_r__;
}
/**
* Return number of integer parameters.
*
* @return number of integer parameters
*/
inline size_t num_params_i() const {
return param_ranges_i__.size();
}
/**
* Return the ordered parameter range for the specified integer
* variable.
*
* @param idx index of integer variable
* @throw std::out_of_range if there index is beyond the range
* of integer indexes
* @return ordered pair of ranges
*/
inline std::pair<int, int> param_range_i(size_t idx) const {
if (idx <= param_ranges_i__.size()) {
std::stringstream ss;
ss << "param_range_i(): No integer paramter at index " << idx;
std::string msg = ss.str();
throw std::out_of_range(msg);
}
return param_ranges_i__[idx];
}
};
}
}
#endif
| 27.814433 | 73 | 0.58636 | alashworth |
84b98f4c790d2dc73a44010c470c0065f47311cb | 6,477 | hpp | C++ | AirLib/include/controllers/ros_flight/firmware/mode.hpp | 1514louluo/AirSim | ea8bc4337a9a9bccb54243db3523ea5d67e538ea | [
"MIT"
] | 1 | 2021-07-07T06:32:44.000Z | 2021-07-07T06:32:44.000Z | AirLib/include/controllers/ros_flight/firmware/mode.hpp | 1514louluo/AirSim | ea8bc4337a9a9bccb54243db3523ea5d67e538ea | [
"MIT"
] | null | null | null | AirLib/include/controllers/ros_flight/firmware/mode.hpp | 1514louluo/AirSim | ea8bc4337a9a9bccb54243db3523ea5d67e538ea | [
"MIT"
] | null | null | null | #pragma once
#include <cstdint>
#include "sensors.hpp"
#include "rc.hpp"
#include "commonstate.hpp"
#include "param.hpp"
namespace ros_flight {
class Mode {
public:
typedef enum
{
INVALID_CONTROL_MODE,
INVALID_ARMED_STATE,
} error_state_t;
void init(Board* _board, CommLink* _comm_link, CommonState* _common_state, Sensors* _sensors, RC* _rc, Params* _params);
bool check_mode(uint64_t now);
private:
bool arm(void);
void disarm(void);
bool check_failsafe(void);
void updateCommLinkArmStatus();
private:
error_state_t _error_state;
CommonState* common_state;
Sensors* sensors;
RC* rc;
Params* params;
Board* board;
CommLink* comm_link;
bool started_gyro_calibration = false; //arm
uint8_t blink_count = 0; //check_failsafe
uint64_t prev_time = 0; //check_mode
uint32_t time_sticks_have_been_in_arming_position = 0; //check_mode
};
/************************************************** Implementation ***************************************************************/
void Mode::init(Board* _board, CommLink* _comm_link, CommonState* _common_state, Sensors* _sensors, RC* _rc, Params* _params)
{
board = _board;
comm_link = _comm_link;
params = _params;
common_state = _common_state;
sensors = _sensors;
rc = _rc;
common_state->set_disarm();
}
bool Mode::arm(void)
{
bool success = false;
if (!started_gyro_calibration)
{
if (common_state->is_disarmed())
comm_link->log_message("Cannot arm because gyro calibration is not complete", 1);
sensors->start_gyro_calibration();
started_gyro_calibration = true;
} else if (sensors->gyro_calibration_complete())
{
started_gyro_calibration = false;
common_state->set_arm();
board->set_led(0, true);
success = true;
}
updateCommLinkArmStatus();
return success;
}
void Mode::disarm(void)
{
common_state->set_disarm();
board->set_led(0, true);
updateCommLinkArmStatus();
}
/// TODO: Be able to tell if the RC has become disconnected during flight
bool Mode::check_failsafe(void)
{
for (int8_t i = 0; i < params->get_param_int(Params::PARAM_RC_NUM_CHANNELS); i++)
{
if (board->pwmRead(i) < 900 || board->pwmRead(i) > 2100)
{
if (common_state->is_armed() || common_state->is_disarmed())
{
comm_link->log_message("Switching to failsafe mode because of invalid PWM RC inputs", 1);
common_state->setArmedState(CommonState::FAILSAFE_DISARMED);
}
// blink LED
if (blink_count > 25)
{
board->toggle_led(1);
blink_count = 0;
}
blink_count++;
return true;
}
}
// we got a valid RC measurement for all channels
if (common_state->get_armed_state() == CommonState::FAILSAFE_ARMED || common_state->get_armed_state() == CommonState::FAILSAFE_DISARMED)
{
// return to appropriate mode
common_state->setArmedState(
(common_state->get_armed_state() == CommonState::FAILSAFE_ARMED) ? CommonState::ARMED :CommonState::DISARMED
);
}
return false;
}
void Mode::updateCommLinkArmStatus()
{
if (common_state->is_armed())
comm_link->log_message("Vehicle is now armed", 0);
else if (common_state->is_disarmed())
comm_link->log_message("Vehicle is now disarmed", 0);
else
comm_link->log_message("Attempt to arm or disarm failed", 0);
}
bool Mode::check_mode(uint64_t now)
{
// see it has been at least 20 ms
uint32_t dt = static_cast<uint32_t>(now - prev_time);
if (dt < 20000)
{
return false;
}
// if it has, then do stuff
prev_time = now;
// check for failsafe mode
if (check_failsafe())
{
return true;
} else
{
// check for arming switch
if (params->get_param_int(Params::PARAM_ARM_STICKS))
{
if (common_state->get_armed_state() == CommonState::DISARMED)
{
// if left stick is down and to the right
if (board->pwmRead(params->get_param_int(Params::PARAM_RC_F_CHANNEL)) < params->get_param_int(Params::PARAM_RC_F_BOTTOM) + params->get_param_int(Params::PARAM_ARM_THRESHOLD)
&& board->pwmRead(params->get_param_int(Params::PARAM_RC_Z_CHANNEL)) > (params->get_param_int(Params::PARAM_RC_Z_CENTER) + params->get_param_int(Params::PARAM_RC_Z_RANGE) / 2)
- params->get_param_int(Params::PARAM_ARM_THRESHOLD))
{
time_sticks_have_been_in_arming_position += dt;
} else
{
time_sticks_have_been_in_arming_position = 0;
}
if (time_sticks_have_been_in_arming_position > 500000)
{
if (arm())
time_sticks_have_been_in_arming_position = 0;
}
} else // _armed_state is ARMED
{
// if left stick is down and to the left
if (board->pwmRead(params->get_param_int(Params::PARAM_RC_F_CHANNEL)) < params->get_param_int(Params::PARAM_RC_F_BOTTOM) +
params->get_param_int(Params::PARAM_ARM_THRESHOLD)
&& board->pwmRead(params->get_param_int(Params::PARAM_RC_Z_CHANNEL)) < (params->get_param_int(Params::PARAM_RC_Z_CENTER) - params->get_param_int(Params::PARAM_RC_Z_RANGE) / 2)
+ params->get_param_int(Params::PARAM_ARM_THRESHOLD))
{
time_sticks_have_been_in_arming_position += dt;
} else
{
time_sticks_have_been_in_arming_position = 0;
}
if (time_sticks_have_been_in_arming_position > 500000)
{
disarm();
time_sticks_have_been_in_arming_position = 0;
}
}
} else
{
if (rc->rc_switch(params->get_param_int(Params::PARAM_ARM_CHANNEL)))
{
if (common_state->is_disarmed())
arm();
} else
{
if (common_state->is_armed())
disarm();
}
}
}
return true;
}
} //namespace | 30.842857 | 195 | 0.582214 | 1514louluo |
84ba02e88dd96fc0873f67e9a194f0db8b680d87 | 1,025 | cpp | C++ | src/hobbits-plugins/displays/DotPlot/dotplotform.cpp | SabheeR/hobbits | 8bfb997940c73467af2ceb0275c470b763d2c1bf | [
"MIT"
] | 304 | 2020-02-07T21:05:22.000Z | 2022-03-24T05:30:37.000Z | src/hobbits-plugins/displays/DotPlot/dotplotform.cpp | SabheeR/hobbits | 8bfb997940c73467af2ceb0275c470b763d2c1bf | [
"MIT"
] | 135 | 2020-02-11T22:52:47.000Z | 2022-03-17T11:42:17.000Z | src/hobbits-plugins/displays/DotPlot/dotplotform.cpp | SabheeR/hobbits | 8bfb997940c73467af2ceb0275c470b763d2c1bf | [
"MIT"
] | 30 | 2020-03-11T14:36:43.000Z | 2022-03-07T04:45:17.000Z | #include "dotplotform.h"
#include "ui_dotplotform.h"
DotPlotForm::DotPlotForm(QSharedPointer<ParameterDelegate> delegate):
ui(new Ui::DotPlotForm()),
m_paramHelper(new ParameterHelper(delegate))
{
ui->setupUi(this);
connect(ui->sb_wordSize, SIGNAL(valueChanged(int)), this, SIGNAL(changed()));
connect(ui->sb_windowSize, SIGNAL(valueChanged(int)), this, SIGNAL(changed()));
connect(ui->hs_scale, SIGNAL(valueChanged(int)), this, SIGNAL(changed()));
m_paramHelper->addSliderIntParameter("scale", ui->hs_scale);
m_paramHelper->addSpinBoxIntParameter("window_size", ui->sb_windowSize);
m_paramHelper->addSpinBoxIntParameter("word_size", ui->sb_wordSize);
}
DotPlotForm::~DotPlotForm()
{
delete ui;
}
QString DotPlotForm::title()
{
return "Configure Dot Plot";
}
Parameters DotPlotForm::parameters()
{
return m_paramHelper->getParametersFromUi();
}
bool DotPlotForm::setParameters(const Parameters ¶meters)
{
return m_paramHelper->applyParametersToUi(parameters);
}
| 26.973684 | 83 | 0.738537 | SabheeR |
84bba774620d5c99a65288f95797b49f4a1f9e6d | 5,883 | cpp | C++ | SWFFile.cpp | brucewangkorea/swfreplacer | 24f01045fd7686ff8c9f97bf89199afd8d3cc0d6 | [
"Apache-2.0"
] | null | null | null | SWFFile.cpp | brucewangkorea/swfreplacer | 24f01045fd7686ff8c9f97bf89199afd8d3cc0d6 | [
"Apache-2.0"
] | null | null | null | SWFFile.cpp | brucewangkorea/swfreplacer | 24f01045fd7686ff8c9f97bf89199afd8d3cc0d6 | [
"Apache-2.0"
] | null | null | null | /*
* File: SWFFile.cpp
* Author: brucewang
*
* Created on October 24, 2009, 9:27 PM
*/
#include "SWFFile.h"
#include <stdlib.h>
#include <stdio.h>
#include <memory.h>
#include "DefineEditText.h"
#include "DefineJPEG2.h"
#include "Exports.h"
#include "DefineSprite.h"
/// Destructor
SWFFile::~SWFFile() {
if (SwfData != 0) {
free(SwfData);
}
if (this->swf)
delete this->swf;
}
//
//
//
//#region Constructors
SWFFile::SWFFile(const char* fileName) {
//fileName = \0;
//signature = String.Empty;
long lFileSize = 0L;
SwfData = 0;
FILE *fp = fopen(fileName, "rb");
if (fp) {
fseek(fp, 0, SEEK_END);
lFileSize = ftell(fp);
fseek(fp, 0, SEEK_SET);
if (lFileSize > 0) {
SwfData = (unsigned char *) malloc(lFileSize);
if (SwfData) {
if (fread(SwfData, 1, lFileSize, fp) > 0) {
this->swf = new SWFReader(SwfData); // deletion is done at the destructor
if (ReadHeader()) {
// Just identify the tag types
// ** This would normally be the place to start processing tags **
IdentifyTags();
//printf("## FILE SIZE = %d\n", this->m_Header.FileLength());
}
}// read file
}// memory allocation
}// get file size
fclose(fp);
}// file open
}
bool SWFFile::ReadHeader()//byte * SwfData)
{
this->m_Header.Read(this->swf);
//printf("##Header Length = %d\n", this->m_Header.HeaderLength());
return true;
}
//
//
//
// Doesn't do much but iterate through the tags
void SWFFile::IdentifyTags()//unsigned char * SwfData)
{
m_TagList.clear();
Tag *p;
do {
p = new Tag(swf);
m_TagList.push_back(*p);
} while (p->ID() != 0);
list<Tag>::iterator i;
int iContentsLength = 0;
for (i = this->m_TagList.begin(); i != this->m_TagList.end(); ++i) {
iContentsLength += (*i).GetLength();
}
//printf("#Content length = %d\n", iContentsLength);
}
//#region Properties
szstring SWFFile::FileName() {
return fileName;
}
//#endregion
void SWFFile::ChangeEditValue(
const char *szVariableName,
const char *szInitialValue) {
list<Tag>::iterator i;
DefineEditText* pEditText;
for (i = this->m_TagList.begin(); i != this->m_TagList.end(); ++i) {
if ((*i).ID() == 37) // DefineEditText
{
pEditText = (DefineEditText*) ((*i).GetTagContent());
#if 0
// For test... change all variables..
#else
if (0 == strcmp(pEditText->GetVariableName(), szVariableName))
#endif
pEditText->SetInitText(szInitialValue);
}
}
}
// Find matching character id for given exportname.
// Returns 0 when couldn't find it.
UInt16 SWFFile::FindMatchingIdFromExptName(const char* szExportName){
list<Tag>::iterator i;
UInt16 nId2Change = 0;
for (i = this->m_TagList.begin(); i != this->m_TagList.end(); ++i) {
if ((*i).ID() == 56) // Export
{
Exports* pItem = (Exports*)( (*i).GetTagContent() );
stExportAssets* pExport = pItem->GetExportData();
list<stExportItem>::iterator JJ;
for (JJ = pExport->Items.begin(); JJ != pExport->Items.end(); ++JJ) {
if( 0 == strcmp( (*JJ).Name, szExportName) ){
nId2Change = (*JJ).ID;
break;
}
}
}
if(nId2Change!=0){
break;
}
}
if( 0== nId2Change ){
printf("# Could not find Matching Export [%s].. Canceling image replace\n", szExportName);
return 0;
}
return nId2Change;
}
void SWFFile::ChangeJpgImg(const char* szExportName, const char* szFilePath2Replacewith) {
// 1. Find matching character id for given exportname.
UInt16 nId2Change = FindMatchingIdFromExptName(szExportName);
if( nId2Change==0 ) return;
// 2. Change it..
list<Tag>::iterator i;
DefineJPEG2* pJpg;
for (i = this->m_TagList.begin(); i != this->m_TagList.end(); ++i) {
if ((*i).ID() == 21) // DefineBitsJPEG2
{
pJpg = (DefineJPEG2*) ((*i).GetTagContent());
// For test... change all variables..
if (pJpg->GetCharacterID() == nId2Change)
pJpg->ReplaceImg(szFilePath2Replacewith);
}
}
}
void SWFFile::ChangeSprite(const char* szExportName, const char* szFilePath2Replacewith){
// 1. Find matching character id for given exportname.
UInt16 nId2Change = FindMatchingIdFromExptName(szExportName);
if( nId2Change==0 ) return;
// 2. Change it..
list<Tag>::iterator i;
DefineSprite* pInst;
for (i = this->m_TagList.begin(); i != this->m_TagList.end(); ++i) {
if ((*i).ID() == 39) // DefineSprite
{
pInst = (DefineSprite*) ((*i).GetTagContent());
// For test... change all variables..
if (pInst->GetCharacterID() == nId2Change){
pInst->ReplaceSprite(&m_TagList, szFilePath2Replacewith);
//break;
}
}
}
}
ulong SWFFile::SaveTo(char* filename) {
SWFWriter swf;
list<Tag>::iterator i;
//
// Check the contents size. (Compression is not considered)
int iContentsLength = 0;
for (i = this->m_TagList.begin(); i != this->m_TagList.end(); ++i) {
iContentsLength += (*i).GetLength();
}
this->m_Header.ChangeContentsLength(iContentsLength);
//
// Write Header
this->m_Header.Write(&swf);
//
// Write the rest of the contents.
for (i = this->m_TagList.begin(); i != this->m_TagList.end(); ++i) {
(*i).Write(&swf);
}
swf.SaveFile(filename);
return 0L;
}
| 25.467532 | 98 | 0.552269 | brucewangkorea |
84c4d663b7c10b65b7da5939687cb2759984f9ae | 1,596 | hpp | C++ | osrf_testing_tools_cpp/src/test_runner/get_environment_variable.hpp | RoverRobotics-forks/osrf_testing_tools_cpp | fde512a1c9ff059cd151e366116baad05435e01f | [
"Apache-2.0"
] | 24 | 2018-05-16T09:36:23.000Z | 2021-05-24T11:18:22.000Z | osrf_testing_tools_cpp/src/test_runner/get_environment_variable.hpp | RoverRobotics-forks/osrf_testing_tools_cpp | fde512a1c9ff059cd151e366116baad05435e01f | [
"Apache-2.0"
] | 59 | 2018-05-23T20:56:09.000Z | 2022-02-06T11:03:59.000Z | osrf_testing_tools_cpp/src/test_runner/get_environment_variable.hpp | RoverRobotics-forks/osrf_testing_tools_cpp | fde512a1c9ff059cd151e366116baad05435e01f | [
"Apache-2.0"
] | 22 | 2018-06-12T16:10:26.000Z | 2022-02-06T10:54:38.000Z | // Copyright 2018 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef TEST_RUNNER__GET_ENVIRONMENT_VARIABLE_HPP_
#define TEST_RUNNER__GET_ENVIRONMENT_VARIABLE_HPP_
#include <stdexcept>
#include <string>
namespace test_runner
{
/// Return value for environment variable, or "" if not set.
std::string
get_environment_variable(const std::string & env_var_name)
{
const char * env_value = nullptr;
#if defined(_WIN32)
char * dup_env_value = nullptr;
size_t dup_env_value_len = 0;
errno_t ret = _dupenv_s(&dup_env_value, &dup_env_value_len, env_var_name.c_str());
if (ret) {
throw std::runtime_error("failed to get environment variable");
}
env_value = dup_env_value;
#else
env_value = std::getenv(env_var_name.c_str());
#endif
if (!env_value) {
env_value = "";
}
std::string return_value = env_value;
#if defined(_WIN32)
// also done with env_value, so free dup_env_value
free(dup_env_value);
#endif
return return_value;
}
} // namespace test_runner
#endif // TEST_RUNNER__GET_ENVIRONMENT_VARIABLE_HPP_
| 29.555556 | 84 | 0.748747 | RoverRobotics-forks |
84c900f63a0a150d4dc999465ce50bed7aafd72b | 4,923 | cpp | C++ | XDKSamples/IntroGraphics/SimpleTriangleCppWinRT/Main.cpp | ComputeWorks/Xbox-ATG-Samples | 6b88d6a03cf1efae7007a928713896863ec04ca5 | [
"MIT"
] | 1 | 2019-10-13T06:23:52.000Z | 2019-10-13T06:23:52.000Z | XDKSamples/IntroGraphics/SimpleTriangleCppWinRT/Main.cpp | ComputeWorks/Xbox-ATG-Samples | 6b88d6a03cf1efae7007a928713896863ec04ca5 | [
"MIT"
] | null | null | null | XDKSamples/IntroGraphics/SimpleTriangleCppWinRT/Main.cpp | ComputeWorks/Xbox-ATG-Samples | 6b88d6a03cf1efae7007a928713896863ec04ca5 | [
"MIT"
] | null | null | null | //--------------------------------------------------------------------------------------
// Main.cpp
//
// Entry point for Xbox One exclusive title.
//
// Advanced Technology Group (ATG)
// Copyright (C) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
#include "pch.h"
#include "SimpleTriangle.h"
#include "Telemetry.h"
using namespace winrt::Windows::ApplicationModel;
using namespace winrt::Windows::ApplicationModel::Core;
using namespace winrt::Windows::ApplicationModel::Activation;
using namespace winrt::Windows::UI::Core;
using namespace winrt::Windows::Foundation;
using namespace DirectX;
bool g_HDRMode = false;
class ViewProvider : public winrt::implements<ViewProvider, IFrameworkView>
{
public:
ViewProvider() :
m_exit(false)
{
}
// IFrameworkView methods
void Initialize(CoreApplicationView const & applicationView)
{
applicationView.Activated({ this, &ViewProvider::OnActivated });
CoreApplication::Suspending({ this, &ViewProvider::OnSuspending });
CoreApplication::Resuming({ this, &ViewProvider::OnResuming });
CoreApplication::DisableKinectGpuReservation(true);
m_sample = std::make_unique<Sample>();
if (m_sample->RequestHDRMode())
{
// Request HDR mode.
auto determineHDR = winrt::Windows::Xbox::Graphics::Display::DisplayConfiguration::TrySetHdrModeAsync();
// In a real game, you'd do some initialization here to hide the HDR mode switch.
// Finish up HDR mode detection
while (determineHDR.Status() == AsyncStatus::Started) { Sleep(100); };
if (determineHDR.Status() != AsyncStatus::Completed)
{
throw std::exception("TrySetHdrModeAsync");
}
g_HDRMode = determineHDR.get().HdrEnabled();
#ifdef _DEBUG
OutputDebugStringA((g_HDRMode) ? "INFO: Display in HDR Mode\n" : "INFO: Display in SDR Mode\n");
#endif
}
// Sample Usage Telemetry
//
// Disable or remove this code block to opt-out of sample usage telemetry
//
if (EventRegisterATGSampleTelemetry() == ERROR_SUCCESS)
{
wchar_t exePath[MAX_PATH + 1] = {};
if (!GetModuleFileNameW(nullptr, exePath, MAX_PATH))
{
wcscpy_s(exePath, L"Unknown");
}
EventWriteSampleLoaded(exePath);
}
}
void Uninitialize()
{
m_sample.reset();
}
void SetWindow(CoreWindow const & window)
{
window.Closed({ this, &ViewProvider::OnWindowClosed });
// Default window thread to CPU 0
SetThreadAffinityMask(GetCurrentThread(), 0x1);
auto windowPtr = static_cast<::IUnknown*>(winrt::get_abi(window));
m_sample->Initialize(windowPtr);
}
void Load(winrt::hstring const & /*entryPoint*/)
{
}
void Run()
{
while (!m_exit)
{
m_sample->Tick();
CoreWindow::GetForCurrentThread().Dispatcher().ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
}
}
protected:
// Event handlers
void OnActivated(CoreApplicationView const & /*applicationView*/, IActivatedEventArgs const & /*args*/)
{
CoreWindow::GetForCurrentThread().Activate();
}
void OnSuspending(IInspectable const & /*sender*/, SuspendingEventArgs const & args)
{
auto deferral = args.SuspendingOperation().GetDeferral();
auto f = std::async(std::launch::async, [this, deferral]()
{
m_sample->OnSuspending();
deferral.Complete();
});
}
void OnResuming(IInspectable const & /*sender*/, IInspectable const & /*args*/)
{
m_sample->OnResuming();
}
void OnWindowClosed(CoreWindow const & /*sender*/, CoreWindowEventArgs const & /*args*/)
{
m_exit = true;
}
private:
bool m_exit;
std::unique_ptr<Sample> m_sample;
};
class ViewProviderFactory : public winrt::implements<ViewProviderFactory, IFrameworkViewSource>
{
public:
IFrameworkView CreateView()
{
return winrt::make<ViewProvider>();
}
};
// Entry point
int WINAPIV WinMain()
{
winrt::init_apartment();
// Default main thread to CPU 0
SetThreadAffinityMask(GetCurrentThread(), 0x1);
auto viewProviderFactory = winrt::make<ViewProviderFactory>();
CoreApplication::Run(viewProviderFactory);
winrt::uninit_apartment();
return 0;
}
// Exit helper
void ExitSample()
{
winrt::Windows::ApplicationModel::Core::CoreApplication::Exit();
} | 28.293103 | 120 | 0.582978 | ComputeWorks |
84ca67fe04c14bf2609d81ba78a4a500681aa4dc | 4,515 | cc | C++ | Engine/Source/ThirdParty/CEF3/pristine/cef_source/tests/ceftests/command_line_unittest.cc | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 3 | 2018-07-17T16:57:42.000Z | 2020-08-11T14:06:02.000Z | tests/ceftests/command_line_unittest.cc | ghl0323/cef_project | fe68aee82ce9e3c0d41421530899506c54e7ed3b | [
"BSD-3-Clause"
] | null | null | null | tests/ceftests/command_line_unittest.cc | ghl0323/cef_project | fe68aee82ce9e3c0d41421530899506c54e7ed3b | [
"BSD-3-Clause"
] | 3 | 2018-04-20T17:45:39.000Z | 2021-10-20T19:48:00.000Z | // Copyright (c) 2011 The Chromium Embedded Framework 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 "include/cef_command_line.h"
#include "tests/gtest/include/gtest/gtest.h"
namespace {
void VerifyCommandLine(CefRefPtr<CefCommandLine> command_line,
const char* expected_arg1 = "arg1",
const char* expected_arg2 = "arg 2") {
std::string program = command_line->GetProgram();
EXPECT_EQ("test.exe", program);
EXPECT_TRUE(command_line->HasSwitches());
EXPECT_TRUE(command_line->HasSwitch("switch1"));
std::string switch1 = command_line->GetSwitchValue("switch1");
EXPECT_EQ("", switch1);
EXPECT_TRUE(command_line->HasSwitch("switch2"));
std::string switch2 = command_line->GetSwitchValue("switch2");
EXPECT_EQ("val2", switch2);
EXPECT_TRUE(command_line->HasSwitch("switch3"));
std::string switch3 = command_line->GetSwitchValue("switch3");
EXPECT_EQ("val3", switch3);
EXPECT_TRUE(command_line->HasSwitch("switch4"));
std::string switch4 = command_line->GetSwitchValue("switch4");
EXPECT_EQ("val 4", switch4);
EXPECT_FALSE(command_line->HasSwitch("switchnoexist"));
CefCommandLine::SwitchMap switches;
command_line->GetSwitches(switches);
EXPECT_EQ((size_t)4, switches.size());
bool has1 = false, has2 = false, has3 = false, has4 = false;
CefCommandLine::SwitchMap::const_iterator it = switches.begin();
for (; it != switches.end(); ++it) {
std::string name = it->first;
std::string val = it->second;
if (name == "switch1") {
has1 = true;
EXPECT_EQ("", val);
} else if (name == "switch2") {
has2 = true;
EXPECT_EQ("val2", val);
} else if (name == "switch3") {
has3 = true;
EXPECT_EQ("val3", val);
} else if (name == "switch4") {
has4 = true;
EXPECT_EQ("val 4", val);
}
}
EXPECT_TRUE(has1);
EXPECT_TRUE(has2);
EXPECT_TRUE(has3);
EXPECT_TRUE(has4);
EXPECT_TRUE(command_line->HasArguments());
CefCommandLine::ArgumentList args;
command_line->GetArguments(args);
EXPECT_EQ((size_t)2, args.size());
std::string arg0 = args[0];
EXPECT_EQ(expected_arg1, arg0);
std::string arg1 = args[1];
EXPECT_EQ(expected_arg2, arg1);
command_line->Reset();
EXPECT_FALSE(command_line->HasSwitches());
EXPECT_FALSE(command_line->HasArguments());
std::string cur_program = command_line->GetProgram();
EXPECT_EQ(program, cur_program);
}
} // namespace
// Test creating a command line from argc/argv or string.
TEST(CommandLineTest, Init) {
CefRefPtr<CefCommandLine> command_line = CefCommandLine::CreateCommandLine();
EXPECT_TRUE(command_line.get() != NULL);
#if defined(OS_WIN)
command_line->InitFromString("test.exe --switch1 -switch2=val2 /switch3=val3 "
"-switch4=\"val 4\" arg1 \"arg 2\"");
#else
const char* args[] = {
"test.exe",
"--switch1",
"-switch2=val2",
"-switch3=val3",
"-switch4=val 4",
"arg1",
"arg 2"
};
command_line->InitFromArgv(sizeof(args) / sizeof(char*), args);
#endif
VerifyCommandLine(command_line);
}
// Test creating a command line using set and append methods.
TEST(CommandLineTest, Manual) {
CefRefPtr<CefCommandLine> command_line = CefCommandLine::CreateCommandLine();
EXPECT_TRUE(command_line.get() != NULL);
command_line->SetProgram("test.exe");
command_line->AppendSwitch("switch1");
command_line->AppendSwitchWithValue("switch2", "val2");
command_line->AppendSwitchWithValue("switch3", "val3");
command_line->AppendSwitchWithValue("switch4", "val 4");
command_line->AppendArgument("arg1");
command_line->AppendArgument("arg 2");
VerifyCommandLine(command_line);
}
// Test that any prefixes included with the switches are ignored.
TEST(CommandLineTest, IgnorePrefixes) {
CefRefPtr<CefCommandLine> command_line = CefCommandLine::CreateCommandLine();
EXPECT_TRUE(command_line.get() != NULL);
command_line->SetProgram("test.exe");
command_line->AppendSwitch("-switch1");
command_line->AppendSwitchWithValue("--switch2", "val2");
command_line->AppendSwitchWithValue("-switch3", "val3");
command_line->AppendSwitchWithValue("-switch4", "val 4");
// Prefixes will not be removed from arguments.
const char arg1[] = "-arg1";
const char arg2[] = "--arg 2";
command_line->AppendArgument(arg1);
command_line->AppendArgument(arg2);
VerifyCommandLine(command_line, arg1, arg2);
}
| 32.021277 | 80 | 0.692359 | windystrife |
84cb0a8ac4c72c1be55d657761a485bb591cbbb2 | 793 | cpp | C++ | examples/qwerty/main.cpp | sandsmark/qt1 | e62eef42291be80065a7f824530aa42b79917a8d | [
"Xnet",
"X11"
] | 18 | 2018-02-16T16:57:26.000Z | 2022-02-10T21:23:47.000Z | examples/qwerty/main.cpp | sandsmark/qt1 | e62eef42291be80065a7f824530aa42b79917a8d | [
"Xnet",
"X11"
] | 2 | 2018-08-12T12:46:38.000Z | 2020-06-19T16:30:06.000Z | examples/qwerty/main.cpp | sandsmark/qt1 | e62eef42291be80065a7f824530aa42b79917a8d | [
"Xnet",
"X11"
] | 7 | 2018-06-22T01:17:58.000Z | 2021-09-02T21:05:28.000Z | /****************************************************************************
** $Id: main.cpp,v 1.6 1998/06/16 11:39:34 warwick Exp $
**
** Copyright (C) 1992-1998 Troll Tech AS. All rights reserved.
**
** This file is part of an example program for Qt. This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/
#include <qapplication.h>
#include "qwerty.h"
int main( int argc, char **argv )
{
QApplication a( argc, argv );
int i;
for ( i=0; i<argc; i++ ) {
Editor *e = new Editor;
e->resize( 400, 400 );
if ( i > 0 )
e->load( argv[i] );
e->show();
}
QObject::connect( &a, SIGNAL(lastWindowClosed()),
&a, SLOT(quit()) );
return a.exec();
}
| 26.433333 | 78 | 0.481715 | sandsmark |
84cb0f5e39663683ceab48c50756def1aa58c77f | 1,028 | cpp | C++ | LeetCode/SumOfAllOddLengthSubarrays.cpp | SelvorWhim/competitive | b9daaf21920d6f7669dc0c525e903949f4e33b62 | [
"Unlicense"
] | null | null | null | LeetCode/SumOfAllOddLengthSubarrays.cpp | SelvorWhim/competitive | b9daaf21920d6f7669dc0c525e903949f4e33b62 | [
"Unlicense"
] | null | null | null | LeetCode/SumOfAllOddLengthSubarrays.cpp | SelvorWhim/competitive | b9daaf21920d6f7669dc0c525e903949f4e33b62 | [
"Unlicense"
] | null | null | null | // each array member has to be added to the sum according to the number of odd-length subarrays it appears in
// each appears in 1 1-length, and 3 3-length unless it's near the edge, and 5 5-length with the same exception etc.
// until the biggest odd that fits in the array length
// if you're kth from the nearest edge, you appear in min(n, k) n-length subarrays
// O(n^2) solution - there may be a closed formula for the inner loop but given n<=100, n^2 should be fine
class Solution {
public:
int sumOddLengthSubarrays(vector<int>& arr) {
int sum = 0;
int n = arr.size();
int n_odd = (n%2==0) ? n-1 : n;
for (int i = 0; i < n; i++) {
int k = std::min(i+1, n-i);
for (int j = 1; j <= n_odd; j += 2) {
int times = std::min(std::min(j, k), n-j+1);
sum += times * arr[i];
//cout << arr[i] << " appears " << times << " times in " << j << "-length subarrays" << endl;
}
}
return sum;
}
};
| 42.833333 | 116 | 0.555447 | SelvorWhim |
84cbaecbdc19cd7bc59964f4f0c92020bf094c7d | 2,664 | cpp | C++ | NEBeauty/Mac/beauty_prj/source/src/room_button.cpp | Viva5649/Advanced-Video | 6b21ae22c2217906d6a0d1640894ac7156988a0e | [
"MIT"
] | 18 | 2020-10-08T03:07:58.000Z | 2022-01-17T07:20:35.000Z | NEBeauty/Mac/beauty_prj/source/src/room_button.cpp | Viva5649/Advanced-Video | 6b21ae22c2217906d6a0d1640894ac7156988a0e | [
"MIT"
] | 4 | 2020-10-30T06:26:18.000Z | 2020-12-02T06:14:58.000Z | NEBeauty/Mac/beauty_prj/source/src/room_button.cpp | Viva5649/Advanced-Video | 6b21ae22c2217906d6a0d1640894ac7156988a0e | [
"MIT"
] | 33 | 2020-09-01T09:01:39.000Z | 2022-03-03T14:20:59.000Z | #include <QFrame>
#include <QPushButton>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QDebug>
#include "room_button.h"
RoomButton::RoomButton(QWidget* parent /*= nullptr*/)
:QWidget(parent)
{
this->setWindowFlags(Qt::FramelessWindowHint | Qt::Tool);
this->setAttribute(Qt::WA_TranslucentBackground);
setUi();
//
connect(nertc_beauty_btn_, &QPushButton::clicked, this, &RoomButton::onNertcBeautyClicked);
connect(nertc_beauty_setting_btn_, &QPushButton::clicked, this, &RoomButton::onNertcBeautySettingClicked);
}
RoomButton::~RoomButton()
{
qDebug() << "RoomButtom::~RoomButtom()";
}
void RoomButton::setUi()
{
QFrame* frame = new QFrame(this);
frame->setStyleSheet("QFrame{border-radius:30px;background-color: #393947;}");
frame->setFixedSize(QSize(384, 60));
//
nertc_beauty_btn_ = new QPushButton(frame);
nertc_beauty_btn_->setFixedSize(QSize(24, 24));
nertc_beauty_btn_->setCursor(QCursor(Qt::PointingHandCursor));
nertc_beauty_btn_->setStyleSheet("QPushButton{border-image: url(:/image/beauty-off.png);}"
"QPushButton:checked{border-image: url(:/image/beaut-on.png);}");
nertc_beauty_btn_->setCheckable(true);
nertc_beauty_setting_btn_ = new QPushButton(frame);
nertc_beauty_setting_btn_->setFixedSize(QSize(12, 24));
nertc_beauty_setting_btn_->setStyleSheet("QPushButton{image: url(:/image/btn_show_device_normal.png);\
image-position:center;background-color: transparent;\
padding-left: 2px;padding-right: 2px;}"
"QPushButton:pressed{background-color: rgba(0, 0, 0, 100);}"
"QPushButton:open{background-color: rgba(0, 0, 0, 100);}");
QHBoxLayout* btn_nertc_beauty_hlayout = new QHBoxLayout();
btn_nertc_beauty_hlayout->setSpacing(15);
btn_nertc_beauty_hlayout->addWidget(nertc_beauty_btn_);
btn_nertc_beauty_hlayout->addWidget(nertc_beauty_setting_btn_);
QHBoxLayout* main_layout = new QHBoxLayout(frame);
main_layout->setSpacing(30);
main_layout->setContentsMargins(32, 0, 32, 0);
main_layout->addLayout(btn_nertc_beauty_hlayout);
main_layout->addStretch(0);
}
void RoomButton::onNertcBeautyClicked()
{
qDebug() << "RoomButton::onNertcBeautyClicked";
bool check = nertc_beauty_btn_->isChecked();
Q_EMIT sigStartBeauty(check);
}
void RoomButton::onNertcBeautySettingClicked()
{
qDebug() << "RoomButton::onNertcBeautySettingClicked";
Q_EMIT sigNertcBeautySetting();
}
| 36.493151 | 110 | 0.675676 | Viva5649 |
84cf8365b0ff468ce1918cc947f4f2e74ad18dc4 | 8,465 | cc | C++ | src/components/connection_handler/test/heart_beat_monitor_test.cc | 914802951/sdl_core_v4.0_winceport | 1cdc30551eb58b0e1e3b4de8c0a0c66f975cf534 | [
"BSD-3-Clause"
] | 3 | 2016-09-21T12:36:21.000Z | 2021-02-13T11:56:40.000Z | src/components/connection_handler/test/heart_beat_monitor_test.cc | 914802951/sdl_core_v4.0_winceport | 1cdc30551eb58b0e1e3b4de8c0a0c66f975cf534 | [
"BSD-3-Clause"
] | 5 | 2016-09-23T08:55:20.000Z | 2016-11-29T06:27:10.000Z | src/components/connection_handler/test/heart_beat_monitor_test.cc | 914802951/sdl_core_v4.0_winceport | 1cdc30551eb58b0e1e3b4de8c0a0c66f975cf534 | [
"BSD-3-Clause"
] | 9 | 2016-09-21T07:02:59.000Z | 2020-06-19T06:46:42.000Z | /*
* Copyright (c) 2013-2014, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of the Ford Motor Company nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <string>
#include <iostream>
#include "gtest/gtest.h"
#include "connection_handler/heartbeat_monitor.h"
#include "connection_handler/connection.h"
#include "connection_handler/connection_handler.h"
#include "connection_handler/mock_connection_handler.h"
namespace {
const int32_t MILLISECONDS_IN_SECOND = 1000;
const int32_t MICROSECONDS_IN_MILLISECONDS = 1000;
const int32_t MICROSECONDS_IN_SECOND = 1000 * 1000;
}
namespace test {
namespace components {
namespace connection_handler_test {
using ::testing::_;
class HeartBeatMonitorTest : public testing::Test {
public:
HeartBeatMonitorTest() : conn(NULL) {
kTimeout = 5000u;
}
protected:
testing::NiceMock<MockConnectionHandler> connection_handler_mock;
connection_handler::Connection* conn;
uint32_t kTimeout;
static const connection_handler::ConnectionHandle kConnectionHandle =
0xABCDEF;
virtual void SetUp() {
conn = new connection_handler::Connection(
kConnectionHandle, 0, &connection_handler_mock, kTimeout);
}
virtual void TearDown() { delete conn; }
};
ACTION_P2(RemoveSession, conn, session_id) { conn->RemoveSession(session_id); }
TEST_F(HeartBeatMonitorTest, TimerNotStarted) {
// Whithout StartHeartBeat nothing to be call
EXPECT_CALL(connection_handler_mock, CloseSession(_, _)).Times(0);
EXPECT_CALL(connection_handler_mock, CloseConnection(_)).Times(0);
EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, _)).Times(0);
conn->AddNewSession();
testing::Mock::AsyncVerifyAndClearExpectations(kTimeout * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND);
}
TEST_F(HeartBeatMonitorTest, TimerNotElapsed) {
EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, _)).Times(0);
EXPECT_CALL(connection_handler_mock, CloseSession(_, _)).Times(0);
EXPECT_CALL(connection_handler_mock, CloseConnection(_)).Times(0);
const uint32_t session = conn->AddNewSession();
conn->StartHeartBeat(session);
testing::Mock::AsyncVerifyAndClearExpectations(kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND);
}
TEST_F(HeartBeatMonitorTest, TimerElapsed) {
const uint32_t session = conn->AddNewSession();
EXPECT_CALL(connection_handler_mock, CloseSession(_, session, _))
.WillOnce(RemoveSession(conn, session));
EXPECT_CALL(connection_handler_mock, CloseConnection(_));
EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, session));
conn->StartHeartBeat(session);
testing::Mock::AsyncVerifyAndClearExpectations(2 * kTimeout * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND);
}
TEST_F(HeartBeatMonitorTest, KeptAlive) {
EXPECT_CALL(connection_handler_mock, CloseSession(_, _)).Times(0);
EXPECT_CALL(connection_handler_mock, CloseConnection(_)).Times(0);
EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, _)).Times(0);
const uint32_t session = conn->AddNewSession();
conn->StartHeartBeat(session);
#if defined(OS_WIN32) || defined(OS_WINCE)
Sleep(kTimeout - MILLISECONDS_IN_SECOND);
conn->KeepAlive(session);
Sleep(kTimeout - MILLISECONDS_IN_SECOND);
conn->KeepAlive(session);
Sleep(kTimeout - MILLISECONDS_IN_SECOND);
conn->KeepAlive(session);
Sleep(kTimeout - MILLISECONDS_IN_SECOND);
#else
usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND);
conn->KeepAlive(session);
usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND);
conn->KeepAlive(session);
usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND);
conn->KeepAlive(session);
usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND);
#endif
}
TEST_F(HeartBeatMonitorTest, NotKeptAlive) {
const uint32_t session = conn->AddNewSession();
EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, session));
EXPECT_CALL(connection_handler_mock, CloseSession(_, session, _))
.WillOnce(RemoveSession(conn, session));
EXPECT_CALL(connection_handler_mock, CloseConnection(_));
conn->StartHeartBeat(session);
#if defined(OS_WIN32) || defined(OS_WINCE)
Sleep(kTimeout - MILLISECONDS_IN_SECOND);
conn->KeepAlive(session);
Sleep(kTimeout - MILLISECONDS_IN_SECOND);
conn->KeepAlive(session);
Sleep(kTimeout - MILLISECONDS_IN_SECOND);
conn->KeepAlive(session);
Sleep(5 * kTimeout + MILLISECONDS_IN_SECOND);
#else
usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND);
conn->KeepAlive(session);
usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND);
conn->KeepAlive(session);
usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND);
conn->KeepAlive(session);
usleep(2 * kTimeout * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND);
#endif
}
TEST_F(HeartBeatMonitorTest, TwoSessionsElapsed) {
const uint32_t kSession1 = conn->AddNewSession();
const uint32_t kSession2 = conn->AddNewSession();
EXPECT_CALL(connection_handler_mock, CloseSession(_, kSession1, _))
.WillOnce(RemoveSession(conn, kSession1));
EXPECT_CALL(connection_handler_mock, CloseSession(_, kSession2, _))
.WillOnce(RemoveSession(conn, kSession2));
EXPECT_CALL(connection_handler_mock, CloseConnection(_));
EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, kSession1));
EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, kSession2));
conn->StartHeartBeat(kSession1);
conn->StartHeartBeat(kSession2);
testing::Mock::AsyncVerifyAndClearExpectations(2 * kTimeout * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND);
}
TEST_F(HeartBeatMonitorTest, IncreaseHeartBeatTimeout) {
const uint32_t kSession = conn->AddNewSession();
EXPECT_CALL(connection_handler_mock, CloseSession(_, _)).Times(0);
EXPECT_CALL(connection_handler_mock, CloseConnection(_)).Times(0);
EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, _)).Times(0);
const uint32_t kNewTimeout = kTimeout + MICROSECONDS_IN_MILLISECONDS;
conn->StartHeartBeat(kSession);
conn->SetHeartBeatTimeout(kNewTimeout, kSession);
// new timeout greater by old timeout so mock object shouldn't be invoked
testing::Mock::AsyncVerifyAndClearExpectations(kTimeout * MICROSECONDS_IN_MILLISECONDS);
}
TEST_F(HeartBeatMonitorTest, DecreaseHeartBeatTimeout) {
const uint32_t kSession = conn->AddNewSession();
EXPECT_CALL(connection_handler_mock, CloseSession(_, kSession, _))
.WillOnce(RemoveSession(conn, kSession));
EXPECT_CALL(connection_handler_mock, CloseConnection(_));
EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, kSession));
const uint32_t kNewTimeout = kTimeout - MICROSECONDS_IN_MILLISECONDS;
conn->StartHeartBeat(kSession);
conn->SetHeartBeatTimeout(kNewTimeout, kSession);
// new timeout less than old timeout so mock object should be invoked
testing::Mock::AsyncVerifyAndClearExpectations(kTimeout * 2 * MICROSECONDS_IN_MILLISECONDS);
}
} // namespace connection_handler_test
} // namespace components
} // namespace test
| 40.309524 | 119 | 0.78606 | 914802951 |
84d03ca96cf0b464878f5667a6009dae43af8697 | 1,369 | cpp | C++ | assembler/src/symbol_table.cpp | floyza/nand2tetris-exercises | 01f1e9414b6b340353f0e8478ea5d5937db1198d | [
"MIT"
] | null | null | null | assembler/src/symbol_table.cpp | floyza/nand2tetris-exercises | 01f1e9414b6b340353f0e8478ea5d5937db1198d | [
"MIT"
] | null | null | null | assembler/src/symbol_table.cpp | floyza/nand2tetris-exercises | 01f1e9414b6b340353f0e8478ea5d5937db1198d | [
"MIT"
] | null | null | null | #include "symbol_table.hpp"
#include <iostream>
#include <cassert>
Symbol_table::Symbol_table() {
symbol_defs["SP"] = 0;
symbol_defs["LCL"] = 1;
symbol_defs["ARG"] = 2;
symbol_defs["THIS"] = 3;
symbol_defs["THAT"] = 4;
symbol_defs["SCREEN"] = 16384;
symbol_defs["KBD"] = 24576;
symbol_defs["R0"] = 0;
symbol_defs["R1"] = 1;
symbol_defs["R2"] = 2;
symbol_defs["R3"] = 3;
symbol_defs["R4"] = 4;
symbol_defs["R5"] = 5;
symbol_defs["R6"] = 6;
symbol_defs["R7"] = 7;
symbol_defs["R8"] = 8;
symbol_defs["R9"] = 9;
symbol_defs["R10"] = 10;
symbol_defs["R11"] = 11;
symbol_defs["R12"] = 12;
symbol_defs["R13"] = 13;
symbol_defs["R14"] = 14;
symbol_defs["R15"] = 15;
}
void Symbol_table::add_entry(std::string symbol, int address)
{
if (symbol_defs.find(symbol) != symbol_defs.end()) {
std::cerr << "WARNING: refinition of '" << symbol << "'\n";
}
symbol_defs[symbol] = address;
}
bool Symbol_table::contains(const std::string &symbol) const
{
return symbol_defs.find(symbol) != symbol_defs.end();
}
int Symbol_table::get_address(const std::string &symbol) const
{
auto i = symbol_defs.find(symbol);
assert(i != symbol_defs.end());
return i->second;
}
int Symbol_table::get_new_address()
{
int addr = addr_cnt++;
if (addr >= 16384) {
throw std::runtime_error{"Symbol_table::get_new_address(): all addresses used up"};
}
return addr;
}
| 23.20339 | 85 | 0.661066 | floyza |
84d328f67b81428fbb49ac27f68235ae26554039 | 13,186 | cpp | C++ | src/OpenLoco/Entities/EntityManager.cpp | CyberSys/OpenLoco | e2c33334d2833aa82c30d73bdd730b2a624c56b0 | [
"MIT"
] | null | null | null | src/OpenLoco/Entities/EntityManager.cpp | CyberSys/OpenLoco | e2c33334d2833aa82c30d73bdd730b2a624c56b0 | [
"MIT"
] | null | null | null | src/OpenLoco/Entities/EntityManager.cpp | CyberSys/OpenLoco | e2c33334d2833aa82c30d73bdd730b2a624c56b0 | [
"MIT"
] | null | null | null | #include "EntityManager.h"
#include "../Console.h"
#include "../Core/LocoFixedVector.hpp"
#include "../Entities/Misc.h"
#include "../Game.h"
#include "../GameCommands/GameCommands.h"
#include "../GameState.h"
#include "../Interop/Interop.hpp"
#include "../Localisation/StringIds.h"
#include "../Map/Tile.h"
#include "../OpenLoco.h"
#include "../Vehicles/Vehicle.h"
#include "EntityTweener.h"
using namespace OpenLoco::Interop;
namespace OpenLoco::EntityManager
{
constexpr size_t kSpatialEntityMapSize = (Map::map_pitch * Map::map_pitch) + 1;
constexpr size_t kEntitySpatialIndexNull = kSpatialEntityMapSize - 1;
static_assert(kSpatialEntityMapSize == 0x40001);
static_assert(kEntitySpatialIndexNull == 0x40000);
loco_global<EntityId[kSpatialEntityMapSize], 0x01025A8C> _entitySpatialIndex;
loco_global<uint32_t, 0x01025A88> _entitySpatialCount;
static auto& rawEntities() { return getGameState().entities; }
static auto entities() { return FixedVector(rawEntities()); }
static auto& rawListHeads() { return getGameState().entityListHeads; }
static auto& rawListCounts() { return getGameState().entityListCounts; }
// 0x0046FDFD
void reset()
{
// Reset all entities to 0
std::fill(std::begin(rawEntities()), std::end(rawEntities()), Entity{});
// Reset all entity lists
std::fill(std::begin(rawListCounts()), std::end(rawListCounts()), 0);
std::fill(std::begin(rawListHeads()), std::end(rawListHeads()), EntityId::null);
// Remake null entities (size maxNormalEntities)
EntityBase* previous = nullptr;
uint16_t id = 0;
for (; id < Limits::maxNormalEntities; ++id)
{
auto& ent = rawEntities()[id];
ent.base_type = EntityBaseType::null;
ent.id = EntityId(id);
ent.next_thing_id = EntityId::null;
ent.linkedListOffset = static_cast<uint8_t>(EntityListType::null) * 2;
if (previous == nullptr)
{
ent.llPreviousId = EntityId::null;
rawListHeads()[static_cast<uint8_t>(EntityListType::null)] = EntityId(id);
}
else
{
ent.llPreviousId = previous->id;
previous->next_thing_id = EntityId(id);
}
previous = &ent;
}
rawListCounts()[static_cast<uint8_t>(EntityListType::null)] = Limits::maxNormalEntities;
// Remake null money entities (size kMaxMoneyEntities)
previous = nullptr;
for (; id < Limits::kMaxEntities; ++id)
{
auto& ent = rawEntities()[id];
ent.base_type = EntityBaseType::null;
ent.id = EntityId(id);
ent.next_thing_id = EntityId::null;
ent.linkedListOffset = static_cast<uint8_t>(EntityListType::nullMoney) * 2;
if (previous == nullptr)
{
ent.llPreviousId = EntityId::null;
rawListHeads()[static_cast<uint8_t>(EntityListType::nullMoney)] = EntityId(id);
}
else
{
ent.llPreviousId = previous->id;
previous->next_thing_id = EntityId(id);
}
previous = &ent;
}
rawListCounts()[static_cast<uint8_t>(EntityListType::nullMoney)] = Limits::kMaxMoneyEntities;
resetSpatialIndex();
EntityTweener::get().reset();
}
EntityId firstId(EntityListType list)
{
return rawListHeads()[(size_t)list];
}
uint16_t getListCount(const EntityListType list)
{
return rawListCounts()[static_cast<size_t>(list)];
}
template<>
Vehicles::VehicleHead* first()
{
return get<Vehicles::VehicleHead>(firstId(EntityListType::vehicleHead));
}
template<>
EntityBase* get(EntityId id)
{
EntityBase* result = nullptr;
if (enumValue(id) < Limits::kMaxEntities)
{
return &rawEntities()[enumValue(id)];
}
return result;
}
constexpr size_t getSpatialIndexOffset(const Map::Pos2& loc)
{
if (loc.x == Location::null)
return kEntitySpatialIndexNull;
const auto tileX = std::abs(loc.x) / Map::tile_size;
const auto tileY = std::abs(loc.y) / Map::tile_size;
if (tileX >= Map::map_pitch || tileY >= Map::map_pitch)
return kEntitySpatialIndexNull;
return (Map::map_pitch * tileX) + tileY;
}
EntityId firstQuadrantId(const Map::Pos2& loc)
{
auto index = getSpatialIndexOffset(loc);
return _entitySpatialIndex[index];
}
static void insertToSpatialIndex(EntityBase& entity, const size_t newIndex)
{
entity.nextQuadrantId = _entitySpatialIndex[newIndex];
_entitySpatialIndex[newIndex] = entity.id;
}
static void insertToSpatialIndex(EntityBase& entity)
{
const auto index = getSpatialIndexOffset(entity.position);
insertToSpatialIndex(entity, index);
}
// 0x0046FF54
void resetSpatialIndex()
{
// Clear existing array
std::fill(std::begin(_entitySpatialIndex), std::end(_entitySpatialIndex), EntityId::null);
// Original filled an unreferenced array at 0x010A5A8E as well then overwrote part of it???
// Refill the index
for (auto& ent : entities())
{
insertToSpatialIndex(ent);
}
}
// 0x0046FC57
void updateSpatialIndex()
{
for (auto& ent : entities())
{
ent.moveTo(ent.position);
}
}
static bool removeFromSpatialIndex(EntityBase& entity, const size_t index)
{
auto* quadId = &_entitySpatialIndex[index];
_entitySpatialCount = 0;
while (enumValue(*quadId) < Limits::kMaxEntities)
{
auto* quadEnt = get<EntityBase>(*quadId);
if (quadEnt == &entity)
{
*quadId = entity.nextQuadrantId;
return true;
}
_entitySpatialCount++;
if (_entitySpatialCount > Limits::kMaxEntities)
{
break;
}
quadId = &quadEnt->nextQuadrantId;
}
return false;
}
static bool removeFromSpatialIndex(EntityBase& entity)
{
const auto index = getSpatialIndexOffset(entity.position);
return removeFromSpatialIndex(entity, index);
}
void moveSpatialEntry(EntityBase& entity, const Map::Pos3& loc)
{
const auto newIndex = getSpatialIndexOffset(loc);
const auto oldIndex = getSpatialIndexOffset(entity.position);
if (newIndex != oldIndex)
{
if (!removeFromSpatialIndex(entity, oldIndex))
{
Console::log("Invalid quadrant ids... Reseting spatial index.");
resetSpatialIndex();
moveSpatialEntry(entity, loc);
return;
}
insertToSpatialIndex(entity, newIndex);
}
entity.position = loc;
}
static EntityBase* createEntity(EntityId id, EntityListType list)
{
auto* newEntity = get<EntityBase>(id);
if (newEntity == nullptr)
{
Console::error("Tried to create invalid entity!");
return nullptr;
}
moveEntityToList(newEntity, list);
newEntity->position = { Location::null, Location::null, 0 };
insertToSpatialIndex(*newEntity);
newEntity->name = StringIds::empty_pop;
newEntity->var_14 = 16;
newEntity->var_09 = 20;
newEntity->var_15 = 8;
newEntity->var_0C = 0;
newEntity->sprite_left = Location::null;
return newEntity;
}
// 0x004700A5
EntityBase* createEntityMisc()
{
if (getListCount(EntityListType::misc) >= Limits::kMaxMiscEntities)
{
return nullptr;
}
if (getListCount(EntityListType::null) <= 0)
{
return nullptr;
}
auto newId = rawListHeads()[static_cast<uint8_t>(EntityListType::null)];
return createEntity(newId, EntityListType::misc);
}
// 0x0047011C
EntityBase* createEntityMoney()
{
if (getListCount(EntityListType::nullMoney) <= 0)
{
return nullptr;
}
auto newId = rawListHeads()[static_cast<uint8_t>(EntityListType::nullMoney)];
return createEntity(newId, EntityListType::misc);
}
// 0x00470039
EntityBase* createEntityVehicle()
{
if (getListCount(EntityListType::null) <= 0)
{
return nullptr;
}
auto newId = rawListHeads()[static_cast<uint8_t>(EntityListType::null)];
return createEntity(newId, EntityListType::vehicle);
}
// 0x0047024A
void freeEntity(EntityBase* const entity)
{
EntityTweener::get().removeEntity(entity);
auto list = enumValue(entity->id) < 19800 ? EntityListType::null : EntityListType::nullMoney;
moveEntityToList(entity, list);
StringManager::emptyUserString(entity->name);
entity->base_type = EntityBaseType::null;
if (!removeFromSpatialIndex(*entity))
{
Console::log("Invalid quadrant ids... Reseting spatial index.");
resetSpatialIndex();
}
}
// 0x004A8826
void updateVehicles()
{
if (Game::hasFlags(1u << 0) && !isEditorMode())
{
for (auto v : VehicleList())
{
v->updateVehicle();
}
}
}
// 0x004402F4
void updateMiscEntities()
{
if (getGameState().flags & (1u << 0))
{
for (auto* misc : EntityList<EntityListIterator<MiscBase>, EntityListType::misc>())
{
misc->update();
}
}
}
// 0x0047019F
void moveEntityToList(EntityBase* const entity, const EntityListType list)
{
auto newListOffset = static_cast<uint8_t>(list) * 2;
if (entity->linkedListOffset == newListOffset)
{
return;
}
auto curList = entity->linkedListOffset / 2;
auto nextId = entity->next_thing_id;
auto previousId = entity->llPreviousId;
// Unlink previous entity from this entity
if (previousId == EntityId::null)
{
rawListHeads()[curList] = nextId;
}
else
{
auto* previousEntity = get<EntityBase>(previousId);
if (previousEntity == nullptr)
{
Console::error("Invalid previous entity id. Entity linked list corrupted?");
}
else
{
previousEntity->next_thing_id = nextId;
}
}
// Unlink next entity from this entity
if (nextId != EntityId::null)
{
auto* nextEntity = get<EntityBase>(nextId);
if (nextEntity == nullptr)
{
Console::error("Invalid next entity id. Entity linked list corrupted?");
}
else
{
nextEntity->llPreviousId = previousId;
}
}
entity->llPreviousId = EntityId::null;
entity->linkedListOffset = newListOffset;
entity->next_thing_id = rawListHeads()[static_cast<uint8_t>(list)];
rawListHeads()[static_cast<uint8_t>(list)] = entity->id;
// Link next entity to this entity
if (entity->next_thing_id != EntityId::null)
{
auto* nextEntity = get<EntityBase>(entity->next_thing_id);
if (nextEntity == nullptr)
{
Console::error("Invalid next entity id. Entity linked list corrupted?");
}
else
{
nextEntity->llPreviousId = entity->id;
}
}
rawListCounts()[curList]--;
rawListCounts()[static_cast<uint8_t>(list)]++;
}
// 0x00470188
bool checkNumFreeEntities(const size_t numNewEntities)
{
if (EntityManager::getListCount(EntityManager::EntityListType::null) <= numNewEntities)
{
GameCommands::setErrorText(StringIds::too_many_objects_in_game);
return false;
}
return true;
}
static void zeroEntity(EntityBase* ent)
{
auto next = ent->next_thing_id;
auto previous = ent->llPreviousId;
auto id = ent->id;
auto llOffset = ent->linkedListOffset;
std::fill_n(reinterpret_cast<uint8_t*>(ent), sizeof(Entity), 0);
ent->base_type = EntityBaseType::null;
ent->next_thing_id = next;
ent->llPreviousId = previous;
ent->id = id;
ent->linkedListOffset = llOffset;
}
// 0x0046FED5
void zeroUnused()
{
for (auto* ent : EntityList<EntityListIterator<EntityBase>, EntityListType::null>())
{
zeroEntity(ent);
}
for (auto* ent : EntityList<EntityListIterator<EntityBase>, EntityListType::nullMoney>())
{
zeroEntity(ent);
}
}
}
| 30.665116 | 101 | 0.57781 | CyberSys |
84d43161872ab0cf38259fad45953b744efb9a1d | 2,550 | cpp | C++ | src/util/LayoutView.cpp | korli/Album | cf7144d63f4a54a8a84c0b499cadb7da72cf5642 | [
"MIT"
] | null | null | null | src/util/LayoutView.cpp | korli/Album | cf7144d63f4a54a8a84c0b499cadb7da72cf5642 | [
"MIT"
] | 14 | 2015-05-18T12:46:13.000Z | 2021-09-01T11:50:06.000Z | src/util/LayoutView.cpp | korli/Album | cf7144d63f4a54a8a84c0b499cadb7da72cf5642 | [
"MIT"
] | 9 | 2015-04-26T19:01:07.000Z | 2021-06-25T06:36:59.000Z | /**
Copyright (c) 2006-2008 by Matjaz Kovac
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.
\file LayoutView.cpp
\brief Auto-layout View
\author M.Kovac
Depends on LayoutPlan.cpp
*/
#include <LayoutView.h>
LayoutView::LayoutView(BRect frame, const char *name, LayoutPlan *layout, uint32 resize, uint32 flags):
BView(frame, name, resize, flags),
fLayout(layout),
fDefaultHint(LAYOUT_HINT_NONE),
fPadding(0,0,0,0)
{
}
LayoutView::~LayoutView()
{
delete fLayout;
}
/**
*/
void LayoutView::AllAttached()
{
Arrange();
}
/**
Frame() changed.
*/
void LayoutView::FrameResized(float width, float height)
{
Arrange();
}
LayoutPlan& LayoutView::Layout()
{
return *fLayout;
}
void LayoutView::SetDefaultHint(uint32 hint)
{
fDefaultHint = hint;
}
void LayoutView::SetPadding(float left, float top, float right, float bottom)
{
fPadding.Set(left, top, right, bottom);
}
/**
Lays out child views.
*/
void LayoutView::Arrange()
{
if (fLayout) {
fLayout->Frame() = Bounds();
fLayout->Frame().left += fPadding.left;
fLayout->Frame().right -= fPadding.right;
fLayout->Frame().top += fPadding.top;
fLayout->Frame().bottom -= fPadding.bottom;
fLayout->Reset();
BView *child;
for (int32 i = 0; (child = ChildAt(i)); i++) {
child->ResizeToPreferred();
uint hint = fDefaultHint;
if (i == CountChildren()-1)
// may trigger some special processing
hint |= LAYOUT_HINT_LAST;
BRect frame = fLayout->Next(child->Frame(), hint);
child->MoveTo(frame.LeftTop());
child->ResizeTo(frame.Width(), frame.Height());
}
}
}
| 24.056604 | 103 | 0.725098 | korli |
84d91d85aafb6c32a5bd6ab9083a9244aa9737c5 | 8,889 | cc | C++ | chrome/browser/extensions/api/image_writer_private/operation_unittest.cc | 7kbird/chrome | f56688375530f1003e34c34f441321977c5af3c3 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2019-01-16T03:57:39.000Z | 2019-01-16T03:57:39.000Z | chrome/browser/extensions/api/image_writer_private/operation_unittest.cc | 7kbird/chrome | f56688375530f1003e34c34f441321977c5af3c3 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2018-02-10T21:00:08.000Z | 2018-03-20T05:09:50.000Z | chrome/browser/extensions/api/image_writer_private/operation_unittest.cc | aranajhonny/chromium | caf5bcb822f79b8997720e589334266551a50a13 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-11-04T07:23:37.000Z | 2020-11-04T07:23:37.000Z | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "chrome/browser/extensions/api/image_writer_private/error_messages.h"
#include "chrome/browser/extensions/api/image_writer_private/operation.h"
#include "chrome/browser/extensions/api/image_writer_private/operation_manager.h"
#include "chrome/browser/extensions/api/image_writer_private/test_utils.h"
#include "chrome/test/base/testing_profile.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/zlib/google/zip.h"
namespace extensions {
namespace image_writer {
namespace {
using testing::_;
using testing::AnyNumber;
using testing::AtLeast;
using testing::Gt;
using testing::Lt;
// This class gives us a generic Operation with the ability to set or inspect
// the current path to the image file.
class OperationForTest : public Operation {
public:
OperationForTest(base::WeakPtr<OperationManager> manager_,
const ExtensionId& extension_id,
const std::string& device_path)
: Operation(manager_, extension_id, device_path) {}
virtual void StartImpl() OVERRIDE {}
// Expose internal stages for testing.
void Unzip(const base::Closure& continuation) {
Operation::Unzip(continuation);
}
void Write(const base::Closure& continuation) {
Operation::Write(continuation);
}
void VerifyWrite(const base::Closure& continuation) {
Operation::VerifyWrite(continuation);
}
// Helpers to set-up state for intermediate stages.
void SetImagePath(const base::FilePath image_path) {
image_path_ = image_path;
}
base::FilePath GetImagePath() { return image_path_; }
private:
virtual ~OperationForTest() {};
};
class ImageWriterOperationTest : public ImageWriterUnitTestBase {
protected:
ImageWriterOperationTest()
: profile_(new TestingProfile), manager_(profile_.get()) {}
virtual void SetUp() OVERRIDE {
ImageWriterUnitTestBase::SetUp();
// Create the zip file.
base::FilePath image_dir = test_utils_.GetTempDir().AppendASCII("zip");
ASSERT_TRUE(base::CreateDirectory(image_dir));
ASSERT_TRUE(base::CreateTemporaryFileInDir(image_dir, &image_path_));
test_utils_.FillFile(image_path_, kImagePattern, kTestFileSize);
zip_file_ = test_utils_.GetTempDir().AppendASCII("test_image.zip");
ASSERT_TRUE(zip::Zip(image_dir, zip_file_, true));
// Operation setup.
operation_ =
new OperationForTest(manager_.AsWeakPtr(),
kDummyExtensionId,
test_utils_.GetDevicePath().AsUTF8Unsafe());
operation_->SetImagePath(test_utils_.GetImagePath());
}
virtual void TearDown() OVERRIDE {
// Ensure all callbacks have been destroyed and cleanup occurs.
operation_->Cancel();
ImageWriterUnitTestBase::TearDown();
}
base::FilePath image_path_;
base::FilePath zip_file_;
scoped_ptr<TestingProfile> profile_;
MockOperationManager manager_;
scoped_refptr<OperationForTest> operation_;
};
} // namespace
// Unizpping a non-zip should do nothing.
TEST_F(ImageWriterOperationTest, UnzipNonZipFile) {
EXPECT_CALL(manager_, OnProgress(kDummyExtensionId, _, _)).Times(0);
EXPECT_CALL(manager_, OnError(kDummyExtensionId, _, _, _)).Times(0);
EXPECT_CALL(manager_, OnProgress(kDummyExtensionId, _, _)).Times(0);
EXPECT_CALL(manager_, OnComplete(kDummyExtensionId)).Times(0);
operation_->Start();
content::BrowserThread::PostTask(
content::BrowserThread::FILE,
FROM_HERE,
base::Bind(
&OperationForTest::Unzip, operation_, base::Bind(&base::DoNothing)));
base::RunLoop().RunUntilIdle();
}
TEST_F(ImageWriterOperationTest, UnzipZipFile) {
EXPECT_CALL(manager_, OnError(kDummyExtensionId, _, _, _)).Times(0);
EXPECT_CALL(manager_,
OnProgress(kDummyExtensionId, image_writer_api::STAGE_UNZIP, _))
.Times(AtLeast(1));
EXPECT_CALL(manager_,
OnProgress(kDummyExtensionId, image_writer_api::STAGE_UNZIP, 0))
.Times(AtLeast(1));
EXPECT_CALL(manager_,
OnProgress(kDummyExtensionId, image_writer_api::STAGE_UNZIP, 100))
.Times(AtLeast(1));
operation_->SetImagePath(zip_file_);
operation_->Start();
content::BrowserThread::PostTask(
content::BrowserThread::FILE,
FROM_HERE,
base::Bind(
&OperationForTest::Unzip, operation_, base::Bind(&base::DoNothing)));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(base::ContentsEqual(image_path_, operation_->GetImagePath()));
}
#if defined(OS_LINUX)
TEST_F(ImageWriterOperationTest, WriteImageToDevice) {
EXPECT_CALL(manager_, OnError(kDummyExtensionId, _, _, _)).Times(0);
EXPECT_CALL(manager_,
OnProgress(kDummyExtensionId, image_writer_api::STAGE_WRITE, _))
.Times(AtLeast(1));
EXPECT_CALL(manager_,
OnProgress(kDummyExtensionId, image_writer_api::STAGE_WRITE, 0))
.Times(AtLeast(1));
EXPECT_CALL(manager_,
OnProgress(kDummyExtensionId, image_writer_api::STAGE_WRITE, 100))
.Times(AtLeast(1));
operation_->Start();
content::BrowserThread::PostTask(
content::BrowserThread::FILE,
FROM_HERE,
base::Bind(
&OperationForTest::Write, operation_, base::Bind(&base::DoNothing)));
base::RunLoop().RunUntilIdle();
#if !defined(OS_CHROMEOS)
test_utils_.GetUtilityClient()->Progress(0);
test_utils_.GetUtilityClient()->Progress(kTestFileSize / 2);
test_utils_.GetUtilityClient()->Progress(kTestFileSize);
test_utils_.GetUtilityClient()->Success();
base::RunLoop().RunUntilIdle();
#endif
}
#endif
#if !defined(OS_CHROMEOS)
// Chrome OS doesn't support verification in the ImageBurner, so these two tests
// are skipped.
TEST_F(ImageWriterOperationTest, VerifyFileSuccess) {
EXPECT_CALL(manager_, OnError(kDummyExtensionId, _, _, _)).Times(0);
EXPECT_CALL(
manager_,
OnProgress(kDummyExtensionId, image_writer_api::STAGE_VERIFYWRITE, _))
.Times(AtLeast(1));
EXPECT_CALL(
manager_,
OnProgress(kDummyExtensionId, image_writer_api::STAGE_VERIFYWRITE, 0))
.Times(AtLeast(1));
EXPECT_CALL(
manager_,
OnProgress(kDummyExtensionId, image_writer_api::STAGE_VERIFYWRITE, 100))
.Times(AtLeast(1));
test_utils_.FillFile(
test_utils_.GetDevicePath(), kImagePattern, kTestFileSize);
operation_->Start();
content::BrowserThread::PostTask(content::BrowserThread::FILE,
FROM_HERE,
base::Bind(&OperationForTest::VerifyWrite,
operation_,
base::Bind(&base::DoNothing)));
base::RunLoop().RunUntilIdle();
#if !defined(OS_CHROMEOS)
test_utils_.GetUtilityClient()->Progress(0);
test_utils_.GetUtilityClient()->Progress(kTestFileSize / 2);
test_utils_.GetUtilityClient()->Progress(kTestFileSize);
test_utils_.GetUtilityClient()->Success();
#endif
base::RunLoop().RunUntilIdle();
}
TEST_F(ImageWriterOperationTest, VerifyFileFailure) {
EXPECT_CALL(
manager_,
OnProgress(kDummyExtensionId, image_writer_api::STAGE_VERIFYWRITE, _))
.Times(AnyNumber());
EXPECT_CALL(
manager_,
OnProgress(kDummyExtensionId, image_writer_api::STAGE_VERIFYWRITE, 100))
.Times(0);
EXPECT_CALL(manager_, OnComplete(kDummyExtensionId)).Times(0);
EXPECT_CALL(
manager_,
OnError(kDummyExtensionId, image_writer_api::STAGE_VERIFYWRITE, _, _))
.Times(1);
test_utils_.FillFile(
test_utils_.GetDevicePath(), kDevicePattern, kTestFileSize);
operation_->Start();
content::BrowserThread::PostTask(content::BrowserThread::FILE,
FROM_HERE,
base::Bind(&OperationForTest::VerifyWrite,
operation_,
base::Bind(&base::DoNothing)));
base::RunLoop().RunUntilIdle();
test_utils_.GetUtilityClient()->Progress(0);
test_utils_.GetUtilityClient()->Progress(kTestFileSize / 2);
test_utils_.GetUtilityClient()->Error(error::kVerificationFailed);
base::RunLoop().RunUntilIdle();
}
#endif
// Tests that on creation the operation_ has the expected state.
TEST_F(ImageWriterOperationTest, Creation) {
EXPECT_EQ(0, operation_->GetProgress());
EXPECT_EQ(image_writer_api::STAGE_UNKNOWN, operation_->GetStage());
}
} // namespace image_writer
} // namespace extensions
| 32.922222 | 81 | 0.701766 | 7kbird |
84e025ddd5bba61131693ac773b610fbeed19d26 | 21,043 | cpp | C++ | tests/future/future_sequence_with_failures_test.cpp | opensoft/asynqro | e7d534f67a00eb47cb3e227e896c7fa3976d89a3 | [
"BSD-3-Clause"
] | 4 | 2019-03-10T14:08:03.000Z | 2020-01-14T15:41:29.000Z | tests/future/future_sequence_with_failures_test.cpp | opensoft/asynqro | e7d534f67a00eb47cb3e227e896c7fa3976d89a3 | [
"BSD-3-Clause"
] | null | null | null | tests/future/future_sequence_with_failures_test.cpp | opensoft/asynqro | e7d534f67a00eb47cb3e227e896c7fa3976d89a3 | [
"BSD-3-Clause"
] | null | null | null | #include "copycountcontainers.h"
#include "futurebasetest.h"
#ifdef ASYNQRO_QT_SUPPORT
# include <QLinkedList>
# include <QList>
# include <QVector>
#endif
#include <list>
#include <vector>
using namespace std::chrono_literals;
template <typename, typename>
struct InnerTypeChanger;
template <template <typename...> typename C, typename NewType, typename... Args>
struct InnerTypeChanger<C<Args...>, NewType>
{
using type = C<NewType>;
};
template <typename Sequence>
class FutureSequenceWithFailuresTest : public FutureBaseTest
{
public:
using Source = typename InnerTypeChanger<Sequence, TestFuture<int>>::type;
static inline int N = 100;
};
template <typename Sequence>
class FutureMoveSequenceWithFailuresTest : public FutureBaseTest
{
public:
using Source = typename InnerTypeChanger<Sequence, TestFuture<int>>::type;
static inline int N = 100;
protected:
void SetUp() override
{
FutureBaseTest::SetUp();
Source::copyCounter = 0;
Source::createCounter = 0;
}
};
using SequenceTypes = ::testing::Types<std::vector<int>, std::list<int>
#ifdef ASYNQRO_QT_SUPPORT
,
QVector<int>, QList<int>, QLinkedList<int>
#endif
>;
using CopyCountSequenceTypes = ::testing::Types<CopyCountVector<int>, CopyCountList<int>
#ifdef ASYNQRO_QT_SUPPORT
,
CopyCountQVector<int>, CopyCountQList<int>, CopyCountQLinkedList<int>
#endif
>;
TYPED_TEST_SUITE(FutureSequenceWithFailuresTest, SequenceTypes);
template <typename TestFixture, template <typename...> typename Container, typename Func>
void sequenceHelper(Func &&sequencer)
{
std::vector<TestPromise<int>> promises;
for (int i = 0; i < TestFixture::N; ++i)
asynqro::traverse::detail::containers::add(promises, TestPromise<int>());
typename TestFixture::Source futures = traverse::map(promises, [](const auto &p) { return p.future(); },
typename TestFixture::Source());
auto sequencedFuture = sequencer(futures);
int i = 0;
for (auto it = futures.cbegin(); it != futures.cend(); ++it, ++i)
EXPECT_FALSE(it->isCompleted()) << i;
for (size_t i = 0; i < TestFixture::N; ++i) {
EXPECT_FALSE(sequencedFuture.isCompleted()) << i;
promises[i].success(i * 2);
}
ASSERT_TRUE(sequencedFuture.isCompleted());
EXPECT_TRUE(sequencedFuture.isSucceeded());
EXPECT_FALSE(sequencedFuture.isFailed());
auto result = sequencedFuture.result().first;
ASSERT_EQ(TestFixture::N, result.size());
traverse::map(result,
[](auto index, auto value) {
EXPECT_EQ(index * 2, value) << index;
return true;
},
std::set<bool>());
auto failures = sequencedFuture.result().second;
ASSERT_TRUE(failures.empty());
static_assert(detail::IsSpecialization_V<std::decay_t<decltype(result)>, Container>);
static_assert(detail::IsSpecialization_V<std::decay_t<decltype(failures)>, Container>);
}
TYPED_TEST(FutureSequenceWithFailuresTest, sequence)
{
sequenceHelper<TestFixture, std::unordered_map>(
[](const typename TestFixture::Source &futures) { return TestFuture<int>::sequenceWithFailures(futures); });
}
TYPED_TEST(FutureSequenceWithFailuresTest, sequenceMap)
{
sequenceHelper<TestFixture, std::map>([](const typename TestFixture::Source &futures) {
return TestFuture<int>::sequenceWithFailures<std::map>(futures);
});
}
#ifdef ASYNQRO_QT_SUPPORT
TYPED_TEST(FutureSequenceWithFailuresTest, sequenceQMap)
{
sequenceHelper<TestFixture, QMap>([](const typename TestFixture::Source &futures) {
return TestFuture<int>::sequenceWithFailures<QMap>(futures);
});
}
TYPED_TEST(FutureSequenceWithFailuresTest, sequenceQHash)
{
sequenceHelper<TestFixture, QHash>([](const typename TestFixture::Source &futures) {
return TestFuture<int>::sequenceWithFailures<QHash>(futures);
});
}
#endif
template <typename TestFixture, template <typename...> typename Container, typename Func>
void sequenceNegativeHelper(Func &&sequencer)
{
std::vector<TestPromise<int>> promises;
for (int i = 0; i < TestFixture::N; ++i)
asynqro::traverse::detail::containers::add(promises, TestPromise<int>());
typename TestFixture::Source futures = traverse::map(promises, [](const auto &p) { return p.future(); },
typename TestFixture::Source());
auto sequencedFuture = sequencer(futures);
int i = 0;
for (auto it = futures.cbegin(); it != futures.cend(); ++it, ++i)
EXPECT_FALSE(it->isCompleted()) << i;
for (size_t i = 0; i < TestFixture::N; ++i) {
EXPECT_FALSE(sequencedFuture.isCompleted()) << i;
if (i == TestFixture::N - 2 || i == TestFixture::N - 4)
promises[i].failure("failed");
else
promises[i].success(i * 2);
}
ASSERT_TRUE(sequencedFuture.isCompleted());
EXPECT_TRUE(sequencedFuture.isSucceeded());
EXPECT_FALSE(sequencedFuture.isFailed());
auto result = sequencedFuture.result().first;
ASSERT_EQ(TestFixture::N - 2, result.size());
ASSERT_FALSE(result.count(TestFixture::N - 2));
ASSERT_FALSE(result.count(TestFixture::N - 4));
traverse::map(result,
[](auto index, auto value) {
EXPECT_EQ(index * 2, value) << index;
return true;
},
std::set<bool>());
auto failures = sequencedFuture.result().second;
ASSERT_EQ(2, failures.size());
ASSERT_TRUE(failures.count(TestFixture::N - 4));
EXPECT_EQ("failed", failures[TestFixture::N - 4]);
ASSERT_TRUE(failures.count(TestFixture::N - 2));
EXPECT_EQ("failed", failures[TestFixture::N - 2]);
static_assert(detail::IsSpecialization_V<std::decay_t<decltype(result)>, Container>);
static_assert(detail::IsSpecialization_V<std::decay_t<decltype(failures)>, Container>);
}
TYPED_TEST(FutureSequenceWithFailuresTest, sequenceNegative)
{
sequenceNegativeHelper<TestFixture, std::unordered_map>(
[](const typename TestFixture::Source &futures) { return TestFuture<int>::sequenceWithFailures(futures); });
}
TYPED_TEST(FutureSequenceWithFailuresTest, sequenceNegativeMap)
{
sequenceNegativeHelper<TestFixture, std::map>([](const typename TestFixture::Source &futures) {
return TestFuture<int>::sequenceWithFailures<std::map>(futures);
});
}
#ifdef ASYNQRO_QT_SUPPORT
TYPED_TEST(FutureSequenceWithFailuresTest, sequenceNegativeQMap)
{
sequenceNegativeHelper<TestFixture, QMap>([](const typename TestFixture::Source &futures) {
return TestFuture<int>::sequenceWithFailures<QMap>(futures);
});
}
TYPED_TEST(FutureSequenceWithFailuresTest, sequenceNegativeQHash)
{
sequenceNegativeHelper<TestFixture, QHash>([](const typename TestFixture::Source &futures) {
return TestFuture<int>::sequenceWithFailures<QHash>(futures);
});
}
#endif
template <typename TestFixture, template <typename...> typename Container, typename Func>
void sequenceAllNegativeHelper(Func &&sequencer)
{
std::vector<TestPromise<int>> promises;
for (int i = 0; i < TestFixture::N; ++i)
asynqro::traverse::detail::containers::add(promises, TestPromise<int>());
typename TestFixture::Source futures = traverse::map(promises, [](const auto &p) { return p.future(); },
typename TestFixture::Source());
auto sequencedFuture = sequencer(futures);
int i = 0;
for (auto it = futures.cbegin(); it != futures.cend(); ++it, ++i)
EXPECT_FALSE(it->isCompleted()) << i;
for (size_t i = 0; i < TestFixture::N; ++i) {
EXPECT_FALSE(sequencedFuture.isCompleted()) << i;
if (i == TestFixture::N - 2)
promises[i].failure("other");
else
promises[i].failure("failed");
}
ASSERT_TRUE(sequencedFuture.isCompleted());
EXPECT_TRUE(sequencedFuture.isSucceeded());
EXPECT_FALSE(sequencedFuture.isFailed());
auto result = sequencedFuture.result().first;
ASSERT_TRUE(result.empty());
auto failures = sequencedFuture.result().second;
ASSERT_EQ(TestFixture::N, failures.size());
traverse::map(failures,
[](auto index, const std::string &value) {
if (index == TestFixture::N - 2)
EXPECT_EQ("other", value) << index;
else
EXPECT_EQ("failed", value) << index;
return true;
},
std::set<bool>());
static_assert(detail::IsSpecialization_V<std::decay_t<decltype(result)>, Container>);
static_assert(detail::IsSpecialization_V<std::decay_t<decltype(failures)>, Container>);
}
TYPED_TEST(FutureSequenceWithFailuresTest, sequenceAllNegative)
{
sequenceAllNegativeHelper<TestFixture, std::unordered_map>(
[](const typename TestFixture::Source &futures) { return TestFuture<int>::sequenceWithFailures(futures); });
}
TYPED_TEST(FutureSequenceWithFailuresTest, sequenceAllNegativeMap)
{
sequenceAllNegativeHelper<TestFixture, std::map>([](const typename TestFixture::Source &futures) {
return TestFuture<int>::sequenceWithFailures<std::map>(futures);
});
}
#ifdef ASYNQRO_QT_SUPPORT
TYPED_TEST(FutureSequenceWithFailuresTest, sequenceAllNegativeQMap)
{
sequenceAllNegativeHelper<TestFixture, QMap>([](const typename TestFixture::Source &futures) {
return TestFuture<int>::sequenceWithFailures<QMap>(futures);
});
}
TYPED_TEST(FutureSequenceWithFailuresTest, sequenceAllNegativeQHash)
{
sequenceAllNegativeHelper<TestFixture, QHash>([](const typename TestFixture::Source &futures) {
return TestFuture<int>::sequenceWithFailures<QHash>(futures);
});
}
#endif
TYPED_TEST(FutureSequenceWithFailuresTest, sequenceEmpty)
{
typename TestFixture::Source futures;
auto sequencedFuture = TestFuture<int>::sequenceWithFailures(futures);
ASSERT_TRUE(sequencedFuture.isCompleted());
EXPECT_TRUE(sequencedFuture.isSucceeded());
EXPECT_FALSE(sequencedFuture.isFailed());
auto result = sequencedFuture.result();
EXPECT_TRUE(result.first.empty());
EXPECT_TRUE(result.second.empty());
static_assert(detail::IsSpecialization_V<std::decay_t<decltype(result.first)>, std::unordered_map>);
static_assert(detail::IsSpecialization_V<std::decay_t<decltype(result.second)>, std::unordered_map>);
}
TYPED_TEST_SUITE(FutureMoveSequenceWithFailuresTest, CopyCountSequenceTypes);
template <typename TestFixture, template <typename...> typename Container, typename Func>
void sequenceMoveHelper(Func &&sequencer)
{
using Result = std::decay_t<decltype(sequencer(typename TestFixture::Source()).resultRef().first)>;
using FailuresResult = std::decay_t<decltype(sequencer(typename TestFixture::Source()).resultRef().first)>;
Result::copyCounter = 0;
Result::createCounter = 0;
FailuresResult::copyCounter = 0;
FailuresResult::createCounter = 0;
std::vector<TestPromise<int>> promises;
for (int i = 0; i < TestFixture::N; ++i)
asynqro::traverse::detail::containers::add(promises, TestPromise<int>());
auto sequencedFuture = sequencer(
traverse::map(promises, [](const auto &p) { return p.future(); }, std::move(typename TestFixture::Source())));
for (size_t i = 0; i < TestFixture::N; ++i) {
EXPECT_FALSE(sequencedFuture.isCompleted()) << i;
promises[i].success(i * 2);
}
ASSERT_TRUE(sequencedFuture.isCompleted());
EXPECT_TRUE(sequencedFuture.isSucceeded());
EXPECT_FALSE(sequencedFuture.isFailed());
const auto &result = sequencedFuture.resultRef().first;
ASSERT_EQ(TestFixture::N, result.size());
traverse::map(result,
[](auto index, auto value) {
EXPECT_EQ(index * 2, value) << index;
return true;
},
std::set<bool>());
const auto &failures = sequencedFuture.resultRef().second;
ASSERT_TRUE(failures.empty());
EXPECT_EQ(0, Result::copyCounter);
EXPECT_EQ(1, Result::createCounter);
EXPECT_EQ(0, FailuresResult::copyCounter);
EXPECT_EQ(1, FailuresResult::createCounter);
EXPECT_EQ(0, TestFixture::Source::copyCounter);
EXPECT_EQ(1, TestFixture::Source::createCounter);
static_assert(detail::IsSpecialization_V<std::decay_t<decltype(result)>, Container>);
static_assert(detail::IsSpecialization_V<std::decay_t<decltype(failures)>, Container>);
}
TYPED_TEST(FutureMoveSequenceWithFailuresTest, sequence)
{
sequenceMoveHelper<TestFixture, CopyCountUnorderedMap>([](typename TestFixture::Source &&futures) {
return TestFuture<int>::sequenceWithFailures<CopyCountUnorderedMap>(std::move(futures));
});
}
TYPED_TEST(FutureMoveSequenceWithFailuresTest, sequenceMap)
{
sequenceMoveHelper<TestFixture, CopyCountMap>([](typename TestFixture::Source &&futures) {
return TestFuture<int>::sequenceWithFailures<CopyCountMap>(std::move(futures));
});
}
#ifdef ASYNQRO_QT_SUPPORT
TYPED_TEST(FutureMoveSequenceWithFailuresTest, sequenceQMap)
{
sequenceMoveHelper<TestFixture, CopyCountQMap>([](typename TestFixture::Source &&futures) {
return TestFuture<int>::sequenceWithFailures<CopyCountQMap>(std::move(futures));
});
}
TYPED_TEST(FutureMoveSequenceWithFailuresTest, sequenceQHash)
{
sequenceMoveHelper<TestFixture, CopyCountQHash>([](typename TestFixture::Source &&futures) {
return TestFuture<int>::sequenceWithFailures<CopyCountQHash>(std::move(futures));
});
}
#endif
template <typename TestFixture, template <typename...> typename Container, typename Func>
void sequenceNegativeMoveHelper(Func &&sequencer)
{
using Result = std::decay_t<decltype(sequencer(typename TestFixture::Source()).resultRef().first)>;
using FailuresResult = std::decay_t<decltype(sequencer(typename TestFixture::Source()).resultRef().first)>;
Result::copyCounter = 0;
Result::createCounter = 0;
FailuresResult::copyCounter = 0;
FailuresResult::createCounter = 0;
std::vector<TestPromise<int>> promises;
for (int i = 0; i < TestFixture::N; ++i)
asynqro::traverse::detail::containers::add(promises, TestPromise<int>());
auto sequencedFuture = sequencer(
traverse::map(promises, [](const auto &p) { return p.future(); }, std::move(typename TestFixture::Source())));
for (size_t i = 0; i < TestFixture::N; ++i) {
EXPECT_FALSE(sequencedFuture.isCompleted()) << i;
if (i == TestFixture::N - 2 || i == TestFixture::N - 4)
promises[i].failure("failed");
else
promises[i].success(i * 2);
}
ASSERT_TRUE(sequencedFuture.isCompleted());
EXPECT_TRUE(sequencedFuture.isSucceeded());
EXPECT_FALSE(sequencedFuture.isFailed());
const auto &result = sequencedFuture.resultRef().first;
ASSERT_EQ(TestFixture::N - 2, result.size());
ASSERT_FALSE(result.count(TestFixture::N - 2));
ASSERT_FALSE(result.count(TestFixture::N - 4));
traverse::map(result,
[](auto index, auto value) {
EXPECT_EQ(index * 2, value) << index;
return true;
},
std::set<bool>());
const auto &failures = sequencedFuture.resultRef().second;
ASSERT_EQ(2, failures.size());
ASSERT_TRUE(failures.count(TestFixture::N - 4));
EXPECT_EQ("failed", failures[TestFixture::N - 4]);
ASSERT_TRUE(failures.count(TestFixture::N - 2));
EXPECT_EQ("failed", failures[TestFixture::N - 2]);
EXPECT_EQ(0, Result::copyCounter);
EXPECT_EQ(1, Result::createCounter);
EXPECT_EQ(0, FailuresResult::copyCounter);
EXPECT_EQ(1, FailuresResult::createCounter);
EXPECT_EQ(0, TestFixture::Source::copyCounter);
EXPECT_EQ(1, TestFixture::Source::createCounter);
static_assert(detail::IsSpecialization_V<std::decay_t<decltype(result)>, Container>);
static_assert(detail::IsSpecialization_V<std::decay_t<decltype(failures)>, Container>);
}
TYPED_TEST(FutureMoveSequenceWithFailuresTest, sequenceNegative)
{
sequenceNegativeMoveHelper<TestFixture, CopyCountUnorderedMap>([](typename TestFixture::Source &&futures) {
return TestFuture<int>::sequenceWithFailures<CopyCountUnorderedMap>(std::move(futures));
});
}
TYPED_TEST(FutureMoveSequenceWithFailuresTest, sequenceNegativeMap)
{
sequenceNegativeMoveHelper<TestFixture, CopyCountMap>([](typename TestFixture::Source &&futures) {
return TestFuture<int>::sequenceWithFailures<CopyCountMap>(std::move(futures));
});
}
#ifdef ASYNQRO_QT_SUPPORT
TYPED_TEST(FutureMoveSequenceWithFailuresTest, sequenceNegativeQMap)
{
sequenceNegativeMoveHelper<TestFixture, CopyCountQMap>([](typename TestFixture::Source &&futures) {
return TestFuture<int>::sequenceWithFailures<CopyCountQMap>(std::move(futures));
});
}
TYPED_TEST(FutureMoveSequenceWithFailuresTest, sequenceNegativeQHash)
{
sequenceNegativeMoveHelper<TestFixture, CopyCountQHash>([](typename TestFixture::Source &&futures) {
return TestFuture<int>::sequenceWithFailures<CopyCountQHash>(std::move(futures));
});
}
#endif
template <typename TestFixture, template <typename...> typename Container, typename Func>
void sequenceAllNegativeMoveHelper(Func &&sequencer)
{
using Result = std::decay_t<decltype(sequencer(typename TestFixture::Source()).resultRef().first)>;
using FailuresResult = std::decay_t<decltype(sequencer(typename TestFixture::Source()).resultRef().first)>;
Result::copyCounter = 0;
Result::createCounter = 0;
FailuresResult::copyCounter = 0;
FailuresResult::createCounter = 0;
std::vector<TestPromise<int>> promises;
for (int i = 0; i < TestFixture::N; ++i)
asynqro::traverse::detail::containers::add(promises, TestPromise<int>());
auto sequencedFuture = sequencer(
traverse::map(promises, [](const auto &p) { return p.future(); }, std::move(typename TestFixture::Source())));
for (size_t i = 0; i < TestFixture::N; ++i) {
EXPECT_FALSE(sequencedFuture.isCompleted()) << i;
if (i == TestFixture::N - 2)
promises[i].failure("other");
else
promises[i].failure("failed");
}
ASSERT_TRUE(sequencedFuture.isCompleted());
EXPECT_TRUE(sequencedFuture.isSucceeded());
EXPECT_FALSE(sequencedFuture.isFailed());
const auto &result = sequencedFuture.resultRef().first;
ASSERT_TRUE(result.empty());
const auto &failures = sequencedFuture.resultRef().second;
ASSERT_EQ(TestFixture::N, failures.size());
traverse::map(failures,
[](auto index, const std::string &value) {
if (index == TestFixture::N - 2)
EXPECT_EQ("other", value) << index;
else
EXPECT_EQ("failed", value) << index;
return true;
},
std::set<bool>());
EXPECT_EQ(0, Result::copyCounter);
EXPECT_EQ(1, Result::createCounter);
EXPECT_EQ(0, FailuresResult::copyCounter);
EXPECT_EQ(1, FailuresResult::createCounter);
EXPECT_EQ(0, TestFixture::Source::copyCounter);
EXPECT_EQ(1, TestFixture::Source::createCounter);
static_assert(detail::IsSpecialization_V<std::decay_t<decltype(result)>, Container>);
static_assert(detail::IsSpecialization_V<std::decay_t<decltype(failures)>, Container>);
}
TYPED_TEST(FutureMoveSequenceWithFailuresTest, sequenceAllNegative)
{
sequenceAllNegativeMoveHelper<TestFixture, CopyCountUnorderedMap>([](typename TestFixture::Source &&futures) {
return TestFuture<int>::sequenceWithFailures<CopyCountUnorderedMap>(std::move(futures));
});
}
TYPED_TEST(FutureMoveSequenceWithFailuresTest, sequenceAllNegativeMap)
{
sequenceAllNegativeMoveHelper<TestFixture, CopyCountMap>([](typename TestFixture::Source &&futures) {
return TestFuture<int>::sequenceWithFailures<CopyCountMap>(std::move(futures));
});
}
#ifdef ASYNQRO_QT_SUPPORT
TYPED_TEST(FutureMoveSequenceWithFailuresTest, sequenceAllNegativeQMap)
{
sequenceAllNegativeMoveHelper<TestFixture, CopyCountQMap>([](typename TestFixture::Source &&futures) {
return TestFuture<int>::sequenceWithFailures<CopyCountQMap>(std::move(futures));
});
}
TYPED_TEST(FutureMoveSequenceWithFailuresTest, sequenceAllNegativeQHash)
{
sequenceAllNegativeMoveHelper<TestFixture, CopyCountQHash>([](typename TestFixture::Source &&futures) {
return TestFuture<int>::sequenceWithFailures<CopyCountQHash>(std::move(futures));
});
}
#endif
| 39.554511 | 118 | 0.676757 | opensoft |
84e08c0e96253bb5bc5846fda80a7e37d673ff52 | 1,500 | cpp | C++ | LPA-TPS/KnightsInFEN.cpp | OttoWBitt/LPA | 706596b64b38cff690dcc624998a70bd0929ea27 | [
"MIT"
] | 1 | 2018-08-23T17:31:23.000Z | 2018-08-23T17:31:23.000Z | LPA-TPS/KnightsInFEN.cpp | OttoWBitt/LPA | 706596b64b38cff690dcc624998a70bd0929ea27 | [
"MIT"
] | null | null | null | LPA-TPS/KnightsInFEN.cpp | OttoWBitt/LPA | 706596b64b38cff690dcc624998a70bd0929ea27 | [
"MIT"
] | null | null | null | /*
Nome: Otto Bittencourt
Matricula: 504654
LPA
*/
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int loop = 0;
char board[5][5];
char target[5][5] = {
'1', '1', '1', '1', '1',
'0', '1', '1', '1', '1',
'0', '0', ' ', '1', '1',
'0', '0', '0', '0', '1',
'0', '0', '0', '0', '0',
};
int cont;
int movex[8] = { 1, 2, 2, 1, -1, -2, -2, -1,};
int movey[8] = { -2, -1, 1, 2, 2, 1, -1, -2,};
bool ehValido(int pri, int seg) {
if (pri >= 5 || pri < 0)return false;
if (seg >= 5 || seg < 0)return false;
return true;
}
void dfs(int cont2, int x, int y) {
if (cont2 == 11){
return;
}
if (memcmp(board, target, sizeof(board)) == 0) {
cont = min(cont, cont2);
return;
}
for (int i = 0; i < 8; i++) {
int xx = x + movex[i];
int yy = y + movey[i];
if (ehValido(xx, yy)) {
swap(board[x][y], board[xx][yy]);
dfs(cont2 + 1, xx, yy);
loop++;
swap(board[x][y], board[xx][yy]);
}
}
}
int main() {
int numeroDeCasos;
cin >> numeroDeCasos;
string ent1;
getline(cin, ent1);
for (int i = 0; i < numeroDeCasos; i++) {
int x, y;
for (int j = 0; j < 5; j++) {
getline(cin, ent1);
for (int k = 0; k < 5; k++) {
board[j][k] = ent1[k];
if (ent1[k] == ' ') {
x = j;
y = k;
}
}
}
cont = 11;
dfs(0, x, y);
if (cont == 11) {
printf("Unsolvable in less than 11 move(s).\n");
}
else {
printf("Solvable in %d move(s).\n", cont);
}
//printf("contador eh %d \n",loop);
}
return 0;
}
| 15.625 | 51 | 0.486 | OttoWBitt |
84e0bb08d41b721206af82aade2a49e8c08200b3 | 9,365 | cpp | C++ | modules/task_3/olenin_method_conjugate_gradient/gradient.cpp | Oskg/pp_2021_autumn | c05d35f4d4b324cc13e58188b4a0c0174f891976 | [
"BSD-3-Clause"
] | 1 | 2021-12-09T17:20:25.000Z | 2021-12-09T17:20:25.000Z | modules/task_3/olenin_method_conjugate_gradient/gradient.cpp | Oskg/pp_2021_autumn | c05d35f4d4b324cc13e58188b4a0c0174f891976 | [
"BSD-3-Clause"
] | null | null | null | modules/task_3/olenin_method_conjugate_gradient/gradient.cpp | Oskg/pp_2021_autumn | c05d35f4d4b324cc13e58188b4a0c0174f891976 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2021 Olenin Sergey
#include <mpi.h>
#include <ctime>
#include <random>
#include <vector>
#include "../../../modules/task_3/olenin_method_conjugate_gradient/gradient.h"
std::vector<double> rand_matrix(int size) {
if (0 >= size) throw "wrong matrix size";
std::default_random_engine gene;
gene.seed(static_cast<unsigned int>(time(0)));
int sizematrix = size * size;
std::vector<double> rand_matrix(sizematrix);
for (int Index = 0; Index < size; ++Index) {
for (int Jindex = Index; Jindex < size; ++Jindex) {
rand_matrix[Index * size + Jindex] = gene() % 10;
rand_matrix[Jindex * size + Index] = rand_matrix[Index * size + Jindex];
}
}
return rand_matrix;
}
std::vector<double> rand_vec(int size) {
if (0 >= size) throw "wrong size of vector";
std::default_random_engine gene;
gene.seed(static_cast<unsigned int>(time(0)));
std::vector<double> vec(size);
for (int index = 0; index < size; ++index) {
vec[index] = 1 + gene() % 10;
}
return vec;
}
double vec_mult(const std::vector<double>& vec_a,
const std::vector<double>& vec_b) {
if (vec_a.size() != vec_b.size()) throw "vector sizes are not consistent ";
double multi = 0.0;
for (size_t index = 0; index < vec_a.size(); ++index)
multi += vec_a[index] * vec_b[index];
return multi;
}
std::vector<double> matrix_vec_mult(const std::vector<double>& matrix,
const std::vector<double>& vec) {
if ((matrix.size() % vec.size()) != 0)
throw "matrix and vector sizes are incompatible";
std::vector<double> multi(matrix.size() / vec.size());
for (size_t Index = 0; Index < (matrix.size() / vec.size()); ++Index) {
multi[Index] = 0.0;
for (size_t Jindex = 0; Jindex < vec.size(); ++Jindex) {
multi[Index] += matrix[Index * vec.size() + Jindex] * vec[Jindex];
}
}
return multi;
}
std::vector<double> get_sol_for_one_proc(const std::vector<double>& matrix,
const std::vector<double>& vec, int size) {
if (size <= 0) throw "wrong size";
int iteration = 0;
double alpha = 0.0, beta = 0.0;
double norm_residual = 0.0, criteria = 0.1;
std::vector<double> x(size);
for (int index = 0; index < size; index++) {
x[index] = 1;
}
std::vector<double> Az = matrix_vec_mult(matrix, x);
std::vector<double> residualprev(size), residualnext(size);
for (int index = 0; index < size; index++)
residualprev[index] = vec[index] - Az[index];
// residualprev^(k) = b - A * x
std::vector<double> gradient(residualprev);
// gradient = r^(k)
do {
iteration++;
Az = matrix_vec_mult(matrix, gradient);
// Az = A * gradient
alpha = vec_mult(residualprev, residualprev) / vec_mult(gradient, Az);
for (int index = 0; index < size; index++) {
x[index] += alpha * gradient[index];
residualnext[index] = residualprev[index] - alpha * Az[index];
// residualnext^(k+1) = residualprev^(k)-alpha*Az
}
beta = vec_mult(residualnext, residualnext) /
vec_mult(residualprev, residualprev);
norm_residual = sqrt(vec_mult(residualnext, residualnext));
for (int index = 0; index < size; index++)
gradient[index] = residualnext[index] + beta * gradient[index];
// gradient^(k+1) = residualnext^(k+1) + beta*gradient^(k)
residualprev = residualnext;
} while ((norm_residual > criteria) && (iteration <= size));
return x;
}
std::vector<double> get_sol_for_multiply_proc(
const std::vector<double>& matrix,
const std::vector<double>& vec,
int size) {
if (0 >= size) throw "wrong size";
std::vector<double> matrixtmp = matrix;
std::vector<double> vectortmp = vec;
MPI_Bcast(matrixtmp.data(), size * size, MPI_DOUBLE, 0, MPI_COMM_WORLD);
MPI_Bcast(vectortmp.data(), size, MPI_DOUBLE, 0, MPI_COMM_WORLD);
int size_comm, rank;
MPI_Comm_size(MPI_COMM_WORLD, &size_comm);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int k_rows = size / size_comm;
int balance = size % size_comm;
std::vector<double> matrixL(k_rows * size);
if (0 == rank) {
if (0 != balance) {
matrixL.resize(size * k_rows + balance * size);
}
if (0 != k_rows) {
for (int process = 1; process < size_comm; process++) {
MPI_Send(&matrixtmp[0] + process * k_rows * size + balance * size,
k_rows * size, MPI_DOUBLE, process, 1, MPI_COMM_WORLD);
}
}
}
if (0 == rank) {
if (balance != 0) {
for (int index = 0; index < size * k_rows + size * balance; index++) {
matrixL[index] = matrixtmp[index];
}
} else {
for (int index = 0; index < size * k_rows; index++) {
matrixL[index] = matrixtmp[index];
}
}
} else {
MPI_Status message;
if (k_rows != 0) {
MPI_Recv(&matrixL[0], k_rows * size, MPI_DOUBLE, 0, 1, MPI_COMM_WORLD,
&message);
}
}
int iteration = 0;
double beta = 0.0, alpha = 0.0;
double norm_residual = 0.0, criteria = 0.1;
std::vector<double> x(size);
for (int index = 0; index < size; index++) {
x[index] = 1;
}
std::vector<double> Az = matrix_vec_mult(matrixL, x);
std::vector<double> residualprev(k_rows), residualnext(k_rows);
if (0 == rank) {
if (0 != balance) {
residualprev.resize(k_rows + balance);
residualnext.resize(k_rows + balance);
}
for (int index = 0; index < k_rows + balance; index++)
residualprev[index] = vectortmp[index] - Az[index];
// residualprev^(k) = b - A * x
} else {
for (int index = 0; index < k_rows; index++)
residualprev[index] =
vectortmp[rank * k_rows + balance + index] - Az[index];
// residualprev^(k) = b - A * x
}
std::vector<double> gradient(size);
// gradient = residualprev^(k)
if (rank == 0) {
if (balance != 0) {
for (int index = 0; index < k_rows + balance; index++) {
gradient[index] = residualprev[index];
}
} else {
for (int index = 0; index < k_rows; index++) {
gradient[index] = residualprev[index];
}
}
if (k_rows != 0) {
MPI_Status message;
for (int process = 1; process < size_comm; process++) {
MPI_Recv(&gradient[0] + process * k_rows + balance, k_rows, MPI_DOUBLE,
process, 2, MPI_COMM_WORLD, &message);
}
}
} else {
if (k_rows != 0) {
MPI_Send(&residualprev[0], k_rows, MPI_DOUBLE, 0, 2, MPI_COMM_WORLD);
}
}
MPI_Bcast(gradient.data(), size, MPI_DOUBLE, 0, MPI_COMM_WORLD);
std::vector<double> gradientblock(k_rows);
std::vector<double> gradientlocal(k_rows);
if (rank == 0) {
if (balance != 0) {
gradientblock.resize(k_rows + balance);
}
}
do {
iteration++;
Az = matrix_vec_mult(matrixL, gradient); // Az = A * gradient
if (rank == 0) {
for (int index = 0; index < k_rows + balance; index++) {
gradientblock[index] = gradient[index];
}
} else {
for (int index = 0; index < k_rows; index++) {
gradientblock[index] = gradient[rank * k_rows + balance + index];
}
}
double tmp_f = vec_mult(residualprev, residualprev);
double tmp_s = vec_mult(gradientblock, Az);
double residualprevscalar;
double devideralpha;
MPI_Allreduce(&tmp_f, &residualprevscalar, 1, MPI_DOUBLE, MPI_SUM,
MPI_COMM_WORLD);
MPI_Allreduce(&tmp_s, &devideralpha, 1, MPI_DOUBLE, MPI_SUM,
MPI_COMM_WORLD);
alpha = residualprevscalar / devideralpha;
for (int index = 0; index < size; index++) {
x[index] += alpha * gradient[index];
}
if (rank == 0) {
for (int index = 0; index < k_rows + balance; index++) {
residualnext[index] = residualprev[index] - alpha * Az[index];
// residualnext^(k+1) = residualprev^(k)-alpha*Az
}
} else {
for (int index = 0; index < k_rows; index++) {
residualnext[index] = residualprev[index] - alpha * Az[index];
// residualnext^(k+1) = residualprev^(k)-alpha*Az
}
}
double residualnextscalar;
tmp_f = vec_mult(residualnext, residualnext);
MPI_Allreduce(&tmp_f, &residualnextscalar, 1, MPI_DOUBLE, MPI_SUM,
MPI_COMM_WORLD);
beta = residualnextscalar / residualprevscalar;
norm_residual = sqrt(residualnextscalar);
if (rank == 0) {
for (int index = 0; index < k_rows + balance; index++) {
gradient[index] = residualnext[index] + beta * gradient[index];
}
if (k_rows != 0) {
MPI_Status message;
for (int process = 1; process < size_comm; process++) {
MPI_Recv(&gradient[0] + process * k_rows + balance,
k_rows, MPI_DOUBLE, process, 3, MPI_COMM_WORLD, &message);
}
}
} else {
for (int index = 0; index < k_rows; index++) {
gradientlocal[index] = residualnext[index] +
beta * gradient[rank * k_rows + balance + index];
}
if (k_rows != 0) {
MPI_Send(&gradientlocal[0], k_rows, MPI_DOUBLE, 0, 3, MPI_COMM_WORLD);
}
}
MPI_Bcast(gradient.data(), size, MPI_DOUBLE, 0, MPI_COMM_WORLD);
residualprev = residualnext;
} while ((norm_residual > criteria) && (iteration <= size));
return x;
}
| 28.207831 | 80 | 0.593914 | Oskg |
84e1d56ff8faac504ce60f40a4db29830ca9f906 | 32,087 | cpp | C++ | distributions/univariate/continuous/StableRand.cpp | aWeinzierl/RandLib | 7af0237d1902aadbf2451b7dfab02c52cf98ae87 | [
"MIT"
] | null | null | null | distributions/univariate/continuous/StableRand.cpp | aWeinzierl/RandLib | 7af0237d1902aadbf2451b7dfab02c52cf98ae87 | [
"MIT"
] | null | null | null | distributions/univariate/continuous/StableRand.cpp | aWeinzierl/RandLib | 7af0237d1902aadbf2451b7dfab02c52cf98ae87 | [
"MIT"
] | null | null | null | #include "StableRand.h"
#include "LevyRand.h"
#include "CauchyRand.h"
#include "NormalRand.h"
#include "UniformRand.h"
#include "ExponentialRand.h"
#include <functional>
StableDistribution::StableDistribution(double exponent, double skewness, double scale, double location)
{
SetParameters(exponent, skewness, scale, location);
}
SUPPORT_TYPE StableDistribution::SupportType() const
{
if (alpha < 1) {
if (beta == 1)
return RIGHTSEMIFINITE_T;
if (beta == -1)
return LEFTSEMIFINITE_T;
}
return INFINITE_T;
}
double StableDistribution::MinValue() const
{
return (alpha < 1 && beta == 1) ? mu : -INFINITY;
}
double StableDistribution::MaxValue() const
{
return (alpha < 1 && beta == -1) ? mu : INFINITY;
}
void StableDistribution::SetParameters(double exponent, double skewness, double scale, double location)
{
if (exponent < 0.1 || exponent > 2.0)
throw std::invalid_argument("Stable distribution: exponent should be in the interval [0.1, 2]");
if (std::fabs(skewness) > 1.0)
throw std::invalid_argument("Stable distribution: skewness of should be in the interval [-1, 1]");
if (scale <= 0.0)
throw std::invalid_argument("Stable distribution: scale should be positive");
/// the following errors should be removed soon
if (exponent != 1.0 && std::fabs(exponent - 1.0) < 0.01 && skewness != 0.0)
throw std::invalid_argument("Stable distribution: exponent close to 1 with non-zero skewness is not yet supported");
if (exponent == 1.0 && skewness != 0.0 && std::fabs(skewness) < 0.01)
throw std::invalid_argument("Stable distribution: skewness close to 0 with exponent equal to 1 is not yet supported");
alpha = exponent;
alphaInv = 1.0 / alpha;
beta = skewness;
mu = location;
gamma = scale;
logGamma = std::log(gamma);
/// Set id of distribution
if (alpha == 2.0)
distributionType = NORMAL;
else if (alpha == 1.0)
distributionType = (beta == 0.0) ? CAUCHY : UNITY_EXPONENT;
else if (alpha == 0.5 && std::fabs(beta) == 1.0)
distributionType = LEVY;
else
distributionType = GENERAL;
alpha_alpham1 = alpha / (alpha - 1.0);
if (distributionType == NORMAL)
pdfCoef = M_LN2 + logGamma + 0.5 * M_LNPI;
else if (distributionType == LEVY)
pdfCoef = logGamma - M_LN2 - M_LNPI;
else if (distributionType == CAUCHY)
pdfCoef = -logGamma - M_LNPI;
else if (distributionType == UNITY_EXPONENT) {
pdfCoef = 0.5 / (gamma * std::fabs(beta));
pdftailBound = 0; // not in the use for now
logGammaPi_2 = logGamma + M_LNPI - M_LN2;
}
else if (distributionType == GENERAL) {
if (beta != 0.0) {
zeta = -beta * std::tan(M_PI_2 * alpha);
omega = 0.5 * alphaInv * std::log1p(zeta * zeta);
xi = alphaInv * RandMath::atan(-zeta);
}
else {
zeta = omega = xi = 0.0;
}
pdfCoef = M_1_PI * std::fabs(alpha_alpham1) / gamma;
pdftailBound = 3.0 / (1.0 + alpha) * M_LN10;
cdftailBound = 3.0 / alpha * M_LN10;
/// define boundaries of region near 0, where we use series expansion
if (alpha <= ALMOST_TWO) {
seriesZeroParams.first = std::round(std::min(alpha * alpha * 40 + 1, 10.0));
/// corresponds to boundaries from 10^(-15.5) to ~ 0.056
seriesZeroParams.second = -(alphaInv * 1.5 + 0.5) * M_LN10;
}
else {
seriesZeroParams.first = 85;
/// corresponds to 6
seriesZeroParams.second = M_LN2 + M_LN3;
}
}
}
void StableDistribution::SetLocation(double location)
{
mu = location;
}
void StableDistribution::SetScale(double scale)
{
if (scale <= 0.0)
throw std::invalid_argument("Scale of Stable distribution should be positive");
gamma = scale;
logGamma = std::log(gamma);
if (distributionType == NORMAL)
pdfCoef = M_LN2 + logGamma + 0.5 * M_LNPI;
else if (distributionType == LEVY)
pdfCoef = logGamma - M_LN2 - M_LNPI;
else if (distributionType == CAUCHY)
pdfCoef = -logGamma - M_LNPI;
else if (distributionType == UNITY_EXPONENT) {
pdfCoef = 0.5 / (gamma * std::fabs(beta));
logGammaPi_2 = logGamma + M_LNPI - M_LN2;
}
else if (distributionType == GENERAL)
pdfCoef = M_1_PI * std::fabs(alpha_alpham1) / gamma;
}
double StableDistribution::pdfNormal(double x) const
{
return std::exp(logpdfNormal(x));
}
double StableDistribution::logpdfNormal(double x) const
{
double y = x - mu;
y *= 0.5 / gamma;
y *= y;
y += pdfCoef;
return -y;
}
double StableDistribution::pdfCauchy(double x) const
{
double y = x - mu;
y *= y;
y /= gamma;
y += gamma;
return M_1_PI / y;
}
double StableDistribution::logpdfCauchy(double x) const
{
double x0 = x - mu;
x0 /= gamma;
double xSq = x0 * x0;
return pdfCoef - std::log1p(xSq);
}
double StableDistribution::pdfLevy(double x) const
{
return (x <= mu) ? 0.0 : std::exp(logpdfLevy(x));
}
double StableDistribution::logpdfLevy(double x) const
{
double x0 = x - mu;
if (x0 <= 0.0)
return -INFINITY;
double y = gamma / x0;
y += 3 * std::log(x0);
y -= pdfCoef;
return -0.5 * y;
}
double StableDistribution::fastpdfExponentiation(double u)
{
if (u > 5 || u < -50)
return 0.0;
return (u < -25) ? std::exp(u) : std::exp(u - std::exp(u));
}
double StableDistribution::pdfShortTailExpansionForUnityExponent(double x) const
{
if (x > 10)
return 0.0;
double xm1 = x - 1.0;
double y = 0.5 * xm1 - std::exp(xm1);
y -= 0.5 * (M_LN2 + M_LNPI);
return std::exp(y);
}
double StableDistribution::limitCaseForIntegrandAuxForUnityExponent(double theta, double xAdj) const
{
if (theta > 0.0) {
if (beta > 0.0)
return BIG_NUMBER;
return (beta == -1) ? xAdj - 1.0 : -BIG_NUMBER;
}
if (beta < 0.0)
return BIG_NUMBER;
return (beta == 1) ? xAdj - 1.0 : -BIG_NUMBER;
}
double StableDistribution::integrandAuxForUnityExponent(double theta, double xAdj) const
{
if (std::fabs(theta) >= M_PI_2)
return limitCaseForIntegrandAuxForUnityExponent(theta, xAdj);
if (theta == 0.0)
return xAdj + M_LNPI - M_LN2;
double thetaAdj = (M_PI_2 + beta * theta) / std::cos(theta);
double u = std::log(thetaAdj);
u += thetaAdj * std::sin(theta) / beta;
return std::isfinite(u) ? u + xAdj : limitCaseForIntegrandAuxForUnityExponent(theta, xAdj);
}
double StableDistribution::integrandForUnityExponent(double theta, double xAdj) const
{
if (std::fabs(theta) >= M_PI_2)
return 0.0;
double u = integrandAuxForUnityExponent(theta, xAdj);
return fastpdfExponentiation(u);
}
double StableDistribution::pdfForUnityExponent(double x) const
{
double xSt = (x - mu) / gamma;
double xAdj = -M_PI_2 * xSt / beta - logGammaPi_2;
/// We squeeze boudaries for too peaked integrands
double boundary = RandMath::atan(M_2_PI * beta * (5.0 - xAdj));
double upperBoundary = (beta > 0.0) ? boundary : M_PI_2;
double lowerBoundary = (beta < 0.0) ? boundary : -M_PI_2;
/// Find peak of the integrand
double theta0 = 0;
std::function<double (double)> funPtr = std::bind(&StableDistribution::integrandAuxForUnityExponent, this, std::placeholders::_1, xAdj);
RandMath::findRoot(funPtr, lowerBoundary, upperBoundary, theta0);
/// Sanity check
/// if we failed while looking for the peak position
/// we set it in the middle between boundaries
if (theta0 >= upperBoundary || theta0 <= lowerBoundary)
theta0 = 0.5 * (upperBoundary + lowerBoundary);
std::function<double (double)> integrandPtr = std::bind(&StableDistribution::integrandForUnityExponent, this, std::placeholders::_1, xAdj);
/// If theta0 is too close to +/-π/2 then we can still underestimate the integral
int maxRecursionDepth = 11;
double closeness = M_PI_2 - std::fabs(theta0);
if (closeness < 0.1)
maxRecursionDepth = 20;
else if (closeness < 0.2)
maxRecursionDepth = 15;
double int1 = RandMath::integral(integrandPtr, lowerBoundary, theta0, 1e-11, maxRecursionDepth);
double int2 = RandMath::integral(integrandPtr, theta0, upperBoundary, 1e-11, maxRecursionDepth);
return pdfCoef * (int1 + int2);
}
double StableDistribution::pdfShortTailExpansionForGeneralExponent(double logX) const
{
double logAlpha = std::log(alpha);
double log1mAlpha = (alpha < 1) ? std::log1p(-alpha) : std::log(alpha - 1);
double temp = logX - logAlpha;
double y = std::exp(alpha_alpham1 * temp);
y *= -std::fabs(1.0 - alpha);
double z = (1.0 - 0.5 * alpha) / (alpha - 1) * temp;
z -= 0.5 * (M_LN2 + M_LNPI + logAlpha + log1mAlpha);
return std::exp(y + z);
}
double StableDistribution::pdfAtZero() const
{
double y0 = 0.0;
if (beta == 0.0)
y0 = std::tgamma(alphaInv);
else {
y0 = std::lgamma(alphaInv) - omega;
y0 = std::exp(y0) * std::cos(xi);
}
return y0 * M_1_PI / alpha;
}
double StableDistribution::pdfSeriesExpansionAtZero(double logX, double xiAdj, int k) const
{
/// Calculate first term of the sum
/// (if x = 0, only this term is non-zero)
double y0 = pdfAtZero();
double sum = 0.0;
if (beta == 0.0) {
/// Symmetric distribution
for (int n = 1; n <= k; ++n)
{
int n2 = n + n;
double term = std::lgamma((n2 + 1) / alpha);
term += n2 * logX;
term -= RandMath::lfact(n2);
term = std::exp(term);
sum += (n & 1) ? -term : term;
}
}
else {
/// Asymmetric distribution
double rhoPi_alpha = M_PI_2 + xiAdj;
for (int n = 1; n <= k; ++n) {
int np1 = n + 1;
double term = std::lgamma(np1 * alphaInv);
term += n * logX;
term -= RandMath::lfact(n);
term = std::exp(term - omega);
term *= std::sin(np1 * rhoPi_alpha);
sum += (n & 1) ? -term : term;
}
}
return y0 + sum * M_1_PI / alpha;
}
double StableDistribution::pdfSeriesExpansionAtInf(double logX, double xiAdj) const
{
static constexpr int k = 10; ///< number of elements in the series
double rhoPi = M_PI_2 + xiAdj;
rhoPi *= alpha;
double sum = 0.0;
for (int n = 1; n <= k; ++n) {
double aux = n * alpha + 1.0;
double term = std::lgamma(aux);
term -= aux * logX;
term -= RandMath::lfact(n);
term = std::exp(term - omega);
term *= std::sin(rhoPi * n);
sum += (n & 1) ? term : -term;
}
return M_1_PI * sum;
}
double StableDistribution::pdfTaylorExpansionTailNearCauchy(double x) const
{
double xSq = x * x;
double y = 1.0 + xSq;
double ySq = y * y;
double z = RandMath::atan(x);
double zSq = z * z;
double logY = std::log1p(xSq);
double alpham1 = alpha - 1.0;
double temp = 1.0 - M_EULER - 0.5 * logY;
/// first derivative
double f_a = temp;
f_a *= xSq - 1.0;
f_a += 2 * x * z;
f_a /= ySq;
static constexpr long double M_PI_SQ_6 = 1.64493406684822643647l; /// π^2 / 6
/// second derivative
double f_aa1 = M_PI_SQ_6;
f_aa1 += temp * temp;
f_aa1 -= 1.0 + z * z;
f_aa1 *= xSq * xSq - 6.0 * xSq + 1.0;
double f_aa2 = 0.5 + temp;
f_aa2 *= z;
f_aa2 *= 8 * x * (xSq - 1.0);
double f_aa3 = (1.0 - 3 * xSq) * temp;
f_aa3 -= x * y * z;
f_aa3 += f_aa3;
double f_aa = f_aa1 + f_aa2 + f_aa3;
f_aa /= std::pow(y, 3);
/// Hashed values of special functions for x = 2, 3, 4
/// Gamma(x)
static constexpr int gammaTable[] = {1, 2, 6};
/// Gamma'(x)
static constexpr long double gammaDerTable[] = {1.0 - M_EULER, 3.0 - 2.0 * M_EULER, 11.0 - 6.0 * M_EULER};
/// Gamma''(x)
static constexpr long double gammaSecDerTable[] = {0.82368066085287938958l, 2.49292999190269305794l, 11.1699273161019477314l};
/// Digamma(x)
static constexpr long double digammaTable[] = {1.0 - M_EULER, 1.5 - M_EULER, 11.0 / 6 - M_EULER};
/// Digamma'(x)
static constexpr long double digammaDerTable[] = {M_PI_SQ_6 - 1.0, M_PI_SQ_6 - 1.25, M_PI_SQ_6 - 49.0 / 36};
/// Digamma''(x)
static constexpr long double digammaSecDerTable[] = {-0.40411380631918857080l, -0.15411380631918857080l, -0.08003973224511449673l};
/// third derivative
double gTable[] = {0, 0, 0};
for (int i = 0; i < 3; ++i) {
double g_11 = 0.25 * gammaTable[i] * logY * logY;
g_11 -= gammaDerTable[i] * logY;
g_11 += gammaSecDerTable[i];
double aux = digammaTable[i] - 0.5 * logY;
double g_12 = aux;
double zip2 = z * (i + 2);
double cosZNu = std::cos(zip2), zSinZNu = z * std::sin(zip2);
g_12 *= cosZNu;
g_12 -= zSinZNu;
double g_1 = g_11 * g_12;
double g_21 = -gammaTable[i] * logY + 2 * gammaDerTable[i];
double g_22 = -zSinZNu * aux;
g_22 -= zSq * cosZNu;
g_22 += cosZNu * digammaDerTable[i];
double g_2 = g_21 * g_22;
double g_3 = -zSq * cosZNu * aux;
g_3 -= 2 * zSinZNu * digammaDerTable[i];
g_3 += zSq * zSinZNu;
g_3 += cosZNu * digammaSecDerTable[i];
g_3 *= gammaTable[i];
double g = g_1 + g_2 + g_3;
g *= std::pow(y, -0.5 * i - 1);
gTable[i] = g;
}
double f_aaa = -gTable[0] + 3 * gTable[1] - gTable[2];
/// summarize all three derivatives
double tail = f_a * alpham1;
tail += 0.5 * f_aa * alpham1 * alpham1;
tail += std::pow(alpham1, 3) * f_aaa / 6.0;
tail /= M_PI;
return tail;
}
double StableDistribution::limitCaseForIntegrandAuxForGeneralExponent(double theta, double xiAdj) const
{
/// We got numerical error, need to investigate to which extreme point we are closer
if (theta < 0.5 * (M_PI_2 - xiAdj))
return alpha < 1 ? -BIG_NUMBER : BIG_NUMBER;
return alpha < 1 ? BIG_NUMBER : -BIG_NUMBER;
}
double StableDistribution::integrandAuxForGeneralExponent(double theta, double xAdj, double xiAdj) const
{
if (std::fabs(theta) >= M_PI_2 || theta <= -xiAdj)
return limitCaseForIntegrandAuxForGeneralExponent(theta, xiAdj);
double thetaAdj = alpha * (theta + xiAdj);
double sinThetaAdj = std::sin(thetaAdj);
double y = std::log(std::cos(theta));
y -= alpha * std::log(sinThetaAdj);
y /= alpha - 1.0;
y += std::log(std::cos(thetaAdj - theta));
y += xAdj;
return std::isfinite(y) ? y : limitCaseForIntegrandAuxForGeneralExponent(theta, xiAdj);
}
double StableDistribution::integrandFoGeneralExponent(double theta, double xAdj, double xiAdj) const
{
if (std::fabs(theta) >= M_PI_2)
return 0.0;
if (theta <= -xiAdj)
return 0.0;
double u = integrandAuxForGeneralExponent(theta, xAdj, xiAdj);
return fastpdfExponentiation(u);
}
double StableDistribution::pdfForGeneralExponent(double x) const
{
/// Standardize
double xSt = (x - mu) / gamma;
double absXSt = xSt;
/// +- xi
double xiAdj = xi;
if (xSt > 0) {
if (alpha < 1 && beta == -1)
return 0.0;
}
else {
if (alpha < 1 && beta == 1)
return 0.0;
absXSt = -xSt;
xiAdj = -xi;
}
/// If α is too close to 1 and distribution is symmetric, then we approximate using Taylor series
if (beta == 0.0 && std::fabs(alpha - 1.0) < 0.01)
return pdfCauchy(x) + pdfTaylorExpansionTailNearCauchy(absXSt) / gamma;
/// If x = 0, we know the analytic solution
if (xSt == 0.0)
return pdfAtZero() / gamma;
double logAbsX = std::log(absXSt) - omega;
/// If x is too close to 0, we do series expansion avoiding numerical problems
if (logAbsX < seriesZeroParams.second) {
if (alpha < 1 && std::fabs(beta) == 1)
return pdfShortTailExpansionForGeneralExponent(logAbsX);
return pdfSeriesExpansionAtZero(logAbsX, xiAdj, seriesZeroParams.first) / gamma;
}
/// If x is large enough we use tail approximation
if (logAbsX > pdftailBound && alpha <= ALMOST_TWO) {
if (alpha > 1 && std::fabs(beta) == 1)
return pdfShortTailExpansionForGeneralExponent(logAbsX);
return pdfSeriesExpansionAtInf(logAbsX, xiAdj) / gamma;
}
double xAdj = alpha_alpham1 * logAbsX;
/// Search for the peak of the integrand
double theta0;
std::function<double (double)> funPtr = std::bind(&StableDistribution::integrandAuxForGeneralExponent, this, std::placeholders::_1, xAdj, xiAdj);
RandMath::findRoot(funPtr, -xiAdj, M_PI_2, theta0);
/// If theta0 is too close to π/2 or -xiAdj then we can still underestimate the integral
int maxRecursionDepth = 11;
double closeness = std::min(M_PI_2 - theta0, theta0 + xiAdj);
if (closeness < 0.1)
maxRecursionDepth = 20;
else if (closeness < 0.2)
maxRecursionDepth = 15;
/// Calculate sum of two integrals
std::function<double (double)> integrandPtr = std::bind(&StableDistribution::integrandFoGeneralExponent, this, std::placeholders::_1, xAdj, xiAdj);
double int1 = RandMath::integral(integrandPtr, -xiAdj, theta0, 1e-11, maxRecursionDepth);
double int2 = RandMath::integral(integrandPtr, theta0, M_PI_2, 1e-11, maxRecursionDepth);
double res = pdfCoef * (int1 + int2) / absXSt;
/// Finally we check if α is not too close to 2
if (alpha <= ALMOST_TWO)
return res;
/// If α is near 2, we use tail aprroximation for large x
/// and compare it with integral representation
double alphap1 = alpha + 1.0;
double tail = std::lgamma(alphap1);
tail -= alphap1 * logAbsX;
tail = std::exp(tail);
tail *= (1.0 - 0.5 * alpha) / gamma;
return std::max(tail, res);
}
double StableDistribution::f(const double & x) const
{
switch (distributionType) {
case NORMAL:
return pdfNormal(x);
case CAUCHY:
return pdfCauchy(x);
case LEVY:
return (beta > 0) ? pdfLevy(x) : pdfLevy(2 * mu - x);
case UNITY_EXPONENT:
return pdfForUnityExponent(x);
case GENERAL:
return pdfForGeneralExponent(x);
default:
return NAN; /// unexpected return
}
}
double StableDistribution::logf(const double & x) const
{
switch (distributionType) {
case NORMAL:
return logpdfNormal(x);
case CAUCHY:
return logpdfCauchy(x);
case LEVY:
return (beta > 0) ? logpdfLevy(x) : logpdfLevy(2 * mu - x);
case UNITY_EXPONENT:
return std::log(pdfForUnityExponent(x));
case GENERAL:
return std::log(pdfForGeneralExponent(x));
default:
return NAN; /// unexpected return
}
}
double StableDistribution::cdfNormal(double x) const
{
double y = mu - x;
y *= 0.5 / gamma;
return 0.5 * std::erfc(y);
}
double StableDistribution::cdfNormalCompl(double x) const
{
double y = x - mu;
y *= 0.5 / gamma;
return 0.5 * std::erfc(y);
}
double StableDistribution::cdfCauchy(double x) const
{
double x0 = x - mu;
x0 /= gamma;
return 0.5 + M_1_PI * RandMath::atan(x0);
}
double StableDistribution::cdfCauchyCompl(double x) const
{
double x0 = mu - x;
x0 /= gamma;
return 0.5 + M_1_PI * RandMath::atan(x0);
}
double StableDistribution::cdfLevy(double x) const
{
if (x <= mu)
return 0;
double y = x - mu;
y += y;
y = gamma / y;
y = std::sqrt(y);
return std::erfc(y);
}
double StableDistribution::cdfLevyCompl(double x) const
{
if (x <= mu)
return 1.0;
double y = x - mu;
y += y;
y = gamma / y;
y = std::sqrt(y);
return std::erf(y);
}
double StableDistribution::fastcdfExponentiation(double u)
{
if (u > 5.0)
return 0.0;
else if (u < -50.0)
return 1.0;
double y = std::exp(u);
return std::exp(-y);
}
double StableDistribution::cdfAtZero(double xiAdj) const
{
return 0.5 - M_1_PI * xiAdj;
}
double StableDistribution::cdfForUnityExponent(double x) const
{
double xSt = (x - mu) / gamma;
double xAdj = -M_PI_2 * xSt / beta - logGammaPi_2;
double y = M_1_PI * RandMath::integral([this, xAdj] (double theta)
{
double u = integrandAuxForUnityExponent(theta, xAdj);
return fastcdfExponentiation(u);
},
-M_PI_2, M_PI_2);
return (beta > 0) ? y : 1.0 - y;
}
double StableDistribution::cdfSeriesExpansionAtZero(double logX, double xiAdj, int k) const
{
/// Calculate first term of the sum
/// (if x = 0, only this term is non-zero)
double y0 = cdfAtZero(xiAdj);
double sum = 0.0;
if (beta == 0.0) {
/// Symmetric distribution
for (int m = 0; m <= k; ++m) {
int m2p1 = 2 * m + 1;
double term = std::lgamma(m2p1 * alphaInv);
term += m2p1 * logX;
term -= RandMath::lfact(m2p1);
term = std::exp(term);
sum += (m & 1) ? -term : term;
}
}
else {
/// Asymmetric distribution
double rhoPi_alpha = M_PI_2 + xiAdj;
for (int n = 1; n <= k; ++n) {
double term = std::lgamma(n * alphaInv);
term += n * logX;
term -= RandMath::lfact(n);
term = std::exp(term);
term *= std::sin(n * rhoPi_alpha);
sum += (n & 1) ? term : -term;
}
}
return y0 + sum * M_1_PI * alphaInv;
}
double StableDistribution::cdfSeriesExpansionAtInf(double logX, double xiAdj) const
{
static constexpr int k = 10; /// number of elements in the series
double rhoPi = M_PI_2 + xiAdj;
rhoPi *= alpha;
double sum = 0.0;
for (int n = 1; n <= k; ++n) {
double aux = n * alpha;
double term = std::lgamma(aux);
term -= aux * logX;
term -= RandMath::lfact(n);
term = std::exp(term);
term *= std::sin(rhoPi * n);
sum += (n & 1) ? term : -term;
}
return M_1_PI * sum;
}
double StableDistribution::cdfIntegralRepresentation(double logX, double xiAdj) const
{
double xAdj = alpha_alpham1 * logX;
return M_1_PI * RandMath::integral([this, xAdj, xiAdj] (double theta)
{
double u = integrandAuxForGeneralExponent(theta, xAdj, xiAdj);
return fastcdfExponentiation(u);
},
-xiAdj, M_PI_2);
}
double StableDistribution::cdfForGeneralExponent(double x) const
{
double xSt = (x - mu) / gamma; /// Standardize
if (xSt == 0)
return cdfAtZero(xi);
if (xSt > 0.0) {
double logAbsX = std::log(xSt) - omega;
/// If x is too close to 0, we do series expansion avoiding numerical problems
if (logAbsX < seriesZeroParams.second)
return cdfSeriesExpansionAtZero(logAbsX, xi, seriesZeroParams.first);
/// If x is large enough we use tail approximation
if (logAbsX > cdftailBound)
return 1.0 - cdfSeriesExpansionAtInf(logAbsX, xi);
if (alpha > 1.0)
return 1.0 - cdfIntegralRepresentation(logAbsX, xi);
return (beta == -1.0) ? 1.0 : cdfAtZero(xi) + cdfIntegralRepresentation(logAbsX, xi);
}
/// For x < 0 we use relation F(-x, xi) + F(x, -xi) = 1
double logAbsX = std::log(-xSt) - omega;
if (logAbsX < seriesZeroParams.second)
return 1.0 - cdfSeriesExpansionAtZero(logAbsX, -xi, seriesZeroParams.first);
if (logAbsX > cdftailBound)
return cdfSeriesExpansionAtInf(logAbsX, -xi);
if (alpha > 1.0)
return cdfIntegralRepresentation(logAbsX, -xi);
return (beta == 1.0) ? 0.0 : cdfAtZero(xi) - cdfIntegralRepresentation(logAbsX, -xi);
}
double StableDistribution::F(const double & x) const
{
switch (distributionType) {
case NORMAL:
return cdfNormal(x);
case CAUCHY:
return cdfCauchy(x);
case LEVY:
return (beta > 0) ? cdfLevy(x) : cdfLevyCompl(2 * mu - x);
case UNITY_EXPONENT:
return cdfForUnityExponent(x);
case GENERAL:
return cdfForGeneralExponent(x);
default:
return NAN; /// unexpected return
}
}
double StableDistribution::S(const double & x) const
{
switch (distributionType) {
case NORMAL:
return cdfNormalCompl(x);
case CAUCHY:
return cdfCauchyCompl(x);
case LEVY:
return (beta > 0) ? cdfLevyCompl(x) : cdfLevy(2 * mu - x);
case UNITY_EXPONENT:
return 1.0 - cdfForUnityExponent(x);
case GENERAL:
return 1.0 - cdfForGeneralExponent(x);
default:
return NAN; /// unexpected return
}
}
double StableDistribution::variateForUnityExponent() const
{
double U = M_PI * UniformRand::StandardVariate(localRandGenerator) - M_PI_2;
double W = ExponentialRand::StandardVariate(localRandGenerator);
double pi_2pBetaU = M_PI_2 + beta * U;
double Y = W * std::cos(U) / pi_2pBetaU;
double X = std::log(Y);
X += logGammaPi_2;
X *= -beta;
X += pi_2pBetaU * std::tan(U);
X *= M_2_PI;
return mu + gamma * X;
}
double StableDistribution::variateForGeneralExponent() const
{
double U = M_PI * UniformRand::StandardVariate(localRandGenerator) - M_PI_2;
double W = ExponentialRand::StandardVariate(localRandGenerator);
double alphaUpxi = alpha * (U + xi);
double X = std::sin(alphaUpxi);
double W_adj = W / std::cos(U - alphaUpxi);
X *= W_adj;
double R = omega - alphaInv * std::log(W_adj * std::cos(U));
X *= std::exp(R);
return mu + gamma * X;
}
double StableDistribution::variateForExponentEqualOneHalf() const
{
double Z1 = NormalRand::StandardVariate(localRandGenerator);
double Z2 = NormalRand::StandardVariate(localRandGenerator);
double temp1 = (1.0 + beta) / Z1, temp2 = (1.0 - beta) / Z2;
double var = temp1 - temp2;
var *= temp1 + temp2;
var *= 0.25;
return mu + gamma * var;
}
double StableDistribution::Variate() const
{
switch (distributionType) {
case NORMAL:
return mu + M_SQRT2 * gamma * NormalRand::StandardVariate(localRandGenerator);
case CAUCHY:
return mu + gamma * CauchyRand::StandardVariate(localRandGenerator);
case LEVY:
return mu + RandMath::sign(beta) * gamma * LevyRand::StandardVariate(localRandGenerator);
case UNITY_EXPONENT:
return variateForUnityExponent();
case GENERAL:
return (alpha == 0.5) ? variateForExponentEqualOneHalf() : variateForGeneralExponent();
default:
return NAN; /// unexpected return
}
}
void StableDistribution::Sample(std::vector<double> &outputData) const
{
switch (distributionType) {
case NORMAL: {
double stdev = M_SQRT2 * gamma;
for (double &var : outputData)
var = mu + stdev * NormalRand::StandardVariate(localRandGenerator);
}
break;
case CAUCHY: {
for (double &var : outputData)
var = mu + gamma * CauchyRand::StandardVariate(localRandGenerator);
}
break;
case LEVY: {
if (beta > 0) {
for (double &var : outputData)
var = mu + gamma * LevyRand::StandardVariate(localRandGenerator);
}
else {
for (double &var : outputData)
var = mu - gamma * LevyRand::StandardVariate(localRandGenerator);
}
}
break;
case UNITY_EXPONENT: {
for (double &var : outputData)
var = variateForUnityExponent();
}
break;
case GENERAL: {
if (alpha == 0.5) {
for (double &var : outputData)
var = variateForExponentEqualOneHalf();
}
else {
for (double &var : outputData)
var = variateForGeneralExponent();
}
}
break;
default:
break;
}
}
double StableDistribution::Mean() const
{
if (alpha > 1)
return mu;
if (beta == 1)
return INFINITY;
return (beta == -1) ? -INFINITY : NAN;
}
double StableDistribution::Variance() const
{
return (distributionType == NORMAL) ? 2 * gamma * gamma : INFINITY;
}
double StableDistribution::Mode() const
{
/// For symmetric and normal distributions mode is μ
if (beta == 0 || distributionType == NORMAL)
return mu;
if (distributionType == LEVY)
return mu + beta * gamma / 3.0;
return ContinuousDistribution::Mode();
}
double StableDistribution::Median() const
{
/// For symmetric and normal distributions mode is μ
if (beta == 0 || distributionType == NORMAL)
return mu;
return ContinuousDistribution::Median();
}
double StableDistribution::Skewness() const
{
return (distributionType == NORMAL) ? 0 : NAN;
}
double StableDistribution::ExcessKurtosis() const
{
return (distributionType == NORMAL) ? 0 : NAN;
}
double StableDistribution::quantileNormal(double p) const
{
return mu - 2 * gamma * RandMath::erfcinv(2 * p);
}
double StableDistribution::quantileNormal1m(double p) const
{
return mu + 2 * gamma * RandMath::erfcinv(2 * p);
}
double StableDistribution::quantileCauchy(double p) const
{
return mu - gamma / std::tan(M_PI * p);
}
double StableDistribution::quantileCauchy1m(double p) const
{
return mu + gamma / std::tan(M_PI * p);
}
double StableDistribution::quantileLevy(double p) const
{
double y = RandMath::erfcinv(p);
return mu + 0.5 * gamma / (y * y);
}
double StableDistribution::quantileLevy1m(double p) const
{
double y = RandMath::erfinv(p);
return mu + 0.5 * gamma / (y * y);
}
double StableDistribution::quantileImpl(double p) const
{
switch (distributionType) {
case NORMAL:
return quantileNormal(p);
case CAUCHY:
return quantileCauchy(p);
case LEVY:
return (beta > 0) ? quantileLevy(p) : 2 * mu - quantileLevy1m(p);
default:
return ContinuousDistribution::quantileImpl(p);
}
}
double StableDistribution::quantileImpl1m(double p) const
{
switch (distributionType) {
case NORMAL:
return quantileNormal1m(p);
case CAUCHY:
return quantileCauchy1m(p);
case LEVY:
return (beta > 0) ? quantileLevy1m(p) : 2 * mu - quantileLevy(p);
default:
return ContinuousDistribution::quantileImpl1m(p);
}
}
std::complex<double> StableDistribution::cfNormal(double t) const
{
double gammaT = gamma * t;
std::complex<double> y(-gammaT * gammaT, mu * t);
return std::exp(y);
}
std::complex<double> StableDistribution::cfCauchy(double t) const
{
std::complex<double> y(-gamma * t, mu * t);
return std::exp(y);
}
std::complex<double> StableDistribution::cfLevy(double t) const
{
std::complex<double> y(0.0, -2 * gamma * t);
y = -std::sqrt(y);
y += std::complex<double>(0.0, mu * t);
return std::exp(y);
}
std::complex<double> StableDistribution::CFImpl(double t) const
{
double x = 0;
switch (distributionType) {
case NORMAL:
return cfNormal(t);
case CAUCHY:
return cfCauchy(t);
case LEVY: {
std::complex<double> phi = cfLevy(t);
return (beta > 0) ? phi : std::conj(phi);
}
case UNITY_EXPONENT:
x = beta * M_2_PI * std::log(t);
break;
default:
x = -zeta;
}
double re = std::pow(gamma * t, alpha);
std::complex<double> psi = std::complex<double>(re, re * x - mu * t);
return std::exp(-psi);
}
String StableRand::Name() const
{
return "Stable("
+ toStringWithPrecision(GetExponent()) + ", "
+ toStringWithPrecision(GetSkewness()) + ", "
+ toStringWithPrecision(GetScale()) + ", "
+ toStringWithPrecision(GetLocation()) + ")";
}
String HoltsmarkRand::Name() const
{
return "Holtsmark("
+ toStringWithPrecision(GetScale()) + ", "
+ toStringWithPrecision(GetLocation()) + ")";
}
String LandauRand::Name() const
{
return "Landau("
+ toStringWithPrecision(GetScale()) + ", "
+ toStringWithPrecision(GetLocation()) + ")";
}
| 30.942141 | 151 | 0.607099 | aWeinzierl |
84e31e6297924e0688457a0740f037a21f3183c7 | 1,609 | cc | C++ | tensorflow/core/kernels/hexagon/hexagon_remote_fused_graph_executor_build_test.cc | abhaikollara/tensorflow | 4f96df3659696990cb34d0ad07dc67843c4225a9 | [
"Apache-2.0"
] | 850 | 2018-01-18T05:56:02.000Z | 2022-03-31T08:17:34.000Z | tensorflow/core/kernels/hexagon/hexagon_remote_fused_graph_executor_build_test.cc | shrikunjsarda/tensorflow | 7e8927e7af0c51ac20a63bd4eab6ff83df1a39ae | [
"Apache-2.0"
] | 656 | 2019-12-03T00:48:46.000Z | 2022-03-31T18:41:54.000Z | tensorflow/core/kernels/hexagon/hexagon_remote_fused_graph_executor_build_test.cc | shrikunjsarda/tensorflow | 7e8927e7af0c51ac20a63bd4eab6ff83df1a39ae | [
"Apache-2.0"
] | 506 | 2019-12-03T00:46:26.000Z | 2022-03-30T10:34:56.000Z | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/i_remote_fused_graph_executor.h"
#include "tensorflow/core/kernels/remote_fused_graph_execute_utils.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/test.h"
namespace tensorflow {
namespace hexagon_remote_fused_graph_executor_build {
Status BuildRemoteFusedGraphExecutor(
std::unique_ptr<IRemoteFusedGraphExecutor>* executor);
namespace {
TEST(HexagonBuildRemoteFusedGraphExecutorTest, BasicRun) {
std::unique_ptr<IRemoteFusedGraphExecutor> executor;
ASSERT_FALSE(static_cast<bool>(executor));
TF_ASSERT_OK(BuildRemoteFusedGraphExecutor(&executor));
ASSERT_TRUE(static_cast<bool>(executor));
ASSERT_NE(RemoteFusedGraphExecuteUtils::GetExecutorBuildFunc(
"build_hexagon_remote_fused_graph_executor"),
nullptr);
}
} // namespace
} // namespace hexagon_remote_fused_graph_executor_build
} // namespace tensorflow
| 37.418605 | 80 | 0.759478 | abhaikollara |
84e358c80f6bf140121735659d6c042ecb82cb30 | 2,325 | cpp | C++ | src/mog_train.cpp | palikar/skin_detector | 2b8e776fe140136299579fbcd2e95efe716395f7 | [
"MIT"
] | null | null | null | src/mog_train.cpp | palikar/skin_detector | 2b8e776fe140136299579fbcd2e95efe716395f7 | [
"MIT"
] | null | null | null | src/mog_train.cpp | palikar/skin_detector | 2b8e776fe140136299579fbcd2e95efe716395f7 | [
"MIT"
] | null | null | null | #include <mog.h>
void MOG::train( std::vector<cv::Mat>& training_images, std::vector<cv::Mat>& masks ){
cv::Mat pos_samples, neg_samples;
std::cout << "Organizing the data" << std::endl;
// organize all the samples
organizeSamples(training_images, masks, pos_samples, neg_samples);
std::cout << "Training the models, this may take a while" << std::endl;
// train the models
pos_model->trainEM( pos_samples );
neg_model->trainEM( neg_samples );
emToMixture();
std::cout << "Finished training the models" << std::endl;
}
void MOG::organizeSamples( std::vector<cv::Mat>& imgs,
std::vector<cv::Mat>& masks,
cv::Mat& pos_samples,
cv::Mat& neg_samples ){
std::vector<double> pos, neg;
const size_t channels = imgs[0].channels();
for ( int i = 0; i < (int)imgs.size(); i++ )
organizeSample( imgs[i], masks[i], pos, neg );
// std::vector -> cv::Mat // 3Nx1 -> Nx3
pos_samples = cv::Mat( pos, true );
pos_samples = pos_samples.reshape( 1, pos.size() / channels );
neg_samples = cv::Mat( neg, true );
neg_samples = neg_samples.reshape( 1, neg.size() / channels );
}
// organize samples in an array
void MOG::organizeSample( const cv::Mat& img,
const cv::Mat& mask,
std::vector<double>& pos,
std::vector<double>& neg ){
CV_Assert( img.cols == mask.cols &&
img.rows == mask.rows &&
mask.type() == CV_16UC1 );
const size_t channels = img.channels();
double sample[channels];
for ( int yyy = 0; yyy < img.rows; yyy++ ) {
for ( int xxx = 0; xxx < img.cols; xxx++ ) {
// 3 channel pixel to 1x3 mat
sample[0] = img.at<cv::Vec3b>( yyy, xxx ) ( 2 );
sample[1] = img.at<cv::Vec3b>( yyy, xxx ) ( 1 );
sample[2] = img.at<cv::Vec3b>( yyy, xxx ) ( 0 );
// appends 3 elements (of 3 channels)
// at the end of *pos* or *neg*
if ( mask.at<unsigned short>( yyy, xxx ) > 0 )
pos.insert( pos.end(), sample, sample + channels );
else
neg.insert( neg.end(), sample, sample + channels );
}
}
}
| 31.849315 | 86 | 0.529462 | palikar |
84e47bd1256f7360f5d878622043a3854d6971c0 | 699 | cpp | C++ | src/NoughtGraphic.cpp | That-Cool-Coder/sfml-tictactoe | af43fd32b70acd8e73b54a2feb074df93c36bc6d | [
"MIT"
] | null | null | null | src/NoughtGraphic.cpp | That-Cool-Coder/sfml-tictactoe | af43fd32b70acd8e73b54a2feb074df93c36bc6d | [
"MIT"
] | null | null | null | src/NoughtGraphic.cpp | That-Cool-Coder/sfml-tictactoe | af43fd32b70acd8e73b54a2feb074df93c36bc6d | [
"MIT"
] | null | null | null | #include "NoughtGraphic.hpp"
NoughtGraphic::NoughtGraphic() {}
NoughtGraphic::NoughtGraphic(int i_radius)
{
radius = i_radius;
}
void NoughtGraphic::draw(int xPos, int yPos, sf::RenderWindow &window,
sf::Color backgroundColor)
{
// xPos and yPos should be pos of center
m_outerShape.setFillColor(m_color);
m_outerShape.setRadius(radius);
m_outerShape.setPosition(xPos - radius, yPos - radius);
m_innerShape.setFillColor(backgroundColor);
m_innerShape.setRadius(radius * m_holeProportion);
m_innerShape.setPosition(xPos - radius * m_holeProportion,
yPos - radius * m_holeProportion);
window.draw(m_outerShape);
window.draw(m_innerShape);
} | 27.96 | 70 | 0.728183 | That-Cool-Coder |
84e52caf5bf2e0397bacf14b940faf1faa98f580 | 1,259 | hpp | C++ | include/cpp/vkt/Crop.hpp | Kniggi/volkit | ca9f6eca143bb1306d743ba64d9e55057822d2e4 | [
"MIT"
] | 11 | 2020-02-11T20:25:48.000Z | 2022-03-23T14:50:36.000Z | include/cpp/vkt/Crop.hpp | Kniggi/volkit | ca9f6eca143bb1306d743ba64d9e55057822d2e4 | [
"MIT"
] | null | null | null | include/cpp/vkt/Crop.hpp | Kniggi/volkit | ca9f6eca143bb1306d743ba64d9e55057822d2e4 | [
"MIT"
] | 4 | 2020-02-11T20:25:57.000Z | 2021-12-13T14:47:38.000Z | // This file is distributed under the MIT license.
// See the LICENSE file for details.
#pragma once
#include <cstdint>
#include "common.hpp"
#include "forward.hpp"
#include "linalg.hpp"
namespace vkt
{
VKTAPI Error CropResize(HierarchicalVolume& dst,
HierarchicalVolume& src,
int32_t firstX,
int32_t firstY,
int32_t firstZ,
int32_t lastX,
int32_t lastY,
int32_t lastZ);
VKTAPI Error CropResize(HierarchicalVolume& dst,
HierarchicalVolume& src,
Vec3i first,
Vec3i last);
VKTAPI Error Crop(HierarchicalVolume& dst,
HierarchicalVolume& src,
int32_t firstX,
int32_t firstY,
int32_t firstZ,
int32_t lastX,
int32_t lastY,
int32_t lastZ);
VKTAPI Error Crop(HierarchicalVolume& dst,
HierarchicalVolume& src,
Vec3i first,
Vec3i last);
} // vkt
| 29.97619 | 52 | 0.462272 | Kniggi |
84e8e7b53145f7af8ed027e2f6c6d359fdac4871 | 1,228 | cpp | C++ | Ass_4/C files/billu.cpp | pratik8696/Assignment | 6fa02f4f7ec135b13dbebea9920eeb2a57bd1489 | [
"MIT"
] | null | null | null | Ass_4/C files/billu.cpp | pratik8696/Assignment | 6fa02f4f7ec135b13dbebea9920eeb2a57bd1489 | [
"MIT"
] | null | null | null | Ass_4/C files/billu.cpp | pratik8696/Assignment | 6fa02f4f7ec135b13dbebea9920eeb2a57bd1489 | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
vector<int> billu; //initialization/declaration
//input
billu.push_back(4); //billu[0]
billu.push_back(7); //billu[1]
billu.push_back(18); //billu[2]
billu.push_back(45); //billu[3]
billu.push_back(10); //billu[4]
//output
for (auto element:billu)
{
cout << element << " ";
}
cout << endl;
for (int i = 0; i < billu.size(); i++)
{
cout << billu[i] << " ";
}
cout << endl;
vector<int> pandu;
int size;
cout << endl
<< "enter the size for pandu";
cin >> size;
for (int i = 0; i < size; i++)
{
int input;
cin >> input;
pandu.push_back(input);
}
cout << endl;
for (auto element : pandu)
{
cout << element << " ";
}
cout << endl;
billu.pop_back();
cout << endl;
for (auto element : billu)
{
cout << element << " ";
}
cout<<endl;
swap(billu, pandu);
for (auto element : billu)
{
cout << element << " ";
}
cout<<endl;
for (auto element : pandu)
{
cout << element << " ";
}
return 0;
}
| 19.492063 | 51 | 0.488599 | pratik8696 |
84ec95c44cc910110f3ba23ac3f3ad8e20017554 | 25,603 | cpp | C++ | src/Component/Component.cpp | TheReincarnator/glaziery | f688943163b73cea7034e929539fff8aa39d63e5 | [
"MIT"
] | null | null | null | src/Component/Component.cpp | TheReincarnator/glaziery | f688943163b73cea7034e929539fff8aa39d63e5 | [
"MIT"
] | null | null | null | src/Component/Component.cpp | TheReincarnator/glaziery | f688943163b73cea7034e929539fff8aa39d63e5 | [
"MIT"
] | null | null | null | /*
* This file is part of the Glaziery.
* Copyright Thomas Jacob.
*
* READ README.TXT BEFORE USE!!
*/
// Main header file
#include <Glaziery/src/Headers.h>
Component::Component()
{
ASSERTION_COBJECT(this);
disposed = false;
maximumSize = Vector(4096, 4096);
minimumSize = Vector(0, 0);
parent = NULL;
size = Vector(64, 32);
visible = true;
visibleDeferred = visible;
}
Component::~Component()
{
ASSERTION_COBJECT(this);
while (!effects.IsEmpty())
{
ComponentEffect * effect = effects.UnlinkFirst();
effect->onComponentDestroying();
effect->release();
}
}
void Component::addEffect(ComponentEffect * effect)
{
ASSERTION_COBJECT(this);
effects.Append(effect);
effect->addReference();
}
void Component::addContextMenuItems(Menu * menu, Vector position, bool option1, bool option2)
{
ASSERTION_COBJECT(this);
}
void Component::appendWidget(Widget * widget)
{
ASSERTION_COBJECT(this);
if (widget->component != NULL)
throw EILLEGALSTATE("The widget is already registered to another component");
widget->component = this;
widgets.Append(widget);
}
void Component::cancelEffects()
{
ASSERTION_COBJECT(this);
for (int i=0; i<effects.GetCount(); i++)
effects.Get(i)->cancel();
}
void Component::center()
{
ASSERTION_COBJECT(this);
Vector parentSize;
if (parent != NULL)
parentSize = parent->getSize();
else
{
PlatformAdapter * adapter = Desktop::getInstance()->getPlatformAdapter();
parentSize = adapter->getScreenSize();
}
moveTo((parentSize - size) / 2);
}
void Component::deleteChild(Component * child)
{
ASSERTION_COBJECT(this);
ASSERTION_COBJECT(child);
if (child->getParent() != this)
throw EILLEGALARGUMENT("The component is not a child of this component");
delete child;
}
void Component::destroy()
{
ASSERTION_COBJECT(this);
if (disposed)
return;
// Add the component to the disposables.
// It will be destroyed next frame.
disposed = true;
Desktop * desktop = Desktop::getInstance();
desktop->addDisposable(this);
// Then, notify listeners.
onDestroying();
}
void Component::executeDeferrals()
{
ASSERTION_COBJECT(this);
EventTarget::executeDeferrals();
if (visibleDeferred && !visible)
show();
else if (!visibleDeferred && visible)
hide();
}
Vector Component::getAbsolutePosition()
{
ASSERTION_COBJECT(this);
if (parent == NULL)
return position;
else
return position + parent->getChildrenOrigin();
}
Vector Component::getChildrenOrigin()
{
ASSERTION_COBJECT(this);
return getAbsolutePosition();
}
const ArrayList<ComponentEffect> & Component::getEffects()
{
ASSERTION_COBJECT(this);
return effects;
}
EventTarget * Component::getEventTargetAt(Vector position)
{
ASSERTION_COBJECT(this);
int widgetsCount = widgets.GetCount();
for (int i=0; i<widgetsCount; i++)
{
Widget * widget = widgets.Get(i);
if (widget->isHitAt(position))
return widget;
}
return this;
}
Component * Component::getFocusChild()
{
ASSERTION_COBJECT(this);
return NULL;
}
Vector Component::getMaximumSize()
{
ASSERTION_COBJECT(this);
return maximumSize;
}
Vector Component::getMinimumSize()
{
ASSERTION_COBJECT(this);
return minimumSize;
}
Vector Component::getOrigin()
{
ASSERTION_COBJECT(this);
return getAbsolutePosition();
}
Component * Component::getParent()
{
ASSERTION_COBJECT(this);
return parent;
}
Vector Component::getPosition()
{
ASSERTION_COBJECT(this);
return position;
}
class Vector Component::getSize()
{
ASSERTION_COBJECT(this);
return size;
}
const ArrayList<Widget> & Component::getWidgets()
{
ASSERTION_COBJECT(this);
return widgets;
}
bool Component::hasFocus()
{
ASSERTION_COBJECT(this);
Component * parent = getParent();
if (parent != NULL)
return parent->getFocusChild() == this && parent->hasFocus();
else
return Desktop::getInstance()->getFocusWindowOrPopup() == this;
}
void Component::hide()
{
ASSERTION_COBJECT(this);
if (!visible)
return;
// Invalidation must take place before hiding, because the invalidate checks that flag
invalidate();
visible = false;
visibleDeferred = visible;
int listenersCount = listeners.GetCount();
for (int i=0; i<listenersCount; i++)
{
Component::Listener * componentListener
= dynamic_cast<Component::Listener *>(listeners.Get(i));
if (componentListener != NULL)
componentListener->onHidden(this);
}
}
void Component::hideDeferred()
{
ASSERTION_COBJECT(this);
setVisibleDeferred(false);
}
#if defined(_DEBUG) && (defined(_AFX) || defined(_AFXDLL))
IMPLEMENT_DYNAMIC(Component, EventTarget);
#endif
void Component::invalidate()
{
ASSERTION_COBJECT(this);
invalidateArea(Vector(), size);
}
void Component::invalidateArea(Vector position, Vector size)
{
ASSERTION_COBJECT(this);
Component * parent = getParent();
if (parent != NULL && parent->isChildVisible(this))
parent->invalidateArea(getPosition() + position, size);
}
bool Component::isChildVisible(Component * child)
{
ASSERTION_COBJECT(this);
return child->isVisible();
}
bool Component::isDisposed()
{
ASSERTION_COBJECT(this);
return disposed;
}
bool Component::isVisible()
{
ASSERTION_COBJECT(this);
return visible;
}
bool Component::isVisibleIncludingAncestors()
{
ASSERTION_COBJECT(this);
Component * ancestor = this;
while (ancestor != NULL)
{
if (!ancestor->isVisible())
return false;
ancestor = ancestor->getParent();
}
return true;
}
void Component::moveComponent(Component * relatedComponent, Vector position)
{
ASSERTION_COBJECT(this);
relatedComponent->moveInternal(position, false);
}
bool Component::moveInternal(Vector position, bool notifyParent)
{
ASSERTION_COBJECT(this);
if (this->position == position)
return false;
Vector oldPosition = this->position;
this->position = position;
if (parent != NULL && notifyParent)
parent->onChildMoved(this, oldPosition);
int listenersCount = listeners.GetCount();
for (int i=0; i<listenersCount; i++)
{
Component::Listener * componentListener
= dynamic_cast<Component::Listener *>(listeners.Get(i));
if (componentListener != NULL)
componentListener->onMoved(this, oldPosition);
}
invalidate();
return true;
}
bool Component::moveRelative(Vector delta)
{
ASSERTION_COBJECT(this);
return moveTo(position + delta);
}
bool Component::moveTo(Vector position)
{
ASSERTION_COBJECT(this);
return moveInternal(position, true);
}
bool Component::onAnyKey(bool option1, bool option2)
{
ASSERTION_COBJECT(this);
bool consumed = EventTarget::onAnyKey(option1, option2);
Component * focusChild = getFocusChild();
if (focusChild != NULL)
if (focusChild->onAnyKey(option1, option2))
consumed = true;
return consumed;
}
bool Component::onBackSpace()
{
ASSERTION_COBJECT(this);
bool consumed = EventTarget::onBackSpace();
Component * focusChild = getFocusChild();
if (focusChild != NULL)
if (focusChild->onBackSpace())
consumed = true;
return consumed;
}
bool Component::onBackTab(bool secondary)
{
ASSERTION_COBJECT(this);
bool consumed = EventTarget::onBackTab(secondary);
Component * focusChild = getFocusChild();
if (focusChild != NULL)
if (focusChild->onBackTab(secondary))
consumed = true;
return consumed;
}
bool Component::onCancel()
{
ASSERTION_COBJECT(this);
bool consumed = EventTarget::onCancel();
Component * focusChild = getFocusChild();
if (focusChild != NULL)
if (focusChild->onCancel())
consumed = true;
return consumed;
}
bool Component::onCharacter(char character, bool option1, bool option2)
{
ASSERTION_COBJECT(this);
bool consumed = EventTarget::onCharacter(character, option1, option2);
Component * focusChild = getFocusChild();
if (focusChild != NULL)
if (focusChild->onCharacter(character, option1, option2))
consumed = true;
return consumed;
}
void Component::onChildMaximumSizeChanged(Component * child, Vector oldMaximumSize)
{
ASSERTION_COBJECT(this);
}
void Component::onChildMinimumSizeChanged(Component * child, Vector oldMinimumSize)
{
ASSERTION_COBJECT(this);
}
void Component::onChildMoved(Component * child, Vector oldPosition)
{
ASSERTION_COBJECT(this);
}
void Component::onChildResized(Component * child, Vector oldSize)
{
ASSERTION_COBJECT(this);
}
void Component::onContextClick(Vector position, bool option1, bool option2)
{
ASSERTION_COBJECT(this);
EventTarget::onContextClick(position, option1, option2);
Menu * menu;
if ((menu = new Menu(this)) == NULL)
throw EOUTOFMEMORY;
addContextMenuItems(menu, position, option1, option2);
if (menu->getItems().IsEmpty())
{
delete menu;
return;
}
MenuPopup * popup = new MenuPopup(menu, true);
Desktop::getInstance()->addPopup(popup);
Vector popupPosition = getAbsolutePosition() + position;
if (popupPosition.x + popup->getSize().x > Desktop::getInstance()->getSize().x)
popupPosition.x -= popup->getSize().x;
if (popupPosition.y + popup->getSize().y > Desktop::getInstance()->getSize().y)
popupPosition.y -= popup->getSize().y;
popup->moveTo(popupPosition);
}
bool Component::onCopy()
{
ASSERTION_COBJECT(this);
bool consumed = EventTarget::onCopy();
Component * focusChild = getFocusChild();
if (focusChild != NULL)
if (focusChild->onCopy())
consumed = true;
return consumed;
}
bool Component::onCut()
{
ASSERTION_COBJECT(this);
bool consumed = EventTarget::onCut();
Component * focusChild = getFocusChild();
if (focusChild != NULL)
if (focusChild->onCut())
consumed = true;
return consumed;
}
bool Component::onDelete()
{
ASSERTION_COBJECT(this);
bool consumed = EventTarget::onDelete();
Component * focusChild = getFocusChild();
if (focusChild != NULL)
if (focusChild->onDelete())
consumed = true;
return consumed;
}
void Component::onDestroying()
{
ASSERTION_COBJECT(this);
ArrayList<Component::Listener> listenersToNotify;
int listenersCount = listeners.GetCount();
for (int i=0; i<listenersCount; i++)
{
Component::Listener * componentListener
= dynamic_cast<Component::Listener *>(listeners.Get(i));
if (componentListener != NULL)
{
listenersToNotify.Append(componentListener);
componentListener->addReference();
}
}
listenersCount = listenersToNotify.GetCount();
while (!listenersToNotify.IsEmpty())
{
Component::Listener * listener = listenersToNotify.UnlinkFirst();
listener->onDestroying(this);
listener->release();
}
}
bool Component::onEdit()
{
ASSERTION_COBJECT(this);
bool consumed = EventTarget::onEdit();
Component * focusChild = getFocusChild();
if (focusChild != NULL)
if (focusChild->onEdit())
consumed = true;
return consumed;
}
bool Component::onEnter(bool option1, bool option2)
{
ASSERTION_COBJECT(this);
bool consumed = EventTarget::onEnter(option1, option2);
Component * focusChild = getFocusChild();
if (focusChild != NULL)
if (focusChild->onEnter(option1, option2))
consumed = true;
return consumed;
}
void Component::onGotFocus(bool byParent)
{
ASSERTION_COBJECT(this);
// First notify listeners of this component about focus gain
int listenersCount = listeners.GetCount();
for (int i=0; i<listenersCount; i++)
{
Component::Listener * componentListener
= dynamic_cast<Component::Listener *>(listeners.Get(i));
if (componentListener != NULL)
componentListener->onGotFocus(this, byParent);
}
// Then notify child
Component * focusChild = getFocusChild();
if (focusChild != NULL)
focusChild->onGotFocus(true);
// Finally, invalidate the component
invalidate();
}
bool Component::onHotKey(char character, bool option1, bool option2)
{
ASSERTION_COBJECT(this);
bool consumed = EventTarget::onHotKey(character, option1, option2);
Component * focusChild = getFocusChild();
if (focusChild != NULL)
if (focusChild->onHotKey(character, option1, option2))
consumed = true;
return consumed;
}
bool Component::onKeyStroke(int keyCode, bool option1, bool option2)
{
ASSERTION_COBJECT(this);
bool consumed = EventTarget::onKeyStroke(keyCode, option1, option2);
Component * focusChild = getFocusChild();
if (focusChild != NULL)
if (focusChild->onKeyStroke(keyCode, option1, option2))
consumed = true;
return consumed;
}
void Component::onLostFocus()
{
ASSERTION_COBJECT(this);
// First notify child about focus loss
Component * focusChild = getFocusChild();
if (focusChild != NULL)
focusChild->onLostFocus();
// Then notify listeners of this component
int listenersCount = listeners.GetCount();
for (int i=0; i<listenersCount; i++)
{
Component::Listener * componentListener
= dynamic_cast<Component::Listener *>(listeners.Get(i));
if (componentListener != NULL)
componentListener->onLostFocus(this);
}
// Finally, invalidate the component
invalidate();
}
void Component::onMaximumSizeChanged(Vector oldMaximumSize)
{
ASSERTION_COBJECT(this);
}
void Component::onMinimumSizeChanged(Vector oldMinimumSize)
{
ASSERTION_COBJECT(this);
}
bool Component::onMoveDown(bool option1, bool option2)
{
ASSERTION_COBJECT(this);
bool consumed = EventTarget::onMoveDown(option1, option2);
Component * focusChild = getFocusChild();
if (focusChild != NULL)
if (focusChild->onMoveDown(option1, option2))
consumed = true;
return consumed;
}
bool Component::onMoveLeft(bool option1, bool option2)
{
ASSERTION_COBJECT(this);
bool consumed = EventTarget::onMoveLeft(option1, option2);
Component * focusChild = getFocusChild();
if (focusChild != NULL)
if (focusChild->onMoveLeft(option1, option2))
consumed = true;
return consumed;
}
bool Component::onMoveRight(bool option1, bool option2)
{
ASSERTION_COBJECT(this);
bool consumed = EventTarget::onMoveRight(option1, option2);
Component * focusChild = getFocusChild();
if (focusChild != NULL)
if (focusChild->onMoveRight(option1, option2))
consumed = true;
return consumed;
}
bool Component::onMoveToEnd(bool option1, bool option2)
{
ASSERTION_COBJECT(this);
bool consumed = EventTarget::onMoveToEnd(option1, option2);
Component * focusChild = getFocusChild();
if (focusChild != NULL)
if (focusChild->onMoveToEnd(option1, option2))
consumed = true;
return consumed;
}
bool Component::onMoveToStart(bool option1, bool option2)
{
ASSERTION_COBJECT(this);
bool consumed = EventTarget::onMoveToStart(option1, option2);
Component * focusChild = getFocusChild();
if (focusChild != NULL)
if (focusChild->onMoveToStart(option1, option2))
consumed = true;
return consumed;
}
bool Component::onMoveUp(bool option1, bool option2)
{
ASSERTION_COBJECT(this);
bool consumed = EventTarget::onMoveUp(option1, option2);
Component * focusChild = getFocusChild();
if (focusChild != NULL)
if (focusChild->onMoveUp(option1, option2))
consumed = true;
return consumed;
}
bool Component::onPageDown(bool option1, bool option2)
{
ASSERTION_COBJECT(this);
bool consumed = EventTarget::onPageDown(option1, option2);
Component * focusChild = getFocusChild();
if (focusChild != NULL)
if (focusChild->onPageDown(option1, option2))
consumed = true;
return consumed;
}
bool Component::onPageUp(bool option1, bool option2)
{
ASSERTION_COBJECT(this);
bool consumed = EventTarget::onPageUp(option1, option2);
Component * focusChild = getFocusChild();
if (focusChild != NULL)
if (focusChild->onPageUp(option1, option2))
consumed = true;
return consumed;
}
bool Component::onPaste()
{
ASSERTION_COBJECT(this);
bool consumed = EventTarget::onPaste();
Component * focusChild = getFocusChild();
if (focusChild != NULL)
if (focusChild->onPaste())
consumed = true;
return consumed;
}
bool Component::onSelectAll()
{
ASSERTION_COBJECT(this);
bool consumed = EventTarget::onSelectAll();
Component * focusChild = getFocusChild();
if (focusChild != NULL)
if (focusChild->onSelectAll())
consumed = true;
return consumed;
}
bool Component::onTab(bool secondary)
{
ASSERTION_COBJECT(this);
bool consumed = EventTarget::onTab(secondary);
Component * focusChild = getFocusChild();
if (focusChild != NULL)
if (focusChild->onTab(secondary))
consumed = true;
return consumed;
}
void Component::prependWidget(Widget * widget)
{
ASSERTION_COBJECT(this);
if (widget->component != NULL)
throw EILLEGALARGUMENT("The widget is already registered to another component");
widget->component = this;
widgets.Prepend(widget);
}
void Component::removeEffect(ComponentEffect * effect)
{
ASSERTION_COBJECT(this);
ComponentEffect * unlinkedEffect = effects.Unlink(effect);
if (unlinkedEffect != NULL)
unlinkedEffect->release();
}
void Component::removeWidget(Widget * widget)
{
ASSERTION_COBJECT(this);
widgets.Delete(widget);
}
bool Component::resize(Vector size)
{
ASSERTION_COBJECT(this);
return resizeInternal(size, true);
}
bool Component::resizeToMaximum()
{
ASSERTION_COBJECT(this);
return resizeInternal(maximumSize, true);
}
bool Component::resizeToMinimum()
{
ASSERTION_COBJECT(this);
return resizeInternal(minimumSize, true);
}
void Component::resizeComponent(Component * relatedComponent, Vector size)
{
ASSERTION_COBJECT(this);
relatedComponent->resizeInternal(size, false);
}
bool Component::resizeInternal(Vector size, bool notifyParent)
{
ASSERTION_COBJECT(this);
size = Vector(size.x > maximumSize.x ? maximumSize.x : size.x,
size.y > maximumSize.y ? maximumSize.y : size.y);
size = Vector(size.x < minimumSize.x ? minimumSize.x : size.x,
size.y < minimumSize.y ? minimumSize.y : size.y);
if (this->size == size)
return false;
Vector oldSize = this->size;
this->size = size;
if (parent != NULL && notifyParent)
parent->onChildResized(this, oldSize);
int listenersCount = listeners.GetCount();
for (int i=0; i<listenersCount; i++)
{
Component::Listener * componentListener
= dynamic_cast<Component::Listener *>(listeners.Get(i));
if (componentListener != NULL)
componentListener->onResized(this, oldSize);
}
invalidate();
return true;
}
void Component::setComponentParent(Component * child)
{
ASSERTION_COBJECT(this);
if (child->getParent() != NULL)
throw EILLEGALARGUMENT("The component already has a parent, it may not be changed");
child->parent = this;
}
void Component::setComponentMaximumSize(Component * component, Vector maximumSize, bool notifyParent)
{
ASSERTION_COBJECT(this);
component->setMaximumSizeInternal(maximumSize, notifyParent);
}
void Component::setComponentMinimumSize(Component * component, Vector minimumSize, bool notifyParent)
{
ASSERTION_COBJECT(this);
component->setMinimumSizeInternal(minimumSize, notifyParent);
}
void Component::setDisposed()
{
ASSERTION_COBJECT(this);
disposed = true;
}
void Component::setMaximumSize(Vector maximumSize)
{
ASSERTION_COBJECT(this);
setMaximumSizeInternal(maximumSize, true);
}
void Component::setMaximumSizeInternal(Vector maximumSize, bool notifyParent)
{
ASSERTION_COBJECT(this);
if (maximumSize.x < 0)
maximumSize.x = 0;
if (maximumSize.y < 0)
maximumSize.y = 0;
if (this->maximumSize == maximumSize)
return;
Vector oldMaximumSize = this->maximumSize;
this->maximumSize = maximumSize;
onMaximumSizeChanged(oldMaximumSize);
if (notifyParent && parent != NULL)
parent->onChildMaximumSizeChanged(this, oldMaximumSize);
if (!(minimumSize <= maximumSize))
setMinimumSize(Vector(minimumSize.x > maximumSize.x ? maximumSize.x : minimumSize.x,
minimumSize.y > maximumSize.y ? maximumSize.y : minimumSize.y));
if (!(size <= maximumSize))
resize(Vector(size.x > maximumSize.x ? maximumSize.x : size.x,
size.y > maximumSize.y ? maximumSize.y : size.y));
}
void Component::setMinimumSize(Vector minimumSize)
{
ASSERTION_COBJECT(this);
setMinimumSizeInternal(minimumSize, true);
}
void Component::setMinimumSizeInternal(Vector minimumSize, bool notifyParent)
{
ASSERTION_COBJECT(this);
if (minimumSize.x < 0)
minimumSize.x = 0;
if (minimumSize.y < 0)
minimumSize.y = 0;
if (this->minimumSize == minimumSize)
return;
Vector oldMinimumSize = this->minimumSize;
this->minimumSize = minimumSize;
onMinimumSizeChanged(oldMinimumSize);
if (notifyParent && parent != NULL)
parent->onChildMinimumSizeChanged(this, oldMinimumSize);
if (!(maximumSize >= minimumSize))
setMaximumSize(Vector(maximumSize.x < minimumSize.x ? minimumSize.x : maximumSize.x,
maximumSize.y < minimumSize.y ? minimumSize.y : maximumSize.y));
if (!(size >= minimumSize))
resize(Vector(size.x < minimumSize.x ? minimumSize.x : size.x,
size.y < minimumSize.y ? minimumSize.y : size.y));
}
void Component::setSkinData(SkinData * skinData)
{
ASSERTION_COBJECT(this);
GlazieryObject::setSkinData(skinData);
skinData->component = this;
}
void Component::setVisible(bool visible)
{
ASSERTION_COBJECT(this);
if (visible)
show();
else
hide();
}
void Component::setVisibleDeferred(bool visible)
{
ASSERTION_COBJECT(this);
if (visible)
showDeferred();
else
hideDeferred();
}
void Component::show()
{
ASSERTION_COBJECT(this);
if (visible)
return;
visible = true;
visibleDeferred = visible;
int listenersCount = listeners.GetCount();
for (int i=0; i<listenersCount; i++)
{
Component::Listener * componentListener
= dynamic_cast<Component::Listener *>(listeners.Get(i));
if (componentListener != NULL)
componentListener->onShown(this);
}
invalidate();
}
BalloonPopup * Component::showBalloonPopup(const String & text)
{
ASSERTION_COBJECT(this);
BalloonPopup * popup;
if ((popup = new BalloonPopup) == NULL)
throw EOUTOFMEMORY;
Desktop::getInstance()->addPopup(popup);
popup->setMessage(text);
popup->pointTo(this);
return popup;
}
void Component::showDeferred()
{
ASSERTION_COBJECT(this);
Mutex * mutex = Desktop::getInstance()->getDeferralMutex();
if (!mutex->lock())
return;
visibleDeferred = visible;
Desktop::getInstance()->deferObject(this);
mutex->release();
}
String Component::toString()
{
ASSERTION_COBJECT(this);
String string;
string.Format("Component(position:%s,size:%s)",
(const char *) position.toString(), (const char *) size.toString());
return string;
}
void Component::tutorialClick(PointerEffect::ButtonEffect buttonEffect, bool option1, bool option2, long time)
{
ASSERTION_COBJECT(this);
Desktop * desktop = Desktop::getInstance();
if (!Desktop::getInstance()->isTutorialMode())
throw EILLEGALSTATE("Use the tutorial methods in Tutorial::run() implementations only");
if (time < 0)
time = 1000;
if (buttonEffect == PointerEffect::BUTTONEFFECT_DRAGDROP)
throw EILLEGALARGUMENT("tutorialClick cannot have a drag-drop button effect. Use tutorialDragDropTo instead.");
Vector positionEnd = getAbsolutePosition() + getSize() / 2;
if (Desktop::getInstance()->getPointerPosition() == positionEnd)
time = 0;
PointerEffect * pointerEffect;
if ((pointerEffect = new PointerEffect(time)) == NULL) \
throw EOUTOFMEMORY;
pointerEffect->setPositionEnd(positionEnd);
pointerEffect->setTimeCurveToAcceleration();
pointerEffect->setButtonEffect(buttonEffect);
pointerEffect->setButtonOption1(option1);
pointerEffect->setButtonOption2(option2);
Desktop::getInstance()->addEffect(pointerEffect);
pointerEffect->waitFor();
}
void Component::tutorialDragDropTo(Vector position, bool option1, bool option2, long time)
{
ASSERTION_COBJECT(this);
if (!Desktop::getInstance()->isTutorialMode())
throw EILLEGALSTATE("Use the tutorial methods in Tutorial::run() implementations only");
if (time < 0)
time = 1000;
EffectSequence * sequence;
if ((sequence = new EffectSequence) == NULL)
throw EOUTOFMEMORY;
Vector dragPosition = getAbsolutePosition() + getSize() / 2;
if (Desktop::getInstance()->getPointerPosition() == dragPosition)
time = 0;
PointerEffect * effect;
if ((effect = new PointerEffect(time)) == NULL) \
throw EOUTOFMEMORY;
effect->setPositionEnd(dragPosition);
effect->setTimeCurveToAcceleration();
sequence->appendEffect(effect);
if ((effect = new PointerEffect(time)) == NULL) \
throw EOUTOFMEMORY;
effect->setPositionEnd(position);
effect->setTimeCurveToAcceleration();
effect->setButtonEffect(PointerEffect::BUTTONEFFECT_DRAGDROP);
effect->setButtonOption1(option1);
effect->setButtonOption2(option2);
sequence->appendEffect(effect);
Desktop::getInstance()->addEffect(sequence);
effect->waitFor();
}
void Component::tutorialMoveTo(long time)
{
ASSERTION_COBJECT(this);
if (!Desktop::getInstance()->isTutorialMode())
throw EILLEGALSTATE("Use the tutorial methods in Tutorial::run() implementations only");
Vector positionEnd = getAbsolutePosition() + getSize() / 2;
if (Desktop::getInstance()->getPointerPosition() == positionEnd)
return;
if (time < 0)
time = 1000;
PointerEffect * effect;
if ((effect = new PointerEffect(time)) == NULL) \
throw EOUTOFMEMORY;
effect->setPositionEnd(positionEnd);
effect->setTimeCurveToAcceleration();
Desktop::getInstance()->addEffect(effect);
effect->waitFor();
}
void Component::unsetComponentParent(Component * child)
{
ASSERTION_COBJECT(this);
ASSERTION_COBJECT(child);
child->parent = NULL;
}
void Component::Listener::onDestroying(Component * component)
{
ASSERTION_COBJECT(this);
}
void Component::Listener::onGotFocus(Component * component, bool byParent)
{
ASSERTION_COBJECT(this);
}
void Component::Listener::onHidden(Component * component)
{
ASSERTION_COBJECT(this);
}
void Component::Listener::onLostFocus(Component * component)
{
ASSERTION_COBJECT(this);
}
void Component::Listener::onMoved(Component * component, Vector oldPosition)
{
ASSERTION_COBJECT(this);
}
void Component::Listener::onResized(Component * component, Vector oldSize)
{
ASSERTION_COBJECT(this);
}
void Component::Listener::onShown(Component * component)
{
ASSERTION_COBJECT(this);
}
| 21.389307 | 113 | 0.732883 | TheReincarnator |
84eecad9d8db36e8099376e696f0e1c538abaecf | 1,724 | cpp | C++ | lib/AnnotateInstructions.cpp | compor/loop-meta-annotator | 2ecc6633960c1372e1f88c493fe7831f0df0ee7d | [
"MIT"
] | null | null | null | lib/AnnotateInstructions.cpp | compor/loop-meta-annotator | 2ecc6633960c1372e1f88c493fe7831f0df0ee7d | [
"MIT"
] | null | null | null | lib/AnnotateInstructions.cpp | compor/loop-meta-annotator | 2ecc6633960c1372e1f88c493fe7831f0df0ee7d | [
"MIT"
] | 1 | 2020-06-16T10:21:20.000Z | 2020-06-16T10:21:20.000Z | //
//
//
#include "AnnotateValues/AnnotateInstructions.hpp"
#include "llvm/IR/Module.h"
// using llvm::Module
#include "llvm/IR/Type.h"
// using llvm::IntType
#include "llvm/IR/Constants.h"
// using llvm::ConstantInt
#include "llvm/IR/Metadata.h"
// using llvm::Metadata
// using llvm::MDNode
// using llvm::ConstantAsMetadata
#include "llvm/IR/MDBuilder.h"
// using llvm::MDBuilder
#include "llvm/ADT/SmallVector.h"
// using llvm::SmallVector
#include "llvm/Support/Casting.h"
// using llvm::dyn_cast
#include <cassert>
// using assert
namespace icsa {
namespace AnnotateInstructions {
bool Reader::has(const llvm::Instruction &CurInstruction) const {
return nullptr != CurInstruction.getMetadata(key());
}
InstructionIDTy Reader::get(const llvm::Instruction &CurInstruction) const {
const auto *IDNode = CurInstruction.getMetadata(key());
assert(nullptr != IDNode &&
"Instruction does not have the requested metadata!");
const auto *constantMD =
llvm::dyn_cast<llvm::ConstantAsMetadata>(IDNode->getOperand(1).get());
const auto &IDConstant = constantMD->getValue()->getUniqueInteger();
return IDConstant.getLimitedValue();
}
//
InstructionIDTy Writer::put(llvm::Instruction &CurInstruction) {
auto &curContext = CurInstruction.getParent()->getParent()->getContext();
llvm::MDBuilder builder{curContext};
auto *intType = llvm::Type::getInt32Ty(curContext);
auto curID = current();
llvm::SmallVector<llvm::Metadata *, 1> IDValues{
builder.createConstant(llvm::ConstantInt::get(intType, curID))};
next();
CurInstruction.setMetadata(key(), llvm::MDNode::get(curContext, IDValues));
return curID;
}
} // namespace AnnotateInstructions
} // namespace icsa
| 23.616438 | 77 | 0.723898 | compor |
84efda42e10bc5a89ecf957576cddb0c81dd3c5d | 519 | hpp | C++ | Game.hpp | CLA-TC1030/s1t1.sye | c210a4956fe0fbb978b1d541d2fdf6079f804585 | [
"MIT"
] | null | null | null | Game.hpp | CLA-TC1030/s1t1.sye | c210a4956fe0fbb978b1d541d2fdf6079f804585 | [
"MIT"
] | null | null | null | Game.hpp | CLA-TC1030/s1t1.sye | c210a4956fe0fbb978b1d541d2fdf6079f804585 | [
"MIT"
] | null | null | null | #pragma once
#include "Ctesconf.hpp"
#include "Tablero.hpp"
#include "Jugador.hpp"
#include "CDado.hpp"
#include <fstream>
#include <ostream>
class Game {
private:
Tablero t;
Jugador j[MAX_JUGADORES];
CDado d;
bool swio;
// Archivos de entrada/salida para el caso de configuracion de IO por archivos ---------
std::ifstream fi{"input"};
std::ofstream fo{"output"};
public:
static int turno;
Game();
Game(std::string, bool, bool);
void start();
void outMsg(std::string);
}; | 19.961538 | 88 | 0.649326 | CLA-TC1030 |
84f4004ce83c63e784a536adba6b4f4724bafc27 | 2,696 | cpp | C++ | src/fuselage/CCPACSFuselages.cpp | Mk-arc/tigl | 45ace0b17008e2beab3286babe310a817fcd6578 | [
"Apache-2.0"
] | 171 | 2015-04-13T11:24:34.000Z | 2022-03-26T00:56:38.000Z | src/fuselage/CCPACSFuselages.cpp | Mk-arc/tigl | 45ace0b17008e2beab3286babe310a817fcd6578 | [
"Apache-2.0"
] | 620 | 2015-01-20T08:34:36.000Z | 2022-03-30T11:05:33.000Z | src/fuselage/CCPACSFuselages.cpp | Mk-arc/tigl | 45ace0b17008e2beab3286babe310a817fcd6578 | [
"Apache-2.0"
] | 56 | 2015-02-09T13:33:56.000Z | 2022-03-19T04:52:51.000Z | /*
* Copyright (C) 2007-2013 German Aerospace Center (DLR/SC)
*
* Created: 2010-08-13 Markus Litz <Markus.Litz@dlr.de>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file
* @brief Implementation of CPACS fuselages handling routines.
*/
#include "CCPACSFuselages.h"
#include "CCPACSFuselage.h"
#include "CCPACSAircraftModel.h"
#include "CCPACSFuselageProfiles.h"
#include "CCPACSConfiguration.h"
#include "CTiglError.h"
namespace tigl
{
CCPACSFuselages::CCPACSFuselages(CCPACSAircraftModel* parent, CTiglUIDManager* uidMgr)
: generated::CPACSFuselages(parent, uidMgr) {}
CCPACSFuselages::CCPACSFuselages(CCPACSRotorcraftModel* parent, CTiglUIDManager* uidMgr)
: generated::CPACSFuselages(parent, uidMgr) {}
// Read CPACS fuselages element
void CCPACSFuselages::ReadCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath)
{
generated::CPACSFuselages::ReadCPACS(tixiHandle, xpath);
}
// Write CPACS fuselage elements
void CCPACSFuselages::WriteCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) const
{
generated::CPACSFuselages::WriteCPACS(tixiHandle, xpath);
}
// Returns the total count of fuselages in a configuration
int CCPACSFuselages::GetFuselageCount() const
{
return static_cast<int>(m_fuselages.size());
}
// Returns the fuselage for a given index.
CCPACSFuselage& CCPACSFuselages::GetFuselage(int index) const
{
index--;
if (index < 0 || index >= GetFuselageCount()) {
throw CTiglError("Invalid index in CCPACSFuselages::GetFuselage", TIGL_INDEX_ERROR);
}
return *m_fuselages[index];
}
// Returns the fuselage for a given UID.
CCPACSFuselage& CCPACSFuselages::GetFuselage(const std::string& UID) const
{
return *m_fuselages[GetFuselageIndex(UID) - 1];
}
// Returns the fuselage index for a given UID.
int CCPACSFuselages::GetFuselageIndex(const std::string& UID) const
{
for (int i=0; i < GetFuselageCount(); i++) {
const std::string tmpUID(m_fuselages[i]->GetUID());
if (tmpUID == UID) {
return i+1;
}
}
// UID not there
throw CTiglError("Invalid UID in CCPACSFuselages::GetFuselageIndex", TIGL_UID_ERROR);
}
} // end namespace tigl
| 31.348837 | 102 | 0.736647 | Mk-arc |
84f8acb67141d9256497274918609d9aa1529ad4 | 7,462 | cpp | C++ | 2019/20.cpp | wgevaert/AOC | aaa9c06f9817e338cca01bbf37b6ba81256dd5ba | [
"WTFPL"
] | 2 | 2020-08-06T22:14:51.000Z | 2020-08-10T19:42:36.000Z | 2019/20.cpp | wgevaert/AOC | aaa9c06f9817e338cca01bbf37b6ba81256dd5ba | [
"WTFPL"
] | null | null | null | 2019/20.cpp | wgevaert/AOC | aaa9c06f9817e338cca01bbf37b6ba81256dd5ba | [
"WTFPL"
] | null | null | null | #include <iostream>
#include <vector>
#define NORTH 1
#define SOUTH 2
#define WEST 3
#define EAST 4
void get_direction(int command, int& dx, int & dy) {
switch(command) {
case NORTH: dx=0;dy=1;break;
case SOUTH: dx=0;dy=-1;break;
case WEST: dx=-1;dy=0;break;
case EAST: dx=1;dy=0;break;
default:std::cout<<command<<" IS NOT A VALID DIRECTION"<<std::endl;
}
}
struct flower {
bool flowing = true,waiting =false;
int px,py,size;
flower(int pos_x,int pos_y,int sze) {px=pos_x;py=pos_y;flowing=true;size = sze;}
flower(){};
};
struct tile {
char type,p1,p2;
int dist=-1,x,y;
};
#define WALL '#'
#define PATH '.'
#define PORTAL 'p'
#define USED 'O'
#define NOTHING ' '
int main() {
int x=0,x_max=0,y_max=0;
int x_start,y_start,x_end,y_end;
char a=std::cin.get();
tile robot_pos[300][300];
std::vector<int> lines_with_letters ={0};
std::vector<std::pair<int,int>> portals={};
while (!std::cin.eof()) {
if (a!='\n') {
if ('A'<=a&&a<='Z') {
robot_pos[x][y_max].type = a;
if (lines_with_letters.back() != y_max)lines_with_letters.push_back(y_max);
} else if (a=='.') {
robot_pos[x][y_max].type = a;
} else if (a=='#') {
robot_pos[x][y_max].type = a;
} else if (a!=' ') {
std::cout<<"UNEXPECTED CHAR: "<<a<<" (VALUE "<<static_cast<int>(a)<<")\n"<<std::flush;
} else robot_pos[x][y_max].type = a;
x++;
} else {
if (x>x_max)x_max = x;
y_max++;
x=0;
}
a=std::cin.get();
}
std::cout<<--x_max<<' '<<--y_max<<std::endl;
for (int j=0;j<=y_max;j++) {
for (int i=0;i<=x_max;i++) {
std::cout<<robot_pos[i][j].type<<' ';
}std::cout<<'\t'<<j<<"\n";
}std::cout<<std::flush;
for (int line : lines_with_letters) {
for (int i=0;i<=x_max;i++) {
if (robot_pos[i][line].type <= 'Z' && 'A' <= robot_pos[i][line].type) {
if (line < y_max-3 && robot_pos[i][line+1].type <='Z' && robot_pos[i][line+1].type >='A' && robot_pos[i][line+2].type == PATH) {
robot_pos[i][line+2].p1 = robot_pos[i][line].type;
robot_pos[i][line+2].p2 = robot_pos[i][line+1].type;
portals.push_back({i,line+2});
}
else if (x < x_max-2 && robot_pos[i+1][line].type <='Z' && robot_pos[i+1][line].type >='A' && robot_pos[i-1][line].type == PATH) {
robot_pos[i-1][line].p1 = robot_pos[i][line].type;
robot_pos[i-1][line].p2 = robot_pos[i+1][line].type;
portals.push_back({i-1,line});
}
else if (x < x_max-3 && robot_pos[i+1][line].type <='Z' && robot_pos[i+1][line].type >='A' && robot_pos[i+2][line].type == PATH) {
robot_pos[i+2][line].p1 = robot_pos[i][line].type;
robot_pos[i+2][line].p2 = robot_pos[i+1][line].type;
portals.push_back({i+2,line});
}
else if (line < y_max && robot_pos[i][line+1].type <='Z' && robot_pos[i][line+1].type >='A' && robot_pos[i][line-1].type == PATH) {
robot_pos[i][line-1].p1 = robot_pos[i][line].type;
robot_pos[i][line-1].p2 = robot_pos[i][line+1].type;
portals.push_back({i,line-1});
}
robot_pos[i][line].type=NOTHING;
}
}
}
lines_with_letters.clear();
int st,ed;
for (int i=0;i<portals.size();i++){
if (robot_pos[portals[i].first][portals[i].second].p1 == 'A' && robot_pos[portals[i].first][portals[i].second].p2 == 'A'){
x_start = portals[i].first;
y_start = portals[i].second;
st = i;
} else if(robot_pos[portals[i].first][portals[i].second].p1 == 'Z' && robot_pos[portals[i].first][portals[i].second].p2 == 'Z') {
x_end = portals[i].first;
y_end = portals[i].second;
ed = i;
} else for(int j=i+1;j<portals.size();j++)
if(robot_pos[portals[i].first][portals[i].second].p1 == robot_pos[portals[j].first][portals[j].second].p1 && robot_pos[portals[i].first][portals[i].second].p2 == robot_pos[portals[j].first][portals[j].second].p2) {
std::cout<< "Connecting "<<robot_pos[portals[i].first][portals[i].second].p1<<robot_pos[portals[i].first][portals[i].second].p2<<" on "<<portals[i].first<<','<<portals[i].second<<" to "<<portals[j].first<<','<<portals[j].second<<std::endl;
robot_pos[portals[i].first][portals[i].second].x = portals[j].first;
robot_pos[portals[i].first][portals[i].second].y = portals[j].second;
robot_pos[portals[j].first][portals[j].second].x = portals[i].first;
robot_pos[portals[j].first][portals[j].second].y = portals[i].second;
robot_pos[portals[i].first][portals[i].second].type = PORTAL;
robot_pos[portals[j].first][portals[j].second].type = PORTAL;
}
}
for (int i=0;i<portals.size();i++) {
if (i!=st && i!= ed && robot_pos[portals[i].first][portals[i].second].type != PORTAL) {
std::cout<<"ERROR: "<<robot_pos[portals[i].first][portals[i].second].p1<<robot_pos[portals[i].first][portals[i].second].p2<<" ON "<< portals[i].first<<','<<portals[i].second<<" IS NOT CONNECTED"<<std::endl;
}
}
std::cout<<"SEARCHING ROUTE FROM "<<x_start<<','<<y_start<<" TO "<<x_end<<','<<y_end<<std::endl;
for (int j=0;j<y_max;j++) {
for (int i=0;i<x_max;i++) {
std::cout<<robot_pos[i][j].type<<' ';
}std::cout<<"\n";
}std::cout<<std::flush;
flower myflowers[2048];
bool flowed;
int flower_cnt=1,px,py,dx,dy;
myflowers[0]=flower(x_start,y_start,0);
unsigned cnt=0;
while (robot_pos[x_end][y_end].type != USED) {
int dummy=flower_cnt;
for (int flwr=0;flwr<dummy;flwr++) {
if (!myflowers[flwr].flowing){
continue;
}
if (myflowers[flwr].waiting) {
myflowers[flwr].waiting = false;
myflowers[flwr].size++;
}
px=myflowers[flwr].px;
py=myflowers[flwr].py;
flowed = false;
for (int i=1;i<=4;i++) {
get_direction(i,dx,dy);
if (robot_pos[px+dx][py+dy].type==PATH || robot_pos[px+dx][py+dy].type==PORTAL) {
int new_x=px+dx,new_y=py+dy;
bool should_wait = false;
if (robot_pos[new_x][new_y].type==PORTAL) {
new_x = robot_pos[px+dx][py+dy].x;
new_y = robot_pos[px+dx][py+dy].y;
should_wait=true;
}
if (!flowed) {
myflowers[flwr].px = new_x;
myflowers[flwr].py = new_y;
myflowers[flwr].size++;
myflowers[flwr].waiting = should_wait;
} else {
std::cout<<"SIZE: "<<myflowers[flwr].size;
myflowers[flower_cnt]=flower(new_x,new_y,myflowers[flwr].size);
std::cout<<','<<myflowers[flower_cnt].size<<std::endl;
myflowers[flower_cnt].waiting = should_wait;
flower_cnt++;
}
robot_pos[px+dx][py+dy].type = robot_pos[new_x][new_y].type = USED;
robot_pos[px+dx][py+dy].dist = myflowers[flwr].size;
flowed = true;
}
}
if (!flowed) {
myflowers[flwr].flowing = false;
}
}
std::cout<<"\n\nAFTER "<<cnt+1<<" MINUTES:"<<std::endl;
for(int j=0;j<=y_max;j++){
for(int i=0;i<=x_max;i++){
if (i==x_end && j==y_end)
std::cout<<'X';
else
std::cout<<robot_pos[i][j].type;
}std::cout<<std::endl;
}
++cnt;
}
std::cout<<robot_pos[x_end][y_end].dist<<std::endl;
return 0;
}
| 38.266667 | 243 | 0.552935 | wgevaert |
84fa61c5233c5531a96f34bc8ca5316b913690c2 | 13,923 | cpp | C++ | liblwScript/Ast.cpp | lwScript/lwScript | 86f3e991bda2725abe90e13468f58185d8b77483 | [
"Apache-2.0"
] | 1 | 2021-11-22T05:28:13.000Z | 2021-11-22T05:28:13.000Z | liblwScript/Ast.cpp | lwScript/lwScript | 86f3e991bda2725abe90e13468f58185d8b77483 | [
"Apache-2.0"
] | null | null | null | liblwScript/Ast.cpp | lwScript/lwScript | 86f3e991bda2725abe90e13468f58185d8b77483 | [
"Apache-2.0"
] | null | null | null | #include "Ast.h"
namespace lws
{
//----------------------Expressions-----------------------------
IntNumExpr::IntNumExpr()
: value(0)
{
}
IntNumExpr::IntNumExpr(int64_t value)
: value(value)
{
}
IntNumExpr::~IntNumExpr()
{
}
std::wstring IntNumExpr::Stringify()
{
return std::to_wstring(value);
}
AstType IntNumExpr::Type()
{
return AST_INT;
}
RealNumExpr::RealNumExpr()
: value(0.0)
{
}
RealNumExpr::RealNumExpr(double value)
: value(value)
{
}
RealNumExpr::~RealNumExpr()
{
}
std::wstring RealNumExpr::Stringify()
{
return std::to_wstring(value);
}
AstType RealNumExpr::Type()
{
return AST_REAL;
}
StrExpr::StrExpr()
{
}
StrExpr::StrExpr(std::wstring_view str)
: value(str)
{
}
StrExpr::~StrExpr()
{
}
std::wstring StrExpr::Stringify()
{
return L"\"" + value + L"\"";
}
AstType StrExpr::Type()
{
return AST_STR;
}
NullExpr::NullExpr()
{
}
NullExpr::~NullExpr()
{
}
std::wstring NullExpr::Stringify()
{
return L"null";
}
AstType NullExpr::Type()
{
return AST_NULL;
}
BoolExpr::BoolExpr()
: value(false)
{
}
BoolExpr::BoolExpr(bool value)
: value(value)
{
}
BoolExpr::~BoolExpr()
{
}
std::wstring BoolExpr::Stringify()
{
return value ? L"true" : L"false";
}
AstType BoolExpr::Type()
{
return AST_BOOL;
}
IdentifierExpr::IdentifierExpr()
{
}
IdentifierExpr::IdentifierExpr(std::wstring_view literal)
: literal(literal)
{
}
IdentifierExpr::~IdentifierExpr()
{
}
std::wstring IdentifierExpr::Stringify()
{
return literal;
}
AstType IdentifierExpr::Type()
{
return AST_IDENTIFIER;
}
ArrayExpr::ArrayExpr()
{
}
ArrayExpr::ArrayExpr(std::vector<Expr *> elements) : elements(elements)
{
}
ArrayExpr::~ArrayExpr()
{
std::vector<Expr *>().swap(elements);
}
std::wstring ArrayExpr::Stringify()
{
std::wstring result = L"[";
if (!elements.empty())
{
for (auto e : elements)
result += e->Stringify() + L",";
result = result.substr(0, result.size() - 1);
}
result += L"]";
return result;
}
AstType ArrayExpr::Type()
{
return AST_ARRAY;
}
TableExpr::TableExpr()
{
}
TableExpr::TableExpr(std::unordered_map<Expr *, Expr *> elements)
: elements(elements)
{
}
TableExpr::~TableExpr()
{
std::unordered_map<Expr *, Expr *>().swap(elements);
}
std::wstring TableExpr::Stringify()
{
std::wstring result = L"{";
if (!elements.empty())
{
for (auto [key, value] : elements)
result += key->Stringify() + L":" + value->Stringify();
result = result.substr(0, result.size() - 1);
}
result += L"}";
return result;
}
AstType TableExpr::Type()
{
return AST_TABLE;
}
GroupExpr::GroupExpr()
: expr(nullptr)
{
}
GroupExpr::GroupExpr(Expr *expr)
: expr(expr)
{
}
GroupExpr::~GroupExpr()
{
}
std::wstring GroupExpr::Stringify()
{
return L"(" + expr->Stringify() + L")";
}
AstType GroupExpr::Type()
{
return AST_GROUP;
}
PrefixExpr::PrefixExpr()
: right(nullptr)
{
}
PrefixExpr::PrefixExpr(std::wstring_view op, Expr *right)
: op(op), right(right)
{
}
PrefixExpr::~PrefixExpr()
{
delete right;
right = nullptr;
}
std::wstring PrefixExpr::Stringify()
{
return op + right->Stringify();
}
AstType PrefixExpr::Type()
{
return AST_PREFIX;
}
InfixExpr::InfixExpr()
: left(nullptr), right(nullptr)
{
}
InfixExpr::InfixExpr(std::wstring_view op, Expr *left, Expr *right)
: op(op), left(left), right(right)
{
}
InfixExpr::~InfixExpr()
{
delete left;
left = nullptr;
delete right;
right = nullptr;
}
std::wstring InfixExpr::Stringify()
{
return left->Stringify() + op + right->Stringify();
}
AstType InfixExpr::Type()
{
return AST_INFIX;
}
PostfixExpr::PostfixExpr()
: left(nullptr)
{
}
PostfixExpr::PostfixExpr(Expr *left, std::wstring_view op)
: left(left), op(op)
{
}
PostfixExpr::~PostfixExpr()
{
delete left;
left = nullptr;
}
std::wstring PostfixExpr::Stringify()
{
return left->Stringify() + op;
}
AstType PostfixExpr::Type()
{
return AST_POSTFIX;
}
ConditionExpr::ConditionExpr()
: condition(nullptr), trueBranch(nullptr), falseBranch(nullptr)
{
}
ConditionExpr::ConditionExpr(Expr *condition, Expr *trueBranch, Expr *falseBranch)
: condition(condition), trueBranch(trueBranch), falseBranch(falseBranch)
{
}
ConditionExpr::~ConditionExpr()
{
delete condition;
condition = nullptr;
delete trueBranch;
trueBranch = nullptr;
delete falseBranch;
trueBranch = nullptr;
}
std::wstring ConditionExpr::Stringify()
{
return condition->Stringify() + L"?" + trueBranch->Stringify() + L":" + falseBranch->Stringify();
}
AstType ConditionExpr::Type()
{
return AST_CONDITION;
}
IndexExpr::IndexExpr()
: ds(nullptr), index(nullptr)
{
}
IndexExpr::IndexExpr(Expr *ds, Expr *index)
: ds(ds), index(index)
{
}
IndexExpr::~IndexExpr()
{
delete ds;
ds = nullptr;
delete index;
index = nullptr;
}
std::wstring IndexExpr::Stringify()
{
return ds->Stringify() + L"[" + index->Stringify() + L"]";
}
AstType IndexExpr::Type()
{
return AST_INDEX;
}
RefExpr::RefExpr()
: refExpr(nullptr)
{
}
RefExpr::RefExpr(Expr *refExpr)
: refExpr(refExpr) {}
RefExpr::~RefExpr()
{
}
std::wstring RefExpr::Stringify()
{
return L"&" + refExpr->Stringify();
}
AstType RefExpr::Type()
{
return AST_REF;
}
LambdaExpr::LambdaExpr()
: body(nullptr)
{
}
LambdaExpr::LambdaExpr(std::vector<IdentifierExpr *> parameters, ScopeStmt *body)
: parameters(parameters), body(body)
{
}
LambdaExpr::~LambdaExpr()
{
std::vector<IdentifierExpr *>().swap(parameters);
delete body;
body = nullptr;
}
std::wstring LambdaExpr::Stringify()
{
std::wstring result = L"fn(";
if (!parameters.empty())
{
for (auto param : parameters)
result += param->Stringify() + L",";
result = result.substr(0, result.size() - 1);
}
result += L")";
result += body->Stringify();
return result;
}
AstType LambdaExpr::Type()
{
return AST_LAMBDA;
}
FunctionCallExpr::FunctionCallExpr()
{
}
FunctionCallExpr::FunctionCallExpr(Expr *name, std::vector<Expr *> arguments)
: name(name), arguments(arguments)
{
}
FunctionCallExpr::~FunctionCallExpr()
{
}
std::wstring FunctionCallExpr::Stringify()
{
std::wstring result = name->Stringify() + L"(";
if (!arguments.empty())
{
for (const auto &arg : arguments)
result += arg->Stringify() + L",";
result = result.substr(0, result.size() - 1);
}
result += L")";
return result;
}
AstType FunctionCallExpr::Type()
{
return AST_FUNCTION_CALL;
}
ClassCallExpr::ClassCallExpr()
: callee(nullptr), callMember(nullptr)
{
}
ClassCallExpr::ClassCallExpr(Expr *callee, Expr *callMember)
: callee(callee), callMember(callMember)
{
}
ClassCallExpr::~ClassCallExpr()
{
}
std::wstring ClassCallExpr::Stringify()
{
return callee->Stringify() + L"." + callMember->Stringify();
}
AstType ClassCallExpr::Type()
{
return AST_CLASS_CALL;
}
//----------------------Statements-----------------------------
ExprStmt::ExprStmt()
: expr(nullptr)
{
}
ExprStmt::ExprStmt(Expr *expr)
: expr(expr)
{
}
ExprStmt::~ExprStmt()
{
delete expr;
expr = nullptr;
}
std::wstring ExprStmt::Stringify()
{
return expr->Stringify() + L";";
}
AstType ExprStmt::Type()
{
return AST_EXPR;
}
LetStmt::LetStmt()
{
}
LetStmt::LetStmt(const std::unordered_map<IdentifierExpr *, VarDesc> &variables)
: variables(variables)
{
}
LetStmt::~LetStmt()
{
std::unordered_map<IdentifierExpr *, VarDesc>().swap(variables);
}
std::wstring LetStmt::Stringify()
{
std::wstring result = L"let ";
if (!variables.empty())
{
for (auto [key, value] : variables)
result += key->Stringify() + L":" + value.type + L"=" + value.value->Stringify() + L",";
result = result.substr(0, result.size() - 1);
}
return result + L";";
}
AstType LetStmt::Type()
{
return AST_LET;
}
ConstStmt::ConstStmt()
{
}
ConstStmt::ConstStmt(const std::unordered_map<IdentifierExpr *, VarDesc> &consts)
: consts(consts)
{
}
ConstStmt::~ConstStmt()
{
std::unordered_map<IdentifierExpr *, VarDesc>().swap(consts);
}
std::wstring ConstStmt::Stringify()
{
std::wstring result = L"const ";
if (!consts.empty())
{
for (auto [key, value] : consts)
result += key->Stringify() + L":" + value.type + L"=" + value.value->Stringify() + L",";
result = result.substr(0, result.size() - 1);
}
return result + L";";
}
AstType ConstStmt::Type()
{
return AST_CONST;
}
ReturnStmt::ReturnStmt()
: expr(nullptr)
{
}
ReturnStmt::ReturnStmt(Expr *expr)
: expr(expr)
{
}
ReturnStmt::~ReturnStmt()
{
delete expr;
expr = nullptr;
}
std::wstring ReturnStmt::Stringify()
{
if (expr)
return L"return " + expr->Stringify() + L";";
else
return L"return;";
}
AstType ReturnStmt::Type()
{
return AST_RETURN;
}
IfStmt::IfStmt()
: condition(nullptr), thenBranch(nullptr), elseBranch(nullptr)
{
}
IfStmt::IfStmt(Expr *condition, Stmt *thenBranch, Stmt *elseBranch)
: condition(condition),
thenBranch(thenBranch),
elseBranch(elseBranch)
{
}
IfStmt::~IfStmt()
{
delete condition;
condition = nullptr;
delete thenBranch;
thenBranch = nullptr;
delete elseBranch;
elseBranch = nullptr;
}
std::wstring IfStmt::Stringify()
{
std::wstring result;
result = L"if(" + condition->Stringify() + L")" + thenBranch->Stringify();
if (elseBranch != nullptr)
result += L"else " + elseBranch->Stringify();
return result;
}
AstType IfStmt::Type()
{
return AST_IF;
}
ScopeStmt::ScopeStmt()
{
}
ScopeStmt::ScopeStmt(std::vector<Stmt *> stmts)
: stmts(stmts) {}
ScopeStmt::~ScopeStmt()
{
std::vector<Stmt *>().swap(stmts);
}
std::wstring ScopeStmt::Stringify()
{
std::wstring result = L"{";
for (const auto &stmt : stmts)
result += stmt->Stringify();
result += L"}";
return result;
}
AstType ScopeStmt::Type()
{
return AST_SCOPE;
}
WhileStmt::WhileStmt()
: condition(nullptr), body(nullptr), increment(nullptr)
{
}
WhileStmt::WhileStmt(Expr *condition, ScopeStmt *body, ScopeStmt *increment)
: condition(condition), body(body), increment(increment)
{
}
WhileStmt::~WhileStmt()
{
delete condition;
condition = nullptr;
delete body;
body = nullptr;
delete increment;
increment = nullptr;
}
std::wstring WhileStmt::Stringify()
{
std::wstring result = L"while(" + condition->Stringify() + L"){" + body->Stringify();
if (increment)
result += increment->Stringify();
return result += L"}";
}
AstType WhileStmt::Type()
{
return AST_WHILE;
}
BreakStmt::BreakStmt()
{
}
BreakStmt::~BreakStmt()
{
}
std::wstring BreakStmt::Stringify()
{
return L"break;";
}
AstType BreakStmt::Type()
{
return AST_BREAK;
}
ContinueStmt::ContinueStmt()
{
}
ContinueStmt::~ContinueStmt()
{
}
std::wstring ContinueStmt::Stringify()
{
return L"continue;";
}
AstType ContinueStmt::Type()
{
return AST_CONTINUE;
}
EnumStmt::EnumStmt()
{
}
EnumStmt::EnumStmt(IdentifierExpr *enumName, const std::unordered_map<IdentifierExpr *, Expr *> &enumItems)
: enumName(enumName), enumItems(enumItems)
{
}
EnumStmt::~EnumStmt()
{
}
std::wstring EnumStmt::Stringify()
{
std::wstring result = L"enum " + enumName->Stringify() + L"{";
if (!enumItems.empty())
{
for (auto [key, value] : enumItems)
result += key->Stringify() + L"=" + value->Stringify() + L",";
result = result.substr(0, result.size() - 1);
}
return result + L"}";
}
AstType EnumStmt::Type()
{
return AST_ENUM;
}
FunctionStmt::FunctionStmt()
: name(nullptr), body(nullptr)
{
}
FunctionStmt::FunctionStmt(IdentifierExpr *name, std::vector<IdentifierExpr *> parameters, ScopeStmt *body)
: name(name), parameters(parameters), body(body)
{
}
FunctionStmt::~FunctionStmt()
{
std::vector<IdentifierExpr *>().swap(parameters);
delete body;
body = nullptr;
}
std::wstring FunctionStmt::Stringify()
{
std::wstring result = L"fn " + name->Stringify() + L"(";
if (!parameters.empty())
{
for (auto param : parameters)
result += param->Stringify() + L",";
result = result.substr(0, result.size() - 1);
}
result += L")";
result += body->Stringify();
return result;
}
AstType FunctionStmt::Type()
{
return AST_FUNCTION;
}
ClassStmt::ClassStmt()
{
}
ClassStmt::ClassStmt(std::wstring name,
std::vector<LetStmt *> letStmts,
std::vector<ConstStmt *> constStmts,
std::vector<FunctionStmt *> fnStmts,
std::vector<IdentifierExpr *> parentClasses)
: name(name),
letStmts(letStmts),
constStmts(constStmts),
fnStmts(fnStmts),
parentClasses(parentClasses)
{
}
ClassStmt::~ClassStmt()
{
std::vector<IdentifierExpr *>().swap(parentClasses);
std::vector<LetStmt *>().swap(letStmts);
std::vector<ConstStmt *>().swap(constStmts);
std::vector<FunctionStmt *>().swap(fnStmts);
}
std::wstring ClassStmt::Stringify()
{
std::wstring result = L"class " + name;
if (!parentClasses.empty())
{
result += L":";
for (const auto &parentClass : parentClasses)
result += parentClass->Stringify() + L",";
result = result.substr(0, result.size() - 1);
}
result += L"{";
for (auto constStmt : constStmts)
result += constStmt->Stringify();
for (auto letStmt : letStmts)
result += letStmt->Stringify();
for (auto fnStmt : fnStmts)
result += fnStmt->Stringify();
return result + L"}";
}
AstType ClassStmt::Type()
{
return AST_CLASS;
}
AstStmts::AstStmts()
{
}
AstStmts::AstStmts(std::vector<Stmt *> stmts)
: stmts(stmts) {}
AstStmts::~AstStmts()
{
std::vector<Stmt *>().swap(stmts);
}
std::wstring AstStmts::Stringify()
{
std::wstring result;
for (const auto &stmt : stmts)
result += stmt->Stringify();
return result;
}
AstType AstStmts::Type()
{
return AST_ASTSTMTS;
}
}
| 17.579545 | 108 | 0.635352 | lwScript |
84fb0470375bc6017671736d95673dd7afbf2a31 | 1,068 | cpp | C++ | POJ/POJ1723.cpp | dong628/OhMyCodes | 238e3045a98505a4880e85ad71d43d64a20f9452 | [
"MIT"
] | 2 | 2020-07-18T01:19:04.000Z | 2020-11-03T17:34:22.000Z | POJ/POJ1723.cpp | dong628/OhMyCodes | 238e3045a98505a4880e85ad71d43d64a20f9452 | [
"MIT"
] | null | null | null | POJ/POJ1723.cpp | dong628/OhMyCodes | 238e3045a98505a4880e85ad71d43d64a20f9452 | [
"MIT"
] | 1 | 2021-09-09T12:52:58.000Z | 2021-09-09T12:52:58.000Z | #include <cstdio>
#include <iostream>
#include <algorithm>
const int Max=105;
int col[3*Max], zws, n, ans;
struct Node { int x, y; } p[Max];
bool cmp0(Node x, Node y) { return x.y < y.y; }
bool cmp1(Node x, Node y) { return x.x < y.x; }
inline int abs(int x) { return x>0?x:-x; }
int main(){
freopen("data.in", "r", stdin);
scanf("%d", &n);
for(int i=0; i<n; i++){
scanf("%d %d", &p[i].x, &p[i].y);
col[p[i].x+Max]++;
// xmax = p[i].x>xmax?p[i].x:xmax;
// xmin = p[i].x<xmin?p[i].x:xmin;
}
std::sort(p, p+n, cmp0);
zws=p[n>>1].y;
for(int i=0; i<n; i++){
ans+=abs(p[i].y-zws);
}
std::sort(p, p+n, cmp1);
zws=p[n>>1].x+Max;
for(int i=0; i<n/2; i++){
if(col[zws+i]>1){
for(int j=zws+i+1; j<=zws+i+1+n; j++){
if(col[j]==0){
col[j]++;
col[zws+i]--;
ans+=j-(zws+i);
}
if(col[zws+i]==1) break;
}
}
if(col[zws-i]>1){
for(int j=zws-i-1; j>=zws-i-1-n; j--){
if(col[j]==0){
col[j]++;
col[zws-i]--;
ans+=zws-i-j;
}
if(col[zws+i]==1) break;
}
}
}
printf("%d", ans);
return 0;
}
| 18.413793 | 47 | 0.484082 | dong628 |
84fb60accb966f98e6b594f740d0e36096a0b0ba | 1,145 | cc | C++ | components/sync_driver/generic_change_processor_factory.cc | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2019-01-28T08:09:58.000Z | 2021-11-15T15:32:10.000Z | components/sync_driver/generic_change_processor_factory.cc | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | null | null | null | components/sync_driver/generic_change_processor_factory.cc | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | 6 | 2020-09-23T08:56:12.000Z | 2021-11-18T03:40:49.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/sync_driver/generic_change_processor_factory.h"
#include "base/memory/ptr_util.h"
#include "components/sync_driver/generic_change_processor.h"
#include "sync/api/syncable_service.h"
namespace sync_driver {
GenericChangeProcessorFactory::GenericChangeProcessorFactory() {}
GenericChangeProcessorFactory::~GenericChangeProcessorFactory() {}
std::unique_ptr<GenericChangeProcessor>
GenericChangeProcessorFactory::CreateGenericChangeProcessor(
syncer::ModelType type,
syncer::UserShare* user_share,
syncer::DataTypeErrorHandler* error_handler,
const base::WeakPtr<syncer::SyncableService>& local_service,
const base::WeakPtr<syncer::SyncMergeResult>& merge_result,
SyncClient* sync_client) {
DCHECK(user_share);
return base::WrapUnique(new GenericChangeProcessor(
type, error_handler, local_service, merge_result, user_share, sync_client,
local_service->GetAttachmentStoreForSync()));
}
} // namespace sync_driver
| 34.69697 | 80 | 0.793886 | Wzzzx |
ebcc816ccfca1e227e3c1745a7c02ddd4ef27ca9 | 7,718 | cpp | C++ | extra_src/json2array_jacek.cpp | anujaprojects1/shinglejs | fd2052afcd6f3b0e83df6634aa8dcf997aee4e6b | [
"ECL-2.0",
"Apache-2.0"
] | 30 | 2017-07-19T12:35:41.000Z | 2020-04-19T07:55:20.000Z | extra_src/json2array_jacek.cpp | anujaprojects1/shinglejs | fd2052afcd6f3b0e83df6634aa8dcf997aee4e6b | [
"ECL-2.0",
"Apache-2.0"
] | 3 | 2018-08-12T09:01:47.000Z | 2018-08-15T13:48:31.000Z | extra_src/json2array_jacek.cpp | anujaprojects1/shinglejs | fd2052afcd6f3b0e83df6634aa8dcf997aee4e6b | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2018-08-11T16:06:33.000Z | 2020-01-12T15:25:34.000Z | #include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "graph.h"
#include "MFRUtils.h"
#include "jsontokenizer.h"
#include <set>
#include <map>
#include <string>
/************************************************
Started 2016 Ayal Pinkus
Read in json arrays and dump as binary files for
faster processing later on.
************************************************/
struct EdgeIds
{
EdgeIds(long long nodeIdA, long long nodeIdB)
{
if (nodeIdA < nodeIdB)
{
low = nodeIdA;
high = nodeIdB;
}
else
{
low = nodeIdB;
high = nodeIdA;
}
};
EdgeIds(const EdgeIds& other)
{
low=other.low;
high=other.high;
};
long long low;
long long high;
};
bool operator< (const EdgeIds& lhs, const EdgeIds& rhs)
{
if (lhs.high < rhs.high)
{
return true;
}
else if (lhs.high > rhs.high)
{
return false;
}
else
{
if (lhs.low < rhs.low)
{
return true;
}
else
{
return false;
}
}
}
std::set<EdgeIds> edgeids;
static FILE* json_in_file = NULL;
static FILE* node_out_file = NULL;
static FILE* edge_out_file = NULL;
static void processFile(const char* fname)
{
JSONTokenizer tokenizer(fname);
//
// Read nodes
//
tokenizer.Match("{");
tokenizer.Match("nodes");
tokenizer.Match(":");
tokenizer.Match("[");
while (!strcmp(tokenizer.nextToken, "{"))
{
MFRNode node;
tokenizer.Match("{");
while (strcmp(tokenizer.nextToken, "}"))
{
if (!strcasecmp(tokenizer.nextToken, "eid"))
{
tokenizer.LookAhead();
tokenizer.Match(":");
node.SetNodeId(tokenizer.nextToken);
}
else if (!strcasecmp(tokenizer.nextToken, "name"))
{
tokenizer.LookAhead();
tokenizer.Match(":");
node.SetName(tokenizer.nextToken);
}
else if (!strcasecmp(tokenizer.nextToken, "author_name"))
{
tokenizer.LookAhead();
tokenizer.Match(":");
node.SetName(tokenizer.nextToken);
}
else if (!strcasecmp(tokenizer.nextToken, "x"))
{
tokenizer.LookAhead();
tokenizer.Match(":");
node.x = atof(tokenizer.nextToken);
}
else if (!strcasecmp(tokenizer.nextToken, "y"))
{
tokenizer.LookAhead();
tokenizer.Match(":");
node.y = atof(tokenizer.nextToken);
}
else if (!strcasecmp(tokenizer.nextToken, "community"))
{
tokenizer.LookAhead();
tokenizer.Match(":");
node.community = atol(tokenizer.nextToken);
}
else
{
tokenizer.LookAhead();
tokenizer.Match(":");
}
tokenizer.LookAhead();
if (!strcmp(tokenizer.nextToken, ","))
{
tokenizer.Match(",");
}
}
tokenizer.Match("}");
fwrite(&node,sizeof(MFRNode),1,node_out_file);
{
static int nodecount=0;
if ((nodecount & 1023) == 0)
{
fprintf(stderr,"\rNode %d",nodecount);
}
nodecount++;
}
if (!strcmp(tokenizer.nextToken, ","))
{
tokenizer.Match(",");
}
}
tokenizer.Match("]");
tokenizer.Match(",");
tokenizer.Match("edges");
tokenizer.Match(":");
tokenizer.Match("[");
while (!strcmp(tokenizer.nextToken, "["))
{
MFREdgeExt edge;
tokenizer.Match("[");
edge.SetNodeIdA(tokenizer.nextToken);
tokenizer.LookAhead();
tokenizer.Match(",");
edge.SetNodeIdB(tokenizer.nextToken);
tokenizer.LookAhead();
// Read edge strength here.
tokenizer.Match(",");
// Bug in data: some fields were left empty, so assuming edge strength 1 here.
if (!strcmp(tokenizer.nextToken, ","))
{
edge.strength = 1;
}
else
{
edge.strength = atoi(tokenizer.nextToken);
tokenizer.LookAhead();
}
/* Skip any additional fields */
while (!strcmp(tokenizer.nextToken, ","))
{
tokenizer.Match(",");
tokenizer.LookAhead();
}
tokenizer.Match("]");
if (!strcmp(tokenizer.nextToken, ","))
{
tokenizer.Match(",");
}
EdgeIds thisedge(atoll(edge.nodeidA), atoll(edge.nodeidB));
std::set<EdgeIds>::iterator eentry = edgeids.find(thisedge);
if (eentry == edgeids.end())
{
edgeids.insert(thisedge);
fwrite(&edge,sizeof(MFREdgeExt),1,edge_out_file);
{
static int edgecount=0;
if ((edgecount & 1023) == 0)
{
fprintf(stderr, "\rEdge %d",edgecount);
}
edgecount++;
}
}
}
tokenizer.Match("]");
tokenizer.Match("}");
}
static void processMetaNodeFile(MFRNodeArray& nodes, const char* fname)
{
JSONTokenizer tokenizer(fname);
tokenizer.Match("{");
tokenizer.Match("nodes");
tokenizer.Match(":");
tokenizer.Match("[");
while (!strcmp(tokenizer.nextToken, "{"))
{
char nodeid[256];
int hindex=0;
double pagerank;
int pagerank_set = 0;
int asjc=0;
tokenizer.Match("{");
while (strcmp(tokenizer.nextToken, "}"))
{
if (!strcasecmp(tokenizer.nextToken, "eid"))
{
pagerank_set = 0;
pagerank=0;
hindex=0;
asjc=10;
tokenizer.LookAhead();
tokenizer.Match(":");
strcpy(nodeid,tokenizer.nextToken);
}
else if (!strcasecmp(tokenizer.nextToken, "hindex"))
{
tokenizer.LookAhead();
tokenizer.Match(":");
hindex = atoi(tokenizer.nextToken);
}
else if (!strcasecmp(tokenizer.nextToken, "pagerank"))
{
tokenizer.LookAhead();
tokenizer.Match(":");
pagerank = atof(tokenizer.nextToken);
pagerank_set = 1;
}
else if (!strcasecmp(tokenizer.nextToken, "asjc"))
{
tokenizer.LookAhead();
tokenizer.Match(":");
char* ptr = tokenizer.nextToken;
int len = strlen(ptr);
if (len>2 && *ptr == '\"')
{
ptr[len-1] = 0;
ptr = ptr + 1;
}
asjc = atoi(ptr);
}
else
{
tokenizer.LookAhead();
tokenizer.Match(":");
}
tokenizer.LookAhead();
if (!strcmp(tokenizer.nextToken, ","))
{
tokenizer.Match(",");
}
}
tokenizer.Match("}");
MFRNode* node = nodes.LookUp(nodeid);
if (node == NULL)
{
fprintf(stderr,"WARNING: meta data for non-existing node with id %s.\n", nodeid);
}
else
{
// I don't want to have to handle -1 in shingle.js. asjc 1000 is "general"
if (asjc<0)
{
asjc = 10;
}
node->size = hindex;
node->level = hindex;
if (pagerank_set)
{
node->level = pagerank;
}
node->community = asjc;
}
if (!strcmp(tokenizer.nextToken, ","))
{
tokenizer.Match(",");
}
}
tokenizer.Match("]");
tokenizer.Match("}");
}
int main(int argc, char** argv)
{
printf("sizeof(long long)=%lud\n",sizeof(long long));
if (argc<4)
{
fprintf(stderr,"%s data_path node_out_file edge_out_file",argv[0]);
exit(-1);
}
const char* data_path = argv[1];
const char* node_out_fname = argv[2];
const char* edge_out_fname = argv[3];
node_out_file = MFRUtils::OpenFile(node_out_fname,"w");
edge_out_file = MFRUtils::OpenFile(edge_out_fname,"w");
char json_in_fname[1024];
sprintf(json_in_fname,"%snode.json",data_path);
processFile(json_in_fname);
fclose(node_out_file);
fclose(edge_out_file);
MFRNodeArray nodes(node_out_fname);
nodes.Sort();
char json_meta_in_fname[1024];
sprintf(json_meta_in_fname,"%smeta.json",data_path);
processMetaNodeFile(nodes, json_meta_in_fname);
node_out_file = MFRUtils::OpenFile(node_out_fname,"w");
fwrite(nodes.nodes,nodes.nrnodes*sizeof(MFRNode),1,node_out_file);
fclose(node_out_file);
return 0;
}
| 20.310526 | 87 | 0.575667 | anujaprojects1 |
ebcd8a501d771dbce115085187301729a59bdb60 | 659 | cpp | C++ | cf/1096/b.cpp | tusikalanse/acm-icpc | 20150f42752b85e286d812e716bb32ae1fa3db70 | [
"MIT"
] | 2 | 2021-06-09T12:27:07.000Z | 2021-06-11T12:02:03.000Z | cf/1096/b.cpp | tusikalanse/acm-icpc | 20150f42752b85e286d812e716bb32ae1fa3db70 | [
"MIT"
] | 1 | 2021-09-08T12:00:05.000Z | 2021-09-08T14:52:30.000Z | cf/1096/b.cpp | tusikalanse/acm-icpc | 20150f42752b85e286d812e716bb32ae1fa3db70 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10, mod = 998244353;
int n;
char s[N];
int cnt[26], num, l, r;
int main() {
scanf("%d%s", &n, s);
for(int i = 0; i < n; ++i) {
cnt[s[i] - 'a']++;
}
for(int i = 0; i < 26; ++i)
num += (cnt[i] != 0);
if(num == 1) {
printf("%lld\n", (1LL * n * (n + 1)) % mod);
return 0;
}
l = 0, r = n - 1;
for(; l < n; ++l)
if(s[0] != s[l])
break;
l--;
for(; r >= 0; --r)
if(s[n - 1] != s[r])
break;
r++;
if(s[0] == s[n - 1]) {
printf("%lld\n", (1LL * (l + 2) * (1 + n - r)) % mod);
return 0;
}
else {
printf("%lld\n", (2LL + l + n - r) % mod);
return 0;
}
return 0;
} | 17.810811 | 56 | 0.426404 | tusikalanse |
ebcdd79ecfcdaf4a82b7fa9d326a793522aa886d | 4,853 | cpp | C++ | tests/SurfaceMeshIOTest.cpp | choyfung/pmp-library | 4a72c918494dac92f5e77545b71c7a327dafe71e | [
"BSD-3-Clause"
] | 1 | 2020-05-21T04:15:44.000Z | 2020-05-21T04:15:44.000Z | tests/SurfaceMeshIOTest.cpp | choyfung/pmp-library | 4a72c918494dac92f5e77545b71c7a327dafe71e | [
"BSD-3-Clause"
] | null | null | null | tests/SurfaceMeshIOTest.cpp | choyfung/pmp-library | 4a72c918494dac92f5e77545b71c7a327dafe71e | [
"BSD-3-Clause"
] | 1 | 2020-05-21T04:15:52.000Z | 2020-05-21T04:15:52.000Z | //=============================================================================
// Copyright (C) 2011-2018 The pmp-library developers
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
// =============================================================================
#include "SurfaceMeshTest.h"
#include <pmp/io/SurfaceMeshIO.h>
#include <pmp/algorithms/SurfaceNormals.h>
#include <vector>
using namespace pmp;
class SurfaceMeshIOTest : public SurfaceMeshTest
{
};
TEST_F(SurfaceMeshIOTest, polyIO)
{
addTriangle();
mesh.write("test.pmp");
mesh.clear();
EXPECT_TRUE(mesh.isEmpty());
mesh.read("test.pmp");
EXPECT_EQ(mesh.nVertices(), size_t(3));
EXPECT_EQ(mesh.nFaces(), size_t(1));
// check malformed file names
EXPECT_FALSE(mesh.write("testpolyly"));
}
TEST_F(SurfaceMeshIOTest, objIO)
{
addTriangle();
SurfaceNormals::computeVertexNormals(mesh);
mesh.addHalfedgeProperty<TextureCoordinate>("h:texcoord",TextureCoordinate(0,0));
mesh.write("test.obj");
mesh.clear();
EXPECT_TRUE(mesh.isEmpty());
mesh.read("test.obj");
EXPECT_EQ(mesh.nVertices(), size_t(3));
EXPECT_EQ(mesh.nFaces(), size_t(1));
}
TEST_F(SurfaceMeshIOTest, offIO)
{
addTriangle();
SurfaceNormals::computeVertexNormals(mesh);
mesh.addVertexProperty<TextureCoordinate>("v:texcoord",TextureCoordinate(0,0));
mesh.addVertexProperty<Color>("v:color",Color(0,0,0));
IOOptions options(false, // binary
true, // normals
true, // colors
true); // texcoords
mesh.write("test.off",options);
mesh.clear();
EXPECT_TRUE(mesh.isEmpty());
mesh.read("test.off");
EXPECT_EQ(mesh.nVertices(), size_t(3));
EXPECT_EQ(mesh.nFaces(), size_t(1));
}
TEST_F(SurfaceMeshIOTest, offIOBinary)
{
addTriangle();
IOOptions options(true);
mesh.write("binary.off", options);
mesh.clear();
EXPECT_TRUE(mesh.isEmpty());
mesh.read("binary.off");
EXPECT_EQ(mesh.nVertices(), size_t(3));
EXPECT_EQ(mesh.nFaces(), size_t(1));
}
TEST_F(SurfaceMeshIOTest, stlIO)
{
mesh.read("pmp-data/stl/icosahedron_ascii.stl");
EXPECT_EQ(mesh.nVertices(), size_t(12));
EXPECT_EQ(mesh.nFaces(), size_t(20));
EXPECT_EQ(mesh.nEdges(), size_t(30));
mesh.clear();
mesh.read("pmp-data/stl/icosahedron_binary.stl");
EXPECT_EQ(mesh.nVertices(), size_t(12));
EXPECT_EQ(mesh.nFaces(), size_t(20));
EXPECT_EQ(mesh.nEdges(), size_t(30));
// try to write without normals being present
EXPECT_FALSE(mesh.write("test.stl"));
// the same with normals computed
SurfaceNormals::computeFaceNormals(mesh);
EXPECT_TRUE(mesh.write("test.stl"));
// try to write non-triangle mesh
mesh.clear();
addQuad();
EXPECT_FALSE(mesh.write("test.stl"));
}
TEST_F(SurfaceMeshIOTest, plyIO)
{
addTriangle();
mesh.write("test.ply");
mesh.clear();
EXPECT_TRUE(mesh.isEmpty());
mesh.read("test.ply");
EXPECT_EQ(mesh.nVertices(), size_t(3));
EXPECT_EQ(mesh.nFaces(), size_t(1));
}
TEST_F(SurfaceMeshIOTest, plyBinaryIO)
{
addTriangle();
IOOptions options(true);
mesh.write("binary.ply",options);
mesh.clear();
EXPECT_TRUE(mesh.isEmpty());
mesh.read("binary.ply");
EXPECT_EQ(mesh.nVertices(), size_t(3));
EXPECT_EQ(mesh.nFaces(), size_t(1));
}
| 33.239726 | 85 | 0.673604 | choyfung |
ebcfcaa6d627031057b9fc02bde0cc4c8d021fe1 | 4,338 | cc | C++ | xrtl/ui/control.cc | google/xrtl | 8cf0e7cd67371297149bda8e62d03b8c1e2e2dfe | [
"Apache-2.0"
] | 132 | 2017-03-30T03:26:57.000Z | 2021-11-18T09:18:04.000Z | xrtl/ui/control.cc | google/xrtl | 8cf0e7cd67371297149bda8e62d03b8c1e2e2dfe | [
"Apache-2.0"
] | 36 | 2017-04-02T22:57:53.000Z | 2018-06-27T04:20:30.000Z | xrtl/ui/control.cc | google/xrtl | 8cf0e7cd67371297149bda8e62d03b8c1e2e2dfe | [
"Apache-2.0"
] | 24 | 2017-04-09T12:48:13.000Z | 2021-10-20T02:20:07.000Z | // Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "xrtl/ui/control.h"
namespace xrtl {
namespace ui {
void Control::set_listener(ListenerPtr listener) {
std::lock_guard<std::mutex> lock(listener_mutex_);
listener_ = std::move(listener);
}
void Control::set_input_listener(InputListenerPtr input_listener) {
std::lock_guard<std::mutex> lock(input_listener_mutex_);
input_listener_ = std::move(input_listener);
}
void Control::PostError() {
PostEvent([](Listener* listener, ref_ptr<Control> control) {
listener->OnError(control);
});
}
void Control::PostCreating() {
PostEvent([](Listener* listener, ref_ptr<Control> control) {
listener->OnCreating(control);
});
}
void Control::PostCreated() {
PostEvent([](Listener* listener, ref_ptr<Control> control) {
listener->OnCreated(control);
});
}
void Control::PostDestroying() {
PostEvent([](Listener* listener, ref_ptr<Control> control) {
listener->OnDestroying(control);
});
}
void Control::PostDestroyed() {
PostEvent([](Listener* listener, ref_ptr<Control> control) {
listener->OnDestroyed(control);
});
}
void Control::PostSystemThemeChanged() {
PostEvent([](Listener* listener, ref_ptr<Control> control) {
listener->OnSystemThemeChanged(control);
});
}
void Control::PostSuspendChanged(bool is_suspended) {
PostEvent([this, is_suspended](Listener* listener, ref_ptr<Control> control) {
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
if (has_posted_suspended_ && is_suspended == is_suspended_shadow_) {
return; // Debounce.
}
has_posted_suspended_ = true;
is_suspended_shadow_ = is_suspended;
}
listener->OnSuspendChanged(control, is_suspended);
});
}
void Control::PostFocusChanged(bool is_focused) {
PostEvent([this, is_focused](Listener* listener, ref_ptr<Control> control) {
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
if (has_posted_focused_ && is_focused == is_focused_shadow_) {
return; // Debounce.
}
has_posted_focused_ = true;
is_focused_shadow_ = is_focused;
}
listener->OnFocusChanged(control, is_focused);
});
}
void Control::PostResized(Rect2D bounds) {
PostEvent([this, bounds](Listener* listener, ref_ptr<Control> control) {
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
if (has_posted_bounds_ && bounds == bounds_shadow_) {
return; // Debounce.
}
has_posted_bounds_ = true;
bounds_shadow_ = bounds;
}
listener->OnResized(control, bounds);
});
}
void Control::ResetEventShadows() {
std::lock_guard<std::recursive_mutex> lock(mutex_);
has_posted_suspended_ = false;
has_posted_focused_ = false;
has_posted_bounds_ = false;
}
void Control::PostEvent(
std::function<void(Listener*, ref_ptr<Control>)> callback) {
auto callback_baton = MoveToLambda(callback);
message_loop_->MarshalSync([this, callback_baton]() {
std::lock_guard<std::mutex> lock(listener_mutex_);
if (listener_) {
ref_ptr<Control> control{this};
callback_baton.value(listener_.get(), control);
}
});
}
void Control::PostInputEvent(
std::function<void(InputListener*, ref_ptr<Control>)> callback) {
switch (state()) {
case State::kCreating:
case State::kDestroying:
case State::kDestroyed:
// Ignore input events when the control is not active.
return;
default:
break;
}
auto callback_baton = MoveToLambda(callback);
message_loop_->MarshalSync([this, callback_baton]() {
std::lock_guard<std::mutex> lock(input_listener_mutex_);
if (input_listener_) {
ref_ptr<Control> control{this};
callback_baton.value(input_listener_.get(), control);
}
});
}
} // namespace ui
} // namespace xrtl
| 28.92 | 80 | 0.696404 | google |
ebd12e6bfde8423db98e1d9f919e6de5983bcb8a | 1,838 | cc | C++ | elasticsearch/src/model/RecommendTemplatesResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | elasticsearch/src/model/RecommendTemplatesResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | elasticsearch/src/model/RecommendTemplatesResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* 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/elasticsearch/model/RecommendTemplatesResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Elasticsearch;
using namespace AlibabaCloud::Elasticsearch::Model;
RecommendTemplatesResult::RecommendTemplatesResult() :
ServiceResult()
{}
RecommendTemplatesResult::RecommendTemplatesResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
RecommendTemplatesResult::~RecommendTemplatesResult()
{}
void RecommendTemplatesResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto allResultNode = value["Result"]["TemplateConfig"];
for (auto valueResultTemplateConfig : allResultNode)
{
TemplateConfig resultObject;
if(!valueResultTemplateConfig["templateName"].isNull())
resultObject.templateName = valueResultTemplateConfig["templateName"].asString();
if(!valueResultTemplateConfig["content"].isNull())
resultObject.content = valueResultTemplateConfig["content"].asString();
result_.push_back(resultObject);
}
}
std::vector<RecommendTemplatesResult::TemplateConfig> RecommendTemplatesResult::getResult()const
{
return result_;
}
| 30.633333 | 96 | 0.772035 | aliyun |
ebd3cb4b469c4b5d7736d9336083f25d368351e9 | 1,113 | cc | C++ | cc/py.cc | acorg/acmacs-py | e0bf6ff7ecfe7332980d15b50f9b6dd6f6f78de1 | [
"MIT"
] | null | null | null | cc/py.cc | acorg/acmacs-py | e0bf6ff7ecfe7332980d15b50f9b6dd6f6f78de1 | [
"MIT"
] | null | null | null | cc/py.cc | acorg/acmacs-py | e0bf6ff7ecfe7332980d15b50f9b6dd6f6f78de1 | [
"MIT"
] | null | null | null | #include "acmacs-base/log.hh"
#include "acmacs-py/py.hh"
// ======================================================================
PYBIND11_MODULE(acmacs, mdl)
{
using namespace pybind11::literals;
mdl.doc() = "Acmacs backend";
acmacs_py::chart(mdl);
acmacs_py::chart_util(mdl);
acmacs_py::avidity(mdl);
acmacs_py::antigen(mdl);
acmacs_py::titers(mdl);
acmacs_py::DEPRECATED::antigen_indexes(mdl);
acmacs_py::common(mdl);
acmacs_py::merge(mdl);
acmacs_py::mapi(mdl);
acmacs_py::draw(mdl);
acmacs_py::seqdb(mdl);
acmacs_py::tal(mdl);
// ----------------------------------------------------------------------
mdl.def(
"enable_logging", //
[](const std::string& keys) { acmacs::log::enable(std::string_view{keys}); }, //
"keys"_a);
mdl.def("logging_enabled", &acmacs::log::report_enabled);
}
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
| 30.081081 | 88 | 0.4708 | acorg |
ebd7c9f5749615605bb85f9e6c95a39787740773 | 1,258 | cpp | C++ | main.cpp | jleben/protobuf-spec-comparator | 9599c32d0b6d5a92c30fd9251c77aad9d6472a07 | [
"MIT"
] | null | null | null | main.cpp | jleben/protobuf-spec-comparator | 9599c32d0b6d5a92c30fd9251c77aad9d6472a07 | [
"MIT"
] | null | null | null | main.cpp | jleben/protobuf-spec-comparator | 9599c32d0b6d5a92c30fd9251c77aad9d6472a07 | [
"MIT"
] | 1 | 2021-09-17T07:22:26.000Z | 2021-09-17T07:22:26.000Z | #include "comparison.h"
#include <iostream>
using namespace std;
int main(int argc, char * argv[])
{
if (argc < 6)
{
cerr << "Expected arguments: root-dir1 file1 root-dir2 file2 type [--binary]" << endl;
cerr << "Use '.' for <type> to compare all messages and enums in given files." << endl;
return 1;
}
Comparison::Options options;
if (argc > 6)
{
for (int i = 6; i < argc; ++i)
{
string arg = argv[i];
if (arg == "--binary")
{
options.binary = true;
}
else
{
cerr << "Unknown option: " << arg << endl;
return 1;
}
}
}
Comparison comparison(options);
try
{
Source source1(argv[2], argv[1]);
Source source2(argv[4], argv[3]);
string message_name = argv[5];
if (message_name == ".")
comparison.compare(source1, source2);
else
comparison.compare(source1, message_name, source2, message_name);
}
catch(std::exception & e)
{
cerr << e.what() << endl;
return 1;
}
comparison.root.trim();
comparison.root.print();
return 0;
}
| 21.322034 | 95 | 0.486486 | jleben |
ebd7d759c1ea2c2cc32f0d535d027c43f0b252ac | 630 | cc | C++ | 05_String/Json/Main.cc | pataya235/UdemyCpp_Template-main | 46583e2d252005eaba3a8a6f04b112454722e315 | [
"MIT"
] | null | null | null | 05_String/Json/Main.cc | pataya235/UdemyCpp_Template-main | 46583e2d252005eaba3a8a6f04b112454722e315 | [
"MIT"
] | null | null | null | 05_String/Json/Main.cc | pataya235/UdemyCpp_Template-main | 46583e2d252005eaba3a8a6f04b112454722e315 | [
"MIT"
] | null | null | null | #include "json.hpp"
#include <fstream>
#include <iostream>
int main()
{
std::ifstream ifs("c_cpp_properties.json"); //input filestream to read
nlohmann::json data; //json object
ifs >> data; //.json file into data object
std::cout << data["configurations"][0]["compilerPath"] << std::endl;
std::cout << data["configurations"][0]["intelliSenseMode"] << std::endl;
data["configurations"][0]["cppStandard"] = "c++11";
std::ofstream ofs("c_cpp_properties_edited.json"); //output filestream to write
ofs << std::setw(4) << data;
return 0;
}
| 31.5 | 83 | 0.592063 | pataya235 |
ebd9a3b7091aa3ace2bd61248ee9f62f11a64e17 | 511 | cpp | C++ | test/testIo/testByteArrayReader/main.cpp | wangsun1983/Obotcha | 2464e53599305703f5150df72bf73579a39d8ef4 | [
"MIT"
] | 27 | 2019-04-27T00:51:22.000Z | 2022-03-30T04:05:44.000Z | test/testIo/testByteArrayReader/main.cpp | wangsun1983/Obotcha | 2464e53599305703f5150df72bf73579a39d8ef4 | [
"MIT"
] | 9 | 2020-05-03T12:17:50.000Z | 2021-10-15T02:18:47.000Z | test/testIo/testByteArrayReader/main.cpp | wangsun1983/Obotcha | 2464e53599305703f5150df72bf73579a39d8ef4 | [
"MIT"
] | 1 | 2019-04-16T01:45:36.000Z | 2019-04-16T01:45:36.000Z | #include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include "Thread.hpp"
#include "Object.hpp"
#include "System.hpp"
#include "Barrier.hpp"
#include "ByteArrayReader.hpp"
using namespace obotcha;
extern void testReadline();
extern void basetest();
extern void testByteArrayLittleEndian();
extern void testByteArrayBigEndian();
extern void testReaderArray();
int main() {
testReaderArray();
testByteArrayLittleEndian();
testByteArrayBigEndian();
testReadline();
//basetest();
}
| 19.653846 | 40 | 0.731898 | wangsun1983 |
ebdcd9a0c15ccfd734063547817eab73805518ba | 556 | cpp | C++ | async_error_handling.cpp | pgulotta/FunctionalCpp | e8a1a1af87c17050e49e129b08b68ce22ecf39ae | [
"MIT"
] | 1 | 2020-04-28T17:40:27.000Z | 2020-04-28T17:40:27.000Z | async_error_handling.cpp | pgulotta/FunctionalCpp | e8a1a1af87c17050e49e129b08b68ce22ecf39ae | [
"MIT"
] | null | null | null | async_error_handling.cpp | pgulotta/FunctionalCpp | e8a1a1af87c17050e49e129b08b68ce22ecf39ae | [
"MIT"
] | null | null | null | #include <iostream>
#include <future>
#include <exception>
#include <stdexcept>
using namespace std;
int calculate()
{
throw runtime_error("Exception thrown from calculate().");
}
int main()
{
// Use the launch::async policy to force asynchronous execution.
auto myFuture = async(launch::async, calculate);
// Do some more work...
// Get the result.
try {
int result = myFuture.get();
cout << result << endl;
} catch (const exception& ex) {
cout << "Caught exception: " << ex.what() << endl;
}
return 0;
}
| 18.533333 | 66 | 0.629496 | pgulotta |
ebdd6396f7658fccd5956c7a1219d5aa05f22d93 | 848 | cpp | C++ | src/ecs/Complex.cpp | murataka/two | f6f9835de844a38687e11f649ff97c3fb4146bbe | [
"Zlib"
] | 578 | 2019-05-04T09:09:42.000Z | 2022-03-27T23:02:21.000Z | src/ecs/Complex.cpp | murataka/two | f6f9835de844a38687e11f649ff97c3fb4146bbe | [
"Zlib"
] | 14 | 2019-05-11T14:34:56.000Z | 2021-02-02T07:06:46.000Z | src/ecs/Complex.cpp | murataka/two | f6f9835de844a38687e11f649ff97c3fb4146bbe | [
"Zlib"
] | 42 | 2019-05-11T16:04:19.000Z | 2022-01-24T02:21:43.000Z | // Copyright (c) 2019 Hugo Amiard hugo.amiard@laposte.net
// This software is provided 'as-is' under the zlib License, see the LICENSE.txt file.
// This notice and the license may not be removed or altered from any source distribution.
#ifdef TWO_MODULES
module;
#include <infra/Cpp20.h>
module TWO(ecs);
#else
#include <type/Indexer.h>
#include <type/Proto.h>
#include <ecs/Complex.h>
#endif
namespace two
{
Complex::Complex(uint32_t id, Type& type)
: m_id(index(type, id, Ref(this, type)))
, m_type(type)
, m_prototype(proto(type))
, m_parts(m_prototype.m_parts.size())
{}
Complex::Complex(uint32_t id, Type& type, span<Ref> parts)
: Complex(id, type)
{
this->setup(parts);
}
Complex::~Complex()
{
unindex(m_type, m_id);
}
void Complex::setup(span<Ref> parts)
{
for(Ref ref : parts)
this->add_part(ref);
}
}
| 20.682927 | 91 | 0.688679 | murataka |
ebdda3f79a83aeca6739c5a05e0d93e71a216f05 | 1,035 | cpp | C++ | Dimensionality_Reduction/AE1d/src/loss.cpp | o8r/pytorch_cpp | 70ba1e64270da6d870847c074ce33afb154f1ef8 | [
"MIT"
] | 181 | 2020-03-26T12:33:25.000Z | 2022-03-28T04:04:25.000Z | Dimensionality_Reduction/AE1d/src/loss.cpp | o8r/pytorch_cpp | 70ba1e64270da6d870847c074ce33afb154f1ef8 | [
"MIT"
] | 11 | 2020-07-26T13:18:50.000Z | 2022-01-09T10:04:10.000Z | Dimensionality_Reduction/AE1d/src/loss.cpp | o8r/pytorch_cpp | 70ba1e64270da6d870847c074ce33afb154f1ef8 | [
"MIT"
] | 38 | 2020-05-04T05:06:55.000Z | 2022-03-29T19:10:51.000Z | #include <iostream>
#include <string>
// For External Library
#include <torch/torch.h>
// For Original Header
#include "loss.hpp"
#include "losses.hpp"
// -----------------------------------
// class{Loss} -> constructor
// -----------------------------------
Loss::Loss(const std::string loss){
if (loss == "l1"){
this->judge = 0;
}
else if (loss == "l2"){
this->judge = 1;
}
else{
std::cerr << "Error : The loss fuction isn't defined right." << std::endl;
std::exit(1);
}
}
// -----------------------------------
// class{Loss} -> operator
// -----------------------------------
torch::Tensor Loss::operator()(torch::Tensor &input, torch::Tensor &target){
if (this->judge == 0){
static auto criterion = torch::nn::L1Loss(torch::nn::L1LossOptions().reduction(torch::kMean));
return criterion(input, target);
}
static auto criterion = torch::nn::MSELoss(torch::nn::MSELossOptions().reduction(torch::kMean));
return criterion(input, target);
}
| 27.236842 | 102 | 0.520773 | o8r |
ebdfe31f9d93f6792305dd8137a3dd82eb496e68 | 1,721 | cpp | C++ | Vic2ToHoI4/Source/HOI4World/Ideas/Ideas.cpp | kingofmen/Vic2ToHoI4 | 04e3b872f84cf8aa56e44a63021fe66db1cfe233 | [
"MIT"
] | 1 | 2020-12-19T07:55:43.000Z | 2020-12-19T07:55:43.000Z | Vic2ToHoI4/Source/HOI4World/Ideas/Ideas.cpp | kingofmen/Vic2ToHoI4 | 04e3b872f84cf8aa56e44a63021fe66db1cfe233 | [
"MIT"
] | null | null | null | Vic2ToHoI4/Source/HOI4World/Ideas/Ideas.cpp | kingofmen/Vic2ToHoI4 | 04e3b872f84cf8aa56e44a63021fe66db1cfe233 | [
"MIT"
] | null | null | null | #include "Ideas.h"
#include "IdeaGroup.h"
#include "IdeaUpdaters.h"
#include "Log.h"
#include "ParserHelpers.h"
#include <fstream>
HoI4::Ideas::Ideas() noexcept
{
importIdeologicalIdeas();
importGeneralIdeas();
}
void HoI4::Ideas::importIdeologicalIdeas()
{
registerRegex(commonItems::catchallRegex, [this](const std::string& ideology, std::istream& theStream) {
ideologicalIdeas.insert(make_pair(ideology, IdeaGroup(ideology, theStream)));
});
parseFile("ideologicalIdeas.txt");
clearRegisteredKeywords();
}
void HoI4::Ideas::importGeneralIdeas()
{
registerRegex(commonItems::catchallRegex, [this](const std::string& ideaGroupName, std::istream& theStream) {
generalIdeas.emplace_back(IdeaGroup{ideaGroupName, theStream});
});
parseFile("converterIdeas.txt");
clearRegisteredKeywords();
}
void HoI4::Ideas::updateIdeas(const std::set<std::string>& majorIdeologies)
{
Log(LogLevel::Info) << "\tUpdating ideas";
auto foundGroup = std::find_if(generalIdeas.begin(), generalIdeas.end(), [](auto& theGroup) {
return (theGroup.getName() == "mobilization_laws");
});
updateMobilizationLaws(*foundGroup, majorIdeologies);
foundGroup = std::find_if(generalIdeas.begin(), generalIdeas.end(), [](auto& theGroup) {
return (theGroup.getName() == "economy");
});
updateEconomyIdeas(*foundGroup, majorIdeologies);
foundGroup = std::find_if(generalIdeas.begin(), generalIdeas.end(), [](auto& theGroup) {
return (theGroup.getName() == "trade_laws");
});
updateTradeLaws(*foundGroup, majorIdeologies);
foundGroup = std::find_if(generalIdeas.begin(), generalIdeas.end(), [](auto& theGroup) {
return (theGroup.getName() == "country");
});
updateGeneralIdeas(*foundGroup, majorIdeologies);
} | 27.758065 | 110 | 0.731551 | kingofmen |
ebe015235a16cf280a5637d376a4b61dd4894212 | 5,495 | cpp | C++ | src/Parser.cpp | FelixKlauke/princept | 835c18031efac598c2d77d0787a45d248a918c58 | [
"MIT"
] | null | null | null | src/Parser.cpp | FelixKlauke/princept | 835c18031efac598c2d77d0787a45d248a918c58 | [
"MIT"
] | null | null | null | src/Parser.cpp | FelixKlauke/princept | 835c18031efac598c2d77d0787a45d248a918c58 | [
"MIT"
] | null | null | null | //
// Created by Felix Klauke on 29.03.18.
//
#include <RootNode.h>
#include <ClassNode.h>
#include <iostream>
#include <StatementNode.h>
#include <VarDeclarationNode.h>
#include <VarAssignNode.h>
#include <IntegerNode.h>
#include <FunctionCallNode.h>
#include <VarDeclarationAndInitializationNode.h>
#include "Parser.h"
Parser::Parser(const Lexer &lexer) : lexer(lexer) {
}
Node *Parser::parse() {
currentToken = lexer.ReadNextToken();
std::vector<Node *> classNodes = std::vector<Node *>();
while (currentToken->GetTokenType() == TokenType::CLASS) {
ClassNode *classNode = ParseClass();
classNodes.push_back(classNode);
}
auto *rootNode = new RootNode(&classNodes);
std::cout << "Found root with " << classNodes.size() << " classes.";
return rootNode;
}
ClassNode *Parser::ParseClass() {
std::vector<FunctionNode *> functionNodes = std::vector<FunctionNode *>();
EatToken(TokenType::CLASS);
std::string className = currentToken->GetValue();
EatToken(TokenType::LABEL);
EatToken(TokenType::LEFT_CURLY_BRACE);
while (currentToken->GetTokenType() == TokenType::FUNCTION) {
FunctionNode *functionNode = ParseFunction();
functionNodes.push_back(functionNode);
}
EatToken(TokenType::RIGHT_CURLY_BRACE);
auto *classNode = new ClassNode(className, &functionNodes);
std::cout << "Found class " << className << " with " << functionNodes.size() << " functions." << std::endl;
return classNode;
}
void Parser::EatToken(TokenType type) {
if (currentToken->GetTokenType() == type) {
Token *token = lexer.ReadNextToken();
currentToken = token;
return;
}
throw std::invalid_argument("Unexpected token " + currentToken->GetValue());
}
FunctionNode *Parser::ParseFunction() {
EatToken(TokenType::FUNCTION);
std::string functionName = currentToken->GetValue();
EatToken(TokenType::FUNCTION_CALL);
EatToken(TokenType::LEFT_BRACE);
std::vector<Node *> parameters = std::vector<Node *>();
while (currentToken->GetTokenType() != TokenType::RIGHT_BRACE) {
parameters.push_back(ParseValue());
if (currentToken->GetTokenType() == TokenType::COMMA) {
EatToken(TokenType::COMMA);
}
}
EatToken(TokenType::RIGHT_BRACE);
EatToken(TokenType::LEFT_CURLY_BRACE);
std::vector<Node *> statements = std::vector<Node *>();
while (currentToken->GetTokenType() != TokenType::RIGHT_CURLY_BRACE) {
Node *statementNode = ParseStatement();
statements.push_back(statementNode);
}
EatToken(TokenType::RIGHT_CURLY_BRACE);
auto *functionNode = new FunctionNode(&functionName, &statements, ¶meters);
std::cout << "Found function " << functionName << " with " << statements.size() << " statements and "
<< parameters.size() << " parameters." << std::endl;
return functionNode;
}
Node *Parser::ParseStatement() {
if (currentToken->GetTokenType() == TokenType::INTEGER || currentToken->GetTokenType() == TokenType::STRING) {
return ParseVariableStatement();
} else if (currentToken->GetTokenType() == TokenType::FUNCTION_CALL) {
return ParseFunctionCall();
} else if (currentToken->GetTokenType() == TokenType::LABEL) {
return ParseVariableAssignStatement();
}
}
StatementNode *Parser::ParseVariableStatement() {
TokenType variableType = currentToken->GetTokenType();
EatToken(variableType);
std::string variableName = currentToken->GetValue();
EatToken(TokenType::LABEL);
if (currentToken->GetTokenType() == TokenType::ASSIGN) {
EatToken(TokenType::ASSIGN);
auto *variableStatement = new VarDeclarationAndInitializationNode(&variableName, variableType, ParseValue());
std::cout << "Found declared and assigned variable: " << variableName << "." << std::endl;
return variableStatement;
}
auto *variableStatement = new VarDeclarationNode(&variableName, variableType);
std::cout << "Found declared variable: " << variableName << "." << std::endl;
return variableStatement;
}
Node *Parser::ParseValue() {
if (currentToken->GetTokenType() == TokenType::INTEGER) {
IntegerNode *integerNode = new IntegerNode(std::stoi(currentToken->GetValue()));
EatToken(TokenType::INTEGER);
return integerNode;
}
}
Node *Parser::ParseFunctionCall() {
std::string functionName = currentToken->GetValue();
EatToken(TokenType::FUNCTION_CALL);
EatToken(TokenType::LEFT_BRACE);
std::vector<Node *> parameters = std::vector<Node *>();
while (currentToken->GetTokenType() != TokenType::RIGHT_BRACE) {
parameters.push_back(ParseValue());
if (currentToken->GetTokenType() == TokenType::COMMA) {
EatToken(TokenType::COMMA);
}
}
EatToken(TokenType::RIGHT_BRACE);
auto *functionCallNode = new FunctionCallNode(nullptr, ¶meters);
std::cout << "Found function call: " << functionName << " with " << parameters.size() << " parameters."
<< std::endl;
return functionCallNode;
}
Node *Parser::ParseVariableAssignStatement() {
std::string variableName = currentToken->GetValue();
EatToken(TokenType::LABEL);
EatToken(TokenType::ASSIGN);
auto *varAssignNode = new VarAssignNode(&variableName, ParseValue());
std::cout << "Found variable assign node: " << variableName << std::endl;
return varAssignNode;
}
| 31.045198 | 117 | 0.66697 | FelixKlauke |
ebe3e93682ad299f8ed7386b049f861e2e313e7d | 436 | cpp | C++ | solved/c-e/clockhands/clock.cpp | abuasifkhan/pc-code | 77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90 | [
"Unlicense"
] | 13 | 2015-09-30T19:18:04.000Z | 2021-06-26T21:11:30.000Z | solved/c-e/clockhands/clock.cpp | sbmaruf/pc-code | 77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90 | [
"Unlicense"
] | null | null | null | solved/c-e/clockhands/clock.cpp | sbmaruf/pc-code | 77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90 | [
"Unlicense"
] | 13 | 2015-01-04T09:49:54.000Z | 2021-06-03T13:18:44.000Z | #include <algorithm>
#include <cstdio>
using namespace std;
int H, M;
double a, b; // angles for the two hands
int main()
{
while (true) {
scanf("%d:%d", &H, &M);
if (H == 0 && M == 0) break;
a = H*30 + 1.0*M/2.0;
b = M*6;
double x = a - b;
double y = b - a;
if (x < 0) x += 360;
if (y < 0) y += 360;
printf("%.3lf\n", min(x, y));
}
return 0;
}
| 16.148148 | 41 | 0.419725 | abuasifkhan |
ebe3ea59960afffa21becef88968acac9b4ca82d | 922 | cc | C++ | chromecast/browser/cast_content_window.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | chromecast/browser/cast_content_window.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | chromecast/browser/cast_content_window.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2018 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 "chromecast/browser/cast_content_window.h"
namespace chromecast {
CastContentWindow::CastContentWindow(const CreateParams& params)
: delegate_(params.delegate) {}
CastContentWindow::~CastContentWindow() = default;
CastContentWindow::CreateParams::CreateParams() = default;
CastContentWindow::CreateParams::CreateParams(const CreateParams& other) =
default;
CastContentWindow::CreateParams::~CreateParams() = default;
void CastContentWindow::AddObserver(Observer* observer) {
observer_list_.AddObserver(observer);
}
void CastContentWindow::RemoveObserver(Observer* observer) {
observer_list_.RemoveObserver(observer);
}
mojom::MediaControlUi* CastContentWindow::media_controls() {
return nullptr;
}
} // namespace chromecast
| 28.8125 | 74 | 0.786334 | sarang-apps |
ebe57cecc324b43eec1fdab43ab14ec9347ea301 | 5,050 | cpp | C++ | libs/dev/PCSTree/PA1/PCSTree.cpp | Norseman055/immaterial-engine | 6aca0fad64f5b2b9fe6eb351528a79a39dc94625 | [
"MIT"
] | null | null | null | libs/dev/PCSTree/PA1/PCSTree.cpp | Norseman055/immaterial-engine | 6aca0fad64f5b2b9fe6eb351528a79a39dc94625 | [
"MIT"
] | null | null | null | libs/dev/PCSTree/PA1/PCSTree.cpp | Norseman055/immaterial-engine | 6aca0fad64f5b2b9fe6eb351528a79a39dc94625 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <assert.h>
#include <string.h>
#include "PCSTree.h"
#include "PCSNode.h"
// constructor
PCSTree::PCSTree()
{
info.maxLevelCount = 0;
info.maxNodeCount = 0;
info.numLevels = 0;
info.numNodes = 0;
root = NULL;
};
// destructor
PCSTree::~PCSTree()
{
// printf("PCSTree: destructor()\n");
};
// get Root
PCSNode *PCSTree::getRoot( void ) const
{
return (PCSNode *)root;
}
// insert
void PCSTree::insert(PCSNode *inNode, PCSNode *parent)
{
if (this->getRoot() != 0) // if tree has a root already
{
inNode->setParent(parent); // set node's parent to specified parent.
inNode->setLevel((inNode->getParent()->getLevel()) + 1);
if (parent->getChild() != 0) // if parent node has children, add it as first sibling on list.
{ // store first sibling as tmp, add node as parent's child, adjust sibling list
PCSNode *tmp = parent->getChild();
parent->setChild(inNode);
inNode->setSibling(tmp);
}
else // if that parent node has no children, make it a child.
{
parent->setChild(inNode); // set parents node child to inNode
}
}
else // tree has no root. it is now the root. forget your parent specifier.
{
root = inNode; // make root the first node
inNode->setParent(NULL); // set the node's parent to null. its now the root.
inNode->setLevel(1);
}
checkLevels(inNode);
info.maxNodeCount++;
info.numNodes++;
}
// Remove
// super easy process. just remove its link from the parent and make sure siblings to left link to the right
void PCSTree::remove(PCSNode * const inNode)
{
// make sure inNode is NOT the root. if it is the root, just zero out all its stats.
if (inNode != root)
{
// check to see if inNode is NOT the only child.
if (inNode->getParent()->getChild() != inNode || inNode->getSibling())
{
// first case, its a "first child". set the parent's first child to the next child in line.
if (inNode->getParent()->getChild() == inNode)
{
inNode->getParent()->setChild( inNode->getSibling() );
}
// second case, its the "middle" or "youngest". find previous sibling point.
else
{
PCSNode *tmp = inNode->getParent()->getChild(); // create temp node to find previous child
while (tmp->getSibling() != inNode)
tmp = tmp->getSibling(); // move temp node to position right before child
// youngest
if (inNode->getSibling() == NULL)
tmp->setSibling(NULL); // set final sibling to null
// middle
else
tmp->setSibling(inNode->getSibling()); // link inNode's previous sibling to its next sibling.
}
}
// inNode is only child. just tell parent that it has no children.
else
inNode->getParent()->setChild(NULL);
}
else
root = NULL;
// set everything derived from inNode (children and their siblings, etc) to 0
if (inNode->getChild())
removeDown(inNode->getChild());
// clean up inNode links to 0
inNode->setChild(NULL);
inNode->setParent(NULL);
inNode->setSibling(NULL);
// update info
info.numNodes--;
}
// get tree info
void PCSTree::getInfo( PCSTreeInfo &infoContainer )
{
info.numLevels = 0;
PCSNode *travelTree = root;
if (travelTree != NULL) // if it isn't a null pointer, check the depth of the tree.
{
goDown(travelTree);
}
infoContainer.maxLevelCount = info.maxLevelCount;
infoContainer.maxNodeCount = info.maxNodeCount;
infoContainer.numLevels = info.numLevels;
infoContainer.numNodes = info.numNodes;
}
void PCSTree::dumpTree( ) const
{
if (root)
{
printf("\ndumpTree() ----------------");
root->printDown(root);
}
}
// this function is called just once to check the levels with getInfo().
void PCSTree::goDown( const PCSNode* const _root )
{
if (_root->getChild() != NULL) // if root has a child, go down again.
{
goDown(_root->getChild());
}
checkLevels(_root); // check levels for that tree
if (_root->getSibling() != NULL) // now traverse siblings.
{
goDown(_root->getSibling());
}
}
// this deletes all children below a specified original root. basically the same as goDown, but calls remove function.
// at its final iteration, it is always at the final sibling, so it zeroes everything out.
void PCSTree::removeDown( PCSNode * const _root )
{
if (_root->getChild() != NULL) // if root has a child, go down again.
{
removeDown(_root->getChild());
}
if (_root->getSibling() != NULL) // now traverse siblings.
{
removeDown(_root->getSibling());
}
// zero out current node
_root->setChild(NULL);
_root->setParent(NULL);
_root->setSibling(NULL);
// update info
info.numNodes--;
}
// this is a function that just checks the number of levels away from the root any given node is.
void PCSTree::checkLevels( const PCSNode * const inNode )
{
if (inNode->getLevel() > info.maxLevelCount) // if current level is greater than max, increase max
info.maxLevelCount = inNode->getLevel();
if (inNode->getLevel() > info.numLevels) // if current level is greater than recorded levels, increase recorded levels
info.numLevels = inNode->getLevel();
} | 26.302083 | 121 | 0.671683 | Norseman055 |
ebe7b4999a1de061dfec998206e07727d0ea13c1 | 282 | hpp | C++ | src_ordenacao_imperador_algoritmo2/include/Bubble.hpp | victormagalhaess/TP2-ED-2020 | 78d020c6da1c036fd6643d6ed066f3440a45a981 | [
"MIT"
] | null | null | null | src_ordenacao_imperador_algoritmo2/include/Bubble.hpp | victormagalhaess/TP2-ED-2020 | 78d020c6da1c036fd6643d6ed066f3440a45a981 | [
"MIT"
] | null | null | null | src_ordenacao_imperador_algoritmo2/include/Bubble.hpp | victormagalhaess/TP2-ED-2020 | 78d020c6da1c036fd6643d6ed066f3440a45a981 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <iostream>
#include "./Civilization.hpp"
#ifndef BUBBLE
#define BUBBLE
namespace Emperor2
{
class Bubble
{
public:
Civilization *BubbleSort(Civilization *civilizations, int numberOfCivilizations);
};
} // namespace Emperor2
#endif | 20.142857 | 89 | 0.712766 | victormagalhaess |
ebea36374ee8bf322642b91d60d644b4f780b60f | 2,255 | hpp | C++ | src/sosofo.hpp | hvellyr/sairy | 3b7b797c71384222d58b67bded24ee5b5cc6aa2a | [
"BSD-3-Clause"
] | null | null | null | src/sosofo.hpp | hvellyr/sairy | 3b7b797c71384222d58b67bded24ee5b5cc6aa2a | [
"BSD-3-Clause"
] | null | null | null | src/sosofo.hpp | hvellyr/sairy | 3b7b797c71384222d58b67bded24ee5b5cc6aa2a | [
"BSD-3-Clause"
] | 1 | 2018-01-29T10:57:09.000Z | 2018-01-29T10:57:09.000Z | // Copyright (c) 2015 Gregor Klinke
// All rights reserved.
#pragma once
#include "fo.hpp"
#include <iterator>
#include <memory>
#include <string>
#include <vector>
namespace eyestep {
class SosofoIterator;
class Sosofo
{
public:
/*! Creates an empty sosofo */
Sosofo();
Sosofo(const Sosofo& one, const Sosofo& two);
Sosofo(const std::vector<Sosofo>& sosofos);
/*! Creates a sosofo with exactly one formatting object */
Sosofo(std::shared_ptr<IFormattingObject> fo);
Sosofo(const std::string& label, std::shared_ptr<IFormattingObject> fo);
/*! Returns a new sosofo with all FOs from @p other appended */
Sosofo concat(const Sosofo& other) const;
void set_label(const std::string& lbl) {
_label = lbl;
}
const std::string& label() const {
return _label;
}
bool empty() const {
return _fos.empty();
}
int length() const {
return int(_fos.size());
}
const IFormattingObject* operator[](size_t idx) const {
return _fos[idx].get();
}
SosofoIterator begin() const;
SosofoIterator end() const;
private:
std::string _label;
std::vector<std::shared_ptr<IFormattingObject>> _fos;
};
class SosofoIterator
{
const Sosofo* _sosofo = nullptr;
int _idx = 0;
public:
using iterator_category = std::forward_iterator_tag;
using value_type = const IFormattingObject;
using difference_type = std::ptrdiff_t;
using pointer = value_type*;
using reference = value_type&;
/*! the end iterator */
SosofoIterator() = default;
SosofoIterator(const Sosofo* sosofo, int idx)
: _sosofo(sosofo)
, _idx(idx) {
if (_idx < 0 || _idx >= _sosofo->length()) {
*this = {};
}
}
SosofoIterator& operator++() {
++_idx;
if (_idx >= _sosofo->length()) {
*this = {};
}
return *this;
}
SosofoIterator operator++(int) {
SosofoIterator retval = *this;
++(*this);
return retval;
}
bool operator==(SosofoIterator other) const {
return _sosofo == other._sosofo && _idx == other._idx;
}
bool operator!=(SosofoIterator other) const {
return !(*this == other);
}
reference operator*() const {
return *(*_sosofo)[_idx];
}
pointer operator->() const {
return (*_sosofo)[_idx];
}
};
} // ns eyestep
| 19.273504 | 74 | 0.647007 | hvellyr |
ebeed60cd61c7c5dd636502acb36f1b78ccd8dc7 | 7,542 | cpp | C++ | android/filament-android/src/main/cpp/IndirectLight.cpp | Alan-love/filament | 87ee5783b7f72bb5b045d9334d719ea2de9f5247 | [
"Apache-2.0"
] | 1 | 2020-04-04T17:14:40.000Z | 2020-04-04T17:14:40.000Z | android/filament-android/src/main/cpp/IndirectLight.cpp | Alan-love/filament | 87ee5783b7f72bb5b045d9334d719ea2de9f5247 | [
"Apache-2.0"
] | null | null | null | android/filament-android/src/main/cpp/IndirectLight.cpp | Alan-love/filament | 87ee5783b7f72bb5b045d9334d719ea2de9f5247 | [
"Apache-2.0"
] | 1 | 2020-03-06T06:27:49.000Z | 2020-03-06T06:27:49.000Z | /*
* Copyright (C) 2017 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 <jni.h>
#include <filament/IndirectLight.h>
#include <filament/Texture.h>
#include <common/NioUtils.h>
#include <common/CallbackUtils.h>
#include <math/mat4.h>
using namespace filament;
extern "C" JNIEXPORT jlong JNICALL
Java_com_google_android_filament_IndirectLight_nCreateBuilder(JNIEnv*, jclass) {
return (jlong) new IndirectLight::Builder();
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_IndirectLight_nDestroyBuilder(JNIEnv*, jclass,
jlong nativeBuilder) {
IndirectLight::Builder* builder = (IndirectLight::Builder*) nativeBuilder;
delete builder;
}
extern "C" JNIEXPORT jlong JNICALL
Java_com_google_android_filament_IndirectLight_nBuilderBuild(JNIEnv*, jclass,
jlong nativeBuilder, jlong nativeEngine) {
IndirectLight::Builder* builder = (IndirectLight::Builder*) nativeBuilder;
Engine *engine = (Engine *) nativeEngine;
return (jlong) builder->build(*engine);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_IndirectLight_nBuilderReflections(JNIEnv*, jclass,
jlong nativeBuilder, jlong nativeTexture) {
IndirectLight::Builder* builder = (IndirectLight::Builder*) nativeBuilder;
const Texture *texture = (const Texture *) nativeTexture;
builder->reflections(texture);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_IndirectLight_nIrradiance(JNIEnv* env, jclass,
jlong nativeBuilder, jint bands, jfloatArray sh_) {
IndirectLight::Builder* builder = (IndirectLight::Builder*) nativeBuilder;
jfloat* sh = env->GetFloatArrayElements(sh_, NULL);
builder->irradiance((uint8_t) bands, (const filament::math::float3*) sh);
env->ReleaseFloatArrayElements(sh_, sh, JNI_ABORT);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_IndirectLight_nRadiance(JNIEnv* env, jclass,
jlong nativeBuilder, jint bands, jfloatArray sh_) {
IndirectLight::Builder* builder = (IndirectLight::Builder*) nativeBuilder;
jfloat* sh = env->GetFloatArrayElements(sh_, NULL);
builder->radiance((uint8_t) bands, (const filament::math::float3*) sh);
env->ReleaseFloatArrayElements(sh_, sh, JNI_ABORT);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_IndirectLight_nIrradianceAsTexture(JNIEnv*, jclass,
jlong nativeBuilder, jlong nativeTexture) {
IndirectLight::Builder* builder = (IndirectLight::Builder*) nativeBuilder;
const Texture* texture = (const Texture*) nativeTexture;
builder->irradiance(texture);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_IndirectLight_nIntensity(JNIEnv*, jclass,
jlong nativeBuilder, jfloat envIntensity) {
IndirectLight::Builder* builder = (IndirectLight::Builder*) nativeBuilder;
builder->intensity(envIntensity);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_IndirectLight_nRotation(JNIEnv *, jclass, jlong nativeBuilder,
jfloat v0, jfloat v1, jfloat v2, jfloat v3, jfloat v4, jfloat v5, jfloat v6, jfloat v7,
jfloat v8) {
IndirectLight::Builder *builder = (IndirectLight::Builder *) nativeBuilder;
builder->rotation(filament::math::mat3f{v0, v1, v2, v3, v4, v5, v6, v7, v8});
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_IndirectLight_nSetIntensity(JNIEnv*, jclass,
jlong nativeIndirectLight, jfloat intensity) {
IndirectLight* indirectLight = (IndirectLight*) nativeIndirectLight;
indirectLight->setIntensity(intensity);
}
extern "C" JNIEXPORT jfloat JNICALL
Java_com_google_android_filament_IndirectLight_nGetIntensity(JNIEnv*, jclass,
jlong nativeIndirectLight) {
IndirectLight* indirectLight = (IndirectLight*) nativeIndirectLight;
return indirectLight->getIntensity();
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_IndirectLight_nSetRotation(JNIEnv*, jclass,
jlong nativeIndirectLight, jfloat v0, jfloat v1, jfloat v2,
jfloat v3, jfloat v4, jfloat v5, jfloat v6, jfloat v7, jfloat v8) {
IndirectLight *indirectLight = (IndirectLight *) nativeIndirectLight;
indirectLight->setRotation(filament::math::mat3f{v0, v1, v2, v3, v4, v5, v6, v7, v8});
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_IndirectLight_nGetRotation(JNIEnv* env, jclass,
jlong nativeIndirectLight, jfloatArray outRotation_) {
IndirectLight *indirectLight = (IndirectLight *) nativeIndirectLight;
jfloat *outRotation = env->GetFloatArrayElements(outRotation_, NULL);
*reinterpret_cast<filament::math::mat3f*>(outRotation) = indirectLight->getRotation();
env->ReleaseFloatArrayElements(outRotation_, outRotation, 0);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_IndirectLight_nGetDirectionEstimate(JNIEnv* env, jclass,
jlong nativeIndirectLight, jfloatArray outDirection_) {
IndirectLight *indirectLight = (IndirectLight *) nativeIndirectLight;
jfloat *outDirection = env->GetFloatArrayElements(outDirection_, NULL);
*reinterpret_cast<filament::math::float3*>(outDirection) = indirectLight->getDirectionEstimate();
env->ReleaseFloatArrayElements(outDirection_, outDirection, 0);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_IndirectLight_nGetColorEstimate(JNIEnv* env, jclass,
jlong nativeIndirectLight, jfloatArray outColor_, jfloat x, jfloat y, jfloat z) {
IndirectLight *indirectLight = (IndirectLight *) nativeIndirectLight;
jfloat *outColor = env->GetFloatArrayElements(outColor_, NULL);
*reinterpret_cast<filament::math::float4*>(outColor) =
indirectLight->getColorEstimate(math::float3{x, y, z});
env->ReleaseFloatArrayElements(outColor_, outColor, 0);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_IndirectLight_nGetDirectionEstimateStatic(JNIEnv *env, jclass,
jfloatArray sh_, jfloatArray outDirection_) {
jfloat* sh = env->GetFloatArrayElements(sh_, NULL);
jfloat *outDirection = env->GetFloatArrayElements(outDirection_, NULL);
*reinterpret_cast<filament::math::float3*>(outDirection) = IndirectLight::getDirectionEstimate((filament::math::float3*)sh);
env->ReleaseFloatArrayElements(outDirection_, outDirection, 0);
env->ReleaseFloatArrayElements(sh_, sh, JNI_ABORT);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_IndirectLight_nGetColorEstimateStatic(JNIEnv *env, jclass,
jfloatArray outColor_, jfloatArray sh_, jfloat x, jfloat y, jfloat z) {
jfloat* sh = env->GetFloatArrayElements(sh_, NULL);
jfloat *outColor = env->GetFloatArrayElements(outColor_, NULL);
*reinterpret_cast<filament::math::float4*>(outColor) =
IndirectLight::getColorEstimate((filament::math::float3*)sh, math::float3{x, y, z});
env->ReleaseFloatArrayElements(outColor_, outColor, 0);
env->ReleaseFloatArrayElements(sh_, sh, JNI_ABORT);
} | 45.433735 | 128 | 0.764121 | Alan-love |
ebefb9f00c972446b26434541bac080107dde993 | 7,796 | cpp | C++ | source/games/sw/src/mclip.cpp | alexey-lysiuk/Raze | 690994ea1e6b105d4fc55d6b81ffda5e26e68c36 | [
"RSA-MD"
] | null | null | null | source/games/sw/src/mclip.cpp | alexey-lysiuk/Raze | 690994ea1e6b105d4fc55d6b81ffda5e26e68c36 | [
"RSA-MD"
] | null | null | null | source/games/sw/src/mclip.cpp | alexey-lysiuk/Raze | 690994ea1e6b105d4fc55d6b81ffda5e26e68c36 | [
"RSA-MD"
] | null | null | null | //-------------------------------------------------------------------------
/*
Copyright (C) 1997, 2005 - 3D Realms Entertainment
This file is part of Shadow Warrior version 1.2
Shadow Warrior is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Original Source: 1997 - Frank Maddin and Jim Norwood
Prepared for public release: 03/28/2005 - Charlie Wiederhold, 3D Realms
*/
//-------------------------------------------------------------------------
#include "ns.h"
#include "build.h"
#include "mytypes.h"
#include "names2.h"
#include "panel.h"
#include "game.h"
#include "tags.h"
#include "player.h"
#include "mclip.h"
BEGIN_SW_NS
int MultiClipMove(PLAYERp pp, int z, int floor_dist)
{
int i;
vec3_t opos[MAX_CLIPBOX], pos[MAX_CLIPBOX];
SECTOR_OBJECTp sop = pp->sop;
short ang;
short min_ndx = 0;
int min_dist = 999999;
int dist;
int ret_start;
int ret;
int min_ret=0;
int xvect,yvect;
for (i = 0; i < sop->clipbox_num; i++)
{
// move the box to position instead of using offset- this prevents small rounding errors
// allowing you to move through wall
ang = NORM_ANGLE(pp->angle.ang.asbuild() + sop->clipbox_ang[i]);
vec3_t spos = { pp->posx, pp->posy, z };
xvect = sop->clipbox_vdist[i] * bcos(ang);
yvect = sop->clipbox_vdist[i] * bsin(ang);
ret_start = clipmove(&spos, &pp->cursectnum, xvect, yvect, (int)sop->clipbox_dist[i], Z(4), floor_dist, CLIPMASK_PLAYER, 1);
if (ret_start)
{
// hit something moving into start position
min_dist = 0;
min_ndx = i;
// ox is where it should be
opos[i].x = pos[i].x = pp->posx + MulScale(sop->clipbox_vdist[i], bcos(ang), 14);
opos[i].y = pos[i].y = pp->posy + MulScale(sop->clipbox_vdist[i], bsin(ang), 14);
// spos.x is where it hit
pos[i].x = spos.x;
pos[i].y = spos.y;
// see the dist moved
dist = ksqrt(SQ(pos[i].x - opos[i].x) + SQ(pos[i].y - opos[i].y));
// save it off
if (dist < min_dist)
{
min_dist = dist;
min_ndx = i;
min_ret = ret_start;
}
}
else
{
// save off the start position
opos[i] = pos[i] = spos;
pos[i].z = z;
// move the box
ret = clipmove(&pos[i], &pp->cursectnum, pp->xvect, pp->yvect, (int)sop->clipbox_dist[i], Z(4), floor_dist, CLIPMASK_PLAYER);
// save the dist moved
dist = ksqrt(SQ(pos[i].x - opos[i].x) + SQ(pos[i].y - opos[i].y));
if (ret)
{
}
if (dist < min_dist)
{
min_dist = dist;
min_ndx = i;
min_ret = ret;
}
}
}
// put posx and y off from offset
pp->posx += pos[min_ndx].x - opos[min_ndx].x;
pp->posy += pos[min_ndx].y - opos[min_ndx].y;
return min_ret;
}
short MultiClipTurn(PLAYERp pp, short new_ang, int z, int floor_dist)
{
int i;
SECTOR_OBJECTp sop = pp->sop;
int ret;
int x,y;
short ang;
int xvect, yvect;
int cursectnum = pp->cursectnum;
for (i = 0; i < sop->clipbox_num; i++)
{
ang = NORM_ANGLE(new_ang + sop->clipbox_ang[i]);
vec3_t pos = { pp->posx, pp->posy, z };
xvect = sop->clipbox_vdist[i] * bcos(ang);
yvect = sop->clipbox_vdist[i] * bsin(ang);
// move the box
ret = clipmove(&pos, &cursectnum, xvect, yvect, (int)sop->clipbox_dist[i], Z(4), floor_dist, CLIPMASK_PLAYER);
ASSERT(cursectnum >= 0);
if (ret)
{
// attempt to move a bit when turning against a wall
//ang = NORM_ANGLE(ang + 1024);
//pp->xvect += 20 * bcos(ang);
//pp->yvect += 20 * bsin(ang);
return false;
}
}
return true;
}
int testquadinsect(int *point_num, vec2_t const * q, short sectnum)
{
int i,next_i;
*point_num = -1;
for (i=0; i < 4; i++)
{
if (!inside(q[i].x, q[i].y, sectnum))
{
*point_num = i;
return false;
}
}
for (i=0; i<4; i++)
{
next_i = (i+1) & 3;
if (!cansee(q[i].x, q[i].y,0x3fffffff, sectnum,
q[next_i].x, q[next_i].y,0x3fffffff, sectnum))
{
return false;
}
}
return true;
}
//Ken gives the tank clippin' a try...
int RectClipMove(PLAYERp pp, int *qx, int *qy)
{
int i;
vec2_t xy[4];
int point_num;
for (i = 0; i < 4; i++)
{
xy[i].x = qx[i] + (pp->xvect>>14);
xy[i].y = qy[i] + (pp->yvect>>14);
}
//Given the 4 points: x[4], y[4]
if (testquadinsect(&point_num, xy, pp->cursectnum))
{
pp->posx += (pp->xvect>>14);
pp->posy += (pp->yvect>>14);
return true;
}
if (point_num < 0)
return false;
if ((point_num == 0) || (point_num == 3)) //Left side bad - strafe right
{
for (i = 0; i < 4; i++)
{
xy[i].x = qx[i] - (pp->yvect>>15);
xy[i].y = qy[i] + (pp->xvect>>15);
}
if (testquadinsect(&point_num, xy, pp->cursectnum))
{
pp->posx -= (pp->yvect>>15);
pp->posy += (pp->xvect>>15);
}
return false;
}
if ((point_num == 1) || (point_num == 2)) //Right side bad - strafe left
{
for (i = 0; i < 4; i++)
{
xy[i].x = qx[i] + (pp->yvect>>15);
xy[i].y = qy[i] - (pp->xvect>>15);
}
if (testquadinsect(&point_num, xy, pp->cursectnum))
{
pp->posx += (pp->yvect>>15);
pp->posy -= (pp->xvect>>15);
}
return false;
}
return false;
}
int testpointinquad(int x, int y, int *qx, int *qy)
{
int i, cnt, x1, y1, x2, y2;
cnt = 0;
for (i=0; i<4; i++)
{
y1 = qy[i]-y;
y2 = qy[(i+1)&3]-y;
if ((y1^y2) >= 0) continue;
x1 = qx[i]-x;
x2 = qx[(i+1)&3]-x;
if ((x1^x2) >= 0)
cnt ^= x1;
else
cnt ^= (x1*y2-x2*y1)^y2;
}
return cnt>>31;
}
short RectClipTurn(PLAYERp pp, short new_ang, int *qx, int *qy, int *ox, int *oy)
{
int i;
vec2_t xy[4];
SECTOR_OBJECTp sop = pp->sop;
short rot_ang;
int point_num;
rot_ang = NORM_ANGLE(new_ang + sop->spin_ang - sop->ang_orig);
for (i = 0; i < 4; i++)
{
vec2_t const p = { ox[i], oy[i] };
rotatepoint(pp->pos.vec2, p, rot_ang, &xy[i]);
// cannot use sop->xmid and ymid because the SO is off the map at this point
//rotatepoint(&sop->xmid, p, rot_ang, &xy[i]);
}
//Given the 4 points: x[4], y[4]
if (testquadinsect(&point_num, xy, pp->cursectnum))
{
// move to new pos
for (i = 0; i < 4; i++)
{
qx[i] = xy[i].x;
qy[i] = xy[i].y;
}
return true;
}
if (point_num < 0)
return false;
return false;
}
END_SW_NS
| 25.394137 | 137 | 0.506542 | alexey-lysiuk |
ebf103c146e5be8b574ba6777f15b84687b8e067 | 1,133 | cpp | C++ | oreore/oreore/cocos2d/actions/ShakeFadeOut.cpp | Giemsa/oreore | 18c2f07bca7df9599aa68cf79d627e239b17461c | [
"Zlib"
] | 4 | 2015-01-26T17:46:26.000Z | 2018-12-28T09:09:19.000Z | oreore/oreore/cocos2d/actions/ShakeFadeOut.cpp | Giemsa/oreore | 18c2f07bca7df9599aa68cf79d627e239b17461c | [
"Zlib"
] | null | null | null | oreore/oreore/cocos2d/actions/ShakeFadeOut.cpp | Giemsa/oreore | 18c2f07bca7df9599aa68cf79d627e239b17461c | [
"Zlib"
] | null | null | null | #include "ShakeFadeOut.h"
#include "../../Utils.h"
namespace oreore
{
using namespace cocos2d;
ShakeFadeOut *ShakeFadeOut::create(const float duration, const float strength)
{
return create(duration, strength, strength);
}
ShakeFadeOut *ShakeFadeOut::create(const float duration, const float level_x, const float level_y)
{
ShakeFadeOut *action = new ShakeFadeOut();
if(action && action->initWithDuration(duration, level_x, level_y))
{
action->autorelease();
return action;
}
delete action;
return nullptr;
}
void ShakeFadeOut::update(float time)
{
const float x = (random<float>(strength_x * 2) - strength_x) * (1.0f - time);
const float y = (random<float>(strength_y * 2) - strength_y) * (1.0f - time);
getOriginalTarget()->setPosition(dpos + Point(x, y));
}
ShakeFadeOut *ShakeFadeOut::reverse() const
{
return clone();
}
ShakeFadeOut *ShakeFadeOut::clone() const
{
return ShakeFadeOut::create(getDuration(), strength_x, strength_y);
}
}
| 25.75 | 102 | 0.616064 | Giemsa |
ebf67bcb4413e9c999e91f98f9eff5627331c191 | 12,727 | cpp | C++ | roxe.cdt/roxe_llvm/tools/llvm-mca/Scheduler.cpp | APFDev/actc | be5c1c0539d30a3745a725b0027767448ef8e1f6 | [
"MIT"
] | 5 | 2021-01-13T03:34:00.000Z | 2021-09-09T05:42:18.000Z | roxe.cdt/roxe_llvm/tools/llvm-mca/Scheduler.cpp | APFDev/actc | be5c1c0539d30a3745a725b0027767448ef8e1f6 | [
"MIT"
] | 1 | 2020-05-16T06:30:28.000Z | 2020-05-16T06:37:55.000Z | roxe.cdt/roxe_llvm/tools/llvm-mca/Scheduler.cpp | APFDev/actc | be5c1c0539d30a3745a725b0027767448ef8e1f6 | [
"MIT"
] | 6 | 2020-01-06T11:18:54.000Z | 2020-01-07T09:32:18.000Z | //===--------------------- Scheduler.cpp ------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// A scheduler for processor resource units and processor resource groups.
//
//===----------------------------------------------------------------------===//
#include "Scheduler.h"
#include "Backend.h"
#include "HWEventListener.h"
#include "Support.h"
#include "llvm/Support/raw_ostream.h"
namespace mca {
using namespace llvm;
uint64_t ResourceState::selectNextInSequence() {
assert(isReady());
uint64_t Next = getNextInSequence();
while (!isSubResourceReady(Next)) {
updateNextInSequence();
Next = getNextInSequence();
}
return Next;
}
#ifndef NDEBUG
void ResourceState::dump() const {
dbgs() << "MASK: " << ResourceMask << ", SIZE_MASK: " << ResourceSizeMask
<< ", NEXT: " << NextInSequenceMask << ", RDYMASK: " << ReadyMask
<< ", BufferSize=" << BufferSize
<< ", AvailableSlots=" << AvailableSlots
<< ", Reserved=" << Unavailable << '\n';
}
#endif
void ResourceManager::initialize(const llvm::MCSchedModel &SM) {
computeProcResourceMasks(SM, ProcResID2Mask);
for (unsigned I = 0, E = SM.getNumProcResourceKinds(); I < E; ++I)
addResource(*SM.getProcResource(I), I, ProcResID2Mask[I]);
}
// Adds a new resource state in Resources, as well as a new descriptor in
// ResourceDescriptor. Map 'Resources' allows to quickly obtain ResourceState
// objects from resource mask identifiers.
void ResourceManager::addResource(const MCProcResourceDesc &Desc,
unsigned Index, uint64_t Mask) {
assert(Resources.find(Mask) == Resources.end() && "Resource already added!");
Resources[Mask] = llvm::make_unique<ResourceState>(Desc, Index, Mask);
}
// Returns the actual resource consumed by this Use.
// First, is the primary resource ID.
// Second, is the specific sub-resource ID.
std::pair<uint64_t, uint64_t> ResourceManager::selectPipe(uint64_t ResourceID) {
ResourceState &RS = *Resources[ResourceID];
uint64_t SubResourceID = RS.selectNextInSequence();
if (RS.isAResourceGroup())
return selectPipe(SubResourceID);
return std::pair<uint64_t, uint64_t>(ResourceID, SubResourceID);
}
void ResourceState::removeFromNextInSequence(uint64_t ID) {
assert(NextInSequenceMask);
assert(countPopulation(ID) == 1);
if (ID > getNextInSequence())
RemovedFromNextInSequence |= ID;
NextInSequenceMask = NextInSequenceMask & (~ID);
if (!NextInSequenceMask) {
NextInSequenceMask = ResourceSizeMask;
assert(NextInSequenceMask != RemovedFromNextInSequence);
NextInSequenceMask ^= RemovedFromNextInSequence;
RemovedFromNextInSequence = 0;
}
}
void ResourceManager::use(ResourceRef RR) {
// Mark the sub-resource referenced by RR as used.
ResourceState &RS = *Resources[RR.first];
RS.markSubResourceAsUsed(RR.second);
// If there are still available units in RR.first,
// then we are done.
if (RS.isReady())
return;
// Notify to other resources that RR.first is no longer available.
for (const std::pair<uint64_t, UniqueResourceState> &Res : Resources) {
ResourceState &Current = *Res.second.get();
if (!Current.isAResourceGroup() || Current.getResourceMask() == RR.first)
continue;
if (Current.containsResource(RR.first)) {
Current.markSubResourceAsUsed(RR.first);
Current.removeFromNextInSequence(RR.first);
}
}
}
void ResourceManager::release(ResourceRef RR) {
ResourceState &RS = *Resources[RR.first];
bool WasFullyUsed = !RS.isReady();
RS.releaseSubResource(RR.second);
if (!WasFullyUsed)
return;
for (const std::pair<uint64_t, UniqueResourceState> &Res : Resources) {
ResourceState &Current = *Res.second.get();
if (!Current.isAResourceGroup() || Current.getResourceMask() == RR.first)
continue;
if (Current.containsResource(RR.first))
Current.releaseSubResource(RR.first);
}
}
ResourceStateEvent
ResourceManager::canBeDispatched(ArrayRef<uint64_t> Buffers) const {
ResourceStateEvent Result = ResourceStateEvent::RS_BUFFER_AVAILABLE;
for (uint64_t Buffer : Buffers) {
Result = isBufferAvailable(Buffer);
if (Result != ResourceStateEvent::RS_BUFFER_AVAILABLE)
break;
}
return Result;
}
void ResourceManager::reserveBuffers(ArrayRef<uint64_t> Buffers) {
for (const uint64_t R : Buffers) {
reserveBuffer(R);
ResourceState &Resource = *Resources[R];
if (Resource.isADispatchHazard()) {
assert(!Resource.isReserved());
Resource.setReserved();
}
}
}
void ResourceManager::releaseBuffers(ArrayRef<uint64_t> Buffers) {
for (const uint64_t R : Buffers)
releaseBuffer(R);
}
bool ResourceManager::canBeIssued(const InstrDesc &Desc) const {
return std::all_of(Desc.Resources.begin(), Desc.Resources.end(),
[&](const std::pair<uint64_t, const ResourceUsage> &E) {
unsigned NumUnits =
E.second.isReserved() ? 0U : E.second.NumUnits;
return isReady(E.first, NumUnits);
});
}
// Returns true if all resources are in-order, and there is at least one
// resource which is a dispatch hazard (BufferSize = 0).
bool ResourceManager::mustIssueImmediately(const InstrDesc &Desc) {
if (!canBeIssued(Desc))
return false;
bool AllInOrderResources = all_of(Desc.Buffers, [&](uint64_t BufferMask) {
const ResourceState &Resource = *Resources[BufferMask];
return Resource.isInOrder() || Resource.isADispatchHazard();
});
if (!AllInOrderResources)
return false;
return any_of(Desc.Buffers, [&](uint64_t BufferMask) {
return Resources[BufferMask]->isADispatchHazard();
});
}
void ResourceManager::issueInstruction(
const InstrDesc &Desc,
SmallVectorImpl<std::pair<ResourceRef, double>> &Pipes) {
for (const std::pair<uint64_t, ResourceUsage> &R : Desc.Resources) {
const CycleSegment &CS = R.second.CS;
if (!CS.size()) {
releaseResource(R.first);
continue;
}
assert(CS.begin() == 0 && "Invalid {Start, End} cycles!");
if (!R.second.isReserved()) {
ResourceRef Pipe = selectPipe(R.first);
use(Pipe);
BusyResources[Pipe] += CS.size();
// Replace the resource mask with a valid processor resource index.
const ResourceState &RS = *Resources[Pipe.first];
Pipe.first = RS.getProcResourceID();
Pipes.emplace_back(
std::pair<ResourceRef, double>(Pipe, static_cast<double>(CS.size())));
} else {
assert((countPopulation(R.first) > 1) && "Expected a group!");
// Mark this group as reserved.
assert(R.second.isReserved());
reserveResource(R.first);
BusyResources[ResourceRef(R.first, R.first)] += CS.size();
}
}
}
void ResourceManager::cycleEvent(SmallVectorImpl<ResourceRef> &ResourcesFreed) {
for (std::pair<ResourceRef, unsigned> &BR : BusyResources) {
if (BR.second)
BR.second--;
if (!BR.second) {
// Release this resource.
const ResourceRef &RR = BR.first;
if (countPopulation(RR.first) == 1)
release(RR);
releaseResource(RR.first);
ResourcesFreed.push_back(RR);
}
}
for (const ResourceRef &RF : ResourcesFreed)
BusyResources.erase(RF);
}
#ifndef NDEBUG
void Scheduler::dump() const {
dbgs() << "[SCHEDULER]: WaitQueue size is: " << WaitQueue.size() << '\n';
dbgs() << "[SCHEDULER]: ReadyQueue size is: " << ReadyQueue.size() << '\n';
dbgs() << "[SCHEDULER]: IssuedQueue size is: " << IssuedQueue.size() << '\n';
Resources->dump();
}
#endif
bool Scheduler::canBeDispatched(const InstRef &IR,
HWStallEvent::GenericEventType &Event) const {
Event = HWStallEvent::Invalid;
const InstrDesc &Desc = IR.getInstruction()->getDesc();
if (Desc.MayLoad && LSU->isLQFull())
Event = HWStallEvent::LoadQueueFull;
else if (Desc.MayStore && LSU->isSQFull())
Event = HWStallEvent::StoreQueueFull;
else {
switch (Resources->canBeDispatched(Desc.Buffers)) {
default:
return true;
case ResourceStateEvent::RS_BUFFER_UNAVAILABLE:
Event = HWStallEvent::SchedulerQueueFull;
break;
case ResourceStateEvent::RS_RESERVED:
Event = HWStallEvent::DispatchGroupStall;
}
}
return false;
}
void Scheduler::issueInstructionImpl(
InstRef &IR,
SmallVectorImpl<std::pair<ResourceRef, double>> &UsedResources) {
Instruction *IS = IR.getInstruction();
const InstrDesc &D = IS->getDesc();
// Issue the instruction and collect all the consumed resources
// into a vector. That vector is then used to notify the listener.
Resources->issueInstruction(D, UsedResources);
// Notify the instruction that it started executing.
// This updates the internal state of each write.
IS->execute();
if (IS->isExecuting())
IssuedQueue[IR.getSourceIndex()] = IS;
}
// Release the buffered resources and issue the instruction.
void Scheduler::issueInstruction(
InstRef &IR,
SmallVectorImpl<std::pair<ResourceRef, double>> &UsedResources) {
const InstrDesc &Desc = IR.getInstruction()->getDesc();
releaseBuffers(Desc.Buffers);
issueInstructionImpl(IR, UsedResources);
}
void Scheduler::promoteToReadyQueue(SmallVectorImpl<InstRef> &Ready) {
// Scan the set of waiting instructions and promote them to the
// ready queue if operands are all ready.
for (auto I = WaitQueue.begin(), E = WaitQueue.end(); I != E;) {
const unsigned IID = I->first;
Instruction *IS = I->second;
// Check if this instruction is now ready. In case, force
// a transition in state using method 'update()'.
IS->update();
const InstrDesc &Desc = IS->getDesc();
bool IsMemOp = Desc.MayLoad || Desc.MayStore;
if (!IS->isReady() || (IsMemOp && !LSU->isReady({IID, IS}))) {
++I;
continue;
}
Ready.emplace_back(IID, IS);
ReadyQueue[IID] = IS;
auto ToRemove = I;
++I;
WaitQueue.erase(ToRemove);
}
}
InstRef Scheduler::select() {
// Give priority to older instructions in the ReadyQueue. Since the ready
// queue is ordered by key, this will always prioritize older instructions.
const auto It = std::find_if(ReadyQueue.begin(), ReadyQueue.end(),
[&](const QueueEntryTy &Entry) {
const InstrDesc &D = Entry.second->getDesc();
return Resources->canBeIssued(D);
});
if (It == ReadyQueue.end())
return {0, nullptr};
// We found an instruction to issue.
InstRef IR(It->first, It->second);
ReadyQueue.erase(It);
return IR;
}
void Scheduler::updatePendingQueue(SmallVectorImpl<InstRef> &Ready) {
// Notify to instructions in the pending queue that a new cycle just
// started.
for (QueueEntryTy Entry : WaitQueue)
Entry.second->cycleEvent();
promoteToReadyQueue(Ready);
}
void Scheduler::updateIssuedQueue(SmallVectorImpl<InstRef> &Executed) {
for (auto I = IssuedQueue.begin(), E = IssuedQueue.end(); I != E;) {
const QueueEntryTy Entry = *I;
Instruction *IS = Entry.second;
IS->cycleEvent();
if (IS->isExecuted()) {
Executed.push_back({Entry.first, Entry.second});
auto ToRemove = I;
++I;
IssuedQueue.erase(ToRemove);
} else {
LLVM_DEBUG(dbgs() << "[SCHEDULER]: Instruction " << Entry.first
<< " is still executing.\n");
++I;
}
}
}
void Scheduler::onInstructionExecuted(const InstRef &IR) {
LSU->onInstructionExecuted(IR);
}
void Scheduler::reclaimSimulatedResources(SmallVectorImpl<ResourceRef> &Freed) {
Resources->cycleEvent(Freed);
}
bool Scheduler::reserveResources(InstRef &IR) {
// If necessary, reserve queue entries in the load-store unit (LSU).
const bool Reserved = LSU->reserve(IR);
if (!IR.getInstruction()->isReady() || (Reserved && !LSU->isReady(IR))) {
LLVM_DEBUG(dbgs() << "[SCHEDULER] Adding " << IR << " to the Wait Queue\n");
WaitQueue[IR.getSourceIndex()] = IR.getInstruction();
return false;
}
return true;
}
bool Scheduler::issueImmediately(InstRef &IR) {
const InstrDesc &Desc = IR.getInstruction()->getDesc();
if (!Desc.isZeroLatency() && !Resources->mustIssueImmediately(Desc)) {
LLVM_DEBUG(dbgs() << "[SCHEDULER] Adding " << IR
<< " to the Ready Queue\n");
ReadyQueue[IR.getSourceIndex()] = IR.getInstruction();
return false;
}
return true;
}
} // namespace mca
| 32.886305 | 80 | 0.656085 | APFDev |
ebf6f7382807ed1f1b6d9b7c3f094ef1253c0120 | 225,178 | cpp | C++ | bench/ml2cpp-demo/BaggingClassifier/FourClass_100/ml2cpp-demo_BaggingClassifier_FourClass_100.cpp | antoinecarme/ml2cpp | 2b241d44de00eafda620c2b605690276faf5f8fb | [
"BSD-3-Clause"
] | null | null | null | bench/ml2cpp-demo/BaggingClassifier/FourClass_100/ml2cpp-demo_BaggingClassifier_FourClass_100.cpp | antoinecarme/ml2cpp | 2b241d44de00eafda620c2b605690276faf5f8fb | [
"BSD-3-Clause"
] | 33 | 2020-09-13T09:55:01.000Z | 2022-01-06T11:53:55.000Z | bench/ml2cpp-demo/BaggingClassifier/FourClass_100/ml2cpp-demo_BaggingClassifier_FourClass_100.cpp | antoinecarme/ml2cpp | 2b241d44de00eafda620c2b605690276faf5f8fb | [
"BSD-3-Clause"
] | 1 | 2021-01-26T14:41:58.000Z | 2021-01-26T14:41:58.000Z | // ********************************************************
// This C++ code was automatically generated by ml2cpp (development version).
// Copyright 2020
// https://github.com/antoinecarme/ml2cpp
// Model : BaggingClassifier
// Dataset : FourClass_100
// This CPP code can be compiled using any C++-17 compiler.
// g++ -Wall -Wno-unused-function -std=c++17 -g -o ml2cpp-demo_BaggingClassifier_FourClass_100.exe ml2cpp-demo_BaggingClassifier_FourClass_100.cpp
// Model deployment code
// ********************************************************
#include "../../Generic.i"
namespace {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2, 3 };
return lClasses;
}
namespace SubModel_0 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2, 3 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 3 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 7 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 8 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 11 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 12 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 13 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 17 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 18 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 20 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 21 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 23 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 25 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 26 , {0.0, 0.0, 0.0, 1.0 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
int lNodeIndex = (Feature_44 <= -2.1092634201049805) ? ( (Feature_62 <= 1.503589004278183) ? ( 2 ) : ( 3 ) ) : ( (Feature_19 <= -0.5789696276187897) ? ( (Feature_78 <= -0.6031690239906311) ? ( (Feature_56 <= -8.097998857498169) ? ( 7 ) : ( 8 ) ) : ( (Feature_42 <= -0.2146744355559349) ? ( (Feature_90 <= 1.5686895251274109) ? ( 11 ) : ( 12 ) ) : ( 13 ) ) ) : ( (Feature_99 <= 0.00624384731054306) ? ( (Feature_44 <= -0.7715538442134857) ? ( (Feature_53 <= -1.3674404621124268) ? ( 17 ) : ( 18 ) ) : ( (Feature_89 <= -1.1485321521759033) ? ( 20 ) : ( 21 ) ) ) : ( (Feature_11 <= 0.45316772162914276) ? ( 23 ) : ( (Feature_50 <= -0.7742524668574333) ? ( 25 ) : ( 26 ) ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2", "Score_3",
"Proba_0", "Proba_1", "Proba_2", "Proba_3",
"LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
std::any(),
std::any(),
std::any(),
std::any()
} ;
lTable["Proba"] = {
lNodeValue [ 0 ],
lNodeValue [ 1 ],
lNodeValue [ 2 ],
lNodeValue [ 3 ]
} ;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]);
return lTable;
}
} // eof namespace SubModel_0
namespace SubModel_1 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2, 3 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 1 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 6 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 7 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 9 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 10 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 12 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 14 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 15 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 19 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 20 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 21 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 23 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 24 , {0.0, 0.0, 0.0, 1.0 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
int lNodeIndex = (Feature_44 <= -2.1092634201049805) ? ( 1 ) : ( (Feature_33 <= -0.08118173107504845) ? ( (Feature_41 <= 0.6967471539974213) ? ( (Feature_16 <= -0.818017452955246) ? ( (Feature_41 <= -0.07286195456981659) ? ( 6 ) : ( 7 ) ) : ( (Feature_41 <= -2.0635533332824707) ? ( 9 ) : ( 10 ) ) ) : ( (Feature_78 <= 1.29881152510643) ? ( 12 ) : ( (Feature_14 <= -0.16014254093170166) ? ( 14 ) : ( 15 ) ) ) ) : ( (Feature_46 <= 0.3926301449537277) ? ( (Feature_48 <= -0.17612321954220533) ? ( (Feature_30 <= -0.8991427272558212) ? ( 19 ) : ( 20 ) ) : ( 21 ) ) : ( (Feature_11 <= -1.096106618642807) ? ( 23 ) : ( 24 ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2", "Score_3",
"Proba_0", "Proba_1", "Proba_2", "Proba_3",
"LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
std::any(),
std::any(),
std::any(),
std::any()
} ;
lTable["Proba"] = {
lNodeValue [ 0 ],
lNodeValue [ 1 ],
lNodeValue [ 2 ],
lNodeValue [ 3 ]
} ;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]);
return lTable;
}
} // eof namespace SubModel_1
namespace SubModel_2 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2, 3 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 4 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 5 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 8 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 9 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 10 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 11 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 16 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 17 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 18 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 21 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 22 , {0.5, 0.0, 0.0, 0.5 }} ,
{ 23 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 24 , {1.0, 0.0, 0.0, 0.0 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
int lNodeIndex = (Feature_99 <= -0.09796052239835262) ? ( (Feature_78 <= 1.7039188742637634) ? ( (Feature_89 <= -0.5055654942989349) ? ( (Feature_54 <= 0.032076217234134674) ? ( 4 ) : ( 5 ) ) : ( (Feature_59 <= -0.3915305733680725) ? ( (Feature_94 <= -0.7241016756743193) ? ( 8 ) : ( 9 ) ) : ( 10 ) ) ) : ( 11 ) ) : ( (Feature_24 <= 0.5892128348350525) ? ( (Feature_45 <= 0.11031141877174377) ? ( (Feature_38 <= -0.8665039539337158) ? ( (Feature_60 <= -0.029639005661010742) ? ( 16 ) : ( 17 ) ) : ( 18 ) ) : ( (Feature_24 <= -0.6491396576166153) ? ( (Feature_69 <= -0.3395440876483917) ? ( 21 ) : ( 22 ) ) : ( 23 ) ) ) : ( 24 ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2", "Score_3",
"Proba_0", "Proba_1", "Proba_2", "Proba_3",
"LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
std::any(),
std::any(),
std::any(),
std::any()
} ;
lTable["Proba"] = {
lNodeValue [ 0 ],
lNodeValue [ 1 ],
lNodeValue [ 2 ],
lNodeValue [ 3 ]
} ;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]);
return lTable;
}
} // eof namespace SubModel_2
namespace SubModel_3 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2, 3 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 1 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 6 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 7 , {0.08, 0.44, 0.32, 0.16 }} ,
{ 9 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 10 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 13 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 14 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 15 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 17 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 18 , {1.0, 0.0, 0.0, 0.0 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
int lNodeIndex = (Feature_44 <= -2.2519255876541138) ? ( 1 ) : ( (Feature_92 <= 0.8728378117084503) ? ( (Feature_78 <= 0.8840557038784027) ? ( (Feature_41 <= 0.37245966494083405) ? ( (Feature_70 <= -0.36322344839572906) ? ( 6 ) : ( 7 ) ) : ( (Feature_7 <= 1.2444062232971191) ? ( 9 ) : ( 10 ) ) ) : ( (Feature_14 <= -0.3580637127161026) ? ( (Feature_40 <= 1.0264981649816036) ? ( 13 ) : ( 14 ) ) : ( 15 ) ) ) : ( (Feature_79 <= 1.8128423690795898) ? ( 17 ) : ( 18 ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2", "Score_3",
"Proba_0", "Proba_1", "Proba_2", "Proba_3",
"LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
std::any(),
std::any(),
std::any(),
std::any()
} ;
lTable["Proba"] = {
lNodeValue [ 0 ],
lNodeValue [ 1 ],
lNodeValue [ 2 ],
lNodeValue [ 3 ]
} ;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]);
return lTable;
}
} // eof namespace SubModel_3
namespace SubModel_4 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2, 3 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 4 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 6 , {0.0, 0.5, 0.5, 0.0 }} ,
{ 7 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 8 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 11 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 12 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 14 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 15 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 19 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 20 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 22 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 23 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 25 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 26 , {0.0, 0.0, 0.0, 1.0 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
int lNodeIndex = (Feature_78 <= -0.6542530655860901) ? ( (Feature_44 <= 0.2128865383565426) ? ( (Feature_99 <= -1.187854915857315) ? ( (Feature_6 <= 0.2931538235861808) ? ( 4 ) : ( (Feature_50 <= -0.677160769701004) ? ( 6 ) : ( 7 ) ) ) : ( 8 ) ) : ( (Feature_9 <= 0.727972537279129) ? ( (Feature_74 <= 1.5878617763519287) ? ( 11 ) : ( 12 ) ) : ( (Feature_7 <= -0.2916768416762352) ? ( 14 ) : ( 15 ) ) ) ) : ( (Feature_19 <= -0.08902734890580177) ? ( (Feature_32 <= 0.42078158259391785) ? ( (Feature_49 <= -2.1161219477653503) ? ( 19 ) : ( 20 ) ) : ( (Feature_43 <= 0.031263142824172974) ? ( 22 ) : ( 23 ) ) ) : ( (Feature_28 <= 1.1810160875320435) ? ( 25 ) : ( 26 ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2", "Score_3",
"Proba_0", "Proba_1", "Proba_2", "Proba_3",
"LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
std::any(),
std::any(),
std::any(),
std::any()
} ;
lTable["Proba"] = {
lNodeValue [ 0 ],
lNodeValue [ 1 ],
lNodeValue [ 2 ],
lNodeValue [ 3 ]
} ;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]);
return lTable;
}
} // eof namespace SubModel_4
namespace SubModel_5 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2, 3 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 4 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 6 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 7 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 11 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 12 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 15 , {0.6666666666666666, 0.0, 0.3333333333333333, 0.0 }} ,
{ 16 , {0.0, 0.05263157894736842, 0.0, 0.9473684210526315 }} ,
{ 17 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 21 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 22 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 23 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 25 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 26 , {0.0, 0.0, 1.0, 0.0 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
int lNodeIndex = (Feature_44 <= -1.309776484966278) ? ( (Feature_99 <= -2.194583535194397) ? ( 2 ) : ( (Feature_45 <= 0.1697009578347206) ? ( 4 ) : ( (Feature_76 <= -0.5688562635332346) ? ( 6 ) : ( 7 ) ) ) ) : ( (Feature_94 <= -0.33069832623004913) ? ( (Feature_38 <= -0.7251038551330566) ? ( (Feature_53 <= -3.49560284614563) ? ( 11 ) : ( 12 ) ) : ( (Feature_5 <= 0.5689798295497894) ? ( (Feature_73 <= -0.648361474275589) ? ( 15 ) : ( 16 ) ) : ( 17 ) ) ) : ( (Feature_24 <= 0.4838130474090576) ? ( (Feature_16 <= -0.5087056756019592) ? ( (Feature_76 <= -0.5111970640718937) ? ( 21 ) : ( 22 ) ) : ( 23 ) ) : ( (Feature_91 <= -0.035808783024549484) ? ( 25 ) : ( 26 ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2", "Score_3",
"Proba_0", "Proba_1", "Proba_2", "Proba_3",
"LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
std::any(),
std::any(),
std::any(),
std::any()
} ;
lTable["Proba"] = {
lNodeValue [ 0 ],
lNodeValue [ 1 ],
lNodeValue [ 2 ],
lNodeValue [ 3 ]
} ;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]);
return lTable;
}
} // eof namespace SubModel_5
namespace SubModel_6 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2, 3 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 3 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 4 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 8 , {0.9130434782608695, 0.043478260869565216, 0.043478260869565216, 0.0 }} ,
{ 9 , {0.0, 0.16666666666666666, 0.16666666666666666, 0.6666666666666666 }} ,
{ 11 , {0.1111111111111111, 0.8333333333333334, 0.0, 0.05555555555555555 }} ,
{ 12 , {0.3333333333333333, 0.0, 0.0, 0.6666666666666666 }} ,
{ 15 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 16 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 18 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 19 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 20 , {0.0, 1.0, 0.0, 0.0 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
int lNodeIndex = (Feature_73 <= 1.6641205549240112) ? ( (Feature_44 <= -2.1092634201049805) ? ( (Feature_63 <= -1.0751223862171173) ? ( 3 ) : ( 4 ) ) : ( (Feature_14 <= 1.0025184750556946) ? ( (Feature_45 <= 0.25321291387081146) ? ( (Feature_20 <= 0.688479095697403) ? ( 8 ) : ( 9 ) ) : ( (Feature_32 <= 0.28152644634246826) ? ( 11 ) : ( 12 ) ) ) : ( (Feature_99 <= -0.3237369656562805) ? ( (Feature_27 <= 0.9087257087230682) ? ( 15 ) : ( 16 ) ) : ( (Feature_38 <= -0.6264585703611374) ? ( 18 ) : ( 19 ) ) ) ) ) : ( 20 );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2", "Score_3",
"Proba_0", "Proba_1", "Proba_2", "Proba_3",
"LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
std::any(),
std::any(),
std::any(),
std::any()
} ;
lTable["Proba"] = {
lNodeValue [ 0 ],
lNodeValue [ 1 ],
lNodeValue [ 2 ],
lNodeValue [ 3 ]
} ;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]);
return lTable;
}
} // eof namespace SubModel_6
namespace SubModel_7 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2, 3 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 3 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 7 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 8 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 10 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 12 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 13 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 16 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 18 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 19 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 22 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 23 , {0.0, 0.5, 0.0, 0.5 }} ,
{ 25 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 26 , {0.07692307692307693, 0.3076923076923077, 0.5384615384615384, 0.07692307692307693 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
int lNodeIndex = (Feature_44 <= -2.1092634201049805) ? ( (Feature_66 <= 1.6641189455986023) ? ( 2 ) : ( 3 ) ) : ( (Feature_44 <= -0.49318933486938477) ? ( (Feature_68 <= -0.910584956407547) ? ( (Feature_39 <= 0.012014441192150116) ? ( 7 ) : ( 8 ) ) : ( (Feature_32 <= -1.8123965859413147) ? ( 10 ) : ( (Feature_11 <= 1.5604674816131592) ? ( 12 ) : ( 13 ) ) ) ) : ( (Feature_99 <= -0.3237369656562805) ? ( (Feature_47 <= 0.7225238382816315) ? ( 16 ) : ( (Feature_93 <= -1.1102982759475708) ? ( 18 ) : ( 19 ) ) ) : ( (Feature_29 <= -1.114558756351471) ? ( (Feature_0 <= 0.44958434998989105) ? ( 22 ) : ( 23 ) ) : ( (Feature_30 <= -0.5763616859912872) ? ( 25 ) : ( 26 ) ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2", "Score_3",
"Proba_0", "Proba_1", "Proba_2", "Proba_3",
"LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
std::any(),
std::any(),
std::any(),
std::any()
} ;
lTable["Proba"] = {
lNodeValue [ 0 ],
lNodeValue [ 1 ],
lNodeValue [ 2 ],
lNodeValue [ 3 ]
} ;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]);
return lTable;
}
} // eof namespace SubModel_7
namespace SubModel_8 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2, 3 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 3 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 6 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 8 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 10 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 11 , {0.5, 0.0, 0.0, 0.5 }} ,
{ 14 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 15 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 18 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 19 , {0.9285714285714286, 0.03571428571428571, 0.03571428571428571, 0.0 }} ,
{ 21 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 22 , {0.0, 0.0, 0.0, 1.0 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
int lNodeIndex = (Feature_44 <= -2.1092634201049805) ? ( (Feature_30 <= 0.7127983272075653) ? ( 2 ) : ( 3 ) ) : ( (Feature_78 <= -0.8434274196624756) ? ( (Feature_99 <= -0.5882234573364258) ? ( 6 ) : ( (Feature_19 <= -0.8192912638187408) ? ( 8 ) : ( (Feature_1 <= 0.6547807157039642) ? ( 10 ) : ( 11 ) ) ) ) : ( (Feature_43 <= -0.7006235718727112) ? ( (Feature_91 <= -0.12150455266237259) ? ( 14 ) : ( 15 ) ) : ( (Feature_27 <= 3.23024845123291) ? ( (Feature_81 <= -1.4423141479492188) ? ( 18 ) : ( 19 ) ) : ( (Feature_20 <= 0.9908088445663452) ? ( 21 ) : ( 22 ) ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2", "Score_3",
"Proba_0", "Proba_1", "Proba_2", "Proba_3",
"LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
std::any(),
std::any(),
std::any(),
std::any()
} ;
lTable["Proba"] = {
lNodeValue [ 0 ],
lNodeValue [ 1 ],
lNodeValue [ 2 ],
lNodeValue [ 3 ]
} ;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]);
return lTable;
}
} // eof namespace SubModel_8
namespace SubModel_9 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2, 3 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 3 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 8 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 9 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 11 , {0.0, 0.0, 0.3333333333333333, 0.6666666666666666 }} ,
{ 12 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 13 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 15 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 18 , {0.0, 0.037037037037037035, 0.07407407407407407, 0.8888888888888888 }} ,
{ 19 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 21 , {0.5, 0.5, 0.0, 0.0 }} ,
{ 22 , {0.0, 0.0, 1.0, 0.0 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
int lNodeIndex = (Feature_44 <= -2.1092634201049805) ? ( (Feature_48 <= 1.2093676924705505) ? ( 2 ) : ( 3 ) ) : ( (Feature_29 <= -0.10024451464414597) ? ( (Feature_24 <= 0.3782288730144501) ? ( (Feature_49 <= 0.33082690834999084) ? ( (Feature_85 <= 1.473156750202179) ? ( 8 ) : ( 9 ) ) : ( (Feature_72 <= 0.03332477807998657) ? ( 11 ) : ( 12 ) ) ) : ( 13 ) ) : ( (Feature_28 <= -1.3160618543624878) ? ( 15 ) : ( (Feature_71 <= 0.7019776701927185) ? ( (Feature_93 <= 1.258106768131256) ? ( 18 ) : ( 19 ) ) : ( (Feature_77 <= -0.0934767834842205) ? ( 21 ) : ( 22 ) ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2", "Score_3",
"Proba_0", "Proba_1", "Proba_2", "Proba_3",
"LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
std::any(),
std::any(),
std::any(),
std::any()
} ;
lTable["Proba"] = {
lNodeValue [ 0 ],
lNodeValue [ 1 ],
lNodeValue [ 2 ],
lNodeValue [ 3 ]
} ;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]);
return lTable;
}
} // eof namespace SubModel_9
namespace SubModel_10 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2, 3 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 5 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 6 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 8 , {0.5, 0.5, 0.0, 0.0 }} ,
{ 9 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 12 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 13 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 14 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 17 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 18 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 21 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 22 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 24 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 25 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 27 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 28 , {0.0, 0.0, 0.0, 1.0 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
int lNodeIndex = (Feature_44 <= 2.0125714540481567) ? ( (Feature_56 <= 0.6710653007030487) ? ( (Feature_10 <= 0.4213555306196213) ? ( (Feature_91 <= -0.9002590477466583) ? ( (Feature_61 <= 2.485666036605835) ? ( 5 ) : ( 6 ) ) : ( (Feature_40 <= -1.0761661529541016) ? ( 8 ) : ( 9 ) ) ) : ( (Feature_4 <= 0.049746282398700714) ? ( (Feature_36 <= 0.48682308197021484) ? ( 12 ) : ( 13 ) ) : ( 14 ) ) ) : ( (Feature_12 <= -0.7289259433746338) ? ( (Feature_36 <= 0.3711119145154953) ? ( 17 ) : ( 18 ) ) : ( (Feature_29 <= 0.9479873329401016) ? ( (Feature_78 <= 4.133114576339722) ? ( 21 ) : ( 22 ) ) : ( (Feature_91 <= 0.15714242216199636) ? ( 24 ) : ( 25 ) ) ) ) ) : ( (Feature_1 <= -0.5874605476856232) ? ( 27 ) : ( 28 ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2", "Score_3",
"Proba_0", "Proba_1", "Proba_2", "Proba_3",
"LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
std::any(),
std::any(),
std::any(),
std::any()
} ;
lTable["Proba"] = {
lNodeValue [ 0 ],
lNodeValue [ 1 ],
lNodeValue [ 2 ],
lNodeValue [ 3 ]
} ;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]);
return lTable;
}
} // eof namespace SubModel_10
namespace SubModel_11 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2, 3 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 3 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 8 , {0.7142857142857143, 0.14285714285714285, 0.0, 0.14285714285714285 }} ,
{ 9 , {0.0, 0.7741935483870968, 0.0967741935483871, 0.12903225806451613 }} ,
{ 11 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 12 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 14 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 15 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 16 , {0.0, 0.0, 0.0, 1.0 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
int lNodeIndex = (Feature_44 <= -2.1092634201049805) ? ( (Feature_48 <= 0.9457052946090698) ? ( 2 ) : ( 3 ) ) : ( (Feature_20 <= 1.2383397221565247) ? ( (Feature_24 <= 0.5572461783885956) ? ( (Feature_71 <= 0.8951122760772705) ? ( (Feature_65 <= -1.0845131874084473) ? ( 8 ) : ( 9 ) ) : ( (Feature_1 <= 0.8677243292331696) ? ( 11 ) : ( 12 ) ) ) : ( (Feature_38 <= 0.7453548833727837) ? ( 14 ) : ( 15 ) ) ) : ( 16 ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2", "Score_3",
"Proba_0", "Proba_1", "Proba_2", "Proba_3",
"LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
std::any(),
std::any(),
std::any(),
std::any()
} ;
lTable["Proba"] = {
lNodeValue [ 0 ],
lNodeValue [ 1 ],
lNodeValue [ 2 ],
lNodeValue [ 3 ]
} ;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]);
return lTable;
}
} // eof namespace SubModel_11
namespace SubModel_12 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2, 3 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 4 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 6 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 7 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 9 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 10 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 12 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 14 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 15 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 18 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 20 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 21 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 24 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 25 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 28 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 29 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 31 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 32 , {0.0, 0.0, 0.6, 0.4 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
int lNodeIndex = (Feature_78 <= -0.6111561059951782) ? ( (Feature_44 <= 1.6692100763320923) ? ( (Feature_15 <= 0.9708277881145477) ? ( (Feature_94 <= -1.621713638305664) ? ( 4 ) : ( (Feature_27 <= -2.2659579515457153) ? ( 6 ) : ( 7 ) ) ) : ( (Feature_75 <= 0.3124377280473709) ? ( 9 ) : ( 10 ) ) ) : ( (Feature_99 <= -0.3222829457372427) ? ( 12 ) : ( (Feature_0 <= 0.4392481744289398) ? ( 14 ) : ( 15 ) ) ) ) : ( (Feature_33 <= -0.31368252635002136) ? ( (Feature_67 <= 1.2143447399139404) ? ( 18 ) : ( (Feature_45 <= 0.17234395071864128) ? ( 20 ) : ( 21 ) ) ) : ( (Feature_38 <= -0.8088268935680389) ? ( (Feature_91 <= -0.5887814164161682) ? ( 24 ) : ( 25 ) ) : ( (Feature_88 <= 0.273276109714061) ? ( (Feature_51 <= -3.0600167512893677) ? ( 28 ) : ( 29 ) ) : ( (Feature_72 <= -0.6026551425457001) ? ( 31 ) : ( 32 ) ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2", "Score_3",
"Proba_0", "Proba_1", "Proba_2", "Proba_3",
"LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
std::any(),
std::any(),
std::any(),
std::any()
} ;
lTable["Proba"] = {
lNodeValue [ 0 ],
lNodeValue [ 1 ],
lNodeValue [ 2 ],
lNodeValue [ 3 ]
} ;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]);
return lTable;
}
} // eof namespace SubModel_12
namespace SubModel_13 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2, 3 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 3 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 7 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 8 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 11 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 12 , {0.4, 0.6, 0.0, 0.0 }} ,
{ 13 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 17 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 18 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 20 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 21 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 24 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 25 , {0.0, 0.8, 0.0, 0.2 }} ,
{ 26 , {1.0, 0.0, 0.0, 0.0 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
int lNodeIndex = (Feature_44 <= -2.1092634201049805) ? ( (Feature_99 <= -2.194583535194397) ? ( 2 ) : ( 3 ) ) : ( (Feature_20 <= -0.08544048853218555) ? ( (Feature_92 <= 0.16372115537524223) ? ( (Feature_41 <= 1.1139306724071503) ? ( 7 ) : ( 8 ) ) : ( (Feature_22 <= 0.12712760269641876) ? ( (Feature_83 <= 0.04717770963907242) ? ( 11 ) : ( 12 ) ) : ( 13 ) ) ) : ( (Feature_19 <= -0.5648867189884186) ? ( (Feature_68 <= -0.43200263381004333) ? ( (Feature_23 <= 0.18997395038604736) ? ( 17 ) : ( 18 ) ) : ( (Feature_6 <= 1.6022411584854126) ? ( 20 ) : ( 21 ) ) ) : ( (Feature_78 <= 1.8294076323509216) ? ( (Feature_94 <= 0.11547934566624463) ? ( 24 ) : ( 25 ) ) : ( 26 ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2", "Score_3",
"Proba_0", "Proba_1", "Proba_2", "Proba_3",
"LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
std::any(),
std::any(),
std::any(),
std::any()
} ;
lTable["Proba"] = {
lNodeValue [ 0 ],
lNodeValue [ 1 ],
lNodeValue [ 2 ],
lNodeValue [ 3 ]
} ;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]);
return lTable;
}
} // eof namespace SubModel_13
namespace SubModel_14 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2, 3 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 4 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 5 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 8 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 9 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 10 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 13 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 14 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 15 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 18 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 20 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 21 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 23 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 26 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 27 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 29 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 30 , {0.0, 1.0, 0.0, 0.0 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
int lNodeIndex = (Feature_78 <= -0.5283965766429901) ? ( (Feature_10 <= 0.3236100971698761) ? ( (Feature_44 <= -0.010307437914889306) ? ( (Feature_51 <= -2.8441089391708374) ? ( 4 ) : ( 5 ) ) : ( (Feature_10 <= -0.5565105974674225) ? ( (Feature_90 <= 0.7287018746137619) ? ( 8 ) : ( 9 ) ) : ( 10 ) ) ) : ( (Feature_84 <= -1.0485740900039673) ? ( (Feature_85 <= 0.9519887706264853) ? ( 13 ) : ( 14 ) ) : ( 15 ) ) ) : ( (Feature_72 <= -0.9955059289932251) ? ( (Feature_50 <= -0.025953032076358795) ? ( 18 ) : ( (Feature_70 <= 1.5127062797546387) ? ( 20 ) : ( 21 ) ) ) : ( (Feature_68 <= -1.1216784715652466) ? ( 23 ) : ( (Feature_63 <= 1.0354410409927368) ? ( (Feature_24 <= -1.6794065833091736) ? ( 26 ) : ( 27 ) ) : ( (Feature_42 <= -0.2587735503911972) ? ( 29 ) : ( 30 ) ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2", "Score_3",
"Proba_0", "Proba_1", "Proba_2", "Proba_3",
"LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
std::any(),
std::any(),
std::any(),
std::any()
} ;
lTable["Proba"] = {
lNodeValue [ 0 ],
lNodeValue [ 1 ],
lNodeValue [ 2 ],
lNodeValue [ 3 ]
} ;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]);
return lTable;
}
} // eof namespace SubModel_14
namespace SubModel_15 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2, 3 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 3 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 7 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 8 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 10 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 12 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 13 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 15 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 18 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 19 , {0.3333333333333333, 0.0, 0.5, 0.16666666666666666 }} ,
{ 21 , {0.0, 0.0, 0.038461538461538464, 0.9615384615384616 }} ,
{ 22 , {0.5, 0.5, 0.0, 0.0 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
int lNodeIndex = (Feature_44 <= -2.0734068751335144) ? ( (Feature_48 <= 0.9457052946090698) ? ( 2 ) : ( 3 ) ) : ( (Feature_29 <= 0.022716662992024794) ? ( (Feature_9 <= -0.41657423973083496) ? ( (Feature_96 <= 1.575301468372345) ? ( 7 ) : ( 8 ) ) : ( (Feature_50 <= -1.501459538936615) ? ( 10 ) : ( (Feature_90 <= 0.12944400310516357) ? ( 12 ) : ( 13 ) ) ) ) : ( (Feature_8 <= -1.0347691178321838) ? ( 15 ) : ( (Feature_56 <= -3.686617374420166) ? ( (Feature_18 <= -0.11845160275697708) ? ( 18 ) : ( 19 ) ) : ( (Feature_88 <= 1.3707586526870728) ? ( 21 ) : ( 22 ) ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2", "Score_3",
"Proba_0", "Proba_1", "Proba_2", "Proba_3",
"LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
std::any(),
std::any(),
std::any(),
std::any()
} ;
lTable["Proba"] = {
lNodeValue [ 0 ],
lNodeValue [ 1 ],
lNodeValue [ 2 ],
lNodeValue [ 3 ]
} ;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]);
return lTable;
}
} // eof namespace SubModel_15
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2", "Score_3",
"Proba_0", "Proba_1", "Proba_2", "Proba_3",
"LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
auto lClasses = get_classes();
std::vector<tTable> lTreeScores = {
SubModel_0::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99),
SubModel_1::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99),
SubModel_2::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99),
SubModel_3::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99),
SubModel_4::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99),
SubModel_5::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99),
SubModel_6::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99),
SubModel_7::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99),
SubModel_8::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99),
SubModel_9::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99),
SubModel_10::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99),
SubModel_11::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99),
SubModel_12::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99),
SubModel_13::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99),
SubModel_14::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99),
SubModel_15::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99)
};
tTable lAggregatedTable = aggregate_bag_scores(lTreeScores, {"Proba", "Score"});
tTable lTable = lAggregatedTable;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]);
return lTable;
}
} // eof namespace
int main() {
score_csv_file("outputs/ml2cpp-demo/datasets/FourClass_100.csv");
return 0;
}
| 146.695765 | 2,839 | 0.70979 | antoinecarme |
ebf8fca698458856c4deef95982dd656690d4c50 | 1,682 | cc | C++ | gcc-gcc-7_3_0-release/libstdc++-v3/testsuite/20_util/any/cons/nontrivial.cc | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | 7 | 2020-05-02T17:34:05.000Z | 2021-10-17T10:15:18.000Z | gcc-gcc-7_3_0-release/libstdc++-v3/testsuite/20_util/any/cons/nontrivial.cc | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | null | null | null | gcc-gcc-7_3_0-release/libstdc++-v3/testsuite/20_util/any/cons/nontrivial.cc | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | 2 | 2020-07-27T00:22:36.000Z | 2021-04-01T09:41:02.000Z | // Copyright (C) 2015-2017 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// { dg-options "-std=gnu++17" }
#include <any>
#include <testsuite_hooks.h>
struct LocationAware
{
LocationAware() { }
~LocationAware() { VERIFY(self == this); }
LocationAware(const LocationAware&) { }
LocationAware& operator=(const LocationAware&) { return *this; }
LocationAware(LocationAware&&) noexcept { }
LocationAware& operator=(LocationAware&&) noexcept { return *this; }
void* const self = this;
};
static_assert(std::is_nothrow_move_constructible<LocationAware>::value, "");
static_assert(!std::is_trivially_copyable<LocationAware>::value, "");
using std::any;
void
test01()
{
LocationAware l;
any a = l;
}
void
test02()
{
LocationAware l;
any a = l;
any b = a;
{
any tmp = std::move(a);
a = std::move(b);
b = std::move(tmp);
}
}
void
test03()
{
LocationAware l;
any a = l;
any b = a;
swap(a, b);
}
int
main()
{
test01();
test02();
test03();
}
| 22.131579 | 76 | 0.684304 | best08618 |
ebfc3837e61270fc86a6705696fee9076f62daf0 | 4,722 | cpp | C++ | libs/vgc/widgets/font.cpp | wookay/vgc | 21ec9f207219f43ed89c43f37b623d60a2bbb8cc | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | libs/vgc/widgets/font.cpp | wookay/vgc | 21ec9f207219f43ed89c43f37b623d60a2bbb8cc | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | libs/vgc/widgets/font.cpp | wookay/vgc | 21ec9f207219f43ed89c43f37b623d60a2bbb8cc | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2021-02-22T01:16:38.000Z | 2021-02-22T01:16:38.000Z | // Copyright 2020 The VGC Developers
// See the COPYRIGHT file at the top-level directory of this distribution
// and at https://github.com/vgc/vgc/blob/master/COPYRIGHT
//
// 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 <vgc/widgets/font.h>
#include <iostream>
#include <QFontDatabase>
#include <vgc/core/logging.h>
#include <vgc/core/paths.h>
#include <vgc/widgets/qtutil.h>
namespace vgc {
namespace widgets {
void addDefaultApplicationFonts()
{
const bool printFontInfo = false;
std::vector<std::pair<std::string, std::string>> fontNames {
{"SourceCodePro", "Black"},
{"SourceCodePro", "BlackIt"},
{"SourceCodePro", "Bold"},
{"SourceCodePro", "BoldIt"},
{"SourceCodePro", "ExtraLight"},
{"SourceCodePro", "ExtraLightIt"},
{"SourceCodePro", "It"},
{"SourceCodePro", "Light"},
{"SourceCodePro", "LightIt"},
{"SourceCodePro", "Medium"},
{"SourceCodePro", "MediumIt"},
{"SourceCodePro", "Regular"},
{"SourceCodePro", "Semibold"},
{"SourceCodePro", "SemiboldIt"},
{"SourceSansPro", "Black"},
{"SourceSansPro", "BlackIt"},
{"SourceSansPro", "Bold"},
{"SourceSansPro", "BoldIt"},
{"SourceSansPro", "ExtraLight"},
{"SourceSansPro", "ExtraLightIt"},
{"SourceSansPro", "It"},
{"SourceSansPro", "Light"},
{"SourceSansPro", "LightIt"},
{"SourceSansPro", "Regular"},
{"SourceSansPro", "Semibold"},
{"SourceSansPro", "SemiboldIt"},
};
for (const auto& name : fontNames) {
std::string fontExtension = ".ttf";
std::string fontSubFolder = "/TTF/";
std::string filename = name.first + "-" + name.second + fontExtension;
std::string filepath = "widgets/fonts/" + name.first + fontSubFolder + filename;
int id = widgets::addApplicationFont(filepath);
if (id == -1) {
core::warning() << "Failed to add font \"" + filepath + "\".\n";
}
else {
if (printFontInfo) {
std::cout << "Added font file: " + filepath + "\n";
}
}
}
if (printFontInfo) {
widgets::printFontFamilyInfo("Source Sans Pro");
widgets::printFontFamilyInfo("Source Code Pro");
}
}
int addApplicationFont(const std::string& name)
{
std::string fontPath = core::resourcePath(name);
int id = QFontDatabase::addApplicationFont(toQt(fontPath));
return id;
}
void printFontFamilyInfo(const std::string& family)
{
QFontDatabase fd;
std::cout << "Font Family: " << family << "\n";
std::cout << " Styles:\n";
QString f = toQt(family);
QStringList styles = fd.styles(f);
Q_FOREACH (const QString& s, styles) {
std::cout << " " << fromQt(s) << ":\n";
std::cout << " weight: " << fd.weight(f, s) << "\n";
std::cout << " bold: " << (fd.bold(f, s) ? "true" : "false") << "\n";
std::cout << " italic: " << (fd.italic(f, s) ? "true" : "false") << "\n";
std::cout << " isBitmapScalable: " << (fd.isBitmapScalable(f, s) ? "true" : "false") << "\n";
std::cout << " isFixedPitch: " << (fd.isFixedPitch(f, s) ? "true" : "false") << "\n";
std::cout << " isScalable: " << (fd.isScalable(f, s) ? "true" : "false") << "\n";
std::cout << " isSmoothlyScalable: " << (fd.isSmoothlyScalable(f, s) ? "true" : "false") << "\n";
QList<int> pointSizes = fd.pointSizes(f, s);
std::cout << " pointSizes: [";
std::string delimiter = "";
Q_FOREACH (int ps, pointSizes) {
std::cout << delimiter << ps;
delimiter = ", ";
}
std::cout << "]\n";
QList<int> smoothSizes = fd.smoothSizes(f, s);
std::cout << " smoothSizes: [";
delimiter = "";
Q_FOREACH (int ss, smoothSizes) {
std::cout << delimiter << ss;
delimiter = ", ";
}
std::cout << "]\n";
}
}
} // namespace widgets
} // namespace vgc
| 37.47619 | 112 | 0.548708 | wookay |
ebfd9f52b69f35ceb865206a613f9465517e9389 | 1,166 | cpp | C++ | AeSys/EoSelectCmd.cpp | terry-texas-us/Eo | 5652b68468c0bacd8e8da732befa2374360a4bbd | [
"MIT"
] | 1 | 2020-09-07T07:06:19.000Z | 2020-09-07T07:06:19.000Z | AeSys/EoSelectCmd.cpp | terry-texas-us/Eo | 5652b68468c0bacd8e8da732befa2374360a4bbd | [
"MIT"
] | null | null | null | AeSys/EoSelectCmd.cpp | terry-texas-us/Eo | 5652b68468c0bacd8e8da732befa2374360a4bbd | [
"MIT"
] | 2 | 2019-10-24T00:36:58.000Z | 2020-09-30T16:45:56.000Z | #include "stdafx.h"
#include "EoSelectCmd.h"
#include "AeSysDoc.h"
#include "AeSysView.h"
#include <DbCommandContext.h>
const OdString CommandSelect::groupName() const {
return L"AeSys";
}
const OdString CommandSelect::Name() {
return L"SELECT";
}
const OdString CommandSelect::globalName() const {
return Name();
}
void CommandSelect::execute(OdEdCommandContext* commandContext) {
OdDbCommandContextPtr CommandContext(commandContext);
OdDbDatabaseDocPtr Database {CommandContext->database()};
auto Document {Database->Document()};
auto View {Document->GetViewer()};
if (View == nullptr) {
throw OdEdCancel();
}
Document->OnEditClearSelection();
Document->UpdateAllViews(nullptr);
auto UserIo {CommandContext->dbUserIO()};
UserIo->setPickfirst(nullptr);
const auto SelectOptions {OdEd::kSelLeaveHighlighted | OdEd::kSelAllowEmpty};
try {
OdDbSelectionSetPtr SelectionSet {UserIo->select(L"", SelectOptions, View->EditorObject().GetWorkingSelectionSet())};
View->EditorObject().SetWorkingSelectionSet(SelectionSet);
} catch (const OdError&) {
throw OdEdCancel();
}
View->EditorObject().SelectionSetChanged();
Database->pageObjects();
}
| 28.439024 | 119 | 0.756432 | terry-texas-us |
ebff4a602701e56f0b58baaa1bb4b01018aa66f6 | 2,177 | cpp | C++ | dali-toolkit/public-api/controls/buttons/button.cpp | dalihub/dali-toolk | 980728a7e35b8ddd28f70c090243e8076e21536e | [
"Apache-2.0",
"BSD-3-Clause"
] | 7 | 2016-11-18T10:26:51.000Z | 2021-01-28T13:51:59.000Z | dali-toolkit/public-api/controls/buttons/button.cpp | dalihub/dali-toolk | 980728a7e35b8ddd28f70c090243e8076e21536e | [
"Apache-2.0",
"BSD-3-Clause"
] | 13 | 2020-07-15T11:33:03.000Z | 2021-04-09T21:29:23.000Z | dali-toolkit/public-api/controls/buttons/button.cpp | dalihub/dali-toolk | 980728a7e35b8ddd28f70c090243e8076e21536e | [
"Apache-2.0",
"BSD-3-Clause"
] | 10 | 2019-05-17T07:15:09.000Z | 2021-05-24T07:28:08.000Z | /*
* Copyright (c) 2020 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// CLASS HEADER
#include <dali-toolkit/public-api/controls/buttons/button.h>
// EXTERNAL INCLUDES
#include <dali/integration-api/debug.h>
#include <dali/public-api/object/property-map.h>
// INTERNAL INCLUDES
#include <dali-toolkit/internal/controls/buttons/button-impl.h>
#include <dali-toolkit/public-api/controls/image-view/image-view.h>
#include <dali-toolkit/public-api/visuals/text-visual-properties.h>
namespace Dali
{
namespace Toolkit
{
Button::Button()
{
}
Button::Button(const Button& button) = default;
Button::Button(Button&& rhs) = default;
Button& Button::operator=(const Button& button) = default;
Button& Button::operator=(Button&& rhs) = default;
Button::~Button()
{
}
Button Button::DownCast(BaseHandle handle)
{
return Control::DownCast<Button, Internal::Button>(handle);
}
Button::ButtonSignalType& Button::PressedSignal()
{
return Dali::Toolkit::GetImplementation(*this).PressedSignal();
}
Button::ButtonSignalType& Button::ReleasedSignal()
{
return Dali::Toolkit::GetImplementation(*this).ReleasedSignal();
}
Button::ButtonSignalType& Button::ClickedSignal()
{
return Dali::Toolkit::GetImplementation(*this).ClickedSignal();
}
Button::ButtonSignalType& Button::StateChangedSignal()
{
return Dali::Toolkit::GetImplementation(*this).StateChangedSignal();
}
Button::Button(Internal::Button& implementation)
: Control(implementation)
{
}
Button::Button(Dali::Internal::CustomActor* internal)
: Control(internal)
{
VerifyCustomActorPointer<Internal::Button>(internal);
}
} // namespace Toolkit
} // namespace Dali
| 24.460674 | 75 | 0.748277 | dalihub |
23035442399b2d186798f79ffc59cc97b8bd9617 | 2,473 | cpp | C++ | src/lib/spirent_pga/scalar/checksum.cpp | ronanjs/openperf | 55b759e399254547f8a6590b2e19cb47232265b7 | [
"Apache-2.0"
] | null | null | null | src/lib/spirent_pga/scalar/checksum.cpp | ronanjs/openperf | 55b759e399254547f8a6590b2e19cb47232265b7 | [
"Apache-2.0"
] | null | null | null | src/lib/spirent_pga/scalar/checksum.cpp | ronanjs/openperf | 55b759e399254547f8a6590b2e19cb47232265b7 | [
"Apache-2.0"
] | null | null | null | #include <algorithm>
#include <cstdint>
#include <numeric>
#include <arpa/inet.h>
#include "spirent_pga/common/headers.h"
namespace scalar {
inline uint32_t fold64(uint64_t sum)
{
sum = (sum >> 32) + (sum & 0xffffffff);
sum += sum >> 32;
return (static_cast<uint32_t>(sum));
}
inline uint16_t fold32(uint32_t sum)
{
sum = (sum >> 16) + (sum & 0xffff);
sum += sum >> 16;
return (static_cast<uint16_t>(sum));
}
void checksum_ipv4_headers(const uint8_t* ipv4_header_ptrs[],
uint16_t count,
uint32_t checksums[])
{
std::transform(ipv4_header_ptrs,
ipv4_header_ptrs + count,
checksums,
[](const uint8_t* ptr) {
auto header =
reinterpret_cast<const pga::headers::ipv4*>(ptr);
uint64_t sum = header->data[0];
sum += header->data[1];
sum += header->data[2];
sum += header->data[3];
sum += header->data[4];
uint16_t csum = fold32(fold64(sum));
return (csum == 0xffff ? csum : (0xffff ^ csum));
});
}
void checksum_ipv4_pseudoheaders(const uint8_t* ipv4_header_ptrs[],
uint16_t count,
uint32_t checksums[])
{
std::transform(
ipv4_header_ptrs,
ipv4_header_ptrs + count,
checksums,
[](const uint8_t* ptr) {
auto ipv4 = reinterpret_cast<const pga::headers::ipv4*>(ptr);
auto pheader = pga::headers::ipv4_pseudo{
.src_address = ipv4->src_address,
.dst_address = ipv4->dst_address,
.zero = 0,
.protocol = ipv4->protocol,
.length = htons(static_cast<uint16_t>(
ntohs(ipv4->length) - sizeof(pga::headers::ipv4)))};
uint64_t sum = pheader.data[0];
sum += pheader.data[1];
sum += pheader.data[2];
return (fold32(fold64(sum)));
});
}
uint32_t checksum_data_aligned(const uint32_t data[], uint16_t length)
{
uint64_t sum = std::accumulate(
data,
data + length,
uint64_t{0},
[](const auto& left, const auto& right) { return (left + right); });
return (fold64(sum));
}
} // namespace scalar
| 29.094118 | 76 | 0.506672 | ronanjs |
2303f9330df23968e2db707dd88c75be3e688228 | 209 | cpp | C++ | FaceApi/Messages/CommandMessage.cpp | bkornel/face-api | ce818f2d1e3615797079c9a098d7d45ffd525291 | [
"MIT"
] | 6 | 2018-09-21T02:49:17.000Z | 2022-03-02T17:47:04.000Z | FaceApi/Messages/CommandMessage.cpp | bkornel/face-api | ce818f2d1e3615797079c9a098d7d45ffd525291 | [
"MIT"
] | 1 | 2019-09-18T12:51:33.000Z | 2019-09-18T12:51:33.000Z | FaceApi/Messages/CommandMessage.cpp | bkornel/face-api | ce818f2d1e3615797079c9a098d7d45ffd525291 | [
"MIT"
] | null | null | null | #include "Messages/CommandMessage.h"
namespace face
{
CommandMessage::CommandMessage(Type iType, unsigned iFrameId, long long iTimestamp) :
fw::Message(iFrameId, iTimestamp),
mType(iType)
{
}
}
| 19 | 87 | 0.722488 | bkornel |
2305ba8edddb4ea3943bcb13d322990903877ab9 | 1,981 | cpp | C++ | java/com/intel/daal/algorithms/quality_metric_set/qualitymetricset_batch.cpp | cmsxbc/oneDAL | eeb8523285907dc359c84ca4894579d5d1d9f57e | [
"Apache-2.0"
] | 169 | 2020-03-30T09:13:05.000Z | 2022-03-15T11:12:36.000Z | java/com/intel/daal/algorithms/quality_metric_set/qualitymetricset_batch.cpp | cmsxbc/oneDAL | eeb8523285907dc359c84ca4894579d5d1d9f57e | [
"Apache-2.0"
] | 1,198 | 2020-03-24T17:26:18.000Z | 2022-03-31T08:06:15.000Z | java/com/intel/daal/algorithms/quality_metric_set/qualitymetricset_batch.cpp | cmsxbc/oneDAL | eeb8523285907dc359c84ca4894579d5d1d9f57e | [
"Apache-2.0"
] | 75 | 2020-03-30T11:39:58.000Z | 2022-03-26T05:16:20.000Z | /* file: qualitymetricset_batch.cpp */
/*******************************************************************************
* Copyright 2014-2021 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
#include "daal.h"
#include "com_intel_daal_algorithms_quality_metric_set_QualityMetricSetBatch.h"
/*
* Class: com_intel_daal_algorithms_QualityMetricSetBatch
* Method: cCompute
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_com_intel_daal_algorithms_quality_1metric_1set_QualityMetricSetBatch_cCompute(JNIEnv * env, jobject thisObj,
jlong algAddr)
{
(*(daal::algorithms::quality_metric_set::Batch *)algAddr).compute();
if ((*(daal::algorithms::quality_metric_set::Batch *)algAddr).getErrors()->size() > 0)
{
env->ThrowNew(env->FindClass("java/lang/Exception"), (*(daal::algorithms::quality_metric_set::Batch *)algAddr).getErrors()->getDescription());
}
}
/*
* Class: com_intel_daal_algorithms_QualityMetricSetBatch
* Method: cDispose
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_com_intel_daal_algorithms_quality_1metric_1set_QualityMetricSetBatch_cDispose(JNIEnv *, jobject, jlong algAddr)
{
delete (daal::algorithms::quality_metric_set::Batch *)algAddr;
}
| 42.148936 | 150 | 0.655225 | cmsxbc |
2309266fc602812e006f7a648963a6e9df1d4005 | 637 | hpp | C++ | test/include/cjdb/test/functional/rangecmp/is_equivalence.hpp | cjdb/clang-concepts-ranges | 7019754e97c8f3863035db74de62004ae3814954 | [
"Apache-2.0"
] | 4 | 2019-03-02T01:09:07.000Z | 2019-10-16T15:46:21.000Z | test/include/cjdb/test/functional/rangecmp/is_equivalence.hpp | cjdb/clang-concepts-ranges | 7019754e97c8f3863035db74de62004ae3814954 | [
"Apache-2.0"
] | 5 | 2018-12-16T13:47:32.000Z | 2019-10-13T01:27:11.000Z | test/include/cjdb/test/functional/rangecmp/is_equivalence.hpp | cjdb/clang-concepts-ranges | 7019754e97c8f3863035db74de62004ae3814954 | [
"Apache-2.0"
] | 3 | 2020-06-08T18:27:28.000Z | 2021-03-27T17:49:46.000Z | // Copyright (c) Christopher Di Bella.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
#ifndef CJDB_TEST_FUNCTIONAL_RANGECMP_IS_EQUIVALENCE_HPP
#define CJDB_TEST_FUNCTIONAL_RANGECMP_IS_EQUIVALENCE_HPP
#include "cjdb/test/constexpr_check.hpp"
#include "cjdb/test/functional/rangecmp/is_partial_equivalence.hpp"
#include "cjdb/test/functional/rangecmp/is_reflexive.hpp"
#define CHECK_IS_EQUIVALENCE(r, a, b, c) \
{ \
CHECK_IS_PARTIAL_EQUIVALENCE(r, a, b, c); \
CHECK_IS_REFLEXIVE(r, a); \
}
#endif // CJDB_TEST_FUNCTIONAL_RANGECMP_IS_EQUIVALENCE_HPP
| 35.388889 | 67 | 0.715856 | cjdb |
230a0b7c9d8bde4d8d0586c8a1610b8e9de5b569 | 8,913 | cpp | C++ | ros/src/computing/perception/detection/lidar_detector/packages/lidar_apollo_cnn_seg_detect/nodes/cnn_segmentation.cpp | baharkhabbazan/autoware | 4285b539199af172faadba92bed887fdbb225472 | [
"Apache-2.0"
] | 20 | 2019-05-21T06:14:17.000Z | 2021-11-03T04:36:09.000Z | ros/src/computing/perception/detection/lidar_detector/packages/lidar_apollo_cnn_seg_detect/nodes/cnn_segmentation.cpp | anhnv3991/autoware | d5b2ed9dc309193c8a2a7c77a2b6c88104c28328 | [
"Apache-2.0"
] | 18 | 2019-04-08T16:09:37.000Z | 2019-06-05T15:24:40.000Z | ros/src/computing/perception/detection/lidar_detector/packages/lidar_apollo_cnn_seg_detect/nodes/cnn_segmentation.cpp | anhnv3991/autoware | d5b2ed9dc309193c8a2a7c77a2b6c88104c28328 | [
"Apache-2.0"
] | 8 | 2019-04-28T13:15:18.000Z | 2021-06-03T07:05:16.000Z | /*
* Copyright 2018-2019 Autoware Foundation. 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 "cnn_segmentation.h"
CNNSegmentation::CNNSegmentation() : nh_()
{
}
bool CNNSegmentation::init()
{
std::string proto_file;
std::string weight_file;
ros::NodeHandle private_node_handle("~");//to receive args
if (private_node_handle.getParam("network_definition_file", proto_file))
{
ROS_INFO("[%s] network_definition_file: %s", __APP_NAME__, proto_file.c_str());
} else
{
ROS_INFO("[%s] No Network Definition File was received. Finishing execution.", __APP_NAME__);
return false;
}
if (private_node_handle.getParam("pretrained_model_file", weight_file))
{
ROS_INFO("[%s] Pretrained Model File: %s", __APP_NAME__, weight_file.c_str());
} else
{
ROS_INFO("[%s] No Pretrained Model File was received. Finishing execution.", __APP_NAME__);
return false;
}
private_node_handle.param<std::string>("points_src", topic_src_, "points_raw");
ROS_INFO("[%s] points_src: %s", __APP_NAME__, topic_src_.c_str());
private_node_handle.param<double>("range", range_, 60.);
ROS_INFO("[%s] Pretrained Model File: %.2f", __APP_NAME__, range_);
private_node_handle.param<double>("score_threshold", score_threshold_, 0.6);
ROS_INFO("[%s] score_threshold: %.2f", __APP_NAME__, score_threshold_);
private_node_handle.param<int>("width", width_, 512);
ROS_INFO("[%s] width: %d", __APP_NAME__, width_);
private_node_handle.param<int>("height", height_, 512);
ROS_INFO("[%s] height: %d", __APP_NAME__, height_);
private_node_handle.param<bool>("use_gpu", use_gpu_, false);
ROS_INFO("[%s] use_gpu: %d", __APP_NAME__, use_gpu_);
private_node_handle.param<int>("gpu_device_id", gpu_device_id_, 0);
ROS_INFO("[%s] gpu_device_id: %d", __APP_NAME__, gpu_device_id_);
/// Instantiate Caffe net
if (!use_gpu_)
{
caffe::Caffe::set_mode(caffe::Caffe::CPU);
}
else
{
caffe::Caffe::SetDevice(gpu_device_id_);
caffe::Caffe::set_mode(caffe::Caffe::GPU);
caffe::Caffe::DeviceQuery();
}
caffe_net_.reset(new caffe::Net<float>(proto_file, caffe::TEST));
caffe_net_->CopyTrainedLayersFrom(weight_file);
std::string instance_pt_blob_name = "instance_pt";
instance_pt_blob_ = caffe_net_->blob_by_name(instance_pt_blob_name);
CHECK(instance_pt_blob_ != nullptr) << "`" << instance_pt_blob_name
<< "` layer required";
std::string category_pt_blob_name = "category_score";
category_pt_blob_ = caffe_net_->blob_by_name(category_pt_blob_name);
CHECK(category_pt_blob_ != nullptr) << "`" << category_pt_blob_name
<< "` layer required";
std::string confidence_pt_blob_name = "confidence_score";
confidence_pt_blob_ = caffe_net_->blob_by_name(confidence_pt_blob_name);
CHECK(confidence_pt_blob_ != nullptr) << "`" << confidence_pt_blob_name
<< "` layer required";
std::string height_pt_blob_name = "height_pt";
height_pt_blob_ = caffe_net_->blob_by_name(height_pt_blob_name);
CHECK(height_pt_blob_ != nullptr) << "`" << height_pt_blob_name
<< "` layer required";
std::string feature_blob_name = "data";
feature_blob_ = caffe_net_->blob_by_name(feature_blob_name);
CHECK(feature_blob_ != nullptr) << "`" << feature_blob_name
<< "` layer required";
std::string class_pt_blob_name = "class_score";
class_pt_blob_ = caffe_net_->blob_by_name(class_pt_blob_name);
CHECK(class_pt_blob_ != nullptr) << "`" << class_pt_blob_name
<< "` layer required";
cluster2d_.reset(new Cluster2D());
if (!cluster2d_->init(height_, width_, range_))
{
ROS_ERROR("[%s] Fail to Initialize cluster2d for CNNSegmentation", __APP_NAME__);
return false;
}
feature_generator_.reset(new FeatureGenerator());
if (!feature_generator_->init(feature_blob_.get()))
{
ROS_ERROR("[%s] Fail to Initialize feature generator for CNNSegmentation", __APP_NAME__);
return false;
}
return true;
}
bool CNNSegmentation::segment(const pcl::PointCloud<pcl::PointXYZI>::Ptr &pc_ptr,
const pcl::PointIndices &valid_idx,
autoware_msgs::DetectedObjectArray &objects)
{
int num_pts = static_cast<int>(pc_ptr->points.size());
if (num_pts == 0)
{
ROS_INFO("[%s] Empty point cloud.", __APP_NAME__);
return true;
}
feature_generator_->generate(pc_ptr);
// network forward process
caffe_net_->Forward();
#ifndef USE_CAFFE_GPU
// caffe::Caffe::set_mode(caffe::Caffe::CPU);
#else
// int gpu_id = 0;
// caffe::Caffe::SetDevice(gpu_id);
// caffe::Caffe::set_mode(caffe::Caffe::GPU);
// caffe::Caffe::DeviceQuery();
#endif
// clutser points and construct segments/objects
float objectness_thresh = 0.5;
bool use_all_grids_for_clustering = true;
cluster2d_->cluster(*category_pt_blob_, *instance_pt_blob_, pc_ptr,
valid_idx, objectness_thresh,
use_all_grids_for_clustering);
cluster2d_->filter(*confidence_pt_blob_, *height_pt_blob_);
cluster2d_->classify(*class_pt_blob_);
float confidence_thresh = score_threshold_;
float height_thresh = 0.5;
int min_pts_num = 3;
cluster2d_->getObjects(confidence_thresh, height_thresh, min_pts_num,
objects, message_header_);
return true;
}
void CNNSegmentation::test_run()
{
std::string in_pcd_file = "uscar_12_1470770225_1470770492_1349.pcd";
pcl::PointCloud<pcl::PointXYZI>::Ptr in_pc_ptr(new pcl::PointCloud<pcl::PointXYZI>);
pcl::io::loadPCDFile(in_pcd_file, *in_pc_ptr);
pcl::PointIndices valid_idx;
auto &indices = valid_idx.indices;
indices.resize(in_pc_ptr->size());
std::iota(indices.begin(), indices.end(), 0);
autoware_msgs::DetectedObjectArray objects;
init();
segment(in_pc_ptr, valid_idx, objects);
}
void CNNSegmentation::run()
{
init();
points_sub_ = nh_.subscribe(topic_src_, 1, &CNNSegmentation::pointsCallback, this);
points_pub_ = nh_.advertise<sensor_msgs::PointCloud2>("/detection/lidar_detector/points_cluster", 1);
objects_pub_ = nh_.advertise<autoware_msgs::DetectedObjectArray>("/detection/lidar_detector/objects", 1);
ROS_INFO("[%s] Ready. Waiting for data...", __APP_NAME__);
}
void CNNSegmentation::pointsCallback(const sensor_msgs::PointCloud2 &msg)
{
std::chrono::system_clock::time_point start, end;
start = std::chrono::system_clock::now();
pcl::PointCloud<pcl::PointXYZI>::Ptr in_pc_ptr(new pcl::PointCloud<pcl::PointXYZI>);
pcl::fromROSMsg(msg, *in_pc_ptr);
pcl::PointIndices valid_idx;
auto &indices = valid_idx.indices;
indices.resize(in_pc_ptr->size());
std::iota(indices.begin(), indices.end(), 0);
message_header_ = msg.header;
autoware_msgs::DetectedObjectArray objects;
objects.header = message_header_;
segment(in_pc_ptr, valid_idx, objects);
pubColoredPoints(objects);
objects_pub_.publish(objects);
end = std::chrono::system_clock::now();
double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
}
void CNNSegmentation::pubColoredPoints(const autoware_msgs::DetectedObjectArray &objects_array)
{
pcl::PointCloud<pcl::PointXYZRGB> colored_cloud;
for (size_t object_i = 0; object_i < objects_array.objects.size(); object_i++)
{
// std::cout << "objct i" << object_i << std::endl;
pcl::PointCloud<pcl::PointXYZI> object_cloud;
pcl::fromROSMsg(objects_array.objects[object_i].pointcloud, object_cloud);
int red = (object_i) % 256;
int green = (object_i * 7) % 256;
int blue = (object_i * 13) % 256;
for (size_t i = 0; i < object_cloud.size(); i++)
{
// std::cout << "point i" << i << "/ size: "<<object_cloud.size() << std::endl;
pcl::PointXYZRGB colored_point;
colored_point.x = object_cloud[i].x;
colored_point.y = object_cloud[i].y;
colored_point.z = object_cloud[i].z;
colored_point.r = red;
colored_point.g = green;
colored_point.b = blue;
colored_cloud.push_back(colored_point);
}
}
sensor_msgs::PointCloud2 output_colored_cloud;
pcl::toROSMsg(colored_cloud, output_colored_cloud);
output_colored_cloud.header = message_header_;
points_pub_.publish(output_colored_cloud);
}
| 34.546512 | 107 | 0.693481 | baharkhabbazan |
230aed13e0c171ee888ec6eccfeede61d4d547c2 | 780 | cpp | C++ | questions/46367568/main.cpp | sesu089/stackoverflow | 6fae69be6fa74fba9d554e6b5f387e5d3c1aad73 | [
"MIT"
] | 302 | 2017-03-04T00:05:23.000Z | 2022-03-28T22:51:29.000Z | questions/46367568/main.cpp | sesu089/stackoverflow | 6fae69be6fa74fba9d554e6b5f387e5d3c1aad73 | [
"MIT"
] | 30 | 2017-12-02T19:26:43.000Z | 2022-03-28T07:40:36.000Z | questions/46367568/main.cpp | sesu089/stackoverflow | 6fae69be6fa74fba9d554e6b5f387e5d3c1aad73 | [
"MIT"
] | 388 | 2017-07-04T16:53:12.000Z | 2022-03-18T22:20:19.000Z | #include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QStringListModel>
class StringListModel : public QStringListModel {
Q_OBJECT
public:
Q_INVOKABLE bool removeRows(int row, int count,
const QModelIndex &parent = QModelIndex()) {
return QStringListModel::removeRows(row, count, parent);
}
};
#include "main.moc"
int main(int argc, char *argv[]) {
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
QStringList l{"a", "b", "c", "d"};
StringListModel model;
model.setStringList(l);
engine.rootContext()->setContextProperty("myModel", &model);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
| 26 | 74 | 0.692308 | sesu089 |
230bed5b01f64f1cb1089f71ac503d8567d45205 | 13,004 | cpp | C++ | src/reactive/http/request.cpp | ReactiveFramework/ReactiveFramework | c986f67cca10789e7a85e5a226c0cf7abb642698 | [
"MIT"
] | null | null | null | src/reactive/http/request.cpp | ReactiveFramework/ReactiveFramework | c986f67cca10789e7a85e5a226c0cf7abb642698 | [
"MIT"
] | null | null | null | src/reactive/http/request.cpp | ReactiveFramework/ReactiveFramework | c986f67cca10789e7a85e5a226c0cf7abb642698 | [
"MIT"
] | 1 | 2021-09-07T11:08:28.000Z | 2021-09-07T11:08:28.000Z | /**
* Reactive
*
* (c) 2015-2016 Axel Etcheverry
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#include <string>
#include <reactive/http/request.hpp>
namespace reactive {
namespace http {
int request::on_message_begin(http_parser* parser_)
{
//request& r = *(static_cast<request*>(parser_->data));
//r.setComplete(false);
//r.setHeadersComplete(false);
return 0;
}
int request::on_message_complete(http_parser* parser_)
{
//request& r = *static_cast<request*>(parser_->data);
//r.setComplete(true);
// Force the parser to stop after the request is parsed so clients
// can process the request (or response). This is to properly
// handle HTTP/1.1 pipelined requests.
//http_parser_pause(parser_, 1);
return 0;
}
int request::on_header_field(http_parser* parser_, const char* data_, std::size_t size_)
{
request& r = *static_cast<request*>(parser_->data);
if (!r.getCurrentValue().empty()) {
process_header(r, r.getCurrentField(), r.getCurrentValue());
r.getCurrentField().clear();
r.getCurrentValue().clear();
}
r.getCurrentField().append(data_, size_);
return 0;
}
int request::on_header_value(http_parser* parser_, const char* data_, std::size_t size_)
{
request& r = *static_cast<request*>(parser_->data);
r.getCurrentValue().append(data_, size_);
return 0;
}
int request::on_headers_complete(http_parser* parser_)
{
request& r = *(static_cast<request*>(parser_->data));
if (!r.getCurrentValue().empty()) {
process_header(r, r.getCurrentField(), r.getCurrentValue());
r.getCurrentField().clear();
r.getCurrentValue().clear();
}
//r.setHeadersComplete(true);
// Force the parser to stop after the headers are parsed so clients
// can process the request (or response). This is to properly
// handle HTTP/1.1 pipelined requests.
//http_parser_pause(parser_, 1);
return 0;
}
int request::on_url(http_parser* parser_, const char* data_, std::size_t size_)
{
std::string path;
std::string query;
bool is_path = true;
for (std::size_t i = 0; i < size_; ++i) {
char chr = data_[i];
if (is_path) {
if (chr == '?') {
is_path = false;
continue;
}
path += chr;
} else {
query += chr;
}
}
request& r = *static_cast<request*>(parser_->data);
r.getUrl().setPath(path);
if (!query.empty()) {
r.getUrl().setQuery(query);
}
return 0;
}
int request::on_body(http_parser* parser_, const char* data_, std::size_t size_)
{
static_cast<request*>(parser_->data)->getContent().append(data_, size_);
return 0;
}
void request::process_header(request& request_, const std::string& field_, const std::string& value_)
{
if (field_ == "Host") {
request_.getUrl().setHost(value_);
} else if (field_ == "User-Agent") {
request_.setUserAgent(value_);
} else if (field_ == "Cookie") {
//@TODO convert this code in state machine parser
std::vector<std::string> cookies;
reactive::string::split(REACTIVE_HTTP_COOKIE_SEPARATOR, value_, cookies);
for (std::size_t i = 0; i < cookies.size(); ++i) {
std::vector<std::string> cookie_string;
reactive::string::split("=", cookies.at(i), cookie_string);
cookie_t cookie;
cookie.name = reactive::uri::decode(cookie_string[0]);
cookie.value = reactive::uri::decode(cookie_string[1]);
cookie_string.clear();
request_.getCookies().add(cookie);
}
cookies.clear();
} else if (field_ == "X-Forwarded-For") {
process_ip(request_, value_);
} else if (field_ == "X-Client") {
process_ip(request_, value_);
} else if (field_ == "Content-Type") {
request_.setContentType(value_);
}
request_.getHeaders().add(field_, value_);
}
void request::process_ip(request& request_, const std::string& ip_)
{
request_.info.by_proxy = true;
request_.info.proxy_ip_version = request_.info.ip_version;
request_.info.proxy_ip = request_.info.ip;
request_.info.proxy_port = request_.info.port;
std::size_t pos = ip_.find(",");
request_.info.ip = ip_;
if (pos != std::string::npos) {
request_.info.ip = ip_.substr(0, pos);
}
try {
boost::asio::ip::address ip_version = boost::asio::ip::address::from_string(request_.info.ip);
if (ip_version.is_v4()) {
request_.info.ip_version = reactive::net::ip::IPV4;
} else if (ip_version.is_v6()) {
request_.info.ip_version = reactive::net::ip::IPV6;
}
} catch (std::exception& e) {
request_.info.ip_version = reactive::net::ip::UNDEFINED;
//request_.info.by_proxy = false;
}
// In this process we have no port information
request_.info.port.clear();
}
request::request()
{
reset();
memset(&m_settings, 0, sizeof(m_settings));
// Setting state machine callbacks
m_settings.on_message_begin = &request::on_message_begin;
m_settings.on_message_complete = &request::on_message_complete;
m_settings.on_header_field = &request::on_header_field;
m_settings.on_header_value = &request::on_header_value;
m_settings.on_headers_complete = &request::on_headers_complete;
m_settings.on_url = &request::on_url;
m_settings.on_body = &request::on_body;
memset(&m_parser, 0, sizeof(m_parser));
http_parser_init(&m_parser, HTTP_REQUEST);
m_parser.data = this;
}
request::~request()
{
// clear headers list
getHeaders().clear();
// clear cookies list
m_cookies.clear();
}
void request::reset()
{
info.reset();
m_useragent = REACTIVE_HTTP_REQUEST_USER_AGENT;
setVersion(protocol::VERSION_11);
m_method = protocol::METHOD_GET;
// Resetting content and its type
setContent("");
m_content_type = "";
// unused undocumented variables
//m_complete = false;
//m_headers_complete = false;
m_query.clear();
m_body.clear();
}
std::size_t request::parse(const char* data_, std::size_t size_)
{
std::size_t parsed = 0;
if (size_ > 0) {
parsed = http_parser_execute(&m_parser, &m_settings, data_, size_);
//if (parsed < size_)
// LIMIT in reading is 80x1024
}
//const http_errno errno = static_cast<http_errno>(m_parser.http_errno);
// The 'on_message_complete' and 'on_headers_complete' callbacks fail
// on purpose to force the parser to stop between pipelined requests.
// This allows the clients to reliably detect the end of headers and
// the end of the message. Make sure the parser is always unpaused
// for the next call to 'feed'.
/*if (herrno == HPE_PAUSED)
{
http_parser_pause(&m_parser, 0);
}*/
/*if (used < size_)
{
if (herrno == HPE_PAUSED)
{
// Make sure the byte that triggered the pause
// after the headers is properly processed.
if (!m_complete)
{
used += http_parser_execute(&m_parser, &m_settings, data_+used, 1);
}
}
else
{
throw (error(herrno));
}
}*/
m_method = std::string(http_method_str((http_method)m_parser.method));
setVersion(std::to_string(m_parser.http_major) + "." + std::to_string(m_parser.http_minor));
if (!m_url.getQuery().empty()) {
m_query.parse(m_url.getQuery());
}
if (m_content_type == "application/x-www-form-urlencoded") {
m_body.parse(getContent());
}
return parsed;
}
bool request::hasQueryArgument(const std::string& key_) const
{
return m_query.has(key_);
}
bool request::hasBodyArgument(const std::string& key_) const
{
return m_body.has(key_);
}
bool request::shouldKeepAlive() const
{
return (http_should_keep_alive(const_cast<http_parser*>(&m_parser)) != 0);
}
const cookie_bag& request::getCookies() const
{
return m_cookies;
}
cookie_bag& request::getCookies()
{
return m_cookies;
}
void request::setMethod(const std::string& method_)
{
m_method = method_;
}
const std::string& request::getMethod() const
{
return m_method;
}
void request::setUserAgent(const std::string& useragent_)
{
m_useragent = useragent_;
}
const std::string& request::getUserAgent() const
{
return m_useragent;
}
void request::setUrl(reactive::uri::url& url_)
{
m_url = url_;
}
void request::setUrl(const std::string& url_)
{
m_url = reactive::uri::url(url_);
}
const reactive::uri::url& request::getUrl() const
{
return m_url;
}
reactive::uri::url& request::getUrl()
{
return m_url;
}
void request::setContentType(const std::string& type_)
{
std::size_t pos = type_.find(";");
if (pos != std::string::npos) {
m_content_type = type_.substr(0, pos);
} else {
m_content_type = type_;
}
getHeaders().add("Content-Type", m_content_type);
}
/**
* Get content type
*
* @return The string of content type
*/
const std::string& request::getContentType() const
{
return m_content_type;
}
bool request::isXmlHttpRequest() const
{
if (getHeaders().has("X-Requested-With") && getHeaders().get("X-Requested-With").value == "XMLHttpRequest") {
return true;
}
return false;
}
reactive::uri::query request::getData() const
{
return m_body;
}
std::string request::toString() const
{
header_bag headers = getHeaders();
headers.add("Host", m_url.toString(reactive::uri::url::HOST | reactive::uri::url::PORT));
if (!headers.has("Cache-Control")) {
headers.add("Cache-Control", "max-age=0");
}
if (!headers.has("Accept")) {
headers.add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
}
if (!headers.has("User-Agent")) {
headers.add("User-Agent", m_useragent);
}
if (!headers.has("Accept-Charset")) {
headers.add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
}
std::string reqstr = m_method
+ " "
+ m_url.toString(reactive::uri::url::PATH | reactive::uri::url::QUERY)
+ " HTTP/"
+ getVersion()
+ protocol::CRLF;
// --- Constructing the cookie string
std::string full_cookies;
std::size_t count_cookie = m_cookies.size();
for (std::size_t i = 0; i < count_cookie; ++i) {
std::string cookie;
cookie.append(reactive::uri::encode(m_cookies.at(i).name));
cookie.append("=");
cookie.append(reactive::uri::encode(m_cookies.at(i).value));
if (i != (count_cookie - 1)) {
cookie.append(REACTIVE_HTTP_COOKIE_SEPARATOR);
}
full_cookies.append(cookie);
}
// --- Using the cookie string to build the header
if (!full_cookies.empty()) {
headers.add("Cookie", full_cookies);
}
// In HTTP/1.1 the default connection type is Keep-Alive
// while it is not fully supported in HTTP/1.0 it does not matter.
//
// Anyway this default header is set during connection and not here
//headers.add("Connection", "Keep-Alive");
reqstr.append(headers.toString() + protocol::CRLF);
if (!getContent().empty()) {
reqstr.append(getContent());
}
return reqstr;
}
} // end of http namespace
} // end of reactive namespace
| 28.208243 | 117 | 0.556521 | ReactiveFramework |
230d73f8f945d97a3783cedc26ae2c87222cc557 | 1,548 | hpp | C++ | include/boost/simd/constant/definition/thousand.hpp | nickporubsky/boost-simd-clone | b81dfcd9d6524a131ea714f1eebb5bb75adddcc7 | [
"BSL-1.0"
] | 5 | 2018-02-20T11:21:12.000Z | 2019-11-12T13:45:09.000Z | include/boost/simd/constant/definition/thousand.hpp | nickporubsky/boost-simd-clone | b81dfcd9d6524a131ea714f1eebb5bb75adddcc7 | [
"BSL-1.0"
] | null | null | null | include/boost/simd/constant/definition/thousand.hpp | nickporubsky/boost-simd-clone | b81dfcd9d6524a131ea714f1eebb5bb75adddcc7 | [
"BSL-1.0"
] | 2 | 2017-11-17T15:30:36.000Z | 2018-03-01T02:06:25.000Z | //==================================================================================================
/*!
@file
@copyright 2016 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_CONSTANT_DEFINITION_THOUSAND_HPP_INCLUDED
#define BOOST_SIMD_CONSTANT_DEFINITION_THOUSAND_HPP_INCLUDED
#include <boost/simd/config.hpp>
#include <boost/simd/detail/brigand.hpp>
#include <boost/simd/detail/dispatch.hpp>
#include <boost/simd/detail/constant_traits.hpp>
#include <boost/simd/detail/dispatch/function/make_callable.hpp>
#include <boost/simd/detail/dispatch/hierarchy/functions.hpp>
#include <boost/simd/detail/dispatch/as.hpp>
namespace boost { namespace simd
{
namespace tag
{
struct thousand_ : boost::dispatch::constant_value_<thousand_>
{
BOOST_DISPATCH_MAKE_CALLABLE(ext,thousand_,boost::dispatch::constant_value_<thousand_>);
BOOST_SIMD_REGISTER_CONSTANT(1000, 0x447a0000UL, 0x408f400000000000ULL);
};
}
namespace ext
{
BOOST_DISPATCH_FUNCTION_DECLARATION(tag, thousand_)
}
namespace detail
{
BOOST_DISPATCH_CALLABLE_DEFINITION(tag::thousand_,thousand);
}
template<typename T> BOOST_FORCEINLINE auto Thousand()
BOOST_NOEXCEPT_DECLTYPE(detail::thousand( boost::dispatch::as_<T>{}))
{
return detail::thousand( boost::dispatch::as_<T>{} );
}
} }
#endif
| 30.352941 | 100 | 0.663437 | nickporubsky |
231844adbf30c001bf10c931c6edabf567b8d2d1 | 5,669 | cpp | C++ | Code/BBearEditor/Engine/Utils/BBUtils.cpp | lishangdian/BBearEditor-2.0 | 1f4b463ef756ed36cc15d10abae822efc400c4d7 | [
"MIT"
] | 1 | 2021-09-01T08:19:34.000Z | 2021-09-01T08:19:34.000Z | Code/BBearEditor/Engine/Utils/BBUtils.cpp | lishangdian/BBearEditor-2.0 | 1f4b463ef756ed36cc15d10abae822efc400c4d7 | [
"MIT"
] | null | null | null | Code/BBearEditor/Engine/Utils/BBUtils.cpp | lishangdian/BBearEditor-2.0 | 1f4b463ef756ed36cc15d10abae822efc400c4d7 | [
"MIT"
] | null | null | null | #include "BBUtils.h"
#include <QDir>
#include <QProcess>
#include "FileSystem/BBFileListWidget.h"
#include <GL/gl.h>
QString BBConstant::BB_NAME_PROJECT = "";
QString BBConstant::BB_PATH_PROJECT = "";
// there is no / at the end
QString BBConstant::BB_PATH_PROJECT_ENGINE = "";
QString BBConstant::BB_PATH_PROJECT_USER = "";
QString BBConstant::BB_NAME_FILE_SYSTEM_USER = "contents";
QString BBConstant::BB_NAME_FILE_SYSTEM_ENGINE = "engine";
QString BBConstant::BB_NAME_OVERVIEW_MAP = "overview map.jpg";
QString BBConstant::BB_NAME_DEFAULT_SCENE = "new scene.bbscene";
QString BBConstant::BB_NAME_DEFAULT_MATERIAL = "new material.bbmtl";
QVector3D BBConstant::m_Red = QVector3D(0.937255f, 0.378431f, 0.164706f);
QVector4D BBConstant::m_RedTransparency = QVector4D(0.937255f, 0.378431f, 0.164706f, 0.7f);
QVector3D BBConstant::m_Green = QVector3D(0.498039f, 0.827451f, 0.25098f);
QVector4D BBConstant::m_GreenTransparency = QVector4D(0.498039f, 0.827451f, 0.25098f, 0.7f);
QVector3D BBConstant::m_Blue = QVector3D(0.341176f, 0.662745f, 1.0f);
QVector4D BBConstant::m_BlueTransparency = QVector4D(0.341176f, 0.662745f, 1.0f, 0.7f);
QVector3D BBConstant::m_Yellow = QVector3D(1.0f, 1.0f, 0.305882f);
QVector3D BBConstant::m_Gray = QVector3D(0.8f, 0.8f, 0.8f);
QVector4D BBConstant::m_GrayTransparency = QVector4D(0.8f, 0.8f, 0.8f, 0.7f);
//QVector3D BBConstant::m_Red = QVector3D(0.909804f, 0.337255f, 0.333333f);
//QVector4D BBConstant::m_RedTransparency = QVector4D(0.909804f, 0.337255f, 0.333333f, 0.5f);
//QVector3D BBConstant::m_Green = QVector3D(0.356863f, 0.729412f, 0.619608f);
//QVector4D BBConstant::m_GreenTransparency = QVector4D(0.356863f, 0.729412f, 0.619608f, 0.5f);
//QVector3D BBConstant::m_Blue = QVector3D(0.384314f, 0.631373f, 0.847059f);
//QVector4D BBConstant::m_BlueTransparency = QVector4D(0.384314f, 0.631373f, 0.847059f, 0.5f);
//QVector3D BBConstant::m_Yellow = QVector3D(0.847059f, 0.603922f, 0.309804f);
QVector3D BBConstant::m_OrangeRed = QVector3D(0.909804f, 0.337255f, 0.333333f);
char *BBUtils::loadFileContent(const char *filePath, int &nFileSize)
{
FILE *pFile = NULL;
char *pData = NULL;
// Read files by binary mode
// path.toLatin1().data(); will cause Chinese garbled
do{
pFile = fopen(filePath, "rb");
BB_PROCESS_ERROR(pFile);
// Seek the pointer to the end of the file
BB_PROCESS_ERROR(BB_SUCCEEDED(fseek(pFile, 0, SEEK_END)));
// Get the size of the file
size_t length = ftell(pFile);
BB_PROCESS_ERROR(length);
// Seek to the beginning of the file
BB_PROCESS_ERROR(BB_SUCCEEDED(fseek(pFile, 0, SEEK_SET)));
// +1 Terminator
pData = new char[length + 1];
BB_PROCESS_ERROR(pData);
// 1*length is the size of the file to be read
BB_PROCESS_ERROR(fread(pData, 1, length, pFile));
// Terminator
pData[length] = 0;
nFileSize = length;
}while(0);
if (pFile)
fclose(pFile);
return pData;
}
bool BBUtils::saveToFile(const char *pFilePath, void *pBuffer, int nSize)
{
FILE *pFile = fopen(pFilePath, "wb");
BB_PROCESS_ERROR_RETURN_FALSE(pFile);
fwrite(pBuffer, sizeof(char), nSize, pFile);
fclose(pFile);
return true;
}
unsigned char* BBUtils::decodeBMP(unsigned char *pBmpFileData, int &nWidth, int &nHeight)
{
// Is it a bitmap file
if (0x4D42 == *((unsigned short*)pBmpFileData))
{
int nPixelDataOffset = *((int*)(pBmpFileData + 10));
nWidth = *((int*)(pBmpFileData + 18));
nHeight = *((int*)(pBmpFileData + 22));
unsigned char *pPixelData = pBmpFileData + nPixelDataOffset;
// be saved as BGR, but opengl support RGB, exchange B with R
// bmp does not support alpha
for (int i = 0; i < nWidth * nHeight * 3; i += 3)
{
unsigned char temp = pPixelData[i];
pPixelData[i] = pPixelData[i + 2];
pPixelData[i + 2] = temp;
}
return pPixelData;
}
return nullptr;
}
QString BBUtils::getBaseName(const QString &name)
{
return name.mid(0, name.lastIndexOf('.'));
}
QString BBUtils::getPathRelativeToExecutionDirectory(const QString &absolutePath)
{
QDir dir(QDir::currentPath());
return dir.relativeFilePath(absolutePath);
}
unsigned int BBUtils::getBlendFunc(int nIndex)
{
unsigned int func = GL_ZERO;
switch (nIndex) {
case 0:
func = GL_ZERO;
break;
case 1:
func = GL_ONE;
break;
case 2:
func = GL_SRC_COLOR;
break;
case 3:
func = GL_ONE_MINUS_SRC_COLOR;
break;
case 4:
func = GL_SRC_ALPHA;
break;
case 5:
func = GL_ONE_MINUS_SRC_ALPHA;
break;
case 6:
func = GL_DST_ALPHA;
break;
case 7:
func = GL_ONE_MINUS_DST_ALPHA;
break;
default:
break;
}
return func;
}
QString BBUtils::getBlendFuncName(unsigned int func)
{
QString name;
switch (func) {
case GL_ZERO:
name = "GL_ZERO";
break;
case GL_ONE:
name = "GL_ONE";
break;
case GL_SRC_COLOR:
name = "GL_SRC_COLOR";
break;
case GL_ONE_MINUS_SRC_COLOR:
name = "GL_ONE_MINUS_SRC_COLOR";
break;
case GL_SRC_ALPHA:
name = "GL_SRC_ALPHA";
break;
case GL_ONE_MINUS_SRC_ALPHA:
name = "GL_ONE_MINUS_SRC_ALPHA";
break;
case GL_DST_ALPHA:
name = "GL_DST_ALPHA";
break;
case GL_ONE_MINUS_DST_ALPHA:
name = "GL_ONE_MINUS_DST_ALPHA";
break;
default:
break;
}
return name;
}
| 30.978142 | 95 | 0.652672 | lishangdian |
231b0b7c02947ac2cd973c765a2e2d2c1a1a05fd | 648 | cc | C++ | src/virtualization/lib/guest_interaction/client/guest_discovery_service_main.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 5 | 2022-01-10T20:22:17.000Z | 2022-01-21T20:14:17.000Z | src/virtualization/lib/guest_interaction/client/guest_discovery_service_main.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 1 | 2022-03-01T01:12:04.000Z | 2022-03-01T01:17:26.000Z | src/virtualization/lib/guest_interaction/client/guest_discovery_service_main.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <lib/async-loop/cpp/loop.h>
#include <lib/async-loop/default.h>
#include "src/virtualization/lib/guest_interaction/client/guest_discovery_service.h"
int main(int argc, char** argv) {
async::Loop loop(&kAsyncLoopConfigNoAttachToCurrentThread);
// Create the guest interaction service and run its gRPC processing loop on
// a separate thread.
GuestDiscoveryServiceImpl guest_discovery_service = GuestDiscoveryServiceImpl(loop.dispatcher());
return loop.Run();
}
| 34.105263 | 99 | 0.774691 | allansrc |
231bebc432243dd3f9569ff093363b854aa9edd8 | 8,492 | cpp | C++ | Sources/Display/Font/font.cpp | ValtoFrameworks/ClanLib | 2d6b59386ce275742653b354a1daab42cab7cb3e | [
"Linux-OpenIB"
] | null | null | null | Sources/Display/Font/font.cpp | ValtoFrameworks/ClanLib | 2d6b59386ce275742653b354a1daab42cab7cb3e | [
"Linux-OpenIB"
] | null | null | null | Sources/Display/Font/font.cpp | ValtoFrameworks/ClanLib | 2d6b59386ce275742653b354a1daab42cab7cb3e | [
"Linux-OpenIB"
] | null | null | null | /*
** ClanLib SDK
** Copyright (c) 1997-2016 The ClanLib Team
**
** This software is provided 'as-is', without any express or implied
** warranty. In no event will the authors be held liable for any damages
** arising from the use of this software.
**
** Permission is granted to anyone to use this software for any purpose,
** including commercial applications, and to alter it and redistribute it
** freely, subject to the following restrictions:
**
** 1. The origin of this software must not be misrepresented; you must not
** claim that you wrote the original software. If you use this software
** in a product, an acknowledgment in the product documentation would be
** appreciated but is not required.
** 2. Altered source versions must be plainly marked as such, and must not be
** misrepresented as being the original software.
** 3. This notice may not be removed or altered from any source distribution.
**
** Note: Some of the libraries ClanLib may link to may have additional
** requirements or restrictions.
**
** File Author(s):
**
** Magnus Norddahl
*/
#include "Display/precomp.h"
#include "API/Display/Font/font.h"
#include "API/Display/Font/font_metrics.h"
#include "API/Display/Font/font_description.h"
#include "API/Display/TargetProviders/graphic_context_provider.h"
#include "API/Core/IOData/path_help.h"
#include "API/Core/Text/string_help.h"
#include "API/Core/Text/string_format.h"
#include "API/Core/Text/utf8_reader.h"
#include "API/Display/2D/canvas.h"
#include "API/Display/Resources/display_cache.h"
#include "font_impl.h"
namespace clan
{
Font::Font()
{
}
Font::Font(FontFamily &font_family, float height)
{
font_family.throw_if_null();
FontDescription desc;
desc.set_height(height);
*this = Font(font_family, desc);
}
Font::Font(FontFamily &font_family, const FontDescription &desc)
{
impl = std::make_shared<Font_Impl>(font_family, desc);
}
Font::Font(const std::string &typeface_name, float height)
{
FontDescription desc;
desc.set_height(height);
*this = Font(typeface_name, desc);
}
Font::Font(const std::string &typeface_name, const FontDescription &desc)
{
FontFamily font_family(typeface_name);
*this = Font(font_family, desc);
}
Font::Font(const FontDescription &desc, const std::string &ttf_filename)
{
std::string path = PathHelp::get_fullpath(ttf_filename, PathHelp::path_type_file);
std::string new_filename = PathHelp::get_filename(ttf_filename, PathHelp::path_type_file);
FileSystem vfs(path);
FontFamily font_family(new_filename);
font_family.add(desc, new_filename, vfs);
impl = std::make_shared<Font_Impl>(font_family, desc);
}
Font::Font(const FontDescription &desc, const std::string &ttf_filename, FileSystem fs)
{
std::string new_filename = PathHelp::get_filename(ttf_filename, PathHelp::path_type_file);
FontFamily font_family(new_filename);
font_family.add(desc, ttf_filename, fs);
impl = std::make_shared<Font_Impl>(font_family, desc);
}
Font::Font(Canvas &canvas, const std::string &typeface_name, Sprite &sprite, const std::string &glyph_list, float spacelen, bool monospace, const FontMetrics &metrics)
{
FontDescription desc;
desc.set_height(metrics.get_height());
FontFamily font_family(typeface_name);
font_family.add(canvas, sprite, glyph_list, spacelen, monospace, metrics);
impl = std::make_shared<Font_Impl>(font_family, desc);
}
Resource<Font> Font::resource(Canvas &canvas, const std::string &family_name, const FontDescription &desc, const ResourceManager &resources)
{
return DisplayCache::get(resources).get_font(canvas, family_name, desc);
}
void Font::throw_if_null() const
{
if (!impl)
throw Exception("Font is null");
}
void Font::set_height(float value)
{
if (impl)
impl->set_height(value);
}
void Font::set_weight(FontWeight value)
{
if (impl)
impl->set_weight(value);
}
void Font::set_line_height(float height)
{
if (impl)
impl->set_line_height(height);
}
void Font::set_style(FontStyle style)
{
if (impl)
impl->set_style(style);
}
void Font::set_scalable(float height_threshold)
{
if (impl)
impl->set_scalable(height_threshold);
}
GlyphMetrics Font::get_metrics(Canvas &canvas, unsigned int glyph) const
{
if (impl)
return impl->get_metrics(canvas, glyph);
return GlyphMetrics();
}
GlyphMetrics Font::measure_text(Canvas &canvas, const std::string &string) const
{
if (impl)
return impl->measure_text(canvas, string);
return GlyphMetrics();
}
size_t Font::clip_from_left(Canvas &canvas, const std::string &text, float width) const
{
float x = 0.0f;
UTF8_Reader reader(text.data(), text.length());
while (!reader.is_end())
{
unsigned int glyph = reader.get_char();
GlyphMetrics char_abc = get_metrics(canvas, glyph);
if (x + char_abc.advance.width > width)
return reader.get_position();
x += char_abc.advance.width;
reader.next();
}
return text.size();
}
size_t Font::clip_from_right(Canvas &canvas, const std::string &text, float width) const
{
float x = 0.0f;
UTF8_Reader reader(text.data(), text.length());
reader.set_position(text.length());
while (reader.get_position() != 0)
{
reader.prev();
unsigned int glyph = reader.get_char();
GlyphMetrics char_abc = get_metrics(canvas, glyph);
if (x + char_abc.advance.width > width)
{
reader.next();
return reader.get_position();
}
x += char_abc.advance.width;
}
return 0;
}
void Font::draw_text(Canvas &canvas, const Pointf &position, const std::string &text, const Colorf &color)
{
if (impl)
{
impl->draw_text(canvas, position, text, color);
}
}
std::string Font::get_clipped_text(Canvas &canvas, const Sizef &box_size, const std::string &text, const std::string &ellipsis_text) const
{
std::string out_string;
out_string.reserve(text.length());
if (impl)
{
Pointf pos;
FontMetrics fm = get_font_metrics(canvas);
float descent = fm.get_descent();
float line_spacing = fm.get_line_height();
std::vector<std::string> lines = StringHelp::split_text(text, "\n", false);
for (std::vector<std::string>::size_type i = 0; i < lines.size(); i++)
{
if (i == 0 || pos.y + descent < box_size.height)
{
Sizef size = measure_text(canvas, lines[i]).bbox_size;
if (pos.x + size.width <= box_size.width)
{
if (!out_string.empty())
out_string += "\n";
out_string += lines[i];
}
else
{
Sizef ellipsis = measure_text(canvas, ellipsis_text).bbox_size;
int seek_start = 0;
int seek_end = lines[i].size();
int seek_center = (seek_start + seek_end) / 2;
UTF8_Reader utf8_reader(lines[i].data(), lines[i].length());
while (true)
{
utf8_reader.set_position(seek_center);
utf8_reader.move_to_leadbyte();
if (seek_center != utf8_reader.get_position())
utf8_reader.next();
seek_center = utf8_reader.get_position();
if (seek_center == seek_end)
break;
utf8_reader.set_position(seek_start);
utf8_reader.next();
if (utf8_reader.get_position() == seek_end)
break;
Sizef text_size = measure_text(canvas, lines[i].substr(0, seek_center)).bbox_size;
if (pos.x + text_size.width + ellipsis.width >= box_size.width)
seek_end = seek_center;
else
seek_start = seek_center;
seek_center = (seek_start + seek_end) / 2;
}
if (!out_string.empty())
out_string += "\n";
out_string += lines[i].substr(0, seek_center) + ellipsis_text;
}
pos.y += line_spacing;
}
}
}
return out_string;
}
FontMetrics Font::get_font_metrics(Canvas &canvas) const
{
if (impl)
return impl->get_font_metrics(canvas);
return FontMetrics();
}
int Font::get_character_index(Canvas &canvas, const std::string &text, const Pointf &point) const
{
if (impl)
return impl->get_character_index(canvas, text, point);
return 0;
}
std::vector<Rectf> Font::get_character_indices(Canvas &canvas, const std::string &text) const
{
if (impl)
return impl->get_character_indices(canvas, text);
return std::vector<Rectf>();
}
FontHandle *Font::get_handle(Canvas &canvas)
{
if (impl)
return impl->get_handle(canvas);
return nullptr;
}
FontHandle::~FontHandle()
{
}
FontDescription Font::get_description() const
{
if (impl)
return impl->get_description();
return FontDescription();
}
}
| 26.788644 | 168 | 0.693005 | ValtoFrameworks |
231d4237aba480c8729ffe1c79a8b6aa08faaf08 | 2,128 | cpp | C++ | moses/moses/ChartTrellisPath.cpp | anshsarkar/TailBench | 25845756aee9a892229c25b681051591c94daafd | [
"MIT"
] | 3 | 2018-01-25T00:51:56.000Z | 2022-01-07T15:09:38.000Z | moses/moses/ChartTrellisPath.cpp | anshsarkar/TailBench | 25845756aee9a892229c25b681051591c94daafd | [
"MIT"
] | 1 | 2020-06-23T08:29:09.000Z | 2020-06-24T12:11:47.000Z | moses/moses/ChartTrellisPath.cpp | anshsarkar/TailBench | 25845756aee9a892229c25b681051591c94daafd | [
"MIT"
] | 3 | 2018-06-08T08:36:27.000Z | 2021-12-26T20:36:16.000Z | // $Id$
// vim:tabstop=2
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2010 Hieu Hoang
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
***********************************************************************/
#include "ChartTrellisPath.h"
#include "ChartHypothesis.h"
#include "ChartTrellisDetour.h"
#include "ChartTrellisDetourQueue.h"
#include "ChartTrellisNode.h"
namespace Moses
{
ChartTrellisPath::ChartTrellisPath(const ChartHypothesis &hypo)
: m_finalNode(new ChartTrellisNode(hypo))
, m_deviationPoint(NULL)
, m_scoreBreakdown(hypo.GetScoreBreakdown())
, m_totalScore(hypo.GetTotalScore())
{
}
ChartTrellisPath::ChartTrellisPath(const ChartTrellisDetour &detour)
: m_finalNode(new ChartTrellisNode(detour, m_deviationPoint))
, m_scoreBreakdown(detour.GetBasePath().m_scoreBreakdown)
, m_totalScore(0)
{
CHECK(m_deviationPoint);
ScoreComponentCollection scoreChange;
scoreChange = detour.GetReplacementHypo().GetScoreBreakdown();
scoreChange.MinusEquals(detour.GetSubstitutedNode().GetHypothesis().GetScoreBreakdown());
m_scoreBreakdown.PlusEquals(scoreChange);
m_totalScore = m_scoreBreakdown.GetWeightedScore();
}
ChartTrellisPath::~ChartTrellisPath()
{
delete m_finalNode;
}
Phrase ChartTrellisPath::GetOutputPhrase() const
{
Phrase ret = GetFinalNode().GetOutputPhrase();
return ret;
}
} // namespace Moses
| 32.738462 | 91 | 0.726034 | anshsarkar |
2322c13f90bef22a89b54712c0a482e5fa3f524d | 736 | hpp | C++ | include/Player.hpp | esweet431/Cnake | faaaea177d26070fd6c1cd664222d4041ecc7bec | [
"MIT"
] | 3 | 2019-10-15T04:16:29.000Z | 2019-10-19T03:55:39.000Z | include/Player.hpp | esweet431/Cnake | faaaea177d26070fd6c1cd664222d4041ecc7bec | [
"MIT"
] | 5 | 2019-05-16T06:59:48.000Z | 2019-10-13T06:09:59.000Z | include/Player.hpp | esweet431/Cnake | faaaea177d26070fd6c1cd664222d4041ecc7bec | [
"MIT"
] | 2 | 2020-02-14T18:27:35.000Z | 2021-07-08T20:41:21.000Z | #pragma once
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <vector>
#include <mutex>
enum Direction {
Up,
Right,
Down,
Left
};
class Player : public sf::Drawable
{
public:
// Constructor
Player(const std::map<std::string, sf::Texture>&, std::mutex*);
// Destructor
~Player();
// Setters
void processKeys(sf::Keyboard::Key);
// Getters
sf::Vector2f getHeadPos();
// Processors
void movePlayer();
void addPart();
bool safeCheck(sf::RectangleShape&, sf::Text&, sf::Sound&, sf::Sound&);
private:
virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const;
private:
std::vector<sf::RectangleShape> snakeBody;
Direction m_dir;
Direction m_lastDir;
std::mutex* mu;
int playerScore;
};
| 19.368421 | 76 | 0.702446 | esweet431 |
2323218e955ff7679ccea944280d0866e90fd87d | 21,503 | cpp | C++ | src/assembler/RhsAssembler.cpp | ldXiao/polyfem | d4103af16979ff67d461a9ebe46a14bbc4dc8c7c | [
"MIT"
] | null | null | null | src/assembler/RhsAssembler.cpp | ldXiao/polyfem | d4103af16979ff67d461a9ebe46a14bbc4dc8c7c | [
"MIT"
] | null | null | null | src/assembler/RhsAssembler.cpp | ldXiao/polyfem | d4103af16979ff67d461a9ebe46a14bbc4dc8c7c | [
"MIT"
] | null | null | null | #include <polyfem/RhsAssembler.hpp>
#include <polyfem/BoundarySampler.hpp>
#include <polyfem/LinearSolver.hpp>
// #include <polyfem/UIState.hpp>
#include <polyfem/Logger.hpp>
#include <Eigen/Sparse>
#ifdef USE_TBB
#include <tbb/parallel_for.h>
#include <tbb/task_scheduler_init.h>
#include <tbb/enumerable_thread_specific.h>
#endif
#include <iostream>
#include <map>
#include <memory>
namespace polyfem
{
namespace
{
class LocalThreadScalarStorage
{
public:
double val;
ElementAssemblyValues vals;
LocalThreadScalarStorage()
{
val = 0;
}
};
}
RhsAssembler::RhsAssembler(const Mesh &mesh, const int n_basis, const int size, const std::vector< ElementBases > &bases, const std::vector< ElementBases > &gbases, const std::string &formulation, const Problem &problem)
: mesh_(mesh), n_basis_(n_basis), size_(size), bases_(bases), gbases_(gbases), formulation_(formulation), problem_(problem)
{ }
void RhsAssembler::assemble(Eigen::MatrixXd &rhs, const double t) const
{
rhs = Eigen::MatrixXd::Zero(n_basis_ * size_, 1);
if(!problem_.is_rhs_zero())
{
Eigen::MatrixXd rhs_fun;
const int n_elements = int(bases_.size());
ElementAssemblyValues vals;
for(int e = 0; e < n_elements; ++e)
{
vals.compute(e, mesh_.is_volume(), bases_[e], gbases_[e]);
const Quadrature &quadrature = vals.quadrature;
problem_.rhs(formulation_, vals.val, t, rhs_fun);
for(int d = 0; d < size_; ++d)
rhs_fun.col(d) = rhs_fun.col(d).array() * vals.det.array() * quadrature.weights.array();
const int n_loc_bases_ = int(vals.basis_values.size());
for(int i = 0; i < n_loc_bases_; ++i)
{
const AssemblyValues &v = vals.basis_values[i];
for(int d = 0; d < size_; ++d)
{
const double rhs_value = (rhs_fun.col(d).array() * v.val.array()).sum();
for(std::size_t ii = 0; ii < v.global.size(); ++ii)
rhs(v.global[ii].index*size_+d) += rhs_value * v.global[ii].val;
}
}
}
}
}
void RhsAssembler::initial_solution(Eigen::MatrixXd &sol) const
{
time_bc([&](const Eigen::MatrixXd&pts, Eigen::MatrixXd&val){ problem_.initial_solution(pts, val);}, sol);
}
void RhsAssembler::initial_velocity(Eigen::MatrixXd &sol) const
{
time_bc([&](const Eigen::MatrixXd&pts, Eigen::MatrixXd&val){ problem_.initial_velocity(pts, val);}, sol);
}
void RhsAssembler::initial_acceleration(Eigen::MatrixXd &sol) const
{
time_bc([&](const Eigen::MatrixXd&pts, Eigen::MatrixXd&val){ problem_.initial_acceleration(pts, val);}, sol);
}
void RhsAssembler::time_bc(const std::function<void(const Eigen::MatrixXd&, Eigen::MatrixXd&)> &fun,Eigen::MatrixXd &sol) const
{
sol = Eigen::MatrixXd::Zero(n_basis_ * size_, 1);
Eigen::MatrixXd loc_sol;
const int n_elements = int(bases_.size());
ElementAssemblyValues vals;
for(int e = 0; e < n_elements; ++e)
{
vals.compute(e, mesh_.is_volume(), bases_[e], gbases_[e]);
const Quadrature &quadrature = vals.quadrature;
//problem_.initial_solution(vals.val, loc_sol);
fun(vals.val, loc_sol);
for(int d = 0; d < size_; ++d)
loc_sol.col(d) = loc_sol.col(d).array() * vals.det.array() * quadrature.weights.array();
const int n_loc_bases_ = int(vals.basis_values.size());
for(int i = 0; i < n_loc_bases_; ++i)
{
const AssemblyValues &v = vals.basis_values[i];
for(int d = 0; d < size_; ++d)
{
const double sol_value = (loc_sol.col(d).array() * v.val.array()).sum();
for(std::size_t ii = 0; ii < v.global.size(); ++ii)
sol(v.global[ii].index*size_+d) += sol_value * v.global[ii].val;
}
}
}
}
void RhsAssembler::set_bc(
const std::function<void(const Eigen::MatrixXi&, const Eigen::MatrixXd&, const Eigen::MatrixXd&, Eigen::MatrixXd &)> &df,
const std::function<void(const Eigen::MatrixXi&, const Eigen::MatrixXd&, const Eigen::MatrixXd&, Eigen::MatrixXd &)> &nf,
const std::vector< LocalBoundary > &local_boundary, const std::vector<int> &bounday_nodes, const int resolution, const std::vector< LocalBoundary > &local_neumann_boundary, Eigen::MatrixXd &rhs) const
{
const int n_el=int(bases_.size());
Eigen::MatrixXd uv, samples, gtmp, rhs_fun;
Eigen::VectorXi global_primitive_ids;
int index = 0;
std::vector<int> indices; indices.reserve(n_el*10);
// std::map<int, int> global_index_to_col;
long total_size = 0;
Eigen::Matrix<bool, Eigen::Dynamic, 1> is_boundary(n_basis_); is_boundary.setConstant(false);
Eigen::VectorXi global_index_to_col(n_basis_); global_index_to_col.setConstant(-1);
const int actual_dim = problem_.is_scalar() ? 1 : mesh_.dimension();
// assert((bounday_nodes.size()/actual_dim)*actual_dim == bounday_nodes.size());
for(int b : bounday_nodes)
is_boundary[b/actual_dim] = true;
for(const auto &lb : local_boundary)
{
const int e = lb.element_id();
bool has_samples = sample_boundary(lb, resolution, true, uv, samples, global_primitive_ids);
if(!has_samples)
continue;
const ElementBases &bs = bases_[e];
const int n_local_bases = int(bs.bases.size());
total_size += samples.rows();
for(int j = 0; j < n_local_bases; ++j)
{
const Basis &b=bs.bases[j];
for(std::size_t ii = 0; ii < b.global().size(); ++ii)
{
//pt found
// if(std::find(bounday_nodes.begin(), bounday_nodes.end(), size_ * b.global()[ii].index) != bounday_nodes.end())
if(is_boundary[b.global()[ii].index])
{
//if(global_index_to_col.find( b.global()[ii].index ) == global_index_to_col.end())
if(global_index_to_col(b.global()[ii].index) == -1)
{
// global_index_to_col[b.global()[ii].index] = index++;
global_index_to_col(b.global()[ii].index) = index++;
indices.push_back(b.global()[ii].index);
assert(indices.size() == size_t(index));
}
}
}
}
}
// Eigen::MatrixXd global_mat = Eigen::MatrixXd::Zero(total_size, indices.size());
Eigen::MatrixXd global_rhs = Eigen::MatrixXd::Zero(total_size, size_);
const long buffer_size = total_size * long(indices.size());
std::vector< Eigen::Triplet<double> > entries, entries_t;
// entries.reserve(buffer_size);
// entries_t.reserve(buffer_size);
index = 0;
int global_counter = 0;
Eigen::MatrixXd mapped;
std::vector<AssemblyValues> tmp_val;
for(const auto &lb : local_boundary)
{
const int e = lb.element_id();
bool has_samples = sample_boundary(lb, resolution, false, uv, samples, global_primitive_ids);
if(!has_samples)
continue;
const ElementBases &bs = bases_[e];
const ElementBases &gbs = gbases_[e];
const int n_local_bases = int(bs.bases.size());
gbs.eval_geom_mapping(samples, mapped);
bs.evaluate_bases(samples, tmp_val);
for(int j = 0; j < n_local_bases; ++j)
{
const Basis &b=bs.bases[j];
const auto &tmp = tmp_val[j].val;
for(std::size_t ii = 0; ii < b.global().size(); ++ii)
{
// auto item = global_index_to_col.find(b.global()[ii].index);
// if(item != global_index_to_col.end()){
auto item = global_index_to_col(b.global()[ii].index);
if(item != -1){
for(int k = 0; k < int(tmp.size()); ++k)
{
// entries.push_back(Eigen::Triplet<double>(global_counter+k, item->second, tmp(k, j) * b.global()[ii].val));
// entries_t.push_back(Eigen::Triplet<double>(item->second, global_counter+k, tmp(k, j) * b.global()[ii].val));
entries.push_back(Eigen::Triplet<double>(global_counter+k, item, tmp(k) * b.global()[ii].val));
entries_t.push_back(Eigen::Triplet<double>(item, global_counter+k, tmp(k) * b.global()[ii].val));
}
// global_mat.block(global_counter, item->second, tmp.size(), 1) = tmp;
}
}
}
// problem_.bc(mesh_, global_primitive_ids, mapped, t, rhs_fun);
df(global_primitive_ids, uv, mapped, rhs_fun);
global_rhs.block(global_counter, 0, rhs_fun.rows(), rhs_fun.cols()) = rhs_fun;
global_counter += rhs_fun.rows();
//UIState::ui_state().debug_data().add_points(mapped, Eigen::MatrixXd::Constant(1, 3, 0));
//Eigen::MatrixXd asd(mapped.rows(), 3);
//asd.col(0)=mapped.col(0);
//asd.col(1)=mapped.col(1);
//asd.col(2)=rhs_fun;
//UIState::ui_state().debug_data().add_points(asd, Eigen::MatrixXd::Constant(1, 3, 0));
}
assert(global_counter == total_size);
if(total_size > 0)
{
const double mmin = global_rhs.minCoeff();
const double mmax = global_rhs.maxCoeff();
if(fabs(mmin) < 1e-8 && fabs(mmax) < 1e-8)
{
// std::cout<<"is all zero, skipping"<<std::endl;
for(size_t i = 0; i < indices.size(); ++i){
for(int d = 0; d < size_; ++d){
if(problem_.all_dimentions_dirichelt() || std::find(bounday_nodes.begin(), bounday_nodes.end(), indices[i]*size_+d) != bounday_nodes.end())
rhs(indices[i]*size_+d) = 0;
}
}
}
else
{
StiffnessMatrix mat(int(total_size), int(indices.size()));
mat.setFromTriplets(entries.begin(), entries.end());
StiffnessMatrix mat_t(int(indices.size()), int(total_size));
mat_t.setFromTriplets(entries_t.begin(), entries_t.end());
StiffnessMatrix A = mat_t * mat;
Eigen::MatrixXd b = mat_t * global_rhs;
Eigen::MatrixXd coeffs(b.rows(), b.cols());
json params = {
{"mtype", -2}, // matrix type for Pardiso (2 = SPD)
// {"max_iter", 0}, // for iterative solvers
// {"tolerance", 1e-9}, // for iterative solvers
};
// auto solver = LinearSolver::create("", "");
auto solver = LinearSolver::create(LinearSolver::defaultSolver(), LinearSolver::defaultPrecond());
solver->setParameters(params);
solver->analyzePattern(A);
solver->factorize(A);
for(long i = 0; i < b.cols(); ++i){
solver->solve(b.col(i), coeffs.col(i));
}
logger().trace("RHS solve error {}", (A*coeffs-b).norm());
for(long i = 0; i < coeffs.rows(); ++i){
for(int d = 0; d < size_; ++d){
if(problem_.all_dimentions_dirichelt() || std::find(bounday_nodes.begin(), bounday_nodes.end(), indices[i]*size_+d) != bounday_nodes.end())
rhs(indices[i]*size_+d) = coeffs(i, d);
}
}
}
}
//Neumann
Eigen::MatrixXd points;
Eigen::VectorXd weights;
ElementAssemblyValues vals;
for(const auto &lb : local_neumann_boundary)
{
const int e = lb.element_id();
bool has_samples = boundary_quadrature(lb, resolution, false, uv, points, weights, global_primitive_ids);
if(!has_samples)
continue;
const ElementBases &gbs = gbases_[e];
const ElementBases &bs = bases_[e];
vals.compute(e, mesh_.is_volume(), points, bs, gbs);
// problem_.neumann_bc(mesh_, global_primitive_ids, vals.val, t, rhs_fun);
nf(global_primitive_ids, uv, vals.val, rhs_fun);
// UIState::ui_state().debug_data().add_points(vals.val, Eigen::RowVector3d(0,1,0));
for(int d = 0; d < size_; ++d)
rhs_fun.col(d) = rhs_fun.col(d).array() * weights.array();
for(int i = 0; i < lb.size(); ++i)
{
const int primitive_global_id = lb.global_primitive_id(i);
const auto nodes = bs.local_nodes_for_primitive(primitive_global_id, mesh_);
for(long n = 0; n < nodes.size(); ++n)
{
// const auto &b = bs.bases[nodes(n)];
const AssemblyValues &v = vals.basis_values[nodes(n)];
for(int d = 0; d < size_; ++d)
{
const double rhs_value = (rhs_fun.col(d).array() * v.val.array()).sum();
for(size_t g = 0; g < v.global.size(); ++g)
{
const int g_index = v.global[g].index*size_+d;
const bool is_neumann = std::find(bounday_nodes.begin(), bounday_nodes.end(), g_index ) == bounday_nodes.end();
if(is_neumann){
rhs(g_index) += rhs_value * v.global[g].val;
// UIState::ui_state().debug_data().add_points(v.global[g].node, Eigen::RowVector3d(1,0,0));
}
// else
// std::cout<<"skipping "<<g_index<<" "<<rhs_value * v.global[g].val<<std::endl;
}
}
}
}
}
}
void RhsAssembler::set_bc(const std::vector< LocalBoundary > &local_boundary, const std::vector<int> &bounday_nodes, const int resolution, const std::vector< LocalBoundary > &local_neumann_boundary, Eigen::MatrixXd &rhs, const double t) const
{
set_bc(
[&](const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, Eigen::MatrixXd &val){ problem_.bc(mesh_, global_ids, uv, pts, t, val);},
[&](const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, Eigen::MatrixXd &val){ problem_.neumann_bc(mesh_, global_ids, uv, pts, t, val);},
local_boundary, bounday_nodes, resolution, local_neumann_boundary, rhs);
}
void RhsAssembler::set_velocity_bc(const std::vector< LocalBoundary > &local_boundary, const std::vector<int> &bounday_nodes, const int resolution, const std::vector< LocalBoundary > &local_neumann_boundary, Eigen::MatrixXd &rhs, const double t) const
{
set_bc(
[&](const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, Eigen::MatrixXd &val){ problem_.velocity_bc(mesh_, global_ids, uv, pts, t, val);},
[&](const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, Eigen::MatrixXd &val){ problem_.neumann_velocity_bc(mesh_, global_ids, uv, pts, t, val);},
local_boundary, bounday_nodes, resolution, local_neumann_boundary, rhs);
}
void RhsAssembler::set_acceleration_bc(const std::vector< LocalBoundary > &local_boundary, const std::vector<int> &bounday_nodes, const int resolution, const std::vector< LocalBoundary > &local_neumann_boundary, Eigen::MatrixXd &rhs, const double t) const
{
set_bc(
[&](const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, Eigen::MatrixXd &val){ problem_.acceleration_bc(mesh_, global_ids, uv, pts, t, val);},
[&](const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, Eigen::MatrixXd &val){ problem_.neumann_acceleration_bc(mesh_, global_ids, uv, pts, t, val);},
local_boundary, bounday_nodes, resolution, local_neumann_boundary, rhs);
}
void RhsAssembler::compute_energy_grad(const std::vector< LocalBoundary > &local_boundary, const std::vector<int> &bounday_nodes, const int resolution, const std::vector< LocalBoundary > &local_neumann_boundary, const Eigen::MatrixXd &final_rhs, const double t, Eigen::MatrixXd &rhs) const
{
if(problem_.is_linear_in_time()){
if(problem_.is_time_dependent())
rhs = final_rhs;
else
rhs = final_rhs * t;
}
else
{
assemble(rhs, t);
rhs *= -1;
set_bc(local_boundary, bounday_nodes, resolution, local_neumann_boundary, rhs, t);
}
}
double RhsAssembler::compute_energy(const Eigen::MatrixXd &displacement, const std::vector< LocalBoundary > &local_neumann_boundary, const int resolution, const double t) const
{
Eigen::Matrix<double, Eigen::Dynamic, 1, 0, 3, 1> local_displacement(size_);
double res = 0;
Eigen::MatrixXd forces;
if(!problem_.is_rhs_zero())
{
#ifdef USE_TBB
typedef tbb::enumerable_thread_specific< LocalThreadScalarStorage > LocalStorage;
LocalStorage storages((LocalThreadScalarStorage()));
#else
LocalThreadScalarStorage loc_storage;
#endif
const int n_bases = int(bases_.size());
#ifdef USE_TBB
tbb::parallel_for( tbb::blocked_range<int>(0, n_bases), [&](const tbb::blocked_range<int> &r) {
LocalStorage::reference loc_storage = storages.local();
for (int e = r.begin(); e != r.end(); ++e) {
#else
for(int e=0; e < n_bases; ++e) {
#endif
ElementAssemblyValues &vals = loc_storage.vals;
vals.compute(e, mesh_.is_volume(), bases_[e], gbases_[e]);
const Quadrature &quadrature = vals.quadrature;
const Eigen::VectorXd da = vals.det.array() * quadrature.weights.array();
problem_.rhs(formulation_, vals.val, t, forces);
assert(forces.rows() == da.size());
assert(forces.cols() == size_);
for(long p = 0; p < da.size(); ++p)
{
local_displacement.setZero();
for(size_t i = 0; i < vals.basis_values.size(); ++i)
{
const auto &bs = vals.basis_values[i];
assert(bs.val.size() == da.size());
const double b_val = bs.val(p);
for(int d = 0; d < size_; ++d)
{
for(std::size_t ii = 0; ii < bs.global.size(); ++ii)
{
local_displacement(d) += (bs.global[ii].val * b_val) * displacement(bs.global[ii].index*size_ + d);
}
}
}
for(int d = 0; d < size_; ++d)
loc_storage.val += forces(p, d) * local_displacement(d) * da(p);
// res += forces(p, d) * local_displacement(d) * da(p);
}
#ifdef USE_TBB
}});
#else
}
#endif
#ifdef USE_TBB
for (LocalStorage::iterator i = storages.begin(); i != storages.end(); ++i)
{
res += i->val;
}
#else
res = loc_storage.val;
#endif
}
ElementAssemblyValues vals;
//Neumann
Eigen::MatrixXd points, uv;
Eigen::VectorXd weights;
Eigen::VectorXi global_primitive_ids;
for(const auto &lb : local_neumann_boundary)
{
const int e = lb.element_id();
bool has_samples = boundary_quadrature(lb, resolution, false, uv, points, weights, global_primitive_ids);
if(!has_samples)
continue;
const ElementBases &gbs = gbases_[e];
const ElementBases &bs = bases_[e];
vals.compute(e, mesh_.is_volume(), points, bs, gbs);
problem_.neumann_bc(mesh_, global_primitive_ids, uv, vals.val, t, forces);
// UIState::ui_state().debug_data().add_points(vals.val, Eigen::RowVector3d(1,0,0));
for(long p = 0; p < weights.size(); ++p)
{
local_displacement.setZero();
for(size_t i = 0; i < vals.basis_values.size(); ++i)
{
const auto &vv = vals.basis_values[i];
assert(vv.val.size() == weights.size());
const double b_val = vv.val(p);
for(int d = 0; d < size_; ++d)
{
for(std::size_t ii = 0; ii < vv.global.size(); ++ii)
{
local_displacement(d) += (vv.global[ii].val * b_val) * displacement(vv.global[ii].index*size_ + d);
}
}
}
for(int d = 0; d < size_; ++d)
res -= forces(p, d) * local_displacement(d) * weights(p);
}
}
return res;
}
bool RhsAssembler::boundary_quadrature(const LocalBoundary &local_boundary, const int order, const bool skip_computation, Eigen::MatrixXd &uv, Eigen::MatrixXd &points, Eigen::VectorXd &weights, Eigen::VectorXi &global_primitive_ids) const
{
uv.resize(0, 0);
points.resize(0, 0);
weights.resize(0);
global_primitive_ids.resize(0);
for(int i = 0; i < local_boundary.size(); ++i)
{
const int gid = local_boundary.global_primitive_id(i);
Eigen::MatrixXd tmp_p, tmp_uv;
Eigen::VectorXd tmp_w;
switch(local_boundary.type())
{
case BoundaryType::TriLine: BoundarySampler::quadrature_for_tri_edge(local_boundary[i], order, gid, mesh_, tmp_uv, tmp_p, tmp_w); break;
case BoundaryType::QuadLine: BoundarySampler::quadrature_for_quad_edge(local_boundary[i], order, gid, mesh_, tmp_uv, tmp_p, tmp_w); break;
case BoundaryType::Quad: BoundarySampler::quadrature_for_quad_face(local_boundary[i], order, gid, mesh_, tmp_uv, tmp_p, tmp_w); break;
case BoundaryType::Tri: BoundarySampler::quadrature_for_tri_face(local_boundary[i], order, gid, mesh_, tmp_uv, tmp_p, tmp_w); break;
case BoundaryType::Invalid: assert(false); break;
default: assert(false);
}
uv.conservativeResize(uv.rows() + tmp_uv.rows(), tmp_uv.cols());
uv.bottomRows(tmp_uv.rows()) = tmp_uv;
points.conservativeResize(points.rows() + tmp_p.rows(), tmp_p.cols());
points.bottomRows(tmp_p.rows()) = tmp_p;
weights.conservativeResize(weights.rows() + tmp_w.rows(), tmp_w.cols());
weights.bottomRows(tmp_w.rows()) = tmp_w;
global_primitive_ids.conservativeResize(global_primitive_ids.rows() + tmp_p.rows());
global_primitive_ids.bottomRows(tmp_p.rows()).setConstant(gid);
}
assert(uv.rows() == global_primitive_ids.size());
assert(points.rows() == global_primitive_ids.size());
assert(weights.size() == global_primitive_ids.size());
return true;
}
bool RhsAssembler::sample_boundary(const LocalBoundary &local_boundary, const int n_samples, const bool skip_computation, Eigen::MatrixXd &uv, Eigen::MatrixXd &samples, Eigen::VectorXi &global_primitive_ids) const
{
uv.resize(0, 0);
samples.resize(0, 0);
global_primitive_ids.resize(0);
for(int i = 0; i < local_boundary.size(); ++i)
{
Eigen::MatrixXd tmp, tmp_uv;
switch(local_boundary.type())
{
case BoundaryType::TriLine: BoundarySampler::sample_parametric_tri_edge(local_boundary[i], n_samples, tmp_uv, tmp); break;
case BoundaryType::QuadLine: BoundarySampler::sample_parametric_quad_edge(local_boundary[i], n_samples, tmp_uv, tmp); break;
case BoundaryType::Quad: BoundarySampler::sample_parametric_quad_face(local_boundary[i], n_samples, tmp_uv, tmp); break;
case BoundaryType::Tri: BoundarySampler::sample_parametric_tri_face(local_boundary[i], n_samples, tmp_uv, tmp); break;
case BoundaryType::Invalid: assert(false); break;
default: assert(false);
}
uv.conservativeResize(uv.rows() + tmp_uv.rows(), tmp_uv.cols());
uv.bottomRows(tmp_uv.rows()) = tmp_uv;
samples.conservativeResize(samples.rows() + tmp.rows(), tmp.cols());
samples.bottomRows(tmp.rows()) = tmp;
global_primitive_ids.conservativeResize(global_primitive_ids.rows() + tmp.rows());
global_primitive_ids.bottomRows(tmp.rows()).setConstant(local_boundary.global_primitive_id(i));
}
assert(uv.rows() == global_primitive_ids.size());
assert(samples.rows() == global_primitive_ids.size());
return true;
}
}
| 34.794498 | 290 | 0.668837 | ldXiao |
2325a5a23508c0d5cb259beb42feeaea35917197 | 5,274 | cpp | C++ | src/FrenetOptimalTrajectory/fot_wrapper.cpp | erdos-project/frenet-optimal-trajectory-planner | ba0cb5662a0e2ea668b1c2b2951c0f6b84f44f5b | [
"Apache-2.0"
] | null | null | null | src/FrenetOptimalTrajectory/fot_wrapper.cpp | erdos-project/frenet-optimal-trajectory-planner | ba0cb5662a0e2ea668b1c2b2951c0f6b84f44f5b | [
"Apache-2.0"
] | null | null | null | src/FrenetOptimalTrajectory/fot_wrapper.cpp | erdos-project/frenet-optimal-trajectory-planner | ba0cb5662a0e2ea668b1c2b2951c0f6b84f44f5b | [
"Apache-2.0"
] | 1 | 2020-03-07T01:49:50.000Z | 2020-03-07T01:49:50.000Z | #include "FrenetOptimalTrajectory.h"
#include "FrenetPath.h"
#include "py_cpp_struct.h"
#include "CubicSpline2D.h"
#include "utils.h"
#include <stddef.h>
#include <vector>
using namespace std;
// C++ wrapper to expose the FrenetOptimalTrajectory class to python
extern "C" {
// Compute the frenet optimal trajectory given initial conditions
// in frenet space.
//
// Arguments:
// fot_ic (FrenetInitialConditions *):
// struct ptr containing relevant initial conditions to compute
// Frenet Optimal Trajectory
// fot_hp (FrenetHyperparameters *):
// struct ptr containing relevant hyperparameters to compute
// Frenet Optimal Trajectory
// x_path, y_path, speeds (double *):
// ptr to storage arrays for Frenet Optimal Trajectory
// params (double *):
// ptr to store initial conditions for debugging
//
// Returns:
// 1 if successful, 0 if failure
// Also stores the Frenet Optimal Trajectory into x_path, y_path,
// speeds if it exists
void run_fot(
FrenetInitialConditions *fot_ic, FrenetHyperparameters *fot_hp,
FrenetReturnValues *fot_rv
) {
FrenetOptimalTrajectory fot = FrenetOptimalTrajectory(fot_ic, fot_hp);
FrenetPath* best_frenet_path = fot.getBestPath();
if (best_frenet_path && !best_frenet_path->x.empty()){
fot_rv->success = 1;
fot_rv->path_length = std::min(best_frenet_path->x.size(), MAX_PATH_LENGTH);
for (size_t i = 0; i < fot_rv->path_length; i++) {
fot_rv->x_path[i] = best_frenet_path->x[i];
fot_rv->y_path[i] = best_frenet_path->y[i];
fot_rv->speeds[i] = best_frenet_path->s_d[i];
fot_rv->ix[i] = best_frenet_path->ix[i];
fot_rv->iy[i] = best_frenet_path->iy[i];
fot_rv->iyaw[i] = best_frenet_path->iyaw[i];
fot_rv->d[i] = best_frenet_path->d[i];
fot_rv->s[i] = best_frenet_path->s[i];
fot_rv->speeds_x[i] = cos(best_frenet_path->yaw[i]) *
fot_rv->speeds[i];
fot_rv->speeds_y[i] = sin(best_frenet_path->yaw[i]) *
fot_rv->speeds[i];
}
// store info for debug
fot_rv->params[0] = best_frenet_path->s[1];
fot_rv->params[1] = best_frenet_path->s_d[1];
fot_rv->params[2] = best_frenet_path->d[1];
fot_rv->params[3] = best_frenet_path->d_d[1];
fot_rv->params[4] = best_frenet_path->d_dd[1];
// store costs for logging
fot_rv->costs[0] = best_frenet_path->c_lateral_deviation;
fot_rv->costs[1] = best_frenet_path->c_lateral_velocity;
fot_rv->costs[2] = best_frenet_path->c_lateral_acceleration;
fot_rv->costs[3] = best_frenet_path->c_lateral_jerk;
fot_rv->costs[4] = best_frenet_path->c_lateral;
fot_rv->costs[5] = best_frenet_path->c_longitudinal_acceleration;
fot_rv->costs[6] = best_frenet_path->c_longitudinal_jerk;
fot_rv->costs[7] = best_frenet_path->c_time_taken;
fot_rv->costs[8] = best_frenet_path->c_end_speed_deviation;
fot_rv->costs[9] = best_frenet_path->c_longitudinal;
fot_rv->costs[10] = best_frenet_path->c_inv_dist_to_obstacles;
fot_rv->costs[11] = best_frenet_path->cf;
}
}
// Convert the initial conditions from cartesian space to frenet space
void to_frenet_initial_conditions(
double s0, double x, double y, double vx,
double vy, double forward_speed, double* xp, double* yp, int np,
double* initial_conditions
) {
vector<double> wx (xp, xp + np);
vector<double> wy (yp, yp + np);
CubicSpline2D* csp = new CubicSpline2D(wx, wy);
// get distance from car to spline and projection
double s = csp->find_s(x, y, s0);
double distance = norm(csp->calc_x(s) - x, csp->calc_y(s) - y);
tuple<double, double> bvec ((csp->calc_x(s) - x) / distance,
(csp->calc_y(s) - y) / distance);
// normal spline vector
double x0 = csp->calc_x(s0);
double y0 = csp->calc_y(s0);
double x1 = csp->calc_x(s0 + 2);
double y1 = csp->calc_y(s0 + 2);
// unit vector orthog. to spline
tuple<double, double> tvec (y1-y0, -(x1-x0));
as_unit_vector(tvec);
// compute tangent / normal car vectors
tuple<double, double> fvec (vx, vy);
as_unit_vector(fvec);
// get initial conditions in frenet frame
initial_conditions[0] = s; // current longitudinal position s
initial_conditions[1] = forward_speed; // speed [m/s]
// lateral position c_d [m]
initial_conditions[2] = copysign(distance, dot(tvec, bvec));
// lateral speed c_d_d [m/s]
initial_conditions[3] = -forward_speed * dot(tvec, fvec);
initial_conditions[4] = 0.0; // lateral acceleration c_d_dd [m/s^2]
// TODO: add lateral acceleration when CARLA 9.7 is patched (IMU)
delete csp;
}
}
| 42.532258 | 88 | 0.595184 | erdos-project |
23266ff1a1d3228c045af3d71ae0a5d5c7e6476d | 2,938 | cpp | C++ | src/xercesc/xinclude/XIncludeDOMDocumentProcessor.cpp | rajesh-ibm-power/xerces-c | bee41e87651b935130ed76015fe4c38507f6b32f | [
"Apache-2.0"
] | 115 | 2015-03-17T16:22:59.000Z | 2022-03-09T12:06:59.000Z | src/xercesc/xinclude/XIncludeDOMDocumentProcessor.cpp | rajesh-ibm-power/xerces-c | bee41e87651b935130ed76015fe4c38507f6b32f | [
"Apache-2.0"
] | 25 | 2018-11-19T14:10:23.000Z | 2022-03-12T17:18:24.000Z | src/xercesc/xinclude/XIncludeDOMDocumentProcessor.cpp | rajesh-ibm-power/xerces-c | bee41e87651b935130ed76015fe4c38507f6b32f | [
"Apache-2.0"
] | 122 | 2015-03-16T11:44:23.000Z | 2022-03-15T12:33:22.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id$
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/xinclude/XIncludeDOMDocumentProcessor.hpp>
#include <xercesc/xinclude/XIncludeUtils.hpp>
#include <xercesc/dom/DOM.hpp>
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/framework/XMLErrorReporter.hpp>
namespace XERCES_CPP_NAMESPACE {
DOMDocument *
XIncludeDOMDocumentProcessor::doXIncludeDOMProcess(const DOMDocument * const source, XMLErrorReporter *errorHandler, XMLEntityHandler* entityResolver /*=NULL*/){
XIncludeUtils xiu(errorHandler);
DOMImplementation* impl = source->getImplementation();
DOMDocument *xincludedDocument = impl->createDocument();
try
{
/* set up the declaration etc of the output document to match the source */
xincludedDocument->setDocumentURI( source->getDocumentURI());
xincludedDocument->setXmlStandalone( source->getXmlStandalone());
xincludedDocument->setXmlVersion( source->getXmlVersion());
/* copy entire source document into the xincluded document. Xincluded document can
then be modified in place */
DOMNode *child = source->getFirstChild();
for (; child != NULL; child = child->getNextSibling()){
if (child->getNodeType() == DOMNode::DOCUMENT_TYPE_NODE){
/* I am simply ignoring these at the moment */
continue;
}
DOMNode *newNode = xincludedDocument->importNode(child, true);
xincludedDocument->appendChild(newNode);
}
DOMNode *docNode = xincludedDocument->getDocumentElement();
/* parse and include the document node */
xiu.parseDOMNodeDoingXInclude(docNode, xincludedDocument, entityResolver);
xincludedDocument->normalizeDocument();
}
catch(const XMLErrs::Codes)
{
xincludedDocument->release();
return NULL;
}
catch(...)
{
xincludedDocument->release();
throw;
}
return xincludedDocument;
}
}
| 36.271605 | 161 | 0.65725 | rajesh-ibm-power |
23288f4a73b963314c78ee1f635d01b952a59ca0 | 151 | cpp | C++ | archive/1/cukierki.cpp | Aleshkev/algoritmika | fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189 | [
"MIT"
] | 2 | 2019-05-04T09:37:09.000Z | 2019-05-22T18:07:28.000Z | archive/1/cukierki.cpp | Aleshkev/algoritmika | fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189 | [
"MIT"
] | null | null | null | archive/1/cukierki.cpp | Aleshkev/algoritmika | fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef int I;
int main()
{
string s;
cin >> s;
cout << s << s << '\n';
return 0;
}
| 9.4375 | 27 | 0.503311 | Aleshkev |
23298054ce30a578a9d7d5169992e6122c39b610 | 1,916 | cpp | C++ | Sources/Particles/Particle.cpp | CarysT/Acid | ab81fd13ab288ceaa152e0f64f6d97daf032fc19 | [
"MIT"
] | 977 | 2019-05-23T01:53:42.000Z | 2022-03-30T04:22:41.000Z | Sources/Particles/Particle.cpp | CarysT/Acid | ab81fd13ab288ceaa152e0f64f6d97daf032fc19 | [
"MIT"
] | 44 | 2019-06-02T17:30:32.000Z | 2022-03-27T14:22:40.000Z | Sources/Particles/Particle.cpp | CarysT/Acid | ab81fd13ab288ceaa152e0f64f6d97daf032fc19 | [
"MIT"
] | 121 | 2019-05-23T05:18:01.000Z | 2022-03-27T21:59:23.000Z | #include "Particle.hpp"
#include "Scenes/Scenes.hpp"
namespace acid {
static constexpr float FADE_TIME = 1.0f;
Particle::Particle(std::shared_ptr<ParticleType> particleType, const Vector3f &position, const Vector3f &velocity, float lifeLength, float stageCycles,
float rotation, float scale, float gravityEffect) :
particleType(std::move(particleType)),
position(position),
velocity(velocity),
lifeLength(lifeLength),
stageCycles(stageCycles),
rotation(rotation),
scale(scale),
gravityEffect(gravityEffect) {
}
void Particle::Update() {
auto delta = Engine::Get()->GetDelta().AsSeconds();
velocity.y += -10.0f * gravityEffect * delta;
change = velocity;
change *= delta;
position += change;
elapsedTime += delta;
if (elapsedTime > lifeLength - FADE_TIME)
transparency -= delta / FADE_TIME;
if (!IsAlive() || !Scenes::Get()->GetCamera())
return;
auto cameraToParticle = Scenes::Get()->GetCamera()->GetPosition() - position;
distanceToCamera = cameraToParticle.LengthSquared();
auto lifeFactor = stageCycles * elapsedTime / lifeLength;
if (!particleType->GetImage())
return;
auto stageCount = static_cast<int32_t>(std::pow(particleType->GetNumberOfRows(), 2));
auto atlasProgression = lifeFactor * stageCount;
auto index1 = static_cast<int32_t>(std::floor(atlasProgression));
auto index2 = index1 < stageCount - 1 ? index1 + 1 : index1;
imageBlendFactor = std::fmod(atlasProgression, 1.0f);
imageOffset1 = CalculateImageOffset(index1);
imageOffset2 = CalculateImageOffset(index2);
}
bool Particle::operator<(const Particle &rhs) const {
return distanceToCamera > rhs.distanceToCamera;
}
Vector2f Particle::CalculateImageOffset(int32_t index) const {
auto column = index % particleType->GetNumberOfRows();
auto row = index / particleType->GetNumberOfRows();
return Vector2f(static_cast<float>(column), static_cast<float>(row)) / particleType->GetNumberOfRows();
}
}
| 29.9375 | 151 | 0.745825 | CarysT |
2329d0e1a90927cda11ef0b45fe8cad1d7823b46 | 13,179 | cc | C++ | manager/calibrateProcesses.cc | yahoo/Pluton | 82bbab17c0013d87063b398ec777d5977f353d0a | [
"MIT"
] | 8 | 2015-05-22T21:27:17.000Z | 2017-03-19T06:07:41.000Z | manager/calibrateProcesses.cc | YahooArchive/Pluton | 82bbab17c0013d87063b398ec777d5977f353d0a | [
"MIT"
] | null | null | null | manager/calibrateProcesses.cc | YahooArchive/Pluton | 82bbab17c0013d87063b398ec777d5977f353d0a | [
"MIT"
] | 6 | 2015-10-16T08:40:00.000Z | 2016-11-14T06:48:09.000Z | /*
Copyright (c) 2010, Yahoo! Inc. All rights reserved.
Redistribution and use of this software in source and binary forms, with or
without modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
* Neither the name of Yahoo! Inc. nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission of Yahoo! Inc.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include <iostream>
#include <sys/time.h>
#include <sys/types.h>
#include <signal.h>
#include "debug.h"
#include "logging.h"
#include "util.h"
#include "pidMap.h"
#include "processExitReason.h"
#include "manager.h"
#include "service.h"
#include "process.h"
using namespace std;
//////////////////////////////////////////////////////////////////////
// Determine how many processes should be running for a given service
// and adjust accordingly.
//
// Calibration is called for the following reasons:
//
// o) A serviceSocket has a connect request and no processes are
// running (the service is in the initial state).
//
// o) A process has sent a report via the reportingChannel
//
// o) The service has timed out waiting for a report
//
// o) A process has exited
//////////////////////////////////////////////////////////////////////
void
service::calibrateProcesses(const char* why, int listenBacklog,
bool decreaseOkFlag, bool increaseToMinimumOkFlag)
{
if (debug::calibrate()) DBGPRT << "calibrate: " << _name << ":" << why
<< " do=" << decreaseOkFlag << " io=" << increaseToMinimumOkFlag
<< endl;
//////////////////////////////////////////////////////////////////////
// If we need to ramp up to minimum, do that and return
//////////////////////////////////////////////////////////////////////
if (increaseToMinimumOkFlag && (_activeProcessCount < _config.minimumProcesses)) {
int pc = _config.minimumProcesses - _activeProcessCount;
while (pc-- > 0) createProcess("createMinimum", false);
return;
}
++_calibrateSamples;
_currListenBacklog += listenBacklog;
//////////////////////////////////////////////////////////////////////
// Only check for algorithmic changes periodically, so that activity
// times and counters aren't too granular.
//////////////////////////////////////////////////////////////////////
struct timeval now;
gettimeofday(&now, 0);
bool doneOne = false;
int samplePeriod = now.tv_sec - _prevCalibrationTime;
// First the occupancy-base tests which roll counters, etc.
if (_nextCalibrationTime <= now.tv_sec) {
_currListenBacklog /= _calibrateSamples;
_calibrateSamples = 0;
// Always do "Up" as that does calibration calcs
doneOne = calibrateOccupancyUp(why, now, samplePeriod);
// Only do "Down" if "Up" didn't create a process
if (!doneOne && decreaseOkFlag && (_activeProcessCount > _config.minimumProcesses)) {
doneOne = calibrateOccupancyDown(why, now, samplePeriod);
}
// Roll all the values from current -> previous
_prevListenBacklog = _currListenBacklog;
_currListenBacklog = 0;
if (doneOne) {
_prevOccupancyByTime = _config.occupancyPercent; // That's our guess
}
else {
_prevOccupancyByTime = _currOccupancyByTime;
}
_prevCalibrationTime = now.tv_sec;
_nextCalibrationTime = now.tv_sec + minimumSamplePeriod;
_shmService.resetAggregateCounters();
_timeInProcess = 0;
_requestsCompleted = 0;
}
// Idle timeout is done every call if nothing else happened.
if (!doneOne && decreaseOkFlag) doneOne = calibrateIdleDown(why, now, samplePeriod);
}
//////////////////////////////////////////////////////////////////////
// Ramp up processes based on occupancy. Return true if at least one
// process was started.
//////////////////////////////////////////////////////////////////////
bool
service::calibrateOccupancyUp(const char* why, const struct timeval& now, int samplePeriod)
{
if (debug::calibrate()) DBGPRT << "calibrateOccUp: " << _name << ":" << why << endl;
//////////////////////////////////////////////////////////////////////
// Get active uSeconds and request count for this sample period.
//////////////////////////////////////////////////////////////////////
long long activeuSecs = _shmService.getActiveuSecs();
long requestCount = _shmService.getRequestCount();
//////////////////////////////////////////////////////////////////////
// Sanity check shared counters and timers. They can get trashed due
// to lock-less updates or memory stomping services.
//////////////////////////////////////////////////////////////////////
long activeSecs = activeuSecs / util::MICROSECOND;
if ( (activeSecs < 0) ||
(activeSecs > (minimumSamplePeriod * 2 * _activeProcessCount))) {
if (debug::calibrate()) DBGPRT << "no calibrate: " << _name
<< " " << activeSecs << " " << _activeProcessCount << endl;
return false;
}
//////////////////////////////////////////////////////////////////////
// Average out the backlog across the sample period
//////////////////////////////////////////////////////////////////////
if (_activeProcessCount > 0) {
_currOccupancyByTime = activeuSecs;
_currOccupancyByTime /= _activeProcessCount;
_currOccupancyByTime *= 100;
_currOccupancyByTime /= static_cast<float>(samplePeriod * util::MICROSECOND);
}
else {
_currOccupancyByTime = 0;
}
//////////////////////////////////////////////////////////////////////
// Use a moving average occupancy to smooth spikes
//////////////////////////////////////////////////////////////////////
_currOccupancyByTime = _currOccupancyByTime * 0.75 + _prevOccupancyByTime * 0.25;
_currListenBacklog = _currListenBacklog * 0.75 + _prevListenBacklog * 0.25;
if (debug::calibrate()) {
DBGPRT << "calibrateUp: " << _name << ":" << why << " sample=" << samplePeriod
<< " uSecs=" << activeuSecs << "/" << _timeInProcess
<< " reqs=" << requestCount << "/" << _requestsCompleted
<< " apc=" << _activeProcessCount << "/" << _childCount
<< " occ=" << (int) _currOccupancyByTime << "/" << (int) _prevOccupancyByTime
<< " LQ=" << _currListenBacklog << "/" << _prevListenBacklog
<< " targetO=" << _config.occupancyPercent
<< endl;
}
//////////////////////////////////////////////////////////////////////
// If more are needed, calculate how many more to get to the desired
// occupancy and start them up.
//////////////////////////////////////////////////////////////////////
if (_currOccupancyByTime <= _config.occupancyPercent) return false;
int shortFall = (int) _currOccupancyByTime - _config.occupancyPercent;
shortFall *= _activeProcessCount;
shortFall += 99; // Round % up
shortFall /= 100;
if (shortFall == 0) ++shortFall; // Make sure it's at least one
if (_currListenBacklog >= 1) ++shortFall; // These may overshoot since
if ((_prevListenBacklog >= 10) && (_prevListenBacklog >= 10)) {
shortFall += 5;
}
if (shortFall > (_config.maximumProcesses - _activeProcessCount)) {
shortFall = _config.maximumProcesses - _activeProcessCount;
}
if (logging::calibrate()) {
LOGPRT << "Calibrate Up: " << _name
<< " apc=" << _activeProcessCount
<< " currO=" << (int) _currOccupancyByTime
<< " prevO=" << (int) _prevOccupancyByTime
<< " currLQ=" << (int) _currListenBacklog
<< " prevLQ=" << (int) _prevListenBacklog
<< " shortfall=" << shortFall
<< endl;
}
while (shortFall-- > 0) {
if (!createProcess("createIncrease", false)) break;
}
return true; // Say we started some
}
//////////////////////////////////////////////////////////////////////
// Ramp down processes based on occupancy. Return true if at least one
// process was told to exit.
//
// Calculate what the new occupancy would be if a process were to be
// removed. The idea is that a process will only be removed if the new
// occupancy is still below the threshold. In other words, don't
// remove a process if the result is that next time through this code
// a process is started up.
//
// n=new, o=old, C=count, O=occupancy
// nO = oO * nC / (nC-1)
//////////////////////////////////////////////////////////////////////
bool
service::calibrateOccupancyDown(const char* why, const struct timeval& now, int samplePeriod)
{
if (debug::calibrate()) DBGPRT << "calibrateOccDown: " << _name << ":" << why << endl;
float new1Occupancy = _currOccupancyByTime;
new1Occupancy *= _activeProcessCount;
new1Occupancy /= (_activeProcessCount - 1);
float new2Occupancy = _prevOccupancyByTime;
new2Occupancy *= _activeProcessCount;
new2Occupancy /= (_activeProcessCount - 1);
if (debug::calibrate()) DBGPRT << "calibrateDown: " << _name
<< " new1Occ=" << new1Occupancy
<< " new2Occ=" << new2Occupancy
<< endl;
int lowerThreshold = _config.occupancyPercent - 5; // XX Hack
if ((new1Occupancy >= lowerThreshold) && (new2Occupancy >= lowerThreshold)) return false;
if (logging::calibrate()) {
LOGPRT << "Calibrate Down: " << _name
<< " apc=" << _activeProcessCount
<< " currO=" << (int) _currOccupancyByTime
<< " prevO=" << (int) _prevOccupancyByTime
<< " propCO=" << (int) new1Occupancy
<< " propPO=" << (int) new2Occupancy
<< endl;
}
removeOldestProcess(processExit::excessProcesses);
return true;
}
//////////////////////////////////////////////////////////////////////
// Idle timeout calibration only applies when no reports have been
// seen for the idle-timeout period and there is more than the
// configured minimum processes still running.
//////////////////////////////////////////////////////////////////////
bool
service::calibrateIdleDown(const char* why, const struct timeval& now, int samplePeriod)
{
if (debug::calibrate()) DBGPRT << "calibrateIdle: " << _config.idleTimeout
<< " apc=" << _activeProcessCount
<< " lp=" << _lastPerformanceReport
<< " now=" << now.tv_sec
<< endl;
if ((_config.idleTimeout == 0) || (_activeProcessCount <= _config.minimumProcesses)) {
return false;
}
if ((_lastPerformanceReport + _config.idleTimeout) > now.tv_sec) return false;
removeOldestProcess(processExit::idleTimeout);
return true;
}
//////////////////////////////////////////////////////////////////////
// Create a new process for this service. Return true if the service
// started. The fork/exec is done here so that we *know* we have a
// pidMap entry prior to returning to the main loop and possibly
// reaping children.
//
// Return: true if a process was started.
//////////////////////////////////////////////////////////////////////
bool
service::createProcess(const char* reason, bool applyRateLimiting)
{
if (debug::service()) DBGPRT << "service::createProcess: " << _logID
<< " R=" << reason
<< " UU=" << _unusedIds.size()
<< " apc=" << _activeProcessCount
<< " nextStart " << _nextStartAttempt
<< endl;
if (!createAllowed(applyRateLimiting, false)) return false;
int id = _unusedIds.front(); // Get an unused id
_unusedIds.pop_front();
process* P = new process(this, id, _name,
_acceptSocket, _shmServiceFD, getReportingChannelWriterSocket(),
&_shmService);
_processMap[P] = P;
_M->addProcessCount(); // Add to aggregate totals
++_activeProcessCount; // It's also active until shutdown
if (!P->initialize()) {
destroyOffspring(P, "initialize failed");
return false;
}
if (debug::service()) DBGPRT << "Service: createProcess " << P->getID() << endl;
return true;
}
//////////////////////////////////////////////////////////////////////
// Find the oldest process and initiate a shutdown.
//////////////////////////////////////////////////////////////////////
bool
service::removeOldestProcess(processExit::reason why)
{
process* P = findOldestProcess();
if (!P) {
LOGPRT << "Warning: " << _logID << " Could not find oldest process" << endl;
return false;
}
P->setShutdownReason(why, true);
return true;
}
| 34.409922 | 93 | 0.595189 | yahoo |
232c1992a0b985e0771a9358e9884746096939f4 | 1,617 | cc | C++ | lib/lf/geometry/point.cc | Pascal-So/lehrfempp | e2716e914169eec7ee59e822ea3ab303143eacd1 | [
"MIT"
] | null | null | null | lib/lf/geometry/point.cc | Pascal-So/lehrfempp | e2716e914169eec7ee59e822ea3ab303143eacd1 | [
"MIT"
] | null | null | null | lib/lf/geometry/point.cc | Pascal-So/lehrfempp | e2716e914169eec7ee59e822ea3ab303143eacd1 | [
"MIT"
] | null | null | null | #include "point.h"
namespace lf::geometry {
Eigen::MatrixXd Point::Global(const Eigen::MatrixXd& local) const {
LF_ASSERT_MSG(local.rows() == 0, "local.rows() != 0");
return coord_.replicate(1, local.cols());
}
// NOLINTNEXTLINE(misc-unused-parameters)
Eigen::MatrixXd Point::Jacobian(const Eigen::MatrixXd& local) const {
return Eigen::MatrixXd::Zero(DimGlobal(), 0);
}
Eigen::MatrixXd Point::JacobianInverseGramian(
const Eigen::MatrixXd& local) const { // NOLINT(misc-unused-parameters)
LF_VERIFY_MSG(false, "JacobianInverseGramian undefined for points.");
}
Eigen::VectorXd Point::IntegrationElement(const Eigen::MatrixXd& local) const {
return Eigen::VectorXd::Ones(local.cols());
}
std::unique_ptr<Geometry> Point::SubGeometry(dim_t codim, dim_t i) const {
if (codim == 0 && i == 0) {
return std::make_unique<Point>(coord_);
}
LF_VERIFY_MSG(false, "codim or i out of bounds.");
}
std::vector<std::unique_ptr<Geometry>> Point::ChildGeometry(
const RefinementPattern& ref_pattern, lf::base::dim_t codim) const {
LF_VERIFY_MSG(codim == 0, "Only codim = 0 allowed for a point");
std::vector<std::unique_ptr<Geometry>> child_geo_uptrs{};
LF_VERIFY_MSG(ref_pattern.RefEl() == lf::base::RefEl::kPoint(),
"ref_patern.RefEl() = " << ref_pattern.RefEl().ToString());
LF_VERIFY_MSG(ref_pattern.noChildren(0) == 1,
"ref_pattern.noChildren() = " << ref_pattern.noChildren(0));
// The only way to "refine" a point is to copy it
child_geo_uptrs.push_back(std::make_unique<Point>(coord_));
return child_geo_uptrs;
}
} // namespace lf::geometry
| 36.75 | 79 | 0.700062 | Pascal-So |
232ccb1bb40892f5b0a04510fd9b37b06e65cc55 | 27,849 | cpp | C++ | FlexEngine/src/Window/GLFWWindowWrapper.cpp | ajweeks/Rendering-Engine | fe0f2cdb44a067fec875110572b3b91f5f4c659c | [
"MIT"
] | 762 | 2017-11-07T23:40:58.000Z | 2022-03-31T16:03:22.000Z | FlexEngine/src/Window/GLFWWindowWrapper.cpp | ajweeks/Rendering-Engine | fe0f2cdb44a067fec875110572b3b91f5f4c659c | [
"MIT"
] | 5 | 2018-03-13T14:41:06.000Z | 2020-11-01T12:02:29.000Z | FlexEngine/src/Window/GLFWWindowWrapper.cpp | ajweeks/Rendering-Engine | fe0f2cdb44a067fec875110572b3b91f5f4c659c | [
"MIT"
] | 43 | 2017-11-17T11:22:37.000Z | 2022-03-14T01:51:19.000Z | #include "stdafx.hpp"
#include "Window/GLFWWindowWrapper.hpp"
#include "FlexEngine.hpp"
#include "Editor.hpp"
#if COMPILE_OPEN_GL
#include "Graphics/GL/GLHelpers.hpp"
#endif
#include "Graphics/Renderer.hpp"
#include "Helpers.hpp"
#include "InputManager.hpp"
#include "Platform/Platform.hpp"
#include "Window/Monitor.hpp"
namespace flex
{
std::array<bool, MAX_JOYSTICK_COUNT> g_JoysticksConnected;
GLFWWindowWrapper::GLFWWindowWrapper(const std::string& title) :
Window(title)
{
m_LastNonFullscreenWindowMode = WindowMode::WINDOWED;
}
GLFWWindowWrapper::~GLFWWindowWrapper()
{
}
void GLFWWindowWrapper::Initialize()
{
glfwSetErrorCallback(GLFWErrorCallback);
if (!glfwInit())
{
PrintError("Failed to initialize glfw! Exiting...\n");
exit(EXIT_FAILURE);
return;
}
{
i32 maj, min, rev;
glfwGetVersion(&maj, &min, &rev);
Print("GLFW v%d.%d.%d\n", maj, min, rev);
}
i32 numJoysticksConnected = 0;
for (i32 i = 0; i < MAX_JOYSTICK_COUNT; ++i)
{
g_JoysticksConnected[i] = (glfwJoystickPresent(i) == GLFW_TRUE);
if (g_JoysticksConnected[i])
{
++numJoysticksConnected;
}
}
if (numJoysticksConnected > 0)
{
Print("%i joysticks connected on bootup\n", numJoysticksConnected);
}
g_EngineInstance->mainProcessID = Platform::GetCurrentProcessID();
// TODO: Look into supporting system-DPI awareness
//SetProcessDPIAware();
}
void GLFWWindowWrapper::PostInitialize()
{
PROFILE_AUTO("GLFWWindowWrapper PostInitialize");
// TODO: Set window location/size based on previous session (load from disk)
glfwGetWindowSize(m_Window, &m_LastWindowedSize.x, &m_LastWindowedSize.y);
glfwGetWindowPos(m_Window, &m_LastWindowedPos.x, &m_LastWindowedPos.y);
}
void GLFWWindowWrapper::Destroy()
{
if (m_Window)
{
m_Window = nullptr;
}
}
void GLFWWindowWrapper::Create(const glm::vec2i& size, const glm::vec2i& pos)
{
InitFromConfig();
if (m_bMoveConsoleToOtherMonitor)
{
Platform::MoveConsole();
}
// Only use parameters if values weren't set through config file
if (m_Size.x == 0)
{
m_Size = size;
m_Position = pos;
}
m_FrameBufferSize = m_Size;
m_LastWindowedSize = m_Size;
m_StartingPosition = m_Position;
m_LastWindowedPos = m_Position;
// Don't hide window when losing focus in Windowed Fullscreen
glfwWindowHint(GLFW_AUTO_ICONIFY, GLFW_TRUE);
glfwWindowHint(GLFW_FOCUS_ON_SHOW, GLFW_TRUE);
if (g_bOpenGLEnabled)
{
#if COMPILE_OPEN_GL && DEBUG
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
#endif // DEBUG
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_CONTEXT_CREATION_API, GLFW_NATIVE_CONTEXT_API);
}
else if (g_bVulkanEnabled)
{
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
}
if (m_bMaximized)
{
glfwWindowHint(GLFW_MAXIMIZED, 1);
}
GLFWmonitor* monitor = NULL;
if (m_CurrentWindowMode == WindowMode::FULLSCREEN)
{
monitor = glfwGetPrimaryMonitor();
}
m_Window = glfwCreateWindow(m_Size.x, m_Size.y, m_TitleString.c_str(), monitor, NULL);
if (!m_Window)
{
PrintError("Failed to create glfw Window! Exiting...\n");
glfwTerminate();
// TODO: Try creating a window manually here
exit(EXIT_FAILURE);
}
glfwSetWindowUserPointer(m_Window, this);
SetUpCallbacks();
i32 monitorCount;
GLFWmonitor** monitors = glfwGetMonitors(&monitorCount);
// If previously the window was on an additional monitor that is no longer present,
// move the window to the primary monitor
if (monitorCount == 1)
{
const GLFWvidmode* vidMode = glfwGetVideoMode(monitors[0]);
i32 monitorWidth = vidMode->width;
i32 monitorHeight = vidMode->height;
if (m_StartingPosition.x < 0)
{
m_StartingPosition.x = 100;
}
else if (m_StartingPosition.x > monitorWidth)
{
m_StartingPosition.x = 100;
}
if (m_StartingPosition.y < 0)
{
m_StartingPosition.y = 100;
}
else if (m_StartingPosition.y > monitorHeight)
{
m_StartingPosition.y = 100;
}
}
glfwSetWindowPos(m_Window, m_StartingPosition.x, m_StartingPosition.y);
glfwFocusWindow(m_Window);
m_bHasFocus = true;
}
void GLFWWindowWrapper::RetrieveMonitorInfo()
{
GLFWmonitor* monitor = glfwGetPrimaryMonitor();
if (!monitor)
{
i32 count;
glfwGetMonitors(&count);
PrintError("Failed to find primary monitor!\n");
PrintError("%d monitors found\n", count);
return;
}
const GLFWvidmode* vidMode = glfwGetVideoMode(monitor);
if (!vidMode)
{
PrintError("Failed to get monitor's video mode!\n");
return;
}
assert(g_Monitor); // Monitor must be created before calling RetrieveMonitorInfo!
g_Monitor->width = vidMode->width;
g_Monitor->height = vidMode->height;
g_Monitor->redBits = vidMode->redBits;
g_Monitor->greenBits = vidMode->greenBits;
g_Monitor->blueBits = vidMode->blueBits;
g_Monitor->refreshRate = vidMode->refreshRate;
// 25.4mm = 1 inch
i32 widthMM, heightMM;
glfwGetMonitorPhysicalSize(monitor, &widthMM, &heightMM);
g_Monitor->DPI = glm::vec2(vidMode->width / (widthMM / 25.4f),
vidMode->height / (heightMM / 25.4f));
glfwGetMonitorContentScale(monitor, &g_Monitor->contentScaleX, &g_Monitor->contentScaleY);
}
void GLFWWindowWrapper::SetUpCallbacks()
{
if (!m_Window)
{
PrintError("SetUpCallbacks was called before m_Window was set!\n");
return;
}
glfwSetKeyCallback(m_Window, GLFWKeyCallback);
glfwSetCharCallback(m_Window, GLFWCharCallback);
glfwSetMouseButtonCallback(m_Window, GLFWMouseButtonCallback);
glfwSetCursorPosCallback(m_Window, GLFWCursorPosCallback);
glfwSetScrollCallback(m_Window, GLFWScrollCallback);
glfwSetWindowSizeCallback(m_Window, GLFWWindowSizeCallback);
glfwSetFramebufferSizeCallback(m_Window, GLFWFramebufferSizeCallback);
glfwSetWindowFocusCallback(m_Window, GLFWWindowFocusCallback);
glfwSetWindowPosCallback(m_Window, GLFWWindowPosCallback);
// TODO: Only enable in editor builds
glfwSetDropCallback(m_Window, GLFWDropCallback);
glfwSetJoystickCallback(GLFWJoystickCallback);
glfwSetMonitorCallback(GLFWMointorCallback);
}
void GLFWWindowWrapper::SetFrameBufferSize(i32 width, i32 height)
{
m_FrameBufferSize = glm::vec2i(width, height);
m_Size = m_FrameBufferSize;
if (g_Renderer)
{
g_Renderer->OnWindowSizeChanged(width, height);
}
}
void GLFWWindowWrapper::SetSize(i32 width, i32 height)
{
glfwSetWindowSize(m_Window, width, height);
OnSizeChanged(width, height);
}
void GLFWWindowWrapper::OnSizeChanged(i32 width, i32 height)
{
m_Size = glm::vec2i(width, height);
m_FrameBufferSize = m_Size;
if (m_CurrentWindowMode == WindowMode::WINDOWED)
{
m_LastWindowedSize = m_Size;
}
if (g_Renderer)
{
g_Renderer->OnWindowSizeChanged(width, height);
}
}
void GLFWWindowWrapper::SetPosition(i32 newX, i32 newY)
{
if (m_Window)
{
glfwSetWindowPos(m_Window, newX, newY);
}
else
{
m_StartingPosition = { newX, newY };
}
OnPositionChanged(newX, newY);
}
void GLFWWindowWrapper::OnPositionChanged(i32 newX, i32 newY)
{
m_Position = { newX, newY };
if (m_CurrentWindowMode == WindowMode::WINDOWED)
{
m_LastWindowedPos = m_Position;
}
}
void GLFWWindowWrapper::PollEvents()
{
glfwPollEvents();
}
void GLFWWindowWrapper::SetCursorPos(const glm::vec2& newCursorPos)
{
glfwSetCursorPos(m_Window, newCursorPos.x, newCursorPos.y);
}
void GLFWWindowWrapper::SetCursorMode(CursorMode mode)
{
if (m_CursorMode != mode)
{
Window::SetCursorMode(mode);
i32 glfwCursorMode = 0;
switch (mode)
{
case CursorMode::NORMAL: glfwCursorMode = GLFW_CURSOR_NORMAL; break;
case CursorMode::HIDDEN: glfwCursorMode = GLFW_CURSOR_HIDDEN; break;
case CursorMode::DISABLED: glfwCursorMode = GLFW_CURSOR_DISABLED; break;
case CursorMode::_NONE:
default: PrintError("Unhandled cursor mode passed to GLFWWindowWrapper::SetCursorMode: %i\n", (i32)mode); break;
}
glfwSetInputMode(m_Window, GLFW_CURSOR, glfwCursorMode);
// Enable raw motion when cursor disabled for smoother camera controls
if (glfwCursorMode == GLFW_CURSOR_DISABLED)
{
if (glfwRawMouseMotionSupported())
{
glfwSetInputMode(m_Window, GLFW_RAW_MOUSE_MOTION, GLFW_TRUE);
}
}
}
}
void GLFWWindowWrapper::SetWindowMode(WindowMode mode, bool bForce)
{
if (bForce || m_CurrentWindowMode != mode)
{
m_CurrentWindowMode = mode;
GLFWmonitor* monitor = glfwGetPrimaryMonitor();
if (!monitor)
{
PrintError("Failed to find primary monitor! Can't set window mode\n");
return;
}
const GLFWvidmode* videoMode = glfwGetVideoMode(monitor);
if (!videoMode)
{
PrintError("Failed to get monitor's video mode! Can't set window mode\n");
return;
}
switch (mode)
{
case WindowMode::FULLSCREEN:
{
glfwSetWindowMonitor(m_Window, monitor, 0, 0, videoMode->width, videoMode->height, videoMode->refreshRate);
} break;
case WindowMode::WINDOWED_FULLSCREEN:
{
glfwSetWindowMonitor(m_Window, monitor, 0, 0, videoMode->width, videoMode->height, videoMode->refreshRate);
m_LastNonFullscreenWindowMode = WindowMode::WINDOWED_FULLSCREEN;
} break;
case WindowMode::WINDOWED:
{
assert(m_LastWindowedSize.x != 0 && m_LastWindowedSize.y != 0);
if (m_LastWindowedPos.y == 0)
{
// When in windowed mode a y position of 0 means the title bar isn't
// visible. This will occur if the app launched in fullscreen since
// the last y position to never have been set to a valid value.
m_LastWindowedPos.y = 40;
}
glfwSetWindowMonitor(m_Window, nullptr, m_LastWindowedPos.x, m_LastWindowedPos.y, m_LastWindowedSize.x, m_LastWindowedSize.y, videoMode->refreshRate);
m_LastNonFullscreenWindowMode = WindowMode::WINDOWED;
} break;
case WindowMode::_NONE:
default:
{
PrintError("Unhandled window mode: %u\n", (u32)mode);
} break;
}
}
}
void GLFWWindowWrapper::ToggleFullscreen(bool bForce)
{
if (m_CurrentWindowMode == WindowMode::FULLSCREEN)
{
assert(m_LastNonFullscreenWindowMode == WindowMode::WINDOWED || m_LastNonFullscreenWindowMode == WindowMode::WINDOWED_FULLSCREEN);
SetWindowMode(m_LastNonFullscreenWindowMode, bForce);
}
else
{
SetWindowMode(WindowMode::FULLSCREEN, bForce);
}
}
void GLFWWindowWrapper::Maximize()
{
glfwMaximizeWindow(m_Window);
}
void GLFWWindowWrapper::Iconify()
{
glfwIconifyWindow(m_Window);
}
void GLFWWindowWrapper::Update()
{
Window::Update();
if (glfwWindowShouldClose(m_Window))
{
g_EngineInstance->Stop();
return;
}
GLFWgamepadstate gamepad0State;
static bool bPrevP0JoystickPresent = false;
if (glfwGetGamepadState(0, &gamepad0State) == GLFW_TRUE)
{
g_InputManager->UpdateGamepadState(0, gamepad0State.axes, gamepad0State.buttons);
bPrevP0JoystickPresent = true;
}
else
{
if (bPrevP0JoystickPresent)
{
g_InputManager->ClearGampadInput(0);
bPrevP0JoystickPresent = false;
}
}
GLFWgamepadstate gamepad1State;
static bool bPrevP1JoystickPresent = false;
if (glfwGetGamepadState(1, &gamepad1State) == GLFW_TRUE)
{
g_InputManager->UpdateGamepadState(1, gamepad1State.axes, gamepad1State.buttons);
bPrevP1JoystickPresent = true;
}
else
{
if (bPrevP1JoystickPresent)
{
g_InputManager->ClearGampadInput(1);
bPrevP1JoystickPresent = false;
}
}
}
GLFWwindow* GLFWWindowWrapper::GetWindow() const
{
return m_Window;
}
const char* GLFWWindowWrapper::GetClipboardText()
{
return glfwGetClipboardString(m_Window);
}
void GLFWWindowWrapper::SetClipboardText(const char* text)
{
glfwSetClipboardString(m_Window, text);
}
void GLFWWindowWrapper::SetWindowTitle(const std::string& title)
{
glfwSetWindowTitle(m_Window, title.c_str());
}
void GLFWWindowWrapper::SetMousePosition(glm::vec2 mousePosition)
{
glfwSetCursorPos(m_Window, (double)mousePosition.x, (double)mousePosition.y);
}
glm::vec2 GLFWWindowWrapper::GetMousePosition()
{
double posX, posY;
glfwGetCursorPos(m_Window, &posX, &posY);
return glm::vec2((real)posX, (real)posY);
}
void GLFWErrorCallback(i32 error, const char* description)
{
PrintError("GLFW Error: %i: %s\n", error, description);
}
void GLFWKeyCallback(GLFWwindow* glfwWindow, i32 key, i32 scancode, i32 action, i32 mods)
{
FLEX_UNUSED(scancode);
Window* window = static_cast<Window*>(glfwGetWindowUserPointer(glfwWindow));
const KeyAction inputAction = GLFWActionToInputManagerAction(action);
const KeyCode inputKey = GLFWKeyToInputManagerKey(key);
const i32 inputMods = GLFWModsToInputManagerMods(mods);
window->KeyCallback(inputKey, inputAction, inputMods);
}
void GLFWCharCallback(GLFWwindow* glfwWindow, u32 character)
{
Window* window = static_cast<Window*>(glfwGetWindowUserPointer(glfwWindow));
window->CharCallback(character);
}
void GLFWMouseButtonCallback(GLFWwindow* glfwWindow, i32 button, i32 action, i32 mods)
{
Window* window = static_cast<Window*>(glfwGetWindowUserPointer(glfwWindow));
const KeyAction inputAction = GLFWActionToInputManagerAction(action);
const i32 inputMods = GLFWModsToInputManagerMods(mods);
const MouseButton mouseButton = GLFWButtonToInputManagerMouseButton(button);
window->MouseButtonCallback(mouseButton, inputAction, inputMods);
}
void GLFWWindowFocusCallback(GLFWwindow* glfwWindow, i32 focused)
{
Window* window = static_cast<Window*>(glfwGetWindowUserPointer(glfwWindow));
window->WindowFocusCallback(focused);
}
void GLFWWindowPosCallback(GLFWwindow* glfwWindow, i32 newX, i32 newY)
{
Window* window = static_cast<Window*>(glfwGetWindowUserPointer(glfwWindow));
window->WindowPosCallback(newX, newY);
}
void GLFWCursorPosCallback(GLFWwindow* glfwWindow, double x, double y)
{
Window* window = static_cast<Window*>(glfwGetWindowUserPointer(glfwWindow));
window->CursorPosCallback(x, y);
}
void GLFWScrollCallback(GLFWwindow* glfwWindow, double xoffset, double yoffset)
{
Window* window = static_cast<Window*>(glfwGetWindowUserPointer(glfwWindow));
window->ScrollCallback(xoffset, yoffset);
}
void GLFWWindowSizeCallback(GLFWwindow* glfwWindow, i32 width, i32 height)
{
Window* window = static_cast<Window*>(glfwGetWindowUserPointer(glfwWindow));
bool bMaximized = (glfwGetWindowAttrib(glfwWindow, GLFW_MAXIMIZED) == GLFW_TRUE);
bool bIconified = (glfwGetWindowAttrib(glfwWindow, GLFW_ICONIFIED) == GLFW_TRUE);
window->WindowSizeCallback(width, height, bMaximized, bIconified);
}
void GLFWFramebufferSizeCallback(GLFWwindow* glfwWindow, i32 width, i32 height)
{
Window* window = static_cast<Window*>(glfwGetWindowUserPointer(glfwWindow));
window->FrameBufferSizeCallback(width, height);
}
void GLFWDropCallback(GLFWwindow* glfwWindow, int count, const char** paths)
{
g_Editor->OnDragDrop(count, paths);
glfwFocusWindow(glfwWindow);
}
void GLFWJoystickCallback(i32 JID, i32 event)
{
if (JID > MAX_JOYSTICK_COUNT)
{
PrintWarn("Unhandled joystick connection event, JID out of range: %i\n", JID);
return;
}
if (event == GLFW_CONNECTED)
{
Print("Joystick %i connected\n", JID);
}
else if (event == GLFW_DISCONNECTED)
{
Print("Joystick %i disconnected\n", JID);
}
g_JoysticksConnected[(u32)JID] = (event == GLFW_CONNECTED);
}
void GLFWMointorCallback(GLFWmonitor* monitor, int event)
{
i32 w, h;
glfwGetMonitorPhysicalSize(monitor, &w, &h);
if (event == GLFW_CONNECTED)
{
Print("Monitor connected: %s, %dmm x %dmm\n", glfwGetMonitorName(monitor), w, h);
}
else
{
Print("Monitor disconnected: %s, %dmm x %dmm\n", glfwGetMonitorName(monitor), w, h);
}
}
KeyAction GLFWActionToInputManagerAction(i32 glfwAction)
{
KeyAction inputAction = KeyAction::_NONE;
switch (glfwAction)
{
case GLFW_PRESS: inputAction = KeyAction::KEY_PRESS; break;
case GLFW_REPEAT: inputAction = KeyAction::KEY_REPEAT; break;
case GLFW_RELEASE: inputAction = KeyAction::KEY_RELEASE; break;
case -1: break; // We don't care about events GLFW can't handle
default: PrintError("Unhandled glfw action passed to GLFWActionToInputManagerAction in GLFWWIndowWrapper: %i\n",
glfwAction);
}
return inputAction;
}
KeyCode GLFWKeyToInputManagerKey(i32 glfwKey)
{
KeyCode inputKey = KeyCode::_NONE;
switch (glfwKey)
{
case GLFW_KEY_SPACE: inputKey = KeyCode::KEY_SPACE; break;
case GLFW_KEY_APOSTROPHE: inputKey = KeyCode::KEY_APOSTROPHE; break;
case GLFW_KEY_COMMA: inputKey = KeyCode::KEY_COMMA; break;
case GLFW_KEY_MINUS: inputKey = KeyCode::KEY_MINUS; break;
case GLFW_KEY_PERIOD: inputKey = KeyCode::KEY_PERIOD; break;
case GLFW_KEY_SLASH: inputKey = KeyCode::KEY_SLASH; break;
case GLFW_KEY_0: inputKey = KeyCode::KEY_0; break;
case GLFW_KEY_1: inputKey = KeyCode::KEY_1; break;
case GLFW_KEY_2: inputKey = KeyCode::KEY_2; break;
case GLFW_KEY_3: inputKey = KeyCode::KEY_3; break;
case GLFW_KEY_4: inputKey = KeyCode::KEY_4; break;
case GLFW_KEY_5: inputKey = KeyCode::KEY_5; break;
case GLFW_KEY_6: inputKey = KeyCode::KEY_6; break;
case GLFW_KEY_7: inputKey = KeyCode::KEY_7; break;
case GLFW_KEY_8: inputKey = KeyCode::KEY_8; break;
case GLFW_KEY_9: inputKey = KeyCode::KEY_9; break;
case GLFW_KEY_SEMICOLON: inputKey = KeyCode::KEY_SEMICOLON; break;
case GLFW_KEY_EQUAL: inputKey = KeyCode::KEY_EQUAL; break;
case GLFW_KEY_A: inputKey = KeyCode::KEY_A; break;
case GLFW_KEY_B: inputKey = KeyCode::KEY_B; break;
case GLFW_KEY_C: inputKey = KeyCode::KEY_C; break;
case GLFW_KEY_D: inputKey = KeyCode::KEY_D; break;
case GLFW_KEY_E: inputKey = KeyCode::KEY_E; break;
case GLFW_KEY_F: inputKey = KeyCode::KEY_F; break;
case GLFW_KEY_G: inputKey = KeyCode::KEY_G; break;
case GLFW_KEY_H: inputKey = KeyCode::KEY_H; break;
case GLFW_KEY_I: inputKey = KeyCode::KEY_I; break;
case GLFW_KEY_J: inputKey = KeyCode::KEY_J; break;
case GLFW_KEY_K: inputKey = KeyCode::KEY_K; break;
case GLFW_KEY_L: inputKey = KeyCode::KEY_L; break;
case GLFW_KEY_M: inputKey = KeyCode::KEY_M; break;
case GLFW_KEY_N: inputKey = KeyCode::KEY_N; break;
case GLFW_KEY_O: inputKey = KeyCode::KEY_O; break;
case GLFW_KEY_P: inputKey = KeyCode::KEY_P; break;
case GLFW_KEY_Q: inputKey = KeyCode::KEY_Q; break;
case GLFW_KEY_R: inputKey = KeyCode::KEY_R; break;
case GLFW_KEY_S: inputKey = KeyCode::KEY_S; break;
case GLFW_KEY_T: inputKey = KeyCode::KEY_T; break;
case GLFW_KEY_U: inputKey = KeyCode::KEY_U; break;
case GLFW_KEY_V: inputKey = KeyCode::KEY_V; break;
case GLFW_KEY_W: inputKey = KeyCode::KEY_W; break;
case GLFW_KEY_X: inputKey = KeyCode::KEY_X; break;
case GLFW_KEY_Y: inputKey = KeyCode::KEY_Y; break;
case GLFW_KEY_Z: inputKey = KeyCode::KEY_Z; break;
case GLFW_KEY_LEFT_BRACKET: inputKey = KeyCode::KEY_LEFT_BRACKET; break;
case GLFW_KEY_BACKSLASH: inputKey = KeyCode::KEY_BACKSLASH; break;
case GLFW_KEY_RIGHT_BRACKET: inputKey = KeyCode::KEY_RIGHT_BRACKET; break;
case GLFW_KEY_GRAVE_ACCENT: inputKey = KeyCode::KEY_GRAVE_ACCENT; break;
case GLFW_KEY_WORLD_1: inputKey = KeyCode::KEY_WORLD_1; break;
case GLFW_KEY_WORLD_2: inputKey = KeyCode::KEY_WORLD_2; break;
case GLFW_KEY_ESCAPE: inputKey = KeyCode::KEY_ESCAPE; break;
case GLFW_KEY_ENTER: inputKey = KeyCode::KEY_ENTER; break;
case GLFW_KEY_TAB: inputKey = KeyCode::KEY_TAB; break;
case GLFW_KEY_BACKSPACE: inputKey = KeyCode::KEY_BACKSPACE; break;
case GLFW_KEY_INSERT: inputKey = KeyCode::KEY_INSERT; break;
case GLFW_KEY_DELETE: inputKey = KeyCode::KEY_DELETE; break;
case GLFW_KEY_RIGHT: inputKey = KeyCode::KEY_RIGHT; break;
case GLFW_KEY_LEFT: inputKey = KeyCode::KEY_LEFT; break;
case GLFW_KEY_DOWN: inputKey = KeyCode::KEY_DOWN; break;
case GLFW_KEY_UP: inputKey = KeyCode::KEY_UP; break;
case GLFW_KEY_PAGE_UP: inputKey = KeyCode::KEY_PAGE_UP; break;
case GLFW_KEY_PAGE_DOWN: inputKey = KeyCode::KEY_PAGE_DOWN; break;
case GLFW_KEY_HOME: inputKey = KeyCode::KEY_HOME; break;
case GLFW_KEY_END: inputKey = KeyCode::KEY_END; break;
case GLFW_KEY_CAPS_LOCK: inputKey = KeyCode::KEY_CAPS_LOCK; break;
case GLFW_KEY_SCROLL_LOCK: inputKey = KeyCode::KEY_SCROLL_LOCK; break;
case GLFW_KEY_NUM_LOCK: inputKey = KeyCode::KEY_NUM_LOCK; break;
case GLFW_KEY_PRINT_SCREEN: inputKey = KeyCode::KEY_PRINT_SCREEN; break;
case GLFW_KEY_PAUSE: inputKey = KeyCode::KEY_PAUSE; break;
case GLFW_KEY_F1: inputKey = KeyCode::KEY_F1; break;
case GLFW_KEY_F2: inputKey = KeyCode::KEY_F2; break;
case GLFW_KEY_F3: inputKey = KeyCode::KEY_F3; break;
case GLFW_KEY_F4: inputKey = KeyCode::KEY_F4; break;
case GLFW_KEY_F5: inputKey = KeyCode::KEY_F5; break;
case GLFW_KEY_F6: inputKey = KeyCode::KEY_F6; break;
case GLFW_KEY_F7: inputKey = KeyCode::KEY_F7; break;
case GLFW_KEY_F8: inputKey = KeyCode::KEY_F8; break;
case GLFW_KEY_F9: inputKey = KeyCode::KEY_F9; break;
case GLFW_KEY_F10: inputKey = KeyCode::KEY_F10; break;
case GLFW_KEY_F11: inputKey = KeyCode::KEY_F11; break;
case GLFW_KEY_F12: inputKey = KeyCode::KEY_F12; break;
case GLFW_KEY_F13: inputKey = KeyCode::KEY_F13; break;
case GLFW_KEY_F14: inputKey = KeyCode::KEY_F14; break;
case GLFW_KEY_F15: inputKey = KeyCode::KEY_F15; break;
case GLFW_KEY_F16: inputKey = KeyCode::KEY_F16; break;
case GLFW_KEY_F17: inputKey = KeyCode::KEY_F17; break;
case GLFW_KEY_F18: inputKey = KeyCode::KEY_F18; break;
case GLFW_KEY_F19: inputKey = KeyCode::KEY_F19; break;
case GLFW_KEY_F20: inputKey = KeyCode::KEY_F20; break;
case GLFW_KEY_F21: inputKey = KeyCode::KEY_F21; break;
case GLFW_KEY_F22: inputKey = KeyCode::KEY_F22; break;
case GLFW_KEY_F23: inputKey = KeyCode::KEY_F23; break;
case GLFW_KEY_F24: inputKey = KeyCode::KEY_F24; break;
case GLFW_KEY_F25: inputKey = KeyCode::KEY_F25; break;
case GLFW_KEY_KP_0: inputKey = KeyCode::KEY_KP_0; break;
case GLFW_KEY_KP_1: inputKey = KeyCode::KEY_KP_1; break;
case GLFW_KEY_KP_2: inputKey = KeyCode::KEY_KP_2; break;
case GLFW_KEY_KP_3: inputKey = KeyCode::KEY_KP_3; break;
case GLFW_KEY_KP_4: inputKey = KeyCode::KEY_KP_4; break;
case GLFW_KEY_KP_5: inputKey = KeyCode::KEY_KP_5; break;
case GLFW_KEY_KP_6: inputKey = KeyCode::KEY_KP_6; break;
case GLFW_KEY_KP_7: inputKey = KeyCode::KEY_KP_7; break;
case GLFW_KEY_KP_8: inputKey = KeyCode::KEY_KP_8; break;
case GLFW_KEY_KP_9: inputKey = KeyCode::KEY_KP_9; break;
case GLFW_KEY_KP_DECIMAL: inputKey = KeyCode::KEY_KP_DECIMAL; break;
case GLFW_KEY_KP_DIVIDE: inputKey = KeyCode::KEY_KP_DIVIDE; break;
case GLFW_KEY_KP_MULTIPLY: inputKey = KeyCode::KEY_KP_MULTIPLY; break;
case GLFW_KEY_KP_SUBTRACT: inputKey = KeyCode::KEY_KP_SUBTRACT; break;
case GLFW_KEY_KP_ADD: inputKey = KeyCode::KEY_KP_ADD; break;
case GLFW_KEY_KP_ENTER: inputKey = KeyCode::KEY_KP_ENTER; break;
case GLFW_KEY_KP_EQUAL: inputKey = KeyCode::KEY_KP_EQUAL; break;
case GLFW_KEY_LEFT_SHIFT: inputKey = KeyCode::KEY_LEFT_SHIFT; break;
case GLFW_KEY_LEFT_CONTROL: inputKey = KeyCode::KEY_LEFT_CONTROL; break;
case GLFW_KEY_LEFT_ALT: inputKey = KeyCode::KEY_LEFT_ALT; break;
case GLFW_KEY_LEFT_SUPER: inputKey = KeyCode::KEY_LEFT_SUPER; break;
case GLFW_KEY_RIGHT_SHIFT: inputKey = KeyCode::KEY_RIGHT_SHIFT; break;
case GLFW_KEY_RIGHT_CONTROL: inputKey = KeyCode::KEY_RIGHT_CONTROL; break;
case GLFW_KEY_RIGHT_ALT: inputKey = KeyCode::KEY_RIGHT_ALT; break;
case GLFW_KEY_RIGHT_SUPER: inputKey = KeyCode::KEY_RIGHT_SUPER; break;
case GLFW_KEY_MENU: inputKey = KeyCode::KEY_MENU; break;
case -1: break; // We don't care about events GLFW can't handle
default:
PrintError("Unhandled glfw key passed to GLFWKeyToInputManagerKey in GLFWWIndowWrapper: %i\n",
glfwKey);
break;
}
return inputKey;
}
i32 GLFWModsToInputManagerMods(i32 glfwMods)
{
i32 inputMods = 0;
if (glfwMods & GLFW_MOD_SHIFT) inputMods |= (i32)InputModifier::SHIFT;
if (glfwMods & GLFW_MOD_ALT) inputMods |= (i32)InputModifier::ALT;
if (glfwMods & GLFW_MOD_CONTROL) inputMods |= (i32)InputModifier::CONTROL;
if (glfwMods & GLFW_MOD_SUPER) inputMods |= (i32)InputModifier::SUPER;
if (glfwMods & GLFW_MOD_CAPS_LOCK) inputMods |= (i32)InputModifier::CAPS_LOCK;
if (glfwMods & GLFW_MOD_NUM_LOCK) inputMods |= (i32)InputModifier::NUM_LOCK;
return inputMods;
}
MouseButton GLFWButtonToInputManagerMouseButton(i32 glfwButton)
{
MouseButton inputMouseButton = MouseButton::_NONE;
switch (glfwButton)
{
case GLFW_MOUSE_BUTTON_1: inputMouseButton = MouseButton::MOUSE_BUTTON_1; break;
case GLFW_MOUSE_BUTTON_2: inputMouseButton = MouseButton::MOUSE_BUTTON_2; break;
case GLFW_MOUSE_BUTTON_3: inputMouseButton = MouseButton::MOUSE_BUTTON_3; break;
case GLFW_MOUSE_BUTTON_4: inputMouseButton = MouseButton::MOUSE_BUTTON_4; break;
case GLFW_MOUSE_BUTTON_5: inputMouseButton = MouseButton::MOUSE_BUTTON_5; break;
case GLFW_MOUSE_BUTTON_6: inputMouseButton = MouseButton::MOUSE_BUTTON_6; break;
case GLFW_MOUSE_BUTTON_7: inputMouseButton = MouseButton::MOUSE_BUTTON_7; break;
case GLFW_MOUSE_BUTTON_8: inputMouseButton = MouseButton::MOUSE_BUTTON_8; break;
case -1: break; // We don't care about events GLFW can't handle
default: PrintError("Unhandled glfw button passed to GLFWButtonToInputManagerMouseButton in GLFWWIndowWrapper: %i\n",
glfwButton); break;
}
return inputMouseButton;
}
#if defined(_WINDOWS) && COMPILE_OPEN_GL
void WINAPI glDebugOutput(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length,
const GLchar* message, const void* userParam)
{
FLEX_UNUSED(userParam);
FLEX_UNUSED(length);
// Ignore insignificant error/warning codes and notification messages
if (id == 131169 || id == 131185 || id == 131218 || id == 131204 ||
severity == GL_DEBUG_SEVERITY_NOTIFICATION)
{
return;
}
PrintError("-----------------------------------------\n");
PrintError("GL Debug message (%u): %s\n", id, message);
switch (source)
{
case GL_DEBUG_SOURCE_API: PrintError("Source: API"); break;
case GL_DEBUG_SOURCE_WINDOW_SYSTEM: PrintError("Source: Window System"); break;
case GL_DEBUG_SOURCE_SHADER_COMPILER: PrintError("Source: Shader Compiler"); break;
case GL_DEBUG_SOURCE_THIRD_PARTY: PrintError("Source: Third Party"); break;
case GL_DEBUG_SOURCE_APPLICATION: PrintError("Source: Application"); break;
case GL_DEBUG_SOURCE_OTHER: PrintError("Source: Other"); break;
}
PrintError("\n");
switch (type)
{
case GL_DEBUG_TYPE_ERROR: PrintError("Type: Error"); break;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: PrintError("Type: Deprecated Behaviour"); break;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: PrintError("Type: Undefined Behaviour"); break;
case GL_DEBUG_TYPE_PORTABILITY: PrintError("Type: Portability"); break;
case GL_DEBUG_TYPE_PERFORMANCE: PrintError("Type: Performance"); break;
case GL_DEBUG_TYPE_MARKER: PrintError("Type: Marker"); break;
case GL_DEBUG_TYPE_PUSH_GROUP: PrintError("Type: Push Group"); break;
case GL_DEBUG_TYPE_POP_GROUP: PrintError("Type: Pop Group"); break;
case GL_DEBUG_TYPE_OTHER: PrintError("Type: Other"); break;
}
PrintError("\n");
switch (severity)
{
case GL_DEBUG_SEVERITY_HIGH: PrintError("Severity: high"); break;
case GL_DEBUG_SEVERITY_MEDIUM: PrintError("Severity: medium"); break;
case GL_DEBUG_SEVERITY_LOW: PrintError("Severity: low"); break;
//case GL_DEBUG_SEVERITY_NOTIFICATION: PrintError("Severity: notification"); break;
}
PrintError("\n-----------------------------------------\n");
}
#endif
} // namespace flex
| 32.6483 | 154 | 0.738016 | ajweeks |
2331e0219ab4482e80e287d213ad0093d02a0677 | 505 | hpp | C++ | libraries/chain/include/graphene/chain/protocol/cyva.hpp | cyvasia/cyva | e98b26abfe8e96d0e1470626b0a525d44f9372a9 | [
"MIT"
] | null | null | null | libraries/chain/include/graphene/chain/protocol/cyva.hpp | cyvasia/cyva | e98b26abfe8e96d0e1470626b0a525d44f9372a9 | [
"MIT"
] | null | null | null | libraries/chain/include/graphene/chain/protocol/cyva.hpp | cyvasia/cyva | e98b26abfe8e96d0e1470626b0a525d44f9372a9 | [
"MIT"
] | null | null | null | /* (c) 2018 CYVA. For details refer to LICENSE */
#pragma once
#include <graphene/chain/protocol/base.hpp>
#include <graphene/chain/protocol/types.hpp>
#include <graphene/chain/protocol/asset.hpp>
#include <boost/preprocessor/seq/seq.hpp>
#include <fc/reflect/reflect.hpp>
#include <fc/crypto/ripemd160.hpp>
#include <fc/time.hpp>
#include <stdint.h>
#include <vector>
#include <utility>
#include <cyva/encrypt/crypto_types.hpp>
namespace graphene { namespace chain {
} } // graphene::chain
| 18.703704 | 49 | 0.732673 | cyvasia |
23329fe028bb17c96abe4e83ff364e332119b8e4 | 5,297 | cpp | C++ | src/systemcmds/tests/test_List.cpp | a093050472/PX4-Auotopilot | 177da1f92324dcb98b23643b73cfe5cb342ba32f | [
"BSD-3-Clause"
] | 8 | 2017-12-02T15:00:44.000Z | 2022-03-29T15:09:12.000Z | src/systemcmds/tests/test_List.cpp | a093050472/PX4-Auotopilot | 177da1f92324dcb98b23643b73cfe5cb342ba32f | [
"BSD-3-Clause"
] | 4 | 2020-11-07T12:08:43.000Z | 2021-06-18T15:16:17.000Z | src/systemcmds/tests/test_List.cpp | a093050472/PX4-Auotopilot | 177da1f92324dcb98b23643b73cfe5cb342ba32f | [
"BSD-3-Clause"
] | 20 | 2020-07-09T03:11:03.000Z | 2021-12-21T13:01:18.000Z | /****************************************************************************
*
* Copyright (C) 2019 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file test_List.cpp
* Tests the List container.
*/
#include <unit_test.h>
#include <containers/List.hpp>
#include <float.h>
#include <math.h>
class testContainer : public ListNode<testContainer *>
{
public:
int i{0};
};
class ListTest : public UnitTest
{
public:
virtual bool run_tests();
bool test_add();
bool test_remove();
bool test_range_based_for();
};
bool ListTest::run_tests()
{
ut_run_test(test_add);
ut_run_test(test_remove);
ut_run_test(test_range_based_for);
return (_tests_failed == 0);
}
bool ListTest::test_add()
{
List<testContainer *> list1;
// size should be 0 initially
ut_compare("size initially 0", list1.size(), 0);
ut_assert_true(list1.empty());
// insert 100
for (int i = 0; i < 100; i++) {
testContainer *t = new testContainer();
t->i = i;
list1.add(t);
ut_compare("size increasing with i", list1.size(), i + 1);
ut_assert_true(!list1.empty());
}
// verify full size (100)
ut_assert_true(list1.size() == 100);
int i = 99;
for (auto t : list1) {
// verify all elements were inserted in order
ut_compare("stored i", i, t->i);
i--;
}
// delete all elements
list1.clear();
// verify list has been cleared
ut_assert_true(list1.empty());
ut_compare("size 0", list1.size(), 0);
return true;
}
bool ListTest::test_remove()
{
List<testContainer *> list1;
// size should be 0 initially
ut_compare("size initially 0", list1.size(), 0);
ut_assert_true(list1.empty());
// insert 100
for (int i = 0; i < 100; i++) {
testContainer *t = new testContainer();
t->i = i;
list1.add(t);
ut_compare("size increasing with i", list1.size(), i + 1);
ut_assert_true(!list1.empty());
}
// verify full size (100)
ut_assert_true(list1.size() == 100);
// test removing elements
for (int remove_i = 0; remove_i < 100; remove_i++) {
// find node with i == remove_i
testContainer *removed = nullptr;
for (auto t : list1) {
if (t->i == remove_i) {
ut_assert_true(list1.remove(t));
removed = t;
}
}
delete removed;
// iterate list again to verify removal
for (auto t : list1) {
ut_assert_true(t->i != remove_i);
}
ut_assert_true(list1.size() == 100 - remove_i - 1);
}
// list should now be empty
ut_assert_true(list1.empty());
ut_compare("size 0", list1.size(), 0);
// delete all elements (should be safe on empty list)
list1.clear();
// verify list has been cleared
ut_assert_true(list1.empty());
ut_compare("size 0", list1.size(), 0);
return true;
}
bool ListTest::test_range_based_for()
{
List<testContainer *> list1;
// size should be 0 initially
ut_compare("size initially 0", list1.size(), 0);
ut_assert_true(list1.empty());
// insert 100 elements in order
for (int i = 99; i >= 0; i--) {
testContainer *t = new testContainer();
t->i = i;
list1.add(t);
ut_assert_true(!list1.empty());
}
// first element should be 0
ut_compare("first 0", list1.getHead()->i, 0);
// verify all elements were inserted in order
int i = 0;
auto t1 = list1.getHead();
while (t1 != nullptr) {
ut_compare("check count", i, t1->i);
t1 = t1->getSibling();
i++;
}
// verify full size (100)
ut_compare("size check", list1.size(), 100);
i = 0;
for (auto t2 : list1) {
ut_compare("range based for i", i, t2->i);
i++;
}
// verify full size (100)
ut_compare("size check", list1.size(), 100);
// delete all elements
list1.clear();
// verify list has been cleared
ut_assert_true(list1.empty());
ut_compare("size check", list1.size(), 0);
return true;
}
ut_declare_test_c(test_List, ListTest)
| 23.86036 | 78 | 0.664338 | a093050472 |
2332e54db470fdefbe24528bec8fe715e3872c60 | 2,301 | cpp | C++ | remill/Arch/X86/Semantics/UNCOND_BR.cpp | mewbak/remill | 6ea2e7ee011260996b83bf865e0c186af2c1208a | [
"Apache-2.0"
] | null | null | null | remill/Arch/X86/Semantics/UNCOND_BR.cpp | mewbak/remill | 6ea2e7ee011260996b83bf865e0c186af2c1208a | [
"Apache-2.0"
] | null | null | null | remill/Arch/X86/Semantics/UNCOND_BR.cpp | mewbak/remill | 6ea2e7ee011260996b83bf865e0c186af2c1208a | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017 Trail of Bits, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace {
template <typename T>
DEF_SEM(JMP, T target_pc) {
WriteZExt(REG_PC, Read(target_pc));
return memory;
}
template <typename T>
DEF_SEM(JMP_FAR_MEM, T target_seg_pc) {
HYPER_CALL = AsyncHyperCall::kX86JmpFar;
uint64_t target_fword = UShr(UShl(Read(target_seg_pc), 0xf), 0xf);
auto pc = static_cast<uint32_t>(target_fword);
auto seg = static_cast<uint16_t>(UShr(target_fword, 32));
WriteZExt(REG_PC, pc);
Write(REG_CS.flat, seg);
// TODO(tathanhdinh): Update the hidden part (segment shadow) of CS,
// see Issue #334
return memory;
}
template <typename S1, typename S2>
DEF_SEM(JMP_FAR_PTR, S1 src1, S2 src2) {
HYPER_CALL = AsyncHyperCall::kX86JmpFar;
auto pc = Read(src1);
auto seg = Read(src2);
WriteZExt(REG_PC, pc);
Write(REG_CS.flat, seg);
// TODO(tathanhdinh): Update the hidden part (segment shadow) of CS,
// see Issue #334
return memory;
}
} // namespace
DEF_ISEL(JMP_RELBRd) = JMP<PC>;
DEF_ISEL(JMP_RELBRb) = JMP<PC>;
DEF_ISEL_32or64(JMP_RELBRz, JMP<PC>);
#if 64 == ADDRESS_SIZE_BITS
DEF_ISEL(JMP_MEMv_64) = JMP<M64>;
DEF_ISEL(JMP_GPRv_64) = JMP<R64>;
DEF_ISEL(JMP_FAR_MEMp2_32) = JMP_FAR_MEM<M64>;
#else
DEF_ISEL(JMP_MEMv_16) = JMP<M16>;
DEF_ISEL(JMP_MEMv_32) = JMP<M32>;
DEF_ISEL(JMP_GPRv_16) = JMP<R16>;
DEF_ISEL(JMP_GPRv_32) = JMP<R32>;
DEF_ISEL(JMP_FAR_MEMp2_32) = JMP_FAR_MEM<M32>;
DEF_ISEL(JMP_FAR_PTRp_IMMw_32) = JMP_FAR_PTR<I32, I16>;
DEF_ISEL(JMP_FAR_PTRp_IMMw_16) = JMP_FAR_PTR<I16, I16>;
#endif
/*
1807 JMP_FAR JMP_FAR_MEMp2 UNCOND_BR BASE I86 ATTRIBUTES: FAR_XFER NOTSX SCALABLE
1808 JMP_FAR JMP_FAR_PTRp_IMMw UNCOND_BR BASE I86 ATTRIBUTES: FAR_XFER NOTSX SCALABLE
*/
| 27.722892 | 85 | 0.72186 | mewbak |
233764cf02f1b169af3957995c73a1e2e68fe63e | 2,524 | cpp | C++ | YorozuyaGSLib/source/CChatStealSystem.cpp | lemkova/Yorozuya | f445d800078d9aba5de28f122cedfa03f26a38e4 | [
"MIT"
] | 29 | 2017-07-01T23:08:31.000Z | 2022-02-19T10:22:45.000Z | YorozuyaGSLib/source/CChatStealSystem.cpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 90 | 2017-10-18T21:24:51.000Z | 2019-06-06T02:30:33.000Z | YorozuyaGSLib/source/CChatStealSystem.cpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 44 | 2017-12-19T08:02:59.000Z | 2022-02-24T23:15:01.000Z | #include <CChatStealSystem.hpp>
START_ATF_NAMESPACE
CChatStealSystem::CChatStealSystem()
{
using org_ptr = void (WINAPIV*)(struct CChatStealSystem*);
(org_ptr(0x1403f86a0L))(this);
};
void CChatStealSystem::ctor_CChatStealSystem()
{
using org_ptr = void (WINAPIV*)(struct CChatStealSystem*);
(org_ptr(0x1403f86a0L))(this);
};
struct CChatStealSystem* CChatStealSystem::Instance()
{
using org_ptr = struct CChatStealSystem* (WINAPIV*)();
return (org_ptr(0x140094f00L))();
};
void CChatStealSystem::SendStealMsg(struct CPlayer* pPlayer, char byChatType, unsigned int dwSenderSerial, char* pwszSender, char byRaceCode, char* pwszMessage)
{
using org_ptr = void (WINAPIV*)(struct CChatStealSystem*, struct CPlayer*, char, unsigned int, char*, char, char*);
(org_ptr(0x1403f8a30L))(this, pPlayer, byChatType, dwSenderSerial, pwszSender, byRaceCode, pwszMessage);
};
bool CChatStealSystem::SetGm(struct CPlayer* pGM)
{
using org_ptr = bool (WINAPIV*)(struct CChatStealSystem*, struct CPlayer*);
return (org_ptr(0x1403f88b0L))(this, pGM);
};
bool CChatStealSystem::SetTargetInfoFromBoss(char byType, char byRaceCode)
{
using org_ptr = bool (WINAPIV*)(struct CChatStealSystem*, char, char);
return (org_ptr(0x1403f8870L))(this, byType, byRaceCode);
};
bool CChatStealSystem::SetTargetInfoFromCharacter(char byType, char* szCharName)
{
using org_ptr = bool (WINAPIV*)(struct CChatStealSystem*, char, char*);
return (org_ptr(0x1403f87c0L))(this, byType, szCharName);
};
bool CChatStealSystem::SetTargetInfoFromRace(char byType, char byRaceCode)
{
using org_ptr = bool (WINAPIV*)(struct CChatStealSystem*, char, char);
return (org_ptr(0x1403f8830L))(this, byType, byRaceCode);
};
void CChatStealSystem::StealChatMsg(struct CPlayer* pPlayer, char byChatType, char* szChatMsg)
{
using org_ptr = void (WINAPIV*)(struct CChatStealSystem*, struct CPlayer*, char, char*);
(org_ptr(0x1403f8900L))(this, pPlayer, byChatType, szChatMsg);
};
CChatStealSystem::~CChatStealSystem()
{
using org_ptr = void (WINAPIV*)(struct CChatStealSystem*);
(org_ptr(0x1403f8700L))(this);
};
void CChatStealSystem::dtor_CChatStealSystem()
{
using org_ptr = void (WINAPIV*)(struct CChatStealSystem*);
(org_ptr(0x1403f8700L))(this);
};
END_ATF_NAMESPACE
| 41.377049 | 164 | 0.679477 | lemkova |
2338686a01673886d8ca2fc65adcb35c5ecd9190 | 1,889 | hpp | C++ | modules/boost/simd/bitwise/include/boost/simd/toolbox/bitwise/functions/ctz.hpp | timblechmann/nt2 | 6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce | [
"BSL-1.0"
] | 2 | 2016-09-14T00:23:53.000Z | 2018-01-14T12:51:18.000Z | modules/boost/simd/bitwise/include/boost/simd/toolbox/bitwise/functions/ctz.hpp | timblechmann/nt2 | 6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce | [
"BSL-1.0"
] | null | null | null | modules/boost/simd/bitwise/include/boost/simd/toolbox/bitwise/functions/ctz.hpp | timblechmann/nt2 | 6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce | [
"BSL-1.0"
] | null | null | null | //==============================================================================
// Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
/*!
* \file
**/
#ifndef BOOST_SIMD_TOOLBOX_BITWISE_FUNCTIONS_CTZ_HPP_INCLUDED
#define BOOST_SIMD_TOOLBOX_BITWISE_FUNCTIONS_CTZ_HPP_INCLUDED
#include <boost/simd/include/functor.hpp>
#include <boost/dispatch/include/functor.hpp>
/*!
* \ingroup boost_simd_bitwise
* \defgroup boost_simd_bitwise_ctz ctz
*
* \par Description
* The function finds the first bit set (beginning with the least
* significant bit) in a0, and return the index of that bit.
* \par
* Bits are numbered starting at one (the least significant bit).
*
* \par Header file
*
* \code
* #include <nt2/include/functions/ctz.hpp>
* \endcode
*
*
* \synopsis
*
* \code
* namespace boost::simd
* {
* template <class A0>
* meta::call<tag::ctz_(A0)>::type
* ctz(const A0 & a0);
* }
* \endcode
*
* \param a0 the unique parameter of ctz
*
* \return always returns an integer value
*
* \par Notes
* In SIMD mode, this function acts elementwise on the inputs vectors elements
* \par
*
**/
namespace boost { namespace simd { namespace tag
{
/*!
* \brief Define the tag ctz_ of functor ctz
* in namespace boost::simd::tag for toolbox boost.simd.bitwise
**/
struct ctz_ : ext::elementwise_<ctz_> { typedef ext::elementwise_<ctz_> parent; };
}
BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::ctz_, ctz, 1)
} }
#endif
// modified by jt the 25/12/2010
| 27.376812 | 86 | 0.611964 | timblechmann |
2339012f9340b23c94e09b688a3a0df9cd2b7d85 | 3,145 | cpp | C++ | src/io/nanopolish_fast5_processor.cpp | Yufeng98/nanopolish | 1c6ce4d041d461b6a95baff8099cc7e11bb5a8a2 | [
"MIT"
] | 439 | 2015-03-11T15:23:41.000Z | 2022-03-31T14:24:20.000Z | src/io/nanopolish_fast5_processor.cpp | Yufeng98/nanopolish | 1c6ce4d041d461b6a95baff8099cc7e11bb5a8a2 | [
"MIT"
] | 917 | 2015-03-11T18:28:58.000Z | 2022-03-30T23:11:15.000Z | src/io/nanopolish_fast5_processor.cpp | Yufeng98/nanopolish | 1c6ce4d041d461b6a95baff8099cc7e11bb5a8a2 | [
"MIT"
] | 177 | 2015-04-22T23:50:53.000Z | 2022-03-25T06:41:35.000Z | //---------------------------------------------------------
// Copyright 2016 Ontario Institute for Cancer Research
// Written by Jared Simpson (jared.simpson@oicr.on.ca)
//---------------------------------------------------------
//
// nanopolish_fast5_processor -- framework for iterating
// over a collection of fast5 files and performing some
// action on each read in parallel
//
#include "nanopolish_fast5_processor.h"
#include "nanopolish_common.h"
#include "nanopolish_fast5_io.h"
#include <assert.h>
#include <omp.h>
#include <vector>
Fast5Processor::Fast5Processor(const ReadDB& read_db,
const int num_threads,
const int batch_size) :
m_num_threads(num_threads),
m_batch_size(batch_size)
{
m_fast5s = read_db.get_unique_fast5s();
}
Fast5Processor::Fast5Processor(const std::string& fast5_file,
const int num_threads,
const int batch_size) :
m_num_threads(num_threads),
m_batch_size(batch_size)
{
m_fast5s.push_back(fast5_file);
}
Fast5Processor::~Fast5Processor()
{
}
void Fast5Processor::parallel_run(fast5_processor_work_function func)
{
// store number of threads so we can restore it after we're done
int prev_num_threads = omp_get_num_threads();
omp_set_num_threads(m_num_threads);
for(size_t i = 0; i < m_fast5s.size(); ++i) {
fast5_file f5_file = fast5_open(m_fast5s[i]);
if(!fast5_is_open(f5_file)) {
continue;
}
std::vector<Fast5Data> fast5_data;
std::vector<std::string> reads = fast5_get_multi_read_groups(f5_file);
for(size_t j = 0; j < reads.size(); j++) {
// groups have names like "read_<uuid>"
// we're only interested in the uuid bit
assert(reads[j].find("read_") == 0);
std::string read_name = reads[j].substr(5);
Fast5Data data;
data.is_valid = true;
data.read_name = read_name;
// metadata
data.sequencing_kit = fast5_get_sequencing_kit(f5_file, read_name);
data.experiment_type = fast5_get_experiment_type(f5_file, read_name);
// raw data
data.channel_params = fast5_get_channel_params(f5_file, read_name);
data.rt = fast5_get_raw_samples(f5_file, read_name, data.channel_params);
data.start_time = fast5_get_start_time(f5_file, read_name);
fast5_data.push_back(data);
}
fast5_close(f5_file);
// run in parallel
#pragma omp parallel for schedule(dynamic)
for(size_t j = 0; j < fast5_data.size(); ++j) {
func(fast5_data[j]);
}
// destroy fast5 data
for(size_t j = 0; j < fast5_data.size(); ++j) {
free(fast5_data[j].rt.raw);
fast5_data[j].rt.raw = NULL;
}
fast5_data.clear();
}
// restore number of threads
omp_set_num_threads(prev_num_threads);
}
| 33.105263 | 85 | 0.575199 | Yufeng98 |
233b9832a92c5b20230f771ad0ada6e425ffa32f | 1,305 | cpp | C++ | leetcode/problems/medium/784-letter-case-permutation.cpp | wingkwong/competitive-programming | e8bf7aa32e87b3a020b63acac20e740728764649 | [
"MIT"
] | 18 | 2020-08-27T05:27:50.000Z | 2022-03-08T02:56:48.000Z | leetcode/problems/medium/784-letter-case-permutation.cpp | wingkwong/competitive-programming | e8bf7aa32e87b3a020b63acac20e740728764649 | [
"MIT"
] | null | null | null | leetcode/problems/medium/784-letter-case-permutation.cpp | wingkwong/competitive-programming | e8bf7aa32e87b3a020b63acac20e740728764649 | [
"MIT"
] | 1 | 2020-10-13T05:23:58.000Z | 2020-10-13T05:23:58.000Z | /*
Letter Case Permutation
https://leetcode.com/problems/letter-case-permutation/
Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string.
Return a list of all possible strings we could create. You can return the output in any order.
Example 1:
Input: S = "a1b2"
Output: ["a1b2","a1B2","A1b2","A1B2"]
Example 2:
Input: S = "3z4"
Output: ["3z4","3Z4"]
Example 3:
Input: S = "12345"
Output: ["12345"]
Example 4:
Input: S = "0"
Output: ["0"]
Constraints:
S will be a string with length between 1 and 12.
S will consist only of letters or digits.
*/
class Solution {
public:
void backtrack(string &s, int i, vector<string> &ans) {
if(i == s.size()) {
ans.push_back(s);
return;
}
// handle letter / digit
backtrack(s, i + 1, ans);
if(isalpha(s[i])) {
// A: 1 0000 0001
// a: 1 0010 0001
// Z: 1 0001 1010
// z: 1 0011 1010
// a -> A / A -> a
s[i] ^= (1 << 5);
// A -> a / a -> A
backtrack(s, i + 1, ans);
}
}
vector<string> letterCasePermutation(string S) {
vector<string> ans;
backtrack(S, 0, ans);
return ans;
}
}; | 21.75 | 115 | 0.544828 | wingkwong |
233dbdcd6e0bdebc9558c82e25aff45d1cf28385 | 18,563 | hpp | C++ | viennacl/linalg/direct_solve.hpp | bollig/viennacl | 6dac70e558ed42abe63d8c5bfd08465aafeda859 | [
"MIT"
] | 1 | 2020-09-21T08:33:10.000Z | 2020-09-21T08:33:10.000Z | viennacl/linalg/direct_solve.hpp | bollig/viennacl | 6dac70e558ed42abe63d8c5bfd08465aafeda859 | [
"MIT"
] | null | null | null | viennacl/linalg/direct_solve.hpp | bollig/viennacl | 6dac70e558ed42abe63d8c5bfd08465aafeda859 | [
"MIT"
] | null | null | null | #ifndef VIENNACL_LINALG_DIRECT_SOLVE_HPP_
#define VIENNACL_LINALG_DIRECT_SOLVE_HPP_
/* =========================================================================
Copyright (c) 2010-2012, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
Portions of this software are copyright by UChicago Argonne, LLC.
-----------------
ViennaCL - The Vienna Computing Library
-----------------
Project Head: Karl Rupp rupp@iue.tuwien.ac.at
(A list of authors and contributors can be found in the PDF manual)
License: MIT (X11), see file LICENSE in the base directory
============================================================================= */
/** @file viennacl/linalg/direct_solve.hpp
@brief Implementations of dense direct solvers are found here.
*/
#include "viennacl/forwards.h"
#include "viennacl/meta/enable_if.hpp"
#include "viennacl/vector.hpp"
#include "viennacl/matrix.hpp"
#include "viennacl/linalg/host_based/direct_solve.hpp"
#ifdef VIENNACL_WITH_OPENCL
#include "viennacl/linalg/opencl/direct_solve.hpp"
#endif
#ifdef VIENNACL_WITH_CUDA
#include "viennacl/linalg/cuda/direct_solve.hpp"
#endif
namespace viennacl
{
namespace linalg
{
//
// A \ B:
//
/** @brief Direct inplace solver for dense triangular systems. Matlab notation: A \ B
*
* @param A The system matrix
* @param B The matrix of row vectors, where the solution is directly written to
*/
template <typename M1,
typename M2, typename SOLVERTAG>
typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value
&& viennacl::is_any_dense_nonstructured_matrix<M2>::value
>::type
inplace_solve(const M1 & A, M2 & B, SOLVERTAG)
{
assert( (viennacl::traits::size1(A) == viennacl::traits::size2(A)) && bool("Size check failed in inplace_solve(): size1(A) != size2(A)"));
assert( (viennacl::traits::size1(A) == viennacl::traits::size1(B)) && bool("Size check failed in inplace_solve(): size1(A) != size1(B)"));
switch (viennacl::traits::handle(A).get_active_handle_id())
{
case viennacl::MAIN_MEMORY:
viennacl::linalg::host_based::inplace_solve(A, B, SOLVERTAG());
break;
#ifdef VIENNACL_WITH_OPENCL
case viennacl::OPENCL_MEMORY:
viennacl::linalg::opencl::inplace_solve(A, B, SOLVERTAG());
break;
#endif
#ifdef VIENNACL_WITH_CUDA
case viennacl::CUDA_MEMORY:
viennacl::linalg::cuda::inplace_solve(A, B, SOLVERTAG());
break;
#endif
default:
throw "not implemented";
}
}
/** @brief Direct inplace solver for dense triangular systems with transposed right hand side
*
* @param A The system matrix
* @param proxy_B The transposed matrix of row vectors, where the solution is directly written to
*/
template <typename M1,
typename M2, typename SOLVERTAG>
typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value
&& viennacl::is_any_dense_nonstructured_matrix<M2>::value
>::type
inplace_solve(const M1 & A,
matrix_expression< const M2, const M2, op_trans> proxy_B,
SOLVERTAG)
{
assert( (viennacl::traits::size1(A) == viennacl::traits::size2(A)) && bool("Size check failed in inplace_solve(): size1(A) != size2(A)"));
assert( (viennacl::traits::size1(A) == viennacl::traits::size1(proxy_B)) && bool("Size check failed in inplace_solve(): size1(A) != size1(B^T)"));
switch (viennacl::traits::handle(A).get_active_handle_id())
{
case viennacl::MAIN_MEMORY:
viennacl::linalg::host_based::inplace_solve(A, proxy_B, SOLVERTAG());
break;
#ifdef VIENNACL_WITH_OPENCL
case viennacl::OPENCL_MEMORY:
viennacl::linalg::opencl::inplace_solve(A, proxy_B, SOLVERTAG());
break;
#endif
#ifdef VIENNACL_WITH_CUDA
case viennacl::CUDA_MEMORY:
viennacl::linalg::cuda::inplace_solve(A, proxy_B, SOLVERTAG());
break;
#endif
default:
throw "not implemented";
}
}
//upper triangular solver for transposed lower triangular matrices
/** @brief Direct inplace solver for dense triangular systems that stem from transposed triangular systems
*
* @param proxy_A The system matrix proxy
* @param B The matrix holding the load vectors, where the solution is directly written to
*/
template <typename M1,
typename M2, typename SOLVERTAG>
typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value
&& viennacl::is_any_dense_nonstructured_matrix<M2>::value
>::type
inplace_solve(const matrix_expression< const M1, const M1, op_trans> & proxy_A,
M2 & B,
SOLVERTAG)
{
assert( (viennacl::traits::size1(proxy_A) == viennacl::traits::size2(proxy_A)) && bool("Size check failed in inplace_solve(): size1(A) != size2(A)"));
assert( (viennacl::traits::size1(proxy_A) == viennacl::traits::size1(B)) && bool("Size check failed in inplace_solve(): size1(A^T) != size1(B)"));
switch (viennacl::traits::handle(proxy_A.lhs()).get_active_handle_id())
{
case viennacl::MAIN_MEMORY:
viennacl::linalg::host_based::inplace_solve(proxy_A, B, SOLVERTAG());
break;
#ifdef VIENNACL_WITH_OPENCL
case viennacl::OPENCL_MEMORY:
viennacl::linalg::opencl::inplace_solve(proxy_A, B, SOLVERTAG());
break;
#endif
#ifdef VIENNACL_WITH_CUDA
case viennacl::CUDA_MEMORY:
viennacl::linalg::cuda::inplace_solve(proxy_A, B, SOLVERTAG());
break;
#endif
default:
throw "not implemented";
}
}
/** @brief Direct inplace solver for dense transposed triangular systems with transposed right hand side. Matlab notation: A' \ B'
*
* @param proxy_A The system matrix proxy
* @param proxy_B The matrix holding the load vectors, where the solution is directly written to
*/
template <typename M1,
typename M2, typename SOLVERTAG>
typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value
&& viennacl::is_any_dense_nonstructured_matrix<M2>::value
>::type
inplace_solve(const matrix_expression< const M1, const M1, op_trans> & proxy_A,
matrix_expression< const M2, const M2, op_trans> proxy_B,
SOLVERTAG)
{
assert( (viennacl::traits::size1(proxy_A) == viennacl::traits::size2(proxy_A)) && bool("Size check failed in inplace_solve(): size1(A) != size2(A)"));
assert( (viennacl::traits::size1(proxy_A) == viennacl::traits::size1(proxy_B)) && bool("Size check failed in inplace_solve(): size1(A^T) != size1(B^T)"));
switch (viennacl::traits::handle(proxy_A.lhs()).get_active_handle_id())
{
case viennacl::MAIN_MEMORY:
viennacl::linalg::host_based::inplace_solve(proxy_A, proxy_B, SOLVERTAG());
break;
#ifdef VIENNACL_WITH_OPENCL
case viennacl::OPENCL_MEMORY:
viennacl::linalg::opencl::inplace_solve(proxy_A, proxy_B, SOLVERTAG());
break;
#endif
#ifdef VIENNACL_WITH_CUDA
case viennacl::CUDA_MEMORY:
viennacl::linalg::cuda::inplace_solve(proxy_A, proxy_B, SOLVERTAG());
break;
#endif
default:
throw "not implemented";
}
}
//
// A \ b
//
template <typename M1,
typename V1, typename SOLVERTAG>
typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value
&& viennacl::is_any_dense_nonstructured_vector<V1>::value
>::type
inplace_solve(const M1 & mat,
V1 & vec,
SOLVERTAG)
{
assert( (mat.size1() == vec.size()) && bool("Size check failed in inplace_solve(): size1(A) != size(b)"));
assert( (mat.size2() == vec.size()) && bool("Size check failed in inplace_solve(): size2(A) != size(b)"));
switch (viennacl::traits::handle(mat).get_active_handle_id())
{
case viennacl::MAIN_MEMORY:
viennacl::linalg::host_based::inplace_solve(mat, vec, SOLVERTAG());
break;
#ifdef VIENNACL_WITH_OPENCL
case viennacl::OPENCL_MEMORY:
viennacl::linalg::opencl::inplace_solve(mat, vec, SOLVERTAG());
break;
#endif
#ifdef VIENNACL_WITH_CUDA
case viennacl::CUDA_MEMORY:
viennacl::linalg::cuda::inplace_solve(mat, vec, SOLVERTAG());
break;
#endif
default:
throw "not implemented";
}
}
/** @brief Direct inplace solver for dense upper triangular systems that stem from transposed lower triangular systems
*
* @param proxy The system matrix proxy
* @param vec The load vector, where the solution is directly written to
*/
template <typename M1,
typename V1, typename SOLVERTAG>
typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value
&& viennacl::is_any_dense_nonstructured_vector<V1>::value
>::type
inplace_solve(const matrix_expression< const M1, const M1, op_trans> & proxy,
V1 & vec,
SOLVERTAG)
{
assert( (proxy.lhs().size1() == vec.size()) && bool("Size check failed in inplace_solve(): size1(A) != size(b)"));
assert( (proxy.lhs().size2() == vec.size()) && bool("Size check failed in inplace_solve(): size2(A) != size(b)"));
switch (viennacl::traits::handle(proxy.lhs()).get_active_handle_id())
{
case viennacl::MAIN_MEMORY:
viennacl::linalg::host_based::inplace_solve(proxy, vec, SOLVERTAG());
break;
#ifdef VIENNACL_WITH_OPENCL
case viennacl::OPENCL_MEMORY:
viennacl::linalg::opencl::inplace_solve(proxy, vec, SOLVERTAG());
break;
#endif
#ifdef VIENNACL_WITH_CUDA
case viennacl::CUDA_MEMORY:
viennacl::linalg::cuda::inplace_solve(proxy, vec, SOLVERTAG());
break;
#endif
default:
throw "not implemented";
}
}
/////////////////// general wrappers for non-inplace solution //////////////////////
namespace detail
{
template <typename T>
struct extract_embedded_type
{
typedef T type;
};
template <typename T>
struct extract_embedded_type< matrix_range<T> >
{
typedef T type;
};
template <typename T>
struct extract_embedded_type< matrix_slice<T> >
{
typedef T type;
};
template <typename T>
struct extract_embedded_type< vector_range<T> >
{
typedef T type;
};
template <typename T>
struct extract_embedded_type< vector_slice<T> >
{
typedef T type;
};
}
/** @brief Convenience functions for C = solve(A, B, some_tag()); Creates a temporary result matrix and forwards the request to inplace_solve()
*
* @param A The system matrix
* @param B The matrix of load vectors
* @param tag Dispatch tag
*/
template <typename M1,
typename M2,
typename SOLVERTAG>
typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value
&& viennacl::is_any_dense_nonstructured_matrix<M2>::value,
typename detail::extract_embedded_type<M2>::type
>::type
solve(const M1 & A, const M2 & B, SOLVERTAG tag)
{
typedef typename detail::extract_embedded_type<M2>::type MatrixType;
// do an inplace solve on the result vector:
MatrixType result(B);
inplace_solve(A, result, tag);
return result;
}
//////////
/** @brief Convenience functions for C = solve(A, B^T, some_tag()); Creates a temporary result matrix and forwards the request to inplace_solve()
*
* @param A The system matrix
* @param proxy The transposed load vector
* @param tag Dispatch tag
*/
template <typename M1,
typename M2, typename SOLVERTAG>
typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value
&& viennacl::is_any_dense_nonstructured_matrix<M2>::value,
typename detail::extract_embedded_type<M2>::type
>::type
solve(const M1 & A,
const matrix_expression< const M2, const M2, op_trans> & proxy,
SOLVERTAG tag)
{
typedef typename detail::extract_embedded_type<M2>::type MatrixType;
// do an inplace solve on the result vector:
MatrixType result(proxy);
inplace_solve(A, result, tag);
return result;
}
/** @brief Convenience functions for result = solve(mat, vec, some_tag()); Creates a temporary result vector and forwards the request to inplace_solve()
*
* @param mat The system matrix
* @param vec The load vector
* @param tag Dispatch tag
*/
template<typename M1,
typename V1, typename SOLVERTAG>
typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value
&& viennacl::is_any_dense_nonstructured_vector<V1>::value,
typename detail::extract_embedded_type<V1>::type
>::type
solve(const M1 & mat,
const V1 & vec,
SOLVERTAG const & tag)
{
// do an inplace solve on the result vector:
typename detail::extract_embedded_type<V1>::type result(vec);
inplace_solve(mat, result, tag);
return result;
}
///////////// transposed system matrix:
/** @brief Convenience functions for result = solve(trans(mat), B, some_tag()); Creates a temporary result matrix and forwards the request to inplace_solve()
*
* @param proxy The transposed system matrix proxy
* @param B The matrix of load vectors
* @param tag Dispatch tag
*/
template <typename M1,
typename M2, typename SOLVERTAG>
typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value
&& viennacl::is_any_dense_nonstructured_matrix<M2>::value,
typename detail::extract_embedded_type<M2>::type
>::type
solve(const matrix_expression< const M1, const M1, op_trans> & proxy,
const M2 & B,
SOLVERTAG tag)
{
typedef typename detail::extract_embedded_type<M2>::type MatrixType;
// do an inplace solve on the result vector:
MatrixType result(B);
inplace_solve(proxy, result, tag);
return result;
}
/** @brief Convenience functions for result = solve(trans(mat), vec, some_tag()); Creates a temporary result vector and forwards the request to inplace_solve()
*
* @param proxy_A The transposed system matrix proxy
* @param proxy_B The transposed matrix of load vectors, where the solution is directly written to
* @param tag Dispatch tag
*/
template <typename M1,
typename M2, typename SOLVERTAG>
typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value
&& viennacl::is_any_dense_nonstructured_matrix<M2>::value,
typename detail::extract_embedded_type<M2>::type
>::type
solve(const matrix_expression< const M1, const M1, op_trans> & proxy_A,
const matrix_expression< const M2, const M2, op_trans> & proxy_B,
SOLVERTAG tag)
{
typedef typename detail::extract_embedded_type<M2>::type MatrixType;
// do an inplace solve on the result vector:
MatrixType result(proxy_B);
inplace_solve(proxy_A, result, tag);
return result;
}
/** @brief Convenience functions for result = solve(trans(mat), vec, some_tag()); Creates a temporary result vector and forwards the request to inplace_solve()
*
* @param proxy The transposed system matrix proxy
* @param vec The load vector, where the solution is directly written to
* @param tag Dispatch tag
*/
template<typename M1,
typename V1, typename SOLVERTAG>
typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value
&& viennacl::is_any_dense_nonstructured_vector<V1>::value,
typename detail::extract_embedded_type<V1>::type
>::type
solve(const matrix_expression< const M1,
const M1,
op_trans> & proxy,
const V1 & vec,
SOLVERTAG const & tag)
{
// do an inplace solve on the result vector:
typename detail::extract_embedded_type<V1>::type result(vec);
inplace_solve(proxy, result, tag);
return result;
}
}
}
#endif
| 39.495745 | 164 | 0.575661 | bollig |
2342b0b19f851d7dda2cc6af31c32e3b1163ec82 | 15,043 | cpp | C++ | src/content_loader.cpp | adct-the-experimenter/DTL-Dungeon-Editor | 6e97f56effbec3923b85bf5753b408aec10f863f | [
"BSD-3-Clause"
] | null | null | null | src/content_loader.cpp | adct-the-experimenter/DTL-Dungeon-Editor | 6e97f56effbec3923b85bf5753b408aec10f863f | [
"BSD-3-Clause"
] | null | null | null | src/content_loader.cpp | adct-the-experimenter/DTL-Dungeon-Editor | 6e97f56effbec3923b85bf5753b408aec10f863f | [
"BSD-3-Clause"
] | null | null | null | #include "content_loader.h"
#include "pugixml.hpp"
#include <iostream>
#include <string>
#include "globalvariables.h"
#include "sprite.h"
enemy_content_map enemyContentMap;
void SetEnemyContentFromEnemyDirXMLFile(std::string xml_enemy_scripts_file_dir,
std::string xml_enemy_scripts_file_path)
{
// Create empty XML document within memory
pugi::xml_document doc;
// Load XML file into memory
// Remark: to fully read declaration entries you have to specify
// "pugi::parse_declaration"
pugi::xml_parse_result result = doc.load_file(xml_enemy_scripts_file_path.c_str(),
pugi::parse_default);
if (!result)
{
std::cout << "Parse error: " << result.description()
<< ", character pos= " << result.offset;
return;
}
pugi::xml_node enemyDirRoot = doc.child("EnemyDirRoot");
size_t iterator = 0;
//go through each tile type in tiles node
for (pugi::xml_node enemyNode = enemyDirRoot.first_child(); enemyNode; enemyNode = enemyNode.next_sibling())
{
std::string valName = enemyNode.attribute("name").value();
std::string valFilepath = enemyNode.attribute("scriptfilepath").value();
std::string valMediaDir = enemyNode.attribute("mediaDir").value();
std::string valXMLDefFilepath = enemyNode.attribute("xmldefpath").value();
//assuming file paths in xml file is set relative to xml filepath itself
std::string filepath = xml_enemy_scripts_file_dir + "/" + valFilepath;
std::cout << "file read:" << filepath << std::endl;
std::string mediaDir = xml_enemy_scripts_file_dir + "/" + valMediaDir;
std::string xml_def_fp = xml_enemy_scripts_file_dir + "/" + valXMLDefFilepath;
EnemyContent ec;
ec.name = valName;
ec.script_filepath = filepath;
ec.mediaDir = mediaDir;
ec.xml_def_filepath = xml_def_fp;
std::pair<std::string,EnemyContent> thisEnemyContentPair (valName,ec);
enemyContentMap.insert (thisEnemyContentPair);
iterator++;
}
}
void LoadContentFromXMLFiles()
{
std::string xml_enemy_scripts_file_dir = DATADIR_STR + "/EnemyPacks";
std::string xml_enemy_scripts_file_path = xml_enemy_scripts_file_dir + "/enemy_directory.xml";
SetEnemyContentFromEnemyDirXMLFile(xml_enemy_scripts_file_dir,xml_enemy_scripts_file_path);
}
bool loadScriptedEnemyVisualMedia(std::string xml_file_path,std::string xml_file_dir,
LTexture* cTexture,
std::vector <SDL_Rect> &walk_clips,
SDL_Renderer* gRenderer )
{
// Create empty XML document within memory
pugi::xml_document doc;
// Load XML file into memory
// Remark: to fully read declaration entries you have to specify
// "pugi::parse_declaration"
pugi::xml_parse_result result = doc.load_file(xml_file_path.c_str(),
pugi::parse_default);
if (!result)
{
std::cout << "Parse error: " << result.description() << ", character pos= " << result.offset;
return false;
}
pugi::xml_node root = doc.child("EnemyRoot");
std::string cTexFilePath = xml_file_dir + "/" + root.child("Texture").attribute("path").value();
//initialize texture
if(!cTexture->loadFromFile(cTexFilePath.c_str(),gRenderer) )
{
std::cout << "scripted enemy image loading failed! \n";
std::cout << "filepath:" << cTexFilePath << std::endl;
return false;
}
else
{
std::string valString;
//set size of walk clips vector
valString = root.child("WalkClips").child("clip_num").attribute("number").value();
size_t clipsNum = atoi(valString.c_str());
walk_clips.resize(clipsNum);
//set width and height of each uniform clips
valString = root.child("WalkClips").child("clip_width").attribute("width").value();
std::int8_t width = atoi(valString.c_str());
valString = root.child("WalkClips").child("clip_height").attribute("height").value();
std::int8_t height = atoi(valString.c_str());
SDL_Rect clip;
clip.w = width;
clip.h = height;
valString = root.child("WalkClips").child("UP_1").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("UP_1").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::UP_1] = clip;
valString = root.child("WalkClips").child("UP_2").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("UP_2").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::UP_2] = clip;
valString = root.child("WalkClips").child("UP_3").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("UP_3").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::UP_3] = clip;
valString = root.child("WalkClips").child("UP_4").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("UP_4").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::UP_4] = clip;
valString = root.child("WalkClips").child("UP_LEFT_1").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("UP_LEFT_1").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::UP_LEFT_1] = clip;
valString = root.child("WalkClips").child("UP_LEFT_2").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("UP_LEFT_2").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::UP_LEFT_2] = clip;
valString = root.child("WalkClips").child("UP_LEFT_3").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("UP_LEFT_3").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::UP_LEFT_3] = clip;
valString = root.child("WalkClips").child("UP_LEFT_4").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("UP_LEFT_4").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::UP_LEFT_4] = clip;
valString = root.child("WalkClips").child("LEFT_1").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("LEFT_1").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::LEFT_1] = clip;
valString = root.child("WalkClips").child("LEFT_2").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("LEFT_2").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::LEFT_2] = clip;
valString = root.child("WalkClips").child("LEFT_3").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("LEFT_3").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::LEFT_3] = clip;
valString = root.child("WalkClips").child("LEFT_4").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("LEFT_4").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::LEFT_4] = clip;
valString = root.child("WalkClips").child("DOWN_LEFT_1").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("DOWN_LEFT_1").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::DOWN_LEFT_1] = clip;
valString = root.child("WalkClips").child("DOWN_LEFT_2").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("DOWN_LEFT_2").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::DOWN_LEFT_2] = clip;
valString = root.child("WalkClips").child("DOWN_LEFT_3").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("DOWN_LEFT_3").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::DOWN_LEFT_3] = clip;
valString = root.child("WalkClips").child("DOWN_LEFT_4").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("DOWN_LEFT_4").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::DOWN_LEFT_4] = clip;
valString = root.child("WalkClips").child("DOWN_1").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("DOWN_1").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::DOWN_1] = clip;
valString = root.child("WalkClips").child("DOWN_2").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("DOWN_2").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::DOWN_2] = clip;
valString = root.child("WalkClips").child("UP_1").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("UP_1").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::DOWN_3] = clip;
valString = root.child("WalkClips").child("DOWN_4").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("DOWN_4").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::DOWN_4] = clip;
valString = root.child("WalkClips").child("RIGHT_1").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("RIGHT_1").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::RIGHT_1] = clip;
valString = root.child("WalkClips").child("RIGHT_2").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("RIGHT_2").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::RIGHT_2] = clip;
valString = root.child("WalkClips").child("RIGHT_3").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("RIGHT_3").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::RIGHT_3] = clip;
valString = root.child("WalkClips").child("RIGHT_4").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("RIGHT_4").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::RIGHT_4] = clip;
valString = root.child("WalkClips").child("DOWN_RIGHT_1").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("DOWN_RIGHT_1").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::DOWN_RIGHT_1] = clip;
valString = root.child("WalkClips").child("DOWN_RIGHT_2").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("DOWN_RIGHT_2").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::DOWN_RIGHT_2] = clip;
valString = root.child("WalkClips").child("DOWN_RIGHT_3").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("DOWN_RIGHT_3").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::DOWN_RIGHT_3] = clip;
valString = root.child("WalkClips").child("DOWN_RIGHT_4").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("DOWN_RIGHT_4").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::DOWN_RIGHT_4] = clip;
valString = root.child("WalkClips").child("UP_RIGHT_1").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("UP_RIGHT_1").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::UP_RIGHT_1] = clip;
valString = root.child("WalkClips").child("UP_RIGHT_2").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("UP_RIGHT_2").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::UP_RIGHT_2] = clip;
valString = root.child("WalkClips").child("UP_RIGHT_3").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("UP_RIGHT_3").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::UP_RIGHT_3] = clip;
valString = root.child("WalkClips").child("UP_RIGHT_4").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("UP_RIGHT_4").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::UP_RIGHT_4] = clip;
}
return true;
}
void freeScriptedEnemyVisualMedia(LTexture* cTexture)
{
if(cTexture != nullptr)
{
cTexture = nullptr;
}
}
bool setEnemyTypeAttributes(EnemyContent* thisEnemyContent, std::string xml_file_path)
{
// Create empty XML document within memory
pugi::xml_document doc;
// Load XML file into memory
// Remark: to fully read declaration entries you have to specify
// "pugi::parse_declaration"
pugi::xml_parse_result result = doc.load_file(xml_file_path.c_str(),
pugi::parse_default);
if (!result)
{
std::cout << "Parse error: " << result.description() << ", character pos= " << result.offset;
return false;
}
pugi::xml_node root = doc.child("EnemyRoot");
std::string healthStr = root.child("Attributes").attribute("health").value();
std::string speedStr = root.child("Attributes").attribute("speed").value();
thisEnemyContent->health = std::stoi(healthStr);
thisEnemyContent->speed = std::stof(speedStr);
return true;
}
| 42.85755 | 109 | 0.62082 | adct-the-experimenter |
2346bec40cbcc0e227680ce6aab5c0413125682e | 712 | cpp | C++ | answers/lintcode/Candy.cpp | FeiZhan/Algo-Collection | 708c4a38112e0b381864809788b9e44ac5ae4d05 | [
"MIT"
] | 3 | 2015-09-04T21:32:31.000Z | 2020-12-06T00:37:32.000Z | answers/lintcode/Candy.cpp | FeiZhan/Algo-Collection | 708c4a38112e0b381864809788b9e44ac5ae4d05 | [
"MIT"
] | null | null | null | answers/lintcode/Candy.cpp | FeiZhan/Algo-Collection | 708c4a38112e0b381864809788b9e44ac5ae4d05 | [
"MIT"
] | null | null | null | class Solution {
public:
/**
* @param ratings Children's ratings
* @return the minimum candies you must give
*/
int candy(vector<int>& ratings) {
// Write your code here
vector<int> candy_list(ratings.size(), 0);
for (size_t i = 0; i < ratings.size(); ++ i) {
candy_list[i] = (i > 0 && ratings[i] > ratings[i - 1]) ? candy_list[i - 1] + 1 : 1;
}
for (size_t i = ratings.size() - 1; i < ratings.size(); -- i) {
candy_list[i] = max(candy_list[i], ((i + 1 < ratings.size() && ratings[i] > ratings[i + 1]) ? candy_list[i + 1] + 1 : 1));
}
return std::accumulate(candy_list.begin(), candy_list.end(), 0);
}
};
| 37.473684 | 134 | 0.523876 | FeiZhan |
2347f795da7678007632158d192f842b7f34764e | 31,446 | cpp | C++ | dbmanager.cpp | svasighi/UMIS | 4d930bbc6749e92ce1b8889bf8556ec3c68f50e0 | [
"MIT"
] | 1 | 2020-01-08T19:57:08.000Z | 2020-01-08T19:57:08.000Z | dbmanager.cpp | svasighi/UMIS | 4d930bbc6749e92ce1b8889bf8556ec3c68f50e0 | [
"MIT"
] | null | null | null | dbmanager.cpp | svasighi/UMIS | 4d930bbc6749e92ce1b8889bf8556ec3c68f50e0 | [
"MIT"
] | null | null | null | #include "dbmanager.h"
#include <QDir>
#include <QFile>
#include <QMessageBox>
#include <math.h>
DbManager::DbManager()
{
m_db = QSqlDatabase::addDatabase("QSQLITE", "Connection");
QString db_path = QDir::currentPath();
db_path = db_path + QString("/university.db");
m_db.setDatabaseName(db_path);
if (m_db.isOpen())
{
QMessageBox msgBox;
qDebug() << "opened";
}
else
{
if (!m_db.open())
qDebug() << m_db.lastError();
}
}
DbManager::~DbManager()
{
if (m_db.isOpen())
{
m_db.close();
}
}
bool DbManager::deleteProfessor(int username)
{
if (ProfessorExist(username))
{
QSqlQuery query(m_db);
query.prepare("DELETE FROM professors WHERE username = (:username)");
query.bindValue(":username", username);
bool success = query.exec();
if (!success)
{
qDebug() << "removeProf error: "
<< query.lastError();
return false;
}
return true;
}
}
Professor* DbManager::getProfessor(int username)
{
QSqlQuery query(m_db);
query.prepare("SELECT * FROM professors WHERE username = :username ");
query.bindValue(":username", username);
if (!query.exec())
{
qWarning() << __FUNCTION__ << ":" << __LINE__ << "Failed to fetch professors";
qWarning() << __FUNCTION__ << ":" << __LINE__ << m_db.databaseName();
}
if (query.next())
{
int username = username;
QString password = query.value(2).toString();
QString firstname = query.value(3).toString();
QString lastname = query.value(4).toString();
int departmentcode = query.value(5).toInt();
int groupcode = query.value(6).toInt();
QString object_type = query.value(7).toString();
int is_supervisor = query.value(8).toInt();
int degree = query.value(9).toInt();
if (object_type == "faculty")
{
Faculty* ProfessorTemp = new Faculty(username, password.toStdString(), firstname.toStdString(), lastname.toStdString(), departmentcode, groupcode, is_supervisor, degree);
return dynamic_cast<Professor*> (ProfessorTemp);
}
else if (object_type == "adjunctprofessor")
{
AdjunctProfessor* ProfessorTemp = new AdjunctProfessor(username, password.toStdString(), firstname.toStdString(), lastname.toStdString(), departmentcode, groupcode);
return dynamic_cast<Professor*> (ProfessorTemp);
}
else if (object_type == "groupmanager")
{
GroupManager* ProfessorTemp = new GroupManager(username, password.toStdString(), firstname.toStdString(), lastname.toStdString(), departmentcode, groupcode, is_supervisor, degree);
return dynamic_cast<Professor*> (ProfessorTemp);
}
else if (object_type == "departmentacademicassistant")
{
//
}
else if (object_type == "departmenthead")
{
DepartmentHead* ProfessorTemp = new DepartmentHead(username, lastname.toStdString(), password.toStdString(), lastname.toStdString(), departmentcode, groupcode, is_supervisor, degree);
return dynamic_cast<Professor*> (ProfessorTemp);
}
}
}
bool DbManager::addProfessor(int username, const QString& password, const QString& firstname, const QString& lastname, const int& departmentcode, const int& groupcode, const QString& object_type, const int& is_supervisor, const int& degree)
{
bool success = false;
QSqlQuery query(m_db);
query.prepare("INSERT INTO professors (username,password,firstname,lastname,departmentcode,groupcode,object_type,is_supervisor,degree) VALUES (:username,:password,:firstname,:lastname,:departmentcode,:groupcode,:object_type,:is_supervisor,:degree)");
query.bindValue(":username", username);
query.bindValue(":password", QString(QCryptographicHash::hash((password.toUtf8()), QCryptographicHash::Md5).toHex()));
query.bindValue(":firstname", firstname);
query.bindValue(":lastname", lastname);
query.bindValue(":departmentcode", departmentcode);
query.bindValue(":groupcode", groupcode);
query.bindValue(":object_type", object_type);
query.bindValue(":is_supervisor", is_supervisor);
query.bindValue(":degree", degree);
if (query.exec())
{
success = true;
}
else
{
qDebug() << "addProfessor error: "
<< query.lastError();
}
return success;
}
bool DbManager::ProfessorExist(int username)
{
QSqlQuery query(m_db);
query.prepare("SELECT username FROM professors WHERE username = (:username)");
query.bindValue(":username", username);
if (query.exec())
{
if (query.next())
{
return true;
}
}
return false;
}
std::vector<Professor*> DbManager::allProfessors(void)
{
std::vector<Professor*> professors;
QSqlQuery query(m_db);
query.prepare("SELECT username, password, firstname, lastname, departmentcode, groupcode, object_type, is_supervisor, degree FROM professors");
while (query.next())
{
int username = query.value(0).toInt();
QString password = query.value(1).toString();
QString firstname = query.value(2).toString();
QString lastname = query.value(3).toString();
int departmentcode = query.value(4).toInt();
int groupcode = query.value(5).toInt();
QString object_type = query.value(6).toString();
int is_supervisor = query.value(7).toInt();
int degree = query.value(8).toInt();
if (object_type == "adjunctprofessor")
{
AdjunctProfessor* adjunct = new AdjunctProfessor(username, password.toStdString(), firstname.toStdString(), lastname.toStdString(), departmentcode, groupcode);
professors.push_back(adjunct);
}
else if (object_type == "faculty")
{
Faculty* faculty = new Faculty(username, password.toStdString(), firstname.toStdString(), lastname.toStdString(), departmentcode, groupcode, is_supervisor, degree);
faculty->setDegree(query.value(1).toInt());
if (query.value(0).toInt())
faculty->setAsSupervisor(true);
professors.push_back(faculty);
}
else if (object_type == "groupmanager")
{
GroupManager* groupmanager = new GroupManager(username, password.toStdString(), firstname.toStdString(), lastname.toStdString(), departmentcode, groupcode, is_supervisor, degree);
groupmanager->setDegree(query.value(1).toInt());
if (query.value(0).toInt())
groupmanager->setAsSupervisor();
professors.push_back(groupmanager);
}
else if (object_type == "departmentacademicassistant")
{
/*
DepartmentAcademicAssistant* departmentacademicassistant = new DepartmentAcademicAssistant(username, password.toStdString(), firstname.toStdString(), lastname.toStdString(), departmentcode, groupcode, is_supervisor, degree);
departmentacademicassistant->setDegree(query.value(1).toInt());
if(query.value(0).toInt())
departmentacademicassistant->setAsSupervisor();
professors.push_back(departmentacademicassistant);
*/
}
else if (object_type == "departmenthead")
{
DepartmentHead* departmenthead = new DepartmentHead(username, password.toStdString(), firstname.toStdString(), lastname.toStdString(), departmentcode, groupcode, is_supervisor, degree);
departmenthead->setDegree(query.value(1).toInt());
if (query.value(0).toInt())
departmenthead->setAsSupervisor();
professors.push_back(departmenthead);
}
}
return professors;
}
Student* DbManager::getStudent(int username)
{
QSqlQuery query(m_db);
query.prepare("SELECT * FROM students WHERE username = :username ");
query.bindValue(":username", username);
if (!query.exec())
{
qWarning() << __FUNCTION__ << ":" << __LINE__ << "Failed to fetch students";
qWarning() << __FUNCTION__ << ":" << __LINE__ << m_db.databaseName();
}
if (query.next())
{
int username = username;
QString password = query.value(2).toString();
QString firstname = query.value(3).toString();
QString lastname = query.value(4).toString();
int departmentcode = query.value(5).toInt();
int groupcode = query.value(6).toInt();
int type = query.value(7).toInt();
QString field = query.value(8).toString();
Student* StudentTemp = new Student(username, password.toStdString(), firstname.toStdString(), lastname.toStdString(), departmentcode, type, field.toStdString(), groupcode);
return StudentTemp;
}
}
bool DbManager::addStudent(int username, const QString& password, const QString& firstname, const QString& lastname, const int& departmentcode, const int& groupcode, const int& type, const QString& field)
{
bool success = false;
QSqlQuery query(m_db);
query.prepare("INSERT INTO students (username, password, firstname, lastname, departmentcode, groupcode, type, field) VALUES (:username,:password,:firstname,:lastname,:departmentcode,:groupcode,:type,:field)");
query.bindValue(":username", username);
query.bindValue(":password", QString(QCryptographicHash::hash((password.toUtf8()), QCryptographicHash::Md5).toHex()));
query.bindValue(":firstname", firstname);
query.bindValue(":lastname", lastname);
query.bindValue(":departmentcode", departmentcode);
query.bindValue(":groupcode", groupcode);
query.bindValue(":type", type);
query.bindValue(":field", field);
if (query.exec())
{
success = true;
}
else
{
qDebug() << "addProfessor error: "
<< query.lastError();
}
return success;
}
bool DbManager::StudentExist(int username)
{
QSqlQuery query(m_db);
query.prepare("SELECT username FROM students WHERE username = (:username)");
query.bindValue(":username", username);
if (query.exec())
{
if (query.next())
{
return true;
}
}
return false;
}
std::vector<Student*> DbManager::allStudents(void)
{
std::vector<Student*> students;
QSqlQuery query(m_db);
query.prepare("SELECT username, password, firstname,lastname, departmentcode, groupcode, type, field FROM students");
while (query.next())
{
int username = query.value(1).toInt();
QString password = query.value(2).toString();
QString firstname = query.value(3).toString();
QString lastname = query.value(4).toString();
int departmentcode = query.value(5).toInt();
int groupcode = query.value(6).toInt();
int type = query.value(7).toInt();
QString field = query.value(8).toString();
Student* stu = new Student(username, password.toStdString(), firstname.toStdString(), lastname.toStdString(), departmentcode, type, field.toStdString(), groupcode);
students.push_back(stu);
}
return students;
}
bool DbManager::addCourse(const int& departmentcode, const int& groupcode,const int& coursecode, const int& credit, const QString& name, const int& type)
{
bool success = false;
QSqlQuery query(m_db);
query.prepare("INSERT INTO courses (departmentcode, groupcode, coursecode, credit, name, type) VALUES (:departmentcode,:groupcode,:coursecode,:credit,:name,:type)");
query.bindValue(":departmentcode", departmentcode);
query.bindValue(":groupcode", groupcode);
query.bindValue(":coursecode", coursecode);
query.bindValue(":credit", credit);
query.bindValue(":name", name);
query.bindValue(":type", type);
if (query.exec())
{
success = true;
}
else
{
qDebug() << "addCourse error: "
<< query.lastError();
}
return success;
}
bool DbManager::courseExistByCode(int departmentcode,int groupcode ,int coursecode){
QSqlQuery query(m_db);
query.prepare("SELECT * FROM courses WHERE departmentcode = :departmentcode AND groupcode = :groupcode AND coursecode = :coursecode");
query.bindValue(":departmentcode", departmentcode);
query.bindValue(":groupcode", groupcode);
query.bindValue(":coursecode", coursecode);
if (query.exec())
{
if (query.next())
{
return true;
}
}
return false;
}
bool DbManager::deleteCourseByCode(int departmentcode,int groupcode ,int coursecode){
if (courseExistByCode(departmentcode ,groupcode ,coursecode))
{
QSqlQuery query(m_db);
query.prepare("DELETE FROM courses WHERE departmentcode = :departmentcode AND groupcode = :groupcode AND coursecode = :coursecode");
query.bindValue(":departmentcode", departmentcode);
query.bindValue(":groupcode", groupcode);
query.bindValue(":coursecode", coursecode);
bool success = query.exec();
if (!success)
{
qDebug() << "removeCourse error: "
<< query.lastError();
return false;
}
return true;
}
}
Course* DbManager::getCourseByCode(int departmentcode,int groupcode ,int coursecode){
QSqlQuery query(m_db);
query.prepare("SELECT * FROM courses WHERE departmentcode = :departmentcode AND groupcode = :groupcode AND coursecode = :coursecode");
query.bindValue(":departmentcode", departmentcode);
query.bindValue(":groupcode", groupcode);
query.bindValue(":coursecode", coursecode);
if (!query.exec())
{
qWarning() << __FUNCTION__ << ":" << __LINE__ << "Failed to fetch course";
qWarning() << __FUNCTION__ << ":" << __LINE__ << m_db.databaseName();
}
if (query.next())
{
int departmentcode = query.value(1).toInt();
int groupcode = query.value(2).toInt();
int coursecode = query.value(3).toInt();
int credit = query.value(4).toInt();
QString name = query.value(5).toString();
int type = query.value(6).toInt();
Course* CourseTemp = new Course(departmentcode, groupcode, coursecode, credit, name.toStdString(), type);
return CourseTemp;
}
}
std::vector<Course*> DbManager::allCourse(void){
std::vector<Course*> courses;
QSqlQuery query(m_db);
query.prepare("SELECT * FROM courses");
while (query.next())
{
int departmentcode = query.value(1).toInt();
int groupcode = query.value(2).toInt();
int coursecode = query.value(3).toInt();
int credit = query.value(4).toInt();
QString name = query.value(5).toString();
int type = query.value(6).toInt();
Course* CourseTemp = new Course(departmentcode, groupcode, coursecode, credit, name.toStdString(), type);
courses.push_back(CourseTemp);
}
return courses;
}
std::vector<Course*> DbManager::getCourseByDepartment(int departmentcode){
std::vector<Course*> courses;
QSqlQuery query(m_db);
query.prepare("SELECT * FROM courses WHERE departmentcode = :departmentcode");
query.bindValue(":departmentcode", departmentcode);
while (query.next())
{
int departmentcode = query.value(1).toInt();
int groupcode = query.value(2).toInt();
int coursecode = query.value(3).toInt();
int credit = query.value(4).toInt();
QString name = query.value(5).toString();
int type = query.value(6).toInt();
Course* CourseTemp = new Course(departmentcode, groupcode, coursecode, credit, name.toStdString(), type);
courses.push_back(CourseTemp);
}
return courses;
}
std::vector<Course*> DbManager::getCourseByGroup(int departmentcode , int groupcode){
std::vector<Course*> courses;
QSqlQuery query(m_db);
query.prepare("SELECT * FROM courses WHERE departmentcode = :departmentcode AND groupcode = :groupcode ");
query.bindValue(":departmentcode", departmentcode);
query.bindValue(":groupcode", groupcode);
while (query.next())
{
int departmentcode = query.value(1).toInt();
int groupcode = query.value(2).toInt();
int coursecode = query.value(3).toInt();
int credit = query.value(4).toInt();
QString name = query.value(5).toString();
int type = query.value(6).toInt();
Course* CourseTemp = new Course(departmentcode, groupcode, coursecode, credit, name.toStdString(), type);
courses.push_back(CourseTemp);
}
return courses;
}
bool DbManager::addPresentedCourse(const int& course_id, const int& course_professor_id,const int& capacity, const int& enrolled_number, const int& waiting_number, const int& group_number, const int& term_number, std::vector<Course*> corequisit, std::vector<Course*> prerequisit)
{
QString prerequisit_string;
for(int i = 0 ; i < prerequisit.size() ; i++)
{
prerequisit_string += prerequisit[i]->getCourseID() + ";";
}
QString corequisit_string;
for(int i = 0 ; i < corequisit.size() ; i++)
{
corequisit_string += corequisit[i]->getCourseID() + ";";
}
bool success = false;
QSqlQuery query(m_db);
query.prepare("INSERT INTO presented_courses (course_id, course_professor_id, capacity, enrolled_number, waiting_number, group_number , term_number , corequisit , preriqisit) VALUES (:course_id,:course_professor_id,:capacity,:enrolled_number,:waiting_number,:group_number ,:term_number ,:corequisit ,:preriqisit)");
query.bindValue(":course_id", course_id);
query.bindValue(":course_professor_id", course_professor_id);
query.bindValue(":capacity", capacity);
query.bindValue(":enrolled_number", enrolled_number);
query.bindValue(":waiting_number", group_number);
query.bindValue(":term_number", term_number);
query.bindValue(":corequisit", corequisit_string.toUtf8());
query.bindValue(":prerequisit", prerequisit_string.toUtf8());
if (query.exec())
{
success = true;
}
else
{
qDebug() << "addPresentedCourse error: "
<< query.lastError();
}
return success;
}
bool DbManager::deletePresentedCourseByCode(const int& course_id ,const int& group_number,const int& term_number)
{
if (presentedCourseExistbyCode(course_id ,group_number ,term_number))
{
QSqlQuery query(m_db);
query.prepare("DELETE FROM presented_courses WHERE course_id = :course_id AND group_number = :group_number AND term_number = :term_number");
query.bindValue(":course_id", course_id);
query.bindValue(":group_number", group_number);
query.bindValue(":term_number", term_number);
bool success = query.exec();
if (!success)
{
qDebug() << "removePresentedCourse error: "
<< query.lastError();
return false;
}
return true;
}
}
bool DbManager::presentedCourseExistbyCode(const int& course_id ,const int& group_number,const int& term_number)
{
QSqlQuery query(m_db);
query.prepare("SELECT * FROM presented_courses WHERE course_id = :course_id AND group_number = :group_number AND term_number = :term_number");
query.bindValue(":course_id", course_id);
query.bindValue(":group_number", group_number);
query.bindValue(":term_number", term_number);
if (query.exec())
{
if (query.next())
{
return true;
}
}
return false;
}
PresentedCourse* DbManager::getPresentedCourseByCode(const int& course_id ,const int& group_number ,const int& term_number)
{
QSqlQuery query(m_db);
query.prepare("SELECT * FROM presented_courses WHERE course_id = :course_id AND group_number = :group_number AND term_number = :term_number");
query.bindValue(":course_id", course_id);
query.bindValue(":group_number", group_number);
query.bindValue(":term_number", term_number);
if (!query.exec())
{
qWarning() << __FUNCTION__ << ":" << __LINE__ << "Failed to fetch course";
qWarning() << __FUNCTION__ << ":" << __LINE__ << m_db.databaseName();
}
if (query.next())
{
int course_id = query.value(1).toInt();
int course_professor_id = query.value(2).toInt();
int capacity = query.value(3).toInt();
int enrolled_number = query.value(4).toInt();
int waiting_number = query.value(4).toInt();
int group_number = query.value(4).toInt();
int term_number = query.value(6).toInt();
int length = QString(course_id).length();
Course* corurse_temp = getCourseByCode( course_id / (int) pow(10 , length - 2) , course_id % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),course_id % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) );
Professor* professor_temp = getProfessor(course_professor_id);
PresentedCourse* PresentedCourseTemp = new PresentedCourse(corurse_temp ,term_number ,group_number , professor_temp ,capacity);
PresentedCourseTemp->setEnrolledNumber(enrolled_number);
PresentedCourseTemp->setWaitingNumber(waiting_number);
QStringList corequisit_list = query.value(5).toString().split(';');
QStringList prerequisit_list = query.value(5).toString().split(';');
for(int i =0 ; i < corequisit_list.count();i++)
{
int length = corequisit_list.at(i).length();
Course* coCoursTemp = getCourseByCode( corequisit_list.at(i).toInt() / (int) pow(10 , length - 2) , corequisit_list.at(i).toInt() % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),corequisit_list.at(i).toInt() % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) );
PresentedCourseTemp->addCorequisite(coCoursTemp);
}
for(int i =0 ; i < prerequisit_list.count();i++)
{
int length = prerequisit_list.at(i).length();
Course* preCoursTemp = getCourseByCode( prerequisit_list.at(i).toInt() / (int) pow(10 , length - 2) , prerequisit_list.at(i).toInt() % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),prerequisit_list.at(i).toInt() % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) );
PresentedCourseTemp->addPrerequisite(preCoursTemp);
}
return PresentedCourseTemp;
}
}
std::vector<PresentedCourse*> DbManager::allPresentedCourse(void){
std::vector<PresentedCourse*> presentedcourses;
QSqlQuery query(m_db);
query.prepare("SELECT * FROM presented_courses");
if (!query.exec())
{
qWarning() << __FUNCTION__ << ":" << __LINE__ << "Failed to fetch course";
qWarning() << __FUNCTION__ << ":" << __LINE__ << m_db.databaseName();
}
if (query.next())
{
int course_id = query.value(1).toInt();
int course_professor_id = query.value(2).toInt();
int capacity = query.value(3).toInt();
int enrolled_number = query.value(4).toInt();
int waiting_number = query.value(4).toInt();
int group_number = query.value(4).toInt();
int term_number = query.value(6).toInt();
int length = QString(course_id).length();
Course* corurse_temp = getCourseByCode( course_id / (int) pow(10 , length - 2) , course_id % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),course_id % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) );
Professor* professor_temp = getProfessor(course_professor_id);
PresentedCourse* PresentedCourseTemp = new PresentedCourse(corurse_temp ,term_number ,group_number , professor_temp ,capacity);
PresentedCourseTemp->setEnrolledNumber(enrolled_number);
PresentedCourseTemp->setWaitingNumber(waiting_number);
presentedcourses.push_back(PresentedCourseTemp);
QStringList corequisit_list = query.value(5).toString().split(';');
QStringList prerequisit_list = query.value(5).toString().split(';');
for(int i =0 ; i < corequisit_list.count();i++)
{
int length = corequisit_list.at(i).length();
Course* coCoursTemp = getCourseByCode( corequisit_list.at(i).toInt() / (int) pow(10 , length - 2) , corequisit_list.at(i).toInt() % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),corequisit_list.at(i).toInt() % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) );
PresentedCourseTemp->addCorequisite(coCoursTemp);
}
for(int i =0 ; i < prerequisit_list.count();i++)
{
int length = prerequisit_list.at(i).length();
Course* preCoursTemp = getCourseByCode( prerequisit_list.at(i).toInt() / (int) pow(10 , length - 2) , prerequisit_list.at(i).toInt() % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),prerequisit_list.at(i).toInt() % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) );
PresentedCourseTemp->addPrerequisite(preCoursTemp);
}
}
return presentedcourses;
}
std::vector<PresentedCourse*> DbManager::getPresentedCourseByCourseId(const int& _course_id ,const int& _term_number){
std::vector<PresentedCourse*> presentedcourses;
QSqlQuery query(m_db);
query.prepare("SELECT * FROM presented_courses WHERE course_id = :course_id AND term_number = :term_number");
query.bindValue(":course_id", _course_id);
query.bindValue(":term_number", _term_number);
if (!query.exec())
{
qWarning() << __FUNCTION__ << ":" << __LINE__ << "Failed to fetch course";
qWarning() << __FUNCTION__ << ":" << __LINE__ << m_db.databaseName();
}
if (query.next())
{
int course_id = query.value(1).toInt();
int course_professor_id = query.value(2).toInt();
int capacity = query.value(3).toInt();
int enrolled_number = query.value(4).toInt();
int waiting_number = query.value(4).toInt();
int group_number = query.value(4).toInt();
int term_number = query.value(6).toInt();
int length = QString(course_id).length();
Course* corurse_temp = getCourseByCode( course_id / (int) pow(10 , length - 2) , course_id % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),course_id % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) );
Professor* professor_temp = getProfessor(course_professor_id);
PresentedCourse* PresentedCourseTemp = new PresentedCourse(corurse_temp ,term_number ,group_number , professor_temp ,capacity);
PresentedCourseTemp->setEnrolledNumber(enrolled_number);
PresentedCourseTemp->setWaitingNumber(waiting_number);
presentedcourses.push_back(PresentedCourseTemp);
QStringList corequisit_list = query.value(5).toString().split(';');
QStringList prerequisit_list = query.value(5).toString().split(';');
for(int i =0 ; i < corequisit_list.count();i++)
{
int length = corequisit_list.at(i).length();
Course* coCoursTemp = getCourseByCode( corequisit_list.at(i).toInt() / (int) pow(10 , length - 2) , corequisit_list.at(i).toInt() % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),corequisit_list.at(i).toInt() % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) );
PresentedCourseTemp->addCorequisite(coCoursTemp);
}
for(int i =0 ; i < prerequisit_list.count();i++)
{
int length = prerequisit_list.at(i).length();
Course* preCoursTemp = getCourseByCode( prerequisit_list.at(i).toInt() / (int) pow(10 , length - 2) , prerequisit_list.at(i).toInt() % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),prerequisit_list.at(i).toInt() % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) );
PresentedCourseTemp->addPrerequisite(preCoursTemp);
}
}
return presentedcourses;
}
std::vector<PresentedCourse*> DbManager::getPresentedCourseByCourseProfessorId(const int& course_professor_id ,const int& term_number){
std::vector<PresentedCourse*> presentedcourses;
QSqlQuery query(m_db);
query.prepare("SELECT * FROM presented_courses WHERE course_professor_id = :course_professor_id AND term_number = :term_number");
query.bindValue(":course_professor_id", course_professor_id);
query.bindValue(":term_number", term_number);
if (!query.exec())
{
qWarning() << __FUNCTION__ << ":" << __LINE__ << "Failed to fetch course";
qWarning() << __FUNCTION__ << ":" << __LINE__ << m_db.databaseName();
}
if (query.next())
{
int course_id = query.value(1).toInt();
int course_professor_id = query.value(2).toInt();
int capacity = query.value(3).toInt();
int enrolled_number = query.value(4).toInt();
int waiting_number = query.value(4).toInt();
int group_number = query.value(4).toInt();
int term_number = query.value(6).toInt();
int length = QString(course_id).length();
Course* corurse_temp = getCourseByCode( course_id / (int) pow(10 , length - 2) , course_id % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),course_id % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) );
Professor* professor_temp = getProfessor(course_professor_id);
PresentedCourse* PresentedCourseTemp = new PresentedCourse(corurse_temp ,term_number ,group_number , professor_temp ,capacity);
PresentedCourseTemp->setEnrolledNumber(enrolled_number);
PresentedCourseTemp->setWaitingNumber(waiting_number);
presentedcourses.push_back(PresentedCourseTemp);
QStringList corequisit_list = query.value(5).toString().split(';');
QStringList prerequisit_list = query.value(5).toString().split(';');
for(int i =0 ; i < corequisit_list.count();i++)
{
int length = corequisit_list.at(i).length();
Course* coCoursTemp = getCourseByCode( corequisit_list.at(i).toInt() / (int) pow(10 , length - 2) , corequisit_list.at(i).toInt() % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),corequisit_list.at(i).toInt() % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) );
PresentedCourseTemp->addCorequisite(coCoursTemp);
}
for(int i =0 ; i < prerequisit_list.count();i++)
{
int length = prerequisit_list.at(i).length();
Course* preCoursTemp = getCourseByCode( prerequisit_list.at(i).toInt() / (int) pow(10 , length - 2) , prerequisit_list.at(i).toInt() % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),prerequisit_list.at(i).toInt() % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) );
PresentedCourseTemp->addPrerequisite(preCoursTemp);
}
}
return presentedcourses;
}
std::vector<PresentedCourse*> DbManager::getPresentedCourseByDepartment(const int& departmentcode ,const int& term_number){
std::vector<Course*> departmentcourses = getCourseByDepartment(departmentcode);
std::vector<PresentedCourse*> result ;
for(int i = 0 ; i < departmentcourses.size(); i++ ){
int course_id = departmentcourses[i]->getCourseID();
std::vector<PresentedCourse*> departmentPresentedCourse = getPresentedCourseByCourseId(course_id ,term_number);
for(int j = 0 ; j < departmentPresentedCourse.size(); j++ ){
result.push_back(departmentPresentedCourse[j]);
}
}
return result;
}
| 43.614424 | 319 | 0.645074 | svasighi |
234811d7f869c989805feacef1a6b93f1a4fcc77 | 3,235 | cpp | C++ | src/statisticsmenu.cpp | aobolensk/fishing-time | a56970eb026e8e86d16e9a7444ef892996d74546 | [
"MIT"
] | 1 | 2019-07-08T09:47:06.000Z | 2019-07-08T09:47:06.000Z | src/statisticsmenu.cpp | gooddoog/fishing-time | a56970eb026e8e86d16e9a7444ef892996d74546 | [
"MIT"
] | 278 | 2019-07-01T19:11:13.000Z | 2020-01-12T08:42:53.000Z | src/statisticsmenu.cpp | aobolensk/fishing-time | a56970eb026e8e86d16e9a7444ef892996d74546 | [
"MIT"
] | null | null | null | #include "statisticsmenu.h"
#include "game.h"
StatisticsMenu::StatisticsMenu(Game *game, QGridLayout *grid) :
Menu(game, grid) {
grid->addWidget(&statisticsLabel, 0, 1);
statisticsLabel.setVisible(false);
statisticsLabel.setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
grid->addWidget(&statisticsText, 1, 0, 1, 3);
statisticsText.setReadOnly(true);
statisticsText.setVisible(false);
statisticsText.setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
statisticsText.setTextInteractionFlags(Qt::NoTextInteraction);
statisticsText.setFrameStyle(QFrame::NoFrame);
grid->addWidget(&itemsButton, 2, 0);
itemsButton.setVisible(false);
itemsButton.setEnabled(false);
connect(&itemsButton, SIGNAL(released()), this, SLOT(itemsFunction()));
grid->addWidget(&coinsButton, 2, 1);
coinsButton.setVisible(false);
coinsButton.setEnabled(false);
connect(&coinsButton, SIGNAL(released()), this, SLOT(coinsFunction()));
grid->addWidget(&backButton, 3, 1);
backButton.setVisible(false);
backButton.setEnabled(false);
connect(&backButton, SIGNAL(released()), this, SLOT(backFunction()));
}
void StatisticsMenu::updateStatistics() {
qDebug() << "Statistics have been updated";
QString statText;
auto stats = game->users[game->activeUser].getStatistics(game);
auto it = stats.cbegin();
statText += "<table border=\"1\" width=\"100%\">";
while (it != stats.cend()) {
statText += QString(
"<tr>"
"<td width=\"50%\">%1</td>"
"<td width=\"50%\">%2</td>"
"</tr>"
).arg(
it->first,
it->second
);
++it;
}
statText += "</table>";
statisticsText.setText(statText);
}
void StatisticsMenu::display() {
this->pre_display();
timerUpdater = connect(&timer, SIGNAL(timeout()), this, SLOT(updateStatistics()));
timer.start(Config::STATISTICS_UPDATE_PERIOD);
updateStatistics();
statisticsLabel.setText(game->str.statistics);
statisticsLabel.setVisible(true);
statisticsText.setVisible(true);
itemsButton.setText(game->str.items);
itemsButton.setVisible(true);
itemsButton.setEnabled(true);
coinsButton.setText(game->str.coins);
coinsButton.setVisible(true);
coinsButton.setEnabled(true);
backButton.setText(game->str.back);
backButton.setVisible(true);
backButton.setEnabled(true);
displayed = true;
}
void StatisticsMenu::backFunction() {
this->hide();
game->gameMenu.display();
}
void StatisticsMenu::itemsFunction() {
this->hide();
game->itemStatisticsMenu.display();
}
void StatisticsMenu::coinsFunction() {
this->hide();
game->coinStatisticsMenu.display();
}
void StatisticsMenu::hide() {
this->pre_hide();
timer.stop();
disconnect(timerUpdater);
statisticsLabel.setVisible(false);
statisticsText.setVisible(false);
itemsButton.setVisible(false);
itemsButton.setEnabled(false);
coinsButton.setVisible(false);
coinsButton.setEnabled(false);
backButton.setVisible(false);
backButton.setEnabled(false);
displayed = false;
}
StatisticsMenu::~StatisticsMenu() {
}
| 26.516393 | 86 | 0.664297 | aobolensk |
23482a99736a6b10aed2567f92350be1b59d41fe | 349 | hpp | C++ | NativePlugin/CaptainAsteroid/src/physics/components/Identity.hpp | axoloto/CaptainAsteroid | fcdcb6bc6987ecf53226daa7027116e40d74401a | [
"Apache-2.0"
] | null | null | null | NativePlugin/CaptainAsteroid/src/physics/components/Identity.hpp | axoloto/CaptainAsteroid | fcdcb6bc6987ecf53226daa7027116e40d74401a | [
"Apache-2.0"
] | null | null | null | NativePlugin/CaptainAsteroid/src/physics/components/Identity.hpp | axoloto/CaptainAsteroid | fcdcb6bc6987ecf53226daa7027116e40d74401a | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "entityx/Entity.h"
namespace CaptainAsteroidCPP
{
namespace Comp
{
enum class Id
{
Unknown,
Asteroid,
SpaceShip,
LaserShot
};
struct Identity : public entityx::Component<Identity>
{
Identity(Id _id = Id::Unknown) : id(_id){};
Id id;
};
}// namespace Comp
}// namespace CaptainAsteroidCPP | 14.541667 | 55 | 0.659026 | axoloto |
234a2463845aca23371c81de23b68c50737f283d | 1,002 | cpp | C++ | MonoNative.Tests/mscorlib/System/Threading/mscorlib_System_Threading_LockCookie_Fixture.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | 7 | 2015-03-10T03:36:16.000Z | 2021-11-05T01:16:58.000Z | MonoNative.Tests/mscorlib/System/Threading/mscorlib_System_Threading_LockCookie_Fixture.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | 1 | 2020-06-23T10:02:33.000Z | 2020-06-24T02:05:47.000Z | MonoNative.Tests/mscorlib/System/Threading/mscorlib_System_Threading_LockCookie_Fixture.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | null | null | null | // Mono Native Fixture
// Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// Namespace: System.Threading
// Name: LockCookie
// C++ Typed Name: mscorlib::System::Threading::LockCookie
#include <gtest/gtest.h>
#include <mscorlib/System/Threading/mscorlib_System_Threading_LockCookie.h>
#include <mscorlib/System/mscorlib_System_String.h>
#include <mscorlib/System/mscorlib_System_Type.h>
namespace mscorlib
{
namespace System
{
namespace Threading
{
//Public Methods Tests
// Method GetHashCode
// Signature:
TEST(mscorlib_System_Threading_LockCookie_Fixture,GetHashCode_Test)
{
}
// Method Equals
// Signature: mscorlib::System::Threading::LockCookie obj
TEST(mscorlib_System_Threading_LockCookie_Fixture,Equals_1_Test)
{
}
// Method Equals
// Signature: mscorlib::System::Object obj
TEST(mscorlib_System_Threading_LockCookie_Fixture,Equals_2_Test)
{
}
}
}
}
| 19.269231 | 88 | 0.719561 | brunolauze |
234a614db5848cb39b632e5010b32656ed3dd194 | 10,096 | cpp | C++ | WebKit/Source/WebCore/bindings/scripts/test/JS/JSTestNamedConstructor.cpp | JavaScriptTesting/LJS | 9818dbdb421036569fff93124ac2385d45d01c3a | [
"Apache-2.0"
] | 1 | 2019-06-18T06:52:54.000Z | 2019-06-18T06:52:54.000Z | WebKit/Source/WebCore/bindings/scripts/test/JS/JSTestNamedConstructor.cpp | JavaScriptTesting/LJS | 9818dbdb421036569fff93124ac2385d45d01c3a | [
"Apache-2.0"
] | null | null | null | WebKit/Source/WebCore/bindings/scripts/test/JS/JSTestNamedConstructor.cpp | JavaScriptTesting/LJS | 9818dbdb421036569fff93124ac2385d45d01c3a | [
"Apache-2.0"
] | null | null | null | /*
This file is part of the WebKit open source project.
This file has been generated by generate-bindings.pl. DO NOT MODIFY!
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "JSTestNamedConstructor.h"
#include "ExceptionCode.h"
#include "JSDOMBinding.h"
#include "TestNamedConstructor.h"
#include <runtime/Error.h>
#include <wtf/GetPtr.h>
using namespace JSC;
namespace WebCore {
ASSERT_CLASS_FITS_IN_CELL(JSTestNamedConstructor);
ASSERT_HAS_TRIVIAL_DESTRUCTOR(JSTestNamedConstructor);
/* Hash table for constructor */
static const HashTableValue JSTestNamedConstructorTableValues[] =
{
{ "constructor", DontEnum | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsTestNamedConstructorConstructor), (intptr_t)0, NoIntrinsic },
{ 0, 0, 0, 0, NoIntrinsic }
};
static const HashTable JSTestNamedConstructorTable = { 2, 1, JSTestNamedConstructorTableValues, 0 };
/* Hash table for constructor */
static const HashTableValue JSTestNamedConstructorConstructorTableValues[] =
{
{ 0, 0, 0, 0, NoIntrinsic }
};
static const HashTable JSTestNamedConstructorConstructorTable = { 1, 0, JSTestNamedConstructorConstructorTableValues, 0 };
ASSERT_HAS_TRIVIAL_DESTRUCTOR(JSTestNamedConstructorConstructor);
const ClassInfo JSTestNamedConstructorConstructor::s_info = { "TestNamedConstructorConstructor", &Base::s_info, &JSTestNamedConstructorConstructorTable, 0, CREATE_METHOD_TABLE(JSTestNamedConstructorConstructor) };
JSTestNamedConstructorConstructor::JSTestNamedConstructorConstructor(Structure* structure, JSDOMGlobalObject* globalObject)
: DOMConstructorObject(structure, globalObject)
{
}
void JSTestNamedConstructorConstructor::finishCreation(ExecState* exec, JSDOMGlobalObject* globalObject)
{
Base::finishCreation(exec->globalData());
ASSERT(inherits(&s_info));
putDirect(exec->globalData(), exec->propertyNames().prototype, JSTestNamedConstructorPrototype::self(exec, globalObject), DontDelete | ReadOnly);
}
bool JSTestNamedConstructorConstructor::getOwnPropertySlot(JSCell* cell, ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
{
return getStaticValueSlot<JSTestNamedConstructorConstructor, JSDOMWrapper>(exec, &JSTestNamedConstructorConstructorTable, static_cast<JSTestNamedConstructorConstructor*>(cell), propertyName, slot);
}
bool JSTestNamedConstructorConstructor::getOwnPropertyDescriptor(JSObject* object, ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor)
{
return getStaticValueDescriptor<JSTestNamedConstructorConstructor, JSDOMWrapper>(exec, &JSTestNamedConstructorConstructorTable, static_cast<JSTestNamedConstructorConstructor*>(object), propertyName, descriptor);
}
const ClassInfo JSTestNamedConstructorNamedConstructor::s_info = { "AudioConstructor", &Base::s_info, 0, 0, CREATE_METHOD_TABLE(JSTestNamedConstructorNamedConstructor) };
JSTestNamedConstructorNamedConstructor::JSTestNamedConstructorNamedConstructor(Structure* structure, JSDOMGlobalObject* globalObject)
: DOMConstructorWithDocument(structure, globalObject)
{
}
void JSTestNamedConstructorNamedConstructor::finishCreation(ExecState* exec, JSDOMGlobalObject* globalObject)
{
Base::finishCreation(globalObject);
ASSERT(inherits(&s_info));
putDirect(exec->globalData(), exec->propertyNames().prototype, JSTestNamedConstructorPrototype::self(exec, globalObject), None);
}
EncodedJSValue JSC_HOST_CALL JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor(ExecState* exec)
{
JSTestNamedConstructorNamedConstructor* jsConstructor = static_cast<JSTestNamedConstructorNamedConstructor*>(exec->callee());
if (exec->argumentCount() < 1)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
ExceptionCode ec = 0;
const String& str1(ustringToString(MAYBE_MISSING_PARAMETER(exec, 0, MissingIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 0, MissingIsUndefined).toString(exec)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
const String& str2(ustringToString(MAYBE_MISSING_PARAMETER(exec, 1, MissingIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 1, MissingIsUndefined).toString(exec)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
const String& str3(ustringToString(MAYBE_MISSING_PARAMETER(exec, 2, MissingIsEmpty).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 2, MissingIsEmpty).toString(exec)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
RefPtr<TestNamedConstructor> object = TestNamedConstructor::createForJSConstructor(jsConstructor->document(), str1, str2, str3, ec);
if (ec) {
setDOMException(exec, ec);
return JSValue::encode(JSValue());
}
return JSValue::encode(asObject(toJS(exec, jsConstructor->globalObject(), object.get())));
}
ConstructType JSTestNamedConstructorNamedConstructor::getConstructData(JSCell*, ConstructData& constructData)
{
constructData.native.function = constructJSTestNamedConstructor;
return ConstructTypeHost;
}
/* Hash table for prototype */
static const HashTableValue JSTestNamedConstructorPrototypeTableValues[] =
{
{ 0, 0, 0, 0, NoIntrinsic }
};
static const HashTable JSTestNamedConstructorPrototypeTable = { 1, 0, JSTestNamedConstructorPrototypeTableValues, 0 };
const ClassInfo JSTestNamedConstructorPrototype::s_info = { "TestNamedConstructorPrototype", &Base::s_info, &JSTestNamedConstructorPrototypeTable, 0, CREATE_METHOD_TABLE(JSTestNamedConstructorPrototype) };
JSObject* JSTestNamedConstructorPrototype::self(ExecState* exec, JSGlobalObject* globalObject)
{
return getDOMPrototype<JSTestNamedConstructor>(exec, globalObject);
}
const ClassInfo JSTestNamedConstructor::s_info = { "TestNamedConstructor", &Base::s_info, &JSTestNamedConstructorTable, 0 , CREATE_METHOD_TABLE(JSTestNamedConstructor) };
JSTestNamedConstructor::JSTestNamedConstructor(Structure* structure, JSDOMGlobalObject* globalObject, PassRefPtr<TestNamedConstructor> impl)
: JSDOMWrapper(structure, globalObject)
, m_impl(impl.leakRef())
{
}
void JSTestNamedConstructor::finishCreation(JSGlobalData& globalData)
{
Base::finishCreation(globalData);
ASSERT(inherits(&s_info));
}
JSObject* JSTestNamedConstructor::createPrototype(ExecState* exec, JSGlobalObject* globalObject)
{
return JSTestNamedConstructorPrototype::create(exec->globalData(), globalObject, JSTestNamedConstructorPrototype::createStructure(globalObject->globalData(), globalObject, globalObject->objectPrototype()));
}
bool JSTestNamedConstructor::getOwnPropertySlot(JSCell* cell, ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
{
JSTestNamedConstructor* thisObject = jsCast<JSTestNamedConstructor*>(cell);
ASSERT_GC_OBJECT_INHERITS(thisObject, &s_info);
return getStaticValueSlot<JSTestNamedConstructor, Base>(exec, &JSTestNamedConstructorTable, thisObject, propertyName, slot);
}
bool JSTestNamedConstructor::getOwnPropertyDescriptor(JSObject* object, ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor)
{
JSTestNamedConstructor* thisObject = jsCast<JSTestNamedConstructor*>(object);
ASSERT_GC_OBJECT_INHERITS(thisObject, &s_info);
return getStaticValueDescriptor<JSTestNamedConstructor, Base>(exec, &JSTestNamedConstructorTable, thisObject, propertyName, descriptor);
}
JSValue jsTestNamedConstructorConstructor(ExecState* exec, JSValue slotBase, const Identifier&)
{
JSTestNamedConstructor* domObject = static_cast<JSTestNamedConstructor*>(asObject(slotBase));
return JSTestNamedConstructor::getConstructor(exec, domObject->globalObject());
}
JSValue JSTestNamedConstructor::getConstructor(ExecState* exec, JSGlobalObject* globalObject)
{
return getDOMConstructor<JSTestNamedConstructorConstructor>(exec, static_cast<JSDOMGlobalObject*>(globalObject));
}
static inline bool isObservable(JSTestNamedConstructor* jsTestNamedConstructor)
{
if (jsTestNamedConstructor->hasCustomProperties())
return true;
return false;
}
bool JSTestNamedConstructorOwner::isReachableFromOpaqueRoots(JSC::Handle<JSC::Unknown> handle, void*, SlotVisitor& visitor)
{
JSTestNamedConstructor* jsTestNamedConstructor = static_cast<JSTestNamedConstructor*>(handle.get().asCell());
if (jsTestNamedConstructor->impl()->hasPendingActivity())
return true;
if (!isObservable(jsTestNamedConstructor))
return false;
UNUSED_PARAM(visitor);
return false;
}
void JSTestNamedConstructorOwner::finalize(JSC::Handle<JSC::Unknown> handle, void* context)
{
JSTestNamedConstructor* jsTestNamedConstructor = static_cast<JSTestNamedConstructor*>(handle.get().asCell());
DOMWrapperWorld* world = static_cast<DOMWrapperWorld*>(context);
uncacheWrapper(world, jsTestNamedConstructor->impl(), jsTestNamedConstructor);
jsTestNamedConstructor->releaseImpl();
}
JSC::JSValue toJS(JSC::ExecState* exec, JSDOMGlobalObject* globalObject, TestNamedConstructor* impl)
{
return wrap<JSTestNamedConstructor>(exec, globalObject, impl);
}
TestNamedConstructor* toTestNamedConstructor(JSC::JSValue value)
{
return value.inherits(&JSTestNamedConstructor::s_info) ? static_cast<JSTestNamedConstructor*>(asObject(value))->impl() : 0;
}
}
| 46.100457 | 215 | 0.793483 | JavaScriptTesting |
234bfccab3251929a3269a0a312310297d174a52 | 10,710 | hpp | C++ | AabbIndex.hpp | stefanos-86/GeoIndex | 3c421ccdc8d18e771d03f6e52e03616b28ae4707 | [
"MIT"
] | 2 | 2017-06-25T09:21:42.000Z | 2020-05-20T12:57:51.000Z | AabbIndex.hpp | stefanos-86/GeoIndex | 3c421ccdc8d18e771d03f6e52e03616b28ae4707 | [
"MIT"
] | null | null | null | AabbIndex.hpp | stefanos-86/GeoIndex | 3c421ccdc8d18e771d03f6e52e03616b28ae4707 | [
"MIT"
] | null | null | null | #ifndef GEOINDEX_AABB_INDEX
#define GEOINDEX_AABB_INDEX
#include <vector>
#include <algorithm> // Or #include <parallel/algorithm>.
#include <iterator>
#include "Common.hpp"
namespace geoIndex {
/** This index uses the "Axis Aligned Bounding Box" (AABB) trick to quickly find points close to the
* given reference. Imagine a box, with sides parallel to the axes. That is the AABB.
* Its position makes it very easy to discover points inside: just ensure that each coordinate
* it between the min/max coordinates inside the box. We only have to compute the "top" and "bottom" corners.
* To go even faster, we keep the point coordinates sorted, so in a single pass (on each x, y, z) we can find
* all the indexes in the box limit.
*
* At each query it builds the AABB centered on the reference point and work on what is inside.
*
* The user must call complete() between modifications and lookups. But this is a costly operation.
*
*/
template <typename POINT>
class AabbIndex {
public:
/** If you know how many points you are going to use, tell it to this constructor to
* reserve memory. */
AabbIndex(const size_t expectedCollectionSize = 0) {
indexX.reserve(expectedCollectionSize);
indexY.reserve(expectedCollectionSize);
indexZ.reserve(expectedCollectionSize);
#ifdef GEO_INDEX_SAFETY_CHECKS
// There is nothing in the index, so it is sorted (you can't misplace... nothing). You can do lookups.
readyForLookups = true;
#endif
}
/** Adds a point to the index. Remember its name too. */
void index(const POINT& p, const typename PointTraits<POINT>::index index){
#ifdef GEO_INDEX_SAFETY_CHECKS
// Adding points probably breaks the order.
readyForLookups = false;
if (std::find_if(begin(indexX),
end(indexX),
[index](const IndexAndCoordinate<POINT>& indexEntry) {
return indexEntry.pointIndex == index; }
) != end(indexX))
throw std::runtime_error("Point indexed twice");
#endif
indexX.push_back({index, p.x});
indexY.push_back({index, p.y});
indexZ.push_back({index, p.z});
}
/** "Close" the index and allows lookups.
* Basically, sort its entries. It is best done "once and forever" as testing proves it can be a significant bottleneck.
* If the user forgets to call it he will get garbage results.
*/
void completed() {
std::sort(std::begin(indexX), std::end(indexX), SortByGeometry<POINT>);
std::sort(std::begin(indexY), std::end(indexY), SortByGeometry<POINT>);
std::sort(std::begin(indexZ), std::end(indexZ), SortByGeometry<POINT>);
/* The latest STL (C++17) has a parallel sort that could be useful...
* In the meanwhile, there is this nice thing from GNU.
__gnu_parallel::sort(indexX.begin(), indexX.end());
__gnu_parallel::sort(indexY.begin(), indexY.end());
__gnu_parallel::sort(indexZ.begin(), indexZ.end());
...but depends on openMP (libgomp) - for the moment I don't do it, to keep deps simple.
The speedup we can get here should be tested.
*/
#ifdef GEO_INDEX_SAFETY_CHECKS
readyForLookups = true;
#endif
}
/** Finds the points that are within distance d from p. Cleans the output vector before filling it.
* Returns the points sorted in distance order from p (to simplify computing the k-nearest-neighbor).
* The returned structure also gives the squared distance. The client can do a sqrt and use it for its computations.
*
* Uses the AABB trick described on top of the class to speed up the search for close points.
*
* Returns only points strictly within the AABB.
*/
void pointsWithinDistance(const POINT& p,
const typename PointTraits<POINT>::coordinate d,
std::vector<IndexAndSquaredDistance<POINT> >& output) const
{
#ifdef GEO_INDEX_SAFETY_CHECKS
CheckMeaningfulDistance(d);
if (! readyForLookups)
throw std::runtime_error("Index not ready. Did you call completed() after the last call to index(...)?");
#endif
std::vector<IndexAndCoordinate<POINT> > candidatesX;
std::vector<IndexAndCoordinate<POINT> > candidatesY;
std::vector<IndexAndCoordinate<POINT> > candidatesZ;
candidatesOnDimension(indexX, d, p.x, candidatesX);
candidatesOnDimension(indexY, d, p.y, candidatesY);
candidatesOnDimension(indexZ, d, p.z, candidatesZ);
std::vector<IndexAndCoordinate<POINT> > insideAabbXY;
std::set_intersection(std::begin(candidatesX),
std::end(candidatesX),
std::begin(candidatesY),
std::end(candidatesY),
std::back_inserter(insideAabbXY),
SortByPointIndex<POINT>
);
std::vector<IndexAndCoordinate<POINT> > insideAabb;
std::set_intersection(std::begin(insideAabbXY),
std::end(insideAabbXY),
std::begin(candidatesZ),
std::end(candidatesZ),
std::back_inserter(insideAabb),
SortByPointIndex<POINT>
);
const typename PointTraits<POINT>::coordinate referenceSquareDistance = d * d;
#ifdef GEO_INDEX_SAFETY_CHECKS
CheckOverflow(referenceSquareDistance);
#endif
output.clear();
for (const auto& candidate : insideAabb) {
const auto candidateIndex = candidate.pointIndex;
const typename PointTraits<POINT>::coordinate candidateX = findCoordinateOf(candidateIndex, candidatesX);
const typename PointTraits<POINT>::coordinate candidateY = findCoordinateOf(candidateIndex, candidatesY);
const typename PointTraits<POINT>::coordinate candidateZ = findCoordinateOf(candidateIndex, candidatesZ);
const auto candidateSquareDistance = SquaredDistance(p, POINT{candidateX, candidateY, candidateZ});
if (candidateSquareDistance < referenceSquareDistance)
output.push_back({candidateIndex, candidateSquareDistance});
}
// Don't forget we have to give the closests point first.
std::sort(std::begin(output), std::end(output), SortByGeometry<POINT>);
}
private:
std::vector<IndexAndCoordinate<POINT> > indexX;
std::vector<IndexAndCoordinate<POINT> > indexY;
std::vector<IndexAndCoordinate<POINT> > indexZ;
#ifdef GEO_INDEX_SAFETY_CHECKS
bool readyForLookups;
#endif
static bool CompareEntryWithCoordinate(const IndexAndCoordinate<POINT>& indexEntry,
const typename PointTraits<POINT>::coordinate searchedValue) {
return indexEntry.geometricValue < searchedValue;
}
static bool CompareEntryWithIndex(const IndexAndCoordinate<POINT>& indexEntry,
const typename PointTraits<POINT>::index searchedValue) {
return indexEntry.pointIndex < searchedValue;
}
/** Scan the given index and returns the indices of the "interesting" points.*/
void candidatesOnDimension(const std::vector<IndexAndCoordinate<POINT> >& indexForDimension,
const typename PointTraits<POINT>::coordinate searchDistance,
const typename PointTraits<POINT>::coordinate referenceCoordnate,
std::vector<IndexAndCoordinate<POINT> >& candidates) const
{
const typename PointTraits<POINT>::coordinate minAcceptedCoordinate = referenceCoordnate - searchDistance;
const typename PointTraits<POINT>::coordinate maxAcceptedCoordinate = referenceCoordnate + searchDistance;
const auto beginCandidates = std::lower_bound(std::begin(indexForDimension),
std::end(indexForDimension),
minAcceptedCoordinate,
CompareEntryWithCoordinate);
const auto endCandidates = std::lower_bound(beginCandidates, // the bigger values must be after, skip some elements.
std::end(indexForDimension),
maxAcceptedCoordinate,
CompareEntryWithCoordinate);
candidates.clear();
candidates.reserve(std::distance(beginCandidates, endCandidates));
for (auto i = beginCandidates; i != endCandidates; ++i)
candidates.push_back(*i);
// TODO: would it be faster with sets? THIS IS A MAJOR BOTTLENECK... in callgrind only?
//std::sort(std::begin(candidates), std::end(candidates), SortByPointIndex<POINT>);
std::sort(std::begin(candidates), std::end(candidates), [](const IndexAndGeometry<POINT>& lhs,
const IndexAndGeometry<POINT>& rhs)
{return lhs.pointIndex < rhs.pointIndex;});
}
/** This index does not store the full collection of points (but maybe it should, or should have a reference to it,
* to avoid this kind of issues - or maybe we should move the distance test outside the indexes).
* Assume that groupOfCandidates is sorted by point index and point indices do not repeat. */
typename PointTraits<POINT>::coordinate findCoordinateOf(const typename PointTraits<POINT>::index pointIndex,
const std::vector<IndexAndCoordinate<POINT> >& groupOfCandidates) const
{
const auto indexEntry = std::lower_bound(std::begin(groupOfCandidates),
std::end(groupOfCandidates),
pointIndex,
CompareEntryWithIndex);
return indexEntry->geometricValue;
}
};
}
#endif
| 46.768559 | 132 | 0.597479 | stefanos-86 |
054b8ff3f294f45f74688bdadd81c04fc2cbde9d | 2,162 | cpp | C++ | 2D Graphics/Histograms/Sapostavyashta Vertikalna Histograma/main.cpp | BorisLechev/-University | c6a29bc7438733adb9f5818a9674f546187db555 | [
"MIT"
] | null | null | null | 2D Graphics/Histograms/Sapostavyashta Vertikalna Histograma/main.cpp | BorisLechev/-University | c6a29bc7438733adb9f5818a9674f546187db555 | [
"MIT"
] | 1 | 2022-03-02T09:56:43.000Z | 2022-03-02T09:56:43.000Z | 2D Graphics/Histograms/Sapostavyashta Vertikalna Histograma/main.cpp | BorisLechev/University | c6a29bc7438733adb9f5818a9674f546187db555 | [
"MIT"
] | null | null | null | #include <iostream>
#include <graphics.h>
using namespace std;
int main()
{
initwindow(800, 800);
double startPointX = 100;
double startPointY = 600;
double windowSizeX = 600;
double windowSizeY = 500;
double columnWidth = 70;
double distanceBetweenColumns = 70;
double D = 60;
double bi[] = {5, 26};
double ai[] = {15, 20};
double mi[] = {10, 12};
double amin = ai[0];
double amax = ai[0];
double bmin = bi[0];
double bmax = bi[0];
double sum[4];
double maxSum;
for(int i = 0; i < 2; i++)
{
sum[i] = ai[i] + bi[i] + mi[i];
}
maxSum = sum[0];
for(int i = 1; i < 3; i++)
{
if (sum[i] > maxSum)
{
maxSum = sum[i];
}
}
float scaleFactor = maxSum / windowSizeY;
// koordinatna sistema
line(startPointX, startPointY, startPointX + windowSizeX, startPointY);
line(startPointX, startPointY, startPointX, startPointY - windowSizeY);
// chertite na deleniyata
// double value;
//
// for(p = 1; p < windowSizeY / D; p++)
// {
// line(startPointX, startPointY - p * D, startPointX - 3, startPointY - p * D);
// value = p * D * scaleFactor;
// cout << value << endl;
// }
for(int i = 1; i <= 2; i++)
{
bar(startPointX + i * (columnWidth + distanceBetweenColumns) - columnWidth,
startPointY - ai[i - 1] / scaleFactor,
startPointX + i * (columnWidth + distanceBetweenColumns),
startPointY);
setfillstyle(i, i);
bar(startPointX + i * (columnWidth + distanceBetweenColumns) - columnWidth,
startPointY - (ai[i - 1] + bi[i - 1]) / scaleFactor,
startPointX + i * (columnWidth + distanceBetweenColumns),
startPointY - ai[i - 1] / scaleFactor);
setfillstyle(i + 1, i + 1);
bar(startPointX + i * (columnWidth + distanceBetweenColumns) - columnWidth,
startPointY - (ai[i - 1] + bi[i - 1] + mi[i - 1]) / scaleFactor,
startPointX + i * (columnWidth + distanceBetweenColumns),
startPointY - (ai[i - 1] + bi[i - 1]) / scaleFactor);
setfillstyle(i + 2, i + 2);
}
getch();
return 0;
}
| 24.850575 | 81 | 0.567068 | BorisLechev |
054c821ee05d62550d458af50a06efa16b64be7e | 977 | cpp | C++ | Software/GUI.cpp | seanziegler/TennisBallTracker | b4ad4c2f4a0394dc2e111769f58b8e8f9d77a853 | [
"MIT"
] | 1 | 2020-10-29T08:44:54.000Z | 2020-10-29T08:44:54.000Z | Software/GUI.cpp | seanziegler/TennisBallTracker | b4ad4c2f4a0394dc2e111769f58b8e8f9d77a853 | [
"MIT"
] | 2 | 2019-07-25T15:23:54.000Z | 2019-07-25T15:25:19.000Z | Software/GUI.cpp | seanziegler/TennisBallTracker | b4ad4c2f4a0394dc2e111769f58b8e8f9d77a853 | [
"MIT"
] | null | null | null | #include "openCV.h"
using namespace cv;
class GUI {
int lowH, lowS, lowV = 90;
int highH = 180;
int highS = 255, highV = 255;
void lowHChange(int pos, void*) {
int lowH = pos;
}
void lowSChange(int pos, void*) {
int lowS = pos;
}
void lowVChange(int pos, void*) {
int lowV = pos;
}
void highHChange(int pos, void*) {
int highH = pos;
}
void highSChange(int pos, void*) {
int highS = pos;
}
void highVChange(int pos, void*) {
int highV = pos;
}
/*cv::namedWindow("HSV Value Selection");
const String HSVwindowName = "HSV Value Selection";
createTrackbar("Low H", HSVwindowName, 0, 180, lowHChange);
createTrackbar("Low S", HSVwindowName, 0, 255, lowSChange);
createTrackbar("Low V", HSVwindowName, 0, 255, lowVChange);
createTrackbar("High H", HSVwindowName, &highH, 180, highHChange);
createTrackbar("High S", HSVwindowName, &highS, 255, highSChange);
createTrackbar("High V", HSVwindowName, &highV, 255, highVChange);
*/
}; | 19.54 | 67 | 0.669396 | seanziegler |
054d0de95f0452e026174ae515310216e4164f53 | 7,808 | hpp | C++ | src/ParallelAlgorithms/LinearSolver/Gmres/Gmres.hpp | fmahebert/spectre | 936e2dff0434f169b9f5b03679cd27794003700a | [
"MIT"
] | 117 | 2017-04-08T22:52:48.000Z | 2022-03-25T07:23:36.000Z | src/ParallelAlgorithms/LinearSolver/Gmres/Gmres.hpp | GitHimanshuc/spectre | 4de4033ba36547113293fe4dbdd77591485a4aee | [
"MIT"
] | 3,177 | 2017-04-07T21:10:18.000Z | 2022-03-31T23:55:59.000Z | src/ParallelAlgorithms/LinearSolver/Gmres/Gmres.hpp | geoffrey4444/spectre | 9350d61830b360e2d5b273fdd176dcc841dbefb0 | [
"MIT"
] | 85 | 2017-04-07T19:36:13.000Z | 2022-03-01T10:21:00.000Z | // Distributed under the MIT License.
// See LICENSE.txt for details.
#pragma once
#include "DataStructures/DataBox/PrefixHelpers.hpp"
#include "DataStructures/DataBox/Prefixes.hpp"
#include "IO/Observer/Helpers.hpp"
#include "ParallelAlgorithms/LinearSolver/Gmres/ElementActions.hpp"
#include "ParallelAlgorithms/LinearSolver/Gmres/InitializeElement.hpp"
#include "ParallelAlgorithms/LinearSolver/Gmres/ResidualMonitor.hpp"
#include "ParallelAlgorithms/LinearSolver/Observe.hpp"
#include "ParallelAlgorithms/LinearSolver/Tags.hpp"
#include "Utilities/TMPL.hpp"
/// Items related to the GMRES linear solver
///
/// \see `LinearSolver::gmres::Gmres`
namespace LinearSolver::gmres {
/*!
* \ingroup LinearSolverGroup
* \brief A GMRES solver for nonsymmetric linear systems of equations
* \f$Ax=b\f$.
*
* \details The only operation we need to supply to the algorithm is the
* result of the operation \f$A(p)\f$ (see \ref LinearSolverGroup). Each step of
* the algorithm expects that \f$A(q)\f$ is computed and stored in the DataBox
* as `db::add_tag_prefix<LinearSolver::Tags::OperatorAppliedTo, operand_tag>`.
* To perform a solve, add the `solve` action list to an array parallel
* component. Pass the actions that compute \f$A(q)\f$, as well as any further
* actions you wish to run in each step of the algorithm, as the first template
* parameter to `solve`. If you add the `solve` action list multiple times, use
* the second template parameter to label each solve with a different type.
*
* This linear solver supports preconditioning. Enable preconditioning by
* setting the `Preconditioned` template parameter to `true`. If you do, run a
* preconditioner (e.g. another parallel linear solver) in each step. The
* preconditioner should approximately solve the linear problem \f$A(q)=b\f$
* where \f$q\f$ is the `operand_tag` and \f$b\f$ is the
* `preconditioner_source_tag`. Make sure the tag
* `db::add_tag_prefix<LinearSolver::Tags::OperatorAppliedTo, operand_tag>`
* is updated with the preconditioned result in each step of the algorithm, i.e.
* that it is \f$A(q)\f$ where \f$q\f$ is the preconditioner's approximate
* solution to \f$A(q)=b\f$. The preconditioner always begins at an initial
* guess of zero. It does not need to compute the operator applied to the
* initial guess, since it's zero as well due to the linearity of the operator.
*
* Note that the operand \f$q\f$ for which \f$A(q)\f$ needs to be computed is
* not the field \f$x\f$ we are solving for but
* `db::add_tag_prefix<LinearSolver::Tags::Operand, FieldsTag>`. This field is
* initially set to the residual \f$q_0 = b - A(x_0)\f$ where \f$x_0\f$ is the
* initial value of the `FieldsTag`.
*
* When the algorithm step is performed after the operator action \f$A(q)\f$ has
* been computed and stored in the DataBox, the GMRES algorithm implemented here
* will converge the field \f$x\f$ towards the solution and update the operand
* \f$q\f$ in the process. This requires reductions over all elements that are
* received by a `ResidualMonitor` singleton parallel component, processed, and
* then broadcast back to all elements. Since the reductions are performed to
* find a vector that is orthogonal to those used in previous steps, the number
* of reductions increases linearly with iterations. No restarting mechanism is
* currently implemented. The actions are implemented in the `gmres::detail`
* namespace and constitute the full algorithm in the following order:
* 1. `PerformStep` (on elements): Start an Arnoldi orthogonalization by
* computing the inner product between \f$A(q)\f$ and the first of the
* previously determined set of orthogonal vectors.
* 2. `StoreOrthogonalization` (on `ResidualMonitor`): Keep track of the
* computed inner product in a Hessenberg matrix, then broadcast.
* 3. `OrthogonalizeOperand` (on elements): Proceed with the Arnoldi
* orthogonalization by computing inner products and reducing to
* `StoreOrthogonalization` on the `ResidualMonitor` until the new orthogonal
* vector is constructed. Then compute its magnitude and reduce.
* 4. `StoreOrthogonalization` (on `ResidualMonitor`): Perform a QR
* decomposition of the Hessenberg matrix to produce a residual vector.
* Broadcast to `NormalizeOperandAndUpdateField` along with a termination
* flag if the `Convergence::Tags::Criteria` are met.
* 5. `NormalizeOperandAndUpdateField` (on elements): Set the operand \f$q\f$ as
* the new orthogonal vector and normalize. Use the residual vector and the set
* of orthogonal vectors to determine the solution \f$x\f$.
*
* \par Array sections
* This linear solver supports running over a subset of the elements in the
* array parallel component (see `Parallel::Section`). Set the
* `ArraySectionIdTag` template parameter to restrict the solver to elements in
* that section. Only a single section must be associated with the
* `ArraySectionIdTag`. The default is `void`, which means running over all
* elements in the array. Note that the actions in the `ApplyOperatorActions`
* list passed to `solve` will _not_ be restricted to run only on section
* elements, so all elements in the array may participate in preconditioning
* (see LinearSolver::multigrid::Multigrid).
*
* \see ConjugateGradient for a linear solver that is more efficient when the
* linear operator \f$A\f$ is symmetric.
*/
template <typename Metavariables, typename FieldsTag, typename OptionsGroup,
bool Preconditioned,
typename SourceTag =
db::add_tag_prefix<::Tags::FixedSource, FieldsTag>,
typename ArraySectionIdTag = void>
struct Gmres {
using fields_tag = FieldsTag;
using options_group = OptionsGroup;
using source_tag = SourceTag;
static constexpr bool preconditioned = Preconditioned;
/// Apply the linear operator to this tag in each iteration
using operand_tag = std::conditional_t<
Preconditioned,
db::add_tag_prefix<
LinearSolver::Tags::Preconditioned,
db::add_tag_prefix<LinearSolver::Tags::Operand, fields_tag>>,
db::add_tag_prefix<LinearSolver::Tags::Operand, fields_tag>>;
/// Invoke a linear solver on the `operand_tag` sourced by the
/// `preconditioner_source_tag` before applying the operator in each step
using preconditioner_source_tag =
db::add_tag_prefix<LinearSolver::Tags::Operand, fields_tag>;
/*!
* \brief The parallel components used by the GMRES linear solver
*/
using component_list = tmpl::list<
detail::ResidualMonitor<Metavariables, FieldsTag, OptionsGroup>>;
using initialize_element =
detail::InitializeElement<FieldsTag, OptionsGroup, Preconditioned>;
using register_element = tmpl::list<>;
using observed_reduction_data_tags = observers::make_reduction_data_tags<
tmpl::list<observe_detail::reduction_data>>;
template <typename ApplyOperatorActions, typename Label = OptionsGroup>
using solve = tmpl::list<
detail::PrepareSolve<FieldsTag, OptionsGroup, Preconditioned, Label,
SourceTag, ArraySectionIdTag>,
detail::NormalizeInitialOperand<FieldsTag, OptionsGroup, Preconditioned,
Label, ArraySectionIdTag>,
detail::PrepareStep<FieldsTag, OptionsGroup, Preconditioned, Label,
ArraySectionIdTag>,
ApplyOperatorActions,
detail::PerformStep<FieldsTag, OptionsGroup, Preconditioned, Label,
ArraySectionIdTag>,
detail::OrthogonalizeOperand<FieldsTag, OptionsGroup, Preconditioned,
Label, ArraySectionIdTag>,
detail::NormalizeOperandAndUpdateField<
FieldsTag, OptionsGroup, Preconditioned, Label, ArraySectionIdTag>>;
};
} // namespace LinearSolver::gmres
| 51.368421 | 80 | 0.740779 | fmahebert |