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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cfc63ea2d5bd5db41678cdf5ab4fb14eff58aee4 | 9,617 | cpp | C++ | src/Stitcher.cpp | rhiestan/RegardRGBD | 04a6135c537828ef7b35d5b1ac4f1e1a3b4e0b34 | [
"MIT"
] | 2 | 2021-06-03T20:32:02.000Z | 2021-08-12T09:38:09.000Z | src/Stitcher.cpp | rhiestan/RegardRGBD | 04a6135c537828ef7b35d5b1ac4f1e1a3b4e0b34 | [
"MIT"
] | null | null | null | src/Stitcher.cpp | rhiestan/RegardRGBD | 04a6135c537828ef7b35d5b1ac4f1e1a3b4e0b34 | [
"MIT"
] | null | null | null |
#include "Stitcher.h"
#include <iostream>
#include <sstream>
#include <limits>
#include <Eigen/LU>
#include <Eigen/Geometry>
#include <open3d/pipelines/registration/GlobalOptimization.h>
#include <open3d/pipelines/color_map/ColorMapOptimization.h>
Stitcher::Stitcher()
{
}
Stitcher::~Stitcher()
{
}
void Stitcher::setup()
{
volume_ = std::make_unique<open3d::pipelines::integration::ScalableTSDFVolume>(4.0 / 512, 0.04, open3d::pipelines::integration::TSDFVolumeColorType::RGB8);
}
bool printRotMatrix(const Eigen::Matrix4d &mat)
{
double theta = -std::asin(mat(2, 0));
double psi = std::atan2(mat(2, 1)/std::cos(theta), mat(2, 2)/std::cos(theta));
double phi = std::atan2(mat(1, 0)/std::cos(theta), mat(0, 0)/std::cos(theta));
std::cout << theta << ", " << psi << ", " << phi << std::endl;
return (std::abs(theta) > 0.1 || std::abs(psi) > 0.1 || std::abs(phi) > 0.1);
}
void printRotMatrixQ(const Eigen::Matrix4d& mat)
{
Eigen::Matrix3d rot = mat.block<3,3>(0, 0);
Eigen::Quaterniond q(rot);
std::cout << mat(0, 3) << ", " << mat(1, 3) << ", " << mat(2, 3) << ", " << q.x() << ", " << q.y() << ", " << q.z() << ", " << std::endl;
}
void Stitcher::addNewImage(const open3d::geometry::Image& colorImg, const open3d::geometry::Image& depthImg)
{
std::unique_lock<std::mutex> lock(mutex_);
open3d::camera::PinholeCameraIntrinsic intrinsic = open3d::camera::PinholeCameraIntrinsic(
open3d::camera::PinholeCameraIntrinsicParameters::PrimeSenseDefault);
//intrinsic.SetIntrinsics(640, 480, 524.0, 524.0, 316.7, 238.5); // from https://www.researchgate.net/figure/ntrinsic-parameters-of-Kinect-RGB-camera_tbl2_305108995
//intrinsic.SetIntrinsics(640, 480, 517.3, 516.5, 318.6, 255.3); // from Freiburg test data set
//intrinsic.SetIntrinsics(640, 480, 537.408, 537.40877, 321.897, 236.29); // from Calibration of my own camera
//intrinsic.SetIntrinsics(640, 480, 533.82, 533.82, 320.55, 232.35); // from Calibration of my own camera
intrinsic.SetIntrinsics(640, 480, 542.7693, 544.396, 318.79, 239.99); // from Calibration of my own camera
//open3d::io::WriteImageToPNG("color.png", colorImg_);
//open3d::io::WriteImageToPNG("depth.png", depthImg_);
Eigen::Matrix4d odo_init = Eigen::Matrix4d::Identity();
auto depthFlt = depthImg.ConvertDepthToFloatImage(depthScale_, std::numeric_limits<float>::max());
/*{
float *ptr = depthFlt->PointerAt<float>(0, 0);
int size = depthImg.width_ * depthImg.height_;
float maxVal{ std::numeric_limits<float>::lowest() }, minVal{ std::numeric_limits<float>::max() };
for (int i = 0; i < size; i++)
{
const float& val = *ptr;
maxVal = std::max(maxVal, val);
minVal = std::min(minVal, val);
ptr++;
}
std::cout << "Min: " << minVal << ", max: " << maxVal << std::endl;
}*/
open3d::geometry::RGBDImage source(colorImg, *depthFlt);
images_.push_back(source);
if (!oldRGBDImage_.IsEmpty())
{
std::tuple<bool, Eigen::Matrix4d, Eigen::Matrix6d> rgbd_odo =
open3d::pipelines::odometry::ComputeRGBDOdometry(
oldRGBDImage_, source, intrinsic, odo_init,
open3d::pipelines::odometry::RGBDOdometryJacobianFromHybridTerm(),
open3d::pipelines::odometry::OdometryOption({ 20,10,5 }, 0.2));
std::cout << "Matching ";
if (std::get<0>(rgbd_odo))
std::cout << "successful";
else
std::cout << "unsuccessful";
std::cout << std::endl;
//std::cout << " " << std::get<1>(rgbd_odo) << std::endl;
//bool doIntegrate = printRotMatrix(std::get<1>(rgbd_odo)) && (transvec_.size() < 2);
printRotMatrixQ(std::get<1>(rgbd_odo));
if (std::get<0>(rgbd_odo))
{
Eigen::Matrix4d extrinsic = std::get<1>(rgbd_odo);
//Eigen::Matrix4d extrinsicInv = extrinsic.inverse();
transvec_.push_back(extrinsic);
infovec_.push_back(std::get<2>(rgbd_odo));
pos_ = extrinsic * pos_;
Eigen::Matrix4d posInv = pos_.inverse();
volume_->Integrate(source, intrinsic, pos_);
}
}
else
{
Eigen::Matrix4d identity = Eigen::Matrix4d::Identity();
pos_ = identity;
volume_->Integrate(source, intrinsic, identity);
infovec_.push_back(Eigen::Matrix6d::Identity());
transvec_.push_back(identity);
}
posvec_.push_back(pos_);
oldRGBDImage_ = source;
/*{
std::ostringstream ostr;
ostr << "mesh_online_" << transvec_.size() << ".ply";
auto mesh = volume_->ExtractTriangleMesh();
open3d::io::WriteTriangleMesh(ostr.str(),
*mesh);
}*/
}
void Stitcher::saveVolume()
{
auto mesh = volume_->ExtractTriangleMesh();
open3d::io::WriteTriangleMesh("mesh_online.ply",
*mesh);
/*{
std::ostringstream ostr;
ostr << "mesh_online_" << variant_ << ".ply";
auto mesh = volume_->ExtractTriangleMesh();
open3d::io::WriteTriangleMesh(ostr.str(),
*mesh);
}*/
std::cout << "Online mesh saved" << std::endl;
const size_t keyFrameInterval = 3;
const size_t maxKeyFrameDistance = 9;
open3d::camera::PinholeCameraIntrinsic intrinsic = open3d::camera::PinholeCameraIntrinsic(
open3d::camera::PinholeCameraIntrinsicParameters::PrimeSenseDefault);
open3d::pipelines::registration::PoseGraph poseGraph;
Eigen::Matrix4d transOdometry = Eigen::Matrix4d::Identity(), transOdometryInv;
poseGraph.nodes_.push_back(open3d::pipelines::registration::PoseGraphNode(transOdometry));
for (size_t i = 0; i < images_.size() - 1; i++)
{
for (size_t j = i + 1; j < images_.size(); j++)
{
bool isNeighbour = (j == i + 1);
bool doLoopClosure = (i % keyFrameInterval == 0 && j % keyFrameInterval == 0 && (j-i) <= maxKeyFrameDistance);
const open3d::geometry::RGBDImage& source = images_[i];
const open3d::geometry::RGBDImage& target = images_[j];
if (isNeighbour)
{
//Eigen::Matrix4d odo_init = Eigen::Matrix4d::Identity();
//std::tuple<bool, Eigen::Matrix4d, Eigen::Matrix6d> rgbd_odo =
// open3d::pipelines::odometry::ComputeRGBDOdometry(
// source, target, intrinsic, odo_init,
// open3d::pipelines::odometry::RGBDOdometryJacobianFromHybridTerm(),
// open3d::pipelines::odometry::OdometryOption());
//
//transOdometry = std::get<1>(rgbd_odo) * transOdometry;
transOdometry = posvec_[j];
transOdometryInv = transOdometry.inverse();
poseGraph.nodes_.push_back(open3d::pipelines::registration::PoseGraphNode(transOdometryInv));
poseGraph.edges_.push_back(open3d::pipelines::registration::PoseGraphEdge(i, j,
// std::get<1>(rgbd_odo), std::get<2>(rgbd_odo), false));
transvec_[j], infovec_[j], false));
}
else if (doLoopClosure)
{
Eigen::Matrix4d odo_init = Eigen::Matrix4d::Identity();
std::tuple<bool, Eigen::Matrix4d, Eigen::Matrix6d> rgbd_odo =
open3d::pipelines::odometry::ComputeRGBDOdometry(
source, target, intrinsic, odo_init,
open3d::pipelines::odometry::RGBDOdometryJacobianFromHybridTerm(),
open3d::pipelines::odometry::OdometryOption({ 20,10,5 }, 0.1));
if (std::get<0>(rgbd_odo)) // if success==true
{
poseGraph.edges_.push_back(open3d::pipelines::registration::PoseGraphEdge(i, j,
std::get<1>(rgbd_odo), std::get<2>(rgbd_odo), true));
}
}
}
}
open3d::utility::SetVerbosityLevel(open3d::utility::VerbosityLevel::Debug);
// Global optimization
open3d::pipelines::registration::GlobalOptimization(poseGraph);
open3d::utility::SetVerbosityLevel(open3d::utility::VerbosityLevel::Error);
// Integrate
open3d::pipelines::integration::ScalableTSDFVolume optVolume(2.0 / 512, 0.04, open3d::pipelines::integration::TSDFVolumeColorType::RGB8);
for (size_t i = 0; i < poseGraph.nodes_.size(); i++)
{
auto pose = poseGraph.nodes_[i].pose_;
Eigen::Matrix4d poseInv = pose.inverse();
optVolume.Integrate(images_[i], intrinsic, poseInv);
}
// Simplify
auto optMesh = optVolume.ExtractTriangleMesh();
auto simplMesh = optMesh->SimplifyQuadricDecimation(static_cast<int>(optMesh->triangles_.size() / 2), std::numeric_limits<double>::infinity(), 1.0);
open3d::io::WriteTriangleMesh("mesh_opt.ply",
*simplMesh);
std::cout << "Optimized mesh saved" << std::endl;
// Subdivide the mesh to allow for finer color resolution
auto subdivMesh = simplMesh->SubdivideLoop(1);
// Optimize color map
open3d::pipelines::color_map::ColorMapOptimizationOption option(true);
open3d::camera::PinholeCameraTrajectory camera;
for (size_t i = 0; i < poseGraph.nodes_.size(); i++)
{
auto pose = poseGraph.nodes_[i].pose_;
Eigen::Matrix4d poseInv = pose.inverse();
open3d::camera::PinholeCameraParameters cameraParams;
cameraParams.intrinsic_ = intrinsic;
cameraParams.extrinsic_ = poseInv;
camera.parameters_.push_back(cameraParams);
}
open3d::geometry::RGBDImagePyramid rgbdImages;
for (const auto& img : images_)
{
rgbdImages.push_back(std::make_shared<open3d::geometry::RGBDImage>(img));
}
open3d::pipelines::color_map::ColorMapOptimization(*subdivMesh, rgbdImages, camera, option);
open3d::io::WriteTriangleMesh("mesh_color_opt.ply",
*subdivMesh);
}
void Stitcher::reset()
{
std::unique_lock<std::mutex> lock(mutex_);
/*{
std::ostringstream ostr;
ostr << "mesh_online_" << variant_ << ".ply";
auto mesh = volume_->ExtractTriangleMesh();
open3d::io::WriteTriangleMesh(ostr.str(),
*mesh);
}*/
std::cout << "Reset" << std::endl;
oldRGBDImage_.Clear();
pos_ = Eigen::Matrix4d::Identity();
setup();
//volume_->Reset();
images_.clear();
posvec_.clear();
transvec_.clear();
infovec_.clear();
} | 33.862676 | 166 | 0.668192 | [
"mesh",
"geometry"
] |
cfc8e844443b2924d7b3650d6d8a61e736e7e1f7 | 1,610 | cpp | C++ | lib/libCFG/src/BlockQueueUniq.cpp | cyber-itl/citl-static-analysis | 32ef8e519dac1c6a49ff41d902a62df8f5a8e948 | [
"MIT"
] | 14 | 2021-05-03T16:03:22.000Z | 2022-02-14T23:42:39.000Z | lib/libCFG/src/BlockQueueUniq.cpp | cyber-itl/citl-static-analysis | 32ef8e519dac1c6a49ff41d902a62df8f5a8e948 | [
"MIT"
] | 1 | 2021-09-27T12:01:33.000Z | 2021-09-27T12:01:33.000Z | lib/libCFG/src/BlockQueueUniq.cpp | cyber-itl/citl-static-analysis | 32ef8e519dac1c6a49ff41d902a62df8f5a8e948 | [
"MIT"
] | null | null | null | #include <cstdint>
#include <vector>
#include <utility>
#include "glog/logging.h"
#include "Block.hpp"
#include "BlockQueueUniq.hpp"
bool BlockQueueUniq::push(Block block) {
if (m_set.insert(block.start).second) {
m_queue.emplace(block);
return true;
}
return false;
}
Block BlockQueueUniq::pop() {
if (m_queue.empty()) {
LOG(FATAL) << "popped from empty queue";
}
Block val = m_queue.front();
auto it = m_set.find(val.start);
if (it == m_set.end()) {
LOG(FATAL) << "Tried to pop item that was missing from set";
}
if (*it != val.start) {
LOG(FATAL) << "queue and set became mismatched, set != queue.start";
}
m_set.erase(it);
m_queue.pop();
return val;
}
// This should be a slow operation will all the copies,
// but in the context of the CFG it is called very rarely.
// Returns a copy of the deleted element
bool BlockQueueUniq::del_elm(Block block) {
if (!m_set.count(block.start)) {
return false;
}
m_set.erase(block.start);
std::vector<Block> popped_elms;
while (!m_queue.empty()) {
Block cur_elm = m_queue.front();
m_queue.pop();
if (cur_elm == block) {
continue;
}
popped_elms.emplace_back(cur_elm);
}
for (const auto &elm : popped_elms) {
m_queue.emplace(elm);
}
return true;
}
bool BlockQueueUniq::in_queue(const Block &block) const {
if (m_set.count(block.start)) {
return true;
}
return false;
}
bool BlockQueueUniq::empty() const {
return m_queue.empty();
}
| 21.466667 | 76 | 0.604348 | [
"vector"
] |
cfc921f34f5d74d2f81a29e813127c9cef7914fb | 11,207 | cpp | C++ | source/utopian/core/renderer/jobs/AtmosphereJob.cpp | simplerr/Papageno | 7ec1da40dc0459e26f5b9a8a3f72d8962237040d | [
"MIT"
] | null | null | null | source/utopian/core/renderer/jobs/AtmosphereJob.cpp | simplerr/Papageno | 7ec1da40dc0459e26f5b9a8a3f72d8962237040d | [
"MIT"
] | null | null | null | source/utopian/core/renderer/jobs/AtmosphereJob.cpp | simplerr/Papageno | 7ec1da40dc0459e26f5b9a8a3f72d8962237040d | [
"MIT"
] | null | null | null | #include "core/renderer/jobs/AtmosphereJob.h"
#include "core/renderer/jobs/GBufferJob.h"
#include "core/renderer/CommonJobIncludes.h"
#include "core/renderer/Light.h"
#include "core/renderer/Primitive.h"
#include "core/renderer/Model.h"
#include "core/Camera.h"
#include "core/Input.h"
#include <vulkan/vulkan_core.h>
namespace Utopian
{
AtmosphereJob::AtmosphereJob(Vk::Device* device, uint32_t width, uint32_t height)
: BaseJob(device, width, height)
{
sunImage = std::make_shared<Vk::ImageColor>(device, width, height, VK_FORMAT_R8G8B8A8_UNORM, "Atmosphere sun image");
mEnvironmentGenerated = false;
}
AtmosphereJob::~AtmosphereJob()
{
}
void AtmosphereJob::LoadResources()
{
auto loadShader = [&]()
{
Vk::EffectCreateInfo effectDesc;
effectDesc.shaderDesc.vertexShaderPath = "data/shaders/atmosphere/atmosphere.vert";
effectDesc.shaderDesc.fragmentShaderPath = "data/shaders/atmosphere/atmosphere.frag";
effectDesc.pipelineDesc.rasterizationState.cullMode = VK_CULL_MODE_FRONT_BIT;
effectDesc.pipelineDesc.depthStencilState.depthWriteEnable = VK_FALSE;
mEffect = Vk::gEffectManager().AddEffect<Vk::Effect>(mDevice, mRenderTarget->GetRenderPass(), effectDesc);
};
loadShader();
}
void AtmosphereJob::Init(const std::vector<BaseJob*>& jobs, const GBuffer& gbuffer)
{
mRenderTarget = std::make_shared<Vk::RenderTarget>(mDevice, mWidth, mHeight);
mRenderTarget->AddReadWriteColorAttachment(gbuffer.mainImage, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
mRenderTarget->AddWriteOnlyColorAttachment(sunImage);
mRenderTarget->AddReadWriteDepthAttachment(gbuffer.depthImage, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
mRenderTarget->SetClearColor(0, 0, 0);
mRenderTarget->Create();
mParameterBlock.Create(mDevice, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT);
mSkydomeModel = gModelLoader().LoadModel("data/models/sphere.obj");
//environmentCube = Vk::gTextureLoader().LoadCubemapTexture("data/textures/environments/papermill.ktx", VK_FORMAT_R16G16B16A16_SFLOAT);
environmentCube = Vk::gTextureLoader().CreateCubemapTexture(VK_FORMAT_R32G32B32A32_SFLOAT, 512, 512, (uint32_t)floor(log2(512)) + 1);
irradianceMap = Vk::gTextureLoader().CreateCubemapTexture(VK_FORMAT_R32G32B32A32_SFLOAT, 64, 64, (uint32_t)floor(log2(64)) + 1);
specularMap = Vk::gTextureLoader().CreateCubemapTexture(VK_FORMAT_R16G16B16A16_SFLOAT, 512, 512, (uint32_t)floor(log2(512)) + 1);
// const uint32_t size = 240;
// gScreenQuadUi().AddQuad(5 * (size + 10) + 10, mHeight - (2 * size + 10), size, size, sunImage.get(), mRenderTarget->GetSampler());
}
void AtmosphereJob::PostInit(const std::vector<BaseJob*>& jobs, const GBuffer& gbuffer)
{
mEffect->BindUniformBuffer("UBO_sharedVariables", gRenderer().GetSharedShaderVariables());
mEffect->BindUniformBuffer("UBO_atmosphere", mParameterBlock);
}
void AtmosphereJob::CaptureEnvironmentCubemap(glm::vec3 sunDir)
{
mParameterBlock.data.sunDir = sunDir;
mParameterBlock.UpdateMemory();
const uint32_t dimension = environmentCube->GetWidth();
const VkFormat format = environmentCube->GetImage().GetFormat();
const uint32_t numMipLevels = (uint32_t)floor(log2(dimension)) + 1;
//environmentCube = Vk::gTextureLoader().CreateCubemapTexture(format, dimension, dimension, numMipLevels);
// Offscreen framebuffer
SharedPtr<Vk::Image> offscreen = std::make_shared<Vk::ImageColor>(mDevice, dimension,
dimension, format, "Offscreen atmosphere cubemap capture image");
SharedPtr<Vk::ImageDepth> depthImage = std::make_shared<Vk::ImageDepth>(mDevice, mWidth, mHeight, VK_FORMAT_D32_SFLOAT_S8_UINT, "G-buffer depth image");
SharedPtr<Vk::RenderTarget> renderTarget = std::make_shared<Vk::RenderTarget>(mDevice, dimension, dimension);
renderTarget->AddWriteOnlyColorAttachment(offscreen);
renderTarget->AddWriteOnlyColorAttachment(sunImage);
renderTarget->AddWriteOnlyDepthAttachment(depthImage);
renderTarget->SetClearColor(1, 1, 1, 1);
renderTarget->Create();
glm::mat4 matrices[] =
{
glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3( 1.0f, 0.0f, 0.0f), glm::vec3(0.0f, -1.0f, 0.0f)),
glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(-1.0f, 0.0f, 0.0f), glm::vec3(0.0f, -1.0f, 0.0f)),
glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3( 0.0f, 1.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f)),
glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3( 0.0f, -1.0f, 0.0f), glm::vec3(0.0f, 0.0f, -1.0f)),
glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3( 0.0f, 0.0f, 1.0f), glm::vec3(0.0f, -1.0f, 0.0f)),
glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3( 0.0f, 0.0f, -1.0f), glm::vec3(0.0f, -1.0f, 0.0f))
};
Vk::CommandBuffer* commandBuffer = renderTarget->GetCommandBuffer();
commandBuffer->Begin();
renderTarget->BeginDebugLabelAndQueries("Irradiance cubemap generation", glm::vec4(1.0f));
environmentCube->GetImage().LayoutTransition(*commandBuffer, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
for (uint32_t mipLevel = 0; mipLevel < numMipLevels; mipLevel++)
{
for (uint32_t face = 0; face < 6; face++)
{
renderTarget->BeginRenderPass();
float viewportSize = dimension * (float)std::pow(0.5f, mipLevel);
commandBuffer->CmdSetViewPort(viewportSize, viewportSize);
struct PushConsts {
glm::mat4 projection;
glm::mat4 view;
glm::mat4 world;
} pushConsts;
pushConsts.view = matrices[face];
pushConsts.projection = glm::perspective(glm::radians(90.0f), 1.0f, 0.01f, 20000.0f);
glm::mat4 world = glm::rotate(glm::mat4(), glm::radians(180.0f), glm::vec3(1.0f, 0.0f, 0.0f));
pushConsts.world = glm::scale(world, glm::vec3(16.0f));
commandBuffer->CmdPushConstants(mEffect->GetPipelineInterface(), VK_SHADER_STAGE_ALL, sizeof(PushConsts), &pushConsts.projection);
commandBuffer->CmdBindPipeline(mEffect->GetPipeline());
commandBuffer->CmdBindDescriptorSets(mEffect);
Primitive* primitive = mSkydomeModel->GetPrimitive(0);
commandBuffer->CmdBindVertexBuffer(0, 1, primitive->GetVertxBuffer());
commandBuffer->CmdBindIndexBuffer(primitive->GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32);
commandBuffer->CmdDrawIndexed(primitive->GetNumIndices(), 1, 0, 0, 0);
commandBuffer->CmdEndRenderPass();
// Copy region for transfer from framebuffer to cube face
VkImageCopy copyRegion = {};
copyRegion.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
copyRegion.srcSubresource.baseArrayLayer = 0;
copyRegion.srcSubresource.mipLevel = 0;
copyRegion.srcSubresource.layerCount = 1;
copyRegion.srcOffset = { 0, 0, 0 };
copyRegion.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
copyRegion.dstSubresource.baseArrayLayer = face;
copyRegion.dstSubresource.mipLevel = mipLevel;
copyRegion.dstSubresource.layerCount = 1;
copyRegion.dstOffset = { 0, 0, 0 };
copyRegion.extent.width = static_cast<uint32_t>(viewportSize);
copyRegion.extent.height = static_cast<uint32_t>(viewportSize);
copyRegion.extent.depth = 1;
offscreen->LayoutTransition(*commandBuffer, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
vkCmdCopyImage(commandBuffer->GetVkHandle(), offscreen->GetVkHandle(),
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, environmentCube->GetImage().GetVkHandle(),
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©Region);
offscreen->LayoutTransition(*commandBuffer, offscreen->GetFinalLayout());
}
}
environmentCube->GetImage().LayoutTransition(*commandBuffer, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
renderTarget->EndDebugLabelAndQueries();
commandBuffer->Flush();
}
void AtmosphereJob::PreRender(const JobInput& jobInput)
{
// If there is a new directional light in the scene then the
// environment map needs to be recaptured. Note: if the environment
// capturing is moved to somewhere else this could be cleaned up.
static Light* directionalLight = jobInput.sceneInfo.directionalLight;
bool newLight = false;
if (directionalLight != jobInput.sceneInfo.directionalLight)
{
newLight = true;
directionalLight = jobInput.sceneInfo.directionalLight;
}
if (newLight || !mEnvironmentGenerated || gInput().KeyPressed('R'))
{
glm::vec3 sunDir = glm::vec3(0.0f);
if (jobInput.sceneInfo.directionalLight != nullptr)
sunDir = jobInput.sceneInfo.directionalLight->GetDirection();
CaptureEnvironmentCubemap(sunDir);
gRendererUtility().FilterCubemap(environmentCube.get(), irradianceMap.get(),
"data/shaders/ibl_filtering/irradiance_filter.frag");
gRendererUtility().FilterCubemap(environmentCube.get(), specularMap.get(),
"data/shaders/ibl_filtering/specular_filter.frag");
mEnvironmentGenerated = true;
}
}
void AtmosphereJob::Render(const JobInput& jobInput)
{
if (jobInput.sceneInfo.directionalLight != nullptr)
mParameterBlock.data.sunDir = jobInput.sceneInfo.directionalLight->GetDirection();
else
mParameterBlock.data.sunDir = glm::vec3(0.0f);
mParameterBlock.UpdateMemory();
mRenderTarget->Begin("Atmosphere pass", glm::vec4(0.1, 0.8, 0.8, 1.0));
Vk::CommandBuffer* commandBuffer = mRenderTarget->GetCommandBuffer();
struct PushConsts {
glm::mat4 projection;
glm::mat4 view;
glm::mat4 world;
} pushConsts;
pushConsts.view = gRenderer().GetMainCamera()->GetView();
pushConsts.projection = gRenderer().GetMainCamera()->GetProjection();
glm::mat4 world = glm::rotate(glm::mat4(), glm::radians(180.0f), glm::vec3(1.0f, 0.0f, 0.0f));
pushConsts.world = glm::scale(world, glm::vec3(16.0f));
commandBuffer->CmdPushConstants(mEffect->GetPipelineInterface(), VK_SHADER_STAGE_ALL, sizeof(PushConsts), &pushConsts.projection);
// Todo: Should this be moved to the effect instead?
commandBuffer->CmdBindPipeline(mEffect->GetPipeline());
commandBuffer->CmdBindDescriptorSets(mEffect);
Primitive* primitive = mSkydomeModel->GetPrimitive(0);
commandBuffer->CmdBindVertexBuffer(0, 1, primitive->GetVertxBuffer());
commandBuffer->CmdBindIndexBuffer(primitive->GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32);
commandBuffer->CmdDrawIndexed(primitive->GetNumIndices(), 1, 0, 0, 0);
mRenderTarget->End(GetWaitSemahore(), GetCompletedSemahore());
}
}
| 46.695833 | 161 | 0.681271 | [
"render",
"vector",
"model"
] |
cfd49ac327751d735fc0c63611692e13ea9c0d5e | 1,802 | cpp | C++ | lib/modules/CommLink.cpp | CollinAvidano/robocup-firmware | 847900af9a4a4b3aef4b9aab494b75723b3e10a4 | [
"Apache-2.0"
] | null | null | null | lib/modules/CommLink.cpp | CollinAvidano/robocup-firmware | 847900af9a4a4b3aef4b9aab494b75723b3e10a4 | [
"Apache-2.0"
] | null | null | null | lib/modules/CommLink.cpp | CollinAvidano/robocup-firmware | 847900af9a4a4b3aef4b9aab494b75723b3e10a4 | [
"Apache-2.0"
] | null | null | null | #include "CommLink.hpp"
#include "Assert.hpp"
#include "Logger.hpp"
namespace {
// DEFAULT_STACK_SIZE defined in rtos library
constexpr auto STACK_SIZE = DEFAULT_STACK_SIZE / 2;
constexpr auto RX_PRIORITY = osPriorityHigh;
}
std::unique_ptr<CommLink> globalRadio = nullptr;
CommLink::CommLink(SpiPtrT sharedSPI, PinName nCs, PinName intPin)
: SharedSPIDevice(sharedSPI, nCs, true),
m_intIn(intPin),
m_rxThread(&CommLink::rxThreadHelper, this, RX_PRIORITY, STACK_SIZE) {
setSPIFrequency(5'000'000);
m_intIn.mode(PullDown);
ready();
}
// Task operations for placing received data into the received data queue
void CommLink::rxThread() {
// Store our priority so we know what to reset it to if ever needed
// const auto threadPriority = m_rxThread.get_priority();
//(void)threadPriority; // disable compiler warning for unused-variable
// ASSERT(threadPriority != osPriorityError);
// Set the function to call on an interrupt trigger
m_intIn.rise(this, &CommLink::ISR);
// Only continue past this point once the hardware link is initialized
Thread::signal_wait(SIGNAL_START);
// LOG(OK, "RX communication link ready!\r\n Thread ID: %u, Priority:
// %d",
// reinterpret_cast<P_TCB>(m_rxThread.gettid())->task_id,
// threadPriority);
while (true) {
// Wait until new data has arrived
Thread::signal_wait(SIGNAL_RX);
LOG(DEBUG, "RX interrupt triggered");
// Get the received data from the external chip
auto response = getData();
if (!response.empty()) {
// Write the data to the CommModule object's rxQueue
CommModule::Instance->receive(rtp::Packet(response));
}
}
ASSERT(!"Execution is at an unreachable line!");
}
| 31.068966 | 76 | 0.679245 | [
"object"
] |
cfd66b84d2e61b51c666f7f7f3cf26f85aae455d | 2,488 | cpp | C++ | Furiosity/Gameplay/3D/DynamicEntity3D.cpp | enci/Furiosity | 0f823b31ba369a6f20a69ca079627dccd4b4549a | [
"MIT"
] | 7 | 2015-05-14T18:36:18.000Z | 2020-08-30T19:09:33.000Z | Furiosity/Gameplay/3D/DynamicEntity3D.cpp | enci/Furiosity | 0f823b31ba369a6f20a69ca079627dccd4b4549a | [
"MIT"
] | 1 | 2015-10-23T14:24:08.000Z | 2015-10-23T14:24:08.000Z | Furiosity/Gameplay/3D/DynamicEntity3D.cpp | enci/Furiosity | 0f823b31ba369a6f20a69ca079627dccd4b4549a | [
"MIT"
] | 1 | 2020-07-31T23:34:49.000Z | 2020-07-31T23:34:49.000Z | ////////////////////////////////////////////////////////////////////////////////
// DynamicEntity3D.cpp
// Furiosity
//
// Created by Bojan Endrovski on 9/17/13.
// Copyright (c) 2013 Furious Pixels. All rights reserved.
////////////////////////////////////////////////////////////////////////////////
#include "DynamicEntity3D.h"
#include "DebugDraw3D.h"
using namespace Furiosity;
DynamicEntity3D::DynamicEntity3D(World3D* world, Entity3D* parent, float radius) :
Entity3D(world, parent, radius),
maxForce(FLT_MAX),
maxSpeed(FLT_MAX),
linearDamping(0.98f),
inverseMass(1.0f)
{}
void DynamicEntity3D::LoadFromXml(const XMLElement& settings)
{
// Load bounding radius
Entity3D::LoadFromXml(settings);
// Params
settings.QueryFloatAttribute("maxSpeed", &maxSpeed);
settings.QueryFloatAttribute("maxForce", &maxForce);
settings.QueryFloatAttribute("linearDamping", &linearDamping);
//
// Mass
float mass;
settings.QueryFloatAttribute("mass", &mass);
inverseMass = 1 / mass;
}
void DynamicEntity3D::Update(float dt)
{
// Trim max force
force.Trim(maxForce);
// gDebugDraw2D.AddLine(Position(), Position() + force, Color::Orange);
// Acceleration = Force/Mass
Vector3 acceleration = force * 1.0f; // inverseMass;
// update velocity
velocity += acceleration * dt;
// Add fake linear damping
velocity -= velocity * linearDamping;
// make sure vehicle does not exceed maximum velocity
velocity.Trim(maxSpeed);
// clear the accumulator for the next frame
force.Clear();
//update the heading if the vehicle has a non zero velocity
if(velocity.SquareMagnitude() > 0.001f)
{
// update the position
Vector3 position = Position();
position += velocity * dt;
SetPosition(position);
/*
// if(maxTurnRate > 0.0f)
{
// Set local coordinate frame
Vector3 fwd = velocity;
fwd.Normalize();
//
Vector3 up(0, 1, 0);
// Vector3 up = position;
// up.Normalize();
Vector3 side = fwd % up; // Cross
up = side % fwd;
//
_trns.SetOrientation(side, up, fwd);
}
*/
}
#ifdef DEBUG
gDebugDraw3D.AddAxis(Transform(), 0.3f);
gDebugDraw3D.AddLine(Position(), Position() + force);
#endif
} | 27.340659 | 82 | 0.561093 | [
"transform"
] |
cfe6d7bf3b5c71fe5e302a6697bc0e346a6eb7a0 | 111 | cpp | C++ | Framework/01_pjsua/src/Global.cpp | zhenkunhe/Developer-Tutorial | 6e4e4e36364fd8081a68ebf43bf6ab433add613e | [
"MIT"
] | null | null | null | Framework/01_pjsua/src/Global.cpp | zhenkunhe/Developer-Tutorial | 6e4e4e36364fd8081a68ebf43bf6ab433add613e | [
"MIT"
] | null | null | null | Framework/01_pjsua/src/Global.cpp | zhenkunhe/Developer-Tutorial | 6e4e4e36364fd8081a68ebf43bf6ab433add613e | [
"MIT"
] | null | null | null | #include <pjsua/Global.hpp>
ThreadPool Global::pool( THREAD_POOL_SIZE );
vector<future<int>> Global::results;
| 22.2 | 44 | 0.765766 | [
"vector"
] |
cfe8bce432387eeaaadd64a8b9b3422ab3cd6237 | 8,355 | cpp | C++ | src/lib/VideoReader.subsref.cpp | Joe136/octave-forge-video | eb31e64ae5933b09c3c05033404c89b9fe88c8b9 | [
"BSD-2-Clause"
] | null | null | null | src/lib/VideoReader.subsref.cpp | Joe136/octave-forge-video | eb31e64ae5933b09c3c05033404c89b9fe88c8b9 | [
"BSD-2-Clause"
] | null | null | null | src/lib/VideoReader.subsref.cpp | Joe136/octave-forge-video | eb31e64ae5933b09c3c05033404c89b9fe88c8b9 | [
"BSD-2-Clause"
] | null | null | null | /* Copyright (C) 2015 Joe136 <Joe136@users.noreply.github.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. */
//---------------------------Includes----------------------------------------------//
#include <octave/oct.h>
#include <octave/oct-map.h>
#include "VideoReader.h"
#include <opencv2/opencv.hpp>
#include "includes/logging.h"
//---------------------------Start subsref-----------------------------------------//
octave_value_list VideoReader::subsref (const std::string &type, const std::list< octave_value_list > &idx, int nargout) {
LOGGING ("VideoReader::subsref(\"%s\", <idx>[%lu], %i)\n", type.c_str (), idx.size (), nargout); //TODO 'type' and 'idx' could be nullptr
octave_value_list retval;
// Variables
if (idx.size () == 1 && type.length () >= 1 && type[0] == '.') {
std::string s = idx.front ()(0).string_value ();
std::transform(s.begin(), s.end(), s.begin(), ::tolower);
if (!s.compare ("numberofframes") )
retval(0) = octave_value (m_oVC.get (CV_CAP_PROP_FRAME_COUNT) );
else if (!s.compare ("height") )
retval(0) = octave_value (m_oVC.get (CV_CAP_PROP_FRAME_HEIGHT) );
else if (!s.compare ("width") )
retval(0) = octave_value (m_oVC.get (CV_CAP_PROP_FRAME_WIDTH) );
else if (!s.compare ("framerate") )
retval(0) = octave_value (m_oVC.get (CV_CAP_PROP_FPS) );
else if (!s.compare ("userdata") )
retval(0) = octave_value (m_oUserData);
else if (!s.compare ("tag") )
retval(0) = octave_value (m_sTag);
else if (!s.compare ("currenttime") )
retval(0) = octave_value (m_oVC.get (CV_CAP_PROP_POS_MSEC) / 1000);
//warning ("VideoReader: 'currenttime' not implemented yet");
else if (!s.compare ("duration") ) {
#ifdef FFMPEG_HACK
cv::CvCapture_FFMPEG *cap = m_oVC.getFFmpegCap ();
if (!cap || !cap->ic)
retval(0) = octave_value (-1);
else {
retval(0) = octave_value ( ( (double)cap->ic->duration) / 1000000.0f);
}
#else
warning ("VideoReader: 'duration' not implemented yet");
#endif
} else if (!s.compare ("time") ) {
#ifdef FFMPEG_HACK
cv::CvCapture_FFMPEG *cap = m_oVC.getFFmpegCap ();
if (!cap || !cap->ic)
retval(0) = octave_value (-1);
else {
char s[20];
double duration = (double)cap->ic->duration;
int msec = duration / 1000;
int sec = msec / 1000;
int min = sec / 60;
int hour = min / 60;
snprintf (s, 20, "%02i:%02i:%02i.%03i", hour, min % 60, sec % 60, msec % 1000);
retval(0) = octave_value (std::string (s) );
}
#else
warning ("VideoReader: 'time' not implemented yet");
#endif
} else if (!s.compare ("path") )
retval(0) = octave_value (m_sFilename);
else if (!s.compare ("iscamera") )
retval(0) = octave_value (m_bIsCamera);
else if (!s.compare ("isvalid") )
retval(0) = octave_value (m_bIsValid);
else if (!s.compare ("name") )
warning ("VideoReader: 'name' not implemented yet");
else if (!s.compare ("bitsperpixel") )
warning ("VideoReader: 'bitsperpixel' not implemented yet");
else if (!s.compare ("type") )
retval(0) = octave_value (std::string ("VideoReader") );
//warning ("VideoReader: 'type' not implemented yet");
else if (!s.compare ("videoformat") )
retval(0) = octave_value (fourccToString (m_oVC.get (CV_CAP_PROP_FOURCC) ) ); //TODO this is not the same as matlab says, it's the image type: e.g. 'RGB24'
//warning ("VideoReader: 'videoformat' not implemented yet");
else if (!s.compare ("fourcc") )
retval(0) = octave_value (fourccToString (m_oVC.get (CV_CAP_PROP_FOURCC) ) );
else
error ("VideoReader: unknown VideoReader property %s", s.c_str () );
// Functions
} else if (idx.size () == 2 && type.length () >= 1 && type[0] == '.' && type[1] == '(') {
std::string s = idx.front ()(0).string_value ();
std::transform(s.begin(), s.end(), s.begin(), ::tolower);
if (!s.compare ("read") ) {
octave_value_list list = *(++ idx.begin () );
int from = 1;
int to = m_oVC.get (CV_CAP_PROP_FRAME_COUNT); //TODO this call doesn't work
bool native = false;
if (list.length () > 0) {
//for (int i = 0; i < list.length(); ++i) {
// list(i).print_info (octave_stdout);
//}//end for
if (list(0).is_real_matrix () ) {
Matrix m = list(0).matrix_value ();
if (m.length () >= 1) {
from = (int)m(0);
if (m.length () >= 2)
to = (int)m(1);
else
to = from;
} else {
error ("VideoReader: argument 1 is an empty vector");
return retval;
}
} else if (list(0).is_scalar_type () ) {
from = (int)list(0).scalar_value ();
to = from;
}
for (int i = 0; i < list.length(); ++i) {
if (list(i).is_char_matrix () ) {
std::string ss = list(i).char_matrix_value ().row_as_string (0);
std::transform(ss.begin(), ss.end(), ss.begin(), ::tolower);
if (!ss.compare ("native") )
native = true;
}
}//end for
}
retval(0) = read (from, to, native);
} else if (!s.compare ("readframe") ) {
retval(0) = read ();
} else if (!s.compare ("hasframe") ) {
warning ("VideoReader: 'hasFrame' not implemented yet");
} else if (!s.compare ("get") ) {
warning ("VideoReader: 'get' not implemented yet");
} else if (!s.compare ("set") ) {
octave_value_list list = *(++ idx.begin () );
if (list.length () >= 2 && list.length () % 2 == 0) {
boolNDArray resMap = boolNDArray (dim_vector (list.length () / 2, 1) );
for (int i = 0, n = 0; i < list.length(); i += 2, ++n) {
if (list(i).is_char_matrix () )
resMap(n) = this->set (list(i).char_matrix_value ().row_as_string (0), list(i + 1) );
else
error ("VideoReader: argument %i (should be a parameter name) is not a string", i);
}//end for
retval(0) = resMap;
} else
error ("VideoReader: uneven count of arguments");
// } else if (!s.compare ("codecs") ) {
// retval(0) = octave_value (m_oVC.print_codecs () );
} else if (!s.compare ("getfileformats") ) {
//retval(0) = octave_value (m_oVC.print_file_formats () );
warning ("VideoReader: 'getfileformats' not implemented yet");
} else if (!s.compare ("fullcheck") ) {
retval(0) = fullCheck ();
} else
error ("VideoReader: unknown VideoReader method '%s'", s.c_str () );
}
return retval;
}//end Fct
| 37.977273 | 166 | 0.553561 | [
"vector",
"transform"
] |
cff6bd8c7e1c167b78592cf03c8a9ce2a2f037b0 | 9,476 | cpp | C++ | test/test_linear_model.cpp | accosmin/libnan | a47c28f22df2c0943697dccb007de946090c7705 | [
"MIT"
] | null | null | null | test/test_linear_model.cpp | accosmin/libnan | a47c28f22df2c0943697dccb007de946090c7705 | [
"MIT"
] | null | null | null | test/test_linear_model.cpp | accosmin/libnan | a47c28f22df2c0943697dccb007de946090c7705 | [
"MIT"
] | null | null | null | #include "fixture/loss.h"
#include "fixture/linear.h"
#include <nano/linear/regularization.h>
using namespace nano;
static void check_outputs(const dataset_generator_t& generator,
const indices_t& samples, const tensor4d_t& outputs, scalar_t epsilon)
{
auto iterator = flatten_iterator_t{generator, samples};
iterator.batch(7);
iterator.scaling(scaling_type::none);
iterator.execution(execution_type::seq);
iterator.loop([&] (tensor_range_t range, size_t, tensor4d_cmap_t targets)
{
UTEST_CHECK_CLOSE(targets, outputs.slice(range), epsilon);
});
}
static auto make_smooth_solver()
{
auto solver = solver_t::all().get("lbfgs");
UTEST_REQUIRE(solver);
solver->parameter("solver::max_evals") = 1000;
solver->parameter("solver::epsilon") = 1e-12;
solver->lsearchk("cgdescent");
return solver;
}
static auto make_nonsmooth_solver()
{
auto solver = solver_t::all().get("osga");
UTEST_REQUIRE(solver);
solver->parameter("solver::max_evals") = 2000;
solver->parameter("solver::epsilon") = 1e-6;
return solver;
}
static auto make_solver(const string_t& loss_id)
{
return loss_id == "squared" ? make_smooth_solver() : make_nonsmooth_solver();
}
static auto make_model()
{
auto model = linear_model_t{};
model.parameter("model::folds") = 2;
model.parameter("model::linear::batch") = 10;
model.logger([] (const fit_result_t& result, const string_t& prefix)
{
auto&& logger = log_info();
logger << std::fixed << std::setprecision(9) << std::fixed << prefix << ": ";
const auto print_params = [&] (const tensor1d_t& param_values)
{
assert(result.m_param_names.size() == static_cast<size_t>(param_values.size()));
for (size_t i = 0U, size = result.m_param_names.size(); i < size; ++ i)
{
logger << result.m_param_names[i] << "=" << param_values(static_cast<tensor_size_t>(i)) << ",";
}
};
if (std::isfinite(result.m_refit_error))
{
print_params(result.m_refit_params);
logger << "refit=" << result.m_refit_value << "/" << result.m_refit_error << ".";
}
else if (!result.m_cv_results.empty())
{
const auto& cv_result = *result.m_cv_results.rbegin();
print_params(cv_result.m_params);
logger << "train=" << cv_result.m_train_values.mean() << "/" << cv_result.m_train_errors.mean() << ",";
logger << "valid=" << cv_result.m_valid_values.mean() << "/" << cv_result.m_valid_errors.mean() << ".";
}
});
return model;
}
static void check_result(const fit_result_t& result,
const strings_t& expected_param_names, size_t min_cv_results_size, scalar_t epsilon)
{
UTEST_CHECK_CLOSE(result.m_refit_value, 0.0, epsilon);
UTEST_CHECK_CLOSE(result.m_refit_error, 0.0, epsilon);
UTEST_CHECK_EQUAL(result.m_param_names, expected_param_names);
UTEST_REQUIRE_GREATER_EQUAL(result.m_cv_results.size(), min_cv_results_size);
const auto opt_values = make_full_tensor<scalar_t>(make_dims(2), 0.0);
const auto opt_errors = make_full_tensor<scalar_t>(make_dims(2), 0.0);
tensor_size_t hits = 0;
for (const auto& cv_result : result.m_cv_results)
{
UTEST_CHECK_GREATER(cv_result.m_params.min(), 0.0);
UTEST_CHECK_EQUAL(cv_result.m_params.size(), static_cast<tensor_size_t>(expected_param_names.size()));
if (close(cv_result.m_train_errors, opt_errors, epsilon))
{
++ hits;
UTEST_CHECK_CLOSE(cv_result.m_train_values, opt_values, 1.0 * epsilon);
UTEST_CHECK_CLOSE(cv_result.m_train_errors, opt_errors, 1.0 * epsilon);
UTEST_CHECK_CLOSE(cv_result.m_valid_values, opt_values, 5.0 * epsilon);
UTEST_CHECK_CLOSE(cv_result.m_valid_errors, opt_errors, 5.0 * epsilon);
}
}
if (!expected_param_names.empty())
{
UTEST_CHECK_GREATER(hits, 0);
}
else
{
UTEST_CHECK(result.m_cv_results.empty());
}
}
static void check_model(const linear_model_t& model,
const dataset_generator_t& dataset, const indices_t& samples, scalar_t epsilon)
{
const auto outputs = model.predict(dataset, samples);
check_outputs(dataset, samples, outputs, epsilon);
string_t str;
{
std::ostringstream stream;
UTEST_REQUIRE_NOTHROW(model.write(stream));
str = stream.str();
}
{
auto new_model = linear_model_t{};
std::istringstream stream(str);
UTEST_REQUIRE_NOTHROW(new_model.read(stream));
const auto new_outputs = model.predict(dataset, samples);
UTEST_CHECK_CLOSE(outputs, new_outputs, epsilon0<scalar_t>());
}
}
UTEST_BEGIN_MODULE(test_linear_model)
UTEST_CASE(regularization_none)
{
const auto dataset = make_dataset(100, 1, 4);
const auto generator = make_generator(dataset);
const auto samples = arange(0, dataset.samples());
auto model = make_model();
model.parameter("model::linear::scaling") = scaling_type::none;
model.parameter("model::linear::regularization") = linear::regularization_type::none;
const auto param_names = strings_t{};
for (const auto* const loss_id : {"squared", "absolute"})
{
[[maybe_unused]] const auto _ = utest_test_name_t{loss_id};
const auto loss = make_loss(loss_id);
const auto solver = make_solver(loss_id);
const auto result = model.fit(generator, samples, *loss, *solver);
const auto epsilon = string_t{loss_id} == "squared" ? 1e-6 : 1e-3;
check_result(result, param_names, 0U, epsilon);
check_model(model, generator, samples, epsilon);
}
}
UTEST_CASE(regularization_lasso)
{
const auto dataset = make_dataset(100, 1, 4);
const auto generator = make_generator(dataset);
const auto samples = arange(0, dataset.samples());
auto model = make_model();
model.parameter("model::linear::scaling") = scaling_type::standard;
model.parameter("model::linear::regularization") = linear::regularization_type::lasso;
const auto param_names = strings_t{"l1reg"};
for (const auto* const loss_id : {"squared", "absolute"})
{
[[maybe_unused]] const auto _ = utest_test_name_t{loss_id};
const auto loss = make_loss(loss_id);
const auto solver = make_nonsmooth_solver();
const auto result = model.fit(generator, samples, *loss, *solver);
const auto epsilon = 1e-3;
check_result(result, param_names, 6U, epsilon);
check_model(model, generator, samples, epsilon);
}
}
UTEST_CASE(regularization_ridge)
{
const auto dataset = make_dataset(100, 1, 4);
const auto generator = make_generator(dataset);
const auto samples = arange(0, dataset.samples());
auto model = make_model();
model.parameter("model::linear::scaling") = scaling_type::mean;
model.parameter("model::linear::regularization") = linear::regularization_type::ridge;
const auto param_names = strings_t{"l2reg"};
for (const auto* const loss_id : {"squared", "absolute"})
{
[[maybe_unused]] const auto _ = utest_test_name_t{loss_id};
const auto loss = make_loss(loss_id);
const auto solver = make_solver(loss_id);
const auto result = model.fit(generator, samples, *loss, *solver);
const auto epsilon = string_t{loss_id} == "squared" ? 1e-6 : 1e-3;
check_result(result, param_names, 6U, epsilon);
check_model(model, generator, samples, epsilon);
}
}
UTEST_CASE(regularization_variance)
{
const auto dataset = make_dataset(100, 1, 4);
const auto generator = make_generator(dataset);
const auto samples = arange(0, dataset.samples());
auto model = make_model();
model.parameter("model::linear::scaling") = scaling_type::minmax;
model.parameter("model::linear::regularization") = linear::regularization_type::variance;
const auto param_names = strings_t{"vAreg"};
for (const auto* const loss_id : {"squared", "absolute"})
{
[[maybe_unused]] const auto _ = utest_test_name_t{loss_id};
const auto loss = make_loss(loss_id);
const auto solver = make_solver(loss_id);
const auto result = model.fit(generator, samples, *loss, *solver);
const auto epsilon = string_t{loss_id} == "squared" ? 1e-6 : 1e-3;
check_result(result, param_names, 6U, epsilon);
check_model(model, generator, samples, epsilon);
}
}
UTEST_CASE(regularization_elasticnet)
{
const auto dataset = make_dataset(200, 1, 4);
const auto generator = make_generator(dataset);
const auto samples = arange(0, dataset.samples());
auto model = make_model();
model.parameter("model::linear::scaling") = scaling_type::minmax;
model.parameter("model::linear::regularization") = linear::regularization_type::elasticnet;
const auto param_names = strings_t{"l1reg", "l2reg"};
for (const auto* const loss_id : {"squared", "absolute"})
{
[[maybe_unused]] const auto _ = utest_test_name_t{loss_id};
const auto loss = make_loss(loss_id);
const auto solver = make_nonsmooth_solver();
const auto result = model.fit(generator, samples, *loss, *solver);
const auto epsilon = 1e-3;
check_result(result, param_names, 15U, epsilon);
check_model(model, generator, samples, epsilon);
}
}
UTEST_END_MODULE()
| 35.62406 | 115 | 0.663149 | [
"model"
] |
cff7613b7626248e1d3ccaf2bebeb907742cbff4 | 3,771 | hpp | C++ | ext/src/java/lang/Long.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | ext/src/java/lang/Long.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | ext/src/java/lang/Long.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | // Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar
#pragma once
#include <fwd-POI.hpp>
#include <java/lang/fwd-POI.hpp>
#include <java/math/fwd-POI.hpp>
#include <java/lang/Number.hpp>
#include <java/lang/Comparable.hpp>
struct default_init_tag;
class java::lang::Long final
: public Number
, public Comparable
{
public:
typedef Number super;
static constexpr int32_t BYTES { int32_t(8) };
static constexpr int64_t MAX_VALUE { int64_t(9223372036854775807LL) };
static constexpr int64_t MIN_VALUE { int64_t(-0x7fffffffffffffffLL-1) };
static constexpr int32_t SIZE { int32_t(64) };
private:
static Class* TYPE_;
static constexpr int64_t serialVersionUID { int64_t(4290774380558885855LL) };
int64_t value { };
protected:
void ctor(int64_t value);
void ctor(String* s);
public:
static int32_t bitCount(int64_t i);
int8_t byteValue() override;
static int32_t compare(int64_t x, int64_t y);
int32_t compareTo(Long* anotherLong);
static int32_t compareUnsigned(int64_t x, int64_t y);
static Long* decode(String* nm);
static int64_t divideUnsigned(int64_t dividend, int64_t divisor);
double doubleValue() override;
bool equals(Object* obj) override;
float floatValue() override;
public: /* package */
static int32_t formatUnsignedLong(int64_t val, int32_t shift, ::char16_tArray* buf, int32_t offset, int32_t len);
static void getChars(int64_t i, int32_t index, ::char16_tArray* buf);
public:
static Long* getLong(String* nm);
static Long* getLong(String* nm, int64_t val);
static Long* getLong(String* nm, Long* val);
int32_t hashCode() override;
static int32_t hashCode(int64_t value);
static int64_t highestOneBit(int64_t i);
int32_t intValue() override;
int64_t longValue() override;
static int64_t lowestOneBit(int64_t i);
static int64_t max(int64_t a, int64_t b);
static int64_t min(int64_t a, int64_t b);
static int32_t numberOfLeadingZeros(int64_t i);
static int32_t numberOfTrailingZeros(int64_t i);
static int64_t parseLong(String* s);
static int64_t parseLong(String* s, int32_t radix);
static int64_t parseUnsignedLong(String* s);
static int64_t parseUnsignedLong(String* s, int32_t radix);
static int64_t remainderUnsigned(int64_t dividend, int64_t divisor);
static int64_t reverse(int64_t i);
static int64_t reverseBytes(int64_t i);
static int64_t rotateLeft(int64_t i, int32_t distance);
static int64_t rotateRight(int64_t i, int32_t distance);
int16_t shortValue() override;
static int32_t signum(int64_t i);
public: /* package */
static int32_t stringSize(int64_t x);
public:
static int64_t sum(int64_t a, int64_t b);
static String* toBinaryString(int64_t i);
static String* toHexString(int64_t i);
static String* toOctalString(int64_t i);
String* toString() override;
static String* toString(int64_t i);
static String* toString(int64_t i, int32_t radix);
/*static ::java::math::BigInteger* toUnsignedBigInteger(int64_t i); (private) */
static String* toUnsignedString(int64_t i);
static String* toUnsignedString(int64_t i, int32_t radix);
public: /* package */
static String* toUnsignedString0(int64_t val, int32_t shift);
public:
static Long* valueOf(String* s);
static Long* valueOf(int64_t l);
static Long* valueOf(String* s, int32_t radix);
// Generated
Long(int64_t value);
Long(String* s);
protected:
Long(const ::default_init_tag&);
public:
static ::java::lang::Class *class_();
virtual int32_t compareTo(Object* o) override;
static Class*& TYPE();
private:
virtual ::java::lang::Class* getClass0();
};
| 33.078947 | 117 | 0.718907 | [
"object"
] |
320219c7e5af97fd329c0e728a2987747dba62c5 | 7,449 | cpp | C++ | Code/Framework/AzCore/AzCore/Settings/ConfigurableStack.cpp | BreakerOfThings/o3de | f4c59f868c726470ec910623facd836047d059c3 | [
"Apache-2.0",
"MIT"
] | 1 | 2022-03-28T08:06:58.000Z | 2022-03-28T08:06:58.000Z | Code/Framework/AzCore/AzCore/Settings/ConfigurableStack.cpp | BreakerOfThings/o3de | f4c59f868c726470ec910623facd836047d059c3 | [
"Apache-2.0",
"MIT"
] | null | null | null | Code/Framework/AzCore/AzCore/Settings/ConfigurableStack.cpp | BreakerOfThings/o3de | f4c59f868c726470ec910623facd836047d059c3 | [
"Apache-2.0",
"MIT"
] | null | null | null | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <AzCore/Memory/SystemAllocator.h>
#include <AzCore/Settings/ConfigurableStack.h>
#include <AzCore/Serialization/Json/RegistrationContext.h>
#include <AzCore/std/containers/queue.h>
#include <AzCore/std/tuple.h>
namespace AZ
{
AZ_CLASS_ALLOCATOR_IMPL(JsonConfigurableStackSerializer, AZ::SystemAllocator, 0);
JsonSerializationResult::Result JsonConfigurableStackSerializer::Load(
void* outputValue,
[[maybe_unused]] const Uuid& outputValueTypeId,
const rapidjson::Value& inputValue,
JsonDeserializerContext& context)
{
namespace JSR = JsonSerializationResult; // Used remove name conflicts in AzCore in uber builds.
switch (inputValue.GetType())
{
case rapidjson::kArrayType:
return LoadFromArray(outputValue, inputValue, context);
case rapidjson::kObjectType:
return LoadFromObject(outputValue, inputValue, context);
case rapidjson::kNullType:
[[fallthrough]];
case rapidjson::kFalseType:
[[fallthrough]];
case rapidjson::kTrueType:
[[fallthrough]];
case rapidjson::kStringType:
[[fallthrough]];
case rapidjson::kNumberType:
return context.Report(
JSR::Tasks::ReadField, JSR::Outcomes::Unsupported,
"Unsupported type. Configurable stack values can only be read from arrays or objects.");
default:
return context.Report(JSR::Tasks::ReadField, JSR::Outcomes::Unknown, "Unknown json type encountered for string value.");
}
}
JsonSerializationResult::Result JsonConfigurableStackSerializer::Store(
[[maybe_unused]] rapidjson::Value& outputValue,
[[maybe_unused]] const void* inputValue,
[[maybe_unused]] const void* defaultValue,
[[maybe_unused]] const Uuid& valueTypeId,
JsonSerializerContext& context)
{
return context.Report(
JsonSerializationResult::Tasks::WriteValue, JsonSerializationResult::Outcomes::Unsupported,
"Configuration stacks can not be written out.");
}
void JsonConfigurableStackSerializer::Reflect(ReflectContext* context)
{
if (JsonRegistrationContext* jsonContext = azrtti_cast<JsonRegistrationContext*>(context))
{
jsonContext->Serializer<JsonConfigurableStackSerializer>()->HandlesType<ConfigurableStack>();
}
}
JsonSerializationResult::Result JsonConfigurableStackSerializer::LoadFromArray(
void* outputValue, const rapidjson::Value& inputValue, JsonDeserializerContext& context)
{
namespace JSR = JsonSerializationResult; // Used remove name conflicts in AzCore in uber builds.
auto stack = reinterpret_cast<ConfigurableStackInterface*>(outputValue);
const Uuid& nodeValueType = stack->GetNodeType();
JSR::ResultCode result(JSR::Tasks::ReadField);
uint32_t counter = 0;
for (auto& it : inputValue.GetArray())
{
ScopedContextPath subPath(context, counter);
void* value = stack->AddNode(AZStd::to_string(counter));
result.Combine(ContinueLoading(value, nodeValueType, it, context));
counter++;
}
return context.Report(
result,
result.GetProcessing() != JSR::Processing::Halted ? "Loaded configurable stack from array."
: "Failed to load configurable stack from array.");
}
JsonSerializationResult::Result JsonConfigurableStackSerializer::LoadFromObject(
void* outputValue, const rapidjson::Value& inputValue, JsonDeserializerContext& context)
{
namespace JSR = JsonSerializationResult; // Used remove name conflicts in AzCore in uber builds.
auto stack = reinterpret_cast<ConfigurableStackInterface*>(outputValue);
const Uuid& nodeValueType = stack->GetNodeType();
AZStd::queue<AZStd::tuple<ConfigurableStackInterface::InsertPosition, AZStd::string_view, rapidjson::Value::ConstMemberIterator>>
delayedEntries;
JSR::ResultCode result(JSR::Tasks::ReadField);
auto add = [&](ConfigurableStackInterface::InsertPosition position, rapidjson::Value::ConstMemberIterator target,
rapidjson::Value::ConstMemberIterator it)
{
if (target->value.IsString())
{
delayedEntries.emplace(position, AZStd::string_view(target->value.GetString(), target->value.GetStringLength()), it);
}
else
{
result.Combine(context.Report(
JSR::Tasks::ReadField, JSR::Outcomes::Skipped,
"Skipped value for the Configurable Stack because the target wasn't a string."));
}
};
// Load all the regular entries into the stack and store any with a before or after binding for
// later inserting.
for (auto it = inputValue.MemberBegin(); it != inputValue.MemberEnd(); ++it)
{
AZStd::string_view name(it->name.GetString(), it->name.GetStringLength());
ScopedContextPath subPath(context, name);
if (it->value.IsObject())
{
if (auto target = it->value.FindMember(StackBefore); target != it->value.MemberEnd())
{
add(ConfigurableStackInterface::InsertPosition::Before, target, it);
continue;
}
if (auto target = it->value.FindMember(StackAfter); target != it->value.MemberEnd())
{
add(ConfigurableStackInterface::InsertPosition::After, target, it);
continue;
}
}
void* value = stack->AddNode(name);
result.Combine(ContinueLoading(value, nodeValueType, it->value, context));
}
// Insert the entries that have been delayed.
while (!delayedEntries.empty())
{
auto&& [insertPosition, target, valueStore] = delayedEntries.front();
AZStd::string_view name(valueStore->name.GetString(), valueStore->name.GetStringLength());
ScopedContextPath subPath(context, name);
void* value = stack->AddNode(name, target, insertPosition);
if (value != nullptr)
{
result.Combine(ContinueLoading(value, nodeValueType, valueStore->value, context));
}
else
{
result.Combine(context.Report(
JSR::Tasks::ReadField, JSR::Outcomes::Skipped,
AZStd::string::format(
"Skipped value for the Configurable Stack because the target '%.*s' couldn't be found.", AZ_STRING_ARG(name))));
}
delayedEntries.pop();
}
return context.Report(
result,
result.GetProcessing() != JSR::Processing::Halted ? "Loaded configurable stack from array."
: "Failed to load configurable stack from array.");
}
} // namespace AZ
| 43.057803 | 137 | 0.618204 | [
"3d"
] |
320392735062c5f05d8a0c00e3f770b5c1788afa | 15,026 | cpp | C++ | base/cluster/wmiprovider/clusterwmiprovider.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | base/cluster/wmiprovider/clusterwmiprovider.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | base/cluster/wmiprovider/clusterwmiprovider.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /////////////////////////////////////////////////////////////////////
//
// CopyRight (c) 1999-2002 Microsoft Corporation
//
// Module Name:
// ClusterWMIProvider.cpp
//
// Description:
// Implementation of the provider registration and entry point.
//
// Author:
// Henry Wang (HenryWa) 24-AUG-1999
//
//////////////////////////////////////////////////////////////////////
#include "Pch.h"
#include <initguid.h>
#include "ProvFactory.h"
#include "InstanceProv.h"
#include "EventProv.h"
#include "ClusterWMIProvider.tmh"
//////////////////////////////////////////////////////////////////////////////
// Global Data
//////////////////////////////////////////////////////////////////////////////
// {598065EA-EDC9-4b2c-913B-5104D04D098A}
DEFINE_GUID( CLSID_CLUSTER_WMI_PROVIDER,
0x598065ea, 0xedc9, 0x4b2c, 0x91, 0x3b, 0x51, 0x4, 0xd0, 0x4d, 0x9, 0x8a );
// {6A52C339-DCB0-4682-8B1B-02DE2C436A6D}
DEFINE_GUID( CLSID_CLUSTER_WMI_CLASS_PROVIDER,
0x6a52c339, 0xdcb0, 0x4682, 0x8b, 0x1b, 0x2, 0xde, 0x2c, 0x43, 0x6a, 0x6d );
// {92863246-4EDE-4eff-B606-79C1971DB230}
DEFINE_GUID( CLSID_CLUSTER_WMI_EVENT_PROVIDER,
0x92863246, 0x4ede, 0x4eff, 0xb6, 0x6, 0x79, 0xc1, 0x97, 0x1d, 0xb2, 0x30 );
// Count number of objects and number of locks.
long g_cObj = 0;
long g_cLock = 0;
HMODULE g_hModule;
FactoryData g_FactoryDataArray[] =
{
{
&CLSID_CLUSTER_WMI_PROVIDER,
CInstanceProv::S_HrCreateThis,
L"Cluster service WMI instance provider"
},
{
&CLSID_CLUSTER_WMI_CLASS_PROVIDER,
CClassProv::S_HrCreateThis,
L"Cluster service WMI class provider"
},
{
&CLSID_CLUSTER_WMI_EVENT_PROVIDER,
CEventProv::S_HrCreateThis,
L"Cluster service WMI event provider"
},
};
//////////////////////////////////////////////////////////////////////////////
//++
//
// BOOL
// WINAPI
// DllMain(
// HANDLE hModule,
// DWORD ul_reason_for_call,
// LPVOID lpReserved
// )
//
// Description:
// Main DLL entry point.
//
// Arguments:
// hModule -- DLL module handle.
// ul_reason_for_call --
// lpReserved --
//
// Return Values:
// TRUE
//
//--
//////////////////////////////////////////////////////////////////////////////
BOOL
WINAPI
DllMain(
HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
// begin_wpp config
// CUSTOM_TYPE(dllreason, ItemListLong(DLL_PROCESS_DETACH, DLL_PROCESS_ATTACH, DLL_THREAD_ATTACH, DLL_THREAD_DETACH) );
//
// CUSTOM_TYPE(EventIdx, ItemSetLong(NODE_STATE, NODE_DELETED, NODE_ADDED, NODE_PROPERTY, REGISTRY_NAME,REGISTRY_ATTRIBUTES, REGISTRY_VALUE, REGISTRY_SUBTREE, RESOURCE_STATE, RESOURCE_DELETED, RESOURCE_ADDED, RESOURCE_PROPERTY, GROUP_STATE, GROUP_DELETED, GROUP_ADDED, GROUP_PROPERTY, RESOURCE_TYPE_DELETED, RESOURCE_TYPE_ADDED, RESOURCE_TYPE_PROPERTY, CLUSTER_RECONNECT, NETWORK_STATE, NETWORK_DELETED, NETWORK_ADDED, NETWORK_PROPERTY, NETINTERFACE_STATE, NETINTERFACE_DELETED, NETINTERFACE_ADDED, NETINTERFACE_PROPERTY, QUORUM_STATE, CLUSTER_STATE, CLUSTER_PROPERTY, HANDLE_CLOSE));
//
// CUSTOM_TYPE(GroupState, ItemListLong(Online, Offline, Failed, PartialOnline, Pending) );
// CUSTOM_TYPE(ResourceState, ItemListLong(Initing, Initializing, Online, Offline, Failed) );
// end_wpp
//
// Cluster event filter flags.
//
/*
NODE_STATE = 0x00000001,
NODE_DELETED = 0x00000002,
NODE_ADDED = 0x00000004,
NODE_PROPERTY = 0x00000008,
REGISTRY_NAME = 0x00000010,
REGISTRY_ATTRIBUTES = 0x00000020,
REGISTRY_VALUE = 0x00000040,
REGISTRY_SUBTREE = 0x00000080,
RESOURCE_STATE = 0x00000100,
RESOURCE_DELETED = 0x00000200,
RESOURCE_ADDED = 0x00000400,
RESOURCE_PROPERTY = 0x00000800,
GROUP_STATE = 0x00001000,
GROUP_DELETED = 0x00002000,
GROUP_ADDED = 0x00004000,
GROUP_PROPERTY = 0x00008000,
RESOURCE_TYPE_DELETED = 0x00010000,
RESOURCE_TYPE_ADDED = 0x00020000,
RESOURCE_TYPE_PROPERTY = 0x00040000,
CLUSTER_RECONNECT = 0x00080000,
NETWORK_STATE = 0x00100000,
NETWORK_DELETED = 0x00200000,
NETWORK_ADDED = 0x00400000,
NETWORK_PROPERTY = 0x00800000,
NETINTERFACE_STATE = 0x01000000,
NETINTERFACE_DELETED = 0x02000000,
NETINTERFACE_ADDED = 0x04000000,
NETINTERFACE_PROPERTY = 0x08000000,
QUORUM_STATE = 0x10000000,
CLUSTER_STATE = 0x20000000,
CLUSTER_PROPERTY = 0x40000000,
HANDLE_CLOSE = 0x80000000,
*/
//#ifdef _DEBUG
// _CrtSetBreakAlloc( 228 );
//#endif
TracePrint(("ClusWMI: DllMain entry, reason = %!dllreason!", ul_reason_for_call));
g_hModule = static_cast< HMODULE >( hModule );
switch ( ul_reason_for_call ) {
case DLL_PROCESS_ATTACH:
WPP_INIT_TRACING( NULL );
break;
case DLL_PROCESS_DETACH:
WPP_CLEANUP();
break;
default:
break;
}
return TRUE;
} //*** DllMain()
//////////////////////////////////////////////////////////////////////////////
//++
//
// STDAPI
// DllCanUnloadNow( void )
//
// Description:
// Called periodically by Ole in order to determine if the
// DLL can be freed.
//
// Arguments:
// None.
//
// Return Values:
// S_OK if there are no objects in use and the class factory
// isn't locked.
//
//--
//////////////////////////////////////////////////////////////////////////////
STDAPI DllCanUnloadNow( void )
{
SCODE sc;
//It is OK to unload if there are no objects or locks on the
// class factory.
sc = ( (0L == g_cObj) && (0L == g_cLock) ) ? S_OK : S_FALSE;
TracePrint(("ClusWMI: DllCanUnloadNow is returning %d", sc));
return sc;
} //*** DllCanUnloadNow()
//////////////////////////////////////////////////////////////////////////////
//++
//
// STDAPI
// DllRegisterServer( void )
//
// Description:
// Called during setup or by regsvr32.
//
// Arguments:
// None.
//
// Return Values:
// NOERROR if registration successful, error otherwise.
// SELFREG_E_CLASS
//
//--
//////////////////////////////////////////////////////////////////////////////
STDAPI DllRegisterServer( void )
{
WCHAR wszID[ 128 ];
WCHAR wszCLSID[ 128 ];
WCHAR wszModule[ MAX_PATH ];
INT idx;
WCHAR * pwszModel = L"Both";
HKEY hKey1 = NULL;
HKEY hKey2 = NULL;
DWORD dwRt = ERROR_SUCCESS;
INT cArray = sizeof ( g_FactoryDataArray ) / sizeof ( FactoryData );
TracePrint(("ClusWMI: DllRegisterServer entry"));
// Create the path.
try
{
DWORD cbModuleNameSize = 0;
if ( GetModuleFileNameW( g_hModule, wszModule, MAX_PATH ) == 0 )
{
dwRt = GetLastError();
throw( dwRt );
}
wszModule[ MAX_PATH - 1 ] = L'\0';
cbModuleNameSize = (DWORD) ( wcslen( wszModule ) + 1 ) * sizeof( wszModule[ 0 ] );
for ( idx = 0 ; idx < cArray && dwRt == ERROR_SUCCESS ; idx++ )
{
LPCWSTR pwszName = g_FactoryDataArray[ idx ].m_pwszRegistryName;
StringFromGUID2(
*g_FactoryDataArray[ idx ].m_pCLSID,
wszID,
128
);
HRESULT hr = StringCchPrintfW( wszCLSID, RTL_NUMBER_OF( wszCLSID ), L"Software\\Classes\\CLSID\\%ws", wszID );
dwRt = (DWORD) hr;
if ( dwRt != ERROR_SUCCESS )
{
throw( dwRt );
}
// Create entries under CLSID
dwRt = RegCreateKeyExW(
HKEY_LOCAL_MACHINE,
wszCLSID,
0,
NULL,
REG_OPTION_NON_VOLATILE,
KEY_CREATE_SUB_KEY | KEY_WRITE,
NULL,
&hKey1,
NULL
);
if ( dwRt != ERROR_SUCCESS )
{
throw( dwRt );
}
dwRt = RegSetValueExW(
hKey1,
NULL,
0,
REG_SZ,
(BYTE *) pwszName,
(DWORD) ( sizeof( WCHAR ) * ( wcslen( pwszName ) + 1 ) )
);
if ( dwRt != ERROR_SUCCESS )
{
throw( dwRt );
}
dwRt = RegCreateKeyExW(
hKey1,
L"InprocServer32",
0,
NULL,
REG_OPTION_NON_VOLATILE,
KEY_CREATE_SUB_KEY | KEY_WRITE,
NULL,
&hKey2,
NULL
);
if ( dwRt != ERROR_SUCCESS )
{
throw( dwRt );
}
dwRt = RegSetValueExW(
hKey2,
NULL,
0,
REG_SZ,
(BYTE *) wszModule,
cbModuleNameSize
);
if ( dwRt != ERROR_SUCCESS )
{
throw( dwRt );
}
dwRt = RegSetValueExW(
hKey2,
L"ThreadingModel",
0,
REG_SZ,
(BYTE *) pwszModel,
(DWORD) ( sizeof( WCHAR ) * ( wcslen( pwszModel ) + 1 ) )
);
if ( dwRt != ERROR_SUCCESS )
{
throw( dwRt );
}
} // for: each entry in factory entry array
if ( dwRt != ERROR_SUCCESS )
{
throw( dwRt );
}
}
catch ( DWORD sc )
{
dwRt = sc;
}
catch ( ... )
{
dwRt = (DWORD) SELFREG_E_CLASS;
}
TracePrint(("ClusWMI: RegisterServer returned %d", dwRt));
if ( hKey1 != NULL )
{
RegCloseKey( hKey1 );
}
if ( hKey2 != NULL )
{
RegCloseKey( hKey2 );
}
return dwRt;
} //*** DllRegisterServer()
//////////////////////////////////////////////////////////////////////////////
//++
//
// STDAPI
// DllUnregisterServer( void )
//
// Description:
// Called when it is time to remove the registry entries.
//
// Arguments:
// None.
//
// Return Values:
// NOERROR if registration successful, error otherwise.
// SELFREG_E_CLASS
//
//--
//////////////////////////////////////////////////////////////////////////////
STDAPI DllUnregisterServer( void )
{
WCHAR wszID[ 128 ];
WCHAR wszCLSID[ 128 ];
HKEY hKey;
INT idx;
DWORD dwRet = ERROR_SUCCESS;
for ( idx = 0 ; idx < 2 && dwRet == ERROR_SUCCESS ; idx++ )
{
StringFromGUID2(
*g_FactoryDataArray[ idx ].m_pCLSID,
wszID,
128
);
HRESULT hr = StringCchPrintfW( wszCLSID, RTL_NUMBER_OF( wszCLSID ), L"Software\\Classes\\CLSID\\%ws", wszID );
dwRet = (DWORD) hr;
if ( dwRet != ERROR_SUCCESS )
{
break;
}
// First delete the InProcServer subkey.
dwRet = RegOpenKeyExW(
HKEY_LOCAL_MACHINE,
wszCLSID,
0,
KEY_ALL_ACCESS,
&hKey
);
if ( dwRet != ERROR_SUCCESS )
{
break;
}
dwRet = RegDeleteKeyW( hKey, L"InProcServer32" );
RegCloseKey( hKey );
if ( dwRet != ERROR_SUCCESS )
{
break;
}
dwRet = RegOpenKeyExW(
HKEY_LOCAL_MACHINE,
L"Software\\Classes\\CLSID",
0,
KEY_ALL_ACCESS,
&hKey
);
if ( dwRet != ERROR_SUCCESS )
{
break;
}
dwRet = RegDeleteKeyW( hKey,wszID );
RegCloseKey( hKey );
if ( dwRet != ERROR_SUCCESS )
{
break;
}
} // for: each object
if ( dwRet != ERROR_SUCCESS )
{
dwRet = (DWORD) SELFREG_E_CLASS;
}
return dwRet;
} //*** DllUnregisterServer()
//////////////////////////////////////////////////////////////////////////////
//++
//
// STDAPI
// DllGetClassObject(
// REFCLSID rclsidIn,
// REFIID riidIn,
// PPVOID ppvOut
// )
//
// Description:
// Called by Ole when some client wants a class factory. Return
// one only if it is the sort of class this DLL supports.
//
// Arguments:
// rclsidIn --
// riidIn --
// ppvOut --
//
// Return Values:
// NOERROR if registration successful, error otherwise.
// E_OUTOFMEMORY
// E_FAIL
//
//--
//////////////////////////////////////////////////////////////////////////////
STDAPI
DllGetClassObject(
REFCLSID rclsidIn,
REFIID riidIn,
PPVOID ppvOut
)
{
HRESULT hr;
CProvFactory * pObj = NULL;
UINT idx;
UINT cDataArray = sizeof ( g_FactoryDataArray ) / sizeof ( FactoryData );
for ( idx = 0 ; idx < cDataArray ; idx++ )
{
if ( rclsidIn == *g_FactoryDataArray[ idx ].m_pCLSID )
{
pObj= new CProvFactory( &g_FactoryDataArray[ idx ] );
if ( NULL == pObj )
{
return E_OUTOFMEMORY;
}
hr = pObj->QueryInterface( riidIn, ppvOut );
if ( FAILED( hr ) )
{
delete pObj;
}
return hr;
}
}
return E_FAIL;
} //*** DllGetClassObject()
| 27.621324 | 585 | 0.449621 | [
"object"
] |
3205e75112c846bad8257abe52020eb1e594e092 | 11,828 | cpp | C++ | src/load_obj.cpp | madmann91/hagrid | fa3eb62eba14d073dfeddd3b9ca8fbfb2d6848af | [
"MIT"
] | 24 | 2017-03-13T05:40:11.000Z | 2018-11-05T16:10:04.000Z | src/load_obj.cpp | madmann91/hagrid | fa3eb62eba14d073dfeddd3b9ca8fbfb2d6848af | [
"MIT"
] | 1 | 2020-07-15T12:55:46.000Z | 2020-07-15T14:30:14.000Z | src/load_obj.cpp | madmann91/hagrid | fa3eb62eba14d073dfeddd3b9ca8fbfb2d6848af | [
"MIT"
] | 5 | 2017-03-13T09:56:11.000Z | 2018-03-05T16:53:45.000Z | #include <fstream>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include "load_obj.h"
namespace hagrid {
inline void error() {
std::cerr << std::endl;
}
template <typename T, typename... Args>
inline void error(T t, Args... args) {
#ifndef NDEBUG
std::cerr << t;
error(args...);
#endif
}
inline void remove_eol(char* ptr) {
int i = 0;
while (ptr[i]) i++;
i--;
while (i > 0 && std::isspace(ptr[i])) {
ptr[i] = '\0';
i--;
}
}
inline char* strip_text(char* ptr) {
while (*ptr && !std::isspace(*ptr)) { ptr++; }
return ptr;
}
inline char* strip_spaces(char* ptr) {
while (std::isspace(*ptr)) { ptr++; }
return ptr;
}
inline bool read_index(char** ptr, ObjLoader::Index& idx) {
char* base = *ptr;
// Detect end of line (negative indices are supported)
base = strip_spaces(base);
if (!std::isdigit(*base) && *base != '-') return false;
idx.v = 0;
idx.t = 0;
idx.n = 0;
idx.v = std::strtol(base, &base, 10);
base = strip_spaces(base);
if (*base == '/') {
base++;
// Handle the case when there is no texture coordinate
if (*base != '/') {
idx.t = std::strtol(base, &base, 10);
}
base = strip_spaces(base);
if (*base == '/') {
base++;
idx.n = std::strtol(base, &base, 10);
}
}
*ptr = base;
return true;
}
bool ObjLoader::load_obj(const std::string& path, File& file) {
std::ifstream stream(path);
if (!stream) return false;
// Add an empty object to the scene
int cur_object = 0;
file.objects.emplace_back();
// Add an empty group to this object
int cur_group = 0;
file.objects[0].groups.emplace_back();
// Add an empty material to the scene
int cur_mtl = 0;
file.materials.emplace_back("");
// Add dummy vertex, normal, and texcoord
file.vertices.emplace_back();
file.normals.emplace_back();
file.texcoords.emplace_back();
int err_count = 0;
const int max_line = 1024;
char line[max_line];
while (stream.getline(line, max_line)) {
// Strip spaces
char* ptr = strip_spaces(line);
const char* err_line = ptr;
// Skip comments and empty lines
if (*ptr == '\0' || *ptr == '#')
continue;
remove_eol(ptr);
// Test each command in turn, the most frequent first
if (*ptr == 'v') {
switch (ptr[1]) {
case ' ':
case '\t':
{
vec3 v;
v.x = std::strtof(ptr + 1, &ptr);
v.y = std::strtof(ptr, &ptr);
v.z = std::strtof(ptr, &ptr);
file.vertices.push_back(v);
}
break;
case 'n':
#ifndef SKIP_NORMALS
{
vec3 n;
n.x = std::strtof(ptr + 2, &ptr);
n.y = std::strtof(ptr, &ptr);
n.z = std::strtof(ptr, &ptr);
file.normals.push_back(n);
}
#endif
break;
case 't':
#ifndef SKIP_TEXCOORDS
{
vec2 t;
t.x = std::strtof(ptr + 2, &ptr);
t.y = std::strtof(ptr, &ptr);
file.texcoords.push_back(t);
}
#endif
break;
default:
error("invalid vertex");
err_count++;
break;
}
} else if (*ptr == 'f' && std::isspace(ptr[1])) {
Face f;
f.index_count = 0;
f.material = cur_mtl;
bool valid = true;
ptr += 2;
while(f.index_count < Face::max_indices) {
Index index;
valid = read_index(&ptr, index);
if (valid) {
f.indices[f.index_count++] = index;
} else {
break;
}
}
if (f.index_count < 3) {
error("invalid face");
err_count++;
} else {
// Convert relative indices to absolute
for (int i = 0; i < f.index_count; i++) {
f.indices[i].v = (f.indices[i].v < 0) ? file.vertices.size() + f.indices[i].v : f.indices[i].v;
f.indices[i].t = (f.indices[i].t < 0) ? file.texcoords.size() + f.indices[i].t : f.indices[i].t;
f.indices[i].n = (f.indices[i].n < 0) ? file.normals.size() + f.indices[i].n : f.indices[i].n;
}
// Check if the indices are valid or not
valid = true;
for (int i = 0; i < f.index_count; i++) {
if (f.indices[i].v <= 0 || f.indices[i].t < 0 || f.indices[i].n < 0) {
valid = false;
break;
}
}
if (valid) {
file.objects[cur_object].groups[cur_group].faces.push_back(f);
} else {
error("invalid indices");
err_count++;
}
}
} else if (*ptr == 'g' && std::isspace(ptr[1])) {
file.objects[cur_object].groups.emplace_back();
cur_group++;
} else if (*ptr == 'o' && std::isspace(ptr[1])) {
file.objects.emplace_back();
cur_object++;
file.objects[cur_object].groups.emplace_back();
cur_group = 0;
} else if (!std::strncmp(ptr, "usemtl", 6) && std::isspace(ptr[6])) {
ptr += 6;
ptr = strip_spaces(ptr);
char* base = ptr;
ptr = strip_text(ptr);
const std::string mtl_name(base, ptr);
cur_mtl = std::find(file.materials.begin(), file.materials.end(), mtl_name) - file.materials.begin();
if (cur_mtl == (int)file.materials.size()) {
file.materials.push_back(mtl_name);
}
} else if (!std::strncmp(ptr, "mtllib", 6) && std::isspace(ptr[6])) {
ptr += 6;
ptr = strip_spaces(ptr);
char* base = ptr;
ptr = strip_text(ptr);
const std::string lib_name(base, ptr);
file.mtl_libs.push_back(lib_name);
} else if (*ptr == 's' && std::isspace(ptr[1])) {
// Ignore smooth commands
} else {
error("unknown command ", ptr);
err_count++;
}
}
return (err_count == 0);
}
bool ObjLoader::load_mtl(const std::string& path, MaterialLib& mtl_lib) {
std::ifstream stream(path);
if (!stream) return false;
const int max_line = 1024;
char line[max_line];
char* err_line = line;
int err_count = 0;
std::string mtl_name;
auto current_material = [&] () -> Material& {
return mtl_lib[mtl_name];
};
while (stream.getline(line, max_line)) {
// Strip spaces
char* ptr = strip_spaces(line);
err_line = ptr;
// Skip comments and empty lines
if (*ptr == '\0' || *ptr == '#')
continue;
remove_eol(ptr);
if (!std::strncmp(ptr, "newmtl", 6) && std::isspace(ptr[6])) {
ptr = strip_spaces(ptr + 7);
char* base = ptr;
ptr = strip_text(ptr);
mtl_name = std::string(base, ptr);
if (mtl_lib.find(mtl_name) != mtl_lib.end()) {
error("material redefinition");
err_count++;
}
} else if (ptr[0] == 'K') {
if (ptr[1] == 'a' && std::isspace(ptr[2])) {
auto& mat = current_material();
mat.ka.r = std::strtof(ptr + 3, &ptr);
mat.ka.g = std::strtof(ptr, &ptr);
mat.ka.b = std::strtof(ptr, &ptr);
} else if (ptr[1] == 'd' && std::isspace(ptr[2])) {
auto& mat = current_material();
mat.kd.r = std::strtof(ptr + 3, &ptr);
mat.kd.g = std::strtof(ptr, &ptr);
mat.kd.b = std::strtof(ptr, &ptr);
} else if (ptr[1] == 's' && std::isspace(ptr[2])) {
auto& mat = current_material();
mat.ks.r = std::strtof(ptr + 3, &ptr);
mat.ks.g = std::strtof(ptr, &ptr);
mat.ks.b = std::strtof(ptr, &ptr);
} else if (ptr[1] == 'e' && std::isspace(ptr[2])) {
auto& mat = current_material();
mat.ke.r = std::strtof(ptr + 3, &ptr);
mat.ke.g = std::strtof(ptr, &ptr);
mat.ke.b = std::strtof(ptr, &ptr);
} else {
error("invalid command");
err_count++;
}
} else if (ptr[0] == 'N') {
if (ptr[1] == 's' && std::isspace(ptr[2])) {
auto& mat = current_material();
mat.ns = std::strtof(ptr + 3, &ptr);
} else if (ptr[1] == 'i' && std::isspace(ptr[2])) {
auto& mat = current_material();
mat.ni = std::strtof(ptr + 3, &ptr);
} else {
error("invalid command");
err_count++;
}
} else if (ptr[0] == 'T') {
if (ptr[1] == 'f' && std::isspace(ptr[2])) {
auto& mat = current_material();
mat.tf.r = std::strtof(ptr + 3, &ptr);
mat.tf.g = std::strtof(ptr, &ptr);
mat.tf.b = std::strtof(ptr, &ptr);
} else if (ptr[1] == 'r' && std::isspace(ptr[2])) {
auto& mat = current_material();
mat.tr = std::strtof(ptr + 3, &ptr);
} else {
error("invalid command");
err_count++;
}
} else if (ptr[0] == 'd' && std::isspace(ptr[1])) {
auto& mat = current_material();
mat.d = std::strtof(ptr + 2, &ptr);
} else if (!std::strncmp(ptr, "illum", 5) && std::isspace(ptr[5])) {
auto& mat = current_material();
mat.illum = std::strtof(ptr + 6, &ptr);
} else if (!std::strncmp(ptr, "map_Ka", 6) && std::isspace(ptr[6])) {
auto& mat = current_material();
mat.map_ka = std::string(strip_spaces(ptr + 7));
} else if (!std::strncmp(ptr, "map_Kd", 6) && std::isspace(ptr[6])) {
auto& mat = current_material();
mat.map_kd = std::string(strip_spaces(ptr + 7));
} else if (!std::strncmp(ptr, "map_Ks", 6) && std::isspace(ptr[6])) {
auto& mat = current_material();
mat.map_ks = std::string(strip_spaces(ptr + 7));
} else if (!std::strncmp(ptr, "map_Ke", 6) && std::isspace(ptr[6])) {
auto& mat = current_material();
mat.map_ke = std::string(strip_spaces(ptr + 7));
} else if (!std::strncmp(ptr, "map_bump", 8) && std::isspace(ptr[8])) {
auto& mat = current_material();
mat.map_bump = std::string(strip_spaces(ptr + 9));
} else if (!std::strncmp(ptr, "bump", 4) && std::isspace(ptr[4])) {
auto& mat = current_material();
mat.map_bump = std::string(strip_spaces(ptr + 5));
} else if (!std::strncmp(ptr, "map_d", 5) && std::isspace(ptr[5])) {
auto& mat = current_material();
mat.map_d = std::string(strip_spaces(ptr + 6));
} else {
error("unknown command ", ptr);
err_count++;
}
}
return (err_count == 0);
}
} // namespace hagrid
| 32.674033 | 116 | 0.453247 | [
"object"
] |
320eca4a39357ec0f538d414d3e90b45f65f50cc | 1,001 | hpp | C++ | include/plane_detector/plane.hpp | robotics-upo/plane_detector | c3ca7d25b5be9c7d7063489523bed9388d4a5ee0 | [
"MIT"
] | 42 | 2018-08-02T01:08:15.000Z | 2022-03-18T05:11:27.000Z | include/plane_detector/plane.hpp | robotics-upo/plane_detector | c3ca7d25b5be9c7d7063489523bed9388d4a5ee0 | [
"MIT"
] | 3 | 2019-07-17T04:03:03.000Z | 2022-01-27T11:02:45.000Z | include/plane_detector/plane.hpp | robotics-upo/plane_detector | c3ca7d25b5be9c7d7063489523bed9388d4a5ee0 | [
"MIT"
] | 8 | 2018-08-03T07:15:20.000Z | 2020-09-03T06:33:38.000Z | #ifndef PLANE_HPP__
#define PLANE_HPP__
#include <eigen3/Eigen/Geometry>
#include <sstream>
// Describes the plane as all the points (p) that fulfills v*p = d
class Plane {
public:
// Basic data
Eigen::Vector3d v;
double d;
//! @brief Default constructor
Plane() {
v(0) = v(1) = v(2) = d = 0.0;
}
//! @brief Recommended constructor
Plane(const Eigen::Vector3d v_, double d_):v(v_),d(d_) {
}
//! @brief Returns the distance from the point v_ to the plane
//! @return The distance from v_ to the plane
double distance(const Eigen::Vector3d v_) const;
virtual std::string toString() const;
void makeDPositive();
};
double Plane::distance(const Eigen::Vector3d v_) const
{
return fabs(v_.dot(v) - d);
}
std::string Plane::toString() const
{
std::ostringstream os;
os << "n = " << v.transpose() << "\t d = " << d;
return os.str();
}
void Plane::makeDPositive()
{
if (d < 0.0) {
d *= -1.0;
v *= -1.0;
}
}
#endif | 16.683333 | 66 | 0.605395 | [
"geometry"
] |
321469cc7762a12ab12daddd5b2a3d8b586cfc9e | 4,135 | cpp | C++ | src/PDFArrayDriver.cpp | shutterstock/HummusJS | e6e4b0e4887129bf45d7950c6008d00c9d6cb3fd | [
"Apache-2.0"
] | null | null | null | src/PDFArrayDriver.cpp | shutterstock/HummusJS | e6e4b0e4887129bf45d7950c6008d00c9d6cb3fd | [
"Apache-2.0"
] | null | null | null | src/PDFArrayDriver.cpp | shutterstock/HummusJS | e6e4b0e4887129bf45d7950c6008d00c9d6cb3fd | [
"Apache-2.0"
] | 2 | 2016-05-13T08:16:22.000Z | 2021-03-25T20:58:53.000Z | /*
Source File : PDFArrayDriver.h
Copyright 2013 Gal Kahana HummusJS
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 "PDFArrayDriver.h"
#include "RefCountPtr.h"
using namespace v8;
Persistent<Function> PDFArrayDriver::constructor;
Persistent<FunctionTemplate> PDFArrayDriver::constructor_template;
void PDFArrayDriver::Init()
{
CREATE_ISOLATE_CONTEXT;
Local<FunctionTemplate> t = NEW_FUNCTION_TEMPLATE(New);
t->SetClassName(NEW_STRING("PDFArray"));
t->InstanceTemplate()->SetInternalFieldCount(1);
SET_PROTOTYPE_METHOD(t, "toJSArray", ToJSArray);
SET_PROTOTYPE_METHOD(t, "queryObject", QueryObject);
SET_PROTOTYPE_METHOD(t, "getLength", GetLength);
PDFObjectDriver::Init(t);
SET_CONSTRUCTOR(constructor, t);
SET_CONSTRUCTOR_TEMPLATE(constructor_template, t);
}
METHOD_RETURN_TYPE PDFArrayDriver::NewInstance(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
Local<Object> instance = NEW_INSTANCE(constructor);
SET_FUNCTION_RETURN_VALUE(instance);
}
v8::Handle<v8::Value> PDFArrayDriver::GetNewInstance()
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
Local<Object> instance = NEW_INSTANCE(constructor);
return CLOSE_SCOPE(instance);
}
bool PDFArrayDriver::HasInstance(Handle<Value> inObject)
{
CREATE_ISOLATE_CONTEXT;
return inObject->IsObject() && HAS_INSTANCE(constructor_template, inObject);
}
METHOD_RETURN_TYPE PDFArrayDriver::New(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
PDFArrayDriver* array = new PDFArrayDriver();
array->Wrap(args.This());
SET_FUNCTION_RETURN_VALUE(args.This());
}
PDFObject* PDFArrayDriver::GetObject()
{
return TheObject.GetPtr();
}
METHOD_RETURN_TYPE PDFArrayDriver::ToJSArray(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
PDFArrayDriver* arrayDriver = ObjectWrap::Unwrap<PDFArrayDriver>(args.This());
Local<Array> result = NEW_ARRAY((int)arrayDriver->TheObject->GetLength());
for(unsigned long i=0; i < arrayDriver->TheObject->GetLength();++i)
{
RefCountPtr<PDFObject> anObject(arrayDriver->TheObject->QueryObject(i));
result->Set(NEW_NUMBER(i),PDFObjectDriver::CreateDriver(anObject.GetPtr()));
}
SET_FUNCTION_RETURN_VALUE(result);
}
METHOD_RETURN_TYPE PDFArrayDriver::GetLength(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
PDFArrayDriver* arrayDriver = ObjectWrap::Unwrap<PDFArrayDriver>(args.This());
Local<Number> result = NEW_NUMBER(arrayDriver->TheObject->GetLength());
SET_FUNCTION_RETURN_VALUE(result);
}
METHOD_RETURN_TYPE PDFArrayDriver::QueryObject(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
if(args.Length() != 1 || !args[0]->IsNumber())
{
THROW_EXCEPTION("wrong arguments, pass 1 argument which is an index in the array");
SET_FUNCTION_RETURN_VALUE(UNDEFINED);
}
PDFArrayDriver* arrayDriver = ObjectWrap::Unwrap<PDFArrayDriver>(args.This());
if(args[0]->ToNumber()->Uint32Value() >= arrayDriver->TheObject->GetLength())
{
THROW_EXCEPTION("wrong arguments, pass 1 argument which is a valid index in the array");
SET_FUNCTION_RETURN_VALUE(UNDEFINED);
}
RefCountPtr<PDFObject> anObject = arrayDriver->TheObject->QueryObject(args[0]->ToNumber()->Uint32Value());
Handle<Value> result = PDFObjectDriver::CreateDriver(anObject.GetPtr());
SET_FUNCTION_RETURN_VALUE(result);
} | 29.535714 | 111 | 0.727207 | [
"object"
] |
3214d828cdaebdb397991fd93abb2e814865b63c | 1,178 | cpp | C++ | DSA_Implementation/Z01/Sorting/4. Merge Sort Recursive.cpp | Sowmik23/All-Codes | 212ef0d940fa84624bb2972a257768a830a709a3 | [
"MIT"
] | 5 | 2021-02-14T17:48:21.000Z | 2022-01-24T14:29:44.000Z | DSA_Implementation/Z01/Sorting/4. Merge Sort Recursive.cpp | Sowmik23/All-Codes | 212ef0d940fa84624bb2972a257768a830a709a3 | [
"MIT"
] | null | null | null | DSA_Implementation/Z01/Sorting/4. Merge Sort Recursive.cpp | Sowmik23/All-Codes | 212ef0d940fa84624bb2972a257768a830a709a3 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
// Time: O(nlogn)
// Auxiliary Space: O(n)
// In-Place: No
// Stable: Yes
// Class: Comparison based
// Divide and Conquer algorithm
//Drawbacks:
/// Takes extra memory
/// It goes through the whole process even if the array is sorted
void merge(vector<int> &nums, int left, int mid, int right){
int n1 = mid-left+1;
int n2 = right -mid;
vector<int> a(n1), b(n2);
for(int i=0;i<n1;i++){
a[i] = nums[left+i];
}
for(int i=0;i<n2;i++){
b[i] = nums[mid+1+i];
}
int i=0, j = 0, k = left;
while(i<n1 and j<n2){
if(a[i]<b[j]){
nums[k] = a[i];
i++;
}
else {
nums[k] = b[j];
j++;
}
k++;
}
while(i<n1){
nums[k++] = a[i++];
}
while(j<n2){
nums[k++] = b[j++];
}
}
void mergeSort(vector<int> &nums, int left, int right){
if(left<right){
int mid = left+(right-left)/2;
mergeSort(nums, left, mid);
mergeSort(nums, mid+1, right);
merge(nums, left, mid, right);
}
}
int main(){
vector<int> nums = { 37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54 };
mergeSort(nums, 0, nums.size()-1);
for(int i=0;i<nums.size();i++){
cout<<nums[i]<<" ";
}
cout<<endl;
return 0;
}
| 15.298701 | 67 | 0.55348 | [
"vector"
] |
321987cb6acccbdfe5805cfb0baf407a16808428 | 2,581 | cpp | C++ | src/SpawnLoader.cpp | SentientCoffee/Primordial | d9bd9161851507f2ef51c3548b710944207e8d10 | [
"MIT"
] | 2 | 2019-11-08T17:22:50.000Z | 2020-01-09T00:56:35.000Z | src/SpawnLoader.cpp | SentientCoffee/Primordial | d9bd9161851507f2ef51c3548b710944207e8d10 | [
"MIT"
] | null | null | null | src/SpawnLoader.cpp | SentientCoffee/Primordial | d9bd9161851507f2ef51c3548b710944207e8d10 | [
"MIT"
] | null | null | null | #include "SpawnLoader.h"
#include <string>
#include <iostream>
void SpawnPoint::rotate(float rotation)
{
if (rotation / 90.0f == 1.0f) {
_position = glm::vec3(_position.z, _position.y, -_position.x);
}
else if (rotation / 90.0f == 2.0f) {
_position.x *= -1;
_position.z *= -1;
}
else if (rotation / 90.0f == 3.0f) {
_position = glm::vec3(-_position.z, _position.y, _position.x);
}
_spawned = false;
}
SpawnLoader::SpawnLoader(const char* filename)
{
char tempName[256] = "";
FILE* file = fopen(filename, "r");
bool moreFile = true;
if (file == NULL)
{
printf("Failed to open file\n");
moreFile = false;
}
while (moreFile)
{
char line[1024] ="";
int lineNumber = fscanf(file, "%s", line);
if (lineNumber == EOF) {//if end of file
moreFile = false;
}
else if (strcmp(line, "o") == 0) {//if new object
int errorThing = fscanf(file, "%s\n", &tempName);//get name of object
}
else if (strcmp(line, "v") == 0) {//if vertex
glm::vec3 vertex;
int errorThing = fscanf(file, "%f %f %f\n", &vertex.x, &vertex.y, &vertex.z);
_tempVerts.push_back(vertex);
}
else if (strcmp(line, "s") == 0) {
if (tempName[0] == 'S') {
SpawnPoint temp;
temp._position = findCenter();
//std::cout << _spawnPoints.size()+1<< " x: " << temp._position.x << " y: " << temp._position.y << " z: " << temp._position.z << std::endl;
_spawnPoints.push_back(temp);
}
else if(tempName[0]=='W') {
std::string weightString = tempName;
weightString = weightString.substr(weightString.find_first_of('_') + 1, weightString.find_last_of('_')-2);
_weight = std::stof(weightString);
//std::cout << _weight << std::endl;
}
_tempVerts.clear();
}
}
}
void SpawnLoader::rotate(float rotation)
{
for (unsigned i = 0; i < _spawnPoints.size(); i++)
_spawnPoints[i].rotate(rotation);
_usedWeight = 0.0f;
}
glm::vec3 SpawnLoader::findCenter()
{
glm::vec3 tempHigh = _tempVerts[0];
glm::vec3 tempLow = _tempVerts[0];
for (unsigned int i = 0; i < _tempVerts.size(); i++)
{
if (_tempVerts[i].x > tempHigh.x)
tempHigh.x = _tempVerts[i].x;
if (_tempVerts[i].y > tempHigh.y)
tempHigh.y = _tempVerts[i].y;
if (_tempVerts[i].z > tempHigh.z)
tempHigh.z = _tempVerts[i].z;
if (_tempVerts[i].x < tempLow.x)
tempLow.x = _tempVerts[i].x;
if (_tempVerts[i].y < tempLow.y)
tempLow.y = _tempVerts[i].y;
if (_tempVerts[i].z < tempLow.z)
tempLow.z = _tempVerts[i].z;
}
return glm::vec3(tempHigh.x / 2 + tempLow.x / 2,
(tempHigh.y / 2 + tempLow.y / 2) - 2,
tempHigh.z / 2 + tempLow.z / 2);
}
| 25.81 | 143 | 0.615653 | [
"object"
] |
3224200cac7188e1b9d7e3c7d50788ccd47d54f0 | 1,124 | cpp | C++ | 804_uniqueMorseCodeWords.cpp | xyp8023/LeetCode_Solutions | de330cfb99b71538f96a70205fecf34f3d19093a | [
"MIT"
] | null | null | null | 804_uniqueMorseCodeWords.cpp | xyp8023/LeetCode_Solutions | de330cfb99b71538f96a70205fecf34f3d19093a | [
"MIT"
] | null | null | null | 804_uniqueMorseCodeWords.cpp | xyp8023/LeetCode_Solutions | de330cfb99b71538f96a70205fecf34f3d19093a | [
"MIT"
] | null | null | null | #include <vector>
#include <string>
#include <set>
#include <algorithm>
#include <iostream>
using namespace std;
class Solution {
public:
int uniqueMorseRepresentations(vector<string>& words) {
string alphabet = "abcdefghijklmnopqrstuvwxyz";
vector<string> morse = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
for (int i=0;i<=alphabet.size();++i){
}
set<string> lookup;
for(int i=0; i<words.size(); ++i){
string word;
for (int j=0; j<words[i].size(); ++j){
size_t index= alphabet.find(words[i][j]) ;
if (index!=string::npos){
word+=morse[index];
}
}
lookup.insert(word);
}
return lookup.size();
}
};
int main(){
Solution sol;
vector<string> words={"gin", "zen", "gig", "msg"};
int res = sol.uniqueMorseRepresentations(words);
cout << res << endl;
cin.get();
} | 28.1 | 193 | 0.435053 | [
"vector"
] |
3228f11a89137c5ecfa3f9f2583aa28710040f2b | 2,425 | hpp | C++ | Tefnout/src/Tefnout/ECS/WarehouseManager.hpp | JeremyBois/Tefnout | 3e0d79c96857a395d2f00a61bb25a49ce39c8c89 | [
"Apache-2.0",
"MIT"
] | null | null | null | Tefnout/src/Tefnout/ECS/WarehouseManager.hpp | JeremyBois/Tefnout | 3e0d79c96857a395d2f00a61bb25a49ce39c8c89 | [
"Apache-2.0",
"MIT"
] | null | null | null | Tefnout/src/Tefnout/ECS/WarehouseManager.hpp | JeremyBois/Tefnout | 3e0d79c96857a395d2f00a61bb25a49ce39c8c89 | [
"Apache-2.0",
"MIT"
] | null | null | null | #ifndef __TEFNOUT_WAREHOUSEMANAGER__HPP
#define __TEFNOUT_WAREHOUSEMANAGER__HPP
#include "Tefnout/Core/Debug.hpp"
#include "Tefnout/ECS/Entity.hpp"
#include "Tefnout/ECS/FamilyGenerator.hpp"
#include "Tefnout/ECS/SparseSet.hpp"
#include "Tefnout/ECS/Warehouse.hpp"
#include <memory>
#include <utility>
namespace Tefnout
{
namespace ECS
{
class WarehouseManager
{
public:
using size_type = std::size_t;
WarehouseManager() : m_warehouses()
{
m_warehouses.reserve(100);
};
~WarehouseManager() = default;
template <typename T> Warehouse<T>& Get()
{
return *PrepareWarehouse<T>();
}
template <typename T> T& GetComponent(Entity entity)
{
auto* warehouse = PrepareWarehouse<T>();
return warehouse->Get(entity);
}
template <typename T> T& AddComponent(Entity entity, T component)
{
auto* warehouse = PrepareWarehouse<T>();
return warehouse->EmplaceBack(std::move(entity), std::move(component));
}
template <typename T, typename... Args> T& AddComponent(Entity entity, Args&&... args)
{
auto* warehouse = PrepareWarehouse<T>();
return warehouse->EmplaceBack(std::move(entity), std::forward<Args>(args)...);
}
template <typename T> void RemoveComponent(Entity entity)
{
auto* warehouse = PrepareWarehouse<T>();
return warehouse->Remove(entity);
}
private:
std::vector<std::unique_ptr<SparseSet>> m_warehouses;
template <typename T> Warehouse<T>* PrepareWarehouse()
{
const size_type warehouseId = FamilyGenerator::TypeIdentifier<T>();
// Reserve enough place
InsureSpace(warehouseId);
// Get warehouse or create it first if needed
auto& mgr = m_warehouses.at(warehouseId);
if (mgr == nullptr)
{
m_warehouses[warehouseId] = std::make_unique<Warehouse<T>>();
TEFNOUT_ASSERT(mgr != nullptr,
"Warehouse at <{0}> should have been created and reference updated.",
warehouseId);
}
// Extract a reference to wrapped data
return static_cast<Warehouse<T>*>(mgr.get());
}
void InsureSpace(const size_type index)
{
if (index >= m_warehouses.size())
{
m_warehouses.resize(index + 1u);
}
}
};
} // namespace ECS
} // namespace Tefnout
#endif
| 25 | 96 | 0.625155 | [
"vector"
] |
322b8d9b736e1388eaa3981727267ae8de1e8e35 | 6,606 | cpp | C++ | PAT_A/PAT_A1026new.cpp | EnhydraGod/PATCode | ff38ea33ba319af78b3aeba8aa6c385cc5e8329f | [
"BSD-2-Clause"
] | 3 | 2019-07-08T05:20:28.000Z | 2021-09-22T10:53:26.000Z | PAT_A/PAT_A1026new.cpp | EnhydraGod/PATCode | ff38ea33ba319af78b3aeba8aa6c385cc5e8329f | [
"BSD-2-Clause"
] | null | null | null | PAT_A/PAT_A1026new.cpp | EnhydraGod/PATCode | ff38ea33ba319af78b3aeba8aa6c385cc5e8329f | [
"BSD-2-Clause"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
const int inf = 1000000000;
int n, hour, minute, second, lasttime, tag, k, m;
bool isviproom[110];
int counts[110];
struct player
{
int arrivetime, lasttime;
player(int _arrivetime, int _lasttime){arrivetime = _arrivetime;lasttime = _lasttime;}
};
struct room
{
int canusetime, id;
room(int _canusetime, int _id){canusetime = _canusetime;id = _id;}
};
struct cmproom
{
bool operator()(const room &a, const room &b){if (a.canusetime != b.canusetime) return a.canusetime > b.canusetime; else return a.id > b.id;}
};
bool cmpplayer(const player &a, const player &b) { return a.arrivetime < b.arrivetime; }
bool cmpres(const player &a, const player &b) { return a.lasttime < b.lasttime; }
vector<player> vip, ord;
vector<player> res;
priority_queue<room, vector<room>, cmproom> viproomqueue, ordroomqueue;
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
scanf("%d:%d:%d %d %d\n", &hour, &minute, &second, &lasttime, &tag);
if (lasttime > 120) lasttime = 120;
if (tag == 1) vip.push_back(player(hour * 3600 + minute * 60 + second, lasttime * 60));
else ord.push_back(player(hour * 3600 + minute * 60 + second, lasttime * 60));
}
scanf("%d%d", &k, &m);
for (int i = 1; i <= m; i++)
{
scanf("%d", &tag);
isviproom[tag] = true;
}
for (int i = 1; i <= k; i++)
{
if (isviproom[i]) viproomqueue.push(room(8 * 3600, i));
else ordroomqueue.push(room(8 * 3600, i));
}
sort(vip.begin(), vip.end(), cmpplayer);
sort(ord.begin(), ord.end(), cmpplayer);
vip.push_back(player(inf, inf)); //插入尾部数据,避免溢出
ord.push_back(player(inf, inf));
viproomqueue.push(room(inf, inf));
ordroomqueue.push(room(inf, inf));
int indexordplayer = 0, indexvipplayer = 0;
for (int i = 0; i < n; i++)
{
int updatetime = (vip[indexvipplayer].arrivetime < ord[indexordplayer].arrivetime) ? vip[indexvipplayer].arrivetime : ord[indexordplayer].arrivetime;
int mincanuse, minisvip;
if (viproomqueue.top().canusetime < ordroomqueue.top().canusetime)
{
mincanuse = viproomqueue.top().canusetime;
minisvip = 1;
}
else
{
mincanuse = ordroomqueue.top().canusetime;
minisvip = 0;
}
while (mincanuse < updatetime)
{
if (minisvip == 1)
{
int temp1 = viproomqueue.top().id;
viproomqueue.pop();
viproomqueue.push(room(updatetime, temp1));
}
else
{
int temp1 = ordroomqueue.top().id;
ordroomqueue.pop();
ordroomqueue.push(room(updatetime, temp1));
}
if (viproomqueue.top().canusetime < ordroomqueue.top().canusetime)
{
mincanuse = viproomqueue.top().canusetime;
minisvip = 1;
}
else
{
mincanuse = ordroomqueue.top().canusetime;
minisvip = 0;
}
}
if (mincanuse >= 21 * 3600) break;
if (vip[indexvipplayer].arrivetime < ord[indexordplayer].arrivetime)
{
//当前需要分配room的是一个vip: 有vip就分配vip,没有vip就分配普通房间(之前update操作保证了肯定存在房间)
if (viproomqueue.top().canusetime <= ordroomqueue.top().canusetime)
{
res.push_back(player(vip[indexvipplayer].arrivetime, viproomqueue.top().canusetime));
int temptime = viproomqueue.top().canusetime;
int tempid = viproomqueue.top().id;
viproomqueue.pop();
viproomqueue.push(room(temptime + vip[indexvipplayer].lasttime, tempid));
indexvipplayer++;
counts[tempid]++;
}
else
{
res.push_back(player(vip[indexvipplayer].arrivetime, ordroomqueue.top().canusetime));
int temptime = ordroomqueue.top().canusetime;
int tempid = ordroomqueue.top().id;
ordroomqueue.pop();
ordroomqueue.push(room(temptime + vip[indexvipplayer].lasttime, tempid));
indexvipplayer++;
counts[tempid]++;
}
}
else
{
if ((viproomqueue.top().canusetime < 21 * 3600) && vip[indexvipplayer].arrivetime <= viproomqueue.top().canusetime)
{
res.push_back(player(vip[indexvipplayer].arrivetime, viproomqueue.top().canusetime));
int temptime = viproomqueue.top().canusetime;
int tempid = viproomqueue.top().id;
viproomqueue.pop();
viproomqueue.push(room(temptime + vip[indexvipplayer].lasttime, tempid));
indexvipplayer++;
counts[tempid]++;
continue;
}
//当分配的是一个普通人,直接分配最小usetime和最小的id的就行了
if (viproomqueue.top().canusetime < ordroomqueue.top().canusetime || (viproomqueue.top().canusetime == ordroomqueue.top().canusetime && viproomqueue.top().id < ordroomqueue.top().id))
{
res.push_back(player(ord[indexordplayer].arrivetime, viproomqueue.top().canusetime));
int temptime = viproomqueue.top().canusetime;
int tempid = viproomqueue.top().id;
viproomqueue.pop();
viproomqueue.push(room(temptime + ord[indexordplayer].lasttime, tempid));
indexordplayer++;
counts[tempid]++;
}
else
{
res.push_back(player(ord[indexordplayer].arrivetime, ordroomqueue.top().canusetime));
int temptime = ordroomqueue.top().canusetime;
int tempid = ordroomqueue.top().id;
ordroomqueue.pop();
ordroomqueue.push(room(temptime + ord[indexordplayer].lasttime, tempid));
indexordplayer++;
counts[tempid]++;
}
}
}
sort(res.begin(), res.end(), cmpres);
for (int i = 0; i < res.size(); i++) printf("%02d:%02d:%02d %02d:%02d:%02d %d\n", res[i].arrivetime / 3600, res[i].arrivetime % 3600 / 60, res[i].arrivetime % 60, res[i].lasttime / 3600, res[i].lasttime % 3600 / 60, res[i].lasttime % 60, (res[i].lasttime - res[i].arrivetime + 30) / 60);
for (int i = 1; i <= k; i++)
{
if (i == 1) printf("%d", counts[i]);
else printf(" %d", counts[i]);
}
printf("\n");
return 0;
} | 40.527607 | 291 | 0.551922 | [
"vector"
] |
7a9254e8170e414dcfbb000f286d8242a1bd7d09 | 13,806 | cc | C++ | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrgeo/geo_griddedpoints.cc | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrgeo/geo_griddedpoints.cc | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrgeo/geo_griddedpoints.cc | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | #ifndef INCLUDED_STDDEFX
#include "stddefx.h"
#define INCLUDED_STDDEFX
#endif
#ifndef INCLUDED_GEO_GRIDDEDPOINTS
#include "geo_griddedpoints.h"
#define INCLUDED_GEO_GRIDDEDPOINTS
#endif
// Library headers.
#ifndef INCLUDED_ALGORITHM
#include <algorithm>
#define INCLUDED_ALGORITHM
#endif
#ifndef INCLUDED_FUNCTIONAL
#include <functional>
#define INCLUDED_FUNCTIONAL
#endif
// PCRaster library headers.
// Module headers.
#ifndef INCLUDED_GEO_CIRCULARNEIGHBOURHOOD
#include "geo_circularneighbourhood.h"
#define INCLUDED_GEO_CIRCULARNEIGHBOURHOOD
#endif
#ifndef INCLUDED_GEO_RASTERSPACE
#include "geo_rasterspace.h"
#define INCLUDED_GEO_RASTERSPACE
#endif
#ifndef INCLUDED_GEO_SCANCONVERSION
#include "geo_scanconversion.h"
#define INCLUDED_GEO_SCANCONVERSION
#endif
/*!
\file
This file contains the implementation of the GriddedPoints class.
*/
namespace geo {
//------------------------------------------------------------------------------
// DEFINITION OF STATIC GRIDDEDPOINTS MEMBERS
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// DEFINITION OF GRIDDEDPOINTS MEMBERS
//------------------------------------------------------------------------------
//! Constructor.
/*!
\param space Spatial properties of the raster.
\exception .
\warning .
\sa .
All cell are initialized as non-missing value, empty cells.
*/
template<class Point>
GriddedPoints<Point>::GriddedPoints(const RasterSpace& space)
: d_space(space), d_points(space.nrRows(), space.nrCols()),
d_missingValues(space.nrRows(), space.nrCols(), false)
{
PRECOND((space.nrRows() > 0) && (space.nrCols() > 0));
}
template<class Point>
GriddedPoints<Point>::GriddedPoints(const RasterSpace& space,
const MVRaster& missingValues)
: d_space(space), d_points(space.nrRows(), space.nrCols()),
d_missingValues(missingValues)
{
PRECOND((space.nrRows() > 0) && (space.nrCols() > 0));
}
template<class Point>
GriddedPoints<Point>::GriddedPoints(const GriddedPoints& rhs)
: d_space(rhs.d_space),
d_points(static_cast<RasterDim const&>(rhs.d_points)),
d_missingValues(rhs.d_missingValues)
{
d_points = rhs.d_points;
}
//! dtor
template<class Point>
GriddedPoints<Point>::~GriddedPoints()
{
}
//! Sets cell \a row, \a col to a missing value.
/*!
\param row Row index.
\param col Column index.
\warning All points in this cell are removed.
*/
template<class Point>
void GriddedPoints<Point>::setMV(size_t row, size_t col)
{
d_points.cell(row, col).clear();
d_missingValues.cell(row, col) = true;
}
template<class Point>
void GriddedPoints<Point>::setMV(const CellLoc& loc)
{
d_points.cell(loc.row(), loc.col()).clear();
d_missingValues.cell(loc.row(), loc.col()) = true;
}
//! Inserts point \a point in a grid cell.
/*!
\param point Point to insert.
\return .
\exception .
\warning The coordinates of \a point must correspond to a cell in the raster. This cell must not be a missing value cell.
\sa .
*/
template<class Point>
typename GriddedPoints<Point>::iterator
GriddedPoints<Point>::insert(const Point& point)
{
/*
*double r, c;
*d_space.coords2RowCol(point[0], point[1], r, c);
*PRECOND(r >= 0.0);
*PRECOND(c >= 0.0);
*size_t row = static_cast<size_t>(r);
*size_t col = static_cast<size_t>(c);
*PRECOND(row < nrRows());
*PRECOND(col < nrCols());
*PRECOND(!isMV(row, col));
*d_points.cell(row, col).push_back(point);
*/
CellLoc loc = cellLoc<Point>(point);
PRECOND(!isMV(loc));
d_points.cell(loc).push_back(point);
return --d_points.cell(loc).end();
}
//! Removes all points from the raster. Makes each raster cell empty.
/*!
*/
template<class Point>
void GriddedPoints<Point>::clear()
{
std::for_each(d_points.begin(), d_points.end(),
std::mem_fun_ref(&List::clear));
}
//! Removes point pointed to by \a it from cell \a row, \a col.
/*!
\param it Iterator to point.
\param row Row index.
\param col Column index.
\exception .
\warning The cell at position \a row, \a col must not be a missing value. This cell must contain the point pointed to by \a it.
\sa .
\todo check if precondition is still needed.
*/
template<class Point>
void GriddedPoints<Point>::remove(iterator it, size_t row, size_t col)
{
PRECOND(!isMV(row, col));
PRECOND(std::find(begin(row, col), end(row, col), *it) != end(row, col));
d_points.cell(row, col).erase(it);
}
template<class Point>
void GriddedPoints<Point>::remove(const Point& point, size_t row,
size_t col)
{
PRECOND(!isMV(row, col));
iterator it = std::find(begin(row, col), end(row, col), point);
POSTCOND(it != end(row, col));
d_points.cell(row, col).erase(it);
}
//!
/*!
\param .
\return .
\exception .
\warning .
\sa .
This function assumes that the co-ordinates of the point in *it have changed.
*/
template<class Point>
void GriddedPoints<Point>::move(iterator it, size_t row, size_t col)
{
Point point = *it;
remove(it, row, col);
insert(point);
}
template<class Point>
const RasterSpace& GriddedPoints<Point>::space() const
{
return d_space;
}
template<class Point>
const typename GriddedPoints<Point>::MVRaster&
GriddedPoints<Point>::missingValues() const
{
return d_missingValues;
}
template<class Point>
typename GriddedPoints<Point>::List& GriddedPoints<Point>::cell(
LinearLoc loc)
{
DEVELOP_PRECOND(!isMV(loc));
return d_points.cell(loc);
}
template<class Point>
typename GriddedPoints<Point>::List const& GriddedPoints<Point>::cell(
LinearLoc loc) const
{
DEVELOP_PRECOND(!isMV(loc));
return d_points.cell(loc);
}
template<class Point>
const typename GriddedPoints<Point>::List&
GriddedPoints<Point>::cell(const CellLoc& loc) const
{
DEVELOP_PRECOND(!isMV(loc));
return d_points.cell(loc);
}
template<class Point>
typename GriddedPoints<Point>::List&
GriddedPoints<Point>::cell(const CellLoc& loc)
{
DEVELOP_PRECOND(!isMV(loc));
return d_points.cell(loc);
}
template<class Point>
typename GriddedPoints<Point>::const_iterator GriddedPoints<Point>::begin(
size_t row, size_t col) const
{
DEVELOP_PRECOND(!isMV(row, col));
return d_points.cell(row, col).begin();
}
template<class Point>
typename GriddedPoints<Point>::const_iterator GriddedPoints<Point>::end(size_t row, size_t col) const
{
DEVELOP_PRECOND(!isMV(row, col));
return d_points.cell(row, col).end();
}
template<class Point>
typename GriddedPoints<Point>::iterator GriddedPoints<Point>::begin(size_t row, size_t col)
{
DEVELOP_PRECOND(!isMV(row, col));
return d_points.cell(row, col).begin();
}
template<class Point>
typename GriddedPoints<Point>::iterator GriddedPoints<Point>::end(size_t row, size_t col)
{
DEVELOP_PRECOND(!isMV(row, col));
return d_points.cell(row, col).end();
}
template<class Point>
typename GriddedPoints<Point>::iterator GriddedPoints<Point>::begin(const CellLoc& loc)
{
DEVELOP_PRECOND(!isMV(loc.row(), loc.col()));
return d_points.cell(loc.row(), loc.col()).begin();
}
template<class Point>
typename GriddedPoints<Point>::iterator GriddedPoints<Point>::end(const CellLoc& loc)
{
DEVELOP_PRECOND(!isMV(loc.row(), loc.col()));
return d_points.cell(loc.row(), loc.col()).end();
}
template<class Point>
typename GriddedPoints<Point>::const_iterator GriddedPoints<Point>::begin(const CellLoc& loc) const
{
DEVELOP_PRECOND(!isMV(loc.row(), loc.col()));
return d_points.cell(loc.row(), loc.col()).begin();
}
template<class Point>
typename GriddedPoints<Point>::const_iterator GriddedPoints<Point>::end(const CellLoc& loc) const
{
DEVELOP_PRECOND(!isMV(loc.row(), loc.col()));
return d_points.cell(loc.row(), loc.col()).end();
}
template<class Point>
bool GriddedPoints<Point>::empty() const
{
return nrPoints() == 0;
}
template<class Point>
bool GriddedPoints<Point>::empty(LinearLoc loc) const
{
DEVELOP_PRECOND(!isMV(loc));
return d_points.cell(loc).empty();
}
template<class Point>
bool GriddedPoints<Point>::empty(size_t row, size_t col) const
{
DEVELOP_PRECOND(!isMV(row, col));
return d_points.cell(row, col).empty();
}
template<class Point>
size_t GriddedPoints<Point>::size() const
{
size_t sum = 0;
for(typename PointsRaster::const_iterator it = d_points.begin();
it != d_points.end(); ++it) {
sum += (*it).size();
}
return sum;
}
template<class Point>
size_t GriddedPoints<Point>::size(size_t row, size_t col) const
{
DEVELOP_PRECOND(!isMV(row, col));
return d_points.cell(row, col).size();
}
template<class Point>
size_t GriddedPoints<Point>::size(const CellLoc& loc) const
{
return d_points.cell(loc).size();
}
template<class Point>
bool GriddedPoints<Point>::isMV(LinearLoc loc) const
{
return d_missingValues.cell(loc);
}
template<class Point>
bool GriddedPoints<Point>::isMV(size_t row, size_t col) const
{
return d_missingValues.cell(row, col);
}
template<class Point>
bool GriddedPoints<Point>::isMV(const CellLoc& loc) const
{
return d_missingValues.cell(loc.row(), loc.col());
}
template<class Point>
size_t GriddedPoints<Point>::nrRows() const
{
return d_space.nrRows();
}
template<class Point>
size_t GriddedPoints<Point>::nrCols() const
{
return d_space.nrCols();
}
template<class Point>
size_t GriddedPoints<Point>::nrCells() const
{
return d_space.nrCells();
}
template<class Point>
size_t GriddedPoints<Point>::nrPoints() const
{
size_t sum = 0;
for(size_t row = 0; row < nrRows(); ++row) {
for(size_t col = 0; col < nrCols(); ++col) {
sum += nrPoints(row, col);
}
}
return sum;
}
template<class Point>
size_t GriddedPoints<Point>::nrPoints(size_t row, size_t col) const
{
return !isMV(row, col) ? d_points.cell(row, col).size(): 0;
}
template<class Point>
size_t GriddedPoints<Point>::nrPoints(const CellLoc& loc) const
{
return !isMV(loc) ? d_points.cell(loc).size(): 0;
}
/*
namespace geo {
template<class Point>
class GetPoints {
private:
// All points.
const GriddedPoints<Point>& d_griddedPoints;
// Points within neighbourhood.
std::vector<Point> d_points;
public:
GetPoints(const GriddedPoints<Point>& griddedPoints)
: d_griddedPoints(griddedPoints)
{
}
bool operator()(size_t col, size_t row) {
if(!d_griddedPoints.isMV(row, col)) {
d_points.insert(d_points.end(), d_griddedPoints.begin(row, col),
d_griddedPoints.end(row, col));
}
return true;
}
const std::vector<Point>& points() {
return d_points;
}
};
}
*/
template<class Point>
void GriddedPoints<Point>::points(const CellLoc& loc,
double radius, std::vector<Point>& points) const
{
CircularNeighbourhood neighbourhood(0, radius);
this->points(loc, neighbourhood, points);
}
template<class Point>
void GriddedPoints<Point>::points(const CellLoc& loc,
double radius, std::vector<Point*>& points)
{
CircularNeighbourhood neighbourhood(0, radius);
this->points(loc, neighbourhood, points);
}
template<class Point>
void GriddedPoints<Point>::points(const CellLoc& loc,
const Neighbourhood& neighbourhood, std::vector<Point>& points) const
{
int startRow, startCol, rowOffset, colOffset;
if(loc.row() < neighbourhood.radius()) {
startRow = 0;
rowOffset = neighbourhood.radius() - loc.row();
}
else {
startRow = loc.row() - neighbourhood.radius();
rowOffset = -startRow;
}
if(loc.col() < neighbourhood.radius()) {
startCol = 0;
colOffset = neighbourhood.radius() - loc.col();
}
else {
startCol = loc.col() - neighbourhood.radius();
colOffset = -startCol;
}
size_t endRow = std::min(loc.row() + neighbourhood.radius(), nrRows() - 1);
size_t endCol = std::min(loc.col() + neighbourhood.radius(), nrCols() - 1);
for(size_t row = startRow; row <= endRow; ++row) {
for(size_t col = startCol; col <= endCol; ++col) {
if(neighbourhood.cell(rowOffset + row, colOffset + col) > 0.0 &&
!isMV(row, col)) {
points.insert(points.end(), begin(row, col), end(row, col));
}
}
}
}
template<class Point>
void GriddedPoints<Point>::points(const CellLoc& loc,
const Neighbourhood& neighbourhood, std::vector<Point*>& points)
{
int startRow, startCol, rowOffset, colOffset;
if(loc.row() < neighbourhood.radius()) {
startRow = 0;
rowOffset = neighbourhood.radius() - loc.row();
}
else {
startRow = loc.row() - neighbourhood.radius();
rowOffset = -startRow;
}
if(loc.col() < neighbourhood.radius()) {
startCol = 0;
colOffset = neighbourhood.radius() - loc.col();
}
else {
startCol = loc.col() - neighbourhood.radius();
colOffset = -startCol;
}
size_t endRow = std::min(loc.row() + neighbourhood.radius(), nrRows() - 1);
size_t endCol = std::min(loc.col() + neighbourhood.radius(), nrCols() - 1);
for(size_t row = startRow; row <= endRow; ++row) {
for(size_t col = startCol; col <= endCol; ++col) {
if(neighbourhood.cell(rowOffset + row, colOffset + col) > 0.0 &&
!isMV(row, col)) {
for(iterator it = begin(row, col); it != end(row, col); ++it) {
points.push_back(&*it);
}
}
}
}
}
//------------------------------------------------------------------------------
// DEFINITION OF FREE OPERATORS
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// DEFINITION OF FREE FUNCTIONS
//------------------------------------------------------------------------------
} // namespace
| 20.243402 | 131 | 0.648921 | [
"vector"
] |
7aac660d19198592467393489ff0768de90afe60 | 1,507 | cpp | C++ | solutions/LeetCode/C++/1110.cpp | timxor/leetcode-journal | 5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a | [
"MIT"
] | 854 | 2018-11-09T08:06:16.000Z | 2022-03-31T06:05:53.000Z | solutions/LeetCode/C++/1110.cpp | timxor/leetcode-journal | 5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a | [
"MIT"
] | 29 | 2019-06-02T05:02:25.000Z | 2021-11-15T04:09:37.000Z | solutions/LeetCode/C++/1110.cpp | timxor/leetcode-journal | 5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a | [
"MIT"
] | 347 | 2018-12-23T01:57:37.000Z | 2022-03-12T14:51:21.000Z | __________________________________________________________________________________________________
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<TreeNode *> roots;
void dfs(TreeNode *root, bool has_parent, const vector<int> &to_delete) {
if (root == nullptr)
return;
if (find(to_delete.begin(), to_delete.end(), root->val) != to_delete.end()) {
dfs(root->left, false, to_delete);
dfs(root->right, false, to_delete);
return;
}
if (!has_parent)
roots.push_back(root);
dfs(root->left, true, to_delete);
dfs(root->right, true, to_delete);
if (root->left != nullptr && find(to_delete.begin(), to_delete.end(), root->left->val) != to_delete.end())
root->left = nullptr;
if (root->right != nullptr && find(to_delete.begin(), to_delete.end(), root->right->val) != to_delete.end())
root->right = nullptr;
}
vector<TreeNode*> delNodes(TreeNode* root, vector<int>& to_delete) {
roots = {};
dfs(root, false, to_delete);
return roots;
}
};
__________________________________________________________________________________________________
__________________________________________________________________________________________________
| 32.06383 | 116 | 0.638354 | [
"vector"
] |
7aadabeb103675dc712ace30435769ab75b786dc | 43,429 | hpp | C++ | include/htool/solvers/proto_ddm.hpp | htool-ddm/htool | e4dbec7c08c5008e62344fd0d5ebfdf95ef8863f | [
"MIT"
] | 15 | 2020-05-06T15:20:42.000Z | 2022-03-15T10:27:56.000Z | include/htool/solvers/proto_ddm.hpp | htool-ddm/htool | e4dbec7c08c5008e62344fd0d5ebfdf95ef8863f | [
"MIT"
] | 14 | 2020-05-25T13:59:11.000Z | 2022-03-02T16:40:45.000Z | include/htool/solvers/proto_ddm.hpp | PierreMarchand20/htool | b6e91690f8d7c20d67dfb3b8db2e7ea674405a37 | [
"MIT"
] | 2 | 2018-04-25T07:44:35.000Z | 2019-11-05T16:57:00.000Z | #ifndef HTOOL_PROTO_DDM_HPP
#define HTOOL_PROTO_DDM_HPP
#include "../types/hmatrix.hpp"
#include "../types/matrix.hpp"
#include "../wrappers/wrapper_hpddm.hpp"
#include "../wrappers/wrapper_mpi.hpp"
#include <HPDDM.hpp>
namespace htool {
template <typename T, template <typename, typename> class LowRankMatrix, class ClusterImpl, template <typename> class AdmissibleCondition>
class Proto_HPDDM;
template <typename T, template <typename, typename> class LowRankMatrix, class ClusterImpl, template <typename> class AdmissibleCondition>
class Proto_DDM {
private:
int n;
int n_inside;
const std::vector<int> neighbors;
std::vector<std::vector<int>> intersections;
std::vector<T> vec_ovr;
std::vector<T> mat_loc;
std::vector<double> D;
const MPI_Comm &comm;
mutable std::map<std::string, std::string> infos;
std::vector<std::vector<T>> snd, rcv;
std::vector<int> _ipiv;
std::vector<int> _ipiv_coarse;
int nevi;
std::vector<T> evi;
std::vector<int> renum_to_global;
Matrix<T> E;
const HMatrix<T, LowRankMatrix, AdmissibleCondition> &hmat;
const T *const *Z;
std::vector<int> recvcounts;
std::vector<int> displs;
void synchronize(bool scaled) {
// Partition de l'unité
if (scaled)
fill(vec_ovr.begin() + n_inside, vec_ovr.end(), 0);
for (int i = 0; i < neighbors.size(); i++) {
for (int j = 0; j < intersections[i].size(); j++) {
snd[i][j] = vec_ovr[intersections[i][j]];
}
}
// Communications
std::vector<MPI_Request> rq(2 * neighbors.size());
for (int i = 0; i < neighbors.size(); i++) {
MPI_Isend(snd[i].data(), snd[i].size(), wrapper_mpi<T>::mpi_type(), neighbors[i], 0, comm, &(rq[i]));
MPI_Irecv(rcv[i].data(), rcv[i].size(), wrapper_mpi<T>::mpi_type(), neighbors[i], MPI_ANY_TAG, comm, &(rq[i + neighbors.size()]));
}
MPI_Waitall(rq.size(), rq.data(), MPI_STATUSES_IGNORE);
for (int i = 0; i < neighbors.size(); i++) {
for (int j = 0; j < intersections[i].size(); j++) {
vec_ovr[intersections[i][j]] += rcv[i][j];
}
}
}
public:
double timing_one_level;
double timing_Q;
Proto_DDM(const IMatrix<T> &mat0, const HMatrix<T, LowRankMatrix, ClusterImpl, AdmissibleCondition> &hmat_0, const std::vector<int> &ovr_subdomain_to_global0, const std::vector<int> &cluster_to_ovr_subdomain0, const std::vector<int> &neighbors0, const std::vector<std::vector<int>> &intersections0) : n(ovr_subdomain_to_global0.size()), n_inside(cluster_to_ovr_subdomain0.size()), neighbors(neighbors0), vec_ovr(n), mat_loc(n * n), D(n), comm(hmat_0.get_comm()), _ipiv(n), hmat(hmat_0), timing_Q(0), timing_one_level(0), recvcounts(hmat_0.get_sizeworld()), displs(hmat_0.get_sizeworld()) {
// Timing
MPI_Barrier(hmat.get_comm());
double mytime, maxtime;
double time = MPI_Wtime();
std::vector<int> renum(n, -1);
renum_to_global.resize(n);
for (int i = 0; i < cluster_to_ovr_subdomain0.size(); i++) {
renum[cluster_to_ovr_subdomain0[i]] = i;
renum_to_global[i] = ovr_subdomain_to_global0[cluster_to_ovr_subdomain0[i]];
}
int count = cluster_to_ovr_subdomain0.size();
// std::cout << count << std::endl;
for (int i = 0; i < n; i++) {
if (renum[i] == -1) {
renum[i] = count;
renum_to_global[count++] = ovr_subdomain_to_global0[i];
}
}
intersections.resize(neighbors.size());
for (int i = 0; i < neighbors.size(); i++) {
intersections[i].resize(intersections0[i].size());
for (int j = 0; j < intersections[i].size(); j++) {
intersections[i][j] = renum[intersections0[i][j]];
}
}
// Building Ai
bool sym = false;
const std::vector<LowRankMatrix<T, ClusterImpl> *> &MyDiagFarFieldMats = hmat_0.get_MyDiagFarFieldMats();
const std::vector<SubMatrix<T> *> &MyDiagNearFieldMats = hmat_0.get_MyDiagNearFieldMats();
// Internal dense blocks
for (int i = 0; i < MyDiagNearFieldMats.size(); i++) {
const SubMatrix<T> &submat = *(MyDiagNearFieldMats[i]);
int local_nr = submat.nb_rows();
int local_nc = submat.nb_cols();
int offset_i = submat.get_offset_i() - hmat_0.get_local_offset();
int offset_j = submat.get_offset_j() - hmat_0.get_local_offset();
for (int i = 0; i < local_nc; i++) {
std::copy_n(&(submat(0, i)), local_nr, &mat_loc[offset_i + (offset_j + i) * n]);
}
}
// Internal compressed block
Matrix<T> FarFielBlock(n, n);
for (int i = 0; i < MyDiagFarFieldMats.size(); i++) {
const LowRankMatrix<T, ClusterImpl> &lmat = *(MyDiagFarFieldMats[i]);
int local_nr = lmat.nb_rows();
int local_nc = lmat.nb_cols();
int offset_i = lmat.get_offset_i() - hmat_0.get_local_offset();
int offset_j = lmat.get_offset_j() - hmat_0.get_local_offset();
;
FarFielBlock.resize(local_nr, local_nc);
lmat.get_whole_matrix(&(FarFielBlock(0, 0)));
for (int i = 0; i < local_nc; i++) {
std::copy_n(&(FarFielBlock(0, i)), local_nr, &mat_loc[offset_i + (offset_j + i) * n]);
}
}
// Overlap
std::vector<T> horizontal_block(n - n_inside, n_inside), vertical_block(n, n - n_inside);
horizontal_block = mat0.get_submatrix(std::vector<int>(renum_to_global.begin() + n_inside, renum_to_global.end()), std::vector<int>(renum_to_global.begin(), renum_to_global.begin() + n_inside)).get_mat();
vertical_block = mat0.get_submatrix(renum_to_global, std::vector<int>(renum_to_global.begin() + n_inside, renum_to_global.end())).get_mat();
for (int j = 0; j < n_inside; j++) {
std::copy_n(horizontal_block.begin() + j * (n - n_inside), n - n_inside, &mat_loc[n_inside + j * n]);
}
for (int j = n_inside; j < n; j++) {
std::copy_n(vertical_block.begin() + (j - n_inside) * n, n, &mat_loc[j * n]);
}
// Timing
mytime = MPI_Wtime() - time;
MPI_Reduce(&(mytime), &(maxtime), 1, MPI_DOUBLE, MPI_MAX, 0, this->comm);
infos["DDM_setup_one_level_max"] = NbrToStr(maxtime);
// infos["DDM_facto_one_level_max" ]= NbrToStr(maxtime[1]);
//
snd.resize(neighbors.size());
rcv.resize(neighbors.size());
for (int i = 0; i < neighbors.size(); i++) {
snd[i].resize(intersections[i].size());
rcv[i].resize(intersections[i].size());
}
}
void facto_one_level() {
double time = MPI_Wtime();
double mytime, maxtime;
int lda = n;
int info;
HPDDM::Lapack<T>::getrf(&n, &n, mat_loc.data(), &lda, _ipiv.data(), &info);
if (info != 0)
std::cout << "Error in getrf from Lapack for mat_loc: info=" << info << std::endl;
mytime = MPI_Wtime() - time;
MPI_Barrier(hmat.get_comm());
// Timing
MPI_Reduce(&(mytime), &(maxtime), 1, MPI_DOUBLE, MPI_MAX, 0, this->comm);
infos["DDM_facto_one_level_max"] = NbrToStr(maxtime);
}
void build_coarse_space_geev(Matrix<T> &Mi, IMatrix<T> &generator_Bi, const std::vector<R3> &x) {
// Timing
std::vector<double> mytime(2), maxtime(2);
double time = MPI_Wtime();
// Data
int n_global = hmat.nb_cols();
int sizeWorld = hmat.get_sizeworld();
int rankWorld = hmat.get_rankworld();
int info;
// Building Neumann matrix
htool::HMatrix<T, LowRankMatrix, ClusterImpl, AdmissibleCondition> HBi(generator_Bi, hmat.get_cluster_tree_t().get_local_cluster_tree(), x, -1, MPI_COMM_SELF);
Matrix<T> Bi(n, n);
// Building Bi
bool sym = false;
const std::vector<LowRankMatrix<T, ClusterImpl> *> &MyLocalFarFieldMats = HBi.get_MyFarFieldMats();
const std::vector<SubMatrix<T> *> &MyLocalNearFieldMats = HBi.get_MyNearFieldMats();
// std::cout << MyLocalNearFieldMats.size()<<std::endl;
// std::cout << MyLocalFarFieldMats.size()<<std::endl;
// Internal dense blocks
for (int i = 0; i < MyLocalNearFieldMats.size(); i++) {
const SubMatrix<T> &submat = *(MyLocalNearFieldMats[i]);
int local_nr = submat.nb_rows();
int local_nc = submat.nb_cols();
int offset_i = submat.get_offset_i() - hmat.get_local_offset();
int offset_j = submat.get_offset_j() - hmat.get_local_offset();
for (int i = 0; i < local_nc; i++) {
std::copy_n(&(submat(0, i)), local_nr, Bi.data() + offset_i + (offset_j + i) * n);
}
}
// Internal compressed block
Matrix<T> FarFielBlock(n, n);
for (int i = 0; i < MyLocalFarFieldMats.size(); i++) {
const LowRankMatrix<T, ClusterImpl> &lmat = *(MyLocalFarFieldMats[i]);
int local_nr = lmat.nb_rows();
int local_nc = lmat.nb_cols();
int offset_i = lmat.get_offset_i() - hmat.get_local_offset();
int offset_j = lmat.get_offset_j() - hmat.get_local_offset();
;
FarFielBlock.resize(local_nr, local_nc);
lmat.get_whole_matrix(&(FarFielBlock(0, 0)));
for (int i = 0; i < local_nc; i++) {
std::copy_n(&(FarFielBlock(0, i)), local_nr, Bi.data() + offset_i + (offset_j + i) * n);
}
}
// Overlap
std::vector<T> horizontal_block(n - n_inside, n_inside), vertical_block(n, n - n_inside);
horizontal_block = generator_Bi.get_submatrix(std::vector<int>(renum_to_global.begin() + n_inside, renum_to_global.end()), std::vector<int>(renum_to_global.begin(), renum_to_global.begin() + n_inside)).get_mat();
vertical_block = generator_Bi.get_submatrix(renum_to_global, std::vector<int>(renum_to_global.begin() + n_inside, renum_to_global.end())).get_mat();
for (int j = 0; j < n_inside; j++) {
std::copy_n(horizontal_block.begin() + j * (n - n_inside), n - n_inside, Bi.data() + n_inside + j * n);
}
for (int j = n_inside; j < n; j++) {
std::copy_n(vertical_block.begin() + (j - n_inside) * n, n, Bi.data() + j * n);
}
// test
// double error=0;
// double norm_frob=0;
// for (int i=0;i<n;i++){
// for (int j=0;j<n;j++){
// error+=abs(pow(Bi(i,j)-Bi_test[i+j*n],2));
// norm_frob+=abs(pow(Bi(i,j),2));
// }
// }
// std::cout << "COUCOU "<<normFrob(Bi-Bi_test)/normFrob(Bi)<<std::endl;
// LU facto for mass matrix
int lda = n;
std::vector<int> _ipiv_mass(n);
HPDDM::Lapack<Cplx>::getrf(&n, &n, Mi.data(), &lda, _ipiv_mass.data(), &info);
if (info != 0)
std::cout << "Error in getrf from Lapack for Mi: info=" << info << std::endl;
// Partition of unity
Matrix<T> DAiD(n, n);
for (int i = 0; i < n_inside; i++) {
std::copy_n(&(mat_loc[i * n]), n_inside, &(DAiD(0, i)));
}
// M^-1
const char l = 'N';
lda = n;
int ldb = n;
HPDDM::Lapack<Cplx>::getrs(&l, &n, &n, Mi.data(), &lda, _ipiv_mass.data(), DAiD.data(), &ldb, &info);
if (info != 0)
std::cout << "Error in getrs from Lapack for Mi: info=" << info << std::endl;
HPDDM::Lapack<Cplx>::getrs(&l, &n, &n, Mi.data(), &lda, _ipiv_mass.data(), Bi.data(), &ldb, &info);
if (info != 0)
std::cout << "Error in getrs from Lapack for Bi: info=" << info << std::endl;
// Build local eigenvalue problem
Matrix<T> evp(n, n);
Bi.mvprod(DAiD.data(), evp.data(), n);
mytime[0] = MPI_Wtime() - time;
MPI_Barrier(hmat.get_comm());
time = MPI_Wtime();
// Local eigenvalue problem
int ldvl = n, ldvr = n, lwork = -1;
lda = n;
std::vector<T> work(n);
std::vector<double> rwork(2 * n);
std::vector<T> w(n);
std::vector<T> vl(n * n), vr(n * n);
HPDDM::Lapack<T>::geev("N", "V", &n, evp.data(), &lda, w.data(), nullptr, vl.data(), &ldvl, vr.data(), &ldvr, work.data(), &lwork, rwork.data(), &info);
lwork = (int)std::real(work[0]);
work.resize(lwork);
HPDDM::Lapack<T>::geev("N", "V", &n, evp.data(), &lda, w.data(), nullptr, vl.data(), &ldvl, vr.data(), &ldvr, work.data(), &lwork, rwork.data(), &info);
std::vector<int> index(n, 0);
if (info != 0)
std::cout << "Error in geev from Lapack: info=" << info << std::endl;
for (int i = 0; i != index.size(); i++) {
index[i] = i;
}
std::sort(index.begin(), index.end(), [&](const int &a, const int &b) {
return (std::abs(w[a]) > std::abs(w[b]));
});
HPDDM::Option &opt = *HPDDM::Option::get();
nevi = 0;
double threshold = opt.val("geneo_threshold", -1.0);
if (threshold > 0.0) {
while (std::abs(w[index[nevi]]) > threshold && nevi < index.size()) {
nevi++;
}
} else {
nevi = opt.val("geneo_nu", 2);
}
mytime[1] = MPI_Wtime() - time;
MPI_Barrier(hmat.get_comm());
time = MPI_Wtime();
// Timing
MPI_Reduce(&(mytime[0]), &(maxtime[0]), 2, MPI_DOUBLE, MPI_MAX, 0, this->comm);
infos["DDM_setup_geev_max"] = NbrToStr(maxtime[0]);
infos["DDM_geev_max"] = NbrToStr(maxtime[1]);
// build the coarse space
build_ZtAZ(vr, index);
}
void build_coarse_space(Matrix<T> &Mi, IMatrix<T> &generator_Bi, const std::vector<R3> &x) {
// Timing
std::vector<double> mytime(2), maxtime(2);
double time = MPI_Wtime();
// Data
int n_global = hmat.nb_cols();
int sizeWorld = hmat.get_sizeworld();
int rankWorld = hmat.get_rankworld();
int info;
// Building Neumann matrix
htool::HMatrix<T, LowRankMatrix, ClusterImpl, AdmissibleCondition> HBi(generator_Bi, hmat.get_cluster_tree_t().get_local_cluster_tree(), x, -1, MPI_COMM_SELF);
Matrix<T> Bi(n, n);
// Building Bi
bool sym = false;
const std::vector<LowRankMatrix<T, ClusterImpl> *> &MyLocalFarFieldMats = HBi.get_MyFarFieldMats();
const std::vector<SubMatrix<T> *> &MyLocalNearFieldMats = HBi.get_MyNearFieldMats();
// Internal dense blocks
for (int i = 0; i < MyLocalNearFieldMats.size(); i++) {
const SubMatrix<T> &submat = *(MyLocalNearFieldMats[i]);
int local_nr = submat.nb_rows();
int local_nc = submat.nb_cols();
int offset_i = submat.get_offset_i() - hmat.get_local_offset();
int offset_j = submat.get_offset_j() - hmat.get_local_offset();
for (int i = 0; i < local_nc; i++) {
std::copy_n(&(submat(0, i)), local_nr, Bi.data() + offset_i + (offset_j + i) * n);
}
}
// Internal compressed block
Matrix<T> FarFielBlock(n, n);
for (int i = 0; i < MyLocalFarFieldMats.size(); i++) {
const LowRankMatrix<T, ClusterImpl> &lmat = *(MyLocalFarFieldMats[i]);
int local_nr = lmat.nb_rows();
int local_nc = lmat.nb_cols();
int offset_i = lmat.get_offset_i() - hmat.get_local_offset();
int offset_j = lmat.get_offset_j() - hmat.get_local_offset();
;
FarFielBlock.resize(local_nr, local_nc);
lmat.get_whole_matrix(&(FarFielBlock(0, 0)));
for (int i = 0; i < local_nc; i++) {
std::copy_n(&(FarFielBlock(0, i)), local_nr, Bi.data() + offset_i + (offset_j + i) * n);
}
}
// Overlap
std::vector<T> horizontal_block(n - n_inside, n_inside), vertical_block(n, n - n_inside);
horizontal_block = generator_Bi.get_submatrix(std::vector<int>(renum_to_global.begin() + n_inside, renum_to_global.end()), std::vector<int>(renum_to_global.begin(), renum_to_global.begin() + n_inside)).get_mat();
vertical_block = generator_Bi.get_submatrix(renum_to_global, std::vector<int>(renum_to_global.begin() + n_inside, renum_to_global.end())).get_mat();
for (int j = 0; j < n_inside; j++) {
std::copy_n(horizontal_block.begin() + j * (n - n_inside), n - n_inside, Bi.data() + n_inside + j * n);
}
for (int j = n_inside; j < n; j++) {
std::copy_n(vertical_block.begin() + (j - n_inside) * n, n, Bi.data() + j * n);
}
// Partition of unity
Matrix<T> DAiD(n, n);
for (int i = 0; i < n_inside; i++) {
std::copy_n(&(mat_loc[i * n]), n_inside, &(DAiD(0, i)));
}
// Build local eigenvalue problem
Matrix<T> evp(n, n);
evp = Mi + Bi;
mytime[0] = MPI_Wtime() - time;
MPI_Barrier(hmat.get_comm());
time = MPI_Wtime();
// Local eigenvalue problem
int ldvl = n, ldvr = n, lwork = -1;
int lda = n, ldb = n;
std::vector<T> alpha(n), beta(n);
std::vector<T> work(n);
std::vector<double> rwork(8 * n);
std::vector<T> vl(n * n), vr(n * n);
std::vector<int> index(n, 0);
HPDDM::Lapack<T>::ggev("N", "V", &n, DAiD.data(), &lda, evp.data(), &ldb, alpha.data(), nullptr, beta.data(), vl.data(), &ldvl, vr.data(), &ldvr, work.data(), &lwork, rwork.data(), &info);
lwork = (int)std::real(work[0]);
work.resize(lwork);
HPDDM::Lapack<T>::ggev("N", "V", &n, DAiD.data(), &lda, evp.data(), &ldb, alpha.data(), nullptr, beta.data(), vl.data(), &ldvl, vr.data(), &ldvr, work.data(), &lwork, rwork.data(), &info);
if (info != 0)
std::cout << "Error in ggev from Lapack: info=" << info << std::endl;
for (int i = 0; i != index.size(); i++) {
index[i] = i;
}
std::sort(index.begin(), index.end(), [&](const int &a, const int &b) {
return ((std::abs(beta[a]) < 1e-15 || (std::abs(alpha[a] / beta[a]) > std::abs(alpha[b] / beta[b]))) && !(std::abs(beta[b]) < 1e-15));
});
HPDDM::Option &opt = *HPDDM::Option::get();
nevi = 0;
double threshold = opt.val("geneo_threshold", -1.0);
if (threshold > 0.0) {
while (std::abs(beta[index[nevi]]) < 1e-15 || (std::abs(alpha[index[nevi]] / beta[index[nevi]]) > threshold && nevi < index.size())) {
nevi++;
}
} else {
nevi = opt.val("geneo_nu", 2);
}
mytime[1] = MPI_Wtime() - time;
MPI_Barrier(hmat.get_comm());
time = MPI_Wtime();
// Timing
MPI_Reduce(&(mytime[0]), &(maxtime[0]), 2, MPI_DOUBLE, MPI_MAX, 0, this->comm);
infos["DDM_setup_geev_max"] = NbrToStr(maxtime[0]);
infos["DDM_geev_max"] = NbrToStr(maxtime[1]);
// build the coarse space
build_ZtAZ(vr, index);
}
void build_coarse_space(Matrix<T> &Ki, const std::vector<R3> &x) {
// Timing
std::vector<double> mytime(2), maxtime(2);
double time = MPI_Wtime();
// Data
int n_global = hmat.nb_cols();
int sizeWorld = hmat.get_sizeworld();
int rankWorld = hmat.get_rankworld();
int info;
// Partition of unity
Matrix<T> DAiD(n, n);
for (int i = 0; i < n_inside; i++) {
std::copy_n(&(mat_loc[i * n]), n_inside, &(DAiD(0, i)));
}
mytime[0] = MPI_Wtime() - time;
MPI_Barrier(hmat.get_comm());
time = MPI_Wtime();
// Local eigenvalue problem
int ldvl = n, ldvr = n, lwork = -1;
int lda = n, ldb = n;
std::vector<T> alpha(n), beta(n);
std::vector<T> work(n);
std::vector<double> rwork(8 * n);
std::vector<T> vl(n * n), vr(n * n);
std::vector<int> index(n, 0);
HPDDM::Lapack<T>::ggev("N", "V", &n, DAiD.data(), &lda, Ki.data(), &ldb, alpha.data(), nullptr, beta.data(), vl.data(), &ldvl, vr.data(), &ldvr, work.data(), &lwork, rwork.data(), &info);
lwork = (int)std::real(work[0]);
work.resize(lwork);
HPDDM::Lapack<T>::ggev("N", "V", &n, DAiD.data(), &lda, Ki.data(), &ldb, alpha.data(), nullptr, beta.data(), vl.data(), &ldvl, vr.data(), &ldvr, work.data(), &lwork, rwork.data(), &info);
if (info != 0)
std::cout << "Error in ggev from Lapack: info=" << info << std::endl;
for (int i = 0; i != index.size(); i++) {
index[i] = i;
}
std::sort(index.begin(), index.end(), [&](const int &a, const int &b) {
return ((std::abs(beta[a]) < 1e-15 || (std::abs(alpha[a] / beta[a]) > std::abs(alpha[b] / beta[b]))) && !(std::abs(beta[b]) < 1e-15));
});
HPDDM::Option &opt = *HPDDM::Option::get();
nevi = 0;
double threshold = opt.val("geneo_threshold", -1.0);
if (threshold > 0.0) {
while (std::abs(beta[index[nevi]]) < 1e-15 || (std::abs(alpha[index[nevi]] / beta[index[nevi]]) > threshold && nevi < index.size())) {
nevi++;
}
} else {
nevi = opt.val("geneo_nu", 2);
}
mytime[1] = MPI_Wtime() - time;
MPI_Barrier(hmat.get_comm());
time = MPI_Wtime();
// Timing
MPI_Reduce(&(mytime[0]), &(maxtime[0]), 2, MPI_DOUBLE, MPI_MAX, 0, this->comm);
infos["DDM_setup_geev_max"] = NbrToStr(maxtime[0]);
infos["DDM_geev_max"] = NbrToStr(maxtime[1]);
// Cleaning eigenvectors associated with kernel of Ki
int count = 0;
std::vector<int> nb_comp_conn;
while (std::abs(beta[index[count]]) < 1e-15) {
std::cout << std::setprecision(18);
std::vector<T> values;
std::vector<T> temp(n, 0);
// Find values
for (int i = 0; i < n; i++) {
bool in = 0;
for (int j = 0; j < values.size(); j++) {
if (std::abs(values[j] - vr[i + index[count] * n]) < 1e-6) {
in = 1;
break;
}
}
if (!in) {
values.push_back(vr[i + index[count] * n]);
}
}
// Find connex component
for (int i = 0; i < n; i++) {
if (std::abs(values[count] - vr[i + index[count] * n]) < 1e-6) {
temp[i] = 1;
}
}
std::copy_n(temp.data(), n, vr.data() + index[count] * n);
nb_comp_conn.push_back(values.size());
count++;
}
count = 0;
std::vector<T> test_comp(n, 0);
while (std::abs(beta[index[count]]) < 1e-15) {
for (int i = 0; i < n; i++) {
test_comp[i] = test_comp[i] + vr[i + index[count] * n];
}
count++;
}
if (std::abs(std::accumulate(test_comp.begin(), test_comp.end(), std::complex<double>(0)) - test_comp.size() * 1.0) > 1e-10 && std::abs(beta[index[0]]) < 1e-15) {
std::cout << "WARNING: something wrong happened computing the eigenvectors in the kernel of the Neumann matrix" << std::endl;
}
// build the coarse space
build_ZtAZ(vr, index);
}
// // Not working
// void build_coarse_space_arpack( Matrix<T>& Ki, const std::vector<R3>& x ){
// // Timing
// std::vector<double> mytime(2), maxtime(2);
// double time = MPI_Wtime();
// // Data
// int n_global= hmat.nb_cols();
// int sizeWorld = hmat.get_sizeworld();
// int rankWorld = hmat.get_rankworld();
// int info;
// // Partition of unity
// Matrix<T> DAiD(n,n);
// for (int i =0 ;i < n_inside;i++){
// std::copy_n(&(mat_loc[i*n]),n_inside,&(DAiD(0,i)));
// }
// mytime[0] = MPI_Wtime() - time;
// MPI_Barrier(hmat.get_comm());
// time = MPI_Wtime();
// // Local eigenvalue problem
// HPDDM::Option& opt = *HPDDM::Option::get();
// int nu = opt.val("geneo_nu",2);
// int threshold = opt.val("geneo_threshold",2);
// bool sym= false;
// T** Z;
// HPDDM::MatrixCSR<T>* A = new HPDDM::MatrixCSR<T>(n, n, n * n, DAiD.data(), nullptr, nullptr, sym);
// HPDDM::MatrixCSR<T>* B = new HPDDM::MatrixCSR<T>(n, n, n * n, Ki.data(), nullptr, nullptr, sym);
// HPDDM::Arpack<T> eps(threshold, n, nu);
// std::cout <<"Warning"<<std::endl;
// eps.template solve<HPDDM::LapackTRSub>(A,B,Z,hmat.get_comm());
// int nevi = eps._nu;
// std::cout << "(rankWorld,nevi): "<<rankWorld<<" "<<nevi<<std::endl;
// mytime[1] = MPI_Wtime() - time;
// MPI_Barrier(hmat.get_comm());
// time = MPI_Wtime();
// // Timing
// MPI_Reduce(&(mytime[0]), &(maxtime[0]), 2, MPI_DOUBLE, MPI_MAX, 0,this->comm);
// infos["DDM_setup_geev_max" ]= NbrToStr(maxtime[0]);
// infos["DDM_geev_max" ]= NbrToStr(maxtime[1]);
// // build the coarse space
// build_ZtAZ_arpack(Z,nevi);
// }
void build_ZtAZ(const std::vector<T> &vr, const std::vector<int> &index) {
// Timing
std::vector<double> mytime(2), maxtime(2);
double time = MPI_Wtime();
// Data
int sizeWorld = hmat.get_sizeworld();
int rankWorld = hmat.get_rankworld();
int info = 0;
// Allgather
MPI_Allgather(&nevi, 1, MPI_INT, recvcounts.data(), 1, MPI_INT, comm);
displs[0] = 0;
for (int i = 1; i < sizeWorld; i++) {
displs[i] = displs[i - 1] + recvcounts[i - 1];
}
//
int size_E = std::accumulate(recvcounts.begin(), recvcounts.end(), 0);
int nevi_max = *std::max_element(recvcounts.begin(), recvcounts.end());
evi.resize(nevi * n, 0);
for (int i = 0; i < nevi; i++) {
// std::fill_n(evi.data()+i*n,n_inside,rankWorld+1);
// std::copy_n(Z[i],n_inside,evi.data()+i*n);
std::copy_n(vr.data() + index[i] * n, n_inside, evi.data() + i * n);
}
int local_max_size_j = 0;
const std::vector<LowRankMatrix<T, ClusterImpl> *> &MyFarFieldMats = hmat.get_MyFarFieldMats();
const std::vector<SubMatrix<T> *> &MyNearFieldMats = hmat.get_MyNearFieldMats();
for (int i = 0; i < MyFarFieldMats.size(); i++) {
if (local_max_size_j < (*MyFarFieldMats[i]).nb_cols())
local_max_size_j = (*MyFarFieldMats[i]).nb_cols();
}
for (int i = 0; i < MyNearFieldMats.size(); i++) {
if (local_max_size_j < (*MyNearFieldMats[i]).nb_cols())
local_max_size_j = (*MyNearFieldMats[i]).nb_cols();
}
std::vector<T> AZ(nevi_max * n_inside, 0);
E.resize(size_E, size_E);
for (int i = 0; i < sizeWorld; i++) {
std::vector<T> buffer((hmat.get_MasterOffset_t(i).second + 2 * local_max_size_j) * recvcounts[i], 0);
std::fill_n(AZ.data(), recvcounts[i] * n_inside, 0);
if (rankWorld == i) {
for (int j = 0; j < recvcounts[i]; j++) {
for (int k = 0; k < n_inside; k++) {
buffer[recvcounts[i] * (k + local_max_size_j) + j] = evi[j * n + k];
}
}
}
MPI_Bcast(buffer.data() + local_max_size_j * recvcounts[i], hmat.get_MasterOffset_t(i).second * recvcounts[i], wrapper_mpi<T>::mpi_type(), i, comm);
hmat.mvprod_subrhs(buffer.data(), AZ.data(), recvcounts[i], hmat.get_MasterOffset_t(i).first, hmat.get_MasterOffset_t(i).second, local_max_size_j);
for (int j = 0; j < recvcounts[i]; j++) {
for (int k = 0; k < n_inside; k++) {
vec_ovr[k] = AZ[j + recvcounts[i] * k];
}
// Parce que partition de l'unité...
// synchronize(true);
for (int jj = 0; jj < nevi; jj++) {
int coord_E_i = displs[i] + j;
int coord_E_j = displs[rankWorld] + jj;
E(coord_E_i, coord_E_j) = std::inner_product(evi.data() + jj * n, evi.data() + jj * n + n_inside, vec_ovr.data(), T(0), std::plus<T>(), [](T u, T v) { return u * std::conj(v); });
}
}
}
if (rankWorld == 0)
MPI_Reduce(MPI_IN_PLACE, E.data(), size_E * size_E, wrapper_mpi<T>::mpi_type(), MPI_SUM, 0, comm);
else
MPI_Reduce(E.data(), E.data(), size_E * size_E, wrapper_mpi<T>::mpi_type(), MPI_SUM, 0, comm);
mytime[0] = MPI_Wtime() - time;
MPI_Barrier(hmat.get_comm());
time = MPI_Wtime();
int n_coarse = size_E;
_ipiv_coarse.resize(n_coarse);
HPDDM::Lapack<T>::getrf(&n_coarse, &n_coarse, E.data(), &n_coarse, _ipiv_coarse.data(), &info);
if (info != 0)
std::cout << "Error in getrf from Lapack for E: info=" << info << std::endl;
mytime[1] = MPI_Wtime() - time;
MPI_Barrier(hmat.get_comm());
time = MPI_Wtime();
// Timing
MPI_Reduce(&(mytime[0]), &(maxtime[0]), 2, MPI_DOUBLE, MPI_MAX, 0, this->comm);
infos["DDM_setup_ZtAZ_max"] = NbrToStr(maxtime[0]);
infos["DDM_facto_ZtAZ_max"] = NbrToStr(maxtime[1]);
}
void build_ZtAZ_arpack(T **Z, int nevi) {
// Timing
std::vector<double> mytime(2), maxtime(2);
double time = MPI_Wtime();
// Data
int sizeWorld = hmat.get_sizeworld();
int rankWorld = hmat.get_rankworld();
int info = 0;
// Allgather
MPI_Allgather(&nevi, 1, MPI_INT, recvcounts.data(), 1, MPI_INT, comm);
displs[0] = 0;
for (int i = 1; i < sizeWorld; i++) {
displs[i] = displs[i - 1] + recvcounts[i - 1];
}
//
int size_E = std::accumulate(recvcounts.begin(), recvcounts.end(), 0);
int nevi_max = *std::max_element(recvcounts.begin(), recvcounts.end());
evi.resize(nevi * n, 0);
for (int i = 0; i < nevi; i++) {
// std::fill_n(evi.data()+i*n,n_inside,rankWorld+1);
// std::copy_n(Z[i],n_inside,evi.data()+i*n);
std::copy_n(Z[i], n_inside, evi.data() + i * n);
}
int local_max_size_j = 0;
const std::vector<LowRankMatrix<T, ClusterImpl> *> &MyFarFieldMats = hmat.get_MyFarFieldMats();
const std::vector<SubMatrix<T> *> &MyNearFieldMats = hmat.get_MyNearFieldMats();
for (int i = 0; i < MyFarFieldMats.size(); i++) {
if (local_max_size_j < (*MyFarFieldMats[i]).nb_cols())
local_max_size_j = (*MyFarFieldMats[i]).nb_cols();
}
for (int i = 0; i < MyNearFieldMats.size(); i++) {
if (local_max_size_j < (*MyNearFieldMats[i]).nb_cols())
local_max_size_j = (*MyNearFieldMats[i]).nb_cols();
}
std::vector<T> AZ(nevi_max * n_inside, 0);
E.resize(size_E, size_E);
for (int i = 0; i < sizeWorld; i++) {
std::vector<T> buffer((hmat.get_MasterOffset_t(i).second + 2 * local_max_size_j) * recvcounts[i], 0);
std::fill_n(AZ.data(), recvcounts[i] * n_inside, 0);
if (rankWorld == i) {
for (int j = 0; j < recvcounts[i]; j++) {
for (int k = 0; k < n_inside; k++) {
buffer[recvcounts[i] * (k + local_max_size_j) + j] = evi[j * n + k];
}
}
}
MPI_Bcast(buffer.data() + local_max_size_j * recvcounts[i], hmat.get_MasterOffset_t(i).second * recvcounts[i], wrapper_mpi<T>::mpi_type(), i, comm);
hmat.mvprod_subrhs(buffer.data(), AZ.data(), recvcounts[i], hmat.get_MasterOffset_t(i).first, hmat.get_MasterOffset_t(i).second, local_max_size_j);
for (int j = 0; j < recvcounts[i]; j++) {
for (int k = 0; k < n_inside; k++) {
vec_ovr[k] = AZ[j + recvcounts[i] * k];
}
// Parce que partition de l'unité...
// synchronize(true);
for (int jj = 0; jj < nevi; jj++) {
int coord_E_i = displs[i] + j;
int coord_E_j = displs[rankWorld] + jj;
E(coord_E_i, coord_E_j) = std::inner_product(evi.data() + jj * n, evi.data() + jj * n + n_inside, vec_ovr.data(), T(0), std::plus<T>(), [](T u, T v) { return u * std::conj(v); });
}
}
}
if (rankWorld == 0)
MPI_Reduce(MPI_IN_PLACE, E.data(), size_E * size_E, wrapper_mpi<T>::mpi_type(), MPI_SUM, 0, comm);
else
MPI_Reduce(E.data(), E.data(), size_E * size_E, wrapper_mpi<T>::mpi_type(), MPI_SUM, 0, comm);
mytime[0] = MPI_Wtime() - time;
MPI_Barrier(hmat.get_comm());
time = MPI_Wtime();
int n_coarse = size_E;
_ipiv_coarse.resize(n_coarse);
HPDDM::Lapack<T>::getrf(&n_coarse, &n_coarse, E.data(), &n_coarse, _ipiv_coarse.data(), &info);
if (info != 0)
std::cout << "Error in getrf from Lapack for E: info=" << info << std::endl;
mytime[1] = MPI_Wtime() - time;
MPI_Barrier(hmat.get_comm());
time = MPI_Wtime();
// Timing
MPI_Reduce(&(mytime[0]), &(maxtime[0]), 2, MPI_DOUBLE, MPI_MAX, 0, this->comm);
infos["DDM_setup_ZtAZ_max"] = NbrToStr(maxtime[0]);
infos["DDM_facto_ZtAZ_max"] = NbrToStr(maxtime[1]);
}
void one_level(const T *const in, T *const out) {
int sizeWorld;
MPI_Comm_size(comm, &sizeWorld);
// Without overlap to with overlap
std::copy_n(in, n_inside, vec_ovr.data());
// std::cout << n<<" "<<n_inside <<std::endl;
// std::fill(vec_ovr.begin(),vec_ovr.end(),0);
// std::fill_n(vec_ovr.begin(),n_inside,1);
synchronize(true);
// Timing
MPI_Barrier(hmat.get_comm());
double time = MPI_Wtime();
// std::cout << n_inside<<std::endl;
// std::cout << n<<std::endl;
const char l = 'N';
int lda = n;
int ldb = n;
int nrhs = 1;
int info;
// std::cout << n <<" "<<n_inside<<" "<<mat_loc.size()<<" "<<vec_ovr.size()<<std::endl;
HPDDM::Lapack<T>::getrs(&l, &n, &nrhs, mat_loc.data(), &lda, _ipiv.data(), vec_ovr.data(), &ldb, &info);
if (info != 0)
std::cout << "Error in getrs from Lapack for mat_loc: info=" << info << std::endl;
timing_one_level += MPI_Wtime() - time;
// std::cout << info << std::endl;
HPDDM::Option &opt = *HPDDM::Option::get();
int schwarz_method = opt.val("schwarz_method", HPDDM_SCHWARZ_METHOD_RAS);
if (schwarz_method == HPDDM_SCHWARZ_METHOD_RAS) {
synchronize(true);
} else if (schwarz_method == HPDDM_SCHWARZ_METHOD_ASM) {
synchronize(false);
}
std::copy_n(vec_ovr.data(), n_inside, out);
}
void Q(const T *const in, T *const out) {
std::copy_n(in, n_inside, vec_ovr.data());
synchronize(true);
std::vector<T> zti(nevi);
int sizeWorld;
int rankWorld;
MPI_Comm_size(comm, &sizeWorld);
MPI_Comm_rank(comm, &rankWorld);
// Timing
MPI_Barrier(hmat.get_comm());
double time = MPI_Wtime();
for (int i = 0; i < nevi; i++) {
zti[i] = std::inner_product(evi.begin() + i * n, evi.begin() + i * n + n, vec_ovr.begin(), T(0), std::plus<T>(), [](T u, T v) { return u * std::conj(v); });
// zti[i]=std::inner_product(Z[i],Z[i+1],vec_ovr.begin(),T(0),std::plus<T>(), [](T u,T v){return u*std::conj(v);});
}
std::vector<T> zt(E.nb_cols(), 0);
// if (rankWorld==0){
// // std::cout << zt.size() <<" " << zti.size() << std::endl;
// }
MPI_Gatherv(zti.data(), zti.size(), wrapper_mpi<T>::mpi_type(), zt.data(), recvcounts.data(), displs.data(), wrapper_mpi<T>::mpi_type(), 0, comm);
if (rankWorld == 0) {
const char l = 'N';
int zt_size = zt.size();
int lda = zt_size;
int ldb = zt_size;
int nrhs = 1;
int info;
// std::cout << n <<" "<<n_inside<<" "<<mat_loc.size()<<" "<<vec_ovr.size()<<std::endl;
HPDDM::Lapack<T>::getrs(&l, &zt_size, &nrhs, E.data(), &lda, _ipiv_coarse.data(), zt.data(), &ldb, &info);
if (info != 0)
std::cout << "Error in getrs from Lapack for E: info=" << info << std::endl;
// std::cout << "GETRS : "<<info << std::endl;
}
MPI_Scatterv(zt.data(), recvcounts.data(), displs.data(), wrapper_mpi<T>::mpi_type(), zti.data(), zti.size(), wrapper_mpi<T>::mpi_type(), 0, comm);
std::fill_n(vec_ovr.data(), n, 0);
for (int i = 0; i < nevi; i++) {
std::transform(vec_ovr.begin(), vec_ovr.begin() + n, evi.begin() + n * i, vec_ovr.begin(), [&i, &zti](T u, T v) { return u + v * zti[i]; });
// std::transform(vec_ovr.begin(),vec_ovr.begin()+n,Z[i],vec_ovr.begin(),[&i,&zti](T u, T v){return u+v*zti[i];});
}
timing_Q += MPI_Wtime() - time;
synchronize(true);
std::copy_n(vec_ovr.data(), n_inside, out);
}
void apply(const T *const in, T *const out) {
std::vector<T> out_one_level(n_inside, 0);
std::vector<T> out_Q(n_inside, 0);
std::vector<T> buffer(hmat.nb_cols());
std::vector<T> aq(n_inside);
std::vector<T> p(n_inside);
std::vector<T> am1p(n_inside);
std::vector<T> qam1p(n_inside);
std::vector<T> ptm1p(n_inside);
HPDDM::Option &opt = *HPDDM::Option::get();
int schwarz_method = opt.val("schwarz_method", HPDDM_SCHWARZ_METHOD_RAS);
if (schwarz_method == HPDDM_SCHWARZ_METHOD_NONE) {
std::copy_n(in, n_inside, out);
} else {
switch (opt.val("schwarz_coarse_correction", 42)) {
case HPDDM_SCHWARZ_COARSE_CORRECTION_BALANCED:
Q(in, out_Q.data());
hmat.mvprod_local(out_Q.data(), aq.data(), buffer.data(), 1);
std::transform(in, in + n_inside, aq.begin(), p.begin(), std::minus<T>());
one_level(p.data(), out_one_level.data());
hmat.mvprod_local(out_one_level.data(), am1p.data(), buffer.data(), 1);
Q(am1p.data(), qam1p.data());
std::transform(out_one_level.begin(), out_one_level.begin() + n_inside, qam1p.begin(), ptm1p.data(), std::minus<T>());
std::transform(out_Q.begin(), out_Q.begin() + n_inside, ptm1p.begin(), out, std::plus<T>());
break;
case HPDDM_SCHWARZ_COARSE_CORRECTION_DEFLATED:
Q(in, out_Q.data());
hmat.mvprod_local(out_Q.data(), aq.data(), buffer.data(), 1);
std::transform(in, in + n_inside, aq.begin(), p.begin(), std::minus<T>());
one_level(p.data(), out_one_level.data());
std::transform(out_one_level.begin(), out_one_level.begin() + n_inside, out_Q.begin(), out, std::plus<T>());
break;
case HPDDM_SCHWARZ_COARSE_CORRECTION_ADDITIVE:
Q(in, out_Q.data());
one_level(in, out_one_level.data());
std::transform(out_one_level.begin(), out_one_level.begin() + n_inside, out_Q.begin(), out, std::plus<T>());
break;
default:
one_level(in, out);
break;
}
}
// ASM
// one_level(in,out);
// Q(in,out_Q.data());
// std::transform(out_one_level.begin(),out_one_level.begin()+n_inside,out_Q.begin(),out,std::plus<T>());
// // ADEF1
// Q(in,out_Q.data());
// std::vector<T> aq(n_inside);
// hmat.mvprod_local(out_Q.data(),aq.data(),buffer.data(),1);
// std::vector<T> p(n_inside);
//
// std::transform(in, in+n_inside , aq.begin(),p.begin(),std::minus<T>());
//
// one_level(p.data(),out_one_level.data());
//
// std::transform(out_one_level.begin(),out_one_level.begin()+n_inside,out_Q.begin(),out,std::plus<T>());
// // BNN
//
// Q(in,out_Q.data());
// hmat.mvprod_local(out_Q.data(),aq.data(),buffer.data(),1);
// std::transform(in, in+n_inside , aq.begin(),p.begin(),std::minus<T>());
//
// one_level(p.data(),out_one_level.data());
// hmat.mvprod_local(out_one_level.data(),am1p.data(),buffer.data(),1);
// Q(am1p.data(),qam1p.data());
//
// std::transform(out_one_level.begin(),out_one_level.begin()+n_inside,qam1p.begin(),ptm1p.data(),std::minus<T>());
// std::transform(out_Q.begin(),out_Q.begin()+n_inside,ptm1p.begin(),out,std::plus<T>());
}
void init_hpddm(Proto_HPDDM<T, LowRankMatrix, ClusterImpl, AdmissibleCondition> &hpddm_op) {
bool sym = false;
hpddm_op.initialize(n, sym, nullptr, neighbors, intersections);
}
int get_n() const { return n; }
int get_n_inside() const { return n_inside; }
int get_nevi() const { return nevi; }
int get_size_E() const { return E.nb_cols(); } // E is not rectangular...
std::map<std::string, std::string> &get_infos() const { return infos; }
std::string get_infos(const std::string &key) const { return infos[key]; }
void set_infos(const std::string &key, const std::string &value) const { infos[key] = value; }
double get_timing_one_level() const { return timing_one_level; }
double get_timing_Q() const { return timing_Q; }
};
} // namespace htool
#endif
| 43.299103 | 593 | 0.523521 | [
"vector",
"transform"
] |
7aae4faf7d06808703d984cc45b84bb439ae6e56 | 3,252 | cpp | C++ | i2p1/src/function/lab12_3_107021128.cpp | richard21708/i2p-nthu-math | 2cd2aedd31fcfe29fd59f21db72e012b4e113421 | [
"MIT"
] | null | null | null | i2p1/src/function/lab12_3_107021128.cpp | richard21708/i2p-nthu-math | 2cd2aedd31fcfe29fd59f21db72e012b4e113421 | [
"MIT"
] | 7 | 2021-12-30T08:51:25.000Z | 2022-01-19T02:26:49.000Z | i2p1/src/function/lab12_3_107021128.cpp | richard21708/i2p-nthu-math | 2cd2aedd31fcfe29fd59f21db72e012b4e113421 | [
"MIT"
] | 17 | 2021-09-23T07:54:26.000Z | 2022-01-11T11:58:48.000Z | #include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
void parse_expression(const string &expression, vector<string> &tokens);
bool check_expression(const vector<string> &tokens);
string calculate_postfix_expression(vector<string> &tokens, int &last_pos);
// hint: use std::to_string(long) to convert long to string
// see https://en.cppreference.com/w/cpp/string/basic_string/to_string
// hint: use recursion to find the subexpressions of two operands
void print_ops(const vector<string> &tokens);
void print_nums(const vector<string> &tokens);
int main(int argc, char *argv[])
{
string input_buffer;
vector<string> tokens;
cout << "Please input the expression: ";
std::getline(cin, input_buffer);
parse_expression(input_buffer, tokens);
if (!check_expression(tokens))
{
cout << "Invalid expression." << endl;
return EXIT_FAILURE;
}
print_nums(tokens);
print_ops(tokens);
cout << "Result:";
int last_pos = tokens.size() - 1;
calculate_postfix_expression(tokens, last_pos);
cout << endl;
return EXIT_SUCCESS;
}
void parse_expression(string const &expression, vector<string> &tokens)
{
stringstream tokens_extractor(expression);
for (string new_token; (tokens_extractor >> new_token);)
{
tokens.push_back(new_token);
}
}
bool check_expression(const vector<string> &tokens)
{
int op_cnt = 0, num_cnt = 0;
int number_in_stack_cnt = 0;
for (int i = 0; i < tokens.size(); ++i)
{
if (tokens[i] == "+" || tokens[i] == "-"
|| tokens[i] == "*" || tokens[i] == "/")
{
++op_cnt;
if (--number_in_stack_cnt < 1)
return false;
}
else
{
try
{
stol(tokens[i]);
++num_cnt;
++number_in_stack_cnt;
}
catch (const std::exception &e)
{
return false;
}
}
}
return num_cnt == op_cnt + 1 && number_in_stack_cnt == 1;
}
string calculate_postfix_expression(vector<string> &tokens, int &last_pos)
{
if (tokens.size() == 1)
{
cout << " " << tokens[0];
return tokens[0];
}
vector<long> numbers;
for (int i = 0; i < tokens.size(); ++i)
{
if (tokens[i] == "+" || tokens[i] == "-"
|| tokens[i] == "*" || tokens[i] == "/")
{
long b = numbers.back();
numbers.pop_back();
long a = numbers.back();
numbers.pop_back();
if (tokens[i] == "+")
numbers.push_back(a + b);
else if (tokens[i] == "-")
numbers.push_back(a - b);
else if (tokens[i] == "*")
numbers.push_back(a * b);
else if (b != 0)
numbers.push_back(a / b);
else
{
numbers.push_back(a);
cerr << endl
<< "ERROR: divided by zero" << endl;
}
cout << " " << numbers.back();
}
else
{
numbers.push_back(stol(tokens[i]));
}
}
return to_string(numbers.back());
}
void print_ops(const vector<string> &tokens)
{
cout << "Operators:";
for (int i = 0; i < tokens.size(); ++i)
{
if (tokens[i] == "+" || tokens[i] == "-"
|| tokens[i] == "*" || tokens[i] == "/")
{
cout << " " << tokens[i];
}
}
cout << endl;
}
void print_nums(const vector<string> &tokens)
{
cout << "Operands:";
for (int i = 0; i < tokens.size(); ++i)
{
try
{
long number = stol(tokens[i]);
cout << " " << number;
}
catch (const std::exception &e)
{
}
}
cout << endl;
} | 20.45283 | 75 | 0.612854 | [
"vector"
] |
7aaf3e866632d8ddfd8df45fb811c501e6b5dd98 | 4,408 | cxx | C++ | Examples/DataManipulation/Cxx/RGrid.cxx | forestGzh/VTK | bc98327275bd5cfa95c5825f80a2755a458b6da8 | [
"BSD-3-Clause"
] | 3 | 2015-07-28T18:07:50.000Z | 2018-02-28T20:59:58.000Z | Examples/DataManipulation/Cxx/RGrid.cxx | forestGzh/VTK | bc98327275bd5cfa95c5825f80a2755a458b6da8 | [
"BSD-3-Clause"
] | null | null | null | Examples/DataManipulation/Cxx/RGrid.cxx | forestGzh/VTK | bc98327275bd5cfa95c5825f80a2755a458b6da8 | [
"BSD-3-Clause"
] | 4 | 2016-09-08T02:11:00.000Z | 2019-08-15T02:38:39.000Z | /*=========================================================================
Program: Visualization Toolkit
Module: RGrid.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// This example shows how to create a rectilinear grid.
//
#include <vtkActor.h>
#include <vtkCamera.h>
#include <vtkFloatArray.h>
#include <vtkNamedColors.h>
#include <vtkNew.h>
#include <vtkPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkRectilinearGrid.h>
#include <vtkRectilinearGridGeometryFilter.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <array>
int main()
{
vtkNew<vtkNamedColors> colors;
std::array<double, 47> x = {
{-1.22396, -1.17188, -1.11979, -1.06771, -1.01562, -0.963542,
-0.911458, -0.859375, -0.807292, -0.755208, -0.703125, -0.651042,
-0.598958, -0.546875, -0.494792, -0.442708, -0.390625, -0.338542,
-0.286458, -0.234375, -0.182292, -0.130209, -0.078125, -0.026042,
0.0260415, 0.078125, 0.130208, 0.182291, 0.234375, 0.286458,
0.338542, 0.390625, 0.442708, 0.494792, 0.546875, 0.598958,
0.651042, 0.703125, 0.755208, 0.807292, 0.859375, 0.911458,
0.963542, 1.01562, 1.06771, 1.11979, 1.17188}};
std::array<double, 33> y = {
{-1.25, -1.17188, -1.09375, -1.01562, -0.9375, -0.859375,
-0.78125, -0.703125, -0.625, -0.546875, -0.46875, -0.390625,
-0.3125, -0.234375, -0.15625, -0.078125, 0, 0.078125,
0.15625, 0.234375, 0.3125, 0.390625, 0.46875, 0.546875,
0.625, 0.703125, 0.78125, 0.859375, 0.9375, 1.01562,
1.09375, 1.17188, 1.25}};
std::array<double, 44> z = {{0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.75,
0.8, 0.9, 1, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6,
1.7, 1.75, 1.8, 1.9, 2, 2.1, 2.2, 2.3, 2.4,
2.5, 2.6, 2.7, 2.75, 2.8, 2.9, 3, 3.1, 3.2,
3.3, 3.4, 3.5, 3.6, 3.7, 3.75, 3.8, 3.9}};
// Create a rectilinear grid by defining three arrays specifying the
// coordinates in the x-y-z directions.
vtkNew<vtkFloatArray> xCoords;
for (auto&& i : x)
{
xCoords->InsertNextValue(i);
}
vtkNew<vtkFloatArray> yCoords;
for (auto&& i : y)
{
yCoords->InsertNextValue(i);
}
vtkNew<vtkFloatArray> zCoords;
for (auto&& i : z)
{
zCoords->InsertNextValue(i);
}
// The coordinates are assigned to the rectilinear grid. Make sure that
// the number of values in each of the XCoordinates, YCoordinates,
// and ZCoordinates is equal to what is defined in SetDimensions().
//
vtkNew<vtkRectilinearGrid> rgrid;
rgrid->SetDimensions(int(x.size()), int(y.size()), int(z.size()));
rgrid->SetXCoordinates(xCoords);
rgrid->SetYCoordinates(yCoords);
rgrid->SetZCoordinates(zCoords);
// Extract a plane from the grid to see what we've got.
vtkNew<vtkRectilinearGridGeometryFilter> plane;
plane->SetInputData(rgrid);
plane->SetExtent(0, 46, 16, 16, 0, 43);
vtkNew<vtkPolyDataMapper> rgridMapper;
rgridMapper->SetInputConnection(plane->GetOutputPort());
vtkNew<vtkActor> wireActor;
wireActor->SetMapper(rgridMapper);
wireActor->GetProperty()->SetRepresentationToWireframe();
wireActor->GetProperty()->SetColor(colors->GetColor3d("Indigo").GetData());
// Create the usual rendering stuff.
vtkNew<vtkRenderer> renderer;
vtkNew<vtkRenderWindow> renWin;
renWin->AddRenderer(renderer);
vtkNew<vtkRenderWindowInteractor> iren;
iren->SetRenderWindow(renWin);
renderer->AddActor(wireActor);
renderer->SetBackground(1, 1, 1);
renderer->ResetCamera();
renderer->GetActiveCamera()->Elevation(60.0);
renderer->GetActiveCamera()->Azimuth(30.0);
renderer->GetActiveCamera()->Zoom(1.0);
renderer->SetBackground(colors->GetColor3d("Cornsilk").GetData());
renWin->SetSize(600, 600);
// interact with data
renWin->Render();
iren->Start();
return EXIT_SUCCESS;
}
| 35.837398 | 79 | 0.619328 | [
"render"
] |
7aca74cfa8c8cde3806f54dc2b57e2b11fdfa373 | 14,029 | cc | C++ | onnxruntime/core/providers/cpu/math/einsum_auxiliary_ops.cc | hwangdeyu/onnxruntime | 989fe2498f4dd0beaf1b4324bf74a39abaf86a29 | [
"MIT"
] | 1 | 2020-06-01T11:48:12.000Z | 2020-06-01T11:48:12.000Z | onnxruntime/core/providers/cpu/math/einsum_auxiliary_ops.cc | harish-kamath/onnxruntime_vw | 2c731cbf5aceb42182f1b40183a4e18d12a832c7 | [
"MIT"
] | 17 | 2020-07-21T11:13:27.000Z | 2022-03-27T02:37:05.000Z | onnxruntime/core/providers/cpu/math/einsum_auxiliary_ops.cc | Surfndez/onnxruntime | 9d748afff19e9604a00632d66b97159b917dabb2 | [
"MIT"
] | 1 | 2020-11-09T07:51:33.000Z | 2020-11-09T07:51:33.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "einsum_auxiliary_ops.h"
namespace onnxruntime {
namespace EinsumOp {
std::unique_ptr<Tensor> Transpose(const Tensor& input, const std::vector<int64_t>& input_shape_override,
const std::vector<size_t>& permutation, AllocatorPtr allocator) {
auto input_rank = input_shape_override.size();
ORT_ENFORCE(input_rank == permutation.size(), "Length of permutation must match the rank of the input to be permutated");
std::vector<int64_t> output_dims;
output_dims.reserve(input_rank);
for (const auto& dim : permutation) {
output_dims.push_back(input_shape_override.at(dim));
}
// Pass in allocator as that will be used as an allocator deleter by the framework
// and it will de-allocate the memory for this intermediate tensor when it goes out of scope
std::unique_ptr<Tensor> output = onnxruntime::make_unique<Tensor>(input.DataType(), output_dims, allocator);
TensorShape overriden_shape(input_shape_override);
TransposeBase::DoTranspose(permutation, input, *output, &overriden_shape);
return output;
}
template <typename T>
std::unique_ptr<Tensor> MatMul(const Tensor& input_1, const std::vector<int64_t>& input_shape_1_override,
const Tensor& input_2, const std::vector<int64_t>& input_shape_2_override,
AllocatorPtr allocator, concurrency::ThreadPool* tp) {
// Sanity checks before the actual MatMul
ORT_ENFORCE(input_1.DataType() == input_2.DataType(), "Data types of the inputs must match for MatMul");
ORT_ENFORCE(input_shape_1_override.size() == 3 && input_shape_2_override.size() == 3, "Only 1 batch dimension is allowed for MatMul");
ORT_ENFORCE(input_shape_1_override[0] == input_shape_2_override[0], "Batch dimension should match for MatMul;");
ORT_ENFORCE(input_shape_1_override[2] == input_shape_2_override[1], "Incompatible matrix dimensions for matMul");
size_t batches = static_cast<size_t>(input_shape_1_override[0]);
size_t M = static_cast<size_t>(input_shape_1_override[1]);
size_t K = static_cast<size_t>(input_shape_1_override[2]);
size_t N = static_cast<size_t>(input_shape_2_override[2]);
size_t left_offset = M * K;
size_t right_offset = K * N;
size_t output_offset = M * N;
std::vector<int64_t> output_dims;
output_dims.reserve(3);
output_dims.push_back(static_cast<int64_t>(batches));
output_dims.push_back(static_cast<int64_t>(M));
output_dims.push_back(static_cast<int64_t>(N));
// Pass in allocator as that will be used as an allocator deleter by the framework
// and it will de-allocate the memory for this intermediate tensor when it goes out of scope
std::unique_ptr<Tensor> output = onnxruntime::make_unique<Tensor>(input_1.DataType(), output_dims, allocator);
const T* input_1_data = input_1.template Data<T>();
const T* input_2_data = input_2.template Data<T>();
T* output_data = output->template MutableData<T>();
// Process each batch
// TODO: Currently we parallelize a single MatMul operation, add logic to determine if
// we can parallelizing on batches would be more optimal
for (size_t i = 0; i < batches; ++i) {
math::MatMul<T>(
static_cast<int>(M),
static_cast<int>(N),
static_cast<int>(K),
input_1_data + i * left_offset,
input_2_data + i * right_offset,
output_data + i * output_offset, tp);
}
return output;
}
template <typename T>
std::unique_ptr<Tensor> ReduceSum(const Tensor& input, const std::vector<int64_t>& input_shape_override,
const std::vector<int64_t>& reduce_axes, AllocatorPtr allocator, concurrency::ThreadPool* tp) {
TensorShape overriden_shape(input_shape_override);
auto output = onnxruntime::ReduceSum<T>::Impl(input, reduce_axes, allocator, tp, true, &overriden_shape);
return onnxruntime::make_unique<Tensor>(std::move(output));
}
// A specific helper just for the Diagonal op
static inline bool IsTransposeRequiredForDiagonal(int64_t dim_1, int64_t dim_2, int64_t rank) {
// If the input is 2D, we don't need a transpose
if (rank == 2)
return false;
// If the two dims are the innermost dims, no transpose is required
if ((dim_1 == rank - 1 && dim_2 == rank - 2) ||
(dim_1 == rank - 2 && dim_2 == rank - 1))
return false;
// Transpose is required
return true;
}
template <typename T>
static void DiagonalDataAssignment(const T* input_data, T* output_data, int64_t batch_size, int64_t base_stride, int64_t inner_stride) {
int64_t output_iter = 0;
// TODO: Parallelize this operation
for (int64_t i = 0; i < batch_size; ++i) {
auto base_offset = i * base_stride;
for (int64_t j = 0; j < inner_stride; ++j) {
output_data[output_iter] = input_data[base_offset + j * inner_stride + j];
output_iter++;
}
}
}
// Parse diagonal elements along the 2 innermost dimensions
// E.g.: input_shape = [1, 2, 3, 3]
// This implementation provides flexibility as to which of the 2 innermost dim values is preserved
// via the `preserve_innermost_dim_val` parameter
// preserve_innermost_dim_val == true,
// output_shape = [1, 2, 1, 3] => the diagonal contains 3 elements and the dim value of the innermost dim is preserved
// preserve_innermost_dim_val == false,
// output_shape = [1, 2, 3, 1] => the diagonal contains 3 elements and the dim value of the non-innermost dim is preserved
static std::unique_ptr<Tensor> DiagonalInnermostDims(const Tensor& input,
bool preserve_innermost_dim_val, AllocatorPtr allocator) {
const auto& input_dims = input.Shape().GetDims();
auto rank = input_dims.size();
const size_t element_size_in_bytes = input.DataType()->Size();
// This is an internal method and we already have finished all validations in the calling method.
// We proceed without duplicating all validations again here.
// We have a minimalistic check here to make sure the innermost dims have the same dim value
// as the calling method may have done a transpose before calling this method
ORT_ENFORCE(input_dims[rank - 2] == input_dims[rank - 1],
"The innermost dims should have the same dim value to parse the diagonal elements");
std::vector<int64_t> output_dims;
output_dims.reserve(rank);
int64_t batch_size = 1; // Flatten the outermost dims - this will be the number of iterations
for (size_t i = 0; i < rank - 2; ++i) {
auto input_dim_value = input_dims[i];
batch_size *= input_dim_value;
output_dims.push_back(input_dim_value);
}
if (preserve_innermost_dim_val) {
output_dims.push_back(1);
output_dims.push_back(input_dims[rank - 1]);
} else {
output_dims.push_back(input_dims[rank - 1]);
output_dims.push_back(1);
}
int64_t inner_stride = input_dims[rank - 1]; // offset to move over the innermost dim
int64_t base_stride = inner_stride * inner_stride; // offset to move over all the axes except the 2 innermost dims
// Pass in allocator as that will be used as an allocator deleter by the framework
// and it will de-allocate the memory for this intermediate tensor when it goes out of scope
std::unique_ptr<Tensor> output = onnxruntime::make_unique<Tensor>(input.DataType(), output_dims, allocator);
switch (element_size_in_bytes) {
case 4:
DiagonalDataAssignment<float>(reinterpret_cast<const float*>(input.DataRaw()), reinterpret_cast<float*>(output->MutableDataRaw()),
batch_size, base_stride, inner_stride);
break;
case 8:
DiagonalDataAssignment<double>(reinterpret_cast<const double*>(input.DataRaw()), reinterpret_cast<double*>(output->MutableDataRaw()),
batch_size, base_stride, inner_stride);
break;
default:
ORT_THROW("Einsum op: Unsupported data type for Diagonal ", input.DataType());
}
return output;
}
std::unique_ptr<Tensor> Diagonal(const Tensor& input, int64_t dim_1, int64_t dim_2, AllocatorPtr allocator) {
const auto& input_shape = input.Shape();
const auto& input_dims = input_shape.GetDims();
auto rank = static_cast<int64_t>(input_dims.size());
ORT_ENFORCE(rank >= 2 && dim_1 != dim_2 && input_dims[dim_1] == input_dims[dim_2],
"Cannot parse the diagonal elements along dims ", dim_1, " and ", dim_2, " for input shape ", input_shape);
int64_t first_dim = -1; // first_dim holds the lesser of dim_1 and dim_2
int64_t second_dim = -1; // second_dim holds the greater of dim_1 and dim_2
if (dim_1 < dim_2) {
first_dim = dim_1;
second_dim = dim_2;
} else {
first_dim = dim_2;
second_dim = dim_1;
}
std::unique_ptr<Tensor> output;
bool preserve_innermost_dim_val = false;
bool is_transpose_required = IsTransposeRequiredForDiagonal(dim_1, dim_2, rank);
if (is_transpose_required) {
std::vector<size_t> permutation(rank, 0);
int64_t first_dim_axis = -1; // This is the axis eventually occupied by the first_dim
// If one of the diagonal dimensions is one of the 2 innermost dims, then leave it as such
// so as to avoid transpose overhead
if (first_dim == rank - 2) { // If rank - 2 is occupied by first_dim, keep it there
permutation[rank - 2] = first_dim;
first_dim_axis = rank - 2;
} else {
if (second_dim != rank - 2) { // If rank - 2 is not occupied by second_dim, then put first_dim there
permutation[rank - 2] = first_dim;
first_dim_axis = rank - 2;
} else { // If rank - 2 is occupied by second_dim, then put first_dim in rank - 1
permutation[rank - 1] = first_dim;
first_dim_axis = rank - 1;
preserve_innermost_dim_val = true; // We always want to preserve the dim value of the first_dim
}
}
// Put the second_dim in the dim not occupied by the first_dim
if (first_dim_axis != rank - 1) {
permutation[rank - 1] = second_dim;
} else {
permutation[rank - 2] = second_dim;
}
int64_t iter = 0;
for (int64_t i = 0; i < rank; ++i) {
if (i != first_dim && i != second_dim) {
permutation[iter++] = i;
}
}
// Permutate the input so that the dims from which we need the diagonal forms the innermost dims
auto transposed = Transpose(input, input_dims, permutation, allocator);
// Parse the diagonal from the innermost dims
output = DiagonalInnermostDims(*transposed, preserve_innermost_dim_val, allocator);
// Swap back the dimensions to the original axes ordering using a "reverse permutation"
// Find the "reverse" permutation
iter = 0;
std::vector<size_t> reverse_permutation(rank, 0);
for (const auto& perm : permutation) {
reverse_permutation[perm] = iter++;
}
// Permutate using the reverse permutation to get back the original axes ordering
output = Transpose(*output, output->Shape().GetDims(), reverse_permutation, allocator);
} else {
// No transposing required
output = DiagonalInnermostDims(input, preserve_innermost_dim_val, allocator);
}
// Make copy of the output dims
auto output_dims = output->Shape().GetDims();
// Unsqueeze the reduced dim
auto iter = output_dims.begin() + second_dim;
output_dims.erase(iter);
output->Reshape(output_dims);
return output;
}
// Explicit template instantiation
// float
template std::unique_ptr<Tensor> MatMul<float>(const Tensor& input_1, const std::vector<int64_t>& input_shape_1_override,
const Tensor& input_2, const std::vector<int64_t>& input_shape_2_override,
AllocatorPtr allocator, concurrency::ThreadPool* tp);
template std::unique_ptr<Tensor> ReduceSum<float>(const Tensor& input, const std::vector<int64_t>& input_shape_override,
const std::vector<int64_t>& reduce_axes, AllocatorPtr allocator, concurrency::ThreadPool* tp);
// int32_t
template std::unique_ptr<Tensor> MatMul<int32_t>(const Tensor& input_1, const std::vector<int64_t>& input_shape_1_override,
const Tensor& input_2, const std::vector<int64_t>& input_shape_2_override,
AllocatorPtr allocator, concurrency::ThreadPool* tp);
template std::unique_ptr<Tensor> ReduceSum<int32_t>(const Tensor& input, const std::vector<int64_t>& input_shape_override,
const std::vector<int64_t>& reduce_axes, AllocatorPtr allocator, concurrency::ThreadPool* tp);
// double
template std::unique_ptr<Tensor> MatMul<double>(const Tensor& input_1, const std::vector<int64_t>& input_shape_1_override,
const Tensor& input_2, const std::vector<int64_t>& input_shape_2_override,
AllocatorPtr allocator, concurrency::ThreadPool* tp);
template std::unique_ptr<Tensor> ReduceSum<double>(const Tensor& input, const std::vector<int64_t>& input_shape_override,
const std::vector<int64_t>& reduce_axes, AllocatorPtr allocator, concurrency::ThreadPool* tp);
// int64_t
template std::unique_ptr<Tensor> MatMul<int64_t>(const Tensor& input_1, const std::vector<int64_t>& input_shape_1_override,
const Tensor& input_2, const std::vector<int64_t>& input_shape_2_override,
AllocatorPtr allocator, concurrency::ThreadPool* tp);
template std::unique_ptr<Tensor> ReduceSum<int64_t>(const Tensor& input, const std::vector<int64_t>& input_shape_override,
const std::vector<int64_t>& reduce_axes, AllocatorPtr allocator, concurrency::ThreadPool* tp);
} // namespace EinsumOp
} // namespace onnxruntime
| 45.846405 | 146 | 0.683299 | [
"shape",
"vector"
] |
7ad58f03e195f92a0d5a6da532ef2c24fcb30019 | 18,553 | cpp | C++ | shore/shore-mt/src/sm/tests/htab.cpp | anshsarkar/TailBench | 25845756aee9a892229c25b681051591c94daafd | [
"MIT"
] | 4 | 2019-01-24T02:00:23.000Z | 2021-03-17T11:56:59.000Z | shore/shore-mt/src/sm/tests/htab.cpp | anshsarkar/TailBench | 25845756aee9a892229c25b681051591c94daafd | [
"MIT"
] | 1 | 2020-06-23T08:29:09.000Z | 2020-06-24T12:11:47.000Z | shore/shore-mt/src/sm/tests/htab.cpp | anshsarkar/TailBench | 25845756aee9a892229c25b681051591c94daafd | [
"MIT"
] | 4 | 2019-01-22T10:35:55.000Z | 2021-03-17T11:57:23.000Z | /*<std-header orig-src='shore'>
$Id: htab.cpp,v 1.3 2010/06/08 22:28:15 nhall Exp $
SHORE -- Scalable Heterogeneous Object REpository
Copyright (c) 1994-99 Computer Sciences Department, University of
Wisconsin -- Madison
All Rights Reserved.
Permission to use, copy, modify and distribute this software and its
documentation is hereby granted, provided that both the copyright
notice and this permission notice appear in all copies of the
software, derivative works or modified versions, and any portions
thereof, and that both notices appear in supporting documentation.
THE AUTHORS AND THE COMPUTER SCIENCES DEPARTMENT OF THE UNIVERSITY
OF WISCONSIN - MADISON ALLOW FREE USE OF THIS SOFTWARE IN ITS
"AS IS" CONDITION, AND THEY DISCLAIM ANY LIABILITY OF ANY KIND
FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
This software was developed with support by the Advanced Research
Project Agency, ARPA order number 018 (formerly 8230), monitored by
the U.S. Army Research Laboratory under contract DAAB07-91-C-Q518.
Further funding for this work was provided by DARPA through
Rome Research Laboratory Contract No. F30602-97-2-0247.
*/
#define SM_SOURCE
#define HTAB_UNIT_TEST_C
#include "w.h"
typedef w_rc_t rc_t;
typedef unsigned short uint2_t;
#include "sm_int_4.h"
#include "bf_core.h"
#include "w_getopt.h"
#include "rand48.h"
rand48 tls_rng = RAND48_INITIALIZER;
bool debug(false);
bool Random(false);
bool Random_uniq(false);
int tries(10);
signed48_t pagebound(1000);
uint2_t vol(1);
uint storenum(5);
uint bufkb(1024);
uint4_t npgwriters(1);
uint4_t nbufpages = 0;
void usage(int W_UNUSED(argc), char *const *argv)
{
// while ((option = getopt(argc, argv, "b:dn:p:Rs:v:w:")) != -1) {
cerr << "usage: " << argv[0]
<< " -b <bufpoolsz in KB> : default=" << int(bufkb)
<< endl
<< " -w <#pagewriters> : default=" << int(npgwriters)
<< endl
<< " -v <volume#> : default= " << int(vol)
<< endl
<< " -s <store#> : default=" << int(storenum)
<< endl
<< " -R (means use random page#s : default="
<< (const char *)(Random?"true":"false")
<< endl
<< " -r (means use unique random page#s : default="
<< (const char *)(Random_uniq?"true":"false")
<< endl
<< " -p <page# limit> : default=" << long(pagebound)
<< endl
<< " -n <# tries> : default=" << tries
<< endl
<< " -d (means debug : default="
<< (const char *)(debug?"true":"false")
<< endl;
}
class bfcb_t; // forward
// This has to derive from smthread_t because the buffer-pool has to
// be used in an smthread_t::run() context, in order that its statistics
// can be gathered in a per-thread structure. If we don't do it this way,
// we'll croak in INC_TSTAT deep in the buffer pool.
class htab_tester : public smthread_t
{
typedef enum { Zero, Init, Inserted, Evicted, Returned, Removed } Status;
// Zero: not used yet
// Init : initialized with a pid
// Inserted : Inserted into the htab
// Evicted: we noticed it's not in the ht any more -
// bf_core::replacement evicted it
// Returned: got moved by an insert (we don't get told about every move)
// Removed: we removed it
bf_m * _bfm;
int _tries;
signed48_t _pagebound;
uint2_t _vol;
uint _store;
bf_core_m *core;
protected:
struct pidinfo
{
lpid_t pid; // index i -> pid
lpid_t returned; // return value from insert
Status status;
int count; // # times random gave us this pid
int count_removes; // # times returned/evicted/removed
int inserts;
int evicts;
pidinfo() : status(Zero),count(0),count_removes(0),
inserts(0), evicts(0) {}
friend ostream & operator<< (ostream &o, const struct pidinfo &info);
};
friend ostream & operator<< (ostream &o, const struct pidinfo &info);
private:
lpid_t *_i2pid; // indexed by i
pidinfo *_pid2info; // indexed by pid
bf_core_m::Tstats S;
public:
htab_tester(int i, signed48_t pb, uint2_t v, uint s) :
_bfm(NULL),
_tries(i),
_pagebound(pb),
_vol(v), _store(s)
{
{
long space_needed = bf_m::mem_needed(nbufpages);
/*
* Allocate the buffer-pool memory
*/
char *shmbase;
w_rc_t e;
#ifdef HAVE_HUGETLBFS
// fprintf(stderr, "setting path to %s\n", _hugetlbfs_path->value());
e = smthread_t::set_hugetlbfs_path(HUGETLBFS_PATH);
#endif
e = smthread_t::set_bufsize(space_needed, shmbase);
if (e.is_error()) {
W_COERCE(e);
}
w_assert1(is_aligned(shmbase));
bf_m *_bfm = new bf_m(nbufpages, shmbase, npgwriters);
if (! _bfm) {
W_FATAL(fcOUTOFMEMORY);
}
}
_pid2info = new pidinfo[int(pb)];
_i2pid = new lpid_t[i];
core = _bfm->_core;
memset(&S, '\0', sizeof(S));
}
~htab_tester()
{
}
void run();
void run_inserts();
void run_lookups();
void run_removes();
void cleanup();
pidinfo & pid2info(const lpid_t &p) { return _pid2info[p.page]; }
pidinfo &i2info(int i) { return pid2info(i2pid(i)); }
lpid_t &i2pid(int i) { return _i2pid[i]; }
bool was_returned(lpid_t &p)
{
for(int i=0; i < _tries; i++)
{
if(_pid2info[i].returned == p) return true;
}
return false;
}
// non-const b/c it updates the stats
void printstats(ostream &o, bool final=false);
void print_bf_fill(ostream &o) const;
};
void
htab_tester::print_bf_fill(ostream &o) const
{
int frames, slots;
htab_count(core, frames, slots);
o << "BPool HTable stats part2: #buffers " << frames
<< " #slots " << slots
<< " " << (slots*100.0)/(float)frames
<< "% full "
<< endl;
}
void
htab_tester::printstats(ostream &o, bool final)
{
if(final) o << "FINAL ";
o << "NEW htab stats:" << endl;
#define D(x) if(S.bf_htab_##x > 0) o << S.bf_htab_##x << " " << #x << endl;
if(!final)
{
D(insertions);
D(ensures);
D(cuckolds);
D(slow_inserts);
D(slots_tried);
D(probes);
D(harsh_probes);
D(probe_empty);
D(hash_collisions);
D(harsh_lookups);
D(lookups);
D(lookups_failed);
D(removes);
D(max_limit);
D(limit_exceeds);
}
#undef D
#define D(x) if(S.x > 0) o << #x << " " << S.x << endl;
else
{
_bfm->htab_stats(S);
S.compute();
D(bf_htab_insertions);
// D(bf_htab_slots_tried);
D(bf_htab_slow_inserts);
D(bf_htab_probe_empty);
// D(bf_htab_hash_collisions); (depends on hash funcs, optimiz level)
D(bf_htab_harsh_lookups);
D(bf_htab_lookups);
D(bf_htab_lookups_failed);
D(bf_htab_removes);
}
#undef D
print_bf_fill(o);
}
void htab_tester::cleanup()
{
run_removes();
delete[] _pid2info;
delete[] _i2pid;
// delete core;
delete _bfm;
_bfm=0;
}
void htab_tester::run()
{
signed48_t pgnum(0);
// Create the set of page ids
// Either sequential or random.
for(int i=0; i < _tries; i++)
{
pidinfo &info = i2info(i);
w_assert0(info.status == Zero);
}
for(int i=0; i < _tries; i++)
{
if(Random) {
// If Random_uniq, we have to look through all
// the already-created pids and if this pgnum is
// already there, we have to jettison it and
// try another.
pgnum = tls_rng.randn(_pagebound);
if(Random_uniq) {
// give it at most _pagebound tries
int j= int(_pagebound);
while (j-- > 0)
{
pidinfo &info = _pid2info[pgnum];
// Is it already in use?
if(info.status == Zero) break;
// yes -> try again
pgnum = tls_rng.randn(_pagebound);
}
if(j == 0) {
cerr << " Could not create unique random set " << endl;
exit (-1);
}
#if 0
} else {
pidinfo &info = _pid2info[pgnum];
if(info.status != Zero)
if(debug) {
// merely report duplicate
cout << " random produced duplicate "
<< info.pid
<< endl;
}
#endif
}
} else {
// sequential
pgnum = i % _pagebound;
}
// Create a pid based on pgnum and store it
#define START 0
// Well, there IS a page 0...
pgnum += START;
lpid_t p(_vol, _store, pgnum);
pidinfo &info = pid2info(p);
#if 0
if(info.status != Zero) if(debug)
{
// duplicate
cout << __LINE__
<< " detected duplicate " << p
<< " at index " << i
// << " info: " << info
<< endl;
w_assert1(info.status == Init);
w_assert1(info.pid == p);
w_assert1(info.count > 0);
}
#endif
_i2pid[i] = p;
info.pid = p;
info.count ++;
// info.returned is null pid
info.status = Init;
info.inserts = info.evicts = 0;
#if 0
if(debug) cout << p << endl;
#endif
}
// let's verify that we have no dups if we don't want dups
if(debug || Random_uniq) for(int i=0; i < _tries; i++)
{
pidinfo &info=_pid2info[_i2pid[i].page];
if(Random_uniq) w_assert0(int(info.pid.page) == i || info.pid.page == 0);
#if 0
if(info.count > 1) {
cout << info.pid << " duplicated; count= "
<< info.count << endl;
}
#endif
}
if(Random_uniq) {
cout << "verified no dups" << endl;
}
// do the test
run_inserts();
run_lookups();
// Don't remove: just see how the hash table used the
// available buffers and entries.
// run_removes();
{
int evicted(0), returned(0), inserted(0), inited(0), removed(0);
for(int i=0; i < _tries; i++)
{
pidinfo &info = i2info(i);
if(info.status == Init) inited++;
if(info.status == Inserted) inserted++;
if(info.status == Returned) returned++;
if(info.status == Evicted) evicted++;
if(info.status == Removed) removed++;
}
int unaccounted = _tries - (inited + inserted+ returned + evicted
+ removed);
cout << "Remaining Init " << inited
<< " Inserted " << inserted
<< " Evicted " << evicted
<< " Returned " << returned
<< " Removed " << removed
<< " Unaccounted " << unaccounted
<< endl;
}
printstats(cout, true);
cleanup();
}
void htab_tester::run_inserts()
{
for(int i=0; i < _tries; i++)
{
pidinfo &info = i2info(i);
lpid_t pid = info.pid;
if(info.status == Inserted)
if(debug) {
cout
<< "i=" << i
<< " pid=" << pid
<< " ALREADY INSERTED "
<< endl;
// This COULD trigger an assert in bf_core.cpp
cout << " #inserts " << info.inserts
<< " #evicts " << info.evicts
<< " count " << info.count
<< endl;
}
int slots(0);
int frames(0);
if(debug)
{
htab_count(core, frames, slots);
cout << "before htab_insert:\t frames =" << frames
<< " slots in use " << slots <<endl;;
}
bfcb_t *p = htab_insert(core, pid, S);
if(p)
{
if(debug) {
cout << "Possible move: : pid= "
<< pid
<< " returned pid "
<< p->pid()
<< endl;
printstats(cout);
}
info.returned = p->pid();
pidinfo &info_returned = pid2info(p->pid());
info_returned.status = Returned;
info_returned.evicts++ ;
// make sure the pin count is zero so that
// the sm has a possibility of evicting it later.
p->zero_pin_cnt();
}
info.status = Inserted;
info.inserts++;
if(debug) {
if(i % 10) cout << "." ;
else cout << i << endl;
}
bfcb_t *p2 = htab_lookup(core, pid, S);
if(!p2) {
cerr << " Cannot find just-inserted page " << pid << endl;
printstats(cerr);
w_assert1(0);
} else {
// correct the pin-count, since the lookup incremented it...
// This is to avoid an assert at shut-down
// and to give the old bf htab half a chance to evict a
// page.
p2->zero_pin_cnt();
}
w_assert1(p2->pid() == pid);
if(debug) {
int slots2;
htab_count(core, frames, slots2);
if(slots2 < slots)
{
cout << "htab_insert reduced # entries in use:\t frames ="
<< frames << " slots in use " << slots2 <<endl;
// w_assert1(0);
}
}
}
if(debug) {
cout <<endl << " after insertions : " << endl; printstats(cout);
}
}
void htab_tester::run_lookups()
{
for(int i=0; i < _tries; i++)
{
pidinfo &info = i2info(i);
lpid_t pid=info.pid;
bfcb_t *p = htab_lookup(core, pid, S);
if(!p) {
if(info.status != Returned)
{
// NOTE: the hash table at this writing gives
// no indication when it cannot insert because
// it ran out of room. The assumption is that
// there is room for everything because in the
// sm the number of page buffers in the pool limits
// the number of things you would have inserted
// at any time.
// What happens here is that the bf_core::replacement()
// pitches out what it finds that has pin_cnt of 0,
// which is the case for every one of these we are inserting.
if(debug) {
cout << pid << " was evicted; "
<< " status = " << info.status
<< " was_returned = " << was_returned(pid)
<< endl;
}
info.status = Evicted; // without explanation
info.evicts++; // without explanation
}
}
}
if(debug) {
cout <<endl << " after lookups : " << endl; printstats(cout);
}
}
void htab_tester::run_removes()
{
for(int i=0; i < _tries; i++)
{
pidinfo &info = i2info(i);
lpid_t pid=info.pid;
if(info.count_removes == 0)
{
// Don't try to remove it twice
/*bool b =*/ htab_remove(core, pid, S);
info.status = Removed;
// note: returns false if pin count was zero, which
// it will be for this test.
info.count_removes++;
}
}
if(debug) {
cout << endl << " after removes : " << endl; printstats(cout);
cout << endl;
}
}
#include <pthread.h>
int
main (int argc, char *const argv[])
{
const int page_sz = SM_PAGESIZE;
char option;
while ((option = getopt(argc, argv, "b:dFn:p:rRs:Tv:w:")) != -1) {
switch (option) {
case 'r' :
Random_uniq = true;
Random = true;
break;
case 'R' :
Random = true;
break;
case 'd' :
debug = true;
break;
case 'b' :
bufkb = strtol(optarg, 0, 0);
break;
case 'w' :
npgwriters = strtol(optarg, 0, 0);
break;
case 'v':
vol = atoi(optarg);
break;
case 's':
storenum = atoi(optarg);
break;
case 'p':
pagebound = strtol(optarg, 0, 0);
break;
case 'n':
tries = atoi(optarg);
break;
default:
usage(argc, argv);
return 1;
break;
}
}
if(Random_uniq && (tries > pagebound)) {
// NOTE: we now have to do this because we index
// the info structures on the page #
cerr << "For " << tries
<< " page bound (-p) is too low: "
<< int(pagebound) << ". Using " << tries << endl;
pagebound = tries;
}
nbufpages = (bufkb * 1024 - 1) / page_sz + 1;
if (nbufpages < 10) {
cerr << error_prio << "ERROR: buffer size ("
<< bufkb
<< "-KB) is too small" << flushl;
cerr << error_prio << " at least " << 10 * page_sz / 1024
<< "-KB is needed" << flushl;
W_FATAL(fcOUTOFMEMORY);
}
#if DEAD
long space_needed = bf_m::mem_needed(nbufpages);
/*
* Allocate the buffer-pool memory
*/
char *shmbase;
w_rc_t e;
#ifdef HAVE_HUGETLBFS
// fprintf(stderr, "setting path to %s\n", _hugetlbfs_path->value());
e = smthread_t::set_hugetlbfs_path(HUGETLBFS_PATH);
#endif
e = smthread_t::set_bufsize(space_needed, shmbase);
if (e.is_error()) {
W_COERCE(e);
}
w_assert1(is_aligned(shmbase));
// cout <<"SHM at address " << W_ADDR(shmbase) << endl;
bf_m *bf = new bf_m(nbufpages, shmbase, npgwriters);
if (! bf) {
W_FATAL(fcOUTOFMEMORY);
}
// cout <<"bfm at address " << W_ADDR(bf)
// << " nbufpages " << nbufpages
// << " npagewriters " << npgwriters
// << endl;
#endif
latch_t::on_thread_init(me());
{
cout <<"creating tests with "
<< tries << " tries, "
<< pagebound << " upper bound on pages, "
<< " volume " << vol
<< ", store " << storenum
<< "."
<< endl;
htab_tester anon(tries, pagebound, vol, storenum);
anon.fork();
anon.join();
}
// cerr << endl << flushl;
latch_t::on_thread_destroy(me());
return 0;
}
| 28.282012 | 82 | 0.514688 | [
"object"
] |
7ad85db5f5ab9108f2166ee08ae0d7822b1b68e0 | 3,325 | cpp | C++ | samples/hello_ar_c/app/src/main/gef_abertay/platform/win32/system/platform_win32_null_renderer.cpp | JD1305/arcore-android-sdk | ac3661d9dc65a608235d775cf6a916df2329b399 | [
"Apache-2.0"
] | null | null | null | samples/hello_ar_c/app/src/main/gef_abertay/platform/win32/system/platform_win32_null_renderer.cpp | JD1305/arcore-android-sdk | ac3661d9dc65a608235d775cf6a916df2329b399 | [
"Apache-2.0"
] | null | null | null | samples/hello_ar_c/app/src/main/gef_abertay/platform/win32/system/platform_win32_null_renderer.cpp | JD1305/arcore-android-sdk | ac3661d9dc65a608235d775cf6a916df2329b399 | [
"Apache-2.0"
] | null | null | null | #define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <platform/win32/system/platform_win32_null_renderer.h>
#include <platform/win32/system/file_win32.h>
#include <maths/matrix44.h>
namespace gef
{
PlatformWin32NullRenderer::PlatformWin32NullRenderer()
{
}
PlatformWin32NullRenderer::~PlatformWin32NullRenderer()
{
}
void PlatformWin32NullRenderer::PreRender()
{
}
void PlatformWin32NullRenderer::PostRender()
{
}
void PlatformWin32NullRenderer::Clear() const
{
}
bool PlatformWin32NullRenderer::Update()
{
return true;
}
float PlatformWin32NullRenderer::GetFrameTime()
{
return 0.0f;
}
std::string PlatformWin32NullRenderer::FormatFilename(const std::string& filename) const
{
return filename;
}
std::string PlatformWin32NullRenderer::FormatFilename(const char* filename) const
{
return std::string(filename);
}
Matrix44 PlatformWin32NullRenderer::PerspectiveProjectionFov(const float fov, const float aspect_ratio, const float near_distance, const float far_distance) const
{
Matrix44 projection_matrix;
projection_matrix.SetIdentity();
return projection_matrix;
}
Matrix44 PlatformWin32NullRenderer::PerspectiveProjectionFrustum(const float left, const float right, const float top, const float bottom, const float near_distance, const float far_distance) const
{
Matrix44 projection_matrix;
projection_matrix.SetIdentity();
return projection_matrix;
}
Matrix44 PlatformWin32NullRenderer::OrthographicFrustum(const float left, const float right, const float top, const float bottom, const float near_distance, const float far_distance) const
{
Matrix44 projection_matrix;
projection_matrix.SetIdentity();
return projection_matrix;
}
void PlatformWin32NullRenderer::BeginScene() const
{
}
void PlatformWin32NullRenderer::EndScene() const
{
}
const char* PlatformWin32NullRenderer::GetShaderDirectory() const
{
return NULL;
}
const char* PlatformWin32NullRenderer::GetShaderFileExtension() const
{
return NULL;
}
class SpriteRenderer* PlatformWin32NullRenderer::CreateSpriteRenderer()
{
return NULL;
}
Renderer3D* PlatformWin32NullRenderer::CreateRenderer3D()
{
return NULL;
}
class InputManager* PlatformWin32NullRenderer::CreateInputManager()
{
return NULL;
}
#if 0
class Mesh* PlatformWin32NullRenderer::CreateMesh()
{
return NULL;
}
class Texture* PlatformWin32NullRenderer::CreateTexture(const ImageData& image_data) const
{
return NULL;
}
File* PlatformWin32NullRenderer::CreateFile() const
{
return new gef::FileWin32();
}
AudioManager* PlatformWin32NullRenderer::CreateAudioManager() const
{
return NULL;
}
// TouchInputManager* PlatformWin32NullRenderer::CreateTouchInputManager() const
// {
// return NULL;
// }
RenderTarget* PlatformWin32NullRenderer::CreateRenderTarget(const Int32 width, const Int32 height) const
{
return NULL;
}
class VertexBuffer* PlatformWin32NullRenderer::CreateVertexBuffer() const
{
return NULL;
}
class IndexBuffer* PlatformWin32NullRenderer::CreateIndexBuffer() const
{
return NULL;
}
class ShaderInterface* PlatformWin32NullRenderer::CreateShaderInterface() const
{
return NULL;
}
DepthBuffer* PlatformWin32NullRenderer::CreateDepthBuffer(UInt32 width, UInt32 height) const
{
return NULL;
}
#endif
} | 20.524691 | 198 | 0.774135 | [
"mesh"
] |
7ad8fee5dc6174dceb4b5371ddac32079602414d | 1,858 | cpp | C++ | DP/NQueens/NQueens.cpp | yijingbai/LeetCode | 6ae6dbdf3a720b4206323401a0ed16ac2066031e | [
"MIT"
] | 2 | 2015-08-28T03:52:05.000Z | 2015-09-03T09:54:40.000Z | DP/NQueens/NQueens.cpp | yijingbai/LeetCode | 6ae6dbdf3a720b4206323401a0ed16ac2066031e | [
"MIT"
] | null | null | null | DP/NQueens/NQueens.cpp | yijingbai/LeetCode | 6ae6dbdf3a720b4206323401a0ed16ac2066031e | [
"MIT"
] | null | null | null | // Source : https://leetcode.com/problems/n-queens/
// Author : Yijing Bai
// Date : 2016-03-30
/**********************************************************************************
*
* The n-queens puzzle is the problem of placing n queens on an n×n chessboard such
* that no two queens attack each other.
*
* Given an integer n, return all distinct solutions to the n-queens puzzle.
*
* Each solution contains a distinct board configuration of the n-queens' placement,
* where 'Q' and '.' both indicate a queen and an empty space respectively.
*
* For example,
* There exist two distinct solutions to the 4-queens puzzle:
*
* [
* [".Q..", // Solution 1
* "...Q",
* "Q...",
* "..Q."],
*
* ["..Q.", // Solution 2
* "Q...",
* "...Q",
* ".Q.."]
* ]
*
*
*
*
*
*
*
*
**********************************************************************************/
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> res;
vector<string> nQueens(n, string(n, '.'));
vector<int> flag(5 * n - 2, 1);
solveNQueens(res, nQueens, flag, 0, n);
return res;
}
private:
void solveNQueens(vector<vector<string>> &res, vector<string> &nQueens, vector<int>& flag, int row, int &n) {
if (row == n) {
res.push_back(nQueens);
return;
}
for (int col = 0; col != n; ++col) {
if (flag[col] && flag[n + row + col] && flag[4 * n - 2 + col - row]) {
flag[col] = flag[n + row + col] = flag[4 * n - 2 + col - row] = 0;
nQueens[row][col] = 'Q';
solveNQueens(res, nQueens, flag, row + 1, n);
nQueens[row][col] = '.';
flag[col] = flag[n + row + col] = flag[4 * n - 2 + col - row] = 1;
}
}
}
};
| 27.731343 | 113 | 0.466631 | [
"vector"
] |
7ade102d98f7302a21595b2f6633fe6ae40cf1d8 | 4,305 | cpp | C++ | src/stubgenerator/stubgenerator.cpp | asphaltpanthers/libjson-rpc-cpp | cff57ced952e5ff6f86da02fe59c1e2d02f1493f | [
"MIT"
] | 1 | 2019-05-06T06:58:00.000Z | 2019-05-06T06:58:00.000Z | src/bitcoin/stubgenerator/stubgenerator.cpp | mmgrant73/bitcoinapi | a7886ea4315852a457efed6e6f44d0b65a8993d6 | [
"MIT"
] | null | null | null | src/bitcoin/stubgenerator/stubgenerator.cpp | mmgrant73/bitcoinapi | a7886ea4315852a457efed6e6f44d0b65a8993d6 | [
"MIT"
] | 1 | 2021-07-14T14:18:22.000Z | 2021-07-14T14:18:22.000Z | /*************************************************************************
* libjson-rpc-cpp
*************************************************************************
* @file stubgenerator.cpp
* @date 01.05.2013
* @author Peter Spiess-Knafl <peter.knafl@gmail.com>
* @license See attached LICENSE.txt
************************************************************************/
#include <fstream>
#include <algorithm>
#include <jsonrpc/specificationparser.h>
#include "stubgenerator.h"
using namespace std;
using namespace jsonrpc;
StubGenerator::StubGenerator(const string &stubname, const string &filename) :
stubname(stubname)
{
this->procedures = SpecificationParser::GetProceduresFromFile(filename);
}
StubGenerator::~StubGenerator()
{
delete this->procedures;
}
void StubGenerator::replaceAll(string &text, const string &fnd, const string &rep)
{
size_t pos = text.find(fnd);
while (pos != string::npos)
{
text.replace(pos, fnd.length(), rep);
pos = text.find(fnd, pos + rep.length());
}
}
std::string StubGenerator::generateStubToFile(const string &path)
{
ofstream stream;
string filename = this->stubname + ".h";
string completepath;
std::transform(filename.begin(), filename.end(), filename.begin(), ::tolower);
if (path.at(path.size()-1) == '/')
{
completepath = path + filename;
}
else
{
completepath = path + "/" + filename;
}
stream.open(completepath.c_str(), ios_base::out);
stream << this->generateStub();
stream.close();
return completepath;
}
string StubGenerator::getStubName()
{
return this->stubname;
}
string StubGenerator::toCppType(jsontype_t type, bool isConst, bool isReference)
{
string result;
switch(type)
{
case JSON_BOOLEAN:
result = "bool";
break;
case JSON_INTEGER:
result = "int";
break;
case JSON_REAL:
result = "double";
break;
case JSON_STRING:
result = "std::string";
break;
default:
result = "Json::Value";
break;
}
if(isConst)
{
result = "const " + result;
}
if(isReference)
{
result = result + "&";
}
return result;
}
string StubGenerator::toCppConversion(jsontype_t type)
{
string result;
switch(type)
{
case JSON_BOOLEAN:
result = ".asBool()";
break;
case JSON_INTEGER:
result = ".asInt()";
break;
case JSON_REAL:
result = ".asDouble()";
break;
case JSON_STRING:
result = ".asString()";
break;
default:
result = "";
break;
}
return result;
}
string StubGenerator::toString(jsontype_t type)
{
string result;
switch(type)
{
case JSON_BOOLEAN:
result = "jsonrpc::JSON_BOOLEAN";
break;
case JSON_INTEGER:
result = "jsonrpc::JSON_INTEGER";
break;
case JSON_REAL:
result = "jsonrpc::JSON_REAL";
break;
case JSON_STRING:
result = "jsonrpc::JSON_STRING";
break;
case JSON_OBJECT:
result = "jsonrpc::JSON_OBJECT";
break;
case JSON_ARRAY:
result = "jsonrpc::JSON_ARRAY";
break;
case JSON_NULL:
result = "jsonrpc::JSON_NULL";
}
return result;
}
string StubGenerator::generateParameterDeclarationList(Procedure &proc)
{
stringstream param_string;
parameterNameList_t list = proc.GetParameters();
for (parameterNameList_t::iterator it = list.begin(); it != list.end();)
{
param_string << toCppType(it->second, true, true) << " " << it->first;
if (++it != list.end())
{
param_string << ", ";
}
}
return param_string.str();
}
string StubGenerator::normalizeString(const string &text)
{
string result = text;
for(unsigned int i=0; i < text.length(); i++)
{
if (!((text[i] >= 'a' && text[i] <= 'z') || (text[i] >= 'A' && text[i] <= 'Z')))
{
result[i] = '_';
}
}
return result;
}
| 24.322034 | 88 | 0.527062 | [
"transform"
] |
7ae80d1dfa4bc3005bef235673553efb15ba2335 | 2,264 | cpp | C++ | aws-cpp-sdk-iotwireless/source/IoTWirelessErrors.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-iotwireless/source/IoTWirelessErrors.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-iotwireless/source/IoTWirelessErrors.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/core/client/AWSError.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/iotwireless/IoTWirelessErrors.h>
#include <aws/iotwireless/model/ConflictException.h>
#include <aws/iotwireless/model/ResourceNotFoundException.h>
#include <aws/iotwireless/model/TooManyTagsException.h>
using namespace Aws::Client;
using namespace Aws::Utils;
using namespace Aws::IoTWireless;
using namespace Aws::IoTWireless::Model;
namespace Aws
{
namespace IoTWireless
{
template<> AWS_IOTWIRELESS_API ConflictException IoTWirelessError::GetModeledError()
{
assert(this->GetErrorType() == IoTWirelessErrors::CONFLICT);
return ConflictException(this->GetJsonPayload().View());
}
template<> AWS_IOTWIRELESS_API ResourceNotFoundException IoTWirelessError::GetModeledError()
{
assert(this->GetErrorType() == IoTWirelessErrors::RESOURCE_NOT_FOUND);
return ResourceNotFoundException(this->GetJsonPayload().View());
}
template<> AWS_IOTWIRELESS_API TooManyTagsException IoTWirelessError::GetModeledError()
{
assert(this->GetErrorType() == IoTWirelessErrors::TOO_MANY_TAGS);
return TooManyTagsException(this->GetJsonPayload().View());
}
namespace IoTWirelessErrorMapper
{
static const int CONFLICT_HASH = HashingUtils::HashString("ConflictException");
static const int INTERNAL_SERVER_HASH = HashingUtils::HashString("InternalServerException");
static const int TOO_MANY_TAGS_HASH = HashingUtils::HashString("TooManyTagsException");
AWSError<CoreErrors> GetErrorForName(const char* errorName)
{
int hashCode = HashingUtils::HashString(errorName);
if (hashCode == CONFLICT_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(IoTWirelessErrors::CONFLICT), false);
}
else if (hashCode == INTERNAL_SERVER_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(IoTWirelessErrors::INTERNAL_SERVER), false);
}
else if (hashCode == TOO_MANY_TAGS_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(IoTWirelessErrors::TOO_MANY_TAGS), false);
}
return AWSError<CoreErrors>(CoreErrors::UNKNOWN, false);
}
} // namespace IoTWirelessErrorMapper
} // namespace IoTWireless
} // namespace Aws
| 32.342857 | 100 | 0.785777 | [
"model"
] |
7aeea888089bb14c57aebd69f975bd6a47290703 | 2,853 | cpp | C++ | Samples/ContactCards/cpp/Scenario1_Mini.xaml.cpp | dujianxin/Windows-universal-samples | d4e95ff0ac408c5d4d980bb18d53fb2c6556a273 | [
"MIT"
] | 2,504 | 2019-05-07T06:56:42.000Z | 2022-03-31T19:37:59.000Z | Samples/ContactCards/cpp/Scenario1_Mini.xaml.cpp | dujianxin/Windows-universal-samples | d4e95ff0ac408c5d4d980bb18d53fb2c6556a273 | [
"MIT"
] | 314 | 2019-05-08T16:56:30.000Z | 2022-03-21T07:13:45.000Z | Samples/ContactCards/cpp/Scenario1_Mini.xaml.cpp | dujianxin/Windows-universal-samples | d4e95ff0ac408c5d4d980bb18d53fb2c6556a273 | [
"MIT"
] | 2,219 | 2019-05-07T00:47:26.000Z | 2022-03-30T21:12:31.000Z | //*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// 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 "Scenario1_Mini.xaml.h"
using namespace SDKTemplate;
using namespace Platform;
using namespace Windows::ApplicationModel::Contacts;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Popups;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Input;
Scenario1_Mini::Scenario1_Mini()
{
InitializeComponent();
}
void Scenario1_Mini::OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e)
{
if (!ContactManager::IsShowContactCardSupported())
{
NotSupportedWarning->Visibility = Windows::UI::Xaml::Visibility::Visible;
}
}
void Scenario1_Mini::ShowContactCard_Click(Platform::Object^ sender, RoutedEventArgs^ e)
{
Contact^ contact = rootPage->CreateContactFromUserInput(EmailAddress, PhoneNumber);
if (contact != nullptr)
{
// Show the contact card next to the button.
Rect rect = MainPage::GetElementRect(safe_cast<FrameworkElement^>(sender));
// Show with default placement.
ContactManager::ShowContactCard(contact, rect);
}
}
void Scenario1_Mini::ShowContactCardWithPlacement_Click(Platform::Object^ sender, RoutedEventArgs^ e)
{
Contact^ contact = rootPage->CreateContactFromUserInput(EmailAddress, PhoneNumber);
if (contact != nullptr)
{
// Show the contact card next to the button.
Rect rect = MainPage::GetElementRect(safe_cast<FrameworkElement^>(sender));
// Show with preferred placement to the right.
ContactManager::ShowContactCard(contact, rect, Placement::Right);
}
}
void Scenario1_Mini::ShowContactCardWithOptions_Click(Platform::Object^ sender, RoutedEventArgs^ e)
{
Contact^ contact = rootPage->CreateContactFromUserInput(EmailAddress, PhoneNumber);
if (contact != nullptr)
{
// Show the contact card next to the button.
Rect rect = MainPage::GetElementRect(safe_cast<FrameworkElement^>(sender));
// Ask for the initial tab to be Phone.
ContactCardOptions^ options = ref new ContactCardOptions();
options->InitialTabKind = ContactCardTabKind::Phone;
// Show with default placement.
ContactManager::ShowContactCard(contact, rect, Placement::Default);
}
}
| 35.6625 | 102 | 0.67578 | [
"object"
] |
7af30174ba31f91bf49aecb8f3817e4946b2520f | 1,717 | hpp | C++ | include/scran/differential_analysis/delta_detected.hpp | LTLA/libscran | 12faf62c42c388f26db3b03d322c5f430e2c5080 | [
"MIT"
] | 4 | 2021-06-16T10:08:04.000Z | 2022-02-23T14:03:41.000Z | include/scran/differential_analysis/delta_detected.hpp | LTLA/libscran | 12faf62c42c388f26db3b03d322c5f430e2c5080 | [
"MIT"
] | 3 | 2021-10-16T23:14:47.000Z | 2021-12-23T07:51:54.000Z | include/scran/differential_analysis/delta_detected.hpp | LTLA/libscran | 12faf62c42c388f26db3b03d322c5f430e2c5080 | [
"MIT"
] | null | null | null | #ifndef SCRAN_DELTA_DETECTED_HPP
#define SCRAN_DELTA_DETECTED_HPP
#include <vector>
#include <limits>
namespace scran {
namespace differential_analysis {
template<typename Count, typename Stat, typename Ls>
void compute_pairwise_delta_detected (const Count* detected, const Ls& level_size, int ngroups, int nblocks, Stat* output) {
for (int g1 = 0; g1 < ngroups; ++g1) {
for (int g2 = 0; g2 < g1; ++g2) {
double total_weight = 0;
Stat& total_d1 = output[g1 * ngroups + g2];
total_d1 = 0;
for (int b = 0; b < nblocks; ++b) {
int offset1 = g1 * nblocks + b;
const auto& left_detected = detected[offset1];
const auto& left_size = level_size[offset1];
if (!left_size) {
continue;
}
int offset2 = g2 * nblocks + b;
const auto& right_detected = detected[offset2];
const auto& right_size = level_size[offset2];
if (!right_size) {
continue;
}
double weight = left_size * right_size;
total_weight += weight;
total_d1 += (static_cast<double>(left_detected)/left_size - static_cast<double>(right_detected)/right_size) * weight;
}
Stat& total_d2 = output[g2 * ngroups + g1];
if (total_weight) {
total_d1 /= total_weight;
total_d2 = -total_d1;
} else {
total_d1 = std::numeric_limits<Stat>::quiet_NaN();
total_d2 = std::numeric_limits<Stat>::quiet_NaN();
}
}
}
}
}
}
#endif
| 30.660714 | 133 | 0.532324 | [
"vector"
] |
7af4026178cd5c65a74eeda9bd45741a5d75a1f2 | 120 | cpp | C++ | src/handlers/ObjectHandler.cpp | GoldenbergDaniel/SFMLTemplate | d92806f406a13e02fc4de468921ac8adb2cc4da6 | [
"MIT"
] | null | null | null | src/handlers/ObjectHandler.cpp | GoldenbergDaniel/SFMLTemplate | d92806f406a13e02fc4de468921ac8adb2cc4da6 | [
"MIT"
] | null | null | null | src/handlers/ObjectHandler.cpp | GoldenbergDaniel/SFMLTemplate | d92806f406a13e02fc4de468921ac8adb2cc4da6 | [
"MIT"
] | null | null | null |
#include "../Globals.h"
#include "../content/Object.h"
#include "ObjectHandler.h"
// vector<Object> ObjectHandler::;
| 15 | 34 | 0.683333 | [
"object",
"vector"
] |
bb04c54f14099e0cd74a7933a62f8c7f8b2a2436 | 6,109 | cpp | C++ | 3rdparty/webkit/Source/JavaScriptCore/heap/CompleteSubspace.cpp | mchiasson/PhaserNative | f867454602c395484bf730a7c43b9c586c102ac2 | [
"MIT"
] | null | null | null | 3rdparty/webkit/Source/JavaScriptCore/heap/CompleteSubspace.cpp | mchiasson/PhaserNative | f867454602c395484bf730a7c43b9c586c102ac2 | [
"MIT"
] | null | null | null | 3rdparty/webkit/Source/JavaScriptCore/heap/CompleteSubspace.cpp | mchiasson/PhaserNative | f867454602c395484bf730a7c43b9c586c102ac2 | [
"MIT"
] | 1 | 2019-01-25T13:55:25.000Z | 2019-01-25T13:55:25.000Z | /*
* Copyright (C) 2017-2018 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "Subspace.h"
#include "AlignedMemoryAllocator.h"
#include "AllocatorInlines.h"
#include "BlockDirectoryInlines.h"
#include "JSCInlines.h"
#include "LocalAllocatorInlines.h"
#include "MarkedBlockInlines.h"
#include "PreventCollectionScope.h"
#include "SubspaceInlines.h"
#include "ThreadLocalCacheInlines.h"
namespace JSC {
CompleteSubspace::CompleteSubspace(CString name, Heap& heap, HeapCellType* heapCellType, AlignedMemoryAllocator* alignedMemoryAllocator)
: Subspace(name, heap)
{
initialize(heapCellType, alignedMemoryAllocator);
}
CompleteSubspace::~CompleteSubspace()
{
}
Allocator CompleteSubspace::allocatorFor(size_t size, AllocatorForMode mode)
{
return allocatorForNonVirtual(size, mode);
}
void* CompleteSubspace::allocate(VM& vm, size_t size, GCDeferralContext* deferralContext, AllocationFailureMode failureMode)
{
return allocateNonVirtual(vm, size, deferralContext, failureMode);
}
void* CompleteSubspace::allocateNonVirtual(VM& vm, size_t size, GCDeferralContext* deferralContext, AllocationFailureMode failureMode)
{
Allocator allocator = allocatorForNonVirtual(size, AllocatorForMode::AllocatorIfExists);
return allocator.tryAllocate(
vm, deferralContext, failureMode,
[&] () {
return allocateSlow(vm, size, deferralContext, failureMode);
});
}
Allocator CompleteSubspace::allocatorForSlow(size_t size)
{
size_t index = MarkedSpace::sizeClassToIndex(size);
size_t sizeClass = MarkedSpace::s_sizeClassForSizeStep[index];
if (!sizeClass)
return Allocator();
// This is written in such a way that it's OK for the JIT threads to end up here if they want
// to generate code that uses some allocator that hadn't been used yet. Note that a possibly-
// just-as-good solution would be to return null if we're in the JIT since the JIT treats null
// allocator as "please always take the slow path". But, that could lead to performance
// surprises and the algorithm here is pretty easy. Only this code has to hold the lock, to
// prevent simultaneously BlockDirectory creations from multiple threads. This code ensures
// that any "forEachAllocator" traversals will only see this allocator after it's initialized
// enough: it will have
auto locker = holdLock(m_space.directoryLock());
if (Allocator allocator = m_allocatorForSizeStep[index])
return allocator;
if (false)
dataLog("Creating marked allocator for ", m_name, ", ", m_attributes, ", ", sizeClass, ".\n");
std::unique_ptr<BlockDirectory> uniqueDirectory =
std::make_unique<BlockDirectory>(m_space.heap(), sizeClass);
BlockDirectory* directory = uniqueDirectory.get();
m_directories.append(WTFMove(uniqueDirectory));
directory->setSubspace(this);
m_space.addBlockDirectory(locker, directory);
index = MarkedSpace::sizeClassToIndex(sizeClass);
for (;;) {
if (MarkedSpace::s_sizeClassForSizeStep[index] != sizeClass)
break;
m_allocatorForSizeStep[index] = directory->allocator();
if (!index--)
break;
}
directory->setNextDirectoryInSubspace(m_firstDirectory);
m_alignedMemoryAllocator->registerDirectory(directory);
WTF::storeStoreFence();
m_firstDirectory = directory;
return directory->allocator();
}
void* CompleteSubspace::allocateSlow(VM& vm, size_t size, GCDeferralContext* deferralContext, AllocationFailureMode failureMode)
{
void* result = tryAllocateSlow(vm, size, deferralContext);
if (failureMode == AllocationFailureMode::Assert)
RELEASE_ASSERT(result);
return result;
}
void* CompleteSubspace::tryAllocateSlow(VM& vm, size_t size, GCDeferralContext* deferralContext)
{
sanitizeStackForVM(&vm);
if (Allocator allocator = allocatorFor(size, AllocatorForMode::EnsureAllocator))
return allocator.allocate(vm, deferralContext, AllocationFailureMode::ReturnNull);
if (size <= Options::largeAllocationCutoff()
&& size <= MarkedSpace::largeCutoff) {
dataLog("FATAL: attampting to allocate small object using large allocation.\n");
dataLog("Requested allocation size: ", size, "\n");
RELEASE_ASSERT_NOT_REACHED();
}
vm.heap.collectIfNecessaryOrDefer(deferralContext);
size = WTF::roundUpToMultipleOf<MarkedSpace::sizeStep>(size);
LargeAllocation* allocation = LargeAllocation::tryCreate(vm.heap, size, this);
if (!allocation)
return nullptr;
m_space.m_largeAllocations.append(allocation);
vm.heap.didAllocate(size);
m_space.m_capacity += size;
m_largeAllocations.append(allocation);
return allocation->cell();
}
} // namespace JSC
| 39.412903 | 136 | 0.732689 | [
"object"
] |
bb051078ad3023053a6c89e020bf6a71fadf40c6 | 3,918 | cpp | C++ | src/graphics/Sprite.cpp | simiaosimis/I_See_Fit_SDL2 | 29015ee729ad409fe5c5ff5a2dc74e01b8470c8e | [
"MIT"
] | null | null | null | src/graphics/Sprite.cpp | simiaosimis/I_See_Fit_SDL2 | 29015ee729ad409fe5c5ff5a2dc74e01b8470c8e | [
"MIT"
] | null | null | null | src/graphics/Sprite.cpp | simiaosimis/I_See_Fit_SDL2 | 29015ee729ad409fe5c5ff5a2dc74e01b8470c8e | [
"MIT"
] | null | null | null | #include "graphics/Sprite.h"
#include "engine/Game.h"
#include "util/Logger.h"
#include "util/Assert.h"
namespace sdl2engine {
Sprite::Sprite(const std::string& path) :
m_sdl_texture{nullptr},
m_width{0},
m_height{0},
m_path{path}
{
LoadFrom(m_path);
SetBlendMode(SDL_BLENDMODE_BLEND);
SetAlpha(255);
ASSERT(m_width >= 0 , "Must be >= 0");
ASSERT(m_height >= 0, "Must be >= 0");
}
Sprite::~Sprite() {
if(m_sdl_texture != nullptr) {
SDL_DestroyTexture(m_sdl_texture);
m_sdl_texture = nullptr;
}
}
void Sprite::LoadFrom(const std::string& path) {
SDL_Surface* loadedSurface = IMG_Load(path.c_str());
if(loadedSurface != nullptr) {
m_sdl_texture = SurfaceToTexture(loadedSurface);
}
else {
log_error() << "Could not load surface from path." << IMG_GetError();
}
// Display error log if image wasn't loaded.
if(m_sdl_texture == nullptr) {
log_error() << "Sprite load failed: " << path;
}
}
void Sprite::Render(const double x, const double y, SDL_Rect* const clip,
const bool stretch, const double angle, SDL_Point* const center,
SDL_RendererFlip flip) {
// This is the destination SDL_Rect structure.
SDL_Rect renderQuad = {static_cast<int>(x), static_cast<int>(y), m_width, m_height};
if(clip != nullptr) {
renderQuad.w = clip->w;
renderQuad.h = clip->h;
}
else {
// Don't clip the sprite.
}
int logicalW = 0;
int logicalH = 0;
Game::Instance().GetRenderer()->LogicalSize(&logicalW, &logicalH);
SDL_Rect stretch_rectangle = {static_cast<int>(x), static_cast<int>(y), logicalW,
logicalH};
const int successfullRender = (!stretch) ?
SDL_RenderCopyEx(Game::Instance().GetRenderer()->SdlRenderer(), m_sdl_texture, clip,
&renderQuad, angle, center, flip) :
SDL_RenderCopyEx(Game::Instance().GetRenderer()->SdlRenderer(), m_sdl_texture, clip,
&stretch_rectangle, angle, center, flip);
if(successfullRender != 0) {
log_error() << "Failed to render sprite." << SDL_GetError();
}
}
int Sprite::Width() {
return m_width;
}
int Sprite::Height() {
return m_height;
}
void Sprite::SetWidth(int width) {
ASSERT(width >= 0, "Must be >= 0");
m_width = width;
}
void Sprite::SetHeight(int height) {
ASSERT(height >= 0, "Must be >= 0");
m_height = height;
}
SDL_Texture* Sprite::SurfaceToTexture(SDL_Surface* const surface) {
ASSERT(Game::Instance().GetRenderer()->SdlRenderer() != nullptr, "Window renderer should not be null!");
// The final texture.
SDL_Texture* newTexture = nullptr;
if(surface != nullptr) {
// Create texture from the surface pixels.
newTexture = SDL_CreateTextureFromSurface(
Game::Instance().GetRenderer()->SdlRenderer(), surface);
if(newTexture != nullptr) {
// Set the Sprites width and height, from the loaded surface.
m_width = surface->w;
m_height = surface->h;
}
else {
log_error() << "Could not create texture from surface." << SDL_GetError();
}
// Free the loaded surface.
SDL_FreeSurface(surface);
}
else {
log_warn() << "Trying to convert a null surface to a texture.";
}
return newTexture;
}
std::string Sprite::Path() {
return m_path;
}
double Sprite::Alpha() {
Uint8 alpha = 0;
const int rc = SDL_GetTextureAlphaMod(m_sdl_texture, &alpha);
if(rc != 0) {
log_error() << "Could not get alpha value from Sprite (" << m_path << "). " <<
SDL_GetError();
}
return static_cast<double>(alpha);
}
void Sprite::SetAlpha(int alpha) {
if(alpha < 0) {
alpha = 0;
}
else if(alpha > 255) {
alpha = 255;
}
const int rc = SDL_SetTextureAlphaMod(m_sdl_texture, alpha);
if(rc != 0) {
log_error() << "Could not set alpha value of Sprite (" << m_path << "). " <<
SDL_GetError();
}
}
void Sprite::SetBlendMode(SDL_BlendMode blend_mode) {
const int rc = SDL_SetTextureBlendMode(m_sdl_texture, blend_mode);
if(rc != 0) {
log_error() << "Could not set blend mode of Sprite (" << m_path << "). " <<
SDL_GetError();
}
}
} // namespace sdl2engine
| 23.745455 | 105 | 0.67611 | [
"render"
] |
bb0f6efff66364e9215bbd855fd35178b0f3d617 | 85,867 | cpp | C++ | src/MapLoopsBackToMeshLevelSetAndArc.cpp | anapupa/ReebHanTun | 679ba774b75f4f53c502cb79f69bc9061c009eb8 | [
"Unlicense"
] | null | null | null | src/MapLoopsBackToMeshLevelSetAndArc.cpp | anapupa/ReebHanTun | 679ba774b75f4f53c502cb79f69bc9061c009eb8 | [
"Unlicense"
] | null | null | null | src/MapLoopsBackToMeshLevelSetAndArc.cpp | anapupa/ReebHanTun | 679ba774b75f4f53c502cb79f69bc9061c009eb8 | [
"Unlicense"
] | null | null | null | /*
(c) 2012 Fengtao Fan
*/
#include "MapLoopsBackToMeshLevelSetAndArc.h"
#include <boost/unordered_map.hpp>
#include <boost/unordered_set.hpp>
void MapLoopsBackToMeshLevelSetAndArc::FindEdgeConnectingTwoVertices(const int src_x, const int dist_y, const int eid_y,
int &outEdge) {
int edge_u = 0;
int edge_v = 0;
int triangle_id = TriangleAdjacentToOneEdgesOneVertex(eid_y, src_x);
//
edge_u = (*inMeshPtr).vecTriangle[triangle_id].e01;
if ((*inMeshPtr).vecTriangle[triangle_id].e01 == eid_y)
edge_u = (*inMeshPtr).vecTriangle[triangle_id].e02;
//
edge_v = (*inMeshPtr).vecTriangle[triangle_id].e01 +
(*inMeshPtr).vecTriangle[triangle_id].e02 +
(*inMeshPtr).vecTriangle[triangle_id].e12 -
(eid_y + edge_u);
//
if ((*inMeshPtr).vecEdge[edge_u].v0 == dist_y ||
(*inMeshPtr).vecEdge[edge_u].v1 == dist_y) {
outEdge = edge_u;
} else {
outEdge = edge_v;
}
return;
}
void MapLoopsBackToMeshLevelSetAndArc::ComputeLevelCycle() {
// preq: level cycle pointType is initialized
// //////////////////////////
/*
The level set can be treated as a closed triangle strip
So one can trace the triangle strip
*/
/*
boost::unordered_set<int> triangleDegree;
std::vector<int> triangleOrder ;
for (unsigned int i = 0; i < _levelCyclePointTypePtr->size() - 1; i++)
{
int triangle_id = 0;
int edge_a = (*_levelCyclePointTypePtr)[i].first;
int edge_b = (*_levelCyclePointTypePtr)[i + 1].first;
//if (i == 0)
//{
// triangle_id = TriangleAdjacentToOneEdgesOneVertex(edge_b, edge_a);
//}
//else
//{
// if (i == _arcCyclePointTypePtr->size() - 2)
// {
// triangle_id = TriangleAdjacentToOneEdgesOneVertex(edge_a, edge_b);
// }
// else
// {
// triangle_id = TriangleAdjacentToTwoEdges(edge_a, edge_b);
// }
//}
//
triangle_id = TriangleAdjacentToTwoEdges(edge_a, edge_b);
//
boost::unordered_set<int>::iterator sIter = triangleDegree.find(triangle_id);
if (sIter == triangleDegree.end())
{
triangleDegree.insert(triangle_id);
triangleOrder.push_back(triangle_id);
}
else
{//
std::cout << "NOT a triangle trip" << std::endl;
exit(9);
}
//
}
//
_simpGraph triangleStripGraph;
boost::unordered_map<int, int> verToGraphNode;
boost::unordered_map<int, int>::iterator mIter;
int nGrapNodeCounter = 0;
for (unsigned int i = 0; i < triangleOrder.size(); i++)
{
int node[3] = { (*inMeshPtr).vecTriangle[triangleOrder[i]].v0,
(*inMeshPtr).vecTriangle[triangleOrder[i]].v1,
(*inMeshPtr).vecTriangle[triangleOrder[i]].v2};
int gNode[3] = {0};
for (int j = 0; j < 3; j++)
{
mIter = verToGraphNode.find(node[j]);
if (mIter == verToGraphNode.end())
{
triangleStripGraph.AddNode(nGrapNodeCounter, node[j]);
gNode[j] = nGrapNodeCounter;
verToGraphNode[node[j]] = nGrapNodeCounter;
nGrapNodeCounter++;
}
else
{
gNode[j] = mIter->second;
}
}
triangleStripGraph.AddEdge(gNode[0], gNode[1]); // since graph node use set to store adjacent list
triangleStripGraph.AddEdge(gNode[0], gNode[2]); // no need to check the edge exists or not
triangleStripGraph.AddEdge(gNode[1], gNode[2]);
}
//
for (unsigned int i = 0; i < _levelCyclePointTypePtr->size() - 1; i++)
{
int edge_idx = (*_levelCyclePointTypePtr)[i].first;
triangleStripGraph.RemoveEdge( verToGraphNode[(*inMeshPtr).vecEdge[edge_idx].v0], verToGraphNode[(*inMeshPtr).vecEdge[edge_idx].v1]);
}
//there exist two disjont two components
std::vector<bool> colors(triangleStripGraph.vecNode.size(), false);
std::vector<int> parents(triangleStripGraph.vecNode.size(), -1);
int components = 0;
int currentNode = -1;
int oppositeNode = -1;
for (unsigned int i = 0; i < colors.size(); i++)
{
if (!colors[i])
{// visit the components
std::queue<int> Q;
Q.push(i);
colors[i] = true;
parents[i] = -1;
while (!Q.empty())
{
int node = Q.front();
Q.pop();
for (std::set<int>::iterator sIter = triangleStripGraph.vecNode[node].adjList.begin();
sIter != triangleStripGraph.vecNode[node].adjList.end(); sIter++)
{
if (!colors[*sIter])
{
colors[*sIter] = true;
Q.push(*sIter);
parents[*sIter] = node;
}
else
{
if (parents[node] != *sIter)
{// non-tree edge
currentNode = node;
oppositeNode = *sIter;
}
}
}
}
components++;
}
}
if (components != 2)
{
std::cout << "wrong method again" << std::endl;
exit(4);
}
outLevelCycle_VertexOnMesh.reserve(triangleStripGraph.vecNode.size());
outLevelCycle_EdgeOnMesh.reserve(triangleStripGraph.vecNode.size());
//
//for (int i = 0; i < triangleStripGraph.vecNode.size(); i++)
//{
// if (parents[i] < 0 && triangleStripGraph.vecNode[i].adjList.size() > 1)
// {
// currentNode = i;
// break;
// }
//}
if (currentNode < 0 || oppositeNode < 0)
{
std::cout << "CANNOT find intial node for level cycle " << std::endl;
exit(4);
}
//for (std::set<int>::iterator sIter = triangleStripGraph.vecNode[currentNode].adjList.begin();
// sIter != triangleStripGraph.vecNode[currentNode].adjList.end(); sIter++)
//{
// if (currentNode != parents[*sIter])
// {
// oppositeNode = *sIter;
// break;
// }
//}
//
std::vector<int> leftPath;
int iterNode = currentNode;
while (iterNode >= 0)
{
leftPath.push_back(triangleStripGraph.vecNode[iterNode].color);
iterNode = parents[iterNode];
}
for (std::vector<int>::reverse_iterator rvIter = leftPath.rbegin();
rvIter != leftPath.rend(); rvIter++)
{
outLevelCycle_VertexOnMesh.push_back(*rvIter);
}
//
iterNode = oppositeNode;
while (iterNode >= 0)
{
outLevelCycle_VertexOnMesh.push_back(triangleStripGraph.vecNode[iterNode].color);
iterNode = parents[iterNode];
}
if (outLevelCycle_VertexOnMesh.back() != leftPath.back())
{
std::cout << "in different compoents" << std::endl;
exit(4);
}
//
for (unsigned int i = 0; i < outLevelCycle_VertexOnMesh.size() - 1; i++)
{
int curNode = outLevelCycle_VertexOnMesh[i];
int oppNode = outLevelCycle_VertexOnMesh[i + 1];
for (std::vector<int>::iterator vIter = (*inMeshPtr).vecVertex[curNode].adjEdges.begin();
vIter != (*inMeshPtr).vecVertex[curNode].adjEdges.end(); vIter++)
{
if ((*inMeshPtr).vecEdge[*vIter].v0 == oppNode ||
(*inMeshPtr).vecEdge[*vIter].v1 == oppNode)
{
outLevelCycle_EdgeOnMesh.push_back(*vIter);
break;
}
}
}
//
//
return;
*/
// // critical point
//std::set<int> processed_vertex;
//std::set<int>::iterator findIter;
//
int pot_vertex = 0;
int pot_edge_id = 0;
int current_edge_id = 0;
int current_active_vertex = 0;
int shared_vertex = 0;
/*
Initializing current active vertex
*/
if ((*_levelCyclePointTypePtr)[0].second) {// it is an edge
current_edge_id = (*_levelCyclePointTypePtr)[0].first;
current_active_vertex = (*inMeshPtr).vecEdge[current_edge_id].v0;
//
//processed_vertex.insert(current_active_vertex);
//
outLevelCycle_VertexOnMesh.push_back(current_active_vertex);
} else {// it is only a vertex
current_active_vertex = (*_levelCyclePointTypePtr)[0].first;
//
//processed_vertex.insert(current_active_vertex);
//
outLevelCycle_VertexOnMesh.push_back(current_active_vertex);
}
// boundary check is done YET !!!!!!!!!!!!!!!
for (unsigned int i = 1; i < _levelCyclePointTypePtr->size() - 1; i++) {
/*
Invariant : current_active_vertex is always on current edge if current array element is an edge
or it is the current vertex if current array element is a vertex
*/
if ((*_levelCyclePointTypePtr)[i].second) {// this is an edge type vertex
current_edge_id = (*_levelCyclePointTypePtr)[i].first;
if (inMeshPtr->vecEdge[current_edge_id].v0 != current_active_vertex &&
inMeshPtr->vecEdge[current_edge_id].v1 !=
current_active_vertex) {// if current active vertex is on this edge, then do nothing
// else add one more edge and update current_active_vertex
// since the levele set cross the edge only once, so there must exist at least one vertex on the edge not visited yet
if ((*_levelCyclePointTypePtr)[i - 1].second) {// previous one is an edge
shared_vertex = inMeshPtr->vecEdge[(*_levelCyclePointTypePtr)[i - 1].first].v0 +
inMeshPtr->vecEdge[(*_levelCyclePointTypePtr)[i - 1].first].v1 -
current_active_vertex;
pot_vertex = inMeshPtr->vecEdge[current_edge_id].v0;
if (shared_vertex == pot_vertex)
pot_vertex = inMeshPtr->vecEdge[current_edge_id].v1;
//
FindEdgeConnectingTwoVertices(current_active_vertex, pot_vertex, current_edge_id, pot_edge_id);
//
current_active_vertex = pot_vertex;
//
outLevelCycle_VertexOnMesh.push_back(current_active_vertex);
outLevelCycle_EdgeOnMesh.push_back(pot_edge_id);
//
//processed_vertex.insert(current_active_vertex);
} else {
std::cout << "error in levelset mapping, exist an vertex?" << std::endl;
exit(2);
}
}
} else {// it is a vertex
std::cout << "error in levelset mapping, exist an vertex?" << std::endl;
exit(2);
pot_vertex = (*_levelCyclePointTypePtr)[i].first;
// check if this vertex is there or not
// if it is there, ignore it
// otherwise, push it
//
pot_edge_id = -1;
//if (processed_vertex.find(pot_vertex) == processed_vertex.end())
{
for (std::vector<int>::iterator vIter = inMeshPtr->vecVertex[current_active_vertex].adjEdges.begin();
vIter != inMeshPtr->vecVertex[current_active_vertex].adjEdges.end(); vIter++) {
if (inMeshPtr->vecEdge[*vIter].v0 == pot_vertex ||
inMeshPtr->vecEdge[*vIter].v1 == pot_vertex) {
pot_edge_id = *vIter;
break;
}
}
if (pot_edge_id > -1) {
outLevelCycle_VertexOnMesh.push_back(pot_vertex);
outLevelCycle_EdgeOnMesh.push_back(pot_edge_id);
} else {
std::cout << "No edge connecting two vertices " << std::endl;
exit(0);
}
//
current_active_vertex = pot_vertex;
//
//processed_vertex.insert(current_active_vertex);
}
}// else it is a vertex
}
// Handle the boundary case
pot_vertex = outLevelCycle_VertexOnMesh.front();
if ((*_levelCyclePointTypePtr).back().second) {
if (pot_vertex != current_active_vertex) {
current_edge_id = (*_levelCyclePointTypePtr).back().first;
if (inMeshPtr->vecEdge[current_edge_id].v0 == current_active_vertex ||
inMeshPtr->vecEdge[current_edge_id].v1 == current_active_vertex) {
outLevelCycle_EdgeOnMesh.push_back(current_edge_id);
outLevelCycle_VertexOnMesh.push_back(pot_vertex);
} else {
FindEdgeConnectingTwoVertices(current_active_vertex, pot_vertex, current_edge_id, pot_edge_id);
//
outLevelCycle_EdgeOnMesh.push_back(pot_edge_id);
outLevelCycle_VertexOnMesh.push_back(pot_vertex);
}
}
} else {
std::cout << "error in levelset mapping, exist an vertex?" << std::endl;
exit(2);
pot_edge_id = -1;
for (std::vector<int>::iterator vIter = inMeshPtr->vecVertex[current_active_vertex].adjEdges.begin();
vIter != inMeshPtr->vecVertex[current_active_vertex].adjEdges.end(); vIter++) {
if (inMeshPtr->vecEdge[*vIter].v0 == pot_vertex ||
inMeshPtr->vecEdge[*vIter].v1 == pot_vertex) {
pot_edge_id = *vIter;
break;
}
}
if (pot_edge_id > -1) {
outLevelCycle_VertexOnMesh.push_back(pot_vertex);
outLevelCycle_EdgeOnMesh.push_back(pot_edge_id);
} else {
std::cout << "No edge connecting two vertices " << std::endl;
exit(0);
}
}
return;
//
//// Trace a vertex-edge path on the mesh which is homotopic to the input cycle on mesh
//// the second part is the pair to its parent and the edge connecting it to its parent
//std::map<int, std::pair<int,int>> processed_vertex;
//int current_edge_a = 0;
//int current_edge_b = 0;
//int current_edge_c = 0;
//int opposite_vertex = 0;
//int tracing_termination_pt = 0;
//int current_active_node = 0;
//if ((*_levelCyclePointTypePtr)[0].second)
//{// it is an edge
// current_edge_a = (*_levelCyclePointTypePtr)[0].first;
// tracing_termination_pt = (*inMeshPtr).vecEdge[current_edge_a].v0;
// processed_vertex[(*inMeshPtr).vecEdge[current_edge_a].v0] = std::pair<int,int>(-1, -1);
// processed_vertex[(*inMeshPtr).vecEdge[current_edge_a].v1] = std::pair<int,int>((*inMeshPtr).vecEdge[current_edge_a].v0, current_edge_a);
// current_active_node = (*inMeshPtr).vecEdge[current_edge_a].v1;
//}
//else
//{// it is only a vertex
// current_edge_a = (*_levelCyclePointTypePtr)[0].first;
// tracing_termination_pt = current_edge_a;
// processed_vertex[current_edge_a] = std::pair<int,int>(-1, -1);
// current_active_node = current_edge_a;
//}
//////////////////////////////
//for (unsigned int i = 0; i < _levelCyclePointTypePtr->size() - 2; i++)
//{
// // find triangle conntaining the edge [i, i+1]
// int triangle_or_edge_id = 0;
// if ((*_levelCyclePointTypePtr)[i].second)
// {
// if ((*_levelCyclePointTypePtr)[i+1].second)
// {// both points are on edges
// // there exists an triangle containing them
// current_edge_a = (*_levelCyclePointTypePtr)[i].first;
// current_edge_b = (*_levelCyclePointTypePtr)[i+1].first;
// triangle_or_edge_id = TriangleAdjacentToTwoEdges(current_edge_a, current_edge_b);
// opposite_vertex = (*inMeshPtr).vecTriangle[triangle_or_edge_id].v0 +
// (*inMeshPtr).vecTriangle[triangle_or_edge_id].v1 +
// (*inMeshPtr).vecTriangle[triangle_or_edge_id].v2 -
// ((*inMeshPtr).vecEdge[current_edge_a].v0 + (*inMeshPtr).vecEdge[current_edge_a].v1);
// //
// current_edge_c = (*inMeshPtr).vecTriangle[triangle_or_edge_id].e01 +
// (*inMeshPtr).vecTriangle[triangle_or_edge_id].e02 +
// (*inMeshPtr).vecTriangle[triangle_or_edge_id].e12 -
// (current_edge_a + current_edge_b);
// //
// if (processed_vertex.find(opposite_vertex) == processed_vertex.end())
// {
// if ((*inMeshPtr).vecEdge[current_edge_b].v1 == current_active_node ||
// (*inMeshPtr).vecEdge[current_edge_b].v0 == current_active_node)
// {
// processed_vertex[opposite_vertex] = std::pair<int,int>(((*inMeshPtr).vecEdge[current_edge_b].v0 + (*inMeshPtr).vecEdge[current_edge_b].v1) - opposite_vertex, current_edge_b);
// }
// else
// {
// processed_vertex[opposite_vertex] = std::pair<int,int>(((*inMeshPtr).vecEdge[current_edge_c].v0 + (*inMeshPtr).vecEdge[current_edge_c].v1) - opposite_vertex, current_edge_c);
// }
// }
// if (opposite_vertex == tracing_termination_pt)
// {
// current_active_node = (*inMeshPtr).vecEdge[current_edge_b].v0;
// if ((*inMeshPtr).vecEdge[current_edge_b].v0 == tracing_termination_pt)
// current_active_node = (*inMeshPtr).vecEdge[current_edge_b].v1;
// }
// else
// {
// current_active_node = opposite_vertex;
// }
//
// }
// else
// {// first is on edge , the second is a vertex
// opposite_vertex = (*_levelCyclePointTypePtr)[i+1].first;
// if (processed_vertex.find(opposite_vertex) == processed_vertex.end())
// {
// current_edge_a = (*_levelCyclePointTypePtr)[i].first;
// FindEdgeConnectingTwoVertices(opposite_vertex, current_active_node, current_edge_a, current_edge_c);
// processed_vertex[opposite_vertex] = std::pair<int, int>( current_active_node, current_edge_c);
//
// }
// current_active_node = opposite_vertex;
// }
// }
// else
// {
// if((*_levelCyclePointTypePtr)[i+1].second)
// {//
// opposite_vertex = (*_levelCyclePointTypePtr)[i].first;
// current_edge_c = (*_levelCyclePointTypePtr)[i+1].first;
// //
// triangle_or_edge_id = TriangleAdjacentToOneEdgesOneVertex(current_edge_c, opposite_vertex);
// //
// current_edge_a = (*inMeshPtr).vecTriangle[triangle_or_edge_id].e01;
// if ((*inMeshPtr).vecTriangle[triangle_or_edge_id].e01 == current_edge_c)
// current_edge_a = (*inMeshPtr).vecTriangle[triangle_or_edge_id].e02;
// //
// current_edge_b = (*inMeshPtr).vecTriangle[triangle_or_edge_id].e01 +
// (*inMeshPtr).vecTriangle[triangle_or_edge_id].e02 +
// (*inMeshPtr).vecTriangle[triangle_or_edge_id].e12 -
// (current_edge_a + current_edge_c);
// //
// int pot_vertex = (*inMeshPtr).vecEdge[current_edge_a].v0 + (*inMeshPtr).vecEdge[current_edge_a].v1 - opposite_vertex;
// if (processed_vertex.find(pot_vertex) == processed_vertex.end())
// {
// processed_vertex[pot_vertex] = std::pair<int,int>(opposite_vertex, current_edge_a);
// }
// //
// pot_vertex = (*inMeshPtr).vecEdge[current_edge_b].v0 + (*inMeshPtr).vecEdge[current_edge_b].v1 - opposite_vertex;
// if (processed_vertex.find(pot_vertex) == processed_vertex.end())
// {
// processed_vertex[pot_vertex] = std::pair<int,int>(opposite_vertex, current_edge_b);
//
// }
// current_active_node = pot_vertex;
// }
// else
// {
// int src_node = (*_levelCyclePointTypePtr)[i].first;
// opposite_vertex = (*_levelCyclePointTypePtr)[i+1].first;
// if (processed_vertex.find(opposite_vertex) == processed_vertex.end())
// {
// for (std::vector<int>::iterator vIter = (*inMeshPtr).vecVertex[src_node].adjEdges.begin();
// vIter != (*inMeshPtr).vecVertex[src_node].adjEdges.begin();
// vIter++)
// {
// if ((*inMeshPtr).vecEdge[*vIter].v0 == opposite_vertex ||
// (*inMeshPtr).vecEdge[*vIter].v1 == opposite_vertex)
// {
// processed_vertex[opposite_vertex] = std::pair<int,int>(src_node, *vIter);
// break;
// }
// }
// }
// current_active_node = opposite_vertex;
// }
// }
//}
//// find the starting point for tracing the closed loop
//int starting_point = 0;
//int starting_edge = 0;
//if (_levelCyclePointTypePtr->back().second)
//{
// int triangle_id = 0;
// current_edge_a = (*_levelCyclePointTypePtr).back().first;
// if ((*_levelCyclePointTypePtr)[(*_levelCyclePointTypePtr).size() - 2].second)
// {
// current_edge_b = (*_levelCyclePointTypePtr)[(*_levelCyclePointTypePtr).size() - 2].first;
// triangle_id = TriangleAdjacentToTwoEdges(current_edge_a, current_edge_b);
// starting_point = (*inMeshPtr).vecTriangle[triangle_id].v0 +
// (*inMeshPtr).vecTriangle[triangle_id].v1 +
// (*inMeshPtr).vecTriangle[triangle_id].v2 -
// ((*inMeshPtr).vecEdge[current_edge_a].v0 + (*inMeshPtr).vecEdge[current_edge_a].v1);
// //
// FindEdgeConnectingTwoVertices(starting_point, tracing_termination_pt, current_edge_a, starting_edge);
// }
// else
// {
// starting_point = (*_levelCyclePointTypePtr)[(*_levelCyclePointTypePtr).size() - 2].first;
// FindEdgeConnectingTwoVertices(starting_point, tracing_termination_pt, current_edge_a, starting_edge);
// }
//}
//else
//{//
// if ((*_levelCyclePointTypePtr)[(*_levelCyclePointTypePtr).size() - 2].second)
// {
// current_edge_a = (*_levelCyclePointTypePtr)[(*_levelCyclePointTypePtr).size() - 2].first;
// starting_point = (*inMeshPtr).vecEdge[current_edge_a].v0;
// FindEdgeConnectingTwoVertices(tracing_termination_pt, starting_point, current_edge_a, starting_edge);
// }
// else
// {
// starting_point = (*_levelCyclePointTypePtr)[(*_levelCyclePointTypePtr).size() - 2].first;
// for (std::vector<int>::iterator vIter = (*inMeshPtr).vecVertex[starting_point].adjEdges.begin();
// vIter != (*inMeshPtr).vecVertex[starting_point].adjEdges.begin();
// vIter++)
// {
// if ((*inMeshPtr).vecEdge[*vIter].v0 == tracing_termination_pt ||
// (*inMeshPtr).vecEdge[*vIter].v1 == tracing_termination_pt)
// {
// starting_edge = *vIter;
// break;
// }
// }
// }
//}
////
//outLevelCycle_VertexOnMesh.push_back(tracing_termination_pt);
//outLevelCycle_VertexOnMesh.push_back(starting_point);
//outLevelCycle_EdgeOnMesh.push_back(starting_edge);
//int current_vertex = starting_point;
//std::pair<int, int> current_vertex_parents = processed_vertex[current_vertex];
//while (current_vertex_parents.first != -1)
//{
// outLevelCycle_VertexOnMesh.push_back(current_vertex_parents.first);
// outLevelCycle_EdgeOnMesh.push_back(current_vertex_parents.second);
// current_vertex_parents = processed_vertex[current_vertex_parents.first];
//}
////////////////////////////
//return;
}
//void MapLoopsBackToMeshLevelSetAndArc::ComputeLevelCycle()
//{
// // preq: both level cycle and arc cycle , point and pointType are initialized
//
// //
// // Trace a vertex-edge path on the mesh which is homotopic to the input cycle on mesh
// // the second part is the pair to its parent and the edge connecting it to its parent
// std::map<int, std::pair<int,int>> processed_vertex;
// int current_edge_a = 0;
// int current_edge_b = 0;
// int current_edge_c = 0;
// int opposite_vertex = 0;
// int tracing_termination_pt = 0;
// int current_active_node = 0;
// if ((*_levelCyclePointTypePtr)[0].second)
// {// it is an edge
// current_edge_a = (*_levelCyclePointTypePtr)[0].first;
// tracing_termination_pt = (*inMeshPtr).vecEdge[current_edge_a].v0;
// processed_vertex[(*inMeshPtr).vecEdge[current_edge_a].v0] = std::pair<int,int>(-1, -1);
// processed_vertex[(*inMeshPtr).vecEdge[current_edge_a].v1] = std::pair<int,int>((*inMeshPtr).vecEdge[current_edge_a].v0, current_edge_a);
// current_active_node = (*inMeshPtr).vecEdge[current_edge_a].v1;
// }
// else
// {// it is only a vertex
// current_edge_a = (*_levelCyclePointTypePtr)[0].first;
// tracing_termination_pt = current_edge_a;
// processed_vertex[current_edge_a] = std::pair<int,int>(-1, -1);
// current_active_node = current_edge_a;
// }
// ////////////////////////////
// for (unsigned int i = 0; i < _levelCyclePointTypePtr->size() - 2; i++)
// {
// // find triangle conntaining the edge [i, i+1]
// int triangle_or_edge_id = 0;
//
// if ((*_levelCyclePointTypePtr)[i].second)
// {
// if ((*_levelCyclePointTypePtr)[i+1].second)
// {// both points are on edges
// // there exists an triangle containing them
// current_edge_a = (*_levelCyclePointTypePtr)[i].first;
// current_edge_b = (*_levelCyclePointTypePtr)[i+1].first;
// triangle_or_edge_id = TriangleAdjacentToTwoEdges(current_edge_a, current_edge_b);
// opposite_vertex = (*inMeshPtr).vecTriangle[triangle_or_edge_id].v0 +
// (*inMeshPtr).vecTriangle[triangle_or_edge_id].v1 +
// (*inMeshPtr).vecTriangle[triangle_or_edge_id].v2 -
// ((*inMeshPtr).vecEdge[current_edge_a].v0 + (*inMeshPtr).vecEdge[current_edge_a].v1);
// //
// current_edge_c = (*inMeshPtr).vecTriangle[triangle_or_edge_id].e01 +
// (*inMeshPtr).vecTriangle[triangle_or_edge_id].e02 +
// (*inMeshPtr).vecTriangle[triangle_or_edge_id].e12 -
// (current_edge_a + current_edge_b);
// //
// if (processed_vertex.find(opposite_vertex) == processed_vertex.end())
// {
// if ((*inMeshPtr).vecEdge[current_edge_b].v1 == current_active_node ||
// (*inMeshPtr).vecEdge[current_edge_b].v0 == current_active_node)
// {
// processed_vertex[opposite_vertex] = std::pair<int,int>(((*inMeshPtr).vecEdge[current_edge_b].v0 + (*inMeshPtr).vecEdge[current_edge_b].v1) - opposite_vertex, current_edge_b);
// }
// else
// {
// processed_vertex[opposite_vertex] = std::pair<int,int>(((*inMeshPtr).vecEdge[current_edge_c].v0 + (*inMeshPtr).vecEdge[current_edge_c].v1) - opposite_vertex, current_edge_c);
// }
// }
// if (opposite_vertex == tracing_termination_pt)
// {
// current_active_node = (*inMeshPtr).vecEdge[current_edge_b].v0;
// if ((*inMeshPtr).vecEdge[current_edge_b].v0 == tracing_termination_pt)
// current_active_node = (*inMeshPtr).vecEdge[current_edge_b].v1;
// }
// else
// {
// current_active_node = opposite_vertex;
// }
//
//
// }
// else
// {// first is on edge , the second is a vertex
// opposite_vertex = (*_levelCyclePointTypePtr)[i+1].first;
// if (processed_vertex.find(opposite_vertex) == processed_vertex.end())
// {
// current_edge_a = (*_levelCyclePointTypePtr)[i].first;
// FindEdgeConnectingTwoVertices(opposite_vertex, current_active_node, current_edge_a, current_edge_c);
// processed_vertex[opposite_vertex] = std::pair<int, int>( current_active_node, current_edge_c);
//
// }
// current_active_node = opposite_vertex;
// }
// }
// else
// {
// if((*_levelCyclePointTypePtr)[i+1].second)
// {//
// opposite_vertex = (*_levelCyclePointTypePtr)[i].first;
// current_edge_c = (*_levelCyclePointTypePtr)[i+1].first;
// //
// triangle_or_edge_id = TriangleAdjacentToOneEdgesOneVertex(current_edge_c, opposite_vertex);
// //
// current_edge_a = (*inMeshPtr).vecTriangle[triangle_or_edge_id].e01;
// if ((*inMeshPtr).vecTriangle[triangle_or_edge_id].e01 == current_edge_c)
// current_edge_a = (*inMeshPtr).vecTriangle[triangle_or_edge_id].e02;
// //
// current_edge_b = (*inMeshPtr).vecTriangle[triangle_or_edge_id].e01 +
// (*inMeshPtr).vecTriangle[triangle_or_edge_id].e02 +
// (*inMeshPtr).vecTriangle[triangle_or_edge_id].e12 -
// (current_edge_a + current_edge_c);
// //
// int pot_vertex = (*inMeshPtr).vecEdge[current_edge_a].v0 + (*inMeshPtr).vecEdge[current_edge_a].v1 - opposite_vertex;
// if (processed_vertex.find(pot_vertex) == processed_vertex.end())
// {
// processed_vertex[pot_vertex] = std::pair<int,int>(opposite_vertex, current_edge_a);
// }
// //
// pot_vertex = (*inMeshPtr).vecEdge[current_edge_b].v0 + (*inMeshPtr).vecEdge[current_edge_b].v1 - opposite_vertex;
// if (processed_vertex.find(pot_vertex) == processed_vertex.end())
// {
// processed_vertex[pot_vertex] = std::pair<int,int>(opposite_vertex, current_edge_b);
//
// }
// current_active_node = pot_vertex;
// }
// else
// {
// int src_node = (*_levelCyclePointTypePtr)[i].first;
// opposite_vertex = (*_levelCyclePointTypePtr)[i+1].first;
// if (processed_vertex.find(opposite_vertex) == processed_vertex.end())
// {
// for (std::vector<int>::iterator vIter = (*inMeshPtr).vecVertex[src_node].adjEdges.begin();
// vIter != (*inMeshPtr).vecVertex[src_node].adjEdges.begin();
// vIter++)
// {
// if ((*inMeshPtr).vecEdge[*vIter].v0 == opposite_vertex ||
// (*inMeshPtr).vecEdge[*vIter].v1 == opposite_vertex)
// {
// processed_vertex[opposite_vertex] = std::pair<int,int>(src_node, *vIter);
// break;
// }
// }
// }
// current_active_node = opposite_vertex;
// }
// }
//
// }
// // find the starting point for tracing the closed loop
// int starting_point = 0;
// int starting_edge = 0;
// if (_levelCyclePointTypePtr->back().second)
// {
// int triangle_id = 0;
// current_edge_a = (*_levelCyclePointTypePtr).back().first;
// if ((*_levelCyclePointTypePtr)[(*_levelCyclePointTypePtr).size() - 2].second)
// {
// current_edge_b = (*_levelCyclePointTypePtr)[(*_levelCyclePointTypePtr).size() - 2].first;
// triangle_id = TriangleAdjacentToTwoEdges(current_edge_a, current_edge_b);
// starting_point = (*inMeshPtr).vecTriangle[triangle_id].v0 +
// (*inMeshPtr).vecTriangle[triangle_id].v1 +
// (*inMeshPtr).vecTriangle[triangle_id].v2 -
// ((*inMeshPtr).vecEdge[current_edge_a].v0 + (*inMeshPtr).vecEdge[current_edge_a].v1);
// //
// FindEdgeConnectingTwoVertices(starting_point, tracing_termination_pt, current_edge_a, starting_edge);
// }
// else
// {
// starting_point = (*_levelCyclePointTypePtr)[(*_levelCyclePointTypePtr).size() - 2].first;
// FindEdgeConnectingTwoVertices(starting_point, tracing_termination_pt, current_edge_a, starting_edge);
// }
// }
// else
// {//
// if ((*_levelCyclePointTypePtr)[(*_levelCyclePointTypePtr).size() - 2].second)
// {
// current_edge_a = (*_levelCyclePointTypePtr)[(*_levelCyclePointTypePtr).size() - 2].first;
// starting_point = (*inMeshPtr).vecEdge[current_edge_a].v0;
// FindEdgeConnectingTwoVertices(tracing_termination_pt, starting_point, current_edge_a, starting_edge);
// }
// else
// {
// starting_point = (*_levelCyclePointTypePtr)[(*_levelCyclePointTypePtr).size() - 2].first;
// for (std::vector<int>::iterator vIter = (*inMeshPtr).vecVertex[starting_point].adjEdges.begin();
// vIter != (*inMeshPtr).vecVertex[starting_point].adjEdges.begin();
// vIter++)
// {
// if ((*inMeshPtr).vecEdge[*vIter].v0 == tracing_termination_pt ||
// (*inMeshPtr).vecEdge[*vIter].v1 == tracing_termination_pt)
// {
// starting_edge = *vIter;
// break;
// }
// }
// }
// }
// //
// outLevelCycle_VertexOnMesh.push_back(tracing_termination_pt);
// outLevelCycle_VertexOnMesh.push_back(starting_point);
// outLevelCycle_EdgeOnMesh.push_back(starting_edge);
// int current_vertex = starting_point;
// std::pair<int, int> current_vertex_parents = processed_vertex[current_vertex];
// while (current_vertex_parents.first != -1)
// {
// outLevelCycle_VertexOnMesh.push_back(current_vertex_parents.first);
// outLevelCycle_EdgeOnMesh.push_back(current_vertex_parents.second);
// current_vertex_parents = processed_vertex[current_vertex_parents.first];
// }
// //////////////////////////
// // critical point
// //int crit_vertex_a = _arcCyclePointTypePtr->front().first;
// //int crit_vertex_b = _arcCyclePointTypePtr->back().first;
// //std::set<int> processed_vertex;
// //std::set<int>::iterator findIter;
// ////
// //int pot_vertex = 0;
// //// boundary check is done YET !!!!!!!!!!!!!!!
// //for (unsigned int i = 0; i < _levelCyclePointTypePtr->size() - 1; i++)
// //{
// //
// // if ((*_levelCyclePointTypePtr)[i].second)
// // {// this is an edge type vertex
// // pot_vertex = inMeshPtr->vecEdge[(*_levelCyclePointTypePtr)[i].first].v0;
// // //
// // if (i != 0 && pot_vertex == outLevelCycle_VertexOnMesh.back())
// // continue;
// // // check if this vertex is there or not
// // // if it is there, ignore it
// // // otherwise, push it
// // //
// // //
// // outLevelCycle_VertexOnMesh.push_back(pot_vertex);
// // //
// // if (i != 0)
// // {// find the edge connecting (i-1)--(i)
// // // First, if the (i-1)-vertex is on the edge, as the other vertex of this edge is taken
// // // so the edge connecting (i-1)--(i) is just the processing edge
// // if (inMeshPtr->vecEdge[(*_levelCyclePointTypePtr)[i].first].v0 == outLevelCycle_VertexOnMesh[outLevelCycle_VertexOnMesh.size() - 2] ||
// // inMeshPtr->vecEdge[(*_levelCyclePointTypePtr)[i].first].v1 == outLevelCycle_VertexOnMesh[outLevelCycle_VertexOnMesh.size() - 2] )
// // {
// // outLevelCycle_EdgeOnMesh.push_back((*_levelCyclePointTypePtr)[i].first);
// // }
// // else
// // {
// // // find the triangle first containing the edge and prev vertex
// // int triangle_id = 0;
// // for (unsigned int nTri = 0; nTri < 1; nTri++)
// // {
// // int tot_sum = inMeshPtr->vecTriangle[inMeshPtr->vecEdge[(*_levelCyclePointTypePtr)[i].first].AdjTri[nTri]].v0 +
// // inMeshPtr->vecTriangle[inMeshPtr->vecEdge[(*_levelCyclePointTypePtr)[i].first].AdjTri[nTri]].v1 +
// // inMeshPtr->vecTriangle[inMeshPtr->vecEdge[(*_levelCyclePointTypePtr)[i].first].AdjTri[nTri]].v2;
// // int tot_edge_sum = inMeshPtr->vecEdge[(*_levelCyclePointTypePtr)[i].first].v0 +
// // inMeshPtr->vecEdge[(*_levelCyclePointTypePtr)[i].first].v1;
//
// // if (tot_sum - tot_edge_sum == outLevelCycle_VertexOnMesh[outLevelCycle_VertexOnMesh.size() - 2])
// // {
// // triangle_id = inMeshPtr->vecEdge[(*_levelCyclePointTypePtr)[i].first].AdjTri[nTri];
// // }
// // else
// // {
// // triangle_id = inMeshPtr->vecEdge[(*_levelCyclePointTypePtr)[i].first].AdjTri[nTri + 1];
// // }
// // }
// // //
// // int edge_vec[3] = {inMeshPtr->vecTriangle[triangle_id].e01, inMeshPtr->vecTriangle[triangle_id].e02,
// // inMeshPtr->vecTriangle[triangle_id].e12};
// // for (int eid = 0; eid < 3; eid++)
// // {
// // if (( inMeshPtr->vecEdge[edge_vec[eid]].v0 == pot_vertex ||
// // inMeshPtr->vecEdge[edge_vec[eid]].v1 == pot_vertex) &&
// // (inMeshPtr->vecEdge[edge_vec[eid]].v0 == outLevelCycle_VertexOnMesh[outLevelCycle_VertexOnMesh.size() - 2] ||
// // inMeshPtr->vecEdge[edge_vec[eid]].v1 == outLevelCycle_VertexOnMesh[outLevelCycle_VertexOnMesh.size() - 2]))
// // {
// // outLevelCycle_EdgeOnMesh.push_back(edge_vec[eid]);
// // break;
// // }
// // }
// // //
// // }
// // }
// // //
//
// //
// // }
// // else
// // {// it is a vertex
// // pot_vertex = (*_levelCyclePointTypePtr)[i].first;
// // // check if this vertex is there or not
// // // if it is there, ignore it
// // // otherwise, push it
// // //
// // if (i != 0 && pot_vertex == outLevelCycle_VertexOnMesh.back())
// // continue;
// // //
// // outLevelCycle_VertexOnMesh.push_back(pot_vertex);
// // //
// // if (i != 0)
// // {
// // for (unsigned int k = 0; k < inMeshPtr->vecVertex[outLevelCycle_VertexOnMesh[outLevelCycle_VertexOnMesh.size() - 2]].adjEdges.size();
// // k++)
// // {
// // if (inMeshPtr->vecEdge[inMeshPtr->vecVertex[outLevelCycle_VertexOnMesh[outLevelCycle_VertexOnMesh.size() - 2]].adjEdges[k]].v0 == pot_vertex ||
// // inMeshPtr->vecEdge[inMeshPtr->vecVertex[outLevelCycle_VertexOnMesh[outLevelCycle_VertexOnMesh.size() - 2]].adjEdges[k]].v1 == pot_vertex)
// // {
// // outLevelCycle_EdgeOnMesh.push_back(inMeshPtr->vecVertex[outLevelCycle_VertexOnMesh[outLevelCycle_VertexOnMesh.size() - 2]].adjEdges[k]);
// // break;
// // }
// // }
// // }// if i != 0
// //
// // }// else it is a vertex
// //}
// //// Handle the boundary case
// //if (outLevelCycle_VertexOnMesh.back() != outLevelCycle_VertexOnMesh.front())
// //{
// // for (unsigned int i = 0; i < inMeshPtr->vecVertex[outLevelCycle_VertexOnMesh.front()].adjEdges.size();
// // i++)
// // {
// // if (inMeshPtr->vecEdge[inMeshPtr->vecVertex[outLevelCycle_VertexOnMesh.front()].adjEdges[i]].v0 == outLevelCycle_VertexOnMesh.back() ||
// // inMeshPtr->vecEdge[inMeshPtr->vecVertex[outLevelCycle_VertexOnMesh.front()].adjEdges[i]].v1 == outLevelCycle_VertexOnMesh.back())
// // {
// // outLevelCycle_EdgeOnMesh.push_back(inMeshPtr->vecVertex[outLevelCycle_VertexOnMesh.front()].adjEdges[i]);
// // break;
// // }
// // }
// // // add the first vertex into the back to close the loop
// // outLevelCycle_VertexOnMesh.push_back(outLevelCycle_VertexOnMesh.front());
// //}
// //
// return;
//}
//void MapLoopsBackToMeshLevelSetAndArc::ComputeLevelCycle()
//{
// // preq: both level cycle and arc cycle , point and pointType are initialized
// // critical point
// int crit_vertex_a = _arcCyclePointTypePtr->front().first;
// int crit_vertex_b = _arcCyclePointTypePtr->back().first;
// //
// std::set<int> processed_vertex;
// std::set<int>::iterator findIter;
// //
// int pot_vertex = 0;
// // boundary check is done YET !!!!!!!!!!!!!!!
// for (unsigned int i = 0; i < _levelCyclePointTypePtr->size() - 1; i++)
// {
// if (outLevelCycle_VertexOnMesh.size() == 53)
// i = i;
// if ((*_levelCyclePointTypePtr)[i].second)
// {// this is an edge type vertex
// pot_vertex = inMeshPtr->vecEdge[(*_levelCyclePointTypePtr)[i].first].v0;
// //
// if (i != 0 && pot_vertex == outLevelCycle_VertexOnMesh.back())
// continue;
// findIter = processed_vertex.find(pot_vertex);
//
// if (findIter != processed_vertex.end())
// {
// pot_vertex = inMeshPtr->vecEdge[(*_levelCyclePointTypePtr)[i].first].v1;
// findIter = processed_vertex.find(pot_vertex);
// }
// else
// {
// //
// if (inMeshPtr->vecEdge[(*_levelCyclePointTypePtr)[i].first].v1 == crit_vertex_a ||
// inMeshPtr->vecEdge[(*_levelCyclePointTypePtr)[i].first].v1 == crit_vertex_b)
// {
//
// findIter = processed_vertex.find(inMeshPtr->vecEdge[(*_levelCyclePointTypePtr)[i].first].v1);
// if (findIter == processed_vertex.end())
// pot_vertex = inMeshPtr->vecEdge[(*_levelCyclePointTypePtr)[i].first].v1;
// }
// }
// //
// if (i != 0 && pot_vertex == outLevelCycle_VertexOnMesh.back())
// continue;
// // check if this vertex is there or not
// // if it is there, ignore it
// // otherwise, push it
// //
// //findIter = processed_vertex.find(pot_vertex);
// if (i == 0 || pot_vertex != outLevelCycle_VertexOnMesh.back())//findIter == processed_vertex.end())
// {
// processed_vertex.insert(pot_vertex);
// //
// outLevelCycle_VertexOnMesh.push_back(pot_vertex);
// //
// if (i != 0)
// {// find the edge connecting (i-1)--(i)
// // First, if the (i-1)-vertex is on the edge, as the other vertex of this edge is taken
// // so the edge connecting (i-1)--(i) is just the processing edge
// if (inMeshPtr->vecEdge[(*_levelCyclePointTypePtr)[i].first].v0 == outLevelCycle_VertexOnMesh[outLevelCycle_VertexOnMesh.size() - 2] ||
// inMeshPtr->vecEdge[(*_levelCyclePointTypePtr)[i].first].v1 == outLevelCycle_VertexOnMesh[outLevelCycle_VertexOnMesh.size() - 2] )
// {
// outLevelCycle_EdgeOnMesh.push_back((*_levelCyclePointTypePtr)[i].first);
// }
// else
// {
// // find the triangle first containing the edge and prev vertex
// int triangle_id = 0;
// for (unsigned int nTri = 0; nTri < 1; nTri++)
// {
// int tot_sum = inMeshPtr->vecTriangle[inMeshPtr->vecEdge[(*_levelCyclePointTypePtr)[i].first].AdjTri[nTri]].v0 +
// inMeshPtr->vecTriangle[inMeshPtr->vecEdge[(*_levelCyclePointTypePtr)[i].first].AdjTri[nTri]].v1 +
// inMeshPtr->vecTriangle[inMeshPtr->vecEdge[(*_levelCyclePointTypePtr)[i].first].AdjTri[nTri]].v2;
// int tot_edge_sum = inMeshPtr->vecEdge[(*_levelCyclePointTypePtr)[i].first].v0 +
// inMeshPtr->vecEdge[(*_levelCyclePointTypePtr)[i].first].v1;
//
// if (tot_sum - tot_edge_sum == outLevelCycle_VertexOnMesh[outLevelCycle_VertexOnMesh.size() - 2])
// {
// triangle_id = inMeshPtr->vecEdge[(*_levelCyclePointTypePtr)[i].first].AdjTri[nTri];
// }
// else
// {
// triangle_id = inMeshPtr->vecEdge[(*_levelCyclePointTypePtr)[i].first].AdjTri[nTri + 1];
// }
// }
// //
// int edge_vec[3] = {inMeshPtr->vecTriangle[triangle_id].e01, inMeshPtr->vecTriangle[triangle_id].e02,
// inMeshPtr->vecTriangle[triangle_id].e12};
// for (int eid = 0; eid < 3; eid++)
// {
// if (( inMeshPtr->vecEdge[edge_vec[eid]].v0 == pot_vertex ||
// inMeshPtr->vecEdge[edge_vec[eid]].v1 == pot_vertex) &&
// (inMeshPtr->vecEdge[edge_vec[eid]].v0 == outLevelCycle_VertexOnMesh[outLevelCycle_VertexOnMesh.size() - 2] ||
// inMeshPtr->vecEdge[edge_vec[eid]].v1 == outLevelCycle_VertexOnMesh[outLevelCycle_VertexOnMesh.size() - 2]))
// {
// outLevelCycle_EdgeOnMesh.push_back(edge_vec[eid]);
// break;
// }
// }
// //
// }
// }// if findIter
// //
//
// }
// // else
// // do nothing
// }
// else
// {// it is a vertex
// pot_vertex = (*_levelCyclePointTypePtr)[i].first;
// // check if this vertex is there or not
// // if it is there, ignore it
// // otherwise, push it
// //
// if (i != 0 && pot_vertex == outLevelCycle_VertexOnMesh.back())
// continue;
// findIter = processed_vertex.find(pot_vertex);
// if (findIter == processed_vertex.end())
// {
// processed_vertex.insert(pot_vertex);
// //
// outLevelCycle_VertexOnMesh.push_back(pot_vertex);
// //
// if (i != 0)
// {
// for (unsigned int k = 0; k < inMeshPtr->vecVertex[outLevelCycle_VertexOnMesh[outLevelCycle_VertexOnMesh.size() - 2]].adjEdges.size();
// k++)
// {
// if (inMeshPtr->vecEdge[inMeshPtr->vecVertex[outLevelCycle_VertexOnMesh[outLevelCycle_VertexOnMesh.size() - 2]].adjEdges[k]].v0 == pot_vertex ||
// inMeshPtr->vecEdge[inMeshPtr->vecVertex[outLevelCycle_VertexOnMesh[outLevelCycle_VertexOnMesh.size() - 2]].adjEdges[k]].v1 == pot_vertex)
// {
// outLevelCycle_EdgeOnMesh.push_back(inMeshPtr->vecVertex[outLevelCycle_VertexOnMesh[outLevelCycle_VertexOnMesh.size() - 2]].adjEdges[k]);
// break;
// }
// }
// }// if i != 0
// }// if findIter
// }// else it is a vertex
// }
// // Handle the boundary case
// for (unsigned int i = 0; i < inMeshPtr->vecVertex[outLevelCycle_VertexOnMesh.front()].adjEdges.size();
// i++)
// {
// if (inMeshPtr->vecEdge[inMeshPtr->vecVertex[outLevelCycle_VertexOnMesh.front()].adjEdges[i]].v0 == outLevelCycle_VertexOnMesh.back() ||
// inMeshPtr->vecEdge[inMeshPtr->vecVertex[outLevelCycle_VertexOnMesh.front()].adjEdges[i]].v1 == outLevelCycle_VertexOnMesh.back())
// {
// outLevelCycle_EdgeOnMesh.push_back(inMeshPtr->vecVertex[outLevelCycle_VertexOnMesh.front()].adjEdges[i]);
// break;
// }
// }
// // add the first vertex into the back to close the loop
// outLevelCycle_VertexOnMesh.push_back(outLevelCycle_VertexOnMesh.front());
// //
// return;
//}
//
void MapLoopsBackToMeshLevelSetAndArc::WalkAlongArcWithInitialSide_InverseArcOrder(const int init_vertex_for_side,
int ¤t_active_vertex,
int &refEdge, int &outTriagleId,
const std::vector<std::pair<int, int> > &arcPointType,
std::vector<int> &vecArc_vertex,
std::vector<int> &vecArc_edge) {//
// preq: the arc is not an edge,
// current_active_vertex is the lowest critical point on the mesh
int pot_vertex = 0;
int pot_edge_id = 0;
int current_edge_id = 0;
//init_vertex_for_side is on the first edge and it is NOT in the vertex_array
int shared_vertex = 0;
if (arcPointType.size() == 2) {// init_vertex_for_side is the opposite vertex to current_ative_vertex
vecArc_vertex.push_back(init_vertex_for_side);
//
int three_edges[3] = {inMeshPtr->vecTriangle[outTriagleId].e01,
inMeshPtr->vecTriangle[outTriagleId].e02,
inMeshPtr->vecTriangle[outTriagleId].e12};
for (int teid = 0; teid < 3; teid++) {
if ((inMeshPtr->vecEdge[three_edges[teid]].v0 == current_active_vertex ||
inMeshPtr->vecEdge[three_edges[teid]].v1 == current_active_vertex) &&
(inMeshPtr->vecEdge[three_edges[teid]].v0 == init_vertex_for_side ||
inMeshPtr->vecEdge[three_edges[teid]].v1 == init_vertex_for_side)) {
pot_edge_id = three_edges[teid];
break;
}
}
//
vecArc_edge.push_back(pot_edge_id);
//
// update current_active_vertex and refEdge
int third_vertex = inMeshPtr->vecTriangle[outTriagleId].v0 +
inMeshPtr->vecTriangle[outTriagleId].v1 +
inMeshPtr->vecTriangle[outTriagleId].v2 -
(current_active_vertex + init_vertex_for_side);
//
current_active_vertex = init_vertex_for_side;
for (int teid = 0; teid < 3; teid++) {
if ((inMeshPtr->vecEdge[three_edges[teid]].v0 == current_active_vertex ||
inMeshPtr->vecEdge[three_edges[teid]].v1 == current_active_vertex) &&
(inMeshPtr->vecEdge[three_edges[teid]].v0 == third_vertex ||
inMeshPtr->vecEdge[three_edges[teid]].v1 == third_vertex)) {
refEdge = three_edges[teid];
break;
}
}
} else {
/*
Initializing current active vertex
*/
if (!arcPointType[arcPointType.size() - 2].second) {// it is only a vertex
std::cout << "vertex except critical points on the arc ?" << std::endl;
exit(0);
}
// Handle the intial case
current_edge_id = arcPointType[arcPointType.size() - 2].first;
pot_vertex = init_vertex_for_side;
//
FindEdgeConnectingTwoVertices(current_active_vertex, pot_vertex, current_edge_id, pot_edge_id);
//
current_active_vertex = pot_vertex;
//
vecArc_vertex.push_back(current_active_vertex);
vecArc_edge.push_back(pot_edge_id);
//
for (unsigned int i = arcPointType.size() - 3; i > 0; i--) {
/*
Invariant : current_active_vertex is always on current edge if current array element is an edge
or it is the current vertex if current array element is a vertex
*/
if (arcPointType[i].second) {// this is an edge type vertex
current_edge_id = arcPointType[i].first;
if (arcPointType[i + 1].second) {// previous has one edge
if (inMeshPtr->vecEdge[current_edge_id].v0 != current_active_vertex &&
inMeshPtr->vecEdge[current_edge_id].v1 !=
current_active_vertex) {// if current active vertex is on this edge, then do nothing
// else add one more edge and update current_active_vertex
// since the levele set cross the edge only once, so there must exist at least one vertex on the edge not visited yet
shared_vertex = inMeshPtr->vecEdge[arcPointType[i + 1].first].v0 +
inMeshPtr->vecEdge[arcPointType[i + 1].first].v1 - current_active_vertex;
pot_vertex = inMeshPtr->vecEdge[current_edge_id].v0;
if (shared_vertex == pot_vertex)
pot_vertex = inMeshPtr->vecEdge[current_edge_id].v1;
//
FindEdgeConnectingTwoVertices(current_active_vertex, pot_vertex, current_edge_id, pot_edge_id);
//
current_active_vertex = pot_vertex;
//
vecArc_vertex.push_back(current_active_vertex);
vecArc_edge.push_back(pot_edge_id);
//
}
} else {// previous one is an vertex
std::cout << "vertex except critical points on the arc ?" << std::endl;
exit(0);
}
} else {// it is a vertex
std::cout << "vertex except critical points on the arc ?" << std::endl;
exit(0);
}// else it is a vertex
}
// Handle the boundary case
pot_vertex = arcPointType.front().first; // the last vertex
if (current_active_vertex != pot_vertex) {
current_edge_id = arcPointType[1].first;
FindEdgeConnectingTwoVertices(pot_vertex, current_active_vertex, current_edge_id, pot_edge_id);
//
vecArc_vertex.push_back(pot_vertex);
vecArc_edge.push_back(pot_edge_id);
//
outTriagleId = TriangleAdjacentToOneEdgesOneVertex(current_edge_id, pot_vertex);
refEdge = pot_edge_id;
current_active_vertex = pot_vertex;
} else {//
std::cout << "the one before downforking pt is a vertex ?" << std::endl;
exit(1);
}
}
// invariant : outTrinagleId is the one triangle which is adjacent to the last edge in vecArc_edge
return;
}
void MapLoopsBackToMeshLevelSetAndArc::WalkAlongArcWithInitialSide_ArcOrder(const int init_vertex_for_side,
int ¤t_active_vertex, int &refEdge,
int &outTriagleId,
const std::vector<std::pair<int, int> > &arcPointType,
std::vector<int> &vecArc_vertex,
std::vector<int> &vecArc_edge) {//
// preq: the arc is not an edge,
// current_active_vertex is the lowest critical point on the mesh
int pot_vertex = 0;
int pot_edge_id = 0;
int current_edge_id = 0;
//init_vertex_for_side is on the first edge and it is NOT in the vertex_array
int shared_vertex = 0;
if (arcPointType.size() == 2) {// init_vertex_for_side is the opposite vertex to current_ative_vertex
vecArc_vertex.push_back(init_vertex_for_side);
//
int three_edges[3] = {inMeshPtr->vecTriangle[outTriagleId].e01,
inMeshPtr->vecTriangle[outTriagleId].e02,
inMeshPtr->vecTriangle[outTriagleId].e12};
for (int teid = 0; teid < 3; teid++) {
if ((inMeshPtr->vecEdge[three_edges[teid]].v0 == current_active_vertex ||
inMeshPtr->vecEdge[three_edges[teid]].v1 == current_active_vertex) &&
(inMeshPtr->vecEdge[three_edges[teid]].v0 == init_vertex_for_side ||
inMeshPtr->vecEdge[three_edges[teid]].v1 == init_vertex_for_side)) {
pot_edge_id = three_edges[teid];
break;
}
}
//
vecArc_edge.push_back(pot_edge_id);
//
// update current_active_vertex and refEdge
int third_vertex = inMeshPtr->vecTriangle[outTriagleId].v0 +
inMeshPtr->vecTriangle[outTriagleId].v1 +
inMeshPtr->vecTriangle[outTriagleId].v2 -
(current_active_vertex + init_vertex_for_side);
//
current_active_vertex = init_vertex_for_side;
for (int teid = 0; teid < 3; teid++) {
if ((inMeshPtr->vecEdge[three_edges[teid]].v0 == current_active_vertex ||
inMeshPtr->vecEdge[three_edges[teid]].v1 == current_active_vertex) &&
(inMeshPtr->vecEdge[three_edges[teid]].v0 == third_vertex ||
inMeshPtr->vecEdge[three_edges[teid]].v1 == third_vertex)) {
refEdge = three_edges[teid];
break;
}
}
} else {
/*
Initializing current active vertex
*/
if (!arcPointType[1].second) {// it is only a vertex
std::cout << "vertex except critical points on the arc ?" << std::endl;
exit(0);
}
// Handle the intial case
current_edge_id = arcPointType[1].first;
pot_vertex = init_vertex_for_side;
//
FindEdgeConnectingTwoVertices(current_active_vertex, pot_vertex, current_edge_id, pot_edge_id);
//
current_active_vertex = pot_vertex;
//
vecArc_vertex.push_back(current_active_vertex);
vecArc_edge.push_back(pot_edge_id);
//
for (unsigned int i = 2; i < arcPointType.size() - 1; i++) {
/*
Invariant : current_active_vertex is always on current edge if current array element is an edge
or it is the current vertex if current array element is a vertex
*/
if (arcPointType[i].second) {// this is an edge type vertex
current_edge_id = arcPointType[i].first;
if (arcPointType[i - 1].second) {// previous has one edge
if (inMeshPtr->vecEdge[current_edge_id].v0 != current_active_vertex &&
inMeshPtr->vecEdge[current_edge_id].v1 !=
current_active_vertex) {// if current active vertex is on this edge, then do nothing
// else add one more edge and update current_active_vertex
// since the levele set cross the edge only once, so there must exist at least one vertex on the edge not visited yet
shared_vertex = inMeshPtr->vecEdge[arcPointType[i - 1].first].v0 +
inMeshPtr->vecEdge[arcPointType[i - 1].first].v1 - current_active_vertex;
pot_vertex = inMeshPtr->vecEdge[current_edge_id].v0;
if (shared_vertex == pot_vertex)
pot_vertex = inMeshPtr->vecEdge[current_edge_id].v1;
//
FindEdgeConnectingTwoVertices(current_active_vertex, pot_vertex, current_edge_id, pot_edge_id);
//
current_active_vertex = pot_vertex;
//
vecArc_vertex.push_back(current_active_vertex);
vecArc_edge.push_back(pot_edge_id);
//
}
} else {// previous one is an vertex
std::cout << "vertex except critical points on the arc ?" << std::endl;
exit(0);
}
} else {// it is a vertex
std::cout << "vertex except critical points on the arc ?" << std::endl;
exit(0);
}// else it is a vertex
}
// Handle the boundary case
pot_vertex = arcPointType.back().first; // the last vertex
if (current_active_vertex != pot_vertex) {
current_edge_id = arcPointType[arcPointType.size() - 2].first;
FindEdgeConnectingTwoVertices(pot_vertex, current_active_vertex, current_edge_id, pot_edge_id);
//
vecArc_vertex.push_back(pot_vertex);
vecArc_edge.push_back(pot_edge_id);
//
outTriagleId = TriangleAdjacentToOneEdgesOneVertex(current_edge_id, pot_vertex);
refEdge = pot_edge_id;
current_active_vertex = pot_vertex;
} else {//
std::cout << "the one before downforking pt is a vertex ?" << std::endl;
exit(1);
}
// invariant : outTrinagleId is the one triangle which is adjacent to the last edge in vecArc_edge
}
return;
}
void MapLoopsBackToMeshLevelSetAndArc::ComputeArcCycle() {
// // critical point
if ((*_arcCyclePointTypePtr).size() == 2) {// this is arc corresponding to an edge on the mesh
int dst_node = (*_arcCyclePointTypePtr).back().first;
int src_node = (*_arcCyclePointTypePtr).front().first;
for (std::vector<int>::iterator vIter = (*inMeshPtr).vecVertex[src_node].adjEdges.begin();
vIter != (*inMeshPtr).vecVertex[src_node].adjEdges.end();
vIter++) {
if ((*inMeshPtr).vecEdge[*vIter].v0 == dst_node ||
(*inMeshPtr).vecEdge[*vIter].v1 == dst_node) {
outArcCycle_EdgeOnMesh.push_back(*vIter);
break;
}
}
//
outArcCycle_VertexOnMesh.push_back(src_node);
outArcCycle_VertexOnMesh.push_back(dst_node);
} else {
std::set<int> processed_vertex;
std::set<int>::iterator findIter;
//
int pot_vertex = 0;
int pot_edge_id = 0;
int current_edge_id = 0;
int current_active_vertex = 0;
int shared_vertex = 0;
/*
Initializing current active vertex
*/
if ((*_arcCyclePointTypePtr)[0].second) {// it is an edge
current_edge_id = (*_arcCyclePointTypePtr)[0].first;
current_active_vertex = (*inMeshPtr).vecEdge[current_edge_id].v0;
//
processed_vertex.insert(current_active_vertex);
//
outArcCycle_VertexOnMesh.push_back(current_active_vertex);
} else {// it is only a vertex
current_active_vertex = (*_arcCyclePointTypePtr)[0].first;
//
processed_vertex.insert(current_active_vertex);
//
outArcCycle_VertexOnMesh.push_back(current_active_vertex);
}
// boundary check is done YET !!!!!!!!!!!!!!!
for (unsigned int i = 1; i < _arcCyclePointTypePtr->size() - 1; i++) {
/*
Invariant : current_active_vertex is always on current edge if current array element is an edge
or it is the current vertex if current array element is a vertex
*/
if ((*_arcCyclePointTypePtr)[i].second) {// this is an edge type vertex
current_edge_id = (*_arcCyclePointTypePtr)[i].first;
if ((*_arcCyclePointTypePtr)[i - 1].second) {// previous has one edge
if (inMeshPtr->vecEdge[current_edge_id].v0 != current_active_vertex &&
inMeshPtr->vecEdge[current_edge_id].v1 !=
current_active_vertex) {// if current active vertex is on this edge, then do nothing
// else add one more edge and update current_active_vertex
// since the levele set cross the edge only once, so there must exist at least one vertex on the edge not visited yet
shared_vertex = inMeshPtr->vecEdge[(*_arcCyclePointTypePtr)[i - 1].first].v0 +
inMeshPtr->vecEdge[(*_arcCyclePointTypePtr)[i - 1].first].v1 -
current_active_vertex;
pot_vertex = inMeshPtr->vecEdge[current_edge_id].v0;
if (shared_vertex == pot_vertex)
pot_vertex = inMeshPtr->vecEdge[current_edge_id].v1;
//
FindEdgeConnectingTwoVertices(current_active_vertex, pot_vertex, current_edge_id, pot_edge_id);
//
current_active_vertex = pot_vertex;
//
outArcCycle_VertexOnMesh.push_back(current_active_vertex);
outArcCycle_EdgeOnMesh.push_back(pot_edge_id);
//
processed_vertex.insert(current_active_vertex);
}
} else {// previous one is an vertex
if (inMeshPtr->vecEdge[current_edge_id].v0 != current_active_vertex &&
inMeshPtr->vecEdge[current_edge_id].v1 != current_active_vertex) {// take arbitrary decision
pot_vertex = inMeshPtr->vecEdge[current_edge_id].v0;
//
FindEdgeConnectingTwoVertices(current_active_vertex, pot_vertex, current_edge_id, pot_edge_id);
//
current_active_vertex = pot_vertex;
//
outArcCycle_VertexOnMesh.push_back(current_active_vertex);
outArcCycle_EdgeOnMesh.push_back(pot_edge_id);
//
processed_vertex.insert(current_active_vertex);
} else {//
std::cout << "potential error in arc computation" << std::endl;
exit(0);
}
}
} else {// it is a vertex
pot_vertex = (*_arcCyclePointTypePtr)[i].first;
// check if this vertex is there or not
// if it is there, ignore it
// otherwise, push it
//
pot_edge_id = -1;
if (processed_vertex.find(pot_vertex) == processed_vertex.end()) {
for (std::vector<int>::iterator vIter = inMeshPtr->vecVertex[current_active_vertex].adjEdges.begin();
vIter != inMeshPtr->vecVertex[current_active_vertex].adjEdges.end(); vIter++) {
if (inMeshPtr->vecEdge[*vIter].v0 == pot_vertex ||
inMeshPtr->vecEdge[*vIter].v1 == pot_vertex) {
pot_edge_id = *vIter;
break;
}
}
if (pot_edge_id > -1) {
outArcCycle_VertexOnMesh.push_back(pot_vertex);
outArcCycle_EdgeOnMesh.push_back(pot_edge_id);
} else {
std::cout << "No edge connecting two vertices " << std::endl;
exit(0);
}
//
current_active_vertex = pot_vertex;
//
processed_vertex.insert(current_active_vertex);
}
}// else it is a vertex
}
// Handle the boundary case
pot_vertex = (*_arcCyclePointTypePtr).back().first; // the last vertex
if (current_active_vertex != pot_vertex) {
pot_edge_id = -1;
for (std::vector<int>::iterator vIter = inMeshPtr->vecVertex[current_active_vertex].adjEdges.begin();
vIter != inMeshPtr->vecVertex[current_active_vertex].adjEdges.end(); vIter++) {
if (inMeshPtr->vecEdge[*vIter].v0 == pot_vertex ||
inMeshPtr->vecEdge[*vIter].v1 == pot_vertex) {
pot_edge_id = *vIter;
break;
}
}
if (pot_edge_id > -1) {
outArcCycle_VertexOnMesh.push_back(pot_vertex);
outArcCycle_EdgeOnMesh.push_back(pot_edge_id);
} else {
std::cout << "No edge connecting two vertices " << std::endl;
exit(0);
}
}
}
return;
/*
if ((*_arcCyclePointTypePtr).size() == 2)
{// this is arc corresponding to an edge on the mesh
int dst_node = (*_arcCyclePointTypePtr).back().first;
int src_node = (*_arcCyclePointTypePtr).front().first;
for (std::vector<int>::iterator vIter = (*inMeshPtr).vecVertex[src_node].adjEdges.begin();
vIter != (*inMeshPtr).vecVertex[src_node].adjEdges.end();
vIter++)
{
if ((*inMeshPtr).vecEdge[*vIter].v0 == dst_node ||
(*inMeshPtr).vecEdge[*vIter].v1 == dst_node)
{
outArcCycle_EdgeOnMesh.push_back(*vIter);
break;
}
}
//
outArcCycle_VertexOnMesh.push_back(dst_node);
outArcCycle_VertexOnMesh.push_back(src_node);
}
else
{
boost::unordered_set<int> triangleDegree;
std::vector<int> triangleOrder ;
for (unsigned int i = 0; i < _arcCyclePointTypePtr->size() - 1; i++)
{
int triangle_id = 0;
int edge_a = (*_arcCyclePointTypePtr)[i].first;
int edge_b = (*_arcCyclePointTypePtr)[i + 1].first;
if (i == 0)
{
triangle_id = TriangleAdjacentToOneEdgesOneVertex(edge_b, edge_a);
}
else
{
if (i == _arcCyclePointTypePtr->size() - 2)
{
triangle_id = TriangleAdjacentToOneEdgesOneVertex(edge_a, edge_b);
}
else
{
triangle_id = TriangleAdjacentToTwoEdges(edge_a, edge_b);
}
}
//
//
boost::unordered_set<int>::iterator sIter = triangleDegree.find(triangle_id);
if (sIter == triangleDegree.end())
{
triangleDegree.insert(triangle_id);
triangleOrder.push_back(triangle_id);
}
else
{//
std::cout << "NOT a triangle trip" << std::endl;
exit(9);
}
//
}
//
_simpGraph triangleStripGraph;
boost::unordered_map<int, int> verToGraphNode;
boost::unordered_map<int, int>::iterator mIter;
int nGrapNodeCounter = 0;
for (unsigned int i = 0; i < triangleOrder.size(); i++)
{
int node[3] = { (*inMeshPtr).vecTriangle[triangleOrder[i]].v0,
(*inMeshPtr).vecTriangle[triangleOrder[i]].v1,
(*inMeshPtr).vecTriangle[triangleOrder[i]].v2};
int gNode[3] = {0};
for (int j = 0; j < 3; j++)
{
mIter = verToGraphNode.find(node[j]);
if (mIter == verToGraphNode.end())
{
triangleStripGraph.AddNode(nGrapNodeCounter, node[j]);
gNode[j] = nGrapNodeCounter;
verToGraphNode[node[j]] = nGrapNodeCounter;
nGrapNodeCounter++;
}
else
{
gNode[j] = mIter->second;
}
}
triangleStripGraph.AddEdge(gNode[0], gNode[1]); // since graph node use set to store adjacent list
triangleStripGraph.AddEdge(gNode[0], gNode[2]); // no need to check the edge exists or not
triangleStripGraph.AddEdge(gNode[1], gNode[2]);
}
//
for (unsigned int i = 1; i < _arcCyclePointTypePtr->size() - 1; i++)
{
int edge_idx = (*_arcCyclePointTypePtr)[i].first;
triangleStripGraph.RemoveEdge( verToGraphNode[(*inMeshPtr).vecEdge[edge_idx].v0], verToGraphNode[(*inMeshPtr).vecEdge[edge_idx].v1]);
}
//there exist two disjont two components
std::vector<bool> colors(triangleStripGraph.vecNode.size(), false);
std::vector<int> parents(triangleStripGraph.vecNode.size(), -1);
int components = 1;
int currentNode = verToGraphNode[_arcCyclePointTypePtr->front().first];
int oppositeNode = verToGraphNode[_arcCyclePointTypePtr->back().first];
// visit the components
std::queue<int> Q;
Q.push(currentNode);
colors[currentNode] = true;
parents[currentNode] = -1;
while (!Q.empty())
{
int node = Q.front();
Q.pop();
for (std::set<int>::iterator sIter = triangleStripGraph.vecNode[node].adjList.begin();
sIter != triangleStripGraph.vecNode[node].adjList.end(); sIter++)
{
if (!colors[*sIter])
{
colors[*sIter] = true;
Q.push(*sIter);
parents[*sIter] = node;
}
}
}
for (unsigned int i = 0; i < colors.size(); i++)
{
if (!colors[i])
{
components++;
}
}
if (components != 1)
{
std::cout << "wrong method again for arc" << std::endl;
exit(4);
}
outLevelCycle_VertexOnMesh.reserve(triangleStripGraph.vecNode.size());
outLevelCycle_EdgeOnMesh.reserve(triangleStripGraph.vecNode.size());
//
//
//
int iterNode = oppositeNode;
while (iterNode >= 0)
{
outArcCycle_VertexOnMesh.push_back(triangleStripGraph.vecNode[iterNode].color);
iterNode = parents[iterNode];
}
if (outArcCycle_VertexOnMesh.back() != triangleStripGraph.vecNode[currentNode].color)
{
std::cout << "in different compoents for arc" << std::endl;
exit(4);
}
//
for (unsigned int i = 0; i < outArcCycle_VertexOnMesh.size() - 1; i++)
{
int curNode = outArcCycle_VertexOnMesh[i];
int oppNode = outArcCycle_VertexOnMesh[i + 1];
for (std::vector<int>::iterator vIter = (*inMeshPtr).vecVertex[curNode].adjEdges.begin();
vIter != (*inMeshPtr).vecVertex[curNode].adjEdges.end(); vIter++)
{
if ((*inMeshPtr).vecEdge[*vIter].v0 == oppNode ||
(*inMeshPtr).vecEdge[*vIter].v1 == oppNode)
{
outArcCycle_EdgeOnMesh.push_back(*vIter);
break;
}
}
}
}
return;
*/
/////////////////////////////////////////////
/* std::map<int, std::pair<int,int>> processed_vertex;
int current_edge_a = 0;
int current_edge_b = 0;
int current_edge_c = 0;
int opposite_vertex = 0;
int tracing_termination_pt = 0;
//
if ((*_arcCyclePointTypePtr).size() == 2)
{// this is arc corresponding to an edge on the mesh
int dst_node = (*_arcCyclePointTypePtr).back().first;
int src_node = (*_arcCyclePointTypePtr).front().first;
for (std::vector<int>::iterator vIter = (*inMeshPtr).vecVertex[src_node].adjEdges.begin();
vIter != (*inMeshPtr).vecVertex[src_node].adjEdges.end();
vIter++)
{
if ((*inMeshPtr).vecEdge[*vIter].v0 == dst_node ||
(*inMeshPtr).vecEdge[*vIter].v1 == dst_node)
{
outArcCycle_EdgeOnMesh.push_back(*vIter);
break;
}
}
//
outArcCycle_VertexOnMesh.push_back(dst_node);
outArcCycle_VertexOnMesh.push_back(src_node);
}
else
{ // it always starts with a vertex
////////////////////////////
current_edge_a = (*_arcCyclePointTypePtr)[0].first;
tracing_termination_pt = current_edge_a;
processed_vertex[current_edge_a] = std::pair<int,int>(-1, -1);
////////////////////////////
for (unsigned int i = 0; i < _arcCyclePointTypePtr->size() - 1; i++)
{
// find triangle conntaining the edge [i, i+1]
int triangle_or_edge_id = 0;
if ((*_arcCyclePointTypePtr)[i].second)
{
if ((*_arcCyclePointTypePtr)[i+1].second)
{// both points are on edges
// there exists an triangle containing them
current_edge_a = (*_arcCyclePointTypePtr)[i].first;
current_edge_b = (*_arcCyclePointTypePtr)[i+1].first;
triangle_or_edge_id = TriangleAdjacentToTwoEdges(current_edge_a, current_edge_b);
opposite_vertex = (*inMeshPtr).vecTriangle[triangle_or_edge_id].v0 +
(*inMeshPtr).vecTriangle[triangle_or_edge_id].v1 +
(*inMeshPtr).vecTriangle[triangle_or_edge_id].v2 -
((*inMeshPtr).vecEdge[current_edge_a].v0 + (*inMeshPtr).vecEdge[current_edge_a].v1);
//
if (processed_vertex.find(opposite_vertex) == processed_vertex.end())
{
processed_vertex[opposite_vertex] = std::pair<int,int>(((*inMeshPtr).vecEdge[current_edge_b].v0 + (*inMeshPtr).vecEdge[current_edge_b].v1) - opposite_vertex, current_edge_b);
}
}
else
{// first is on edge , the second is a vertex
opposite_vertex = (*_arcCyclePointTypePtr)[i+1].first;
if (processed_vertex.find(opposite_vertex) == processed_vertex.end())
{
current_edge_a = (*_arcCyclePointTypePtr)[i].first;
FindEdgeConnectingTwoVertices(opposite_vertex, (*inMeshPtr).vecEdge[current_edge_a].v0, current_edge_a, current_edge_c);
processed_vertex[opposite_vertex] = std::pair<int, int>( (*inMeshPtr).vecEdge[current_edge_a].v0, current_edge_c);
}
}
}
else
{
if ((*_arcCyclePointTypePtr)[i+1].second)
{//
opposite_vertex = (*_arcCyclePointTypePtr)[i].first;
current_edge_c = (*_arcCyclePointTypePtr)[i+1].first;
//
triangle_or_edge_id = TriangleAdjacentToOneEdgesOneVertex(current_edge_c, opposite_vertex);
//
current_edge_a = (*inMeshPtr).vecTriangle[triangle_or_edge_id].e01;
if ((*inMeshPtr).vecTriangle[triangle_or_edge_id].e01 == current_edge_c)
current_edge_a = (*inMeshPtr).vecTriangle[triangle_or_edge_id].e02;
//
current_edge_b = (*inMeshPtr).vecTriangle[triangle_or_edge_id].e01 +
(*inMeshPtr).vecTriangle[triangle_or_edge_id].e02 +
(*inMeshPtr).vecTriangle[triangle_or_edge_id].e12 -
(current_edge_a + current_edge_c);
//
int pot_vertex = (*inMeshPtr).vecEdge[current_edge_a].v0 + (*inMeshPtr).vecEdge[current_edge_a].v1 - opposite_vertex;
if (processed_vertex.find(pot_vertex) == processed_vertex.end())
{
processed_vertex[pot_vertex] = std::pair<int,int>(opposite_vertex, current_edge_a);
}
//
pot_vertex = (*inMeshPtr).vecEdge[current_edge_b].v0 + (*inMeshPtr).vecEdge[current_edge_b].v1 - opposite_vertex;
if (processed_vertex.find(pot_vertex) == processed_vertex.end())
{
processed_vertex[pot_vertex] = std::pair<int,int>(opposite_vertex, current_edge_b);
}
}
else
{
int src_node = (*_arcCyclePointTypePtr)[i].first;
opposite_vertex = (*_arcCyclePointTypePtr)[i+1].first;
if (processed_vertex.find(opposite_vertex) == processed_vertex.end())
{
for (std::vector<int>::iterator vIter = (*inMeshPtr).vecVertex[src_node].adjEdges.begin();
vIter != (*inMeshPtr).vecVertex[src_node].adjEdges.begin();
vIter++)
{
if ((*inMeshPtr).vecEdge[*vIter].v0 == opposite_vertex ||
(*inMeshPtr).vecEdge[*vIter].v1 == opposite_vertex)
{
processed_vertex[opposite_vertex] = std::pair<int,int>(src_node, *vIter);
break;
}
}
}
}
}// else i
}
//
int current_vertex = (*_arcCyclePointTypePtr).back().first;
outArcCycle_VertexOnMesh.push_back(current_vertex);
std::pair<int, int> current_vertex_parents = processed_vertex[current_vertex];
while (current_vertex_parents.first != -1)
{
outArcCycle_VertexOnMesh.push_back(current_vertex_parents.first);
outArcCycle_EdgeOnMesh.push_back(current_vertex_parents.second);
current_vertex_parents = processed_vertex[current_vertex_parents.first];
}
}// else == 2
*/
//////////////////////////
////////////////////////////////////////////////////
// preq: arc cycle point and pointType are initialized
////std::cout << "IN ComputeArcCycle" << std::endl;
//std::set<int> processed_vertex;
//std::set<int>::iterator findIter;
////
//int pot_vertex = 0;
////
//if (_arcCyclePointTypePtr->size() == 3)
//{
// if ( (*_arcCyclePointTypePtr)[1].second &&
// !(*_arcCyclePointTypePtr)[0].second &&
// !(*_arcCyclePointTypePtr)[2].second &&
// (
// (inMeshPtr->vecEdge[(*_arcCyclePointTypePtr)[1].first].v0 == (*_arcCyclePointTypePtr)[0].first ||
// inMeshPtr->vecEdge[(*_arcCyclePointTypePtr)[1].first].v0 == (*_arcCyclePointTypePtr)[2].first) &&
// (inMeshPtr->vecEdge[(*_arcCyclePointTypePtr)[1].first].v1 == (*_arcCyclePointTypePtr)[0].first ||
// inMeshPtr->vecEdge[(*_arcCyclePointTypePtr)[1].first].v1 == (*_arcCyclePointTypePtr)[2].first)
// )
// )
// {// this is the 2 points case
// outArcCycle_VertexOnMesh.push_back((*_arcCyclePointTypePtr)[0].first);
// outArcCycle_VertexOnMesh.push_back((*_arcCyclePointTypePtr)[2].first);
// outArcCycle_EdgeOnMesh.push_back((*_arcCyclePointTypePtr)[1].first);
// return;
// }
//}
//// boundary check is done YET !!!!!!!!!!!!!!!
//for (unsigned int i = 0; i < _arcCyclePointTypePtr->size(); i++)
//{
// if ((*_arcCyclePointTypePtr)[i].second)
// {// this is an edge type vertex
// pot_vertex = inMeshPtr->vecEdge[(*_arcCyclePointTypePtr)[i].first].v0;
// if (i != 0 && pot_vertex == outArcCycle_VertexOnMesh.back())
// continue;
// findIter = processed_vertex.find(pot_vertex);
// if (findIter != processed_vertex.end())
// {
// pot_vertex = inMeshPtr->vecEdge[(*_arcCyclePointTypePtr)[i].first].v1;
// //if (i != 0 && pot_vertex == outArcCycle_VertexOnMesh.back())
// //continue;
// }
// }
// else
// {// this is a vertex
// pot_vertex = (*_arcCyclePointTypePtr)[i].first;
// }
// if (i != 0 && pot_vertex == outArcCycle_VertexOnMesh.back())
// continue;
// // check if this vertex is there or not
// // if it is there, ignore it
// // otherwise, push it
// //
// findIter = processed_vertex.find(pot_vertex);
// if (i == 0 || pot_vertex != outArcCycle_VertexOnMesh.back())//if (findIter == processed_vertex.end())
// {
// processed_vertex.insert(pot_vertex);
// //
// outArcCycle_VertexOnMesh.push_back(pot_vertex);
// //
// if (i != 0)
// {// find the edge connecting (i-1)--(i)
// // First, if the (i-1)-vertex is on the edge, as the other vertex of this edge is taken
// // so the edge connecting (i-1)--(i) is just the processing edge
// if ((*_arcCyclePointTypePtr)[i].second)
// {
// if (inMeshPtr->vecEdge[(*_arcCyclePointTypePtr)[i].first].v0 == outArcCycle_VertexOnMesh[outArcCycle_VertexOnMesh.size() - 2] ||
// inMeshPtr->vecEdge[(*_arcCyclePointTypePtr)[i].first].v1 == outArcCycle_VertexOnMesh[outArcCycle_VertexOnMesh.size() - 2] )
// {
// outArcCycle_EdgeOnMesh.push_back((*_arcCyclePointTypePtr)[i].first);
// }
// else
// {
// // find the triangle first containing the edge and prev vertex
// int triangle_id = 0;
// for (unsigned int nTri = 0; nTri < 1; nTri++)
// {
// int tot_sum = inMeshPtr->vecTriangle[inMeshPtr->vecEdge[(*_arcCyclePointTypePtr)[i].first].AdjTri[nTri]].v0 +
// inMeshPtr->vecTriangle[inMeshPtr->vecEdge[(*_arcCyclePointTypePtr)[i].first].AdjTri[nTri]].v1 +
// inMeshPtr->vecTriangle[inMeshPtr->vecEdge[(*_arcCyclePointTypePtr)[i].first].AdjTri[nTri]].v2;
// int tot_edge_sum = inMeshPtr->vecEdge[(*_arcCyclePointTypePtr)[i].first].v0 +
// inMeshPtr->vecEdge[(*_arcCyclePointTypePtr)[i].first].v1;
// if (tot_sum - tot_edge_sum == outArcCycle_VertexOnMesh[outArcCycle_VertexOnMesh.size() - 2])
// {
// triangle_id = inMeshPtr->vecEdge[(*_arcCyclePointTypePtr)[i].first].AdjTri[nTri];
// }
// else
// {
// triangle_id = inMeshPtr->vecEdge[(*_arcCyclePointTypePtr)[i].first].AdjTri[nTri + 1];
// }
// }
// //
// int edge_vec[3] = {inMeshPtr->vecTriangle[triangle_id].e01, inMeshPtr->vecTriangle[triangle_id].e02,
// inMeshPtr->vecTriangle[triangle_id].e12};
// for (int eid = 0; eid < 3; eid++)
// {
// if (( inMeshPtr->vecEdge[edge_vec[eid]].v0 == pot_vertex ||
// inMeshPtr->vecEdge[edge_vec[eid]].v1 == pot_vertex) &&
// (inMeshPtr->vecEdge[edge_vec[eid]].v0 == outArcCycle_VertexOnMesh[outArcCycle_VertexOnMesh.size() - 2] ||
// inMeshPtr->vecEdge[edge_vec[eid]].v1 == outArcCycle_VertexOnMesh[outArcCycle_VertexOnMesh.size() - 2]))
// {
// outArcCycle_EdgeOnMesh.push_back(edge_vec[eid]);
// break;
// }
// }
// //
// }
// }//.second
// else
// {
// // Handle the vertex case
// for (unsigned int k = 0; k < inMeshPtr->vecVertex[pot_vertex].adjEdges.size();
// k++)
// {
// if (inMeshPtr->vecEdge[inMeshPtr->vecVertex[pot_vertex].adjEdges[k]].v0 == outArcCycle_VertexOnMesh[outArcCycle_VertexOnMesh.size() - 2] ||
// inMeshPtr->vecEdge[inMeshPtr->vecVertex[pot_vertex].adjEdges[k]].v1 == outArcCycle_VertexOnMesh[outArcCycle_VertexOnMesh.size() - 2])
// {
// outArcCycle_EdgeOnMesh.push_back(inMeshPtr->vecVertex[pot_vertex].adjEdges[k]);
// break;
// }
// } // for
// }
// } // i != 0
// // else
// // do nothing for i == 0
// }// if findIter
//}
//std::cout << "OUT ComputeArcCycle" << std::endl;
return;
}
////
//void MapLoopsBackToMeshLevelSetAndArc::ComputeLoopOnMeshPolygon()
//{
// // preq: all arcs are processed before
//// path is encoded in this way
//// v0--e0--v1--e1--....vn--en--v(n+1)[==v0]
//// each cycle are passing from high to low
//// each edge is taken in this way [a...b)-[b...c)-[c...a)
// int curArcId = 0;
// int startNodeId = 0;
// int endNodeId = 0;
// Vector3 translatedPt;
// Vector3 prePt, nxtPt;
// // walk around the path in terms of simplified arcs
// for (unsigned int i = 0; i < _meshLoopPtr->simpArcIndexSet.size(); i++)
// {
// curArcId = _meshLoopPtr->simpArcIndexSet[i];
// startNodeId = _meshLoopPtr->nodeIndexSet[i];
// endNodeId = _meshLoopPtr->nodeIndexSet[i+1];
// //
// if ((*_pVecSimplifiedArc)[curArcId].nCriticalNode0 == startNodeId)
// {// since the arc are traversed from high to low,
// // need to travel in the opposite direction
// //
// for ( int iarc = (*_arcVerOnMeshPtr)[curArcId].size() - 1; iarc > 0 ; iarc--)
// {// be aware of which arc to take like _offsetPathArcOnMeshPtr or _pathArcOnMeshPtr
// outArcCycle_VertexOnMesh.push_back((*_arcVerOnMeshPtr)[curArcId][iarc]);
// outArcCycle_EdgeOnMesh.push_back((*_arcEdgOnMeshPtr)[curArcId][iarc - 1]);
// }
// }
// else
// {// ignore the last point
// for (unsigned int iarc = 0; iarc < (*_arcVerOnMeshPtr)[curArcId].size() - 1 ; iarc++)
// {
// outArcCycle_VertexOnMesh.push_back((*_arcVerOnMeshPtr)[curArcId][iarc]);
// outArcCycle_EdgeOnMesh.push_back((*_arcEdgOnMeshPtr)[curArcId][iarc]);
// }
// }
// }
// // push the first point into the loop to close it
// outArcCycle_VertexOnMesh.push_back(outArcCycle_VertexOnMesh[0]);
// //
// return;
//}
bool MapLoopsBackToMeshLevelSetAndArc::VerifyingEmbeddedPath(std::vector<int> &vertices, std::vector<int> &edges) {
for (unsigned int i = 0; i < vertices.size() - 1; i++) {
if (!((inMeshPtr->vecEdge[edges[i]].v0 == vertices[i] &&
inMeshPtr->vecEdge[edges[i]].v1 == vertices[i + 1]) ||
(inMeshPtr->vecEdge[edges[i]].v1 == vertices[i] &&
inMeshPtr->vecEdge[edges[i]].v0 == vertices[i + 1]))
) {
return false;
}
}
return true;
}
| 44.375711 | 186 | 0.580526 | [
"mesh",
"vector"
] |
bb1f93652cded3e2418553995fb1cee7d8efc050 | 3,509 | cc | C++ | oos/src/model/ListPatchBaselinesResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | oos/src/model/ListPatchBaselinesResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | oos/src/model/ListPatchBaselinesResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/oos/model/ListPatchBaselinesResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Oos;
using namespace AlibabaCloud::Oos::Model;
ListPatchBaselinesResult::ListPatchBaselinesResult() :
ServiceResult()
{}
ListPatchBaselinesResult::ListPatchBaselinesResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
ListPatchBaselinesResult::~ListPatchBaselinesResult()
{}
void ListPatchBaselinesResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto allPatchBaselinesNode = value["PatchBaselines"]["PatchBaseline"];
for (auto valuePatchBaselinesPatchBaseline : allPatchBaselinesNode)
{
PatchBaseline patchBaselinesObject;
if(!valuePatchBaselinesPatchBaseline["Id"].isNull())
patchBaselinesObject.id = valuePatchBaselinesPatchBaseline["Id"].asString();
if(!valuePatchBaselinesPatchBaseline["Name"].isNull())
patchBaselinesObject.name = valuePatchBaselinesPatchBaseline["Name"].asString();
if(!valuePatchBaselinesPatchBaseline["CreatedDate"].isNull())
patchBaselinesObject.createdDate = valuePatchBaselinesPatchBaseline["CreatedDate"].asString();
if(!valuePatchBaselinesPatchBaseline["CreatedBy"].isNull())
patchBaselinesObject.createdBy = valuePatchBaselinesPatchBaseline["CreatedBy"].asString();
if(!valuePatchBaselinesPatchBaseline["UpdatedDate"].isNull())
patchBaselinesObject.updatedDate = valuePatchBaselinesPatchBaseline["UpdatedDate"].asString();
if(!valuePatchBaselinesPatchBaseline["UpdatedBy"].isNull())
patchBaselinesObject.updatedBy = valuePatchBaselinesPatchBaseline["UpdatedBy"].asString();
if(!valuePatchBaselinesPatchBaseline["Description"].isNull())
patchBaselinesObject.description = valuePatchBaselinesPatchBaseline["Description"].asString();
if(!valuePatchBaselinesPatchBaseline["ShareType"].isNull())
patchBaselinesObject.shareType = valuePatchBaselinesPatchBaseline["ShareType"].asString();
if(!valuePatchBaselinesPatchBaseline["OperationSystem"].isNull())
patchBaselinesObject.operationSystem = valuePatchBaselinesPatchBaseline["OperationSystem"].asString();
if(!valuePatchBaselinesPatchBaseline["IsDefault"].isNull())
patchBaselinesObject.isDefault = valuePatchBaselinesPatchBaseline["IsDefault"].asString() == "true";
patchBaselines_.push_back(patchBaselinesObject);
}
if(!value["MaxResults"].isNull())
maxResults_ = std::stoi(value["MaxResults"].asString());
if(!value["NextToken"].isNull())
nextToken_ = value["NextToken"].asString();
}
std::string ListPatchBaselinesResult::getNextToken()const
{
return nextToken_;
}
int ListPatchBaselinesResult::getMaxResults()const
{
return maxResults_;
}
std::vector<ListPatchBaselinesResult::PatchBaseline> ListPatchBaselinesResult::getPatchBaselines()const
{
return patchBaselines_;
}
| 38.988889 | 105 | 0.787689 | [
"vector",
"model"
] |
bb22d6c0915af2c689cc5ada7a1411d9e979cd6a | 16,080 | cpp | C++ | src/mongo/s/catalog_cache_test.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/s/catalog_cache_test.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/s/catalog_cache_test.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2018-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* 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
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/platform/basic.h"
#include <boost/optional/optional_io.hpp>
#include "mongo/s/catalog/type_database_gen.h"
#include "mongo/s/catalog_cache.h"
#include "mongo/s/catalog_cache_loader_mock.h"
#include "mongo/s/sharding_router_test_fixture.h"
#include "mongo/s/stale_exception.h"
#include "mongo/s/type_collection_common_types_gen.h"
#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kDefault
namespace mongo {
namespace {
class CatalogCacheTest : public ShardingTestFixture {
protected:
void setUp() override {
ShardingTestFixture::setUp();
// Setup dummy config server
setRemote(kConfigHostAndPort);
configTargeter()->setFindHostReturnValue(kConfigHostAndPort);
// Setup catalogCache with mock loader
_catalogCacheLoader = std::make_shared<CatalogCacheLoaderMock>();
_catalogCache = std::make_unique<CatalogCache>(getServiceContext(), *_catalogCacheLoader);
// Populate the shardRegistry with the shards from kShards vector
std::vector<std::tuple<ShardId, HostAndPort>> shardInfos;
for (const auto& shardId : kShards) {
shardInfos.emplace_back(
std::make_tuple(shardId, HostAndPort(shardId.toString(), kDummyPort)));
}
addRemoteShards(shardInfos);
};
class ScopedCollectionProvider {
public:
ScopedCollectionProvider(std::shared_ptr<CatalogCacheLoaderMock> catalogCacheLoader,
const StatusWith<CollectionType>& swCollection)
: _catalogCacheLoader(catalogCacheLoader) {
_catalogCacheLoader->setCollectionRefreshReturnValue(swCollection);
}
~ScopedCollectionProvider() {
_catalogCacheLoader->clearCollectionReturnValue();
}
private:
std::shared_ptr<CatalogCacheLoaderMock> _catalogCacheLoader;
};
ScopedCollectionProvider scopedCollectionProvider(
const StatusWith<CollectionType>& swCollection) {
return {_catalogCacheLoader, swCollection};
}
class ScopedChunksProvider {
public:
ScopedChunksProvider(std::shared_ptr<CatalogCacheLoaderMock> catalogCacheLoader,
const StatusWith<std::vector<ChunkType>>& swChunks)
: _catalogCacheLoader(catalogCacheLoader) {
_catalogCacheLoader->setChunkRefreshReturnValue(swChunks);
}
~ScopedChunksProvider() {
_catalogCacheLoader->clearChunksReturnValue();
}
private:
std::shared_ptr<CatalogCacheLoaderMock> _catalogCacheLoader;
};
ScopedChunksProvider scopedChunksProvider(const StatusWith<std::vector<ChunkType>>& swChunks) {
return {_catalogCacheLoader, swChunks};
}
class ScopedDatabaseProvider {
public:
ScopedDatabaseProvider(std::shared_ptr<CatalogCacheLoaderMock> catalogCacheLoader,
const StatusWith<DatabaseType>& swDatabase)
: _catalogCacheLoader(catalogCacheLoader) {
_catalogCacheLoader->setDatabaseRefreshReturnValue(swDatabase);
}
~ScopedDatabaseProvider() {
_catalogCacheLoader->clearDatabaseReturnValue();
}
private:
std::shared_ptr<CatalogCacheLoaderMock> _catalogCacheLoader;
};
ScopedDatabaseProvider scopedDatabaseProvider(const StatusWith<DatabaseType>& swDatabase) {
return {_catalogCacheLoader, swDatabase};
}
void loadDatabases(const std::vector<DatabaseType>& databases) {
for (const auto& db : databases) {
const auto scopedDbProvider = scopedDatabaseProvider(db);
const auto swDatabase = _catalogCache->getDatabase(operationContext(), db.getName());
ASSERT_OK(swDatabase.getStatus());
}
}
void loadCollection(const ChunkVersion& version) {
const auto coll = makeCollectionType(version);
const auto scopedCollProv = scopedCollectionProvider(coll);
const auto scopedChunksProv = scopedChunksProvider(makeChunks(version));
const auto swChunkManager =
_catalogCache->getCollectionRoutingInfo(operationContext(), coll.getNss());
ASSERT_OK(swChunkManager.getStatus());
}
void loadUnshardedCollection(const NamespaceString& nss) {
const auto scopedCollProvider =
scopedCollectionProvider(Status(ErrorCodes::NamespaceNotFound, "collection not found"));
const auto swChunkManager =
_catalogCache->getCollectionRoutingInfo(operationContext(), nss);
ASSERT_OK(swChunkManager.getStatus());
}
std::vector<ChunkType> makeChunks(ChunkVersion version) {
ChunkType chunk(kUUID,
{kShardKeyPattern.getKeyPattern().globalMin(),
kShardKeyPattern.getKeyPattern().globalMax()},
version,
{"0"});
chunk.setName(OID::gen());
return {chunk};
}
CollectionType makeCollectionType(const ChunkVersion& collVersion) {
return {kNss,
collVersion.epoch(),
collVersion.getTimestamp(),
Date_t::now(),
kUUID,
kShardKeyPattern.getKeyPattern()};
}
const NamespaceString kNss{"catalgoCacheTestDB.foo"};
const UUID kUUID = UUID::gen();
const std::string kPattern{"_id"};
const ShardKeyPattern kShardKeyPattern{BSON(kPattern << 1)};
const int kDummyPort{12345};
const HostAndPort kConfigHostAndPort{"DummyConfig", kDummyPort};
const std::vector<ShardId> kShards{{"0"}, {"1"}};
std::shared_ptr<CatalogCacheLoaderMock> _catalogCacheLoader;
std::unique_ptr<CatalogCache> _catalogCache;
};
TEST_F(CatalogCacheTest, GetDatabase) {
const auto dbName = "testDB";
const auto dbVersion = DatabaseVersion(UUID::gen(), Timestamp(1, 1));
_catalogCacheLoader->setDatabaseRefreshReturnValue(DatabaseType(dbName, kShards[0], dbVersion));
const auto swDatabase = _catalogCache->getDatabase(operationContext(), dbName);
ASSERT_OK(swDatabase.getStatus());
const auto cachedDb = swDatabase.getValue();
ASSERT_EQ(cachedDb->getPrimary(), kShards[0]);
ASSERT_EQ(cachedDb->getVersion().getUuid(), dbVersion.getUuid());
ASSERT_EQ(cachedDb->getVersion().getLastMod(), dbVersion.getLastMod());
}
TEST_F(CatalogCacheTest, GetCachedDatabase) {
const auto dbName = "testDB";
const auto dbVersion = DatabaseVersion(UUID::gen(), Timestamp(1, 1));
loadDatabases({DatabaseType(dbName, kShards[0], dbVersion)});
const auto swDatabase = _catalogCache->getDatabase(operationContext(), dbName);
ASSERT_OK(swDatabase.getStatus());
const auto cachedDb = swDatabase.getValue();
ASSERT_EQ(cachedDb->getPrimary(), kShards[0]);
ASSERT_EQ(cachedDb->getVersion().getUuid(), dbVersion.getUuid());
ASSERT_EQ(cachedDb->getVersion().getLastMod(), dbVersion.getLastMod());
}
TEST_F(CatalogCacheTest, GetDatabaseDrop) {
const auto dbName = "testDB";
const auto dbVersion = DatabaseVersion(UUID::gen(), Timestamp(1, 1));
_catalogCacheLoader->setDatabaseRefreshReturnValue(DatabaseType(dbName, kShards[0], dbVersion));
// The CatalogCache doesn't have any valid info about this DB and finds a new DatabaseType
auto swDatabase = _catalogCache->getDatabase(operationContext(), dbName);
ASSERT_OK(swDatabase.getStatus());
const auto cachedDb = swDatabase.getValue();
ASSERT_EQ(cachedDb->getVersion().getUuid(), dbVersion.getUuid());
ASSERT_EQ(cachedDb->getVersion().getLastMod(), dbVersion.getLastMod());
// Advancing the timeInStore, e.g. because of a movePrimary
_catalogCache->onStaleDatabaseVersion(dbName, dbVersion.makeUpdated());
// However, when this CatalogCache asks to the loader for the new info associated to dbName it
// didn't find any (i.e. the database was dropped)
_catalogCacheLoader->setDatabaseRefreshReturnValue(
Status(ErrorCodes::NamespaceNotFound, "dummy errmsg"));
// Finally, the CatalogCache shouldn't find the Database
swDatabase = _catalogCache->getDatabase(operationContext(), dbName);
ASSERT_EQUALS(ErrorCodes::NamespaceNotFound, swDatabase.getStatus());
}
TEST_F(CatalogCacheTest, InvalidateSingleDbOnShardRemoval) {
const auto dbName = "testDB";
const auto dbVersion = DatabaseVersion(UUID::gen(), Timestamp(1, 1));
loadDatabases({DatabaseType(dbName, kShards[0], dbVersion)});
_catalogCache->invalidateEntriesThatReferenceShard(kShards[0]);
_catalogCacheLoader->setDatabaseRefreshReturnValue(DatabaseType(dbName, kShards[1], dbVersion));
const auto swDatabase = _catalogCache->getDatabase(operationContext(), dbName);
ASSERT_OK(swDatabase.getStatus());
auto cachedDb = swDatabase.getValue();
ASSERT_EQ(cachedDb->getPrimary(), kShards[1]);
}
TEST_F(CatalogCacheTest, OnStaleDatabaseVersionNoVersion) {
// onStaleDatabaseVesrsion must invalidate the database entry if invoked with no version
const auto dbVersion = DatabaseVersion(UUID::gen(), Timestamp(1, 1));
loadDatabases({DatabaseType(kNss.db().toString(), kShards[0], dbVersion)});
_catalogCache->onStaleDatabaseVersion(kNss.db(), boost::none);
const auto status = _catalogCache->getDatabase(operationContext(), kNss.db()).getStatus();
ASSERT(status == ErrorCodes::InternalError);
}
TEST_F(CatalogCacheTest, OnStaleShardVersionWithSameVersion) {
const auto dbVersion = DatabaseVersion(UUID::gen(), Timestamp(1, 1));
const auto cachedCollVersion = ChunkVersion(1, 0, OID::gen(), Timestamp(1, 1));
loadDatabases({DatabaseType(kNss.db().toString(), kShards[0], dbVersion)});
loadCollection(cachedCollVersion);
_catalogCache->invalidateShardOrEntireCollectionEntryForShardedCollection(
kNss, cachedCollVersion, kShards[0]);
ASSERT_OK(_catalogCache->getCollectionRoutingInfo(operationContext(), kNss).getStatus());
}
TEST_F(CatalogCacheTest, OnStaleShardVersionWithNoVersion) {
const auto dbVersion = DatabaseVersion(UUID::gen(), Timestamp(1, 1));
const auto cachedCollVersion = ChunkVersion(1, 0, OID::gen(), Timestamp(1, 1));
loadDatabases({DatabaseType(kNss.db().toString(), kShards[0], dbVersion)});
loadCollection(cachedCollVersion);
_catalogCache->invalidateShardOrEntireCollectionEntryForShardedCollection(
kNss, boost::none, kShards[0]);
const auto status =
_catalogCache->getCollectionRoutingInfo(operationContext(), kNss).getStatus();
ASSERT(status == ErrorCodes::InternalError);
}
TEST_F(CatalogCacheTest, OnStaleShardVersionWithGraterVersion) {
const auto dbVersion = DatabaseVersion(UUID::gen(), Timestamp(1, 1));
const auto cachedCollVersion = ChunkVersion(1, 0, OID::gen(), Timestamp(1, 1));
const auto wantedCollVersion =
ChunkVersion(2, 0, cachedCollVersion.epoch(), cachedCollVersion.getTimestamp());
loadDatabases({DatabaseType(kNss.db().toString(), kShards[0], dbVersion)});
loadCollection(cachedCollVersion);
_catalogCache->invalidateShardOrEntireCollectionEntryForShardedCollection(
kNss, wantedCollVersion, kShards[0]);
const auto status =
_catalogCache->getCollectionRoutingInfo(operationContext(), kNss).getStatus();
ASSERT(status == ErrorCodes::InternalError);
}
TEST_F(CatalogCacheTest, TimeseriesFieldsAreProperlyPropagatedOnCC) {
const auto dbVersion = DatabaseVersion(UUID::gen(), Timestamp(1, 1));
const auto epoch = OID::gen();
const auto version = ChunkVersion(1, 0, epoch, Timestamp(42));
loadDatabases({DatabaseType(kNss.db().toString(), kShards[0], dbVersion)});
auto coll = makeCollectionType(version);
auto chunks = makeChunks(version);
auto timeseriesOptions = TimeseriesOptions("fieldName");
// 1st refresh: we should find a bucket granularity of seconds (default)
{
TypeCollectionTimeseriesFields tsFields;
tsFields.setTimeseriesOptions(timeseriesOptions);
coll.setTimeseriesFields(tsFields);
const auto scopedCollProv = scopedCollectionProvider(coll);
const auto scopedChunksProv = scopedChunksProvider(chunks);
const auto swChunkManager =
_catalogCache->getCollectionRoutingInfoWithRefresh(operationContext(), coll.getNss());
ASSERT_OK(swChunkManager.getStatus());
const auto& chunkManager = swChunkManager.getValue();
ASSERT(chunkManager.getTimeseriesFields().is_initialized());
ASSERT(chunkManager.getTimeseriesFields()->getGranularity() ==
BucketGranularityEnum::Seconds);
}
// 2nd refresh: we should find a bucket granularity of hours
{
TypeCollectionTimeseriesFields tsFields;
timeseriesOptions.setGranularity(BucketGranularityEnum::Hours);
tsFields.setTimeseriesOptions(timeseriesOptions);
coll.setTimeseriesFields(tsFields);
auto& lastChunk = chunks.back();
ChunkVersion newCollectionVersion = lastChunk.getVersion();
newCollectionVersion.incMinor();
lastChunk.setVersion(newCollectionVersion);
const auto scopedCollProv = scopedCollectionProvider(coll);
const auto scopedChunksProv = scopedChunksProvider(std::vector{lastChunk});
const auto swChunkManager =
_catalogCache->getCollectionRoutingInfoWithRefresh(operationContext(), coll.getNss());
ASSERT_OK(swChunkManager.getStatus());
const auto& chunkManager = swChunkManager.getValue();
ASSERT(chunkManager.getTimeseriesFields().is_initialized());
ASSERT(chunkManager.getTimeseriesFields()->getGranularity() ==
BucketGranularityEnum::Hours);
}
}
TEST_F(CatalogCacheTest, LookupCollectionWithInvalidOptions) {
const auto dbVersion = DatabaseVersion(UUID::gen(), Timestamp(1, 1));
const auto epoch = OID::gen();
const auto version = ChunkVersion(1, 0, epoch, Timestamp(42));
loadDatabases({DatabaseType(kNss.db().toString(), kShards[0], dbVersion)});
auto coll = makeCollectionType(version);
const auto scopedCollProv = scopedCollectionProvider(coll);
const auto scopedChunksProv = scopedChunksProvider(StatusWith<std::vector<ChunkType>>(
ErrorCodes::InvalidOptions, "Testing error with invalid options"));
const auto swChunkManager =
_catalogCache->getCollectionRoutingInfoWithRefresh(operationContext(), coll.getNss());
ASSERT_EQUALS(swChunkManager.getStatus(), ErrorCodes::InvalidOptions);
}
} // namespace
} // namespace mongo
| 42.204724 | 100 | 0.711007 | [
"vector"
] |
bb25899c84f90bdbe991af556e5903d1074ca936 | 387 | inl | C++ | libiqxmlrpc/value_type.inl | kborkows/libiqxmlrpc | 046ac8a55b1b674f7406442dee533e1ecbfbb88d | [
"BSD-2-Clause"
] | 12 | 2016-01-20T15:25:30.000Z | 2022-03-02T20:21:01.000Z | libiqxmlrpc/value_type.inl | kborkows/libiqxmlrpc | 046ac8a55b1b674f7406442dee533e1ecbfbb88d | [
"BSD-2-Clause"
] | 11 | 2016-06-07T11:48:47.000Z | 2021-01-24T14:20:15.000Z | libiqxmlrpc/value_type.inl | kborkows/libiqxmlrpc | 046ac8a55b1b674f7406442dee533e1ecbfbb88d | [
"BSD-2-Clause"
] | 9 | 2016-05-02T16:05:27.000Z | 2020-10-09T07:43:03.000Z | // Libiqxmlrpc - an object-oriented XML-RPC solution.
// Copyright (C) 2013 Anton Dedov
#ifndef _iqxmlrpc_value_type_inl_
#define _iqxmlrpc_value_type_inl_
#include "value.h"
namespace iqxmlrpc {
template <class In>
void Array::assign( In first, In last )
{
clear();
for( ; first != last; ++first )
values.push_back( new Value(*first) );
}
} // namespace iqxmlrpc
#endif
| 17.590909 | 54 | 0.702842 | [
"object"
] |
bb262dc1df8a1a437e4cd8082108cb5bc9150d4b | 3,156 | cpp | C++ | src/apps/icon-o-matic/transformable/TransformPointsBox.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 1,338 | 2015-01-03T20:06:56.000Z | 2022-03-26T13:49:54.000Z | src/apps/icon-o-matic/transformable/TransformPointsBox.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 15 | 2015-01-17T22:19:32.000Z | 2021-12-20T12:35:00.000Z | src/apps/icon-o-matic/transformable/TransformPointsBox.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 350 | 2015-01-08T14:15:27.000Z | 2022-03-21T18:14:35.000Z | /*
* Copyright 2006, Haiku. All rights reserved.
* Distributed under the terms of the MIT License.
*
* Authors:
* Stephan Aßmus <superstippi@gmx.de>
*/
#include "TransformPointsBox.h"
#include <new>
#include <stdio.h>
#include <string.h>
#include "StateView.h"
#include "TransformPointsCommand.h"
#include "VectorPath.h"
using std::nothrow;
// constructor
TransformPointsBox::TransformPointsBox(CanvasView* view,
PathManipulator* manipulator,
VectorPath* path,
const int32* indices,
int32 count)
: CanvasTransformBox(view),
fManipulator(manipulator),
fPath(path),
fIndices(path && count > 0 ? new (nothrow) int32[count] : NULL),
fCount(count),
fPoints(count > 0 ? new (nothrow) control_point[count] : NULL)
{
fPath->AcquireReference();
BRect bounds(0, 0, -1, -1);
if (fPoints && fIndices) {
// copy indices
memcpy(fIndices, indices, fCount * sizeof(int32));
// make a copy of the points as they are and calculate bounds
for (int32 i = 0; i < fCount; i++) {
if (fPath->GetPointsAt(fIndices[i], fPoints[i].point,
fPoints[i].point_in,
fPoints[i].point_out,
&fPoints[i].connected)) {
BRect dummy(fPoints[i].point, fPoints[i].point);
if (i == 0) {
bounds = dummy;
} else {
bounds = bounds | dummy;
}
dummy.Set(fPoints[i].point_in.x, fPoints[i].point_in.y,
fPoints[i].point_in.x, fPoints[i].point_in.y);
bounds = bounds | dummy;
dummy.Set(fPoints[i].point_out.x, fPoints[i].point_out.y,
fPoints[i].point_out.x, fPoints[i].point_out.y);
bounds = bounds | dummy;
} else {
memset((void*)&fPoints[i], 0, sizeof(control_point));
}
}
}
SetBox(bounds);
}
// destructor
TransformPointsBox::~TransformPointsBox()
{
delete[] fIndices;
delete[] fPoints;
fPath->ReleaseReference();
}
// #pragma mark -
// ObjectChanged
void
TransformPointsBox::ObjectChanged(const Observable* object)
{
}
// #pragma mark -
// Update
void
TransformPointsBox::Update(bool deep)
{
BRect r = Bounds();
TransformBox::Update(deep);
BRect dirty(r | Bounds());
dirty.InsetBy(-8, -8);
fView->Invalidate(dirty);
if (!deep || !fIndices || !fPoints)
return;
for (int32 i = 0; i < fCount; i++) {
BPoint transformed = fPoints[i].point;
BPoint transformedIn = fPoints[i].point_in;
BPoint transformedOut = fPoints[i].point_out;
Transform(&transformed);
Transform(&transformedIn);
Transform(&transformedOut);
fPath->SetPoint(fIndices[i], transformed,
transformedIn,
transformedOut,
fPoints[i].connected);
}
}
// MakeCommand
TransformCommand*
TransformPointsBox::MakeCommand(const char* commandName,
uint32 nameIndex)
{
return new TransformPointsCommand(this, fPath,
fIndices,
fPoints,
fCount,
Pivot(),
Translation(),
LocalRotation(),
LocalXScale(),
LocalYScale(),
commandName,
nameIndex);
}
// #pragma mark -
// Cancel
void
TransformPointsBox::Cancel()
{
SetTransformation(B_ORIGIN, B_ORIGIN, 0.0, 1.0, 1.0);
}
| 21.324324 | 67 | 0.636882 | [
"object",
"transform"
] |
bb26c2aee0b92d0c35147b054d0ee62b9fbde2db | 22,610 | cpp | C++ | src/ri/Texture.cpp | tuxalin/vulkanri | a64897a31fba30c74b18308c59f70ea16767f578 | [
"WTFPL"
] | 5 | 2019-10-04T09:50:33.000Z | 2022-02-05T15:52:22.000Z | src/ri/Texture.cpp | RobertBeckebans/vulkanri | a64897a31fba30c74b18308c59f70ea16767f578 | [
"WTFPL"
] | 20 | 2017-11-22T22:58:06.000Z | 2019-02-19T22:18:48.000Z | src/ri/Texture.cpp | RobertBeckebans/vulkanri | a64897a31fba30c74b18308c59f70ea16767f578 | [
"WTFPL"
] | 1 | 2019-10-04T09:50:36.000Z | 2019-10-04T09:50:36.000Z |
#include <ri/Texture.h>
#include <ri/Buffer.h>
#include <ri/CommandBuffer.h>
#include <ri/DeviceContext.h>
namespace ri
{
namespace detail
{
const ri::Texture* createReferenceTexture(VkImage handle, int type, int format, const Sizei& size)
{
return new ri::Texture(handle, TextureType::from(type), ColorFormat::from(format), size);
}
VkImageView getImageViewHandle(const ri::Texture& texture)
{
return texture.m_view;
}
VkImageAspectFlags getImageAspectFlags(VkFormat format)
{
VkImageAspectFlags flags;
if (format == VK_FORMAT_D32_SFLOAT_S8_UINT || format == VK_FORMAT_D24_UNORM_S8_UINT)
{
flags = VK_IMAGE_ASPECT_STENCIL_BIT | VK_IMAGE_ASPECT_DEPTH_BIT;
}
else if (format == VK_FORMAT_D32_SFLOAT)
{
flags = VK_IMAGE_ASPECT_DEPTH_BIT;
}
else
{
flags = VK_IMAGE_ASPECT_COLOR_BIT;
}
return flags;
}
VkImageType getImageType(int type)
{
switch (type)
{
case ri::TextureType::e1D:
case ri::TextureType::eArray1D:
return VK_IMAGE_TYPE_1D;
case ri::TextureType::e2D:
case ri::TextureType::eArray2D:
case ri::TextureType::eCube:
return VK_IMAGE_TYPE_2D;
case ri::TextureType::e3D:
return VK_IMAGE_TYPE_3D;
default:
assert(false);
return VK_IMAGE_TYPE_2D;
}
}
TextureDescriptorInfo getTextureDescriptorInfo(const Texture& texture)
{
assert(texture.m_view);
assert(texture.m_sampler);
return TextureDescriptorInfo({texture.m_view, texture.m_sampler, (VkImageLayout)texture.m_layout});
}
VkImageView createExtraImageView(const Texture& texture, uint32_t baseMipLevel, uint32_t baseArrayLayer)
{
auto view = texture.createImageView(VK_IMAGE_ASPECT_COLOR_BIT, baseMipLevel, baseArrayLayer);
texture.m_extraViews.push_back(view);
return view;
}
}
namespace
{
uint32_t findMemoryIndex(const VkPhysicalDeviceMemoryProperties& memProperties, uint32_t typeFilter,
VkMemoryPropertyFlags flags)
{
size_t i = 0;
auto found = std::find_if(memProperties.memoryTypes, memProperties.memoryTypes + memProperties.memoryTypeCount,
[typeFilter, flags, &i](const auto& memoryType) {
return (typeFilter & (1 << i++)) && (memoryType.propertyFlags & flags) == flags;
});
assert(found != (memProperties.memoryTypes + memProperties.memoryTypeCount));
return i - 1;
}
}
Texture::Texture(const DeviceContext& device, const TextureParams& params)
: m_device(detail::getVkHandle(device))
, m_type(params.type)
, m_format(params.format)
, m_size(params.size)
, m_mipLevels(params.mipLevels ? params.mipLevels
: (uint32_t)floor(log2(std::max(params.size.width, params.size.height))) + 1)
, m_arrayLevels(m_type == TextureType::eCube ? 6 : params.arrayLevels)
{
assert(params.flags);
#ifndef NDEBUG
const TextureProperties props =
device.textureProperties(params.format, params.type, TextureTiling::eOptimal, params.flags);
assert(props.sampleCounts >= params.samples);
assert(props.maxExtent.width >= params.size.width);
assert(props.maxExtent.height >= params.size.height);
assert(props.maxExtent.depth >= params.depth);
assert(props.maxMipLevels >= m_mipLevels);
assert(props.maxArrayLayers >= params.arrayLevels);
#endif
createImage(params);
allocateMemory(device, params);
if (params.flags & TextureUsageFlags::eSampled)
{
createSampler(params.samplerParams);
m_view = createImageView(VK_IMAGE_ASPECT_COLOR_BIT, 0, 0);
}
else if (m_format == ColorFormat::eDepth32)
{
m_view = createImageView(VK_IMAGE_ASPECT_DEPTH_BIT, 0, 0);
}
}
Texture::Texture(VkImage handle, TextureType type, ColorFormat format, const Sizei& size)
: RenderObject<VkImage>(handle)
, m_type(type)
, m_format(format)
, m_size(size)
, m_arrayLevels(0)
{
}
Texture::~Texture()
{
if (m_device)
{
vkDestroyImage(m_device, m_handle, nullptr);
vkFreeMemory(m_device, m_memory, nullptr);
vkDestroyImageView(m_device, m_view, nullptr);
vkDestroySampler(m_device, m_sampler, nullptr);
for (auto view : m_extraViews)
vkDestroyImageView(m_device, view, nullptr);
}
}
void Texture::copy(const Buffer& src, const CopyParams& params, CommandBuffer& commandBuffer)
{
assert(Sizei(params.offsetX + params.size.width, params.offsetY + params.size.height) <= m_size);
const TextureLayoutType dstTransferLayout(VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
if (params.oldLayout != dstTransferLayout)
transitionImageLayout(params.oldLayout, dstTransferLayout, commandBuffer);
// copy buffer to image
assert((m_arrayLevels * m_size.pixelCount() * sizeof(uint32_t)) < src.bytes());
std::vector<VkBufferImageCopy> bufferCopyRegions;
VkBufferImageCopy region = {};
region.bufferOffset = params.bufferOffset;
region.bufferRowLength = 0;
region.bufferImageHeight = 0;
region.imageSubresource.aspectMask = detail::getImageAspectFlags((VkFormat)m_format);
region.imageSubresource.mipLevel = params.mipLevel;
region.imageSubresource.baseArrayLayer = params.baseArrayLayer;
region.imageSubresource.layerCount = m_arrayLevels;
const Sizei size = params.size.width == 0 || params.size.height == 0 ? m_size : params.size;
region.imageOffset = {params.offsetX, params.offsetY, params.offsetZ};
region.imageExtent = {size.width, size.height, params.depth};
bufferCopyRegions.push_back(region);
vkCmdCopyBufferToImage(detail::getVkHandle(commandBuffer), detail::getVkHandle(src), m_handle,
(VkImageLayout)dstTransferLayout, bufferCopyRegions.size(), bufferCopyRegions.data());
if (dstTransferLayout != params.finalLayout)
transitionImageLayout(dstTransferLayout, params.finalLayout, false, commandBuffer);
}
void Texture::generateMipMaps(CommandBuffer& commandBuffer)
{
assert(m_format != ColorFormat::eDepth32 && m_format != ColorFormat::eDepth24Stencil8 &&
m_format != ColorFormat::eDepth32Stencil8);
VkImageSubresourceRange mipSubRange = {};
mipSubRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
mipSubRange.baseMipLevel = 0;
mipSubRange.levelCount = 1;
mipSubRange.layerCount = m_arrayLevels;
// Transition current mip level to transfer source for read in next iteration
transitionImageLayout(m_layout, TextureLayoutType::eTransferSrcOptimal, false, mipSubRange, commandBuffer);
// Copy down mips from n-1 to n
for (uint32_t i = 1; i < m_mipLevels; i++)
{
VkImageBlit imageBlit {};
// Source
imageBlit.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
imageBlit.srcSubresource.layerCount = m_arrayLevels;
imageBlit.srcSubresource.mipLevel = i - 1;
imageBlit.srcOffsets[1].x = int32_t(m_size.width >> (i - 1));
imageBlit.srcOffsets[1].y = int32_t(m_size.height >> (i - 1));
imageBlit.srcOffsets[1].z = 1;
// Destination
imageBlit.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
imageBlit.dstSubresource.layerCount = m_arrayLevels;
imageBlit.dstSubresource.mipLevel = i;
imageBlit.dstOffsets[1].x = int32_t(m_size.width >> i);
imageBlit.dstOffsets[1].y = int32_t(m_size.height >> i);
imageBlit.dstOffsets[1].z = 1;
mipSubRange.baseMipLevel = i;
// Transition current mip level to transfer destination
transitionImageLayout(TextureLayoutType::eUndefined, TextureLayoutType::eTransferDstOptimal, //
false, mipSubRange, commandBuffer);
// Blit from previous level
vkCmdBlitImage(detail::getVkHandle(commandBuffer),
m_handle,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
m_handle,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1,
&imageBlit,
VK_FILTER_LINEAR);
// Transition current mip level to transfer source for read in next iteration
transitionImageLayout(TextureLayoutType::eTransferDstOptimal, TextureLayoutType::eTransferSrcOptimal, false,
mipSubRange, commandBuffer);
}
// After the loop, all mip layers transfer src, so transition all to shader access
VkImageSubresourceRange subresourceRange = {};
subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
subresourceRange.baseMipLevel = 0;
subresourceRange.levelCount = m_mipLevels;
subresourceRange.baseArrayLayer = 0;
subresourceRange.layerCount = m_arrayLevels;
transitionImageLayout(TextureLayoutType::eTransferSrcOptimal, m_layout, //
false, subresourceRange, commandBuffer);
}
inline void Texture::createImage(const TextureParams& params)
{
VkImageCreateInfo imageInfo = {};
imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
imageInfo.imageType = detail::getImageType(params.type.get());
imageInfo.extent.width = static_cast<uint32_t>(params.size.width);
imageInfo.extent.height = static_cast<uint32_t>(params.size.height);
imageInfo.extent.depth = params.depth;
imageInfo.mipLevels = m_mipLevels;
imageInfo.arrayLayers = m_arrayLevels;
imageInfo.format = (VkFormat)params.format;
imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
imageInfo.usage = (VkImageUsageFlags)params.flags;
// the image will only be used by one queue family: the one that supports graphics and transfer operations.
imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
assert(math::isPowerOfTwo(params.samples));
imageInfo.samples = (VkSampleCountFlagBits)params.samples;
imageInfo.flags = 0;
if (m_type == TextureType::eCube)
imageInfo.flags = VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;
RI_CHECK_RESULT_MSG("failed to create image") = vkCreateImage(m_device, &imageInfo, nullptr, &m_handle);
}
VkImageView Texture::createImageView(VkImageAspectFlags aspectFlags, uint32_t baseMipLevel,
uint32_t baseArrayLayer) const
{
assert(m_mipLevels > baseMipLevel);
assert(m_arrayLevels > baseArrayLayer);
VkImageView viewHandle = VK_NULL_HANDLE;
VkImageViewCreateInfo viewInfo = {};
viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
viewInfo.image = m_handle;
viewInfo.viewType = (VkImageViewType)m_type;
viewInfo.format = (VkFormat)m_format;
viewInfo.components = {VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G, //
VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A};
viewInfo.subresourceRange.aspectMask = aspectFlags;
viewInfo.subresourceRange.baseMipLevel = baseMipLevel;
viewInfo.subresourceRange.levelCount = m_mipLevels - baseMipLevel;
viewInfo.subresourceRange.baseArrayLayer = baseArrayLayer;
viewInfo.subresourceRange.layerCount = m_arrayLevels - baseArrayLayer;
RI_CHECK_RESULT_MSG("failed to create image view") = vkCreateImageView(m_device, &viewInfo, nullptr, &viewHandle);
return viewHandle;
}
void Texture::createSampler(const SamplerParams& params)
{
assert(params.minLod <= m_mipLevels);
VkSamplerCreateInfo samplerInfo = {};
samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
samplerInfo.magFilter = (VkFilter)params.magFilter;
samplerInfo.minFilter = (VkFilter)params.minFilter;
samplerInfo.addressModeU = (VkSamplerAddressMode)params.addressModeU;
samplerInfo.addressModeV = (VkSamplerAddressMode)params.addressModeV;
samplerInfo.addressModeW = (VkSamplerAddressMode)params.addressModeW;
samplerInfo.anisotropyEnable = params.anisotropyEnable;
samplerInfo.maxAnisotropy = params.maxAnisotropy;
samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
samplerInfo.unnormalizedCoordinates = VK_FALSE;
samplerInfo.compareEnable = params.compareEnable;
samplerInfo.compareOp = (VkCompareOp)params.compareOp;
assert(params.mipmapMode != SamplerParams::eCubic);
samplerInfo.mipmapMode =
params.mipmapMode == SamplerParams::eLinear ? VK_SAMPLER_MIPMAP_MODE_LINEAR : VK_SAMPLER_MIPMAP_MODE_NEAREST;
samplerInfo.mipLodBias = params.mipLodBias;
samplerInfo.minLod = params.minLod;
samplerInfo.maxLod = static_cast<float>(m_mipLevels);
RI_CHECK_RESULT_MSG("failed to create texture sampler") =
vkCreateSampler(m_device, &samplerInfo, nullptr, &m_sampler);
}
inline void Texture::allocateMemory(const DeviceContext& device, const TextureParams& params)
{
VkMemoryRequirements memRequirements;
vkGetImageMemoryRequirements(m_device, m_handle, &memRequirements);
VkMemoryAllocateInfo allocInfo = {};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = memRequirements.size;
const VkPhysicalDeviceMemoryProperties& memProperties = detail::getDeviceMemoryProperties(device);
allocInfo.memoryTypeIndex =
findMemoryIndex(memProperties, memRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
RI_CHECK_RESULT_MSG("failed to allocate image memory") = vkAllocateMemory(m_device, &allocInfo, nullptr, &m_memory);
vkBindImageMemory(m_device, m_handle, m_memory, 0);
}
Texture::PipelineBarrierSettings Texture::getPipelineBarrierSettings(TextureLayoutType oldLayout,
TextureLayoutType newLayout,
bool readAccess,
const VkImageSubresourceRange& subresourceRange)
{
VkImageMemoryBarrier imageMemoryBarrier = {};
imageMemoryBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
imageMemoryBarrier.oldLayout = (VkImageLayout)oldLayout;
imageMemoryBarrier.newLayout = (VkImageLayout)newLayout;
imageMemoryBarrier.image = m_handle;
imageMemoryBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
imageMemoryBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
imageMemoryBarrier.subresourceRange = subresourceRange;
VkPipelineStageFlags srcStageFlags = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
VkPipelineStageFlags dstStageFlags = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
switch (oldLayout.get())
{
case VK_IMAGE_LAYOUT_UNDEFINED:
// Only valid as initial layout, memory contents are not preserved
// Can be accessed directly, no source dependency required
imageMemoryBarrier.srcAccessMask = 0;
break;
case VK_IMAGE_LAYOUT_PREINITIALIZED:
// Only valid as initial layout for linear images, preserves memory contents
// Make sure host writes to the image have been finished
imageMemoryBarrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
// Image is a color attachment
// Make sure any writes to the color buffer have been finished
imageMemoryBarrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
// Image is a depth/stencil attachment
// Make sure any writes to the depth/stencil buffer have been finished
imageMemoryBarrier.srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
// Image is a transfer source
// Make sure any reads from the image have been finished
srcStageFlags = VK_ACCESS_TRANSFER_WRITE_BIT;
imageMemoryBarrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
break;
case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
// Image is read by a shader
// Make sure any shader reads from the image have been finished
imageMemoryBarrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT;
break;
case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
// Old layout is transfer destination
// Make sure any writes to the image have been finished
imageMemoryBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
srcStageFlags = VK_PIPELINE_STAGE_TRANSFER_BIT;
break;
}
switch (newLayout.get())
{
case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
// Transfer source (copy, blit)
// Make sure any reads from the image have been finished
imageMemoryBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
dstStageFlags = VK_PIPELINE_STAGE_TRANSFER_BIT;
break;
case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
case VK_IMAGE_LAYOUT_GENERAL:
// Transfer destination (copy, blit)
// Make sure any writes to the image have been finished
imageMemoryBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
dstStageFlags = VK_PIPELINE_STAGE_TRANSFER_BIT;
break;
case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
// Image will be used as a color attachment
// Make sure any writes to the color buffer have been finished
imageMemoryBarrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
if (readAccess)
imageMemoryBarrier.dstAccessMask |= VK_ACCESS_COLOR_ATTACHMENT_READ_BIT;
dstStageFlags = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
break;
case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
// Image layout will be used as a depth/stencil attachment
// Make sure any writes to depth/stencil buffer have been finished
imageMemoryBarrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
if (readAccess)
imageMemoryBarrier.dstAccessMask |= VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT;
dstStageFlags = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
break;
case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
// Shader read (sampler, input attachment)
imageMemoryBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
dstStageFlags = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_HOST_BIT;
break;
}
if (oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL)
{
dstStageFlags = srcStageFlags = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
}
return std::make_tuple(imageMemoryBarrier, srcStageFlags, dstStageFlags);
}
void Texture::transitionImageLayout(TextureLayoutType oldLayout, TextureLayoutType newLayout, //
bool readAccess, //
VkPipelineStageFlags srcStageFlags, //
VkPipelineStageFlags dstStageFlags, //
const VkImageSubresourceRange& subresourceRange, //
CommandBuffer& commandBuffer)
{
const PipelineBarrierSettings settings =
getPipelineBarrierSettings(oldLayout, newLayout, readAccess, subresourceRange);
VkImageMemoryBarrier imageMemoryBarrier = std::get<0>(settings);
vkCmdPipelineBarrier(detail::getVkHandle(commandBuffer), srcStageFlags, dstStageFlags, 0, 0, nullptr, 0, nullptr, 1,
&imageMemoryBarrier);
}
void Texture::transitionImageLayout(TextureLayoutType oldLayout, TextureLayoutType newLayout, bool readAccess,
CommandBuffer& commandBuffer)
{
VkImageSubresourceRange subresourceRange = {};
subresourceRange.aspectMask = detail::getImageAspectFlags((VkFormat)m_format);
subresourceRange.baseMipLevel = 0;
subresourceRange.levelCount = m_mipLevels;
subresourceRange.baseArrayLayer = 0;
subresourceRange.layerCount = m_arrayLevels;
const PipelineBarrierSettings settings =
getPipelineBarrierSettings(oldLayout, newLayout, readAccess, subresourceRange);
VkImageMemoryBarrier imageMemoryBarrier = std::get<0>(settings);
vkCmdPipelineBarrier(detail::getVkHandle(commandBuffer), std::get<1>(settings), std::get<2>(settings), 0, 0,
nullptr, 0, nullptr, 1, &imageMemoryBarrier);
m_layout = newLayout;
}
void Texture::transitionImageLayout(TextureLayoutType oldLayout, TextureLayoutType newLayout, bool readAccess,
const VkImageSubresourceRange& subresourceRange, CommandBuffer& commandBuffer)
{
const PipelineBarrierSettings settings =
getPipelineBarrierSettings(oldLayout, newLayout, readAccess, subresourceRange);
const VkImageMemoryBarrier imageMemoryBarrier = std::get<0>(settings);
vkCmdPipelineBarrier(detail::getVkHandle(commandBuffer), std::get<1>(settings), std::get<2>(settings), 0, 0,
nullptr, 0, nullptr, 1, &imageMemoryBarrier);
}
} // namespace ri
| 45.676768 | 120 | 0.663025 | [
"vector"
] |
bb296237de395704eaf571c85f6effb6b6e839ec | 374 | cpp | C++ | lonestar/patternmining/debug.cpp | bowu/Galois | 81f619a2bb1bdc95899729f2d96a7da38dd0c0a3 | [
"BSD-3-Clause"
] | null | null | null | lonestar/patternmining/debug.cpp | bowu/Galois | 81f619a2bb1bdc95899729f2d96a7da38dd0c0a3 | [
"BSD-3-Clause"
] | null | null | null | lonestar/patternmining/debug.cpp | bowu/Galois | 81f619a2bb1bdc95899729f2d96a7da38dd0c0a3 | [
"BSD-3-Clause"
] | null | null | null | #include "AutoMiner.h"
// template<class T>
// void print_vector(const std::vector<T> &v)
// {
// std::copy(v.begin(), v.end(), std::ostream_iterator<T>(std::cout, " "));
// //std::cout << std::endl;
// }
//
// void print_vector(std::vector<T> &v)
// {
// std::copy(v.begin(), v.end(), std::ostream_iterator<T>(std::cout, " "));
// //std::cout << std::endl;
// }
| 23.375 | 77 | 0.550802 | [
"vector"
] |
bb2cf60b76460e25cf6d91900d9e4862abae4316 | 46,373 | cc | C++ | Network.cc | karlredgate/redx | c9fe9b43fe8bd36c90cab516470799d417b580ba | [
"MIT"
] | 1 | 2016-03-23T22:04:07.000Z | 2016-03-23T22:04:07.000Z | Network.cc | karlredgate/redx | c9fe9b43fe8bd36c90cab516470799d417b580ba | [
"MIT"
] | null | null | null | Network.cc | karlredgate/redx | c9fe9b43fe8bd36c90cab516470799d417b580ba | [
"MIT"
] | null | null | null |
/*
* Copyright (c) 2012-2021 Karl N. Redgate
*
* 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 Network.cc
* \brief
*
* Can I create a tunnel device or the like that creates a pseudo-interface
* called mgmt0 that can be used by HB etc..?
*
* Make sure to set PID for socket (in NetLink.cc)
*
* Add Interface multicast thread - clone from old ekg
* - sender/receiver
* - started when Interface constructed?
* - stopped in destructor?
* - Should this be a full Thread subclass -- or is there a way to make
* it a simple Thread object with a simple method for run?
*/
#include <asm/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <stdlib.h>
#include <signal.h>
#include <fcntl.h>
#include <time.h>
#include <string.h>
#include <glob.h>
#include <errno.h>
#include <tcl.h>
#include "tcl_util.h"
#include "logger.h"
#include "util.h"
#include "host_table.h"
#include "NetLink.h"
#include "Network.h"
namespace { int debug = 0; }
/**
* Used to iterate through the node list and clear the partner
* bit in all entries.
*/
class ClearNodePartner : public Network::NodeIterator {
public:
ClearNodePartner() {}
virtual ~ClearNodePartner() {}
virtual int operator() ( Network::Node& node ) {
if ( node.not_partner() ) return 0;
log_notice( "clear partner [%s]", node.uuid().to_s() );
node.clear_partner();
return 1;
}
};
/** When a NewLink message is received, create/update interface object.
*
*
*/
void Network::Monitor::receive( NetLink::NewLink *message ) {
bool link_requires_repair = false;
Interface *interface = interfaces[ message->index() ];
if ( interface == NULL ) {
if ( debug > 0 ) {
log_notice( "adding %s(%d) to interface list", message->name(), message->index() );
}
interface = new Network::Interface( interp, message );
interfaces[ message->index() ] = interface;
if ( _manager != NULL ) {
_manager->add_interface( interface );
}
interface->update( message );
if ( interface->is_physical() ) {
// if ( interface->not_private() ) {
// if ( interface->not_captured() ) capture( interface );
// }
if ( interface->has_link() ) {
interface->linkUp( message );
} else {
interface->linkDown( message );
}
}
// This can happen on a bridge device if a shared network is deleted before we
// receive the NewLink event announcing that it has been created.
// Typically this happens if there was a buffer overflow on the Netlink socket.
if ( !interface->exists() ) {
log_notice( "WARNING: interface %s(%d) does not appear to exist, skipping...",
message->name(), message->index() );
return;
}
bool is_bridge = interface->is_bridge();
bool is_physical = interface->is_physical();
log_notice( "checking to see if interface %s(%d) should be brought up: %s %s",
message->name(), message->index(), is_bridge ? "is BRIDGE" : "not BRIDGE",
is_physical ? "is PHYSICAL" : "not PHYSICAL" );
// Temporary code to get around problem where NewLink message arrives
// before /sysfs entries for the bridge are constructed. Otherwise we
// won't bring up the interface and the pulse code will not work.
// Have to check for "net_<N>" names and "biz<N>" names as well due to upgrade.
const char *name = message->name();
if ( ( ( ( name[0] == 'n' ) &&
( name[1] == 'e' ) &&
( name[2] == 't' ) ) ||
( ( name[0] == 'b' ) &&
( name[1] == 'i' ) &&
( name[2] == 'z' ) ) ) &&
( !is_bridge ) ) {
log_notice( "WARNING: interface %s(%d) does not appear to be a bridge, waiting up to 10 seconds",
message->name(), message->index() );
for (int i = 0; i < 10; i++) {
sleep( 1 );
if ( interface->is_bridge() ) {
is_bridge = true;
break;
}
}
if ( interface->not_bridge() ) {
log_notice( "WARNING: interface %s(%d) still does not appear to be a bridge, not bringing it up",
message->name(), message->index() );
}
}
if ( is_bridge or is_physical ) {
bring_up( interface );
log_notice( "brought up interface %s(%d)", message->name(), message->index() );
}
if ( interface->is_up() and interface->is_private() and
interface->not_sync() and interface->not_listening_to("udp6", 123) ) { // NTP
log_notice( "%s is not listening to port 123 on its primary address, restart ntpd",
interface->name() );
system( "/usr/bin/config_ntpd --restart" );
}
} else { // if we do have it ... look for state changes
interface->update( message );
bool report_required = false;
const char *link_message = "";
const char *up_message = "";
const char *running_message = "";
const char *promisc_message = "";
if ( interface->link_changed() ) {
if ( interface->has_link() ) {
interface->linkUp( message );
link_message = ", link up";
if ( interface->is_up() and interface->is_private() and
interface->not_sync() and interface->not_listening_to("udp6", 123) ) { // NTP
log_notice( "%s is not listening to port 123 on its primary address, restart ntpd",
interface->name() );
system( "/usr/bin/config_ntpd --restart" );
}
} else {
interface->linkDown( message );
link_message = ", link down";
interface->clean_topology();
topology_changed();
}
report_required = true;
}
if ( ( interface->has_link() == false ) and interface->bounce_expired() ) {
if ( interface->is_physical() and ( interface->not_private() or interface->is_sync() ) ) {
link_requires_repair = true;
}
}
if ( interface->up_changed() ) {
up_message = interface->is_up() ? ", oper brought up" : ", oper brought down";
report_required = true;
}
if ( interface->running_changed() ) {
running_message = interface->has_link() ? ", started running" : ", stopped running";
report_required = true;
}
if ( interface->promiscuity_changed() ) {
promisc_message = interface->is_promiscuous() ? ", went promiscuous" : ", left promiscuous";
report_required = true;
}
if ( report_required or (debug > 0) ) {
log_notice( "%s(%d): <NewLink>%s%s%s%s", interface->name(), interface->index(),
link_message, up_message, running_message, promisc_message );
}
if ( message->family() == AF_BRIDGE ) {
const char *bridge_name = "UNKNOWN";
int bridge_index = message->bridge_index();
if ( bridge_index != 0 ) {
Interface *bridge = interfaces[ bridge_index ];
if ( bridge != NULL ) bridge_name = bridge->name();
}
log_notice( "%s(%d): added to bridge '%s'",
interface->name(), interface->index(), bridge_name );
}
}
if ( link_requires_repair ) {
if ( interface->has_fault_injected() ) {
log_notice( "%s(%d) fault injected, not repairing link", interface->name(), interface->index() );
} else {
interface->repair_link();
}
}
}
/**
*/
void Network::Monitor::receive( NetLink::DelLink *message ) {
if ( message->index() == 0 ) {
log_warn( "received a DelLink message for inteface index 0 (INVALID)" );
return;
}
Interface *interface = interfaces[ message->index() ];
if ( interface == NULL ) {
const char *name = message->name();
if ( name == NULL ) name = "Unknown";
log_warn( "unknown interface removed: %s(%d)", name, message->index() );
return;
}
interface->update( message );
bool report_required = false; // Change this to false
const char *link_message = "";
const char *up_message = "";
const char *running_message = "";
const char *promisc_message = "";
if ( interface->link_changed() ) {
if ( interface->has_link() ) {
interface->linkUp( message );
link_message = ", link up";
} else {
interface->linkDown( message );
link_message = ", link down";
}
report_required = true;
}
if ( interface->up_changed() ) {
up_message = interface->is_up() ? ", oper brought up" : ", oper brought down";
report_required = true;
}
if ( interface->running_changed() ) {
running_message = interface->has_link() ? ", started running" : ", stopped running";
report_required = true;
}
if ( interface->promiscuity_changed() ) {
promisc_message = interface->is_promiscuous() ? ", went promiscuous" : ", left promiscuous";
report_required = true;
}
if ( report_required or (debug > 0) ) {
log_notice( "%s(%d): <DelLink>%s%s%s%s", interface->name(), interface->index(),
link_message, up_message, running_message, promisc_message );
}
if ( message->family() == AF_BRIDGE ) {
const char *bridge_name = "UNKNOWN";
int bridge_index = message->bridge_index();
if ( bridge_index != 0 ) {
Interface *bridge = interfaces[ bridge_index ];
if ( bridge != NULL ) bridge_name = bridge->name();
}
if ( interface->is_captured() ) {
log_notice( "%s(%d): removed from bridge '%s'",
interface->name(), interface->index(), bridge_name );
} else {
log_notice( "%s(%d): DelLink message from bridge '%s' -- but not removed",
interface->name(), interface->index(), bridge_name );
}
return;
}
if ( message->change() == 0xFFFFFFFF ) {
log_warn( "%s(%d): removed from system", interface->name(), interface->index() );
// stop listener thread
// need Interface to have a handle on its listener thread
interface->remove();
}
}
/**
*/
void Network::Monitor::receive( NetLink::NewRoute *message ) {
if ( debug > 1 ) {
log_info( "Network::Monitor => process NewRoute --> scope %d, family %d\n",
message->scope(),
message->family()
);
}
}
/**
*/
void Network::Monitor::receive( NetLink::DelRoute *message ) {
if ( debug > 1 ) {
log_info( "Network::Monitor => process DelRoute --> scope %d, family %d\n",
message->scope(),
message->family()
);
}
}
/**
*/
void Network::Monitor::receive( NetLink::NewAddress *message ) {
Interface *interface = interfaces[ message->index() ];
if ( interface == NULL ) {
// address was removed from an interface we do not
// track (like a VIF)
return;
}
switch ( message->family() ) {
case AF_INET6: // skip below and attempt to reconfigure
break;
case AF_INET:
log_notice( "IPv4 address added to '%s'", interface->name() );
return;
default:
log_notice( "Unknown address family added to '%s'", interface->name() );
return;
}
if ( interface->is_primary( message->in6_addr() ) ) {
log_notice( "primary ipv6 address added to '%s'", interface->name() );
if ( interface->is_private() and interface->not_sync() and
interface->not_listening_to("udp6", 123) ) { // NTP
log_notice( "%s is not listening to port 123 on its primary address, restart ntpd",
interface->name() );
system( "/usr/bin/config_ntpd --restart" );
}
} else {
if ( debug > 0 ) {
log_notice( "secondary ipv6 address added to '%s', ignoring", interface->name() );
}
}
}
/**
*/
void Network::Monitor::receive( NetLink::DelAddress *message ) {
Interface *interface = interfaces[ message->index() ];
if ( interface == NULL ) {
// address was removed from an interface we do not
// track (like a VIF)
return;
}
switch ( message->family() ) {
case AF_INET6: // skip below and attempt to reconfigure
break;
case AF_INET:
log_notice( "IPv4 address removed from '%s', ignoring", interface->name() );
return;
default:
log_notice( "Unknown address family removed from '%s', ignoring", interface->name() );
return;
}
if ( interface->is_primary( message->in6_addr() ) ) {
if ( debug > 0 ) {
log_notice( "primary ipv6 address removed from '%s', repairing", interface->name() );
}
interface->configure_addresses();
} else {
if ( debug > 0 ) {
log_notice( "secondary ipv6 address removed from '%s', ignoring", interface->name() );
}
}
}
/**
*/
void Network::Monitor::receive( NetLink::NewNeighbor *message ) {
if ( debug > 1 ) {
log_info( "Network::Monitor => process NewNeighbor \n" );
}
}
/**
*/
void Network::Monitor::receive( NetLink::DelNeighbor *message ) {
if ( debug > 1 ) {
log_info( "Network::Monitor => process DelNeighbor\n");
}
}
/**
*/
void Network::Monitor::receive( NetLink::RouteMessage *message ) {
if ( debug > 1 ) {
log_info( "Network::Monitor unknown RouteMessage (%d) -- skipping\n", message->type_code() );
}
}
/**
* \todo should have some internal state that tells us the last message
* we received was an error, and what the error was.
*/
void Network::Monitor::receive( NetLink::RouteError *message ) {
if ( debug > 1 ) {
log_info( "Network::Monitor RouteError %d\n", message->error() );
}
}
/** Send a packet to each interface.
*
* The interface code will prune which interfaces are valid to send to
* based on interface specific policy. Currently, this means priv0
* and bizN bridge interfaces.
*
* See Interface::sendto() method (in Interface.cc) for description
* of how this is done.
*/
int Network::Monitor::sendto( void *message, size_t length, int flags, const struct sockaddr_in6 *address) {
std::map<int, Interface *>::const_iterator iter = interfaces.begin();
while ( iter != interfaces.end() ) {
Network::Interface *interface = iter->second;
if ( interface != NULL ) {
interface->sendto( message, length, flags, address );
}
iter++;
}
return 0;
}
/** Send ICMPv6 neighbor advertisements for each interface.
*
* Iterate through each known priv/biz network and send neighbor
* advertisements out of this interface. This will keep the peer's
* neighbor table up to date for this host.
*
* When looking at the peer's * neighbor table (ip -6 neighbor ls) you
* should see "REACHABLE" for this hosts addresses if this node is up and
* running netmgr.
*
* See the Interface.cc advertise code for how this is done.
*/
int Network::Monitor::advertise() {
std::map<int, Interface *>::const_iterator iter = interfaces.begin();
while ( iter != interfaces.end() ) {
Network::Interface *interface = iter->second;
if ( interface != NULL ) interface->advertise();
iter++;
}
return 0;
}
/** Iterate and call a callback for each Interface.
*/
int Network::Monitor::each_interface( InterfaceIterator& callback ) {
int result = 0;
std::map<int, Interface *>::const_iterator iter = interfaces.begin();
while ( iter != interfaces.end() ) {
Network::Interface *interface = iter->second;
if ( interface != NULL ) result += callback( *interface );
iter++;
}
return result;
}
/** Iterate and call a callback for each Node.
*/
int Network::Monitor::each_node( NodeIterator& callback ) {
int result = 0;
pthread_mutex_lock( &node_table_lock );
for ( int i = 0 ; i < NODE_TABLE_SIZE ; ++i ) {
Network::Node& node = node_table[i];
if ( node.is_invalid() ) continue;
result += callback( node );
}
pthread_mutex_unlock( &node_table_lock );
return result;
}
/** Return the Bridge Interface for a physical Interface that
* has been captured in a Bridge.
*/
Network::Interface *
Network::Monitor::find_bridge_interface( Interface *interface ) {
if ( interface->not_physical() ) return NULL;
if ( interface->not_captured() ) return NULL;
std::map<int, Interface *>::const_iterator iter = interfaces.begin();
while ( iter != interfaces.end() ) {
Network::Interface *interface2 = iter->second;
if ( ( interface2 != NULL ) && interface2->is_bridge() ) {
char path[1024];
sprintf( path, "/sys/class/net/%s/brif/*", interface2->name() );
glob_t paths;
memset(&paths, 0, sizeof(paths));
glob( path, GLOB_NOSORT, NULL, &paths );
for ( size_t i = 0 ; i < paths.gl_pathc ; i++ ) {
if ( strcmp( interface->name(), basename( paths.gl_pathv[i]) ) == 0 ) {
globfree( &paths );
return interface2;
}
}
globfree( &paths );
}
iter++;
}
log_notice( "Unable to find bridge interface for %s", interface->name() );
return NULL;
}
/** Return the physical Interface for a Bridge Interface.
*/
Network::Interface *
Network::Monitor::find_physical_interface( Interface *interface ) {
if ( interface->not_bridge() ) return NULL;
char path[1024];
sprintf( path, "/sys/class/net/%s/brif/*", interface->name() );
glob_t paths;
memset(&paths, 0, sizeof(paths));
glob( path, GLOB_NOSORT, NULL, &paths );
for ( size_t i = 0 ; i < paths.gl_pathc ; i++ ) {
std::map<int, Interface *>::const_iterator iter = interfaces.begin();
while ( iter != interfaces.end() ) {
Network::Interface *interface2 = iter->second;
if ( ( interface2 != NULL ) && interface2->is_physical() ) {
if ( strcmp( interface2->name(), basename( paths.gl_pathv[i]) ) == 0 ) {
globfree( &paths );
return interface2;
}
}
iter++;
}
}
globfree( &paths );
// Note: This happens when the interface has been temporarily removed from the
// bridge by the tunnel code when the tunnel is set up to use the peer's interface.
if ( debug > 0 ) log_notice( "Unable to find physical interface for %s", interface->name() );
return NULL;
}
/**
*/
static bool
send_topology_event( const char *who ) {
log_notice( "%s sending NetTopologyUpdate event to spine", who );
char *event_name = const_cast<char*>("SuperNova::NetTopologyUpdate");
pid_t child = fork();
if ( child < 0 ) {
log_err( "failed to send %s event - couldn't fork", event_name );
return false;
}
if ( child > 0 ) {
int status;
waitpid( child, &status, 0);
return true;
}
char *argv[] = { const_cast<char*>("genevent"), event_name, 0 };
char *envp[] = { 0 };
if ( execve("/usr/lib/spine/bin/genevent", argv, envp) < 0 ) {
log_err( "failed to send %s event - couldn't execve", event_name );
_exit( 0 );
}
// NOT REACHED
return true;
}
/**
*/
void Network::Monitor::topology_changed() {
// If no Manager, send the event ourselves.
if ( _manager != NULL ) {
_manager->topology_changed();
} else {
send_topology_event("Monitor");
}
}
/** Persist the current interface config.
*/
void Network::Monitor::persist_interface_configuration() {
log_notice( "persisting the change in interface configuration" );
FILE *f = fopen( "/etc/udev/rules.d/.tmp", "w" );
std::map<int, Interface *>::const_iterator iter = interfaces.begin();
for ( ; iter != interfaces.end() ; iter++ ) {
Network::Interface *interface = iter->second;
if ( interface == NULL ) continue;
if ( interface->not_physical() ) continue;
// save this interface??
// KERNEL=="eth*", SYSFS{address}=="<mac>", NAME="<newname>"
const unsigned char *mac = interface->mac();
fprintf( f, "KERNEL==\"eth*\", SYSFS{address}==\"%02x:%02x:%02x:%02x:%02x:%02x\", NAME=\"%s\", OPTIONS=\"last_rule\"\n",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5], interface->name() );
}
int fd = fileno(f);
if ( fdatasync(fd) < 0 ) {
log_err( "IO error saving persistent device names" );
}
fclose( f );
rename( "/etc/udev/rules.d/.tmp", "/etc/udev/rules.d/58-net-rename.rules" );
}
/** Capture the interface in a bridge
*
* Bridges are numbered based on the backing ibizN number.
* The number is simply cloned from the backing interface to
* the bridge name.
*/
void Network::Monitor::capture( Interface *interface ) {
if ( interface->has_fault_injected() ) {
log_notice( "%s(%d) fault injected, not capturing in bridge", interface->name(), interface->index() );
return;
}
log_notice( "need to capture '%s'", interface->name() );
int id = 0xdead;
sscanf( interface->name(), "ibiz%d", &id );
if ( id == 0xdead ) {
log_err( "ERROR : invalid interface name for bridge" );
return;
}
char buffer[40];
sprintf( buffer, "biz%d", id );
Bridge *bridge = new Bridge( buffer );
const char *error = bridge->create();
if ( error != NULL ) {
log_err( "ERROR : Failed to create bridge: %s", error );
// \todo when bridge create fails -- what do we do?
return;
}
bridge->set_mac_address( interface->mac() );
if ( bridge->is_tunnelled() ) {
log_warn( "WARNING '%s' is tunnelled, not capturing '%s'", bridge->name(), interface->name() );
} else {
bridge->capture( interface );
}
// Don't need this after creation
delete bridge;
interface->bring_link_up();
}
/** Bring up link and addresses for this interface
*
*/
void Network::Monitor::bring_up( Interface *interface ) {
if ( debug > 0 ) log_notice( "bring up '%s'", interface->name() );
if ( interface->has_fault_injected() ) {
log_notice( "%s(%d) fault injected, not bringing link up", interface->name(), interface->index() );
} else {
interface->bring_link_up();
interface->configure_addresses();
}
interface->create_sockets();
Network::ListenerInterface *listener = factory( interp, this, interface );
listener->thread()->start();
}
/**
*
*/
Network::Node*
Network::Monitor::intern_node( UUID& uuid ) {
int in_use_count = 0;
Network::Node *result = NULL;
Network::Node *available = NULL;
pthread_mutex_lock( &node_table_lock );
int i = 0;
for ( ; i < NODE_TABLE_SIZE ; ++i ) {
Network::Node& node = node_table[i];
if ( node.is_invalid() ) {
available = &node;
continue;
}
in_use_count += 1;
if ( node != uuid ) continue;
result = &node;
break;
}
if ( in_use_count > 256 ) {
if ( table_warning_reported == false ) {
log_warn( "WARNING: node table exceeds 256 entries" );
table_warning_reported = true;
}
}
if ( result == NULL ) {
if ( available == NULL ) { // EDM ??? wasn't this set above ???
for ( ; i < NODE_TABLE_SIZE ; ++i ) {
Network::Node& node = node_table[i];
if ( node.is_valid() ) continue;
available = &node;
break;
}
}
if ( available != NULL ) {
available->uuid( uuid );
result = available;
} else {
if ( table_error_reported == false ) {
log_err( "ERROR: node table is full" );
table_error_reported = true;
}
}
}
pthread_mutex_unlock( &node_table_lock );
return result;
}
/**
*
*/
bool
Network::Monitor::remove_node( UUID *uuid ) {
pthread_mutex_lock( &node_table_lock );
for ( int i = 0 ; i < NODE_TABLE_SIZE ; ++i ) {
Network::Node& node = node_table[i];
if ( node.is_invalid() ) continue;
if ( node != *uuid ) continue;
node.invalidate();
}
pthread_mutex_unlock( &node_table_lock );
return true;
}
/**
*
*/
Network::Node*
Network::Monitor::find_node( UUID *uuid ) {
using namespace Network;
Node *result = NULL;
pthread_mutex_lock( &node_table_lock );
for ( int i = 0 ; i < NODE_TABLE_SIZE ; ++i ) {
Network::Node& node = node_table[i];
if ( node.is_invalid() ) continue;
if ( node != *uuid ) continue;
result = &node;
}
pthread_mutex_unlock( &node_table_lock );
return result;
}
/**
* Save the partner node id for later usage as a cache - in case
* priv0 is down and we cannot discover the node id dynamically.
*/
void
Network::Monitor::save_cache() {
FILE *f = fopen( "partner-cache", "w" );
if ( f == NULL ) {
log_notice( "could not save partner cache" );
return;
}
int partner_count = 0;
pthread_mutex_lock( &node_table_lock );
for ( int i = 0 ; i < NODE_TABLE_SIZE ; ++i ) {
Network::Node& node = node_table[i];
if ( node.is_invalid() ) continue;
if ( node.not_partner() ) continue;
if ( debug ) log_notice( "save partner [%s]", node.uuid().to_s() );
if ( partner_count == 0 ) {
fprintf( f, "%s\n", node.uuid().to_s() );
}
partner_count++;
}
pthread_mutex_unlock( &node_table_lock );
fclose( f );
if ( partner_count > 1 ) {
log_err( "%%BUG multiple partner entries in node table" );
}
}
/**
*/
void
Network::Monitor::clear_partners() {
ClearNodePartner callback;
int partner_count = each_node( callback );
if ( partner_count > 0 ) {
log_notice( "cleared %d partners", partner_count );
}
}
/**
* This is called when netmgr starts. It simply loads the previous saved
* value of the partner node id and creates an entry in the node table
* marked as a partner. This value was written the last time netmgr
* discovered a partner node on priv0.
*/
void
Network::Monitor::load_cache() {
char buffer[80];
FILE *f = fopen( "partner-cache", "r" );
if ( f == NULL ) {
log_notice( "partner cache not present" );
return;
}
fscanf( f, "%s\n", buffer );
fclose( f );
log_notice( "loaded partner as [%s]", buffer );
/*
* This should not be necessary - when netmgr starts it should
* not have any partner node table entries.
*/
ClearNodePartner callback;
int partner_count = each_node( callback );
if ( partner_count > 0 ) {
log_notice( "cleared %d partners", partner_count );
}
UUID uuid(buffer);
Network::Node *node = intern_node( uuid );
node->make_partner();
}
/**
*/
class WriteHostsForNeighbors : public Network::NeighborIterator {
int fd;
public:
WriteHostsForNeighbors( int fd ) : fd(fd) {}
virtual ~WriteHostsForNeighbors() {}
virtual int operator() ( Network::Peer& neighbor ) {
struct host_entry entry;
memset( &entry, 0, sizeof(entry) );
Network::Node *node = neighbor.node();
if ( node == NULL ) {
return 0;
}
if ( node->not_partner() ) {
return 0;
}
entry.flags.valid = 1;
entry.flags.partner = neighbor.is_partner();
entry.node.ordinal = node->ordinal();
entry.interface.ordinal = neighbor.ordinal();
entry.flags.is_private = neighbor.is_private();
neighbor.copy_address( &(entry.primary_address) );
if ( debug > 1 ) log_notice( "write host entry for peer" );
// populate entry for the interface itself
ssize_t bytes = write( fd, &entry, sizeof(entry) );
if ( (size_t)bytes < sizeof(entry) ) {
log_err( "write failed creating hosts entry peer" );
}
return 0;
}
};
/**
*/
class WriteHostsForInterface : public Network::InterfaceIterator {
int fd;
public:
WriteHostsForInterface( int fd ) : fd(fd) {}
virtual ~WriteHostsForInterface() {}
virtual int operator() ( Network::Interface& interface ) {
struct host_entry entry;
memset( &entry, 0, sizeof(entry) );
entry.flags.valid = 1;
entry.flags.partner = 0;
entry.node.ordinal = gethostid();
entry.flags.is_private = interface.is_private();
entry.interface.ordinal = interface.ordinal();
interface.lladdr( &entry.primary_address );
unsigned char *mac = interface.mac();
entry.mac[0] = mac[0];
entry.mac[1] = mac[1];
entry.mac[2] = mac[2];
entry.mac[3] = mac[3];
entry.mac[4] = mac[4];
entry.mac[5] = mac[5];
if ( interface.not_bridge() and interface.not_private() ) {
return 0;
}
if ( debug > 1 ) log_notice( "write host entry for %s", interface.name() );
// populate entry for the interface itself
ssize_t bytes = write( fd, &entry, sizeof(entry) );
if ( (size_t)bytes < sizeof(entry) ) {
log_err( "write failed creating hosts entry" );
}
// call iterator for each neighbor
WriteHostsForNeighbors callback(fd);
interface.each_neighbor( callback );
return 0;
}
};
/** Update hosts file with partner addresses
*
* For each interface, check each neighbor, if it is a partner
* then add a host file entry for that name/uuid and interface
*
* node0.ip6.ibiz0 fe80::XXXX
*/
void
Network::Monitor::update_hosts() {
if ( mkfile(const_cast<char*>("hosts.tmp"), HOST_TABLE_SIZE) == 0 ) {
log_err( "could not create the tmp hosts table" );
return;
}
int fd = open("hosts.tmp", O_RDWR);
if ( fd < 0 ) {
if ( debug > 0 ) log_err( "could not open the hosts table for writing" );
return;
}
WriteHostsForInterface callback(fd);
each_interface( callback );
fsync( fd );
close( fd );
unlink( "hosts.1" );
link( "hosts", "hosts.1" );
rename( "hosts.tmp", "hosts" );
}
/**
* This thread connects a netlink socket and listens for broadcast
* messages from the kernel. This should inform us of the network
* related events.
*
* When an event occurs, this needs to trigger some other action.
* The action will be either a TCL script, or a TCL assembled AST.
*
* NewLink -- if not known add -- eval event
* -- if known -- call object->update( NewLink )
* always -- if bridge -- create bridge?
* check if bridge present -- check if private
*
* NewRoute ??
* NewAddr
*
* General: make sure all biz interfaces have bridges, make sure
* private does not, and make sure all interfaces (bridge and
* private) have addresses. Make sure all interfaces and bridges
* are named appropriately.
*
* Need platform service to determine which is private...
*
* For each interface -- ping/ICMP NUD and multicast svc
*
* ZeroConf specific interfaces
*/
void Network::Monitor::run() {
// Disable neighbor and route messages from being reported
// because we do not process them and we can get 100's of them
// every second. This causes -ENOBUFS and we can miss Link events.
//
// uint32_t groups = RTMGRP_LINK | RTMGRP_NOTIFY | RTNLGRP_NEIGH |
// RTMGRP_IPV4_IFADDR | RTMGRP_IPV4_ROUTE |
// RTMGRP_IPV6_IFADDR | RTMGRP_IPV6_ROUTE |
// RTMGRP_IPV6_IFINFO | RTMGRP_IPV6_PREFIX ;
load_cache();
uint32_t groups = RTMGRP_LINK | RTMGRP_NOTIFY |
RTMGRP_IPV4_IFADDR |
RTMGRP_IPV6_IFADDR |
RTMGRP_IPV6_IFINFO | RTMGRP_IPV6_PREFIX ;
route_socket = new NetLink::RouteSocket(groups);
NetLink::RouteSocket &rs = *route_socket;
probe();
if ( debug > 0 ) log_notice( "network monitor started" );
for (;;) {
rs.receive( this );
sleep( 1 );
}
}
void Network::Monitor::probe() {
if ( route_socket == NULL ) return;
if ( debug > 0 ) log_notice( "Monitor: sending probe" );
NetLink::RouteSocket &rs = *route_socket;
NetLink::GetLink getlink;
getlink.send( rs );
}
/**
* The network monitor needs to probe the current system for network
* devices and keep a list of devices that are being monitored.
*
* The discover interface bit here -- creates a RouteSocket, send
* a GetLink request, and process each response by calling the monitor
* object's receive callback interface. This callback will popoulate the
* Interface table.
*
* Tcl_Interp arg to the constructor is for handlers that are registered
* for network events. (?? also how to handle ASTs for handlers)
*/
Network::Monitor::Monitor( Tcl_Interp *interp, Network::ListenerInterfaceFactory factory,
Network::Manager *manager )
: Thread("netlink.monitor"), interp(interp), route_socket(NULL), factory(factory),
table_warning_reported(false), table_error_reported(false), _manager(manager) {
pthread_mutex_init( &node_table_lock, NULL );
size_t size = sizeof(Node) * NODE_TABLE_SIZE;
node_table = (Node *)mmap( 0, size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0 );
if ( node_table == MAP_FAILED ) {
log_err( "node table alloc failed" );
exit( errno );
}
for ( int i = 0 ; i < NODE_TABLE_SIZE ; i++ ) {
node_table[i].invalidate();
}
if ( debug > 0 ) log_err( "node table is at %p (%zu)", node_table, size );
}
/**
*/
static int
Monitor_obj( ClientData data, Tcl_Interp *interp,
int objc, Tcl_Obj * CONST *objv )
{
using namespace Network;
Monitor *monitor = (Monitor *)data;
if ( objc == 1 ) {
Tcl_SetObjResult( interp, Tcl_NewLongObj((long)(monitor)) );
return TCL_OK;
}
char *command = Tcl_GetStringFromObj( objv[1], NULL );
if ( Tcl_StringMatch(command, "type") ) {
Svc_SetResult( interp, "Network::Monitor", TCL_STATIC );
return TCL_OK;
}
if ( Tcl_StringMatch(command, "start") ) {
// this should have some sort of result so we know it has started correctly
monitor->start();
/*
if ( result == NULL ) {
Tcl_ResetResult( interp );
return TCL_OK;
}
Svc_SetResult( interp, (char *)result, TCL_STATIC );
return TCL_ERROR;
*/
Tcl_ResetResult( interp );
return TCL_OK;
}
/**
*/
if ( Tcl_StringMatch(command, "stop") ) {
/*
const char *result = monitor->stop();
if ( result == NULL ) {
Tcl_ResetResult( interp );
return TCL_OK;
}
Svc_SetResult( interp, (char *)result, TCL_STATIC );
return TCL_ERROR;
*/
Tcl_ResetResult( interp );
return TCL_OK;
}
/*
* I want an 'interfaces' sub command ...
*/
Svc_SetResult( interp, "Unknown command for Monitor object", TCL_STATIC );
return TCL_ERROR;
}
/**
*/
static void
Monitor_delete( ClientData data ) {
using namespace Network;
Monitor *message = (Monitor *)data;
delete message;
}
/**
*/
static int
Monitor_cmd( ClientData data, Tcl_Interp *interp,
int objc, Tcl_Obj * CONST *objv )
{
if ( objc != 3 ) {
Tcl_ResetResult( interp );
Tcl_WrongNumArgs( interp, 1, objv, "name factory" );
return TCL_ERROR;
}
using namespace Network;
ListenerInterfaceFactory factory;
void *p = (void *)&(factory); // avoid strict aliasing errors in the compiler
if ( Tcl_GetLongFromObj(interp,objv[2],(long*)p) != TCL_OK ) {
Svc_SetResult( interp, "invalid listener object", TCL_STATIC );
return TCL_ERROR;
}
char *name = Tcl_GetStringFromObj( objv[1], NULL );
Monitor *object = new Monitor( interp, factory, NULL );
Tcl_CreateObjCommand( interp, name, Monitor_obj, (ClientData)object, Monitor_delete );
Svc_SetResult( interp, name, TCL_VOLATILE );
return TCL_OK;
}
/**
* This is a sample command for testing the straight line netlink
* probe code.
*/
static int
Probe_cmd( ClientData data, Tcl_Interp *interp,
int objc, Tcl_Obj * CONST *objv )
{
// Yes, this is intentional, it may get removed later
pid_t pid __attribute((unused)) = getpid();
int result;
// Discover interfaces and add objects
int fd;
fd = socket( AF_NETLINK, SOCK_RAW, NETLINK_ROUTE );
if ( socket < 0 ) {
log_err( "Probe socket() failed, %s", strerror(errno) );
exit( 1 );
}
// setup sndbuf and rcvbuf
// bind
struct sockaddr_nl address;
memset( &address, 0, sizeof(address) );
address.nl_family = AF_NETLINK;
address.nl_groups = 0;
if ( bind(fd, (struct sockaddr *)&address, sizeof(address)) < 0 ) {
log_err( "Probe bind() failed, %s", strerror(errno) );
exit( 1 );
}
// send request
struct {
struct nlmsghdr nlh;
struct rtgenmsg g;
} nlreq;
memset( &nlreq, 0, sizeof(nlreq) );
nlreq.nlh.nlmsg_len = sizeof(nlreq);
nlreq.nlh.nlmsg_type = RTM_GETLINK;
nlreq.nlh.nlmsg_flags = NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST;
nlreq.nlh.nlmsg_pid = 0;
nlreq.nlh.nlmsg_seq = 34;
nlreq.g.rtgen_family = AF_PACKET;
result = sendto( fd, (void*)&nlreq, sizeof(nlreq), 0, (struct sockaddr *)&address, sizeof(address) );
if ( result < 0 ) {
log_err( "Probe sendto() failed, %s", strerror(errno) );
exit( 1 );
}
// Now I am going to reuse the "address" structure for receiving the responses.
memset( &address, 0, sizeof(address) );
char msg_buf[16384];
struct iovec iov;
memset( &iov, 0, sizeof(iov) );
iov.iov_base = msg_buf;
struct msghdr rsp_msg;
rsp_msg.msg_name = &address;
rsp_msg.msg_namelen = sizeof(address);
rsp_msg.msg_iov = &iov;
rsp_msg.msg_iovlen = 1;
// loop around waiting for netlink messages
// for each response create an interface object
for (;;) {
unsigned int status;
struct nlmsghdr *h;
iov.iov_len = sizeof(msg_buf);
status = recvmsg( fd, &rsp_msg, 0 );
if ( status < 0 ) {
if ( errno == EINTR ) {
// normally just continue here
printf( "interupted recvmsg\n" );
} else {
log_err( "Probe recvmsg() failed, %s", strerror(errno) );
}
continue;
}
if ( status == 0 ) {
printf( "finished nlmsgs\n" );
break;
}
printf( "status=%d\n", status );
h = (struct nlmsghdr *)msg_buf;
while ( NLMSG_OK(h, status) ) {
if ( h->nlmsg_type == NLMSG_DONE ) {
printf( "NLMSG_DONE\n" );
goto finish;
}
if ( h->nlmsg_type == NLMSG_ERROR ) {
printf( "NLMSG_ERROR\n" );
goto finish;
}
/*
if ( h->nlmsg_flags & NLM_F_MULTI ) {
printf( "NLM_F_MULTI\n" );
} else {
printf( "not:NLM_F_MULTI\n" );
}
*/
printf( "process nlmsg type=%d flags=0x%08x pid=%d seq=%d\n", h->nlmsg_type, h->nlmsg_flags, h->nlmsg_pid, h->nlmsg_seq );
{ // type is in linux/if_arp.h -- flags are in linux/if.h
NetLink::NewLink *m = new NetLink::NewLink( h );
Network::Interface *ii = new Network::Interface( interp, m );
if ( ii == NULL ) { // remove -Wall warning by using this
}
}
h = NLMSG_NEXT( h, status );
}
printf( "finished with this message (notOK)\n" );
if ( rsp_msg.msg_flags & MSG_TRUNC ) {
printf( "msg truncated" );
continue;
}
if ( status != 0 ) {
printf( "remnant\n" );
}
}
finish:
close( fd );
// Discover Bridges
// Search for existing bridges and create objects for them
// and for each object create a command
// the bridge commands should remain in the Network namespace
// -- maybe no -- create in whichever namespace you need
return TCL_OK;
}
/**
*/
Network::Event::Event( const char *name, void *data ) {
_name = strdup(name);
_data = data;
}
/**
*/
Network::Event::~Event() {
if ( _name != NULL ) free(_name);
}
/**
*/
static int
Manager_obj( ClientData data, Tcl_Interp *interp,
int objc, Tcl_Obj * CONST *objv )
{
using namespace Network;
Manager *manager = (Manager *)data;
if ( objc == 1 ) {
Tcl_SetObjResult( interp, Tcl_NewLongObj((long)(manager)) );
return TCL_OK;
}
char *command = Tcl_GetStringFromObj( objv[1], NULL );
if ( Tcl_StringMatch(command, "type") ) {
Svc_SetResult( interp, "Network::Manager", TCL_STATIC );
return TCL_OK;
}
if ( Tcl_StringMatch(command, "start") ) {
// this should have some sort of result so we know it has started correctly
manager->start();
/*
if ( result == NULL ) {
Tcl_ResetResult( interp );
return TCL_OK;
}
Svc_SetResult( interp, (char *)result, TCL_STATIC );
return TCL_ERROR;
*/
Tcl_ResetResult( interp );
return TCL_OK;
}
/**
*/
if ( Tcl_StringMatch(command, "stop") ) {
/*
const char *result = manager->stop();
if ( result == NULL ) {
Tcl_ResetResult( interp );
return TCL_OK;
}
Svc_SetResult( interp, (char *)result, TCL_STATIC );
return TCL_ERROR;
*/
Tcl_ResetResult( interp );
return TCL_OK;
}
Svc_SetResult( interp, "Unknown command for Manager object", TCL_STATIC );
return TCL_ERROR;
}
/**
*/
static void
Manager_delete( ClientData data ) {
using namespace Network;
Manager *message = (Manager *)data;
delete message;
}
/**
*/
static int
Manager_cmd( ClientData data, Tcl_Interp *interp,
int objc, Tcl_Obj * CONST *objv )
{
if ( objc != 2 ) {
Tcl_ResetResult( interp );
Tcl_WrongNumArgs( interp, 1, objv, "name" );
return TCL_ERROR;
}
using namespace Network;
char *name = Tcl_GetStringFromObj( objv[1], NULL );
Manager *object = new Manager( interp );
Tcl_CreateObjCommand( interp, name, Manager_obj, (ClientData)object, Manager_delete );
Svc_SetResult( interp, name, TCL_VOLATILE );
return TCL_OK;
}
/**
* need some way to find these objects...
* use TCL ..hmmm
*/
bool Network::Initialize( Tcl_Interp *interp ) {
Tcl_Command command;
Tcl_Namespace *ns = Tcl_CreateNamespace(interp, "Network", (ClientData)0, NULL);
if ( ns == NULL ) {
return false;
}
if ( Tcl_LinkVar(interp, "Network::debug", (char *)&debug, TCL_LINK_INT) != TCL_OK ) {
log_err( "failed to link Network::debug" );
exit( 1 );
}
command = Tcl_CreateObjCommand(interp, "Network::Monitor", Monitor_cmd, (ClientData)0, NULL);
if ( command == NULL ) {
// logger ?? want to report TCL Error
return false;
}
command = Tcl_CreateObjCommand(interp, "Network::Probe", Probe_cmd, (ClientData)0, NULL);
if ( command == NULL ) {
// logger ?? want to report TCL Error
return false;
}
command = Tcl_CreateObjCommand(interp, "Network::Manager", Manager_cmd, (ClientData)0, NULL);
if ( command == NULL ) {
// logger ?? want to report TCL Error
return false;
}
if ( Network::Interface::Initialize(interp) == false ) {
log_err( "Network::Interface::Initialize failed" );
return false;
}
if ( Network::SharedNetwork::Initialize(interp) == false ) {
log_err( "Network::SharedNetwork::Initialize failed" );
return false;
}
if ( Network::Bridge::Initialize(interp) == false ) {
log_err( "Network::Bridge::Initialize failed" );
return false;
}
if ( Network::Tunnel::Initialize(interp) == false ) {
log_err( "Network::Tunnel:Initialize failed" );
return false;
}
return true;
}
/* vim: set autoindent expandtab sw=4 : */
| 30.751326 | 134 | 0.580079 | [
"object"
] |
7d6bf66b7a29cb8e2a1b261cc57fe5003206c3a1 | 13,348 | cc | C++ | A4/Main/DatabaseTable/source/MyDB_BPlusTreeReaderWriter.cc | Hanyi-Wang-DarkStardust/Database-Implementation | fcbf529691482fcece44fa24adc16c86fc012822 | [
"Apache-2.0"
] | null | null | null | A4/Main/DatabaseTable/source/MyDB_BPlusTreeReaderWriter.cc | Hanyi-Wang-DarkStardust/Database-Implementation | fcbf529691482fcece44fa24adc16c86fc012822 | [
"Apache-2.0"
] | null | null | null | A4/Main/DatabaseTable/source/MyDB_BPlusTreeReaderWriter.cc | Hanyi-Wang-DarkStardust/Database-Implementation | fcbf529691482fcece44fa24adc16c86fc012822 | [
"Apache-2.0"
] | null | null | null |
#ifndef BPLUS_C
#define BPLUS_C
#include <MyDB_PageListIteratorAlt.h>
#include "MyDB_INRecord.h"
#include "MyDB_BPlusTreeReaderWriter.h"
#include "MyDB_PageReaderWriter.h"
#include "MyDB_PageListIteratorSelfSortingAlt.h"
#include "RecordComparator.h"
#include "algorithm"
//TO DO
MyDB_BPlusTreeReaderWriter :: MyDB_BPlusTreeReaderWriter(string orderOnAttName, MyDB_TablePtr forMe,
MyDB_BufferManagerPtr myBuffer) : MyDB_TableReaderWriter(forMe, myBuffer) {
// find the ordering attribute
auto res = forMe->getSchema()->getAttByName(orderOnAttName);
// remember information about the ordering attribute
orderingAttType = res.second; //MyDB_AttTypePtr
whichAttIsOrdering = res.first; //int
// and the root location
rootLocation = getTable()->getRootLocation();
}
MyDB_RecordIteratorAltPtr MyDB_BPlusTreeReaderWriter :: getRangeIterHelper(vector<MyDB_PageReaderWriter> &list, MyDB_AttValPtr low, MyDB_AttValPtr high, bool needSort) {
// Prepare other parameters for MyDB_PageListIteratorSelfSortingAlt
MyDB_RecordPtr leftRec;
MyDB_RecordPtr rightRec;
function<bool()> comparator;
MyDB_RecordPtr currRec;
function<bool()> lowVSCurrComparator;
function<bool()> CurrVSHighComparator;
currRec = getEmptyRecord();
// low Comparator: curr vs low
MyDB_INRecordPtr lowRec = getINRecord();
lowRec->setKey(low);
lowVSCurrComparator = buildComparator(currRec, lowRec);
// high Comparator: high vs curr
MyDB_INRecordPtr highRec = getINRecord();
highRec->setKey(high);
CurrVSHighComparator = buildComparator(highRec, currRec);
// Comparator: left vs right
leftRec = getEmptyRecord();
rightRec = getEmptyRecord();
comparator = buildComparator(leftRec, rightRec);
// Create Record Iterator over target pages
MyDB_RecordIteratorAltPtr rangeIter =
make_shared<MyDB_PageListIteratorSelfSortingAlt>(list, leftRec, rightRec, comparator, currRec,
lowVSCurrComparator, CurrVSHighComparator, needSort);
return rangeIter;
}
MyDB_RecordIteratorAltPtr
MyDB_BPlusTreeReaderWriter :: getSortedRangeIteratorAlt(MyDB_AttValPtr low, MyDB_AttValPtr high) {
// Get the pages within range
vector<MyDB_PageReaderWriter> list;
discoverPages(rootLocation, list, low, high);
return getRangeIterHelper(list, low, high, true);
}
//TO DO
MyDB_RecordIteratorAltPtr MyDB_BPlusTreeReaderWriter :: getRangeIteratorAlt(MyDB_AttValPtr low, MyDB_AttValPtr high) {
// Get the pages within range
vector<MyDB_PageReaderWriter> list;
discoverPages(rootLocation, list, low, high);
// MyDB_RecordIteratorAltPtr rangeIter = make_shared<MyDB_PageListIteratorAlt>(list);
// return rangeIter;
return getRangeIterHelper(list, low, high, false);
}
bool MyDB_BPlusTreeReaderWriter :: discoverPages(int whichPage, vector<MyDB_PageReaderWriter> &list, MyDB_AttValPtr low, MyDB_AttValPtr high) {
// Find the page
MyDB_PageReaderWriter targetPage(*this, whichPage);
queue<MyDB_PageReaderWriter> pageQ;
pageQ.push(targetPage);
MyDB_INRecordPtr lowRec = getINRecord();
lowRec->setKey(low);
MyDB_INRecordPtr highRec = getINRecord();
highRec->setKey(high);
while (!pageQ.empty()) {
MyDB_PageReaderWriter popPage = pageQ.front();
pageQ.pop();
if (popPage.getType() == RegularPage) {
list.push_back(popPage);
} else {
MyDB_INRecordPtr rec = getINRecord();
MyDB_RecordIteratorAltPtr recIter = popPage.getIteratorAlt();
function<bool()> lowComparator = buildComparator(rec, lowRec);
function<bool()> highComparator = buildComparator(highRec, rec);
while (recIter->advance()) {
recIter->getCurrent(rec);
bool lowInbound = !lowComparator();
if (!lowInbound) continue;
MyDB_PageReaderWriter nextPage = (*this)[rec->getPtr()];
pageQ.push(nextPage);
bool highInbound = !highComparator();
if (!highInbound) break;
}
}
}
return false;
}
//TO DO
void MyDB_BPlusTreeReaderWriter :: append(MyDB_RecordPtr appendMe) {
if (getNumPages() <= 1) { // no corresponding B+-Tree
rootLocation = 0;
getTable()->setRootLocation(0);
getTable()->setLastPage(1);
auto rootNode = (*this)[0];
auto leafNode = (*this)[1];
rootNode.clear();
rootNode.setType(DirectoryPage);
leafNode.clear();
leafNode.setType(RegularPage);
auto INF = getINRecord();
INF->setPtr(1);
rootNode.append(INF);
leafNode.append (appendMe);
}
else {
auto splitPtr = append(rootLocation, appendMe);
if (splitPtr != nullptr) {
int newRootLocation = getTable()->lastPage() + 1;
getTable()->setLastPage(newRootLocation);
getTable()->setRootLocation(newRootLocation);
auto newRootNode = (*this)[newRootLocation];
newRootNode.clear();
newRootNode.setType(DirectoryPage);
newRootNode.append(splitPtr);
auto INF = getINRecord();
INF->setPtr(rootLocation);
newRootNode.append(INF);
rootLocation = newRootLocation;
} else return ;
}
}
//TO DO
MyDB_RecordPtr MyDB_BPlusTreeReaderWriter :: split(MyDB_PageReaderWriter splitMe, MyDB_RecordPtr andMe) {
// Node split:
// Sort all records in over-fill page on the key
// Choose median key (if even number, use upper one)
// Create new pages
// Kick a copy of median key up a level and adjust pointers
bool isLeaf = splitMe.getType() == RegularPage;
// 1. make an list containing records of over-filled page (splitMe + andMe)
vector<MyDB_RecordPtr> over_filled_page;
MyDB_RecordIteratorAltPtr iter = splitMe.getIteratorAlt();
while (iter->advance()) {
MyDB_RecordPtr rec = isLeaf? getEmptyRecord(): getINRecord(); // set the base class to be RecPtr
iter->getCurrent(rec);
over_filled_page.push_back(rec);
}
over_filled_page.push_back(andMe); // support polymorphism
// 2. Sort the over-filled page
stable_sort(over_filled_page.begin(), over_filled_page.end(),
[this](const MyDB_RecordPtr& lhs, const MyDB_RecordPtr& rhs){
auto cmp = buildComparator(lhs, rhs);
return cmp();
});
// 3. select median in the over-filled list
auto median = over_filled_page.size() % 2 == 0 ? over_filled_page.size() / 2 : over_filled_page.size() / 2 + 1;
// 4. create a new page
int lastPageNum = getTable()->lastPage() + 1;
getTable()->setLastPage(lastPageNum);
lastPage = make_shared<MyDB_PageReaderWriter>(*this, lastPageNum);
lastPage->clear();
if (isLeaf)
lastPage->setType(RegularPage);
else
lastPage->setType(DirectoryPage);
// 5. put the small records in the new page and large records in old page
splitMe.clear();
if (isLeaf)
splitMe.setType(RegularPage);
else
splitMe.setType(DirectoryPage);
for (int i = 0; i < over_filled_page.size(); i++) {
if (i < median)
lastPage->append(over_filled_page[i]);
else
splitMe.append(over_filled_page[i]);
}
// 6. return the pointer to the record in new page
MyDB_INRecordPtr newRec = getINRecord();
auto largestRecNewPage = over_filled_page[median - 1]; // get the largest record in the new page (lastPage)
newRec->setKey(getKey(largestRecNewPage));
newRec->setPtr(getTable()->lastPage());
return newRec;
}
//TO DO
MyDB_RecordPtr MyDB_BPlusTreeReaderWriter::append(int whichPage, MyDB_RecordPtr appendMe) {
MyDB_PageReaderWriter appendPageNode(*this, whichPage);
if (appendPageNode.getType() == RegularPage) { // leaf node
if (appendPageNode.append(appendMe)) {
return nullptr; // no split
}
else {
return split(appendPageNode, appendMe);
}
}
else { // Internal node
MyDB_INRecordPtr IN = getINRecord();
function<bool()> comp = buildComparator(appendMe, IN);
MyDB_RecordIteratorAltPtr recIter = appendPageNode.getIteratorAlt();
do {
recIter->getCurrent(IN);
if (comp()) { // < current IN
int pageNodeId = IN->getPtr();
MyDB_RecordPtr splitPtr = append(pageNodeId, appendMe); // recursively find a position
if (splitPtr) {
bool pageAppendSuccess = appendPageNode.append(splitPtr);
if (!pageAppendSuccess) return split(appendPageNode, splitPtr); // current node cannot insert more ptr
else {
MyDB_INRecordPtr compIN = getINRecord();
function<bool()> cmp = buildComparator(splitPtr, compIN);
appendPageNode.sortInPlace(cmp, splitPtr, compIN);
return nullptr;
}
}
else
return nullptr;
} else continue;
} while (recIter->advance());
}
}
void MyDB_BPlusTreeReaderWriter :: printTree() {
vector<vector<vector<MyDB_RecordPtr>>> level_order_list = getPrintTreeLevel(rootLocation);
for (int i = 0; i < level_order_list.size(); i++) {
vector<vector<MyDB_RecordPtr>> list = level_order_list[i];
for (int j = 0; j < list.size(); j++) {
vector<MyDB_RecordPtr> tmpList = list[j];
for (int k = 0; k < tmpList.size(); k++) {
cout << tmpList[k] << endl;
}
cout << endl;
}
cout << endl;
}
}
vector<vector<vector<MyDB_RecordPtr>>> MyDB_BPlusTreeReaderWriter::getPrintTreeLevel(int root) {
MyDB_PageReaderWriter rootPage = (*this)[root];
vector<vector<vector<MyDB_RecordPtr>>> level_order_list;
queue<MyDB_PageReaderWriter> pageQ;
pageQ.push(rootPage);
while (!pageQ.empty()) {
int size = pageQ.size();
vector<vector<MyDB_RecordPtr>> list;
for (int i = 0; i < size; i++) {
auto popPage = pageQ.front();
pageQ.pop();
vector<MyDB_RecordPtr> tmpList;
if (popPage.getType() == RegularPage) {
MyDB_RecordIteratorAltPtr recIter = popPage.getIteratorAlt();
while (recIter->advance()) {
MyDB_RecordPtr rec = getEmptyRecord();
recIter->getCurrent(rec);
tmpList.push_back(rec);
}
} else {
MyDB_RecordIteratorAltPtr recIter = popPage.getIteratorAlt();
while (recIter->advance()) {
MyDB_INRecordPtr rec = getINRecord();
recIter->getCurrent(rec);
tmpList.push_back(rec);
MyDB_PageReaderWriter nextPage = (*this)[rec->getPtr()];
pageQ.push(nextPage);
}
}
list.push_back(tmpList);
}
level_order_list.push_back(list);
}
return level_order_list;
}
//----------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------
MyDB_INRecordPtr MyDB_BPlusTreeReaderWriter :: getINRecord() {
return make_shared<MyDB_INRecord>(orderingAttType->createAttMax());
}
MyDB_AttValPtr MyDB_BPlusTreeReaderWriter::getKey(MyDB_RecordPtr fromMe) {
// in this case, got an IN record
if (fromMe->getSchema() == nullptr)
return fromMe->getAtt(0)->getCopy();
// in this case, got a data record
else
return fromMe->getAtt(whichAttIsOrdering)->getCopy();
}
function<bool()> MyDB_BPlusTreeReaderWriter :: buildComparator(MyDB_RecordPtr lhs, MyDB_RecordPtr rhs) {
MyDB_AttValPtr lhAtt, rhAtt;
// in this case, the LHS is an IN record
if (lhs->getSchema() == nullptr) {
lhAtt = lhs->getAtt(0);
// here, it is a regular data record
} else {
lhAtt = lhs->getAtt(whichAttIsOrdering);
}
// in this case, the LHS is an IN record
if (rhs->getSchema() == nullptr) {
rhAtt = rhs->getAtt(0);
// here, it is a regular data record
} else {
rhAtt = rhs->getAtt(whichAttIsOrdering);
}
// now, build the comparison lambda and return
if (orderingAttType->promotableToInt()) {
return [lhAtt, rhAtt] { return lhAtt->toInt() < rhAtt->toInt(); };
} else if (orderingAttType->promotableToDouble()) {
return [lhAtt, rhAtt] { return lhAtt->toDouble() < rhAtt->toDouble(); };
} else if (orderingAttType->promotableToString()) {
return [lhAtt, rhAtt] { return lhAtt->toString() < rhAtt->toString(); };
} else {
cout << "This is bad... cannot do anything with the >.\n";
exit(1);
}
}
#endif | 36.469945 | 169 | 0.610054 | [
"vector"
] |
7d777574145b7e48f297ac720a4e4ee5eef75d50 | 10,152 | cpp | C++ | test/getting_started.cpp | JuliaComputing/arrayfire | 93427f09ff928f97df29c0e358c3fcf6b478bec6 | [
"BSD-3-Clause"
] | 1 | 2018-06-14T23:49:18.000Z | 2018-06-14T23:49:18.000Z | test/getting_started.cpp | JuliaComputing/arrayfire | 93427f09ff928f97df29c0e358c3fcf6b478bec6 | [
"BSD-3-Clause"
] | 1 | 2015-07-02T15:53:02.000Z | 2015-07-02T15:53:02.000Z | test/getting_started.cpp | JuliaComputing/arrayfire | 93427f09ff928f97df29c0e358c3fcf6b478bec6 | [
"BSD-3-Clause"
] | 1 | 2018-02-26T17:11:03.000Z | 2018-02-26T17:11:03.000Z | /*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <gtest/gtest.h>
#include <arrayfire.h>
#include <vector>
#include <complex>
#include <testHelpers.hpp>
using namespace af;
using std::vector;
TEST(GettingStarted, SNIPPET_getting_started_gen)
{
//! [ex_getting_started_gen]
// Generate an array of size three filled with zeros.
// If no data type is specified, ArrayFire defaults to f32.
// The af::constant function generates the data on the device.
array zeros = constant(0, 3);
// Generate a 1x4 array of uniformly distributed [0,1] random numbers
// The af::randu function generates the data on the device.
array rand1 = randu(1, 4);
// Generate a 2x2 array (or matrix, if you prefer) of random numbers
// sampled from a normal distribution.
// The af::randn function generates data on the device.
array rand2 = randn(2, 2);
// Generate a 3x3 identity matrix. The data is generated on the device.
array iden = af::identity(3, 3);
// Lastly, create a 2x1 array (column vector) of uniformly distributed
// 32-bit complex numbers (c32 data type):
array randcplx = randu(2, 1, c32);
//! [ex_getting_started_gen]
{
vector<float> output;
output.resize(zeros.elements());
zeros.host(&output.front());
ASSERT_EQ(f32, zeros.type());
for(unsigned i = 0; i < zeros.elements(); i++) ASSERT_FLOAT_EQ(0, output[i]);
}
if (!noDoubleTests<double>()) {
array ones = constant(1, 3, 2, f64);
vector<double> output(ones.elements());
ones.host(&output.front());
ASSERT_EQ(f64, ones.type());
for(unsigned i = 0; i < ones.elements(); i++) ASSERT_FLOAT_EQ(1, output[i]);
}
{
vector<float> output;
output.resize(iden.elements());
iden.host(&output.front());
for(unsigned i = 0; i < iden.dims(0); i++)
for(unsigned j = 0; j < iden.dims(1); j++)
if(i == j) ASSERT_FLOAT_EQ(1, output[i * iden.dims(0) + j]);
else ASSERT_FLOAT_EQ(0, output[i * iden.dims(0) + j]);
}
}
TEST(GettingStarted, SNIPPET_getting_started_init)
{
//! [ex_getting_started_init]
// Create a six-element array on the host
float hA[] = {0, 1, 2, 3, 4, 5};
// Which can be copied into an ArrayFire Array using the pointer copy
// constructor. Here we copy the data into a 2x3 matrix:
array A(2, 3, hA);
// ArrayFire provides a convenince function for printing af::array
// objects in case you wish to see how the data is stored:
af_print(A);
// This technique can also be used to populate an array with complex
// data (stored in {{real, imaginary}, {real, imaginary}, ... } format
// as found in C's complex.h and C++'s <complex>.
// Below we create a 3x1 column vector of complex data values:
array dB(3, 1, (cfloat*) hA); // 3x1 column vector of complex numbers
af_print(dB);
//! [ex_getting_started_init]
vector<float> out(A.elements());
A.host(&out.front());
for(unsigned int i = 0; i < out.size(); i++) ASSERT_FLOAT_EQ(hA[i], out[i]);
}
TEST(GettingStarted, SNIPPET_getting_started_print)
{
//! [ex_getting_started_print]
// Generate two arrays
array a = randu(2, 2);
array b = constant(1, 2, 1);
// Print them to the console using af_print
af_print(a);
af_print(b);
// Print the results of an expression involving arrays:
af_print(a.col(0) + b + .4);
//! [ex_getting_started_print]
array result = a.col(0) + b + 0.4;
vector<float> outa(a.elements());
vector<float> outb(b.elements());
vector<float> out(result.elements());
a.host(&outa.front());
b.host(&outb.front());
result.host(&out.front());
for(unsigned i = 0; i < outb.size(); i++) ASSERT_FLOAT_EQ(outa[i] + outb[i] + 0.4, out[i]);
}
TEST(GettingStarted, SNIPPET_getting_started_dims)
{
//! [ex_getting_started_dims]
// Create a 4x5x2 array of uniformly distributed random numbers
array a = randu(4,5,2);
// Determine the number of dimensions using the numdims() function:
printf("numdims(a) %d\n", a.numdims()); // 3
// We can also find the size of the individual dimentions using either
// the `dims` function:
printf("dims = [%lld %lld]\n", a.dims(0), a.dims(1)); // 4,5
// Or the elements of a af::dim4 object:
dim4 dims = a.dims();
printf("dims = [%lld %lld]\n", dims[0], dims[1]); // 4,5
//! [ex_getting_started_dims]
//! [ex_getting_started_prop]
// Get the type stored in the array. This will be one of the many
// `af_dtype`s presented above:
printf("underlying type: %d\n", a.type());
// Arrays also have several conveience functions to determine if
// an Array contains complex or real values:
printf("is complex? %d is real? %d\n", a.iscomplex(), a.isreal());
// if it is a column or row vector
printf("is vector? %d column? %d row? %d\n", a.isvector(), a.iscolumn(), a.isrow());
// and whether or not the array is empty and how much memory it takes on
// the device:
printf("empty? %d total elements: %lld bytes: %lu\n", a.isempty(), a.elements(), a.bytes());
//! [ex_getting_started_prop]
ASSERT_EQ(f32, a.type());
ASSERT_TRUE(a.isreal());
ASSERT_FALSE(a.iscomplex());
ASSERT_FALSE(a.isvector());
ASSERT_FALSE(a.iscolumn());
ASSERT_FALSE(a.isrow());
ASSERT_FALSE(a.isempty());
ASSERT_EQ(40, a.elements());
ASSERT_EQ(f32, a.type());
ASSERT_EQ(f32, a.type());
ASSERT_EQ(4, dims[0]);
ASSERT_EQ(4, a.dims(0));
ASSERT_EQ(5, dims[1]);
ASSERT_EQ(5, a.dims(1));
}
TEST(GettingStarted, SNIPPET_getting_started_arith)
{
//! [ex_getting_started_arith]
array R = randu(3, 3);
af_print(constant(1, 3, 3) + af::complex(sin(R))); // will be c32
// rescale complex values to unit circle
array a = randn(5, c32);
af_print(a / abs(a));
// calculate L2 norm of vectors
array X = randn(3, 4);
af_print(sqrt(sum(pow(X, 2)))); // norm of every column vector
af_print(sqrt(sum(pow(X, 2), 0))); // same as above
af_print(sqrt(sum(pow(X, 2), 1))); // norm of every row vector
//! [ex_getting_started_arith]
}
TEST(GettingStarted, SNIPPET_getting_started_dev_ptr)
{
#ifdef __CUDACC__
//! [ex_getting_started_dev_ptr]
// Create an array on the host, copy it into an ArrayFire 2x3 ArrayFire array
float host_ptr[] = {0,1,2,3,4,5};
array a(2, 3, host_ptr);
// Create a CUDA device pointer, populate it with data from the host
float *device_ptr;
cudaMalloc((void**)&device_ptr, 6*sizeof(float));
cudaMemcpy(device_ptr, host_ptr, 6*sizeof(float), cudaMemcpyHostToDevice);
// Convert the CUDA-allocated device memory into an ArrayFire array:
array b(2,3, device_ptr, afDevice); // Note: afDevice (default: afHost)
// Note that ArrayFire takes ownership over `device_ptr`, so memory will
// be freed when `b` id destructed. Do not call cudaFree(device_ptr)!
//! [ex_getting_started_dev_ptr]
#endif //__CUDACC__
}
TEST(GettingStarted, SNIPPET_getting_started_ptr)
{
#ifdef __CUDACC__
//! [ex_getting_started_ptr]
// Create an array consisting of 3 random numbers
array a = randu(3, f32);
// Copy an array on the device to the host:
float * host_a = a.host<float>();
// access the host data as a normal array
printf("host_a[2] = %g\n", host_a[2]); // last element
// and free memory using delete:
delete[] host_a;
// Get access to the device memory for a CUDA kernel
float * d_cuda = a.device<float>(); // no need to free this
float value;
cudaMemcpy(&value, d_cuda + 2, sizeof(float), cudaMemcpyDeviceToHost);
printf("d_cuda[2] = %g\n", value);
a.unlock(); // unlock to allow garbage collection if necessary
// Because OpenCL uses references rather than pointers, accessing memory
// is similar, but has a somewhat clunky syntax. For the C-API
cl_mem d_opencl = (cl_mem) a.device<float>();
// for the C++ API, you can just wrap this object into a cl::Buffer
// after calling clRetainMemObject.
//! [ex_getting_started_ptr]
#endif //__CUDACC__
}
TEST(GettingStarted, SNIPPET_getting_started_scalar)
{
//! [ex_getting_started_scalar]
array a = randu(3);
float val = a.scalar<float>();
printf("scalar value: %g\n", val);
//! [ex_getting_started_scalar]
}
TEST(GettingStarted, SNIPPET_getting_started_bit)
{
//! [ex_getting_started_bit]
int h_A[] = {1, 1, 0, 0, 4, 0, 0, 2, 0};
int h_B[] = {1, 0, 1, 0, 1, 0, 1, 1, 1};
array A = array(3, 3, h_A), B = array(3, 3, h_B);
af_print(A); af_print(B);
array A_and_B = A & B; af_print(A_and_B);
array A_or_B = A | B; af_print(A_or_B);
array A_xor_B = A ^ B; af_print(A_xor_B);
//! [ex_getting_started_bit]
vector<int> Andout(A_and_B.elements());
vector<int> Orout(A_or_B.elements());
vector<int> Xorout(A_xor_B.elements());
A_and_B.host(&Andout.front());
A_or_B.host(&Orout.front());
A_xor_B.host(&Xorout.front());
for(unsigned int i = 0; i < Andout.size(); i++) ASSERT_FLOAT_EQ(h_A[i] & h_B[i], Andout[i]);
for(unsigned int i = 0; i < Orout.size(); i++) ASSERT_FLOAT_EQ(h_A[i] | h_B[i], Orout[i]);
for(unsigned int i = 0; i < Xorout.size(); i++) ASSERT_FLOAT_EQ(h_A[i] ^ h_B[i], Xorout[i]);
}
TEST(GettingStarted, SNIPPET_getting_started_constants)
{
//! [ex_getting_started_constants]
array A = randu(5,5);
A(where(A > .5)) = af::NaN;
array x = randu(10e6), y = randu(10e6);
double pi_est = 4 * sum<float>(hypot(x,y) < 1) / 10e6;
printf("estimation error: %g\n", fabs(Pi - pi_est));
//! [ex_getting_started_constants]
ASSERT_LE(fabs(Pi-pi_est), 0.005);
}
| 33.84 | 98 | 0.627955 | [
"object",
"vector"
] |
7d7a2c1cfc1a732a4f8ba710bdede88d12106948 | 12,294 | cpp | C++ | src/tests/document/document.cpp | suma/hex | d45026bfde6277e03c37d7f4411589c200051387 | [
"BSD-3-Clause"
] | 3 | 2015-03-17T14:34:44.000Z | 2021-12-22T12:43:38.000Z | src/tests/document/document.cpp | suma/hex | d45026bfde6277e03c37d7f4411589c200051387 | [
"BSD-3-Clause"
] | null | null | null | src/tests/document/document.cpp | suma/hex | d45026bfde6277e03c37d7f4411589c200051387 | [
"BSD-3-Clause"
] | null | null | null | #include <QtTest/QtTest>
#include <QTemporaryFile>
#include <QDataStream>
#include <vector>
#include "control/document.h"
#include "control/commands.h"
#include "control/filemapreader.h"
class TestDocument: public QObject
{
Q_OBJECT
public:
TestDocument();
private slots:
void initTestCase();
void cleanupTestCase();
void checkCompare();
// FileMapReader
void testOpenReader();
// Document
void testOverwritable1();
void testOverwritable2();
void testOpenFile();
void testUndoDelete();
void testUndoInsert();
void testUndoReplace();
void testUndoStack();
void testDocumentSaveAs();
void testDocumentSave();
private:
QTemporaryFile *createTemp();
QFile *openFile();
Document *open();
static Document *createDoc(QFile *file);
bool compareDocument(QFile *file, Document *doc);
bool compareDocument(Document *, Document *);
void dumpFragments(Document *doc);
private:
QTemporaryFile *temp_file_;
std::vector<uchar> data_;
};
const int TEST_FILE_SIZE = 1024 * 1024 * 2; // 64MB
const uint MAP_BLOCK_SIZE = 0x1000;
const uint BLOCK_SIZE = 0x1000;
const int WRITE_TEST_REPEAT = 10;
TestDocument::TestDocument()
: temp_file_(NULL)
{
}
QTemporaryFile *TestDocument::createTemp()
{
// write to dummy file
data_.resize(TEST_FILE_SIZE);
qsrand(107);
for (int i = 0; i < TEST_FILE_SIZE; i++) {
data_.push_back(static_cast<uchar>(qrand() & 0xFF));
}
QTemporaryFile *temp = new QTemporaryFile();
temp->setAutoRemove(true);
Q_ASSERT(temp->open());
QDataStream outStream(temp);
Q_ASSERT(outStream.writeRawData(reinterpret_cast<char*>(&data_[0]), TEST_FILE_SIZE) == TEST_FILE_SIZE);
return temp;
}
void TestDocument::initTestCase()
{
temp_file_ = createTemp();
}
void TestDocument::cleanupTestCase()
{
// delete dummy file
delete temp_file_;
temp_file_ = NULL;
}
QFile* TestDocument::openFile()
{
QFile *file = new QFile(temp_file_->fileName());
Q_ASSERT(file->open(QIODevice::ReadWrite));
return file;
}
Document *TestDocument::open()
{
QFile *file = openFile();
return new Document(file, MAP_BLOCK_SIZE);
}
Document *TestDocument::createDoc(QFile *file)
{
return new Document(file, MAP_BLOCK_SIZE);
}
bool TestDocument::compareDocument(QFile *file, Document *doc)
{
Q_ASSERT(file != NULL && doc != NULL);
// length
if (static_cast<quint64>(file->size()) != doc->length()) {
return false;
}
// file data
QDataStream stream(file);
file->seek(0);
uchar buffer1[BLOCK_SIZE];
char buffer2[BLOCK_SIZE];
for (quint64 pos = 0, len = doc->length(); len != 0; ) {
const uint copy_size = static_cast<uint>(qMin(len, (quint64)BLOCK_SIZE));
doc->get(pos, buffer1, copy_size);
int res = stream.readRawData(buffer2, copy_size);
Q_ASSERT(res != -1);
if (memcmp(buffer1, buffer2, copy_size)) {
return false;
}
pos += copy_size;
len -= copy_size;
}
return true;
}
bool TestDocument::compareDocument(Document *lhs, Document *rhs)
{
Q_ASSERT(lhs != NULL && rhs != NULL);
if (lhs->length() != rhs->length()) {
return false;
}
uchar buffer1[BLOCK_SIZE];
uchar buffer2[BLOCK_SIZE];
for (quint64 pos = 0, len = lhs->length(); len != 0; ) {
const uint copy_size = static_cast<uint>(qMin(len, (quint64)BLOCK_SIZE));
lhs->get(pos, buffer1, copy_size);
rhs->get(pos, buffer2, copy_size);
if (memcmp(buffer1, buffer2, copy_size)) {
return false;
}
pos += copy_size;
len -= copy_size;
}
return true;
}
void TestDocument::dumpFragments(Document *doc)
{
Q_ASSERT(doc != NULL);
Document::FragmentList fragments(doc->get());
Document::FragmentList::iterator it = fragments.begin();
qDebug() << doc << "length =" << doc->length() << " fragment.size() =" << fragments.size();
quint64 index = 0;
while (it != fragments.end()) {
if (it->type() == Document::DOCTYPE_ORIGINAL) {
qDebug() << "index = " << index <<
"(type, pos, len) =" << it->type() << it->position() << it->length();
if (index != it->position()) {
qDebug() << "not equals index and position";
}
}
index += it->length();
++it;
}
qDebug() << "<END>";
}
// TEST
void TestDocument::checkCompare()
{
{
Document *doc = open();
QVERIFY(compareDocument(doc->file(), doc));
delete doc;
}
{
Document *lhs = open();
Document *rhs = open();
QVERIFY(compareDocument(lhs, rhs));
delete lhs;
delete rhs;
}
{
QTemporaryFile *file = createTemp();
QDataStream data(file);
// append string
data << "123456";
QVERIFY(file->size() != temp_file_->size());
// compare
Document *doc = open();
Document *doc2 = createDoc(file);
QVERIFY(compareDocument(file, doc) == false);
QVERIFY(compareDocument(doc, doc2) == false);
delete doc;
delete doc2; // delete file in doc2
}
{
QTemporaryFile *file = createTemp();
QDataStream data(file);
// rewrite first 4bytes
const char *test = "1234";
file->seek(0);
QVERIFY(data.writeRawData(test, 4) == 4);
QVERIFY(file->size() == temp_file_->size());
// compare
Document *doc = open();
Document *doc2 = createDoc(file);
QVERIFY(compareDocument(file, doc) == false);
QVERIFY(compareDocument(doc, doc2) == false);
delete doc;
delete doc2; // delete file in doc2
}
}
void TestDocument::testOverwritable1()
{
Document *doc = open();
QVERIFY(doc->overwritable() == true);
delete doc;
}
void TestDocument::testOverwritable2()
{
Document *doc = open();
// Replace data
std::vector<uchar> dummy;
const int SIZE = 1024 * 100;
int insert_size = SIZE;
for (int insert_pos = doc->length() / 2; insert_size > 0; ) {
// assert: pos + len <= doc->lenght
const int size = qMin(qMin(1024, qrand()), insert_size);
// fix insert_pos
while (insert_pos + size > doc->length()) {
insert_pos -= qMin(insert_pos, qrand());
}
dummy.resize(size);
doc->undoStack()->push(new ReplaceCommand(doc, insert_pos, size, &dummy[0], size));
//dumpFragments(doc);
// ovewritable
QVERIFY(doc->overwritable());
insert_pos = (insert_pos + size + qrand()) % doc->length();
insert_size -= size;
}
delete doc;
}
void TestDocument::testOpenReader()
{
QFile *file = openFile();
Q_ASSERT(file != NULL);
const quint64 max = file->size();
const size_t COPY_SIZE = 1000;
{
FileMapReader reader(file, COPY_SIZE);
QVERIFY(reader.seek(0));
for (quint64 pos = 0; pos < max; pos += COPY_SIZE) {
const uint copy_size = (uint)qMin((quint64)COPY_SIZE, file->size() - pos);
const uchar *ptr = reader.get();
Q_ASSERT(ptr != NULL);
QVERIFY(memcmp(ptr, &data_[pos], copy_size) == 0);
reader += COPY_SIZE;
}
}
delete file;
}
void TestDocument::testOpenFile()
{
Document *doc = open();
QFile *file = doc->file();
// check length
QVERIFY(file->size() == doc->length());
// verify data
const quint64 COPY_SIZE = 1000;
QVERIFY( COPY_SIZE <= MAP_BLOCK_SIZE );
uchar buff[COPY_SIZE];
for (quint64 pos = 0; pos < doc->length(); pos += COPY_SIZE) {
uint copy_size = (uint)qMin((quint64)COPY_SIZE, doc->length() - pos);
doc->get(pos, buff, copy_size);
QVERIFY(memcmp(buff, &data_[pos], copy_size) == 0);
}
delete doc;
}
void TestDocument::testUndoDelete()
{
Document *doc = open();
QFile *file = doc->file();
// check check length
QVERIFY(file->size() == doc->length());
size_t DELETE_SIZE = 100;
for (size_t i = 0; i < DELETE_SIZE; i++) {
doc->undoStack()->push(new DeleteCommand(doc, i, 1));
}
// after delete
QVERIFY(file->size() == (doc->length() + DELETE_SIZE));
while (doc->undoStack()->canUndo()) {
doc->undoStack()->undo();
}
// Compare original
Document *orig = open();
QVERIFY(file->size() == doc->length());
QVERIFY(compareDocument(doc, orig));
delete orig;
delete doc;
}
void TestDocument::testUndoInsert()
{
Document *doc = open();
QFile *file = doc->file();
// check check length(before insert)
QVERIFY(file->size() == doc->length());
// Insert data
size_t INSERT_SIZE = 1000;
uchar data = 0x90;
for (size_t i = 0; i < INSERT_SIZE; i++) {
doc->undoStack()->push(new InsertCommand(doc, doc->length() / 2 + i, &data, 1));
}
// after insert
QVERIFY(file->size() == (doc->length() - INSERT_SIZE));
// Undo
while (doc->undoStack()->canUndo()) {
doc->undoStack()->undo();
}
// Compare original
Document *orig = open();
QVERIFY(file->size() == doc->length());
QVERIFY(compareDocument(doc, orig));
delete orig;
delete doc;
}
void TestDocument::testUndoReplace()
{
Document *doc = open();
QFile *file = doc->file();
// check check length
QVERIFY(file->size() == doc->length());
// Replace data
std::vector<uchar> dummy;
const int SIZE = 1024 * 100;
int insert_size = SIZE;
for (int insert_pos = doc->length() / 2; insert_size > 0; ) {
// assert: pos + len <= doc->lenght
const int size = qMin(qMin(1024, qrand()), insert_size);
// fix insert_pos
while (insert_pos + size > doc->length()) {
insert_pos -= qMin(insert_pos, qrand());
}
dummy.resize(size);
doc->undoStack()->push(new ReplaceCommand(doc, insert_pos, size, &dummy[0], size));
QVERIFY(doc->overwritable() == true);
insert_pos = (insert_pos + size + qrand()) % doc->length();
insert_size -= size;
}
// after replace
QVERIFY(file->size() == doc->length());
// Undo
while (doc->undoStack()->canUndo()) {
doc->undoStack()->undo();
}
QVERIFY(doc->overwritable() == true);
// Compare original
Document *orig = open();
QVERIFY(file->size() == doc->length());
QVERIFY(compareDocument(doc, orig));
delete orig;
delete doc;
}
void TestDocument::testUndoStack()
{
// TODO: implement Document::reopenKeepUndo test case
}
void TestDocument::testDocumentSaveAs()
{
for (int x = 0; x < WRITE_TEST_REPEAT; x++) {
Document *doc = open();
std::vector<uchar> dummy;
const int SIZE = 1024 * 1024 * 2;
int insert_size = SIZE;
for (int insert_pos = doc->length() / 2; insert_size > 0; ) {
const int size = qMin(qMax(1, (qrand() % 5000)), insert_size);
dummy.resize(size);
doc->undoStack()->push(new InsertCommand(doc, insert_pos, &dummy[0], size));
insert_pos = (insert_pos + size + qrand()) % doc->length();
insert_size -= size;
}
// check
QVERIFY((doc->file()->size() + SIZE) == doc->length());
// write file
QTemporaryFile temp;
QVERIFY2(temp.open(), "file open failed");
temp.setAutoRemove(true);
// write document
QVERIFY(doc->write(&temp, NULL));
QVERIFY(doc->overwritable() == false); // returns false
// check document
QVERIFY(compareDocument(&temp, doc));
delete doc;
}
}
void TestDocument::testDocumentSave()
{
for (int x = 0; x < WRITE_TEST_REPEAT; x++) {
Document *doc = open();
Document *doc_safe = open();
std::vector<uchar> dummy;
const int SIZE = 1024 * 1024 * 1;
int insert_size = SIZE;
for (int insert_pos = doc->length() / 2; insert_size > 0; ) {
// assert: pos + len <= doc->lenght
const int size = qMin(qMin(1024, qrand()), insert_size);
// fix insert_pos
while (insert_pos + size > doc->length()) {
insert_pos -= qMin(insert_pos, qrand());
}
dummy.resize(size);
doc->undoStack()->push(new ReplaceCommand(doc, insert_pos, size, &dummy[0], size));
insert_pos = (insert_pos + size + qrand()) % doc->length();
insert_size -= size;
}
QVERIFY(doc->overwritable()); // returns true
// check
QVERIFY(doc->file()->size() == doc->length());
QVERIFY(doc->overwritable()); // returns true
// write document
QVERIFY(doc->write(NULL));
// check document
QVERIFY(compareDocument(doc->file(), doc_safe));
// Undo
while (doc->undoStack()->canUndo()) {
doc->undoStack()->undo();
doc_safe->undoStack()->undo();
}
// check document
QVERIFY(compareDocument(doc->file(), doc));
QVERIFY(compareDocument(doc, doc_safe));
delete doc;
delete doc_safe;
}
}
QTEST_MAIN(TestDocument)
#include "document.moc"
| 22.766667 | 105 | 0.624614 | [
"vector"
] |
7d8048b1e96bd0ebe0a89c4095517d77e46419b6 | 2,596 | hpp | C++ | include/emulator/access.hpp | shift-crops/x86emu | fa65d448d71145fd611559a8a037dba211bb31a5 | [
"MIT"
] | 85 | 2017-03-24T13:02:38.000Z | 2022-02-17T23:22:55.000Z | include/emulator/access.hpp | shift-crops/x86emu | fa65d448d71145fd611559a8a037dba211bb31a5 | [
"MIT"
] | null | null | null | include/emulator/access.hpp | shift-crops/x86emu | fa65d448d71145fd611559a8a037dba211bb31a5 | [
"MIT"
] | 14 | 2017-05-06T18:34:31.000Z | 2021-05-12T10:24:43.000Z | #ifndef _DATA_ACCESS_H
#define _DATA_ACCESS_H
#include "common.hpp"
#include <vector>
#include "hardware/hardware.hpp"
struct PDE {
uint32_t P : 1;
uint32_t RW : 1;
uint32_t US : 1;
uint32_t PWT : 1;
uint32_t PCD : 1;
uint32_t A : 1;
uint32_t : 1;
uint32_t PS : 1;
uint32_t G : 1;
uint32_t : 3;
uint32_t ptbl_base : 20;
};
struct PTE {
uint32_t P : 1;
uint32_t RW : 1;
uint32_t US : 1;
uint32_t PWT : 1;
uint32_t PCD : 1;
uint32_t A : 1;
uint32_t D : 1;
uint32_t PAT : 1;
uint32_t G : 1;
uint32_t : 3;
uint32_t page_base : 20;
};
enum acsmode_t { MODE_READ, MODE_WRITE, MODE_EXEC };
class DataAccess : public virtual Hardware {
private:
std::vector<PTE*> tlb;
public:
void set_segment(sgreg_t seg, uint16_t v);
uint16_t get_segment(sgreg_t seg);
uint8_t get_data8(sgreg_t seg, uint32_t addr){ return read_mem8_seg(seg, addr); };
uint16_t get_data16(sgreg_t seg, uint32_t addr){ return read_mem16_seg(seg, addr); };
uint32_t get_data32(sgreg_t seg, uint32_t addr){ return read_mem32_seg(seg, addr); };
void put_data8(sgreg_t seg, uint32_t addr, uint8_t v){ write_mem8_seg(seg, addr, v); };
void put_data16(sgreg_t seg, uint32_t addr, uint16_t v){ write_mem16_seg(seg, addr, v); };
void put_data32(sgreg_t seg, uint32_t addr, uint32_t v){ write_mem32_seg(seg, addr, v); };
uint8_t get_code8(int index){ return exec_mem8_seg(CS, get_eip() + index); };
uint16_t get_code16(int index){ return exec_mem16_seg(CS, get_eip() + index); };
uint32_t get_code32(int index){ return exec_mem32_seg(CS, get_eip() + index); };
void push32(uint32_t v);
uint32_t pop32(void);
void push16(uint16_t v);
uint16_t pop16(void);
private:
uint32_t trans_v2p(acsmode_t mode, sgreg_t seg, uint32_t vaddr);
uint32_t trans_v2l(acsmode_t mode, sgreg_t seg, uint32_t vaddr);
bool search_tlb(uint32_t vpn, PTE *pte);
void cache_tlb(uint32_t vpn, PTE pte);
uint32_t read_mem32_seg(sgreg_t seg, uint32_t addr);
uint16_t read_mem16_seg(sgreg_t seg, uint32_t addr);
uint8_t read_mem8_seg(sgreg_t seg, uint32_t addr);
void write_mem32_seg(sgreg_t seg, uint32_t addr, uint32_t v);
void write_mem16_seg(sgreg_t seg, uint32_t addr, uint16_t v);
void write_mem8_seg(sgreg_t seg, uint32_t addr, uint8_t v);
uint32_t exec_mem32_seg(sgreg_t seg, uint32_t addr) { return read_mem32(trans_v2p(MODE_EXEC, seg, addr)); };
uint16_t exec_mem16_seg(sgreg_t seg, uint32_t addr) { return read_mem16(trans_v2p(MODE_EXEC, seg, addr)); };
uint8_t exec_mem8_seg(sgreg_t seg, uint32_t addr) { return read_mem8(trans_v2p(MODE_EXEC, seg, addr)); };
};
#endif
| 31.658537 | 110 | 0.727273 | [
"vector"
] |
7d837dd48787ddb013adeb20b4706c054e248336 | 569 | cpp | C++ | DSA/Week16/heap.cpp | lixk28/Assignment | 1128d041a111063be0dba1699ebcf4aa8a74e49c | [
"MIT"
] | null | null | null | DSA/Week16/heap.cpp | lixk28/Assignment | 1128d041a111063be0dba1699ebcf4aa8a74e49c | [
"MIT"
] | null | null | null | DSA/Week16/heap.cpp | lixk28/Assignment | 1128d041a111063be0dba1699ebcf4aa8a74e49c | [
"MIT"
] | null | null | null | /*
* @Author: Xuekun Li
* @Date: 2020-12-16 17:10:46
* @LastEditor: Xuekun Li
* @LastEditTime: 2020-12-16 17:16:24
* @Description: Try to code your bug.
*/
#include <iostream>
#include <vector>
using namespace std;
typedef int T;
void push_heap(vector<T> &v, size_t i) {
//Pre: v[0...i-1] is a heap
//Post: perculate up v[i] and make v[0..i] a heap, while v[i+1...] unchanged
}
void pop_heap() {
//Pre: v[0..i] is a heap
//Post: swap v[0] and v[i] and make v[0..i-1] into a heap
}
int main()
{
return 0;
} | 19.62069 | 81 | 0.56942 | [
"vector"
] |
7d87b2dc14b54b0357cf151d845b09e340d98de0 | 849 | cpp | C++ | kickstart/2020/round e/longest_arithmetic.cpp | Surya-06/My-Solutions | 58f7c7f1a0a3a28f25eff22d03a09cb2fbcf7806 | [
"MIT"
] | null | null | null | kickstart/2020/round e/longest_arithmetic.cpp | Surya-06/My-Solutions | 58f7c7f1a0a3a28f25eff22d03a09cb2fbcf7806 | [
"MIT"
] | null | null | null | kickstart/2020/round e/longest_arithmetic.cpp | Surya-06/My-Solutions | 58f7c7f1a0a3a28f25eff22d03a09cb2fbcf7806 | [
"MIT"
] | null | null | null | #include <iostream>
#include <limits>
#include <vector>
using namespace std;
typedef long long int llint;
llint __calc__() {
llint n;
cin >> n;
llint first_value, previous_value, current_value;
cin >> first_value >> previous_value;
llint diff = previous_value - first_value;
llint answer = 1, current_count = 1;
for (llint i = 2; i < n; i++) {
cin >> current_value;
if ((current_value - previous_value) == diff) {
current_count++;
} else {
current_count = 1;
diff = (current_value - previous_value);
}
answer = max(answer, current_count);
previous_value = current_value;
}
return answer + 1;
}
int main() {
llint t;
cin >> t;
for (llint i = 1; i <= t; i++) {
llint answer = __calc__();
cout << "Case #" << i << ": " << answer;
if (i < t)
cout << endl;
}
} | 19.744186 | 51 | 0.592462 | [
"vector"
] |
7d92114596cac624f4e6dac3c9e802169bba94e9 | 12,269 | cpp | C++ | External/Quiver/Source/Quiver/Quiver/Application/WorldEditor/WorldEditor.cpp | rachelnertia/Quarrel | 69616179fc71305757549c7fcaccc22707a91ba4 | [
"MIT"
] | 39 | 2017-10-22T15:47:39.000Z | 2020-03-31T22:19:55.000Z | External/Quiver/Source/Quiver/Quiver/Application/WorldEditor/WorldEditor.cpp | rachelnertia/Quarrel | 69616179fc71305757549c7fcaccc22707a91ba4 | [
"MIT"
] | 46 | 2017-10-26T21:21:51.000Z | 2018-10-13T14:46:17.000Z | Source/Quiver/Quiver/Application/WorldEditor/WorldEditor.cpp | rachelnertia/Quiver | c8ef9591117bdfc8d6fa509ae53451e0807f5686 | [
"MIT"
] | 8 | 2017-10-22T14:47:57.000Z | 2020-03-19T10:08:45.000Z | #include "WorldEditor.h"
#include <iostream>
#include <string>
#include <fstream>
#include <Box2D/Collision/Shapes/b2CircleShape.h>
#include <Box2D/Collision/Shapes/b2PolygonShape.h>
#include <Box2D/Dynamics/b2Fixture.h>
#include <Box2D/Dynamics/b2World.h>
#include <Box2D/Dynamics/b2WorldCallbacks.h>
#include <ImGui/imgui.h>
#include <SFML/Graphics/CircleShape.hpp>
#include <SFML/Graphics/RectangleShape.hpp>
#include <SFML/Graphics/RenderTexture.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Graphics/Sprite.hpp>
#include <SFML/Window/Event.hpp>
#include <spdlog/spdlog.h>
#include "Quiver/Application/Game/Game.h"
#include "Quiver/Entity/Entity.h"
#include "Quiver/Entity/EntityEditor.h"
#include "Quiver/Entity/PhysicsComponent/PhysicsComponent.h"
#include "Quiver/Entity/RenderComponent/RenderComponent.h"
#include "Quiver/Graphics/ColourUtils.h"
#include "Quiver/Graphics/FrameTexture.h"
#include "Quiver/Graphics/TextureLibrary.h"
#include "Quiver/Misc/ImGuiHelpers.h"
#include "Quiver/World/World.h"
#include "EditorTools.h"
namespace qvr {
WorldEditor::WorldEditor(ApplicationStateContext & context)
: WorldEditor(context, nullptr)
{}
WorldEditor::WorldEditor(ApplicationStateContext& context, std::unique_ptr<World> world)
: ApplicationState(context)
, mWorld(std::move(world))
, mFrameTex(std::make_unique<sf::RenderTexture>())
, mMouse(context.GetWindow())
{
if (!mWorld) {
mWorld = std::make_unique<World>(GetContext().GetWorldContext());
}
// Instantiate EditorTools.
mTools.push_back(std::make_unique<NoTool>());
mTools.push_back(std::make_unique<SelectTool>());
mTools.push_back(std::make_unique<CopySelectedEntityTool>());
mTools.push_back(std::make_unique<MoveTool>());
mTools.push_back(std::make_unique<RotateTool>());
mTools.push_back(std::make_unique<CreateCircleTool>());
mTools.push_back(std::make_unique<CreateBoxTool>());
mTools.push_back(std::make_unique<CreatePolygonTool>());
mTools.push_back(std::make_unique<CreateInstanceOfPrefabTool>());
mCurrentToolIndex = 1;
const sf::Vector2u windowSize = GetContext().GetWindow().getSize();
UpdateFrameTexture(
*mFrameTex,
GetContext().GetWindow().getSize(),
GetContext().GetFrameTextureResolutionRatio());
}
WorldEditor::~WorldEditor() {}
void WorldEditor::ProcessFrame()
{
if (GetContext().WindowResized()) {
const auto newSize = GetContext().GetWindow().getSize();
mFrameTex->create(newSize.x, newSize.y);
}
auto dt = frameClock.restart();
HandleInput(dt.asSeconds());
ProcessGUI();
mAnimationEditor.Update(dt.asSeconds());
if (GetQuit()) {
ImGui::EndFrame();
return;
}
Render();
}
void WorldEditor::HandleInput(const float dt)
{
mJoysticks.Update();
mKeyboard.Update();
mMouse.OnStep();
mMouse.OnFrame();
if (mMouse.GetPositionDelta() != sf::Vector2i(0, 0)) {
OnMouseMove(
sf::Event::MouseMoveEvent{
mMouse.GetPositionRelative().x,
mMouse.GetPositionRelative().y });
}
if (mMouse.JustDown(qvr::MouseButton::Left)) {
OnMouseClick(
sf::Event::MouseButtonEvent{
sf::Mouse::Button::Left,
mMouse.GetPositionRelative().x,
mMouse.GetPositionRelative().y });
}
if (!GetContext().GetWindow().hasFocus()) {
return;
}
if (ImGui::GetIO().WantTextInput) {
return;
}
if (mInPreviewMode) {
FreeControl(mCamera.Get3D(), dt);
mCamera.Get2D().SetPosition(mCamera.Get3D().GetPosition());
mCamera.Get2D().SetRotation(mCamera.Get3D().GetRotation() - b2_pi);
}
else {
FreeControl(mCamera.Get2D(), dt);
mCamera.Get3D().SetPosition(mCamera.Get2D().GetPosition());
mCamera.Get3D().SetRotation(mCamera.Get2D().GetRotation() + b2_pi);
}
}
void WorldEditor::Render()
{
sf::RenderWindow& window = GetContext().GetWindow();
window.clear(sf::Color(128, 128, 255));
if (mInPreviewMode) {
mFrameTex->clear(sf::Color(128, 128, 255));
mWorld->Render3D(*mFrameTex, mCamera.Get3D(), mWorldRaycastRenderer);
mFrameTex->display();
// Copy the frame texture to the window.
{
sf::Sprite frameSprite(mFrameTex->getTexture());
frameSprite.setScale((float)window.getSize().x / (float)mFrameTex->getSize().x,
(float)window.getSize().y / (float)mFrameTex->getSize().y);
window.draw(frameSprite);
}
}
else {
mCamera.Get2D().mOffsetX = (float)window.getSize().x / 2.0f;
mCamera.Get2D().mOffsetY = (float)window.getSize().y / 2.0f;
mWorld->RenderDebug(window, mCamera.Get2D());
mTools.at(mCurrentToolIndex)->Draw(window, mCamera.Get2D());
}
// Mark the middle of the screen
{
sf::RectangleShape r;
r.setPosition(sf::Vector2f((float)window.getSize().x / 2.0f, (float)window.getSize().y / 2.0f));
r.setSize(sf::Vector2f(3.0f, 3.0f));
r.setOrigin(sf::Vector2f(1.5f, 1.5f));
r.setFillColor(sf::Color::White);
window.draw(r);
}
ImGui::Render();
window.display();
}
void WorldEditor::ProcessGUI()
{
auto log = spdlog::get("console");
assert(log);
ImGui::SetNextWindowPos(ImVec2(0.0f, 0.0f));
ImGui::SetNextWindowSize(ImVec2(600.0f, (float)GetContext().GetWindow().getSize().y));
ImGui::AutoWindow window("World Editor", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove);
ImGui::AutoStyleVar styleVar(ImGuiStyleVar_IndentSpacing, 5.0f);
if (ImGui::Button("Play!")) {
SetQuit(std::make_unique<Game>(GetContext(), std::move(mWorld)));
return;
}
if (ImGui::Button("New")) {
mWorld = std::make_unique<World>(GetContext().GetWorldContext());
mCurrentSelectionEditor = nullptr;
mWorldFilename.clear();
}
if (ImGui::CollapsingHeader("Save/Load")) {
ImGui::InputText<64>("Filename", mWorldFilename);
if (ImGui::Button("Save")) {
if (mWorldFilename.empty()) {
log->error("No filename specified.");
}
else {
SaveWorld(*mWorld, mWorldFilename);
}
}
if (ImGui::Button("Load")) {
if (mWorldFilename.empty()) {
log->error("No filename specified.");
}
else {
mCurrentSelectionEditor = nullptr;
if (auto newWorld =
LoadWorld(
mWorldFilename,
GetContext().GetWorldContext()))
{
mWorld.reset(newWorld.release());
}
}
}
}
if (ImGui::CollapsingHeader("Animation Editor")) {
if (ImGui::Button("Open/Close Animation Editor")) {
mAnimationEditor.SetOpen(!mAnimationEditor.IsOpen());
}
if (mAnimationEditor.IsOpen()) {
mAnimationEditor.ProcessGui();
}
}
if (ImGui::CollapsingHeader("Options")) {
ImGui::AutoIndent indent;
if (ImGui::SliderFloat("Resolution Thing", &GetContext().GetFrameTextureResolutionRatio(), 0.2f, 1.0f)) {
UpdateFrameTexture(
*mFrameTex,
GetContext().GetWindow().getSize(),
GetContext().GetFrameTextureResolutionRatio());
}
}
if (ImGui::CollapsingHeader("Camera")) {
if (ImGui::Button(mInPreviewMode ? "Switch to 2D" : " Switch to 3D")) {
mInPreviewMode = !mInPreviewMode;
}
{
b2Vec2 p = mCamera.Get2D().GetPosition();
if (ImGui::InputFloat2("Position", &p.x)) {
mCamera.SetPosition(p);
}
}
{
float angle = mCamera.Get2D().GetRotation();
if (ImGui::SliderAngle("Rotation", &angle, -180.0f, 180.0f)) {
mCamera.SetRotation(angle);
}
}
if (ImGui::Button("Return to Origin")) {
mCamera.SetPosition(b2Vec2(0.0f, 0.0f));
}
if (mInPreviewMode) {
float height = mCamera.Get3D().GetHeight();
if (ImGui::SliderFloat("Camera Height", &height, 0.0f, 4.0f)) {
mCamera.Get3D().SetHeight(height);
}
float pitchRadians = mCamera.Get3D().GetPitchRadians();
if (ImGui::SliderAngle("Pitch", &pitchRadians, -45.0f, 45.0f)) {
mCamera.Get3D().SetPitch(pitchRadians);
}
float fovRadians = mCamera.Get3D().GetFovRadians();
if (ImGui::SliderAngle("Horizontal FOV", &fovRadians, 45.0f, 135.0f)) {
mCamera.Get3D().SetFov(fovRadians);
}
}
if (!mInPreviewMode) {
float pixelsPerMetre = mCamera.Get2D().mPixelsPerMetre;
if (ImGui::SliderFloat("Pixels Per Metre", &pixelsPerMetre, 1.0f, 128.0f)) {
mCamera.Get2D().mPixelsPerMetre = pixelsPerMetre;
}
}
ImGui::Text("Controls:\n%s", mInPreviewMode ? GetFreeControlCamera3DInstructions() : GetFreeControlCamera2DInstructions());
}
if (ImGui::CollapsingHeader("Performance Info")) {
ImGui::AutoIndent indent;
ImGui::Text("Application FPS: %.f", ImGui::GetIO().Framerate);
if (ImGui::CollapsingHeader("World##perf")) {
mWorld->GuiPerformanceInfo();
}
}
if (ImGui::CollapsingHeader("World##ctrl")) {
ImGui::AutoIndent indent;
mWorld->GuiControls();
}
if (ImGui::CollapsingHeader("World Animation System")) {
ImGui::AutoIndent indent;
GuiControls(mWorld->GetAnimators(), mAnimationLibraryEditorData);
}
if (ImGui::CollapsingHeader("Texture Library")) {
ImGui::AutoIndent indent;
if (mTextureLibraryGui == nullptr) {
mTextureLibraryGui =
std::make_unique<TextureLibraryGui>(mWorld->GetTextureLibrary());
}
mTextureLibraryGui->ProcessGui();
}
if (ImGui::CollapsingHeader("Editor Tools")) {
// Create a list, with selectable entries, of all the EditorTools in mTools.
// The strings to populate the list with are extracted from mTools using the
// anonymous lambda (3rd argument to ListBox).
int previousIndex = mCurrentToolIndex;
bool selectionChanged = ImGui::ListBox("Tool Select", &mCurrentToolIndex,
[](void* data, int index, const char** itemText) -> bool {
auto toolArray = (std::vector<EditorTool*>*)data;
if (index >= (int)toolArray->size()) return false;
if (index < 0) return false;
if (toolArray->at(index) == nullptr) return false;
*itemText = toolArray->at(index)->GetName();
return true;
}, (void*)&mTools, (int)mTools.size());
if (selectionChanged) {
mTools.at(previousIndex)->OnCancel(*this, mCamera.Get2D());
}
mTools.at(mCurrentToolIndex)->DoGui(*this);
}
if (ImGui::CollapsingHeader("Selected Entity")) {
ImGui::AutoIndent indent;
if (mCurrentSelectionEditor) {
if (ImGui::Button("Delete Entity")) {
mWorld->RemoveEntityImmediate(mCurrentSelectionEditor->GetTarget());
mCurrentSelectionEditor.release();
}
else {
// Edit the Entity!
mCurrentSelectionEditor->GuiControls();
}
}
else {
ImGui::Text("No Entity is selected. Use the Select Tool to pick one!");
}
}
}
void WorldEditor::OnMouseClick(const sf::Event::MouseButtonEvent & mouseInfo)
{
if (mouseInfo.button != sf::Mouse::Button::Left) {
return;
}
// Reject mouse click if it's over an ImGui window.
if (ImGui::IsMouseHoveringAnyWindow()) {
return;
}
const auto windowSize = sf::Vector2i(GetContext().GetWindow().getSize());
// Reject mouse click if it's outside the window.
if (mouseInfo.x < 0 || mouseInfo.x >= windowSize.x) {
return;
}
if (mouseInfo.y < 0 || mouseInfo.y >= windowSize.y) {
return;
}
// Pass execution down to the tools layer.
if (mInPreviewMode) {
mTools.at(mCurrentToolIndex)->OnMouseClick3D(*this,
mCamera.Get3D(),
mouseInfo,
(float)mFrameTex->getSize().x);
}
else {
mTools.at(mCurrentToolIndex)->OnMouseClick(*this, mCamera.Get2D(), mouseInfo);
}
}
void WorldEditor::OnMouseMove(const sf::Event::MouseMoveEvent & mouseInfo)
{
// Reject mouse move if it's over an ImGui window.
if (ImGui::IsMouseHoveringAnyWindow()) {
return;
}
const auto windowSize = sf::Vector2i(GetContext().GetWindow().getSize());
// Reject mouse move if it's outside the window.
if (mouseInfo.x < 0 || mouseInfo.x >= windowSize.x) {
return;
}
if (mouseInfo.y < 0 || mouseInfo.y >= windowSize.y) {
return;
}
if (!mInPreviewMode) {
// Pass execution down to the tools layer.
mTools.at(mCurrentToolIndex)->OnMouseMove(*this, mCamera.Get2D(), mouseInfo);
}
}
void WorldEditor::SetCurrentSelection(Entity* entity) {
if (entity) {
if (!mCurrentSelectionEditor ||
!mCurrentSelectionEditor->IsTargeting(*entity))
{
mCurrentSelectionEditor =
std::make_unique<EntityEditor>(*entity);
}
}
else {
mCurrentSelectionEditor.release();
}
}
auto WorldEditor::GetCurrentSelection() -> Entity* {
return mCurrentSelectionEditor ? &mCurrentSelectionEditor->GetTarget() : nullptr;
}
void WorldEditor::CameraPair::SetPosition(const b2Vec2& pos)
{
mCamera2D.SetPosition(pos);
mCamera3D.SetPosition(pos);
}
void WorldEditor::CameraPair::SetRotation(const float angle)
{
mCamera2D.SetRotation(angle);
mCamera3D.SetRotation(angle);
}
} | 25.883966 | 125 | 0.697938 | [
"render",
"vector",
"3d"
] |
7d9add1f08b6b2361c35e18c23f0e89367c2909a | 16,377 | cpp | C++ | Sandbox/Eudora/TridentPreviewView.cpp | dusong7/eudora-win | 850a6619e6b0d5abc770bca8eb5f3b9001b7ccd2 | [
"BSD-3-Clause-Clear"
] | 10 | 2018-05-23T10:43:48.000Z | 2021-12-02T17:59:48.000Z | Windows/Sandbox/Eudora/TridentPreviewView.cpp | officialrafsan/EUDORA | bf43221f5663ec2338aaf90710a89d1490b92ed2 | [
"MIT"
] | 1 | 2019-03-19T03:56:36.000Z | 2021-05-26T18:36:03.000Z | Windows/Sandbox/Eudora/TridentPreviewView.cpp | officialrafsan/EUDORA | bf43221f5663ec2338aaf90710a89d1490b92ed2 | [
"MIT"
] | 11 | 2018-05-23T10:43:53.000Z | 2021-12-27T15:42:58.000Z | // TridentPreviewView.cpp: implementation of the CTridentPreviewView class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "eudora.h"
#ifdef IDM_PROPERTIES
#undef IDM_PROPERTIES
#endif
#include "TridentReadMessageView.h"
#include "TridentPreviewView.h"
#include "ReadMessageDoc.h"
#include "TocFrame.h"
#include "tocdoc.h"
#include "msgutils.h"
#include "rs.h"
#include "summary.h"
#include "mshtml.h"
#include "mshtmcid.h"
#include "text2html.h"
#include "site.h"
#include "bstr.h"
#include "trnslate.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
IMPLEMENT_DYNCREATE(CTridentPreviewView, CTridentView)
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CTridentPreviewView::CTridentPreviewView()
{
}
CTridentPreviewView::~CTridentPreviewView()
{
}
void CTridentPreviewView::OnInitialUpdate()
{
CTridentView::OnInitialUpdate();
EnableWindow( FALSE );
ExecCommand( IDM_BROWSEMODE );
}
BOOL CTridentPreviewView::SetSelectedText(
const char* szText,
bool bSign )
{
HRESULT hr;
IHTMLDocument2* pDoc;
IHTMLSelectionObject* pSel;
IHTMLTxtRange* pRange;
IHTMLTxtRange* pBodyRange;
CBstr cbstrType;
CBstr cbstrText;
CBstr cbstr;
BOOL bReturn;
BOOL bDone;
IHTMLElementCollection* pCollection;
IHTMLElement* pElement;
IDispatch* pDispatch;
VARIANT varIndex;
VARIANT var;
VARIANT_BOOL vb;
LONG lCount;
LONG lIndex;
CRString szBody( IDS_HTML_BODY );
CString szTemp;
USES_CONVERSION;
pRange = NULL;
pBodyRange = NULL;
pSel = NULL;
pDoc = NULL;
bReturn = FALSE;
bDone = FALSE;
// Get document
pDoc = m_pSite->GetDoc2();
if (!pDoc)
{
return FALSE;
}
// Get selection
hr = pDoc->get_selection(&pSel);
if( !SUCCEEDED( hr ) || !pSel )
{
return FALSE;
}
// Create range
hr = pSel->createRange((IDispatch**)&pRange);
if( !SUCCEEDED( hr ) || !pRange )
{
pSel->Release();
return FALSE;
}
hr = pRange->duplicate( &pBodyRange );
// see if it takes up the entire message body
// note: this is a hack because CTRL-A run plugin caused
// new text to put inside the taboo header span
hr = pDoc->get_all( &pCollection );
if( ( hr == S_OK ) && pCollection )
{
hr = pCollection->get_length( &lCount );
if ( hr == S_OK )
{
for ( lIndex = 0; !bDone && ( lIndex < lCount ); lIndex++ )
{
varIndex.vt = VT_UINT;
varIndex.lVal = lIndex;
VariantInit( &var );
hr = pCollection->item( varIndex, var, &pDispatch );
if( ( hr == S_OK ) && pDispatch )
{
hr = pDispatch->QueryInterface( IID_IHTMLElement, (void **)&pElement );
if( ( hr == S_OK ) && pElement )
{
hr = pElement->get_tagName( BSTRARG( cbstr ) );
szTemp = cbstr;
if( szTemp.CompareNoCase( szBody ) == 0 )
{
// bail out -- even if bDone == FALSE
lCount = 0;
pBodyRange->moveToElementText( pElement );
vb = VARIANT_FALSE;
hr = pRange->isEqual( pBodyRange, &vb );
#pragma warning(disable : 4310)
if( SUCCEEDED( hr ) && ( vb == VARIANT_TRUE ) )
#pragma warning(default : 4310)
{
szTemp = Text2Html( szText, TRUE, FALSE );
cbstr = A2BSTR( szTemp );
if( ( ( BSTR ) cbstr ) != NULL )
{
hr = pElement->put_innerHTML( cbstr );
if ( S_OK == hr )
{
bDone = TRUE;
GetDocument()->SetModifiedFlag();
}
}
}
}
pElement->Release();
}
}
}
}
pCollection->Release();
}
pBodyRange->Release();
if( bDone )
{
pRange->Release();
pSel->Release();
return TRUE;
}
// Get type
hr = pSel->get_type( BSTRARG( cbstrType ) );
if ( ( S_OK == hr ) && ( ( ( BSTR ) cbstrType ) != NULL ) )
{
CString strType = cbstrType;
// If type isnt text, bail
if( ( strType.CompareNoCase( CRString( IDS_TEXT ) ) == 0 ) || ( strType.CompareNoCase( CRString( IDS_NONE ) ) == 0 ) )
{
cbstrText = A2BSTR( szText );
if( ( ( BSTR ) cbstrText ) != NULL )
{
hr = pRange->put_text( cbstrText );
if ( S_OK == hr )
{
bReturn = TRUE;
GetDocument()->SetModifiedFlag();
}
}
}
pRange->Release();
}
return bReturn;
}
BOOL CTridentPreviewView::GetMessageAsText(
CString& szMsg,
BOOL bIncludeHeaders)
{
HRESULT hr;
IHTMLBodyElement* pBody;
IHTMLTxtRange* pRange;
BOOL bReturn;
CBstr cbstrText;
bReturn = FALSE;
szMsg.Empty();
CSummary *pSum = ((CTocDoc *)m_pDocument)->GetPreviewableSummary();
if (!pSum)
return FALSE;
CMessageDoc* pMsgDoc = pSum->GetMessageDoc();
if (!pMsgDoc)
return FALSE;
char* FMBuffer = pMsgDoc->GetFullMessage(RAW);
CString szFullMessage(FMBuffer);
delete [] FMBuffer;
pSum->NukeMessageDocIfUnused();
// delete pSum;
//HTML to Text translation is not really symmetric in Trident
//So if the document has not been modified then return the text
//from the message doc ONLY if it was originally a plain text message
if (!(pMsgDoc->IsModified()) &&
!(pMsgDoc->m_Sum->IsXRich()) && !pMsgDoc->m_Sum->IsHTML())
{
if (bIncludeHeaders)
szMsg = szFullMessage;
else
{
const char* pHeadersBGone;
pHeadersBGone = strstr(szFullMessage, "\r\n\r\n");
if (pHeadersBGone)
szMsg = pHeadersBGone + 4;
else
szMsg = szFullMessage;
}
return TRUE;
}
// Well what we'll do is read the headers off the disk and read the body from the pane.
CString szMsgInPane;
pBody = m_pSite->GetBody();
if (!pBody)
return FALSE;
pRange = NULL;
// Create range
hr = pBody->createTextRange( &pRange );
if( ( S_OK == hr ) && pRange )
{
hr = pRange->get_text( BSTRARG( cbstrText ) );
if ( S_OK == hr && ( ( ( BSTR ) cbstrText ) != NULL ) )
{
szMsgInPane = cbstrText;
bReturn = TRUE;
}
pRange->Release();
}
pBody->Release();
// BOG
// CTridentReadMessageView::StripNBSP( szMsgInPane.GetBuffer( 0 ) );
StripNBSP( szMsgInPane.GetBuffer( 0 ) );
szMsgInPane.ReleaseBuffer();
char *EndOfHeader = strstr(szFullMessage, "\r\n\r\n");
if (EndOfHeader)
*EndOfHeader = 0;
if (bIncludeHeaders) // Here's the difference.
szMsg = szFullMessage;
if (EndOfHeader)
*EndOfHeader = 65; // I don't know what it was, but it better not be zero or CString's gonna have a fit.
EndOfHeader = strstr(szMsgInPane, "\r\n\r\n");
szMsg += EndOfHeader;
return bReturn;
}
BOOL CTridentPreviewView::WriteTempFile(
CFile& theFile,
CString& szStyleSheetFormat )
{
CString szLine;
BOOL bReturn = FALSE;
CTocFrame* pParentFrame = (CTocFrame* )GetParentFrame(); // the Ugly Typecast(tm)
ASSERT_KINDOF(CTocFrame, pParentFrame);
// Can't use GetDocument() here since that gives you the CTocDoc.
// We really need to grab the CMessageDoc from the summary that the
// frame used to make this preview pane.
//
CSummary* pSummary = pParentFrame->GetPreviewSummary();
if( pSummary == NULL )
{
// This isn't actually an error. No summary means no message
// to display.
return TRUE;
}
BOOL bLoadedDoc = FALSE;
CMessageDoc* pDoc = NULL;
if (NULL == (pDoc = pSummary->FindMessageDoc()))
{
//
// Document not loaded into memory, so force it to load.
//
pDoc = pSummary->GetMessageDoc();
bLoadedDoc = TRUE;
}
if (NULL == pDoc)
{
ASSERT(0);
return FALSE;
}
ASSERT_KINDOF(CMessageDoc, pDoc);
// get the whole message
char* szFullMessage = pDoc->GetFullMessage( RAW );
#ifdef IMAP4
//
// It's possible for this to fail if the message couldn't be retrieved
// from the IMAP server
//
if (NULL == szFullMessage)
{
if (bLoadedDoc)
{
pSummary->NukeMessageDocIfUnused();
pDoc = NULL;
}
return TRUE;
}
#endif // IMAP4
CString szFontName;
if (GetIniShort(IDS_INI_USE_PROPORTIONAL_AS_DEFAULT))
{
szFontName = GetIniString(IDS_INI_MESSAGE_FONT);
}
else
{
szFontName = GetIniString(IDS_INI_MESSAGE_FIXED_FONT);
}
CString szStyleSheet;
szStyleSheet.Format(szStyleSheetFormat,
(LPCSTR)szFontName,
(LPCSTR)GetIniString(IDS_INI_MESSAGE_FIXED_FONT),
(LPCSTR)GetIniString(IDS_INI_EXCERPT_BARS),
"none");
// convert cid's to local file URLs
MorphMHTML(&szFullMessage);
pDoc->m_QCMessage.Init(pDoc->m_MessageId, szFullMessage);
bReturn = TRUE;
try
{
theFile.Write(szStyleSheet, szStyleSheet.GetLength());
COLORREF cr;
char szBgColor[8];
char szFgColor[8];
cr = ::GetSysColor(COLOR_BTNFACE);
sprintf(szBgColor, "#%02X%02X%02X", GetRValue(cr), GetGValue(cr), GetBValue(cr));
cr = ::GetSysColor(COLOR_BTNTEXT);
sprintf(szFgColor, "#%02X%02X%02X", GetRValue(cr), GetGValue(cr), GetBValue(cr));
CString PreviewHeaders(StripNonPreviewHeaders(szFullMessage));
if (PreviewHeaders.IsEmpty() == FALSE)
{
szLine.Format(GetIniString(IDS_INI_PVTABLE_START), (LPCSTR)szBgColor, (LPCSTR)szFgColor);
theFile.Write(szLine, szLine.GetLength());
szLine.Format(GetIniString(IDS_INI_PVTABLE_ROW_START), (LPCSTR)szBgColor, (LPCSTR)szFgColor);
theFile.Write(szLine, szLine.GetLength());
szLine = Text2Html(PreviewHeaders, TRUE, FALSE);
theFile.Write(szLine, szLine.GetLength());
const char* szTableRowEnd = GetIniString(IDS_INI_PVTABLE_ROW_END);
theFile.Write(szTableRowEnd, strlen(szTableRowEnd));
const char* szTableEnd = GetIniString(IDS_INI_PVTABLE_END);
theFile.Write(szTableEnd, strlen(szTableEnd));
theFile.Write("<BR>\r\n", 6);
}
// get the body as html and save it to theFile
CString theBody;
pDoc->m_QCMessage.GetBodyAsHTML(theBody);
theFile.Write(theBody, theBody.GetLength());
theFile.Flush();
}
catch( CException* pExp )
{
pExp->Delete();
bReturn = FALSE;
}
if (bLoadedDoc)
{
pSummary->NukeMessageDocIfUnused();
pDoc = NULL;
}
delete [] szFullMessage;
return bReturn;
}
extern UINT umsgLoadNewPreview;
BEGIN_MESSAGE_MAP(CTridentPreviewView, CTridentView)
//{{AFX_MSG_MAP(CTridentPreviewView)
//}}AFX_MSG_MAP
ON_REGISTERED_MESSAGE(umsgLoadNewPreview, LoadNewPreview)
END_MESSAGE_MAP()
////////////////////////////////////////////////////////////////////////
// OnCmdMsg [public, virtual]
//
// Override for virtual CCmdTarget::OnCmdMsg() method. The idea is
// to "tweak" the standard command routing to forward commands from the
// view to the "fake" CMessageDoc document that was used to create this
// view in the first place.
////////////////////////////////////////////////////////////////////////
BOOL CTridentPreviewView::OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo)
{
switch (nID)
{
case ID_NEXT_MESSAGE:
case ID_PREVIOUS_MESSAGE:
//
// Fall through and let the MessageDoc, if any, handle these.
// Trust me.
//
break;
default:
//
// Let this view and the TocDoc have first crack at most commands.
//
if (CTridentView::OnCmdMsg(nID, nCode, pExtra, pHandlerInfo))
return TRUE;
break;
}
//
// If we get this far, neither this view nor the TocDoc handled the
// command, so let the preview's MessageDoc have a crack at it.
//
CSummary* pSummary = NULL;
CTocFrame* pTocFrame = (CTocFrame *) GetParentFrame(); // the Ugly Typecast(tm)
if (pTocFrame->IsKindOf(RUNTIME_CLASS(CTocFrame)))
pSummary = pTocFrame->GetPreviewSummary();
else
{
ASSERT(0);
}
if( pSummary == NULL )
return FALSE;
//
// This is ugly since GetMessageDoc() leaves the message document
// loaded into memory, typically without a view. We rely
// on CTocFrame to clean up this document for us.
//
CMessageDoc* pDoc = pSummary->GetMessageDoc();
return pDoc->OnCmdMsg(nID, nCode, pExtra, pHandlerInfo);
}
BOOL CTridentPreviewView::DoOnDisplayPlugin(
IHTMLElement* pElement )
{ HRESULT hr;
IHTMLDocument2* pDoc;
IHTMLElement* pParent;
IHTMLElement* p;
IHTMLAnchorElement* pAnchor;
CBstr cbstr;
CString szValue;
VARIANT v;
CBstr cbstrEudora( IDS_EUDORA_TAG );
IHTMLBodyElement* pBody;
IHTMLTxtRange* pRange;
CEudoraApp* pApp;
CString szFixed( "" );
INT i;
CString szHRef( "" );
USES_CONVERSION;
// Get document
VERIFY( pDoc = m_pSite->GetDoc2() );
if ( !pDoc )
{
return FALSE;
}
VERIFY( pBody = m_pSite->GetBody() );
if( !pBody )
{
return FALSE;
}
hr = pElement->get_tagName( BSTRARG( cbstr ) );
szValue = cbstr;
pParent = NULL;
p = pElement;
if( szValue.CompareNoCase( CRString( IDS_HTML_IMG ) ) == 0 )
{
pParent = NULL;
hr = pElement->get_parentElement( &pParent );
if( ( hr == S_OK ) && ( pParent != NULL ) )
{
hr = pParent->get_tagName( BSTRARG( cbstr ) );
p = pParent;
szValue = cbstr;
}
}
if( szValue.CompareNoCase( CRString( IDS_HTML_ANCHOR ) ) == 0 )
{
// see if it's a plugin
hr = p->getAttribute( cbstrEudora, 0, &v );
if( ( hr == S_OK ) && ( v.vt == VT_BSTR ) )
{
szValue = v.bstrVal;
if( szValue.CompareNoCase( CRString( IDS_PLUGIN ) ) == 0 )
{
// get the anchor
pAnchor = NULL;
hr = p->QueryInterface( IID_IHTMLAnchorElement, ( void** )( &pAnchor ) );
if( ( hr == S_OK ) && ( pAnchor != NULL ) )
{
hr = pAnchor->get_href( BSTRARG( cbstr ) );
if( ( hr == S_OK ) && ( ( ( BSTR ) cbstr ) != NULL ) )
{
szHRef = cbstr;
hr = pBody->createTextRange( &pRange );
hr = pRange->moveToElementText( p );
hr = pRange->collapse( FALSE );
hr = pRange->select();
}
pAnchor->Release();
}
}
}
VariantClear( &v );
}
if( pParent )
{
pParent->Release();
}
pBody->Release();
if( szHRef == "" )
{
return FALSE;
}
// don't release it if we're returning FALSE
pElement->Release();
// get rid of the "file:///"
szHRef = szHRef.Right( szHRef.GetLength() - 8 ) ;
szFixed.GetBuffer( szHRef.GetLength() + 1 );
while( ( i = szHRef.Find( "%20" ) ) >= 0 )
{
szFixed += szHRef.Left( i );
szFixed += ' ';
szHRef = szHRef.Right( szHRef.GetLength() - i - 3 );
}
szFixed += szHRef;
pApp = (CEudoraApp*) AfxGetApp();
pApp->GetTranslators()->XLateDisplay( this, szFixed );
return TRUE;
}
BOOL CTridentPreviewView::PreTranslateMessage(MSG* pMsg)
{
//
// Treat Tab keys as a special case for optionally navigating
// through the anchors in the HTML document.
//
if ((WM_KEYDOWN == pMsg->message) && (VK_TAB == pMsg->wParam))
{
if (! GetIniShort(IDS_INI_SWITCH_PREVIEW_WITH_TAB))
{
if (m_pIOleIPActiveObject)
{
HRESULT hr = m_pIOleIPActiveObject->TranslateAccelerator(pMsg);
if ( NOERROR == hr )
{
// The object translated the accelerator, so we're done
return TRUE;
}
}
}
}
return CTridentView::PreTranslateMessage(pMsg);
}
void CTridentPreviewView::OnActivateView
(
BOOL bActivate, // being activated or deactivated
CView* pActivateView, // view being activated
CView* pDeactiveView // view being deactivated (can be the same)
)
{
if ( bActivate && !IsWindowEnabled() ) {
EnableWindow( TRUE );
}
CTridentView::OnActivateView( bActivate, pActivateView, pDeactiveView );
}
///////////////////////////////////////////////////////////////////////////////
// Timer stuff for delayed enabling
// EnableWindowWithDelay - to prevent Trident from rudely grabbing focus, we
// disable ourselves in OnInitialUpdate; this routine re-enables us with a
// specified delay to compensate for Trident's sloppy completion reporting.
void CTridentPreviewView::EnableWindowWithDelay( unsigned ucDelay )
{
HWND theWnd = GetSafeHwnd();
::SetTimer( theWnd,
(UINT)theWnd,
ucDelay,
CTridentPreviewView::WMTimerProc );
}
// WMTimerProc - callback for ordinary WM_TIMER-based notifications
void CALLBACK CTridentPreviewView::WMTimerProc
(
HWND hwnd, // handle of window for timer messages
UINT uMsg, // WM_TIMER message
UINT idEvent, // timer identifier
DWORD dwTime // current system time
)
{
::KillTimer( hwnd, idEvent );
if ( ::IsWindow( hwnd ) ) {
::EnableWindow( hwnd, TRUE );
}
}
LRESULT CTridentPreviewView::LoadNewPreview(WPARAM, LPARAM)
{
EnableWindow( FALSE );
return LoadMessage();
}
| 22.161028 | 120 | 0.634487 | [
"object"
] |
7d9b4d12037382363497d048291b7651d3662e6b | 1,180 | cc | C++ | solutions/codeforces/contest/702/c.cc | zwliew/ctci | 871f4fc957be96c6d0749d205549b7b35dc53d9e | [
"MIT"
] | 4 | 2020-11-07T14:38:02.000Z | 2022-01-03T19:02:36.000Z | solutions/codeforces/contest/702/c.cc | zwliew/ctci | 871f4fc957be96c6d0749d205549b7b35dc53d9e | [
"MIT"
] | 1 | 2019-04-17T06:55:14.000Z | 2019-04-17T06:55:14.000Z | solutions/codeforces/contest/702/c.cc | zwliew/ctci | 871f4fc957be96c6d0749d205549b7b35dc53d9e | [
"MIT"
] | null | null | null | #include <algorithm>
#include <array>
#include <bitset>
#include <chrono>
#include <climits>
#include <cmath>
#include <deque>
#include <ext/pb_ds/assoc_container.hpp>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
//#include "bits/stdc++.h"
using namespace std;
#ifdef LOCAL
#include "../../_library/cc/debug.h"
#define FILE "test"
#else
#define debug(...) 0
#define FILE "pairup"
#endif
int main() {
cin.tie(nullptr)->sync_with_stdio(false);
if (fopen(FILE ".in", "r")) {
freopen(FILE ".in", "r", stdin);
freopen(FILE ".out", "w", stdout);
}
int n, m;
cin >> n >> m;
vector<int> cities(n), towers(m);
for (auto& x : cities)
cin >> x;
for (auto& x : towers)
cin >> x;
int ans = 0;
int j = -1;
for (int i = 0; i < n; ++i) {
while (j + 1 < m && towers[j + 1] <= cities[i]) {
++j;
}
ans = max(ans, min(j >= 0 ? cities[i] - towers[j] : INT_MAX,
j + 1 < m ? towers[j + 1] - cities[i] : INT_MAX));
}
cout << ans;
}
| 19.344262 | 73 | 0.581356 | [
"vector"
] |
7da640c79403850ac5bcddcf1217097537ba2153 | 16,579 | cpp | C++ | labs/lab1/src/lightir/Instruction.cpp | ltzheng/compiler-ustc | 4856701207876e73480a5c431c03d19b7dcce7a3 | [
"MIT"
] | 2 | 2021-06-19T23:58:00.000Z | 2021-12-07T10:49:13.000Z | labs/lab1/src/lightir/Instruction.cpp | ltzheng/compiler-ustc | 4856701207876e73480a5c431c03d19b7dcce7a3 | [
"MIT"
] | null | null | null | labs/lab1/src/lightir/Instruction.cpp | ltzheng/compiler-ustc | 4856701207876e73480a5c431c03d19b7dcce7a3 | [
"MIT"
] | null | null | null | #include "Type.h"
#include "Module.h"
#include "Function.h"
#include "BasicBlock.h"
#include "Instruction.h"
#include "IRprinter.h"
#include <cassert>
Instruction::Instruction(Type *ty, OpID id, unsigned num_ops,
BasicBlock *parent)
: User(ty, "", num_ops), op_id_(id), num_ops_(num_ops), parent_(parent)
{
parent_->add_instruction(this);
}
Function *Instruction::get_function()
{
return parent_->get_parent();
}
Module *Instruction::get_module()
{
return parent_->get_module();
}
BinaryInst::BinaryInst(Type *ty, OpID id, Value *v1, Value *v2,
BasicBlock *bb)
: Instruction(ty, id, 2, bb)
{
set_operand(0, v1);
set_operand(1, v2);
// assertValid();
}
void BinaryInst::assertValid()
{
assert(get_operand(0)->get_type()->is_integer_type());
assert(get_operand(1)->get_type()->is_integer_type());
assert(static_cast<IntegerType *>(get_operand(0)->get_type())->get_num_bits()
== static_cast<IntegerType *>(get_operand(1)->get_type())->get_num_bits());
}
BinaryInst *BinaryInst::create_add(Value *v1, Value *v2, BasicBlock *bb, Module *m)
{
return new BinaryInst(Type::get_int32_type(m), Instruction::Add, v1, v2, bb);
}
BinaryInst *BinaryInst::create_sub(Value *v1, Value *v2, BasicBlock *bb, Module *m)
{
return new BinaryInst(Type::get_int32_type(m), Instruction::Sub, v1, v2, bb);
}
BinaryInst *BinaryInst::create_mul(Value *v1, Value *v2, BasicBlock *bb, Module *m)
{
return new BinaryInst(Type::get_int32_type(m), Instruction::Mul, v1, v2, bb);
}
BinaryInst *BinaryInst::create_sdiv(Value *v1, Value *v2, BasicBlock *bb, Module *m)
{
return new BinaryInst(Type::get_int32_type(m), Instruction::Div, v1, v2, bb);
}
BinaryInst *BinaryInst::create_fadd(Value *v1, Value *v2, BasicBlock *bb, Module *m)
{
return new BinaryInst(Type::get_float_type(m), Instruction::FAdd, v1, v2, bb);
}
BinaryInst *BinaryInst::create_fsub(Value *v1, Value *v2, BasicBlock *bb, Module *m)
{
return new BinaryInst(Type::get_float_type(m), Instruction::FSub, v1, v2, bb);
}
BinaryInst *BinaryInst::create_fmul(Value *v1, Value *v2, BasicBlock *bb, Module *m)
{
return new BinaryInst(Type::get_float_type(m), Instruction::FMul, v1, v2, bb);
}
BinaryInst *BinaryInst::create_fdiv(Value *v1, Value *v2, BasicBlock *bb, Module *m)
{
return new BinaryInst(Type::get_float_type(m), Instruction::FDiv, v1, v2, bb);
}
std::string BinaryInst::print()
{
std::string instr_ir;
instr_ir += "%";
instr_ir += this->get_name();
instr_ir += " = ";
instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() );
instr_ir += " ";
instr_ir += this->get_operand(0)->get_type()->print();
instr_ir += " ";
instr_ir += print_as_op(this->get_operand(0), false);
instr_ir += ", ";
if (Type::is_eq_type(this->get_operand(0)->get_type(), this->get_operand(1)->get_type()))
{
instr_ir += print_as_op(this->get_operand(1), false);
}
else
{
instr_ir += print_as_op(this->get_operand(1), true);
}
return instr_ir;
}
CmpInst::CmpInst(Type *ty, CmpOp op, Value *lhs, Value *rhs,
BasicBlock *bb)
: Instruction(ty, Instruction::Cmp, 2, bb), cmp_op_(op)
{
set_operand(0, lhs);
set_operand(1, rhs);
// assertValid();
}
void CmpInst::assertValid()
{
assert(get_operand(0)->get_type()->is_integer_type());
assert(get_operand(1)->get_type()->is_integer_type());
assert(static_cast<IntegerType *>(get_operand(0)->get_type())->get_num_bits()
== static_cast<IntegerType *>(get_operand(1)->get_type())->get_num_bits());
}
CmpInst *CmpInst::create_cmp(CmpOp op, Value *lhs, Value *rhs,
BasicBlock *bb, Module *m)
{
return new CmpInst(m->get_int1_type(), op, lhs, rhs, bb);
}
std::string CmpInst::print()
{
std::string instr_ir;
instr_ir += "%";
instr_ir += this->get_name();
instr_ir += " = ";
instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() );
instr_ir += " ";
instr_ir += print_cmp_type(this->cmp_op_);
instr_ir += " ";
instr_ir += this->get_operand(0)->get_type()->print();
instr_ir += " ";
instr_ir += print_as_op(this->get_operand(0), false);
instr_ir += ", ";
if (Type::is_eq_type(this->get_operand(0)->get_type(), this->get_operand(1)->get_type()))
{
instr_ir += print_as_op(this->get_operand(1), false);
}
else
{
instr_ir += print_as_op(this->get_operand(1), true);
}
return instr_ir;
}
FCmpInst::FCmpInst(Type *ty, CmpOp op, Value *lhs, Value *rhs,
BasicBlock *bb)
: Instruction(ty, Instruction::FCmp, 2, bb), cmp_op_(op)
{
set_operand(0, lhs);
set_operand(1, rhs);
// assertValid();
}
void FCmpInst::assert_valid()
{
assert(get_operand(0)->get_type()->is_float_type());
assert(get_operand(1)->get_type()->is_float_type());
}
FCmpInst *FCmpInst::create_fcmp(CmpOp op, Value *lhs, Value *rhs,
BasicBlock *bb, Module *m)
{
return new FCmpInst(m->get_int1_type(), op, lhs, rhs, bb);
}
std::string FCmpInst::print()
{
std::string instr_ir;
instr_ir += "%";
instr_ir += this->get_name();
instr_ir += " = ";
instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() );
instr_ir += " ";
instr_ir += print_fcmp_type(this->cmp_op_);
instr_ir += " ";
instr_ir += this->get_operand(0)->get_type()->print();
instr_ir += " ";
instr_ir += print_as_op(this->get_operand(0), false);
instr_ir += ",";
if (Type::is_eq_type(this->get_operand(0)->get_type(), this->get_operand(1)->get_type()))
{
instr_ir += print_as_op(this->get_operand(1), false);
}
else
{
instr_ir += print_as_op(this->get_operand(1), true);
}
return instr_ir;
}
CallInst::CallInst(Function *func, std::vector<Value *> args, BasicBlock *bb)
: Instruction(func->get_return_type(), Instruction::Call, args.size() + 1, bb)
{
assert(func->get_num_of_args() == args.size());
int num_ops = args.size() + 1;
set_operand(0, func);
for (int i = 1; i < num_ops; i++) {
set_operand(i, args[i-1]);
}
}
CallInst *CallInst::create(Function *func, std::vector<Value *> args, BasicBlock *bb)
{
return new CallInst(func, args, bb);
}
FunctionType *CallInst::get_function_type() const
{
return static_cast<FunctionType *>(get_operand(0)->get_type());
}
std::string CallInst::print()
{
std::string instr_ir;
if( !this->is_void() )
{
instr_ir += "%";
instr_ir += this->get_name();
instr_ir += " = ";
}
instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() );
instr_ir += " ";
instr_ir += this->get_function_type()->get_return_type()->print();
instr_ir += " ";
assert(dynamic_cast<Function *>(this->get_operand(0)) && "Wrong call operand function");
instr_ir += print_as_op(this->get_operand(0), false);
instr_ir += "(";
for (int i = 1; i < this->get_num_operand(); i++)
{
if( i > 1 )
instr_ir += ", ";
instr_ir += this->get_operand(i)->get_type()->print();
instr_ir += " ";
instr_ir += print_as_op(this->get_operand(i), false);
}
instr_ir += ")";
return instr_ir;
}
BranchInst::BranchInst(Value *cond, BasicBlock *if_true, BasicBlock *if_false,
BasicBlock *bb)
: Instruction(Type::get_void_type(if_true->get_module()), Instruction::Br, 3, bb)
{
set_operand(0, cond);
set_operand(1, if_true);
set_operand(2, if_false);
}
BranchInst::BranchInst(BasicBlock *if_true, BasicBlock *bb)
: Instruction(Type::get_void_type(if_true->get_module()), Instruction::Br, 1, bb)
{
set_operand(0, if_true);
}
BranchInst *BranchInst::create_cond_br(Value *cond, BasicBlock *if_true, BasicBlock *if_false,
BasicBlock *bb)
{
return new BranchInst(cond, if_true, if_false, bb);
}
BranchInst *BranchInst::create_br(BasicBlock *if_true, BasicBlock *bb)
{
return new BranchInst(if_true, bb);
}
bool BranchInst::is_cond_br() const
{
return get_num_operand() == 3;
}
std::string BranchInst::print()
{
std::string instr_ir;
instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() );
instr_ir += " ";
// instr_ir += this->get_operand(0)->get_type()->print();
instr_ir += print_as_op(this->get_operand(0), true);
if( is_cond_br() )
{
instr_ir += ", ";
instr_ir += print_as_op(this->get_operand(1), true);
instr_ir += ", ";
instr_ir += print_as_op(this->get_operand(2), true);
}
return instr_ir;
}
ReturnInst::ReturnInst(Value *val, BasicBlock *bb)
: Instruction(Type::get_void_type(bb->get_module()), Instruction::Ret, 1, bb)
{
set_operand(0, val);
}
ReturnInst::ReturnInst(BasicBlock *bb)
: Instruction(Type::get_void_type(bb->get_module()), Instruction::Ret, 0, bb)
{
}
ReturnInst *ReturnInst::create_ret(Value *val, BasicBlock *bb)
{
return new ReturnInst(val, bb);
}
ReturnInst *ReturnInst::create_void_ret(BasicBlock *bb)
{
return new ReturnInst(bb);
}
bool ReturnInst::is_void_ret() const
{
return get_num_operand() == 0;
}
std::string ReturnInst::print()
{
std::string instr_ir;
instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() );
instr_ir += " ";
if ( !is_void_ret() )
{
instr_ir += this->get_operand(0)->get_type()->print();
instr_ir += " ";
instr_ir += print_as_op(this->get_operand(0), false);
}
else
{
instr_ir += "void";
}
return instr_ir;
}
GetElementPtrInst::GetElementPtrInst(Value *ptr, std::vector<Value *> idxs, BasicBlock *bb)
: Instruction(PointerType::get(get_element_type(ptr, idxs)), Instruction::GEP,
1 + idxs.size(), bb)
{
set_operand(0, ptr);
for (int i = 0; i < idxs.size(); i++) {
set_operand(i + 1, idxs[i]);
}
element_ty_ = get_element_type(ptr, idxs);
}
Type *GetElementPtrInst::get_element_type(Value *ptr, std::vector<Value *> idxs)
{
Type *ty = ptr->get_type()->get_pointer_element_type();
assert(ty->is_array_type()||ty->is_integer_type()||ty->is_float_type());
if (ty->is_array_type())
{
ArrayType *arr_ty = static_cast<ArrayType *>(ty);
for (int i = 1; i < idxs.size(); i++) {
ty = arr_ty->get_element_type();
if (i < idxs.size() - 1) {
assert(ty->is_array_type() && "Index error!");
}
if (ty->is_array_type()) {
arr_ty = static_cast<ArrayType *>(ty);
}
}
}
return ty;
}
Type *GetElementPtrInst::get_element_type() const
{
return element_ty_;
}
GetElementPtrInst *GetElementPtrInst::create_gep(Value *ptr, std::vector<Value *> idxs, BasicBlock *bb)
{
return new GetElementPtrInst(ptr, idxs, bb);
}
std::string GetElementPtrInst::print()
{
std::string instr_ir;
instr_ir += "%";
instr_ir += this->get_name();
instr_ir += " = ";
instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() );
instr_ir += " ";
assert(this->get_operand(0)->get_type()->is_pointer_type());
instr_ir += this->get_operand(0)->get_type()->get_pointer_element_type()->print();
instr_ir += ", ";
for (int i = 0; i < this->get_num_operand(); i++)
{
if( i > 0 )
instr_ir += ", ";
instr_ir += this->get_operand(i)->get_type()->print();
instr_ir += " ";
instr_ir += print_as_op(this->get_operand(i), false);
}
return instr_ir;
}
StoreInst::StoreInst(Value *val, Value *ptr, BasicBlock *bb)
: Instruction(Type::get_void_type(bb->get_module()), Instruction::Store, 2, bb)
{
set_operand(0, val);
set_operand(1, ptr);
}
StoreInst *StoreInst::create_store(Value *val, Value *ptr, BasicBlock *bb)
{
return new StoreInst(val, ptr, bb);
}
std::string StoreInst::print()
{
std::string instr_ir;
instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() );
instr_ir += " ";
instr_ir += this->get_operand(0)->get_type()->print();
instr_ir += " ";
instr_ir += print_as_op(this->get_operand(0), false);
instr_ir += ", ";
instr_ir += print_as_op(this->get_operand(1), true);
return instr_ir;
}
LoadInst::LoadInst(Type *ty, Value *ptr, BasicBlock *bb)
: Instruction(ty, Instruction::Load, 1, bb)
{
assert(ptr->get_type()->is_pointer_type());
assert(ty == static_cast<PointerType *>(ptr->get_type())->get_element_type());
set_operand(0, ptr);
}
LoadInst *LoadInst::create_load(Type *ty, Value *ptr, BasicBlock *bb)
{
return new LoadInst(ty, ptr, bb);
}
Type *LoadInst::get_load_type() const
{
return static_cast<PointerType *>(get_operand(0)->get_type())->get_element_type();
}
std::string LoadInst::print()
{
std::string instr_ir;
instr_ir += "%";
instr_ir += this->get_name();
instr_ir += " = ";
instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() );
instr_ir += " ";
assert(this->get_operand(0)->get_type()->is_pointer_type());
instr_ir += this->get_operand(0)->get_type()->get_pointer_element_type()->print();
instr_ir += ",";
instr_ir += " ";
instr_ir += print_as_op(this->get_operand(0), true);
return instr_ir;
}
AllocaInst::AllocaInst(Type *ty, BasicBlock *bb)
: Instruction(PointerType::get(ty), Instruction::Alloca, 0, bb), alloca_ty_(ty)
{
}
AllocaInst *AllocaInst::create_alloca(Type *ty, BasicBlock *bb)
{
return new AllocaInst(ty, bb);
}
Type *AllocaInst::get_alloca_type() const
{
return alloca_ty_;
}
std::string AllocaInst::print()
{
std::string instr_ir;
instr_ir += "%";
instr_ir += this->get_name();
instr_ir += " = ";
instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() );
instr_ir += " ";
instr_ir += get_alloca_type()->print();
return instr_ir;
}
ZextInst::ZextInst(OpID op, Value *val, Type *ty, BasicBlock *bb)
: Instruction(ty, op, 1, bb), dest_ty_(ty)
{
set_operand(0, val);
}
ZextInst *ZextInst::create_zext(Value *val, Type *ty, BasicBlock *bb)
{
return new ZextInst(Instruction::ZExt, val, ty, bb);
}
Type *ZextInst::get_dest_type() const
{
return dest_ty_;
}
std::string ZextInst::print()
{
std::string instr_ir;
instr_ir += "%";
instr_ir += this->get_name();
instr_ir += " = ";
instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() );
instr_ir += " ";
instr_ir += this->get_operand(0)->get_type()->print();
instr_ir += " ";
instr_ir += print_as_op(this->get_operand(0), false);
instr_ir += " to ";
instr_ir += this->get_dest_type()->print();
return instr_ir;
}
FpToSiInst::FpToSiInst(OpID op, Value *val, Type *ty, BasicBlock *bb)
: Instruction(ty, op, 1, bb), dest_ty_(ty)
{
set_operand(0, val);
}
FpToSiInst *FpToSiInst::create_fptosi(Value *val, Type *ty, BasicBlock *bb)
{
return new FpToSiInst(Instruction::FpToSi, val, ty, bb);
}
Type *FpToSiInst::get_dest_type() const
{
return dest_ty_;
}
std::string FpToSiInst::print()
{
std::string instr_ir;
instr_ir += "%";
instr_ir += this->get_name();
instr_ir += " = ";
instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() );
instr_ir += " ";
instr_ir += this->get_operand(0)->get_type()->print();
instr_ir += " ";
instr_ir += print_as_op(this->get_operand(0), false);
instr_ir += " to ";
instr_ir += this->get_dest_type()->print();
return instr_ir;
}
SiToFpInst::SiToFpInst(OpID op, Value *val, Type *ty, BasicBlock *bb)
: Instruction(ty, op, 1, bb), dest_ty_(ty)
{
set_operand(0, val);
}
SiToFpInst *SiToFpInst::create_sitofp(Value *val, Type *ty, BasicBlock *bb)
{
return new SiToFpInst(Instruction::SiToFp, val, ty, bb);
}
Type *SiToFpInst::get_dest_type() const
{
return dest_ty_;
}
std::string SiToFpInst::print()
{
std::string instr_ir;
instr_ir += "%";
instr_ir += this->get_name();
instr_ir += " = ";
instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() );
instr_ir += " ";
instr_ir += this->get_operand(0)->get_type()->print();
instr_ir += " ";
instr_ir += print_as_op(this->get_operand(0), false);
instr_ir += " to ";
instr_ir += this->get_dest_type()->print();
return instr_ir;
}
| 28.1 | 103 | 0.626214 | [
"vector"
] |
7dab7462f5add32354ba182028a9832b62338666 | 2,281 | cpp | C++ | examples/wandbox_example/wandbox_example.cpp | gracicot/DICL | 47c89c18a599382bd39cfb80ad6e2496e4c9ce42 | [
"MIT"
] | 362 | 2015-10-07T09:24:46.000Z | 2022-03-16T07:31:05.000Z | examples/wandbox_example/wandbox_example.cpp | gracicot/DICL | 47c89c18a599382bd39cfb80ad6e2496e4c9ce42 | [
"MIT"
] | 91 | 2015-04-13T19:19:25.000Z | 2022-03-07T13:23:26.000Z | examples/wandbox_example/wandbox_example.cpp | gracicot/DICL | 47c89c18a599382bd39cfb80ad6e2496e4c9ce42 | [
"MIT"
] | 40 | 2015-04-13T11:46:33.000Z | 2022-02-13T18:43:27.000Z | #include <kangaru/kangaru.hpp>
#include <iostream>
// This macro is used as a shortcut to use kgr::Method. Won't be needed in C++17
#define METHOD(...) ::kgr::method<decltype(__VA_ARGS__), __VA_ARGS__>
// The following classes are user classes.
// As you can see, this library is not intrusive and don't require modifications
struct Credential {};
struct Connection {
// The connect needs some credential
void connect(Credential const&) {
std::cout << "connection established" << std::endl;
}
};
struct Database {
// A database needs a connection
explicit Database(Connection const&) {
std::cout << "database created" << std::endl;
}
// For the sake of having a method to call
void commit() {
std::cout << "database commited" << std::endl;
}
};
// Service definitions.
// We define all dependencies between classes,
// and tell the container how to map function parameter to those definitions.
// Simple injectable service by value
struct CredentialService : kgr::service<Credential> {};
// Connection service is single,
// and need the connect function to be called on creation
struct ConnectionService : kgr::single_service<Connection>,
kgr::autocall<METHOD(&Connection::connect)> {};
// Database is also a single, and has a connection as dependency
struct DatabaseService : kgr::single_service<Database, kgr::dependency<ConnectionService>> {};
// The service map maps a function parameter type to a service definition
// We also want to map a Database argument type for the example.
auto service_map(Database const&) -> DatabaseService;
auto service_map(Credential const&) -> CredentialService;
int main() {
kgr::container container;
// Get the database.
// The database has a connection injected,
// and the connection had the connect function called before injection.
auto&& database = container.service<DatabaseService>();
// Commit the database
database.commit();
// Let `function` be a callable object that takes mapped services.
auto function = [](Credential c, Database& db) {
// Do stuff with credential and database
};
// The function is called with it's parameter injected automatically.
container.invoke(function);
// The programs outputs:
// connection established
// database created
// database commited
}
| 30.013158 | 94 | 0.734327 | [
"object"
] |
7dada59be2ee5a2df875c24deb025bcbdf8f65bd | 2,511 | hpp | C++ | lib/lib/propcov-cpp/RectangularSensor.hpp | ryanketzner/sphericalpolygon | de7ab321382d192b86e7ad9527f025a143f3f3f7 | [
"Apache-2.0"
] | 4 | 2021-12-23T16:49:06.000Z | 2022-02-09T21:36:31.000Z | lib/lib/propcov-cpp/RectangularSensor.hpp | ryanketzner/sphericalpolygon | de7ab321382d192b86e7ad9527f025a143f3f3f7 | [
"Apache-2.0"
] | 15 | 2022-01-14T17:28:14.000Z | 2022-02-11T02:39:25.000Z | lib/lib/propcov-cpp/RectangularSensor.hpp | ryanketzner/sphericalpolygon | de7ab321382d192b86e7ad9527f025a143f3f3f7 | [
"Apache-2.0"
] | 1 | 2022-02-03T15:44:16.000Z | 2022-02-03T15:44:16.000Z | //------------------------------------------------------------------------------
// RectangularSensor
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool.
//
// Copyright (c) 2002 - 2017 United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration.
// All Other 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.
//
// Author: Wendy Shoan, NASA/GSFC
// Created: 2016.05.03
//
/**
* Definition of the Conical Sensor class. This class models a conical sensor.
*/
//------------------------------------------------------------------------------
#ifndef RectangularSensor_hpp
#define RectangularSensor_hpp
#include "gmatdefs.hpp"
#include "Sensor.hpp"
class RectangularSensor : public Sensor
{
public:
/// class construction/destruction
RectangularSensor(Real angleWidthIn, Real angleHeightIn);
RectangularSensor( const RectangularSensor ©);
RectangularSensor& operator=(const RectangularSensor ©);
virtual ~RectangularSensor();
/// Check the target visibility given the input cone and clock angles:
/// determines whether or not the point is in the sensor FOV.
virtual bool CheckTargetVisibility(Real viewConeAngle,
Real viewClockAngle);
/// Set/Get angle width
virtual void SetAngleWidth(Real angleWidthIn);
virtual Real GetAngleWidth();
/// Set/Get angle height
virtual void SetAngleHeight(Real angleHeightIn);
virtual Real GetAngleHeight();
/// New Functions
std::vector<Real> getClockAngles();
std::vector<Rvector3> getCornerHeadings(std::vector<Real> &clocks);
std::vector<Rvector3> getPoleHeadings(std::vector<Rvector3> &corners);
protected:
/// Angle width
Real angleWidth;
/// Angle height
Real angleHeight;
std::vector<Rvector3> poles;
};
#endif // RectangularSensor_hpp
| 34.875 | 80 | 0.642772 | [
"vector"
] |
7dae65c1db40507fc42c08d22ccd95e90f461807 | 16,862 | cpp | C++ | cplus/libcfint/CFIntURLProtocolEditObj.cpp | msobkow/cfint_2_13 | 63ff9dfc85647066d0c8d61469ada572362e2b48 | [
"Apache-2.0"
] | null | null | null | cplus/libcfint/CFIntURLProtocolEditObj.cpp | msobkow/cfint_2_13 | 63ff9dfc85647066d0c8d61469ada572362e2b48 | [
"Apache-2.0"
] | null | null | null | cplus/libcfint/CFIntURLProtocolEditObj.cpp | msobkow/cfint_2_13 | 63ff9dfc85647066d0c8d61469ada572362e2b48 | [
"Apache-2.0"
] | null | null | null | // Description: C++18 edit object instance implementation for CFInt URLProtocol.
/*
* org.msscf.msscf.CFInt
*
* Copyright (c) 2020 Mark Stephen Sobkow
*
* MSS Code Factory CFInt 2.13 Internet Essentials
*
* Copyright 2020-2021 Mark Stephen Sobkow
*
* This file is part of MSS Code Factory.
*
* MSS Code Factory is available under dual commercial license from Mark Stephen
* Sobkow, or under the terms of the GNU General Public License, Version 3
* or later.
*
* MSS Code Factory is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MSS Code Factory is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MSS Code Factory. If not, see <https://www.gnu.org/licenses/>.
*
* Donations to support MSS Code Factory can be made at
* https://www.paypal.com/paypalme2/MarkSobkow
*
* Please contact Mark Stephen Sobkow at mark.sobkow@gmail.com for commercial licensing.
*
* Manufactured by MSS Code Factory 2.12
*/
#include <cflib/ICFLibPublic.hpp>
using namespace std;
#include <cfint/ICFIntPublic.hpp>
#include <cfintobj/ICFIntObjPublic.hpp>
#include <cfintobj/CFIntURLProtocolObj.hpp>
#include <cfintobj/CFIntURLProtocolEditObj.hpp>
namespace cfint {
const std::string CFIntURLProtocolEditObj::CLASS_NAME( "CFIntURLProtocolEditObj" );
CFIntURLProtocolEditObj::CFIntURLProtocolEditObj( cfint::ICFIntURLProtocolObj* argOrig )
: ICFIntURLProtocolEditObj()
{
static const std::string S_ProcName( "CFIntURLProtocolEditObj-construct" );
static const std::string S_OrigBuff( "origBuff" );
orig = argOrig;
cfint::CFIntURLProtocolBuff* origBuff = orig->getBuff();
if( origBuff == NULL ) {
throw cflib::CFLibNullArgumentException( CLASS_NAME,
S_ProcName,
0,
S_OrigBuff );
}
buff = dynamic_cast<cfint::CFIntURLProtocolBuff*>( origBuff->clone() );
}
CFIntURLProtocolEditObj::~CFIntURLProtocolEditObj() {
orig = NULL;
if( buff != NULL ) {
delete buff;
buff = NULL;
}
}
const std::string& CFIntURLProtocolEditObj::getClassName() const {
return( CLASS_NAME );
}
cfsec::ICFSecSecUserObj* CFIntURLProtocolEditObj::getCreatedBy() {
if( createdBy == NULL ) {
createdBy = dynamic_cast<cfint::ICFIntSchemaObj*>( getSchema() )->getSecUserTableObj()->readSecUserByIdIdx( getURLProtocolBuff()->getCreatedByUserId() );
}
return( createdBy );
}
const std::chrono::system_clock::time_point& CFIntURLProtocolEditObj::getCreatedAt() {
return( getURLProtocolBuff()->getCreatedAt() );
}
cfsec::ICFSecSecUserObj* CFIntURLProtocolEditObj::getUpdatedBy() {
if( updatedBy == NULL ) {
updatedBy = dynamic_cast<cfint::ICFIntSchemaObj*>( getSchema() )->getSecUserTableObj()->readSecUserByIdIdx( getURLProtocolBuff()->getUpdatedByUserId() );
}
return( updatedBy );
}
const std::chrono::system_clock::time_point& CFIntURLProtocolEditObj::getUpdatedAt() {
return( getURLProtocolBuff()->getUpdatedAt() );
}
void CFIntURLProtocolEditObj::setCreatedBy( cfsec::ICFSecSecUserObj* value ) {
createdBy = value;
if( value != NULL ) {
getURLProtocolEditBuff()->setCreatedByUserId( value->getRequiredSecUserIdReference() );
}
}
void CFIntURLProtocolEditObj::setCreatedAt( const std::chrono::system_clock::time_point& value ) {
getURLProtocolEditBuff()->setCreatedAt( value );
}
void CFIntURLProtocolEditObj::setUpdatedBy( cfsec::ICFSecSecUserObj* value ) {
updatedBy = value;
if( value != NULL ) {
getURLProtocolEditBuff()->setUpdatedByUserId( value->getRequiredSecUserIdReference() );
}
}
void CFIntURLProtocolEditObj::setUpdatedAt( const std::chrono::system_clock::time_point& value ) {
getURLProtocolEditBuff()->setUpdatedAt( value );
}
const classcode_t CFIntURLProtocolEditObj::getClassCode() const {
return( cfint::CFIntURLProtocolBuff::CLASS_CODE );
}
bool CFIntURLProtocolEditObj::implementsClassCode( const classcode_t value ) const {
if( value == cfint::CFIntURLProtocolBuff::CLASS_CODE ) {
return( true );
}
else {
return( false );
}
}
std::string CFIntURLProtocolEditObj::toString() {
static const std::string S_Space( " " );
static const std::string S_Preamble( "<CFIntURLProtocolEditObj" );
static const std::string S_Postamble( "/>" );
static const std::string S_Revision( "Revision" );
static const std::string S_CreatedBy( "CreatedBy" );
static const std::string S_CreatedAt( "CreatedAt" );
static const std::string S_UpdatedBy( "UpdatedBy" );
static const std::string S_UpdatedAt( "UpdatedAt" );
static const std::string S_URLProtocolId( "URLProtocolId" );
static const std::string S_Name( "Name" );
static const std::string S_Description( "Description" );
static const std::string S_IsSecure( "IsSecure" );
std::string ret( S_Preamble );
ret.append( cflib::CFLibXmlUtil::formatRequiredInt32( &S_Space, S_Revision, CFIntURLProtocolEditObj::getRequiredRevision() ) );
ret.append( cflib::CFLibXmlUtil::formatRequiredXmlString( &S_Space, S_CreatedBy, CFIntURLProtocolEditObj::getCreatedBy()->toString() ) );
ret.append( cflib::CFLibXmlUtil::formatRequiredTZTimestamp( &S_Space, S_CreatedAt, CFIntURLProtocolEditObj::getCreatedAt() ) );
ret.append( cflib::CFLibXmlUtil::formatRequiredXmlString( &S_Space, S_UpdatedBy, CFIntURLProtocolEditObj::getUpdatedBy()->toString() ) );
ret.append( cflib::CFLibXmlUtil::formatRequiredTZTimestamp( &S_Space, S_UpdatedAt, CFIntURLProtocolEditObj::getUpdatedAt() ) );
ret.append( cflib::CFLibXmlUtil::formatRequiredInt32( &S_Space, S_URLProtocolId, CFIntURLProtocolEditObj::getRequiredURLProtocolId() ) );
ret.append( cflib::CFLibXmlUtil::formatRequiredXmlString( &S_Space, S_Name, CFIntURLProtocolEditObj::getRequiredName() ) );
ret.append( cflib::CFLibXmlUtil::formatRequiredXmlString( &S_Space, S_Description, CFIntURLProtocolEditObj::getRequiredDescription() ) );
ret.append( cflib::CFLibXmlUtil::formatRequiredBoolean( &S_Space, S_IsSecure, CFIntURLProtocolEditObj::getRequiredIsSecure() ) );
ret.append( S_Postamble );
return( ret );
}
int32_t CFIntURLProtocolEditObj::getRequiredRevision() const {
return( buff->getRequiredRevision() );
}
void CFIntURLProtocolEditObj::setRequiredRevision( int32_t value ) {
getURLProtocolEditBuff()->setRequiredRevision( value );
}
std::string CFIntURLProtocolEditObj::getObjName() {
std::string objName( CLASS_NAME ); objName;
objName.clear();
objName.append( getRequiredName() );
return( objName );
}
const std::string CFIntURLProtocolEditObj::getGenDefName() {
return( cfint::CFIntURLProtocolBuff::GENDEFNAME );
}
cflib::ICFLibAnyObj* CFIntURLProtocolEditObj::getScope() {
return( NULL );
}
cflib::ICFLibAnyObj* CFIntURLProtocolEditObj::getObjScope() {
return( NULL );
}
cflib::ICFLibAnyObj* CFIntURLProtocolEditObj::getObjQualifier( const classcode_t* qualifyingClass ) {
cflib::ICFLibAnyObj* container = this;
if( qualifyingClass != NULL ) {
while( container != NULL ) {
if( container->getClassCode() == cfsec::CFSecClusterBuff::CLASS_CODE ) {
break;
}
else if( container->getClassCode() == cfsec::CFSecTenantBuff::CLASS_CODE ) {
break;
}
else if( container->implementsClassCode( *qualifyingClass ) ) {
break;
}
container = container->getObjScope();
}
}
else {
while( container != NULL ) {
if( container->getClassCode() == cfsec::CFSecClusterBuff::CLASS_CODE ) {
break;
}
else if( container->getClassCode() == cfsec::CFSecTenantBuff::CLASS_CODE ) {
break;
}
container = container->getObjScope();
}
}
return( container );
}
cflib::ICFLibAnyObj* CFIntURLProtocolEditObj::getNamedObject( const classcode_t* qualifyingClass, const std::string& objName ) {
cflib::ICFLibAnyObj* topContainer = getObjQualifier( qualifyingClass );
if( topContainer == NULL ) {
return( NULL );
}
cflib::ICFLibAnyObj* namedObject = topContainer->getNamedObject( objName );
return( namedObject );
}
cflib::ICFLibAnyObj* CFIntURLProtocolEditObj::getNamedObject( const std::string& objName ) {
std::string nextName;
std::string remainingName;
cflib::ICFLibAnyObj* subObj = NULL;
cflib::ICFLibAnyObj* retObj;
int32_t nextDot = objName.find( '.' );
if( nextDot >= 0 ) {
nextName = objName.substr( 0, nextDot );
remainingName = objName.substr( nextDot + 1 );
}
else {
nextName.clear();
nextName.append( objName );
remainingName.clear();
}
if( remainingName.length() <= 0 ) {
retObj = subObj;
}
else if( subObj == NULL ) {
retObj = NULL;
}
else {
retObj = subObj->getNamedObject( remainingName );
}
return( retObj );
}
std::string CFIntURLProtocolEditObj::getObjQualifiedName() {
const static std::string S_Dot( "." );
std::string qualName( getObjName() );
cflib::ICFLibAnyObj* container = getObjScope();
std::string containerName;
std::string buildName;
while( container != NULL ) {
if( container->getClassCode() == cfsec::CFSecClusterBuff::CLASS_CODE ) {
container = NULL;
}
else if( container->getClassCode() == cfsec::CFSecTenantBuff::CLASS_CODE ) {
container = NULL;
}
else {
containerName = container->getObjName();
buildName.clear();
buildName.append( containerName );
buildName.append( S_Dot );
buildName.append( qualName );
qualName.clear();
qualName.append( buildName );
container = container->getObjScope();
}
}
return( qualName );
}
std::string CFIntURLProtocolEditObj::getObjFullName() {
const static std::string S_Dot( "." );
std::string fullName = getObjName();
cflib::ICFLibAnyObj* container = getObjScope();
std::string containerName;
std::string buildName;
while( container != NULL ) {
if( container->getClassCode() == cfsec::CFSecClusterBuff::CLASS_CODE ) {
container = NULL;
}
else if( container->getClassCode() == cfsec::CFSecTenantBuff::CLASS_CODE ) {
container = NULL;
}
else {
containerName = container->getObjName();
buildName.clear();
buildName.append( containerName );
buildName.append( S_Dot );
buildName.append( fullName );
fullName.clear();
fullName.append( buildName );
container = container->getObjScope();
}
}
return( fullName );
}
cfint::ICFIntURLProtocolObj* CFIntURLProtocolEditObj::realize() {
// We realize this so that it's buffer will get copied to orig during realization
cfint::ICFIntURLProtocolObj* retobj = getSchema()->getURLProtocolTableObj()->realizeURLProtocol( dynamic_cast<cfint::ICFIntURLProtocolObj*>( this ) );
return( retobj );
}
cfint::ICFIntURLProtocolObj* CFIntURLProtocolEditObj::read( bool forceRead ) {
cfint::ICFIntURLProtocolObj* retval = getOrigAsURLProtocol()->read( forceRead );
if( retval != orig ) {
throw cflib::CFLibUsageException( CLASS_NAME,
"read",
"retval != orig" );
}
copyOrigToBuff();
return( retval );
}
cfint::ICFIntURLProtocolObj* CFIntURLProtocolEditObj::create() {
cfint::ICFIntURLProtocolObj* retobj = dynamic_cast<cfint::ICFIntSchemaObj*>( getOrigAsURLProtocol()->getSchema() )->getURLProtocolTableObj()->createURLProtocol( this );
// Note that this instance is usually discarded during the creation process,
// and retobj now references the cached instance of the created object.
return( retobj );
}
cfint::ICFIntURLProtocolEditObj* CFIntURLProtocolEditObj::update() {
getSchema()->getURLProtocolTableObj()->updateURLProtocol( this );
return( NULL );
}
cfint::ICFIntURLProtocolEditObj* CFIntURLProtocolEditObj::deleteInstance() {
static const std::string S_MethodName( "deleteInstance" );
static const std::string S_CannotDeleteNewInstance( "Cannot delete a new instance" );
if( getIsNew() ) {
throw cflib::CFLibUsageException( CLASS_NAME, S_MethodName, S_CannotDeleteNewInstance );
}
getSchema()->getURLProtocolTableObj()->deleteURLProtocol( this );
return( NULL );
}
cfint::ICFIntURLProtocolTableObj* CFIntURLProtocolEditObj::getURLProtocolTable() {
return( orig->getSchema()->getURLProtocolTableObj() );
}
cfint::ICFIntURLProtocolEditObj* CFIntURLProtocolEditObj::getEdit() {
return( this );
}
cfint::ICFIntURLProtocolEditObj* CFIntURLProtocolEditObj::getURLProtocolEdit() {
return( (cfint::ICFIntURLProtocolEditObj*)this );
}
cfint::ICFIntURLProtocolEditObj* CFIntURLProtocolEditObj::beginEdit() {
static const std::string S_ProcName( "beginEdit" );
static const std::string S_Message( "Cannot edit an edition" );
throw cflib::CFLibUsageException( CLASS_NAME,
S_ProcName,
S_Message );
}
void CFIntURLProtocolEditObj::endEdit() {
orig->endEdit();
}
cfint::ICFIntURLProtocolObj* CFIntURLProtocolEditObj::getOrig() {
return( orig );
}
cfint::ICFIntURLProtocolObj* CFIntURLProtocolEditObj::getOrigAsURLProtocol() {
return( dynamic_cast<cfint::ICFIntURLProtocolObj*>( orig ) );
}
cfint::ICFIntSchemaObj* CFIntURLProtocolEditObj::getSchema() {
return( orig->getSchema() );
}
cfint::CFIntURLProtocolBuff* CFIntURLProtocolEditObj::getBuff() {
return( buff );
}
void CFIntURLProtocolEditObj::setBuff( cfint::CFIntURLProtocolBuff* value ) {
if( buff != value ) {
if( ( buff != NULL ) && ( buff != value ) ) {
delete buff;
buff = NULL;
}
buff = value;
}
}
cfint::CFIntURLProtocolPKey* CFIntURLProtocolEditObj::getPKey() {
return( orig->getPKey() );
}
void CFIntURLProtocolEditObj::setPKey( cfint::CFIntURLProtocolPKey* value ) {
if( orig->getPKey() != value ) {
orig->setPKey( value );
}
copyPKeyToBuff();
}
bool CFIntURLProtocolEditObj::getIsNew() {
return( orig->getIsNew() );
}
void CFIntURLProtocolEditObj::setIsNew( bool value ) {
orig->setIsNew( value );
}
const int32_t CFIntURLProtocolEditObj::getRequiredURLProtocolId() {
return( getPKey()->getRequiredURLProtocolId() );
}
const int32_t* CFIntURLProtocolEditObj::getRequiredURLProtocolIdReference() {
return( getPKey()->getRequiredURLProtocolIdReference() );
}
const std::string& CFIntURLProtocolEditObj::getRequiredName() {
return( getURLProtocolBuff()->getRequiredName() );
}
const std::string* CFIntURLProtocolEditObj::getRequiredNameReference() {
return( getURLProtocolBuff()->getRequiredNameReference() );
}
void CFIntURLProtocolEditObj::setRequiredName( const std::string& value ) {
if( getURLProtocolBuff()->getRequiredName() != value ) {
getURLProtocolEditBuff()->setRequiredName( value );
}
}
const std::string& CFIntURLProtocolEditObj::getRequiredDescription() {
return( getURLProtocolBuff()->getRequiredDescription() );
}
const std::string* CFIntURLProtocolEditObj::getRequiredDescriptionReference() {
return( getURLProtocolBuff()->getRequiredDescriptionReference() );
}
void CFIntURLProtocolEditObj::setRequiredDescription( const std::string& value ) {
if( getURLProtocolBuff()->getRequiredDescription() != value ) {
getURLProtocolEditBuff()->setRequiredDescription( value );
}
}
const bool CFIntURLProtocolEditObj::getRequiredIsSecure() {
return( getURLProtocolBuff()->getRequiredIsSecure() );
}
const bool* CFIntURLProtocolEditObj::getRequiredIsSecureReference() {
return( getURLProtocolBuff()->getRequiredIsSecureReference() );
}
void CFIntURLProtocolEditObj::setRequiredIsSecure( const bool value ) {
if( getURLProtocolBuff()->getRequiredIsSecure() != value ) {
getURLProtocolEditBuff()->setRequiredIsSecure( value );
}
}
void CFIntURLProtocolEditObj::copyPKeyToBuff() {
cfint::CFIntURLProtocolPKey* tablePKey = getPKey();
cfint::CFIntURLProtocolBuff* tableBuff = getURLProtocolEditBuff();
tableBuff->setRequiredURLProtocolId( tablePKey->getRequiredURLProtocolId() );
}
void CFIntURLProtocolEditObj::copyBuffToPKey() {
cfint::CFIntURLProtocolPKey* tablePKey = getPKey();
cfint::CFIntURLProtocolBuff* tableBuff = getURLProtocolBuff();
tablePKey->setRequiredURLProtocolId( tableBuff->getRequiredURLProtocolId() );
}
void CFIntURLProtocolEditObj::copyBuffToOrig() {
cfint::CFIntURLProtocolBuff* origBuff = getOrigAsURLProtocol()->getURLProtocolEditBuff();
cfint::CFIntURLProtocolBuff* myBuff = getURLProtocolBuff();
if( origBuff != myBuff ) {
*origBuff = *myBuff;
}
}
void CFIntURLProtocolEditObj::copyOrigToBuff() {
cfint::CFIntURLProtocolBuff* origBuff = getOrigAsURLProtocol()->getURLProtocolBuff();
cfint::CFIntURLProtocolBuff* myBuff = getURLProtocolEditBuff();
if( origBuff != myBuff ) {
*myBuff = *origBuff;
}
}
}
| 33.724 | 170 | 0.726308 | [
"object"
] |
7db96f120a2e94e9b3767585fb2748eca5aba2a6 | 12,052 | cpp | C++ | manta_positioning/src/manta_positioning.cpp | lgkimjy/manta_pozyx | 2f9cac8d9df99538e5f9c51498eaaa25907ea8b0 | [
"MIT"
] | 1 | 2021-09-24T07:17:21.000Z | 2021-09-24T07:17:21.000Z | manta_positioning/src/manta_positioning.cpp | lgkimjy/manta_pozyx | 2f9cac8d9df99538e5f9c51498eaaa25907ea8b0 | [
"MIT"
] | null | null | null | manta_positioning/src/manta_positioning.cpp | lgkimjy/manta_pozyx | 2f9cac8d9df99538e5f9c51498eaaa25907ea8b0 | [
"MIT"
] | null | null | null | /*
* manta_positioning.cpp
* Author: junyoung kim / lgkimjy
*/
#include "manta_positioning/manta_positioning.h"
void readConfigData()
{
try{
lpf_doc = YAML::LoadFile(path_lpf.c_str());
offset_doc = YAML::LoadFile(path_offset.c_str());
ROS_INFO("[Positioning Node] Read Config Data");
}
catch(const std::exception& e){
ROS_ERROR("Fail to load Config yaml file!");
return;
}
tags.clear();
for(int i=0; i<docs.size(); i++)
{
tag temp;
temp.id = lpf_doc[docs[i]]["id"].as<string>();
temp.alpha[0] = lpf_doc[docs[i]]["x_alpha"].as<float>();
temp.alpha[1] = lpf_doc[docs[i]]["y_alpha"].as<float>();
temp.alpha[2] = lpf_doc[docs[i]]["z_alpha"].as<float>();
temp.offset[0] = offset_doc[docs[i]]["x"].as<float>();
temp.offset[1] = offset_doc[docs[i]]["y"].as<float>();
temp.offset[2] = offset_doc[docs[i]]["z"].as<float>();
tags.push_back(temp);
}
}
void updateConfigData()
{
try{
lpf_doc = YAML::LoadFile(path_lpf.c_str());
offset_doc = YAML::LoadFile(path_offset.c_str());
}
catch(const std::exception& e){
ROS_ERROR("Fail to load Config yaml file!");
return;
}
for(int i=0; i<docs.size(); i++)
{
tags[i].alpha[0] = lpf_doc[docs[i]]["x_alpha"].as<float>();
tags[i].alpha[1] = lpf_doc[docs[i]]["y_alpha"].as<float>();
tags[i].alpha[2] = lpf_doc[docs[i]]["z_alpha"].as<float>();
tags[i].offset[0] = offset_doc[docs[i]]["x"].as<float>();
tags[i].offset[1] = offset_doc[docs[i]]["y"].as<float>();
tags[i].offset[2] = offset_doc[docs[i]]["z"].as<float>();
}
}
float LowPassFilter(tag tag_data, int index, int num)
{
float output;
output = tag_data.alpha[num] * tag_data.pose[num] + (1.0 - tag_data.alpha[num]) * tag_data.prev_raw_value[num];
tags[index].pose[num] = output;
tags[index].prev_raw_value[num] = output;
return output;
}
float MovingAvgeFilter(float raw_value, int n_samples)
{
float output;
float samples;
data_buff.push_back(raw_value);
if(data_buff.size() == 1){
output = raw_value;
}
else if(data_buff.size() < n_samples){
output = (accumulate(data_buff.begin(), data_buff.end(), 0)) / data_buff.size();
}
else{
samples = data_buff.front();
data_buff.erase(data_buff.begin());
output = prev_avg_value + (raw_value - samples) / n_samples;
prev_avg_value = output;
}
return output;
}
float setoffset(tag tag_data, int index, int num)
{
float output;
output = tag_data.pose[num] - tag_data.offset[num];
tags[index].pose[num] = output;
return output;
}
bool computeOrientation(
WorldFrame::WorldFrame frame,
geometry_msgs::Vector3 A,
geometry_msgs::Vector3 E,
geometry_msgs::Quaternion &orientation)
{
float Hx, Hy, Hz;
float Mx, My, Mz;
float normH;
// A: pointing up
// E: pointing down/north
float Ax = A.x, Ay = A.y, Az = A.z;
float Ex = E.x, Ey = E.y, Ez = E.z;
// H: vector horizontal, pointing east
// H = E x A
crossProduct(Ex, Ey, Ez, Ax, Ay, Az, Hx, Hy, Hz);
// normalize H
normH = normalizeVector(Hx, Hy, Hz);
if (normH < 1E-7) return false; // device is close to free fall or close to magnetic north pole. typical threshold values are > 1E-5.
// normalize A
normalizeVector(Ax, Ay, Az);
// M: vector horizontal, pointing north
// M = A x H
crossProduct(Ax, Ay, Az, Hx, Hy, Hz, Mx, My, Mz);
// Create matrix for basis transformation
tf2::Matrix3x3 R;
switch (frame)
{
case WorldFrame::NED:
// R: Transform Matrix local => world equals basis of L, because basis of W is I
R[0][0] = Mx; R[0][1] = Hx; R[0][2] = -Ax;
R[1][0] = My; R[1][1] = Hy; R[1][2] = -Ay;
R[2][0] = Mz; R[2][1] = Hz; R[2][2] = -Az;
break;
case WorldFrame::NWU:
// R: Transform Matrix local => world equals basis of L, because basis of W is I
R[0][0] = Mx; R[0][1] = -Hx; R[0][2] = Ax;
R[1][0] = My; R[1][1] = -Hy; R[1][2] = Ay;
R[2][0] = Mz; R[2][1] = -Hz; R[2][2] = Az;
break;
default:
case WorldFrame::ENU:
// R: Transform Matrix local => world equals basis of L, because basis of W is I
R[0][0] = Hx; R[0][1] = Mx; R[0][2] = Ax;
R[1][0] = Hy; R[1][1] = My; R[1][2] = Ay;
R[2][0] = Hz; R[2][1] = Mz; R[2][2] = Az;
break;
}
// Matrix.getRotation assumes vector rotation, but we're using coordinate systems. Thus negate rotation angle (inverse).
tf2::Quaternion q;
R.getRotation(q);
tf2::convert(q.inverse(), orientation);
return true;
}
double Convert(double radian)
{
double pi = 3.14159;
return(radian * (180 / pi));
}
void imuMagPoseCallback(
const mqtt2ros::mqtt_imu::ConstPtr &imu_msg_raw,
const mqtt2ros::mqtt_mag::ConstPtr &mag_msg,
const mqtt2ros::mqtt_msg::ConstPtr &msg)
{
updateConfigData();
pose_msg.data.clear();
if(flag == 0){
for(int i=0; i<msg->data.size(); i++){
for(int j=0; j<tags.size(); j++){
if(tags[j].id == msg->data[i].header.frame_id){
tags[j].prev_raw_value[0] = msg->data[i].pose.position.x;
tags[j].prev_raw_value[1] = msg->data[i].pose.position.y;
tags[j].prev_raw_value[2] = msg->data[i].pose.position.z;
}
}
}
flag++;
}
if(ahrs_flag) ROS_INFO("----------------------------------------------------------");
for(int i=0; i<msg->data.size(); i++){
pose = msg->data[i]; // data copy (deep copy)
for(int j=0; j<tags.size(); j++){
if(tags[j].id == msg->data[i].header.frame_id){
tags[j].pose[0] = msg->data[i].pose.position.x;
tags[j].pose[1] = msg->data[i].pose.position.y;
tags[j].pose[2] = msg->data[i].pose.position.z;
// Filtering (LPF)
pose.pose.position.x = LowPassFilter(tags[j], j, 0); // Low Pass Filter x
pose.pose.position.y = LowPassFilter(tags[j], j, 1); // Low Pass Filter y
pose.pose.position.z = LowPassFilter(tags[j], j, 2); // Low Pass Filter z
// Offset
pose.pose.position.x = setoffset(tags[j], j, 0); // offset x
pose.pose.position.y = setoffset(tags[j], j, 1); // offset y
pose.pose.position.z = setoffset(tags[j], j, 2); // offset z
geometry_msgs::Vector3 ang_vel = imu_msg_raw->data[i].angular_velocity;
geometry_msgs::Vector3 lin_acc = imu_msg_raw->data[i].linear_acceleration;
geometry_msgs::Vector3 mag_fld = mag_msg->data[i].magnetic_field;
if(ahrs_flag){
double roll, pitch, yaw = 0.0;
// wait for mag message without NaN / inf
if (!isfinite(mag_fld.x) || !isfinite(mag_fld.y) || !isfinite(mag_fld.z)) return;
geometry_msgs::Quaternion init_q;
if (!computeOrientation(WorldFrame::ENU, lin_acc, mag_fld, init_q))
{
ROS_WARN_THROTTLE(5.0, "[%s] The IMU seems to be in free fall or close to magnetic north pole, cannot determine gravity direction!", msg->data[i].header.frame_id.c_str());
return;
}
// ROS_INFO("[%s] %f | %f | %f | %f ", msg->data[i].header.frame_id.c_str(), init_q.x, init_q.y, init_q.z,init_q.w);
tf2::Matrix3x3(tf2::Quaternion(init_q.x, init_q.y, init_q.z,init_q.w)).getRPY(roll, pitch, yaw, 0);
ROS_INFO("[%s] %f | %f | %f ", msg->data[i].header.frame_id.c_str() ,Convert(roll), Convert(pitch), Convert(yaw));
/*
have to apply madgwickAHRSupdateIMU function to calculate absolute heading
*/
pose.pose.orientation.x = Convert(roll);
pose.pose.orientation.y = Convert(pitch);
pose.pose.orientation.z = Convert(yaw);
}
}
}
pose_msg.data.push_back(pose);
}
pose_pub.publish(pose_msg);
}
void poseCallback(const mqtt2ros::mqtt_msg::ConstPtr& msg)
{
updateConfigData();
pose_msg.data.clear();
if(flag == 0){
for(int i=0; i<msg->data.size(); i++){
for(int j=0; j<tags.size(); j++){
if(tags[j].id == msg->data[i].header.frame_id){
tags[j].prev_raw_value[0] = msg->data[i].pose.position.x;
tags[j].prev_raw_value[1] = msg->data[i].pose.position.y;
tags[j].prev_raw_value[2] = msg->data[i].pose.position.z;
}
}
}
flag++;
}
for(int i=0; i<msg->data.size(); i++){
pose = msg->data[i]; // data copy (deep copy)
for(int j=0; j<tags.size(); j++){
if(tags[j].id == msg->data[i].header.frame_id){
tags[j].pose[0] = msg->data[i].pose.position.x;
tags[j].pose[1] = msg->data[i].pose.position.y;
tags[j].pose[2] = msg->data[i].pose.position.z;
// Filtering
pose.pose.position.x = LowPassFilter(tags[j], j, 0); // Low Pass Filter x
pose.pose.position.y = LowPassFilter(tags[j], j, 1); // Low Pass Filter y
pose.pose.position.z = LowPassFilter(tags[j], j, 2); // Low Pass Filter z
// Offset
pose.pose.position.x = setoffset(tags[j], j, 0); // offset x
pose.pose.position.y = setoffset(tags[j], j, 1); // offset y
pose.pose.position.z = setoffset(tags[j], j, 2); // offset z
}
}
pose_msg.data.push_back(pose);
}
pose_pub.publish(pose_msg);
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "manta_positioning_node");
ros::NodeHandle nh;
ros::Rate loop_rate(10);
ROS_INFO("[Positioning Node] Initialize");
int queue_size = 5;
// ros::Subscriber obstacle_sub = nh.subscribe("/mqtt_coord", queue_size, poseCallback); // Data from mqtt protocol
message_filters::Subscriber<mqtt2ros::mqtt_imu> image_sub(nh, "/mqtt_imu", 1);
message_filters::Subscriber<mqtt2ros::mqtt_mag> mag_sub(nh, "/mqtt_mag", 1);
message_filters::Subscriber<mqtt2ros::mqtt_msg> pose_sub(nh, "/mqtt_coord", 1);
TimeSynchronizer<mqtt2ros::mqtt_imu, mqtt2ros::mqtt_mag, mqtt2ros::mqtt_msg> sync(image_sub, mag_sub, pose_sub, 10);
sync.registerCallback(boost::bind(imuMagPoseCallback, _1, _2, _3));
pose_pub = nh.advertise<mqtt2ros::mqtt_msg>("/filtered/mqtt_coord", 10);
path_lpf = ros::package::getPath("manta_positioning") + "/config/LPF.yaml";
path_offset = ros::package::getPath("manta_positioning") + "/config/offset.yaml";
docs = {"tag 101", "tag 102", "tag 103", "tag 104", "tag 105", "tag 106", "tag 107", "tag 108", "tag 109", "tag 110",
"tag 111", "tag 112", "tag 113", "tag 114", "tag 115", "tag 116", "tag 117", "tag 118", "tag 119", "tag 120",
"tag 121", "tag 122", "tag 123", "tag 124", "tag 125", "tag 126", "tag 127", "tag 128", "tag 129", "tag 130",
"tag 131", "tag 132", "tag 133", "tag 134", "tag 135", "tag 136", "tag 137", "tag 138", "tag 139", "tag 140",
"tag 141", "tag 142", "tag 143", "tag 144", "tag 145", "tag 146", "tag 147", "tag 148", "tag 149", "tag 150"};
readConfigData();
while (ros::ok())
{
ros::spinOnce();
loop_rate.sleep();
}
return 0;
} | 38.504792 | 195 | 0.537753 | [
"vector",
"transform"
] |
7dba30ecfc578d2d0f6a3f35c5cf7adeec2012fe | 3,996 | cpp | C++ | src/logging/logger.cpp | CraftSpider/AlphaUtils | 70ff9cd4ec4184f67d7e8b779538ef88f1e88682 | [
"MIT"
] | 1 | 2019-06-23T14:03:16.000Z | 2019-06-23T14:03:16.000Z | src/logging/logger.cpp | CraftSpider/AlphaUtils | 70ff9cd4ec4184f67d7e8b779538ef88f1e88682 | [
"MIT"
] | null | null | null | src/logging/logger.cpp | CraftSpider/AlphaUtils | 70ff9cd4ec4184f67d7e8b779538ef88f1e88682 | [
"MIT"
] | 2 | 2019-06-23T14:03:17.000Z | 2020-11-19T02:16:51.000Z |
#include <stdexcept>
#include <sstream>
#include <cctype>
#include "logging/logger.h"
namespace logging {
Logger::Logger(const std::string& name) {
this->name = name;
this->level = NO_LEVEL;
this->stream_level = AT_DEFAULT_LOGGER_LEVEL;
this->handlers = std::vector<Handler*>();
}
Logger& Logger::operator<<(Level* level) {
stream_level = level;
return *this;
}
Logger& Logger::operator<<(const std::string& input) {
this->log(input, stream_level);
return *this;
}
Level* Logger::get_effective_level() const {
if (level == NO_LEVEL) {
return parent->get_effective_level();
}
return level;
}
std::string Logger::get_effective_pattern() const {
if (pattern.empty()) {
return parent->get_effective_pattern();
}
return pattern;
}
std::string Logger::format_instruct(const std::string& instruct, std::string message, const Level* level) {
std::stringstream out;
if (instruct[0] == 'l') {
out << (std::string)*level;
} else if (instruct[0] == 'm') {
out << message;
} else if (instruct[0] == 'n') {
out << name;
} else {
throw std::runtime_error("Unrecognized log format instruction");
}
return out.str();
}
std::string Logger::log_format(const std::string& message, const Level* level) {
bool escaped = false, in_pat = false;
std::stringstream out;
std::string instruct, eff_pattern = get_effective_pattern();
for (char c : eff_pattern) {
if (escaped) {
out << c;
} else if (in_pat) {
if (!std::isalnum(c)) {
out << format_instruct(instruct, message, level);
instruct = "";
if (c != '%') {
in_pat = false;
out << c;
}
} else {
instruct += c;
}
continue;
}
if (c == '\\') {
escaped = true;
} else if (c == '%') {
in_pat = true;
} else {
out << c;
}
}
if (!instruct.empty()) {
out << format_instruct(instruct, message, level);
}
return out.str();
}
void Logger::set_level(Level* level) {
if (name == "root" && level == NO_LEVEL) {
throw std::runtime_error("Root logger cannot have NO_LEVEL");
}
this->level = level;
}
Level* Logger::get_level() const {
return level;
}
void Logger::set_pattern(const std::string& pattern) {
this->pattern = pattern;
}
std::string Logger::get_pattern() const {
return pattern;
}
void Logger::set_parent(Logger* parent) {
this->parent = parent;
}
Logger* Logger::get_parent() const {
return parent;
}
void Logger::log(const std::string& message, const Level* level) {
if (propagate && parent != nullptr) {
parent->log(message, level);
}
if (*level >= *get_effective_level()) {
for (auto handler : handlers) {
handler->log(log_format(message, level), level);
}
}
}
void Logger::trace(const std::string& message) {
log(message, TRACE);
}
void Logger::debug(const std::string& message) {
log(message, DEBUG);
}
void Logger::info(const std::string& message) {
log(message, INFO);
}
void Logger::warn(const std::string& message) {
log(message, WARN);
}
void Logger::error(const std::string& message) {
log(message, ERROR);
}
void Logger::fatal(const std::string& message) {
log(message, FATAL);
}
void Logger::add_handler(Handler* handler) {
handlers.push_back(handler);
}
bool Logger::remove_handler(Handler* handler) {
for (std::size_t i = 0; i < handlers.size(); ++i) {
if (handlers[i] == handler) {
handlers.erase(handlers.begin() + i);
return true;
}
}
return false;
}
void Logger::set_propagation(bool propagate) {
this->propagate = propagate;
}
bool Logger::get_propagation() const {
return propagate;
}
} | 22.965517 | 107 | 0.574825 | [
"vector"
] |
7dbef915f8fbe8f5728b0a9d643ac74eaef5ad07 | 5,118 | cc | C++ | mace/ops/nonlocal_reshape.cc | zhangzhimin/mace | c28f093d719fd650a4308895cd045c26d0f198f6 | [
"Apache-2.0"
] | 1 | 2021-08-02T12:17:58.000Z | 2021-08-02T12:17:58.000Z | mace/ops/nonlocal_reshape.cc | zhangzhimin/mace | c28f093d719fd650a4308895cd045c26d0f198f6 | [
"Apache-2.0"
] | null | null | null | mace/ops/nonlocal_reshape.cc | zhangzhimin/mace | c28f093d719fd650a4308895cd045c26d0f198f6 | [
"Apache-2.0"
] | 1 | 2021-08-02T12:18:00.000Z | 2021-08-02T12:18:00.000Z | // Copyright 2020 The MACE Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <vector>
#include "mace/core/ops/operator.h"
#include "mace/core/registry/ops_registry.h"
#include "mace/utils/math.h"
#ifdef MACE_ENABLE_OPENCL
#include "mace/ops/opencl/buffer/reshape.h"
#include "mace/ops/opencl/image/reshape.h"
#endif
namespace mace {
namespace ops {
template <DeviceType D, class T>
class NonlocalReshapeOp : public Operation {
public:
explicit NonlocalReshapeOp(OpConstructContext *context)
: Operation(context),
has_df_(Operation::GetOptionalArg<int>("has_data_format", 0)) {}
MaceStatus Run(OpContext *context) override {
MACE_UNUSED(context);
const Tensor *input = this->Input(INPUT);
const Tensor *shape = this->Input(SHAPE);
std::vector<index_t> out_shape;
for (int i = 0; i < 2; i++) {
out_shape.push_back(input->dim(i));
}
for (int i = 2; i < 4; i++) {
out_shape.push_back(shape->dim(i));
}
Tensor *output = this->Output(OUTPUT);
output->ReuseTensorBuffer(*input);
output->Reshape(out_shape);
return MaceStatus::MACE_SUCCESS;
}
private:
bool has_df_;
private:
MACE_OP_INPUT_TAGS(INPUT, SHAPE);
MACE_OP_OUTPUT_TAGS(OUTPUT);
};
#ifdef MACE_ENABLE_OPENCL
template <>
class NonlocalReshapeOp<GPU, float> : public Operation {
public:
explicit NonlocalReshapeOp(OpConstructContext *context)
: Operation(context) {
if (context->GetOpMemoryType() == MemoryType::GPU_IMAGE) {
kernel_ = make_unique<opencl::image::ReshapeKernel>(context);
} else {
kernel_ = make_unique<opencl::buffer::ReshapeKernel>();
}
}
MaceStatus Run(OpContext *context) override {
const Tensor *input = this->Input(INPUT);
const Tensor *shape = this->Input(SHAPE);
std::vector<index_t> out_shape;
for (int i = 0; i < 2; i++) {
out_shape.push_back(input->dim(i));
}
for (int i = 2; i < 4; i++) {
out_shape.push_back(shape->dim(i));
}
Tensor *output = this->Output(OUTPUT);
return kernel_->Compute(context, input, out_shape, output);
}
private:
std::unique_ptr<OpenCLReshapeKernel> kernel_;
MACE_OP_INPUT_TAGS(INPUT, SHAPE);
MACE_OP_OUTPUT_TAGS(OUTPUT);
};
#endif
void RegisterNonlocalReshape(OpRegistry *op_registry) {
MACE_REGISTER_OP(op_registry, "NonlocalReshape",
NonlocalReshapeOp, DeviceType::CPU, float);
MACE_REGISTER_OP(op_registry, "NonlocalReshape",
NonlocalReshapeOp, DeviceType::CPU, int32_t);
MACE_REGISTER_GPU_OP(op_registry, "NonlocalReshape", NonlocalReshapeOp);
MACE_REGISTER_OP_CONDITION(
op_registry, OpConditionBuilder("NonlocalReshape").SetDevicePlacerFunc(
[](OpConditionContext *context) -> std::set<DeviceType> {
auto op = context->operator_def();
if (op->output_shape_size() != op->output_size()) {
return {DeviceType::CPU, DeviceType::GPU};
}
// When transforming a model, has_data_format is set
// to true only when the data dimension conforms to
// specific rules, such as dimension == 4
int has_data_format =
ProtoArgHelper::GetOptionalArg<OperatorDef, int>(
*op, "has_data_format", 0);
if (has_data_format) {
return {DeviceType::CPU, DeviceType::GPU};
}
DataFormat op_data_format = static_cast<DataFormat>(
ProtoArgHelper::GetOptionalArg<OperatorDef, int>(
*context->operator_def(), "data_format",
static_cast<int>(DataFormat::NONE)));
auto tensor_shape_info = context->tensor_shape_info();
const std::string &input_0 = op->input(0);
const auto out_dims_size =
op->output_shape(0).dims_size();
if (op_data_format == DataFormat::NHWC &&
4 == tensor_shape_info->at(input_0).size() &&
(out_dims_size == 4 || out_dims_size == 2)) {
return {DeviceType::CPU, DeviceType::GPU};
}
return {DeviceType::CPU};
}));
}
} // namespace ops
} // namespace mace
| 36.297872 | 80 | 0.601798 | [
"shape",
"vector",
"model"
] |
7dc54a75cb2afdd7dc69216420a11c83c4320f2a | 5,231 | cpp | C++ | ace/tao/orbsvcs/tests/CosEvent/Basic/Shutdown.cpp | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | 46 | 2015-12-04T17:12:58.000Z | 2022-03-11T04:30:49.000Z | ace/tao/orbsvcs/tests/CosEvent/Basic/Shutdown.cpp | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | null | null | null | ace/tao/orbsvcs/tests/CosEvent/Basic/Shutdown.cpp | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | 23 | 2016-10-24T09:18:14.000Z | 2022-02-25T02:11:35.000Z | // Shutdown.cpp,v 1.2 2000/02/15 16:25:09 coryan Exp
#include "Counting_Consumer.h"
#include "Counting_Supplier.h"
#include "orbsvcs/CosEvent/CEC_EventChannel.h"
#include "orbsvcs/CosEvent/CEC_Default_Factory.h"
ACE_RCSID(CEC_Tests_Basic, Shutdown, "Shutdown.cpp,v 1.2 2000/02/15 16:25:09 coryan Exp")
static void run_test (PortableServer::POA_ptr poa,
int with_callbacks,
CORBA::Environment &ACE_TRY_ENV);
int
main (int argc, char* argv[])
{
TAO_CEC_Default_Factory::init_svcs ();
ACE_DECLARE_NEW_CORBA_ENV;
ACE_TRY
{
// ORB initialization boiler plate...
CORBA::ORB_var orb =
CORBA::ORB_init (argc, argv, "", ACE_TRY_ENV);
ACE_TRY_CHECK;
CORBA::Object_var object =
orb->resolve_initial_references ("RootPOA", ACE_TRY_ENV);
ACE_TRY_CHECK;
PortableServer::POA_var poa =
PortableServer::POA::_narrow (object.in (), ACE_TRY_ENV);
ACE_TRY_CHECK;
PortableServer::POAManager_var poa_manager =
poa->the_POAManager (ACE_TRY_ENV);
ACE_TRY_CHECK;
poa_manager->activate (ACE_TRY_ENV);
ACE_TRY_CHECK;
// ****************************************************************
run_test (poa.in (), 0, ACE_TRY_ENV);
ACE_TRY_CHECK;
run_test (poa.in (), 1, ACE_TRY_ENV);
ACE_TRY_CHECK;
// ****************************************************************
poa->destroy (1, 1, ACE_TRY_ENV);
ACE_TRY_CHECK;
orb->destroy (ACE_TRY_ENV);
ACE_TRY_CHECK;
}
ACE_CATCHANY
{
ACE_PRINT_EXCEPTION (ACE_ANY_EXCEPTION, "Service");
return 1;
}
ACE_ENDTRY;
return 0;
}
void
deactivate_servant (PortableServer::Servant servant,
CORBA::Environment &ACE_TRY_ENV)
{
PortableServer::POA_var poa =
servant->_default_POA (ACE_TRY_ENV);
ACE_CHECK;
PortableServer::ObjectId_var id =
poa->servant_to_id (servant, ACE_TRY_ENV);
ACE_CHECK;
poa->deactivate_object (id.in (), ACE_TRY_ENV);
ACE_CHECK;
}
static void
run_test (PortableServer::POA_ptr poa,
int with_callbacks,
CORBA::Environment &ACE_TRY_ENV)
{
TAO_CEC_EventChannel_Attributes attributes (poa,
poa);
attributes.disconnect_callbacks = with_callbacks;
TAO_CEC_EventChannel ec_impl (attributes);
ec_impl.activate (ACE_TRY_ENV);
ACE_CHECK;
CosEventChannelAdmin::EventChannel_var event_channel =
ec_impl._this (ACE_TRY_ENV);
ACE_CHECK;
// ****************************************************************
// Obtain the consumer admin..
CosEventChannelAdmin::ConsumerAdmin_var consumer_admin =
event_channel->for_consumers (ACE_TRY_ENV);
ACE_CHECK;
// Obtain the supplier admin..
CosEventChannelAdmin::SupplierAdmin_var supplier_admin =
event_channel->for_suppliers (ACE_TRY_ENV);
ACE_CHECK;
// ****************************************************************
CEC_Counting_Consumer **consumer;
CEC_Counting_Supplier **supplier;
const int n = 200;
ACE_NEW (consumer, CEC_Counting_Consumer*[n]);
ACE_NEW (supplier, CEC_Counting_Supplier*[n]);
int i;
for (i = 0; i != n; ++i)
{
char consumer_name[64];
ACE_OS::sprintf (consumer_name, "Consumer/%4.4d", i);
ACE_NEW (consumer[i],
CEC_Counting_Consumer (consumer_name));
ACE_NEW (supplier[i], CEC_Counting_Supplier ());
}
for (i = 0; i != n; ++i)
{
consumer[i]->connect (consumer_admin.in (), ACE_TRY_ENV);
ACE_CHECK;
supplier[i]->connect (supplier_admin.in (), ACE_TRY_ENV);
ACE_CHECK;
}
// ****************************************************************
// Destroy the event channel, *before* disconnecting the
// clients.
event_channel->destroy (ACE_TRY_ENV);
ACE_CHECK;
// ****************************************************************
for (i = 0; i != n; ++i)
{
if (consumer[i]->disconnect_count != 1)
ACE_DEBUG ((LM_DEBUG,
"ERRROR unexpected "
"disconnect count (%d) in Consumer/%04.4d\n",
consumer[i]->disconnect_count,
i));
if (supplier[i]->disconnect_count != 1)
ACE_DEBUG ((LM_DEBUG,
"ERRROR unexpected "
"disconnect count (%d) in Supplier/%04.4d\n",
supplier[i]->disconnect_count,
i));
}
// ****************************************************************
for (i = 0; i != n; ++i)
{
deactivate_servant (supplier[i], ACE_TRY_ENV);
ACE_CHECK;
delete supplier[i];
deactivate_servant (consumer[i], ACE_TRY_ENV);
ACE_CHECK;
delete consumer[i];
}
delete[] supplier;
delete[] consumer;
deactivate_servant (&ec_impl, ACE_TRY_ENV);
ACE_CHECK;
}
#if defined (ACE_HAS_EXPLICIT_TEMPLATE_INSTANTIATION)
#elif defined(ACE_HAS_TEMPLATE_INSTANTIATION_PRAGMA)
#endif /* ACE_HAS_EXPLICIT_TEMPLATE_INSTANTIATION */
| 28.123656 | 90 | 0.558402 | [
"object"
] |
7dcb375612f465abc2554258e9dae1be36fc7908 | 16,584 | cpp | C++ | src/engine/qos.cpp | tisuama/BaikalDB | 22e414eaac9dd6150f61976df6c735d6e51ea3f3 | [
"Apache-2.0"
] | 2 | 2020-04-09T02:09:19.000Z | 2021-12-23T06:56:22.000Z | src/engine/qos.cpp | tisuama/BaikalDB | 22e414eaac9dd6150f61976df6c735d6e51ea3f3 | [
"Apache-2.0"
] | null | null | null | src/engine/qos.cpp | tisuama/BaikalDB | 22e414eaac9dd6150f61976df6c735d6e51ea3f3 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2018-present Baidu, Inc. 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 <boost/algorithm/string.hpp>
#include "qos.h"
namespace baikaldb {
DEFINE_int64(qps_statistics_minutes_ago, 60, "qps_statistics_minutes_ago, default: 1h"); // 默认以前一小时的统计信息作为参考
DEFINE_int64(max_tokens_per_second, 100000, "max_tokens_per_second, default: 10w");
DEFINE_int64(use_token_bucket, 0, "use_token_bucket, 0:close; 1:open, default: 0");
DEFINE_int64(get_token_weight, 5, "get_token_weight, default: 5");
DEFINE_int64(min_global_extended_percent, 40, "min_global_extended_percent, default: 40%");
DEFINE_int64(token_bucket_adjust_interval_s, 60, "token_bucket_adjust_interval_s, default: 60s");
DEFINE_int64(token_bucket_burst_window_ms, 10, "token_bucket_burst_window_ms, default: 10ms");
DEFINE_int64(dml_use_token_bucket, 0, "dml_use_token_bucket, default: 0");
DEFINE_int64(sql_token_bucket_timeout_min, 5, "sql_token_bucket_timeout_min, default: 5min");
DEFINE_int64(qos_reject_interval_s, 30, "qos_reject_interval_s, default: 30s");
DEFINE_int64(qos_reject_ratio, 90, "qos_reject_ratio, default: 90%");
DEFINE_int64(qos_reject_timeout_s, 30*60, "qos_reject_timeout_s, default: 30min");
DEFINE_int64(qos_reject_max_scan_ratio, 50, "qos_reject_max_scan_ratio, default: 50%");
DEFINE_int64(qos_reject_growth_multiple, 100, "qos_reject_growth_multiple, default: 100倍");
DEFINE_int64(qos_need_reject, 0, "qos_need_reject, default: 0");
DEFINE_string(sign_blacklist, "", "sign blacklist");
// need_statistics: 超过最小超额令牌时,不计入统计信息
int64_t TokenBucket::consume(int64_t expect_tokens, int64_t* expire_time, bool* need_statistics) {
const int64_t now = butil::gettimeofday_us();
const int64_t divisor = now / (FLAGS_token_bucket_burst_window_ms * 1000);
const int64_t window_start = divisor * (FLAGS_token_bucket_burst_window_ms * 1000);
const int64_t window_end = (divisor + 1) * (FLAGS_token_bucket_burst_window_ms * 1000);
const int64_t time_need = expect_tokens * _time_per_token;
*expire_time = window_end;
int64_t old_time = _time.load(std::memory_order_relaxed);
int64_t new_time = old_time;
if (new_time > window_end) {
return -1;
}
if (!_valid) {
return -1;
}
if (new_time < window_start) {
// 前一个窗口的令牌丢弃
new_time = window_start;
}
while (true) {
if (new_time > window_end) {
return -1;
}
int64_t desired_time = new_time + time_need;
if (desired_time > window_end + _time_per_token) {
// 该窗口内令牌不足,减少令牌获取量
expect_tokens = (window_end - new_time) / _time_per_token + 1;
desired_time = new_time + expect_tokens * _time_per_token;
}
if (_time.compare_exchange_weak(old_time, desired_time)) {
if (_is_extended && desired_time > (window_start + _statistics_threshold)) {
// 获取的令牌超过了最小超额令牌桶限制,不计入qps统计,防止超过阈值后等比例压缩造成正常sql被挤压
*need_statistics = false;
} else {
*need_statistics = true;
}
return expect_tokens;
}
new_time = old_time;
}
return 0;
}
// 归还令牌
void TokenBucket::return_tokens(const int64_t tokens, const int64_t expire_time) {
const int64_t now = butil::gettimeofday_us();
const int64_t divisor = now / (FLAGS_token_bucket_burst_window_ms * 1000);
const int64_t window_start = divisor * (FLAGS_token_bucket_burst_window_ms * 1000);
const int64_t window_end = (divisor + 1) * (FLAGS_token_bucket_burst_window_ms * 1000);
const int64_t time_need = tokens * _time_per_token;
int64_t old_time = _time.load();
if (expire_time < now || expire_time <= window_start || expire_time < old_time) {
return;
}
int64_t new_time = old_time;
while (true) {
new_time -= time_need;
if (new_time < window_start) {
new_time = window_start;
}
if (_time.compare_exchange_weak(old_time, new_time)) {
return;
}
if (old_time > expire_time) {
return;
}
new_time = old_time;
}
}
QosBthreadLocal::QosBthreadLocal(QosType type, const uint64_t sign, const int64_t index_id) : _qos_type(type),
_sign(sign),
_index_id(index_id) {
_bthread_id = bthread_self();
if (_sign != 0) {
_sqlqos_ptr = StoreQos::get_instance()->get_sql_shared_ptr(sign);
_sqlqos_ptr->inc_index_count(index_id);
}
_get_token_weight = FLAGS_get_token_weight;
_use_token_bucket = FLAGS_use_token_bucket;
if (_sign == 0) {
// 非sql请求不使用令牌桶
_use_token_bucket = 0;
}
// DML需要单独判断是否需要限流
if (_use_token_bucket == 1 && type == QOS_DML) {
_use_token_bucket = FLAGS_dml_use_token_bucket;
}
}
QosBthreadLocal::~QosBthreadLocal() {
if (_sqlqos_ptr != nullptr) {
// sql统计
_sqlqos_ptr->dec_index_count(_index_id);
_sqlqos_ptr->sql_statistics_adder(1);
_sqlqos_ptr->get_statistics_adder(_get_count, _get_statistics_count);
_sqlqos_ptr->scan_statistics_adder(_scan_count, _scan_statistics_count);
}
}
void QosBthreadLocal::update_statistics() {
if (_sqlqos_ptr != nullptr) {
_sqlqos_ptr->get_statistics_adder(_get_count, _get_statistics_count);
_sqlqos_ptr->scan_statistics_adder(_scan_count, _scan_statistics_count);
_get_count = 0;
_scan_count = 0;
_get_statistics_count = 0;
_scan_statistics_count = 0;
}
}
void QosBthreadLocal::rate_limiting(int64_t tokens, bool* need_statistics) {
if (_use_token_bucket == 0) {
// 不限流
*need_statistics = true;
return;
}
if (tokens <= 0) {
*need_statistics = false;
return;
}
int64_t expire_time = 0;
_sqlqos_ptr->fetch_tokens(tokens, &expire_time, &_is_commited_bucket, need_statistics);
RocksdbVars::get_instance()->qos_fetch_tokens_count << tokens;
}
bool QosBthreadLocal::need_reject() {
if (_sqlqos_ptr != nullptr) {
return _sqlqos_ptr->need_reject(_index_id);
}
return false;
}
void SqlQos::get_statistics_adder(int64_t count, int64_t statistics_count) {
_get_real.adder(count);
_get_statistics.adder(statistics_count);
}
void SqlQos::scan_statistics_adder(int64_t count, int64_t statistics_count) {
_scan_real.adder(count);
_scan_statistics.adder(statistics_count);
}
void SqlQos::sql_statistics_adder(int64_t count) {
_sql_real.adder(count);
_sql_statistics.adder(count);
}
int64_t SqlQos::fetch_tokens(const int64_t tokens, int64_t* token_expire_time, bool* is_committed_bucket, bool* need_statistics) {
TimeCost cost;
bool wait = false;
ON_SCOPE_EXIT(([this, &wait, &cost, tokens]() {
_token_fetch.adder(tokens);
if (wait) {
RocksdbVars::get_instance()->qos_fetch_tokens_wait_time_cost << cost.get_time();
}
}));
while (true) {
int64_t expire_time = 0;
int64_t count = _committed_bucket.consume(tokens, &expire_time);
if (count > 0) {
// 从承诺令牌桶中获取成功
*is_committed_bucket = true;
*token_expire_time = expire_time;
*need_statistics = true;
return count;
}
// 从全局超额令牌桶中获取令牌
count = StoreQos::get_instance()->globle_extended_bucket_consume(tokens, &expire_time, need_statistics);
if (count > 0) {
*is_committed_bucket = false;
*token_expire_time = expire_time;
return count;
}
RocksdbVars::get_instance()->qos_fetch_tokens_wait_count << 1;
// 获取令牌失败,等待到下一个窗口
int64_t timeout_us = expire_time - butil::gettimeofday_us();
if (timeout_us < 0) {
RocksdbVars::get_instance()->qos_fetch_tokens_wait_count << -1;
continue;
}
bthread_usleep(timeout_us);
wait = true;
RocksdbVars::get_instance()->qos_fetch_tokens_wait_count << -1;
}
return 0;
}
void SqlQos::return_tokens(const int64_t tokens, const bool is_committed_bucket, const int64_t expire_time) {
if (is_committed_bucket) {
_committed_bucket.return_tokens(tokens, expire_time);
} else {
StoreQos::get_instance()->globle_extended_bucket_return_tokens(tokens, expire_time);
}
}
void QosReject::wheather_need_reject() {
const int window_count = FLAGS_qos_reject_interval_s * 1000 / FLAGS_token_bucket_burst_window_ms;
const int count = _count.get_value();
bool match_reject_condition = (count * 100 / window_count > FLAGS_qos_reject_ratio);
DB_WARNING("count: %d, window_count: %d, need_reject: %d, match_reject_condition: %d, time: %ld",
count, window_count, _has_reject, match_reject_condition, _reject_begin_time.get_time());
// 已经是拒绝状态
if (_has_reject) {
// 拒绝状态下压力无法降低,再次选择需要拒绝的sql
if (match_reject_condition && _reject_begin_time.get_time() > FLAGS_qos_reject_interval_s * 1000 * 1000LL) {
if (StoreQos::get_instance()->mark_need_reject_sql() >= 0) {
_reject_begin_time.reset();
DB_WARNING("mark need reject again count: %d, window_count: %d", count, window_count);
}
} else if (_reject_begin_time.get_time() > FLAGS_qos_reject_timeout_s * 1000 * 1000LL) {
// 超时清理拒绝标记
StoreQos::get_instance()->clear_need_reject();
_has_reject = false;
DB_WARNING("clear need reject, count: %d, window_count: %d", count, window_count);
}
} else if (match_reject_condition) {
if (StoreQos::get_instance()->mark_need_reject_sql() >= 0) {
_reject_begin_time.reset();
_has_reject = true;
DB_WARNING("mark need reject count: %d, window_count: %d", count, window_count);
}
}
}
void QosReject::update_blacklist() {
std::set<uint64_t> cur_blacklist;
if (!FLAGS_sign_blacklist.empty()) {
std::vector<std::string> vec;
boost::split(vec, FLAGS_sign_blacklist, boost::is_any_of(","));
for (auto& sign : vec) {
std::string sign_str = string_trim(sign);
cur_blacklist.insert(atoll(sign_str.c_str()));
}
}
if (cur_blacklist.empty() && _last_blacklist.empty()) {
return;
}
std::set<uint64_t> clear_list;
std::set<uint64_t> set_list;
for (uint64_t sign : _last_blacklist) {
if (cur_blacklist.find(sign) != cur_blacklist.end()) {
clear_list.insert(sign);
}
}
for (uint64_t sign : cur_blacklist) {
if (_last_blacklist.find(sign) != _last_blacklist.end()) {
set_list.insert(sign);
}
}
if (!clear_list.empty()) {
StoreQos::get_instance()->update_blacklist(clear_list, true);
}
if (!set_list.empty()) {
StoreQos::get_instance()->update_blacklist(set_list, false);
}
_last_blacklist.clear();
_last_blacklist = cur_blacklist;
}
void StoreQos::update_blacklist(const std::set<uint64_t>& signs, const bool is_clear) {
DoubleBufQos::ScopedPtr ptr;
if (_sign_sqlqos_map.Read(&ptr) != 0) {
return;
}
if (ptr->empty()) {
DB_WARNING("sign sqlqos map is empty");
return;
}
for (const auto& sign : signs) {
auto iter = ptr->find(sign);
if (iter != ptr->end()) {
if (is_clear) {
iter->second->clear_blacklist();
} else {
iter->second->set_blacklist();
}
}
}
}
void StoreQos::token_bucket_modify() {
int64_t max_token = FLAGS_max_tokens_per_second; // 最大qps限制
int64_t get_token_weight = FLAGS_get_token_weight; // get需要的令牌权重,即scan_token = get_token / weight
if (get_token_weight <= 0) {
get_token_weight = 5;
}
int64_t total_get_qps = 0;
int64_t total_scan_qps = 0;
analyze_qps(total_get_qps, total_scan_qps);
int64_t total_consume_token = total_get_qps + total_scan_qps / get_token_weight;
int64_t min_global_extended_tokens = max_token * FLAGS_min_global_extended_percent / 100;// 最小全局超额令牌个数
int64_t global_extended_token = max_token - total_consume_token;
double compression_ratio = 1.0; // 1.0 不压缩;< 1.0 等比例压缩
if ((max_token - min_global_extended_tokens) < total_consume_token) {
compression_ratio = (max_token - min_global_extended_tokens) * 1.0 / total_consume_token;
global_extended_token = min_global_extended_tokens;
total_consume_token = max_token - global_extended_token;
}
DB_WARNING("max_token: %ld, global_extended_token: %ld, total_consume_token: %ld, compression_ratio: %lf",
max_token, global_extended_token, total_consume_token, compression_ratio);
{
int64_t now = butil::gettimeofday_us();
DoubleBufQos::ScopedPtr ptr;
if (_sign_sqlqos_map.Read(&ptr) != 0) {
return;
}
for (auto iter : *ptr) {
int64_t get_qps = iter.second->rocksdb_get_qps();
int64_t scan_qps = iter.second->rocksdb_scan_qps();
int64_t consume_token = (get_qps + scan_qps / get_token_weight) * compression_ratio;
// 修改承诺令牌桶速率
iter.second->reset_committed_rate(consume_token);
total_consume_token -= consume_token;
if (consume_token != 0) {
DB_WARNING("sign: %lu, committed rate: %ld", iter.first, consume_token);
}
}
global_extended_token += total_consume_token;
DB_WARNING("globle extended bucket rate: %ld", global_extended_token);
// 修改全局超额令牌桶速率
_globle_extended_bucket.reset_rate(global_extended_token);
}
}
int StoreQos::mark_need_reject_sql() {
DoubleBufQos::ScopedPtr ptr;
if (_sign_sqlqos_map.Read(&ptr) != 0) {
return -1;
}
if (ptr->empty()) {
DB_WARNING("sign sqlqos map is empty");
return -1;
}
std::map<uint64_t, SqlInfo> sql_with_multi_index;
// std::map<int64_t, SqlInfo> get_qps_sqlinfo_map;
std::set<uint64_t> affect_indexids;
auto iter = ptr->begin();
while (iter != ptr->end()) {
auto cur_iter = iter++;
std::set<uint64_t> tmp_affect_indexids = cur_iter->second->fill_sqlqos_info(sql_with_multi_index);
for (uint64_t indexid : tmp_affect_indexids) {
affect_indexids.insert(indexid);
}
}
bool mark = false;
// 使用多个索引的高危sql
if (sql_with_multi_index.empty()) {
return -1;
}
for (auto it = sql_with_multi_index.rbegin(); it != sql_with_multi_index.rend(); it++) {
int64_t index_id = met_rejection_conditions(it->second, affect_indexids);
if (index_id <= 0) {
DB_WARNING("conditions not met. sign: %lu, log_term [get: %ld, scan: %ld], short_term [get: %ld, scan: %ld]",
it->first, it->second.get_long_term, it->second.scan_long_term, it->second.get_short_term, it->second.scan_short_term);
continue;
}
auto sql_it = ptr->find(it->first);
if (sql_it != ptr->end()) {
DB_WARNING("sql use multi index need reject sign: %lu, log_term [get: %ld, scan: %ld], short_term [get: %ld, scan: %ld]",
it->first, it->second.get_long_term, it->second.scan_long_term, it->second.get_short_term, it->second.scan_short_term);
sql_it->second->set_need_reject(index_id);
mark = true;
}
}
// 没有标记成功
if (!mark) {
return -1;
}
return 0;
}
} // namespace baikaldb
| 36.052174 | 135 | 0.637783 | [
"vector"
] |
7dd1704f1a966c6071635ec2594b81c424f6fa13 | 12,447 | cpp | C++ | src/shelly_rpc_service.cpp | louis49/shelly-homekit | 33bb58feca9dc51b85c59d98284adf0bd95cf885 | [
"Apache-2.0"
] | 1 | 2021-03-30T03:56:09.000Z | 2021-03-30T03:56:09.000Z | src/shelly_rpc_service.cpp | Mouttet/shelly-homekit | c2b899b60a6059bad495238ee6b34c33bf746e3b | [
"Apache-2.0"
] | null | null | null | src/shelly_rpc_service.cpp | Mouttet/shelly-homekit | c2b899b60a6059bad495238ee6b34c33bf746e3b | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) Shelly-HomeKit Contributors
* 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 "shelly_rpc_service.hpp"
#include "mgos.hpp"
#include "mgos_dns_sd.h"
#include "mgos_http_server.h"
#include "mgos_rpc.h"
#include "HAPAccessoryServer+Internal.h"
#include "shelly_debug.hpp"
#include "shelly_hap_switch.hpp"
#include "shelly_main.hpp"
namespace shelly {
static HAPAccessoryServerRef *s_server;
static HAPPlatformKeyValueStoreRef s_kvs;
static HAPPlatformTCPStreamManagerRef s_tcpm;
static void SendStatusResp(struct mg_rpc_request_info *ri, const Status &st) {
if (st.ok()) {
mg_rpc_send_responsef(ri, nullptr);
return;
}
mg_rpc_send_errorf(ri, st.error_code(), "%s", st.error_message().c_str());
}
static void GetInfoHandler(struct mg_rpc_request_info *ri, void *cb_arg,
struct mg_rpc_frame_info *fi, struct mg_str args) {
bool hap_paired = HAPAccessoryServerIsPaired(s_server);
bool hap_running = (HAPAccessoryServerGetState(s_server) ==
kHAPAccessoryServerState_Running);
HAPPlatformTCPStreamManagerStats tcpm_stats = {};
HAPPlatformTCPStreamManagerGetStats(s_tcpm, &tcpm_stats);
uint16_t hap_cn;
if (HAPAccessoryServerGetCN(s_kvs, &hap_cn) != kHAPError_None) {
hap_cn = 0;
}
bool debug_en = mgos_sys_config_get_file_logger_enable();
int flags = GetServiceFlags();
#ifdef MGOS_HAVE_WIFI
const char *wifi_ssid = mgos_sys_config_get_wifi_sta_ssid();
int wifi_rssi = mgos_wifi_sta_get_rssi();
char wifi_ip[16] = {};
struct mgos_net_ip_info ip_info = {};
if (mgos_net_get_ip_info(MGOS_NET_IF_TYPE_WIFI, MGOS_NET_IF_WIFI_STA,
&ip_info)) {
mgos_net_ip_to_str(&ip_info.ip, wifi_ip);
}
const char *wifi_ap_ssid = mgos_sys_config_get_wifi_ap_ssid();
const char *wifi_ap_ip = mgos_sys_config_get_wifi_ap_ip();
#endif
std::string res = mgos::JSONPrintStringf(
"{device_id: %Q, name: %Q, app: %Q, model: %Q, stock_model: %Q, "
"host: %Q, version: %Q, fw_build: %Q, uptime: %d, failsafe_mode: %B, "
#ifdef MGOS_HAVE_WIFI
"wifi_en: %B, wifi_ssid: %Q, wifi_pass: %Q, "
"wifi_rssi: %d, wifi_ip: %Q, wifi_ap_ssid: %Q, wifi_ap_ip: %Q, "
#endif
"hap_cn: %d, hap_running: %B, hap_paired: %B, "
"hap_ip_conns_pending: %u, hap_ip_conns_active: %u, "
"hap_ip_conns_max: %u, sys_mode: %d, wc_avail: %B, gdo_avail: %B, "
"debug_en: %B",
mgos_sys_config_get_device_id(), mgos_sys_config_get_shelly_name(),
MGOS_APP, CS_STRINGIFY_MACRO(PRODUCT_MODEL),
CS_STRINGIFY_MACRO(STOCK_FW_MODEL), mgos_dns_sd_get_host_name(),
mgos_sys_ro_vars_get_fw_version(), mgos_sys_ro_vars_get_fw_id(),
(int) mgos_uptime(), false /* failsafe_mode */,
#ifdef MGOS_HAVE_WIFI
mgos_sys_config_get_wifi_sta_enable(), (wifi_ssid ? wifi_ssid : ""),
(mgos_sys_config_get_wifi_sta_pass() ? "***" : ""), wifi_rssi, wifi_ip,
(wifi_ap_ssid ? wifi_ap_ssid : ""), (wifi_ap_ip ? wifi_ap_ip : ""),
#endif
hap_cn, hap_running, hap_paired,
(unsigned) tcpm_stats.numPendingTCPStreams,
(unsigned) tcpm_stats.numActiveTCPStreams,
(unsigned) tcpm_stats.maxNumTCPStreams, mgos_sys_config_get_shelly_mode(),
#ifdef MGOS_SYS_CONFIG_HAVE_WC1 // wc_avail
true,
#else
false,
#endif
#ifdef MGOS_SYS_CONFIG_HAVE_GDO1 // gdo_avail
true,
#else
false,
#endif
debug_en);
auto sys_temp = GetSystemTemperature();
if (sys_temp.ok()) {
mgos::JSONAppendStringf(&res, ", sys_temp: %d, overheat_on: %B",
sys_temp.ValueOrDie(),
(flags & SHELLY_SERVICE_FLAG_OVERHEAT));
}
mgos::JSONAppendStringf(&res, ", components: [");
bool first = true;
for (const auto &c : g_comps) {
const auto &is = c->GetInfoJSON();
if (is.ok()) {
if (!first) res.append(", ");
res.append(is.ValueOrDie());
first = false;
}
}
mgos::JSONAppendStringf(&res, "]}");
mg_rpc_send_responsef(ri, "%s", res.c_str());
(void) cb_arg;
(void) fi;
(void) args;
}
static void GetInfoFailsafeHandler(struct mg_rpc_request_info *ri, void *cb_arg,
struct mg_rpc_frame_info *fi,
struct mg_str args) {
mg_rpc_send_responsef(
ri,
"{device_id: %Q, name: %Q, app: %Q, model: %Q, stock_model: %Q, "
"host: %Q, version: %Q, fw_build: %Q, uptime: %d, failsafe_mode: %B}",
mgos_sys_config_get_device_id(), mgos_sys_config_get_shelly_name(),
MGOS_APP, CS_STRINGIFY_MACRO(PRODUCT_MODEL),
CS_STRINGIFY_MACRO(STOCK_FW_MODEL), mgos_dns_sd_get_host_name(),
mgos_sys_ro_vars_get_fw_version(), mgos_sys_ro_vars_get_fw_id(),
(int) mgos_uptime(), true /* failsafe_mode */);
(void) cb_arg;
(void) fi;
(void) args;
}
static void SetConfigHandler(struct mg_rpc_request_info *ri, void *cb_arg,
struct mg_rpc_frame_info *fi, struct mg_str args) {
int id = -1;
int type = -1;
struct json_token config_tok = JSON_INVALID_TOKEN;
json_scanf(args.p, args.len, ri->args_fmt, &id, &type, &config_tok);
if (config_tok.len == 0) {
mg_rpc_send_errorf(ri, 400, "%s is required", "config");
return;
}
Status st = Status::OK();
bool restart_required = false;
if (id == -1 && type == -1) {
// System settings.
char *name_c = NULL;
int sys_mode = -1;
int8_t debug_en = -1;
json_scanf(config_tok.ptr, config_tok.len,
"{name: %Q, sys_mode: %d, debug_en: %B}", &name_c, &sys_mode,
&debug_en);
mgos::ScopedCPtr name_owner(name_c);
if (sys_mode == 0 || sys_mode == 1 || sys_mode == 2) {
if (sys_mode != mgos_sys_config_get_shelly_mode()) {
mgos_sys_config_set_shelly_mode(sys_mode);
restart_required = true;
}
} else if (sys_mode == -1) {
// Nothing.
} else {
st = mgos::Errorf(STATUS_INVALID_ARGUMENT, "invalid %s", "sys_mode");
}
if (name_c != nullptr) {
mgos_expand_mac_address_placeholders(name_c);
std::string name(name_c);
if (name.length() > 64) {
mg_rpc_send_errorf(ri, 400, "invalid %s", "name");
return;
}
for (char c : name) {
if (!std::isalnum(c) && c != '-') {
mg_rpc_send_errorf(ri, 400, "invalid %s", "name");
return;
}
}
if (strcmp(mgos_sys_config_get_shelly_name(), name.c_str()) != 0) {
LOG(LL_INFO, ("Name change: %s -> %s",
mgos_sys_config_get_shelly_name(), name.c_str()));
mgos_sys_config_set_shelly_name(name.c_str());
mgos_sys_config_set_dns_sd_host_name(name.c_str());
mgos_dns_sd_set_host_name(name.c_str());
mgos_http_server_publish_dns_sd();
restart_required = true;
}
}
if (debug_en != -1) {
SetDebugEnable(debug_en);
}
} else {
// Component settings.
bool found = false;
for (auto &c : g_comps) {
if (c->id() != id || (int) c->type() != type) continue;
st = c->SetConfig(std::string(config_tok.ptr, config_tok.len),
&restart_required);
found = true;
break;
}
if (!found) {
st = mgos::Errorf(STATUS_INVALID_ARGUMENT, "component not found");
}
}
if (st.ok()) {
LOG(LL_ERROR, ("SetConfig ok, %d", restart_required));
mgos_sys_config_save(&mgos_sys_config, false /* try once */, nullptr);
if (restart_required) {
LOG(LL_INFO, ("Configuration change requires server restart"));
RestartService();
}
}
SendStatusResp(ri, st);
(void) cb_arg;
(void) fi;
}
static void SetStateHandler(struct mg_rpc_request_info *ri, void *cb_arg,
struct mg_rpc_frame_info *fi, struct mg_str args) {
int id = -1;
int type = -1;
struct json_token state_tok = JSON_INVALID_TOKEN;
json_scanf(args.p, args.len, ri->args_fmt, &id, &type, &state_tok);
if (state_tok.len == 0) {
mg_rpc_send_errorf(ri, 400, "%s is required", "state");
return;
}
Status st = Status::OK();
bool found = false;
for (auto &c : g_comps) {
if (c->id() != id || (int) c->type() != type) continue;
st = c->SetState(std::string(state_tok.ptr, state_tok.len));
found = true;
break;
}
if (!found) {
st = mgos::Errorf(STATUS_INVALID_ARGUMENT, "component not found");
}
SendStatusResp(ri, st);
(void) cb_arg;
(void) fi;
}
static void InjectInputEventHandler(struct mg_rpc_request_info *ri,
void *cb_arg, struct mg_rpc_frame_info *fi,
struct mg_str args) {
int id = -1, ev = -1;
json_scanf(args.p, args.len, ri->args_fmt, &id, &ev);
if (id < 0 || ev < 0) {
mg_rpc_send_errorf(ri, 400, "%s are required", "id and event");
return;
}
// Should we allow Reset event to be injected? Maybe. Disallow for now.
// For now we only allow "higher-level" events to be injected,
// since injecting Change won't match with the value returne by GetState.
if (ev != (int) Input::Event::kSingle && ev != (int) Input::Event::kDouble &&
ev != (int) Input::Event::kLong) {
mg_rpc_send_errorf(ri, 400, "invalid %s", "event");
return;
}
Input *in = FindInput(id);
if (in == nullptr) {
mg_rpc_send_errorf(ri, 400, "%s not found", "input");
return;
}
in->InjectEvent(static_cast<Input::Event>(ev), false);
mg_rpc_send_responsef(ri, nullptr);
(void) cb_arg;
(void) fi;
}
static void GetDebugInfoHandler(struct mg_rpc_request_info *ri, void *cb_arg,
struct mg_rpc_frame_info *fi,
struct mg_str args) {
std::string res;
GetDebugInfo(&res);
mg_rpc_send_responsef(ri, "{info: %Q}", res.c_str());
(void) cb_arg;
(void) args;
(void) fi;
}
static void WipeDeviceHandler(struct mg_rpc_request_info *ri, void *cb_arg,
struct mg_rpc_frame_info *fi,
struct mg_str args) {
bool wiped = WipeDevice();
mg_rpc_send_responsef(ri, "{wiped: %B}", wiped);
if (wiped) {
mgos_system_restart_after(500);
}
(void) cb_arg;
(void) args;
(void) fi;
}
static void AbortHandler(struct mg_rpc_request_info *ri, void *cb_arg,
struct mg_rpc_frame_info *fi, struct mg_str args) {
LOG(LL_ERROR, ("Aborting as requested"));
abort();
(void) cb_arg;
(void) args;
(void) fi;
(void) ri;
}
bool shelly_rpc_service_init(HAPAccessoryServerRef *server,
HAPPlatformKeyValueStoreRef kvs,
HAPPlatformTCPStreamManagerRef tcpm) {
s_server = server;
s_kvs = kvs;
s_tcpm = tcpm;
if (server != nullptr) {
mg_rpc_add_handler(mgos_rpc_get_global(), "Shelly.GetInfo", "",
GetInfoHandler, nullptr);
mg_rpc_add_handler(mgos_rpc_get_global(), "Shelly.SetConfig",
"{id: %d, type: %d, config: %T}", SetConfigHandler,
nullptr);
mg_rpc_add_handler(mgos_rpc_get_global(), "Shelly.SetState",
"{id: %d, type: %d, state: %T}", SetStateHandler,
nullptr);
mg_rpc_add_handler(mgos_rpc_get_global(), "Shelly.InjectInputEvent",
"{id: %d, event: %d}", InjectInputEventHandler, nullptr);
mg_rpc_add_handler(mgos_rpc_get_global(), "Shelly.Abort", "", AbortHandler,
nullptr);
} else {
mg_rpc_add_handler(mgos_rpc_get_global(), "Shelly.GetInfo", "",
GetInfoFailsafeHandler, nullptr);
}
mg_rpc_add_handler(mgos_rpc_get_global(), "Shelly.GetDebugInfo", "",
GetDebugInfoHandler, nullptr);
mg_rpc_add_handler(mgos_rpc_get_global(), "Shelly.WipeDevice", "",
WipeDeviceHandler, nullptr);
return true;
}
} // namespace shelly
| 33.731707 | 80 | 0.630594 | [
"model"
] |
7ddb59a83843e8f308754955783b0f44db59d729 | 3,832 | cpp | C++ | android-31/java/nio/charset/Charset.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/java/nio/charset/Charset.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-29/java/nio/charset/Charset.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../../../JObjectArray.hpp"
#include "../../../JArray.hpp"
#include "../../../JObject.hpp"
#include "../../../JString.hpp"
#include "../../lang/ThreadLocal.hpp"
#include "../ByteBuffer.hpp"
#include "../CharBuffer.hpp"
#include "./CharsetDecoder.hpp"
#include "./CharsetEncoder.hpp"
#include "./spi/CharsetProvider.hpp"
#include "../../util/Locale.hpp"
#include "./Charset.hpp"
namespace java::nio::charset
{
// Fields
// QJniObject forward
Charset::Charset(QJniObject obj) : JObject(obj) {}
// Constructors
// Methods
JObject Charset::availableCharsets()
{
return callStaticObjectMethod(
"java.nio.charset.Charset",
"availableCharsets",
"()Ljava/util/SortedMap;"
);
}
java::nio::charset::Charset Charset::defaultCharset()
{
return callStaticObjectMethod(
"java.nio.charset.Charset",
"defaultCharset",
"()Ljava/nio/charset/Charset;"
);
}
java::nio::charset::Charset Charset::forName(JString arg0)
{
return callStaticObjectMethod(
"java.nio.charset.Charset",
"forName",
"(Ljava/lang/String;)Ljava/nio/charset/Charset;",
arg0.object<jstring>()
);
}
jboolean Charset::isSupported(JString arg0)
{
return callStaticMethod<jboolean>(
"java.nio.charset.Charset",
"isSupported",
"(Ljava/lang/String;)Z",
arg0.object<jstring>()
);
}
JObject Charset::aliases() const
{
return callObjectMethod(
"aliases",
"()Ljava/util/Set;"
);
}
jboolean Charset::canEncode() const
{
return callMethod<jboolean>(
"canEncode",
"()Z"
);
}
jint Charset::compareTo(JObject arg0) const
{
return callMethod<jint>(
"compareTo",
"(Ljava/lang/Object;)I",
arg0.object<jobject>()
);
}
jint Charset::compareTo(java::nio::charset::Charset arg0) const
{
return callMethod<jint>(
"compareTo",
"(Ljava/nio/charset/Charset;)I",
arg0.object()
);
}
jboolean Charset::contains(java::nio::charset::Charset arg0) const
{
return callMethod<jboolean>(
"contains",
"(Ljava/nio/charset/Charset;)Z",
arg0.object()
);
}
java::nio::CharBuffer Charset::decode(java::nio::ByteBuffer arg0) const
{
return callObjectMethod(
"decode",
"(Ljava/nio/ByteBuffer;)Ljava/nio/CharBuffer;",
arg0.object()
);
}
JString Charset::displayName() const
{
return callObjectMethod(
"displayName",
"()Ljava/lang/String;"
);
}
JString Charset::displayName(java::util::Locale arg0) const
{
return callObjectMethod(
"displayName",
"(Ljava/util/Locale;)Ljava/lang/String;",
arg0.object()
);
}
java::nio::ByteBuffer Charset::encode(JString arg0) const
{
return callObjectMethod(
"encode",
"(Ljava/lang/String;)Ljava/nio/ByteBuffer;",
arg0.object<jstring>()
);
}
java::nio::ByteBuffer Charset::encode(java::nio::CharBuffer arg0) const
{
return callObjectMethod(
"encode",
"(Ljava/nio/CharBuffer;)Ljava/nio/ByteBuffer;",
arg0.object()
);
}
jboolean Charset::equals(JObject arg0) const
{
return callMethod<jboolean>(
"equals",
"(Ljava/lang/Object;)Z",
arg0.object<jobject>()
);
}
jint Charset::hashCode() const
{
return callMethod<jint>(
"hashCode",
"()I"
);
}
jboolean Charset::isRegistered() const
{
return callMethod<jboolean>(
"isRegistered",
"()Z"
);
}
JString Charset::name() const
{
return callObjectMethod(
"name",
"()Ljava/lang/String;"
);
}
java::nio::charset::CharsetDecoder Charset::newDecoder() const
{
return callObjectMethod(
"newDecoder",
"()Ljava/nio/charset/CharsetDecoder;"
);
}
java::nio::charset::CharsetEncoder Charset::newEncoder() const
{
return callObjectMethod(
"newEncoder",
"()Ljava/nio/charset/CharsetEncoder;"
);
}
JString Charset::toString() const
{
return callObjectMethod(
"toString",
"()Ljava/lang/String;"
);
}
} // namespace java::nio::charset
| 20.491979 | 72 | 0.659186 | [
"object"
] |
7de83af4558b2159c2a60f6c9792361ed51aecb1 | 1,392 | hpp | C++ | src/KawaiiEngine/include/Engine.hpp | Mathieu-Lala/Cute_Solar_System_-3 | 0bfe496991344709481995af348da2be37a19cac | [
"MIT"
] | 4 | 2021-06-03T11:20:09.000Z | 2022-02-11T06:52:54.000Z | src/KawaiiEngine/include/Engine.hpp | Mathieu-Lala/Cute_Solar_System_-3 | 0bfe496991344709481995af348da2be37a19cac | [
"MIT"
] | 35 | 2021-05-29T09:25:57.000Z | 2021-06-28T04:49:22.000Z | src/KawaiiEngine/include/Engine.hpp | Mathieu-Lala/Kawaii_Engine | 0bfe496991344709481995af348da2be37a19cac | [
"MIT"
] | null | null | null | #pragma once
#include <memory>
#include <thread>
#include <spdlog/spdlog.h>
#include <glm/vec4.hpp>
#include <entt/entt.hpp>
#include "helpers/overloaded.hpp"
#include "graphics/Window.hpp"
#include "EventProvider.hpp"
#include "Event.hpp"
#include "graphics/Shader.hpp"
#include "component.hpp"
#include "Context.hpp"
#include "resources/ResourceLoader.hpp"
#include "widgets/ComponentInspector.hpp"
#include "widgets/EntityHierarchy.hpp"
#include "widgets/EventMonitor.hpp"
#include "widgets/Recorder.hpp"
#include "widgets/Console.hpp"
#include "System.hpp"
using namespace std::chrono_literals;
namespace kawe {
class Engine {
public:
Engine();
~Engine();
bool render_internal_gui = true;
auto start(const std::function<void(entt::registry &)> on_create) -> void;
private:
// widgets
Console console;
ComponentInspector component_inspector;
EntityHierarchy entity_hierarchy;
std::unique_ptr<EventMonitor> event_monitor;
std::unique_ptr<Recorder> recorder;
std::unique_ptr<EventProvider> events;
// todo : should be an entity
std::unique_ptr<Window> window;
ResourceLoader loader;
entt::dispatcher dispatcher;
entt::registry world;
std::unique_ptr<Context> ctx;
std::unique_ptr<System> system;
auto on_imgui(const kawe::action::Render<kawe::Render::Layout::UI>) -> void;
};
} // namespace kawe
| 21.090909 | 80 | 0.722701 | [
"render"
] |
8fbde99a1d6c48197406845514d0568123e57bb2 | 6,652 | hpp | C++ | include/mp/tools/strided_array_view.hpp | mbeckem/mp | 872325079269143386f71195ec14019eb7ff59a2 | [
"MIT"
] | null | null | null | include/mp/tools/strided_array_view.hpp | mbeckem/mp | 872325079269143386f71195ec14019eb7ff59a2 | [
"MIT"
] | null | null | null | include/mp/tools/strided_array_view.hpp | mbeckem/mp | 872325079269143386f71195ec14019eb7ff59a2 | [
"MIT"
] | null | null | null | #ifndef MP_TOOLS_STRIDED_ARRAY_VIEW_HPP
#define MP_TOOLS_STRIDED_ARRAY_VIEW_HPP
#include <boost/iterator/iterator_facade.hpp>
#include "../defs.hpp"
#include "array_view.hpp"
namespace mp {
/*
* A template class similar to "array_view" but with a non-zero
* gap (the "stride") between each of its elements.
*
* For example, given the following vector
*
* vector<int> v{1, 2, 3, 4, 5, 6};
*
* and a strided_array_view declared like this
*
* strided_array_view<int> i(v.begin(), v.end(), 2);
*
* the contents of i will be {1, 3, 5}.
*/
template<typename T>
class strided_array_view
{
public:
struct iterator;
using value_type = T;
using const_iterator = iterator;
using reference = T&;
using const_reference = T&;
public:
// Constructors
strided_array_view();
strided_array_view(T *begin, T *end, size_t stride);
strided_array_view(T *begin, size_t size, size_t stride);
strided_array_view(array_view<T> v, size_t stride);
strided_array_view(const strided_array_view &) = default;
strided_array_view(strided_array_view &&) = default;
// Iterators
iterator begin() const;
iterator end() const;
// Access
bool empty() const;
size_t size() const;
reference operator [](size_t index) const;
reference at(size_t index) const;
reference front() const;
reference back() const;
// Slicing (index based)
strided_array_view slice(size_t start_index) const;
strided_array_view slice(size_t start_index, size_t length) const;
// Slicing (iterator based)
strided_array_view slice(iterator begin) const;
strided_array_view slice(iterator begin, iterator end) const;
strided_array_view& operator =(const strided_array_view &) = default;
strided_array_view& operator =(strided_array_view &&) = default;
// Array views are convertible to their const version.
operator strided_array_view<const T>() const;
private:
T *m_begin = nullptr;
size_t m_size = 0;
size_t m_stride = 0;
};
template<typename T>
struct strided_array_view<T>::iterator
: boost::iterator_facade<iterator, T, std::random_access_iterator_tag>
{
public:
iterator(): m_item(nullptr), m_stride(1) {}
iterator(T *item, size_t stride)
: m_item(item)
, m_stride(stride)
{
assert(stride != 0);
}
private:
using base = boost::iterator_facade<iterator, T, boost::random_access_traversal_tag>;
friend class boost::iterator_core_access;
T& dereference() const
{
return *m_item;
}
bool equal(const iterator &other) const
{
assert(m_stride == other.m_stride);
return m_item == other.m_item;
}
void increment()
{
m_item += m_stride;
}
void decrement()
{
m_item -= m_stride;
}
void advance(ptrdiff_t n)
{
m_item += n * static_cast<ptrdiff_t>(m_stride);
}
ptrdiff_t distance_to(const iterator &other) const
{
return (other.m_item - m_item) / static_cast<ptrdiff_t>(m_stride);
}
private:
T *m_item;
size_t m_stride;
};
// Constructors
template<typename T>
strided_array_view<T>::strided_array_view()
: m_begin(nullptr), m_size(0), m_stride(1)
{}
template<typename T>
strided_array_view<T>::strided_array_view(T *begin, T *end, size_t stride)
: m_begin(begin)
, m_size((end - begin) / stride)
, m_stride(stride)
{
assert(end >= begin && "End >= begin");
assert(stride != 0 && "Stride must never be 0");
}
template<typename T>
strided_array_view<T>::strided_array_view(T *begin, size_t size, size_t stride)
: m_begin(begin)
, m_size(size)
, m_stride(stride)
{
assert(stride != 0 && "Stride must never be 0");
}
template<typename T>
strided_array_view<T>::strided_array_view(array_view<T> v, size_t stride)
: m_begin(v.begin())
, m_size(v.size() / stride)
, m_stride(stride)
{
assert(stride != 0 && "Stride must never be 0");
}
// Iterators
template<typename T>
typename strided_array_view<T>::iterator strided_array_view<T>::begin() const
{
return iterator(m_begin, m_stride);
}
template<typename T>
typename strided_array_view<T>::iterator strided_array_view<T>::end() const
{
return iterator(m_begin + (m_size * m_stride), m_stride);
}
// Access
template<typename T>
bool strided_array_view<T>::empty() const
{
return m_size == 0;
}
template<typename T>
size_t strided_array_view<T>::size() const
{
return m_size;
}
template<typename T>
typename strided_array_view<T>::reference strided_array_view<T>::operator [](size_t index) const
{
assert(index < m_size && "Index in range");
return *(m_begin + (index * m_stride));
}
template<typename T>
typename strided_array_view<T>::reference strided_array_view<T>::at(size_t index) const
{
if (index >= m_size) {
throw std::out_of_range("strided_array_view::at()");
}
return *(m_begin + (index * m_stride));
}
template<typename T>
typename strided_array_view<T>::reference strided_array_view<T>::front() const
{
assert(!empty() && "Range has front");
return *m_begin;
}
template<typename T>
typename strided_array_view<T>::reference strided_array_view<T>::back() const
{
assert(!empty() && "Range has back");
return *(m_begin + ((m_size - 1) * m_stride));
}
// Slicing (index based)
template<typename T>
strided_array_view<T> strided_array_view<T>::slice(size_t start_index) const
{
return slice(start_index, size() - start_index);
}
template<typename T>
strided_array_view<T> strided_array_view<T>::slice(size_t start_index, size_t length) const
{
assert(start_index <= size() && "Start index in range");
assert(start_index + length <= size() && "Length in range");
T* begin = m_begin + (start_index * m_stride);
return strided_array_view<T>(begin, length, m_stride);
}
// Slicing (iterator based)
template<typename T>
strided_array_view<T> strided_array_view<T>::slice(iterator begin) const
{
return slice(begin, end());
}
template<typename T>
strided_array_view<T> strided_array_view<T>::slice(iterator begin, iterator end) const
{
assert((begin >= this->begin() && begin <= this->end()) && "Begin in range");
assert((end >= this->begin() && end <= this->end() && end >= begin && "End in range"));
return strided_array_view<T>(begin.m_item, end.m_item, m_stride);
}
template<typename T>
strided_array_view<T>::operator strided_array_view<const T>() const
{
return strided_array_view<const T>(m_begin, m_size, m_stride);
}
} // namespace bew
#endif // MP_TOOLS_STRIDED_ARRAY_VIEW_HPP
| 25.292776 | 96 | 0.67739 | [
"vector"
] |
8fc1bb437971315d07705bbfb98db43e4da2a450 | 4,060 | cpp | C++ | Interpretator/src/Function.cpp | dimitarkyurtov/Interpretator | 61bbe21a6475dd81a5187a41c0bf7039eb80803d | [
"MIT"
] | null | null | null | Interpretator/src/Function.cpp | dimitarkyurtov/Interpretator | 61bbe21a6475dd81a5187a41c0bf7039eb80803d | [
"MIT"
] | null | null | null | Interpretator/src/Function.cpp | dimitarkyurtov/Interpretator | 61bbe21a6475dd81a5187a41c0bf7039eb80803d | [
"MIT"
] | null | null | null | #include "Function.h"
Function::Function(const std::string& expr, const std::vector<std::string>& varrs){
this->expr = expr;
paramsCount = varrs.size();
paramsPtr = Variables::getInstance();
for(auto x : varrs){
if(paramsPtr->isVariable(x) && !paramsPtr->isPresent(x)){
this->vars[x] = 0;
}
}
}
const std::string Function::isValid(const std::string&){
return expr;
}
bigint Function::call(const std::vector<bigint>& vals){
if(paramsCount == vals.size()){
unsigned i = 0;
for(auto x : vars){
vars[x.first] = vals[i];
i++;
}
return evaluate();
} else {
std::cerr << "Not enough arguments provided\n expected: " << paramsCount << "\n provided: " << vals.size() << std::endl;
return bigint("0");
}
}
bigint Function::evaluate(){
std::stack<char> ops;
std::stack<bigint> nums;
unsigned i;
bigint a;
bigint b;
unsigned size = expr.size();
for(i = 0; i < size; i ++){
if(expr[i] == '('){
ops.push(expr[i]);
}
else if(isNumber(expr[i])){
std::string val;
while(i < size && isNumber(expr[i])){
val += expr[i];
i++;
}
bigint val2(val);
nums.push(val2);
i--;
}
else if(paramsPtr->isCharacter(expr[i])){
std::string val;
while(i < size && paramsPtr->isCharacter(expr[i])){
val += expr[i];
i++;
}
if(paramsPtr->isPresent(val)){
nums.push(paramsPtr->params[val]);
} else if(vars.find(val) != vars.end()){
nums.push(vars[val]);
}
else{
std::cerr << "No variable called " << val << " defined yet" << std::endl;
return 0;
}
i--;
}
else if(Functions::getInstance()->isCapitalCharacter(expr[i])){
std::string val;
while(i < size && Functions::getInstance()->isCapitalCharacter(expr[i])){
val += expr[i];
i++;
}
i++;
std::vector<bigint> vars;
while(expr[i] != ']'){
if(isNumber(expr[i])){
std::string val;
while(i < size && isNumber(expr[i])){
val += expr[i];
i++;
}
bigint val2(val);
vars.push_back(val2);
i--;
}
i++;
}
i++;
if(Functions::getInstance()->isPresent(val)){
nums.push(Functions::getInstance()->at(val)->call(vars));
} else{
std::cerr << "No function called " << val << " defined yet" << std::endl;
return 0;
}
i--;
i++;
}
else if(expr[i] == ')'){
while(!ops.empty() && ops.top() != '('){
a = nums.top();
nums.pop();
b = nums.top();
nums.pop();
nums.push(applyOp(b, a, ops.top()));
ops.pop();
}
ops.pop();
}
else {
while(!ops.empty() && precedence(ops.top()) >= precedence(expr[i])){
a = nums.top();
nums.pop();
b = nums.top();
nums.pop();
nums.push(applyOp(b, a, ops.top()));
ops.pop();
}
ops.push(expr[i]);
}
}
while(!ops.empty() && precedence(ops.top()) >= precedence(expr[i])){
a = nums.top();
nums.pop();
b = nums.top();
nums.pop();
nums.push(applyOp(b, a, ops.top()));
ops.pop();
}
return nums.top();
}
| 24.907975 | 132 | 0.398522 | [
"vector"
] |
8fc4f9b0eb4c31dd68a850d54b6e98a72105b923 | 2,429 | cpp | C++ | src/animatedtransform.cpp | arpit15/dpt | 5a9eec75b506d2c1867e3d5cfc1746d7f01c4639 | [
"MIT"
] | 73 | 2020-05-07T04:23:33.000Z | 2022-01-21T05:57:18.000Z | src/animatedtransform.cpp | arpit15/Langevin-MCMC | e6c5f1b03e20f991c791000ba09a6e9c02f31a1a | [
"MIT"
] | 2 | 2020-05-15T15:21:36.000Z | 2021-06-23T18:48:05.000Z | src/animatedtransform.cpp | arpit15/Langevin-MCMC | e6c5f1b03e20f991c791000ba09a6e9c02f31a1a | [
"MIT"
] | 11 | 2020-05-13T12:18:16.000Z | 2022-01-10T23:30:55.000Z | #include "animatedtransform.h"
#include "transform.h"
int GetAnimatedTransformSerializedSize() {
return 1 + // isMoving
3 * 2 + // translate[2]
4 * 2; // rotate[2]
}
void Decompose(const Matrix4x4 &m, Vector3 *t, Quaternion *r) {
Matrix3x3 A = m.topLeftCorner<3, 3>();
Eigen::JacobiSVD<Matrix3x3> svd(A, Eigen::ComputeFullU | Eigen::ComputeFullV);
Matrix3x3 U = svd.matrixU();
Matrix3x3 V = svd.matrixV();
Matrix3x3 S = svd.singularValues().asDiagonal();
if (svd.singularValues().prod() < 0) {
S = -S;
U = -U;
}
Matrix3x3 Q = U * V.transpose();
Matrix3x3 P = V * S * V.transpose();
if (fabs(P(0, 0) - Float(1.0)) > Float(1e-5) || fabs(P(1, 1) - Float(1.0)) > Float(1e-5) ||
fabs(P(2, 2) - Float(1.0)) > Float(1e-5)) {
Error("Scaling in animation");
}
Matrix4x4 Q4 = Matrix4x4::Identity();
Q4.topLeftCorner<3, 3>() = Q;
*r = MakeQuaternion(Q4);
*t = Vector3(m(0, 3), m(1, 3), m(2, 3));
}
Matrix4x4 Interpolate(const AnimatedTransform &transform, const Float time) {
if (transform.isMoving == FFALSE) {
Vector3 translate = transform.translate[0];
Vector4 rotate = transform.rotate[0];
return Translate(translate) * ToMatrix4x4(rotate);
} else {
Vector3 trans =
(Float(1.0) - time) * transform.translate[0] + time * transform.translate[1];
Quaternion rot = Slerp(time, transform.rotate[0], transform.rotate[1]);
return Translate(trans) * ToMatrix4x4(rot);
}
}
ADMatrix4x4 Interpolate(const ADAnimatedTransform &transform, const ADFloat time) {
std::vector<CondExprCPtr> ret = CreateCondExprVec(16);
BeginIf(Eq(transform.isMoving, FFALSE), ret);
{
ADMatrix4x4 ret = Translate(transform.translate[0]) * ToMatrix4x4(transform.rotate[0]);
SetCondOutput(ToADFloatVec(ret));
}
BeginElse();
{
ADVector3 trans =
(Float(1.0) - time) * transform.translate[0] + time * transform.translate[1];
ADQuaternion rot = Slerp(time, transform.rotate[0], transform.rotate[1]);
ADMatrix4x4 ret = Translate(trans) * ToMatrix4x4(rot);
SetCondOutput(ToADFloatVec(ret));
}
EndIf();
return ToADMatrix4x4(ret);
}
ADMatrix4x4 ToMatrix4x4(const ADAnimatedTransform &transform) {
return Translate(transform.translate[0]) * ToMatrix4x4(transform.rotate[0]);
}
| 35.720588 | 95 | 0.622067 | [
"vector",
"transform"
] |
8feb9289ffdefd19db4a128bacd1bb6cf694b477 | 11,394 | hpp | C++ | databases.hpp | technicolor-research/quick-adc | aff7dfd371bfb2742e9cfdc6d9fd542d1cfb40a7 | [
"BSD-3-Clause-Clear"
] | 19 | 2017-09-19T15:11:44.000Z | 2022-03-08T17:27:17.000Z | databases.hpp | technicolor-research/quick-adc | aff7dfd371bfb2742e9cfdc6d9fd542d1cfb40a7 | [
"BSD-3-Clause-Clear"
] | 1 | 2021-02-10T16:20:28.000Z | 2021-02-10T20:20:06.000Z | databases.hpp | technicolor-research/quick-adc | aff7dfd371bfb2742e9cfdc6d9fd542d1cfb40a7 | [
"BSD-3-Clause-Clear"
] | null | null | null | //
// Copyright (c) 2017 – Technicolor R&D France
//
// The source code form of this open source project is subject to the terms of the
// Clear BSD license.
//
// You can redistribute it and/or modify it under the terms of the Clear BSD
// License (See LICENSE file).
//
#ifndef DATABASES_HPP_
#define DATABASES_HPP_
#include <cstdint>
#include <cassert>
#include <cstdlib>
#include <omp.h>
#include <cereal/types/vector.hpp>
#include <cereal/types/polymorphic.hpp>
#include "binheap.hpp"
#include "neighbors.hpp"
#include "distances.hpp"
#include "quantizers.hpp"
#include "vector_io.hpp"
const unsigned MIN_VECTORS_PER_THREAD = 10000;
inline int optimal_thread_count(unsigned vector_count) {
const int thread_count = static_cast<int>(std::min(
static_cast<unsigned>(omp_get_max_threads()),
vector_count / MIN_VECTORS_PER_THREAD));
return thread_count;
}
struct base_db {
std::unique_ptr<base_pq> pq;
base_db() {};
base_db(std::unique_ptr<base_pq>&& pq_) :
pq(std::move(pq_)) {
}
// Function to assign queries
virtual void assign_compute_residuals(const float* vector, int multiple_assign,
int* assignements, float* residuals) = 0;
virtual void assign_compute_residuals_mutiple(const float* vectors,
const int count, const int multiple_assign, int* assignements,
float* residuals) = 0;
virtual int partition_count() const = 0;
virtual void get_partition(int part_i, const std::uint8_t*& codes,
unsigned*& labels, unsigned& size) const = 0;
virtual void free_partition(int part_i) = 0;
virtual void add_vectors(float* vectors, unsigned count,
unsigned labels_offset, int thread_count = 1) = 0;
virtual void print(std::ostream& os) const = 0;
virtual ~base_db() {};
};
inline void compute_thread_task(unsigned count, unsigned& off, unsigned& cnt) {
const int thread_id = omp_get_thread_num();
const int thread_count = omp_get_num_threads();
const unsigned chunk_size = count / thread_count;
off = thread_id * chunk_size;
cnt = chunk_size;
if (thread_id == thread_count - 1) {
cnt = count - off;
}
}
struct flat_db: public base_db {
std::vector<std::uint8_t> codes;
unsigned codes_count;
flat_db() {};
flat_db(std::unique_ptr<base_pq>&& pq_) :
base_db(std::move(pq_)), codes_count(0) {
}
virtual void print(std::ostream& os) const {
os << "Flat DB" << std::endl;
os << *pq;
}
virtual void assign_compute_residuals(const float* vector, int multiple_assign,
int* assignements, float* residuals) {
const int dim = pq->dim;
for(int ass_i = 0; ass_i < multiple_assign; ++ass_i) {
assignements[ass_i] = 0;
std::copy(vector, vector + dim, residuals);
residuals += dim;
}
}
virtual void assign_compute_residuals_mutiple(const float* vectors,
const int count, const int multiple_assign, int* assignements,
float* residuals) {
const int dim = pq->dim;
for (int vec_i = 0; vec_i < count; ++vec_i) {
for (int ass_i = 0; ass_i < multiple_assign; ++ass_i) {
assignements[ass_i] = 0;
std::copy(vectors, vectors + dim, residuals);
residuals += dim;
}
vectors += dim;
assignements += multiple_assign;
}
}
virtual int partition_count() const {
return 1;
}
virtual void get_partition(int part_i, const std::uint8_t*& codes_,
unsigned*& labels, unsigned& codes_count_) const {
assert(part_i == 0);
codes_ = codes.data();
codes_count_ = codes_count;
labels = nullptr;
}
virtual void free_partition(int part_i) {
codes.resize(0);
codes.shrink_to_fit();
codes_count = 0;
}
virtual void add_vectors(float* vectors, unsigned count,
unsigned labels_offset, int thread_count = 1) {
const long code_size = pq->code_size();
// Resize buffer
if (labels_offset + count > codes_count) {
codes_count = labels_offset + count;
codes.resize(codes_count * code_size);
}
// Encode vectors
#pragma omp parallel num_threads(thread_count)
{
unsigned off;
unsigned cnt;
compute_thread_task(count, off, cnt);
long code_off = (labels_offset + off) * code_size;
pq->encode_multiple_vectors(vectors + off * pq->dim,
codes.data() + code_off, cnt);
}
}
template<typename Archive>
inline void save(Archive& ar) const {
ar(pq, codes_count, codes);
}
template<typename Archive>
inline void load(Archive& ar) {
ar(pq, codes_count, codes);
}
};
void substract_vectors(float *vectors, int dim, int count,
const float *base_vectors, int *assignements);
void substract_vectors_from_unique(const float* vector, int dim,
const float* base_vectors, int* assignements, int assign_count,
float* substracted);
struct index_db: public base_db {
int part_count;
std::unique_ptr<float[]> centroids;
std::unique_ptr<std::vector<std::uint8_t>[]> partitions;
std::unique_ptr<std::vector<unsigned>[]> labels;
index_db() {};
index_db(std::unique_ptr<base_pq>&& pq_, int partition_count_,
std::unique_ptr<float[]>&& centroids_) :
base_db(std::move(pq_)), part_count(partition_count_), centroids(
std::move(centroids_)) {
setup_partitions();
}
virtual void print(std::ostream& os) const {
os << "Indexed DB (partitions=" << part_count << ")" << std::endl;
os << *pq;
}
void setup_partitions() {
partitions.reset(new std::vector<std::uint8_t>[part_count]);
labels.reset(new std::vector<unsigned>[part_count]);
}
virtual void assign_compute_residuals(const float* vector, int multiple_assign,
int* assignements, float* residuals) {
// Assign
const int dim = pq->dim;
const int count = 1;
find_k_neighbors(count, part_count, dim,
multiple_assign, vector, centroids.get(), assignements);
// Compute residuals
substract_vectors_from_unique(vector, pq->dim, centroids.get(),
assignements, multiple_assign, residuals);
}
virtual void assign_compute_residuals_mutiple(const float* vectors,
const int count, const int multiple_assign, int* assignements,
float* residuals) {
const int dim = pq->dim;
// Assign
find_k_neighbors(count, part_count, dim,
multiple_assign, vectors, centroids.get(), assignements);
// Compute residuals
const int res_dim = multiple_assign * dim;
for(int vec_i = 0; vec_i < count; ++vec_i) {
substract_vectors_from_unique(vectors, dim, centroids.get(),
assignements, multiple_assign, residuals);
vectors += dim;
residuals += res_dim;
assignements += multiple_assign;
}
}
virtual int partition_count() const {
return part_count;
}
virtual void get_partition(int part_i, const std::uint8_t*& codes_,
unsigned*& labels_, unsigned& codes_count_) const {
assert(part_i < part_count);
codes_ = partitions[part_i].data();
labels_ = labels[part_i].data();
codes_count_ = labels[part_i].size();
}
virtual void free_partition(int part_i) {
partitions[part_i].resize(0);
partitions[part_i].shrink_to_fit();
labels[part_i].resize(0);
labels[part_i].shrink_to_fit();
}
void assign_single_compute_residuals(float* vectors, unsigned count,
int* assignements, int thread_count = 1) {
// Compute residuals
#pragma omp parallel num_threads(thread_count)
{
unsigned off;
unsigned cnt;
compute_thread_task(count, off, cnt);
// Assign
find_k_neighbors(cnt, part_count, pq->dim, 1, vectors + off * pq->dim,
centroids.get(), assignements + off);
substract_vectors(vectors + off * pq->dim, pq->dim, cnt,
centroids.get(), assignements + off);
}
}
virtual void add_vectors(float* vectors, unsigned count,
unsigned labels_offset, int thread_count = 1) {
// Assign and compute residuals
std::unique_ptr<int[]> assignements = std::make_unique<int[]>(count);
assign_single_compute_residuals(vectors, count, assignements.get(),
thread_count);
// Encode
const long code_size = pq->code_size();
std::unique_ptr<std::uint8_t[]> codes_buffer = std::make_unique<
std::uint8_t[]>(count * code_size);
#pragma omp parallel num_threads(thread_count)
{
unsigned off;
unsigned cnt;
compute_thread_task(count, off, cnt);
pq->encode_multiple_vectors(vectors + off * pq->dim,
codes_buffer.get() + off * code_size, cnt);
}
// Dispatch
for (unsigned vec_i = 0; vec_i < count; ++vec_i) {
const int part_i = assignements[vec_i];
const std::uint8_t* code = codes_buffer.get() + vec_i * code_size;
partitions[part_i].insert(partitions[part_i].end(), code,
code + code_size);
labels[part_i].push_back(vec_i + labels_offset);
}
}
template<typename Archive>
inline void save(Archive& ar) const {
ar(part_count, pq);
const int centroids_dim = part_count * pq->dim;
ar(
cereal::binary_data(centroids.get(),
centroids_dim * sizeof(*centroids.get())));
for (int part_i = 0; part_i < part_count; ++part_i) {
ar(partitions[part_i]);
}
for (int part_i = 0; part_i < part_count; ++part_i) {
ar(labels[part_i]);
}
}
template<typename Archive>
inline void load(Archive& ar) {
ar(part_count, pq);
const int centroids_dim = part_count * pq->dim;
centroids.reset(new float[centroids_dim]);
ar(
cereal::binary_data(centroids.get(),
centroids_dim * sizeof(*centroids.get())));
setup_partitions();
for (int part_i = 0; part_i < part_count; ++part_i) {
ar(partitions[part_i]);
}
for (int part_i = 0; part_i < part_count; ++part_i) {
ar(labels[part_i]);
}
}
};
#include <cereal/archives/binary.hpp>
CEREAL_REGISTER_TYPE(flat_db);
CEREAL_REGISTER_TYPE(index_db);
CEREAL_REGISTER_POLYMORPHIC_RELATION(base_db, flat_db);
CEREAL_REGISTER_POLYMORPHIC_RELATION(base_db, index_db);
std::ostream& operator<<(std::ostream& os, const base_db& db);
std::unique_ptr<float[]> learn_coarse_quantizer(
vectors_owner<float>& learn_vectors, int centroid_count);
void check_db_filename(const std::unique_ptr<flat_db>& db,
const char* db_filename, const char* db_ext);
#endif /* DATABASES_HPP_ */
| 32.835735 | 83 | 0.609531 | [
"vector"
] |
8fef95bfc1d05e7f6631254e322605cce4d320d3 | 142 | cpp | C++ | src/Shapes/Shape.cpp | Shunseii/cpp-arcade-app | e7bad1b8401d9886243f3a6af3bedf40d939e9c1 | [
"MIT"
] | null | null | null | src/Shapes/Shape.cpp | Shunseii/cpp-arcade-app | e7bad1b8401d9886243f3a6af3bedf40d939e9c1 | [
"MIT"
] | null | null | null | src/Shapes/Shape.cpp | Shunseii/cpp-arcade-app | e7bad1b8401d9886243f3a6af3bedf40d939e9c1 | [
"MIT"
] | null | null | null | #include "Shapes/Shape.h"
void Shape::MoveBy(const Vec2D& deltaOffset) {
for (Vec2D& point : mPoints) {
point = point + deltaOffset;
}
}
| 17.75 | 46 | 0.676056 | [
"shape"
] |
8ff38021c0ff786a278ed25164f3e66d71aae3c6 | 512 | cpp | C++ | leetcode/416.cpp | yyong119/ACM-OnlineJudge | 5871993b15231c6615bfa3e7c2b04f0f6a23e9dc | [
"MIT"
] | 22 | 2017-08-12T11:56:19.000Z | 2022-03-27T10:04:31.000Z | leetcode/416.cpp | yyong119/ACM-OnlineJudge | 5871993b15231c6615bfa3e7c2b04f0f6a23e9dc | [
"MIT"
] | 2 | 2017-12-17T02:52:59.000Z | 2018-02-09T02:10:43.000Z | leetcode/416.cpp | yyong119/ACM-OnlineJudge | 5871993b15231c6615bfa3e7c2b04f0f6a23e9dc | [
"MIT"
] | 4 | 2017-12-22T15:24:38.000Z | 2020-05-18T14:51:16.000Z | class Solution {
public:
bool canPartition(vector<int>& nums) {
int n = nums.size(), sum = accumulate(nums.begin(), nums.end(), 0);
int f[sum + 1]; memset(f, 0, sizeof(f));
int cur_max = nums[0];
f[cur_max] = 1;
for (int i = 1; i < n; ++i) {
cur_max += nums[i];
for (int j = cur_max; j >= nums[i]; --j)
if (f[j - nums[i]]) f[j] = 1;
}
if (sum % 2 == 0 && f[sum >> 1]) return true;
return false;
}
};
| 30.117647 | 75 | 0.441406 | [
"vector"
] |
8ff505e7806e23cb9463a4bfb36076f788e777f0 | 8,708 | cc | C++ | cppnetlib/net/timer_container.cc | tfzhang006/netlib | 1e3c2fb5f2cbb3a4786b4991a2fb3b0c973e5de5 | [
"MIT"
] | null | null | null | cppnetlib/net/timer_container.cc | tfzhang006/netlib | 1e3c2fb5f2cbb3a4786b4991a2fb3b0c973e5de5 | [
"MIT"
] | null | null | null | cppnetlib/net/timer_container.cc | tfzhang006/netlib | 1e3c2fb5f2cbb3a4786b4991a2fb3b0c973e5de5 | [
"MIT"
] | null | null | null | #include "cppnetlib/net/timer_container.h"
#include <sys/timerfd.h>
#include <unistd.h>
#include "cppnetlib/core/logger.h"
#include "cppnetlib/net/timer.h"
#include "cppnetlib/net/event_loop.h"
#include "cppnetlib/net/timer_id.h"
// int timerfd_create(int clockid, int flags);
// int timerfd_settime(int fd, int flags,
// const struct itimerspec *new_value,
// struct itimerspec *old_value);
// int timerfd_gettime(int fd, struct itimerspec *curr_value);
//
// These system calls create and operate on a timer that delivers timer
// expiration notifications via a file descriptor with the advantage that the
// file descriptor may be monitored by select(2), poll(2), and epoll(7).
namespace cppnetlib {
namespace net {
namespace detail {
struct timespec TimeIntervalFromNow(TimeAnchor when) {
int64_t msecs = when.time_micro() - TimeAnchor::Now().time_micro();
if (msecs < 100)
msecs = 100;
struct timespec ts;
ts.tv_sec = static_cast<time_t>(msecs / TimeAnchor::kMSecsPerSec);
ts.tv_nsec = static_cast<time_t>(1000 * (msecs % TimeAnchor::kMSecsPerSec));
return ts;
}
inline bool CmpTimer(const Timer* lhs, const Timer* rhs) {
return (lhs->expiration()).time_micro() < (rhs->expiration()).time_micro();
}
int CreateTimerFD() {
int timerfd = ::timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC);
if (timerfd < 0) {
LOG_SYSFATAL << "Failed in timerfd_create()";
}
return timerfd;
}
void ResetTimerFD(int timerfd, TimeAnchor expiration) {
struct itimerspec new_value;
struct itimerspec old_value;
memset(&new_value, 0, sizeof(new_value));
memset(&old_value, 0, sizeof(old_value));
new_value.it_value = TimeIntervalFromNow(expiration);
int ret = ::timerfd_settime(timerfd, 0, &new_value, &old_value);
if (ret) {
LOG_ERROR << "timerfd_settimer()";
}
}
void ReadTimerFD(int timerfd, TimeAnchor now) {
uint64_t howmany;
ssize_t n = ::read(timerfd, &howmany, sizeof(howmany));
LOG_TRACE << "TimerContainer::ReadTimerFD " << howmany << " at "
<< now.ToStr();
if (n != sizeof(howmany)) {
LOG_ERROR << "TimerContainer::ReadTimerFD() reads " << n
<< " bytes instead of 8";
}
}
inline size_t HeapNodeLeftChild(size_t pos) { return pos + pos + 1; }
inline size_t HeapNodeRightChild(size_t pos) { return pos + pos + 2; }
inline size_t HeapNodeParent(size_t pos) { return pos == 0 ? 0 : ((pos-1)/2); }
const int kInvalidHeapPosition = -1;
const int kTopHeapPosition = 0;
} // namespace detail
TimerContainer::TimerContainer(EventLoop* loop)
: loop_(loop), timer_list_(), timer_num_(0),
timerfd_(detail::CreateTimerFD()),
timerfd_channel_(loop, timerfd_),
calling_expired_timers_(false) {
timerfd_channel_.set_read_callback(
std::bind(&TimerContainer::HandlerRead, this));
timerfd_channel_.EnableReading();
}
TimerContainer::~TimerContainer() {
timerfd_channel_.DisableAll();
timerfd_channel_.Unsubscribe();
::close(timerfd_);
for (Timer* timer : timer_list_) {
delete timer;
}
}
// public
TimerID TimerContainer::AddTimer(TimerCallback cb, TimeAnchor expiration,
double interval) {
Timer* timer = new Timer(std::move(cb), expiration, interval);
loop_->RunInLoop(std::bind(&TimerContainer::AddTimerInLoop, this, timer));
return TimerID(timer, timer->seq_id());
}
void TimerContainer::Cancel(TimerID timerid) {
loop_->RunInLoop(std::bind(&TimerContainer::CancelInLoop, this, timerid));
}
// private
// Add Timer to heap.
// Reset the expiration as earliest timer
void TimerContainer::AddTimerInLoop(Timer* timer) {
loop_->AssertInLoopThread();
TimeAnchor old_earliest;
if (!IsHeapEmpty()) {
old_earliest = HeapTop()->expiration();
}
HeapAdd(timer);
if (timer_num_ == 1 || HeapTop()->expiration() < old_earliest) {
detail::ResetTimerFD(timerfd_, timer->expiration());
}
}
void TimerContainer::CancelInLoop(TimerID timerid) {
loop_->AssertInLoopThread();
Timer* cancel_timer = timerid.timer_;
if (cancel_timer->InHeap() &&
static_cast<size_t>(cancel_timer->timer_pos()) < timer_num_) {
HeapDel(cancel_timer);
delete cancel_timer;
}
}
// Execute callback of expired timers.
// Reset the expiration as earliest timer
void TimerContainer::HandlerRead() {
loop_->AssertInLoopThread();
TimeAnchor now(TimeAnchor::Now());
detail::ReadTimerFD(timerfd_, now);
TimerList expired = GetExpiredTimers(now);
calling_expired_timers_ = true;
for (const Timer* expired_timer : expired) {
expired_timer->Run();
}
calling_expired_timers_ = false;
Reset(expired);
}
std::vector<Timer*> TimerContainer::GetExpiredTimers(TimeAnchor now) {
assert(timer_list_.size() == timer_num_);
TimerList expired;
while (timer_num_ > 0 && HeapTop()->expiration() <= now) {
expired.push_back(HeapTop());
HeapPop();
}
assert(timer_list_.size() == timer_num_);
return expired;
}
void TimerContainer::Reset(const TimerList& expired) {
for (Timer* expired_timer : expired) {
delete expired_timer;
}
if (timer_num_ > 0) {
TimeAnchor next_expire = HeapTop()->expiration();
detail::ResetTimerFD(timerfd_, next_expire);
}
}
// All Timers are managed by a minimum heap (stored in a vector/array).
// The following are interfaces for Minimum Heap.
Timer* TimerContainer::HeapTop() { return timer_list_.front(); }
bool TimerContainer::IsHeapEmpty() {
assert(timer_num_ == timer_list_.size());
return timer_num_ == 0;
}
void TimerContainer::HeapAdd(Timer* timer) {
if (!timer->InHeap()) {
timer_list_.push_back(timer);
timer->set_timer_pos(timer_num_++);
}
assert(timer->timer_pos() == static_cast<int>(timer_num_ - 1));
HeapSiftUp(static_cast<size_t>(timer->timer_pos()));
}
void TimerContainer::HeapDel(Timer* timer) {
assert(timer_num_ > 0);
assert(timer->InHeap() &&
static_cast<size_t>(timer->timer_pos()) < timer_num_);
assert(timer_num_ == timer_list_.size());
size_t del_pos = static_cast<size_t>(timer->timer_pos());
if(--timer_num_ > 0) {
{
Timer* tmp = timer_list_[timer_num_];
timer_list_[timer_num_] = timer_list_[del_pos];
timer_list_[del_pos] = tmp;
}
timer_list_[del_pos]->set_timer_pos(del_pos);
HeapSiftDown(del_pos);
HeapSiftUp(del_pos);
}
timer_list_.back()->set_timer_pos(detail::kInvalidHeapPosition);
timer_list_.pop_back();
}
void TimerContainer::HeapPush(Timer* timer) {
HeapAdd(timer);
}
void TimerContainer::HeapPop() {
assert(timer_num_ > 0);
assert(timer_num_ == timer_list_.size());
assert(0 == HeapTop()->timer_pos());
if (--timer_num_ > 0) {
{
Timer* tmp = timer_list_[timer_num_];
timer_list_[timer_num_] = timer_list_[0];
timer_list_[0] = tmp;
}
timer_list_[0]->set_timer_pos(detail::kTopHeapPosition);
timer_list_[timer_num_]->set_timer_pos(detail::kInvalidHeapPosition);
HeapSiftDown(0);
} else {
HeapTop()->set_timer_pos(detail::kInvalidHeapPosition);
}
timer_list_.pop_back();
}
// Adjust the position of one node to keep heap order.
void TimerContainer::HeapSiftUp(size_t heap_pos) {
if (heap_pos == 0) return ;
size_t child_pos = heap_pos;
size_t parent_pos = detail::HeapNodeParent(heap_pos);
do {
if (detail::CmpTimer(timer_list_[child_pos], timer_list_[parent_pos])) {
{
Timer* tmp = timer_list_[child_pos];
timer_list_[child_pos] = timer_list_[parent_pos];
timer_list_[parent_pos] = tmp;
}
timer_list_[child_pos]->set_timer_pos(child_pos);
timer_list_[parent_pos]->set_timer_pos(parent_pos);
child_pos = parent_pos;
parent_pos = detail::HeapNodeParent(child_pos);
} else {
break;
}
} while (child_pos > 0);
}
void TimerContainer::HeapSiftDown(size_t heap_pos) {
size_t parent_pos = heap_pos;
size_t child_pos = detail::HeapNodeLeftChild(parent_pos);
if (child_pos >= timer_num_) return;
do {
if ((1+child_pos) < timer_num_ &&
(detail::CmpTimer(timer_list_[1+child_pos], timer_list_[child_pos]))) {
++child_pos;
}
if (detail::CmpTimer(timer_list_[child_pos], timer_list_[parent_pos])) {
{
Timer* tmp = timer_list_[child_pos];
timer_list_[child_pos] = timer_list_[parent_pos];
timer_list_[parent_pos] = tmp;
}
timer_list_[child_pos]->set_timer_pos(child_pos);
timer_list_[parent_pos]->set_timer_pos(parent_pos);
parent_pos = child_pos;
child_pos = detail::HeapNodeLeftChild(parent_pos);
} else {
return;
}
} while (child_pos < timer_num_);
}
} // namespace net
} // namespace cppnetlib
| 28.090323 | 80 | 0.687529 | [
"vector"
] |
8ff643ae4a9a85c7daae66023eb9dd1f0805f138 | 3,672 | cpp | C++ | src/CwshWord.cpp | colinw7/Cwsh | f39e93ca48e92b14a55c1dce8c85b37843cff81e | [
"MIT"
] | 1 | 2021-12-23T02:22:56.000Z | 2021-12-23T02:22:56.000Z | src/CwshWord.cpp | colinw7/Cwsh | f39e93ca48e92b14a55c1dce8c85b37843cff81e | [
"MIT"
] | null | null | null | src/CwshWord.cpp | colinw7/Cwsh | f39e93ca48e92b14a55c1dce8c85b37843cff81e | [
"MIT"
] | null | null | null | #include <CwshI.h>
void
CwshWord::
toWords(const std::string &line, CwshWordArray &words)
{
std::vector<std::string> words1;
CwshString::addWords(line, words1);
int num_words1 = words1.size();
for (int i = 0; i < num_words1; i++) {
const std::string &word = words1[i];
words.push_back(CwshWord(word));
}
}
std::string
CwshWord::
toString(const CwshWordArray &words)
{
std::string str;
int num_words = words.size();
for (int i = 0; i < num_words; i++) {
if (i > 0)
str += " ";
str += words[i].getWord();
}
return str;
}
std::string
CwshWord::
toString(const CwshSubWordArray &sub_words)
{
std::string str;
int num_sub_words = sub_words.size();
for (int i = 0; i < num_sub_words; i++)
str += sub_words[i].getString();
return str;
}
void
CwshWord::
printWords(const CwshWordArray &words)
{
int num_words = words.size();
for (int i = 0; i < num_words; i++) {
if (i > 0)
std::cerr << " ";
std::cerr << "'" << words[i] << "'";
}
std::cerr << std::endl;
}
void
CwshWord::
printWord(const CwshWord &word)
{
std::cerr << word << std::endl;
}
CwshWord::
CwshWord(const std::string &word) :
word_(word)
{
}
const CwshSubWordArray &
CwshWord::
getSubWords() const
{
if (! sub_words_created_) {
CwshWord *th = const_cast<CwshWord *>(this);
th->createSubWords();
}
return sub_words_;
}
void
CwshWord::
createSubWords()
{
uint len = word_.size();
std::string sub_word;
uint i = 0;
while (i < len) {
uint i1 = i;
while (i < len && word_[i] != '\"' && word_[i] != '\'' && word_[i] != '`')
i++;
if (i > i1) {
sub_word = word_.substr(i1, i - i1);
sub_words_.push_back(CwshSubWord(sub_word));
}
if (i >= len)
break;
if (word_[i] == '\"') {
uint i2 = i + 1;
if (! CStrUtil::skipDoubleQuotedString(word_, &i))
CWSH_THROW("Unmatched \".");
sub_word = word_.substr(i2, i - i2 - 1);
sub_words_.push_back(
CwshSubWord(sub_word, CwshSubWordType::DOUBLE_QUOTED));
}
else if (word_[i] == '\'') {
uint i2 = i + 1;
if (! CStrUtil::skipSingleQuotedString(word_, &i))
CWSH_THROW("Unmatched \'.");
sub_word = word_.substr(i2, i - i2 - 1);
sub_words_.push_back(
CwshSubWord(sub_word, CwshSubWordType::SINGLE_QUOTED));
}
else if (word_[i] == '`') {
uint i2 = i + 1;
if (! CStrUtil::skipBackQuotedString(word_, &i))
CWSH_THROW("Unmatched `.");
sub_word = word_.substr(i2, i - i2 - 1);
sub_words_.push_back(
CwshSubWord(sub_word, CwshSubWordType::BACK_QUOTED));
}
}
sub_words_created_ = true;
}
void
CwshWord::
removeQuotes()
{
const CwshSubWordArray &sub_words = getSubWords();
std::string str;
int num_sub_words = sub_words.size();
for (int i = 0; i < num_sub_words; i++)
str += sub_words[i].getWord();
word_ = str;
sub_words_.clear();
sub_words_created_ = false;
}
std::ostream &
operator<<(std::ostream &os, const CwshWord &word)
{
os << ">>" << word.word_ << "<<";
return os;
}
CwshSubWord::
CwshSubWord(const std::string &word, CwshSubWordType type) :
word_(word), type_(type)
{
}
std::string
CwshSubWord::
getString() const
{
if (type_ == CwshSubWordType::SINGLE_QUOTED)
return "'" + word_ + "'";
else if (type_ == CwshSubWordType::DOUBLE_QUOTED)
return "\"" + word_ + "\"";
else if (type_ == CwshSubWordType::BACK_QUOTED)
return "`" + word_ + "`";
else
return word_;
}
std::ostream &
operator<<(std::ostream &os, const CwshSubWord &sub_word)
{
os << ">>" << sub_word.getString() << "<<";
return os;
}
| 17.320755 | 78 | 0.589325 | [
"vector"
] |
8ffd5762dbb59fb51cde4920a365b854da6b65fa | 3,122 | cpp | C++ | camera/opencv-util.cpp | qwantix/qxeye | 7d777768947f74cc3b35535254ae498380b56dca | [
"Apache-2.0"
] | 2 | 2017-12-17T16:07:18.000Z | 2018-01-19T08:11:44.000Z | camera/opencv-util.cpp | qwantix/qxeye | 7d777768947f74cc3b35535254ae498380b56dca | [
"Apache-2.0"
] | null | null | null | camera/opencv-util.cpp | qwantix/qxeye | 7d777768947f74cc3b35535254ae498380b56dca | [
"Apache-2.0"
] | null | null | null |
#include <iostream>
#include <opencv2/opencv.hpp>
#include "opencv-util.hpp"
#include "util.hpp"
using namespace std;
using namespace cv;
Rect adjustRectToSize(Rect rect, Size size)
{
Rect out(rect);
if (size.width > rect.width)
{
out.x -= (int)((size.width - rect.width) / 2);
out.width = size.width;
}
if (size.height > rect.height)
{
out.y -= (int)((size.height - rect.height) / 2);
out.height = size.height;
}
return out;
}
std::vector<cv::Rect> squarizeRois(Size imgSize, std::vector<cv::Rect> rois, int minSize, int padding)
{
int roisLen = rois.size();
std::vector<cv::Rect> out;
for (int i = 0; i < roisLen; i++)
{
Rect originRoi = rois.at(i);
Rect roi(originRoi);
// Convert roi as square
// get max size
int maxSize = max(roi.width, roi.height);
maxSize = max(maxSize - padding, minSize - padding);
// Add margin
maxSize += padding;
roi = adjustRectToSize(roi, Size(maxSize, maxSize));
// OK, now adjust square into imgSize bounds
if (roi.height > imgSize.height)
{
roi.height = imgSize.height;
roi.width = imgSize.width;
}
else if (roi.width > imgSize.width)
{
roi.height = imgSize.height;
roi.width = imgSize.width;
}
roi.x = max(0, roi.x);
roi.y = max(0, roi.y);
if ((roi.x + roi.width) > imgSize.width)
{
roi.width = imgSize.width - roi.x;
}
if ((roi.y + roi.height) > imgSize.height)
{
roi.height = imgSize.height - roi.y;
}
if (false && roi.height != roi.width)
{
Rect roi2;
// create sliding window when rect require 2 squares
if (roi.height > roi.width)
{ // portrait
roi2.height = roi2.width = roi.width;
roi2.x = roi.x;
roi2.y = roi.height - roi.width;
roi.height = roi.width;
}
else
{ // landscape
roi2.width = roi2.height = roi.height;
roi2.y = roi.y;
roi2.x = roi.width - roi.height;
roi.width = roi.height;
}
out.push_back(roi2);
}
out.push_back(roi);
}
return out;
}
bool isNear(Rect a, Rect b, int distance)
{
return b.x > a.x ? b.x - a.x <= a.width + distance : a.x - b.x <= b.width + distance && b.y > a.y ? b.y - a.y <= a.height + distance : a.y - b.y <= b.height + distance;
}
std::vector<cv::Rect> mergeRois(std::vector<cv::Rect> rois, int distance)
{
std::vector<cv::Rect> out = rois;
std::vector<cv::Rect> subset;
bool merged = false;
do
{
Rect a, b;
subset = out;
out.clear();
int len = subset.size();
merged = false;
for (int i = 0; i < len && !merged; i++)
{
a = Rect(subset.at(i));
for (int j = i + 1; j < len; j++)
{
b = subset.at(j);
if (isNear(a, b, distance))
{
a.width = max(a.x + a.width, b.x + b.width) - min(a.x, b.x);
a.height = max(a.y + a.height, b.y + b.height) - min(a.y, b.y);
a.x = min(a.x, b.x);
a.y = min(a.y, b.y);
merged = true;
}
}
out.push_back(a);
}
} while (merged);
return out;
}
| 24.20155 | 170 | 0.546124 | [
"vector"
] |
890776604dadf969c37aba2441e63567e4028dee | 8,940 | cpp | C++ | Samples/Audio/SimpleWASAPICapture/SimpleWASAPICapture.cpp | acidburn0zzz/Xbox-GDK-Samples | 0a998ca467f923aa04bd124a5e5ca40fe16c386c | [
"MIT"
] | 1 | 2021-12-30T09:49:18.000Z | 2021-12-30T09:49:18.000Z | Samples/Audio/SimpleWASAPICapture/SimpleWASAPICapture.cpp | acidburn0zzz/Xbox-GDK-Samples | 0a998ca467f923aa04bd124a5e5ca40fe16c386c | [
"MIT"
] | null | null | null | Samples/Audio/SimpleWASAPICapture/SimpleWASAPICapture.cpp | acidburn0zzz/Xbox-GDK-Samples | 0a998ca467f923aa04bd124a5e5ca40fe16c386c | [
"MIT"
] | null | null | null | //--------------------------------------------------------------------------------------
// SimpleWASAPICapture.cpp
//
// Advanced Technology Group (ATG)
// Copyright (C) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
#include "pch.h"
#include "SimpleWASAPICapture.h"
#include "ATGColors.h"
#include "ControllerFont.h"
extern void ExitSample();
using namespace DirectX;
using namespace DirectX::SimpleMath;
using Microsoft::WRL::ComPtr;
using namespace Windows::Foundation;
namespace
{
bool g_bListDirty = true;
int g_CaptureID = 0;
void NotifyListUpdate(int iCaptureID)
{
g_CaptureID = iCaptureID;
g_bListDirty = true;
}
}
Sample::Sample() noexcept(false) :
m_bHasCaptured(false),
m_keyDown(false)
{
// Renders only 2D, so no need for a depth buffer.
m_deviceResources = std::make_unique<DX::DeviceResources>(DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_UNKNOWN);
}
// Initialize the Direct3D resources required to run.
void Sample::Initialize(HWND window)
{
m_gamePad = std::make_unique<GamePad>();
m_deviceResources->SetWindow(window);
m_deviceResources->CreateDeviceResources();
CreateDeviceDependentResources();
m_deviceResources->CreateWindowSizeDependentResources();
CreateWindowSizeDependentResources();
m_wm = std::make_unique<WASAPIManager>();
m_wm->SetDeviceChangeCallback(&NotifyListUpdate);
}
#pragma region Frame Update
// Executes basic render loop.
void Sample::Tick()
{
m_timer.Tick([&]()
{
Update(m_timer);
});
Render();
}
// Updates the world.
void Sample::Update(DX::StepTimer const&)
{
auto pad = m_gamePad->GetState(0);
if (pad.IsConnected())
{
if (pad.IsViewPressed())
{
ExitSample();
}
}
if (!m_keyDown)
{
if (pad.IsAPressed() && m_bHasCaptured)
{
m_wm->PlayToggle();
m_keyDown = true;
}
else if (pad.IsBPressed())
{
m_wm->RecordToggle();
m_keyDown = true;
m_bHasCaptured = true;
}
else if (pad.IsDPadUpPressed())
{
m_keyDown = true;
g_CaptureID--;
if (g_CaptureID < 0)
{
g_CaptureID = (int)m_deviceList.size() - 1;
}
HRESULT hr = m_wm->SetCaptureDevice(UINT32(g_CaptureID));
if (FAILED(hr))
{
m_errorString = L"Error: " + std::to_wstring(hr);
}
else
{
m_errorString.clear();
}
}
else if (pad.IsDPadDownPressed())
{
m_keyDown = true;
g_CaptureID++;
if (g_CaptureID > int(m_deviceList.size() - 1))
{
g_CaptureID = 0;
}
HRESULT hr = m_wm->SetCaptureDevice(UINT32(g_CaptureID));
if (FAILED(hr))
{
m_errorString = L"Error: " + std::to_wstring(hr);
}
else
{
m_errorString.clear();
}
}
else if (pad.IsViewPressed())
{
ExitSample();
}
}
else if (!pad.IsAPressed() && !pad.IsBPressed() && !pad.IsDPadUpPressed() && !pad.IsDPadDownPressed())
{
m_keyDown = false;
}
}
#pragma endregion
#pragma region Frame Render
// Draws the scene.
void Sample::Render()
{
// Don't try to render anything before the first Update.
if (m_timer.GetFrameCount() == 0)
{
return;
}
// Prepare the command list to render a new frame.
m_deviceResources->Prepare();
Clear();
auto commandList = m_deviceResources->GetCommandList();
auto fullscreen = m_deviceResources->GetOutputSize();
auto safeRect = Viewport::ComputeTitleSafeArea(UINT(fullscreen.right - fullscreen.left), UINT(fullscreen.bottom - fullscreen.top));
XMFLOAT2 pos(float(safeRect.left), float(safeRect.top));
std::wstring tempString;
if (g_bListDirty)
{
m_wm->GetCaptureDevices(m_deviceList);
g_bListDirty = false;
}
auto heap = m_resourceDescriptors->Heap();
commandList->SetDescriptorHeaps(1, &heap);
m_spriteBatch->Begin(commandList);
float spacing = m_font->GetLineSpacing();
m_font->DrawString(m_spriteBatch.get(), L"Audio captured from the selected mic is played back to the default output", pos, ATG::Colors::OffWhite);
pos.y += spacing;
m_font->DrawString(m_spriteBatch.get(), L"Note that no sample conversion is done!", pos, ATG::Colors::OffWhite);
pos.y += spacing;
if (!m_errorString.empty())
{
m_font->DrawString(m_spriteBatch.get(), m_errorString.c_str(), pos, ATG::Colors::Orange);
}
pos.y += spacing;
if (m_deviceList.empty())
{
m_font->DrawString(m_spriteBatch.get(), L"No capture devices!", pos, ATG::Colors::Orange);
}
else
{
for (size_t i = 0; i < m_deviceList.size(); i++)
{
if (int(i) == g_CaptureID)
{
tempString = L"> " + std::wstring(m_deviceList.at(i));
}
else
{
tempString = m_deviceList.at(i);
}
m_font->DrawString(m_spriteBatch.get(), tempString.c_str(), pos, ATG::Colors::OffWhite);
pos.y += spacing;
}
}
pos.y += spacing;
if (m_bHasCaptured)
{
DX::DrawControllerString(m_spriteBatch.get(), m_font.get(), m_ctrlFont.get(), L"Press [A] Button to start / stop playback of last recording", pos);
pos.y += spacing;
}
DX::DrawControllerString(m_spriteBatch.get(), m_font.get(), m_ctrlFont.get(), L"Press [B] Button to start / stop recording", pos, ATG::Colors::OffWhite);
pos.y += spacing;
DX::DrawControllerString(m_spriteBatch.get(), m_font.get(), m_ctrlFont.get(), L"Press [DPad] Up/Down to change capture device", pos, ATG::Colors::OffWhite);
pos.y += spacing * 1.5f;
tempString = L"Capture: " + convertBoolToRunning(m_wm->m_recordingSound);
m_font->DrawString(m_spriteBatch.get(), tempString.c_str(), pos, ATG::Colors::OffWhite);
pos.y += spacing;
tempString = L"Playback: " + convertBoolToRunning(m_wm->m_playingSound);
m_font->DrawString(m_spriteBatch.get(), tempString.c_str(), pos, ATG::Colors::OffWhite);
pos.y += spacing;
m_spriteBatch->End();
// Show the new frame.
m_deviceResources->Present();
m_graphicsMemory->Commit(m_deviceResources->GetCommandQueue());
}
// Helper method to clear the back buffers.
void Sample::Clear()
{
auto commandList = m_deviceResources->GetCommandList();
// Clear the views.
auto rtvDescriptor = m_deviceResources->GetRenderTargetView();
commandList->OMSetRenderTargets(1, &rtvDescriptor, FALSE, nullptr);
commandList->ClearRenderTargetView(rtvDescriptor, ATG::Colors::Background, 0, nullptr);
// Set the viewport and scissor rect.
auto viewport = m_deviceResources->GetScreenViewport();
auto scissorRect = m_deviceResources->GetScissorRect();
commandList->RSSetViewports(1, &viewport);
commandList->RSSetScissorRects(1, &scissorRect);
}
#pragma endregion
#pragma region Message Handlers
// Message handlers
void Sample::OnSuspending()
{
m_wm->StopPlayback();
m_deviceResources->Suspend();
}
void Sample::OnResuming()
{
m_deviceResources->Resume();
m_timer.ResetElapsedTime();
}
#pragma endregion
#pragma region Direct3D Resources
// These are the resources that depend on the device.
void Sample::CreateDeviceDependentResources()
{
auto device = m_deviceResources->GetD3DDevice();
m_graphicsMemory = std::make_unique<GraphicsMemory>(device);
m_resourceDescriptors = std::make_unique<DescriptorHeap>(device, Descriptors::Count);
RenderTargetState rtState(m_deviceResources->GetBackBufferFormat(), m_deviceResources->GetDepthBufferFormat());
ResourceUploadBatch upload(device);
upload.Begin();
{
SpriteBatchPipelineStateDescription pd(
rtState,
&CommonStates::AlphaBlend);
m_spriteBatch = std::make_unique<SpriteBatch>(device, upload, pd);
}
m_font = std::make_unique<SpriteFont>(device, upload,
L"SegoeUI_18.spritefont",
m_resourceDescriptors->GetCpuHandle(Descriptors::TextFont),
m_resourceDescriptors->GetGpuHandle(Descriptors::TextFont));
m_ctrlFont = std::make_unique<SpriteFont>(device, upload,
L"XboxOneControllerLegendSmall.spritefont",
m_resourceDescriptors->GetCpuHandle(Descriptors::CtrlFont),
m_resourceDescriptors->GetGpuHandle(Descriptors::CtrlFont));
DX::ThrowIfFailed(CreateDDSTextureFromFile(device, upload, L"ATGSampleBackground.DDS", m_background.ReleaseAndGetAddressOf()));
auto finish = upload.End(m_deviceResources->GetCommandQueue());
finish.wait();
m_deviceResources->WaitForGpu();
CreateShaderResourceView(device, m_background.Get(), m_resourceDescriptors->GetCpuHandle(Descriptors::Background));
}
// Allocate all memory resources that change on a window SizeChanged event.
void Sample::CreateWindowSizeDependentResources()
{
auto vp = m_deviceResources->GetScreenViewport();
m_spriteBatch->SetViewport(vp);
}
#pragma endregion
| 27.173252 | 158 | 0.661409 | [
"render"
] |
89080b4b0d814f232f780ec8f4a63a31a40ae13b | 39,822 | hpp | C++ | Source/Lib/Public/PyHelpers.hpp | ankarako/SMPLTools | 52f9e809484217e4249910120532fa1facb796a3 | [
"MIT"
] | 1 | 2020-10-22T03:12:43.000Z | 2020-10-22T03:12:43.000Z | Source/Lib/Public/PyHelpers.hpp | ankarako/SMPLTools | 52f9e809484217e4249910120532fa1facb796a3 | [
"MIT"
] | null | null | null | Source/Lib/Public/PyHelpers.hpp | ankarako/SMPLTools | 52f9e809484217e4249910120532fa1facb796a3 | [
"MIT"
] | null | null | null | #ifndef __LIB_PUBLIC_PYHELPERS_HPP__
#define __LIB_PUBLIC_PYHELPERS_HPP__
#include <Vector.hpp>
#include <Python.h>
#include <vector>
#include <map>
#include <string>
#include <exception>
namespace util {
/// \class CPyInstance
/// \brief An Python interpreter instance
/// \see https://www.codeproject.com/Articles/820116/Embedding-Python-program-in-a-C-Cplusplus-code
/// "RAII" object for easy initialization/termination of the python interpreter
class CPyInstance
{
public:
/// \brief Default constructor
/// Initializes the Python Interpreter
CPyInstance();
/// \brief Destructor
/// Destroys the python interpreter
~CPyInstance();
}; /// !class CPyInstance
/// \class CPyObject
/// \brief A wrapper around PyObject for easer instantation and destruction
/// \see https://www.codeproject.com/Articles/820116/Embedding-Python-program-in-a-C-Cplusplus-code
class CPyObject
{
public:
/// \brief default constructor
/// Initializes PyObject pointer to null
CPyObject();
/// \brief Construct from existing PyObject
/// \param p The PyObject pointer to construct from
CPyObject(PyObject* p);
/// \brief Destructor
/// Sets PyObject pointer to null
~CPyObject();
/// \brief Get the PyObject pointer
/// \return The PyObject pointer
PyObject* GetObject();
/// \brief Set the PyObject pointer
/// \param p The pointer to set
/// \return The PyObject pointer
PyObject* SetObject(PyObject* p);
/// \brief add a reference to the PyObject's reference counter
/// \return The PyObject pointer
PyObject* AddRef();
/// \brief decrease the reference counter of the PyObject
/// Also sets the PyObject pointer to null
void Release();
/// \brief dereference operator
/// \return The PyObject pointer
PyObject* operator->();
/// \brief assignment operator
/// Assign a pointer to the PyObject
/// \return The PyObject pointer
PyObject* operator=(PyObject* p);
/// \brief Check if the PyObject pointer is not null
/// return true if the pointer is not null, false otherwise
operator bool();
private:
PyObject* m_Ptr;
}; /// !class CPyObject
///===================================
/// Utilities for loading Python lists
///===================================
/// \struct LoadPyList
/// \brief Utility for loading python lists
/// \tparam Dim The dimensionality of the list
/// \tparam DataType The type of the data the list holds
template <unsigned int Dim, typename DataType>
struct PyList
{
using ValueType = typename DataType;
using OutputType = std::vector<DataType>;
};
///==========================
/// Lists of Single Dimension
///==========================
/// \struct LoadPyList
/// \brief Specialization for lists of floats with one dimension
template <>
struct PyList<1, float>
{
using ValueType = float;
using OutputType = std::vector<ValueType>;
/// \brief Load a python list of single dimension
/// \param pyList The python object that represents the list
/// \param[out] output The output vectpr to copy the list into
static void Load(PyObject* pyList, std::vector<ValueType>& output)
{
if (PyList_Check(pyList))
{
output = std::vector<ValueType>(size_t(PyList_Size(pyList)));
for (unsigned int pos = 0; pos < output.size(); ++pos)
{
PyObject* value = PyList_GetItem(pyList, pos);
output[pos] = static_cast<ValueType>(PyFloat_AsDouble(value));
}
}
}
}; /// !struct LoadPyList
/// \struct LoadPyList
/// \brief Specialization for lists of doubles with one dimension
template <>
struct PyList<1, double>
{
using ValueType = double;
using OutputType = std::vector<ValueType>;
/// \brief Load a python list of single dimension
/// \param pyList The python object that represents the list
/// \param[out] output The output vectpr to copy the list into
static void Load(PyObject* pyList, std::vector<ValueType>& output)
{
if (PyList_Check(pyList))
{
output = std::vector<ValueType>(size_t(PyList_Size(pyList)));
for (unsigned int pos = 0; pos < output.size(); ++pos)
{
PyObject* value = PyList_GetItem(pyList, pos);
output[pos] = static_cast<ValueType>(PyFloat_AsDouble(value));
}
}
}
}; /// !struct LoadPyList
/// \struct LoadPyList
/// \brief Specialization for lists of longs with one dimension
template <>
struct PyList<1, long>
{
using ValueType = long;
using OutputType = std::vector<ValueType>;
/// \brief Load a python list of single dimension
/// \param pyList The python object that represents the list
/// \param[out] output The output vectpr to copy the list into
static void Load(PyObject* pyList, std::vector<ValueType>& output)
{
if (PyList_Check(pyList))
{
output = std::vector<ValueType>(size_t(PyList_Size(pyList)));
for (unsigned int pos = 0; pos < output.size(); ++pos)
{
PyObject* value = PyList_GetItem(pyList, pos);
output[pos] = static_cast<ValueType>(PyLong_AsLong(value));
}
}
}
}; /// !struct LoadPyList
/// \struct LoadPyList
/// \brief Specialization for lists of unsigned longs with one dimension
template <>
struct PyList<1, unsigned long>
{
using ValueType = unsigned long;
using OutputType = std::vector<ValueType>;
/// \brief Load a python list of single dimension
/// \param pyList The python object that represents the list
/// \param[out] output The output vectpr to copy the list into
static void Load(PyObject* pyList, std::vector<ValueType>& output)
{
if (PyList_Check(pyList))
{
output = std::vector<ValueType>(size_t(PyList_Size(pyList)));
for (unsigned int pos = 0; pos < output.size(); ++pos)
{
PyObject* value = PyList_GetItem(pyList, pos);
output[pos] = static_cast<ValueType>(PyLong_AsUnsignedLong(value));
}
}
}
}; /// !struct LoadPyList
/// \struct LoadPyList
/// \brief Specialization for lists of long longs with one dimension
template <>
struct PyList<1, long long>
{
using ValueType = long long;
using OutputType = std::vector<ValueType>;
/// \brief Load a python list of single dimension
/// \param pyList The python object that represents the list
/// \param[out] output The output vectpr to copy the list into
static void Load(PyObject* pyList, std::vector<ValueType>& output)
{
if (PyList_Check(pyList))
{
output = std::vector<ValueType>(size_t(PyList_Size(pyList)));
for (unsigned int pos = 0; pos < output.size(); ++pos)
{
PyObject* value = PyList_GetItem(pyList, pos);
output[pos] = static_cast<ValueType>(PyLong_AsLongLong(value));
}
}
}
}; /// !struct LoadPyList
/// \struct LoadPyList
/// \brief Specialization for lists of unsigned long longs with one dimension
template <>
struct PyList<1, unsigned long long>
{
using ValueType = unsigned long long;
using OutputType = std::vector<ValueType>;
/// \brief Load a python list of single dimension
/// \param pyList The python object that represents the list
/// \param[out] output The output vectpr to copy the list into
static void Load(PyObject* pyList, std::vector<ValueType>& output)
{
if (PyList_Check(pyList))
{
output = std::vector<ValueType>(size_t(PyList_Size(pyList)));
for (unsigned int pos = 0; pos < output.size(); ++pos)
{
PyObject* value = PyList_GetItem(pyList, pos);
output[pos] = static_cast<ValueType>(PyLong_AsUnsignedLongLong(value));
}
}
}
}; /// !struct LoadPyList
/// \struct LoadPyList
/// \brief Specialization for lists of ints with one dimension
template <>
struct PyList<1, int>
{
using ValueType = int;
using OutputType = std::vector<ValueType>;
/// \brief Load a python list of single dimension
/// \param pyList The python object that represents the list
/// \param[out] output The output vectpr to copy the list into
static void Load(PyObject* pyList, std::vector<ValueType>& output)
{
if (PyList_Check(pyList))
{
output = std::vector<ValueType>(size_t(PyList_Size(pyList)));
for (unsigned int pos = 0; pos < output.size(); ++pos)
{
PyObject* value = PyList_GetItem(pyList, pos);
output[pos] = static_cast<ValueType>(PyLong_AsLong(value));
}
}
}
}; /// !struct LoadPyList
/// \struct LoadPyList
/// \brief Specialization for lists of unsigned ints with one dimension
template <>
struct PyList<1, unsigned int>
{
using ValueType = unsigned int;
using OutputType = std::vector<ValueType>;
/// \brief Load a python list of single dimension
/// \param pyList The python object that represents the list
/// \param[out] output The output vectpr to copy the list into
static void Load(PyObject* pyList, std::vector<ValueType>& output)
{
if (PyList_Check(pyList))
{
output = std::vector<ValueType>(size_t(PyList_Size(pyList)));
for (unsigned int pos = 0; pos < output.size(); ++pos)
{
PyObject* value = PyList_GetItem(pyList, pos);
output[pos] = static_cast<ValueType>(PyLong_AsUnsignedLong(value));
}
}
}
}; /// !struct LoadPyList
/// \struct LoadPyList
/// \brief Specialization for lists of unsigned ints with one dimension
template <>
struct PyList<1, smpl::Vector3f>
{
using ValueType = smpl::Vector3f;
using OutputType = std::vector<ValueType>;
/// \brief Load a python list of single dimension
/// \param pyList The python object that represents the list
/// \param[out] output The output vectpr to copy the list into
static void Load(PyObject* pyList, std::vector<ValueType>& output)
{
if (PyList_Check(pyList))
{
output = std::vector<ValueType>(size_t(PyList_Size(pyList)));
for (unsigned int pos = 0; pos < output.size(); ++pos)
{
PyObject* value = PyList_GetItem(pyList, pos);
if (PyList_Check(value))
{
PyObject* x = PyList_GetItem(value, 0);
PyObject* y = PyList_GetItem(value, 1);
PyObject* z = PyList_GetItem(value, 2);
output[pos].x = static_cast<float>(PyFloat_AsDouble(x));
output[pos].y = static_cast<float>(PyFloat_AsDouble(y));
output[pos].z = static_cast<float>(PyFloat_AsDouble(z));
}
}
}
}
}; /// !struct LoadPyList
/// \struct LoadPyList
/// \brief Specialization for lists of unsigned ints with one dimension
template <>
struct PyList<1, smpl::Vector3d>
{
using ValueType = smpl::Vector3d;
using OutputType = std::vector<ValueType>;
/// \brief Load a python list of single dimension
/// \param pyList The python object that represents the list
/// \param[out] output The output vectpr to copy the list into
static void Load(PyObject* pyList, std::vector<ValueType>& output)
{
if (PyList_Check(pyList))
{
output = std::vector<ValueType>(size_t(PyList_Size(pyList)));
for (unsigned int pos = 0; pos < output.size(); ++pos)
{
PyObject* value = PyList_GetItem(pyList, pos);
if (PyList_Check(value))
{
PyObject* x = PyList_GetItem(value, 0);
PyObject* y = PyList_GetItem(value, 1);
PyObject* z = PyList_GetItem(value, 2);
output[pos].x = static_cast<double>(PyFloat_AsDouble(x));
output[pos].y = static_cast<double>(PyFloat_AsDouble(y));
output[pos].z = static_cast<double>(PyFloat_AsDouble(z));
}
}
}
}
}; /// !struct LoadPyList
/// \struct LoadPyList
/// \brief Specialization for lists of unsigned ints with one dimension
template <>
struct PyList<1, smpl::Vector3ui>
{
using ValueType = smpl::Vector3ui;
using OutputType = std::vector<ValueType>;
/// \brief Load a python list of single dimension
/// \param pyList The python object that represents the list
/// \param[out] output The output vectpr to copy the list into
static void Load(PyObject* pyList, std::vector<ValueType>& output)
{
if (PyList_Check(pyList))
{
output = std::vector<ValueType>(size_t(PyList_Size(pyList)));
for (unsigned int pos = 0; pos < output.size(); ++pos)
{
PyObject* value = PyList_GetItem(pyList, pos);
if (PyList_Check(value))
{
PyObject* x = PyList_GetItem(value, 0);
PyObject* y = PyList_GetItem(value, 1);
PyObject* z = PyList_GetItem(value, 2);
output[pos].x = static_cast<unsigned int>(PyLong_AsUnsignedLong(x));
output[pos].y = static_cast<unsigned int>(PyLong_AsUnsignedLong(y));
output[pos].z = static_cast<unsigned int>(PyLong_AsUnsignedLong(z));
}
}
}
}
}; /// !struct LoadPyList
///============================
/// One Dimension List Typedefs
///=============================
using PyList1f = PyList<1, float>;
using PyList1d = PyList<1, double>;
using PyList1l = PyList<1, long>;
using PyList1ul = PyList<1, unsigned long>;
using PyList1ll = PyList<1, long long>;
using PyList1ull = PyList<1, unsigned long long>;
using PyList1i = PyList<1, int>;
using PyList1ui = PyList<1, unsigned int>;
using PyList1Vec3f = PyList<1, smpl::Vector3f>;
using PyList1Vec3d = PyList<1, smpl::Vector3d>;
using PyList1Vec3ui = PyList<1, smpl::Vector3ui>;
///========================
/// Lists of Two Dimensions
///========================
/// \struct LoadPyList
/// \brief Specialization for lists with 2 dimensions holding floats
template <>
struct PyList<2, float>
{
using ValueType = float;
using OutputType = std::vector<std::vector<ValueType>>;
/// \brief Load a python list of single dimension
/// \param pyList The python object that represents the list
/// \param[out] output The output vectpr to copy the list into
static void Load(PyObject* pyList, OutputType& output)
{
if (PyList_Check(pyList))
{
output = std::vector<std::vector<ValueType>>(size_t(PyList_Size(pyList)));
for (unsigned int pos1 = 0; pos1 < output.size(); ++pos1)
{
PyObject* valList = PyList_GetItem(pyList, pos1);
if (PyList_Check(valList))
{
output[pos1] = std::vector<ValueType>(size_t(PyList_Size(valList)));
for (unsigned int pos2 = 0; pos2 < output[pos1].size(); ++pos2)
{
PyObject* value = PyList_GetItem(valList, pos2);
output[pos1][pos2] = static_cast<ValueType>(PyFloat_AsDouble(value));
}
}
}
}
}
};
/// \struct LoadPyList
/// \brief Specialization for lists with 2 dimensions holding doubles
template <>
struct PyList<2, double>
{
using ValueType = double;
using OutputType = std::vector<std::vector<ValueType>>;
/// \brief Load a python list of single dimension
/// \param pyList The python object that represents the list
/// \param[out] output The output vectpr to copy the list into
static void Load(PyObject* pyList, OutputType& output)
{
if (PyList_Check(pyList))
{
output = std::vector<std::vector<ValueType>>(size_t(PyList_Size(pyList)));
for (unsigned int pos1 = 0; pos1 < output.size(); ++pos1)
{
PyObject* valList = PyList_GetItem(pyList, pos1);
if (PyList_Check(valList))
{
output[pos1] = std::vector<ValueType>(size_t(PyList_Size(valList)));
for (unsigned int pos2 = 0; pos2 < output[pos1].size(); ++pos2)
{
PyObject* value = PyList_GetItem(valList, pos2);
output[pos1][pos2] = static_cast<ValueType>(PyFloat_AsDouble(value));
}
}
}
}
}
};
/// \struct LoadPyList
/// \brief Specialization for lists with 2 dimensions holding longs
template <>
struct PyList<2, long>
{
using ValueType = long;
using OutputType = std::vector<std::vector<ValueType>>;
/// \brief Load a python list of single dimension
/// \param pyList The python object that represents the list
/// \param[out] output The output vectpr to copy the list into
static void Load(PyObject* pyList, OutputType& output)
{
if (PyList_Check(pyList))
{
output = std::vector<std::vector<ValueType>>(size_t(PyList_Size(pyList)));
for (unsigned int pos1 = 0; pos1 < output.size(); ++pos1)
{
PyObject* valList = PyList_GetItem(pyList, pos1);
if (PyList_Check(valList))
{
output[pos1] = std::vector<ValueType>(size_t(PyList_Size(valList)));
for (unsigned int pos2 = 0; pos2 < output[pos1].size(); ++pos2)
{
PyObject* value = PyList_GetItem(valList, pos2);
output[pos1][pos2] = static_cast<ValueType>(PyLong_AsLong(value));
}
}
}
}
}
};
/// \struct LoadPyList
/// \brief Specialization for lists with 2 dimensions holding unsigend longs
template <>
struct PyList<2, unsigned long>
{
using ValueType = unsigned long;
using OutputType = std::vector<std::vector<ValueType>>;
/// \brief Load a python list of single dimension
/// \param pyList The python object that represents the list
/// \param[out] output The output vectpr to copy the list into
static void Load(PyObject* pyList, OutputType& output)
{
if (PyList_Check(pyList))
{
output = std::vector<std::vector<ValueType>>(size_t(PyList_Size(pyList)));
for (unsigned int pos1 = 0; pos1 < output.size(); ++pos1)
{
PyObject* valList = PyList_GetItem(pyList, pos1);
if (PyList_Check(valList))
{
output[pos1] = std::vector<ValueType>(size_t(PyList_Size(valList)));
for (unsigned int pos2 = 0; pos2 < output[pos1].size(); ++pos2)
{
PyObject* value = PyList_GetItem(valList, pos2);
output[pos1][pos2] = static_cast<ValueType>(PyLong_AsUnsignedLong(value));
}
}
}
}
}
};
/// \struct LoadPyList
/// \brief Specialization for lists with 2 dimensions holding long longs
template <>
struct PyList<2, long long>
{
using ValueType = long long;
using OutputType = std::vector<std::vector<ValueType>>;
/// \brief Load a python list of single dimension
/// \param pyList The python object that represents the list
/// \param[out] output The output vectpr to copy the list into
static void Load(PyObject* pyList, OutputType& output)
{
if (PyList_Check(pyList))
{
output = std::vector<std::vector<ValueType>>(size_t(PyList_Size(pyList)));
for (unsigned int pos1 = 0; pos1 < output.size(); ++pos1)
{
PyObject* valList = PyList_GetItem(pyList, pos1);
if (PyList_Check(valList))
{
output[pos1] = std::vector<ValueType>(size_t(PyList_Size(valList)));
for (unsigned int pos2 = 0; pos2 < output[pos1].size(); ++pos2)
{
PyObject* value = PyList_GetItem(valList, pos2);
output[pos1][pos2] = static_cast<ValueType>(PyLong_AsLongLong(value));
}
}
}
}
}
};
/// \struct LoadPyList
/// \brief Specialization for lists with 2 dimensions holding long longs
template <>
struct PyList<2, unsigned long long>
{
using ValueType = unsigned long long;
using OutputType = std::vector<std::vector<ValueType>>;
/// \brief Load a python list of single dimension
/// \param pyList The python object that represents the list
/// \param[out] output The output vectpr to copy the list into
static void Load(PyObject* pyList, OutputType& output)
{
if (PyList_Check(pyList))
{
output = std::vector<std::vector<ValueType>>(size_t(PyList_Size(pyList)));
for (unsigned int pos1 = 0; pos1 < output.size(); ++pos1)
{
PyObject* valList = PyList_GetItem(pyList, pos1);
if (PyList_Check(valList))
{
output[pos1] = std::vector<ValueType>(size_t(PyList_Size(valList)));
for (unsigned int pos2 = 0; pos2 < output[pos1].size(); ++pos2)
{
PyObject* value = PyList_GetItem(valList, pos2);
output[pos1][pos2] = static_cast<ValueType>(PyLong_AsUnsignedLongLong(value));
}
}
}
}
}
};
/// \struct LoadPyList
/// \brief Specialization for lists with 2 dimensions holding ints
template <>
struct PyList<2, int>
{
using ValueType = int;
using OutputType = std::vector<std::vector<ValueType>>;
/// \brief Load a python list of single dimension
/// \param pyList The python object that represents the list
/// \param[out] output The output vectpr to copy the list into
static void Load(PyObject* pyList, OutputType& output)
{
if (PyList_Check(pyList))
{
output = std::vector<std::vector<ValueType>>(size_t(PyList_Size(pyList)));
for (unsigned int pos1 = 0; pos1 < output.size(); ++pos1)
{
PyObject* valList = PyList_GetItem(pyList, pos1);
if (PyList_Check(valList))
{
output[pos1] = std::vector<ValueType>(size_t(PyList_Size(valList)));
for (unsigned int pos2 = 0; pos2 < output[pos1].size(); ++pos2)
{
PyObject* value = PyList_GetItem(valList, pos2);
output[pos1][pos2] = static_cast<ValueType>(PyLong_AsLong(value));
}
}
}
}
}
};
/// \struct LoadPyList
/// \brief Specialization for lists with 2 dimensions holding ints
template <>
struct PyList<2, unsigned int>
{
using ValueType = unsigned int;
using OutputType = std::vector<std::vector<ValueType>>;
/// \brief Load a python list of single dimension
/// \param pyList The python object that represents the list
/// \param[out] output The output vectpr to copy the list into
static void Load(PyObject* pyList, OutputType& output)
{
if (PyList_Check(pyList))
{
output = std::vector<std::vector<ValueType>>(size_t(PyList_Size(pyList)));
for (unsigned int pos1 = 0; pos1 < output.size(); ++pos1)
{
PyObject* valList = PyList_GetItem(pyList, pos1);
if (PyList_Check(valList))
{
output[pos1] = std::vector<ValueType>(size_t(PyList_Size(valList)));
for (unsigned int pos2 = 0; pos2 < output[pos1].size(); ++pos2)
{
PyObject* value = PyList_GetItem(valList, pos2);
output[pos1][pos2] = static_cast<ValueType>(PyLong_AsUnsignedLong(value));
}
}
}
}
}
};
/// \struct LoadPyList
/// \brief Specialization for lists with 2 dimensions holding ints
template <>
struct PyList<2, smpl::Vector3f>
{
using ValueType = smpl::Vector3f;
using OutputType = std::vector<std::vector<ValueType>>;
/// \brief Load a python list of single dimension
/// \param pyList The python object that represents the list
/// \param[out] output The output vectpr to copy the list into
static void Load(PyObject* pyList, OutputType& output)
{
if (PyList_Check(pyList))
{
output = std::vector<std::vector<ValueType>>(size_t(PyList_Size(pyList)));
for (unsigned int pos1 = 0; pos1 < output.size(); ++pos1)
{
PyObject* valList = PyList_GetItem(pyList, pos1);
if (PyList_Check(valList))
{
output[pos1] = std::vector<ValueType>(size_t(PyList_Size(valList)));
for (unsigned int pos2 = 0; pos2 < output[pos1].size(); ++pos2)
{
PyObject* value = PyList_GetItem(valList, pos2);
if (PyList_Check(value))
{
PyObject* x = PyList_GetItem(value, 0);
PyObject* y = PyList_GetItem(value, 1);
PyObject* z = PyList_GetItem(value, 2);
output[pos1][pos2].x = static_cast<float>(PyFloat_AsDouble(x));
output[pos1][pos2].y = static_cast<float>(PyFloat_AsDouble(y));
output[pos1][pos2].z = static_cast<float>(PyFloat_AsDouble(z));
}
}
}
}
}
}
};
/// \struct LoadPyList
/// \brief Specialization for lists with 2 dimensions holding ints
template <>
struct PyList<2, smpl::Vector3d>
{
using ValueType = smpl::Vector3d;
using OutputType = std::vector<std::vector<ValueType>>;
/// \brief Load a python list of single dimension
/// \param pyList The python object that represents the list
/// \param[out] output The output vectpr to copy the list into
static void Load(PyObject* pyList, OutputType& output)
{
if (PyList_Check(pyList))
{
output = std::vector<std::vector<ValueType>>(size_t(PyList_Size(pyList)));
for (unsigned int pos1 = 0; pos1 < output.size(); ++pos1)
{
PyObject* valList = PyList_GetItem(pyList, pos1);
if (PyList_Check(valList))
{
output[pos1] = std::vector<ValueType>(size_t(PyList_Size(valList)));
for (unsigned int pos2 = 0; pos2 < output[pos1].size(); ++pos2)
{
PyObject* value = PyList_GetItem(valList, pos2);
if (PyList_Check(value))
{
PyObject* x = PyList_GetItem(value, 0);
PyObject* y = PyList_GetItem(value, 1);
PyObject* z = PyList_GetItem(value, 2);
output[pos1][pos2].x = static_cast<double>(PyFloat_AsDouble(x));
output[pos1][pos2].y = static_cast<double>(PyFloat_AsDouble(y));
output[pos1][pos2].z = static_cast<double>(PyFloat_AsDouble(z));
}
}
}
}
}
}
};
/// \struct LoadPyList
/// \brief Specialization for lists with 2 dimensions holding ints
template <>
struct PyList<2, smpl::Vector3ui>
{
using ValueType = smpl::Vector3ui;
using OutputType = std::vector<std::vector<ValueType>>;
/// \brief Load a python list of single dimension
/// \param pyList The python object that represents the list
/// \param[out] output The output vectpr to copy the list into
static void Load(PyObject* pyList, OutputType& output)
{
if (PyList_Check(pyList))
{
output = std::vector<std::vector<ValueType>>(size_t(PyList_Size(pyList)));
for (unsigned int pos1 = 0; pos1 < output.size(); ++pos1)
{
PyObject* valList = PyList_GetItem(pyList, pos1);
if (PyList_Check(valList))
{
output[pos1] = std::vector<ValueType>(size_t(PyList_Size(valList)));
for (unsigned int pos2 = 0; pos2 < output[pos1].size(); ++pos2)
{
PyObject* value = PyList_GetItem(valList, pos2);
if (PyList_Check(value))
{
PyObject* x = PyList_GetItem(value, 0);
PyObject* y = PyList_GetItem(value, 1);
PyObject* z = PyList_GetItem(value, 2);
output[pos1][pos2].x = static_cast<unsigned int>(PyLong_AsUnsignedLong(x));
output[pos1][pos2].y = static_cast<unsigned int>(PyLong_AsUnsignedLong(y));
output[pos1][pos2].z = static_cast<unsigned int>(PyLong_AsUnsignedLong(z));
}
}
}
}
}
}
};
///=============================
/// 2-dimensional Lists typedefs
///=============================
using PyList2f = PyList<2, float>;
using PyList2d = PyList<2, double>;
using PyList2l = PyList<2, long>;
using PyList2ul = PyList<2, unsigned long>;
using PyList2ll = PyList<2, long long>;
using PyList2ull = PyList<2, unsigned long long>;
using PyList2i = PyList<2, int>;
using PyList2ui = PyList<2, unsigned int>;
using PyList2Vec3f = PyList<2, smpl::Vector3f>;
using PyList2Vec3d = PyList<2, smpl::Vector3d>;
using PyList2Vec3ui = PyList<2, smpl::Vector3ui>;
///=====================
/// 3-dimensional lists
///=====================
/// \struct LoadPyList
/// \brief Specialization for lists with 3 dimensions holding floats
template <>
struct PyList<3, float>
{
using ValueType = float;
using OutputType = std::vector<std::vector<std::vector<ValueType>>>;
/// \brief Load a python list of single dimension
/// \param pyList The python object that represents the list
/// \param[out] output The output vectpr to copy the list into
static void Load(PyObject* pyList, OutputType& output)
{
if (PyList_Check(pyList))
{
output = std::vector<std::vector<std::vector<ValueType>>>(size_t(PyList_Size(pyList)));
for (unsigned int pos1 = 0; pos1 < output.size(); ++pos1)
{
PyObject* valList = PyList_GetItem(pyList, pos1);
if (PyList_Check(valList))
{
output[pos1] = std::vector<std::vector<ValueType>>(size_t(PyList_Size(valList)));
for (unsigned int pos2 = 0; pos2 < output[pos1].size(); ++pos2)
{
PyObject* value = PyList_GetItem(valList, pos2);
if (PyList_Check(value))
{
output[pos1][pos2] = std::vector<ValueType>(size_t(PyList_Size(value)));
for (unsigned int pos3 = 0; pos3 < output[pos1][pos2].size(); ++pos3)
{
PyObject* val = PyList_GetItem(value, pos3);
output[pos1][pos2][pos3] = static_cast<ValueType>(PyFloat_AsDouble(val));
}
}
}
}
}
}
}
};
/// \struct LoadPyList
/// \brief Specialization for lists with 3 dimensions holding doubles
template <>
struct PyList<3, double>
{
using ValueType = double;
using OutputType = std::vector<std::vector<std::vector<ValueType>>>;
/// \brief Load a python list of single dimension
/// \param pyList The python object that represents the list
/// \param[out] output The output vectpr to copy the list into
static void Load(PyObject* pyList, OutputType& output)
{
if (PyList_Check(pyList))
{
output = std::vector<std::vector<std::vector<ValueType>>>(size_t(PyList_Size(pyList)));
for (unsigned int pos1 = 0; pos1 < output.size(); ++pos1)
{
PyObject* valList = PyList_GetItem(pyList, pos1);
if (PyList_Check(valList))
{
output[pos1] = std::vector<std::vector<ValueType>>(size_t(PyList_Size(valList)));
for (unsigned int pos2 = 0; pos2 < output[pos1].size(); ++pos2)
{
PyObject* value = PyList_GetItem(valList, pos2);
if (PyList_Check(value))
{
output[pos1][pos2] = std::vector<ValueType>(size_t(PyList_Size(value)));
for (unsigned int pos3 = 0; pos3 < output[pos1][pos2].size(); ++pos3)
{
PyObject* val = PyList_GetItem(value, pos3);
output[pos1][pos2][pos3] = static_cast<ValueType>(PyFloat_AsDouble(val));
}
}
}
}
}
}
}
};
/// \struct LoadPyList
/// \brief Specialization for lists with 3 dimensions holding floats
template <>
struct PyList<3, long>
{
using ValueType = long;
using OutputType = std::vector<std::vector<std::vector<ValueType>>>;
/// \brief Load a python list of single dimension
/// \param pyList The python object that represents the list
/// \param[out] output The output vectpr to copy the list into
static void Load(PyObject* pyList, OutputType& output)
{
if (PyList_Check(pyList))
{
output = std::vector<std::vector<std::vector<ValueType>>>(size_t(PyList_Size(pyList)));
for (unsigned int pos1 = 0; pos1 < output.size(); ++pos1)
{
PyObject* valList = PyList_GetItem(pyList, pos1);
if (PyList_Check(valList))
{
output[pos1] = std::vector<std::vector<ValueType>>(size_t(PyList_Size(valList)));
for (unsigned int pos2 = 0; pos2 < output[pos1].size(); ++pos2)
{
PyObject* value = PyList_GetItem(valList, pos2);
if (PyList_Check(value))
{
output[pos1][pos2] = std::vector<ValueType>(size_t(PyList_Size(value)));
for (unsigned int pos3 = 0; pos3 < output[pos1][pos2].size(); ++pos3)
{
PyObject* val = PyList_GetItem(value, pos3);
output[pos1][pos2][pos3] = static_cast<ValueType>(PyLong_AsLong(val));
}
}
}
}
}
}
}
};
/// \struct LoadPyList
/// \brief Specialization for lists with 3 dimensions holding floats
template <>
struct PyList<3, unsigned long>
{
using ValueType = unsigned long;
using OutputType = std::vector<std::vector<std::vector<ValueType>>>;
/// \brief Load a python list of single dimension
/// \param pyList The python object that represents the list
/// \param[out] output The output vectpr to copy the list into
static void Load(PyObject* pyList, OutputType& output)
{
if (PyList_Check(pyList))
{
output = std::vector<std::vector<std::vector<ValueType>>>(size_t(PyList_Size(pyList)));
for (unsigned int pos1 = 0; pos1 < output.size(); ++pos1)
{
PyObject* valList = PyList_GetItem(pyList, pos1);
if (PyList_Check(valList))
{
output[pos1] = std::vector<std::vector<ValueType>>(size_t(PyList_Size(valList)));
for (unsigned int pos2 = 0; pos2 < output[pos1].size(); ++pos2)
{
PyObject* value = PyList_GetItem(valList, pos2);
if (PyList_Check(value))
{
output[pos1][pos2] = std::vector<ValueType>(size_t(PyList_Size(value)));
for (unsigned int pos3 = 0; pos3 < output[pos1][pos2].size(); ++pos3)
{
PyObject* val = PyList_GetItem(value, pos3);
output[pos1][pos2][pos3] = static_cast<ValueType>(PyLong_AsUnsignedLong(val));
}
}
}
}
}
}
}
};
/// \struct LoadPyList
/// \brief Specialization for lists with 3 dimensions holding floats
template <>
struct PyList<3, long long>
{
using ValueType = long long;
using OutputType = std::vector<std::vector<std::vector<ValueType>>>;
/// \brief Load a python list of single dimension
/// \param pyList The python object that represents the list
/// \param[out] output The output vectpr to copy the list into
static void Load(PyObject* pyList, OutputType& output)
{
if (PyList_Check(pyList))
{
output = std::vector<std::vector<std::vector<ValueType>>>(size_t(PyList_Size(pyList)));
for (unsigned int pos1 = 0; pos1 < output.size(); ++pos1)
{
PyObject* valList = PyList_GetItem(pyList, pos1);
if (PyList_Check(valList))
{
output[pos1] = std::vector<std::vector<ValueType>>(size_t(PyList_Size(valList)));
for (unsigned int pos2 = 0; pos2 < output[pos1].size(); ++pos2)
{
PyObject* value = PyList_GetItem(valList, pos2);
if (PyList_Check(value))
{
output[pos1][pos2] = std::vector<ValueType>(size_t(PyList_Size(value)));
for (unsigned int pos3 = 0; pos3 < output[pos1][pos2].size(); ++pos3)
{
PyObject* val = PyList_GetItem(value, pos3);
output[pos1][pos2][pos3] = static_cast<ValueType>(PyLong_AsLongLong(val));
}
}
}
}
}
}
}
};
/// \struct LoadPyList
/// \brief Specialization for lists with 3 dimensions holding floats
template <>
struct PyList<3, unsigned long long>
{
using ValueType = unsigned long long;
using OutputType = std::vector<std::vector<std::vector<ValueType>>>;
/// \brief Load a python list of single dimension
/// \param pyList The python object that represents the list
/// \param[out] output The output vectpr to copy the list into
static void Load(PyObject* pyList, OutputType& output)
{
if (PyList_Check(pyList))
{
output = std::vector<std::vector<std::vector<ValueType>>>(size_t(PyList_Size(pyList)));
for (unsigned int pos1 = 0; pos1 < output.size(); ++pos1)
{
PyObject* valList = PyList_GetItem(pyList, pos1);
if (PyList_Check(valList))
{
output[pos1] = std::vector<std::vector<ValueType>>(size_t(PyList_Size(valList)));
for (unsigned int pos2 = 0; pos2 < output[pos1].size(); ++pos2)
{
PyObject* value = PyList_GetItem(valList, pos2);
if (PyList_Check(value))
{
output[pos1][pos2] = std::vector<ValueType>(size_t(PyList_Size(value)));
for (unsigned int pos3 = 0; pos3 < output[pos1][pos2].size(); ++pos3)
{
PyObject* val = PyList_GetItem(value, pos3);
output[pos1][pos2][pos3] = static_cast<ValueType>(PyLong_AsUnsignedLongLong(val));
}
}
}
}
}
}
}
};
/// \struct LoadPyList
/// \brief Specialization for lists with 3 dimensions holding floats
template <>
struct PyList<3, int>
{
using ValueType = int;
using OutputType = std::vector<std::vector<std::vector<ValueType>>>;
/// \brief Load a python list of single dimension
/// \param pyList The python object that represents the list
/// \param[out] output The output vectpr to copy the list into
static void Load(PyObject* pyList, OutputType& output)
{
if (PyList_Check(pyList))
{
output = std::vector<std::vector<std::vector<ValueType>>>(size_t(PyList_Size(pyList)));
for (unsigned int pos1 = 0; pos1 < output.size(); ++pos1)
{
PyObject* valList = PyList_GetItem(pyList, pos1);
if (PyList_Check(valList))
{
output[pos1] = std::vector<std::vector<ValueType>>(size_t(PyList_Size(valList)));
for (unsigned int pos2 = 0; pos2 < output[pos1].size(); ++pos2)
{
PyObject* value = PyList_GetItem(valList, pos2);
if (PyList_Check(value))
{
output[pos1][pos2] = std::vector<ValueType>(size_t(PyList_Size(value)));
for (unsigned int pos3 = 0; pos3 < output[pos1][pos2].size(); ++pos3)
{
PyObject* val = PyList_GetItem(value, pos3);
output[pos1][pos2][pos3] = static_cast<ValueType>(PyLong_AsLong(val));
}
}
}
}
}
}
}
};
/// \struct LoadPyList
/// \brief Specialization for lists with 3 dimensions holding floats
template <>
struct PyList<3, unsigned int>
{
using ValueType = unsigned int;
using OutputType = std::vector<std::vector<std::vector<ValueType>>>;
/// \brief Load a python list of single dimension
/// \param pyList The python object that represents the list
/// \param[out] output The output vectpr to copy the list into
static void Load(PyObject* pyList, OutputType& output)
{
if (PyList_Check(pyList))
{
output = std::vector<std::vector<std::vector<ValueType>>>(size_t(PyList_Size(pyList)));
for (unsigned int pos1 = 0; pos1 < output.size(); ++pos1)
{
PyObject* valList = PyList_GetItem(pyList, pos1);
if (PyList_Check(valList))
{
output[pos1] = std::vector<std::vector<ValueType>>(size_t(PyList_Size(valList)));
for (unsigned int pos2 = 0; pos2 < output[pos1].size(); ++pos2)
{
PyObject* value = PyList_GetItem(valList, pos2);
if (PyList_Check(value))
{
output[pos1][pos2] = std::vector<ValueType>(size_t(PyList_Size(value)));
for (unsigned int pos3 = 0; pos3 < output[pos1][pos2].size(); ++pos3)
{
PyObject* val = PyList_GetItem(value, pos3);
output[pos1][pos2][pos3] = static_cast<ValueType>(PyLong_AsUnsignedLong(val));
}
}
}
}
}
}
}
};
///=======================
/// 3-dimensional typedefs
///=======================
using PyList3f = PyList<3, float>;
using PyList3d = PyList<3, double>;
using PyList3l = PyList<3, long>;
using PyList3ul = PyList<3, unsigned long>;
using PyList3ll = PyList<3, long long>;
using PyList3ull = PyList<3, unsigned long long>;
using PyList3i = PyList<3, int>;
using PyList3ui = PyList<3, unsigned int>;
///==================
/// Dictionary Types
///==================
/// In python dictionaries can hold a very diverse amount of data
/// here we make utilities for marshalling dictionaries specific
/// to our purposes (i.e. our key types will be mostly std::strings
/// and we will specialize on the value types
/// \struct PyDict
/// \brief template does nothing
/// \tparam KeyType The key data type
/// \tparam ValueType The value data type
template <typename KType, typename VType>
struct PyDict
{
using KeyType = KType;
using ValueType = VType;
};
/// \struct PyDict
/// \brief Specialization for String Key Types and float values
template <>
struct PyDict<std::string, float>
{
using KeyType = std::string;
using ValueType = float;
/// \brief copy a python dictionary into an std::map<KeyType, ValueType>
/// \param pyDict The python object that represents the dictionary to copy
/// \param[out] output The std::map to copy the data into
static void Load(PyObject* pyDict, std::map<KeyType, ValueType>& output)
{
if (PyDict_Check(pyDict))
{
PyObject* key;
PyObject* value;
Py_ssize_t pos = 0;
while (PyDict_Next(pyDict, &pos, &key, &value))
{
KeyType nKey;
ValueType nValue;
/// Convert python key to std::string
if (PyUnicode_Check(key))
{
//Py_ssize_t strSize = PyUnicode_GET_LENGTH(key);
nKey = std::string(PyUnicode_AsUTF8(key));
}
if (PyFloat_Check(value))
{
nValue = PyFloat_AsDouble(value);
}
output[nKey] = nValue;
}
}
}
};
/// \struct PyDict
/// \brief Specialization for String Key Types and float values
template <>
struct PyDict<std::string, unsigned int>
{
using KeyType = std::string;
using ValueType = unsigned int;
/// \brief copy a python dictionary into an std::map<KeyType, ValueType>
/// \param pyDict The python object that represents the dictionary to copy
/// \param[out] output The std::map to copy the data into
static void Load(PyObject* pyDict, std::map<KeyType, ValueType>& output)
{
if (PyDict_Check(pyDict))
{
PyObject* key;
PyObject* value;
Py_ssize_t pos = 0;
while (PyDict_Next(pyDict, &pos, &key, &value))
{
KeyType nKey;
ValueType nValue;
/// Convert python key to std::string
if (PyUnicode_Check(key))
{
//Py_ssize_t strSize = PyUnicode_GET_LENGTH(key);
nKey = std::string(PyUnicode_AsUTF8(key));
}
if (PyLong_Check(value))
{
nValue = PyLong_AsUnsignedLong(value);
}
output[nKey] = nValue;
}
}
}
};
///================
/// PyDict typedefs
///================
using PyDictStrf = PyDict<std::string, float>;
using PyDictStrui = PyDict<std::string, unsigned int>;
} /// !namespace util
#endif /// !__LIB_PUBLIC_PYHELPERS_HPP__ | 33.49201 | 99 | 0.667671 | [
"object",
"vector"
] |
8915745747e0cd0bf77ed2d9d860475738ff7592 | 26,514 | cpp | C++ | tests/mytests.cpp | kubaszpak/ieee754_implementation | f75e54e4f7e027b8fe31386d4eda88de9523ac58 | [
"MIT"
] | null | null | null | tests/mytests.cpp | kubaszpak/ieee754_implementation | f75e54e4f7e027b8fe31386d4eda88de9523ac58 | [
"MIT"
] | null | null | null | tests/mytests.cpp | kubaszpak/ieee754_implementation | f75e54e4f7e027b8fe31386d4eda88de9523ac58 | [
"MIT"
] | 1 | 2021-06-15T17:47:51.000Z | 2021-06-15T17:47:51.000Z | #include <gtest/gtest.h>
#include "../lib/ieee754.h"
#include <vector>
#include <chrono>
#include <math.h> //isnan
IEEE_754 zero(std::bitset<32>(0b00000000000000000000000000000000));
IEEE_754 infinity(std::bitset<32>(0b01111111100000000000000000000000));
IEEE_754 negative_infinity(std::bitset<32>(0b11111111100000000000000000000000));
// IEEE_754 nan(std::bitset<32>(0b11111111100001100000000000000000));
IEEE_754 small_number1(std::bitset<32>(0b00000000011100000000000000000000)); // 1.02855755697e-38
IEEE_754 small_number2(std::bitset<32>(0b00000111110000000000000000000000)); // 9.11008121887e-38
IEEE_754 small_number3(std::bitset<32>(0b00111100001000000000000000000000)); // 0.009765625
IEEE_754 big_number1(std::bitset<32>(0b01111111011111111111111111111111)); // 3.40282346639e+38
IEEE_754 big_number2(std::bitset<32>(0b01111111001110111111011111111111)); // 2.4985330455e+38
IEEE_754 big_number3(std::bitset<32>(0b01111110100111000100000000000000)); // 1.03845937171e+38
IEEE_754 four(std::bitset<32>(0b01000000100000000000000000000000));
IEEE_754 two(std::bitset<32>(0b01000000000000000000000000000000));
IEEE_754 ten(std::bitset<32>(0b01000001001000000000000000000000));
IEEE_754 eighty(std::bitset<32>(0b01000010101000000000000000000000));
IEEE_754 ten_thousand(std::bitset<32>(0b01000110000111000100000000000000));
IEEE_754 over_five(std::bitset<32>(0b01000000101001100000000000000000));
IEEE_754 three_hundred_thousand(std::bitset<32>(0b01001000101001100000000000000000));
IEEE_754 denormalized_number1(std::bitset<32>(0b00000000010000000000000000000000)); // 5.87747175411e-39
IEEE_754 denormalized_number2(std::bitset<32>(0b00000000001000000000000000000000)); // 2.93873587706e-39
IEEE_754 denormalized_number3(std::bitset<32>(0b00000000001110111111011111111111)); // 5.50725850893e-39
IEEE_754 denormalized_number4(std::bitset<32>(0b00000000001000000000000000000000)); // 2.93873587706e-39
std::vector<IEEE_754> numbers;
TEST(IEEE_754_TEST, big_addition_test)
{
numbers.push_back(zero);
numbers.push_back(infinity);
numbers.push_back(negative_infinity);
// numbers.push_back(nan);
numbers.push_back(small_number1);
numbers.push_back(small_number2);
numbers.push_back(small_number3);
numbers.push_back(big_number1);
numbers.push_back(big_number2);
numbers.push_back(big_number3);
numbers.push_back(four);
numbers.push_back(two);
numbers.push_back(ten);
numbers.push_back(eighty);
numbers.push_back(ten_thousand);
numbers.push_back(over_five);
numbers.push_back(three_hundred_thousand);
numbers.push_back(denormalized_number1);
numbers.push_back(denormalized_number2);
numbers.push_back(denormalized_number3);
numbers.push_back(denormalized_number4);
int temp = 0;
for (int i = numbers.size() - 1; i >= 0; i--)
{
temp++;
for (size_t j = 0; j < numbers.size(); j++)
{
std::cout << "----------\n"
<< "addition test " << temp << "." << (j + 1) << std::endl;
float f_result = numbers[i].to_float() + numbers[j].to_float();
std::cout << f_result << " = " << numbers[i].to_float() << " + " << numbers[j].to_float() << std::endl;
IEEE_754 result = numbers[i] + numbers[j];
std::cout << result.get_number() << " = " << numbers[i].get_number() << " + " << numbers[j].get_number() << std::endl;
if (isnan(f_result))
continue;
EXPECT_EQ(f_result, result.to_float());
std::cout << "----------\n"
<< std::endl;
}
numbers.pop_back();
}
}
TEST(IEEE_754_TEST, big_subtraction_test)
{
numbers.push_back(zero);
numbers.push_back(infinity);
numbers.push_back(negative_infinity);
// numbers.push_back(nan);
numbers.push_back(small_number1);
numbers.push_back(small_number2);
numbers.push_back(small_number3);
numbers.push_back(big_number1);
numbers.push_back(big_number2);
numbers.push_back(big_number3);
numbers.push_back(four);
numbers.push_back(two);
numbers.push_back(ten);
numbers.push_back(eighty);
numbers.push_back(ten_thousand);
numbers.push_back(over_five);
numbers.push_back(three_hundred_thousand);
numbers.push_back(denormalized_number1);
numbers.push_back(denormalized_number2);
numbers.push_back(denormalized_number3);
numbers.push_back(denormalized_number4);
int temp = 0;
for (int i = numbers.size() - 1; i >= 0; i--)
{
temp++;
for (size_t j = 0; j < numbers.size(); j++)
{
std::cout << "----------\n"
<< "subtraction test " << temp << "." << (j + 1) << std::endl;
float f_result = numbers[i].to_float() - numbers[j].to_float();
std::cout << f_result << " = " << numbers[i].to_float() << " - " << numbers[j].to_float() << std::endl;
IEEE_754 result = numbers[i] - numbers[j];
std::cout << result.get_number() << " = " << numbers[i].get_number() << " - " << numbers[j].get_number() << std::endl;
if (isnan(f_result))
continue;
EXPECT_EQ(f_result, result.to_float());
std::cout << "----------\n"
<< std::endl;
}
numbers.pop_back();
}
}
TEST(IEEE_754_TEST, big_multiplication_test)
{
numbers.push_back(zero);
numbers.push_back(infinity);
numbers.push_back(negative_infinity);
// numbers.push_back(nan);
numbers.push_back(small_number1);
numbers.push_back(small_number2);
numbers.push_back(small_number3);
numbers.push_back(big_number1);
numbers.push_back(big_number2);
numbers.push_back(big_number3);
numbers.push_back(four);
numbers.push_back(two);
numbers.push_back(ten);
numbers.push_back(eighty);
numbers.push_back(ten_thousand);
numbers.push_back(over_five);
numbers.push_back(three_hundred_thousand);
numbers.push_back(denormalized_number1);
numbers.push_back(denormalized_number2);
numbers.push_back(denormalized_number3);
numbers.push_back(denormalized_number4);
int temp = 0;
for (int i = numbers.size() - 1; i >= 0; i--)
{
temp++;
for (size_t j = 0; j < numbers.size(); j++)
{
std::cout << "----------\n"
<< "multiplication test " << temp << "." << (j + 1) << std::endl;
float f_result = numbers[i].to_float() * numbers[j].to_float();
std::cout << f_result << " = " << numbers[i].to_float() << " * " << numbers[j].to_float() << std::endl;
IEEE_754 result = numbers[i] * numbers[j];
std::cout << result.get_number() << " = " << numbers[i].get_number() << " * " << numbers[j].get_number() << std::endl;
if (isnan(f_result))
continue;
EXPECT_EQ(f_result, result.to_float());
std::cout << "----------\n"
<< std::endl;
}
numbers.pop_back();
}
}
TEST(IEEE_754_TEST, big_division_test)
{
// numbers.push_back(zero);
numbers.push_back(infinity);
numbers.push_back(negative_infinity);
// numbers.push_back(nan);
numbers.push_back(small_number1);
numbers.push_back(small_number2);
numbers.push_back(small_number3);
numbers.push_back(big_number1);
numbers.push_back(big_number2);
numbers.push_back(big_number3);
numbers.push_back(four);
numbers.push_back(two);
numbers.push_back(ten);
numbers.push_back(eighty);
numbers.push_back(ten_thousand);
numbers.push_back(over_five);
numbers.push_back(three_hundred_thousand);
numbers.push_back(denormalized_number1);
numbers.push_back(denormalized_number2);
numbers.push_back(denormalized_number3);
numbers.push_back(denormalized_number4);
int temp = 0;
for (int i = numbers.size() - 1; i >= 0; i--)
{
std::cout << "##" << i << std::endl;
temp++;
for (size_t j = 0; j < numbers.size(); j++)
{
std::cout << "----------\n"
<< "division test " << temp << "." << (j + 1) << std::endl;
float f_result = numbers[i].to_float() / numbers[j].to_float();
std::cout << f_result << " = " << numbers[i].to_float() << " / " << numbers[j].to_float() << std::endl;
IEEE_754 result = numbers[i] / numbers[j];
std::cout << result.get_number() << " = " << numbers[i].get_number() << " / " << numbers[j].get_number() << std::endl;
if (isnan(f_result))
continue;
EXPECT_EQ(f_result, result.to_float());
std::cout << "----------\n"
<< std::endl;
}
numbers.pop_back();
}
}
TEST(IEEE_754_TEST, StartAtZero)
{
IEEE_754 number;
float x = number.to_float();
std::cout << "X: " << x << std::endl;
EXPECT_EQ("0", number.display_in_decimal());
}
TEST(IEEE_754_TEST, AllZerosEqualZero)
{
IEEE_754 number(std::bitset<32>(0b00000000000000000000000000000000));
EXPECT_EQ("0", number.display_in_decimal());
}
TEST(IEEE_754_TEST, NegativeInfinity)
{
IEEE_754 negative_infinity(std::bitset<32>(0b11111111100000000000000000000000));
IEEE_754 number;
EXPECT_EQ("-Inf", negative_infinity.display_in_decimal());
}
//addition tests
TEST(IEEE_754_TEST, Infinity_Add)
{
// number - Inf = - Inf
IEEE_754 normalized_number(std::bitset<32>(0b00111111100001100000000000000000));
IEEE_754 infinity(std::bitset<32>(0b01111111100000000000000000000000));
IEEE_754 result = normalized_number + infinity;
EXPECT_EQ(result.get_number(), std::bitset<32>(0b01111111100000000000000000000000));
// check for problems with references between
result.flip_sign_bit();
EXPECT_EQ(result.get_number(), std::bitset<32>(0b11111111100000000000000000000000));
EXPECT_EQ(infinity.get_number(), std::bitset<32>(0b01111111100000000000000000000000));
}
TEST(IEEE_754_TEST, InfinityAddMinusInfinityEqualsNaN)
{
// Inf - Inf = NaN
IEEE_754 plus_infinity(std::bitset<32>(0b01111111100000000000000000000000));
IEEE_754 minus_infinity(std::bitset<32>(0b11111111100000000000000000000000));
IEEE_754 result = plus_infinity + minus_infinity;
EXPECT_EQ("NaN", result.display_in_decimal());
}
TEST(IEEE_754_TEST, Four_Plus_Two)
{
// 4 + 2 = 6
IEEE_754 four(std::bitset<32>(0b01000000100000000000000000000000));
IEEE_754 two(std::bitset<32>(0b01000000000000000000000000000000));
float x = four.to_float();
float y = two.to_float();
std::cout << "X: " << x << std::endl;
std::cout << "Y: " << y << std::endl;
IEEE_754 result = four + two;
EXPECT_EQ(result.get_number(), std::bitset<32>(0b01000000110000000000000000000000));
}
TEST(IEEE_754_TEST, NaN_Add)
{
// number + NaN = NaN
IEEE_754 normalized_number(std::bitset<32>(0b00111111100001100000000000000000));
IEEE_754 nan(std::bitset<32>(0b11111111100001100000000000000000));
IEEE_754 result = normalized_number + nan;
EXPECT_EQ(result.get_number(), std::bitset<32>(0b11111111100001100000000000000000));
result = nan + normalized_number;
EXPECT_EQ(result.get_number(), std::bitset<32>(0b11111111100001100000000000000000));
}
TEST(IEEE_754_TEST, TwoBigNumbersAdd)
{
// 3.40282346639e+38 + 3.40282346639e+38 = Inf
IEEE_754 big_number1(std::bitset<32>(0b01111111011111111111111111111111));
IEEE_754 big_number2(std::bitset<32>(0b01111111011111111111111111111111));
IEEE_754 result = big_number1 + big_number2;
EXPECT_EQ(result.display_in_decimal(), "+Inf");
}
TEST(IEEE_754_TEST, TwoDenormalizedNumbersAdd)
{
// 5.87747175411e-39 + 2.93873587706e-39 = 8.81620763117e-39
IEEE_754 denormalized_number1(std::bitset<32>(0b00000000010000000000000000000000));
IEEE_754 denormalized_number2(std::bitset<32>(0b00000000001000000000000000000000));
IEEE_754 result = denormalized_number1 + denormalized_number2;
EXPECT_EQ(result.get_number(), std::bitset<32>(0b00000000011000000000000000000000));
}
//subtraction tests
TEST(IEEE_754_TEST, Two_Denormalized_Numbers_Subtract)
{
// denormalized - same_denormalized = 0
IEEE_754 denormalized_number1(std::bitset<32>(0b00000000001000000000000000000000));
IEEE_754 denormalized_number2(std::bitset<32>(0b00000000001000000000000000000000));
IEEE_754 result = denormalized_number1 - denormalized_number2;
EXPECT_EQ(result.get_number(), std::bitset<32>(0b00000000000000000000000000000000));
}
TEST(IEEE_754_TEST, Infinity_Subtract)
{
// number - Inf = -Inf
IEEE_754 number1(std::bitset<32>(0b00111111100001100000000000000000));
IEEE_754 infinity(std::bitset<32>(0b01111111100000000000000000000000));
IEEE_754 result = number1 - infinity;
EXPECT_EQ(result.get_number(), std::bitset<32>(0b11111111100000000000000000000000));
}
TEST(IEEE_754_TEST, Minus_Infinity_Subtract)
{
// number - (-Inf) = Inf
IEEE_754 number1(std::bitset<32>(0b00111111100001100000000000000000));
IEEE_754 minus_infinity(std::bitset<32>(0b11111111100000000000000000000000));
IEEE_754 result = number1 - minus_infinity;
EXPECT_EQ(result.get_number(), std::bitset<32>(0b01111111100000000000000000000000));
}
TEST(IEEE_754_TEST, Normal_Substract_TEST1)
{
// 1.25 - 1.25 = 0
IEEE_754 number1(std::bitset<32>(0b00111111101000000000000000000000));
IEEE_754 number2(std::bitset<32>(0b00111111101000000000000000000000));
IEEE_754 result = number1 - number2;
EXPECT_EQ(result.get_number(), std::bitset<32>(0b00000000000000000000000000000000));
}
TEST(IEEE_754_TEST, Normal_Substract_TEST2)
{
// 1.5 - 1.25 = 0.25
IEEE_754 number1(std::bitset<32>(0b00111111110000000000000000000000));
IEEE_754 number2(std::bitset<32>(0b00111111101000000000000000000000));
IEEE_754 result = number1 - number2;
EXPECT_EQ(result.get_number(), std::bitset<32>(0b00111110100000000000000000000000));
}
TEST(IEEE_754_TEST, Normal_Substract_TEST3)
{
// 4 - 2 = 2
IEEE_754 four(std::bitset<32>(0b01000000100000000000000000000000));
IEEE_754 two(std::bitset<32>(0b01000000000000000000000000000000));
IEEE_754 result = four - two;
EXPECT_EQ(result.get_number(), std::bitset<32>(0b01000000000000000000000000000000));
}
TEST(IEEE_754_TEST, Normal_Substract_TEST4)
{
// 24 - 28.5 = -4.5
IEEE_754 four(std::bitset<32>(0b01000001110000000000000000000000));
IEEE_754 two(std::bitset<32>(0b01000001111001000000000000000000));
IEEE_754 result = four - two;
EXPECT_EQ(result.get_number(), std::bitset<32>(0b11000000100100000000000000000000));
}
TEST(IEEE_754_TEST, Denormalized_subtract_2_4)
{
// subtraction test 2.4
// -4.4081e-39 = 5.87747e-39 - 1.02856e-38
IEEE_754 num1(std::bitset<32>(0b00000000010000000000000000000000));
IEEE_754 num2(std::bitset<32>(0b00000000011100000000000000000000));
IEEE_754 result = num1 - num2;
float f_result = num1.to_float() - num2.to_float();
std::cout << f_result << " = " << num1.to_float() << " * " << num2.to_float() << std::endl;
std::cout << result.get_number() << " = " << num1.get_number() << " * " << num2.get_number() << std::endl;
EXPECT_EQ(f_result, result.to_float());
}
TEST(IEEE_754_TEST, SubstractionTestUnsolved)
{
IEEE_754 number1(std::bitset<32>(0b00000000001000000000000000000000));
IEEE_754 number2(std::bitset<32>(0b00000000010000000000000000000000));
IEEE_754 result = number1 - number2;
float f_result = number1.to_float() - number2.to_float();
std::cout << f_result << " = " << number1.to_float() << " * " << number2.to_float() << std::endl;
EXPECT_EQ(result.get_number(), std::bitset<32>(0b10000000001000000000000000000000));
EXPECT_EQ(f_result, result.to_float());
}
//multiplication tests
TEST(IEEE_754_TEST, Normal_Multiply_TEST1)
{
// 4 * 2 = 8
IEEE_754 four(std::bitset<32>(0b01000000100000000000000000000000));
IEEE_754 two(std::bitset<32>(0b01000000000000000000000000000000));
IEEE_754 result = four * two;
EXPECT_EQ(result.get_number(), std::bitset<32>(0b01000001000000000000000000000000));
}
TEST(IEEE_754_TEST, Normal_Multiply_TEST2)
{
// 4 * 4 = 16
IEEE_754 four(std::bitset<32>(0b01000000100000000000000000000000));
IEEE_754 result = four * four;
EXPECT_EQ(result.get_number(), std::bitset<32>(0b01000001100000000000000000000000));
}
TEST(IEEE_754_TEST, Normal_Multiply_TEST3)
{
// 16 * 16 = 256
IEEE_754 sixteen(std::bitset<32>(0b01000001100000000000000000000000));
IEEE_754 result = sixteen * sixteen;
EXPECT_EQ(result.get_number(), std::bitset<32>(0b01000011100000000000000000000000));
}
TEST(IEEE_754_TEST, Normal_Multiply_TEST4)
{
// -5 * 4.25 = -21.25
IEEE_754 number1(std::bitset<32>(0b11000000101000000000000000000000));
IEEE_754 number2(std::bitset<32>(0b01000000100010000000000000000000));
IEEE_754 result = number1 * number2;
std::cout << number1.to_float() << " * " << number2.to_float() << " = " << result.to_float() << std::endl;
EXPECT_EQ(result.get_number(), std::bitset<32>(0b11000001101010100000000000000000));
}
TEST(IEEE_754_TEST, Denormalized_Multiply_TEST1)
{
// 1.02855755697e-38 * 9.11008121887e-38 = 0
IEEE_754 number1(std::bitset<32>(0b00000000011100000000000000000000));
IEEE_754 number2(std::bitset<32>(0b00000111110000000000000000000000));
IEEE_754 result = number1 * number2;
std::cout << number1.to_float() << " * " << number2.to_float() << " = " << result.to_float() << std::endl;
EXPECT_EQ(result.get_number(), std::bitset<32>(0b00000000000000000000000000000000));
}
TEST(IEEE_754_TEST, Denormalized_Multiply_TEST2)
{
// 1.02855755697e-38 0 * 6442450944 = 0
IEEE_754 number1(std::bitset<32>(0b00000000011100000000000000000000));
IEEE_754 number2(std::bitset<32>(0b01001111110000000000000000000000));
IEEE_754 result = number1 * number2;
std::cout << number1.to_float() << " * " << number2.to_float() << " = " << result.to_float() << std::endl;
EXPECT_EQ(result.get_number(), std::bitset<32>(0b00010000101010000000000000000000));
}
// special numbers [multiplication]
TEST(IEEE_754_TEST, Infinity_Times_Number)
{
// number* Inf = Inf
IEEE_754 normalized_number(std::bitset<32>(0b00111111100001100000000000000000));
IEEE_754 infinity(std::bitset<32>(0b01111111100000000000000000000000));
IEEE_754 result = normalized_number * infinity;
EXPECT_EQ(result.get_number(), std::bitset<32>(0b01111111100000000000000000000000));
}
TEST(IEEE_754_TEST, Infinity_Times_Infinity)
{
// Inf * Inf = Inf
IEEE_754 infinity(std::bitset<32>(0b01111111100000000000000000000000));
IEEE_754 result = infinity * infinity;
EXPECT_EQ(result.get_number(), std::bitset<32>(0b01111111100000000000000000000000));
}
TEST(IEEE_754_TEST, NaN_Multiplication)
{
// number * NaN = NaN
IEEE_754 normalized_number(std::bitset<32>(0b00111111100001100000000000000000));
IEEE_754 nan(std::bitset<32>(0b11111111100001100000000000000000));
IEEE_754 result = normalized_number * nan;
EXPECT_EQ(result.get_number(), std::bitset<32>(0b11111111100001100000000000000000));
}
TEST(IEEE_754_TEST, TwoBigNumbersMultiplication)
{
// 3.40282346639e+38 * 3.40282346639e+38 = Inf
IEEE_754 big_number(std::bitset<32>(0b01111111011111111111111111111111));
IEEE_754 result = big_number + big_number;
EXPECT_EQ(result.get_number(), std::bitset<32>(0b01111111100000000000000000000000));
}
TEST(IEEE_754_TEST, Unsolved_Multiplication_Example)
{
// multiplication test 1.6
// 1 = 2.93874e-39 * 3.40282e+38
// 2097152 * 16777215 = 35184369991680
// 01000000011111111111111111111111 = 00000000001000000000000000000000 * 01111111011111111111111111111111
IEEE_754 num1(std::bitset<32>(0b00000000001000000000000000000000)); // 1 = 2.93874e-39
IEEE_754 num2(std::bitset<32>(0b01111111011111111111111111111111)); //3.40282e+38
IEEE_754 result = num1 * num2;
float f_result = num1.to_float() * num2.to_float();
std::cout << f_result << " = " << num1.to_float() << " * " << num2.to_float() << std::endl;
std::cout << result.get_number() << " = " << num1.get_number() << " * " << num2.get_number() << std::endl;
EXPECT_EQ(f_result, result.to_float());
}
//division tests
TEST(IEEE_754_TEST, Normal_Division_TEST1)
{
// 4 / 2 = 2
IEEE_754 four(std::bitset<32>(0b01000000100000000000000000000000));
IEEE_754 two(std::bitset<32>(0b01000000000000000000000000000000));
IEEE_754 result = four / two;
EXPECT_EQ(result.get_number(), std::bitset<32>(0b01000000000000000000000000000000));
}
TEST(IEEE_754_TEST, Normal_Division_TEST2)
{
// 10/ 80 = 0.125
IEEE_754 ten(std::bitset<32>(0b01000001001000000000000000000000));
IEEE_754 eighty(std::bitset<32>(0b01000010101000000000000000000000));
IEEE_754 result = ten / eighty;
EXPECT_EQ(result.get_number(), std::bitset<32>(0b00111110000000000000000000000000));
}
TEST(IEEE_754_TEST, Normal_Division_TEST3)
{
// 4 / 4 = 1
IEEE_754 four(std::bitset<32>(0b01000000100000000000000000000000));
IEEE_754 result = four / four;
EXPECT_EQ(result.get_number(), std::bitset<32>(0b00111111100000000000000000000000));
}
TEST(IEEE_754_TEST, Dividing_By_Infinity)
{
// 4 / inf = 0
IEEE_754 four(std::bitset<32>(0b01000000100000000000000000000000));
IEEE_754 infinity(std::bitset<32>(0b01111111100000000000000000000000));
IEEE_754 result = four / infinity;
EXPECT_EQ(result.get_number(), std::bitset<32>(0b00000000000000000000000000000000));
}
TEST(IEEE_754_TEST, Unsolved_Dividing_test1)
{
IEEE_754 ten(std::bitset<32>(0b01000001001000000000000000000000));
IEEE_754 two(std::bitset<32>(0b01000000000000000000000000000000));
IEEE_754 result = ten / two;
EXPECT_EQ(result.get_number(), std::bitset<32>(0b01000000101000000000000000000000));
float f_result = ten.to_float() / two.to_float();
std::cout << f_result << " = " << ten.to_float() << " / " << two.to_float() << std::endl;
std::cout << result.get_number() << " = " << ten.get_number() << " / " << two.get_number() << std::endl;
EXPECT_EQ(f_result, result.to_float());
}
TEST(IEEE_754_TEST, Unsolved_Dividing_test2)
{
IEEE_754 numb1(std::bitset<32>(0b00000000001000000000000000000000));
IEEE_754 numb2(std::bitset<32>(0b01000001001000000000000000000000));
IEEE_754 result = numb1 / numb2;
float f_result = numb1.to_float() / numb2.to_float();
std::cout << f_result << " = " << numb1.to_float() << " / " << numb2.to_float() << std::endl;
std::cout << result.get_number() << " = " << numb1.get_number() << " / " << numb2.get_number() << std::endl;
EXPECT_EQ(f_result, result.to_float());
}
TEST(IEEE_754_TEST, Unsolved_Dividing_test3)
{
IEEE_754 num1(std::bitset<32>(0b00000000010000000000000000000000));
IEEE_754 num2(std::bitset<32>(0b01111111011111111111111111111111));
IEEE_754 result = num1 / num2;
EXPECT_EQ(result.get_number(), std::bitset<32>(0b00000000000000000000000000000000));
float f_result = num1.to_float() / num2.to_float();
std::cout << f_result << " = " << num1.to_float() << " / " << num2.to_float() << std::endl;
std::cout << result.get_number() << " = " << num1.get_number() << " / " << num2.get_number() << std::endl;
std::cout << "NOWY TESfdsdfT" << std::endl;
EXPECT_EQ(f_result, result.to_float());
}
TEST(IEEE_754_TEST, time_measurment)
{
numbers.push_back(zero);
numbers.push_back(infinity);
numbers.push_back(negative_infinity);
// numbers.push_back(nan);
numbers.push_back(small_number1);
numbers.push_back(small_number2);
numbers.push_back(small_number3);
numbers.push_back(big_number1);
numbers.push_back(big_number2);
numbers.push_back(big_number3);
numbers.push_back(four);
numbers.push_back(two);
numbers.push_back(ten);
numbers.push_back(eighty);
numbers.push_back(ten_thousand);
numbers.push_back(over_five);
numbers.push_back(three_hundred_thousand);
numbers.push_back(denormalized_number1);
numbers.push_back(denormalized_number2);
numbers.push_back(denormalized_number3);
numbers.push_back(denormalized_number4);
int counter = 0;
auto start = std::chrono::system_clock::now();
for (int x = 0; x < 100; x++)
{
for (int i = numbers.size() - 1; i >= 0; i--)
{
for (size_t j = 0; j < numbers.size(); j++)
{
counter++;
IEEE_754 result = numbers[i] / numbers[j];
}
}
}
auto end = std::chrono::system_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
std::cout << counter << " ieee754 operations - measured time = " << elapsed.count() << '\n';
//float
// numbers.push_back(zero);
// numbers.push_back(infinity);
// numbers.push_back(negative_infinity);
// // numbers.push_back(nan);
// numbers.push_back(small_number1);
// numbers.push_back(small_number2);
// numbers.push_back(small_number3);
// numbers.push_back(big_number1);
// numbers.push_back(big_number2);
// numbers.push_back(big_number3);
// numbers.push_back(four);
// numbers.push_back(two);
// numbers.push_back(ten);
// numbers.push_back(eighty);
// numbers.push_back(ten_thousand);
// numbers.push_back(over_five);
// numbers.push_back(three_hundred_thousand);
// numbers.push_back(denormalized_number1);
// numbers.push_back(denormalized_number2);
// numbers.push_back(denormalized_number3);
// numbers.push_back(denormalized_number4);
counter = 0;
start = std::chrono::system_clock::now();
for (int x = 0; x < 100; x++)
{
for (int i = numbers.size() - 1; i >= 0; i--)
{
for (size_t j = 0; j < numbers.size(); j++)
{
counter++;
float result = numbers[i].to_float() / numbers[j].to_float();
}
}
}
end = std::chrono::system_clock::now();
elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
std::cout << counter << " float operations - measured time = " << elapsed.count() << '\n';
EXPECT_EQ(1, 1);
}
int main(int argc, char *argv[])
{
fesetround(FE_TONEAREST);
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} | 37.502122 | 130 | 0.680659 | [
"vector"
] |
8919162b90c8ea70d3ef08c6c0ca6ff032661df7 | 6,427 | cpp | C++ | emulator/src/devices/bus/abcbus/cadmouse.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | 1 | 2022-01-15T21:38:38.000Z | 2022-01-15T21:38:38.000Z | emulator/src/devices/bus/abcbus/cadmouse.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | emulator/src/devices/bus/abcbus/cadmouse.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | // license:BSD-3-Clause
// copyright-holders:Peter Bortas
/*
ABC CAD Mouse/Hi-res video card
The ABC CAD was an innovative electronics CAD accessory invented by
Marek Gorczyca, Betronex Elektronik AB 1983 to overcome the limitations
in the ABC80 microcomputer graphics which was very popular in Sweden at the time.
The mouse feature is in the form of a small box with a handle sticking out at the front.
The handle can be manipulated in one direction by turning it around its internal pivot
point left and right. The other dimension in handled by pulling and pushing the handle.
One button is available on the top of the handle.
The mouse is connected via the ABC bus, but also passes through the
ABC80<->Monitor power/AV cable
The mouse was sold with the PCB CAD program "CAD-ABC"
PCB Layout
----------
|-| CN1 |------------------------------|
| 4164 CN2 CN3 CN4 PROM5|
| 4164 Z80 PROM6|
| 4164 PROM7|
| 4164 PROM3 PROM4 |
| 4164 |
| 4164 EPROM0 |
| 4164 EPROM1 |
| 4416 4801 |
| PROM2 CR1 |
|-------------------------------------------|
Notes:
Relevant IC's shown.
4801 - Mostek MK4801AN-2 1KiB SRAM 150ns
4164 - TI TMS4164-15NL 8KiB DRAM
4416 - TI TMS4416-15NL 16k x 4bit DRAM (= 8KiB)
EPROM0 - Intel 2764-25 8KiB EPROM "D"
EPROM1 - Intel 2764-25 8KiB EPROM "E"
PROM2 - TI TBP18S030 256b PROM "TBP18S030"
PROM3 - Harris HM7602 256b PROM "M3-7603-5 1"
PROM4 - Signetics N82S129N 1024b PROM "N82S129N 1"
PROM5 - Harris HM7602 256b PROM "M3-7603-5 2"
PROM6 - Signetics N82S129N 1024b PROM "N82S129N 2"
PROM7 - Signetics N82S129N 1024b PROM "N82S129N 3"
Z80 - Z80 CPU "Z 80/1C"
CN1 - ABCBUS connector
CN2 - ABC80 power/AV connector passthrough?
CN3 - ABC80 power/AV connector passthrough?
CN4 - ABC80 power/AV connector passthrough?
CR1 - Crystal "8.000 OSI"
*/
#include "emu.h"
#include "cadmouse.h"
#define Z80_TAG "cardcpu"
//**************************************************************************
// DEVICE DEFINITIONS
//**************************************************************************
DEFINE_DEVICE_TYPE(ABC_CADMOUSE, abc_cadmouse_device, "cadabc", "CAD ABC Mouse/Hi-res Unit")
//-------------------------------------------------
// ROM( abc_cadmouse )
//-------------------------------------------------
ROM_START( abc_cadmouse )
ROM_REGION( 0x4000, Z80_TAG, 0 )
// FIXME: The mapping of the EPROMs or if the map locally or on
// the bus in unknown. 0x0 and 0x2k are just placeholders.
ROM_LOAD( "eprom0.bin", 0x2000, 0x2000, CRC(c19d655d) SHA1(332ad862b77cff3ec55f0f78ac31b2b8cf93b7b3) )
ROM_LOAD( "eprom1.bin", 0x0000, 0x2000, CRC(e71c9141) SHA1(07a6fae4e3fff3d7a4f67ad0791e4e297c1763aa) )
ROM_REGION( 0x20, "cadmouse_prom2", 0 )
ROM_LOAD( "prom2.bin", 0x0000, 0x0020, CRC(C6C3BC9B) SHA1(5944cce355657b7bdc693f47a72f6b01decdc02a) ) // 32x8
ROM_REGION( 0x20, "cadmouse_prom3", 0 )
ROM_LOAD( "prom3.bin", 0x0000, 0x0020, CRC(862FC73A) SHA1(8a5391cd2ab61e5c3e22bb8805ace48566f5f57d) ) // 32x8
ROM_REGION( 0x100, "cadmouse_prom4", 0 )
ROM_LOAD( "prom4.bin", 0x0000, 0x0100, CRC(DF58AAA9) SHA1(a2ab3b19a85ba3da6d78d1b0d44e2c33b44de5bc) ) // 256x4
ROM_REGION( 0x20, "cadmouse_prom5", 0 )
ROM_LOAD( "prom5.bin", 0x0000, 0x0020, CRC(5EFD8B94) SHA1(cbfd6ebee815b02667ae886bb0820efa29311d37) ) // 32x8
ROM_REGION( 0x100, "cadmouse_prom6", 0 )
ROM_LOAD( "prom6.bin", 0x0000, 0x0100, CRC(EE3D8B75) SHA1(1afb22e3cff6e36f49228f63d0c7830bc48cf3cf) ) // 256x4
ROM_REGION( 0x100, "cadmouse_prom7", 0 )
ROM_LOAD( "prom7.bin", 0x0000, 0x0100, CRC(395110BD) SHA1(54720d155b4990d9879b95c0d13592bb7534da09) ) // 256x4
ROM_END
//-------------------------------------------------
// rom_region - device-specific ROM region
//-------------------------------------------------
const tiny_rom_entry *abc_cadmouse_device::device_rom_region() const
{
return ROM_NAME( abc_cadmouse );
}
//-------------------------------------------------
// ADDRESS_MAP( abc_cadmouse_mem )
//-------------------------------------------------
void abc_cadmouse_device::abc_cadmouse_mem(address_map &map)
{
map.unmap_value_high();
map.global_mask(0x3fff);
map(0x0000, 0x3fff).rom().region(Z80_TAG, 0);
}
//-------------------------------------------------
// ADDRESS_MAP( abc_cadmouse_io )
//-------------------------------------------------
void abc_cadmouse_device::abc_cadmouse_io(address_map &map)
{
}
//-------------------------------------------------
// device_add_mconfig - add device configuration
//-------------------------------------------------
MACHINE_CONFIG_START(abc_cadmouse_device::device_add_mconfig)
MCFG_CPU_ADD(Z80_TAG, Z80, XTAL(8'000'000)/2)
MCFG_CPU_PROGRAM_MAP(abc_cadmouse_mem)
MCFG_CPU_IO_MAP(abc_cadmouse_io)
MACHINE_CONFIG_END
//**************************************************************************
// LIVE DEVICE
//**************************************************************************
//-------------------------------------------------
// abc_cadmouse_device - constructor
//-------------------------------------------------
abc_cadmouse_device::abc_cadmouse_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: device_t(mconfig, ABC_CADMOUSE, tag, owner, clock),
device_abcbus_card_interface(mconfig, *this),
m_maincpu(*this, Z80_TAG)
{
}
//-------------------------------------------------
// device_start - device-specific startup
//-------------------------------------------------
void abc_cadmouse_device::device_start()
{
}
//-------------------------------------------------
// device_reset - device-specific reset
//-------------------------------------------------
void abc_cadmouse_device::device_reset()
{
}
//**************************************************************************
// ABC BUS INTERFACE
//**************************************************************************
//-------------------------------------------------
// abcbus_cs -
//-------------------------------------------------
void abc_cadmouse_device::abcbus_cs(uint8_t data)
{
}
| 35.705556 | 121 | 0.535086 | [
"cad"
] |
89266154389c6e044f2f61759ee2b3c8a0e18b65 | 6,303 | hpp | C++ | src/org/apache/poi/ss/usermodel/DataFormatter.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | src/org/apache/poi/ss/usermodel/DataFormatter.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | src/org/apache/poi/ss/usermodel/DataFormatter.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | // Generated from /POI/java/org/apache/poi/ss/usermodel/DataFormatter.java
#pragma once
#include <fwd-POI.hpp>
#include <java/lang/fwd-POI.hpp>
#include <java/math/fwd-POI.hpp>
#include <java/text/fwd-POI.hpp>
#include <java/util/fwd-POI.hpp>
#include <java/util/regex/fwd-POI.hpp>
#include <org/apache/poi/ss/formula/fwd-POI.hpp>
#include <org/apache/poi/ss/usermodel/fwd-POI.hpp>
#include <org/apache/poi/util/fwd-POI.hpp>
#include <java/lang/Object.hpp>
#include <java/util/Observer.hpp>
struct default_init_tag;
class poi::ss::usermodel::DataFormatter
: public virtual ::java::lang::Object
, public virtual ::java::util::Observer
{
public:
typedef ::java::lang::Object super;
private:
static ::java::lang::String* defaultFractionWholePartFormat_;
static ::java::lang::String* defaultFractionFractionPartFormat_;
static ::java::util::regex::Pattern* numPattern_;
static ::java::util::regex::Pattern* daysAsText_;
static ::java::util::regex::Pattern* amPmPattern_;
static ::java::util::regex::Pattern* rangeConditionalPattern_;
static ::java::util::regex::Pattern* localePatternGroup_;
static ::java::util::regex::Pattern* colorPattern_;
static ::java::util::regex::Pattern* fractionPattern_;
static ::java::util::regex::Pattern* fractionStripper_;
static ::java::util::regex::Pattern* alternateGrouping_;
static ::java::lang::String* invalidDateTimeString_;
::java::text::DecimalFormatSymbols* decimalSymbols { };
::java::text::DateFormatSymbols* dateSymbols { };
::java::text::DateFormat* defaultDateformat { };
::java::text::Format* generalNumberFormat { };
::java::text::Format* defaultNumFormat { };
::java::util::Map* formats { };
bool emulateCSV { };
::java::util::Locale* locale { };
bool localeIsAdapting { };
DataFormatter_LocaleChangeObservable* localeChangedObservable { };
static ::poi::util::POILogger* logger_;
protected:
void ctor();
void ctor(bool emulateCSV);
void ctor(::java::util::Locale* locale);
void ctor(::java::util::Locale* locale, bool emulateCSV);
void ctor(::java::util::Locale* locale, bool localeIsAdapting, bool emulateCSV);
private:
::java::text::Format* getFormat(Cell* cell, ::poi::ss::formula::ConditionalFormattingEvaluator* cfEvaluator);
::java::text::Format* getFormat(double cellValue, int32_t formatIndex, ::java::lang::String* formatStrIn);
public:
virtual ::java::text::Format* createFormat(Cell* cell);
private:
::java::text::Format* createFormat(double cellValue, int32_t formatIndex, ::java::lang::String* sFormat);
::java::text::Format* createDateFormat(::java::lang::String* pFormatStr, double cellValue);
::java::lang::String* cleanFormatForNumber(::java::lang::String* formatStr);
::java::text::Format* createNumberFormat(::java::lang::String* formatStr, double cellValue);
public:
virtual ::java::text::Format* getDefaultFormat(Cell* cell);
private:
::java::text::Format* getDefaultFormat(double cellValue);
::java::lang::String* performDateFormatting(::java::util::Date* d, ::java::text::Format* dateFormat);
::java::lang::String* getFormattedDateString(Cell* cell, ::poi::ss::formula::ConditionalFormattingEvaluator* cfEvaluator);
::java::lang::String* getFormattedNumberString(Cell* cell, ::poi::ss::formula::ConditionalFormattingEvaluator* cfEvaluator);
public:
virtual ::java::lang::String* formatRawCellContents(double value, int32_t formatIndex, ::java::lang::String* formatString);
virtual ::java::lang::String* formatRawCellContents(double value, int32_t formatIndex, ::java::lang::String* formatString, bool use1904Windowing);
virtual ::java::lang::String* formatCellValue(Cell* cell);
virtual ::java::lang::String* formatCellValue(Cell* cell, FormulaEvaluator* evaluator);
virtual ::java::lang::String* formatCellValue(Cell* cell, FormulaEvaluator* evaluator, ::poi::ss::formula::ConditionalFormattingEvaluator* cfEvaluator);
virtual void setDefaultNumberFormat(::java::text::Format* format);
virtual void addFormat(::java::lang::String* excelFormatStr, ::java::text::Format* format);
private:
static ::java::text::DecimalFormat* createIntegerOnlyFormat(::java::lang::String* fmt);
public:
static void setExcelStyleRoundingMode(::java::text::DecimalFormat* format);
static void setExcelStyleRoundingMode(::java::text::DecimalFormat* format, ::java::math::RoundingMode* roundingMode);
virtual ::java::util::Observable* getLocaleChangedObservable();
void update(::java::util::Observable* observable, ::java::lang::Object* localeObj) override;
// Generated
DataFormatter();
DataFormatter(bool emulateCSV);
DataFormatter(::java::util::Locale* locale);
DataFormatter(::java::util::Locale* locale, bool emulateCSV);
private:
DataFormatter(::java::util::Locale* locale, bool localeIsAdapting, bool emulateCSV);
protected:
DataFormatter(const ::default_init_tag&);
public:
static ::java::lang::Class *class_();
static void clinit();
private:
void init();
static ::java::lang::String*& defaultFractionWholePartFormat();
static ::java::lang::String*& defaultFractionFractionPartFormat();
static ::java::util::regex::Pattern*& numPattern();
static ::java::util::regex::Pattern*& daysAsText();
static ::java::util::regex::Pattern*& amPmPattern();
static ::java::util::regex::Pattern*& rangeConditionalPattern();
static ::java::util::regex::Pattern*& localePatternGroup();
static ::java::util::regex::Pattern*& colorPattern();
static ::java::util::regex::Pattern*& fractionPattern();
static ::java::util::regex::Pattern*& fractionStripper();
static ::java::util::regex::Pattern*& alternateGrouping();
static ::java::lang::String*& invalidDateTimeString();
static ::poi::util::POILogger*& logger();
virtual ::java::lang::Class* getClass0();
friend class DataFormatter_LocaleChangeObservable;
friend class DataFormatter_InternalDecimalFormatWithScale;
friend class DataFormatter_SSNFormat;
friend class DataFormatter_ZipPlusFourFormat;
friend class DataFormatter_PhoneFormat;
friend class DataFormatter_ConstantStringFormat;
friend class DataFormatter_CellFormatResultWrapper;
};
| 45.673913 | 156 | 0.71934 | [
"object"
] |
8926dd42fcb2b0aa8dad9893afdd0776741c7dfd | 4,424 | cpp | C++ | Examples/CPP/WorkingWithCalendars/CreatingUpdatingAndRemoving/WriteUpdatedCalendarDataToMPP.cpp | aspose-tasks/Aspose.Tasks-for-C | acb3e2b75685f65cbe34dd739c7eae0dfc285aa1 | [
"MIT"
] | 1 | 2022-03-16T14:31:36.000Z | 2022-03-16T14:31:36.000Z | Examples/CPP/WorkingWithCalendars/CreatingUpdatingAndRemoving/WriteUpdatedCalendarDataToMPP.cpp | aspose-tasks/Aspose.Tasks-for-C | acb3e2b75685f65cbe34dd739c7eae0dfc285aa1 | [
"MIT"
] | null | null | null | Examples/CPP/WorkingWithCalendars/CreatingUpdatingAndRemoving/WriteUpdatedCalendarDataToMPP.cpp | aspose-tasks/Aspose.Tasks-for-C | acb3e2b75685f65cbe34dd739c7eae0dfc285aa1 | [
"MIT"
] | 1 | 2020-07-01T01:26:17.000Z | 2020-07-01T01:26:17.000Z | /*
This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Tasks for .NET API reference
when the project is build. Please check https:// Docs.nuget.org/consume/nuget-faq for more information.
If you do not wish to use NuGet, you can manually download Aspose.Tasks for .NET API from https://www.nuget.org/packages/Aspose.Tasks/,
install it and then add its reference to this project. For any issues, questions or suggestions
please feel free to contact us using https://forum.aspose.com/c/tasks
*/
#include "WriteUpdatedCalendarDataToMPP.h"
#include <WorkingTimeCollection.h>
#include <WorkingTime.h>
#include <system/type_info.h>
#include <system/string.h>
#include <system/shared_ptr.h>
#include <system/reflection/method_base.h>
#include <system/object.h>
#include <system/exceptions.h>
#include <system/date_time.h>
#include <system/console.h>
#include <saving/Enums/SaveFileFormat.h>
#include <Project.h>
#include <Prj.h>
#include <Key.h>
#include <enums/PrjKey.h>
#include <CalendarExceptionCollection.h>
#include <CalendarException.h>
#include <CalendarCollection.h>
#include <Calendar.h>
#include "RunExamples.h"
using namespace Aspose::Tasks;
using namespace Aspose::Tasks::Saving;
namespace Aspose {
namespace Tasks {
namespace Examples {
namespace CPP {
namespace WorkingWithCalendars {
namespace CreatingUpdatingAndRemoving {
RTTI_INFO_IMPL_HASH(444529282u, ::Aspose::Tasks::Examples::CPP::WorkingWithCalendars::CreatingUpdatingAndRemoving::WriteUpdatedCalendarDataToMPP, ThisTypeBaseTypesInfo);
void WriteUpdatedCalendarDataToMPP::Run()
{
// ExStart:WriteUpdatedCalendarDataToMPP
System::String resultFile = u"result_WriteUpdatedCalendarDataToMPP_out.mpp";
System::String newFile = u"project_update_test.mpp";
System::String dataDir = Examples::CPP::RunExamples::GetDataDir(System::Reflection::MethodBase::GetCurrentMethod(ASPOSE_CURRENT_FUNCTION)->get_DeclaringType().get_FullName());
try
{
// Create project instance and access calendar
System::SharedPtr<Project> project = System::MakeObject<Project>(dataDir + newFile);
System::SharedPtr<Calendar> cal = project->get_Calendars()->GetByUid(3);
// Update the calendar information
Calendar::MakeStandardCalendar(cal);
cal->set_Name(u"Test calendar");
System::SharedPtr<CalendarException> exc = System::MakeObject<CalendarException>();
exc->set_FromDate(System::DateTime::get_Now());
exc->set_ToDate(System::DateTime::get_Now().AddDays(2));
exc->set_DayWorking(true);
System::SharedPtr<WorkingTime> wt1 = System::MakeObject<WorkingTime>();
wt1->set_FromTime(System::DateTime(10, 1, 1, 9, 0, 0));
wt1->set_ToTime(System::DateTime(10, 1, 1, 13, 0, 0));
System::SharedPtr<WorkingTime> wt2 = System::MakeObject<WorkingTime>();
wt2->set_FromTime(System::DateTime(10, 1, 1, 14, 0, 0));
wt2->set_ToTime(System::DateTime(10, 1, 1, 19, 0, 0));
System::SharedPtr<WorkingTime> wt3 = System::MakeObject<WorkingTime>();
wt3->set_FromTime(System::DateTime(10, 1, 1, 20, 0, 0));
wt3->set_ToTime(System::DateTime(10, 1, 1, 21, 0, 0));
exc->get_WorkingTimes()->Add(wt1);
exc->get_WorkingTimes()->Add(wt2);
exc->get_WorkingTimes()->Add(wt3);
cal->get_Exceptions()->Add(exc);
System::SharedPtr<CalendarException> exc2 = System::MakeObject<CalendarException>();
exc2->set_FromDate(System::DateTime::get_Now().AddDays(7));
exc2->set_ToDate(exc2->get_FromDate());
exc2->set_DayWorking(false);
cal->get_Exceptions()->Add(exc2);
project->Set<System::SharedPtr<Calendar>>(Prj::Calendar(), cal);
// Save project
project->Save(dataDir + resultFile, Aspose::Tasks::Saving::SaveFileFormat::MPP);
}
catch (System::Exception& ex)
{
System::Console::WriteLine(ex->get_Message() + u"\nThis example will only work if you apply a valid Aspose License. You can purchase full license or get 30 day temporary license from http:// Www.aspose.com/purchase/default.aspx.");
}
// ExEnd:WriteUpdatedCalendarDataToMPP
}
} // namespace CreatingUpdatingAndRemoving
} // namespace WorkingWithCalendars
} // namespace CPP
} // namespace Examples
} // namespace Tasks
} // namespace Aspose
| 39.5 | 239 | 0.702758 | [
"object"
] |
89334f5e9158c33a3f4349d0e2d29eaa765c42f4 | 8,447 | cpp | C++ | legacy/btmux-mux20/mux/src/player_c.cpp | murrayma/btmux | 3519fdbfb9d5d27b4ce8e46ee16796961f1a0bfa | [
"ClArtistic",
"Naumen",
"Condor-1.1",
"MS-PL"
] | 1 | 2020-07-09T17:37:42.000Z | 2020-07-09T17:37:42.000Z | legacy/btmux-mux20/mux/src/player_c.cpp | murrayma/btmux | 3519fdbfb9d5d27b4ce8e46ee16796961f1a0bfa | [
"ClArtistic",
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | legacy/btmux-mux20/mux/src/player_c.cpp | murrayma/btmux | 3519fdbfb9d5d27b4ce8e46ee16796961f1a0bfa | [
"ClArtistic",
"Naumen",
"Condor-1.1",
"MS-PL"
] | 1 | 2020-11-07T00:02:47.000Z | 2020-11-07T00:02:47.000Z | /*! \file player_c.cpp
* Player cache routines.
*
* $Id: player_c.cpp,v 1.16 2005/10/30 11:27:05 sdennis Exp $
*
* Frequenty-used items which appear on every object generally find a home in
* the db[] structure managed in db.cpp. However, there are a few items
* related only to players which are still accessed frequently enough that
* they should be cached. These items are money, current number of queued
* commands, and the limit on the number of queued commands.
*/
#include "copyright.h"
#include "autoconf.h"
#include "config.h"
#include "externs.h"
#include "attrs.h"
/*! \brief structure to hold cached data for player-type objects.
*/
typedef struct player_cache
{
dbref player;
int money;
int queue;
int qmax;
int cflags;
struct player_cache *next;
} PCACHE;
/*! \brief Hash Table which maps player dbref to PCACHE entry.
*/
CHashTable pcache_htab;
/*! \brief The head of a singly-linked list of all PCACHE entries.
*/
PCACHE *pcache_head;
#define PF_REF 0x0002
#define PF_MONEY_CH 0x0004
/*! \brief Initializes the player cache.
*
* This is called once to initialize the player cache and supporting
* data structures: Player cache structures are pooled, the Hash Table
* initializes itself, and the singly-linked list is started.
*
* \return None.
*/
void pcache_init(void)
{
pool_init(POOL_PCACHE, sizeof(PCACHE));
pcache_head = NULL;
}
/*! \brief Updates player cache items from the database.
*
* The Money and QueueMax attributes are used to initialize the corresponding
* items in the player cache. If a Money attribute does not exist for some
* strange reason, it it initialized to zero and marked as dirty. If a
* QueueMax attribute doesn't exist or is negative, then the game will
* choose a reasonable limit later in QueueMax().
*
* \param player player object to begin caching.
* \param pp pointer to PCACHE structure.
* \return None.
*/
static void pcache_reload1(dbref player, PCACHE *pp)
{
const char *cp = atr_get_raw(player, A_MONEY);
if (cp && *cp)
{
pp->money = mux_atol(cp);
}
else
{
pp->cflags |= PF_MONEY_CH;
pp->money = 0;
}
int m = -1;
cp = atr_get_raw(player, A_QUEUEMAX);
if (cp && *cp)
{
m = mux_atol(cp);
if (m < 0)
{
m = -1;
}
}
pp->qmax = m;
}
/*! \brief Returns a player's cache record.
*
* Whether created from scratch or found in the cache, pcache_find() always
* returns a valid player cache record for the requested player object dbref.
* This function uses Hash Table access primarily, but it maintains the
* singly-linked list as well.
*
* \param player player object dbref.
* \return Pointer to new or existing player cache record.
*/
static PCACHE *pcache_find(dbref player)
{
PCACHE *pp = (PCACHE *)hashfindLEN(&player, sizeof(player), &pcache_htab);
if (pp)
{
pp->cflags |= PF_REF;
return pp;
}
pp = alloc_pcache("pcache_find");
pp->queue = 0;
pp->cflags = PF_REF;
pp->player = player;
pcache_reload1(player, pp);
pp->next = pcache_head;
pcache_head = pp;
hashaddLEN(&player, sizeof(player), pp, &pcache_htab);
return pp;
}
/*! \brief Saves any dirty player data items to the database.
*
* \param pp pointer to potentially dirty PCACHE structure.
* \return None.
*/
static void pcache_save(PCACHE *pp)
{
if (pp->cflags & PF_MONEY_CH)
{
IBUF tbuf;
mux_ltoa(pp->money, tbuf);
atr_add_raw(pp->player, A_MONEY, tbuf);
pp->cflags &= ~PF_MONEY_CH;
}
}
/*! \brief Re-initializes Money and QueueMax items from the database.
*
* \param player player object dbref.
* \return None.
*/
void pcache_reload(dbref player)
{
if ( Good_obj(player)
&& OwnsOthers(player))
{
PCACHE *pp = pcache_find(player);
pcache_save(pp);
pcache_reload1(player, pp);
}
}
/*! \brief Ages and trims the player cache of stale entries.
*
* pcache_trim() relies primarily on the singly-linked list, but it also
* maintains the Hash Table. To be trimmed, a player cache record must
* not have outstanding commands in the command queue.
*
* The one level of aging is accomplished with PR_REF. On the first pass
* through the linked list, the PR_REF bit is removed. On the second pass
* through the list, the record is trimmed.
*
* \return None.
*/
void pcache_trim(void)
{
PCACHE *pp = pcache_head;
PCACHE *pplast = NULL;
while (pp)
{
PCACHE *ppnext = pp->next;
if ( pp->queue
|| (pp->cflags & PF_REF))
{
// This entry either has outstanding commands in the queue or we
// need to let it age.
//
pp->cflags &= ~PF_REF;
pplast = pp;
}
else
{
// Unlink and destroy this entry.
//
if (pplast)
{
pplast->next = ppnext;
}
else
{
pcache_head = ppnext;
}
pcache_save(pp);
hashdeleteLEN(&(pp->player), sizeof(pp->player), &pcache_htab);
free_pcache(pp);
}
pp = ppnext;
}
}
/*! \brief Flushes any dirty player items to the database.
*
* The primary access is via the singly-linked list. Upon return, all the
* player cache records are marked as clean.
*
* \return None.
*/
void pcache_sync(void)
{
PCACHE *pp = pcache_head;
while (pp)
{
pcache_save(pp);
pp = pp->next;
}
}
/*! \brief Adjusts the count of queued commands up or down.
*
* cque.cpp uses this as it schedules and performs queued commands.
*
* \param player dbref of player object responsible for command.
* \param adj new (+) or completed (-) commands being queued.
* \return None.
*/
int a_Queue(dbref player, int adj)
{
if ( Good_obj(player)
&& OwnsOthers(player))
{
PCACHE *pp = pcache_find(player);
pp->queue += adj;
return pp->queue;
}
return 0;
}
/*! \brief Returns the player's upper limit of queued commands.
*
* If a QueueMax is set on the player, we use that. Otherwise, there is
* a configurable game-wide limit (given by player_queue_limit) unless the
* player is a Wizard in which case, we reason that well behaved Wizard code
* should be able to schedule as much work as there are objects in the
* database -- larger game, more work to be expected in the queue.
*
* \param player dbref of player object.
* \return None.
*/
int QueueMax(dbref player)
{
int m = 0;
if ( Good_obj(player)
&& OwnsOthers(player))
{
PCACHE *pp = pcache_find(player);
if (pp->qmax >= 0)
{
m = pp->qmax;
}
else
{
// @queuemax was not valid so we use the game-wide limit.
//
m = mudconf.queuemax;
if ( Wizard(player)
&& m < mudstate.db_top + 1)
{
m = mudstate.db_top + 1;
}
}
}
return m;
}
/*! \brief Returns how many coins are in a player's purse.
*
* \param player dbref of player object.
* \return None.
*/
int Pennies(dbref obj)
{
if (mudstate.bStandAlone)
{
const char *cp = atr_get_raw(obj, A_MONEY);
if (cp)
{
return mux_atol(cp);
}
}
else if ( Good_obj(obj)
&& OwnsOthers(obj))
{
PCACHE *pp = pcache_find(obj);
return pp->money;
}
return 0;
}
/*! \brief Sets the number of coins in a player's purse.
*
* This changes the number of coins a player holds and sets this attribute
* as dirty so that it will be updated in the attribute database later.
*
* \param player dbref of player object responsible for command.
* \param howfew Number of coins
* \return None.
*/
void s_Pennies(dbref obj, int howfew)
{
if (mudstate.bStandAlone)
{
IBUF tbuf;
mux_ltoa(howfew, tbuf);
atr_add_raw(obj, A_MONEY, tbuf);
}
else if ( Good_obj(obj)
&& OwnsOthers(obj))
{
PCACHE *pp = pcache_find(obj);
pp->money = howfew;
pp->cflags |= PF_MONEY_CH;
}
}
| 24.844118 | 78 | 0.601634 | [
"object"
] |
89349cdd6de529a21121c8ce9a299517d54f4344 | 1,172 | hpp | C++ | libs/besiq/method/peer_method.hpp | hoehleatsu/besiq | 94959e2819251805e19311ce377919e6bccb7bf9 | [
"BSD-3-Clause"
] | 1 | 2015-10-21T14:22:12.000Z | 2015-10-21T14:22:12.000Z | libs/besiq/method/peer_method.hpp | hoehleatsu/besiq | 94959e2819251805e19311ce377919e6bccb7bf9 | [
"BSD-3-Clause"
] | 2 | 2019-05-26T20:52:31.000Z | 2019-05-28T16:19:49.000Z | libs/besiq/method/peer_method.hpp | hoehleatsu/besiq | 94959e2819251805e19311ce377919e6bccb7bf9 | [
"BSD-3-Clause"
] | 2 | 2016-11-06T14:58:37.000Z | 2019-05-26T14:03:13.000Z | #ifndef __PEER_METHOD_H__
#define __PEER_METHOD_H__
#include <string>
#include <vector>
#include <armadillo>
#include <besiq/method/method.hpp>
#include <besiq/method/wald_method.hpp>
#include <besiq/stats/log_scale.hpp>
/**
* This class is responsible for intializing and repeatedly
* executing the case-only test by Lewinger et al.
*/
class peer_method
: public method_type
{
public:
/**
* Constructor.
*
* @param data Additional data required by all methods, such as
* covariates.
*/
peer_method(method_data_ptr data);
/**
* @see method_type::init.
*/
virtual std::vector<std::string> init();
/**
* @see method_type::run.
*/
virtual double run(const snp_row &row1, const snp_row &row2, float *output);
private:
void compute_ld_p(const arma::mat &counts, float *ld_case_z, float *ld_contrast_z);
arma::mat encode_counts(const arma::mat &counts, size_t snp1_onestart, size_t snp2_onestart);
/**
* A weight > 0 associated with each sample, that allows for
* covariate adjustment.
*/
arma::vec m_weight;
};
#endif /* End of __PEER_METHOD_H__ */
| 23.44 | 97 | 0.665529 | [
"vector"
] |
893ad351d195dbab00baab81a0551fa3343da5c9 | 2,226 | cpp | C++ | Graph/MAY TARGET/Cycle Detection in Undirected Graph using BFS.cpp | scortier/DSA-Complete-Sheet | 925a5cb148d9addcb32192fe676be76bfb2915c7 | [
"MIT"
] | 1 | 2021-07-20T06:08:26.000Z | 2021-07-20T06:08:26.000Z | Graph/MAY TARGET/Cycle Detection in Undirected Graph using BFS.cpp | scortier/DSA-Complete-Sheet | 925a5cb148d9addcb32192fe676be76bfb2915c7 | [
"MIT"
] | null | null | null | Graph/MAY TARGET/Cycle Detection in Undirected Graph using BFS.cpp | scortier/DSA-Complete-Sheet | 925a5cb148d9addcb32192fe676be76bfb2915c7 | [
"MIT"
] | null | null | null | /*
Approach :
1.bfs traversal m root node(start node) se dist=1 wale simultaneously ssaare visit honge fir dist=2 then so on
2. ab agr traversal karte karte pata chale ki koi adj node pehle se visted bas baat khtm mtlb cycle hai.
*/
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution {
//Cycle check By BFS
bool checkForCycle(int src, int V, vector<int> adj[], vector<int>& visited)
{
//saare node ko -1 se initialize
vector<int>parent(V, -1);
//create a queue for bfs in pair of (node,parent of the node)
queue<pair<int, int>>q;
//node ko vis mark karo
visited[src] = true;
//q m push karo with parent koi nhi as parent ka parent nhi hai
q.push({src, -1});
//jab tk q bhari hai trvaersal karte rho
while (!q.empty())
{
int node = q.front().first;
int node_ka_parent = q.front().second;
q.pop();
//dekho agr node k adj node vis hai ya nhi
for (auto child : adj[node])
{
//agr vis nhi hai toh vis karao aur q m bhi push kar do
if (!visited[child])
{
visited[child] = 1;
q.push({child, node});
}
//agr vis hai and node_ka_parent child nhi hai toh badiya hai badhai ho
//MIRACLE MIRACLE MIRACLE
else if (node_ka_parent != child)
{
return true;
}
}
}
return false;
}
public:
bool isCycle(int V, vector<int>adj[])
{
//make visited array and initialize all weit 0
vector<int>vis(V + 1, 0);
//traverse trought each vertex one by one
for (int i = 1; i <= V; i++)
{
//agr node vis nhi hai toh visite karao aur uske adj node ko bhi vis karao
if (!vis[i])
{
//aur agr adj node pehle viss nikla mtlb cycle hai
if (checkForCycle(i, V, adj, vis))
{
return true;
}
}
}
//sab vi karliye par koi bhi adj node vis nhi mila hence cycle nhi hai
return false;
}
};
// { Driver Code Starts.
int main() {
int tc;
cin >> tc;
while (tc--) {
int V, E;
cin >> V >> E;
vector<int>adj[V];
for (int i = 0; i < E; i++) {
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
Solution obj;
bool ans = obj.isCycle(V, adj);
if (ans)
cout << "1\n";
else cout << "0\n";
}
return 0;
} // } Driver Code Ends
| 20.803738 | 110 | 0.611411 | [
"vector"
] |
9f1e9d9c7640768ab2556df107492e5f4f1694b9 | 1,558 | cpp | C++ | Source/USlicingLogic/Private/SlicingTipComponent.cpp | joserochh/USlicing | 17c2cd0f1bd4b09c132818219997a695537e6d99 | [
"BSD-3-Clause"
] | null | null | null | Source/USlicingLogic/Private/SlicingTipComponent.cpp | joserochh/USlicing | 17c2cd0f1bd4b09c132818219997a695537e6d99 | [
"BSD-3-Clause"
] | 1 | 2020-08-05T17:22:52.000Z | 2020-08-05T18:25:00.000Z | Source/USlicingLogic/Private/SlicingTipComponent.cpp | joserochh/USlicing | 17c2cd0f1bd4b09c132818219997a695537e6d99 | [
"BSD-3-Clause"
] | 1 | 2020-07-01T07:26:22.000Z | 2020-07-01T07:26:22.000Z | // Copyright 2018, Institute for Artificial Intelligence - University of Bremen
#include "SlicingTipComponent.h"
#include "SlicingBladeComponent.h"
#include "SlicingHelper.h"
// Called when the game starts
void USlicingTipComponent::BeginPlay()
{
Super::BeginPlay();
// Check for the blade component to know which object is being cut
BladeComponent = FSlicingHelper::GetSlicingComponent<USlicingBladeComponent>(SlicingObject);
// Register the overlap events
OnComponentBeginOverlap.AddDynamic(this, &USlicingTipComponent::OnBeginOverlap);
OnComponentEndOverlap.AddDynamic(this, &USlicingTipComponent::OnEndOverlap);
SetGenerateOverlapEvents(true);
}
void USlicingTipComponent::OnBeginOverlap(UPrimitiveComponent* OverlappedComp, AActor* OtherActor,
UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
OverlappedComponent = OtherComp;
if (BladeComponent->CutComponent != NULL && OtherComp == BladeComponent->CutComponent)
{
UE_LOG(LogTemp, Warning, TEXT("SLICING: The tip enters the same object as the blade is inside of"));
CutComponent = OtherComp;
bEnteredCurrentlyCutObject = true;
}
}
void USlicingTipComponent::OnEndOverlap(UPrimitiveComponent* OverlappedComp, AActor* OtherActor,
UPrimitiveComponent* OtherComp, int32 OtherBodyIndex)
{
OverlappedComponent = NULL;
if (OtherComp == CutComponent)
{
UE_LOG(LogTemp, Warning, TEXT("SLICING: The tip exits the same object as the blade is inside of"));
CutComponent = NULL;
bEnteredCurrentlyCutObject = false;
}
} | 32.458333 | 102 | 0.790757 | [
"object"
] |
9f240b9714334ebaec7285d4bf818ca02605f61c | 2,053 | hpp | C++ | include/dish2/load/reconstitute_population.hpp | schregardusc/dishtiny | b0b1841a457a955fa4c22f36a050d91f12484f9e | [
"MIT"
] | 1 | 2021-02-12T23:53:55.000Z | 2021-02-12T23:53:55.000Z | include/dish2/load/reconstitute_population.hpp | schregardusc/dishtiny | b0b1841a457a955fa4c22f36a050d91f12484f9e | [
"MIT"
] | null | null | null | include/dish2/load/reconstitute_population.hpp | schregardusc/dishtiny | b0b1841a457a955fa4c22f36a050d91f12484f9e | [
"MIT"
] | null | null | null | #pragma once
#ifndef DISH2_LOAD_RECONSTITUTE_POPULATION_HPP_INCLUDE
#define DISH2_LOAD_RECONSTITUTE_POPULATION_HPP_INCLUDE
#include <fstream>
#include "../../../third-party/bxzstr/include/bxzstr.hpp"
#include "../../../third-party/cereal/include/cereal/archives/binary.hpp"
#include "../../../third-party/conduit/include/uitsl/mpi/comm_utils.hpp"
#include "../../../third-party/conduit/include/uitsl/polyfill/filesystem.hpp"
#include "../../../third-party/conduit/include/uitsl/utility/keyname_directory_filter.hpp"
#include "../../../third-party/Empirical/include/emp/base/always_assert.hpp"
#include "../../../third-party/Empirical/include/emp/base/vector.hpp"
#include "../../../third-party/Empirical/include/emp/tools/keyname_utils.hpp"
#include "../../../third-party/Empirical/include/emp/tools/string_utils.hpp"
#include "../algorithm/seed_genomes_into.hpp"
#include "../genome/Genome.hpp"
#include "../world/ThreadWorld.hpp"
namespace dish2 {
template< typename Spec >
void reconstitute_population(
const size_t thread_idx, dish2::ThreadWorld<Spec>& world
) {
// must set root ids here?
emp::vector< dish2::Genome<Spec> > reconstituted;
{
const auto eligible_population_paths = uitsl::keyname_directory_filter({
{"a", "population"},
{"proc", emp::to_string( uitsl::get_proc_id() )},
{"thread", emp::to_string( thread_idx )},
{"ext", ".bin.xz"}
});
emp_always_assert(
eligible_population_paths.size() == 1,
eligible_population_paths.size(), eligible_population_paths
);
bxz::ifstream ifs( eligible_population_paths.front() );
cereal::BinaryInputArchive iarchive( ifs );
iarchive( reconstituted );
std::cout << "proc " << uitsl::get_proc_id() << " thread " << thread_idx
<< " reconstituted " << reconstituted.size() << " cells from "
<< eligible_population_paths.front() << std::endl;
}
dish2::seed_genomes_into<Spec>( reconstituted, world );
}
} // namespace dish2
#endif // #ifndef DISH2_LOAD_RECONSTITUTE_POPULATION_HPP_INCLUDE
| 28.915493 | 90 | 0.701413 | [
"vector"
] |
9f2b5b08db6b9bc3c120872f44aa84646a639dc1 | 1,831 | cc | C++ | src/PPMReader.cc | dlcrush/crush-engine | 880ec89af4f34156af388fe6fe48da57850d4d6e | [
"MIT"
] | null | null | null | src/PPMReader.cc | dlcrush/crush-engine | 880ec89af4f34156af388fe6fe48da57850d4d6e | [
"MIT"
] | null | null | null | src/PPMReader.cc | dlcrush/crush-engine | 880ec89af4f34156af388fe6fe48da57850d4d6e | [
"MIT"
] | null | null | null | #include "headers/PPMReader.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
// WARNING: This expects a PPM file with no header. To use correctly,
// you will need to delete the header information from the PPM file.
PPMReader::PPMReader(string file2) {
file = file2;
}
// constructor
PPMReader::~PPMReader() {
file = "";
}
// Sets the file to the specified file.
// NOTE: It is assumed that file is a valid file. Otherwise,
// very bad things will happen.
void PPMReader::setFile(string file) {
this->file = file;
}
// Returns the name of the file
string PPMReader::getFile() {
return file;
}
//
void PPMReader::readHeader(ifstream & inputFile, int & width, int & height) {
char * crap = new char[500]; // good variable name!
inputFile.getline(crap, 500);
inputFile.getline(crap, 500);
inputFile >> width;
inputFile >> height;
inputFile.getline(crap, 500);
inputFile.getline(crap, 500);
}
// WARNING: This will only work if PPM file 4 line header with line 3 containing the width and
// height information for the texture.
// NOTE: Method used here is pretty stupid as the insert method for
// vector is extremely inefficient. However, I'm too lazy to fix it right now.
void PPMReader::read(unsigned char * & result, int & tex_size, int & tex_width, int & tex_height) {
// TODO
ifstream inputFile(file); // open fstream
bool done = ! inputFile.good(); // check to see if fstream is good
readHeader(inputFile, tex_width, tex_height);
cout << tex_width << endl;
cout << tex_height << endl;
tex_size = tex_width * tex_height * 3;
result = new unsigned char[tex_size];
// for (int i = tex_size - 1; i >= 0; i --) {
// result[i] = inputFile.get();
// }
for (int i = 0; i < tex_size; i ++) {
result[i] = inputFile.get();
}
cout << tex_size << endl;
} | 28.609375 | 99 | 0.690879 | [
"vector"
] |
9f2b94def70a70f748ad33d3c546ccd36edd3859 | 2,493 | hpp | C++ | include/etl/crtp/value_testable.hpp | wichtounet/etl | 8cc5b7eaf56f1d9f9f78d337d64339731ffe2a94 | [
"MIT"
] | 210 | 2015-02-13T11:40:45.000Z | 2022-01-21T21:46:42.000Z | include/etl/crtp/value_testable.hpp | wichtounet/etl | 8cc5b7eaf56f1d9f9f78d337d64339731ffe2a94 | [
"MIT"
] | 5 | 2017-01-31T18:12:48.000Z | 2020-07-16T15:18:00.000Z | include/etl/crtp/value_testable.hpp | wichtounet/etl | 8cc5b7eaf56f1d9f9f78d337d64339731ffe2a94 | [
"MIT"
] | 25 | 2016-11-26T16:32:56.000Z | 2021-07-20T02:08:51.000Z | //=======================================================================
// Copyright (c) 2014-2020 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
/*!
* \file value_testable.hpp
* \brief Use CRTP technique to inject functions that test the values of the expressions or the value classes.
*/
#pragma once
namespace etl {
/*!
* \brief CRTP class to inject functions testing values of the expressions.
*
* This CRTP class injects test for is_finite and is_zero.
*/
template <typename D>
struct value_testable {
using derived_t = D; ///< The derived type
/*!
* \brief Returns a reference to the derived object, i.e. the object using the CRTP injector.
* \return a reference to the derived object.
*/
derived_t& as_derived() noexcept {
return *static_cast<derived_t*>(this);
}
/*!
* \brief Returns a reference to the derived object, i.e. the object using the CRTP injector.
* \return a reference to the derived object.
*/
const derived_t& as_derived() const noexcept {
return *static_cast<const derived_t*>(this);
}
/*!
* \brief Indicates if the expression contains only finite values.
* \return true if the sequence only contains finite values, false otherwise.
*/
bool is_finite() const noexcept {
return std::all_of(as_derived().begin(), as_derived().end(), static_cast<bool (*)(value_t<derived_t>)>(std::isfinite));
}
/*!
* \brief Indicates if the expression contains only zero values.
* \return true if the sequence only contains zero values, false otherwise.
*/
bool is_zero() const noexcept {
return std::all_of(as_derived().begin(), as_derived().end(), [](value_t<derived_t> v) { return v == value_t<derived_t>(0); });
}
/*!
* \brief Indicates if the expression is diagonal.
* \return true if the expression is diagonal, false otherwise.
*/
bool is_diagonal() const noexcept {
return etl::is_diagonal(as_derived());
}
/*!
* \brief Indicates if the expression is uniform, i.e. all elements are of the same value
* \return true if the expression is uniform, false otherwise.
*/
bool is_uniform() const noexcept {
return etl::is_uniform(as_derived());
}
};
} //end of namespace etl
| 32.802632 | 134 | 0.622543 | [
"object"
] |
9f468e8e458e7484b66a9b7268b95ca82bd22eb7 | 4,748 | cpp | C++ | Solutions/ExerciseA/Cpp/pi_vocl.cpp | Lucksong/Exercises-Solutions | 614c3ad9945d83de21ef2bfdd38e0c67cedc4c8b | [
"CC-BY-3.0"
] | 436 | 2015-01-09T23:29:34.000Z | 2022-03-31T11:25:38.000Z | Solutions/ExerciseA/Cpp/pi_vocl.cpp | Lucksong/Exercises-Solutions | 614c3ad9945d83de21ef2bfdd38e0c67cedc4c8b | [
"CC-BY-3.0"
] | 13 | 2015-04-12T12:54:32.000Z | 2020-03-07T06:52:09.000Z | Solutions/ExerciseA/Cpp/pi_vocl.cpp | Lucksong/Exercises-Solutions | 614c3ad9945d83de21ef2bfdd38e0c67cedc4c8b | [
"CC-BY-3.0"
] | 195 | 2015-01-14T05:08:28.000Z | 2022-02-21T21:01:55.000Z | //
// Pi reduction - vectorized
//
// Numeric integration to estimate pi
// Asks the user to select a device at runtime
// Vector size must be present as a CLI argument
//
// History: C version written by Tim Mattson, May 2010
// Ported to the C++ Wrapper API by Benedict R. Gaster, September 2011
// C++ version Updated by Tom Deakin and Simon McIntosh-Smith, October 2012
// Updated by Tom Deakin, September 2013
//
#define __CL_ENABLE_EXCEPTIONS
#include "cl.hpp"
#include "util.hpp"
#include <vector>
#include <iostream>
#include <fstream>
//pick up device type from compiler command line or from
//the default type
#ifndef DEVICE
#define DEVICE CL_DEVICE_TYPE_DEFAULT
#endif
#include "err_code.h"
#define INSTEPS (512*512*512)
int main(int argc, char** argv)
{
if (argc != 2)
{
std::cout << "Usage: ./pi_vocl num\n"
<< "\twhere num = 1, 4 or 8\n";
return EXIT_FAILURE;
}
int vector_size = atoi(argv[1]);
// Define some vector size specific constants
unsigned int ITERS, WGS;
if (vector_size == 1)
{
ITERS = 262144;
WGS = 8;
}
else if (vector_size == 4)
{
ITERS = 262144 / 4;
WGS = 32;
}
else if (vector_size == 8)
{
ITERS = 262144 / 8;
WGS = 64;
}
else
{
std::cerr << "Invalid vector size\n";
return EXIT_FAILURE;
}
// Set some default values:
// Default number of steps (updated later to device preferable)
unsigned int in_nsteps = INSTEPS;
// Default number of iterations
unsigned int niters = ITERS;
unsigned int work_group_size = WGS;
try
{
// Create context, queue and build program
cl::Context context(DEVICE);
cl::CommandQueue queue(context);
cl::Program program(context, util::loadProgram("../pi_vocl.cl"), true);
cl::Kernel kernel;
// Now that we know the size of the work_groups, we can set the number of work
// groups, the actual number of steps, and the step size
unsigned int nwork_groups = in_nsteps/(work_group_size*niters);
// Get the max work group size for the kernel pi on our device
unsigned int max_size;
std::vector<cl::Device> devices = context.getInfo<CL_CONTEXT_DEVICES>();
if (vector_size == 1)
{
kernel = cl::Kernel(program, "pi");
max_size = kernel.getWorkGroupInfo<CL_KERNEL_WORK_GROUP_SIZE>(devices[0]);
}
else if (vector_size == 4)
{
kernel = cl::Kernel(program, "pi_vec4");
max_size = kernel.getWorkGroupInfo<CL_KERNEL_WORK_GROUP_SIZE>(devices[0]);
}
else if (vector_size == 8)
{
kernel = cl::Kernel(program, "pi_vec8");
max_size = kernel.getWorkGroupInfo<CL_KERNEL_WORK_GROUP_SIZE>(devices[0]);
}
if (max_size > work_group_size)
{
work_group_size = max_size;
nwork_groups = in_nsteps/(nwork_groups*niters);
}
if (nwork_groups < 1)
{
nwork_groups = devices[0].getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>();
work_group_size = in_nsteps/(nwork_groups*niters);
}
unsigned int nsteps = work_group_size * niters * nwork_groups;
float step_size = 1.0f / (float) nsteps;
// Vector to hold partial sum
std::vector<float> h_psum(nwork_groups);
std::cout << nwork_groups << " work groups of size " << work_group_size << ".\n"
<< nsteps << " Integration steps\n";
cl::Buffer d_partial_sums(context, CL_MEM_WRITE_ONLY, sizeof(float) * nwork_groups);
// Start the timer
util::Timer timer;
// Execute the kernel over the entire range of our 1d input data et
// using the maximum number of work group items for this device
cl::NDRange global(nwork_groups * work_group_size);
cl::NDRange local(work_group_size);
kernel.setArg(0, niters);
kernel.setArg(1, step_size);
cl::LocalSpaceArg localmem = cl::Local(sizeof(float) * work_group_size);
kernel.setArg(2, localmem);
kernel.setArg(3, d_partial_sums);
queue.enqueueNDRangeKernel(kernel, cl::NullRange, global, local);
cl::copy(queue, d_partial_sums, h_psum.begin(), h_psum.end());
// Complete the sum and compute the final integral value
float pi_res = 0.0;
for (std::vector<float>::iterator x = h_psum.begin(); x != h_psum.end(); x++)
pi_res += *x;
pi_res *= step_size;
// Stop the timer
double rtime = static_cast<double>(timer.getTimeMilliseconds()) / 1000.;
std::cout << "The calculation ran in " << rtime << " seconds\n"
<< " pi = " << pi_res << " for " << nsteps << " steps\n";
return EXIT_SUCCESS;
}
catch (cl::Error err)
{
std::cout << "Exception\n";
std::cerr
<< "ERROR: "
<< err.what()
<< "("
<< err_code(err.err())
<< ")"
<< std::endl;
return EXIT_FAILURE;
}
}
| 27.445087 | 92 | 0.64385 | [
"vector"
] |
9f492b78f8c55fc8c8a844e29bffb8b6864da59d | 11,222 | cc | C++ | ncrystal_core/src/NCFastConvolve.cc | mctools/ncrystal | 33ec51187a3bef418046c30e591ff7d8f239d54f | [
"Apache-2.0"
] | 22 | 2017-08-31T08:44:10.000Z | 2022-03-21T08:18:26.000Z | ncrystal_core/src/NCFastConvolve.cc | XuShuqi7/ncrystal | acf26db3dfd5f0a95355c7c3bbfcbfee55040175 | [
"Apache-2.0"
] | 77 | 2018-01-23T10:19:45.000Z | 2022-03-21T07:57:32.000Z | ncrystal_core/src/NCFastConvolve.cc | XuShuqi7/ncrystal | acf26db3dfd5f0a95355c7c3bbfcbfee55040175 | [
"Apache-2.0"
] | 11 | 2017-09-14T19:49:50.000Z | 2022-02-28T11:07:00.000Z | ////////////////////////////////////////////////////////////////////////////////
// //
// This file is part of NCrystal (see https://mctools.github.io/ncrystal/) //
// //
// Copyright 2015-2021 NCrystal developers //
// //
// 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 "NCrystal/NCDefs.hh"
#include "NCrystal/internal/NCFastConvolve.hh"
#include <cstdlib>
namespace NC = NCrystal;
//Temporarily uncomment the following define to test with safer but slower code:
//#define NCRYSTAL_FASTCONVOLVE_EXTRASAFEMATH
NC::FastConvolve::FastConvolve() = default;
NC::FastConvolve::~FastConvolve() = default;
void NC::FastConvolve::initWTable( unsigned n_size )
{
//round n_size up to next power of 2:
unsigned n_size_pow2 = 1;
while (n_size_pow2<n_size)
n_size_pow2 *= 2;
unsigned n=0;
unsigned tmp = 1;
while ( tmp < n_size_pow2 ) {
n+=1;
tmp *= 2;
}
nc_assert(tmp==n_size_pow2);
m_w.clear();
m_w.reserve(n_size_pow2);
for( unsigned i = 0; i < n_size_pow2; ++i ) {
NC::PairDD res = NC::FastConvolve::calcPhase(i, n);
m_w.emplace_back(std::complex<double>(res.first,res.second));
}
}
void NC::FastConvolve::fftconv( const NC::VectD& a1, const NC::VectD& a2, NC::VectD& y, double dt )
{
const int minimum_out_size = a1.size() + a2.size() - 1;
std::vector<std::complex<double> > b1(a1.begin(),a1.end());
fftd(b1,FT_forward,minimum_out_size);
std::vector<std::complex<double> > b2(a2.begin(),a2.end());
fftd(b2,FT_forward,minimum_out_size);
nc_assert(b1.size()==b2.size());
std::vector<std::complex<double> >::iterator itb1(b1.begin()), itb1E(b1.end()), itb2(b2.begin());
while (itb1!=itb1E)
*itb1++ *= *itb2++;
fftd(b1,FT_inverse,minimum_out_size);
y.resize(minimum_out_size);
const double k = dt/b1.size();
nc_assert(b1.size()==b2.size());
nc_assert(y.size()<=b1.size());
VectD::iterator ity(y.begin()), ityE(y.end());
itb1 = b1.begin();
for(;ity!=ityE;++ity,++itb1) {
#ifdef NCRYSTAL_FASTCONVOLVE_EXTRASAFEMATH
//use std::abs which calls std::hypot behind the scenes (expensive but can avoid overflows)
*ity = k * std::abs(*itb1);
#else
//naive and simple, avoids std::hypot
double a(itb1->real());
double b(itb1->imag());
*ity = std::sqrt(a*a+b*b)*k;
#endif
}
}
void NC::FastConvolve::fftd( std::vector<std::complex< double> > &data, FastConvolve::caltype ct,
unsigned minimum_output_size )
{
double output_log_size_fp = std::ceil(std::log2(minimum_output_size));
nc_assert_always(output_log_size_fp<32);
const int output_log_size = output_log_size_fp;
const int output_size = ( 1 << output_log_size );//this is now minimum_output_size rounded up to next power of 2
const unsigned wTableSizeNeeded = std::max<unsigned>(output_size,data.size());
if ( m_w.size() < wTableSizeNeeded )
initWTable( wTableSizeNeeded );
nc_assert_always( data.size() <= (std::size_t)output_size );
if( data.size() != (size_t)output_size )
data.resize(output_size,std::complex<double>());
for(int j=1;j<output_size-1;++j)
{
int i=0;
for(int k=1,tmp=j; k<output_size; i=(i<<1)|(tmp&1),k<<=1,tmp>>=1)
{
}
if(j<i)
swap(data[i],data[j]);
}
const int jump = m_w.size()/output_size;
#ifndef NCRYSTAL_FASTCONVOLVE_EXTRASAFEMATH
const double convfact = (ct==FT_inverse?-1.0:1.0);
#endif
for(int i=0;i<output_log_size;++i){
int z=0;
const int i1 = (1<<i);
const int i1m1 = i1-1;
const int i2 = 1<<(output_log_size-i-1);
for(int j=0;j<output_size;++j){
if((j/i1)%2){
std::complex<double>& data_j = data[j];
std::complex<double>& data_sympos = data[j-i1];
#ifdef NCRYSTAL_FASTCONVOLVE_EXTRASAFEMATH
//std::complex<> multiplication is slow since it takes care of proper inf/nan/overflow
data_j *= (ct==inverse?std::conj(m_w[z*jump]):m_w[z*jump]);
//and the -=,+= operators seems to carry significant overhead for some reason:
std::complex<double> temp = data_sympos;
data_sympos += data_j;
temp -= data_j;
data_j = temp;
#else
//naive and simple is faster:
const std::complex<double>& w_zjump = m_w[z*jump];
const double a(data_j.real()), b(data_j.imag()), c(w_zjump.real()), d(convfact * w_zjump.imag());
const double jr(a*c-b*d);
const double ji(a*d+b*c);
const double sr(data_sympos.real());//no by-ref access to real/imag parts
const double si(data_sympos.imag());
data_j.real( sr - jr );
data_j.imag( si - ji );
data_sympos.real( sr + jr );
data_sympos.imag( si + ji );
#endif
z += i2;
} else {
z = 0;
//will be the same result for the next i1-1 loops, so skip ahead:
j += i1m1;
}
}
}
}
NC::PairDD NC::FastConvolve::calcPhase(unsigned k, unsigned n)
{
//Calculate exp(i*2*pi*k/n^2) where n must a nonzero number n=1,2,3,4,...
//and k must be a number in 0...n-1.
//
//NB: Using PairDD for (real,imag) parts, rather than std::complex<double> => for
//efficiency (we don't need the safety checks for obscure cases....
//
//Idea, use exp(a*b)=exp(a)*exp(b) and a small cache of
//exp(i2pi/2^N), N=0,1,2,. when k!=1, one can combine as in these examples:
//
// 13/32 = 1/32 + 12/32 = 1/32 + 3/8 = 1/32 + 1/8 + 1/4
//
// 17/32 = 1/32 + 1/2
//
// 11/32 = 1/32 + 5/16 = 1/32 + 1/16 + 1/4
//
//Trivial case:
if ( k == 0 )
return { 1.0, 0.0 };
//Eliminate common factors of 2 in fraction k/n^2:
while ( k%2==0 ) {
nc_assert( n>=1 );
n -= 1;
k /= 2;
}
if ( k == 1 ) {
//Fundamental form.
nc_assert(n>=1);//k>0, so it follows from k<=n-1 that n>1
//Cache high-precision numbers (from Python's mpmath module) (for
//efficiency, accuracy and reproducability):
static std::array<double, 20> cosvals = { -1.0, // cos(2pi/2^1)
0.0, // cos(2pi/2^2)
0.707106781186547524401, // cos(2pi/2^3)
0.923879532511286756128, // cos(2pi/2^4)
0.980785280403230449126, // cos(2pi/2^5)
0.995184726672196886245, // cos(2pi/2^6)
0.998795456205172392715, // cos(2pi/2^7)
0.999698818696204220116, // cos(2pi/2^8)
0.999924701839144540922, // cos(2pi/2^9)
0.999981175282601142657, // cos(2pi/2^10)
0.999995293809576171512, // cos(2pi/2^11)
0.999998823451701909929, // cos(2pi/2^12)
0.99999970586288221916, // cos(2pi/2^13)
0.999999926465717851145, // cos(2pi/2^14)
0.999999981616429293808, // cos(2pi/2^15)
0.999999995404107312891, // cos(2pi/2^16)
0.999999998851026827563, // cos(2pi/2^17)
0.999999999712756706849, // cos(2pi/2^18)
0.99999999992818917671, // cos(2pi/2^19)
0.999999999982047294177 }; // cos(2pi/2^20)
static std::array<double, 20> sinvals = { 0.0, // sin(2pi/2^1)
1.0, // sin(2pi/2^2)
0.707106781186547524401, // sin(2pi/2^3)
0.382683432365089771728, // sin(2pi/2^4)
0.195090322016128267848, // sin(2pi/2^5)
0.0980171403295606019942, // sin(2pi/2^6)
0.049067674327418014255, // sin(2pi/2^7)
0.0245412285229122880317, // sin(2pi/2^8)
0.0122715382857199260794, // sin(2pi/2^9)
0.00613588464915447535964, // sin(2pi/2^10)
0.00306795676296597627015, // sin(2pi/2^11)
0.0015339801862847656123, // sin(2pi/2^12)
0.000766990318742704526939, // sin(2pi/2^13)
0.000383495187571395589072, // sin(2pi/2^14)
0.00019174759731070330744, // sin(2pi/2^15)
0.0000958737990959773458705, // sin(2pi/2^16)
0.000047936899603066884549, // sin(2pi/2^17)
0.0000239684498084182187292, // sin(2pi/2^18)
0.0000119842249050697064215, // sin(2pi/2^19)
0.00000599211245264242784288 }; // sin(2pi/2^20)
double cosval = ( n < cosvals.size() ? cosvals.at(n-1) : std::cos(k2Pi / (double(n)*n)) );
double sinval = ( n < sinvals.size() ? sinvals.at(n-1) : std::sin(k2Pi / (double(n)*n)) );
return { cosval, sinval };
}
//Non-fundamental form, must combine results from several fundamental forms
//using multiplication of complex numbers.
nc_assert(k%2==1);//must be odd at this point
PairDD factor1 = calcPhase(1, n);
PairDD factor2 = calcPhase(k-1, n);
return { (factor1.first*factor2.first-factor1.second*factor2.second),
(factor1.first*factor2.second+factor1.second*factor2.first) };
}
| 43.66537 | 114 | 0.50205 | [
"vector"
] |
9f4d811a94be87583476a5e08679ff968d9a2efe | 53,714 | cpp | C++ | WebKit2-7606.2.104.1.1/WebKit2-7606.2.104.1.1/NetworkProcess/NetworkResourceLoader.cpp | mlcldh/appleWebKit2 | 39cc42a4710c9319c8da269621844493ab2ccdd6 | [
"MIT"
] | 1 | 2021-05-27T07:29:31.000Z | 2021-05-27T07:29:31.000Z | WebKit2-7606.2.104.1.1/WebKit2-7606.2.104.1.1/NetworkProcess/NetworkResourceLoader.cpp | mlcldh/appleWebKit2 | 39cc42a4710c9319c8da269621844493ab2ccdd6 | [
"MIT"
] | null | null | null | WebKit2-7606.2.104.1.1/WebKit2-7606.2.104.1.1/NetworkProcess/NetworkResourceLoader.cpp | mlcldh/appleWebKit2 | 39cc42a4710c9319c8da269621844493ab2ccdd6 | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2012-2018 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "NetworkResourceLoader.h"
#include "DataReference.h"
#include "FormDataReference.h"
#include "Logging.h"
#include "NetworkBlobRegistry.h"
#include "NetworkCache.h"
#include "NetworkConnectionToWebProcess.h"
#include "NetworkLoad.h"
#include "NetworkLoadChecker.h"
#include "NetworkProcess.h"
#include "NetworkProcessConnectionMessages.h"
#include "SessionTracker.h"
#include "WebCoreArgumentCoders.h"
#include "WebErrors.h"
#include "WebPageMessages.h"
#include "WebResourceLoaderMessages.h"
#include "WebsiteDataStoreParameters.h"
#include <JavaScriptCore/ConsoleTypes.h>
#include <WebCore/BlobDataFileReference.h>
#include <WebCore/CertificateInfo.h>
#include <WebCore/ContentSecurityPolicy.h>
#include <WebCore/DiagnosticLoggingKeys.h>
#include <WebCore/HTTPHeaderNames.h>
#include <WebCore/HTTPParsers.h>
#include <WebCore/NetworkLoadMetrics.h>
#include <WebCore/ProtectionSpace.h>
#include <WebCore/SameSiteInfo.h>
#include <WebCore/SecurityOrigin.h>
#include <WebCore/SharedBuffer.h>
#include <WebCore/SynchronousLoaderClient.h>
#include <wtf/RunLoop.h>
#if HAVE(CFNETWORK_STORAGE_PARTITIONING) && !RELEASE_LOG_DISABLED
#include <WebCore/NetworkStorageSession.h>
#include <WebCore/PlatformCookieJar.h>
#endif
#if USE(QUICK_LOOK)
#include <WebCore/PreviewLoader.h>
#endif
using namespace WebCore;
#define RELEASE_LOG_IF_ALLOWED(fmt, ...) RELEASE_LOG_IF(isAlwaysOnLoggingAllowed(), Network, "%p - NetworkResourceLoader::" fmt, this, ##__VA_ARGS__)
#define RELEASE_LOG_ERROR_IF_ALLOWED(fmt, ...) RELEASE_LOG_ERROR_IF(isAlwaysOnLoggingAllowed(), Network, "%p - NetworkResourceLoader::" fmt, this, ##__VA_ARGS__)
namespace WebKit {
struct NetworkResourceLoader::SynchronousLoadData {
SynchronousLoadData(Messages::NetworkConnectionToWebProcess::PerformSynchronousLoad::DelayedReply&& reply)
: delayedReply(WTFMove(reply))
{
ASSERT(delayedReply);
}
ResourceRequest currentRequest;
Messages::NetworkConnectionToWebProcess::PerformSynchronousLoad::DelayedReply delayedReply;
ResourceResponse response;
ResourceError error;
};
static void sendReplyToSynchronousRequest(NetworkResourceLoader::SynchronousLoadData& data, const SharedBuffer* buffer)
{
ASSERT(data.delayedReply);
ASSERT(!data.response.isNull() || !data.error.isNull());
Vector<char> responseBuffer;
if (buffer && buffer->size())
responseBuffer.append(buffer->data(), buffer->size());
data.delayedReply(data.error, data.response, responseBuffer);
data.delayedReply = nullptr;
}
NetworkResourceLoader::NetworkResourceLoader(NetworkResourceLoadParameters&& parameters, NetworkConnectionToWebProcess& connection, Messages::NetworkConnectionToWebProcess::PerformSynchronousLoad::DelayedReply&& synchronousReply)
: m_parameters { WTFMove(parameters) }
, m_connection { connection }
, m_defersLoading { parameters.defersLoading }
, m_isAllowedToAskUserForCredentials { m_parameters.clientCredentialPolicy == ClientCredentialPolicy::MayAskClientForCredentials }
, m_bufferingTimer { *this, &NetworkResourceLoader::bufferingTimerFired }
, m_cache { sessionID().isEphemeral() ? nullptr : NetworkProcess::singleton().cache() }
{
ASSERT(RunLoop::isMain());
// FIXME: This is necessary because of the existence of EmptyFrameLoaderClient in WebCore.
// Once bug 116233 is resolved, this ASSERT can just be "m_webPageID && m_webFrameID"
ASSERT((m_parameters.webPageID && m_parameters.webFrameID) || m_parameters.clientCredentialPolicy == ClientCredentialPolicy::CannotAskClientForCredentials);
if (originalRequest().httpBody()) {
for (const auto& element : originalRequest().httpBody()->elements()) {
if (element.m_type == FormDataElement::Type::EncodedBlob)
m_fileReferences.appendVector(NetworkBlobRegistry::singleton().filesInBlob(connection, element.m_url));
}
}
if (synchronousReply || parameters.shouldRestrictHTTPResponseAccess) {
m_networkLoadChecker = std::make_unique<NetworkLoadChecker>(FetchOptions { m_parameters.options }, m_parameters.sessionID, m_parameters.webPageID, m_parameters.webFrameID, HTTPHeaderMap { m_parameters.originalRequestHeaders }, URL { m_parameters.request.url() }, m_parameters.sourceOrigin.copyRef(), m_parameters.preflightPolicy, originalRequest().httpReferrer(), shouldCaptureExtraNetworkLoadMetrics());
if (m_parameters.cspResponseHeaders)
m_networkLoadChecker->setCSPResponseHeaders(ContentSecurityPolicyResponseHeaders { m_parameters.cspResponseHeaders.value() });
#if ENABLE(CONTENT_EXTENSIONS)
m_networkLoadChecker->setContentExtensionController(URL { m_parameters.mainDocumentURL }, m_parameters.userContentControllerIdentifier);
#endif
}
if (synchronousReply)
m_synchronousLoadData = std::make_unique<SynchronousLoadData>(WTFMove(synchronousReply));
}
NetworkResourceLoader::~NetworkResourceLoader()
{
ASSERT(RunLoop::isMain());
ASSERT(!m_networkLoad);
ASSERT(!isSynchronous() || !m_synchronousLoadData->delayedReply);
}
bool NetworkResourceLoader::canUseCache(const ResourceRequest& request) const
{
if (!m_cache)
return false;
ASSERT(!sessionID().isEphemeral());
if (!request.url().protocolIsInHTTPFamily())
return false;
if (originalRequest().cachePolicy() == WebCore::ResourceRequestCachePolicy::DoNotUseAnyCache)
return false;
return true;
}
bool NetworkResourceLoader::canUseCachedRedirect(const ResourceRequest& request) const
{
if (!canUseCache(request))
return false;
// Limit cached redirects to avoid cycles and other trouble.
// Networking layer follows over 30 redirects but caching that many seems unnecessary.
static const unsigned maximumCachedRedirectCount { 5 };
if (m_redirectCount > maximumCachedRedirectCount)
return false;
return true;
}
bool NetworkResourceLoader::isSynchronous() const
{
return !!m_synchronousLoadData;
}
void NetworkResourceLoader::start()
{
ASSERT(RunLoop::isMain());
m_networkActivityTracker = m_connection->startTrackingResourceLoad(m_parameters.webPageID, m_parameters.identifier, isMainResource(), sessionID());
if (m_defersLoading) {
RELEASE_LOG_IF_ALLOWED("start: Loading is deferred (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ", isMainResource = %d, isSynchronous = %d)", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier, isMainResource(), isSynchronous());
return;
}
ASSERT(!m_wasStarted);
m_wasStarted = true;
if (m_networkLoadChecker) {
m_networkLoadChecker->check(ResourceRequest { originalRequest() }, this, [this] (auto&& result) {
if (!result.has_value()) {
if (!result.error().isCancellation())
this->didFailLoading(result.error());
return;
}
if (this->canUseCache(this->originalRequest())) {
RELEASE_LOG_IF_ALLOWED("start: Checking cache for resource (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ", isMainResource = %d, isSynchronous = %d)", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier, this->isMainResource(), this->isSynchronous());
this->retrieveCacheEntry(this->originalRequest());
return;
}
this->startNetworkLoad(WTFMove(result.value()), FirstLoad::Yes);
});
return;
}
// FIXME: Remove that code path once m_networkLoadChecker is used for all network loads.
if (canUseCache(originalRequest())) {
RELEASE_LOG_IF_ALLOWED("start: Checking cache for resource (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ", isMainResource = %d, isSynchronous = %d)", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier, isMainResource(), isSynchronous());
retrieveCacheEntry(originalRequest());
return;
}
startNetworkLoad(ResourceRequest { originalRequest() }, FirstLoad::Yes);
}
void NetworkResourceLoader::retrieveCacheEntry(const ResourceRequest& request)
{
ASSERT(canUseCache(request));
RefPtr<NetworkResourceLoader> loader(this);
m_cache->retrieve(request, { m_parameters.webPageID, m_parameters.webFrameID }, [this, loader = WTFMove(loader), request = ResourceRequest { request }](auto entry, auto info) mutable {
if (loader->hasOneRef()) {
// The loader has been aborted and is only held alive by this lambda.
return;
}
loader->logSlowCacheRetrieveIfNeeded(info);
if (!entry) {
RELEASE_LOG_IF_ALLOWED("retrieveCacheEntry: Resource not in cache (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ", isMainResource = %d, isSynchronous = %d)", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier, isMainResource(), isSynchronous());
loader->startNetworkLoad(WTFMove(request), FirstLoad::Yes);
return;
}
if (entry->redirectRequest()) {
RELEASE_LOG_IF_ALLOWED("retrieveCacheEntry: Handling redirect (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ", isMainResource = %d, isSynchronous = %d)", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier, isMainResource(), isSynchronous());
loader->dispatchWillSendRequestForCacheEntry(WTFMove(request), WTFMove(entry));
return;
}
if (loader->m_parameters.needsCertificateInfo && !entry->response().certificateInfo()) {
RELEASE_LOG_IF_ALLOWED("retrieveCacheEntry: Resource does not have required certificate (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ", isMainResource = %d, isSynchronous = %d)", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier, isMainResource(), isSynchronous());
loader->startNetworkLoad(WTFMove(request), FirstLoad::Yes);
return;
}
if (entry->needsValidation() || request.cachePolicy() == WebCore::ResourceRequestCachePolicy::RefreshAnyCacheData) {
RELEASE_LOG_IF_ALLOWED("retrieveCacheEntry: Validating cache entry (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ", isMainResource = %d, isSynchronous = %d)", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier, isMainResource(), isSynchronous());
loader->validateCacheEntry(WTFMove(entry));
return;
}
RELEASE_LOG_IF_ALLOWED("retrieveCacheEntry: Retrieved resource from cache (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ", isMainResource = %d, isSynchronous = %d)", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier, isMainResource(), isSynchronous());
loader->didRetrieveCacheEntry(WTFMove(entry));
});
}
void NetworkResourceLoader::startNetworkLoad(ResourceRequest&& request, FirstLoad load)
{
if (load == FirstLoad::Yes) {
RELEASE_LOG_IF_ALLOWED("startNetworkLoad: (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ", isMainResource = %d, isSynchronous = %d)", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier, isMainResource(), isSynchronous());
consumeSandboxExtensions();
if (isSynchronous() || m_parameters.maximumBufferingTime > 0_s)
m_bufferedData = SharedBuffer::create();
if (canUseCache(request))
m_bufferedDataForCache = SharedBuffer::create();
}
NetworkLoadParameters parameters = m_parameters;
parameters.defersLoading = m_defersLoading;
parameters.networkActivityTracker = m_networkActivityTracker;
if (m_networkLoadChecker)
parameters.storedCredentialsPolicy = m_networkLoadChecker->storedCredentialsPolicy();
if (request.url().protocolIsBlob())
parameters.blobFileReferences = NetworkBlobRegistry::singleton().filesInBlob(m_connection, originalRequest().url());
auto* networkSession = SessionTracker::networkSession(parameters.sessionID);
if (!networkSession && parameters.sessionID.isEphemeral()) {
NetworkProcess::singleton().addWebsiteDataStore(WebsiteDataStoreParameters::privateSessionParameters(parameters.sessionID));
networkSession = SessionTracker::networkSession(parameters.sessionID);
}
if (!networkSession) {
WTFLogAlways("Attempted to create a NetworkLoad with a session (id=%" PRIu64 ") that does not exist.", parameters.sessionID.sessionID());
RELEASE_LOG_ERROR_IF_ALLOWED("startNetworkLoad: Attempted to create a NetworkLoad with a session that does not exist (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ", sessionID=%" PRIu64 ")", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier, parameters.sessionID.sessionID());
NetworkProcess::singleton().logDiagnosticMessage(m_parameters.webPageID, WebCore::DiagnosticLoggingKeys::internalErrorKey(), WebCore::DiagnosticLoggingKeys::invalidSessionIDKey(), WebCore::ShouldSample::No);
didFailLoading(internalError(request.url()));
return;
}
parameters.request = WTFMove(request);
m_networkLoad = std::make_unique<NetworkLoad>(*this, WTFMove(parameters), *networkSession);
RELEASE_LOG_IF_ALLOWED("startNetworkLoad: (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ", description = %{public}s)", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier, m_networkLoad->description().utf8().data());
if (m_defersLoading) {
RELEASE_LOG_IF_ALLOWED("startNetworkLoad: Created, but deferred (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ")",
m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier);
}
}
void NetworkResourceLoader::setDefersLoading(bool defers)
{
if (m_defersLoading == defers)
return;
m_defersLoading = defers;
if (defers)
RELEASE_LOG_IF_ALLOWED("setDefersLoading: Deferring resource load (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ")", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier);
else
RELEASE_LOG_IF_ALLOWED("setDefersLoading: Resuming deferred resource load (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ")", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier);
if (m_networkLoad) {
m_networkLoad->setDefersLoading(defers);
return;
}
if (!m_defersLoading && !m_wasStarted)
start();
else
RELEASE_LOG_IF_ALLOWED("setDefersLoading: defers = %d, but nothing to do (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ")", m_defersLoading, m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier);
}
void NetworkResourceLoader::cleanup(LoadResult result)
{
ASSERT(RunLoop::isMain());
m_connection->stopTrackingResourceLoad(m_parameters.identifier,
result == LoadResult::Success ? NetworkActivityTracker::CompletionCode::Success :
result == LoadResult::Failure ? NetworkActivityTracker::CompletionCode::Failure :
NetworkActivityTracker::CompletionCode::None);
m_bufferingTimer.stop();
invalidateSandboxExtensions();
m_networkLoad = nullptr;
// This will cause NetworkResourceLoader to be destroyed and therefore we do it last.
m_connection->didCleanupResourceLoader(*this);
}
void NetworkResourceLoader::convertToDownload(DownloadID downloadID, const ResourceRequest& request, const ResourceResponse& response)
{
ASSERT(m_networkLoad);
NetworkProcess::singleton().downloadManager().convertNetworkLoadToDownload(downloadID, std::exchange(m_networkLoad, nullptr), WTFMove(m_fileReferences), request, response);
}
void NetworkResourceLoader::abort()
{
ASSERT(RunLoop::isMain());
RELEASE_LOG_IF_ALLOWED("abort: Canceling resource load (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ")",
m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier);
if (m_networkLoad) {
if (canUseCache(m_networkLoad->currentRequest())) {
// We might already have used data from this incomplete load. Ensure older versions don't remain in the cache after cancel.
if (!m_response.isNull())
m_cache->remove(m_networkLoad->currentRequest());
}
m_networkLoad->cancel();
}
cleanup(LoadResult::Cancel);
}
bool NetworkResourceLoader::shouldInterruptLoadForXFrameOptions(const String& xFrameOptions, const URL& url)
{
if (isMainFrameLoad())
return false;
switch (parseXFrameOptionsHeader(xFrameOptions)) {
case XFrameOptionsNone:
case XFrameOptionsAllowAll:
return false;
case XFrameOptionsDeny:
return true;
case XFrameOptionsSameOrigin: {
auto origin = SecurityOrigin::create(url);
auto topFrameOrigin = m_parameters.frameAncestorOrigins.last();
if (!origin->isSameSchemeHostPort(*topFrameOrigin))
return true;
for (auto& ancestorOrigin : m_parameters.frameAncestorOrigins) {
if (!origin->isSameSchemeHostPort(*ancestorOrigin))
return true;
}
return false;
}
case XFrameOptionsConflict: {
String errorMessage = "Multiple 'X-Frame-Options' headers with conflicting values ('" + xFrameOptions + "') encountered when loading '" + url.stringCenterEllipsizedToLength() + "'. Falling back to 'DENY'.";
send(Messages::WebPage::AddConsoleMessage { m_parameters.webFrameID, MessageSource::JS, MessageLevel::Error, errorMessage, identifier() }, m_parameters.webPageID);
return true;
}
case XFrameOptionsInvalid: {
String errorMessage = "Invalid 'X-Frame-Options' header encountered when loading '" + url.stringCenterEllipsizedToLength() + "': '" + xFrameOptions + "' is not a recognized directive. The header will be ignored.";
send(Messages::WebPage::AddConsoleMessage { m_parameters.webFrameID, MessageSource::JS, MessageLevel::Error, errorMessage, identifier() }, m_parameters.webPageID);
return false;
}
}
ASSERT_NOT_REACHED();
return false;
}
bool NetworkResourceLoader::shouldInterruptLoadForCSPFrameAncestorsOrXFrameOptions(const ResourceResponse& response)
{
ASSERT(isMainResource());
#if USE(QUICK_LOOK)
if (PreviewLoader::shouldCreateForMIMEType(response.mimeType()))
return false;
#endif
auto url = response.url();
ContentSecurityPolicy contentSecurityPolicy { URL { url }, this };
contentSecurityPolicy.didReceiveHeaders(ContentSecurityPolicyResponseHeaders { response }, originalRequest().httpReferrer());
if (!contentSecurityPolicy.allowFrameAncestors(m_parameters.frameAncestorOrigins, url))
return true;
String xFrameOptions = m_response.httpHeaderField(HTTPHeaderName::XFrameOptions);
if (!xFrameOptions.isNull() && shouldInterruptLoadForXFrameOptions(xFrameOptions, response.url())) {
String errorMessage = "Refused to display '" + response.url().stringCenterEllipsizedToLength() + "' in a frame because it set 'X-Frame-Options' to '" + xFrameOptions + "'.";
send(Messages::WebPage::AddConsoleMessage { m_parameters.webFrameID, MessageSource::Security, MessageLevel::Error, errorMessage, identifier() }, m_parameters.webPageID);
return true;
}
return false;
}
auto NetworkResourceLoader::didReceiveResponse(ResourceResponse&& receivedResponse) -> ShouldContinueDidReceiveResponse
{
RELEASE_LOG_IF_ALLOWED("didReceiveResponse: (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ", httpStatusCode = %d, length = %" PRId64 ")", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier, receivedResponse.httpStatusCode(), receivedResponse.expectedContentLength());
m_response = WTFMove(receivedResponse);
if (shouldCaptureExtraNetworkLoadMetrics() && m_networkLoadChecker) {
auto information = m_networkLoadChecker->takeNetworkLoadInformation();
information.response = m_response;
m_connection->addNetworkLoadInformation(identifier(), WTFMove(information));
}
// For multipart/x-mixed-replace didReceiveResponseAsync gets called multiple times and buffering would require special handling.
if (!isSynchronous() && m_response.isMultipart())
m_bufferedData = nullptr;
if (m_response.isMultipart())
m_bufferedDataForCache = nullptr;
if (m_cacheEntryForValidation) {
bool validationSucceeded = m_response.httpStatusCode() == 304; // 304 Not Modified
if (validationSucceeded) {
m_cacheEntryForValidation = m_cache->update(originalRequest(), { m_parameters.webPageID, m_parameters.webFrameID }, *m_cacheEntryForValidation, m_response);
// If the request was conditional then this revalidation was not triggered by the network cache and we pass the 304 response to WebCore.
if (originalRequest().isConditional())
m_cacheEntryForValidation = nullptr;
} else
m_cacheEntryForValidation = nullptr;
}
if (m_cacheEntryForValidation)
return ShouldContinueDidReceiveResponse::Yes;
if (isMainResource() && shouldInterruptLoadForCSPFrameAncestorsOrXFrameOptions(m_response)) {
send(Messages::WebResourceLoader::StopLoadingAfterXFrameOptionsOrContentSecurityPolicyDenied { });
return ShouldContinueDidReceiveResponse::No;
}
if (m_networkLoadChecker) {
auto error = m_networkLoadChecker->validateResponse(m_response);
if (!error.isNull()) {
RunLoop::main().dispatch([protectedThis = makeRef(*this), error = WTFMove(error)] {
if (protectedThis->m_networkLoad)
protectedThis->didFailLoading(error);
});
return ShouldContinueDidReceiveResponse::No;
}
}
auto response = sanitizeResponseIfPossible(ResourceResponse { m_response }, ResourceResponse::SanitizationType::CrossOriginSafe);
if (isSynchronous()) {
m_synchronousLoadData->response = WTFMove(response);
return ShouldContinueDidReceiveResponse::Yes;
}
// We wait to receive message NetworkResourceLoader::ContinueDidReceiveResponse before continuing a load for
// a main resource because the embedding client must decide whether to allow the load.
bool willWaitForContinueDidReceiveResponse = isMainResource();
send(Messages::WebResourceLoader::DidReceiveResponse { response, willWaitForContinueDidReceiveResponse });
return willWaitForContinueDidReceiveResponse ? ShouldContinueDidReceiveResponse::No : ShouldContinueDidReceiveResponse::Yes;
}
void NetworkResourceLoader::didReceiveBuffer(Ref<SharedBuffer>&& buffer, int reportedEncodedDataLength)
{
if (!m_numBytesReceived) {
RELEASE_LOG_IF_ALLOWED("didReceiveBuffer: Started receiving data (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ")", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier);
}
m_numBytesReceived += buffer->size();
ASSERT(!m_cacheEntryForValidation);
if (m_bufferedDataForCache) {
// Prevent memory growth in case of streaming data.
const size_t maximumCacheBufferSize = 10 * 1024 * 1024;
if (m_bufferedDataForCache->size() + buffer->size() <= maximumCacheBufferSize)
m_bufferedDataForCache->append(buffer.get());
else
m_bufferedDataForCache = nullptr;
}
// FIXME: At least on OS X Yosemite we always get -1 from the resource handle.
unsigned encodedDataLength = reportedEncodedDataLength >= 0 ? reportedEncodedDataLength : buffer->size();
m_bytesReceived += buffer->size();
if (m_bufferedData) {
m_bufferedData->append(buffer.get());
m_bufferedDataEncodedDataLength += encodedDataLength;
startBufferingTimerIfNeeded();
return;
}
sendBuffer(buffer, encodedDataLength);
}
void NetworkResourceLoader::didFinishLoading(const NetworkLoadMetrics& networkLoadMetrics)
{
RELEASE_LOG_IF_ALLOWED("didFinishLoading: (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ", length = %zd)", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier, m_numBytesReceived);
if (shouldCaptureExtraNetworkLoadMetrics())
m_connection->addNetworkLoadInformationMetrics(identifier(), networkLoadMetrics);
if (m_cacheEntryForValidation) {
// 304 Not Modified
ASSERT(m_response.httpStatusCode() == 304);
LOG(NetworkCache, "(NetworkProcess) revalidated");
didRetrieveCacheEntry(WTFMove(m_cacheEntryForValidation));
return;
}
#if HAVE(CFNETWORK_STORAGE_PARTITIONING) && !RELEASE_LOG_DISABLED
if (shouldLogCookieInformation())
logCookieInformation();
#endif
if (isSynchronous())
sendReplyToSynchronousRequest(*m_synchronousLoadData, m_bufferedData.get());
else {
if (m_bufferedData && !m_bufferedData->isEmpty()) {
// FIXME: Pass a real value or remove the encoded data size feature.
sendBuffer(*m_bufferedData, -1);
}
send(Messages::WebResourceLoader::DidFinishResourceLoad(networkLoadMetrics));
}
tryStoreAsCacheEntry();
cleanup(LoadResult::Success);
}
void NetworkResourceLoader::didFailLoading(const ResourceError& error)
{
RELEASE_LOG_IF_ALLOWED("didFailLoading: (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ", isTimeout = %d, isCancellation = %d, isAccessControl = %d, errCode = %d)", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier, error.isTimeout(), error.isCancellation(), error.isAccessControl(), error.errorCode());
if (shouldCaptureExtraNetworkLoadMetrics())
m_connection->removeNetworkLoadInformation(identifier());
ASSERT(!error.isNull());
m_cacheEntryForValidation = nullptr;
if (isSynchronous()) {
m_synchronousLoadData->error = error;
sendReplyToSynchronousRequest(*m_synchronousLoadData, nullptr);
} else if (auto* connection = messageSenderConnection())
connection->send(Messages::WebResourceLoader::DidFailResourceLoad(error), messageSenderDestinationID());
cleanup(LoadResult::Failure);
}
void NetworkResourceLoader::didBlockAuthenticationChallenge()
{
send(Messages::WebResourceLoader::DidBlockAuthenticationChallenge());
}
void NetworkResourceLoader::willSendRedirectedRequest(ResourceRequest&& request, ResourceRequest&& redirectRequest, ResourceResponse&& redirectResponse)
{
++m_redirectCount;
if (redirectResponse.source() == ResourceResponse::Source::Network && canUseCachedRedirect(request))
m_cache->storeRedirect(request, redirectResponse, redirectRequest);
if (m_networkLoadChecker) {
m_networkLoadChecker->storeRedirectionIfNeeded(request, redirectResponse);
m_networkLoadChecker->checkRedirection(WTFMove(request), WTFMove(redirectRequest), WTFMove(redirectResponse), this, [protectedThis = makeRef(*this), this, storedCredentialsPolicy = m_networkLoadChecker->storedCredentialsPolicy()](auto&& result) mutable {
if (!result.has_value()) {
if (result.error().isCancellation())
return;
this->didFailLoading(result.error());
return;
}
if (m_parameters.options.redirect == FetchOptions::Redirect::Manual) {
this->didFinishWithRedirectResponse(WTFMove(result->redirectResponse));
return;
}
if (this->isSynchronous()) {
if (storedCredentialsPolicy != m_networkLoadChecker->storedCredentialsPolicy()) {
// We need to restart the load to update the session according the new credential policy.
this->restartNetworkLoad(WTFMove(result->redirectRequest));
return;
}
// We do not support prompting for credentials for synchronous loads. If we ever change this policy then
// we need to take care to prompt if and only if request and redirectRequest are not mixed content.
this->continueWillSendRequest(WTFMove(result->redirectRequest), false);
return;
}
m_shouldRestartLoad = storedCredentialsPolicy != m_networkLoadChecker->storedCredentialsPolicy();
this->continueWillSendRedirectedRequest(WTFMove(result->request), WTFMove(result->redirectRequest), WTFMove(result->redirectResponse));
});
return;
}
continueWillSendRedirectedRequest(WTFMove(request), WTFMove(redirectRequest), WTFMove(redirectResponse));
}
void NetworkResourceLoader::continueWillSendRedirectedRequest(ResourceRequest&& request, ResourceRequest&& redirectRequest, ResourceResponse&& redirectResponse)
{
ASSERT(!isSynchronous());
send(Messages::WebResourceLoader::WillSendRequest(redirectRequest, sanitizeResponseIfPossible(WTFMove(redirectResponse), ResourceResponse::SanitizationType::Redirection)));
}
void NetworkResourceLoader::didFinishWithRedirectResponse(ResourceResponse&& redirectResponse)
{
redirectResponse.setType(ResourceResponse::Type::Opaqueredirect);
didReceiveResponse(WTFMove(redirectResponse));
WebCore::NetworkLoadMetrics networkLoadMetrics;
networkLoadMetrics.markComplete();
networkLoadMetrics.responseBodyBytesReceived = 0;
networkLoadMetrics.responseBodyDecodedSize = 0;
send(Messages::WebResourceLoader::DidFinishResourceLoad { networkLoadMetrics });
cleanup(LoadResult::Success);
}
ResourceResponse NetworkResourceLoader::sanitizeResponseIfPossible(ResourceResponse&& response, ResourceResponse::SanitizationType type)
{
if (m_parameters.shouldRestrictHTTPResponseAccess)
response.sanitizeHTTPHeaderFields(type);
return WTFMove(response);
}
void NetworkResourceLoader::restartNetworkLoad(WebCore::ResourceRequest&& newRequest)
{
if (m_networkLoad)
m_networkLoad->cancel();
if (m_networkLoadChecker)
m_networkLoadChecker->prepareRedirectedRequest(newRequest);
startNetworkLoad(WTFMove(newRequest), FirstLoad::No);
}
void NetworkResourceLoader::continueWillSendRequest(ResourceRequest&& newRequest, bool isAllowedToAskUserForCredentials)
{
if (m_shouldRestartLoad) {
m_shouldRestartLoad = false;
restartNetworkLoad(WTFMove(newRequest));
return;
}
if (m_networkLoadChecker) {
// FIXME: We should be doing this check when receiving the redirection and not allow about protocol as per fetch spec.
if (!newRequest.url().protocolIsInHTTPFamily() && !newRequest.url().isBlankURL() && m_redirectCount) {
didFailLoading(ResourceError { String { }, 0, newRequest.url(), "Redirection to URL with a scheme that is not HTTP(S)"_s, ResourceError::Type::AccessControl });
return;
}
}
RELEASE_LOG_IF_ALLOWED("continueWillSendRequest: (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ")", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier);
if (m_networkLoadChecker)
m_networkLoadChecker->prepareRedirectedRequest(newRequest);
m_isAllowedToAskUserForCredentials = isAllowedToAskUserForCredentials;
// If there is a match in the network cache, we need to reuse the original cache policy and partition.
newRequest.setCachePolicy(originalRequest().cachePolicy());
newRequest.setCachePartition(originalRequest().cachePartition());
if (m_isWaitingContinueWillSendRequestForCachedRedirect) {
m_isWaitingContinueWillSendRequestForCachedRedirect = false;
LOG(NetworkCache, "(NetworkProcess) Retrieving cached redirect");
if (canUseCachedRedirect(newRequest))
retrieveCacheEntry(newRequest);
else
startNetworkLoad(WTFMove(newRequest), FirstLoad::Yes);
return;
}
if (m_networkLoad)
m_networkLoad->continueWillSendRequest(WTFMove(newRequest));
}
void NetworkResourceLoader::continueDidReceiveResponse()
{
if (m_cacheEntryWaitingForContinueDidReceiveResponse) {
continueProcessingCachedEntryAfterDidReceiveResponse(WTFMove(m_cacheEntryWaitingForContinueDidReceiveResponse));
return;
}
// FIXME: Remove this check once BlobResourceHandle implements didReceiveResponseAsync correctly.
// Currently, it does not wait for response, so the load is likely to finish before continueDidReceiveResponse.
if (m_networkLoad)
m_networkLoad->continueDidReceiveResponse();
}
void NetworkResourceLoader::didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
{
if (!isSynchronous())
send(Messages::WebResourceLoader::DidSendData(bytesSent, totalBytesToBeSent));
}
void NetworkResourceLoader::startBufferingTimerIfNeeded()
{
if (isSynchronous())
return;
if (m_bufferingTimer.isActive())
return;
m_bufferingTimer.startOneShot(m_parameters.maximumBufferingTime);
}
void NetworkResourceLoader::bufferingTimerFired()
{
ASSERT(m_bufferedData);
ASSERT(m_networkLoad);
if (m_bufferedData->isEmpty())
return;
IPC::SharedBufferDataReference dataReference(m_bufferedData.get());
size_t encodedLength = m_bufferedDataEncodedDataLength;
m_bufferedData = SharedBuffer::create();
m_bufferedDataEncodedDataLength = 0;
send(Messages::WebResourceLoader::DidReceiveData(dataReference, encodedLength));
}
void NetworkResourceLoader::sendBuffer(SharedBuffer& buffer, size_t encodedDataLength)
{
ASSERT(!isSynchronous());
IPC::SharedBufferDataReference dataReference(&buffer);
send(Messages::WebResourceLoader::DidReceiveData(dataReference, encodedDataLength));
}
void NetworkResourceLoader::tryStoreAsCacheEntry()
{
if (!canUseCache(m_networkLoad->currentRequest()))
return;
if (!m_bufferedDataForCache)
return;
m_cache->store(m_networkLoad->currentRequest(), m_response, WTFMove(m_bufferedDataForCache), [loader = makeRef(*this)](auto& mappedBody) mutable {
#if ENABLE(SHAREABLE_RESOURCE)
if (mappedBody.shareableResourceHandle.isNull())
return;
LOG(NetworkCache, "(NetworkProcess) sending DidCacheResource");
loader->send(Messages::NetworkProcessConnection::DidCacheResource(loader->originalRequest(), mappedBody.shareableResourceHandle, loader->sessionID()));
#endif
});
}
void NetworkResourceLoader::didRetrieveCacheEntry(std::unique_ptr<NetworkCache::Entry> entry)
{
auto response = entry->response();
if (isMainResource() && shouldInterruptLoadForCSPFrameAncestorsOrXFrameOptions(response)) {
send(Messages::WebResourceLoader::StopLoadingAfterXFrameOptionsOrContentSecurityPolicyDenied { });
return;
}
if (m_networkLoadChecker) {
auto error = m_networkLoadChecker->validateResponse(response);
if (!error.isNull()) {
didFailLoading(error);
return;
}
}
response = sanitizeResponseIfPossible(WTFMove(response), ResourceResponse::SanitizationType::CrossOriginSafe);
if (isSynchronous()) {
m_synchronousLoadData->response = WTFMove(response);
sendReplyToSynchronousRequest(*m_synchronousLoadData, entry->buffer());
cleanup(LoadResult::Success);
return;
}
bool needsContinueDidReceiveResponseMessage = isMainResource();
send(Messages::WebResourceLoader::DidReceiveResponse { response, needsContinueDidReceiveResponseMessage });
if (needsContinueDidReceiveResponseMessage)
m_cacheEntryWaitingForContinueDidReceiveResponse = WTFMove(entry);
else
continueProcessingCachedEntryAfterDidReceiveResponse(WTFMove(entry));
}
void NetworkResourceLoader::continueProcessingCachedEntryAfterDidReceiveResponse(std::unique_ptr<NetworkCache::Entry> entry)
{
if (entry->sourceStorageRecord().bodyHash && !m_parameters.derivedCachedDataTypesToRetrieve.isEmpty()) {
auto bodyHash = *entry->sourceStorageRecord().bodyHash;
auto* entryPtr = entry.release();
auto retrieveCount = m_parameters.derivedCachedDataTypesToRetrieve.size();
for (auto& type : m_parameters.derivedCachedDataTypesToRetrieve) {
NetworkCache::DataKey key { originalRequest().cachePartition(), type, bodyHash };
m_cache->retrieveData(key, [loader = makeRef(*this), entryPtr, type, retrieveCount] (const uint8_t* data, size_t size) mutable {
loader->m_retrievedDerivedDataCount++;
bool retrievedAll = loader->m_retrievedDerivedDataCount == retrieveCount;
std::unique_ptr<NetworkCache::Entry> entry(retrievedAll ? entryPtr : nullptr);
if (loader->hasOneRef())
return;
if (data) {
IPC::DataReference dataReference(data, size);
loader->send(Messages::WebResourceLoader::DidRetrieveDerivedData(type, dataReference));
}
if (retrievedAll) {
loader->sendResultForCacheEntry(WTFMove(entry));
loader->cleanup(LoadResult::Success);
}
});
}
return;
}
sendResultForCacheEntry(WTFMove(entry));
cleanup(LoadResult::Success);
}
void NetworkResourceLoader::sendResultForCacheEntry(std::unique_ptr<NetworkCache::Entry> entry)
{
#if ENABLE(SHAREABLE_RESOURCE)
if (!entry->shareableResourceHandle().isNull()) {
send(Messages::WebResourceLoader::DidReceiveResource(entry->shareableResourceHandle()));
return;
}
#endif
#if HAVE(CFNETWORK_STORAGE_PARTITIONING) && !RELEASE_LOG_DISABLED
if (shouldLogCookieInformation())
logCookieInformation();
#endif
WebCore::NetworkLoadMetrics networkLoadMetrics;
networkLoadMetrics.markComplete();
networkLoadMetrics.requestHeaderBytesSent = 0;
networkLoadMetrics.requestBodyBytesSent = 0;
networkLoadMetrics.responseHeaderBytesReceived = 0;
networkLoadMetrics.responseBodyBytesReceived = 0;
networkLoadMetrics.responseBodyDecodedSize = 0;
sendBuffer(*entry->buffer(), entry->buffer()->size());
send(Messages::WebResourceLoader::DidFinishResourceLoad(networkLoadMetrics));
}
void NetworkResourceLoader::validateCacheEntry(std::unique_ptr<NetworkCache::Entry> entry)
{
ASSERT(!m_networkLoad);
// If the request is already conditional then the revalidation was not triggered by the disk cache
// and we should not overwrite the existing conditional headers.
ResourceRequest revalidationRequest = originalRequest();
if (!revalidationRequest.isConditional()) {
String eTag = entry->response().httpHeaderField(HTTPHeaderName::ETag);
String lastModified = entry->response().httpHeaderField(HTTPHeaderName::LastModified);
if (!eTag.isEmpty())
revalidationRequest.setHTTPHeaderField(HTTPHeaderName::IfNoneMatch, eTag);
if (!lastModified.isEmpty())
revalidationRequest.setHTTPHeaderField(HTTPHeaderName::IfModifiedSince, lastModified);
}
m_cacheEntryForValidation = WTFMove(entry);
startNetworkLoad(WTFMove(revalidationRequest), FirstLoad::Yes);
}
void NetworkResourceLoader::dispatchWillSendRequestForCacheEntry(ResourceRequest&& request, std::unique_ptr<NetworkCache::Entry>&& entry)
{
ASSERT(entry->redirectRequest());
ASSERT(!m_isWaitingContinueWillSendRequestForCachedRedirect);
LOG(NetworkCache, "(NetworkProcess) Executing cached redirect");
m_isWaitingContinueWillSendRequestForCachedRedirect = true;
willSendRedirectedRequest(WTFMove(request), ResourceRequest { *entry->redirectRequest() }, ResourceResponse { entry->response() });
}
IPC::Connection* NetworkResourceLoader::messageSenderConnection()
{
return &connectionToWebProcess().connection();
}
void NetworkResourceLoader::consumeSandboxExtensions()
{
ASSERT(!m_didConsumeSandboxExtensions);
for (auto& extension : m_parameters.requestBodySandboxExtensions)
extension->consume();
if (auto& extension = m_parameters.resourceSandboxExtension)
extension->consume();
for (auto& fileReference : m_fileReferences)
fileReference->prepareForFileAccess();
m_didConsumeSandboxExtensions = true;
}
void NetworkResourceLoader::invalidateSandboxExtensions()
{
if (m_didConsumeSandboxExtensions) {
for (auto& extension : m_parameters.requestBodySandboxExtensions)
extension->revoke();
if (auto& extension = m_parameters.resourceSandboxExtension)
extension->revoke();
for (auto& fileReference : m_fileReferences)
fileReference->revokeFileAccess();
m_didConsumeSandboxExtensions = false;
}
m_fileReferences.clear();
}
#if USE(PROTECTION_SPACE_AUTH_CALLBACK)
void NetworkResourceLoader::canAuthenticateAgainstProtectionSpaceAsync(const ProtectionSpace& protectionSpace)
{
NetworkProcess::singleton().canAuthenticateAgainstProtectionSpace(protectionSpace, pageID(), frameID(), [this, protectedThis = makeRef(*this)] (bool result) {
if (m_networkLoad)
m_networkLoad->continueCanAuthenticateAgainstProtectionSpace(result);
});
}
#endif
bool NetworkResourceLoader::isAlwaysOnLoggingAllowed() const
{
if (NetworkProcess::singleton().sessionIsControlledByAutomation(sessionID()))
return true;
return sessionID().isAlwaysOnLoggingAllowed();
}
bool NetworkResourceLoader::shouldCaptureExtraNetworkLoadMetrics() const
{
return m_connection->captureExtraNetworkLoadMetricsEnabled();
}
#if HAVE(CFNETWORK_STORAGE_PARTITIONING) && !RELEASE_LOG_DISABLED
bool NetworkResourceLoader::shouldLogCookieInformation()
{
return NetworkProcess::singleton().shouldLogCookieInformation();
}
static String escapeForJSON(String s)
{
return s.replace('\\', "\\\\").replace('"', "\\\"");
}
static String escapeIDForJSON(const std::optional<uint64_t>& value)
{
return value ? String::number(value.value()) : String("None");
};
void NetworkResourceLoader::logCookieInformation() const
{
ASSERT(shouldLogCookieInformation());
auto networkStorageSession = WebCore::NetworkStorageSession::storageSession(sessionID());
ASSERT(networkStorageSession);
logCookieInformation("NetworkResourceLoader", reinterpret_cast<const void*>(this), *networkStorageSession, originalRequest().firstPartyForCookies(), SameSiteInfo::create(originalRequest()), originalRequest().url(), originalRequest().httpReferrer(), frameID(), pageID(), identifier());
}
static void logBlockedCookieInformation(const String& label, const void* loggedObject, const WebCore::NetworkStorageSession& networkStorageSession, const WebCore::URL& firstParty, const SameSiteInfo& sameSiteInfo, const WebCore::URL& url, const String& referrer, std::optional<uint64_t> frameID, std::optional<uint64_t> pageID, std::optional<uint64_t> identifier)
{
ASSERT(NetworkResourceLoader::shouldLogCookieInformation());
auto escapedURL = escapeForJSON(url.string());
auto escapedFirstParty = escapeForJSON(firstParty.string());
auto escapedFrameID = escapeIDForJSON(frameID);
auto escapedPageID = escapeIDForJSON(pageID);
auto escapedIdentifier = escapeIDForJSON(identifier);
auto escapedReferrer = escapeForJSON(referrer);
#define LOCAL_LOG_IF_ALLOWED(fmt, ...) RELEASE_LOG_IF(networkStorageSession.sessionID().isAlwaysOnLoggingAllowed(), Network, "%p - %s::" fmt, loggedObject, label.utf8().data(), ##__VA_ARGS__)
#define LOCAL_LOG(str, ...) \
LOCAL_LOG_IF_ALLOWED("logCookieInformation: BLOCKED cookie access for pageID = %s, frameID = %s, resourceID = %s, firstParty = %s: " str, escapedPageID.utf8().data(), escapedFrameID.utf8().data(), escapedIdentifier.utf8().data(), escapedFirstParty.utf8().data(), ##__VA_ARGS__)
LOCAL_LOG(R"({ "url": "%{public}s",)", escapedURL.utf8().data());
LOCAL_LOG(R"( "partition": "%{public}s",)", "BLOCKED");
LOCAL_LOG(R"( "hasStorageAccess": %{public}s,)", "false");
LOCAL_LOG(R"( "referer": "%{public}s",)", escapedReferrer.utf8().data());
LOCAL_LOG(R"( "isSameSite": "%{public}s",)", sameSiteInfo.isSameSite ? "true" : "false");
LOCAL_LOG(R"( "isTopSite": "%{public}s",)", sameSiteInfo.isTopSite ? "true" : "false");
LOCAL_LOG(R"( "cookies": [])");
LOCAL_LOG(R"( })");
#undef LOCAL_LOG
#undef LOCAL_LOG_IF_ALLOWED
}
static void logCookieInformationInternal(const String& label, const void* loggedObject, const WebCore::NetworkStorageSession& networkStorageSession, const WebCore::URL& partition, const WebCore::SameSiteInfo& sameSiteInfo, const WebCore::URL& url, const String& referrer, std::optional<uint64_t> frameID, std::optional<uint64_t> pageID, std::optional<uint64_t> identifier)
{
ASSERT(NetworkResourceLoader::shouldLogCookieInformation());
Vector<WebCore::Cookie> cookies;
if (!WebCore::getRawCookies(networkStorageSession, partition, sameSiteInfo, url, frameID, pageID, cookies))
return;
auto escapedURL = escapeForJSON(url.string());
auto escapedPartition = escapeForJSON(partition.string());
auto escapedReferrer = escapeForJSON(referrer);
auto escapedFrameID = escapeIDForJSON(frameID);
auto escapedPageID = escapeIDForJSON(pageID);
auto escapedIdentifier = escapeIDForJSON(identifier);
bool hasStorageAccess = (frameID && pageID) ? networkStorageSession.hasStorageAccess(url.string(), partition.string(), frameID.value(), pageID.value()) : false;
#define LOCAL_LOG_IF_ALLOWED(fmt, ...) RELEASE_LOG_IF(networkStorageSession.sessionID().isAlwaysOnLoggingAllowed(), Network, "%p - %s::" fmt, loggedObject, label.utf8().data(), ##__VA_ARGS__)
#define LOCAL_LOG(str, ...) \
LOCAL_LOG_IF_ALLOWED("logCookieInformation: pageID = %s, frameID = %s, resourceID = %s: " str, escapedPageID.utf8().data(), escapedFrameID.utf8().data(), escapedIdentifier.utf8().data(), ##__VA_ARGS__)
LOCAL_LOG(R"({ "url": "%{public}s",)", escapedURL.utf8().data());
LOCAL_LOG(R"( "partition": "%{public}s",)", escapedPartition.utf8().data());
LOCAL_LOG(R"( "hasStorageAccess": %{public}s,)", hasStorageAccess ? "true" : "false");
LOCAL_LOG(R"( "referer": "%{public}s",)", escapedReferrer.utf8().data());
LOCAL_LOG(R"( "isSameSite": "%{public}s",)", sameSiteInfo.isSameSite ? "true" : "false");
LOCAL_LOG(R"( "isTopSite": "%{public}s",)", sameSiteInfo.isTopSite ? "true" : "false");
LOCAL_LOG(R"( "cookies": [)");
auto size = cookies.size();
decltype(size) count = 0;
for (const auto& cookie : cookies) {
const char* trailingComma = ",";
if (++count == size)
trailingComma = "";
auto escapedName = escapeForJSON(cookie.name);
auto escapedValue = escapeForJSON(cookie.value);
auto escapedDomain = escapeForJSON(cookie.domain);
auto escapedPath = escapeForJSON(cookie.path);
auto escapedComment = escapeForJSON(cookie.comment);
auto escapedCommentURL = escapeForJSON(cookie.commentURL.string());
// FIXME: Log Same-Site policy for each cookie. See <https://bugs.webkit.org/show_bug.cgi?id=184894>.
LOCAL_LOG(R"( { "name": "%{public}s",)", escapedName.utf8().data());
LOCAL_LOG(R"( "value": "%{public}s",)", escapedValue.utf8().data());
LOCAL_LOG(R"( "domain": "%{public}s",)", escapedDomain.utf8().data());
LOCAL_LOG(R"( "path": "%{public}s",)", escapedPath.utf8().data());
LOCAL_LOG(R"( "created": %f,)", cookie.created);
LOCAL_LOG(R"( "expires": %f,)", cookie.expires);
LOCAL_LOG(R"( "httpOnly": %{public}s,)", cookie.httpOnly ? "true" : "false");
LOCAL_LOG(R"( "secure": %{public}s,)", cookie.secure ? "true" : "false");
LOCAL_LOG(R"( "session": %{public}s,)", cookie.session ? "true" : "false");
LOCAL_LOG(R"( "comment": "%{public}s",)", escapedComment.utf8().data());
LOCAL_LOG(R"( "commentURL": "%{public}s")", escapedCommentURL.utf8().data());
LOCAL_LOG(R"( }%{public}s)", trailingComma);
}
LOCAL_LOG(R"(]})");
#undef LOCAL_LOG
#undef LOCAL_LOG_IF_ALLOWED
}
void NetworkResourceLoader::logCookieInformation(const String& label, const void* loggedObject, const NetworkStorageSession& networkStorageSession, const URL& firstParty, const SameSiteInfo& sameSiteInfo, const URL& url, const String& referrer, std::optional<uint64_t> frameID, std::optional<uint64_t> pageID, std::optional<uint64_t> identifier)
{
ASSERT(shouldLogCookieInformation());
if (networkStorageSession.shouldBlockCookies(firstParty, url))
logBlockedCookieInformation(label, loggedObject, networkStorageSession, firstParty, sameSiteInfo, url, referrer, frameID, pageID, identifier);
else {
auto partition = URL(ParsedURLString, networkStorageSession.cookieStoragePartition(firstParty, url, frameID, pageID));
logCookieInformationInternal(label, loggedObject, networkStorageSession, partition, sameSiteInfo, url, referrer, frameID, pageID, identifier);
}
}
#endif
void NetworkResourceLoader::addConsoleMessage(MessageSource messageSource, MessageLevel messageLevel, const String& message, unsigned long)
{
send(Messages::WebPage::AddConsoleMessage { m_parameters.webFrameID, messageSource, messageLevel, message, identifier() }, m_parameters.webPageID);
}
void NetworkResourceLoader::sendCSPViolationReport(URL&& reportURL, Ref<FormData>&& report)
{
send(Messages::WebPage::SendCSPViolationReport { m_parameters.webFrameID, WTFMove(reportURL), IPC::FormDataReference { WTFMove(report) } }, m_parameters.webPageID);
}
void NetworkResourceLoader::enqueueSecurityPolicyViolationEvent(WebCore::SecurityPolicyViolationEvent::Init&& eventInit)
{
send(Messages::WebPage::EnqueueSecurityPolicyViolationEvent { m_parameters.webFrameID, WTFMove(eventInit) }, m_parameters.webPageID);
}
void NetworkResourceLoader::logSlowCacheRetrieveIfNeeded(const NetworkCache::Cache::RetrieveInfo& info)
{
#if RELEASE_LOG_DISABLED
UNUSED_PARAM(info);
#else
if (!isAlwaysOnLoggingAllowed())
return;
auto duration = info.completionTime - info.startTime;
if (duration < 1_s)
return;
RELEASE_LOG_IF_ALLOWED("logSlowCacheRetrieveIfNeeded: Took %.0fms, priority %d", duration.milliseconds(), info.priority);
if (info.wasSpeculativeLoad)
RELEASE_LOG_IF_ALLOWED("logSlowCacheRetrieveIfNeeded: Was speculative load");
if (!info.storageTimings.startTime)
return;
RELEASE_LOG_IF_ALLOWED("logSlowCacheRetrieveIfNeeded: Storage retrieve time %.0fms", (info.storageTimings.completionTime - info.storageTimings.startTime).milliseconds());
if (info.storageTimings.dispatchTime) {
auto time = (info.storageTimings.dispatchTime - info.storageTimings.startTime).milliseconds();
auto count = info.storageTimings.dispatchCountAtDispatch - info.storageTimings.dispatchCountAtStart;
RELEASE_LOG_IF_ALLOWED("logSlowCacheRetrieveIfNeeded: Dispatch delay %.0fms, dispatched %lu resources first", time, count);
}
if (info.storageTimings.recordIOStartTime)
RELEASE_LOG_IF_ALLOWED("logSlowCacheRetrieveIfNeeded: Record I/O time %.0fms", (info.storageTimings.recordIOEndTime - info.storageTimings.recordIOStartTime).milliseconds());
if (info.storageTimings.blobIOStartTime)
RELEASE_LOG_IF_ALLOWED("logSlowCacheRetrieveIfNeeded: Blob I/O time %.0fms", (info.storageTimings.blobIOEndTime - info.storageTimings.blobIOStartTime).milliseconds());
if (info.storageTimings.synchronizationInProgressAtDispatch)
RELEASE_LOG_IF_ALLOWED("logSlowCacheRetrieveIfNeeded: Synchronization was in progress");
if (info.storageTimings.shrinkInProgressAtDispatch)
RELEASE_LOG_IF_ALLOWED("logSlowCacheRetrieveIfNeeded: Shrink was in progress");
if (info.storageTimings.wasCanceled)
RELEASE_LOG_IF_ALLOWED("logSlowCacheRetrieveIfNeeded: Retrieve was canceled");
#endif
}
} // namespace WebKit
| 47.40865 | 412 | 0.725491 | [
"vector"
] |
9f5bc29f32d26256bfe6c3aee7d78e39dd57029e | 3,511 | hpp | C++ | irobot_create_common/irobot_create_nodes/include/irobot_create_nodes/mock_publisher.hpp | roni-kreinin/create3_sim | 637f02b9f7ddcc28de35e5e003c998290a51fccd | [
"BSD-3-Clause"
] | null | null | null | irobot_create_common/irobot_create_nodes/include/irobot_create_nodes/mock_publisher.hpp | roni-kreinin/create3_sim | 637f02b9f7ddcc28de35e5e003c998290a51fccd | [
"BSD-3-Clause"
] | null | null | null | irobot_create_common/irobot_create_nodes/include/irobot_create_nodes/mock_publisher.hpp | roni-kreinin/create3_sim | 637f02b9f7ddcc28de35e5e003c998290a51fccd | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2021 iRobot Corporation. All Rights Reserved.
// @author Lola Segura (lsegura@irobot.com)
#ifndef IROBOT_CREATE_NODES__MOCK_PUBLISHER_HPP_
#define IROBOT_CREATE_NODES__MOCK_PUBLISHER_HPP_
#include <limits>
#include <memory>
#include <string>
#include <vector>
#include "irobot_create_msgs/action/led_animation.hpp"
#include "irobot_create_msgs/msg/audio_note_vector.hpp"
#include "irobot_create_msgs/msg/button.hpp"
#include "irobot_create_msgs/msg/interface_buttons.hpp"
#include "irobot_create_msgs/msg/led_color.hpp"
#include "irobot_create_msgs/msg/lightring_leds.hpp"
#include "irobot_create_msgs/msg/slip_status.hpp"
#include "rclcpp/rclcpp.hpp"
#include "rclcpp_action/rclcpp_action.hpp"
namespace irobot_create_nodes
{
class MockPublisher : public rclcpp::Node
{
public:
/// \brief Constructor
explicit MockPublisher(const rclcpp::NodeOptions & options = rclcpp::NodeOptions());
// Callback functions
void lightring_callback(irobot_create_msgs::msg::LightringLeds::SharedPtr msg);
void audio_callback(irobot_create_msgs::msg::AudioNoteVector::SharedPtr msg);
private:
rclcpp_action::GoalResponse handle_led_animation_goal(
const rclcpp_action::GoalUUID & uuid,
std::shared_ptr<const irobot_create_msgs::action::LedAnimation::Goal> goal);
rclcpp_action::CancelResponse handle_led_animation_cancel(
const std::shared_ptr<
rclcpp_action::ServerGoalHandle<irobot_create_msgs::action::LedAnimation>> goal_handle);
void handle_led_animation_accepted(
const std::shared_ptr<
rclcpp_action::ServerGoalHandle<irobot_create_msgs::action::LedAnimation>> goal_handle);
void execute_led_animation(
const std::shared_ptr<
rclcpp_action::ServerGoalHandle<irobot_create_msgs::action::LedAnimation>> goal_handle);
// Publish aggregated detections on timer_'s frequency
rclcpp::TimerBase::SharedPtr buttons_timer_;
rclcpp::TimerBase::SharedPtr slip_status_timer_;
// Publishers
std::shared_ptr<
rclcpp::Publisher<irobot_create_msgs::msg::InterfaceButtons>> buttons_publisher_{nullptr};
rclcpp::Publisher<irobot_create_msgs::msg::SlipStatus>::SharedPtr slip_status_publisher_{nullptr};
// Subscribers
rclcpp::Subscription<irobot_create_msgs::msg::LightringLeds>::SharedPtr lightring_subscription_;
rclcpp::Subscription<irobot_create_msgs::msg::AudioNoteVector>::SharedPtr audio_subscription_;
// Actions
rclcpp_action::Server<irobot_create_msgs::action::LedAnimation>::SharedPtr
led_animation_action_server_;
// Gazebo simulator being used
std::string gazebo_;
// Topic to publish interface buttons to
std::string buttons_publisher_topic_;
// Topic to publish slip status to
std::string slip_status_publisher_topic_;
// Topic to subscribe to light ring vector
std::string lightring_subscription_topic_;
// Topic to subscribe to audio note vector
std::string audio_subscription_topic_;
// Message to store the interface buttons
irobot_create_msgs::msg::InterfaceButtons buttons_msg_;
// Message to store the slip status
irobot_create_msgs::msg::SlipStatus slip_status_msg_;
const std::string base_frame_ {"base_link"};
std::mutex led_animation_params_mutex_;
rclcpp::Duration led_animation_end_duration_;
rclcpp::Time led_animation_start_time_;
rclcpp::Time last_animation_feedback_time_;
const rclcpp::Duration report_animation_feedback_interval_ {std::chrono::seconds(3)};
};
} // namespace irobot_create_nodes
#endif // IROBOT_CREATE_NODES__MOCK_PUBLISHER_HPP_
| 36.957895 | 100 | 0.799772 | [
"vector"
] |
9f5cbf9660a94f6d1dc4f5d71a9d4f8adb018799 | 25,370 | cpp | C++ | shell/services/hdsrv/shhwdtct/dispatch.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | shell/services/hdsrv/shhwdtct/dispatch.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | shell/services/hdsrv/shhwdtct/dispatch.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | #include <nt.h>
#include <ntrtl.h>
#include <nturtl.h>
#undef ASSERT
#include "dtct.h"
#include "hwdev.h"
#include "dtctreg.h"
#include "users.h"
#include "cmmn.h"
#include "sfstr.h"
#include "reg.h"
#include "misc.h"
#include "dbg.h"
#include "tfids.h"
#include <shpriv.h>
#define ARRAYSIZE(a) (sizeof((a))/sizeof((a)[0]))
// {C1FB73D0-EC3A-4ba2-B512-8CDB9187B6D1}
const CLSID IID_IHWEventHandler =
{0xC1FB73D0, 0xEC3A, 0x4ba2,
{0xB5, 0x12, 0x8C, 0xDB, 0x91, 0x87, 0xB6, 0xD1}};
///////////////////////////////////////////////////////////////////////////////
//
HRESULT _CreateAndInitEventHandler(LPCWSTR pszHandler, CLSID* pclsid,
IHWEventHandler** ppihweh)
{
IHWEventHandler* pihweh;
HRESULT hres = _CoCreateInstanceInConsoleSession(*pclsid, NULL,
CLSCTX_LOCAL_SERVER, IID_PPV_ARG(IHWEventHandler, &pihweh));
*ppihweh = NULL;
if (SUCCEEDED(hres))
{
LPWSTR pszInitCmdLine;
hres = _GetInitCmdLine(pszHandler, &pszInitCmdLine);
if (SUCCEEDED(hres))
{
if (S_FALSE == hres)
{
ASSERT(!pszInitCmdLine);
hres = pihweh->Initialize(TEXT(""));
}
else
{
hres = pihweh->Initialize(pszInitCmdLine);
}
if (SUCCEEDED(hres))
{
*ppihweh = pihweh;
}
if (pszInitCmdLine)
{
LocalFree((HLOCAL)pszInitCmdLine);
}
}
if (FAILED(hres))
{
pihweh->Release();
*ppihweh = NULL;
}
}
return hres;
}
struct EXECUTEHANDLERDATA
{
CLSID clsidHandler;
LPWSTR pszDeviceIDForAutoplay;
LPWSTR pszEventType;
union
{
LPWSTR pszHandler;
LPWSTR pszInitCmdLine;
};
};
HRESULT _CreateExecuteHandlerData(EXECUTEHANDLERDATA** ppehd)
{
HRESULT hres;
*ppehd = (EXECUTEHANDLERDATA*)LocalAlloc(LPTR, sizeof(EXECUTEHANDLERDATA));
if (*ppehd)
{
hres = S_OK;
}
else
{
hres = E_OUTOFMEMORY;
}
return hres;
}
HRESULT _FreeEHDStrings(EXECUTEHANDLERDATA* pehd)
{
if (pehd->pszHandler)
{
LocalFree((HLOCAL)pehd->pszHandler);
pehd->pszHandler = NULL;
}
if (pehd->pszDeviceIDForAutoplay)
{
LocalFree((HLOCAL)pehd->pszDeviceIDForAutoplay);
pehd->pszDeviceIDForAutoplay = NULL;
}
if (pehd->pszEventType)
{
LocalFree((HLOCAL)pehd->pszEventType);
pehd->pszEventType = NULL;
}
return S_OK;
}
HRESULT _FreeExecuteHandlerData(EXECUTEHANDLERDATA* pehd)
{
_FreeEHDStrings(pehd);
LocalFree((HLOCAL)pehd);
return S_OK;
}
HRESULT _SetExecuteHandlerData(EXECUTEHANDLERDATA* pehd,
LPCWSTR pszDeviceIDForAutoplay, LPCWSTR pszEventType,
LPCWSTR pszHandlerOrInitCmdLine, const CLSID* pclsidHandler)
{
HRESULT hres = DupString(pszHandlerOrInitCmdLine, &(pehd->pszHandler));
if (SUCCEEDED(hres))
{
hres = DupString(pszDeviceIDForAutoplay,
&(pehd->pszDeviceIDForAutoplay));
if (SUCCEEDED(hres))
{
hres = DupString(pszEventType, &(pehd->pszEventType));
if (SUCCEEDED(hres))
{
pehd->clsidHandler = *pclsidHandler;
}
}
}
if (FAILED(hres))
{
// Free everything
_FreeEHDStrings(pehd);
}
return hres;
}
DWORD WINAPI _ExecuteHandlerThreadProc(void* pv)
{
EXECUTEHANDLERDATA* pehd = (EXECUTEHANDLERDATA*)pv;
IHWEventHandler* pihweh;
DIAGNOSTIC((TEXT("[0100]Attempting to execute handler for: %s %s %s"),
pehd->pszDeviceIDForAutoplay, pehd->pszEventType,
pehd->pszHandler));
TRACE(TF_SHHWDTCTDTCT,
TEXT("_ExecuteHandlerThreadProc for: %s %s %s"),
pehd->pszDeviceIDForAutoplay, pehd->pszEventType,
pehd->pszHandler);
HRESULT hres = _CreateAndInitEventHandler(pehd->pszHandler,
&(pehd->clsidHandler), &pihweh);
if (SUCCEEDED(hres) && (S_FALSE != hres))
{
WCHAR szDeviceIDAlt[MAX_PATH];
DIAGNOSTIC((TEXT("[0101]Got Handler Interface")));
TRACE(TF_SHHWDTCTDTCT, TEXT("Got Handler Interface"));
hres = _GetAltDeviceID(pehd->pszDeviceIDForAutoplay, szDeviceIDAlt,
ARRAYSIZE(szDeviceIDAlt));
if (S_FALSE == hres)
{
szDeviceIDAlt[0] = 0;
}
if (SUCCEEDED(hres))
{
hres = pihweh->HandleEvent(pehd->pszDeviceIDForAutoplay,
szDeviceIDAlt, pehd->pszEventType);
DIAGNOSTIC((TEXT("[0103]IHWEventHandler::HandleEvent returned: hr = 0x%08X"), hres));
TRACE(TF_SHHWDTCTDTCT,
TEXT("pIEventHandler->HandleEvent result: 0x%08X"), hres);
}
pihweh->Release();
}
else
{
DIAGNOSTIC((TEXT("[0102]Did not get Handler Interface: hr = 0x%08X"), hres));
TRACE(TF_SHHWDTCTDTCT,
TEXT("Did not get Handler Interface: 0x%08X"), hres);
}
_FreeExecuteHandlerData(pehd);
TRACE(TF_SHHWDTCTDTCT, TEXT("Exiting _ExecuteHandlerThreadProc"));
return (DWORD)hres;
}
HRESULT _DelegateToExecuteHandlerThread(EXECUTEHANDLERDATA* pehd,
LPTHREAD_START_ROUTINE pThreadProc, HANDLE* phThread)
{
HRESULT hres;
// set thread stack size?
*phThread = CreateThread(NULL, 0, pThreadProc, pehd, 0, NULL);
if (*phThread)
{
hres = S_OK;
}
else
{
hres = E_FAIL;
}
return hres;
}
HRESULT _ExecuteHandlerHelper(LPCWSTR pszDeviceIDForAutoplay,
LPCWSTR pszEventType,
LPCWSTR pszHandlerOrInitCmdLine, LPTHREAD_START_ROUTINE pThreadProc,
const CLSID* pclsidHandler, HANDLE* phThread)
{
// Let's prepare to delegate to other thread
EXECUTEHANDLERDATA* pehd;
HRESULT hres = _CreateExecuteHandlerData(&pehd);
*phThread = NULL;
if (SUCCEEDED(hres))
{
hres = _SetExecuteHandlerData(pehd, pszDeviceIDForAutoplay,
pszEventType, pszHandlerOrInitCmdLine,
pclsidHandler);
if (SUCCEEDED(hres))
{
hres = _DelegateToExecuteHandlerThread(pehd,
pThreadProc, phThread);
}
if (FAILED(hres))
{
_FreeExecuteHandlerData(pehd);
}
}
return hres;
}
HRESULT _ExecuteHandler(LPCWSTR pszDeviceIDForAutoplay, LPCWSTR pszEventType,
LPCWSTR pszHandler)
{
CLSID clsidHandler;
HRESULT hres = _GetHandlerCLSID(pszHandler, &clsidHandler);
if (SUCCEEDED(hres) && (S_FALSE != hres))
{
HANDLE hThread;
hres = _ExecuteHandlerHelper(pszDeviceIDForAutoplay, pszEventType,
pszHandler, _ExecuteHandlerThreadProc,
&clsidHandler, &hThread);
if (SUCCEEDED(hres))
{
CloseHandle(hThread);
}
}
return hres;
}
///////////////////////////////////////////////////////////////////////////////
//
DWORD WINAPI _PromptUserThreadProc(void* pv)
{
IHWEventHandler* pihweh;
EXECUTEHANDLERDATA* pehd = (EXECUTEHANDLERDATA*)pv;
DIAGNOSTIC((TEXT("[0110]Will prompt user for preferences")));
TRACE(TF_SHHWDTCTDTCT, TEXT("Entered _PromptUserThreadProc"));
HRESULT hr = _CoCreateInstanceInConsoleSession(pehd->clsidHandler, NULL,
CLSCTX_LOCAL_SERVER, IID_PPV_ARG(IHWEventHandler, &pihweh));
if (SUCCEEDED(hr))
{
hr = pihweh->Initialize(pehd->pszInitCmdLine);
if (SUCCEEDED(hr))
{
WCHAR szDeviceIDAlt[MAX_PATH];
TRACE(TF_SHHWDTCTDTCT, TEXT("Got Handler Interface"));
hr = _GetAltDeviceID(pehd->pszDeviceIDForAutoplay, szDeviceIDAlt,
ARRAYSIZE(szDeviceIDAlt));
if (S_FALSE == hr)
{
szDeviceIDAlt[0] = 0;
}
if (SUCCEEDED(hr))
{
hr = pihweh->HandleEvent(pehd->pszDeviceIDForAutoplay,
szDeviceIDAlt, pehd->pszEventType);
}
}
pihweh->Release();
}
_FreeExecuteHandlerData(pehd);
TRACE(TF_SHHWDTCTDTCT, TEXT("Exiting _PromptUserThreadProc"));
return (DWORD)hr;
}
HRESULT _PromptUser(LPCWSTR pszDeviceIDForAutoplay, LPCWSTR pszEventType,
LPCWSTR pszInitCmdLine)
{
HANDLE hThread;
HRESULT hr = _ExecuteHandlerHelper(pszDeviceIDForAutoplay, pszEventType,
pszInitCmdLine, _PromptUserThreadProc,
&CLSID_ShellAutoplay, &hThread);
if (SUCCEEDED(hr))
{
CloseHandle(hThread);
}
return hr;
}
///////////////////////////////////////////////////////////////////////////////
//
struct QUERYRUNNINGOBJECTSTRUCT
{
IHWEventHandler* phweh;
WCHAR szDeviceIntfID[MAX_DEVICEID];
WCHAR szEventType[MAX_EVENTTYPE];
};
DWORD WINAPI _QueryRunningObjectThreadProc(void* pv)
{
QUERYRUNNINGOBJECTSTRUCT* pqro = (QUERYRUNNINGOBJECTSTRUCT*)pv;
HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE);
if (SUCCEEDED(hr))
{
hr = pqro->phweh->HandleEvent(pqro->szDeviceIntfID, TEXT(""), pqro->szEventType);
CoUninitialize();
}
pqro->phweh->Release();
LocalFree((HLOCAL)pqro);
return (DWORD)hr;
}
HRESULT _QueryRunningObject(IHWEventHandler* phweh, LPCWSTR pszDeviceIntfID,
LPCWSTR pszEventType, LPCWSTR pszHandler, BOOL* pfHandlesEvent)
{
HRESULT hr;
QUERYRUNNINGOBJECTSTRUCT* pqro = (QUERYRUNNINGOBJECTSTRUCT*)LocalAlloc(LPTR,
sizeof(QUERYRUNNINGOBJECTSTRUCT));
*pfHandlesEvent = FALSE;
if (pqro)
{
phweh->AddRef();
pqro->phweh = phweh;
hr = SafeStrCpyN(pqro->szDeviceIntfID, pszDeviceIntfID,
ARRAYSIZE(pqro->szDeviceIntfID));
if (SUCCEEDED(hr))
{
hr = SafeStrCpyN(pqro->szEventType, pszEventType,
ARRAYSIZE(pqro->szEventType));
}
if (SUCCEEDED(hr))
{
HANDLE hThread = CreateThread(NULL, 0, _QueryRunningObjectThreadProc, pqro,
0, NULL);
if (hThread)
{
// Wait 3 sec to see if wants to process it. If not, it's
// fair play for us.
DWORD dwWait = WaitForSingleObject(hThread, 3000);
if (WAIT_OBJECT_0 == dwWait)
{
// Return within time and did not failed
DWORD dwExitCode;
if (GetExitCodeThread(hThread, &dwExitCode))
{
HRESULT hrHandlesEvent = (HRESULT)dwExitCode;
// WIA will return S_FALSE if they do NOT want to process
// the event
if (SUCCEEDED(hrHandlesEvent) && (S_FALSE != hrHandlesEvent))
{
DIAGNOSTIC((TEXT("[0124]Already running handler will handle event (%s)"), pszHandler));
TRACE(TF_WIA,
TEXT("Already running handler will handle event"));
*pfHandlesEvent = TRUE;
}
else
{
DIAGNOSTIC((TEXT("[0125]Already running handler will *NOT* handle event(%s)"), pszHandler));
TRACE(TF_WIA,
TEXT("WIA.HandleEventOverride will NOT Handle Event"));
}
hr = S_OK;
}
else
{
hr = S_FALSE;
}
}
else
{
if (WAIT_TIMEOUT == dwWait)
{
DIAGNOSTIC((TEXT("[0126]Timed out on already running handler ( > 3 sec)")));
TRACE(TF_WIA,
TEXT("Timed out waiting on already running object (%s)"), pszHandler);
}
hr = S_FALSE;
}
CloseHandle(hThread);
}
else
{
hr = E_OUTOFMEMORY;
}
}
if (FAILED(hr))
{
pqro->phweh->Release();
LocalFree((HLOCAL)pqro);
}
}
else
{
hr = E_OUTOFMEMORY;
}
return hr;
}
HRESULT _FindAlreadyRunningHandler(LPCWSTR pszDeviceIntfID,
LPCWSTR pszEventType, LPCWSTR pszEventHandler, BOOL* pfHandlesEvent)
{
CImpersonateConsoleSessionUser icsu;
HRESULT hr = icsu.Impersonate();
*pfHandlesEvent = FALSE;
if (SUCCEEDED(hr) && (S_FALSE != hr))
{
IBindCtx* pbindctx;
hr = CreateBindCtx(0, &pbindctx);
if (SUCCEEDED(hr))
{
IRunningObjectTable* prot;
hr = pbindctx->GetRunningObjectTable(&prot);
if (SUCCEEDED(hr))
{
WCHAR szKeyName[MAX_KEY] = SHDEVICEEVENTROOT(TEXT("EventHandlers\\"));
hr = SafeStrCatN(szKeyName, pszEventHandler, ARRAYSIZE(szKeyName));
if (SUCCEEDED(hr))
{
HKEY hkey;
hr = _RegOpenKey(HKEY_LOCAL_MACHINE, szKeyName, &hkey);
if (SUCCEEDED(hr) && (S_FALSE != hr))
{
WCHAR szHandler[MAX_HANDLER];
DWORD dwIndex = 0;
while (!*pfHandlesEvent && SUCCEEDED(hr) &&
SUCCEEDED(hr = _RegEnumStringValue(hkey, dwIndex,
szHandler, ARRAYSIZE(szHandler))) &&
(S_FALSE != hr))
{
CLSID clsid;
hr = _GetHandlerCancelCLSID(szHandler, &clsid);
if (SUCCEEDED(hr) && (S_FALSE != hr))
{
IMoniker* pmoniker;
hr = _BuildMoniker(pszEventHandler, clsid,
(USER_SHARED_DATA->ActiveConsoleId), &pmoniker);
if (SUCCEEDED(hr))
{
IUnknown* punk;
hr = prot->GetObject(pmoniker, &punk);
if (SUCCEEDED(hr) && (S_FALSE != hr))
{
IHWEventHandler* phweh;
hr = punk->QueryInterface(
IID_IHWEventHandler, (void**)&phweh);
if (SUCCEEDED(hr))
{
hr = _QueryRunningObject(phweh,
pszDeviceIntfID, pszEventType,
szHandler, pfHandlesEvent);
phweh->Release();
}
punk->Release();
}
else
{
// if it can't find it, it return s failure
hr = S_FALSE;
}
pmoniker->Release();
}
}
++dwIndex;
}
_RegCloseKey(hkey);
}
}
prot->Release();
}
pbindctx->Release();
}
icsu.RevertToSelf();
}
return hr;
}
HRESULT _FinalDispatch(LPCWSTR pszDeviceIntfID, LPCWSTR pszEventType,
LPCWSTR pszEventHandler)
{
DIAGNOSTIC((TEXT("[0111]Looking for already running handler for: %s, %s, %s"),
pszDeviceIntfID, pszEventType, pszEventHandler));
BOOL fHandlesEvent;
HRESULT hres = _FindAlreadyRunningHandler(pszDeviceIntfID, pszEventType,
pszEventHandler, &fHandlesEvent);
if (SUCCEEDED(hres) && !fHandlesEvent)
{
WCHAR szHandler[MAX_HANDLER];
hres = _GetUserDefaultHandler(pszDeviceIntfID, pszEventHandler,
szHandler, ARRAYSIZE(szHandler), GUH_USEWINSTA0USER);
if (SUCCEEDED(hres) && (S_FALSE != hres))
{
// We have a handler
TRACE(TF_SHHWDTCTDTCT, TEXT("Found Handler: %s"), szHandler);
BOOL fPrompt = FALSE;
BOOL fCheckAlwaysDoThis = FALSE;
BOOL fExecuteHandler = FALSE;
if (HANDLERDEFAULT_GETFLAGS(hres) &
HANDLERDEFAULT_USERCHOSENDEFAULT)
{
// We have a user chosen default...
if (HANDLERDEFAULT_GETFLAGS(hres) &
HANDLERDEFAULT_MORERECENTHANDLERSINSTALLED)
{
// ... but we have more recent apps that were installed
fPrompt = TRUE;
}
else
{
if (lstrcmp(szHandler, TEXT("MSTakeNoAction")))
{
// The handler is *not* "Take no action"
if (!lstrcmp(szHandler, TEXT("MSPromptEachTime")))
{
// The handler is "Prompt each time"
fPrompt = TRUE;
}
else
{
fExecuteHandler = TRUE;
}
}
}
}
else
{
// If we do not have a user chosen handler, then we always
// prompt
fPrompt = TRUE;
}
if (fPrompt)
{
if (HANDLERDEFAULT_GETFLAGS(hres) &
HANDLERDEFAULT_MORERECENTHANDLERSINSTALLED)
{
// There are more recent handlers
if (HANDLERDEFAULT_GETFLAGS(hres) &
HANDLERDEFAULT_USERCHOSENDEFAULT)
{
// The user chose a default handler
if (!(HANDLERDEFAULT_GETFLAGS(hres) &
HANDLERDEFAULT_DEFAULTSAREDIFFERENT))
{
// The handlers are the same, check the checkbox
fCheckAlwaysDoThis = TRUE;
}
}
}
_GiveAllowForegroundToConsoleShell();
if (fCheckAlwaysDoThis)
{
// Notice the '*' at the end of the string
hres = _PromptUser(pszDeviceIntfID, pszEventType,
TEXT("PromptEachTimeNoContent*"));
}
else
{
hres = _PromptUser(pszDeviceIntfID, pszEventType,
TEXT("PromptEachTimeNoContent"));
}
}
else
{
if (fExecuteHandler)
{
hres = _ExecuteHandler(pszDeviceIntfID, pszEventType,
szHandler);
}
}
}
}
return hres;
}
///////////////////////////////////////////////////////////////////////////////
//
HRESULT _IsWIAHandlingEvent(LPCWSTR pszDeviceIDForAutoplay,
LPCWSTR pszEventType, BOOL* pfWIAHandlingEvent)
{
CLSID clsid = {0};
HRESULT hr = CLSIDFromProgID(TEXT("WIA.HandleEventOverride"), &clsid);
*pfWIAHandlingEvent = FALSE;
if (SUCCEEDED(hr))
{
HANDLE hThread;
hr = _ExecuteHandlerHelper(pszDeviceIDForAutoplay, pszEventType,
TEXT(""), _ExecuteHandlerThreadProc, &clsid, &hThread);
if (SUCCEEDED(hr))
{
// Wait 3 sec to see if WIA wants to process it. If not, it's
// fair play for us.
DWORD dwWait = WaitForSingleObject(hThread, 3000);
if (WAIT_OBJECT_0 == dwWait)
{
// Return within time and did not failed
DWORD dwExitCode;
if (GetExitCodeThread(hThread, &dwExitCode))
{
HRESULT hrWIA = (HRESULT)dwExitCode;
// WIA will return S_FALSE if they do NOT want to process
// the event
if (SUCCEEDED(hrWIA) && (S_FALSE != hrWIA))
{
DIAGNOSTIC((TEXT("[0114]WIA will handle event")));
TRACE(TF_WIA,
TEXT("WIA.HandleEventOverride will Handle Event"));
*pfWIAHandlingEvent = TRUE;
}
else
{
TRACE(TF_WIA,
TEXT("WIA.HandleEventOverride will NOT Handle Event"));
}
}
}
else
{
if (WAIT_TIMEOUT == dwWait)
{
TRACE(TF_WIA,
TEXT("Timed out waiting on WIA.HandleEventOverride"));
}
}
CloseHandle(hThread);
}
else
{
TRACE(TF_WIA,
TEXT("_ExecuteHandlerHelper failed for WIA.HandleEventOverride"));
}
}
else
{
TRACE(TF_WIA,
TEXT("Could not get CLSID for WIA.HandleEventOverride"));
}
return hr;
}
HRESULT _DispatchToHandler(LPCWSTR pszDeviceIntfID, CHWDeviceInst* phwdevinst,
LPCWSTR pszEventType, BOOL* pfHasHandler)
{
WCHAR szDeviceHandler[MAX_DEVICEHANDLER];
HRESULT hres = _GetDeviceHandler(phwdevinst, szDeviceHandler,
ARRAYSIZE(szDeviceHandler));
*pfHasHandler = FALSE;
if (SUCCEEDED(hres) && (S_FALSE != hres))
{
WCHAR szEventHandler[MAX_EVENTHANDLER];
DIAGNOSTIC((TEXT("[0115]Found DeviceHandler: %s"), szDeviceHandler));
TRACE(TF_SHHWDTCTDTCT,
TEXT("Found Device Handler: %s"), szDeviceHandler);
if (SUCCEEDED(hres))
{
DIAGNOSTIC((TEXT("[0117]Device does NOT Support Content")));
TRACE(TF_SHHWDTCTDTCT, TEXT("Device does NOT Support Content"));
BOOL fWIAHandlingEvent = FALSE;
GUID guidInterface;
HRESULT hres2 = phwdevinst->GetInterfaceGUID(&guidInterface);
if (SUCCEEDED(hres2))
{
if ((guidInterface == guidImagingDeviceClass) ||
(guidInterface == guidVideoCameraClass))
{
_IsWIAHandlingEvent(pszDeviceIntfID, pszEventType,
&fWIAHandlingEvent);
}
}
if (!fWIAHandlingEvent)
{
hres = _GetEventHandlerFromDeviceHandler(szDeviceHandler,
pszEventType, szEventHandler, ARRAYSIZE(szEventHandler));
if (SUCCEEDED(hres))
{
if (S_FALSE != hres)
{
*pfHasHandler = TRUE;
hres = _FinalDispatch(pszDeviceIntfID, pszEventType,
szEventHandler);
TRACE(TF_SHHWDTCTDTCTDETAILED,
TEXT(" _GetEventHandlerFromDeviceHandler returned: %s"),
szEventHandler);
}
}
}
else
{
DIAGNOSTIC((TEXT("[0123]WIA will handle event")));
TRACE(TF_SHHWDTCTDTCTDETAILED, TEXT(" WIA will handle event"));
}
}
}
else
{
DIAGNOSTIC((TEXT("[0112]Did NOT find DeviceHandler: 0x%08X"), hres));
TRACE(TF_SHHWDTCTDTCT, TEXT("Did not find Device Handler: 0x%08X"),
hres);
}
return hres;
}
| 29.261822 | 121 | 0.479227 | [
"object"
] |
9f5f7650c10ea113d2c681d975779ce5bc925787 | 1,742 | cpp | C++ | src/SMLMat2x2.cpp | aceoyale/SML | 513d60be40f1e2629b4475cfdf1b4913c1a5154a | [
"MIT"
] | 1 | 2020-10-08T09:31:54.000Z | 2020-10-08T09:31:54.000Z | src/SMLMat2x2.cpp | aceoyale/SML | 513d60be40f1e2629b4475cfdf1b4913c1a5154a | [
"MIT"
] | null | null | null | src/SMLMat2x2.cpp | aceoyale/SML | 513d60be40f1e2629b4475cfdf1b4913c1a5154a | [
"MIT"
] | null | null | null | #include "SMLMat2x2.h"
SML::Mat2x2::Mat2x2(const float& a, const float& b, const float& c, const float& d)
{
m[0][0] = a; m[0][1] = b;
m[1][0] = c; m[1][1] = d;
}
SML::Mat2x2::Mat2x2(const Vector& r1, const Vector& r2)
{
m[0][0] = r1.x; m[0][1] = r1.y;
m[1][0] = r2.x; m[1][1] = r2.y;
}
SML::Mat2x2::Mat2x2(const Mat2x2& v)
{
m[0][0] = v.m[0][0]; m[0][1] = v.m[0][1];
m[1][0] = v.m[1][0]; m[1][1] = v.m[1][1];
}
float SML::Mat2x2::det()const
{
return(m[0][0] * m[1][1] - m[0][1] * m[1][0]);
}
SML::Mat2x2 SML::Mat2x2::operator+(const Mat2x2& v)const
{
return Mat2x2(m[0][0] + v.m[0][0], m[0][1] + v.m[0][1], m[1][0] + v.m[1][0], m[1][1] + v.m[1][1]);
/*Vector result;
_declspec(align(16)) Vector X(m[0][0], m[][], m[][]);
_declspec(align(16)) Vector Y(v.m[][], v.m[][], v.m[][]);
_mm_store_ps(&result.x, _mm_add_ps(_mm_load_ps(&X.x), _mm_load_ps(&Y.x)));
return result;*/
}
SML::Mat2x2 SML::Mat2x2::operator-(const Mat2x2& v)const
{
return Mat2x2(m[0][0] - v.m[0][0], m[0][1] - v.m[0][1], m[1][0] - v.m[1][0], m[1][1] - v.m[1][1]);
}
SML::Mat2x2 SML::Mat2x2::operator*(const float& s)const
{
return Mat2x2(m[0][0] * s, m[0][1] * s, m[1][0] * s, m[1][1] * s);
}
SML::Mat2x2 SML::Mat2x2::operator/(const float& s)const
{
return Mat2x2(m[0][0] / s, m[0][1] / s, m[1][0] / s, m[1][1] / s);
}
SML::Mat2x2 SML::Mat2x2::Transpose() const
{
return Mat2x2(m[0][0], m[1][0], m[0][1], m[1][1]);
}
SML::Mat2x2 SML::Mat2x2::Identity() const
{
return Mat2x2(1,0, 0,1);
}
SML::Mat2x2 SML::Mat2x2::operator*(const Mat2x2& v)const
{
return Mat2x2(m[0][0] * v.m[0][0] + m[0][1] * v.m[1][0], m[0][0] * v.m[0][1] + m[0][1] * v.m[1][1], m[1][0] * v.m[0][0] + m[1][1] * v.m[1][0], m[1][0] * v.m[0][1] + m[1][1] * v.m[1][1]);
} | 26.393939 | 187 | 0.52124 | [
"vector"
] |
9f62dfe03c6875e3f7c2306b3972ca7eba5a8538 | 358 | cpp | C++ | Warmup/Jumping on the Clouds/solution.cpp | xqphd/q_hackerrank_solutions | 102bbdc03af6958133c4597bde27175e18b06c47 | [
"MIT"
] | null | null | null | Warmup/Jumping on the Clouds/solution.cpp | xqphd/q_hackerrank_solutions | 102bbdc03af6958133c4597bde27175e18b06c47 | [
"MIT"
] | null | null | null | Warmup/Jumping on the Clouds/solution.cpp | xqphd/q_hackerrank_solutions | 102bbdc03af6958133c4597bde27175e18b06c47 | [
"MIT"
] | null | null | null | // Complete the jumpingOnClouds function below.
int jumpingOnClouds(vector<int> c) {
c.push_back(1);
int result = 0;
int num_zeros = 0;
for(int i=0;i<c.size();i++){
if(c[i]==0){
num_zeros++;
}
if(c[i]==1){
result += num_zeros/2+1;
num_zeros=0;
}
}
return result-1;
} | 22.375 | 47 | 0.488827 | [
"vector"
] |
9f75c62cfc9a687085ab29fb06d67db095f0bceb | 705 | cpp | C++ | ComputerGraphics/Transform.cpp | ylzf0000/TinyGameEngine | d15c3eb80189d91ed430eca1089475213ef0cad3 | [
"MIT"
] | null | null | null | ComputerGraphics/Transform.cpp | ylzf0000/TinyGameEngine | d15c3eb80189d91ed430eca1089475213ef0cad3 | [
"MIT"
] | null | null | null | ComputerGraphics/Transform.cpp | ylzf0000/TinyGameEngine | d15c3eb80189d91ed430eca1089475213ef0cad3 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "Transform.h"
#include "Matrix4x4.h"
#include "Vector4.h"
void cg::Transform::Rotate(float x, float y, float z)
{
eulerRotation.x += x;
eulerRotation.y += y;
eulerRotation.z += z;
}
void cg::Transform::Rotate(const Vector3 &rotation)
{
Rotate(rotation.x, rotation.y, rotation.z);
}
void cg::Transform::RotateAround(const Vector3 &point, const Vector3 &axis, float angle)
{
Vector3 dist = point - position;
Matrix4x4 tmp;
Matrix4x4 root = Matrix4x4::Identity();
//tmp.RotationZ(angle);
//root = tmp*root;
tmp.RotationY(angle);
root = tmp*root;
//tmp.RotationX(angle);
//root = tmp*root;
dist = (root*dist.GetVector4()).GetVector3();
position = point - dist;
}
| 22.741935 | 88 | 0.695035 | [
"transform"
] |
9f7fcf61e992a2a411402a3c04958e7d04049663 | 2,265 | hpp | C++ | 1.48/tuning/sys/cthmutex.hpp | spirick/tuninglib | c390d7abc74847be0ebd9d08905151d72347ab82 | [
"MIT"
] | 3 | 2021-12-01T18:31:31.000Z | 2021-12-06T02:15:00.000Z | 1.48/tuning/sys/cthmutex.hpp | spirick/tuninglib | c390d7abc74847be0ebd9d08905151d72347ab82 | [
"MIT"
] | null | null | null | 1.48/tuning/sys/cthmutex.hpp | spirick/tuninglib | c390d7abc74847be0ebd9d08905151d72347ab82 | [
"MIT"
] | null | null | null |
// Spirick Tuning
//
// A C++ class and template library
// for performance critical applications.
// Copyright (C) 1996-2021 Dietmar Deimling.
// All rights reserved.
// Internet www.spirick.com
// E-Mail info@spirick.com
//
// Version 1.48
// File tuning/sys/cthmutex.hpp
#ifndef TUNING_SYS_CTHMUTEX_HPP
#define TUNING_SYS_CTHMUTEX_HPP
#include "tuning/sys/creserror.hpp"
//---------------------------------------------------------------------------
// Thread mutex
#if defined TL_MULTI
const unsigned cu_ThMutexDataSize = 40; // Multiple of sizeof (t_UInt64)
class TL_EXPORT ct_ThMutex
{
// Don't use char buffer because of alignment
t_UInt64 au_Data [cu_ThMutexDataSize / sizeof (t_UInt64)];
bool b_InitSuccess;
int i_LockCount;
// Do not copy this object
ct_ThMutex (const ct_ThMutex &);
ct_ThMutex & operator = (const ct_ThMutex &);
public:
ct_ThMutex ();
~ct_ThMutex ();
static inline void * operator new (size_t, void * pv) { return pv; }
static inline void operator delete (void *, void *) { }
static inline void operator delete (void *) { }
bool GetInitSuccess () const;
et_ResError TryLock (bool & b_success);
et_ResError Lock ();
et_ResError Unlock ();
};
#else
class TL_EXPORT ct_ThMutex
{
// Do not copy this object
ct_ThMutex (const ct_ThMutex &);
ct_ThMutex & operator = (const ct_ThMutex &);
public:
bool GetInitSuccess () const { return true; }
et_ResError TryLock (bool & b_success)
{ b_success = true; return ec_ResOK; }
et_ResError Lock () { return ec_ResOK; }
et_ResError Unlock () { return ec_ResOK; }
};
#endif
//---------------------------------------------------------------------------
// Thread critical section
bool TL_EXPORT tl_CriticalSectionInitSuccess ();
void TL_EXPORT tl_DeleteCriticalSection ();
et_ResError TL_EXPORT tl_TryEnterCriticalSection (bool & b_success);
et_ResError TL_EXPORT tl_EnterCriticalSection ();
et_ResError TL_EXPORT tl_LeaveCriticalSection ();
#endif
| 28.670886 | 78 | 0.586755 | [
"object"
] |
9f8f7c2724b210492ff81a671b22c955c005df2b | 70,852 | cpp | C++ | AStyleTest/src/AStyleTest_ObjC.cpp | a-w/astyle | 8225c7fc9b65162bdd958cabb87eedd9749f1ecd | [
"MIT"
] | null | null | null | AStyleTest/src/AStyleTest_ObjC.cpp | a-w/astyle | 8225c7fc9b65162bdd958cabb87eedd9749f1ecd | [
"MIT"
] | null | null | null | AStyleTest/src/AStyleTest_ObjC.cpp | a-w/astyle | 8225c7fc9b65162bdd958cabb87eedd9749f1ecd | [
"MIT"
] | null | null | null | // AStyleTest_ObjC.cpp
// Copyright (c) 2016 by Jim Pattee <jimp03@email.com>.
// Licensed under the MIT license.
// License.txt describes the conditions under which this software may be distributed.
//----------------------------------------------------------------------------
// headers
//----------------------------------------------------------------------------
#include "AStyleTest.h"
//----------------------------------------------------------------------------
// anonymous namespace
//----------------------------------------------------------------------------
namespace {
//
//----------------------------------------------------------------------------
// AStyle Objective-C Styles
//----------------------------------------------------------------------------
struct ObjCStyleF : public Test
{
string textStr;
const char* textIn;
ObjCStyleF()
{
textStr =
"\n@interface Foo : NSObject {\n"
" NSString* var1;\n"
" NSString* var2;\n"
"}\n"
"@end\n"
"\n"
"@implementation Foo\n"
"\n"
"- (void) foo\n"
"{\n"
" if (isFoo)\n"
" {\n"
" bar();\n"
" }\n"
"}\n"
"\n"
"- (void) foo : (int) icon\n"
" ofSize : (int) size {\n"
" if (isFoo) {\n"
" bar();\n"
" }\n"
"}\n"
"\n"
"@end\n";
textIn = textStr.c_str();
}
};
TEST_F(ObjCStyleF, Default)
{
// test default style option
char options[] = "";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(textIn, textOut);
delete [] textOut;
}
TEST_F(ObjCStyleF, Allman)
{
// test allman style option
char text[] =
"\n@interface Foo : NSObject\n"
"{\n"
" NSString* var1;\n"
" NSString* var2;\n"
"}\n"
"@end\n"
"\n"
"@implementation Foo\n"
"\n"
"- (void) foo\n"
"{\n"
" if (isFoo)\n"
" {\n"
" bar();\n"
" }\n"
"}\n"
"\n"
"- (void) foo : (int) icon\n"
" ofSize : (int) size\n"
"{\n"
" if (isFoo)\n"
" {\n"
" bar();\n"
" }\n"
"}\n"
"\n"
"@end\n";
char options[] = "style=allman";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST_F(ObjCStyleF, Java)
{
// test java style option
char text[] =
"\n@interface Foo : NSObject {\n"
" NSString* var1;\n"
" NSString* var2;\n"
"}\n"
"@end\n"
"\n"
"@implementation Foo\n"
"\n"
"- (void) foo {\n"
" if (isFoo) {\n"
" bar();\n"
" }\n"
"}\n"
"\n"
"- (void) foo : (int) icon\n"
" ofSize : (int) size {\n"
" if (isFoo) {\n"
" bar();\n"
" }\n"
"}\n"
"\n"
"@end\n";
char options[] = "style=java";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST_F(ObjCStyleF, KR)
{
// test k&r style option
char text[] =
"\n@interface Foo : NSObject\n"
"{\n"
" NSString* var1;\n"
" NSString* var2;\n"
"}\n"
"@end\n"
"\n"
"@implementation Foo\n"
"\n"
"- (void) foo\n"
"{\n"
" if (isFoo) {\n"
" bar();\n"
" }\n"
"}\n"
"\n"
"- (void) foo : (int) icon\n"
" ofSize : (int) size\n"
"{\n"
" if (isFoo) {\n"
" bar();\n"
" }\n"
"}\n"
"\n"
"@end\n";
char options[] = "style=kr";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST_F(ObjCStyleF, Stroustrup)
{
// test stroustrup style option
char text[] =
"\n@interface Foo : NSObject\n"
"{\n"
" NSString* var1;\n"
" NSString* var2;\n"
"}\n"
"@end\n"
"\n"
"@implementation Foo\n"
"\n"
"- (void) foo\n"
"{\n"
" if (isFoo) {\n"
" bar();\n"
" }\n"
"}\n"
"\n"
"- (void) foo : (int) icon\n"
" ofSize : (int) size\n"
"{\n"
" if (isFoo) {\n"
" bar();\n"
" }\n"
"}\n"
"\n"
"@end\n";
char options[] = "style=stroustrup, indent=spaces=5";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST_F(ObjCStyleF, Whitesmith)
{
// test whitesmith style option
char text[] =
"\n@interface Foo : NSObject\n"
" {\n"
" NSString* var1;\n"
" NSString* var2;\n"
" }\n"
"@end\n"
"\n"
"@implementation Foo\n"
"\n"
"- (void) foo\n"
" {\n"
" if (isFoo)\n"
" {\n"
" bar();\n"
" }\n"
" }\n"
"\n"
"- (void) foo : (int) icon\n"
" ofSize : (int) size\n"
" {\n"
" if (isFoo)\n"
" {\n"
" bar();\n"
" }\n"
" }\n"
"\n"
"@end\n";
char options[] = "style=whitesmith";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST_F(ObjCStyleF, VTK)
{
// test vtk style option
char text[] =
"\n@interface Foo : NSObject\n"
"{\n"
" NSString* var1;\n"
" NSString* var2;\n"
"}\n"
"@end\n"
"\n"
"@implementation Foo\n"
"\n"
"- (void) foo\n"
"{\n"
" if (isFoo)\n"
" {\n"
" bar();\n"
" }\n"
"}\n"
"\n"
"- (void) foo : (int) icon\n"
" ofSize : (int) size\n"
"{\n"
" if (isFoo)\n"
" {\n"
" bar();\n"
" }\n"
"}\n"
"\n"
"@end\n";
char options[] = "style=vtk";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST_F(ObjCStyleF, Banner)
{
// test banner style option
char text[] =
"\n@interface Foo : NSObject {\n"
" NSString* var1;\n"
" NSString* var2;\n"
" }\n"
"@end\n"
"\n"
"@implementation Foo\n"
"\n"
"- (void) foo {\n"
" if (isFoo) {\n"
" bar();\n"
" }\n"
" }\n"
"\n"
"- (void) foo : (int) icon\n"
" ofSize : (int) size {\n"
" if (isFoo) {\n"
" bar();\n"
" }\n"
" }\n"
"\n"
"@end\n";
char options[] = "style=banner";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST_F(ObjCStyleF, Gnu)
{
// test gnu style option
char text[] =
"\n@interface Foo : NSObject\n"
"{\n"
" NSString* var1;\n"
" NSString* var2;\n"
"}\n"
"@end\n"
"\n"
"@implementation Foo\n"
"\n"
"- (void) foo\n"
"{\n"
" if (isFoo)\n"
" {\n"
" bar();\n"
" }\n"
"}\n"
"\n"
"- (void) foo : (int) icon\n"
" ofSize : (int) size\n"
"{\n"
" if (isFoo)\n"
" {\n"
" bar();\n"
" }\n"
"}\n"
"\n"
"@end\n";
char options[] = "style=gnu, indent=spaces=2";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST_F(ObjCStyleF, Linux)
{
// test linux style option
char text[] =
"\n@interface Foo : NSObject\n"
"{\n"
" NSString* var1;\n"
" NSString* var2;\n"
"}\n"
"@end\n"
"\n"
"@implementation Foo\n"
"\n"
"- (void) foo\n"
"{\n"
" if (isFoo) {\n"
" bar();\n"
" }\n"
"}\n"
"\n"
"- (void) foo : (int) icon\n"
" ofSize : (int) size\n"
"{\n"
" if (isFoo) {\n"
" bar();\n"
" }\n"
"}\n"
"\n"
"@end\n";
char options[] = "style=linux, indent=spaces=8";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST_F(ObjCStyleF, Horstmann)
{
// test horstmann style option
char text[] =
"\n@interface Foo : NSObject\n"
"{ NSString* var1;\n"
" NSString* var2;\n"
"}\n"
"@end\n"
"\n"
"@implementation Foo\n"
"\n"
"- (void) foo\n"
"{ if (isFoo)\n"
" { bar();\n"
" }\n"
"}\n"
"\n"
"- (void) foo : (int) icon\n"
" ofSize : (int) size\n"
"{ if (isFoo)\n"
" { bar();\n"
" }\n"
"}\n"
"\n"
"@end\n";
char options[] = "style=horstmann, indent=spaces=3";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST_F(ObjCStyleF, 1TBS)
{
// test 1tbs style option
char text[] =
"\n@interface Foo : NSObject\n"
"{\n"
" NSString* var1;\n"
" NSString* var2;\n"
"}\n"
"@end\n"
"\n"
"@implementation Foo\n"
"\n"
"- (void) foo\n"
"{\n"
" if (isFoo) {\n"
" bar();\n"
" }\n"
"}\n"
"\n"
"- (void) foo : (int) icon\n"
" ofSize : (int) size\n"
"{\n"
" if (isFoo) {\n"
" bar();\n"
" }\n"
"}\n"
"\n"
"@end\n";
char options[] = "style=1tbs";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST_F(ObjCStyleF, Google)
{
// test google style option
char text[] =
"\n@interface Foo : NSObject {\n"
" NSString* var1;\n"
" NSString* var2;\n"
"}\n"
"@end\n"
"\n"
"@implementation Foo\n"
"\n"
"- (void) foo {\n"
" if (isFoo) {\n"
" bar();\n"
" }\n"
"}\n"
"\n"
"- (void) foo : (int) icon\n"
" ofSize : (int) size {\n"
" if (isFoo) {\n"
" bar();\n"
" }\n"
"}\n"
"\n"
"@end\n";
char options[] = "style=google";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST_F(ObjCStyleF, Pico)
{
// test pico style option
char text[] =
"\n@interface Foo : NSObject\n"
"{ NSString* var1;\n"
" NSString* var2; }\n"
"@end\n"
"\n"
"@implementation Foo\n"
"\n"
"- (void) foo\n"
"{ if (isFoo)\n"
" { bar(); } }\n"
"\n"
"- (void) foo : (int) icon\n"
" ofSize : (int) size\n"
"{ if (isFoo)\n"
" { bar(); } }\n"
"\n"
"@end\n";
char options[] = "style=pico";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST_F(ObjCStyleF, Lisp)
{
// test lisp style option
char text[] =
"\n@interface Foo : NSObject {\n"
" NSString* var1;\n"
" NSString* var2; }\n"
"@end\n"
"\n"
"@implementation Foo\n"
"\n"
"- (void) foo {\n"
" if (isFoo) {\n"
" bar(); } }\n"
"\n"
"- (void) foo : (int) icon\n"
" ofSize : (int) size {\n"
" if (isFoo) {\n"
" bar(); } }\n"
"\n"
"@end\n";
char options[] = "style=lisp";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
//-------------------------------------------------------------------------
// AStyle Objective-C Pad Method Prefix
//-------------------------------------------------------------------------
TEST(ObjCPadMethodPrefix, LongOption)
{
// Test pad method prefix long option.
char textIn[] =
"\n"
"-(void)Foo1;\n"
"+ (void)Foo2;\n"
"- (void)Foo3;\n"
"\n"
"-(void)Foo4\n"
"{ }";
char text[] =
"\n"
"- (void)Foo1;\n"
"+ (void)Foo2;\n"
"- (void)Foo3;\n"
"\n"
"- (void)Foo4\n"
"{ }";
char options[] = "pad-method-prefix";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCPadMethodPrefix, ShortOption)
{
// Test pad method prefix short option.
char textIn[] =
"\n"
"-(void)Foo1;\n"
"+ (void)Foo2;\n"
"- (void)Foo3;\n"
"\n"
"-(void)Foo4\n"
"{ }";
char text[] =
"\n"
"- (void)Foo1;\n"
"+ (void)Foo2;\n"
"- (void)Foo3;\n"
"\n"
"- (void)Foo4\n"
"{ }";
char options[] = "-xQ";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCPadMethodPrefix, UnPadMethodPrefix)
{
// Test objective-c with pad-method-prefix and unpad-method-prefix.
// The result should be pad-method-prefix.
char textIn[] =
"\n"
"-(void)Foo1;\n"
"+ (void)Foo2;\n"
"- (void)Foo3;\n"
"\n"
"-(void)Foo4\n"
"{ }";
char text[] =
"\n"
"- (void)Foo1;\n"
"+ (void)Foo2;\n"
"- (void)Foo3;\n"
"\n"
"- (void)Foo4\n"
"{ }";
char options[] = "pad-method-prefix, unpad-method-prefix";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCPadMethodPrefix, SansPadUnPad)
{
// Test objective-c with no method prefix option.
// The result should be no change.
char text[] =
"\n"
"-(void)Foo1;\n"
"+ (void)Foo2;\n"
"- (void)Foo3;\n"
"\n"
"-(void)Foo4\n"
"{ }";
char options[] = "";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCPadMethodPrefix, Comments)
{
// Test pad method prefix with comments.
// The comment alignment should be maintained.
char textIn[] =
"\n"
"-(void)Foo1; // comment\n"
"+ (void)Foo2; // comment\n"
"- (void)Foo3; /* comment */\n"
"\n"
"-(void)Foo4 // comment\n"
"{ }";
char text[] =
"\n"
"- (void)Foo1; // comment\n"
"+ (void)Foo2; // comment\n"
"- (void)Foo3; /* comment */\n"
"\n"
"- (void)Foo4 // comment\n"
"{ }";
char options[] = "pad-method-prefix";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST(ObjCPadMethodPrefix, PadParenOutComments)
{
// Test pad method prefix with pad-paren-out.
// The comment alignment should be maintained.
char textIn[] =
"\n"
"-(void)Foo1; // comment\n"
"+ (void)Foo2; // comment\n"
"- (void)Foo3; /* comment */\n"
"\n"
"-(void)Foo4 // comment\n"
"{ }";
char text[] =
"\n"
"- (void) Foo1; // comment\n"
"+ (void) Foo2; // comment\n"
"- (void) Foo3; /* comment */\n"
"\n"
"- (void) Foo4 // comment\n"
"{ }";
char options[] = "pad-method-prefix, pad-paren-out";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
//-------------------------------------------------------------------------
// AStyle Objective-C UnPad Method Prefix
//-------------------------------------------------------------------------
TEST(ObjCUnPadMethodPrefix, LongOption)
{
// Test unpad-method-prefix long option.
char textIn[] =
"\n"
"-(void)Foo1;\n"
"+ (void)Foo2;\n"
"- (void)Foo3;\n"
"\n"
"-(void)Foo4\n"
"{ }";
char text[] =
"\n"
"-(void)Foo1;\n"
"+(void)Foo2;\n"
"-(void)Foo3;\n"
"\n"
"-(void)Foo4\n"
"{ }";
char options[] = "unpad-method-prefix";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCUnPadMethodPrefix, ShortOption)
{
// Test unpad method prefix short option.
char textIn[] =
"\n"
"-(void)Foo1;\n"
"+ (void)Foo2;\n"
"- (void)Foo3;\n"
"\n"
"-(void)Foo4\n"
"{ }";
char text[] =
"\n"
"-(void)Foo1;\n"
"+(void)Foo2;\n"
"-(void)Foo3;\n"
"\n"
"-(void)Foo4\n"
"{ }";
char options[] = "-xR";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCUnPadMethodPrefix, Comments)
{
// Test unpad-method-prefix with comments.
// The comment alignment should be maintained.
char textIn[] =
"\n"
"-(void)Foo1; // comment\n"
"+ (void)Foo2; // comment\n"
"- (void)Foo3; /* comment */\n"
"\n"
"-(void)Foo4 // comment\n"
"{ }";
char text[] =
"\n"
"-(void)Foo1; // comment\n"
"+(void)Foo2; // comment\n"
"-(void)Foo3; /* comment */\n"
"\n"
"-(void)Foo4 // comment\n"
"{ }";
char options[] = "unpad-method-prefix";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST(ObjCUnPadMethodPrefix, PadParenOutComments)
{
// Test unpad method prefix with pad-paren-out.
// The comment alignment should be maintained.
char textIn[] =
"\n"
"-(void)Foo1; // comment\n"
"+ (void)Foo2; // comment\n"
"- (void)Foo3; /* comment */\n"
"\n"
"-(void)Foo4 // comment\n"
"{ }";
char text[] =
"\n"
"-(void) Foo1; // comment\n"
"+(void) Foo2; // comment\n"
"-(void) Foo3; /* comment */\n"
"\n"
"-(void) Foo4 // comment\n"
"{ }";
char options[] = "unpad-method-prefix, pad-paren-out";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
//-------------------------------------------------------------------------
// AStyle Objective-C Pad Return Type
//-------------------------------------------------------------------------
TEST(ObjCPadReturnType, LongOption)
{
// Test pad return type long option.
char textIn[] =
"\n"
"-(void)Foo1;\n"
"+(void) Foo2;\n"
"\n"
"-(void)Foo3\n"
"{ }";
char text[] =
"\n"
"-(void) Foo1;\n"
"+(void) Foo2;\n"
"\n"
"-(void) Foo3\n"
"{ }";
char options[] = "pad-return-type";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST(ObjCPadReturnType, ShortOption)
{
// Test pad return type short option.
char textIn[] =
"\n"
"-(void)Foo1;\n"
"+(void) Foo2;\n"
"\n"
"-(void)Foo3\n"
"{ }";
char text[] =
"\n"
"-(void) Foo1;\n"
"+(void) Foo2;\n"
"\n"
"-(void) Foo3\n"
"{ }";
char options[] = "-xq";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST(ObjCPadReturnType, UnPadReturnType)
{
// Test objective-c with pad-return-type and unpad-return-type.
// The result should be pad-return-type.
char textIn[] =
"\n"
"-(void) Foo1;\n"
"+(void) Foo2;\n"
"\n"
"-(void) Foo3\n"
"{ }";
char text[] =
"\n"
"-(void) Foo1;\n"
"+(void) Foo2;\n"
"\n"
"-(void) Foo3\n"
"{ }";
char options[] = "pad-return-type, unpad-return-type";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST(ObjCPadReturnType, SansPadUnPad)
{
// Test objective-c with no return type option.
// The result should be no change.
char text[] =
"\n"
"-(void)Foo1;\n"
"+(void) Foo2;\n"
"\n"
"-(void) Foo3\n"
"{ }";
char options[] = "";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST(ObjCPadReturnType, Comments)
{
// Test pad return type with comments.
// The comment alignment should be maintained.
char textIn[] =
"\n"
"-(void)Foo1; // comment\n"
"+(void) Foo2; /* comment */\n"
"\n"
"-(void)Foo3 // comment\n"
"{ }";
char text[] =
"\n"
"-(void) Foo1; // comment\n"
"+(void) Foo2; /* comment */\n"
"\n"
"-(void) Foo3 // comment\n"
"{ }";
char options[] = "pad-return-type";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST(ObjCPadReturnType, PadParenOutComments)
{
// Test pad return type with pad-paren-out.
// The comment alignment should be maintained.
char textIn[] =
"\n"
"-(void)Foo1; // comment\n"
"+(void) Foo2; /* comment */\n"
"\n"
"-(void)Foo3 // comment\n"
"{ }";
char text[] =
"\n"
"- (void) Foo1; // comment\n"
"+ (void) Foo2; /* comment */\n"
"\n"
"- (void) Foo3 // comment\n"
"{ }";
char options[] = "pad-return-type, pad-paren-out";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
//-------------------------------------------------------------------------
// AStyle Objective-C UnPad Return Type
//-------------------------------------------------------------------------
TEST(ObjCUnPadReturnType, LongOption)
{
// Test unpad return type long option.
char textIn[] =
"\n"
"-(void) Foo1;\n"
"+(void)Foo2;\n"
"\n"
"-(void) Foo3\n"
"{ }";
char text[] =
"\n"
"-(void)Foo1;\n"
"+(void)Foo2;\n"
"\n"
"-(void)Foo3\n"
"{ }";
char options[] = "unpad-return-type";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST(ObjCUnPadReturnType, ShortOption)
{
// Test unpad return type short option.
char textIn[] =
"\n"
"-(void) Foo1;\n"
"+(void)Foo2;\n"
"\n"
"-(void) Foo3\n"
"{ }";
char text[] =
"\n"
"-(void)Foo1;\n"
"+(void)Foo2;\n"
"\n"
"-(void)Foo3\n"
"{ }";
char options[] = "-xr";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST(ObjCUnPadReturnType, Comments)
{
// Test unpad return type with comments.
// The comment alignment should be maintained.
char textIn[] =
"\n"
"-(void) Foo1; // comment\n"
"+(void)Foo2; /* comment */\n"
"\n"
"-(void) Foo3 // comment\n"
"{ }";
char text[] =
"\n"
"-(void)Foo1; // comment\n"
"+(void)Foo2; /* comment */\n"
"\n"
"-(void)Foo3 // comment\n"
"{ }";
char options[] = "unpad-return-type";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST(ObjCUnPadReturnType, PadParenOutComments)
{
// Test unpad return type with pad-paren-out.
// The comment alignment should be maintained.
char textIn[] =
"\n"
"-(void)Foo1; // comment\n"
"+(void) Foo2; /* comment */\n"
"\n"
"-(void)Foo3 // comment\n"
"{ }";
char text[] =
"\n"
"- (void)Foo1; // comment\n"
"+ (void)Foo2; /* comment */\n"
"\n"
"- (void)Foo3 // comment\n"
"{ }";
char options[] = "unpad-return-type, pad-paren-out";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
//-------------------------------------------------------------------------
// AStyle Objective-C Pad Method Colon
//-------------------------------------------------------------------------
TEST(ObjCPadMethodColon, NoOption)
{
// Test without pad-method-colon option.
// Statements should not change.
char text[] =
"\n"
"-(void)foo1:(int)row;\n"
"-(void)foo2 : (int)row;\n"
"-(void)foo3: (int)row;\n"
"-(void)foo4 :(int)row;";
char options[] = "";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCPadMethodColon, LongOptionNone)
{
// Test pad-method-colon=none long option.
char textIn[] =
"\n"
"-(void)foo1:(int)row;\n"
"-(void)foo2 : (int)row;\n"
"-(void)foo3: (int)row;\n"
"-(void)foo4 :(int)row;";
char text[] =
"\n"
"-(void)foo1:(int)row;\n"
"-(void)foo2:(int)row;\n"
"-(void)foo3:(int)row;\n"
"-(void)foo4:(int)row;";
char options[] = "pad-method-colon=none";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCPadMethodColon, LongOptionAll)
{
// Test pad-method-colon=all long option.
char textIn[] =
"\n"
"-(void)foo1:(int)row;\n"
"-(void)foo2 : (int)row;\n"
"-(void)foo3: (int)row;\n"
"-(void)foo4 :(int)row;";
char text[] =
"\n"
"-(void)foo1 : (int)row;\n"
"-(void)foo2 : (int)row;\n"
"-(void)foo3 : (int)row;\n"
"-(void)foo4 : (int)row;";
char options[] = "pad-method-colon=all";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCPadMethodColon, LongOptionAfter)
{
// Test pad-method-colon=after long option.
char textIn[] =
"\n"
"-(void)foo1:(int)row;\n"
"-(void)foo2 : (int)row;\n"
"-(void)foo3: (int)row;\n"
"-(void)foo4 :(int)row;";
char text[] =
"\n"
"-(void)foo1: (int)row;\n"
"-(void)foo2: (int)row;\n"
"-(void)foo3: (int)row;\n"
"-(void)foo4: (int)row;";
char options[] = "pad-method-colon=after";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCPadMethodColon, LongOptionBefore)
{
// Test pad-method-colon=before long option.
char textIn[] =
"\n"
"-(void)foo1:(int)row;\n"
"-(void)foo2 : (int)row;\n"
"-(void)foo3: (int)row;\n"
"-(void)foo4 :(int)row;";
char text[] =
"\n"
"-(void)foo1 :(int)row;\n"
"-(void)foo2 :(int)row;\n"
"-(void)foo3 :(int)row;\n"
"-(void)foo4 :(int)row;";
char options[] = "pad-method-colon=before";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCPadMethodColon, ShortOptionNone)
{
// Test pad-method-colon=none short option.
char textIn[] =
"\n"
"-(void)foo1:(int)row;\n"
"-(void)foo2 : (int)row;\n"
"-(void)foo3: (int)row;\n"
"-(void)foo4 :(int)row;";
char text[] =
"\n"
"-(void)foo1:(int)row;\n"
"-(void)foo2:(int)row;\n"
"-(void)foo3:(int)row;\n"
"-(void)foo4:(int)row;";
char options[] = "-xP0";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCPadMethodColon, ShortOptionAll)
{
// Test pad-method-colon=all short option.
char textIn[] =
"\n"
"-(void)foo1:(int)row;\n"
"-(void)foo2 : (int)row;\n"
"-(void)foo3: (int)row;\n"
"-(void)foo4 :(int)row;";
char text[] =
"\n"
"-(void)foo1 : (int)row;\n"
"-(void)foo2 : (int)row;\n"
"-(void)foo3 : (int)row;\n"
"-(void)foo4 : (int)row;";
char options[] = "-xP1";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCPadMethodColon, ShortOptionAfter)
{
// Test pad-method-colon=after short option.
char textIn[] =
"\n"
"-(void)foo1:(int)row;\n"
"-(void)foo2 : (int)row;\n"
"-(void)foo3: (int)row;\n"
"-(void)foo4 :(int)row;";
char text[] =
"\n"
"-(void)foo1: (int)row;\n"
"-(void)foo2: (int)row;\n"
"-(void)foo3: (int)row;\n"
"-(void)foo4: (int)row;";
char options[] = "-xP2";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCPadMethodColon, ShortOptionBefore)
{
// Test pad-method-colon=before short option.
char textIn[] =
"\n"
"-(void)foo1:(int)row;\n"
"-(void)foo2 : (int)row;\n"
"-(void)foo3: (int)row;\n"
"-(void)foo4 :(int)row;";
char text[] =
"\n"
"-(void)foo1 :(int)row;\n"
"-(void)foo2 :(int)row;\n"
"-(void)foo3 :(int)row;\n"
"-(void)foo4 :(int)row;";
char options[] = "-xP3";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCPadMethodColon, MultipleSpacesNone)
{
// Test pad-method-colon=none with multiple spaces.
// This and pad-method-colon=all will test all options.
char textIn[] =
"\n"
"-(void)foo : (int)row;";
char text[] =
"\n"
"-(void)foo:(int)row;";
char options[] = "pad-method-colon=none";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCPadMethodColon, MultipleSpacesAll)
{
// Test pad-method-colon=all with multiple spaces.
// This and pad-method-colon=none will test all options.
char textIn[] =
"\n"
"-(void)foo : (int)row;";
char text[] =
"\n"
"-(void)foo : (int)row;";
char options[] = "pad-method-colon=all";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCPadMethodColon, LimitsNone)
{
// Test pad-method-colon=none with 'for' and 'while' loop limits.
// This should not cause an exception.
// This and pad-method-colon=all will test all options.
char textIn[] =
"\n-(void)readHeader\n"
"{\n"
" NSData *data = [file dataOfLength\n"
" : HEADLEN\n"
" atOffset :\n"
" [NSNumber numberWithUnsignedLong\n"
":\n"
" 0L]];\n"
"}";
char text[] =
"\n-(void)readHeader\n"
"{\n"
" NSData *data = [file dataOfLength\n"
" :HEADLEN\n"
" atOffset:\n"
" [NSNumber numberWithUnsignedLong\n"
" :\n"
" 0L]];\n"
"}";
char options[] = "pad-method-colon=none";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCPadMethodColon, LimitsAll)
{
// Test pad-method-colon=all with 'for' and 'while' loop limits.
// This should not cause an exception.
// This and pad-method-colon=none will test all options.
char textIn[] =
"\n-(void)readHeader\n"
"{\n"
" NSData *data = [file dataOfLength\n"
" :HEADLEN\n"
" atOffset:\n"
" [NSNumber numberWithUnsignedLong\n"
":\n"
" 0L]];\n"
"}";
char text[] =
"\n-(void)readHeader\n"
"{\n"
" NSData *data = [file dataOfLength\n"
" : HEADLEN\n"
" atOffset :\n"
" [NSNumber numberWithUnsignedLong\n"
" :\n"
" 0L]];\n"
"}";
char options[] = "pad-method-colon=all";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCPadMethodColon, SingleCharFollowsNone)
{
// Test pad-method-colon=none 'for' and 'while' loop limits.
// The single char following the colon should be recognized.
// This and pad-method-colon=all will test all options.
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" [[matrix cellAtRow:0 column:0] setTitle: NSLocalizedString(@\"Name\")];\n"
" [[matrix cellAtRow: 1 column: 0] setTitle : NSLocalizedString(@\"Type\")];\n"
" [[matrix cellAtRow: 2 column: 0] setTitle: NSLocalizedString(@\"Date\")];\n"
" [[matrix cellAtRow :3 column :0] setTitle :NSLocalizedString(@\"Size\")];\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" [[matrix cellAtRow:0 column:0] setTitle:NSLocalizedString(@\"Name\")];\n"
" [[matrix cellAtRow:1 column:0] setTitle:NSLocalizedString(@\"Type\")];\n"
" [[matrix cellAtRow:2 column:0] setTitle:NSLocalizedString(@\"Date\")];\n"
" [[matrix cellAtRow:3 column:0] setTitle:NSLocalizedString(@\"Size\")];\n"
"}";
char options[] = "pad-method-colon=none";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCPadMethodColon, SingleCharFollowsAll)
{
// Test pad-method-colon=all 'for' and 'while' loop limits.
// The single char following the colon should be recognized.
// This and pad-method-colon=none will test all options.
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" [[matrix cellAtRow:0 column:0] setTitle: NSLocalizedString(@\"Name\")];\n"
" [[matrix cellAtRow: 1 column: 0] setTitle : NSLocalizedString(@\"Type\")];\n"
" [[matrix cellAtRow: 2 column: 0] setTitle: NSLocalizedString(@\"Date\")];\n"
" [[matrix cellAtRow :3 column :0] setTitle :NSLocalizedString(@\"Size\")];\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" [[matrix cellAtRow : 0 column : 0] setTitle : NSLocalizedString(@\"Name\")];\n"
" [[matrix cellAtRow : 1 column : 0] setTitle : NSLocalizedString(@\"Type\")];\n"
" [[matrix cellAtRow : 2 column : 0] setTitle : NSLocalizedString(@\"Date\")];\n"
" [[matrix cellAtRow : 3 column : 0] setTitle : NSLocalizedString(@\"Size\")];\n"
"}";
char options[] = "pad-method-colon=all";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCPadMethodColon, EndOfLineFollowsNone)
{
// The colon is at end-of-line.
// This and pad-method-colon=all will test all options.
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" [(NSMutableData *)data appendData :\n"
" [handle readDataOfLength : nbytes]];\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" [(NSMutableData *)data appendData:\n"
" [handle readDataOfLength:nbytes]];\n"
"}";
char options[] = "pad-method-colon=none";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCPadMethodColon, EndOfLineFollowsAll)
{
// The colon is at end-of-line.
// This and pad-method-colon=none will test all options.
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" [(NSMutableData *)data appendData:\n"
" [handle readDataOfLength:nbytes]];\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" [(NSMutableData *)data appendData :\n"
" [handle readDataOfLength : nbytes]];\n"
"}";
char options[] = "pad-method-colon=all";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCPadMethodColon, NoneComment)
{
// Test pad-method-colon=none with following comments.
char textIn[] =
"\n"
"-(void)foo1:(int)row; // comment\n"
"-(void)foo2 : (int)row; // comment\n"
"-(void)foo3: (int)row; /* comment */\n"
"-(void)foo4 :(int)row; // comment\n";
char text[] =
"\n"
"-(void)foo1:(int)row; // comment\n"
"-(void)foo2:(int)row; // comment\n"
"-(void)foo3:(int)row; /* comment */\n"
"-(void)foo4:(int)row; // comment\n";
char options[] = "pad-method-colon=none";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST(ObjCPadMethodColon, AllComment)
{
// Test pad-method-colon=none with following comments.
char textIn[] =
"\n"
"-(void)foo1:(int)row; // comment\n"
"-(void)foo2 : (int)row; // comment\n"
"-(void)foo3: (int)row; /* comment */\n"
"-(void)foo4 :(int)row; // comment\n";
char text[] =
"\n"
"-(void)foo1 : (int)row; // comment\n"
"-(void)foo2 : (int)row; // comment\n"
"-(void)foo3 : (int)row; /* comment */\n"
"-(void)foo4 : (int)row; // comment\n";
char options[] = "pad-method-colon=all";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST(ObjCPadMethodColon, AfterComment)
{
// Test pad-method-colon=none with following comments.
char textIn[] =
"\n"
"-(void)foo1:(int)row; // comment\n"
"-(void)foo2 : (int)row; // comment\n"
"-(void)foo3: (int)row; /* comment */\n"
"-(void)foo4 :(int)row; // comment\n";
char text[] =
"\n"
"-(void)foo1: (int)row; // comment\n"
"-(void)foo2: (int)row; // comment\n"
"-(void)foo3: (int)row; /* comment */\n"
"-(void)foo4: (int)row; // comment\n";
char options[] = "pad-method-colon=after";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST(ObjCPadMethodColon, BeforeComment)
{
// Test pad-method-colon=none with following comments.
char textIn[] =
"\n"
"-(void)foo1:(int)row; // comment\n"
"-(void)foo2 : (int)row; // comment\n"
"-(void)foo3: (int)row; /* comment */\n"
"-(void)foo4 :(int)row; // comment\n";
char text[] =
"\n"
"-(void)foo1 :(int)row; // comment\n"
"-(void)foo2 :(int)row; // comment\n"
"-(void)foo3 :(int)row; /* comment */\n"
"-(void)foo4 :(int)row; // comment\n";
char options[] = "pad-method-colon=before";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST(ObjCPadMethodColon, Selector)
{
// Test pad-method-colon=all within a @selector.
// The ending colon should not be padded.
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" cutTitleSel = @selector(cutTitle:toFitWidth:);\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" cutTitleSel = @selector(cutTitle : toFitWidth:);\n"
"}";
char options[] = "pad-method-colon=all";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCPadMethodColon, ParenFollowsNone)
{
// Test pad-method-colon=none with a following ')'.
// The ending colon should not be padded.
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" [panel setAction:@selector(colorChoosen : )];\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" [panel setAction:@selector(colorChoosen:)];\n"
"}";
char options[] = "pad-method-colon=none";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCPadMethodColon, ParenFollowsAll)
{
// Test pad-method-colon=all with a following ')'.
// The ending colon should not be padded.
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" [panel setAction : @selector(colorChoosen : )];\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" [panel setAction : @selector(colorChoosen:)];\n"
"}";
char options[] = "pad-method-colon=all";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCPadMethodColon, ParenFollowsAfter)
{
// Test pad-method-colon=after with a following ')'.
// The ending colon should not be padded.
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" [panel setAction : @selector(colorChoosen : )];\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" [panel setAction: @selector(colorChoosen:)];\n"
"}";
char options[] = "pad-method-colon=after";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCPadMethodColon, ParenFollowsBefore)
{
// Test pad-method-colon=before with a following ')'.
// The ending colon should not be padded.
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" [panel setAction : @selector(colorChoosen : )];\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" [panel setAction :@selector(colorChoosen:)];\n"
"}";
char options[] = "pad-method-colon=before";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCPadMethodColon, QuestionColon1)
{
// Test pad-method-colon=none with '?' and ':'.
// This should not remove the padding.
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" [caseSensButt setState : ([entry boolValue] ? NSOnState : NSOffState)];\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" [caseSensButt setState:([entry boolValue] ? NSOnState : NSOffState)];\n"
"}";
char options[] = "pad-method-colon=none";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCPadMethodColon, QuestionColon2)
{
// Test pad-method-colon=none with '?' and ':'.
// This should not remove the padding for '? :'.
// But should remove for the method call.
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" fsfilter = fsattribute ? [info objectForKey : @\"fsfilter\"] : nil;\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" fsfilter = fsattribute ? [info objectForKey:@\"fsfilter\"] : nil;\n"
"}";
char options[] = "pad-method-colon=none";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCPadMethodColon, QuestionColon3)
{
// Test pad-method-colon=none with '?' and ':'.
// This should not remove the padding for '? :'.
// But should remove for the method call.
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" FSNode *pnode = (i == 0) ? nil : [components objectAtIndex : (i-1)];\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" FSNode *pnode = (i == 0) ? nil : [components objectAtIndex:(i-1)];\n"
"}";
char options[] = "pad-method-colon=none";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCPadMethodColon, ScopeResolution)
{
// pad-method-colon should not pad a scope resolution operator.
char text[] =
"\nconst char* TiXmlBase::errorString[TiXmlBase::TIXML_ERROR_STRING_COUNT] =\n"
"{\n"
"};\n"
"\n"
"void GetDetectorState(DetectorState[nsUniversalDetector::NumDetectors], PRUint32& offset )\n"
"{\n"
" ListStyles style[Logger::num_levels];\n"
"}";
char options[] = "pad-method-colon=all";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCPadMethodColon, CSharpFile)
{
// pad-method-colon should not pad in a C# file.
char text[] =
"\n[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n"
"[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n"
"\n"
"[assembly: AssemblyTitle(\"TreeMaps\")]\n"
"[assembly: AssemblyDescription("")]\n"
"\n"
"[field: NonSerialized]\n"
"public class GitVersion: IDocumentVersion\n"
"{\n"
" [param: MarshalAs(UnmanagedType.Currency)]\n"
" [return: MarshalAs(UnmanagedType.Bool)]\n"
"}";
char options[] = "pad-method-colon=all, mode=cs";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
//-------------------------------------------------------------------------
// AStyle Objective-C Align Method Colon
//-------------------------------------------------------------------------
TEST(ObjCAlignMethodColon, LongOption)
{
// Test align-method-colon long option.
char text[] =
"\n"
"- (BOOL)tableView:(NSTableView *)tableView\n"
" acceptDrop:(id <NSDraggingInfo>)info\n"
" row:(int)row";
char options[] = "align-method-colon";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST(ObjCAlignMethodColon, ShortOption)
{
// Test align-method-colon short option.
char text[] =
"\n"
"- (BOOL)tableView:(NSTableView *)tableView\n"
" acceptDrop:(id <NSDraggingInfo>)info\n"
" row:(int)row";
char options[] = "-xM";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST(ObjCAlignMethodColon, Headers)
{
// Test align-method-colon headers.
char text[] =
"\n"
"- (BOOL)tableView:(NSTableView *)tableView\n"
" acceptDrop:(id <NSDraggingInfo>)info\n"
" row:(int)row;\n"
"\n"
"- (id)tableView:(NSTableView *)aTableView\n"
" objectValueForTableColumn:(NSTableColumn *)aTableColumn\n"
" row:(int)rowIndex;\n"
"\n"
"- (BOOL)openFile:(NSString *)fullPath\n"
" withApplication:(NSString *)appname\n"
" andDeactivate:(BOOL)flag;";
char options[] = "align-method-colon";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST(ObjCAlignMethodColon, MethodsBreak)
{
// Test align-method-colon methods with broken brackets.
char text[] =
"\n"
"- (BOOL)tableView:(NSTableView *)tableView\n"
" acceptDrop:(id <NSDraggingInfo>)info\n"
" row:(int)row\n"
"{ }\n"
"\n"
"- (id)tableView:(NSTableView *)aTableView\n"
" objectValueForTableColumn:(NSTableColumn *)aTableColumn\n"
" row:(int)rowIndex\n"
"{ }\n"
"\n"
"- (BOOL)openFile:(NSString *)fullPath\n"
" withApplication:(NSString *)appname\n"
" andDeactivate:(BOOL)flag\n"
"{ }\n";
char options[] = "align-method-colon";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST(ObjCAlignMethodColon, MethodsAttach)
{
// Test align-method-colon methods with attached brackets.
char text[] =
"\n"
"- (BOOL)tableView:(NSTableView *)tableView\n"
" acceptDrop:(id <NSDraggingInfo>)info\n"
" row:(int)row {\n"
"}\n"
"\n"
"- (id)tableView:(NSTableView *)aTableView\n"
" objectValueForTableColumn:(NSTableColumn *)aTableColumn\n"
" row:(int)rowIndex {\n"
"}\n"
"\n"
"- (BOOL)openFile:(NSString *)fullPath\n"
" withApplication:(NSString *)appname\n"
" andDeactivate:(BOOL)flag {\n"
"}\n";
char options[] = "align-method-colon";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST(ObjCAlignMethodColon, MethodsAttachToLongest)
{
// Test align-method-colon methods with attached brackets.
// Attached bracket is the longest line.
char text[] =
"\n"
"- (void)short : (GTMFoo *)theFoo\n"
" longKeyword : (NSRect)theRect\n"
" error : (NSError **)theError\n"
" evenLongerKeyword : (float)theInterval {\n"
"}\n";
char options[] = "align-method-colon";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST(ObjCAlignMethodColon, MultiLineDefinition)
{
// Test align-method-colon methods with multi-line definition.
// Semicolon is the longest line.
char text[] =
"\n"
"- (void)short : (GTMFoo *)theFoo\n"
" longKeyword : (NSRect)theRect\n"
" error : (NSError **)theError\n"
" evenLongerKeyword : (float)theInterval;\n";
char options[] = "align-method-colon";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST(ObjCAlignMethodColon, Define1)
{
// Test align-method-colon methods with a define.
// The define should not be formatted.
char text[] =
"\n"
"#define BZ_UPDATE_CRC(crcVar,cha) \\\n"
"{ \\\n"
" crcVar = (crcVar << 8) ^ \\\n"
" BZ2_crc32Table[(crcVar >> 24) ^ \\\n"
" ((UChar)cha)]; \\\n"
"}";
char options[] = "align-method-colon";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST(ObjCAlignMethodColon, Define2)
{
// Test align-method-colon methods with an indented define.
// The define should be formatted correctly.
char textIn[] =
"\n"
"#define BZ_UPDATE_CRC(crcVar,cha) \\\n"
"{ \\\n"
" crcVar = (crcVar << 8) ^ \\\n"
" BZ2_crc32Table[(crcVar >> 24) ^ \\\n"
" ((UChar)cha)]; \\\n"
"}";
char text[] =
"\n"
"#define BZ_UPDATE_CRC(crcVar,cha) \\\n"
" { \\\n"
" crcVar = (crcVar << 8) ^ \\\n"
" BZ2_crc32Table[(crcVar >> 24) ^ \\\n"
" ((UChar)cha)]; \\\n"
" }";
char options[] = "align-method-colon, indent-preproc-define";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST(ObjCAlignMethodColon, PadMethodColonNone)
{
// Test align-method-colon with pad-method-colon=none.
char textIn[] =
"\n"
"- (id)tableView :(NSTableView *)aTableView\n"
" objectValueForTableColumn : (NSTableColumn *)aTableColumn\n"
" row : (int)rowIndex\n"
"{ }\n";
char text[] =
"\n"
"- (id)tableView:(NSTableView *)aTableView\n"
" objectValueForTableColumn:(NSTableColumn *)aTableColumn\n"
" row:(int)rowIndex\n"
"{ }\n";
char options[] = "align-method-colon, pad-method-colon=none";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST(ObjCAlignMethodColon, PadMethodColonAll)
{
// Test align-method-colon with pad-method-colon=all.
char textIn[] =
"\n"
"- (id)tableView : (NSTableView *)aTableView\n"
" objectValueForTableColumn:(NSTableColumn *)aTableColumn\n"
" row : (int)rowIndex\n"
"{ }\n";
char text[] =
"\n"
"- (id)tableView : (NSTableView *)aTableView\n"
" objectValueForTableColumn : (NSTableColumn *)aTableColumn\n"
" row : (int)rowIndex\n"
"{ }\n";
char options[] = "align-method-colon, pad-method-colon=all";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST(ObjCAlignMethodColon, PadMethodColonAfter)
{
// Test align-method-colon with pad-method-colon=after.
char textIn[] =
"\n"
"- (id)tableView :(NSTableView *)aTableView\n"
" objectValueForTableColumn : (NSTableColumn *)aTableColumn\n"
" row : (int)rowIndex\n"
"{ }\n";
char text[] =
"\n"
"- (id)tableView: (NSTableView *)aTableView\n"
" objectValueForTableColumn: (NSTableColumn *)aTableColumn\n"
" row: (int)rowIndex\n"
"{ }\n";
char options[] = "align-method-colon, pad-method-colon=after";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST(ObjCAlignMethodColon, PadMethodColonBefore)
{
// Test align-method-colon with pad-method-colon=before.
char textIn[] =
"\n"
"- (id)tableView: (NSTableView *)aTableView\n"
" objectValueForTableColumn : (NSTableColumn *)aTableColumn\n"
" row : (int)rowIndex\n"
"{ }\n";
char text[] =
"\n"
"- (id)tableView :(NSTableView *)aTableView\n"
" objectValueForTableColumn :(NSTableColumn *)aTableColumn\n"
" row :(int)rowIndex\n"
"{ }\n";
char options[] = "align-method-colon, pad-method-colon=before";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
//-------------------------------------------------------------------------
// AStyle Objective-C Other Tests
//-------------------------------------------------------------------------
TEST(ObjCOther, 1TBSAddBrackets)
{
// test 1tbs style option with added brackets
char textIn[] =
"\n@interface Foo : NSObject\n"
"{\n"
" NSString* var1;\n"
" NSString* var2;\n"
"}\n"
"@end\n"
"\n"
"@implementation Foo\n"
"\n"
"- (void) foo\n"
"{\n"
" if (isFoo)\n"
" bar();\n"
"}\n"
"\n"
"- (void) foo : (int) icon\n"
" ofSize : (int) size {\n"
" if (isFoo)\n"
" bar();\n"
"}\n"
"\n"
"@end\n";
char text[] =
"\n@interface Foo : NSObject\n"
"{\n"
" NSString* var1;\n"
" NSString* var2;\n"
"}\n"
"@end\n"
"\n"
"@implementation Foo\n"
"\n"
"- (void) foo\n"
"{\n"
" if (isFoo) {\n"
" bar();\n"
" }\n"
"}\n"
"\n"
"- (void) foo : (int) icon\n"
" ofSize : (int) size\n"
"{\n"
" if (isFoo) {\n"
" bar();\n"
" }\n"
"}\n"
"\n"
"@end\n";
char options[] = "style=1tbs";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCOther, GoogleWithAccessModifiers)
{
// test google style option with access modifiers
char text[] =
"\n@interface Foo : NSObject {\n"
" @public\n"
" bool var1;\n"
" @protected\n"
" bool var2;\n"
" @private\n"
" bool var3;\n"
"}\n"
"@end\n";
char options[] = "style=google";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCOther, GoogleWithMultilineInterface)
{
// test google style option with a multi-line interface
char text[] =
"\n@interface Foo\n"
" : NSObject {\n"
" bool var1;\n"
" bool var2;\n"
"}\n"
"@end\n";
char options[] = "style=google";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCOther, HeaderData)
{
// test a header with Objective-C statements
char text[] =
"\n#include <Foundation/Foundation.h>\n"
"\n"
"@class FooClass;\n"
"\n"
"@interface Foo : NSObject\n"
"{\n"
" NSString* var1;\n"
" NSString* var2;\n"
"}\n"
"@property(retain)NSString* var3;\n"
"\n"
"-(void)method1;\n"
"\n"
"-(void)methodWithArg1:(NSString*)param1;\n"
"\n"
"+void removeComponentsOfPath(NSString *path,\n"
" pcomp *base);\n"
"\n"
"-(void)writeData:(NSData *)data\n"
" atOffset:(NSNumber *)offset;\n"
"\n"
"-(void)method2;\n"
"\n"
"@end";
char options[] = "";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
ASSERT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCOther, InterfaceContinuation1)
{
// test an Objective-C header with continuation lines
// no bracket
char text[] =
"\n@interface Foo1 :\n"
" NSObject\n"
"@end\n"
"\n"
"@interface Foo2\n"
" : NSObject\n"
"@end\n";
char options[] = "";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
ASSERT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCOther, InterfaceContinuation2)
{
// test google style option with a multi-line interface
// attached bracket
char text[] =
"\n@interface Foo1 :\n"
" NSObject {\n"
"}\n"
"@end\n"
"\n"
"@interface Foo2\n"
" : NSObject {\n"
"}\n"
"@end\n";
char options[] = "";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCOther, InterfaceContinuation3)
{
// test google style option with a multi-line interface
// broken bracket
char text[] =
"\n@interface Foo1 :\n"
" NSObject\n"
"{\n"
"}\n"
"@end\n"
"\n"
"@interface Foo2\n"
" : NSObject\n"
"{\n"
"}\n"
"@end\n";
char options[] = "";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCOther, MethodCallIndent)
{
// test indent of method call containing a colon
char text[] =
"\n- (void) Foo\n"
"{\n"
" NSString* homeDirectory = [NSString stringWithUTF8String: homeDirectoryChar];\n"
" NSString* projectPath = [NSString stringWithFormat: @\"%@/%@/%@\",\n"
" homeDirectory, @\"Projects\", subPath];\n"
"}";
char options[] = "";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
ASSERT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCOther, NSExceptionMacros)
{
// test indent of NSException macros NS_DURING and NS_HANDLER
// tabs are used to check the continuation line indent
char text[] =
"\nvoid Foo()\n"
"{\n"
" NS_DURING\n"
" {\n"
" [[NSWorkspace sharedWorkspace] openFile: path\n"
" withApplication: [node name]];\n"
" }\n"
" NS_HANDLER\n"
" {\n"
" NSRunAlertPanel(NSLocalizedString(@\"error\", @\"\"),\n"
" [NSString stringWithFormat: @\"%@ %@!\"]);\n"
" }\n"
" NS_ENDHANDLER\n"
"}";
char options[] = "indent=tab";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
ASSERT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCOther, OtherColonIndent)
{
// test indent of other troublesome objects containing a colon
char text[] =
"\n- (void) Foo\n"
"{\n"
" if (pathCompareSel == NULL) {\n"
" pathCompareSel = @selector(compare:);\n"
" }\n"
" if (initialized == NO) {\n"
" cutTitleSel = @selector(cutTitle:toFitWidth:);\n"
" cutTitle = (cutIMP)[self instanceMethodForSelector: cutTitleSel];\n"
" }\n"
" return (([paths count] > 0) ? [paths makeImmutableCopyOnFail: NO] : nil);\n"
"}";
char options[] = "";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
ASSERT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCOther, MethodCallHeader)
{
// test method call containing a header (default)
// the header should not be recognized
// break-blocks tests ASFormatter, indentation tests ASBeautifier
char text[] =
"\nvoid Foo()\n"
"{\n"
" [[NSNotificationCenter default Center]\n"
" postNotificationName:myNotification\n"
" object:self\n"
" userinfo:nil];\n"
"}";
char options[] = "break-blocks";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
ASSERT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCOther, AutoreleasepoolBreak)
{
// Precommand header autoreleasepoolwith broken brackets.
char text[] =
"\nvirtual void foo()\n"
"{\n"
" @autoreleasepool\n"
" {\n"
" bar()\n"
" }\n"
"}\n";
char options[] = "style=break";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST(ObjCOther, AutoreleasepoolAttach)
{
// Precommand header autoreleasepoolwith attached brackets.
char textIn[] =
"\nvirtual void foo()\n"
"{\n"
" @autoreleasepool\n"
" {\n"
" bar()\n"
" }\n"
"}\n";
char text[] =
"\nvirtual void foo() {\n"
" @autoreleasepool {\n"
" bar()\n"
" }\n"
"}\n";
char options[] = "style=attach";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST(ObjCOther, AutoreleasepoolKandR)
{
// Precommand header autoreleasepoolwith K&R brackets.
char textIn[] =
"\nvirtual void foo()\n"
"{\n"
" @autoreleasepool\n"
" {\n"
" bar()\n"
" }\n"
"}\n";
char text[] =
"\nvirtual void foo()\n"
"{\n"
" @autoreleasepool {\n"
" bar()\n"
" }\n"
"}\n";
char options[] = "style=k&r";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST(ObjCOther, IndentClasses)
{
// test google style option with indent classes
// classes should NOT be indented
char text[] =
"\n@interface Foo : NSObject {\n"
"@public\n"
" bool var1;\n"
"@protected\n"
" bool var2;\n"
"@private\n"
" bool var3;\n"
"}\n"
"@end\n";
char options[] = "indent-classes";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCOther, IndentModifiers)
{
// test google style option with indent classes
char text[] =
"\n@interface Foo : NSObject {\n"
" @public\n"
" bool var1;\n"
" @protected\n"
" bool var2;\n"
" @private\n"
" bool var3;\n"
"}\n"
"@end\n";
char options[] = "indent-modifiers";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCOther, InStatementIndent1)
{
// test method containing a long indent
// the in-statement indent must be increased for correct alignment
char text[] =
"\n-(void) Foo\n"
"{\n"
" NSDateComponents* components = [calendar components:(NSYearCalendarUnit |\n"
" NSMonthCalendarUnit |\n"
" NSDayCalendarUnit)\n"
" fromDate:today];\n"
"}";
char options[] = "max-instatement-indent=60";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
ASSERT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCOther, InStatementIndent2)
{
// The first function has no ending ';' and the ending '}' is followed by a comment.
// The next objective statement should NOT be flagged as a 'isNonInStatementArray'.
// If it is the indentation will be wrong.
char text[] =
"\nvoid Foo2()\n"
"{\n"
" dict = [[NSDictionary alloc] initWithObjects:@\"foo\", @\"bar\", @\"baz\"]\n"
"} // p 277\n"
"\n"
"-(void) Foo\n"
"{\n"
" NSDateComponents* components = [calendar components:(NSYearCalendarUnit |\n"
" NSDayCalendarUnit)\n"
" fromDate:today];\n"
"}";
char options[] = "max-instatement-indent=60";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
ASSERT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCOther, AlignPointer)
{
// Test align-pointer=name option.
// The (*) should not change.
char textIn[] =
"\nvoid foo()\n"
"{\n"
" [icons sortUsingFunction: (int (*)(id, id, void*))compareWithExtType\n"
" context: (void*)NULL];\n"
"}";
char text[] =
"\nvoid foo()\n"
"{\n"
" [icons sortUsingFunction: (int (*)(id, id, void *))compareWithExtType\n"
" context: (void *)NULL];\n"
"}";
char options[] = "align-pointer=name";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCOther, PadInterfaceColon1)
{
// test padding a @interface statement.
char textIn[] =
"\n@interface Foo:NSObject\n"
"{\n"
"}\n"
"\n"
"@interface Foo:NSObject\n"
"\n"
"-(void)method1;\n";
char text[] =
"\n@interface Foo : NSObject\n"
"{\n"
"}\n"
"\n"
"@interface Foo : NSObject\n"
"\n"
"-(void)method1;\n";
char options[] = "";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
ASSERT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCOther, PadInterfaceColon2)
{
// test limits in padding a @interface statement.
char textIn[] =
"\n@interface Foo:\n"
"NSObject\n"
"@end\n"
"\n"
"@interface Foo\n"
":NSObject\n"
"@end\n";
char text[] =
"\n@interface Foo :\n"
" NSObject\n"
"@end\n"
"\n"
"@interface Foo\n"
" : NSObject\n"
"@end\n";
char options[] = "";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
ASSERT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCOther, PadOperator1)
{
// Test methods with pad-oper option.
// Statements should not change.
char text[] =
"\n"
"-(void)foo1:(int)row\n"
"{\n"
" [[NSNotificationCenter default Center]\n"
" postNotificationName:myNotification\n"
" object:self\n"
" userinfo:nil];\n"
"}";
char options[] = "pad-oper";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCOther, PadOperator2)
{
// Test selector with pad-oper option.
// Statement should not change.
char text[] =
"\n"
"-(void)foo1:(int)row\n"
"{\n"
" cutTitleSel = @selector(cutTitle:toFitWidth:);\n"
"}";
char options[] = "pad-oper";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCOther, PadOperator3)
{
// Test 'or' with pad-oper option.
// The 'or' at the end should not be padded.
char text[] =
"\nvoid foo()\n"
"{\n"
" leafpos = [[LeafPosition alloc] initWithPosX:x posY:y relativeToPoint:or];\n"
"}";
char options[] = "pad-oper";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCOther, PadOperator4)
{
// Test pad-oper question.
// Don't pad '?:' within the '[]'.
char textIn[] =
"\nvoid foo()\n"
"{\n"
" fsfilter = fsattribute?[info objectForKey:@\"fsfilter\"]:nil;\n"
" FSNode *pnode = (i == 0)?nil:[components objectAtIndex:(i)];\n"
"}";
char text[] =
"\nvoid foo()\n"
"{\n"
" fsfilter = fsattribute ? [info objectForKey:@\"fsfilter\"] : nil;\n"
" FSNode *pnode = (i == 0) ? nil : [components objectAtIndex:(i)];\n"
"}";
char options[] = "pad-oper";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ObjCOther, PadOperator5)
{
// Test pad-oper question.
// Test the questionMarkStack with multiple '(' and '['.
char textIn[] =
"\nvoid foo()\n"
"{\n"
" caseSensitive = Attribute(\"CaseSensitive\")?atol(Attribute(\"CaseSensitive\")) != 0:false;\n"
" tabPoints[5].y = HasFlag?(tabPoints[4].y):tabPoints[4].y;\n"
"}";
char text[] =
"\nvoid foo()\n"
"{\n"
" caseSensitive = Attribute(\"CaseSensitive\") ? atol(Attribute(\"CaseSensitive\")) != 0 : false;\n"
" tabPoints[5].y = HasFlag ? (tabPoints[4].y) : tabPoints[4].y;\n"
"}";
char options[] = "pad-oper";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
//----------------------------------------------------------------------------
} // namespace
| 27.828751 | 109 | 0.522836 | [
"object"
] |
9f917c7034faddb65e384f8b5847b3b30b1cfbb2 | 3,645 | cpp | C++ | oneflow/core/kernel/collective_boxing_kernels.cpp | Oneflow-Inc/oneflow | b105cacd1e3b0b21bdec1a824a2c125390a2a665 | [
"Apache-2.0"
] | 3,285 | 2020-07-31T05:51:22.000Z | 2022-03-31T15:20:16.000Z | oneflow/core/kernel/collective_boxing_kernels.cpp | Oneflow-Inc/oneflow | b105cacd1e3b0b21bdec1a824a2c125390a2a665 | [
"Apache-2.0"
] | 2,417 | 2020-07-31T06:28:58.000Z | 2022-03-31T23:04:14.000Z | oneflow/core/kernel/collective_boxing_kernels.cpp | Oneflow-Inc/oneflow | b105cacd1e3b0b21bdec1a824a2c125390a2a665 | [
"Apache-2.0"
] | 520 | 2020-07-31T05:52:42.000Z | 2022-03-29T02:38:11.000Z | /*
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "oneflow/core/kernel/kernel.h"
#include "oneflow/core/job/collective_boxing/scheduler.h"
#include "oneflow/core/common/blocking_counter.h"
#include "oneflow/core/graph/boxing/collective_boxing_util.h"
#include "oneflow/core/device/collective_boxing_device_context.h"
namespace oneflow {
class CollectiveBoxingKernelState final : public KernelState {
public:
OF_DISALLOW_COPY_AND_MOVE(CollectiveBoxingKernelState);
explicit CollectiveBoxingKernelState(const RankDesc& rank_desc)
: request_handle_(Global<Scheduler>::Get()->CreateRequestHandle(rank_desc)) {}
~CollectiveBoxingKernelState() override {
Global<Scheduler>::Get()->DestroyRequestHandle(request_handle_);
}
RequestHandle* request_handle() { return request_handle_; }
private:
RequestHandle* request_handle_ = nullptr;
};
using namespace boxing::collective;
class CollectiveBoxingGenericKernel final : public Kernel {
public:
OF_DISALLOW_COPY_AND_MOVE(CollectiveBoxingGenericKernel);
CollectiveBoxingGenericKernel() = default;
~CollectiveBoxingGenericKernel() override = default;
private:
void VirtualKernelInit(KernelContext* ctx) override;
bool IsKernelLaunchSynchronized() const override { return false; }
void ForwardDataContent(KernelContext* ctx) const override;
};
void CollectiveBoxingGenericKernel::VirtualKernelInit(KernelContext* ctx) {
const RankDesc& rank_desc = this->op_conf().collective_boxing_generic_conf().rank_desc();
ctx->set_state(std::make_shared<CollectiveBoxingKernelState>(rank_desc));
}
void CollectiveBoxingGenericKernel::ForwardDataContent(KernelContext* ctx) const {
RequestHandle* request_handle =
CHECK_NOTNULL(dynamic_cast<CollectiveBoxingKernelState*>(ctx->state().get()))
->request_handle();
auto request = std::make_shared<RuntimeRequestInfo>();
const RankDesc& rank_desc = this->op_conf().collective_boxing_generic_conf().rank_desc();
const DataType data_type = rank_desc.op_desc().data_type();
if (GenericOpHasInput(rank_desc)) {
const Blob* in = ctx->BnInOp2Blob("in");
CHECK_EQ(in->data_type(), data_type);
CHECK(in->shape() == ShapeView(GenericOpGetInputShape(rank_desc)));
request->send_buff = in->dptr();
} else {
request->send_buff = nullptr;
}
if (GenericOpHasOutput(rank_desc)) {
Blob* out = ctx->BnInOp2Blob("out");
CHECK_EQ(out->data_type(), data_type);
CHECK(out->shape() == ShapeView(GenericOpGetOutputShape(rank_desc)));
request->recv_buff = out->mut_dptr();
} else {
request->recv_buff = nullptr;
}
auto* device_ctx = dynamic_cast<CollectiveBoxingDeviceCtx*>(ctx->device_ctx());
CHECK_NOTNULL(device_ctx);
std::shared_ptr<CollectiveBoxingDeviceCtxCheckpoint> checkpoint = device_ctx->AddCheckpoint();
request->callback = [checkpoint](const Maybe<void>& status) {
CHECK(status.IsOk());
checkpoint->SetDone();
};
Global<Scheduler>::Get()->Schedule(request_handle, request);
}
REGISTER_KERNEL(OperatorConf::kCollectiveBoxingGenericConf, CollectiveBoxingGenericKernel);
} // namespace oneflow
| 39.193548 | 96 | 0.767627 | [
"shape"
] |
9f95b1d5b9af2e38d2bc1e380cc5d2396e5341d2 | 43,375 | cc | C++ | distbench_engine.cc | isabella232/distbench | 831bf89c052233e7b070d392b19fdc3ba15d104e | [
"Apache-2.0"
] | null | null | null | distbench_engine.cc | isabella232/distbench | 831bf89c052233e7b070d392b19fdc3ba15d104e | [
"Apache-2.0"
] | null | null | null | distbench_engine.cc | isabella232/distbench | 831bf89c052233e7b070d392b19fdc3ba15d104e | [
"Apache-2.0"
] | null | null | null | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.
#include "distbench_engine.h"
#include "distbench_utils.h"
#include "absl/status/statusor.h"
#include "absl/strings/match.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_split.h"
#include "glog/logging.h"
namespace distbench {
grpc::Status DistBenchEngine::SetupConnection(grpc::ServerContext* context,
const ConnectRequest* request,
ConnectResponse* response) {
auto maybe_info = pd_->HandlePreConnect(request->initiator_info(), 0);
if (!maybe_info.ok()) {
return abslStatusToGrpcStatus(maybe_info.status());
}
response->set_responder_info(maybe_info.value());
return grpc::Status::OK;
}
DistBenchEngine::DistBenchEngine(std::unique_ptr<ProtocolDriver> pd)
: pd_(std::move(pd)) {
clock_ = &pd_->GetClock();
}
DistBenchEngine::~DistBenchEngine() {
FinishTraffic();
if (server_) {
server_->Shutdown();
server_->Wait();
}
if (pd_) {
pd_->ShutdownServer();
while (detached_actionlist_threads_) {
sched_yield();
}
pd_->ShutdownClient();
}
}
// Initialize the payload map and perform basic validation
absl::Status DistBenchEngine::InitializePayloadsMap() {
for (int i = 0; i < traffic_config_.payload_descriptions_size(); ++i) {
const auto& payload_spec = traffic_config_.payload_descriptions(i);
const auto& payload_spec_name = payload_spec.name();
// Check for double declaration
if ( payload_map_.find(payload_spec_name) != payload_map_.end() )
return absl::InvalidArgumentError(
"Double definition of payload_descriptions: " + payload_spec_name);
payload_map_[payload_spec_name] = payload_spec;
}
return absl::OkStatus();
}
int DistBenchEngine::get_payload_size(const std::string& payload_name) {
const auto& payload = payload_map_[payload_name];
int size = -1; // Not found value
if (payload.has_size()) {
size = payload.size();
} else {
LOG(WARNING) << "No size defined for payload " << payload_name << "\n";
}
return size;
}
absl::Status DistBenchEngine::InitializeRpcDefinitionStochastic(
RpcDefinition& rpc_def) {
const auto& rpc_spec = rpc_def.rpc_spec;
std::string fanout_filter = rpc_spec.fanout_filter();
const std::string stochastic_keyword = "stochastic";
rpc_def.is_stochastic_fanout = false;
if (!absl::StartsWith(fanout_filter, stochastic_keyword))
return absl::OkStatus();
fanout_filter.erase(0, stochastic_keyword.length());
if (!absl::StartsWith(fanout_filter, "{")) {
return absl::InvalidArgumentError(
"Invalid stochastic filter; should starts with stochastic{");
}
fanout_filter.erase(0, 1); // Consume the '{'
if (!absl::EndsWith(fanout_filter, "}")) {
return absl::InvalidArgumentError(
"Invalid stochastic filter; should ends with }");
}
fanout_filter.pop_back(); // Consume the '}'
float total_probability = 0.;
for (auto s : absl::StrSplit(fanout_filter, ',')) {
std::vector<std::string> v = absl::StrSplit(s, ':');
if (v.size() != 2)
return absl::InvalidArgumentError(
"Invalid stochastic filter; only 1 : accepted");
StochasticDist dist;
if (!absl::SimpleAtof(v[0], &dist.probability))
return absl::InvalidArgumentError(
"Invalid stochastic filter; unable to decode probability");
if (dist.probability < 0 || dist.probability > 1)
return absl::InvalidArgumentError(
"Invalid stochastic filter; probability should be between 0. and 1.");
total_probability += dist.probability;
if (!absl::SimpleAtoi(v[1], &dist.nb_targets))
return absl::InvalidArgumentError(
"Invalid stochastic filter; unable to decode nb_targets");
if (dist.nb_targets < 0)
return absl::InvalidArgumentError(
"Invalid stochastic filter; nb_targets should be >= 0");
rpc_def.stochastic_dist.push_back(dist);
}
if (total_probability != 1.0)
LOG(WARNING) << "The probability for the stochastic fanout of "
<< rpc_def.rpc_spec.name()
<< " does not add up to 1.0 (is "
<< total_probability << ")";
if (rpc_def.stochastic_dist.empty()) {
return absl::InvalidArgumentError(
"Invalid stochastic filter; need at least a value pair");
}
rpc_def.is_stochastic_fanout = true;
return absl::OkStatus();
}
absl::Status DistBenchEngine::InitializeRpcDefinitionsMap() {
for (int i = 0; i < traffic_config_.rpc_descriptions_size(); ++i) {
const auto& rpc_spec = traffic_config_.rpc_descriptions(i);
const auto& rpc_name = rpc_spec.name();
RpcDefinition rpc_def;
rpc_def.rpc_spec = rpc_spec;
// Get request payload size
rpc_def.request_payload_size = -1;
if (rpc_spec.has_request_payload_name()) {
const auto& payload_name = rpc_spec.request_payload_name();
rpc_def.request_payload_size = get_payload_size(payload_name);
}
if (rpc_def.request_payload_size == -1) {
rpc_def.request_payload_size = 16;
LOG(WARNING) << "No request payload defined for " << rpc_name <<
"; using a default of " <<
rpc_def.request_payload_size;
}
// Get response payload size
rpc_def.response_payload_size = -1;
if (rpc_spec.has_response_payload_name()) {
const auto& payload_name = rpc_spec.response_payload_name();
rpc_def.response_payload_size = get_payload_size(payload_name);
}
if (rpc_def.response_payload_size == -1) {
rpc_def.response_payload_size = 32;
LOG(WARNING) << "No response payload defined for " << rpc_name <<
"; using a default of " <<
rpc_def.response_payload_size;
}
auto ret = InitializeRpcDefinitionStochastic(rpc_def);
if (!ret.ok())
return ret;
rpc_map_[rpc_name] = rpc_def;
}
return absl::OkStatus();
}
absl::Status DistBenchEngine::InitializeTables() {
auto ret_init_payload = InitializePayloadsMap();
if ( !ret_init_payload.ok() )
return ret_init_payload;
auto ret_init_rpc_def = InitializeRpcDefinitionsMap();
if ( !ret_init_rpc_def.ok() )
return ret_init_rpc_def;
// Convert the action table to a map indexed by name:
std::map<std::string, Action> action_map;
for (int i = 0; i < traffic_config_.actions_size(); ++i) {
const auto& action = traffic_config_.actions(i);
action_map[action.name()] = traffic_config_.actions(i);
}
std::map<std::string, int> rpc_name_index_map =
EnumerateRpcs(traffic_config_);
std::map<std::string, int> service_index_map =
EnumerateServiceTypes(traffic_config_);
std::map<std::string, int> action_list_index_map;
action_lists_.resize(traffic_config_.action_lists().size());
for (int i = 0; i < traffic_config_.action_lists_size(); ++i) {
const auto& action_list = traffic_config_.action_lists(i);
action_list_index_map[action_list.name()] = i;
action_lists_[i].proto = action_list;
action_lists_[i].list_actions.resize(action_list.action_names_size());
}
for (int i = 0; i < traffic_config_.action_lists_size(); ++i) {
const auto& action_list = traffic_config_.action_lists(i);
std::map<std::string, int> list_action_indices;
for (int j = 0; j < action_list.action_names().size(); ++j) {
const auto& action_name = action_list.action_names(j);
list_action_indices[action_name] = j;
auto it = action_map.find(action_name);
if (it == action_map.end()) {
return absl::NotFoundError(action_name);
}
if (it->second.has_rpc_name()) {
action_lists_[i].has_rpcs = true;
// Validate rpc can be sent from this local node
}
action_lists_[i].list_actions[j].proto = it->second;
}
// second pass to fixup deps:
for (size_t j = 0; j < action_lists_[i].list_actions.size(); ++j) {
auto& action = action_lists_[i].list_actions[j];
if (action.proto.has_rpc_name()) {
auto it2 = rpc_name_index_map.find(action.proto.rpc_name());
if (it2 == rpc_name_index_map.end()) {
return absl::NotFoundError(action.proto.rpc_name());
}
action.rpc_index = it2->second;
std::string target_service_name =
traffic_config_.rpc_descriptions(action.rpc_index).server();
auto it3 = service_index_map.find(target_service_name);
if (it3 == service_index_map.end()) {
return absl::NotFoundError(target_service_name);
}
action.rpc_service_index = it3->second;
} else if (action.proto.has_action_list_name()) {
auto it4 = action_list_index_map.find(action.proto.action_list_name());
if (it4 == action_list_index_map.end()) {
return absl::InvalidArgumentError(absl::StrCat(
"Action_list not found: ", action.proto.action_list_name()));
}
action.actionlist_index = it4->second;
} else {
LOG(FATAL) << "only rpc actions are supported for now";
}
action.dependent_action_indices.resize(action.proto.dependencies_size());
for (int k = 0; k < action.proto.dependencies_size(); ++k) {
auto it = list_action_indices.find(action.proto.dependencies(k));
if (it == list_action_indices.end()) {
return absl::NotFoundError(action.proto.dependencies(k));
}
action.dependent_action_indices[k] = it->second;
if (static_cast<size_t>(it->second) >= j) {
return absl::InvalidArgumentError(
"dependencies must refer to prior actions");
}
}
}
}
client_rpc_table_ = std::make_unique<SimulatedClientRpc[]>(
traffic_config_.rpc_descriptions().size());
server_rpc_table_.resize(traffic_config_.rpc_descriptions().size());
std::map<std::string, int> client_rpc_index_map;
std::set<std::string> server_rpc_set;
for (int i = 0; i < traffic_config_.rpc_descriptions_size(); ++i) {
const auto& rpc = traffic_config_.rpc_descriptions(i);
const std::string server_service_name = rpc.server();
const std::string client_service_name = rpc.client();
if (client_service_name.empty()) {
LOG(INFO) << rpc.ShortDebugString();
return absl::InvalidArgumentError(
absl::StrCat("Rpc ", rpc.name(), " must have a client_service_name"));
}
if (server_service_name.empty()) {
return absl::InvalidArgumentError(
absl::StrCat("Rpc ", rpc.name(), " must have a server_service_name"));
}
if (client_service_name == service_name_) {
client_rpc_index_map[rpc.name()] = i;
dependent_services_.insert(server_service_name);
}
if (server_service_name == service_name_) {
server_rpc_set.insert(rpc.name());
}
auto it = action_list_index_map.find(rpc.name());
if (it == action_list_index_map.end()) {
return absl::NotFoundError(rpc.name());
}
int action_list_index = it->second;
server_rpc_table_[i].handler_action_list_index = action_list_index;
// Optimize by setting handler to -1 if the action list is empty
if (action_lists_[action_list_index].proto.action_names().empty())
server_rpc_table_[i].handler_action_list_index = action_list_index = -1;
server_rpc_table_[i].rpc_definition = rpc_map_[rpc.name()];
auto it1 = service_index_map.find(server_service_name);
if (it1 == service_index_map.end()) {
return absl::InvalidArgumentError(
absl::StrCat(
"Rpc ", rpc.name(), " specifies unknown server service_type ",
server_service_name));
}
auto it2 = service_index_map.find(client_service_name);
if (it2 == service_index_map.end()) {
return absl::InvalidArgumentError(
absl::StrCat(
"Rpc ", rpc.name(), " specifies unknown client service_type ",
client_service_name));
}
client_rpc_table_[i].service_index = it1->second;
client_rpc_table_[i].rpc_definition = rpc_map_[rpc.name()];
client_rpc_table_[i].pending_requests_per_peer.resize(
traffic_config_.services(it1->second).count(), 0);
}
return absl::OkStatus();
}
absl::Status DistBenchEngine::Initialize(
const DistributedSystemDescription& global_description,
std::string_view service_name,
int service_instance,
int* port) {
traffic_config_ = global_description;
CHECK(!service_name.empty());
service_name_ = service_name;
auto maybe_service_spec = GetServiceSpec(service_name, global_description);
if (!maybe_service_spec.ok()) return maybe_service_spec.status();
service_spec_ = maybe_service_spec.value();
service_instance_ = service_instance;
absl::Status ret = InitializeTables();
if (!ret.ok()) return ret;
// Start server
std::string server_address = absl::StrCat("[::]:", *port);
grpc::ServerBuilder builder;
builder.SetMaxReceiveMessageSize(std::numeric_limits<int32_t>::max());
std::shared_ptr<grpc::ServerCredentials> server_creds =
MakeServerCredentials();
builder.AddListeningPort(server_address, server_creds, port);
builder.AddChannelArgument(GRPC_ARG_ALLOW_REUSEPORT, 0);
builder.RegisterService(this);
server_ = builder.BuildAndStart();
server_address = absl::StrCat("[::]:", *port); // port may have changed
if (!server_) {
LOG(ERROR) << "Engine start failed on " << server_address;
return absl::UnknownError("Engine service failed to start");
}
LOG(INFO) << "Engine server listening on " << server_address;
std::map<std::string, int> services =
EnumerateServiceTypes(traffic_config_);
auto it = services.find(service_name_);
if (it == services.end()) {
LOG(ERROR) << "could not find service to run: " << service_name_;
return absl::NotFoundError("Service not found in config.");
}
service_index_ = it->second;
return absl::OkStatus();
}
absl::Status DistBenchEngine::ConfigurePeers(
const ServiceEndpointMap& peers) {
pd_->SetHandler([this](ServerRpcState* state) { RpcHandler(state);});
service_map_ = peers;
if (service_map_.service_endpoints_size() < 2) {
return absl::NotFoundError("No peers configured.");
}
return ConnectToPeers();
}
absl::Status DistBenchEngine::ConnectToPeers() {
std::map<std::string, int> service_sizes =
EnumerateServiceSizes(traffic_config_);
std::map<std::string, int> service_instance_ids =
EnumerateServiceInstanceIds(traffic_config_);
std::map<std::string, int> service_index_map =
EnumerateServiceTypes(traffic_config_);
// peers_[service_id][instance_id]
peers_.resize(traffic_config_.services_size());
for (int i = 0; i < traffic_config_.services_size(); ++i) {
peers_[i].resize(traffic_config_.services(i).count());
}
int num_targets = 0;
std::string my_name = absl::StrCat(service_name_, "/", service_instance_);
for (const auto& service : service_map_.service_endpoints()) {
auto it = service_instance_ids.find(service.first);
CHECK(it != service_instance_ids.end());
int peer_trace_id = it->second;
std::vector<std::string> service_and_instance =
absl::StrSplit(service.first, '/');
CHECK_EQ(service_and_instance.size(), 2ul);
auto& service_type = service_and_instance[0];
int instance;
CHECK(absl::SimpleAtoi(service_and_instance[1], &instance));
if (service.first == my_name) {
trace_id_ = peer_trace_id;
}
auto it2 = service_index_map.find(service_type);
CHECK(it2 != service_index_map.end());
int service_id = it2->second;
peers_[service_id][instance].log_name = service.first;
peers_[service_id][instance].trace_id = peer_trace_id;
if (dependent_services_.count(service_type)) {
peers_[service_id][instance].endpoint_address =
service.second.endpoint_address();
peers_[service_id][instance].pd_id = num_targets;
++num_targets;
}
}
pd_->SetNumPeers(num_targets);
grpc::CompletionQueue cq;
struct PendingRpc {
std::unique_ptr<ConnectionSetup::Stub> stub;
grpc::ClientContext context;
std::unique_ptr<grpc::ClientAsyncResponseReader<ConnectResponse>> rpc;
grpc::Status status;
ConnectRequest request;
ConnectResponse response;
std::string server_address;
};
grpc::Status status;
std::vector<PendingRpc> pending_rpcs(num_targets);
int rpc_count = 0;
for (const auto& service_type : peers_) {
for (const auto& service_instance : service_type) {
if (!service_instance.endpoint_address.empty()) {
auto& rpc_state = pending_rpcs[rpc_count];
std::shared_ptr<grpc::ChannelCredentials> creds =
MakeChannelCredentials();
std::shared_ptr<grpc::Channel> channel =
grpc::CreateCustomChannel(service_instance.endpoint_address, creds,
DistbenchCustomChannelArguments());
rpc_state.stub = ConnectionSetup::NewStub(channel);
rpc_state.server_address = service_instance.endpoint_address;
CHECK(rpc_state.stub);
++rpc_count;
rpc_state.request.set_initiator_info(pd_->Preconnect().value());
rpc_state.rpc = rpc_state.stub->AsyncSetupConnection(
&rpc_state.context, rpc_state.request, &cq);
rpc_state.rpc->Finish(
&rpc_state.response, &rpc_state.status, &rpc_state);
}
}
}
while (rpc_count) {
bool ok;
void* tag;
cq.Next(&tag, &ok);
if (ok) {
--rpc_count;
PendingRpc *finished_rpc = static_cast<PendingRpc*>(tag);
if (!finished_rpc->status.ok()) {
pd_->HandleConnectFailure(finished_rpc->request.initiator_info());
status = finished_rpc->status;
LOG(ERROR) << "ConnectToPeers error:"
<< finished_rpc->status.error_code()
<< " "
<< finished_rpc->status.error_message()
<< " connecting to "
<< finished_rpc->server_address;
}
}
}
for (size_t i = 0; i < pending_rpcs.size(); ++i) {
if (pending_rpcs[i].status.ok()) {
absl::Status final_status = pd_->HandleConnect(
pending_rpcs[i].response.responder_info(), i);
if (!final_status.ok()) {
LOG(INFO) << "weird, a connect failed after rpc succeeded.";
status = abslStatusToGrpcStatus(final_status);
}
}
}
return grpcStatusToAbslStatus(status);
}
absl::Status DistBenchEngine::RunTraffic(const RunTrafficRequest* request) {
if (service_map_.service_endpoints_size() < 2) {
return absl::NotFoundError("No peers configured.");
}
for (int i = 0; i < traffic_config_.action_lists_size(); ++i) {
if (service_name_ == traffic_config_.action_lists(i).name()) {
LOG(INFO) << "running Main for " << service_name_
<< "/" << service_instance_;
engine_main_thread_ = RunRegisteredThread(
"EngineMain", [this, i]() {RunActionList(i, nullptr);});
break;
}
}
return absl::OkStatus();
}
void DistBenchEngine::CancelTraffic() {
LOG(INFO) << "did the cancelation now";
canceled_.Notify();
}
void DistBenchEngine::FinishTraffic() {
if (engine_main_thread_.joinable()) {
engine_main_thread_.join();
LOG(INFO) << "Finished running Main for "
<< service_name_ << "/" << service_instance_;
}
}
ServicePerformanceLog DistBenchEngine::GetLogs() {
ServicePerformanceLog log;
for (size_t i = 0; i < peers_.size(); ++i) {
for (size_t j = 0; j < peers_[i].size(); ++j) {
absl::MutexLock m(&peers_[i][j].mutex);
if (!peers_[i][j].log.rpc_logs().empty()) {
(*log.mutable_peer_logs())[peers_[i][j].log_name] =
std::move(peers_[i][j].log);
}
}
}
return log;
}
void DistBenchEngine::RpcHandler(ServerRpcState* state) {
// LOG(INFO) << state->request->ShortDebugString();
CHECK(state->request->has_rpc_index());
const auto& simulated_server_rpc =
server_rpc_table_[state->request->rpc_index()];
const auto& rpc_def = simulated_server_rpc.rpc_definition;
state->response.set_payload(std::string(rpc_def.response_payload_size, 'D'));
int handler_action_index = simulated_server_rpc.handler_action_list_index;
if (handler_action_index == -1) {
state->send_response();
if (state->free_state) {
state->free_state();
}
return;
}
if (state->have_dedicated_thread) {
RunActionList(handler_action_index, state);
return;
}
++detached_actionlist_threads_;
RunRegisteredThread(
"DedicatedActionListThread",
[=]() {
RunActionList(handler_action_index, state);
--detached_actionlist_threads_;
}).detach();
}
void DistBenchEngine::RunActionList(
int list_index, const ServerRpcState* incoming_rpc_state) {
CHECK_LT(static_cast<size_t>(list_index), action_lists_.size());
CHECK_GE(list_index, 0);
ActionListState s;
s.incoming_rpc_state = incoming_rpc_state;
s.action_list = &action_lists_[list_index];
bool sent_response_early = false;
// Allocate peer_logs_ for performance gathering, if needed:
if (s.action_list->has_rpcs) {
s.packed_samples_size_ = s.action_list->proto.max_rpc_samples();
s.packed_samples_.reset(new PackedLatencySample[s.packed_samples_size_]);
s.remaining_initial_samples_ = s.action_list->proto.max_rpc_samples();
absl::MutexLock m(&s.action_mu);
s.peer_logs_.resize(peers_.size());
for (size_t i = 0; i < peers_.size(); ++i) {
s.peer_logs_[i].resize(peers_[i].size());
}
}
int size = s.action_list->proto.action_names_size();
s.finished_action_indices.reserve(size);
s.state_table = std::make_unique<ActionState[]>(size);
while (true) {
absl::Time now = clock_->Now();
for (int i = 0; i < size; ++i) {
if (s.state_table[i].started) {
if (s.state_table[i].next_iteration_time < now) {
StartOpenLoopIteration(&s.state_table[i]);
}
continue;
}
auto deps = s.action_list->list_actions[i].dependent_action_indices;
bool deps_ready = true;
for (const auto& dep : deps) {
if (!s.state_table[dep].finished) {
deps_ready = false;
break;
}
}
if (!deps_ready) {
continue;
}
s.state_table[i].started = true;
s.state_table[i].action = &s.action_list->list_actions[i];
if ((!sent_response_early && incoming_rpc_state) &&
((size == 1) ||
s.state_table[i].action->proto.send_response_when_done())) {
sent_response_early = true;
s.state_table[i].all_done_callback = [&s, i, incoming_rpc_state]() {
incoming_rpc_state->send_response();
s.FinishAction(i);
};
} else {
s.state_table[i].all_done_callback = [&s, i]() {s.FinishAction(i);};
}
s.state_table[i].s = &s;
RunAction(&s.state_table[i]);
}
absl::Time next_iteration_time = absl::InfiniteFuture();
bool done = true;
for (int i = 0; i < size; ++i) {
if (!s.state_table[i].finished) {
if (s.state_table[i].next_iteration_time < next_iteration_time) {
next_iteration_time = s.state_table[i].next_iteration_time;
}
done = false;
break;
}
}
if (done) {
break;
}
auto some_actions_finished = [&s]() {
return !s.finished_action_indices.empty();
};
if (clock_->MutexLockWhenWithDeadline(
&s.action_mu,
absl::Condition(&some_actions_finished), next_iteration_time)) {
if (s.finished_action_indices.empty()) {
LOG(FATAL) << "finished_action_indices is empty";
}
for (const auto& finished_action_index : s.finished_action_indices) {
s.state_table[finished_action_index].finished = true;
s.state_table[finished_action_index].next_iteration_time =
absl::InfiniteFuture();
}
s.finished_action_indices.clear();
}
s.action_mu.Unlock();
if (canceled_.HasBeenNotified()) {
LOG(INFO) << "cancelled an action list";
s.WaitForAllPendingActions();
break;
}
}
if (incoming_rpc_state) {
if (!sent_response_early) {
incoming_rpc_state->send_response();
}
if (incoming_rpc_state->free_state) {
incoming_rpc_state->free_state();
}
}
// Merge the per-action-list logs into the overall logs:
if (s.action_list->has_rpcs) {
s.UnpackLatencySamples();
absl::MutexLock m(&s.action_mu);
for (size_t i = 0; i < s.peer_logs_.size(); ++i) {
for (size_t j = 0; j < s.peer_logs_[i].size(); ++j) {
absl::MutexLock m(&peers_[i][j].mutex);
for (const auto& rpc_log : s.peer_logs_[i][j].rpc_logs()) {
(*peers_[i][j].log.mutable_rpc_logs())[rpc_log.first].MergeFrom(
rpc_log.second);
}
}
}
}
}
void DistBenchEngine::ActionListState::FinishAction(int action_index) {
action_mu.Lock();
finished_action_indices.push_back(action_index);
action_mu.Unlock();
}
void DistBenchEngine::ActionListState::WaitForAllPendingActions() {
auto some_actions_finished = [&]() {return !finished_action_indices.empty();};
bool done;
do {
action_mu.LockWhen(absl::Condition(&some_actions_finished));
finished_action_indices.clear();
done = true;
int size = action_list->proto.action_names_size();
for (int i = 0; i < size; ++i) {
const auto& state = state_table[i];
if (state.started && !state.finished) {
done = false;
break;
}
}
action_mu.Unlock();
} while (!done);
}
void DistBenchEngine::ActionListState::UnpackLatencySamples() {
absl::MutexLock m(&action_mu);
if (packed_sample_number_ <= packed_samples_size_) {
packed_samples_size_ = packed_sample_number_;
} else {
// If we did Reservoir sampling, we should sort the data:
std::sort(packed_samples_.get(),
packed_samples_.get() + packed_samples_size_);
}
for (size_t i = 0; i < packed_samples_size_; ++i) {
const auto& packed_sample = packed_samples_[i];
CHECK_LT(packed_sample.service_type, peer_logs_.size());
auto& service_log = peer_logs_[packed_sample.service_type];
CHECK_LT(packed_sample.instance, service_log.size());
auto& peer_log = service_log[packed_sample.instance];
auto& rpc_log = (*peer_log.mutable_rpc_logs())[packed_sample.rpc_index];
auto* sample = packed_sample.success ? rpc_log.add_successful_rpc_samples()
: rpc_log.add_failed_rpc_samples();
sample->set_request_size(packed_sample.request_size);
sample->set_response_size(packed_sample.response_size);
sample->set_start_timestamp_ns(packed_sample.start_timestamp_ns);
sample->set_latency_ns(packed_sample.latency_ns);
if (packed_sample.latency_weight) {
sample->set_latency_weight(packed_sample.latency_weight);
}
if (packed_sample.trace_context) {
*sample->mutable_trace_context() = *packed_sample.trace_context;
}
}
}
void DistBenchEngine::ActionListState::RecordLatency(
size_t rpc_index,
size_t service_type,
size_t instance,
ClientRpcState* state) {
// If we are using packed samples we avoid grabbing a mutex, but are limited
// in how many samples total we can collect:
if (packed_samples_size_) {
const size_t sample_number = atomic_fetch_add_explicit(
&packed_sample_number_, static_cast<long unsigned int> (1),
std::memory_order_relaxed);
size_t index = sample_number;
if (index < packed_samples_size_) {
RecordPackedLatency(
sample_number, index, rpc_index, service_type, instance, state);
atomic_fetch_sub_explicit(
&remaining_initial_samples_, static_cast<long unsigned int> (1),
std::memory_order_release);
return;
}
// Simple Reservoir Sampling:
absl::BitGen bitgen;
index = absl::Uniform(absl::IntervalClosedClosed, bitgen, 0UL, index);
if (index >= packed_samples_size_) {
// Histogram per [rpc_index, service] would be ideal here:
// Also client rpc state could point to the destination stats instead
// of requiring us to look them up below.
// dropped_rpc_count_ += 1;
// dropped_rpc_total_latency_ += latency
// dropped_rpc_request_size_ += state->request.payload().size();
// dropped_rpc_response_size_ += state->response.payload().size();
return;
}
// Wait until all initial samples are done:
while (atomic_load_explicit(
&remaining_initial_samples_, std::memory_order_acquire)) {}
// Reservoir samples are serialized.
absl::MutexLock m(&reservoir_sample_lock_);
PackedLatencySample& packed_sample = packed_samples_[index];
if (packed_sample.sample_number < sample_number) {
// Without arena allocation, via sample_arena_ we would need to do:
// delete packed_sample.trace_context;
RecordPackedLatency(
sample_number, index, rpc_index, service_type, instance, state);
}
return;
}
// Without packed samples we can support any number of samples, but then we
// also have to grab a mutex for each sample, and may have to grow the
// underlying array while holding the mutex.
absl::MutexLock m(&action_mu);
CHECK_LT(service_type, peer_logs_.size());
auto& service_log = peer_logs_[service_type];
CHECK_LT(instance, service_log.size());
auto& peer_log = service_log[instance];
auto& rpc_log = (*peer_log.mutable_rpc_logs())[rpc_index];
auto* sample = state->success ? rpc_log.add_successful_rpc_samples()
: rpc_log.add_failed_rpc_samples();
auto latency = state->end_time - state->start_time;
sample->set_start_timestamp_ns(absl::ToUnixNanos(state->start_time));
sample->set_latency_ns(absl::ToInt64Nanoseconds(latency));
if (state->prior_start_time != absl::InfinitePast()) {
sample->set_latency_weight(absl::ToInt64Nanoseconds(
state->start_time - state->prior_start_time));
}
sample->set_request_size(state->request.payload().size());
sample->set_response_size(state->response.payload().size());
if (!state->request.trace_context().engine_ids().empty()) {
*sample->mutable_trace_context() =
std::move(state->request.trace_context());
}
}
void DistBenchEngine::ActionListState::RecordPackedLatency(
size_t sample_number,
size_t index,
size_t rpc_index,
size_t service_type,
size_t instance,
ClientRpcState* state) {
PackedLatencySample& packed_sample = packed_samples_[index];
packed_sample.sample_number = sample_number;
packed_sample.trace_context = nullptr;
packed_sample.rpc_index = rpc_index;
packed_sample.service_type = service_type;
packed_sample.instance = instance;
packed_sample.success = state->success;
auto latency = state->end_time - state->start_time;
packed_sample.start_timestamp_ns = absl::ToUnixNanos(state->start_time);
packed_sample.latency_ns = absl::ToInt64Nanoseconds(latency);
packed_sample.latency_weight = 0;
if (state->prior_start_time != absl::InfinitePast()) {
packed_sample.latency_weight = absl::ToInt64Nanoseconds(
state->start_time - state->prior_start_time);
}
packed_sample.request_size = state->request.payload().size();
packed_sample.response_size = state->response.payload().size();
if (!state->request.trace_context().engine_ids().empty()) {
packed_sample.trace_context =
google::protobuf::Arena::CreateMessage<TraceContext>(&sample_arena_);
*packed_sample.trace_context = state->request.trace_context();
}
}
void DistBenchEngine::RunAction(ActionState* action_state) {
auto& action = *action_state->action;
if (action.actionlist_index >= 0) {
int action_list_index = action.actionlist_index;
action_state->iteration_function =
[this, action_list_index]
(std::shared_ptr<ActionIterationState>iteration_state) {
RunRegisteredThread(
"ActionListThread",
[this, action_list_index, iteration_state]() mutable {
RunActionList(action_list_index, nullptr);
FinishIteration(iteration_state);
}).detach();
};
} else if (action.rpc_service_index >= 0) {
CHECK_LT(static_cast<size_t>(action.rpc_service_index), peers_.size());
std::shared_ptr<ServerRpcState> server_rpc_state =
std::make_shared<ServerRpcState>();
int rpc_service_index = action.rpc_service_index;
CHECK_GE(rpc_service_index, 0);
CHECK_LT(static_cast<size_t>(rpc_service_index), peers_.size());
if (peers_[rpc_service_index].empty()) {
return;
}
action_state->rpc_index = action.rpc_index;
action_state->rpc_service_index = rpc_service_index;
action_state->iteration_function =
[this] (std::shared_ptr<ActionIterationState> iteration_state) {
RunRpcActionIteration(iteration_state);
};
} else {
LOG(FATAL) << "Do not support simulated computations yet";
}
bool open_loop = false;
int64_t max_iterations = 1;
absl::Time time_limit = absl::InfiniteFuture();
if (action.proto.has_iterations()) {
if (action.proto.iterations().has_max_iteration_count()) {
max_iterations = action.proto.iterations().max_iteration_count();
} else {
max_iterations = std::numeric_limits<int64_t>::max();
}
if (action.proto.iterations().has_max_duration_us()) {
time_limit = clock_->Now() + absl::Microseconds(
action.proto.iterations().max_duration_us());
}
open_loop = action.proto.iterations().has_open_loop_interval_ns();
}
if (max_iterations < 1) {
LOG(WARNING) << "an action had a weird number of iterations";
}
action_state->iteration_mutex.Lock();
action_state->iteration_limit = max_iterations;
action_state->time_limit = time_limit;
action_state->next_iteration = 0;
action_state->iteration_mutex.Unlock();
if (open_loop) {
CHECK_EQ(action_state->next_iteration_time, absl::InfiniteFuture());
absl::Duration period = absl::Nanoseconds(
action_state->action->proto.iterations().open_loop_interval_ns());
auto& interval_distribution = action_state->action->proto.iterations()
.open_loop_interval_distribution();
if (interval_distribution == "sync_burst") {
absl::Duration start = clock_->Now() - absl::UnixEpoch();
action_state->next_iteration_time =
period + absl::UnixEpoch() + absl::Floor(start, period);
} else if (interval_distribution == "sync_burst_spread") {
absl::Duration start = clock_->Now() - absl::UnixEpoch();
double nb_peers = peers_[action_state->rpc_service_index].size();
double fraction = service_instance_ / nb_peers;
LOG(INFO) << "sync_burst_spread burst delay: " << fraction * period;
action_state->next_iteration_time =
period + absl::UnixEpoch() + absl::Floor(start, period) +
fraction * period;
} else {
action_state->next_iteration_time = clock_->Now();
StartOpenLoopIteration(action_state);
}
} else {
int64_t parallel_copies = std::min(
action.proto.iterations().max_parallel_iterations(), max_iterations);
action_state->iteration_mutex.Lock();
action_state->next_iteration = parallel_copies;
action_state->iteration_mutex.Unlock();
for (int i = 0; i < parallel_copies; ++i) {
auto it_state = std::make_shared<ActionIterationState>();
it_state->action_state = action_state;
it_state->iteration_number = i;
StartIteration(it_state);
}
}
}
void DistBenchEngine::StartOpenLoopIteration(ActionState* action_state) {
absl::Duration period = absl::Nanoseconds(
action_state->action->proto.iterations().open_loop_interval_ns());
auto it_state = std::make_shared<ActionIterationState>();
it_state->action_state = action_state;
action_state->iteration_mutex.Lock();
action_state->next_iteration_time += period;
if (action_state->next_iteration_time > action_state->time_limit) {
action_state->next_iteration_time = absl::InfiniteFuture();
}
it_state->iteration_number = ++action_state->next_iteration;
action_state->iteration_mutex.Unlock();
StartIteration(it_state);
}
void DistBenchEngine::FinishIteration(
std::shared_ptr<ActionIterationState> iteration_state) {
ActionState* state = iteration_state->action_state;
bool open_loop =
state->action->proto.iterations().has_open_loop_interval_ns();
bool start_another_iteration = !open_loop;
bool done = false;
state->iteration_mutex.Lock();
++state->finished_iterations;
if (state->next_iteration == state->iteration_limit) {
done = true;
start_another_iteration = false;
} else if (!open_loop) {
// Closed loop iteration:
if (state->time_limit != absl::InfiniteFuture()) {
if (clock_->Now() > state->time_limit) {
done = true;
start_another_iteration = false;
}
}
} else {
// Open loop (possibly sync_burst) iteration:
if (state->next_iteration_time > state->time_limit) {
done = true;
start_another_iteration = false;
}
}
if (start_another_iteration) {
++state->next_iteration;
}
int pending_iterations = state->next_iteration - state->finished_iterations;
state->iteration_mutex.Unlock();
if (done && !pending_iterations) {
state->all_done_callback();
} else if (start_another_iteration) {
StartIteration(iteration_state);
}
}
void DistBenchEngine::StartIteration(
std::shared_ptr<ActionIterationState> iteration_state) {
iteration_state->action_state->iteration_function(iteration_state);
}
// This works fine for 1-at-a-time closed-loop iterations:
void DistBenchEngine::RunRpcActionIteration(
std::shared_ptr<ActionIterationState> iteration_state) {
ActionState* state = iteration_state->action_state;
// Pick the subset of the target service instances to fanout to:
std::vector<int> current_targets = PickRpcFanoutTargets(state);
iteration_state->rpc_states.resize(current_targets.size());
iteration_state->remaining_rpcs = current_targets.size();
// Setup tracing:
const auto& rpc_def = client_rpc_table_[state->rpc_index].rpc_definition;
const auto& rpc_spec = rpc_def.rpc_spec;
bool do_trace = false;
int trace_count = ++client_rpc_table_[state->rpc_index].rpc_tracing_counter;
if (rpc_spec.tracing_interval() > 0) {
do_trace = (trace_count % rpc_spec.tracing_interval()) == 0;
}
GenericRequest common_request;
if (state->s->incoming_rpc_state) {
*common_request.mutable_trace_context() =
state->s->incoming_rpc_state->request->trace_context();
} else if (do_trace) {
common_request.mutable_trace_context()->add_engine_ids(trace_id_);
common_request.mutable_trace_context()->add_iterations(
iteration_state->iteration_number);
}
common_request.set_rpc_index(state->rpc_index);
common_request.set_payload(std::string(rpc_def.request_payload_size, 'D'));
const auto& servers = peers_[state->rpc_service_index];
for (size_t i = 0; i < current_targets.size(); ++i) {
int peer_instance = current_targets[i];
ClientRpcState* rpc_state;
{
absl::MutexLock m(&peers_[state->rpc_service_index][peer_instance].mutex);
rpc_state = &iteration_state->rpc_states[i];
rpc_state->request = common_request;
if (!common_request.trace_context().engine_ids().empty()) {
rpc_state->request.mutable_trace_context()->add_engine_ids(
peers_[state->rpc_service_index][peer_instance].trace_id);
rpc_state->request.mutable_trace_context()->add_iterations(i);
}
CHECK_EQ(rpc_state->request.trace_context().engine_ids().size(),
rpc_state->request.trace_context().iterations().size());
} // End of MutexLock m
rpc_state->prior_start_time = rpc_state->start_time;
rpc_state->start_time = clock_->Now();
pd_->InitiateRpc(servers[peer_instance].pd_id, rpc_state,
[this, rpc_state, iteration_state, peer_instance]() mutable {
ActionState* state = iteration_state->action_state;
rpc_state->end_time = clock_->Now();
state->s->RecordLatency(
state->rpc_index,
state->rpc_service_index,
peer_instance,
rpc_state);
if (--iteration_state->remaining_rpcs == 0) {
FinishIteration(iteration_state);
}
});
}
}
// Return a vector of service instances, which have to be translated to
// protocol_drivers endpoint ids by the caller.
std::vector<int> DistBenchEngine::PickRpcFanoutTargets(ActionState* state) {
const auto& rpc_def = client_rpc_table_[state->rpc_index].rpc_definition;
const auto& rpc_spec = rpc_def.rpc_spec;
std::vector<int> targets;
int num_servers = peers_[state->rpc_service_index].size();
const std::string& fanout_filter = rpc_spec.fanout_filter();
if (rpc_def.is_stochastic_fanout) {
std::map<int, std::vector<int>> partial_rand_vects =
state->partially_randomized_vectors;
int nb_targets = 0;
float random_val = absl::Uniform(random_generator, 0, 1.0);
float cur_val = 0.0;
for (const auto &d : rpc_def.stochastic_dist) {
cur_val += d.probability;
if (random_val <= cur_val) {
nb_targets = d.nb_targets;
break;
}
}
if (nb_targets > num_servers)
nb_targets = num_servers;
// Generate a vector to pick random targets from (only done once)
partial_rand_vects.try_emplace(num_servers, std::vector<int>());
std::vector<int>& from_vector = partial_rand_vects[num_servers];
if (from_vector.empty()) {
for (int i = 0; i < num_servers; i++)
from_vector.push_back(i);
}
// Randomize and pick up to nb_targets
for (int i = 0; i < nb_targets; i++) {
int rnd_pos = i + (random() % (num_servers - i));
std::swap(from_vector[i], from_vector[rnd_pos]);
int target = from_vector[i];
CHECK_NE(target, -1);
targets.push_back(target);
}
} else if (fanout_filter == "all") {
targets.reserve(num_servers);
for (int i = 0; i < num_servers; ++i) {
int target = i;
if (state->rpc_service_index != service_index_ ||
target != service_instance_) {
CHECK_NE(target, -1);
targets.push_back(target);
}
}
} else { // The following fanout options return 1 target
int target;
targets.reserve(1);
if (fanout_filter == "random") {
target = random() % num_servers;
} else if (fanout_filter == "round_robin") {
int64_t iteration =
client_rpc_table_[state->rpc_index].rpc_tracing_counter;
target = iteration % num_servers;
} else {
// Default case: return the first instance of the service
target = 0;
}
CHECK_NE(target, -1);
targets.push_back(target);
}
return targets;
}
} // namespace distbench
| 37.199828 | 80 | 0.677233 | [
"vector"
] |
7a052bc27dfab2a1cdf9205eb33809ac0c44289f | 8,527 | cpp | C++ | libsrc/leddevice/LedDevicePhilipsHueEntertainment.cpp | Sneezoo/hyperion | ece0fda7c572cb435c9c853c29630a7bf188a665 | [
"MIT"
] | null | null | null | libsrc/leddevice/LedDevicePhilipsHueEntertainment.cpp | Sneezoo/hyperion | ece0fda7c572cb435c9c853c29630a7bf188a665 | [
"MIT"
] | null | null | null | libsrc/leddevice/LedDevicePhilipsHueEntertainment.cpp | Sneezoo/hyperion | ece0fda7c572cb435c9c853c29630a7bf188a665 | [
"MIT"
] | null | null | null | #include "LedDevicePhilipsHueEntertainment.h"
// jsoncpp includes
#include <json/json.h>
// Qt includes
#include <QDebug>
#include <QDebug>
// Mbedtls
#include "mbedtls/net_sockets.h"
#include "mbedtls/debug.h"
#include "mbedtls/ssl.h"
#include "mbedtls/entropy.h"
#include "mbedtls/ctr_drbg.h"
#include "mbedtls/error.h"
#include "mbedtls/certs.h"
#include "mbedtls/timing.h"
#include "mbedtls/config.h"
LedDevicePhilipsHueEntertainment::LedDevicePhilipsHueEntertainment(const std::string &output,
const std::string &username,
const std::string &clientkey,
unsigned int groupId)
: LedDevicePhilipsHue(output, username, false, 1),
clientkey(clientkey.c_str()),
groupId(groupId) {
QByteArray response = get(getGroupRoute(groupId));
//qDebug() << response;
Json::Reader reader;
Json::Value json;
if (!reader.parse(QString(response).toStdString(), json)) {
throw std::runtime_error(("Error getting lights from group " + getUrl(getGroupRoute(groupId))).toStdString());
}
if(json["type"] != "Entertainment") {
throw std::runtime_error("Given group is no entertainment group");
}
Json::Value lightsArray = json["lights"];
// Loop over all children.
for (Json::ValueIterator it = lightsArray.begin(); it != lightsArray.end(); it++) {
lightIds.push_back(atoi(lightsArray[it.index()].asCString()));
}
saveStates(lightIds.size());
switchOn(0);
worker = new HueEntertainmentWorker(output, username, clientkey, &lights);
worker->start();
}
LedDevicePhilipsHueEntertainment::~LedDevicePhilipsHueEntertainment() {
worker->terminate();
worker->wait();
delete worker;
}
int LedDevicePhilipsHueEntertainment::write(const std::vector <ColorRgb> &ledValues) {
worker->ledValues = ledValues;
unsigned int idx = 0;
for (const ColorRgb& color : ledValues) {
// Get lamp.
PhilipsHueLight& lamp = lights.at(idx);
// Scale colors from [0, 255] to [0, 1] and convert to xy space.
CiColor xy = lamp.rgbToCiColor(color.red / 255.0f, color.green / 255.0f, color.blue / 255.0f);
if(xy != lamp.color) {
// Remember last color.
lamp.color = xy;
}
// Next light id.
idx++;
}
return 0;
}
int LedDevicePhilipsHueEntertainment::switchOff() {
put(getGroupRoute(groupId), "{\"stream\":{\"active\":false}}");
return 0;
}
void LedDevicePhilipsHueEntertainment::switchOn(unsigned int nLights) {
put(getGroupRoute(groupId), "{\"stream\":{\"active\":true}}");
}
QString LedDevicePhilipsHueEntertainment::getGroupRoute(unsigned int groupId) {
return QString("groups/%1").arg(groupId);
}
HueEntertainmentWorker::HueEntertainmentWorker(const std::string &output,
const std::string &username,
const std::string &clientkey,
std::vector<PhilipsHueLight>* lights): output(output.c_str()),
username(username.c_str()),
clientkey(clientkey.c_str()),
lights(lights) {
}
void HueEntertainmentWorker::run() {
int ret;
const char *pers = "dtls_client";
mbedtls_net_context server_fd;
mbedtls_ssl_context ssl;
mbedtls_entropy_context entropy;
mbedtls_ctr_drbg_context ctr_drbg;
mbedtls_ssl_config conf;
mbedtls_x509_crt cacert;
mbedtls_timing_delay_context timer;
mbedtls_debug_set_threshold(1000);
/*
* -1. Load psk
*/
QByteArray pskArray = clientkey.toUtf8();
QByteArray pskRawArray = QByteArray::fromHex(pskArray);
QByteArray pskIdArray = username.toUtf8();
QByteArray pskIdRawArray = pskIdArray;
/*
* 0. Initialize the RNG and the session data
*/
mbedtls_net_init(&server_fd);
mbedtls_ssl_init(&ssl);
mbedtls_ssl_config_init(&conf);
mbedtls_x509_crt_init(&cacert);
mbedtls_ctr_drbg_init(&ctr_drbg);
mbedtls_entropy_init(&entropy);
if ((ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy,
(const unsigned char *)pers,
strlen(pers))) != 0)
{
qFatal("mbedtls_ctr_drbg_seed returned %d", ret);
}
/*
* 1. Start the connection
*/
if ((ret = mbedtls_net_connect(&server_fd, output.toUtf8(),
"2100", MBEDTLS_NET_PROTO_UDP)) != 0)
{
qFatal("mbedtls_net_connect FAILED %d", ret);
}
/*
* 2. Setup stuff
*/
if ((ret = mbedtls_ssl_config_defaults(&conf,
MBEDTLS_SSL_IS_CLIENT,
MBEDTLS_SSL_TRANSPORT_DATAGRAM,
MBEDTLS_SSL_PRESET_DEFAULT)) != 0)
{
qFatal("mbedtls_ssl_config_defaults FAILED %d", ret);
}
mbedtls_ssl_conf_authmode(&conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
mbedtls_ssl_conf_ca_chain(&conf, &cacert, NULL);
mbedtls_ssl_conf_rng(&conf, mbedtls_ctr_drbg_random, &ctr_drbg);
if ((ret = mbedtls_ssl_setup(&ssl, &conf)) != 0)
{
qFatal("mbedtls_ssl_setup FAILED %d", ret);
}
if (0 != (ret = mbedtls_ssl_conf_psk(&conf, (const unsigned char*)pskRawArray.data(), pskRawArray.length() * sizeof(char),
(const unsigned char *)pskIdRawArray.data(), pskIdRawArray.length() * sizeof(char))))
{
qFatal("mbedtls_ssl_conf_psk FAILED %d", ret);
}
int ciphers[2];
ciphers[0] = MBEDTLS_TLS_PSK_WITH_AES_128_GCM_SHA256;
ciphers[1] = 0;
mbedtls_ssl_conf_ciphersuites(&conf, ciphers);
if ((ret = mbedtls_ssl_set_hostname(&ssl, "Hue")) != 0)
{
qCritical("mbedtls_ssl_set_hostname FAILED", ret);
}
mbedtls_ssl_set_bio(&ssl, &server_fd,
mbedtls_net_send, mbedtls_net_recv, mbedtls_net_recv_timeout);
mbedtls_ssl_set_timer_cb(&ssl, &timer, mbedtls_timing_set_delay,
mbedtls_timing_get_delay);
/*
* 4. Handshake
*/
for (int attempt = 0; attempt < 4; ++attempt)
{
mbedtls_ssl_conf_handshake_timeout(&conf, 400, 1000);
do ret = mbedtls_ssl_handshake(&ssl);
while (ret == MBEDTLS_ERR_SSL_WANT_READ ||
ret == MBEDTLS_ERR_SSL_WANT_WRITE);
if (ret == 0)
break;
}
if (ret != 0)
{
qFatal("mbedtls_ssl_handshake FAILED %d", ret);
}
char header[] = {
'H', 'u', 'e', 'S', 't', 'r', 'e', 'a', 'm', //protocol
0x01, 0x00, //version 1.0
0x01, //sequence number 1
0x00, 0x00, //reserved
0x01, //color mode RGB
0x00, //linear filter
};
while (true)
{
QByteArray Msg;
Msg.append(header, sizeof(header));
unsigned int idx = 0;
for (const PhilipsHueLight& lamp : *lights) {
quint64 R = lamp.color.x * 0xffff;
quint64 G = lamp.color.y * 0xffff;
quint64 B = lamp.color.bri * 0xffff;
char light_stream[] = {
0x00, 0x00, (char)lamp.id, //light ID 1
static_cast<uint8_t>((R >> 8) & 0xff), static_cast<uint8_t>(R & 0xff),
static_cast<uint8_t>((G >> 8) & 0xff), static_cast<uint8_t>(G & 0xff),
static_cast<uint8_t>((B >> 8) & 0xff), static_cast<uint8_t>(B & 0xff)
};
Msg.append(light_stream, sizeof(light_stream));
idx++;
}
int len = Msg.size();
do ret = mbedtls_ssl_write(&ssl, (unsigned char *) Msg.data(), len);
while (ret == MBEDTLS_ERR_SSL_WANT_READ ||
ret == MBEDTLS_ERR_SSL_WANT_WRITE);
if(ret < 0) {
break;
}
QThread::msleep(30);
}
mbedtls_net_free(&server_fd);
mbedtls_x509_crt_free(&cacert);
mbedtls_ssl_free(&ssl);
mbedtls_ssl_config_free(&conf);
mbedtls_ctr_drbg_free(&ctr_drbg);
mbedtls_entropy_free(&entropy);
} | 32.056391 | 126 | 0.570072 | [
"vector"
] |
7a08a9ed66d543dfcb88560871fcbe8c91c98b7d | 1,921 | hpp | C++ | tests/assertions.hpp | tinyplasticgreyknight/fieldmapgen | 0fda12b71f5f6ce9fdb3f576d1cbc85b459b5ef8 | [
"MIT"
] | null | null | null | tests/assertions.hpp | tinyplasticgreyknight/fieldmapgen | 0fda12b71f5f6ce9fdb3f576d1cbc85b459b5ef8 | [
"MIT"
] | 4 | 2016-08-13T23:16:14.000Z | 2016-08-13T23:33:45.000Z | tests/assertions.hpp | tinyplasticgreyknight/fieldmapgen | 0fda12b71f5f6ce9fdb3f576d1cbc85b459b5ef8 | [
"MIT"
] | null | null | null | #ifndef H_ASSERTIONS
#define H_ASSERTIONS
#include <string>
#include <sstream>
#include <vector>
namespace test_support {
int assert_failed(std::string message, std::string filename, int line_number);
template <typename T>
std::string assert_value_to_string(const T& value);
std::string assert_format_internal(std::string left_name, std::string relation, std::string right_name, std::string left_val, std::string right_val);
template <typename T>
std::string assert_format(std::string left_name, std::string relation, std::string right_name, const T& left_val, const T& right_val);
#include "assertions.tmpl.hpp"
}
#define ASSERT_GENERAL(a, msg) if (!(a)) { return test_support::assert_failed(msg, __FILE__, __LINE__); }
#define ASSERT_THAT(a) ASSERT_GENERAL(a, #a)
#define ASSERT_TRUE(p) ASSERT_GENERAL(p, "expected true:\nexpression: " #p)
#define ASSERT_SOME(T, exp, opt) ASSERT_EQ(Some(exp), (opt))
#define ASSERT_NONE(T, opt) ASSERT_EQ(None<T>(), (opt))
#define ASSERT_EMPTY(coll) ASSERT_GENERAL((coll).empty(), "expected empty collection\nexpression: " #coll)
#define ASSERT_LIST_EQ(expected, actual) do { \
auto __assertion_exp = expected; \
auto __assertion_exp_iter = __assertion_exp.begin(); \
for (auto __assertion_item : actual) { \
ASSERT_GENERAL(__assertion_exp_iter != __assertion_exp.end(), "expected same size: actual was too big\nexpression: " #actual); \
ASSERT_EQ(__assertion_item, *__assertion_exp_iter); \
__assertion_exp_iter++; \
} \
ASSERT_GENERAL(__assertion_exp_iter == __assertion_exp.end(), "expected same size: actual was too small\nexpression: " #actual); \
} while(0)
#define ASSERT_EQ(expected, actual) do { \
auto __assertion_exp = (expected); \
auto __assertion_act = (actual); \
ASSERT_GENERAL(__assertion_exp == __assertion_act, test_support::assert_format("expected", "==", "actual", __assertion_exp, __assertion_act)); \
} while(0)
#endif
| 40.87234 | 150 | 0.745966 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.