hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
12d15cfaf11addc2eca4e603e824295ac81cdd74 | 2,144 | hpp | C++ | include/util/GridMosaic.hpp | pjcuadra/feature_tracking | e3082a420fd97df29951d304936734916f0fce33 | [
"MIT"
] | null | null | null | include/util/GridMosaic.hpp | pjcuadra/feature_tracking | e3082a420fd97df29951d304936734916f0fce33 | [
"MIT"
] | null | null | null | include/util/GridMosaic.hpp | pjcuadra/feature_tracking | e3082a420fd97df29951d304936734916f0fce33 | [
"MIT"
] | null | null | null | /*
* MIT License
*
* Copyright (c) 2017 Pedro Cuadra
*
* 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.
*
*/
#ifndef GRIDMOSAIC_H
#define GRIDMOSAIC_H
#include <opencv2/core/core.hpp>
#include <opencv2/core/utility.hpp>
#include <chrono>
#include <iostream>
#include <util/Debug.hpp>
using namespace std;
using namespace cv;
class GridMosaic {
public:
/**
* Constructor
* @param rows number of rows
* @param cols number of columns
*/
GridMosaic(int rows, int cols, string name = "Grid Mosaic");
/**
* Set an image in the corresponing row and column
* @param row row of the image
* @param col column of the image
* @param image image
*/
void setImage(int rows, int cols, Mat image);
/**
* Create the mosaic image
* @return Mosaic image
*/
Mat create();
/**
* Display the window
*/
void show();
protected:
/* Images storage */
vector<vector<Mat>> images;
/* Window name */
string name;
void checkRowCol(int row, int col);
private:
/* Number of Rows */
int rows;
/* Number of columns */
int cols;
};
#endif /* GRIDMOSAIC_H */
| 25.831325 | 80 | 0.703825 | [
"vector"
] |
12e02effdd940128ea9596e74561bba828ace21b | 763 | hpp | C++ | vcl/src/project/fish.hpp | UnrealLink/Projet-INF443 | a80e698d35d2b5057137a11d5a50418c9efcfcbd | [
"MIT"
] | null | null | null | vcl/src/project/fish.hpp | UnrealLink/Projet-INF443 | a80e698d35d2b5057137a11d5a50418c9efcfcbd | [
"MIT"
] | null | null | null | vcl/src/project/fish.hpp | UnrealLink/Projet-INF443 | a80e698d35d2b5057137a11d5a50418c9efcfcbd | [
"MIT"
] | null | null | null | #ifndef FISH_HPP
#define FISH_HPP
#include "../vcl/core/drawable/mesh_drawable/mesh_drawable.hpp"
#include "vcl/external_lib/headers/glad.hpp"
#define ONDULANTLEN 50
#define STEPPRE 0.001f
struct fish : public vcl::mesh_drawable
{
float mu;
vcl::vec3 embossMinMap, embossMaxMap;
fish();
fish(const vcl::mesh& data);
/** Display the mesh with and send the uniform parameters */
void draw(GLuint shader, const vcl::camera_scene& camera);
/** gizes the position of the point 0,0,t */
virtual vcl::vec3 func(float z) = 0;
protected:
float mesh_length;
};
struct fishexp : public fish
{
fishexp();
fishexp(const vcl::mesh& data);
virtual vcl::vec3 func(float z);
float ampl, start;
};
#endif // FISH_HPP
| 19.075 | 64 | 0.68152 | [
"mesh"
] |
12e69ade3860bd59f9c5ea38bc61fc76c9785f62 | 17,787 | cpp | C++ | widget.cpp | HeyCat-svg/my-soft-raster | f721871b8d8c7a90a7f422e6d1da937a0710a9c6 | [
"MIT"
] | null | null | null | widget.cpp | HeyCat-svg/my-soft-raster | f721871b8d8c7a90a7f422e6d1da937a0710a9c6 | [
"MIT"
] | null | null | null | widget.cpp | HeyCat-svg/my-soft-raster | f721871b8d8c7a90a7f422e6d1da937a0710a9c6 | [
"MIT"
] | null | null | null | #include "widget.h"
#include "skybox.h"
// #define CLEAR_RT
// #define SOFT_RASTER
// #define RAY_TRACER
// #define PATH_TRACER
// "./obj/diablo3_pose/diablo3_pose.obj"
// "./obj/cornell_box/cornell_box.obj"
Model africanHeadModel("./obj/cornell_box/cornell_box.obj");
std::vector<Model*> worldMesh; // 全局model数组
std::vector<Accel*> worldAccel; // 与每一个model对应的加速结构
std::vector<BRDFMaterial*> worldMaterial; // 全局material数组
World world; // 全局世界
SoftRaster::SoftRaster(QWidget *parent) : QWidget(parent) {
this->setParent(parent);
this->setWindowTitle(QString("Soft Raster"));
this->resize(m_WindowWidth, m_WindowHeight);
m_AnotherMonitor = new Monitor();
m_AnotherMonitor->show();
// init pixel buffer
m_PixelBuffer = new QRgb[m_WindowWidth * m_WindowHeight];
// init zbuffer
m_Zbuffer = new float[m_WindowWidth * m_WindowHeight];
m_Zbuffer1 = new float[m_WindowWidth * m_WindowHeight];
// init shadow map
m_ShadowMap = new QRgb[m_WindowWidth * m_WindowHeight];
// init AO map
m_AOMap = new QRgb[m_WindowWidth * m_WindowHeight];
// set shader env
// 设置模型TRS
vec3 translate(0, 0, 0);
vec3 rotation(0, 0, 0);
vec3 scale(1.2, 1.2, 1.2);
mat4x4 model = TRS(translate, rotation, scale);
SetModelMatrix(model);
// 设置相机参数
vec3 worldUp(0, 1, 0);
vec3 cameraPos(0.f, 0.f, 2.5f); // 0.5 0.5 2.5 -0.5 0.5 2.0
vec3 lookDir = vec3(0, 0, 0) - cameraPos;
m_Camera = new Camera(cameraPos, lookDir, PI / 3.f, 1.f, 0.3f, 10.f);
// 设置光源
vec3 lightColor(1, 1, 1);
vec3 lightPos(1, 1, 1);
vec3 lightDir = vec3(0, 0, 0) - lightPos;
m_PointLight = new Light(lightColor, lightPos, lightDir, ProjectionType::PERSP);
SetCameraAndLight(cameraPos, embed<4>(lightPos));
SetViewMatrix(m_PointLight->GetViewMatrix()); // 利用set函数 将raw view和proj矩阵转变成最后使用的VP_MATRIX
SetProjectionMatrix(m_PointLight->GetProjectionMatrix());
m_PointLight->SetWorld2Light(VP_MATRIX);
// 设置光源数组
ShaderLight lights[2];
lights[0] = {{-0.5f, 0.5f, 0.5f, 1.f}, {0.8, 1, 1}, 0.7f};
lights[1] = {{0.5f, 0.5f, 0.5f, 1.f}, {1, 0.8, 1}, 0.7f};
SetLightArray(lights, 2);
// 设置render target分辨率
SetRenderTargetResolution(m_WindowWidth, m_WindowHeight);
// 初始化模型加速结构
m_ModelAccel = new Accel(&africanHeadModel);
m_ModelAccel->Build();
qDebug() << "face number: " << africanHeadModel.nfaces();
// 加载model数组 初始化obj和world
worldMaterial.push_back(new OpaqueBRDF(vec3(0.4f, 0.5f, 0.6f), 0.8f, 0.0f));
worldMaterial.push_back(new OpaqueBRDF(vec3(1.f, 0.f, 0.f), 0.0f, 0.0f));
worldMaterial.push_back(new OpaqueBRDF(vec3(0.f, 1.f, 0.f), 0.0f, 0.0f));
worldMaterial.push_back(new PointLightBRDF(vec3(1.f, 1.f, 1.f), 15.f));
worldMaterial.push_back(new OpaqueBRDF(vec3(0.7f, 0.7f, 0.7f), 0.0f, 0.0f));
worldMesh = Model::ModelReader("./obj/cornell_box/cornell_box.obj");
int size = worldMesh.size();
for (int i = 0; i < size; ++i) {
Accel* accel = new Accel(worldMesh[i]);
accel->Build();
worldAccel.push_back(accel);
// 使用mesh生成obj
if (worldMesh[i]->GetName().find("block") != std::string::npos) {
Object obj(worldMesh[i], accel, worldMaterial[0], vec3(0, 0, 0), vec3(0, 0, 0), vec3(1.f, 1.f, 1.f));
world.AddObjects(obj);
}
else if (worldMesh[i]->GetName().find("light") != std::string::npos) {
Object obj(worldMesh[i], accel, worldMaterial[3], vec3(0, 0, 0), vec3(0, 0, 0), vec3(1.f, 1.f, 1.f));
world.AddObjects(obj);
}
else if (worldMesh[i]->GetName().find("green_wall") != std::string::npos) {
Object obj(worldMesh[i], accel, worldMaterial[2], vec3(0, 0, 0), vec3(0, 0, 0), vec3(1.f, 1.f, 1.f));
world.AddObjects(obj);
}
else if (worldMesh[i]->GetName().find("red_wall") != std::string::npos) {
Object obj(worldMesh[i], accel, worldMaterial[1], vec3(0, 0, 0), vec3(0, 0, 0), vec3(1.f, 1.f, 1.f));
world.AddObjects(obj);
}
else {
Object obj(worldMesh[i], accel, worldMaterial[4], vec3(0, 0, 0), vec3(0, 0, 0), vec3(1.f, 1.f, 1.f));
world.AddObjects(obj);
}
}
world.Build();
// 加载资源与生成shader
TGAImage* diffuseImg = new TGAImage();
diffuseImg->read_tga_file("./obj/diablo3_pose/diablo3_pose_diffuse.tga");
diffuseImg->flip_vertically(); // 垂直反转让uv取到正确的值
TGAImage* normalImg = new TGAImage();
normalImg->read_tga_file("./obj/diablo3_pose/diablo3_pose_nm_tangent.tga");
normalImg->flip_vertically();
TGAImage* specImg = new TGAImage();
specImg->read_tga_file("./obj/diablo3_pose/diablo3_pose_spec.tga");
specImg->flip_vertically();
Skybox* skybox = new Skybox("./resources/skybox/skybox");
m_Shader = new GeneralShader(
&africanHeadModel, diffuseImg, normalImg, specImg,
new QImage((uchar*)m_ShadowMap, m_WindowWidth, m_WindowHeight, QImage::Format_ARGB32),
m_PointLight->GetWorld2Light(),
new QImage((uchar*)m_AOMap, m_WindowWidth, m_WindowHeight, QImage::Format_ARGB32)
);
m_ShadowMapShader = new ShadowMapShader(&africanHeadModel);
m_HBAOShader = new HBAOShader(&africanHeadModel, m_Zbuffer1, m_WindowWidth, m_WindowHeight);
m_ZWriteShader = new ZWriteShader(&africanHeadModel);
m_RayTracerShader = new RayTracerShader(&africanHeadModel, m_ModelAccel, skybox);
m_PathTracerShader = new PathTracerShader(&world, skybox);
// start repaint timer
m_RepaintTimer = startTimer(m_RepaintInterval);
}
SoftRaster::~SoftRaster() {
killTimer(m_RepaintTimer);
delete m_AnotherMonitor;
delete[] m_PixelBuffer;
delete[] m_Zbuffer;
delete[] m_Zbuffer1;
delete[] m_ShadowMap;
delete[] m_AOMap;
delete m_Shader;
delete m_ShadowMapShader;
delete m_HBAOShader;
delete m_ZWriteShader;
delete m_RayTracerShader;
delete m_PathTracerShader;
delete m_ModelAccel;
delete m_PointLight;
delete m_Camera;
int size = worldMesh.size();
for (int i = 0; i < size; ++i) {
delete worldMesh[i];
delete worldAccel[i];
}
size = worldMaterial.size();
for (int i = 0; i < size; ++i) {
delete worldMaterial[i];
}
}
void SoftRaster::paintEvent(QPaintEvent*) {
QPainter painter(this);
QImage image((uchar*)m_PixelBuffer, m_WindowWidth, m_WindowHeight, QImage::Format_ARGB32);
// timer start
LARGE_INTEGER cpuFreq;
LARGE_INTEGER startTime;
LARGE_INTEGER endTime;
double runtime = 0.0;
QueryPerformanceFrequency(&cpuFreq);
QueryPerformanceCounter(&startTime);
#ifdef CLEAR_RT
// clear image with black and clear depth buffer
QRgb bgColor = 255 << 24;
#pragma omp parallel for
for (int i = 0; i < m_WindowHeight; ++i) {
for (int j = 0; j < m_WindowWidth; ++j) {
m_PixelBuffer[i * m_WindowWidth + j] = bgColor;
m_Zbuffer[i * m_WindowWidth + j] = Z_MIN;
m_Zbuffer1[i * m_WindowWidth + j] = Z_MIN;
m_ShadowMap[i * m_WindowWidth + j] = bgColor;
m_AOMap[i * m_WindowWidth + j] = bgColor;
}
}
#endif
///////////////////////////////////////// SOFT RASTER START ////////////////////////////
#ifdef SOFT_RASTER
/// HBAO rendering
// Pass 0: z write
{
SetViewMatrix(m_Camera->GetViewMatrix());
SetProjectionMatrix(m_Camera->GetProjectionMatrix());
int faceCount = africanHeadModel.nfaces();
for (int i = 0; i < faceCount; ++i) {
vec4 clipPts[3];
for (int j = 0; j < 3; ++j) {
clipPts[j] = m_ZWriteShader->Vertex(i, j);
}
// 将深度写入m_Zbuffer1
Triangle(clipPts, m_ZWriteShader, m_PixelBuffer, m_Zbuffer1);
}
}
// Pass 1: draw HBAO
{
int faceCount = africanHeadModel.nfaces();
for (int i = 0; i < faceCount; ++i) {
vec4 clipPts[3];
for (int j = 0; j < 3; ++j) {
clipPts[j] = m_HBAOShader->Vertex(i, j);
}
// 将深度写入m_Zbuffer1
Triangle(clipPts, m_HBAOShader, m_AOMap, m_Zbuffer);
}
}
/// shadow rendering
// Pass 2: draw shadow map
{
#pragma omp parallel for
for (int i = 0; i < m_WindowHeight; ++i) {
for (int j = 0; j < m_WindowWidth; ++j) {
m_Zbuffer[i * m_WindowWidth + j] = Z_MIN;
}
}
SetViewMatrix(m_PointLight->GetViewMatrix());
SetProjectionMatrix(m_PointLight->GetProjectionMatrix());
int faceCount = africanHeadModel.nfaces();
for (int i = 0; i < faceCount; ++i) {
vec4 clipPts[3];
for (int j = 0; j < 3; ++j) {
clipPts[j] = m_ShadowMapShader->Vertex(i, j);
}
Triangle(clipPts, m_ShadowMapShader, m_ShadowMap, m_Zbuffer);
}
}
/// blin phong rendering
// Pass 3: draw model
{
#pragma omp parallel for
for (int i = 0; i < m_WindowHeight; ++i) {
for (int j = 0; j < m_WindowWidth; ++j) {
m_Zbuffer[i * m_WindowWidth + j] = Z_MIN;
m_PixelBuffer[i * m_WindowWidth + j] = bgColor;
}
}
SetViewMatrix(m_Camera->GetViewMatrix());
SetProjectionMatrix(m_Camera->GetProjectionMatrix());
int faceCount = africanHeadModel.nfaces();
for (int i = 0; i < faceCount; ++i) {
vec4 clipPts[3];
for (int j = 0; j < 3; ++j) {
clipPts[j] = m_Shader->Vertex(i, j);
}
m_Shader->Geometry();
Triangle(clipPts, m_Shader, m_PixelBuffer, m_Zbuffer);
}
}
#endif
///////////////////////////////// SOFT RASTER END /////////////////////////////
///////////////////////////////// RAY TRACER START ////////////////////////////
#ifdef RAY_TRACER
SetViewMatrix(m_Camera->GetViewMatrix());
SetProjectionMatrix(m_Camera->GetProjectionMatrix());
// 光栅化的步骤是为了插值ray 实际只有两个三角面片构成的长方形mesh
for (int i = 0; i < 2; ++i) {
vec4 clipPts[3];
for (int j = 0; j < 3; ++j) {
clipPts[j] = m_RayTracerShader->Vertex(i, j);
}
Triangle(clipPts, m_RayTracerShader, m_PixelBuffer, m_Zbuffer);
}
#endif
///////////////////////////////// RAY TRACER END ////////////////////////////
///////////////////////////////// PATH TRACER START ////////////////////////////
#ifdef PATH_TRACER
SetViewMatrix(m_Camera->GetViewMatrix());
SetProjectionMatrix(m_Camera->GetProjectionMatrix());
SetRenderTargetResolution(m_WindowWidth, m_WindowHeight);
// 光栅化的步骤是为了插值ray 实际只有两个三角面片构成的长方形mesh
for (int i = 0; i < 2; ++i) {
vec4 clipPts[3];
for (int j = 0; j < 3; ++j) {
clipPts[j] = m_PathTracerShader->Vertex(i, j);
}
Triangle(clipPts, m_PathTracerShader, m_PixelBuffer, m_Zbuffer);
}
#endif
///////////////////////////////// PATH TRACER END ////////////////////////////
// timer end
QueryPerformanceCounter(&endTime);
runtime = (((endTime.QuadPart - startTime.QuadPart) * 1000.0f) / cpuFreq.QuadPart);
qDebug() << "runtime: " << runtime << "ms";
// draw image on window
painter.drawImage(0, 0, image);
// m_AnotherMonitor->Draw(m_ShadowMap, m_WindowWidth, m_WindowHeight);
}
void SoftRaster::timerEvent(QTimerEvent* event) {
int timerID = event->timerId();
// repaint event
if (timerID == m_RepaintTimer) {
update();
}
}
void SoftRaster::Line(int x1, int y1, int x2, int y2, QRgb color) {
bool steep = false; // k<1->false k>1->true
// 如果斜率绝对值>1 则交换xy 沿着y考虑x的增长
if (std::abs(y1 - y2) > std::abs(x1 - x2)) {
std::swap(x1, y1);
std::swap(x2, y2);
steep = true;
}
// 必须让x1 < x2
if (x1 > x2) {
std::swap(x1, x2);
std::swap(y1, y2);
}
int stepY = (y2 < y1) ? -1 : 1; // 确定y是向上还是向下长一个像素格
if (steep) {
int m = 2 * std::abs(y2 - y1);
int dx = x2 - x1;
int error = 0;
for (int x = x1, y = y1; x <= x2; ++x) {
m_PixelBuffer[y + x * m_WindowWidth] = color; // steep=true xy需要交换一下
error += m;
if (error > dx) {
y += stepY;
error -= 2 * dx;
}
}
}
else {
int m = 2 * std::abs(y2 - y1);
int dx = x2 - x1;
int error = 0;
for (int x = x1, y = y1; x <= x2; ++x) {
m_PixelBuffer[x + y * m_WindowWidth] = color;
error += m;
if (error > dx) {
y += stepY;
error -= 2 * dx;
}
}
}
}
void SoftRaster::Triangle(vec4 *clipPts, IShader* shader, QRgb* renderTarget, float* zbuffer) {
vec2 screenPts[3] = {
vec2((0.5f * (clipPts[0].x / clipPts[0].w) + 0.5f) * m_WindowWidth, (0.5f * (clipPts[0].y / clipPts[0].w) + 0.5f) * m_WindowHeight),
vec2((0.5f * (clipPts[1].x / clipPts[1].w) + 0.5f) * m_WindowWidth, (0.5f * (clipPts[1].y / clipPts[1].w) + 0.5f) * m_WindowHeight),
vec2((0.5f * (clipPts[2].x / clipPts[2].w) + 0.5f) * m_WindowWidth, (0.5f * (clipPts[2].y / clipPts[2].w) + 0.5f) * m_WindowHeight)
};
vec2 boundBoxMin = vec2(m_WindowWidth - 1, m_WindowHeight - 1);
vec2 boundBoxMax = vec2(0, 0);
for (int i = 0; i < 3; ++i) {
boundBoxMin.x = std::max(0.f, std::min(screenPts[i].x, boundBoxMin.x));
boundBoxMin.y = std::max(0.f, std::min(screenPts[i].y, boundBoxMin.y));
boundBoxMax.x = std::min(m_WindowWidth - 1.f, std::max(screenPts[i].x, boundBoxMax.x));
boundBoxMax.y = std::min(m_WindowHeight - 1.f, std::max(screenPts[i].y, boundBoxMax.y));
}
#pragma omp parallel for
for (int y = (int)boundBoxMin.y; y <= (int)boundBoxMax.y; ++y) {
for (int x = (int)boundBoxMin.x; x <= (int)boundBoxMax.x; ++x) {
vec3 screenBar = Barycentric(screenPts, vec2(x, y)); // 屏幕空间重心坐标
if (screenBar.x < 0.f || screenBar.y < 0.f || screenBar.z < 0.f) {
continue;
}
// 计算实际空间的重心坐标 透视矫正 1/zt = a*1/z1 + b*1/z2 + c*1/z3 It/zt = a*I1/z1 + b*I2/z2 + c*I3/z3 然后view->proj后w分量是z值
vec3 clipBar = vec3(screenBar.x / clipPts[0].w, screenBar.y / clipPts[1].w, screenBar.z / clipPts[2].w);
clipBar = clipBar / (clipBar.x + clipBar.y + clipBar.z);
float depth = (clipBar.x * clipPts[0].z + clipBar.y * clipPts[1].z + clipBar.z * clipPts[2].z) / (clipBar.x * clipPts[0].w + clipBar.y * clipPts[1].w + clipBar.z * clipPts[2].w);
// 深度测试 z从里到外增大 [far, near]->[0, 1]
if (depth < zbuffer[x + y * m_WindowWidth]) {
continue;
}
QRgb color;
bool discard = shader->Fragment(clipBar, color);
if (!discard) {
renderTarget[x + y * m_WindowWidth] = color;
zbuffer[x + y * m_WindowWidth] = depth;
}
}
}
}
// 解重心坐标 u*AB + v*AC + PA = 0
vec3 SoftRaster::Barycentric(vec2 *pts, vec2 p) {
vec3 ret = cross(
vec3(pts[1].x - pts[0].x, pts[2].x - pts[0].x, pts[0].x - p.x),
vec3(pts[1].y - pts[0].y, pts[2].y - pts[0].y, pts[0].y - p.y)
);
// 整数坐标输入 cross后应该也是整数 abs(ret.z)<1意味着ret[2]是0 即输入三角形退化成线段或点
if (std::abs(ret.z) < 1.f) {
return vec3(-1.f, 1.f, 1.f);
}
// (ret.x + ret.y) / ret.z 先+后x 增加精度 避免在BC边上像素漏画
return vec3(1.f - (ret.x + ret.y) / ret.z, ret.x / ret.z, ret.y / ret.z);
}
void SoftRaster::GenerateImage() {
QImage image((uchar*)m_PixelBuffer, m_WindowWidth, m_WindowHeight, QImage::Format_ARGB32);
// timer start
LARGE_INTEGER cpuFreq;
LARGE_INTEGER startTime;
LARGE_INTEGER endTime;
double runtime = 0.0;
QueryPerformanceFrequency(&cpuFreq);
QueryPerformanceCounter(&startTime);
// clear image with black and clear depth buffer
QRgb bgColor = 255 << 24;
#pragma omp parallel for
for (int i = 0; i < m_WindowHeight; ++i) {
for (int j = 0; j < m_WindowWidth; ++j) {
m_PixelBuffer[i * m_WindowWidth + j] = bgColor;
m_Zbuffer[i * m_WindowWidth + j] = Z_MIN;
m_Zbuffer1[i * m_WindowWidth + j] = Z_MIN;
m_ShadowMap[i * m_WindowWidth + j] = bgColor;
m_AOMap[i * m_WindowWidth + j] = bgColor;
}
}
SetViewMatrix(m_Camera->GetViewMatrix());
SetProjectionMatrix(m_Camera->GetProjectionMatrix());
SetRenderTargetResolution(m_WindowWidth, m_WindowHeight);
// 光栅化的步骤是为了插值ray 实际只有两个三角面片构成的长方形mesh
for (int i = 0; i < 2; ++i) {
vec4 clipPts[3];
for (int j = 0; j < 3; ++j) {
clipPts[j] = m_PathTracerShader->Vertex(i, j);
}
Triangle(clipPts, m_PathTracerShader, m_PixelBuffer, m_Zbuffer);
}
// timer end
QueryPerformanceCounter(&endTime);
runtime = (((endTime.QuadPart - startTime.QuadPart) * 1000.0f) / cpuFreq.QuadPart);
qDebug() << "runtime: " << runtime << "ms";
image.save("./img/ray_tracer/result.png");
}
| 37.211297 | 191 | 0.554562 | [
"geometry",
"object",
"vector",
"model"
] |
12e82e8194a063f7cbdd34f141c09b24a979691b | 550 | hpp | C++ | src/Material.hpp | kevxiao/Bouncer | c4166fcfbb4db09da13cdec00ec02a15e47602be | [
"MIT"
] | null | null | null | src/Material.hpp | kevxiao/Bouncer | c4166fcfbb4db09da13cdec00ec02a15e47602be | [
"MIT"
] | null | null | null | src/Material.hpp | kevxiao/Bouncer | c4166fcfbb4db09da13cdec00ec02a15e47602be | [
"MIT"
] | null | null | null | #pragma once
#include <glm/glm.hpp>
// Material surface properties to be used as input into a local illumination model
// (e.g. the Phong Reflection Model).
struct Material {
Material()
: kd(glm::vec3(0.0f)),
ks(glm::vec3(0.0f)),
shininess(0.0f) { }
// Diffuse reflection coefficient
glm::vec3 kd;
// Specular reflection coefficient
glm::vec3 ks;
// Material shininess constant. Larger positive values model surfaces that
// are smoother or mirror-like. Smaller positive values model rougher surfaces.
float shininess;
};
| 23.913043 | 82 | 0.710909 | [
"model"
] |
12ea406a26bce73b4eda21d74b64170e02d56633 | 1,989 | cc | C++ | tests/test_distances.cc | eudoxos/Aleph | 874882c33a0e8429c74e567eb01525613fee0616 | [
"MIT"
] | 56 | 2019-04-24T22:11:15.000Z | 2022-03-22T11:37:47.000Z | tests/test_distances.cc | eudoxos/Aleph | 874882c33a0e8429c74e567eb01525613fee0616 | [
"MIT"
] | 48 | 2016-11-30T09:37:13.000Z | 2019-01-30T21:43:39.000Z | tests/test_distances.cc | eudoxos/Aleph | 874882c33a0e8429c74e567eb01525613fee0616 | [
"MIT"
] | 11 | 2019-05-02T11:54:31.000Z | 2020-12-10T14:05:40.000Z | #include <tests/Base.hh>
#include <aleph/geometry/distances/Euclidean.hh>
#include <aleph/geometry/distances/Hamming.hh>
#include <aleph/geometry/distances/Manhattan.hh>
#include <vector>
using namespace aleph;
using namespace geometry;
using namespace distances;
template <class T> void testEuclideanDistance()
{
ALEPH_TEST_BEGIN( "Euclidean distance" );
std::vector<T> x = {1,2,3};
std::vector<T> y = {4,5,6};
auto functor = Euclidean<T>();
auto distance = functor( x.begin(), y.begin(), x.size() );
ALEPH_ASSERT_THROW( functor.name() == "Euclidean distance" );
ALEPH_ASSERT_THROW( distance > T(0) );
ALEPH_ASSERT_EQUAL( distance, T(27) );
ALEPH_ASSERT_EQUAL( distance, functor( y.begin(), x.begin(), y.size() ) );
ALEPH_TEST_END();
}
template <class T> void testHammingDistance()
{
ALEPH_TEST_BEGIN( "Hamming distance" );
std::vector<T> x = {1,2,3};
std::vector<T> y = {4,5,6};
auto functor = Hamming<T>();
auto distance = functor( x.begin(), y.begin(), x.size() );
ALEPH_ASSERT_THROW( functor.name() == "Hamming distance" );
ALEPH_ASSERT_THROW( distance > T(0) );
ALEPH_ASSERT_EQUAL( distance, T(3) );
ALEPH_ASSERT_EQUAL( distance, functor( y.begin(), x.begin(), y.size() ) );
ALEPH_TEST_END();
}
template <class T> void testManhattanDistance()
{
ALEPH_TEST_BEGIN( "Manhattan distance" );
std::vector<T> x = {1,2,3};
std::vector<T> y = {4,5,6};
auto functor = Manhattan<T>();
auto distance = functor( x.begin(), y.begin(), x.size() );
ALEPH_ASSERT_THROW( functor.name() == "Manhattan distance" );
ALEPH_ASSERT_THROW( distance > T(0) );
ALEPH_ASSERT_EQUAL( distance, T(9) );
ALEPH_ASSERT_EQUAL( distance, functor( y.begin(), x.begin(), y.size() ) );
ALEPH_TEST_END();
}
int main(int, char**)
{
testEuclideanDistance<float> ();
testEuclideanDistance<double>();
testHammingDistance<float> ();
testHammingDistance<double>();
testManhattanDistance<float> ();
testManhattanDistance<double>();
}
| 25.5 | 76 | 0.675716 | [
"geometry",
"vector"
] |
12f08c2387f37b6235f50ce647507e53901919b4 | 3,748 | hpp | C++ | include/seec/Util/Observer.hpp | seec-team/seec | 4b92456011e86b70f9d88833a95c1f655a21cf1a | [
"MIT"
] | 7 | 2018-06-25T12:06:13.000Z | 2022-01-18T09:20:13.000Z | include/seec/Util/Observer.hpp | seec-team/seec | 4b92456011e86b70f9d88833a95c1f655a21cf1a | [
"MIT"
] | 20 | 2016-12-01T23:46:12.000Z | 2019-08-11T02:41:04.000Z | include/seec/Util/Observer.hpp | seec-team/seec | 4b92456011e86b70f9d88833a95c1f655a21cf1a | [
"MIT"
] | 1 | 2020-10-19T03:20:05.000Z | 2020-10-19T03:20:05.000Z | //===- seec/Util/Observer.hpp --------------------------------------- C++ -===//
//
// SeeC
//
// This file is distributed under The MIT License (MIT). See LICENSE.TXT for
// details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
//===----------------------------------------------------------------------===//
#ifndef SEEC_UTIL_OBSERVER_HPP
#define SEEC_UTIL_OBSERVER_HPP
#include <algorithm>
#include <cassert>
#include <functional>
#include <memory>
#include <vector>
#include <utility>
namespace seec {
namespace observer {
using observer_id = unsigned;
/// \brief Shared base type for the deregistration proxy.
///
class deregistration_proxy {
public:
virtual void deregisterObserver(observer_id const ID) = 0;
};
/// \brief Holds a listener's registration to a subject.
/// The registration can be moved, but not copied. When the registration is
/// destroyed, the listener's function will be removed from the subject.
///
class registration {
std::weak_ptr<deregistration_proxy> m_Proxy;
observer_id m_ID;
void deregister()
{
if (auto Proxy = m_Proxy.lock()) {
Proxy->deregisterObserver(m_ID);
}
}
public:
registration()
: m_Proxy(),
m_ID(0)
{}
registration(std::weak_ptr<deregistration_proxy> Proxy,
observer_id const ID)
: m_Proxy(Proxy),
m_ID(ID)
{}
registration(registration &&Other)
: registration()
{
*this = std::move(Other);
}
registration &operator=(registration &&RHS)
{
deregister();
std::swap(m_Proxy, RHS.m_Proxy);
std::swap(m_ID, RHS.m_ID);
return *this;
}
~registration()
{
deregister();
}
registration(registration &) = delete;
registration(registration const &) = delete;
registration &operator=(registration &) = delete;
registration &operator=(registration const &) = delete;
};
/// \brief Something that can be observed.
///
template<typename... NotificationTs>
class subject {
/// \brief This specialization's implementation of the deregistration proxy.
class deregistration_proxy_impl : public deregistration_proxy {
subject &m_Subject;
public:
deregistration_proxy_impl(subject &Subject)
: m_Subject(Subject)
{}
virtual ~deregistration_proxy_impl() {}
virtual void deregisterObserver(observer_id const ID) override
{
m_Subject.deregisterObserver(ID);
}
};
using FnT = std::function<void (NotificationTs...)>;
std::shared_ptr<deregistration_proxy> m_Proxy;
observer_id m_NextID;
std::vector<std::pair<observer_id, FnT>> m_Observers;
void deregisterObserver(observer_id const ID)
{
auto const It = std::find_if(m_Observers.begin(), m_Observers.end(),
[=] (std::pair<observer_id, FnT> const &Entry) {
return Entry.first == ID;
});
if (It != m_Observers.end()) {
m_Observers.erase(It);
}
}
public:
subject()
: m_Proxy(std::make_shared<deregistration_proxy_impl>(*this)),
m_NextID(0),
m_Observers()
{}
~subject()
{
// Destroy the proxy object so that registration objects will not attempt
// to deregister with this subject hereafter.
assert(m_Proxy && m_Proxy.use_count() == 1);
m_Proxy.reset();
}
registration registerObserver(FnT F)
{
auto const ID = m_NextID++;
m_Observers.emplace_back(ID, std::move(F));
return registration(m_Proxy, ID);
}
void notifyObservers(NotificationTs const & ...Args) const
{
for (auto &P : m_Observers) {
if (P.second) {
P.second(Args...);
}
}
}
};
} // namespace observer
} // namespace seec
#endif // define SEEC_UTIL_OBSERVER_HPP
| 22.309524 | 80 | 0.619797 | [
"object",
"vector"
] |
12f102db685d141446cefbd630627e253c7c518e | 5,943 | cpp | C++ | src/tabu_search.cpp | vss2sn/cvrp | 685cea9017f4cce44c9d089d86271657082ac978 | [
"BSD-3-Clause"
] | 12 | 2019-10-26T19:26:49.000Z | 2022-01-26T04:53:00.000Z | src/tabu_search.cpp | NeiH4207/cvrp | 685cea9017f4cce44c9d089d86271657082ac978 | [
"BSD-3-Clause"
] | 1 | 2019-12-27T12:16:45.000Z | 2020-01-01T19:11:30.000Z | src/tabu_search.cpp | NeiH4207/cvrp | 685cea9017f4cce44c9d089d86271657082ac978 | [
"BSD-3-Clause"
] | 13 | 2019-10-14T16:09:41.000Z | 2022-02-16T07:06:46.000Z | /**
* @file tabu_search.cpp
* @author vss2sn
* @brief Contains the TabuSearchSolution class
*/
#include "cvrp/tabu_search.hpp"
#include <iostream>
#include <numeric>
TabuSearchSolution::TabuSearchSolution(
const std::vector<Node> &nodes, const std::vector<Vehicle> &vehicles,
const std::vector<std::vector<double>> &distanceMatrix, const int n_tabu,
const int max_it)
: Solution(nodes, vehicles, distanceMatrix),
n_tabu_(n_tabu),
max_it_(max_it) {
CreateInitialSolution();
}
TabuSearchSolution::TabuSearchSolution(const Problem &p, const int n_tabu,
const int max_it)
: Solution(p.nodes_, p.vehicles_, p.distanceMatrix_),
n_tabu_(n_tabu),
max_it_(max_it) {
CreateInitialSolution();
}
TabuSearchSolution::TabuSearchSolution(const Solution &s, const int n_tabu,
const int max_it)
: Solution(s), n_tabu_(n_tabu), max_it_(max_it) {
if (!s.CheckSolutionValid()) {
std::cout << "The input solution is invalid. Exiting." << '\n';
exit(0);
}
}
inline bool TabuSearchSolution::IsTabu(const std::pair<int, int> &p) const {
return tabu_list_set_.find(p) != std::end(tabu_list_set_);
}
inline bool TabuSearchSolution::Aspiration(const double cost_increase,
const double cost_reduction) const {
return new_cost_ + cost_increase + cost_reduction < best_cost_;
}
void TabuSearchSolution::Solve() {
double cost = std::accumulate(
std::begin(vehicles_), std::end(vehicles_), 0.0,
[](const double sum, const Vehicle &v) { return sum + v.cost_; });
tabu_list_set_.clear();
for (int i = 0; i < n_tabu_; i++) {
tabu_list_queue_.emplace();
}
auto best_vehicles = vehicles_;
best_cost_ = cost;
new_cost_ = cost;
Vehicle *v_temp = nullptr;
Vehicle *v_temp_2 = nullptr;
for (int c_it = 0; c_it < max_it_; c_it++) {
int best_c = -1;
int best_r = -1;
double delta = std::numeric_limits<double>::max();
for (auto &v : vehicles_) {
for (size_t cur = 1; cur < v.nodes_.size() - 1; cur++) {
const int v_cur = v.nodes_[cur];
const int v_prev = v.nodes_[cur - 1];
const int v_next_c = v.nodes_[cur + 1];
const double cost_reduction = distanceMatrix_[v_prev][v_next_c] -
distanceMatrix_[v_prev][v_cur] -
distanceMatrix_[v_cur][v_next_c];
const bool is_tabu_1 =
IsTabu({v_prev, v_cur}) || IsTabu({v_cur, v_prev}) ||
IsTabu({v_cur, v_next_c}) || IsTabu({v_next_c, v_cur});
for (auto &v2 : vehicles_) {
for (size_t rep = 0; rep < v2.nodes_.size() - 1; rep++) {
const int v_rep = v2.nodes_[rep];
const int v_next_r = v2.nodes_[rep + 1];
if (v_rep != v_cur && (v.id_ != v2.id_ || v_rep != v_prev)) {
const bool is_tabu_2 =
IsTabu({v_rep, v_cur}) || IsTabu({v_cur, v_next_r});
const double cost_increase = distanceMatrix_[v_rep][v_cur] +
distanceMatrix_[v_cur][v_next_r] -
distanceMatrix_[v_rep][v_next_r];
if ((cost_increase + cost_reduction < delta) &&
(v2.load_ - nodes_[v_cur].demand_ >= 0 || v.id_ == v2.id_) &&
(!(is_tabu_1 || is_tabu_2) ||
Aspiration(cost_increase, cost_reduction))) {
delta = cost_increase + cost_reduction;
best_c = cur;
best_r = rep;
v_temp_2 = &v2;
v_temp = &v;
}
}
}
}
}
}
if (delta == std::numeric_limits<double>::max() || v_temp == nullptr ||
v_temp_2 == nullptr) {
std::cout << "On iteration " << c_it
<< "No possible moves. Consider adjusting tabu list size.\n";
break;
}
const int val_best_c = *std::next(v_temp->nodes_.begin(), best_c);
v_temp->nodes_.erase(std::next(v_temp->nodes_.begin(), best_c));
v_temp->CalculateCost(distanceMatrix_);
if (v_temp->id_ == v_temp_2->id_ && best_c < best_r) {
v_temp_2->nodes_.insert(std::next(v_temp_2->nodes_.begin(), best_r),
val_best_c);
tabu_list_set_.insert({v_temp_2->nodes_[best_r - 1], val_best_c});
tabu_list_queue_.push({v_temp_2->nodes_[best_r - 1], val_best_c});
} else {
v_temp_2->nodes_.insert(std::next(v_temp_2->nodes_.begin(), best_r + 1),
val_best_c);
tabu_list_set_.insert({v_temp_2->nodes_[best_r], val_best_c});
tabu_list_queue_.push({v_temp_2->nodes_[best_r], val_best_c});
}
tabu_list_set_.insert({v_temp->nodes_[best_c - 1], val_best_c});
tabu_list_queue_.push({v_temp->nodes_[best_c - 1], val_best_c});
v_temp_2->CalculateCost(distanceMatrix_);
v_temp->load_ += nodes_[val_best_c].demand_;
v_temp_2->load_ -= nodes_[val_best_c].demand_;
new_cost_ = std::accumulate(
std::begin(vehicles_), std::end(vehicles_), 0.0,
[](const double sum, const Vehicle &v) { return sum + v.cost_; });
if (new_cost_ < best_cost_) {
best_vehicles = vehicles_;
best_cost_ = new_cost_;
}
tabu_list_set_.erase(tabu_list_queue_.front());
tabu_list_queue_.pop();
tabu_list_set_.erase(tabu_list_queue_.front());
tabu_list_queue_.pop();
}
vehicles_ = best_vehicles;
cost = std::accumulate(
std::begin(vehicles_), std::end(vehicles_), 0.0,
[](const double sum, const Vehicle &v) { return sum + v.cost_; });
std::cout << "Cost: " << cost << '\n';
for (const auto &i : nodes_) {
if (!i.is_routed_) {
std::cout << "Unreached node: " << '\n';
std::cout << i << '\n';
}
}
std::cout << "Solution valid: " << CheckSolutionValid() << '\n';
}
| 37.853503 | 79 | 0.582702 | [
"vector"
] |
12f7a536827cdb950988777470e329b7619a957d | 1,900 | hpp | C++ | include/naoqi_driver/ros_helpers.hpp | simwijs/naoqi_driver | 89b00459dc517f8564b1d7092eb36a3fc68a7096 | [
"Apache-2.0"
] | null | null | null | include/naoqi_driver/ros_helpers.hpp | simwijs/naoqi_driver | 89b00459dc517f8564b1d7092eb36a3fc68a7096 | [
"Apache-2.0"
] | null | null | null | include/naoqi_driver/ros_helpers.hpp | simwijs/naoqi_driver | 89b00459dc517f8564b1d7092eb36a3fc68a7096 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2015 Aldebaran
*
* 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 HELPERS_HPP
#define HELPERS_HPP
#include <rclcpp/rclcpp.hpp>
#include <boost/shared_ptr.hpp>
namespace naoqi {
namespace helpers {
/**
* @brief Node helper class, holds a pointer towards the driver rclcpp::Node
*
*/
class Node {
public:
/**
* @brief Set the Node object
*
* @param node_ptr_
*/
static void setNode(const boost::shared_ptr<rclcpp::Node>& node_ptr) {
Node::node_ptr_ = node_ptr;
}
/**
* @brief Get the logger object for the driver node
*
* @return rclcpp::Logger
*/
static rclcpp::Logger get_logger() {
return Node::node_ptr_->get_logger();
}
/**
* @brief Get the number of subscribers for a publisher on a specific topic
*
* @return int
*/
static size_t count_subscribers(const std::string& topic_name) {
return Node::node_ptr_->count_subscribers(topic_name);
}
protected:
static boost::shared_ptr<rclcpp::Node> node_ptr_;
};
/**
* @brief Time helper class, used to access to time related functionalities
* throughout the project
*
*/
class Time : public Node {
public:
/**
* @brief Calls the method now of the node instance
*
* @return rclcpp::Time
*/
static rclcpp::Time now() {
return Time::node_ptr_->now();
}
};
} // naoqi
} // helpers
#endif // HELPERS_HPP | 22.352941 | 77 | 0.680526 | [
"object"
] |
12fb9469cc7f4e69cabcdc4737e4f1f6bc33de8d | 20,616 | cpp | C++ | rtt_dynamic_reconfigure/src/auto_config.cpp | mcx/rtt_ros_integration | df79afb7a7b6e90ea7b807f0e4322662caee8c07 | [
"BSD-3-Clause"
] | 73 | 2015-03-18T00:00:00.000Z | 2022-03-28T10:15:56.000Z | rtt_dynamic_reconfigure/src/auto_config.cpp | mcx/rtt_ros_integration | df79afb7a7b6e90ea7b807f0e4322662caee8c07 | [
"BSD-3-Clause"
] | 86 | 2015-01-20T19:12:34.000Z | 2021-12-20T07:18:58.000Z | rtt_dynamic_reconfigure/src/auto_config.cpp | mcx/rtt_ros_integration | df79afb7a7b6e90ea7b807f0e4322662caee8c07 | [
"BSD-3-Clause"
] | 59 | 2015-02-22T18:14:47.000Z | 2021-09-04T19:40:12.000Z | /*
* (C) 2014, Intermodalics BVBA
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <rtt_dynamic_reconfigure/auto_config.h>
#include <rtt/Property.hpp>
#include <rtt/internal/DataSources.hpp>
#include <rtt/types/PropertyComposition.hpp>
#include <cassert>
#include <climits>
#include <cfloat>
#include <boost/thread/locks.hpp>
#include <dynamic_reconfigure/config_tools.h>
namespace rtt_dynamic_reconfigure {
using namespace dynamic_reconfigure;
/**
* A special datasource that holds an instance of an AutoConfig description.
*
* The AutoConfigDataSource is used internally to store AutoConfig instances in a Property<RTT::PropertyBag>.
*/
class AutoConfigDataSource
: public RTT::internal::AssignableDataSource<RTT::PropertyBag>
{
protected:
AutoConfig mdata;
public:
~AutoConfigDataSource() {}
typedef boost::intrusive_ptr<AutoConfigDataSource> shared_ptr;
AutoConfigDataSource(const AutoConfig &data) : mdata(data) {}
AutoConfigDataSource() {}
RTT::internal::DataSource<RTT::PropertyBag>::result_t get() const { return mdata; }
RTT::internal::DataSource<RTT::PropertyBag>::result_t value() const { return mdata; }
void set( typename AssignableDataSource<RTT::PropertyBag>::param_t t ) { mdata = t; }
AutoConfig& set() { return mdata; }
const AutoConfig& rvalue() const { return mdata; }
virtual AutoConfigDataSource* clone() const { return new AutoConfigDataSource(mdata); }
/* copied from ValueDataSource<T>::copy() in DataSources.inl */
virtual AutoConfigDataSource* copy( std::map<const RTT::base::DataSourceBase*, RTT::base::DataSourceBase*>& replace ) const
{
// if somehow a copy exists, return the copy, otherwise return this (see Attribute copy)
if ( replace[this] != 0 ) {
assert ( dynamic_cast<AutoConfigDataSource*>( replace[this] ) == static_cast<AutoConfigDataSource*>( replace[this] ) );
return static_cast<AutoConfigDataSource*>( replace[this] );
}
// Other pieces in the code rely on insertion in the map :
replace[this] = const_cast<AutoConfigDataSource*>(this);
// return this instead of a copy.
return const_cast<AutoConfigDataSource*>(this);
}
/**
* This method narrows a base::DataSourceBase to a AutoConfigDataSource,
* possibly returning a new object.
*/
static AutoConfigDataSource* narrow(RTT::base::DataSourceBase* dsb) {
AutoConfigDataSource* ret = dynamic_cast< AutoConfigDataSource* >( dsb );
return ret;
}
};
AutoConfig::AutoConfig()
: parent(), id(), state()
{
}
AutoConfig::AutoConfig(const RTT::PropertyBag &bag)
: parent(), id(), state()
{
this->fromProperties(bag);
}
AutoConfig::~AutoConfig()
{
}
// default type
template <typename T> struct PropertyTypeInfo {
typedef std::string dynamic_reconfigure_type;
static std::string getType() { return "str"; }
static bool hasLimits() { return false; }
static T getMin() { return std::numeric_limits<T>::lowest(); }
static T getMax() { return std::numeric_limits<T>::max(); }
};
template <> struct PropertyTypeInfo<bool>
{
typedef bool dynamic_reconfigure_type;
static std::string getType() { return "bool"; }
static bool hasLimits() { return false; }
static bool getMin() { return false; }
static bool getMax() { return true; }
};
template <> struct PropertyTypeInfo<int>
{
typedef int dynamic_reconfigure_type;
static std::string getType() { return "int"; }
static bool hasLimits() { return true; }
static int getMin() { return INT_MIN; }
static int getMax() { return INT_MAX; }
};
template <> struct PropertyTypeInfo<unsigned int>
{
typedef int dynamic_reconfigure_type;
static std::string getType() { return "int"; }
static bool hasLimits() { return true; }
static int getMin() { return 0; }
static int getMax() { return INT_MAX; }
};
template <> struct PropertyTypeInfo<std::string>
{
typedef std::string dynamic_reconfigure_type;
static std::string getType() { return "str"; }
static bool hasLimits() { return false; }
static std::string getMin() { return ""; }
static std::string getMax() { return ""; }
};
template <> struct PropertyTypeInfo<double>
{
typedef double dynamic_reconfigure_type;
static std::string getType() { return "double"; }
static bool hasLimits() { return true; }
static double getMin() { return -DBL_MAX; }
static double getMax() { return DBL_MAX; }
};
template <> struct PropertyTypeInfo<float>
{
typedef double dynamic_reconfigure_type;
static std::string getType() { return "double"; }
static bool hasLimits() { return true; }
static double getMin() { return -FLT_MAX; }
static double getMax() { return FLT_MAX; }
};
static AutoConfig *getAutoConfigFromProperty(const RTT::base::PropertyBase *pb)
{
const RTT::Property<RTT::PropertyBag> *prop = dynamic_cast<const RTT::Property<RTT::PropertyBag> *>(pb);
if (!prop) return 0;
AutoConfigDataSource *ds = AutoConfigDataSource::narrow(prop->getDataSource().get());
if (!ds) return 0;
return &(ds->set());
}
template <typename T>
static bool propertyFromMessage(AutoConfig &config, Config &msg, const RTT::base::PropertyBase *sample, const std::string ¶m_name)
{
const RTT::Property<T> *sample_prop = dynamic_cast<const RTT::Property<T> *>(sample);
if (!sample_prop) return false;
typename PropertyTypeInfo<T>::dynamic_reconfigure_type value;
if (!ConfigTools::getParameter(msg, param_name, value)) return false;
RTT::Property<T> *prop = config.getPropertyType<T>(sample->getName());
if (!prop) {
prop = sample_prop->create();
config.ownProperty(prop);
}
prop->set(value);
return true;
}
bool AutoConfig::__fromMessage__(Config &msg, const AutoConfig &sample)
{
return __fromMessage__(*this, msg, sample);
}
bool AutoConfig::__fromMessage__(AutoConfig &config, Config &msg, const AutoConfig &sample)
{
// get group state
config.prefix_ = sample.prefix_;
config.name = sample.name;
config.id = sample.id;
config.parent = sample.parent;
dynamic_reconfigure::ConfigTools::getGroupState(msg, config.name, config);
// iterate over all properties in sample
bool result = true;
for(RTT::PropertyBag::const_iterator i = sample.begin(); i != sample.end(); ++i) {
std::string param_name = config.prefix_ + (*i)->getName();
// For sub groups, add a sub config to *this and recurse...
const AutoConfig *sample_sub = getAutoConfigFromProperty(*i);
if (sample_sub) {
RTT::Property<RTT::PropertyBag> *sub = config.getPropertyType<RTT::PropertyBag>((*i)->getName());
AutoConfigDataSource *ds;
if (sub) {
ds = AutoConfigDataSource::narrow(sub->getDataSource().get());
assert(ds->rvalue().getType() == sample_sub->getType());
} else {
ds = new AutoConfigDataSource();
ds->set().setType(sample_sub->getType());
}
if (ds && __fromMessage__(ds->set(), msg, *sample_sub)) {
if (!sub) {
// new AutoConfigDataSource
if (!ds->rvalue().empty()) {
sub = new RTT::Property<RTT::PropertyBag>((*i)->getName(), (*i)->getDescription(), AutoConfigDataSource::shared_ptr(ds));
config.ownProperty(sub);
} else {
delete ds;
}
}
continue;
}
}
// search parameter in Config message
bool param_found = false;
for(Config::_bools_type::const_iterator n = msg.bools.begin(); n != msg.bools.end(); ++n) {
if (n->name == param_name) param_found = true;
}
for(Config::_ints_type::const_iterator n = msg.ints.begin(); n != msg.ints.end(); ++n) {
if (n->name == param_name) param_found = true;
}
for(Config::_strs_type::const_iterator n = msg.strs.begin(); n != msg.strs.end(); ++n) {
if (n->name == param_name) param_found = true;
}
for(Config::_doubles_type::const_iterator n = msg.doubles.begin(); n != msg.doubles.end(); ++n) {
if (n->name == param_name) param_found = true;
}
if (!param_found) continue;
// get parameter value from Config message
if (
propertyFromMessage<bool>(config, msg, *i, param_name) ||
propertyFromMessage<int>(config, msg, *i, param_name) ||
propertyFromMessage<unsigned int>(config, msg, *i, param_name) ||
propertyFromMessage<std::string>(config, msg, *i, param_name) ||
propertyFromMessage<double>(config, msg, *i, param_name) ||
propertyFromMessage<float>(config, msg, *i, param_name)
) continue;
result = false;
}
return result;
}
template <typename T>
static bool propertyToMessage(Config &msg, const RTT::base::PropertyBase *pb, const std::string &_prefix)
{
const RTT::Property<T> *prop = dynamic_cast<const RTT::Property<T> *>(pb);
if (!prop) return false;
typename PropertyTypeInfo<T>::dynamic_reconfigure_type value = prop->get();
ConfigTools::appendParameter(msg, _prefix + pb->getName(), value);
return true;
}
void AutoConfig::__toMessage__(Config &msg) const
{
__toMessage__(*this, msg);
}
void AutoConfig::__toMessage__(const AutoConfig &config, Config &msg)
{
// add group state
dynamic_reconfigure::ConfigTools::appendGroup(msg, config.name, config.id, config.parent, config);
// iterate over all properties
bool result = true;
for(RTT::PropertyBag::const_iterator i = config.begin(); i != config.end(); ++i) {
if (propertyToMessage<bool>(msg, *i, config.prefix_) ||
propertyToMessage<int>(msg, *i, config.prefix_) ||
propertyToMessage<unsigned int>(msg, *i, config.prefix_) ||
propertyToMessage<std::string>(msg, *i, config.prefix_) ||
propertyToMessage<double>(msg, *i, config.prefix_) ||
propertyToMessage<float>(msg, *i, config.prefix_)
) continue;
// test if *i has type AutoConfig
const AutoConfig *sub = getAutoConfigFromProperty(*i);
if (sub) {
__toMessage__(*sub, msg);
continue;
}
result = false;
}
}
void AutoConfig::__toServer__(const ros::NodeHandle &nh) const
{
}
void AutoConfig::__fromServer__(const ros::NodeHandle &nh)
{
}
void AutoConfig::__clamp__(const ServerType *server)
{
const AutoConfig &min = server->getConfigMin();
const AutoConfig &max = server->getConfigMax();
// TODO: clamp values
}
uint32_t AutoConfig::__level__(const AutoConfig &config) const
{
return 0;
}
bool AutoConfig::updateProperties(RTT::PropertyBag &target) const
{
RTT::PropertyBag composed;
if (!RTT::types::composePropertyBag(*this, composed)) return false;
return RTT::updateProperties(target, composed);
}
bool AutoConfig::fromProperties(const RTT::PropertyBag &source)
{
RTT::PropertyBag decomposed;
if (!RTT::types::decomposePropertyBag(source, decomposed)) return false;
for(RTT::PropertyBag::const_iterator i = decomposed.begin(); i != decomposed.end(); ++i) {
RTT::base::PropertyBase *pb = this->getProperty((*i)->getName());
if (pb) {
pb->update(*i);
continue;
}
RTT::Property<RTT::PropertyBag> *sub = dynamic_cast<RTT::Property<RTT::PropertyBag> *>(*i);
if (sub) {
AutoConfigDataSource *ds = new AutoConfigDataSource(sub->rvalue());
ds->set().setType(sub->rvalue().getType());
this->ownProperty(new RTT::Property<RTT::PropertyBag>(sub->getName(), sub->getDescription(), ds));
continue;
} else {
this->ownProperty((*i)->clone());
}
}
return true;
}
template <typename T>
static bool buildParamDescription(const RTT::base::PropertyBase *pb, const std::string &prefix, Group::_parameters_type& params, AutoConfig& dflt, AutoConfig& min, AutoConfig& max)
{
const RTT::Property<T> *prop = dynamic_cast<const RTT::Property<T> *>(pb);
if (!prop) return false;
ParamDescription param;
param.name = prefix + pb->getName();
param.type = PropertyTypeInfo<T>::getType();
param.description = pb->getDescription();
params.push_back(param);
// get current value as default
if (!dflt.getProperty(pb->getName())) {
RTT::Property<T> *dflt_prop = prop->create();
dflt_prop->set(prop->get());
dflt.ownProperty(dflt_prop);
}
// get minimum/maximum value
if (!min.getProperty(pb->getName())) {
RTT::Property<T> *min_prop = prop->create();
min_prop->set(PropertyTypeInfo<T>::getMin());
min.ownProperty(min_prop);
}
if (!max.getProperty(pb->getName())) {
RTT::Property<T> *max_prop = prop->create();
max_prop->set(PropertyTypeInfo<T>::getMax());
max.ownProperty(max_prop);
}
return true;
}
static void buildGroupDescription(RTT::TaskContext *owner, const RTT::PropertyBag &bag, ConfigDescription& config_description, AutoConfig& dflt, AutoConfig& min, AutoConfig& max, const std::string &prefix, const std::string &name, const std::string &type, int32_t parent, int32_t &id)
{
std::size_t group_index = config_description.groups.size();
config_description.groups.push_back(Group());
Group &group = config_description.groups[group_index];
group.name = name.empty() ? "Default" : name;
group.type = type;
group.parent = parent;
group.id = id;
dflt.prefix_ = prefix;
dflt.name = group.name;
dflt.type = group.type;
dflt.parent = group.parent;
dflt.id = group.id;
dflt.state = true;
min.prefix_ = prefix;
min.name = group.name;
min.type = group.type;
min.parent = group.parent;
min.id = group.id;
min.state = true;
max.prefix_ = prefix;
max.name = group.name;
max.type = group.type;
max.parent = group.parent;
max.id = group.id;
max.state = true;
// for loop might invalidate group reference -> use index group_index instead
for(RTT::PropertyBag::const_iterator i = bag.begin(); i != bag.end(); ++i) {
if (buildParamDescription<bool>(*i, prefix, config_description.groups[group_index].parameters, dflt, min, max) ||
buildParamDescription<int>(*i, prefix, config_description.groups[group_index].parameters, dflt, min, max) ||
buildParamDescription<unsigned int>(*i, prefix, config_description.groups[group_index].parameters, dflt, min, max) ||
buildParamDescription<std::string>(*i, prefix, config_description.groups[group_index].parameters, dflt, min, max) ||
buildParamDescription<double>(*i, prefix, config_description.groups[group_index].parameters, dflt, min, max) ||
buildParamDescription<float>(*i, prefix, config_description.groups[group_index].parameters, dflt, min, max)
) continue;
const RTT::Property<RTT::PropertyBag> *sub = dynamic_cast<RTT::Property<RTT::PropertyBag> *>(*i);
if (sub) {
AutoConfig *sub_dflt = getAutoConfigFromProperty(dflt.getProperty(sub->getName()));
if (!sub_dflt) {
AutoConfigDataSource *ds = new AutoConfigDataSource();
sub_dflt = &(ds->set());
sub_dflt->setType(sub->rvalue().getType());
dflt.ownProperty(new RTT::Property<RTT::PropertyBag>(sub->getName(), sub->getDescription(), ds));
}
AutoConfig *sub_min = getAutoConfigFromProperty(min.getProperty(sub->getName()));
if (!sub_min) {
AutoConfigDataSource *ds = new AutoConfigDataSource();
sub_min = &(ds->set());
sub_min->setType(sub->rvalue().getType());
min.ownProperty(new RTT::Property<RTT::PropertyBag>(sub->getName(), sub->getDescription(), ds));
}
AutoConfig *sub_max = getAutoConfigFromProperty(max.getProperty(sub->getName()));
if (!sub_max) {
AutoConfigDataSource *ds = new AutoConfigDataSource();
sub_max = &(ds->set());
sub_max->setType(sub->rvalue().getType());
max.ownProperty(new RTT::Property<RTT::PropertyBag>(sub->getName(), sub->getDescription(), ds));
}
buildGroupDescription(owner, sub->rvalue(), config_description, *sub_dflt, *sub_min, *sub_max, prefix + sub->getName() + "__", prefix + sub->getName(), "", config_description.groups[group_index].id, ++id);
}
}
}
std::map<const AutoConfig::ServerType *, AutoConfig::CachePtr> AutoConfig::cache_;
boost::shared_mutex AutoConfig::cache_mutex_;
void AutoConfig::buildCache(const ServerType *server, RTT::TaskContext *owner)
{
RTT::PropertyBag decomposed;
if (!RTT::types::decomposePropertyBag(*(owner->properties()), decomposed)) {
RTT::log(RTT::Error) << "Failed to decompose properties of '" << owner->getName() << "' for dynamic_reconfigure. Properties with custom types will not be available for reconfiguration." << RTT::endlog();
decomposed = *(owner->properties());
}
boost::upgrade_lock<boost::shared_mutex> upgrade_lock(cache_mutex_);
if (upgrade_lock.owns_lock())
{
boost::upgrade_to_unique_lock<boost::shared_mutex> unique_lock(upgrade_lock);
CachePtr& cache = cache_[server];
if (!cache) cache.reset(new Cache());
cache->description_message_.reset(new ConfigDescription);
int32_t id = 0;
buildGroupDescription(owner, decomposed, *(cache->description_message_), cache->default_, cache->min_, cache->max_, "", "", "", 0, id);
}
}
dynamic_reconfigure::ConfigDescriptionPtr AutoConfig::__getDescriptionMessage__(const ServerType *server)
{
boost::shared_lock<boost::shared_mutex> lock(cache_mutex_);
if (!cache_.count(server)) buildCache(server, server->getOwner());
return cache_.at(server)->description_message_;
}
const AutoConfig &AutoConfig::__getDefault__(const ServerType *server)
{
boost::shared_lock<boost::shared_mutex> lock(cache_mutex_);
if (!cache_.count(server)) buildCache(server, server->getOwner());
return cache_.at(server)->default_;
}
const AutoConfig &AutoConfig::__getMax__(const ServerType *server)
{
boost::shared_lock<boost::shared_mutex> lock(cache_mutex_);
if (!cache_.count(server)) buildCache(server, server->getOwner());
return cache_.at(server)->max_;
}
const AutoConfig &AutoConfig::__getMin__(const ServerType *server)
{
boost::shared_lock<boost::shared_mutex> lock(cache_mutex_);
if (!cache_.count(server)) buildCache(server, server->getOwner());
return cache_.at(server)->min_;
}
void AutoConfig::__refreshDescription__(const ServerType *server)
{
buildCache(server, server->getOwner());
}
} // namespace rtt_dynamic_reconfigure
| 37.827523 | 284 | 0.658372 | [
"object"
] |
42022df97ddb00b04459180b9b8967ae3f621e77 | 2,930 | cpp | C++ | app/src/main/cpp/wrapper/camera_manager.cpp | brunomorishita/learning-camera2 | e4e08e592f0b9c5a14b2814c1a58d6d938a6f913 | [
"MIT"
] | null | null | null | app/src/main/cpp/wrapper/camera_manager.cpp | brunomorishita/learning-camera2 | e4e08e592f0b9c5a14b2814c1a58d6d938a6f913 | [
"MIT"
] | null | null | null | app/src/main/cpp/wrapper/camera_manager.cpp | brunomorishita/learning-camera2 | e4e08e592f0b9c5a14b2814c1a58d6d938a6f913 | [
"MIT"
] | null | null | null | //
// Created by bruno on 12/06/2021.
//
#include "camera_manager.h"
#include "log_internal.h"
#include "camera_device.h"
#include <camera/NdkCameraDevice.h>
#include <camera/NdkCameraManager.h>
#include <camera/NdkCameraMetadata.h>
namespace devices {
CameraManager::CameraManager() {
camera_status_t camera_status = ACAMERA_OK;
m_cameraManager = ACameraManager_create();
camera_status = ACameraManager_getCameraIdList(m_cameraManager, &m_cameraIdList);
if (camera_status != ACAMERA_OK) {
LOGE("Failed to get camera id list (reason: %d)\n", camera_status);
return;
}
}
CameraManager::~CameraManager() {
if (m_cameraManager)
ACameraManager_delete(m_cameraManager);
if (m_cameraIdList)
ACameraManager_deleteCameraIdList(m_cameraIdList);
}
std::vector<std::string> CameraManager::getCameraIds() {
std::vector<std::string> ret;
for (int i = 0; i < m_cameraIdList->numCameras; ++i) {
const char* selectedCameraId = m_cameraIdList->cameraIds[i];
ret.push_back(std::string(selectedCameraId));
}
return ret;
}
CameraMetadata CameraManager::getCameraCharacteristics(std::string id) {
camera_status_t camera_status = ACAMERA_OK;
ACameraMetadata *cameraMetadata = nullptr;
CameraMetadata metadata;
camera_status = ACameraManager_getCameraCharacteristics(m_cameraManager, id.c_str(),
&cameraMetadata);
if (camera_status != ACAMERA_OK) {
ACameraMetadata_free(cameraMetadata);
LOGE("Failed to get camera meta data of ID:%s\n", id.c_str());
return metadata;
}
ACameraMetadata_const_entry entry;
if(ACameraMetadata_getConstEntry(cameraMetadata, ACAMERA_LENS_FACING, &entry) == ACAMERA_OK)
{
auto facing = static_cast<acamera_metadata_enum_android_lens_facing_t>(entry.data.u8[0]);
if(facing == ACAMERA_LENS_FACING_BACK)
metadata.camera_lens_facing = CAMERA_LENS_FACING::BACK;
else if (facing == ACAMERA_LENS_FACING_FRONT)
metadata.camera_lens_facing = CAMERA_LENS_FACING::FRONT;
else
metadata.camera_lens_facing = CAMERA_LENS_FACING::EXTERNAL;
}
ACameraMetadata_free(cameraMetadata);
return metadata;
}
std::shared_ptr<devices::CameraDevice> CameraManager::getCameraDevice(std::string id) {
if (auto dev{m_devices.find(id ) }; dev != std::end(m_devices ) ) {
auto[ key, value ] { *dev };
return value;
}
auto cameraDevice = std::make_shared<devices::CameraDevice>(m_cameraManager, id);
m_devices.emplace(id, cameraDevice);
return cameraDevice;
}
} // namespace devices | 33.295455 | 101 | 0.63686 | [
"vector"
] |
4207197d019d7f5cb8919a3dc347343e8d7637bd | 7,262 | cpp | C++ | tests/test_moves_knight.cpp | MathewRGB/BlaEngine | fd64b7e8b54efad09f6466c6cb47ee920dc445f7 | [
"MIT"
] | 1 | 2019-12-06T00:42:54.000Z | 2019-12-06T00:42:54.000Z | tests/test_moves_knight.cpp | MathewRGB/BlaEngine | fd64b7e8b54efad09f6466c6cb47ee920dc445f7 | [
"MIT"
] | null | null | null | tests/test_moves_knight.cpp | MathewRGB/BlaEngine | fd64b7e8b54efad09f6466c6cb47ee920dc445f7 | [
"MIT"
] | null | null | null | #include "gtest/gtest.h"
#include "helper_for_tests.h"
#include "source/calculation/move_generator.h"
using namespace blaengine::calculation;
TEST(KnightMoves, test_general_moves_all) {
auto move_generator = MoveGenerator();
auto game_state = GameState();
ushort field_before = 27;
game_state.board[field_before] = Piece::white_knight;
auto knight_moves = move_generator.getKnightMoves(game_state, field_before);
vector<Move> expected_moves = {{field_before, 17, Piece::left_piece},
{field_before, 10, Piece::left_piece},
{field_before, 12, Piece::left_piece},
{field_before, 21, Piece::left_piece},
{field_before, 37, Piece::left_piece},
{field_before, 44, Piece::left_piece},
{field_before, 42, Piece::left_piece},
{field_before, 33, Piece::left_piece}};
ASSERT_TRUE(expectedMovesInMoves(knight_moves, expected_moves));
}
TEST(KnightMoves, test_general_moves_pos0) {
auto move_generator = MoveGenerator();
auto game_state = GameState();
ushort field_before = 0;
game_state.board[field_before] = Piece::black_knight;
auto knight_moves = move_generator.getKnightMoves(game_state, field_before);
vector<Move> expected_moves = {{field_before, 17, Piece::left_piece},
{field_before, 10, Piece::left_piece}};
ASSERT_TRUE(expectedMovesInMoves(knight_moves, expected_moves));
}
TEST(KnightMoves, test_general_moves_pos7) {
auto move_generator = MoveGenerator();
auto game_state = GameState();
ushort field_before = 7;
game_state.board[field_before] = Piece::white_knight;
auto knight_moves = move_generator.getKnightMoves(game_state, field_before);
vector<Move> expected_moves = {{field_before, 13, Piece::left_piece},
{field_before, 22, Piece::left_piece}};
ASSERT_TRUE(expectedMovesInMoves(knight_moves, expected_moves));
}
TEST(KnightMoves, test_general_moves_pos63) {
auto move_generator = MoveGenerator();
auto game_state = GameState();
ushort field_before = 63;
game_state.board[field_before] = Piece::black_knight;
auto knight_moves = move_generator.getKnightMoves(game_state, field_before);
vector<Move> expected_moves = {{field_before, 53, Piece::left_piece},
{field_before, 46, Piece::left_piece}};
ASSERT_TRUE(expectedMovesInMoves(knight_moves, expected_moves));
}
TEST(KnightMoves, test_general_moves_pos56) {
auto move_generator = MoveGenerator();
auto game_state = GameState();
ushort field_before = 56;
game_state.board[field_before] = Piece::white_knight;
auto knight_moves = move_generator.getKnightMoves(game_state, field_before);
vector<Move> expected_moves = {{field_before, 41, Piece::left_piece},
{field_before, 50, Piece::left_piece}};
ASSERT_TRUE(expectedMovesInMoves(knight_moves, expected_moves));
}
TEST(KnightMoves, test_general_moves_pos24) {
auto move_generator = MoveGenerator();
auto game_state = GameState();
ushort field_before = 24;
game_state.board[field_before] = Piece::black_knight;
auto knight_moves = move_generator.getKnightMoves(game_state, field_before);
vector<Move> expected_moves = {{field_before, 41, Piece::left_piece},
{field_before, 34, Piece::left_piece},
{field_before, 9, Piece::left_piece},
{field_before, 18, Piece::left_piece}};
ASSERT_TRUE(expectedMovesInMoves(knight_moves, expected_moves));
}
TEST(KnightMoves, test_general_moves_pos55) {
auto move_generator = MoveGenerator();
auto game_state = GameState();
ushort field_before = 55;
game_state.board[field_before] = Piece::white_knight;
auto knight_moves = move_generator.getKnightMoves(game_state, field_before);
vector<Move> expected_moves = {{field_before, 61, Piece::left_piece},
{field_before, 45, Piece::left_piece},
{field_before, 38, Piece::left_piece}};
ASSERT_TRUE(expectedMovesInMoves(knight_moves, expected_moves));
}
TEST(KnightMoves, test_general_moves_pos3) {
auto move_generator = MoveGenerator();
auto game_state = GameState();
ushort field_before = 3;
game_state.board[field_before] = Piece::black_knight;
auto knight_moves = move_generator.getKnightMoves(game_state, field_before);
vector<Move> expected_moves = {{field_before, 9, Piece::left_piece},
{field_before, 18, Piece::left_piece},
{field_before, 20, Piece::left_piece},
{field_before, 13, Piece::left_piece}};
ASSERT_TRUE(expectedMovesInMoves(knight_moves, expected_moves));
}
TEST(KnightMoves, test_w_moves_piece_taking) {
auto move_generator = MoveGenerator();
auto game_state = GameState();
ushort field_before = 45;
game_state.board[field_before] = Piece::white_knight;
game_state.board[51] = Piece::white_knight;
game_state.board[60] = Piece::black_knight;
game_state.board[62] = Piece::white_queen;
game_state.board[55] = Piece::black_pawn;
game_state.board[39] = Piece::white_king;
game_state.board[30] = Piece::white_bishop;
game_state.board[28] = Piece::black_rook;
game_state.board[35] = Piece::white_rook;
auto knight_moves = move_generator.getKnightMoves(game_state, field_before);
vector<Move> expected_moves = {{field_before, 60, Piece::left_piece},
{field_before, 55, Piece::left_piece},
{field_before, 28, Piece::left_piece}};
ASSERT_TRUE(expectedMovesInMoves(knight_moves, expected_moves));
}
TEST(KnightMoves, test_b_moves_piece_taking) {
auto move_generator = MoveGenerator();
auto game_state = GameState();
ushort field_before = 45;
game_state.board[field_before] = Piece::black_knight;
game_state.board[51] = Piece::black_knight;
game_state.board[60] = Piece::white_knight;
game_state.board[62] = Piece::black_queen;
game_state.board[55] = Piece::white_pawn;
game_state.board[39] = Piece::black_king;
game_state.board[30] = Piece::black_rook;
game_state.board[28] = Piece::white_rook;
game_state.board[35] = Piece::black_rook;
auto knight_moves = move_generator.getKnightMoves(game_state, field_before);
vector<Move> expected_moves = {{field_before, 60, Piece::left_piece},
{field_before, 55, Piece::left_piece},
{field_before, 28, Piece::left_piece}};
ASSERT_TRUE(expectedMovesInMoves(knight_moves, expected_moves));
}
TEST(KnightMoves, test_moves_no_moves) {
auto move_generator = MoveGenerator();
auto game_state = GameState();
ushort field_before = 0;
game_state.board[field_before] = Piece::black_knight;
game_state.board[17] = Piece::black_knight;
game_state.board[10] = Piece::black_pawn;
auto knight_moves = move_generator.getKnightMoves(game_state, field_before);
vector<Move> expected_moves = {};
ASSERT_TRUE(expectedMovesInMoves(knight_moves, expected_moves));
}
| 40.569832 | 78 | 0.687414 | [
"vector"
] |
420b6c87cea2c305cd3310395470068db7acddb5 | 518 | hpp | C++ | infra/util/test_helper/MockHelpers.hpp | ghsecuritylab/embeddedinfralib | 46ebdfcc495150afb38cc380f22be7c3e3dcbfbc | [
"Unlicense"
] | 54 | 2019-04-02T14:42:54.000Z | 2022-03-20T23:02:19.000Z | infra/util/test_helper/MockHelpers.hpp | ghsecuritylab/embeddedinfralib | 46ebdfcc495150afb38cc380f22be7c3e3dcbfbc | [
"Unlicense"
] | 32 | 2019-03-26T06:57:29.000Z | 2022-03-25T00:04:44.000Z | infra/util/test_helper/MockHelpers.hpp | ghsecuritylab/embeddedinfralib | 46ebdfcc495150afb38cc380f22be7c3e3dcbfbc | [
"Unlicense"
] | 20 | 2019-03-25T15:49:49.000Z | 2022-03-20T23:02:22.000Z | #ifndef INFRA_MOCK_HELPERS_HPP
#define INFRA_MOCK_HELPERS_HPP
#include "gmock/gmock.h"
#include <functional>
#include <type_traits>
#include <vector>
namespace infra
{
MATCHER_P(CheckByteRangeContents, contents, "")
{
return std::vector<uint8_t>(arg.begin(), arg.end()) == std::vector<uint8_t>(contents.begin(), contents.end());
}
ACTION_TEMPLATE(SaveRef,
HAS_1_TEMPLATE_PARAMS(int, k),
AND_1_VALUE_PARAMS(pointer)) {
*pointer = &::std::get<k>(args);
}
}
#endif
| 21.583333 | 118 | 0.667954 | [
"vector"
] |
42120fb20da3e318304dcd7af3697907cffcf13c | 8,034 | cpp | C++ | Engine/Source/Runtime/CinematicCamera/Private/CameraRig_Crane.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/Runtime/CinematicCamera/Private/CameraRig_Crane.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/Runtime/CinematicCamera/Private/CameraRig_Crane.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "CameraRig_Crane.h"
#include "UObject/ConstructorHelpers.h"
#include "Components/StaticMeshComponent.h"
#include "Engine/StaticMesh.h"
#include "Engine/CollisionProfile.h"
#define LOCTEXT_NAMESPACE "CameraRig_Crane"
ACameraRig_Crane::ACameraRig_Crane(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
PrimaryActorTick.bCanEverTick = true;
// default control values
CraneYaw = 0.f;
CranePitch = 0.f;
CraneArmLength = 500.f;
bLockMountPitch = false;
bLockMountYaw = false;
// create the root component
TransformComponent = CreateDefaultSubobject<USceneComponent>(TEXT("TransformComponent"));
RootComponent = TransformComponent;
// create the functional component hierarchy
CraneYawControl = CreateDefaultSubobject<USceneComponent>(TEXT("CraneYawControl"));
CraneYawControl->SetupAttachment(TransformComponent);
CraneYawControl->RelativeLocation = FVector(0.f, 0.f, 70.f); // pivot height off the ground
CraneYawControl->RelativeRotation = FRotator(0.f, CraneYaw, 0.f);
CranePitchControl = CreateDefaultSubobject<USceneComponent>(TEXT("CranePitchControl"));
CranePitchControl->SetupAttachment(CraneYawControl);
CranePitchControl->RelativeRotation = FRotator(CranePitch, 0.f, 0.f);
CraneCameraMount = CreateDefaultSubobject<USceneComponent>(TEXT("CraneCameraMount"));
CraneCameraMount->SetupAttachment(CranePitchControl);
CraneCameraMount->RelativeLocation = FVector(CraneArmLength, 0.f, -15.f); // negative z == underslung mount
#if WITH_EDITORONLY_DATA
// create preview meshes
if (!IsRunningDedicatedServer())
{
static ConstructorHelpers::FObjectFinder<UStaticMesh> CraneBaseMesh(TEXT("/Engine/EditorMeshes/Camera/SM_CraneRig_Base.SM_CraneRig_Base"));
PreviewMesh_CraneBase = CreateOptionalDefaultSubobject<UStaticMeshComponent>(TEXT("PreviewMesh_CraneBase"));
if (PreviewMesh_CraneBase)
{
PreviewMesh_CraneBase->SetStaticMesh(CraneBaseMesh.Object);
PreviewMesh_CraneBase->bIsEditorOnly = true;
PreviewMesh_CraneBase->SetCollisionProfileName(UCollisionProfile::NoCollision_ProfileName);
PreviewMesh_CraneBase->bHiddenInGame = true;
PreviewMesh_CraneBase->CastShadow = false;
PreviewMesh_CraneBase->PostPhysicsComponentTick.bCanEverTick = false;
PreviewMesh_CraneBase->SetupAttachment(TransformComponent); // sibling of yawcontrol
}
static ConstructorHelpers::FObjectFinder<UStaticMesh> CraneArmMesh(TEXT("/Engine/EditorMeshes/Camera/SM_CraneRig_Arm.SM_CraneRig_Arm"));
PreviewMesh_CraneArm = CreateOptionalDefaultSubobject<UStaticMeshComponent>(TEXT("PreviewMesh_CraneArm"));
if (PreviewMesh_CraneArm)
{
PreviewMesh_CraneArm->SetStaticMesh(CraneArmMesh.Object);
PreviewMesh_CraneArm->bIsEditorOnly = true;
PreviewMesh_CraneArm->SetCollisionProfileName(UCollisionProfile::NoCollision_ProfileName);
PreviewMesh_CraneArm->bHiddenInGame = true;
PreviewMesh_CraneArm->CastShadow = false;
PreviewMesh_CraneArm->PostPhysicsComponentTick.bCanEverTick = false;
PreviewMesh_CraneArm->SetupAttachment(CranePitchControl); // sibling of the mount
PreviewMesh_CraneArm->RelativeRotation = FRotator(0.f, 90.f, 0.f);
PreviewMesh_CraneArm->RelativeLocation = FVector(0.f, 0.f, 52.f);
PreviewMesh_CraneArm->RelativeScale3D = FVector(0.7f, 0.7f, 0.7f);
}
static ConstructorHelpers::FObjectFinder<UStaticMesh> CraneArmMount(TEXT("/Engine/EditorMeshes/Camera/SM_CraneRig_Mount.SM_CraneRig_Mount"));
PreviewMesh_CraneMount = CreateOptionalDefaultSubobject<UStaticMeshComponent>(TEXT("PreviewMesh_CraneMount"));
if (PreviewMesh_CraneMount)
{
PreviewMesh_CraneMount->SetStaticMesh(CraneArmMount.Object);
PreviewMesh_CraneMount->bIsEditorOnly = true;
PreviewMesh_CraneMount->SetCollisionProfileName(UCollisionProfile::NoCollision_ProfileName);
PreviewMesh_CraneMount->bHiddenInGame = true;
PreviewMesh_CraneMount->CastShadow = false;
PreviewMesh_CraneMount->PostPhysicsComponentTick.bCanEverTick = false;
PreviewMesh_CraneMount->SetupAttachment(CranePitchControl);
PreviewMesh_CraneMount->RelativeRotation = FRotator(0.f, 90.f, 0.f);
PreviewMesh_CraneMount->RelativeLocation = FVector(CraneArmLength, 0.f, 0.f);
PreviewMesh_CraneMount->RelativeScale3D = FVector(0.7f, 0.7f, 0.7f);
}
static ConstructorHelpers::FObjectFinder<UStaticMesh> CraneArmCW(TEXT("/Engine/EditorMeshes/Camera/SM_CraneRig_Body.SM_CraneRig_Body"));
PreviewMesh_CraneCounterWeight = CreateOptionalDefaultSubobject<UStaticMeshComponent>(TEXT("PreviewMesh_CraneCounterWeight"));
if (PreviewMesh_CraneCounterWeight)
{
PreviewMesh_CraneCounterWeight->SetStaticMesh(CraneArmCW.Object);
PreviewMesh_CraneCounterWeight->bIsEditorOnly = true;
PreviewMesh_CraneCounterWeight->SetCollisionProfileName(UCollisionProfile::NoCollision_ProfileName);
PreviewMesh_CraneCounterWeight->bHiddenInGame = true;
PreviewMesh_CraneCounterWeight->CastShadow = false;
PreviewMesh_CraneCounterWeight->PostPhysicsComponentTick.bCanEverTick = false;
PreviewMesh_CraneCounterWeight->SetupAttachment(CranePitchControl);
PreviewMesh_CraneCounterWeight->RelativeRotation = FRotator(0.f, 90.f, 0.f);
PreviewMesh_CraneCounterWeight->RelativeScale3D = FVector(0.7f, 0.7f, 0.7f);
}
UpdatePreviewMeshes();
}
#endif
}
static const float CraneArmMesh_DefaultMeshSize = 29.f * 0.7f; // size of the mesh in the dimension that will stretch (accounting for the 0.7 scale)
#if WITH_EDITORONLY_DATA
void ACameraRig_Crane::UpdatePreviewMeshes()
{
if (PreviewMesh_CraneArm)
{
// note to explain the math here:
// this tailored to the dimensions of the asset (29cm in scaling direction, pivot at the edge)
float const CraneArmYScale = CraneArmLength / CraneArmMesh_DefaultMeshSize;
FVector NewRelScale3D = PreviewMesh_CraneArm->RelativeScale3D;
NewRelScale3D.Y = CraneArmYScale * 0.7f;
PreviewMesh_CraneArm->SetRelativeScale3D(NewRelScale3D);
}
if (PreviewMesh_CraneMount)
{
const float ZOffset = 40.f; // make it appear in the right place
FVector const NewLoc(CraneArmLength, 0.f, ZOffset);
PreviewMesh_CraneMount->SetRelativeLocation(NewLoc);
}
}
#endif
void ACameraRig_Crane::UpdateCraneComponents()
{
FRotator NewYawControlRot = CraneYawControl->RelativeRotation;
NewYawControlRot.Yaw = CraneYaw;
CraneYawControl->SetRelativeRotation(FRotator(0.f, CraneYaw, 0.f));
FRotator NewPitchControlRot = CranePitchControl->RelativeRotation;
NewPitchControlRot.Pitch = CranePitch;
CranePitchControl->SetRelativeRotation(FRotator(CranePitch, 0.f, 0.f));
FVector NewCameraMountLoc = CraneCameraMount->RelativeLocation;
NewCameraMountLoc.X = CraneArmLength;
CraneCameraMount->SetRelativeLocation(NewCameraMountLoc);
// zero the pitch from the camera mount component
// this effectively gives us bAbsoluteRotation for only pitch component of an attached camera
FRotator NewCameraMountWorldRot = CraneCameraMount->GetAttachParent() ? CraneCameraMount->GetAttachParent()->GetComponentRotation() : FRotator(0.f, 0.f, 0.f);
if (!bLockMountPitch)
{
NewCameraMountWorldRot.Pitch = 0.f;
}
if (!bLockMountYaw)
{
NewCameraMountWorldRot.Yaw = RootComponent->RelativeRotation.Yaw;
}
NewCameraMountWorldRot.Roll = 0.f;
CraneCameraMount->SetWorldRotation(NewCameraMountWorldRot);
#if WITH_EDITORONLY_DATA
UpdatePreviewMeshes();
#endif
}
void ACameraRig_Crane::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
// feed exposed API into underlying components
UpdateCraneComponents();
}
#if WITH_EDITOR
void ACameraRig_Crane::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent)
{
Super::PostEditChangeProperty(PropertyChangedEvent);
UpdateCraneComponents();
}
void ACameraRig_Crane::PostEditUndo()
{
Super::PostEditUndo();
UpdateCraneComponents();
}
#endif // WITH_EDITOR
USceneComponent* ACameraRig_Crane::GetDefaultAttachComponent() const
{
return CraneCameraMount;
}
bool ACameraRig_Crane::ShouldTickIfViewportsOnly() const
{
return true;
}
#undef LOCTEXT_NAMESPACE
| 38.257143 | 159 | 0.803709 | [
"mesh",
"object"
] |
421698ee1c24cbc4100aead98ccab151b9c97a6a | 3,496 | hpp | C++ | src/uml/src_gen/uml/impl/FactoryImpl.hpp | dataliz9r/MDE4CPP | 9c5ce01c800fb754c371f1a67f648366eeabae49 | [
"MIT"
] | null | null | null | src/uml/src_gen/uml/impl/FactoryImpl.hpp | dataliz9r/MDE4CPP | 9c5ce01c800fb754c371f1a67f648366eeabae49 | [
"MIT"
] | 1 | 2019-03-01T00:54:13.000Z | 2019-03-04T02:15:50.000Z | src/uml/src_gen/uml/impl/FactoryImpl.hpp | vallesch/MDE4CPP | 7f8a01dd6642820913b2214d255bef2ea76be309 | [
"MIT"
] | null | null | null | //********************************************************************
//*
//* Warning: This file was generated by ecore4CPP Generator
//*
//********************************************************************
#ifndef UML_FACTORYFACTORYIMPL_HPP
#define UML_FACTORYFACTORYIMPL_HPP
//*********************************
// generated Includes
//Model includes
#include "../Factory.hpp"
#include "uml/impl/ElementImpl.hpp"
//*********************************
namespace uml
{
class FactoryImpl :virtual public ElementImpl, virtual public Factory
{
public:
FactoryImpl(const FactoryImpl & obj);
virtual std::shared_ptr<ecore::EObject> copy() const;
private:
FactoryImpl& operator=(FactoryImpl const&) = delete;
protected:
friend class UmlFactoryImpl;
FactoryImpl();
virtual std::shared_ptr<Factory> getThisFactoryPtr() const;
virtual void setThisFactoryPtr(std::weak_ptr<Factory> thisFactoryPtr);
//Additional constructors for the containments back reference
FactoryImpl(std::weak_ptr<uml::Element > par_owner);
public:
//destructor
virtual ~FactoryImpl();
//*********************************
// Operations
//*********************************
/*!
Creates an element that is an instance of the metaClass. Object::metaClass == metaClass and metaClass.isInstance(object)
== true.
All properties of the element are considered unset. The values are the same as if object.unset(property) was invoked for
every property. */
virtual std::shared_ptr<uml::Element> create(std::shared_ptr<uml::Class> metaClass) ;
//*********************************
// Attributes Getter Setter
//*********************************
//*********************************
// Reference
//*********************************
//*********************************
// Union Getter
//*********************************
/*!
The Elements owned by this Element.
<p>From package UML::CommonStructure.</p> */
virtual std::shared_ptr<Union<uml::Element>> getOwnedElement() const ;
//*********************************
// Structural Feature Getter/Setter
//*********************************
virtual std::shared_ptr<ecore::EObject> eContainer() const ;
//*********************************
// Persistence Functions
//*********************************
virtual void load(std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler) ;
virtual void loadAttributes(std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler, std::map<std::string, std::string> attr_list);
virtual void loadNode(std::string nodeName, std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler, std::shared_ptr<uml::UmlFactory> modelFactory);
virtual void resolveReferences(const int featureID, std::list<std::shared_ptr<ecore::EObject> > references) ;
virtual void save(std::shared_ptr<persistence::interfaces::XSaveHandler> saveHandler) const ;
virtual void saveContent(std::shared_ptr<persistence::interfaces::XSaveHandler> saveHandler) const;
protected:
virtual std::shared_ptr<ecore::EClass> eStaticClass() const;
virtual Any eGet(int featureID, bool resolve, bool coreType) const ;
virtual bool internalEIsSet(int featureID) const ;
virtual bool eSet(int featureID, Any newValue) ;
private:
std::weak_ptr<Factory> m_thisFactoryPtr;
};
}
#endif /* end of include guard: UML_FACTORYFACTORYIMPL_HPP */
| 33.295238 | 162 | 0.587243 | [
"object",
"model"
] |
42183586ed99ff227d57fcad7082f175acfa93e3 | 482 | cpp | C++ | playcontext.cpp | RustedBot/Pong | 8e75d64b306cc4c3db433061dd2e3418b7102354 | [
"MIT"
] | null | null | null | playcontext.cpp | RustedBot/Pong | 8e75d64b306cc4c3db433061dd2e3418b7102354 | [
"MIT"
] | null | null | null | playcontext.cpp | RustedBot/Pong | 8e75d64b306cc4c3db433061dd2e3418b7102354 | [
"MIT"
] | null | null | null | #include "playcontext.hpp"
#include "event.hpp"
#include "inputhandler.hpp"
#include "keyname.hpp"
std::vector<Event> PlayContext::update(InputHandler& inputHandler)
{
std::vector<Event> events;
if(inputHandler.keyboard.isKeyPressed(keyBindings[KeyName::UP_KEY]))
{
events.push_back(Event::MOVE_UP);
}
if(inputHandler.keyboard.isKeyPressed(keyBindings[KeyName::DOWN_KEY]))
{
events.push_back(Event::MOVE_DOWN);
}
return events;
}
| 21.909091 | 74 | 0.697095 | [
"vector"
] |
4218be28631a4f639b5588205e2471f0a2f4fb1a | 7,513 | cpp | C++ | UiModule/Inworld/ControlPanel/BindingWidget.cpp | mattire/naali | 28c9cdc84c6a85e0151a222e55ae35c9403f0212 | [
"Apache-2.0"
] | 1 | 2018-04-02T15:38:10.000Z | 2018-04-02T15:38:10.000Z | UiModule/Inworld/ControlPanel/BindingWidget.cpp | mattire/naali | 28c9cdc84c6a85e0151a222e55ae35c9403f0212 | [
"Apache-2.0"
] | null | null | null | UiModule/Inworld/ControlPanel/BindingWidget.cpp | mattire/naali | 28c9cdc84c6a85e0151a222e55ae35c9403f0212 | [
"Apache-2.0"
] | null | null | null | // For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "BindingWidget.h"
#include <QMap>
#include <QVariant>
#include <QMessageBox>
#include <QDebug>
namespace CoreUi
{
BindingWidget::BindingWidget(QObject *settings_object) :
QWidget()
{
setupUi(this);
helpWidget->hide();
connect(settings_object, SIGNAL(SaveSettingsClicked()), SLOT(ExportSettings()));
connect(restoreDefaultsPushButton, SIGNAL(clicked()), SLOT(RestoreBindingsToDefault()));
connect(helpPushButton, SIGNAL(clicked()), SLOT(ToggleHelp()));
// Loop trough all of our line edits and set a input validator
KeySequenceValidator *key_sequence_validator = new KeySequenceValidator(this);
Foundation::KeyBindings *bindings = new Foundation::KeyBindings();
foreach (QString line_edit_identifier, bindings->GetConfigKeys())
{
QLineEdit *line_edit = GetLineEditForName(line_edit_identifier);
if (line_edit)
line_edit->setValidator(key_sequence_validator);
}
SAFE_DELETE(bindings);
}
// Public
void BindingWidget::UpdateContent(Foundation::KeyBindings *bindings)
{
Foundation::KeyBindingList bindings_list = bindings->GetBindings();
Foundation::KeyBindingList::const_iterator iter = bindings_list.begin();
Foundation::KeyBindingList::const_iterator end = bindings_list.end();
// Generate internal format QMap from KeyBindings data
QMap<QString, QList<QVariant> > name_to_seq_list_map;
while (iter != end)
{
Foundation::Binding binding = (*iter);
QString event_name = bindings->NameForEvent(binding.event_ids.enter_id);
if (!event_name.isEmpty())
{
if (name_to_seq_list_map.contains(event_name))
name_to_seq_list_map[event_name].append(binding.sequence);
else
{
QList<QVariant> seq_list;
seq_list.append(binding.sequence);
name_to_seq_list_map[event_name] = seq_list;
}
}
iter++;
}
// Update ui with internal format list
foreach (QString identifier, name_to_seq_list_map.keys())
{
QList<QVariant> value_list = name_to_seq_list_map[identifier];
QLineEdit *line_edit = GetLineEditForName(identifier);
if (!line_edit)
continue;
QString text = "";
foreach (QVariant value, value_list)
text += value.toString() + ", ";
line_edit->setText(text.left(text.lastIndexOf(",")));
}
}
// Private
void BindingWidget::ExportSettings()
{
// Create KeyBindings from internal format map
Foundation::KeyBindings *bindings = new Foundation::KeyBindings();
// Generate internal format map
QMap<QString, QList<QVariant> > name_to_seq_list_map;
foreach (QString identifier, bindings->GetConfigKeys())
{
QLineEdit *line_edit = GetLineEditForName(identifier);
if (!line_edit)
continue;
QList<QVariant> seq_value_list;
QStringList line_edit_values = line_edit->text().split(", ");
foreach (QString sequence_string, line_edit_values)
seq_value_list.append(QKeySequence(sequence_string));
name_to_seq_list_map[identifier] = seq_value_list;
}
foreach (QString identifier, name_to_seq_list_map.keys())
{
QList<QVariant> seq_list = name_to_seq_list_map[identifier];
std::pair<int,int> id_pair = bindings->EventPairForName(identifier);
if (id_pair.first == 0)
continue;
foreach (QVariant seq, seq_list)
bindings->BindKey(QKeySequence(seq.toString()), id_pair);
}
emit KeyBindingsUpdated(bindings);
}
void BindingWidget::RestoreBindingsToDefault()
{
int selection = QMessageBox::question(this, "Restoring default bindings", "Really want to restore? This will remove your\ncurrently stored bindings permanently.", QMessageBox::Yes, QMessageBox::No);
if (selection == QMessageBox::Yes)
emit RestoreDefaultBindings();
}
void BindingWidget::ToggleHelp()
{
if (helpWidget->isVisible())
helpWidget->hide();
else
helpWidget->show();
}
QLineEdit *BindingWidget::GetLineEditForName(QString name)
{
if (name == "toggle.fly")
return toggleFlyLineEdit;
else if (name == "toggle.camera")
return toggleCameraModeLineEdit;
else if (name == "toggle.console")
return toggleConsoleLineEdit;
else if (name == "zoom.in")
return zoomInLineEdit;
else if (name == "zoom.out")
return zoomOutLineEdit;
else if (name == "move.forward")
return forwardLineEdit;
else if (name == "move.back")
return backwardLineEdit;
else if (name == "move.left")
return strafeLeftLineEdit;
else if (name == "move.right")
return strafeRightLineEdit;
else if (name == "move.up")
return upJumpLineEdit;
else if (name == "move.down")
return downLineEdit;
else if (name == "rotate.left")
return turnLeftLineEdit;
else if (name == "rotate.right")
return turnRightLineEdit;
else if (name == "naali.delete")
return deleteLineEdit;
else if (name == "naali.undo")
return undoLineEdit;
else if (name == "naali.object.link")
return objectLinkLineEdit;
else if (name == "naali.object.unlink")
return objectUnlinkLineEdit;
else if (name == "naali.toggle.ether")
return toggleEtherLineEdit;
else if (name == "naali.toggle.worldchat")
return focusChatLineEdit;
else if (name == "python.run")
return runLineEdit;
else if (name == "python.restart")
return restartLineEdit;
else if (name == "python.duplicate.drag")
return duplicateDragLineEdit;
else if (name == "python.object.toggle.move")
return toggleObjectMoveLineEdit;
else if (name == "python.object.toggle.scale")
return toggleObjectScaleLineEdit;
return 0;
}
// =========================================================================
// KeySequenceValidator for line edits
KeySequenceValidator::KeySequenceValidator(QObject *parent) :
QValidator(parent)
{
}
QValidator::State KeySequenceValidator::validate(QString &input, int &pos) const
{
if (pos == 0)
return QValidator::Acceptable;
QString new_char, is_space = "", seq_string;
new_char = input.right(1);
if (pos >= 2)
is_space = QString(input.at(pos-2));
if (new_char == " ")
return QValidator::Acceptable;
seq_string = QKeySequence(new_char).toString();
if (pos != 1 && (is_space != " " && is_space != "+"))
seq_string = seq_string.toLower();
input = input.left(pos-1) + seq_string;
return QValidator::Acceptable;
}
} | 36.120192 | 206 | 0.59244 | [
"object"
] |
4218d8d69837d3fb9e19aa38f4a409d54401c707 | 6,508 | cpp | C++ | src/atomsciflow/nwchem/nwchem.cpp | DeqiTang/build-test-atomsciflow | 6fb65c79e74993e2100fbbca31b910d495076805 | [
"MIT"
] | 1 | 2022-01-25T01:44:32.000Z | 2022-01-25T01:44:32.000Z | src/atomsciflow/nwchem/nwchem.cpp | DeqiTang/build-test-atomsciflow | 6fb65c79e74993e2100fbbca31b910d495076805 | [
"MIT"
] | null | null | null | src/atomsciflow/nwchem/nwchem.cpp | DeqiTang/build-test-atomsciflow | 6fb65c79e74993e2100fbbca31b910d495076805 | [
"MIT"
] | null | null | null | /************************************************************************
MIT License
Copyright (c) 2021 Deqi Tang
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 src/atomsciflow/nwchem/nwchem.cpp
/// @author DeqiTang
/// Mail: deqitang@gmail.com
/// Created Time: Fri 25 Mar 2022 03:28:12 PM CST
#include "atomsciflow/nwchem/nwchem.h"
#include <iostream>
#include <fstream>
#include <boost/filesystem.hpp>
#include <boost/format.hpp>
#include <iomanip>
namespace atomsciflow {
namespace fs = boost::filesystem;
NWChem::NWChem() {
add_keyword("Charge", 0);
add_keyword("title", "NWChem calculation");
job.set_run_default("llhpc");
job.set_run_default("pbs");
job.set_run_default("bash");
job.set_run_default("lsf_sz");
job.set_run_default("lsf_sustc");
job.set_run_default("cdcloud");
job.set_run("cmd", "$ASF_CMD_NWCHEM");
job.set_run("script_name_head", "nwchem-run");
}
NWChem::~NWChem() {
}
// task directive must be specified in the end
std::string NWChem::to_string() {
std::ostringstream out;
for (const auto& item : this->directives) {
if ("task" == item.first) {
continue;
}
out << item.second->to_string() << "\n";
}
out << this->directives["task"]->to_string();
return out.str();
}
void NWChem::new_directive(const std::string& name) {
this->directives[name] = std::make_shared<nwchem::Directive>(name);
}
template <typename T>
void NWChem::add_keyword(const std::string& path, T keyword) {
if (this->directives.find(path) == this->directives.end()) {
this->new_directive(path);
}
this->directives[path]->keywords.push_back(boost::lexical_cast<std::string>(keyword));
}
/**
* Sometimes in NWChem, only two keywords make sense, like "units angstroms"
* Thus, we provide an overloaded template here.
* Note that usually the keyword_1 in such case is usually a string, and
* when build the instantiation of the template we only sepcify std::string
* for keyword_1 type.
*/
template <typename T, typename U>
void NWChem::add_keyword(const std::string& path, T keyword_1, U keyword_2) {
this->add_keyword(path, keyword_1);
this->add_keyword(path, keyword_2);
}
void NWChem::py_add_keyword(const std::string& path, int keyword) {
this->add_keyword(path, keyword);
}
void NWChem::py_add_keyword(const std::string& path, double keyword) {
this->add_keyword(path, keyword);
}
void NWChem::py_add_keyword(const std::string& path, std::string keyword) {
this->add_keyword(path, keyword);
}
void NWChem::py_add_keyword(const std::string& path, std::string keyword_1, int keyword_2) {
this->add_keyword(path, keyword_1);
this->add_keyword(path, keyword_2);
}
void NWChem::py_add_keyword(const std::string& path, std::string keyword_1, double keyword_2) {
this->add_keyword(path, keyword_1);
this->add_keyword(path, keyword_2);
}
void NWChem::py_add_keyword(const std::string& path, std::string keyword_1, std::string keyword_2) {
this->add_keyword(path, keyword_1);
this->add_keyword(path, keyword_2);
}
void NWChem::py_set_field(const std::string& path, int field, int row, int col) {
this->set_field(path, field, row, col);
}
void NWChem::py_set_field(const std::string& path, double field, int row, int col) {
this->set_field(path, field, row, col);
}
void NWChem::py_set_field(const std::string& path, std::string field, int row, int col) {
this->set_field(path, field, row, col);
}
void NWChem::get_xyz(const std::string& filepath) {
this->xyz.read_xyz_file(filepath);
job.set_run("xyz_file", fs::absolute(filepath).string());
this->new_directive("geometry");
this->directives["geometry"]->keywords.push_back("units");
this->directives["geometry"]->keywords.push_back("angstroms");
for (const auto& item : this->xyz.atoms) {
std::vector<std::string> atom;
atom.push_back(item.name);
atom.push_back(boost::lexical_cast<std::string>(item.x));
atom.push_back(boost::lexical_cast<std::string>(item.y));
atom.push_back(boost::lexical_cast<std::string>(item.z));
this->directives["geometry"]->fields.push_back(atom);
}
this->new_directive("basis");
for (const auto& item : this->xyz.elements_set) {
std::vector<std::string> basis;
basis.push_back(item);
basis.push_back("library");
basis.push_back("6-31g");
this->directives["basis"]->fields.push_back(basis);
}
}
void NWChem::run(const std::string& directory) {
std::ostringstream step;
step << "cd ${ABSOLUTE_WORK_DIR}" << "\n";
step << "cat > nwchem.nw<<EOF\n";
step << this->to_string();
step << "EOF\n";
step << "$CMD_HEAD " << job.run_params["cmd"] << "\n";
job.steps.push_back(step.str());
step.clear();
job.run(directory);
}
// explicit template instantiation
template void NWChem::add_keyword<int>(const std::string&, int);
template void NWChem::add_keyword<double>(const std::string&, double);
template void NWChem::add_keyword<std::string>(const std::string&, std::string);
template void NWChem::add_keyword<std::string, int>(const std::string&, std::string, int);
template void NWChem::add_keyword<std::string, double>(const std::string&, std::string, double);
template void NWChem::add_keyword<std::string, std::string>(const std::string&, std::string, std::string);
} // namespace atomsciflow
| 34.802139 | 106 | 0.683006 | [
"geometry",
"vector"
] |
421c03cde2efebb3aa11219a610370db7836fd15 | 21,974 | cpp | C++ | pbihdfutils/SamFilter.cpp | mchaisso/blasr | 044b97e6e581a936d93e8226b25ac44aebf3c9da | [
"BSD-3-Clause"
] | 17 | 2015-05-05T12:41:15.000Z | 2021-03-24T05:50:58.000Z | pbihdfutils/SamFilter.cpp | EichlerLab/blasr | c9bced1fedfb026b4992e2b49e4ffa0f107819ea | [
"BSD-3-Clause"
] | 6 | 2015-07-07T14:01:00.000Z | 2021-04-17T07:53:12.000Z | pbihdfutils/SamFilter.cpp | EichlerLab/blasr | c9bced1fedfb026b4992e2b49e4ffa0f107819ea | [
"BSD-3-Clause"
] | 10 | 2015-01-22T19:27:40.000Z | 2022-02-17T06:43:01.000Z | /*
* =====================================================================================
*
* Filename: SAMFilter.cpp
*
* Description: Filter SAM Hits according to
* filteration criteria
* minPctSimilarity, minAccuracy,
* minLength, holeNumber
* and multiple-hit policy
* random : a random hit
* all : all hits
* allbest : all hits with the best score
* randombest: a random hit selected from all the hits
* that have the best score
*
* Version: 1.0
* Created: 03/19/2013 01:19:43 PM
* Revision: none
* Compiler: gcc
*
* Author: Yuan Li (yli), yli@pacificbiosciences.com
* Company: Pacific Biosciences
*
* =====================================================================================
*/
#include <iostream>
#include "FASTASequence.h"
#include "FASTAReader.h"
#include "CommandLineParser.h"
#include "utils/ChangeListID.h"
#include "utils/TimeUtils.h"
#include "utils/RangeUtils.h"
#include "utils/SMRTReadUtils.h"
#include "algorithms/alignment/ScoreMatrices.h"
#include "algorithms/alignment/AlignmentUtils.h"
#include "algorithms/alignment/StringToScoreMatrix.h"
#include "algorithms/alignment/readers/sam/SAMReader.h"
#include "algorithms/alignment/printers/SAMPrinter.h"
#include "datastructures/alignment/AlignmentCandidate.h"
#include "datastructures/alignment/FilterCriteria.h"
#include "datastructures/alignmentset/SAMToAlignmentCandidateAdapter.h"
#include "algorithms/alignment/DistanceMatrixScoreFunction.h"
//#define USE_GOOGLE_PROFILER
#ifdef USE_GOOGLE_PROFILER
#include "gperftools/profiler.h"
#endif
char VERSION[] = "v0.1.0";
char PERFORCE_VERSION_STRING[] = "$Change: 126414 $";
// By default negative score is better.
SCORESIGN scoreSign = NEG;
// Score functions can be:
// ALIGNERSCORE: aligner's score as indicated by 'as' flag
// EDITDIST : edit distance between query and target
// BLASESCORE : blasr's default score
// USERSCORE : score computed from user specifed score matrix, and
// insertion & deletion scores
enum SCOREFUNC {ALIGNERSCORE, EDITDIST, BLASRSCORE, USERSCORE};
enum HITPOLICY {RANDOM, ALL, ALLBEST, RANDOMBEST};//, LEFTPOSITIVE};
// Return a multiple hit policy.
HITPOLICY setHitPolicy(const string & hitPolicyStr) {
if (hitPolicyStr == "random") return RANDOM;
else if (hitPolicyStr == "all") return ALL;
else if (hitPolicyStr == "allbest") return ALLBEST;
else if (hitPolicyStr == "randombest") return RANDOMBEST;
else {
cout <<"ERROR, the specified multiple hit policy "
<< hitPolicyStr <<" is not supported." << endl;
exit(1);
}
}
// Return a score function for computing alignment scores.
SCOREFUNC setScoreFunction(const string & scoreFuncStr) {
if (scoreFuncStr == "alignerscore") return ALIGNERSCORE;
else if (scoreFuncStr == "editdist") return EDITDIST;
else if (scoreFuncStr == "blasrscore") return BLASRSCORE;
else if (scoreFuncStr == "userscore") return USERSCORE;
else {
cout <<"ERROR, the specified score function "
<< scoreFuncStr <<" is not supported." << endl;
exit(1);
}
}
// Compare SAMAlignment objects by qName, score and
// target positions.
bool byQNameScoreTStart(const SAMAlignment & a,
const SAMAlignment & b) {
if (a.qName == b.qName) {
if (a.score == b.score)
return a.pos < b.pos;
return Score(a.score, scoreSign).WorseThan(b.score);
}
return (a.qName < b.qName);
}
// Compare SAMAlignment objects by rName and qName
bool byRNameQName(const SAMAlignment & a,
const SAMAlignment & b) {
if (a.rName == b.rName) {
return a.qName < b.qName;
}
return (a.rName < b.rName);
}
// Get the next group of SAM alignments that have the same qName from
// allSAMAlignments[groupBegin ... groupEnd)
// Note that allSAMAlignments is already sorted by qName, score and tPos.
void GetNextSAMAlignmentGroup(vector<SAMAlignment> & allSAMAlignments,
unsigned int groupBegin,
unsigned int & groupEnd) {
assert(groupBegin < allSAMAlignments.size());
groupEnd = groupBegin + 1;
string queryName = allSAMAlignments[groupBegin].qName;
while(groupEnd < allSAMAlignments.size()) {
if (allSAMAlignments[groupEnd].qName == queryName)
groupEnd ++;
else break;
}
}
// Get the best SAM alignments whose alignment score are the best.
// Assume that alignments in allSAMAlignments[groupBegin, groupEnd)
// all have the same queryName and are sorted by score and tPos.
void GetBestSAMAlignmentsInGroup(vector<SAMAlignment> & allSAMAlignments,
const unsigned int & groupBegin,
const unsigned int & groupEnd,
unsigned int & bestBegin,
unsigned int & bestEnd) {
assert(groupEnd <= allSAMAlignments.size() and
groupBegin < groupEnd);
bestBegin = groupBegin;
bestEnd = bestBegin + 1;
int groupBestScore = allSAMAlignments[bestBegin].score;
string queryName = allSAMAlignments[bestBegin].qName;
while(bestEnd < groupEnd) {
assert(allSAMAlignments[bestEnd].qName == queryName);
if (allSAMAlignments[bestEnd].score == groupBestScore)
bestEnd ++;
else break;
}
}
// Apply hit policy to a group of SAM alignments and return indices
// of the selected alignments.
vector<unsigned int> ApplyHitPolicy(HITPOLICY hitPolicy,
vector<SAMAlignment> & allSAMAlignments,
const unsigned int & groupBegin,
const unsigned int & groupEnd) {
vector<unsigned int> hitIndices;
if (hitPolicy == ALL) {
for(unsigned int i = groupBegin; i < groupEnd; i++){
hitIndices.push_back(i);
}
} else if (hitPolicy == RANDOM) {
hitIndices.push_back(rand()%(groupEnd - groupBegin) + groupBegin);
} else {
unsigned int bestBegin, bestEnd;
GetBestSAMAlignmentsInGroup(allSAMAlignments, groupBegin, groupEnd,
bestBegin, bestEnd);
if (hitPolicy == ALLBEST) {
for(unsigned int i = bestBegin; i < bestEnd; i++){
hitIndices.push_back(i);
}
} else if (hitPolicy == RANDOMBEST) {
hitIndices.push_back(rand()%(bestEnd - bestBegin) + bestBegin);
}
}
return hitIndices;
}
int main(int argc, char* argv[]) {
#ifdef USE_GOOGLE_PROFILER
char *profileFileName = getenv("CPUPROFILE");
if (profileFileName != NULL) {
ProfilerStart(profileFileName);
}
else {
ProfilerStart("google_profile.txt");
}
#endif
string samFileName, refFileName, outFileName;
bool parseSmrtTitle = false;
int scoreCutoff = INF_INT;
int scoreSignInt = -1;
string scoreFuncStr = "alignerscore";
string scoreMatrixStr= "";
SCOREFUNC scoreFunc;
int insScore = 5; // Insertion penalty
int delScore = 5; // Deletion penalty
int seed = 1;
bool isSorted = false; // Whether input sam file is sorted.
int verbosity = 0;
string holeNumberStr;
Ranges holeNumberRanges;
FilterCriteria filterCriteria;
string hitPolicyStr = "randombest";
HITPOLICY hitPolicy = ALLBEST;
CommandLineParser clp;
clp.RegisterStringOption("file.sam", &samFileName,
"Input SAM file.");
clp.RegisterStringOption("reference.fasta", &refFileName,
"Reference used to generate reads.");
clp.RegisterStringOption("out.sam", &outFileName,
"Output SAM file.");
clp.RegisterPreviousFlagsAsHidden();
stringstream help;
help << "(" << filterCriteria.minAccuracy
<< ") Minimum accuracy to the reference.";
clp.RegisterIntOption("minAccuracy", &filterCriteria.minAccuracy,
help.str(), CommandLineParser::PositiveInteger);
help.str(string());
help << "(" << filterCriteria.minPctSimilarity
<< ") Minimum percentage similarity to the reference.";
clp.RegisterIntOption("minPctSimilarity", &filterCriteria.minPctSimilarity,
help.str(), CommandLineParser::PositiveInteger);
help.str(string());
help << "(" << filterCriteria.minLength
<< ") Minimum aligned read length to output a hit.";
clp.RegisterIntOption("minLength", &filterCriteria.minLength,
help.str(), CommandLineParser::PositiveInteger);
clp.RegisterStringOption("hitPolicy", &hitPolicyStr,
"(randombest) Specify a policy for how to treat multiple hits from "
"[random, all, allbest, randombest]\n"
" random : selects a random hit.\n"
" all : selects all hits.\n"
" allbest : selects all the best alignment score hits.\n"
" randombest: selects a random hit from all best alignment score hits.");
clp.RegisterStringOption("scoreFunction", &scoreFuncStr,
"(alignerscore) Specify an alignment score function from "
"[alignerscore, editdist, blasrscore, userscore]\n" // affine
" alignerscore : aligner's score in SAM tag 'as'.\n"
" editdist : edit distance between read and reference.\n"
" blasrscore : blasr's default score function.\n"
" userscore : score computed using a user-defined scoring\n"
" matrix (specified by -scoreMatrix) and \n"
" insertion & deletion scores (specified by \n"
" -insertion and -deletion respectively).");
clp.RegisterStringOption("scoreMatrix", &scoreMatrixStr,
"Specify a user-defined score matrix for scoring reads."
"The matrix is in the format\n"
" ACGTN\n"
" A abcde\n"
" C fghij\n"
" G klmno\n"
" T pqrst\n"
" N uvwxy\n"
". The values a...y should be input as a quoted space "
"seperated string: \"a b c ... y\". Lower scores are better, "
"so matches should be less than mismatches e.g. a,g,m,s = -5 "
"(match), mismatch = 6. ");
clp.RegisterIntOption("deletion", &delScore,
"Specify a user-defined deletion score.",
CommandLineParser::Integer);
clp.RegisterIntOption("insertion", &insScore,
"Specify a user-defined insertion score.",
CommandLineParser::Integer);
clp.RegisterIntOption("scoreCutoff", &scoreCutoff,
"Score cut off defines the worst score to output a hit.",
CommandLineParser::Integer);
clp.RegisterIntOption("scoreSign", &scoreSignInt,
"(-1) Sepcifiy the alignment score sign."
" -1: negative scores are better than positive ones."
" 1: positive scores are better than negative ones.",
CommandLineParser::Integer);
clp.RegisterIntOption ("seed", &seed,
"(1) Seed for random number generator."
" If seed is 0, then the current time will be used as seed.",
CommandLineParser::Integer);
//clp.RegisterFlagOption("sorted", &isSorted,
// "Sepcify that the sam file has been sorted by read name.");
clp.RegisterFlagOption("smrtTitle", &parseSmrtTitle,
"Use this read when converting alignments generated by "
"programs other than blasr, e.g. bwa-sw or gmap. "
" Parse read coordinates from the SMRT read title. "
"The title is in the format /name/hole/coordinates, where"
" coordinates are in the format \\d+_\\d+, and represent "
"the interval of the read that was aligned.");
clp.RegisterStringOption("holeNumbers", &holeNumberStr,
"A string of comma-delimited hole number ranges to output hits, "
"such as '1,2,10-12'. "
"This requires hit titles to be in SMRT read title format.");
clp.SetExamples(
"Because SAM has optional tags that have different meanings"
" in different programs, careful usage is required in order "
"to have proper output. The \"xs\" tag in bwa-sw is used to "
"show the suboptimal score, but in PacBio SAM (blasr) it is "
"defined as the start in the query sequence of the alignment.\n"
"When \"-smrtTitle\" is specified, the xs tag is ignored, but "
"when it is not specified, the coordinates given by the xs and "
"xe tags are used to define the interval of a read that is "
"aligned. The CIGAR string is relative to this interval.");
// Set random number seed.
if (seed == 0) {
srand(time(NULL));
} else {
srand(0);
}
clp.ParseCommandLine(argc, argv);
filterCriteria.verbosity = verbosity;
// Set hit policy.
hitPolicy = setHitPolicy(hitPolicyStr);
// Set score function.
scoreFunc = setScoreFunction(scoreFuncStr);
// Set score cutoff and sign
if (scoreCutoff != INF_INT)
filterCriteria.SetScoreCutoff((double)scoreCutoff);
scoreSign = filterCriteria.SetScoreSign(scoreSignInt);
if (scoreFunc == USERSCORE and scoreMatrixStr == "") {
cout << "ERROR. Please specify user-defined score matrix using -scoreMatrix." << endl;
exit(1);
}
if (scoreMatrixStr != "") {
if (scoreFunc != USERSCORE) {
cout << "ERROR. scoreFunc should be 'userscore' if -scoreMatrix is used." << endl;
exit(1);
}
if (StringToScoreMatrix(scoreMatrixStr, SMRTDistanceMatrix) == false) {
cout << "ERROR. The string " << endl
<< scoreMatrixStr << endl
<< "is not a valid format. It should be a quoted, space separated string of " << endl
<< "integer values. The matrix: " << endl
<< " A C G T N" << endl
<< " A 1 2 3 4 5" << endl
<< " C 6 7 8 9 10" << endl
<< " G 11 12 13 14 15" << endl
<< " T 16 17 18 19 20" << endl
<< " N 21 22 23 24 25" << endl
<< " should be specified as \"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 " << endl
<< "20 21 22 23 24 25\"" << endl;
exit(1);
}
}
// Parse hole number ranges.
if (holeNumberStr.size() != 0) {
if (not holeNumberRanges.setRanges(holeNumberStr)) {
cout << "Could not parse hole number ranges: "
<< holeNumberStr << "." << endl;
exit(1);
}
}
int scoreMatrix[5][5];
memcpy(scoreMatrix, SMRTDistanceMatrix, 25*sizeof(int));
if (scoreFunc == EDITDIST) {
// Penalty=1 for each mismatch and indel.
memcpy(scoreMatrix, EditDistanceMatrix, 25*sizeof(int));
insScore = delScore = 1;
scoreSign = filterCriteria.SetScoreSign(NEG);
} else if (scoreFunc == BLASRSCORE) {
memcpy(scoreMatrix, SMRTDistanceMatrix, 25*sizeof(int));
insScore = delScore = 5;
scoreSign = filterCriteria.SetScoreSign(NEG);
}
//
// If ALIGNERSCORE, score matrix does not matter.
// If USERSCORE, use user-specified scorematrix, insScore
// and delScore.
//
ostream * outFilePtr = &cout;
ofstream outFileStrm;
if (outFileName != "") {
CrucialOpen(outFileName, outFileStrm, std::ios::out);
outFilePtr = &outFileStrm;
}
SAMReader<SAMFullReferenceSequence, SAMReadGroup, SAMAlignment> samReader;
FASTAReader fastaReader;
//
// Initialize samReader and fastaReader.
//
samReader.Initialize(samFileName);
fastaReader.Initialize(refFileName);
//
// Configure the file log.
//
string command;
CommandLineParser::CommandLineToString(argc, argv, command);
string log = "Filter sam hits.";
string program = "samFilter";
string versionString = VERSION;
AppendPerforceChangelist(PERFORCE_VERSION_STRING, versionString);
//
// Read necessary input.
//
vector<FASTASequence> references;
fastaReader.ReadAllSequences(references);
AlignmentSet<SAMFullReferenceSequence, SAMReadGroup, SAMAlignment> alignmentSet;
vector<string> allHeaders = samReader.ReadHeader(alignmentSet);
// Process SAM Header.
string commandLineString;
clp.CommandLineToString(argc, argv, commandLineString);
allHeaders.push_back("@PG\tID:SAMFILTER\tVN:" + versionString + \
"\tCL:" + program + " " + commandLineString);
for (int i = 0; i < allHeaders.size(); i++) {
outFileStrm << allHeaders[i] << endl;
}
//
// The order of references in vector<FASTASequence> references and
// AlignmentSet<, , >alignmentSet.references can be different.
// Rearrange alignmentSet.references such that it is ordered in
// exactly the same way as vector<FASTASequence> references.
//
alignmentSet.RearrangeReferences(references);
// Map reference name obtained from SAM file to indices
map<string, int> refNameToIndex;
for (int i = 0; i < references.size(); i++) {
string refName = alignmentSet.references[i].GetSequenceName();
refNameToIndex[refName] = i;
}
//
// Store the alignments.
//
SAMAlignment samAlignment;
int alignIndex = 0;
//
// For 150K, each chip produces about 300M sequences
// (not including quality values and etc.).
// Let's assume that the sam file and reference data can
// fit in the memory.
// Need to scale for larger sequal data in the future.
//
vector<SAMAlignment> allSAMAlignments;
DistanceMatrixScoreFunction<DNASequence, FASTQSequence> distScoreFn(SMRTDistanceMatrix, insScore, delScore);
while (samReader.GetNextAlignment(samAlignment)) {
if (samAlignment.rName == "*") {
continue;
}
if (parseSmrtTitle and holeNumberStr.size() != 0) {
string movieName;
int thisHoleNumber;
if (not ParsePBIReadName(samAlignment.qName,
movieName,
thisHoleNumber)) {
cout << "ERROR, could not parse SMRT title: "
<< samAlignment.qName << "." << endl;
exit(1);
}
if (not holeNumberRanges.contains(UInt(thisHoleNumber))) {
if (verbosity > 0)
cout << thisHoleNumber << " is not in range." << endl;
continue;
}
}
if (samAlignment.cigar.find('P') != string::npos) {
cout << "WARNING. Could not process sam record with 'P' in its cigar string."
<< endl;
continue;
}
vector<AlignmentCandidate<> > convertedAlignments;
SAMAlignmentsToCandidates(samAlignment,
references, refNameToIndex,
convertedAlignments, parseSmrtTitle, false);
if (convertedAlignments.size() > 1) {
cout << "WARNING. Ignore multiple segments." << endl;
continue;
}
for (int i = 0; i < 1; i++) {
AlignmentCandidate<> & alignment = convertedAlignments[i];
ComputeAlignmentStats(alignment, alignment.qAlignedSeq.seq,
alignment.tAlignedSeq.seq, distScoreFn);
if (verbosity > 0) {
cout << "Aligner's score = " << samAlignment.as
<< ", computed score = " << alignment.score << endl;
}
// Assign score to samAlignment.
samAlignment.score = alignment.score;
if (scoreFunc == ALIGNERSCORE)
samAlignment.score = samAlignment.as;
if (not filterCriteria.Satisfy(alignment)) {
if (verbosity > 0)
cout << alignment.qName
<< " does not satisfy filter criteria." << endl;
continue;
}
allSAMAlignments.push_back( samAlignment );
alignment.FreeSubsequences();
}
++alignIndex;
}
// Sort all SAM alignments by qName, score and target position.
if (!isSorted) {
sort(allSAMAlignments.begin(), allSAMAlignments.end(),
byQNameScoreTStart);
}
unsigned int groupBegin = 0;
unsigned int groupEnd = -1;
vector<SAMAlignment> filteredSAMAlignments;
while(groupBegin < allSAMAlignments.size()) {
// Get the next group of SAM alignments which have the same qName
// from allSAMAlignments[groupBegin ... groupEnd)
GetNextSAMAlignmentGroup(allSAMAlignments, groupBegin, groupEnd);
vector<unsigned int> hitIndices = ApplyHitPolicy(
hitPolicy, allSAMAlignments, groupBegin, groupEnd);
for(unsigned int i = 0; i < hitIndices.size(); i++) {
filteredSAMAlignments.push_back(allSAMAlignments[hitIndices[i]]);
}
groupBegin = groupEnd;
}
sort(filteredSAMAlignments.begin(), filteredSAMAlignments.end(),
byRNameQName);
for(unsigned int i = 0; i < filteredSAMAlignments.size(); i++) {
filteredSAMAlignments[i].PrintSAMAlignment(outFileStrm);
}
if (outFileName != "") {
outFileStrm.close();
}
#ifdef USE_GOOGLE_PROFILER
ProfilerStop();
#endif
return 0;
}
| 39.030195 | 110 | 0.598161 | [
"vector"
] |
42350732d1ff37238f9978c97c46426f7b9f1aa8 | 1,304 | cpp | C++ | projects/client/visual/through/source/through/Doorway.cpp | silentorb/mythic-cpp | 97319d158800d77e1a944c47c13523662bc07e08 | [
"MIT"
] | null | null | null | projects/client/visual/through/source/through/Doorway.cpp | silentorb/mythic-cpp | 97319d158800d77e1a944c47c13523662bc07e08 | [
"MIT"
] | null | null | null | projects/client/visual/through/source/through/Doorway.cpp | silentorb/mythic-cpp | 97319d158800d77e1a944c47c13523662bc07e08 | [
"MIT"
] | null | null | null | #include "Doorway.h"
#include "glm/glm.hpp"
#include "glow.h"
#include <stdexcept>
#include "glow_gl.h"
using namespace glm;
namespace through {
Doorway::Doorway(int id, const Field_Type &type, int offset)
: id(id), offset(offset), type(type) {
updater = determine_updater(type);
}
void update_matrix(int index, void *matrix) {
glUniformMatrix4fv(index, 1, GL_FALSE, (GLfloat *) matrix);
}
void update_vector3(int index, void *pointer) {
auto vector = (vec3 *) pointer;
glUniform3f(index, vector->x, vector->y, vector->z);
}
void update_int(int index, void *pointer) {
glUniform1i(index, *(int *) pointer);
}
void update_float(int index, void *pointer) {
glUniform1f(index, *(int *) pointer);
}
Doorway_Delegate Doorway::determine_updater(const Field_Type &type) {
switch (type) {
case Field_Type::matrix:
return update_matrix;
case Field_Type::vector3:
return update_vector3;
case Field_Type::integer:
return update_int;
case Field_Type::floating_point:
return update_float;
}
throw std::runtime_error("Invalid field type.");
}
void Doorway::update(void *data) {
updater(id, ((char *) data) + offset);
}
}
| 23.285714 | 72 | 0.627301 | [
"vector"
] |
4246a1031dbb9280f88bc6446666742732f8eae6 | 1,349 | cpp | C++ | aws-cpp-sdk-shield/source/model/TimeRange.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-shield/source/model/TimeRange.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-shield/source/model/TimeRange.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-12-30T04:25:33.000Z | 2021-12-30T04:25:33.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/shield/model/TimeRange.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace Shield
{
namespace Model
{
TimeRange::TimeRange() :
m_fromInclusiveHasBeenSet(false),
m_toExclusiveHasBeenSet(false)
{
}
TimeRange::TimeRange(JsonView jsonValue) :
m_fromInclusiveHasBeenSet(false),
m_toExclusiveHasBeenSet(false)
{
*this = jsonValue;
}
TimeRange& TimeRange::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("FromInclusive"))
{
m_fromInclusive = jsonValue.GetDouble("FromInclusive");
m_fromInclusiveHasBeenSet = true;
}
if(jsonValue.ValueExists("ToExclusive"))
{
m_toExclusive = jsonValue.GetDouble("ToExclusive");
m_toExclusiveHasBeenSet = true;
}
return *this;
}
JsonValue TimeRange::Jsonize() const
{
JsonValue payload;
if(m_fromInclusiveHasBeenSet)
{
payload.WithDouble("FromInclusive", m_fromInclusive.SecondsWithMSPrecision());
}
if(m_toExclusiveHasBeenSet)
{
payload.WithDouble("ToExclusive", m_toExclusive.SecondsWithMSPrecision());
}
return payload;
}
} // namespace Model
} // namespace Shield
} // namespace Aws
| 18.479452 | 81 | 0.728688 | [
"model"
] |
4249a63946651c3b7c8e36950f741f5da039ccef | 513 | cpp | C++ | 0201-0300/0275-H-Index II/0275-H-Index II.cpp | jiadaizhao/LeetCode | 4ddea0a532fe7c5d053ffbd6870174ec99fc2d60 | [
"MIT"
] | 49 | 2018-05-05T02:53:10.000Z | 2022-03-30T12:08:09.000Z | 0201-0300/0275-H-Index II/0275-H-Index II.cpp | jolly-fellow/LeetCode | ab20b3ec137ed05fad1edda1c30db04ab355486f | [
"MIT"
] | 11 | 2017-12-15T22:31:44.000Z | 2020-10-02T12:42:49.000Z | 0201-0300/0275-H-Index II/0275-H-Index II.cpp | jolly-fellow/LeetCode | ab20b3ec137ed05fad1edda1c30db04ab355486f | [
"MIT"
] | 28 | 2017-12-05T10:56:51.000Z | 2022-01-26T18:18:27.000Z | class Solution {
public:
int hIndex(vector<int>& citations) {
int n = citations.size();
int low = 0, high = n - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (citations[mid] == n - mid) {
return n - mid;
}
else if (citations[mid] > n - mid) {
high = mid - 1;
}
else {
low = mid + 1;
}
}
return n - low;
}
};
| 23.318182 | 48 | 0.358674 | [
"vector"
] |
424b80d231f41ff5d5f10e8675b3c3740ca99b86 | 98,033 | cpp | C++ | sevn-interface/SEVN/src/star/property.cpp | giulianoiorio/PeTar | f6a849552b3d8e47c5e08fe90fed05bf38bc407d | [
"MIT"
] | null | null | null | sevn-interface/SEVN/src/star/property.cpp | giulianoiorio/PeTar | f6a849552b3d8e47c5e08fe90fed05bf38bc407d | [
"MIT"
] | null | null | null | sevn-interface/SEVN/src/star/property.cpp | giulianoiorio/PeTar | f6a849552b3d8e47c5e08fe90fed05bf38bc407d | [
"MIT"
] | null | null | null | //
// Created by mario on 09/02/19.
//
#include <property.h>
#include <star.h>
#include <iomanip>
#include <supernova.h>
#include <remnant.h>
#include <lambda_nanjing.h>
void Property::evolve_fake(Star *s){
///Set v0=v
set_0_fk(value); //save the previous value, before the evolution
///Move to new value in the interpolating track
FOR4 {
val_in[_i] = val_ref[_i] + s->pos[_i];
}
///Find new values at times t for the interpolatring tracks using linear interpolation
for(int i = 0; i < 4; i++) {
//cout<<"cycle = "<<i<<endl;
double *_val = val_in[i];
double *_time = s->times_in[i];
double slope = ((*(_val + 1)) - *_val) / ((*(_time +1)) - *_time);
double intercept = *_val - slope * (*_time);
interpolating_values[i] = slope * s->ttimes[i] + intercept; //ttimes come from function tracktimes()
}
///Find the interpolating z value, M1*v1 + M2*v2
double val_zlow = interpolating_values[0]*wM[0] + interpolating_values[1]*wM[1];
double val_zhigh = interpolating_values[2]*wM[2] + interpolating_values[3]*wM[3];
///Find the final interpolated value, v=Z1*v1 + Z2*v2
set_fk(wZ[0]*val_zlow + wZ[1]*val_zhigh);
//if (s->getp(Worldtime::ID)>9.8947394131 and name()=="MCO" and s->get_ID()==0)
// utilities::wait("AAc",value0,value, V0, V,__FILE__,__LINE__);
}
/**Table properties**/
void TableProperty::set_refpointers(Star *s) {
for(int i = 0; i < 4; i++) {
val_ref[i] = s->get_table_pointer_atpos(TabID(), i, 0);
if (val_ref[i]== nullptr){
svlog.critical("One of the interpolating tracks did not found tables for the property " + name(),
__FILE__,__LINE__,sevnstd::sanity_error());
}
}
table_loaded=true;
}
/**Optional table properties**/
void OptionalTableProperty::set_refpointers(Star *s) {
table_loaded=true; //Preset table_loaded to true, if some of the table are not loaded set table_loaded to false below
for(int i = 0; i < 4; i++) {
val_ref[i] = s->get_table_pointer_atpos(TabID(), i, 0);
if (val_ref[i]==nullptr){
V=V0=value=value0=std::nan("");
table_loaded=false;
break;
}
}
}
void OptionalTableProperty::update_derived(Star *s) {
//If acting as derived properties
if (amiderived()){
//Here we want to evolve the derived properties, without setting V0
//1-Save the V0 value
double _V0= V0;
//2-Evolve (depending on the stellar type)
if(!s->amiremnant()) evolve(s);
else if(s->aminakedco()) evolve_nakedco(s);
else if(!s->amiempty()) evolve_remnant(s);
//Notice: do nothing if the star is empty
//3-Restore the V0 value
set_0(_V0);
}
//else use the common update_derived
else{
Property::update_derived(s);
}
}
void SuperficialAbundanceTable::set_refpointers(Star *s) {
//If we don't want to use the tables just set them to false
if (!s->get_svpar_bool("tabuse_Xsup"))
table_loaded=false;
else
OptionalTableProperty::set_refpointers(s);
OptionalTableProperty::set_refpointers(s);
if (!table_loaded and s->get_svpar_bool("tabuse_Xsup"))
svlog.critical("The table "+name()+" has not be loaded, but the option tabuse_envconv is set to true."
"This table is needed if the option is enabled.",__FILE__,__LINE__,sevnstd::sanity_error());
}
void ConvectiveTable::set_refpointers(Star *s) {
//If we don't want to use the tables just set them to false
if (!s->get_svpar_bool("tabuse_envconv"))
table_loaded=false;
else
OptionalTableProperty::set_refpointers(s);
if (!table_loaded and s->get_svpar_bool("tabuse_envconv"))
svlog.critical("The table "+name()+" has not be loaded, but the option tabuse_envconv is set to true."
"This table is needed if the option is enabled.",__FILE__,__LINE__,sevnstd::sanity_error());
}
/**Mass**/
void Mass::set_w(Star *s){
double *Mtrack = s->get_mtrack();
double *Ztrack = s->get_ztrack();
double mzams = s->get_zams();
double Z = s->get_Z();
//set also the default weights
for(int i = 0; i < 4; i+=2) {
wM[i] = (Mtrack[i + 1] - mzams) / (Mtrack[i + 1] - Mtrack[i]);
wM[i+1] = (mzams - Mtrack[i]) / (Mtrack[i + 1] - Mtrack[i]);
svlog.debug("set w for Mass i:"+ utilities::n2s(wM[i], __FILE__,__LINE__) + " i+1:" + utilities::n2s(wM[i+1], __FILE__,__LINE__), __FILE__, __LINE__ );
}
wZ[0] = (Ztrack[1] - Z) / (Ztrack[1] - Ztrack[0]);
wZ[1] = (Z - Ztrack[0]) / (Ztrack[1] - Ztrack[0]);
}
void Mass::set_remnant(Star *s) {
V0 = V;
value0 = value;
V = s->get_staremnant()->get_Mremnant_at_born();
value = V;
}
void Mass::changed_track(_UNUSED Star* s,Star* s_jtrack){
//copy the fake tracks value from s_jtrack
value=s_jtrack->getp_fk(ID);
value0=s_jtrack->getp_fk0(ID);
}
void Mass::update_from_binary(Star* s, const double &DV) {
if (std::isnan(DV) or std::isinf(DV))
svlog.critical("Update from Binary of property " +
name()+" is nan or infinite (Star ID:"+
utilities::n2s(s->get_ID(),__FILE__,__LINE__)+").",
__FILE__,__LINE__);
V+=DV;
//TODO problem: the mass lost in the processes can be larger than the total mass (cumulative)
if (V<=0) {
svlog.warning("Update from Binary for Mass property is using a DV larger than the current Mass. The "
" star will be set to a tiny value. Notice that this is safely taken into account"
" if the update is from binary processes.", __FILE__, __LINE__);
//s->set_empty();
V = utilities::TINY;
}
/*
// This is just a temporary patch, if V_DV<0, we have to put this star empty.
double V_tmp = V+DV;
if (DV>V or std::isnan(DV) or std::isinf(DV))
svlog.critical("Update from Binary of property " +
name()+" is larger than the property value or is nan or infite",__FILE__,__LINE__);
//utilities::wait(DV,__FILE__,__LINE__);
V = V_tmp>0 ? V_tmp : 1e-2*V;
svlog.debug("update_from_binary AFTER " + name() + " "+ std::to_string(V),__FILE__,__LINE__);
//if (s->getp(Phase::ID)==7 and s->getp(Worldtime::ID)>464.30)
//utilities::wait(V,DV,s->getp(dMcumul_binary::ID)-s->getp_0(dMcumul_binary::ID),__FILE__,__LINE__);
*/
};
void Mass::correct_interpolation_errors(_UNUSED Star *s) {
//1-Mass cannot increase in a timestep
if ( (value>value0) && (value0>0.0) ){
svlog.warning("Interpolation Warning: total mass cannot increase in "
"single stellar evolution.\n value0 is "+utilities::n2s(value0,__FILE__,__LINE__)
+ ", value is "+utilities::n2s(value,__FILE__,__LINE__)+
".\n value set to value0 and V to V0.",__FILE__,__LINE__);
set_fk(value0);
set(V0);
utilities::wait();
}
}
void Mass::correct_interpolation_errors_real( Star *s) {
if ( (V>V0) && (V0>0.0) ){
svlog.warning("Interpolation Warning: total mass cannot increase in "
"single stellar evolution.\n V0 is "+utilities::n2s(V0,__FILE__,__LINE__)
+", V is "+utilities::n2s(V,__FILE__,__LINE__)+
".\n V set to V0.",__FILE__,__LINE__);
set(V0);
}
//If I am a naked helium, I cannot go below the minimum HE mass set the first time the star develope a CO core
//unless this was already decreased below this minimum by binary proceses (this is checked with get_0>=get_MHE_min(), if it is false the reset of the mass is not done)
if (!std::isnan(s->get_MHE_min()) and s->aminakedhelium() and get_0()>=s->get_MHE_min()){
set(get() < s->get_MHE_min() ? s->get_MHE_min() : get() );
}
}
/**Inertia**/
void Inertia::set_w(Star *s){
double *Mtrack = s->get_mtrack();
double *Ztrack = s->get_ztrack();
double mzams = s->get_zams();
double Z = s->get_Z();
/*cout << "Linear weights" << endl;
for(int i = 0; i < 4; i+=2) {
wM[i] = (Mtrack[i + 1] - mzams) / (Mtrack[i + 1] - Mtrack[i]);
wM[i+1] = (mzams - Mtrack[i]) / (Mtrack[i + 1] - Mtrack[i]);
cout<<wM[i]<<" "<<wM[i+1]<<" ";
}
cout<<endl;*/
//cout << "Log weights" << endl;
for(int i = 0; i < 4; i+=2) {
wM[i] = (log10(Mtrack[i + 1]) - log10(mzams)) / (log10(Mtrack[i + 1]) - log10(Mtrack[i]));
wM[i+1] = (log10(mzams) - log10(Mtrack[i])) / (log10(Mtrack[i + 1]) - log10(Mtrack[i]));
//cout<<wM[i]<<" "<<wM[i+1]<<endl;
//cout<<" track = "<<Mtrack[i]<<" "<<Mtrack[i+1]<<" "<<mzams<<endl;
}
//cout<<endl;
//utilities::wait("Check");
wZ[0] = (Ztrack[1] - Z) / (Ztrack[1] - Ztrack[0]);
wZ[1] = (Z - Ztrack[0]) / (Ztrack[1] - Ztrack[0]);
}
void Inertia::changed_track(Star *s, Star *s_jtrack) {
if (table_loaded){
// When we change traclk we are using the old mass but the new raidius
// We assume that I propto MR so the new inertia propto Mold Rnew^2
// while the new stars as I propto Mnew Rnew^2, therefore we rescale for a factor Mold/Mnew
//GI 23/03, I found that sometime when the new Inertia is small (close to 1) there could be
//a problem in evolving the Inertia with a mismatch between V,VO and value,value0.
//THis is due to the fact that internally we use a logInertia and when Inertia<1, logInertia<0
//It could happens that sometime DValue is negative but also V0 is negative and as a result
//the inertia will increase instead of decrease.
//In order to avoid this problem, we set V to Vjtrack if Inertia is smaller than 1.5
if (s_jtrack->getp(ID)<1.5){
V=std::log10(s_jtrack->getp(ID));
} else{
double weight_factor=s->getp(Mass::ID)/s_jtrack->getp(Mass::ID);
weight_factor = fabs(weight_factor-1) < 0.1 ? 1. : weight_factor; // If the masses are very similar do not use this factor
V=std::log10(weight_factor*s_jtrack->getp(ID)); //Remember get is 10**V that is stored in log
}
} else {
V=estimate_logInertia(s); //Here we have to estimate again the inertia on s using the updated value of Masses and Radius, already updated.
}
value=log10(s_jtrack->getp_fk(ID));
value0=log10(s_jtrack->getp_fk0(ID));
}
void Inertia::set_remnant(Star *s) {
V0 = V;
value0 = value;
V = log10(s->get_staremnant(Inertia::ID));
value = log10(s->get_staremnant(Inertia::ID));
}
void Inertia::evolve_remnant(Star *s) {
V0 = V;
V = log10(s->get_staremnant(Inertia::ID));
}
void Inertia::evolve_nakedco(Star *s) {
V0 = V;
V = log10(estimate_Inertia_homogeneous_sphere(s));
}
void Inertia::set_refpointers(Star *s) {
//If we don't want to use the tables just set them to false
if (!s->get_svpar_bool("tabuse_inertia")){
table_loaded=false;
//Set the function to be used
if (s->get_svpar_str("inertiamode")=="hsphere")
inertia_func = &Inertia::estimate_Inertia_homogeneous_sphere;
else if (s->get_svpar_str("inertiamode")=="hspherecore")
inertia_func = &Inertia::estimate_Inertia_homogeneous_sphere_wcore;
else if (s->get_svpar_str("inertiamode")=="Hurley")
inertia_func = &Inertia::estimate_Inertia_Hurley;
else if (s->get_svpar_str("inertiamode")=="DeMink"){
inertia_func = &Inertia::estimate_Inertia_DeMink;
}
else
svlog.critical("inertiamode "+s->get_svpar_str("inertiamode")+" not allowed.",__FILE__,__LINE__,sevnstd::params_error());
}
else
OptionalTableProperty::set_refpointers(s);
if (!table_loaded and s->get_svpar_bool("tabuse_inertia"))
svlog.critical("The table "+name()+" has not be loaded, but the option tabuse_inertia is set to true."
"This table is needed if the option is enabled.",__FILE__,__LINE__,sevnstd::sanity_error());
}
void Inertia::correct_interpolation_errors_real(_UNUSED Star *s){
if (get()<=1e-6){
V=-6; //Log10(0.1), set a minimum value
}
}
void Inertia::evolve_without_table(Star *s) {
set_0(std::log10(get()));
set( estimate_logInertia(s) );
//Set V,V0 but also v, v0. This is needed because even if the tables are loaded
//the user can choice do not use them.
synch_v_value_without_table();
}
double Inertia::estimate_logInertia(Star *s) {
return std::log10((*this.*inertia_func)(s));
}
double Inertia::estimate_Inertia_homogeneous_sphere(double Mass,double Outer_radius, double Inner_radius){
if (Inner_radius>Outer_radius)
svlog.critical("In estimate_Inertia_homogeneous_sphere Inner radius ("+
utilities::n2s(Inner_radius,__FILE__,__LINE__)+") is larger than Outer radius ("+utilities::n2s(Outer_radius,__FILE__,__LINE__)+")");
else if (Outer_radius==0 and Inner_radius==0)
return 0.0;
double num=Outer_radius*Outer_radius*Outer_radius*Outer_radius*Outer_radius;
double den = Outer_radius*Outer_radius*Outer_radius;
if (Inner_radius>0){
num = num - Inner_radius*Inner_radius*Inner_radius*Inner_radius*Inner_radius;
den = den - Inner_radius*Inner_radius*Inner_radius;
}
return 0.4*Mass*num/den; //0.4 is 2/5 for a homogeneous sphere
}
double Inertia::estimate_Inertia_homogeneous_sphere(Star *s){
return estimate_Inertia_homogeneous_sphere(s->getp(Mass::ID),s->getp(Radius::ID));
}
double Inertia::estimate_Inertia_homogeneous_sphere_wcore(Star *s){
double inertia_core = estimate_Inertia_homogeneous_sphere(s->Mcore(),s->Rcore());
double inertia_envelope = estimate_Inertia_homogeneous_sphere(s->Menvelope(),s->getp(Radius::ID),s->Rcore());
return inertia_core + inertia_envelope;
}
//TODO This is taken directly from SEVN1, but in bse k2 depends on stellar phase
double Inertia::estimate_Inertia_Hurley(_UNUSED Star *s){
double k2=0.1, k3=0.21;
double ifac = 2.5; //Factor to eliminate the 2/5 factor used inside estimate_Inertia_homogeneous_sphere
double inertia_core = k3*ifac*estimate_Inertia_homogeneous_sphere(s->Mcore(),s->Rcore());
double inertia_envelope = k2*ifac*estimate_Inertia_homogeneous_sphere(s->Menvelope(),s->getp(Radius::ID),s->Rcore());
return inertia_core + inertia_envelope;
}
//TODO This is taken directly from SEVN1, but in DeMink13 it seems that this formalism is valid only for MS
double Inertia::estimate_Inertia_DeMink(Star *s){
const double Radius = s->getp(Radius::ID);
//TODO It is not clear if after a jump we should use mzams-rzams or mzams0-rzmas0
const double mzams = s->get_zams();
const double rzams = s->get_rzams();
double logmz = std::log10(mzams);
double logm = std::log10(s->getp(Mass::ID));
//Estimate k0, Eq. A1
double k = std::min(0.21, std::max(0.09-0.27*logmz, 0.037+0.033*logmz));
//correct for logmz>1/3
if(logmz > 1.3) k-= 0.055*(logmz -1.3)*(logmz -1.3);
//Estimate exponent C, Eq. A3
//TODO In the paper is not clear if in this part we should use logm or logmz, in the old SEVN verison we used logmz, but in a meeting (04/06/21) we decided to use logm
double C;
if (logm<0){
C=-2.5;
}
else if(logm > 0 and logm < 0.2){
C=-2.5+5*logm;
}
else{
C=-1.5;
}
//Estimate final k, Eq. A2
k = (k - 0.025)*std::pow(Radius/rzams, C) + 0.025 * pow(Radius/rzams, -0.1);
return k*s->getp(Mass::ID)*Radius*Radius;
}
/**Luminosity**/
void Luminosity::set_w(Star *s){
double *Mtrack = s->get_mtrack();
double *Ztrack = s->get_ztrack();
double mzams = s->get_zams();
double Z = s->get_Z();
//cout<<"set W for Lumi "<<endl;
for(int i = 0; i < 4; i+=2) {
wM[i] = (log10(Mtrack[i + 1]) - log10(mzams)) / (log10(Mtrack[i + 1]) - log10(Mtrack[i]));
wM[i+1] = (log10(mzams) - log10(Mtrack[i])) / (log10(Mtrack[i + 1]) - log10(Mtrack[i]));
//cout<<wM[i]<<" "<<wM[i+1]<<endl;
//cout<<" track = "<<Mtrack[i]<<" "<<Mtrack[i+1]<<" "<<mzams<<endl;
}
wZ[0] = (Ztrack[1] - Z) / (Ztrack[1] - Ztrack[0]);
wZ[1] = (Z - Ztrack[0]) / (Ztrack[1] - Ztrack[0]);
//exit(1);
}
void Luminosity::changed_track(_UNUSED Star* s,Star* s_jtrack){
///Copy the Luminosity from the jtrack star
V=log10(s_jtrack->getp(ID)); //Remember get is 10**V that is stored in log
//V0=log10(s_jtrack->getp(ID));
value=log10(s_jtrack->getp_fk(ID));
value0=log10(s_jtrack->getp_fk0(ID));
//svlog.pdebug("Radius changed track", get(), get_0(), value, value0,__FILE__,__LINE__);
//utilities::wait();
}
void Luminosity::set_remnant(Star *s) {
V0 = V;
value0 = value;
V = log10(s->get_staremnant(Luminosity::ID));
value = log10(s->get_staremnant(Luminosity::ID));
}
void Luminosity::evolve_remnant(Star *s) {
V0 = V;
V = log10(s->get_staremnant(Luminosity::ID));
}
/**Radius**/
void Radius::evolve(Star *s){
if (s->amifollowingQHE()){
set_0(get());
}
else
Property::evolve(s);
return;
}
void Radius::set_w(Star *s){
double *Mtrack = s->get_mtrack();
double *Ztrack = s->get_ztrack();
double mzams = s->get_zams();
double Z = s->get_Z();
//cout<<"set W for mass "<<endl;
for(int i = 0; i < 4; i+=2) {
wM[i] = (log10(Mtrack[i + 1]) - log10(mzams)) / (log10(Mtrack[i + 1]) - log10(Mtrack[i]));
wM[i+1] = (log10(mzams) - log10(Mtrack[i])) / (log10(Mtrack[i + 1]) - log10(Mtrack[i]));
}
wZ[0] = (Ztrack[1] - Z) / (Ztrack[1] - Ztrack[0]);
wZ[1] = (Z - Ztrack[0]) / (Ztrack[1] - Ztrack[0]);
}
void Radius::changed_track(_UNUSED Star* s,Star* s_jtrack){
//If we are followng the QHE does not change Radius
if (s->amifollowingQHE())
return;
V=log10(s_jtrack->getp(ID)); //Remember get is 10**V that is stored in log
//V0=log10(s_jtrack->getp(ID));
value=log10(s_jtrack->getp_fk(ID));
value0=log10(s_jtrack->getp_fk0(ID));
//svlog.pdebug("Radius changed track", get(), get_0(), value, value0,__FILE__,__LINE__);
//utilities::wait();
}
void Radius::set_remnant(Star *s) {
V0 = V;
value0 = value;
V = log10(s->get_staremnant(Radius::ID));
value = log10(s->get_staremnant(Radius::ID));
}
void Radius::evolve_remnant(Star *s) {
V0 = V;
V = log10(s->get_staremnant(Radius::ID));
}
/**Phase**/
//this property evolves outside the main loop
void Phase::special_evolve(Star *s){
const double *tphase = s->get_tphase();
//cout<<" OLD phase = "<<get()<<" subphase = "<<get_fk()<<endl;
set_0(get());
set_0_fk(get_0_fk());
set(-1);
double localtime = s->getp(Localtime::ID);
//TODO for WR stars maybe we should refer to different phases (same for pureHE tracks)
//if(amiwr()) then use the tphaseWR vector coupled with the PhasesWR enum
svlog.pdebug("Local time in Phase evolve ",localtime,V0,std::setprecision(20),__FILE__,__LINE__);
svlog.pdebug(std::setprecision(20),"Tphase "+std::to_string(tphase[0]),std::setprecision(20),__FILE__,__LINE__);
svlog.pdebug("Check "+std::to_string(localtime < tphase[0]),std::setprecision(20),__FILE__,__LINE__);
svlog.pdebug(std::setprecision(20),"Local time in Phase evolve ",localtime,
"Tphase "+std::to_string(tphase[0]),"Check "+std::to_string(localtime < tphase[0]),std::setprecision(20),__FILE__,__LINE__);
if(localtime < tphase[0])
svlog.critical("Initial time is likely negative (Star ID " + utilities::n2s(s->get_ID(),__FILE__,__LINE__) + ")",__FILE__,__LINE__);
for(int i = 0; i < Nphases-1; i++) {
svlog.pdebug(std::setprecision(20),"LTRRRRR",localtime,tphase[i],tphase[i+1],s->get_zams(),__FILE__,__LINE__);
if (localtime < tphase[i + 1] && localtime >= tphase[i])
set(i);
}
//TODO the next two line are for debug remove them
//if (s->get_ID()==0 and s->getp(Worldtime::ID)!=0)
// std::cout<<std::setprecision(20)<<s->getp(Worldtime::ID)<<" "<<localtime<<" "<<tphase[Nphases-1]<<std::endl;
if(localtime >= tphase[Nphases-1]){
//set(Nphases-1);
set(Lookup::Phases::Remnant);
}
if(get() == -1)
svlog.critical("Cannot initialize the phase of the star", __FILE__, __LINE__);
if(tphase[(int)get()] == -1)
svlog.critical("Cannot set the phase of the star, tphase not set. Interpolating track with different phases? Check in the look-up tables",
__FILE__, __LINE__);
}
void Phase::changed_track(_UNUSED Star *s, Star *s_jtrack){
V=s_jtrack->getp(Phase::ID);
}
//Notice here we don't do nothing because as for Localtime and Worldtime this property has been already evolved in the special evolve
//void Phase::set_remnant(Star *s) {
//return;
//Notice here we don't do nothing because as for Localtime and Worldtime this property has been already evolved in the special evolve
//V0 = V; Notice here we do not use
//value0 = value;
//V = Lookup::Phases::Remnant;
//value = Lookup::Phases::Remnant;
//}
/**Localtime**/
void Localtime::special_evolve(Star *s){
svlog.debug("Old Localtime T_0= "+utilities::n2s(get_0(),__FILE__,__LINE__),__FILE__,__LINE__);
svlog.debug("Old Localtime T= "+utilities::n2s(get(),__FILE__,__LINE__),__FILE__,__LINE__);
set_0(get());
set(get() + s->getp(Timestep::ID));
svlog.debug("New Localtime T_0= "+utilities::n2s(get_0(),__FILE__,__LINE__),__FILE__,__LINE__);
svlog.debug("New Localtime T= "+utilities::n2s(get(),__FILE__,__LINE__),__FILE__,__LINE__);
}
void Localtime::changed_track(_UNUSED Star* s,Star* s_jtrack){
V=V0=value=value0=s_jtrack->getp(ID);
}
/**Temperature**/
void Temperature::evolve(Star *s){
set_0(get());
double Teff4=s->getp(Luminosity::ID)/(4*M_PI*s->getp(Radius::ID)*s->getp(Radius::ID)*utilities::Sigma_StefBoltz);
set(pow(Teff4,0.25));
}
void Temperature::changed_track(_UNUSED Star *s, Star *s_jtrack) {
//V=s_jtrack->getp(ID);
//V0=s_jtrack->getp(ID);
V = s_jtrack->getp(Luminosity::ID)/(4*M_PI*s_jtrack->getp(Radius::ID)*s_jtrack->getp(Radius::ID)*utilities::Sigma_StefBoltz);
value=s_jtrack->getp_fk(ID);
value0=s_jtrack->getp_fk0(ID);
}
/*Mass objects*/
double Mass_obejct::get_Vlast(const Star *s) const {
double last_values [4]; //last values of the 4 interpolating track
for(int i = 0; i < 4; i++){
last_values[i] = s->get_last_fromtable((Lookup::Tables)TabID(),i);
}
double val_zlow = last_values[0]*wM[0] + last_values[1]*wM[1];
double val_zhigh = last_values[2]*wM[2] + last_values[3]*wM[3];
///Find the final interpolated value, v=Z1*v1 + Z2*v2
return wZ[0]*val_zlow + wZ[1]*val_zhigh;
}
/**MCO**/
void MCO::evolve(Star *s){
if(s->getp(Phase::ID) >= TerminalHecoreBurning)
Property::evolve(s);
else
return;
}
void MCO::set_w(Star *s){
double *Mtrack = s->get_mtrack();
double *Ztrack = s->get_ztrack();
double mzams = s->get_zams();
double Z = s->get_Z();
//cout<<"set W for mass "<<endl;
//set also the default weights
for(int i = 0; i < 4; i+=2) {
wM[i] = (Mtrack[i + 1] - mzams) / (Mtrack[i + 1] - Mtrack[i]);
wM[i+1] = (mzams - Mtrack[i]) / (Mtrack[i + 1] - Mtrack[i]);
}
wZ[0] = (Ztrack[1] - Z) / (Ztrack[1] - Ztrack[0]);
wZ[1] = (Z - Ztrack[0]) / (Ztrack[1] - Ztrack[0]);
}
void MCO::correct_interpolation_errors_real(_UNUSED Star *s) {
double v = get();
double v0 = get_0();
///1-CO cannot decrease
set((v < v0) ? v0 : v); //CO mass cannot decrease
//2-CO cannot grow more than maximum CO (if set)
//unless some binary processes give to the star more MCO than the maximum.
//This condition is checked looking at v0 (that is the last value after a complete bse step, is the star is a binary).
//If this value is larger tha maximum CO, the reset to the maximum CO is not done (see next if).
if (!std::isnan(s->get_MCO_max()) and v0<=s->get_MCO_max()){
set(v > s->get_MCO_max() ? s->get_MCO_max() : v);
}
//If the MCO was already decreased above the maximumjust set it to this value (the one after the last step of BSE)
//do not allow to become larger due to SSE
else if(!std::isnan(s->get_MCO_max())){
set(v > s->get_MCO_max() ? v0 : v);
}
///3-MCO cannot be larger than MHE or total Mass
//If MCO is larger than the Mass in the current timestep there was a point in which the decreasing Mass
//and the increasing MCO cross each other. Since the interpolation is linear, we can easily find this point
//Then we set Mass=MHE=MCO=Mcross.
//TODO In order to be totally consistent we shoud trigger a repeat setting the newtimestep as the one to reach the crossig point.
if (get()>s->getp(Mass::ID)){
double m_mass, m_mco, b_mass, b_mco;
utilities::find_line(0,s->getp(Timestep::ID), s->getp_0(Mass::ID),s->getp(Mass::ID),m_mass,b_mass);
utilities::find_line(0,s->getp(Timestep::ID), get_0(),get(),m_mco,b_mco);
double t_match = (b_mco-b_mass)/(m_mass-m_mco);
double M_match = m_mass*t_match+b_mass;
set(M_match);
s->copy_property_from(Mass::ID,MCO::ID);
//The following is a trick to don't have exactly Mass=MHE (this will force the radius to be equal with a sequent likely repeat due to large Radius variation)
M_match=M_match-std::min(1e-5,0.1*s->get_svpar_num("ev_naked_tshold"));
set(M_match);
s->copy_property_from(MHE::ID,MCO::ID);
//The following is a trick to don't have exactly MCO=MHE (this will force the radius to be equal with a sequent likely repeat due to large Radius variation)
M_match=M_match-std::min(1e-5,0.1*s->get_svpar_num("ev_naked_tshold"));
set(M_match);
}
else if(get()>s->getp(MHE::ID)){
double m_mhe, m_mco, b_mhe, b_mco;
utilities::find_line(0,s->getp(Timestep::ID), s->getp_0(MHE::ID),s->getp(MHE::ID),m_mhe,b_mhe);
utilities::find_line(0,s->getp(Timestep::ID), get_0(),get(),m_mco,b_mco);
double t_match = (b_mco-b_mhe)/(m_mhe-m_mco);
double M_match = m_mhe*t_match+b_mhe;
set(M_match);
s->copy_property_from(MHE::ID,MCO::ID);
set(M_match-std::min(1e-5,0.1*s->get_svpar_num("ev_naked_tshold")));
}
}
void MCO::changed_track(_UNUSED Star *s, Star *s_jtrack) {
value=s_jtrack->getp_fk(ID);
value0=s_jtrack->getp_fk0(ID);
//TODO THis is just a patch to avoid the problem in which we wrongly have an overmassive or undermassive core
//if (s->getp(Phase::ID) == TerminalHecoreBurning and V<1e-5)
// V= s_jtrack->getp(ID)>0.0 ? s_jtrack->getp(ID) : 1e-7;
}
/**MHE**/
void MHE::evolve(Star *s){
//Check if it is naked helium
//PureHe tracks from Parsec have Mtot and R that are slighly different wrt MHE and RHE, this becasue there is
//an Helium atmosphere. In order to simplify the pureHE star we force the evolution to just follow the total Mass evolution
if (s->aminakedhelium()){
set_0(get());
set_0_fk(get_0_fk());
set_fk(s->getp_fk(Mass::ID));
set(s->getp(Mass::ID));
return;
}
else if (s->getp(Phase::ID) >= TerminalMainSequence)
Property::evolve(s);
else
return;
//cout<<" NEW MHE = "<<get()<<endl;
}
void MHE::set_w(Star *s){
double *Mtrack = s->get_mtrack();
double *Ztrack = s->get_ztrack();
double mzams = s->get_zams();
double Z = s->get_Z();
//cout<<"set W for mass "<<endl;
//set also the default weights
for(int i = 0; i < 4; i+=2) {
wM[i] = (Mtrack[i + 1] - mzams) / (Mtrack[i + 1] - Mtrack[i]);
wM[i+1] = (mzams - Mtrack[i]) / (Mtrack[i + 1] - Mtrack[i]);
}
wZ[0] = (Ztrack[1] - Z) / (Ztrack[1] - Ztrack[0]);
wZ[1] = (Z - Ztrack[0]) / (Ztrack[1] - Ztrack[0]);
}
void MHE::correct_interpolation_errors_real(Star *s){
//I cannot go below the minimum HE mass set the first time the star develope a CO core
//unless this was already decreased below this minimum by binary proceses (this is checked with get_0>=get_MHE_min(), if it is false the reset of the mass is not done)
//see next else if
if (!std::isnan(s->get_MHE_min()) and get_0()>=s->get_MHE_min()){
set(get() < s->get_MHE_min() ? s->get_MHE_min() : get() );
}
//TODO Notice that using it we essentially disable the pureHE winds if the star that becomes a pureHE start with a MHE smaller than the MHE_min
//If the MHE was already decreased below the minimum by the binary process, just set it to this value (the one after the last step of BSE)
//do not allow to become even smaller
else if (!std::isnan(s->get_MHE_min())){
set(get() < s->get_MHE_min() ? get_0() : get() );
}
///Now compare with Mass
//If MHE is larger than the Mass in the current timestep there was a point in which the decreasing Mass
//and the increasing or decreasing MHE cross each other. Since the interpolation is linear, we can easily find this point
//Then we set Mass=MHE=Mcross.
//TODO In order to be totally consistent we shoud triggere a repeat setting the newtimestep as the one to reach the crossig point.
if (get()>s->getp(Mass::ID)){
double m_mass, m_mhe, b_mass, b_mhe;
utilities::find_line(0,s->getp(Timestep::ID), s->getp_0(Mass::ID),s->getp(Mass::ID),m_mass,b_mass);
utilities::find_line(0,s->getp(Timestep::ID), get_0(),get(),m_mhe,b_mhe);
double t_match = (b_mhe-b_mass)/(m_mass-m_mhe);
double M_match = m_mass*t_match+b_mass;
set(M_match);
s->copy_property_from(Mass::ID,MHE::ID);
//Set real M_match
//The following is a trick to don't have exactly Mass=MHE (this will force the radius to be equal with a sequent likely repeat due to large Radius variation)
set(M_match-std::min(1e-5,0.1*s->get_svpar_num("ev_naked_tshold")));
}
}
void MHE::changed_track(Star *s, Star *s_jtrack) {
//If Naked Helium, the MHE has to follow the total mass
if (s->aminakedhelium() )
V=s->getp(Mass::ID);
//TODO THis is just a patch to avoid the problem in which we wrongly have an overmassive or undermassive core
//else if (s->getp(Phase::ID) == TerminalMainSequence and V<1e-5)
// V=s_jtrack->getp(ID)>0.0 ? s_jtrack->getp(ID) : 1e-7;
value=s_jtrack->getp_fk(ID);
value0=s_jtrack->getp_fk0(ID);
}
/**RHE**/
void RHE::evolve(Star *s){
//First think, check if it is naked helium. In this case RHE is just equal to the total Radius
if (s->aminakedhelium()){
set_0(get());
set_0_fk(get_0_fk());
set_fk(s->getp_fk(Radius::ID));
set(s->getp(Radius::ID));
return;
}
//second check if He core actually exists and table are loaded(Phase larger than Terminal Main Sequence)
else if(s->getp(Phase::ID) >= TerminalMainSequence and table_loaded){
Property::evolve(s);
}
//third if He core actually exists and but table are not loaded evolve using functional form
else if(s->getp(Phase::ID) >= TerminalMainSequence and !table_loaded){
evolve_without_table(s);
}
//fourth in all the other cases do nothing
else{
return;
}
}
void RHE::set_w(Star *s){
double *Mtrack = s->get_mtrack();
double *Ztrack = s->get_ztrack();
double mzams = s->get_zams();
double Z = s->get_Z();
//set also the default weights
for(int i = 0; i < 4; i+=2) {
wM[i] = (Mtrack[i + 1] - mzams) / (Mtrack[i + 1] - Mtrack[i]);
wM[i+1] = (mzams - Mtrack[i]) / (Mtrack[i + 1] - Mtrack[i]);
}
wZ[0] = (Ztrack[1] - Z) / (Ztrack[1] - Ztrack[0]);
wZ[1] = (Z - Ztrack[0]) / (Ztrack[1] - Ztrack[0]);
}
void RHE::correct_interpolation_errors_real(Star *s){
if (s->getp(MHE::ID)<s->getp(Mass::ID)){
//RHE cannot be larger than R, for the real star
set(get() > 0.9999*s->getp(Radius::ID) ? 0.9999*s->getp(Radius::ID) : get());
}
else if (s->getp(MHE::ID)==s->getp(Mass::ID) and !s->aminakedhelium()){
//This is (will become) a naked Helium set the Radius to the RHE
s->copy_property_from(Radius::ID,RHE::ID);
}
}
void RHE::changed_track(Star *s, Star *s_jtrack) {
//If Naked Helium, the RHE has to follow the Radius
//TODO Myabe it is better to check if s_jtrack is nakedhelium otherwise the first time the star is transformed to a pureHe it is still not a pureHE so this check will be false
if (s->aminakedhelium())
V=s->getp(Radius::ID);
else if (table_loaded)
V=s_jtrack->getp(ID);
else
V=estimate_Rcore(s); //Use the updated MHE mass
value=s_jtrack->getp_fk(ID);
value0=s_jtrack->getp_fk0(ID);
}
void RHE::evolve_without_table(Star *s){
set_0(get());
set( estimate_Rcore(s) );
//Set V,V0 but also v, v0. This is needed because even if the tables are loaded
//the user can choice to not use them.
synch_v_value_without_table();
return;
}
void RHE::set_refpointers(Star *s) {
//If we don't want to use the tables just set them to false
if (!s->get_svpar_bool("tabuse_rhe"))
table_loaded=false;
else
OptionalTableProperty::set_refpointers(s);
if (!table_loaded and s->get_svpar_bool("tabuse_rhe"))
svlog.critical("The table "+name()+" has not be loaded, but the option tabuse_rhe is set to true."
"This table is needed if the option is enabled.",__FILE__,__LINE__,sevnstd::sanity_error());
}
double RHE::estimate_Rcore(Star *s) {
double best_scale_factor=0.10746657; //RHE at MHE=1 Msun from a fit done on the SEVNtracks_G tables (see Wiki)
double Rcore_from_func = CoreRadius::estimate_Rcore(s->getp(MHE::ID),best_scale_factor);
//Do not allow Rcore larger than total Radius
return Rcore_from_func >= s->getp(Radius::ID) ? 0.99*s->getp(Radius::ID) : Rcore_from_func;
}
/**RCO**/
void RCO::evolve(Star *s){
if(s->getp(Phase::ID) >= TerminalHecoreBurning and table_loaded)
Property::evolve(s);
else if(s->getp(Phase::ID) >= TerminalHecoreBurning and !table_loaded)
evolve_without_table(s);
else
return;
}
void RCO::set_w(Star *s){
double *Mtrack = s->get_mtrack();
double *Ztrack = s->get_ztrack();
double mzams = s->get_zams();
double Z = s->get_Z();
//set also the default weights
for(int i = 0; i < 4; i+=2) {
wM[i] = (Mtrack[i + 1] - mzams) / (Mtrack[i + 1] - Mtrack[i]);
wM[i+1] = (mzams - Mtrack[i]) / (Mtrack[i + 1] - Mtrack[i]);
}
wZ[0] = (Ztrack[1] - Z) / (Ztrack[1] - Ztrack[0]);
wZ[1] = (Z - Ztrack[0]) / (Ztrack[1] - Ztrack[0]);
}
void RCO::correct_interpolation_errors_real(Star *s){
//RCO cannot be larger than RHE, for the real star
if (get()>0.9999*s->getp(Radius::ID))
set(0.9999*s->getp(Radius::ID));
else if (get()>s->getp(RHE::ID))
set(0.9999*s->getp(RHE::ID));
//TODO Notice that setting the radius to the RCO radius in this phase we prevent possible RLOs (the star is set to naked CO only at the end)
//If MCO==MHE the radii have to be the same, we set the radius to the radius of the CO (if the star is a pureHE the Radius is set to RCO too)
//In any case this star will become a nakedCO star
if (s->getp(MCO::ID)==s->getp(MHE::ID)){
s->copy_property_from(RHE::ID,RCO::ID);
if (s->aminakedhelium()) s->copy_property_from(Radius::ID,RCO::ID);
}
//Sometimes During the initial stage of the TerminalHecore, CCO is 0, in that case we force it to be not zero so that it is consistent we
//other section of the code
//if (s->getp(Phase::ID) == TerminalHecoreBurning and V==0.0)
// V=1e-7;
}
void RCO::changed_track(_UNUSED Star *s, Star *s_jtrack) {
if (table_loaded)
V=s_jtrack->getp(ID);
else
V=estimate_Rcore(s); //Use the updated MHE mass
value=s_jtrack->getp_fk(ID);
value0=s_jtrack->getp_fk0(ID);
}
void RCO::set_refpointers(Star *s) {
//If we don't want to use the tables just set them to false
if (!s->get_svpar_bool("tabuse_rco"))
table_loaded=false;
else
OptionalTableProperty::set_refpointers(s);
if (!table_loaded and s->get_svpar_bool("tabuse_rco"))
svlog.critical("The table "+name()+" has not be loaded, but the option tabuse_rco is set to true."
"This table is needed if the option is enabled.",__FILE__,__LINE__,sevnstd::sanity_error());
}
void RCO::evolve_without_table(Star *s){
set_0(get());
set( estimate_Rcore(s) );
//Set V,V0 but also v, v0. This is needed because even if the tables are loaded
//the user can choice to not use them.
synch_v_value_without_table();
return;
}
double RCO::estimate_Rcore(Star *s) {
double best_scale_factor=0.04149729; //RCO at MCO=1 Msun from a fit done on the SEVNtracks_G tables (see Wiki)
double Rcore_from_func = CoreRadius::estimate_Rcore(s->getp(MCO::ID),best_scale_factor);
//Do not allow Rcore larger than the RHE radius
return Rcore_from_func >= s->getp(RHE::ID) ? 0.99*s->getp(RHE::ID) : Rcore_from_func;
}
/**Bmag**/
void Bmag::evolve(_UNUSED Star *s) {
set_0(get());
}
void Bmag::set_remnant(Star *s) {
V0 = V;
value0 = value;
V = s->get_staremnant(Bmag::ID);
value = s->get_staremnant(Bmag::ID);
}
void Bmag::evolve_remnant(Star *s) {
set_0(get());
set(s->get_staremnant(Bmag::ID));
}
/**OmegaRem**/
void OmegaRem::set_remnant(Star *s) {
V0 = V;
value0 = value;
V = s->get_staremnant(OmegaRem::ID);
value = s->get_staremnant(OmegaRem::ID);
}
void OmegaRem::evolve_remnant(Star *s) {
set_0(get());
set(s->get_staremnant(OmegaRem::ID));
}
/**Rs**/
void Rs::evolve( Star *s){
set_0(get());
set(utilities::R_Schwarzschild(s->getp(Mass::ID)));
//set(rs);
}
/**Spin**/
void Spin::evolve(Star *s) {
set_0(get());
set(Spin_from_OmegaSpin(s->getp(OmegaSpin::ID),s->getp(Mass::ID),s->getp(Radius::ID)));
}
double Spin::Spin_from_OmegaSpin(double OmegaSpin, double Mass, double Radius) {
return OmegaSpin/utilities::omega_crit(Mass,Radius);
}
/**Worldtime**/
void Worldtime::special_evolve(Star *s){
svlog.debug("Old Worldtime T_0= "+utilities::n2s(get_0(),__FILE__,__LINE__),__FILE__,__LINE__);
svlog.debug("Old Worldtime T= "+utilities::n2s(get(),__FILE__,__LINE__),__FILE__,__LINE__);
set_0(get());
set(get() + s->getp(Timestep::ID));
svlog.debug("New Worldtime T_0= "+utilities::n2s(get_0(),__FILE__,__LINE__),__FILE__,__LINE__);
svlog.debug("New Worldtime T= "+utilities::n2s(get(),__FILE__,__LINE__),__FILE__,__LINE__);
}
/**NextOutput**/
void NextOutput::special_evolve(Star *s){
set_0(get());
//Condition to avoid that the get() + s remains always lower than the current worldtime.
get() + s->get_dtout()>s->getp(Worldtime::ID) ? set(get() + s->get_dtout()) : set(s->getp(Worldtime::ID) + s->get_dtout());
}
/**Timestep**/
void Timestep::evolve(Star *s){
set_0(get());
double max_variation = s->get_svpar_num("ts_maximum_variation");
//bool dprint=s->getp(Worldtime::ID)>1.686631 and s->get_ID()==0;
bool dprint=false;
s->repeatstep = false; //Reset flag repeatstep
///Check and repeat
//Perform check and repeat only if dt is not equal to the minimum timestep
if ( get_0()!=s->get_svpar_num("ts_min_dt") ){
//check if total mass has varied a lot, despite the timestep control
if(check_repeat(s, s->getp_0(Mass::ID), s->getp(Mass::ID), s->getp(dMdt::ID), 0.0)){
//if (s->get_ID()==0) std::cout<<" Mass repeat "<<__FILE__<<" "<<__LINE__<<std::endl;
if (dprint)
utilities::wait("Mass repeat",s->get_ID(),s->getp_0(Mass::ID), s->getp(Mass::ID), s->getp(Phase::ID), s->getp(Localtime::ID), s->getp_0(MHE::ID), s->getp(MHE::ID),s->hestart(),__FILE__,__LINE__);
handle_star_check_repeat(s);
return;
}
//check if helium has varied a lot, despiting the timestep control
//If the star is a pureHE, disable the MHE check
if (!s->aminakedhelium()){
if(check_repeat(s, s->getp_0(MHE::ID), s->getp(MHE::ID), s->getp(dMHEdt::ID), s->hestart())){
//if (s->get_ID()==0) std::cout<<" MHE repeat "<<__FILE__<<" "<<__LINE__<<std::endl;
if (dprint)
utilities::wait("MHE repeat",s->get_ID(), s->getp(Phase::ID), s->getp(Localtime::ID), s->getp_0(MHE::ID), s->getp(MHE::ID),s->hestart(),__FILE__,__LINE__);
handle_star_check_repeat(s);
return;
}
}
//check if carbon-oxygen has varied a lot, despiting the timestep control
if(check_repeat(s, s->getp_0(MCO::ID), s->getp(MCO::ID), s->getp(dMCOdt::ID), s->costart())){
//if (s->get_ID()==0) std::cout<<" MCO repeat "<<__FILE__<<" "<<__LINE__<<std::endl;
if (dprint)
utilities::wait("MCO repeat", s->getp(Timestep::ID),__FILE__,__LINE__);
handle_star_check_repeat(s);
return;
}
//check if Radius has varied a lot, despiting the timestep control
if(check_repeat(s, s->getp_0(Radius::ID), s->getp(Radius::ID), s->getp(dRdt::ID), 0.0)){
//if (s->get_ID()==0) std::cout<<" Radius repeat "<<__FILE__<<" "<<__LINE__<<std::endl;
if (dprint){
utilities::wait("R repeat",s->getp(Phase::ID),s->getp_0(Radius::ID),s->getp(Radius::ID),s->getp(dRdt::ID),__FILE__,__LINE__);
utilities::wait("info",s->getp(Mass::ID),s->getp(MHE::ID),s->getp(MCO::ID),s->aminakedco(),s->amiremnant(),__FILE__,__LINE__);
}
handle_star_check_repeat(s);
return;
}
//Check OmegaSpin
double dSpindt = (s->getp(OmegaSpin::ID)-s->getp_0(OmegaSpin::ID))/s->getp(Timestep::ID);
//Make this check only of if allowed by the runtime option (ts_check_spin) and the velocity is significant (> 1 km/s)
bool dSpin_check =s->get_svpar_bool("ts_check_spin") and s->getp_0(OmegaSpin::ID)>1.;
if( dSpin_check and check_repeat(s,s->getp_0(OmegaSpin::ID),s->getp(OmegaSpin::ID),dSpindt,0.0)){
handle_star_check_repeat(s);
return;
}
}
double time_to_end=s->get_tf() - s->getp(Worldtime::ID);
if (time_to_end==0)
return; //THis is the last step not need to estimate a new timestep.
double new_timestep = std::min(s->get_dtmax(), time_to_end);
svlog.debug("Max timestep"+std::to_string(new_timestep));
if(dprint)
utilities::wait("before", s->getp_0(Mass::ID), s->getp(Mass::ID),s->get_ID(),new_timestep, s->getp(Worldtime::ID),s->get_dtmax(),s->get_tf() - s->getp(Worldtime::ID),s->getp(Mass::ID),__FILE__,__LINE__);
//determine next dt by imposing a maximum relative variation of stellar mass and radius
if(fabs(s->getp(dMdt::ID)) != 0.0) {
new_timestep = std::min(new_timestep,
max_variation * (s->getp(Mass::ID) / fabs(s->getp(dMdt::ID))));
//std::cout<<std::scientific<<s->getp(Mass::ID)<<std::endl;
//std::cout<<std::scientific<<s->getp(MHE::ID)<<std::endl;
//svlog.pdebug("Entrato",__FILE__,__LINE__);
if(dprint)
utilities::wait("dMdt", new_timestep, s->getp(Worldtime::ID),s->getp(dMdt::ID),max_variation * (s->getp(Mass::ID) / fabs(s->getp(dMdt::ID))),__FILE__,__LINE__);
}
svlog.debug("timestep dM/dt end"+std::to_string(new_timestep)+" " + std::to_string(s->getp(Mass::ID))+ " " + std::to_string(s->getp(dMdt::ID)));
if(fabs(s->getp(dRdt::ID)) != 0.0)
new_timestep = std::min(new_timestep, max_variation*( s->getp(Radius::ID)/fabs(s->getp(dRdt::ID)) ) );
if(dprint)
utilities::wait("dRdt", new_timestep, s->getp(Radius::ID),s->getp_0(Radius::ID),s->getp(Worldtime::ID),s->getp(dRdt::ID), max_variation*( s->getp(Radius::ID)/fabs(s->getp(dRdt::ID)) ),__FILE__,__LINE__);
svlog.debug("timestep dR/dt end "+std::to_string(new_timestep)+" " + std::to_string(s->getp(dRdt::ID))+ " " + std::to_string(s->getp(dRdt::ID)));
//Disable if the star is a Naked Helium
if( (s->getp(MHE::ID) != 0.0 or s->getp_0(MHE::ID) != 0.0) and !s->aminakedhelium()) {
if (s->getp_0(MHE::ID) > 4.0 && s->getp(MHE::ID) > 4.0) {
new_timestep = std::min(new_timestep,
max_variation * (s->getp(MHE::ID) / fabs(s->getp(dMHEdt::ID))));
} else {//fixed maximum variation under 2.0 Msun (avoid small time steps just because Mhe or MCO are small)
double new_dt = 0.2 / s->getp(Timestep::ID);
new_timestep = std::min(new_timestep, new_dt);
}
}
if(dprint)
utilities::wait("dMHEdt", new_timestep, s->getp(Worldtime::ID),s->getp(dMHEdt::ID),max_variation * (s->getp(MHE::ID) / fabs(s->getp(dMHEdt::ID))),__FILE__,__LINE__);
svlog.debug("timestep dMhe/dt end "+std::to_string(new_timestep)+" " + std::to_string(s->getp(MHE::ID))+ " " + std::to_string(s->getp(dMHEdt::ID)));
if(s->getp(MCO::ID) != 0.0 || s->getp_0(MCO::ID) != 0.0) {
if (s->getp_0(MCO::ID) > 4.0 && s->getp(MCO::ID) > 4.0) {
new_timestep = std::min(new_timestep,
max_variation * (s->getp(MCO::ID) / fabs(s->getp(dMCOdt::ID))));
} else {//fixed maximum variation under 2.0Msun (avoid small time steps just because Mhe or MCO are small)
double new_dt = 0.2 / s->getp(Timestep::ID);
new_timestep = std::min(new_timestep, new_dt);
}
}
//svlog.pinfo("New timestep end",new_timestep,__FILE__,__LINE__);
if(dprint)
utilities::wait("dMCO", new_timestep, s->getp(Worldtime::ID),__FILE__,__LINE__);
///Predict timestep trying to avoid the Mass to become smaller than the MHE
//Notice if the Masses are already within the ev_naked_tshold we skip this.
//We need the skip to a void a sort of "Achille s paradox" in which we continue to infinitely reduce the timestep to avoid that the Mass becomes larger than MHE
//In practie, here we reduce the timestep to slowly approach the moment in which the star will becomes pureHE or nakedCO
//Here we start from:
// M = M0 + dMdt * DT
// m = m0 + dmdt *DT
// where for example M=Mass and m=MHE
// now we want a DT so that m=M, so
// m0 + dmdt *DT = M0 + dMdt * DT
// DT (dmdt - dMdt ) = M0-m0
// so DT = (M0-m0) / (dmdt - dMdt )
// hence we set DT_new = 0.5* (M0-m0) / (dmdt - dMdt )
bool check_almost_naked_Hstar= !s->aminakedhelium() and s->getp(Mass::ID)>s->getp(MHE::ID)+std::max(1e-6,s->get_svpar_num("ev_naked_tshold"));
bool check_almost_naked_HEstar= s->aminakedhelium() and s->getp(Mass::ID)>s->getp(MCO::ID)+std::max(1e-6,s->get_svpar_num("ev_naked_tshold"));
if (check_almost_naked_Hstar and s->getp(MHE::ID)>=0.9*s->getp(Mass::ID)){
double new_dt= 0.5*( s->getp(Mass::ID)-s->getp(MHE::ID) ) / (s->getp(dMHEdt::ID)-s->getp(dMdt::ID));
if (new_dt>0) new_timestep = std::min(new_timestep,new_dt);
}
if (check_almost_naked_HEstar and s->getp(MCO::ID)>=0.9*s->getp(Mass::ID)){
double new_dt= 0.5*( s->getp(Mass::ID)-s->getp(MCO::ID) ) / (s->getp(dMCOdt::ID)-s->getp(dMdt::ID));
if (new_dt>0) new_timestep = std::min(new_timestep,new_dt);
}
/*****************************/
///Spins
double dOSpin = fabs(s->getp(OmegaSpin::ID) - s->getp_0(OmegaSpin::ID))/s->getp(Timestep::ID);
//Make this check only of if allowed by the runtime option (ts_check_spin) and the velocity is significant (> 1 km/s)
bool dSpin_check =s->get_svpar_bool("ts_check_spin") and s->getp_0(OmegaSpin::ID)>1. and dOSpin != 0.0;
//Notice: Make this check just when OmegaSpin is significant (in order to avoi a large number of timesteps with OmegaSpin close to 0)
if(dSpin_check){
//std::cout<<dSpin<<" "<<s->getp(Spin::ID)<<" "<<s->getp_0(Spin::ID)<<std::endl;
new_timestep = std::min(new_timestep, max_variation*( s->getp(OmegaSpin::ID)/dOSpin ) );
}
//reduce the time-step at every critical passage (e.g. formation of the He core, CO core, remnant, ...)
//TODO maybe we should take into account also the transformation into a WR star??
double referencetime = 0.0;
if(s->getp(Localtime::ID)+new_timestep > s->get_next_tphase()) {
referencetime = s->get_next_tphase();
}
svlog.pdebug("referencetime",std::setprecision(20),referencetime,new_timestep,s->getp(Localtime::ID),s->get_next_tphase());
if(dprint)
utilities::wait("referencetime", std::setprecision(20),referencetime,new_timestep,s->getp(Localtime::ID),s->get_next_tphase(),__FILE__,__LINE__);
//TODO the factor 1e10 is needed to follows the last part of the evolution.
//TODO It seems to work better than just using a percentange, but it is maybe worth checking at a certain point
if(referencetime != 0.0) {
if (s->changedphase) {
//cout << "A timestep/localtime = " << new_timestep << " " << referencetime << " " << s->getp(Localtime::ID) << endl;
//utilities::hardwait();
new_timestep = std::min(new_timestep, (referencetime - s->getp(Localtime::ID)+1e-10));
s->changedphase = false;
svlog.pdebug("A New timestep end",new_timestep,referencetime,s->getp(Localtime::ID),s->getp(Mass::ID),__FILE__,__LINE__);
if (dprint)
utilities::wait("A New timestep end",new_timestep,referencetime,s->getp(Localtime::ID),s->getp(Mass::ID),__FILE__,__LINE__);
} else {
s->changedphase = true;
//cout << " changed phase true" << endl;
//cout << "P timestep/localtime = " << new_timestep << " " << referencetime << " " << s->getp(Localtime::ID) << endl;
new_timestep = std::min(new_timestep, (referencetime - s->getp(Localtime::ID)-1e-10));
if (new_timestep<0) new_timestep= (referencetime - s->getp(Localtime::ID))*0.99;
//cout << " timestep/localtime = " << new_timestep << " " << referencetime << " " << s->getp(Localtime::ID) << " " << s->getp(MCO::ID) << endl;
//utilities::wait();
svlog.pdebug("B New timestep end",new_timestep,referencetime,s->getp(Localtime::ID),__FILE__,__LINE__);
if (dprint)
utilities::wait("B New timestep end",new_timestep,referencetime,s->getp(Localtime::ID),s->getp(Mass::ID),__FILE__,__LINE__);
}
}
//Check and modify if new_timestep>max_dt or new_timestep<min_dt
check_dt_limits(new_timestep, s);
if (new_timestep==0)
svlog.critical("Proposed timestep is equal to 0",__FILE__,__LINE__,sevnstd::sse_error());
else if(new_timestep<0)
svlog.critical("Proposed timestep is negative "+
utilities::n2s(new_timestep,__FILE__,__LINE__),__FILE__,__LINE__,sevnstd::sse_error());
else if (new_timestep<utilities::TINY)
svlog.warning("New dt estimated in Timestep evolve is extremely small ("+
utilities::n2s(new_timestep,__FILE__,__LINE__)+"). If this happens just few times, it can be ignored, but"
"if this message it is frequent during the evoluton of a system, it "
"can be an hint that somethin is broken in the sse.",__FILE__,__LINE__);
set(new_timestep);
}
//TODO All the hardcoded numbers should be input parameters
//TODO Write different check and repeat for MHE/MCO and for Radius, currently we use tstart to discriminate
inline bool Timestep::check_repeat(Star *s, const double &V0, const double &V, const double &derivative, const double tstart) {
double new_dt = s->get_dtmax();
bool shouldIrepeat = false;
double max_variation = s->get_svpar_num("ts_maximum_variation");
if(tstart!=0.0){
if(V <= 4.0 or V0 <= 4.0){
if(fabs(V-V0) > 0.4){
new_dt = max_variation*(0.4/fabs(derivative)); //TODO this should be weighted with the mass of the star!! 0.4 is now hardcoded!!
shouldIrepeat = true;
}
else
shouldIrepeat = false;
}
else if(fabs(V-V0)/V > 2.0 * max_variation && V != 0.0){ //repeat tge step if we got twice the variation!
new_dt = max_variation*(V/fabs(derivative));
shouldIrepeat = true;
}
else
shouldIrepeat = false;
//TODO Is something as below needed? It should assure that if already are in a new phase we do not came brack in the previous phase
//new_dt = std::max(new_dt,tstart-s->getp_0(Localtime::ID)+new_dt);
}
else{
if(fabs(V-V0)/V > 2.0 * max_variation) {
shouldIrepeat = true;
new_dt = get()*0.5;//max_variation*(m/fabs(derivative));
}
}
//TODO it should be better to use (m-m0)/m0 as relative variation (relative wrt the starting point)
//if (s->getp(Worldtime::ID)>9.8947394131 and s->get_ID()==0)
// utilities::wait("CHeck and r",V,V0,fabs(V-V0),shouldIrepeat,__FILE__,__LINE__);
//Check and modify if new_dt>max_dt or new_dt<min_dt
check_dt_limits(new_dt, s);
if(new_dt >= 0.8*get()) return false;
if(shouldIrepeat) {
if (new_dt<utilities::TINY)
svlog.warning("New dt estimated in check and repeat is extremely small ("+
utilities::n2s(new_dt,__FILE__,__LINE__)+"). If this happens just few times, it can be ignored, but"
"if this message it is frequent during the evoluton of a system, it "
"can be an hint that somethin is broken in the sse.",__FILE__,__LINE__);
set(new_dt);
set_0(get());
return true;
}
else
return false;
}
inline bool Timestep::check_repeat_almost_naked(Star *s) {
if (checked_almost_naked){
checked_almost_naked=false;
return false;
}
double new_dt = s->get_dtmax();
bool shouldIrepeat = false;
//Here we start from:
// M = M0 + dMdt * DT
// m = m0 + dmdt *DT
// where for example M=Mass and m=MHE
// now we want a DT so that m<M, so
// m0 + dmdt *DT < M0 + dMdt * DT
// DT (dmdt - dMdt ) < M0-m0
// so DT < (M0-m0) / (dmdt - dMdt )
// hence we set DT_new = 0.9* (M0-m0) / (dmdt - dMdt )
if (!s->aminakedhelium() and std::abs(s->getp(Mass::ID)-s->getp(MHE::ID))<=s->get_svpar_num("ev_naked_tshold")){
new_dt = 0.5*( s->getp_0(Mass::ID)-s->getp_0(MHE::ID) ) / (s->getp(dMHEdt::ID)-s->getp(dMdt::ID));
shouldIrepeat=true;
}
else if (std::abs(s->getp(Mass::ID)-s->getp(MCO::ID))<=s->get_svpar_num("ev_naked_tshold")){
new_dt = 0.5*( s->getp_0(Mass::ID)-s->getp_0(MCO::ID) ) / (s->getp(dMCOdt::ID)-s->getp(dMdt::ID));
shouldIrepeat=true;
}
else if (s->getp(MHE::ID)!=0 and s->getp(MCO::ID)!=0 and std::abs(s->getp(MHE::ID)-s->getp(MCO::ID))<=s->get_svpar_num("ev_naked_tshold")){
new_dt = 0.5*( s->getp_0(MHE::ID)-s->getp_0(MCO::ID) ) / (s->getp(dMCOdt::ID)-s->getp(dMHEdt::ID));
shouldIrepeat=true;
}
if (shouldIrepeat){
//Check and modify if new_dt>max_dt or new_dt<min_dt
check_dt_limits(new_dt, s);
if(new_dt >= 0.8*get()){
std::cout<<"exit"<<std::endl;
return false;
}
if (new_dt<utilities::TINY)
svlog.warning("New dt estimated in check and repeat is extremely small ("+
utilities::n2s(new_dt,__FILE__,__LINE__)+"). If this happens just few times, it can be ignored, but"
"if this message it is frequent during the evoluton of a system, it "
"can be an hint that somethin is broken in the sse.",__FILE__,__LINE__);
set(new_dt);
set_0(get());
checked_almost_naked=true;
return true;
}
return false;
}
void Timestep::handle_star_check_repeat(Star *s){
s->repeatstep = true; //Set the repeatstep flag to true
//TODO I remove the following command, because the reset of changephase is now handled dreictly by the method Star::restore, that is more genreal since it can bel called also after a repeat triggered by the Binary evolution
//Myabe we can remove this function and use s->repeatstep = true directly in Timestep::evolve
//s->changedphase = false; //In case the previous step start the reduction of the timestep for the next change of phase, reset it since we are repeating
return;
}
void Timestep::resynch(Star *s) {
set(s->getp(Timestep::ID));
}
double Timestep::timestep_remnant(Star *s) {
double new_timestep;
if (s->get_COnaked() and s->getp(Phase::ID)==Remnant)
svlog.critical("Inside Timestep::set_remnant the star flags remnant and isconaked are both true, this is not allowed",
__FILE__,__LINE__,sevnstd::sse_error());
else if (s->get_COnaked()){
new_timestep=1.001*(s->get_tphase()[Remnant] - s->getp(Localtime::ID));
}
else if (s->getp(Phase::ID)==Remnant){
new_timestep=s->get_tf() - s->getp(Worldtime::ID);
if (new_timestep==0) new_timestep=get_0(); //If we reach tf, just put a fake timestep to avoid to raise the warning
}
else if (!s->get_COnaked() and s->getp(Phase::ID)!=Remnant){
svlog.critical("Inside Timestep::set_remnant when isconaked is false and the Phase is not Remnant, this is not allowed",
__FILE__,__LINE__,sevnstd::sse_error());
}
else
svlog.critical("Inside Timestep::set_remnant the star flags remnant and isconaked are both false, this is not allowed",
__FILE__,__LINE__,sevnstd::sse_error());
new_timestep = std::min(new_timestep,s->get_dtmax()); //Use the mimimum
return new_timestep;
}
void Timestep::set_remnant(Star *s) {
set_0(get());
double new_timestep = timestep_remnant(s);
if (new_timestep==0)
svlog.critical("Proposed timestep is equal to 0",__FILE__,__LINE__,sevnstd::sse_error());
if(new_timestep<0)
svlog.critical("Proposed timestep is negative " +
utilities::n2s(new_timestep, __FILE__, __LINE__), __FILE__, __LINE__, sevnstd::sse_error());
else if (new_timestep<utilities::TINY)
svlog.warning("New dt estimated in Timestep evolve is extremely small ("+
utilities::n2s(new_timestep,__FILE__,__LINE__)+"). If this happens just few times, it can be ignored, but"
"if this message it is frequent during the evoluton of a system, it "
"can be an hint that somethin is broken in the sse.",__FILE__,__LINE__);
set(new_timestep);
}
void Timestep::set_remnant_in_bse(Star *s, _UNUSED Binstar *b){
double old_dt0 = get_0();
set_remnant(s);
set_0(old_dt0); //Restore t0
}
void Timestep::set_empty_in_bse(Star *s, Binstar *b){
set_remnant_in_bse(s,b);
}
void Timestep::check_dt_limits(double &dt, Star *s){
if (s->get_svpar_num("ts_max_dt")>0)
dt=std::min(dt, s->get_svpar_num("ts_max_dt"));
if (s->get_svpar_num("ts_min_dt")>0)
dt=std::max(dt, s->get_svpar_num("ts_min_dt"));
}
void Timestep::changed_track(Star* s,Star* s_jtrack){
//Here we set the next time step rescaling the dt proposed for the ration between the DT_phase of the new track wrt to the old one.
double rescale = (s_jtrack->get_next_tphase()-s_jtrack->get_current_tphase()) / (s->get_next_tphase()-s->get_current_tphase());
V=V*rescale;
}
/**dRdt**/
void dRdt::evolve(Star *s){
set_0(get());
set((s->getp(Radius::ID) - s->getp_0(Radius::ID))/s->getp(Timestep::ID));
}
/**dMCOdt**/
void dMCOdt::evolve(Star *s){
set_0(get());
set((s->getp(MCO::ID) - s->getp_0(MCO::ID))/s->getp(Timestep::ID));
}
/**dMHEdt**/
void dMHEdt::evolve(Star *s){
set_0(get());
set((s->getp(MHE::ID) - s->getp_0(MHE::ID))/s->getp(Timestep::ID));
}
/**dMdt**/
void dMdt::evolve(Star *s){
set_0(get());
svlog.debug("Inside dM/dt "+ std::to_string(s->getp(Timestep::ID)));
//utilities::wait();
set((s->getp(Mass::ID) - s->getp_0(Mass::ID))/s->getp(Timestep::ID));
}
/**Chemical composition on the surface**/
void Hsup::set_w(Star *s){
double *Mtrack = s->get_mtrack();
double *Ztrack = s->get_ztrack();
double mzams = s->get_zams();
double Z = s->get_Z();
//set also the default weights
for(int i = 0; i < 4; i+=2) {
wM[i] = (Mtrack[i + 1] - mzams) / (Mtrack[i + 1] - Mtrack[i]);
wM[i+1] = (mzams - Mtrack[i]) / (Mtrack[i + 1] - Mtrack[i]);
}
wZ[0] = (Ztrack[1] - Z) / (Ztrack[1] - Ztrack[0]);
wZ[1] = (Z - Ztrack[0]) / (Ztrack[1] - Ztrack[0]);
}
void Hsup::changed_track(_UNUSED Star *s, Star *s_jtrack) {
//copy the fake tracks value from s_jtrack
V=s_jtrack->getp(ID);
value=s_jtrack->getp_fk(ID);
value0=s_jtrack->getp_fk0(ID);
}
void HEsup::set_w(Star *s){
double *Mtrack = s->get_mtrack();
double *Ztrack = s->get_ztrack();
double mzams = s->get_zams();
double Z = s->get_Z();
//set also the default weights
for(int i = 0; i < 4; i+=2) {
wM[i] = (Mtrack[i + 1] - mzams) / (Mtrack[i + 1] - Mtrack[i]);
wM[i+1] = (mzams - Mtrack[i]) / (Mtrack[i + 1] - Mtrack[i]);
}
wZ[0] = (Ztrack[1] - Z) / (Ztrack[1] - Ztrack[0]);
wZ[1] = (Z - Ztrack[0]) / (Ztrack[1] - Ztrack[0]);
}
void HEsup::changed_track(_UNUSED Star *s, Star *s_jtrack) {
//copy the fake tracks value from s_jtrack
V=s_jtrack->getp(ID);
value=s_jtrack->getp_fk(ID);
value0=s_jtrack->getp_fk0(ID);
}
void Csup::set_w(Star *s){
double *Mtrack = s->get_mtrack();
double *Ztrack = s->get_ztrack();
double mzams = s->get_zams();
double Z = s->get_Z();
//set also the default weights
for(int i = 0; i < 4; i+=2) {
wM[i] = (Mtrack[i + 1] - mzams) / (Mtrack[i + 1] - Mtrack[i]);
wM[i+1] = (mzams - Mtrack[i]) / (Mtrack[i + 1] - Mtrack[i]);
}
wZ[0] = (Ztrack[1] - Z) / (Ztrack[1] - Ztrack[0]);
wZ[1] = (Z - Ztrack[0]) / (Ztrack[1] - Ztrack[0]);
}
void Csup::changed_track(_UNUSED Star *s, Star *s_jtrack) {
//copy the fake tracks value from s_jtrack
V=s_jtrack->getp(ID);
value=s_jtrack->getp_fk(ID);
value0=s_jtrack->getp_fk0(ID);
}
void Nsup::set_w(Star *s){
double *Mtrack = s->get_mtrack();
double *Ztrack = s->get_ztrack();
double mzams = s->get_zams();
double Z = s->get_Z();
//set also the default weights
for(int i = 0; i < 4; i+=2) {
wM[i] = (Mtrack[i + 1] - mzams) / (Mtrack[i + 1] - Mtrack[i]);
wM[i+1] = (mzams - Mtrack[i]) / (Mtrack[i + 1] - Mtrack[i]);
}
wZ[0] = (Ztrack[1] - Z) / (Ztrack[1] - Ztrack[0]);
wZ[1] = (Z - Ztrack[0]) / (Ztrack[1] - Ztrack[0]);
}
void Nsup::changed_track(_UNUSED Star *s, Star *s_jtrack) {
//copy the fake tracks value from s_jtrack
V=s_jtrack->getp(ID);
value=s_jtrack->getp_fk(ID);
value0=s_jtrack->getp_fk0(ID);
}
void Osup::set_w(Star *s){
double *Mtrack = s->get_mtrack();
double *Ztrack = s->get_ztrack();
double mzams = s->get_zams();
double Z = s->get_Z();
//set also the default weights
for(int i = 0; i < 4; i+=2) {
wM[i] = (Mtrack[i + 1] - mzams) / (Mtrack[i + 1] - Mtrack[i]);
wM[i+1] = (mzams - Mtrack[i]) / (Mtrack[i + 1] - Mtrack[i]);
}
wZ[0] = (Ztrack[1] - Z) / (Ztrack[1] - Ztrack[0]);
wZ[1] = (Z - Ztrack[0]) / (Ztrack[1] - Ztrack[0]);
}
void Osup::changed_track(_UNUSED Star *s, Star *s_jtrack) {
//copy the fake tracks value from s_jtrack
V=s_jtrack->getp(ID);
value=s_jtrack->getp_fk(ID);
value0=s_jtrack->getp_fk0(ID);
}
/**Convective envelope properties**/
void Qconv::set_w(Star *s){
double *Mtrack = s->get_mtrack();
double *Ztrack = s->get_ztrack();
double mzams = s->get_zams();
double Z = s->get_Z();
//set also the default weights
for(int i = 0; i < 4; i+=2) {
wM[i] = (Mtrack[i + 1] - mzams) / (Mtrack[i + 1] - Mtrack[i]);
wM[i+1] = (mzams - Mtrack[i]) / (Mtrack[i + 1] - Mtrack[i]);
}
wZ[0] = (Ztrack[1] - Z) / (Ztrack[1] - Ztrack[0]);
wZ[1] = (Z - Ztrack[0]) / (Ztrack[1] - Ztrack[0]);
}
void Qconv::changed_track(_UNUSED Star *s, Star *s_jtrack) {
if (table_loaded){
V=s_jtrack->getp(ID);
} else {
V=estimate_Qconv(s_jtrack);
}
value=s_jtrack->getp_fk(ID);
value0=s_jtrack->getp_fk0(ID);
}
void Qconv::evolve_without_table(Star *s) {
set_0(get());
set(estimate_Qconv(s));
//Set V,V0 but also v, v0. This is needed because even if the tables are loaded
//the user can choice do not use them.
synch_v_value_without_table();
}
double Qconv::estimate_Qconv(Star *s) {
//We follow Hurley02 with some minor change:
//-We assume all pureHE stars are radiative (see below)
//-We use the SEVN phase instead of the bse phases (we need this to track the lifetime in each phase)
//-We assume all the stars <1.25 are completely convective. In BSE stars <0.3 are completely convective,
//while stars between 0.3 and 1.25 are partially convective. However to set the convective Radius we should
//have an estimate of the zams Radius for a 0.3 Msun, that depends on Models and metallcities. Given that
//this is in any case a rough estiamte of the Dconv, we decided to use 1.25 as limit
double Mcnv=0;
//We assume all the pureHE are radiative.
//We check with parsec tracks that this is totally consistent:
//all the pureHE are completely radiative or have a very light convective envelope (Qconv<1e-3) toward the end
//of their life. Metal rich pureHE stars (Z>0.02) are purely radiate up to the end.
if (s->aminakedhelium()){
return 0.0;
}
//From Hurley+00
else if (s->getp(Phase::ID)==Lookup::MainSequence){
if (s->get_zams()>1.25){
return 0.0;
}
else{
Mcnv = s->getp(Mass::ID);
Mcnv*=pow((1-s->plife()),0.25); //plife is t/tMS as in Hurley00, Sec. 7.2
}
}
else if (s->getp(Phase::ID)==Lookup::TerminalMainSequence){
Mcnv=s->plife()*(s->getp(Mass::ID)-s->getp(MHE::ID)); //plife = t-tMS/(tGB_start - tMS) as in Hurley00, Sec. 7.2
}
//All the Giants
else{
Mcnv=s->getp(Mass::ID)-s->getp(MHE::ID);
}
return std::min(Mcnv/s->getp(Mass::ID),1.0); //Depthconv is the Mass of the envelope layer normalised over the total mass
}
void Tconv::set_w(Star *s){
double *Mtrack = s->get_mtrack();
double *Ztrack = s->get_ztrack();
double mzams = s->get_zams();
double Z = s->get_Z();
//set also the default weights
for(int i = 0; i < 4; i+=2) {
wM[i] = (Mtrack[i + 1] - mzams) / (Mtrack[i + 1] - Mtrack[i]);
wM[i+1] = (mzams - Mtrack[i]) / (Mtrack[i + 1] - Mtrack[i]);
}
wZ[0] = (Ztrack[1] - Z) / (Ztrack[1] - Ztrack[0]);
wZ[1] = (Z - Ztrack[0]) / (Ztrack[1] - Ztrack[0]);
}
void Tconv::changed_track(_UNUSED Star *s, Star *s_jtrack) {
///Copy the Tconv from the jtrack star
V=s_jtrack->getp(ID);
//V0=log10(s_jtrack->getp(ID));
value=s_jtrack->getp_fk(ID);
value0=s_jtrack->getp_fk0(ID);
}
void Depthconv::set_w(Star *s){
double *Mtrack = s->get_mtrack();
double *Ztrack = s->get_ztrack();
double mzams = s->get_zams();
double Z = s->get_Z();
//set also the default weights
for(int i = 0; i < 4; i+=2) {
wM[i] = (Mtrack[i + 1] - mzams) / (Mtrack[i + 1] - Mtrack[i]);
wM[i+1] = (mzams - Mtrack[i]) / (Mtrack[i + 1] - Mtrack[i]);
}
wZ[0] = (Ztrack[1] - Z) / (Ztrack[1] - Ztrack[0]);
wZ[1] = (Z - Ztrack[0]) / (Ztrack[1] - Ztrack[0]);
}
void Depthconv::changed_track(_UNUSED Star *s, Star *s_jtrack) {
if (table_loaded){
V=s_jtrack->getp(ID);
} else {
V=estimate_Dconv(s_jtrack);
}
value=s_jtrack->getp_fk(ID);
value0=s_jtrack->getp_fk0(ID);
}
void Depthconv::evolve_without_table(Star *s) {
set_0(get());
set(estimate_Dconv(s));
//Set V,V0 but also v, v0. This is needed because even if the tables are loaded
//the user can choice do not use them.
synch_v_value_without_table();
}
double Depthconv::estimate_Dconv(Star *s) {
//We follow Hurley02 with some minor change:
//-We assume all pureHE stars are radiative (see below)
//-We use the SEVN phase instead of the bse phases (we need this to track the lifetime in each phase)
//-We assume all the stars <1.25 are completely convective. In BSE stars <0.3 are completely convective,
//while stars between 0.3 and 1.25 are partially convective. However to set the convective Radius we should
//have an estimate of the zams Radius for a 0.3 Msun, that depends on Models and metallcities. Given that
//this is in any case a rough estiamte of the Dconv, we decided to use 1.25 as limit
double Dcnv=0.0;
//We assume all the pureHE are radiative.
//We check with parsec tracks that this is totally consistent:
//all the pureHE are completely radiative or have a very light convective envelope (Qconv<1e-3) toward the end
//of their life. Metal rich pureHE stars (Z>0.02) are purely radiate up to the end.
if (s->aminakedhelium()){
return 0.0;
}
//From Hurley+02
else if (s->getp(Phase::ID)==Lookup::MainSequence){
if (s->get_zams()>1.25){
return 0.0;
}
else{
Dcnv = s->getp(Radius::ID); //RHE is 0 becasue MainSequence
Dcnv*=pow((1-s->plife()),0.25); //plife is t/tMS, from Hurley02 Eq. 37
}
}
else if (s->getp(Phase::ID)==Lookup::TerminalMainSequence){
Dcnv=std::sqrt(s->plife())*(s->getp(Radius::ID)-s->getp(RHE::ID)); //plife = t-tMS/(tGB_start - tMS) from Hurley02 Eq. 39.
}
//All the Giants
else{
Dcnv=s->getp(Radius::ID)-s->getp(RHE::ID);
}
return std::min(Dcnv/s->getp(Radius::ID),1.0); //Depthconv is normalised over the total radius
}
/**Spin**/
void AngMomSpin::evolve(_UNUSED Star *s){
set_0(get());
//If 0 just return, it cannot become larger than 0 because Ltot=0
if (get_0()==0)
return;
double new_spin = evolve_angmom(s);
set(new_spin);
}
double AngMomSpin::evolve_angmom(_UNUSED Star *s){
double dM_wind = s->getp(Mass::ID)-s->getp_0(Mass::ID);
const double & R0 = s->getp_0(Radius::ID);
double OmegaSpin0 = s->getp(OmegaSpin::ID); //OmegaSpin has to be evolved
///1- Stellar angular momentum loss through winds
// In order to estimate the angular momentum loss by winds, we assume that the wind removed
// a thin shell of material with Radius R0 and mass DM_wind, so dL = 2/3 * R0^2 * R0^2 * dM * OmegaSpin0
//0.6666666666666666=2/3, notice dM_wind is negative, so dLwind is negative
double dLwind = 0.6666666666666666*R0*R0*dM_wind*OmegaSpin0;
///2- Stellar angular momentum loss trough magnetic braking
//Here we follow Hurley+02, Eq. 50 and MOBSE, in MOBSE the comment is:
// Include magnetic braking for stars that have appreciable convective
// envelopes. This includes MS stars with M < 1.25, HG stars near the GB
// and giants. MB is not allowed for fully convective MS stars.
//Notice that even if stated there is not a proper check on the amount of convective envelope
//TODO Use the amoun of convective envelope mass instead of the whole convective envelope
double dLmbraking=0;
if (s->getp_0(Mass::ID)>=0.35 and s->get_bse_phase_0()<10){
dLmbraking = -(5.83e-16*s->Menvelope(true)*R0*R0*R0*OmegaSpin0*OmegaSpin0*OmegaSpin0/s->getp_0(Mass::ID))*s->getp(Timestep::ID)*1e-6; //Timestep is in Myr, Eq. is in yr
}
///2- Estimate new angmom
//V is the current L
double Lnew = V + dLwind + dLmbraking; //Both dLwind and dLmbraking are <0
//Limit to 0 or to maximum Lcrit allowe by critical rotational velocity
double Lcrit = s->getp(Inertia::ID)*utilities::omega_crit(s->getp(Mass::ID),s->getp(Radius::ID));
Lnew = std::min(std::max(Lnew,0.0),Lcrit);
return Lnew;
}
void AngMomSpin::changed_track(Star *s, _UNUSED Star *s_jtrack) {
//We consider that angular momentum is conserved, however we have to check
//if the new angmom is below the critical L, otherwise set is to Lcrit
//Notice Inertia, Mass and Radius alread changed
//if (s->get_ID()==0) utilities::hardwait("Jc", V, s->getp(Inertia::ID),utilities::omega_crit(s->getp(Mass::ID),s->getp(Radius::ID)));
double Lcrit = s->getp(Inertia::ID)*utilities::omega_crit(s->getp(Mass::ID),s->getp(Radius::ID));
V = std::min(V,Lcrit);
}
void OmegaSpin::evolve(_UNUSED Star *s){
set_0(get());
set(s->getp(AngMomSpin::ID)/s->getp(Inertia::ID));
}
/**Xspin (black hole spin) properties**/
void Xspin::set_remnant(Star *s){
V0 = V;
value0 = value;
V = s->get_staremnant(Xspin::ID);
value = s->get_staremnant(Xspin::ID);
}
void Xspin::evolve_remnant(Star *s){
set_0(get());
set(s->get_staremnant(Xspin::ID));
}
/**RemnantType properties**/
void RemnantType::set_remnant(Star *s) {
V = value = (double)s->get_staremnant()->get_remnant_type();
}
void RemnantType::set_empty(_UNUSED Star *s){
V0 = V = Lookup::Remnants::Empty;
value0 = value = Lookup::Remnants::Empty;
}
void RemnantType::evolve(_UNUSED Star *s) {
//Do not evolve if it is not a remnant
//V = V0 = value = value0 = s->get_supernova()->get_remnant_type();
}
/**JIT properties**/
//Lambda for envelope binding energy
double Lambda::get(const Star *s) {
//If evolve_number>last_evolve_number, we have to obtain a new estimate for lambda
if(new_estimate_needed()){
//When we don't have a clear core-envelope separation return nan
if (!s->haveienvelope())
set(std::nan(""));
else
set(estimate_lambda(s)); //Set the new V and set evolve_number=last_evolve_number
}
return V;
}
double Lambda::estimate_lambda (const Star *star){
const double &lambda_option = star->get_svpar_num("star_lambda");
if (lambda_option==-1)
return estimate_lambda_BSE(star, false,true);
else if (lambda_option==-11)
return estimate_lambda_BSE(star, false,false);
else if (lambda_option==-12)
return estimate_lambda_BSE(star, true,true);
else if (lambda_option==-13)
return estimate_lambda_BSE(star, true,false);
else if(lambda_option==-2)
return estimate_lambda_Claeys14(star,false);
else if(lambda_option==-21)
return estimate_lambda_Claeys14(star,true);
else if(lambda_option==-3)
return estimate_lambda_Izzard04(star,false);
else if(lambda_option==-31)
return estimate_lambda_Izzard04(star,true);
else if(lambda_option==-4)
return estimate_lambda_Klencki21(star,true);
else if(lambda_option==-41)
return estimate_lambda_Klencki21(star,false);
else if(lambda_option==-5)
return estimate_lambda_Nanjing(star,true); //As in Compas but interpolating between XU&Li10 and Dominik+12 tracks
else if(lambda_option==-51)
return estimate_lambda_Nanjing(star,false); //Exactly as in Compas
else if (lambda_option>0){
int bse_phase = star->get_bse_phase(); //NakedHelium or WR
if (bse_phase==7 or bse_phase==8 or bse_phase==9) return star->get_svpar_num("star_lambda_pureHe");
else return star->get_svpar_num("star_lambda");
}
else
svlog.critical("Option " + utilities::n2s(lambda_option,__FILE__,__LINE__)+
" not implemented",__FILE__,__LINE__,sevnstd::sevnio_error());
return std::nan("");
}
double Lambda::estimate_lambda_Izzard04(const Star *star,bool whole_cenv) {
//Lambda estimate following Claeys et al. 2014 (Appendix A)
///Initial checks
//Extra check: we should not call this fuction for Main Sequence Star and Remnants
if (!star->haveienvelope())
svlog.critical("Trying to estimate the lambda for envelope binding energy, "
"for a star without a clear Envelope/Core separation:"
"\nStar ID: " + utilities::n2s(star->get_ID(),__FILE__,__LINE__) +
"\nStar Phase " + utilities::n2s((int)star->getp(Phase::ID),__FILE__,__LINE__),
__FILE__,__LINE__,sevnstd::ce_error());
//To be consistent with MOBSE, use the BSE phases
int bse_phase = star->get_bse_phase();
//If it is a Naked He, Clayes has not fitting formula, she just assumed 0.5
if (bse_phase==7 or bse_phase==8 or bse_phase==9)
return star->get_svpar_num("star_lambda_pureHe"); //No fit just return 0.5 as done in MOBSE/BSE/Claeys
///Start Estimate
double lambda_ce; //Final results
/**
* The final lambda depends on the Mass of the convective envelope.
* If we are using convective tables just use the table value, otherwise estimate the Mcenv
* using analytic approximation from Hurley (see Qconv::estimate_without_table)
* Mcenv_env=Qconv*Mass,
* If whole_cenv is true consider the whole envelope as convective
*/
double Mcenv= whole_cenv ? star->getp(Mass::ID)-star->getp(MHE::ID) : star->getp(Mass::ID)*star->getp(Qconv::ID);//Mass of the convective envelope
//Mcenv = whole_cenv ? 1 : star->getp(Mass::ID)*star->getp(Qconv::ID)/(star->getp(Mass::ID)-star->getp(MHE::ID));
//Other variables
double logL = std::log10(star->getp(Luminosity::ID));
double logM = std::log10(star->getp(Mass::ID));
double lam1=0, lam2=0; //lambda1 e lambda2 in Claeys et al. 2014 (Appendix A)
///Estimate lam2 (needed only for Mcenv<1)
if (Mcenv<1){
//Calculate Rzams
double Rzams = get_Rzams(star);
lam2 = 0.42*pow(Rzams/star->getp(Radius::ID),0.4);
}
///Estimate lam1 (needed only for Mcenv>0)
if (Mcenv>0){
//HG and RGB (eq. A3)
if (bse_phase<=3){
double proposed_lam1 = 3/(2.4 + pow(star->getp(Mass::ID),-3./2.));
proposed_lam1 -= 0.15*logL;
lam1 = std::min(0.8, proposed_lam1);
}
//CHEB, E-AGB, TP-AGB (eq. A4-A5)
else if (bse_phase<=6){
double lam3 = std::min(0.9, 0.58 + 0.75*logM) - 0.08*logL; //Eq. A4 (typo in the paper: -0.9)
//CHEB, E-AGB
if(bse_phase<6) lam1 = std::min(0.8, std::min(1.25-0.15*logL,lam3)); //Eq. A5a
//TP-AGB
else lam1= std::min(std::max(-3.5 -0.75*logM+logL, lam3),1.0); //Note maximum of 1 is written in the text.
}
else
svlog.critical("Star with BSE Phase "+utilities::n2s(bse_phase,__FILE__,__LINE__)+
"should enter here.",__FILE__,__LINE__,sevnstd::ce_error());
}
///Multiply by 2
//Notice, in the Claeys paper it seems that this multiplication by 2 has to be made only at the end
//after the correction for ionization energy, however in bse and in the original izzard phd (http://personal.ph.surrey.ac.uk/~ri0005/doc/thesis/thesis.pdf, Appendix E)
//is the opposite, lam1 is estimated multplying by 2 and then it is used in the ion machinary.
//Therefore here we multiply both lam1 and lam2 by 2
lam2=2*lam2;
lam1=2*lam1;
///Estimate ionization contribution //Eq. A6
double f_ion=star->get_svpar_num("star_lambda_fth"); //This is the equivalent of lambda_ion in Claeys et al. 2014 (Appendix A)
if (f_ion>0 and Mcenv>0) {
double lam4, lam5; //Eq. A6, A8
//Parameter to estimate lam5
double a_ion, b_ion, c_ion, d_ion;
b_ion = std::max(1.5, 3 - 5 * logM);
c_ion = std::max(3.7 + 1.6 * logM, 3.3 + 2.1 * logM);
if (bse_phase <= 3) { //HG,RGB
a_ion = std::min(-0.5, 1.2 * (logM - 0.25) * (logM - 0.25) - 0.7); // Eq. A9a
d_ion = std::max(0., std::min(0.15, 0.15 - 0.25 * logM)); //Eq. 12a
} else if (bse_phase <= 6) { //CHEB,EAGB.TAGB
a_ion = std::max(-0.5, -0.2 - logM); // Eq. A9b
d_ion = 0.; //Eq. 12b
} else {
svlog.critical("Unexpected BSE type " + utilities::n2s(bse_phase, __FILE__, __LINE__), __FILE__, __LINE__,
sevnstd::sanity_error());
}
lam5 = 1 / ( a_ion + std::atan(b_ion*(c_ion-logL)) + d_ion*(logL-2.) ); //Eq. A8
lam4 = std::max( std::min(lam5,100.),lam1 ); //Eq. A7
//Eq. A6
if (f_ion==1) lam1 = lam4;
else lam1 = lam1 + f_ion*(lam4-lam1); //Eq. A6
}
///Final lambda_ce estimate //Eq. A1 without 2, see comment above
if (Mcenv==0) lambda_ce=lam2;
else if (Mcenv>=1) lambda_ce =lam1;
else lambda_ce=(lam2 + std::sqrt(Mcenv)*(lam1-lam2));
return lambda_ce;
}
double Lambda::estimate_lambda_Claeys14(const Star *star,bool whole_cenv) {
//Lambda estimate following Claeys et al. 2014 (Appendix A)
///Initial checks
//Extra check: we should not call this fuction for Main Sequence Star and Remnants
if (!star->haveienvelope())
svlog.critical("Trying to estimate the lambda for envelope binding energy, "
"for a star without a clear Envelope/Core separation:"
"\nStar ID: " + utilities::n2s(star->get_ID(),__FILE__,__LINE__) +
"\nStar Phase " + utilities::n2s((int)star->getp(Phase::ID),__FILE__,__LINE__),
__FILE__,__LINE__,sevnstd::ce_error());
//To be consistent with MOBSE, use the BSE phases
int bse_phase = star->get_bse_phase();
//If it is a Naked He, Clayes has not fitting formula, she just assumed 0.5
//TODO we can do it with PARSEC
if (bse_phase==7 or bse_phase==8 or bse_phase==9) //NakedHelium or WR
return star->get_svpar_num("star_lambda_pureHe"); //No fit just return 0.5 as done in MOBSE/BSE/Claeys
///Start Estimate
double lambda_ce; //Final results
/**
* The final lambda depends on the Mass of the convective envelope.
* If we are using convective tables just use the table value, otherwise estimate the Mcenv
* using analytic approximation from Hurley (see Qconv::estimate_without_table)
* Mcenv_env=Qconv*Mass,
* If whole_cenv is true consider the whole envelope as convective
*/
double Mcenv= whole_cenv ? star->getp(Mass::ID)-star->getp(MHE::ID) : star->getp(Mass::ID)*star->getp(Qconv::ID);//Mass of the convective envelope
//Mcenv = whole_cenv ? 1 : star->getp(Mass::ID)*star->getp(Qconv::ID)/(star->getp(Mass::ID)-star->getp(MHE::ID));
//Other variables
double logL = std::log10(star->getp(Luminosity::ID));
double logM = std::log10(star->getp(Mass::ID));
double lam1=0, lam2=0; //lambda1 e lambda2 in Claeys et al. 2014 (Appendix A)
///Estimate lam2 (needed only for Mcenv<1)
if (Mcenv<1){
//Calculate Rzams
double Rzams = get_Rzams(star);
lam2 = 0.42*pow(Rzams/star->getp(Radius::ID),0.4);
}
///Estimate lam1 (needed only for Mcenv>0)
if (Mcenv>0){
//HG and RGB (eq. A3)
if (bse_phase<=3){
double proposed_lam1 = 3/(2.4 + pow(star->getp(Mass::ID),-3./2.));
proposed_lam1 -= 0.15*logL;
lam1 = std::min(0.8, proposed_lam1);
}
//CHEB, E-AGB, TP-AGB (eq. A4-A5)
else if (bse_phase<=6){
double lam3 = std::min(0.9, 0.58 + 0.75*logM) - 0.08*logL; //Eq. A4 (typo in the paper: -0.9)
//CHEB, E-AGB
if(bse_phase<6) lam1 = std::min(0.8, std::min(1.25-0.15*logL,lam3)); //Eq. A5a
//TP-AGB
else lam1= std::min(std::max(-3.5 -0.75*logM+logL, lam3),1.0); //Note maximum of 1 is written in the text.
}
else
svlog.critical("Star with BSE Phase "+utilities::n2s(bse_phase,__FILE__,__LINE__)+
"should enter here.",__FILE__,__LINE__,sevnstd::ce_error());
}
///Estimate ionization contribution //Eq. A6
double f_ion=star->get_svpar_num("star_lambda_fth"); //This is the equivalent of lambda_ion in Claeys et al. 2014 (Appendix A)
if (f_ion>0 and Mcenv>0) {
double lam4, lam5; //Eq. A6, A8
//Parameter to estimate lam5
double a_ion, b_ion, c_ion, d_ion;
b_ion = std::max(1.5, 3 - 5 * logM);
c_ion = std::max(3.7 + 1.6 * logM, 3.3 + 2.1 * logM);
if (bse_phase <= 3) { //HG,RGB
a_ion = std::min(-0.5, 1.2 * (logM - 0.25) * (logM - 0.25) - 0.7); // Eq. A9a
d_ion = std::max(0., std::min(0.15, 0.15 - 0.25 * logM)); //Eq. 12a
} else if (bse_phase <= 6) { //CHEB,EAGB.TAGB
a_ion = std::max(-0.5, -0.2 - logM); // Eq. A9b
d_ion = 0.; //Eq. 12b
} else {
svlog.critical("Unexpected BSE type " + utilities::n2s(bse_phase, __FILE__, __LINE__), __FILE__, __LINE__,
sevnstd::sanity_error());
}
lam5 = 1 / ( a_ion + std::atan(b_ion*(c_ion-logL)) + d_ion*(logL-2.) ); //Eq. A8
lam4 = std::max( std::min(lam5,100.),lam1 ); //Eq. A7
//Eq. A6
if (f_ion==1) lam1 = lam4;
else lam1 = lam1 + f_ion*(lam4-lam1); //Eq. A6
}
///Final lambda_ce estimate //Eq. A1 without 2, see comment above
if (Mcenv==0) lambda_ce=2*lam2;
else if (Mcenv>=1) lambda_ce =2*lam1;
else lambda_ce=2*(lam2 + std::sqrt(Mcenv)*(lam1-lam2));
return lambda_ce;
}
double Lambda::estimate_lambda_Parsec(const Star *star) {
return 0.1*estimate_lambda_BSE(star,false);
}
double Lambda::estimate_lambda_BSE(const Star *star, bool whole_cenv, bool m0_as_hurley) {
//Lambda estimate following exactly the implementation of the function CELAMF in zfuncs.f in MOBSE ()
//NOTICE: this should come from the Appendix A in Claeys+14, but there is a typo fixed (it was already fixed
//also in estimate_lambda_Claeys14) and several other differences.
///Initial checks
//Extra check: we should not call this fuction for Main Sequence Star and Remnants
if (!star->haveienvelope())
svlog.critical("Trying to estimate the lambda for envelope binding energy, "
"for a star without a clear Envelope/Core separation:"
"\nStar ID: " + utilities::n2s(star->get_ID(),__FILE__,__LINE__) +
"\nStar Phase " + utilities::n2s((int)star->getp(Phase::ID),__FILE__,__LINE__),
__FILE__,__LINE__,sevnstd::ce_error());
//To be consistent with MOBSE, use the BSE phases
int bse_phase = star->get_bse_phase();
//If it is a Naked He, Clayes has not fitting formula, she just assumed 0.5
if (bse_phase==7 or bse_phase==8 or bse_phase==9) //NakedHelium or WR
return star->get_svpar_num("star_lambda_pureHe"); //No fit just return 0.5 as done in MOBSE/BSE/Claeys
///Start Estimate
double lambda_ce; //Final results
/**
* The final lambda depends on the fraction of the mass convective envelope over the total envelope mass.
* If we are using convective tables just use the table value, otherwise estimate the Mcenv
* using analytic approximation from Hurley (see Qconv::estimate_without_table)
* fcenv=Qconv,
* If whole_cenv is true consider the whole envelope as convective fcenv=1
*/
double fcenv = whole_cenv ? 1 : star->getp(Mass::ID)*star->getp(Qconv::ID) / (star->getp(Mass::ID) - star->getp(MHE::ID));//Mass of the convective envelope
//Other variables
//Notice, in Clayes+2014, the mass seems the current mass while in BSE/MOBSE it is M0
//M0 is the initial effective mass (see Sec. 7.1 in Hurley+00), during the MS, HG and nakedHelium MS
//M0=M, but for later stages M0 is not changed except when the star starts the ZAHB (M0=M) or become a pureHE
//This was explained in Sec. 7.1 because the age depends mainly on the core and in these phases the evolution of the envelope
//and of the core is decoupled.
//However (GI opinion, for the binding energy of the envelope the current mass of the envelope DOES matter)
double Mass = star->getp(Mass::ID);
//Exploring MOBSE/BSE we realise that during MS and nakedHe MS M0=M, in all the other cases
//M0 is freezed to the value at the end of the MS and of the nakedHE MS
//THerefore, the first time we enter here in a phase outside MS (we do not have to consider Cheb since the lambda for them is set to 0.5)
//we can set a value M0 that can be used later, in this way we will be in agreement with MOBSE/BSE
if (star->getp(Phase::ID)>1 and m0_as_hurley){
Mass = get_M0_BSE(star);
}
double lam1=0, lam2=0; //lambda1 e lambda2 in Claeys et al. 2014 (Appendix A)
if (fcenv>0){
double logL = std::log10(star->getp(Luminosity::ID));
double logM = std::log10(Mass);
//Comment from MOBSE: Formulae for giant-like stars; also used for HG and CHeB stars close
// to the Hayashi track.
if (bse_phase<=5){
double m1 = Mass;
if (bse_phase>3) m1 = 100.0;
lam1 = 3./(2.4 + 1./std::pow(m1,3./2.)) - 0.15*logL;
lam1 = std::min(lam1,0.8);
}
else{
lam1 = -3.5 - 0.75*logM + logL;
}
if (bse_phase>3){
//Comment from MOBSE: Eq A.4 lam2 = lam3
lam2 = std::min(0.9,0.58 + 0.75*logM) - 0.08*logL;
if (bse_phase<6){
lam1 = std::min(lam2,lam1);
}else{
lam1 = std::max(lam2,lam1);
lam1 = std::min(lam1,1.);
}
}
lam1 = 2.*lam1;
double f_ion=star->get_svpar_num("star_lambda_fth"); //This is the equivalent of lambda_ion in Claeys et al. 2014 (Appendix A)
if (f_ion>0){
//Comment from MOBSE: Use a fraction FAC of the ionization energy in the energy balance.
// Note that from eq. A.6 to eq. A.12 lam5 = 1/lam2
// Eq. A.9
double aa=0, bb=0, cc=0, dd=0;
if (bse_phase<=3){
double logM_m_025= (logM - 0.25);
aa = std::min(1.2*logM_m_025*logM_m_025 - 0.7,-0.5);
} else{
aa = std::max(-0.2 - logM,-0.5);
}
//Comment from MOBSE: Eq. A.10
bb = std::max(3. - 5.*logM,1.5);
//Comment from MOBSE: Eq. A.11
cc = std::max(3.7 + 1.6*logM,3.3 + 2.1*logM);
lam2 = aa + std::atan(bb*(cc - logL));
//Comment from MOBSE: Eq. A.12
if(bse_phase<=3){
dd = std::max(0.,std::min(0.15,0.15 - 0.25*logM));
lam2 = lam2 + dd*(logL - 2.);
}
lam2 = std::max(lam2,0.01);
lam2 = std::max(1./lam2,lam1);
if(f_ion>=1.0){
lam1 = lam2;
} else{
//Comment from MOBSE: Eq. A.6
lam1 = lam1 + f_ion*(lam2 - lam1);
}
}
}
if (fcenv<1){
double Rzams = get_Rzams(star);
lam2 = 0.42*std::pow(Rzams/star->getp(Radius::ID),0.4);
lam2 = 2*lam2;
}
if (fcenv<=0.0){
lambda_ce = lam2;
}
else if (fcenv>=1){
lambda_ce = lam1;
} else{
//Comment from MOBSE: Interpolate between HG and GB values depending on conv. envelope mass.
lambda_ce = lam2 + std::sqrt(fcenv) * (lam1-lam2);
}
return lambda_ce;
}
double Lambda::get_M0_BSE(const Star *s) {
if (Mzams_cachedM!=s->get_zams() or Zmet_cachedM!=s->get_Z()){
Star s_auxiliary(s, 0, s->get_zams(), s->get_Z(), "tms"); //Notice no need to seet pureHe false of true since pureHE cannot enter here
M0_cached = s_auxiliary.getp(Mass::ID);
Mzams_cachedM=s->get_zams();
Zmet_cachedM=s->get_Z();
}
return M0_cached;
}
double Lambda::get_Rzams(const Star *s) {
if (Mzams_cachedR!=s->get_zams() or Zmet_cachedR!=s->get_Z()){
Star s_auxiliary(s, 0, s->get_zams(), s->get_Z(), "zams"); //Notice no need to seet pureHe false of true since pureHE cannot enter here
Rzams_cached = s_auxiliary.getp(Radius::ID);
Mzams_cachedR=s->get_zams();
Zmet_cachedR=s->get_Z();
}
return Rzams_cached;
}
double Lambda::estimate_lambda_Klencki21(const Star *star, bool interpolate) {
if (star->aminakedhelium()){ //In this case we consider really only the pureHe stars since we have a fit for WR direcly from the tracks
return star->get_svpar_num("star_lambda_pureHe"); //No fit just return 0.5 as done in MOBSE/BSE/Claeys
}
//If it is the first time initialise the unique_ptr with the Lambda Klencki class
//and reset the flag
if (first_call){
if (interpolate) lambda_base_ptr = utilities::make_unique<Lambda_Klencki_interpolator>(star);
else lambda_base_ptr = utilities::make_unique<Lambda_Klencki>(star);
first_call=false;
}
//Return lambda from Klencki
return lambda_base_ptr->operator()(star);
}
double Lambda::estimate_lambda_Nanjing(const Star *star, bool interpolate) {
//If it is the first time initialise the unique_ptr with the Lambda Nanjing class
//and reset the flag
if (first_call){
if (interpolate) lambda_base_ptr = utilities::make_unique<Lambda_Nanjing_interpolator>(star);
else lambda_base_ptr = utilities::make_unique<Lambda_Nanjing>(star);
first_call=false;
}
//Return lambda from Nanjing
return lambda_base_ptr->operator()(star);
}
//Envelope binding energy
double Ebind::get(const Star *s) {
//If evolve_number>last_evolve_number, we have to obtain a new estimate for lambda
if(new_estimate_needed()){
//When we don't have a clear core-envelope separation return nan
if (s->haveienvelope()){
double Menv = s->aminakedhelium() ? s->getp(Mass::ID) - s->getp(MCO::ID) : s->getp(Mass::ID) - s->getp(MHE::ID);
double E = - (1/s->getp(Lambda::ID))*s->getp(Mass::ID)*Menv/(s->getp(Radius::ID));
set(E); //Set the new V and set evolve_number=last_evolve_number
}
else
set(0.); //Set the new V and set evolve_number=last_evolve_number
}
return V;
}
//Phase BSE
double PhaseBSE::get(const Star *s){
//If evolve_number>last_evolve_number, we have to obtain a new estimate for lambda
if(new_estimate_needed()){
set(s->get_bse_phase());
}
return V;
}
//Zams
double Zams::get(const Star *s){
//If evolve_number>last_evolve_number, we have to obtain a new estimate for lambda
if(new_estimate_needed()){
set(s->get_zams());
}
return V;
}
double Zmet::get(const Star* s){
if(new_estimate_needed()){
set(s->get_Z());
}
return V;
}
void dMcumul_RLO::update_from_binary(_UNUSED Star *s, const double &DV){
if (std::isnan(DV) or std::isinf(DV))
svlog.critical("Update from Binary of property " +
name()+" is nan or infinite",__FILE__,__LINE__);
//Check if we have just stopped a RLO phase
//e.g. when DV from RLO is 0 and dMcumu_RLO is not 0
//If this is the case reset the property V (i.e. V=0).
//We do not use directly the method reset()
//because we don't want to set V0 to 0.
//A non 0 zero value of V0 is needed if we have to restore the property after a repetitions
if (DV==0. and V!=0.)
V=value=0.0;
else
V = V + DV;
}
double Event::get(const Star *s) {
//If evolve_number>last_evolve_number, we have to obtain a new estimate
if(new_estimate_needed()){
if (!is_qhe_set and s->amifollowingQHE()){
is_qhe_set=true; //To avoid to enter here again
set(Lookup::EventsList::QHE);
}
else if (s->getp_0(Phase::ID)!=s->getp(Phase::ID) and s->getp(Worldtime::ID)>0){
set(Lookup::EventsList::ChangePhase);
}
else if (s->getp_0(RemnantType::ID)!=s->getp(RemnantType::ID) and s->getp(Worldtime::ID)>0){
set(Lookup::EventsList::ChangeRemnant);
}
else{
set(Lookup::EventsList::NoEvent);
}
}
return V;
}
void NSsalpha::set_remnant(Star *s) {
//First check if the star is a NS
if (s->amiNS()){
//2-We are sure the Star is a NS, so downcast from Staremant* to NS* to use the get_salpha method
const NSrem *n = static_cast<const NSrem*> (s->get_staremnant()); //Cast to NSrem pointer
sinalpha = n->get_salpha();
}
}
void Derived_Property::update_derived(Star *s) {
//Here we want to evolve the derived properties, without setting V0
//1-Save the V0 value
double _V0=V0;
//2-Evolve (depending on the stellar type)
if(!s->amiremnant()) evolve(s);
else if(s->aminakedco()) evolve_nakedco(s);
else if(!s->amiempty()) evolve_remnant(s);
//Notice: do nothing if the star is empty
//3-Restore the V0 value
set_0(_V0);
}
| 37.218299 | 227 | 0.61666 | [
"vector"
] |
4261fbc8a4f32f38ed3f7fd514e824fe097da335 | 3,199 | cpp | C++ | p1/project1.cpp | Xiao-Siqi/VE281-Project | 49ba5994f5289873c6a0abd84b6f5a954591f166 | [
"MIT"
] | null | null | null | p1/project1.cpp | Xiao-Siqi/VE281-Project | 49ba5994f5289873c6a0abd84b6f5a954591f166 | [
"MIT"
] | null | null | null | p1/project1.cpp | Xiao-Siqi/VE281-Project | 49ba5994f5289873c6a0abd84b6f5a954591f166 | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <math.h>
#include "sort1.hpp"
using namespace std;
struct point
{
int x;
int y;
};
void get_set(vector<point> &whole){
//input the whole point set
int num=0;
cin>>num;
for(int i=0;i<num;i++){
point p;
cin>>p.x>>p.y;
whole.push_back(p);
}
}
point find_p0(vector<point> &whole){
//first find p0 in the whole set
//second change p0's position to the beginning of the vector
point p0=whole[0];
int index=0;
int length=whole.size();
for(int i=1;i<=length-1;i++){
if(whole[i].y<p0.x){
p0.x=whole[i].x;
p0.y=whole[i].y;
index=i;
}
else if(whole[i].y==p0.y){
if(whole[i].x<p0.x){
p0.x=whole[i].x;
p0.y=whole[i].y;
index=i;
}
}
else ;
}
point tmp;
tmp=whole[0];
whole[0]=whole[index];
whole[index]=tmp;
return p0;
}
int ccw(point &p1,point &p2,point &p3){
return((p2.x-p1.x)*(p3.y-p1.y)-(p2.y-p1.y)*(p3.x-p1.x));
}
double distance(point x, point y)
{
//calculate the distance between two points.
return ((x.x - y.x) * (x.x - y.x) + (x.y - y.y) * (x.y - y.y));
}
void minimize_whole(vector<point> &whole){
//cancel all points that are duplicated
//cancel points on a line expect the farthest one with p0
//assume the vector whole is already sorted with the angle and p0 is already found
point p0=whole[0];
int index=1;
while((whole[index].x==p0.x)&&(whole[index].y==p0.y)){
//cancel all member the same as p0
whole.erase(whole.begin()+index);
}//index is still 1
while(index<=whole.size()-1){
//get out while loop when searching to the current last one member in the vector
if(ccw(p0,whole[index],whole[index+1])){
index++;
}
else if(ccw(p0,whole[index],whole[index+1])==0){
whole.erase(whole.begin()+index);
}
else{
//will not happen in ideal case
whole.erase(whole.begin()+index+1);
}
}
}
struct cmp
{
point p0;
bool operator ()(point &x,point &y){
return((ccw(p0,x,y)>0)||((ccw(p0,x,y)==0)&&(distance(p0,x)<distance(p0,y))));
}
};
void find_result(vector<point> &whole,vector<point> &S){
//note that p0 is still at the beginning of the whole vector
//vector S is the final convex hull set
//find S while at the beginning, S is an empty vector
for(int i=0;i<whole.size();i++){
while((S.size()>1)&&ccw(S[S.size()-2],S[S.size()-1],whole[i])<=0){
S.pop_back();
}
S.push_back(whole[i]);
}
}
int main(){
vector<point> whole;
get_set(whole);//all input are read
point p0=find_p0(whole);//p0 is found and is at the beginning of the vector
cmp compare={p0};
sort(whole.begin()+1,whole.end(),compare);
minimize_whole(whole);//no duplicated member in whole
vector<point> result;
find_result(whole,result);//result is found
for(int i=0;i<result.size();i++){
cout<<result[i].x<<' '<<result[i].y<<endl;
}
return 0;
} | 26.438017 | 88 | 0.559237 | [
"vector"
] |
4264803a703c0998346913dabe19c99f456e364c | 3,894 | cpp | C++ | src/meshfactory.cpp | jmpounders/radtrans | c6f2f6208f65c3eb08cbd5cf3af7a73172368295 | [
"BSL-1.0"
] | 1 | 2021-08-09T02:13:26.000Z | 2021-08-09T02:13:26.000Z | src/meshfactory.cpp | jmpounders/radtrans | c6f2f6208f65c3eb08cbd5cf3af7a73172368295 | [
"BSL-1.0"
] | null | null | null | src/meshfactory.cpp | jmpounders/radtrans | c6f2f6208f65c3eb08cbd5cf3af7a73172368295 | [
"BSL-1.0"
] | null | null | null | #include "meshfactory.h"
#include "mesh.h"
#include "moabmesh.h"
#include "log.h"
void
MeshFactory::createMeshFromInput(InputParser& input, MaterialFactory& materialFactory)
{
std::cout << "Making mesh... ";
std::vector<std::string> path(1,"Mesh");
std::vector<double> v;
// Get the name of the mesh
std::string meshName = input.getString(path, "name");
if (meshName == "empty") {
LOG_ERR("Must give the mesh a name; use the name parameter.");
}
// Load or create a mesh based on the mesh type
// The mesh type determines which derivative of the MeshInterface class gets instantiated
mesh_t meshType;
std::string meshTypeStr = input.getString(path, "type");
if (meshTypeStr == "moab") {
// Instantiate the class based on the MOAB mesh library
LOG("Creating MOAB mesh.");
meshType = MOAB;
MeshInterface* moabMesh = createNewMesh(meshName, meshType);
std::string meshFileName = input.getString(path, "file");
moabMesh->loadMesh(meshFileName);
std::string sweepFileName = input.getString(path, "sweep");
if (sweepFileName == "empty")
moabMesh->createDefaultMeshSweepOrder();
else
moabMesh->readMeshSweepOrder(sweepFileName);
std::string fileName("material");
std::string varName("/materials");
unsigned int* matArray;
HDF5Interface h5;
h5.open(fileName,'R');
HDFData* materialData = h5.readData(fileName, varName);
matArray = (unsigned int*)materialData->data;
h5.close(fileName);
MoabMesh* meshp = static_cast<MoabMesh*>(moabMesh);
for (int elementID=0; elementID<meshp->numElements(); elementID++)
meshp->setElementMat( elementID, materialFactory.getMaterial(matArray[elementID]) );
delete [] (unsigned int*)materialData->data;
delete materialData;
}
else if (meshTypeStr == "native" || meshTypeStr == "empty") {
// Instantiate the native mesh class (currently 1D only)
LOG("Creating native mesh.");
meshType = NATIVE;
v = input.getVector(path, "slabWidth");
if (v.size() == 0) {
LOG_ERR("Must specify the slab width; use the slabWidth parameter.");
}
double slabWidth = v[0];
v = input.getVector(path, "numCells");
if (v.size() == 0) {
LOG_ERR("Must specify number of cells in mesh; use the numCells parameter.");
}
int numCells = int(v[0]);
MeshInterface* mesh1d = createNewMesh(meshName, meshType, numCells+1, numCells);
static_cast<Mesh*>(mesh1d)->make1DUniform( slabWidth, numCells);
// Assign materials to mesh
std::string matName = "mat1";
for (int i=0; i<numCells; i++) {
mesh1d->getElement(i)->setMat( materialFactory.getMaterial(matName) );
}
}
std::cout << "done" << std::endl;
}
MeshInterface*
MeshFactory::createNewMesh(std::string& meshName, mesh_t meshType, int nNodesReserve, int nElementsReserve)
{
MeshInterface* mesh = getMesh(meshName);
if ( mesh ) {
std::cerr << "****** Mesh name collision" << std::endl;
return mesh;
}
switch (meshType) {
case NATIVE:
mesh = new Mesh(nNodesReserve, nElementsReserve);
break;
case MOAB:
mesh = new MoabMesh();
break;
}
_meshMap[meshName] = mesh;
return mesh;
}
MeshInterface*
MeshFactory::getMesh(std::string& meshName)
{
std::map<std::string, MeshInterface*>::iterator _meshIt;
_meshIt = _meshMap.find( meshName );
if ( _meshIt == _meshMap.end() ) {
return NULL;
}
else {
return _meshIt->second;
}
}
void
MeshFactory::deleteAllMesh()
{
for (std::map<std::string, MeshInterface*>::iterator it=_meshMap.begin(); it!=_meshMap.end(); ++it)
delete it->second;
}
void
MeshFactory::list()
{
std::cout << std::endl << "Mesh generated:" << std::endl;
for (std::map<std::string, MeshInterface*>::iterator it=_meshMap.begin(); it!=_meshMap.end(); ++it) {
std::cout << " " << it->first << std::endl;
}
}
| 28.217391 | 107 | 0.657935 | [
"mesh",
"vector"
] |
426666f1f5207dc24656ff0dd67d61fed6987411 | 2,643 | cxx | C++ | ChangingString.cxx | jackytck/topcoder | 5a83ce478d4f05aeb97062f8a30aa1d6fbc969d3 | [
"MIT"
] | null | null | null | ChangingString.cxx | jackytck/topcoder | 5a83ce478d4f05aeb97062f8a30aa1d6fbc969d3 | [
"MIT"
] | null | null | null | ChangingString.cxx | jackytck/topcoder | 5a83ce478d4f05aeb97062f8a30aa1d6fbc969d3 | [
"MIT"
] | null | null | null | // BEGIN CUT HERE
// PROBLEM STATEMENT
// You are given two strings A and B that have the same length and contain only lowercase letters ('a'-'z'). The distance between two letters is defined as the absolute value of their difference. The distance between A and B is defined as the sum of the differences between each letter in A and the letter in B at the same position. For example, the distance between "abcd" and "bcda" is 6 (1 + 1 + 1 + 3).
You must change exactly K characters in A into other lowercase letters. Return the minimum possible distance between A and B after you perform that change.
DEFINITION
Class:ChangingString
Method:distance
Parameters:string, string, int
Returns:int
Method signature:int distance(string A, string B, int K)
CONSTRAINTS
-A and B will each contain between 1 and 50 characters, inclusive.
-K will be between 1 and the length of A, inclusive.
-A and B will contain the same number of characters.
-A and B will contain only lowercase letters ('a' - 'z').
EXAMPLES
0)
"ab"
"ba"
2
Returns: 0
The minimum distance (equal to 0) can be achieved when we change 'a' to 'b' and 'b' to 'a'.
1)
"aa"
"aa"
2
Returns: 2
We must change both letters 'a' to some other letters. Changing them to 'b' results in the smallest distance.
2)
"aaa"
"baz"
1
Returns: 1
3)
"fdfdfdfdfdsfabasd"
"jhlakfjdklsakdjfk"
8
Returns: 24
4)
"aa"
"bb"
2
Returns: 0
// END CUT HERE
#line 72 "ChangingString.cxx"
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#define sz size()
#define PB push_back
#define clr(x) memset(x, 0, sizeof(x))
#define forn(i,n) for(__typeof(n) i = 0; i < (n); i++)
#define ford(i,n) for(int i = (n) - 1; i >= 0; i--)
#define forv(i,v) forn(i, v.sz)
#define For(i, st, en) for(__typeof(en) i = (st); i < (en); i++)
using namespace std;
class ChangingString {
public:
int distance(string A, string B, int K)
{
int ret = 0;
vector <int> a;
forn(i, A.sz)
{
a.PB(abs(A[i] - B[i]));
}
sort(a.begin(), a.end());
ford(i, a.sz)
{
forn(j, A.sz)
{
if(K != 0 && a[i] != 0 && abs(A[j] - B[j]) == a[i])
{
A[j] = B[j];
K--;
}
}
}
forn(i, A.sz)
{
ret += abs(A[i] - B[i]);
}
return ret + K;
}
};
| 20.330769 | 409 | 0.619372 | [
"vector"
] |
426c1ce47eed0148a7d67f570bdecfac4248c645 | 2,274 | cpp | C++ | src/apps/backend/car/lane_detector_service.cpp | raymanfx/seraphim | 4d388d21831d349fe1085bc3cb7c73f5d2b103a7 | [
"MIT"
] | null | null | null | src/apps/backend/car/lane_detector_service.cpp | raymanfx/seraphim | 4d388d21831d349fe1085bc3cb7c73f5d2b103a7 | [
"MIT"
] | null | null | null | src/apps/backend/car/lane_detector_service.cpp | raymanfx/seraphim | 4d388d21831d349fe1085bc3cb7c73f5d2b103a7 | [
"MIT"
] | null | null | null | /*
* (C) Copyright 2019
* The Seraphim Project Developers.
*
* SPDX-License-Identifier: MIT
*/
#include <seraphim/image.h>
#include <seraphim/polygon.h>
#include <utils.h>
#include "lane_detector_service.h"
using namespace sph;
using namespace sph::car;
LaneDetectorService::LaneDetectorService(std::shared_ptr<sph::car::LaneDetector> detector) {
m_detector = detector;
}
bool LaneDetectorService::handle_request(const Seraphim::Request &req, Seraphim::Response &res) {
if (req.inner().Is<Seraphim::Car::LaneDetector::DetectionRequest>()) {
Seraphim::Car::LaneDetector::DetectionRequest inner_req;
Seraphim::Car::LaneDetector::DetectionResponse inner_res;
req.inner().UnpackTo(&inner_req);
if (handle_detection_request(inner_req, inner_res)) {
res.mutable_inner()->PackFrom(inner_res);
return true;
}
}
return false;
}
bool LaneDetectorService::handle_detection_request(
const Seraphim::Car::LaneDetector::DetectionRequest &req,
Seraphim::Car::LaneDetector::DetectionResponse &res) {
CoreImage image;
Polygon<int> polyroi;
std::vector<Polygon<int>> lanes;
if (!sph::backend::Image2DtoImage(req.image(), image)) {
return false;
}
if (req.has_polyroi()) {
std::vector<Point2<int>> points;
for (const auto &point : req.polyroi().points()) {
points.emplace_back(point.x(), point.y());
}
polyroi = Polygon<int>(points);
m_detector->set_roi(polyroi);
} else {
m_detector->set_roi({});
}
m_detector->detect(image, lanes);
for (const auto &lane : lanes) {
Seraphim::Car::LaneDetector::Lane *lane_ = res.add_lanes();
lane_->mutable_bottomleft()->set_x(lane.vertices()[0].x);
lane_->mutable_bottomleft()->set_y(lane.vertices()[0].y);
lane_->mutable_topleft()->set_x(lane.vertices()[1].x);
lane_->mutable_topleft()->set_y(lane.vertices()[1].y);
lane_->mutable_topright()->set_x(lane.vertices()[2].x);
lane_->mutable_topright()->set_y(lane.vertices()[2].y);
lane_->mutable_bottomright()->set_x(lane.vertices()[3].x);
lane_->mutable_bottomright()->set_y(lane.vertices()[3].y);
}
return true;
}
| 31.150685 | 97 | 0.649077 | [
"vector"
] |
426d66bb0adc3e77e980161e02321b2cd595d1d1 | 130,060 | cpp | C++ | src/acmi/src/acmitape.cpp | Terebinth/freefalcon-central | c28d807183ab447ef6a801068aa3769527d55deb | [
"BSD-2-Clause"
] | 117 | 2015-01-13T14:48:49.000Z | 2022-03-16T01:38:19.000Z | src/acmi/src/acmitape.cpp | darongE/freefalcon-central | c28d807183ab447ef6a801068aa3769527d55deb | [
"BSD-2-Clause"
] | 4 | 2015-05-01T13:09:53.000Z | 2017-07-22T09:11:06.000Z | src/acmi/src/acmitape.cpp | darongE/freefalcon-central | c28d807183ab447ef6a801068aa3769527d55deb | [
"BSD-2-Clause"
] | 78 | 2015-01-13T09:27:47.000Z | 2022-03-18T14:39:09.000Z | #pragma optimize( "", off )
#include <windows.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <direct.h>
#include <tchar.h>
#include "Graphics/Include/Setup.h"
#include "Graphics/Include/drawsgmt.h"
#include "Graphics/Include/drawtrcr.h"
#include "Graphics/Include/rViewpnt.h"
#include "Graphics/Include/draw2d.h"
#include "Graphics/Include/drawBSP.h"
#include "Graphics/Include/drawpole.h"
#include "Graphics/Include/drawplat.h"
#include "Graphics/Include/drawbrdg.h"
#include "Graphics/Include/renderow.h"
#include "falclib.h"
#include "fsound.h"
#include "Graphics/Include/grTypes.h"
#include "codelib/tools/lists/lists.h"
#include "debuggr.h"
#include "AcmiTape.h"
#include "sim/include/misctemp.h" // for Clamp function.
#include "sim/include/simbase.h"
#include "sim/include/otwdrive.h"
#include "sim/include/sfx.h"
#include "acmirec.h"
#include "sim/include/simfeat.h"
#include "Campaign/include/CmpGlobl.h"
#include "Campaign/include/evtparse.h"
#include "ClassTbl.h"
#include "Entity.h"
#include "ui/include/events.h"
#include "f4vu.h"
#include "feature.h"
#include "campstr.h"
#include "team.h"
#include "acmihash.h"
//////////////////////////////////////////////////////////////////////////
/// 3-23 BING
#include "AcmiView.h"
#include "AcmiUI.h"
extern ACMIView *acmiView;
long tempTarget; // for missile lock.
//////////////////////////////////////////////////////////////////////////
void CalcTransformMatrix(SimBaseClass* theObject);
void CreateDrawable(SimBaseClass* theObject, float objectScale);
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// these are for raw data import
LIST *importEntityList;
LIST *importFeatList;
LIST *importPosList;
LIST *importEventList;
LIST *importEntEventList;
LIST *importEntityListEnd;
LIST *importFeatListEnd;
LIST *importPosListEnd;
LIST *importEventListEnd;
LIST *importEntEventListEnd;
LIST *importFeatEventList;
LIST *importFeatEventListEnd;
int importNumPos;
int importNumEnt;
int importNumFeat;
int importNumFeatEvents;
int importNumEvents;
int importNumEntEvents;
int importEntOffset;
int importFeatOffset;
int importFeatEventOffset;
int importPosOffset;
int importEventOffset;
int importEntEventOffset;
ACMIEventTrailer *importEventTrailerList;
extern long TeamSimColorList[NUM_TEAMS];
LIST * AppendToEndOfList(LIST * list, LIST **end, void * node);
void DestroyTheList(LIST * list);
extern float CalcKIAS(float, float);
ACMI_CallRec *ACMI_Callsigns = NULL;
ACMI_CallRec *Import_Callsigns = NULL;
long import_count = 0;
//extern GLOBAL_SPEED;
//extern GLOBAL_ALTITUDE;
//extern GLOBAL_HEADING;
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void DefaultForwardACMIGeneralEventCallback
(
ACMITape *,
EventIdData eventId,
void *,
void *
)
{
MonoPrint
(
"General event occured in forward ACMI Tape play --> event type: %d.\n",
eventId.type
);
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void DefaultReverseACMIGeneralEventCallback
(
ACMITape *,
EventIdData eventId,
void *,
void *
)
{
MonoPrint
(
"General event occured in reverse ACMI Tape play --> event type: %d.\n",
eventId.type
);
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/*
** Callback compare function from qsort.
*/
int CompareEventTrailer(const void *p1, const void *p2)
{
ACMIEventTrailer *t1 = (ACMIEventTrailer *)p1;
ACMIEventTrailer *t2 = (ACMIEventTrailer *)p2;
if (t1->timeEnd < t2->timeEnd)
return -1;
else if (t1->timeEnd > t2->timeEnd)
return 1;
else
return 0;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void DestroyACMIRawPositionDataList(LIST *list)
{
// LIST_DESTROY (list, (PFV)DeleteACMIRawPositionData);
DestroyTheList(list);
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void DeleteACMIRawPositionData(ACMIRawPositionData* rawPositionData)
{
delete rawPositionData;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void DeleteACMIEntityData(ACMIEntityData *data)
{
delete data;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void DeleteACMIEventHeader(ACMIEventHeader *data)
{
delete data;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void DeleteACMIEntityPositionData(ACMIEntityPositionData *data)
{
delete data;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void DeleteACMIFeatEventImportData(ACMIFeatEventImportData *data)
{
delete data;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
ACMITape::ACMITape(char *name, RenderOTW *renderer, RViewPoint *viewPoint)
{
int i, numEntities;
char fullName[MAX_PATH];
ACMIEntityData *e;
long length = 0;
char *callsigns = NULL;
long numcalls = 0;
// initialize storage for drawable poled objects
#ifdef USE_SH_POOLS
DrawablePoled::InitializeStorage();
#endif
F4Assert(name not_eq NULL);
_tape = NULL;
_entityReadHeads = NULL;
_simTapeEntities = NULL;
_simTapeFeatures = NULL;
_activeEventHead = NULL;
_eventList = NULL;
_screenCapturing = FALSE;
_wingTrails = FALSE;
_tapeObjScale = 1.0f;
// set our render and viewpoint
_renderer = renderer;
_viewPoint = viewPoint;
Init();
// Open up a map file with the given name.
// edg note on hack: right now, ALWAYS do an import from the acmi.flt
// file to convert to a tape file. Later we'll probably want to import
// right after an ACMIU record session to get into .vhs format
//strcpy( fullName, "campaign\\save\\fltfiles\\" );
strcpy(fullName, "acmibin\\");
strcat(fullName, name);
// commented out if statement for quick testing....
// if ( Import( fullName ) )
{
// create the memory mapping
length = OpenTapeFile(fullName);
// just test
if (IsLoaded())
{
numEntities = NumEntities();
for (i = 0; i < numEntities; i++)
{
e = EntityData(i);
MonoPrint("Entity %d: Type = %d, Id = %d, Offset = %d\n",
i,
e->type,
e->uniqueID,
e->firstPositionDataOffset);
}
// CloseTapeFile();
}
else
{
MonoPrint("Unable to test memory mapped tape file\n");
}
}
// If it loaded, do any additional setup.
if (IsLoaded())
{
// Setup Callsigns...
callsigns = (char*)GetCallsignList(&numcalls);
if (((char *)callsigns - (char *)_tape) < length and numcalls > 0) // there are callsigns...
{
ACMI_Callsigns = new ACMI_CallRec[numcalls];
memcpy(ACMI_Callsigns, callsigns, sizeof(ACMI_CallRec)*numcalls);
}
numEntities = NumEntities();
// Setup entity event callbacks. and read heads
_entityReadHeads = new ACMIEntityReadHead[numEntities];
F4Assert(_entityReadHeads not_eq NULL);
for (i = 0; i < numEntities; i++)
{
// set the read heads to the first position
e = EntityData(i);
_entityReadHeads[i].positionDataOffset = e->firstPositionDataOffset;
_entityReadHeads[i].eventDataOffset = e->firstEventDataOffset;
}
// Setup general event callbacks.
SetGeneralEventCallbacks
(
DefaultForwardACMIGeneralEventCallback,
DefaultReverseACMIGeneralEventCallback,
NULL
);
// setup the sim tape entities
SetupSimTapeEntities();
// create an array of ActiveEvent pointers -- 1 for every event
_eventList = new ActiveEvent * [ _tapeHdr.numEvents ];
// make sure they're null
memset(_eventList, 0, sizeof(ActiveEvent *) * _tapeHdr.numEvents);
// set the first and last event trailer pointers
if (_tapeHdr.numEvents == 0)
{
_firstEventTrailer = NULL;
_lastEventTrailer = NULL;
}
else
{
_firstEventTrailer = (ACMIEventTrailer *)((char *)_tape + _tapeHdr.firstEventTrailerOffset);
_lastEventTrailer = _firstEventTrailer + (_tapeHdr.numEvents - 1);
}
_generalEventReadHeadTrailer = _firstEventTrailer;
if (_tapeHdr.numFeatEvents == 0)
{
_firstFeatEvent = NULL;
_lastFeatEvent = NULL;
}
else
{
_firstFeatEvent = (ACMIFeatEvent *)((char *)_tape + _tapeHdr.firstFeatEventOffset);
_lastFeatEvent = _firstFeatEvent + (_tapeHdr.numFeatEvents - 1);
}
_featEventReadHead = _firstFeatEvent;
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
ACMITape::~ACMITape()
{
// Delete Callsigns
if (ACMI_Callsigns)
{
delete ACMI_Callsigns;
ACMI_Callsigns = NULL;
}
Init();
#ifdef USE_SH_POOLS
DrawablePoled::ReleaseStorage();
#endif
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void ACMITape::Init()
{
if (_entityReadHeads)
{
delete [] _entityReadHeads;
_entityReadHeads = NULL;
}
if (_simTapeEntities)
{
CleanupSimTapeEntities();
}
if (_eventList)
{
CleanupEventList();
}
SetGeneralEventCallbacks
(
NULL,
NULL,
NULL
);
if (_tape)
{
// close file mapping.
CloseTapeFile();
}
_playVelocity = 0.0;
_playAcceleration = 0.0;
_maxPlaySpeed = 4.0;
_simTime = 0.0;
_stepTrail = 0.0;
_lastRealTime = 0.0;
_unpause = FALSE;
_paused = TRUE;
_simulateOnly = FALSE;
_generalEventReadHeadHeader = 0;
_featEventReadHead = NULL;
_generalEventReadHeadTrailer = NULL;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
BOOL ReadRawACMIPositionData
(
FILE *flightFile,
ACMIRawPositionData &rawPositionData
)
{
int
result;
fscanf
(
flightFile,
"%d %d",
&rawPositionData.type,
&rawPositionData.uniqueID
);
// We don't need to check the status of our last two fscanf calls, because
// if they fail, this one will too.
result = fscanf
(
flightFile,
"%f %f %f %f %f %f\n",
&rawPositionData.entityPosData.posData.x,
&rawPositionData.entityPosData.posData.y,
&rawPositionData.entityPosData.posData.z,
&rawPositionData.entityPosData.posData.pitch,
&rawPositionData.entityPosData.posData.roll,
&rawPositionData.entityPosData.posData.yaw
);
// insure pitch roll and yaw are positive (edg:?)
// or in 0 - 2PI range
/* nah, this ain't right.... need to fix songy's stuff
if ( rawPositionData.entityPosData.pitch < 0.0f )
rawPositionData.entityPosData.pitch += 2.0f * PI;
if ( rawPositionData.entityPosData.roll < 0.0f )
rawPositionData.entityPosData.roll += 2.0f * PI;
if ( rawPositionData.entityPosData.yaw < 0.0f )
rawPositionData.entityPosData.yaw += 2.0f * PI;
*/
return ( not result or result == EOF ? FALSE : TRUE);
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void CleanupACMIImportPositionData
(
FILE *flightFile,
ACMIRawPositionData *rawPositionData
)
{
if (flightFile not_eq NULL)
{
fclose(flightFile);
}
if (rawPositionData not_eq NULL)
{
delete rawPositionData;
}
if (importEntityList not_eq NULL)
{
DestroyTheList(importEntityList);
importEntityList = NULL;
}
if (importFeatList not_eq NULL)
{
DestroyTheList(importFeatList);
importFeatList = NULL;
}
if (importPosList not_eq NULL)
{
DestroyTheList(importPosList);
importPosList = NULL;
}
if (importEntEventList not_eq NULL)
{
DestroyTheList(importEntEventList);
importEntEventList = NULL;
}
if (importEventList not_eq NULL)
{
DestroyTheList(importEventList);
importEventList = NULL;
}
if (importEventTrailerList not_eq NULL)
{
delete [] importEventTrailerList;
importEventTrailerList = NULL;
}
if (importFeatEventList not_eq NULL)
{
DestroyTheList(importFeatEventList);
importFeatEventList = NULL;
}
if (Import_Callsigns)
{
delete Import_Callsigns;
Import_Callsigns = NULL;
import_count = 0;
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
BOOL ACMITape::Import(char *inFltFile, char *outTapeFileName)
{
FILE
*flightFile;
ACMIRawPositionData
*rawPositionData = NULL;
ACMIEventHeader
*ehdr = NULL;
ACMIFeatEventImportData
*fedata = NULL;
float
begTime,
endTime;
ACMITapeHeader tapeHdr;
ACMIRecHeader hdr;
ACMIGenPositionData genpos;
ACMIFeaturePositionData featpos;
ACMITracerStartData tracer;
ACMIStationarySfxData sfx;
ACMIMovingSfxData msfx;
ACMISwitchData sd;
ACMIDOFData dd;
ACMIFeatureStatusData fs;
// zero our counters
importNumFeat = 0;
importNumPos = 0;
importNumEnt = 0;
importNumEvents = 0;
importNumFeatEvents = 0;
importNumEntEvents = 0;
// zero out position list
importFeatList = NULL;
importFeatEventList = NULL;
importPosList = NULL;
importEventList = NULL;
importEntEventList = NULL;
importEventTrailerList = NULL;
// this value comes from tod type record
tapeHdr.todOffset = 0.0f;
// Load flight file for positional data.
//flightFile = fopen("campaign\\save\\fltfiles\\acmi.flt", "rb");
flightFile = fopen(inFltFile, "rb");
if (flightFile == NULL)
{
MonoPrint("Error opening acmi flight file");
return FALSE;
}
begTime = -1.0;
endTime = 0.0;
MonoPrint("ACMITape Import: Reading Raw Data ....\n");
while (fread(&hdr, sizeof(ACMIRecHeader), 1, flightFile))
{
// now read in the rest of the record depending on type
switch (hdr.type)
{
case ACMIRecTodOffset:
tapeHdr.todOffset = hdr.time;
break;
case ACMIRecGenPosition:
case ACMIRecMissilePosition:
case ACMIRecChaffPosition:
case ACMIRecFlarePosition:
case ACMIRecAircraftPosition:
// Read the data
if ( not fread(&genpos, sizeof(ACMIGenPositionData), 1, flightFile))
{
CleanupACMIImportPositionData(flightFile, rawPositionData);
return FALSE;
}
if (hdr.type == ACMIRecAircraftPosition)
fread(&tempTarget, sizeof(tempTarget), 1, flightFile);
else
tempTarget = -1;
// Allocate a new data node.
F4Assert(rawPositionData == NULL);
rawPositionData = new ACMIRawPositionData;
F4Assert(rawPositionData not_eq NULL);
// fill in raw position data
rawPositionData->uniqueID = genpos.uniqueID;
rawPositionData->type = genpos.type;
if (hdr.type == ACMIRecMissilePosition)
rawPositionData->flags = ENTITY_FLAG_MISSILE;
else if (hdr.type == ACMIRecAircraftPosition)
rawPositionData->flags = ENTITY_FLAG_AIRCRAFT;
else if (hdr.type == ACMIRecChaffPosition)
rawPositionData->flags = ENTITY_FLAG_CHAFF;
else if (hdr.type == ACMIRecFlarePosition)
rawPositionData->flags = ENTITY_FLAG_FLARE;
else
rawPositionData->flags = 0;
rawPositionData->entityPosData.time = hdr.time;
rawPositionData->entityPosData.type = PosTypePos;
// remove rawPositionData->entityPosData.teamColor = genpos.teamColor;
// remove strcpy((char*)rawPositionData->entityPosData.label, (char*)genpos.label);
rawPositionData->entityPosData.posData.x = genpos.x;
rawPositionData->entityPosData.posData.y = genpos.y;
rawPositionData->entityPosData.posData.z = genpos.z;
rawPositionData->entityPosData.posData.roll = genpos.roll;
rawPositionData->entityPosData.posData.pitch = genpos.pitch;
rawPositionData->entityPosData.posData.yaw = genpos.yaw;
rawPositionData->entityPosData.posData.radarTarget = tempTarget;
// Append our new position data.
importPosList = AppendToEndOfList(importPosList, &importPosListEnd, rawPositionData);
rawPositionData = NULL;
// bump counter
importNumPos++;
break;
case ACMIRecTracerStart:
// Read the data
if ( not fread(&tracer, sizeof(ACMITracerStartData), 1, flightFile))
{
CleanupACMIImportPositionData(flightFile, rawPositionData);
return FALSE;
}
// Allocate a new data node.
F4Assert(ehdr == NULL);
ehdr = new ACMIEventHeader;
F4Assert(ehdr not_eq NULL);
// fill in data
ehdr->eventType = hdr.type;
ehdr->time = hdr.time;
ehdr->timeEnd = hdr.time + 2.5F;
ehdr->index = importNumEvents;
ehdr->x = tracer.x;
ehdr->y = tracer.y;
ehdr->z = tracer.z;
ehdr->dx = tracer.dx;
ehdr->dy = tracer.dy;
ehdr->dz = tracer.dz;
// Append our new data.
importEventList = AppendToEndOfList(importEventList, &importEventListEnd, ehdr);
ehdr = NULL;
// bump counter
importNumEvents++;
break;
case ACMIRecStationarySfx:
// Read the data
if ( not fread(&sfx, sizeof(ACMIStationarySfxData), 1, flightFile))
{
CleanupACMIImportPositionData(flightFile, rawPositionData);
return FALSE;
}
// Allocate a new data node.
F4Assert(ehdr == NULL);
ehdr = new ACMIEventHeader;
F4Assert(ehdr not_eq NULL);
// fill in data
ehdr->eventType = hdr.type;
ehdr->index = importNumEvents;
ehdr->time = hdr.time;
ehdr->timeEnd = hdr.time + sfx.timeToLive;
ehdr->x = sfx.x;
ehdr->y = sfx.y;
ehdr->z = sfx.z;
ehdr->type = sfx.type;
ehdr->scale = sfx.scale;
// Append our new data.
importEventList = AppendToEndOfList(importEventList, &importEventListEnd, ehdr);
ehdr = NULL;
// bump counter
importNumEvents++;
break;
case ACMIRecFeatureStatus:
// Read the data
if ( not fread(&fs, sizeof(ACMIFeatureStatusData), 1, flightFile))
{
CleanupACMIImportPositionData(flightFile, rawPositionData);
return FALSE;
}
// Allocate a new data node.
F4Assert(fedata == NULL);
fedata = new ACMIFeatEventImportData;
F4Assert(fedata not_eq NULL);
// fill in data
fedata->uniqueID = fs.uniqueID;
fedata->data.index = -1; // will be filled in later
fedata->data.time = hdr.time;
fedata->data.newStatus = fs.newStatus;
fedata->data.prevStatus = fs.prevStatus;
// Append our new data.
importFeatEventList = AppendToEndOfList(importFeatEventList, &importFeatEventListEnd, fedata);
fedata = NULL;
// bump counter
importNumFeatEvents++;
break;
// not ready for these yet
case ACMIRecMovingSfx:
// Read the data
if ( not fread(&msfx, sizeof(ACMIMovingSfxData), 1, flightFile))
{
CleanupACMIImportPositionData(flightFile, rawPositionData);
return FALSE;
}
// Allocate a new data node.
F4Assert(ehdr == NULL);
ehdr = new ACMIEventHeader;
F4Assert(ehdr not_eq NULL);
// fill in data
ehdr->eventType = hdr.type;
ehdr->index = importNumEvents;
ehdr->time = hdr.time;
ehdr->timeEnd = hdr.time + msfx.timeToLive;
ehdr->x = msfx.x;
ehdr->y = msfx.y;
ehdr->z = msfx.z;
ehdr->dx = msfx.dx;
ehdr->dy = msfx.dy;
ehdr->dz = msfx.dz;
ehdr->flags = msfx.flags;
ehdr->user = msfx.user;
ehdr->type = msfx.type;
ehdr->scale = msfx.scale;
// Append our new data.
importEventList = AppendToEndOfList(importEventList, &importEventListEnd, ehdr);
ehdr = NULL;
// bump counter
importNumEvents++;
break;
case ACMIRecSwitch:
// Read the data
if ( not fread(&sd, sizeof(ACMISwitchData), 1, flightFile))
{
CleanupACMIImportPositionData(flightFile, rawPositionData);
return FALSE;
}
// Allocate a new data node.
F4Assert(rawPositionData == NULL);
rawPositionData = new ACMIRawPositionData;
F4Assert(rawPositionData not_eq NULL);
// fill in raw position data
rawPositionData->uniqueID = sd.uniqueID;
rawPositionData->type = sd.type;
rawPositionData->flags = 0;
rawPositionData->entityPosData.time = hdr.time;
rawPositionData->entityPosData.type = PosTypeSwitch;
rawPositionData->entityPosData.switchData.switchNum = sd.switchNum;
rawPositionData->entityPosData.switchData.switchVal = sd.switchVal;
rawPositionData->entityPosData.switchData.prevSwitchVal = sd.prevSwitchVal;
// Append our new position data.
importEntEventList = AppendToEndOfList(importEntEventList, &importEntEventListEnd, rawPositionData);
rawPositionData = NULL;
// bump counter
importNumEntEvents++;
break;
case ACMIRecDOF:
// Read the data
if ( not fread(&dd, sizeof(ACMIDOFData), 1, flightFile))
{
CleanupACMIImportPositionData(flightFile, rawPositionData);
return FALSE;
}
// Allocate a new data node.
F4Assert(rawPositionData == NULL);
rawPositionData = new ACMIRawPositionData;
F4Assert(rawPositionData not_eq NULL);
// fill in raw position data
rawPositionData->uniqueID = dd.uniqueID;
rawPositionData->type = dd.type;
rawPositionData->flags = 0;
rawPositionData->entityPosData.time = hdr.time;
rawPositionData->entityPosData.type = PosTypeDOF;
rawPositionData->entityPosData.dofData.DOFNum = dd.DOFNum;
rawPositionData->entityPosData.dofData.DOFVal = dd.DOFVal;
rawPositionData->entityPosData.dofData.prevDOFVal = dd.prevDOFVal;
// Append our new position data.
importEntEventList = AppendToEndOfList(importEntEventList, &importEntEventListEnd, rawPositionData);
rawPositionData = NULL;
// bump counter
importNumEntEvents++;
break;
case ACMIRecFeaturePosition:
// Read the data
if ( not fread(&featpos, sizeof(ACMIFeaturePositionData), 1, flightFile))
{
CleanupACMIImportPositionData(flightFile, rawPositionData);
return FALSE;
}
// Allocate a new data node.
F4Assert(rawPositionData == NULL);
rawPositionData = new ACMIRawPositionData;
F4Assert(rawPositionData not_eq NULL);
// fill in raw position data
rawPositionData->uniqueID = featpos.uniqueID;
rawPositionData->leadIndex = featpos.leadUniqueID;
rawPositionData->specialFlags = featpos.specialFlags;
rawPositionData->slot = featpos.slot;
rawPositionData->type = featpos.type;
rawPositionData->flags = ENTITY_FLAG_FEATURE;
rawPositionData->entityPosData.time = hdr.time;
rawPositionData->entityPosData.type = PosTypePos;
rawPositionData->entityPosData.posData.x = featpos.x;
rawPositionData->entityPosData.posData.y = featpos.y;
rawPositionData->entityPosData.posData.z = featpos.z;
rawPositionData->entityPosData.posData.roll = featpos.roll;
rawPositionData->entityPosData.posData.pitch = featpos.pitch;
rawPositionData->entityPosData.posData.yaw = featpos.yaw;
// Append our new position data.
importPosList = AppendToEndOfList(importPosList, &importPosListEnd, rawPositionData);
rawPositionData = NULL;
// bump counter
importNumPos++;
break;
case ACMICallsignList:
// Read the data
if ( not fread(&import_count, sizeof(long), 1, flightFile))
{
CleanupACMIImportPositionData(flightFile, rawPositionData);
return FALSE;
}
F4Assert(Import_Callsigns == NULL);
Import_Callsigns = new ACMI_CallRec[import_count];
F4Assert(Import_Callsigns not_eq NULL);
if ( not fread(Import_Callsigns, import_count * sizeof(ACMI_CallRec), 1, flightFile))
{
CleanupACMIImportPositionData(flightFile, rawPositionData);
return FALSE;
}
break;
default:
// KCK: I was hitting this repeatidly.. So I'm making it a ShiAssert (and therefore ignorable)
// ShiAssert(0);
break;
}
// save begin and end times
if (hdr.type not_eq ACMIRecTodOffset)
{
if (begTime < 0.0)
begTime = hdr.time;
if (hdr.time > endTime)
endTime = hdr.time;
}
}
// build the importEntityList
MonoPrint("ACMITape Import: Parsing Entities ....\n");
ParseEntities();
// setup the tape header
tapeHdr.fileID = 'TAPE';
tapeHdr.numEntities = importNumEnt;
tapeHdr.numFeat = importNumFeat;
tapeHdr.entityBlockOffset = sizeof(ACMITapeHeader);
tapeHdr.featBlockOffset = tapeHdr.entityBlockOffset +
sizeof(ACMIEntityData) * importNumEnt;
tapeHdr.timelineBlockOffset = tapeHdr.featBlockOffset +
sizeof(ACMIEntityData) * importNumFeat;
tapeHdr.firstEntEventOffset = tapeHdr.timelineBlockOffset +
sizeof(ACMIEntityPositionData) * importNumPos;
tapeHdr.firstGeneralEventOffset = tapeHdr.firstEntEventOffset +
sizeof(ACMIEntityPositionData) * importNumEntEvents;
tapeHdr.firstEventTrailerOffset = tapeHdr.firstGeneralEventOffset +
sizeof(ACMIEventHeader) * importNumEvents;
tapeHdr.firstFeatEventOffset = tapeHdr.firstEventTrailerOffset +
sizeof(ACMIEventTrailer) * importNumEvents;
tapeHdr.firstTextEventOffset = tapeHdr.firstFeatEventOffset +
sizeof(ACMIFeatEvent) * importNumFeatEvents;
tapeHdr.numEntityPositions = importNumPos;
tapeHdr.numEvents = importNumEvents;
tapeHdr.numFeatEvents = importNumFeatEvents;
tapeHdr.numEntEvents = importNumEntEvents;
tapeHdr.totPlayTime = endTime - begTime;
tapeHdr.startTime = begTime;
// set up the chain offsets of entity positions
MonoPrint("ACMITape Import: Threading Positions ....\n");
ThreadEntityPositions(&tapeHdr);
// set up the chain offsets of entity events
MonoPrint("ACMITape Import: Threading Entity Events ....\n");
ThreadEntityEvents(&tapeHdr);
// Calculate size of .vhs file.
tapeHdr.fileSize = tapeHdr.timelineBlockOffset +
sizeof(ACMIEntityPositionData) * importNumPos +
sizeof(ACMIEntityPositionData) * importNumEntEvents +
sizeof(ACMIEventHeader) * importNumEvents +
sizeof(ACMIFeatEvent) * importNumFeatEvents +
sizeof(ACMIEventTrailer) * importNumEvents;
// Open a writecopy file mapping.
// Write out file in .vhs format.
MonoPrint("ACMITape Import: Writing Tape File ....\n");
WriteTapeFile(outTapeFileName, &tapeHdr);
// Cleanup import data.
CleanupACMIImportPositionData(flightFile, rawPositionData);
// now delete the acmi.flt file
//remove("campaign\\save\\fltfiles\\acmi.flt");
remove(inFltFile);
return TRUE;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void ACMITape::ParseEntities(void)
{
int
i = 0,
count = 0;
LIST
*entityPtr,
*rawList;
ACMIRawPositionData
*entityType;
ACMIEntityData
*importEntityInfo;
importEntityList = NULL;
rawList = importPosList;
for (count = 0; count < importNumPos; count++)
{
// rawList = LIST_NTH(importPosList, count);
entityType = (ACMIRawPositionData *)rawList->node;
if (entityType->flags bitand ENTITY_FLAG_FEATURE)
{
// look for existing entity
entityPtr = importFeatList;
for (i = 0; i < importNumFeat; i++)
{
// entityPtr = LIST_NTH(importEntityList, i);
importEntityInfo = (ACMIEntityData *)entityPtr->node;
if (entityType->uniqueID == importEntityInfo->uniqueID)
{
break;
}
entityPtr = entityPtr->next;
}
// create new import entity record
if (i == importNumFeat)
{
importEntityInfo = new ACMIEntityData;
importEntityInfo->count = 0;
F4Assert(importEntityInfo);
importEntityInfo->uniqueID = entityType->uniqueID;
importEntityInfo->type = entityType->type;
importEntityInfo->flags = entityType->flags;
importEntityInfo->leadIndex = entityType->leadIndex;
importEntityInfo->specialFlags = entityType->specialFlags;
importEntityInfo->slot = entityType->slot;
importFeatList = AppendToEndOfList(importFeatList, &importFeatListEnd, importEntityInfo);
importNumFeat++;
}
}
else
{
// not a feature
// look for existing entity
entityPtr = importEntityList;
for (i = 0; i < importNumEnt; i++)
{
// entityPtr = LIST_NTH(importEntityList, i);
importEntityInfo = (ACMIEntityData *)entityPtr->node;
if (entityType->uniqueID == importEntityInfo->uniqueID)
{
break;
}
entityPtr = entityPtr->next;
}
// create new import entity record
if (i == importNumEnt)
{
importEntityInfo = new ACMIEntityData;
importEntityInfo->count = 0;
F4Assert(importEntityInfo);
importEntityInfo->uniqueID = entityType->uniqueID;
importEntityInfo->type = entityType->type;
importEntityInfo->flags = entityType->flags;
// remove importEntityInfo->teamColor = entityType->entityPosData.teamColor;
// remove strcpy((importEntityInfo->label), (char*) entityType->entityPosData.label);
importEntityList = AppendToEndOfList(importEntityList, &importEntityListEnd, importEntityInfo);
importNumEnt++;
}
}
rawList = rawList->next;
}
// Count instances of each unique type
LIST* list1 = importEntityList;
LIST* list2;
ACMIEntityData* thing1;
ACMIEntityData* thing2;
int objCount;
while (list1)
{
thing1 = (ACMIEntityData*)list1->node;
if (thing1->count == 0)
{
thing1->count = 1;
objCount = 2;
list2 = list1->next;
while (list2)
{
thing2 = (ACMIEntityData*)list2->node;
if (thing2->type == thing1->type and thing2->count == 0)
{
thing2->count = objCount;
objCount ++;
}
list2 = list2->next;
}
}
list1 = list1->next;
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/*
** Description:
** At this point importEntList and importPosList should be populated.
** Now, we're going to have to setup the offset pointers to do the
** file mapping. Each entity chains back and forth thru its position
** list.
*/
void ACMITape::ThreadEntityPositions(ACMITapeHeader *tapeHdr)
{
int i, j;
long prevOffset;
LIST *entityListPtr, *posListPtr, *featListPtr;
ACMIEntityData *entityPtr, *featPtr;
ACMIRawPositionData *posPtr;
ACMIRawPositionData *prevPosPtr;
ACMIFeatEventImportData *fePtr;
BOOL foundFirst;
long currOffset;
// we run an outer and inner loop here.
// the outer loops steps thru each entity
// the inner loop searches each position update for one owned by the
// entity and chains them together
entityListPtr = importEntityList;
for (i = 0; i < importNumEnt; i++)
{
// entityListPtr = LIST_NTH(importEntityList, i);
entityPtr = (ACMIEntityData *)entityListPtr->node;
foundFirst = FALSE;
prevOffset = 0;
prevPosPtr = NULL;
entityPtr->firstPositionDataOffset = 0;
posListPtr = importPosList;
for (j = 0; j < importNumPos; j++)
{
// posListPtr = LIST_NTH(importPosList, j);
posPtr = (ACMIRawPositionData *)posListPtr->node;
// check the id to see if this position belongs to the entity
if (posPtr->uniqueID not_eq entityPtr->uniqueID)
{
// nope
posListPtr = posListPtr->next;
continue;
}
// calculate the offset of this positional record
currOffset = tapeHdr->timelineBlockOffset +
sizeof(ACMIEntityPositionData) * j;
// if it's the 1st in the chain, set the offset to it in
// the entity's record
if (foundFirst == FALSE)
{
entityPtr->firstPositionDataOffset = currOffset;
foundFirst = TRUE;
}
// thread current to previous
posPtr->entityPosData.prevPositionUpdateOffset = prevOffset;
posPtr->entityPosData.nextPositionUpdateOffset = 0;
// thread previous to current
if (prevPosPtr)
{
prevPosPtr->entityPosData.nextPositionUpdateOffset = currOffset;
}
// set vals for next time thru loop
prevOffset = currOffset;
prevPosPtr = posPtr;
// next in list
posListPtr = posListPtr->next;
} // end for position loop
entityListPtr = entityListPtr->next;
} // end for entity loop
entityListPtr = importFeatList;
for (i = 0; i < importNumFeat; i++)
{
entityPtr = (ACMIEntityData *)entityListPtr->node;
foundFirst = FALSE;
prevOffset = 0;
prevPosPtr = NULL;
entityPtr->firstPositionDataOffset = 0;
posListPtr = importPosList;
for (j = 0; j < importNumPos; j++)
{
// posListPtr = LIST_NTH(importPosList, j);
posPtr = (ACMIRawPositionData *)posListPtr->node;
// check the id to see if this position belongs to the entity
if (posPtr->uniqueID not_eq entityPtr->uniqueID)
{
// nope
posListPtr = posListPtr->next;
continue;
}
// calculate the offset of this positional record
currOffset = tapeHdr->timelineBlockOffset +
sizeof(ACMIEntityPositionData) * j;
// if it's the 1st in the chain, set the offset to it in
// the entity's record
if (foundFirst == FALSE)
{
entityPtr->firstPositionDataOffset = currOffset;
foundFirst = TRUE;
}
// thread current to previous
posPtr->entityPosData.prevPositionUpdateOffset = prevOffset;
posPtr->entityPosData.nextPositionUpdateOffset = 0;
// thread previous to current
if (prevPosPtr)
{
prevPosPtr->entityPosData.nextPositionUpdateOffset = currOffset;
}
// set vals for next time thru loop
prevOffset = currOffset;
prevPosPtr = posPtr;
// next in list
posListPtr = posListPtr->next;
} // end for position loop
// while we're doing the features, for each one, go thru the
// feature event list looking for our unique ID in the events
// and setting the index value of our feature in the event
posListPtr = importFeatEventList;
for (j = 0; j < importNumFeatEvents; j++)
{
// posListPtr = LIST_NTH(importPosList, j);
fePtr = (ACMIFeatEventImportData *)posListPtr->node;
// check the id to see if this event belongs to the entity
if (fePtr->uniqueID == entityPtr->uniqueID)
{
fePtr->data.index = i;
}
// next in list
posListPtr = posListPtr->next;
} // end for feature event loop
// now go thru the feature list again and find lead unique ID's and
// change them to indices into the list
// actually NOW, go through and just make sure they exist... otherwise, clear
if (entityPtr->leadIndex not_eq -1)
{
featListPtr = importFeatList;
for (j = 0; j < importNumFeat; j++)
{
// we don't compare ourselves
if (j not_eq i)
{
featPtr = (ACMIEntityData *)featListPtr->node;
if (entityPtr->leadIndex == featPtr->uniqueID)
{
entityPtr->leadIndex = j;
break;
}
}
// next in list
featListPtr = featListPtr->next;
}
// if we're gone thru the whole list and haven't found
// a lead index, we're in trouble. To protect, set the
// lead index to -1
if (j == importNumFeat)
{
entityPtr->leadIndex = -1;
}
}
entityListPtr = entityListPtr->next;
} // end for feature entity loop
}
/*
** Description:
** At this point importEntList and importPosList should be populated.
** Now, we're going to have to setup the offset pointers to do the
** file mapping. Each entity chains back and forth thru its position
** list.
*/
void ACMITape::ThreadEntityEvents(ACMITapeHeader *tapeHdr)
{
int i, j;
long prevOffset;
LIST *entityListPtr, *posListPtr;
ACMIEntityData *entityPtr;
ACMIRawPositionData *posPtr;
ACMIRawPositionData *prevPosPtr;
BOOL foundFirst;
long currOffset;
// we run an outer and inner loop here.
// the outer loops steps thru each entity
// the inner loop searches each position update for one owned by the
// entity and chains them together
entityListPtr = importEntityList;
for (i = 0; i < importNumEnt; i++)
{
// entityListPtr = LIST_NTH(importEntityList, i);
entityPtr = (ACMIEntityData *)entityListPtr->node;
foundFirst = FALSE;
prevOffset = 0;
prevPosPtr = NULL;
entityPtr->firstEventDataOffset = 0;
posListPtr = importEntEventList;
for (j = 0; j < importNumEntEvents; j++)
{
// posListPtr = LIST_NTH(importPosList, j);
posPtr = (ACMIRawPositionData *)posListPtr->node;
// check the id to see if this position belongs to the entity
if (posPtr->uniqueID not_eq entityPtr->uniqueID)
{
// nope
posListPtr = posListPtr->next;
continue;
}
// calculate the offset of this positional record
currOffset = tapeHdr->firstEntEventOffset +
sizeof(ACMIEntityPositionData) * j;
// if it's the 1st in the chain, set the offset to it in
// the entity's record
if (foundFirst == FALSE)
{
entityPtr->firstEventDataOffset = currOffset;
foundFirst = TRUE;
}
// thread current to previous
posPtr->entityPosData.prevPositionUpdateOffset = prevOffset;
posPtr->entityPosData.nextPositionUpdateOffset = 0;
// thread previous to current
if (prevPosPtr)
{
prevPosPtr->entityPosData.nextPositionUpdateOffset = currOffset;
}
// set vals for next time thru loop
prevOffset = currOffset;
prevPosPtr = posPtr;
// next in list
posListPtr = posListPtr->next;
} // end for position loop
entityListPtr = entityListPtr->next;
} // end for entity loop
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/*
** Description:
** At this point importEntList and importPosList should be populated.
** Also the entities and positions are now threaded
** write out the file
*/
void ACMITape::WriteTapeFile(char *fname, ACMITapeHeader *tapeHdr)
{
int i, j;
LIST *entityListPtr, *posListPtr, *eventListPtr;
ACMIEntityData *entityPtr;
ACMIEventHeader *eventPtr;
ACMIRawPositionData *posPtr;
ACMIFeatEventImportData *fePtr;
FILE *tapeFile;
long ret;
tapeFile = fopen(fname, "wb");
if (tapeFile == NULL)
{
MonoPrint("Error opening new tape file\n");
return;
}
// write the header
ret = fwrite(tapeHdr, sizeof(ACMITapeHeader), 1, tapeFile);
if ( not ret)
goto error_exit;
// write out the entities
entityListPtr = importEntityList;
for (i = 0; i < importNumEnt; i++)
{
// entityListPtr = LIST_NTH(importEntityList, i);
entityPtr = (ACMIEntityData *)entityListPtr->node;
ret = fwrite(entityPtr, sizeof(ACMIEntityData), 1, tapeFile);
if ( not ret)
goto error_exit;
entityListPtr = entityListPtr->next;
} // end for entity loop
// write out the features
entityListPtr = importFeatList;
for (i = 0; i < importNumFeat; i++)
{
// entityListPtr = LIST_NTH(importEntityList, i);
entityPtr = (ACMIEntityData *)entityListPtr->node;
ret = fwrite(entityPtr, sizeof(ACMIEntityData), 1, tapeFile);
if ( not ret)
goto error_exit;
entityListPtr = entityListPtr->next;
} // end for entity loop
// write out the entitiy positions
posListPtr = importPosList;
for (i = 0; i < importNumPos; i++)
{
// posListPtr = LIST_NTH(importPosList, i);
posPtr = (ACMIRawPositionData *)posListPtr->node;
// we now want to do a "fixup" of the radar targets. These are
// currently in "uniqueIDs" and we want to convert them into
// an index into the entity list
if (posPtr->entityPosData.posData.radarTarget not_eq -1)
{
entityListPtr = importEntityList;
for (j = 0; j < importNumEnt; j++)
{
entityPtr = (ACMIEntityData *)entityListPtr->node;
if (posPtr->entityPosData.posData.radarTarget == entityPtr->uniqueID)
{
posPtr->entityPosData.posData.radarTarget = j;
break;
}
entityListPtr = entityListPtr->next;
} // end for entity loop
// did we find it?
if (j == importNumEnt)
{
// nope
posPtr->entityPosData.posData.radarTarget = -1;
}
} // end if there's a radar target
ret = fwrite(&posPtr->entityPosData, sizeof(ACMIEntityPositionData), 1, tapeFile);
if ( not ret)
goto error_exit;
posListPtr = posListPtr->next;
}
// write out the entitiy events
posListPtr = importEntEventList;
for (i = 0; i < importNumEntEvents; i++)
{
// posListPtr = LIST_NTH(importPosList, i);
posPtr = (ACMIRawPositionData *)posListPtr->node;
ret = fwrite(&posPtr->entityPosData, sizeof(ACMIEntityPositionData), 1, tapeFile);
if ( not ret)
goto error_exit;
posListPtr = posListPtr->next;
}
// allocate the trailer list
importEventTrailerList = new ACMIEventTrailer[importNumEvents];
F4Assert(importEventTrailerList);
// write out the events
eventListPtr = importEventList;
for (i = 0; i < importNumEvents; i++)
{
// eventListPtr = LIST_NTH(importEventList, i);
eventPtr = (ACMIEventHeader *)eventListPtr->node;
// set the trailer data
importEventTrailerList[i].index = i;
importEventTrailerList[i].timeEnd = eventPtr->timeEnd;
ret = fwrite(eventPtr, sizeof(ACMIEventHeader), 1, tapeFile);
if ( not ret)
goto error_exit;
eventListPtr = eventListPtr->next;
} // end for events loop
// now sort the trailers in ascending order by endTime and
// write them out
qsort(importEventTrailerList,
importNumEvents,
sizeof(ACMIEventTrailer),
CompareEventTrailer);
for (i = 0; i < importNumEvents; i++)
{
ret = fwrite(&importEventTrailerList[i], sizeof(ACMIEventTrailer), 1, tapeFile);
if ( not ret)
goto error_exit;
} // end for events loop
// write out the feature events
posListPtr = importFeatEventList;
for (i = 0; i < importNumFeatEvents; i++)
{
// posListPtr = LIST_NTH(importPosList, i);
fePtr = (ACMIFeatEventImportData *)posListPtr->node;
ret = fwrite(&fePtr->data, sizeof(ACMIFeatEvent), 1, tapeFile);
if ( not ret)
goto error_exit;
posListPtr = posListPtr->next;
}
// finally import and write out the text events
ImportTextEventList(tapeFile, tapeHdr);
// normal exit
fclose(tapeFile);
return;
error_exit:
MonoPrint("Error writing new tape file\n");
if (tapeFile)
fclose(tapeFile);
return;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
BOOL ACMITape::GetEntityPosition
(
int index,
float &x,
float &y,
float &z,
float &yaw,
float &pitch,
float &roll,
float &speed,
float &turnrate,
float &turnradius
)
{
float
deltaTime;
float dx, dy, dz;
float dx1, dy1, dz1;
ACMIEntityPositionData
*pos1,
*pos2,
*pos3;
// init speed to 0.0
speed = 0.0f;
turnrate = 0.0f;
turnradius = 0.0f;
F4Assert(index >= 0 and index < NumEntities());
pos1 = CurrentEntityPositionHead(index);
// If there is not at least 1 positional update, the entity doesn't exist.
F4Assert(pos1 not_eq NULL);
if (pos1->time > _simTime)
{
x = pos1->posData.x;
y = pos1->posData.y;
z = pos1->posData.z;
yaw = pos1->posData.yaw;
pitch = pos1->posData.pitch;
roll = pos1->posData.roll;
return FALSE;
}
pos2 = HeadNext(pos1);
if (pos2 == NULL)
{
x = pos1->posData.x;
y = pos1->posData.y;
z = pos1->posData.z;
yaw = pos1->posData.yaw;
pitch = pos1->posData.pitch;
roll = pos1->posData.roll;
return FALSE;
}
else
{
pos3 = HeadPrev(pos1);
F4Assert(pos1->time <= _simTime);
F4Assert(pos2->time > _simTime);
dx = pos2->posData.x - pos1->posData.x;
dy = pos2->posData.y - pos1->posData.y;
dz = pos2->posData.z - pos1->posData.z;
// Interpolate.
deltaTime =
(
(_simTime - pos1->time) /
(pos2->time - pos1->time)
);
x =
(
pos1->posData.x + dx * deltaTime
);
y =
(
pos1->posData.y + dy * deltaTime
);
z =
(
pos1->posData.z + dz * deltaTime
);
yaw = AngleInterp(pos1->posData.yaw, pos2->posData.yaw, deltaTime);
pitch = AngleInterp(pos1->posData.pitch, pos2->posData.pitch, deltaTime);
roll = AngleInterp(pos1->posData.roll, pos2->posData.roll, deltaTime);
// get the average speed
speed = (float)sqrt(dx * dx + dy * dy + dz * dz) / (pos2->time - pos1->time);
float dAng = pos2->posData.yaw - pos1->posData.yaw;
if (fabs(dAng) > 180.0f * DTR)
{
if (dAng >= 0.0f)
dAng -= 360.0f * DTR;
else
dAng += 360.0f * DTR;
}
if (pos3)
{
dx1 = pos1->posData.x - pos3->posData.x;
dy1 = pos1->posData.y - pos3->posData.y;
dz1 = pos1->posData.z - pos3->posData.z;
// Turn rate = solid angle delta between velocity vectors
turnrate = (float)acos((dx * dx1 + dy * dy1 + dz * dz1) /
(float)sqrt((dx * dx + dy * dy + dz * dz) * (dx1 * dx1 + dy1 * dy1 + dz1 * dz1)));
turnrate *= RTD / (pos2->time - pos1->time);
// turnrate = RTD * fabs( dAng ) / ( pos2->time - pos1->time );
if (turnrate not_eq 0.0f)
{
// sec to turn 360 deg
float secs = 360.0f / turnrate;
// get circumference
float circum = speed * secs;
// now we get turn radius ( circum = 2 * PI * R )
turnradius = circum / (2.0f * PI);
}
}
else
{
turnrate = 0.0F;
turnradius = 0.0F;
}
}
return TRUE;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void ACMITape::SetGeneralEventCallbacks
(
ACMI_GENERAL_EVENT_CALLBACK forwardEventCallback,
ACMI_GENERAL_EVENT_CALLBACK reverseEventCallback,
void *userData
)
{
_generalEventCallbacks.forwardCallback = forwardEventCallback;
_generalEventCallbacks.reverseCallback = reverseEventCallback;
_generalEventCallbacks.userData = userData;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void ACMITape::SetHeadPosition(float t)
{
float newSimTime;
// t should be normalized from 0 to 1
newSimTime = _tapeHdr.startTime + (_tapeHdr.totPlayTime - 0.1f) * t;
// run the update cycle until we've reached the new sim time
while (_simTime not_eq newSimTime)
Update(newSimTime);
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
float ACMITape::GetNewSimTime(float t)
{
float newSimTime;
// t should be normalized from 0 to 1
newSimTime = _tapeHdr.startTime + (_tapeHdr.totPlayTime - 0.1f) * t;
return newSimTime;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
float ACMITape::HeadPosition()
{
return _simTime;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void ACMITape::Update(float newSimTime)
{
float
realTime,
deltaRealTime;
float
deltaLimit;
if (_screenCapturing)
deltaLimit = 0.0625f;
else
deltaLimit = 0.2f;
// Update active events
UpdateActiveEvents();
// Calculate delta time and unpause us if necessary.
realTime = timeGetTime() * 0.001F;
// if new sim time is not negative, we are trying to
// reach a new play position that the user has set with the slider
// we'll be going in steps until _simTime = newSimTime
_simulateOnly = FALSE;
if (newSimTime >= 0.0f)
{
_simulateOnly = TRUE;
deltaLimit = newSimTime - _simTime;
deltaRealTime = 0.2f;
if (deltaLimit > 0.0f)
{
_playVelocity = 1.0f;
}
else if (deltaLimit < 0.0f)
{
_playVelocity = -1.0f;
}
else
{
_playVelocity = 0.0f;
}
if (deltaLimit < 0.0f)
deltaLimit = -deltaLimit;
if (deltaRealTime > deltaLimit)
deltaRealTime = deltaLimit;
}
else if (_unpause and _paused)
{
deltaRealTime = 0.0;
_paused = FALSE;
}
else if (_paused)
{
deltaRealTime = 0.0;
}
else
{
deltaRealTime = realTime - _lastRealTime;
// for debugger stops, make sure delta never is larger
// than 1/5 second
if (deltaRealTime < -deltaLimit)
deltaRealTime = -deltaLimit;
if (deltaRealTime > deltaLimit)
deltaRealTime = deltaLimit;
}
_lastRealTime = realTime;
_unpause = FALSE;
// Advance time.
_deltaSimTime = _playVelocity * deltaRealTime;
_simTime += _deltaSimTime;
// sanity check -- don't allow the head to go beyond tape ends
if (_simTime < _tapeHdr.startTime)
_simTime = _tapeHdr.startTime;
if (_simTime > _tapeHdr.startTime + _tapeHdr.totPlayTime - 0.1f)
_simTime = _tapeHdr.startTime + _tapeHdr.totPlayTime - 0.1f;
_playVelocity += _playAcceleration * deltaRealTime;
Clamp((float)(-_maxPlaySpeed), _playVelocity, (float)_maxPlaySpeed);
// Advance all entity read heads.
AdvanceAllHeads();
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void ACMITape::AdvanceEntityPositionHead(int index)
{
ACMIEntityPositionData
*curr,
*next,
*prev;
F4Assert(index >= 0 and index < NumEntities());
// Backward.
curr = CurrentEntityPositionHead(index);
if (curr == NULL) return;
while (_simTime < curr->time)
{
prev = HeadPrev(curr);
if (prev == NULL) return;
// Advance the head.
_entityReadHeads[index].positionDataOffset = curr->prevPositionUpdateOffset;
curr = prev;
}
// Forward.
next = HeadNext(curr);
if (next == NULL) return;
while (_simTime >= next->time)
{
// Advance the head.
_entityReadHeads[index].positionDataOffset = curr->nextPositionUpdateOffset;
curr = next;
next = HeadNext(curr);
if (next == NULL) return;
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void ACMITape::AdvanceEntityEventHead(int index)
{
ACMIEntityPositionData
*curr,
*next,
*prev;
SimTapeEntity *e;
F4Assert(index >= 0 and index < NumEntities());
// get the entity if we need to change switch settings
e = &_simTapeEntities[ index ];
// Backward.
curr = CurrentEntityEventHead(index);
if (curr == NULL) return;
while (_simTime < curr->time)
{
prev = HeadPrev(curr);
if (prev == NULL) return;
// handle switch settings
if (curr->type == PosTypeSwitch)
{
((DrawableBSP *)e->objBase->drawPointer)->SetSwitchMask(curr->switchData.switchNum, curr->switchData.prevSwitchVal);
}
else if (curr->type == PosTypeDOF)
{
((DrawableBSP *)e->objBase->drawPointer)->SetDOFangle(curr->dofData.DOFNum, curr->dofData.prevDOFVal);
}
// Advance the head.
_entityReadHeads[index].eventDataOffset = curr->prevPositionUpdateOffset;
curr = prev;
}
// Forward.
next = HeadNext(curr);
if (next == NULL) return;
while (_simTime >= next->time)
{
// Advance the head.
_entityReadHeads[index].eventDataOffset = curr->nextPositionUpdateOffset;
// handle switch settings
if (curr->type == PosTypeSwitch)
{
((DrawableBSP *)e->objBase->drawPointer)->SetSwitchMask(curr->switchData.switchNum, curr->switchData.switchVal);
}
else if (curr->type == PosTypeDOF)
{
((DrawableBSP *)e->objBase->drawPointer)->SetDOFangle(curr->dofData.DOFNum, curr->dofData.DOFVal);
}
curr = next;
next = HeadNext(curr);
if (next == NULL) return;
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void ACMITape::AdvanceGeneralEventHeadHeader(void)
{
ACMIEventHeader
*curr,
*next,
*prev;
// Reverse.
curr = GeneralEventData();
if (curr == NULL) return;
while (_simTime < curr->time)
{
prev = Prev(curr);
if (prev == NULL) return;
if (_eventList[ curr->index ])
RemoveActiveEvent(&_eventList[ curr->index ]);
// Advance the head.
curr = prev;
_generalEventReadHeadHeader = curr->index;
}
// Forward.
next = Next(curr);
if (next == NULL) return;
while (_simTime >= next->time)
{
// Advance the head.
curr = next;
_generalEventReadHeadHeader = curr->index;
if ( not _eventList[ curr->index ])
{
_eventList[curr->index] = InsertActiveEvent(curr, _simTime - curr->time);
}
next = Next(curr);
if (next == NULL) return;
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void ACMITape::AdvanceGeneralEventHeadTrailer(void)
{
ACMIEventHeader *e;
ACMIEventTrailer
*curr,
*next,
*prev;
// Reverse.
curr = GeneralEventTrailer();
if (curr == NULL) return;
while (_simTime < curr->timeEnd)
{
prev = Prev(curr);
if (prev == NULL) return;
if ( not _eventList[ curr->index ])
{
e = GetGeneralEventData(curr->index);
_eventList[curr->index] = InsertActiveEvent(e, _simTime - e->time);
}
// Advance the head.
curr = prev;
_generalEventReadHeadTrailer = curr;
}
// Forward.
next = Next(curr);
if (next == NULL) return;
while (_simTime >= next->timeEnd)
{
// Advance the head.
curr = next;
_generalEventReadHeadTrailer = curr;
if (_eventList[ curr->index ])
RemoveActiveEvent(&_eventList[ curr->index ]);
next = Next(curr);
if (next == NULL) return;
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void ACMITape::AdvanceFeatEventHead(void)
{
ACMIFeatEvent
*curr,
*next,
*prev;
SimTapeEntity *feat;
// Reverse.
curr = CurrFeatEvent();
if (curr == NULL) return;
while (_simTime < curr->time)
{
prev = Prev(curr);
if (prev == NULL) return;
// do stuff
// sanity check that we have the right index
if (curr->index >= 0)
{
// get the feature entity
feat = &_simTapeFeatures[ curr->index ];
// create the new drawable object
// set new status
feat->objBase->ClearStatusBit(VIS_TYPE_MASK);
feat->objBase->SetStatusBit(curr->prevStatus);
// this function now handles inserts and removes from
// drawlist
CreateFeatureDrawable(feat);
F4Assert(feat->objBase->drawPointer not_eq NULL);
if (curr->prevStatus == VIS_DAMAGED)
{
((DrawableBSP *)feat->objBase->drawPointer)->SetTextureSet(1);
}
// remove old from display and delete
/*
if(feat->objBase->drawPointer->InDisplayList())
{
_viewPoint->RemoveObject(feat->objBase->drawPointer);
}
delete feat->objBase->drawPointer;
feat->objBase->drawPointer = NULL;
// set new status
feat->objBase->ClearStatusBit( VIS_TYPE_MASK );
feat->objBase->SetStatusBit( curr->prevStatus );
CreateDrawable ( feat->objBase, 1.0F);
F4Assert(feat->objBase->drawPointer not_eq NULL);
// set damaged texture set if needed
if ( curr->prevStatus == VIS_DAMAGED )
{
((DrawableBSP *)feat->objBase->drawPointer)->SetTextureSet( 1 );
}
// features get put into draw list and positioned here.
_viewPoint->InsertObject( feat->objBase->drawPointer );
*/
}
// Advance the head.
curr = prev;
_featEventReadHead = curr;
}
// Forward.
next = Next(curr);
if (next == NULL) return;
if (F4IsBadReadPtr(curr, sizeof(ACMIFeatEvent)))
return;
while (_simTime >= next->time)
{
if (F4IsBadReadPtr(next, sizeof(ACMIFeatEvent)))
return;
// Advance the head.
curr = next;
_featEventReadHead = curr;
// do stuff
// sanity check that we have the right index
if (curr->index >= 0)
{
// get the feature entity
feat = &_simTapeFeatures[ curr->index ];
// create the new drawable object
// set new status
feat->objBase->ClearStatusBit(VIS_TYPE_MASK);
feat->objBase->SetStatusBit(curr->newStatus);
CreateFeatureDrawable(feat);
F4Assert(feat->objBase->drawPointer not_eq NULL);
// set damaged texture set if needed
if (curr->newStatus == VIS_DAMAGED)
{
((DrawableBSP *)feat->objBase->drawPointer)->SetTextureSet(1);
}
/*
// remove old from display and delete
if(feat->objBase->drawPointer->InDisplayList())
{
_viewPoint->RemoveObject(feat->objBase->drawPointer);
}
delete feat->objBase->drawPointer;
feat->objBase->drawPointer = NULL;
// set new status
feat->objBase->ClearStatusBit( VIS_TYPE_MASK );
feat->objBase->SetStatusBit( curr->newStatus );
CreateDrawable ( feat->objBase, 1.0F);
F4Assert(feat->objBase->drawPointer not_eq NULL);
// set damaged texture set if needed
if ( curr->newStatus == VIS_DAMAGED )
{
((DrawableBSP *)feat->objBase->drawPointer)->SetTextureSet( 1 );
}
// features get put into draw list and positioned here.
_viewPoint->InsertObject( feat->objBase->drawPointer );
*/
}
next = Next(curr);
if (next == NULL) return;
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/*
** Description:
** Opens the passed in tape file name and sets up the memory mapped
** stuff
*/
long ACMITape::OpenTapeFile(char *fname)
{
FILE *fd;
long length = 0;
// 1st get the header info and check it out
fd = fopen(fname, "rb");
if (fd == NULL)
{
MonoPrint("Unable to Open Tape File\n");
return(0);
}
// read in the tape header
if ( not fread(&_tapeHdr, sizeof(ACMITapeHeader), 1, fd))
{
MonoPrint("Unable to to read tape header\n");
fclose(fd);
return(0);
}
// close the file
fclose(fd);
// check that we've got a valid file
if (_tapeHdr.fileID not_eq 'TAPE')
{
MonoPrint("Invalid Tape File\n");
return(0);
}
// Set up memory mapping
// open the tape file
_tapeFileHandle = CreateFile(
fname,
GENERIC_READ bitor GENERIC_WRITE,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL bitor FILE_FLAG_RANDOM_ACCESS,
NULL);
if (_tapeFileHandle == INVALID_HANDLE_VALUE)
{
MonoPrint("CreateFile failed on tape open\n");
return(0);
}
length = GetFileSize(_tapeFileHandle, NULL);
// create file mapping
_tapeMapHandle = CreateFileMapping(
_tapeFileHandle,
NULL,
PAGE_READONLY,
0,
0,
NULL);
if (_tapeMapHandle == NULL)
{
MonoPrint("CreateFileMapping failed on tape open\n");
CloseHandle(_tapeFileHandle);
return(0);
}
// map view of file
_tape = MapViewOfFile(
_tapeMapHandle,
FILE_MAP_READ,
0,
0,
0);
if (_tape == NULL)
{
MonoPrint("MapViewOfFile failed on tape open\n");
CloseHandle(_tapeMapHandle);
CloseHandle(_tapeFileHandle);
return(0);
}
// hunky dory
return(length);
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/*
** Description:
** Releases system stuff done in OpenTapeFile
*/
void ACMITape::CloseTapeFile(void)
{
UnmapViewOfFile(_tape);
CloseHandle(_tapeMapHandle);
CloseHandle(_tapeFileHandle);
_tape = NULL;
return;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/*
** Description:
** Interpolates between 2 angles. dT is the relative dist (0-1)
** between begin and end.
*/
float ACMITape::AngleInterp(float begAng, float endAng, float dT)
{
float dAng;
// get the delta angle
dAng = endAng - begAng;
// always rotate in shortest direction (ie when delta > 180 deg in mag)
if (fabs(dAng) > 180.0f * DTR)
{
if (dAng >= 0.0f)
endAng -= 360.0f * DTR;
else
endAng += 360.0f * DTR;
dAng = endAng - begAng;
}
/*
if ( endAng < -0.5f * PI and begAng > 0.5f * PI )
dAng = endAng + ( 2.0f * PI ) - begAng;
else if ( endAng > 0.5f * PI and begAng < -0.5f * PI )
dAng = endAng - ( 2.0f * PI ) - begAng;
else
dAng = endAng - begAng;
*/
return (float)(begAng + dAng * dT);
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void ACMITape::AdvanceAllHeads(void)
{
int
i,
numEntities;
// Advance all entity read heads.
numEntities = NumEntities();
for (i = 0; i < numEntities; i++)
{
// Advance entity position head.
AdvanceEntityPositionHead(i);
AdvanceEntityEventHead(i);
}
// Advance general event head, and apply events that are encountered.
AdvanceGeneralEventHeadHeader();
AdvanceGeneralEventHeadTrailer();
// advance head for any feature events
AdvanceFeatEventHead();
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/*
** Description:
** Reads the entities off of the tape and sets up the in-memory
** sim and graphics representation for them so that they can be
** manipulated and moved
*/
void ACMITape::SetupSimTapeEntities()
{
int
i,
numEntities;
Tpoint pos;
ACMIEntityData *e;
ACMIEntityPositionData *p;
Tpoint origin = { 0.0f, 0.0f, 0.0f };
F4Assert(_simTapeEntities == NULL);
F4Assert(_tape not_eq NULL);
// create array of SimTapeEntity
numEntities = NumEntities();
_simTapeEntities = new SimTapeEntity [numEntities];
F4Assert(_simTapeEntities not_eq NULL);
// for each entity, create it's object stuff....
for (i = 0; i < numEntities; i++)
{
// get the tape entity data
e = EntityData(i);
// get the 1st position data for the entity
p = CurrentEntityPositionHead(i);
_simTapeEntities[i].flags = e->flags;
if (e->flags bitand ENTITY_FLAG_FEATURE)
{
// edg: I believe this code path should no longer be in use
// since features are in a different list
_simTapeEntities[i].objBase = new SimFeatureClass(EntityType(i));
_simTapeEntities[i].objBase->SetDelta(0.0f, 0.0f, 0.0f);
_simTapeEntities[i].objBase->SetYPRDelta(0.0f, 0.0f, 0.0f);
}
else
{
// create the base class
_simTapeEntities[i].objBase = new SimStaticClass(EntityType(i));// new SimBaseClass(EntityType(i));
GetEntityPosition(i,
_simTapeEntities[i].x,
_simTapeEntities[i].y,
_simTapeEntities[i].z,
_simTapeEntities[i].yaw,
_simTapeEntities[i].pitch,
_simTapeEntities[i].roll,
_simTapeEntities[i].aveSpeed,
_simTapeEntities[i].aveTurnRate,
_simTapeEntities[i].aveTurnRadius);
}
// set the matrix
_simTapeEntities[i].objBase->SetYPR(p->posData.yaw, p->posData.pitch, p->posData.roll);
_simTapeEntities[i].objBase->SetPosition(p->posData.x, p->posData.y, p->posData.z);
CalcTransformMatrix(_simTapeEntities[i].objBase);
// create thge drawable object
// special case chaff and flares
if (e->flags bitand ENTITY_FLAG_CHAFF)
{
pos.x = p->posData.x;
pos.y = p->posData.y;
pos.z = p->posData.z;
_simTapeEntities[i].objBase->drawPointer =
new DrawableBSP(MapVisId(VIS_CHAFF), &pos, &IMatrix, 1.0f);
((DrawableBSP *)_simTapeEntities[i].objBase->drawPointer)->SetLabel("", 0);
}
else if (e->flags bitand ENTITY_FLAG_FLARE)
{
pos.x = p->posData.x;
pos.y = p->posData.y;
pos.z = p->posData.z;
_simTapeEntities[i].objBase->drawPointer =
new Drawable2D(DRAW2D_FLARE, 2.0f, &pos);
}
// aircraft use special Drawable Poled class
else if (e->flags bitand ENTITY_FLAG_AIRCRAFT)
{
short visType;
SimBaseClass *theObject = _simTapeEntities[i].objBase;
// get the class pointer
Falcon4EntityClassType* classPtr =
(Falcon4EntityClassType*)theObject->EntityType();
pos.x = p->posData.x;
pos.y = p->posData.y;
pos.z = p->posData.z;
visType = classPtr->visType[theObject->Status() bitand VIS_TYPE_MASK];
theObject->drawPointer = new DrawablePoled(visType, &pos, &IMatrix, 1.0f);
F4Assert(theObject->drawPointer not_eq NULL);
if (ACMI_Callsigns) // we have callsigns
theObject->drawPointer->SetLabel(ACMI_Callsigns[e->uniqueID].label, TeamSimColorList[ACMI_Callsigns[e->uniqueID].teamColor]);
}
else
{
CreateDrawable(_simTapeEntities[i].objBase, 1.0F);
if (ACMI_Callsigns)
((DrawableBSP*)_simTapeEntities[i].objBase->drawPointer)->SetLabel(((DrawableBSP*)_simTapeEntities[i].objBase->drawPointer)->Label(), TeamSimColorList[ACMI_Callsigns[e->uniqueID].teamColor]);
}
// sigh. hack for ejections
if (_simTapeEntities[i].objBase->drawPointer == NULL)
{
short visType;
SimBaseClass *theObject = _simTapeEntities[i].objBase;
// get the class pointer
Falcon4EntityClassType* classPtr =
(Falcon4EntityClassType*)theObject->EntityType();
if (classPtr->vuClassData.classInfo_[VU_TYPE] == TYPE_EJECT)
{
pos.x = p->posData.x;
pos.y = p->posData.y;
pos.z = p->posData.z;
visType = classPtr->visType[theObject->Status() bitand VIS_TYPE_MASK];
theObject->drawPointer = new DrawableBSP(MapVisId(VIS_EJECT1), &pos, &IMatrix, 1.0f);
((DrawableBSP *)theObject->drawPointer)->SetLabel("Ejected Pilot", 0x0000FF00);
}
F4Assert(theObject->drawPointer not_eq NULL);
}
// features get put into draw list and positioned here.
if (e->flags bitand ENTITY_FLAG_FEATURE)
{
// edg: I believe this code path should no longer be in use
// since features are in a different list
_viewPoint->InsertObject(_simTapeEntities[i].objBase->drawPointer);
}
// create other stuff as needed by the object
// (ie, if this is missile, create the drawable trail for it...)
_simTapeEntities[i].objTrail = NULL;
_simTapeEntities[i].objBsp1 = NULL;
_simTapeEntities[i].objBsp2 = NULL;
_simTapeEntities[i].obj2d = NULL;
_simTapeEntities[i].wlTrail = NULL;
_simTapeEntities[i].wrTrail = NULL;
_simTapeEntities[i].wtLength = 0;
// a missile -- it needs drawable trail set up
if ((e->flags bitand ENTITY_FLAG_MISSILE))
{
_simTapeEntities[i].objTrail = new DrawableTrail(TRAIL_SAM);
_simTapeEntities[i].objBsp1 = new DrawableBSP(MapVisId(VIS_MFLAME_L), &origin, (struct Trotation *)&IMatrix, 1.0f);
_simTapeEntities[i].objTrail->KeepStaleSegs(TRUE);
_simTapeEntities[i].trailStartTime = p->time;
_simTapeEntities[i].trailEndTime = p->time + 120.0F; //me123 to 30 we wanna see the trials in acmi// trail lasts 3 sec
}
// a flare -- it needs drawable trail set up and a glow sphere
else if ((e->flags bitand ENTITY_FLAG_FLARE))
{
_simTapeEntities[i].objTrail = new DrawableTrail(TRAIL_SAM);
_simTapeEntities[i].objTrail->KeepStaleSegs(TRUE);
_simTapeEntities[i].trailStartTime = p->time;
_simTapeEntities[i].trailEndTime = p->time + 3.0F; // trail lasts 3 sec
_simTapeEntities[i].obj2d =
new Drawable2D(DRAW2D_EXPLCIRC_GLOW, 8.0f, &origin);
}
// a aircraft -- it needs drawable wing trails set up
else if ((e->flags bitand ENTITY_FLAG_AIRCRAFT))
{
_simTapeEntities[i].wlTrail = new DrawableTrail(TRAIL_LWING);
_simTapeEntities[i].wlTrail->KeepStaleSegs(true); // MLR 12/14/2003 -
_simTapeEntities[i].wrTrail = new DrawableTrail(TRAIL_RWING);
_simTapeEntities[i].wrTrail->KeepStaleSegs(true); // MLR 12/14/2003 -
//_simTapeEntities[i].wlTrail = new DrawableTrail(TRAIL_AIM120);
//_simTapeEntities[i].wrTrail = new DrawableTrail(TRAIL_MAVERICK);
}
}
F4Assert(_simTapeFeatures == NULL);
// create array of SimTapeEntity
if (_tapeHdr.numFeat == 0)
return;
_simTapeFeatures = new SimTapeEntity [_tapeHdr.numFeat];
F4Assert(_simTapeFeatures not_eq NULL);
// for each feature, create it's object stuff....
for (i = 0; i < _tapeHdr.numFeat; i++)
{
// get the tape entity data
e = FeatureData(i);
// get the 1st position data for the entity
p = CurrentFeaturePositionHead(i);
_simTapeFeatures[i].flags = e->flags;
// protect against bad indices( not ?)
// edg: I'm not sure what's going on but it seems like we
// occasionally get a bad lead VU ID. The imported can't find
// it. This is protected for in Import. Also protect here...
if (e->leadIndex >= _tapeHdr.numFeat)
_simTapeFeatures[i].leadIndex = -1;
else
_simTapeFeatures[i].leadIndex = e->leadIndex;
_simTapeFeatures[i].slot = e->slot;
_simTapeFeatures[i].objBase = new SimFeatureClass(e->type);
F4Assert(_simTapeFeatures[i].objBase not_eq NULL);
_simTapeFeatures[i].objBase->SetDelta(0.0f, 0.0f, 0.0f);
_simTapeFeatures[i].objBase->SetYPRDelta(0.0f, 0.0f, 0.0f);
_simTapeFeatures[i].objBase->SetYPR(p->posData.yaw, p->posData.pitch, p->posData.roll);
_simTapeFeatures[i].objBase->SetPosition(p->posData.x, p->posData.y, p->posData.z);
((SimFeatureClass *)_simTapeFeatures[i].objBase)->featureFlags = e->specialFlags;
// get the class pointer
Falcon4EntityClassType* classPtr =
(Falcon4EntityClassType*)_simTapeFeatures[i].objBase->EntityType();
// get the feature class data
FeatureClassDataType *fc = (FeatureClassDataType *)classPtr->dataPtr;
_simTapeFeatures[i].objBase->SetCampaignFlag(fc->Flags);
CalcTransformMatrix(_simTapeFeatures[i].objBase);
// create other stuff as needed by the object
// (ie, if this is missile, create the drawable trail for it...)
_simTapeFeatures[i].objTrail = NULL;
_simTapeFeatures[i].objBsp1 = NULL;
_simTapeFeatures[i].objBsp2 = NULL;
_simTapeFeatures[i].obj2d = NULL;
}
// for each feature, create it's drawable object
// we do this in a different loop because we want to make sure all the
// objbase's are created first since some feature objects are actually
// subcomponents of others and have thier drawpointer inserted into
// the drawpointer list of another rather than the main drawlist
for (i = 0; i < _tapeHdr.numFeat; i++)
{
// create the drawable object
CreateFeatureDrawable(&_simTapeFeatures[i]);
F4Assert(_simTapeFeatures[i].objBase->drawPointer not_eq NULL);
// NOTE: insertion into draw list should now be done in
// CreateFeatureDrawable
// features get put into draw list and positioned here.
// _viewPoint->InsertObject( _simTapeFeatures[i].objBase->drawPointer );
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/*
** Description:
** Cleans up the _simTapeEntities list freeing objects and removing
** drawables from lists
*/
void ACMITape::CleanupSimTapeEntities(void)
{
int
i,
numEntities;
SimTapeEntity *ep;
F4Assert(_simTapeEntities not_eq NULL);
// create array of SimTapeEntity
numEntities = NumEntities();
// for each entity, create it's object stuff....
for (i = 0; i < numEntities; i++)
{
// get pointer
ep = &_simTapeEntities[i];
// if there's a base object...
if (ep->objBase)
{
// remove from display
if (ep->objBase->drawPointer->InDisplayList())
{
_viewPoint->RemoveObject(ep->objBase->drawPointer);
}
delete ep->objBase->drawPointer;
ep->objBase->drawPointer = NULL;
delete ep->objBase;
ep->objBase = NULL;
}
// if there's a trail object...
if (ep->objTrail)
{
// remove from display
if (ep->objTrail->InDisplayList())
{
_viewPoint->RemoveObject(ep->objTrail);
}
delete ep->objTrail;
ep->objTrail = NULL;
}
// if there's a 2d object...
if (ep->obj2d)
{
// remove from display
if (ep->obj2d->InDisplayList())
{
_viewPoint->RemoveObject(ep->obj2d);
}
delete ep->obj2d;
ep->obj2d = NULL;
}
// if there's a bsp object...
if (ep->objBsp1)
{
// remove from display
if (ep->objBsp1->InDisplayList())
{
_viewPoint->RemoveObject(ep->objBsp1);
}
delete ep->objBsp1;
ep->objBsp1 = NULL;
}
// if there's a bsp object...
if (ep->objBsp2)
{
// remove from display
if (ep->objBsp2->InDisplayList())
{
_viewPoint->RemoveObject(ep->objBsp2);
}
delete ep->objBsp2;
ep->objBsp2 = NULL;
}
// if there's a trail object...
if (ep->wlTrail)
{
// remove from display
if (ep->wlTrail->InDisplayList())
{
_viewPoint->RemoveObject(ep->wlTrail);
}
delete ep->wlTrail;
ep->wlTrail = NULL;
}
// if there's a trail object...
if (ep->wrTrail)
{
// remove from display
if (ep->wrTrail->InDisplayList())
{
_viewPoint->RemoveObject(ep->wrTrail);
}
delete ep->wrTrail;
ep->wrTrail = NULL;
}
}
delete [] _simTapeEntities;
_simTapeEntities = NULL;
// for each feature, remove its object stuff
// 1st pass do drawpointer
for (i = 0; i < _tapeHdr.numFeat; i++)
{
// get pointer
ep = &_simTapeFeatures[i];
// if there's a base object...
if (ep->objBase)
{
// remove from display
if (ep->objBase->drawPointer->InDisplayList())
{
_viewPoint->RemoveObject(ep->objBase->drawPointer);
}
delete ep->objBase->drawPointer;
ep->objBase->drawPointer = NULL;
}
}
// 2nd pass delete baseObj pointer and objBase
for (i = 0; i < _tapeHdr.numFeat; i++)
{
// get pointer
ep = &_simTapeFeatures[i];
// if there's a base object...
if (ep->objBase)
{
// remove from display
if (((SimFeatureClass *)ep->objBase)->baseObject)
{
if (((SimFeatureClass *)ep->objBase)->baseObject->InDisplayList())
{
_viewPoint->RemoveObject(((SimFeatureClass*)ep->objBase)->baseObject);
}
delete((SimFeatureClass *)ep->objBase)->baseObject;
((SimFeatureClass *)ep->objBase)->baseObject = NULL;
}
delete ep->objBase;
ep->objBase = NULL;
}
}
delete [] _simTapeFeatures;
_simTapeFeatures = NULL;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/*
** Description:
** Access simtape entity by index
*/
SimTapeEntity * ACMITape::GetSimTapeEntity(int index)
{
F4Assert(_simTapeEntities not_eq NULL);
F4Assert(index < NumEntities());
return &_simTapeEntities[index];
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/*
** Description:
** Returns if entity exists in current frame or not
*/
BOOL ACMITape::IsEntityInFrame(int index)
{
ACMIEntityPositionData
*pos1,
*pos2;
F4Assert(index >= 0 and index < NumEntities());
pos1 = CurrentEntityPositionHead(index);
// If there is not at least 1 positional update, the entity doesn't exist.
F4Assert(pos1 not_eq NULL);
if (pos1->time > _simTime)
{
return FALSE;
}
pos2 = HeadNext(pos1);
if (pos2 == NULL or pos2->time < _simTime)
{
return FALSE;
}
return TRUE;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/*
** Description:
** returns the index of the entity targeted by the entity who's
** index is passed in. -1 is no target.
*/
int ACMITape::GetEntityCurrentTarget(int index)
{
ACMIEntityPositionData
*pos1,
*pos2;
F4Assert(index >= 0 and index < NumEntities());
pos1 = CurrentEntityPositionHead(index);
// If there is not at least 1 positional update, the entity doesn't exist.
F4Assert(pos1 not_eq NULL);
if (pos1->time > _simTime)
{
return -1;
}
pos2 = HeadNext(pos1);
if (pos2 == NULL or pos2->time < _simTime)
{
return -1;
}
return pos1->posData.radarTarget;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/*
** Description:
** Puts the entity into darw list
*/
void ACMITape::InsertEntityInFrame(int index)
{
F4Assert(_simTapeEntities not_eq NULL);
F4Assert(index < NumEntities());
if (_simTapeEntities[index].objBase->drawPointer->InDisplayList())
return;
_viewPoint->InsertObject(_simTapeEntities[index].objBase->drawPointer);
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/*
** Description:
** removes the entity from darw list
*/
void ACMITape::RemoveEntityFromFrame(int index)
{
F4Assert(_simTapeEntities not_eq NULL);
F4Assert(index < NumEntities());
if ( not _simTapeEntities[index].objBase->drawPointer->InDisplayList())
return;
_viewPoint->RemoveObject(_simTapeEntities[index].objBase->drawPointer);
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/*
** Description:
** Runs thru the entity list and determines if the entities
** should be inserted/removed from draw and/or positioned in the frame.
*/
void ACMITape::UpdateSimTapeEntities(void)
{
int
i,
numEntities;
SimTapeEntity *ep;
Tpoint pos;
Tpoint wtpos;
Trotation rot;
Tpoint newPoint;
F4Assert(_simTapeEntities not_eq NULL);
// create array of SimTapeEntity
numEntities = NumEntities();
_renderer->SetColor(0xffff0000);
// for each entity, create it's object stuff....
for (i = 0; i < numEntities; i++)
{
// get pointer
ep = &_simTapeEntities[i];
if (GetEntityPosition(i, ep->x, ep->y, ep->z, ep->yaw, ep->pitch, ep->roll, ep->aveSpeed, ep->aveTurnRate, ep->aveTurnRadius) == FALSE)
{
// make sure we remove from draw list
if (ep->objBase->drawPointer->InDisplayList())
{
_viewPoint->RemoveObject(ep->objBase->drawPointer);
// remove trail too
if (ep->objTrail and ep->objTrail->InDisplayList() and _simTime < ep->trailStartTime)
{
ep->objTrail->TrimTrail(0);
_viewPoint->RemoveObject(ep->objTrail);
}
// remove Bsp1 too
if (ep->objBsp1 and ep->objBsp1->InDisplayList() and _simTime < ep->trailStartTime)
{
_viewPoint->RemoveObject(ep->objBsp1);
}
// remove Bsp2 too
if (ep->objBsp2 and ep->objBsp2->InDisplayList() and _simTime < ep->trailStartTime)
{
_viewPoint->RemoveObject(ep->objBsp2);
}
// remove 2d too
if (ep->obj2d and ep->obj2d->InDisplayList())
{
_viewPoint->RemoveObject(ep->obj2d);
}
}
continue;
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// set the scalar value...// put check in if Isometric view
ep->objBase->drawPointer->SetScale(_tapeObjScale);
// if the entity is an aircraft we set its labels
if (ep->flags bitand ENTITY_FLAG_AIRCRAFT)
{
float tmp;
char tmpstr[32];
DrawablePoled *dp = (DrawablePoled *)ep->objBase->drawPointer;
// LOCK RANGES
// get the target entity
Tpoint posb;
int tgt = GetEntityCurrentTarget(i);
float distance;
if (tgt > 0)
{
SimTapeEntity *targep = GetSimTapeEntity(tgt);
ep->objBase->drawPointer->GetPosition(&pos);
targep->objBase->drawPointer->GetPosition(&posb);
distance = (float)(FT_TO_NM * (float)sqrt(((pos.x - posb.x) * (pos.x - posb.x) + (pos.y - posb.y) * (pos.y - posb.y))));
}
else distance = 0;
tmp = distance;
sprintf(tmpstr, "%0.0f Rng", tmp);
dp->SetDataLabel(DP_LABEL_LOCK_RANGE, tmpstr);
{
// heading
tmp = ep->yaw * RTD;
if (tmp < 0.0f)
tmp += 360.0f;
sprintf(tmpstr, "%0.0f Deg", tmp);
dp->SetDataLabel(DP_LABEL_HEADING, tmpstr);
}
// alt
sprintf(tmpstr, "%0.0f ft", -ep->z);
dp->SetDataLabel(DP_LABEL_ALT, tmpstr);
// speed
// tmp=ep->aveSpeed * FTPSEC_TO_KNOTS;
tmp = CalcKIAS(ep->aveSpeed, -ep->z);
sprintf(tmpstr, "%0.0f Kts", tmp);
dp->SetDataLabel(DP_LABEL_SPEED, tmpstr);
// turn rate
tmp = ep->aveTurnRate;
sprintf(tmpstr, "%0.0f deg/s", tmp);
dp->SetDataLabel(DP_LABEL_TURNRATE, tmpstr);
// turn radius
tmp = ep->aveTurnRadius;
sprintf(tmpstr, "%0.0f ft", tmp);
dp->SetDataLabel(DP_LABEL_TURNRADIUS, tmpstr);
}
// update object's position
ep->objBase->SetPosition
(
ep->x,
ep->y,
ep->z
);
ep->objBase->SetYPR
(
ep->yaw,
ep->pitch,
ep->roll
);
// just to make sure....
ep->objBase->SetYPRDelta
(
0.0f,
0.0f,
0.0f
);
// set the matrix
CalcTransformMatrix(ep->objBase);
// get position and matrix for drawable BSP
ObjectSetData(ep->objBase, &pos, &rot);
// update the BSP
if (ep->flags bitand ENTITY_FLAG_FLARE)
((Drawable2D *)ep->objBase->drawPointer)->SetPosition(&pos);
else
((DrawableBSP *)ep->objBase->drawPointer)->Update(&pos, &rot);
////////////////////////////////////////////////////////////////////////////////////
// BING 3-20-98
// TURN ON LABELS FOR ENTITIES.
// acmiView->GetObjectName(acmiView->Tape()->GetSimTapeEntity(i)->objBase,tmpStr);
// ((DrawableBSP *)ep->objBase->drawPointer)->SetLabel(ep->name , labelColor );
/////////////////////////////////////////////////////////////////////////////////////
// entity is in the frame .....
// make sure we tell draw loop to draw it
if ( not ep->objBase->drawPointer->InDisplayList())
{
_viewPoint->InsertObject(ep->objBase->drawPointer);
}
// likewise for 2d portion
if (ep->obj2d)
{
if ( not ep->obj2d->InDisplayList())
_viewPoint->InsertObject(ep->obj2d);
ep->obj2d->SetPosition(&pos);
}
// do the wing trails if turned on
// edg: partial hack. For regen in dogfight the wingtrails are
// continue from dead pos to new position. Since we don't have the
// info to detect a regen, if we see that the airspeed is too high
// trim the trails back to 0
if (_wingTrails and (ep->flags bitand ENTITY_FLAG_AIRCRAFT) and CalcKIAS(ep->aveSpeed, -ep->z) > 1100.0f)
{
ep->wrTrail->TrimTrail(0);
ep->wlTrail->TrimTrail(0);
ep->wtLength = 0;
}
else if (_wingTrails and (ep->flags bitand ENTITY_FLAG_AIRCRAFT))
{
if (_playVelocity < 0.0f and ( not _paused or _simulateOnly))
{
ep->wtLength -= ep->wrTrail->RewindTrail((DWORD)(_simTime * 1000));
ep->wlTrail->RewindTrail((DWORD)(_simTime * 1000));
}
else if (_playVelocity > 0.0f and ( not _paused or _simulateOnly))
{
ep->wtLength++;
wtpos.x = ep->objBase->dmx[1][0] * -20.0f * _tapeObjScale + ep->x;
wtpos.y = ep->objBase->dmx[1][1] * -20.0f * _tapeObjScale + ep->y;
wtpos.z = ep->objBase->dmx[1][2] * -20.0f * _tapeObjScale + ep->z;
ep->wlTrail->AddPointAtHead(&wtpos, (DWORD)(_simTime * 1000));
wtpos.x = ep->objBase->dmx[1][0] * 20.0f * _tapeObjScale + ep->x;
wtpos.y = ep->objBase->dmx[1][1] * 20.0f * _tapeObjScale + ep->y;
wtpos.z = ep->objBase->dmx[1][2] * 20.0f * _tapeObjScale + ep->z;
ep->wrTrail->AddPointAtHead(&wtpos, (DWORD)(_simTime * 1000));
/* ep->wtLength++;
wtpos.x = ep->objBase->dmx[1][0] * -40.0f + ep->x;
wtpos.y = ep->objBase->dmx[1][1] * -40.0f + ep->y;
wtpos.z = ep->objBase->dmx[1][2] * -40.0f + ep->z;
ep->wlTrail->AddPointAtHead( &wtpos, (DWORD)(_simTime * 1000) );
wtpos.x = ep->objBase->dmx[1][0] * 40.0f + ep->x;
wtpos.y = ep->objBase->dmx[1][1] * 40.0f + ep->y;
wtpos.z = ep->objBase->dmx[1][2] * 40.0f + ep->z;
ep->wrTrail->AddPointAtHead( &wtpos, (DWORD)(_simTime * 1000) );
*/
}
else if (_stepTrail < 0.0f)
{
ep->wtLength -= ep->wrTrail->RewindTrail((DWORD)(_simTime * 1000));
ep->wlTrail->RewindTrail((DWORD)(_simTime * 1000));
}
else if (_stepTrail > 0.0f)
{
ep->wtLength++;
wtpos.x = ep->objBase->dmx[1][0] * -20.0f * _tapeObjScale + ep->x;
wtpos.y = ep->objBase->dmx[1][1] * -20.0f * _tapeObjScale + ep->y;
wtpos.z = ep->objBase->dmx[1][2] * -20.0f * _tapeObjScale + ep->z;
ep->wlTrail->AddPointAtHead(&wtpos, (DWORD)(_simTime * 1000));
wtpos.x = ep->objBase->dmx[1][0] * 20.0f * _tapeObjScale + ep->x;
wtpos.y = ep->objBase->dmx[1][1] * 20.0f * _tapeObjScale + ep->y;
wtpos.z = ep->objBase->dmx[1][2] * 20.0f * _tapeObjScale + ep->z;
ep->wrTrail->AddPointAtHead(&wtpos, (DWORD)(_simTime * 1000));
}
if (ep->wtLength not_eq _wtMaxLength) // MLR 12/14/2003 -
{
ep->wrTrail->TrimTrail(_wtMaxLength);
ep->wlTrail->TrimTrail(_wtMaxLength);
ep->wtLength = _wtMaxLength;
}
}
// check for trail
if ( not ep->objTrail)
continue;
// we need to deal with the trail....
// if the trail end time is before the read head, we do nothing
if (_simTime > ep->trailEndTime)
{
// remove Bsp1 too
if (ep->objBsp1 and ep->objBsp1->InDisplayList())
{
_viewPoint->RemoveObject(ep->objBsp1);
}
// remove Bsp2 too
if (ep->objBsp2 and ep->objBsp2->InDisplayList())
{
_viewPoint->RemoveObject(ep->objBsp2);
}
continue;
}
// if the trail start time is after the current read head,
// make sure trail is no longer in display list
if (_simTime < ep->trailStartTime)
{
if (ep->objTrail->InDisplayList())
{
ep->objTrail->TrimTrail(0);
_viewPoint->RemoveObject(ep->objTrail);
}
// remove Bsp1 too
if (ep->objBsp1 and ep->objBsp1->InDisplayList())
{
_viewPoint->RemoveObject(ep->objBsp1);
}
// remove Bsp2 too
if (ep->objBsp2 and ep->objBsp2->InDisplayList())
{
_viewPoint->RemoveObject(ep->objBsp2);
}
continue;
}
// the read head is between trail start and end times
// we need need to determine if we're moving forwards or
// backwards in time, if back we rewind the trail, otherwise
// add a new point
if ( not ep->objTrail->InDisplayList())
{
_viewPoint->InsertObject(ep->objTrail);
}
// insert Bsp1 too
if (ep->objBsp1 and not ep->objBsp1->InDisplayList())
{
_viewPoint->InsertObject(ep->objBsp1);
}
// insert Bsp2 too
if (ep->objBsp2 and not ep->objBsp2->InDisplayList())
{
_viewPoint->InsertObject(ep->objBsp2);
}
// update the BSPs
// placement a bit behind the missile
newPoint = pos;
newPoint.x += ep->objBase->dmx[0][0] * -7.0f;
newPoint.y += ep->objBase->dmx[0][1] * -7.0f;
newPoint.z += ep->objBase->dmx[0][2] * -7.0f;
if (ep->objBsp1)
ep->objBsp1->Update(&newPoint, &rot);
if (ep->objBsp2)
ep->objBsp2->Update(&newPoint, &rot);
newPoint.x += ep->objBase->dmx[0][0] * -30.0f;
newPoint.y += ep->objBase->dmx[0][1] * -30.0f;
newPoint.z += ep->objBase->dmx[0][2] * -30.0f;
if (_playVelocity < 0.0f and ( not _paused or _simulateOnly))
{
ep->objTrail->RewindTrail((DWORD)(_simTime * 1000));
}
else if (_playVelocity > 0.0f and ( not _paused or _simulateOnly))
{
ep->objTrail->AddPointAtHead(&newPoint, (DWORD)(_simTime * 1000));
}
else if (_stepTrail < 0.0f)
{
ep->objTrail->RewindTrail((DWORD)(_simTime * 1000));
}
else if (_stepTrail > 0.0f)
{
ep->objTrail->AddPointAtHead(&newPoint, (DWORD)(_simTime * 1000));
}
}
_stepTrail = 0.0;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void ACMITape::ObjectSetData(SimBaseClass *obj, Tpoint *simView, Trotation *viewRotation)
{
viewRotation->M11 = obj->dmx[0][0];
viewRotation->M21 = obj->dmx[0][1];
viewRotation->M31 = obj->dmx[0][2];
viewRotation->M12 = obj->dmx[1][0];
viewRotation->M22 = obj->dmx[1][1];
viewRotation->M32 = obj->dmx[1][2];
viewRotation->M13 = obj->dmx[2][0];
viewRotation->M23 = obj->dmx[2][1];
viewRotation->M33 = obj->dmx[2][2];
// Update object position
simView->x = obj->XPos();
simView->y = obj->YPos();
simView->z = obj->ZPos();
}
/*
** Makes sure all memory used by events is free'd up
*/
void ACMITape::CleanupEventList(void)
{
int i;
F4Assert(_eventList);
for (i = 0; i < _tapeHdr.numEvents; i++)
{
if (_eventList[i])
{
RemoveActiveEvent(&_eventList[i]);
}
}
delete [] _eventList;
_eventList = NULL;
}
/*
** Takes the acmi info passed in from the tape and creates an
** active event record for it, sets up the objects, inserts them
** into the display list(if needed) and chains it to the active list head
** dT should be the time delta between start time for event and read head
*/
ActiveEvent *
ACMITape::InsertActiveEvent(ACMIEventHeader *eh, float dT)
{
ActiveEvent *event = NULL;
TracerEventData *td = NULL;
SfxClass *sfx = NULL;
SimBaseClass *simBase;
Tpoint pos;
Tpoint vec;
// don't insert if passed end time
if (eh->time + dT > eh->timeEnd)
return NULL;
// creation based on type
switch (eh->eventType)
{
case ACMIRecTracerStart:
// create new event record
event = new ActiveEvent;
F4Assert(event);
event->eventType = eh->eventType;
event->index = eh->index;
event->time = eh->time;
event->timeEnd = eh->timeEnd;
// create new tracer event record
td = new TracerEventData;
F4Assert(td);
event->eventData = (void *)td;
// init tracer data
td->x = eh->x;
td->y = eh->y;
td->z = eh->z;
td->dx = eh->dx;
td->dy = eh->dy;
td->dz = eh->dz;
// create tracer
td->objTracer = new DrawableTracer(1.3f);
td->objTracer->SetAlpha(0.8f);
td->objTracer->SetRGB(1.0f, 1.0f, 0.2f);
UpdateTracerEvent(td, dT);
// put it into the draw list
_viewPoint->InsertObject(td->objTracer);
break;
case ACMIRecStationarySfx:
// create new event record
event = new ActiveEvent;
F4Assert(event);
event->eventType = eh->eventType;
event->index = eh->index;
event->time = eh->time;
event->timeEnd = eh->timeEnd;
pos.x = eh->x;
pos.y = eh->y;
pos.z = eh->z;
// create new tracer event record
sfx = new SfxClass(eh->type,
&pos,
(float)(eh->timeEnd - eh->time),
eh->scale);
F4Assert(sfx);
event->eventData = (void *)sfx;
sfx->ACMIStart(_viewPoint, event->time, _simTime);
break;
case ACMIRecMovingSfx:
// create new event record
event = new ActiveEvent;
F4Assert(event);
event->eventType = eh->eventType;
event->index = eh->index;
event->time = eh->time;
event->timeEnd = eh->timeEnd;
pos.x = eh->x;
pos.y = eh->y;
pos.z = eh->z;
vec.x = eh->dx;
vec.y = eh->dy;
vec.z = eh->dz;
// create new sfx
if (eh->user < 0)
{
sfx = new SfxClass(eh->type,
eh->flags,
&pos,
&vec,
(float)(eh->timeEnd - eh->time),
eh->scale);
}
else
{
// we need to build a base obj first
simBase = new SimStaticClass(0);// SimBaseClass( 0 );
simBase->drawPointer = new DrawableBSP(eh->user, &pos, &IMatrix, 1.0f);
simBase->SetPosition(pos.x, pos.y, pos.z);
simBase->SetDelta(vec.x, vec.y, vec.z);
simBase->SetYPR(0.0f, 0.0f, 0.0f);
simBase->SetYPRDelta(0.0f, 0.0f, 0.0f);
sfx = new SfxClass(eh->type, eh->flags, simBase, (float)(eh->timeEnd - eh->time), eh->scale);
}
F4Assert(sfx);
event->eventData = (void *)sfx;
sfx->ACMIStart(_viewPoint, event->time, _simTime);
break;
// current don't handle anything else
default:
return NULL;
}
// now insert it into the active list
event->prev = NULL;
if (_activeEventHead)
{
_activeEventHead->prev = event;
}
event->next = _activeEventHead;
_activeEventHead = event;
return event;
}
/*
** Removes objects from display lists
** Frees memory for any objects.
** Frees memory for ActiveEvent and event data
*/
void
ACMITape::RemoveActiveEvent(ActiveEvent **eptrptr)
{
ActiveEvent *event = *eptrptr;
TracerEventData *td = NULL;
SfxClass *sfx;
// deletion based on type
switch (event->eventType)
{
case ACMIRecTracerStart:
// cast eventData to appropriate type
td = (TracerEventData *)event->eventData;
// remove from draw list
if (td->objTracer->InDisplayList())
_viewPoint->RemoveObject(td->objTracer);
// free data memory
delete td->objTracer;
delete td;
break;
case ACMIRecMovingSfx:
case ACMIRecStationarySfx:
// cast eventData to appropriate type
sfx = (SfxClass *)event->eventData;
// free data memory
delete sfx;
break;
// current don't handle anything else
default:
return;
}
// take event out of active Event List
if (event->prev)
event->prev->next = event->next;
else
_activeEventHead = event->next;
if (event->next)
event->next->prev = event->prev;
// delete event data and set caller's pointer to NULL
delete event;
*eptrptr = NULL;
}
/*
** Update tracer info based on delta Time
*/
void
ACMITape::UpdateTracerEvent(TracerEventData *td, float dT)
{
Tpoint pos, end;
pos.x = td->x + td->dx * dT;
pos.y = td->y + td->dy * dT;
pos.z = td->z + td->dz * dT;
end.x = pos.x - td->dx * 0.05f;
end.y = pos.y - td->dy * 0.05f;
end.z = pos.z - td->dz * 0.05f;
td->objTracer->Update(&pos, &end);
}
/*
** Run the update cycle for all active events
*/
void
ACMITape::UpdateActiveEvents(void)
{
ActiveEvent *event = NULL;
TracerEventData *td = NULL;
SfxClass *sfx;
event = _activeEventHead;
while (event)
{
// handle based on type
switch (event->eventType)
{
case ACMIRecTracerStart:
// deref eventData
td = (TracerEventData *)event->eventData;
UpdateTracerEvent(td, _simTime - event->time);
// remove from display list if event no longer exists
// blech, this is a very less than optimal solution
// the active event list is going to bloat over time
/*
if ( _simTime > event->timeEnd or event->time > _simTime )
{
if ( td->objTracer->InDisplayList() )
_viewPoint->RemoveObject( td->objTracer );
}
else
{
// the event is active....
if ( not td->objTracer->InDisplayList() )
_viewPoint->InsertObject( td->objTracer );
UpdateTracerEvent( td, _simTime - event->time );
}
*/
break;
case ACMIRecMovingSfx:
case ACMIRecStationarySfx:
// deref eventData
sfx = (SfxClass *)event->eventData;
sfx->ACMIExec(_simTime);
break;
// currently don't handle anything else
default:
break;
}
event = event->next;
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/*
** Description:
** Sets the wing trails
*/
void ACMITape::SetWingTrails(BOOL turnOn)
{
int
i,
numEntities;
SimTapeEntity *ep;
F4Assert(_simTapeEntities not_eq NULL);
F4Assert(_tape not_eq NULL);
// set flag
_wingTrails = turnOn;
// create array of SimTapeEntity
numEntities = NumEntities();
// for each entity, create it's object stuff....
for (i = 0; i < numEntities; i++)
{
// get the tape entity data
ep = &_simTapeEntities[i];
if ( not (ep->flags bitand ENTITY_FLAG_AIRCRAFT))
{
continue;
}
if (turnOn)
{
// turn trails on
if ( not ep->wrTrail->InDisplayList())
_viewPoint->InsertObject(ep->wrTrail);
if ( not ep->wlTrail->InDisplayList())
_viewPoint->InsertObject(ep->wlTrail);
}
else
{
// turn trails off
if (ep->wrTrail->InDisplayList())
_viewPoint->RemoveObject(ep->wrTrail);
if (ep->wlTrail->InDisplayList())
_viewPoint->RemoveObject(ep->wlTrail);
}
ep->wrTrail->TrimTrail(0);
ep->wlTrail->TrimTrail(0);
ep->wtLength = 0;
}
}
/*
* append new node to end of list
* caller should cast returned value to appropriate type
*/
LIST *
AppendToEndOfList(LIST * list, LIST **end, void * node)
{
LIST * newnode;
newnode = new LIST;
newnode -> node = node;
newnode -> next = NULL;
/* list was null */
if ( not list)
{
list = newnode;
*end = list;
}
else
{
/* chain in at end */
(*end) -> next = newnode;
*end = newnode;
}
return(list);
}
/*
* destroy a list
* optionally free the data pointed to by node, using supplied destructor fn
* If destructor is NULL, node data not affected, only list nodes get freed
*/
void
DestroyTheList(LIST * list)
{
LIST * prev,
* curr;
if ( not list)
return;
prev = list;
curr = list -> next;
while (curr)
{
// if ( destructor )
// (*destructor)(prev -> node);
delete prev->node;
prev -> next = NULL;
delete prev;
prev = curr;
curr = curr -> next;
}
// if( destructor )
// (*destructor)( prev -> node );
delete prev->node;
prev -> next = NULL;
delete prev;
//ListGlobalPack();
}
extern EventElement *ProcessEventListForACMI(void);
extern void ClearSortedEventList(void);
/*
** Description:
** Reads the event file and writes out associated text events with
** the tape.
*/
void
ACMITape::ImportTextEventList(FILE *fd, ACMITapeHeader *tapeHdr)
{
EventElement *cur;
long ret;
ACMITextEvent te;
char timestr[20];
tapeHdr->numTextEvents = 0;
cur = ProcessEventListForACMI();
memset(&te, 0, sizeof(ACMITextEvent));
// PJW Totally rewrote event debriefing stuff... thus the new code
while (cur)
{
te.intTime = cur->eventTime;
GetTimeString(cur->eventTime, timestr);
_tcscpy(te.timeStr, timestr + 3);
_tcscpy(te.msgStr, cur->eventString);
// KCK: Edit out some script info which is used in debreiefings
_TCHAR *strptr = _tcschr(te.msgStr, '@');
if (strptr)
{
strptr[0] = ' ';
strptr[1] = '-';
strptr[2] = ' ';
}
ret = fwrite(&te, sizeof(ACMITextEvent), 1, fd);
if ( not ret)
{
MonoPrint("Error writing TAPE event element\n");
break;
}
tapeHdr->numTextEvents++;
// next one
cur = cur->next;
} // end for events loop
// write callsign list
if (Import_Callsigns)
{
ret = fwrite(&import_count, sizeof(long), 1, fd);
if ( not ret)
goto error_exit;
ret = fwrite(Import_Callsigns, import_count * sizeof(ACMI_CallRec), 1, fd);
if ( not ret)
goto error_exit;
}
// write the header again (bleck)
ret = fseek(fd, 0, SEEK_SET);
if (ret)
{
MonoPrint("Error seeking TAPE start\n");
goto error_exit;
}
ret = fwrite(tapeHdr, sizeof(ACMITapeHeader), 1, fd);
if ( not ret)
{
MonoPrint("Error writing TAPE header again\n");
}
error_exit:
// free up mem
// DisposeEventList(evList);
ClearSortedEventList();
}
/*
** Description:
** returns pointer to 1st text event element and the count of
** elements
*/
void *
ACMITape::GetTextEvents(int *count)
{
if (_tapeHdr.numTextEvents > 1048576) // Sanity check
{
count = 0;
return NULL;
}
*count = _tapeHdr.numTextEvents;
return (void *)((char *)_tape + _tapeHdr.firstTextEventOffset);
}
void *ACMITape::GetCallsignList(long *count)
{
if (_tapeHdr.numTextEvents > 1048576) // Sanity check
{
count = 0;
return NULL;
}
*count = (long)(*(long*)((char*)_tape + _tapeHdr.firstTextEventOffset + _tapeHdr.numTextEvents * sizeof(ACMITextEvent)));
return((void *)((char*)_tape + _tapeHdr.firstTextEventOffset + _tapeHdr.numTextEvents * sizeof(ACMITextEvent) + sizeof(long)));
}
/*
** Name: CreateFeatureDrawable
** Description:
** Creates and/or updates the drawpointer for a feature.
** This function will also insert the drawpointer in the viewpoint
** display list or into the drawpointer of another object if it's
** a composite object like a bridge or airbase.
** Rewritten from CreateDrawable in OTWDriver.
*/
void ACMITape::CreateFeatureDrawable(SimTapeEntity *feat)
{
short visType = -1;
Tpoint simView;
Trotation viewRotation;
SimBaseClass* baseObject;
DrawableObject* lastPointer = NULL;
// get the object and pointer to its classtbl entry
SimBaseClass* theObject = feat->objBase;
Falcon4EntityClassType* classPtr = (Falcon4EntityClassType*)theObject->EntityType();
// Set position and orientations
viewRotation.M11 = theObject->dmx[0][0];
viewRotation.M21 = theObject->dmx[0][1];
viewRotation.M31 = theObject->dmx[0][2];
viewRotation.M12 = theObject->dmx[1][0];
viewRotation.M22 = theObject->dmx[1][1];
viewRotation.M32 = theObject->dmx[1][2];
viewRotation.M13 = theObject->dmx[2][0];
viewRotation.M23 = theObject->dmx[2][1];
viewRotation.M33 = theObject->dmx[2][2];
// Update object position
simView.x = theObject->XPos();
simView.y = theObject->YPos();
simView.z = theObject->ZPos();
visType = classPtr->visType[theObject->Status() bitand VIS_TYPE_MASK];
// make sure things are sane
F4Assert(visType >= 0 or theObject->drawPointer);
F4Assert(classPtr->vuClassData.classInfo_[VU_DOMAIN] == DOMAIN_LAND);
F4Assert(classPtr->vuClassData.classInfo_[VU_CLASS] == CLASS_FEATURE);
// A feature thingy..
SimBaseClass *prevObj = NULL, *nextObj = NULL;
// In many cases, our visType should be modified by our neighbors.
if ((theObject->Status() bitand VIS_TYPE_MASK) not_eq VIS_DESTROYED and
(((SimFeatureClass*)theObject)->featureFlags bitand FEAT_NEXT_NORM or
((SimFeatureClass*)theObject)->featureFlags bitand FEAT_PREV_NORM))
{
int idx = feat->slot;
prevObj = FindComponentFeature(feat->leadIndex, idx - 1);
nextObj = FindComponentFeature(feat->leadIndex, idx + 1);
if (prevObj and
(((SimFeatureClass*)theObject)->featureFlags bitand FEAT_PREV_NORM) and
(prevObj->Status() bitand VIS_TYPE_MASK) == VIS_DESTROYED)
{
if (nextObj and
(((SimFeatureClass*)theObject)->featureFlags bitand FEAT_NEXT_NORM) and
(nextObj->Status() bitand VIS_TYPE_MASK) == VIS_DESTROYED)
{
visType = classPtr->visType[VIS_BOTH_DEST];
}
else
{
visType = classPtr->visType[VIS_LEFT_DEST];
}
}
else if (nextObj and
(((SimFeatureClass*)theObject)->featureFlags bitand FEAT_NEXT_NORM) and
(nextObj->Status() bitand VIS_TYPE_MASK) == VIS_DESTROYED)
{
visType = classPtr->visType[VIS_RIGHT_DEST];
}
}
// Check for change - and don't bother if there is none.
if (theObject->drawPointer and
((DrawableBSP*)theObject->drawPointer)->GetID() == visType)
return;
if (theObject->drawPointer and theObject->drawPointer->InDisplayList())
{
// KCK: In some cases we still need this pointer (specifically
// when we replace bridge segments), so let's save it here - we'll
// toss it out after we're done.
lastPointer = theObject->drawPointer;
theObject->drawPointer = NULL;
}
// get the lead baseobject if any
// otherwise set base object to ourself
if (feat->leadIndex >= 0)
baseObject = _simTapeFeatures[ feat->leadIndex ].objBase;
else
baseObject = theObject;
// Some things require Base Objects (like bridges and airbases)
if ( not ((SimFeatureClass*)baseObject)->baseObject)
{
// Is this a bridge?
if (theObject->IsSetCampaignFlag(FEAT_ELEV_CONTAINER))
{
// baseObject is the "container" object for all parts of the bridge
// There is only one container for the entire bridge, stored in the lead element
((SimFeatureClass*)baseObject)->baseObject = new DrawableBridge(1.0F);
// Insert only the bridge drawable.
_viewPoint->InsertObject(((SimFeatureClass*)baseObject)->baseObject);
}
// Is this a big flat thing with things on it (like an airbase?)
else if (theObject->IsSetCampaignFlag(FEAT_FLAT_CONTAINER))
{
// baseObject is the "container" object for all parts of the platform
// There is only one container for the entire platform, stored in the
// lead element.
((SimFeatureClass*)baseObject)->baseObject = new DrawablePlatform(1.0F);
// Insert only the platform drawable.
_viewPoint->InsertObject(((SimFeatureClass*)baseObject)->baseObject);
}
}
// Add another building to this grouping of buildings, or replace the drawable
// of one which is here.
// Is the container a bridge?
if (baseObject->IsSetCampaignFlag(FEAT_ELEV_CONTAINER))
{
// Make the new BRIDGE object
if (visType)
{
if (theObject->IsSetCampaignFlag(FEAT_NEXT_IS_TOP) and theObject->Status() not_eq VIS_DESTROYED)
theObject->drawPointer = new DrawableRoadbed(visType, visType + 1, &simView, theObject->Yaw(), 10.0f, (float)atan(20.0f / 280.0f));
else
theObject->drawPointer = new DrawableRoadbed(visType, -1, &simView, theObject->Yaw(), 10.0f, (float)atan(20.0f / 280.0f));
}
else
theObject->drawPointer = NULL;
// Check for replacement
if (lastPointer)
{
ShiAssert(lastPointer->GetClass() == DrawableObject::Roadbed);
ShiAssert(theObject->drawPointer->GetClass() == DrawableObject::Roadbed);
((DrawableBridge*)(((SimFeatureClass*)baseObject)->baseObject))->ReplacePiece((DrawableRoadbed*)(lastPointer), (DrawableRoadbed*)(theObject->drawPointer));
}
else if (theObject->drawPointer)
{
ShiAssert(theObject->drawPointer->GetClass() == DrawableObject::Roadbed);
((DrawableBridge*)(((SimFeatureClass*)baseObject)->baseObject))->AddSegment((DrawableRoadbed*)(theObject->drawPointer));
}
}
// Is the container a big flat thing (airbase)?
else if (baseObject->IsSetCampaignFlag(FEAT_FLAT_CONTAINER))
{
// Everything on a platform is a Building
// That means it sticks straight up the -Z axis
theObject->drawPointer = new DrawableBuilding(visType, &simView, theObject->Yaw(), 1.0F);
// Am I Flat (can things drive across it)?
if (theObject->IsSetCampaignFlag((FEAT_FLAT_CONTAINER bitor FEAT_ELEV_CONTAINER)))
((DrawablePlatform*)((SimFeatureClass*)baseObject)->baseObject)->InsertStaticSurface(((DrawableBuilding*)theObject->drawPointer));
else
((DrawablePlatform*)((SimFeatureClass*)baseObject)->baseObject)->InsertStaticObject(theObject->drawPointer);
}
else
{
// if we get here then this is just a loose collection of buildings, like a
// village or city, with no big flat objects between them
theObject->drawPointer = new DrawableBuilding(visType, &simView, theObject->Yaw(), 1.0F);
// Insert the object
_viewPoint->InsertObject(((SimFeatureClass*)theObject)->drawPointer);
}
// KCK: Remove any previous drawable object
if (lastPointer)
{
if (lastPointer->InDisplayList())
_viewPoint->RemoveObject(lastPointer);
delete lastPointer;
}
}
/*
** Name: FindComponentFeature
** Description:
** Tries to find the feature with the leadindex and slot
** Passed in.
*/
SimBaseClass *ACMITape::FindComponentFeature(long leadIndex, int slot)
{
int i;
if (leadIndex < 0 or slot < 0)
return NULL;
for (i = 0; i < _tapeHdr.numFeat; i++)
{
if (_simTapeFeatures[i].leadIndex == leadIndex and
_simTapeFeatures[i].slot == slot)
{
return _simTapeFeatures[i].objBase;
}
}
return NULL;
}
| 30.050832 | 207 | 0.513355 | [
"render",
"object",
"solid"
] |
426d7e905afdc598f1ff585749f473d2afb0230f | 2,484 | cpp | C++ | CdCoverCreatorExtensions/CDDBDiagnostics/CDDBDiagnosticsDlg.cpp | matthias-christen/CdCoverCreator | edb223c2cf33ab3fb72d84ce2a9bce8500408c2a | [
"MIT"
] | null | null | null | CdCoverCreatorExtensions/CDDBDiagnostics/CDDBDiagnosticsDlg.cpp | matthias-christen/CdCoverCreator | edb223c2cf33ab3fb72d84ce2a9bce8500408c2a | [
"MIT"
] | null | null | null | CdCoverCreatorExtensions/CDDBDiagnostics/CDDBDiagnosticsDlg.cpp | matthias-christen/CdCoverCreator | edb223c2cf33ab3fb72d84ce2a9bce8500408c2a | [
"MIT"
] | null | null | null | // CDDBDiagnosticsDlg.cpp : implementation file
//
#include "stdafx.h"
#include "CDDBDiagnostics.h"
#include "CDDBDiagnosticsDlg.h"
#include ".\cddbdiagnosticsdlg.h"
#include "AudioCDTracks.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CCDDBDiagnosticsDlg dialog
CCDDBDiagnosticsDlg::CCDDBDiagnosticsDlg(CWnd* pParent /*=NULL*/)
: CDialog(CCDDBDiagnosticsDlg::IDD, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CCDDBDiagnosticsDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_EDIT1, m_txtResult);
}
BEGIN_MESSAGE_MAP(CCDDBDiagnosticsDlg, CDialog)
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
//}}AFX_MSG_MAP
ON_BN_CLICKED(IDC_BUTTON1, OnBnClickedButton1)
END_MESSAGE_MAP()
// CCDDBDiagnosticsDlg message handlers
BOOL CCDDBDiagnosticsDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
return TRUE; // return TRUE unless you set the focus to a control
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CCDDBDiagnosticsDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// The system calls this function to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CCDDBDiagnosticsDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CCDDBDiagnosticsDlg::OnBnClickedButton1()
{
CAudioCDTracks act;
CString s;
m_txtResult.GetWindowText (s);
m_txtResult.SetWindowText (s + "\r\n===============================================================\r\n\r\n" + act.GetInfo ());
}
| 25.090909 | 129 | 0.688808 | [
"model"
] |
f11942a2c707ede33e81fc7c0f40ffa1a332c04f | 83 | cpp | C++ | src/model/Settings.cpp | aarcangeli/Light-Show-Maker | c0e74251ea4943bca9f114e0304fa08761fe83d5 | [
"MIT"
] | null | null | null | src/model/Settings.cpp | aarcangeli/Light-Show-Maker | c0e74251ea4943bca9f114e0304fa08761fe83d5 | [
"MIT"
] | null | null | null | src/model/Settings.cpp | aarcangeli/Light-Show-Maker | c0e74251ea4943bca9f114e0304fa08761fe83d5 | [
"MIT"
] | null | null | null | #include "Settings.h"
using namespace sm::model;
Settings::Settings() = default;
| 13.833333 | 31 | 0.722892 | [
"model"
] |
f11d9c6d6cad27eab52c8cd0bb1f6eaf63c8fd04 | 1,149 | hxx | C++ | ds/adsi/msext/common.hxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | ds/adsi/msext/common.hxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | ds/adsi/msext/common.hxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //+------------------------------------------------------------------------
//
// Class: Common
//
// Purpose: Contains Winnt routines and properties that are common to
// all Winnt objects. Winnt objects get the routines and
// properties through C++ inheritance.
//
//-------------------------------------------------------------------------
#define MAX_DWORD 0xFFFFFFFF
#define SCHEMA_NAME TEXT("Schema")
#define ROOTDSE_NAME TEXT("RootDSE")
#define LDP_CACHE_ENTRY 0
#define LDAP_HANDLE 1
#define OBJECT_CREDENTIALS 2
#define LDAP_SERVER 3
#define LDAP_DN 4
#define LDAP_MUTUAL_AUTH_STATUS 8
#define LDAP_MEMBER_HAS_RANGE 9
#define LDAP_USERACCOUNTCONTROL 0xa
HRESULT
MakeUncName(
LPTSTR szSrcBuffer,
LPTSTR szTargBuffer
);
HRESULT
ValidateOutParameter(
BSTR * retval
);
//
// Accessing Well-known object types
//
typedef struct _filters {
TCHAR szObjectName[MAX_PATH];
DWORD dwFilterId;
} FILTERS, *PFILTERS;
extern PFILTERS gpFilters;
extern DWORD gdwMaxFilters;
| 22.98 | 76 | 0.565709 | [
"object"
] |
f1229ddf5492048ff59d36a96456dead294b4c9e | 1,699 | cpp | C++ | source/shape/ShapeScatterNd.cpp | stephehuang/MNN | e8d9ee89aca3e8247745fb89b338eca2ad9b583d | [
"Apache-2.0"
] | 3 | 2019-12-27T01:10:32.000Z | 2021-05-14T08:10:40.000Z | source/shape/ShapeScatterNd.cpp | stephehuang/MNN | e8d9ee89aca3e8247745fb89b338eca2ad9b583d | [
"Apache-2.0"
] | 10 | 2019-07-04T01:40:13.000Z | 2019-10-30T02:38:42.000Z | source/shape/ShapeScatterNd.cpp | stephehuang/MNN | e8d9ee89aca3e8247745fb89b338eca2ad9b583d | [
"Apache-2.0"
] | 1 | 2021-06-06T06:54:53.000Z | 2021-06-06T06:54:53.000Z | //
// ShapeScatterNd.cpp
// MNN
//
// Created by MNN on 2019/11/27.
// Copyright © 2018, Alibaba Group Holding Limited
//
#include "core/Macro.h"
#include "core/SizeComputer.hpp"
namespace MNN {
// Size Computer
class ShapeScatterNd : public SizeComputer {
bool onComputeSize(const MNN::Op *op, const std::vector<Tensor *> &inputs,
const std::vector<Tensor *> &outputs) const override {
MNN_ASSERT(3 == inputs.size());
auto indices = inputs[0];
auto updates = inputs[1];
auto shape = inputs[2];
auto output = outputs[0];
MNN_CHECK(shape->dimensions() == 1, "shape rank should be one");
const int indicesDimension = indices->dimensions();
MNN_CHECK(indices->length(indicesDimension - 1) == 1, "indices.shape[-1] = shape.rank");
const int outerDims = indicesDimension - 1;
for (int i = 0; i < outerDims; ++i) {
MNN_CHECK(indices->length(i) == updates->length(i), "indices shape does not match updates'");
}
const int dimension = shape->length(0);
MNN_CHECK(updates->dimensions() == dimension, "updates dimension should be equal to given shape");
output->buffer().dimensions = dimension;
auto shapeData = shape->host<int>();
for (int i = 0; i < dimension; ++i) {
output->setLength(i, shapeData[i]);
}
output->buffer().type = updates->buffer().type;
TensorUtils::getDescribe(output)->dimensionFormat = TensorUtils::getDescribe(updates)->dimensionFormat;
return true;
}
};
REGISTER_SHAPE_INPUTS(ShapeScatterNd, OpType_ScatterNd, (std::vector<int>{2}));
} // namespace MNN
| 33.313725 | 111 | 0.619188 | [
"shape",
"vector"
] |
f12503258490f3f0a1369c4eea1d53172c7020fb | 3,758 | cc | C++ | test/integration/attach_light_plugin.cc | yinnglu/gazebo | 3a5618a2a18873141e3cac734a692b778cec4fc0 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2019-03-04T14:12:55.000Z | 2019-03-04T14:12:55.000Z | test/integration/attach_light_plugin.cc | yinnglu/gazebo | 3a5618a2a18873141e3cac734a692b778cec4fc0 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | test/integration/attach_light_plugin.cc | yinnglu/gazebo | 3a5618a2a18873141e3cac734a692b778cec4fc0 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2016-04-25T22:05:09.000Z | 2020-03-08T08:45:12.000Z | /*
* Copyright (C) 2017 Open Source Robotics Foundation
*
* 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 "gazebo/test/ServerFixture.hh"
#include "gazebo/physics/physics.hh"
#include "gazebo/test/helper_physics_generator.hh"
using namespace gazebo;
class AttachLightTest : public ServerFixture,
public testing::WithParamInterface<const char*>
{
/// \brief Test AttachLightPlugin by verifying light pose against link pose
/// \param[in] _physicsEngine Name of physics engine
public: void AttachLightPlugin(const std::string &_physicsEngine);
};
void AttachLightTest::AttachLightPlugin(const std::string &_physicsEngine)
{
// Test plugin for attaching lights to links
this->Load("worlds/attach_lights.world", true, _physicsEngine);
physics::WorldPtr world = physics::get_world("default");
ASSERT_TRUE(world != nullptr);
// Get the double pendulum model
physics::ModelPtr pendulumModel =
world->ModelByName("double_pendulum_with_lights");
ASSERT_TRUE(pendulumModel != nullptr);
// Get the links
physics::LinkPtr upperLink =
pendulumModel->GetLink("double_pendulum_with_base::upper_link");
ASSERT_TRUE(upperLink != nullptr);
physics::LinkPtr lowerLink =
pendulumModel->GetLink("double_pendulum_with_base::lower_link");
ASSERT_TRUE(lowerLink != nullptr);
// Get the lights
physics::LightPtr pointLight = world->LightByName("point");
ASSERT_TRUE(pointLight != nullptr);
physics::LightPtr pointLight2 = world->LightByName("point2");
ASSERT_TRUE(pointLight2 != nullptr);
physics::LightPtr spotLight = world->LightByName("spot");
ASSERT_TRUE(spotLight != nullptr);
// step the world
world->Step(1);
// Get the initial light pose offset relative to link
ignition::math::Pose3d pointLightPose = pointLight->WorldPose() -
upperLink->WorldPose();
ignition::math::Pose3d pointLight2Pose = pointLight2->WorldPose() -
upperLink->WorldPose();
ignition::math::Pose3d spotLightPose = spotLight->WorldPose() -
lowerLink->WorldPose();
// verify light pose against link pose.
// NOTE: there seem to be race condition when verifying pose using
// GetWorldPose in the test thread so do the verification in the update
// callback which is guaranteed to be done in the physics thread
int iteration = 0;
auto verifyPose = [&]()
{
ignition::math::Pose3d upperLinkPose = upperLink->WorldPose();
ignition::math::Pose3d lowerLinkPose = lowerLink->WorldPose();
EXPECT_EQ(pointLight->WorldPose(), pointLightPose + upperLinkPose);
EXPECT_EQ(pointLight2->WorldPose(), pointLight2Pose + upperLinkPose);
EXPECT_EQ(spotLight->WorldPose(), spotLightPose + lowerLinkPose);
iteration++;
};
auto connection = event::Events::ConnectWorldUpdateEnd(std::bind(verifyPose));
// verify pose for 1000 iterations
for (unsigned int i = 0; i < 1000u; ++i)
world->Step(1);
// verify that update is called
EXPECT_EQ(iteration, 1000);
}
TEST_P(AttachLightTest, AttachLightPlugin)
{
AttachLightPlugin(GetParam());
}
INSTANTIATE_TEST_CASE_P(PhysicsEngines, AttachLightTest, PHYSICS_ENGINE_VALUES);
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 34.477064 | 80 | 0.731506 | [
"model"
] |
f1396ae00d40a339d794478e1fab6a410ebff41e | 1,950 | cc | C++ | contrib/gnu/gdb/dist/gold/testsuite/constructor_test.cc | TheSledgeHammer/2.11BSD | fe61f0b9aaa273783cd027c7b5ec77e95ead2153 | [
"BSD-3-Clause"
] | 3 | 2021-05-04T17:09:06.000Z | 2021-10-04T07:19:26.000Z | contrib/gnu/gdb/dist/gold/testsuite/constructor_test.cc | TheSledgeHammer/2.11BSD | fe61f0b9aaa273783cd027c7b5ec77e95ead2153 | [
"BSD-3-Clause"
] | null | null | null | contrib/gnu/gdb/dist/gold/testsuite/constructor_test.cc | TheSledgeHammer/2.11BSD | fe61f0b9aaa273783cd027c7b5ec77e95ead2153 | [
"BSD-3-Clause"
] | null | null | null | // constructor_test.cc -- a test case for gold global constructors
// Copyright (C) 2006-2020 Free Software Foundation, Inc.
// Written by Ian Lance Taylor <iant@google.com>.
// This file is part of gold.
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
// 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.
// This file just runs some global constructors and destructors. The
// last global destructor verifies that the state is as expected, and
// we assume that it runs correctly itself.
#include <cassert>
#include <cstdlib>
// These counters let us verify the state.
int c1_count;
int c2_count;
int atexit_count;
// This class verifies that there are no objects left when it is
// destroyed. Therefore, we can only have one instance of this
// object.
class c1
{
public:
static int count;
c1()
{ ++c1_count; }
~c1()
{
--c1_count;
assert(c1_count == 0 && c2_count == 0 && atexit_count == 0);
}
};
c1 c1v;
// A function called at atexit time.
void
atexit_function()
{
--atexit_count;
assert(atexit_count == c2_count);
}
// A class which counts itself and also calls atexit.
class c2
{
public:
c2()
{
assert(atexit_count == c2_count);
++c2_count;
atexit(atexit_function);
++atexit_count;
}
~c2()
{ --c2_count; }
};
c2 c2v1;
c2 c2v2;
int
main()
{
return 0;
}
| 21.428571 | 71 | 0.702564 | [
"object"
] |
f13a81c65641a68cc626250bd692b629e54843ac | 3,452 | cpp | C++ | alpaca_zorro_plugin/market_data/polygon.cpp | kzhdev/alpaca_zorro_plugin | 8d6c85a2298d48ebee79d11b43009e89d691023e | [
"MIT"
] | 11 | 2020-10-08T21:14:49.000Z | 2021-12-23T11:57:12.000Z | alpaca_zorro_plugin/market_data/polygon.cpp | webclinic017/alpaca_zorro_plugin | 6edc53a385dcf7b893f6c401e6b7c870fb358a5d | [
"MIT"
] | 4 | 2020-10-14T00:31:17.000Z | 2021-09-17T00:53:03.000Z | alpaca_zorro_plugin/market_data/polygon.cpp | webclinic017/alpaca_zorro_plugin | 6edc53a385dcf7b893f6c401e6b7c870fb358a5d | [
"MIT"
] | 4 | 2020-11-23T05:45:29.000Z | 2021-12-23T11:57:15.000Z | #include "stdafx.h"
#include "market_data/polygon.h"
#include "date/date.h"
using namespace alpaca;
Response<std::vector<Bar>> Polygon::getBars(
const std::string& symbol,
__time32_t start,
__time32_t end,
int nTickMinutes,
uint32_t limit,
int32_t price_type) const {
if (end == 0) {
end = static_cast<__time32_t>(std::time(nullptr));
}
auto t_end = end;
Response<std::vector<Bar>> result;
auto& rtBars = result.content();
rtBars.reserve(limit);
__time32_t upperBound = t_end;
do {
std::stringstream url;
url << baseUrl_ << "/v2/aggs/ticker/" << symbol << "/range/" << nTickMinutes << "/minute";
try {
using namespace date;
url << "/" << format("%F", date::sys_seconds{ std::chrono::seconds{ start } });
url << "/" << format("%F", date::sys_seconds{ std::chrono::seconds{ t_end } });
}
catch (const std::exception& e) {
assert(false);
return Response<std::vector<Bar>>(1, "invalid time. " + std::string(e.what()));
}
url << "?sort=desc&limit="<<limit; // in desending order
LOG_DEBUG("--> %s\n", url.str().c_str());
url << "&" << apiKey_;
auto response = request<std::vector<Bar>, Polygon>(url.str(), nullptr, nullptr);
if (!response) {
BrokerError(response.what().c_str());
break;
}
auto& bars = response.content();
size_t nExclude = 0;
LOG_DEBUG("%d bars downloaded.\n", bars.size());
if (!bars.empty()) {
using namespace date;
auto from = bars.front().time;
auto to = bars.back().time;
LOG_DEBUG("%s(%d) - %s(%d)\n", format("%F %T", date::sys_seconds{ std::chrono::seconds{ from } }).c_str(), from,
format("%F %T", date::sys_seconds{ std::chrono::seconds{ to } }).c_str(), to);
}
else {
// no more data
break;
}
// remove record passed end time
auto it = bars.cbegin();
for (; it != bars.cend();) {
if ((__time32_t)(*it).time <= upperBound) {
break;
}
++it;
}
if (it != bars.cbegin()) {
bars.erase(bars.cbegin(), it);
}
if (bars.empty()) {
break;
}
rtBars.insert(rtBars.end(), bars.begin(), bars.end());
if (!rtBars.empty()) {
upperBound = rtBars.back().time - 1;
}
} while (rtBars.size() < limit);
// remove order older than start
auto it = rtBars.end();
while (it != rtBars.begin()) {
--it;
if ((*it).time >= (uint32_t)start) {
break;
}
it = rtBars.erase(it);
}
// keep number of records up to limit
if (rtBars.size() > limit) {
rtBars.resize(limit);
}
LOG_DEBUG("return %d bars.\n", rtBars.size());
if (!rtBars.empty()) {
using namespace date;
LOG_DEBUG("%s(%d) - %s(%d)\n", format("%F %T", date::sys_seconds{ std::chrono::seconds{ rtBars.front().time } }).c_str(), rtBars.front().time,
format("%F %T", date::sys_seconds{ std::chrono::seconds{ rtBars.back().time } }).c_str(), rtBars.back().time);
}
// change to asending order, BrokerHistory2 handles asending order
std::reverse(rtBars.begin(), rtBars.end());
return result;
} | 31.099099 | 150 | 0.517381 | [
"vector"
] |
f13b831695d419ffbe6da241914b182a7bc089bd | 17,675 | cxx | C++ | main/chart2/source/tools/OPropertySet.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/chart2/source/tools/OPropertySet.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/chart2/source/tools/OPropertySet.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.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.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "OPropertySet.hxx"
#include "ImplOPropertySet.hxx"
#include "ContainerHelper.hxx"
#include <rtl/uuid.h>
#include <cppuhelper/queryinterface.hxx>
#include <vector>
#include <algorithm>
using namespace ::com::sun::star;
using ::com::sun::star::style::XStyleSupplier;
// using ::com::sun::star::beans::XFastPropertyState;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::uno::Any;
using ::rtl::OUString;
using ::osl::MutexGuard;
// needed for MS compiler
using ::cppu::OBroadcastHelper;
using ::cppu::OPropertySetHelper;
using ::cppu::OWeakObject;
namespace property
{
OPropertySet::OPropertySet( ::osl::Mutex & par_rMutex ) :
OBroadcastHelper( par_rMutex ),
// the following causes a warning; there seems to be no way to avoid it
OPropertySetHelper( static_cast< OBroadcastHelper & >( *this )),
m_rMutex( par_rMutex ),
m_pImplProperties( new impl::ImplOPropertySet() ),
m_bSetNewValuesExplicitlyEvenIfTheyEqualDefault(false)
{
}
OPropertySet::OPropertySet( const OPropertySet & rOther, ::osl::Mutex & par_rMutex ) :
OBroadcastHelper( par_rMutex ),
// the following causes a warning; there seems to be no way to avoid it
OPropertySetHelper( static_cast< OBroadcastHelper & >( *this )),
m_rMutex( par_rMutex ),
m_bSetNewValuesExplicitlyEvenIfTheyEqualDefault(false)
{
// /--
MutexGuard aGuard( m_rMutex );
if( rOther.m_pImplProperties.get())
m_pImplProperties.reset( new impl::ImplOPropertySet( * rOther.m_pImplProperties.get()));
// \--
}
void OPropertySet::SetNewValuesExplicitlyEvenIfTheyEqualDefault()
{
m_bSetNewValuesExplicitlyEvenIfTheyEqualDefault = true;
}
OPropertySet::~OPropertySet()
{}
void OPropertySet::disposePropertySet()
{
m_pImplProperties.reset( 0 );
}
Any SAL_CALL OPropertySet::queryInterface( const uno::Type& aType )
throw (uno::RuntimeException)
{
return ::cppu::queryInterface(
aType,
// static_cast< uno::XInterface * >(
// static_cast< uno::XWeak * >( this )),
// static_cast< uno::XWeak * >( this ),
// static_cast< lang::XServiceInfo * >( this ),
static_cast< lang::XTypeProvider * >( this ),
static_cast< beans::XPropertySet * >( this ),
static_cast< beans::XMultiPropertySet * >( this ),
static_cast< beans::XFastPropertySet * >( this ),
static_cast< beans::XPropertyState * >( this ),
static_cast< beans::XMultiPropertyStates * >( this ),
static_cast< XStyleSupplier * >( this ) );
// static_cast< XFastPropertyState * >( this ) );
}
// void SAL_CALL OPropertySet::acquire() throw ()
// {
// OWeakObject::acquire();
// }
// void SAL_CALL OPropertySet::release() throw ()
// {
// OWeakObject::release();
// }
// ____ XServiceInfo ____
// OUString SAL_CALL
// OPropertySet::getImplementationName()
// throw (uno::RuntimeException)
// {
// return OUString( RTL_CONSTASCII_USTRINGPARAM( "property::OPropertySet" ));
// }
// sal_Bool SAL_CALL
// OPropertySet::supportsService( const OUString& ServiceName )
// throw (uno::RuntimeException)
// {
// return ( 0 == ServiceName.reverseCompareToAsciiL(
// RTL_CONSTASCII_STRINGPARAM( "com.sun.star.beans.PropertySet" )));
// }
// Sequence< OUString > SAL_CALL
// OPropertySet::getSupportedServiceNames()
// throw (uno::RuntimeException)
// {
// Sequence< OUString > aServiceNames( 1 );
// aServiceNames[ 0 ] = OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.beans.PropertySet" ));
// return aServiceNames;
// }
#define LCL_PROP_CPPUTYPE(t) (::getCppuType( reinterpret_cast< const Reference<t> *>(0)))
// // ____ XTypeProvider ____
Sequence< uno::Type > SAL_CALL
OPropertySet::getTypes()
throw (uno::RuntimeException)
{
static Sequence< uno::Type > aTypeList;
// /--
MutexGuard aGuard( m_rMutex );
if( aTypeList.getLength() == 0 )
{
::std::vector< uno::Type > aTypes;
// aTypes.push_back( LCL_PROP_CPPUTYPE( uno::XWeak ));
// aTypes.push_back( LCL_PROP_CPPUTYPE( lang::XServiceInfo ));
aTypes.push_back( LCL_PROP_CPPUTYPE( lang::XTypeProvider ));
aTypes.push_back( LCL_PROP_CPPUTYPE( beans::XPropertySet ));
aTypes.push_back( LCL_PROP_CPPUTYPE( beans::XMultiPropertySet ));
aTypes.push_back( LCL_PROP_CPPUTYPE( beans::XFastPropertySet ));
aTypes.push_back( LCL_PROP_CPPUTYPE( beans::XPropertyState ));
aTypes.push_back( LCL_PROP_CPPUTYPE( beans::XMultiPropertyStates ));
aTypes.push_back( LCL_PROP_CPPUTYPE( XStyleSupplier ));
// aTypes.push_back( LCL_PROP_CPPUTYPE( XFastPropertyState ));
aTypeList = ::chart::ContainerHelper::ContainerToSequence( aTypes );
}
return aTypeList;
// \--
}
Sequence< sal_Int8 > SAL_CALL
OPropertySet::getImplementationId()
throw (uno::RuntimeException)
{
static uno::Sequence< sal_Int8 > aId;
if( aId.getLength() == 0 )
{
aId.realloc( 16 );
rtl_createUuid( (sal_uInt8 *)aId.getArray(), 0, sal_True );
}
return aId;
}
// ____ XPropertyState ____
beans::PropertyState SAL_CALL
OPropertySet::getPropertyState( const OUString& PropertyName )
throw (beans::UnknownPropertyException,
uno::RuntimeException)
{
cppu::IPropertyArrayHelper & rPH = getInfoHelper();
return m_pImplProperties->GetPropertyStateByHandle(
rPH.getHandleByName( PropertyName ));
}
Sequence< beans::PropertyState > SAL_CALL
OPropertySet::getPropertyStates( const Sequence< OUString >& aPropertyName )
throw (beans::UnknownPropertyException,
uno::RuntimeException)
{
cppu::IPropertyArrayHelper & rPH = getInfoHelper();
sal_Int32 * pHandles = new sal_Int32[ aPropertyName.getLength() ];
rPH.fillHandles( pHandles, aPropertyName );
::std::vector< sal_Int32 > aHandles( pHandles, pHandles + aPropertyName.getLength());
delete[] pHandles;
return m_pImplProperties->GetPropertyStatesByHandle( aHandles );
}
void SAL_CALL
OPropertySet::setPropertyToDefault( const OUString& PropertyName )
throw (beans::UnknownPropertyException,
uno::RuntimeException)
{
cppu::IPropertyArrayHelper & rPH = getInfoHelper();
m_pImplProperties->SetPropertyToDefault( rPH.getHandleByName( PropertyName ));
firePropertyChangeEvent();
}
Any SAL_CALL
OPropertySet::getPropertyDefault( const OUString& aPropertyName )
throw (beans::UnknownPropertyException,
lang::WrappedTargetException,
uno::RuntimeException)
{
cppu::IPropertyArrayHelper & rPH = getInfoHelper();
return GetDefaultValue( rPH.getHandleByName( aPropertyName ) );
}
// ____ XMultiPropertyStates ____
// Note: getPropertyStates() is already implemented in XPropertyState with the
// same signature
void SAL_CALL
OPropertySet::setAllPropertiesToDefault()
throw (uno::RuntimeException)
{
m_pImplProperties->SetAllPropertiesToDefault();
firePropertyChangeEvent();
}
void SAL_CALL
OPropertySet::setPropertiesToDefault( const Sequence< OUString >& aPropertyNames )
throw (beans::UnknownPropertyException,
uno::RuntimeException)
{
cppu::IPropertyArrayHelper & rPH = getInfoHelper();
sal_Int32 * pHandles = new sal_Int32[ aPropertyNames.getLength() ];
rPH.fillHandles( pHandles, aPropertyNames );
::std::vector< sal_Int32 > aHandles( pHandles, pHandles + aPropertyNames.getLength());
delete[] pHandles;
m_pImplProperties->SetPropertiesToDefault( aHandles );
}
Sequence< Any > SAL_CALL
OPropertySet::getPropertyDefaults( const Sequence< OUString >& aPropertyNames )
throw (beans::UnknownPropertyException,
lang::WrappedTargetException,
uno::RuntimeException)
{
::cppu::IPropertyArrayHelper & rPH = getInfoHelper();
const sal_Int32 nElements = aPropertyNames.getLength();
Sequence< Any > aResult( nElements );
Any * pResultArray = aResult.getArray();
sal_Int32 nI = 0;
for( ; nI < nElements; ++nI )
{
pResultArray[ nI ] = GetDefaultValue(
rPH.getHandleByName( aPropertyNames[ nI ] ));
}
return aResult;
}
sal_Bool SAL_CALL OPropertySet::convertFastPropertyValue
( Any & rConvertedValue,
Any & rOldValue,
sal_Int32 nHandle,
const Any& rValue )
throw (lang::IllegalArgumentException)
{
getFastPropertyValue( rOldValue, nHandle );
//accept longs also for short values
{
sal_Int16 nValue;
if( (rOldValue>>=nValue) && !(rValue>>=nValue) )
{
sal_Int32 n32Value = 0;
if( rValue>>=n32Value )
{
rConvertedValue = uno::makeAny( static_cast<sal_Int16>(n32Value) );
return sal_True;
}
sal_Int64 n64Value = 0;
if( rValue>>=n64Value )
{
rConvertedValue = uno::makeAny( static_cast<sal_Int16>(n64Value) );
return sal_True;
}
}
}
rConvertedValue = rValue;
if( !m_bSetNewValuesExplicitlyEvenIfTheyEqualDefault && rOldValue == rConvertedValue )
return sal_False;//no change necessary
return sal_True;
}
void SAL_CALL OPropertySet::setFastPropertyValue_NoBroadcast
( sal_Int32 nHandle,
const Any& rValue )
throw (uno::Exception)
{
#if OSL_DEBUG_LEVEL > 0
if( rValue.hasValue())
{
cppu::IPropertyArrayHelper & rPH = getInfoHelper();
OUString aName;
rPH.fillPropertyMembersByHandle( &aName, 0, nHandle );
OSL_ENSURE( rValue.isExtractableTo( rPH.getPropertyByName( aName ).Type ),
"Property type is wrong" );
}
#endif
Any aDefault;
try
{
aDefault = GetDefaultValue( nHandle );
}
catch( beans::UnknownPropertyException ex )
{
aDefault.clear();
}
m_pImplProperties->SetPropertyValueByHandle( nHandle, rValue );
if( !m_bSetNewValuesExplicitlyEvenIfTheyEqualDefault && aDefault.hasValue() && aDefault == rValue ) //#i98893# don't export defaults to file
m_pImplProperties->SetPropertyToDefault( nHandle );
else
m_pImplProperties->SetPropertyValueByHandle( nHandle, rValue );
}
void SAL_CALL OPropertySet::getFastPropertyValue
( Any& rValue,
sal_Int32 nHandle ) const
{
if( ! m_pImplProperties->GetPropertyValueByHandle( rValue, nHandle ))
{
// OSL_TRACE( "OPropertySet: asking style for property" );
// property was not set -> try style
uno::Reference< beans::XFastPropertySet > xStylePropSet( m_pImplProperties->GetStyle(), uno::UNO_QUERY );
if( xStylePropSet.is() )
{
#ifdef DBG_UTIL
{
// check if the handle of the style points to the same property
// name as the handle in this property set
uno::Reference< beans::XPropertySet > xPropSet( xStylePropSet, uno::UNO_QUERY );
if( xPropSet.is())
{
uno::Reference< beans::XPropertySetInfo > xInfo( xPropSet->getPropertySetInfo(),
uno::UNO_QUERY );
if( xInfo.is() )
{
// for some reason the virtual method getInfoHelper() is
// not const
::cppu::IPropertyArrayHelper & rPH =
const_cast< OPropertySet * >( this )->getInfoHelper();
// find the Property with Handle nHandle in Style
Sequence< beans::Property > aProps( xInfo->getProperties() );
sal_Int32 nI = aProps.getLength() - 1;
while( ( nI >= 0 ) && nHandle != aProps[ nI ].Handle )
--nI;
if( nI >= 0 ) // => nHandle == aProps[nI].Handle
{
// check whether the handle in this property set is
// the same as the one in the style
beans::Property aProp( rPH.getPropertyByName( aProps[ nI ].Name ) );
OSL_ENSURE( nHandle == aProp.Handle,
"HandleCheck: Handles for same property differ!" );
if( nHandle == aProp.Handle )
{
OSL_ENSURE( aProp.Type == aProps[nI].Type,
"HandleCheck: Types differ!" );
OSL_ENSURE( aProp.Attributes == aProps[nI].Attributes,
"HandleCheck: Attributes differ!" );
}
}
else
{
OSL_ENSURE( false, "HandleCheck: Handle not found in Style" );
}
}
else
OSL_ENSURE( false, "HandleCheck: Invalid XPropertySetInfo returned" );
}
else
OSL_ENSURE( false, "HandleCheck: XPropertySet not supported" );
}
#endif
rValue = xStylePropSet->getFastPropertyValue( nHandle );
}
else
{
// OSL_TRACE( "OPropertySet: no style => getting default for property" );
// there is no style (or the style does not support XFastPropertySet)
// => take the default value
try
{
rValue = GetDefaultValue( nHandle );
}
catch( beans::UnknownPropertyException ex )
{
rValue.clear();
}
}
}
}
void OPropertySet::firePropertyChangeEvent()
{
// nothing in base class
}
// ____ XStyleSupplier ____
Reference< style::XStyle > SAL_CALL OPropertySet::getStyle()
throw (uno::RuntimeException)
{
return m_pImplProperties->GetStyle();
}
void SAL_CALL OPropertySet::setStyle( const Reference< style::XStyle >& xStyle )
throw (lang::IllegalArgumentException,
uno::RuntimeException)
{
if( ! m_pImplProperties->SetStyle( xStyle ))
throw lang::IllegalArgumentException(
OUString( RTL_CONSTASCII_USTRINGPARAM( "Empty Style" )),
static_cast< beans::XPropertySet * >( this ),
0 );
}
// ____ XFastPropertyState ____
// beans::PropertyState OPropertySet::SAL_CALL getFastPropertyState( sal_Int32 nHandle )
// throw (beans::UnknownPropertyException,
// uno::RuntimeException)
// {
// return m_pImplProperties->GetPropertyStateByHandle( nHandle );
// }
// uno::Sequence< beans::PropertyState > OPropertySet::SAL_CALL getFastPropertyStates(
// const uno::Sequence< sal_Int32 >& aHandles )
// throw (beans::UnknownPropertyException,
// uno::RuntimeException)
// {
// ::std::vector< sal_Int32 > aHandleVec(
// aHandles.getConstArray(),
// aHandles.getConstArray() + aHandles.getLength() );
// return m_pImplProperties->GetPropertyStatesByHandle( aHandleVec );
// }
// void OPropertySet::SAL_CALL setFastPropertyToDefault( sal_Int32 nHandle )
// throw (beans::UnknownPropertyException,
// uno::RuntimeException)
// {
// m_pImplProperties->SetPropertyToDefault( nHandle );
// }
// uno::Any OPropertySet::SAL_CALL getFastPropertyDefault( sal_Int32 nHandle )
// throw (beans::UnknownPropertyException,
// lang::WrappedTargetException,
// uno::RuntimeException)
// {
// return GetDefaultValue( nHandle );
// }
// ____ XMultiPropertySet ____
void SAL_CALL OPropertySet::setPropertyValues(
const Sequence< OUString >& PropertyNames, const Sequence< Any >& Values )
throw(beans::PropertyVetoException,
lang::IllegalArgumentException,
lang::WrappedTargetException,
uno::RuntimeException)
{
::cppu::OPropertySetHelper::setPropertyValues( PropertyNames, Values );
firePropertyChangeEvent();
}
// ____ XFastPropertySet ____
void SAL_CALL OPropertySet::setFastPropertyValue( sal_Int32 nHandle, const Any& rValue )
throw(beans::UnknownPropertyException,
beans::PropertyVetoException,
lang::IllegalArgumentException,
lang::WrappedTargetException, uno::RuntimeException)
{
::cppu::OPropertySetHelper::setFastPropertyValue( nHandle, rValue );
firePropertyChangeEvent();
}
} // namespace property
| 33.538899 | 144 | 0.630099 | [
"vector"
] |
f1449d20f79631b1b970b0527f4a4f6ee0990235 | 9,531 | cc | C++ | simple_jepg.cc | smarsu/SMJEPG | b723fd267042a796f16e9c16dd90c65e104270eb | [
"MIT"
] | null | null | null | simple_jepg.cc | smarsu/SMJEPG | b723fd267042a796f16e9c16dd90c65e104270eb | [
"MIT"
] | null | null | null | simple_jepg.cc | smarsu/SMJEPG | b723fd267042a796f16e9c16dd90c65e104270eb | [
"MIT"
] | null | null | null | // Copyright (c) 2020 smarsufan. All Rights Reserved.
#include <fstream>
#include <iostream>
#include <sys/time.h>
#include <cstring>
#include <cassert>
#include <cmath>
#include "simple_jepg.h"
static uint8_t zip_table_[64] = {
0, 1, 5, 6, 14, 15, 27, 28,
2, 4, 7, 13, 16, 26, 29, 42,
3, 8, 12, 17, 25, 30, 41, 43,
9, 11, 18, 24, 31, 40, 44, 53,
10, 19, 23, 32, 39, 45, 52, 54,
20, 22, 33, 38, 46, 41, 55, 60,
21, 34, 37, 47, 50, 56, 59, 61,
35, 36, 48, 49, 57, 58, 62, 63,
};
static float MtxIDCT[64] = {
0.3536, 0.4904, 0.4619, 0.4157, 0.3536, 0.2778, 0.1913, 0.0975,
0.3536, 0.4157, 0.1913, -0.0975, -0.3536, -0.4904, -0.4619, -0.2778,
0.3536, 0.2778, -0.1913, -0.4904, -0.3536, 0.0975, 0.4619, 0.4157,
0.3536, 0.0975, -0.4619, -0.2778, 0.3536, 0.4157, -0.1913, -0.4904,
0.3536, -0.0975, -0.4619, 0.2778, 0.3536, -0.4157, -0.1913, 0.4904,
0.3536, -0.2778, -0.1913, 0.4904, -0.3536, -0.0975, 0.4619, -0.4157,
0.3536, -0.4157, 0.1913, 0.0975, -0.3536, 0.4904, -0.4619, 0.2778,
0.3536, -0.4904, 0.4619, -0.4157, 0.3536, -0.2778, 0.1913, -0.0975,
};
static float MtxDCT[64] = {
0.3536, 0.3536, 0.3536, 0.3536, 0.3536, 0.3536, 0.3536, 0.3536,
0.4904, 0.4157, 0.2778, 0.0975, -0.0975, -0.2778, -0.4157, -0.4904,
0.4619, 0.1913, -0.1913, -0.4619, -0.4619, -0.1913, 0.1913, 0.4619,
0.4157, -0.0975, -0.4904, -0.2778, 0.2778, 0.4904, 0.0975, -0.4157,
0.3536, -0.3536, -0.3536, 0.3536, 0.3536, -0.3536, -0.3536, 0.3536,
0.2778, -0.4904, 0.0975, 0.4157, -0.4157, -0.0975, 0.4904, -0.2778,
0.1913, -0.4619, 0.4619, -0.1913, -0.1913, 0.4619, -0.4619, 0.1913,
0.0975, -0.2778, 0.4157, -0.4904, 0.4904, -0.4157, 0.2778, -0.0975
};
template<typename T, typename... Ts>
std::unique_ptr<T> make_unique(Ts&&... params) {
return std::unique_ptr<T>(new T(std::forward<Ts>(params)...));
}
int64_t timeus() {
struct timeval tv;
gettimeofday(&tv,NULL);
return tv.tv_sec * 1000000 + tv.tv_usec;
}
std::unique_ptr<std::vector<uint8_t>> Read(const std::string &path) {
std::ifstream fb(path);
if (!fb.is_open()) {
return nullptr;
}
fb.seekg(0, fb.end);
size_t size = fb.tellg();
fb.seekg(0, fb.beg);
std::unique_ptr<std::vector<uint8_t>> vec = make_unique<std::vector<uint8_t>>(size);
fb.read(reinterpret_cast<char *>(vec->data()), size);
fb.close();
return std::move(vec);
}
template <typename T, typename V, typename R>
void matmul(T *A, V *B, R *C) {
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
R sum = 0;
for (int k = 0; k < 8; ++k) {
sum += A[i * 8 + k] * B[k * 8 + j];
}
C[i * 8 + j] = round(sum);
}
}
}
JPEGDecoder::JPEGDecoder(const std::string path) {
raw_ = Read(path);
raw_data_ = raw_->data();
Decode();
}
int pack(uint8_t *ptr, int size, bool isLittleEnd) {
// TODO: Decode little endian and big endian.
return -1;
}
void JPEGDecoder::Decode() {
GetQuantTable();
GetSize();
GetHuffmanTable();
DecodeData();
}
void JPEGDecoder::GetQuantTable() {
quant_tables_[0] = raw_data_ + 25;
quant_tables_[1] = raw_data_ + 25 + 64 + 5;
#ifndef NDEBUG
std::cout << "quant Y: " << std::endl;
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
std::cout << int(quant_tables_[0][i * 8 + j]) << " ";
}
std::cout << std::endl;
}
std::cout << "quant C: " << std::endl;
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
std::cout << int(quant_tables_[1][i * 8 + j]) << " ";
}
std::cout << std::endl;
}
#endif
}
void JPEGDecoder::GetSize() {
uint8_t *height_ptr = raw_data_ + 163;
uint8_t *width_ptr = raw_data_ + 165;
height_ = (height_ptr[0] << 8) | height_ptr[1];
width_ = (width_ptr[0] << 8) | width_ptr[1];
#ifndef NDEBUG
std::cout << "height ... " << height_ << " width ... " << width_ << std::endl;
#endif
}
void JPEGDecoder::GetHuffmanTable() {
uint8_t *ptr = raw_data_ + 181;
ptr = DecodeHuffmanTable(ptr);
ptr += 4;
ptr = DecodeHuffmanTable(ptr);
ptr += 4;
ptr = DecodeHuffmanTable(ptr);
ptr += 4;
ptr = DecodeHuffmanTable(ptr);
#ifndef NDEBUG
huffman.show();
#endif
}
uint8_t *JPEGDecoder::DecodeHuffmanTable(uint8_t *ptr) {
uint8_t table_idx = ptr[0];
auto &table = huffman[table_idx];
uint8_t *num_keys_ptr = ptr + 1;
uint8_t *val_ptr = num_keys_ptr + 16;
uint16_t pre_bits_value = 0;
for (int idx = 0; idx < 16; ++idx) {
pre_bits_value <<= 1;
int high_key = (idx + 1) << 16;
uint8_t num = num_keys_ptr[idx];
for (uint8_t n = 0; n < num; ++n) {
uint8_t val = (val_ptr++)[0];
int low_key = (n + pre_bits_value);
table[high_key | low_key] = val;
}
pre_bits_value += num;
}
return val_ptr;
}
void JPEGDecoder::DecodeData() {
im_data_ = raw_data_ + 623;
bit_value_ = im_data_[0];
int h_block = (height_ + 16 - 1) / 16;
int w_block = (width_ + 16 - 1) / 16;
float matrix[6][64];
data_ = new uint8_t[height_ * width_ * 3];
for (int h_block_id = 0; h_block_id < h_block; ++h_block_id) {
for (int w_block_id = 0; w_block_id < w_block; ++w_block_id) {
memset(matrix, 0, sizeof(matrix));
// Decode matrix Y
DecodeMatrix(matrix[0], 0, quant_tables_[0], dc[0]);
DecodeMatrix(matrix[1], 0, quant_tables_[0], dc[0]);
DecodeMatrix(matrix[2], 0, quant_tables_[0], dc[0]);
DecodeMatrix(matrix[3], 0, quant_tables_[0], dc[0]);
// Decode matrix Cb
DecodeMatrix(matrix[4], 1, quant_tables_[1], dc[1]);
// Decode matrix Cr
DecodeMatrix(matrix[5], 1, quant_tables_[1], dc[2]);
// YUV2RGB
{
int h_offset = h_block_id * 16;
int w_offset = w_block_id * 16;
YUV2RGB(data_, matrix[0], matrix[4], matrix[5], std::min(8, height_ - h_offset), std::min(8, width_ - w_offset), h_offset, w_offset);
YUV2RGB(data_, matrix[1], matrix[4] + 4, matrix[5] + 4, std::min(8, height_ - h_offset), std::min(8, width_ - w_offset + 8), h_offset, w_offset + 8);
YUV2RGB(data_, matrix[2], matrix[4] + 4 * 8, matrix[5] + 4 * 8, std::min(8, height_ - h_offset - 8), std::min(8, width_ - w_offset), h_offset + 8, w_offset);
YUV2RGB(data_, matrix[3], matrix[4] + 4 * 8 + 4, matrix[5] + 4 * 8 + 4, std::min(8, height_ - h_offset - 8), std::min(8, width_ - w_offset + 8), h_offset + 8, w_offset + 8);
}
}
}
}
void JPEGDecoder::DecodeMatrix(float *matrix, uint8_t table_idx, uint8_t *quant, int &dc) {
auto &table = huffman[table_idx];
uint8_t len = FindInHuffmanTable(table);
int value = GetValue(len);
dc += value;
matrix[0] = dc;
auto &ac_table = huffman[table_idx | 16];
for (int idx = 1; idx < 64; ++idx) {
uint8_t len = FindInHuffmanTable(ac_table);
if (len == 0) break;
value = GetValue(len & 0xf);
idx += (len >> 4);
matrix[idx] = value;
}
for (int idx = 0; idx < 64; ++idx) {
matrix[idx] *= quant[idx];
}
unzip(matrix);
IDCT(matrix);
}
uint8_t JPEGDecoder::FindInHuffmanTable(std::unordered_map<int, uint8_t> &table) {
int val = 0;
for (int idx = 0; idx < 16; ++idx) {
val <<= 1;
val += NextBit();
int r_val = ((idx + 1) << 16) | val;
if (table.find(r_val) != table.end()) {
return table[r_val];
}
}
assert(0);
}
int JPEGDecoder::NextBit() {
if (bit_mask_ == 0x00) {
bit_mask_ = 0x80;
// bit_offset = 0;
bit_value_ = (++im_data_)[0];
if (bit_value_ == 0xFF) {
bit_value_ = (++im_data_)[0];
switch (bit_value_) {
case 0x00:
bit_value_ = 0xFF;
break;
case 0xD7:
dc[0] = dc[1] = dc[2] = 0;
break;
default:
break;
}
}
}
int val = bit_mask_ & bit_value_;
bit_mask_ >>= 1;
// bit_offset += 1;
return val > 0 ? 1 : 0;
}
int JPEGDecoder::GetValue(uint8_t len) {
// if (len == 0) return 0;
// int tag = -2 * NextBit() + 1;
// int value = 0;
// for (int idx = 1; idx < len; ++idx) {
// value = (value << 1) | NextBit();
// }
// value *= tag;
// return value;
int value = 0;
for (int idx = 0; idx < len; ++idx) {
value = (value << 1) + NextBit();
}
return value >= pow(2, len - 1) ? value : value - pow(2, len) + 1;
}
template <typename T>
void JPEGDecoder::unzip(T *matrix) {
memcpy(unzip_matrix_, matrix, sizeof(T) * 64);
for (int idx = 0; idx < 64; ++idx) {
matrix[idx] = unzip_matrix_[zip_table_[idx]];
}
}
template <typename T>
void JPEGDecoder::IDCT(T *matrix) {
matmul(MtxIDCT, matrix, unzip_matrix_);
matmul(unzip_matrix_, MtxDCT, matrix);
}
template <typename T>
void JPEGDecoder::YUV2RGB(uint8_t *data, T *Y, T *Cr, T *Cb, int h, int w, int rh, int rw) {
for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j) {
uint8_t *rgb = data + ((i + rh) * width_ + j + rw) * 3;
T y = Y[i * 8 + j];
T cr = Cr[i / 2 * 8 + j / 2];
T cb = Cb[i / 2 * 8 + j / 2];
T R = y + 1.402f * cr + 128.f;
T G = y - 0.34414f * cb - 0.71414f * cr + 128.f;
T B = y + 1.772f * cb + 128.f;
R = std::min(std::max(R, 0.f), 255.f);
G = std::min(std::max(G, 0.f), 255.f);
B = std::min(std::max(B, 0.f), 255.f);
rgb[0] = R;
rgb[1] = G;
rgb[2] = B;
}
}
}
| 27.466859 | 181 | 0.545168 | [
"vector"
] |
f14ae8ad3588124ca4db185a8c9dcac3074ce04a | 9,876 | cpp | C++ | correlation_view_plugin/correlation_calc.cpp | rabouwlab/phast | 8134f8e86c72f9212be4ca142c59635ce93ba160 | [
"MIT"
] | 1 | 2021-05-22T17:40:51.000Z | 2021-05-22T17:40:51.000Z | correlation_view_plugin/correlation_calc.cpp | rabouwlab/phast | 8134f8e86c72f9212be4ca142c59635ce93ba160 | [
"MIT"
] | null | null | null | correlation_view_plugin/correlation_calc.cpp | rabouwlab/phast | 8134f8e86c72f9212be4ca142c59635ce93ba160 | [
"MIT"
] | 1 | 2021-03-15T07:09:03.000Z | 2021-03-15T07:09:03.000Z | /* Copyright (c) 2020 Stijn Hinterding, Utrecht University
* This sofware is licensed under the MIT license (see the LICENSE file)
*/
#include "correlation_calc.h"
#include <phast_gui/support/detectionupdate.h>
#include <libtimetag/algos.h>
#include <math.h>
correlation_calc::correlation_calc(const std::vector<chan_id>& chans_to_correlate,
uint64_t bin_width,
opaque_ptr our_ref,
double bin_low,
double bin_high,
bool display_only_initial_data,
double time_unit,
bool correlate_FCS) :
Base_ui_calc(chans_to_correlate, bin_width, our_ref, display_only_initial_data, time_unit),
leftchannel(chans_to_correlate.at(0)),
rightchannel(chans_to_correlate.at(1)),
t_min(INT64_MAX),
t_max(0),
bin_low(bin_low),
bin_high(bin_high),
n_photons_left(0),
n_photons_right(0),
correlate_FCS(correlate_FCS)
{
if (!correlate_FCS) {
int64_t len = linspace_len(static_cast<timestamp>(this->bin_low),
static_cast<timestamp>(this->bin_high), 1, 1, 1);
this->xs.resize(len, 0);
this->ys.resize(len - 1, 0);
linspace(this->bin_low, this->bin_high, 1, 1, 1, this->xs.data(), this->xs.size());
} else {
this->xs.resize(this->bin_width, 0);
this->ys.resize(this->bin_width - 1, 0);
std::vector<double> temp(this->bin_width, 0);
logspace(log10(this->bin_low),
log10(this->bin_high),
this->bin_width,
10,
temp.data());
for (uint64_t i = 0; i < temp.size(); i++) {
this->xs[i] = (int64_t)temp[i];
}
}
}
void correlation_calc::ClearData()
{
this->ys.clear();
this->ys.resize(this->xs.size() - 1, 0);
this->n_photons_left = 0;
this->n_photons_right = 0;
this->t_min = INT64_MAX;
this->t_max = 0;
data_displayed = false;
}
chan_data_map correlation_calc::get_times_to_save(DetectionUpdate event) const
{
int64_t lower_bound = this->bin_low;
int64_t abs_lower_bound = this->t_max + lower_bound;
chan_data_map ret;
for (auto pair : event.updates) { // For each channel...
chan_id chan = pair.first;
chan_det_update update = pair.second;
// If we are not interested in this channel,
// signal that everything can be trashed.
if (chan != this->leftchannel && chan != this->rightchannel) {
ret[chan] = update.macro_end;
continue;
}
uint64_t counter = 0;
for (data_type it = update.macro_start; it != update.macro_end; ++it) {
counter++;
if (*it > abs_lower_bound) {
ret[chan] = it;
break;
}
}
}
return ret;
}
void correlation_calc::update_tmin(DetectionUpdate event)
{
if (event.updates.count(this->leftchannel) == 0 ||
event.updates.count(this->rightchannel) == 0) {
// We don't have any data to work with.
return;
}
chan_det_update left = event.updates.at(this->leftchannel);
chan_det_update right = event.updates.at(this->rightchannel);
timestamp t_min_= INT64_MAX;
if (left.n_new_macro != 0) {
if (*left.new_macro_start < t_min_) {
t_min_ = *left.new_macro_start;
}
}
if (right.n_new_macro != 0) {
if (*right.new_macro_start < t_min_) {
t_min_ = *right.new_macro_start;
}
}
if (t_min_ < this->t_min) {
this->t_min = t_min_;
}
}
void correlation_calc::update_tmax(DetectionUpdate event)
{
if (event.updates.count(this->leftchannel) == 0 ||
event.updates.count(this->rightchannel) == 0) {
// We don't have any data to work with.
return;
}
chan_det_update left = event.updates.at(this->leftchannel);
chan_det_update right = event.updates.at(this->rightchannel);
timestamp t_max_= 0;
if (left.n_new_macro != 0) {
if (*(left.macro_end-1) > t_max_) {
t_max_ = *(left.macro_end-1);
}
}
if (right.n_new_macro != 0) {
if (*(right.macro_end-1) > t_max_) {
t_max_ = *(right.macro_end-1);
}
}
if (t_max_ > this->t_max) {
this->t_max = t_max_;
}
}
void correlation_calc::update_n_photons_leftchan(DetectionUpdate event)
{
if (event.updates.count(this->leftchannel) == 0)
return;
this->n_photons_left += event.updates.at(this->leftchannel).n_new_macro;
}
void correlation_calc::update_n_photons_rightchan(DetectionUpdate event)
{
if (event.updates.count(this->rightchannel) == 0)
return;
this->n_photons_right += event.updates.at(this->rightchannel).n_new_macro;
}
DataView::data_update correlation_calc::arrange_update(DetectionUpdate event, bool rebin_only)
{
DataView::data_update ret;
if (event.updates.count(this->leftchannel) == 0 ||
event.updates.count(this->rightchannel) == 0) {
// We don't have any data to work with.
return ret;
}
chan_det_update left = event.updates.at(this->leftchannel);
chan_det_update right = event.updates.at(this->rightchannel);
if (!rebin_only) {
// See if we have any photons
this->update_tmin(event);
this->update_tmax(event);
this->update_n_photons_leftchan(event);
this->update_n_photons_rightchan(event);
// First we correlate *just* the new data on channel 1 to all the data on chan 2
// Correlated are then:
// old chan 1 <-> old chan 2
// new chan 1 <-> old chan 2
// new chan 1 <-> new chan 2
//
// Still missing is:
// old chan 1 <-> new chan 2
//
// This last part we do in a second step.
if (this->correlate_FCS) {
uint64_t n_left_photons = left.n_new_macro;
uint64_t n_right_photons = right.n_macro;
if (n_left_photons != 0 && n_right_photons != 0) {
correlate_many_per_bin(this->xs.data(),
this->xs.size(),
&*left.new_macro_start,
n_left_photons,
&*right.macro_start,
n_right_photons,
this->ys.data(),
this->ys.size());
}
n_left_photons = left.n_old_macro;
n_right_photons = right.n_new_macro;
if (n_left_photons != 0 && n_right_photons != 0) {
correlate_many_per_bin(this->xs.data(),
this->xs.size(),
&*left.macro_start,
n_left_photons,
&*right.new_macro_start,
n_right_photons,
this->ys.data(),
this->ys.size());
}
} else {
correlate_unit_bins(this->xs.data(),
this->xs.size(),
&*left.new_macro_start,
left.n_new_macro,
&*right.macro_start,
right.n_macro,
this->ys.data(),
this->ys.size());
correlate_unit_bins(this->xs.data(),
this->xs.size(),
&*left.macro_start,
left.n_old_macro,
&*right.new_macro_start,
right.n_new_macro,
this->ys.data(),
this->ys.size());
}
}
std::vector<int64_t> rebinned_xs(rebin_bin_edges_len(this->xs.size(), this->bin_width), 0);
std::vector<int64_t> rebinned_ys(rebin_len(this->ys.size(), this->bin_width), 0);
if (this->bin_width > 1 && !this->correlate_FCS) {
rebin(this->ys.data(),
this->ys.size(),
this->bin_width,
rebinned_ys.data(),
rebinned_ys.size());
rebin_bin_edges(this->xs.data(),
this->xs.size(),
this->bin_width,
rebinned_xs.data(),
rebinned_xs.size());
} else {
rebinned_xs = this->xs;
rebinned_ys = this->ys;
}
std::vector<double> xs2;
std::vector<double> ys2(rebinned_ys.size(), 0.0);
normalize_correlation(rebinned_ys.data(),
rebinned_ys.size(),
rebinned_xs.data(),
rebinned_xs.size(),
this->t_min,
this->t_max,
this->n_photons_left,
this->n_photons_right,
ys2.data());
for (uint64_t i = 0; i < rebinned_xs.size() - 1; i++) {
xs2.push_back((double)rebinned_xs[i]*this->time_unit*1e9); // TODO: do not hardcode the timeunit
}
ret.xs = xs2;
ret.ys = ys2;
return ret;
}
| 32.810631 | 105 | 0.496861 | [
"vector"
] |
f14dc77f846c4762d6676ce49407de59cc94708a | 4,777 | hpp | C++ | include/mcnla/core/random/streams/streams.hpp | emfomy/mcnla | 9f9717f4d6449bbd467c186651856d6212035667 | [
"MIT"
] | null | null | null | include/mcnla/core/random/streams/streams.hpp | emfomy/mcnla | 9f9717f4d6449bbd467c186651856d6212035667 | [
"MIT"
] | null | null | null | include/mcnla/core/random/streams/streams.hpp | emfomy/mcnla | 9f9717f4d6449bbd467c186651856d6212035667 | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @file include/mcnla/core/random/streams/streams.hpp
/// @brief The random generator driver.
///
/// @author Mu Yang <<emfomy@gmail.com>>
///
#ifndef MCNLA_CORE_RANDOM_STREAMS_STREAMS_HPP_
#define MCNLA_CORE_RANDOM_STREAMS_STREAMS_HPP_
#include <mcnla/core/random/streams/streams.hh>
#include <random>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// The MCNLA namespace
//
namespace mcnla {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// The random namespace
//
namespace random {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Construct with given seed.
/// @copydoc setSeedImpl
///
Streams::Streams(
const index_t seed
) noexcept
#ifdef _OPENMP
: omp_size_(omp_get_max_threads()),
#else // _OPENMP
: omp_size_(1),
#endif // _OPENMP
streams_(omp_size_) {
setSeedImpl(seed);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Construct with given seed.
/// @copydoc setSeedsImpl
///
Streams::Streams(
const index_t seed,
const mpi_int_t mpi_root,
const MPI_Comm mpi_comm
) noexcept
#ifdef _OPENMP
: omp_size_(omp_get_max_threads()),
#else // _OPENMP
: omp_size_(1),
#endif // _OPENMP
streams_(omp_size_) {
setSeedsImpl(seed, mpi_root, mpi_comm);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Default destructor.
///
Streams::~Streams() noexcept {
#ifdef MCNLA_USE_MKL
for ( index_t i = 0; i < omp_size_; ++i ) {
vslDeleteStream(&(streams_[i]));
}
#endif // MCNLA_USE_MKL
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Gets the number of OpenMP threads.
///
index_t Streams::ompSize() const noexcept {
return omp_size_;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Gets the raw random stream.
///
Streams::StreamType& Streams::operator[](
const index_t i
) const noexcept {
return const_cast<StreamType&>(streams_[i]);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Sets the random seed.
///
void Streams::setSeed(
const index_t seed
) noexcept {
#ifdef MCNLA_USE_MKL
for ( index_t i = 0; i < omp_size_; ++i ) {
vslDeleteStream(&(streams_[i]));
}
#endif // MCNLA_USE_MKL
setSeedImpl(seed);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Generate the random seeds and send to each MPI nodes.
///
void Streams::setSeeds(
const index_t seed,
const mpi_int_t mpi_root,
const MPI_Comm mpi_comm
) noexcept {
#ifdef MCNLA_USE_MKL
for ( index_t i = 0; i < omp_size_; ++i ) {
vslDeleteStream(&(streams_[i]));
}
#endif // MCNLA_USE_MKL
setSeedsImpl(seed, mpi_root, mpi_comm);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @copydoc setSeed
///
void Streams::setSeedImpl(
const index_t seed
) noexcept {
std::seed_seq seq{seed};
std::vector<index_t> seeds(omp_size_);
seq.generate(seeds.begin(), seeds.end());
for ( index_t i = 0; i < omp_size_; ++i ) {
#ifdef MCNLA_USE_MKL
vslNewStream(&(streams_[i]), VSL_BRNG_SFMT19937, seeds[i]);
#else // MCNLA_USE_MKL
streams_[i].seed(seeds[i]);
#endif // MCNLA_USE_MKL
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @copydoc setSeeds
///
void Streams::setSeedsImpl(
const index_t seed,
const mpi_int_t mpi_root,
const MPI_Comm mpi_comm
) noexcept {
std::vector<index_t> seeds(mpi::commSize(mpi_comm));
if ( mpi::isCommRoot(mpi_root, mpi_comm) ) {
std::seed_seq seq{seed};
seq.generate(seeds.begin(), seeds.end());
}
constexpr const MPI_Datatype datatype = traits::MpiValTraits<index_t>::datatype;
index_t seed_tmp;
MPI_Scatter(seeds.data(), 1, datatype, &seed_tmp, 1, datatype, mpi_root, mpi_comm);
setSeedImpl(seed_tmp);
}
} // namespace random
} // namespace mcnla
#endif // MCNLA_CORE_RANDOM_STREAMS_STREAMS_HPP_
| 30.426752 | 128 | 0.463261 | [
"vector"
] |
f151522855d5afd599d940f1740161fde61dbb79 | 8,787 | cpp | C++ | src/tests/apps/fake_app_server/ServerApp.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 1,338 | 2015-01-03T20:06:56.000Z | 2022-03-26T13:49:54.000Z | src/tests/apps/fake_app_server/ServerApp.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 15 | 2015-01-17T22:19:32.000Z | 2021-12-20T12:35:00.000Z | src/tests/apps/fake_app_server/ServerApp.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 350 | 2015-01-08T14:15:27.000Z | 2022-03-21T18:14:35.000Z | /*
* Copyright 2001-2005, Haiku.
* Distributed under the terms of the MIT License.
*
* Authors:
* DarkWyrm <bpmagic@columbus.rr.com>
* Adrian Oanca <adioanca@cotty.iren.ro>
* Stephan Aßmus <superstippi@gmx.de>
* Stefano Ceccherini (burton666@libero.it)
* Axel Dörfler, axeld@pinc-software.de
*/
#include <AppDefs.h>
#include <List.h>
#include <String.h>
#include <stdio.h>
#include <string.h>
#include <ServerProtocol.h>
#include "AppServer.h"
#include "ServerApp.h"
//#define DEBUG_SERVERAPP
#ifdef DEBUG_SERVERAPP
# include <stdio.h>
# define STRACE(x) printf x
#else
# define STRACE(x) ;
#endif
//#define DEBUG_SERVERAPP_FONT
#ifdef DEBUG_SERVERAPP_FONT
# include <stdio.h>
# define FTRACE(x) printf x
#else
# define FTRACE(x) ;
#endif
/*!
\brief Constructor
\param sendport port ID for the BApplication which will receive the ServerApp's messages
\param rcvport port by which the ServerApp will receive messages from its BApplication.
\param fSignature NULL-terminated string which contains the BApplication's
MIME fSignature.
*/
ServerApp::ServerApp(port_id sendport, port_id rcvport, port_id clientLooperPort,
team_id clientTeamID, int32 handlerID, const char* signature)
:
fClientAppPort(sendport),
fMessagePort(rcvport),
fClientLooperPort(clientLooperPort),
fSignature(signature),
fMonitorThreadID(-1),
fClientTeamID(clientTeamID),
fLink(fClientAppPort, fMessagePort),
fLockSem(create_sem(1, "ServerApp sem")),
fCursorHidden(false),
fIsActive(false),
fQuitting(false)
{
if (fSignature == "")
fSignature = "application/x-vnd.NULL-application-signature";
Run();
STRACE(("ServerApp %s:\n", fSignature.String()));
STRACE(("\tBApp port: %ld\n", fClientAppPort));
STRACE(("\tReceiver port: %ld\n", fMessagePort));
}
//! Does all necessary teardown for application
ServerApp::~ServerApp(void)
{
STRACE(("*ServerApp %s:~ServerApp()\n",fSignature.String()));
fQuitting = true;
// This shouldn't be necessary -- all cursors owned by the app
// should be cleaned up by RemoveAppCursors
// if(fAppCursor)
// delete fAppCursor;
delete_sem(fLockSem);
STRACE(("#ServerApp %s:~ServerApp()\n", fSignature.String()));
// TODO: Is this the right place for this ?
// From what I've understood, this is the port created by
// the BApplication (?), but if I delete it in there, GetNextMessage()
// in the MonitorApp thread never returns. Cleanup.
delete_port(fMessagePort);
status_t dummyStatus;
wait_for_thread(fMonitorThreadID, &dummyStatus);
STRACE(("ServerApp %s::~ServerApp(): Exiting\n", fSignature.String()));
}
/*!
\brief Starts the ServerApp monitoring for messages
\return false if the application couldn't start, true if everything went OK.
*/
bool
ServerApp::Run(void)
{
// Unlike a BApplication, a ServerApp is *supposed* to return immediately
// when its Run() function is called.
fMonitorThreadID = spawn_thread(MonitorApp, fSignature.String(), B_NORMAL_PRIORITY, this);
if (fMonitorThreadID < B_OK)
return false;
return resume_thread(fMonitorThreadID) == B_OK;
}
/*!
\brief Pings the target app to make sure it's still working
\return true if target is still "alive" and false if "He's dead, Jim."
"But that's impossible..."
This function is called by the app_server thread to ensure that
the target app still exists. We do this not by sending a message
but by calling get_port_info. We don't want to send ping messages
just because the app might simply be hung. If this is the case, it
should be up to the user to kill it. If the app has been killed, its
ports will be invalid. Thus, if get_port_info returns an error, we
tell the app_server to delete the respective ServerApp.
*/
bool
ServerApp::PingTarget(void)
{
team_info tinfo;
if (get_team_info(fClientTeamID, &tinfo) == B_BAD_TEAM_ID) {
BPrivate::LinkSender link(gAppServerPort);
link.StartMessage(AS_DELETE_APP);
link.Attach(&fMonitorThreadID, sizeof(thread_id));
link.Flush();
return false;
}
return true;
}
/*!
\brief Send a message to the ServerApp with no attachments
\param code ID code of the message to post
*/
void
ServerApp::PostMessage(int32 code)
{
BPrivate::LinkSender link(fMessagePort);
link.StartMessage(code);
link.Flush();
}
/*!
\brief Send a message to the ServerApp's BApplication
\param msg The message to send
*/
void
ServerApp::SendMessageToClient(const BMessage *msg) const
{
ssize_t size = msg->FlattenedSize();
char *buffer = new char[size];
if (msg->Flatten(buffer, size) == B_OK)
write_port(fClientLooperPort, msg->what, buffer, size);
else
printf("PANIC: ServerApp: '%s': can't flatten message in 'SendMessageToClient()'\n", fSignature.String());
delete [] buffer;
}
/*!
\brief Sets the ServerApp's active status
\param value The new status of the ServerApp.
This changes an internal flag and also sets the current cursor to the one specified by
the application
*/
void
ServerApp::Activate(bool value)
{
fIsActive = value;
}
/*!
\brief The thread function ServerApps use to monitor messages
\param data Pointer to the thread's ServerApp object
\return Throwaway value - always 0
*/
int32
ServerApp::MonitorApp(void *data)
{
// Message-dispatching loop for the ServerApp
ServerApp *app = (ServerApp *)data;
BPrivate::LinkReceiver &reader = app->fLink.Receiver();
int32 code;
status_t err = B_OK;
while (!app->fQuitting) {
STRACE(("info: ServerApp::MonitorApp listening on port %ld.\n", app->fMessagePort));
err = reader.GetNextMessage(code, B_INFINITE_TIMEOUT);
if (err < B_OK) {
STRACE(("ServerApp::MonitorApp(): GetNextMessage returned %s\n", strerror(err)));
// ToDo: this should kill the app, but it doesn't work
BPrivate::LinkSender link(gAppServerPort);
link.StartMessage(AS_DELETE_APP);
link.Attach(&app->fMonitorThreadID, sizeof(thread_id));
link.Flush();
break;
}
switch (code) {
case AS_QUIT_APP:
{
// This message is received only when the app_server is asked to shut down in
// test/debug mode. Of course, if we are testing while using AccelerantDriver, we do
// NOT want to shut down client applications. The server can be quit o in this fashion
// through the driver's interface, such as closing the ViewDriver's window.
STRACE(("ServerApp %s:Server shutdown notification received\n",
app->fSignature.String()));
// If we are using the real, accelerated version of the
// DisplayDriver, we do NOT want the user to be able shut down
// the server. The results would NOT be pretty
break;
}
case B_QUIT_REQUESTED:
{
STRACE(("ServerApp %s: B_QUIT_REQUESTED\n",app->fSignature.String()));
// Our BApplication sent us this message when it quit.
// We need to ask the app_server to delete ourself.
BPrivate::LinkSender sender(gAppServerPort);
sender.StartMessage(AS_DELETE_APP);
sender.Attach(&app->fMonitorThreadID, sizeof(thread_id));
sender.Flush();
break;
}
default:
STRACE(("ServerApp %s: Got a Message to dispatch\n", app->fSignature.String()));
app->DispatchMessage(code, reader);
break;
}
}
return 0;
}
/*!
\brief Handler function for BApplication API messages
\param code Identifier code for the message. Equivalent to BMessage::what
\param buffer Any attachments
Note that the buffer's exact format is determined by the particular message.
All attachments are placed in the buffer via a PortLink, so it will be a
matter of casting and incrementing an index variable to access them.
*/
void
ServerApp::DispatchMessage(int32 code, BPrivate::LinkReceiver &link)
{
switch (code) {
case AS_CURRENT_WORKSPACE:
{
STRACE(("ServerApp %s: get current workspace\n", fSignature.String()));
// TODO: Locking this way is not nice
fLink.StartMessage(B_OK);
fLink.Attach<int32>(0);
fLink.Flush();
break;
}
case AS_ACTIVATE_WORKSPACE:
{
STRACE(("ServerApp %s: activate workspace\n", fSignature.String()));
// TODO: See above
int32 index;
link.Read<int32>(&index);
// no reply
break;
}
case AS_QUERY_CURSOR_HIDDEN:
{
STRACE(("ServerApp %s: Received IsCursorHidden request\n", fSignature.String()));
// Attached data
// 1) int32 port to reply to
fLink.StartMessage(fCursorHidden ? B_OK : B_ERROR);
fLink.Flush();
break;
}
default:
printf("ServerApp %s received unhandled message code offset %lx\n",
fSignature.String(), code);
if (link.NeedsReply()) {
// the client is now blocking and waiting for a reply!
fLink.StartMessage(B_ERROR);
fLink.Flush();
} else
puts("message doesn't need a reply!");
break;
}
}
team_id
ServerApp::ClientTeamID() const
{
return fClientTeamID;
}
thread_id
ServerApp::MonitorThreadID() const
{
return fMonitorThreadID;
}
| 26.229851 | 108 | 0.718106 | [
"object"
] |
f15661dd0043caee83cdfce19337064ef83946d2 | 4,332 | hpp | C++ | suffix_array.hpp | nel215/sasa | 37074f07dfec4f91e6f89ed79d9f9a52f61ce3dc | [
"MIT"
] | 1 | 2016-07-07T15:00:59.000Z | 2016-07-07T15:00:59.000Z | suffix_array.hpp | nel215/sasa | 37074f07dfec4f91e6f89ed79d9f9a52f61ce3dc | [
"MIT"
] | null | null | null | suffix_array.hpp | nel215/sasa | 37074f07dfec4f91e6f89ed79d9f9a52f61ce3dc | [
"MIT"
] | null | null | null | #ifndef SUFFIX_ARRAY_HPP
#define SUFFIX_ARRAY_HPP
#include <vector>
#include <string>
#include <set>
#include <algorithm>
namespace sasa{
bool is_lms(int index, const std::vector<bool> &sl_seq){
if(index+1 == (int)sl_seq.size())return true;
if(0 < index && index < (int)sl_seq.size()){
return sl_seq[index] && !sl_seq[index-1];
}
return false;
}
std::vector<int> get_bucket(int* seq, const int n, const int alphabet_size){
std::vector<int> bucket(alphabet_size);
for(int i=0 ; i<n ; i++)bucket[seq[i]]++;
for(int i=0 ; i<alphabet_size-1 ; i++)bucket[i+1] += bucket[i];
return bucket;
}
void sort_type_l(int* seq, const int n, const std::vector<bool> &is_type_s, int* arr, const int alphabet_size){
std::vector<int> bucket = get_bucket(seq, n, alphabet_size);
for(int i=0 ; i<n ; i++){
if(arr[i] != -1 && arr[i]>0 && !is_type_s[arr[i]-1]){
arr[bucket[seq[arr[i]-1]-1]++] = arr[i]-1;
}
}
}
void sort_type_s(int* seq, const int n, const std::vector<bool> &is_type_s, int* arr, const int alphabet_size){
std::vector<int> bucket = get_bucket(seq, n, alphabet_size);
for(int i=n-1 ; i>=0 ; i--){
if(arr[i] != -1 && arr[i]>0 && is_type_s[arr[i]-1]){
arr[--bucket[seq[arr[i]-1]]] = arr[i]-1;
}
}
}
void create_suffix_array(int* arr, int* seq, const int n, const int alphabet_size){
for(int i=0 ; i<n ; i++)arr[i] = -1;
std::vector<bool> is_type_s(n);
is_type_s[n-1] = true;
for(int i=n-2 ; i>=0 ; i--){
if(seq[i] == seq[i+1])is_type_s[i] = is_type_s[i+1];
else is_type_s[i] = seq[i] < seq[i+1];
}
std::vector<int> bucket = get_bucket(seq, n, alphabet_size);
for(int i=0 ; i < n ; i++){
if(is_lms(i, is_type_s))arr[--bucket[seq[i]]] = i;
}
sort_type_l(seq, n, is_type_s, arr, alphabet_size);
sort_type_s(seq, n, is_type_s, arr, alphabet_size);
// LMS-substringの元の数値列における位置を辞書順に左詰めで格納する
int num_lms = 0;
for(int i=0 ; i<n ; i++){
if(is_lms(arr[i], is_type_s))arr[num_lms++] = arr[i];
}
// 辞書順以外を一旦クリア
for(int i=num_lms ; i<n ; i++)arr[i] = -1;
// LMS-substringのidを元の数値列における出現順で空いているところに格納する
arr[num_lms + arr[0]/2] = 0;
for(int i=1 ; i<num_lms ; i++){
int p = arr[i-1], q = arr[i];
bool same = i != 1; // 番兵回避
for(int w=1 ; same ; w++){
if(seq[p+w]!=seq[q+w])same = false;
bool p_is_lms = is_lms(p+w, is_type_s);
bool q_is_lms = is_lms(q+w, is_type_s);
if(!p_is_lms && !q_is_lms)continue;
if(!(p_is_lms && q_is_lms))same = false;
break;
}
if(same){
arr[num_lms + q/2] = arr[num_lms + p/2];
}else{
arr[num_lms + q/2] = arr[num_lms + p/2] + 1;
}
}
// LMS-substringのidを元の数値列における出現順で右詰で格納する
int next_alphabet_size = arr[num_lms + arr[num_lms-1]/2] + 1;
for(int i=n-1, p=n-1 ; i >= num_lms ; i--){
if(arr[i] != -1)arr[p--] = arr[i];
}
// 同じLMS-substringがある場合は再帰的に順序を求めるa
if(next_alphabet_size != num_lms){
create_suffix_array(arr, arr+n-num_lms, num_lms, next_alphabet_size);
for(int i=0 ; i < num_lms ; i++)arr[n-num_lms+arr[i]] = i;
for(int i=0, p=0 ; i < n ; i++){
if(is_lms(i, is_type_s)){
arr[arr[n-num_lms+p]] = i;
p++;
}
}
}
// 辞書順以外を一旦クリア
for(int i=num_lms ; i<n ; i++)arr[i] = -1;
// 配列の末尾から正規の位置に詰めなおす
bucket = get_bucket(seq, n, alphabet_size);
for(int i=num_lms-1 ; i >= 0 ; i--){
bucket[seq[arr[i]]]--;
std::swap(arr[bucket[seq[arr[i]]]], arr[i]);
}
sort_type_l(seq, n, is_type_s, arr, alphabet_size);
sort_type_s(seq, n, is_type_s, arr, alphabet_size);
}
std::vector<int> create_suffix_array_from_string(const std::string &str){
std::set<char> _alphabet(str.begin(), str.end());
std::vector<char> alphabet(_alphabet.begin(), _alphabet.end());
int n = str.size()+1;
int* seq = new int[n];
int* arr = new int[n];
for(int i=0 ; i < n-1 ; i++)seq[i] = lower_bound(alphabet.begin(), alphabet.end(), str[i]) - alphabet.begin() + 1;
create_suffix_array(arr, seq, n, alphabet.size());
return std::vector<int>(arr, arr+n);
}
};
#endif
| 32.571429 | 118 | 0.560942 | [
"vector"
] |
f15a6a46d6491e96a2a8ed3577f4b3f2b020fc2c | 10,128 | cc | C++ | src/plugins/interactive_view_control/InteractiveViewControl.cc | zflat/ign-gui | 879a8d193d0cc976587f437a2ec1254093681963 | [
"ECL-2.0",
"Apache-2.0"
] | 31 | 2020-04-17T22:47:47.000Z | 2022-03-31T11:00:06.000Z | src/plugins/interactive_view_control/InteractiveViewControl.cc | zflat/ign-gui | 879a8d193d0cc976587f437a2ec1254093681963 | [
"ECL-2.0",
"Apache-2.0"
] | 297 | 2020-04-25T02:55:37.000Z | 2022-03-30T20:18:23.000Z | src/plugins/interactive_view_control/InteractiveViewControl.cc | zflat/ign-gui | 879a8d193d0cc976587f437a2ec1254093681963 | [
"ECL-2.0",
"Apache-2.0"
] | 33 | 2020-04-20T00:38:42.000Z | 2022-03-18T10:10:46.000Z | /*
* Copyright (C) 2021 Open Source Robotics Foundation
*
* 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 <string>
#include <mutex>
#include <ignition/common/MouseEvent.hh>
#include <ignition/gui/Application.hh>
#include <ignition/gui/GuiEvents.hh>
#include <ignition/gui/MainWindow.hh>
#include <ignition/plugin/Register.hh>
#include <ignition/rendering/Camera.hh>
#include <ignition/rendering/OrbitViewController.hh>
#include <ignition/rendering/OrthoViewController.hh>
#include <ignition/rendering/RenderingIface.hh>
#include <ignition/rendering/RayQuery.hh>
#include <ignition/rendering/Utils.hh>
#include <ignition/transport/Node.hh>
#include "InteractiveViewControl.hh"
/// \brief Private data class for InteractiveViewControl
class ignition::gui::plugins::InteractiveViewControlPrivate
{
/// \brief Perform rendering calls in the rendering thread.
public: void OnRender();
/// \brief Callback for camera view controller request
/// \param[in] _msg Request message to set the camera view controller
/// \param[in] _res Response data
/// \return True if the request is received
public: bool OnViewControl(const msgs::StringMsg &_msg,
msgs::Boolean &_res);
/// \brief Flag to indicate if mouse event is dirty
public: bool mouseDirty = false;
/// \brief True to block orbiting with the mouse.
public: bool blockOrbit = false;
/// \brief Mouse event
public: common::MouseEvent mouseEvent;
/// \brief Mouse move distance since last event.
public: math::Vector2d drag;
/// \brief User camera
public: rendering::CameraPtr camera{nullptr};
/// \brief View control focus target
public: math::Vector3d target;
/// \brief Orbit view controller
public: rendering::OrbitViewController orbitViewControl;
/// \brief Ortho view controller
public: rendering::OrthoViewController orthoViewControl;
/// \brief Camera view controller
public: rendering::ViewController *viewControl{nullptr};
/// \brief Mutex to protect View Controllers
public: std::mutex mutex;
/// \brief View controller
public: std::string viewController{"orbit"};
/// \brief Camera view control service
public: std::string cameraViewControlService;
/// \brief Ray query for mouse clicks
public: rendering::RayQueryPtr rayQuery{nullptr};
//// \brief Pointer to the rendering scene
public: rendering::ScenePtr scene{nullptr};
/// \brief Transport node for making transform control requests
public: transport::Node node;
};
using namespace ignition;
using namespace gui;
using namespace plugins;
/////////////////////////////////////////////////
void InteractiveViewControlPrivate::OnRender()
{
if (!this->scene)
{
this->scene = rendering::sceneFromFirstRenderEngine();
if (!this->scene)
return;
for (unsigned int i = 0; i < this->scene->NodeCount(); ++i)
{
auto cam = std::dynamic_pointer_cast<rendering::Camera>(
this->scene->NodeByIndex(i));
if (cam)
{
bool isUserCamera = false;
try
{
isUserCamera = std::get<bool>(cam->UserData("user-camera"));
}
catch (std::bad_variant_access &)
{
continue;
}
if (isUserCamera)
{
this->camera = cam;
igndbg << "InteractiveViewControl plugin is moving camera ["
<< this->camera->Name() << "]" << std::endl;
break;
}
}
}
if (!this->camera)
{
ignerr << "InteractiveViewControl camera is not available" << std::endl;
return;
}
this->rayQuery = this->camera->Scene()->CreateRayQuery();
}
if (this->blockOrbit)
{
this->drag = {0, 0};
return;
}
if (!this->mouseDirty)
return;
if (!this->camera)
return;
std::lock_guard<std::mutex> lock(this->mutex);
if (this->viewController == "ortho")
{
this->viewControl = &this->orthoViewControl;
}
else if (this->viewController == "orbit")
{
this->viewControl = &this->orbitViewControl;
}
else
{
ignerr << "Unknown view controller: " << this->viewController
<< ". Defaulting to orbit view controller" << std::endl;
this->viewController = "orbit";
this->viewControl = &this->orbitViewControl;
}
this->viewControl->SetCamera(this->camera);
if (this->mouseEvent.Type() == common::MouseEvent::SCROLL)
{
this->target = rendering::screenToScene(
this->mouseEvent.Pos(), this->camera, this->rayQuery);
this->viewControl->SetTarget(this->target);
double distance = this->camera->WorldPosition().Distance(
this->target);
double amount = -this->drag.Y() * distance / 5.0;
this->viewControl->Zoom(amount);
}
else if (this->mouseEvent.Type() == common::MouseEvent::PRESS)
{
this->target = rendering::screenToScene(
this->mouseEvent.PressPos(), this->camera, this->rayQuery);
this->viewControl->SetTarget(this->target);
}
else
{
// Pan with left button
if (this->mouseEvent.Buttons() & common::MouseEvent::LEFT)
{
if (Qt::ShiftModifier == QGuiApplication::queryKeyboardModifiers())
this->viewControl->Orbit(this->drag);
else
this->viewControl->Pan(this->drag);
}
// Orbit with middle button
else if (this->mouseEvent.Buttons() & common::MouseEvent::MIDDLE)
{
this->viewControl->Orbit(this->drag);
}
// Zoom with right button
else if (this->mouseEvent.Buttons() & common::MouseEvent::RIGHT)
{
double hfov = this->camera->HFOV().Radian();
double vfov = 2.0f * atan(tan(hfov / 2.0f) / this->camera->AspectRatio());
double distance = this->camera->WorldPosition().Distance(this->target);
double amount = ((-this->drag.Y() /
static_cast<double>(this->camera->ImageHeight()))
* distance * tan(vfov/2.0) * 6.0);
this->viewControl->Zoom(amount);
}
}
this->drag = 0;
this->mouseDirty = false;
}
/////////////////////////////////////////////////
bool InteractiveViewControlPrivate::OnViewControl(const msgs::StringMsg &_msg,
msgs::Boolean &_res)
{
std::lock_guard<std::mutex> lock(this->mutex);
if (_msg.data() != "orbit" && _msg.data() != "ortho")
{
ignwarn << "View controller type not supported [" << _msg.data() << "]"
<< std::endl;
_res.set_data(false);
return true;
}
this->viewController = _msg.data();
// mark mouse dirty to trigger HandleMouseEvent call and
// set up a new view controller
this->mouseDirty = true;
_res.set_data(true);
return true;
}
/////////////////////////////////////////////////
InteractiveViewControl::InteractiveViewControl()
: Plugin(), dataPtr(std::make_unique<InteractiveViewControlPrivate>())
{
}
/////////////////////////////////////////////////
InteractiveViewControl::~InteractiveViewControl() = default;
/////////////////////////////////////////////////
void InteractiveViewControl::LoadConfig(
const tinyxml2::XMLElement * /*_pluginElem*/)
{
// camera view control mode
this->dataPtr->cameraViewControlService = "/gui/camera/view_control";
this->dataPtr->node.Advertise(this->dataPtr->cameraViewControlService,
&InteractiveViewControlPrivate::OnViewControl, this->dataPtr.get());
ignmsg << "Camera view controller topic advertised on ["
<< this->dataPtr->cameraViewControlService << "]" << std::endl;
ignition::gui::App()->findChild<
ignition::gui::MainWindow *>()->installEventFilter(this);
}
/////////////////////////////////////////////////
bool InteractiveViewControl::eventFilter(QObject *_obj, QEvent *_event)
{
if (_event->type() == events::Render::kType)
{
this->dataPtr->OnRender();
}
else if (_event->type() == events::LeftClickOnScene::kType)
{
auto leftClickOnScene =
reinterpret_cast<ignition::gui::events::LeftClickOnScene *>(_event);
this->dataPtr->mouseDirty = true;
this->dataPtr->drag = math::Vector2d::Zero;
this->dataPtr->mouseEvent = leftClickOnScene->Mouse();
}
else if (_event->type() == events::MousePressOnScene::kType)
{
auto pressOnScene =
reinterpret_cast<ignition::gui::events::MousePressOnScene *>(_event);
this->dataPtr->mouseDirty = true;
this->dataPtr->drag = math::Vector2d::Zero;
this->dataPtr->mouseEvent = pressOnScene->Mouse();
}
else if (_event->type() == events::DragOnScene::kType)
{
auto dragOnScene =
reinterpret_cast<ignition::gui::events::DragOnScene *>(_event);
this->dataPtr->mouseDirty = true;
auto dragStart = this->dataPtr->mouseEvent.Pos();
auto dragInt = dragOnScene->Mouse().Pos() - dragStart;
auto dragDistance = math::Vector2d(dragInt.X(), dragInt.Y());
this->dataPtr->drag += dragDistance;
this->dataPtr->mouseEvent = dragOnScene->Mouse();
}
else if (_event->type() == events::ScrollOnScene::kType)
{
auto scrollOnScene =
reinterpret_cast<ignition::gui::events::ScrollOnScene *>(_event);
this->dataPtr->mouseDirty = true;
this->dataPtr->drag += math::Vector2d(
scrollOnScene->Mouse().Scroll().X(),
scrollOnScene->Mouse().Scroll().Y());
this->dataPtr->mouseEvent = scrollOnScene->Mouse();
}
else if (_event->type() == ignition::gui::events::BlockOrbit::kType)
{
auto blockOrbit = reinterpret_cast<ignition::gui::events::BlockOrbit *>(
_event);
this->dataPtr->blockOrbit = blockOrbit->Block();
}
// Standard event processing
return QObject::eventFilter(_obj, _event);
}
// Register this plugin
IGNITION_ADD_PLUGIN(ignition::gui::plugins::InteractiveViewControl,
ignition::gui::Plugin)
| 30.053412 | 80 | 0.649289 | [
"render",
"transform"
] |
f16f378096cc3273057df0bb2c3381310148e4d7 | 2,163 | cc | C++ | src/core/cast.cc | inordeng/TASO | 17a01a7fab21795d8bacfd7ba4f3ba00f11aedf3 | [
"Apache-2.0"
] | 529 | 2019-10-01T00:01:08.000Z | 2022-03-17T12:56:01.000Z | src/core/cast.cc | inordeng/TASO | 17a01a7fab21795d8bacfd7ba4f3ba00f11aedf3 | [
"Apache-2.0"
] | 68 | 2019-10-10T18:41:40.000Z | 2022-03-17T07:42:49.000Z | src/core/cast.cc | inordeng/TASO | 17a01a7fab21795d8bacfd7ba4f3ba00f11aedf3 | [
"Apache-2.0"
] | 81 | 2019-10-04T23:48:12.000Z | 2022-03-17T13:04:25.000Z | /* Copyright 2019 Stanford
*
* 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 "taso/ops.h"
using namespace taso;
TensorHandle Graph::cast(const TensorHandle _input, DataType _datatype)
{
Op op = model->get_or_create_cast(*_input, _datatype);
assert(op != Op::INVALID_OP);
add_edge(_input->op, op, _input->idx, 0);
TensorHandle t = new Tensor(op.ptr->outputs[0]);
t->op = op;
return t;
}
Op Model::get_or_create_cast(const Tensor& _input, DataType _datatype)
{
CastKey key(_input, _datatype);
Cast* castOp;
if (cast.find(key) != cast.end()) {
castOp = cast[key];
} else {
castOp = new Cast(this, _input, _datatype);
measure_cast_cost(castOp);
cast[key] = castOp;
}
Op ret;
ret.guid = global_unique_id ++;
ret.ptr = castOp;
return ret;
}
Cast::Cast(Model* _model, const Tensor& _input, DataType _datatype)
: OpBase(_input, _model, OP_CAST)
{
numOutputs = 1;
outputs[0] = _input;
outputs[0].idx = 0;
}
Cast::~Cast(void)
{}
bool Cast::get_int_parameter(PMParameter para, int* value)
{
return OpBase::get_int_parameter(para, value);
}
void Cast::collect_costs(float& exe_time, float& flops,
float& mem_acc, int& num_kernels)
{
// cost metrics
exe_time += runtime;
flops += outputs[0].volume();
mem_acc += inputs[0].volume();
num_kernels += 1;
printf(" cost[Cast]: cost(%.4lf) total_cost(%.4lf)\n",
runtime, exe_time);
}
CastKey::CastKey(const Tensor& _input, DataType _datatype)
{
int idx = 0;
keys[idx++] = _datatype;
_input.serialize(keys, idx);
while (idx < KEY_LENGTH)
keys[idx++] = 0;
assert(idx == KEY_LENGTH);
}
| 26.060241 | 75 | 0.676838 | [
"model"
] |
f1724f6c819691b10af6e549ec543fe0b7d53ac6 | 209,611 | cpp | C++ | cwp/src/v20180228/CwpClient.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | cwp/src/v20180228/CwpClient.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | cwp/src/v20180228/CwpClient.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/cwp/v20180228/CwpClient.h>
#include <tencentcloud/core/Executor.h>
#include <tencentcloud/core/Runnable.h>
using namespace TencentCloud;
using namespace TencentCloud::Cwp::V20180228;
using namespace TencentCloud::Cwp::V20180228::Model;
using namespace std;
namespace
{
const string VERSION = "2018-02-28";
const string ENDPOINT = "cwp.tencentcloudapi.com";
}
CwpClient::CwpClient(const Credential &credential, const string ®ion) :
CwpClient(credential, region, ClientProfile())
{
}
CwpClient::CwpClient(const Credential &credential, const string ®ion, const ClientProfile &profile) :
AbstractClient(ENDPOINT, VERSION, credential, region, profile)
{
}
CwpClient::AddLoginWhiteListOutcome CwpClient::AddLoginWhiteList(const AddLoginWhiteListRequest &request)
{
auto outcome = MakeRequest(request, "AddLoginWhiteList");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
AddLoginWhiteListResponse rsp = AddLoginWhiteListResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return AddLoginWhiteListOutcome(rsp);
else
return AddLoginWhiteListOutcome(o.GetError());
}
else
{
return AddLoginWhiteListOutcome(outcome.GetError());
}
}
void CwpClient::AddLoginWhiteListAsync(const AddLoginWhiteListRequest& request, const AddLoginWhiteListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->AddLoginWhiteList(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::AddLoginWhiteListOutcomeCallable CwpClient::AddLoginWhiteListCallable(const AddLoginWhiteListRequest &request)
{
auto task = std::make_shared<std::packaged_task<AddLoginWhiteListOutcome()>>(
[this, request]()
{
return this->AddLoginWhiteList(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::AddMachineTagOutcome CwpClient::AddMachineTag(const AddMachineTagRequest &request)
{
auto outcome = MakeRequest(request, "AddMachineTag");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
AddMachineTagResponse rsp = AddMachineTagResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return AddMachineTagOutcome(rsp);
else
return AddMachineTagOutcome(o.GetError());
}
else
{
return AddMachineTagOutcome(outcome.GetError());
}
}
void CwpClient::AddMachineTagAsync(const AddMachineTagRequest& request, const AddMachineTagAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->AddMachineTag(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::AddMachineTagOutcomeCallable CwpClient::AddMachineTagCallable(const AddMachineTagRequest &request)
{
auto task = std::make_shared<std::packaged_task<AddMachineTagOutcome()>>(
[this, request]()
{
return this->AddMachineTag(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::CloseProVersionOutcome CwpClient::CloseProVersion(const CloseProVersionRequest &request)
{
auto outcome = MakeRequest(request, "CloseProVersion");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
CloseProVersionResponse rsp = CloseProVersionResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return CloseProVersionOutcome(rsp);
else
return CloseProVersionOutcome(o.GetError());
}
else
{
return CloseProVersionOutcome(outcome.GetError());
}
}
void CwpClient::CloseProVersionAsync(const CloseProVersionRequest& request, const CloseProVersionAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->CloseProVersion(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::CloseProVersionOutcomeCallable CwpClient::CloseProVersionCallable(const CloseProVersionRequest &request)
{
auto task = std::make_shared<std::packaged_task<CloseProVersionOutcome()>>(
[this, request]()
{
return this->CloseProVersion(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::CreateBaselineStrategyOutcome CwpClient::CreateBaselineStrategy(const CreateBaselineStrategyRequest &request)
{
auto outcome = MakeRequest(request, "CreateBaselineStrategy");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
CreateBaselineStrategyResponse rsp = CreateBaselineStrategyResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return CreateBaselineStrategyOutcome(rsp);
else
return CreateBaselineStrategyOutcome(o.GetError());
}
else
{
return CreateBaselineStrategyOutcome(outcome.GetError());
}
}
void CwpClient::CreateBaselineStrategyAsync(const CreateBaselineStrategyRequest& request, const CreateBaselineStrategyAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->CreateBaselineStrategy(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::CreateBaselineStrategyOutcomeCallable CwpClient::CreateBaselineStrategyCallable(const CreateBaselineStrategyRequest &request)
{
auto task = std::make_shared<std::packaged_task<CreateBaselineStrategyOutcome()>>(
[this, request]()
{
return this->CreateBaselineStrategy(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::CreateOpenPortTaskOutcome CwpClient::CreateOpenPortTask(const CreateOpenPortTaskRequest &request)
{
auto outcome = MakeRequest(request, "CreateOpenPortTask");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
CreateOpenPortTaskResponse rsp = CreateOpenPortTaskResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return CreateOpenPortTaskOutcome(rsp);
else
return CreateOpenPortTaskOutcome(o.GetError());
}
else
{
return CreateOpenPortTaskOutcome(outcome.GetError());
}
}
void CwpClient::CreateOpenPortTaskAsync(const CreateOpenPortTaskRequest& request, const CreateOpenPortTaskAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->CreateOpenPortTask(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::CreateOpenPortTaskOutcomeCallable CwpClient::CreateOpenPortTaskCallable(const CreateOpenPortTaskRequest &request)
{
auto task = std::make_shared<std::packaged_task<CreateOpenPortTaskOutcome()>>(
[this, request]()
{
return this->CreateOpenPortTask(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::CreateProcessTaskOutcome CwpClient::CreateProcessTask(const CreateProcessTaskRequest &request)
{
auto outcome = MakeRequest(request, "CreateProcessTask");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
CreateProcessTaskResponse rsp = CreateProcessTaskResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return CreateProcessTaskOutcome(rsp);
else
return CreateProcessTaskOutcome(o.GetError());
}
else
{
return CreateProcessTaskOutcome(outcome.GetError());
}
}
void CwpClient::CreateProcessTaskAsync(const CreateProcessTaskRequest& request, const CreateProcessTaskAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->CreateProcessTask(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::CreateProcessTaskOutcomeCallable CwpClient::CreateProcessTaskCallable(const CreateProcessTaskRequest &request)
{
auto task = std::make_shared<std::packaged_task<CreateProcessTaskOutcome()>>(
[this, request]()
{
return this->CreateProcessTask(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::CreateProtectServerOutcome CwpClient::CreateProtectServer(const CreateProtectServerRequest &request)
{
auto outcome = MakeRequest(request, "CreateProtectServer");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
CreateProtectServerResponse rsp = CreateProtectServerResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return CreateProtectServerOutcome(rsp);
else
return CreateProtectServerOutcome(o.GetError());
}
else
{
return CreateProtectServerOutcome(outcome.GetError());
}
}
void CwpClient::CreateProtectServerAsync(const CreateProtectServerRequest& request, const CreateProtectServerAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->CreateProtectServer(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::CreateProtectServerOutcomeCallable CwpClient::CreateProtectServerCallable(const CreateProtectServerRequest &request)
{
auto task = std::make_shared<std::packaged_task<CreateProtectServerOutcome()>>(
[this, request]()
{
return this->CreateProtectServer(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::CreateSearchLogOutcome CwpClient::CreateSearchLog(const CreateSearchLogRequest &request)
{
auto outcome = MakeRequest(request, "CreateSearchLog");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
CreateSearchLogResponse rsp = CreateSearchLogResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return CreateSearchLogOutcome(rsp);
else
return CreateSearchLogOutcome(o.GetError());
}
else
{
return CreateSearchLogOutcome(outcome.GetError());
}
}
void CwpClient::CreateSearchLogAsync(const CreateSearchLogRequest& request, const CreateSearchLogAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->CreateSearchLog(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::CreateSearchLogOutcomeCallable CwpClient::CreateSearchLogCallable(const CreateSearchLogRequest &request)
{
auto task = std::make_shared<std::packaged_task<CreateSearchLogOutcome()>>(
[this, request]()
{
return this->CreateSearchLog(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::CreateSearchTemplateOutcome CwpClient::CreateSearchTemplate(const CreateSearchTemplateRequest &request)
{
auto outcome = MakeRequest(request, "CreateSearchTemplate");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
CreateSearchTemplateResponse rsp = CreateSearchTemplateResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return CreateSearchTemplateOutcome(rsp);
else
return CreateSearchTemplateOutcome(o.GetError());
}
else
{
return CreateSearchTemplateOutcome(outcome.GetError());
}
}
void CwpClient::CreateSearchTemplateAsync(const CreateSearchTemplateRequest& request, const CreateSearchTemplateAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->CreateSearchTemplate(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::CreateSearchTemplateOutcomeCallable CwpClient::CreateSearchTemplateCallable(const CreateSearchTemplateRequest &request)
{
auto task = std::make_shared<std::packaged_task<CreateSearchTemplateOutcome()>>(
[this, request]()
{
return this->CreateSearchTemplate(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::CreateUsualLoginPlacesOutcome CwpClient::CreateUsualLoginPlaces(const CreateUsualLoginPlacesRequest &request)
{
auto outcome = MakeRequest(request, "CreateUsualLoginPlaces");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
CreateUsualLoginPlacesResponse rsp = CreateUsualLoginPlacesResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return CreateUsualLoginPlacesOutcome(rsp);
else
return CreateUsualLoginPlacesOutcome(o.GetError());
}
else
{
return CreateUsualLoginPlacesOutcome(outcome.GetError());
}
}
void CwpClient::CreateUsualLoginPlacesAsync(const CreateUsualLoginPlacesRequest& request, const CreateUsualLoginPlacesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->CreateUsualLoginPlaces(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::CreateUsualLoginPlacesOutcomeCallable CwpClient::CreateUsualLoginPlacesCallable(const CreateUsualLoginPlacesRequest &request)
{
auto task = std::make_shared<std::packaged_task<CreateUsualLoginPlacesOutcome()>>(
[this, request]()
{
return this->CreateUsualLoginPlaces(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DeleteAttackLogsOutcome CwpClient::DeleteAttackLogs(const DeleteAttackLogsRequest &request)
{
auto outcome = MakeRequest(request, "DeleteAttackLogs");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DeleteAttackLogsResponse rsp = DeleteAttackLogsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DeleteAttackLogsOutcome(rsp);
else
return DeleteAttackLogsOutcome(o.GetError());
}
else
{
return DeleteAttackLogsOutcome(outcome.GetError());
}
}
void CwpClient::DeleteAttackLogsAsync(const DeleteAttackLogsRequest& request, const DeleteAttackLogsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DeleteAttackLogs(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DeleteAttackLogsOutcomeCallable CwpClient::DeleteAttackLogsCallable(const DeleteAttackLogsRequest &request)
{
auto task = std::make_shared<std::packaged_task<DeleteAttackLogsOutcome()>>(
[this, request]()
{
return this->DeleteAttackLogs(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DeleteBashEventsOutcome CwpClient::DeleteBashEvents(const DeleteBashEventsRequest &request)
{
auto outcome = MakeRequest(request, "DeleteBashEvents");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DeleteBashEventsResponse rsp = DeleteBashEventsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DeleteBashEventsOutcome(rsp);
else
return DeleteBashEventsOutcome(o.GetError());
}
else
{
return DeleteBashEventsOutcome(outcome.GetError());
}
}
void CwpClient::DeleteBashEventsAsync(const DeleteBashEventsRequest& request, const DeleteBashEventsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DeleteBashEvents(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DeleteBashEventsOutcomeCallable CwpClient::DeleteBashEventsCallable(const DeleteBashEventsRequest &request)
{
auto task = std::make_shared<std::packaged_task<DeleteBashEventsOutcome()>>(
[this, request]()
{
return this->DeleteBashEvents(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DeleteBashRulesOutcome CwpClient::DeleteBashRules(const DeleteBashRulesRequest &request)
{
auto outcome = MakeRequest(request, "DeleteBashRules");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DeleteBashRulesResponse rsp = DeleteBashRulesResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DeleteBashRulesOutcome(rsp);
else
return DeleteBashRulesOutcome(o.GetError());
}
else
{
return DeleteBashRulesOutcome(outcome.GetError());
}
}
void CwpClient::DeleteBashRulesAsync(const DeleteBashRulesRequest& request, const DeleteBashRulesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DeleteBashRules(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DeleteBashRulesOutcomeCallable CwpClient::DeleteBashRulesCallable(const DeleteBashRulesRequest &request)
{
auto task = std::make_shared<std::packaged_task<DeleteBashRulesOutcome()>>(
[this, request]()
{
return this->DeleteBashRules(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DeleteBruteAttacksOutcome CwpClient::DeleteBruteAttacks(const DeleteBruteAttacksRequest &request)
{
auto outcome = MakeRequest(request, "DeleteBruteAttacks");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DeleteBruteAttacksResponse rsp = DeleteBruteAttacksResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DeleteBruteAttacksOutcome(rsp);
else
return DeleteBruteAttacksOutcome(o.GetError());
}
else
{
return DeleteBruteAttacksOutcome(outcome.GetError());
}
}
void CwpClient::DeleteBruteAttacksAsync(const DeleteBruteAttacksRequest& request, const DeleteBruteAttacksAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DeleteBruteAttacks(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DeleteBruteAttacksOutcomeCallable CwpClient::DeleteBruteAttacksCallable(const DeleteBruteAttacksRequest &request)
{
auto task = std::make_shared<std::packaged_task<DeleteBruteAttacksOutcome()>>(
[this, request]()
{
return this->DeleteBruteAttacks(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DeleteLoginWhiteListOutcome CwpClient::DeleteLoginWhiteList(const DeleteLoginWhiteListRequest &request)
{
auto outcome = MakeRequest(request, "DeleteLoginWhiteList");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DeleteLoginWhiteListResponse rsp = DeleteLoginWhiteListResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DeleteLoginWhiteListOutcome(rsp);
else
return DeleteLoginWhiteListOutcome(o.GetError());
}
else
{
return DeleteLoginWhiteListOutcome(outcome.GetError());
}
}
void CwpClient::DeleteLoginWhiteListAsync(const DeleteLoginWhiteListRequest& request, const DeleteLoginWhiteListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DeleteLoginWhiteList(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DeleteLoginWhiteListOutcomeCallable CwpClient::DeleteLoginWhiteListCallable(const DeleteLoginWhiteListRequest &request)
{
auto task = std::make_shared<std::packaged_task<DeleteLoginWhiteListOutcome()>>(
[this, request]()
{
return this->DeleteLoginWhiteList(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DeleteMachineOutcome CwpClient::DeleteMachine(const DeleteMachineRequest &request)
{
auto outcome = MakeRequest(request, "DeleteMachine");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DeleteMachineResponse rsp = DeleteMachineResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DeleteMachineOutcome(rsp);
else
return DeleteMachineOutcome(o.GetError());
}
else
{
return DeleteMachineOutcome(outcome.GetError());
}
}
void CwpClient::DeleteMachineAsync(const DeleteMachineRequest& request, const DeleteMachineAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DeleteMachine(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DeleteMachineOutcomeCallable CwpClient::DeleteMachineCallable(const DeleteMachineRequest &request)
{
auto task = std::make_shared<std::packaged_task<DeleteMachineOutcome()>>(
[this, request]()
{
return this->DeleteMachine(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DeleteMachineTagOutcome CwpClient::DeleteMachineTag(const DeleteMachineTagRequest &request)
{
auto outcome = MakeRequest(request, "DeleteMachineTag");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DeleteMachineTagResponse rsp = DeleteMachineTagResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DeleteMachineTagOutcome(rsp);
else
return DeleteMachineTagOutcome(o.GetError());
}
else
{
return DeleteMachineTagOutcome(outcome.GetError());
}
}
void CwpClient::DeleteMachineTagAsync(const DeleteMachineTagRequest& request, const DeleteMachineTagAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DeleteMachineTag(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DeleteMachineTagOutcomeCallable CwpClient::DeleteMachineTagCallable(const DeleteMachineTagRequest &request)
{
auto task = std::make_shared<std::packaged_task<DeleteMachineTagOutcome()>>(
[this, request]()
{
return this->DeleteMachineTag(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DeleteMaliciousRequestsOutcome CwpClient::DeleteMaliciousRequests(const DeleteMaliciousRequestsRequest &request)
{
auto outcome = MakeRequest(request, "DeleteMaliciousRequests");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DeleteMaliciousRequestsResponse rsp = DeleteMaliciousRequestsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DeleteMaliciousRequestsOutcome(rsp);
else
return DeleteMaliciousRequestsOutcome(o.GetError());
}
else
{
return DeleteMaliciousRequestsOutcome(outcome.GetError());
}
}
void CwpClient::DeleteMaliciousRequestsAsync(const DeleteMaliciousRequestsRequest& request, const DeleteMaliciousRequestsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DeleteMaliciousRequests(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DeleteMaliciousRequestsOutcomeCallable CwpClient::DeleteMaliciousRequestsCallable(const DeleteMaliciousRequestsRequest &request)
{
auto task = std::make_shared<std::packaged_task<DeleteMaliciousRequestsOutcome()>>(
[this, request]()
{
return this->DeleteMaliciousRequests(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DeleteMalwaresOutcome CwpClient::DeleteMalwares(const DeleteMalwaresRequest &request)
{
auto outcome = MakeRequest(request, "DeleteMalwares");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DeleteMalwaresResponse rsp = DeleteMalwaresResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DeleteMalwaresOutcome(rsp);
else
return DeleteMalwaresOutcome(o.GetError());
}
else
{
return DeleteMalwaresOutcome(outcome.GetError());
}
}
void CwpClient::DeleteMalwaresAsync(const DeleteMalwaresRequest& request, const DeleteMalwaresAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DeleteMalwares(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DeleteMalwaresOutcomeCallable CwpClient::DeleteMalwaresCallable(const DeleteMalwaresRequest &request)
{
auto task = std::make_shared<std::packaged_task<DeleteMalwaresOutcome()>>(
[this, request]()
{
return this->DeleteMalwares(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DeleteNonlocalLoginPlacesOutcome CwpClient::DeleteNonlocalLoginPlaces(const DeleteNonlocalLoginPlacesRequest &request)
{
auto outcome = MakeRequest(request, "DeleteNonlocalLoginPlaces");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DeleteNonlocalLoginPlacesResponse rsp = DeleteNonlocalLoginPlacesResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DeleteNonlocalLoginPlacesOutcome(rsp);
else
return DeleteNonlocalLoginPlacesOutcome(o.GetError());
}
else
{
return DeleteNonlocalLoginPlacesOutcome(outcome.GetError());
}
}
void CwpClient::DeleteNonlocalLoginPlacesAsync(const DeleteNonlocalLoginPlacesRequest& request, const DeleteNonlocalLoginPlacesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DeleteNonlocalLoginPlaces(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DeleteNonlocalLoginPlacesOutcomeCallable CwpClient::DeleteNonlocalLoginPlacesCallable(const DeleteNonlocalLoginPlacesRequest &request)
{
auto task = std::make_shared<std::packaged_task<DeleteNonlocalLoginPlacesOutcome()>>(
[this, request]()
{
return this->DeleteNonlocalLoginPlaces(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DeletePrivilegeEventsOutcome CwpClient::DeletePrivilegeEvents(const DeletePrivilegeEventsRequest &request)
{
auto outcome = MakeRequest(request, "DeletePrivilegeEvents");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DeletePrivilegeEventsResponse rsp = DeletePrivilegeEventsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DeletePrivilegeEventsOutcome(rsp);
else
return DeletePrivilegeEventsOutcome(o.GetError());
}
else
{
return DeletePrivilegeEventsOutcome(outcome.GetError());
}
}
void CwpClient::DeletePrivilegeEventsAsync(const DeletePrivilegeEventsRequest& request, const DeletePrivilegeEventsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DeletePrivilegeEvents(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DeletePrivilegeEventsOutcomeCallable CwpClient::DeletePrivilegeEventsCallable(const DeletePrivilegeEventsRequest &request)
{
auto task = std::make_shared<std::packaged_task<DeletePrivilegeEventsOutcome()>>(
[this, request]()
{
return this->DeletePrivilegeEvents(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DeletePrivilegeRulesOutcome CwpClient::DeletePrivilegeRules(const DeletePrivilegeRulesRequest &request)
{
auto outcome = MakeRequest(request, "DeletePrivilegeRules");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DeletePrivilegeRulesResponse rsp = DeletePrivilegeRulesResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DeletePrivilegeRulesOutcome(rsp);
else
return DeletePrivilegeRulesOutcome(o.GetError());
}
else
{
return DeletePrivilegeRulesOutcome(outcome.GetError());
}
}
void CwpClient::DeletePrivilegeRulesAsync(const DeletePrivilegeRulesRequest& request, const DeletePrivilegeRulesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DeletePrivilegeRules(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DeletePrivilegeRulesOutcomeCallable CwpClient::DeletePrivilegeRulesCallable(const DeletePrivilegeRulesRequest &request)
{
auto task = std::make_shared<std::packaged_task<DeletePrivilegeRulesOutcome()>>(
[this, request]()
{
return this->DeletePrivilegeRules(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DeleteReverseShellEventsOutcome CwpClient::DeleteReverseShellEvents(const DeleteReverseShellEventsRequest &request)
{
auto outcome = MakeRequest(request, "DeleteReverseShellEvents");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DeleteReverseShellEventsResponse rsp = DeleteReverseShellEventsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DeleteReverseShellEventsOutcome(rsp);
else
return DeleteReverseShellEventsOutcome(o.GetError());
}
else
{
return DeleteReverseShellEventsOutcome(outcome.GetError());
}
}
void CwpClient::DeleteReverseShellEventsAsync(const DeleteReverseShellEventsRequest& request, const DeleteReverseShellEventsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DeleteReverseShellEvents(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DeleteReverseShellEventsOutcomeCallable CwpClient::DeleteReverseShellEventsCallable(const DeleteReverseShellEventsRequest &request)
{
auto task = std::make_shared<std::packaged_task<DeleteReverseShellEventsOutcome()>>(
[this, request]()
{
return this->DeleteReverseShellEvents(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DeleteReverseShellRulesOutcome CwpClient::DeleteReverseShellRules(const DeleteReverseShellRulesRequest &request)
{
auto outcome = MakeRequest(request, "DeleteReverseShellRules");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DeleteReverseShellRulesResponse rsp = DeleteReverseShellRulesResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DeleteReverseShellRulesOutcome(rsp);
else
return DeleteReverseShellRulesOutcome(o.GetError());
}
else
{
return DeleteReverseShellRulesOutcome(outcome.GetError());
}
}
void CwpClient::DeleteReverseShellRulesAsync(const DeleteReverseShellRulesRequest& request, const DeleteReverseShellRulesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DeleteReverseShellRules(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DeleteReverseShellRulesOutcomeCallable CwpClient::DeleteReverseShellRulesCallable(const DeleteReverseShellRulesRequest &request)
{
auto task = std::make_shared<std::packaged_task<DeleteReverseShellRulesOutcome()>>(
[this, request]()
{
return this->DeleteReverseShellRules(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DeleteSearchTemplateOutcome CwpClient::DeleteSearchTemplate(const DeleteSearchTemplateRequest &request)
{
auto outcome = MakeRequest(request, "DeleteSearchTemplate");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DeleteSearchTemplateResponse rsp = DeleteSearchTemplateResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DeleteSearchTemplateOutcome(rsp);
else
return DeleteSearchTemplateOutcome(o.GetError());
}
else
{
return DeleteSearchTemplateOutcome(outcome.GetError());
}
}
void CwpClient::DeleteSearchTemplateAsync(const DeleteSearchTemplateRequest& request, const DeleteSearchTemplateAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DeleteSearchTemplate(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DeleteSearchTemplateOutcomeCallable CwpClient::DeleteSearchTemplateCallable(const DeleteSearchTemplateRequest &request)
{
auto task = std::make_shared<std::packaged_task<DeleteSearchTemplateOutcome()>>(
[this, request]()
{
return this->DeleteSearchTemplate(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DeleteTagsOutcome CwpClient::DeleteTags(const DeleteTagsRequest &request)
{
auto outcome = MakeRequest(request, "DeleteTags");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DeleteTagsResponse rsp = DeleteTagsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DeleteTagsOutcome(rsp);
else
return DeleteTagsOutcome(o.GetError());
}
else
{
return DeleteTagsOutcome(outcome.GetError());
}
}
void CwpClient::DeleteTagsAsync(const DeleteTagsRequest& request, const DeleteTagsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DeleteTags(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DeleteTagsOutcomeCallable CwpClient::DeleteTagsCallable(const DeleteTagsRequest &request)
{
auto task = std::make_shared<std::packaged_task<DeleteTagsOutcome()>>(
[this, request]()
{
return this->DeleteTags(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DeleteUsualLoginPlacesOutcome CwpClient::DeleteUsualLoginPlaces(const DeleteUsualLoginPlacesRequest &request)
{
auto outcome = MakeRequest(request, "DeleteUsualLoginPlaces");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DeleteUsualLoginPlacesResponse rsp = DeleteUsualLoginPlacesResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DeleteUsualLoginPlacesOutcome(rsp);
else
return DeleteUsualLoginPlacesOutcome(o.GetError());
}
else
{
return DeleteUsualLoginPlacesOutcome(outcome.GetError());
}
}
void CwpClient::DeleteUsualLoginPlacesAsync(const DeleteUsualLoginPlacesRequest& request, const DeleteUsualLoginPlacesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DeleteUsualLoginPlaces(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DeleteUsualLoginPlacesOutcomeCallable CwpClient::DeleteUsualLoginPlacesCallable(const DeleteUsualLoginPlacesRequest &request)
{
auto task = std::make_shared<std::packaged_task<DeleteUsualLoginPlacesOutcome()>>(
[this, request]()
{
return this->DeleteUsualLoginPlaces(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DeleteWebPageEventLogOutcome CwpClient::DeleteWebPageEventLog(const DeleteWebPageEventLogRequest &request)
{
auto outcome = MakeRequest(request, "DeleteWebPageEventLog");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DeleteWebPageEventLogResponse rsp = DeleteWebPageEventLogResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DeleteWebPageEventLogOutcome(rsp);
else
return DeleteWebPageEventLogOutcome(o.GetError());
}
else
{
return DeleteWebPageEventLogOutcome(outcome.GetError());
}
}
void CwpClient::DeleteWebPageEventLogAsync(const DeleteWebPageEventLogRequest& request, const DeleteWebPageEventLogAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DeleteWebPageEventLog(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DeleteWebPageEventLogOutcomeCallable CwpClient::DeleteWebPageEventLogCallable(const DeleteWebPageEventLogRequest &request)
{
auto task = std::make_shared<std::packaged_task<DeleteWebPageEventLogOutcome()>>(
[this, request]()
{
return this->DeleteWebPageEventLog(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeAccountStatisticsOutcome CwpClient::DescribeAccountStatistics(const DescribeAccountStatisticsRequest &request)
{
auto outcome = MakeRequest(request, "DescribeAccountStatistics");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeAccountStatisticsResponse rsp = DescribeAccountStatisticsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeAccountStatisticsOutcome(rsp);
else
return DescribeAccountStatisticsOutcome(o.GetError());
}
else
{
return DescribeAccountStatisticsOutcome(outcome.GetError());
}
}
void CwpClient::DescribeAccountStatisticsAsync(const DescribeAccountStatisticsRequest& request, const DescribeAccountStatisticsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeAccountStatistics(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeAccountStatisticsOutcomeCallable CwpClient::DescribeAccountStatisticsCallable(const DescribeAccountStatisticsRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeAccountStatisticsOutcome()>>(
[this, request]()
{
return this->DescribeAccountStatistics(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeAccountsOutcome CwpClient::DescribeAccounts(const DescribeAccountsRequest &request)
{
auto outcome = MakeRequest(request, "DescribeAccounts");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeAccountsResponse rsp = DescribeAccountsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeAccountsOutcome(rsp);
else
return DescribeAccountsOutcome(o.GetError());
}
else
{
return DescribeAccountsOutcome(outcome.GetError());
}
}
void CwpClient::DescribeAccountsAsync(const DescribeAccountsRequest& request, const DescribeAccountsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeAccounts(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeAccountsOutcomeCallable CwpClient::DescribeAccountsCallable(const DescribeAccountsRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeAccountsOutcome()>>(
[this, request]()
{
return this->DescribeAccounts(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeAgentVulsOutcome CwpClient::DescribeAgentVuls(const DescribeAgentVulsRequest &request)
{
auto outcome = MakeRequest(request, "DescribeAgentVuls");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeAgentVulsResponse rsp = DescribeAgentVulsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeAgentVulsOutcome(rsp);
else
return DescribeAgentVulsOutcome(o.GetError());
}
else
{
return DescribeAgentVulsOutcome(outcome.GetError());
}
}
void CwpClient::DescribeAgentVulsAsync(const DescribeAgentVulsRequest& request, const DescribeAgentVulsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeAgentVuls(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeAgentVulsOutcomeCallable CwpClient::DescribeAgentVulsCallable(const DescribeAgentVulsRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeAgentVulsOutcome()>>(
[this, request]()
{
return this->DescribeAgentVuls(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeAlarmAttributeOutcome CwpClient::DescribeAlarmAttribute(const DescribeAlarmAttributeRequest &request)
{
auto outcome = MakeRequest(request, "DescribeAlarmAttribute");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeAlarmAttributeResponse rsp = DescribeAlarmAttributeResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeAlarmAttributeOutcome(rsp);
else
return DescribeAlarmAttributeOutcome(o.GetError());
}
else
{
return DescribeAlarmAttributeOutcome(outcome.GetError());
}
}
void CwpClient::DescribeAlarmAttributeAsync(const DescribeAlarmAttributeRequest& request, const DescribeAlarmAttributeAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeAlarmAttribute(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeAlarmAttributeOutcomeCallable CwpClient::DescribeAlarmAttributeCallable(const DescribeAlarmAttributeRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeAlarmAttributeOutcome()>>(
[this, request]()
{
return this->DescribeAlarmAttribute(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeAssetInfoOutcome CwpClient::DescribeAssetInfo(const DescribeAssetInfoRequest &request)
{
auto outcome = MakeRequest(request, "DescribeAssetInfo");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeAssetInfoResponse rsp = DescribeAssetInfoResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeAssetInfoOutcome(rsp);
else
return DescribeAssetInfoOutcome(o.GetError());
}
else
{
return DescribeAssetInfoOutcome(outcome.GetError());
}
}
void CwpClient::DescribeAssetInfoAsync(const DescribeAssetInfoRequest& request, const DescribeAssetInfoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeAssetInfo(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeAssetInfoOutcomeCallable CwpClient::DescribeAssetInfoCallable(const DescribeAssetInfoRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeAssetInfoOutcome()>>(
[this, request]()
{
return this->DescribeAssetInfo(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeAssetRecentMachineInfoOutcome CwpClient::DescribeAssetRecentMachineInfo(const DescribeAssetRecentMachineInfoRequest &request)
{
auto outcome = MakeRequest(request, "DescribeAssetRecentMachineInfo");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeAssetRecentMachineInfoResponse rsp = DescribeAssetRecentMachineInfoResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeAssetRecentMachineInfoOutcome(rsp);
else
return DescribeAssetRecentMachineInfoOutcome(o.GetError());
}
else
{
return DescribeAssetRecentMachineInfoOutcome(outcome.GetError());
}
}
void CwpClient::DescribeAssetRecentMachineInfoAsync(const DescribeAssetRecentMachineInfoRequest& request, const DescribeAssetRecentMachineInfoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeAssetRecentMachineInfo(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeAssetRecentMachineInfoOutcomeCallable CwpClient::DescribeAssetRecentMachineInfoCallable(const DescribeAssetRecentMachineInfoRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeAssetRecentMachineInfoOutcome()>>(
[this, request]()
{
return this->DescribeAssetRecentMachineInfo(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeAttackLogInfoOutcome CwpClient::DescribeAttackLogInfo(const DescribeAttackLogInfoRequest &request)
{
auto outcome = MakeRequest(request, "DescribeAttackLogInfo");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeAttackLogInfoResponse rsp = DescribeAttackLogInfoResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeAttackLogInfoOutcome(rsp);
else
return DescribeAttackLogInfoOutcome(o.GetError());
}
else
{
return DescribeAttackLogInfoOutcome(outcome.GetError());
}
}
void CwpClient::DescribeAttackLogInfoAsync(const DescribeAttackLogInfoRequest& request, const DescribeAttackLogInfoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeAttackLogInfo(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeAttackLogInfoOutcomeCallable CwpClient::DescribeAttackLogInfoCallable(const DescribeAttackLogInfoRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeAttackLogInfoOutcome()>>(
[this, request]()
{
return this->DescribeAttackLogInfo(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeAttackLogsOutcome CwpClient::DescribeAttackLogs(const DescribeAttackLogsRequest &request)
{
auto outcome = MakeRequest(request, "DescribeAttackLogs");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeAttackLogsResponse rsp = DescribeAttackLogsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeAttackLogsOutcome(rsp);
else
return DescribeAttackLogsOutcome(o.GetError());
}
else
{
return DescribeAttackLogsOutcome(outcome.GetError());
}
}
void CwpClient::DescribeAttackLogsAsync(const DescribeAttackLogsRequest& request, const DescribeAttackLogsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeAttackLogs(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeAttackLogsOutcomeCallable CwpClient::DescribeAttackLogsCallable(const DescribeAttackLogsRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeAttackLogsOutcome()>>(
[this, request]()
{
return this->DescribeAttackLogs(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeAttackVulTypeListOutcome CwpClient::DescribeAttackVulTypeList(const DescribeAttackVulTypeListRequest &request)
{
auto outcome = MakeRequest(request, "DescribeAttackVulTypeList");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeAttackVulTypeListResponse rsp = DescribeAttackVulTypeListResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeAttackVulTypeListOutcome(rsp);
else
return DescribeAttackVulTypeListOutcome(o.GetError());
}
else
{
return DescribeAttackVulTypeListOutcome(outcome.GetError());
}
}
void CwpClient::DescribeAttackVulTypeListAsync(const DescribeAttackVulTypeListRequest& request, const DescribeAttackVulTypeListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeAttackVulTypeList(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeAttackVulTypeListOutcomeCallable CwpClient::DescribeAttackVulTypeListCallable(const DescribeAttackVulTypeListRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeAttackVulTypeListOutcome()>>(
[this, request]()
{
return this->DescribeAttackVulTypeList(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeBashEventsOutcome CwpClient::DescribeBashEvents(const DescribeBashEventsRequest &request)
{
auto outcome = MakeRequest(request, "DescribeBashEvents");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeBashEventsResponse rsp = DescribeBashEventsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeBashEventsOutcome(rsp);
else
return DescribeBashEventsOutcome(o.GetError());
}
else
{
return DescribeBashEventsOutcome(outcome.GetError());
}
}
void CwpClient::DescribeBashEventsAsync(const DescribeBashEventsRequest& request, const DescribeBashEventsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeBashEvents(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeBashEventsOutcomeCallable CwpClient::DescribeBashEventsCallable(const DescribeBashEventsRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeBashEventsOutcome()>>(
[this, request]()
{
return this->DescribeBashEvents(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeBashRulesOutcome CwpClient::DescribeBashRules(const DescribeBashRulesRequest &request)
{
auto outcome = MakeRequest(request, "DescribeBashRules");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeBashRulesResponse rsp = DescribeBashRulesResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeBashRulesOutcome(rsp);
else
return DescribeBashRulesOutcome(o.GetError());
}
else
{
return DescribeBashRulesOutcome(outcome.GetError());
}
}
void CwpClient::DescribeBashRulesAsync(const DescribeBashRulesRequest& request, const DescribeBashRulesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeBashRules(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeBashRulesOutcomeCallable CwpClient::DescribeBashRulesCallable(const DescribeBashRulesRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeBashRulesOutcome()>>(
[this, request]()
{
return this->DescribeBashRules(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeBruteAttackListOutcome CwpClient::DescribeBruteAttackList(const DescribeBruteAttackListRequest &request)
{
auto outcome = MakeRequest(request, "DescribeBruteAttackList");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeBruteAttackListResponse rsp = DescribeBruteAttackListResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeBruteAttackListOutcome(rsp);
else
return DescribeBruteAttackListOutcome(o.GetError());
}
else
{
return DescribeBruteAttackListOutcome(outcome.GetError());
}
}
void CwpClient::DescribeBruteAttackListAsync(const DescribeBruteAttackListRequest& request, const DescribeBruteAttackListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeBruteAttackList(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeBruteAttackListOutcomeCallable CwpClient::DescribeBruteAttackListCallable(const DescribeBruteAttackListRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeBruteAttackListOutcome()>>(
[this, request]()
{
return this->DescribeBruteAttackList(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeBruteAttacksOutcome CwpClient::DescribeBruteAttacks(const DescribeBruteAttacksRequest &request)
{
auto outcome = MakeRequest(request, "DescribeBruteAttacks");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeBruteAttacksResponse rsp = DescribeBruteAttacksResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeBruteAttacksOutcome(rsp);
else
return DescribeBruteAttacksOutcome(o.GetError());
}
else
{
return DescribeBruteAttacksOutcome(outcome.GetError());
}
}
void CwpClient::DescribeBruteAttacksAsync(const DescribeBruteAttacksRequest& request, const DescribeBruteAttacksAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeBruteAttacks(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeBruteAttacksOutcomeCallable CwpClient::DescribeBruteAttacksCallable(const DescribeBruteAttacksRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeBruteAttacksOutcome()>>(
[this, request]()
{
return this->DescribeBruteAttacks(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeComponentInfoOutcome CwpClient::DescribeComponentInfo(const DescribeComponentInfoRequest &request)
{
auto outcome = MakeRequest(request, "DescribeComponentInfo");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeComponentInfoResponse rsp = DescribeComponentInfoResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeComponentInfoOutcome(rsp);
else
return DescribeComponentInfoOutcome(o.GetError());
}
else
{
return DescribeComponentInfoOutcome(outcome.GetError());
}
}
void CwpClient::DescribeComponentInfoAsync(const DescribeComponentInfoRequest& request, const DescribeComponentInfoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeComponentInfo(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeComponentInfoOutcomeCallable CwpClient::DescribeComponentInfoCallable(const DescribeComponentInfoRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeComponentInfoOutcome()>>(
[this, request]()
{
return this->DescribeComponentInfo(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeComponentStatisticsOutcome CwpClient::DescribeComponentStatistics(const DescribeComponentStatisticsRequest &request)
{
auto outcome = MakeRequest(request, "DescribeComponentStatistics");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeComponentStatisticsResponse rsp = DescribeComponentStatisticsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeComponentStatisticsOutcome(rsp);
else
return DescribeComponentStatisticsOutcome(o.GetError());
}
else
{
return DescribeComponentStatisticsOutcome(outcome.GetError());
}
}
void CwpClient::DescribeComponentStatisticsAsync(const DescribeComponentStatisticsRequest& request, const DescribeComponentStatisticsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeComponentStatistics(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeComponentStatisticsOutcomeCallable CwpClient::DescribeComponentStatisticsCallable(const DescribeComponentStatisticsRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeComponentStatisticsOutcome()>>(
[this, request]()
{
return this->DescribeComponentStatistics(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeComponentsOutcome CwpClient::DescribeComponents(const DescribeComponentsRequest &request)
{
auto outcome = MakeRequest(request, "DescribeComponents");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeComponentsResponse rsp = DescribeComponentsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeComponentsOutcome(rsp);
else
return DescribeComponentsOutcome(o.GetError());
}
else
{
return DescribeComponentsOutcome(outcome.GetError());
}
}
void CwpClient::DescribeComponentsAsync(const DescribeComponentsRequest& request, const DescribeComponentsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeComponents(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeComponentsOutcomeCallable CwpClient::DescribeComponentsCallable(const DescribeComponentsRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeComponentsOutcome()>>(
[this, request]()
{
return this->DescribeComponents(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeESAggregationsOutcome CwpClient::DescribeESAggregations(const DescribeESAggregationsRequest &request)
{
auto outcome = MakeRequest(request, "DescribeESAggregations");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeESAggregationsResponse rsp = DescribeESAggregationsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeESAggregationsOutcome(rsp);
else
return DescribeESAggregationsOutcome(o.GetError());
}
else
{
return DescribeESAggregationsOutcome(outcome.GetError());
}
}
void CwpClient::DescribeESAggregationsAsync(const DescribeESAggregationsRequest& request, const DescribeESAggregationsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeESAggregations(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeESAggregationsOutcomeCallable CwpClient::DescribeESAggregationsCallable(const DescribeESAggregationsRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeESAggregationsOutcome()>>(
[this, request]()
{
return this->DescribeESAggregations(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeESHitsOutcome CwpClient::DescribeESHits(const DescribeESHitsRequest &request)
{
auto outcome = MakeRequest(request, "DescribeESHits");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeESHitsResponse rsp = DescribeESHitsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeESHitsOutcome(rsp);
else
return DescribeESHitsOutcome(o.GetError());
}
else
{
return DescribeESHitsOutcome(outcome.GetError());
}
}
void CwpClient::DescribeESHitsAsync(const DescribeESHitsRequest& request, const DescribeESHitsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeESHits(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeESHitsOutcomeCallable CwpClient::DescribeESHitsCallable(const DescribeESHitsRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeESHitsOutcome()>>(
[this, request]()
{
return this->DescribeESHits(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeExportMachinesOutcome CwpClient::DescribeExportMachines(const DescribeExportMachinesRequest &request)
{
auto outcome = MakeRequest(request, "DescribeExportMachines");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeExportMachinesResponse rsp = DescribeExportMachinesResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeExportMachinesOutcome(rsp);
else
return DescribeExportMachinesOutcome(o.GetError());
}
else
{
return DescribeExportMachinesOutcome(outcome.GetError());
}
}
void CwpClient::DescribeExportMachinesAsync(const DescribeExportMachinesRequest& request, const DescribeExportMachinesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeExportMachines(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeExportMachinesOutcomeCallable CwpClient::DescribeExportMachinesCallable(const DescribeExportMachinesRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeExportMachinesOutcome()>>(
[this, request]()
{
return this->DescribeExportMachines(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeGeneralStatOutcome CwpClient::DescribeGeneralStat(const DescribeGeneralStatRequest &request)
{
auto outcome = MakeRequest(request, "DescribeGeneralStat");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeGeneralStatResponse rsp = DescribeGeneralStatResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeGeneralStatOutcome(rsp);
else
return DescribeGeneralStatOutcome(o.GetError());
}
else
{
return DescribeGeneralStatOutcome(outcome.GetError());
}
}
void CwpClient::DescribeGeneralStatAsync(const DescribeGeneralStatRequest& request, const DescribeGeneralStatAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeGeneralStat(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeGeneralStatOutcomeCallable CwpClient::DescribeGeneralStatCallable(const DescribeGeneralStatRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeGeneralStatOutcome()>>(
[this, request]()
{
return this->DescribeGeneralStat(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeHistoryAccountsOutcome CwpClient::DescribeHistoryAccounts(const DescribeHistoryAccountsRequest &request)
{
auto outcome = MakeRequest(request, "DescribeHistoryAccounts");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeHistoryAccountsResponse rsp = DescribeHistoryAccountsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeHistoryAccountsOutcome(rsp);
else
return DescribeHistoryAccountsOutcome(o.GetError());
}
else
{
return DescribeHistoryAccountsOutcome(outcome.GetError());
}
}
void CwpClient::DescribeHistoryAccountsAsync(const DescribeHistoryAccountsRequest& request, const DescribeHistoryAccountsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeHistoryAccounts(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeHistoryAccountsOutcomeCallable CwpClient::DescribeHistoryAccountsCallable(const DescribeHistoryAccountsRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeHistoryAccountsOutcome()>>(
[this, request]()
{
return this->DescribeHistoryAccounts(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeHistoryServiceOutcome CwpClient::DescribeHistoryService(const DescribeHistoryServiceRequest &request)
{
auto outcome = MakeRequest(request, "DescribeHistoryService");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeHistoryServiceResponse rsp = DescribeHistoryServiceResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeHistoryServiceOutcome(rsp);
else
return DescribeHistoryServiceOutcome(o.GetError());
}
else
{
return DescribeHistoryServiceOutcome(outcome.GetError());
}
}
void CwpClient::DescribeHistoryServiceAsync(const DescribeHistoryServiceRequest& request, const DescribeHistoryServiceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeHistoryService(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeHistoryServiceOutcomeCallable CwpClient::DescribeHistoryServiceCallable(const DescribeHistoryServiceRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeHistoryServiceOutcome()>>(
[this, request]()
{
return this->DescribeHistoryService(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeImpactedHostsOutcome CwpClient::DescribeImpactedHosts(const DescribeImpactedHostsRequest &request)
{
auto outcome = MakeRequest(request, "DescribeImpactedHosts");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeImpactedHostsResponse rsp = DescribeImpactedHostsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeImpactedHostsOutcome(rsp);
else
return DescribeImpactedHostsOutcome(o.GetError());
}
else
{
return DescribeImpactedHostsOutcome(outcome.GetError());
}
}
void CwpClient::DescribeImpactedHostsAsync(const DescribeImpactedHostsRequest& request, const DescribeImpactedHostsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeImpactedHosts(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeImpactedHostsOutcomeCallable CwpClient::DescribeImpactedHostsCallable(const DescribeImpactedHostsRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeImpactedHostsOutcome()>>(
[this, request]()
{
return this->DescribeImpactedHosts(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeImportMachineInfoOutcome CwpClient::DescribeImportMachineInfo(const DescribeImportMachineInfoRequest &request)
{
auto outcome = MakeRequest(request, "DescribeImportMachineInfo");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeImportMachineInfoResponse rsp = DescribeImportMachineInfoResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeImportMachineInfoOutcome(rsp);
else
return DescribeImportMachineInfoOutcome(o.GetError());
}
else
{
return DescribeImportMachineInfoOutcome(outcome.GetError());
}
}
void CwpClient::DescribeImportMachineInfoAsync(const DescribeImportMachineInfoRequest& request, const DescribeImportMachineInfoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeImportMachineInfo(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeImportMachineInfoOutcomeCallable CwpClient::DescribeImportMachineInfoCallable(const DescribeImportMachineInfoRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeImportMachineInfoOutcome()>>(
[this, request]()
{
return this->DescribeImportMachineInfo(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeIndexListOutcome CwpClient::DescribeIndexList(const DescribeIndexListRequest &request)
{
auto outcome = MakeRequest(request, "DescribeIndexList");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeIndexListResponse rsp = DescribeIndexListResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeIndexListOutcome(rsp);
else
return DescribeIndexListOutcome(o.GetError());
}
else
{
return DescribeIndexListOutcome(outcome.GetError());
}
}
void CwpClient::DescribeIndexListAsync(const DescribeIndexListRequest& request, const DescribeIndexListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeIndexList(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeIndexListOutcomeCallable CwpClient::DescribeIndexListCallable(const DescribeIndexListRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeIndexListOutcome()>>(
[this, request]()
{
return this->DescribeIndexList(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeLogStorageStatisticOutcome CwpClient::DescribeLogStorageStatistic(const DescribeLogStorageStatisticRequest &request)
{
auto outcome = MakeRequest(request, "DescribeLogStorageStatistic");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeLogStorageStatisticResponse rsp = DescribeLogStorageStatisticResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeLogStorageStatisticOutcome(rsp);
else
return DescribeLogStorageStatisticOutcome(o.GetError());
}
else
{
return DescribeLogStorageStatisticOutcome(outcome.GetError());
}
}
void CwpClient::DescribeLogStorageStatisticAsync(const DescribeLogStorageStatisticRequest& request, const DescribeLogStorageStatisticAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeLogStorageStatistic(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeLogStorageStatisticOutcomeCallable CwpClient::DescribeLogStorageStatisticCallable(const DescribeLogStorageStatisticRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeLogStorageStatisticOutcome()>>(
[this, request]()
{
return this->DescribeLogStorageStatistic(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeLoginWhiteListOutcome CwpClient::DescribeLoginWhiteList(const DescribeLoginWhiteListRequest &request)
{
auto outcome = MakeRequest(request, "DescribeLoginWhiteList");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeLoginWhiteListResponse rsp = DescribeLoginWhiteListResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeLoginWhiteListOutcome(rsp);
else
return DescribeLoginWhiteListOutcome(o.GetError());
}
else
{
return DescribeLoginWhiteListOutcome(outcome.GetError());
}
}
void CwpClient::DescribeLoginWhiteListAsync(const DescribeLoginWhiteListRequest& request, const DescribeLoginWhiteListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeLoginWhiteList(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeLoginWhiteListOutcomeCallable CwpClient::DescribeLoginWhiteListCallable(const DescribeLoginWhiteListRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeLoginWhiteListOutcome()>>(
[this, request]()
{
return this->DescribeLoginWhiteList(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeMachineInfoOutcome CwpClient::DescribeMachineInfo(const DescribeMachineInfoRequest &request)
{
auto outcome = MakeRequest(request, "DescribeMachineInfo");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeMachineInfoResponse rsp = DescribeMachineInfoResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeMachineInfoOutcome(rsp);
else
return DescribeMachineInfoOutcome(o.GetError());
}
else
{
return DescribeMachineInfoOutcome(outcome.GetError());
}
}
void CwpClient::DescribeMachineInfoAsync(const DescribeMachineInfoRequest& request, const DescribeMachineInfoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeMachineInfo(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeMachineInfoOutcomeCallable CwpClient::DescribeMachineInfoCallable(const DescribeMachineInfoRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeMachineInfoOutcome()>>(
[this, request]()
{
return this->DescribeMachineInfo(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeMachineListOutcome CwpClient::DescribeMachineList(const DescribeMachineListRequest &request)
{
auto outcome = MakeRequest(request, "DescribeMachineList");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeMachineListResponse rsp = DescribeMachineListResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeMachineListOutcome(rsp);
else
return DescribeMachineListOutcome(o.GetError());
}
else
{
return DescribeMachineListOutcome(outcome.GetError());
}
}
void CwpClient::DescribeMachineListAsync(const DescribeMachineListRequest& request, const DescribeMachineListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeMachineList(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeMachineListOutcomeCallable CwpClient::DescribeMachineListCallable(const DescribeMachineListRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeMachineListOutcome()>>(
[this, request]()
{
return this->DescribeMachineList(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeMachineOsListOutcome CwpClient::DescribeMachineOsList(const DescribeMachineOsListRequest &request)
{
auto outcome = MakeRequest(request, "DescribeMachineOsList");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeMachineOsListResponse rsp = DescribeMachineOsListResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeMachineOsListOutcome(rsp);
else
return DescribeMachineOsListOutcome(o.GetError());
}
else
{
return DescribeMachineOsListOutcome(outcome.GetError());
}
}
void CwpClient::DescribeMachineOsListAsync(const DescribeMachineOsListRequest& request, const DescribeMachineOsListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeMachineOsList(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeMachineOsListOutcomeCallable CwpClient::DescribeMachineOsListCallable(const DescribeMachineOsListRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeMachineOsListOutcome()>>(
[this, request]()
{
return this->DescribeMachineOsList(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeMachineRegionsOutcome CwpClient::DescribeMachineRegions(const DescribeMachineRegionsRequest &request)
{
auto outcome = MakeRequest(request, "DescribeMachineRegions");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeMachineRegionsResponse rsp = DescribeMachineRegionsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeMachineRegionsOutcome(rsp);
else
return DescribeMachineRegionsOutcome(o.GetError());
}
else
{
return DescribeMachineRegionsOutcome(outcome.GetError());
}
}
void CwpClient::DescribeMachineRegionsAsync(const DescribeMachineRegionsRequest& request, const DescribeMachineRegionsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeMachineRegions(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeMachineRegionsOutcomeCallable CwpClient::DescribeMachineRegionsCallable(const DescribeMachineRegionsRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeMachineRegionsOutcome()>>(
[this, request]()
{
return this->DescribeMachineRegions(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeMachinesOutcome CwpClient::DescribeMachines(const DescribeMachinesRequest &request)
{
auto outcome = MakeRequest(request, "DescribeMachines");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeMachinesResponse rsp = DescribeMachinesResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeMachinesOutcome(rsp);
else
return DescribeMachinesOutcome(o.GetError());
}
else
{
return DescribeMachinesOutcome(outcome.GetError());
}
}
void CwpClient::DescribeMachinesAsync(const DescribeMachinesRequest& request, const DescribeMachinesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeMachines(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeMachinesOutcomeCallable CwpClient::DescribeMachinesCallable(const DescribeMachinesRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeMachinesOutcome()>>(
[this, request]()
{
return this->DescribeMachines(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeMaliciousRequestsOutcome CwpClient::DescribeMaliciousRequests(const DescribeMaliciousRequestsRequest &request)
{
auto outcome = MakeRequest(request, "DescribeMaliciousRequests");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeMaliciousRequestsResponse rsp = DescribeMaliciousRequestsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeMaliciousRequestsOutcome(rsp);
else
return DescribeMaliciousRequestsOutcome(o.GetError());
}
else
{
return DescribeMaliciousRequestsOutcome(outcome.GetError());
}
}
void CwpClient::DescribeMaliciousRequestsAsync(const DescribeMaliciousRequestsRequest& request, const DescribeMaliciousRequestsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeMaliciousRequests(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeMaliciousRequestsOutcomeCallable CwpClient::DescribeMaliciousRequestsCallable(const DescribeMaliciousRequestsRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeMaliciousRequestsOutcome()>>(
[this, request]()
{
return this->DescribeMaliciousRequests(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeMalwareInfoOutcome CwpClient::DescribeMalwareInfo(const DescribeMalwareInfoRequest &request)
{
auto outcome = MakeRequest(request, "DescribeMalwareInfo");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeMalwareInfoResponse rsp = DescribeMalwareInfoResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeMalwareInfoOutcome(rsp);
else
return DescribeMalwareInfoOutcome(o.GetError());
}
else
{
return DescribeMalwareInfoOutcome(outcome.GetError());
}
}
void CwpClient::DescribeMalwareInfoAsync(const DescribeMalwareInfoRequest& request, const DescribeMalwareInfoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeMalwareInfo(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeMalwareInfoOutcomeCallable CwpClient::DescribeMalwareInfoCallable(const DescribeMalwareInfoRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeMalwareInfoOutcome()>>(
[this, request]()
{
return this->DescribeMalwareInfo(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeMalwaresOutcome CwpClient::DescribeMalwares(const DescribeMalwaresRequest &request)
{
auto outcome = MakeRequest(request, "DescribeMalwares");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeMalwaresResponse rsp = DescribeMalwaresResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeMalwaresOutcome(rsp);
else
return DescribeMalwaresOutcome(o.GetError());
}
else
{
return DescribeMalwaresOutcome(outcome.GetError());
}
}
void CwpClient::DescribeMalwaresAsync(const DescribeMalwaresRequest& request, const DescribeMalwaresAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeMalwares(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeMalwaresOutcomeCallable CwpClient::DescribeMalwaresCallable(const DescribeMalwaresRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeMalwaresOutcome()>>(
[this, request]()
{
return this->DescribeMalwares(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeNonlocalLoginPlacesOutcome CwpClient::DescribeNonlocalLoginPlaces(const DescribeNonlocalLoginPlacesRequest &request)
{
auto outcome = MakeRequest(request, "DescribeNonlocalLoginPlaces");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeNonlocalLoginPlacesResponse rsp = DescribeNonlocalLoginPlacesResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeNonlocalLoginPlacesOutcome(rsp);
else
return DescribeNonlocalLoginPlacesOutcome(o.GetError());
}
else
{
return DescribeNonlocalLoginPlacesOutcome(outcome.GetError());
}
}
void CwpClient::DescribeNonlocalLoginPlacesAsync(const DescribeNonlocalLoginPlacesRequest& request, const DescribeNonlocalLoginPlacesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeNonlocalLoginPlaces(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeNonlocalLoginPlacesOutcomeCallable CwpClient::DescribeNonlocalLoginPlacesCallable(const DescribeNonlocalLoginPlacesRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeNonlocalLoginPlacesOutcome()>>(
[this, request]()
{
return this->DescribeNonlocalLoginPlaces(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeOpenPortStatisticsOutcome CwpClient::DescribeOpenPortStatistics(const DescribeOpenPortStatisticsRequest &request)
{
auto outcome = MakeRequest(request, "DescribeOpenPortStatistics");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeOpenPortStatisticsResponse rsp = DescribeOpenPortStatisticsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeOpenPortStatisticsOutcome(rsp);
else
return DescribeOpenPortStatisticsOutcome(o.GetError());
}
else
{
return DescribeOpenPortStatisticsOutcome(outcome.GetError());
}
}
void CwpClient::DescribeOpenPortStatisticsAsync(const DescribeOpenPortStatisticsRequest& request, const DescribeOpenPortStatisticsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeOpenPortStatistics(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeOpenPortStatisticsOutcomeCallable CwpClient::DescribeOpenPortStatisticsCallable(const DescribeOpenPortStatisticsRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeOpenPortStatisticsOutcome()>>(
[this, request]()
{
return this->DescribeOpenPortStatistics(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeOpenPortTaskStatusOutcome CwpClient::DescribeOpenPortTaskStatus(const DescribeOpenPortTaskStatusRequest &request)
{
auto outcome = MakeRequest(request, "DescribeOpenPortTaskStatus");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeOpenPortTaskStatusResponse rsp = DescribeOpenPortTaskStatusResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeOpenPortTaskStatusOutcome(rsp);
else
return DescribeOpenPortTaskStatusOutcome(o.GetError());
}
else
{
return DescribeOpenPortTaskStatusOutcome(outcome.GetError());
}
}
void CwpClient::DescribeOpenPortTaskStatusAsync(const DescribeOpenPortTaskStatusRequest& request, const DescribeOpenPortTaskStatusAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeOpenPortTaskStatus(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeOpenPortTaskStatusOutcomeCallable CwpClient::DescribeOpenPortTaskStatusCallable(const DescribeOpenPortTaskStatusRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeOpenPortTaskStatusOutcome()>>(
[this, request]()
{
return this->DescribeOpenPortTaskStatus(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeOpenPortsOutcome CwpClient::DescribeOpenPorts(const DescribeOpenPortsRequest &request)
{
auto outcome = MakeRequest(request, "DescribeOpenPorts");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeOpenPortsResponse rsp = DescribeOpenPortsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeOpenPortsOutcome(rsp);
else
return DescribeOpenPortsOutcome(o.GetError());
}
else
{
return DescribeOpenPortsOutcome(outcome.GetError());
}
}
void CwpClient::DescribeOpenPortsAsync(const DescribeOpenPortsRequest& request, const DescribeOpenPortsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeOpenPorts(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeOpenPortsOutcomeCallable CwpClient::DescribeOpenPortsCallable(const DescribeOpenPortsRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeOpenPortsOutcome()>>(
[this, request]()
{
return this->DescribeOpenPorts(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeOverviewStatisticsOutcome CwpClient::DescribeOverviewStatistics(const DescribeOverviewStatisticsRequest &request)
{
auto outcome = MakeRequest(request, "DescribeOverviewStatistics");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeOverviewStatisticsResponse rsp = DescribeOverviewStatisticsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeOverviewStatisticsOutcome(rsp);
else
return DescribeOverviewStatisticsOutcome(o.GetError());
}
else
{
return DescribeOverviewStatisticsOutcome(outcome.GetError());
}
}
void CwpClient::DescribeOverviewStatisticsAsync(const DescribeOverviewStatisticsRequest& request, const DescribeOverviewStatisticsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeOverviewStatistics(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeOverviewStatisticsOutcomeCallable CwpClient::DescribeOverviewStatisticsCallable(const DescribeOverviewStatisticsRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeOverviewStatisticsOutcome()>>(
[this, request]()
{
return this->DescribeOverviewStatistics(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribePrivilegeEventsOutcome CwpClient::DescribePrivilegeEvents(const DescribePrivilegeEventsRequest &request)
{
auto outcome = MakeRequest(request, "DescribePrivilegeEvents");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribePrivilegeEventsResponse rsp = DescribePrivilegeEventsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribePrivilegeEventsOutcome(rsp);
else
return DescribePrivilegeEventsOutcome(o.GetError());
}
else
{
return DescribePrivilegeEventsOutcome(outcome.GetError());
}
}
void CwpClient::DescribePrivilegeEventsAsync(const DescribePrivilegeEventsRequest& request, const DescribePrivilegeEventsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribePrivilegeEvents(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribePrivilegeEventsOutcomeCallable CwpClient::DescribePrivilegeEventsCallable(const DescribePrivilegeEventsRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribePrivilegeEventsOutcome()>>(
[this, request]()
{
return this->DescribePrivilegeEvents(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribePrivilegeRulesOutcome CwpClient::DescribePrivilegeRules(const DescribePrivilegeRulesRequest &request)
{
auto outcome = MakeRequest(request, "DescribePrivilegeRules");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribePrivilegeRulesResponse rsp = DescribePrivilegeRulesResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribePrivilegeRulesOutcome(rsp);
else
return DescribePrivilegeRulesOutcome(o.GetError());
}
else
{
return DescribePrivilegeRulesOutcome(outcome.GetError());
}
}
void CwpClient::DescribePrivilegeRulesAsync(const DescribePrivilegeRulesRequest& request, const DescribePrivilegeRulesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribePrivilegeRules(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribePrivilegeRulesOutcomeCallable CwpClient::DescribePrivilegeRulesCallable(const DescribePrivilegeRulesRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribePrivilegeRulesOutcome()>>(
[this, request]()
{
return this->DescribePrivilegeRules(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeProVersionInfoOutcome CwpClient::DescribeProVersionInfo(const DescribeProVersionInfoRequest &request)
{
auto outcome = MakeRequest(request, "DescribeProVersionInfo");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeProVersionInfoResponse rsp = DescribeProVersionInfoResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeProVersionInfoOutcome(rsp);
else
return DescribeProVersionInfoOutcome(o.GetError());
}
else
{
return DescribeProVersionInfoOutcome(outcome.GetError());
}
}
void CwpClient::DescribeProVersionInfoAsync(const DescribeProVersionInfoRequest& request, const DescribeProVersionInfoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeProVersionInfo(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeProVersionInfoOutcomeCallable CwpClient::DescribeProVersionInfoCallable(const DescribeProVersionInfoRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeProVersionInfoOutcome()>>(
[this, request]()
{
return this->DescribeProVersionInfo(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeProcessStatisticsOutcome CwpClient::DescribeProcessStatistics(const DescribeProcessStatisticsRequest &request)
{
auto outcome = MakeRequest(request, "DescribeProcessStatistics");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeProcessStatisticsResponse rsp = DescribeProcessStatisticsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeProcessStatisticsOutcome(rsp);
else
return DescribeProcessStatisticsOutcome(o.GetError());
}
else
{
return DescribeProcessStatisticsOutcome(outcome.GetError());
}
}
void CwpClient::DescribeProcessStatisticsAsync(const DescribeProcessStatisticsRequest& request, const DescribeProcessStatisticsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeProcessStatistics(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeProcessStatisticsOutcomeCallable CwpClient::DescribeProcessStatisticsCallable(const DescribeProcessStatisticsRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeProcessStatisticsOutcome()>>(
[this, request]()
{
return this->DescribeProcessStatistics(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeProcessTaskStatusOutcome CwpClient::DescribeProcessTaskStatus(const DescribeProcessTaskStatusRequest &request)
{
auto outcome = MakeRequest(request, "DescribeProcessTaskStatus");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeProcessTaskStatusResponse rsp = DescribeProcessTaskStatusResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeProcessTaskStatusOutcome(rsp);
else
return DescribeProcessTaskStatusOutcome(o.GetError());
}
else
{
return DescribeProcessTaskStatusOutcome(outcome.GetError());
}
}
void CwpClient::DescribeProcessTaskStatusAsync(const DescribeProcessTaskStatusRequest& request, const DescribeProcessTaskStatusAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeProcessTaskStatus(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeProcessTaskStatusOutcomeCallable CwpClient::DescribeProcessTaskStatusCallable(const DescribeProcessTaskStatusRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeProcessTaskStatusOutcome()>>(
[this, request]()
{
return this->DescribeProcessTaskStatus(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeProcessesOutcome CwpClient::DescribeProcesses(const DescribeProcessesRequest &request)
{
auto outcome = MakeRequest(request, "DescribeProcesses");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeProcessesResponse rsp = DescribeProcessesResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeProcessesOutcome(rsp);
else
return DescribeProcessesOutcome(o.GetError());
}
else
{
return DescribeProcessesOutcome(outcome.GetError());
}
}
void CwpClient::DescribeProcessesAsync(const DescribeProcessesRequest& request, const DescribeProcessesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeProcesses(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeProcessesOutcomeCallable CwpClient::DescribeProcessesCallable(const DescribeProcessesRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeProcessesOutcome()>>(
[this, request]()
{
return this->DescribeProcesses(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeReverseShellEventsOutcome CwpClient::DescribeReverseShellEvents(const DescribeReverseShellEventsRequest &request)
{
auto outcome = MakeRequest(request, "DescribeReverseShellEvents");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeReverseShellEventsResponse rsp = DescribeReverseShellEventsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeReverseShellEventsOutcome(rsp);
else
return DescribeReverseShellEventsOutcome(o.GetError());
}
else
{
return DescribeReverseShellEventsOutcome(outcome.GetError());
}
}
void CwpClient::DescribeReverseShellEventsAsync(const DescribeReverseShellEventsRequest& request, const DescribeReverseShellEventsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeReverseShellEvents(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeReverseShellEventsOutcomeCallable CwpClient::DescribeReverseShellEventsCallable(const DescribeReverseShellEventsRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeReverseShellEventsOutcome()>>(
[this, request]()
{
return this->DescribeReverseShellEvents(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeReverseShellRulesOutcome CwpClient::DescribeReverseShellRules(const DescribeReverseShellRulesRequest &request)
{
auto outcome = MakeRequest(request, "DescribeReverseShellRules");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeReverseShellRulesResponse rsp = DescribeReverseShellRulesResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeReverseShellRulesOutcome(rsp);
else
return DescribeReverseShellRulesOutcome(o.GetError());
}
else
{
return DescribeReverseShellRulesOutcome(outcome.GetError());
}
}
void CwpClient::DescribeReverseShellRulesAsync(const DescribeReverseShellRulesRequest& request, const DescribeReverseShellRulesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeReverseShellRules(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeReverseShellRulesOutcomeCallable CwpClient::DescribeReverseShellRulesCallable(const DescribeReverseShellRulesRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeReverseShellRulesOutcome()>>(
[this, request]()
{
return this->DescribeReverseShellRules(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeRiskDnsListOutcome CwpClient::DescribeRiskDnsList(const DescribeRiskDnsListRequest &request)
{
auto outcome = MakeRequest(request, "DescribeRiskDnsList");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeRiskDnsListResponse rsp = DescribeRiskDnsListResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeRiskDnsListOutcome(rsp);
else
return DescribeRiskDnsListOutcome(o.GetError());
}
else
{
return DescribeRiskDnsListOutcome(outcome.GetError());
}
}
void CwpClient::DescribeRiskDnsListAsync(const DescribeRiskDnsListRequest& request, const DescribeRiskDnsListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeRiskDnsList(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeRiskDnsListOutcomeCallable CwpClient::DescribeRiskDnsListCallable(const DescribeRiskDnsListRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeRiskDnsListOutcome()>>(
[this, request]()
{
return this->DescribeRiskDnsList(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeScanMalwareScheduleOutcome CwpClient::DescribeScanMalwareSchedule(const DescribeScanMalwareScheduleRequest &request)
{
auto outcome = MakeRequest(request, "DescribeScanMalwareSchedule");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeScanMalwareScheduleResponse rsp = DescribeScanMalwareScheduleResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeScanMalwareScheduleOutcome(rsp);
else
return DescribeScanMalwareScheduleOutcome(o.GetError());
}
else
{
return DescribeScanMalwareScheduleOutcome(outcome.GetError());
}
}
void CwpClient::DescribeScanMalwareScheduleAsync(const DescribeScanMalwareScheduleRequest& request, const DescribeScanMalwareScheduleAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeScanMalwareSchedule(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeScanMalwareScheduleOutcomeCallable CwpClient::DescribeScanMalwareScheduleCallable(const DescribeScanMalwareScheduleRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeScanMalwareScheduleOutcome()>>(
[this, request]()
{
return this->DescribeScanMalwareSchedule(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeSearchExportListOutcome CwpClient::DescribeSearchExportList(const DescribeSearchExportListRequest &request)
{
auto outcome = MakeRequest(request, "DescribeSearchExportList");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeSearchExportListResponse rsp = DescribeSearchExportListResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeSearchExportListOutcome(rsp);
else
return DescribeSearchExportListOutcome(o.GetError());
}
else
{
return DescribeSearchExportListOutcome(outcome.GetError());
}
}
void CwpClient::DescribeSearchExportListAsync(const DescribeSearchExportListRequest& request, const DescribeSearchExportListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeSearchExportList(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeSearchExportListOutcomeCallable CwpClient::DescribeSearchExportListCallable(const DescribeSearchExportListRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeSearchExportListOutcome()>>(
[this, request]()
{
return this->DescribeSearchExportList(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeSearchLogsOutcome CwpClient::DescribeSearchLogs(const DescribeSearchLogsRequest &request)
{
auto outcome = MakeRequest(request, "DescribeSearchLogs");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeSearchLogsResponse rsp = DescribeSearchLogsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeSearchLogsOutcome(rsp);
else
return DescribeSearchLogsOutcome(o.GetError());
}
else
{
return DescribeSearchLogsOutcome(outcome.GetError());
}
}
void CwpClient::DescribeSearchLogsAsync(const DescribeSearchLogsRequest& request, const DescribeSearchLogsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeSearchLogs(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeSearchLogsOutcomeCallable CwpClient::DescribeSearchLogsCallable(const DescribeSearchLogsRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeSearchLogsOutcome()>>(
[this, request]()
{
return this->DescribeSearchLogs(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeSearchTemplatesOutcome CwpClient::DescribeSearchTemplates(const DescribeSearchTemplatesRequest &request)
{
auto outcome = MakeRequest(request, "DescribeSearchTemplates");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeSearchTemplatesResponse rsp = DescribeSearchTemplatesResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeSearchTemplatesOutcome(rsp);
else
return DescribeSearchTemplatesOutcome(o.GetError());
}
else
{
return DescribeSearchTemplatesOutcome(outcome.GetError());
}
}
void CwpClient::DescribeSearchTemplatesAsync(const DescribeSearchTemplatesRequest& request, const DescribeSearchTemplatesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeSearchTemplates(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeSearchTemplatesOutcomeCallable CwpClient::DescribeSearchTemplatesCallable(const DescribeSearchTemplatesRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeSearchTemplatesOutcome()>>(
[this, request]()
{
return this->DescribeSearchTemplates(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeSecurityDynamicsOutcome CwpClient::DescribeSecurityDynamics(const DescribeSecurityDynamicsRequest &request)
{
auto outcome = MakeRequest(request, "DescribeSecurityDynamics");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeSecurityDynamicsResponse rsp = DescribeSecurityDynamicsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeSecurityDynamicsOutcome(rsp);
else
return DescribeSecurityDynamicsOutcome(o.GetError());
}
else
{
return DescribeSecurityDynamicsOutcome(outcome.GetError());
}
}
void CwpClient::DescribeSecurityDynamicsAsync(const DescribeSecurityDynamicsRequest& request, const DescribeSecurityDynamicsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeSecurityDynamics(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeSecurityDynamicsOutcomeCallable CwpClient::DescribeSecurityDynamicsCallable(const DescribeSecurityDynamicsRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeSecurityDynamicsOutcome()>>(
[this, request]()
{
return this->DescribeSecurityDynamics(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeSecurityEventsCntOutcome CwpClient::DescribeSecurityEventsCnt(const DescribeSecurityEventsCntRequest &request)
{
auto outcome = MakeRequest(request, "DescribeSecurityEventsCnt");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeSecurityEventsCntResponse rsp = DescribeSecurityEventsCntResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeSecurityEventsCntOutcome(rsp);
else
return DescribeSecurityEventsCntOutcome(o.GetError());
}
else
{
return DescribeSecurityEventsCntOutcome(outcome.GetError());
}
}
void CwpClient::DescribeSecurityEventsCntAsync(const DescribeSecurityEventsCntRequest& request, const DescribeSecurityEventsCntAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeSecurityEventsCnt(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeSecurityEventsCntOutcomeCallable CwpClient::DescribeSecurityEventsCntCallable(const DescribeSecurityEventsCntRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeSecurityEventsCntOutcome()>>(
[this, request]()
{
return this->DescribeSecurityEventsCnt(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeSecurityTrendsOutcome CwpClient::DescribeSecurityTrends(const DescribeSecurityTrendsRequest &request)
{
auto outcome = MakeRequest(request, "DescribeSecurityTrends");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeSecurityTrendsResponse rsp = DescribeSecurityTrendsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeSecurityTrendsOutcome(rsp);
else
return DescribeSecurityTrendsOutcome(o.GetError());
}
else
{
return DescribeSecurityTrendsOutcome(outcome.GetError());
}
}
void CwpClient::DescribeSecurityTrendsAsync(const DescribeSecurityTrendsRequest& request, const DescribeSecurityTrendsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeSecurityTrends(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeSecurityTrendsOutcomeCallable CwpClient::DescribeSecurityTrendsCallable(const DescribeSecurityTrendsRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeSecurityTrendsOutcome()>>(
[this, request]()
{
return this->DescribeSecurityTrends(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeTagMachinesOutcome CwpClient::DescribeTagMachines(const DescribeTagMachinesRequest &request)
{
auto outcome = MakeRequest(request, "DescribeTagMachines");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeTagMachinesResponse rsp = DescribeTagMachinesResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeTagMachinesOutcome(rsp);
else
return DescribeTagMachinesOutcome(o.GetError());
}
else
{
return DescribeTagMachinesOutcome(outcome.GetError());
}
}
void CwpClient::DescribeTagMachinesAsync(const DescribeTagMachinesRequest& request, const DescribeTagMachinesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeTagMachines(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeTagMachinesOutcomeCallable CwpClient::DescribeTagMachinesCallable(const DescribeTagMachinesRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeTagMachinesOutcome()>>(
[this, request]()
{
return this->DescribeTagMachines(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeTagsOutcome CwpClient::DescribeTags(const DescribeTagsRequest &request)
{
auto outcome = MakeRequest(request, "DescribeTags");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeTagsResponse rsp = DescribeTagsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeTagsOutcome(rsp);
else
return DescribeTagsOutcome(o.GetError());
}
else
{
return DescribeTagsOutcome(outcome.GetError());
}
}
void CwpClient::DescribeTagsAsync(const DescribeTagsRequest& request, const DescribeTagsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeTags(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeTagsOutcomeCallable CwpClient::DescribeTagsCallable(const DescribeTagsRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeTagsOutcome()>>(
[this, request]()
{
return this->DescribeTags(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeUsualLoginPlacesOutcome CwpClient::DescribeUsualLoginPlaces(const DescribeUsualLoginPlacesRequest &request)
{
auto outcome = MakeRequest(request, "DescribeUsualLoginPlaces");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeUsualLoginPlacesResponse rsp = DescribeUsualLoginPlacesResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeUsualLoginPlacesOutcome(rsp);
else
return DescribeUsualLoginPlacesOutcome(o.GetError());
}
else
{
return DescribeUsualLoginPlacesOutcome(outcome.GetError());
}
}
void CwpClient::DescribeUsualLoginPlacesAsync(const DescribeUsualLoginPlacesRequest& request, const DescribeUsualLoginPlacesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeUsualLoginPlaces(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeUsualLoginPlacesOutcomeCallable CwpClient::DescribeUsualLoginPlacesCallable(const DescribeUsualLoginPlacesRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeUsualLoginPlacesOutcome()>>(
[this, request]()
{
return this->DescribeUsualLoginPlaces(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeVulInfoOutcome CwpClient::DescribeVulInfo(const DescribeVulInfoRequest &request)
{
auto outcome = MakeRequest(request, "DescribeVulInfo");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeVulInfoResponse rsp = DescribeVulInfoResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeVulInfoOutcome(rsp);
else
return DescribeVulInfoOutcome(o.GetError());
}
else
{
return DescribeVulInfoOutcome(outcome.GetError());
}
}
void CwpClient::DescribeVulInfoAsync(const DescribeVulInfoRequest& request, const DescribeVulInfoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeVulInfo(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeVulInfoOutcomeCallable CwpClient::DescribeVulInfoCallable(const DescribeVulInfoRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeVulInfoOutcome()>>(
[this, request]()
{
return this->DescribeVulInfo(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeVulScanResultOutcome CwpClient::DescribeVulScanResult(const DescribeVulScanResultRequest &request)
{
auto outcome = MakeRequest(request, "DescribeVulScanResult");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeVulScanResultResponse rsp = DescribeVulScanResultResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeVulScanResultOutcome(rsp);
else
return DescribeVulScanResultOutcome(o.GetError());
}
else
{
return DescribeVulScanResultOutcome(outcome.GetError());
}
}
void CwpClient::DescribeVulScanResultAsync(const DescribeVulScanResultRequest& request, const DescribeVulScanResultAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeVulScanResult(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeVulScanResultOutcomeCallable CwpClient::DescribeVulScanResultCallable(const DescribeVulScanResultRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeVulScanResultOutcome()>>(
[this, request]()
{
return this->DescribeVulScanResult(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeVulsOutcome CwpClient::DescribeVuls(const DescribeVulsRequest &request)
{
auto outcome = MakeRequest(request, "DescribeVuls");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeVulsResponse rsp = DescribeVulsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeVulsOutcome(rsp);
else
return DescribeVulsOutcome(o.GetError());
}
else
{
return DescribeVulsOutcome(outcome.GetError());
}
}
void CwpClient::DescribeVulsAsync(const DescribeVulsRequest& request, const DescribeVulsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeVuls(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeVulsOutcomeCallable CwpClient::DescribeVulsCallable(const DescribeVulsRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeVulsOutcome()>>(
[this, request]()
{
return this->DescribeVuls(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeWebPageGeneralizeOutcome CwpClient::DescribeWebPageGeneralize(const DescribeWebPageGeneralizeRequest &request)
{
auto outcome = MakeRequest(request, "DescribeWebPageGeneralize");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeWebPageGeneralizeResponse rsp = DescribeWebPageGeneralizeResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeWebPageGeneralizeOutcome(rsp);
else
return DescribeWebPageGeneralizeOutcome(o.GetError());
}
else
{
return DescribeWebPageGeneralizeOutcome(outcome.GetError());
}
}
void CwpClient::DescribeWebPageGeneralizeAsync(const DescribeWebPageGeneralizeRequest& request, const DescribeWebPageGeneralizeAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeWebPageGeneralize(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeWebPageGeneralizeOutcomeCallable CwpClient::DescribeWebPageGeneralizeCallable(const DescribeWebPageGeneralizeRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeWebPageGeneralizeOutcome()>>(
[this, request]()
{
return this->DescribeWebPageGeneralize(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeWeeklyReportBruteAttacksOutcome CwpClient::DescribeWeeklyReportBruteAttacks(const DescribeWeeklyReportBruteAttacksRequest &request)
{
auto outcome = MakeRequest(request, "DescribeWeeklyReportBruteAttacks");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeWeeklyReportBruteAttacksResponse rsp = DescribeWeeklyReportBruteAttacksResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeWeeklyReportBruteAttacksOutcome(rsp);
else
return DescribeWeeklyReportBruteAttacksOutcome(o.GetError());
}
else
{
return DescribeWeeklyReportBruteAttacksOutcome(outcome.GetError());
}
}
void CwpClient::DescribeWeeklyReportBruteAttacksAsync(const DescribeWeeklyReportBruteAttacksRequest& request, const DescribeWeeklyReportBruteAttacksAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeWeeklyReportBruteAttacks(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeWeeklyReportBruteAttacksOutcomeCallable CwpClient::DescribeWeeklyReportBruteAttacksCallable(const DescribeWeeklyReportBruteAttacksRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeWeeklyReportBruteAttacksOutcome()>>(
[this, request]()
{
return this->DescribeWeeklyReportBruteAttacks(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeWeeklyReportInfoOutcome CwpClient::DescribeWeeklyReportInfo(const DescribeWeeklyReportInfoRequest &request)
{
auto outcome = MakeRequest(request, "DescribeWeeklyReportInfo");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeWeeklyReportInfoResponse rsp = DescribeWeeklyReportInfoResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeWeeklyReportInfoOutcome(rsp);
else
return DescribeWeeklyReportInfoOutcome(o.GetError());
}
else
{
return DescribeWeeklyReportInfoOutcome(outcome.GetError());
}
}
void CwpClient::DescribeWeeklyReportInfoAsync(const DescribeWeeklyReportInfoRequest& request, const DescribeWeeklyReportInfoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeWeeklyReportInfo(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeWeeklyReportInfoOutcomeCallable CwpClient::DescribeWeeklyReportInfoCallable(const DescribeWeeklyReportInfoRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeWeeklyReportInfoOutcome()>>(
[this, request]()
{
return this->DescribeWeeklyReportInfo(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeWeeklyReportMalwaresOutcome CwpClient::DescribeWeeklyReportMalwares(const DescribeWeeklyReportMalwaresRequest &request)
{
auto outcome = MakeRequest(request, "DescribeWeeklyReportMalwares");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeWeeklyReportMalwaresResponse rsp = DescribeWeeklyReportMalwaresResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeWeeklyReportMalwaresOutcome(rsp);
else
return DescribeWeeklyReportMalwaresOutcome(o.GetError());
}
else
{
return DescribeWeeklyReportMalwaresOutcome(outcome.GetError());
}
}
void CwpClient::DescribeWeeklyReportMalwaresAsync(const DescribeWeeklyReportMalwaresRequest& request, const DescribeWeeklyReportMalwaresAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeWeeklyReportMalwares(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeWeeklyReportMalwaresOutcomeCallable CwpClient::DescribeWeeklyReportMalwaresCallable(const DescribeWeeklyReportMalwaresRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeWeeklyReportMalwaresOutcome()>>(
[this, request]()
{
return this->DescribeWeeklyReportMalwares(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeWeeklyReportNonlocalLoginPlacesOutcome CwpClient::DescribeWeeklyReportNonlocalLoginPlaces(const DescribeWeeklyReportNonlocalLoginPlacesRequest &request)
{
auto outcome = MakeRequest(request, "DescribeWeeklyReportNonlocalLoginPlaces");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeWeeklyReportNonlocalLoginPlacesResponse rsp = DescribeWeeklyReportNonlocalLoginPlacesResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeWeeklyReportNonlocalLoginPlacesOutcome(rsp);
else
return DescribeWeeklyReportNonlocalLoginPlacesOutcome(o.GetError());
}
else
{
return DescribeWeeklyReportNonlocalLoginPlacesOutcome(outcome.GetError());
}
}
void CwpClient::DescribeWeeklyReportNonlocalLoginPlacesAsync(const DescribeWeeklyReportNonlocalLoginPlacesRequest& request, const DescribeWeeklyReportNonlocalLoginPlacesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeWeeklyReportNonlocalLoginPlaces(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeWeeklyReportNonlocalLoginPlacesOutcomeCallable CwpClient::DescribeWeeklyReportNonlocalLoginPlacesCallable(const DescribeWeeklyReportNonlocalLoginPlacesRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeWeeklyReportNonlocalLoginPlacesOutcome()>>(
[this, request]()
{
return this->DescribeWeeklyReportNonlocalLoginPlaces(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeWeeklyReportVulsOutcome CwpClient::DescribeWeeklyReportVuls(const DescribeWeeklyReportVulsRequest &request)
{
auto outcome = MakeRequest(request, "DescribeWeeklyReportVuls");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeWeeklyReportVulsResponse rsp = DescribeWeeklyReportVulsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeWeeklyReportVulsOutcome(rsp);
else
return DescribeWeeklyReportVulsOutcome(o.GetError());
}
else
{
return DescribeWeeklyReportVulsOutcome(outcome.GetError());
}
}
void CwpClient::DescribeWeeklyReportVulsAsync(const DescribeWeeklyReportVulsRequest& request, const DescribeWeeklyReportVulsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeWeeklyReportVuls(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeWeeklyReportVulsOutcomeCallable CwpClient::DescribeWeeklyReportVulsCallable(const DescribeWeeklyReportVulsRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeWeeklyReportVulsOutcome()>>(
[this, request]()
{
return this->DescribeWeeklyReportVuls(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::DescribeWeeklyReportsOutcome CwpClient::DescribeWeeklyReports(const DescribeWeeklyReportsRequest &request)
{
auto outcome = MakeRequest(request, "DescribeWeeklyReports");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeWeeklyReportsResponse rsp = DescribeWeeklyReportsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeWeeklyReportsOutcome(rsp);
else
return DescribeWeeklyReportsOutcome(o.GetError());
}
else
{
return DescribeWeeklyReportsOutcome(outcome.GetError());
}
}
void CwpClient::DescribeWeeklyReportsAsync(const DescribeWeeklyReportsRequest& request, const DescribeWeeklyReportsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeWeeklyReports(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::DescribeWeeklyReportsOutcomeCallable CwpClient::DescribeWeeklyReportsCallable(const DescribeWeeklyReportsRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeWeeklyReportsOutcome()>>(
[this, request]()
{
return this->DescribeWeeklyReports(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::EditBashRuleOutcome CwpClient::EditBashRule(const EditBashRuleRequest &request)
{
auto outcome = MakeRequest(request, "EditBashRule");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
EditBashRuleResponse rsp = EditBashRuleResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return EditBashRuleOutcome(rsp);
else
return EditBashRuleOutcome(o.GetError());
}
else
{
return EditBashRuleOutcome(outcome.GetError());
}
}
void CwpClient::EditBashRuleAsync(const EditBashRuleRequest& request, const EditBashRuleAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->EditBashRule(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::EditBashRuleOutcomeCallable CwpClient::EditBashRuleCallable(const EditBashRuleRequest &request)
{
auto task = std::make_shared<std::packaged_task<EditBashRuleOutcome()>>(
[this, request]()
{
return this->EditBashRule(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::EditPrivilegeRuleOutcome CwpClient::EditPrivilegeRule(const EditPrivilegeRuleRequest &request)
{
auto outcome = MakeRequest(request, "EditPrivilegeRule");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
EditPrivilegeRuleResponse rsp = EditPrivilegeRuleResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return EditPrivilegeRuleOutcome(rsp);
else
return EditPrivilegeRuleOutcome(o.GetError());
}
else
{
return EditPrivilegeRuleOutcome(outcome.GetError());
}
}
void CwpClient::EditPrivilegeRuleAsync(const EditPrivilegeRuleRequest& request, const EditPrivilegeRuleAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->EditPrivilegeRule(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::EditPrivilegeRuleOutcomeCallable CwpClient::EditPrivilegeRuleCallable(const EditPrivilegeRuleRequest &request)
{
auto task = std::make_shared<std::packaged_task<EditPrivilegeRuleOutcome()>>(
[this, request]()
{
return this->EditPrivilegeRule(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::EditReverseShellRuleOutcome CwpClient::EditReverseShellRule(const EditReverseShellRuleRequest &request)
{
auto outcome = MakeRequest(request, "EditReverseShellRule");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
EditReverseShellRuleResponse rsp = EditReverseShellRuleResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return EditReverseShellRuleOutcome(rsp);
else
return EditReverseShellRuleOutcome(o.GetError());
}
else
{
return EditReverseShellRuleOutcome(outcome.GetError());
}
}
void CwpClient::EditReverseShellRuleAsync(const EditReverseShellRuleRequest& request, const EditReverseShellRuleAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->EditReverseShellRule(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::EditReverseShellRuleOutcomeCallable CwpClient::EditReverseShellRuleCallable(const EditReverseShellRuleRequest &request)
{
auto task = std::make_shared<std::packaged_task<EditReverseShellRuleOutcome()>>(
[this, request]()
{
return this->EditReverseShellRule(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::EditTagsOutcome CwpClient::EditTags(const EditTagsRequest &request)
{
auto outcome = MakeRequest(request, "EditTags");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
EditTagsResponse rsp = EditTagsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return EditTagsOutcome(rsp);
else
return EditTagsOutcome(o.GetError());
}
else
{
return EditTagsOutcome(outcome.GetError());
}
}
void CwpClient::EditTagsAsync(const EditTagsRequest& request, const EditTagsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->EditTags(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::EditTagsOutcomeCallable CwpClient::EditTagsCallable(const EditTagsRequest &request)
{
auto task = std::make_shared<std::packaged_task<EditTagsOutcome()>>(
[this, request]()
{
return this->EditTags(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::ExportAssetCoreModuleListOutcome CwpClient::ExportAssetCoreModuleList(const ExportAssetCoreModuleListRequest &request)
{
auto outcome = MakeRequest(request, "ExportAssetCoreModuleList");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
ExportAssetCoreModuleListResponse rsp = ExportAssetCoreModuleListResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return ExportAssetCoreModuleListOutcome(rsp);
else
return ExportAssetCoreModuleListOutcome(o.GetError());
}
else
{
return ExportAssetCoreModuleListOutcome(outcome.GetError());
}
}
void CwpClient::ExportAssetCoreModuleListAsync(const ExportAssetCoreModuleListRequest& request, const ExportAssetCoreModuleListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->ExportAssetCoreModuleList(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::ExportAssetCoreModuleListOutcomeCallable CwpClient::ExportAssetCoreModuleListCallable(const ExportAssetCoreModuleListRequest &request)
{
auto task = std::make_shared<std::packaged_task<ExportAssetCoreModuleListOutcome()>>(
[this, request]()
{
return this->ExportAssetCoreModuleList(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::ExportAttackLogsOutcome CwpClient::ExportAttackLogs(const ExportAttackLogsRequest &request)
{
auto outcome = MakeRequest(request, "ExportAttackLogs");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
ExportAttackLogsResponse rsp = ExportAttackLogsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return ExportAttackLogsOutcome(rsp);
else
return ExportAttackLogsOutcome(o.GetError());
}
else
{
return ExportAttackLogsOutcome(outcome.GetError());
}
}
void CwpClient::ExportAttackLogsAsync(const ExportAttackLogsRequest& request, const ExportAttackLogsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->ExportAttackLogs(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::ExportAttackLogsOutcomeCallable CwpClient::ExportAttackLogsCallable(const ExportAttackLogsRequest &request)
{
auto task = std::make_shared<std::packaged_task<ExportAttackLogsOutcome()>>(
[this, request]()
{
return this->ExportAttackLogs(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::ExportBashEventsOutcome CwpClient::ExportBashEvents(const ExportBashEventsRequest &request)
{
auto outcome = MakeRequest(request, "ExportBashEvents");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
ExportBashEventsResponse rsp = ExportBashEventsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return ExportBashEventsOutcome(rsp);
else
return ExportBashEventsOutcome(o.GetError());
}
else
{
return ExportBashEventsOutcome(outcome.GetError());
}
}
void CwpClient::ExportBashEventsAsync(const ExportBashEventsRequest& request, const ExportBashEventsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->ExportBashEvents(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::ExportBashEventsOutcomeCallable CwpClient::ExportBashEventsCallable(const ExportBashEventsRequest &request)
{
auto task = std::make_shared<std::packaged_task<ExportBashEventsOutcome()>>(
[this, request]()
{
return this->ExportBashEvents(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::ExportBruteAttacksOutcome CwpClient::ExportBruteAttacks(const ExportBruteAttacksRequest &request)
{
auto outcome = MakeRequest(request, "ExportBruteAttacks");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
ExportBruteAttacksResponse rsp = ExportBruteAttacksResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return ExportBruteAttacksOutcome(rsp);
else
return ExportBruteAttacksOutcome(o.GetError());
}
else
{
return ExportBruteAttacksOutcome(outcome.GetError());
}
}
void CwpClient::ExportBruteAttacksAsync(const ExportBruteAttacksRequest& request, const ExportBruteAttacksAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->ExportBruteAttacks(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::ExportBruteAttacksOutcomeCallable CwpClient::ExportBruteAttacksCallable(const ExportBruteAttacksRequest &request)
{
auto task = std::make_shared<std::packaged_task<ExportBruteAttacksOutcome()>>(
[this, request]()
{
return this->ExportBruteAttacks(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::ExportMaliciousRequestsOutcome CwpClient::ExportMaliciousRequests(const ExportMaliciousRequestsRequest &request)
{
auto outcome = MakeRequest(request, "ExportMaliciousRequests");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
ExportMaliciousRequestsResponse rsp = ExportMaliciousRequestsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return ExportMaliciousRequestsOutcome(rsp);
else
return ExportMaliciousRequestsOutcome(o.GetError());
}
else
{
return ExportMaliciousRequestsOutcome(outcome.GetError());
}
}
void CwpClient::ExportMaliciousRequestsAsync(const ExportMaliciousRequestsRequest& request, const ExportMaliciousRequestsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->ExportMaliciousRequests(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::ExportMaliciousRequestsOutcomeCallable CwpClient::ExportMaliciousRequestsCallable(const ExportMaliciousRequestsRequest &request)
{
auto task = std::make_shared<std::packaged_task<ExportMaliciousRequestsOutcome()>>(
[this, request]()
{
return this->ExportMaliciousRequests(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::ExportMalwaresOutcome CwpClient::ExportMalwares(const ExportMalwaresRequest &request)
{
auto outcome = MakeRequest(request, "ExportMalwares");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
ExportMalwaresResponse rsp = ExportMalwaresResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return ExportMalwaresOutcome(rsp);
else
return ExportMalwaresOutcome(o.GetError());
}
else
{
return ExportMalwaresOutcome(outcome.GetError());
}
}
void CwpClient::ExportMalwaresAsync(const ExportMalwaresRequest& request, const ExportMalwaresAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->ExportMalwares(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::ExportMalwaresOutcomeCallable CwpClient::ExportMalwaresCallable(const ExportMalwaresRequest &request)
{
auto task = std::make_shared<std::packaged_task<ExportMalwaresOutcome()>>(
[this, request]()
{
return this->ExportMalwares(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::ExportNonlocalLoginPlacesOutcome CwpClient::ExportNonlocalLoginPlaces(const ExportNonlocalLoginPlacesRequest &request)
{
auto outcome = MakeRequest(request, "ExportNonlocalLoginPlaces");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
ExportNonlocalLoginPlacesResponse rsp = ExportNonlocalLoginPlacesResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return ExportNonlocalLoginPlacesOutcome(rsp);
else
return ExportNonlocalLoginPlacesOutcome(o.GetError());
}
else
{
return ExportNonlocalLoginPlacesOutcome(outcome.GetError());
}
}
void CwpClient::ExportNonlocalLoginPlacesAsync(const ExportNonlocalLoginPlacesRequest& request, const ExportNonlocalLoginPlacesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->ExportNonlocalLoginPlaces(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::ExportNonlocalLoginPlacesOutcomeCallable CwpClient::ExportNonlocalLoginPlacesCallable(const ExportNonlocalLoginPlacesRequest &request)
{
auto task = std::make_shared<std::packaged_task<ExportNonlocalLoginPlacesOutcome()>>(
[this, request]()
{
return this->ExportNonlocalLoginPlaces(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::ExportPrivilegeEventsOutcome CwpClient::ExportPrivilegeEvents(const ExportPrivilegeEventsRequest &request)
{
auto outcome = MakeRequest(request, "ExportPrivilegeEvents");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
ExportPrivilegeEventsResponse rsp = ExportPrivilegeEventsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return ExportPrivilegeEventsOutcome(rsp);
else
return ExportPrivilegeEventsOutcome(o.GetError());
}
else
{
return ExportPrivilegeEventsOutcome(outcome.GetError());
}
}
void CwpClient::ExportPrivilegeEventsAsync(const ExportPrivilegeEventsRequest& request, const ExportPrivilegeEventsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->ExportPrivilegeEvents(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::ExportPrivilegeEventsOutcomeCallable CwpClient::ExportPrivilegeEventsCallable(const ExportPrivilegeEventsRequest &request)
{
auto task = std::make_shared<std::packaged_task<ExportPrivilegeEventsOutcome()>>(
[this, request]()
{
return this->ExportPrivilegeEvents(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::ExportReverseShellEventsOutcome CwpClient::ExportReverseShellEvents(const ExportReverseShellEventsRequest &request)
{
auto outcome = MakeRequest(request, "ExportReverseShellEvents");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
ExportReverseShellEventsResponse rsp = ExportReverseShellEventsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return ExportReverseShellEventsOutcome(rsp);
else
return ExportReverseShellEventsOutcome(o.GetError());
}
else
{
return ExportReverseShellEventsOutcome(outcome.GetError());
}
}
void CwpClient::ExportReverseShellEventsAsync(const ExportReverseShellEventsRequest& request, const ExportReverseShellEventsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->ExportReverseShellEvents(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::ExportReverseShellEventsOutcomeCallable CwpClient::ExportReverseShellEventsCallable(const ExportReverseShellEventsRequest &request)
{
auto task = std::make_shared<std::packaged_task<ExportReverseShellEventsOutcome()>>(
[this, request]()
{
return this->ExportReverseShellEvents(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::ExportTasksOutcome CwpClient::ExportTasks(const ExportTasksRequest &request)
{
auto outcome = MakeRequest(request, "ExportTasks");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
ExportTasksResponse rsp = ExportTasksResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return ExportTasksOutcome(rsp);
else
return ExportTasksOutcome(o.GetError());
}
else
{
return ExportTasksOutcome(outcome.GetError());
}
}
void CwpClient::ExportTasksAsync(const ExportTasksRequest& request, const ExportTasksAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->ExportTasks(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::ExportTasksOutcomeCallable CwpClient::ExportTasksCallable(const ExportTasksRequest &request)
{
auto task = std::make_shared<std::packaged_task<ExportTasksOutcome()>>(
[this, request]()
{
return this->ExportTasks(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::ExportVulDetectionExcelOutcome CwpClient::ExportVulDetectionExcel(const ExportVulDetectionExcelRequest &request)
{
auto outcome = MakeRequest(request, "ExportVulDetectionExcel");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
ExportVulDetectionExcelResponse rsp = ExportVulDetectionExcelResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return ExportVulDetectionExcelOutcome(rsp);
else
return ExportVulDetectionExcelOutcome(o.GetError());
}
else
{
return ExportVulDetectionExcelOutcome(outcome.GetError());
}
}
void CwpClient::ExportVulDetectionExcelAsync(const ExportVulDetectionExcelRequest& request, const ExportVulDetectionExcelAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->ExportVulDetectionExcel(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::ExportVulDetectionExcelOutcomeCallable CwpClient::ExportVulDetectionExcelCallable(const ExportVulDetectionExcelRequest &request)
{
auto task = std::make_shared<std::packaged_task<ExportVulDetectionExcelOutcome()>>(
[this, request]()
{
return this->ExportVulDetectionExcel(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::ExportVulDetectionReportOutcome CwpClient::ExportVulDetectionReport(const ExportVulDetectionReportRequest &request)
{
auto outcome = MakeRequest(request, "ExportVulDetectionReport");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
ExportVulDetectionReportResponse rsp = ExportVulDetectionReportResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return ExportVulDetectionReportOutcome(rsp);
else
return ExportVulDetectionReportOutcome(o.GetError());
}
else
{
return ExportVulDetectionReportOutcome(outcome.GetError());
}
}
void CwpClient::ExportVulDetectionReportAsync(const ExportVulDetectionReportRequest& request, const ExportVulDetectionReportAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->ExportVulDetectionReport(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::ExportVulDetectionReportOutcomeCallable CwpClient::ExportVulDetectionReportCallable(const ExportVulDetectionReportRequest &request)
{
auto task = std::make_shared<std::packaged_task<ExportVulDetectionReportOutcome()>>(
[this, request]()
{
return this->ExportVulDetectionReport(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::IgnoreImpactedHostsOutcome CwpClient::IgnoreImpactedHosts(const IgnoreImpactedHostsRequest &request)
{
auto outcome = MakeRequest(request, "IgnoreImpactedHosts");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
IgnoreImpactedHostsResponse rsp = IgnoreImpactedHostsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return IgnoreImpactedHostsOutcome(rsp);
else
return IgnoreImpactedHostsOutcome(o.GetError());
}
else
{
return IgnoreImpactedHostsOutcome(outcome.GetError());
}
}
void CwpClient::IgnoreImpactedHostsAsync(const IgnoreImpactedHostsRequest& request, const IgnoreImpactedHostsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->IgnoreImpactedHosts(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::IgnoreImpactedHostsOutcomeCallable CwpClient::IgnoreImpactedHostsCallable(const IgnoreImpactedHostsRequest &request)
{
auto task = std::make_shared<std::packaged_task<IgnoreImpactedHostsOutcome()>>(
[this, request]()
{
return this->IgnoreImpactedHosts(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::InquiryPriceOpenProVersionPrepaidOutcome CwpClient::InquiryPriceOpenProVersionPrepaid(const InquiryPriceOpenProVersionPrepaidRequest &request)
{
auto outcome = MakeRequest(request, "InquiryPriceOpenProVersionPrepaid");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
InquiryPriceOpenProVersionPrepaidResponse rsp = InquiryPriceOpenProVersionPrepaidResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return InquiryPriceOpenProVersionPrepaidOutcome(rsp);
else
return InquiryPriceOpenProVersionPrepaidOutcome(o.GetError());
}
else
{
return InquiryPriceOpenProVersionPrepaidOutcome(outcome.GetError());
}
}
void CwpClient::InquiryPriceOpenProVersionPrepaidAsync(const InquiryPriceOpenProVersionPrepaidRequest& request, const InquiryPriceOpenProVersionPrepaidAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->InquiryPriceOpenProVersionPrepaid(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::InquiryPriceOpenProVersionPrepaidOutcomeCallable CwpClient::InquiryPriceOpenProVersionPrepaidCallable(const InquiryPriceOpenProVersionPrepaidRequest &request)
{
auto task = std::make_shared<std::packaged_task<InquiryPriceOpenProVersionPrepaidOutcome()>>(
[this, request]()
{
return this->InquiryPriceOpenProVersionPrepaid(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::MisAlarmNonlocalLoginPlacesOutcome CwpClient::MisAlarmNonlocalLoginPlaces(const MisAlarmNonlocalLoginPlacesRequest &request)
{
auto outcome = MakeRequest(request, "MisAlarmNonlocalLoginPlaces");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
MisAlarmNonlocalLoginPlacesResponse rsp = MisAlarmNonlocalLoginPlacesResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return MisAlarmNonlocalLoginPlacesOutcome(rsp);
else
return MisAlarmNonlocalLoginPlacesOutcome(o.GetError());
}
else
{
return MisAlarmNonlocalLoginPlacesOutcome(outcome.GetError());
}
}
void CwpClient::MisAlarmNonlocalLoginPlacesAsync(const MisAlarmNonlocalLoginPlacesRequest& request, const MisAlarmNonlocalLoginPlacesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->MisAlarmNonlocalLoginPlaces(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::MisAlarmNonlocalLoginPlacesOutcomeCallable CwpClient::MisAlarmNonlocalLoginPlacesCallable(const MisAlarmNonlocalLoginPlacesRequest &request)
{
auto task = std::make_shared<std::packaged_task<MisAlarmNonlocalLoginPlacesOutcome()>>(
[this, request]()
{
return this->MisAlarmNonlocalLoginPlaces(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::ModifyAlarmAttributeOutcome CwpClient::ModifyAlarmAttribute(const ModifyAlarmAttributeRequest &request)
{
auto outcome = MakeRequest(request, "ModifyAlarmAttribute");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
ModifyAlarmAttributeResponse rsp = ModifyAlarmAttributeResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return ModifyAlarmAttributeOutcome(rsp);
else
return ModifyAlarmAttributeOutcome(o.GetError());
}
else
{
return ModifyAlarmAttributeOutcome(outcome.GetError());
}
}
void CwpClient::ModifyAlarmAttributeAsync(const ModifyAlarmAttributeRequest& request, const ModifyAlarmAttributeAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->ModifyAlarmAttribute(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::ModifyAlarmAttributeOutcomeCallable CwpClient::ModifyAlarmAttributeCallable(const ModifyAlarmAttributeRequest &request)
{
auto task = std::make_shared<std::packaged_task<ModifyAlarmAttributeOutcome()>>(
[this, request]()
{
return this->ModifyAlarmAttribute(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::ModifyAutoOpenProVersionConfigOutcome CwpClient::ModifyAutoOpenProVersionConfig(const ModifyAutoOpenProVersionConfigRequest &request)
{
auto outcome = MakeRequest(request, "ModifyAutoOpenProVersionConfig");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
ModifyAutoOpenProVersionConfigResponse rsp = ModifyAutoOpenProVersionConfigResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return ModifyAutoOpenProVersionConfigOutcome(rsp);
else
return ModifyAutoOpenProVersionConfigOutcome(o.GetError());
}
else
{
return ModifyAutoOpenProVersionConfigOutcome(outcome.GetError());
}
}
void CwpClient::ModifyAutoOpenProVersionConfigAsync(const ModifyAutoOpenProVersionConfigRequest& request, const ModifyAutoOpenProVersionConfigAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->ModifyAutoOpenProVersionConfig(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::ModifyAutoOpenProVersionConfigOutcomeCallable CwpClient::ModifyAutoOpenProVersionConfigCallable(const ModifyAutoOpenProVersionConfigRequest &request)
{
auto task = std::make_shared<std::packaged_task<ModifyAutoOpenProVersionConfigOutcome()>>(
[this, request]()
{
return this->ModifyAutoOpenProVersionConfig(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::ModifyLoginWhiteListOutcome CwpClient::ModifyLoginWhiteList(const ModifyLoginWhiteListRequest &request)
{
auto outcome = MakeRequest(request, "ModifyLoginWhiteList");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
ModifyLoginWhiteListResponse rsp = ModifyLoginWhiteListResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return ModifyLoginWhiteListOutcome(rsp);
else
return ModifyLoginWhiteListOutcome(o.GetError());
}
else
{
return ModifyLoginWhiteListOutcome(outcome.GetError());
}
}
void CwpClient::ModifyLoginWhiteListAsync(const ModifyLoginWhiteListRequest& request, const ModifyLoginWhiteListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->ModifyLoginWhiteList(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::ModifyLoginWhiteListOutcomeCallable CwpClient::ModifyLoginWhiteListCallable(const ModifyLoginWhiteListRequest &request)
{
auto task = std::make_shared<std::packaged_task<ModifyLoginWhiteListOutcome()>>(
[this, request]()
{
return this->ModifyLoginWhiteList(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::ModifyMalwareTimingScanSettingsOutcome CwpClient::ModifyMalwareTimingScanSettings(const ModifyMalwareTimingScanSettingsRequest &request)
{
auto outcome = MakeRequest(request, "ModifyMalwareTimingScanSettings");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
ModifyMalwareTimingScanSettingsResponse rsp = ModifyMalwareTimingScanSettingsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return ModifyMalwareTimingScanSettingsOutcome(rsp);
else
return ModifyMalwareTimingScanSettingsOutcome(o.GetError());
}
else
{
return ModifyMalwareTimingScanSettingsOutcome(outcome.GetError());
}
}
void CwpClient::ModifyMalwareTimingScanSettingsAsync(const ModifyMalwareTimingScanSettingsRequest& request, const ModifyMalwareTimingScanSettingsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->ModifyMalwareTimingScanSettings(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::ModifyMalwareTimingScanSettingsOutcomeCallable CwpClient::ModifyMalwareTimingScanSettingsCallable(const ModifyMalwareTimingScanSettingsRequest &request)
{
auto task = std::make_shared<std::packaged_task<ModifyMalwareTimingScanSettingsOutcome()>>(
[this, request]()
{
return this->ModifyMalwareTimingScanSettings(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::ModifyProVersionRenewFlagOutcome CwpClient::ModifyProVersionRenewFlag(const ModifyProVersionRenewFlagRequest &request)
{
auto outcome = MakeRequest(request, "ModifyProVersionRenewFlag");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
ModifyProVersionRenewFlagResponse rsp = ModifyProVersionRenewFlagResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return ModifyProVersionRenewFlagOutcome(rsp);
else
return ModifyProVersionRenewFlagOutcome(o.GetError());
}
else
{
return ModifyProVersionRenewFlagOutcome(outcome.GetError());
}
}
void CwpClient::ModifyProVersionRenewFlagAsync(const ModifyProVersionRenewFlagRequest& request, const ModifyProVersionRenewFlagAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->ModifyProVersionRenewFlag(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::ModifyProVersionRenewFlagOutcomeCallable CwpClient::ModifyProVersionRenewFlagCallable(const ModifyProVersionRenewFlagRequest &request)
{
auto task = std::make_shared<std::packaged_task<ModifyProVersionRenewFlagOutcome()>>(
[this, request]()
{
return this->ModifyProVersionRenewFlag(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::ModifyWebPageProtectSettingOutcome CwpClient::ModifyWebPageProtectSetting(const ModifyWebPageProtectSettingRequest &request)
{
auto outcome = MakeRequest(request, "ModifyWebPageProtectSetting");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
ModifyWebPageProtectSettingResponse rsp = ModifyWebPageProtectSettingResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return ModifyWebPageProtectSettingOutcome(rsp);
else
return ModifyWebPageProtectSettingOutcome(o.GetError());
}
else
{
return ModifyWebPageProtectSettingOutcome(outcome.GetError());
}
}
void CwpClient::ModifyWebPageProtectSettingAsync(const ModifyWebPageProtectSettingRequest& request, const ModifyWebPageProtectSettingAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->ModifyWebPageProtectSetting(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::ModifyWebPageProtectSettingOutcomeCallable CwpClient::ModifyWebPageProtectSettingCallable(const ModifyWebPageProtectSettingRequest &request)
{
auto task = std::make_shared<std::packaged_task<ModifyWebPageProtectSettingOutcome()>>(
[this, request]()
{
return this->ModifyWebPageProtectSetting(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::OpenProVersionOutcome CwpClient::OpenProVersion(const OpenProVersionRequest &request)
{
auto outcome = MakeRequest(request, "OpenProVersion");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
OpenProVersionResponse rsp = OpenProVersionResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return OpenProVersionOutcome(rsp);
else
return OpenProVersionOutcome(o.GetError());
}
else
{
return OpenProVersionOutcome(outcome.GetError());
}
}
void CwpClient::OpenProVersionAsync(const OpenProVersionRequest& request, const OpenProVersionAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->OpenProVersion(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::OpenProVersionOutcomeCallable CwpClient::OpenProVersionCallable(const OpenProVersionRequest &request)
{
auto task = std::make_shared<std::packaged_task<OpenProVersionOutcome()>>(
[this, request]()
{
return this->OpenProVersion(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::OpenProVersionPrepaidOutcome CwpClient::OpenProVersionPrepaid(const OpenProVersionPrepaidRequest &request)
{
auto outcome = MakeRequest(request, "OpenProVersionPrepaid");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
OpenProVersionPrepaidResponse rsp = OpenProVersionPrepaidResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return OpenProVersionPrepaidOutcome(rsp);
else
return OpenProVersionPrepaidOutcome(o.GetError());
}
else
{
return OpenProVersionPrepaidOutcome(outcome.GetError());
}
}
void CwpClient::OpenProVersionPrepaidAsync(const OpenProVersionPrepaidRequest& request, const OpenProVersionPrepaidAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->OpenProVersionPrepaid(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::OpenProVersionPrepaidOutcomeCallable CwpClient::OpenProVersionPrepaidCallable(const OpenProVersionPrepaidRequest &request)
{
auto task = std::make_shared<std::packaged_task<OpenProVersionPrepaidOutcome()>>(
[this, request]()
{
return this->OpenProVersionPrepaid(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::RecoverMalwaresOutcome CwpClient::RecoverMalwares(const RecoverMalwaresRequest &request)
{
auto outcome = MakeRequest(request, "RecoverMalwares");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
RecoverMalwaresResponse rsp = RecoverMalwaresResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return RecoverMalwaresOutcome(rsp);
else
return RecoverMalwaresOutcome(o.GetError());
}
else
{
return RecoverMalwaresOutcome(outcome.GetError());
}
}
void CwpClient::RecoverMalwaresAsync(const RecoverMalwaresRequest& request, const RecoverMalwaresAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->RecoverMalwares(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::RecoverMalwaresOutcomeCallable CwpClient::RecoverMalwaresCallable(const RecoverMalwaresRequest &request)
{
auto task = std::make_shared<std::packaged_task<RecoverMalwaresOutcome()>>(
[this, request]()
{
return this->RecoverMalwares(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::RenewProVersionOutcome CwpClient::RenewProVersion(const RenewProVersionRequest &request)
{
auto outcome = MakeRequest(request, "RenewProVersion");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
RenewProVersionResponse rsp = RenewProVersionResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return RenewProVersionOutcome(rsp);
else
return RenewProVersionOutcome(o.GetError());
}
else
{
return RenewProVersionOutcome(outcome.GetError());
}
}
void CwpClient::RenewProVersionAsync(const RenewProVersionRequest& request, const RenewProVersionAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->RenewProVersion(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::RenewProVersionOutcomeCallable CwpClient::RenewProVersionCallable(const RenewProVersionRequest &request)
{
auto task = std::make_shared<std::packaged_task<RenewProVersionOutcome()>>(
[this, request]()
{
return this->RenewProVersion(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::RescanImpactedHostOutcome CwpClient::RescanImpactedHost(const RescanImpactedHostRequest &request)
{
auto outcome = MakeRequest(request, "RescanImpactedHost");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
RescanImpactedHostResponse rsp = RescanImpactedHostResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return RescanImpactedHostOutcome(rsp);
else
return RescanImpactedHostOutcome(o.GetError());
}
else
{
return RescanImpactedHostOutcome(outcome.GetError());
}
}
void CwpClient::RescanImpactedHostAsync(const RescanImpactedHostRequest& request, const RescanImpactedHostAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->RescanImpactedHost(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::RescanImpactedHostOutcomeCallable CwpClient::RescanImpactedHostCallable(const RescanImpactedHostRequest &request)
{
auto task = std::make_shared<std::packaged_task<RescanImpactedHostOutcome()>>(
[this, request]()
{
return this->RescanImpactedHost(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::ScanVulOutcome CwpClient::ScanVul(const ScanVulRequest &request)
{
auto outcome = MakeRequest(request, "ScanVul");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
ScanVulResponse rsp = ScanVulResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return ScanVulOutcome(rsp);
else
return ScanVulOutcome(o.GetError());
}
else
{
return ScanVulOutcome(outcome.GetError());
}
}
void CwpClient::ScanVulAsync(const ScanVulRequest& request, const ScanVulAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->ScanVul(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::ScanVulOutcomeCallable CwpClient::ScanVulCallable(const ScanVulRequest &request)
{
auto task = std::make_shared<std::packaged_task<ScanVulOutcome()>>(
[this, request]()
{
return this->ScanVul(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::SeparateMalwaresOutcome CwpClient::SeparateMalwares(const SeparateMalwaresRequest &request)
{
auto outcome = MakeRequest(request, "SeparateMalwares");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
SeparateMalwaresResponse rsp = SeparateMalwaresResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return SeparateMalwaresOutcome(rsp);
else
return SeparateMalwaresOutcome(o.GetError());
}
else
{
return SeparateMalwaresOutcome(outcome.GetError());
}
}
void CwpClient::SeparateMalwaresAsync(const SeparateMalwaresRequest& request, const SeparateMalwaresAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->SeparateMalwares(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::SeparateMalwaresOutcomeCallable CwpClient::SeparateMalwaresCallable(const SeparateMalwaresRequest &request)
{
auto task = std::make_shared<std::packaged_task<SeparateMalwaresOutcome()>>(
[this, request]()
{
return this->SeparateMalwares(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::SetBashEventsStatusOutcome CwpClient::SetBashEventsStatus(const SetBashEventsStatusRequest &request)
{
auto outcome = MakeRequest(request, "SetBashEventsStatus");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
SetBashEventsStatusResponse rsp = SetBashEventsStatusResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return SetBashEventsStatusOutcome(rsp);
else
return SetBashEventsStatusOutcome(o.GetError());
}
else
{
return SetBashEventsStatusOutcome(outcome.GetError());
}
}
void CwpClient::SetBashEventsStatusAsync(const SetBashEventsStatusRequest& request, const SetBashEventsStatusAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->SetBashEventsStatus(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::SetBashEventsStatusOutcomeCallable CwpClient::SetBashEventsStatusCallable(const SetBashEventsStatusRequest &request)
{
auto task = std::make_shared<std::packaged_task<SetBashEventsStatusOutcome()>>(
[this, request]()
{
return this->SetBashEventsStatus(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::SwitchBashRulesOutcome CwpClient::SwitchBashRules(const SwitchBashRulesRequest &request)
{
auto outcome = MakeRequest(request, "SwitchBashRules");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
SwitchBashRulesResponse rsp = SwitchBashRulesResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return SwitchBashRulesOutcome(rsp);
else
return SwitchBashRulesOutcome(o.GetError());
}
else
{
return SwitchBashRulesOutcome(outcome.GetError());
}
}
void CwpClient::SwitchBashRulesAsync(const SwitchBashRulesRequest& request, const SwitchBashRulesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->SwitchBashRules(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::SwitchBashRulesOutcomeCallable CwpClient::SwitchBashRulesCallable(const SwitchBashRulesRequest &request)
{
auto task = std::make_shared<std::packaged_task<SwitchBashRulesOutcome()>>(
[this, request]()
{
return this->SwitchBashRules(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::SyncAssetScanOutcome CwpClient::SyncAssetScan(const SyncAssetScanRequest &request)
{
auto outcome = MakeRequest(request, "SyncAssetScan");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
SyncAssetScanResponse rsp = SyncAssetScanResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return SyncAssetScanOutcome(rsp);
else
return SyncAssetScanOutcome(o.GetError());
}
else
{
return SyncAssetScanOutcome(outcome.GetError());
}
}
void CwpClient::SyncAssetScanAsync(const SyncAssetScanRequest& request, const SyncAssetScanAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->SyncAssetScan(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::SyncAssetScanOutcomeCallable CwpClient::SyncAssetScanCallable(const SyncAssetScanRequest &request)
{
auto task = std::make_shared<std::packaged_task<SyncAssetScanOutcome()>>(
[this, request]()
{
return this->SyncAssetScan(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::TrustMaliciousRequestOutcome CwpClient::TrustMaliciousRequest(const TrustMaliciousRequestRequest &request)
{
auto outcome = MakeRequest(request, "TrustMaliciousRequest");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
TrustMaliciousRequestResponse rsp = TrustMaliciousRequestResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return TrustMaliciousRequestOutcome(rsp);
else
return TrustMaliciousRequestOutcome(o.GetError());
}
else
{
return TrustMaliciousRequestOutcome(outcome.GetError());
}
}
void CwpClient::TrustMaliciousRequestAsync(const TrustMaliciousRequestRequest& request, const TrustMaliciousRequestAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->TrustMaliciousRequest(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::TrustMaliciousRequestOutcomeCallable CwpClient::TrustMaliciousRequestCallable(const TrustMaliciousRequestRequest &request)
{
auto task = std::make_shared<std::packaged_task<TrustMaliciousRequestOutcome()>>(
[this, request]()
{
return this->TrustMaliciousRequest(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::TrustMalwaresOutcome CwpClient::TrustMalwares(const TrustMalwaresRequest &request)
{
auto outcome = MakeRequest(request, "TrustMalwares");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
TrustMalwaresResponse rsp = TrustMalwaresResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return TrustMalwaresOutcome(rsp);
else
return TrustMalwaresOutcome(o.GetError());
}
else
{
return TrustMalwaresOutcome(outcome.GetError());
}
}
void CwpClient::TrustMalwaresAsync(const TrustMalwaresRequest& request, const TrustMalwaresAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->TrustMalwares(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::TrustMalwaresOutcomeCallable CwpClient::TrustMalwaresCallable(const TrustMalwaresRequest &request)
{
auto task = std::make_shared<std::packaged_task<TrustMalwaresOutcome()>>(
[this, request]()
{
return this->TrustMalwares(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::UntrustMaliciousRequestOutcome CwpClient::UntrustMaliciousRequest(const UntrustMaliciousRequestRequest &request)
{
auto outcome = MakeRequest(request, "UntrustMaliciousRequest");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
UntrustMaliciousRequestResponse rsp = UntrustMaliciousRequestResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return UntrustMaliciousRequestOutcome(rsp);
else
return UntrustMaliciousRequestOutcome(o.GetError());
}
else
{
return UntrustMaliciousRequestOutcome(outcome.GetError());
}
}
void CwpClient::UntrustMaliciousRequestAsync(const UntrustMaliciousRequestRequest& request, const UntrustMaliciousRequestAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->UntrustMaliciousRequest(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::UntrustMaliciousRequestOutcomeCallable CwpClient::UntrustMaliciousRequestCallable(const UntrustMaliciousRequestRequest &request)
{
auto task = std::make_shared<std::packaged_task<UntrustMaliciousRequestOutcome()>>(
[this, request]()
{
return this->UntrustMaliciousRequest(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::UntrustMalwaresOutcome CwpClient::UntrustMalwares(const UntrustMalwaresRequest &request)
{
auto outcome = MakeRequest(request, "UntrustMalwares");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
UntrustMalwaresResponse rsp = UntrustMalwaresResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return UntrustMalwaresOutcome(rsp);
else
return UntrustMalwaresOutcome(o.GetError());
}
else
{
return UntrustMalwaresOutcome(outcome.GetError());
}
}
void CwpClient::UntrustMalwaresAsync(const UntrustMalwaresRequest& request, const UntrustMalwaresAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->UntrustMalwares(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::UntrustMalwaresOutcomeCallable CwpClient::UntrustMalwaresCallable(const UntrustMalwaresRequest &request)
{
auto task = std::make_shared<std::packaged_task<UntrustMalwaresOutcome()>>(
[this, request]()
{
return this->UntrustMalwares(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
CwpClient::UpdateBaselineStrategyOutcome CwpClient::UpdateBaselineStrategy(const UpdateBaselineStrategyRequest &request)
{
auto outcome = MakeRequest(request, "UpdateBaselineStrategy");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
UpdateBaselineStrategyResponse rsp = UpdateBaselineStrategyResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return UpdateBaselineStrategyOutcome(rsp);
else
return UpdateBaselineStrategyOutcome(o.GetError());
}
else
{
return UpdateBaselineStrategyOutcome(outcome.GetError());
}
}
void CwpClient::UpdateBaselineStrategyAsync(const UpdateBaselineStrategyRequest& request, const UpdateBaselineStrategyAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->UpdateBaselineStrategy(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
CwpClient::UpdateBaselineStrategyOutcomeCallable CwpClient::UpdateBaselineStrategyCallable(const UpdateBaselineStrategyRequest &request)
{
auto task = std::make_shared<std::packaged_task<UpdateBaselineStrategyOutcome()>>(
[this, request]()
{
return this->UpdateBaselineStrategy(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
| 35.323728 | 249 | 0.694491 | [
"model"
] |
f1733f7b11796d402650d76dd31ee466f249ad52 | 33,115 | cxx | C++ | main/sw/source/core/undo/undel.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/sw/source/core/undo/undel.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/sw/source/core/undo/undel.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.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.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#include <UndoDelete.hxx>
#include <hintids.hxx>
#include <unotools/charclass.hxx>
#include <editeng/brkitem.hxx>
#include <fmtpdsc.hxx>
#include <frmfmt.hxx>
#include <fmtanchr.hxx>
#include <doc.hxx>
#include <UndoManager.hxx>
#include <swtable.hxx>
#include <swundo.hxx> // fuer die UndoIds
#include <pam.hxx>
#include <ndtxt.hxx>
#include <UndoCore.hxx>
#include <rolbck.hxx>
#include <poolfmt.hxx>
#include <mvsave.hxx>
#include <redline.hxx>
#include <docary.hxx>
#include <sfx2/app.hxx>
#include <fldbas.hxx>
#include <fmtfld.hxx>
#include <comcore.hrc> // #111827#
#include <undo.hrc>
// #include <editeng/svxacorr.hxx>
// #include <comphelper/processfactory.hxx>
// #include <editeng/unolingu.hxx>
// #include <unotools/localedatawrapper.hxx>
// using namespace comphelper;
// DELETE
/* lcl_MakeAutoFrms has to call MakeFrms for objects bounded "AtChar" ( == AUTO ),
if the anchor frame has be moved via _MoveNodes(..) and DelFrms(..)
*/
void lcl_MakeAutoFrms( const SwSpzFrmFmts& rSpzArr, sal_uLong nMovedIndex )
{
if( rSpzArr.Count() )
{
SwFlyFrmFmt* pFmt;
const SwFmtAnchor* pAnchor;
for( sal_uInt16 n = 0; n < rSpzArr.Count(); ++n )
{
pFmt = (SwFlyFrmFmt*)rSpzArr[n];
pAnchor = &pFmt->GetAnchor();
if (pAnchor->GetAnchorId() == FLY_AT_CHAR)
{
const SwPosition* pAPos = pAnchor->GetCntntAnchor();
if( pAPos && nMovedIndex == pAPos->nNode.GetIndex() )
pFmt->MakeFrms();
}
}
}
}
/*
SwUndoDelete has to perform a deletion and to record anything that is needed to restore the
situation before the deletion. Unfortunately a part of the deletion will be done after calling
this Ctor, this has to be kept in mind! In this Ctor only the complete paragraphs will be deleted,
the joining of the first and last paragraph of the selection will be handled outside this function.
Here are the main steps of the function:
1. Deletion/recording of content indizes of the selection: footnotes, fly frames and bookmarks
Step 1 could shift all nodes by deletion of footnotes => nNdDiff will be set.
2. If the paragraph where the selection ends, is the last content of a section so that this
section becomes empty when the paragraphs will be joined we have to do some smart actions ;-)
The paragraph will be moved outside the section and replaced by a dummy text node, the complete
section will be deleted in step 3. The difference between replacement dummy and original is
nReplacementDummy.
3. Moving complete selected nodes into the UndoArray. Before this happens the selection has to be
extended if there are sections which would become empty otherwise. BTW: sections will be moved into
the UndoArray if they are complete part of the selection. Sections starting or ending outside of the
selection will not be removed from the DocNodeArray even they got a "dummy"-copy in the UndoArray.
4. We have to anticipate the joining of the two paragraphs if the start paragraph is inside a
section and the end paragraph not. Then we have to move the paragraph into this section and to
record this in nSectDiff.
*/
SwUndoDelete::SwUndoDelete(
SwPaM& rPam,
sal_Bool bFullPara,
sal_Bool bCalledByTblCpy )
: SwUndo(UNDO_DELETE)
, SwUndRng( rPam )
, pMvStt( 0 )
, pSttStr(0)
, pEndStr(0)
, pRedlData(0)
, pRedlSaveData(0)
, nNode(0)
, nNdDiff(0)
, nSectDiff(0)
, nReplaceDummy(0)
, nSetPos(0)
, bGroup( sal_False )
, bBackSp( sal_False )
, bJoinNext( sal_False )
, bTblDelLastNd( sal_False )
, bDelFullPara( bFullPara )
, bResetPgDesc( sal_False )
, bResetPgBrk( sal_False )
, bFromTableCopy( bCalledByTblCpy )
{
bDelFullPara = bFullPara; // This is set e.g. if an empty paragraph before a table is deleted
bCacheComment = false;
SwDoc * pDoc = rPam.GetDoc();
if( !pDoc->IsIgnoreRedline() && pDoc->GetRedlineTbl().Count() )
{
pRedlSaveData = new SwRedlineSaveDatas;
if( !FillSaveData( rPam, *pRedlSaveData ))
delete pRedlSaveData, pRedlSaveData = 0;
}
if( !pHistory )
pHistory = new SwHistory;
// loesche erstmal alle Fussnoten
const SwPosition *pStt = rPam.Start(),
*pEnd = rPam.GetPoint() == pStt
? rPam.GetMark()
: rPam.GetPoint();
// Step 1. deletion/record of content indizes
if( bDelFullPara )
{
ASSERT( rPam.HasMark(), "PaM ohne Mark" );
DelCntntIndex( *rPam.GetMark(), *rPam.GetPoint(),
DelCntntType(nsDelCntntType::DELCNT_ALL | nsDelCntntType::DELCNT_CHKNOCNTNT) );
::sw::UndoGuard const undoGuard(pDoc->GetIDocumentUndoRedo());
_DelBookmarks(pStt->nNode, pEnd->nNode);
}
else
DelCntntIndex( *rPam.GetMark(), *rPam.GetPoint() );
nSetPos = pHistory ? pHistory->Count() : 0;
// wurde schon was geloescht ??
nNdDiff = nSttNode - pStt->nNode.GetIndex();
bJoinNext = !bFullPara && pEnd == rPam.GetPoint();
bBackSp = !bFullPara && !bJoinNext;
SwTxtNode *pSttTxtNd = 0, *pEndTxtNd = 0;
if( !bFullPara )
{
pSttTxtNd = pStt->nNode.GetNode().GetTxtNode();
pEndTxtNd = nSttNode == nEndNode
? pSttTxtNd
: pEnd->nNode.GetNode().GetTxtNode();
}
sal_Bool bMoveNds = *pStt == *pEnd // noch ein Bereich vorhanden ??
? sal_False
: ( SaveCntnt( pStt, pEnd, pSttTxtNd, pEndTxtNd ) || bFromTableCopy );
if( pSttTxtNd && pEndTxtNd && pSttTxtNd != pEndTxtNd )
{
// zwei unterschiedliche TextNodes, also speicher noch die
// TextFormatCollection fuers
pHistory->Add( pSttTxtNd->GetTxtColl(),pStt->nNode.GetIndex(), ND_TEXTNODE );
pHistory->Add( pEndTxtNd->GetTxtColl(),pEnd->nNode.GetIndex(), ND_TEXTNODE );
if( !bJoinNext ) // Selection von Unten nach Oben
{
// Beim JoinPrev() werden die AUTO-PageBreak's richtig
// kopiert. Um diese beim Undo wieder herzustellen, muss das
// Auto-PageBreak aus dem EndNode zurueckgesetzt werden.
// - fuer die PageDesc, ColBreak dito !
if( pEndTxtNd->HasSwAttrSet() )
{
SwRegHistory aRegHist( *pEndTxtNd, pHistory );
if( SFX_ITEM_SET == pEndTxtNd->GetpSwAttrSet()->GetItemState(
RES_BREAK, sal_False ) )
pEndTxtNd->ResetAttr( RES_BREAK );
if( pEndTxtNd->HasSwAttrSet() &&
SFX_ITEM_SET == pEndTxtNd->GetpSwAttrSet()->GetItemState(
RES_PAGEDESC, sal_False ) )
pEndTxtNd->ResetAttr( RES_PAGEDESC );
}
}
}
// verschiebe jetzt noch den PaM !!!
// der SPoint steht am Anfang der SSelection
if( pEnd == rPam.GetPoint() && ( !bFullPara || pSttTxtNd || pEndTxtNd ) )
rPam.Exchange();
if( !pSttTxtNd && !pEndTxtNd )
rPam.GetPoint()->nNode--;
rPam.DeleteMark(); // der SPoint ist aus dem Bereich
if( !pEndTxtNd )
nEndCntnt = 0;
if( !pSttTxtNd )
nSttCntnt = 0;
if( bMoveNds ) // sind noch Nodes zu verschieben ?
{
SwNodes& rNds = pDoc->GetUndoManager().GetUndoNodes();
SwNodes& rDocNds = pDoc->GetNodes();
SwNodeRange aRg( rDocNds, nSttNode - nNdDiff,
rDocNds, nEndNode - nNdDiff );
if( !bFullPara && !pEndTxtNd &&
&aRg.aEnd.GetNode() != &pDoc->GetNodes().GetEndOfContent() )
{
SwNode* pNode = aRg.aEnd.GetNode().StartOfSectionNode();
if( pNode->GetIndex() >= nSttNode - nNdDiff )
aRg.aEnd++; // Deletion of a complete table
}
SwNode* pTmpNd;
// Step 2: Expand selection if necessary
if( bJoinNext || bFullPara )
{
// If all content of a section will be moved into Undo,
// the section itself should be moved complete.
while( aRg.aEnd.GetIndex() + 2 < rDocNds.Count() &&
( (pTmpNd = rDocNds[ aRg.aEnd.GetIndex()+1 ])->IsEndNode() &&
pTmpNd->StartOfSectionNode()->IsSectionNode() &&
pTmpNd->StartOfSectionNode()->GetIndex() >= aRg.aStart.GetIndex() ) )
aRg.aEnd++;
nReplaceDummy = aRg.aEnd.GetIndex() + nNdDiff - nEndNode;
if( nReplaceDummy )
{ // The selection has been expanded, because
aRg.aEnd++;
if( pEndTxtNd )
{
// The end text node has to leave the (expanded) selection
// The dummy is needed because _MoveNodes deletes empty sections
++nReplaceDummy;
SwNodeRange aMvRg( *pEndTxtNd, 0, *pEndTxtNd, 1 );
SwPosition aSplitPos( *pEndTxtNd );
::sw::UndoGuard const ug(pDoc->GetIDocumentUndoRedo());
pDoc->SplitNode( aSplitPos, false );
rDocNds._MoveNodes( aMvRg, rDocNds, aRg.aEnd, sal_True );
aRg.aEnd--;
}
else
nReplaceDummy = 0;
}
}
if( bBackSp || bFullPara )
{
//See above, the selection has to expanded if there are "nearly empty" sections
// and a replacement dummy has to be set if needed.
while( 1 < aRg.aStart.GetIndex() &&
( (pTmpNd = rDocNds[ aRg.aStart.GetIndex()-1 ])->IsSectionNode() &&
pTmpNd->EndOfSectionIndex() < aRg.aEnd.GetIndex() ) )
aRg.aStart--;
if( pSttTxtNd )
{
nReplaceDummy = nSttNode - nNdDiff - aRg.aStart.GetIndex();
if( nReplaceDummy )
{
SwNodeRange aMvRg( *pSttTxtNd, 0, *pSttTxtNd, 1 );
SwPosition aSplitPos( *pSttTxtNd );
::sw::UndoGuard const ug(pDoc->GetIDocumentUndoRedo());
pDoc->SplitNode( aSplitPos, false );
rDocNds._MoveNodes( aMvRg, rDocNds, aRg.aStart, sal_True );
aRg.aStart--;
}
}
}
if( bFromTableCopy )
{
if( !pEndTxtNd )
{
if( pSttTxtNd )
aRg.aStart++;
else if( !bFullPara && !aRg.aEnd.GetNode().IsCntntNode() )
aRg.aEnd--;
}
}
else if( pSttTxtNd && ( pEndTxtNd || pSttTxtNd->GetTxt().Len() ) )
aRg.aStart++;
// Step 3: Moving into UndoArray...
nNode = rNds.GetEndOfContent().GetIndex();
rDocNds._MoveNodes( aRg, rNds, SwNodeIndex( rNds.GetEndOfContent() ));
pMvStt = new SwNodeIndex( rNds, nNode );
nNode = rNds.GetEndOfContent().GetIndex() - nNode; // Differenz merken !
if( pSttTxtNd && pEndTxtNd )
{
//Step 4: Moving around sections
nSectDiff = aRg.aEnd.GetIndex() - aRg.aStart.GetIndex();
// nSect is the number of sections which starts(ends) between start and end node of the
// selection. The "loser" paragraph has to be moved into the section(s) of the
// "winner" paragraph
if( nSectDiff )
{
if( bJoinNext )
{
SwNodeRange aMvRg( *pEndTxtNd, 0, *pEndTxtNd, 1 );
rDocNds._MoveNodes( aMvRg, rDocNds, aRg.aStart, sal_True );
}
else
{
SwNodeRange aMvRg( *pSttTxtNd, 0, *pSttTxtNd, 1 );
rDocNds._MoveNodes( aMvRg, rDocNds, aRg.aEnd, sal_True );
}
}
}
if( nSectDiff || nReplaceDummy )
lcl_MakeAutoFrms( *pDoc->GetSpzFrmFmts(),
bJoinNext ? pEndTxtNd->GetIndex() : pSttTxtNd->GetIndex() );
}
else
nNode = 0; // kein Node verschoben -> keine Differenz zum Ende
// wurden davor noch Nodes geloescht ?? (FootNotes haben ContentNodes!)
if( !pSttTxtNd && !pEndTxtNd )
{
nNdDiff = nSttNode - rPam.GetPoint()->nNode.GetIndex() - (bFullPara ? 0 : 1);
rPam.Move( fnMoveForward, fnGoNode );
}
else
{
nNdDiff = nSttNode;
if( nSectDiff && bBackSp )
nNdDiff += nSectDiff;
nNdDiff -= rPam.GetPoint()->nNode.GetIndex();
}
if( !rPam.GetNode()->IsCntntNode() )
rPam.GetPoint()->nContent.Assign( 0, 0 );
// wird die History ueberhaupt benoetigt ??
if( pHistory && !pHistory->Count() )
DELETEZ( pHistory );
}
sal_Bool SwUndoDelete::SaveCntnt( const SwPosition* pStt, const SwPosition* pEnd,
SwTxtNode* pSttTxtNd, SwTxtNode* pEndTxtNd )
{
sal_uLong nNdIdx = pStt->nNode.GetIndex();
// 1 - kopiere den Anfang in den Start-String
if( pSttTxtNd )
{
sal_Bool bOneNode = nSttNode == nEndNode;
xub_StrLen nLen = bOneNode ? nEndCntnt - nSttCntnt
: pSttTxtNd->GetTxt().Len() - nSttCntnt;
SwRegHistory aRHst( *pSttTxtNd, pHistory );
// always save all text atttibutes because of possibly overlapping
// areas of on/off
pHistory->CopyAttr( pSttTxtNd->GetpSwpHints(), nNdIdx,
0, pSttTxtNd->GetTxt().Len(), true );
if( !bOneNode && pSttTxtNd->HasSwAttrSet() )
pHistory->CopyFmtAttr( *pSttTxtNd->GetpSwAttrSet(), nNdIdx );
// die Laenge kann sich veraendert haben (!!Felder!!)
nLen = ( bOneNode ? pEnd->nContent.GetIndex() : pSttTxtNd->GetTxt().Len() )
- pStt->nContent.GetIndex();
// loesche jetzt noch den Text (alle Attribut-Aenderungen kommen in
// die Undo-History
pSttStr = (String*)new String( pSttTxtNd->GetTxt().Copy( nSttCntnt, nLen ));
pSttTxtNd->EraseText( pStt->nContent, nLen );
if( pSttTxtNd->GetpSwpHints() )
pSttTxtNd->GetpSwpHints()->DeRegister();
// METADATA: store
bool emptied( pSttStr->Len() && !pSttTxtNd->Len() );
if (!bOneNode || emptied) // merging may overwrite xmlids...
{
m_pMetadataUndoStart = (emptied)
? pSttTxtNd->CreateUndoForDelete()
: pSttTxtNd->CreateUndo();
}
if( bOneNode )
return sal_False; // keine Nodes mehr verschieben
}
// 2 - kopiere das Ende in den End-String
if( pEndTxtNd )
{
SwIndex aEndIdx( pEndTxtNd );
nNdIdx = pEnd->nNode.GetIndex();
SwRegHistory aRHst( *pEndTxtNd, pHistory );
// always save all text atttibutes because of possibly overlapping
// areas of on/off
pHistory->CopyAttr( pEndTxtNd->GetpSwpHints(), nNdIdx, 0,
pEndTxtNd->GetTxt().Len(), true );
if( pEndTxtNd->HasSwAttrSet() )
pHistory->CopyFmtAttr( *pEndTxtNd->GetpSwAttrSet(), nNdIdx );
// loesche jetzt noch den Text (alle Attribut-Aenderungen kommen in
// die Undo-History
pEndStr = (String*)new String( pEndTxtNd->GetTxt().Copy( 0,
pEnd->nContent.GetIndex() ));
pEndTxtNd->EraseText( aEndIdx, pEnd->nContent.GetIndex() );
if( pEndTxtNd->GetpSwpHints() )
pEndTxtNd->GetpSwpHints()->DeRegister();
// METADATA: store
bool emptied( pEndStr->Len() && !pEndTxtNd->Len() );
m_pMetadataUndoEnd = (emptied)
? pEndTxtNd->CreateUndoForDelete()
: pEndTxtNd->CreateUndo();
}
// sind es nur zwei Nodes, dann ist schon alles erledigt.
if( ( pSttTxtNd || pEndTxtNd ) && nSttNode + 1 == nEndNode )
return sal_False; // keine Nodes mehr verschieben
return sal_True; // verschiebe die dazwischen liegenden Nodes
}
sal_Bool SwUndoDelete::CanGrouping( SwDoc* pDoc, const SwPaM& rDelPam )
{
// ist das Undo groesser als 1 Node ? (sprich: Start und EndString)
if( pSttStr ? !pSttStr->Len() || pEndStr : sal_True )
return sal_False;
// es kann nur das Loeschen von einzelnen char's zusammengefasst werden
if( nSttNode != nEndNode || ( !bGroup && nSttCntnt+1 != nEndCntnt ))
return sal_False;
const SwPosition *pStt = rDelPam.Start(),
*pEnd = rDelPam.GetPoint() == pStt
? rDelPam.GetMark()
: rDelPam.GetPoint();
if( pStt->nNode != pEnd->nNode ||
pStt->nContent.GetIndex()+1 != pEnd->nContent.GetIndex() ||
pEnd->nNode != nSttNode )
return sal_False;
// untercheide zwischen BackSpace und Delete. Es muss dann das
// Undo-Array unterschiedlich aufgebaut werden !!
if( pEnd->nContent == nSttCntnt )
{
if( bGroup && !bBackSp ) return sal_False;
bBackSp = sal_True;
}
else if( pStt->nContent == nSttCntnt )
{
if( bGroup && bBackSp ) return sal_False;
bBackSp = sal_False;
}
else
return sal_False;
// sind die beiden Nodes (Nodes-/Undo-Array) ueberhaupt TextNodes?
SwTxtNode * pDelTxtNd = pStt->nNode.GetNode().GetTxtNode();
if( !pDelTxtNd ) return sal_False;
xub_StrLen nUChrPos = bBackSp ? 0 : pSttStr->Len()-1;
sal_Unicode cDelChar = pDelTxtNd->GetTxt().GetChar( pStt->nContent.GetIndex() );
CharClass& rCC = GetAppCharClass();
if( ( CH_TXTATR_BREAKWORD == cDelChar || CH_TXTATR_INWORD == cDelChar ) ||
rCC.isLetterNumeric( String( cDelChar ), 0 ) !=
rCC.isLetterNumeric( *pSttStr, nUChrPos ) )
return sal_False;
{
SwRedlineSaveDatas* pTmpSav = new SwRedlineSaveDatas;
if( !FillSaveData( rDelPam, *pTmpSav, sal_False ))
delete pTmpSav, pTmpSav = 0;
sal_Bool bOk = ( !pRedlSaveData && !pTmpSav ) ||
( pRedlSaveData && pTmpSav &&
SwUndo::CanRedlineGroup( *pRedlSaveData, *pTmpSav, bBackSp ));
delete pTmpSav;
if( !bOk )
return sal_False;
pDoc->DeleteRedline( rDelPam, false, USHRT_MAX );
}
// Ok, die beiden 'Deletes' koennen zusammen gefasst werden, also
// 'verschiebe' das enstprechende Zeichen
if( bBackSp )
nSttCntnt--; // BackSpace: Zeichen in Array einfuegen !!
else
{
nEndCntnt++; // Delete: Zeichen am Ende anhaengen
nUChrPos++;
}
pSttStr->Insert( cDelChar, nUChrPos );
pDelTxtNd->EraseText( pStt->nContent, 1 );
bGroup = sal_True;
return sal_True;
}
SwUndoDelete::~SwUndoDelete()
{
delete pSttStr;
delete pEndStr;
if( pMvStt ) // loesche noch den Bereich aus dem UndoNodes Array
{
// Insert speichert den Inhalt in der IconSection
pMvStt->GetNode().GetNodes().Delete( *pMvStt, nNode );
delete pMvStt;
}
delete pRedlData;
delete pRedlSaveData;
}
static SwRewriter lcl_RewriterFromHistory(SwHistory & rHistory)
{
SwRewriter aRewriter;
bool bDone = false;
for ( sal_uInt16 n = 0; n < rHistory.Count(); n++)
{
String aDescr = rHistory[n]->GetDescription();
if (aDescr.Len() > 0)
{
aRewriter.AddRule(UNDO_ARG2, aDescr);
bDone = true;
break;
}
}
if (! bDone)
{
aRewriter.AddRule(UNDO_ARG2, SW_RES(STR_FIELD));
}
return aRewriter;
}
SwRewriter SwUndoDelete::GetRewriter() const
{
SwRewriter aResult;
String * pStr = NULL;
if (nNode != 0)
{
if (sTableName.Len() > 0)
{
SwRewriter aRewriter;
aRewriter.AddRule(UNDO_ARG1, SW_RES(STR_START_QUOTE));
aRewriter.AddRule(UNDO_ARG2, sTableName);
aRewriter.AddRule(UNDO_ARG3, SW_RES(STR_END_QUOTE));
String sTmp = aRewriter.Apply(SW_RES(STR_TABLE_NAME));
aResult.AddRule(UNDO_ARG1, sTmp);
}
else
aResult.AddRule(UNDO_ARG1, String(SW_RES(STR_PARAGRAPHS)));
}
else
{
String aStr;
if (pSttStr != NULL && pEndStr != NULL && pSttStr->Len() == 0 &&
pEndStr->Len() == 0)
{
aStr = SW_RES(STR_PARAGRAPH_UNDO);
}
else
{
if (pSttStr != NULL)
pStr = pSttStr;
else if (pEndStr != NULL)
pStr = pEndStr;
if (pStr != NULL)
{
aStr = DenoteSpecialCharacters(*pStr);
}
else
{
aStr = UNDO_ARG2;
}
}
aStr = ShortenString(aStr, nUndoStringLength, String(SW_RES(STR_LDOTS)));
if (pHistory)
{
SwRewriter aRewriter = lcl_RewriterFromHistory(*pHistory);
aStr = aRewriter.Apply(aStr);
}
aResult.AddRule(UNDO_ARG1, aStr);
}
return aResult;
}
// Every object, anchored "AtCntnt" will be reanchored at rPos
void lcl_ReAnchorAtCntntFlyFrames( const SwSpzFrmFmts& rSpzArr, SwPosition &rPos, sal_uLong nOldIdx )
{
if( rSpzArr.Count() )
{
SwFlyFrmFmt* pFmt;
const SwFmtAnchor* pAnchor;
const SwPosition* pAPos;
for( sal_uInt16 n = 0; n < rSpzArr.Count(); ++n )
{
pFmt = (SwFlyFrmFmt*)rSpzArr[n];
pAnchor = &pFmt->GetAnchor();
if (pAnchor->GetAnchorId() == FLY_AT_PARA)
{
pAPos = pAnchor->GetCntntAnchor();
if( pAPos && nOldIdx == pAPos->nNode.GetIndex() )
{
SwFmtAnchor aAnch( *pAnchor );
aAnch.SetAnchor( &rPos );
pFmt->SetFmtAttr( aAnch );
}
}
}
}
}
void SwUndoDelete::UndoImpl(::sw::UndoRedoContext & rContext)
{
SwDoc *const pDoc = & rContext.GetDoc();
sal_uLong nCalcStt = nSttNode - nNdDiff;
if( nSectDiff && bBackSp )
nCalcStt += nSectDiff;
SwNodeIndex aIdx( pDoc->GetNodes(), nCalcStt );
SwNode* pInsNd = &aIdx.GetNode();
{ // Block, damit der SwPosition beim loeschen vom Node
// abgemeldet ist
SwPosition aPos( aIdx );
if( !bDelFullPara )
{
if( pInsNd->IsTableNode() )
{
pInsNd = pDoc->GetNodes().MakeTxtNode( aIdx,
(SwTxtFmtColl*)pDoc->GetDfltTxtFmtColl() );
aIdx--;
aPos.nNode = aIdx;
aPos.nContent.Assign( pInsNd->GetCntntNode(), nSttCntnt );
}
else
{
if( pInsNd->IsCntntNode() )
aPos.nContent.Assign( (SwCntntNode*)pInsNd, nSttCntnt );
if( !bTblDelLastNd )
pInsNd = 0; // Node nicht loeschen !!
}
}
else
pInsNd = 0; // Node nicht loeschen !!
sal_Bool bNodeMove = 0 != nNode;
if( pEndStr )
{
// alle Attribute verwerfen, wurden alle gespeichert!
SwTxtNode* pTxtNd = aPos.nNode.GetNode().GetTxtNode();
if( pTxtNd && pTxtNd->HasSwAttrSet() )
pTxtNd->ResetAllAttr();
if( pTxtNd && pTxtNd->GetpSwpHints() )
pTxtNd->ClearSwpHintsArr( true );
if( pSttStr && !bFromTableCopy )
{
sal_uLong nOldIdx = aPos.nNode.GetIndex();
pDoc->SplitNode( aPos, false );
// After the split all objects are anchored at the first paragraph,
// but the pHistory of the fly frame formats relies on anchoring at
// the start of the selection => selection backwards needs a correction.
if( bBackSp )
lcl_ReAnchorAtCntntFlyFrames( *pDoc->GetSpzFrmFmts(), aPos, nOldIdx );
pTxtNd = aPos.nNode.GetNode().GetTxtNode();
}
if( pTxtNd )
{
pTxtNd->InsertText( *pEndStr, aPos.nContent,
IDocumentContentOperations::INS_NOHINTEXPAND );
// METADATA: restore
pTxtNd->RestoreMetadata(m_pMetadataUndoEnd);
}
}
else if( pSttStr && bNodeMove )
{
SwTxtNode * pNd = aPos.nNode.GetNode().GetTxtNode();
if( pNd )
{
if( nSttCntnt < pNd->GetTxt().Len() )
{
sal_uLong nOldIdx = aPos.nNode.GetIndex();
pDoc->SplitNode( aPos, false );
if( bBackSp )
lcl_ReAnchorAtCntntFlyFrames( *pDoc->GetSpzFrmFmts(), aPos, nOldIdx );
}
else
aPos.nNode++;
}
}
SwNode* pMovedNode = NULL;
if( nSectDiff )
{
sal_uLong nMoveIndex = aPos.nNode.GetIndex();
int nDiff = 0;
if( bJoinNext )
{
nMoveIndex += nSectDiff + 1;
pMovedNode = &aPos.nNode.GetNode();
}
else
{
nMoveIndex -= nSectDiff + 1;
++nDiff;
}
SwNodeIndex aMvIdx( pDoc->GetNodes(), nMoveIndex );
SwNodeRange aRg( aPos.nNode, 0 - nDiff, aPos.nNode, 1 - nDiff );
aPos.nNode--;
if( !bJoinNext )
pMovedNode = &aPos.nNode.GetNode();
pDoc->GetNodes()._MoveNodes( aRg, pDoc->GetNodes(), aMvIdx, sal_True );
aPos.nNode++;
}
if( bNodeMove )
{
SwNodeRange aRange( *pMvStt, 0, *pMvStt, nNode );
SwNodeIndex aCopyIndex( aPos.nNode, -1 );
pDoc->GetUndoManager().GetUndoNodes()._Copy( aRange, aPos.nNode );
if( nReplaceDummy )
{
sal_uLong nMoveIndex;
if( bJoinNext )
{
nMoveIndex = nEndNode - nNdDiff;
aPos.nNode = nMoveIndex + nReplaceDummy;
}
else
{
aPos = SwPosition( aCopyIndex );
nMoveIndex = aPos.nNode.GetIndex() + nReplaceDummy + 1;
}
SwNodeIndex aMvIdx( pDoc->GetNodes(), nMoveIndex );
SwNodeRange aRg( aPos.nNode, 0, aPos.nNode, 1 );
pMovedNode = &aPos.nNode.GetNode();
pDoc->GetNodes()._MoveNodes( aRg, pDoc->GetNodes(), aMvIdx, sal_True );
pDoc->GetNodes().Delete( aMvIdx, 1 );
}
}
if( pMovedNode )
lcl_MakeAutoFrms( *pDoc->GetSpzFrmFmts(), pMovedNode->GetIndex() );
if( pSttStr )
{
aPos.nNode = nSttNode - nNdDiff + ( bJoinNext ? 0 : nReplaceDummy );
SwTxtNode * pTxtNd = aPos.nNode.GetNode().GetTxtNode();
// wenn mehr als ein Node geloescht wurde, dann wurden auch
// alle "Node"-Attribute gespeichert
if (pTxtNd != NULL)
{
if( pTxtNd->HasSwAttrSet() && bNodeMove && !pEndStr )
pTxtNd->ResetAllAttr();
if( pTxtNd->GetpSwpHints() )
pTxtNd->ClearSwpHintsArr( true );
// SectionNode-Modus und von oben nach unten selektiert:
// -> im StartNode steht noch der Rest vom Join => loeschen
aPos.nContent.Assign( pTxtNd, nSttCntnt );
pTxtNd->InsertText( *pSttStr, aPos.nContent,
IDocumentContentOperations::INS_NOHINTEXPAND );
// METADATA: restore
pTxtNd->RestoreMetadata(m_pMetadataUndoStart);
}
}
if( pHistory )
{
pHistory->TmpRollback( pDoc, nSetPos, false );
if( nSetPos ) // es gab Fussnoten/FlyFrames
{
// gibts ausser diesen noch andere ?
if( nSetPos < pHistory->Count() )
{
// dann sicher die Attribute anderen Attribute
SwHistory aHstr;
aHstr.Move( 0, pHistory, nSetPos );
pHistory->Rollback( pDoc );
pHistory->Move( 0, &aHstr );
}
else
{
pHistory->Rollback( pDoc );
DELETEZ( pHistory );
}
}
}
if( bResetPgDesc || bResetPgBrk )
{
sal_uInt16 nStt = static_cast<sal_uInt16>( bResetPgDesc ? RES_PAGEDESC : RES_BREAK );
sal_uInt16 nEnd = static_cast<sal_uInt16>( bResetPgBrk ? RES_BREAK : RES_PAGEDESC );
SwNode* pNode = pDoc->GetNodes()[ nEndNode + 1 ];
if( pNode->IsCntntNode() )
((SwCntntNode*)pNode)->ResetAttr( nStt, nEnd );
else if( pNode->IsTableNode() )
((SwTableNode*)pNode)->GetTable().GetFrmFmt()->ResetFmtAttr( nStt, nEnd );
}
}
// den temp. eingefuegten Node noch loeschen !!
if( pInsNd )
pDoc->GetNodes().Delete( aIdx, 1 );
if( pRedlSaveData )
SetSaveData( *pDoc, *pRedlSaveData );
AddUndoRedoPaM(rContext, true);
}
void SwUndoDelete::RedoImpl(::sw::UndoRedoContext & rContext)
{
SwPaM & rPam = AddUndoRedoPaM(rContext);
SwDoc& rDoc = *rPam.GetDoc();
if( pRedlSaveData )
{
bool bSuccess = FillSaveData(rPam, *pRedlSaveData, sal_True);
OSL_ENSURE(bSuccess,
"SwUndoDelete::Redo: used to have redline data, but now none?");
if (!bSuccess)
{
delete pRedlSaveData, pRedlSaveData = 0;
}
}
if( !bDelFullPara )
{
SwUndRng aTmpRng( rPam );
RemoveIdxFromRange( rPam, sal_False );
aTmpRng.SetPaM( rPam );
if( !bJoinNext ) // Dann Selektion von unten nach oben
rPam.Exchange(); // wieder herstellen!
}
if( pHistory ) // wurden Attribute gesichert ?
{
pHistory->SetTmpEnd( pHistory->Count() );
SwHistory aHstr;
aHstr.Move( 0, pHistory );
if( bDelFullPara )
{
ASSERT( rPam.HasMark(), "PaM ohne Mark" );
DelCntntIndex( *rPam.GetMark(), *rPam.GetPoint(),
DelCntntType(nsDelCntntType::DELCNT_ALL | nsDelCntntType::DELCNT_CHKNOCNTNT) );
_DelBookmarks(rPam.GetMark()->nNode, rPam.GetPoint()->nNode);
}
else
DelCntntIndex( *rPam.GetMark(), *rPam.GetPoint() );
nSetPos = pHistory ? pHistory->Count() : 0;
pHistory->Move( nSetPos, &aHstr );
}
else
{
if( bDelFullPara )
{
ASSERT( rPam.HasMark(), "PaM ohne Mark" );
DelCntntIndex( *rPam.GetMark(), *rPam.GetPoint(),
DelCntntType(nsDelCntntType::DELCNT_ALL | nsDelCntntType::DELCNT_CHKNOCNTNT) );
_DelBookmarks( rPam.GetMark()->nNode, rPam.GetPoint()->nNode );
}
else
DelCntntIndex( *rPam.GetMark(), *rPam.GetPoint() );
nSetPos = pHistory ? pHistory->Count() : 0;
}
if( !pSttStr && !pEndStr )
{
SwNodeIndex aSttIdx = ( bDelFullPara || bJoinNext )
? rPam.GetMark()->nNode
: rPam.GetPoint()->nNode;
SwTableNode* pTblNd = aSttIdx.GetNode().GetTableNode();
if( pTblNd )
{
if( bTblDelLastNd )
{
// dann am Ende wieder einen Node einfuegen
const SwNodeIndex aTmpIdx( *pTblNd->EndOfSectionNode(), 1 );
rDoc.GetNodes().MakeTxtNode( aTmpIdx,
rDoc.GetTxtCollFromPool( RES_POOLCOLL_STANDARD ) );
}
SwCntntNode* pNextNd = rDoc.GetNodes()[
pTblNd->EndOfSectionIndex()+1 ]->GetCntntNode();
if( pNextNd )
{
SwFrmFmt* pTableFmt = pTblNd->GetTable().GetFrmFmt();
const SfxPoolItem *pItem;
if( SFX_ITEM_SET == pTableFmt->GetItemState( RES_PAGEDESC,
sal_False, &pItem ) )
pNextNd->SetAttr( *pItem );
if( SFX_ITEM_SET == pTableFmt->GetItemState( RES_BREAK,
sal_False, &pItem ) )
pNextNd->SetAttr( *pItem );
}
pTblNd->DelFrms();
}
rPam.SetMark();
rPam.DeleteMark();
rDoc.GetNodes().Delete( aSttIdx, nEndNode - nSttNode );
// setze den Cursor immer in einen ContentNode !!
if( !rPam.Move( fnMoveBackward, fnGoCntnt ) &&
!rPam.Move( fnMoveForward, fnGoCntnt ) )
rPam.GetPoint()->nContent.Assign( rPam.GetCntntNode(), 0 );
}
else if( bDelFullPara )
{
// der Pam wurde am Point( == Ende) um eins erhoeht, um einen
// Bereich fuers Undo zu haben. Der muss jetzt aber wieder entfernt
// werden!!!
rPam.End()->nNode--;
if( rPam.GetPoint()->nNode == rPam.GetMark()->nNode )
*rPam.GetMark() = *rPam.GetPoint();
rDoc.DelFullPara( rPam );
}
else
rDoc.DeleteAndJoin( rPam );
}
void SwUndoDelete::RepeatImpl(::sw::RepeatContext & rContext)
{
// this action does not seem idempotent,
// so make sure it is only executed once on repeat
if (rContext.m_bDeleteRepeated)
return;
SwPaM & rPam = rContext.GetRepeatPaM();
SwDoc& rDoc = *rPam.GetDoc();
::sw::GroupUndoGuard const undoGuard(rDoc.GetIDocumentUndoRedo());
if( !rPam.HasMark() )
{
rPam.SetMark();
rPam.Move( fnMoveForward, fnGoCntnt );
}
if( bDelFullPara )
rDoc.DelFullPara( rPam );
else
rDoc.DeleteAndJoin( rPam );
rContext.m_bDeleteRepeated = true;
}
void SwUndoDelete::SetTableName(const String & rName)
{
sTableName = rName;
}
| 32.787129 | 107 | 0.589703 | [
"object"
] |
f17cdd102cdb57871921e6387586dc6ecca92c21 | 2,287 | cpp | C++ | Data structures for RMQ/SegmentTree.cpp | afentev/Algorithms-and-Data-structures | 4049c8dd21e9db90f341aefeb1669d4d3f33a519 | [
"MIT"
] | 1 | 2022-03-22T16:53:17.000Z | 2022-03-22T16:53:17.000Z | Data structures for RMQ/SegmentTree.cpp | afentev/Algorithms-and-Data-structures | 4049c8dd21e9db90f341aefeb1669d4d3f33a519 | [
"MIT"
] | null | null | null | Data structures for RMQ/SegmentTree.cpp | afentev/Algorithms-and-Data-structures | 4049c8dd21e9db90f341aefeb1669d4d3f33a519 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#define int int64_t
struct SegmentTree {
static inline int neutral = 0;
int op(int arg1, int arg2) {
return arg1 + arg2;
}
SegmentTree(const std::vector<int>& a) {
n = a.size();
t.resize(n << 2, neutral);
build(a, 1, 0, n - 1);
}
void build(const std::vector<int>& a, int i, int lSubSeg, int rSubSeg) {
if (rSubSeg == lSubSeg == 1) {
t[i] = a[lSubSeg];
} else {
int mid = (lSubSeg + rSubSeg) >> 1;
build(a, i << 1, lSubSeg, mid);
build(a, (i << 1) | 1, mid + 1, rSubSeg);
t[i] = op(t[i << 1], t[(i << 1) | 1]);
}
}
int query(int l, int r) { // [l; r]
return query(1, 0, n - 1, l, r);
}
int query(int i, int lSubSeg, int rSubSeg, int lQuery, int rQuery) {
if (lQuery > rSubSeg || rQuery < lSubSeg) {
return neutral;
}
if (lQuery <= lSubSeg && rSubSeg <= rQuery) {
return t[i];
}
int mid = (lSubSeg + rSubSeg) >> 1;
int left = query(i << 1, lSubSeg, mid, lQuery, rQuery);
int right = query((i << 1) | 1, mid + 1, rSubSeg, lQuery, rQuery);
return op(left, right);
}
void update(int pos, int newVal) {
update(1, 0, n - 1, pos, newVal);
}
void update(int i, int lSubSeg, int rSubSeg, int pos, int newVal) {
if (lSubSeg == rSubSeg) {
t[i] = newVal;
} else {
int mid = (lSubSeg + rSubSeg) >> 1;
if (pos <= mid) {
update(i << 1, lSubSeg, mid, pos, newVal);
} else {
update((i << 1) | 1, mid + 1, rSubSeg, pos, newVal);
}
t[i] = op(t[i << 1], t[(i << 1) | 1]);
}
}
std::vector<int> t;
int n = 0;
};
// solution for https://codeforces.com/group/QmrArgR1Jp/contest/269449/problem/B
int32_t main() {
std::cin.tie(nullptr);
std::ios_base::sync_with_stdio(false);
int n;
std::cin >> n;
std::vector<int> a(n, 0);
for (int i = 0; i < n; ++i) {
std::cin >> a[i];
}
SegmentTree tree(a);
std::string command;
while (std::cin >> command) {
if (command == "sum") {
int l, r;
std::cin >> l >> r;
--l, --r;
std::cout << tree.query(l, r) << '\n';
} else {
int index, newVal;
std::cin >> index >> newVal;
--index;
tree.update(index, newVal);
}
}
return 0;
}
| 21.990385 | 80 | 0.514211 | [
"vector"
] |
1afd81f84bfb101ecd3c123f32144c35a86ffba6 | 3,266 | cpp | C++ | tc 160+/EncodedSum.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 3 | 2015-05-25T06:24:37.000Z | 2016-09-10T07:58:00.000Z | tc 160+/EncodedSum.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | null | null | null | tc 160+/EncodedSum.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 5 | 2015-05-25T06:24:40.000Z | 2021-08-19T19:22:29.000Z | #include <algorithm>
#include <cassert>
#include <cstdio>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cstring>
#include <set>
using namespace std;
long long cnt[10];
class EncodedSum {
public:
long long maximumSum(vector <string> numbers) {
set<char> S;
for (int i=0; i<(int)numbers.size(); ++i)
for (int j=0; j<(int)numbers[i].size(); ++j)
S.insert(numbers[i][j]);
memset(cnt, 0, sizeof cnt);
for (int i=0; i<(int)numbers.size(); ++i) {
long long mul = 1;
for (int j=(int)numbers[i].size()-1; j>=0; --j, mul*=10)
cnt[numbers[i][j]-'A'] += mul;
}
string m(S.begin(), S.end());
long long sol = 0;
do {
bool ok = true;
if (m.size() == 10)
for (int i=0; i<(int)numbers.size(); ++i)
if (numbers[i][0] == m[9]) {
ok = false;
break;
}
if (!ok)
continue;
long long cur = 0;
for (int i=0; i<(int)m.size(); ++i)
cur += cnt[m[i]-'A']*(9-i);
sol = max(sol, cur);
} while (next_permutation(m.begin(), m.end()));
return sol;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const long long &Expected, const long long &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { string Arr0[] = {"ABC",
"BCA"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); long long Arg1 = 1875LL; verify_case(0, Arg1, maximumSum(Arg0)); }
void test_case_1() { string Arr0[] = {"ABCDEFGHIJ"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); long long Arg1 = 9876543210LL; verify_case(1, Arg1, maximumSum(Arg0)); }
void test_case_2() { string Arr0[] = {"ABCDEFGHIJ",
"J"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); long long Arg1 = 9876543202LL; verify_case(2, Arg1, maximumSum(Arg0)); }
void test_case_3() { string Arr0[] = {"A",
"BB",
"CCC",
"DDDD",
"EEEEE",
"FFFFFF",
"GGGGGGG",
"HHHHHHHH",
"IIIIIIIII",
"AJJJJJJJJJ"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); long long Arg1 = 9973936905LL; verify_case(3, Arg1, maximumSum(Arg0)); }
void test_case_4() { string Arr0[] = {"GHJIDDD",
"AHHCCCA",
"IIJCEJ",
"F",
"HDBIGFJAAJ"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); long long Arg1 = 9888114550LL; verify_case(4, Arg1, maximumSum(Arg0)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
EncodedSum ___test;
___test.run_test(-1);
}
// END CUT HERE
| 33.326531 | 321 | 0.570729 | [
"vector"
] |
1afdd0f37e3cc14ed558bb1ae4adcc74ad4950b3 | 1,710 | cpp | C++ | src/erhe/primitive/primitive.cpp | tksuoran/erhe | 07d1ea014e1675f6b09bff0d9d4f3568f187e0d8 | [
"Apache-2.0"
] | 36 | 2021-05-03T10:47:49.000Z | 2022-03-19T12:54:03.000Z | src/erhe/primitive/primitive.cpp | tksuoran/erhe | 07d1ea014e1675f6b09bff0d9d4f3568f187e0d8 | [
"Apache-2.0"
] | 29 | 2020-05-17T08:26:31.000Z | 2022-03-27T08:52:47.000Z | src/erhe/primitive/primitive.cpp | tksuoran/erhe | 07d1ea014e1675f6b09bff0d9d4f3568f187e0d8 | [
"Apache-2.0"
] | 2 | 2022-01-24T09:24:37.000Z | 2022-01-31T20:45:36.000Z | #include "erhe/primitive/primitive.hpp"
#include "erhe/primitive/primitive_geometry.hpp"
#include "erhe/primitive/log.hpp"
#include "erhe/graphics/buffer.hpp"
#include "erhe/raytrace/ibuffer.hpp"
#include "erhe/toolkit/verify.hpp"
namespace erhe::primitive
{
// Primitive::Primitive() = default;
//Primitive::Primitive(
// const std::shared_ptr<Primitive_geometry>& primitive_geometry,
// const std::shared_ptr<Material>& material
//)
// : primitive_geometry{primitive_geometry}
// , material {material}
//{
//}
auto c_str(const Primitive_mode primitive_mode) -> const char*
{
switch (primitive_mode)
{
case Primitive_mode::not_set: return "not_set";
case Primitive_mode::polygon_fill: return "polygon_fill";
case Primitive_mode::edge_lines: return "edge_lines";
case Primitive_mode::corner_points: return "corner_points";
case Primitive_mode::corner_normals: return "corner_normals";
case Primitive_mode::polygon_centroids: return "polygon_centroids";
case Primitive_mode::count: return "count";
default:
{
ERHE_FATAL("Bad mesh mode");
}
}
}
auto c_str(const Normal_style normal_style) -> const char*
{
switch (normal_style)
{
case Normal_style::none: return "none";
case Normal_style::corner_normals: return "corner_normals";
case Normal_style::polygon_normals: return "polygon_normals";
case Normal_style::point_normals: return "point_normals";
default:
{
ERHE_FATAL("Bad mesh normal style");
}
}
}
} // namespace erhe::primitive
| 30 | 75 | 0.650877 | [
"mesh"
] |
21089594dc0b0a26d2cef10a08b643c5be14f90a | 60,330 | cpp | C++ | src/CAPSImg/CapsImageStd.cpp | jvernet/capsimage | b6a7693d9379333ae6f1c7d29164d12866170904 | [
"Linux-OpenIB"
] | 8 | 2019-04-01T10:06:14.000Z | 2021-02-06T23:54:01.000Z | src/CAPSImg/CapsImageStd.cpp | jvernet/capsimage | b6a7693d9379333ae6f1c7d29164d12866170904 | [
"Linux-OpenIB"
] | 3 | 2018-11-09T17:11:13.000Z | 2021-02-25T17:57:58.000Z | src/CAPSImg/CapsImageStd.cpp | jvernet/capsimage | b6a7693d9379333ae6f1c7d29164d12866170904 | [
"Linux-OpenIB"
] | 5 | 2020-04-14T19:37:43.000Z | 2021-02-07T00:32:24.000Z | #include "stdafx.h"
using namespace std;
CCapsImageStd::CCapsImageStd()
{
InitSystem();
Clear();
}
CCapsImageStd::~CCapsImageStd()
{
FreeDecoder();
}
// lock and scan file
int CCapsImageStd::Lock(PCAPSFILE pcf)
{
// release image data
Unlock();
// try to lock
switch (loader.Lock(pcf)) {
// file open error
case CCapsLoader::ccidErrFile:
return imgeOpen;
// not a caps file
case CCapsLoader::ccidErrType:
return imgeType;
// yes, caps file
case CCapsLoader::ccidCaps:
break;
// unknown problem
default:
return imgeGeneric;
}
// store open mode
dii.readonly=(pcf->flag & CFF_WRITE) ? 0 : 1;
// scan whole file for information
int res=ScanImage();
if (res != imgeOk)
return res;
return CheckEncoder(dii.ci.encoder, dii.ci.encrev);
}
// release file
int CCapsImageStd::Unlock()
{
Destroy();
loader.Unlock();
return imgeOk;
}
// read and decode caps track format
int CCapsImageStd::LoadTrack(PDISKTRACKINFO pti, UDWORD flag)
{
// set lock flags
di.pdt=pti;
di.flag=flag;
int res = imgeOk;
// update the track image if already available
if (pti->trackcnt) {
switch (pti->type) {
case dtitCapsDump:
res = UpdateDump();
break;
case dtitCapsImage:
res = UpdateImage(0);
break;
default:
res = imgeGeneric;
break;
}
return res;
}
// process stored track data or generate data
if (pti->datasize) {
// load data, check data header
loader.SetPosition(pti->datapos);
if (loader.ReadChunk() == CCapsLoader::ccidData) {
// allocate data buffer if needed
AllocDiskData(pti->datasize);
di.datacount=pti->datasize;
// load and decode data
if (loader.ReadData(di.data) == pti->datasize) {
switch (pti->type) {
case dtitCapsDump:
res=DecompressDump();
break;
case dtitCapsImage:
res=DecodeImage();
break;
default:
res=imgeGeneric;
break;
}
} else
res=imgeGeneric;
} else
res=imgeGeneric;
} else {
// generate data
switch (pti->type) {
case dtitCapsImage:
di.datacount=0;
res=DecodeImage();
break;
default:
res=imgeGeneric;
break;
}
}
return res;
}
// scan file; collect all information available
int CCapsImageStd::ScanImage()
{
vector <ScanInfo> si;
si.reserve(DEF_SCANINFO);
ScanInfo empty_si = { 0, 0 };
DiskTrackInfo dt;
// process complete file
for (int run = 1; run;) {
int pos = loader.GetPosition();
int type = loader.ReadChunk();
PCAPSCHUNK pc = loader.GetChunk();
int did = 0;
switch (type) {
// end of file
case CCapsLoader::ccidEof:
run = 0;
continue;
// remember data position
case CCapsLoader::ccidData:
did = pc->cg.mod.data.did;
if ((unsigned)did >= si.size())
si.resize(did + 1, empty_si);
si[did].data = pos;
loader.SkipData();
break;
// remember track header position
case CCapsLoader::ccidTrck:
did = pc->cg.mod.trck.did;
if ((unsigned)did >= si.size())
si.resize(did + 1, empty_si);
si[did].track = pos;
break;
// handle file/format errors
case CCapsLoader::ccidErrFile:
case CCapsLoader::ccidErrType:
case CCapsLoader::ccidErrShort:
case CCapsLoader::ccidErrHeader:
case CCapsLoader::ccidErrData:
return imgeGeneric;
// image info
case CCapsLoader::ccidInfo:
dii.ci = pc->cg.mod.info;
dii.civalid = 1;
continue;
// remember track image descriptor
case CCapsLoader::ccidImge:
did = pc->cg.mod.imge.did;
if ((unsigned)did >= si.size())
si.resize(did + 1, empty_si);
si[did].track = pos;
break;
// ignore other data
default:
continue;
}
// find highest data id
if (did > dii.didmax)
dii.didmax = did;
// if did found, process if both header and data available
if (did && (unsigned)did < si.size()) {
if (si[did].track && si[did].data) {
// reset track info
memset(&dt, 0, sizeof(dt));
// save image position
int actpos = loader.GetPosition();
// create track info
loader.SetPosition(si[did].track);
type = loader.ReadChunk();
pc = loader.GetChunk();
// set track by type
switch (type) {
case CCapsLoader::ccidTrck:
dt.type = dtitCapsDump;
dt.cylinder = pc->cg.mod.trck.cyl;
dt.head = pc->cg.mod.trck.head;
dii.dmpcount++;
break;
case CCapsLoader::ccidImge:
dt.type = dtitCapsImage;
dt.cylinder = pc->cg.mod.imge.cylinder;
dt.head = pc->cg.mod.imge.head;
dt.sectorcnt = pc->cg.mod.imge.blkcnt;
dt.ci = pc->cg.mod.imge;
dii.relcount++;
break;
default:
return imgeGeneric;
}
// remember file positions
dt.headerpos = si[did].track;
dt.datapos = si[did].data;
// create data info
loader.SetPosition(si[did].data);
loader.ReadChunk();
dt.datasize = loader.GetDataSize();
// write info
int res = AddTrack(&dt);
if (res != imgeOk)
return res;
// save to image is not allowed
dii.modimage = 1;
// restore image position
loader.SetPosition(actpos);
}
}
}
return imgeOk;
}
// update any image data that changes for each revolution
int CCapsImageStd::UpdateImage(int group)
{
int res=imgeOk;
// set track buffer information
di.track=di.pdt->trackbuf;
di.trackbc=di.pdt->trackbc;
di.singletrackbc=di.pdt->singletrackbc;
trackbuf.InitBitSize(di.track, di.trackbc);
// stop if track buffer is invalid
if (!di.track || !di.trackbc || !di.singletrackbc)
return imgeOk;
// don't change track data if updates are disabled
if (di.flag & DI_LOCK_NOUPDATE)
return imgeOk;
// update weak bit areas
if (di.pdt->fdpsize && (di.flag & DI_LOCK_UPDATEFD))
res=UpdateWeakBit(group);
return res;
}
// update all weak bits in the image
int CCapsImageStd::UpdateWeakBit(int group)
{
// don't change track data if updates are disabled
if (di.flag & DI_LOCK_NOUPDATE)
return imgeOk;
// get random seed
uint32_t seed=di.pdt->wseed;
// update all areas marked
for (int pos=0; pos < di.pdt->fdpsize; pos++) {
PDISKDATAMARK pd=di.pdt->fdp+pos;
// skip markers that belong to a different group
if (pd->group != group)
continue;
uint32_t bitpos=pd->position;
int bitcnt=pd->size;
// write generated data
while (bitcnt > 0) {
// simple random generator
seed<<=1;
if ((seed>>22 ^ seed) & DF_1)
seed++;
// write largest possible bitfield
int writebc=(bitcnt >= maxwritelen) ? maxwritelen : bitcnt;
// write bitfield
trackbuf.WriteBitWrap(bitpos, seed, writebc);
// next write position
bitcnt-=writebc;
bitpos+=writebc;
// handle track buffer wrap around (disk rotation)
if (bitpos >= di.trackbc)
bitpos-=di.trackbc;
}
}
// save random seed, so any new update on the same track would give new results
di.pdt->wseed=seed;
return imgeOk;
}
// change a few bits at the overlap position
void CCapsImageStd::UpdateOverlap()
{
// don't change track data if updates are disabled
if (di.flag & DI_LOCK_NOUPDATE)
return;
// stop if no bits to change
int ovlsize=CIMG_OVERLAPBIT;
if (ovlsize <= 0)
return;
// stop if overlap position is not available
if (di.pdt->overlapbit < 0)
return;
uint32_t bitpos=di.pdt->overlapbit;
// flip all bits at the overlap position for all tracks
for (int trk=0; trk < di.pdt->trackcnt; trk++) {
uint32_t value=trackbuf.ReadBitWrap(bitpos, ovlsize);
value=~value;
trackbuf.WriteBitWrap(bitpos, value, ovlsize);
// next track
bitpos+=di.singletrackbc;
// handle track buffer wrap around (disk rotation)
if (bitpos >= di.trackbc)
bitpos-=di.trackbc;
}
}
// image decoder
int CCapsImageStd::DecodeImage()
{
// initialize disk and track data used by decoder
int res=InitDecoder();
// run supported encoders only
if (res == imgeOk) {
switch (dii.ci.encoder) {
case CAPS_ENCODER:
case SPS_ENCODER:
res=ProcessImage();
break;
default:
res=imgeIncompatible;
break;
}
}
// if any error destroy track buffers and supress later calls
if (res != imgeOk) {
FreeTrack(di.pdt, 1);
di.pdt->type=dtitError;
}
return res;
}
// decode and encode complete track image
int CCapsImageStd::ProcessImage()
{
// check whether the image is in a supported format
int res=CheckEncoder(dii.ci.encoder, dii.ci.encrev);
if (res != imgeOk)
return res;
PDISKTRACKINFO pti=di.pdt;
// check density type
if (pti->ci.dentype<=cpdenNA || pti->ci.dentype>=cpdenLast)
return imgeIncompatible;
// check signal/cell type
if (pti->ci.sigtype<=cpsigNA || pti->ci.sigtype>=cpsigLast)
return imgeIncompatible;
// check process
if (pti->ci.process)
return imgeIncompatible;
// clear track data
FreeTrack(pti, 1);
// generate comparable image if supported
if (di.flag & DI_LOCK_COMP)
return CompareImage();
// forced indexing not allowed for varied cell density
switch (pti->ci.dentype) {
case cpdenCLAmiga:
case cpdenCLAmiga2:
case cpdenCLST:
case cpdenSLAmiga:
case cpdenSLAmiga2:
case cpdenABAmiga:
case cpdenABAmiga2:
di.flag&=~DI_LOCK_INDEX;
break;
}
// original track size calculated
uint32_t trackbits=di.dsctrackbc;
// generate 1 revolution of data as default, 5 for analyser
int trackcnt=(di.flag & DI_LOCK_ANA) ? 5 : 1;
// set unformatted track parameters
if (pti->ci.dentype == cpdenNoise) {
// 2 revolutions if multiple revolutions defined
if (di.flag & DI_LOCK_NOISEREV)
trackcnt=2;
// don't generate unformatted data unless requested, set default size unless already defined
if (!(di.flag & DI_LOCK_NOISE))
trackcnt=0;
else
if (!trackbits)
trackbits=100000;
}
// 5 revolutions for weak data, if track update is not used
if ((pti->ci.flag & CAPS_IF_FLAKEY) && !(di.flag & DI_LOCK_UPDATEFD))
trackcnt=5;
// 16 bit aligned track size if requested
if (di.flag & DI_LOCK_ALIGN) {
if (trackbits & 15)
trackbits+=16-(trackbits & 15);
}
// re-align track to 8 bit
if (!(di.flag & DI_LOCK_TRKBIT)) {
if (trackbits & 7)
trackbits+=8-(trackbits & 7);
}
// size for all tracks
uint32_t alltrackbits=trackbits*trackcnt;
// get number of bytes required for track buffer
int bufsize=trackbuf.CalculateByteSize(alltrackbits);
uint8_t *tbuf;
// allocate and clear track buffer
if (bufsize) {
tbuf=new uint8_t[bufsize];
memset(tbuf, 0, bufsize);
} else
tbuf=NULL;
// encoding start position, always on first track
uint32_t startbit=di.dscstartbit;
if (trackbits)
startbit=startbit % trackbits;
// start position is 0/index if indexing is forced
if (di.flag & DI_LOCK_INDEX)
startbit=0;
// write track info
pti->trackcnt=trackcnt;
pti->trackbuf=tbuf;
pti->tracklen=bufsize;
pti->sdpos=startbit >> 3;
pti->overlap=-1;
pti->overlapbit=-1;
pti->trackbc=alltrackbits;
pti->singletrackbc=trackbits;
pti->startbit=startbit;
// reset random seed
pti->wseed=0x87654321;
// initialize sector information
AllocTrackSI(pti);
// set track buffer information
di.track=tbuf;
di.trackbc=alltrackbits;
di.singletrackbc=trackbits;
trackbuf.InitBitSize(di.track, di.trackbc);
// additional track size
uint32_t trackdiff=trackbits-di.dsctrackbc;
// track gap split position unknown
int gsvalid=0;
uint32_t gspos=0;
// process all revolutions
uint32_t trksize=0, actpos=startbit;
for (int trk=0; trk < trackcnt; trk++) {
// create track size and pointer for each revolution
uint32_t ofsact=trksize >> 3;
pti->trackdata[trk]=tbuf+ofsact;
pti->trackstart[trk]=ofsact;
trksize+=trackbits;
uint32_t ofsnext=trksize >> 3;
pti->tracksize[trk]=ofsnext-ofsact;
// decode/encode all blocks
for (int blk=0; blk < di.blockcount; blk++) {
uint32_t datasize=di.block[blk].blockbits;
uint32_t gapsize=di.block[blk].gapbits;
// add additional size to last, track gap
if (blk == di.blockcount-1) {
// trying to grow an empty gap area is not supported
if (!gapsize && trackdiff)
return imgeGeneric;
gapsize+=trackdiff;
}
// write block
res=ProcessBlock(blk, actpos, datasize, gapsize);
if (res != imgeOk)
return res;
// if track gap has known split position, save it
if (!trk && (blk == di.blockcount-1) && di.encgsvalid) {
gsvalid=1;
gspos=di.encgapsplit;
}
// next write position, handle track buffer wrap around (disk rotation)
actpos+=datasize+gapsize;
if (actpos >= di.trackbc)
actpos-=di.trackbc;
}
// fix MFM encoding
MFMFixup();
}
// sanity check; writing must end where it started
if (actpos != startbit)
return imgeGeneric;
// set track overlap position
if (gsvalid) {
uint32_t ofs=gspos % trackbits;
pti->overlapbit=ofs;
if (di.flag & DI_LOCK_OVLBIT)
pti->overlap=ofs;
else
pti->overlap=ofs >> 3;
}
// create noise track
if (pti->ci.dentype==cpdenNoise && (di.flag & DI_LOCK_NOISE))
GenerateNoiseTrack(pti);
// create density map
if ((res=DecodeDensity(pti, di.data, di.flag)) != imgeOk)
return res;
// update bits at the overlap position
UpdateOverlap();
// first image update to ensure weak bits etc are in place
res=UpdateImage(0);
return res;
}
// compare image is unsupported in this class
int CCapsImageStd::CompareImage()
{
return imgeUnsupported;
}
// decompress dump is unsupported in this class
int CCapsImageStd::DecompressDump()
{
return imgeUnsupported;
}
// update for CT Raw format is unsupported in this class
int CCapsImageStd::UpdateDump()
{
return imgeUnsupported;
}
// track density decoder
int CCapsImageStd::DecodeDensity(PDISKTRACKINFO pti, PUBYTE buf, UDWORD flag)
{
// generate density
switch (pti->ci.dentype) {
case cpdenNoise:
if (flag & DI_LOCK_DENNOISE)
GenerateNoiseDensity(pti);
break;
case cpdenAuto:
if (flag & DI_LOCK_DENAUTO)
GenerateAutoDensity(pti);
break;
case cpdenCLAmiga:
if (flag & DI_LOCK_DENVAR)
GenerateCLA(pti, buf);
break;
case cpdenCLAmiga2:
if (flag & DI_LOCK_DENVAR)
GenerateCLA2(pti, buf);
break;
case cpdenCLST:
if (flag & DI_LOCK_DENVAR)
GenerateCLST(pti, buf);
break;
case cpdenSLAmiga:
if (flag & DI_LOCK_DENVAR)
GenerateSLA(pti, buf);
break;
case cpdenSLAmiga2:
if (flag & DI_LOCK_DENVAR)
GenerateSLA2(pti, buf);
break;
case cpdenABAmiga:
if (flag & DI_LOCK_DENVAR)
GenerateABA(pti, buf);
break;
case cpdenABAmiga2:
if (flag & DI_LOCK_DENVAR)
GenerateABA2(pti, buf);
break;
}
// density map conversion
if (flag & DI_LOCK_DENALT)
ConvertDensity(pti);
return imgeOk;
}
// density converter from default mapping
int CCapsImageStd::ConvertDensity(PDISKTRACKINFO pti)
{
// cancel if buffer not available
if (!pti->timebuf || !pti->timecnt)
return imgeOk;
// sum fractions
UDWORD sum=0;
for (int pos=0; pos < pti->timecnt; pos++) {
sum+=pti->timebuf[pos];
pti->timebuf[pos]=sum;
}
return imgeOk;
}
// generate unformatted track data
int CCapsImageStd::GenerateNoiseTrack(PDISKTRACKINFO pti)
{
UDWORD val=CIMG_MFMNOISE;
for (int pos=0; pos < pti->tracklen; pos++) {
pti->trackbuf[pos]=(UBYTE)val;
val=val<<8|val>>24;
}
return imgeOk;
}
// generate unformatted cell density
int CCapsImageStd::GenerateNoiseDensity(PDISKTRACKINFO pti)
{
// same size with track data
if (pti->tracklen && pti->trackcnt)
pti->timecnt=pti->tracklen/pti->trackcnt;
else
if (!(pti->timecnt=pti->ci.trksize))
pti->timecnt=12500;
pti->timebuf=new UDWORD[pti->timecnt+1];
int pos;
for (pos=0; pos < pti->timecnt; pos++) {
UDWORD val=1000;
if (pos & 512)
val+=(pos % 99)+(pos&31);
else
val-=(pos % 121)-(pos&31);
pti->timebuf[pos]=val;
}
pti->timebuf[pos]=0;
return imgeOk;
}
// generate auto cell density
int CCapsImageStd::GenerateAutoDensity(PDISKTRACKINFO pti)
{
// same size with track data
if (pti->tracklen && pti->trackcnt)
pti->timecnt=pti->tracklen/pti->trackcnt;
else
if (!(pti->timecnt=pti->ci.trksize))
pti->timecnt=12500;
pti->timebuf=new UDWORD[pti->timecnt+1];
int pos;
for (pos=0; pos < pti->timecnt; pos++) {
pti->timebuf[pos]=1000;
}
pti->timebuf[pos]=0;
return imgeOk;
}
// generate Copylock Amiga cell density
int CCapsImageStd::GenerateCLA(PDISKTRACKINFO pti, PUBYTE buf)
{
// set auto density
GenerateAutoDensity(pti);
// iterate block positions
int lg = trackbuf.CalculateByteSize(di.block[3].gapbits);
int pos=pti->sdpos, cp;
for (unsigned blk=0; blk < pti->ci.blkcnt; blk++) {
int bs = trackbuf.CalculateByteSize(di.block[blk].blockbits);
int gs = trackbuf.CalculateByteSize(di.block[blk].gapbits);
int xs=bs+gs;
switch (blk) {
case 4:
for (cp=0-lg; cp < bs; cp++) {
pti->timebuf[pos+cp]-=55;
}
break;
case 5:
for (cp=0-lg; cp < bs; cp++) {
pti->timebuf[pos+cp]-=5;
}
break;
case 6:
for (cp=0-lg; cp < bs; cp++) {
pti->timebuf[pos+cp]+=45;
}
break;
}
pos+=xs;
if (pos >= pti->timecnt)
pos-=pti->timecnt;
lg=gs;
}
return imgeOk;
}
// generate Copylock Amiga, new cell density
int CCapsImageStd::GenerateCLA2(PDISKTRACKINFO pti, PUBYTE buf)
{
// set auto density
GenerateAutoDensity(pti);
// iterate block positions
int lg = trackbuf.CalculateByteSize(di.block[di.blockcount - 1].gapbits);
int pos=pti->sdpos, cp;
for (unsigned blk=0; blk < pti->ci.blkcnt; blk++) {
int bs = trackbuf.CalculateByteSize(di.block[blk].blockbits);
int gs = trackbuf.CalculateByteSize(di.block[blk].gapbits);
int xs=bs+gs;
switch (blk) {
case 0:
for (cp=0-lg; cp < bs; cp++) {
pti->timebuf[pos+cp]-=55;
}
break;
case 1:
for (cp=0-lg; cp < bs; cp++) {
pti->timebuf[pos+cp]-=5;
}
break;
case 2:
for (cp=0-lg; cp < bs; cp++) {
pti->timebuf[pos+cp]+=45;
}
break;
}
pos+=xs;
if (pos >= pti->timecnt)
pos-=pti->timecnt;
lg=gs;
}
return imgeOk;
}
// generate Copylock ST cell density
int CCapsImageStd::GenerateCLST(PDISKTRACKINFO pti, PUBYTE buf)
{
// set auto density
GenerateAutoDensity(pti);
// iterate block positions
int pos=pti->sdpos, cp;
for (unsigned blk=0; blk < pti->ci.blkcnt; blk++) {
int bs = trackbuf.CalculateByteSize(di.block[blk].blockbits);
int gs = trackbuf.CalculateByteSize(di.block[blk].gapbits);
int xs=bs+gs;
switch (blk) {
case 5:
for (cp=0; cp < bs; cp++) {
pti->timebuf[pos+cp]+=50;
}
break;
}
pos+=xs;
if (pos >= pti->timecnt)
pos-=pti->timecnt;
}
return imgeOk;
}
// generate Speedlock Amiga cell density
int CCapsImageStd::GenerateSLA(PDISKTRACKINFO pti, PUBYTE buf)
{
// set auto density
GenerateAutoDensity(pti);
// iterate block positions
int pos=pti->sdpos, cp;
for (unsigned blk=0; blk < pti->ci.blkcnt; blk++) {
int bs = trackbuf.CalculateByteSize(di.block[blk].blockbits);
int gs = trackbuf.CalculateByteSize(di.block[blk].gapbits);
int xs=bs+gs;
switch (blk) {
case 1:
for (cp=0; cp < bs; cp++) {
pti->timebuf[pos+cp]+=100;
}
break;
case 2:
for (cp=0; cp < bs; cp++) {
pti->timebuf[pos+cp]-=100;
}
break;
}
pos+=xs;
if (pos >= pti->timecnt)
pos-=pti->timecnt;
}
return imgeOk;
}
// generate Speedlock Amiga, old cell density
int CCapsImageStd::GenerateSLA2(PDISKTRACKINFO pti, PUBYTE buf)
{
// set auto density
GenerateAutoDensity(pti);
// iterate block positions
int pos=pti->sdpos, cp;
for (unsigned blk=0; blk < pti->ci.blkcnt; blk++) {
int bs = trackbuf.CalculateByteSize(di.block[blk].blockbits);
int gs = trackbuf.CalculateByteSize(di.block[blk].gapbits);
int xs=bs+gs;
switch (blk) {
case 1:
for (cp=0; cp < bs; cp++) {
pti->timebuf[pos+cp]+=50;
}
break;
}
pos+=xs;
if (pos >= pti->timecnt)
pos-=pti->timecnt;
}
return imgeOk;
}
// generate Adam Brierley Amiga cell density
int CCapsImageStd::GenerateABA(PDISKTRACKINFO pti, PUBYTE buf)
{
// set auto density
GenerateAutoDensity(pti);
// iterate block positions
int pos=pti->sdpos, cp;
for (unsigned blk=0; blk < pti->ci.blkcnt; blk++) {
int bs = trackbuf.CalculateByteSize(di.block[blk].blockbits);
int gs = trackbuf.CalculateByteSize(di.block[blk].gapbits);
int xs=bs+gs;
switch (blk) {
case 1:
for (cp=0; cp < bs; cp++) {
pti->timebuf[pos+cp]+=100;
}
break;
case 2:
for (cp=0; cp < bs; cp++) {
pti->timebuf[pos+cp]+=50;
}
break;
case 4:
for (cp=0; cp < bs; cp++) {
pti->timebuf[pos+cp]-=50;
}
break;
case 5:
for (cp=0; cp < bs; cp++) {
pti->timebuf[pos+cp]-=100;
}
break;
case 6:
for (cp=0; cp < bs; cp++) {
pti->timebuf[pos+cp]-=150;
}
break;
}
pos+=xs;
if (pos >= pti->timecnt)
pos-=pti->timecnt;
}
return imgeOk;
}
// generate Adam Brierley, density key Amiga cell density
int CCapsImageStd::GenerateABA2(PDISKTRACKINFO pti, PUBYTE buf)
{
// set auto density
GenerateAutoDensity(pti);
// iterate block positions
int pos=pti->sdpos, cp;
UDWORD key=0;
UDWORD mask=1;
for (unsigned blk=0; blk < pti->ci.blkcnt; blk++) {
int bs = trackbuf.CalculateByteSize(di.block[blk].blockbits);
int gs = trackbuf.CalculateByteSize(di.block[blk].gapbits);
int xs=bs+gs;
if (!blk) {
key=ReadValue(buf+blk*sizeof(CapsBlock)+offsetof(CapsBlock, gapvalue), sizeof(UDWORD));
} else {
int dns=(key & mask) ? -50 : 50;
mask<<=1;
for (cp=0; cp < bs; cp++) {
int val=pti->timebuf[pos+cp];
val+=dns;
pti->timebuf[pos+cp]=val;
}
}
pos+=xs;
if (pos >= pti->timecnt)
pos-=pti->timecnt;
}
return imgeOk;
}
// initialize encoder/decoder system
void CCapsImageStd::InitSystem()
{
// set bitfield write length supported
maxwritelen = MAX_BITBUFFER_LEN;
// keep number of bits to read at maximum supported by streaming for raw encoding
rawreadlen=MAX_STREAMBIT;
// initialize mfm encoding tables
CDiskEncoding::InitMFM(0x10000);
// keep number of bits to read at maximum supported by mfm encoding
mfmreadlen=CDiskEncoding::mfmcodebit;
// mfm encoding table index mask
mfmindexmask=(1 << mfmreadlen)-1;
// the mfm encoding table assumes the last bit to be 0, correct encoding if it's 1
// 1: 1-01 -> 1-01 unchanged after AND, msb already 0
// 0: 1-10 -> 1-00 AND clears msb
mfmmsbclear=(1 << ((mfmreadlen*2)-1))-1;
}
// clear work area
void CCapsImageStd::Clear()
{
di.pdt=NULL;
di.data=NULL;
di.block=NULL;
di.flag=0;
di.track=NULL;
di.trackbc=0;
di.singletrackbc=0;
di.dsctrackbc=0;
di.dscdatabc=0;
di.dscgapbc=0;
di.dscstartbit=0;
di.encbitpos=0;
di.encwritebc=0;
di.encgsvalid=0;
di.encgapsplit=0;
trackbuf.InitBitSize(di.track, di.trackbc);
FreeDecoder();
}
// allocate disk data buffer
void CCapsImageStd::AllocDiskData(int maxsize)
{
if (di.datasize < maxsize) {
FreeDiskData();
di.data=new uint8_t[maxsize];
di.datasize=maxsize;
}
}
// allocate image block buffer
void CCapsImageStd::AllocImageBlock(int maxsize)
{
if (di.blocksize < maxsize) {
FreeImageBlock();
di.block=new ImageBlockInfo[maxsize];
di.blocksize=maxsize;
}
}
// free disk data buffer
void CCapsImageStd::FreeDiskData()
{
di.datacount=0;
di.datasize=0;
delete [] di.data;
di.data=NULL;
}
// free image block buffer
void CCapsImageStd::FreeImageBlock()
{
di.blockcount=0;
di.blocksize=0;
delete [] di.block;
di.block=NULL;
}
// free decoder data
void CCapsImageStd::FreeDecoder()
{
FreeDiskData();
FreeImageBlock();
}
// check encoder compatibility
int CCapsImageStd::CheckEncoder(int encoder, int revision)
{
if (!dii.civalid)
return imgeOk;
int err=0;
switch (encoder) {
case CAPS_ENCODER:
if (revision < 1 || revision > CAPS_ENCODER_REV)
err=1;
break;
case SPS_ENCODER:
if (revision < 1 || revision > SPS_ENCODER_REV)
err=1;
break;
default:
err=1;
break;
}
return err ? imgeIncompatible : imgeOk;
}
// get block descriptor and convert to image block descriptor
int CCapsImageStd::GetBlock(PIMAGEBLOCKINFO pi, int blk)
{
// check errors
if (!pi)
return imgeGeneric;
// get ipf block descriptor, stop on any error
CapsBlock cb;
int res=GetBlock(&cb, blk);
if (res != imgeOk)
return res;
// set image descriptor
pi->blockbits=cb.blockbits;
pi->gapbits=cb.gapbits;
pi->enctype=cb.enctype;
pi->flag=cb.flag;
pi->gapvalue=cb.gapvalue;
pi->dataoffset=cb.dataoffset;
// CAPS encoder support: no gap streams, no flags, 2us cells
if (dii.ci.encoder == CAPS_ENCODER) {
pi->gapoffset=0;
pi->celltype=cpbct2us;
pi->flag=0;
} else {
pi->gapoffset=cb.bt.sps.gapoffset;
pi->celltype=cb.bt.sps.celltype;
}
// reset encoding information
pi->fdenc=ibieNA;
pi->fdbitpos=0;
return imgeOk;
}
// get block descriptor
int CCapsImageStd::GetBlock(PCAPSBLOCK pb, int blk)
{
// check errors
if (!di.data || !pb || blk<0 || blk>=di.blockcount)
return imgeGeneric;
// check buffer overrun
if (int((blk+1)*sizeof(CapsBlock)) > di.pdt->datasize)
return imgeShort;
// read block descriptor and convert it to host native endiannes
memcpy(pb, di.data+blk*sizeof(CapsBlock), sizeof(CapsBlock));
CCapsLoader::Swap((PUDWORD)pb, sizeof(CapsBlock));
return imgeOk;
}
// initialize decoder data
int CCapsImageStd::InitDecoder()
{
// stop if image descriptor is not available
if (!dii.civalid)
return imgeIncompatible;
// allocate and create block descriptors
AllocImageBlock(di.pdt->ci.blkcnt);
di.blockcount=di.pdt->ci.blkcnt;
int blk;
// initialize block descriptors from image data
for (blk=0; blk < di.blockcount; blk++) {
int res=GetBlock(di.block+blk, blk);
if (res != imgeOk)
return res;
}
// reset track info
di.dsctrackbc=0;
di.dscdatabc=0;
di.dscgapbc=0;
di.dscstartbit=0;
// calculate data and gap sizes
for (blk=0; blk < di.blockcount; blk++) {
PIMAGEBLOCKINFO pi=di.block+blk;
// only allow gap size of 1 byte or more
if (pi->gapbits < 8)
pi->gapbits=0;
di.dscdatabc+=pi->blockbits;
di.dscgapbc+=pi->gapbits;
}
// track size
di.dsctrackbc=di.dscdatabc+di.dscgapbc;
// set encoding start position, limit to track size
if (di.dsctrackbc)
di.dscstartbit=di.pdt->ci.startbit % di.dsctrackbc;
return imgeOk;
}
// initialize stream decoding
int CCapsImageStd::InitStream(PIMAGESTREAMINFO pstr, int strtype, int blk)
{
// check errors
if (!pstr || blk<0 || blk>=di.blockcount)
return imgeGeneric;
// set parameters so all data is available in the stream descriptor
pstr->strtype=strtype;
pstr->actblock=blk;
pstr->enctype=di.block[blk].enctype;
// active encoding is set by the block descriptor, but can be changed later
pstr->actenctype=pstr->enctype;
int res;
switch (strtype) {
case isitData:
res=InitDataStream(pstr);
break;
case isitGap0:
case isitGap1:
res=InitGapStream(pstr);
break;
default:
res=imgeGeneric;
break;
}
// stop if stream could not be initialized
if (res != imgeOk)
return res;
// stop if stream is unreadable
res=ResetStream(pstr);
return res;
}
// initialize data stream decoding
int CCapsImageStd::InitDataStream(PIMAGESTREAMINFO pstr)
{
// sample looping on zero data count is not allowed
pstr->allowloop=0;
PIMAGEBLOCKINFO pi=di.block+pstr->actblock;
// set data size mode to bits or bytes according to the encoder flag
pstr->sizemodebit=(pi->flag & CAPS_BF_DMB) ? 1 : 0;
// stream start from block descriptor
pstr->strstart=pi->dataoffset;
// check buffer overrun for file limit
if (pstr->strstart >= (uint32_t)di.pdt->datasize)
return imgeShort;
// stream ends at the file limit for the current chunk for last block, or at the start of the next block stream
if (pstr->actblock == di.blockcount-1)
pstr->strend=di.pdt->datasize;
else
pstr->strend=pi[1].dataoffset;
// check buffer overrun for stream limit
if (pstr->strstart >= pstr->strend)
return imgeShort;
// set stream pointer and maximum size
pstr->strbase=di.data+pstr->strstart;
pstr->strsize=pstr->strend-pstr->strstart;
return imgeOk;
}
// initialize gap stream decoding
int CCapsImageStd::InitGapStream(PIMAGESTREAMINFO pstr)
{
// sample looping on zero data count is allowed
pstr->allowloop=1;
PIMAGEBLOCKINFO pi=di.block+pstr->actblock;
// always set data size mode to bits for a gap stream
pstr->sizemodebit=1;
// generate gap stream from gap value; 1 byte size, 8 bit pattern, gap value
int align=(pstr->strtype == isitGap0) ? 0 : 1;
int gflag=align ? CAPS_BF_GP1 : CAPS_BF_GP0;
int es=1;
int gc=0;
pstr->gapstr[gc++]=cpgapData | es<<CAPS_SIZE_S;
pstr->gapstr[gc++]=8;
pstr->gapstr[gc++]=(uint8_t)pi->gapvalue;
pstr->gapstr[gc++]=cpgapEnd;
// use the generated gap stream if no gap streams are available at all
if (!(pi->flag & (CAPS_BF_GP0 | CAPS_BF_GP1))) {
pstr->strstart=0;
pstr->strend=0;
pstr->strbase=pstr->gapstr;
pstr->strsize=gc;
return imgeOk;
}
// disable gap stream if not available
if (!(pi->flag & gflag)) {
pstr->strstart=0;
pstr->strend=0;
pstr->strbase=NULL;
pstr->strsize=0;
return imgeOk;
}
// stream start from block descriptor
pstr->strstart=pi->gapoffset;
// check buffer overrun for file limit
if (pstr->strstart >= (uint32_t)di.pdt->datasize)
return imgeShort;
// find the next gap stream stored
int bls;
for (bls=pstr->actblock+1; bls < di.blockcount; bls++) {
if (di.block[bls].flag & (CAPS_BF_GP0 | CAPS_BF_GP1))
break;
}
// stream ends at the beginning of the data streams if this is the last gap stream stored
// if another gap streams follows, this one ends where the next one begins
if (bls == di.blockcount)
pstr->strend=di.block[0].dataoffset;
else
pstr->strend=di.block[bls].gapoffset;
// check buffer overrun for stream limit
if (pstr->strstart >= pstr->strend)
return imgeShort;
// set stream pointer and maximum size
pstr->strbase=di.data+pstr->strstart;
pstr->strsize=pstr->strend-pstr->strstart;
// resize stream; find the end of stream#0; if stream#0 is not present gap stream starts with stream#1
int semode=align && (pi->flag & CAPS_BF_GP0);
int res=FindGapStreamEnd(pstr, semode);
return res;
}
// parse current gap stream until gap end reached and next stream starts
int CCapsImageStd::FindGapStreamEnd(PIMAGESTREAMINFO pstr, int next)
{
uint8_t *buf=di.data;
int end=0;
uint32_t ofs;
for (ofs=pstr->strstart; !end && ofs < pstr->strend; ) {
int code=buf[ofs++];
// read code, sizeof(count), count
int vc=code >> CAPS_SIZE_S;
code&=CAPS_DATAMASK;
uint32_t count;
if (vc) {
if (ofs+vc > pstr->strend)
return imgeTrackData;
count=ReadValue(buf+ofs, vc);
ofs+=vc;
} else
count=0;
switch (code) {
// end of stream
case cpgapEnd:
end=1;
break;
// skip total bitcount setting, already at next element
case cpgapCount:
break;
// add sample data size and go to next element
case cpgapData:
ofs += trackbuf.CalculateByteSize(count);
break;
// no other data is allowed
default:
return imgeTrackStream;
}
}
// no cpgapEnd encountered, stream error
if (!end)
return imgeTrackData;
// update stream start/end position
if (next)
pstr->strstart=ofs;
else
pstr->strend=ofs;
// check buffer overrun for stream limit
if (pstr->strstart >= pstr->strend)
return imgeShort;
// update stream pointer and maximum size
pstr->strbase=di.data+pstr->strstart;
pstr->strsize=pstr->strend-pstr->strstart;
return imgeOk;
}
// reset stream processing
int CCapsImageStd::ResetStream(PIMAGESTREAMINFO pstr)
{
// set first stream data element
pstr->strofs=0;
// no stream errors
pstr->readresult=imgeOk;
pstr->readend=0;
pstr->readvalue=0;
// reset sample and data element streaming
pstr->setencmode=isiemRaw;
pstr->streambc=0;
pstr->samplebc=0;
pstr->remstreambc=0;
pstr->remsamplebc=0;
pstr->sampleofs=0;
pstr->samplemask=0;
pstr->samplebase=0;
pstr->prcbitpos=0;
pstr->prcrembc=0;
pstr->prcskipbc=0;
pstr->prcencstate=1;
pstr->prcwritebc=0;
pstr->loopofs=0;
pstr->loopsize=0;
pstr->looptype=isiltNone;
pstr->esfixbc=0;
pstr->esloopbc=0;
pstr->scenable=0;
pstr->scofs=0;
pstr->scmul=0;
// stop if stream is disabled
if (!pstr->strsize) {
pstr->readend=1;
return imgeOk;
}
// decode the first stream sample data, set correct encoding mode
int res=GetSample(pstr);
return res;
}
// initialize sample reading for a new sample, return true for any processing change or stream end
int CCapsImageStd::ReadSampleInit(PIMAGESTREAMINFO pstr)
{
// signal on stream end
if (pstr->readend)
return 1;
// support sample looping if looping is allowed and last sample size is undefined
if (pstr->allowloop && !pstr->streambc) {
// set countdown values same as the original sample size
pstr->remstreambc=pstr->samplebc;
pstr->remsamplebc=pstr->samplebc;
// reset reading the actual sample data part
pstr->sampleofs=0;
pstr->samplemask=0x80;
} else {
// get current encoding mode
int setencmode=pstr->setencmode;
int actenctype=pstr->actenctype;
// get next sample, signal on error
if (GetSample(pstr) != imgeOk)
return 1;
// signal on stream end
if (pstr->readend)
return 1;
// signal on any encoding change
if (pstr->setencmode != setencmode)
return 1;
if (pstr->actenctype != actenctype)
return 1;
}
// no processing change required
return 0;
}
// read sample data from an ipf stream
int CCapsImageStd::ReadSample(PIMAGESTREAMINFO pstr, int maxbc)
{
// number of bits read
int actbc=0;
// value read
uint32_t readvalue=0;
// process remaining bits from stream
while (maxbc > 0) {
// get new sample when needed
if (!pstr->remstreambc)
if (ReadSampleInit(pstr))
break;
// restore bitstream state
uint32_t remstreambc=pstr->remstreambc;
uint32_t remsamplebc=pstr->remsamplebc;
// stop on invalid sample state
if (!remsamplebc)
break;
// read next sample if stream is empty, e.g. loop size has been changed
if (!remstreambc)
continue;
uint32_t sampleofs=pstr->sampleofs;
uint32_t samplemask=pstr->samplemask;
uint32_t sampledata=pstr->samplebase[sampleofs];
// read remaining bits from sample
while (maxbc > 0) {
// add new bit
readvalue<<=1;
if (sampledata & samplemask)
readvalue|=1;
// bit added
actbc++;
maxbc--;
// one less sample bit to process
if (!--remsamplebc) {
// reset the sample data if all sample bits have been read
remsamplebc=pstr->samplebc;
sampleofs=0;
samplemask=0x80;
sampledata=pstr->samplebase[sampleofs];
} else {
// set next bit position to read
if (!(samplemask>>=1)) {
sampleofs++;
samplemask=0x80;
sampledata=pstr->samplebase[sampleofs];
}
}
// stop reading the current sample if complete data size has been read
if (!--remstreambc)
break;
}
// save bitstream state
pstr->remstreambc=remstreambc;
pstr->remsamplebc=remsamplebc;
pstr->sampleofs=sampleofs;
pstr->samplemask=samplemask;
}
// store value read
pstr->readvalue=readvalue;
return actbc;
}
// get next data element sample from the ipf stream
int CCapsImageStd::GetSample(PIMAGESTREAMINFO pstr)
{
// reset reading the actual sample data part
pstr->sampleofs=0;
pstr->samplemask=0x80;
// undefined bitcount
pstr->streambc=0;
pstr->remstreambc=0;
int res;
// stream encoding specific ipf stream processing
switch (pstr->actenctype) {
// physical encodings supported
case cpencMFM:
// default to encoded stream
pstr->setencmode=isiemType;
if (pstr->strtype == isitData)
res=GetSampleData(pstr);
else
res=GetSampleGap(pstr);
break;
// raw should only be used for testing track data, not a supported release type
case cpencRaw:
// default to unencoded stream
pstr->setencmode=isiemRaw;
if (pstr->strtype == isitData)
res=GetSampleRaw(pstr);
else
res=GetSampleGap(pstr);
break;
default:
res=imgeIncompatible;
break;
}
// set loop point, stop streaming on any error encountered
if (res == imgeOk)
GetLoop(pstr);
else {
pstr->readresult=res;
pstr->readend=1;
}
return res;
}
// get next data element sample from an ipf raw stream
int CCapsImageStd::GetSampleRaw(PIMAGESTREAMINFO pstr)
{
// check current offset in ipf encoding
uint32_t ofs=pstr->strofs;
if (ofs >= pstr->strsize)
return imgeTrackData;
// get stream code and sizeof(count)
uint8_t *buf=pstr->strbase;
int code=buf[ofs++];
int vc=code >> CAPS_SIZE_S;
code&=CAPS_DATAMASK;
uint32_t count, bitcount;
// read the value of the count parameter
if (vc) {
if (ofs+vc > pstr->strsize)
return imgeTrackData;
count=ReadValue(buf+ofs, vc);
ofs+=vc;
} else
count=0;
switch (code) {
// stream finished
case cpdatEnd:
if (count)
return imgeTrackData;
pstr->readend=1;
bitcount=0;
break;
// raw data sample, size in bytes
case cpdatRaw:
if (!count)
return imgeTrackData;
if (ofs+count > pstr->strsize)
return imgeTrackData;
bitcount=count << 3;
break;
// any other data type is an error
default:
return imgeTrackStream;
}
// next offset in ipf stream after the current sample
pstr->strofs=ofs+count;
// position of the sample data, left justified, starting at bit#7
pstr->samplebase=buf+ofs;
// set all sample counters to a simple countdown for the whole sample
pstr->samplebc=bitcount;
pstr->remstreambc=bitcount;
pstr->remsamplebc=bitcount;
return imgeOk;
}
// get next data element sample from an ipf gap stream
int CCapsImageStd::GetSampleGap(PIMAGESTREAMINFO pstr)
{
// get current ipf encoding
uint32_t ofs=pstr->strofs;
uint8_t *buf=pstr->strbase;
uint32_t bitcount, bytecount;
while (1) {
// check offset to be within stream boundaries
if (ofs >= pstr->strsize)
return imgeTrackData;
// get stream code and sizeof(count)
int code=buf[ofs++];
int vc=code >> CAPS_SIZE_S;
code&=CAPS_DATAMASK;
uint32_t count;
// read the value of the count parameter
if (vc) {
if (ofs+vc > pstr->strsize)
return imgeTrackData;
count=ReadValue(buf+ofs, vc);
ofs+=vc;
} else
count=0;
// support data size in bits or bytes
if (pstr->sizemodebit) {
bitcount=count;
bytecount = trackbuf.CalculateByteSize(bitcount);
} else {
bytecount=count;
bitcount=bytecount << 3;
}
switch (code) {
// stream finished
case cpgapEnd:
if (bitcount)
return imgeTrackData;
pstr->readend=1;
break;
// set total sample size
case cpgapCount:
pstr->streambc=bitcount;
continue;
// data sample
case cpgapData:
if (!bitcount)
return imgeTrackData;
if (ofs+bytecount > pstr->strsize)
return imgeTrackData;
break;
// any other data type is an error
default:
return imgeTrackStream;
}
// stop processing after complete data element or stream end
break;
}
// next offset in ipf stream after the current sample
pstr->strofs=ofs+bytecount;
// position of the sample data, left justified, starting at bit#7
pstr->samplebase=buf+ofs;
// set all sample counters to a simple countdown for the whole sample
pstr->samplebc=bitcount;
pstr->remsamplebc=bitcount;
// set total data size to sample size if undefined, or use the defined data size
pstr->remstreambc=pstr->streambc ? pstr->streambc : bitcount;
return imgeOk;
}
// get next data element sample from an ipf data stream
int CCapsImageStd::GetSampleData(PIMAGESTREAMINFO pstr)
{
// get current ipf encoding
uint32_t ofs=pstr->strofs;
uint8_t *buf=pstr->strbase;
uint32_t bitcount, bytecount;
while (1) {
// check offset to be within stream boundaries
if (ofs >= pstr->strsize)
return imgeTrackData;
// get stream code and sizeof(count)
int code=buf[ofs++];
int vc=code >> CAPS_SIZE_S;
code&=CAPS_DATAMASK;
uint32_t count;
// read the value of the count parameter
if (vc) {
if (ofs+vc > pstr->strsize)
return imgeTrackData;
count=ReadValue(buf+ofs, vc);
ofs+=vc;
} else
count=0;
// support data size in bits or bytes
if (pstr->sizemodebit) {
bitcount=count;
bytecount = trackbuf.CalculateByteSize(bitcount);
} else {
bytecount=count;
bitcount=bytecount << 3;
}
switch (code) {
// stream finished
case cpdatEnd:
if (bitcount)
return imgeTrackData;
pstr->readend=1;
break;
// mark sample
case cpdatMark:
// switch to unencoded stream
pstr->setencmode=isiemRaw;
// data sample use default, encoded stream
case cpdatData:
case cpdatGap:
if (!bitcount)
return imgeTrackData;
if (ofs+bytecount > pstr->strsize)
return imgeTrackData;
break;
// weak bits
case cpdatFData:
pstr->setencmode=isiemWeak;
break;
// any other data type is an error
default:
return imgeTrackStream;
}
// stop processing after complete data element or stream end
break;
}
// handle normal or weak data
if (pstr->setencmode != isiemWeak) {
// next offset in ipf stream after the current sample
pstr->strofs=ofs+bytecount;
// position of the sample data, left justified, starting at bit#7
pstr->samplebase=buf+ofs;
// set all sample counters to a simple countdown for the whole sample
pstr->samplebc=bitcount;
pstr->remsamplebc=bitcount;
} else {
// next offset in ipf stream, no sample present for weak data
pstr->strofs=ofs;
// position of the weak sample data, left justified, starting at bit#7
pstr->samplebase=pstr->weakdata;
// set all sample counters to a simple countdown for a 8 bit sample
pstr->samplebc=8;
pstr->remsamplebc=8;
// set weak data
pstr->weakdata[0]=0;
}
// set total data size to sample size if undefined, or use the defined data size
pstr->remstreambc=pstr->streambc ? pstr->streambc : bitcount;
return imgeOk;
}
// read ipf stream and encode to physical recording
int CCapsImageStd::ProcessStream(PIMAGESTREAMINFO pstr, uint32_t bitpos, int maxbc, int skipbc, int encnew)
{
// set stream process state
pstr->prcbitpos=bitpos;
pstr->prcrembc=maxbc;
pstr->prcskipbc=skipbc;
pstr->prcencstate=encnew;
pstr->prcwritebc=0;
// process remaining bits
while (pstr->prcrembc > 0) {
// stop if ipf stream is over
if (pstr->readend)
break;
// process by currently selected encoding mode
switch (pstr->setencmode) {
// raw, no encoding
case isiemRaw:
ProcessStreamRaw(pstr);
break;
// encoding specified by the data encoding type selected
case isiemType:
switch (pstr->actenctype) {
// generic MFM
case cpencMFM:
ProcessStreamMFM(pstr);
break;
// raw data
case cpencRaw:
ProcessStreamRaw(pstr);
break;
default:
return imgeIncompatible;
}
break;
// weak bits
case isiemWeak:
ProcessStreamWeak(pstr);
break;
default:
return imgeGeneric;
}
}
return pstr->readresult;
}
// read ipf stream and write as raw track data
void CCapsImageStd::ProcessStreamRaw(PIMAGESTREAMINFO pstr)
{
// get process state
uint32_t bitpos=pstr->prcbitpos;
int maxbc=pstr->prcrembc;
int skipbc=pstr->prcskipbc;
int actbc=0;
// process remaining bits
while (maxbc > 0) {
// read the ipf stream
int readbc=ReadSample(pstr, rawreadlen);
// number of bits not read/missing
int diffbc=rawreadlen-readbc;
// write track data if anything was read
if (readbc > 0) {
// number of bits to be written
int writebc=readbc;
// skip bits if needed and write bitfield
if (writebc > skipbc) {
writebc-=skipbc;
skipbc=0;
// get value read
uint32_t value=pstr->readvalue;
// if less bits to write than available, right align field to bit#0
if (writebc > maxbc) {
value >>= (writebc-maxbc);
writebc=maxbc;
}
trackbuf.WriteBitWrap(bitpos, value, writebc);
// next write position
actbc+=writebc;
maxbc-=writebc;
bitpos+=writebc;
// handle track buffer wrap around (disk rotation)
if (bitpos >= di.trackbc)
bitpos-=di.trackbc;
} else
skipbc-=writebc;
}
// stop processing if encoding method changed or stream stopped
if (diffbc)
break;
}
// set the type of the very first data
if (!pstr->prcwritebc && pstr->prcencstate && actbc)
di.block[pstr->actblock].fdenc=ibieRaw;
// save process state
pstr->prcbitpos=bitpos;
pstr->prcrembc=maxbc;
pstr->prcskipbc=skipbc;
pstr->prcwritebc+=actbc;
}
// read ipf stream and write as mfm track data
void CCapsImageStd::ProcessStreamMFM(PIMAGESTREAMINFO pstr)
{
// get process state
uint32_t bitpos=pstr->prcbitpos;
int maxbc=pstr->prcrembc;
int skipbc=pstr->prcskipbc;
int actbc=0;
// ignore last bit written if encoding the first bit and new encoding, use last bit otherwise
uint32_t lv;
if (!pstr->prcwritebc && pstr->prcencstate)
lv=0;
else {
uint32_t bp=(bitpos ? bitpos : di.trackbc)-1;
lv = trackbuf.ReadBit(bp);
}
// process remaining bits
while (maxbc > 0) {
// read the ipf stream
int readbc=ReadSample(pstr, mfmreadlen);
// number of bits not read/missing
int diffbc=mfmreadlen-readbc;
// write track data if anything was read
if (readbc > 0) {
// number of mfm encoded bits to be written
int writebc=readbc << 1;
// skip bits if needed and write bitfield
if (writebc > skipbc) {
writebc-=skipbc;
skipbc=0;
// calculate the number of missing bits for indexing the mfm code table
// index size-number of bits to be encoded to reach the target encoded length
int encodebc=mfmreadlen-((writebc+1) >> 1);
// get value read
uint32_t value=pstr->readvalue;
// add 0 bits for any missing data bits; get correct table index
value <<= encodebc;
// convert to mfm
value=CDiskEncoding::mfmcode[value & mfmindexmask];
// fix mfm encoding if last bit written is 1
if (lv & 1)
value &= mfmmsbclear;
// right align all valid bits to bit#0; size doubled since value is in mfm now
value >>= (encodebc << 1);
// if less bits to write than available, right align field to bit#0
if (writebc > maxbc) {
value >>= (writebc-maxbc);
writebc=maxbc;
}
// save last value writen
lv=value;
// write value as bitfield
trackbuf.WriteBitWrap(bitpos, value, writebc);
// next write position
actbc+=writebc;
maxbc-=writebc;
bitpos+=writebc;
// handle track buffer wrap around (disk rotation)
if (bitpos >= di.trackbc)
bitpos-=di.trackbc;
} else
skipbc-=writebc;
}
// stop processing if encoding method changed or stream stopped
if (diffbc)
break;
}
// set the type of the very first data
if (!pstr->prcwritebc && pstr->prcencstate && actbc)
di.block[pstr->actblock].fdenc=ibieMFM;
// save process state
pstr->prcbitpos=bitpos;
pstr->prcrembc=maxbc;
pstr->prcskipbc=skipbc;
pstr->prcwritebc+=actbc;
}
// read ipf stream and write as weak track data
void CCapsImageStd::ProcessStreamWeak(PIMAGESTREAMINFO pstr)
{
// get process state
uint32_t bitpos=pstr->prcbitpos;
int maxbc=pstr->prcrembc;
int skipbc=pstr->prcskipbc;
int actbc=0;
// process remaining bits
if (maxbc > 0) {
// get weak field size without encoding
int writebc=pstr->remstreambc;
// skip reading the sample associated with this field and get the next sample
ReadSampleInit(pstr);
// calculate field size after encoding
switch (pstr->actenctype) {
case cpencMFM:
writebc <<= 1;
break;
}
// skip bits if needed and write bitfield
if (writebc > skipbc) {
writebc-=skipbc;
skipbc=0;
// limit to available bit size
if (writebc > maxbc)
writebc=maxbc;
// mark weak data, use group#0 for IPF image
DiskDataMark ddm;
ddm.group = 0;
ddm.position=bitpos;
ddm.size=writebc;
AddFD(di.pdt, &ddm, 1, DEF_FDALLOC);
// clear field
trackbuf.ClearBitWrap(bitpos, writebc);
// next write position
actbc+=writebc;
maxbc-=writebc;
bitpos+=writebc;
// handle track buffer wrap around (disk rotation)
if (bitpos >= di.trackbc)
bitpos-=di.trackbc;
} else
skipbc-=writebc;
}
// set the type of the very first data
if (!pstr->prcwritebc && pstr->prcencstate && actbc)
di.block[pstr->actblock].fdenc=ibieWeak;
// save process state
pstr->prcbitpos=bitpos;
pstr->prcrembc=maxbc;
pstr->prcskipbc=skipbc;
pstr->prcwritebc+=actbc;
}
// calculate the complete stream size encoded
int CCapsImageStd::CalculateStreamSize(PIMAGESTREAMINFO pstr)
{
// find loop point and loop type
int res=FindLoopPoint(pstr);
if (res != imgeOk)
return res;
// use a copy of the stream to parse data
ImageStreamInfo isi=*pstr;
// allbc: size without looping
// fixbc: fixed bits
// loopbc: loop bits
int fixbc=0, loopbc=0;
// sum all bit counts
while (!isi.readend) {
switch (isi.looptype) {
// no loop
case isiltNone:
fixbc+=GetEncodedSize(&isi, isi.remstreambc);
break;
// auto-generated or stream loop
case isiltAuto:
case isiltStream:
fixbc+=GetEncodedSize(&isi, isi.remstreambc);
if (isi.strofs == isi.loopofs)
loopbc+=GetEncodedSize(&isi, isi.samplebc);
break;
default:
return imgeGeneric;
}
// get next sample
if (GetSample(&isi) != imgeOk)
return imgeGeneric;
}
// save results
pstr->esfixbc=fixbc;
pstr->esloopbc=loopbc;
return imgeOk;
}
// calculate data size after physical encoding
int CCapsImageStd::GetEncodedSize(PIMAGESTREAMINFO pstr, int bitcnt)
{
// process by currently selected and active encoding mode
switch (pstr->setencmode) {
case isiemType:
case isiemWeak:
switch (pstr->actenctype) {
case cpencMFM:
bitcnt <<= 1;
break;
}
break;
}
return bitcnt;
}
// find the loop point in a stream and check for errors
int CCapsImageStd::FindLoopPoint(PIMAGESTREAMINFO pstr)
{
// no loop point if sample looping is not allowed
if (!pstr->allowloop) {
pstr->loopofs=0;
pstr->loopsize=0;
pstr->looptype=isiltNone;
return imgeOk;
}
// use a copy of the stream to parse data
ImageStreamInfo isi=*pstr;
// no loop point
uint32_t loopofs=0;
int loopsize=0, loopfound=0, cnt=0;
while (!isi.readend) {
uint32_t ofs=isi.strofs;
int bc=isi.samplebc;
switch (isi.strtype) {
// loop point is the last data in forward gap stream; any data after a loop is invalid
case isitGap0:
if (loopfound)
return imgeGeneric;
loopofs=ofs;
loopsize=bc;
break;
// loop point is the first data in backward gap stream; any loop after first data is invalid
case isitGap1:
if (!cnt) {
loopofs=ofs;
loopsize=bc;
} else
if (!isi.streambc)
return imgeGeneric;
break;
}
// only allow 1 loop
if (!isi.streambc) {
if (loopfound)
return imgeGeneric;
loopfound++;
}
cnt++;
// get next sample
if (GetSample(&isi) != imgeOk)
return imgeGeneric;
}
// set loop point information
pstr->loopofs=loopofs;
pstr->loopsize=loopsize;
if (loopsize)
pstr->looptype=loopfound ? isiltStream : isiltAuto;
else
pstr->looptype=isiltNone;
return imgeOk;
}
// encode a complete block
int CCapsImageStd::ProcessBlock(int blk, uint32_t bitpos, int datasize, int gapsize)
{
int res;
// set encoding parameters
di.encbitpos=bitpos;
di.encwritebc=0;
di.encgsvalid=0;
di.encgapsplit=0;
// check parameters
if (blk<0 || blk>=di.blockcount || datasize<0 || gapsize<0)
return imgeGeneric;
if (blk >= di.pdt->sipsize)
return imgeGeneric;
// set encoding information
di.block[blk].fdenc=ibieNA;
di.block[blk].fdbitpos=bitpos;
PDISKSECTORINFO si=di.pdt->sip+blk;
si->descdatasize=di.block[blk].blockbits;
si->descgapsize=di.block[blk].gapbits;
si->celltype=di.block[blk].celltype;
si->enctype=di.block[blk].enctype;
// create block data
si->datastart=di.encbitpos;
si->datasize=datasize;
res=ProcessBlockData(blk, datasize);
if (res != imgeOk)
return res;
// create gap data
si->gapstart=di.encbitpos;
si->gapsize=gapsize;
res=ProcessBlockGap(blk, gapsize);
if (res != imgeOk)
return res;
return imgeOk;
}
// encode block data
int CCapsImageStd::ProcessBlockData(int blk, int datasize)
{
// stop if no data area
if (!datasize)
return imgeOk;
int res;
ImageStreamInfo dsi;
// initialize the data stream
res=InitStream(&dsi, isitData, blk);
if (res != imgeOk)
return res;
// encode block data
res=ProcessStream(&dsi, di.encbitpos, datasize, 0, !di.encwritebc);
if (res != imgeOk)
return res;
// error if the requested data size was not filled
if (dsi.prcwritebc != datasize)
return imgeGeneric;
// update bit position and bits written
di.encbitpos=dsi.prcbitpos;
di.encwritebc+=dsi.prcwritebc;
return imgeOk;
}
// encode gap data
int CCapsImageStd::ProcessBlockGap(int blk, int gapsize)
{
// stop if no gap area
if (!gapsize)
return imgeOk;
int res;
ImageStreamInfo gsi0, gsi1;
// initialize the forward gap stream
res=InitStream(&gsi0, isitGap0, blk);
if (res != imgeOk)
return res;
res=CalculateStreamSize(&gsi0);
if (res != imgeOk)
return res;
// initialize the backward gap stream
res=InitStream(&gsi1, isitGap1, blk);
if (res != imgeOk)
return res;
res=CalculateStreamSize(&gsi1);
if (res != imgeOk)
return res;
// seN true if stream is enabled
int se0=gsi0.esfixbc || gsi0.esloopbc;
int se1=gsi1.esfixbc || gsi1.esloopbc;
// number of enabled streams
int secnt=0;
if (se0)
secnt++;
if (se1)
secnt++;
// tlN true if stream has a real loop point defined (not generated)
int tl0=gsi0.esloopbc && (gsi0.looptype == isiltStream);
int tl1=gsi1.esloopbc && (gsi1.looptype == isiltStream);
// number of streams with a real loop point
int tlcnt=0;
if (tl0)
tlcnt++;
if (tl1)
tlcnt++;
PDISKSECTORINFO si=di.pdt->sip+blk;
// set size mode of the forward stream
if (tl0)
si->gapws0mode=csiegmResize;
else
si->gapws0mode=(gsi0.esloopbc) ? csiegmAuto : csiegmFixed;
// set size mode of the backward stream
if (tl1)
si->gapws1mode=csiegmResize;
else
si->gapws1mode=(gsi1.esloopbc) ? csiegmAuto : csiegmFixed;
// encode gap
switch (secnt) {
// error if gap area is present, but there is no gap stream at all
case 0:
return imgeGeneric;
// 1 stream enabled
case 1:
res=ProcessBlockGap((se0 ? &gsi0 : &gsi1), gapsize);
break;
// 2 streams enabled, modify 1 stream if 1 true loop point is defined, otherwise modify both
case 2:
if (tlcnt == 1)
res=ProcessBlockGap(&gsi0, &gsi1, gapsize, (tl0 ? 0 : 1));
else
res=ProcessBlockGap(&gsi0, &gsi1, gapsize);
break;
}
return res;
}
// encode gap data with 1 gap stream present
int CCapsImageStd::ProcessBlockGap(PIMAGESTREAMINFO pg, int gapsize)
{
// stop if no gap area
if (!gapsize)
return imgeOk;
int skip=0;
if (pg->esfixbc >= gapsize) {
// fixed size is enough to fill the gap; disable loop
SetLoop(pg, 0);
// if backwards stream, skip unneeded bits
if (pg->strtype == isitGap1)
skip=pg->esfixbc-gapsize;
} else {
// loop required to fill the gap; error if loop point is not found
if (!pg->esloopbc)
return imgeGeneric;
// number of bits to be generated using the loop
int miss=gapsize-pg->esfixbc;
// number of new samples required to generate the bits
int scnt=miss/pg->esloopbc;
// partial new sample size, 0 if all samples are complete
int smod=miss%pg->esloopbc;
// if partial sample is required
if (smod) {
// add another sample
scnt++;
// if backwards stream, skip bits not required from the added sample
if (pg->strtype == isitGap1)
skip=pg->esloopbc-smod;
}
// enable loop
SetLoop(pg, scnt);
}
// encode gap data
int res=ProcessStream(pg, di.encbitpos, gapsize, skip, !di.encwritebc);
if (res != imgeOk)
return res;
// error if the requested data size was not filled
if (pg->prcwritebc != gapsize)
return imgeGeneric;
// update bit position and bits written
di.encbitpos=pg->prcbitpos;
di.encwritebc+=pg->prcwritebc;
if (pg->strtype == isitGap0)
di.pdt->sip[pg->actblock].gapsizews0=gapsize;
else
di.pdt->sip[pg->actblock].gapsizews1=gapsize;
return imgeOk;
}
// encode gap data with 2 gap streams present, 2 real loop points, or none
int CCapsImageStd::ProcessBlockGap(PIMAGESTREAMINFO pg0, PIMAGESTREAMINFO pg1, int gapsize)
{
int gs0=pg0->esfixbc;
int gs1=pg1->esfixbc;
int fs=gs0+gs1;
if (fs >= gapsize) {
// fixed size would fill the gap; number of extra bits not needed
int rem=fs-gapsize;
int rem0=rem >> 1;
int rem1=rem-rem0;
// remove bits evenly as long as it is possible, then just remove from any stream that has enough bits
while (rem0 || rem1) {
if (gs0 >= rem0) {
gs0-=rem0;
rem0=0;
} else {
rem1+=rem0-gs0;
rem0=0;
gs0=0;
}
if (gs1 >= rem1) {
gs1-=rem1;
rem1=0;
} else {
rem0+=rem1-gs1;
rem1=0;
gs1=0;
}
}
} else {
// loop required to fill the gap; error if loop point is not found in either stream
if (!pg0->esloopbc && !pg1->esloopbc)
return imgeGeneric;
// number of missing bits to fill the gap
int miss=gapsize-fs;
int miss0=miss >> 1;
// if last block and the loop would pass the index (ie track gap at index) re-sync to index
if (pg0->actblock == di.blockcount-1) {
uint32_t sbp=di.encbitpos % di.singletrackbc;
if (sbp+gs0 <= di.singletrackbc)
if (sbp+gs0+miss >= di.singletrackbc)
miss0=di.singletrackbc-(sbp+gs0);
}
int miss1=miss-miss0;
// add bits evenly if both streams have loop points, otherwise just use the one with loop enabled
while (miss0 || miss1) {
if (pg0->esloopbc) {
gs0+=miss0;
miss0=0;
} else {
miss1+=miss0;
miss0=0;
}
if (pg1->esloopbc) {
gs1+=miss1;
miss1=0;
} else {
miss0+=miss1;
miss1=0;
}
}
}
// check if selected stream sizes would fill the entire gap
if (gs0+gs1 != gapsize)
return imgeGeneric;
// encode forward stream
int res=ProcessBlockGap(pg0, gs0);
if (res != imgeOk)
return res;
// set gap split position
di.encgsvalid=1;
di.encgapsplit=di.encbitpos;
// encode backwards stream
ProcessBlockGap(pg1, gs1);
if (res != imgeOk)
return res;
return imgeOk;
}
// encode gap data with 2 gap streams present, 1 real loop point
int CCapsImageStd::ProcessBlockGap(PIMAGESTREAMINFO pg0, PIMAGESTREAMINFO pg1, int gapsize, int loopsel)
{
int gs0=pg0->esfixbc;
int gs1=pg1->esfixbc;
// fixed size stream uses its own size, the stream with the loop fills the remainder
if (loopsel) {
// 0: fix, 1: loop
if (gs0 > gapsize)
gs0=gapsize;
gs1=gapsize-gs0;
} else {
// 0: loop, 1: fix
if (gs1 > gapsize)
gs1=gapsize;
gs0=gapsize-gs1;
}
// encode forward stream
int res=ProcessBlockGap(pg0, gs0);
if (res != imgeOk)
return res;
// set gap split position
di.encgsvalid=1;
di.encgapsplit=di.encbitpos;
// encode backwards stream
ProcessBlockGap(pg1, gs1);
if (res != imgeOk)
return res;
return imgeOk;
}
// set the selected sample loop point to a fixed size
void CCapsImageStd::SetLoop(PIMAGESTREAMINFO pg, int value)
{
switch (pg->looptype) {
// no loop point, disable sample size change
case isiltNone:
pg->scenable=0;
break;
// disable/enable size change at the loop point
case isiltAuto:
if (value) {
pg->scenable=1;
pg->scofs=pg->loopofs;
pg->scmul=value;
} else
pg->scenable=0;
break;
// change loop point to fixed size sample
case isiltStream:
pg->scenable=1;
pg->scofs=pg->loopofs;
pg->scmul=value;
break;
}
// update loop, just in case the current first sample is the loop point
GetLoop(pg);
}
// update loop point if enabled
void CCapsImageStd::GetLoop(PIMAGESTREAMINFO pg)
{
// stop, if not enabled
if (!pg->scenable)
return;
// stop if not a loop point
if (pg->strofs != pg->scofs)
return;
// add new samples
pg->remstreambc+=pg->scmul*pg->samplebc;
// make the sample size fixed
pg->streambc=pg->remstreambc;
}
// fix mfm encoding where needed
void CCapsImageStd::MFMFixup()
{
// process all blocks
for (int blk=0; blk < di.blockcount; blk++) {
PIMAGEBLOCKINFO pi=di.block+blk;
// don't fix if not MFM
if (pi->fdenc != ibieMFM)
continue;
// get bit before the first data bit written
uint32_t lbp=(pi->fdbitpos ? pi->fdbitpos : di.trackbc)-1;
int lv = trackbuf.ReadBit(lbp);
// mfm encoding assumed the last bit to be 0; fix if it is 1
if (lv)
trackbuf.ClearBit(pi->fdbitpos, 1);
}
}
| 21.333098 | 112 | 0.676396 | [
"vector"
] |
21104a4af2c980c9f66e9eee939ec8165ffe1c69 | 8,487 | cpp | C++ | src/messages.cpp | Nakeib/RonClient | 9e816c580ec2a6f1b15fdefd8e15ad62647ca29f | [
"MIT"
] | 11 | 2020-11-07T19:35:24.000Z | 2021-08-19T12:25:27.000Z | src/messages.cpp | Nakeib/RonClient | 9e816c580ec2a6f1b15fdefd8e15ad62647ca29f | [
"MIT"
] | null | null | null | src/messages.cpp | Nakeib/RonClient | 9e816c580ec2a6f1b15fdefd8e15ad62647ca29f | [
"MIT"
] | 5 | 2020-11-06T20:52:11.000Z | 2021-02-25T11:02:31.000Z | /* -------------------------------------------------------------------------- */
/* ------------- RonClient --- Oficial client for RonOTS servers ------------ */
/* -------------------------------------------------------------------------- */
#include "messages.h"
#include "allocator.h"
#include "game.h"
#include "tools.h"
// ---- Message ---- //
Message::Message(TextString txt, int ltime) : text(txt), maxLiveTime(ltime) {
liveTime = 0;
}
Message::~Message() { }
// ---- SystemMessage ---- //
SystemMessage::SystemMessage(TextString txt, int ltime, float pX, float pY) : Message(txt, ltime), posX(pX), posY(pY) { }
SystemMessage::~SystemMessage() { }
// ---- TextMessage ---- //
TextMessage::TextMessage(TextString txt, int ltime, Position ps, bool mlvl) : Message(txt, ltime), pos(ps), multiLevel(mlvl) { }
TextMessage::~TextMessage() { }
// ---- AnimatedMessage ---- //
AnimatedMessage::AnimatedMessage(TextString txt, int ltime, Position ps, float offX, float offY) : Message(txt, ltime), pos(ps), offsetX(offX), offsetY(offY) { }
AnimatedMessage::~AnimatedMessage() { }
// ---- Messages ---- //
MessagesList Messages::messages;
int Messages::threads = 0;
MUTEX Messages::lockMessages;
Messages::Messages() { }
Messages::~Messages() { }
void Messages::AddMessage(Message* message) {
LOCKCLASS lockClass(lockMessages);
if (!message) {
Logger::AddLog("Messages::AddMessage()", "Pointer to message is NULL!", LOG_WARNING);
return;
}
MessagesList::iterator it = std::find(messages.begin(), messages.end(), message);
if (it != messages.end()) {
Logger::AddLog("Messages::AddMessage()", "Message already in list!", LOG_WARNING);
return;
}
else {
SystemMessage* msg = dynamic_cast<SystemMessage*>(message);
if (msg) {
MessagesList toDelete;
int number = 0;
for (MessagesList::reverse_iterator rit = messages.rbegin(); rit != messages.rend(); rit++) {
SystemMessage* smsg = dynamic_cast<SystemMessage*>(*rit);
if (smsg && msg->posX == smsg->posX && msg->posY == smsg->posY) {
if (number < 1)
number++;
else
toDelete.push_back((Message*)smsg);
}
}
for (it = toDelete.begin(); it != toDelete.end(); it++)
RemoveMessage(*it);
}
messages.push_back(message);
}
}
void Messages::RemoveMessage(Message* message) {
LOCKCLASS lockClass(lockMessages);
if (!message) {
Logger::AddLog("Messages::RemoveMessage()", "Pointer to message is NULL!", LOG_WARNING);
return;
}
MessagesList::iterator it = std::find(messages.begin(), messages.end(), message);
if (it != messages.end()) {
messages.erase(it);
delete_debug(message, M_PLACE);
}
else
Logger::AddLog("Messages::RemoveMessage()", "Message not in list!", LOG_WARNING);
}
void Messages::ClearMessages() {
LOCKCLASS lockClass(lockMessages);
MessagesList::iterator it = messages.begin();
for (it; it != messages.end(); it++) {
Message* message = *it;
delete_debug(message, M_PLACE);
}
messages.clear();
}
void Messages::CheckMessages(Game* game) {
if (threads > 0)
return;
threads++;
while(game->GetGameState() == GAME_LOGGEDTOGAME) {
lockMessages.lock();
MessagesList toDelete;
MessagesList::iterator it = messages.begin();
for (it; it != messages.end(); it++) {
Message* message = *it;
if (message && message->liveTime + 10 <= message->maxLiveTime)
message->liveTime += 10;
else
toDelete.push_back(message);
}
for (it = toDelete.begin(); it != toDelete.end(); it++) {
Message* message = *it;
RemoveMessage(message);
}
lockMessages.unlock();
Sleep(10);
}
threads--;
}
void Messages::PrintMessages(AD2D_Window* gfx, AD2D_Font* font, Position pos, unsigned char level, float x, float y, float zoom) {
LOCKCLASS lockClass(lockMessages);
float fontSize = Game::options.textSize;
std::map<const Position, float> textOffset;
std::map<std::pair<float, float>, int> sysLine;
std::map<std::pair<float, float>, int> sysLines;
MessagesList textMessages;
MessagesList animMessages;
MessagesList sysMessages;
for (MessagesList::iterator it = messages.begin(); it != messages.end(); it++) {
Message* message = *it;
TextMessage* txtMsg = dynamic_cast<TextMessage*>(message);
AnimatedMessage* animMsg = dynamic_cast<AnimatedMessage*>(message);
SystemMessage* sysMsg = dynamic_cast<SystemMessage*>(message);
if (txtMsg) {
if (Game::options.flyingSpeed != 0)
textMessages.push_back(txtMsg);
else
textMessages.push_front(txtMsg);
}
else if (animMsg)
animMessages.push_back(animMsg);
else if (sysMsg) {
std::vector<std::pair<unsigned int, TextString> > lines = DivideText(sysMsg->text);
sysLines[std::pair<float, float>(sysMsg->posX, sysMsg->posY)] += lines.size();
sysMessages.push_front(sysMsg);
}
}
MessagesList::iterator it;
for (it = textMessages.begin(); it != textMessages.end(); it++) {
Message* message = *it;
TextMessage* txtMsg = dynamic_cast<TextMessage*>(message);
if (txtMsg && (txtMsg->pos.z == level || txtMsg->multiLevel)) {
int blender = (txtMsg->maxLiveTime - txtMsg->liveTime > 2000 ? 0 : 2000 - (txtMsg->maxLiveTime - txtMsg->liveTime));
float alpha = 1.0f - ((float)blender / 2000);
float flyingSpeed = (float)Game::options.flyingSpeed * 0.01f;
std::vector<std::pair<unsigned int, TextString> > lines = DivideText(txtMsg->text);
for (int i = 0; i < lines.size(); i++) {
std::string printText = lines[i].second.text;
std::string printColor = lines[i].second.color;
float width = font->GetTextWidth(printText, fontSize);
float offset = fontSize * (lines.size() - i - 1);
float px = x + (txtMsg->pos.x - pos.x) * zoom + zoom / 2 - width / 2;
float py = y + (txtMsg->pos.y - pos.y) * zoom - zoom - offset - (float)(flyingSpeed * (zoom / 32) * txtMsg->liveTime) / 150 - textOffset[txtMsg->pos];
if (px < 0.0f) px = 0.0f;
else if (px > (15 * zoom) - width) px = (15 * zoom) - width;
if (py < 0.0f + i * fontSize) py = 0.0f + i * fontSize;
else if (py > (11 * zoom) - (lines.size() - i) * fontSize) py = (11 * zoom) - (lines.size() - i) * fontSize;
AD2D_Window::SetColor(1.0f, 1.0f, 1.0f, alpha);
gfx->CPrint(px, py, fontSize, *font, printText.c_str(), printColor.c_str(), true);
}
if (Game::options.flyingSpeed == 0)
textOffset[txtMsg->pos] = textOffset[txtMsg->pos] + lines.size() * fontSize;
}
}
for (it = animMessages.begin(); it != animMessages.end(); it++) {
Message* message = *it;
AnimatedMessage* animMsg = dynamic_cast<AnimatedMessage*>(message);
if (animMsg && animMsg->pos.z == level) {
std::string printText = animMsg->text.text;
std::string printColor = animMsg->text.color;
float _fontSize = fontSize * (1.0f + (float)animMsg->liveTime / animMsg->maxLiveTime);
float px = x + (float)(animMsg->pos.x - pos.x) * zoom + zoom / 2 - font->GetTextWidth(printText, _fontSize) / 2 + animMsg->offsetX * _fontSize;
float py = y + (float)(animMsg->pos.y - pos.y) * zoom - (float)((zoom / 32) * animMsg->liveTime) / 50 + animMsg->offsetY * _fontSize;
float alpha = 1.0f - ((float)animMsg->liveTime / animMsg->maxLiveTime);
AD2D_Window::SetColor(1.0f, 1.0f, 1.0f, alpha);
gfx->CPrint(px, py, _fontSize, *font, printText.c_str(), printColor.c_str(), true);
}
}
for (it = sysMessages.begin(); it != sysMessages.end(); it++) {
Message* message = *it;
SystemMessage* sysMsg = dynamic_cast<SystemMessage*>(message);
if (sysMsg) {
int blender = (sysMsg->maxLiveTime - sysMsg->liveTime > 2000 ? 0 : 2000 - (sysMsg->maxLiveTime - sysMsg->liveTime));
float alpha = 1.0f - ((float)blender / 2000);
std::vector<std::pair<unsigned int, TextString> > lines = DivideText(sysMsg->text);
for (int i = 0; i < lines.size(); i++) {
std::string printText = lines[i].second.text;
std::string printColor = lines[i].second.color;
float offset = fontSize * sysLine[std::pair<float, float>(sysMsg->posX, sysMsg->posY)];
float px = ((sysMsg->posX + 1.0f) / 2) * (15 * zoom) - ((sysMsg->posX + 1.0f) / 2) * font->GetTextWidth(printText, fontSize);
float py = ((sysMsg->posY + 1.0f) / 2) * (11 * zoom) - ((sysMsg->posY + 1.0f) / 2) * (float)(fontSize * (sysLines[std::pair<float, float>(sysMsg->posX, sysMsg->posY)])) + offset;
AD2D_Window::SetColor(1.0f, 1.0f, 1.0f, alpha);
gfx->CPrint(px, py, fontSize, *font, printText.c_str(), printColor.c_str(), true);
sysLine[std::pair<float, float>(sysMsg->posX, sysMsg->posY)]++;
}
}
}
}
| 32.026415 | 182 | 0.637446 | [
"vector"
] |
211aecd46f948c29561d53353cceca0c933195ca | 18,788 | cpp | C++ | services/bundlemgr/src/zip_file.cpp | openharmony-sig-ci/appexecfwk_standard | 609acd8632803202bd8af4c2a6bfc99ecf61ea2e | [
"Apache-2.0"
] | 1 | 2021-11-23T08:13:14.000Z | 2021-11-23T08:13:14.000Z | services/bundlemgr/src/zip_file.cpp | openharmony-sig-ci/appexecfwk_standard | 609acd8632803202bd8af4c2a6bfc99ecf61ea2e | [
"Apache-2.0"
] | null | null | null | services/bundlemgr/src/zip_file.cpp | openharmony-sig-ci/appexecfwk_standard | 609acd8632803202bd8af4c2a6bfc99ecf61ea2e | [
"Apache-2.0"
] | 1 | 2021-09-13T11:17:54.000Z | 2021-09-13T11:17:54.000Z | /*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "zip_file.h"
#include <cassert>
#include <cstring>
#include <ostream>
#include "securec.h"
#include "zlib.h"
#include "app_log_wrapper.h"
namespace OHOS {
namespace AppExecFwk {
namespace {
constexpr uint32_t MAX_FILE_NAME = 256;
constexpr uint32_t UNZIP_BUFFER_SIZE = 1024;
constexpr uint32_t UNZIP_BUF_IN_LEN = 160 * UNZIP_BUFFER_SIZE; // in buffer length: 160KB
constexpr uint32_t UNZIP_BUF_OUT_LEN = 320 * UNZIP_BUFFER_SIZE; // out buffer length: 320KB
constexpr uint32_t LOCAL_HEADER_SIGNATURE = 0x04034b50;
constexpr uint32_t CENTRAL_SIGNATURE = 0x02014b50;
constexpr uint32_t EOCD_SIGNATURE = 0x06054b50;
constexpr uint32_t DATA_DESC_SIGNATURE = 0x08074b50;
constexpr uint32_t FLAG_DATA_DESC = 0x8;
constexpr size_t FILE_READ_COUNT = 1;
} // namespace
ZipEntry::ZipEntry(const CentralDirEntry ¢ralEntry)
{
compressionMethod = centralEntry.compressionMethod;
uncompressedSize = centralEntry.uncompressedSize;
compressedSize = centralEntry.compressedSize;
localHeaderOffset = centralEntry.localHeaderOffset;
crc = centralEntry.crc;
flags = centralEntry.flags;
}
ZipFile::ZipFile(const std::string &pathName) : pathName_(pathName)
{
APP_LOGI("create instance from %{private}s", pathName_.c_str());
}
ZipFile::~ZipFile()
{
Close();
}
void ZipFile::SetContentLocation(const ZipPos start, const size_t length)
{
APP_LOGD("set content location start position(%{public}llu), length(%{public}zu)", start, length);
fileStartPos_ = start;
fileLength_ = length;
}
bool ZipFile::CheckEndDir(const EndDir &endDir) const
{
size_t lenEndDir = sizeof(EndDir);
if ((endDir.numDisk != 0) || (endDir.signature != EOCD_SIGNATURE) || (endDir.startDiskOfCentralDir != 0) ||
(endDir.offset >= fileLength_) || (endDir.totalEntriesInThisDisk != endDir.totalEntries) ||
(endDir.commentLen != 0) ||
// central dir can't overlap end of central dir
((endDir.offset + endDir.sizeOfCentralDir + lenEndDir) > fileLength_)) {
APP_LOGE("end dir format error");
return false;
}
return true;
}
bool ZipFile::ParseEndDirectory()
{
size_t endDirLen = sizeof(EndDir);
size_t endFilePos = fileStartPos_ + fileLength_;
if (fileLength_ <= endDirLen) {
APP_LOGE("parse EOCD file length(%{public}llu) <= end dir length(%{public}llu)", fileStartPos_, fileLength_);
return false;
}
size_t eocdPos = endFilePos - endDirLen;
if (fseek(file_, eocdPos, SEEK_SET) != 0) {
APP_LOGE("locate EOCD seek failed, error: %{public}s", strerror(errno));
return false;
}
if (fread(&endDir_, sizeof(EndDir), FILE_READ_COUNT, file_) != FILE_READ_COUNT) {
APP_LOGE("read EOCD struct failed, error: %{public}s", strerror(errno));
return false;
}
centralDirPos_ = endDir_.offset + fileStartPos_;
APP_LOGD("parse EOCD offset(0x%{public}08x) file start position(0x%{public}08llx)", endDir_.offset, fileStartPos_);
return CheckEndDir(endDir_);
}
bool ZipFile::ParseAllEntries()
{
bool ret = true;
ZipPos currentPos = centralDirPos_;
CentralDirEntry directoryEntry = {0};
size_t fileLength = 0;
for (int32_t i = 0; i < endDir_.totalEntries; i++) {
std::string fileName;
fileName.reserve(MAX_FILE_NAME);
fileName.resize(MAX_FILE_NAME - 1);
if (fseek(file_, currentPos, SEEK_SET) != 0) {
APP_LOGE("parse entry(%{public}d) seek zipEntry failed, error: %{public}s", i, strerror(errno));
ret = false;
break;
}
if (fread(&directoryEntry, sizeof(CentralDirEntry), FILE_READ_COUNT, file_) != FILE_READ_COUNT) {
APP_LOGE("parse entry(%{public}d) read ZipEntry failed, error: %{public}s", i, strerror(errno));
ret = false;
break;
}
if (directoryEntry.signature != CENTRAL_SIGNATURE) {
APP_LOGE("parse entry(%{public}d) check signature(0x%08x) at pos(0x%08llx) failed",
i,
directoryEntry.signature,
currentPos);
ret = false;
break;
}
fileLength = (directoryEntry.nameSize >= MAX_FILE_NAME) ? (MAX_FILE_NAME - 1) : directoryEntry.nameSize;
if (fread(&(fileName[0]), fileLength, FILE_READ_COUNT, file_) != FILE_READ_COUNT) {
APP_LOGE("parse entry(%{public}d) read file name failed, error: %{public}s", i, strerror(errno));
ret = false;
break;
}
fileName.resize(fileLength);
ZipEntry currentEntry(directoryEntry);
currentEntry.fileName = fileName;
entriesMap_[fileName] = currentEntry;
currentPos += sizeof(directoryEntry);
currentPos += directoryEntry.nameSize + directoryEntry.extraSize + directoryEntry.commentSize;
}
APP_LOGD("parse %{public}d central entries from %{private}s", endDir_.totalEntries, pathName_.c_str());
return ret;
}
bool ZipFile::Open()
{
APP_LOGD("open: %{private}s", pathName_.c_str());
if (isOpen_) {
APP_LOGE("has already opened");
return true;
}
if (pathName_.length() > PATH_MAX) {
APP_LOGE("path length(%{public}u) longer than max path length(%{public}d)",
static_cast<unsigned int>(pathName_.length()),
PATH_MAX);
return false;
}
std::string realPath;
realPath.reserve(PATH_MAX);
realPath.resize(PATH_MAX - 1);
if (realpath(pathName_.c_str(), &(realPath[0])) == nullptr) {
APP_LOGE("transform real path error: %{public}s", strerror(errno));
return false;
}
FILE *tmpFile = fopen(&(realPath[0]), "rb");
if (tmpFile == nullptr) {
APP_LOGE("open file(%{private}s) failed, error: %{public}s", pathName_.c_str(), strerror(errno));
return false;
}
if (fileLength_ == 0) {
if (fseek(tmpFile, 0, SEEK_END) != 0) {
APP_LOGE("file seek failed, error: %{public}s", strerror(errno));
fclose(tmpFile);
return false;
}
fileLength_ = ftell(tmpFile);
if (fileStartPos_ >= fileLength_) {
APP_LOGE("open start pos > length failed");
fclose(tmpFile);
return false;
}
fileLength_ -= fileStartPos_;
}
file_ = tmpFile;
bool result = ParseEndDirectory();
if (result) {
result = ParseAllEntries();
}
// it means open file success.
isOpen_ = true;
return result;
}
void ZipFile::Close()
{
APP_LOGD("close: %{private}s", pathName_.c_str());
if (!isOpen_ || file_ == nullptr) {
APP_LOGW("file is not opened");
return;
}
entriesMap_.clear();
pathName_ = "";
isOpen_ = false;
if (fclose(file_) != 0) {
APP_LOGW("close failed, error: %{public}s", strerror(errno));
}
file_ = nullptr;
}
// Get all file zipEntry in this file
const ZipEntryMap &ZipFile::GetAllEntries() const
{
return entriesMap_;
}
bool ZipFile::GetEntry(const std::string &entryName, ZipEntry &resultEntry) const
{
APP_LOGD("get entry by name: %{public}s", entryName.c_str());
auto iter = entriesMap_.find(entryName);
if (iter != entriesMap_.end()) {
resultEntry = iter->second;
APP_LOGD("get entry succeed");
return true;
}
APP_LOGE("get entry failed");
return false;
}
size_t ZipFile::GetLocalHeaderSize(const uint16_t nameSize, const uint16_t extraSize) const
{
return sizeof(LocalHeader) + nameSize + extraSize;
}
bool ZipFile::CheckDataDesc(const ZipEntry &zipEntry, const LocalHeader &localHeader) const
{
uint32_t crcLocal = 0;
uint32_t compressedLocal = 0;
uint32_t uncompressedLocal = 0;
if (localHeader.flags & FLAG_DATA_DESC) { // use data desc
DataDesc dataDesc;
ZipPos descPos = zipEntry.localHeaderOffset + GetLocalHeaderSize(localHeader.nameSize, localHeader.extraSize);
descPos += fileStartPos_ + zipEntry.compressedSize;
if (fseek(file_, descPos, SEEK_SET) != 0) {
APP_LOGE("check local header seek datadesc failed, error: %{public}s", strerror(errno));
return false;
}
if (fread(&dataDesc, sizeof(DataDesc), FILE_READ_COUNT, file_) != FILE_READ_COUNT) {
APP_LOGE("check local header read datadesc failed, error: %{public}s", strerror(errno));
return false;
}
if (dataDesc.signature != DATA_DESC_SIGNATURE) {
APP_LOGE("check local header check datadesc signature failed");
return false;
}
crcLocal = dataDesc.crc;
compressedLocal = dataDesc.compressedSize;
uncompressedLocal = dataDesc.uncompressedSize;
} else {
crcLocal = localHeader.crc;
compressedLocal = localHeader.compressedSize;
uncompressedLocal = localHeader.uncompressedSize;
}
if ((zipEntry.crc != crcLocal) || (zipEntry.compressedSize != compressedLocal) ||
(zipEntry.uncompressedSize != uncompressedLocal)) {
APP_LOGE("check local header compressed size corrupted");
return false;
}
return true;
}
bool ZipFile::CheckCoherencyLocalHeader(const ZipEntry &zipEntry, uint16_t &extraSize) const
{
LocalHeader localHeader = {0};
if (zipEntry.localHeaderOffset >= fileLength_) {
APP_LOGE("check local file header offset is overflow %{public}d", zipEntry.localHeaderOffset);
return false;
}
if (fseek(file_, fileStartPos_ + zipEntry.localHeaderOffset, SEEK_SET) != 0) {
APP_LOGE("check local header seek failed, error: %{public}s", strerror(errno));
return false;
}
if (fread(&localHeader, sizeof(LocalHeader), FILE_READ_COUNT, file_) != FILE_READ_COUNT) {
APP_LOGE("check local header read localheader failed, error: %{public}s", strerror(errno));
return false;
}
if ((localHeader.signature != LOCAL_HEADER_SIGNATURE) ||
(zipEntry.compressionMethod != localHeader.compressionMethod)) {
APP_LOGE("check local header signature or compressionMethod failed");
return false;
}
// current only support store and Z_DEFLATED method
if ((zipEntry.compressionMethod != Z_DEFLATED) && (zipEntry.compressionMethod != 0)) {
APP_LOGE("check local header compressionMethod(%{public}d) not support", zipEntry.compressionMethod);
return false;
}
std::string fileName;
fileName.reserve(MAX_FILE_NAME);
fileName.resize(MAX_FILE_NAME - 1);
size_t fileLength = (localHeader.nameSize >= MAX_FILE_NAME) ? (MAX_FILE_NAME - 1) : localHeader.nameSize;
if (fileLength != zipEntry.fileName.length()) {
APP_LOGE("check local header file name size failed");
return false;
}
if (fread(&(fileName[0]), fileLength, FILE_READ_COUNT, file_) != FILE_READ_COUNT) {
APP_LOGE("check local header read file name failed, error: %{public}s", strerror(errno));
return false;
}
fileName.resize(fileLength);
if (zipEntry.fileName != fileName) {
APP_LOGE("check local header file name corrupted");
return false;
}
if (!CheckDataDesc(zipEntry, localHeader)) {
APP_LOGE("check data desc failed");
return false;
}
extraSize = localHeader.extraSize;
return true;
}
bool ZipFile::SeekToEntryStart(const ZipEntry &zipEntry, const uint16_t extraSize) const
{
ZipPos startOffset = zipEntry.localHeaderOffset;
// get data offset, add signature+localheader+namesize+extrasize
startOffset += GetLocalHeaderSize(zipEntry.fileName.length(), extraSize);
if (startOffset + zipEntry.compressedSize > fileLength_) {
APP_LOGE("startOffset(%{public}lld)+entryCompressedSize(%{public}ud) > fileLength(%{public}llu)",
startOffset,
zipEntry.compressedSize,
fileLength_);
return false;
}
startOffset += fileStartPos_; // add file start relative to file stream
APP_LOGD("seek to entry start 0x%{public}08llx", startOffset);
if (fseek(file_, startOffset, SEEK_SET) != 0) {
APP_LOGE("seek failed, error: %{public}s", strerror(errno));
return false;
}
return true;
}
bool ZipFile::UnzipWithStore(const ZipEntry &zipEntry, const uint16_t extraSize, std::ostream &dest) const
{
APP_LOGD("unzip with store");
if (!SeekToEntryStart(zipEntry, extraSize)) {
APP_LOGE("seek to entry start failed");
return false;
}
uint32_t remainSize = zipEntry.compressedSize;
std::string readBuffer;
readBuffer.reserve(UNZIP_BUF_OUT_LEN);
readBuffer.resize(UNZIP_BUF_OUT_LEN - 1);
while (remainSize > 0) {
size_t readBytes;
size_t readLen = (remainSize > UNZIP_BUF_OUT_LEN) ? UNZIP_BUF_OUT_LEN : remainSize;
readBytes = fread(&(readBuffer[0]), sizeof(Byte), readLen, file_);
if (readBytes == 0) {
APP_LOGE("unzip store read failed, error: %{public}s", strerror(errno));
return false;
}
remainSize -= readBytes;
dest.write(&(readBuffer[0]), readBytes);
}
return true;
}
bool ZipFile::InitZStream(z_stream &zstream) const
{
// init zlib stream
if (memset_s(&zstream, sizeof(z_stream), 0, sizeof(z_stream))) {
APP_LOGE("unzip stream buffer init failed");
return false;
}
int32_t zlibErr = inflateInit2(&zstream, -MAX_WBITS);
if (zlibErr != Z_OK) {
APP_LOGE("unzip inflated init failed");
return false;
}
BytePtr bufOut = new (std::nothrow) Byte[UNZIP_BUF_OUT_LEN];
if (bufOut == nullptr) {
APP_LOGE("unzip inflated new out buffer failed");
return false;
}
BytePtr bufIn = new (std::nothrow) Byte[UNZIP_BUF_IN_LEN];
if (bufIn == nullptr) {
APP_LOGE("unzip inflated new in buffer failed");
delete[] bufOut;
return false;
}
zstream.next_out = bufOut;
zstream.next_in = bufIn;
zstream.avail_out = UNZIP_BUF_OUT_LEN;
return true;
}
bool ZipFile::ReadZStream(const BytePtr &buffer, z_stream &zstream, uint32_t &remainCompressedSize) const
{
if (zstream.avail_in == 0) {
size_t readBytes;
size_t remainBytes = (remainCompressedSize > UNZIP_BUF_IN_LEN) ? UNZIP_BUF_IN_LEN : remainCompressedSize;
readBytes = fread(buffer, sizeof(Byte), remainBytes, file_);
if (readBytes == 0) {
APP_LOGE("unzip inflated read failed, error: %{public}s", strerror(errno));
return false;
}
remainCompressedSize -= readBytes;
zstream.avail_in = readBytes;
zstream.next_in = buffer;
}
return true;
}
bool ZipFile::UnzipWithInflated(const ZipEntry &zipEntry, const uint16_t extraSize, std::ostream &dest) const
{
APP_LOGD("unzip with inflated");
z_stream zstream;
if (!SeekToEntryStart(zipEntry, extraSize)) {
APP_LOGE("seek to entry start failed");
return false;
}
if (!InitZStream(zstream)) {
APP_LOGE("init zstream failed");
return false;
}
BytePtr bufIn = zstream.next_in;
BytePtr bufOut = zstream.next_out;
bool ret = true;
int32_t zlibErr = Z_OK;
uint32_t remainCompressedSize = zipEntry.compressedSize;
size_t inflateLen = 0;
uint32_t crc = 0;
while ((remainCompressedSize > 0) || (zstream.avail_in > 0)) {
if (!ReadZStream(bufIn, zstream, remainCompressedSize)) {
ret = false;
break;
}
zlibErr = inflate(&zstream, Z_SYNC_FLUSH);
if ((zlibErr >= Z_OK) && (zstream.msg != nullptr)) {
APP_LOGE("unzip inflated inflate, error: %{public}d, err msg: %{public}s", zlibErr, zstream.msg);
ret = false;
break;
}
inflateLen = UNZIP_BUF_OUT_LEN - zstream.avail_out;
if (inflateLen > 0) {
dest.write((const char *)bufOut, inflateLen);
crc = crc32(crc, bufOut, inflateLen);
zstream.next_out = bufOut;
zstream.avail_out = UNZIP_BUF_OUT_LEN;
}
}
if (crc != zipEntry.crc) {
APP_LOGE("unzip inflate crc check");
ret = false;
}
// free all dynamically allocated data structures except the next_in and next_out for this stream.
zlibErr = inflateEnd(&zstream);
if (zlibErr != Z_OK) {
APP_LOGE("unzip inflateEnd error, error: %{public}d", zlibErr);
ret = false;
}
delete[] bufOut;
delete[] bufIn;
return ret;
}
ZipPos ZipFile::GetEntryDataOffset(const ZipEntry &zipEntry, const uint16_t extraSize) const
{
// get entry data offset relative file
ZipPos offset = zipEntry.localHeaderOffset;
offset += GetLocalHeaderSize(zipEntry.fileName.length(), extraSize);
offset += fileStartPos_;
return offset;
}
bool ZipFile::GetDataOffsetRelative(const std::string &file, ZipPos &offset, uint32_t &length) const
{
APP_LOGD("get data relative offset for file %{private}s", file.c_str());
ZipEntry zipEntry;
if (!GetEntry(file, zipEntry)) {
APP_LOGE("extract file: not find file");
return false;
}
uint16_t extraSize = 0;
if (!CheckCoherencyLocalHeader(zipEntry, extraSize)) {
APP_LOGE("check coherency local header failed");
return false;
}
offset = GetEntryDataOffset(zipEntry, extraSize);
length = zipEntry.compressedSize;
return true;
}
bool ZipFile::ExtractFile(const std::string &file, std::ostream &dest) const
{
APP_LOGD("extract file %{private}s", file.c_str());
ZipEntry zipEntry;
if (!GetEntry(file, zipEntry)) {
APP_LOGE("extract file: not find file");
return false;
}
uint16_t extraSize = 0;
if (!CheckCoherencyLocalHeader(zipEntry, extraSize)) {
APP_LOGE("check coherency local header failed");
return false;
}
bool ret = true;
if (zipEntry.compressionMethod == 0) {
ret = UnzipWithStore(zipEntry, extraSize, dest);
} else {
ret = UnzipWithInflated(zipEntry, extraSize, dest);
}
return ret;
}
} // namespace AppExecFwk
} // namespace OHOS
| 32.171233 | 119 | 0.648978 | [
"transform"
] |
211cde2e772880211c7750d742d778cbfdcc5040 | 7,498 | cpp | C++ | source/dialogunicodexmlfileeditor.cpp | nezarati/Negar-Unicode-Fixer | f3ac17c6605e32b633228a0cd912a698a4147a21 | [
"MIT"
] | null | null | null | source/dialogunicodexmlfileeditor.cpp | nezarati/Negar-Unicode-Fixer | f3ac17c6605e32b633228a0cd912a698a4147a21 | [
"MIT"
] | null | null | null | source/dialogunicodexmlfileeditor.cpp | nezarati/Negar-Unicode-Fixer | f3ac17c6605e32b633228a0cd912a698a4147a21 | [
"MIT"
] | null | null | null | #include "dialogunicodexmlfileeditor.h"
#include "ui_dialogunicodexmlfileeditor.h"
#include "QMenu"
#include "QDebug"
#include"convertor.h"
#include "checkboxeditdelegate.h"
#include "QFile"
#include "QXmlStreamWriter"
#include "QFileDialog"
#include <QMainWindow>
#include "QItemSelectionModel"
DialogUnicodeXmlFileEditor::DialogUnicodeXmlFileEditor(QWidget *parent) :
QDialog(parent),
ui(new Ui::DialogUnicodeXmlFileEditor)
{
ui->setupUi(this);
ui->listViewAddress->setContextMenuPolicy(Qt::CustomContextMenu);
model=new QStandardItemModel(1,6);
modelAddress=new QStandardItemModel(1,3);
ui->listViewAddress->setModel(modelAddress);
ui->tableViewXmlData->setModel(model);
checkBoxEditDelegate *comboBox=new checkBoxEditDelegate();
ui->tableViewXmlData->setItemDelegateForColumn(6,comboBox);
ui->tableViewXmlData->setItemDelegateForColumn(7,comboBox);
readSettingsFile();
connect(ui->listViewAddress,SIGNAL(pressed(QModelIndex)),this,SLOT(selectedAdressIschanged()));
connect(ui->listViewAddress, SIGNAL(customContextMenuRequested(const QPoint&)),
this, SLOT(ShowContextMenu(const QPoint&)));
readSettingsFileInit();
this->setLayout(ui->gridLayoutWidget->layout());
}
DialogUnicodeXmlFileEditor::~DialogUnicodeXmlFileEditor()
{
delete ui;
}
void DialogUnicodeXmlFileEditor::ShowContextMenu(const QPoint &pos)
{
QPoint globalPos = ui->listViewAddress->mapToGlobal(pos);
QMenu myMenu(this);
myMenu.addAction("Add XML File");
myMenu.addAction("Remove selected XML File");
myMenu.addAction("Save Adress List");
QAction* selectedItem = myMenu.exec(globalPos);
if (selectedItem)
{
if(!selectedItem->text().compare("Add XML File"))
{
on_pushButtonAdd_clicked();
}
else if(!selectedItem->text().compare("Remove selected XML File"))
{
on_pushButtonRemove_clicked();
}
else if(!selectedItem->text().compare("Save Adress List"))
{
on_pushButtonSave_2_clicked();
}
}
}
void DialogUnicodeXmlFileEditor::on_pushButtonAdd_clicked()
{
QString fileDir = QFileDialog::getOpenFileName(this, tr("Add XML File"), QDir::currentPath(),tr("XML File (*.xml);;All files (*.*)"));
if(!fileDir.isEmpty()){
QStringList strList=fileDir.split('/');
modelAddress->insertRow(modelAddress->rowCount());
modelAddress->setData(modelAddress->index(modelAddress->rowCount()-1,0),strList.last());
modelAddress->setData(modelAddress->index(modelAddress->rowCount()-1,1),fileDir.remove(strList.last()));
modelAddress->setData(modelAddress->index(modelAddress->rowCount()-1,2),0);
}
}
void DialogUnicodeXmlFileEditor::on_pushButtonSave_clicked()
{
convertor::ModelToXML(modelAddress->data(modelAddress->index(ui->listViewAddress->currentIndex().row(),1)).toString()+modelAddress->data(modelAddress->index(ui->listViewAddress->currentIndex().row(),0)).toString(),model);
}
void DialogUnicodeXmlFileEditor::on_pushButtonActivator_clicked()
{
}
void DialogUnicodeXmlFileEditor::selectedAdressIschanged(){
convertor::XMLToModel(modelAddress->data(modelAddress->index(ui->listViewAddress->currentIndex().row(),1)).toString()+modelAddress->data(modelAddress->index(ui->listViewAddress->currentIndex().row(),0)).toString(),model);
qDebug()<<modelAddress->data(modelAddress->index(ui->listViewAddress->currentIndex().row(),1)).toString()+modelAddress->data(modelAddress->index(ui->listViewAddress->currentIndex().row(),0)).toString();
}
void DialogUnicodeXmlFileEditor::readSettingsFile(){
QFile xml("settings.xml");
if (!xml.open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug()<<"Cannot read XML File.";
return;
}
modelAddress->clear();
modelAddress->setColumnCount(3);
modelAddress->insertRow(0);
QXmlStreamReader stream(&xml);
while(!stream.atEnd())
{
if(!stream.attributes().value("address").isEmpty()){
QString str=stream.attributes().value("address").toString();
QStringList strList=str.split('/');
modelAddress->setData(modelAddress->index(modelAddress->rowCount()-1,0),strList.last());
modelAddress->setData(modelAddress->index(modelAddress->rowCount()-1,1),str.remove(strList.last()));
}
if(stream.name()=="active-state"){
modelAddress->setData(modelAddress->index(modelAddress->rowCount()-1,2),stream.readElementText());
modelAddress->insertRow(modelAddress->rowCount());
}
stream.readNext();
}
modelAddress->removeRow(modelAddress->rowCount()-1);
}
void DialogUnicodeXmlFileEditor::on_pushButtonRemove_clicked()
{
if (ui->listViewAddress->currentIndex().isValid()) {
modelAddress->removeRow(ui->listViewAddress->currentIndex().row());
}
}
void DialogUnicodeXmlFileEditor::on_pushButtonSave_2_clicked()
{
QFile output("settings.xml");
output.open(QIODevice::WriteOnly);
//! [write output]
//! [start stream]
QXmlStreamWriter stream(&output);
stream.setAutoFormatting(true);
stream.writeStartDocument();
//! [start stream]
stream.writeDTD("<!DOCTYPE Negar>");
stream.writeStartElement("Negar");
stream.writeAttribute("version", "1.0");
stream.writeStartElement("Settings");
stream.writeAttribute("files", "all");
//! [write element]
for(int row=0;row<modelAddress->rowCount();row++)
{
stream.writeStartElement("XMLUnicodeFiles");
stream.writeAttribute("address", modelAddress->data(modelAddress->index(row,1)).toString()+modelAddress->data(modelAddress->index(row,0)).toString());
stream.writeTextElement("active-state",modelAddress->data(modelAddress->index(row,2)).toString());
//! [write element]
stream.writeEndElement();
}
//! [write element]
stream.writeEndElement();
//! [finish stream]
stream.writeEndDocument();
//! [finish stream]
//! [write output]
output.close();
}
void DialogUnicodeXmlFileEditor::on_pushButtonAddRow_clicked()
{
model->insertRow(model->rowCount());
ui->tableViewXmlData->setCurrentIndex(model->index(model->rowCount(),0));
}
void DialogUnicodeXmlFileEditor::on_pushButtonRemoveRow_clicked()
{
if(ui->tableViewXmlData->currentIndex().isValid())
model->removeRow(ui->tableViewXmlData->currentIndex().row());
}
void DialogUnicodeXmlFileEditor::on_pushButtonActivator_2_clicked()
{
for (int row = 0; row < modelAddress->rowCount(); ++row)
if(ui->listViewAddress->currentIndex().row()==row)
modelAddress->setData(modelAddress->index(row,2),1);
else
modelAddress->setData(modelAddress->index(row,2),0);
}
void DialogUnicodeXmlFileEditor::readSettingsFileInit(){
QFile xml("settings.xml");
if (!xml.open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug()<<"Cannot read XML File.";
return;
}
QString str;
QXmlStreamReader stream(&xml);
while(!stream.atEnd())
{
if(!stream.attributes().value("address").isEmpty()){
str=stream.attributes().value("address").toString();
}
if(stream.name()=="active-state"){
if(stream.readElementText()=="1"){
convertor::XMLToModel(str,model);
}
}
stream.readNext();
}
}
| 36.048077 | 225 | 0.67618 | [
"model"
] |
211e0815c6afb9b6770cf44d32fff0931f13843a | 485 | cpp | C++ | cf1560A.cpp | yonghuatang/codeforces | 7e1268443e14b001049ef854d2b230f1449d5a2d | [
"MIT"
] | null | null | null | cf1560A.cpp | yonghuatang/codeforces | 7e1268443e14b001049ef854d2b230f1449d5a2d | [
"MIT"
] | null | null | null | cf1560A.cpp | yonghuatang/codeforces | 7e1268443e14b001049ef854d2b230f1449d5a2d | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
int cur = 0;
vector<int> v; // memoisation
for (int tc=1; tc<=t; tc++) {
int k;
cin >> k;
while (k > v.size()) {
cur++;
string curString = to_string(cur);
if (cur % 3 != 0 && curString[curString.size()-1] != '3') {
v.push_back(cur);
}
}
cout << v[k-1] << endl;
}
return 0;
}
| 21.086957 | 71 | 0.414433 | [
"vector"
] |
21340789a8951afd5888f96c7cf27afee222f88d | 2,142 | cpp | C++ | Tutorials/GPU/HeatEquation_EX1_C/Exec/CUDA/advance.cpp | ylunalin/amrex | 5715b2fc8a77e0db17bfe7907982e29ec44811ca | [
"BSD-3-Clause-LBNL"
] | null | null | null | Tutorials/GPU/HeatEquation_EX1_C/Exec/CUDA/advance.cpp | ylunalin/amrex | 5715b2fc8a77e0db17bfe7907982e29ec44811ca | [
"BSD-3-Clause-LBNL"
] | null | null | null | Tutorials/GPU/HeatEquation_EX1_C/Exec/CUDA/advance.cpp | ylunalin/amrex | 5715b2fc8a77e0db17bfe7907982e29ec44811ca | [
"BSD-3-Clause-LBNL"
] | null | null | null |
#include "myfunc.H"
#include "mykernel.H"
void advance (MultiFab& phi_old,
MultiFab& phi_new,
std::array<MultiFab, AMREX_SPACEDIM>& flux,
Real dt,
Geometry const& geom)
{
// Fill the ghost cells of each grid from the other grids
// includes periodic domain boundaries
phi_old.FillBoundary(geom.periodicity());
//
// Note that this simple example is not optimized.
// The following two MFIter loops could be merged
// and we do not have to use flux MultiFab.
//
// =======================================================
const Real dxinv = geom.InvCellSize(0);
const Real dyinv = geom.InvCellSize(1);
const Real dzinv = geom.InvCellSize(2);
// Compute fluxes one grid at a time
for ( MFIter mfi(phi_old); mfi.isValid(); ++mfi )
{
const Box& xbx = mfi.nodaltilebox(0);
const Box& ybx = mfi.nodaltilebox(1);
const Box& zbx = mfi.nodaltilebox(2);
Array4<Real> fluxx = flux[0].array(mfi);
Array4<Real> fluxy = flux[1].array(mfi);
Array4<Real> fluxz = flux[2].array(mfi);
const Array4<Real> phi = phi_old.array(mfi);
AMREX_PARALLEL_FOR_3D ( xbx, i, j, k,
{
compute_flux_x(i,j,k,fluxx,phi,dxinv);
});
AMREX_PARALLEL_FOR_3D ( ybx, i, j, k,
{
compute_flux_y(i,j,k,fluxy,phi,dyinv);
});
AMREX_PARALLEL_FOR_3D ( zbx, i, j, k,
{
compute_flux_z(i,j,k,fluxz,phi,dzinv);
});
}
// Advance the solution one grid at a time
for ( MFIter mfi(phi_old); mfi.isValid(); ++mfi )
{
const Box& vbx = mfi.validbox();
const Array4<Real> fluxx = flux[0].array(mfi);
const Array4<Real> fluxy = flux[1].array(mfi);
const Array4<Real> fluxz = flux[2].array(mfi);
const Array4<Real> phiOld = phi_old.array(mfi);
Array4<Real> phiNew = phi_old.array(mfi);
AMREX_PARALLEL_FOR_3D ( vbx, i, j, k,
{
update_phi(i,j,k,phiOld,phiNew,fluxx,fluxy,fluxz,dt,dxinv,dyinv,dzinv);
});
}
}
| 30.6 | 83 | 0.560691 | [
"geometry"
] |
21343dcd8e55ea64ff0990a049486c44ce0001d5 | 1,454 | cpp | C++ | Source/Services/Leaderboard/leaderboard_row.cpp | blgrossMS/xbox-live-api | 17c586336e11f0fa3a2a3f3acd665b18c5487b24 | [
"MIT"
] | 2 | 2021-07-17T13:34:20.000Z | 2022-01-09T00:55:51.000Z | Source/Services/Leaderboard/leaderboard_row.cpp | blgrossMS/xbox-live-api | 17c586336e11f0fa3a2a3f3acd665b18c5487b24 | [
"MIT"
] | null | null | null | Source/Services/Leaderboard/leaderboard_row.cpp | blgrossMS/xbox-live-api | 17c586336e11f0fa3a2a3f3acd665b18c5487b24 | [
"MIT"
] | 1 | 2018-11-18T08:32:40.000Z | 2018-11-18T08:32:40.000Z | //*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
#include "pch.h"
#include "shared_macros.h"
#include "xsapi/leaderboard.h"
NAMESPACE_MICROSOFT_XBOX_SERVICES_LEADERBOARD_CPP_BEGIN
leaderboard_row::leaderboard_row(
_In_ string_t gamertag,
_In_ string_t xboxUserId,
_In_ double percentile,
_In_ uint32_t rank,
_In_ std::vector<string_t> columnValues,
_In_ string_t metadata) :
m_gamertag(std::move(gamertag)),
m_xboxUserId(std::move(xboxUserId)),
m_percentile(percentile),
m_rank(rank),
m_columnValues(std::move(columnValues))
{
if(!metadata.empty())
{
m_metadata = web::json::value::parse(metadata);
}
}
const string_t& leaderboard_row::gamertag() const
{
return m_gamertag;
}
const string_t& leaderboard_row::xbox_user_id() const
{
return m_xboxUserId;
}
double leaderboard_row::percentile() const
{
return m_percentile;
}
uint32_t leaderboard_row::rank() const
{
return m_rank;
}
const std::vector<string_t>& leaderboard_row::column_values() const
{
return m_columnValues;
}
NAMESPACE_MICROSOFT_XBOX_SERVICES_LEADERBOARD_CPP_END | 24.233333 | 67 | 0.675378 | [
"vector"
] |
213951b9e554646fd1d04509290679500e1d8b62 | 5,226 | cc | C++ | chrome/browser/chromeos/gdata/drive_webapps_registry_unittest.cc | Crystalnix/BitPop | 1fae4ecfb965e163f6ce154b3988b3181678742a | [
"BSD-3-Clause"
] | 7 | 2015-05-20T22:41:35.000Z | 2021-11-18T19:07:59.000Z | chrome/browser/chromeos/gdata/drive_webapps_registry_unittest.cc | Crystalnix/BitPop | 1fae4ecfb965e163f6ce154b3988b3181678742a | [
"BSD-3-Clause"
] | 1 | 2015-02-02T06:55:08.000Z | 2016-01-20T06:11:59.000Z | chrome/browser/chromeos/gdata/drive_webapps_registry_unittest.cc | Crystalnix/BitPop | 1fae4ecfb965e163f6ce154b3988b3181678742a | [
"BSD-3-Clause"
] | 2 | 2015-12-08T00:37:41.000Z | 2017-04-06T05:34:05.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/json/json_file_value_serializer.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/string16.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/chromeos/gdata/drive_webapps_registry.h"
#include "chrome/browser/chromeos/gdata/gdata_wapi_parser.h"
#include "chrome/common/chrome_paths.h"
#include "content/public/test/test_browser_thread.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::Value;
using base::DictionaryValue;
using base::ListValue;
#define IF_EXPECT_EQ(arg1, arg2) \
EXPECT_EQ(arg1, arg2); \
if (arg1 == arg2)
namespace gdata {
class DriveWebAppsRegistryTest : public testing::Test {
protected:
DriveWebAppsRegistryTest()
: ui_thread_(content::BrowserThread::UI, &message_loop_){
}
static Value* LoadJSONFile(const std::string& filename) {
FilePath path;
std::string error;
// Test files for this unit test are located in
// src/chrome/test/data/chromeos/gdata/*
PathService::Get(chrome::DIR_TEST_DATA, &path);
path = path.AppendASCII("chromeos")
.AppendASCII("gdata")
.AppendASCII(filename.c_str());
EXPECT_TRUE(file_util::PathExists(path)) <<
"Couldn't find " << path.value();
JSONFileValueSerializer serializer(path);
Value* value = serializer.Deserialize(NULL, &error);
EXPECT_TRUE(value) <<
"Parse error " << path.value() << ": " << error;
return value;
}
bool VerifyApp(const ScopedVector<DriveWebAppInfo>& list,
const std::string& web_store_id,
const std::string& app_id,
const std::string& app_name,
const std::string& object_type,
bool is_primary) {
bool found = false;
for (ScopedVector<DriveWebAppInfo>::const_iterator it = list.begin();
it != list.end(); ++it) {
const DriveWebAppInfo* app = *it;
if (web_store_id == app->web_store_id) {
EXPECT_EQ(app_id, app->app_id);
EXPECT_EQ(app_name, UTF16ToUTF8(app->app_name));
EXPECT_EQ(object_type, UTF16ToUTF8(app->object_type));
EXPECT_EQ(is_primary, app->is_primary_selector);
found = true;
break;
}
}
EXPECT_TRUE(found) << "Unable to find app with web_store_id "
<< web_store_id;
return found;
}
bool VerifyApp1(const ScopedVector<DriveWebAppInfo>& list,
bool is_primary) {
return VerifyApp(list, "abcdefabcdef", "11111111",
"Drive App 1", "Drive App Object 1",
is_primary);
}
bool VerifyApp2(const ScopedVector<DriveWebAppInfo>& list,
bool is_primary) {
return VerifyApp(list, "deadbeefdeadbeef", "22222222",
"Drive App 2", "Drive App Object 2",
is_primary);
}
private:
MessageLoopForUI message_loop_;
content::TestBrowserThread ui_thread_;
};
TEST_F(DriveWebAppsRegistryTest, LoadAndFindWebApps) {
scoped_ptr<Value> document(LoadJSONFile("account_metadata.json"));
ASSERT_TRUE(document.get());
ASSERT_TRUE(document->GetType() == Value::TYPE_DICTIONARY);
DictionaryValue* entry_value;
ASSERT_TRUE(reinterpret_cast<DictionaryValue*>(document.get())->GetDictionary(
std::string("entry"), &entry_value));
ASSERT_TRUE(entry_value);
// Load feed.
scoped_ptr<AccountMetadataFeed> feed(
AccountMetadataFeed::CreateFrom(*document));
ASSERT_TRUE(feed.get());
scoped_ptr<DriveWebAppsRegistry> web_apps(new DriveWebAppsRegistry);
web_apps->UpdateFromFeed(feed.get());
// Find by extension 'ext_1'.
ScopedVector<DriveWebAppInfo> ext_1_results;
FilePath ext1_file(FILE_PATH_LITERAL("gdata/SampleFile.ext_1"));
web_apps->GetWebAppsForFile(ext1_file, std::string(), &ext_1_results);
IF_EXPECT_EQ(1U, ext_1_results.size()) {
EXPECT_TRUE(VerifyApp1(ext_1_results, true));
}
// Find by extension 'ext_3'.
ScopedVector<DriveWebAppInfo> ext_3_results;
FilePath ext3_file(FILE_PATH_LITERAL("gdata/AnotherFile.ext_3"));
web_apps->GetWebAppsForFile(ext3_file, std::string(), &ext_3_results);
IF_EXPECT_EQ(2U, ext_3_results.size()) {
EXPECT_TRUE(VerifyApp1(ext_3_results, false));
EXPECT_TRUE(VerifyApp2(ext_3_results, true));
}
// Find by mimetype 'ext_3'.
ScopedVector<DriveWebAppInfo> mime_results;
web_apps->GetWebAppsForFile(FilePath(), "application/test_type_2",
&mime_results);
IF_EXPECT_EQ(1U, mime_results.size()) {
EXPECT_TRUE(VerifyApp2(mime_results, true));
}
// Find by extension and mimetype.
ScopedVector<DriveWebAppInfo> mime_ext_results;
FilePath mime_file(FILE_PATH_LITERAL("gdata/MimeFile.ext_2"));
web_apps->GetWebAppsForFile(mime_file, "application/test_type_2",
&mime_ext_results);
IF_EXPECT_EQ(2U, mime_ext_results.size()) {
EXPECT_TRUE(VerifyApp1(mime_ext_results, true));
EXPECT_TRUE(VerifyApp2(mime_ext_results, true));
}
}
} // namespace gdata
| 34.84 | 80 | 0.69269 | [
"object"
] |
214ccfc36cf6ac4ed5b0b0a006b07cddedc9027a | 7,218 | cpp | C++ | Runer.cpp | erfanzar/AR-ML-FOR-REPLACEING | e3f0a32203b8b97f889e6f0e948261114df5aa54 | [
"MIT"
] | 1 | 2022-03-16T09:05:28.000Z | 2022-03-16T09:05:28.000Z | Runer.cpp | erfanzar/AR-ML-FOR-REPLACEING | e3f0a32203b8b97f889e6f0e948261114df5aa54 | [
"MIT"
] | null | null | null | Runer.cpp | erfanzar/AR-ML-FOR-REPLACEING | e3f0a32203b8b97f889e6f0e948261114df5aa54 | [
"MIT"
] | null | null | null | #include <vector>
#include <iostream>
#include <cstdlib>
#include <cassert>
#include <cmath>
#include <fstream>
#include <sstream>
using namespace std;
struct Connection
{
double weight;
double deltaWeight;
};
class Neuron;
typedef vector<Neuron> Layer;
class Neuron
{
public:
Neuron(unsigned numOutputs, unsigned myIndex);
void setOutputVal(double val) { m_outputVal = val; }
double getOutputVal(void) const { return m_outputVal; }
void feedForward(const Layer &prevLayer);
void calcOutputGradients(double targetVal);
void calcHiddenGradients(const Layer &nextLayer);
void updateInputWeights(Layer &prevLayer);
private:
static double eta;
static double alpha;
static double transferFunction(double x);
static double transferFunctionDerivative(double x);
static double randomWeight(void) { return rand() / double(RAND_MAX); }
double sumDOW(const Layer &nextLayer) const;
double m_outputVal;
vector<Connection> m_outputWeights;
unsigned m_myIndex;
double m_gradient;
};
double Neuron::eta = 0.15;
double Neuron::alpha = 0.5;
void Neuron::updateInputWeights(Layer &prevLayer)
{
for (unsigned n = 0; n < prevLayer.size(); ++n) {
Neuron &neuron = prevLayer[n];
double oldDeltaWeight = neuron.m_outputWeights[m_myIndex].deltaWeight;
double newDeltaWeight =
neuron.m_outputWeights[m_myIndex].deltaWeight = newDeltaWeight;
neuron.m_outputWeights[m_myIndex].weight += newDeltaWeight;
}
}
double Neuron::sumDOW(const Layer &nextLayer) const
{
double sum = 0.0;
for (unsigned n = 0; n < nextLayer.size() - 1; ++n) {
sum += m_outputWeights[n].weight * nextLayer[n].m_gradient;
}
return sum;
}
void Neuron::calcHiddenGradients(const Layer &nextLayer)
{
double dow = sumDOW(nextLayer);
m_gradient = dow * Neuron::transferFunctionDerivative(m_outputVal);
}
void Neuron::calcOutputGradients(double targetVal)
{
double delta = targetVal - m_outputVal;
m_gradient = delta * Neuron::transferFunctionDerivative(m_outputVal);
}
double Neuron::transferFunction(double x)
{
return tanh(x);
}
double Neuron::transferFunctionDerivative(double x)
{
return 1.0 - x * x;
}
void Neuron::feedForward(const Layer &prevLayer)
{
double sum = 0.0;
for (unsigned n = 0; n < prevLayer.size(); ++n) {
sum += prevLayer[n].getOutputVal() *
prevLayer[n].m_outputWeights[m_myIndex].weight;
}
m_outputVal = Neuron::transferFunction(sum);
}
Neuron::Neuron(unsigned numOutputs, unsigned myIndex)
{
for (unsigned c = 0; c < numOutputs; ++c) {
m_outputWeights.push_back(Connection());
m_outputWeights.back().weight = randomWeight();
}
m_myIndex = myIndex;
}
class Net
{
public:
Net(const vector<unsigned> &topology);
void feedForward(const vector<double> &inputVals);
void backProp(const vector<double> &targetVals);
void getResults(vector<double> &resultVals) const;
double getRecentAverageError(void) const { return m_recentAverageError; }
private:
vector<Layer> m_layers; // m_layers[layerNum][neuronNum]
double m_error;
double m_recentAverageError;
static double m_recentAverageSmoothingFactor;
};
double Net::m_recentAverageSmoothingFactor = 100.0;
void Net::getResults(vector<double> &resultVals) const
{
resultVals.clear();
for (unsigned n = 0; n < m_layers.back().size() - 1; ++n) {
resultVals.push_back(m_layers.back()[n].getOutputVal());
}
}
void Net::backProp(const vector<double> &targetVals)
{
Layer &outputLayer = m_layers.back();
m_error = 0.0;
for (unsigned n = 0; n < outputLayer.size() - 1; ++n) {
double delta = targetVals[n] - outputLayer[n].getOutputVal();
m_error += delta * delta;
}
m_error /= outputLayer.size() - 1; // get average error squared
m_error = sqrt(m_error); // RMS
m_recentAverageError =
(m_recentAverageError * m_recentAverageSmoothingFactor + m_error)
/ (m_recentAverageSmoothingFactor + 1.0);
for (unsigned n = 0; n < outputLayer.size() - 1; ++n) {
outputLayer[n].calcOutputGradients(targetVals[n]);
}
for (unsigned layerNum = m_layers.size() - 2; layerNum > 0; --layerNum) {
Layer &hiddenLayer = m_layers[layerNum];
Layer &nextLayer = m_layers[layerNum + 1];
for (unsigned n = 0; n < hiddenLayer.size(); ++n) {
hiddenLayer[n].calcHiddenGradients(nextLayer);
}
}
for (unsigned layerNum = m_layers.size() - 1; layerNum > 0; --layerNum) {
Layer &layer = m_layers[layerNum];
Layer &prevLayer = m_layers[layerNum - 1];
for (unsigned n = 0; n < layer.size() - 1; ++n) {
layer[n].updateInputWeights(prevLayer);
}
}
}
void Net::feedForward(const vector<double> &inputVals)
{
assert(inputVals.size() == m_layers[0].size() - 1);
for (unsigned i = 0; i < inputVals.size(); ++i) {
m_layers[0][i].setOutputVal(inputVals[i]);
}
for (unsigned layerNum = 1; layerNum < m_layers.size(); ++layerNum) {
Layer &prevLayer = m_layers[layerNum - 1];
for (unsigned n = 0; n < m_layers[layerNum].size() - 1; ++n) {
m_layers[layerNum][n].feedForward(prevLayer);
}
}
}
Net::Net(const vector<unsigned> &topology)
{
unsigned numLayers = topology.size();
for (unsigned layerNum = 0; layerNum < numLayers; ++layerNum) {
m_layers.push_back(Layer());
unsigned numOutputs = layerNum == topology.size() - 1 ? 0 : topology[layerNum + 1];
for (unsigned neuronNum = 0; neuronNum <= topology[layerNum]; ++neuronNum) {
m_layers.back().push_back(Neuron(numOutputs, neuronNum));
cout << "Made a Neuron!" << endl;
}
m_layers.back().back().setOutputVal(1.0);
}
}
void showVectorVals(string label, vector<double> &v)
{
cout << label << " ";
for (unsigned i = 0; i < v.size(); ++i) {
cout << v[i] << " ";
}
cout << endl;
}
// MIT License
// Copyright (c) 2022 Erano-
// 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. | 27.868726 | 91 | 0.66348 | [
"vector"
] |
2150b430353456fbe8e6b86b76d44c0e68207821 | 12,828 | cxx | C++ | Base/QTGUI/qSlicerExtensionsInstallWidget.cxx | TheInterventionCentre/NorMIT-Plan-App | 765ed9a5dccc1cc134b65ccabe93fc132baeb2ea | [
"MIT"
] | null | null | null | Base/QTGUI/qSlicerExtensionsInstallWidget.cxx | TheInterventionCentre/NorMIT-Plan-App | 765ed9a5dccc1cc134b65ccabe93fc132baeb2ea | [
"MIT"
] | null | null | null | Base/QTGUI/qSlicerExtensionsInstallWidget.cxx | TheInterventionCentre/NorMIT-Plan-App | 765ed9a5dccc1cc134b65ccabe93fc132baeb2ea | [
"MIT"
] | null | null | null | /*==============================================================================
Program: 3D Slicer
Copyright (c) Kitware Inc.
See COPYRIGHT.txt
or http://www.slicer.org/copyright/copyright.txt for details.
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.
This file was originally developed by Jean-Christophe Fillion-Robin, Kitware Inc.
and was partially funded by NIH grant 3P41RR013218-12S1
==============================================================================*/
// Qt includes
#include <QDebug>
#include <QDesktopServices>
#include <QWebFrame>
#include <QWebView>
// CTK includes
#include <ctkPimpl.h>
// QtGUI includes
#include "qSlicerExtensionsInstallWidget.h"
#include "qSlicerExtensionsManagerModel.h"
//-----------------------------------------------------------------------------
class qSlicerExtensionsInstallWidgetPrivate
{
Q_DECLARE_PUBLIC(qSlicerExtensionsInstallWidget);
protected:
qSlicerExtensionsInstallWidget* const q_ptr;
public:
qSlicerExtensionsInstallWidgetPrivate(qSlicerExtensionsInstallWidget& object);
/// Return the URL allowing to retrieve the extension list page
/// associated with the current architecture, operating system and slicer revision.
QUrl extensionsListUrl();
void setFailurePage(const QStringList &errors);
qSlicerExtensionsManagerModel * ExtensionsManagerModel;
QString SlicerRevision;
QString SlicerOs;
QString SlicerArch;
bool BrowsingEnabled;
};
// --------------------------------------------------------------------------
qSlicerExtensionsInstallWidgetPrivate::qSlicerExtensionsInstallWidgetPrivate(qSlicerExtensionsInstallWidget& object)
: q_ptr(&object), BrowsingEnabled(true)
{
this->ExtensionsManagerModel = 0;
}
// --------------------------------------------------------------------------
QUrl qSlicerExtensionsInstallWidgetPrivate::extensionsListUrl()
{
QUrl url(this->ExtensionsManagerModel->serverUrlWithExtensionsStorePath());
url.setQueryItems(QList<QPair<QString, QString> >()
<< QPair<QString, QString>("layout", "empty")
<< QPair<QString, QString>("os", this->SlicerOs)
<< QPair<QString, QString>("arch", this->SlicerArch)
<< QPair<QString, QString>("revision", this->SlicerRevision));
return url;
}
// --------------------------------------------------------------------------
void qSlicerExtensionsInstallWidgetPrivate::setFailurePage(const QStringList& errors)
{
Q_Q(qSlicerExtensionsInstallWidget);
QString html =
"<style type='text/css'>"
" div.viewWrapperSlicer{"
" font-family:'Lucida Grande','Lucida Sans Unicode',helvetica,arial,Verdana,sans-serif;"
" font-size:13px;margin-left:8px;color:#777777;"
" }"
" div.extensionsHeader,div.extensionsBody{margin-right:10px;}"
" div.extensionsHeader{height:45px;border-bottom:1px solid #d0d0d0;}"
" div.extensionsTitle{float:left;font-size:24px;font-weight:bolder;margin-top:10px;}"
" div.extensionsBodyLeftColumn{float:left;width:230px;border-right:1px solid #d0d0d0;min-height:450px;}"
" div.extensionsBodyRightColumn{margin-left:230px;}"
" div.error{"
" position: relative;"
" min-width: 13em; max-width: 52em; margin: 4em auto;"
" border: 1px solid threedshadow; border-radius: 10px 10px 10px 10px;"
" padding: 3em;"
" -webkit-padding-start: 30px;"
" background: url('qrc:Icons/ExtensionError.svg') no-repeat scroll left 0px content-box border-box;"
" }"
" #errorTitle, #errorDescription {-webkit-margin-start:80px;}"
" #errorTitle h1 {margin:0px 0px 0.6em;}"
" #errorDescription ul{"
" list-style: square outside none;"
" margin: 0px; -webkit-margin-start: 1.5em; padding: 0px;"
" }"
" #errorDescription ul > li{margin-bottom: 0.5em;}"
" #errorTryAgain{margin-top: 2em;}"
"</style>"
"<div class='viewWrapperSlicer'>"
" <div class='extensionsHeader'>"
" <div class='extensionsTitle'>Slicer Extensions</div>"
" </div>"
" <div class='extensionsBody'>"
" <!-- Following layout and associated CSS style are inspired from Mozilla error message. -->"
" <!-- It is originally covered by http://mozilla.org/MPL/2.0/ license -->"
" <!-- MPL 2.0 license is compatible with Slicer (BSD-like) license -->"
" <div class='error'>"
" <div id='errorTitle'><h1>Ooop. Extensions can not be installed !</h1></div>"
" <div id='errorDescription'>"
" <ul>"
"%1"
" <li>Check that <b>3D Slicer</b> is properly installed. "
"<a href='http://www.slicer.org/slicerWiki/index.php/Documentation/Slicer/Install'>Read more ?</a></li>"
" </ul>"
" <button id='errorTryAgain' onclick='window.extensions_install_widget.refresh();' autofocus='true'>Try Again</button>"
" </div>"
" </div>"
" </div>"
"</div>";
QStringList htmlErrors;
foreach(const QString& error, errors)
{
htmlErrors << QString("<li>%1</li>").arg(error);
}
q->webView()->setHtml(html.arg(htmlErrors.join("/n")));
}
// --------------------------------------------------------------------------
qSlicerExtensionsInstallWidget::qSlicerExtensionsInstallWidget(QWidget* _parent)
: Superclass(_parent)
, d_ptr(new qSlicerExtensionsInstallWidgetPrivate(*this))
{
this->webView()->page()->setLinkDelegationPolicy(QWebPage::DelegateExternalLinks);
}
// --------------------------------------------------------------------------
qSlicerExtensionsInstallWidget::~qSlicerExtensionsInstallWidget()
{
}
// --------------------------------------------------------------------------
qSlicerExtensionsManagerModel* qSlicerExtensionsInstallWidget::extensionsManagerModel()const
{
Q_D(const qSlicerExtensionsInstallWidget);
return d->ExtensionsManagerModel;
}
// --------------------------------------------------------------------------
void qSlicerExtensionsInstallWidget::setExtensionsManagerModel(qSlicerExtensionsManagerModel* model)
{
Q_D(qSlicerExtensionsInstallWidget);
if (this->extensionsManagerModel() == model)
{
return;
}
disconnect(this, SLOT(onExtensionInstalled(QString)));
//disconnect(this, SLOT(onExtensionUninstalled(QString)));
disconnect(this, SLOT(onExtensionScheduledForUninstall(QString)));
disconnect(this, SLOT(onSlicerRequirementsChanged(QString,QString,QString)));
disconnect(this, SLOT(onMessageLogged(QString,ctkErrorLogLevel::LogLevels)));
disconnect(this, SLOT(onDownloadStarted(QNetworkReply*)));
disconnect(this, SLOT(onDownloadFinished(QNetworkReply*)));
d->ExtensionsManagerModel = model;
if (model)
{
this->onSlicerRequirementsChanged(
model->slicerRevision(), model->slicerOs(), model->slicerArch());
QObject::connect(model, SIGNAL(extensionInstalled(QString)),
this, SLOT(onExtensionInstalled(QString)));
QObject::connect(model, SIGNAL(extensionScheduledForUninstall(QString)),
this, SLOT(onExtensionScheduledForUninstall(QString)));
QObject::connect(model, SIGNAL(extensionCancelledScheduleForUninstall(QString)),
this, SLOT(onExtensionCancelledScheduleForUninstall(QString)));
QObject::connect(model, SIGNAL(slicerRequirementsChanged(QString,QString,QString)),
this, SLOT(onSlicerRequirementsChanged(QString,QString,QString)));
QObject::connect(model, SIGNAL(messageLogged(QString,ctkErrorLogLevel::LogLevels)),
this, SLOT(onMessageLogged(QString,ctkErrorLogLevel::LogLevels)));
QObject::connect(model, SIGNAL(downloadStarted(QNetworkReply*)),
this, SLOT(onDownloadStarted(QNetworkReply*)));
QObject::connect(model, SIGNAL(downloadFinished(QNetworkReply*)),
this, SLOT(onDownloadFinished(QNetworkReply*)));
}
}
// --------------------------------------------------------------------------
CTK_GET_CPP(qSlicerExtensionsInstallWidget, QString, slicerRevision, SlicerRevision)
CTK_SET_CPP(qSlicerExtensionsInstallWidget, const QString&, setSlicerRevision, SlicerRevision)
// --------------------------------------------------------------------------
CTK_GET_CPP(qSlicerExtensionsInstallWidget, QString, slicerOs, SlicerOs)
CTK_SET_CPP(qSlicerExtensionsInstallWidget, const QString&, setSlicerOs, SlicerOs)
// --------------------------------------------------------------------------
CTK_GET_CPP(qSlicerExtensionsInstallWidget, QString, slicerArch, SlicerArch)
CTK_SET_CPP(qSlicerExtensionsInstallWidget, const QString&, setSlicerArch, SlicerArch)
// --------------------------------------------------------------------------
CTK_GET_CPP(qSlicerExtensionsInstallWidget, bool, isBrowsingEnabled, BrowsingEnabled)
CTK_SET_CPP(qSlicerExtensionsInstallWidget, bool, setBrowsingEnabled, BrowsingEnabled)
// --------------------------------------------------------------------------
void qSlicerExtensionsInstallWidget::refresh()
{
Q_D(qSlicerExtensionsInstallWidget);
if (!d->ExtensionsManagerModel)
{
return;
}
QStringList errors = this->extensionsManagerModel()->checkInstallPrerequisites();
if (!errors.empty())
{
d->setFailurePage(errors);
return;
}
this->webView()->setUrl(d->extensionsListUrl());
}
// --------------------------------------------------------------------------
void qSlicerExtensionsInstallWidget::onExtensionInstalled(const QString& extensionName)
{
this->evalJS(QString("midas.slicerappstore.setExtensionButtonState('%1', 'ScheduleUninstall')").arg(extensionName));
}
// --------------------------------------------------------------------------
void qSlicerExtensionsInstallWidget::onExtensionScheduledForUninstall(const QString& extensionName)
{
this->evalJS(QString("midas.slicerappstore.setExtensionButtonState('%1', 'CancelScheduledForUninstall')").arg(extensionName));
}
// -------------------------------------------------------------------------
void qSlicerExtensionsInstallWidget::onExtensionCancelledScheduleForUninstall(const QString& extensionName)
{
this->onExtensionInstalled(extensionName);
}
// --------------------------------------------------------------------------
void qSlicerExtensionsInstallWidget::onSlicerRequirementsChanged(const QString& revision,const QString& os,const QString& arch)
{
Q_D(qSlicerExtensionsInstallWidget);
this->setSlicerRevision(revision);
this->setSlicerOs(os);
this->setSlicerArch(arch);
if (d->BrowsingEnabled)
{
this->refresh();
}
}
// --------------------------------------------------------------------------
void qSlicerExtensionsInstallWidget::onMessageLogged(const QString& text, ctkErrorLogLevel::LogLevels level)
{
QString delay = "2500";
QString state;
if (level == ctkErrorLogLevel::Warning)
{
delay = "10000";
state = "warning";
}
else if(level == ctkErrorLogLevel::Critical || level == ctkErrorLogLevel::Fatal)
{
delay = "10000";
state = "error";
}
this->evalJS(QString("midas.createNotice('%1', %2, '%3')").arg(text).arg(delay).arg(state));
}
// --------------------------------------------------------------------------
void qSlicerExtensionsInstallWidget::initJavascript()
{
Q_D(qSlicerExtensionsInstallWidget);
this->Superclass::initJavascript();
this->webView()->page()->mainFrame()->addToJavaScriptWindowObject(
"extensions_manager_model", d->ExtensionsManagerModel);
this->webView()->page()->mainFrame()->addToJavaScriptWindowObject(
"extensions_install_widget", this);
}
// --------------------------------------------------------------------------
void qSlicerExtensionsInstallWidget::onLoadFinished(bool ok)
{
Q_D(qSlicerExtensionsInstallWidget);
this->Superclass::onLoadFinished(ok);
if(!ok)
{
d->setFailurePage(QStringList() << QString("Failed to load extension page using this URL: <strong>%1</strong>")
.arg(d->extensionsListUrl().toString()));
}
}
// --------------------------------------------------------------------------
void qSlicerExtensionsInstallWidget::onLinkClicked(const QUrl& url)
{
if(url.host() == this->extensionsManagerModel()->serverUrl().host())
{
this->Superclass::onLinkClicked(url);
}
else
{
if(!QDesktopServices::openUrl(url))
{
qWarning() << "Failed to open url:" << url;
}
}
}
| 38.755287 | 132 | 0.610695 | [
"object",
"model",
"3d",
"solid"
] |
21586d59a56b05e2cabd2620dbba3a35810dc5df | 22,639 | cpp | C++ | src/api/dcps/isocpp2/code/org/opensplice/core/ListenerDispatcher.cpp | agenihorganization/opensplice | 314d3a4538474f2b8e22acffe3c206f4ac38b66b | [
"Apache-2.0"
] | null | null | null | src/api/dcps/isocpp2/code/org/opensplice/core/ListenerDispatcher.cpp | agenihorganization/opensplice | 314d3a4538474f2b8e22acffe3c206f4ac38b66b | [
"Apache-2.0"
] | null | null | null | src/api/dcps/isocpp2/code/org/opensplice/core/ListenerDispatcher.cpp | agenihorganization/opensplice | 314d3a4538474f2b8e22acffe3c206f4ac38b66b | [
"Apache-2.0"
] | null | null | null | /*
* OpenSplice DDS
*
* This software and documentation are Copyright 2006 to TO_YEAR PrismTech
* Limited, its affiliated companies and licensors. 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.
*
*/
/**
* @file
*/
#include <org/opensplice/core/ScopedLock.hpp>
#include <org/opensplice/core/ListenerDispatcher.hpp>
#include <org/opensplice/core/status/StatusUtils.hpp>
#if 0
#define TRACE_EVENT printf
#else
#define TRACE_EVENT(...)
#endif
#define LISTENER_INITIAL_EVENTS 16
org::opensplice::core::ListenerDispatcher::ListenerDispatcher(
u_participant participant,
const org::opensplice::core::policy::ListenerScheduling& scheduling)
: threadId(OS_THREAD_ID_NONE),
threadState(STOPPED),
scheduling(scheduling)
{
u_cfElement cfg;
os_result osResult;
assert(participant);
osResult = os_mutexInit(&this->mutex, NULL);
ISOCPP_OS_RESULT_CHECK_AND_THROW(osResult, "Could not initialize mutex.");
osResult = os_condInit (&this->cond, &this->mutex, NULL);
ISOCPP_OS_RESULT_CHECK_AND_THROW(osResult, "Could not initialize cond.");
cfg = u_participantGetConfiguration(participant);
if(cfg){
this->stackSize = this->getStackSize(cfg);
u_cfElementFree(cfg);
} else {
this->stackSize = DEFAULT_STACKSIZE;
}
this->uListener = u_listenerNew(u_entity(participant), OS_TRUE);
if (!this->uListener) {
ISOCPP_THROW_EXCEPTION(ISOCPP_ERROR, "Could not get user layer listener.");
}
this->eventListHead = NULL;
this->eventListTail = NULL;
this->freeList = NULL;
for (unsigned i = 0; i < LISTENER_INITIAL_EVENTS; i++) {
v_listenerEvent event = new C_STRUCT(v_listenerEvent);
event->next = this->freeList;
this->freeList = event;
}
}
org::opensplice::core::ListenerDispatcher::~ListenerDispatcher()
{
os_result osResult;
os_duration timeout = 100*OS_DURATION_MILLISECOND;
int i = 0;
bool stop = false;
os_mutexLock(&this->mutex);
/* Stop thread, which also waits until it is stopped. */
if (this->threadState == RUNNING) {
this->threadState = STOPPING;
}
while ((this->threadState != STOPPED) && (!stop)) {
/* This loop will poll at 100ms and repeat notifying the uListener because
* triggers may be missed by the listenerEventThread when the trigger is
* issued just before the listenerEventThread enters the u_listenerWait.
* Polling can be avoided if u_listenerNotify not only generates a trigger
* but also internally keeps an event indicating the notification but the
* current implementation is considered acceptable since this is only
* during stopping the thread.
*/
(void) u_listenerNotify(this->uListener);
osResult = os_condTimedWait(&this->cond, &this->mutex, timeout);
if (osResult == os_resultFail) {
stop = true;
} else if (osResult == os_resultTimeout) {
i++;
if (i > 50) { /* MAX blocking time = 50*100ms */
stop = true;
}
}
}
if (this->uListener) {
u_objectFree (u_object (this->uListener));
this->uListener = NULL;
}
os_mutexUnlock(&this->mutex);
if (os_threadIdToInteger(this->threadId) != os_threadIdToInteger(OS_THREAD_ID_NONE)) {
(void)os_threadWaitExit(this->threadId, NULL);
}
v_listenerEvent event = this->eventListHead;
while (event) {
this->eventListHead = event->next;
c_free(c_object(event->eventData));
delete event;
event = this->eventListHead;
}
event = this->freeList;
while (event) {
this->freeList = event->next;
delete event;
event = this->freeList;
}
os_condDestroy (&this->cond);
os_mutexDestroy (&this->mutex);
}
void
org::opensplice::core::ListenerDispatcher::add_listener(
org::opensplice::core::EntityDelegate* observable,
u_entity uEntity,
const dds::core::status::StatusMask& mask)
{
u_result uResult;
v_eventMask vMask;
assert(observable);
assert(uEntity);
os_mutexLock(&this->mutex);
/* (re)Insert observable into the set. */
this->observables.insert(observable);
/* Set the listener on the user layer. */
vMask = org::opensplice::core::utils::vEventMaskFromStatusMask(mask);
TRACE_EVENT("0x%08lx::ListenerDispatcher::add(observable = 0x%08lx, uEntity = 0x%08lx, mask = 0x%08lx)\n",
this, observable, uEntity, vMask);
uResult = u_entitySetListener(uEntity, this->uListener, NULL, vMask);
try {
ISOCPP_U_RESULT_CHECK_AND_THROW(uResult, "Could not set listener on user layer.");
/* This won't start the thread when it is already running. */
this->threadStart();
os_mutexUnlock(&this->mutex);
} catch (...) {
(void)this->observables.erase(observable);
os_mutexUnlock(&this->mutex);
throw;
}
}
void
org::opensplice::core::ListenerDispatcher::remove_listener(
org::opensplice::core::EntityDelegate* observable,
u_entity uEntity)
{
os_threadId stoppedThread = OS_THREAD_ID_NONE;
u_result uResult;
os_result oResult;
assert(observable);
assert(uEntity);
os_mutexLock(&this->mutex);
/* Remove observable from local management. */
if (this->observables.erase(observable) != 1) {
/* Trying to remove a listener that was not added... */
os_mutexUnlock(&this->mutex);
return;
}
TRACE_EVENT("0x%08lx::ListenerDispatcher::remove_listener(observable = 0x%08lx, uEntity = 0x%08lx)\n",
this, observable, uEntity);
org::opensplice::core::ScopedMutexLock scopedLock(this->entities_mutex);
this->invalid_user_entities.insert(uEntity);
TRACE_EVENT("0x%08lx::ListenerDispatcher::remove_listener(): invalid_user_entities count %d\n", this, (int)this->invalid_user_entities.size());
scopedLock.unlock();
/* Remove observable from user layer. */
uResult = u_entitySetListener(uEntity, NULL, NULL, 0);
if (uResult != U_RESULT_OK) {
os_mutexUnlock(&this->mutex);
ISOCPP_U_RESULT_CHECK_AND_THROW(uResult, "Could not (re)set listener on user layer.");
}
/* Stop the dispatcher when there are no more observables. */
TRACE_EVENT("0x%08lx::ListenerDispatcher::remove_listener(): observable count %d\n", this, (int)this->observables.size());
TRACE_EVENT("0x%08lx::ListenerDispatcher::remove_listener(): thread state %d\n", this, (int)this->threadState);
if ((this->observables.size() == 0) && (this->threadState == RUNNING)) {
this->threadState = STOPPING;
TRACE_EVENT("0x%08lx::ListenerDispatcher::remove_listener(): wake up thread\n", this);
(void)u_listenerNotify(this->uListener);
stoppedThread = this->threadId;
}
/* Wait until dispatcher thread is complete when needed. */
os_mutexUnlock(&this->mutex);
if ((os_threadIdToInteger(stoppedThread) != os_threadIdToInteger(OS_THREAD_ID_NONE)) &&
(os_threadIdToInteger(stoppedThread) != os_threadIdToInteger(os_threadIdSelf())) ) {
/* Don't wait, we're the thread itself or it isn't stopped. */
oResult = os_threadWaitExit(stoppedThread, NULL);
ISOCPP_OS_RESULT_CHECK_AND_THROW(oResult, "Waiting for thread exit failed");
}
}
void
org::opensplice::core::ListenerDispatcher::add_source(
org::opensplice::core::EntityDelegate* source,
u_entity uEntity)
{
/* We need to add the source to the userlayer to get back to the original entity. */
assert(source);
assert(uEntity);
TRACE_EVENT("0x%08lx::ListenerDispatcher::add_source(observable = 0x%08lx, uEntity = 0x%08lx)\n",
this, source, uEntity);
u_observableSetUserData(u_observable(uEntity), source);
}
void
org::opensplice::core::ListenerDispatcher::remove_source(
org::opensplice::core::EntityDelegate* source,
u_entity uEntity)
{
assert(source);
assert(uEntity);
TRACE_EVENT("0x%08lx::ListenerDispatcher::remove_source(observable = 0x%08lx, uEntity = 0x%08lx)\n",
this, source, uEntity);
org::opensplice::core::ScopedMutexLock scopedLock(this->entities_mutex);
bool triggered = u_entityDisableCallbacks(uEntity);
if (triggered) {
this->invalid_user_entities.insert(uEntity);
TRACE_EVENT("0x%08lx::ListenerDispatcher::remove_source(): invalid_user_entities count %d\n", this, (int)this->invalid_user_entities.size());
}
scopedLock.unlock();
u_observableSetUserData(u_observable(uEntity), NULL);
}
uint32_t
org::opensplice::core::ListenerDispatcher::getStackSize(
u_cfElement configuration)
{
u_cfData cfg_data = NULL;
c_iter nodes;
u_cfNode tmp;
c_ulong stackSize = DEFAULT_STACKSIZE;
assert(configuration);
/* Resolve StackSize parameter. */
nodes = u_cfElementXPath(configuration, "Domain/Listeners/StackSize/#text");
tmp = u_cfNode(c_iterTakeFirst(nodes));
if (tmp != NULL) {
if (u_cfNodeKind(tmp) == V_CFDATA) {
cfg_data = u_cfData(tmp);
} else {
u_cfNodeFree(tmp);
}
tmp = u_cfNode(c_iterTakeFirst(nodes));
}
while (tmp != NULL) {
u_cfNodeFree(tmp);
tmp = u_cfNode(c_iterTakeFirst(nodes));
}
c_iterFree(nodes);
/* Translate StackSize parameter. */
if (cfg_data != NULL) {
if (!u_cfDataULongValue(cfg_data, &stackSize)) {
stackSize = DEFAULT_STACKSIZE;
}
u_cfDataFree(cfg_data);
}
return (uint32_t)stackSize;
}
void
org::opensplice::core::ListenerDispatcher::threadStart()
{
os_result osResult;
os_threadAttr osThreadAttr;
switch (this->threadState) {
case STOPPED:
TRACE_EVENT("0x%08lx::ListenerDispatcher::threadStart(): STARTING\n", this);
this->threadState = STARTING;
os_condBroadcast(&this->cond);
os_threadAttrInit(&osThreadAttr);
this->scheduling->os_thread_attr(&osThreadAttr);
if (this->stackSize != DEFAULT_STACKSIZE) {
osThreadAttr.stackSize = this->stackSize;
}
/* Create thread */
osResult = os_threadCreate(&this->threadId,
"ListenerDispatcherThread",
&osThreadAttr,
&org::opensplice::core::ListenerDispatcher::threadWrapper,
(void *)this);
ISOCPP_OS_RESULT_CHECK_AND_THROW(osResult, "Failed to start thread.");
break;
case STOPPING:
this->threadState = RUNNING;
break;
/* No action required, Wait for state to be RUNNING. */
default:
break;
}
while (this->threadState == STARTING) {
/* Wait for event handler loop to switch state to !STARTING. */
os_condWait (&this->cond, &this->mutex);
}
os_condBroadcast (&this->cond);
}
void *
org::opensplice::core::ListenerDispatcher::threadWrapper(
void *arg)
{
org::opensplice::core::ListenerDispatcher *dispatcher = static_cast<org::opensplice::core::ListenerDispatcher*>(arg);
dispatcher->thread();
return NULL;
}
void
org::opensplice::core::ListenerDispatcher::thread()
{
os_result osResult;
u_result uResult = U_RESULT_OK;
/* Needed to remove the 'variable set but not used' compile warning. */
OS_UNUSED_ARG(osResult);
TRACE_EVENT("0x%08lx::ListenerDispatcher::thread(): Start\n", this);
/* Indicate that the thread is running. */
os_mutexLock(&this->mutex);
if (this->threadState == STARTING) {
TRACE_EVENT("0x%08lx::ListenerDispatcher::thread(): STARTING\n", this);
this->threadState = RUNNING;
os_condBroadcast(&this->cond);
}
TRACE_EVENT("0x%08lx::ListenerDispatcher::thread(): RUNNING\n", this);
/* The main listening thread loop. */
while ((uResult == U_RESULT_OK) && (this->threadState == RUNNING)) {
os_mutexUnlock(&this->mutex);
//TRACE_EVENT("0x%08lx::ListenerDispatcher::thread(): Enter Wait\n", this);
uResult = u_listenerWait(this->uListener,
org::opensplice::core::ListenerDispatcher::eventHandlerWrapper,
this,
10*OS_DURATION_MILLISECOND);
if (uResult == U_RESULT_OK) {
this->processEvents();
}
if (uResult != U_RESULT_TIMEOUT) {
TRACE_EVENT("0x%08lx::ListenerDispatcher::thread(): Exit Wait, uResult = %s, state %d\n", this, u_resultImage(uResult), (int)this->threadState);
}
os_mutexLock(&this->mutex);
if (uResult == U_RESULT_TIMEOUT) {
uResult = U_RESULT_OK;
}
}
/* Indicate that the thread has shut down. */
this->threadState = STOPPED;
TRACE_EVENT("0x%08lx::ListenerDispatcher::thread(): STOPPED\n", this);
os_condBroadcast(&this->cond);
os_mutexUnlock(&this->mutex);
TRACE_EVENT("0x%08lx::ListenerDispatcher::thread(): Exit\n", this);
this->threadId = OS_THREAD_ID_NONE;
}
static v_status
copyStatus(
v_status s)
{
v_status copy = NULL;
if (s) {
switch (v_objectKind(s)) {
case K_KERNELSTATUS:
copy = static_cast<v_status>(os_malloc(sizeof(C_STRUCT(v_kernelStatus))));
memcpy(copy, s, sizeof(C_STRUCT(v_kernelStatus)));
break;
case K_TOPICSTATUS:
copy = static_cast<v_status>(os_malloc(sizeof(C_STRUCT(v_topicStatus))));
memcpy(copy, s, sizeof(C_STRUCT(v_topicStatus)));
break;
case K_DOMAINSTATUS:
copy = static_cast<v_status>(os_malloc(sizeof(C_STRUCT(v_partitionStatus))));
memcpy(copy, s, sizeof(C_STRUCT(v_partitionStatus)));
break;
case K_WRITERSTATUS:
copy = static_cast<v_status>(os_malloc(sizeof(C_STRUCT(v_writerStatus))));
memcpy(copy, s, sizeof(C_STRUCT(v_writerStatus)));
break;
case K_READERSTATUS:
copy = static_cast<v_status>(os_malloc(sizeof(C_STRUCT(v_readerStatus))));
memcpy(copy, s, sizeof(C_STRUCT(v_readerStatus)));
break;
case K_PARTICIPANTSTATUS:
copy = static_cast<v_status>(os_malloc(sizeof(C_STRUCT(v_status))));
memcpy(copy, s, sizeof(C_STRUCT(v_status)));
break;
case K_SUBSCRIBERSTATUS:
copy = static_cast<v_status>(os_malloc(sizeof(C_STRUCT(v_status))));
memcpy(copy, s, sizeof(C_STRUCT(v_status)));
break;
case K_PUBLISHERSTATUS:
copy = static_cast<v_status>(os_malloc(sizeof(C_STRUCT(v_status))));
/* These status are just instantations of v_status and have no
* addition attributes! */
memcpy(copy, s, sizeof(C_STRUCT(v_status)));
break;
default:
OS_REPORT(OS_CRITICAL,
"v_statusCopyOut", V_RESULT_ILL_PARAM,
"Unknown object kind %d",
v_objectKind(s));
break;
}
}
return copy;
}
void
org::opensplice::core::ListenerDispatcher::addEvent(
v_listenerEvent e)
{
v_listenerEvent event = this->freeList;
if (event) {
this->freeList = event->next;
} else {
event = new C_STRUCT(v_listenerEvent);
}
/* Copy the listener event */
event->kind = e->kind;
event->source = e->source;
event->userData = e->userData;
if (event->kind == V_EVENT_DATA_AVAILABLE) {
/* the eventData is a reference to the actual data causing this event. */
event->eventData = e->eventData;
} else {
/* the event is caused by a communication status change, the eventData contains the status that is changed. */
event->eventData = copyStatus(v_status(e->eventData));
}
event->next = NULL;
if (this->eventListTail) {
this->eventListTail->next = event;
} else {
this->eventListHead = event;
}
this->eventListTail = event;
}
void
org::opensplice::core::ListenerDispatcher::eventHandlerWrapper(
v_listenerEvent event,
c_voidp arg)
{
org::opensplice::core::ListenerDispatcher *dispatcher = static_cast<org::opensplice::core::ListenerDispatcher*>(arg);
dispatcher->addEvent(event);
}
void
org::opensplice::core::ListenerDispatcher::eventHandler (
v_listenerEvent event)
{
u_entity uSource;
u_entity uListener;
assert(event);
if (event->kind & V_EVENT_TRIGGER) {
/* Nothing to deliver so ignore. */
TRACE_EVENT("static::ListenerDispatcher::eventHandler: received V_EVENT_TRIGGER\n");
return;
}
/* Prevent entity deletion during callback by not allowing the removal of listeners. */
org::opensplice::core::ScopedMutexLock scopedLock(this->entities_mutex);
/* Extract source entity from event source. */
uSource = u_entity(event->source);
assert (uSource != NULL);
TRACE_EVENT("static::ListenerDispatcher::eventHandler: u source 0x%08lx (%d)\n", (unsigned long)uSource, (int)u_objectKind(u_object(uSource)));
/* Extract listening entity instance from user data. */
uListener = u_entity(event->userData);
assert (uListener != NULL);
TRACE_EVENT("static::ListenerDispatcher::eventHandler: u listener 0x%08lx (%d)\n", (unsigned long)uListener, (int)u_objectKind(u_object(uListener)));
/* Check if we've received events from entities that are being/have been removed. */
std::multiset<u_entity>::iterator itSource = this->invalid_user_entities.find(uSource);
if ((itSource != this->invalid_user_entities.end()) ||
(this->invalid_user_entities.find(uListener) != this->invalid_user_entities.end()) ) {
/* We've received events from entity/entities that are being/have been removed. */
if (event->kind & (V_EVENT_OBJECT_DESTROYED | V_EVENT_PREPARE_DELETE)) {
/* We've received the destroy event, so we can delete the related entity from the adminstration. */
this->invalid_user_entities.erase(itSource);
}
TRACE_EVENT("static::ListenerDispatcher::remove_listener(): invalid_user_entities count %d\n", (int)this->invalid_user_entities.size());
/* Ignore these events. */
return;
}
org::opensplice::core::ObjectDelegate::ref_type sRef(
org::opensplice::core::EntityDelegate::extract_strong_ref(uSource));
org::opensplice::core::ObjectDelegate::ref_type lRef(
org::opensplice::core::EntityDelegate::extract_strong_ref(uListener));
/* The strong refs go out of scope, meaning that it is possible that the related entities
* are deleted. This will result in listener removals.
* Be sure to be unlocked before the strong refs go out of scope. */
scopedLock.unlock();
TRACE_EVENT("static::ListenerDispatcher::eventHandler: flags 0x%08lx\n", event->kind);
if (event->kind & (V_EVENT_OBJECT_DESTROYED | V_EVENT_PREPARE_DELETE)) {
/* We should only get these events from invalid entities, which means that they
* should already have been handled. */
assert(false);
} else {
/* Call entity to notify its listener of the current event
* (when they're not in the process of being deleted. */
if (lRef && sRef) {
TRACE_EVENT("static::ListenerDispatcher::eventHandler: trigger 0x%08lx\n", (unsigned long)(lRef.get()));
OSPL_CXX11_STD_MODULE::dynamic_pointer_cast<org::opensplice::core::EntityDelegate>(lRef)
->listener_entity_notify(sRef, event->kind, event->eventData);
}
}
}
void
org::opensplice::core::ListenerDispatcher::processEvents()
{
v_listenerEvent event;
event = this->eventListHead;
while (event) {
this->eventListHead = event->next;
if (!this->eventListHead) {
this->eventListTail = NULL;
}
this->eventHandler(event);
if (event->kind != V_EVENT_DATA_AVAILABLE) {
/* eventData is either a reference to a copy of the entities status in case of
* communication events or a reference to the data in case of a data available event.
* only copies on heap need to be freed, i.e. all other than data available events.
*/
os_free(event->eventData);
}
event->next = this->freeList;
this->freeList = event;
event = this->eventListHead;
}
}
/*
* Special create and destroy functionallity.
*/
org::opensplice::core::ListenerDispatcher*
org::opensplice::core::ListenerDispatcher::create(
u_participant participant,
const org::opensplice::core::policy::ListenerScheduling& scheduling)
{
return new ListenerDispatcher(participant, scheduling);
}
void
org::opensplice::core::ListenerDispatcher::destroy(
org::opensplice::core::ListenerDispatcher* ld)
{
assert(ld);
org::opensplice::core::ScopedMutexLock scopedLock(org::opensplice::core::ListenerDispatcher::livecycle_mutex);
/* Stop thread. */
if (ld->threadState == RUNNING) {
ld->threadState = STOPPING;
}
/* Wake up thread. */
u_result result = u_listenerNotify(ld->uListener);
if (result != U_RESULT_ALREADY_DELETED) {
ISOCPP_U_RESULT_CHECK_AND_THROW(result, "Could not destroy ListenerDispatcher.");
}
/* Don't delete the given ListenerDispatcher, but store it in a strong
* reference. See the header file for the explanation. */
org::opensplice::core::ListenerDispatcher::livecycle_ref.reset(ld);
}
org::opensplice::core::ListenerDispatcher::ref_type org::opensplice::core::ListenerDispatcher::livecycle_ref;
org::opensplice::core::Mutex org::opensplice::core::ListenerDispatcher::livecycle_mutex;
| 35.26324 | 156 | 0.647467 | [
"object"
] |
215fba5cf67c995b7ebe4e2f5f0c17aeb5a808d0 | 20,857 | cc | C++ | src/womersley/womersley_elements.cc | PuneetMatharu/oomph-lib | edd590cbb4f3ef9940b9738f18275ea2fb828c55 | [
"RSA-MD"
] | null | null | null | src/womersley/womersley_elements.cc | PuneetMatharu/oomph-lib | edd590cbb4f3ef9940b9738f18275ea2fb828c55 | [
"RSA-MD"
] | 1 | 2022-03-23T16:16:41.000Z | 2022-03-23T16:16:41.000Z | src/womersley/womersley_elements.cc | PuneetMatharu/oomph-lib | edd590cbb4f3ef9940b9738f18275ea2fb828c55 | [
"RSA-MD"
] | null | null | null | // LIC// ====================================================================
// LIC// This file forms part of oomph-lib, the object-oriented,
// LIC// multi-physics finite-element library, available
// LIC// at http://www.oomph-lib.org.
// LIC//
// LIC// Copyright (C) 2006-2022 Matthias Heil and Andrew Hazel
// LIC//
// LIC// This library is free software; you can redistribute it and/or
// LIC// modify it under the terms of the GNU Lesser General Public
// LIC// License as published by the Free Software Foundation; either
// LIC// version 2.1 of the License, or (at your option) any later version.
// LIC//
// LIC// This library is distributed in the hope that it will be useful,
// LIC// but WITHOUT ANY WARRANTY; without even the implied warranty of
// LIC// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// LIC// Lesser General Public License for more details.
// LIC//
// LIC// You should have received a copy of the GNU Lesser General Public
// LIC// License along with this library; if not, write to the Free Software
// LIC// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
// LIC// 02110-1301 USA.
// LIC//
// LIC// The authors may be contacted at oomph-lib@maths.man.ac.uk.
// LIC//
// LIC//====================================================================
// Non-inline functions for Womersley elements
#include "womersley_elements.h"
namespace oomph
{
/// Default Womersley number
template<unsigned DIM>
double WomersleyEquations<DIM>::Default_ReSt_value = 0.0;
//========================================================================
/// Instantiation of static bool to suppress warning; initialise to false.
//========================================================================
bool TemplateFreeWomersleyMeshBase::Suppress_warning_about_unpinned_nst_dofs =
false;
//========================================================================
/// Zero!
//========================================================================
double TemplateFreeWomersleyImpedanceTubeBase::Zero = 0.0;
//======================================================================
// Set the data for the number of Variables at each node
//======================================================================
template<unsigned DIM, unsigned NNODE_1D>
const unsigned QWomersleyElement<DIM, NNODE_1D>::Initial_Nvalue = 1;
//======================================================================
/// Compute element residual Vector and/or element Jacobian matrix
///
/// flag=1: compute both
/// flag=0: compute only residual Vector
///
/// Pure version without hanging nodes
//======================================================================
template<unsigned DIM>
void WomersleyEquations<DIM>::fill_in_generic_residual_contribution_womersley(
Vector<double>& residuals, DenseMatrix<double>& jacobian, unsigned flag)
{
// Find out how many nodes there are
unsigned n_node = nnode();
// Find the index at which the variable is stored
unsigned u_nodal_index = u_index_womersley();
// Set up memory for the shape and test functions
Shape psi(n_node), test(n_node);
DShape dpsidx(n_node, DIM), dtestdx(n_node, DIM);
// Set the value of n_intpt
unsigned n_intpt = integral_pt()->nweight();
// Set the Vector to hold local coordinates
Vector<double> s(DIM);
// Integers to hold the local equation and unknowns
int local_eqn = 0, local_unknown = 0;
// Loop over the integration points
for (unsigned ipt = 0; ipt < n_intpt; ipt++)
{
// Assign values of s
for (unsigned i = 0; i < DIM; i++) s[i] = integral_pt()->knot(ipt, i);
// Get the integral weight
double w = integral_pt()->weight(ipt);
// Call the derivatives of the shape and test functions
double J = dshape_and_dtest_eulerian_at_knot_womersley(
ipt, psi, dpsidx, test, dtestdx);
// Premultiply the weights and the Jacobian
double W = w * J;
// Allocate memory for local quantities and initialise to zero
double interpolated_u = 0.0;
double dudt = 0.0;
Vector<double> interpolated_x(DIM, 0.0);
Vector<double> interpolated_dudx(DIM, 0.0);
// Calculate function value and derivatives:
// Loop over nodes
for (unsigned l = 0; l < n_node; l++)
{
// Calculate the value at the nodes
double u_value = raw_nodal_value(l, u_nodal_index);
interpolated_u += u_value * psi(l);
dudt += du_dt_womersley(l) * psi(l);
// Loop over directions
for (unsigned j = 0; j < DIM; j++)
{
interpolated_x[j] += raw_nodal_position(l, j) * psi(l);
interpolated_dudx[j] += u_value * dpsidx(l, j);
}
}
// Get pressure gradient
//---------------------
double dpdz;
// If no pressure gradient has been set, use zero
if (Pressure_gradient_data_pt == 0)
{
dpdz = 0.0;
}
else
{
// Get gressure gradient
dpdz = Pressure_gradient_data_pt->value(0);
}
// Assemble residuals and Jacobian
//--------------------------------
// Loop over the test functions
for (unsigned l = 0; l < n_node; l++)
{
local_eqn = nodal_local_eqn(l, u_nodal_index);
/*IF it's not a boundary condition*/
if (local_eqn >= 0)
{
// Add dpdz term and time derivative
residuals[local_eqn] += (re_st() * dudt + dpdz) * test(l) * W;
// Laplace operator
for (unsigned k = 0; k < DIM; k++)
{
residuals[local_eqn] += interpolated_dudx[k] * dtestdx(l, k) * W;
}
// Calculate the jacobian
//-----------------------
if (flag)
{
// Loop over the velocity shape functions again
for (unsigned l2 = 0; l2 < n_node; l2++)
{
local_unknown = nodal_local_eqn(l2, u_nodal_index);
// If at a non-zero degree of freedom add in the entry
if (local_unknown >= 0)
{
// Mass matrix
jacobian(local_eqn, local_unknown) +=
re_st() * test(l) * psi(l2) *
node_pt(l2)->time_stepper_pt()->weight(1, 0) * W;
// Laplace operator & mesh velocity bit
for (unsigned i = 0; i < DIM; i++)
{
double tmp = dtestdx(l, i);
jacobian(local_eqn, local_unknown) += dpsidx(l2, i) * tmp * W;
}
}
}
// Derivative w.r.t. pressure gradient data (if it's
// an unknown)
if ((Pressure_gradient_data_pt != 0) &&
(!Pressure_gradient_data_pt->is_pinned(0)))
{
local_unknown = external_local_eqn(0, 0);
if (local_unknown >= 0)
{
jacobian(local_eqn, local_unknown) += test(l) * W;
}
// Derivatives of the final eqn (volume flux constraint
// w.r.t. to this unknown)
unsigned final_local_eqn = external_local_eqn(0, 0);
unsigned local_unknown = local_eqn; // [from above just renaming
// // for clarity(!?)]
jacobian(final_local_eqn, local_unknown) += psi(l) * W;
}
}
}
}
} // End of loop over integration points
}
//======================================================================
/// Compute volume flux through element
//======================================================================
template<unsigned DIM>
double WomersleyEquations<DIM>::get_volume_flux()
{
// Find out how many nodes there are
unsigned n_node = nnode();
// Find the index at which the variable is stored
unsigned u_nodal_index = u_index_womersley();
// Set up memory for the shape fcs
Shape psi(n_node);
DShape dpsidx(n_node, DIM);
// Set the value of n_intpt
unsigned n_intpt = integral_pt()->nweight();
// Set the Vector to hold local coordinates
Vector<double> s(DIM);
// Initialise flux
double flux = 0.0;
// Loop over the integration points
for (unsigned ipt = 0; ipt < n_intpt; ipt++)
{
// Assign values of s
for (unsigned i = 0; i < DIM; i++) s[i] = integral_pt()->knot(ipt, i);
// Get the integral weight
double w = integral_pt()->weight(ipt);
// Call the derivatives of the shape and test functions
double J = dshape_eulerian_at_knot(ipt, psi, dpsidx);
// Premultiply the weights and the Jacobian
double W = w * J;
// Allocate memory for local quantities and initialise to zero
double interpolated_u = 0.0;
// Calculate function value
// Loop over nodes
for (unsigned l = 0; l < n_node; l++)
{
// Calculate the value at the nodes (takes hanging node status
// into account
interpolated_u += nodal_value(l, u_nodal_index) * psi(l);
}
// Add to flux
flux += interpolated_u * W;
} // End of loop over integration points
return flux;
}
//======================================================================
/// Self-test: Return 0 for OK
//======================================================================
template<unsigned DIM>
unsigned WomersleyEquations<DIM>::self_test()
{
bool passed = true;
// Check lower-level stuff
if (FiniteElement::self_test() != 0)
{
passed = false;
}
// Return verdict
if (passed)
{
return 0;
}
else
{
return 1;
}
}
//======================================================================
/// Output function: x,y,z_out,0,0,u,0 to allow comparison
/// against full Navier Stokes at n_nplot x n_plot points (2D)
//======================================================================
template<unsigned DIM>
void WomersleyEquations<DIM>::output_3d(std::ostream& outfile,
const unsigned& nplot,
const double& z_out)
{
// Vector of local coordinates
Vector<double> s(DIM);
// Tecplot header info
outfile << tecplot_zone_string(nplot);
// Loop over plot points
unsigned num_plot_points = nplot_points(nplot);
for (unsigned iplot = 0; iplot < num_plot_points; iplot++)
{
// Get local coordinates of plot point
get_s_plot(iplot, nplot, s);
for (unsigned i = 0; i < DIM; i++)
{
outfile << interpolated_x(s, i) << " ";
}
outfile << z_out << " 0.0 0.0 ";
outfile << interpolated_u_womersley(s);
outfile << " 0.0 " << std::endl;
}
// Write tecplot footer (e.g. FE connectivity lists)
write_tecplot_zone_footer(outfile, nplot);
}
//======================================================================
/// Output function:
///
/// x,y,u or x,y,z,u
///
/// nplot points in each coordinate direction
//======================================================================
template<unsigned DIM>
void WomersleyEquations<DIM>::output(std::ostream& outfile,
const unsigned& nplot)
{
// Vector of local coordinates
Vector<double> s(DIM);
// Tecplot header info
outfile << tecplot_zone_string(nplot);
// Loop over plot points
unsigned num_plot_points = nplot_points(nplot);
for (unsigned iplot = 0; iplot < num_plot_points; iplot++)
{
// Get local coordinates of plot point
get_s_plot(iplot, nplot, s);
for (unsigned i = 0; i < DIM; i++)
{
outfile << interpolated_x(s, i) << " ";
}
outfile << interpolated_u_womersley(s) << std::endl;
}
// Write tecplot footer (e.g. FE connectivity lists)
write_tecplot_zone_footer(outfile, nplot);
}
//======================================================================
/// C-style output function:
///
/// x,y,u or x,y,z,u
///
/// nplot points in each coordinate direction
//======================================================================
template<unsigned DIM>
void WomersleyEquations<DIM>::output(FILE* file_pt, const unsigned& nplot)
{
// Vector of local coordinates
Vector<double> s(DIM);
// Tecplot header info
fprintf(file_pt, "%s", tecplot_zone_string(nplot).c_str());
// Loop over plot points
unsigned num_plot_points = nplot_points(nplot);
for (unsigned iplot = 0; iplot < num_plot_points; iplot++)
{
// Get local coordinates of plot point
get_s_plot(iplot, nplot, s);
for (unsigned i = 0; i < DIM; i++)
{
fprintf(file_pt, "%g ", interpolated_x(s, i));
}
fprintf(file_pt, "%g \n", interpolated_u_womersley(s));
}
// Write tecplot footer (e.g. FE connectivity lists)
write_tecplot_zone_footer(file_pt, nplot);
}
//======================================================================
/// Output exact solution
///
/// Solution is provided via function pointer.
/// Plot at a given number of plot points.
///
/// x,y,u_exact or x,y,z,u_exact
//======================================================================
template<unsigned DIM>
void WomersleyEquations<DIM>::output_fct(
std::ostream& outfile,
const unsigned& nplot,
FiniteElement::SteadyExactSolutionFctPt exact_soln_pt)
{
// Vector of local coordinates
Vector<double> s(DIM);
// Vector for coordintes
Vector<double> x(DIM);
// Tecplot header info
outfile << tecplot_zone_string(nplot);
// Exact solution Vector (here a scalar)
Vector<double> exact_soln(1);
// Loop over plot points
unsigned num_plot_points = nplot_points(nplot);
for (unsigned iplot = 0; iplot < num_plot_points; iplot++)
{
// Get local coordinates of plot point
get_s_plot(iplot, nplot, s);
// Get x position as Vector
interpolated_x(s, x);
// Get exact solution at this point
(*exact_soln_pt)(x, exact_soln);
// Output x,y,...,u_exact
for (unsigned i = 0; i < DIM; i++)
{
outfile << x[i] << " ";
}
outfile << exact_soln[0] << std::endl;
}
// Write tecplot footer (e.g. FE connectivity lists)
write_tecplot_zone_footer(outfile, nplot);
}
//======================================================================
/// Output exact solution at time t
///
/// Solution is provided via function pointer.
/// Plot at a given number of plot points.
///
/// x,y,u_exact or x,y,z,u_exact
//======================================================================
template<unsigned DIM>
void WomersleyEquations<DIM>::output_fct(
std::ostream& outfile,
const unsigned& nplot,
const double& time,
FiniteElement::UnsteadyExactSolutionFctPt exact_soln_pt)
{
// Vector of local coordinates
Vector<double> s(DIM);
// Vector for coordintes
Vector<double> x(DIM);
// Tecplot header info
outfile << tecplot_zone_string(nplot);
// Exact solution Vector (here a scalar)
Vector<double> exact_soln(1);
// Loop over plot points
unsigned num_plot_points = nplot_points(nplot);
for (unsigned iplot = 0; iplot < num_plot_points; iplot++)
{
// Get local coordinates of plot point
get_s_plot(iplot, nplot, s);
// Get x position as Vector
interpolated_x(s, x);
// Get exact solution at this point
(*exact_soln_pt)(time, x, exact_soln);
// Output x,y,...,u_exact
for (unsigned i = 0; i < DIM; i++)
{
outfile << x[i] << " ";
}
outfile << exact_soln[0] << std::endl;
}
// Write tecplot footer (e.g. FE connectivity lists)
write_tecplot_zone_footer(outfile, nplot);
}
//======================================================================
/// Validate against exact solution
///
/// Solution is provided via function pointer.
/// Plot error at a given number of plot points.
///
//======================================================================
template<unsigned DIM>
void WomersleyEquations<DIM>::compute_error(
std::ostream& outfile,
FiniteElement::SteadyExactSolutionFctPt exact_soln_pt,
double& error,
double& norm)
{
// Initialise
error = 0.0;
norm = 0.0;
// Vector of local coordinates
Vector<double> s(DIM);
// Vector for coordintes
Vector<double> x(DIM);
// Find out how many nodes there are in the element
unsigned n_node = nnode();
Shape psi(n_node);
// Set the value of n_intpt
unsigned n_intpt = integral_pt()->nweight();
// Tecplot header info
outfile << "ZONE" << std::endl;
// Exact solution Vector (here a scalar)
Vector<double> exact_soln(1);
// Loop over the integration points
for (unsigned ipt = 0; ipt < n_intpt; ipt++)
{
// Assign values of s
for (unsigned i = 0; i < DIM; i++)
{
s[i] = integral_pt()->knot(ipt, i);
}
// Get the integral weight
double w = integral_pt()->weight(ipt);
// Get jacobian of mapping
double J = J_eulerian(s);
// Premultiply the weights and the Jacobian
double W = w * J;
// Get x position as Vector
interpolated_x(s, x);
// Get FE function value
double u_fe = interpolated_u_womersley(s);
// Get exact solution at this point
(*exact_soln_pt)(x, exact_soln);
// Output x,y,...,error
for (unsigned i = 0; i < DIM; i++)
{
outfile << x[i] << " ";
}
outfile << exact_soln[0] << " " << exact_soln[0] - u_fe << std::endl;
// Add to error and norm
norm += exact_soln[0] * exact_soln[0] * W;
error += (exact_soln[0] - u_fe) * (exact_soln[0] - u_fe) * W;
}
}
//======================================================================
/// Validate against exact solution at time t.
///
/// Solution is provided via function pointer.
/// Plot error at a given number of plot points.
///
//======================================================================
template<unsigned DIM>
void WomersleyEquations<DIM>::compute_error(
std::ostream& outfile,
FiniteElement::UnsteadyExactSolutionFctPt exact_soln_pt,
const double& time,
double& error,
double& norm)
{
// Initialise
error = 0.0;
norm = 0.0;
// Vector of local coordinates
Vector<double> s(DIM);
// Vector for coordintes
Vector<double> x(DIM);
// Find out how many nodes there are in the element
unsigned n_node = nnode();
Shape psi(n_node);
// Set the value of n_intpt
unsigned n_intpt = integral_pt()->nweight();
// Tecplot
outfile << "ZONE" << std::endl;
// Exact solution Vector (here a scalar)
Vector<double> exact_soln(1);
// Loop over the integration points
for (unsigned ipt = 0; ipt < n_intpt; ipt++)
{
// Assign values of s
for (unsigned i = 0; i < DIM; i++)
{
s[i] = integral_pt()->knot(ipt, i);
}
// Get the integral weight
double w = integral_pt()->weight(ipt);
// Get jacobian of mapping
double J = J_eulerian(s);
// Premultiply the weights and the Jacobian
double W = w * J;
// Get x position as Vector
interpolated_x(s, x);
// Get FE function value
double u_fe = interpolated_u_womersley(s);
// Get exact solution at this point
(*exact_soln_pt)(time, x, exact_soln);
// Output x,y,...,error
for (unsigned i = 0; i < DIM; i++)
{
outfile << x[i] << " ";
}
outfile << exact_soln[0] << " " << exact_soln[0] - u_fe << std::endl;
// Add to error and norm
norm += exact_soln[0] * exact_soln[0] * W;
error += (exact_soln[0] - u_fe) * (exact_soln[0] - u_fe) * W;
}
}
//====================================================================
// Force build of templates
//====================================================================
template class WomersleyEquations<1>;
template class QWomersleyElement<1, 2>;
template class QWomersleyElement<1, 3>;
template class QWomersleyElement<1, 4>;
template class WomersleyEquations<2>;
template class QWomersleyElement<2, 2>;
template class QWomersleyElement<2, 3>;
template class QWomersleyElement<2, 4>;
// template class QWomersleyElement<3,2>;
// template class QWomersleyElement<3,3>;
// template class QWomersleyElement<3,4>;
} // namespace oomph
| 29.881089 | 80 | 0.534017 | [
"mesh",
"object",
"shape",
"vector"
] |
2160333b7ccc523e1aadf02fa5500dc0bfd90b83 | 2,219 | cpp | C++ | 01-algorithmic-toolbox/week4/3_improving_quicksort/sorting.cpp | olpotkin/ds_and_algos_modern_cpp | 12876686a8fb26bc9358930378d235d4470bb6fc | [
"MIT"
] | null | null | null | 01-algorithmic-toolbox/week4/3_improving_quicksort/sorting.cpp | olpotkin/ds_and_algos_modern_cpp | 12876686a8fb26bc9358930378d235d4470bb6fc | [
"MIT"
] | null | null | null | 01-algorithmic-toolbox/week4/3_improving_quicksort/sorting.cpp | olpotkin/ds_and_algos_modern_cpp | 12876686a8fb26bc9358930378d235d4470bb6fc | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <cstdlib>
#include <cassert>
/// Intro: The goal in this problem is to redesign a given implementation of the randomized quick sort
/// algorithm so that it works fast even on sequences containing many equal elements.
///
/// Task: To force the given implementation of the quick sort algorithm to efficiently process sequences with
/// few unique elements, your goal is replace a 2-way partition with a 3-way partition. That is, your new
/// partition procedure should partition the array into three parts: < x part, = x part, and > x part.
///
/// Input Format: The first line of the input contains an integer n. The next line contains a sequence of n
/// integers a_0, a_1, ... , a_n−1.
///
/// Output Format: Output this sequence sorted in non-decreasing order.
std::pair<int, int> partition3(std::vector<int> &a, int l, int r) {
int pivot = a[l];
int gt = r;
int lt = l;
for (int i = l; i <= gt; ++i) {
// case 1: a[i] == pivot -> ++i
// case 2: a[i] < pivot
if (a[i] < pivot) {
std::swap(a[i], a[lt]);
++lt;
}
else if (a[i] > pivot) {
// case 3: a[i] > pivot
std::swap(a[i], a[gt]);
--i;
--gt;
}
}
return std::make_pair(lt, gt);
}
int partition2(std::vector<int> &a, int l, int r) {
int x = a[l];
int j = l;
for (int i = l + 1; i <= r; i++) {
if (a[i] <= x) {
j++;
std::swap(a[i], a[j]);
}
}
std::swap(a[l], a[j]);
return j;
}
void randomized_quick_sort(std::vector<int> &a, int l, int r) {
if (l >= r)
return;
int k = l + rand() % (r - l + 1);
std::swap(a[l], a[k]);
// int m = partition2(a, l, r);
// randomized_quick_sort(a, l, m - 1);
// randomized_quick_sort(a, m + 1, r);
auto m = partition3(a, l, r);
randomized_quick_sort(a, l, m.first - 1);
randomized_quick_sort(a, m.second + 1, r);
}
int main() {
int n;
std::cin >> n;
std::vector<int> a(n);
for (size_t i = 0; i < a.size(); ++i) {
std::cin >> a[i];
}
randomized_quick_sort(a, 0, a.size() - 1);
for (size_t i = 0; i < a.size(); ++i) {
std::cout << a[i] << ' ';
}
std::cout << std::endl;
return 0;
}
| 22.876289 | 111 | 0.559712 | [
"vector"
] |
21653cc1ac4c4d1273e8d92c6f7ee13b533d2c5e | 8,568 | cpp | C++ | billing/src/v20180709/model/CosDetailSets.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | billing/src/v20180709/model/CosDetailSets.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | billing/src/v20180709/model/CosDetailSets.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/billing/v20180709/model/CosDetailSets.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Billing::V20180709::Model;
using namespace std;
CosDetailSets::CosDetailSets() :
m_bucketNameHasBeenSet(false),
m_dosageBeginTimeHasBeenSet(false),
m_dosageEndTimeHasBeenSet(false),
m_subProductCodeNameHasBeenSet(false),
m_billingItemCodeNameHasBeenSet(false),
m_dosageValueHasBeenSet(false),
m_unitHasBeenSet(false)
{
}
CoreInternalOutcome CosDetailSets::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("BucketName") && !value["BucketName"].IsNull())
{
if (!value["BucketName"].IsString())
{
return CoreInternalOutcome(Error("response `CosDetailSets.BucketName` IsString=false incorrectly").SetRequestId(requestId));
}
m_bucketName = string(value["BucketName"].GetString());
m_bucketNameHasBeenSet = true;
}
if (value.HasMember("DosageBeginTime") && !value["DosageBeginTime"].IsNull())
{
if (!value["DosageBeginTime"].IsString())
{
return CoreInternalOutcome(Error("response `CosDetailSets.DosageBeginTime` IsString=false incorrectly").SetRequestId(requestId));
}
m_dosageBeginTime = string(value["DosageBeginTime"].GetString());
m_dosageBeginTimeHasBeenSet = true;
}
if (value.HasMember("DosageEndTime") && !value["DosageEndTime"].IsNull())
{
if (!value["DosageEndTime"].IsString())
{
return CoreInternalOutcome(Error("response `CosDetailSets.DosageEndTime` IsString=false incorrectly").SetRequestId(requestId));
}
m_dosageEndTime = string(value["DosageEndTime"].GetString());
m_dosageEndTimeHasBeenSet = true;
}
if (value.HasMember("SubProductCodeName") && !value["SubProductCodeName"].IsNull())
{
if (!value["SubProductCodeName"].IsString())
{
return CoreInternalOutcome(Error("response `CosDetailSets.SubProductCodeName` IsString=false incorrectly").SetRequestId(requestId));
}
m_subProductCodeName = string(value["SubProductCodeName"].GetString());
m_subProductCodeNameHasBeenSet = true;
}
if (value.HasMember("BillingItemCodeName") && !value["BillingItemCodeName"].IsNull())
{
if (!value["BillingItemCodeName"].IsString())
{
return CoreInternalOutcome(Error("response `CosDetailSets.BillingItemCodeName` IsString=false incorrectly").SetRequestId(requestId));
}
m_billingItemCodeName = string(value["BillingItemCodeName"].GetString());
m_billingItemCodeNameHasBeenSet = true;
}
if (value.HasMember("DosageValue") && !value["DosageValue"].IsNull())
{
if (!value["DosageValue"].IsString())
{
return CoreInternalOutcome(Error("response `CosDetailSets.DosageValue` IsString=false incorrectly").SetRequestId(requestId));
}
m_dosageValue = string(value["DosageValue"].GetString());
m_dosageValueHasBeenSet = true;
}
if (value.HasMember("Unit") && !value["Unit"].IsNull())
{
if (!value["Unit"].IsString())
{
return CoreInternalOutcome(Error("response `CosDetailSets.Unit` IsString=false incorrectly").SetRequestId(requestId));
}
m_unit = string(value["Unit"].GetString());
m_unitHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void CosDetailSets::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_bucketNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "BucketName";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_bucketName.c_str(), allocator).Move(), allocator);
}
if (m_dosageBeginTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "DosageBeginTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_dosageBeginTime.c_str(), allocator).Move(), allocator);
}
if (m_dosageEndTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "DosageEndTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_dosageEndTime.c_str(), allocator).Move(), allocator);
}
if (m_subProductCodeNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "SubProductCodeName";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_subProductCodeName.c_str(), allocator).Move(), allocator);
}
if (m_billingItemCodeNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "BillingItemCodeName";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_billingItemCodeName.c_str(), allocator).Move(), allocator);
}
if (m_dosageValueHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "DosageValue";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_dosageValue.c_str(), allocator).Move(), allocator);
}
if (m_unitHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Unit";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_unit.c_str(), allocator).Move(), allocator);
}
}
string CosDetailSets::GetBucketName() const
{
return m_bucketName;
}
void CosDetailSets::SetBucketName(const string& _bucketName)
{
m_bucketName = _bucketName;
m_bucketNameHasBeenSet = true;
}
bool CosDetailSets::BucketNameHasBeenSet() const
{
return m_bucketNameHasBeenSet;
}
string CosDetailSets::GetDosageBeginTime() const
{
return m_dosageBeginTime;
}
void CosDetailSets::SetDosageBeginTime(const string& _dosageBeginTime)
{
m_dosageBeginTime = _dosageBeginTime;
m_dosageBeginTimeHasBeenSet = true;
}
bool CosDetailSets::DosageBeginTimeHasBeenSet() const
{
return m_dosageBeginTimeHasBeenSet;
}
string CosDetailSets::GetDosageEndTime() const
{
return m_dosageEndTime;
}
void CosDetailSets::SetDosageEndTime(const string& _dosageEndTime)
{
m_dosageEndTime = _dosageEndTime;
m_dosageEndTimeHasBeenSet = true;
}
bool CosDetailSets::DosageEndTimeHasBeenSet() const
{
return m_dosageEndTimeHasBeenSet;
}
string CosDetailSets::GetSubProductCodeName() const
{
return m_subProductCodeName;
}
void CosDetailSets::SetSubProductCodeName(const string& _subProductCodeName)
{
m_subProductCodeName = _subProductCodeName;
m_subProductCodeNameHasBeenSet = true;
}
bool CosDetailSets::SubProductCodeNameHasBeenSet() const
{
return m_subProductCodeNameHasBeenSet;
}
string CosDetailSets::GetBillingItemCodeName() const
{
return m_billingItemCodeName;
}
void CosDetailSets::SetBillingItemCodeName(const string& _billingItemCodeName)
{
m_billingItemCodeName = _billingItemCodeName;
m_billingItemCodeNameHasBeenSet = true;
}
bool CosDetailSets::BillingItemCodeNameHasBeenSet() const
{
return m_billingItemCodeNameHasBeenSet;
}
string CosDetailSets::GetDosageValue() const
{
return m_dosageValue;
}
void CosDetailSets::SetDosageValue(const string& _dosageValue)
{
m_dosageValue = _dosageValue;
m_dosageValueHasBeenSet = true;
}
bool CosDetailSets::DosageValueHasBeenSet() const
{
return m_dosageValueHasBeenSet;
}
string CosDetailSets::GetUnit() const
{
return m_unit;
}
void CosDetailSets::SetUnit(const string& _unit)
{
m_unit = _unit;
m_unitHasBeenSet = true;
}
bool CosDetailSets::UnitHasBeenSet() const
{
return m_unitHasBeenSet;
}
| 29.853659 | 145 | 0.703665 | [
"model"
] |
2171a16462f636b5bd9b72080cedd1b0da404366 | 3,426 | cpp | C++ | Algorithms/DynamicProgramming/editDistance.cpp | Praggya17/HacktoberFestContribute | 098cb1012f1f2ed6ca6b3544a7b962b6c49e2643 | [
"MIT"
] | 98 | 2018-10-09T15:42:41.000Z | 2021-10-04T15:25:44.000Z | Algorithms/DynamicProgramming/editDistance.cpp | Praggya17/HacktoberFestContribute | 098cb1012f1f2ed6ca6b3544a7b962b6c49e2643 | [
"MIT"
] | 141 | 2018-10-06T16:55:20.000Z | 2021-10-31T18:25:35.000Z | Algorithms/DynamicProgramming/editDistance.cpp | Praggya17/HacktoberFestContribute | 098cb1012f1f2ed6ca6b3544a7b962b6c49e2643 | [
"MIT"
] | 885 | 2018-10-06T17:14:44.000Z | 2022-01-29T03:16:21.000Z | #include <iostream>
#include <vector>
#include<math.h>
#include<unordered_map>
using namespace std;
//EFFICIENT BUT WRONG.
//WE HAVE TO TAKE CARE OF THE SEQUENCE OF THE ELEMENTS IN THE STRING TOO.
//LIKE: ABC AND DCB WILL NOT HAVE 1 STEP BUT MINIMUM 3 STEPS TO BECOME EQUAL.
/*
int editDistance(string s1, string s2){
unordered_map<char,int>m;
for(int i=0;i<s1.size();i++)
{
m[s1[i]]++;
}
int count1=0;
int count2=0;
for(int i=0;i<s2.size();i++)
{
if(m.find(s2[i])!=m.end())
{
if(m[s2[i]]>0)
m[s2[i]]--;
else
count2++;
}
else
count2++;
}
unordered_map<char,int>::iterator it;
for(it=m.begin();it!=m.end();it++)
{
if(it->second!=0)
count1=count1+it->second;
}
int res= min(count1,count2) + abs(count1-count2);
cout<<count1<<" "<<count2<<" "<<res<<endl;
return res;
}
*/
int editDistance(string s1, string s2){
if(s1.size()==0||s2.size()==0)
{
if(s1.size()>s2.size())
return s1.size()-s2.size();
return s2.size()-s1.size();
}
if(s1[0]==s2[0])
return editDistance(s1.substr(1),s2.substr(1));
//INSERT S1[0] IN S2[0]
int x=editDistance(s1.substr(1),s2);
//DELETE S2[0] FROM S2
int y=editDistance(s1,s2.substr(1));
//REPLACE S2[0] FROM S1[0]
int z=editDistance(s1.substr(1),s2.substr(1));
return 1+min(x,min(y,z));
}
int editDistancememoisation(string s1, string s2, int**dp)
{
if(s1.size()==0||s2.size()==0)
{
if(s1.size()>s2.size())
{
dp[s1.size()][s2.size()]=s1.size()-s2.size();
return s1.size()-s2.size();
}
dp[s1.size()][s2.size()]=s2.size()-s1.size();
return s2.size()-s1.size();
}
int i=s1.size();
int j=s2.size();
if(dp[i][j]!=-1)
return dp[i][j];
if(s1[0]==s2[0])
{
dp[i][j]=editDistancememoisation(s1.substr(1),s2.substr(1),dp);
return dp[i][j];
}
int x=editDistancememoisation(s1.substr(1),s2,dp);
int y=editDistancememoisation(s1,s2.substr(1),dp);
int z=editDistancememoisation(s1.substr(1),s2.substr(1),dp);
dp[i][j]=1+min(x,min(y,z));
return dp[i][j];
}
int editDistanceMEMOISATION(string s1, string s2)
{
int**dp=new int*[s1.size()+1];
for(int i=0;i<s1.size()+1;i++)
{
dp[i]=new int[s2.size()+1];
for(int j=0;j<s2.size()+1;j++)
dp[i][j]=-1;
}
int x=editDistancememoisation(s1,s2,dp);
for(int i=0;i<s1.size()+1;i++)
{
for(int j=0;j<s2.size()+1;j++)
{
if(dp[i][j]==-1)
cout<<"X ";
else
cout<<dp[i][j]<<" ";
}
cout<<endl;
}
return x;
}
int editDistanceDP(string s1, string s2)
{
int m=s1.size()+1;
int n=s2.size()+1;
int**dp=new int*[m];
for(int i=0;i<m;i++)
dp[i]=new int[n];
for(int i=0;i<m;i++)
dp[i][0]=i;
for(int j=0;j<n;j++)
dp[0][j]=j;
for(int i=1;i<m;i++)
{
for(int j=1;j<n;j++)
{
if(s1[m-1-i]==s2[n-1-j])//OR WE CAN DO if(s1[i-1]==s2[j-1])
{
cout<<s1[i]<<" "<<s2[j]<<endl;
dp[i][j]=dp[i-1][j-1];
}
else
dp[i][j] = 1 + min(dp[i-1][j-1], min(dp[i][j-1], dp[i-1][j]));
}
}
for(int i=0;i<s1.size()+1;i++)
{
for(int j=0;j<s2.size()+1;j++)
{
cout<<dp[i][j]<<" ";
}
cout<<endl;
}
return dp[m-1][n-1];
}
int main()
{
string s1,s2;
cin>>s1>>s2;
cout<<editDistance(s1,s2)<<endl;
cout<<editDistanceMEMOISATION(s1,s2)<<endl;
cout<<editDistanceDP(s1,s2)<<endl;
}
| 18.928177 | 78 | 0.536486 | [
"vector"
] |
217a90185552b3b480bcf36a299e6c5aa7fc7fae | 2,119 | cc | C++ | src/hello_world/server/main.cc | Bjoe/genode-playground | 0be3cbf5b210a17233e79d4417bcf9a4d0dbf04c | [
"MIT"
] | null | null | null | src/hello_world/server/main.cc | Bjoe/genode-playground | 0be3cbf5b210a17233e79d4417bcf9a4d0dbf04c | [
"MIT"
] | null | null | null | src/hello_world/server/main.cc | Bjoe/genode-playground | 0be3cbf5b210a17233e79d4417bcf9a4d0dbf04c | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2017 Joerg-Christian Boehme
*
* This file is part of the Genode OS framework, which is distributed
* under the terms of the GNU Affero General Public License version 3.
*/
#include <base/component.h>
#include <base/log.h>
#include <base/heap.h>
#include <root/component.h>
#include <hello_world_session/hello_session.h>
#include <base/rpc_server.h>
namespace helloworld {
struct Session_component;
class Root_component;
struct Main;
}
struct helloworld::Session_component : Genode::Rpc_object<Session>
{
void say_hello() {
Genode::log("I am here... Hello."); }
int add(int a, int b) {
return a + b; }
};
class helloworld::Root_component
:
public Genode::Root_component<Session_component>
{
protected:
Session_component *_create_session(const char *args)
{
Genode::log("creating hello session");
return new (md_alloc()) Session_component();
}
public:
Root_component(Genode::Entrypoint &ep,
Genode::Allocator &alloc)
:
Genode::Root_component<Session_component>(ep, alloc)
{
Genode::log("creating root component");
}
};
struct helloworld::Main
{
Genode::Env &env;
/*
* A sliced heap is used for allocating session objects - thereby we
* can release objects separately.
*/
Genode::Sliced_heap sliced_heap { env.ram(), env.rm() };
helloworld::Root_component root { env.ep(), sliced_heap };
Main(Genode::Env &env) : env(env)
{
/*
* Create a RPC object capability for the root interface and
* announce the service to our parent.
*/
env.parent().announce(env.ep().manage(root));
}
};
void Component::construct(Genode::Env &env)
{
Genode::Ram_session& ramSession = env.ram();
Genode::Ram_quota available = ramSession.avail_ram();
Genode::log("Available RAM: ", available);
Genode::Ram_quota quota = ramSession.ram_quota();
Genode::log("Quota RAM: ", quota);
Genode::Ram_quota used = ramSession.used_ram();
Genode::log("Used RAM: ", used);
const char* ramName = ramSession.service_name();
Genode::log("RAM service name: ", ramName);
static helloworld::Main main(env);
}
| 22.072917 | 70 | 0.689476 | [
"object"
] |
217f174f1e787cae0b34bd58c48b4e34d5aaeedf | 3,818 | hpp | C++ | include/STELA/symbols.hpp | Kerndog73/STELA | 11449b4bb440494f3ec4b1172b2688b5ec1bcd0a | [
"MIT"
] | 10 | 2018-06-20T05:12:59.000Z | 2021-11-23T02:56:04.000Z | include/STELA/symbols.hpp | Kerndog73/STELA | 11449b4bb440494f3ec4b1172b2688b5ec1bcd0a | [
"MIT"
] | null | null | null | include/STELA/symbols.hpp | Kerndog73/STELA | 11449b4bb440494f3ec4b1172b2688b5ec1bcd0a | [
"MIT"
] | null | null | null | //
// symbols.hpp
// STELA
//
// Created by Indi Kernick on 9/7/18.
// Copyright © 2018 Indi Kernick. All rights reserved.
//
#ifndef stela_symbols_hpp
#define stela_symbols_hpp
#include <string>
#include <memory>
#include "ast.hpp"
#include <unordered_map>
namespace stela::sym {
struct Scope;
struct Symbol {
virtual ~Symbol();
Scope *scope = nullptr;
Loc loc;
bool referenced = false;
};
using SymbolPtr = std::unique_ptr<Symbol>;
// @TODO std::string_view?
using Name = std::string;
using Table = std::unordered_multimap<Name, SymbolPtr>;
enum class ScopeType {
// global namespace scope
ns,
block,
func,
// break and continue are valid within flow scopes (while, for, switch)
flow,
closure
};
struct Scope {
Scope(Scope *const parent, const ast::Name module)
: parent{parent}, type{ScopeType::ns}, symbol{}, module{module} {}
Scope(Scope *const parent, const ScopeType type)
: parent{parent}, type{type}, symbol{}, module{} {
assert(type != ScopeType::func && type != ScopeType::closure);
}
Scope(Scope *const parent, const ScopeType type, sym::Symbol *const symbol)
: parent{parent}, type{type}, symbol{symbol}, module{} {
assert(type == ScopeType::func || type == ScopeType::closure);
}
Scope *const parent;
const ScopeType type;
sym::Symbol *const symbol;
const ast::Name module;
Table table;
};
using ScopePtr = std::unique_ptr<Scope>;
using Scopes = std::vector<ScopePtr>;
enum class ValueMut : uint8_t {
let,
var
};
enum class ValueRef : uint8_t {
val,
ref
};
struct ExprType {
ast::TypePtr type;
ValueMut mut;
ValueRef ref;
};
inline ValueMut common(const ValueMut a, const ValueMut b) {
return a == ValueMut::let ? a : b;
}
inline ValueRef common(const ValueRef a, const ValueRef b) {
return a == ValueRef::val ? a : b;
}
inline ExprType fieldType(const ExprType &obj, const ast::TypePtr &mem) {
return {mem, obj.mut, obj.ref};
}
inline ExprType makeLetVal(ast::TypePtr type) {
return {std::move(type), ValueMut::let, ValueRef::val};
}
inline ExprType makeVarVal(ast::TypePtr type) {
return {std::move(type), ValueMut::var, ValueRef::val};
}
inline bool callMut(const ValueMut param, const ValueMut arg) {
return static_cast<uint8_t>(param) <= static_cast<uint8_t>(arg);
}
inline bool callMutRef(const ExprType ¶m, const ExprType &arg) {
return param.ref == sym::ValueRef::val || callMut(param.mut, arg.mut);
}
const ExprType null_type {};
struct TypeAlias final : Symbol {
~TypeAlias();
retain_ptr<ast::TypeAlias> node;
};
struct Object final : Symbol {
~Object();
ExprType etype;
retain_ptr<ast::Statement> node;
};
// the first parameter is the receiver
// if params.front().type == nullptr then there is no receiver
using FuncParams = std::vector<ExprType>;
struct Func final : Symbol {
~Func();
ExprType ret;
FuncParams params;
// ast::Func or ast::ExtFunc
retain_ptr<ast::Declaration> node;
};
using FuncPtr = std::unique_ptr<Func>;
struct ClosureCap {
ast::TypePtr type;
ast::Statement *object = nullptr;
uint32_t index = ~uint32_t{};
};
struct Lambda final : Symbol {
~Lambda();
ExprType ret;
FuncParams params;
retain_ptr<ast::Lambda> node;
std::vector<ClosureCap> captures;
};
struct BtnFunc final : Symbol {
~BtnFunc();
retain_ptr<ast::BtnFunc> node;
};
struct Builtins {
// Builtin types
ast::BtnTypePtr Void;
ast::BtnTypePtr Opaq;
ast::BtnTypePtr Bool;
ast::BtnTypePtr Byte;
ast::BtnTypePtr Char;
ast::BtnTypePtr Real;
ast::BtnTypePtr Sint;
ast::BtnTypePtr Uint;
// Alias of [char] used as the type of string literals
ast::TypePtr string;
};
}
namespace stela {
struct Symbols {
ast::Decls decls;
sym::Scopes scopes;
sym::Builtins builtins;
sym::Scope *global;
};
}
#endif
| 20.526882 | 77 | 0.684914 | [
"object",
"vector"
] |
217f1784704dfc96f10ef1de8685a47fc247e876 | 3,501 | cpp | C++ | cspark/cspark.cpp | viridia/spark | d1c0f4cc1e72f73b360b119e8b694b58935b0209 | [
"Apache-2.0"
] | 1 | 2015-02-23T18:47:08.000Z | 2015-02-23T18:47:08.000Z | cspark/cspark.cpp | viridia/spark | d1c0f4cc1e72f73b360b119e8b694b58935b0209 | [
"Apache-2.0"
] | null | null | null | cspark/cspark.cpp | viridia/spark | d1c0f4cc1e72f73b360b119e8b694b58935b0209 | [
"Apache-2.0"
] | null | null | null | // ============================================================================
// cspark.cpp: Main entry point.
// ============================================================================
#include "spark/collections/stringref.h"
#include "spark/compiler/compiler.h"
#include <iostream>
#include <vector>
//#include "mcheck.h"
using spark::collections::StringRef;
using spark::compiler::Compiler;
void usage() {
std::cerr << "cspark [options...] sources...\n";
std::cerr << " --version Print version number and exit.\n";
std::cerr << " --out, -o DIR Specify root output directory.\n";
std::cerr << " --modulepath, -m PATH Add path to module search path.\n";
std::cerr << " --sourceroot, -s PATH Root directory for input sources.\n";
exit(-1);
}
class App {
public:
App(int argc, char **argv)
: _argCount(argc)
, _args(argv)
, _compiler(_reporter)
{}
void parseArgs() {
for (int i = 1; i < _argCount; ++i) {
StringRef arg(_args[i]);
if (arg.empty()) {
std::cerr << "Invalid argument: ''\n";
} else if (arg.startsWith("--")) {
StringRef opt = arg.substr(2);
if (opt == "version") {
std::cerr << "cspark version 0.1.\n";
exit(0);
} else if (opt == "out") {
setOutputDir(nextArg(i));
} else if (opt == "modulepath") {
_compiler.addModulePath(nextArg(i));
} else if (opt == "sourceroot") {
setSourceRoot(nextArg(i));
} else {
std::cerr << "Unknown option: " << arg << "\n";
usage();
}
} else if (arg.startsWith("-")) {
StringRef opt = arg.substr(1);
if (opt == "v") {
std::cerr << "cspark version 0.1.\n";
exit(0);
} else if (opt == "m") {
_compiler.addModulePath(nextArg(i));
} else if (opt == "s") {
setSourceRoot(nextArg(i));
} else if (opt == "o") {
setOutputDir(nextArg(i));
} else {
std::cerr << "Unknown option: " << arg << "\n";
usage();
}
} else {
_compiler.addSource(arg);
}
}
}
int run() {
if (_compiler.sources().empty()) {
std::cerr << "No input sources specified.\n";
usage();
}
_compiler.compile();
if (_reporter.errorCount() > 0) {
std::cerr << _reporter.errorCount() << " total errors.\n";
return 2;
}
return 0;
}
private:
void setOutputDir(StringRef dir) {
if (dir.empty()) {
std::cerr << "Invalid output directory ''.\n";
usage();
}
if (!_compiler.outputDir().empty()) {
std::cerr << "Output directory already specified.\n";
usage();
}
_compiler.setOutputDir(dir);
}
void setSourceRoot(StringRef dir) {
if (dir.empty()) {
std::cerr << "Invalid output directory ''.\n";
usage();
}
if (!_compiler.sourceRoot().empty()) {
std::cerr << "Source root directory already specified.\n";
usage();
}
_compiler.setSourceRoot(dir);
}
StringRef nextArg(int& i) {
++i;
if (i < _argCount) {
return _args[i];
} else {
std::cerr << "Option value expected\n";
usage();
return StringRef();
}
}
int _argCount;
char** _args;
spark::error::ConsoleReporter _reporter;
spark::compiler::Compiler _compiler;
};
int main(int argc, char **argv) {
// ::mtrace();
App app(argc, argv);
app.parseArgs();
return app.run();
}
| 25.933333 | 79 | 0.507569 | [
"vector"
] |
217f9df16e8677438e97222989f5b4d42d3f57ba | 23,424 | cpp | C++ | RobotArm/lib/RobotArm/src/RobotArm.cpp | CreateBaseNZ/cb_projects | 0b024cdee6bbc90395814b61cdacc415b90fb931 | [
"MIT"
] | null | null | null | RobotArm/lib/RobotArm/src/RobotArm.cpp | CreateBaseNZ/cb_projects | 0b024cdee6bbc90395814b61cdacc415b90fb931 | [
"MIT"
] | null | null | null | RobotArm/lib/RobotArm/src/RobotArm.cpp | CreateBaseNZ/cb_projects | 0b024cdee6bbc90395814b61cdacc415b90fb931 | [
"MIT"
] | null | null | null | #include "RobotArm.h"
RobotArm::RobotArm()
{
}
RobotArm::RobotArm(float linkLengths[])
{
if (sizeof(*linkLengths) != noOfJoints + 1)
{
//Serial.println("Bad initialisation of Robot Arm");
}
for (int i = 0; i < noOfJoints + 1; i++)
{
this->linkLengths[i] = linkLengths[i];
}
}
void RobotArm::AttachMotors(int pins[])
{
for (int i = 0; i < noOfJoints; i++)
{
servoMotors[i].attach(pins[i]);
}
}
void RobotArm::DetachMotors()
{
for (int i = 0; i < noOfJoints; i++)
{
servoMotors[i].detach();
}
}
void RobotArm::ConfigureBasketBall(int pins[],int number,int limit[]){
for(int i=0;i<number;i++){
pinMode(pins[i],INPUT);
limits[i]=limit[i];
phototransisorPins[i]=pins[i];
}
noOfTransitors=number;
}
void RobotArm::ConfigurePins(int pins[])
{
for (int i = 0; i < noOfJoints; i++){
servoMotors[i].attach(pins[i]);
servoMotors[i].write(90);
}
}
void RobotArm::ConfigureUltraSonic(int pins[],int sonars){
for(int i=0;i<sonars;i++){
sonarTrigPin[i]=pins[i];
pinMode(sonarTrigPin[i],OUTPUT);
pinMode(sonarTrigPin[i]+1,INPUT);
}
sonarUsed=sonars;
}
float RobotArm::findDistance(int sonarNo){
if( sonarNo>=0 && sonarNo<sonarUsed){
int sonarPin=sonarTrigPin[sonarNo];
digitalWrite(sonarPin, HIGH);
delayMicroseconds(2);
digitalWrite(sonarPin, HIGH);
delayMicroseconds(10);
digitalWrite(sonarPin, LOW);
long duration = pulseIn(sonarPin+1, HIGH,100000);
if (duration==0){
return -2;
}
return 330*duration/2/10000;
}
return -1;
}
float RobotArm::torad(float angle){
return angle*M_PI/180;
}
float RobotArm::todeg(float angle){
return angle*180/M_PI;
}
void RobotArm::HandControl(){
float lowest=10,distance,velocities[3]={0,0,0};int lowsetindex=-1;
for(int i=0;i<sonarUsed;i++){
distance=findDistance(i);
if(distance<lowest&&distance>=0){
lowsetindex=i;
lowest=distance;
}
}
if(lowsetindex!=-1){
velocities[lowsetindex]=0.0025;
float v_y_dash=0;//(velocities[1]+velocities[2]) *cos(torad(60))-velocities[0];//
float v_x=(velocities[1]-velocities[2]);//*cos(torad(30));
float theta=0;
for(int i=1;i<noOfJoints;i++){
if(i==1){
theta+=torad(servoMotors[i].read());
}else{
theta+=torad(servoMotors[i].read()-90);
}
}
float v_z=v_y_dash*cos(theta);
float v_y=v_y_dash*sin(theta);
Move(v_x,v_y,v_z,0,0,0);
}
else{
for(int j=0;j<noOfJoints;j++){
servoMotors[j].stop();
}
}
}
float RobotArm::Circle_round(float input){
while(input<=-M_PI){
input+=2*M_PI;
}
while(input>M_PI){
input-=2*M_PI;
}
return input;
}
float RobotArm::roundXdp(float input,int decimalPlaces){
float divider=pow(10,-decimalPlaces);
return (round(input/divider))*divider;
}
bool RobotArm::Move_position_cylinder_theta(float r, float alpha_deg,float z, float theta_deg){
float alpha = alpha_deg * M_PI / 180;
float x = r * cos(alpha);
float y = r * sin(alpha);
return Move_position_cart_theta(x, y, z, theta_deg);
}
bool RobotArm::Move_position_cylinder(float r, float alpha_deg,float z){
float alpha = alpha_deg * M_PI / 180;
float x = r * cos(alpha);
float y = r * sin(alpha);
return Move_position_cart(x, y, z);
}
void RobotArm::getToPosition_cylinder(float r, float alpha_deg,float z){
float alpha = alpha_deg * M_PI / 180;
float x = r * cos(alpha);
float y = r * sin(alpha);
this->getToPosition_cart(x, y, z);
}
void RobotArm::getToPosition_cylinder_theta(float r, float alpha_deg,float z, float theta_deg){
float alpha = alpha_deg * M_PI / 180;
float x = r * cos(alpha);
float y = r * sin(alpha);
getToPosition_cart_theta(x, y, z, theta_deg);
}
bool RobotArm::Move_position_spherical_theta(float R, float alpha_deg,float phi_deg, float theta_deg){
float alpha = alpha_deg * M_PI / 180;
float phi = phi_deg * M_PI / 180;
float z = R * sin(phi);
float r = R * cos(phi);
float x = r * cos(alpha);
float y = r * sin(alpha);
return Move_position_cart_theta(x, y, z, theta_deg);
}
bool RobotArm::Move_position_spherical(float R, float alpha_deg,float phi_deg){
float alpha = alpha_deg * M_PI / 180;
float phi = phi_deg * M_PI / 180;
float z = R * sin(phi);
float r = R * cos(phi);
float x = r * cos(alpha);
float y = r * sin(alpha);
return Move_position_cart(x, y, z);
}
void RobotArm::getToPosition_spherical(float R, float alpha_deg,float phi_deg){
float alpha = alpha_deg * M_PI / 180;
float phi = phi_deg * M_PI / 180;
float z = R * sin(phi);
float r = R * cos(phi);
float x = r * cos(alpha);
float y = r * sin(alpha);
this->getToPosition_cart(x, y, z);
}
void RobotArm::getToPosition_spherical_theta(float R, float alpha_deg,float phi_deg, float theta_deg){
float alpha = alpha_deg * M_PI / 180;
float phi = phi_deg * M_PI / 180;
float z = R * sin(phi);
float r = R * cos(phi);
float x = r * cos(alpha);
float y = r * sin(alpha);
getToPosition_cart_theta(x, y, z, theta_deg);
}
bool RobotArm::Move_x_units(float x_ch, float y_ch, float z_ch){
float location[4];
this->endEffecterPos(location);
float z_new = z_ch+location[2];
float x_new = x_ch+location[0];
float y_new = y_ch + location[1];
return Move_position_cart(x_new, y_new, z_new);
}
bool RobotArm::Move_x_units_theta(float x_ch, float y_ch, float z_ch,float theta_deg_ch){
float location[4];
this->endEffecterPos(location);
float z_new = z_ch+location[2];
float x_new = x_ch+location[0];
float y_new = y_ch + location[1];
float theta_deg_new = theta_deg_ch + location[3];
return Move_position_cart_theta(x_new, y_new, z_new, theta_deg_new);
}
void RobotArm::getToPositionShift_cart(float x_ch, float y_ch, float z_ch){
float location[4];
this->endEffecterPos(location);
float z_new = z_ch+location[2];
float x_new = x_ch+location[0];
float y_new = y_ch + location[1];
getToPosition_cart(x_new, y_new, z_new);
}
void RobotArm::getToPositionShift_cart_theta(float x_ch, float y_ch, float z_ch, float theta_deg_ch){
float location[4];
this->endEffecterPos(location);
float z_new = z_ch+location[2];
float x_new = x_ch+location[0];
float y_new = y_ch + location[1];
float theta_deg_new = theta_deg_ch + location[3];
getToPosition_cart_theta(x_new, y_new, z_new, theta_deg_new);
}
void RobotArm::endEffecterPos(float location[]){
float angles[4];
for (int i = 0; i < noOfJoints; i++){
angles[i] = (servoMotors[i].read() - 90) * M_PI / 180;
}
Matrix<4, 4> o[noOfJoints + 1];
ForwardKinematics(o, angles, linkLengths);
location[0] = -o[noOfJoints](1, 3);
location[1] = o[noOfJoints](0, 3);
location[2] = o[noOfJoints](2, 3);
location[3] = todeg(-angles[3] + M_PI_2 - angles[1] - angles[2]);
}
bool RobotArm::Move_position_cart(float x=0, float y=0,float z=0){
float angles[4];
for (int i = 0; i < noOfJoints; i++){
angles[i] = 0;
}
float distance = 50000;
float tolernece = 0.001 ;
int maxreps = 30;
int maxCounter = maxreps * (noOfJoints - 1), repNo = 0;
float targetLoc[3] = {x, y, z};
int target = noOfJoints - 1;
float totalLength = 0;
for (int i = 1; i < noOfJoints;i++){
totalLength += linkLengths[i];
}
if (sqrt(pow(x, 2) + pow(y, 2) + pow(z - linkLengths[0], 2)) > totalLength)
{
Serial << "Postion Can't be reached\n";
return false;
}
angles[0] = atan2(x, -y);
if (angles[0] < 0)
{
angles[0] += M_PI;
}
while (tolernece < distance)
{
//Find angle between the link to end effector and link to target
Matrix<4, 4> o[noOfJoints + 1];
ForwardKinematics(o, angles, linkLengths);
float endEffectorDist[3], targetDist[3];
for (int i = 0; i < 3; i++)
{
endEffectorDist[i] = o[noOfJoints](i, 3) - o[target](i, 3);
targetDist[i] = targetLoc[i] - o[target](i, 3);
}
float angleBet = findAngle(endEffectorDist, targetDist, 3);
angles[target] -= angleBet;
//confirm is in the correct direction
ForwardKinematics(o, angles, linkLengths);
for (int i = 0; i < 3; i++)
{
endEffectorDist[i] = o[noOfJoints](i, 3) - o[target ](i, 3);
targetDist[i] = targetLoc[i] - o[target](i, 3);
}
angleBet = findAngle(endEffectorDist, targetDist, 3);
angles[target] += angleBet;
//Limit the angle of the motor
if (abs(angles[target]) > M_PI_2)
{
angles[target] = angles[target] * M_PI_2 / abs(angles[target]);
}
//Find endeffector to target distance
ForwardKinematics(o, angles, linkLengths);
float d[3];
for (int i = 0; i < 3; i++)
{
d[i] = targetLoc[i] - o[noOfJoints](i, 3);
}
distance = vectorLength(d, 3);
target--;
if(target<1){
target = noOfJoints - 1;
}
if(repNo>=maxCounter){
break;
}
repNo++;
}
Matrix<4, 4> o[noOfJoints + 1];
ForwardKinematics(o, angles, linkLengths);
angles[0] -= M_PI_2;
for (int i = 0; i < noOfJoints; i++)
{
targetAngle[i] = angles[i] * 180 / M_PI + 90;
servoMotors[i].write(targetAngle[i],50);
}
return true;
}
bool RobotArm::Move_position_cart_theta(float final_x=0, float final_y=0,float final_z=0,float theta_deg=0){
float angles[4];
for (int i = 0; i < noOfJoints; i++){
angles[i] = 0;
}
float distance = 50000;
float tolernece = 0.005;
int maxreps = 50;
int maxCounter = maxreps * (noOfJoints - 2), repNo = 0;
float theta = theta_deg * M_PI / 180;
int jointNo = noOfJoints - 1;
int target = 2;
float totalLength = 0;
for (int i = 1; i < jointNo;i++){
totalLength += linkLengths[i];
}
angles[0] = atan2(final_x, -final_y);
if (angles[0] < 0)
{
angles[0] += M_PI;
}
float x = final_x - linkLengths[3] * cos(theta) * cos(angles[0]-M_PI_2);
float y = final_y - linkLengths[3] * cos(theta) * sin(angles[0]-M_PI_2);
float z = final_z - linkLengths[3] * sin(theta);
if (sqrt(pow(x, 2) + pow(y, 2) + pow(z - linkLengths[0], 2)) > totalLength)
{
Serial << "Postion Can't be reached\n";
return false;
}
float targetLoc[3] = {x, y, z};
while (tolernece < distance)
{
//Find angle between the link to end effector and link to target
Matrix<4, 4> o[noOfJoints + 1];
ForwardKinematics(o, angles, linkLengths);
float endEffectorDist[3], targetDist[3];
for (int i = 0; i < 3; i++)
{
endEffectorDist[i] = o[jointNo](i, 3) - o[target](i, 3);
targetDist[i] = targetLoc[i] - o[target](i, 3);
}
float angleBet = findAngle(endEffectorDist, targetDist, 3);
angles[target] -= angleBet;
//confirm is in the correct direction
ForwardKinematics(o, angles, linkLengths);
for (int i = 0; i < 3; i++)
{
endEffectorDist[i] = o[jointNo](i, 3) - o[target ](i, 3);
targetDist[i] = targetLoc[i] - o[target](i, 3);
}
angleBet = findAngle(endEffectorDist, targetDist, 3);
angles[target] += angleBet;
//Limit the angle of the motor
if (abs(angles[target]) > M_PI_2)
{
angles[target] = angles[target] * M_PI_2 / abs(angles[target]);
}
//Find endeffector to target distance
ForwardKinematics(o, angles, linkLengths);
float d[3];
for (int i = 0; i < 3; i++)
{
d[i] = targetLoc[i] - o[jointNo](i, 3);
}
distance = vectorLength(d, 3);
target--;
if(target<1){
target = 2;
}
if(repNo>=maxCounter){
break;
}
repNo++;
}
angles[0] -= M_PI_2;
angles[3] = -theta + M_PI_2 - angles[1] - angles[2];
for (int i = 0; i < noOfJoints; i++)
{
targetAngle[i] = angles[i] * 180 / M_PI + 90;
servoMotors[i].write(targetAngle[i],50);
}
return true;
}
void RobotArm::getToPosition_cart(float x, float y, float z){
Move_position_cart(x, y, z);
bool reached = false;
while (!reached){
for (int i = 0; i < noOfJoints;i++){
if (this->servoMotors[i].read()!=targetAngle[i]){
break;
}
if(i==noOfJoints-1){
reached = true;
break;
}
}
}
}
void RobotArm::getToPosition_cart_theta(float x, float y, float z,float theta){
bool reached = false;
Move_position_cart_theta(x, y, z,theta);
while (!reached){
for (int i = 0; i < noOfJoints;i++){
if (this->servoMotors[i].read()!=targetAngle[i]){
break;
}
if(i==noOfJoints-1){
reached = true;
break;
}
}
}
}
float RobotArm::dotProduct(float v1[], float v2[], int size = 3){
float value = 0;
for (int i = 0; i < size; i++)
{
value += v1[i] * v2[i];
}
return value;
}
float RobotArm::vectorLength(float v[], int size = 3){
float value = 0;
for (int i = 0; i < size;i++){
value += pow(v[i], 2);
}
return sqrt(value);
}
float RobotArm::findAngle(float v1[], float v2[], int size = 3){
float dot = dotProduct(v1, v2, size);
float size_1 = vectorLength(v1, size);
float size_2 = vectorLength(v2, size);
float cos_alpha = (dot / (size_1 * size_2));
if(cos_alpha>1){
cos_alpha = 1;
}else if(cos_alpha<-1){
cos_alpha = -1;
}
return acos(cos_alpha);
}
// Uses velocity IK to determine actuation for motors
void RobotArm::Move(float vx, float vy, float vz, float wx, float wy, float wz)
{
Matrix<4,1> targetVel={vx,vy,vz,wx};
for(int i=0;i<noOfJoints;i++){
jointAngles[i]=Mapf(servoMotors[i].read(),0,180,-M_PI_2,M_PI_2);
}
Matrix<noOfJoints,1> servoVelocity=InverseVelocityKinematics(jointAngles,linkLengths,targetVel);
for (int i=0;i<noOfJoints;i++){
int dir=0;
if(servoVelocity(i)>0){
dir=180;
}
if((servoMotors[i].read()==0&&servoVelocity(i)<0)||(servoMotors[i].read()==180 &&servoVelocity(i)>0)||isnan(servoVelocity(i))){
for(int j=0;j<noOfJoints;j++){
servoMotors[j].write(Mapf(jointAngles[j],-M_PI_2,M_PI_2,0,180));
}
break;
}
float speed_ticks=(servoVelocity(i)*180.0*2.5/M_PI);
speed_ticks=(abs(speed_ticks));
if(speed_ticks<=1){
servoMotors[i].write(Mapf(jointAngles[i],-M_PI_2,M_PI_2,0,180));
}else{
servoMotors[i].write(dir,speed_ticks+1);
}
}
}
float RobotArm::GetServoDegrees(int servo)
{
return servoMotors[servo].read();
}
float RobotArm::Mapf(float value, float fromLow, float fromHigh, float toLow, float toHigh)
{
return ((value - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) + toLow);
}
// Performs forward kinematics on the arm to determine the end effectors transformation matrix
void RobotArm::ForwardKinematics(Matrix<4, 4> o[], float r[], float t[])
{
o[0] = {1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1};
for (int i = 0; i < noOfJoints; i++)
{
if ((i == 0) || ((noOfJoints == 6) && ((i == 3) || (i == 5))))
{
o[i + 1] = o[i] * Rotate_Z(r[i]) * Translate_XYZ(0, 0, t[i]);
}
else
{
o[i + 1] = o[i] * Rotate_X(r[i]) * Translate_XYZ(0, 0, t[i]);
}
}
}
// Calculates jacobian matrix for the robotic arm required for velocity IK
Matrix<noOfJoints, noOfJoints> RobotArm::CalculateJacobian(Matrix<4, 4> transform[])
{
Matrix<noOfJoints, noOfJoints> jacobian;
Point o_n;
o_n.X() = transform[noOfJoints](0, 3);
o_n.Y() = transform[noOfJoints](1, 3);
o_n.Z() = transform[noOfJoints](2, 3);
for (int i = 0; i < noOfJoints; i++)
{
Point o_i;
o_i.X() = transform[i](0, 3);
o_i.Y() = transform[i](1, 3);
o_i.Z() = transform[i](2, 3);
Point z_i;
if ((i == 0) || ((noOfJoints == 6) && ((i == 3) || (i == 5))))
{
z_i.X() = transform[i](0, 2);
z_i.Y() = transform[i](1, 2);
z_i.Z() = transform[i](2, 2);
}
else
{
z_i.X() = transform[i](0, 0);
z_i.Y() = transform[i](1, 0);
z_i.Z() = transform[i](2, 0);
}
Point d = o_n - o_i;
Point j_v = z_i.CrossProduct(d);
float jacobian_i[] = {j_v.X(), j_v.Y(), j_v.Z(), z_i.X(), z_i.Y(), z_i.Z()};
for (int j = 0; j < noOfJoints; j++)
{
jacobian(j, i) = jacobian_i[j];
if(i==0&&j==3){
jacobian(j,i)=0;
}
}
}
return (jacobian);
}
// Full inverse velocity kinematics to calculate speed each motor should rotate at given a direction to move in
Matrix<noOfJoints, 1> RobotArm::InverseVelocityKinematics( float r[], float t[], Matrix<noOfJoints, 1> targetVelocity)
{
Matrix<4, 4> o[noOfJoints+1];
ForwardKinematics(o, r, t);
Matrix<noOfJoints,noOfJoints> VelForwardKinematics=CalculateJacobian(o);
if(VelForwardKinematics.Det()!=0){
Matrix<noOfJoints,noOfJoints> VelInverseKinematics=VelForwardKinematics.Inverse();
Matrix<noOfJoints, 1> k=(VelInverseKinematics*targetVelocity);
return k;
}else{
Matrix<noOfJoints,1> zeroVector = {0, 0, 0, 0};
return zeroVector;
}
}
bool RobotArm::DetectPassage(){
for (int i=0;i<3;i++){
int val=analogRead(phototransisorPins[i]);
if(val>limits[i]){
delay(1000);
return true;
}
}
return false;
}
//////////////////////////////////////////////////////
void RobotArm::ResetDraw(){
DrawValue=0;
DrawingDone=false;
}
void RobotArm::DrawSquare(float Length,float z){
if(!DrawingDone){
int interval=360/45;
float raduis;
int angle=DrawValue*interval;
int inputAngle=angle;
while(inputAngle>45){
inputAngle-=90;
}
raduis=Length/cos(torad(inputAngle));
int drawingAngle=0;
if(angle>90&&angle<270){
drawingAngle=180;
}
if(Move_position_cylinder_theta(raduis,angle,z,drawingAngle)){
bool notReached=false;
for(int i=0;i<noOfJoints && !notReached;i++){
float error=servoMotors[i].read()-GetServoDegrees(i);
if(abs(error)>10){
notReached=true;
}
}
if(!notReached){
if(DrawValue*interval>=360){
DrawingDone=true;
return;
}else{
DrawValue++;
}
}
}else{
DrawingDone=true;
return;
}
}
}
void RobotArm::DrawCircle(float raduis, float z){
int interval= 360/45;
if(!DrawingDone){
if(Move_position_cylinder_theta(raduis,DrawValue*interval,z,-90)){
bool notReached=false;
for(int i=0;i<noOfJoints && !notReached;i++){
float error=servoMotors[i].read()-GetServoDegrees(i);
if(abs(error)>5){
notReached=true;
}
}
if(!notReached){
if(DrawValue*interval>=360){
DrawingDone=true;
return;
}else{
DrawValue++;
}
}
}else{
DrawingDone=true;
return;
}
}
}
void RobotArm::FindLocation(float locations[]){
float servoAngles[noOfJoints];
for(int i=0;i<noOfJoints;i++){
if(i==1){
servoAngles[i]=torad(servoMotors[i].read());
}else{
servoAngles[i]=torad(servoMotors[i].read()-90);
}
}
float x=0,y=0;
locations[1]=linkLengths[0];
for(int i=1;i<noOfJoints;i++){
float totalAngle_T_A_B[]={0,0,0};
for(int j=i;j>=0;j--){
if(j>0&&j<4){
totalAngle_T_A_B[0]+=servoAngles[j];
}
else if(j==0){
totalAngle_T_A_B[1]+=servoAngles[j];
}
}
x+=linkLengths[i]*cos(totalAngle_T_A_B[0])*cos(totalAngle_T_A_B[1]);
y+=linkLengths[i]*cos(totalAngle_T_A_B[0])*sin(totalAngle_T_A_B[1]);
locations[1]+=linkLengths[i]*sin(totalAngle_T_A_B[0]);
if(i==noOfJoints-1){
locations[2]=todeg(totalAngle_T_A_B[0]);
}
}
locations[3]=todeg(atan2(y,x));
locations[0]=abs(sqrt(pow(x,2)+pow(y,2)));
}
// Solves systems of equations through gaussian elimination method.
Matrix<noOfJoints, 1> RobotArm::GaussianElimination(Matrix<noOfJoints, noOfJoints> jacobian, Matrix<noOfJoints, 1> targetVelocity)
{
Matrix<noOfJoints, noOfJoints + 1> augment = jacobian || targetVelocity;
float scalar;
// Get zeros in lower left
for (int i = 0; i < noOfJoints; i++)
{
scalar = augment(i, i);
if (scalar == 0)
{
break;
}
for (int j = 0; j <= noOfJoints; j++)
{
augment(i, j) /= scalar;
}
for (int j = i + 1; j < noOfJoints; j++)
{
scalar = augment(j, i);
if (scalar == 0)
{
break;
}
for (int k = 0; k <= noOfJoints; k++)
{
augment(j, k) -= scalar * augment(i, k);
}
}
}
// Get zeros in top right
for (int i = noOfJoints - 1; i > 0; i--)
{
for (int j = i - 1; j >= 0; j--)
{
scalar = augment(j, i);
for (int k = 0; k <= noOfJoints; k++)
{
augment(j, k) -= scalar * augment(i, k);
}
}
}
// Output solved matrix
Matrix<noOfJoints, 1> jointVelocity;
for (int i = 0; i < noOfJoints; i++)
{
jointVelocity(i) = augment(i, noOfJoints);
}
return jointVelocity;
}
// Calibration sequence takes the servos to their limits and records
// the positional feedback value
void RobotArm::CalibrateServos()
{
for (int i = 0; i < noOfJoints; i++)
{
servoMotors[i].write(0);
delay(3000);
servoLowerLimit[i] = analogRead(i);
servoMotors[i].write(90);
}
delay(3000);
for (int i = 0; i < noOfJoints; i++)
{
servoMotors[i].write(180);
delay(3000);
servoUpperLimit[i] = analogRead(i);
servoMotors[i].write(90);
}
}
| 28.741104 | 135 | 0.549223 | [
"transform"
] |
21820545096daff6e0240c2a797fe8e35c4fafc9 | 2,665 | cpp | C++ | catkin_ws/src/srrg2_executor/srrg2_executor/src/apps/auto_dl_finder.cpp | laaners/progetto-labiagi_pick_e_delivery | 3453bfbc1dd7562c78ba06c0f79b069b0a952c0e | [
"MIT"
] | null | null | null | catkin_ws/src/srrg2_executor/srrg2_executor/src/apps/auto_dl_finder.cpp | laaners/progetto-labiagi_pick_e_delivery | 3453bfbc1dd7562c78ba06c0f79b069b0a952c0e | [
"MIT"
] | null | null | null | catkin_ws/src/srrg2_executor/srrg2_executor/src/apps/auto_dl_finder.cpp | laaners/progetto-labiagi_pick_e_delivery | 3453bfbc1dd7562c78ba06c0f79b069b0a952c0e | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cstdlib>
#include <srrg_boss/serializer.h>
#include <srrg_config/configurable_manager.h>
#include <srrg_system_utils/parse_command_line.h>
#include <srrg_system_utils/system_utils.h>
#include <unistd.h>
#ifdef DEVEL_SPACE
std::string devel_space = DEVEL_SPACE;
#endif
#define MAX_PATH_LEN 512
using namespace srrg2_core;
// srrg getting bash output [link:
// https://www.jeremymorgan.com/tutorials/c-programming/how-to-capture-the-output-of-a-linux-command-in-c/]
std::vector<std::string> getStdOutFromCommand(std::string& cmd) {
std::vector<std::string> data;
FILE* stream;
const int max_buffer = 2048;
char buffer[max_buffer];
cmd += " 2>&1";
stream = popen(cmd.c_str(), "r");
if (stream) {
while (!feof(stream)) {
if (fgets(buffer, max_buffer, stream) != NULL) {
data.push_back(buffer);
}
}
pclose(stream);
}
return data;
}
const char* banner[] = {"auto dl finder", "assumption: using catkin as building system", 0};
int main(int argc, char** argv) {
#ifndef DEVEL_SPACE
std::cerr << "NO DEVEL SPACE DEFINED" << std::endl;
return -1;
#endif
srrgInit(argc, argv, "auto_dl_finder");
char cwd[MAX_PATH_LEN];
if (!getcwd(cwd, MAX_PATH_LEN)) {
throw std::runtime_error("unable to get the current working directory");
}
ParseCommandLine cmd_line(argv, banner);
ArgumentString dl_stub_file(
&cmd_line, "dlc", "dl-config", "stub where to read/write the stub", "dl.conf");
cmd_line.parse();
std::string stripped_devel_space = devel_space.substr(0, devel_space.find("devel") + 5);
std::cerr << "looking for dynamic libraries in " << stripped_devel_space << std::endl;
std::string output_file(cwd);
output_file += "/" + dl_stub_file.value();
Serializer ser;
ser.setFilePath(output_file);
DynamicLoaderConfig loader;
loader.so_paths.pushBack(stripped_devel_space);
if (chdir(stripped_devel_space.c_str()) != 0) {
std::string error_message = "unable to chdir to " + stripped_devel_space;
throw std::runtime_error(error_message.c_str());
};
std::string command = "find * \\( -type l -o -type f \\) -name '*.so' ";
// srrg exclude already loaded libraries
// command += "! -path '*_core*' ! -path '*qgl_viewport*' ";
std::vector<std::string> things = getStdOutFromCommand(command);
for (auto& a : things) {
a.erase(std::remove(a.begin(), a.end(), '\n'), a.end());
loader.so_names.pushBack(a);
}
for (size_t i = 0; i < loader.so_names.size(); ++i) {
std::cerr << loader.so_names.value(i) << std::endl;
}
std::cerr << "serializing " << output_file << std::endl;
ser.writeObject(loader);
return 0;
}
| 30.632184 | 107 | 0.677298 | [
"vector"
] |
21845bbb106c5cd3a078c78910e37cc70194dbeb | 3,140 | cpp | C++ | Source/Geometry/Mesh/imstkImageData.cpp | quantingxie/vibe | 965a79089ac3ec821ad65c45ac50e69bf32dc92f | [
"Apache-2.0"
] | 2 | 2020-08-14T07:21:30.000Z | 2021-08-30T09:39:09.000Z | Source/Geometry/Mesh/imstkImageData.cpp | quantingxie/vibe | 965a79089ac3ec821ad65c45ac50e69bf32dc92f | [
"Apache-2.0"
] | null | null | null | Source/Geometry/Mesh/imstkImageData.cpp | quantingxie/vibe | 965a79089ac3ec821ad65c45ac50e69bf32dc92f | [
"Apache-2.0"
] | 1 | 2020-08-14T07:00:31.000Z | 2020-08-14T07:00:31.000Z | /*=========================================================================
Library: iMSTK
Copyright (c) Kitware, Inc. & Center for Modeling, Simulation,
& Imaging in Medicine, Rensselaer Polytechnic Institute.
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.txt
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 "imstkImageData.h"
// vtk
#include "vtkImageReslice.h"
#include "vtkTransform.h"
namespace imstk
{
ImageData::ImageData(const std::string name)
: PointSet(Geometry::Type::ImageData, name),
m_dataTransform(vtkSmartPointer<vtkTransform>::New())
{
}
void
ImageData::print() const
{
Geometry::print();
}
double
ImageData::getVolume() const
{
if (!this->m_data)
{
return 0.0;
}
double bounds[6];
this->m_data->GetBounds(bounds);
return ((bounds[1] - bounds[0]) *
(bounds[3] - bounds[2]) *
(bounds[5] - bounds[4]));
}
void
ImageData::initialize(vtkImageData* im)
{
this->clear();
if (im)
{
this->m_data = vtkSmartPointer<vtkImageData>::New();
this->m_data->DeepCopy(im);
}
}
void
ImageData::clear()
{
if (this->m_data)
{
this->m_data = nullptr;
}
this->m_dataTransform->Identity();
this->m_transformApplied = true;
this->m_dataModified = true;
}
vtkImageData*
ImageData::getData(DataType type)
{
if (type == DataType::PostTransform)
{
this->updatePostTransformData();
}
return this->m_data;
}
void
ImageData::applyTranslation(const Vec3d t)
{
this->m_dataTransform->Translate(t[0], t[1], t[2]);
this->m_dataModified = true;
this->m_transformApplied = false;
}
void
ImageData::applyScaling(const double s)
{
this->m_dataTransform->Scale(s, s, s);
this->m_dataModified = true;
this->m_transformApplied = false;
}
void
ImageData::applyRotation(const Mat3d r)
{
vtkNew<vtkMatrix4x4> mat;
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
mat->SetElement(i, j, r(i, j));
}
}
this->m_dataTransform->Concatenate(mat);
this->m_dataModified = true;
this->m_transformApplied = false;
}
void
ImageData::updatePostTransformData()
{
if (m_transformApplied || !this->m_data)
{
return;
}
vtkNew<vtkImageReslice> reslice;
reslice->SetInputData(this->m_data);
reslice->SetResliceTransform(this->m_dataTransform);
reslice->SetInterpolationModeToLinear();
reslice->Update();
this->m_data->DeepCopy(reslice->GetOutput());
this->m_transformApplied = true;
}
} // imstk
| 22.112676 | 75 | 0.616879 | [
"geometry"
] |
21857cf9b91a51a5b8d19ab9daa3f2405d505f2e | 4,409 | cpp | C++ | jaco2_kin_dyn_lib/src/kdl_conversion.cpp | cogsys-tuebingen/jaco2_ros | 13147ae2e69a41936115a40739feb0f358af6f91 | [
"BSD-3-Clause"
] | 4 | 2019-07-01T23:44:12.000Z | 2021-03-12T06:01:24.000Z | jaco2_kin_dyn_lib/src/kdl_conversion.cpp | cogsys-tuebingen/jaco2_ros | 13147ae2e69a41936115a40739feb0f358af6f91 | [
"BSD-3-Clause"
] | null | null | null | jaco2_kin_dyn_lib/src/kdl_conversion.cpp | cogsys-tuebingen/jaco2_ros | 13147ae2e69a41936115a40739feb0f358af6f91 | [
"BSD-3-Clause"
] | 1 | 2021-03-15T06:10:19.000Z | 2021-03-15T06:10:19.000Z | #include <jaco2_kin_dyn_lib/kdl_conversion.h>
void Jaco2KinDynLib::convert(const KDL::JntArray &in, std::vector<double> &out)
{
out.resize(in.rows());
for(std::size_t i = 0; i < out.size(); ++i){
out[i] = in(i);
}
}
void Jaco2KinDynLib::convert(const std::vector<double> &in, KDL::JntArray &out, std::size_t ignore_end)
{
out.resize(in.size() - ignore_end);
for(std::size_t i = 0; i < out.rows(); ++i){
out(i) = in[i];
}
}
void Jaco2KinDynLib::convert(const std::vector<double> &in, Eigen::VectorXd &out, std::size_t ignore_end)
{
out.resize(in.size() - ignore_end);
std::size_t i = 0;
for(auto it = in.begin(); it < in.end() - ignore_end; ++it, ++i){
out(i) = *it;
}
}
void Jaco2KinDynLib::convert(const Eigen::VectorXd &in, std::vector<double> &out, std::size_t ignore_end)
{
out.resize(in.rows() -ignore_end);
for(std::size_t i = 0; i < out.size(); ++i){
out[i] = in(i);
}
}
void Jaco2KinDynLib::poseTFToKDL(const tf::Pose& t, KDL::Frame& k)
{
for (unsigned int i = 0; i < 3; ++i){
k.p[i] = t.getOrigin()[i];
}
for (unsigned int i = 0; i < 9; ++i){
k.M.data[i] = t.getBasis()[i/3][i%3];
}
}
Eigen::Matrix3d Jaco2KinDynLib::skewSymMat(const KDL::Vector &vec)
{
Eigen::Matrix3d res;
res << 0 , -vec(2) , vec(1),
vec(2), 0 , -vec(0),
-vec(1), vec(0) , 0;
return res;
}
Eigen::Matrix<double, 3, 6> Jaco2KinDynLib::inertiaProductMat(const KDL::Vector &vec)
{
Eigen::Matrix<double, 3, 6> res;
res << vec(0), vec(1), vec(2), 0 , 0 , 0,
0 , vec(0), 0 , vec(1), vec(2), 0,
0 , 0 , vec(0), 0 , vec(1), vec(2);
return res;
}
Eigen::Matrix<double, 6, 6> Jaco2KinDynLib::convert2EigenTwistTransform(const KDL::Frame &frame)
{
Eigen::Matrix<double, 6, 6> result;
Eigen::Matrix<double, 3, 3> rot = convert2Eigen(frame.M);
result.block<3,3>(0,0) = rot;
result.block<3,3>(0,3).setZero();
result.block<3,3>(3,0) = skewSymMat(frame.p) * rot;
result.block<3,3>(3,3) = rot;
return result;
}
Eigen::Matrix<double, 6, 6> Jaco2KinDynLib::convert2EigenWrenchTransform(const KDL::Frame &frame)
{
Eigen::Matrix<double, 6, 6> result;
Eigen::Matrix<double, 3, 3> rot = convert2Eigen(frame.M);
result.block<3,3>(0,0) = rot;
result.block<3,3>(0,3) = skewSymMat(frame.p) * rot;
result.block<3,3>(3,0).setZero();
result.block<3,3>(3,3) = rot;
return result;
}
Eigen::Matrix<double, 3, 3> Jaco2KinDynLib::convert2Eigen(const KDL::Rotation &rot)
{
Eigen::Matrix<double, 3, 3> result;
result << rot.data[0], rot.data[1], rot.data[2],
rot.data[3], rot.data[4], rot.data[5],
rot.data[6], rot.data[7], rot.data[8];
return result;
}
void Jaco2KinDynLib::kdlJntArray2Eigen(const KDL::JntArray &q, Eigen::VectorXd& res)
{
res.setZero(q.rows());
for(std::size_t i = 0; i < q.rows(); ++i){
res(i) = q(i);
}
}
void Jaco2KinDynLib::convert2Eigen(const KDL::JntSpaceInertiaMatrix& mat, Eigen::MatrixXd & res)
{
res.setZero(mat.rows(), mat.columns());
for(std::size_t i = 0; i < mat.rows(); ++i){
for(std::size_t j = 0; j < mat.columns(); ++j){
res(i,j) = mat(i,j);
}
}
}
Eigen::Matrix<double, 6, 1> Jaco2KinDynLib::convert2Eigen(const KDL::Twist& twist)
{
Eigen::Matrix<double, 6, 1> result;
result << twist.rot(0), twist.rot(1), twist.rot(2),
twist.vel(0), twist.vel(1), twist.vel(2);
return result;
}
Eigen::Matrix<double, 6, 1> Jaco2KinDynLib::convert2Eigen(const KDL::Wrench& wrench)
{
Eigen::Matrix<double, 6, 1> result;
result << wrench.torque(0), wrench.torque(1), wrench.torque(2),
wrench.force(0), wrench.force(1), wrench.force(2);
return result;
}
void Jaco2KinDynLib::vectorKDLToEigen(const KDL::Vector &in, Eigen::Vector3d &out)
{
out(0) = in(0);
out(1) = in(1);
out(2) = in(2);
}
void Jaco2KinDynLib::rotationKDLToEigen(const KDL::Rotation &in, Eigen::Quaterniond &out)
{
double x,y,z,w;
in.GetQuaternion(x,y,z,w);
out = Eigen::Quaterniond(w,x,y,z);
}
KDL::Wrench Jaco2KinDynLib::convert(const jaco2_data::Wrench& w)
{
KDL::Vector f(w.force(0), w.force(1), w.force(2));
KDL::Vector t(w.torque(0), w.torque(1), w.torque(2));
return KDL::Wrench(f, t);
}
| 29.006579 | 105 | 0.589022 | [
"vector"
] |
218b23d730c286985699ea0cbdf1b57f9bfbb16b | 4,543 | hpp | C++ | batteries/net/internal/parse.hpp | cblauvelt/batteries | 3f894bfd15972abd62a965d88d70c17aaeff443e | [
"Apache-2.0"
] | null | null | null | batteries/net/internal/parse.hpp | cblauvelt/batteries | 3f894bfd15972abd62a965d88d70c17aaeff443e | [
"Apache-2.0"
] | 6 | 2019-12-24T19:36:29.000Z | 2022-03-13T23:54:59.000Z | batteries/net/internal/parse.hpp | cblauvelt/batteries | 3f894bfd15972abd62a965d88d70c17aaeff443e | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 The Batteries Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <sstream>
#include <string>
#include <string_view>
#include <absl/strings/str_cat.h>
#include "batteries/net/base.hpp"
#include "escape.hpp"
namespace batteries {
namespace net {
namespace internal {
using query_map = std::multimap<std::string, std::string>;
/**
* @brief splits a string into two and only two parts at "match". If cutMatch is
* true, the delimiter is consumed.
* @param s The string to split.
* @param match The delimiter to search for and split if present.
* @param cutMatch If true, the delimiter is consumed.
*/
std::tuple<std::string_view, std::string_view>
split(std::string_view s, std::string_view match, bool cutMatch);
/**
* @brief Determine if the port, if present, is a valid port number
* @param port A string_view substring of the port portion of the URL.
*/
bool valid_optional_port(std::string_view port);
/**
* @brief reports whether s is a valid userinfo string per RFC 3986
*
* Section 3.2.1:
* userinfo = *( unreserved / pct-encoded / sub-delims / ":" )
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*
* It doesn't validate pct-encoded. The caller does that via func unescape.
*
* @param s A string that reperesents the user info contained within a URL.
* Usually of the form "username:password"
*/
bool valid_userinfo(std::string_view s);
/**
* @brief Takes a raw url that may contain the form path?query#fragment
* and removes the fragment.
* @param rawurl The url that may contain a fragment section.
* @returns If there is a fragment found, returns fragment,path; else "",rawurl.
*/
std::tuple<std::string, std::string_view, error>
parse_fragment(std::string_view rawurl);
/**
* @brief Takes a raw url that may contain the form scheme:path
* and breaks it down into it's component parts.
* @param rawurl The url that may contain a scheme section.
* @returns If there is a scheme found, returns scheme,path; else "",rawurl.
*/
std::tuple<std::string, std::string_view, error>
parse_scheme(std::string_view rawurl);
/**
* @brief parse_authority takes a string of form [userinfo@]host] and returns
* The username and password, if any, and the string_view to pass on to
* parse_host.
*
* @param authority a string_view of the form [userinfo@]host].
* @returns The username, password, and the host portion of the input.
*/
std::tuple<std::string, std::string, std::string_view, error>
parse_authority(std::string_view authority);
/**
* @brief parse_host parses the portion of the URL that contains the DNS or IP
* address and, optionally, the port.
* @param host The portion of the URL that contains the hostname information.
* @returns A tuple containing the hostname, port number, and error if any.
*/
std::tuple<std::string, std::string, error> parse_host(std::string_view host);
/**
* @brief Takes a raw query and converts it to a multimap of the values.
* @param query The raw query to be parsed.
* @returns A multimap[key] = []{value1, value2, ...}.
* @returns error indicating an error while parsing if any.
*/
std::tuple<query_map, error> parse_query(std::string_view query);
/**
* @brief Takes vector of key value pairs and build a query string.
* @param begin A const_iterator to the begining of the values.
* @param end A const_iterator to the end of the values.
*/
template <typename T> std::string build_query(T begin, T end) {
std::ostringstream buf;
for (auto it = begin; it != end; ++it) {
auto key = escape(it->first, encoding::encodeQueryComponent);
auto value = escape(it->second, encoding::encodeQueryComponent);
buf << absl::StrCat(key, "=", value, "&");
}
std::string retVal = buf.str();
// Remove the last &
retVal.pop_back();
return retVal;
}
} // namespace internal
} // namespace net
} // namespace batteries
| 33.404412 | 80 | 0.692934 | [
"vector"
] |
218dadad29fb68676a16adf2decf20956fe80e07 | 7,714 | hpp | C++ | src/wscb.hpp | aidv/WebSockets-Callback.CPP | 5e97bf021d62d0ce3c0b9cc668cf6502d832d4ad | [
"MIT"
] | 11 | 2019-03-17T12:01:53.000Z | 2021-01-28T12:36:45.000Z | src/wscb.hpp | aidv/WebSockets-Callback.CPP | 5e97bf021d62d0ce3c0b9cc668cf6502d832d4ad | [
"MIT"
] | null | null | null | src/wscb.hpp | aidv/WebSockets-Callback.CPP | 5e97bf021d62d0ce3c0b9cc668cf6502d832d4ad | [
"MIT"
] | 1 | 2020-04-11T10:25:02.000Z | 2020-04-11T10:25:02.000Z | #pragma once
#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/asio/strand.hpp>
#include <boost/asio.hpp>
#include <algorithm>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include <vector>
#include <list>
#include <fstream>
#include <thread>
#include <mutex>
#include <nlohmann/json.hpp>
#include "src/ws.hpp"
#include "src/classes.hpp"
using json = nlohmann::json;
namespace beast = boost::beast; // from <boost/beast.hpp>
namespace http = beast::http; // from <boost/beast/http.hpp>
namespace websocket = beast::websocket; // from <boost/beast/websocket.hpp>
namespace net = boost::asio; // from <boost/asio.hpp>
using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
class WebSockets_Callback {
std::thread thread;
std::condition_variable cv;
WSCB_Triggers* expectations;
WSCB_Triggers* triggers;
public:
WSCB_Options* options;
private:
std::string ws_types [2]; //0 = expector, 1 = responder
void server_thread(WSCB_Options* options){
//cout << "\n" << "WebSockets_Callback_Options::server_thread()";
net::io_context ioc{options->threads};
// Create and launch a listening port
std::make_shared<ws_listener>(ioc, boost::asio::ip::tcp::endpoint{
net::ip::make_address(options->address.c_str()),
static_cast<unsigned short>(options->port)
})->run(options);
// Run the I/O service on the requested number of threads
std::vector<std::thread> v;
v.reserve(options->threads - 1);
for(auto i = options->threads - 1; i > 0; --i)
v.emplace_back([&ioc]{ioc.run();});
ioc.run();
}
void client_thread(WSCB_Options* options){
net::io_context ioc;
auto wsc = std::make_shared<ws_client_session>(ioc);
wsc->run(options);
ioc.run();
}
void server_start(){
std::cout << "\n" << "Attempting to start WebSocket server @ " << options->address.c_str() << ":" << options->port << " using " << options->threads << " threads..." << std::endl;
thread = std::thread([this]() {this->server_thread(this->options);});
thread.detach();
}
void client_connect(){
thread = std::thread([this]() {this->client_thread(this->options);});
thread.detach();
}
void preOnMessage(std::string msg, const void* conn){
json json_;
try{
json_ = json::parse(msg.c_str());
} catch (std::invalid_argument & invalid){
std::cout << "\n" << "Error reading JSON " << invalid.what();
return;
}
bool hasPUID = (json_.find("puid") != json_.end());
if (hasPUID){
this->handleMessage(json_, conn);
} else {
options->callbacks.onUnexpectedMessage(json_, conn);
}
}
void handleMessage(json json_, const void* conn){
std::string sender = json_["puid"].get<std::string>().substr(0,2);
if (sender == this->ws_types[0]){
this->handleResponse(json_, conn);
} else if (sender == this->ws_types[1]){
this->handleExpectation(json_, conn);
}
}
void handleResponse(json json_, const void* conn){
//server responded to a message that we expected to have a response
int expectationIndex = expectations->indexOfPUID(json_["puid"].get<std::string>());
WSCB_Trigger* expectation = (expectationIndex == -1 ? NULL : expectations->elements[expectationIndex]);
if (expectation != NULL){
bool hasProgress = (json_.find("progress") != json_.end());
std::string progress = "";
if ((json_.find("progress") != json_.end())){
progress = json_["progress"].get<std::string>();
}
if (hasProgress == false || progress == "100"){
expectation->onResponse(json_);
expectations->elements.erase(expectations->elements.begin() + expectationIndex);
} else {
expectation->onProgress(json_);
}
}
}
void handleExpectation(json json_, const void* conn){
WSCB_Trigger* trigger = triggers->getByCommand(json_["cmd"].get<std::string>());
if (trigger == NULL) return;
trigger->doHandle(json_, [this, json_, conn](json response) -> void{
this->send(response, NULL, NULL, conn);
});
}
public:
WebSockets_Callback(){
options = new WSCB_Options;
expectations = new WSCB_Triggers;
triggers = new WSCB_Triggers;
if (options->asClient == false)
options->wsClientSessions = new std::vector<void*>();
}
~WebSockets_Callback(){
//cout << "\n" << "Destroying WebSockets_Callback object...";
}
void start(){
if (options->asClient == false){
ws_types[0] = "#s";
ws_types[1] = "#c";
} else {
ws_types[0] = "#c";
ws_types[1] = "#s";
}
options->callbacks.preOnMessage = [this](std::string* msg, const void* conn) -> void{
this->preOnMessage(*msg, conn);
};
if (options->callbacks.onListening != NULL || options->asClient == false){
this->server_start();
} else {
this->client_connect();
}
}
void stop(){
std::cout << "\n" << "Stopping WebSocket...";
}
void send(json json_, std::function<void(json)> onResponse = NULL, std::function<void(json)> onProgress = NULL, const void* conn = NULL){
json json__ = json::parse(json_.dump());
if (onResponse != NULL){
std::string puid = ws_types[0] + std::to_string((uint64_t)std::time(nullptr));
WSCB_Trigger* expectation = expectations->add("", NULL, onResponse, onProgress);
expectation->puid = puid;
json__["puid"] = puid;
}
if (options->asClient == false){
if (conn != NULL){
server_session* conn_ = ((server_session*)conn);
conn_->outputMessageQueue->push_back(json__.dump());
if (conn_->writing == false) conn_->reset();
} else {
for (int i = 0; i < options->wsClientSessions->size(); i++){
std::vector<void*> sessions = *options->wsClientSessions;
server_session* conn_ = ((server_session*)sessions[i]);
conn_->outputMessageQueue->push_back(json__.dump());
if (conn_->writing == false) conn_->reset();
}
}
} else {
if (options->clientSession == NULL) return;
ws_client_session* conn_ = ((ws_client_session*)options->clientSession);
conn_->outputMessageQueue->push_back(json__.dump());
if (conn_->writing == false) conn_->reset();
}
}
void simple(std::string command, std::function<void(json)> onResponse = NULL, void* conn = NULL){
this->send(
json::parse("{\"cmd\": \"" + command + "\"}"),
onResponse,
NULL,
conn
);
}
void on(std::string command, std::function<void(const json, std::function<void(const json)>)> doHandle){
triggers->add(command, doHandle);
}
};
| 33.107296 | 186 | 0.546409 | [
"object",
"vector"
] |
2192930a7156cfe0dcb3eec7c038e376179a54bc | 2,277 | cpp | C++ | feature_extractor/llvm/lib/ir_pass/IntFeature.cpp | ssrg-vt/aira | 96a830480d1ed8317e0175a10d950d7991fb2bb7 | [
"Unlicense"
] | 3 | 2018-12-17T08:20:40.000Z | 2020-02-24T02:08:23.000Z | feature_extractor/llvm/lib/ir_pass/IntFeature.cpp | ssrg-vt/aira | 96a830480d1ed8317e0175a10d950d7991fb2bb7 | [
"Unlicense"
] | null | null | null | feature_extractor/llvm/lib/ir_pass/IntFeature.cpp | ssrg-vt/aira | 96a830480d1ed8317e0175a10d950d7991fb2bb7 | [
"Unlicense"
] | null | null | null | /*****************************************************************************/
/* Implementation of IntFeature class */
/*****************************************************************************/
#include <iostream>
#include <string>
#include <llvm/IR/Function.h>
#include "IntFeature.h"
using namespace std;
using namespace llvm;
void IntFeature::collect(Instruction& instr, double bb_count)
{
if(instr.getNumOperands() < 1)
return;
unsigned int opcode = instr.getOpcode();
if(isVectorType(instr.getOperand(0)))
{
switch(opcode)
{
case Instruction::Add:
vec_adds += (unsigned int)bb_count;
break;
case Instruction::Sub:
vec_subtracts += (unsigned int)bb_count;
break;
case Instruction::Mul:
vec_multiplies += (unsigned int)bb_count;
break;
case Instruction::UDiv:
case Instruction::SDiv:
vec_divides += (unsigned int)bb_count;
break;
case Instruction::URem:
case Instruction::SRem:
vec_remainders += (unsigned int)bb_count;
break;
default:
//Nothing for now...
break;
}
}
else
{
switch(opcode)
{
case Instruction::Add:
adds += (unsigned int)bb_count;
break;
case Instruction::Sub:
subtracts += (unsigned int)bb_count;
break;
case Instruction::Mul:
multiplies += (unsigned int)bb_count;
break;
case Instruction::UDiv:
case Instruction::SDiv:
divides += (unsigned int)bb_count;
break;
case Instruction::URem:
case Instruction::SRem:
remainders += (unsigned int)bb_count;
break;
default:
//Nothing for now...
break;
}
}
}
void IntFeature::print(ostream& stream)
{
stream << "Integer additions: " << adds << endl;
stream << "Integer subtractions: " << subtracts << endl;
stream << "Integer multiplications: " << multiplies << endl;
stream << "Integer divisions (s+u): " << divides << endl;
stream << "Integer remainders (s+u): " << remainders << endl;
stream << "Integer vector additions: " << vec_adds<< endl;
stream << "Integer vector subtractions: " << vec_subtracts<< endl;
stream << "Integer vector multiplications: " << vec_multiplies << endl;
stream << "Integer vector divisions (s+u): " << vec_divides << endl;
stream << "Integer vector remainders (s+u): " << vec_remainders << endl;
}
| 26.172414 | 79 | 0.615722 | [
"vector"
] |
21940908b6168baea96f65faccdf1414ce285f2a | 309 | cc | C++ | FiniteElementSpace/Methods/FiniteVolume/fv_mapping_00a_node_info.cc | Naktakala/FESpace | 5d0e7aebdf17f5da233d97983a2535737207c7df | [
"MIT"
] | null | null | null | FiniteElementSpace/Methods/FiniteVolume/fv_mapping_00a_node_info.cc | Naktakala/FESpace | 5d0e7aebdf17f5da233d97983a2535737207c7df | [
"MIT"
] | null | null | null | FiniteElementSpace/Methods/FiniteVolume/fv_mapping_00a_node_info.cc | Naktakala/FESpace | 5d0e7aebdf17f5da233d97983a2535737207c7df | [
"MIT"
] | null | null | null | #include "fv_mapping.h"
#include "ChiMesh/Cell/cell.h"
using namespace chi_math::finite_element;
//std::vector<NodeInfo> FiniteVolume::GetNodeInfo() const
//{
// return {NodeInfo(NodeType::INTERNAL,
// IdentifyingInfo({{},{m_cell.global_id}}),
// m_cell.centroid)};
//} | 25.75 | 62 | 0.634304 | [
"vector"
] |
219502dbb54792bcd44c0b0f2dac401d385c498e | 32,718 | cxx | C++ | fpMain.cxx | Kairn/fantaisie-piano | 33be911b5bf3b0a5978bbfe6768902a27467c710 | [
"MIT"
] | 3 | 2018-08-28T04:59:29.000Z | 2021-07-26T03:25:10.000Z | fpMain.cxx | Kairn/fantaisie-piano | 33be911b5bf3b0a5978bbfe6768902a27467c710 | [
"MIT"
] | null | null | null | fpMain.cxx | Kairn/fantaisie-piano | 33be911b5bf3b0a5978bbfe6768902a27467c710 | [
"MIT"
] | 1 | 2019-11-22T05:12:58.000Z | 2019-11-22T05:12:58.000Z | /* fpMain.cxx */
/* ===========================================================================
* SOURCE FILE FOR THE MAIN PROGRAM
*
*/
#include "fpClasses.h"
#include "fpSheets.h"
#include "fpConstants.h"
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_mixer.h>
#include <SDL2/SDL_ttf.h>
#include <stdio.h>
#include <string>
#include <vector>
// declare system window and renderer
SDL_Window* fpWindow = NULL;
SDL_Renderer* fpRenderer = NULL;
// declare fonts
TTF_Font* fpFontTitle = NULL;
TTF_Font* fpFontAuthor = NULL;
// allocate memory for texture objects
Texture fpTextures[TEXTURE_TOTAL];
// define rectangle objects for all buttons
SDL_Rect buttonRects[BUTTON_TOTAL] =
{
{1000, 800, 300, 75},
{1000, 500, 300, 75},
{1000, 600, 300, 75},
{1500, 20, 200, 50},
{730, 750, 300, 100},
{1500, 830, 250, 60},
{1500, 910, 250, 60},
// scales
{50, 50, 200, 60},
{50, 150, 200, 60},
{50, 250, 200, 60},
{300, 250, 200, 60},
{300, 150, 200, 60},
{300, 50, 200, 60},
{550, 50, 200, 60},
{550, 150, 200, 60},
{550, 250, 200, 60},
{800, 250, 200, 60},
{800, 150, 200, 60},
{800, 50, 200, 60},
// pieces
{50, 150, 350, 60},
{50, 250, 350, 60},
{50, 350, 350, 60},
{50, 450, 350, 60},
{50, 550, 350, 60},
{50, 650, 350, 60},
{50, 750, 350, 60},
{50, 850, 350, 60},
{600, 150, 350, 60},
};
// allocate memory for button objects
Button fpButtons[BUTTON_TOTAL];
// define the notes on the fourth octave for each scale
int fpScaleNotes[SCALE_TOTAL][DEGREE_TOTAL] =
{
{39, 41, 43, 44, 46, 48, 50},
{39, 41, 43, 45, 46, 48, 50},
{40, 41, 43, 45, 46, 48, 50},
{40, 41, 43, 45, 47, 48, 50},
{40, 42, 43, 45, 47, 48, 50},
{40, 42, 43, 45, 47, 49, 50},
{40, 42, 44, 45, 47, 49, 50},
{39, 40, 42, 44, 45, 47, 49},
{39, 40, 42, 44, 46, 47, 49},
{39, 41, 42, 44, 46, 47, 49},
{39, 41, 42, 44, 46, 48, 49},
{39, 41, 43, 44, 46, 48, 49},
};
// define rectangle objects for all piano keys
SDL_Rect keyRect_1[PK_TOTAL] =
{
{50, 568, 28, 84},
{74, 400, 16, 168},
{82, 568, 28, 84},
{114, 568, 28, 84},
{134, 400, 16, 168},
{146, 568, 28, 84},
{170, 400, 16, 168},
{178, 568, 28, 84},
{210, 568, 28, 84},
{230, 400, 16, 168},
{242, 568, 28, 84},
{264, 400, 16, 168},
{274, 568, 28, 84},
{298, 400, 16, 168},
{306, 568, 28, 84},
{338, 568, 28, 84},
{358, 400, 16, 168},
{370, 568, 28, 84},
{394, 400, 16, 168},
{402, 568, 28, 84},
{434, 568, 28, 84},
{454, 400, 16, 168},
{466, 568, 28, 84},
{488, 400, 16, 168},
{498, 568, 28, 84},
{522, 400, 16, 168},
{530, 568, 28, 84},
{562, 568, 28, 84},
{582, 400, 16, 168},
{594, 568, 28, 84},
{618, 400, 16, 168},
{626, 568, 28, 84},
{658, 568, 28, 84},
{678, 400, 16, 168},
{690, 568, 28, 84},
{712, 400, 16, 168},
{722, 568, 28, 84},
{746, 400, 16, 168},
{754, 568, 28, 84},
{786, 568, 28, 84},
{806, 400, 16, 168},
{818, 568, 28, 84},
{842, 400, 16, 168},
{850, 568, 28, 84},
{882, 568, 28, 84},
{902, 400, 16, 168},
{914, 568, 28, 84},
{936, 400, 16, 168},
{946, 568, 28, 84},
{970, 400, 16, 168},
{978, 568, 28, 84},
{1010, 568, 28, 84},
{1030, 400, 16, 168},
{1042, 568, 28, 84},
{1066, 400, 16, 168},
{1074, 568, 28, 84},
{1106, 568, 28, 84},
{1126, 400, 16, 168},
{1138, 568, 28, 84},
{1160, 400, 16, 168},
{1170, 568, 28, 84},
{1194, 400, 16, 168},
{1202, 568, 28, 84},
{1234, 568, 28, 84},
{1254, 400, 16, 168},
{1266, 568, 28, 84},
{1290, 400, 16, 168},
{1298, 568, 28, 84},
{1330, 568, 28, 84},
{1350, 400, 16, 168},
{1362, 568, 28, 84},
{1384, 400, 16, 168},
{1394, 568, 28, 84},
{1418, 400, 16, 168},
{1426, 568, 28, 84},
{1458, 568, 28, 84},
{1478, 400, 16, 168},
{1490, 568, 28, 84},
{1514, 400, 16, 168},
{1522, 568, 28, 84},
{1554, 568, 28, 84},
{1574, 400, 16, 168},
{1586, 568, 28, 84},
{1608, 400, 16, 168},
{1618, 568, 28, 84},
{1642, 400, 16, 168},
{1650, 568, 28, 84},
{1682, 568, 28, 84},
};
SDL_Rect keyRect_2[PK_TOTAL] =
{
{50, 400, 24, 168},
{0, 0, 0, 0},
{90, 400, 20, 168},
{114, 400, 20, 168},
{0, 0, 0, 0},
{150, 400, 20, 168},
{0, 0, 0, 0},
{186, 400, 20, 168},
{210, 400, 20, 168},
{0, 0, 0, 0},
{246, 400, 18, 168},
{0, 0, 0, 0},
{280, 400, 18, 168},
{0, 0, 0, 0},
{314, 400, 20, 168},
{338, 400, 20, 168},
{0, 0, 0, 0},
{374, 400, 20, 168},
{0, 0, 0, 0},
{410, 400, 20, 168},
{434, 400, 20, 168},
{0, 0, 0, 0},
{470, 400, 18, 168},
{0, 0, 0, 0},
{504, 400, 18, 168},
{0, 0, 0, 0},
{538, 400, 20, 168},
{562, 400, 20, 168},
{0, 0, 0, 0},
{598, 400, 20, 168},
{0, 0, 0, 0},
{634, 400, 20, 168},
{658, 400, 20, 168},
{0, 0, 0, 0},
{694, 400, 18, 168},
{0, 0, 0, 0},
{728, 400, 18, 168},
{0, 0, 0, 0},
{762, 400, 20, 168},
{786, 400, 20, 168},
{0, 0, 0, 0},
{822, 400, 20, 168},
{0, 0, 0, 0},
{858, 400, 20, 168},
{882, 400, 20, 168},
{0, 0, 0, 0},
{918, 400, 18, 168},
{0, 0, 0, 0},
{952, 400, 18, 168},
{0, 0, 0, 0},
{986, 400, 20, 168},
{1010, 400, 20, 168},
{0, 0, 0, 0},
{1046, 400, 20, 168},
{0, 0, 0, 0},
{1082, 400, 20, 168},
{1106, 400, 20, 168},
{0, 0, 0, 0},
{1142, 400, 18, 168},
{0, 0, 0, 0},
{1176, 400, 18, 168},
{0, 0, 0, 0},
{1210, 400, 20, 168},
{1234, 400, 20, 168},
{0, 0, 0, 0},
{1270, 400, 20, 168},
{0, 0, 0, 0},
{1306, 400, 20, 168},
{1330, 400, 20, 168},
{0, 0, 0, 0},
{1366, 400, 18, 168},
{0, 0, 0, 0},
{1400, 400, 18, 168},
{0, 0, 0, 0},
{1434, 400, 20, 168},
{1458, 400, 20, 168},
{0, 0, 0, 0},
{1494, 400, 20, 168},
{0, 0, 0, 0},
{1530, 400, 20, 168},
{1554, 400, 20, 168},
{0, 0, 0, 0},
{1590, 400, 18, 168},
{0, 0, 0, 0},
{1624, 400, 18, 168},
{0, 0, 0, 0},
{1658, 400, 20, 168},
{1682, 400, 28, 168},
};
// allocate memory for piano key objects
PianoKey fpPKs[PK_TOTAL];
// allocate memory for sound chunks
Mix_Chunk* fpNoteSounds[PK_TOTAL];
// allocate memory for piece and author textures
Texture fpPieces[PIECE_TOTAL];
Texture fpAuthorSource[AUTHOR_TOTAL];
Texture* fpAuthors[PIECE_TOTAL];
// set up control variables (default)
bool fpSuccess = false;
bool fpActive = true;
bool fpSustain = false;
bool fpPaused = true;
bool fpHalted = true;
int fpMusic = -1;
int fpState = STATE_WELCOME;
int fpScale = C_MAJOR; // C major is the default scale
int fpAccidental = 0;
int fpOctave = 4; // default octave contains middle C or C4
int fpNextNote = 0; // next note to be played
int fpTempo = 100; // relative speed of the piece
double fpTime1 = 0;
double fpTime2 = 0;
double fpPlaytime = 0; // time into the piece
// set up event structure
SDL_Event fpEvent;
// set up the music sheet pointer
Note* fpSheet;
// set up action queue
std::vector<int> fpActionQueue;
// set up piano key queues
std::vector<int> fpPlayQueue;
std::vector<int> fpFadeQueue;
std::vector<Note> fpChordQueue;
// define the function for initializing SDL
bool initSDL()
{
bool success = true;
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0)
{
printf("%s\n", SDL_GetError());
success = false;
}
else
{
fpWindow = SDL_CreateWindow(
"Fantaisie Piano",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
SCREEN_WIDTH,
SCREEN_HEIGHT,
SDL_WINDOW_SHOWN
);
if (fpWindow == NULL)
{
printf("%s\n", SDL_GetError());
success = false;
}
else
{
fpRenderer = SDL_CreateRenderer(fpWindow, -1, SDL_RENDERER_ACCELERATED);
if (fpRenderer == NULL)
{
printf("%s\n", SDL_GetError());
success = false;
}
else
{
SDL_SetRenderDrawColor(fpRenderer, 0x00, 0x00, 0x00, 0xFF);
int imgFlags = IMG_INIT_PNG;
if (!(IMG_Init(imgFlags) & imgFlags))
{
printf("%s\n", IMG_GetError());
success = false;
}
else
{
if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 1024) < 0)
{
printf("%s\n", Mix_GetError());
success = false;
}
else
{
Mix_AllocateChannels(88);
if (Mix_AllocateChannels(-1) != 88)
{
printf("%s\n", "unable to allocate channels");
success = false;
}
else
{
if (TTF_Init() == -1)
{
printf("%s\n", TTF_GetError());
success = false;
}
else
{
fpFontTitle = TTF_OpenFont("fonts/cac_champagne.ttf", 104);
fpFontAuthor = TTF_OpenFont("fonts/CaviarDreams.ttf", 60);
if (fpFontTitle == NULL || fpFontAuthor == NULL)
{
printf("%s\n", TTF_GetError());
success = false;
}
}
}
}
}
}
}
}
return success;
}
// define the function for quitting SDL
void quitSDL()
{
// free window and renderer
SDL_DestroyRenderer(fpRenderer);
SDL_DestroyWindow(fpWindow);
fpRenderer = NULL;
fpWindow = NULL;
// free fonts
TTF_CloseFont(fpFontTitle);
TTF_CloseFont(fpFontAuthor);
fpFontTitle = NULL;
fpFontAuthor = NULL;
// shutdown SDL
TTF_Quit();
Mix_Quit();
IMG_Quit();
SDL_Quit();
}
// define the function for setting up button and piano key objects
void objSetup()
{
// set up button objects
for (int i = 0; i < BUTTON_TOTAL; ++i)
{
fpButtons[i].setButton(i, &buttonRects[i]);
}
// set up piano key objects
for (int i = 0; i < PK_TOTAL; ++i)
{
fpPKs[i].setPK(i, &keyRect_1[i], &keyRect_2[i]);
}
}
// define the function for loading all images and sounds
bool loadMedia()
{
bool success = true;
// load textures from PNG files
if
(
!fpTextures[TEXTURE_WELCOME].loadTexture("images/welcome.png") ||
!fpTextures[TEXTURE_KEYBOARD_UP].loadTexture("images/keyboard_up.png") ||
!fpTextures[TEXTURE_KEYBOARD_DOWN].loadTexture("images/keyboard_down.png") ||
!fpTextures[TEXTURE_MUSIC_SELECT].loadTexture("images/music_selection.png") ||
!fpTextures[TEXTURE_MUSIC_PLAYER].loadTexture("images/music_player.png") ||
!fpPieces[FANTAISIE_IMPROMPTU].loadFontString("Fantaisie-Impromptu", fpFontTitle) ||
!fpPieces[LIEBESTRAUME].loadFontString("Liebestraum No. 3", fpFontTitle) ||
!fpPieces[FUR_ELISE].loadFontString("Fur Elise", fpFontTitle) ||
!fpPieces[CLAIR_DE_LUNE].loadFontString("Clair de Lune", fpFontTitle) ||
!fpPieces[SONATA_PATHETIQUE].loadFontString("Piano Sonata No. 8 \"Pathetique\"", fpFontTitle) ||
!fpPieces[NOCTURNE_9].loadFontString("Nocturne Op. 9 No. 2", fpFontTitle) ||
!fpPieces[PRELUDE_FUGUE_C].loadFontString("Prelude and Fugue in C Major", fpFontTitle) ||
!fpPieces[BRAHMS_LULLABY].loadFontString("Wiegenlied: Guten Abend, gute Nacht", fpFontTitle) ||
!fpPieces[MOONLIGHT_SONATA].loadFontString("Piano Sonata No. 14 \"Moonlight\"", fpFontTitle) ||
!fpAuthorSource[CHOPIN].loadFontString("By Frederic Chopin", fpFontAuthor) ||
!fpAuthorSource[LISZT].loadFontString("By Franz Liszt", fpFontAuthor) ||
!fpAuthorSource[BEETHOVEN].loadFontString("By Ludwig van Beethoven", fpFontAuthor) ||
!fpAuthorSource[DEBUSSY].loadFontString("By Claude Debussy", fpFontAuthor) ||
!fpAuthorSource[BACH].loadFontString("By Johann Sebastian Bach", fpFontAuthor) ||
!fpAuthorSource[BRAHMS].loadFontString("By Johannes Brahms", fpFontAuthor)
)
{
printf("%s\n", IMG_GetError());
printf("%s\n", "or unable to generate TTF textures");
success = false;
}
else
{
// match author pointers to their sources
fpAuthors[FANTAISIE_IMPROMPTU] = &fpAuthorSource[CHOPIN];
fpAuthors[LIEBESTRAUME] = &fpAuthorSource[LISZT];
fpAuthors[FUR_ELISE] = &fpAuthorSource[BEETHOVEN];
fpAuthors[CLAIR_DE_LUNE] = &fpAuthorSource[DEBUSSY];
fpAuthors[SONATA_PATHETIQUE] = &fpAuthorSource[BEETHOVEN];
fpAuthors[NOCTURNE_9] = &fpAuthorSource[CHOPIN];
fpAuthors[PRELUDE_FUGUE_C] = &fpAuthorSource[BACH];
fpAuthors[BRAHMS_LULLABY] = &fpAuthorSource[BRAHMS];
fpAuthors[MOONLIGHT_SONATA] = &fpAuthorSource[BEETHOVEN];
// load sounds from OGG files
fpNoteSounds[PK_A0] = Mix_LoadWAV("sounds/notes_ogg/A0.ogg");
fpNoteSounds[PK_Bb0] = Mix_LoadWAV("sounds/notes_ogg/Bb0.ogg");
fpNoteSounds[PK_B0] = Mix_LoadWAV("sounds/notes_ogg/B0.ogg");
fpNoteSounds[PK_C1] = Mix_LoadWAV("sounds/notes_ogg/C1.ogg");
fpNoteSounds[PK_Db1] = Mix_LoadWAV("sounds/notes_ogg/Db1.ogg");
fpNoteSounds[PK_D1] = Mix_LoadWAV("sounds/notes_ogg/D1.ogg");
fpNoteSounds[PK_Eb1] = Mix_LoadWAV("sounds/notes_ogg/Eb1.ogg");
fpNoteSounds[PK_E1] = Mix_LoadWAV("sounds/notes_ogg/E1.ogg");
fpNoteSounds[PK_F1] = Mix_LoadWAV("sounds/notes_ogg/F1.ogg");
fpNoteSounds[PK_Gb1] = Mix_LoadWAV("sounds/notes_ogg/Gb1.ogg");
fpNoteSounds[PK_G1] = Mix_LoadWAV("sounds/notes_ogg/G1.ogg");
fpNoteSounds[PK_Ab1] = Mix_LoadWAV("sounds/notes_ogg/Ab1.ogg");
fpNoteSounds[PK_A1] = Mix_LoadWAV("sounds/notes_ogg/A1.ogg");
fpNoteSounds[PK_Bb1] = Mix_LoadWAV("sounds/notes_ogg/Bb1.ogg");
fpNoteSounds[PK_B1] = Mix_LoadWAV("sounds/notes_ogg/B1.ogg");
fpNoteSounds[PK_C2] = Mix_LoadWAV("sounds/notes_ogg/C2.ogg");
fpNoteSounds[PK_Db2] = Mix_LoadWAV("sounds/notes_ogg/Db2.ogg");
fpNoteSounds[PK_D2] = Mix_LoadWAV("sounds/notes_ogg/D2.ogg");
fpNoteSounds[PK_Eb2] = Mix_LoadWAV("sounds/notes_ogg/Eb2.ogg");
fpNoteSounds[PK_E2] = Mix_LoadWAV("sounds/notes_ogg/E2.ogg");
fpNoteSounds[PK_F2] = Mix_LoadWAV("sounds/notes_ogg/F2.ogg");
fpNoteSounds[PK_Gb2] = Mix_LoadWAV("sounds/notes_ogg/Gb2.ogg");
fpNoteSounds[PK_G2] = Mix_LoadWAV("sounds/notes_ogg/G2.ogg");
fpNoteSounds[PK_Ab2] = Mix_LoadWAV("sounds/notes_ogg/Ab2.ogg");
fpNoteSounds[PK_A2] = Mix_LoadWAV("sounds/notes_ogg/A2.ogg");
fpNoteSounds[PK_Bb2] = Mix_LoadWAV("sounds/notes_ogg/Bb2.ogg");
fpNoteSounds[PK_B2] = Mix_LoadWAV("sounds/notes_ogg/B2.ogg");
fpNoteSounds[PK_C3] = Mix_LoadWAV("sounds/notes_ogg/C3.ogg");
fpNoteSounds[PK_Db3] = Mix_LoadWAV("sounds/notes_ogg/Db3.ogg");
fpNoteSounds[PK_D3] = Mix_LoadWAV("sounds/notes_ogg/D3.ogg");
fpNoteSounds[PK_Eb3] = Mix_LoadWAV("sounds/notes_ogg/Eb3.ogg");
fpNoteSounds[PK_E3] = Mix_LoadWAV("sounds/notes_ogg/E3.ogg");
fpNoteSounds[PK_F3] = Mix_LoadWAV("sounds/notes_ogg/F3.ogg");
fpNoteSounds[PK_Gb3] = Mix_LoadWAV("sounds/notes_ogg/Gb3.ogg");
fpNoteSounds[PK_G3] = Mix_LoadWAV("sounds/notes_ogg/G3.ogg");
fpNoteSounds[PK_Ab3] = Mix_LoadWAV("sounds/notes_ogg/Ab3.ogg");
fpNoteSounds[PK_A3] = Mix_LoadWAV("sounds/notes_ogg/A3.ogg");
fpNoteSounds[PK_Bb3] = Mix_LoadWAV("sounds/notes_ogg/Bb3.ogg");
fpNoteSounds[PK_B3] = Mix_LoadWAV("sounds/notes_ogg/B3.ogg");
fpNoteSounds[PK_C4] = Mix_LoadWAV("sounds/notes_ogg/C4.ogg");
fpNoteSounds[PK_Db4] = Mix_LoadWAV("sounds/notes_ogg/Db4.ogg");
fpNoteSounds[PK_D4] = Mix_LoadWAV("sounds/notes_ogg/D4.ogg");
fpNoteSounds[PK_Eb4] = Mix_LoadWAV("sounds/notes_ogg/Eb4.ogg");
fpNoteSounds[PK_E4] = Mix_LoadWAV("sounds/notes_ogg/E4.ogg");
fpNoteSounds[PK_F4] = Mix_LoadWAV("sounds/notes_ogg/F4.ogg");
fpNoteSounds[PK_Gb4] = Mix_LoadWAV("sounds/notes_ogg/Gb4.ogg");
fpNoteSounds[PK_G4] = Mix_LoadWAV("sounds/notes_ogg/G4.ogg");
fpNoteSounds[PK_Ab4] = Mix_LoadWAV("sounds/notes_ogg/Ab4.ogg");
fpNoteSounds[PK_A4] = Mix_LoadWAV("sounds/notes_ogg/A4.ogg");
fpNoteSounds[PK_Bb4] = Mix_LoadWAV("sounds/notes_ogg/Bb4.ogg");
fpNoteSounds[PK_B4] = Mix_LoadWAV("sounds/notes_ogg/B4.ogg");
fpNoteSounds[PK_C5] = Mix_LoadWAV("sounds/notes_ogg/C5.ogg");
fpNoteSounds[PK_Db5] = Mix_LoadWAV("sounds/notes_ogg/Db5.ogg");
fpNoteSounds[PK_D5] = Mix_LoadWAV("sounds/notes_ogg/D5.ogg");
fpNoteSounds[PK_Eb5] = Mix_LoadWAV("sounds/notes_ogg/Eb5.ogg");
fpNoteSounds[PK_E5] = Mix_LoadWAV("sounds/notes_ogg/E5.ogg");
fpNoteSounds[PK_F5] = Mix_LoadWAV("sounds/notes_ogg/F5.ogg");
fpNoteSounds[PK_Gb5] = Mix_LoadWAV("sounds/notes_ogg/Gb5.ogg");
fpNoteSounds[PK_G5] = Mix_LoadWAV("sounds/notes_ogg/G5.ogg");
fpNoteSounds[PK_Ab5] = Mix_LoadWAV("sounds/notes_ogg/Ab5.ogg");
fpNoteSounds[PK_A5] = Mix_LoadWAV("sounds/notes_ogg/A5.ogg");
fpNoteSounds[PK_Bb5] = Mix_LoadWAV("sounds/notes_ogg/Bb5.ogg");
fpNoteSounds[PK_B5] = Mix_LoadWAV("sounds/notes_ogg/B5.ogg");
fpNoteSounds[PK_C6] = Mix_LoadWAV("sounds/notes_ogg/C6.ogg");
fpNoteSounds[PK_Db6] = Mix_LoadWAV("sounds/notes_ogg/Db6.ogg");
fpNoteSounds[PK_D6] = Mix_LoadWAV("sounds/notes_ogg/D6.ogg");
fpNoteSounds[PK_Eb6] = Mix_LoadWAV("sounds/notes_ogg/Eb6.ogg");
fpNoteSounds[PK_E6] = Mix_LoadWAV("sounds/notes_ogg/E6.ogg");
fpNoteSounds[PK_F6] = Mix_LoadWAV("sounds/notes_ogg/F6.ogg");
fpNoteSounds[PK_Gb6] = Mix_LoadWAV("sounds/notes_ogg/Gb6.ogg");
fpNoteSounds[PK_G6] = Mix_LoadWAV("sounds/notes_ogg/G6.ogg");
fpNoteSounds[PK_Ab6] = Mix_LoadWAV("sounds/notes_ogg/Ab6.ogg");
fpNoteSounds[PK_A6] = Mix_LoadWAV("sounds/notes_ogg/A6.ogg");
fpNoteSounds[PK_Bb6] = Mix_LoadWAV("sounds/notes_ogg/Bb6.ogg");
fpNoteSounds[PK_B6] = Mix_LoadWAV("sounds/notes_ogg/B6.ogg");
fpNoteSounds[PK_C7] = Mix_LoadWAV("sounds/notes_ogg/C7.ogg");
fpNoteSounds[PK_Db7] = Mix_LoadWAV("sounds/notes_ogg/Db7.ogg");
fpNoteSounds[PK_D7] = Mix_LoadWAV("sounds/notes_ogg/D7.ogg");
fpNoteSounds[PK_Eb7] = Mix_LoadWAV("sounds/notes_ogg/Eb7.ogg");
fpNoteSounds[PK_E7] = Mix_LoadWAV("sounds/notes_ogg/E7.ogg");
fpNoteSounds[PK_F7] = Mix_LoadWAV("sounds/notes_ogg/F7.ogg");
fpNoteSounds[PK_Gb7] = Mix_LoadWAV("sounds/notes_ogg/Gb7.ogg");
fpNoteSounds[PK_G7] = Mix_LoadWAV("sounds/notes_ogg/G7.ogg");
fpNoteSounds[PK_Ab7] = Mix_LoadWAV("sounds/notes_ogg/Ab7.ogg");
fpNoteSounds[PK_A7] = Mix_LoadWAV("sounds/notes_ogg/A7.ogg");
fpNoteSounds[PK_Bb7] = Mix_LoadWAV("sounds/notes_ogg/Bb7.ogg");
fpNoteSounds[PK_B7] = Mix_LoadWAV("sounds/notes_ogg/B7.ogg");
fpNoteSounds[PK_C8] = Mix_LoadWAV("sounds/notes_ogg/C8.ogg");
}
for (int i = 0; i < PK_TOTAL; ++i)
{
if (fpNoteSounds[i] == NULL)
{
printf("%s\n", Mix_GetError());
success = false;
}
}
return success;
}
// define the function for executing button actions
void actionProcessor()
{
for (size_t i = 0; i < fpActionQueue.size(); ++i)
{
if (fpActionQueue[i] == BUTTON_QUIT)
{
fpActive = false;
fpState = -1;
fpSuccess = true;
break;
}
else if (fpActionQueue[i] <= BUTTON_MUSIC_BOX)
{
fpState = fpActionQueue[i];
fpSustain = false;
fpScale = C_MAJOR;
fpAccidental = 0;
fpOctave = 4;
}
else if (fpActionQueue[i] == BUTTON_GO_BACK)
{
if (fpState == STATE_MUSIC_PLAYER)
{
fpState = STATE_MUSIC_SELECT;
fpMusic = -1;
fpHalted = true;
fpPaused = true;
fpSheet = NULL;
Mix_HaltChannel(-1);
}
else
{
fpState = STATE_WELCOME;
}
}
else if (fpActionQueue[i] == BUTTON_SUSTAIN)
{
fpSustain = !fpSustain;
}
else if (fpActionQueue[i] == BUTTON_PAUSE)
{
if (fpHalted)
{
fpTime1 = SDL_GetTicks();
fpPlaytime = 0;
fpTime2 = 0;
fpNextNote = 0;
fpHalted = false;
fpPaused = false;
}
else if (!fpHalted && !fpPaused)
{
fpPaused = true;
Mix_Pause(-1);
}
else if (!fpHalted && fpPaused)
{
fpPaused = false;
Mix_Resume(-1);
}
}
else if (fpActionQueue[i] == BUTTON_STOP)
{
fpHalted = true;
fpTempo = 100;
Mix_HaltChannel(-1);
}
else if (BUTTON_C_MAJOR <= fpActionQueue[i] && fpActionQueue[i] <= BUTTON_D_MINOR)
{
fpScale = fpActionQueue[i] - 7;
}
else if (fpActionQueue[i] < BUTTON_TOTAL)
{
fpState = STATE_MUSIC_PLAYER;
fpMusic = fpActionQueue[i] - 19;
fpHalted = true;
fpPaused = true;
fpTempo = 100;
// load the programmed sheet music
switch (fpMusic)
{
case FANTAISIE_IMPROMPTU:
fpSheet = musicFantaisieImpromptu;
break;
case LIEBESTRAUME:
fpSheet = musicLiebestraum;
break;
case FUR_ELISE:
fpSheet = musicFurElise;
break;
case CLAIR_DE_LUNE:
fpSheet = musicClairdeLune;
break;
case SONATA_PATHETIQUE:
fpSheet = musicSonataPathetique;
break;
case NOCTURNE_9:
fpSheet = musicNocturnes9;
break;
case PRELUDE_FUGUE_C:
fpSheet = musicPreludeC;
break;
case BRAHMS_LULLABY:
fpSheet = musicBrahmsLullaby;
break;
case MOONLIGHT_SONATA:
fpSheet = musicMoonlightSonata;
break;
}
}
}
// clear action queue
fpActionQueue.clear();
}
// define the function for executing piano key actions
void keyProcessor()
{
// handle key presses
if (!fpPlayQueue.empty())
{
for (size_t i = 0; i < fpPlayQueue.size(); ++i)
{
if (Mix_FadingChannel(fpPlayQueue[i]) == MIX_FADING_OUT)
{
Mix_HaltChannel(fpPlayQueue[i]);
Mix_PlayChannel(fpPlayQueue[i], fpNoteSounds[fpPlayQueue[i]], 0);
}
else
{
Mix_PlayChannel(fpPlayQueue[i], fpNoteSounds[fpPlayQueue[i]], 0);
}
}
}
// handle key releases
if (!fpFadeQueue.empty())
{
for (size_t i = 0; i < fpFadeQueue.size(); ++i)
{
if (!fpSustain)
{
if (Mix_Playing(fpFadeQueue[i]))
{
Mix_FadeOutChannel(fpFadeQueue[i], 1000);
}
}
}
}
// clear piano key queues
fpPlayQueue.clear();
fpFadeQueue.clear();
}
// define the function for updating the play time
int updatePlayTime()
{
fpTime2 = SDL_GetTicks();
if (!fpPaused)
{
fpPlaytime += ((fpTime2 - fpTime1) * fpTempo) / 100;
}
fpTime1 = fpTime2;
}
// define the function for rendering and updating the screen
void updateScreen()
{
// render buttons
if (fpState == STATE_PIANO)
{
// sustain buttion
if (fpSustain)
{
fpTextures[TEXTURE_KEYBOARD_DOWN].renderTexture(buttonRects[BUTTON_SUSTAIN].x, buttonRects[BUTTON_SUSTAIN].y, &buttonRects[BUTTON_SUSTAIN]);
}
// scale buttons
fpTextures[TEXTURE_KEYBOARD_DOWN].renderTexture(buttonRects[fpScale + 7].x, buttonRects[fpScale + 7].y, &buttonRects[fpScale + 7]);
// render piano keys
for (int i = 0; i < PK_TOTAL; ++i)
{
if (Mix_Playing(i))
{
// white keys
if (keyRect_1[i].y == 568)
{
fpTextures[TEXTURE_KEYBOARD_DOWN].renderTexture(keyRect_1[i].x, keyRect_1[i].y, &keyRect_1[i]);
fpTextures[TEXTURE_KEYBOARD_DOWN].renderTexture(keyRect_2[i].x, keyRect_2[i].y, &keyRect_2[i]);
}
// black keys
else if (keyRect_1[i].y == 400)
{
fpTextures[TEXTURE_KEYBOARD_DOWN].renderTexture(keyRect_1[i].x, keyRect_1[i].y, &keyRect_1[i]);
}
}
}
}
// render piece title and author
if (fpState == STATE_MUSIC_PLAYER)
{
fpPieces[fpMusic].renderTexture((SCREEN_WIDTH - fpPieces[fpMusic].getWidth()) / 2, 400, NULL);
fpAuthors[fpMusic] -> renderTexture(SCREEN_WIDTH / 2, 550, NULL);
}
// update screen
SDL_RenderPresent(fpRenderer);
}
// define the function for handling the main loop while the program is active
bool startLoop()
{
// keyboard management booleans
bool acc_good = 1; // for accidentals
bool oct_good = 1; // for octaves
bool z_good = 1; // Z key
bool x_good = 1; // X key
bool c_good = 1; // C key
bool v_good = 1; // V key
bool b_good = 1; // B key
bool n_good = 1; // N key
bool m_good = 1; // M key
// system loop
while (fpActive)
{
// loop on the welcome screen
while (fpState == STATE_WELCOME)
{
SDL_RenderClear(fpRenderer);
fpTextures[TEXTURE_WELCOME].renderTexture(0, 0, NULL);
// detect events
while (SDL_PollEvent(&fpEvent))
{
// mouse events
if (fpEvent.type == SDL_QUIT)
{
fpActive = false;
fpState = -1;
fpSuccess = true;
break;
}
for (int i = BUTTON_QUIT; i <= BUTTON_MUSIC_BOX; ++i)
{
fpButtons[i].handleMouseEvent(&fpEvent, fpActionQueue);
}
}
// process actions
actionProcessor();
// update screen
updateScreen();
}
// loop on the piano mode
while (fpState == STATE_PIANO)
{
SDL_RenderClear(fpRenderer);
fpTextures[TEXTURE_KEYBOARD_UP].renderTexture(0, 0, NULL);
// detect events
while (SDL_PollEvent(&fpEvent))
{
// mouse events
if (fpEvent.type == SDL_QUIT)
{
fpActive = false;
fpState = -1;
fpSuccess = true;
break;
}
for (int i = BUTTON_GO_BACK; i <= BUTTON_D_MINOR; ++i)
{
if (i != BUTTON_PAUSE && i != BUTTON_STOP)
{
fpButtons[i].handleMouseEvent(&fpEvent, fpActionQueue);
}
}
for (int i = 0; i < PK_TOTAL; ++i)
{
fpPKs[i].handleMouseEvent(&fpEvent, fpPlayQueue, fpFadeQueue);
}
// keyboard events
if (fpEvent.type == SDL_KEYDOWN)
{
switch (fpEvent.key.keysym.sym)
{
case SDLK_LSHIFT:
if (acc_good)
{
fpAccidental = 1;
acc_good = false;
}
break;
case SDLK_LCTRL:
if (acc_good)
{
fpAccidental = -1;
acc_good = false;
}
break;
case SDLK_KP_1:
if (oct_good)
{
fpOctave = 1;
oct_good = false;
}
break;
case SDLK_KP_2:
if (oct_good)
{
fpOctave = 2;
oct_good = false;
}
break;
case SDLK_KP_3:
if (oct_good)
{
fpOctave = 3;
oct_good = false;
}
break;
case SDLK_KP_5:
if (oct_good)
{
fpOctave = 5;
oct_good = false;
}
break;
case SDLK_KP_6:
if (oct_good)
{
fpOctave = 6;
oct_good = false;
}
break;
case SDLK_KP_7:
if (oct_good)
{
fpOctave = 7;
oct_good = false;
}
break;
case SDLK_z:
if (z_good)
{
fpPKs[fpScaleNotes[fpScale][CNote] + (fpOctave - 4) * 12 + fpAccidental].pressPK(fpPlayQueue);
z_good = false;
}
break;
case SDLK_x:
if (x_good)
{
fpPKs[fpScaleNotes[fpScale][DNote] + (fpOctave - 4) * 12 + fpAccidental].pressPK(fpPlayQueue);
x_good = false;
}
break;
case SDLK_c:
if (c_good)
{
fpPKs[fpScaleNotes[fpScale][ENote] + (fpOctave - 4) * 12 + fpAccidental].pressPK(fpPlayQueue);
c_good = false;
}
break;
case SDLK_v:
if (v_good)
{
fpPKs[fpScaleNotes[fpScale][FNote] + (fpOctave - 4) * 12 + fpAccidental].pressPK(fpPlayQueue);
v_good = false;
}
break;
case SDLK_b:
if (b_good)
{
fpPKs[fpScaleNotes[fpScale][GNote] + (fpOctave - 4) * 12 + fpAccidental].pressPK(fpPlayQueue);
b_good = false;
}
break;
case SDLK_n:
if (n_good)
{
fpPKs[fpScaleNotes[fpScale][ANote] + (fpOctave - 4) * 12 + fpAccidental].pressPK(fpPlayQueue);
n_good = false;
}
break;
case SDLK_m:
if (m_good)
{
fpPKs[fpScaleNotes[fpScale][BNote] + (fpOctave - 4) * 12 + fpAccidental].pressPK(fpPlayQueue);
m_good = false;
}
}
}
else if (fpEvent.type == SDL_KEYUP)
{
switch (fpEvent.key.keysym.sym)
{
case SDLK_LSHIFT:
fpAccidental = 0;
acc_good = true;
break;
case SDLK_LCTRL:
fpAccidental = 0;
acc_good = true;
break;
case SDLK_KP_1:
fpOctave = 4;
oct_good = true;
break;
case SDLK_KP_2:
fpOctave = 4;
oct_good = true;
break;
case SDLK_KP_3:
fpOctave = 4;
oct_good = true;
break;
case SDLK_KP_5:
fpOctave = 4;
oct_good = true;
break;
case SDLK_KP_6:
fpOctave = 4;
oct_good = true;
break;
case SDLK_KP_7:
fpOctave = 4;
oct_good = true;
break;
case SDLK_z:
fpPKs[fpScaleNotes[fpScale][CNote] + (fpOctave - 4) * 12 + fpAccidental].releasePK(fpFadeQueue);
z_good = true;
break;
case SDLK_x:
fpPKs[fpScaleNotes[fpScale][DNote] + (fpOctave - 4) * 12 + fpAccidental].releasePK(fpFadeQueue);
x_good = true;
break;
case SDLK_c:
fpPKs[fpScaleNotes[fpScale][ENote] + (fpOctave - 4) * 12 + fpAccidental].releasePK(fpFadeQueue);
c_good = true;
break;
case SDLK_v:
fpPKs[fpScaleNotes[fpScale][FNote] + (fpOctave - 4) * 12 + fpAccidental].releasePK(fpFadeQueue);
v_good = true;
break;
case SDLK_b:
fpPKs[fpScaleNotes[fpScale][GNote] + (fpOctave - 4) * 12 + fpAccidental].releasePK(fpFadeQueue);
b_good = true;
break;
case SDLK_n:
fpPKs[fpScaleNotes[fpScale][ANote] + (fpOctave - 4) * 12 + fpAccidental].releasePK(fpFadeQueue);
n_good = true;
break;
case SDLK_m:
fpPKs[fpScaleNotes[fpScale][BNote] + (fpOctave - 4) * 12 + fpAccidental].releasePK(fpFadeQueue);
m_good = true;
break;
case SDLK_TAB:
Mix_HaltChannel(-1);
}
}
}
// process actions
actionProcessor();
keyProcessor();
// update screen
updateScreen();
}
// loop on the piece selection mode
while (fpState == STATE_MUSIC_SELECT)
{
SDL_RenderClear(fpRenderer);
fpTextures[TEXTURE_MUSIC_SELECT].renderTexture(0, 0, NULL);
// detect events
while (SDL_PollEvent(&fpEvent))
{
// mouse events
if (fpEvent.type == SDL_QUIT)
{
fpActive = false;
fpState = -1;
fpSuccess = true;
break;
}
fpButtons[BUTTON_GO_BACK].handleMouseEvent(&fpEvent, fpActionQueue);
for (int i = BUTTON_FANTAISIE_IMPROMPTU; i < BUTTON_TOTAL; ++i)
{
fpButtons[i].handleMouseEvent(&fpEvent, fpActionQueue);
}
}
// process actions
actionProcessor();
// update screen
updateScreen();
}
// loop on the music player mode
while (fpState == STATE_MUSIC_PLAYER)
{
SDL_RenderClear(fpRenderer);
fpTextures[TEXTURE_MUSIC_PLAYER].renderTexture(0, 0, NULL);
// detect events
while (SDL_PollEvent(&fpEvent))
{
if (fpEvent.type == SDL_QUIT)
{
fpActive = false;
fpState = -1;
fpSuccess = true;
break;
}
fpButtons[BUTTON_GO_BACK].handleMouseEvent(&fpEvent, fpActionQueue);
fpButtons[BUTTON_PAUSE].handleMouseEvent(&fpEvent, fpActionQueue);
}
// loop for playing the programmed notes
while (!fpHalted)
{
// play or fade a note based on play time
if (fpSheet[fpNextNote].name != -1 && fpSheet[fpNextNote].name != -2 && fpSheet[fpNextNote].name != -3 && fpSheet[fpNextNote].name != -4)
{
if (fpPlaytime >= fpSheet[fpNextNote].time)
{
if (fpSheet[fpNextNote].toplay)
{
int chord_time = fpSheet[fpNextNote].time;
bool chord_continue = true;
// build chord notes before playing them
while (chord_continue)
{
fpChordQueue.push_back(fpSheet[fpNextNote]);
if (fpSheet[fpNextNote + 1].toplay && fpSheet[fpNextNote + 1].time == chord_time)
{
fpNextNote += 1;
}
else
{
for (Note ni : fpChordQueue)
{
if (Mix_FadingChannel(ni.name) == MIX_FADING_OUT)
{
Mix_HaltChannel(ni.name);
}
Mix_Volume(ni.name, ni.volume);
}
for (Note ni : fpChordQueue)
{
Mix_PlayChannel(ni.name, fpNoteSounds[ni.name], 0);
}
fpChordQueue.clear();
chord_continue = false;
fpNextNote += 1;
}
}
}
else
{
if (Mix_Playing(fpSheet[fpNextNote].name))
{
Mix_FadeOutChannel(fpSheet[fpNextNote].name, 600);
}
fpNextNote += 1;
}
}
}
// time change
else if (fpSheet[fpNextNote].name == -4)
{
fpPlaytime = fpSheet[fpNextNote].time;
fpNextNote += 1;
}
// tempo change
else if (fpSheet[fpNextNote].name == -3)
{
if (fpSheet[fpNextNote].time == 0)
{
fpTempo = 100;
}
else if (fpSheet[fpNextNote].time > 0)
{
fpTempo = fpSheet[fpNextNote].time;
}
fpNextNote += 1;
}
// release pedal
else if (fpSheet[fpNextNote].name == -2)
{
Mix_FadeOutChannel(-1, 600);
fpNextNote += 1;
}
// end piece
else
{
SDL_Delay(2000);
fpHalted = true;
Mix_HaltChannel(-1);
}
// check events
while (SDL_PollEvent(&fpEvent))
{
if (fpEvent.type == SDL_QUIT)
{
fpHalted = true;
fpActive = false;
fpState = -1;
fpSuccess = true;
break;
}
fpButtons[BUTTON_GO_BACK].handleMouseEvent(&fpEvent, fpActionQueue);
fpButtons[BUTTON_PAUSE].handleMouseEvent(&fpEvent, fpActionQueue);
fpButtons[BUTTON_STOP].handleMouseEvent(&fpEvent, fpActionQueue);
}
actionProcessor();
updateScreen();
// update play time
updatePlayTime();
}
// process actions
actionProcessor();
// update screen
updateScreen();
}
}
return fpSuccess;
}
// main program launcher
int main(int argc, char** argv)
{
// initialize SDL
if (!initSDL())
{
printf("\n%s\n", "unable to initialize SDL");
}
else
{
// set up objects
objSetup();
// load media
if (!loadMedia())
{
printf("\n%s\n", "unable to load media files");
}
else
{
// run the main program loop
if (!startLoop())
{
printf("\n%s\n", "process ended unexpectedly");
}
}
// quit SDL
quitSDL();
}
return 0;
}
| 25.864032 | 143 | 0.619231 | [
"render",
"vector"
] |
2195806e1ab1973c46e944caf74c295e22cc2a08 | 6,132 | hpp | C++ | contrib/MassSpectra/flexiblesusy/src/two_scale_convergence_tester_drbar.hpp | aaronvincent/gambit_aaron | a38bd6fc10d781e71f2adafd401c76e1e3476b05 | [
"Unlicense"
] | null | null | null | contrib/MassSpectra/flexiblesusy/src/two_scale_convergence_tester_drbar.hpp | aaronvincent/gambit_aaron | a38bd6fc10d781e71f2adafd401c76e1e3476b05 | [
"Unlicense"
] | null | null | null | contrib/MassSpectra/flexiblesusy/src/two_scale_convergence_tester_drbar.hpp | aaronvincent/gambit_aaron | a38bd6fc10d781e71f2adafd401c76e1e3476b05 | [
"Unlicense"
] | null | null | null | // ====================================================================
// This file is part of FlexibleSUSY.
//
// FlexibleSUSY is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published
// by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later version.
//
// FlexibleSUSY 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 FlexibleSUSY. If not, see
// <http://www.gnu.org/licenses/>.
// ====================================================================
#ifndef TWO_SCALE_CONVERGENCE_TESTER_DRBAR_H
#define TWO_SCALE_CONVERGENCE_TESTER_DRBAR_H
#include "two_scale_convergence_tester.hpp"
#include "convergence_tester_drbar.hpp"
#include "logger.hpp"
#include <cmath>
#include <limits>
namespace flexiblesusy {
template <template<class Method> class Model>
class Convergence_tester_DRbar<Model<Two_scale> > :
public Convergence_tester<Two_scale> {
public:
Convergence_tester_DRbar(Model<Two_scale>*, double);
virtual ~Convergence_tester_DRbar();
virtual bool accuracy_goal_reached();
virtual double get_accuracy_goal() const;
virtual unsigned int max_iterations() const;
double get_current_accuracy() const;
void set_max_iterations(unsigned); ///< set maximum number of iterations
protected:
unsigned get_iteration() const; ///< get current iteration number
const Model<Two_scale>& get_model() const; ///< get model
const Model<Two_scale>& get_last_iteration_model() const; ///< get model state during last iteration
virtual double max_rel_diff() const = 0; ///< maximum relative difference to last iteration
virtual double rel_scale_difference() const; ///< relative scale difference
virtual double scale_difference() const; ///< absolute scale difference
virtual bool scale_has_changed() const; ///< returns true if scale has changed
private:
Model<Two_scale>* model; ///< pointer to model
Model<Two_scale> last_iteration_model; ///< model state at last iteration
unsigned int it_count; ///< iteration
unsigned int max_it; ///< maximum number of iterations
double accuracy_goal; ///< accuracy goal
double current_accuracy; ///< current accuracy
};
template <template<class Method> class Model>
Convergence_tester_DRbar<Model<Two_scale> >::Convergence_tester_DRbar
(Model<Two_scale>* model_, double accuracy_goal_)
: Convergence_tester<Two_scale>()
, model(model_)
, last_iteration_model()
, it_count(0)
, max_it(static_cast<int>(-log10(accuracy_goal_) * 10))
, accuracy_goal(accuracy_goal_)
, current_accuracy(std::numeric_limits<double>::infinity())
{
assert(model && "Error: Convergence_tester_DRbar<Model<Two_scale>>: "
"model pointer must not be zero!");
}
template <template<class Method> class Model>
Convergence_tester_DRbar<Model<Two_scale> >::~Convergence_tester_DRbar()
{
}
template <template<class Method> class Model>
bool Convergence_tester_DRbar<Model<Two_scale> >::accuracy_goal_reached()
{
bool precision_reached;
if (it_count == 0) {
// this is the first run => no comparison possible => assume
// that accuracy goal has not been reached
precision_reached = false;
} else {
const double scale_accuracy_goal = accuracy_goal * 16*M_PI*M_PI;
if (rel_scale_difference() < scale_accuracy_goal) {
current_accuracy = max_rel_diff();
precision_reached = current_accuracy < accuracy_goal;
VERBOSE_MSG("Convergence_tester_DRbar: current accuracy = "
<< current_accuracy
<< ", accuracy goal = " << accuracy_goal);
} else {
precision_reached = false;
VERBOSE_MSG("scale has changed by " << scale_difference()
<< " GeV (" << rel_scale_difference()
<< "), skipping parameter comparison");
}
}
// save old model parameters
last_iteration_model = *model;
++it_count;
return precision_reached;
}
template <template<class Method> class Model>
double Convergence_tester_DRbar<Model<Two_scale> >::get_accuracy_goal() const
{
return accuracy_goal;
}
template <template<class Method> class Model>
double Convergence_tester_DRbar<Model<Two_scale> >::get_current_accuracy() const
{
return current_accuracy;
}
template <template<class Method> class Model>
unsigned Convergence_tester_DRbar<Model<Two_scale> >::get_iteration() const
{
return it_count;
}
template <template<class Method> class Model>
const Model<Two_scale>&
Convergence_tester_DRbar<Model<Two_scale> >::get_model() const
{
return *model;
}
template <template<class Method> class Model>
const Model<Two_scale>&
Convergence_tester_DRbar<Model<Two_scale> >::get_last_iteration_model() const
{
return last_iteration_model;
}
template <template<class Method> class Model>
void Convergence_tester_DRbar<Model<Two_scale> >::set_max_iterations
(unsigned max_it_)
{
max_it = max_it_;
}
template <template<class Method> class Model>
unsigned int Convergence_tester_DRbar<Model<Two_scale> >::max_iterations()
const
{
return max_it;
}
template <template<class Method> class Model>
bool Convergence_tester_DRbar<Model<Two_scale> >::scale_has_changed() const
{
return !is_zero(scale_difference());
}
template <template<class Method> class Model>
double Convergence_tester_DRbar<Model<Two_scale> >::scale_difference() const
{
return model->get_scale() - last_iteration_model.get_scale();
}
template <template<class Method> class Model>
double Convergence_tester_DRbar<Model<Two_scale> >::rel_scale_difference()
const
{
const double diff = scale_difference();
const double last_scale = last_iteration_model.get_scale();
if (!is_zero(last_scale))
return diff / last_scale;
return std::numeric_limits<double>::infinity();
}
} // namespace flexiblesusy
#endif
| 33.145946 | 103 | 0.721624 | [
"model"
] |
4273fb6a36a11329f90bc269364a36fb548f8df4 | 6,890 | cpp | C++ | SFUI/Source/UI/Widgets/PreloaderBox.cpp | JayhawkZombie/SFUI | 2870aab39deacb1a0be41d414d7d9d2349bdd17b | [
"MIT"
] | 1 | 2019-04-30T23:38:05.000Z | 2019-04-30T23:38:05.000Z | SFUI/Source/UI/Widgets/PreloaderBox.cpp | JayhawkZombie/SFUI | 2870aab39deacb1a0be41d414d7d9d2349bdd17b | [
"MIT"
] | null | null | null | SFUI/Source/UI/Widgets/PreloaderBox.cpp | JayhawkZombie/SFUI | 2870aab39deacb1a0be41d414d7d9d2349bdd17b | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////
//
// MIT License
//
// Copyright(c) 2017 Kurt Slagle - kurt_slagle@yahoo.com
//
// 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.
//
// 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 of the software used is required.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Internal Headers
////////////////////////////////////////////////////////////
#include <SFUI/Include/UI/Widgets/PreloaderBox.h>
#include <SFUI/Include/UI/Widgets/Preloader.h>
////////////////////////////////////////////////////////////
// Dependency Headers
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Standard Library Headers
////////////////////////////////////////////////////////////
namespace sfui
{
PreloaderBox::PreloaderBox(optional<Theme*> theme /* = {} */, optional<Widget*> parent /* = {} */)
: Widget(theme, parent)
{
}
PreloaderBox::~PreloaderBox()
{
}
PreloaderBox::shared_ptr PreloaderBox::Create(optional<Theme*> theme /* = {} */, optional<Widget*> parent /* = {} */)
{
return std::make_shared<PreloaderBox>(theme, parent);
}
void PreloaderBox::Update()
{
if (m_State == State::Hidden)
return;
m_SeqTimer.Update();
}
void PreloaderBox::Render(sf::RenderTarget &Target)
{
if (m_State != State::Hidden && m_State != State::Delayed)
Target.draw(m_BackgroundRect);
}
void PreloaderBox::SetPosition(const Vec2i &Position)
{
super::SetPosition(Position);
}
void PreloaderBox::SetSize(const Vec2i &Size)
{
super::SetSize(Size);
}
void PreloaderBox::SetSpawnPosition(const Vec2i &Position)
{
m_SpawnPosition = Position;
}
void PreloaderBox::SetStopPosition(const Vec2i &Position)
{
m_SitPosition = Position;
}
void PreloaderBox::SetDespawnPosition(const Vec2i &Position)
{
m_DespawnPosition = Position;
}
void PreloaderBox::Start(uint32 DurationToSpawn, uint32 DurationToSit, uint32 DurationToDespawn, uint32 Delay)
{
m_SpawnDuration.setFromMilliseconds(DurationToSpawn);
m_SitDuration.setFromMilliseconds(DurationToSit);
m_DespawnDuration.setFromMilliseconds(DurationToDespawn);
m_DelayDuration.setFromMilliseconds(Delay);
m_IsDone = false;
SetPosition(m_SpawnPosition);
m_SeqTimer.AddSequences(
[ ]() { }, [ ]() { }, [this]() { Finished(); },
{
{ /* Delay sequence node */ Delay, [this]() { StartDelay(); }, /* No update */ [ ]() { }, /* No end cb */ [ ]() { } },
{ /* Spawn sequence node */ DurationToSpawn, [this]() { StartSpawn(); }, /* No update */ [ ]() { }, /* No end cb */ [this]() { UpdateSpawn(); } },
{ /* Sit sequence node */ DurationToSit, [this]() { StartSit(); }, /* No update */ [ ]() { }, /* No end cb */ [ ]() { } },
{ /* Despawn seq node */ DurationToDespawn, [this]() { StartDesapwn(); }, /* No update */ [ ]() { }, /* No end cb */ [this]() { UpdateDespawn(); } }
}
);
m_SeqTimer.Start();
}
void PreloaderBox::Pause()
{
m_Timer.pause();
}
void PreloaderBox::Stop()
{
Finished();
}
void PreloaderBox::Restart()
{
m_State = State::Delayed;
m_Timer.setTime(m_DelayDuration);
m_Timer.start();
}
void PreloaderBox::Resume()
{
m_Timer.resume();
}
bool PreloaderBox::IsDone() const
{
return m_IsDone;
}
void PreloaderBox::OnFinished(boost::function<void()> func)
{
m_FinishedSignal.connect(func);
}
void PreloaderBox::StartDelay()
{
m_State = State::Delayed;
}
void PreloaderBox::StartSpawn()
{
m_State = State::Spawning;
m_Timer.stop();
m_Timer.setTime(m_SpawnDuration);
m_Timer.start();
Color bgC = m_BackgroundRect.getFillColor();
bgC.a = 0;
m_BackgroundRect.setFillColor(bgC);
m_Animator.Animate(
WidgetAnimation::SlideIn,
m_SpawnPosition,
m_SitPosition,
Easing::Accelerate,
( uint32 )m_SpawnDuration.asMilliseconds()
);
}
void PreloaderBox::StartSit()
{
m_State = State::Sitting;
m_Timer.stop();
m_Timer.setTime(m_SitDuration);
m_Timer.start();
m_Animator.Stop();
Color bgC = m_BackgroundRect.getFillColor();
bgC.a = 255;
m_BackgroundRect.setFillColor(bgC);
SetPosition(m_SitPosition);
}
void PreloaderBox::StartDesapwn()
{
m_State = State::Despawning;
m_Timer.stop();
m_Timer.setTime(m_DespawnDuration);
m_Timer.start();
m_Animator.Animate(
WidgetAnimation::SlideIn,
m_SitPosition,
m_DespawnPosition,
Easing::Accelerate,
( uint32 )m_DespawnDuration.asMilliseconds()
);
}
void PreloaderBox::Finished()
{
m_State = State::Hidden;
m_SeqTimer.Clear();
Color bgC = m_BackgroundRect.getFillColor();
bgC.a = 255;
m_BackgroundRect.setFillColor(bgC);
m_IsDone = true;
m_FinishedSignal();
}
void PreloaderBox::UpdateSpawn()
{
Color bgC = m_BackgroundRect.getFillColor();
auto totTime = m_Timer.getTime();
float perc = cast_float(totTime.asMilliseconds()) / cast_float(m_SpawnDuration.asMilliseconds());
bgC.a = static_cast< sf::Uint8 >( ceil(255 * ( 1.f - perc )) );
m_BackgroundRect.setFillColor(bgC);
}
void PreloaderBox::UpdateDespawn()
{
Color bgC = m_BackgroundRect.getFillColor();
auto totTime = m_Timer.getTime();
float perc = cast_float(totTime.asMilliseconds()) / cast_float(m_DespawnDuration.asMilliseconds());
bgC.a = static_cast< sf::Uint8 >( ceil(255 * perc) );
m_BackgroundRect.setFillColor(bgC);
}
}
| 28.708333 | 159 | 0.615385 | [
"render"
] |
4278ee553208025038bfbfd23d93290943d43be6 | 373 | cpp | C++ | 62.unique-paths.159521632.ac.cpp | blossom2017/Leetcode | 8bcfc2d5eeb344a1489b0d84a9a81a9f5d61281b | [
"Apache-2.0"
] | null | null | null | 62.unique-paths.159521632.ac.cpp | blossom2017/Leetcode | 8bcfc2d5eeb344a1489b0d84a9a81a9f5d61281b | [
"Apache-2.0"
] | null | null | null | 62.unique-paths.159521632.ac.cpp | blossom2017/Leetcode | 8bcfc2d5eeb344a1489b0d84a9a81a9f5d61281b | [
"Apache-2.0"
] | null | null | null | class Solution {
public:
int uniquePaths(int m, int n) {
vector<vector<int>> paths(m,vector<int> (n));
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(i==0||j==0)paths[i][j]=1;
else paths[i][j]=paths[i-1][j]+paths[i][j-1];
}
}
return paths[m-1][n-1];
}
};
| 23.3125 | 61 | 0.402145 | [
"vector"
] |
42802cdc6cf956ea1a5085f311789b925c46241c | 985 | cpp | C++ | GameEngine/MeshComponent.cpp | laura-96/GameEngine | 9bf5be938e8899d6a083041dae8b52737293f534 | [
"MIT"
] | null | null | null | GameEngine/MeshComponent.cpp | laura-96/GameEngine | 9bf5be938e8899d6a083041dae8b52737293f534 | [
"MIT"
] | null | null | null | GameEngine/MeshComponent.cpp | laura-96/GameEngine | 9bf5be938e8899d6a083041dae8b52737293f534 | [
"MIT"
] | null | null | null | #include "MeshComponent.h"
#include "GameObject.h"
#include "MaterialComponent.h"
#include "TransformComponent.h"
#include "glmath.h"
#include "Geometry.h"
#include "MeshResource.h"
void MeshComponent::Clear()
{
std::vector<GameObject*>::iterator go_res = mesh_res->gos_related.begin();
while (go_res != mesh_res->gos_related.end())
{
if ((*go_res) == this->GO_belong)
{
mesh_res->gos_related.erase(go_res);
break;
}
go_res++;
}
mesh_res = nullptr;
delete this;
}
MeshComponent::MeshComponent(GameObject* _GO_belong, MeshResource* mesh_resource)
{
Component(ComponentType::Mesh, _GO_belong);
mesh_res = mesh_resource;
//mesh_box.SetNegativeInfinity();
mesh_box.Enclose((math::float3*)mesh_resource->vertices, mesh_resource->num_vertex);
}
void MeshComponent::SetResource(MeshResource* new_mesh_res)
{
mesh_res = new_mesh_res;
//mesh_box.SetNegativeInfinity();
mesh_box.Enclose((math::float3*)new_mesh_res->vertices, new_mesh_res->num_vertex);
}
| 20.520833 | 85 | 0.740102 | [
"mesh",
"geometry",
"vector"
] |
428759d56cef9178f4413739305297353f049aa4 | 2,193 | cc | C++ | src/3d/mpi/grid_func.cc | cedar-framework/cedar | 9fb53ec221738b8dd16dfb31dc9a18d69fc2cc44 | [
"BSD-3-Clause"
] | 9 | 2018-03-07T19:15:27.000Z | 2019-02-22T20:10:23.000Z | src/3d/mpi/grid_func.cc | cedar-framework/cedar | 9fb53ec221738b8dd16dfb31dc9a18d69fc2cc44 | [
"BSD-3-Clause"
] | 5 | 2018-11-13T19:59:46.000Z | 2020-04-09T19:31:25.000Z | src/3d/mpi/grid_func.cc | cedar-framework/cedar | 9fb53ec221738b8dd16dfb31dc9a18d69fc2cc44 | [
"BSD-3-Clause"
] | 2 | 2018-07-20T01:06:48.000Z | 2019-11-25T12:15:16.000Z | #include <cedar/3d/mpi/grid_func.h>
using namespace cedar::cdr3::mpi;
grid_func::grid_func(topo_ptr grid) :
::cedar::cdr3::grid_func(grid->nlocal(0)-2, grid->nlocal(1)-2, grid->nlocal(2) - 2),
par_object(grid, grid->comm) {}
grid_func::grid_func(real_t *ext_data, topo_ptr grid) :
::cedar::cdr3::grid_func(ext_data, grid->nlocal(0)-2, grid->nlocal(1)-2, grid->nlocal(2) - 2),
par_object(grid, grid->comm) {}
grid_func::grid_func(len_t nx, len_t ny, len_t nz) : ::cedar::cdr3::grid_func(nx,ny,nz)
{}
grid_func grid_func::zeros(topo_ptr grid)
{
grid_func ret(grid);
ret.set(0.0);
return ret;
}
grid_func grid_func::ones(topo_ptr grid)
{
grid_func ret(grid);
ret.set(1.0);
return ret;
}
grid_func grid_func::like(const grid_func &likeable)
{
grid_func ret(likeable.grid_ptr());
return ret;
}
grid_func grid_func::zeros_like(const grid_func &like)
{
grid_func ret(like.grid_ptr());
ret.set(0.0);
return ret;
}
grid_func grid_func::ones_like(const grid_func &like)
{
grid_func ret(like.grid_ptr());
ret.set(1.0);
return ret;
}
grid_func & grid_func::operator-=(const grid_func &rhs)
{
for (auto k : this->range(2)) {
for (auto j: this->range(1)) {
for (auto i: this->range(0)) {
(*this)(i,j,k) -= rhs(i,j,k);
}
}
}
return *this;
}
cedar::real_t grid_func::inf_norm() const
{
auto mval = cdr3::grid_func::inf_norm();
MPI_Allreduce(MPI_IN_PLACE, &mval, 1, MPI_DOUBLE, MPI_MAX, grid_->comm);
return mval;
}
namespace cedar { namespace cdr3 { namespace mpi {
std::ostream & operator<< (std::ostream &os, const grid_func & obj)
{
auto & topo = obj.grid();
auto iGs = topo.is(0);
auto jGs = topo.is(1);
auto kGs = topo.is(2);
auto NGx = topo.nglobal(0);
auto NGy = topo.nglobal(1);
unsigned int width = 4;
os << std::setprecision(7);
for (auto k : obj.range(2)) {
for (auto j: obj.range(1)) {
for (auto i: obj.range(0)) {
os << std::setw(width) << (kGs+k-2)*NGx*NGy + (jGs+j-2)*NGx + iGs+i-2 << ", "
<< std::setw(width) << iGs + i << ", " << std::setw(width) << jGs + j << ", "
<< std::setw(width) << kGs + k << ", "
<< std::scientific << obj(i,j,k) << '\n';
}
}
}
return os;
}
}}}
| 18.74359 | 95 | 0.623803 | [
"3d"
] |
4291b814b4cd5b51261ccb0f7365f897db273dd9 | 389 | cpp | C++ | vox.render/runtime/shader/shader_property.cpp | yangfengzzz/DigitalVox3 | c3277007d7cae90cf3f55930bf86119c93662493 | [
"MIT"
] | 28 | 2021-11-23T11:52:55.000Z | 2022-03-04T01:48:52.000Z | vox.render/runtime/shader/shader_property.cpp | yangfengzzz/DigitalVox3 | c3277007d7cae90cf3f55930bf86119c93662493 | [
"MIT"
] | null | null | null | vox.render/runtime/shader/shader_property.cpp | yangfengzzz/DigitalVox3 | c3277007d7cae90cf3f55930bf86119c93662493 | [
"MIT"
] | 3 | 2022-01-02T12:23:04.000Z | 2022-01-07T04:21:26.000Z | //
// shader_property.cpp
// vox.render
//
// Created by 杨丰 on 2021/11/27.
//
#include "shader_property.h"
namespace vox {
int ShaderProperty::_propertyNameCounter = 0;
ShaderProperty::ShaderProperty(const std::string &name, ShaderDataGroup::Enum group) :
name(name),
group(group),
uniqueId(ShaderProperty::_propertyNameCounter) {
ShaderProperty::_propertyNameCounter += 1;
}
}
| 18.52381 | 86 | 0.735219 | [
"render"
] |
429bb8ec02a23d19a9bda2dc78d9d49b722b17f9 | 11,015 | cpp | C++ | Code/CommonFiles/src/FuzzyLite/DescriptiveAntecedent.cpp | P4ALLcerthiti/P4ALL_FallDetection | f3fcab26d66f4d36ddca4ba69262022e289a128b | [
"BSD-3-Clause"
] | 2 | 2017-08-28T21:12:40.000Z | 2021-02-20T06:58:19.000Z | Code/CommonFiles/src/FuzzyLite/DescriptiveAntecedent.cpp | P4ALLcerthiti/P4ALL_Fall_Detection_Web_Services | 4d2b4fc4ed326d0ebfb3934ac88f13b78433af7a | [
"BSD-3-Clause"
] | null | null | null | Code/CommonFiles/src/FuzzyLite/DescriptiveAntecedent.cpp | P4ALLcerthiti/P4ALL_Fall_Detection_Web_Services | 4d2b4fc4ed326d0ebfb3934ac88f13b78433af7a | [
"BSD-3-Clause"
] | null | null | null | /* Copyright 2010 Juan Rada-Vilela
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 "stdafx.h"
#include "DescriptiveAntecedent.h"
#include "StrOp.h"
#include <stack>
#include "FuzzyRule.h"
namespace fl {
DescriptiveAntecedent::DescriptiveAntecedent() : FuzzyAntecedent(),
_left(NULL), _right(NULL), _operation(O_NONE), _term(NULL) {
}
DescriptiveAntecedent::DescriptiveAntecedent(const FuzzyOperator& fuzzy_op) :
FuzzyAntecedent(fuzzy_op), _left(NULL), _right(NULL), _operation(O_NONE),
_term(NULL) {
}
DescriptiveAntecedent::~DescriptiveAntecedent() {
if (_left) {
delete _left;
}
if (_right) {
delete _right;
}
}
void DescriptiveAntecedent::setLeft(DescriptiveAntecedent* l_antecedent) {
this->_left = l_antecedent;
}
DescriptiveAntecedent* DescriptiveAntecedent::left() const {
return this->_left;
}
void DescriptiveAntecedent::setRight(DescriptiveAntecedent* r_antecedent) {
this->_right = r_antecedent;
}
DescriptiveAntecedent* DescriptiveAntecedent::right() const {
return this->_right;
}
void DescriptiveAntecedent::setOperation(OPERATION operation) {
this->_operation = operation;
}
DescriptiveAntecedent::OPERATION DescriptiveAntecedent::operation() const {
return this->_operation;
}
void DescriptiveAntecedent::addHedge(Hedge* hedge) {
this->_hedges.push_back(hedge);
}
int DescriptiveAntecedent::numberOfHedges() const {
return this->_hedges.size();
}
Hedge* DescriptiveAntecedent::hedge(int index) const {
return this->_hedges[index];
}
void DescriptiveAntecedent::setTerm(const LinguisticTerm* term) {
this->_term = term;
}
const LinguisticTerm* DescriptiveAntecedent::term() const {
return this->_term;
}
bool DescriptiveAntecedent::isTerminal() const {
return operation() == O_NONE;
}
flScalar DescriptiveAntecedent::degreeOfTruth() const {
if (!isTerminal()) {
if (left() == NULL || right() == NULL) {
throw NullPointerException(FL_AT, toString());
}
switch (operation()) {
case O_AND:
return fuzzyOperator().tnorm().execute(left()->degreeOfTruth(),
right()->degreeOfTruth());
case O_OR:
return fuzzyOperator().snorm().execute(left()->degreeOfTruth(),
right()->degreeOfTruth());
default:
throw InvalidArgumentException(FL_AT, "Operation " + StrOp::IntToString(operation()) + " not available");
}
}
flScalar result = term()->membership(inputLVar()->input());
for (int i = 0; i < numberOfHedges(); ++i) {
result = hedge(i)->hedge(result);
}
return result;
}
std::string DescriptiveAntecedent::toString() const {
std::stringstream ss;
if (isTerminal()) {
ss << inputLVar()->name() + " " + FuzzyRule::FR_IS + " ";
for (int i = 0; i < numberOfHedges(); ++i) {
ss << hedge(i)->name() << " ";
}
ss << term()->name();
} else {
ss << " ( " + (left() ? left()->toString() : "NULL");
ss << " " + (operation() == O_AND ? FuzzyRule::FR_AND : FuzzyRule::FR_OR);
ss << " " + (right() ? right()->toString() : "NULL") + " ) ";
}
return ss.str();
}
void DescriptiveAntecedent::parse(const std::string& antecedent,
const FuzzyEngine& engine) throw (ParsingException) {
enum e_state {
//e.g. Posfix antecedent: Energy is LOW Distance is FAR_AWAY and
S_LVAR = 1, S_IS, S_HEDGE, S_TERM, S_OPERATOR
};
e_state current_state = S_LVAR;
std::string postfix_antecedent = InfixToPostfix(antecedent);
std::stringstream ss(postfix_antecedent);
std::string token;
InputLVar* input = NULL;
std::vector<Hedge*> hedges;
Hedge* hedge = NULL;
LinguisticTerm* term = NULL;
std::stack<DescriptiveAntecedent*> f_antecedents;
DescriptiveAntecedent* tmp_antecedent = NULL;
// <editor-fold desc="State Machine">
while (ss >> token) {
switch (current_state) {
//e.g.Postfix: Energy is LOW Distance is FAR_AWAY and. After term follows Operator or LVar
case S_LVAR:
case S_OPERATOR:
input = engine.inputLVar(token);
if (input) {
current_state = S_IS;
break;
}
if (token != FuzzyRule::FR_AND && token != FuzzyRule::FR_OR) {
//if it is not and InputLVar and not an Operator then exception
throw ParsingException(FL_AT, "Input variable <" +
token + "> not registered in fuzzy engine");
// throw RuleParsingException(FL_AT,
// "Operator expected but found <" + token +
// ">. Antecedent: " + antecedent);
}
//A is a B is b and
if (isTerminal()) {
setLeft(f_antecedents.top());
f_antecedents.pop();
setRight(f_antecedents.top());
f_antecedents.pop();
setOperation(token == FuzzyRule::FR_AND ? DescriptiveAntecedent::O_AND :
DescriptiveAntecedent::O_OR); //I am not terminal anymore
} else {
setLeft(new DescriptiveAntecedent(*this));
setRight(f_antecedents.top());
f_antecedents.pop();
setOperation(token == FuzzyRule::FR_AND ? DescriptiveAntecedent::O_AND :
DescriptiveAntecedent::O_OR); //I am not terminal anymore
}
break;
case S_IS:
if (token == FuzzyRule::FR_IS) {
current_state = S_HEDGE;
} else {
throw ParsingException(FL_AT, "<is> expected but found <" +
token + ">");
}
break;
case S_HEDGE:
hedge = engine.hedgeSet().get(token);
if (hedge) {
hedges.push_back(hedge); //And check for more hedges
break;
}
//intentional fall-through in case there are no hedges
case S_TERM:
term = input->term(token);
if (!term) {
throw ParsingException(FL_AT, "Term <" + token +
"> not found in input variable <" + input->name() +
">");
}
current_state = S_OPERATOR;
tmp_antecedent = new DescriptiveAntecedent(engine.fuzzyOperator());
tmp_antecedent->setInputLVar(input);
tmp_antecedent->setTerm(term);
for (size_t i = 0; i < hedges.size(); ++i) {
tmp_antecedent->addHedge(hedges[i]);
}
f_antecedents.push(tmp_antecedent);
tmp_antecedent = NULL;
hedges.clear();
break;
}
}
//</editor-fold>
if (!f_antecedents.empty()) { //e.g. Rule: if A is a then X is x (one antecedent only)
FL_ASSERT(f_antecedents.size() == 1);
DescriptiveAntecedent* me = f_antecedents.top();
setInputLVar(me->inputLVar());
for (int i = 0; i < me->numberOfHedges(); ++i) {
addHedge(me->hedge(i));
}
setTerm(me->term());
delete me;
}
}
std::string DescriptiveAntecedent::Preprocess(const std::string& infix) {
std::string result;
for (size_t i = 0; i < infix.size(); ++i) {
if (infix[i] == '(') {
result += " ( ";
} else if (infix[i] == ')') {
result += " ) ";
} else {
result += infix[i];
}
}
return result;
}
std::string DescriptiveAntecedent::InfixToPostfix(const std::string& infix) {
std::string p_infix = Preprocess(infix);
std::stringstream ss(p_infix);
std::string token;
std::string tmp;
std::string result;
std::stack<std::string> stack;
while (ss >> token) {
if (token == "(") {
stack.push(token);
} else if (token == ")") {
FL_ASSERT(!stack.empty());
tmp = stack.top();
stack.pop();
while (tmp != "(") {
result += tmp + " ";
FL_ASSERT(!stack.empty());
tmp = stack.top();
stack.pop();
}
} else if (token == FuzzyRule::FR_AND || token == FuzzyRule::FR_OR) {
if (stack.empty()) {
stack.push(token);
} else {
FL_ASSERT(!stack.empty())
tmp = stack.top();
stack.pop();
while (tmp != FuzzyRule::FR_AND && tmp != FuzzyRule::FR_OR && tmp != "(") {
result += tmp + " ";
FL_ASSERT(!stack.empty())
tmp = stack.top();
stack.pop();
}
stack.push(tmp);
stack.push(token);
}
} else {
result += token + " ";
}
}
while (!stack.empty()) {
FL_ASSERT(!stack.empty())
token = stack.top();
stack.pop();
result += token + " ";
}
return result;
}
}
| 36.839465 | 125 | 0.486791 | [
"vector"
] |
429c898f01a73345bdc851d1ef63c2c215f25ac9 | 3,850 | cpp | C++ | test/BaseTestEntityWithSources.cpp | stoewer/nix | 7fe4669284b60b6a27228c2da7d3f61a77c943dc | [
"BSD-3-Clause"
] | 53 | 2015-02-10T01:04:34.000Z | 2021-04-24T14:26:04.000Z | test/BaseTestEntityWithSources.cpp | stoewer/nix | 7fe4669284b60b6a27228c2da7d3f61a77c943dc | [
"BSD-3-Clause"
] | 262 | 2015-01-09T13:24:21.000Z | 2021-07-02T13:45:31.000Z | test/BaseTestEntityWithSources.cpp | gicmo/nix | 17a5b90e6c12a22e921c181b79eb2a3db1bf61af | [
"BSD-3-Clause"
] | 34 | 2015-03-27T16:41:14.000Z | 2020-03-27T06:47:59.000Z | // Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include "BaseTestEntityWithSources.hpp"
#include <iterator>
#include <random>
#include <algorithm>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>
#include <cppunit/TestRunner.h>
#include <cppunit/BriefTestProgressListener.h>
using namespace nix;
void BaseTestEntityWithSources::testSourceAccess() {
std::vector<std::string> names = { "source_a", "source_b", "source_c", "source_d", "source_e" };
CPPUNIT_ASSERT(block.sourceCount() == 0);
CPPUNIT_ASSERT(block.sources().size() == 0);
std::vector<std::string> ids;
for (auto it = names.begin(); it != names.end(); it++) {
Source src = block.createSource(*it, "channel");
CPPUNIT_ASSERT(src.name() == *it);
ids.push_back(src.id());
}
std::string name = names[0];
Source source = block.getSource(name);
CPPUNIT_ASSERT(source.name() == name);
CPPUNIT_ASSERT(block.sourceCount() == names.size());
CPPUNIT_ASSERT(block.sources().size() == names.size());
for (auto it = ids.begin(); it != ids.end(); it++) {
Source src = block.getSource(*it);
CPPUNIT_ASSERT(block.hasSource(*it) == true);
CPPUNIT_ASSERT(src.id() == *it);
block.deleteSource(*it);
}
CPPUNIT_ASSERT(block.sourceCount() == 0);
CPPUNIT_ASSERT(block.sources().size() == 0);
}
void BaseTestEntityWithSources::testSourceVectorSetter() {
std::vector<std::string> names = { "source_a", "source_b", "source_c", "source_d", "source_e" };
std::vector<Source> sources;
DataArray da = block.createDataArray("Test","test", nix::DataType::Double, nix::NDSize {0,0});
for (auto it = names.begin(); it != names.end(); it++) {
sources.push_back(block.createSource(*it, "channel"));
}
CPPUNIT_ASSERT(block.sourceCount() == sources.size());
CPPUNIT_ASSERT(da.sourceCount() == 0);
da.addSource(sources[0]);
da.addSource(sources[1]);
CPPUNIT_ASSERT(da.sourceCount() == 2);
da.sources(sources);
CPPUNIT_ASSERT(da.sourceCount() == sources.size());
sources.clear();
sources.push_back(block.createSource("source_f", "channel"));
sources.push_back(block.createSource("source_g", "channel"));
da.sources(sources);
CPPUNIT_ASSERT(da.sourceCount() == sources.size());
CPPUNIT_ASSERT(block.sourceCount() == (sources.size() + names.size()));
CPPUNIT_ASSERT_THROW(da.addSource(""), EmptyString);
std::vector<Source> deleter;
da.sources(deleter);
CPPUNIT_ASSERT(da.sourceCount() == 0);
}
void BaseTestEntityWithSources::testSourceOrder() {
std::vector<std::string> names = { "source_a", "source_b", "source_c", "source_d", "source_e" };
std::vector<Source> sources;
Group append_group = block.createGroup("ag", "test");
Group set_group = block.createGroup("sg", "test");
std::random_device rd;
std::mt19937 gen(rd());
std::shuffle(names.begin(), names.end(), gen);
for (auto it = names.begin(); it != names.end(); it++) {
sources.push_back(block.createSource(*it, "channel"));
}
// append each source in order
for (auto src : block.sources()) {
append_group.addSource(src);
}
// use the vector setter
set_group.sources(sources);
for (size_t idx = 0; idx < sources.size(); ++idx) {
CPPUNIT_ASSERT(sources[idx].name() == append_group.getSource(idx).name());
CPPUNIT_ASSERT(sources[idx].name() == set_group.getSource(idx).name());
}
sources.clear();
}
| 32.352941 | 100 | 0.654545 | [
"vector"
] |
42a2919b59f3401c1e071f39cfbe6d82738d1db7 | 1,589 | cpp | C++ | src/Cecilion/Renderer/Shader.cpp | robdan7/Cecilion | 7282dc32ee9f9cde13e1e75e817b04714285d82a | [
"MIT"
] | null | null | null | src/Cecilion/Renderer/Shader.cpp | robdan7/Cecilion | 7282dc32ee9f9cde13e1e75e817b04714285d82a | [
"MIT"
] | 3 | 2020-06-12T16:33:45.000Z | 2020-07-07T08:40:50.000Z | src/Cecilion/Renderer/Shader.cpp | robdan7/Cecilion | 7282dc32ee9f9cde13e1e75e817b04714285d82a | [
"MIT"
] | null | null | null | #include <Platform/OpenGL/GL_shader.h>
#include "Renderer.h"
namespace Cecilion {
std::shared_ptr<Shader_stage> Shader::create_shader_stage(const uint32_t shader_type, const std::string&& shader_source) {
switch(Renderer::get_API()) {
case Renderer_API::API::None:
CORE_ASSERT(false, "Cecilion::Shader:: No render API is defined!");
break;
case Renderer_API::API::OpenGL:
return std::make_shared<GL_shader_stage>(shader_type, std::move(shader_source));
break;
}
return nullptr;
}
std::shared_ptr<Shader> Shader::create_shader(const std::initializer_list<std::shared_ptr<Shader_stage>> elements) {
switch (Renderer::get_API()) {
case Renderer_API::API::None:
CORE_ASSERT(false, "Cecilion::Shader:: No render API is defined!");
break;
case Renderer_API::API::OpenGL:
return std::make_shared<GL_shader>(std::move(elements));
break;
}
return nullptr;
}
std::shared_ptr<Shader> Shader::load_binary_shader(uint32_t binary_format, const char *binary, uint32_t size) {
switch (Renderer::get_API()) {
case Renderer_API::API::None:
CORE_ASSERT(false, "Cecilion::Shader:: No render API is defined!");
break;
case Renderer_API::API::OpenGL:
return std::make_shared<GL_shader>(binary_format, binary, size);
break;
}
return nullptr;
}
}
| 36.113636 | 126 | 0.590938 | [
"render"
] |
42a96cf86f91a8874e03a7845c62c1c1480b90b4 | 1,478 | cpp | C++ | Algorithms/1019.NextGreaterNodeInLinkedList/solution.cpp | stdstring/leetcode | 84e6bade7d6fc1a737eb6796cb4e2565440db5e3 | [
"MIT"
] | null | null | null | Algorithms/1019.NextGreaterNodeInLinkedList/solution.cpp | stdstring/leetcode | 84e6bade7d6fc1a737eb6796cb4e2565440db5e3 | [
"MIT"
] | null | null | null | Algorithms/1019.NextGreaterNodeInLinkedList/solution.cpp | stdstring/leetcode | 84e6bade7d6fc1a737eb6796cb4e2565440db5e3 | [
"MIT"
] | null | null | null | #include <stack>
#include <vector>
#include "ListNode.h"
#include "ListNodeUtils.h"
#include "gtest/gtest.h"
using CommonLib::ListNode;
namespace
{
class Solution
{
public:
std::vector<int> nextLargerNodes(ListNode* head) const
{
std::vector<int> result;
while (head != nullptr)
{
result.push_back(head->val);
head = head->next;
}
std::stack<int> nextGreaterNumberStack;
for (size_t index = 0; index < result.size(); ++index)
{
int current = result[result.size() - 1 - index];
while (!nextGreaterNumberStack.empty() && nextGreaterNumberStack.top() <= current)
nextGreaterNumberStack.pop();
result[result.size() - 1 - index] = nextGreaterNumberStack.empty() ? 0 : nextGreaterNumberStack.top();
nextGreaterNumberStack.push(current);
}
return result;
}
};
}
using CommonLib::createLinkedList;
namespace NextGreaterNodeInLinkedListTask
{
TEST(NextGreaterNodeInLinkedListTaskTests, Examples)
{
const Solution solution;
ASSERT_EQ(std::vector<int>({5, 5, 0}), solution.nextLargerNodes(createLinkedList({2, 1, 5}, true).get()));
ASSERT_EQ(std::vector<int>({7, 0, 5, 5, 0}), solution.nextLargerNodes(createLinkedList({2, 7, 4, 3, 5}, true).get()));
ASSERT_EQ(std::vector<int>({7, 9, 9, 9, 0, 5, 0, 0}), solution.nextLargerNodes(createLinkedList({1, 7, 5, 1, 9, 2, 5, 1}, true).get()));
}
} | 27.886792 | 140 | 0.624493 | [
"vector"
] |
42acde1b5ca80682441301b0cf4d0473a45d2704 | 6,369 | cc | C++ | filter-predicate_test.cc | gtaubman/doneyet | 9d9bf5355fdadf063e375a87c2799f2f0759c1e0 | [
"MIT"
] | 24 | 2015-08-07T04:39:49.000Z | 2022-02-15T05:43:38.000Z | filter-predicate_test.cc | gtaubman/doneyet | 9d9bf5355fdadf063e375a87c2799f2f0759c1e0 | [
"MIT"
] | 9 | 2017-02-20T12:39:25.000Z | 2019-09-19T12:15:09.000Z | filter-predicate_test.cc | gtaubman/doneyet | 9d9bf5355fdadf063e375a87c2799f2f0759c1e0 | [
"MIT"
] | 7 | 2016-11-26T18:27:47.000Z | 2021-12-08T20:24:04.000Z | #include "filter-predicate.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
static int errors = 0;
void ERROR(const string& error) {
cout << "ERROR: " << error << endl;
;
++errors;
}
class TestObj {
public:
TestObj(int val) { val_ = val; }
int Val() { return val_; }
static int ValWrapper(TestObj* t) { return t->Val(); }
bool Alive() { return val_; }
static bool AliveWrapper(TestObj* t) { return t->Alive(); }
void SetStr(string str) { str_ = str; }
string Str() { return str_; }
static string StrWrapper(TestObj* t) { return t->Str(); }
private:
int val_;
string str_;
};
bool TestBooleanFilterPredicate() {
bool success = true;
cout << "Testing BooleanFilterPredicate" << endl;
// Create test objects
vector<TestObj*> test_objects;
for (int i = 0; i < 20; ++i) {
test_objects.push_back(new TestObj(i));
}
BooleanFilterPredicate<TestObj> bfp(TestObj::AliveWrapper);
vector<TestObj*> filtered = bfp.FilterVector(test_objects);
for (int i = 0; i < filtered.size(); ++i) {
if (!filtered[i]->Alive()) {
ERROR("All filtered items should have Alive() == true.");
success = false;
}
}
for (int i = 0; i < test_objects.size(); ++i) {
delete test_objects[i];
}
return success;
}
bool TestGTFilterPredicate() {
bool success = true;
cout << "Testing GTFilterPredicate" << endl;
// Create test objects
vector<TestObj*> test_objects;
for (int i = 0; i < 20; ++i) {
test_objects.push_back(new TestObj(i));
}
// Create a GTFilterPredicate to keep any objects > 11.
int val = 11;
GTFilterPredicate<TestObj, int> gtfp(val, TestObj::ValWrapper);
vector<TestObj*> filtered = gtfp.FilterVector(test_objects);
for (int i = 0; i < filtered.size(); ++i) {
cout << "Filtered[" << i << "] = " << filtered[i]->Val() << endl;
if (filtered[i]->Val() <= val) {
ERROR("filtered[i] wasn't > val.");
success = false;
}
}
for (int i = 0; i < test_objects.size(); ++i) {
delete test_objects[i];
}
return success;
}
bool TestLTFilterPredicate() {
bool success = true;
cout << "Testing LTFilterPredicate" << endl;
// Create test objects
vector<TestObj*> test_objects;
for (int i = 0; i < 20; ++i) {
test_objects.push_back(new TestObj(i));
}
// Create a LTFilterPredicate to keep any objects < 6
int val = 6;
LTFilterPredicate<TestObj, int> ltfp(val, TestObj::ValWrapper);
vector<TestObj*> filtered = ltfp.FilterVector(test_objects);
for (int i = 0; i < filtered.size(); ++i) {
cout << "Filtered[" << i << "] = " << filtered[i]->Val() << endl;
if (filtered[i]->Val() >= val) {
ERROR("filtered[i] wasn't < val.");
success = false;
}
}
for (int i = 0; i < test_objects.size(); ++i) {
delete test_objects[i];
}
return success;
}
bool TestORFilterPredicate() {
bool success = true;
cout << "Testing OrFilterPredicate" << endl;
// Create test objects
vector<TestObj*> test_objects;
for (int i = 0; i < 20; ++i) {
test_objects.push_back(new TestObj(i));
}
// Create the OR filter:
OrFilterPredicate<TestObj> or_filter;
// Create two children:
int val1 = 11;
int val2 = 4;
GTFilterPredicate<TestObj, int>* gtfp =
new GTFilterPredicate<TestObj, int>(val1, TestObj::ValWrapper);
LTFilterPredicate<TestObj, int>* ltfp =
new LTFilterPredicate<TestObj, int>(val2, TestObj::ValWrapper);
or_filter.AddChild(gtfp);
or_filter.AddChild(ltfp);
vector<TestObj*> filtered = or_filter.FilterVector(test_objects);
for (int i = 0; i < filtered.size(); ++i) {
cout << "Filtered[" << i << "] = " << filtered[i]->Val() << endl;
if (filtered[i]->Val() <= val1 && filtered[i]->Val() >= val2) {
ERROR("Filtered[i] wasn't > val1 or < val2.");
success = false;
}
}
for (int i = 0; i < test_objects.size(); ++i) {
delete test_objects[i];
}
return success;
}
bool TestANDFilterPredicate() {
bool success = true;
cout << "Testing AndFilterPredicate" << endl;
// Create test objects
vector<TestObj*> test_objects;
for (int i = 0; i < 20; ++i) {
test_objects.push_back(new TestObj(i));
}
// Create the AND filter:
AndFilterPredicate<TestObj> and_filter;
// Create two children:
int val1 = 11;
int val2 = 4;
GTFilterPredicate<TestObj, int>* gtfp =
new GTFilterPredicate<TestObj, int>(val1, TestObj::ValWrapper);
GTFilterPredicate<TestObj, int>* gtfp2 =
new GTFilterPredicate<TestObj, int>(val2, TestObj::ValWrapper);
and_filter.AddChild(gtfp2);
and_filter.AddChild(gtfp);
vector<TestObj*> filtered = and_filter.FilterVector(test_objects);
for (int i = 0; i < filtered.size(); ++i) {
cout << "Filtered[" << i << "] = " << filtered[i]->Val() << endl;
if (!(filtered[i]->Val() > val1 && filtered[i]->Val() > val2)) {
ERROR("Filtered[i] wasn't > val1 and > val2.");
success = false;
}
}
for (int i = 0; i < test_objects.size(); ++i) {
delete test_objects[i];
}
return success;
}
bool TestStringContainsFilterPredicate() {
bool success = true;
cout << "Testing StringContainsFilterPredicate" << endl;
// Create test objects
vector<TestObj*> test_objects;
for (int i = 0; i < 20; ++i) {
test_objects.push_back(new TestObj(i));
}
test_objects[2]->SetStr("hi gabe");
test_objects[3]->SetStr("gabe is cool");
test_objects[10]->SetStr("gabe gabe gabe");
test_objects[11]->SetStr("doesn't have the good word.");
// Make the filter
StringContainsFilterPredicate<TestObj> filter(string("gabe"),
TestObj::StrWrapper);
vector<TestObj*> filtered = filter.FilterVector(test_objects);
for (int i = 0; i < filtered.size(); ++i) {
string str = filtered[i]->Str();
cout << "Filtered[" << i << "] = " << str << endl;
if (str.find("gabe") == string::npos) {
ERROR("Filtered[i] didn't contain \"gabe\"");
success = false;
}
}
assert(filtered.size() == 3);
return success;
}
bool RunTests() {
return TestBooleanFilterPredicate() && TestGTFilterPredicate() &&
TestLTFilterPredicate() && TestORFilterPredicate() &&
TestANDFilterPredicate() && TestStringContainsFilterPredicate();
}
int main() {
bool success = RunTests();
cout << errors << " errors." << endl;
return success;
}
| 26.987288 | 73 | 0.622076 | [
"vector"
] |
42ad1da96daf11f85c3229457ed1407b8cd91f17 | 1,382 | cpp | C++ | Two Best Non-Overlapping Events.cpp | chaitanyks/fuzzy-disco | bc52f779c68da3f259f116cc1f41c464db290fbf | [
"MIT"
] | 1 | 2021-12-12T05:55:44.000Z | 2021-12-12T05:55:44.000Z | Two Best Non-Overlapping Events.cpp | chaitanyks/fuzzy-disco | bc52f779c68da3f259f116cc1f41c464db290fbf | [
"MIT"
] | null | null | null | Two Best Non-Overlapping Events.cpp | chaitanyks/fuzzy-disco | bc52f779c68da3f259f116cc1f41c464db290fbf | [
"MIT"
] | null | null | null | class Solution {
public:
bool static custom(vector<int> &itr1, vector<int> &itr2) {
if (itr1[1] < itr2[1])
return true;
else
return false;
}
int bs(vector<vector<int>> &events, int low, int high, int start) {
if (low <= high) {
int mid = (low + high) / 2;
if (events[mid][1] < start) {
int val = bs(events, mid + 1, high, start);
if (val != -1)
return val;
else
return mid;
} else {
return bs(events, low, mid - 1, start);
}
}
return -1;
}
int maxTwoEvents(vector<vector<int>> &events) {
int n = events.size();
sort(events.begin(), events.end(), custom);
// int maxV[100005]={0};
vector<int> maxV(n, 0);
maxV[0] = events[0][2];
for (int i = 1; i < n; i++) {
maxV[i] = max(events[i][2], maxV[i - 1]);
// cout<<maxV[i]<<" ";
}
int ans = events[0][2];
for (int i = 1; i < n; i++) {
ans = max(ans, events[i][2]);
int val = bs(events, 0, i - 1, events[i][0]);
// cout<<i<<" "<<val<<endl;
if (val != -1)
ans = max(ans, events[i][2] + maxV[val]);
}
return ans;
}
};
| 26.576923 | 71 | 0.404486 | [
"vector"
] |
42afef2dfe0a60955fe602335becbe3af206fad2 | 2,877 | cpp | C++ | tools/random-tensor-gen/random-tensor-gen.cpp | NVlabs/data-orchestration | ad86e65fbd99bb7670700cab7c7031bf232c831f | [
"BSD-3-Clause"
] | 5 | 2019-04-13T02:00:35.000Z | 2019-07-22T18:23:25.000Z | tools/random-tensor-gen/random-tensor-gen.cpp | NVlabs/data-orchestration | ad86e65fbd99bb7670700cab7c7031bf232c831f | [
"BSD-3-Clause"
] | null | null | null | tools/random-tensor-gen/random-tensor-gen.cpp | NVlabs/data-orchestration | ad86e65fbd99bb7670700cab7c7031bf232c831f | [
"BSD-3-Clause"
] | 2 | 2019-06-23T18:14:21.000Z | 2019-12-29T02:34:33.000Z | /* Copyright (c) 2017, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 ``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 "whoop.hpp"
int main(int argc, char** argv)
{
std::vector<int> dim_sizes;
int seed = 1717;
int min_val = 0;
int max_val = 255;
int monotonically_increasing = 0;
whoop::AddOption(&dim_sizes, "dim_sizes,d", "List of dimension sizes, e.g. --dim_sizes 100 200 300");
whoop::AddOption(&seed, "seed,s", "Seed for random number generator.");
whoop::AddOption(&max_val, "max,x", "Maximum possible random number.");
whoop::AddOption(&min_val, "min,m", "Minimum possible random number.");
whoop::AddOption(&monotonically_increasing, "monotonic,mm", "Should the numbers monotonically increase?");
whoop::TensorOut output("output");
whoop::Init(argc, argv);
output.Resize(dim_sizes);
srand(seed);
whoop::T(0) << "Generating random tensor, seed: " << seed << whoop::EndT;
for (int x = dim_sizes.size() - 1; x >= 0; x--)
{
whoop::T(0) << " Dimension " << x << ", size: " << dim_sizes[dim_sizes.size() - x - 1] << whoop::EndT;
}
int size = output.PrimSize();
for (int x = 0; x < size; x++)
{
output.PrimAt(x) = (rand() % (max_val - min_val)) + min_val;
}
if (monotonically_increasing != 0)
{
for (int x = 1; x < size; x++)
{
output.PrimAt(x) += output.PrimAt(x-1);
}
}
whoop::Done();
}
| 39.410959 | 116 | 0.688217 | [
"vector"
] |
42b7c565955138fed0025be96d0f1911c1fec84e | 555 | cpp | C++ | Algorithm/BlankBoard/cpp/DFS&BFS/Subsets II.cpp | Daya-Jin/DataStructureAndAlgorithm | 212e53e255f103fcf0471bdf9422fd306f3745b5 | [
"MIT"
] | 3 | 2019-03-07T03:19:54.000Z | 2019-08-22T08:12:41.000Z | Algorithm/BlankBoard/cpp/DFS&BFS/Subsets II.cpp | Daya-Jin/DataStructureAndAlgorithm | 212e53e255f103fcf0471bdf9422fd306f3745b5 | [
"MIT"
] | null | null | null | Algorithm/BlankBoard/cpp/DFS&BFS/Subsets II.cpp | Daya-Jin/DataStructureAndAlgorithm | 212e53e255f103fcf0471bdf9422fd306f3745b5 | [
"MIT"
] | null | null | null | class Solution {
public:
void dfs(int idx, vector<int>& path, vector<vector<int>>& res, vector<int>& nums)
{
res.push_back(path);
if (idx == nums.size())
return;
for (int i = idx; i < nums.size(); i++)
{
if (i > idx && nums[i] == nums[i - 1])
continue;
else
path.push_back(nums[i]);
dfs(i + 1, path, res, nums);
path.pop_back();
}
}
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<int> path;
vector<vector<int>> res;
dfs(0, path, res, nums);
return res;
}
}; | 20.555556 | 82 | 0.581982 | [
"vector"
] |
42bc73025f958b7ec5ad3bed09c5d5bf3a9658e8 | 5,162 | cpp | C++ | ColorTribe/ColorLib_cpp/src/device/ediddata/NVGetEDID.cpp | mikrosimage/OpenDisplayCalib | a8cc37aa72d378faedc4a44171bcb29a20394432 | [
"BSD-3-Clause"
] | 16 | 2015-02-25T22:35:54.000Z | 2021-12-14T19:59:30.000Z | ColorTribe/ColorLib_cpp/src/device/ediddata/NVGetEDID.cpp | mikrosimage/OpenDisplayCalib | a8cc37aa72d378faedc4a44171bcb29a20394432 | [
"BSD-3-Clause"
] | 2 | 2015-04-02T13:43:01.000Z | 2015-06-01T13:42:00.000Z | ColorTribe/ColorLib_cpp/src/device/ediddata/NVGetEDID.cpp | mikrosimage/OpenDisplayCalib | a8cc37aa72d378faedc4a44171bcb29a20394432 | [
"BSD-3-Clause"
] | 5 | 2016-03-02T16:08:49.000Z | 2019-11-29T11:16:54.000Z | /* Inspired from Read-Edid (c) 2000,2001,2002 John Fremlin */
/* patched by mfe for Linux 64 - 2009 */
#ifdef __linux__
#include "NVGetEDID.h"
#include "EDIDData.h"
#include <string.h>
#include <nv_control.h>
#include <NvCtrlAttributes.h>
#include <iostream>
#include <sys/io.h>
using namespace std;
static char *display_device_name(int mask)
{
switch (mask) {
case (1 << 0): return "CRT-0"; break;
case (1 << 1): return "CRT-1"; break;
case (1 << 2): return "CRT-2"; break;
case (1 << 3): return "CRT-3"; break;
case (1 << 4): return "CRT-4"; break;
case (1 << 5): return "CRT-5"; break;
case (1 << 6): return "CRT-6"; break;
case (1 << 7): return "CRT-7"; break;
case (1 << 8): return "TV-0"; break;
case (1 << 9): return "TV-1"; break;
case (1 << 10): return "TV-2"; break;
case (1 << 11): return "TV-3"; break;
case (1 << 12): return "TV-4"; break;
case (1 << 13): return "TV-5"; break;
case (1 << 14): return "TV-6"; break;
case (1 << 15): return "TV-7"; break;
case (1 << 16): return "DFP-0"; break;
case (1 << 17): return "DFP-1"; break;
case (1 << 18): return "DFP-2"; break;
case (1 << 19): return "DFP-3"; break;
case (1 << 20): return "DFP-4"; break;
case (1 << 21): return "DFP-5"; break;
case (1 << 22): return "DFP-6"; break;
case (1 << 23): return "DFP-7"; break;
default: return "Unknown";
}
}
int
NVGetEDID::getEDID(vector<EDIDData> &edidDataVector )
{
int res = 0;
Display *dpy;
Bool ret;
int screen, display_devices, mask;
int nDisplayDevice;
/*
* Open a display connection, and make sure the NV-CONTROL X
* extension is present on the screen we want to use.
*/
dpy = XOpenDisplay(NULL);
if (!dpy) {
return CANT_RETRIEVE_CONNECTED_DISPLAY;
}
screen = DefaultScreen(dpy);
if (!XNVCTRLIsNvScreen(dpy, screen)) {
return NOT_A_NV_SCREEN_ERROR;
}
// ret = XNVCTRLQueryVersion(dpy, &major, &minor);
// if (ret != True) {
// return;
// }
//
// printf("\nUsing NV-CONTROL extension %d.%d on %s\n",
// major, minor, XDisplayName(NULL));
/*
* query the connected display devices on this X screen and print
* basic information about each X screen
*/
ret = XNVCTRLQueryAttribute(dpy, screen, 0,
NV_CTRL_CONNECTED_DISPLAYS, &display_devices);
if (!ret) {
return NOT_A_NV_SCREEN_ERROR;
}
nDisplayDevice = 0;
for (mask = 1; mask < (1 << 24); mask <<= 1) {
if (display_devices & mask) {
//char *displayDeviceNames[8];
// XNVCTRLQueryStringAttribute(dpy, screen, mask,
// NV_CTRL_STRING_DISPLAY_DEVICE_NAME,
// &str);
//
// displayDeviceNames[nDisplayDevice++] = str;
//
// // printf(" %s (0x%08x): %s\n",
// // display_device_name(mask), mask, str);
// printf(" (0x%08x): %s\n",
// mask, str);
int edidAvalaible = 0;
unsigned char *data = NULL;
int len = 0;
ret = XNVCTRLQueryAttribute(dpy, screen, mask, NV_CTRL_EDID_AVAILABLE, &edidAvalaible);
if(ret && edidAvalaible) {
ret = XNVCTRLQueryBinaryData (
dpy,//Display *dpy
screen,//int target_id, --> a priori c'est bien 0
mask,//unsigned int display_mask,
NV_CTRL_BINARY_DATA_EDID,
&data,
&len
);
EDIDData edid(data, len);
if(edid.isCheckSumOk()) {
edidDataVector.push_back(edid);
}
}
else {
continue;
}
}
}
//
return res;
}
bool NVGetEDID::isGetEDIDEnable()
{
Display *dpy;
int screen;
/*
* Open a display connection, and make sure the NV-CONTROL X
* extension is present on the screen we want to use.
*/
dpy = XOpenDisplay(NULL);
if (!dpy) {
return false;
}
screen = DefaultScreen(dpy);
///
if (!XNVCTRLIsNvScreen(dpy, screen)) {
return false;
}
return true;
}
void NVGetEDID::dumpError(int error) {
switch (error) {
case SUCCESS:
break;
case OPEN_DISPLAY_ERROR:
cout<<"Can't open display"<<endl;
break;
case NOT_A_NV_SCREEN_ERROR:
cout<<"Not a NV screen"<<endl;
break;
case CANT_RETRIEVE_CONNECTED_DISPLAY:
cout<<"Can't retrieve connected display"<<endl;
break;
default:
cout<<"Unknown code : "<<error<<endl;
break;
}
}
int NVGetEDID::getNVControlPrimaryScreen(std::map<std::string,std::string> &maskToName) {
///Test
int res = 0;
Display *dpy;
Bool ret;
int screen, display_devices, mask;
char *str;
char *displayDeviceNames[8];
int nDisplayDevice;
/*
* Open a display connection, and make sure the NV-CONTROL X
* extension is present on the screen we want to use.
*/
dpy = XOpenDisplay(NULL);
if (!dpy) {
return CANT_RETRIEVE_CONNECTED_DISPLAY;
}
screen = DefaultScreen(dpy);
if (!XNVCTRLIsNvScreen(dpy, screen)) {
return NOT_A_NV_SCREEN_ERROR;
}
ret = XNVCTRLQueryAttribute(dpy, screen, 0,
NV_CTRL_CONNECTED_DISPLAYS, &display_devices);
if (!ret) {
return 1;
}
nDisplayDevice = 0;
for (mask = 1; mask < (1 << 24); mask <<= 1) {
if (display_devices & mask) {
XNVCTRLQueryStringAttribute(dpy, screen, mask,
NV_CTRL_STRING_DISPLAY_DEVICE_NAME,
&str);
displayDeviceNames[nDisplayDevice++] = str;
maskToName.insert(std::make_pair(display_device_name(mask), str));
}
}
return res;
}
#endif
| 21.419087 | 90 | 0.633475 | [
"vector"
] |
42c0eb940ae3aed251c11bd2975cf3a652216215 | 45,230 | cpp | C++ | case-studies/PoDoFo/podofo/cib/podofo/doc/PdfPainter.h.cpp | satya-das/cib | 369333ea58b0530b8789a340e21096ba7d159d0e | [
"MIT"
] | 30 | 2018-03-05T17:35:29.000Z | 2022-03-17T18:59:34.000Z | case-studies/PoDoFo/podofo/cib/podofo/doc/PdfPainter.h.cpp | satya-das/cib | 369333ea58b0530b8789a340e21096ba7d159d0e | [
"MIT"
] | 2 | 2016-05-26T04:47:13.000Z | 2019-02-15T05:17:43.000Z | case-studies/PoDoFo/podofo/cib/podofo/doc/PdfPainter.h.cpp | satya-das/cib | 369333ea58b0530b8789a340e21096ba7d159d0e | [
"MIT"
] | 5 | 2019-02-15T05:09:22.000Z | 2021-04-14T12:10:16.000Z | #include "podofo/base/PdfCanvas.h"
#include "podofo/base/PdfColor.h"
#include "podofo/base/PdfCompilerCompat.h"
#include "podofo/base/PdfDefines.h"
#include "podofo/base/PdfName.h"
#include "podofo/base/PdfObject.h"
#include "podofo/base/PdfRect.h"
#include "podofo/base/PdfReference.h"
#include "podofo/base/PdfStream.h"
#include "podofo/base/PdfString.h"
#include "podofo/doc/PdfExtGState.h"
#include "podofo/doc/PdfFont.h"
#include "podofo/doc/PdfImage.h"
#include "podofo/doc/PdfMemDocument.h"
#include "podofo/doc/PdfPainter.h"
#include "podofo/doc/PdfShadingPattern.h"
#include "podofo/doc/PdfTilingPattern.h"
#include "podofo/doc/PdfXObject.h"
#include <vector>
#include "__zz_cib_CibPoDoFo-class-down-cast.h"
#include "__zz_cib_CibPoDoFo-delegate-helper.h"
#include "__zz_cib_CibPoDoFo-generic.h"
#include "__zz_cib_CibPoDoFo-ids.h"
#include "__zz_cib_CibPoDoFo-type-converters.h"
#include "__zz_cib_CibPoDoFo-mtable-helper.h"
#include "__zz_cib_CibPoDoFo-proxy-mgr.h"
namespace __zz_cib_ {
using namespace ::PoDoFo;
template <>
struct __zz_cib_Delegator<::PoDoFo::PdfPainter> : public ::PoDoFo::PdfPainter {
using __zz_cib_Delegatee = __zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>;
using __zz_cib_AbiType = __zz_cib_Delegatee*;
using ::PoDoFo::PdfPainter::PdfPainter;
static __zz_cib_AbiType __zz_cib_decl __zz_cib_New_0() {
return new __zz_cib_Delegatee();
}
static void __zz_cib_decl __zz_cib_Delete_1(__zz_cib_Delegatee* __zz_cib_obj) {
delete __zz_cib_obj;
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SetPage_2(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<::PoDoFo::PdfCanvas*> pPage) {
__zz_cib_obj->::PoDoFo::PdfPainter::SetPage(
__zz_cib_::__zz_cib_FromAbiType<::PoDoFo::PdfCanvas*>(pPage)
);
}
static __zz_cib_AbiType_t<::PoDoFo::PdfCanvas*> __zz_cib_decl GetPage_3(const __zz_cib_Delegatee* __zz_cib_obj) {
return __zz_cib_ToAbiType<::PoDoFo::PdfCanvas*>(
__zz_cib_obj->::PoDoFo::PdfPainter::GetPage()
);
}
static __zz_cib_AbiType_t<::PoDoFo::PdfStream*> __zz_cib_decl GetCanvas_4(const __zz_cib_Delegatee* __zz_cib_obj) {
return __zz_cib_ToAbiType<::PoDoFo::PdfStream*>(
__zz_cib_obj->::PoDoFo::PdfPainter::GetCanvas()
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl FinishPage_5(__zz_cib_Delegatee* __zz_cib_obj) {
__zz_cib_obj->::PoDoFo::PdfPainter::FinishPage();
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SetStrokingGray_6(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<double> g) {
__zz_cib_obj->::PoDoFo::PdfPainter::SetStrokingGray(
__zz_cib_::__zz_cib_FromAbiType<double>(g)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SetGray_7(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<double> g) {
__zz_cib_obj->::PoDoFo::PdfPainter::SetGray(
__zz_cib_::__zz_cib_FromAbiType<double>(g)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SetStrokingColor_8(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<double> r, __zz_cib_AbiType_t<double> g, __zz_cib_AbiType_t<double> b) {
__zz_cib_obj->::PoDoFo::PdfPainter::SetStrokingColor(
__zz_cib_::__zz_cib_FromAbiType<double>(r),
__zz_cib_::__zz_cib_FromAbiType<double>(g),
__zz_cib_::__zz_cib_FromAbiType<double>(b)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SetColor_9(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<double> r, __zz_cib_AbiType_t<double> g, __zz_cib_AbiType_t<double> b) {
__zz_cib_obj->::PoDoFo::PdfPainter::SetColor(
__zz_cib_::__zz_cib_FromAbiType<double>(r),
__zz_cib_::__zz_cib_FromAbiType<double>(g),
__zz_cib_::__zz_cib_FromAbiType<double>(b)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SetStrokingColorCMYK_10(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<double> c, __zz_cib_AbiType_t<double> m, __zz_cib_AbiType_t<double> y, __zz_cib_AbiType_t<double> k) {
__zz_cib_obj->::PoDoFo::PdfPainter::SetStrokingColorCMYK(
__zz_cib_::__zz_cib_FromAbiType<double>(c),
__zz_cib_::__zz_cib_FromAbiType<double>(m),
__zz_cib_::__zz_cib_FromAbiType<double>(y),
__zz_cib_::__zz_cib_FromAbiType<double>(k)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SetColorCMYK_11(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<double> c, __zz_cib_AbiType_t<double> m, __zz_cib_AbiType_t<double> y, __zz_cib_AbiType_t<double> k) {
__zz_cib_obj->::PoDoFo::PdfPainter::SetColorCMYK(
__zz_cib_::__zz_cib_FromAbiType<double>(c),
__zz_cib_::__zz_cib_FromAbiType<double>(m),
__zz_cib_::__zz_cib_FromAbiType<double>(y),
__zz_cib_::__zz_cib_FromAbiType<double>(k)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SetStrokingShadingPattern_12(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<const ::PoDoFo::PdfShadingPattern&> rPattern) {
__zz_cib_obj->::PoDoFo::PdfPainter::SetStrokingShadingPattern(
__zz_cib_::__zz_cib_FromAbiType<const ::PoDoFo::PdfShadingPattern&>(rPattern)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SetShadingPattern_13(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<const ::PoDoFo::PdfShadingPattern&> rPattern) {
__zz_cib_obj->::PoDoFo::PdfPainter::SetShadingPattern(
__zz_cib_::__zz_cib_FromAbiType<const ::PoDoFo::PdfShadingPattern&>(rPattern)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SetStrokingTilingPattern_14(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<const ::PoDoFo::PdfTilingPattern&> rPattern) {
__zz_cib_obj->::PoDoFo::PdfPainter::SetStrokingTilingPattern(
__zz_cib_::__zz_cib_FromAbiType<const ::PoDoFo::PdfTilingPattern&>(rPattern)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SetStrokingTilingPattern_15(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<const std::string&> rPatternName) {
__zz_cib_obj->::PoDoFo::PdfPainter::SetStrokingTilingPattern(
__zz_cib_::__zz_cib_FromAbiType<const std::string&>(rPatternName)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SetTilingPattern_16(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<const ::PoDoFo::PdfTilingPattern&> rPattern) {
__zz_cib_obj->::PoDoFo::PdfPainter::SetTilingPattern(
__zz_cib_::__zz_cib_FromAbiType<const ::PoDoFo::PdfTilingPattern&>(rPattern)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SetTilingPattern_17(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<const std::string&> rPatternName) {
__zz_cib_obj->::PoDoFo::PdfPainter::SetTilingPattern(
__zz_cib_::__zz_cib_FromAbiType<const std::string&>(rPatternName)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SetStrokingColor_18(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<const ::PoDoFo::PdfColor&> rColor) {
__zz_cib_obj->::PoDoFo::PdfPainter::SetStrokingColor(
__zz_cib_::__zz_cib_FromAbiType<const ::PoDoFo::PdfColor&>(rColor)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SetColor_19(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<const ::PoDoFo::PdfColor&> rColor) {
__zz_cib_obj->::PoDoFo::PdfPainter::SetColor(
__zz_cib_::__zz_cib_FromAbiType<const ::PoDoFo::PdfColor&>(rColor)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SetStrokeWidth_20(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<double> dWidth) {
__zz_cib_obj->::PoDoFo::PdfPainter::SetStrokeWidth(
__zz_cib_::__zz_cib_FromAbiType<double>(dWidth)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SetStrokeStyle_21(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<::PoDoFo::EPdfStrokeStyle> eStyle, __zz_cib_AbiType_t<const char*> pszCustom, __zz_cib_AbiType_t<bool> inverted, __zz_cib_AbiType_t<double> scale, __zz_cib_AbiType_t<bool> subtractJoinCap) {
__zz_cib_obj->::PoDoFo::PdfPainter::SetStrokeStyle(
__zz_cib_::__zz_cib_FromAbiType<::PoDoFo::EPdfStrokeStyle>(eStyle),
__zz_cib_::__zz_cib_FromAbiType<const char*>(pszCustom),
__zz_cib_::__zz_cib_FromAbiType<bool>(inverted),
__zz_cib_::__zz_cib_FromAbiType<double>(scale),
__zz_cib_::__zz_cib_FromAbiType<bool>(subtractJoinCap)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SetLineCapStyle_22(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<::PoDoFo::EPdfLineCapStyle> eCapStyle) {
__zz_cib_obj->::PoDoFo::PdfPainter::SetLineCapStyle(
__zz_cib_::__zz_cib_FromAbiType<::PoDoFo::EPdfLineCapStyle>(eCapStyle)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SetLineJoinStyle_23(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<::PoDoFo::EPdfLineJoinStyle> eJoinStyle) {
__zz_cib_obj->::PoDoFo::PdfPainter::SetLineJoinStyle(
__zz_cib_::__zz_cib_FromAbiType<::PoDoFo::EPdfLineJoinStyle>(eJoinStyle)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SetFont_24(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<::PoDoFo::PdfFont*> pFont) {
__zz_cib_obj->::PoDoFo::PdfPainter::SetFont(
__zz_cib_::__zz_cib_FromAbiType<::PoDoFo::PdfFont*>(pFont)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SetTextRenderingMode_25(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<::PoDoFo::EPdfTextRenderingMode> mode) {
__zz_cib_obj->::PoDoFo::PdfPainter::SetTextRenderingMode(
__zz_cib_::__zz_cib_FromAbiType<::PoDoFo::EPdfTextRenderingMode>(mode)
);
}
static __zz_cib_AbiType_t<::PoDoFo::EPdfTextRenderingMode> __zz_cib_decl GetTextRenderingMode_26(const __zz_cib_Delegatee* __zz_cib_obj) {
return __zz_cib_ToAbiType<::PoDoFo::EPdfTextRenderingMode>(
__zz_cib_obj->::PoDoFo::PdfPainter::GetTextRenderingMode()
);
}
static __zz_cib_AbiType_t<::PoDoFo::PdfFont*> __zz_cib_decl GetFont_27(const __zz_cib_Delegatee* __zz_cib_obj) {
return __zz_cib_ToAbiType<::PoDoFo::PdfFont*>(
__zz_cib_obj->::PoDoFo::PdfPainter::GetFont()
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SetClipRect_28(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<double> dX, __zz_cib_AbiType_t<double> dY, __zz_cib_AbiType_t<double> dWidth, __zz_cib_AbiType_t<double> dHeight) {
__zz_cib_obj->::PoDoFo::PdfPainter::SetClipRect(
__zz_cib_::__zz_cib_FromAbiType<double>(dX),
__zz_cib_::__zz_cib_FromAbiType<double>(dY),
__zz_cib_::__zz_cib_FromAbiType<double>(dWidth),
__zz_cib_::__zz_cib_FromAbiType<double>(dHeight)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SetClipRect_29(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<const ::PoDoFo::PdfRect&> rRect) {
__zz_cib_obj->::PoDoFo::PdfPainter::SetClipRect(
__zz_cib_::__zz_cib_FromAbiType<const ::PoDoFo::PdfRect&>(rRect)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SetMiterLimit_30(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<double> value) {
__zz_cib_obj->::PoDoFo::PdfPainter::SetMiterLimit(
__zz_cib_::__zz_cib_FromAbiType<double>(value)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl DrawLine_31(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<double> dStartX, __zz_cib_AbiType_t<double> dStartY, __zz_cib_AbiType_t<double> dEndX, __zz_cib_AbiType_t<double> dEndY) {
__zz_cib_obj->::PoDoFo::PdfPainter::DrawLine(
__zz_cib_::__zz_cib_FromAbiType<double>(dStartX),
__zz_cib_::__zz_cib_FromAbiType<double>(dStartY),
__zz_cib_::__zz_cib_FromAbiType<double>(dEndX),
__zz_cib_::__zz_cib_FromAbiType<double>(dEndY)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl Rectangle_32(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<double> dX, __zz_cib_AbiType_t<double> dY, __zz_cib_AbiType_t<double> dWidth, __zz_cib_AbiType_t<double> dHeight, __zz_cib_AbiType_t<double> dRoundX, __zz_cib_AbiType_t<double> dRoundY) {
__zz_cib_obj->::PoDoFo::PdfPainter::Rectangle(
__zz_cib_::__zz_cib_FromAbiType<double>(dX),
__zz_cib_::__zz_cib_FromAbiType<double>(dY),
__zz_cib_::__zz_cib_FromAbiType<double>(dWidth),
__zz_cib_::__zz_cib_FromAbiType<double>(dHeight),
__zz_cib_::__zz_cib_FromAbiType<double>(dRoundX),
__zz_cib_::__zz_cib_FromAbiType<double>(dRoundY)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl Rectangle_33(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<const ::PoDoFo::PdfRect&> rRect, __zz_cib_AbiType_t<double> dRoundX, __zz_cib_AbiType_t<double> dRoundY) {
__zz_cib_obj->::PoDoFo::PdfPainter::Rectangle(
__zz_cib_::__zz_cib_FromAbiType<const ::PoDoFo::PdfRect&>(rRect),
__zz_cib_::__zz_cib_FromAbiType<double>(dRoundX),
__zz_cib_::__zz_cib_FromAbiType<double>(dRoundY)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl Ellipse_34(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<double> dX, __zz_cib_AbiType_t<double> dY, __zz_cib_AbiType_t<double> dWidth, __zz_cib_AbiType_t<double> dHeight) {
__zz_cib_obj->::PoDoFo::PdfPainter::Ellipse(
__zz_cib_::__zz_cib_FromAbiType<double>(dX),
__zz_cib_::__zz_cib_FromAbiType<double>(dY),
__zz_cib_::__zz_cib_FromAbiType<double>(dWidth),
__zz_cib_::__zz_cib_FromAbiType<double>(dHeight)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl Circle_35(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<double> dX, __zz_cib_AbiType_t<double> dY, __zz_cib_AbiType_t<double> dRadius) {
__zz_cib_obj->::PoDoFo::PdfPainter::Circle(
__zz_cib_::__zz_cib_FromAbiType<double>(dX),
__zz_cib_::__zz_cib_FromAbiType<double>(dY),
__zz_cib_::__zz_cib_FromAbiType<double>(dRadius)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl DrawText_36(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<double> dX, __zz_cib_AbiType_t<double> dY, __zz_cib_AbiType_t<const ::PoDoFo::PdfString&> sText) {
__zz_cib_obj->::PoDoFo::PdfPainter::DrawText(
__zz_cib_::__zz_cib_FromAbiType<double>(dX),
__zz_cib_::__zz_cib_FromAbiType<double>(dY),
__zz_cib_::__zz_cib_FromAbiType<const ::PoDoFo::PdfString&>(sText)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl DrawText_37(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<double> dX, __zz_cib_AbiType_t<double> dY, __zz_cib_AbiType_t<const ::PoDoFo::PdfString&> sText, __zz_cib_AbiType_t<long> lLen) {
__zz_cib_obj->::PoDoFo::PdfPainter::DrawText(
__zz_cib_::__zz_cib_FromAbiType<double>(dX),
__zz_cib_::__zz_cib_FromAbiType<double>(dY),
__zz_cib_::__zz_cib_FromAbiType<const ::PoDoFo::PdfString&>(sText),
__zz_cib_::__zz_cib_FromAbiType<long>(lLen)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl DrawMultiLineText_38(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<double> dX, __zz_cib_AbiType_t<double> dY, __zz_cib_AbiType_t<double> dWidth, __zz_cib_AbiType_t<double> dHeight, __zz_cib_AbiType_t<const ::PoDoFo::PdfString&> rsText, __zz_cib_AbiType_t<::PoDoFo::EPdfAlignment> eAlignment, __zz_cib_AbiType_t<::PoDoFo::EPdfVerticalAlignment> eVertical, __zz_cib_AbiType_t<bool> bClip, __zz_cib_AbiType_t<bool> bSkipSpaces) {
__zz_cib_obj->::PoDoFo::PdfPainter::DrawMultiLineText(
__zz_cib_::__zz_cib_FromAbiType<double>(dX),
__zz_cib_::__zz_cib_FromAbiType<double>(dY),
__zz_cib_::__zz_cib_FromAbiType<double>(dWidth),
__zz_cib_::__zz_cib_FromAbiType<double>(dHeight),
__zz_cib_::__zz_cib_FromAbiType<const ::PoDoFo::PdfString&>(rsText),
__zz_cib_::__zz_cib_FromAbiType<::PoDoFo::EPdfAlignment>(eAlignment),
__zz_cib_::__zz_cib_FromAbiType<::PoDoFo::EPdfVerticalAlignment>(eVertical),
__zz_cib_::__zz_cib_FromAbiType<bool>(bClip),
__zz_cib_::__zz_cib_FromAbiType<bool>(bSkipSpaces)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl DrawMultiLineText_39(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<const ::PoDoFo::PdfRect&> rRect, __zz_cib_AbiType_t<const ::PoDoFo::PdfString&> rsText, __zz_cib_AbiType_t<::PoDoFo::EPdfAlignment> eAlignment, __zz_cib_AbiType_t<::PoDoFo::EPdfVerticalAlignment> eVertical, __zz_cib_AbiType_t<bool> bClip, __zz_cib_AbiType_t<bool> bSkipSpaces) {
__zz_cib_obj->::PoDoFo::PdfPainter::DrawMultiLineText(
__zz_cib_::__zz_cib_FromAbiType<const ::PoDoFo::PdfRect&>(rRect),
__zz_cib_::__zz_cib_FromAbiType<const ::PoDoFo::PdfString&>(rsText),
__zz_cib_::__zz_cib_FromAbiType<::PoDoFo::EPdfAlignment>(eAlignment),
__zz_cib_::__zz_cib_FromAbiType<::PoDoFo::EPdfVerticalAlignment>(eVertical),
__zz_cib_::__zz_cib_FromAbiType<bool>(bClip),
__zz_cib_::__zz_cib_FromAbiType<bool>(bSkipSpaces)
);
}
static __zz_cib_AbiType_t<::std::vector<::PoDoFo::PdfString>> __zz_cib_decl GetMultiLineTextAsLines_40(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<double> dWidth, __zz_cib_AbiType_t<const ::PoDoFo::PdfString&> rsText, __zz_cib_AbiType_t<bool> bSkipSpaces) {
return __zz_cib_ToAbiType<::std::vector<::PoDoFo::PdfString>>(
__zz_cib_obj->::PoDoFo::PdfPainter::GetMultiLineTextAsLines(
__zz_cib_::__zz_cib_FromAbiType<double>(dWidth),
__zz_cib_::__zz_cib_FromAbiType<const ::PoDoFo::PdfString&>(rsText),
__zz_cib_::__zz_cib_FromAbiType<bool>(bSkipSpaces)
)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl DrawTextAligned_41(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<double> dX, __zz_cib_AbiType_t<double> dY, __zz_cib_AbiType_t<double> dWidth, __zz_cib_AbiType_t<const ::PoDoFo::PdfString&> rsText, __zz_cib_AbiType_t<::PoDoFo::EPdfAlignment> eAlignment) {
__zz_cib_obj->::PoDoFo::PdfPainter::DrawTextAligned(
__zz_cib_::__zz_cib_FromAbiType<double>(dX),
__zz_cib_::__zz_cib_FromAbiType<double>(dY),
__zz_cib_::__zz_cib_FromAbiType<double>(dWidth),
__zz_cib_::__zz_cib_FromAbiType<const ::PoDoFo::PdfString&>(rsText),
__zz_cib_::__zz_cib_FromAbiType<::PoDoFo::EPdfAlignment>(eAlignment)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl BeginText_42(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<double> dX, __zz_cib_AbiType_t<double> dY) {
__zz_cib_obj->::PoDoFo::PdfPainter::BeginText(
__zz_cib_::__zz_cib_FromAbiType<double>(dX),
__zz_cib_::__zz_cib_FromAbiType<double>(dY)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl AddText_43(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<const ::PoDoFo::PdfString&> sText) {
__zz_cib_obj->::PoDoFo::PdfPainter::AddText(
__zz_cib_::__zz_cib_FromAbiType<const ::PoDoFo::PdfString&>(sText)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl AddText_44(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<const ::PoDoFo::PdfString&> sText, __zz_cib_AbiType_t<::PoDoFo::pdf_long> lStringLen) {
__zz_cib_obj->::PoDoFo::PdfPainter::AddText(
__zz_cib_::__zz_cib_FromAbiType<const ::PoDoFo::PdfString&>(sText),
__zz_cib_::__zz_cib_FromAbiType<::PoDoFo::pdf_long>(lStringLen)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl MoveTextPos_45(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<double> dX, __zz_cib_AbiType_t<double> dY) {
__zz_cib_obj->::PoDoFo::PdfPainter::MoveTextPos(
__zz_cib_::__zz_cib_FromAbiType<double>(dX),
__zz_cib_::__zz_cib_FromAbiType<double>(dY)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl EndText_46(__zz_cib_Delegatee* __zz_cib_obj) {
__zz_cib_obj->::PoDoFo::PdfPainter::EndText();
}
static __zz_cib_AbiType_t<void> __zz_cib_decl DrawGlyph_47(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<::PoDoFo::PdfMemDocument*> pDocument, __zz_cib_AbiType_t<double> dX, __zz_cib_AbiType_t<double> dY, __zz_cib_AbiType_t<const char*> pszGlyphname) {
__zz_cib_obj->::PoDoFo::PdfPainter::DrawGlyph(
__zz_cib_::__zz_cib_FromAbiType<::PoDoFo::PdfMemDocument*>(pDocument),
__zz_cib_::__zz_cib_FromAbiType<double>(dX),
__zz_cib_::__zz_cib_FromAbiType<double>(dY),
__zz_cib_::__zz_cib_FromAbiType<const char*>(pszGlyphname)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl DrawImage_48(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<double> dX, __zz_cib_AbiType_t<double> dY, __zz_cib_AbiType_t<::PoDoFo::PdfImage*> pObject, __zz_cib_AbiType_t<double> dScaleX, __zz_cib_AbiType_t<double> dScaleY) {
__zz_cib_obj->::PoDoFo::PdfPainter::DrawImage(
__zz_cib_::__zz_cib_FromAbiType<double>(dX),
__zz_cib_::__zz_cib_FromAbiType<double>(dY),
__zz_cib_::__zz_cib_FromAbiType<::PoDoFo::PdfImage*>(pObject),
__zz_cib_::__zz_cib_FromAbiType<double>(dScaleX),
__zz_cib_::__zz_cib_FromAbiType<double>(dScaleY)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl DrawXObject_49(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<double> dX, __zz_cib_AbiType_t<double> dY, __zz_cib_AbiType_t<::PoDoFo::PdfXObject*> pObject, __zz_cib_AbiType_t<double> dScaleX, __zz_cib_AbiType_t<double> dScaleY) {
__zz_cib_obj->::PoDoFo::PdfPainter::DrawXObject(
__zz_cib_::__zz_cib_FromAbiType<double>(dX),
__zz_cib_::__zz_cib_FromAbiType<double>(dY),
__zz_cib_::__zz_cib_FromAbiType<::PoDoFo::PdfXObject*>(pObject),
__zz_cib_::__zz_cib_FromAbiType<double>(dScaleX),
__zz_cib_::__zz_cib_FromAbiType<double>(dScaleY)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl ClosePath_50(__zz_cib_Delegatee* __zz_cib_obj) {
__zz_cib_obj->::PoDoFo::PdfPainter::ClosePath();
}
static __zz_cib_AbiType_t<void> __zz_cib_decl LineTo_51(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<double> dX, __zz_cib_AbiType_t<double> dY) {
__zz_cib_obj->::PoDoFo::PdfPainter::LineTo(
__zz_cib_::__zz_cib_FromAbiType<double>(dX),
__zz_cib_::__zz_cib_FromAbiType<double>(dY)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl MoveTo_52(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<double> dX, __zz_cib_AbiType_t<double> dY) {
__zz_cib_obj->::PoDoFo::PdfPainter::MoveTo(
__zz_cib_::__zz_cib_FromAbiType<double>(dX),
__zz_cib_::__zz_cib_FromAbiType<double>(dY)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl CubicBezierTo_53(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<double> dX1, __zz_cib_AbiType_t<double> dY1, __zz_cib_AbiType_t<double> dX2, __zz_cib_AbiType_t<double> dY2, __zz_cib_AbiType_t<double> dX3, __zz_cib_AbiType_t<double> dY3) {
__zz_cib_obj->::PoDoFo::PdfPainter::CubicBezierTo(
__zz_cib_::__zz_cib_FromAbiType<double>(dX1),
__zz_cib_::__zz_cib_FromAbiType<double>(dY1),
__zz_cib_::__zz_cib_FromAbiType<double>(dX2),
__zz_cib_::__zz_cib_FromAbiType<double>(dY2),
__zz_cib_::__zz_cib_FromAbiType<double>(dX3),
__zz_cib_::__zz_cib_FromAbiType<double>(dY3)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl HorizontalLineTo_54(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<double> dX) {
__zz_cib_obj->::PoDoFo::PdfPainter::HorizontalLineTo(
__zz_cib_::__zz_cib_FromAbiType<double>(dX)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl VerticalLineTo_55(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<double> dY) {
__zz_cib_obj->::PoDoFo::PdfPainter::VerticalLineTo(
__zz_cib_::__zz_cib_FromAbiType<double>(dY)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SmoothCurveTo_56(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<double> dX2, __zz_cib_AbiType_t<double> dY2, __zz_cib_AbiType_t<double> dX3, __zz_cib_AbiType_t<double> dY3) {
__zz_cib_obj->::PoDoFo::PdfPainter::SmoothCurveTo(
__zz_cib_::__zz_cib_FromAbiType<double>(dX2),
__zz_cib_::__zz_cib_FromAbiType<double>(dY2),
__zz_cib_::__zz_cib_FromAbiType<double>(dX3),
__zz_cib_::__zz_cib_FromAbiType<double>(dY3)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl QuadCurveTo_57(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<double> dX1, __zz_cib_AbiType_t<double> dY1, __zz_cib_AbiType_t<double> dX3, __zz_cib_AbiType_t<double> dY3) {
__zz_cib_obj->::PoDoFo::PdfPainter::QuadCurveTo(
__zz_cib_::__zz_cib_FromAbiType<double>(dX1),
__zz_cib_::__zz_cib_FromAbiType<double>(dY1),
__zz_cib_::__zz_cib_FromAbiType<double>(dX3),
__zz_cib_::__zz_cib_FromAbiType<double>(dY3)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SmoothQuadCurveTo_58(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<double> dX3, __zz_cib_AbiType_t<double> dY3) {
__zz_cib_obj->::PoDoFo::PdfPainter::SmoothQuadCurveTo(
__zz_cib_::__zz_cib_FromAbiType<double>(dX3),
__zz_cib_::__zz_cib_FromAbiType<double>(dY3)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl ArcTo_59(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<double> dX, __zz_cib_AbiType_t<double> dY, __zz_cib_AbiType_t<double> dRadiusX, __zz_cib_AbiType_t<double> dRadiusY, __zz_cib_AbiType_t<double> dRotation, __zz_cib_AbiType_t<bool> bLarge, __zz_cib_AbiType_t<bool> bSweep) {
__zz_cib_obj->::PoDoFo::PdfPainter::ArcTo(
__zz_cib_::__zz_cib_FromAbiType<double>(dX),
__zz_cib_::__zz_cib_FromAbiType<double>(dY),
__zz_cib_::__zz_cib_FromAbiType<double>(dRadiusX),
__zz_cib_::__zz_cib_FromAbiType<double>(dRadiusY),
__zz_cib_::__zz_cib_FromAbiType<double>(dRotation),
__zz_cib_::__zz_cib_FromAbiType<bool>(bLarge),
__zz_cib_::__zz_cib_FromAbiType<bool>(bSweep)
);
}
static __zz_cib_AbiType_t<bool> __zz_cib_decl Arc_60(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<double> dX, __zz_cib_AbiType_t<double> dY, __zz_cib_AbiType_t<double> dRadius, __zz_cib_AbiType_t<double> dAngle1, __zz_cib_AbiType_t<double> dAngle2) {
return __zz_cib_ToAbiType<bool>(
__zz_cib_obj->::PoDoFo::PdfPainter::Arc(
__zz_cib_::__zz_cib_FromAbiType<double>(dX),
__zz_cib_::__zz_cib_FromAbiType<double>(dY),
__zz_cib_::__zz_cib_FromAbiType<double>(dRadius),
__zz_cib_::__zz_cib_FromAbiType<double>(dAngle1),
__zz_cib_::__zz_cib_FromAbiType<double>(dAngle2)
)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl Close_61(__zz_cib_Delegatee* __zz_cib_obj) {
__zz_cib_obj->::PoDoFo::PdfPainter::Close();
}
static __zz_cib_AbiType_t<void> __zz_cib_decl Stroke_62(__zz_cib_Delegatee* __zz_cib_obj) {
__zz_cib_obj->::PoDoFo::PdfPainter::Stroke();
}
static __zz_cib_AbiType_t<void> __zz_cib_decl Fill_63(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<bool> useEvenOddRule) {
__zz_cib_obj->::PoDoFo::PdfPainter::Fill(
__zz_cib_::__zz_cib_FromAbiType<bool>(useEvenOddRule)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl FillAndStroke_64(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<bool> useEvenOddRule) {
__zz_cib_obj->::PoDoFo::PdfPainter::FillAndStroke(
__zz_cib_::__zz_cib_FromAbiType<bool>(useEvenOddRule)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl Clip_65(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<bool> useEvenOddRule) {
__zz_cib_obj->::PoDoFo::PdfPainter::Clip(
__zz_cib_::__zz_cib_FromAbiType<bool>(useEvenOddRule)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl EndPath_66(__zz_cib_Delegatee* __zz_cib_obj) {
__zz_cib_obj->::PoDoFo::PdfPainter::EndPath();
}
static __zz_cib_AbiType_t<void> __zz_cib_decl Save_67(__zz_cib_Delegatee* __zz_cib_obj) {
__zz_cib_obj->::PoDoFo::PdfPainter::Save();
}
static __zz_cib_AbiType_t<void> __zz_cib_decl Restore_68(__zz_cib_Delegatee* __zz_cib_obj) {
__zz_cib_obj->::PoDoFo::PdfPainter::Restore();
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SetTransformationMatrix_69(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<double> a, __zz_cib_AbiType_t<double> b, __zz_cib_AbiType_t<double> c, __zz_cib_AbiType_t<double> d, __zz_cib_AbiType_t<double> e, __zz_cib_AbiType_t<double> f) {
__zz_cib_obj->::PoDoFo::PdfPainter::SetTransformationMatrix(
__zz_cib_::__zz_cib_FromAbiType<double>(a),
__zz_cib_::__zz_cib_FromAbiType<double>(b),
__zz_cib_::__zz_cib_FromAbiType<double>(c),
__zz_cib_::__zz_cib_FromAbiType<double>(d),
__zz_cib_::__zz_cib_FromAbiType<double>(e),
__zz_cib_::__zz_cib_FromAbiType<double>(f)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SetExtGState_70(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<::PoDoFo::PdfExtGState*> inGState) {
__zz_cib_obj->::PoDoFo::PdfPainter::SetExtGState(
__zz_cib_::__zz_cib_FromAbiType<::PoDoFo::PdfExtGState*>(inGState)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SetRenderingIntent_71(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<char*> intent) {
__zz_cib_obj->::PoDoFo::PdfPainter::SetRenderingIntent(
__zz_cib_::__zz_cib_FromAbiType<char*>(intent)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SetTabWidth_72(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<unsigned short> nTabWidth) {
__zz_cib_obj->::PoDoFo::PdfPainter::SetTabWidth(
__zz_cib_::__zz_cib_FromAbiType<unsigned short>(nTabWidth)
);
}
static __zz_cib_AbiType_t<unsigned short> __zz_cib_decl GetTabWidth_73(const __zz_cib_Delegatee* __zz_cib_obj) {
return __zz_cib_ToAbiType<unsigned short>(
__zz_cib_obj->::PoDoFo::PdfPainter::GetTabWidth()
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SetPrecision_74(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<unsigned short> inPrec) {
__zz_cib_obj->::PoDoFo::PdfPainter::SetPrecision(
__zz_cib_::__zz_cib_FromAbiType<unsigned short>(inPrec)
);
}
static __zz_cib_AbiType_t<unsigned short> __zz_cib_decl GetPrecision_75(const __zz_cib_Delegatee* __zz_cib_obj) {
return __zz_cib_ToAbiType<unsigned short>(
__zz_cib_obj->::PoDoFo::PdfPainter::GetPrecision()
);
}
static __zz_cib_AbiType_t<std::ostringstream&> __zz_cib_decl GetCurrentPath_76(__zz_cib_Delegatee* __zz_cib_obj) {
return __zz_cib_ToAbiType<std::ostringstream&>(
__zz_cib_obj->::PoDoFo::PdfPainter::GetCurrentPath()
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SetDependICCProfileColor_77(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<const ::PoDoFo::PdfColor&> rColor, __zz_cib_AbiType_t<const std::string&> pCSTag) {
__zz_cib_obj->::PoDoFo::PdfPainter::SetDependICCProfileColor(
__zz_cib_::__zz_cib_FromAbiType<const ::PoDoFo::PdfColor&>(rColor),
__zz_cib_::__zz_cib_FromAbiType<const std::string&>(pCSTag)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl ConvertRectToBezier_78(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<double> dX, __zz_cib_AbiType_t<double> dY, __zz_cib_AbiType_t<double> dWidth, __zz_cib_AbiType_t<double> dHeight, __zz_cib_AbiType_t<double[]> pdPointX, __zz_cib_AbiType_t<double[]> pdPointY) {
__zz_cib_obj->::PoDoFo::PdfPainter::ConvertRectToBezier(
__zz_cib_::__zz_cib_FromAbiType<double>(dX),
__zz_cib_::__zz_cib_FromAbiType<double>(dY),
__zz_cib_::__zz_cib_FromAbiType<double>(dWidth),
__zz_cib_::__zz_cib_FromAbiType<double>(dHeight),
__zz_cib_::__zz_cib_FromAbiType<double[]>(pdPointX),
__zz_cib_::__zz_cib_FromAbiType<double[]>(pdPointY)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl AddToPageResources_79(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<const ::PoDoFo::PdfName&> rIdentifier, __zz_cib_AbiType_t<const ::PoDoFo::PdfReference&> rRef, __zz_cib_AbiType_t<const ::PoDoFo::PdfName&> rName) {
__zz_cib_obj->::PoDoFo::PdfPainter::AddToPageResources(
__zz_cib_::__zz_cib_FromAbiType<const ::PoDoFo::PdfName&>(rIdentifier),
__zz_cib_::__zz_cib_FromAbiType<const ::PoDoFo::PdfReference&>(rRef),
__zz_cib_::__zz_cib_FromAbiType<const ::PoDoFo::PdfName&>(rName)
);
}
static __zz_cib_AbiType_t<void> __zz_cib_decl SetCurrentStrokingColor_80(__zz_cib_Delegatee* __zz_cib_obj) {
__zz_cib_obj->::PoDoFo::PdfPainter::SetCurrentStrokingColor();
}
static __zz_cib_AbiType_t<bool> __zz_cib_decl InternalArc_81(__zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<double> x, __zz_cib_AbiType_t<double> y, __zz_cib_AbiType_t<double> ray, __zz_cib_AbiType_t<double> ang1, __zz_cib_AbiType_t<double> ang2, __zz_cib_AbiType_t<bool> cont_flg) {
return __zz_cib_ToAbiType<bool>(
__zz_cib_obj->::PoDoFo::PdfPainter::InternalArc(
__zz_cib_::__zz_cib_FromAbiType<double>(x),
__zz_cib_::__zz_cib_FromAbiType<double>(y),
__zz_cib_::__zz_cib_FromAbiType<double>(ray),
__zz_cib_::__zz_cib_FromAbiType<double>(ang1),
__zz_cib_::__zz_cib_FromAbiType<double>(ang2),
__zz_cib_::__zz_cib_FromAbiType<bool>(cont_flg)
)
);
}
static __zz_cib_AbiType_t<::PoDoFo::PdfString> __zz_cib_decl ExpandTabs_82(const __zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<const ::PoDoFo::PdfString&> rsString, __zz_cib_AbiType_t<::PoDoFo::pdf_long> lLen) {
return __zz_cib_ToAbiType<::PoDoFo::PdfString>(
__zz_cib_obj->::PoDoFo::PdfPainter::ExpandTabs(
__zz_cib_::__zz_cib_FromAbiType<const ::PoDoFo::PdfString&>(rsString),
__zz_cib_::__zz_cib_FromAbiType<::PoDoFo::pdf_long>(lLen)
)
);
}
#if defined(_MSC_VER) && _MSC_VER <= 1200 // MSC 6.0 has a template-bug
static __zz_cib_AbiType_t<::PoDoFo::PdfString> __zz_cib_decl ExpandTabs_char_83(const __zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<const char*> pszText, __zz_cib_AbiType_t<long> lStringLen, __zz_cib_AbiType_t<int> nTabCnt, __zz_cib_AbiType_t<const char> cTab, __zz_cib_AbiType_t<const char> cSpace) {
return __zz_cib_ToAbiType<::PoDoFo::PdfString>(
__zz_cib_obj->::PoDoFo::PdfPainter::ExpandTabs_char(
__zz_cib_::__zz_cib_FromAbiType<const char*>(pszText),
__zz_cib_::__zz_cib_FromAbiType<long>(lStringLen),
__zz_cib_::__zz_cib_FromAbiType<int>(nTabCnt),
__zz_cib_::__zz_cib_FromAbiType<const char>(cTab),
__zz_cib_::__zz_cib_FromAbiType<const char>(cSpace)
)
);
}
static __zz_cib_AbiType_t<::PoDoFo::PdfString> __zz_cib_decl ExpandTabs_pdf_utf16be_84(const __zz_cib_Delegatee* __zz_cib_obj, __zz_cib_AbiType_t<const ::PoDoFo::pdf_uint16*> pszText, __zz_cib_AbiType_t<long> lStringLen, __zz_cib_AbiType_t<int> nTabCnt, __zz_cib_AbiType_t<const ::PoDoFo::pdf_uint16> cTab, __zz_cib_AbiType_t<const ::PoDoFo::pdf_uint16> cSpace) {
return __zz_cib_ToAbiType<::PoDoFo::PdfString>(
__zz_cib_obj->::PoDoFo::PdfPainter::ExpandTabs_pdf_utf16be(
__zz_cib_::__zz_cib_FromAbiType<const ::PoDoFo::pdf_uint16*>(pszText),
__zz_cib_::__zz_cib_FromAbiType<long>(lStringLen),
__zz_cib_::__zz_cib_FromAbiType<int>(nTabCnt),
__zz_cib_::__zz_cib_FromAbiType<const ::PoDoFo::pdf_uint16>(cTab),
__zz_cib_::__zz_cib_FromAbiType<const ::PoDoFo::pdf_uint16>(cSpace)
)
);
}
#endif
static __zz_cib_AbiType_t<void> __zz_cib_decl SetCurrentTextRenderingMode_85(__zz_cib_Delegatee* __zz_cib_obj) {
__zz_cib_obj->::PoDoFo::PdfPainter::SetCurrentTextRenderingMode();
}
};
}
namespace __zz_cib_ {
namespace __zz_cib_Class333 {
using namespace ::PoDoFo;
namespace __zz_cib_Class464 {
const __zz_cib_MethodTable* __zz_cib_GetMethodTable() {
static const __zz_cib_MTableEntry methodArray[] = {
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::__zz_cib_New_0),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::__zz_cib_Delete_1),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::SetPage_2),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::GetPage_3),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::GetCanvas_4),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::FinishPage_5),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::SetStrokingGray_6),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::SetGray_7),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::SetStrokingColor_8),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::SetColor_9),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::SetStrokingColorCMYK_10),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::SetColorCMYK_11),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::SetStrokingShadingPattern_12),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::SetShadingPattern_13),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::SetStrokingTilingPattern_14),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::SetStrokingTilingPattern_15),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::SetTilingPattern_16),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::SetTilingPattern_17),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::SetStrokingColor_18),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::SetColor_19),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::SetStrokeWidth_20),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::SetStrokeStyle_21),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::SetLineCapStyle_22),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::SetLineJoinStyle_23),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::SetFont_24),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::SetTextRenderingMode_25),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::GetTextRenderingMode_26),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::GetFont_27),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::SetClipRect_28),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::SetClipRect_29),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::SetMiterLimit_30),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::DrawLine_31),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::Rectangle_32),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::Rectangle_33),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::Ellipse_34),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::Circle_35),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::DrawText_36),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::DrawText_37),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::DrawMultiLineText_38),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::DrawMultiLineText_39),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::GetMultiLineTextAsLines_40),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::DrawTextAligned_41),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::BeginText_42),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::AddText_43),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::AddText_44),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::MoveTextPos_45),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::EndText_46),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::DrawGlyph_47),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::DrawImage_48),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::DrawXObject_49),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::ClosePath_50),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::LineTo_51),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::MoveTo_52),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::CubicBezierTo_53),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::HorizontalLineTo_54),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::VerticalLineTo_55),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::SmoothCurveTo_56),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::QuadCurveTo_57),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::SmoothQuadCurveTo_58),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::ArcTo_59),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::Arc_60),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::Close_61),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::Stroke_62),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::Fill_63),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::FillAndStroke_64),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::Clip_65),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::EndPath_66),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::Save_67),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::Restore_68),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::SetTransformationMatrix_69),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::SetExtGState_70),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::SetRenderingIntent_71),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::SetTabWidth_72),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::GetTabWidth_73),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::SetPrecision_74),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::GetPrecision_75),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::GetCurrentPath_76),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::SetDependICCProfileColor_77),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::ConvertRectToBezier_78),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::AddToPageResources_79),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::SetCurrentStrokingColor_80),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::InternalArc_81),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::ExpandTabs_82),
#if defined(_MSC_VER) && _MSC_VER <= 1200 // MSC 6.0 has a template-bug
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::ExpandTabs_char_83),
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::ExpandTabs_pdf_utf16be_84),
#else
reinterpret_cast<__zz_cib_MTableEntry> (0),
reinterpret_cast<__zz_cib_MTableEntry> (0),
#endif
reinterpret_cast<__zz_cib_MTableEntry> (&__zz_cib_::__zz_cib_Delegator<::PoDoFo::PdfPainter>::SetCurrentTextRenderingMode_85)
};
static const __zz_cib_MethodTable methodTable = { methodArray, 86 };
return &methodTable;
}
}}}
| 66.125731 | 481 | 0.779836 | [
"vector"
] |
42c1050e46ffee474efbc2dc0789c26cd466198d | 1,703 | hpp | C++ | src/SinkFilter.hpp | hidenorly/SinkPlugInAlsa | 1d3d90dfa82f69d3e89791ba96d5a0987d2885e4 | [
"Apache-2.0"
] | null | null | null | src/SinkFilter.hpp | hidenorly/SinkPlugInAlsa | 1d3d90dfa82f69d3e89791ba96d5a0987d2885e4 | [
"Apache-2.0"
] | null | null | null | src/SinkFilter.hpp | hidenorly/SinkPlugInAlsa | 1d3d90dfa82f69d3e89791ba96d5a0987d2885e4 | [
"Apache-2.0"
] | null | null | null | /*
Copyright (C) 2021 hidenorly
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 __SINK_FILTER_HPP__
#define __SINK_FILTER_HPP__
#include "Buffer.hpp"
#include "Filter.hpp"
#include "AudioFormat.hpp"
#include <vector>
#include <string>
class NullFilter : public Filter
{
protected:
std::vector<AudioFormat> mSupportedFormats;
public:
NullFilter(){
for(int anEncoding = AudioFormat::ENCODING::PCM_8BIT; anEncoding < AudioFormat::ENCODING::COMPRESSED_UNKNOWN; anEncoding++){
for( int aChannel = AudioFormat::CHANNEL::CHANNEL_MONO; aChannel < AudioFormat::CHANNEL::CHANNEL_UNKNOWN; aChannel++){
mSupportedFormats.push_back( AudioFormat((AudioFormat::ENCODING)anEncoding, 48000, (AudioFormat::CHANNEL)aChannel) );
mSupportedFormats.push_back( AudioFormat((AudioFormat::ENCODING)anEncoding, 96000, (AudioFormat::CHANNEL)aChannel) );
}
}
};
virtual ~NullFilter(){};
virtual std::vector<AudioFormat> getSupportedAudioFormats(void){ return mSupportedFormats; };
virtual void process(AudioBuffer& inBuf, AudioBuffer& outBuf){ outBuf = inBuf; };
virtual std::string toString(void){ return "NullFilter"; };
};
#endif /* __SINK_FILTER_HPP__ */
| 36.234043 | 128 | 0.745156 | [
"vector"
] |
42c3765a97d3d23fdb31feada1778d3051b55563 | 924 | cpp | C++ | abc054/abc054_c.cpp | crazystylus/AtCoderPractice | 8e0f56a9b3905e11f83f351af66af5bfed8606b2 | [
"MIT"
] | null | null | null | abc054/abc054_c.cpp | crazystylus/AtCoderPractice | 8e0f56a9b3905e11f83f351af66af5bfed8606b2 | [
"MIT"
] | null | null | null | abc054/abc054_c.cpp | crazystylus/AtCoderPractice | 8e0f56a9b3905e11f83f351af66af5bfed8606b2 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define rep(i, n) for (int i = 0; i < n; i++)
const int mod = 1e9 + 7; //10^9 + 7;
const int N = 9;
const int M = 29;
///////////////////
// Simply do a DFS with parent array, save the dfs length in a counter and keep comparing till it equals n
vector<int> adj[N];
bool visited[N];
int n, m, a, b, cntr, vc;
void dfs(int u)
{
visited[u] = true;
vc++;
// printf("%d(%d)->", u, vc);
for (auto v : adj[u])
{
if (!visited[v])
dfs(v);
}
if (vc == n)
cntr++;
visited[u] = false;
vc--;
}
void solve()
{
cin >> n >> m;
rep(i, m)
{
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
memset(visited, 0, sizeof visited);
cntr = 0;
vc = 0;
dfs(1);
cout << cntr;
}
int main()
{
solve();
return 0;
} | 18.857143 | 106 | 0.497835 | [
"vector"
] |
42cc91674d1a2f9a16f73fbd54047bb581a575ac | 3,149 | cpp | C++ | Day13.cpp | AlbinMamuti/AoC | 8f65f09787ae10103dc6e1e107c8bd72f133158c | [
"MIT"
] | null | null | null | Day13.cpp | AlbinMamuti/AoC | 8f65f09787ae10103dc6e1e107c8bd72f133158c | [
"MIT"
] | null | null | null | Day13.cpp | AlbinMamuti/AoC | 8f65f09787ae10103dc6e1e107c8bd72f133158c | [
"MIT"
] | null | null | null | #include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
#include <math.h>
#include <cstring>
#include <queue>
#include <stack>
#include <map>
using namespace std;
void tokenize2(string &str, char delim, vector<pair<int,int>> &coord)
{
stringstream ss(str);
std::string s;
std::getline(ss,s,delim);
std::getline(ss,s,delim);
std::getline(ss,s,delim);
bool flagy = false;
if(s == "y")
flagy = true;
std::getline(ss,s,delim);
std::getline(ss,s,delim);
int temp = stoi(s);
if(flagy){
coord.push_back({0,temp});
}
else{
coord.push_back({temp,0});
}
}
bool tokenize(string &str, char delim, vector<pair<int,int>> &coord)
{
stringstream ss(str);
std::string s;
std::getline(ss,s,delim);
if(s == ""){
return false;
}
int t = stoi(s);
std::getline(ss,s,delim);
int b = stoi(s);
pair<int,int> p = {t,b};
coord.push_back(p);
return true;
}
void draw(vector<pair<int,int>> coord){
int xmax = 0;
int ymax = 0;
for(pair<int,int> p : coord){
xmax = p.first > xmax ? p.first : xmax;
ymax = p.second > ymax ? p.second : ymax;
}
ymax++;
xmax++;
char drw[ymax][xmax];
for(int i = 0; i < ymax; i++){
for(int j = 0; j < xmax; j++){
drw[i][j] = '.';
}
}
for(pair <int,int> p : coord){
drw[p.second][p.first] = '#';
}
for(int i = 0; i < ymax; i++){
for(int j = 0; j < xmax; j++){
cout << drw[i][j];
}
cout << endl;
}
}
void eraseD(vector<pair<int,int>> &coord){
vector<pair<int,int>> ret;
for(int i = 0; i < coord.size(); i++){
bool flag = false;
for(int j = i+1; j < coord.size(); j++){
pair<int,int> p1 = coord[i];
pair<int,int> p2 = coord[j];
if(p1.first == p2.first && p1.second == p2.second){
flag = true;
}
}
if(flag)
continue;
ret.push_back(coord[i]);
}
coord = ret;
}
int main(){
string filename = "inputPartOne.txt";
ifstream input_file(filename);
vector<pair<int,int>> coord;
vector<pair<int,int>> folds;
// vector<pair<int,int>> dir = {{0,-1},{0,1},{1,0},{1,1}, {1,-1},{-1,0},{-1,-1},{-1,1}};
for(string line; getline(input_file,line);){
if(!tokenize(line, ',', coord)) break;
}
//read folds
for(string line; getline(input_file,line);){
tokenize2(line, ' ', folds);
}
//draw(coord);
cout << endl;
for(pair<int,int> f : folds){
if(f.first == 0){//y fold
for(pair<int,int> &c : coord){
int diff = std::abs(c.second - f.second);
c.second = f.second - diff;
}
}
else{//x fold
for(pair<int,int> &c: coord){
int diff = std::abs(c.first - f.first);
c.first = f.first - diff;
}
}
eraseD(coord);
//
//cout << coord.size() << endl;
}
draw(coord);
return 0;
}
| 24.992063 | 91 | 0.494125 | [
"vector"
] |
42d0b2a27ea6bfbad1d44a186c42b410293a815d | 24,097 | cc | C++ | project/c++/mri/src/common/src/pubsub_filter/ipv6address_base.cc | jia57196/code41 | df611f84592afd453ccb2d22a7ad999ddb68d028 | [
"Apache-2.0"
] | null | null | null | project/c++/mri/src/common/src/pubsub_filter/ipv6address_base.cc | jia57196/code41 | df611f84592afd453ccb2d22a7ad999ddb68d028 | [
"Apache-2.0"
] | null | null | null | project/c++/mri/src/common/src/pubsub_filter/ipv6address_base.cc | jia57196/code41 | df611f84592afd453ccb2d22a7ad999ddb68d028 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2013 JDSU
* Author: Andy Lai (Andy.Lai@jdsu.com)
*/
#include <vector>
#include <boost/regex.hpp>
#include <boost/algorithm/string/regex.hpp>
#include "xtreme/common/pubsub_filter/ipv4address_base.h"
#include "xtreme/common/pubsub_filter/ipv6address_base.h"
#include "xtreme/common/pubsub_filter/ipv6address.h"
#include "xtreme/common/pubsub_filter/ipv6address_asterisk.h"
#include "xtreme/common/pubsub_filter/ipv6address_asterisk_range.h"
namespace xtreme {
namespace filter {
boost::regex regex_range("(((\\d)|(a-f)|(A-F)){1,4})\\-(((\\d)|(a-f)|(A-F)){1,4})");
IPv6AddressBase* IPv6AddressBase::CreateIPv6Address(const std::string& value)
throw(InvalidFieldValueException) {
bool has_star_symbol = (value.find("*") != std::string::npos);
bool has_range_symbol = (value.find("-") != std::string::npos);
if (!has_star_symbol && !has_range_symbol) {
return (new IPv6Address(value));
} else {
bool is_prefix = (value.find("/") != std::string::npos);
if (is_prefix) {
throw InvalidFieldValueException("not support prefix with wildcard * and -");
}
if (!has_range_symbol) { // only have star symbol
return (new IPv6AddressAsterisk(value));
} else {
return (new IPv6AddressAsteriskRange(value));
}
}
}
void IPv6AddressBase::Ipv6AddressStringToUINT(const std::string& str
, std::list<CompareInfo> &lst_comp_info
, std::list<RangeCompareInfo> &lst_range_comp_info)
throw(InvalidFieldValueException) {
if (str.empty())
return;
bool has_ipv4 = false;
std::list<CompareInfo> lst_comp_info_ipv4;
std::list<RangeCompareInfo> lst_range_comp_info_ipv4;
std::string IPv6_string;
std::vector < std::string > result_mappingipv4;
boost::algorithm::split_regex(result_mappingipv4, str, boost::regex("\\."));
unsigned int result_mappingipv4_len = result_mappingipv4.size();
if (result_mappingipv4_len == 1) {
IPv6_string = str;
} else if (result_mappingipv4_len == 4) {
if (result_mappingipv4[0].empty() || result_mappingipv4[1].empty()
|| result_mappingipv4[2].empty() || result_mappingipv4[3].empty())
throw InvalidFieldValueException(
"Every part of IP V4 should not empty in IPv6 mapping IPv4 address!");
size_t pos = result_mappingipv4[0].find_last_of(':');
if (pos == std::string::npos)
throw InvalidFieldValueException("IPv6 address is incorrect: " + str);
if (pos == result_mappingipv4[0].length() - 1)
throw InvalidFieldValueException(
"The first part of IP V4 should not empty in IPv6 mapping IPv4 address!");
std::string firstpart_IPv4_string = result_mappingipv4[0].substr(
pos + 1, result_mappingipv4[0].length() - pos - 1);
std::string str_ipv4 = firstpart_IPv4_string + "." + result_mappingipv4[1]
+ "." + result_mappingipv4[2] + "." + result_mappingipv4[3];
std::string err_ipv4;
if (!IPv4AddressBase::IsIPv4Address(str_ipv4, err_ipv4))
throw InvalidFieldValueException(err_ipv4);
std::string IPv6AddrFront = result_mappingipv4[0].substr(0, pos);
// std::list<CompareInfo> lst_comp_info_ipv4;
// std::list<RangeCompareInfo> lst_range_comp_info_ipv4;
ExatractIPv4Info(firstpart_IPv4_string, result_mappingipv4[1]
, result_mappingipv4[2], result_mappingipv4[3]
, lst_comp_info_ipv4, lst_range_comp_info_ipv4);
IPv6_string = IPv6AddrFront + ":";
has_ipv4 = true;
} else {
throw InvalidFieldValueException(
"The format of IPv6 mapping IPv4 is incorrect: " + str);
}
std::vector < std::string > result_shortening;
boost::algorithm::split_regex(result_shortening, IPv6_string,
boost::regex("::"));
unsigned int result_shortening_len = result_shortening.size();
if (result_shortening_len == 1) {
// uint8_t* p_ipv6 = NULL;
int IPv6_len = IPv6PartAddressStringToUINT8(IPv6_string, lst_comp_info, lst_range_comp_info);
char str[256];
if (has_ipv4) {
if (IPv6_len != 12) {
snprintf(str, sizeof(str), "IPv6 Address must be 16 octets: %d octets",
IPv6_len + 4);
throw InvalidFieldValueException(str);
}
} else if (IPv6_len != 16) {
snprintf(str, sizeof(str), "IPv6 Address must be 16 octets: %d octets",
IPv6_len);
throw InvalidFieldValueException(str);
}
if (has_ipv4) {
std::list<CompareInfo>::iterator it;
for (it = lst_comp_info_ipv4.begin(); it != lst_comp_info_ipv4.end(); ++it) {
lst_comp_info.push_back(*it);
}
std::list<RangeCompareInfo>::iterator it_range;
for (it_range = lst_range_comp_info_ipv4.begin(); it_range != lst_range_comp_info_ipv4.end(); ++it_range) {
lst_range_comp_info.push_back(*it_range);
}
}
} else if (result_shortening_len == 2) {
std::list<CompareInfo> lst_comp_info2;
std::list<RangeCompareInfo> lst_range_comp_info2;
if (!result_shortening[0].empty() && !result_shortening[1].empty()) {
// uint8_t* p_first_ipv6 = NULL;
// uint8_t* p_second_ipv6 = NULL;
int first_len = IPv6PartAddressStringToUINT8(result_shortening[0],
lst_comp_info, lst_range_comp_info);
int second_len = IPv6PartAddressStringToUINT8(result_shortening[1],
lst_comp_info2, lst_range_comp_info2);
int ipv4_len(0);
if (has_ipv4) {
ipv4_len = 4;
}
if (first_len + second_len + ipv4_len > 16) {
char str[256];
snprintf(str, sizeof(str), "IPv6 Address must be 16 octets: %d octets",
first_len + second_len + ipv4_len);
throw InvalidFieldValueException(str);
}
CompareInfo comp_info;
comp_info.offset_ = first_len;
comp_info.len_ = 16 - (first_len + second_len + ipv4_len);
if (comp_info.len_ > 0) {
comp_info.p_value_ = new uint8_t[comp_info.len_];
memset(comp_info.p_value_, 0, comp_info.len_);
lst_comp_info.push_back(comp_info);
}
std::list<CompareInfo>::iterator it;
std::list<RangeCompareInfo>::iterator it_range;
for (it = lst_comp_info2.begin(); it != lst_comp_info2.end(); ++it) {
(*it).offset_ += comp_info.len_ + first_len;
lst_comp_info.push_back(*it);
}
for (it_range = lst_range_comp_info2.begin(); it_range != lst_range_comp_info2.end(); ++it_range) {
(*it_range).offset_ += comp_info.len_ + first_len;
lst_range_comp_info.push_back(*it_range);
}
if (has_ipv4) {
for (it = lst_comp_info_ipv4.begin(); it != lst_comp_info_ipv4.end(); ++it) {
lst_comp_info.push_back(*it);
}
for (it_range = lst_range_comp_info_ipv4.begin(); it_range != lst_range_comp_info_ipv4.end(); ++it_range) {
lst_range_comp_info.push_back(*it_range);
}
}
} else if (!result_shortening[0].empty() && result_shortening[1].empty()) {
// uint8_t* p_first_ipv6 = NULL;
int first_len = IPv6PartAddressStringToUINT8(result_shortening[0],
lst_comp_info, lst_range_comp_info);
int ipv4_len(0);
if (has_ipv4) {
ipv4_len = 4;
}
if (first_len + ipv4_len > 16) {
char str[256];
snprintf(str, sizeof(str), "IPv6 Address must be 16 octets: %d octets",
first_len + ipv4_len);
throw InvalidFieldValueException(str);
}
CompareInfo comp_info;
comp_info.offset_ = first_len;
comp_info.len_ = 16 - (first_len + ipv4_len);
if (comp_info.len_ > 0) {
comp_info.p_value_ = new uint8_t[comp_info.len_];
memset(comp_info.p_value_, 0, comp_info.len_);
lst_comp_info.push_back(comp_info);
}
if (has_ipv4) {
std::list<CompareInfo>::iterator it;
std::list<RangeCompareInfo>::iterator it_range;
for (it = lst_comp_info_ipv4.begin(); it != lst_comp_info_ipv4.end(); ++it) {
lst_comp_info.push_back(*it);
}
for (it_range = lst_range_comp_info_ipv4.begin(); it_range != lst_range_comp_info_ipv4.end(); ++it_range) {
lst_range_comp_info.push_back(*it_range);
}
}
} else if (result_shortening[0].empty() && !result_shortening[1].empty()) {
std::list<CompareInfo> lst_comp_info2;
std::list<RangeCompareInfo> lst_range_comp_info2;
int second_len = IPv6PartAddressStringToUINT8(result_shortening[1],
lst_comp_info2, lst_range_comp_info2);
int ipv4_len(0);
if (has_ipv4) {
ipv4_len = 4;
}
if (second_len + ipv4_len > 16) {
char str[256];
snprintf(str, sizeof(str), "IPv6 Address must be 16 octets: %d octets",
second_len + ipv4_len);
throw InvalidFieldValueException(str);
}
CompareInfo comp_info;
comp_info.offset_ = 0;
comp_info.len_ = 16 - (second_len + ipv4_len);
if (comp_info.len_ > 0) {
comp_info.p_value_ = new uint8_t[comp_info.len_];
memset(comp_info.p_value_, 0, comp_info.len_);
lst_comp_info.push_back(comp_info);
}
std::list<CompareInfo>::iterator it;
std::list<RangeCompareInfo>::iterator it_range;
for (it = lst_comp_info2.begin(); it != lst_comp_info2.end(); ++it) {
(*it).offset_ += comp_info.len_;
lst_comp_info.push_back(*it);
}
for (it_range = lst_range_comp_info2.begin(); it_range != lst_range_comp_info2.end(); ++it_range) {
(*it_range).offset_ += comp_info.len_;
lst_range_comp_info.push_back(*it_range);
}
if (has_ipv4) {
for (it = lst_comp_info_ipv4.begin(); it != lst_comp_info_ipv4.end(); ++it) {
lst_comp_info.push_back(*it);
}
for (it_range = lst_range_comp_info_ipv4.begin(); it_range != lst_range_comp_info_ipv4.end(); ++it_range) {
lst_range_comp_info.push_back(*it_range);
}
}
} else { // ::
int ipv4_len(0);
if (has_ipv4) {
ipv4_len = 4;
}
CompareInfo comp_info;
comp_info.offset_ = 0;
comp_info.len_ = 16 - ipv4_len;
if (comp_info.len_ > 0) {
comp_info.p_value_ = new uint8_t[comp_info.len_];
memset(comp_info.p_value_, 0, comp_info.len_);
lst_comp_info.push_back(comp_info);
}
if (has_ipv4) {
std::list<CompareInfo>::iterator it;
std::list<RangeCompareInfo>::iterator it_range;
for (it = lst_comp_info_ipv4.begin(); it != lst_comp_info_ipv4.end(); ++it) {
lst_comp_info.push_back(*it);
}
for (it_range = lst_range_comp_info_ipv4.begin(); it_range != lst_range_comp_info_ipv4.end(); ++it_range) {
lst_range_comp_info.push_back(*it_range);
}
}
}
} else {
throw InvalidFieldValueException("The format of IPv6 is incorrect: " + str);
}
}
int IPv6AddressBase::IPv6PartAddressStringToUINT8(const std::string& str
, std::list<CompareInfo> &lst_comp_info
, std::list<RangeCompareInfo> &lst_range_comp_info) {
std::vector < std::string > result_colon;
boost::algorithm::split_regex(result_colon, str, boost::regex(":"));
int result_colon_len = static_cast<int>(result_colon.size());
// for the case like: 2001:0db8:0000:0000:0000:ff00:
if (result_colon[result_colon_len - 1].empty())
result_colon_len--;
int len = result_colon_len * 2;
uint8_t* ipv6 = new uint8_t[len];
if (result_colon_len <= 8) {
try {
uint8_t offset(0);
uint8_t length(0);
for (int i = 0; i < result_colon_len; ++i) {
if (result_colon[i] == "*") {
if (length != 0) {
CompareInfo comp_info;
comp_info.offset_ = offset;
comp_info.len_ = length;
comp_info.p_value_ = new uint8_t[length];
memcpy(comp_info.p_value_, ipv6 + offset, length);
lst_comp_info.push_back(comp_info);
}
offset += length + 2;
length = 0;
} else if (result_colon[i].find("-") != std::string::npos) {
// boost::regex regex_range("(((\\d)|(a-f)|(A-F)){1,4})\\-(((\\d)|(a-f)|(A-F)){1,4})");
boost::match_results<std::string::const_iterator> what;
boost::match_flag_type flags = boost::match_default;
if (boost::regex_match(result_colon[i], what, regex_range, flags)) {
// 1, 6
std::string lower_str = std::string(what[1].first, what[1].second);
std::string upper_str = std::string(what[6].first, what[6].second);
//
RangeCompareInfo range_comp_info;
range_comp_info.type_ = 1;
size_t str_len = lower_str.length();
if (str_len == 4) {
range_comp_info.lower_v6[0] = ((GetUINTbyHexchar(lower_str[0]) << 4)
& 0xF0) + ((GetUINTbyHexchar(lower_str[1])) & 0x0F);
range_comp_info.lower_v6[1] = ((GetUINTbyHexchar(lower_str[2]) << 4)
& 0xF0) + ((GetUINTbyHexchar(lower_str[3])) & 0x0F);
} else if (str_len == 3) {
range_comp_info.lower_v6[0] = (GetUINTbyHexchar(lower_str[0])) & 0x0F;
range_comp_info.lower_v6[1] = ((GetUINTbyHexchar(lower_str[1]) << 4)
& 0xF0) + ((GetUINTbyHexchar(lower_str[2])) & 0x0F);
} else if (str_len == 2) {
range_comp_info.lower_v6[0] = 0;
range_comp_info.lower_v6[1] = ((GetUINTbyHexchar(lower_str[0]) << 4)
& 0xF0) + ((GetUINTbyHexchar(lower_str[1])) & 0x0F);
} else {
range_comp_info.lower_v6[0] = 0;
range_comp_info.lower_v6[1] = (GetUINTbyHexchar(lower_str[0])) & 0x0F;
}
str_len = upper_str.length();
if (str_len == 4) {
range_comp_info.upper_v6[0] = ((GetUINTbyHexchar(upper_str[0]) << 4)
& 0xF0) + ((GetUINTbyHexchar(upper_str[1])) & 0x0F);
range_comp_info.upper_v6[1] = ((GetUINTbyHexchar(upper_str[2]) << 4)
& 0xF0) + ((GetUINTbyHexchar(upper_str[3])) & 0x0F);
} else if (str_len == 3) {
range_comp_info.upper_v6[0] = (GetUINTbyHexchar(upper_str[0])) & 0x0F;
range_comp_info.upper_v6[1] = ((GetUINTbyHexchar(upper_str[1]) << 4)
& 0xF0) + ((GetUINTbyHexchar(upper_str[2])) & 0x0F);
} else if (str_len == 2) {
range_comp_info.upper_v6[0] = 0;
range_comp_info.upper_v6[1] = ((GetUINTbyHexchar(upper_str[0]) << 4)
& 0xF0) + ((GetUINTbyHexchar(upper_str[1])) & 0x0F);
} else {
range_comp_info.upper_v6[0] = 0;
range_comp_info.upper_v6[1] = (GetUINTbyHexchar(upper_str[0])) & 0x0F;
}
if (memcmp(range_comp_info.lower_v6, range_comp_info.upper_v6, 2) > 0) {
// swap
uint8_t tmp;
for (int j = 0; j < 2; ++j) {
tmp = range_comp_info.lower_v6[j];
range_comp_info.lower_v6[j] = range_comp_info.upper_v6[j];
range_comp_info.upper_v6[j] = tmp;
}
}
range_comp_info.offset_ = 2*i;
lst_range_comp_info.push_back(range_comp_info);
if (length != 0) {
CompareInfo comp_info;
comp_info.offset_ = offset;
comp_info.len_ = length;
comp_info.p_value_ = new uint8_t[length];
memcpy(comp_info.p_value_, ipv6 + offset, length);
lst_comp_info.push_back(comp_info);
}
offset += length + 2;
length = 0;
//
} else {
delete[] ipv6;
char str[256];
snprintf(str, sizeof(str),
"The format of ipv6 range is incorrect:%s",
result_colon[i].c_str());
throw InvalidFieldValueException(str);
}
} else {
size_t str_len = result_colon[i].length();
if (str_len == 4) {
*(ipv6 + 2*i) = ((GetUINTbyHexchar(result_colon[i][0]) << 4)
& 0xF0) + ((GetUINTbyHexchar(result_colon[i][1])) & 0x0F);
*(ipv6 +2*i + 1) = ((GetUINTbyHexchar(result_colon[i][2]) << 4)
& 0xF0) + ((GetUINTbyHexchar(result_colon[i][3])) & 0x0F);
} else if (str_len == 3) {
*(ipv6 + 2 * i) = (GetUINTbyHexchar(result_colon[i][0])) & 0x0F;
*(ipv6 + 2 * i + 1) = ((GetUINTbyHexchar(result_colon[i][1]) << 4)
& 0xF0) + ((GetUINTbyHexchar(result_colon[i][2])) & 0x0F);
} else if (str_len == 2) {
*(ipv6 + 2 * i) = 0;
*(ipv6 + 2 * i + 1) = ((GetUINTbyHexchar(result_colon[i][0]) << 4)
& 0xF0) + ((GetUINTbyHexchar(result_colon[i][1])) & 0x0F);
} else {
*(ipv6 + 2 * i) = 0;
*(ipv6 + 2 * i + 1) = (GetUINTbyHexchar(result_colon[i][0])) & 0x0F;
}
length += 2;
}
}
if (length != 0) {
CompareInfo comp_info;
comp_info.offset_ = offset;
comp_info.len_ = length;
comp_info.p_value_ = new uint8_t[length];
memcpy(comp_info.p_value_, ipv6 + offset, length);
lst_comp_info.push_back(comp_info);
}
} catch(InvalidFieldValueException &e) {
delete[] ipv6;
throw;
}
} else {
delete[] ipv6;
char str[256];
snprintf(str, sizeof(str),
"IPv6 Address must be less than or equal 8 parts: %d parts",
result_colon_len);
throw InvalidFieldValueException(str);
}
delete[] ipv6;
return len;
}
void IPv6AddressBase::ExatractIPv4Info(const std::string& str1, const std::string& str2
, const std::string& str3, const std::string& str4
, std::list<CompareInfo> &lst_comp_info
, std::list<RangeCompareInfo> &lst_range_comp_info) {
uint8_t offset = 12;
size_t pos;
if (str1 == "*") {
} else if ((pos = str1.find("-")) != std::string::npos) {
uint8_t lower = static_cast<uint8_t>(atoi(str1.substr(0, pos).c_str()));
uint8_t upper = static_cast<uint8_t>(atoi(str1.substr(pos+1).c_str()));
if (lower > upper) {
uint8_t tmp = lower;
lower = upper;
upper = tmp;
}
RangeCompareInfo range_comp_info;
range_comp_info.type_ = 0;
range_comp_info.offset_ = offset;
range_comp_info.upper_ = upper;
range_comp_info.lower_ = lower;
lst_range_comp_info.push_back(range_comp_info);
} else {
CompareInfo comp_info;
comp_info.offset_ = offset;
comp_info.len_ = 1;
comp_info.p_value_ = new uint8_t(static_cast<uint8_t>(atoi(str1.c_str())));
lst_comp_info.push_back(comp_info);
}
offset++;
if (str2 == "*") {
} else if ((pos = str2.find("-")) != std::string::npos) {
uint8_t lower = static_cast<uint8_t>(atoi(str2.substr(0, pos).c_str()));
uint8_t upper = static_cast<uint8_t>(atoi(str2.substr(pos+1).c_str()));
if (lower > upper) {
uint8_t tmp = lower;
lower = upper;
upper = tmp;
}
RangeCompareInfo range_comp_info;
range_comp_info.type_ = 0;
range_comp_info.offset_ = offset;
range_comp_info.upper_ = upper;
range_comp_info.lower_ = lower;
lst_range_comp_info.push_back(range_comp_info);
} else {
uint8_t value = static_cast<uint8_t>(atoi(str2.c_str()));
bool needAdd(true);
if (lst_comp_info.size() > 0) {
std::list<CompareInfo>::reverse_iterator it = lst_comp_info.rbegin();
if (((*it).offset_ + (*it).len_) == offset) {
uint8_t* p_value = new uint8_t[(*it).len_ + 1];
for (uint8_t i = 0; i < (*it).len_; ++i) {
p_value[i] = (*it).p_value_[i];
}
p_value[(*it).len_] = value;
(*it).len_ += 1;
delete []((*it).p_value_);
(*it).p_value_ = p_value;
needAdd = false;
}
}
if (needAdd) {
CompareInfo comp_info;
comp_info.offset_ = offset;
comp_info.len_ = 1;
comp_info.p_value_ = new uint8_t(value);
lst_comp_info.push_back(comp_info);
}
}
offset++;
if (str3 == "*") {
} else if ((pos = str3.find("-")) != std::string::npos) {
uint8_t lower = static_cast<uint8_t>(atoi(str3.substr(0, pos).c_str()));
uint8_t upper = static_cast<uint8_t>(atoi(str3.substr(pos+1).c_str()));
if (lower > upper) {
uint8_t tmp = lower;
lower = upper;
upper = tmp;
}
RangeCompareInfo range_comp_info;
range_comp_info.type_ = 0;
range_comp_info.offset_ = offset;
range_comp_info.upper_ = upper;
range_comp_info.lower_ = lower;
lst_range_comp_info.push_back(range_comp_info);
} else {
uint8_t value = static_cast<uint8_t>(atoi(str3.c_str()));
bool needAdd(true);
if (lst_comp_info.size() > 0) {
std::list<CompareInfo>::reverse_iterator it = lst_comp_info.rbegin();
if (((*it).offset_ + (*it).len_) == offset) {
uint8_t* p_value = new uint8_t[(*it).len_ + 1];
for (uint8_t i = 0; i < (*it).len_; ++i) {
p_value[i] = (*it).p_value_[i];
}
p_value[(*it).len_] = value;
(*it).len_ += 1;
delete []((*it).p_value_);
(*it).p_value_ = p_value;
needAdd = false;
}
}
if (needAdd) {
CompareInfo comp_info;
comp_info.offset_ = offset;
comp_info.len_ = 1;
comp_info.p_value_ = new uint8_t(value);
lst_comp_info.push_back(comp_info);
}
}
offset++;
if (str4 == "*") {
} else if ((pos = str4.find("-")) != std::string::npos) {
uint8_t lower = static_cast<uint8_t>(atoi(str4.substr(0, pos).c_str()));
uint8_t upper = static_cast<uint8_t>(atoi(str4.substr(pos+1).c_str()));
if (lower > upper) {
uint8_t tmp = lower;
lower = upper;
upper = tmp;
}
RangeCompareInfo range_comp_info;
range_comp_info.type_ = 0;
range_comp_info.offset_ = offset;
range_comp_info.upper_ = upper;
range_comp_info.lower_ = lower;
lst_range_comp_info.push_back(range_comp_info);
} else {
uint8_t value = static_cast<uint8_t>(atoi(str4.c_str()));
bool needAdd(true);
if (lst_comp_info.size() > 0) {
std::list<CompareInfo>::reverse_iterator it = lst_comp_info.rbegin();
if (((*it).offset_ + (*it).len_) == offset) {
uint8_t* p_value = new uint8_t[(*it).len_ + 1];
for (uint8_t i = 0; i < (*it).len_; ++i) {
p_value[i] = (*it).p_value_[i];
}
p_value[(*it).len_] = value;
(*it).len_ += 1;
delete []((*it).p_value_);
(*it).p_value_ = p_value;
needAdd = false;
}
}
if (needAdd) {
CompareInfo comp_info;
comp_info.offset_ = offset;
comp_info.len_ = 1;
comp_info.p_value_ = new uint8_t(value);
lst_comp_info.push_back(comp_info);
}
}
}
uint8_t IPv6AddressBase::GetUINTbyHexchar(char ch)
throw(InvalidFieldValueException) {
uint8_t ret = 0;
switch (ch) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': {
int value = ch - '0';
ret = static_cast<uint8_t>(value);
}
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f': {
int value = ch - 'a';
ret = static_cast<uint8_t>(value + 10);
}
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F': {
int value = ch - 'A';
ret = static_cast<uint8_t>(value + 10);
}
break;
default: {
std::string str("The vaule in the IPv6 address shouel be"
" 0-9 and a-f or A-F, your IP address contains:");
str += ch;
throw InvalidFieldValueException(str);
}
}
return ret;
}
}
}
| 39.503279 | 115 | 0.588745 | [
"vector"
] |
42d1330eb19f5546cc23f92331466404b0c43562 | 4,841 | cpp | C++ | Contest/2015 Arab Collegiate Programming Contest/F.cpp | HeRaNO/OI-ICPC-Codes | 4a4639cd3e347b472520065ca6ab8caadde6906d | [
"MIT"
] | 18 | 2019-01-01T13:16:59.000Z | 2022-02-28T04:51:50.000Z | Contest/2015 Arab Collegiate Programming Contest/F.cpp | HeRaNO/OI-ICPC-Codes | 4a4639cd3e347b472520065ca6ab8caadde6906d | [
"MIT"
] | null | null | null | Contest/2015 Arab Collegiate Programming Contest/F.cpp | HeRaNO/OI-ICPC-Codes | 4a4639cd3e347b472520065ca6ab8caadde6906d | [
"MIT"
] | 5 | 2019-09-13T08:48:17.000Z | 2022-02-19T06:59:03.000Z | #include <bits/stdc++.h>
#define ll long long
#define ls id << 1
#define rs id << 1 | 1
#define mem(array, value, size, type) memset(array, value, ((size) + 5) * sizeof(type))
#define memarray(array, value) memset(array, value, sizeof(array))
#define fillarray(array, value, begin, end) fill((array) + (begin), (array) + (end) + 1, value)
#define fillvector(v, value) fill((v).begin(), (v).end(), value)
#define pb(x) push_back(x)
#define st(x) (1LL << (x))
#define pii pair<int, int>
#define mp(a, b) make_pair((a), (b))
#define Flush fflush(stdout)
#define vecfirst (*vec.begin())
#define veclast (*vec.rbegin())
#define vecall(v) (v).begin(), (v).end()
#define vecupsort(v) (sort((v).begin(), (v).end()))
#define vecdownsort(v, type) (sort(vecall(v), greater<type>()))
#define veccmpsort(v, cmp) (sort(vecall(v), cmp))
using namespace std;
const int N = 500050;
const int inf = 0x3f3f3f3f;
const ll llinf = 0x3f3f3f3f3f3f3f3f;
const int mod = 998244353;
const int MOD = 1e9 + 7;
const double PI = acos(-1.0);
clock_t TIME__START, TIME__END;
void program_end()
{
#ifdef ONLINE
printf("\n\nTime used: %.6lf(s)\n", ((double)TIME__END - TIME__START) / 1000);
system("pause");
#endif
}
int n, m;
const int MAXN = 500050, MAXM = 500050;
struct tarjan_one_direction
{
int head[MAXN], _next[MAXM], to[MAXM], ecnt;
int nodenum[MAXN];
void add_Edge(int u, int v)
{
_next[++ecnt] = head[u];
to[ecnt] = v;
head[u] = ecnt;
_next[++ecnt] = head[v];
to[ecnt] = u;
head[v] = ecnt;
}
int tot, dfn[MAXN], low[MAXN];
int cir[MAXN], cirnum;
stack<int> s;
void init(int n, int m)
{
ecnt = 0;
mem(head, 0, n, int);
mem(_next, 0, m * 2, int);
mem(to, 0, m * 2, int);
tot = 0;
while (!s.empty())
s.pop();
cirnum = 0;
mem(dfn, 0, n, int);
mem(low, 0, n, int);
mem(cir, 0, n, int);
mem(nodenum, 0, n, int);
}
void tarjan(int u, int f)
{
dfn[u] = low[u] = ++tot;
s.push(u);
for (int i = head[u]; i; i = _next[i])
{
int v = to[i];
if (f == v)
continue;
if (!dfn[v])
{
tarjan(v, u);
low[u] = min(low[u], low[v]);
}
else if (!cir[v])
low[u] = min(low[u], dfn[v]);
}
if (dfn[u] == low[u])
{
cir[u] = ++cirnum;
nodenum[cirnum]++;
while (s.top() != u)
{
cir[s.top()] = cirnum;
nodenum[cirnum]++;
s.pop();
}
s.pop();
}
}
void solve()
{
for (int i = 1; i <= n; i++)
if (!dfn[i])
tarjan(i, 0);
}
} tarjan;
vector<int> e[MAXN];
int col[MAXN], sz[MAXN];
bool vis[MAXN];
ll ans;
ll f[MAXN], dep[MAXN];
int nowsz;
vector<int> vec;
ll dfs(int u, int fa)
{
nowsz++;
sz[u] = 1;
for (auto v : e[u])
{
if (v == fa)
continue;
dep[v] = dep[u] + 1;
sz[u] += dfs(v, u);
}
return sz[u];
}
void dfs1(int n, int u, int fa)
{
for (auto v : e[u])
{
if (v == fa)
continue;
f[v] = f[u];
ll tmp = n - sz[v] - 1;
f[v] += tmp - (sz[v] - 1);
dfs1(n, v, u);
}
}
void dfs3(int u, int fa)
{
vis[u] = 1;
vec.push_back(u);
for (int i = tarjan.head[u]; i; i = tarjan._next[i])
{
int v = tarjan.to[i];
if (v == fa)
continue;
if (col[u] != col[v])
{
e[u].push_back(v), e[v].push_back(u);
dfs3(v, u);
}
}
}
inline void solve()
{
ans = 0;
scanf("%d%d", &n, &m);
for (int i = 0; i <= n; ++i)
e[i].resize(0);
mem(col, 0, n, int);
mem(vis, 0, n, bool);
tarjan.init(n, m);
for (int i = 1; i <= m; ++i)
{
int x, y;
scanf("%d%d", &x, &y);
tarjan.add_Edge(x, y);
}
tarjan.solve();
for (int i = 1; i <= n; ++i)
col[i] = tarjan.cir[i];
for (int i = 1; i <= n; ++i)
{
if (!vis[i])
{
vec.resize(0);
dfs3(i, 0);
dfs(i, 0);
vecupsort(vec);
vec.resize(unique(vecall(vec)) - vec.begin());
ll sum = 0;
for (auto u : vec)
sum += dep[u];
f[i] = sum;
dfs1(nowsz, i, 0);
for (auto u : vec)
ans += f[u];
for (auto u : vec)
f[u] = 0, dep[u] = 0, sz[u] = 0, e[u].resize(0);
nowsz = 0;
}
}
// for (int i = 1; i <= n; ++i)
// {
// if (col[tarjan.cir[i]] || vis[tarjan.cir[i]])
// continue;
// vec.resize(0);
// dfs(tarjan.cir[i], 0);
// vecupsort(vec);
// vec.resize(unique(vecall(vec)) - vec.begin());
// ll sum = 0;
// for (auto u : vec)
// sum += dep[u];
// f[tarjan.cir[i]] = sum;
// dfs1(nowsz, tarjan.cir[i], 0);
// for (auto u : vec)
// ans += f[u];
// for (auto u : vec)
// f[u] = 0, dep[u] = 0, sz[u] = 0;
// nowsz = 0;
// }
// for (int i = 1; i <= tarjan.cirnum; ++i)
// {
// if (!col[i])
// continue;
// for (auto v : e[i])
// {
// if (col[v])
// ans++;
// }
// }
printf("%lld\n", ans / 2);
}
int main()
{
TIME__START = clock();
int Test = 1;
scanf("%d", &Test);
while (Test--)
{
solve();
// if (Test)
// putchar('\n');
}
TIME__END = clock();
program_end();
return 0;
} | 20.25523 | 95 | 0.512497 | [
"vector"
] |
42d2ac0ec4f69e2e0c1c31e4ea966e7729b8d3d1 | 16,209 | cpp | C++ | engine/atf_test.cpp | 0mp/kyua | 8713ff0cbf96564ae938b9b853038af5535b6882 | [
"BSD-3-Clause"
] | null | null | null | engine/atf_test.cpp | 0mp/kyua | 8713ff0cbf96564ae938b9b853038af5535b6882 | [
"BSD-3-Clause"
] | null | null | null | engine/atf_test.cpp | 0mp/kyua | 8713ff0cbf96564ae938b9b853038af5535b6882 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2014 The Kyua Authors.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "engine/atf.hpp"
extern "C" {
#include <sys/stat.h>
#include <signal.h>
}
#include <atf-c++.hpp>
#include "engine/config.hpp"
#include "engine/scheduler.hpp"
#include "model/metadata.hpp"
#include "model/test_case.hpp"
#include "model/test_program_fwd.hpp"
#include "model/test_result.hpp"
#include "utils/config/tree.ipp"
#include "utils/datetime.hpp"
#include "utils/env.hpp"
#include "utils/format/containers.ipp"
#include "utils/format/macros.hpp"
#include "utils/fs/operations.hpp"
#include "utils/fs/path.hpp"
#include "utils/optional.ipp"
#include "utils/stacktrace.hpp"
#include "utils/test_utils.ipp"
namespace config = utils::config;
namespace datetime = utils::datetime;
namespace fs = utils::fs;
namespace scheduler = engine::scheduler;
using utils::none;
namespace {
/// Runs one plain test program and checks its result.
///
/// \param program_name Basename of the test program to run.
/// \param root Path to the base of the test suite.
/// \param names_filter Whitespace-separated list of test cases that the helper
/// test program is allowed to expose.
/// \param user_config User-provided configuration.
///
/// \return The list of loaded test cases.
static model::test_cases_map
list_one(const char* program_name,
const fs::path& root,
const char* names_filter = NULL,
config::tree user_config = engine::empty_config())
{
scheduler::scheduler_handle handle = scheduler::setup();
const scheduler::lazy_test_program program(
"atf", fs::path(program_name), root, "the-suite",
model::metadata_builder().build(), user_config, handle);
if (names_filter != NULL)
utils::setenv("TEST_CASES", names_filter);
const model::test_cases_map test_cases = handle.list_tests(
&program, user_config);
handle.cleanup();
return test_cases;
}
/// Runs a bogus test program and checks the error result.
///
/// \param exp_error Expected error string to find.
/// \param program_name Basename of the test program to run.
/// \param root Path to the base of the test suite.
/// \param names_filter Whitespace-separated list of test cases that the helper
/// test program is allowed to expose.
static void
check_list_one_fail(const char* exp_error,
const char* program_name,
const fs::path& root,
const char* names_filter = NULL)
{
const model::test_cases_map test_cases = list_one(
program_name, root, names_filter);
ATF_REQUIRE_EQ(1, test_cases.size());
const model::test_case& test_case = test_cases.begin()->second;
ATF_REQUIRE_EQ("__test_cases_list__", test_case.name());
ATF_REQUIRE(test_case.fake_result());
ATF_REQUIRE_MATCH(exp_error,
test_case.fake_result().get().reason());
}
/// Runs one plain test program and checks its result.
///
/// \param tc Pointer to the calling test case, to obtain srcdir.
/// \param test_case_name Name of the "test case" to select from the helper
/// program.
/// \param exp_result The expected result.
/// \param user_config User-provided configuration.
/// \param check_empty_output If true, verify that the output of the test is
/// silent. This is just a hack to implement one of the test cases; we'd
/// easily have a nicer abstraction here...
static void
run_one(const atf::tests::tc* tc, const char* test_case_name,
const model::test_result& exp_result,
config::tree user_config = engine::empty_config(),
const bool check_empty_output = false)
{
scheduler::scheduler_handle handle = scheduler::setup();
const model::test_program_ptr program(new scheduler::lazy_test_program(
"atf", fs::path("atf_helpers"), fs::path(tc->get_config_var("srcdir")),
"the-suite", model::metadata_builder().build(),
user_config, handle));
(void)handle.spawn_test(program, test_case_name, user_config);
scheduler::result_handle_ptr result_handle = handle.wait_any();
const scheduler::test_result_handle* test_result_handle =
dynamic_cast< const scheduler::test_result_handle* >(
result_handle.get());
atf::utils::cat_file(result_handle->stdout_file().str(), "stdout: ");
atf::utils::cat_file(result_handle->stderr_file().str(), "stderr: ");
ATF_REQUIRE_EQ(exp_result, test_result_handle->test_result());
if (check_empty_output) {
ATF_REQUIRE(atf::utils::compare_file(result_handle->stdout_file().str(),
""));
ATF_REQUIRE(atf::utils::compare_file(result_handle->stderr_file().str(),
""));
}
result_handle->cleanup();
result_handle.reset();
handle.cleanup();
}
} // anonymous namespace
ATF_TEST_CASE_WITHOUT_HEAD(list__ok);
ATF_TEST_CASE_BODY(list__ok)
{
const model::test_cases_map test_cases = list_one(
"atf_helpers", fs::path(get_config_var("srcdir")), "pass crash");
const model::test_cases_map exp_test_cases = model::test_cases_map_builder()
.add("crash")
.add("pass", model::metadata_builder()
.set_description("Always-passing test case")
.build())
.build();
ATF_REQUIRE_EQ(exp_test_cases, test_cases);
}
ATF_TEST_CASE_WITHOUT_HEAD(list__configuration_variables);
ATF_TEST_CASE_BODY(list__configuration_variables)
{
config::tree user_config = engine::empty_config();
user_config.set_string("test_suites.the-suite.var1", "value1");
user_config.set_string("test_suites.the-suite.var2", "value2");
const model::test_cases_map test_cases = list_one(
"atf_helpers", fs::path(get_config_var("srcdir")), "check_list_config",
user_config);
const model::test_cases_map exp_test_cases = model::test_cases_map_builder()
.add("check_list_config", model::metadata_builder()
.set_description("Found: var1=value1 var2=value2")
.build())
.build();
ATF_REQUIRE_EQ(exp_test_cases, test_cases);
}
ATF_TEST_CASE_WITHOUT_HEAD(list__current_directory);
ATF_TEST_CASE_BODY(list__current_directory)
{
const fs::path helpers = fs::path(get_config_var("srcdir")) / "atf_helpers";
ATF_REQUIRE(::symlink(helpers.c_str(), "atf_helpers") != -1);
const model::test_cases_map test_cases = list_one(
"atf_helpers", fs::path("."), "pass");
const model::test_cases_map exp_test_cases = model::test_cases_map_builder()
.add("pass", model::metadata_builder()
.set_description("Always-passing test case")
.build())
.build();
ATF_REQUIRE_EQ(exp_test_cases, test_cases);
}
ATF_TEST_CASE_WITHOUT_HEAD(list__relative_path);
ATF_TEST_CASE_BODY(list__relative_path)
{
const fs::path helpers = fs::path(get_config_var("srcdir")) / "atf_helpers";
ATF_REQUIRE(::mkdir("dir1", 0755) != -1);
ATF_REQUIRE(::mkdir("dir1/dir2", 0755) != -1);
ATF_REQUIRE(::symlink(helpers.c_str(), "dir1/dir2/atf_helpers") != -1);
const model::test_cases_map test_cases = list_one(
"dir2/atf_helpers", fs::path("dir1"), "pass");
const model::test_cases_map exp_test_cases = model::test_cases_map_builder()
.add("pass", model::metadata_builder()
.set_description("Always-passing test case")
.build())
.build();
ATF_REQUIRE_EQ(exp_test_cases, test_cases);
}
ATF_TEST_CASE_WITHOUT_HEAD(list__missing_test_program);
ATF_TEST_CASE_BODY(list__missing_test_program)
{
check_list_one_fail("Cannot find test program", "non-existent",
fs::current_path());
}
ATF_TEST_CASE_WITHOUT_HEAD(list__not_a_test_program);
ATF_TEST_CASE_BODY(list__not_a_test_program)
{
atf::utils::create_file("not-valid", "garbage\n");
ATF_REQUIRE(::chmod("not-valid", 0755) != -1);
check_list_one_fail("Invalid test program format", "not-valid",
fs::current_path());
}
ATF_TEST_CASE_WITHOUT_HEAD(list__no_permissions);
ATF_TEST_CASE_BODY(list__no_permissions)
{
atf::utils::create_file("not-executable", "garbage\n");
check_list_one_fail("Permission denied to run test program",
"not-executable", fs::current_path());
}
ATF_TEST_CASE_WITHOUT_HEAD(list__abort);
ATF_TEST_CASE_BODY(list__abort)
{
check_list_one_fail("Test program received signal", "atf_helpers",
fs::path(get_config_var("srcdir")),
"crash_head");
}
ATF_TEST_CASE_WITHOUT_HEAD(list__empty);
ATF_TEST_CASE_BODY(list__empty)
{
check_list_one_fail("No test cases", "atf_helpers",
fs::path(get_config_var("srcdir")),
"");
}
ATF_TEST_CASE_WITHOUT_HEAD(list__stderr_not_quiet);
ATF_TEST_CASE_BODY(list__stderr_not_quiet)
{
check_list_one_fail("Test case list wrote to stderr", "atf_helpers",
fs::path(get_config_var("srcdir")),
"output_in_list");
}
ATF_TEST_CASE_WITHOUT_HEAD(test__body_only__passes);
ATF_TEST_CASE_BODY(test__body_only__passes)
{
const model::test_result exp_result(model::test_result_passed);
run_one(this, "pass", exp_result);
}
ATF_TEST_CASE_WITHOUT_HEAD(test__body_only__crashes);
ATF_TEST_CASE_BODY(test__body_only__crashes)
{
utils::prepare_coredump_test(this);
const model::test_result exp_result(
model::test_result_broken,
F("Premature exit; test case received signal %s (core dumped)") %
SIGABRT);
run_one(this, "crash", exp_result);
}
ATF_TEST_CASE_WITHOUT_HEAD(test__body_only__times_out);
ATF_TEST_CASE_BODY(test__body_only__times_out)
{
config::tree user_config = engine::empty_config();
user_config.set_string("test_suites.the-suite.control_dir",
fs::current_path().str());
user_config.set_string("test_suites.the-suite.timeout", "1");
const model::test_result exp_result(
model::test_result_broken, "Test case body timed out");
run_one(this, "timeout_body", exp_result, user_config);
ATF_REQUIRE(!atf::utils::file_exists("cookie"));
}
ATF_TEST_CASE_WITHOUT_HEAD(test__body_only__configuration_variables);
ATF_TEST_CASE_BODY(test__body_only__configuration_variables)
{
config::tree user_config = engine::empty_config();
user_config.set_string("test_suites.the-suite.first", "some value");
user_config.set_string("test_suites.the-suite.second", "some other value");
const model::test_result exp_result(model::test_result_passed);
run_one(this, "check_configuration_variables", exp_result, user_config);
}
ATF_TEST_CASE_WITHOUT_HEAD(test__body_only__no_atf_run_warning);
ATF_TEST_CASE_BODY(test__body_only__no_atf_run_warning)
{
const model::test_result exp_result(model::test_result_passed);
run_one(this, "pass", exp_result, engine::empty_config(), true);
}
ATF_TEST_CASE_WITHOUT_HEAD(test__body_and_cleanup__body_times_out);
ATF_TEST_CASE_BODY(test__body_and_cleanup__body_times_out)
{
config::tree user_config = engine::empty_config();
user_config.set_string("test_suites.the-suite.control_dir",
fs::current_path().str());
user_config.set_string("test_suites.the-suite.timeout", "1");
const model::test_result exp_result(
model::test_result_broken, "Test case body timed out");
run_one(this, "timeout_body", exp_result, user_config);
ATF_REQUIRE(!atf::utils::file_exists("cookie"));
ATF_REQUIRE(atf::utils::file_exists("cookie.cleanup"));
}
ATF_TEST_CASE_WITHOUT_HEAD(test__body_and_cleanup__cleanup_crashes);
ATF_TEST_CASE_BODY(test__body_and_cleanup__cleanup_crashes)
{
const model::test_result exp_result(
model::test_result_broken,
"Test case cleanup did not terminate successfully");
run_one(this, "crash_cleanup", exp_result);
}
ATF_TEST_CASE_WITHOUT_HEAD(test__body_and_cleanup__cleanup_times_out);
ATF_TEST_CASE_BODY(test__body_and_cleanup__cleanup_times_out)
{
config::tree user_config = engine::empty_config();
user_config.set_string("test_suites.the-suite.control_dir",
fs::current_path().str());
scheduler::cleanup_timeout = datetime::delta(1, 0);
const model::test_result exp_result(
model::test_result_broken, "Test case cleanup timed out");
run_one(this, "timeout_cleanup", exp_result, user_config);
ATF_REQUIRE(!atf::utils::file_exists("cookie"));
}
ATF_TEST_CASE_WITHOUT_HEAD(test__body_and_cleanup__expect_timeout);
ATF_TEST_CASE_BODY(test__body_and_cleanup__expect_timeout)
{
config::tree user_config = engine::empty_config();
user_config.set_string("test_suites.the-suite.control_dir",
fs::current_path().str());
user_config.set_string("test_suites.the-suite.timeout", "1");
const model::test_result exp_result(
model::test_result_expected_failure, "Times out on purpose");
run_one(this, "expect_timeout", exp_result, user_config);
ATF_REQUIRE(!atf::utils::file_exists("cookie"));
ATF_REQUIRE(atf::utils::file_exists("cookie.cleanup"));
}
ATF_TEST_CASE_WITHOUT_HEAD(test__body_and_cleanup__shared_workdir);
ATF_TEST_CASE_BODY(test__body_and_cleanup__shared_workdir)
{
const model::test_result exp_result(model::test_result_passed);
run_one(this, "shared_workdir", exp_result);
}
ATF_INIT_TEST_CASES(tcs)
{
scheduler::register_interface(
"atf", std::shared_ptr< scheduler::interface >(
new engine::atf_interface()));
ATF_ADD_TEST_CASE(tcs, list__ok);
ATF_ADD_TEST_CASE(tcs, list__configuration_variables);
ATF_ADD_TEST_CASE(tcs, list__current_directory);
ATF_ADD_TEST_CASE(tcs, list__relative_path);
ATF_ADD_TEST_CASE(tcs, list__missing_test_program);
ATF_ADD_TEST_CASE(tcs, list__not_a_test_program);
ATF_ADD_TEST_CASE(tcs, list__no_permissions);
ATF_ADD_TEST_CASE(tcs, list__abort);
ATF_ADD_TEST_CASE(tcs, list__empty);
ATF_ADD_TEST_CASE(tcs, list__stderr_not_quiet);
ATF_ADD_TEST_CASE(tcs, test__body_only__passes);
ATF_ADD_TEST_CASE(tcs, test__body_only__crashes);
ATF_ADD_TEST_CASE(tcs, test__body_only__times_out);
ATF_ADD_TEST_CASE(tcs, test__body_only__configuration_variables);
ATF_ADD_TEST_CASE(tcs, test__body_only__no_atf_run_warning);
ATF_ADD_TEST_CASE(tcs, test__body_and_cleanup__body_times_out);
ATF_ADD_TEST_CASE(tcs, test__body_and_cleanup__cleanup_crashes);
ATF_ADD_TEST_CASE(tcs, test__body_and_cleanup__cleanup_times_out);
ATF_ADD_TEST_CASE(tcs, test__body_and_cleanup__expect_timeout);
ATF_ADD_TEST_CASE(tcs, test__body_and_cleanup__shared_workdir);
}
| 35.940133 | 80 | 0.718243 | [
"model"
] |
42d88f00d90b5043798ad58895783618d0f81531 | 260 | cpp | C++ | libs/core/render/src/gl/detail/bksge_core_render_gl_detail_clear_state.cpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 4 | 2018-06-10T13:35:32.000Z | 2021-06-03T14:27:41.000Z | libs/core/render/src/gl/detail/bksge_core_render_gl_detail_clear_state.cpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 566 | 2017-01-31T05:36:09.000Z | 2022-02-09T05:04:37.000Z | libs/core/render/src/gl/detail/bksge_core_render_gl_detail_clear_state.cpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 1 | 2018-07-05T04:40:53.000Z | 2018-07-05T04:40:53.000Z | /**
* @file bksge_core_render_gl_detail_clear_state.cpp
*
* @brief ClearState の実装
*
* @author myoukaku
*/
#include <bksge/fnd/config.hpp>
#if !defined(BKSGE_HEADER_ONLY)
#include <bksge/core/render/gl/detail/inl/clear_state_inl.hpp>
#endif
| 20 | 63 | 0.707692 | [
"render"
] |
42d98b8af17d0f97f4df60125981132501dda3c9 | 41,768 | cc | C++ | fluxml/FluxMLDocument.cc | ANTS-ON/FluxML | 6feb6f1da638db450351acc664964f5659197bd6 | [
"MIT"
] | 9 | 2019-05-27T18:01:09.000Z | 2022-01-07T11:26:52.000Z | fluxml/FluxMLDocument.cc | ANTS-ON/FluxML | 6feb6f1da638db450351acc664964f5659197bd6 | [
"MIT"
] | 17 | 2019-07-08T16:53:32.000Z | 2022-02-23T07:20:45.000Z | fluxml/FluxMLDocument.cc | ANTS-ON/FluxML | 6feb6f1da638db450351acc664964f5659197bd6 | [
"MIT"
] | 6 | 2019-07-12T10:26:22.000Z | 2022-02-11T09:46:44.000Z | #include <list>
#include <xercesc/dom/DOM.hpp>
#include "Error.h"
#include "Sort.h"
#include "charptr_map.h"
#include "charptr_array.h"
#include "Notation.h"
#include "Configuration.h"
#include "Info.h"
#include "Pool.h"
#include "IsoReaction.h"
#include "DOMWriter.h"
#include "DOMWriterImpl.h"
#include "FluxMLContentObject.h"
#include "FluxMLConfiguration.h"
#include "FluxMLReactionNetwork.h"
#include "FluxMLConstraints.h"
#include "FluxMLInfo.h"
#include "FluxMLUnicodeConstants.h"
#include "MMUnicodeConstants.h"
#include "UnicodeTools.h"
#include "StoichMatrixInteger.h"
#include "XMLElement.h"
#include "FluxMLDocument.h"
#include "XMLFramework.h"
// Xerces C++ Namespace einbinden
XERCES_CPP_NAMESPACE_USE
using namespace flux::la;
using namespace flux::symb;
namespace flux {
namespace xml {
FluxMLDocument::FluxMLDocument(XN DOMDocument * doc)
: FluxMLContentObject(this), info_(0), writer_(0), reader_(0)
{
// Container-Objekte erzeugen:
pool_map_ = new charptr_map< data::Pool* >();
reaction_list_ = new std::list< data::IsoReaction* >();
configuration_map_ = new charptr_map< data::Configuration* >();
// Netzwerk-Konfiguration initialisieren
root_cfg_ = new data::Configuration("__root__", "network root configuration");
configuration_map_->insert("__root__", root_cfg_);
// Initialisierung von pool_roles_ und stoich_matrix_ erfolgt
// durch validatePoolRolesAndStoichiometry():
stoich_matrix_ = 0;
pool_roles_ = 0;
if (doc->getDocumentElement() == 0)
{
delete pool_map_;
delete reaction_list_;
delete root_cfg_;
delete configuration_map_;
fTHROW(XMLException,"XML parser failed on root-element.");
}
// FluxML-Dokument parsen:
parseDocument(doc->getDocumentElement());
}
FluxMLDocument::FluxMLDocument(const char * filename)
: FluxMLContentObject(this), info_(0), writer_(0), reader_(0)
{
try
{
xml::framework::initialize();
}
catch (xml::XMLException& e)
{
fERROR("failed to initialize the XML framework: %s",
(char const*)e);
}
try
{
reader_ = new xml::DOMReaderImpl;
reader_->mapEntity("http://www.13cflux.net/xml-schema/mm.xsd", FLUX_XML_DIR "/mm.xsd");
reader_->mapEntity("http://www.13cflux.net/xml-schema/fluxml.xsd", FLUX_XML_DIR "/fluxml.xsd");
reader_->mapEntity("http://www.w3.org/Math/XMLSchema/mathml2/mathml2.xsd", FLUX_XML_DIR "/mathml2/mathml2.xsd");
reader_->setResolveXInclude(true);
reader_->parseFromFile(filename);
}
catch (xml::XMLException& e)
{
fERROR("FluxML parsing error: %s", (char const*)e);
delete reader_;
throw(xml::XMLException(e));
}
// Container-Objekte erzeugen:
pool_map_ = new charptr_map< data::Pool* >();
reaction_list_ = new std::list< data::IsoReaction* >();
configuration_map_ = new charptr_map< data::Configuration* >();
// Netzwerk-Konfiguration initialisieren
root_cfg_ = new data::Configuration("__root__", "network root configuration");
configuration_map_->insert("__root__", root_cfg_);
// Initialisierung von pool_roles_ und stoich_matrix_ erfolgt
// durch validatePoolRolesAndStoichiometry():
stoich_matrix_ = 0;
pool_roles_ = 0;
XN DOMDocument * doc = reader_->getDOMDocument();
if (doc->getDocumentElement() == 0)
{
delete pool_map_;
delete reaction_list_;
delete root_cfg_;
delete configuration_map_;
delete reader_;
fTHROW(XMLException,"XML parser failed on root-element.");
}
// FluxML-Dokument parsen:
parseDocument(doc->getDocumentElement());
}
FluxMLDocument::~FluxMLDocument()
{
// der Info-Block:
if (info_ != 0) delete info_;
// die Abbildung Pool-Namen -> Pools
if (pool_map_ != 0)
{
charptr_map< data::Pool* >::iterator i;
for (i=pool_map_->begin(); i!=pool_map_->end(); i++)
delete i->value;
delete pool_map_;
}
// die Reaktionsliste
if (reaction_list_ != 0)
{
std::list< data::IsoReaction* >::iterator i;
for (i=reaction_list_->begin(); i!=reaction_list_->end(); i++)
delete *i;
delete reaction_list_;
}
// die Liste der Konfigurationen
if (configuration_map_ != 0)
{
charptr_map< data::Configuration* >::iterator i;
for (i=configuration_map_->begin();
i!=configuration_map_->end();
i++) delete i->value;
delete configuration_map_;
}
if (stoich_matrix_ != 0)
delete stoich_matrix_;
if (pool_roles_ != 0)
delete pool_roles_;
if (writer_ != 0)
delete writer_;
if (reader_ != 0)
delete reader_;
}
/**
* Parst die Pools einer Netzwerkspezifikation aus einem
* pool-Element-Knoten eines DOM-Dokuments
*
* @param node pool-Element-Knoten eines DOM-Dokuments
*/
void FluxMLDocument::parseDocument(DOMNode * node)
{
DOMNode * child;
XMLCh const * xmlns;
if (not XMLElement::match(node,fml_fluxml,fml_xmlns_uri))
fTHROW(XMLException,node,"element node (fluxml) expected.");
xmlns = static_cast< DOMElement* >(node)->getAttribute(fml_xmlns);
if (xmlns == 0)
fWARNING("element node (fluxml) lacks XML namespace attribute");
else
{
if (not XMLString::equals(xmlns,fml_xmlns_uri))
fTHROW(XMLException,node,"invalid FluxML namespace");
}
child = XMLElement::skipJunkNodes(node->getFirstChild());
// Das info-Element ist optional
if (XMLElement::match(child,fml_info,fml_xmlns_uri))
{
FluxMLInfo info(doc_,child);
// nach erfolgreichem Parsen zum nächsten child weiterrücken
child = XMLElement::nextNode(child);
}
// Das reactionnetwork-Element ist vorgeschrieben
if (not XMLElement::match(child,fml_reactionnetwork,fml_xmlns_uri))
{
U2A rn_asc(XMLElement::getName(child));
fTHROW(XMLException,child,"element node (reactionnetwork) expected; found %s", (char const*)rn_asc);
}
// das reactionnetwork-Element parsen
FluxMLReactionNetwork reactionnetwork(doc_,child);
// zum nächsten Element-Knoten vorrücken
child = XMLElement::nextNode(child);
// es folgt ein optionales constraints-Element und möglicherweise
// mehrere (oder keine) configuration-Elemente:
if (child == 0) return;
if (not XMLElement::match(child,fml_constraints,fml_xmlns_uri)
and not XMLElement::match(child,fml_configuration,fml_xmlns_uri))
fTHROW(XMLException,child,"constraints or configuration element expected!");
if (XMLElement::match(child,fml_constraints,fml_xmlns_uri))
{
// das constraints-Element parsen:
FluxMLConstraints(doc_,child,"__root__");
child = XMLElement::nextNode(child);
}
// jetzt können noch einige configuration-Elemente folgen.
while (child != 0)
{
if (not XMLElement::match(child,fml_configuration,fml_xmlns_uri))
fTHROW(XMLException,child,"element node (configuration) expected.");
FluxMLConfiguration cfg(doc_,child);
child = XMLElement::nextNode(child);
}
// Parsen abgeschlossen; Validierung:
// Pools & Reaktionen validieren:
validatePoolsAndReactions();
// Pool-Rollen identifizieren und Stöchiometrische Matrix erstellen
validatePoolRolesAndStoichiometry();
// Konfigurationen (inkl. Input-Pool-Belegungen) validieren
validateConfigurations();
}
/**
* (Private) Methode zur Generierung der Stöchiometrischen Matrix.
*/
void FluxMLDocument::validatePoolRolesAndStoichiometry()
{
charptr_array r_names;
charptr_array p_names;
charptr_map< data::Pool* >::iterator pi;
charptr_map< PoolRole >::iterator qi;
std::list< data::IsoReaction* >::iterator ri;
std::list< data::IsoReaction::Isotopomer* >::const_iterator rm;
// Klassifikation der Pools anhand der Netzwerkstruktur in
// Input-Pools und innere Pools. Mit Hilfe dieser Klassifikation
// können Fehler in der Reversibilität von Reaktionen erkannt werden
pool_roles_ = new charptr_map< PoolRole >(pool_map_->size());
// Da von den Pool-Rollen bislang nichts bekannt ist, erfolgt
// hier eine Vorbelegung:
for (pi = pool_map_->begin(); pi != pool_map_->end(); ++pi)
pool_roles_->insert( pi->key , p_input );
// Verarbeiten der Reaktionsliste und Berechnung der Pool-Rollen:
for (ri = reaction_list_->begin(); ri != reaction_list_->end(); ++ri)
{
data::IsoReaction * R = *ri;
// Reaktionsnamen hinzufügen:
r_names = (r_names, R->getName());
// ein Pool ist solange ein Input-Pool, bis er als
// Produkt einer Reaktion auftaucht:
for (rm = R->getProducts().begin();
rm != R->getProducts().end(); ++rm)
{
data::IsoReaction::Isotopomer * M = *rm;
qi = pool_roles_->find( M->name );
qi->value = p_inner;
} // for ( Products )
} // for ( Reactions )
// Validierung: werden Input- mit inneren Pools auf der Edukt-Seite
// einer Reaktion vermischt - das würde Ärger machen
for (ri = reaction_list_->begin(); ri != reaction_list_->end(); ++ri)
{
data::IsoReaction * R = *ri;
PoolRole pr;
rm = R->getEducts().begin();
fASSERT(rm != R->getEducts().end());
pr = pool_roles_->find( (*rm)->name )->value;
for (; rm != R->getEducts().end(); ++rm)
if (pool_roles_->find( (*rm)->name )->value != pr)
{
// eine schöne Fehlermeldung generieren
charptr_array sub, nonsub;
for (rm = R->getEducts().begin();
rm != R->getEducts().end(); ++rm)
{
if (pool_roles_->find( (*rm)->name )->value == p_input)
sub.add((*rm)->name);
else
nonsub.add((*rm)->name);
}
fTHROW(XMLException,"reaction \"%s\" mixes substrate (%s) "
"and non-substrate pools (%s) on its educt side",
(*ri)->getName(), sub.concat(","), nonsub.concat(","));
}
}
// Erzeuge eine Namens-Liste von inneren Pools:
for (pi = pool_map_->begin(); pi != pool_map_->end(); pi++)
// den Pool-Namen der Liste hinzufügen, falls es sich um einen
// INNEREN(!) Pool handelt:
if ( (*pool_roles_)[ pi->key ] == p_inner )
p_names = (p_names, pi->key);
if (p_names.size() == 0)
fTHROW(XMLException,"network contains only input pools");
// Erzeugung der Stöchiometrischen Matrix:
stoich_matrix_ = new StoichMatrixInteger(
p_names.size(), r_names.size(), // rows, cols
p_names.get(), // metabolite-names
r_names.get() // reaction-names
);
// die Reaktionen in die Stöchiometrische Matrix eintragen:
// abfließend: inc(-1), zufließend: inc(+1)
for (ri = reaction_list_->begin(); ri != reaction_list_->end(); ri++)
{
int idx;
size_t row, col;
data::IsoReaction * R = *ri;
idx = r_names.findIndex( R->getName() );
fASSERT(idx >= 0);
col = size_t(idx);
for (rm = R->getEducts().begin();
rm != R->getEducts().end(); rm++)
{
data::IsoReaction::Isotopomer * M = *rm;
// nur INNERE Pools
if ( (*pool_roles_)[ M->name ] != p_inner )
continue;
idx = p_names.findIndex( M->name );
fASSERT(idx >= 0);
row = size_t(idx);
// Abfluß aus einem Edukt-Pool: inc(-1)
(*stoich_matrix_)(row,col) -= 1;
}
for (rm = R->getProducts().begin();
rm != R->getProducts().end(); rm++)
{
data::IsoReaction::Isotopomer * M = *rm;
// nur INNERE Pools
if ( (*pool_roles_)[ M->name ] != p_inner )
continue;
row = p_names.findIndex( M->name );
// Zufluß in einen Produkt-Pool: inc(+1)
(*stoich_matrix_)(row,col) += 1;
}
} // for ( Reactions )
}
/*
* Validierung des Zusammenspiels der Bezeichnungen der Pools in der
* Pool-Liste und deren Erwähnung innerhalb der Reaktionebeschreibungen
*/
void FluxMLDocument::validatePoolsAndReactions()
{
std::list< data::IsoReaction::Isotopomer* >::const_iterator j;
std::list< data::IsoReaction* >::iterator i;
int k;
bool invalid, network_has_efflux = false;
i = reaction_list_->begin();
while (i != reaction_list_->end())
{
data::IsoReaction * reaction = *i;
std::list< data::IsoReaction::Isotopomer* >::const_iterator iters_begin[] = {
reaction->getEducts().begin(),
reaction->getProducts().begin()
};
std::list< data::IsoReaction::Isotopomer* >::const_iterator iters_end[] = {
reaction->getEducts().end(),
reaction->getProducts().end()
};
// Ein Netzwerk ohne irgendeinen Abfluß ist defekt:
network_has_efflux = network_has_efflux ||
reaction->getProducts().size()==0;
// gibt es die in der Reaktion angegebenen Edukte/Produkte wirklich
// und in der angegebenen Form?
for (k=0; k<2; k++)
{
j = iters_begin[k];
while (j != iters_end[k])
{
data::Pool ** poolptr;
data::IsoReaction::Isotopomer * metab =
static_cast< data::IsoReaction::Isotopomer* >( *j );
// gibt es den genannten Pool?:
if ((poolptr = pool_map_->findPtr(metab->name)) != 0)
{
int natoms = data::Notation::perm_spec_length(metab->atom_cfg);
// Stimmt die Länge der Konfiguration mit der Länge
// der Atom-Ketten überein?
if ((*poolptr)->getNumAtoms() != natoms)
fTHROW(XMLException,
"validation (%s): pool %s shows mismatch in atom cfg.",
reaction->getName(), metab->name);
// der Pool nimmt evtl. zum ersten Mal an einer Reaktion
// teil und wird markiert:
(*poolptr)->setUsedInReaction();
// jeder Pool muss einmal in der Rolle eines Edukts auftreten
// -- ansonsten hat er keinen Abfluss
if (k == 0)
(*poolptr)->setHasEfflux();
}
else
fTHROW(XMLException,
"validation (%s): pool %s does not exist.",
reaction->getName(), metab->name);
j++;
} // alle Edukte/Produkte
} // Edukte/Produkte
i++;
} // alle Reaktionen
// Fehlermeldungen zunächst sammeln, bevor eine Exception ausgelöst wird:
if (not network_has_efflux)
fWARNING("network has no efflux");
// Gibt es isolierte Pools, die mit Reaktionen nicht erreicht werden?
invalid = not network_has_efflux;
charptr_map< data::Pool* >::iterator p = pool_map_->begin();
while (p != pool_map_->end())
{
data::Pool * pool = p->value;
if (pool->isUsedInReaction() == false)
{
fWARNING("pool \"%s\" is isolated", pool->getName());
invalid = true;
}
if (pool->hasEfflux() == false)
{
fWARNING("pool \"%s\" has no efflux (set at least one incident exchange flux >0)",
pool->getName());
}
p++;
}
if (invalid)
fTHROW(XMLException,"validation: inconsistent network structure");
}
// sind die genannten Input-Pools wirklich Input-Pools des Netzwerkes?
// wurden Input-Pools vergessen?
// sind die freien Flüsse konform mit der Stöchiometrie?
void FluxMLDocument::validateConfigurations()
{
bool valid_cfg, found;
// Die Stöchiometrische Matrix muß bereits berechnet sein!
fASSERT(stoich_matrix_ != 0);
// Input-Pools für die Wurzel-Konfiguration erzeugen
charptr_map< PoolRole >::iterator ri;
for (ri = pool_roles_->begin(); ri != pool_roles_->end(); ri++)
{
if (ri->value != p_input) continue;
data::InputPool * ip = root_cfg_->createInputPool(
ri->key,
(*pool_map_)[ri->key]->getNumAtoms(),
data::InputPool::ip_cumomer
);
ip->setCumomerValue(0,1.); // unmarkiert
}
// I/O-Constraints in die Wurzel-Konfiguration eintragen
setConfInputOutputConstraints(root_cfg_);
charptr_map< data::Configuration* >::iterator ci;
for (ci = configuration_map_->begin(); ci != configuration_map_->end(); ci++)
{
// Constraints der Wurzel-Konfiguration übernehmen
valid_cfg = true;
if (ci->value != root_cfg_)
{
ci->value->mergeConstraints(*root_cfg_);
// TODO: ist die Lazy-Validierung besser geeignet?
// // Validierung der Constraints und Flußangaben:
// valid_cfg = validateConfSingle( ci->value );
}
// Validierung der Input-Pool-Spezifikation:
std::list< data::InputPool* > const & ipools = ci->value->getInputPools();
std::list< data::InputPool* >::const_iterator pi;
for (ri = pool_roles_->begin(); ri != pool_roles_->end(); ri++)
{
if (ri->value != p_input) continue;
found = false;
for (pi = ipools.begin(); not found && pi != ipools.end(); pi++)
if ((strcmp( (*pi)->getName(), ri->key ) == 0) /*or ((*pi)->getSize()==0)*/)
found = true;
// Co-factor pool prüfen da sie nicht als input spezifiziert werden müssen
data::Pool ** ptr = pool_map_->findPtr(ri->key);
fASSERT(ptr != 0);
if((*ptr)->getNumAtoms()== 0)
found = true;
if (not found)
{
valid_cfg = false;
fWARNING("missing input pool specification "
"(cfg: \"%s\", pool: \"%s\")",
ci->key,ri->key);
}
}
// gehören die Input-Pool Spezifikationen wirklich zu Input-Pools,
// oder will man uns andere Pools als Input-Pools verkaufen?
for (pi = ipools.begin(); pi != ipools.end(); pi++)
{
ri = pool_roles_->find( (*pi)->getName() );
if (ri == pool_roles_->end())
{
valid_cfg = false;
fWARNING("unknown pool \"%s\" in input pool specification",
(*pi)->getName());
}
else if (ri->value != p_input)
{
valid_cfg = false;
fWARNING("input pool specification for inner pool \"%s\"",
(*pi)->getName());
}
}
if (not valid_cfg)
{
fTHROW(XMLException,"validation of configuration %s failed!",
ci->key);
}
}
}
bool FluxMLDocument::validateConfSingle(data::Configuration * cfg)
{
fASSERT(stoich_matrix_ != 0);
// die Konfiguration der Flüsse und Input-Pools validieren
cfg->validate(
stoich_matrix_
);
switch (cfg->getValidationState())
{
case data::Configuration::cfg_unvalidated:
// nach cfg->validate() sollte dies nicht
// auftreten
fASSERT_NONREACHABLE();
return false;
case data::Configuration::cfg_ok:
// die Konfiguration ist gültig
return true;
case data::Configuration::cfg_too_few_constr:
// es gibt zu wenige Constraints
if (cfg == root_cfg_)
break;
fWARNING("configuration \"%s\": too few constraints or free variables",
cfg->getName());
break;
case data::Configuration::cfg_too_much_constr:
// es gibt zu viele Constraints
fWARNING("configuration \"%s\" is invalid: too much constraints",
cfg->getName());
break;
case data::Configuration::cfg_linear_dep_constr:
// die Constraints sind scheinbar linear abhängig
fWARNING("configuration \"%s\": linear dependencies between constraints",
cfg->getName());
break;
case data::Configuration::cfg_nonlinear_constr:
// das Constraint ist nicht-linear
fWARNING("configuration \"%s\" is invalid: probably non-linear equalities",
cfg->getName());
break;
case data::Configuration::cfg_invalid_constr:
// das Constraint ist ungültig
fWARNING("configuration \"%s\" is invalid: invalid constraints!?",
cfg->getName());
break;
case data::Configuration::cfg_invalid_substrate:
fWARNING("configuration \"%s\" is invalid: illegal substrate mixture",
cfg->getName());
break;
case data::Configuration::cfg_too_much_free_vars:
fWARNING("configuration \"%s\" is invalid: too many free fluxes!",
cfg->getName());
break;
case data::Configuration::cfg_invalid_free_vars:
fWARNING("configuration \"%s\" is invalid: wrong combination of free fluxes",
cfg->getName());
break;
case data::Configuration::cfg_ineqs_violated:
fWARNING("configuration \"%s\": inequality constraints violated",
cfg->getName());
break;
case data::Configuration::cfg_ineqs_infeasible:
fWARNING("configuration \"%s\" is invalid: infeasible inequality constraints",
cfg->getName());
break;
}
// falls die Konfiguration im Wesentlichen validiert ist
// und eine gültige Stöchiometrie erwartet werden kann
// wird hier true zurückgegeben, damit der FluxML-Parser
// späteren Auswertungsschritten nicht im Weg steht ...
return cfg->isValid(3);
}
uint32_t FluxMLDocument::computeCheckSum(int crc_scope) const
{
uint32_t crc = 0u;
// implement a checksum algorithm of your choice here
return crc;
}
char const * FluxMLDocument::getSignature() const
{
if (info_ == 0 or info_->getSignature().size() == 0)
{
fDEBUG(0,"FluxML document does not contain a signature");
return 0;
}
return info_->getSignature().c_str();
}
void FluxMLDocument::setConfInputOutputConstraints(data::Configuration * cfg)
{
// Da nach zuweisung der Pool-Rollen klar ist, welche Pools und
// Reaktionen intra-zelluläre und extra-zelluläre Pools verbinden
// werden jetzt zusätzliche Constraints auf Exchange-Flüsse generiert,
// die besagen, das input- und output-Reaktionen irreversibel sind
// (der Exchange-Fluß wird auf 0 gesetzt).
std::list< data::IsoReaction* >::iterator ri;
std::list< data::IsoReaction::Isotopomer* >::const_iterator rm;
ExprTree * xch_expr; // Exchange von I/O-Fluss == 0
ExprTree * net_expr; // Netto von I/O-Fluss >= 0
bool imp_const;
// Schritt 1: Welche Flüsse sind mit Input-Pools verbunden? Welche
// Flüsse sind Abflüsse? Speichere die Liste der Reaktionen
// in ioReactions.
for (ri = reaction_list_->begin();
ri != reaction_list_->end(); ri++)
{
data::IsoReaction * R = *ri;
imp_const = false;
for (rm = R->getEducts().begin(); rm != R->getEducts().end(); rm++)
if ((*pool_roles_)[ (*rm)->name ] == p_input)
{
imp_const = true;
break;
}
// Falls die Reaktion kein Produkt hat, handelt es sich um einen
// Abfluß. Im Folgenden werden einfache Constraints für alle
// Abflüsse generiert
if (imp_const or R->getProducts().size() == 0)
{
// ein Fluss wird NUR DANN irreversibel, wenn der xch-Wert
// auf 0 festgelegt wird und der net-Wert positiv ist!
net_expr = ExprTree::geq(ExprTree::sym(R->getName()),ExprTree::val(0));
// cfg->createConstraint("unidir I/O",net_expr,true);
cfg->createConstraint("unidir I/O",net_expr,data::NET);
delete net_expr;
xch_expr = ExprTree::eq(ExprTree::sym(R->getName()),ExprTree::val(0));
// cfg->createConstraint("unidir I/O",xch_expr,false);
cfg->createConstraint("unidir I/O",xch_expr,data::XCH);
delete xch_expr;
}
else
{
// bei sonstigen Flüssen soll der Exchange-Fluß niemals
// kleiner als 0 sein
xch_expr = ExprTree::geq(ExprTree::sym(R->getName()),ExprTree::val(0));
// cfg->createConstraint("pos. xch",xch_expr,false);
cfg->createConstraint("pos. xch",xch_expr,data::XCH);
delete xch_expr;
}
}
}
DOMWriter & FluxMLDocument::getDOMWriter()
{
if (writer_)
return *writer_;
writer_ = new DOMWriterImpl(0,"fluxml",0,"fluxml.dtd");
return *writer_;
}
DOMReader & FluxMLDocument::getDOMReader()
{
if (reader_)
return *reader_;
reader_ = new xml::DOMReaderImpl;
reader_->mapEntity("http://www.13cflux.net/xml-schema/mm.xsd", FLUX_XML_DIR "/mm.xsd");
reader_->mapEntity("http://www.13cflux.net/xml-schema/fluxml.xsd", FLUX_XML_DIR "/fluxml.xsd");
reader_->mapEntity("http://www.w3.org/Math/XMLSchema/mathml2/mathml2.xsd", FLUX_XML_DIR "/mathml2/mathml2.xsd");
reader_->setResolveXInclude(true);
return *reader_;
}
bool FluxMLDocument::patchDOM(
DOMDocument & doc,
data::ConstraintSystem const & CS,
char const * cfg_name
)
{
DOMNodeList * configuration_list
= doc.getElementsByTagName(fml_configuration);
DOMElement * fluxvalue, * variables = 0, * simulation;
DOMNode * child, * pchild;
char dbl_str[32];
double net, xch;
bool stationary = true;
A2U utf_cfg_name(cfg_name);
// 1. aus doc "variables" mit name aus variable cfg suchen
// <configuration>
for (XMLSize_t i=0; i<configuration_list->getLength(); i++)
{
DOMElement * conf_node = static_cast< DOMElement* >(
configuration_list->item(i)
);
// passende Konfiguration suchen
if (not XMLString::equals(
conf_node->getAttribute(fml_name),
utf_cfg_name)) continue;
// <simulation>
DOMNodeList * sim_list
= conf_node->getElementsByTagName(fml_simulation);
if (sim_list->getLength() == 0)
{
simulation = doc.createElementNS(fml_xmlns_uri,fml_simulation);
conf_node->appendChild(simulation);
}
else
simulation = dynamic_cast< DOMElement* >(sim_list->item(0));
// <variables>
DOMNodeList * var_list
= simulation->getElementsByTagName(fml_variables);
if (var_list->getLength() == 0)
{
variables = doc.createElementNS(fml_xmlns_uri,fml_variables);
simulation->appendChild(variables);
}
else
variables = dynamic_cast< DOMElement * >(var_list->item(0));
// fluxvalue-Elemente unterhalt von variables entfernen
for (child = variables->getFirstChild(); child != 0;)
{
if (child->getNodeType() == DOMNode::COMMENT_NODE)
{
child = child->getNextSibling();
continue; // Kommentare möglichst erhalten
}
pchild = child->getNextSibling();
variables->removeChild(child);
child = pchild;
}
// Stationarität überprüfen
if (XMLString::equals(
conf_node->getAttribute(fml_stationary),
A2U("false"))) stationary=false;
}
fASSERT(variables != 0);
// neue fluxvalue-Elemente für net und xch anlegen
// net:
charptr_array fluxes_net = CS.getFluxNamesByType(
data::ConstraintSystem::f_free,true);
charptr_array::const_iterator ni;
for (ni=fluxes_net.begin(); ni!=fluxes_net.end(); ni++)
{
CS.getFlux(*ni, net, xch);
fluxvalue = doc.createElementNS(fml_xmlns_uri,fml_fluxvalue);
fluxvalue->setAttribute(fml_flux, A2U(*ni));
fluxvalue->setAttribute(fml_type, fml_net);
dbl2str(dbl_str, net, sizeof(dbl_str));
fluxvalue->appendChild(doc.createTextNode(A2U(dbl_str)));
variables->appendChild(fluxvalue);
}
// xch:
charptr_array fluxes_xch = CS.getFluxNamesByType(
data::ConstraintSystem::f_free,false);
charptr_array::const_iterator xi;
for (xi = fluxes_xch.begin(); xi != fluxes_xch.end(); xi++)
{
CS.getFlux(*xi, net, xch);
fluxvalue = doc.createElementNS(fml_xmlns_uri,fml_fluxvalue);
fluxvalue->setAttribute(fml_flux, A2U(*xi));
fluxvalue->setAttribute(fml_type, fml_xch);
dbl2str(dbl_str, xch, sizeof(dbl_str));
fluxvalue->appendChild(doc.createTextNode(A2U(dbl_str)));
variables->appendChild(fluxvalue);
}
// pool:
if(!stationary)
{
double pool;
DOMElement * poolvalue;
charptr_array pools = CS.getPoolNamesByType(data::ConstraintSystem::p_free);
charptr_array::const_iterator pi;
for (pi = pools.begin(); pi != pools.end(); pi++)
{
CS.getPoolSize(*pi, pool);
poolvalue = doc.createElementNS(fml_xmlns_uri,fml_poolvalue);
poolvalue->setAttribute(fml_pool, A2U(*pi));
dbl2str(dbl_str, pool, sizeof(dbl_str));
poolvalue->appendChild(doc.createTextNode(A2U(dbl_str)));
variables->appendChild(poolvalue);
}
}
return true;
}
bool FluxMLDocument::patchDOM_MS(
DOMDocument & doc,
MGroupMS const & mgms,
DOMElement & data
)
{
size_t w;
char buf[32];
MVector x_meas;
MVector x_stddev;
DOMElement * datum;
std::set<double> times = mgms.getTimeStampSet();
std::set<double>::const_iterator t;
for(t= times.begin(); t!= times.end(); ++t)
{
if (not mgms.getMValuesStdDev(*t, x_meas, x_stddev))
{
fERROR("Failed to get mvalues");
return false;
}
for (w=0; w<mgms.getNumWeights(); w++)
{
datum = doc.createElementNS(fml_xmlns_uri,mm_datum);
datum->setAttribute(fml_id, A2U(mgms.getGroupId()));
if(*t!=-1)
{
dbl2str(buf, *t, sizeof(buf));
datum->setAttribute(mm_time, A2U(buf));
}
snprintf(buf, sizeof(buf), "%d", mgms.getWeights()[w]);
datum->setAttribute(mm_weight, A2U(buf));
dbl2str(buf, x_stddev.get(w), sizeof(buf));
datum->setAttribute(mm_stddev, A2U(buf));
dbl2str(buf, x_meas.get(w), sizeof(buf));
datum->appendChild(doc.createTextNode(A2U(buf)));
data.appendChild(datum);
}
}
return true;
}
bool FluxMLDocument::patchDOM_MSMS(
DOMDocument & doc,
MGroupMSMS const & mgmsms,
DOMElement & data
)
{
size_t w;
char buf[32];
MVector x_meas;
MVector x_stddev;
DOMElement * datum;
std::set<double> times = mgmsms.getTimeStampSet();
std::set<double>::const_iterator t;
for(t= times.begin(); t!= times.end(); ++t)
{
if (not mgmsms.getMValuesStdDev(*t, x_meas, x_stddev))
{
fERROR("failed to retrieve measurement values for measurement group %s",
mgmsms.getGroupId());
return false;
}
for (w=0; w<mgmsms.getNumWeights(); w++)
{
datum = doc.createElementNS(fml_xmlns_uri,mm_datum);
datum->setAttribute(fml_id, A2U(mgmsms.getGroupId()));
if(*t!=-1)
{
dbl2str(buf, *t, sizeof(buf));
datum->setAttribute(mm_time, A2U(buf));
}
snprintf(buf, sizeof(buf), "%d,%d",
mgmsms.getWeights1()[w],
mgmsms.getWeights2()[w]
);
datum->setAttribute(mm_weight, A2U(buf));
dbl2str(buf, x_stddev.get(w), sizeof(buf));
datum->setAttribute(mm_stddev, A2U(buf));
dbl2str(buf, x_meas.get(w), sizeof(buf));
datum->appendChild(doc.createTextNode(A2U(buf)));
data.appendChild(datum);
}
}
return true;
}
bool FluxMLDocument::patchDOM_MIMS(
DOMDocument & doc,
MGroupMIMS const & mgmims,
DOMElement & data
)
{
size_t w;
char buf[32];
MVector x_meas;
MVector x_stddev;
DOMElement * datum;
std::set<double> times = mgmims.getTimeStampSet();
std::set<double>::const_iterator t;
for(t= times.begin(); t!= times.end(); ++t)
{
if (not mgmims.getMValuesStdDev(*t, x_meas, x_stddev))
{
fERROR("failed to retrieve measurement values for measurement group %s",
mgmims.getGroupId());
return false;
}
const std::vector<int *> & weights_vec = mgmims.getWeights();
std::vector<int *>::const_iterator wi;
for (w=0; w<mgmims.getDim(); w++)
{
datum = doc.createElementNS(fml_xmlns_uri,mm_datum);
datum->setAttribute(fml_id, A2U(mgmims.getGroupId()));
if(*t!=-1)
{
dbl2str(buf, *t, sizeof(buf));
datum->setAttribute(mm_time, A2U(buf));
}
std::ostringstream ostr;
for(wi=weights_vec.begin();wi!=weights_vec.end();wi++)
ostr<< (wi!=weights_vec.begin()?",":"") <<(*wi)[w];
snprintf(buf, sizeof(buf), "%s",
ostr.str().c_str()
);
datum->setAttribute(mm_weight, A2U(buf));
dbl2str(buf, x_stddev.get(w), sizeof(buf));
datum->setAttribute(mm_stddev, A2U(buf));
dbl2str(buf, x_meas.get(w), sizeof(buf));
datum->appendChild(doc.createTextNode(A2U(buf)));
data.appendChild(datum);
}
}
return true;
}
bool FluxMLDocument::patchDOM_Generic(
DOMDocument & doc,
MGroupGeneric const & mgg,
DOMElement & data
)
{
size_t r;
char buf[32];
MVector x_meas;
MVector x_stddev;
DOMElement * datum;
if (mgg.getNumRows() > 255)
{
fERROR("number of measurement values exceeds 256");
return false;
}
std::set<double> times = mgg.getTimeStampSet();
std::set<double>::const_iterator t;
for(t= times.begin(); t!= times.end(); ++t)
{
if (not mgg.getMValuesStdDev(*t, x_meas, x_stddev))
{
fERROR("failed to retrieve measurement values for measurement group %s",
mgg.getGroupId());
return false;
}
for (r=0; r<mgg.getNumRows(); r++)
{
datum = doc.createElementNS(fml_xmlns_uri,mm_datum);
datum->setAttribute(fml_id, A2U(mgg.getGroupId()));
if(*t!=-1)
{
dbl2str(buf, *t, sizeof(buf));
datum->setAttribute(mm_time, A2U(buf));
}
snprintf(buf, sizeof(buf), "%u", (unsigned) r + 1);
datum->setAttribute(mm_row, A2U(buf));
dbl2str(buf, x_stddev.get(r), sizeof(buf));
datum->setAttribute(mm_stddev, A2U(buf));
dbl2str(buf, x_meas.get(r), sizeof(buf));
datum->appendChild(doc.createTextNode(A2U(buf)));
data.appendChild(datum);
}
}
return true;
}
bool FluxMLDocument::patchDOM_1HNMR(
DOMDocument & doc,
MGroup1HNMR const & mg1hnmr,
DOMElement & data
)
{
char buf[32];
size_t p;
MVector x_meas;
MVector x_stddev;
DOMElement * datum;
std::set<double> times = mg1hnmr.getTimeStampSet();
std::set<double>::const_iterator t;
for(t= times.begin(); t!= times.end(); ++t)
{
if (not mg1hnmr.getMValuesStdDev(*t, x_meas, x_stddev))
{
fERROR("failed to retrieve measurement values for measurement group %s",
mg1hnmr.getGroupId());
return false;
}
for (p=0; p<mg1hnmr.getNumPositions(); p++)
{
datum = doc.createElementNS(fml_xmlns_uri,mm_datum);
datum->setAttribute(fml_id, A2U(mg1hnmr.getGroupId()));
if(*t!=-1)
{
dbl2str(buf, *t, sizeof(buf));
datum->setAttribute(mm_time, A2U(buf));
}
snprintf(buf, sizeof(buf), "%d", mg1hnmr.getPositions()[p]);
datum->setAttribute(mm_pos, A2U(buf));
dbl2str(buf, x_stddev.get(p), sizeof(buf));
datum->setAttribute(mm_stddev, A2U(buf));
dbl2str(buf, x_meas.get(p), sizeof(buf));
datum->appendChild(doc.createTextNode(A2U(buf)));
data.appendChild(datum);
}
}
return true;
}
bool FluxMLDocument::patchDOM_13CNMR(
DOMDocument & doc,
MGroup13CNMR const & mg13cnmr,
DOMElement & data
)
{
size_t p;
char buf[32];
MVector x_meas;
MVector x_stddev;
std::set<double> times = mg13cnmr.getTimeStampSet();
std::set<double>::const_iterator t;
for(t= times.begin(); t!= times.end(); ++t)
{
if (not mg13cnmr.getMValuesStdDev(*t, x_meas, x_stddev))
{
fERROR("failed to retrieve measurement values for measurement group %s",
mg13cnmr.getGroupId());
return false;
}
for (p=0; p<mg13cnmr.getNumPositions(); p++)
{
DOMElement* datum = doc.createElementNS(fml_xmlns_uri,mm_datum);
datum->setAttribute(fml_id, A2U(mg13cnmr.getGroupId()));
if(*t!=-1)
{
dbl2str(buf, *t, sizeof(buf));
datum->setAttribute(mm_time, A2U(buf));
}
snprintf(buf, sizeof(buf), "%d", mg13cnmr.getPositions()[p]);
datum->setAttribute(mm_pos, A2U(buf));
dbl2str(buf, x_stddev.get(p), sizeof(buf));
datum->setAttribute(mm_stddev, A2U(buf));
buf[1] = 0; buf[2] = 0;
switch (mg13cnmr.getNMRTypes()[p])
{
case MValue13CNMR::S:
buf[0] = 'S';
break;
case MValue13CNMR::DL:
buf[0] = 'D'; buf[1] = 'L';
break;
case MValue13CNMR::DR:
buf[0] = 'D'; buf[1] = 'R';
break;
case MValue13CNMR::DD:
buf[0] = 'D'; buf[1] = 'D';
break;
case MValue13CNMR::T:
buf[0] = 'T';
break;
}
datum->setAttribute(mm_type, A2U(buf));
dbl2str(buf, x_meas.get(p), sizeof(buf));
datum->appendChild(doc.createTextNode(A2U(buf)));
data.appendChild(datum);
}
}
return true;
}
bool FluxMLDocument::patchDOM(
DOMDocument & doc,
MGroup const & MG,
char const * cfg_name
)
{
XMLSize_t i,j,k,d;
DOMNodeList * configuration_list;
DOMElement * conf_node = 0;
// 1. aus doc "variables" mit name aus variable cfg suchen
// <configuration>
configuration_list = doc.getElementsByTagName(fml_configuration);
for (i=0; i<configuration_list->getLength(); i++)
{
if (configuration_list->item(i)->getNodeType() != DOMNode::ELEMENT_NODE)
continue;
conf_node = dynamic_cast< DOMElement* >(configuration_list->item(i));
if (not XMLString::equals(conf_node->getAttribute(fml_name),A2U(cfg_name)))
continue;
// <measurement>
DOMNodeList * meas_list =
conf_node->getElementsByTagName(fml_measurement);
for (j=0; j<meas_list->getLength(); j++)
{
if (meas_list->item(j)->getNodeType() != DOMNode::ELEMENT_NODE)
continue;
DOMElement * measurement = dynamic_cast< DOMElement * >(
meas_list->item(j)
);
DOMNodeList * data_list = measurement->getElementsByTagName(mm_data);
for (d=0; d<data_list->getLength(); d++)
{
if (data_list->item(d)->getNodeType() != DOMNode::ELEMENT_NODE)
continue;
// <data>
DOMElement * data = dynamic_cast< DOMElement * >(
data_list->item(d)
);
DOMNodeList * datum_list = data->getElementsByTagName(
mm_datum
);
for (k=datum_list->getLength(); k>0; k--)
{
if (datum_list->item(k-1)->getNodeType() != DOMNode::ELEMENT_NODE)
continue;
DOMElement * datum = dynamic_cast< DOMElement* >(datum_list->item(k-1));
if (not XMLString::equals(
datum->getAttribute(fml_id),
A2U(MG.getGroupId()))) continue;
data->removeChild(datum);
}
// neue datum-Elemente anlegen anlegen
switch (MG.getType())
{
case MGroup::mg_GENERIC:
if (not patchDOM_Generic(
doc,
dynamic_cast< MGroupGeneric const & >(MG),
*data)) return false;
break;
case MGroup::mg_MS:
if (not patchDOM_MS(
doc,
dynamic_cast< MGroupMS const & >(MG),
*data)) return false;
break;
case MGroup::mg_MSMS:
if (not patchDOM_MSMS(
doc,
dynamic_cast< MGroupMSMS const & >(MG),
*data)) return false;
break;
case MGroup::mg_MIMS:
if (not patchDOM_MIMS(
doc,
dynamic_cast< MGroupMIMS const & >(MG),
*data)) return false;
break;
case MGroup::mg_1HNMR:
if (not patchDOM_1HNMR(
doc,
dynamic_cast< MGroup1HNMR const & >(MG),
*data)) return false;
break;
case MGroup::mg_13CNMR:
if (not patchDOM_13CNMR(
doc,
dynamic_cast< MGroup13CNMR const & >(MG),
*data)) return false;
break;
default: // FLUX und POOL
{
MVector x_meas;
MVector x_stddev;
DOMElement * datum;
char buf[32];
datum = doc.createElementNS(fml_xmlns_uri,mm_datum);
datum->setAttribute(fml_id, A2U(MG.getGroupId()));
if (not MG.getMValuesStdDev(-1., x_meas, x_stddev))
{
fERROR("failed to retrieve measurement values for measurement group %s",
MG.getGroupId());
return false;
}
dbl2str(buf, x_stddev.get(0), sizeof(buf));
datum->setAttribute(mm_stddev, A2U(buf));
dbl2str(buf, x_meas.get(0), sizeof(buf));
datum->appendChild(doc.createTextNode(A2U(buf)));
data->appendChild(datum);
}
} // switch (MG.getType())
data->appendChild(doc.createComment(xercesc::XMLString::transcode("== new datum ==")));
}
}
}
return conf_node;
}
} // namespace flux::xml
} // namespace flux
| 31.031204 | 157 | 0.599143 | [
"vector"
] |
42e6c70382c744f0fc224096f2781ae69933f76b | 2,669 | cpp | C++ | tc 160+/StockHistory.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 3 | 2015-05-25T06:24:37.000Z | 2016-09-10T07:58:00.000Z | tc 160+/StockHistory.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | null | null | null | tc 160+/StockHistory.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 5 | 2015-05-25T06:24:40.000Z | 2021-08-19T19:22:29.000Z | #include <algorithm>
#include <cassert>
#include <cstdio>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cstring>
#include <cmath>
using namespace std;
double dp[51];
class StockHistory {
public:
int maximumEarnings(int ii, int mc, vector <string> stockPrices) {
vector< vector<int> > P;
for (int i=0; i<(int)stockPrices.size(); ++i) {
istringstream is(stockPrices[i]);
int x;
P.push_back(vector<int> ());
while (is >> x)
P.back().push_back(x);
}
int cntStock = P[0].size();
int maxT = P.size();
dp[0] = 0.0;
for (int t=1; t<=maxT; ++t) {
dp[t] = 0;
for (int i=0; i<t; ++i) {
double have = (i==0)*ii + (t-(i==0)-i)*mc;
for (int x=0; x<cntStock; ++x)
dp[t] = max(dp[t], dp[i] + (P.back()[x]-P[t-1][x]) * (have/P[t-1][x]));
}
}
double x = *max_element(dp, dp+maxT+1);
return (int)x + (x-(int)x >= 0.5);
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arg0 = 1000; int Arg1 = 0; string Arr2[] = {"10 20 30", "15 24 32"}; vector <string> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 500; verify_case(0, Arg3, maximumEarnings(Arg0, Arg1, Arg2)); }
void test_case_1() { int Arg0 = 1000; int Arg1 = 0; string Arr2[] = {"10", "9"}; vector <string> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 0; verify_case(1, Arg3, maximumEarnings(Arg0, Arg1, Arg2)); }
void test_case_2() { int Arg0 = 100; int Arg1 = 20; string Arr2[] = {"40 50 60",
"37 48 55",
"100 48 50",
"105 48 47",
"110 50 52",
"110 50 52",
"110 51 54",
"109 49 53"}; vector <string> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 239; verify_case(2, Arg3, maximumEarnings(Arg0, Arg1, Arg2)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
StockHistory ___test;
___test.run_test(-1);
}
// END CUT HERE
| 33.78481 | 309 | 0.563507 | [
"vector"
] |
42ea464ad46c886d4dfaf3bf696fe55556c10207 | 3,590 | cpp | C++ | src/error.cpp | rljacobson/Elsix | e4e508f2a09bb2cddd6d928bfa69a901a3feb74c | [
"MIT"
] | 2 | 2021-03-21T04:53:22.000Z | 2021-07-21T00:55:30.000Z | src/error.cpp | rljacobson/Elsix | e4e508f2a09bb2cddd6d928bfa69a901a3feb74c | [
"MIT"
] | null | null | null | src/error.cpp | rljacobson/Elsix | e4e508f2a09bb2cddd6d928bfa69a901a3feb74c | [
"MIT"
] | null | null | null | #include <utility>
/*
Created by Robert Jacobson on 04 April 2019.
Elsix
Description: An implementation of the Bell Telephone Laboratories'
Low-Level Linked List Language L6.
Copyright (c) 2019 Robert Jacobson.
The MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
#include <iostream>
#include <string>
// #include "fmt/format.h"
#include "error.hpp"
namespace elsix{
// region: ErrorHandler Class Implementation
// region: ErrorHandler constructors
ErrorHandler::ErrorHandler()
: errors_(ErrorVector()), err_stream_(&std::cerr), err_log_stream_(nullptr){
}
ErrorHandler::ErrorHandler(std::ostream &err, std::ostream &log) : errors_(std::vector<Error>()),
err_stream_(&err),
err_log_stream_(&log){
}
ErrorHandler::ErrorHandler(std::ostream &err) : errors_(std::vector<Error>()),
err_stream_(&err),
err_log_stream_(nullptr){
}
// endregion: ErrorHandler constructors
void ErrorHandler::emitError(const std::string &&message, Span span){
errors_.emplace_back(std::forward<const std::string>(message), span);
outputError(errors_.back());
}
void ErrorHandler::emitFatalError(const std::string &&message, Span span){
emitError(std::forward<const std::string>(message), span);
throw (FatalException(errors_.back()));
}
const ErrorVector &ErrorHandler::getErrors() const noexcept{
return errors_;
}
void ErrorHandler::outputError(const Error &error) const noexcept{
if(err_log_stream_ != nullptr){
*err_log_stream_ << error.message << std::endl;
}
if(err_stream_ != nullptr){
*err_stream_ << error.message << std::endl;
}
}
void ErrorHandler::setLogStream(std::ostream &log) noexcept{
err_log_stream_ = &log;
}
const std::ostream &ErrorHandler::getLogStream() const noexcept{
return *err_log_stream_;
}
// endregion: ErrorHandler Implementation
// region: Error Class Implementation
Error::Error(const std::string &&msg, Span spn)
: span(spn), message(std::forward<const std::string>(msg)){
}
// endregion: Error Class Implementation
// region: FatalException Class Implementation
const char *FatalException::what() const noexcept{
return error.message.c_str();
}
FatalException::FatalException(const Error &e) : error(e){
}
// endregion: FatalException Class Implementation
}
| 32.636364 | 97 | 0.68273 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.