hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 77k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 653k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
739be0511a8c2d7671de887ce70681e779f65c2a | 323 | hpp | C++ | include/result/version.hpp | cmrobotics/result | 89f2fdfdb9708fad9e794d6af3f705c4af420e7d | [
"MIT"
] | null | null | null | include/result/version.hpp | cmrobotics/result | 89f2fdfdb9708fad9e794d6af3f705c4af420e7d | [
"MIT"
] | null | null | null | include/result/version.hpp | cmrobotics/result | 89f2fdfdb9708fad9e794d6af3f705c4af420e7d | [
"MIT"
] | null | null | null | #ifndef RESULT_VERSION_HPP
#define RESULT_VERSION_HPP
#pragma once
#define RESULT_VERSION_MAJOR 0
#define RESULT_VERSION_MINOR 2
#define RESULT_VERSION_PATCH 0
#define RESULT_VERSION_CODE (RESULT_VERSION_MAJOR * 10000 + RESULT_VERSION_MINOR * 100 + RESULT_VERSION_PATCH)
#define RESULT_VERSION_STRING "0.2.0"
#endif
| 19 | 110 | 0.826625 |
739cc68ea31cdfc8a7f343f0ff8d06187bcf0767 | 22,188 | cpp | C++ | src/demos/sensor/demo_SEN_Gator.cpp | lucasw/chrono | e79d8c761c718ecb4c796725cff37026f357da8c | [
"BSD-3-Clause"
] | null | null | null | src/demos/sensor/demo_SEN_Gator.cpp | lucasw/chrono | e79d8c761c718ecb4c796725cff37026f357da8c | [
"BSD-3-Clause"
] | null | null | null | src/demos/sensor/demo_SEN_Gator.cpp | lucasw/chrono | e79d8c761c718ecb4c796725cff37026f357da8c | [
"BSD-3-Clause"
] | null | null | null | // =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban
// =============================================================================
//
// Main driver function for the Gator full model.
//
// The vehicle reference frame has Z up, X towards the front of the vehicle, and
// Y pointing to the left.
//
// =============================================================================
#include "chrono/core/ChRealtimeStep.h"
#include "chrono/utils/ChUtilsInputOutput.h"
#include "chrono/physics/ChBodyEasy.h"
#include "chrono_vehicle/ChVehicleModelData.h"
#include "chrono_vehicle/terrain/RigidTerrain.h"
#include "chrono_vehicle/driver/ChIrrGuiDriver.h"
#include "chrono_vehicle/wheeled_vehicle/utils/ChWheeledVehicleVisualSystemIrrlicht.h"
#include "chrono_models/vehicle/gator/Gator.h"
#include "chrono_models/vehicle/gator/Gator_SimplePowertrain.h"
#include "chrono_thirdparty/filesystem/path.h"
#include "chrono_sensor/sensors/ChCameraSensor.h"
#include "chrono_sensor/sensors/ChLidarSensor.h"
#include "chrono_sensor/ChSensorManager.h"
#include "chrono_sensor/filters/ChFilterAccess.h"
#include "chrono_sensor/filters/ChFilterPCfromDepth.h"
#include "chrono_sensor/filters/ChFilterVisualize.h"
#include "chrono_sensor/filters/ChFilterSave.h"
#include "chrono_sensor/filters/ChFilterSavePtCloud.h"
#include "chrono_sensor/filters/ChFilterVisualizePointCloud.h"
#include "chrono_sensor/sensors/ChGPSSensor.h"
#include "chrono_sensor/sensors/ChIMUSensor.h"
#include "chrono_sensor/sensors/ChNoiseModel.h"
#include "chrono_sensor/filters/ChFilterAccess.h"
#include "chrono_sensor/filters/ChFilterVisualize.h"
using namespace chrono;
using namespace chrono::irrlicht;
using namespace chrono::vehicle;
using namespace chrono::vehicle::gator;
using namespace chrono::sensor;
// =============================================================================
// Initial vehicle location and orientation
ChVector<> initLoc(0, 0, 0.5);
ChQuaternion<> initRot(1, 0, 0, 0);
// Visualization type for vehicle parts (PRIMITIVES, MESH, or NONE)
VisualizationType chassis_vis_type = VisualizationType::MESH;
VisualizationType suspension_vis_type = VisualizationType::PRIMITIVES;
VisualizationType steering_vis_type = VisualizationType::PRIMITIVES;
VisualizationType wheel_vis_type = VisualizationType::NONE;
VisualizationType tire_vis_type = VisualizationType::MESH;
// Collision type for chassis (PRIMITIVES, HULLS, or NONE)
CollisionType chassis_collision_type = CollisionType::NONE;
// Type of tire model (RIGID, TMEASY)
TireModelType tire_model = TireModelType::TMEASY;
// Rigid terrain
RigidTerrain::PatchType terrain_model = RigidTerrain::PatchType::BOX;
// Contact method
ChContactMethod contact_method = ChContactMethod::NSC;
// Simulation step sizes
double step_size = 1e-3;
double tire_step_size = step_size;
// Time interval between two render frames
double render_step_size = 1.0 / 50; // FPS = 50
// Output directories
const std::string out_dir = GetChronoOutputPath() + "Gator";
const std::string pov_dir = out_dir + "/POVRAY";
const std::string sens_dir = out_dir + "/SENSOR_OUTPUT";
// POV-Ray output
bool povray_output = false;
// SENSOR PARAMETERS
// Save sensor data
bool sensor_save = false;
// Visualize sensor data
bool sensor_vis = true;
// Update rates of each sensor in Hz
float cam_update_rate = 30.f;
float lidar_update_rate = 10.f;
float exposure_time = 0.02f;
int super_samples = 2;
// Image width and height
unsigned int image_width = 1280;
unsigned int image_height = 720;
// Lidar horizontal and vertical samples
unsigned int horizontal_samples = 4500;
unsigned int vertical_samples = 32;
// Camera's horizontal field of view
float cam_fov = 1.408f;
// Lidar's horizontal and vertical fov
float lidar_hfov = (float)(2 * CH_C_PI); // 360 degrees
float lidar_vmax = (float)(CH_C_PI / 12); // 15 degrees up
float lidar_vmin = (float)(-CH_C_PI / 6); // 30 degrees down
// -----------------------------------------------------------------------------
// IMU parameters
// -----------------------------------------------------------------------------
// Noise model attached to the sensor
enum IMUNoiseModel {
NORMAL_DRIFT, // gaussian drifting noise with noncorrelated equal distributions
IMU_NONE // no noise added
};
IMUNoiseModel imu_noise_type = NORMAL_DRIFT;
// IMU update rate in Hz
float imu_update_rate = 100.0f;
// IMU lag (in seconds) between sensing and when data becomes accessible
float imu_lag = 0.f;
// IMU collection time (in seconds) of each sample
float imu_collection_time = 0.f;
// -----------------------------------------------------------------------------
// GPS parameters
// -----------------------------------------------------------------------------
// Noise model attached to the sensor
enum class GPSNoiseModel {
NORMAL, // individually parameterized independent gaussian distribution
GPS_NONE, // no noise model
};
GPSNoiseModel gps_noise_type = GPSNoiseModel::GPS_NONE;
// GPS update rate in Hz
float gps_update_rate = 10.0f;
// Camera's horizontal field of view
float fov = 1.408f;
// GPS lag (in seconds) between sensing and when data becomes accessible
float gps_lag = 0.f;
// Collection time (in seconds) of eacn sample
float gps_collection_time = 0.f;
// Origin used as the gps reference point
// Located in Madison, WI
ChVector<> gps_reference(-89.400, 43.070, 260.0);
// ---------------
// =============================================================================
int main(int argc, char* argv[]) {
GetLog() << "Copyright (c) 2017 projectchrono.org\nChrono version: " << CHRONO_VERSION << "\n\n";
// --------------
// Create vehicle
// --------------
Gator gator;
gator.SetContactMethod(contact_method);
gator.SetChassisCollisionType(chassis_collision_type);
gator.SetChassisFixed(false);
gator.SetInitPosition(ChCoordsys<>(initLoc, initRot));
gator.SetTireType(tire_model);
gator.SetTireStepSize(tire_step_size);
gator.SetAerodynamicDrag(0.5, 5.0, 1.2);
gator.Initialize();
gator.SetChassisVisualizationType(chassis_vis_type);
gator.SetSuspensionVisualizationType(suspension_vis_type);
gator.SetSteeringVisualizationType(steering_vis_type);
gator.SetWheelVisualizationType(wheel_vis_type);
gator.SetTireVisualizationType(tire_vis_type);
// ------------------
// Create the terrain
// ------------------
RigidTerrain terrain(gator.GetSystem());
MaterialInfo minfo;
minfo.mu = 0.9f;
minfo.cr = 0.01f;
minfo.Y = 2e7f;
auto patch_mat = minfo.CreateMaterial(contact_method);
std::shared_ptr<RigidTerrain::Patch> patch;
switch (terrain_model) {
case RigidTerrain::PatchType::BOX:
patch = terrain.AddPatch(patch_mat, ChVector<>(0, 0, 0), ChVector<>(0, 0, 1), 100.0, 100.0);
patch->SetTexture(vehicle::GetDataFile("terrain/textures/tile4.jpg"), 200, 200);
break;
case RigidTerrain::PatchType::HEIGHT_MAP:
patch = terrain.AddPatch(patch_mat, CSYSNORM, vehicle::GetDataFile("terrain/height_maps/test64.bmp"), 128,
128, 0, 4);
patch->SetTexture(vehicle::GetDataFile("terrain/textures/grass.jpg"), 16, 16);
break;
case RigidTerrain::PatchType::MESH:
patch = terrain.AddPatch(patch_mat, CSYSNORM, vehicle::GetDataFile("terrain/meshes/test.obj"));
patch->SetTexture(vehicle::GetDataFile("terrain/textures/grass.jpg"), 100, 100);
break;
}
patch->SetColor(ChColor(0.8f, 0.8f, 0.5f));
terrain.Initialize();
// -------------------------------------
// Create the vehicle Irrlicht interface
// -------------------------------------
auto vis = chrono_types::make_shared<ChWheeledVehicleVisualSystemIrrlicht>();
vis->SetWindowTitle("Gator Demo");
vis->SetChaseCamera(ChVector<>(0.0, 0.0, 2.0), 5.0, 0.05);
vis->Initialize();
vis->AddTypicalLights();
vis->AddSkyBox();
vis->AddLogo();
gator.GetVehicle().SetVisualSystem(vis);
// -----------------
// Initialize output
// -----------------
if (povray_output) {
if (!filesystem::create_directory(filesystem::path(out_dir))) {
std::cout << "Error creating directory " << out_dir << std::endl;
return 1;
}
if (!filesystem::create_directory(filesystem::path(pov_dir))) {
std::cout << "Error creating directory " << pov_dir << std::endl;
return 1;
}
terrain.ExportMeshPovray(out_dir);
}
// ------------------------
// Create the driver system
// ------------------------
// Create the interactive driver system
ChIrrGuiDriver driver(*vis);
// Set the time response for steering and throttle keyboard inputs.
double steering_time = 1.0; // time to go from 0 to +1 (or from 0 to -1)
double throttle_time = 1.0; // time to go from 0 to +1
double braking_time = 0.3; // time to go from 0 to +1
driver.SetSteeringDelta(render_step_size / steering_time);
driver.SetThrottleDelta(render_step_size / throttle_time);
driver.SetBrakingDelta(render_step_size / braking_time);
driver.Initialize();
auto manager = chrono_types::make_shared<ChSensorManager>(gator.GetSystem());
manager->scene->AddPointLight({100, 100, 100}, {2, 2, 2}, 5000);
Background b;
b.mode = BackgroundMode::ENVIRONMENT_MAP;
b.env_tex = GetChronoDataFile("sensor/textures/quarry_01_4k.hdr");
manager->scene->SetBackground(b);
// third person camera
auto cam = chrono_types::make_shared<ChCameraSensor>(
gator.GetChassisBody(), // body camera is attached to
cam_update_rate, // update rate in Hz
chrono::ChFrame<double>({-8, 0, 3}, Q_from_AngAxis(.2, {0, 1, 0})), // offset pose
image_width, // image width
image_height, // image height
cam_fov,
super_samples); // fov, lag, exposure
cam->SetName("3rd Person Camera Sensor");
cam->SetCollectionWindow(exposure_time);
if (sensor_vis)
cam->PushFilter(chrono_types::make_shared<ChFilterVisualize>(image_width, image_height, "Third-person View"));
if (sensor_save)
cam->PushFilter(chrono_types::make_shared<ChFilterSave>(sens_dir + "/cam1/"));
cam->PushFilter(chrono_types::make_shared<ChFilterRGBA8Access>());
manager->AddSensor(cam);
// roof mounted camera .1, 0, 1.45
auto cam2 = chrono_types::make_shared<ChCameraSensor>(
gator.GetChassisBody(), // body camera is attached to
cam_update_rate, // update rate in Hz
chrono::ChFrame<double>({.1, 0, 1.45}, Q_from_AngAxis(.2, {0, 1, 0})), // offset pose
image_width, // image width
image_height, // image height
cam_fov,
super_samples); // fov, lag, exposure
cam2->SetName("Camera Sensor");
cam2->SetCollectionWindow(exposure_time);
if (sensor_vis)
cam2->PushFilter(
chrono_types::make_shared<ChFilterVisualize>(image_width, image_height, "Front-facing Camera"));
if (sensor_save)
cam2->PushFilter(chrono_types::make_shared<ChFilterSave>(sens_dir + "/cam2/"));
cam2->PushFilter(chrono_types::make_shared<ChFilterRGBA8Access>());
manager->AddSensor(cam2);
auto lidar = chrono_types::make_shared<ChLidarSensor>(
gator.GetChassisBody(), // body to which the IMU is attached
lidar_update_rate, // update rate
chrono::ChFrame<double>({-.282, 0, 1.82}, Q_from_AngAxis(0, {1, 0, 0})), // offset pose from body
horizontal_samples, // horizontal samples
vertical_samples, // vertical samples/channels
lidar_hfov, // horizontal field of view
lidar_vmax, // vertical field of view
lidar_vmin, // vertical field of view
100.0f, // max distance
LidarBeamShape::RECTANGULAR, // beam shape
1, //
0.0f, //
0.0f,
LidarReturnMode::STRONGEST_RETURN, //
0.1f //
);
lidar->SetName("Lidar Sensor");
lidar->SetLag(1 / lidar_update_rate);
lidar->SetCollectionWindow(0);
if (sensor_vis)
lidar->PushFilter(
chrono_types::make_shared<ChFilterVisualize>(horizontal_samples, vertical_samples, "Raw Lidar Data"));
lidar->PushFilter(chrono_types::make_shared<ChFilterPCfromDepth>());
if (sensor_vis)
lidar->PushFilter(chrono_types::make_shared<ChFilterVisualizePointCloud>(640, 480, 0.5f, "Lidar Point Cloud"));
if (sensor_save)
lidar->PushFilter(chrono_types::make_shared<ChFilterSavePtCloud>(sens_dir + "/lidar/"));
lidar->PushFilter(chrono_types::make_shared<ChFilterXYZIAccess>());
manager->AddSensor(lidar);
std::shared_ptr<ChNoiseModel> acc_noise_model;
std::shared_ptr<ChNoiseModel> gyro_noise_model;
std::shared_ptr<ChNoiseModel> mag_noise_model;
switch (imu_noise_type) {
case NORMAL_DRIFT:
// Set the imu noise model to a gaussian model
acc_noise_model =
chrono_types::make_shared<ChNoiseNormalDrift>(100.f, // double updateRate,
ChVector<double>({0., 0., 0.}), // double mean,
ChVector<double>({0.001, 0.001, 0.001}), // double stdev,
.0001, // double bias_drift,
.1); // double tau_drift,
gyro_noise_model = chrono_types::make_shared<ChNoiseNormalDrift>(
100.f, // float updateRate,
ChVector<double>({0., 0., 0.}), // float mean,
ChVector<double>({0.0075, 0.0075, 0.0075}), // float stdev,
.001, // double bias_drift,
.1); // double tau_drift,
mag_noise_model =
chrono_types::make_shared<ChNoiseNormal>(ChVector<double>({0., 0., 0.}), // float mean,
ChVector<double>({0.001, 0.001, 0.001})); // float stdev,
break;
case IMU_NONE:
// Set the imu noise model to none (does not affect the data)
acc_noise_model = chrono_types::make_shared<ChNoiseNone>();
gyro_noise_model = chrono_types::make_shared<ChNoiseNone>();
mag_noise_model = chrono_types::make_shared<ChNoiseNone>();
break;
}
auto imu_offset_pose = chrono::ChFrame<double>({0, 0, 1.45}, Q_from_AngAxis(0, {1, 0, 0}));
auto acc =
chrono_types::make_shared<ChAccelerometerSensor>(gator.GetChassisBody(), // body to which the IMU is attached
imu_update_rate, // update rate
imu_offset_pose, // offset pose from body
acc_noise_model); // IMU noise model
acc->SetName("IMU - Accelerometer");
acc->SetLag(imu_lag);
acc->SetCollectionWindow(imu_collection_time);
acc->PushFilter(chrono_types::make_shared<ChFilterAccelAccess>()); // Add a filter to access the imu data
manager->AddSensor(acc); // Add the IMU sensor to the sensor manager
auto gyro =
chrono_types::make_shared<ChGyroscopeSensor>(gator.GetChassisBody(), // body to which the IMU is attached
100, // update rate
imu_offset_pose, // offset pose from body
gyro_noise_model); // IMU noise model
gyro->SetName("IMU - Gyroscope");
gyro->SetLag(imu_lag);
gyro->SetCollectionWindow(imu_collection_time);
gyro->PushFilter(chrono_types::make_shared<ChFilterGyroAccess>()); // Add a filter to access the imu data
manager->AddSensor(gyro); // Add the IMU sensor to the sensor manager
auto mag =
chrono_types::make_shared<ChMagnetometerSensor>(gator.GetChassisBody(), // body to which the IMU is attached
100, // update rate
imu_offset_pose, // offset pose from body
mag_noise_model,
gps_reference); // IMU noise model
mag->SetName("IMU - Magnetometer");
mag->SetLag(imu_lag);
mag->SetCollectionWindow(imu_collection_time);
mag->PushFilter(chrono_types::make_shared<ChFilterMagnetAccess>()); // Add a filter to access the imu data
manager->AddSensor(mag); // Add the IMU sensor to the sensor manager
// ---------------------------------------------
// Create a GPS and add it to the sensor manager
// ---------------------------------------------
std::shared_ptr<ChNoiseModel> gps_noise_model;
switch (gps_noise_type) {
case GPSNoiseModel::NORMAL:
gps_noise_model =
chrono_types::make_shared<ChNoiseNormal>(ChVector<float>(1.f, 1.f, 1.f), // Mean
ChVector<float>(2.f, 3.f, 1.f) // Standard Deviation
);
break;
case GPSNoiseModel::GPS_NONE:
gps_noise_model = chrono_types::make_shared<ChNoiseNone>();
break;
}
auto gps_offset_pose = chrono::ChFrame<double>({0, 0, 1.45}, Q_from_AngAxis(0, {1, 0, 0}));
auto gps = chrono_types::make_shared<ChGPSSensor>(
gator.GetChassisBody(), // body to which the GPS is attached
gps_update_rate, // update rate
gps_offset_pose, // offset pose from body
gps_reference, // reference GPS location (GPS coordinates of simulation origin)
gps_noise_model // noise model to use for adding GPS noise
);
gps->SetName("GPS");
gps->SetLag(gps_lag);
gps->SetCollectionWindow(gps_collection_time);
gps->PushFilter(chrono_types::make_shared<ChFilterGPSAccess>());
manager->AddSensor(gps);
// ---------------
// Simulation loop
// ---------------
// output vehicle mass
std::cout << "VEHICLE MASS: " << gator.GetVehicle().GetMass() << std::endl;
// Number of simulation steps between miscellaneous events
int render_steps = (int)std::ceil(render_step_size / step_size);
// Initialize simulation frame counters
int step_number = 0;
int render_frame = 0;
float orbit_radius = 10.f;
float orbit_rate = 1;
ChRealtimeStepTimer realtime_timer;
while (vis->Run()) {
double time = gator.GetSystem()->GetChTime();
cam->SetOffsetPose(
chrono::ChFrame<double>({-orbit_radius * cos(time * orbit_rate), -orbit_radius * sin(time * orbit_rate), 3},
Q_from_AngAxis(time * orbit_rate, {0, 0, 1})));
manager->Update();
// Render scene and output POV-Ray data
if (step_number % render_steps == 0) {
vis->BeginScene();
vis->DrawAll();
vis->EndScene();
if (povray_output) {
char filename[100];
sprintf(filename, "%s/data_%03d.dat", pov_dir.c_str(), render_frame + 1);
utils::WriteVisualizationAssets(gator.GetSystem(), filename);
}
render_frame++;
}
// Get driver inputs
DriverInputs driver_inputs = driver.GetInputs();
// Update modules (process inputs from other modules)
driver.Synchronize(time);
terrain.Synchronize(time);
gator.Synchronize(time, driver_inputs, terrain);
vis->Synchronize(driver.GetInputModeAsString(), driver_inputs);
// Advance simulation for one timestep for all modules
driver.Advance(step_size);
terrain.Advance(step_size);
gator.Advance(step_size);
vis->Advance(step_size);
// Increment frame number
step_number++;
// Spin in place for real time to catch up
realtime_timer.Spin(step_size);
}
return 0;
}
| 43.251462 | 120 | 0.570128 |
739dcd6701e5b595ac5bf68d0c537a9d7c46e90f | 10,785 | hpp | C++ | yolox_ros_cpp/yolox_cpp/include/yolox_cpp/core.hpp | HarvestX/YOLOX-ROS | f73bf6ab8f11ac0f720d4e5b3acc9737dfa44498 | [
"Apache-2.0"
] | 2 | 2022-02-21T09:56:42.000Z | 2022-02-22T00:38:41.000Z | yolox_ros_cpp/yolox_cpp/include/yolox_cpp/core.hpp | HarvestX/YOLOX-ROS | f73bf6ab8f11ac0f720d4e5b3acc9737dfa44498 | [
"Apache-2.0"
] | 5 | 2022-02-22T05:38:54.000Z | 2022-03-29T09:17:32.000Z | yolox_ros_cpp/yolox_cpp/include/yolox_cpp/core.hpp | HarvestX/YOLOX-ROS | f73bf6ab8f11ac0f720d4e5b3acc9737dfa44498 | [
"Apache-2.0"
] | null | null | null | #ifndef _YOLOX_CPP_CORE_HPP
#define _YOLOX_CPP_CORE_HPP
#include <opencv2/core/types.hpp>
namespace yolox_cpp{
/**
* @brief Define names based depends on Unicode path support
*/
#define tcout std::cout
#define file_name_t std::string
#define imread_t cv::imread
struct Object
{
cv::Rect_<float> rect;
int label;
float prob;
};
struct GridAndStride
{
int grid0;
int grid1;
int stride;
};
class AbcYoloX{
public:
AbcYoloX(){}
AbcYoloX(float nms_th=0.45, float conf_th=0.3,
std::string model_version="0.1.1rc0")
:nms_thresh_(nms_th), bbox_conf_thresh_(conf_th),
model_version_(model_version)
{}
virtual std::vector<Object> inference(cv::Mat frame) = 0;
protected:
int input_w_;
int input_h_;
float nms_thresh_;
float bbox_conf_thresh_;
int num_classes_ = 80;
std::string model_version_;
const std::vector<float> mean_ = {0.485, 0.456, 0.406};
const std::vector<float> std_ = {0.229, 0.224, 0.225};
const std::vector<int> strides_ = {8, 16, 32};
std::vector<GridAndStride> grid_strides_;
cv::Mat static_resize(cv::Mat& img) {
float r = std::min(input_w_ / (img.cols*1.0), input_h_ / (img.rows*1.0));
// r = std::min(r, 1.0f);
int unpad_w = r * img.cols;
int unpad_h = r * img.rows;
cv::Mat re(unpad_h, unpad_w, CV_8UC3);
cv::resize(img, re, re.size());
cv::Mat out(input_h_, input_w_, CV_8UC3, cv::Scalar(114, 114, 114));
re.copyTo(out(cv::Rect(0, 0, re.cols, re.rows)));
return out;
}
void blobFromImage(cv::Mat& img, float *blob_data){
int channels = 3;
int img_h = img.rows;
int img_w = img.cols;
if(this->model_version_=="0.1.0"){
for (size_t c = 0; c < channels; c++)
{
for (size_t h = 0; h < img_h; h++)
{
for (size_t w = 0; w < img_w; w++)
{
blob_data[c * img_w * img_h + h * img_w + w] =
((float)img.at<cv::Vec3b>(h, w)[c] / 255.0 - this->mean_[c]) / this->std_[c];
}
}
}
}else{
for (size_t c = 0; c < channels; c++)
{
for (size_t h = 0; h < img_h; h++)
{
for (size_t w = 0; w < img_w; w++)
{
blob_data[c * img_w * img_h + h * img_w + w] =
(float)img.at<cv::Vec3b>(h, w)[c]; // 0.1.1rc0 or later
}
}
}
}
}
void generate_grids_and_stride(const int target_w, const int target_h, const std::vector<int>& strides, std::vector<GridAndStride>& grid_strides)
{
for (auto stride : strides)
{
int num_grid_w = target_w / stride;
int num_grid_h = target_h / stride;
for (int g1 = 0; g1 < num_grid_h; g1++)
{
for (int g0 = 0; g0 < num_grid_w; g0++)
{
grid_strides.push_back((GridAndStride){g0, g1, stride});
}
}
}
}
void generate_yolox_proposals(const std::vector<GridAndStride> grid_strides, const float* feat_ptr, const float prob_threshold, std::vector<Object>& objects)
{
const int num_anchors = grid_strides.size();
for (int anchor_idx = 0; anchor_idx < num_anchors; anchor_idx++)
{
const int grid0 = grid_strides[anchor_idx].grid0;
const int grid1 = grid_strides[anchor_idx].grid1;
const int stride = grid_strides[anchor_idx].stride;
const int basic_pos = anchor_idx * (num_classes_ + 5);
float box_objectness = feat_ptr[basic_pos + 4];
int class_id = 0;
float max_class_score = 0.0;
for (int class_idx = 0; class_idx < num_classes_; class_idx++)
{
float box_cls_score = feat_ptr[basic_pos + 5 + class_idx];
float box_prob = box_objectness * box_cls_score;
if (box_prob > max_class_score){
class_id = class_idx;
max_class_score = box_prob;
}
}
if (max_class_score > prob_threshold)
{
// yolox/models/yolo_head.py decode logic
// outputs[..., :2] = (outputs[..., :2] + grids) * strides
// outputs[..., 2:4] = torch.exp(outputs[..., 2:4]) * strides
float x_center = (feat_ptr[basic_pos + 0] + grid0) * stride;
float y_center = (feat_ptr[basic_pos + 1] + grid1) * stride;
float w = exp(feat_ptr[basic_pos + 2]) * stride;
float h = exp(feat_ptr[basic_pos + 3]) * stride;
float x0 = x_center - w * 0.5f;
float y0 = y_center - h * 0.5f;
Object obj;
obj.rect.x = x0;
obj.rect.y = y0;
obj.rect.width = w;
obj.rect.height = h;
obj.label = class_id;
obj.prob = max_class_score;
objects.push_back(obj);
}
} // point anchor loop
}
float intersection_area(const Object& a, const Object& b)
{
cv::Rect_<float> inter = a.rect & b.rect;
return inter.area();
}
void qsort_descent_inplace(std::vector<Object>& faceobjects, int left, int right)
{
int i = left;
int j = right;
float p = faceobjects[(left + right) / 2].prob;
while (i <= j)
{
while (faceobjects[i].prob > p)
i++;
while (faceobjects[j].prob < p)
j--;
if (i <= j)
{
// swap
std::swap(faceobjects[i], faceobjects[j]);
i++;
j--;
}
}
#pragma omp parallel sections
{
#pragma omp section
{
if (left < j) qsort_descent_inplace(faceobjects, left, j);
}
#pragma omp section
{
if (i < right) qsort_descent_inplace(faceobjects, i, right);
}
}
}
void qsort_descent_inplace(std::vector<Object>& objects)
{
if (objects.empty())
return;
qsort_descent_inplace(objects, 0, objects.size() - 1);
}
void nms_sorted_bboxes(const std::vector<Object>& faceobjects, std::vector<int>& picked, const float nms_threshold)
{
picked.clear();
const int n = faceobjects.size();
std::vector<float> areas(n);
for (int i = 0; i < n; i++)
{
areas[i] = faceobjects[i].rect.area();
}
for (int i = 0; i < n; i++)
{
const Object& a = faceobjects[i];
int keep = 1;
for (int j = 0; j < (int)picked.size(); j++)
{
const Object& b = faceobjects[picked[j]];
// intersection over union
float inter_area = intersection_area(a, b);
float union_area = areas[i] + areas[picked[j]] - inter_area;
// float IoU = inter_area / union_area
if (inter_area / union_area > nms_threshold)
keep = 0;
}
if (keep)
picked.push_back(i);
}
}
void decode_outputs(const float* prob, const std::vector<GridAndStride> grid_strides, std::vector<Object>& objects, const float bbox_conf_thresh, const float scale, const int img_w, const int img_h) {
std::vector<Object> proposals;
generate_yolox_proposals(grid_strides, prob, bbox_conf_thresh, proposals);
qsort_descent_inplace(proposals);
std::vector<int> picked;
nms_sorted_bboxes(proposals, picked, nms_thresh_);
int count = picked.size();
objects.resize(count);
for (int i = 0; i < count; i++)
{
objects[i] = proposals[picked[i]];
// adjust offset to original unpadded
float x0 = (objects[i].rect.x) / scale;
float y0 = (objects[i].rect.y) / scale;
float x1 = (objects[i].rect.x + objects[i].rect.width) / scale;
float y1 = (objects[i].rect.y + objects[i].rect.height) / scale;
// clip
x0 = std::max(std::min(x0, (float)(img_w - 1)), 0.f);
y0 = std::max(std::min(y0, (float)(img_h - 1)), 0.f);
x1 = std::max(std::min(x1, (float)(img_w - 1)), 0.f);
y1 = std::max(std::min(y1, (float)(img_h - 1)), 0.f);
objects[i].rect.x = x0;
objects[i].rect.y = y0;
objects[i].rect.width = x1 - x0;
objects[i].rect.height = y1 - y0;
}
}
};
}
#endif | 38.935018 | 212 | 0.418544 |
739e0781817325c9c53c2d1b9c20358752c73dc8 | 8,713 | cpp | C++ | packages/utility/system/test/tstSphericalDirectionalCoordinateConversionPolicy.cpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 10 | 2019-11-14T19:58:30.000Z | 2021-04-04T17:44:09.000Z | packages/utility/system/test/tstSphericalDirectionalCoordinateConversionPolicy.cpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 43 | 2020-03-03T19:59:20.000Z | 2021-09-08T03:36:08.000Z | packages/utility/system/test/tstSphericalDirectionalCoordinateConversionPolicy.cpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 6 | 2020-02-12T17:37:07.000Z | 2020-09-08T18:59:51.000Z | //---------------------------------------------------------------------------//
//!
//! \file tstSphericalDirectionalCoordinateConversionPolicy.cpp
//! \author Alex Robinson
//! \brief Spherical directional coordinate conversion policy unit tests
//!
//---------------------------------------------------------------------------//
// Std Lib Includes
#include <iostream>
// FRENSIE Includes
#include "Utility_SphericalDirectionalCoordinateConversionPolicy.hpp"
#include "Utility_3DCartesianVectorHelpers.hpp"
#include "Utility_Vector.hpp"
#include "Utility_Array.hpp"
#include "Utility_QuantityTraits.hpp"
#include "Utility_PhysicalConstants.hpp"
#include "Utility_UnitTestHarnessWithMain.hpp"
//---------------------------------------------------------------------------//
// Tests.
//---------------------------------------------------------------------------//
// Check that the spherical directional coordinates can be converted to
// Cartesian directional coordinates
FRENSIE_UNIT_TEST( SphericalDirectionalCoordinateConversionPolicy,
convertFromCartesianDirection )
{
// Z-axis
std::array<double,3> cartesian_direction = {0.0, 0.0, 1.0};
std::array<double,3> spherical_direction;
std::array<double,3> ref_spherical_direction = {1.0, 0.0, 1.0};
Utility::SphericalDirectionalCoordinateConversionPolicy::convertFromCartesianDirection(
cartesian_direction.data(),
spherical_direction.data() );
FRENSIE_CHECK_FLOATING_EQUALITY( spherical_direction, ref_spherical_direction, 1e-15 );
// Neg. z-axis
cartesian_direction = {0.0, 0.0, -1.0};
ref_spherical_direction = {1.0, 0.0, -1.0};
Utility::SphericalDirectionalCoordinateConversionPolicy::convertFromCartesianDirection(
cartesian_direction.data(),
spherical_direction.data() );
FRENSIE_CHECK_FLOATING_EQUALITY( spherical_direction, ref_spherical_direction, 1e-15 );
// Y-axis
cartesian_direction = {0.0, 1.0, 0.0};
ref_spherical_direction = {1.0, Utility::PhysicalConstants::pi/2, 0.0};
Utility::SphericalDirectionalCoordinateConversionPolicy::convertFromCartesianDirection(
cartesian_direction.data(),
spherical_direction.data() );
FRENSIE_CHECK_FLOATING_EQUALITY( spherical_direction, ref_spherical_direction, 1e-15 );
// Neg. y-axis
cartesian_direction = {0.0, -1.0, 0.0};
ref_spherical_direction = {1.0, 3*Utility::PhysicalConstants::pi/2, 0.0};
Utility::SphericalDirectionalCoordinateConversionPolicy::convertFromCartesianDirection(
cartesian_direction.data(),
spherical_direction.data() );
FRENSIE_CHECK_FLOATING_EQUALITY( spherical_direction, ref_spherical_direction, 1e-15 );
// X-axis
cartesian_direction = {1.0, 0.0, 0.0};
ref_spherical_direction = {1.0, 0.0, 0.0};
Utility::SphericalDirectionalCoordinateConversionPolicy::convertFromCartesianDirection(
cartesian_direction.data(),
spherical_direction.data() );
FRENSIE_CHECK_FLOATING_EQUALITY( spherical_direction, ref_spherical_direction, 1e-15 );
// Neg. x-axis
cartesian_direction = {-1.0, 0.0, 0.0};
ref_spherical_direction = {1.0, Utility::PhysicalConstants::pi, 0.0};
Utility::SphericalDirectionalCoordinateConversionPolicy::convertFromCartesianDirection(
cartesian_direction.data(),
spherical_direction.data() );
FRENSIE_CHECK_FLOATING_EQUALITY( spherical_direction, ref_spherical_direction, 1e-15 );
// Off axis
cartesian_direction = {1.0/sqrt(3.0), 1.0/sqrt(3.0), 1.0/sqrt(3.0)};
ref_spherical_direction =
{1.0, Utility::PhysicalConstants::pi/4, 1.0/sqrt(3.0)};
Utility::SphericalDirectionalCoordinateConversionPolicy::convertFromCartesianDirection(
cartesian_direction[0],
cartesian_direction[1],
cartesian_direction[2],
spherical_direction[0],
spherical_direction[1],
spherical_direction[2] );
FRENSIE_CHECK_FLOATING_EQUALITY( spherical_direction, ref_spherical_direction, 1e-15 );
}
//---------------------------------------------------------------------------//
// Check that the spherical directional coordinates can be converted to
// Cartesian directional coordinates
FRENSIE_UNIT_TEST( SphericalDirectionalCoordinateConversionPolicy,
convertToCartesianDirection )
{
// Z-axis
std::array<double,3> spherical_direction = {1.0, 0.0, 1.0};
std::array<double,3> cartesian_direction;
std::array<double,3> ref_cartesian_direction = {0.0, 0.0, 1.0};
Utility::SphericalDirectionalCoordinateConversionPolicy::convertToCartesianDirection(
spherical_direction.data(),
cartesian_direction.data() );
FRENSIE_CHECK_FLOATING_EQUALITY( cartesian_direction, ref_cartesian_direction, 1e-15 );
// Neg. Z-axis
spherical_direction = {1.0, 0.0, -1.0};
ref_cartesian_direction = {0.0, 0.0, -1.0};
Utility::SphericalDirectionalCoordinateConversionPolicy::convertToCartesianDirection(
spherical_direction.data(),
cartesian_direction.data() );
FRENSIE_CHECK_FLOATING_EQUALITY( cartesian_direction, ref_cartesian_direction, 1e-15 );
// Y-axis
spherical_direction = {1.0, Utility::PhysicalConstants::pi/2, 0.0};
ref_cartesian_direction = {0.0, 1.0, 0.0};
Utility::SphericalDirectionalCoordinateConversionPolicy::convertToCartesianDirection(
spherical_direction.data(),
cartesian_direction.data() );
Utility::clearVectorOfRoundingErrors( cartesian_direction.data(), 1e-15 );
FRENSIE_CHECK_FLOATING_EQUALITY( cartesian_direction, ref_cartesian_direction, 1e-15 );
// Neg. y-axis
spherical_direction = {1.0, 3*Utility::PhysicalConstants::pi/2, 0.0};
ref_cartesian_direction = {0.0, -1.0, 0.0};
Utility::SphericalDirectionalCoordinateConversionPolicy::convertToCartesianDirection(
spherical_direction.data(),
cartesian_direction.data() );
Utility::clearVectorOfRoundingErrors( cartesian_direction.data(), 1e-15 );
FRENSIE_CHECK_FLOATING_EQUALITY( cartesian_direction, ref_cartesian_direction, 1e-15 );
// X-axis
spherical_direction = {1.0, 0.0, 0.0};
ref_cartesian_direction = {1.0, 0.0, 0.0};
Utility::SphericalDirectionalCoordinateConversionPolicy::convertToCartesianDirection(
spherical_direction.data(),
cartesian_direction.data() );
FRENSIE_CHECK_FLOATING_EQUALITY( cartesian_direction, ref_cartesian_direction, 1e-15 );
// Y-axis
spherical_direction = {1.0, Utility::PhysicalConstants::pi, 0.0};
ref_cartesian_direction = {-1.0, 0.0, 0.0};
Utility::SphericalDirectionalCoordinateConversionPolicy::convertToCartesianDirection(
spherical_direction.data(),
cartesian_direction.data() );
Utility::clearVectorOfRoundingErrors( cartesian_direction.data(), 1e-15 );
FRENSIE_CHECK_FLOATING_EQUALITY( cartesian_direction, ref_cartesian_direction, 1e-15 );
// Off axis
spherical_direction =
{1.0, Utility::PhysicalConstants::pi/4, 1.0/sqrt(3.0)};
ref_cartesian_direction = {1.0/sqrt(3.0), 1.0/sqrt(3.0), 1.0/sqrt(3.0)};
Utility::SphericalDirectionalCoordinateConversionPolicy::convertToCartesianDirection(
spherical_direction.data(),
cartesian_direction.data() );
FRENSIE_CHECK_FLOATING_EQUALITY( cartesian_direction, ref_cartesian_direction, 1e-15 );
}
//---------------------------------------------------------------------------//
// end tstSphericalDirectionalCoordinateConversionPolicy.cpp
//---------------------------------------------------------------------------//
| 44.682051 | 89 | 0.596236 |
73a02df7bd3f19fc1efb0e588c8be63205f76042 | 2,119 | cpp | C++ | extensions_loader.cpp | kevinfrei/neutralinojs | d6433ec105d102a25a011897fa1c0a45dce8aca3 | [
"WTFPL"
] | 1 | 2018-06-23T03:45:10.000Z | 2018-06-23T03:45:10.000Z | extensions_loader.cpp | kevinfrei/neutralinojs | d6433ec105d102a25a011897fa1c0a45dce8aca3 | [
"WTFPL"
] | null | null | null | extensions_loader.cpp | kevinfrei/neutralinojs | d6433ec105d102a25a011897fa1c0a45dce8aca3 | [
"WTFPL"
] | null | null | null | #include <string>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <regex>
#include <vector>
#include "extensions_loader.h"
#include "settings.h"
#include "helpers.h"
#include "auth/authbasic.h"
#include "api/os/os.h"
using namespace std;
using json = nlohmann::json;
namespace extensions {
vector<string> loadedExtensions;
bool initialized = false;
string __buildExtensionArgs(const string &extensionId) {
string options = "";
options += " --nl-port=" + to_string(settings::getOptionForCurrentMode("port").get<int>());
options += " --nl-token=" + authbasic::getTokenInternal();
options += " --nl-extension-id=" + extensionId;
return options;
}
void init() {
json jExtensions = settings::getOptionForCurrentMode("extensions");
if(jExtensions.is_null())
return;
vector<json> extensions = jExtensions.get<vector<json>>();
for(const json &extension: extensions) {
string commandKeyForOs = "command" + string(OS_NAME);
if(!helpers::hasField(extension, "id")) {
continue;
}
string extensionId = extension["id"].get<string>();
if(helpers::hasField(extension, "command") || helpers::hasField(extension, commandKeyForOs)) {
string command = helpers::hasField(extension, commandKeyForOs) ? extension[commandKeyForOs].get<string>()
: extension["command"].get<string>();
command = regex_replace(command, regex("\\$\\{NL_PATH\\}"), settings::getAppPath());
command += __buildExtensionArgs(extensionId);
os::execCommand(command, "", true); // async
}
extensions::loadOne(extensionId);
}
initialized = true;
}
void loadOne(const string &extensionId) {
loadedExtensions.push_back(extensionId);
}
vector<string> getLoaded() {
return loadedExtensions;
}
bool isLoaded(const string &extensionId) {
return find(loadedExtensions.begin(), loadedExtensions.end(), extensionId)
!= loadedExtensions.end();
}
bool isInitialized() {
return initialized;
}
} // namespace extensions
| 27.881579 | 117 | 0.657857 |
73a32a7eab079e8d8054f8741b4a29111e5c527e | 2,159 | hpp | C++ | Testbed/Tests/HalfPipe.hpp | louis-langholtz/Box2D | 7c74792bf177cf36640d735de2bba0225bf7f852 | [
"Zlib"
] | 32 | 2016-10-20T05:55:04.000Z | 2021-11-25T16:34:41.000Z | Testbed/Tests/HalfPipe.hpp | louis-langholtz/Box2D | 7c74792bf177cf36640d735de2bba0225bf7f852 | [
"Zlib"
] | 50 | 2017-01-07T21:40:16.000Z | 2018-01-31T10:04:05.000Z | Testbed/Tests/HalfPipe.hpp | louis-langholtz/Box2D | 7c74792bf177cf36640d735de2bba0225bf7f852 | [
"Zlib"
] | 7 | 2017-02-09T10:02:02.000Z | 2020-07-23T22:49:04.000Z | /*
* Copyright (c) 2017 Louis Langholtz https://github.com/louis-langholtz/Box2D
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#ifndef HalfPipe_hpp
#define HalfPipe_hpp
#include "../Framework/Test.hpp"
namespace box2d {
class HalfPipe : public Test
{
public:
HalfPipe()
{
const auto pipeBody = m_world->CreateBody(BodyDef{}.UseLocation(Vec2(0, 20) * Meter));
{
auto conf = ChainShape::Conf{};
conf.UseFriction(1.0f);
conf.vertices = GetCircleVertices(Real{20.0f} * Meter, 90,
Real(180) * Degree, Real(0.5f));
pipeBody->CreateFixture(std::make_shared<ChainShape>(conf));
}
const auto ballBody = m_world->CreateBody(BodyDef{}
.UseType(BodyType::Dynamic)
.UseLocation(Vec2(-19, 28) * Meter));
ballBody->CreateFixture(std::make_shared<DiskShape>(DiskShape::Conf{}
.UseDensity(Real{0.01f} * KilogramPerSquareMeter)
.UseVertexRadius(Real{1} * Meter)
.UseFriction(1.0f)));
}
};
}
#endif /* HalfPipe_hpp */
| 39.981481 | 98 | 0.592867 |
73a3cc66a9df48306cf9b544108bedb734859e28 | 6,876 | cpp | C++ | test-rpg/src/Character.cpp | sps1112/test-rpg | 28b2acb4379695ad7e04401161ecca92cab9e3a6 | [
"MIT"
] | 2 | 2021-07-09T12:25:24.000Z | 2021-12-22T12:38:47.000Z | test-rpg/src/Character.cpp | sps1112/test-rpg | 28b2acb4379695ad7e04401161ecca92cab9e3a6 | [
"MIT"
] | null | null | null | test-rpg/src/Character.cpp | sps1112/test-rpg | 28b2acb4379695ad7e04401161ecca92cab9e3a6 | [
"MIT"
] | null | null | null | #include "Character.h"
namespace rpgText
{
Character::Character(std::string name_, int level, float str, float sta,
float inte, float agi, float luck)
{
name = name_;
BaseStats bs(str, sta, inte, agi, luck);
stats = Stats(bs, level);
cStats = stats;
}
void Character::change_health(float amount)
{
cStats.health += amount;
cStats.health = clamp(cStats.health, 0, stats.health);
}
void Character::change_mana(float amount)
{
cStats.mana += amount;
cStats.mana = clamp(cStats.mana, 0, stats.mana);
}
void Character::reset_stats()
{
cStats.health = stats.health;
cStats.mana = stats.mana;
}
bool Character::get_status()
{
return (cStats.health > 0);
}
void Character::print_stats()
{
print_line();
log("[STATS]");
print("Name:- ");
log(name);
print_data("Level:- ", stats.level);
print("Health:- ");
print(cStats.health);
print("/");
log(stats.health);
print("Mana:- ");
print(cStats.mana);
print("/");
log(stats.mana);
print_data("Attack:- ", cStats.attack);
print_data("Defence:- ", cStats.defence);
print_data("Mana Attack:- ", cStats.mAttack);
print_data("Mana Defence:- ", cStats.mDefence);
print_data("Speed:- ", cStats.speed);
print_data("Accuracy:- ", cStats.accuracy);
print_data("Evasion:- ", cStats.evasion);
print_data("Crit Chance:- ", cStats.crit);
print_line();
}
Enemy::Enemy(std::string name_, bool viaData, int level, float str, float sta,
float inte, float agi, float luck, float exp, float money)
{
name = name_;
BaseStats bs(str, sta, inte, agi, luck);
stats = Stats(bs, level);
cStats = stats;
expDrop = exp;
moneyDrop = money;
}
Enemy::Enemy(const char *path)
{
std::string statsStr = get_file_data(path);
const char *statsCode = statsStr.c_str();
int index = 0;
// Set Name
index = skip_lines(statsCode, 1, index);
name = arr_to_string(get_data_point(statsCode, ":- ", index));
// Set Strength
index = skip_lines(statsCode, 1, index);
float str = arr_to_float(get_data_point(statsCode, ":- ", index));
// Set Stamina
index = skip_lines(statsCode, 1, index);
float sta = arr_to_float(get_data_point(statsCode, ":- ", index));
// Set Intelligence
index = skip_lines(statsCode, 1, index);
float inte = arr_to_float(get_data_point(statsCode, ":- ", index));
// Set Agility
index = skip_lines(statsCode, 1, index);
float agi = arr_to_float(get_data_point(statsCode, ":- ", index));
// Set Luck
index = skip_lines(statsCode, 1, index);
float luck = arr_to_float(get_data_point(statsCode, ":- ", index));
// Set Level
index = skip_lines(statsCode, 1, index);
int level = int(arr_to_float(get_data_point(statsCode, ":- ", index)));
// Set Stats
BaseStats bs(str, sta, inte, agi, luck);
stats = Stats(bs, level);
cStats = stats;
// Set Exp Drop
index = skip_lines(statsCode, 1, index);
expDrop = arr_to_float(get_data_point(statsCode, ":- ", index));
// Set Money Drop
index = skip_lines(statsCode, 1, index);
moneyDrop = arr_to_float(get_data_point(statsCode, ":- ", index));
}
Player::Player(std::string name_, bool viaData, int level, float str, float sta,
float inte, float agi, float luck, float exp, float next)
{
name = name_;
BaseStats bs(str, sta, inte, agi, luck);
stats = Stats(bs, level);
cStats = stats;
currentExp = exp;
expToNextlevel = next;
write_to_file();
}
Player::Player(const char *path)
{
std::string statsStr = get_file_data(path);
const char *statsCode = statsStr.c_str();
int index = 0;
// Set Name
index = skip_lines(statsCode, 1, index);
name = arr_to_string(get_data_point(statsCode, ":- ", index));
// Set Strength
index = skip_lines(statsCode, 1, index);
float str = arr_to_float(get_data_point(statsCode, ":- ", index));
// Set Stamina
index = skip_lines(statsCode, 1, index);
float sta = arr_to_float(get_data_point(statsCode, ":- ", index));
// Set Intelligence
index = skip_lines(statsCode, 1, index);
float inte = arr_to_float(get_data_point(statsCode, ":- ", index));
// Set Agility
index = skip_lines(statsCode, 1, index);
float agi = arr_to_float(get_data_point(statsCode, ":- ", index));
// Set Luck
index = skip_lines(statsCode, 1, index);
float luck = arr_to_float(get_data_point(statsCode, ":- ", index));
// Set Level
index = skip_lines(statsCode, 1, index);
int level = int(arr_to_float(get_data_point(statsCode, ":- ", index)));
// Set Stats
BaseStats bs(str, sta, inte, agi, luck);
stats = Stats(bs, level);
cStats = stats;
// Set Current EXP
index = skip_lines(statsCode, 1, index);
currentExp = arr_to_float(get_data_point(statsCode, ":- ", index));
// Set EXP to Next Level
index = skip_lines(statsCode, 1, index);
expToNextlevel = arr_to_float(get_data_point(statsCode, ":- ", index));
write_to_file();
}
Player::~Player()
{
write_to_file();
}
void Player::write_to_file()
{
std::ofstream file;
file.open(FileSystem::get_path("test-rpg/data/Player.saved.char").c_str(), std::ios::trunc);
file << "[Stats]" << std::endl;
file << "Name:- " << name.c_str() << std::endl;
file << "Level:- " << stats.level << std::endl;
file << "Health:- " << stats.health << std::endl;
file << "Mana:- " << stats.mana << std::endl;
file << "Attack:- " << stats.attack << std::endl;
file << "Defence:- " << stats.defence << std::endl;
file << "Mana Attack:- " << stats.mAttack << std::endl;
file << "Mana Defence:- " << stats.mDefence << std::endl;
file << "Speed:- " << stats.speed << std::endl;
file << "Accuracy:- " << stats.accuracy << std::endl;
file << "Evasion:- " << stats.evasion << std::endl;
file << "Critical Chance:- " << stats.crit << std::endl;
file << "CurrentExp:- " << currentExp << std::endl;
file << "Exp to Next Level:- " << expToNextlevel << std::endl;
file.close();
}
} // namespace rpgText
| 31.113122 | 100 | 0.557446 |
73a47a22080908680a30abee01a81c8c63776d50 | 2,243 | cpp | C++ | src/scripting/CameraScripting.cpp | ZaOniRinku/NeigeEngine | 8dfe06e428ec1751ba0b5003ccdf5162474f002b | [
"MIT"
] | 9 | 2020-10-06T11:17:07.000Z | 2022-03-29T20:28:07.000Z | src/scripting/CameraScripting.cpp | ZaOniRinku/NeigeEngine | 8dfe06e428ec1751ba0b5003ccdf5162474f002b | [
"MIT"
] | 1 | 2020-10-06T11:55:45.000Z | 2020-10-06T12:07:46.000Z | src/scripting/CameraScripting.cpp | ZaOniRinku/NeigeEngine | 8dfe06e428ec1751ba0b5003ccdf5162474f002b | [
"MIT"
] | null | null | null | #include "CameraScripting.h"
void CameraScripting::init() {
lua_register(L, "getMainCameraIndex", getMainCameraIndex);
lua_register(L, "setMainCameraIndex", setMainCameraIndex);
lua_register(L, "getMainCameraEntity", getMainCameraEntity);
lua_register(L, "getCameraCount", getCameraCount);
}
int CameraScripting::getMainCameraIndex(lua_State* L) {
int n = lua_gettop(L);
if (n == 0) {
bool foundCamera = false;
int cameraId = 0;
int i = 0;
for (Entity camera : *cameras) {
if (mainCamera == camera) {
cameraId = static_cast<int>(i);
foundCamera = true;
break;
}
i++;
}
if (foundCamera) {
lua_pushnumber(L, cameraId);
return 1;
}
else {
NEIGE_SCRIPT_ERROR("Function \"getMainCameraIndex()\": unable to find main camera index.");
return 0;
}
}
else {
NEIGE_SCRIPT_ERROR("Function \"getMainCameraIndex()\" takes no parameter.");
return 0;
}
}
int CameraScripting::setMainCameraIndex(lua_State* L) {
int n = lua_gettop(L);
if (n == 1) {
if (lua_isnumber(L, -1)) {
size_t cameraId = static_cast<size_t>(lua_tonumber(L, 1));
if (cameraId >= 0 && cameraId < cameras->size()) {
mainCamera = *std::next(cameras->begin(), cameraId);
return 0;
}
else {
NEIGE_SCRIPT_ERROR("Function \"setMainCameraIndex(int cameraId)\": cameraId must be between 0 and getCameraCount() - 1.");
return 0;
}
}
else {
NEIGE_SCRIPT_ERROR("Function \"setMainCameraIndex(int cameraId)\" takes 1 integer parameter.");
return 0;
}
}
else {
NEIGE_SCRIPT_ERROR("Function \"setMainCameraIndex(int cameraId)\" takes 1 integer parameter.");
return 0;
}
}
int CameraScripting::getMainCameraEntity(lua_State* L) {
int n = lua_gettop(L);
if (n == 0) {
lua_pushnumber(L, mainCamera);
return 1;
}
else {
NEIGE_SCRIPT_ERROR("Function \"getMainCameraEntity()\" takes no parameter.");
return 0;
}
}
int CameraScripting::getCameraCount(lua_State* L) {
int n = lua_gettop(L);
if (n == 0) {
lua_pushnumber(L, static_cast<int>(cameras->size()));
return 1;
}
else {
NEIGE_SCRIPT_ERROR("Function \"getCameraCount()\" takes no parameter.");
return 0;
}
} | 24.380435 | 127 | 0.644226 |
73a5ec1a46304b47ea877a461b22cdbce9b1cd91 | 1,246 | hpp | C++ | source/ddnspp/common/dlloader.hpp | John-Chan/dnssdpp | 5d974c01db9f01bdd87ff5f547b5a310227a41a3 | [
"Apache-2.0"
] | null | null | null | source/ddnspp/common/dlloader.hpp | John-Chan/dnssdpp | 5d974c01db9f01bdd87ff5f547b5a310227a41a3 | [
"Apache-2.0"
] | null | null | null | source/ddnspp/common/dlloader.hpp | John-Chan/dnssdpp | 5d974c01db9f01bdd87ff5f547b5a310227a41a3 | [
"Apache-2.0"
] | null | null | null | #ifndef DLLOADER_HPP
#define DLLOADER_HPP
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <Windows.h>
#include <string.h>
#include <tchar.h>
#include <boost/utility.hpp>
namespace air{namespace common {
class DllLoader:boost::noncopyable
{
public:
DllLoader(const TCHAR* dll_name)
:dll_(NULL)
{
::_tcsncpy(dll_name_,dll_name,kMaxPathLen-1);
}
~DllLoader()
{
unload();
}
const TCHAR* dll_name()const
{
return dll_name_;
}
HMODULE get_handle()
{
return dll_;
}
bool loaded()const
{
return NULL != dll_;
}
bool load()
{
if(!loaded()){
// will return NULL when fail
dll_=::LoadLibrary( dll_name_);
}
return loaded();
}
void unload()
{
if(loaded()){
::FreeLibrary(dll_);
dll_=NULL;
}
}
template <class FuncType>
FuncType load_dll_func(const char* func_name)
{
return (FuncType)::GetProcAddress(dll_, func_name);
}
private:
enum {kMaxPathLen=512}; // calced by character,not bytes
HMODULE dll_;
TCHAR dll_name_[kMaxPathLen];
};
}}
#endif // DLLOADER_HPP
| 18.057971 | 61 | 0.576244 |
73a80bbfc941fc3e00aadc4871159e1c8922fd67 | 7,678 | cpp | C++ | src/gausskernel/storage/mot/core/src/system/mot_error.cpp | wotchin/openGauss-server | ebd92e92b0cfd76b121d98e4c57a22d334573159 | [
"MulanPSL-1.0"
] | 1 | 2020-06-30T15:00:50.000Z | 2020-06-30T15:00:50.000Z | src/gausskernel/storage/mot/core/src/system/mot_error.cpp | wotchin/openGauss-server | ebd92e92b0cfd76b121d98e4c57a22d334573159 | [
"MulanPSL-1.0"
] | null | null | null | src/gausskernel/storage/mot/core/src/system/mot_error.cpp | wotchin/openGauss-server | ebd92e92b0cfd76b121d98e4c57a22d334573159 | [
"MulanPSL-1.0"
] | null | null | null | /*
* Copyright (c) 2020 Huawei Technologies Co.,Ltd.
*
* openGauss is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
* -------------------------------------------------------------------------
*
* mot_error.cpp
* Utilities for error handling.
*
* IDENTIFICATION
* src/gausskernel/storage/mot/core/src/system/mot_error.cpp
*
* -------------------------------------------------------------------------
*/
#include "mot_error.h"
#include "utilities.h"
#include "postgres.h"
#include "knl/knl_thread.h"
#include <stdarg.h>
#include <string.h>
namespace MOT {
DECLARE_LOGGER(Error, System)
// Attention: all definitions are found in knl_thread.h
#define lastErrorCode t_thrd.mot_cxt.last_error_code
#define lastErrorSeverity t_thrd.mot_cxt.last_error_severity
#define errorStack t_thrd.mot_cxt.error_stack
#define errorFrameCount t_thrd.mot_cxt.error_frame_count
typedef mot_error_frame ErrorFrame;
extern void SetLastError(int errorCode, int severity)
{
lastErrorCode = errorCode;
lastErrorSeverity = severity;
}
extern int GetLastError()
{
int result = lastErrorCode;
if (errorFrameCount > 0) {
result = errorStack[errorFrameCount - 1].m_errorCode;
}
return result;
}
extern int SetLastErrorSeverity()
{
int result = lastErrorSeverity;
if (errorFrameCount > 0) {
result = errorStack[errorFrameCount - 1].m_severity;
}
return result;
}
extern int GetRootError()
{
int result = MOT_NO_ERROR;
if (errorFrameCount > 0) {
result = errorStack[0].m_errorCode;
}
return result;
}
extern int GetRootErrorSeverity()
{
int result = MOT_SEVERITY_NORMAL;
if (errorFrameCount > 0) {
result = errorStack[0].m_severity;
}
return result;
}
extern const char* ErrorCodeToString(int errorCode)
{
switch (errorCode) {
case MOT_ERROR_OOM:
return "Out of memory";
case MOT_ERROR_INVALID_CFG:
return "Invalid configuration";
case MOT_ERROR_INVALID_ARG:
return "Invalid argument passed to function";
case MOT_ERROR_SYSTEM_FAILURE:
return "System call failed";
case MOT_ERROR_RESOURCE_LIMIT:
return "Resource limit reached";
case MOT_ERROR_INTERNAL:
return "Internal logic error";
case MOT_ERROR_RESOURCE_UNAVAILABLE:
return "Resource unavailable";
case MOT_ERROR_UNIQUE_VIOLATION:
return "Unique violation";
case MOT_ERROR_INVALID_MEMORY_SIZE:
return "Invalid memory allocation size";
case MOT_ERROR_INDEX_OUT_OF_RANGE:
return "Index out of range";
default:
return "Error code unknown";
}
}
extern const char* SeverityToString(int severity)
{
switch (severity) {
case MOT_SEVERITY_NORMAL:
return "Normal";
case MOT_SEVERITY_WARN:
return "Warning";
case MOT_SEVERITY_ERROR:
return "Error";
case MOT_SEVERITY_FATAL:
return "Fatal";
default:
return "Error severity unknown";
}
}
extern void PushError(int errorCode, int severity, const char* file, int line, const char* function, const char* entity,
const char* context, const char* format, ...)
{
va_list args;
va_start(args, format);
PushErrorV(errorCode, severity, file, line, function, entity, context, format, args);
va_end(args);
}
extern void PushErrorV(int errorCode, int severity, const char* file, int line, const char* function,
const char* entity, const char* context, const char* format, va_list args)
{
if (errorFrameCount < MOT_MAX_ERROR_FRAMES) {
ErrorFrame* errorFrame = &errorStack[errorFrameCount];
errorFrame->m_errorCode = errorCode;
errorFrame->m_severity = severity;
errorFrame->m_file = file;
errorFrame->m_line = line;
errorFrame->m_function = function;
errorFrame->m_entity = entity;
errorFrame->m_context = context;
va_list args2;
va_copy(args2, args);
errno_t erc =
vsnprintf_s(errorFrame->m_errorMessage, MOT_MAX_ERROR_MESSAGE, MOT_MAX_ERROR_MESSAGE - 1, format, args2);
securec_check_ss(erc, "\0", "\0");
++errorFrameCount;
}
}
extern void PushSystemError(int errorCode, int severity, const char* file, int line, const char* function,
const char* entity, const char* context, const char* systemCall)
{
errno_t erc;
const int bufSize = 256;
char errbuf[bufSize];
if (errorFrameCount < MOT_MAX_ERROR_FRAMES) {
ErrorFrame* errorFrame = &errorStack[errorFrameCount];
errorFrame->m_errorCode = MOT_ERROR_SYSTEM_FAILURE;
errorFrame->m_severity = severity;
errorFrame->m_file = file;
errorFrame->m_line = line;
errorFrame->m_function = function;
errorFrame->m_entity = entity;
errorFrame->m_context = context;
#if (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && !_GNU_SOURCE
strerror_r(errorCode, errbuf, bufSize);
erc = snprintf_s(errorFrame->m_errorMessage,
MOT_MAX_ERROR_MESSAGE,
MOT_MAX_ERROR_MESSAGE - 1,
"System call %s() failed: %s (error code: %d)",
systemCall,
errbuf,
errorCode);
#else
erc = snprintf_s(errorFrame->m_errorMessage,
MOT_MAX_ERROR_MESSAGE,
MOT_MAX_ERROR_MESSAGE - 1,
"System call %s() failed: %s (error code: %d)",
systemCall,
strerror_r(errorCode, errbuf, bufSize),
errorCode);
securec_check_ss(erc, "\0", "\0");
#endif
++errorFrameCount;
}
}
static void PrintErrorFrame(ErrorFrame* errorFrame)
{
fprintf(stderr,
"\nat %s() (%s:%d)\n"
"\tEntity : %s\n"
"\tContext : %s\n"
"\tError : %s\n"
"\tError Code: %d (%s)\n"
"\tSeverity : %d (%s)\n",
errorFrame->m_function,
errorFrame->m_file,
errorFrame->m_line,
errorFrame->m_entity,
errorFrame->m_context,
errorFrame->m_errorMessage,
errorFrame->m_errorCode,
ErrorCodeToString(errorFrame->m_errorCode),
errorFrame->m_severity,
SeverityToString(errorFrame->m_severity));
}
extern void PrintErrorStack()
{
for (int i = errorFrameCount - 1; i >= 0; --i) {
PrintErrorFrame(&errorStack[i]);
}
fprintf(stderr, "\n");
}
extern void ClearErrorStack()
{
errorFrameCount = 0;
lastErrorCode = MOT_NO_ERROR;
lastErrorSeverity = MOT_SEVERITY_NORMAL;
}
extern RC ErrorToRC(int errorCode)
{
switch (errorCode) {
case MOT_NO_ERROR:
return RC_OK;
case MOT_ERROR_OOM:
return RC_MEMORY_ALLOCATION_ERROR;
case MOT_ERROR_UNIQUE_VIOLATION:
return RC_UNIQUE_VIOLATION;
case MOT_ERROR_INVALID_CFG:
case MOT_ERROR_INVALID_ARG:
case MOT_ERROR_SYSTEM_FAILURE:
case MOT_ERROR_RESOURCE_LIMIT:
case MOT_ERROR_INTERNAL:
case MOT_ERROR_RESOURCE_UNAVAILABLE:
case MOT_ERROR_INVALID_MEMORY_SIZE:
default:
return RC_ERROR;
}
}
} // namespace MOT
| 29.417625 | 120 | 0.636494 |
73ae11d09c48fe3a211b70bcb657f26912d2af0b | 780 | hpp | C++ | include/lol/def/LolCollectionsCollectionsTopChampionMasteries.hpp | Maufeat/LeagueAPI | be7cb5093aab3f27d95b3c0e1d5700aa50126c47 | [
"BSD-3-Clause"
] | 1 | 2020-07-22T11:14:55.000Z | 2020-07-22T11:14:55.000Z | include/lol/def/LolCollectionsCollectionsTopChampionMasteries.hpp | Maufeat/LeagueAPI | be7cb5093aab3f27d95b3c0e1d5700aa50126c47 | [
"BSD-3-Clause"
] | null | null | null | include/lol/def/LolCollectionsCollectionsTopChampionMasteries.hpp | Maufeat/LeagueAPI | be7cb5093aab3f27d95b3c0e1d5700aa50126c47 | [
"BSD-3-Clause"
] | 4 | 2018-12-01T22:48:21.000Z | 2020-07-22T11:14:56.000Z | #pragma once
#include "../base_def.hpp"
#include "LolCollectionsCollectionsChampionMastery.hpp"
namespace lol {
struct LolCollectionsCollectionsTopChampionMasteries {
uint64_t summonerId;
uint64_t score;
std::vector<LolCollectionsCollectionsChampionMastery> masteries;
};
inline void to_json(json& j, const LolCollectionsCollectionsTopChampionMasteries& v) {
j["summonerId"] = v.summonerId;
j["score"] = v.score;
j["masteries"] = v.masteries;
}
inline void from_json(const json& j, LolCollectionsCollectionsTopChampionMasteries& v) {
v.summonerId = j.at("summonerId").get<uint64_t>();
v.score = j.at("score").get<uint64_t>();
v.masteries = j.at("masteries").get<std::vector<LolCollectionsCollectionsChampionMastery>>();
}
} | 39 | 98 | 0.725641 |
73ae4b067d02e1b8ff136d311fdc05d96d9a4614 | 49,584 | cpp | C++ | qtmultimedia/src/plugins/winrt/qwinrtcameracontrol.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | 1 | 2020-04-30T15:47:35.000Z | 2020-04-30T15:47:35.000Z | qtmultimedia/src/plugins/winrt/qwinrtcameracontrol.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | qtmultimedia/src/plugins/winrt/qwinrtcameracontrol.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd and/or its subsidiary(-ies).
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL3$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPLv3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or later as published by the Free
** Software Foundation and appearing in the file LICENSE.GPL included in
** the packaging of this file. Please review the following information to
** ensure the GNU General Public License version 2.0 requirements will be
** met: http://www.gnu.org/licenses/gpl-2.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qwinrtcameracontrol.h"
#include "qwinrtcameravideorenderercontrol.h"
#include "qwinrtvideodeviceselectorcontrol.h"
#include "qwinrtcameraimagecapturecontrol.h"
#include "qwinrtimageencodercontrol.h"
#include "qwinrtcamerafocuscontrol.h"
#include "qwinrtcameralockscontrol.h"
#include <QtCore/qfunctions_winrt.h>
#include <QtCore/QPointer>
#include <QtGui/QGuiApplication>
#include <private/qeventdispatcher_winrt_p.h>
#include <functional>
#include <mfapi.h>
#include <mferror.h>
#include <mfidl.h>
#include <wrl.h>
#include <windows.devices.enumeration.h>
#include <windows.media.capture.h>
#include <windows.storage.streams.h>
#include <windows.media.devices.h>
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;
using namespace ABI::Windows::Devices::Enumeration;
using namespace ABI::Windows::Foundation;
using namespace ABI::Windows::Foundation::Collections;
using namespace ABI::Windows::Media;
using namespace ABI::Windows::Media::Capture;
using namespace ABI::Windows::Media::Devices;
using namespace ABI::Windows::Media::MediaProperties;
using namespace ABI::Windows::Storage::Streams;
QT_BEGIN_NAMESPACE
#define RETURN_VOID_AND_EMIT_ERROR(msg) \
if (FAILED(hr)) { \
emit error(QCamera::CameraError, qt_error_string(hr)); \
RETURN_VOID_IF_FAILED(msg); \
}
#define FOCUS_RECT_SIZE 0.01f
#define FOCUS_RECT_HALF_SIZE 0.005f // FOCUS_RECT_SIZE / 2
#define FOCUS_RECT_BOUNDARY 1.0f
#define FOCUS_RECT_POSITION_MIN 0.0f
#define FOCUS_RECT_POSITION_MAX 0.995f // FOCUS_RECT_BOUNDARY - FOCUS_RECT_HALF_SIZE
#define ASPECTRATIO_EPSILON 0.01f
Q_LOGGING_CATEGORY(lcMMCamera, "qt.mm.camera")
HRESULT getMediaStreamResolutions(IMediaDeviceController *device,
MediaStreamType type,
IVectorView<IMediaEncodingProperties *> **propertiesList,
QVector<QSize> *resolutions)
{
HRESULT hr;
hr = device->GetAvailableMediaStreamProperties(type, propertiesList);
Q_ASSERT_SUCCEEDED(hr);
quint32 listSize;
hr = (*propertiesList)->get_Size(&listSize);
Q_ASSERT_SUCCEEDED(hr);
resolutions->reserve(listSize);
for (quint32 index = 0; index < listSize; ++index) {
ComPtr<IMediaEncodingProperties> properties;
hr = (*propertiesList)->GetAt(index, &properties);
Q_ASSERT_SUCCEEDED(hr);
HString propertyType;
hr = properties->get_Type(propertyType.GetAddressOf());
Q_ASSERT_SUCCEEDED(hr);
const HStringReference videoRef = HString::MakeReference(L"Video");
const HStringReference imageRef = HString::MakeReference(L"Image");
if (propertyType == videoRef) {
ComPtr<IVideoEncodingProperties> videoProperties;
hr = properties.As(&videoProperties);
Q_ASSERT_SUCCEEDED(hr);
UINT32 width, height;
hr = videoProperties->get_Width(&width);
Q_ASSERT_SUCCEEDED(hr);
hr = videoProperties->get_Height(&height);
Q_ASSERT_SUCCEEDED(hr);
resolutions->append(QSize(width, height));
} else if (propertyType == imageRef) {
ComPtr<IImageEncodingProperties> imageProperties;
hr = properties.As(&imageProperties);
Q_ASSERT_SUCCEEDED(hr);
UINT32 width, height;
hr = imageProperties->get_Width(&width);
Q_ASSERT_SUCCEEDED(hr);
hr = imageProperties->get_Height(&height);
Q_ASSERT_SUCCEEDED(hr);
resolutions->append(QSize(width, height));
}
}
return resolutions->isEmpty() ? MF_E_INVALID_FORMAT : hr;
}
template<typename T, size_t typeSize> struct CustomPropertyValue;
inline static ComPtr<IPropertyValueStatics> propertyValueStatics()
{
ComPtr<IPropertyValueStatics> valueStatics;
GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Foundation_PropertyValue).Get(), &valueStatics);
return valueStatics;
}
template <typename T>
struct CustomPropertyValue<T, 4>
{
static ComPtr<IReference<T>> create(T value)
{
ComPtr<IInspectable> propertyValueObject;
HRESULT hr = propertyValueStatics()->CreateUInt32(value, &propertyValueObject);
ComPtr<IReference<UINT32>> uint32Object;
Q_ASSERT_SUCCEEDED(hr);
hr = propertyValueObject.As(&uint32Object);
Q_ASSERT_SUCCEEDED(hr);
return reinterpret_cast<IReference<T> *>(uint32Object.Get());
}
};
template <typename T>
struct CustomPropertyValue<T, 8>
{
static ComPtr<IReference<T>> create(T value)
{
ComPtr<IInspectable> propertyValueObject;
HRESULT hr = propertyValueStatics()->CreateUInt64(value, &propertyValueObject);
ComPtr<IReference<UINT64>> uint64Object;
Q_ASSERT_SUCCEEDED(hr);
hr = propertyValueObject.As(&uint64Object);
Q_ASSERT_SUCCEEDED(hr);
return reinterpret_cast<IReference<T> *>(uint64Object.Get());
}
};
// Required camera point focus
class WindowsRegionOfInterestIterableIterator : public RuntimeClass<IIterator<RegionOfInterest *>>
{
public:
explicit WindowsRegionOfInterestIterableIterator(const ComPtr<IRegionOfInterest> &item)
{
regionOfInterest = item;
}
HRESULT __stdcall get_Current(IRegionOfInterest **current)
{
*current = regionOfInterest.Detach();
return S_OK;
}
HRESULT __stdcall get_HasCurrent(boolean *hasCurrent)
{
*hasCurrent = true;
return S_OK;
}
HRESULT __stdcall MoveNext(boolean *hasCurrent)
{
*hasCurrent = false;
return S_OK;
}
private:
ComPtr<IRegionOfInterest> regionOfInterest;
};
class WindowsRegionOfInterestIterable : public RuntimeClass<IIterable<RegionOfInterest *>>
{
public:
explicit WindowsRegionOfInterestIterable(const ComPtr<IRegionOfInterest> &item)
{
regionOfInterest = item;
}
HRESULT __stdcall First(IIterator<RegionOfInterest *> **first)
{
ComPtr<WindowsRegionOfInterestIterableIterator> iterator = Make<WindowsRegionOfInterestIterableIterator>(regionOfInterest);
*first = iterator.Detach();
return S_OK;
}
private:
ComPtr<IRegionOfInterest> regionOfInterest;
};
class MediaStream : public RuntimeClass<RuntimeClassFlags<WinRtClassicComMix>, IMFStreamSink, IMFMediaEventGenerator, IMFMediaTypeHandler>
{
public:
MediaStream(IMFMediaType *type, IMFMediaSink *mediaSink, QWinRTCameraVideoRendererControl *videoRenderer)
: m_type(type), m_sink(mediaSink), m_videoRenderer(videoRenderer)
{
Q_ASSERT(m_videoRenderer);
InitializeCriticalSectionEx(&m_mutex, 0, 0);
HRESULT hr;
hr = MFCreateEventQueue(&m_eventQueue);
Q_ASSERT_SUCCEEDED(hr);
hr = MFAllocateSerialWorkQueue(MFASYNC_CALLBACK_QUEUE_STANDARD, &m_workQueueId);
Q_ASSERT_SUCCEEDED(hr);
}
~MediaStream()
{
CriticalSectionLocker locker(&m_mutex);
m_eventQueue->Shutdown();
DeleteCriticalSection(&m_mutex);
}
HRESULT RequestSample()
{
if (m_pendingSamples.load() < 3) {
m_pendingSamples.ref();
return QueueEvent(MEStreamSinkRequestSample, GUID_NULL, S_OK, Q_NULLPTR);
}
return S_OK;
}
HRESULT __stdcall GetEvent(DWORD flags, IMFMediaEvent **event) Q_DECL_OVERRIDE
{
EnterCriticalSection(&m_mutex);
// Create an extra reference to avoid deadlock
ComPtr<IMFMediaEventQueue> eventQueue = m_eventQueue;
LeaveCriticalSection(&m_mutex);
return eventQueue->GetEvent(flags, event);
}
HRESULT __stdcall BeginGetEvent(IMFAsyncCallback *callback, IUnknown *state) Q_DECL_OVERRIDE
{
CriticalSectionLocker locker(&m_mutex);
HRESULT hr = m_eventQueue->BeginGetEvent(callback, state);
return hr;
}
HRESULT __stdcall EndGetEvent(IMFAsyncResult *result, IMFMediaEvent **event) Q_DECL_OVERRIDE
{
CriticalSectionLocker locker(&m_mutex);
return m_eventQueue->EndGetEvent(result, event);
}
HRESULT __stdcall QueueEvent(MediaEventType eventType, const GUID &extendedType, HRESULT status, const PROPVARIANT *value) Q_DECL_OVERRIDE
{
CriticalSectionLocker locker(&m_mutex);
return m_eventQueue->QueueEventParamVar(eventType, extendedType, status, value);
}
HRESULT __stdcall GetMediaSink(IMFMediaSink **mediaSink) Q_DECL_OVERRIDE
{
*mediaSink = m_sink;
return S_OK;
}
HRESULT __stdcall GetIdentifier(DWORD *identifier) Q_DECL_OVERRIDE
{
*identifier = 0;
return S_OK;
}
HRESULT __stdcall GetMediaTypeHandler(IMFMediaTypeHandler **handler) Q_DECL_OVERRIDE
{
return QueryInterface(IID_PPV_ARGS(handler));
}
HRESULT __stdcall ProcessSample(IMFSample *sample) Q_DECL_OVERRIDE
{
ComPtr<IMFMediaBuffer> buffer;
HRESULT hr = sample->GetBufferByIndex(0, &buffer);
RETURN_HR_IF_FAILED("Failed to get buffer from camera sample");
ComPtr<IMF2DBuffer> buffer2d;
hr = buffer.As(&buffer2d);
RETURN_HR_IF_FAILED("Failed to cast camera sample buffer to 2D buffer");
m_pendingSamples.deref();
m_videoRenderer->queueBuffer(buffer2d.Get());
return hr;
}
HRESULT __stdcall PlaceMarker(MFSTREAMSINK_MARKER_TYPE type, const PROPVARIANT *value, const PROPVARIANT *context) Q_DECL_OVERRIDE
{
Q_UNUSED(type);
Q_UNUSED(value);
QueueEvent(MEStreamSinkMarker, GUID_NULL, S_OK, context);
return S_OK;
}
HRESULT __stdcall Flush() Q_DECL_OVERRIDE
{
m_videoRenderer->discardBuffers();
m_pendingSamples.store(0);
return S_OK;
}
HRESULT __stdcall IsMediaTypeSupported(IMFMediaType *type, IMFMediaType **) Q_DECL_OVERRIDE
{
HRESULT hr;
GUID majorType;
hr = type->GetMajorType(&majorType);
Q_ASSERT_SUCCEEDED(hr);
if (!IsEqualGUID(majorType, MFMediaType_Video))
return MF_E_INVALIDMEDIATYPE;
return S_OK;
}
HRESULT __stdcall GetMediaTypeCount(DWORD *typeCount) Q_DECL_OVERRIDE
{
*typeCount = 1;
return S_OK;
}
HRESULT __stdcall GetMediaTypeByIndex(DWORD index, IMFMediaType **type) Q_DECL_OVERRIDE
{
if (index == 0)
return m_type.CopyTo(type);
return E_BOUNDS;
}
HRESULT __stdcall SetCurrentMediaType(IMFMediaType *type) Q_DECL_OVERRIDE
{
if (FAILED(IsMediaTypeSupported(type, Q_NULLPTR)))
return MF_E_INVALIDREQUEST;
m_type = type;
return S_OK;
}
HRESULT __stdcall GetCurrentMediaType(IMFMediaType **type) Q_DECL_OVERRIDE
{
return m_type.CopyTo(type);
}
HRESULT __stdcall GetMajorType(GUID *majorType) Q_DECL_OVERRIDE
{
return m_type->GetMajorType(majorType);
}
private:
CRITICAL_SECTION m_mutex;
ComPtr<IMFMediaType> m_type;
IMFMediaSink *m_sink;
ComPtr<IMFMediaEventQueue> m_eventQueue;
DWORD m_workQueueId;
QWinRTCameraVideoRendererControl *m_videoRenderer;
QAtomicInt m_pendingSamples;
};
class MediaSink : public RuntimeClass<RuntimeClassFlags<WinRtClassicComMix>, IMediaExtension, IMFMediaSink, IMFClockStateSink>
{
public:
MediaSink(IMediaEncodingProfile *encodingProfile, QWinRTCameraVideoRendererControl *videoRenderer)
: m_videoRenderer(videoRenderer)
{
HRESULT hr;
ComPtr<IVideoEncodingProperties> videoProperties;
hr = encodingProfile->get_Video(&videoProperties);
RETURN_VOID_IF_FAILED("Failed to get video properties");
ComPtr<IMFMediaType> videoType;
hr = MFCreateMediaTypeFromProperties(videoProperties.Get(), &videoType);
RETURN_VOID_IF_FAILED("Failed to create video type");
m_stream = Make<MediaStream>(videoType.Get(), this, videoRenderer);
}
~MediaSink()
{
}
HRESULT RequestSample()
{
return m_stream->RequestSample();
}
HRESULT __stdcall SetProperties(Collections::IPropertySet *configuration) Q_DECL_OVERRIDE
{
Q_UNUSED(configuration);
return E_NOTIMPL;
}
HRESULT __stdcall GetCharacteristics(DWORD *characteristics) Q_DECL_OVERRIDE
{
*characteristics = MEDIASINK_FIXED_STREAMS | MEDIASINK_RATELESS;
return S_OK;
}
HRESULT __stdcall AddStreamSink(DWORD streamSinkIdentifier, IMFMediaType *mediaType, IMFStreamSink **streamSink) Q_DECL_OVERRIDE
{
Q_UNUSED(streamSinkIdentifier);
Q_UNUSED(mediaType);
Q_UNUSED(streamSink);
return E_NOTIMPL;
}
HRESULT __stdcall RemoveStreamSink(DWORD streamSinkIdentifier) Q_DECL_OVERRIDE
{
Q_UNUSED(streamSinkIdentifier);
return E_NOTIMPL;
}
HRESULT __stdcall GetStreamSinkCount(DWORD *streamSinkCount) Q_DECL_OVERRIDE
{
*streamSinkCount = 1;
return S_OK;
}
HRESULT __stdcall GetStreamSinkByIndex(DWORD index, IMFStreamSink **streamSink) Q_DECL_OVERRIDE
{
if (index == 0)
return m_stream.CopyTo(streamSink);
return MF_E_INVALIDINDEX;
}
HRESULT __stdcall GetStreamSinkById(DWORD streamSinkIdentifier, IMFStreamSink **streamSink) Q_DECL_OVERRIDE
{
// ID and index are always 0
HRESULT hr = GetStreamSinkByIndex(streamSinkIdentifier, streamSink);
return hr == MF_E_INVALIDINDEX ? MF_E_INVALIDSTREAMNUMBER : hr;
}
HRESULT __stdcall SetPresentationClock(IMFPresentationClock *presentationClock) Q_DECL_OVERRIDE
{
HRESULT hr = S_OK;
m_presentationClock = presentationClock;
if (m_presentationClock)
hr = m_presentationClock->AddClockStateSink(this);
return hr;
}
HRESULT __stdcall GetPresentationClock(IMFPresentationClock **presentationClock) Q_DECL_OVERRIDE
{
return m_presentationClock.CopyTo(presentationClock);
}
HRESULT __stdcall Shutdown() Q_DECL_OVERRIDE
{
m_stream->Flush();
scheduleSetActive(false);
return m_presentationClock ? m_presentationClock->Stop() : S_OK;
}
HRESULT __stdcall OnClockStart(MFTIME systemTime, LONGLONG clockStartOffset) Q_DECL_OVERRIDE
{
Q_UNUSED(systemTime);
Q_UNUSED(clockStartOffset);
scheduleSetActive(true);
return S_OK;
}
HRESULT __stdcall OnClockStop(MFTIME systemTime) Q_DECL_OVERRIDE
{
Q_UNUSED(systemTime);
scheduleSetActive(false);
return m_stream->QueueEvent(MEStreamSinkStopped, GUID_NULL, S_OK, Q_NULLPTR);
}
HRESULT __stdcall OnClockPause(MFTIME systemTime) Q_DECL_OVERRIDE
{
Q_UNUSED(systemTime);
scheduleSetActive(false);
return m_stream->QueueEvent(MEStreamSinkPaused, GUID_NULL, S_OK, Q_NULLPTR);
}
HRESULT __stdcall OnClockRestart(MFTIME systemTime) Q_DECL_OVERRIDE
{
Q_UNUSED(systemTime);
scheduleSetActive(true);
return m_stream->QueueEvent(MEStreamSinkStarted, GUID_NULL, S_OK, Q_NULLPTR);
}
HRESULT __stdcall OnClockSetRate(MFTIME systemTime, float rate) Q_DECL_OVERRIDE
{
Q_UNUSED(systemTime);
Q_UNUSED(rate);
return E_NOTIMPL;
}
private:
inline void scheduleSetActive(bool active)
{
QMetaObject::invokeMethod(m_videoRenderer, "setActive", Qt::QueuedConnection, Q_ARG(bool, active));
}
ComPtr<MediaStream> m_stream;
ComPtr<IMFPresentationClock> m_presentationClock;
QWinRTCameraVideoRendererControl *m_videoRenderer;
};
class QWinRTCameraControlPrivate
{
public:
QCamera::State state;
QCamera::Status status;
QCamera::CaptureModes captureMode;
ComPtr<IMediaCapture> capture;
ComPtr<IMediaCaptureVideoPreview> capturePreview;
EventRegistrationToken captureFailedCookie;
EventRegistrationToken recordLimitationCookie;
ComPtr<IMediaEncodingProfileStatics> encodingProfileFactory;
ComPtr<IMediaEncodingProfile> encodingProfile;
ComPtr<MediaSink> mediaSink;
ComPtr<IFocusControl> focusControl;
ComPtr<IRegionsOfInterestControl> regionsOfInterestControl;
ComPtr<IAsyncAction> focusOperation;
QPointer<QWinRTCameraVideoRendererControl> videoRenderer;
QPointer<QWinRTVideoDeviceSelectorControl> videoDeviceSelector;
QPointer<QWinRTCameraImageCaptureControl> imageCaptureControl;
QPointer<QWinRTImageEncoderControl> imageEncoderControl;
QPointer<QWinRTCameraFocusControl> cameraFocusControl;
QPointer<QWinRTCameraLocksControl> cameraLocksControl;
QAtomicInt framesMapped;
QEventLoop *delayClose;
};
QWinRTCameraControl::QWinRTCameraControl(QObject *parent)
: QCameraControl(parent), d_ptr(new QWinRTCameraControlPrivate)
{
qCDebug(lcMMCamera) << __FUNCTION__ << parent;
Q_D(QWinRTCameraControl);
d->delayClose = nullptr;
d->state = QCamera::UnloadedState;
d->status = QCamera::UnloadedStatus;
d->captureMode = QCamera::CaptureStillImage;
d->captureFailedCookie.value = 0;
d->recordLimitationCookie.value = 0;
d->videoRenderer = new QWinRTCameraVideoRendererControl(QSize(), this);
connect(d->videoRenderer, &QWinRTCameraVideoRendererControl::bufferRequested,
this, &QWinRTCameraControl::onBufferRequested);
d->videoDeviceSelector = new QWinRTVideoDeviceSelectorControl(this);
d->imageCaptureControl = new QWinRTCameraImageCaptureControl(this);
d->imageEncoderControl = new QWinRTImageEncoderControl(this);
d->cameraFocusControl = new QWinRTCameraFocusControl(this);
d->cameraLocksControl = new QWinRTCameraLocksControl(this);
if (qGuiApp) {
connect(qGuiApp, &QGuiApplication::applicationStateChanged,
this, &QWinRTCameraControl::onApplicationStateChanged);
}
}
QWinRTCameraControl::~QWinRTCameraControl()
{
setState(QCamera::UnloadedState);
}
QCamera::State QWinRTCameraControl::state() const
{
Q_D(const QWinRTCameraControl);
return d->state;
}
void QWinRTCameraControl::setState(QCamera::State state)
{
qCDebug(lcMMCamera) << __FUNCTION__ << state;
Q_D(QWinRTCameraControl);
if (d->state == state)
return;
HRESULT hr;
switch (state) {
case QCamera::ActiveState: {
// Capture has not been created or initialized
if (d->state == QCamera::UnloadedState) {
hr = initialize();
RETURN_VOID_AND_EMIT_ERROR("Failed to initialize media capture");
}
Q_ASSERT(d->state == QCamera::LoadedState);
ComPtr<IAsyncAction> op;
hr = QEventDispatcherWinRT::runOnXamlThread([d, &op]() {
d->mediaSink = Make<MediaSink>(d->encodingProfile.Get(), d->videoRenderer);
HRESULT hr = d->capturePreview->StartPreviewToCustomSinkAsync(d->encodingProfile.Get(), d->mediaSink.Get(), &op);
return hr;
});
RETURN_VOID_AND_EMIT_ERROR("Failed to initiate capture.");
if (d->status != QCamera::StartingStatus) {
d->status = QCamera::StartingStatus;
emit statusChanged(d->status);
}
hr = QEventDispatcherWinRT::runOnXamlThread([&op]() {
return QWinRTFunctions::await(op);
});
if (FAILED(hr)) {
emit error(QCamera::CameraError, qt_error_string(hr));
setState(QCamera::UnloadedState); // Unload everything, as initialize() will need be called again
return;
}
QCameraFocus::FocusModes focusMode = d->cameraFocusControl->focusMode();
if (focusMode != 0 && setFocus(focusMode) && focusMode == QCameraFocus::ContinuousFocus)
focus();
d->state = QCamera::ActiveState;
emit stateChanged(d->state);
d->status = QCamera::ActiveStatus;
emit statusChanged(d->status);
QEventDispatcherWinRT::runOnXamlThread([d]() { d->mediaSink->RequestSample(); return S_OK;});
break;
}
case QCamera::LoadedState: {
// If moving from unloaded, initialize the camera
if (d->state == QCamera::UnloadedState) {
hr = initialize();
RETURN_VOID_AND_EMIT_ERROR("Failed to initialize media capture");
}
// fall through
}
case QCamera::UnloadedState: {
// Stop the camera if it is running (transition to LoadedState)
if (d->status == QCamera::ActiveStatus) {
HRESULT hr;
if (d->focusOperation) {
hr = QWinRTFunctions::await(d->focusOperation);
Q_ASSERT_SUCCEEDED(hr);
}
if (d->framesMapped > 0) {
qWarning("%d QVideoFrame(s) mapped when closing down camera. Camera will wait for unmap before closing down.",
d->framesMapped);
if (!d->delayClose)
d->delayClose = new QEventLoop(this);
d->delayClose->exec();
}
ComPtr<IAsyncAction> op;
hr = QEventDispatcherWinRT::runOnXamlThread([d, &op]() {
HRESULT hr = d->capturePreview->StopPreviewAsync(&op);
return hr;
});
RETURN_VOID_AND_EMIT_ERROR("Failed to stop camera preview");
if (d->status != QCamera::StoppingStatus) {
d->status = QCamera::StoppingStatus;
emit statusChanged(d->status);
}
Q_ASSERT_SUCCEEDED(hr);
hr = QEventDispatcherWinRT::runOnXamlThread([&op]() {
return QWinRTFunctions::await(op); // Synchronize unloading
});
if (FAILED(hr))
emit error(QCamera::InvalidRequestError, qt_error_string(hr));
if (d->mediaSink) {
hr = QEventDispatcherWinRT::runOnXamlThread([d]() {
d->mediaSink->Shutdown();
d->mediaSink.Reset();
return S_OK;
});
}
d->state = QCamera::LoadedState;
emit stateChanged(d->state);
d->status = QCamera::LoadedStatus;
emit statusChanged(d->status);
}
// Completely unload if needed
if (state == QCamera::UnloadedState) {
if (!d->capture) // Already unloaded
break;
if (d->status != QCamera::UnloadingStatus) {
d->status = QCamera::UnloadingStatus;
emit statusChanged(d->status);
}
hr = QEventDispatcherWinRT::runOnXamlThread([d]() {
HRESULT hr;
if (d->capture && d->captureFailedCookie.value) {
hr = d->capture->remove_Failed(d->captureFailedCookie);
Q_ASSERT_SUCCEEDED(hr);
d->captureFailedCookie.value = 0;
}
if (d->capture && d->recordLimitationCookie.value) {
d->capture->remove_RecordLimitationExceeded(d->recordLimitationCookie);
Q_ASSERT_SUCCEEDED(hr);
d->recordLimitationCookie.value = 0;
}
ComPtr<IClosable> capture;
hr = d->capture.As(&capture);
Q_ASSERT_SUCCEEDED(hr);
hr = capture->Close();
RETURN_HR_IF_FAILED("");
d->capture.Reset();
return hr;
});
RETURN_VOID_AND_EMIT_ERROR("Failed to close the capture manger");
if (d->state != QCamera::UnloadedState) {
d->state = QCamera::UnloadedState;
emit stateChanged(d->state);
}
if (d->status != QCamera::UnloadedStatus) {
d->status = QCamera::UnloadedStatus;
emit statusChanged(d->status);
}
}
break;
}
default:
break;
}
}
QCamera::Status QWinRTCameraControl::status() const
{
Q_D(const QWinRTCameraControl);
return d->status;
}
QCamera::CaptureModes QWinRTCameraControl::captureMode() const
{
Q_D(const QWinRTCameraControl);
return d->captureMode;
}
void QWinRTCameraControl::setCaptureMode(QCamera::CaptureModes mode)
{
qCDebug(lcMMCamera) << __FUNCTION__ << mode;
Q_D(QWinRTCameraControl);
if (d->captureMode == mode)
return;
if (!isCaptureModeSupported(mode)) {
qWarning("Unsupported capture mode: %d", mode);
return;
}
d->captureMode = mode;
emit captureModeChanged(d->captureMode);
}
bool QWinRTCameraControl::isCaptureModeSupported(QCamera::CaptureModes mode) const
{
return mode >= QCamera::CaptureViewfinder && mode <= QCamera::CaptureStillImage;
}
bool QWinRTCameraControl::canChangeProperty(QCameraControl::PropertyChangeType changeType, QCamera::Status status) const
{
Q_UNUSED(changeType);
return status == QCamera::UnloadedStatus; // For now, assume shutdown is required for all property changes
}
QVideoRendererControl *QWinRTCameraControl::videoRenderer() const
{
Q_D(const QWinRTCameraControl);
return d->videoRenderer;
}
QVideoDeviceSelectorControl *QWinRTCameraControl::videoDeviceSelector() const
{
Q_D(const QWinRTCameraControl);
return d->videoDeviceSelector;
}
QCameraImageCaptureControl *QWinRTCameraControl::imageCaptureControl() const
{
Q_D(const QWinRTCameraControl);
return d->imageCaptureControl;
}
QImageEncoderControl *QWinRTCameraControl::imageEncoderControl() const
{
Q_D(const QWinRTCameraControl);
return d->imageEncoderControl;
}
QCameraFocusControl *QWinRTCameraControl::cameraFocusControl() const
{
Q_D(const QWinRTCameraControl);
return d->cameraFocusControl;
}
QCameraLocksControl *QWinRTCameraControl::cameraLocksControl() const
{
Q_D(const QWinRTCameraControl);
return d->cameraLocksControl;
}
Microsoft::WRL::ComPtr<ABI::Windows::Media::Capture::IMediaCapture> QWinRTCameraControl::handle() const
{
Q_D(const QWinRTCameraControl);
return d->capture;
}
void QWinRTCameraControl::onBufferRequested()
{
Q_D(QWinRTCameraControl);
if (d->mediaSink)
d->mediaSink->RequestSample();
}
void QWinRTCameraControl::onApplicationStateChanged(Qt::ApplicationState state)
{
qCDebug(lcMMCamera) << __FUNCTION__ << state;
#ifdef _DEBUG
return;
#else // !_DEBUG
Q_D(QWinRTCameraControl);
static QCamera::State savedState = d->state;
switch (state) {
case Qt::ApplicationInactive:
if (d->state != QCamera::UnloadedState) {
savedState = d->state;
setState(QCamera::UnloadedState);
}
break;
case Qt::ApplicationActive:
setState(QCamera::State(savedState));
break;
default:
break;
}
#endif // _DEBUG
}
HRESULT QWinRTCameraControl::initialize()
{
qCDebug(lcMMCamera) << __FUNCTION__;
Q_D(QWinRTCameraControl);
if (d->status != QCamera::LoadingStatus) {
d->status = QCamera::LoadingStatus;
emit statusChanged(d->status);
}
HRESULT hr = QEventDispatcherWinRT::runOnXamlThread([this, d]() {
HRESULT hr;
ComPtr<IInspectable> capture;
hr = RoActivateInstance(Wrappers::HString::MakeReference(RuntimeClass_Windows_Media_Capture_MediaCapture).Get(),
&capture);
Q_ASSERT_SUCCEEDED(hr);
hr = capture.As(&d->capture);
Q_ASSERT_SUCCEEDED(hr);
hr = d->capture.As(&d->capturePreview);
Q_ASSERT_SUCCEEDED(hr);
hr = d->capture->add_Failed(Callback<IMediaCaptureFailedEventHandler>(this, &QWinRTCameraControl::onCaptureFailed).Get(),
&d->captureFailedCookie);
Q_ASSERT_SUCCEEDED(hr);
hr = d->capture->add_RecordLimitationExceeded(Callback<IRecordLimitationExceededEventHandler>(this, &QWinRTCameraControl::onRecordLimitationExceeded).Get(),
&d->recordLimitationCookie);
Q_ASSERT_SUCCEEDED(hr);
hr = RoGetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Media_MediaProperties_MediaEncodingProfile).Get(),
IID_PPV_ARGS(&d->encodingProfileFactory));
Q_ASSERT_SUCCEEDED(hr);
int deviceIndex = d->videoDeviceSelector->selectedDevice();
if (deviceIndex < 0)
deviceIndex = d->videoDeviceSelector->defaultDevice();
const QString deviceName = d->videoDeviceSelector->deviceName(deviceIndex);
if (deviceName.isEmpty()) {
qWarning("No video device available or selected.");
return E_FAIL;
}
const QCamera::Position position = d->videoDeviceSelector->cameraPosition(deviceName);
d->videoRenderer->setScanLineDirection(position == QCamera::BackFace ? QVideoSurfaceFormat::TopToBottom
: QVideoSurfaceFormat::BottomToTop);
ComPtr<IMediaCaptureInitializationSettings> settings;
hr = RoActivateInstance(HString::MakeReference(RuntimeClass_Windows_Media_Capture_MediaCaptureInitializationSettings).Get(),
&settings);
Q_ASSERT_SUCCEEDED(hr);
HStringReference deviceId(reinterpret_cast<LPCWSTR>(deviceName.utf16()), deviceName.length());
hr = settings->put_VideoDeviceId(deviceId.Get());
Q_ASSERT_SUCCEEDED(hr);
hr = settings->put_StreamingCaptureMode(StreamingCaptureMode_Video);
Q_ASSERT_SUCCEEDED(hr);
hr = settings->put_PhotoCaptureSource(PhotoCaptureSource_Auto);
Q_ASSERT_SUCCEEDED(hr);
ComPtr<IAsyncAction> op;
hr = d->capture->InitializeWithSettingsAsync(settings.Get(), &op);
RETURN_HR_IF_FAILED("Failed to begin initialization of media capture manager");
hr = QWinRTFunctions::await(op, QWinRTFunctions::ProcessThreadEvents);
if (hr == E_ACCESSDENIED) {
qWarning("Access denied when initializing the media capture manager. "
"Check your manifest settings for microphone and webcam access.");
}
RETURN_HR_IF_FAILED("Failed to initialize media capture manager");
ComPtr<IVideoDeviceController> videoDeviceController;
hr = d->capture->get_VideoDeviceController(&videoDeviceController);
ComPtr<IAdvancedVideoCaptureDeviceController2> advancedVideoDeviceController;
hr = videoDeviceController.As(&advancedVideoDeviceController);
Q_ASSERT_SUCCEEDED(hr);
hr = advancedVideoDeviceController->get_FocusControl(&d->focusControl);
Q_ASSERT_SUCCEEDED(hr);
boolean isFocusSupported;
hr = d->focusControl->get_Supported(&isFocusSupported);
Q_ASSERT_SUCCEEDED(hr);
if (isFocusSupported) {
hr = advancedVideoDeviceController->get_RegionsOfInterestControl(&d->regionsOfInterestControl);
if (FAILED(hr))
qCDebug(lcMMCamera) << "Focus supported, but no control for regions of interest available";
hr = initializeFocus();
Q_ASSERT_SUCCEEDED(hr);
} else {
d->cameraFocusControl->setSupportedFocusMode(0);
d->cameraFocusControl->setSupportedFocusPointMode(QSet<QCameraFocus::FocusPointMode>());
}
d->cameraLocksControl->initialize();
Q_ASSERT_SUCCEEDED(hr);
ComPtr<IMediaDeviceController> deviceController;
hr = videoDeviceController.As(&deviceController);
Q_ASSERT_SUCCEEDED(hr);
// Get preview stream properties.
ComPtr<IVectorView<IMediaEncodingProperties *>> previewPropertiesList;
QVector<QSize> previewResolutions;
hr = getMediaStreamResolutions(deviceController.Get(),
MediaStreamType_VideoPreview,
&previewPropertiesList,
&previewResolutions);
RETURN_HR_IF_FAILED("Failed to find a suitable video format");
MediaStreamType mediaStreamType =
d->captureMode == QCamera::CaptureVideo ? MediaStreamType_VideoRecord : MediaStreamType_Photo;
// Get capture stream properties.
ComPtr<IVectorView<IMediaEncodingProperties *>> capturePropertiesList;
QVector<QSize> captureResolutions;
hr = getMediaStreamResolutions(deviceController.Get(),
mediaStreamType,
&capturePropertiesList,
&captureResolutions);
RETURN_HR_IF_FAILED("Failed to find a suitable video format");
// Set capture resolutions.
d->imageEncoderControl->setSupportedResolutionsList(captureResolutions.toList());
const QSize captureResolution = d->imageEncoderControl->imageSettings().resolution();
const quint32 captureResolutionIndex = captureResolutions.indexOf(captureResolution);
ComPtr<IMediaEncodingProperties> captureProperties;
hr = capturePropertiesList->GetAt(captureResolutionIndex, &captureProperties);
Q_ASSERT_SUCCEEDED(hr);
hr = deviceController->SetMediaStreamPropertiesAsync(mediaStreamType, captureProperties.Get(), &op);
Q_ASSERT_SUCCEEDED(hr);
hr = QWinRTFunctions::await(op);
Q_ASSERT_SUCCEEDED(hr);
// Set preview resolution.
QVector<QSize> filtered;
const float captureAspectRatio = float(captureResolution.width()) / captureResolution.height();
foreach (const QSize &resolution, previewResolutions) {
const float aspectRatio = float(resolution.width()) / resolution.height();
if (qAbs(aspectRatio - captureAspectRatio) <= ASPECTRATIO_EPSILON)
filtered.append(resolution);
}
qSort(filtered.begin(),
filtered.end(),
[](QSize size1, QSize size2) { return size1.width() * size1.height() < size2.width() * size2.height(); });
const QSize &viewfinderResolution = filtered.first();
const quint32 viewfinderResolutionIndex = previewResolutions.indexOf(viewfinderResolution);
hr = RoActivateInstance(HString::MakeReference(RuntimeClass_Windows_Media_MediaProperties_MediaEncodingProfile).Get(),
&d->encodingProfile);
Q_ASSERT_SUCCEEDED(hr);
ComPtr<IMediaEncodingProperties> previewProperties;
hr = previewPropertiesList->GetAt(viewfinderResolutionIndex, &previewProperties);
Q_ASSERT_SUCCEEDED(hr);
hr = deviceController->SetMediaStreamPropertiesAsync(MediaStreamType_VideoPreview, previewProperties.Get(), &op);
Q_ASSERT_SUCCEEDED(hr);
hr = QWinRTFunctions::await(op);
Q_ASSERT_SUCCEEDED(hr);
ComPtr<IVideoEncodingProperties> videoPreviewProperties;
hr = previewProperties.As(&videoPreviewProperties);
Q_ASSERT_SUCCEEDED(hr);
hr = d->encodingProfile->put_Video(videoPreviewProperties.Get());
Q_ASSERT_SUCCEEDED(hr);
if (d->videoRenderer)
d->videoRenderer->setSize(viewfinderResolution);
return S_OK;
});
if (SUCCEEDED(hr) && d->state != QCamera::LoadedState) {
d->state = QCamera::LoadedState;
emit stateChanged(d->state);
}
if (SUCCEEDED(hr) && d->status != QCamera::LoadedStatus) {
d->status = QCamera::LoadedStatus;
emit statusChanged(d->status);
}
return hr;
}
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP)
HRESULT QWinRTCameraControl::initializeFocus()
{
Q_D(QWinRTCameraControl);
ComPtr<IFocusControl2> focusControl2;
HRESULT hr = d->focusControl.As(&focusControl2);
Q_ASSERT_SUCCEEDED(hr);
ComPtr<IVectorView<enum FocusMode>> focusModes;
hr = focusControl2->get_SupportedFocusModes(&focusModes);
if (FAILED(hr)) {
d->cameraFocusControl->setSupportedFocusMode(0);
d->cameraFocusControl->setSupportedFocusPointMode(QSet<QCameraFocus::FocusPointMode>());
qErrnoWarning(hr, "Failed to get camera supported focus mode list");
return hr;
}
quint32 size;
hr = focusModes->get_Size(&size);
Q_ASSERT_SUCCEEDED(hr);
QCameraFocus::FocusModes supportedModeFlag = 0;
for (quint32 i = 0; i < size; ++i) {
FocusMode mode;
hr = focusModes->GetAt(i, &mode);
Q_ASSERT_SUCCEEDED(hr);
switch (mode) {
case FocusMode_Continuous:
supportedModeFlag |= QCameraFocus::ContinuousFocus;
break;
case FocusMode_Single:
supportedModeFlag |= QCameraFocus::AutoFocus;
break;
default:
break;
}
}
ComPtr<IVectorView<enum AutoFocusRange>> focusRange;
hr = focusControl2->get_SupportedFocusRanges(&focusRange);
if (FAILED(hr)) {
qErrnoWarning(hr, "Failed to get camera supported focus range list");
} else {
hr = focusRange->get_Size(&size);
Q_ASSERT_SUCCEEDED(hr);
for (quint32 i = 0; i < size; ++i) {
AutoFocusRange range;
hr = focusRange->GetAt(i, &range);
Q_ASSERT_SUCCEEDED(hr);
switch (range) {
case AutoFocusRange_Macro:
supportedModeFlag |= QCameraFocus::MacroFocus;
break;
case AutoFocusRange_FullRange:
supportedModeFlag |= QCameraFocus::InfinityFocus;
break;
default:
break;
}
}
}
d->cameraFocusControl->setSupportedFocusMode(supportedModeFlag);
if (!d->regionsOfInterestControl) {
d->cameraFocusControl->setSupportedFocusPointMode(QSet<QCameraFocus::FocusPointMode>());
return S_OK;
}
boolean isRegionsfocusSupported = false;
hr = d->regionsOfInterestControl->get_AutoFocusSupported(&isRegionsfocusSupported);
Q_ASSERT_SUCCEEDED(hr);
UINT32 maxRegions;
hr = d->regionsOfInterestControl->get_MaxRegions(&maxRegions);
Q_ASSERT_SUCCEEDED(hr);
if (!isRegionsfocusSupported || maxRegions == 0) {
d->cameraFocusControl->setSupportedFocusPointMode(QSet<QCameraFocus::FocusPointMode>());
return S_OK;
}
QSet<QCameraFocus::FocusPointMode> supportedFocusPointModes;
supportedFocusPointModes << QCameraFocus::FocusPointCustom
<< QCameraFocus::FocusPointCenter
<< QCameraFocus::FocusPointAuto;
d->cameraFocusControl->setSupportedFocusPointMode(supportedFocusPointModes);
return S_OK;
}
bool QWinRTCameraControl::setFocus(QCameraFocus::FocusModes modes)
{
Q_D(QWinRTCameraControl);
if (d->status == QCamera::UnloadedStatus)
return false;
bool result = false;
HRESULT hr = QEventDispatcherWinRT::runOnXamlThread([modes, &result, d, this]() {
ComPtr<IFocusSettings> focusSettings;
ComPtr<IInspectable> focusSettingsObject;
HRESULT hr = RoActivateInstance(HString::MakeReference(RuntimeClass_Windows_Media_Devices_FocusSettings).Get(), &focusSettingsObject);
Q_ASSERT_SUCCEEDED(hr);
hr = focusSettingsObject.As(&focusSettings);
Q_ASSERT_SUCCEEDED(hr);
FocusMode mode;
if (modes.testFlag(QCameraFocus::ContinuousFocus)) {
mode = FocusMode_Continuous;
} else if (modes.testFlag(QCameraFocus::AutoFocus)
|| modes.testFlag(QCameraFocus::MacroFocus)
|| modes.testFlag(QCameraFocus::InfinityFocus)) {
// The Macro and infinity focus modes are only supported in auto focus mode on WinRT.
// QML camera focus doesn't support combined focus flags settings. In the case of macro
// and infinity Focus modes, the auto focus setting is applied.
mode = FocusMode_Single;
} else {
emit error(QCamera::NotSupportedFeatureError, QStringLiteral("Unsupported camera focus modes."));
result = false;
return S_OK;
}
hr = focusSettings->put_Mode(mode);
Q_ASSERT_SUCCEEDED(hr);
AutoFocusRange range = AutoFocusRange_Normal;
if (modes.testFlag(QCameraFocus::MacroFocus))
range = AutoFocusRange_Macro;
else if (modes.testFlag(QCameraFocus::InfinityFocus))
range = AutoFocusRange_FullRange;
hr = focusSettings->put_AutoFocusRange(range);
Q_ASSERT_SUCCEEDED(hr);
hr = focusSettings->put_WaitForFocus(true);
Q_ASSERT_SUCCEEDED(hr);
hr = focusSettings->put_DisableDriverFallback(false);
Q_ASSERT_SUCCEEDED(hr);
ComPtr<IFocusControl2> focusControl2;
hr = d->focusControl.As(&focusControl2);
Q_ASSERT_SUCCEEDED(hr);
hr = focusControl2->Configure(focusSettings.Get());
result = SUCCEEDED(hr);
RETURN_OK_IF_FAILED("Failed to configure camera focus control");
return S_OK;
});
Q_ASSERT_SUCCEEDED(hr);
Q_UNUSED(hr); // Silence release build
return result;
}
bool QWinRTCameraControl::setFocusPoint(const QPointF &focusPoint)
{
Q_D(QWinRTCameraControl);
if (focusPoint.x() < FOCUS_RECT_POSITION_MIN || focusPoint.x() > FOCUS_RECT_BOUNDARY) {
emit error(QCamera::CameraError, QStringLiteral("Focus horizontal location should be between 0.0 and 1.0."));
return false;
}
if (focusPoint.y() < FOCUS_RECT_POSITION_MIN || focusPoint.y() > FOCUS_RECT_BOUNDARY) {
emit error(QCamera::CameraError, QStringLiteral("Focus vertical location should be between 0.0 and 1.0."));
return false;
}
ABI::Windows::Foundation::Rect rect;
rect.X = qBound<float>(FOCUS_RECT_POSITION_MIN, focusPoint.x() - FOCUS_RECT_HALF_SIZE, FOCUS_RECT_POSITION_MAX);
rect.Y = qBound<float>(FOCUS_RECT_POSITION_MIN, focusPoint.y() - FOCUS_RECT_HALF_SIZE, FOCUS_RECT_POSITION_MAX);
rect.Width = (rect.X + FOCUS_RECT_SIZE) < FOCUS_RECT_BOUNDARY ? FOCUS_RECT_SIZE : FOCUS_RECT_BOUNDARY - rect.X;
rect.Height = (rect.Y + FOCUS_RECT_SIZE) < FOCUS_RECT_BOUNDARY ? FOCUS_RECT_SIZE : FOCUS_RECT_BOUNDARY - rect.Y;
ComPtr<IRegionOfInterest> regionOfInterest;
ComPtr<IInspectable> regionOfInterestObject;
HRESULT hr = RoActivateInstance(HString::MakeReference(RuntimeClass_Windows_Media_Devices_RegionOfInterest).Get(), ®ionOfInterestObject);
Q_ASSERT_SUCCEEDED(hr);
hr = regionOfInterestObject.As(®ionOfInterest);
Q_ASSERT_SUCCEEDED(hr);
ComPtr<IRegionOfInterest2> regionOfInterest2;
hr = regionOfInterestObject.As(®ionOfInterest2);
Q_ASSERT_SUCCEEDED(hr);
hr = regionOfInterest2->put_BoundsNormalized(true);
Q_ASSERT_SUCCEEDED(hr);
hr = regionOfInterest2->put_Weight(1);
Q_ASSERT_SUCCEEDED(hr);
hr = regionOfInterest2->put_Type(RegionOfInterestType_Unknown);
Q_ASSERT_SUCCEEDED(hr);
hr = regionOfInterest->put_AutoFocusEnabled(true);
Q_ASSERT_SUCCEEDED(hr);
hr = regionOfInterest->put_Bounds(rect);
Q_ASSERT_SUCCEEDED(hr);
ComPtr<WindowsRegionOfInterestIterable> regionOfInterestIterable = Make<WindowsRegionOfInterestIterable>(regionOfInterest);
ComPtr<IAsyncAction> op;
hr = d->regionsOfInterestControl->SetRegionsAsync(regionOfInterestIterable.Get(), &op);
Q_ASSERT_SUCCEEDED(hr);
return QWinRTFunctions::await(op) == S_OK;
}
bool QWinRTCameraControl::focus()
{
Q_D(QWinRTCameraControl);
HRESULT hr;
AsyncStatus status = AsyncStatus::Completed;
if (d->focusOperation) {
ComPtr<IAsyncInfo> info;
hr = d->focusOperation.As(&info);
Q_ASSERT_SUCCEEDED(hr);
info->get_Status(&status);
}
if (!d->focusControl || status == AsyncStatus::Started)
return false;
QEventDispatcherWinRT::runOnXamlThread([&d, &hr]() {
hr = d->focusControl->FocusAsync(&d->focusOperation);
Q_ASSERT_SUCCEEDED(hr);
return S_OK;
});
const long errorCode = HRESULT_CODE(hr);
if (errorCode == ERROR_OPERATION_IN_PROGRESS
|| errorCode == ERROR_WRITE_PROTECT) {
return false;
}
Q_ASSERT_SUCCEEDED(hr);
hr = QWinRTFunctions::await(d->focusOperation, QWinRTFunctions::ProcessThreadEvents);
Q_ASSERT_SUCCEEDED(hr);
return hr == S_OK;
}
void QWinRTCameraControl::clearFocusPoint()
{
Q_D(QWinRTCameraControl);
if (!d->focusControl)
return;
ComPtr<IAsyncAction> op;
HRESULT hr = d->regionsOfInterestControl->ClearRegionsAsync(&op);
Q_ASSERT_SUCCEEDED(hr);
hr = QWinRTFunctions::await(op);
Q_ASSERT_SUCCEEDED(hr);
}
bool QWinRTCameraControl::lockFocus()
{
Q_D(QWinRTCameraControl);
if (!d->focusControl)
return false;
ComPtr<IFocusControl2> focusControl2;
HRESULT hr = d->focusControl.As(&focusControl2);
Q_ASSERT_SUCCEEDED(hr);
ComPtr<IAsyncAction> op;
hr = focusControl2->LockAsync(&op);
if (HRESULT_CODE(hr) == ERROR_WRITE_PROTECT)
return false;
Q_ASSERT_SUCCEEDED(hr);
return QWinRTFunctions::await(op) == S_OK;
}
bool QWinRTCameraControl::unlockFocus()
{
Q_D(QWinRTCameraControl);
if (!d->focusControl)
return false;
ComPtr<IFocusControl2> focusControl2;
HRESULT hr = d->focusControl.As(&focusControl2);
Q_ASSERT_SUCCEEDED(hr);
ComPtr<IAsyncAction> op;
hr = focusControl2->UnlockAsync(&op);
if (HRESULT_CODE(hr) == ERROR_WRITE_PROTECT)
return false;
Q_ASSERT_SUCCEEDED(hr);
return QWinRTFunctions::await(op) == S_OK;
}
#else // !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP)
HRESULT QWinRTCameraControl::initializeFocus()
{
Q_D(QWinRTCameraControl);
d->cameraFocusControl->setSupportedFocusMode(0);
d->cameraFocusControl->setSupportedFocusPointMode(QSet<QCameraFocus::FocusPointMode>());
return S_OK;
}
bool QWinRTCameraControl::setFocus(QCameraFocus::FocusModes modes)
{
Q_UNUSED(modes)
return false;
}
bool QWinRTCameraControl::setFocusPoint(const QPointF &focusPoint)
{
Q_UNUSED(focusPoint)
return false;
}
bool QWinRTCameraControl::focus()
{
return false;
}
void QWinRTCameraControl::clearFocusPoint()
{
}
bool QWinRTCameraControl::lockFocus()
{
return false;
}
bool QWinRTCameraControl::unlockFocus()
{
return false;
}
#endif // !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP)
void QWinRTCameraControl::frameMapped()
{
Q_D(QWinRTCameraControl);
++d->framesMapped;
}
void QWinRTCameraControl::frameUnmapped()
{
Q_D(QWinRTCameraControl);
--d->framesMapped;
Q_ASSERT(d->framesMapped >= 0);
if (!d->framesMapped && d->delayClose && d->delayClose->isRunning())
d->delayClose->exit();
}
HRESULT QWinRTCameraControl::onCaptureFailed(IMediaCapture *, IMediaCaptureFailedEventArgs *args)
{
qCDebug(lcMMCamera) << __FUNCTION__ << args;
HRESULT hr;
UINT32 code;
hr = args->get_Code(&code);
RETURN_HR_IF_FAILED("Failed to get error code");
HString message;
args->get_Message(message.GetAddressOf());
RETURN_HR_IF_FAILED("Failed to get error message");
quint32 messageLength;
const wchar_t *messageBuffer = message.GetRawBuffer(&messageLength);
emit error(QCamera::CameraError, QString::fromWCharArray(messageBuffer, messageLength));
setState(QCamera::LoadedState);
return S_OK;
}
HRESULT QWinRTCameraControl::onRecordLimitationExceeded(IMediaCapture *)
{
qCDebug(lcMMCamera) << __FUNCTION__;
emit error(QCamera::CameraError, QStringLiteral("Recording limit exceeded."));
setState(QCamera::LoadedState);
return S_OK;
}
void QWinRTCameraControl::emitError(int errorCode, const QString &errorString)
{
qCDebug(lcMMCamera) << __FUNCTION__ << errorString << errorCode;
emit error(errorCode, errorString);
}
QT_END_NAMESPACE
| 35.697624 | 164 | 0.673362 |
73af7d36d6c4b4d17f1e692a9b88001686d08dcf | 11,290 | cpp | C++ | hi_modules/effects/editors/DelayEditor.cpp | psobot/HISE | cb97378039bae22c8eade3d4b699931bfd65c7d1 | [
"Intel",
"MIT"
] | 1 | 2021-03-04T19:37:06.000Z | 2021-03-04T19:37:06.000Z | hi_modules/effects/editors/DelayEditor.cpp | psobot/HISE | cb97378039bae22c8eade3d4b699931bfd65c7d1 | [
"Intel",
"MIT"
] | null | null | null | hi_modules/effects/editors/DelayEditor.cpp | psobot/HISE | cb97378039bae22c8eade3d4b699931bfd65c7d1 | [
"Intel",
"MIT"
] | null | null | null | /*
==============================================================================
This is an automatically generated GUI class created by the Introjucer!
Be careful when adding custom code to these files, as only the code within
the "//[xyz]" and "//[/xyz]" sections will be retained when the file is loaded
and re-saved.
Created with Introjucer version: 4.1.0
------------------------------------------------------------------------------
The Introjucer is part of the JUCE library - "Jules' Utility Class Extensions"
Copyright (c) 2015 - ROLI Ltd.
==============================================================================
*/
//[Headers] You can add your own extra header files here...
namespace hise { using namespace juce;
//[/Headers]
#include "DelayEditor.h"
//[MiscUserDefs] You can add your own user definitions and misc code here...
//[/MiscUserDefs]
//==============================================================================
DelayEditor::DelayEditor (ProcessorEditor *p)
: ProcessorEditorBody(p)
{
//[Constructor_pre] You can add your own custom stuff here..
//[/Constructor_pre]
addAndMakeVisible (leftTimeSlider = new HiSlider ("Left Time"));
leftTimeSlider->setRange (0, 3000, 1);
leftTimeSlider->setSliderStyle (Slider::RotaryHorizontalVerticalDrag);
leftTimeSlider->setTextBoxStyle (Slider::TextBoxRight, false, 80, 20);
leftTimeSlider->addListener (this);
addAndMakeVisible (rightTimeSlider = new HiSlider ("Right Time"));
rightTimeSlider->setRange (0, 3000, 1);
rightTimeSlider->setSliderStyle (Slider::RotaryHorizontalVerticalDrag);
rightTimeSlider->setTextBoxStyle (Slider::TextBoxRight, false, 80, 20);
rightTimeSlider->addListener (this);
addAndMakeVisible (leftFeedbackSlider = new HiSlider ("Left Feedback"));
leftFeedbackSlider->setRange (0, 100, 1);
leftFeedbackSlider->setSliderStyle (Slider::RotaryHorizontalVerticalDrag);
leftFeedbackSlider->setTextBoxStyle (Slider::TextBoxRight, false, 80, 20);
leftFeedbackSlider->addListener (this);
addAndMakeVisible (rightFeedbackSlider = new HiSlider ("Right Feedback"));
rightFeedbackSlider->setRange (0, 100, 1);
rightFeedbackSlider->setSliderStyle (Slider::RotaryHorizontalVerticalDrag);
rightFeedbackSlider->setTextBoxStyle (Slider::TextBoxRight, false, 80, 20);
rightFeedbackSlider->addListener (this);
addAndMakeVisible (mixSlider = new HiSlider ("Mix"));
mixSlider->setRange (0, 100, 1);
mixSlider->setSliderStyle (Slider::RotaryHorizontalVerticalDrag);
mixSlider->setTextBoxStyle (Slider::TextBoxRight, false, 80, 20);
mixSlider->addListener (this);
addAndMakeVisible (tempoSyncButton = new HiToggleButton ("new toggle button"));
tempoSyncButton->setButtonText (TRANS("TempoSync"));
tempoSyncButton->addListener (this);
tempoSyncButton->setColour (ToggleButton::textColourId, Colours::white);
//[UserPreSize]
tempoSyncButton->setup(getProcessor(), DelayEffect::TempoSync, "TempoSync");
tempoSyncButton->setNotificationType(sendNotification);
leftTimeSlider->setup(getProcessor(), DelayEffect::DelayTimeLeft, "Left Delay");
leftTimeSlider->setMode(HiSlider::Time);
rightTimeSlider->setup(getProcessor(), DelayEffect::DelayTimeRight, "Right Delay");
rightTimeSlider->setMode(HiSlider::Time);
leftFeedbackSlider->setup(getProcessor(), DelayEffect::FeedbackLeft, "Left Feedback");
leftFeedbackSlider->setMode(HiSlider::NormalizedPercentage);
rightFeedbackSlider->setup(getProcessor(), DelayEffect::FeedbackRight, "Right Feedback");
rightFeedbackSlider->setMode(HiSlider::NormalizedPercentage);
mixSlider->setup(getProcessor(), DelayEffect::Mix, "Mix");
mixSlider->setMode(HiSlider::NormalizedPercentage);
//[/UserPreSize]
setSize (900, 170);
//[Constructor] You can add your own custom stuff here..
h = getHeight();
//[/Constructor]
}
DelayEditor::~DelayEditor()
{
//[Destructor_pre]. You can add your own custom destruction code here..
//[/Destructor_pre]
leftTimeSlider = nullptr;
rightTimeSlider = nullptr;
leftFeedbackSlider = nullptr;
rightFeedbackSlider = nullptr;
mixSlider = nullptr;
tempoSyncButton = nullptr;
//[Destructor]. You can add your own custom destruction code here..
//[/Destructor]
}
//==============================================================================
void DelayEditor::paint (Graphics& g)
{
//[UserPrePaint] Add your own custom painting code here..
//[/UserPrePaint]
ProcessorEditorLookAndFeel::fillEditorBackgroundRect(g, this);
g.setColour(Colour(0xAAFFFFFF));
g.setFont(GLOBAL_BOLD_FONT().withHeight(22.0f));
g.drawText (TRANS("delay"),
getWidth() - 53 - 200, 6, 200, 40,
Justification::centredRight, true);
//[UserPaint] Add your own custom painting code here..
//[/UserPaint]
}
void DelayEditor::resized()
{
//[UserPreResize] Add your own custom resize code here..
//[/UserPreResize]
leftTimeSlider->setBounds ((getWidth() / 2) + -145 - 128, 32, 128, 48);
rightTimeSlider->setBounds ((getWidth() / 2) + 6 - 128, 32, 128, 48);
leftFeedbackSlider->setBounds ((getWidth() / 2) + -145 - 128, 96, 128, 48);
rightFeedbackSlider->setBounds ((getWidth() / 2) + 6 - 128, 96, 128, 48);
mixSlider->setBounds ((getWidth() / 2) + 102 - (128 / 2), 32, 128, 48);
tempoSyncButton->setBounds ((getWidth() / 2) + 102 - (128 / 2), 96, 128, 32);
//[UserResized] Add your own custom resize handling here..
//[/UserResized]
}
void DelayEditor::sliderValueChanged (Slider* sliderThatWasMoved)
{
//[UsersliderValueChanged_Pre]
//[/UsersliderValueChanged_Pre]
if (sliderThatWasMoved == leftTimeSlider)
{
//[UserSliderCode_leftTimeSlider] -- add your slider handling code here..
//[/UserSliderCode_leftTimeSlider]
}
else if (sliderThatWasMoved == rightTimeSlider)
{
//[UserSliderCode_rightTimeSlider] -- add your slider handling code here..
//[/UserSliderCode_rightTimeSlider]
}
else if (sliderThatWasMoved == leftFeedbackSlider)
{
//[UserSliderCode_leftFeedbackSlider] -- add your slider handling code here..
//[/UserSliderCode_leftFeedbackSlider]
}
else if (sliderThatWasMoved == rightFeedbackSlider)
{
//[UserSliderCode_rightFeedbackSlider] -- add your slider handling code here..
//[/UserSliderCode_rightFeedbackSlider]
}
else if (sliderThatWasMoved == mixSlider)
{
//[UserSliderCode_mixSlider] -- add your slider handling code here..
//[/UserSliderCode_mixSlider]
}
//[UsersliderValueChanged_Post]
//[/UsersliderValueChanged_Post]
}
void DelayEditor::buttonClicked (Button* buttonThatWasClicked)
{
//[UserbuttonClicked_Pre]
//[/UserbuttonClicked_Pre]
if (buttonThatWasClicked == tempoSyncButton)
{
//[UserButtonCode_tempoSyncButton] -- add your button handler code here..
if(tempoSyncButton->getToggleState())
{
leftTimeSlider->setMode(HiSlider::Mode::TempoSync);
rightTimeSlider->setMode(HiSlider::Mode::TempoSync);
}
else
{
leftTimeSlider->setMode(HiSlider::Mode::Time);
rightTimeSlider->setMode(HiSlider::Mode::Time);
}
//[/UserButtonCode_tempoSyncButton]
}
//[UserbuttonClicked_Post]
//[/UserbuttonClicked_Post]
}
//[MiscUserCode] You can add your own definitions of your custom methods or any other code here...
//[/MiscUserCode]
//==============================================================================
#if 0
/* -- Introjucer information section --
This is where the Introjucer stores the metadata that describe this GUI layout, so
make changes in here at your peril!
BEGIN_JUCER_METADATA
<JUCER_COMPONENT documentType="Component" className="DelayEditor" componentName=""
parentClasses="public ProcessorEditorBody" constructorParams="ProcessorEditor *p"
variableInitialisers="ProcessorEditorBody(p) " snapPixels="8"
snapActive="1" snapShown="1" overlayOpacity="0.330" fixedSize="1"
initialWidth="900" initialHeight="170">
<BACKGROUND backgroundColour="ffffff">
<ROUNDRECT pos="-0.5Cc 6 84M 12M" cornerSize="6" fill="solid: 30000000"
hasStroke="1" stroke="2, mitered, butt" strokeColour="solid: 25ffffff"/>
<TEXT pos="53Rr 6 200 40" fill="solid: 52ffffff" hasStroke="0" text="delay"
fontname="Arial" fontsize="24" bold="1" italic="0" justification="34"/>
</BACKGROUND>
<SLIDER name="Left Time" id="89cc5b4c20e221e" memberName="leftTimeSlider"
virtualName="HiSlider" explicitFocusOrder="0" pos="-145Cr 32 128 48"
posRelativeX="f930000f86c6c8b6" min="0" max="3000" int="1" style="RotaryHorizontalVerticalDrag"
textBoxPos="TextBoxRight" textBoxEditable="1" textBoxWidth="80"
textBoxHeight="20" skewFactor="1"/>
<SLIDER name="Right Time" id="ae1646635cbce8fa" memberName="rightTimeSlider"
virtualName="HiSlider" explicitFocusOrder="0" pos="6Cr 32 128 48"
posRelativeX="f930000f86c6c8b6" min="0" max="3000" int="1" style="RotaryHorizontalVerticalDrag"
textBoxPos="TextBoxRight" textBoxEditable="1" textBoxWidth="80"
textBoxHeight="20" skewFactor="1"/>
<SLIDER name="Left Feedback" id="cc35747a4515e5ae" memberName="leftFeedbackSlider"
virtualName="HiSlider" explicitFocusOrder="0" pos="-145Cr 96 128 48"
posRelativeX="f930000f86c6c8b6" min="0" max="100" int="1" style="RotaryHorizontalVerticalDrag"
textBoxPos="TextBoxRight" textBoxEditable="1" textBoxWidth="80"
textBoxHeight="20" skewFactor="1"/>
<SLIDER name="Right Feedback" id="c6f6406fdd87fc89" memberName="rightFeedbackSlider"
virtualName="HiSlider" explicitFocusOrder="0" pos="6Cr 96 128 48"
posRelativeX="f930000f86c6c8b6" min="0" max="100" int="1" style="RotaryHorizontalVerticalDrag"
textBoxPos="TextBoxRight" textBoxEditable="1" textBoxWidth="80"
textBoxHeight="20" skewFactor="1"/>
<SLIDER name="Mix" id="9115805b4b27f781" memberName="mixSlider" virtualName="HiSlider"
explicitFocusOrder="0" pos="102Cc 32 128 48" posRelativeX="f930000f86c6c8b6"
min="0" max="100" int="1" style="RotaryHorizontalVerticalDrag"
textBoxPos="TextBoxRight" textBoxEditable="1" textBoxWidth="80"
textBoxHeight="20" skewFactor="1"/>
<TOGGLEBUTTON name="new toggle button" id="e6345feaa3cb5bea" memberName="tempoSyncButton"
virtualName="HiToggleButton" explicitFocusOrder="0" pos="102Cc 96 128 32"
posRelativeX="410a230ddaa2f2e8" txtcol="ffffffff" buttonText="TempoSync"
connectedEdges="0" needsCallback="1" radioGroupId="0" state="0"/>
</JUCER_COMPONENT>
END_JUCER_METADATA
*/
#endif
//[EndFile] You can add extra defines here...
} // namespace hise
//[/EndFile]
| 39.475524 | 106 | 0.653322 |
73affffd66868ddc8821e36fdd6faa9691beff8e | 9,342 | cpp | C++ | doc/src/Chapter8-programs/cpp/MBPT/minnesota_potential.cpp | cpmoca/LectureNotesPhysics | 8e9f8c5d7f163ea10b14002850f7c79acc4513df | [
"CC0-1.0"
] | 24 | 2016-11-22T09:42:49.000Z | 2022-03-11T01:33:46.000Z | doc/src/Chapter8-programs/cpp/MBPT/minnesota_potential.cpp | cpmoca/LectureNotesPhysics | 8e9f8c5d7f163ea10b14002850f7c79acc4513df | [
"CC0-1.0"
] | null | null | null | doc/src/Chapter8-programs/cpp/MBPT/minnesota_potential.cpp | cpmoca/LectureNotesPhysics | 8e9f8c5d7f163ea10b14002850f7c79acc4513df | [
"CC0-1.0"
] | 25 | 2016-05-24T22:54:07.000Z | 2022-02-20T00:08:19.000Z | #include "minnesota_potential.hpp"
minnesotaPotential::minnesotaPotential(int numberOfParticles, double density) {
L = pow((numberOfParticles)/density, 1./3.);
piOverL = M_PI/L;
VRfactor = V_0R/(L*L*L)*pow(M_PI/kappa_R,1.5);
VTfactor = -V_0T/(L*L*L)*pow(M_PI/kappa_T,1.5);
VSfactor = -V_0S/(L*L*L)*pow(M_PI/kappa_S,1.5);
}
int kroneckerDelta(const int &i, const int &j) {
if(i != j){ return 0; }
return 1;
}
int spinExchangeTerm(const int &i, const int &j, const int &k, const int &l) {
if(i == l && j == k){ return 1; }
else{ return 0; }
}
inline double minnesotaPotential::get_element(State *qnums, int qi, int qj, int qk, int ql) {
double V_R1, V_T1, V_S1, V_R2, V_T2, V_S2;
double kX1, kY1, kZ1, kX2, kY2, kZ2;
double qSquared1, spinEx1, isoSpinEx1, qSquared2, spinEx2, isoSpinEx2;
double IsIt1, PsIt1, PsPt1, IsPt1, IsIt2, PsIt2, PsPt2, IsPt2;
if(qnums[qi].nx + qnums[qj].nx != qnums[qk].nx + qnums[ql].nx){ return 0.0; }
if(qnums[qi].ny + qnums[qj].ny != qnums[qk].ny + qnums[ql].ny){ return 0.0; }
if(qnums[qi].nz + qnums[qj].nz != qnums[qk].nz + qnums[ql].nz){ return 0.0; }
if(qnums[qi].m + qnums[qj].m != qnums[qk].m + qnums[ql].m){ return 0.0; }
if(qnums[qi].t + qnums[qj].t != qnums[qk].t + qnums[ql].t){ return 0.0; }
kX1 = piOverL * (qnums[qi].nx - qnums[qj].nx - qnums[qk].nx + qnums[ql].nx);
kY1 = piOverL * (qnums[qi].ny - qnums[qj].ny - qnums[qk].ny + qnums[ql].ny);
kZ1 = piOverL * (qnums[qi].nz - qnums[qj].nz - qnums[qk].nz + qnums[ql].nz);
kX2 = piOverL * (qnums[qi].nx - qnums[qj].nx - qnums[ql].nx + qnums[qk].nx);
kY2 = piOverL * (qnums[qi].ny - qnums[qj].ny - qnums[ql].ny + qnums[qk].ny);
kZ2 = piOverL * (qnums[qi].nz - qnums[qj].nz - qnums[ql].nz + qnums[qk].nz);
qSquared1 = kX1 * kX1 + kY1 * kY1 + kZ1 * kZ1;
qSquared2 = kX2 * kX2 + kY2 * kY2 + kZ2 * kZ2;
V_R1 = VRfactor * exp(-qSquared1/(4*kappa_R));
V_T1 = VTfactor * exp(-qSquared1/(4*kappa_T));
V_S1 = VSfactor * exp(-qSquared1/(4*kappa_S));
V_R2 = VRfactor * exp(-qSquared2/(4*kappa_R));
V_T2 = VTfactor * exp(-qSquared2/(4*kappa_T));
V_S2 = VSfactor * exp(-qSquared2/(4*kappa_S));
spinEx1 = spinExchangeTerm(qnums[qi].m, qnums[qj].m, qnums[qk].m, qnums[ql].m);
isoSpinEx1 = spinExchangeTerm(qnums[qi].t, qnums[qj].t, qnums[qk].t, qnums[ql].t);
spinEx2 = spinExchangeTerm(qnums[qi].m, qnums[qj].m, qnums[ql].m, qnums[qk].m);
isoSpinEx2 = spinExchangeTerm(qnums[qi].t, qnums[qj].t, qnums[ql].t, qnums[qk].t);
IsIt1 = kroneckerDelta(qnums[qi].m, qnums[qk].m) * kroneckerDelta(qnums[qj].m, qnums[ql].m) *
kroneckerDelta(qnums[qi].t, qnums[qk].t) * kroneckerDelta(qnums[qj].t, qnums[ql].t);
PsIt1 = spinEx1 * kroneckerDelta(qnums[qi].t, qnums[qk].t) * kroneckerDelta(qnums[qj].t, qnums[ql].t);
PsPt1 = spinEx1 * isoSpinEx1;
IsPt1 = kroneckerDelta(qnums[qi].m, qnums[qk].m)*kroneckerDelta(qnums[qj].m, qnums[ql].m) * isoSpinEx1;
IsIt2 = kroneckerDelta(qnums[qi].m, qnums[ql].m) * kroneckerDelta(qnums[qj].m, qnums[qk].m) *
kroneckerDelta(qnums[qi].t, qnums[ql].t) * kroneckerDelta(qnums[qj].t, qnums[qk].t);
PsIt2 = spinEx2 * kroneckerDelta(qnums[qi].t, qnums[ql].t) * kroneckerDelta(qnums[qj].t, qnums[qk].t);
PsPt2 = spinEx2 * isoSpinEx2;
IsPt2 = kroneckerDelta(qnums[qi].m, qnums[ql].m) * kroneckerDelta(qnums[qj].m, qnums[qk].m) * isoSpinEx2;
return 0.5 * (V_R1 + 0.5*V_T1 + 0.5*V_S1) * IsIt1 +
0.25 * (V_T1 - V_S1) * PsIt1 -
0.5 * (V_R1 + 0.5*V_T1 + 0.5*V_S1) * PsPt1 -
0.25 * (V_T1 - V_S1) * IsPt1 -
0.5 * (V_R2 + 0.5*V_T2 + 0.5*V_S2) * IsIt2 -
0.25 * (V_T2 - V_S2) * PsIt2 +
0.5 * (V_R2 + 0.5*V_T2 + 0.5*V_S2) * PsPt2 +
0.25 * (V_T2 - V_S2) * IsPt2;
}
void calculate_sp_energies(Input_Parameters &Parameters, Model_Space &Space ) {
// With the number of hole states, the length scale and state energies can be calculated
double L = pow(Space.indhol/Parameters.density, 1.0/3.0);
for (int i = 0; i < Space.indtot; ++i) {
if (Space.qnums[i].t == -1) {
Space.qnums[i].energy *= proton_prefac*M_PI*M_PI/(L*L);
}
else if (Space.qnums[i].t == 1) {
Space.qnums[i].energy *= neutron_prefac*M_PI*M_PI/(L*L);
}
}
// Change energies to Hartree-Fock energies, E_p = E_p + 2*V_pipi
for (int p = 0; p < Space.indtot; ++p) {
for (int i = 0; i < Space.indhol; ++i) {
if (p == i) { continue; }
Space.qnums[p].energy += 2*V_Minnesota(Space, p, i, p, i, L);
}
}
// Order two-body states with respect to Nx, Ny, Nz for channel index function
int count1 = 0;
int N2max = 4*Space.Nmax;
Space.map_2b = new int[Space.qsizes.nx * Space.qsizes.ny * Space.qsizes.nz];
for (int nx = -2 * Space.nmax; nx <= 2 * Space.nmax; ++nx) {
for (int ny = -2 * Space.nmax; ny <= 2 * Space.nmax; ++ny) {
for (int nz = -2 * Space.nmax; nz <= 2 * Space.nmax; ++nz) {
if (nx*nx + ny*ny + nz*nz <= N2max) {
int idx = (nx + 2*Space.nmax) * Space.qsizes.ny*Space.qsizes.nz +
(ny + 2*Space.nmax) * Space.qsizes.nz +
(nz + 2*Space.nmax);
Space.map_2b[idx] = count1;
++count1;
}
}
}
}
Space.size_2b = count1 * Space.qsizes.t * Space.qsizes.m;
}
double V_Minnesota(const Model_Space &Space, const int &qi, const int &qj, const int &qk, const int &ql, const double &L)
{
double V_R1, V_T1, V_S1, V_R2, V_T2, V_S2;
double V_0R, V_0T, V_0S;
double kappa_R, kappa_T, kappa_S;
double kX1, kY1, kZ1, kX2, kY2, kZ2;
double qSquared1, spinEx1, isoSpinEx1, qSquared2, spinEx2, isoSpinEx2;
double IsIt1, PsIt1, PsPt1, IsPt1, IsIt2, PsIt2, PsPt2, IsPt2;
V_0R = 200; //MeV
V_0T = 178; //MeV
V_0S = 91.85; //MeV
kappa_R = 1.487; //fm^-2
kappa_T = 0.639; //fm^-2
kappa_S = 0.465; //fm^-2
if(Space.qnums[qi].nx + Space.qnums[qj].nx != Space.qnums[qk].nx + Space.qnums[ql].nx){ return 0.0; }
if(Space.qnums[qi].ny + Space.qnums[qj].ny != Space.qnums[qk].ny + Space.qnums[ql].ny){ return 0.0; }
if(Space.qnums[qi].nz + Space.qnums[qj].nz != Space.qnums[qk].nz + Space.qnums[ql].nz){ return 0.0; }
if(Space.qnums[qi].m + Space.qnums[qj].m != Space.qnums[qk].m + Space.qnums[ql].m){ return 0.0; }
if(Space.qnums[qi].t + Space.qnums[qj].t != Space.qnums[qk].t + Space.qnums[ql].t){ return 0.0; }
kX1 = (M_PI/L) * (Space.qnums[qi].nx - Space.qnums[qj].nx - Space.qnums[qk].nx + Space.qnums[ql].nx);
kY1 = (M_PI/L) * (Space.qnums[qi].ny - Space.qnums[qj].ny - Space.qnums[qk].ny + Space.qnums[ql].ny);
kZ1 = (M_PI/L) * (Space.qnums[qi].nz - Space.qnums[qj].nz - Space.qnums[qk].nz + Space.qnums[ql].nz);
kX2 = (M_PI/L) * (Space.qnums[qi].nx - Space.qnums[qj].nx - Space.qnums[ql].nx + Space.qnums[qk].nx);
kY2 = (M_PI/L) * (Space.qnums[qi].ny - Space.qnums[qj].ny - Space.qnums[ql].ny + Space.qnums[qk].ny);
kZ2 = (M_PI/L) * (Space.qnums[qi].nz - Space.qnums[qj].nz - Space.qnums[ql].nz + Space.qnums[qk].nz);
qSquared1 = kX1 * kX1 + kY1 * kY1 + kZ1 * kZ1;
qSquared2 = kX2 * kX2 + kY2 * kY2 + kZ2 * kZ2;
V_R1 = V_0R/(L*L*L)*pow(M_PI/kappa_R,1.5) * exp(-qSquared1/(4*kappa_R));
V_T1 = -V_0T/(L*L*L)*pow(M_PI/kappa_T,1.5) * exp(-qSquared1/(4*kappa_T));
V_S1 = -V_0S/(L*L*L)*pow(M_PI/kappa_S,1.5) * exp(-qSquared1/(4*kappa_S));
V_R2 = V_0R/(L*L*L)*pow(M_PI/kappa_R,1.5) * exp(-qSquared2/(4*kappa_R));
V_T2 = -V_0T/(L*L*L)*pow(M_PI/kappa_T,1.5) * exp(-qSquared2/(4*kappa_T));
V_S2 = -V_0S/(L*L*L)*pow(M_PI/kappa_S,1.5) * exp(-qSquared2/(4*kappa_S));
spinEx1 = spinExchangeTerm(Space.qnums[qi].m, Space.qnums[qj].m, Space.qnums[qk].m, Space.qnums[ql].m);
isoSpinEx1 = spinExchangeTerm(Space.qnums[qi].t, Space.qnums[qj].t, Space.qnums[qk].t, Space.qnums[ql].t);
spinEx2 = spinExchangeTerm(Space.qnums[qi].m, Space.qnums[qj].m, Space.qnums[ql].m, Space.qnums[qk].m);
isoSpinEx2 = spinExchangeTerm(Space.qnums[qi].t, Space.qnums[qj].t, Space.qnums[ql].t, Space.qnums[qk].t);
IsIt1 = kroneckerDelta(Space.qnums[qi].m, Space.qnums[qk].m) * kroneckerDelta(Space.qnums[qj].m, Space.qnums[ql].m) *
kroneckerDelta(Space.qnums[qi].t, Space.qnums[qk].t) * kroneckerDelta(Space.qnums[qj].t, Space.qnums[ql].t);
PsIt1 = spinEx1 * kroneckerDelta(Space.qnums[qi].t, Space.qnums[qk].t) * kroneckerDelta(Space.qnums[qj].t, Space.qnums[ql].t);
PsPt1 = spinEx1 * isoSpinEx1;
IsPt1 = kroneckerDelta(Space.qnums[qi].m, Space.qnums[qk].m)*kroneckerDelta(Space.qnums[qj].m, Space.qnums[ql].m) * isoSpinEx1;
IsIt2 = kroneckerDelta(Space.qnums[qi].m, Space.qnums[ql].m) * kroneckerDelta(Space.qnums[qj].m, Space.qnums[qk].m) *
kroneckerDelta(Space.qnums[qi].t, Space.qnums[ql].t) * kroneckerDelta(Space.qnums[qj].t, Space.qnums[qk].t);
PsIt2 = spinEx2 * kroneckerDelta(Space.qnums[qi].t, Space.qnums[ql].t) * kroneckerDelta(Space.qnums[qj].t, Space.qnums[qk].t);
PsPt2 = spinEx2 * isoSpinEx2;
IsPt2 = kroneckerDelta(Space.qnums[qi].m, Space.qnums[ql].m) * kroneckerDelta(Space.qnums[qj].m, Space.qnums[qk].m) * isoSpinEx2;
return 0.5 * (V_R1 + 0.5*V_T1 + 0.5*V_S1) * IsIt1 +
0.25 * (V_T1 - V_S1) * PsIt1 -
0.5 * (V_R1 + 0.5*V_T1 + 0.5*V_S1) * PsPt1 -
0.25 * (V_T1 - V_S1) * IsPt1 -
0.5 * (V_R2 + 0.5*V_T2 + 0.5*V_S2) * IsIt2 -
0.25 * (V_T2 - V_S2) * PsIt2 +
0.5 * (V_R2 + 0.5*V_T2 + 0.5*V_S2) * PsPt2 +
0.25 * (V_T2 - V_S2) * IsPt2;
}
| 48.910995 | 131 | 0.621066 |
73b20b0eb8bcfd36319ab1f750b27f5a1e3c8f30 | 12,275 | hpp | C++ | src/ropufu/format/mat4_header.hpp | ropufu/aftermath | ab9364c41672a188879d84ebebb5a23f2d6641ec | [
"MIT"
] | null | null | null | src/ropufu/format/mat4_header.hpp | ropufu/aftermath | ab9364c41672a188879d84ebebb5a23f2d6641ec | [
"MIT"
] | null | null | null | src/ropufu/format/mat4_header.hpp | ropufu/aftermath | ab9364c41672a188879d84ebebb5a23f2d6641ec | [
"MIT"
] | null | null | null |
#ifndef ROPUFU_AFTERMATH_FORMAT_MAT4_HEADER_HPP_INCLUDED
#define ROPUFU_AFTERMATH_FORMAT_MAT4_HEADER_HPP_INCLUDED
#include "../algebra/matrix.hpp"
#include <cstddef> // std::size_t
#include <cstdint> // std::int32_t
#include <fstream> // std::ifstream, std::ofstream
#include <ios> // std::ios_base::failure
#include <string> // std::string
#include <system_error> // std::error_code, std::errc
#include <vector> // std::vector
namespace ropufu::aftermath::format
{
/** Indicates how the data are stored in a .mat file. */
enum struct mat4_data_format : std::int32_t
{
ieee_little_endian = 0000,
ieee_big_endian = 1000,
vax_d_float = 2000,
vax_g_float = 3000,
cray = 4000
}; // enum struct mat4_data_format
/** Indicates what type of data is stored in a .mat file. */
template <typename t_data_type>
struct mat4_data_type_id;
/** Indicates that a .mat file stores \c double. */
template <> struct mat4_data_type_id<double> { static constexpr std::int32_t value = 00; };
/** Indicates that a .mat file stores \c float. */
template <> struct mat4_data_type_id<float> { static constexpr std::int32_t value = 10; };
/** Indicates that a .mat file stores \c std::int32_t. */
template <> struct mat4_data_type_id<std::int32_t> { static constexpr std::int32_t value = 20; };
/** Indicates that a .mat file stores \c std::int16_t. */
template <> struct mat4_data_type_id<std::int16_t> { static constexpr std::int32_t value = 30; };
/** Indicates that a .mat file stores \c std::uint16_t. */
template <> struct mat4_data_type_id<std::uint16_t> { static constexpr std::int32_t value = 40; };
/** Indicates that a .mat file stores \c std::uint8_t. */
template <> struct mat4_data_type_id<std::uint8_t> { static constexpr std::int32_t value = 50; };
[[maybe_unused]]
static std::size_t mat4_data_type_size_by_id(std::int32_t data_type_id) noexcept
{
switch (data_type_id)
{
case mat4_data_type_id<double>::value: return sizeof(double); break;
case mat4_data_type_id<float>::value: return sizeof(float); break;
case mat4_data_type_id<std::int32_t>::value: return sizeof(std::int32_t); break;
case mat4_data_type_id<std::int16_t>::value: return sizeof(std::int16_t); break;
case mat4_data_type_id<std::uint16_t>::value: return sizeof(std::uint16_t); break;
case mat4_data_type_id<std::uint8_t>::value: return sizeof(std::uint8_t); break;
} // switch (...)
return 0;
} // mat4_data_type_size_by_id(...)
/** Indicates the type of matrix stored in a .mat file. */
enum struct mat4_matrix_type_id : std::int32_t
{
full = 0,
text = 1,
sparse = 2
}; // enum struct mat4_matrix_type_id
/** @brief Header format for a .mat file. */
struct mat4_header
{
using type = mat4_header;
static constexpr std::size_t mat_level = 4;
private:
std::int32_t m_data_format_id = 0;
std::int32_t m_data_type_id = 0;
std::int32_t m_matrix_type_id = 0;
std::int32_t m_height = 0;
std::int32_t m_width = 0;
std::int32_t m_is_complex = 0;
std::string m_name = "";
/** Constructs a format type id from member fields. */
std::int32_t build_format_type_id() const noexcept { return this->m_data_format_id + this->m_data_type_id + this->m_matrix_type_id; }
/** Updates member fields from a format type id. */
void decompose_format_type_id(std::int32_t format_type_id) noexcept
{
this->m_data_format_id = 1000 * (format_type_id / 1000);
format_type_id -= this->m_data_format_id;
this->m_data_type_id = 10 * (format_type_id / 10);
format_type_id -= this->m_data_type_id;
this->m_matrix_type_id = format_type_id;
} // decompose_format_type_id(...)
std::size_t on_read_error(std::error_code& ec, std::size_t int32_blocks_processed) const noexcept
{
ec = std::make_error_code(std::errc::io_error);
return int32_blocks_processed * sizeof(std::int32_t);
} // on_read_error(...)
std::size_t on_write_error(std::error_code& ec, std::size_t int32_blocks_processed) const noexcept
{
ec = std::make_error_code(std::errc::io_error);
return int32_blocks_processed * sizeof(std::int32_t);
} // on_write_error(...)
public:
/** @brief Reads header from a .mat file.
* @return Number of bytes read.
* @param ec Set to \c std::errc::io_error if the header could not be read.
*/
std::size_t read(std::ifstream& filestream, std::error_code& ec)
{
std::size_t int32_blocks_processed = 0;
std::int32_t format_type_id = 0;
std::int32_t height = 0;
std::int32_t width = 0;
std::int32_t complex_flag = 0;
std::int32_t name_length = 0;
char terminator = '\0';
std::vector<char> text_data {};
if (!filestream.is_open()) return this->on_read_error(ec, int32_blocks_processed);
if (filestream.fail()) return this->on_read_error(ec, int32_blocks_processed);
// Fixed-size portion of the header: metadata.
filestream.read(reinterpret_cast<char*>(&format_type_id), sizeof(decltype(format_type_id))); // type
if (filestream.fail()) return this->on_read_error(ec, int32_blocks_processed);
++int32_blocks_processed;
filestream.read(reinterpret_cast<char*>(&height), sizeof(decltype(height))); // mrows
if (filestream.fail() || height < 0) return this->on_read_error(ec, int32_blocks_processed);
++int32_blocks_processed;
filestream.read(reinterpret_cast<char*>(&width), sizeof(decltype(width))); // ncols
if (filestream.fail() || width < 0) return this->on_read_error(ec, int32_blocks_processed);
++int32_blocks_processed;
filestream.read(reinterpret_cast<char*>(&complex_flag), sizeof(decltype(complex_flag))); // imagf
if (filestream.fail()) return this->on_read_error(ec, int32_blocks_processed);
++int32_blocks_processed;
filestream.read(reinterpret_cast<char*>(&name_length), sizeof(decltype(name_length))); // namlen
if (filestream.fail() || name_length < 1) return this->on_read_error(ec, int32_blocks_processed);
++int32_blocks_processed;
--name_length; // The name length contains an integer with 1 plus the length of the matrix name.
// Variable-sized header: variable name.
text_data.resize(name_length);
filestream.read(text_data.data(), name_length);
if (filestream.fail() || filestream.gcount() != name_length) return this->on_read_error(ec, int32_blocks_processed);
filestream.read(&terminator, 1);
if (filestream.fail() || terminator != '\0') return this->on_read_error(ec, int32_blocks_processed);
this->decompose_format_type_id(format_type_id);
this->m_height = height;
this->m_width = width;
this->m_is_complex = (complex_flag == 0 ? false : true);
this->m_name = std::string(text_data.begin(), text_data.end());
return this->size();
} // read(...)
/** @brief Writes this header to \p filestream.
* @return Number of bytes written.
* @param ec Set to \c std::errc::io_error if the header could not be written.
*/
std::size_t write(std::ofstream& filestream, std::error_code& ec) const
{
std::size_t int32_blocks_processed = 0;
std::int32_t format_type_id = this->build_format_type_id();
std::int32_t height = static_cast<std::int32_t>(this->m_height);
std::int32_t width = static_cast<std::int32_t>(this->m_width);
std::int32_t complex_flag = this->m_is_complex ? 1 : 0;
std::int32_t name_length = static_cast<std::int32_t>(this->m_name.size() + 1);
char terminator = '\0';
if (!filestream.is_open()) return this->on_write_error(ec, int32_blocks_processed);
if (filestream.fail()) return this->on_write_error(ec, int32_blocks_processed);
// Fixed-size portion of the header: metadata.
filestream.write(reinterpret_cast<char*>(&format_type_id), sizeof(decltype(format_type_id))); // type
if (filestream.fail()) return this->on_write_error(ec, int32_blocks_processed);
++int32_blocks_processed;
filestream.write(reinterpret_cast<char*>(&height), sizeof(decltype(height))); // mrows
if (filestream.fail()) return this->on_write_error(ec, int32_blocks_processed);
++int32_blocks_processed;
filestream.write(reinterpret_cast<char*>(&width), sizeof(decltype(width))); // ncols
if (filestream.fail()) return this->on_write_error(ec, int32_blocks_processed);
++int32_blocks_processed;
filestream.write(reinterpret_cast<char*>(&complex_flag), sizeof(decltype(complex_flag))); // imagf
if (filestream.fail()) return this->on_write_error(ec, int32_blocks_processed);
++int32_blocks_processed;
filestream.write(reinterpret_cast<char*>(&name_length), sizeof(decltype(name_length))); // namlen
if (filestream.fail()) return this->on_write_error(ec, int32_blocks_processed);
++int32_blocks_processed;
// Variable-sized header: variable name.
filestream.write(this->m_name.c_str(), this->m_name.size());
if (filestream.fail()) return this->on_write_error(ec, int32_blocks_processed);
filestream.write(&terminator, 1);
if (filestream.fail()) return this->on_write_error(ec, int32_blocks_processed);
return this->size();
} // write(...)
/** Initializes the header for a given matrix. */
template <typename t_value_type, typename t_allocator_type, typename t_arrangement_type>
void initialize(
const std::string& variable_name,
const aftermath::algebra::matrix<t_value_type, t_allocator_type, t_arrangement_type>& mat,
mat4_data_format data_format = mat4_data_format::ieee_little_endian,
mat4_matrix_type_id matrix_type_id = mat4_matrix_type_id::full) noexcept
{
using data_type = t_value_type;
this->m_data_format_id = static_cast<std::int32_t>(data_format);
this->m_data_type_id = mat4_data_type_id<data_type>::value;
this->m_matrix_type_id = static_cast<std::int32_t>(matrix_type_id);
this->m_height = static_cast<std::int32_t>(mat.height());
this->m_width = static_cast<std::int32_t>(mat.width());
this->m_name = variable_name;
} // initialize(...)
/** Data format id. */
std::int32_t data_format_id() const noexcept { return this->m_data_format_id; }
/** Data type id. */
std::int32_t data_type_id() const noexcept { return this->m_data_type_id; }
/** Matrix type id. */
std::int32_t matrix_type_id() const noexcept { return this->m_matrix_type_id; }
/** Matrix height. */
std::int32_t height() const noexcept { return this->m_height; }
/** Matrix width. */
std::int32_t width() const noexcept { return this->m_width; }
/** Indicates if a matrix contains complex numbers. */
bool is_complex() const noexcept { return this->m_is_complex; }
/** Name of the matrix. */
const std::string& name() const noexcept { return this->m_name; }
/** Gets the size, in bytes, of the current header. */
std::size_t size() const noexcept
{
return 5 * sizeof(std::int32_t) + this->m_name.size() + 1;
} // size(...)
}; // struct mat4_header
} // namespace ropufu::aftermath::format
#endif // ROPUFU_AFTERMATH_FORMAT_MAT4_HEADER_HPP_INCLUDED
| 47.211538 | 141 | 0.635682 |
73b2de56a733c2aebe2a6c67cc40186136ea0917 | 1,425 | hpp | C++ | src/cpu/x64/brgemm/brgemm_amx.hpp | IvanNovoselov/oneDNN | aa47fcd2a03ee5caac119b6417bc66abe3154aab | [
"Apache-2.0"
] | 4 | 2019-02-01T11:16:59.000Z | 2020-04-27T17:27:06.000Z | src/cpu/x64/brgemm/brgemm_amx.hpp | IvanNovoselov/oneDNN | aa47fcd2a03ee5caac119b6417bc66abe3154aab | [
"Apache-2.0"
] | 1 | 2020-04-17T22:23:01.000Z | 2020-04-23T21:11:41.000Z | src/cpu/x64/brgemm/brgemm_amx.hpp | IvanNovoselov/oneDNN | aa47fcd2a03ee5caac119b6417bc66abe3154aab | [
"Apache-2.0"
] | 5 | 2019-02-08T07:36:01.000Z | 2021-07-14T07:58:50.000Z | /*******************************************************************************
* Copyright 2020 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#ifndef CPU_X64_BRGEMM_BRGEMM_AMX_HPP
#define CPU_X64_BRGEMM_BRGEMM_AMX_HPP
namespace dnnl {
namespace impl {
namespace cpu {
namespace x64 {
namespace brgemm_amx {
const static int max_m_block2 = 2;
const static int max_n_block2 = 2;
// Tile register decomposition
inline int get_C_tensor(int m, int n) {
return (m * max_m_block2 + n);
}
inline int get_A_tensor(int m) {
return (max_m_block2 * max_n_block2 + m);
}
inline int get_B_tensor(int n) {
return (max_m_block2 * max_n_block2 + max_m_block2 + n);
}
} // namespace brgemm_amx
} // namespace x64
} // namespace cpu
} // namespace impl
} // namespace dnnl
#endif
//vim: et ts=4 sw=4 cindent cino+=l0,\:4,N-s | 29.6875 | 80 | 0.657544 |
73b2f9daf0db047ffc40f1b58251af9143415345 | 9,510 | cc | C++ | tensorflow/lite/micro/benchmarks/conv_benchmark.cc | abhiram-krishnan/tensorflow | 76069c136cd5042ee8021a7dc15ef591244e5a73 | [
"Apache-2.0"
] | 2 | 2020-11-10T15:43:40.000Z | 2021-05-26T05:19:05.000Z | tensorflow/lite/micro/benchmarks/conv_benchmark.cc | abhiram-krishnan/tensorflow | 76069c136cd5042ee8021a7dc15ef591244e5a73 | [
"Apache-2.0"
] | 4 | 2018-09-04T23:40:36.000Z | 2019-01-30T20:06:11.000Z | tensorflow/lite/micro/benchmarks/conv_benchmark.cc | abhiram-krishnan/tensorflow | 76069c136cd5042ee8021a7dc15ef591244e5a73 | [
"Apache-2.0"
] | 1 | 2019-09-20T15:51:16.000Z | 2019-09-20T15:51:16.000Z | /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/c/builtin_op_data.h"
#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/micro/kernels/micro_ops.h"
#include "tensorflow/lite/micro/micro_time.h"
#include "tensorflow/lite/micro/testing/test_utils.h"
namespace tflite {
namespace testing {
namespace {
// Takes in quantized tensors along with expected outputs, and runs a single
// iteration of the conv op with the supplied parameters. Compares outputs vs
// the expected outputs and logs any differences found. Additionally, logs the
// number of clock ticks taken by the invoke call.
TfLiteStatus ValidateConvGoldens(TfLiteTensor* tensors, int tensors_size,
TfLiteConvParams* conv_params, int tolerance,
int output_length,
const int8_t* expected_output_data,
ErrorReporter* reporter) {
TfLiteContext context;
PopulateContext(tensors, tensors_size, reporter, &context);
const TfLiteRegistration* registration = ops::micro::Register_CONV_2D();
const char* init_data = reinterpret_cast<const char*>(conv_params);
// Init data size is always 0 for builtin ops.
const size_t init_data_size = 0;
void* user_data = nullptr;
if (registration->init) {
user_data = registration->init(&context, init_data, init_data_size);
}
// For an N element array, the raw array will be {N, Element 1, ... Element N}
// There are 3 inputs at index 0, 1 and 2 in the tensors array.
int inputs_array_data[] = {3, 0, 1, 2};
TfLiteIntArray* inputs_array = IntArrayFromInts(inputs_array_data);
// There is 1 output at index 3 in the tensors array.
int outputs_array_data[] = {1, 3};
TfLiteIntArray* outputs_array = IntArrayFromInts(outputs_array_data);
TfLiteNode node;
node.inputs = inputs_array;
node.outputs = outputs_array;
node.user_data = user_data;
node.builtin_data = reinterpret_cast<void*>(conv_params);
node.custom_initial_data = nullptr;
node.custom_initial_data_size = 0;
if (registration->prepare) {
TfLiteStatus prepare_status = registration->prepare(&context, &node);
if (prepare_status != kTfLiteOk) {
return prepare_status;
}
}
int32_t start = tflite::GetCurrentTimeTicks();
TfLiteStatus invoke_status = registration->invoke(&context, &node);
TF_LITE_REPORT_ERROR(reporter, "invoke took %d cycles\n",
tflite::GetCurrentTimeTicks() - start);
if (registration->free) {
registration->free(&context, user_data);
}
if (invoke_status != kTfLiteOk) {
return invoke_status;
}
int8_t* output_data = tensors[3].data.int8;
for (int i = 0; i < output_length; ++i) {
if (std::abs(expected_output_data[i] - output_data[i]) > tolerance) {
TF_LITE_REPORT_ERROR(reporter, "output[%d] failed, was %d expected %d\n",
i, static_cast<int>(output_data[i]),
static_cast<int>(expected_output_data[i]));
}
}
return kTfLiteOk;
}
} // namespace
} // namespace testing
} // namespace tflite
int main() {
tflite::MicroErrorReporter reporter;
const int input_shape[] = {4, 1, 1, 1, 32};
const int filter_shape[] = {4, 32, 1, 1, 32};
const int bias_shape[] = {1, 32};
const int output_shape[] = {4, 1, 1, 1, 32};
float filter_values[32 * 32];
float input_values[32];
float bias_values[32];
// Generated these outputs using the floating point reference conv kernel.
// TODO(b/149942509): Do this comparison automatically on random inputs.
float expected_output[32] = {
5168.000000, 3377.000000, 306.000000, -4045.000000, -4556.000000,
-1227.000000, 822.000000, 1591.000000, 5176.000000, 3385.000000,
314.000000, -4037.000000, -4548.000000, -1219.000000, 830.000000,
1599.000000, 5184.000000, 3393.000000, 322.000000, -4029.000000,
-4540.000000, -1211.000000, 838.000000, 1607.000000, 5192.000000,
3401.000000, 330.000000, -4021.000000, -4532.000000, -1203.000000,
846.000000, 1615.000000};
for (int i = 0; i < 32; i++) {
bias_values[i] = i;
input_values[i] = i - 16;
}
for (int i = 0; i < 32 * 32; i++) {
filter_values[i] = (i * 25) % 256 - 128;
}
TfLiteConvParams conv_params;
conv_params.activation = kTfLiteActNone;
conv_params.dilation_height_factor = 1;
conv_params.dilation_width_factor = 1;
conv_params.stride_height = 1;
conv_params.stride_width = 1;
conv_params.padding = kTfLitePaddingValid;
TfLiteIntArray* input_dims = tflite::testing::IntArrayFromInts(input_shape);
TfLiteIntArray* filter_dims = tflite::testing::IntArrayFromInts(filter_shape);
TfLiteIntArray* bias_dims = tflite::testing::IntArrayFromInts(bias_shape);
TfLiteIntArray* output_dims = tflite::testing::IntArrayFromInts(output_shape);
const int output_dims_count = tflite::ElementCount(*output_dims);
// Quantization Parameters. All scales except output are 1.0, and all zero
// points are 0. This direct-maps the values to floating point and makes it
// easy to reson about them.
int input_zero_point = 0;
float input_scale = 1.0f;
int filter_zero_point = 0;
float filter_scale = 1.0f;
int output_zero_point = 0;
// Output scale of 50 is needed to accomodate a float range of [-6400, 6350]
float output_scale = 50.0f;
// Create per-tensor quantized int8 input tensor.
int8_t input_quantized[32];
TfLiteTensor input_tensor = tflite::testing::CreateQuantizedTensor(
input_values, input_quantized, input_dims, input_scale, input_zero_point);
// Set zero point and scale arrays with a single element for each.
int input_zero_points[] = {1, input_zero_point};
float input_scales[] = {1, input_scale};
TfLiteAffineQuantization input_quant = {
tflite::testing::FloatArrayFromFloats(input_scales),
tflite::testing::IntArrayFromInts(input_zero_points)};
input_tensor.quantization = {kTfLiteAffineQuantization, &input_quant};
// Create per-tensor quantized int8 filter tensor.
int8_t filter_quantized[32 * 32];
TfLiteTensor filter_tensor = tflite::testing::CreateQuantizedTensor(
filter_values, filter_quantized, filter_dims, filter_scale,
filter_zero_point);
// Set zero point and scale arrays with a single element for each.
int filter_zero_points[] = {1, filter_zero_point};
float filter_scales[] = {1, filter_scale};
TfLiteAffineQuantization filter_quant = {
tflite::testing::FloatArrayFromFloats(filter_scales),
tflite::testing::IntArrayFromInts(filter_zero_points)};
filter_tensor.quantization = {kTfLiteAffineQuantization, &filter_quant};
// Create per-tensor quantized int32 bias tensor.
int32_t bias_quantized[32];
tflite::SymmetricQuantize(bias_values, bias_quantized, 32,
input_scale * output_scale);
TfLiteTensor bias_tensor =
tflite::testing::CreateInt32Tensor(bias_quantized, bias_dims);
// There is a single zero point of 0, and a single scale of
// input_scale * filter_scale.
int bias_zero_points[] = {1, 0};
float bias_scales[] = {1, input_scale * filter_scale};
TfLiteAffineQuantization bias_quant = {
tflite::testing::FloatArrayFromFloats(bias_scales),
tflite::testing::IntArrayFromInts(bias_zero_points)};
bias_tensor.quantization = {kTfLiteAffineQuantization, &bias_quant};
// Create per-tensor quantized int8 output tensor.
int8_t output_quantized[32];
TfLiteTensor output_tensor = tflite::testing::CreateQuantizedTensor(
output_quantized, output_dims, output_scale, output_zero_point);
// Set zero point and scale arrays with a single element for each.
int output_zero_points[] = {1, output_zero_point};
float output_scales[] = {1, output_scale};
TfLiteAffineQuantization output_quant = {
tflite::testing::FloatArrayFromFloats(output_scales),
tflite::testing::IntArrayFromInts(output_zero_points)};
output_tensor.quantization = {kTfLiteAffineQuantization, &output_quant};
// The 3 inputs include the input, filter and bias tensors.
TfLiteTensor tensors[] = {
input_tensor,
filter_tensor,
bias_tensor,
output_tensor,
};
int8_t golden_quantized[32];
tflite::AsymmetricQuantize(expected_output, golden_quantized,
output_dims_count, output_scale,
output_zero_point);
// Rounding errors due to quantization should not exceed 1.
constexpr int kQuantizationTolerance = 1;
const int num_tensors = sizeof(tensors) / sizeof(TfLiteTensor);
TfLiteStatus status = tflite::testing::ValidateConvGoldens(
tensors, num_tensors, &conv_params, kQuantizationTolerance,
output_dims_count, golden_quantized, &reporter);
if (status != kTfLiteOk) {
TF_LITE_REPORT_ERROR(&reporter, "Model invoke failed\n");
}
return 0;
}
| 40.991379 | 80 | 0.707886 |
73b3a4596cd78848524d1c62f38c0ef15d1fa680 | 14,544 | cpp | C++ | test/api/wallets.cpp | dated/cpp-client | 392ad9ad87004165651aee61feca1b0320b287f8 | [
"MIT"
] | 11 | 2018-10-23T15:06:01.000Z | 2021-11-17T08:02:24.000Z | test/api/wallets.cpp | dated/cpp-client | 392ad9ad87004165651aee61feca1b0320b287f8 | [
"MIT"
] | 160 | 2018-10-24T17:29:11.000Z | 2021-05-10T14:14:29.000Z | test/api/wallets.cpp | dated/cpp-client | 392ad9ad87004165651aee61feca1b0320b287f8 | [
"MIT"
] | 28 | 2018-10-19T10:05:30.000Z | 2020-11-23T23:31:40.000Z |
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include <arkClient.h>
#include "mocks/mock_api.h"
using testing::_;
using testing::Return;
namespace {
using namespace Ark::Client;
using namespace Ark::Client::api;
constexpr const char* tIp = "167.114.29.55";
constexpr const int tPort = 4003;
} // namespace
/**/
TEST(api, test_wallet) { // NOLINT
Ark::Client::Connection<MockApi> connection(tIp, tPort);
const std::string expected_response = R"({
"data": {
"address": "DL6wmfnA2acPLpBjKS4zPGsSwxkTtGANsK",
"publicKey": "02511f16ffb7b7e9afc12f04f317a11d9644e4be9eb5a5f64673946ad0f6336f34",
"username": "genesis_1",
"balance": "10035728150000",
"isDelegate": true,
"vote": "035c14e8c5f0ee049268c3e75f02f05b4246e746dc42f99271ff164b7be20cf5b8"
}
})";
EXPECT_CALL(connection.api.wallets, get(_))
.Times(1)
.WillOnce(Return(expected_response));
const auto wallet = connection.api.wallets.get(
"DL6wmfnA2acPLpBjKS4zPGsSwxkTtGANsK");
auto responseMatches = strcmp(expected_response.c_str(),
wallet.c_str()) == 0;
ASSERT_TRUE(responseMatches);
}
/**/
TEST(api, test_wallets) { // NOLINT
Ark::Client::Connection<MockApi> connection(tIp, tPort);
const std::string expected_response = R"({
"meta": {
"count": 1,
"pageCount": 196457,
"totalCount": 196457,
"next": "/api/wallets?limit=1&page=2",
"previous": null,
"self": "/api/wallets?limit=1&page=1",
"first": "/api/wallets?limit=1&page=1",
"last": "/api/wallets?limit=1&page=196457"
},
"data": [
{
"address": "D6Z26L69gdk9qYmTv5uzk3uGepigtHY4ax",
"publicKey": "03d3fdad9c5b25bf8880e6b519eb3611a5c0b31adebc8455f0e096175b28321aff",
"balance": "9898440219335676",
"isDelegate": false
}
]
})";
EXPECT_CALL(connection.api.wallets, all(_))
.Times(1)
.WillOnce(Return(expected_response));
const auto wallets = connection.api.wallets.all("?limit=1&page=1");
auto responseMatches = strcmp(expected_response.c_str(),
wallets.c_str()) == 0;
ASSERT_TRUE(responseMatches);
}
/**/
TEST(api, test_wallets_search) { // NOLINT
Ark::Client::Connection<MockApi> connection(tIp, tPort);
const std::string expected_response = R"({
"meta": {
"count": 1,
"pageCount": 1,
"totalCount": 1,
"next": null,
"previous": null,
"self": "/api/wallets/search?limit=1&page=1",
"first": "/api/wallets/search?limit=1&page=1",
"last": "/api/wallets/search?limit=1&page=1"
},
"data": [
{
"address": "DL6wmfnA2acPLpBjKS4zPGsSwxkTtGANsK",
"publicKey": "02511f16ffb7b7e9afc12f04f317a11d9644e4be9eb5a5f64673946ad0f6336f34",
"username": "genesis_1",
"balance": "10035728150000",
"isDelegate": true,
"vote": "035c14e8c5f0ee049268c3e75f02f05b4246e746dc42f99271ff164b7be20cf5b8"
}
]
})";
EXPECT_CALL(connection.api.wallets, search(_, _))
.Times(1)
.WillOnce(Return(expected_response));
const std::map<std::string, std::string> body = {
{ "username", "genesis_1" }
};
const auto wallets = connection.api.wallets.search(body, "?limit=1&page=1");
auto responseMatches = strcmp(expected_response.c_str(),
wallets.c_str()) == 0;
ASSERT_TRUE(responseMatches);
}
/**/
TEST(api, test_wallets_top) { // NOLINT
Ark::Client::Connection<MockApi> connection(tIp, tPort);
const std::string expected_response = R"({
"meta": {
"count": 1,
"pageCount": 196457,
"totalCount": 196457,
"next": "/api/wallets/top?page=2&limit=1",
"previous": null,
"self": "/api/wallets/top?page=1&limit=1",
"first": "/api/wallets/top?page=1&limit=1",
"last": "/api/wallets/top?page=196457&limit=1"
},
"data": [
{
"address": "D6Z26L69gdk9qYmTv5uzk3uGepigtHY4ax",
"publicKey": "03d3fdad9c5b25bf8880e6b519eb3611a5c0b31adebc8455f0e096175b28321aff",
"balance": "9898440219335676",
"isDelegate": false
}
]
})";
EXPECT_CALL(connection.api.wallets, top(_))
.Times(1)
.WillOnce(Return(expected_response));
const auto wallets = connection.api.wallets.top("?limit=1&page=1");
auto responseMatches = strcmp(expected_response.c_str(),
wallets.c_str()) == 0;
ASSERT_TRUE(responseMatches);
}
/**/
TEST(api, test_wallets_locks) { // NOLINT
Ark::Client::Connection<MockApi> connection(tIp, tPort);
const std::string expected_response = R"({
"meta": {
"count": 1,
"pageCount": 1,
"totalCount": 1,
"next": null,
"previous": null,
"self": "/api/wallets/03db91f46dcd94311ab51efc9ca352e2628c27ffce63d1a609a14b8473c0db5b5d/locks?page=1&limit=100",
"first": "/api/wallets/03db91f46dcd94311ab51efc9ca352e2628c27ffce63d1a609a14b8473c0db5b5d/locks?page=1&limit=100",
"last": "/api/wallets/03db91f46dcd94311ab51efc9ca352e2628c27ffce63d1a609a14b8473c0db5b5d/locks?page=1&limit=100"
},
"data": [
{
"lockId": "d8c1d95462081fa211a8c56e717a3cdfaa53fd4985fc44473e392ab5458b336c",
"amount": "1",
"secretHash": "09b9a28393efd02fcd76a21b0f0f55ba2aad8f3640ff8cae86de033a9cfbd78c",
"senderPublicKey": "03db91f46dcd94311ab51efc9ca352e2628c27ffce63d1a609a14b8473c0db5b5d",
"recipientId": "D6eAmMh6FFynorCSjHS1Qx75rXiN89soa7",
"timestamp": {
"epoch": 81911280,
"unix": 1572012480,
"human": "2019-10-25T14:08:00.000Z"
},
"expirationType": 2,
"expirationValue": 6000000,
"vendorField": "0.7712082776486138"
}
]
})";
EXPECT_CALL(connection.api.wallets, locks(_, _))
.Times(1)
.WillOnce(Return(expected_response));
const auto locks = connection.api.wallets.locks(
"D9SAVjqkxwWQmb82iqAedJPccFjDUnMSi9", "?limit=1&page=1");
auto responseMatches = strcmp(expected_response.c_str(),
locks.c_str()) == 0;
ASSERT_TRUE(responseMatches);
}
/**/
TEST(api, test_wallets_transactions) { // NOLINT
Ark::Client::Connection<MockApi> connection(tIp, tPort);
const std::string expected_response = R"({
"meta": {
"totalCountIsEstimate": false,
"count": 1,
"pageCount": 7,
"totalCount": 7,
"next": "/api/wallets/DL6wmfnA2acPLpBjKS4zPGsSwxkTtGANsK/transactions?limit=1&page=2&transform=true",
"previous": null,
"self": "/api/wallets/DL6wmfnA2acPLpBjKS4zPGsSwxkTtGANsK/transactions?limit=1&page=1&transform=true",
"first": "/api/wallets/DL6wmfnA2acPLpBjKS4zPGsSwxkTtGANsK/transactions?limit=1&page=1&transform=true",
"last": "/api/wallets/DL6wmfnA2acPLpBjKS4zPGsSwxkTtGANsK/transactions?limit=1&page=7&transform=true"
},
"data": [
{
"id": "a8c0b8b9acabcb742e1760ce16aef5e92f0863bd035fd9bcb341b30d546abdad",
"blockId": "17044958519703434496",
"version": 1,
"type": 0,
"amount": "100000000",
"fee": "10000000",
"sender": "D6Z26L69gdk9qYmTv5uzk3uGepigtHY4ax",
"senderPublicKey": "03d3fdad9c5b25bf8880e6b519eb3611a5c0b31adebc8455f0e096175b28321aff",
"recipient": "DL6wmfnA2acPLpBjKS4zPGsSwxkTtGANsK",
"signature": "3045022100cde3452fa74e8d9c2ed8187467edd631e55eb9bde5de4a62b7f52ec3d57399a602201827ead48ae19255770d10608fad103dc497f47458737edfae6abebbdd82245e",
"confirmations": 2920745,
"timestamp": {
"epoch": 45021207,
"unix": 1535122407,
"human": "2018-08-24T14:53:27.000Z"
}
}
]
})";
EXPECT_CALL(connection.api.wallets, transactions(_, _))
.Times(1)
.WillOnce(Return(expected_response));
const auto transactions = connection.api.wallets.transactions(
"DL6wmfnA2acPLpBjKS4zPGsSwxkTtGANsK", "?limit=1&page=1");
auto responseMatches = strcmp(expected_response.c_str(),
transactions.c_str()) == 0;
ASSERT_TRUE(responseMatches);
}
/**/
TEST(api, test_wallets_transactions_received) { // NOLINT
Ark::Client::Connection<MockApi> connection(tIp, tPort);
const std::string expected_response = R"({
"meta": {
"totalCountIsEstimate": false,
"count": 1,
"pageCount": 7,
"totalCount": 7,
"next": "/api/wallets/DL6wmfnA2acPLpBjKS4zPGsSwxkTtGANsK/transactions/received?limit=1&page=2&transform=true",
"previous": null,
"self": "/api/wallets/DL6wmfnA2acPLpBjKS4zPGsSwxkTtGANsK/transactions/received?limit=1&page=1&transform=true",
"first": "/api/wallets/DL6wmfnA2acPLpBjKS4zPGsSwxkTtGANsK/transactions/received?limit=1&page=1&transform=true",
"last": "/api/wallets/DL6wmfnA2acPLpBjKS4zPGsSwxkTtGANsK/transactions/received?limit=1&page=7&transform=true"
},
"data": [
{
"id": "6b3d348a4341de3ea281d0af584d04ba78f14154955ac14af044a11bd43388cd",
"blockId": "35da9ef1a5ffb396a180a1ccb7b40ee32ddfced5b6c24cb7133c926e8e66796a",
"version": 1,
"type": 3,
"amount": "0",
"fee": "10000000",
"sender": "DL6wmfnA2acPLpBjKS4zPGsSwxkTtGANsK",
"senderPublicKey": "02511f16ffb7b7e9afc12f04f317a11d9644e4be9eb5a5f64673946ad0f6336f34",
"recipient": "DL6wmfnA2acPLpBjKS4zPGsSwxkTtGANsK",
"signature": "3044022052b1d1f49c2efcbd306906449f6f46824db31110e3afbc0ed6fdca2ca5b3d59c0220039dfc70a8b48d49c5df12a7cbbb0cadc969078786d4824d25e8ff251360e763",
"asset": {
"votes": [
"+035c14e8c5f0ee049268c3e75f02f05b4246e746dc42f99271ff164b7be20cf5b8"
]
},
"confirmations": 218052,
"timestamp": {
"epoch": 70926445,
"unix": 1561027645,
"human": "2019-06-20T10:47:25.000Z"
}
}
]
})";
EXPECT_CALL(connection.api.wallets, transactionsReceived(_, _))
.Times(1)
.WillOnce(Return(expected_response));
const auto received = connection.api.wallets.transactionsReceived(
"DL6wmfnA2acPLpBjKS4zPGsSwxkTtGANsK", "?limit=1&page=1");
auto responseMatches = strcmp(expected_response.c_str(),
received.c_str()) == 0;
ASSERT_TRUE(responseMatches);
}
/**/
TEST(api, test_wallets_transactions_sent) { // NOLINT
Ark::Client::Connection<MockApi> connection(tIp, tPort);
const std::string expected_response = R"({
"meta": {
"totalCountIsEstimate": false,
"count": 1,
"pageCount": 4,
"totalCount": 4,
"next": "/api/wallets/DL6wmfnA2acPLpBjKS4zPGsSwxkTtGANsK/transactions/sent?limit=1&page=2&transform=true",
"previous": null,
"self": "/api/wallets/DL6wmfnA2acPLpBjKS4zPGsSwxkTtGANsK/transactions/sent?limit=1&page=1&transform=true",
"first": "/api/wallets/DL6wmfnA2acPLpBjKS4zPGsSwxkTtGANsK/transactions/sent?limit=1&page=1&transform=true",
"last": "/api/wallets/DL6wmfnA2acPLpBjKS4zPGsSwxkTtGANsK/transactions/sent?limit=1&page=4&transform=true"
},
"data": [
{
"id": "6b3d348a4341de3ea281d0af584d04ba78f14154955ac14af044a11bd43388cd",
"blockId": "35da9ef1a5ffb396a180a1ccb7b40ee32ddfced5b6c24cb7133c926e8e66796a",
"version": 1,
"type": 3,
"amount": "0",
"fee": "10000000",
"sender": "DL6wmfnA2acPLpBjKS4zPGsSwxkTtGANsK",
"senderPublicKey": "02511f16ffb7b7e9afc12f04f317a11d9644e4be9eb5a5f64673946ad0f6336f34",
"recipient": "DL6wmfnA2acPLpBjKS4zPGsSwxkTtGANsK",
"signature": "3044022052b1d1f49c2efcbd306906449f6f46824db31110e3afbc0ed6fdca2ca5b3d59c0220039dfc70a8b48d49c5df12a7cbbb0cadc969078786d4824d25e8ff251360e763",
"asset": {
"votes": [
"+035c14e8c5f0ee049268c3e75f02f05b4246e746dc42f99271ff164b7be20cf5b8"
]
},
"confirmations": 218061,
"timestamp": {
"epoch": 70926445,
"unix": 1561027645,
"human": "2019-06-20T10:47:25.000Z"
}
}
]
})";
EXPECT_CALL(connection.api.wallets, transactionsSent(_, _))
.Times(1)
.WillOnce(Return(expected_response));
const auto sent = connection.api.wallets.transactionsSent(
"DL6wmfnA2acPLpBjKS4zPGsSwxkTtGANsK", "?limit=1&page=1");
auto responseMatches = strcmp(expected_response.c_str(),
sent.c_str()) == 0;
ASSERT_TRUE(responseMatches);
}
/**/
TEST(api, test_wallets_votes) { // NOLINT
Ark::Client::Connection<MockApi> connection(tIp, tPort);
const std::string expected_response = R"({
"meta": {
"totalCountIsEstimate": false,
"count": 1,
"pageCount": 3,
"totalCount": 3,
"next": "/api/wallets/DL6wmfnA2acPLpBjKS4zPGsSwxkTtGANsK/votes?limit=1&page=2&transform=true",
"previous": null,
"self": "/api/wallets/DL6wmfnA2acPLpBjKS4zPGsSwxkTtGANsK/votes?limit=1&page=1&transform=true",
"first": "/api/wallets/DL6wmfnA2acPLpBjKS4zPGsSwxkTtGANsK/votes?limit=1&page=1&transform=true",
"last": "/api/wallets/DL6wmfnA2acPLpBjKS4zPGsSwxkTtGANsK/votes?limit=1&page=3&transform=true"
},
"data": [
{
"id": "6b3d348a4341de3ea281d0af584d04ba78f14154955ac14af044a11bd43388cd",
"blockId": "35da9ef1a5ffb396a180a1ccb7b40ee32ddfced5b6c24cb7133c926e8e66796a",
"version": 1,
"type": 3,
"amount": "0",
"fee": "10000000",
"sender": "DL6wmfnA2acPLpBjKS4zPGsSwxkTtGANsK",
"senderPublicKey": "02511f16ffb7b7e9afc12f04f317a11d9644e4be9eb5a5f64673946ad0f6336f34",
"recipient": "DL6wmfnA2acPLpBjKS4zPGsSwxkTtGANsK",
"signature": "3044022052b1d1f49c2efcbd306906449f6f46824db31110e3afbc0ed6fdca2ca5b3d59c0220039dfc70a8b48d49c5df12a7cbbb0cadc969078786d4824d25e8ff251360e763",
"asset": {
"votes": [
"+035c14e8c5f0ee049268c3e75f02f05b4246e746dc42f99271ff164b7be20cf5b8"
]
},
"confirmations": 218065,
"timestamp": {
"epoch": 70926445,
"unix": 1561027645,
"human": "2019-06-20T10:47:25.000Z"
}
}
]
})";
EXPECT_CALL(connection.api.wallets, votes(_, _))
.Times(1)
.WillOnce(Return(expected_response));
const auto votes = connection.api.wallets.votes(
"DL6wmfnA2acPLpBjKS4zPGsSwxkTtGANsK", "?limit=1&page=1");
auto responseMatches = strcmp(expected_response.c_str(),
votes.c_str()) == 0;
ASSERT_TRUE(responseMatches);
}
| 33.981308 | 166 | 0.656216 |
73b7336f682ba26cfed8a868e6defae302ec6ff4 | 130 | cpp | C++ | src/options.cpp | kz04px/chip8-interpreter | 51476ca70fec25c1657ae94a92a31758b49e195e | [
"MIT"
] | null | null | null | src/options.cpp | kz04px/chip8-interpreter | 51476ca70fec25c1657ae94a92a31758b49e195e | [
"MIT"
] | null | null | null | src/options.cpp | kz04px/chip8-interpreter | 51476ca70fec25c1657ae94a92a31758b49e195e | [
"MIT"
] | null | null | null | #include "options.hpp"
namespace options {
bool borders = true;
bool debug = false;
bool mute = false;
} // namespace options
| 13 | 23 | 0.7 |
73b826ec6a87807b5a000a7871f947cf5e082091 | 820 | cpp | C++ | src/processor.cpp | humbertusa79/CppND-System-Monitor-HumbertoSolution | a0aaf701aadf07a6f4694fd71c8a6a644807fdfa | [
"MIT"
] | null | null | null | src/processor.cpp | humbertusa79/CppND-System-Monitor-HumbertoSolution | a0aaf701aadf07a6f4694fd71c8a6a644807fdfa | [
"MIT"
] | null | null | null | src/processor.cpp | humbertusa79/CppND-System-Monitor-HumbertoSolution | a0aaf701aadf07a6f4694fd71c8a6a644807fdfa | [
"MIT"
] | null | null | null | #include "processor.h"
double Processor::Utilization() {
vector<string> cpuInformation = LinuxParser::CpuUtilization();
double previdle = prevIdle + prevIOWait;
double idle = stod(cpuInformation[CPUStates::kIdle_]) + stod(cpuInformation[CPUStates::kIOwait_]);
double prevNonIdle = prevUser + prevNice + prevSystem + prevIrq + prevSoftIrq + prevSteal;
double nonIdle = stod(cpuInformation[CPUStates::kUser_]) + stod(cpuInformation[CPUStates::kNice_]) + stod(cpuInformation[CPUStates::kSystem_]) + stod(cpuInformation[CPUStates::kIRQ_]) + stod(cpuInformation[CPUStates::kSoftIRQ_]) + stod(cpuInformation[CPUStates::kSteal_]);
double prevTotal = previdle + prevNonIdle;
double total = idle + nonIdle;
double totald = total - prevTotal;
double idled = idle + prevIdle;
return (totald - idled)/totald;
} | 58.571429 | 274 | 0.753659 |
73b8c5a5d085532576b015c9e803a2555fcf495d | 1,884 | cc | C++ | amqp-open/src/model/ListBindingsRequest.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | amqp-open/src/model/ListBindingsRequest.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | amqp-open/src/model/ListBindingsRequest.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/amqp-open/model/ListBindingsRequest.h>
using AlibabaCloud::Amqp_open::Model::ListBindingsRequest;
ListBindingsRequest::ListBindingsRequest() :
RpcServiceRequest("amqp-open", "2019-12-12", "ListBindings")
{
setMethod(HttpRequest::Method::Get);
}
ListBindingsRequest::~ListBindingsRequest()
{}
std::string ListBindingsRequest::getInstanceId()const
{
return instanceId_;
}
void ListBindingsRequest::setInstanceId(const std::string& instanceId)
{
instanceId_ = instanceId;
setParameter("InstanceId", instanceId);
}
std::string ListBindingsRequest::getNextToken()const
{
return nextToken_;
}
void ListBindingsRequest::setNextToken(const std::string& nextToken)
{
nextToken_ = nextToken;
setParameter("NextToken", nextToken);
}
int ListBindingsRequest::getMaxResults()const
{
return maxResults_;
}
void ListBindingsRequest::setMaxResults(int maxResults)
{
maxResults_ = maxResults;
setParameter("MaxResults", std::to_string(maxResults));
}
std::string ListBindingsRequest::getVirtualHost()const
{
return virtualHost_;
}
void ListBindingsRequest::setVirtualHost(const std::string& virtualHost)
{
virtualHost_ = virtualHost;
setParameter("VirtualHost", virtualHost);
}
| 25.459459 | 75 | 0.75 |
73b9eb40e4d41b656d279febf6f9387e66b4d3e2 | 3,735 | cpp | C++ | rocsolver/library/src/lapack/roclapack_potrf.cpp | leekillough/rocSOLVER | a0fa2af65be983dcec60081ed618b0642867aef0 | [
"BSD-2-Clause"
] | null | null | null | rocsolver/library/src/lapack/roclapack_potrf.cpp | leekillough/rocSOLVER | a0fa2af65be983dcec60081ed618b0642867aef0 | [
"BSD-2-Clause"
] | null | null | null | rocsolver/library/src/lapack/roclapack_potrf.cpp | leekillough/rocSOLVER | a0fa2af65be983dcec60081ed618b0642867aef0 | [
"BSD-2-Clause"
] | null | null | null | /* ************************************************************************
* Copyright 2019-2020 Advanced Micro Devices, Inc.
* ************************************************************************ */
#include "roclapack_potrf.hpp"
template <typename S, typename T, typename U>
rocblas_status rocsolver_potrf_impl(rocblas_handle handle, const rocblas_fill uplo,
const rocblas_int n, U A, const rocblas_int lda, rocblas_int* info)
{
if(!handle)
return rocblas_status_invalid_handle;
//logging is missing ???
// argument checking
if (!A || !info)
return rocblas_status_invalid_pointer;
if (n < 0 || lda < n)
return rocblas_status_invalid_size;
rocblas_stride strideA = 0;
rocblas_int batch_count = 1;
// memory managment
size_t size_1; //size of constants
size_t size_2; //size of workspace
size_t size_3;
size_t size_4;
rocsolver_potrf_getMemorySize<T>(n,batch_count,&size_1,&size_2,&size_3,&size_4);
// (TODO) MEMORY SIZE QUERIES AND ALLOCATIONS TO BE DONE WITH ROCBLAS HANDLE
void *scalars, *work, *pivotGPU, *iinfo;
hipMalloc(&scalars,size_1);
hipMalloc(&work,size_2);
hipMalloc(&pivotGPU,size_3);
hipMalloc(&iinfo,size_4);
if (!scalars || (size_2 && !work) || (size_3 && !pivotGPU) || (size_4 && !iinfo))
return rocblas_status_memory_error;
// scalars constants for rocblas functions calls
// (to standarize and enable re-use, size_1 always equals 3)
std::vector<T> sca(size_1);
sca[0] = -1;
sca[1] = 0;
sca[2] = 1;
RETURN_IF_HIP_ERROR(hipMemcpy(scalars, sca.data(), sizeof(T)*size_1, hipMemcpyHostToDevice));
// execution
rocblas_status status =
rocsolver_potrf_template<S,T>(handle,uplo,n,
A,0, //the matrix is shifted 0 entries (will work on the entire matrix)
lda,strideA,
info,batch_count,
(T*)scalars,
(T*)work,
(T*)pivotGPU,
(rocblas_int*)iinfo);
hipFree(scalars);
hipFree(work);
hipFree(pivotGPU);
hipFree(iinfo);
return status;
}
/*
* ===========================================================================
* C wrapper
* ===========================================================================
*/
extern "C" {
ROCSOLVER_EXPORT rocblas_status rocsolver_spotrf(rocblas_handle handle, const rocblas_fill uplo, const rocblas_int n,
float *A, const rocblas_int lda, rocblas_int* info)
{
return rocsolver_potrf_impl<float,float>(handle, uplo, n, A, lda, info);
}
ROCSOLVER_EXPORT rocblas_status rocsolver_dpotrf(rocblas_handle handle, const rocblas_fill uplo, const rocblas_int n,
double *A, const rocblas_int lda, rocblas_int* info)
{
return rocsolver_potrf_impl<double,double>(handle, uplo, n, A, lda, info);
}
ROCSOLVER_EXPORT rocblas_status rocsolver_cpotrf(rocblas_handle handle, const rocblas_fill uplo, const rocblas_int n,
rocblas_float_complex *A, const rocblas_int lda, rocblas_int* info)
{
return rocsolver_potrf_impl<float,rocblas_float_complex>(handle, uplo, n, A, lda, info);
}
ROCSOLVER_EXPORT rocblas_status rocsolver_zpotrf(rocblas_handle handle, const rocblas_fill uplo, const rocblas_int n,
rocblas_double_complex *A, const rocblas_int lda, rocblas_int* info)
{
return rocsolver_potrf_impl<double,rocblas_double_complex>(handle, uplo, n, A, lda, info);
}
}
| 36.262136 | 117 | 0.578849 |
73be838c6e696c7e54255b7284532aa3b36c68ac | 11,643 | cpp | C++ | ngraph/test/backend/group_convolution_backprop_data.in.cpp | monroid/openvino | 8272b3857ef5be0aaa8abbf7bd0d5d5615dc40b6 | [
"Apache-2.0"
] | 1 | 2021-07-14T07:20:24.000Z | 2021-07-14T07:20:24.000Z | ngraph/test/backend/group_convolution_backprop_data.in.cpp | monroid/openvino | 8272b3857ef5be0aaa8abbf7bd0d5d5615dc40b6 | [
"Apache-2.0"
] | 34 | 2020-11-19T12:27:40.000Z | 2022-02-21T13:14:04.000Z | ngraph/test/backend/group_convolution_backprop_data.in.cpp | monroid/openvino | 8272b3857ef5be0aaa8abbf7bd0d5d5615dc40b6 | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "engines_util/test_case.hpp"
#include "engines_util/test_engines.hpp"
#include "gtest/gtest.h"
#include "ngraph/ngraph.hpp"
#include "util/test_control.hpp"
using namespace std;
using namespace ngraph;
static string s_manifest = "${MANIFEST}";
using TestEngine = test::ENGINE_CLASS_NAME(${BACKEND_NAME});
static void GroupConvolutionBackPropDataTest(const std::vector<float>& inputs,
const Shape inputs_shape,
const std::vector<float>& filters,
const Shape filter_shape,
const std::vector<float>& outputs,
const Shape outputs_shape,
const Strides& strides,
const CoordinateDiff& padding,
const Strides& dilations) {
CoordinateDiff pads_begin{padding};
CoordinateDiff pads_end{padding};
const op::PadType auto_pad{op::PadType::EXPLICIT};
auto inputs_param = make_shared<op::Parameter>(element::f32, inputs_shape);
auto filter_param = make_shared<op::Parameter>(element::f32, filter_shape);
auto conv_backprop_data = make_shared<op::v1::GroupConvolutionBackpropData>(inputs_param,
filter_param,
strides,
pads_begin,
pads_end,
dilations,
auto_pad);
auto f = make_shared<Function>(conv_backprop_data, ParameterVector{inputs_param, filter_param});
auto test_case = test::TestCase<TestEngine>(f);
test_case.add_input<float>(inputs_shape, inputs);
test_case.add_input<float>(filter_shape, filters);
test_case.add_expected_output<float>(outputs_shape, outputs);
test_case.run();
}
// --------------------- 1D group convolution ------------------------------------------
// clang-format off
NGRAPH_TEST(${BACKEND_NAME}, group_convolution_backprop_data_1D_1group_1batch_1channel)
{
const Strides strides{1};
const CoordinateDiff padding{0};
const Strides dilations{1};
const Shape inputs_shape{1, 1, 4};
const std::vector<float> inputs{1.0f, 3.0f, 3.0f, 0.0f};
const Shape filter_shape{1, 1, 1, 3};
const std::vector<float> filters{2.0f, 0.0f, 1.0f};
const Shape outputs_shape{1, 1, 6};
const std::vector<float> outputs{2.0f, 6.0f, 7.0f, 3.0f, 3.0f, 0.0f};
GroupConvolutionBackPropDataTest(inputs,
inputs_shape,
filters,
filter_shape,
outputs,
outputs_shape,
strides,
padding,
dilations);
}
NGRAPH_TEST(${BACKEND_NAME}, group_convolution_backprop_data_1D_2group_1batch_2channel)
{
const Strides strides{1};
const CoordinateDiff padding{0};
const Strides dilations{1};
const Shape inputs_shape{1, 2, 4};
const std::vector<float> inputs{1.0f, 3.0f, 3.0f, 0.0f,
1.0f, 2.0f, 1.0f, 3.0f};
const Shape filter_shape{2, 1, 1, 3};
const std::vector<float> filters{1.0f, 0.0f, 3.0f, 3.0f, 0.0f, 1.0f};
const Shape outputs_shape{1, 2, 6};
const std::vector<float> outputs{
1.0f, 3.0f, 6.0f, 9.0f, 9.0f, 0.0f, 3.0f, 6.0f, 4.0f, 11.0f, 1.0f, 3.0f};
GroupConvolutionBackPropDataTest(inputs,
inputs_shape,
filters,
filter_shape,
outputs,
outputs_shape,
strides,
padding,
dilations);
}
NGRAPH_TEST(${BACKEND_NAME}, group_convolution_backprop_data_1D_2group_1batch_2_filters_2channel)
{
const Strides strides{1};
const CoordinateDiff padding{0};
const Strides dilations{1};
const Shape inputs_shape{1, 4, 4};
const std::vector<float> inputs{1.0f, 3.0f, 3.0f, 0.0f,
1.0f, 2.0f, -1.0f, -3.0f,
-3.0f, 0.0f, 1.0f, 2.0f,
0.0f, -2.0f, 3.0f, -1.0f};
const Shape filter_shape{2, 2, 1, 3};
const std::vector<float> filters{
1.0f, 0.0f, 3.0f, 3.0f, 0.0f, 1.0f, -3.0f, 0.0f, 1.0f, 3.0f, 2.0f, -1.0f};
const Shape outputs_shape{1, 2, 6};
const std::vector<float> outputs{
4.0f, 9.0f, 4.0f, 2.0f, 8.0f, -3.0f, 9.0f, -6.0f, -1.0f, -1.0f, -4.0f, 3.0f};
GroupConvolutionBackPropDataTest(inputs,
inputs_shape,
filters,
filter_shape,
outputs,
outputs_shape,
strides,
padding,
dilations);
}
NGRAPH_TEST(${BACKEND_NAME}, group_convolution_backprop_data_1D_2group_2batch_2channel)
{
const Strides strides{1};
const CoordinateDiff padding{0};
const Strides dilations{1};
const Shape inputs_shape{2, 2, 4};
const std::vector<float> inputs{// -- batch 1 --
1.0f, 3.0f, 0.0f, 1.0f,
1.0f, 3.0f, 0.0f, 2.0f,
// -- batch 2 --
1.0f, 3.0f, 0.0f, 1.0f,
1.0f, 3.0f, 0.0f, 2.0f};
const Shape filter_shape{2, 1, 1, 3};
const std::vector<float> filters{1.0f, 0.0f, 3.0f, 3.0f, 0.0f, 1.0f};
const Shape outputs_shape{2, 2, 6};
const std::vector<float> outputs{1.0f, 3.0f, 3.0f, 10.0f, 0.0f, 3.0f,
3.0f, 9.0f, 1.0f, 9.0f, 0.0f, 2.0f,
1.0f, 3.0f, 3.0f, 10.0f, 0.0f, 3.0f,
3.0f, 9.0f, 1.0f, 9.0f, 0.0f, 2.0f};
GroupConvolutionBackPropDataTest(inputs,
inputs_shape,
filters,
filter_shape,
outputs,
outputs_shape,
strides,
padding,
dilations);
}
// clang-format on
// --------------------- 2D group convolution ------------------------------------------
NGRAPH_TEST(${BACKEND_NAME}, group_convolution_backprop_data_2D) {
const CoordinateDiff output_padding{1, 1};
const CoordinateDiff pads_begin{1, 1};
const CoordinateDiff pads_end{1, 1};
Strides strides{2, 2};
Strides dilations{1, 1};
const op::PadType auto_pad{op::PadType::EXPLICIT};
auto data = make_shared<op::Parameter>(element::f32, Shape{1, 1, 3, 3});
auto filters = make_shared<op::Parameter>(element::f32, Shape{1, 1, 1, 3, 3});
auto gcbd = make_shared<op::v1::GroupConvolutionBackpropData>(data,
filters,
strides,
pads_begin,
pads_end,
dilations,
auto_pad,
output_padding);
auto function = make_shared<Function>(NodeVector{gcbd}, ParameterVector{data, filters});
auto test_case = test::TestCase<TestEngine>(function);
// X
test_case.add_input<float>(vector<float>{0.16857791f,
-0.15161794f,
0.08540368f,
0.1820628f,
-0.21746576f,
0.08245695f,
0.1431433f,
-0.43156421f,
0.30591947f});
// W
test_case.add_input<float>({-0.06230065f,
0.37932432f,
-0.25388849f,
0.33878803f,
0.43709868f,
-0.22477469f,
0.04118127f,
-0.44696793f,
0.06373066f});
test_case.add_expected_output(
Shape{1, 1, 6, 6},
vector<float>{0.07368518f, -0.08925839f, -0.06627201f, 0.06301362f, 0.03732984f, -0.01919658f,
-0.00628807f, -0.02817563f, -0.01472169f, 0.04392925f, -0.00689478f, -0.01549204f,
0.07957941f, -0.11459791f, -0.09505399f, 0.07681622f, 0.03604182f, -0.01853423f,
-0.0270785f, -0.00680824f, -0.06650258f, 0.08004665f, 0.07918708f, -0.0724144f,
0.06256775f, -0.17838378f, -0.18863615f, 0.20064656f, 0.133717f, -0.06876295f,
-0.06398046f, -0.00864975f, 0.19289537f, -0.01490572f, -0.13673618f, 0.01949645f});
test_case.run(DEFAULT_FLOAT_TOLERANCE_BITS + 1);
}
NGRAPH_TEST(${BACKEND_NAME}, group_convolution_backprop_data_2D_output_shape) {
Strides strides{1, 1};
Strides dilations{1, 1};
auto data = make_shared<op::Parameter>(element::f32, Shape{1, 1, 1, 10});
auto filters = make_shared<op::Parameter>(element::f32, Shape{1, 1, 1, 1, 5});
auto output_shape = op::Constant::create(element::i64, Shape{2}, {1, 14});
auto gcbd = make_shared<op::v1::GroupConvolutionBackpropData>(data,
filters,
output_shape,
strides,
dilations,
op::PadType::SAME_UPPER);
auto function = make_shared<Function>(NodeVector{gcbd}, ParameterVector{data, filters});
auto test_case = test::TestCase<TestEngine>(function);
// X
test_case.add_input<float>(vector<float>{0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f});
// W
test_case.add_input<float>({1.0f, 2.0f, 3.0f, 2.0f, 1.0f});
test_case.add_expected_output(
Shape{1, 1, 1, 14},
vector<float>{0.0f, 1.0f, 4.0f, 10.0f, 18.0f, 27.0f, 36.0f, 45.0f, 54.0f, 63.0f, 62.0f, 50.0f, 26.0f, 9.0f});
test_case.run();
}
| 46.202381 | 117 | 0.449884 |
73bf6f8d6f2592fe2a09c64173e1b709630ed9ad | 18,066 | cpp | C++ | utils/errmsg/errmsg.cpp | kammerdienerb/flang | 8cc4a02b94713750f09fe6b756d33daced0b4a74 | [
"Apache-2.0"
] | 1 | 2019-12-11T17:43:58.000Z | 2019-12-11T17:43:58.000Z | utils/errmsg/errmsg.cpp | kammerdienerb/flang | 8cc4a02b94713750f09fe6b756d33daced0b4a74 | [
"Apache-2.0"
] | 2 | 2019-12-29T21:15:40.000Z | 2020-06-15T11:21:10.000Z | utils/errmsg/errmsg.cpp | kammerdienerb/flang | 8cc4a02b94713750f09fe6b756d33daced0b4a74 | [
"Apache-2.0"
] | 3 | 2019-12-21T06:35:35.000Z | 2020-06-07T23:18:58.000Z | /*
* Copyright (c) 2016-2018, NVIDIA CORPORATION. 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 <cstring>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
#include <cstdlib>
/**
* \file errmsg.cpp
* \brief utility program for managing compiler error messages.
*
* ERRMSG - Utility program which reads file(s) in nroff format
* defining error numbers and messages, and writes a file of
* C code defining and initializing the data structure
* containing the message text.
*
* INPUT: error message text definition file(s).
*
* OUTPUT: errmsgdf.h
* output format:
* static char* errtxt[] = {
* ** 000 ** "text for message 0",
* ** 001 ** "text for message 1",
* " . . . ",
* };
*
* An error message definition in the errmsg*.n files looks like this:
*
* .MS W 109 "Type specification of field $ ignored"
* Bit fields must be int, char, or short.
* Bit field is given the type unsigned int.
*
* The arguments to the .MS macro are:
*
* - A letter indicating the severity. One of:
* [I]nformational, [W]arning, [S]evere error,
* [F]atal error, or [V]ariable severity.
*
* - A unique error code.
*
* - The error message in quotes.
*
* - Optionaly, a symbolic name for referring to the error in source
* code. If no symbolic name is given, one is derived from the
* error message like this:
*
* W_0109_Type_specification_of_field_OP1_ignored
*
* When the symbolic name is specified explicitly, it replaces the
* automatically generated name.
*/
#if defined(_MSC_VER)
#include <BaseTsd.h>
typedef SSIZE_T ssize_t;
#endif
/**
* \class Message
* \brief Record for each message.
*/
struct Message {
ssize_t number; //!< numeric error code
char severity; //!< error severity code
std::string symbol; //!< enum symbol for the error
std::string message; //!< error message text
std::vector<std::string> lines; //!< human explanation of an error
/**
* \brief Message default constructor
* number is initialized to -1 as a flag for messages that have not
* been defined yet.
* other fields are default initialized to empty strings and vector.
* This constructor is used when the vector of messages is created
* or resized.
*/
Message() : number(-1), severity('\0')
{
}
/**
* \brief fill in the elements of a message.
* \param n the numeric code for the error message.
* \param s the severity code.
* \param m the rest of the macro text specifying the error message.
* \return 0 if successful or 1 otherwise.
*
* Parse a symbolic message identifier or generate a symbolic name
* from the message text.
*/
int
fill(int n, char s, std::string &m)
{
number = n;
severity = s;
// find the boundaries of a message text in quotes " or '.
std::string::size_type begin_position = m.find_first_of("\"'");
if (begin_position != std::string::npos) {
std::string::size_type end_position =
m.find_last_of(m.substr(begin_position, 1));
if (end_position != std::string::npos) {
// message text is the text in quotes excluding the quotes.
message =
m.substr(begin_position + 1, end_position - begin_position - 1);
// find the symbol or generate from message if none found.
begin_position = m.find_first_not_of(" \t", end_position + 1);
std::ostringstream buffer;
if (begin_position != std::string::npos)
buffer << m.substr(begin_position);
else
buffer << severity << "_" << std::setfill('0') << std::setw(4)
<< number << "_" << message;
symbol = buffer.str();
// replace $ with OPn, where n is 1, 2, ...
int op = 1;
bool more = true;
while (more) {
more = false;
begin_position = symbol.find_first_of("$");
if (begin_position != std::string::npos) {
more = true;
buffer.str("");
buffer << "OP" << op++;
symbol.replace(begin_position, 1, buffer.str());
}
}
// replace illegal characters with '_' avoiding multiple
// sequential underscores
begin_position = 0;
while (begin_position != std::string::npos) {
begin_position = symbol.find_first_not_of(
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
begin_position);
if (begin_position != std::string::npos) {
if (symbol[begin_position - 1] == '_')
symbol.replace(begin_position, 1, "");
else
symbol.replace(begin_position++, 1, "_");
}
}
// delete the trailing underscore, if any.
begin_position = symbol.size() - 1;
if (symbol[begin_position] == '_')
symbol.replace(begin_position, 1, "");
return 0;
}
}
return 1;
}
};
/**
* \class Errmsg
* \brief the application class encapsulates the application logic.
*/
class Errmsg
{
private:
std::vector<const char *> input_filenames; //!< one or more input files
const char *header_filename; //!< c header output file
const char *nroff_filename; //!< aggregated doc output file
const char *sphinx_filename; //!< aggregated Sphinx file
//! lines before the first message definition
std::vector<std::string> initial_lines;
std::vector<Message> messages; //!< recorded error messages
public:
/**
* \brief A constructor that processes the command line options.
*
* Multiple options of the same kind are ignored, only the last one
* is used, except for input filename arguments, e.g.
* $ ./errmsg -o out1.h -e err1.n in1.n in2.n -o out2.h
*
* ignores out1.h, reads in1.n and in2.n as input, writes C
* definitions to out2.h, and writes aggregated nroff output to
* err1.n. Throws an exception if the command line options are
* wrong or missing.
*/
Errmsg(int argc, char *argv[])
: header_filename(0), nroff_filename(0), sphinx_filename(0)
{
for (int arg = 1; arg < argc; ++arg) {
if (strcmp(argv[arg], "-e") == 0) {
if (++arg < argc)
nroff_filename = argv[arg];
else
usage("missing error file name");
} else if (strcmp(argv[arg], "-o") == 0) {
if (++arg < argc)
header_filename = argv[arg];
else
usage("missing output file name");
} else if (strcmp(argv[arg], "-s") == 0) {
if (++arg < argc)
sphinx_filename = argv[arg];
else
usage("missing Sphinx file name");
} else if (argv[arg][0] == '-')
usage("unknown option");
else
input_filenames.push_back(argv[arg]);
}
if (input_filenames.size() == 0)
usage("missing input file name");
if (nroff_filename == 0)
usage("missing nroff doc file name");
if (header_filename == 0)
usage("missing header file name");
}
/**
* \brief The driver of the utility program.
* Read the input files and write the output files.
* \return 0 if successful, 1 otherwise.
*/
int
run()
{
for (std::vector<const char *>::iterator it = input_filenames.begin();
it != input_filenames.end(); ++it)
if (read_input(*it))
return 1;
if (sphinx_filename && write_aggregated_sphinx())
return 1;
if (write_aggregated_nroff())
return 1;
return write_c_declarations();
}
private:
/**
* \brief output usage information for the program
* Exit if invalid command line options are given.
* \param error the error messages indicating a problem with the
* command line options.
*/
void
usage(const char *error = 0)
{
std::cout << "Usage: errmsg -e doc_file -o header_file [-s sphinx_file] "
"input_file(s)\n\n";
std::cout
<< "input_file(s) -- one or more input files with error messages\n";
std::cout
<< "-e doc_file -- file to write the aggregated nroff output\n";
std::cout
<< "-o header_file -- file to write the aggregated C declarations\n";
std::cout
<< "-s sphinx_file -- file to write the output in Sphinx format\n\n";
if (error) {
std::cerr << "Invalid command line: " << error << "\n\n";
std::exit(1);
}
}
/**
* \brief read a single input file
* Fill in the information for error messages defined in the input
* file.
* \param filename the name of the input file.
* \return 0 if successful or 1 otherwise.
*/
int
read_input(const char *filename)
{
std::ifstream ifs(filename);
if (!ifs) {
std::cerr << "Input file could not be opened: " << filename << "\n";
return 1;
}
int ret = 0;
int lineno = 0;
std::vector<std::string> *lines = &initial_lines;
for (std::string line; std::getline(ifs, line); ++lineno) {
std::vector<Message>::size_type num;
std::string text;
char severity;
if (line.compare(0, 4, ".MS ")) {
lines->push_back(line);
continue;
}
// extract the components of a macro .MS W 109 "..."
std::istringstream iss(line.substr(4));
iss >> severity >> num;
std::getline(iss, text);
if (text.size() < 2) {
std::cerr << filename << ":" << lineno << ": bad .MS macro: " << line
<< "\n";
ret = 1;
continue;
}
if (num >= messages.size())
messages.resize(num + 1);
// check a messages with the same number has been recorded earlier.
if (messages[num].number != -1) {
std::cerr << filename << ":" << lineno
<< ": two messages with the same number: " << num << "\n";
ret = 1;
continue;
}
// message text is anything between <"> and <"> or <'> and <'>.
if (messages[num].fill(num, severity, text)) {
std::cerr << filename << ":" << lineno << "message text missing: %d"
<< num << "\n";
ret = 1;
continue;
}
lines = &(messages[num].lines);
lines->push_back(line);
}
return ret;
}
/**
* \brief get rid of surrounding quotation mark if any.
* \param input a text that may have leading or trailing whitespace
* and contained in quotation marks "text".
* \return a new string with quotation marks stripped or the
* input text if no quotation marks found.
*/
std::string
strip_surrounding_quotes(const std::string &input)
{
auto begin_pos = input.find_first_of('"');
if (begin_pos == std::string::npos)
return input;
auto end_pos = input.find_first_of('"', begin_pos + 1);
if (end_pos == std::string::npos)
return input;
return input.substr(begin_pos + 1, end_pos - begin_pos - 1);
}
/**
* \brief convert a single line of text from NROFF to RST.
* Parse NROFF control sequences and transform the text to suitable
* RST representation that preserves typesetting encoded in NROFF.
* \param input a string of text to be transformed.
* \return transformed string.
*/
std::string
transform_nroff_to_sphinx(const std::string &input)
{
std::ostringstream oss;
if (input[0] == '.') {
std::istringstream iss(input.substr(1));
std::string macro;
iss >> macro;
if (macro == "NS") {
int chapter;
iss >> chapter;
std::string header;
std::getline(iss, header);
// extract only the first quoted part of the line.
auto begin_pos = header.find_first_of('"');
std::string::size_type end_pos;
if (begin_pos == std::string::npos) {
begin_pos = 0;
end_pos = header.size() + 1;
} else {
begin_pos += 1;
end_pos = header.find_first_of('"', begin_pos);
}
std::string underline(end_pos - begin_pos, '*');
oss << underline << "\n"
<< header.substr(begin_pos, end_pos - begin_pos) << "\n"
<< underline;
} else if (macro == "US") {
std::string text;
std::getline(iss, text);
oss << "* " << strip_surrounding_quotes(text) << " - ";
}
} else
oss << input;
return oss.str();
}
/**
* \brief escape the RST inline markup characters in text.
* Replace special RST symbols with their escaped equivalents so
* that these symbols appear in the typeset document as themselves.
* \param input a text string to be transformed.
* \return the input text string with all markup characters escaped.
*/
std::string
escape_markup(std::string &input)
{
for (std::string::size_type pos = 0; pos != std::string::npos;) {
pos = input.find_first_of("*`|", pos);
if (pos != std::string::npos) {
// if a markup character is already escaped don't do anything,
// because it's a part of an NROFF controlling sequence.
if (pos == 0 || input[pos - 1] != '\\') {
input.insert(pos, 1, '\\');
pos += 2;
} else {
pos += 1;
}
}
}
return input;
}
/**
* \brief trim any trailing whitespace.
* \param input a string of text.
* \return the input text without any trailing whitespace at the
* end.
*/
std::string
trim_trailing_whitespace(const std::string &input)
{
std::string::size_type pos = input.find_last_not_of(' ');
return input.substr(0, pos + 1);
}
/**
* \brief write the aggregated Sphinx file with all error messages.
*
* \return 0 if successful or 1 otherwise.
*/
int
write_aggregated_sphinx()
{
std::ofstream out(sphinx_filename);
if (!out) {
std::cerr << "Output file could not be opened: " << sphinx_filename
<< "\n";
return 1;
}
// output the initial lines.
for (std::vector<std::string>::iterator it = initial_lines.begin();
it != initial_lines.end(); ++it)
out << transform_nroff_to_sphinx(*it) << "\n";
// output each message.
out << std::setfill('0');
for (std::vector<Message>::iterator m = messages.begin();
m != messages.end(); ++m) {
if (m->number != -1) {
out << "**" << m->severity << std::setw(3) << m->number << "** *"
<< trim_trailing_whitespace(m->message) << "*\n";
for (std::vector<std::string>::iterator it = m->lines.begin() + 1;
it != m->lines.end(); ++it)
out << " " << transform_nroff_to_sphinx(escape_markup(*it)) << "\n";
out << "\n";
}
}
return 0;
}
/**
* \brief write the aggregated nroff file with all error messages.
*
* \return 0 if successful or 1 otherwise.
*/
int
write_aggregated_nroff()
{
std::ofstream out(nroff_filename);
if (!out) {
std::cerr << "Output file could not be opened: " << nroff_filename
<< "\n";
return 1;
}
// output the initial lines.
for (std::vector<std::string>::iterator it = initial_lines.begin();
it != initial_lines.end(); ++it)
out << *it << "\n";
// output each message.
for (std::vector<Message>::iterator m = messages.begin();
m != messages.end(); ++m)
for (std::vector<std::string>::iterator it = m->lines.begin();
it != m->lines.end(); ++it)
out << *it << "\n";
return 0;
}
/**
* \brief write the c header file with error message definitions.
*
* \return 0 if successful or 1 otherwise.
*/
int
write_c_declarations()
{
std::ofstream out(header_filename);
if (!out) {
std::cerr << "Output file could not be opened: " << header_filename
<< "\n";
return 1;
}
out << "// This file written by utility program errmsg. Do not modify.\n"
"#ifdef ERRMSG_GET_ERRTXT_TABLE\n"
"#ifndef ERRMSGDFa_H_\n"
"#define ERRMSGDFa_H_\n"
"static char *errtxt[] = {\n";
out << std::setfill('0');
for (std::vector<Message>::size_type num = 0; num < messages.size();
++num) {
out << " /* " << std::setw(3) << num << " */";
if (messages[num].number == -1)
out << " \"\",\n";
else
out << " \"" << messages[num].message << "\",\n";
}
out << "};\n"
"#endif // ERRMSGDFa_H_\n"
"#else /* ERRMSG_GET_ERRTXT_TABLE */\n"
"#ifndef ERRMSGDFb_H_\n"
"#define ERRMSGDFb_H_\n";
// emit an enumeration of all the symbolic error codes.
out << "enum error_code {\n";
for (std::vector<Message>::iterator m = messages.begin();
m != messages.end(); ++m) {
if (m->number != -1) {
out << "\n " << m->symbol << " = " << m->number << ",\n";
for (std::vector<std::string>::iterator it = m->lines.begin() + 1;
it != m->lines.end(); ++it)
out << " // " << *it << "\n";
}
}
out << "};\n"
"#endif // ERRMSGDFb_H_\n"
"#endif /* ERRMSG_GET_ERRTXT_TABLE */\n";
return 0;
}
};
/**
* \brief the application's main function.
*
* Create an application class object and invoke its run() method.
*
* \param argc - argument count
* \param argv - array of arguments
*/
int
main(int argc, char *argv[])
{
Errmsg app(argc, argv);
return app.run();
}
| 31.918728 | 80 | 0.579154 |
73c20d2ab7b184acabd3485d0ca0ca8267bb8a70 | 2,751 | hpp | C++ | breeze/debugging/dump_expression.hpp | gennaroprota/breeze | f1dfd7154222ae358f5ece936c2897a3ae110003 | [
"BSD-3-Clause"
] | 1 | 2021-04-03T22:35:52.000Z | 2021-04-03T22:35:52.000Z | breeze/debugging/dump_expression.hpp | gennaroprota/breeze | f1dfd7154222ae358f5ece936c2897a3ae110003 | [
"BSD-3-Clause"
] | null | null | null | breeze/debugging/dump_expression.hpp | gennaroprota/breeze | f1dfd7154222ae358f5ece936c2897a3ae110003 | [
"BSD-3-Clause"
] | 1 | 2021-10-01T04:26:48.000Z | 2021-10-01T04:26:48.000Z | // ===========================================================================
// Copyright 2013 Gennaro Prota
//
// Licensed under the 3-Clause BSD License.
// (See accompanying file 3_CLAUSE_BSD_LICENSE.txt or
// <https://opensource.org/licenses/BSD-3-Clause>.)
// ___________________________________________________________________________
//
//! \file
//! \brief Displays an expression and its value to `std::cout`.
// ---------------------------------------------------------------------------
#ifndef BREEZE_GUARD_v4ifHvyokFutGDGkksKs5kPv6rpDcUGv
#define BREEZE_GUARD_v4ifHvyokFutGDGkksKs5kPv6rpDcUGv
#include "breeze/preprocessing/stringize_after_expansion.hpp"
#include <cstring>
#include <iostream>
#include <ostream> // not necessary in C++11
// BREEZE_DUMP_EXPRESSION()
// ------------------------
//
//! \copybrief dump_expression.hpp
//!
//! \hideinitializer
//!
//! A simple macro for quickly dumping a variable or, generally, an
//! expression to `std::cout`.
//!
//! It was born as "DUMP_VARIABLE" but then I immediately found a
//! usage where I wanted to display something like `i + j`, so I
//! renamed it to "DUMP_EXPRESSION".
//!
//! It's intended that you use this just for quick and dirty checks,
//! and that you *remove* it after that.
//!
//! The expression is shown in the form `<expression> = value`. If
//! `expression` contains macro invocations, the macros are
//! expanded, but the unexpanded form is displayed, too. In any
//! case, the output ends with `std::endl`.
//!
//! \note
//! The `#include`'s are not part of the interface.
// ---------------------------------------------------------------------------
#define BREEZE_DUMP_EXPRESSION( expression ) \
do { \
char const expanded[] = \
BREEZE_STRINGIZE_AFTER_EXPANSION( expression ) ; \
char const unexpanded[] = # expression ; \
std::ostream & os = std::cout ; \
os << expanded << " = " << ( expression ) ; \
if ( std::strcmp( expanded, unexpanded ) != 0 ) { \
os << " [from: " << unexpanded << ']' ; \
} \
os << std::endl ; \
} while ( false ) /**/
#endif
| 45.85 | 78 | 0.455107 |
73c2fd63df7c371a3d3378954583d8eb779433c2 | 10,153 | cpp | C++ | samples/snippets/cpp/VS_Snippets_Misc/NVC_MFC_RebarTest/cpp/MainFrm.cpp | sashang/docs-1 | 8399f7c62a5ed6031ee7c576503cc73c268c09bb | [
"CC-BY-4.0",
"MIT"
] | null | null | null | samples/snippets/cpp/VS_Snippets_Misc/NVC_MFC_RebarTest/cpp/MainFrm.cpp | sashang/docs-1 | 8399f7c62a5ed6031ee7c576503cc73c268c09bb | [
"CC-BY-4.0",
"MIT"
] | 15 | 2022-03-23T00:40:19.000Z | 2022-03-23T00:40:39.000Z | samples/snippets/cpp/VS_Snippets_Misc/NVC_MFC_RebarTest/cpp/MainFrm.cpp | sashang/docs-1 | 8399f7c62a5ed6031ee7c576503cc73c268c09bb | [
"CC-BY-4.0",
"MIT"
] | null | null | null | // This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (C) Microsoft Corporation
// All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.
#include "stdafx.h"
#include "RebarTest.h"
#include "MainFrm.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CMainFrame
IMPLEMENT_DYNAMIC(CMainFrame, CMDIFrameWndEx)
const int iMaxUserToolbars = 10;
const UINT uiFirstUserToolBarId = AFX_IDW_CONTROLBAR_FIRST + 40;
const UINT uiLastUserToolBarId = uiFirstUserToolBarId + iMaxUserToolbars - 1;
BEGIN_MESSAGE_MAP(CMainFrame, CMDIFrameWndEx)
ON_WM_CREATE()
ON_WM_CLOSE()
ON_COMMAND(ID_WINDOW_MANAGER, OnWindowManager)
ON_COMMAND(ID_VIEW_CUSTOMIZE, OnViewCustomize)
ON_REGISTERED_MESSAGE(AFX_WM_RESETTOOLBAR, OnToolbarReset)
ON_COMMAND_RANGE(ID_VIEW_APPLOOK_2000, ID_VIEW_APPLOOK_2007_3, OnAppLook)
ON_UPDATE_COMMAND_UI_RANGE(ID_VIEW_APPLOOK_2000, ID_VIEW_APPLOOK_2007_3, OnUpdateAppLook)
END_MESSAGE_MAP()
static UINT indicators[] =
{
ID_SEPARATOR, // status line indicator
ID_INDICATOR_CAPS,
ID_INDICATOR_NUM,
ID_INDICATOR_SCRL,
};
// CMainFrame construction/destruction
CMainFrame::CMainFrame()
{
m_nAppLook = theApp.GetInt (_T("ApplicationLook"), ID_VIEW_APPLOOK_WIN_XP);
// TODO: add member initialization code here
}
CMainFrame::~CMainFrame()
{
}
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CMDIFrameWndEx::OnCreate(lpCreateStruct) == -1)
return -1;
OnAppLook (m_nAppLook);
// VISUAL_MANAGER
if (CMFCToolBar::GetUserImages () == NULL)
{
// Load toolbar user images:
if (!m_UserImages.Load (_T(".\\UserImages.bmp")))
{
TRACE(_T("Failed to load user images\n"));
}
else
{
CMFCToolBar::SetUserImages (&m_UserImages);
}
}
CMFCToolBar::EnableQuickCustomization ();
// TODO: Define your own basic commands. Be sure, that each pulldown
// menu have at least one basic command.
CList<UINT, UINT> lstBasicCommands;
lstBasicCommands.AddTail (ID_VIEW_TOOLBARS);
lstBasicCommands.AddTail (ID_FILE_NEW);
lstBasicCommands.AddTail (ID_FILE_OPEN);
lstBasicCommands.AddTail (ID_FILE_SAVE);
lstBasicCommands.AddTail (ID_FILE_PRINT);
lstBasicCommands.AddTail (ID_APP_EXIT);
lstBasicCommands.AddTail (ID_EDIT_CUT);
lstBasicCommands.AddTail (ID_EDIT_PASTE);
lstBasicCommands.AddTail (ID_EDIT_UNDO);
lstBasicCommands.AddTail (ID_RECORD_NEXT);
lstBasicCommands.AddTail (ID_RECORD_LAST);
lstBasicCommands.AddTail (ID_APP_ABOUT);
lstBasicCommands.AddTail (ID_VIEW_TOOLBAR);
lstBasicCommands.AddTail (ID_VIEW_CUSTOMIZE);
lstBasicCommands.AddTail (ID_WINDOW_TILE_HORZ);
lstBasicCommands.AddTail (ID_VIEW_APPLOOK_2000);
lstBasicCommands.AddTail (ID_VIEW_APPLOOK_XP);
lstBasicCommands.AddTail (ID_VIEW_APPLOOK_2003);
lstBasicCommands.AddTail (ID_VIEW_APPLOOK_2007);
lstBasicCommands.AddTail (ID_VIEW_APPLOOK_VS2005);
lstBasicCommands.AddTail (ID_VIEW_APPLOOK_WIN_XP);
lstBasicCommands.AddTail (ID_VIEW_APPLOOK_2007_1);
lstBasicCommands.AddTail (ID_VIEW_APPLOOK_2007_2);
lstBasicCommands.AddTail (ID_VIEW_APPLOOK_2007_3);
CMFCToolBar::SetBasicCommands (lstBasicCommands);
if (!m_wndMenuBar.Create (this))
{
TRACE0("Failed to create menubar\n");
return -1; // fail to create
}
m_wndMenuBar.SetPaneStyle(m_wndMenuBar.GetPaneStyle() | CBRS_SIZE_DYNAMIC);
// Remove menubar gripper and borders:
m_wndMenuBar.SetPaneStyle (m_wndMenuBar.GetPaneStyle() &
~(CBRS_GRIPPER | CBRS_BORDER_TOP | CBRS_BORDER_BOTTOM | CBRS_BORDER_LEFT | CBRS_BORDER_RIGHT));
// Detect color depth. 256 color toolbars can be used in the
// high or true color modes only (bits per pixel is > 8):
CClientDC dc (this);
BOOL bIsHighColor = dc.GetDeviceCaps (BITSPIXEL) > 8;
UINT uiToolbarHotID = bIsHighColor ? IDB_TOOLBAR256 : 0;
if (!m_wndToolBar.CreateEx(this) ||
!m_wndToolBar.LoadToolBar(IDR_MAINFRAME, 0, 0, FALSE, 0, 0, uiToolbarHotID))
{
TRACE0("Failed to create toolbar\n");
return -1; // fail to create
}
// <snippet2>
// Each rebar pane will occupy its own row:
DWORD dwStyle = RBBS_GRIPPERALWAYS | RBBS_FIXEDBMP | RBBS_BREAK;
// CMFCMenuBar m_wndMenuBar
// CMFCToolBar m_wndToolBar
if (!m_wndReBar.Create(this) ||
!m_wndReBar.AddBar (&m_wndMenuBar) ||
!m_wndReBar.AddBar (&m_wndToolBar, NULL, NULL, dwStyle))
{
TRACE0("Failed to create rebar\n");
return -1; // fail to create
}
// </snippet2>
m_wndMenuBar.AdjustLayout ();
m_wndToolBar.AdjustLayout ();
// TODO: Remove this if you don't want chevrons:
m_wndMenuBar.EnableCustomizeButton (TRUE, -1, _T(""));
m_wndToolBar.EnableCustomizeButton (TRUE, ID_VIEW_CUSTOMIZE, _T("Customize..."));
EnableDocking(CBRS_ALIGN_ANY);
m_wndReBar.EnableDocking (CBRS_TOP);
DockPane (&m_wndReBar);
if (!m_wndStatusBar.Create(this) ||
!m_wndStatusBar.SetIndicators(indicators,
sizeof(indicators)/sizeof(UINT)))
{
TRACE0("Failed to create status bar\n");
return -1; // fail to create
}
BOOL bValidString;
CString strMainToolbarTitle;
bValidString = strMainToolbarTitle.LoadString (IDS_MAIN_TOOLBAR);
m_wndToolBar.SetWindowText (strMainToolbarTitle);
// TODO: Remove this if you don't want tool tips
m_wndMenuBar.SetPaneStyle(m_wndMenuBar.GetPaneStyle() |
CBRS_TOOLTIPS | CBRS_FLYBY);
m_wndToolBar.SetPaneStyle(m_wndToolBar.GetPaneStyle() |
CBRS_TOOLTIPS | CBRS_FLYBY);
// Enable windows manager:
EnableWindowsDialog (ID_WINDOW_MANAGER, IDS_WINDOWS_MANAGER, TRUE);
// Enable control bar context menu (list of bars + customize command):
EnablePaneMenu (
TRUE, // Enable
ID_VIEW_CUSTOMIZE, // Customize command ID
_T("Customize..."), // Customize command text
ID_VIEW_TOOLBARS); // Menu items with this ID will be replaced by
// toolbars menu
return 0;
}
BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
if( !CMDIFrameWndEx::PreCreateWindow(cs) )
return FALSE;
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return TRUE;
}
// CMainFrame diagnostics
#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
CMDIFrameWndEx::AssertValid();
}
void CMainFrame::Dump(CDumpContext& dc) const
{
CMDIFrameWndEx::Dump(dc);
}
#endif //_DEBUG
// CMainFrame message handlers
void CMainFrame::OnViewCustomize()
{
//------------------------------------
// Create a customize toolbars dialog:
//------------------------------------
CMFCToolBarsCustomizeDialog* pDlgCust = new CMFCToolBarsCustomizeDialog (this,
TRUE /* Automatic menus scaning */);
pDlgCust->EnableUserDefinedToolbars ();
pDlgCust->Create ();
}
afx_msg LRESULT CMainFrame::OnToolbarReset(WPARAM /*wp*/,LPARAM)
{
// TODO: reset toolbar with id = (UINT) wp to its initial state:
//
// UINT uiToolBarId = (UINT) wp;
// if (uiToolBarId == IDR_MAINFRAME)
// {
// do something with m_wndToolBar
// }
return 0;
}
void CMainFrame::OnWindowManager()
{
ShowWindowsDialog ();
}
void CMainFrame::OnAppLook(UINT id)
{
CDockingManager::SetDockingMode (DT_SMART);
m_nAppLook = id;
CTabbedPane::m_StyleTabWnd = CMFCTabCtrl::STYLE_3D;
switch (m_nAppLook)
{
case ID_VIEW_APPLOOK_2000:
// enable Office 2000 look:
CMFCVisualManager::SetDefaultManager (RUNTIME_CLASS (CMFCVisualManager));
break;
case ID_VIEW_APPLOOK_XP:
// enable Office XP look:
CMFCVisualManager::SetDefaultManager (RUNTIME_CLASS (CMFCVisualManagerOfficeXP));
break;
case ID_VIEW_APPLOOK_WIN_XP:
// enable Windows XP look (in other OS Office XP look will be used):
CMFCVisualManagerWindows::m_b3DTabsXPTheme = TRUE;
CMFCVisualManager::SetDefaultManager (RUNTIME_CLASS (CMFCVisualManagerWindows));
break;
case ID_VIEW_APPLOOK_2003:
// enable Office 2003 look:
CMFCVisualManager::SetDefaultManager (RUNTIME_CLASS (CMFCVisualManagerOffice2003));
CDockingManager::SetDockingMode (DT_SMART);
break;
case ID_VIEW_APPLOOK_2007:
case ID_VIEW_APPLOOK_2007_1:
case ID_VIEW_APPLOOK_2007_2:
case ID_VIEW_APPLOOK_2007_3:
// enable Office 2007 look:
switch (m_nAppLook)
{
case ID_VIEW_APPLOOK_2007:
CMFCVisualManagerOffice2007::SetStyle (CMFCVisualManagerOffice2007::Office2007_LunaBlue);
break;
case ID_VIEW_APPLOOK_2007_1:
CMFCVisualManagerOffice2007::SetStyle (CMFCVisualManagerOffice2007::Office2007_ObsidianBlack);
break;
case ID_VIEW_APPLOOK_2007_2:
CMFCVisualManagerOffice2007::SetStyle (CMFCVisualManagerOffice2007::Office2007_Silver);
break;
case ID_VIEW_APPLOOK_2007_3:
CMFCVisualManagerOffice2007::SetStyle (CMFCVisualManagerOffice2007::Office2007_Aqua);
break;
}
CMFCVisualManager::SetDefaultManager (RUNTIME_CLASS (CMFCVisualManagerOffice2007));
CDockingManager::SetDockingMode (DT_SMART);
break;
case ID_VIEW_APPLOOK_VS2005:
// enable VS 2005 look:
CMFCVisualManager::SetDefaultManager (RUNTIME_CLASS (CMFCVisualManagerVS2005));
CDockingManager::SetDockingMode (DT_SMART);
break;
}
CDockingManager* pDockManager = GetDockingManager ();
if (pDockManager != NULL)
{
ASSERT_VALID (pDockManager);
pDockManager->AdjustPaneFrames ();
}
CTabbedPane::ResetTabs ();
RecalcLayout ();
RedrawWindow (NULL, NULL, RDW_ALLCHILDREN | RDW_INVALIDATE | RDW_UPDATENOW | RDW_ERASE);
theApp.WriteInt (_T("ApplicationLook"), m_nAppLook);
}
void CMainFrame::OnUpdateAppLook(CCmdUI* pCmdUI)
{
pCmdUI->SetRadio (m_nAppLook == pCmdUI->m_nID);
}
CMDIChildWndEx* CMainFrame::CreateDocumentWindow (LPCTSTR lpcszDocName, CObject* /*pObj*/)
{
if (lpcszDocName != NULL && lpcszDocName [0] != '\0')
{
CDocument* pDoc = AfxGetApp()->OpenDocumentFile (lpcszDocName);
if (pDoc != NULL)
{
POSITION pos = pDoc->GetFirstViewPosition();
if (pos != NULL)
{
CView* pView = pDoc->GetNextView (pos);
if (pView == NULL)
{
return NULL;
}
return DYNAMIC_DOWNCAST (CMDIChildWndEx, pView->GetParent ());
}
}
}
return NULL;
}
void CMainFrame::OnClose()
{
SaveMDIState (theApp.GetRegSectionPath ());
CMDIFrameWndEx::OnClose();
}
// RIBBON_APP
| 26.578534 | 97 | 0.751699 |
73c35c2ac358da87aa1b59edd3d1c2f9ce8d68f9 | 1,601 | cpp | C++ | src/trainerwrapper.cpp | roloza7/nn-test | 3400e6e065be68858c6ce692d349f3ddb8596033 | [
"MIT"
] | null | null | null | src/trainerwrapper.cpp | roloza7/nn-test | 3400e6e065be68858c6ce692d349f3ddb8596033 | [
"MIT"
] | null | null | null | src/trainerwrapper.cpp | roloza7/nn-test | 3400e6e065be68858c6ce692d349f3ddb8596033 | [
"MIT"
] | null | null | null | #include "trainerwrapper.h"
#ifdef TrainerWrapper
#undef TrainerWrapper
#endif
#ifndef TrainerWrapper_API
#define TrainerWrapper_API TrainerWrapper
#endif
TrainerWrapper_API::TrainerWrapper_API(int n_subjects, int network_size) {
pImpl = new TrainerWrapper_impl(n_subjects, network_size);
}
TrainerWrapper_API::~TrainerWrapper_API() {
delete pImpl;
}
// double** TrainerWrapper_API::AddInputArray(int input_size) {
// return pImpl->AddInputArray(input_size);
// }
// double** TrainerWrapper_API::AddOutputArray(int output_size) {
// return pImpl->AddOutputArray(output_size);
// }
// bool TrainerWrapper_API::CheckStatus() {
// return true;
// }
// void TrainerWrapper_API::Step() {
// pImpl->Step();
// }
// void TrainerWrapper_API::NextGeneration(int winner_id) {
// pImpl->NextGeneration(winner_id);
// }
// TrainerWrapper* TrainerWrapper_Create(int n_subjects, int network_size) {
// return new TrainerWrapper(n_subjects, network_size);
// }
// double** TrainerWrapper_AddInputArray(TrainerWrapper* tw, int input_size) {
// return tw->AddInputArray(input_size);
// }
// double** TrainerWrapper_AddOutputArray(TrainerWrapper* tw, int output_size) {
// return tw->AddOutputArray(output_size);
// }
// void TrainerWrapper_Step(TrainerWrapper* tw) {
// tw->Step();
// }
// void TrainerWrapper_NextGeneration(TrainerWrapper* tw, int winner_id) {
// tw->NextGeneration(winner_id);
// }
// bool TrainerWrapper_CheckStatus(TrainerWrapper* tw) {
// return tw->CheckStatus();
// } | 26.245902 | 81 | 0.695815 |
73c4be390e11a7acd2aec5c9e208abbb026fa126 | 4,687 | cpp | C++ | VAIC_ISU_24/src/map.cpp | wpivex/vaic-v5-20_21 | ee3528ac0c2a0760ff7e15500a3160f297f889c7 | [
"MIT"
] | null | null | null | VAIC_ISU_24/src/map.cpp | wpivex/vaic-v5-20_21 | ee3528ac0c2a0760ff7e15500a3160f297f889c7 | [
"MIT"
] | null | null | null | VAIC_ISU_24/src/map.cpp | wpivex/vaic-v5-20_21 | ee3528ac0c2a0760ff7e15500a3160f297f889c7 | [
"MIT"
] | null | null | null | /*----------------------------------------------------------------------------*/
/* */
/* Module: map.cpp */
/* Author: Jatin */
/* Created: 2/17/21 */
/* Description: Implementation of the map class's methods */
/* */
/*----------------------------------------------------------------------------*/
#include "vex.h"
#include "map.h"
using namespace vex;
using namespace ai;
/*
* Updates the global Map obj declared in vex.h with data from the Jetson and vex link
*/
void updateMapObj(bool printBalls) {
MAP_RECORD mapRecord; // Map from the Jetson
jetson_comms.get_data(&mapRecord);
jetson_comms.request_map();
// get ball data from mapRecord
int numBalls = mapRecord.mapnum;
BallCoord balls[numBalls];
FILE *fp = fopen("/dev/serial2", "w");
for (int i = 0; i < numBalls; i++) {
float x = (mapRecord.mapobj[i].positionX / -25.4);
float y = (mapRecord.mapobj[i].positionY / -25.4);
balls[i] = {mapRecord.mapobj[i].age, mapRecord.mapobj[i].classID, x, y};
if(printBalls) {
switch(mapRecord.mapobj[i].classID) {
case 0:
fprintf(fp, "* Red ");
break;
case 1:
fprintf(fp, "* Blue ");
break;
default:
fprintf(fp, "* Not a ");
break;
}
fprintf(fp, "Ball: %f, %f\n\r", balls[i].x, balls[i].y );
}
}
fflush(fp);
fclose(fp);
map->setBallCoords(balls, numBalls);
// get manager robot data from mapRecord and worker data from vex link coords
RobotCoord robots[2];
int numRobots = 1;
float managerHeading = (float) ((-mapRecord.pos.az - M_PI/2) * 360 / (2 * M_PI));
float managerX = mapRecord.pos.x / -25.4f + POS_OFFSET * cos(managerHeading * M_PI / 180);
float managerY = mapRecord.pos.y / -25.4f + POS_OFFSET * sin(managerHeading * M_PI / 180);
robots[0] = {
0, // manager
managerX, // hopefully in to the right of (0,0), need to test on field
managerY, // hopefully in above of (0,0), need to test on field
managerHeading, // starts at +x and increases counterclockwise, range of (-270 : 90)
24 // 24 in
};
link.set_remote_location(robots[0].x, robots[0].y, robots[0].deg);
if (link.isLinked()) {
float workerX, workerY, workerHeading;
link.get_remote_location(workerX, workerY, workerHeading);
robots[1] = {
1, // worker
workerX, // hopefully in to the right of (0,0), need to test on field
workerY, // hopefully in above of (0,0), need to test on field
workerHeading, // hopefully starts at +x and increases counterclockwise, need to test on field
15 // 15 in
};
numRobots++;
}
map->setRobotCoords(robots, numRobots);
} // updateMapObj()
BallCoord* Map::getBallCoords(void) {
return balls;
}
int Map::getNumBalls(void) {
return numBalls;
}
bool Map::hasBall(int id) {
MAP_RECORD mapRecord; // Map from the Jetson
jetson_comms.get_data(&mapRecord);
jetson_comms.request_map();
for(int i = 0; i < mapRecord.boxnum; i++) {
if(id == mapRecord.boxobj[i].classID)
return true;
}
return false;
}
RobotCoord Map::getManagerCoords(void) {
return manager;
}
RobotCoord Map::getWorkerCoords(void) {
return worker;
}
RobotCoord* Map::getEnemyCoords(void) {
return enemies;
}
int Map::getNumEnemies(void) {
return numEnemies;
}
// void Map::addBallCoord(BallCoord coord) {
// // TODO implement intelligent management of existing elements given new data
// }
// void Map::addRobotCoord(RobotCoord coord) {
// // TODO implement intelligent management of existing elements given new data
// }
void Map::setBallCoords(BallCoord* coords, int numCoords) {
for (int i = 0; i < MAX_BALLS; i++) {
if (i < numCoords)
balls[i] = coords[i];
else
balls[i] = {0, -1, 0, 0};
}
numBalls = numCoords;
}
void Map::setRobotCoords(RobotCoord* coords, int numCoords) {
manager = {-1, 0, 0, 0, 0};
worker = {-1, 0, 0, 0, 0};
for (int i = 0; i < MAX_ENEMIES; i++)
enemies[i] = {-1, 0, 0, 0, 0};
numEnemies = 0;
for (int i = 0; i < numCoords; i++) {
switch(coords[i].robotID) {
case 0:
manager = coords[i];
break;
case 1:
worker = coords[i];
break;
case 2:
if (numEnemies < MAX_ENEMIES)
enemies[numEnemies++] = coords[i];
break;
}
}
} | 27.570588 | 100 | 0.550245 |
73c7b96ac49869e4b4d20e36744795821b96e551 | 228 | cpp | C++ | 2_1_1.cpp | youngjeff/coursera | 8fc25ab04a1c0749fe4f9fd24f170c02db0b1f82 | [
"Apache-2.0"
] | null | null | null | 2_1_1.cpp | youngjeff/coursera | 8fc25ab04a1c0749fe4f9fd24f170c02db0b1f82 | [
"Apache-2.0"
] | null | null | null | 2_1_1.cpp | youngjeff/coursera | 8fc25ab04a1c0749fe4f9fd24f170c02db0b1f82 | [
"Apache-2.0"
] | null | null | null | #include<iostream>
using namespace std;
int main()
{
int N;
cin>>N;
int a[100];
for(int i=0;i<N;i++)
{
cin>>a[i];
}
for(int i=0;i<N;i++)
{
if(a[i] == i)
{
cout<<i;
return 0;
}
}
cout << "N";
return 0;
}
| 9.913043 | 21 | 0.482456 |
73c803497dd0add1806b854d80e19b0e6e6afda1 | 216 | hpp | C++ | dynamic/wrappers/mesh/PottsElement3.cppwg.hpp | jmsgrogan/PyChaste | 48a9863d2c941c71e47ecb72e917b477ba5c1413 | [
"FTL"
] | 6 | 2017-02-04T16:10:53.000Z | 2021-07-01T08:03:16.000Z | dynamic/wrappers/mesh/PottsElement3.cppwg.hpp | jmsgrogan/PyChaste | 48a9863d2c941c71e47ecb72e917b477ba5c1413 | [
"FTL"
] | 6 | 2017-06-22T08:50:41.000Z | 2019-12-15T20:17:29.000Z | dynamic/wrappers/mesh/PottsElement3.cppwg.hpp | jmsgrogan/PyChaste | 48a9863d2c941c71e47ecb72e917b477ba5c1413 | [
"FTL"
] | 3 | 2017-05-15T21:33:58.000Z | 2019-10-27T21:43:07.000Z | #ifndef PottsElement3_hpp__pyplusplus_wrapper
#define PottsElement3_hpp__pyplusplus_wrapper
namespace py = pybind11;
void register_PottsElement3_class(py::module &m);
#endif // PottsElement3_hpp__pyplusplus_wrapper
| 30.857143 | 49 | 0.87037 |
73c88cb87b8bda75ea13212b26c55f84bb6cb392 | 6,528 | cpp | C++ | OpenSeesParser.cpp | fmckenna/EE-UQ | a1fe96fd000aec933430bda5829c82b5743338c3 | [
"BSD-2-Clause"
] | 1 | 2019-04-30T19:38:17.000Z | 2019-04-30T19:38:17.000Z | OpenSeesParser.cpp | s-m-amin-ghasemi/EE-UQ | 7eb42d09b59b42fd1256c6d8693cfe46e0b8034b | [
"BSD-2-Clause"
] | 2 | 2018-09-11T01:32:27.000Z | 2018-09-11T23:08:06.000Z | OpenSeesParser.cpp | s-m-amin-ghasemi/EE-UQ | 7eb42d09b59b42fd1256c6d8693cfe46e0b8034b | [
"BSD-2-Clause"
] | 6 | 2018-05-14T21:45:24.000Z | 2018-10-04T18:13:42.000Z |
/* *****************************************************************************
Copyright (c) 2016-2017, The Regents of the University of California (Regents).
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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS
PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*************************************************************************** */
// Written: fmckenna
// Purpose: to present a widget for OpenSees,
// 1) to open feap input files, to parse for any parameters that have been set WITH THE PSET command
// and then to return the variablename and values in a string. These are used to init the random variable widget.
// 2) for dakota to again open and parse the input file, this time replacing any input parameters
// with the needed dakota input format: pset varName {varName}
#include <OpenSeesParser.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <regex>
#include <iterator>
#include <string>
#include <QDebug>
using namespace std;
OpenSeesParser::OpenSeesParser()
{
}
OpenSeesParser::~OpenSeesParser()
{
}
QStringList
OpenSeesParser::getVariables(QString inFilename)
{
QStringList result;
ifstream inFile(inFilename.toStdString());
// read lines of input searching for pset using regular expression
regex pset("pset[ ]+[A-Z_a-z0-9]+[ ]+[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?");
string line;
while (getline(inFile, line)) {
if (regex_search(line, pset)) {
// if comment ignore .. c++ regex cannot deal with lookahead .. ugly code results for now
bool commented = false;
std::string comment("#");
std::size_t foundC = line.find(comment);
if (foundC != std::string::npos) {
std::string p("pset");
std::size_t foundP = line.find(p);
if (foundC < foundP)
commented = true;
}
if (commented == false) {
// if found break into cmd, varName and value (ignore the rest)
istringstream iss(line);
string cmd, varName, value;
iss >> cmd >> varName >> value;
// strip possible ; from end of value (possible if comment) line
regex delim(";");
value = regex_replace(value,delim,"");
// add varName and value to results
result.append(QString::fromStdString(varName));
result.append(QString::fromStdString(value));
}
}
}
// close file
inFile.close();
return result;
}
void
OpenSeesParser::writeFile(QString inFilename, QString outFilename, QStringList varToChange)
{
qDebug() << "OpenSeesParser::writeFile: " << inFilename << " out: " << outFilename << " args: " << varToChange;
ifstream inFile(inFilename.toStdString());
ofstream outFile(outFilename.toStdString());
// read lines of input searching for pset using regular expression
regex pset("pset[ ]+[A-Z_a-z0-9]+[ ]+");
string line;
while (getline(inFile, line)) {
if (regex_search(line, pset)) {
// if comment ignore .. c++ regex cannot deal with lookahead .. ugly code results for now
bool commented = false;
std::string comment("#");
std::size_t foundC = line.find(comment);
if (foundC != std::string::npos) {
std::string p("pset");
std::size_t foundP = line.find(p);
if (foundC < foundP)
commented = true;
}
if (commented == false) {
// if found break into cmd, varName and value (ignore the rest)
istringstream iss(line);
string cmd, varName, value;
iss >> cmd >> varName >> value;
// if varName in input sting list, modify line otherwise write current line
QString val1(QString::fromStdString(varName));
if (varToChange.contains(val1)) {
/****drpero cannot handle {} in tcl syntax .. comment out line now instead - python script source new file! ***
// strip possible ; from end of value (possible if comment) line
regex delim(";");
value = regex_replace(value,delim,"");
// write new line format to output
outFile << "pset " << varName << " \{" << varName << "\}\n";
********************************************************************************/
outFile << "#" << line << "\n";
// std::cerr<< "#" << line << "\n";
} else {
// not there, write current line
outFile << line << "\n";
}
}
} else
// just copy line to output
outFile << line << "\n";
}
// close file
inFile.close();
outFile.close();
}
| 36.674157 | 127 | 0.620251 |
73c8afcec42a3d286bf261dd98130ed029e0ff26 | 5,841 | cpp | C++ | FlighterSerrisBertament/FlighterSerrisBertament/Application.cpp | lkstc112233/FlighterSerrisBertament | aa667f799f96c535148bbc7975b337c7b8419816 | [
"MIT"
] | null | null | null | FlighterSerrisBertament/FlighterSerrisBertament/Application.cpp | lkstc112233/FlighterSerrisBertament | aa667f799f96c535148bbc7975b337c7b8419816 | [
"MIT"
] | null | null | null | FlighterSerrisBertament/FlighterSerrisBertament/Application.cpp | lkstc112233/FlighterSerrisBertament | aa667f799f96c535148bbc7975b337c7b8419816 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include <random>
#include <string>
#include "Application.h"
#include "utility.h"
#pragma comment(lib, "d2d1")
#pragma comment(lib, "Dwrite")
Application::Application() : m_hwnd(NULL), fps(0) {
mouse = std::make_shared<Mouse>();
std::default_random_engine randomEngine;
std::uniform_real_distribution<float> positionDistribution(0, 500);
for (int i = 0; i < 100; ++i) {
auto dot = mouseDots.addDot(std::make_shared<MouseDots>(
mouse, mouseDots, positionDistribution(randomEngine),
positionDistribution(randomEngine)));
spriteManager.addSprite(dot->getSprite());
}
}
Application::~Application() {}
void Application::RunMessageLoop() {
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
HRESULT Application::Initialize() {
HRESULT hr;
// Initialize device-indpendent resources, such
// as the Direct2D factory.
hr = CreateDeviceIndependentResources();
if (SUCCEEDED(hr)) {
const char *WINDOW_CLASS_NAME = "D2DDemoApplication";
const char *WINDOW_DEFAULT_TITLE = "Direct2D Practice";
// Register the window class.
WNDCLASSEX wcex = {sizeof(WNDCLASSEX)};
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = Application::WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = sizeof(LONG_PTR);
wcex.hInstance = HINST_THISCOMPONENT;
wcex.hbrBackground = NULL;
wcex.lpszMenuName = NULL;
wcex.hCursor = LoadCursor(NULL, IDI_APPLICATION);
wcex.lpszClassName = WINDOW_CLASS_NAME;
RegisterClassEx(&wcex);
// Because the CreateWindow function takes its size in pixels,
// obtain the system DPI and use it to scale the window size.
FLOAT dpiX, dpiY;
// The factory returns the current system DPI. This is also the value it
// will use to create its own windows.
deviceIndependentResources->getDirect2dFactory()->GetDesktopDpi(&dpiX,
&dpiY);
// Create the window.
m_hwnd = CreateWindow(WINDOW_CLASS_NAME, WINDOW_DEFAULT_TITLE,
WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT,
static_cast<UINT>(ceil(640.f * dpiX / 96.f)),
static_cast<UINT>(ceil(480.f * dpiY / 96.f)), NULL,
NULL, HINST_THISCOMPONENT, this);
hr = m_hwnd ? S_OK : E_FAIL;
if (SUCCEEDED(hr)) {
ShowWindow(m_hwnd, SW_SHOWNORMAL);
UpdateWindow(m_hwnd);
}
}
return hr;
}
HRESULT Application::CreateDeviceIndependentResources() {
HRESULT hr = S_OK;
deviceIndependentResources = std::make_unique<DeviceIndependentResources>();
return hr;
}
HRESULT Application::CreateDeviceResources() {
HRESULT hr = S_OK;
if (!deviceResources) {
deviceResources =
std::make_unique<DeviceResources>(m_hwnd, *deviceIndependentResources);
}
return hr;
}
void Application::DiscardDeviceResources() { deviceResources.reset(); }
HRESULT Application::OnRender() {
static const WCHAR msc_fontName[] = L"Verdana";
static const FLOAT msc_fontSize = 20;
HRESULT hr = S_OK;
hr = CreateDeviceResources();
if (deviceResources->isValid()) {
static const WCHAR sc_helloWorld[] = L"Hello, World!";
auto renderTarget = deviceResources->getRenderTarget();
renderTarget->BeginDraw();
renderTarget->SetTransform(D2D1::Matrix3x2F::Identity());
renderTarget->Clear(D2D1::ColorF(D2D1::ColorF::White));
D2D1_SIZE_F rtSize = renderTarget->GetSize();
// Draw a grid background.
int width = static_cast<int>(rtSize.width);
int height = static_cast<int>(rtSize.height);
for (int x = 0; x < width; x += 10) {
renderTarget->DrawLine(
D2D1::Point2F(static_cast<FLOAT>(x), 0.0f),
D2D1::Point2F(static_cast<FLOAT>(x), rtSize.height),
deviceResources->getLightSlateGrayBrush(), 0.5f);
}
for (int y = 0; y < height; y += 10) {
renderTarget->DrawLine(D2D1::Point2F(0.0f, static_cast<FLOAT>(y)),
D2D1::Point2F(rtSize.width, static_cast<FLOAT>(y)),
deviceResources->getLightSlateGrayBrush(), 0.5f);
}
// Draw two rectangles.
D2D1_RECT_F rectangle1 =
D2D1::RectF(rtSize.width / 2 - 50.0f, rtSize.height / 2 - 50.0f,
rtSize.width / 2 + 50.0f, rtSize.height / 2 + 50.0f);
D2D1_RECT_F rectangle2 =
D2D1::RectF(rtSize.width / 2 - 100.0f, rtSize.height / 2 - 100.0f,
rtSize.width / 2 + 100.0f, rtSize.height / 2 + 100.0f);
spriteManager.draw(*deviceResources);
// Draw a filled rectangle.
renderTarget->FillRectangle(&rectangle1,
deviceResources->getLightSlateGrayBrush());
// Draw the outline of a rectangle.
renderTarget->DrawRectangle(&rectangle2,
deviceResources->getCornflowerBlueBrush());
std::wstring timeString = L"FPS: " + std::to_wstring(fps);
renderTarget->DrawText(
timeString.c_str(), timeString.size(),
deviceIndependentResources->getTextFormat(msc_fontName, msc_fontSize),
D2D1::RectF(0, 0, rtSize.width, rtSize.height),
deviceResources->getBlackBrush());
hr = renderTarget->EndDraw();
}
if (hr == D2DERR_RECREATE_TARGET) {
hr = S_OK;
DiscardDeviceResources();
}
return hr;
}
void Application::OnResize(UINT width, UINT height) {
if (deviceResources) {
// Note: This method can fail, but it's okay to ignore the
// error here, because the error will be returned again
// the next time EndDraw is called.
deviceResources->getRenderTarget()->Resize(D2D1::SizeU(width, height));
}
}
void Application::update() {
mouseDots.update(0.1F);
spriteManager.update();
}
| 30.264249 | 80 | 0.649033 |
73c8b0cdf0697dc2df99d8caf25bec80359fc3e0 | 2,567 | cpp | C++ | tree/medium/173.BinarySearchTreeIterator.cpp | XiaotaoGuo/Leetcode-Solution-In-Cpp | 8e01e35c742a7afb0c8cdd228a6a5e564375434e | [
"Apache-2.0"
] | null | null | null | tree/medium/173.BinarySearchTreeIterator.cpp | XiaotaoGuo/Leetcode-Solution-In-Cpp | 8e01e35c742a7afb0c8cdd228a6a5e564375434e | [
"Apache-2.0"
] | null | null | null | tree/medium/173.BinarySearchTreeIterator.cpp | XiaotaoGuo/Leetcode-Solution-In-Cpp | 8e01e35c742a7afb0c8cdd228a6a5e564375434e | [
"Apache-2.0"
] | null | null | null | /*
* @lc app=leetcode id=173 lang=cpp
*
* [173] Binary Search Tree Iterator
*
* https://leetcode.com/problems/binary-search-tree-iterator/description/
*
* algorithms
* Medium (57.87%)
* Likes: 2998
* Dislikes: 285
* Total Accepted: 347.9K
* Total Submissions: 599.5K
* Testcase Example:
'["BSTIterator","next","next","hasNext","next","hasNext","next","hasNext","next","hasNext"]\n'
+
'[[[7,3,15,null,null,9,20]],[null],[null],[null],[null],[null],[null],[null],[null],[null]]'
*
* Implement an iterator over a binary search tree (BST). Your iterator will be
* initialized with the root node of a BST.
*
* Calling next() will return the next smallest number in the BST.
*
*
*
*
*
*
* Example:
*
*
*
*
* BSTIterator iterator = new BSTIterator(root);
* iterator.next(); // return 3
* iterator.next(); // return 7
* iterator.hasNext(); // return true
* iterator.next(); // return 9
* iterator.hasNext(); // return true
* iterator.next(); // return 15
* iterator.hasNext(); // return true
* iterator.next(); // return 20
* iterator.hasNext(); // return false
*
*
*
*
* Note:
*
*
* next() and hasNext() should run in average O(1) time and uses O(h) memory,
* where h is the height of the tree.
* You may assume that next() call will always be valid, that is, there will be
* at least a next smallest number in the BST when next() is called.
*
*
*/
// @lc code=start
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
* right(right) {}
* };
*/
#include <queue>
class BSTIterator {
public:
BSTIterator(TreeNode* root) { dfs(root); }
/** @return the next smallest number */
int next() {
int val = node_list.front();
node_list.pop();
return val;
}
/** @return whether we have a next smallest number */
bool hasNext() { return !node_list.empty(); }
private:
std::queue<int> node_list;
private:
void dfs(TreeNode* node) {
if (node == nullptr) return;
dfs(node->left);
node_list.push(node->val);
dfs(node->right);
}
};
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator* obj = new BSTIterator(root);
* int param_1 = obj->next();
* bool param_2 = obj->hasNext();
*/
// @lc code=end
| 23.990654 | 95 | 0.609661 |
73ca25d498b6dcf5c52c1a246fe269a47609b4af | 3,357 | cpp | C++ | src/PhyloAcc-GT/profile.cpp | gwct/PhyloAcc | 089162e2bce5a17b95d71add074bf51bccc8a266 | [
"MIT"
] | null | null | null | src/PhyloAcc-GT/profile.cpp | gwct/PhyloAcc | 089162e2bce5a17b95d71add074bf51bccc8a266 | [
"MIT"
] | null | null | null | src/PhyloAcc-GT/profile.cpp | gwct/PhyloAcc | 089162e2bce5a17b95d71add074bf51bccc8a266 | [
"MIT"
] | null | null | null | #include "profile.h"
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cstring>
#include <vector>
#include <map>
#include <cassert>
#include "utils.h"
using namespace std;
// load the phylogenetic profile
PhyloProf LoadPhyloProfiles(string profile_path, string segment_path, string segment_ID)
{
PhyloProf prof;
vector<string> seqs;
prof.G=0;
string linestr;
ifstream in_prof(profile_path.c_str());
if (!in_prof)
{
cerr << "(Error. Cannot open the phylogenetic profile input file: " << profile_path << ")" << endl;
exit(1);
}
// count the num of species, base pairs and load the profiles
string wholeline="";
while(!in_prof.eof())
{
std::getline(in_prof, linestr);
linestr = strutils::trim(linestr);
if(!strncmp(linestr.c_str(),">", 1)) { //return 0 if 1st char of linestr is >.
string tmp = strutils::trim(linestr.substr(1));
prof.species_names.push_back(tmp);
if(prof.G==0) prof.G = wholeline.length();
else assert(wholeline.length() == prof.G);
if(prof.G>0) {
wholeline =strutils::ToLowerCase(wholeline);
prof.X.push_back(wholeline);
}
wholeline = "";
}
else {
wholeline += linestr;
}
}
if(prof.G==0) prof.G = wholeline.length();
wholeline =strutils::ToLowerCase(wholeline);
prof.X.push_back(wholeline);
prof.S = prof.species_names.size();
//read in segment size and specific scaling factor
ifstream in_segment(segment_path.c_str());
if (!in_segment)
{
cerr << "(Error. Cannot open the segment input file: " << segment_path << ")" << endl;
exit(1);
}
while(!in_segment.eof())
{
std::getline(in_segment, linestr);
linestr = strutils::trim(linestr);
vector<string> line_splits = strutils::split(linestr, '\t');
if(line_splits.size()<3) break;
prof.element_names.push_back(line_splits[0]);
double* tmp = new double[3];
//vector<double> tmp=vector<double>(2,0.0);
tmp[0] = atoi(line_splits[1].c_str());
tmp[1] = atoi(line_splits[2].c_str());
//tmp[2] = atof(line_splits[4].c_str()); //add null scale!!
prof.element_pos.push_back(tmp);
if(line_splits.size() >=8) prof.element_tree.push_back(line_splits[7]);
}
prof.C = prof.element_names.size();
in_segment.close();
// read in ID
if (segment_ID != "")
{
string segment_path2 = segment_ID + ".txt";
in_segment.open(segment_path2.c_str());
if (!in_segment)
{
cerr << "(Error. Cannot open the segment input txt file: " << segment_path2 << ")" << endl;
exit(1);
}
while (!in_segment.eof())
{
std::getline(in_segment, linestr);
linestr = strutils::trim(linestr);
if (linestr == "")
continue;
//vector<string> line_splits = strutils::split(linestr, '\t');
//if(line_splits.size()<3) break;
prof.element_id.push_back(linestr);
}
}
in_segment.close();
return prof;
}
| 27.975 | 107 | 0.563003 |
73ca3792a03420a375b91425d40f8015d5fd3bb8 | 2,922 | cpp | C++ | cpp/cpp/721. Accounts Merge.cpp | longwangjhu/LeetCode | a5c33e8d67e67aedcd439953d96ac7f443e2817b | [
"MIT"
] | 3 | 2021-08-07T07:01:34.000Z | 2021-08-07T07:03:02.000Z | cpp/cpp/721. Accounts Merge.cpp | longwangjhu/LeetCode | a5c33e8d67e67aedcd439953d96ac7f443e2817b | [
"MIT"
] | null | null | null | cpp/cpp/721. Accounts Merge.cpp | longwangjhu/LeetCode | a5c33e8d67e67aedcd439953d96ac7f443e2817b | [
"MIT"
] | null | null | null | // https://leetcode.com/problems/accounts-merge/
// Given a list of accounts where each element accounts[i] is a list of strings,
// where the first element accounts[i][0] is a name, and the rest of the elements
// are emails representing emails of the account.
// Now, we would like to merge these accounts. Two accounts definitely belong to
// the same person if there is some common email to both accounts. Note that even
// if two accounts have the same name, they may belong to different people as
// people could have the same name. A person can have any number of accounts
// initially, but all of their accounts definitely have the same name.
// After merging the accounts, return the accounts in the following format: the
// first element of each account is the name, and the rest of the elements are
// emails in sorted order. The accounts themselves can be returned in any order.
////////////////////////////////////////////////////////////////////////////////
// union find -> node: email
// parents[email] = email; owner[email] = name
// map parents[email] -> id to distinguish identical names
// sort before return
class Solution {
public:
vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {
for (auto& account : accounts) {
string name = account[0];
for (int i = 1; i < account.size(); ++i) {
string email = account[i];
owners[email] = name;
if (parents.find(email) == parents.end()) {
parents[email] = email; ranks[email] = 1;
}
unionEmails(account[1], email);
}
}
// ids[root emails] = number
unordered_map<string, int> ids;
for (auto& [email, _] : parents) {
string parent = find(email);
if (ids.find(parent) == ids.end()) { // new parent
int sz = ids.size();
ids[parent] = sz;
}
}
vector<vector<string>> ans(ids.size());
for (auto& [email, parent] : parents) { // loop over every email
int id = ids[parent];
if (ans[id].empty()) ans[id].push_back(owners[parent]);
ans[id].push_back(email);
}
// sort
for (auto& account : ans) {
sort(account.begin() + 1, account.end());
}
return ans;
}
private:
unordered_map<string, string> parents, owners;
unordered_map<string, int> ranks;
string find(string e) {
if (parents[e] != e) parents[e] = find(parents[e]);
return parents[e];
}
void unionEmails(string e1, string e2) {
string p1 = find(e1), p2 = find(e2);
if (p1 == p2) return;
if (ranks[p1] < ranks[p2]) parents[p1] = p2;
else {
if (ranks[p1] == ranks[p2]) ++ranks[p1];
parents[p2] = p1;
}
}
};
| 37.948052 | 81 | 0.562628 |
73ca49245ff62774ee448f2ccb2a5973bf018a42 | 2,029 | cpp | C++ | oneflow/user/kernels/generate_random_batch_permutation_indices_kernel.cpp | wangyuyue/oneflow | 0a71c22fe8355392acc8dc0e301589faee4c4832 | [
"Apache-2.0"
] | 3,285 | 2020-07-31T05:51:22.000Z | 2022-03-31T15:20:16.000Z | oneflow/user/kernels/generate_random_batch_permutation_indices_kernel.cpp | duijiudanggecl/oneflow | d2096ae14cf847509394a3b717021e2bd1d72f62 | [
"Apache-2.0"
] | 2,417 | 2020-07-31T06:28:58.000Z | 2022-03-31T23:04:14.000Z | oneflow/user/kernels/generate_random_batch_permutation_indices_kernel.cpp | duijiudanggecl/oneflow | d2096ae14cf847509394a3b717021e2bd1d72f62 | [
"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 <cstdint>
#include "oneflow/core/framework/framework.h"
#include "oneflow/core/kernel/new_kernel_util.h"
#include "oneflow/user/kernels/op_kernel_state_wrapper.h"
namespace oneflow {
class GenerateRandomBatchPermutationIndicesCPUKernel final : public user_op::OpKernel {
public:
GenerateRandomBatchPermutationIndicesCPUKernel() = default;
~GenerateRandomBatchPermutationIndicesCPUKernel() = default;
std::shared_ptr<user_op::OpKernelState> CreateOpKernelState(
user_op::KernelInitContext* ctx) const override {
int64_t seed = ctx->Attr<int64_t>("seed");
return std::make_shared<OpKernelStateWrapper<std::mt19937>>(seed);
}
private:
void Compute(user_op::KernelComputeContext* ctx, user_op::OpKernelState* state) const override {
auto* random_generator = dynamic_cast<OpKernelStateWrapper<std::mt19937>*>(state);
user_op::Tensor* y = ctx->Tensor4ArgNameAndIndex("y", 0);
std::iota(y->mut_dptr<int32_t>(), y->mut_dptr<int32_t>() + y->shape().elem_cnt(), 0);
std::shuffle(y->mut_dptr<int32_t>(), y->mut_dptr<int32_t>() + y->shape().elem_cnt(),
*random_generator->Mutable());
}
bool AlwaysComputeWhenAllOutputsEmpty() const override { return false; }
};
REGISTER_USER_KERNEL("generate_random_batch_permutation_indices")
.SetCreateFn<GenerateRandomBatchPermutationIndicesCPUKernel>()
.SetIsMatchedHob(user_op::HobDeviceTag() == "cpu");
} // namespace oneflow
| 40.58 | 98 | 0.759487 |
73ca79e05c8b1bf5d9bcf8f7cf628d550a210566 | 4,558 | cc | C++ | mindspore/lite/src/runtime/kernel/arm/string/predict.cc | ZLkanyo009/mindspore | 0a6ed86bb443ed233504fa7eee931a24637d50bb | [
"Apache-2.0"
] | 2 | 2021-07-08T13:10:42.000Z | 2021-11-08T02:48:57.000Z | mindspore/lite/src/runtime/kernel/arm/string/predict.cc | peixinhou/mindspore | fcb2ec2779b753e95c762cf292b23bd81d1f561b | [
"Apache-2.0"
] | null | null | null | mindspore/lite/src/runtime/kernel/arm/string/predict.cc | peixinhou/mindspore | fcb2ec2779b753e95c762cf292b23bd81d1f561b | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2020 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/runtime/kernel/arm/string/predict.h"
#include <string>
#include <algorithm>
#include "src/kernel_registry.h"
using mindspore::lite::KernelRegistrar;
using mindspore::lite::RET_ERROR;
using mindspore::lite::RET_OK;
using mindspore::schema::PrimitiveType_CustomPredict;
namespace mindspore::kernel {
int PredictCPUKernel::Init() {
if (!InferShapeDone()) {
return RET_OK;
}
return ReSize();
}
int PredictCPUKernel::ReSize() { return RET_OK; }
std::vector<LabelInfo> PredictCPUKernel::GetLabelInfo() {
std::vector<LabelInfo> label_info_vec;
auto input_tensor = in_tensors_.at(0);
auto keys_tensor = in_tensors_.at(1);
auto labels_tensor = in_tensors_.at(2);
auto weights_tensor = in_tensors_.at(3);
int32_t *input = reinterpret_cast<int32_t *>(input_tensor->MutableData());
int32_t *key_begin = reinterpret_cast<int32_t *>(keys_tensor->MutableData());
int32_t *key_end = key_begin + keys_tensor->ElementsNum();
int32_t *labels = reinterpret_cast<int32_t *>(labels_tensor->MutableData());
float *weights = reinterpret_cast<float *>(weights_tensor->MutableData());
int32_t input_elements_num = input_tensor->ElementsNum();
int32_t items = labels_tensor->shape().at(1);
for (int i = 0; i < input_elements_num; i++) {
int *p = std::lower_bound(key_begin, key_end, input[i]);
if (p == nullptr || p == key_end || *p != input[i]) {
continue;
}
int index = p - key_begin;
for (int j = 0; j < items; j++) {
int offset = index * items + j;
auto it = std::find_if(label_info_vec.begin(), label_info_vec.end(),
[&](const LabelInfo &element) { return element.label == labels[offset]; });
if (it != label_info_vec.end()) {
it->weight += weights[offset] / input_elements_num;
} else {
LabelInfo tmp = {labels[offset], weights[offset] / input_elements_num};
label_info_vec.push_back(tmp);
}
}
}
return label_info_vec;
}
static bool LabelInfoCmp(const LabelInfo &lhs, const LabelInfo &rhs) { return lhs.weight > rhs.weight; }
int PredictCPUKernel::Run() {
std::vector<LabelInfo> label_info_vec = GetLabelInfo();
std::sort(label_info_vec.begin(), label_info_vec.end(), LabelInfoCmp);
auto output_label_tensor = out_tensors_.at(0);
auto output_weight_tensor = out_tensors_.at(1);
auto output_label = reinterpret_cast<int32_t *>(output_label_tensor->MutableData());
auto output_weight = reinterpret_cast<float *>(output_weight_tensor->MutableData());
auto param = reinterpret_cast<PredictParameter *>(op_parameter_);
for (int i = 0; i < output_label_tensor->ElementsNum(); i++) {
if (static_cast<size_t>(i) >= label_info_vec.size() || label_info_vec[i].weight < param->weight_threshold) {
output_label[i] = -1;
output_weight[i] = 0.0f;
} else {
output_label[i] = label_info_vec[i].label;
output_weight[i] = label_info_vec[i].weight;
}
}
return RET_OK;
}
kernel::LiteKernel *CpuPredictKernelCreator(const std::vector<lite::Tensor *> &inputs,
const std::vector<lite::Tensor *> &outputs, OpParameter *parameter,
const lite::Context *ctx, const kernel::KernelKey &desc) {
auto *kernel =
new (std::nothrow) PredictCPUKernel(parameter, inputs, outputs, static_cast<const lite::InnerContext *>(ctx));
if (kernel == nullptr) {
MS_LOG(ERROR) << "new PredictCPUKernel fail!";
free(parameter);
return nullptr;
}
auto ret = kernel->Init();
if (ret != RET_OK) {
MS_LOG(ERROR) << "Init kernel failed, name: " << parameter->name_
<< ", type: " << schema::EnumNamePrimitiveType(static_cast<schema::PrimitiveType>(parameter->type_));
delete kernel;
return nullptr;
}
return kernel;
}
REG_KERNEL(kCPU, kNumberTypeInt32, PrimitiveType_CustomPredict, CpuPredictKernelCreator)
} // namespace mindspore::kernel
| 38.627119 | 119 | 0.683414 |
73cb633f5fa1a764c122a608cc4757ef3cd2d568 | 2,001 | hpp | C++ | hpx/runtime/components/server/preprocessed/runtime_support_create_component_capabilities.hpp | andreasbuhr/hpx | 4366a90aacbd3e95428a94ab24a1646a67459cc2 | [
"BSL-1.0"
] | null | null | null | hpx/runtime/components/server/preprocessed/runtime_support_create_component_capabilities.hpp | andreasbuhr/hpx | 4366a90aacbd3e95428a94ab24a1646a67459cc2 | [
"BSL-1.0"
] | null | null | null | hpx/runtime/components/server/preprocessed/runtime_support_create_component_capabilities.hpp | andreasbuhr/hpx | 4366a90aacbd3e95428a94ab24a1646a67459cc2 | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2007-2013 Hartmut Kaiser
// Copyright (c) 2012-2013 Thomas Heller
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#if !defined(HPX_PREPROCESSED_RUNTIME_COMPONENTS_SERVER_RUNTIME_SUPPORT_CREATE_COMPONENT_CAPABILITIES_HPP)
#define HPX_PREPROCESSED_RUNTIME_COMPONENTS_SERVER_RUNTIME_SUPPORT_CREATE_COMPONENT_CAPABILITIES_HPP
#if HPX_ACTION_ARGUMENT_LIMIT <= 5
#include <hpx/runtime/components/server/preprocessed/runtime_support_create_component_capabilities_5.hpp>
#elif HPX_ACTION_ARGUMENT_LIMIT <= 10
#include <hpx/runtime/components/server/preprocessed/runtime_support_create_component_capabilities_10.hpp>
#elif HPX_ACTION_ARGUMENT_LIMIT <= 15
#include <hpx/runtime/components/server/preprocessed/runtime_support_create_component_capabilities_15.hpp>
#elif HPX_ACTION_ARGUMENT_LIMIT <= 20
#include <hpx/runtime/components/server/preprocessed/runtime_support_create_component_capabilities_20.hpp>
/*
#elif HPX_ACTION_ARGUMENT_LIMIT <= 25
#include <hpx/runtime/components/server/preprocessed/runtime_support_create_component_capabilities_25.hpp>
#elif HPX_ACTION_ARGUMENT_LIMIT <= 30
#include <hpx/runtime/components/server/preprocessed/runtime_support_create_component_capabilities_30.hpp>
#elif HPX_ACTION_ARGUMENT_LIMIT <= 35
#include <hpx/runtime/components/server/preprocessed/runtime_support_create_component_capabilities_35.hpp>
#elif HPX_ACTION_ARGUMENT_LIMIT <= 40
#include <hpx/runtime/components/server/preprocessed/runtime_support_create_component_capabilities_40.hpp>
#elif HPX_ACTION_ARGUMENT_LIMIT <= 45
#include <hpx/runtime/components/server/preprocessed/runtime_support_create_component_capabilities_45.hpp>
#elif HPX_ACTION_ARGUMENT_LIMIT <= 50
#include <hpx/runtime/components/server/preprocessed/runtime_support_create_component_capabilities_50.hpp>
*/
#else
#error "HPX_ACTION_ARGUMENT_LIMIT out of bounds for preprocessed headers"
#endif
#endif
| 54.081081 | 106 | 0.86007 |
73cc4087180868f033aaa43bc7724e5ad04010e0 | 3,341 | cpp | C++ | AudioSynthesis/Audio/loop.cpp | eliasrm87/AudioSynthesisQt | feb05c74d85494300d0fca868a37015042ec74c8 | [
"Unlicense"
] | 1 | 2021-09-03T11:06:45.000Z | 2021-09-03T11:06:45.000Z | AudioSynthesis/Audio/loop.cpp | eliasrm87/AudioSynthesisQt | feb05c74d85494300d0fca868a37015042ec74c8 | [
"Unlicense"
] | null | null | null | AudioSynthesis/Audio/loop.cpp | eliasrm87/AudioSynthesisQt | feb05c74d85494300d0fca868a37015042ec74c8 | [
"Unlicense"
] | 2 | 2021-09-03T11:06:53.000Z | 2021-09-03T11:07:25.000Z | #include <QDebug>
#include <QJsonArray>
#include "loop.h"
Loop::Loop(QJsonObject *params, QObject *parent) :
Source("Loop", params, parent)
{
//Path
path_ = params_->value("path").toString("");
//Parts
QJsonArray parts = params_->value("parts").toArray();
foreach (QJsonValue part, parts) {
parts_.push_back(part.toString().toULongLong());
}
if (parts_.isEmpty()) {
addPart(0);
} else {
qSort(parts_);
}
}
Loop::Loop(const Loop &loop) :
Source(loop)
{
path_ = loop.path_;
parts_ = loop.parts_;
}
Loop::~Loop()
{
}
const SamplesVector &Loop::getSamples()
{
return Source::getSamples();
}
void Loop::getSamples(SamplesVector &dest, const qint32 &size)
{
QMutexLocker mtxLock(&mtx_);
if (!synthesized_) {
synthesized_ = true;
synthesize();
}
dest.clear();
int currentBeat, nextBeat;
quint32 beatLength, beatPos;
{
QMutexLocker staticVarsMtxLoc(staticVarsMtx_);
currentBeat = (samplesClock_ / beatLength_) % parts_.size();
nextBeat = (currentBeat + 1) % parts_.size();
beatPos = samplesClock_ % beatLength_;
pos_ = parts_[currentBeat] + beatPos;
beatLength = beatLength_;
}
qint32 remSize = size;
qint32 mSize, remBeat;
qint32 available;
while (remSize > 0) {
remBeat = beatLength - beatPos;
if (remSize > remBeat) {
mSize = remBeat;
} else {
mSize = remSize;
}
if (nextBeat == 0) {
available = samplesBuffer_.size() - pos_;
} else {
available = parts_[nextBeat] - pos_;
}
if (available < 0) {
available = 0;
} else if (available > remBeat) {
available = remBeat;
}
if (mSize > available) {
dest.append(samplesBuffer_.mid(pos_, available));
SamplesVector filling;
filling.fill(0, mSize - available);
dest.append(filling);
} else {
dest.append(samplesBuffer_.mid(pos_, mSize));
}
pos_ += mSize;
remSize -= mSize;
nextBeat = (currentBeat + 1) % parts_.size();
}
}
QString Loop::path() const
{
return path_;
}
void Loop::setPath(const QString &path)
{
QMutexLocker mtxLock(&mtx_);
path_ = path;
params_->insert("path", path);
synthesize();
}
void Loop::addPart(const quint64 &part)
{
QMutexLocker mtxLock(&mtx_);
if (parts_.contains(part))
return;
parts_.push_back(part);
QJsonArray jsonArr;
foreach (quint64 p, parts_) {
jsonArr.push_back(QString::number(p));
}
params_->insert("parts", jsonArr);
qSort(parts_);
}
void Loop::delPart(const quint64 &part)
{
QMutexLocker mtxLock(&mtx_);
parts_.removeOne(part);
}
void Loop::synthesize()
{
qDebug() << "Loop::synthesize" << path_;
QFile file(path_);
file.open(QFile::ReadOnly);
QByteArray buffer = file.readAll();
file.close();
qint16 value16;
samplesBuffer_.clear();
for (int i = 0; i < buffer.size(); i += 2) {
value16 = (qint16)(((buffer[i+1] & 0xFF) << 8) | (buffer[i] & 0xFF));
samplesBuffer_.push_back((float)value16 / (float)INT16_MAX);
}
pos_ = 0;
Source::synthesize();
}
| 21.280255 | 77 | 0.57408 |
73ccfd3cb0f80bde181a6d4f4ec41b917af71cc8 | 27,244 | cc | C++ | src/common/chemistry/tests_regression/batch_chem.cc | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 37 | 2017-04-26T16:27:07.000Z | 2022-03-01T07:38:57.000Z | src/common/chemistry/tests_regression/batch_chem.cc | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 494 | 2016-09-14T02:31:13.000Z | 2022-03-13T18:57:05.000Z | src/common/chemistry/tests_regression/batch_chem.cc | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 43 | 2016-09-26T17:58:40.000Z | 2022-03-25T02:29:59.000Z | #include <unistd.h>
//#define ABORT_ON_FLOATING_POINT_EXCEPTIONS
#ifdef __APPLE__
#include <xmmintrin.h>
#endif
#include <cstdlib>
#include <cctype>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <string>
#include <stdexcept>
// TPLs
#include "VerboseObject_objs.hh"
#include "VerboseObject.hh"
// Chemistry
#include "simple_thermo_database.hh"
#include "beaker.hh"
#include "activity_model_factory.hh"
#include "chemistry_utilities.hh"
#include "chemistry_exception.hh"
#include "string_tokenizer.hh"
#include "batch_chem.hh"
namespace ac = Amanzi::AmanziChemistry;
const std::string kCrunch("crunch");
const std::string kPflotran("pflotran");
/* TODO: might be worth switching over to reading the component values
into a map rather than a vector, then order of components in the
cfg file wouldn't matter, but we need to request an name-id map
from the beaker. */
int main(int argc, char** argv) {
#ifdef ABORT_ON_FLOATING_POINT_EXCEPTIONS
#ifdef __APPLE__
// Make floating point exceptions abort the program. runtime error
// message isn't helpful, but running in gdb will stop at the
// correct line. This may code may not be apple specific....
_MM_SET_EXCEPTION_MASK(_MM_GET_EXCEPTION_MASK() & ~_MM_MASK_INVALID);
_MM_SET_EXCEPTION_MASK(_MM_GET_EXCEPTION_MASK() & ~_MM_MASK_DENORM);
_MM_SET_EXCEPTION_MASK(_MM_GET_EXCEPTION_MASK() & ~_MM_MASK_DIV_ZERO);
_MM_SET_EXCEPTION_MASK(_MM_GET_EXCEPTION_MASK() & ~_MM_MASK_OVERFLOW);
_MM_SET_EXCEPTION_MASK(_MM_GET_EXCEPTION_MASK() & ~_MM_MASK_UNDERFLOW);
#endif
#endif
std::stringstream message;
bool debug_batch_driver(false);
std::string verbosity_name("");
std::string input_file_name("");
std::string template_file_name("");
int error = EXIT_SUCCESS;
// if verbosity was specified on the command line, add the level
Amanzi::VerboseObject::global_hide_line_prefix = false; // two default value
Amanzi::VerboseObject::global_default_level = Teuchos::VERB_MEDIUM;
Teuchos::ParameterList plist;
auto vo = Teuchos::rcp(new Amanzi::VerboseObject("Chemistry PK", plist));
error = CommandLineOptions(argc, argv,
&verbosity_name,
&input_file_name,
&template_file_name,
&debug_batch_driver,
vo);
if (!template_file_name.empty()) {
WriteTemplateFile(template_file_name, vo);
exit(EXIT_SUCCESS);
}
ac::Beaker::BeakerComponents components;
SimulationParameters simulation_params;
if (!input_file_name.empty()) {
ReadInputFile(input_file_name, &simulation_params, &components, vo);
}
if (components.total.size() == 0) {
message << "Must have a non-zero number of total component values.\n";
vo->WriteWarning(Teuchos::VERB_LOW, message);
abort();
}
if (debug_batch_driver) {
PrintInput(simulation_params, components, vo);
}
double time_units_conversion = 1.0;
char time_units = 's';
std::fstream text_output;
if (simulation_params.text_output.size() > 0) {
SetupTextOutput(simulation_params, input_file_name,
&text_output, &time_units, &time_units_conversion);
}
ac::Beaker* chem = NULL;
try {
if (simulation_params.database_file.size() != 0) {
chem = new ac::SimpleThermoDatabase(vo);
ac::Beaker::BeakerParameters parameters = chem->GetDefaultParameters();
parameters.thermo_database_file = simulation_params.database_file;
parameters.activity_model_name = simulation_params.activity_model;
parameters.max_iterations = simulation_params.max_iterations;
parameters.tolerance = simulation_params.tolerance;
parameters.porosity = simulation_params.porosity; // -
parameters.saturation = simulation_params.saturation; // -
parameters.volume = simulation_params.volume; // m^3
ModelSpecificParameters(simulation_params.comparison_model, ¶meters);
if (components.free_ion.size() != components.total.size()) {
components.free_ion.resize(components.total.size(), 1.0e-9);
}
chem->Setup(components, parameters);
if (vo->getVerbLevel() >= Teuchos::VERB_HIGH) {
chem->Display();
chem->DisplayComponents(components);
}
// solve for free-ion concentrations
chem->Speciate(&components, parameters);
chem->CopyBeakerToComponents(&components);
if (vo->getVerbLevel() >= Teuchos::VERB_EXTREME) {
chem->DisplayResults();
}
bool using_sorption = false;
if (components.total_sorbed.size() > 0) {
using_sorption = true;
}
if (simulation_params.num_time_steps != 0) {
message.str("");
message << "-- Test Beaker Reaction Stepping -------------------------------------" << std::endl;
vo->Write(Teuchos::VERB_HIGH, message.str());
// write out the headers info and initial conditions
chem->DisplayTotalColumnHeaders(simulation_params.display_free_columns);
chem->DisplayTotalColumns(0.0, components,
simulation_params.display_free_columns);
std::vector<std::string> names;
chem->GetPrimaryNames(&names);
WriteTextOutputHeader(&text_output, time_units, names, using_sorption);
WriteTextOutput(&text_output, 0.0, components);
// parameters.max_iterations = 2;
for (int time_step = 0; time_step < simulation_params.num_time_steps;
time_step++) {
chem->ReactionStep(&components, parameters, simulation_params.delta_time);
if ((time_step + 1) % simulation_params.output_interval == 0) {
double time = (time_step + 1) * simulation_params.delta_time;
chem->DisplayTotalColumns(time, components,
simulation_params.display_free_columns);
WriteTextOutput(&text_output, time * time_units_conversion, components);
}
if (vo->getVerbLevel() >= Teuchos::VERB_HIGH) {
message.str("");
ac::Beaker::SolverStatus status = chem->status();
message << "Timestep: " << time_step << std::endl;
message << " number of rhs evaluations: " << status.num_rhs_evaluations << std::endl;
message << " number of jacobian evaluations: " << status.num_jacobian_evaluations << std::endl;
message << " number of newton iterations: " << status.num_newton_iterations << std::endl;
message << " solution converged: " << status.converged << std::endl;
vo->Write(Teuchos::VERB_HIGH, message.str());
}
}
vo->Write(Teuchos::VERB_HIGH, "---- Final Speciation\n");
chem->Speciate(&components, parameters);
if (vo->getVerbLevel() >= Teuchos::VERB_EXTREME) {
chem->DisplayResults();
}
}
} else {
vo->Write(Teuchos::VERB_HIGH, "No database file specified in input file.\n");
}
} catch (const ac::ChemistryException& geochem_error) {
vo->WriteWarning(Teuchos::VERB_LOW, geochem_error.what());
error = EXIT_FAILURE;
} catch (const std::runtime_error& rt_error) {
vo->WriteWarning(Teuchos::VERB_LOW, rt_error.what());
error = EXIT_FAILURE;
} catch (const std::logic_error& lg_error) {
vo->WriteWarning(Teuchos::VERB_LOW, lg_error.what());
error = EXIT_FAILURE;
}
if (!error) {
vo->Write(Teuchos::VERB_HIGH, "Success!\n");
} else {
vo->Write(Teuchos::VERB_HIGH, "Failed!\n");
}
text_output.close();
// cleanup memory
delete chem;
return error;
} // end main()
void ModelSpecificParameters(const std::string model,
ac::Beaker::BeakerParameters* parameters) {
if (model == kCrunch) {
parameters->water_density = 997.075; // kg / m^3
} else if (model == kPflotran) {
parameters->water_density = 997.16; // kg / m^3
// where did this number come from?
// default parameters->water_density = 997.205133945901; // kg / m^3
} else {
// bad model name, how did we get here....
}
} // end ModelSpecificParameters()
/*******************************************************************************
**
** Commandline
**
*******************************************************************************/
int CommandLineOptions(int argc, char** argv,
std::string* verbosity_name,
std::string* input_file_name,
std::string* template_file_name,
bool* debug_batch_driver,
const Teuchos::RCP<Amanzi::VerboseObject>& vo)
{
int error = -2;
int option;
extern char* optarg;
while ((option = getopt(argc, argv, "di:ht:v:?")) != -1) {
switch (option) {
case 'd': {
*debug_batch_driver = true;
break;
}
case 'i': {
/* input file name */
input_file_name->assign(optarg);
error = EXIT_SUCCESS;
break;
}
case 't': {
/* template file name */
template_file_name->assign(optarg);
error = EXIT_SUCCESS;
break;
}
case 'v': {
verbosity_name->assign(optarg);
break;
}
case '?':
case 'h': { /* help mode */
/* print some help stuff and exit without doing anything */
std::cout << argv[0] << " command line options:" << std::endl;
std::cout << " -d" << std::endl;
std::cout << " debugging flag for batch driver" << std::endl;
std::cout << " -i string " << std::endl;
std::cout << " input file name" << std::endl;
std::cout << std::endl;
std::cout << " -t string" << std::endl;
std::cout << " write a template input file" << std::endl;
std::cout << std::endl;
std::cout << " -v string" << std::endl;
std::cout << " additional verbosity level:" << std::endl;
std::cout << " silent" << std::endl;
std::cout << " terse" << std::endl;
std::cout << " verbose" << std::endl;
std::cout << " debug" << std::endl;
std::cout << " debug_beaker" << std::endl;
std::cout << " debug_database" << std::endl;
std::cout << " debug_mineral_kinetics" << std::endl;
std::cout << " debug_ion_exchange" << std::endl;
std::cout << " debug_newton_solver" << std::endl;
error = -1;
break;
}
default: {
/* no options */
break;
}
}
}
if (!input_file_name->c_str() && !template_file_name->c_str()) {
std::cout << "An input or template file name must be specified." << std::endl;
std::cout << "Run \"" << argv[0] << " -h \" for help." << std::endl;
}
if (*debug_batch_driver) {
std::stringstream message;
message << "- Command Line Options -----------------------------------------------" << std::endl;
message << "\tdebug batch driver: " << *debug_batch_driver << std::endl;
message << "\tinput file name: " << *input_file_name << std::endl;
message << "\ttemplate file name: " << *template_file_name << std::endl;
message << "\tverbosity name: " << *verbosity_name << std::endl;
message << "----------------------------------------------- Command Line Options -" << std::endl;
message << std::endl << std::endl;
vo->Write(Teuchos::VERB_EXTREME, message.str());
}
return error;
} // end commandLineOptions()
/*******************************************************************************
**
** Input file parser
**
*******************************************************************************/
void ReadInputFile(const std::string& file_name,
SimulationParameters* simulation_params,
ac::Beaker::BeakerComponents* components,
const Teuchos::RCP<Amanzi::VerboseObject>& vo)
{
std::stringstream message;
std::ifstream input_file(file_name.c_str());
if (!input_file) {
message.str("");
message << "batch_chem: \n";
message << "input file \'" << file_name
<< "\' could not be opened." << std::endl;
vo->WriteWarning(Teuchos::VERB_LOW, message);
abort();
}
enum LineType {
kCommentLine,
kSection,
kParameter
} line_type;
enum SectionType {
kSectionSimulation,
kSectionTotal,
kSectionMineral,
kSectionSorbed,
kSectionFreeIon,
kSectionIonExchange,
kSectionSiteDensity,
kSectionSpecificSurfaceArea,
kSectionIsotherms
} current_section;
int count = 0;
const int max_lines = 500;
while (!input_file.eof() && count < max_lines) {
count++;
std::string raw_line;
getline(input_file, raw_line);
//std::cout << raw_line << std::endl;
if ((raw_line.size() > 0) && (raw_line.at(raw_line.size() - 1) == '\r')) {
// getline only searches for \n line ends. windows files use \r\n
// check for a hanging \r and remove it if it is there
raw_line.resize(raw_line.size() - 1);
}
char sym_first = '\0';
if (raw_line.length() > 0) sym_first = raw_line[0];
if (sym_first == '#' || sym_first == '\0') {
line_type = kCommentLine;
} else if (sym_first == '[') {
line_type = kSection;
} else {
line_type = kParameter;
}
if (line_type == kSection) {
size_t first = raw_line.find_first_not_of('[');
size_t last = raw_line.find_last_of(']');
last--;
std::string section_name = raw_line.substr(first, last);
if (section_name.compare(kSimulationSection) == 0) {
current_section = kSectionSimulation;
} else if (section_name.compare(kTotalSection) == 0) {
current_section = kSectionTotal;
} else if (section_name.compare(kMineralSection) == 0) {
current_section = kSectionMineral;
} else if (section_name.compare(kIonExchangeSection) == 0) {
current_section = kSectionIonExchange;
} else if (section_name.compare(kSorbedSection) == 0) {
current_section = kSectionSorbed;
} else if (section_name.compare(kFreeIonSection) == 0) {
current_section = kSectionFreeIon;
} else if (section_name.compare(kSiteDensitySection) == 0) {
current_section = kSectionSiteDensity;
} else if (section_name.compare(kSpecificSurfaceAreaSection) == 0) {
current_section = kSectionSpecificSurfaceArea;
} else if (section_name.compare(kIsothermSection) == 0) {
current_section = kSectionIsotherms;
} else {
message.str("");
message << "batch_chem::ReadInputFile(): ";
message << "unknown section found on line " << count << ":";
message << "\'" << raw_line << "\'"<< std::endl;
vo->Write(Teuchos::VERB_LOW, message.str());
}
} else if (line_type == kParameter) {
// assume parameter line, but it may be empty (just spaces or missing an = )...
if (current_section == kSectionSimulation) {
ParseSimulationParameter(raw_line, simulation_params);
} else if (current_section == kSectionTotal) {
ParseComponentValue(raw_line, &(components->total));
} else if (current_section == kSectionSorbed) {
ParseComponentValue(raw_line, &(components->total_sorbed));
} else if (current_section == kSectionFreeIon) {
ParseComponentValue(raw_line, &(components->free_ion));
} else if (current_section == kSectionMineral) {
ParseComponentValue(raw_line, &(components->mineral_volume_fraction));
} else if (current_section == kSectionSpecificSurfaceArea) {
ParseComponentValue(raw_line, &(components->mineral_specific_surface_area));
} else if (current_section == kSectionIonExchange) {
ParseComponentValue(raw_line, &(components->ion_exchange_sites));
} else if (current_section == kSectionSiteDensity) {
ParseComponentValue(raw_line, &(components->surface_site_density));
} else if (current_section == kSectionIsotherms) {
// TODO: need to figure out the format of this data...
}
}
}
input_file.close();
} // end ReadInputFile()
void ParseSimulationParameter(const std::string& raw_line,
SimulationParameters* params)
{
std::string equal("=:");
std::string spaces(" \t");
ac::StringTokenizer param(raw_line, equal);
//std::cout << "\'" << raw_line << "\'" << std::endl;
// if param.size() == 0 then we have a blank line
if (param.size() != 0) {
ac::StringTokenizer values(param.at(1), ",");
std::string value("");
if (values.size() == 1) {
value.assign(values.at(0));
ac::utilities::RemoveLeadingAndTrailingWhitespace(&value);
}
//std::cout << "Parsing -----> '" << param.at(0) << "'" << std::endl;
if (param.at(0).find(kDescriptionParam) != std::string::npos) {
// the description probably has spaces in it, so we want to use
// the raw parameter value from param.at(1) rather than the
// version in value, which has been tokenized by spaces!
params->description.assign(param.at(1));
} else if (param.at(0).find(kTextOutputParam) != std::string::npos) {
params->text_output.assign(value) ;
} else if (param.at(0).find(kTextTimeUnitsParam) != std::string::npos) {
params->text_time_units.assign(value) ;
} else if (param.at(0).find(kComparisonModelParam) != std::string::npos) {
params->comparison_model.assign(value);
} else if (param.at(0).find(kDatabaseTypeParam) != std::string::npos) {
params->database_type.assign(value);
} else if (param.at(0).find(kDatabaseFileParam) != std::string::npos) {
params->database_file.assign(value);
} else if (param.at(0).find(kActivityModelParam) != std::string::npos) {
params->activity_model.assign(value);
} else if (param.at(0).find(kPorosityParam) != std::string::npos) {
params->porosity = std::atof(value.c_str());
} else if (param.at(0).find(kSaturationParam) != std::string::npos) {
params->saturation = std::atof(value.c_str());
} else if (param.at(0).find(kVolumeParam) != std::string::npos) {
params->volume = std::atof(value.c_str());
} else if (param.at(0).find(kDeltaTimeParam) != std::string::npos) {
params->delta_time = std::atof(value.c_str());
} else if (param.at(0).find(kNumTimeStepsParam) != std::string::npos) {
params->num_time_steps = std::atoi(value.c_str());
} else if (param.at(0).find(kOutputIntervalParam) != std::string::npos) {
params->output_interval = std::atoi(value.c_str());
} else if (param.at(0).find(kToleranceParam) != std::string::npos) {
params->tolerance = std::atof(value.c_str());
} else if (param.at(0).find(kMaxIterationsParam) != std::string::npos) {
params->max_iterations = std::atoi(value.c_str());
}
}
} // end ParseSimulationParameter()
void ParseComponentValue(const std::string& raw_line,
std::vector<double>* component)
{
// for now we assume that the order of the component is the
// same as the order in the database file
std::string equal("=:");
std::string spaces(" \t");
ac::StringTokenizer param(raw_line, equal);
//std::cout << "\'" << raw_line << "\'" << std::endl;
// if param.size() == 0 then we have a blank line
if (param.size() != 0) {
ac::StringTokenizer param_value(param.at(1), spaces);
double value;
if (param_value.size() > 0) {
value = std::atof(param_value.at(0).c_str());
}
component->push_back(value);
}
} // end ParseComponentValue();
void ParseComponentValue(const std::string& raw_line,
double* component)
{
// this is intended for a single value, not a c-style array!
std::string equal("=:");
std::string spaces(" \t");
ac::StringTokenizer param(raw_line, equal);
//std::cout << "\'" << raw_line << "\'" << std::endl;
// if param.size() == 0 then we have a blank line
if (param.size() != 0) {
ac::StringTokenizer param_value(param.at(1), spaces);
double value = 0.;
if (param_value.size() > 0) {
value = std::atof(param_value.at(0).c_str());
}
*component = value;
}
} // end ParseComponentValue();
/*******************************************************************************
**
** Output related functions
**
*******************************************************************************/
void WriteTemplateFile(const std::string& file_name,
const Teuchos::RCP<Amanzi::VerboseObject>& vo)
{
std::ofstream template_file(file_name.c_str());
if (!template_file) {
std::stringstream message;
message << "batch_chem: \n";
message << "template file \'" << file_name
<< "\' could not be opened." << std::endl;
vo->WriteWarning(Teuchos::VERB_LOW, message);
abort();
}
template_file << "[" << kSimulationSection << "]" << std::endl;
template_file << kDescriptionParam << " = " << std::endl;
template_file << "# verbosity can be a comma seperated list." << std::endl;
template_file << kComparisonModelParam << " = pflotran" << std::endl;
template_file << kTextOutputParam << " = true" << std::endl;
template_file << kTextTimeUnitsParam << " = days" << std::endl;
template_file << std::endl;
template_file << kDatabaseTypeParam << " = simple" << std::endl;
template_file << kDatabaseFileParam << " = " << std::endl;
template_file << kActivityModelParam << " = debye-huckel" << std::endl;
template_file << kPorosityParam << " = " << std::endl;
template_file << kSaturationParam << " = " << std::endl;
template_file << kVolumeParam << " = " << std::endl;
template_file << kDeltaTimeParam << " = " << std::endl;
template_file << kNumTimeStepsParam << " = " << std::endl;
template_file << kOutputIntervalParam << " = " << std::endl;
template_file << std::endl;
template_file << "# all component values must be in the same order as the database file" << std::endl;
template_file << "[" << kTotalSection << "]" << std::endl;
template_file << std::endl;
template_file << "[" << kMineralSection << "]" << std::endl;
template_file << std::endl;
template_file << "[" << kSorbedSection << "]" << std::endl;
template_file << std::endl;
template_file << "[" << kFreeIonSection << "]" << std::endl;
template_file << std::endl;
template_file << "[" << kIonExchangeSection << "] # CEC" << std::endl;
template_file << std::endl;
template_file << "[" << kIsothermSection << "]" << std::endl;
template_file << std::endl;
template_file.close();
} // end WriteTemplateFile()
void SetupTextOutput(const SimulationParameters& simulation_params,
const std::string& input_file_name,
std::fstream* text_output, char* time_units,
double* time_units_conversion) {
// are we writting to observations to a text file?
if (simulation_params.text_output == "true" ||
simulation_params.text_output == "yes" ||
simulation_params.text_output == "on") {
// generate the output file name:
size_t position = input_file_name.find_last_of('.');
std::string text_output_name = input_file_name.substr(0, position) + ".txt";
text_output->open(text_output_name.c_str(), std::fstream::out);
// do we want to change the time units for the output?
if (simulation_params.text_time_units.size() > 0) {
*time_units = std::tolower(simulation_params.text_time_units.at(0));
switch (*time_units) {
case 's':
break;
case 'm':
*time_units_conversion = 60.0;
break;
case 'h':
*time_units_conversion = 60.0 * 60.0;
break;
case 'd':
*time_units_conversion = 60.0 * 60.0 * 24.0;
break;
case 'y':
*time_units_conversion = 60.0 * 60.0 * 24.0 * 365.25;
break;
default:
break;
}
}
*time_units_conversion = 1.0 / (*time_units_conversion);
}
}
void WriteTextOutputHeader(std::fstream* text_output, const char time_units,
const std::vector<std::string>& names,
const bool using_sorption) {
if (text_output->is_open()) {
*text_output << "# Time(" << time_units << ")";
for (std::vector<std::string>::const_iterator name = names.begin();
name != names.end(); ++name) {
*text_output << " , " << *name;
}
if (using_sorption) {
for (std::vector<std::string>::const_iterator name = names.begin();
name != names.end(); ++name) {
*text_output << " , " << *name << "_sorbed";
}
}
*text_output << std::endl;
}
}
void WriteTextOutput(std::fstream* text_output, const double time,
const Amanzi::AmanziChemistry::Beaker::BeakerComponents& components) {
if (text_output->is_open()) {
std::string seperator(" , ");
*text_output << std::scientific << std::setprecision(6) << std::setw(15) << time;
for (int i = 0; i < components.total.size(); ++i) {
*text_output << seperator << components.total.at(i);
}
for (int i = 0; i < components.total_sorbed.size(); ++i) {
*text_output << seperator << components.total_sorbed.at(i);
}
*text_output << std::endl;
}
}
void PrintInput(const SimulationParameters& params,
const Amanzi::AmanziChemistry::Beaker::BeakerComponents& components,
const Teuchos::RCP<Amanzi::VerboseObject>& vo)
{
vo->Write(Teuchos::VERB_HIGH, "- Input File ---------------------------------------------------------\n");
PrintSimulationParameters(params, vo);
components.Display("-- Input components: \n", vo);
vo->Write(Teuchos::VERB_HIGH, "--------------------------------------------------------- Input File -\n");
} // end PrintInput()
void PrintSimulationParameters(const SimulationParameters& params,
const Teuchos::RCP<Amanzi::VerboseObject>& vo)
{
std::stringstream message;
message << "-- Simulation parameters:" << std::endl;
message << "\tdescription: " << params.description << std::endl;
vo->Write(Teuchos::VERB_HIGH, message.str());
message.str("");
message << "\tcomparison model: " << params.comparison_model << std::endl;
message << "\tdatabase type: " << params.database_type << std::endl;
message << "\tdatabase file: " << params.database_file << std::endl;
message << "\tactivity model: " << params.activity_model << std::endl;
message << "\tporosity: " << params.porosity << std::endl;
message << "\tsaturation: " << params.saturation << std::endl;
message << "\tvolume: " << params.volume << std::endl;
message << "\tdelta time: " << params.delta_time << std::endl;
message << "\tnum time steps: " << params.num_time_steps << std::endl;
message << "\toutput interval: " << params.output_interval << std::endl;
message << "\tmax iterations: " << params.max_iterations << std::endl;
message << "\ttolerance: " << params.tolerance << std::endl;
vo->Write(Teuchos::VERB_HIGH, message.str());
}
| 39.143678 | 110 | 0.602812 |
73d091a7595a87265d1acfa7b9081aac2fc8a915 | 406 | hpp | C++ | src/point.hpp | harry830622/fixed-outline-floorplanning | 8fc1fc91f0e3329c6369c8b1f863bcce31465430 | [
"MIT"
] | 4 | 2019-07-02T18:15:01.000Z | 2021-12-22T06:09:35.000Z | src/point.hpp | harry830622/fixed-outline-floorplanning | 8fc1fc91f0e3329c6369c8b1f863bcce31465430 | [
"MIT"
] | null | null | null | src/point.hpp | harry830622/fixed-outline-floorplanning | 8fc1fc91f0e3329c6369c8b1f863bcce31465430 | [
"MIT"
] | 1 | 2016-12-07T15:13:07.000Z | 2016-12-07T15:13:07.000Z | #ifndef POINT_HPP
#define POINT_HPP
#include <iostream>
class Point {
public:
static double HPWL(const Point& point_a, const Point& point_b);
static Point Center(const Point& point_a, const Point& point_b);
Point(double x, double y);
void Print(std::ostream& os = std::cout, int indent_level = 0) const;
double x() const;
double y() const;
private:
double x_;
double y_;
};
#endif
| 16.916667 | 71 | 0.694581 |
73d158187bc010e9aec65b6a81de99539d4e7b90 | 16,317 | cc | C++ | generator/integration_tests/golden/tests/golden_thing_admin_auth_decorator_test.cc | bryanlaura736/google-cloud-cpp | c0179a2209a4b11f8db1b1b474c1c8bdb2f1df86 | [
"Apache-2.0"
] | null | null | null | generator/integration_tests/golden/tests/golden_thing_admin_auth_decorator_test.cc | bryanlaura736/google-cloud-cpp | c0179a2209a4b11f8db1b1b474c1c8bdb2f1df86 | [
"Apache-2.0"
] | null | null | null | generator/integration_tests/golden/tests/golden_thing_admin_auth_decorator_test.cc | bryanlaura736/google-cloud-cpp | c0179a2209a4b11f8db1b1b474c1c8bdb2f1df86 | [
"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
//
// 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 "generator/integration_tests/golden/internal/golden_thing_admin_auth_decorator.h"
#include "google/cloud/testing_util/mock_grpc_authentication_strategy.h"
#include "google/cloud/testing_util/status_matchers.h"
#include "generator/integration_tests/golden/mocks/mock_golden_thing_admin_stub.h"
#include <gmock/gmock.h>
#include <memory>
namespace google {
namespace cloud {
namespace golden_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
namespace {
using ::google::cloud::testing_util::MakeTypicalAsyncMockAuth;
using ::google::cloud::testing_util::MakeTypicalMockAuth;
using ::google::cloud::testing_util::StatusIs;
using ::testing::ByMove;
using ::testing::IsNull;
using ::testing::Return;
using ::testing::Unused;
future<StatusOr<google::longrunning::Operation>> LongrunningError(Unused,
Unused,
Unused) {
return make_ready_future(StatusOr<google::longrunning::Operation>(
Status(StatusCode::kPermissionDenied, "uh-oh")));
}
// The general pattern of these test is to make two requests, both of which
// return an error. The first one because the auth strategy fails, the second
// because the operation in the mock stub fails.
TEST(GoldenThingAdminAuthDecoratorTest, ListDatabases) {
auto mock = std::make_shared<MockGoldenThingAdminStub>();
EXPECT_CALL(*mock, ListDatabases)
.WillOnce(Return(Status(StatusCode::kPermissionDenied, "uh-oh")));
auto under_test = GoldenThingAdminAuth(MakeTypicalMockAuth(), mock);
google::test::admin::database::v1::ListDatabasesRequest request;
grpc::ClientContext ctx;
auto auth_failure = under_test.ListDatabases(ctx, request);
EXPECT_THAT(ctx.credentials(), IsNull());
EXPECT_THAT(auth_failure, StatusIs(StatusCode::kInvalidArgument));
auto auth_success = under_test.ListDatabases(ctx, request);
EXPECT_THAT(ctx.credentials(), Not(IsNull()));
EXPECT_THAT(auth_success, StatusIs(StatusCode::kPermissionDenied));
}
TEST(GoldenThingAdminAuthDecoratorTest, AsyncCreateDatabase) {
auto mock = std::make_shared<MockGoldenThingAdminStub>();
EXPECT_CALL(*mock, AsyncCreateDatabase).WillOnce(LongrunningError);
auto under_test = GoldenThingAdminAuth(MakeTypicalAsyncMockAuth(), mock);
google::test::admin::database::v1::CreateDatabaseRequest request;
CompletionQueue cq;
auto auth_failure = under_test.AsyncCreateDatabase(
cq, absl::make_unique<grpc::ClientContext>(), request);
EXPECT_THAT(auth_failure.get(), StatusIs(StatusCode::kInvalidArgument));
auto auth_success = under_test.AsyncCreateDatabase(
cq, absl::make_unique<grpc::ClientContext>(), request);
EXPECT_THAT(auth_success.get(), StatusIs(StatusCode::kPermissionDenied));
}
TEST(GoldenThingAdminAuthDecoratorTest, GetDatabase) {
auto mock = std::make_shared<MockGoldenThingAdminStub>();
EXPECT_CALL(*mock, GetDatabase)
.WillOnce(Return(Status(StatusCode::kPermissionDenied, "uh-oh")));
auto under_test = GoldenThingAdminAuth(MakeTypicalMockAuth(), mock);
google::test::admin::database::v1::GetDatabaseRequest request;
grpc::ClientContext ctx;
auto auth_failure = under_test.GetDatabase(ctx, request);
EXPECT_THAT(ctx.credentials(), IsNull());
EXPECT_THAT(auth_failure, StatusIs(StatusCode::kInvalidArgument));
auto auth_success = under_test.GetDatabase(ctx, request);
EXPECT_THAT(ctx.credentials(), Not(IsNull()));
EXPECT_THAT(auth_success, StatusIs(StatusCode::kPermissionDenied));
}
TEST(GoldenThingAdminAuthDecoratorTest, AsyncUpdateDatabaseDdl) {
auto mock = std::make_shared<MockGoldenThingAdminStub>();
EXPECT_CALL(*mock, AsyncUpdateDatabaseDdl).WillOnce(LongrunningError);
auto under_test = GoldenThingAdminAuth(MakeTypicalAsyncMockAuth(), mock);
google::test::admin::database::v1::UpdateDatabaseDdlRequest request;
CompletionQueue cq;
auto auth_failure = under_test.AsyncUpdateDatabaseDdl(
cq, absl::make_unique<grpc::ClientContext>(), request);
EXPECT_THAT(auth_failure.get(), StatusIs(StatusCode::kInvalidArgument));
auto auth_success = under_test.AsyncUpdateDatabaseDdl(
cq, absl::make_unique<grpc::ClientContext>(), request);
EXPECT_THAT(auth_success.get(), StatusIs(StatusCode::kPermissionDenied));
}
TEST(GoldenThingAdminAuthDecoratorTest, DropDatabase) {
auto mock = std::make_shared<MockGoldenThingAdminStub>();
EXPECT_CALL(*mock, DropDatabase)
.WillOnce(Return(Status(StatusCode::kPermissionDenied, "uh-oh")));
auto under_test = GoldenThingAdminAuth(MakeTypicalMockAuth(), mock);
google::test::admin::database::v1::DropDatabaseRequest request;
grpc::ClientContext ctx;
auto auth_failure = under_test.DropDatabase(ctx, request);
EXPECT_THAT(ctx.credentials(), IsNull());
EXPECT_THAT(auth_failure, StatusIs(StatusCode::kInvalidArgument));
auto auth_success = under_test.DropDatabase(ctx, request);
EXPECT_THAT(ctx.credentials(), Not(IsNull()));
EXPECT_THAT(auth_success, StatusIs(StatusCode::kPermissionDenied));
}
TEST(GoldenThingAdminAuthDecoratorTest, GetDatabaseDdl) {
auto mock = std::make_shared<MockGoldenThingAdminStub>();
EXPECT_CALL(*mock, GetDatabaseDdl)
.WillOnce(Return(Status(StatusCode::kPermissionDenied, "uh-oh")));
auto under_test = GoldenThingAdminAuth(MakeTypicalMockAuth(), mock);
google::test::admin::database::v1::GetDatabaseDdlRequest request;
grpc::ClientContext ctx;
auto auth_failure = under_test.GetDatabaseDdl(ctx, request);
EXPECT_THAT(ctx.credentials(), IsNull());
EXPECT_THAT(auth_failure, StatusIs(StatusCode::kInvalidArgument));
auto auth_success = under_test.GetDatabaseDdl(ctx, request);
EXPECT_THAT(ctx.credentials(), Not(IsNull()));
EXPECT_THAT(auth_success, StatusIs(StatusCode::kPermissionDenied));
}
TEST(GoldenThingAdminAuthDecoratorTest, SetIamPolicy) {
auto mock = std::make_shared<MockGoldenThingAdminStub>();
EXPECT_CALL(*mock, SetIamPolicy)
.WillOnce(Return(Status(StatusCode::kPermissionDenied, "uh-oh")));
auto under_test = GoldenThingAdminAuth(MakeTypicalMockAuth(), mock);
google::iam::v1::SetIamPolicyRequest request;
grpc::ClientContext ctx;
auto auth_failure = under_test.SetIamPolicy(ctx, request);
EXPECT_THAT(ctx.credentials(), IsNull());
EXPECT_THAT(auth_failure, StatusIs(StatusCode::kInvalidArgument));
auto auth_success = under_test.SetIamPolicy(ctx, request);
EXPECT_THAT(ctx.credentials(), Not(IsNull()));
EXPECT_THAT(auth_success, StatusIs(StatusCode::kPermissionDenied));
}
TEST(GoldenThingAdminAuthDecoratorTest, GetIamPolicy) {
auto mock = std::make_shared<MockGoldenThingAdminStub>();
EXPECT_CALL(*mock, GetIamPolicy)
.WillOnce(Return(Status(StatusCode::kPermissionDenied, "uh-oh")));
auto under_test = GoldenThingAdminAuth(MakeTypicalMockAuth(), mock);
google::iam::v1::GetIamPolicyRequest request;
grpc::ClientContext ctx;
auto auth_failure = under_test.GetIamPolicy(ctx, request);
EXPECT_THAT(ctx.credentials(), IsNull());
EXPECT_THAT(auth_failure, StatusIs(StatusCode::kInvalidArgument));
auto auth_success = under_test.GetIamPolicy(ctx, request);
EXPECT_THAT(ctx.credentials(), Not(IsNull()));
EXPECT_THAT(auth_success, StatusIs(StatusCode::kPermissionDenied));
}
TEST(GoldenThingAdminAuthDecoratorTest, TestIamPermissions) {
auto mock = std::make_shared<MockGoldenThingAdminStub>();
EXPECT_CALL(*mock, TestIamPermissions)
.WillOnce(Return(Status(StatusCode::kPermissionDenied, "uh-oh")));
auto under_test = GoldenThingAdminAuth(MakeTypicalMockAuth(), mock);
google::iam::v1::TestIamPermissionsRequest request;
grpc::ClientContext ctx;
auto auth_failure = under_test.TestIamPermissions(ctx, request);
EXPECT_THAT(ctx.credentials(), IsNull());
EXPECT_THAT(auth_failure, StatusIs(StatusCode::kInvalidArgument));
auto auth_success = under_test.TestIamPermissions(ctx, request);
EXPECT_THAT(ctx.credentials(), Not(IsNull()));
EXPECT_THAT(auth_success, StatusIs(StatusCode::kPermissionDenied));
}
TEST(GoldenThingAdminAuthDecoratorTest, AsyncCreateBackup) {
auto mock = std::make_shared<MockGoldenThingAdminStub>();
EXPECT_CALL(*mock, AsyncCreateBackup).WillOnce(LongrunningError);
auto under_test = GoldenThingAdminAuth(MakeTypicalAsyncMockAuth(), mock);
google::test::admin::database::v1::CreateBackupRequest request;
CompletionQueue cq;
auto auth_failure = under_test.AsyncCreateBackup(
cq, absl::make_unique<grpc::ClientContext>(), request);
EXPECT_THAT(auth_failure.get(), StatusIs(StatusCode::kInvalidArgument));
auto auth_success = under_test.AsyncCreateBackup(
cq, absl::make_unique<grpc::ClientContext>(), request);
EXPECT_THAT(auth_success.get(), StatusIs(StatusCode::kPermissionDenied));
}
TEST(GoldenThingAdminAuthDecoratorTest, GetBackup) {
auto mock = std::make_shared<MockGoldenThingAdminStub>();
EXPECT_CALL(*mock, GetBackup)
.WillOnce(Return(Status(StatusCode::kPermissionDenied, "uh-oh")));
auto under_test = GoldenThingAdminAuth(MakeTypicalMockAuth(), mock);
google::test::admin::database::v1::GetBackupRequest request;
grpc::ClientContext ctx;
auto auth_failure = under_test.GetBackup(ctx, request);
EXPECT_THAT(ctx.credentials(), IsNull());
EXPECT_THAT(auth_failure, StatusIs(StatusCode::kInvalidArgument));
auto auth_success = under_test.GetBackup(ctx, request);
EXPECT_THAT(ctx.credentials(), Not(IsNull()));
EXPECT_THAT(auth_success, StatusIs(StatusCode::kPermissionDenied));
}
TEST(GoldenThingAdminAuthDecoratorTest, UpdateBackup) {
auto mock = std::make_shared<MockGoldenThingAdminStub>();
EXPECT_CALL(*mock, UpdateBackup)
.WillOnce(Return(Status(StatusCode::kPermissionDenied, "uh-oh")));
auto under_test = GoldenThingAdminAuth(MakeTypicalMockAuth(), mock);
google::test::admin::database::v1::UpdateBackupRequest request;
grpc::ClientContext ctx;
auto auth_failure = under_test.UpdateBackup(ctx, request);
EXPECT_THAT(ctx.credentials(), IsNull());
EXPECT_THAT(auth_failure, StatusIs(StatusCode::kInvalidArgument));
auto auth_success = under_test.UpdateBackup(ctx, request);
EXPECT_THAT(ctx.credentials(), Not(IsNull()));
EXPECT_THAT(auth_success, StatusIs(StatusCode::kPermissionDenied));
}
TEST(GoldenThingAdminAuthDecoratorTest, DeleteBackup) {
auto mock = std::make_shared<MockGoldenThingAdminStub>();
EXPECT_CALL(*mock, DeleteBackup)
.WillOnce(Return(Status(StatusCode::kPermissionDenied, "uh-oh")));
auto under_test = GoldenThingAdminAuth(MakeTypicalMockAuth(), mock);
google::test::admin::database::v1::DeleteBackupRequest request;
grpc::ClientContext ctx;
auto auth_failure = under_test.DeleteBackup(ctx, request);
EXPECT_THAT(ctx.credentials(), IsNull());
EXPECT_THAT(auth_failure, StatusIs(StatusCode::kInvalidArgument));
auto auth_success = under_test.DeleteBackup(ctx, request);
EXPECT_THAT(ctx.credentials(), Not(IsNull()));
EXPECT_THAT(auth_success, StatusIs(StatusCode::kPermissionDenied));
}
TEST(GoldenThingAdminAuthDecoratorTest, ListBackups) {
auto mock = std::make_shared<MockGoldenThingAdminStub>();
EXPECT_CALL(*mock, ListBackups)
.WillOnce(Return(Status(StatusCode::kPermissionDenied, "uh-oh")));
auto under_test = GoldenThingAdminAuth(MakeTypicalMockAuth(), mock);
google::test::admin::database::v1::ListBackupsRequest request;
grpc::ClientContext ctx;
auto auth_failure = under_test.ListBackups(ctx, request);
EXPECT_THAT(ctx.credentials(), IsNull());
EXPECT_THAT(auth_failure, StatusIs(StatusCode::kInvalidArgument));
auto auth_success = under_test.ListBackups(ctx, request);
EXPECT_THAT(ctx.credentials(), Not(IsNull()));
EXPECT_THAT(auth_success, StatusIs(StatusCode::kPermissionDenied));
}
TEST(GoldenThingAdminAuthDecoratorTest, AsyncRestoreDatabase) {
auto mock = std::make_shared<MockGoldenThingAdminStub>();
EXPECT_CALL(*mock, AsyncRestoreDatabase).WillOnce(LongrunningError);
auto under_test = GoldenThingAdminAuth(MakeTypicalAsyncMockAuth(), mock);
google::test::admin::database::v1::RestoreDatabaseRequest request;
CompletionQueue cq;
auto auth_failure = under_test.AsyncRestoreDatabase(
cq, absl::make_unique<grpc::ClientContext>(), request);
EXPECT_THAT(auth_failure.get(), StatusIs(StatusCode::kInvalidArgument));
auto auth_success = under_test.AsyncRestoreDatabase(
cq, absl::make_unique<grpc::ClientContext>(), request);
EXPECT_THAT(auth_success.get(), StatusIs(StatusCode::kPermissionDenied));
}
TEST(GoldenThingAdminAuthDecoratorTest, ListDatabaseOperations) {
auto mock = std::make_shared<MockGoldenThingAdminStub>();
EXPECT_CALL(*mock, ListDatabaseOperations)
.WillOnce(Return(Status(StatusCode::kPermissionDenied, "uh-oh")));
auto under_test = GoldenThingAdminAuth(MakeTypicalMockAuth(), mock);
google::test::admin::database::v1::ListDatabaseOperationsRequest request;
grpc::ClientContext ctx;
auto auth_failure = under_test.ListDatabaseOperations(ctx, request);
EXPECT_THAT(ctx.credentials(), IsNull());
EXPECT_THAT(auth_failure, StatusIs(StatusCode::kInvalidArgument));
auto auth_success = under_test.ListDatabaseOperations(ctx, request);
EXPECT_THAT(ctx.credentials(), Not(IsNull()));
EXPECT_THAT(auth_success, StatusIs(StatusCode::kPermissionDenied));
}
TEST(GoldenThingAdminAuthDecoratorTest, ListBackupOperations) {
auto mock = std::make_shared<MockGoldenThingAdminStub>();
EXPECT_CALL(*mock, ListBackupOperations)
.WillOnce(Return(Status(StatusCode::kPermissionDenied, "uh-oh")));
auto under_test = GoldenThingAdminAuth(MakeTypicalMockAuth(), mock);
google::test::admin::database::v1::ListBackupOperationsRequest request;
grpc::ClientContext ctx;
auto auth_failure = under_test.ListBackupOperations(ctx, request);
EXPECT_THAT(ctx.credentials(), IsNull());
EXPECT_THAT(auth_failure, StatusIs(StatusCode::kInvalidArgument));
auto auth_success = under_test.ListBackupOperations(ctx, request);
EXPECT_THAT(ctx.credentials(), Not(IsNull()));
EXPECT_THAT(auth_success, StatusIs(StatusCode::kPermissionDenied));
}
TEST(GoldenThingAdminAuthDecoratorTest, AsyncGetOperation) {
auto mock = std::make_shared<MockGoldenThingAdminStub>();
EXPECT_CALL(*mock, AsyncGetOperation).WillOnce(LongrunningError);
auto under_test = GoldenThingAdminAuth(MakeTypicalAsyncMockAuth(), mock);
google::longrunning::GetOperationRequest request;
CompletionQueue cq;
auto auth_failure = under_test.AsyncGetOperation(
cq, absl::make_unique<grpc::ClientContext>(), request);
EXPECT_THAT(auth_failure.get(), StatusIs(StatusCode::kInvalidArgument));
auto auth_success = under_test.AsyncGetOperation(
cq, absl::make_unique<grpc::ClientContext>(), request);
EXPECT_THAT(auth_success.get(), StatusIs(StatusCode::kPermissionDenied));
}
TEST(GoldenThingAdminAuthDecoratorTest, AsyncCancelOperation) {
auto mock = std::make_shared<MockGoldenThingAdminStub>();
EXPECT_CALL(*mock, AsyncCancelOperation)
.WillOnce(Return(ByMove(
make_ready_future(Status{StatusCode::kPermissionDenied, "uh-oh"}))));
auto under_test = GoldenThingAdminAuth(MakeTypicalAsyncMockAuth(), mock);
google::longrunning::CancelOperationRequest request;
CompletionQueue cq;
auto auth_failure = under_test.AsyncCancelOperation(
cq, absl::make_unique<grpc::ClientContext>(), request);
EXPECT_THAT(auth_failure.get(), StatusIs(StatusCode::kInvalidArgument));
auto auth_success = under_test.AsyncCancelOperation(
cq, absl::make_unique<grpc::ClientContext>(), request);
EXPECT_THAT(auth_success.get(), StatusIs(StatusCode::kPermissionDenied));
}
} // namespace
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace golden_internal
} // namespace cloud
} // namespace google
| 43.981132 | 90 | 0.771036 |
73d1ac7b1a8d34b165370c90d6fd1b84f8e16aa4 | 666 | cpp | C++ | review_gg/longestCommonPrefix.cpp | alchemz/interview-algorithm-questions | 34039fc0db2766cf7531668a9947779a3835ebf5 | [
"MIT"
] | null | null | null | review_gg/longestCommonPrefix.cpp | alchemz/interview-algorithm-questions | 34039fc0db2766cf7531668a9947779a3835ebf5 | [
"MIT"
] | null | null | null | review_gg/longestCommonPrefix.cpp | alchemz/interview-algorithm-questions | 34039fc0db2766cf7531668a9947779a3835ebf5 | [
"MIT"
] | null | null | null | //longestCommonPrefix.cpp
/*
Description:
Write a function to find the longest common prefix string amongst an array of strings
Thoughts:
从左开始一位一位判断当前位置的字符是否属于common prefix。第i位属于common prefix的前提是:
1. i < strs[k].size(),k = 0, 1, ....n-1
2. strs[0][i] = strs[1][i] = ... = strs[n-1][i]
两个条件缺一不可。
*/
class Solution{
public:
string longestCommonPrefix(vector<string>& strs){
string comPrefix;
if(strs.empty()) return commonPrefix;
for(int i=0; i<strs[0].size(); i++)
{
for(int j=1; j<strs.size(); j++)
{
if(i>=strs[j].size() || strs[j][i] != strs[0][i])
return comPrefix;
}
comPrefix.push_back(strs[0][i]);
}
return comPrefix;
}
}; | 22.965517 | 85 | 0.644144 |
73d1d961b9b2003e9fa235136a493b26046ab0f4 | 3,560 | cpp | C++ | v3d_main/mozak/m_terafly/src/control/m_QUndoMarkerCreate.cpp | lens-biophotonics/v3d_external | 44ff3b60a297a96eaa77ca092e0de9af5c990ed3 | [
"MIT"
] | 39 | 2015-05-10T23:23:03.000Z | 2022-01-26T01:31:30.000Z | v3d_main/mozak/m_terafly/src/control/m_QUndoMarkerCreate.cpp | lens-biophotonics/v3d_external | 44ff3b60a297a96eaa77ca092e0de9af5c990ed3 | [
"MIT"
] | 13 | 2016-03-04T05:29:23.000Z | 2021-02-07T01:11:10.000Z | v3d_main/mozak/m_terafly/src/control/m_QUndoMarkerCreate.cpp | lens-biophotonics/v3d_external | 44ff3b60a297a96eaa77ca092e0de9af5c990ed3 | [
"MIT"
] | 44 | 2015-11-11T07:30:59.000Z | 2021-12-26T16:41:21.000Z | #include "v3dr_glwidget.h"
#include "m_QUndoMarkerCreate.h"
#include "m_CViewer.h"
#include "m_PAnoToolBar.h"
itm::QUndoMarkerCreate::QUndoMarkerCreate(itm::CViewer* _source, LocationSimple _marker) : QUndoCommand()
{
source = _source;
marker = _marker;
redoFirstTime = true;
}
// undo and redo methods
void itm::QUndoMarkerCreate::undo()
{
/**/itm::debug(itm::LEV1, 0, __itm__current__function__);
// get markers from Vaa3D
QList<LocationSimple> vaa3dMarkers = source->V3D_env->getLandmark(source->window);
// remove the marker just created
for(int i=0; i<vaa3dMarkers.size(); i++)
if(vaa3dMarkers[i].x == marker.x && vaa3dMarkers[i].y == marker.y && vaa3dMarkers[i].z == marker.z)
vaa3dMarkers.removeAt(i);
// set new markers
source->V3D_env->setLandmark(source->window, vaa3dMarkers);
source->V3D_env->pushObjectIn3DWindow(source->window);
//update visible markers
PAnoToolBar::instance()->buttonMarkerRoiViewChecked(PAnoToolBar::instance()->buttonMarkerRoiView->isChecked());
// end select mode
//source->view3DWidget->getRenderer()->endSelectMode();
}
void itm::QUndoMarkerCreate::redo()
{
/**/itm::debug(itm::LEV1, itm::strprintf("redoFirstTime = %s", redoFirstTime ? "true" : "false").c_str(), __itm__current__function__);
// first time redo's call is aborted: we don't want it to be called once the command is pushed into the QUndoStack
if(!redoFirstTime)
{
// get markers from Vaa3D
QList<LocationSimple> vaa3dMarkers = source->V3D_env->getLandmark(source->window);
// add previously deleted marker
vaa3dMarkers.push_back(marker);
// set new markers
source->V3D_env->setLandmark(source->window, vaa3dMarkers);
source->V3D_env->pushObjectIn3DWindow(source->window);
//update visible markers
PAnoToolBar::instance()->buttonMarkerRoiViewChecked(PAnoToolBar::instance()->buttonMarkerRoiView->isChecked());
// end select mode
//source->view3DWidget->getRenderer()->endSelectMode();
}
else
redoFirstTime = false;
}
itm::QUndoVaa3DNeuron::QUndoVaa3DNeuron(itm::CViewer* _source) : QUndoCommand()
{
source = _source;
redoFirstTime = true;
}
// undo and redo methods
void itm::QUndoVaa3DNeuron::undo()
{
/**/itm::debug(itm::LEV1, 0, __itm__current__function__);
if (v3dr_getImage4d(source->view3DWidget->_idep) && source->view3DWidget->renderer)
{
v3dr_getImage4d(source->view3DWidget->_idep)->proj_trace_history_undo();
v3dr_getImage4d(source->view3DWidget->_idep)->update_3drenderer_neuron_view(source->view3DWidget, (Renderer_gl1*)source->view3DWidget->renderer);//090924
source->view3DWidget->update();
}
}
void itm::QUndoVaa3DNeuron::redo()
{
/**/itm::debug(itm::LEV1, itm::strprintf("redoFirstTime = %s", redoFirstTime ? "true" : "false").c_str(), __itm__current__function__);
// first time redo's call is aborted: we don't want it to be called once the command is pushed into the QUndoStack
if(!redoFirstTime)
{
if (v3dr_getImage4d(source->view3DWidget->_idep) && source->view3DWidget->renderer)
{
v3dr_getImage4d(source->view3DWidget->_idep)->proj_trace_history_redo();
v3dr_getImage4d(source->view3DWidget->_idep)->update_3drenderer_neuron_view(source->view3DWidget, (Renderer_gl1*)source->view3DWidget->renderer);//090924
source->view3DWidget->update();
}
}
else
redoFirstTime = false;
}
| 34.230769 | 165 | 0.68736 |
73d2718c9ae9549a1baabb2f2bd5d5452ea611d0 | 5,384 | cpp | C++ | common/fileview2/fvquerysource.cpp | miguelvazq/HPCC-Platform | 22ad8e5fcb59626abfd8febecbdfccb1e9fb0aa5 | [
"Apache-2.0"
] | null | null | null | common/fileview2/fvquerysource.cpp | miguelvazq/HPCC-Platform | 22ad8e5fcb59626abfd8febecbdfccb1e9fb0aa5 | [
"Apache-2.0"
] | 1 | 2018-03-01T18:15:12.000Z | 2018-03-01T18:15:12.000Z | common/fileview2/fvquerysource.cpp | miguelvazq/HPCC-Platform | 22ad8e5fcb59626abfd8febecbdfccb1e9fb0aa5 | [
"Apache-2.0"
] | 3 | 2021-05-02T17:01:57.000Z | 2021-05-02T17:02:28.000Z | /*##############################################################################
HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
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 "jliball.hpp"
#include "eclrtl.hpp"
#include "hqlexpr.hpp"
#include "hqlthql.hpp"
#include "fvresultset.ipp"
#include "fileview.hpp"
#include "fvquerysource.ipp"
#include "fvwugen.hpp"
QueryDataSource::QueryDataSource(IConstWUResult * _wuResult, const char * _wuid, const char * _username, const char * _password)
{
wuResult.set(_wuResult);
wuid.set(_wuid);
username.set(_username);
password.set(_password);
}
QueryDataSource::~QueryDataSource()
{
if (browseWuid)
{
Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
factory->deleteWorkUnit(browseWuid);
}
}
bool QueryDataSource::createBrowseWU()
{
StringAttr dataset, datasetDefs;
StringAttrAdaptor a1(dataset), a2(datasetDefs);
wuResult->getResultDataset(a1, a2);
if (!dataset || !datasetDefs)
return false;
StringBuffer fullText;
fullText.append(datasetDefs).append(dataset);
OwnedHqlExpr parsed = parseQuery(fullText.str());
if (!parsed)
return false;
HqlExprAttr selectFields = parsed.getLink();
if (selectFields->getOperator() == no_output)
selectFields.set(selectFields->queryChild(0));
OwnedHqlExpr browseWUcode = buildQueryViewerEcl(selectFields);
if (!browseWUcode)
return false;
returnedRecord.set(browseWUcode->queryChild(0)->queryRecord());
Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
Owned<IConstWorkUnit> parent = factory->openWorkUnit(wuid);
const char *user = parent->queryUser();
Owned<IWorkUnit> workunit = factory->createWorkUnit("fileViewer", user);
workunit->setUser(user);
workunit->setClusterName(parent->queryClusterName());
browseWuid.set(workunit->queryWuid());
workunit->setDebugValueInt("importImplicitModules", false, true);
workunit->setDebugValueInt("importAllModules", false, true);
workunit->setDebugValueInt("forceFakeThor", 1, true);
StringBuffer jobName;
jobName.append("FileView for ").append(wuid).append(":").append("x");
workunit->setJobName(jobName.str());
StringBuffer eclText;
toECL(browseWUcode, eclText, true);
Owned<IWUQuery> query = workunit->updateQuery();
query->setQueryText(eclText.str());
query->setQueryName(jobName.str());
return true;
}
bool QueryDataSource::init()
{
return createBrowseWU();
}
void QueryDataSource::improveLocation(__int64 row, RowLocation & location)
{
#if 0
if (!diskMeta->isFixedSize())
return;
if (location.bestRow <= row && location.bestRow + DISKREAD_PAGE_SIZE > row)
return;
assertex(row >= 0);
//Align the row so the chunks don't overlap....
location.bestRow = (row / DISKREAD_PAGE_SIZE) * DISKREAD_PAGE_SIZE;
location.bestOffset = location.bestRow * diskMeta->fixedSize();
#endif
}
bool QueryDataSource::loadBlock(__int64 startRow, offset_t startOffset)
{
MemoryBuffer temp;
//enter scope....>
{
Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
Owned<IWorkUnit> wu = factory->updateWorkUnit(browseWuid);
Owned<IWUResult> lower = wu->updateVariableByName(LOWER_LIMIT_ID);
lower->setResultInt(startOffset);
lower->setResultStatus(ResultStatusSupplied);
Owned<IWUResult> dataResult = wu->updateResultBySequence(0);
dataResult->setResultRaw(0, NULL, ResultFormatRaw);
dataResult->setResultStatus(ResultStatusUndefined);
wu->clearExceptions();
if (wu->getState() != WUStateUnknown)
wu->setState(WUStateCompiled);
//Owned<IWUResult> count = wu->updateVariableByName(RECORD_LIMIT_ID);
//count->setResultInt64(fetchSize);
}
//Resubmit the query...
submitWorkUnit(browseWuid, username, password);
WUState finalState = waitForWorkUnitToComplete(browseWuid, -1, true);
if(!((finalState == WUStateCompleted) || (finalState == WUStateWait)))
return false;
//Now extract the results...
Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
Owned<IConstWorkUnit> wu = factory->openWorkUnit(browseWuid);
Owned<IConstWUResult> dataResult = wu->getResultBySequence(0);
MemoryBuffer2IDataVal xxx(temp); dataResult->getResultRaw(xxx, NULL, NULL);
if (temp.length() == 0)
return false;
RowBlock * rows;
if (returnedMeta->isFixedSize())
rows = new FilePosFixedRowBlock(temp, startRow, startOffset, returnedMeta->fixedSize());
else
rows = new FilePosVariableRowBlock(temp, startRow, startOffset, returnedMeta, true);
cache.addRowsOwn(rows);
return true;
}
| 31.670588 | 128 | 0.678492 |
73d672c11d2ba0f1999c1eb76be54c5848c0e9d4 | 380 | cpp | C++ | predavanje5/vector12.cpp | Miillky/algoritmi_i_strukture_podataka | b5813f4b897a1370b6f46782bf5ecd474d0d7e20 | [
"MIT"
] | null | null | null | predavanje5/vector12.cpp | Miillky/algoritmi_i_strukture_podataka | b5813f4b897a1370b6f46782bf5ecd474d0d7e20 | [
"MIT"
] | null | null | null | predavanje5/vector12.cpp | Miillky/algoritmi_i_strukture_podataka | b5813f4b897a1370b6f46782bf5ecd474d0d7e20 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using std::cout;
using std::endl;
using std::vector;
int main(){
vector <int> polje = {5,6,7};
vector <int>::iterator it; // iterator it ćemo koristit za pristup pojedinim elementima
it = polje.begin(); // nije istokao front()!
cout << *it << endl;
it = polje.end(); // nije istokao front()!
cout << *it << endl;
} | 22.352941 | 91 | 0.613158 |
73d80f96d5421a87f7fe89992e14e228f26355b3 | 15,621 | cpp | C++ | _studio/shared/umc/codec/vc1_dec/src/umc_vc1_video_decoder_hw.cpp | chuanli1/oneVPL-intel-gpu | 9d337b4add45f861f0307dc75fa1e50786b73462 | [
"MIT"
] | null | null | null | _studio/shared/umc/codec/vc1_dec/src/umc_vc1_video_decoder_hw.cpp | chuanli1/oneVPL-intel-gpu | 9d337b4add45f861f0307dc75fa1e50786b73462 | [
"MIT"
] | null | null | null | _studio/shared/umc/codec/vc1_dec/src/umc_vc1_video_decoder_hw.cpp | chuanli1/oneVPL-intel-gpu | 9d337b4add45f861f0307dc75fa1e50786b73462 | [
"MIT"
] | null | null | null | // Copyright (c) 2004-2019 Intel Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include "umc_defs.h"
#if defined (MFX_ENABLE_VC1_VIDEO_DECODE)
#include "umc_vc1_video_decoder_hw.h"
#include "umc_video_data.h"
#include "umc_media_data_ex.h"
#include "umc_vc1_dec_debug.h"
#include "umc_vc1_dec_seq.h"
#include "vm_sys_info.h"
#include "umc_vc1_dec_task_store.h"
#include "umc_memory_allocator.h"
#include "umc_vc1_common.h"
#include "umc_vc1_common_defs.h"
#include "umc_vc1_dec_exception.h"
#include "umc_va_base.h"
#include "umc_vc1_dec_frame_descr_va.h"
using namespace UMC;
using namespace UMC::VC1Common;
using namespace UMC::VC1Exceptions;
VC1VideoDecoderHW::VC1VideoDecoderHW():
m_stCodes_VA(NULL)
{
}
VC1VideoDecoderHW::~VC1VideoDecoderHW()
{
Close();
}
Status VC1VideoDecoderHW::Init(BaseCodecParams *pInit)
{
VideoDecoderParams *init = DynamicCast<VideoDecoderParams, BaseCodecParams>(pInit);
if (!init)
return UMC_ERR_INIT;
if (init->pVideoAccelerator)
{
if ((init->pVideoAccelerator->m_Profile & VA_CODEC) == VA_VC1)
m_va = init->pVideoAccelerator;
else
return UMC_ERR_UNSUPPORTED;
}
Status umcRes = UMC_OK;
umcRes = VC1VideoDecoder::Init(pInit);
if (umcRes != UMC_OK)
return umcRes;
try
// memory allocation and Init all env for frames/tasks store - VC1TaskStore object
{
m_pStore = new(m_pHeap->s_alloc<VC1TaskStore>()) VC1TaskStore(m_pMemoryAllocator);
if (!m_pStore->Init(m_iThreadDecoderNum,
m_iMaxFramesInProcessing,
this) )
return UMC_ERR_ALLOC;
m_pStore->CreateDSQueue(m_pContext,m_va);
}
catch(...)
{
// only allocation errors here
Close();
return UMC_ERR_ALLOC;
}
return umcRes;
}
Status VC1VideoDecoderHW::Reset(void)
{
Status umcRes = VC1VideoDecoder::Reset();
if (umcRes != UMC_OK)
return umcRes;
if (m_pStore)
{
if (!m_pStore->Reset())
return UMC_ERR_NOT_INITIALIZED;
m_pStore->CreateDSQueue(&m_pInitContext, m_va);
}
return UMC_OK;
}
bool VC1VideoDecoderHW::InitVAEnvironment()
{
m_pContext->m_frmBuff.m_pFrames.Reset(m_FrameStorage);
SetVideoHardwareAccelerator(m_va);
return true;
}
uint32_t VC1VideoDecoderHW::CalculateHeapSize()
{
uint32_t Size = 0;
Size += mfx::align2_value<uint32_t>(sizeof(VC1TaskStore));
if (!m_va)
Size += mfx::align2_value<uint32_t>(sizeof(Frame)*(2*m_iMaxFramesInProcessing + 2*VC1NUMREFFRAMES));
else
Size += mfx::align2_value<uint32_t>(sizeof(Frame)*(m_SurfaceNum));
Size += mfx::align2_value<uint32_t>(sizeof(MediaDataEx));
return Size;
}
Status VC1VideoDecoderHW::Close(void)
{
Status umcRes = UMC_OK;
m_AllocBuffer = 0;
// reset all values
umcRes = Reset();
if (m_pStore)
{
m_pStore->~VC1TaskStore();
m_pStore = nullptr;
}
FreeAlloc(m_pContext);
if(m_pMemoryAllocator)
{
if (static_cast<int>(m_iMemContextID) != -1)
{
m_pMemoryAllocator->Unlock(m_iMemContextID);
m_pMemoryAllocator->Free(m_iMemContextID);
m_iMemContextID = (MemID)-1;
}
if (static_cast<int>(m_iHeapID) != -1)
{
m_pMemoryAllocator->Unlock(m_iHeapID);
m_pMemoryAllocator->Free(m_iHeapID);
m_iHeapID = (MemID)-1;
}
if (static_cast<int>(m_iFrameBufferID) != -1)
{
m_pMemoryAllocator->Unlock(m_iFrameBufferID);
m_pMemoryAllocator->Free(m_iFrameBufferID);
m_iFrameBufferID = (MemID)-1;
}
}
m_pContext = NULL;
m_dataBuffer = NULL;
m_stCodes = NULL;
m_frameData = NULL;
m_pHeap = NULL;
memset(&m_pInitContext,0,sizeof(VC1Context));
m_pMemoryAllocator = 0;
if (m_stCodes_VA)
{
free(m_stCodes_VA);
m_stCodes_VA = NULL;
}
m_pStore = NULL;
m_pContext = NULL;
m_iThreadDecoderNum = 0;
m_decoderInitFlag = 0;
m_decoderFlags = 0;
return umcRes;
}
void VC1VideoDecoderHW::SetVideoHardwareAccelerator (VideoAccelerator* va)
{
if (va)
m_va = (VideoAccelerator*)va;
}
bool VC1VideoDecoderHW::InitAlloc(VC1Context* pContext, uint32_t )
{
if (!InitTables(pContext))
return false;
pContext->m_frmBuff.m_iDisplayIndex = -1;
pContext->m_frmBuff.m_iCurrIndex = -1;
pContext->m_frmBuff.m_iPrevIndex = -1;
pContext->m_frmBuff.m_iNextIndex = -1;
pContext->m_frmBuff.m_iBFrameIndex = -1;
pContext->m_frmBuff.m_iRangeMapIndex = -1;
pContext->m_frmBuff.m_iRangeMapIndexPrev = -1;
m_bLastFrameNeedDisplay = true;
//for slice, field start code
if (m_stCodes_VA == NULL)
{
m_stCodes_VA = (MediaDataEx::_MediaDataEx *)malloc(START_CODE_NUMBER * 2 * sizeof(int32_t) + sizeof(MediaDataEx::_MediaDataEx));
if (m_stCodes_VA == NULL)
return false;
memset(reinterpret_cast<void*>(m_stCodes_VA), 0, (START_CODE_NUMBER * 2 * sizeof(int32_t) + sizeof(MediaDataEx::_MediaDataEx)));
m_stCodes_VA->count = 0;
m_stCodes_VA->index = 0;
m_stCodes_VA->bstrm_pos = 0;
m_stCodes_VA->offsets = (uint32_t*)((uint8_t*)m_stCodes_VA +
sizeof(MediaDataEx::_MediaDataEx));
m_stCodes_VA->values = (uint32_t*)((uint8_t*)m_stCodes_VA->offsets +
START_CODE_NUMBER * sizeof(uint32_t));
}
return true;
}
void VC1VideoDecoderHW::GetStartCodes_HW(MediaData* in, uint32_t &sShift)
{
uint8_t* readPos = (uint8_t*)in->GetBufferPointer();
uint32_t readBufSize = (uint32_t)in->GetDataSize();
uint8_t* readBuf = (uint8_t*)in->GetBufferPointer();
uint32_t frameSize = 0;
MediaDataEx::_MediaDataEx *stCodes = m_stCodes_VA;
stCodes->count = 0;
sShift = 0;
uint32_t size = 0;
uint8_t* ptr = NULL;
uint32_t readDataSize = 0;
uint32_t a = 0x0000FF00 | (*readPos);
uint32_t b = 0xFFFFFFFF;
uint32_t FrameNum = 0;
memset(stCodes->offsets, 0, START_CODE_NUMBER * sizeof(int32_t));
memset(stCodes->values, 0, START_CODE_NUMBER * sizeof(int32_t));
while (readPos < (readBuf + readBufSize))
{
if (stCodes->count > 512)
return;
//find sequence of 0x000001 or 0x000003
while (!(b == 0x00000001 || b == 0x00000003)
&& (++readPos < (readBuf + readBufSize)))
{
a = (a << 8) | (int32_t)(*readPos);
b = a & 0x00FFFFFF;
}
//check end of read buffer
if (readPos < (readBuf + readBufSize - 1))
{
if (*readPos == 0x01)
{
if ((*(readPos + 1) == VC1_Slice) ||
(*(readPos + 1) == VC1_Field) ||
(*(readPos + 1) == VC1_FrameHeader) ||
(*(readPos + 1) == VC1_SliceLevelUserData) ||
(*(readPos + 1) == VC1_FieldLevelUserData) ||
(*(readPos + 1) == VC1_FrameLevelUserData)
)
{
readPos += 2;
ptr = readPos - 5;
size = (uint32_t)(ptr - readBuf - readDataSize + 1);
frameSize = frameSize + size;
stCodes->offsets[stCodes->count] = frameSize;
if (FrameNum)
sShift = 1;
stCodes->values[stCodes->count] = ((*(readPos - 1)) << 24) + ((*(readPos - 2)) << 16) + ((*(readPos - 3)) << 8) + (*(readPos - 4));
readDataSize = (uint32_t)(readPos - readBuf - 4);
a = 0x00010b00 | (int32_t)(*readPos);
b = a & 0x00FFFFFF;
stCodes->count++;
}
else
{
{
readPos += 2;
ptr = readPos - 5;
//trim zero bytes
if (stCodes->count)
{
while ((*ptr == 0) && (ptr > readBuf))
ptr--;
}
//slice or field size
size = (uint32_t)(readPos - readBuf - readDataSize - 4);
frameSize = frameSize + size;
readDataSize = readDataSize + size;
FrameNum++;
}
}
}
else //if(*readPos == 0x03)
{
readPos++;
a = (a << 8) | (int32_t)(*readPos);
b = a & 0x00FFFFFF;
}
}
else
{
//end of stream
size = (uint32_t)(readPos - readBuf - readDataSize);
readDataSize = readDataSize + size;
return;
}
}
}
Status VC1VideoDecoderHW::FillAndExecute(MediaData* in)
{
uint32_t stShift = 0;
int32_t SCoffset = 0;
if ((VC1_PROFILE_ADVANCED != m_pContext->m_seqLayerHeader.PROFILE))
// special header (with frame size) in case of .rcv format
SCoffset = -VC1FHSIZE;
VC1FrameDescriptor* pPackDescriptorChild = m_pStore->GetLastDS();
pPackDescriptorChild->m_bIsFieldAbsent = false;
if ((!VC1_IS_SKIPPED(pPackDescriptorChild->m_pContext->m_picLayerHeader->PTYPE)) &&
(VC1_PROFILE_ADVANCED == m_pContext->m_seqLayerHeader.PROFILE))
{
GetStartCodes_HW(in, stShift);
if (stShift) // we begin since start code frame in case of external MS splitter
{
SCoffset -= *m_stCodes_VA->offsets;
pPackDescriptorChild->m_pContext->m_FrameSize -= *m_stCodes_VA->offsets;
}
}
try
{
pPackDescriptorChild->PrepareVLDVABuffers(m_pContext->m_Offsets,
m_pContext->m_values,
(uint8_t*)in->GetDataPointer() - SCoffset,
m_stCodes_VA + stShift);
}
catch (vc1_exception ex)
{
exception_type e_type = ex.get_exception_type();
if (mem_allocation_er == e_type)
return UMC_ERR_NOT_ENOUGH_BUFFER;
}
if (!VC1_IS_SKIPPED(pPackDescriptorChild->m_pContext->m_picLayerHeader->PTYPE))
{
if (UMC_OK != m_va->EndFrame())
throw VC1Exceptions::vc1_exception(VC1Exceptions::internal_pipeline_error);
}
in->MoveDataPointer(pPackDescriptorChild->m_pContext->m_FrameSize);
if (pPackDescriptorChild->m_pContext->m_picLayerHeader->FCM == VC1_FieldInterlace && m_stCodes_VA->count < 2)
pPackDescriptorChild->m_bIsFieldAbsent = true;
if ((VC1_PROFILE_ADVANCED != m_pContext->m_seqLayerHeader.PROFILE))
{
m_pContext->m_seqLayerHeader.RNDCTRL = pPackDescriptorChild->m_pContext->m_seqLayerHeader.RNDCTRL;
}
return UMC_OK;
}
Status VC1VideoDecoderHW::VC1DecodeFrame(MediaData* in, VideoData* out_data)
{
(void)in;
(void)out_data;
if (m_va->m_Profile == VC1_VLD)
{
return VC1DecodeFrame_VLD<VC1FrameDescriptorVA_Linux<VC1PackerLVA> >(in, out_data);
}
return UMC_ERR_FAILED;
}
FrameMemID VC1VideoDecoderHW::ProcessQueuesForNextFrame(bool& isSkip, mfxU16& Corrupted)
{
FrameMemID currIndx = -1;
UMC::VC1FrameDescriptor *pCurrDescriptor = 0;
UMC::VC1FrameDescriptor *pTempDescriptor = 0;
m_RMIndexToFree = -1;
m_CurrIndexToFree = -1;
pCurrDescriptor = m_pStore->GetFirstDS();
// free first descriptor
m_pStore->SetFirstBusyDescriptorAsReady();
if (!m_pStore->GetPerformedDS(&pTempDescriptor))
m_pStore->GetReadySkippedDS(&pTempDescriptor);
if (pCurrDescriptor)
{
SetCorrupted(pCurrDescriptor, Corrupted);
if (VC1_IS_SKIPPED(pCurrDescriptor->m_pContext->m_picLayerHeader->PTYPE))
{
isSkip = true;
if (!pCurrDescriptor->isDescriptorValid())
{
return currIndx;
}
else
{
currIndx = m_pStore->GetIdx(pCurrDescriptor->m_pContext->m_frmBuff.m_iCurrIndex);
}
// Range Map
if ((pCurrDescriptor->m_pContext->m_seqLayerHeader.RANGE_MAPY_FLAG) ||
(pCurrDescriptor->m_pContext->m_seqLayerHeader.RANGE_MAPUV_FLAG))
{
currIndx = m_pStore->GetIdx(pCurrDescriptor->m_pContext->m_frmBuff.m_iRangeMapIndex);
}
m_pStore->UnLockSurface(pCurrDescriptor->m_pContext->m_frmBuff.m_iToSkipCoping);
return currIndx;
}
else
{
currIndx = m_pStore->GetIdx(pCurrDescriptor->m_pContext->m_frmBuff.m_iCurrIndex);
// We should unlock after LockRect in PrepareOutPut function
if ((pCurrDescriptor->m_pContext->m_seqLayerHeader.RANGE_MAPY_FLAG) ||
(pCurrDescriptor->m_pContext->m_seqLayerHeader.RANGE_MAPUV_FLAG) ||
(pCurrDescriptor->m_pContext->m_seqLayerHeader.RANGERED))
{
if (!VC1_IS_REFERENCE(pCurrDescriptor->m_pContext->m_picLayerHeader->PTYPE))
{
currIndx = m_pStore->GetIdx(pCurrDescriptor->m_pContext->m_frmBuff.m_iRangeMapIndex);
m_RMIndexToFree = pCurrDescriptor->m_pContext->m_frmBuff.m_iRangeMapIndex;
}
else
{
currIndx = m_pStore->GetIdx(pCurrDescriptor->m_pContext->m_frmBuff.m_iRangeMapIndex);
m_RMIndexToFree = pCurrDescriptor->m_pContext->m_frmBuff.m_iRangeMapIndexPrev;
}
}
// Asynchrony Unlock
if (!VC1_IS_REFERENCE(pCurrDescriptor->m_pContext->m_picLayerHeader->PTYPE))
m_CurrIndexToFree = pCurrDescriptor->m_pContext->m_frmBuff.m_iDisplayIndex;
else
{
if (pCurrDescriptor->m_pContext->m_frmBuff.m_iToFreeIndex > -1)
m_CurrIndexToFree = pCurrDescriptor->m_pContext->m_frmBuff.m_iToFreeIndex;
}
}
}
return currIndx;
}
Status VC1VideoDecoderHW::SetRMSurface()
{
Status sts;
sts = VC1VideoDecoder::SetRMSurface();
UMC_CHECK_STATUS(sts);
FillAndExecute(m_pCurrentIn);
return UMC_OK;
}
UMC::FrameMemID VC1VideoDecoderHW::GetSkippedIndex(bool isIn)
{
return VC1VideoDecoder::GetSkippedIndex(m_pStore->GetLastDS(), isIn);
}
#endif //MFX_ENABLE_VC1_VIDEO_DECODE
| 30.629412 | 151 | 0.605147 |
73d9c024579bede1257529c1ffc856074b6b47c2 | 2,679 | cpp | C++ | modules/task_4/iamshchikov_i_sparse_matrix_mult/main.cpp | 381706-1-DenisovVladislavL/pp_2020_spring | 52d640bd274920b1664414a5f9b0f27da6707f7d | [
"BSD-3-Clause"
] | 1 | 2020-04-21T04:02:06.000Z | 2020-04-21T04:02:06.000Z | modules/task_4/iamshchikov_i_sparse_matrix_mult/main.cpp | 381706-1-DenisovVladislavL/pp_2020_spring | 52d640bd274920b1664414a5f9b0f27da6707f7d | [
"BSD-3-Clause"
] | 1 | 2020-05-16T09:02:12.000Z | 2020-05-16T09:02:12.000Z | modules/task_4/iamshchikov_i_sparse_matrix_mult/main.cpp | 381706-1-DenisovVladislavL/pp_2020_spring | 52d640bd274920b1664414a5f9b0f27da6707f7d | [
"BSD-3-Clause"
] | 3 | 2020-07-28T13:12:29.000Z | 2021-03-24T20:22:40.000Z | // Copyright 2020 Iamshchikov Ivan
#include <gtest/gtest.h>
#include <thread>
#include <random>
#include <ctime>
#include <cmath>
#include "../../modules/task_4/iamshchikov_i_sparse_matrix_mult/sparse_matrix_mult.h"
TEST(sparse_matrix_mult_std, can_create_matrix) {
ASSERT_NO_THROW(CcsMatrix m(1, 1, 1));
}
TEST(sparse_matrix_mult_std, throw_when_number_of_rows_are_not_positive) {
ASSERT_ANY_THROW(CcsMatrix m(-3, 1, 1));
}
TEST(sparse_matrix_mult_std, throw_when_number_of_columns_are_not_positive) {
ASSERT_ANY_THROW(CcsMatrix m(1, 0, 1));
}
TEST(sparse_matrix_mult_std, throw_when_number_of_elements_are_not_positive) {
ASSERT_ANY_THROW(CcsMatrix m(1, 0, -3));
}
TEST(sparse_matrix_mult_std, multiply_vector_by_vector) {
CcsMatrix m1(5, 1, 2);
m1.value = { 2, 1 };
m1.row = { 1, 2 };
m1.colIndex = { 0, 2 };
CcsMatrix m2(1, 4, 1);
m2.value = { 3 };
m2.row = { 0 };
m2.colIndex = { 0, 0, 0, 1, 1 };
CcsMatrix m3(5, 4, 2);
m3.value = { 6, 3 };
m3.row = { 1, 2 };
m3.colIndex = { 0, 0, 0, 2, 2 };
EXPECT_EQ(m3, matrixMultiplicate(&m1, &m2));
}
TEST(sparse_matrix_mult_std, multiply_matrix_by_vector) {
CcsMatrix m1(4, 5, 6);
m1.value = { 1, 3, 2, 5, 4, 8 };
m1.row = { 0, 3, 1, 2, 3, 0 };
m1.colIndex = { 0, 1, 2, 3, 5, 6 };
CcsMatrix m2(5, 1, 2);
m2.value = { 2, 1 };
m2.row = { 1, 2 };
m2.colIndex = { 0, 2 };
CcsMatrix m3(4, 1, 2);
m3.value = { 2, 6 };
m3.row = { 1, 3 };
m3.colIndex = { 0, 2 };
EXPECT_EQ(m3, matrixMultiplicate(&m1, &m2));
}
TEST(sparse_matrix_mult_std, multiply_vector_by_matrix) {
CcsMatrix m1(1, 4, 2);
m1.value = { 2, 1 };
m1.row = { 0, 0 };
m1.colIndex = { 0, 0, 1, 2, 2 };
CcsMatrix m2(4, 5, 6);
m2.value = { 1, 3, 2, 5, 4, 8 };
m2.row = { 0, 3, 1, 2, 3, 0 };
m2.colIndex = { 0, 1, 2, 3, 5, 6 };
CcsMatrix m3(1, 5, 2);
m3.value = { 4, 5 };
m3.row = { 0 , 0 };
m3.colIndex = { 0, 0, 0, 1, 2, 2 };
EXPECT_EQ(m3, matrixMultiplicate(&m1, &m2));
}
TEST(sparse_matrix_mult_std, multiply_matrix_by_matrix) {
CcsMatrix m1(4, 5, 6);
m1.value = { 1, 3, 2, 5, 4, 8 };
m1.row = { 0, 3, 1, 2, 3, 0 };
m1.colIndex = { 0, 1, 2, 3, 5, 6 };
CcsMatrix m2(5, 3, 5);
m2.value = { 1, 6, 3, 7, 2 };
m2.row = { 0, 4, 3, 1, 4 };
m2.colIndex = { 0, 2, 3, 5 };
CcsMatrix m3(4, 3, 5);
m3.value = { 49, 15, 12, 16, 21 };
m3.row = { 0, 2, 3, 0, 3 };
m3.colIndex = { 0, 1, 3, 5 };
EXPECT_EQ(m3, matrixMultiplicate(&m1, &m2));
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 25.514286 | 85 | 0.565136 |
73da3b2c1344576195b3a8cba5bc888b9b56d40b | 4,681 | cpp | C++ | src/location.cpp | smu-sc-gj/aicore | b313065e25851a974a3b061ca12595a1fa88d7be | [
"MIT"
] | 412 | 2015-01-05T01:06:31.000Z | 2022-03-08T08:13:36.000Z | src/location.cpp | smu-sc-gj/aicore | b313065e25851a974a3b061ca12595a1fa88d7be | [
"MIT"
] | 6 | 2015-04-18T17:53:13.000Z | 2021-03-29T17:01:23.000Z | src/location.cpp | smu-sc-gj/aicore | b313065e25851a974a3b061ca12595a1fa88d7be | [
"MIT"
] | 141 | 2015-01-11T11:39:48.000Z | 2022-03-24T16:53:15.000Z | /*
* Defines the state classes used for steering.
*
* Part of the Artificial Intelligence for Games system.
*
* Copyright (c) Ian Millington 2003-2006. All Rights Reserved.
*
* This software is distributed under licence. Use of this software
* implies agreement with all terms and conditions of the accompanying
* software licence.
*/
#include <aicore/aicore.h>
namespace aicore
{
/*
* This is messy, but it saves a function call or code duplication.
*/
#define SIMPLE_INTEGRATION(duration, velocity, rotation) \
position.x += (velocity).x*duration; \
position.y += (velocity).y*duration; \
position.z += (velocity).z*duration; \
orientation += (rotation)*duration; \
orientation = real_mod_real(orientation, M_2PI);
/*
* Uses SIMPLE_INTEGRATION(duration), defined above.
*/
void Location::integrate(const SteeringOutput& steer, real duration)
{
SIMPLE_INTEGRATION(duration, steer.linear, steer.angular);
}
void Location::setOrientationFromVelocity(const Vector3& velocity)
{
// If we haven't got any velocity, then we can do nothing.
if (velocity.squareMagnitude() > 0) {
orientation = real_atan2(velocity.x, velocity.z);
}
}
Vector3 Location::getOrientationAsVector() const
{
return Vector3(real_sin(orientation),
0,
real_cos(orientation));
}
/*
* Uses SIMPLE_INTEGRATION(duration), defined above.
*/
void Kinematic::integrate(real duration)
{
SIMPLE_INTEGRATION(duration, velocity, rotation);
}
/*
* Uses SIMPLE_INTEGRATION(duration), defined above.
*/
void Kinematic::integrate(const SteeringOutput& steer,
real duration)
{
SIMPLE_INTEGRATION(duration, velocity, rotation);
velocity.x += steer.linear.x*duration;
velocity.y += steer.linear.y*duration;
velocity.z += steer.linear.z*duration;
rotation += steer.angular*duration;
}
/*
* Uses SIMPLE_INTEGRATION(duration), defined above.
*/
void Kinematic::integrate(const SteeringOutput& steer,
real drag,
real duration)
{
SIMPLE_INTEGRATION(duration, velocity, rotation);
// Slowing velocity and rotational velocity
drag = real_pow(drag, duration);
velocity *= drag;
rotation *= drag*drag;
velocity.x += steer.linear.x*duration;
velocity.y += steer.linear.y*duration;
velocity.z += steer.linear.z*duration;
rotation += steer.angular*duration;
}
/*
* Uses SIMPLE_INTEGRATION(duration), defined above.
*/
void Kinematic::integrate(const SteeringOutput& steer,
const SteeringOutput& drag,
real duration)
{
SIMPLE_INTEGRATION(duration, velocity, rotation);
velocity.x *= real_pow(drag.linear.x, duration);
velocity.y *= real_pow(drag.linear.y, duration);
velocity.z *= real_pow(drag.linear.z, duration);
rotation *= real_pow(drag.angular, duration);
velocity.x += steer.linear.x*duration;
velocity.y += steer.linear.y*duration;
velocity.z += steer.linear.z*duration;
rotation += steer.angular*duration;
}
/* Add and divide used in finding Kinematic means. */
void Kinematic::operator += (const Kinematic& other)
{
position+=other.position;
velocity+=other.velocity;
rotation+=other.rotation;
orientation+=other.orientation;
}
void Kinematic::operator -= (const Kinematic& other)
{
position-=other.position;
velocity-=other.velocity;
rotation-=other.rotation;
orientation-=other.orientation;
}
void Kinematic::operator *= (real f)
{
position*=f;
velocity*=f;
rotation*=f;
orientation*=f;
}
void Kinematic::trimMaxSpeed(real maxSpeed)
{
if (velocity.squareMagnitude() > maxSpeed*maxSpeed) {
velocity.normalise();
velocity *= maxSpeed;
}
}
void Kinematic::setOrientationFromVelocity()
{
// If we haven't got any velocity, then we can do nothing.
if (velocity.squareMagnitude() > 0) {
orientation = real_atan2(velocity.x, velocity.z);
}
}
}; // end of namespace
| 30.00641 | 73 | 0.582995 |
73db55f6b2456faf9da66c82baad16c7f557be4a | 9,059 | hpp | C++ | src/plugins/intel_gpu/include/intel_gpu/primitives/loop.hpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 1,127 | 2018-10-15T14:36:58.000Z | 2020-04-20T09:29:44.000Z | src/plugins/intel_gpu/include/intel_gpu/primitives/loop.hpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 439 | 2018-10-20T04:40:35.000Z | 2020-04-19T05:56:25.000Z | src/plugins/intel_gpu/include/intel_gpu/primitives/loop.hpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 414 | 2018-10-17T05:53:46.000Z | 2020-04-16T17:29:53.000Z | // Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
#include <vector>
#include <functional>
#include "primitive.hpp"
#include "intel_gpu/graph/topology.hpp"
#define DEFAULT_MAX_NUM_ITERATION 256
namespace cldnn {
/// @addtogroup cpp_api C++ API
/// @{
/// @addtogroup cpp_topology Network Topology
/// @{
/// @addtogroup cpp_primitives Primitives
/// @{
///
/// @brief Adds primitive which performs recurrent execution of the topology.
///
/// @details
/// @n The body topology for recurrent execution is described in the body
/// @n The execution of the body topology iterates through the data in the given axis.
/// @n Note: that only loops with fixed iteration count are being validated and supported currently.
/// @n
/// @n\b Example:
/// \code{.cpp}
/// topology body(
/// data("eltwise_operand", operand_mem),
/// eltwise("eltwise", "input", "eltwise_operand", eltwise_mode::sum)
/// );
///
/// std::vector<loop::io_primitive_map> input_primitive_maps { loop::io_primitive_map("input", "input") };
/// std::vector<loop::io_primitive_map> output_primitive_maps { loop::io_primitive_map("loop", "eltwise") };
///
/// std::vector<loop::backedge_mapping> back_edges {
/// loop::backedge_mapping("eltwise", "input")
/// };
///
/// topology topology(
/// input_layout("input", input_mem.get_layout()),
/// input_layout("trip_count", trip_count_mem.get_layout()),
/// input_layout("initial_condition", initial_condition_mem.get_layout()),
/// mutable_data("num_iteration", num_iteration_mem),
/// loop("loop", {"input"}, body,
/// "trip_count", "initial_condition", "num_iteration",
/// input_primitive_maps, output_primitive_maps, back_edges)
/// );
///
/// network network(engine, topology);
/// network.set_input_data("input", input_mem);
/// network.set_input_data("trip_count", trip_count_mem);
/// network.set_input_data("initial_condition", initial_condition_mem);
/// \endcode
struct loop : public primitive_base<loop> {
CLDNN_DECLARE_PRIMITIVE(loop)
struct io_primitive_map {
/// @brief Constructs a mapping from external input/output primitive to input/output primitive in body topology
///
/// @param external_id Primitive id of input of loop or output of body network.
/// @param internal_id Primitive id of input of body network.
/// @param axis Axis to iterate through. Negative value means the axis will not iterate through and start, end, stride arguments will be ignored.
/// @param start Index where the iteration starts from. Applies only when axis >=0.
/// @param end Index where iteration ends. Negative value means counting indexes from the end. Applies only when axis >=0.
/// @param stride Step of iteration. Negative value means backward iteration. Applies only when axis >=0.
io_primitive_map(primitive_id external_id, primitive_id internal_id,
int64_t axis = -1, int64_t start = 0, int64_t end = -1, int64_t stride = 1) :
external_id(external_id),
internal_id(internal_id),
axis(axis),
start(start),
end(end),
stride(stride)
{}
primitive_id external_id;
primitive_id internal_id;
int64_t axis;
int64_t start;
int64_t end;
int64_t stride;
};
struct backedge_mapping {
/// @brief Constructs a mapping from output of body topology to input of body topology for the next iteration
///
/// @param from Output data primitive id of body topology
/// @param to Input data primitive id of body topology
backedge_mapping(primitive_id from, primitive_id to)
: from(from), to(to) {}
primitive_id from;
primitive_id to;
};
/// @brief Constructs loop primitive.
///
/// @param id This primitive id.
/// @param inputs Input data primitive ids.
/// @param body Topology to be recurrently executed.
/// @param trip_count_id Data primitive id in external topology specifying maximum number of iterations.
/// Its data primitive should have 1 integer element. Negative value means infinite
/// number of iteration.
/// @param initial_condition_id Data primitive id in external topology specifying initial execution
/// condition. Its data primitive should have 1 integer element. Zero means
/// loop will not be executed, otherwise loop will be executed.
/// @param num_iteration_id mutable_data primitive id to get the actual number of loop iterations.
/// @param current_iteration_id Optional data primitive id in the body network to specify current iteration.
/// If current_iteration_id is specified but body does not have data whose primitive
/// id is same as current_iteration_id, data primitive will be added in the body network.
/// @param condition_id Optional data primitive id in the body network to specify execution condition
/// for the next iteration. Its data primitive should have 1 integer element. Zero means
/// loop will not be executed, otherwise loop will be executed. If condition_id
/// is specified but body does not have data whose primitive id is same as condition_id,
/// data primitive will be added in the body network.
/// @param primitive_map Rules to map input of loop or output of body topology to input of the body topology
/// @param back_edges Output data primitive id.
/// @param output_padding Optional padding for output from primitive.
loop(const primitive_id& id,
const std::vector<primitive_id>& inputs,
const topology& body,
const primitive_id& trip_count_id,
const primitive_id& initial_condition_id,
const primitive_id& num_iteration_id,
const std::vector<io_primitive_map>& input_primitive_maps,
const std::vector<io_primitive_map>& output_primitive_maps,
const std::vector<backedge_mapping>& back_edges,
int64_t max_iteration = -1,
const primitive_id& current_iteration_id = primitive_id(),
const primitive_id& condition_id = primitive_id(),
const primitive_id& ext_prim_id = "",
const padding& output_padding = padding())
: primitive_base(id, inputs, ext_prim_id, output_padding),
body(body),
trip_count_id(trip_count_id),
initial_execution_id(initial_condition_id),
num_iteration_id(num_iteration_id),
current_iteration_id(current_iteration_id),
condition_id(condition_id),
input_primitive_maps(input_primitive_maps),
output_primitive_maps(output_primitive_maps),
back_edges(back_edges),
max_iteration(max_iteration)
{}
/// @brief Topology to be recurrently executed.
topology body;
/// @brief Data primitive id in external topology specifying maximum number of iterations.
primitive_id trip_count_id;
/// @brief Data primitive id in external topology specifying initial execution condition.
primitive_id initial_execution_id;
/// @brief mutable_data primitive id to get the actual number of loop iterations.
primitive_id num_iteration_id;
/// @brief Data primitive id in the body network to store current iteration
primitive_id current_iteration_id;
/// @brief Data primitive id in the body network to store execution condition
primitive_id condition_id;
/// @brief Rules to map input or output data of loop layer onto input or output data of body topology.
std::vector<io_primitive_map> input_primitive_maps;
std::vector<io_primitive_map> output_primitive_maps;
/// @brief Rules to transfer data from body outputs at one iteration to body input at the next iteration.
std::vector<backedge_mapping> back_edges;
int64_t max_iteration;
protected:
std::vector<std::reference_wrapper<const primitive_id>> get_dependencies() const override {
std::vector<std::reference_wrapper<const primitive_id>> ret{
std::ref(trip_count_id), std::ref(initial_execution_id), std::ref(num_iteration_id)
};
// add external_id in dependencies if not exist
for (const auto& mapping : input_primitive_maps) {
auto target = std::find(input.begin(), input.end(), mapping.external_id);
if (target == input.end()) {
ret.push_back(std::ref(mapping.external_id));
}
}
return ret;
}
};
/// @}
/// @}
/// @}
} // namespace cldnn
| 46.45641 | 153 | 0.65526 |
73dbaf1b035f1ca7b44e95b76ce80967e64c967f | 26,198 | cpp | C++ | olp-cpp-sdk-dataservice-write/tests/VersionedLayerClientImplTest.cpp | fermeise/here-data-sdk-cpp | e0ebd7bd74463fa3958eb0447b90227a4f322643 | [
"Apache-2.0"
] | 21 | 2019-07-03T07:26:52.000Z | 2019-09-04T08:35:07.000Z | olp-cpp-sdk-dataservice-write/tests/VersionedLayerClientImplTest.cpp | fermeise/here-data-sdk-cpp | e0ebd7bd74463fa3958eb0447b90227a4f322643 | [
"Apache-2.0"
] | 639 | 2019-09-13T17:14:24.000Z | 2020-05-13T11:49:14.000Z | olp-cpp-sdk-dataservice-write/tests/VersionedLayerClientImplTest.cpp | fermeise/here-data-sdk-cpp | e0ebd7bd74463fa3958eb0447b90227a4f322643 | [
"Apache-2.0"
] | 21 | 2020-05-14T15:32:28.000Z | 2022-03-15T13:52:33.000Z | /*
* Copyright (C) 2020-2021 HERE Europe B.V.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
* License-Filename: LICENSE
*/
#include <gmock/gmock.h>
#include <matchers/NetworkUrlMatchers.h>
#include <mocks/CacheMock.h>
#include <mocks/NetworkMock.h>
#include <olp/authentication/Settings.h>
#include <olp/authentication/TokenProvider.h>
#include <olp/core/client/OlpClientSettingsFactory.h>
// clang-format off
#include "generated/serializer/ApiSerializer.h"
#include "generated/serializer/PublicationSerializer.h"
#include <olp/core/generated/serializer/SerializerWrapper.h>
#include "generated/serializer/JsonSerializer.h"
// clang-format on
#include "VersionedLayerClientImpl.h"
#include "WriteDefaultResponses.h"
namespace {
using testing::_;
using testing::Mock;
using testing::Return;
namespace client = olp::client;
namespace write = olp::dataservice::write;
namespace model = olp::dataservice::write::model;
constexpr auto kAppId = "id";
constexpr auto kAppSecret = "secret";
constexpr auto kLayer = "layer";
const std::string kPublishApiName = "publish";
const auto kHrn = olp::client::HRN{"hrn:here:data:::catalog"};
const auto kLookupPublishApiUrl =
"https://api-lookup.data.api.platform.here.com/lookup/v1/resources/" +
kHrn.ToString() + "/apis/publish/v2";
const std::string kPublishUrl =
"https://tmp.publish.data.api.platform.here.com/publish/v2/catalogs/" +
kHrn.ToString() + "/publications";
const std::string kUserSigninResponse = R"JSON(
{"accessToken":"password_grant_token","tokenType":"bearer","expiresIn":3599,"refreshToken":"5j687leur4njgb4osomifn55p0","userId":"HERE-5fa10eda-39ff-4cbc-9b0c-5acba4685649"}
)JSON";
class VersionedLayerClientImplTest : public ::testing::Test {
protected:
void SetUp() override {
cache_ = std::make_shared<CacheMock>();
network_ = std::make_shared<NetworkMock>();
olp::authentication::Settings auth_settings({kAppId, kAppSecret});
auth_settings.network_request_handler = network_;
olp::authentication::TokenProviderDefault provider(auth_settings);
olp::client::AuthenticationSettings auth_client_settings;
auth_client_settings.token_provider = provider;
settings_.network_request_handler = network_;
settings_.cache = cache_;
settings_.task_scheduler =
olp::client::OlpClientSettingsFactory::CreateDefaultTaskScheduler(1);
settings_.authentication_settings = auth_client_settings;
}
void TearDown() override {
settings_.network_request_handler.reset();
settings_.cache.reset();
network_.reset();
cache_.reset();
}
write::model::Apis CreateApiResponse(const std::string& service) {
const auto apis =
mockserver::DefaultResponses::GenerateResourceApisResponse(
kHrn.ToCatalogHRNString());
auto it = std::find_if(
apis.begin(), apis.end(),
[&](const model::Api& obj) -> bool { return obj.GetApi() == service; });
write::model::Apis result;
if (it != apis.end()) {
result.push_back(*it);
}
return result;
}
std::shared_ptr<CacheMock> cache_;
std::shared_ptr<NetworkMock> network_;
olp::client::OlpClientSettings settings_;
};
TEST_F(VersionedLayerClientImplTest, StartBatch) {
const auto catalog = kHrn.ToCatalogHRNString();
const auto api = CreateApiResponse(kPublishApiName);
const auto publication =
mockserver::DefaultResponses::GeneratePublicationResponse({kLayer}, {});
ASSERT_FALSE(api.empty());
// auth token should be valid till the end of all tests
EXPECT_CALL(
*network_,
Send(IsPostRequest(olp::authentication::kHereAccountProductionTokenUrl),
_, _, _, _))
.WillOnce(ReturnHttpResponse(olp::http::NetworkResponse().WithStatus(
olp::http::HttpStatusCode::OK),
kUserSigninResponse));
{
SCOPED_TRACE("Successful request, future");
EXPECT_CALL(*network_, Send(IsGetRequest(kLookupPublishApiUrl), _, _, _, _))
.WillOnce(ReturnHttpResponse(olp::http::NetworkResponse().WithStatus(
olp::http::HttpStatusCode::OK),
olp::serializer::serialize(api)));
EXPECT_CALL(*network_, Send(IsPostRequest(kPublishUrl), _, _, _, _))
.WillOnce(ReturnHttpResponse(olp::http::NetworkResponse().WithStatus(
olp::http::HttpStatusCode::OK),
olp::serializer::serialize(publication)));
// mock apis caching
EXPECT_CALL(*cache_, Get(_, _)).Times(1);
EXPECT_CALL(*cache_, Put(_, _, _, _))
.WillOnce([](const std::string& /*key*/, const boost::any& /*value*/,
const olp::cache::Encoder& /*encoder*/,
time_t /*expiry*/) { return true; });
write::VersionedLayerClientImpl write_client(kHrn, settings_);
const auto batch_request = model::StartBatchRequest().WithLayers({kLayer});
auto future = write_client.StartBatch(batch_request).GetFuture();
const auto response = future.get();
const auto& result = response.GetResult();
EXPECT_TRUE(response.IsSuccessful());
ASSERT_TRUE(result.GetId());
ASSERT_TRUE(result.GetDetails());
ASSERT_TRUE(result.GetLayerIds());
ASSERT_EQ(result.GetLayerIds().get().size(), 1);
ASSERT_EQ(result.GetLayerIds().get().front(), kLayer);
ASSERT_NE("", response.GetResult().GetId().value());
Mock::VerifyAndClearExpectations(network_.get());
Mock::VerifyAndClearExpectations(cache_.get());
}
{
SCOPED_TRACE("Successful request, callback");
EXPECT_CALL(*network_, Send(IsGetRequest(kLookupPublishApiUrl), _, _, _, _))
.WillOnce(ReturnHttpResponse(olp::http::NetworkResponse().WithStatus(
olp::http::HttpStatusCode::OK),
olp::serializer::serialize(api)));
EXPECT_CALL(*network_, Send(IsPostRequest(kPublishUrl), _, _, _, _))
.WillOnce(ReturnHttpResponse(olp::http::NetworkResponse().WithStatus(
olp::http::HttpStatusCode::OK),
olp::serializer::serialize(publication)));
// mock apis caching
EXPECT_CALL(*cache_, Get(_, _)).Times(1);
EXPECT_CALL(*cache_, Put(_, _, _, _))
.WillOnce([](const std::string& /*key*/, const boost::any& /*value*/,
const olp::cache::Encoder& /*encoder*/,
time_t /*expiry*/) { return true; });
std::promise<write::StartBatchResponse> promise;
write::VersionedLayerClientImpl write_client(kHrn, settings_);
const auto batch_request = model::StartBatchRequest().WithLayers({kLayer});
const auto token = write_client.StartBatch(
batch_request, [&promise](write::StartBatchResponse response) {
promise.set_value(std::move(response));
});
auto future = promise.get_future();
const auto response = future.get();
const auto& result = response.GetResult();
EXPECT_TRUE(response.IsSuccessful());
ASSERT_TRUE(result.GetId());
ASSERT_TRUE(result.GetDetails());
ASSERT_TRUE(result.GetLayerIds());
ASSERT_EQ(result.GetLayerIds().get().size(), 1);
ASSERT_EQ(result.GetLayerIds().get().front(), kLayer);
ASSERT_NE("", response.GetResult().GetId().value());
Mock::VerifyAndClearExpectations(network_.get());
Mock::VerifyAndClearExpectations(cache_.get());
}
{
SCOPED_TRACE("Apis load from cache");
EXPECT_CALL(*network_, Send(IsPostRequest(kPublishUrl), _, _, _, _))
.WillOnce(ReturnHttpResponse(olp::http::NetworkResponse().WithStatus(
olp::http::HttpStatusCode::OK),
olp::serializer::serialize(publication)));
// mock apis caching
EXPECT_CALL(*cache_, Get(_, _))
.WillOnce([&api](const std::string&, const olp::cache::Decoder&) {
return api[0].GetBaseUrl();
});
write::VersionedLayerClientImpl write_client(kHrn, settings_);
const auto batch_request = model::StartBatchRequest().WithLayers({kLayer});
auto future = write_client.StartBatch(batch_request).GetFuture();
const auto response = future.get();
const auto& result = response.GetResult();
EXPECT_TRUE(response.IsSuccessful());
ASSERT_TRUE(result.GetId());
ASSERT_TRUE(result.GetDetails());
ASSERT_TRUE(result.GetLayerIds());
ASSERT_EQ(result.GetLayerIds().get().size(), 1);
ASSERT_EQ(result.GetLayerIds().get().front(), kLayer);
ASSERT_NE("", response.GetResult().GetId().value());
Mock::VerifyAndClearExpectations(network_.get());
Mock::VerifyAndClearExpectations(cache_.get());
}
{
SCOPED_TRACE("No layer");
write::VersionedLayerClientImpl write_client(kHrn, settings_);
const auto batch_request = model::StartBatchRequest();
auto future = write_client.StartBatch(batch_request).GetFuture();
const auto response = future.get();
EXPECT_FALSE(response.IsSuccessful());
EXPECT_EQ(response.GetError().GetErrorCode(),
client::ErrorCode::InvalidArgument);
Mock::VerifyAndClearExpectations(network_.get());
Mock::VerifyAndClearExpectations(cache_.get());
}
{
SCOPED_TRACE("Empty layers array");
write::VersionedLayerClientImpl write_client(kHrn, settings_);
const auto batch_request = model::StartBatchRequest().WithLayers({});
auto future = write_client.StartBatch(batch_request).GetFuture();
const auto response = future.get();
EXPECT_FALSE(response.IsSuccessful());
EXPECT_EQ(response.GetError().GetErrorCode(),
client::ErrorCode::InvalidArgument);
Mock::VerifyAndClearExpectations(network_.get());
Mock::VerifyAndClearExpectations(cache_.get());
}
}
TEST_F(VersionedLayerClientImplTest, StartBatchCancel) {
const auto catalog = kHrn.ToCatalogHRNString();
// auth token should be valid till the end of all test cases
EXPECT_CALL(
*network_,
Send(IsPostRequest(olp::authentication::kHereAccountProductionTokenUrl),
_, _, _, _))
.WillOnce(ReturnHttpResponse(olp::http::NetworkResponse().WithStatus(
olp::http::HttpStatusCode::OK),
kUserSigninResponse));
{
SCOPED_TRACE("Cancel");
const auto apis =
mockserver::DefaultResponses::GenerateResourceApisResponse(catalog);
olp::http::RequestId request_id;
NetworkCallback send_mock;
CancelCallback cancel_mock;
auto wait_for_cancel = std::make_shared<std::promise<void>>();
auto pause_for_cancel = std::make_shared<std::promise<void>>();
std::tie(request_id, send_mock, cancel_mock) =
GenerateNetworkMockActions(wait_for_cancel, pause_for_cancel,
{olp::http::HttpStatusCode::OK,
olp::serializer::serialize(apis).c_str()});
EXPECT_CALL(*network_, Send(IsGetRequest(kLookupPublishApiUrl), _, _, _, _))
.WillOnce(testing::Invoke(std::move(send_mock)));
EXPECT_CALL(*network_, Cancel(_))
.WillOnce(testing::Invoke(std::move(cancel_mock)));
// mock apis caching
EXPECT_CALL(*cache_, Get(_, _)).Times(1);
std::promise<write::StartBatchResponse> promise;
write::VersionedLayerClientImpl write_client(kHrn, settings_);
const auto batch_request = model::StartBatchRequest().WithLayers({kLayer});
const auto token = write_client.StartBatch(
batch_request, [&promise](write::StartBatchResponse response) {
promise.set_value(std::move(response));
});
wait_for_cancel->get_future().get();
token.Cancel();
pause_for_cancel->set_value();
auto future = promise.get_future();
const auto response = future.get();
ASSERT_FALSE(response.IsSuccessful());
ASSERT_EQ(response.GetError().GetErrorCode(), client::ErrorCode::Cancelled);
Mock::VerifyAndClearExpectations(network_.get());
Mock::VerifyAndClearExpectations(cache_.get());
}
{
SCOPED_TRACE("On client deletion");
const auto apis =
mockserver::DefaultResponses::GenerateResourceApisResponse(catalog);
olp::http::RequestId request_id;
NetworkCallback send_mock;
CancelCallback cancel_mock;
auto wait_for_cancel = std::make_shared<std::promise<void>>();
auto pause_for_cancel = std::make_shared<std::promise<void>>();
std::tie(request_id, send_mock, cancel_mock) =
GenerateNetworkMockActions(wait_for_cancel, pause_for_cancel,
{olp::http::HttpStatusCode::OK,
olp::serializer::serialize(apis).c_str()});
EXPECT_CALL(*network_, Send(IsGetRequest(kLookupPublishApiUrl), _, _, _, _))
.WillOnce(testing::Invoke(std::move(send_mock)));
EXPECT_CALL(*network_, Cancel(_))
.WillOnce(testing::Invoke(std::move(cancel_mock)));
// mock apis caching
EXPECT_CALL(*cache_, Get(_, _)).Times(1);
auto write_client =
std::make_shared<write::VersionedLayerClientImpl>(kHrn, settings_);
const auto batch_request = model::StartBatchRequest().WithLayers({kLayer});
auto future = write_client->StartBatch(batch_request).GetFuture();
wait_for_cancel->get_future().get();
write_client.reset();
pause_for_cancel->set_value();
const auto response = future.get();
ASSERT_FALSE(response.IsSuccessful());
ASSERT_EQ(response.GetError().GetErrorCode(), client::ErrorCode::Cancelled);
Mock::VerifyAndClearExpectations(network_.get());
Mock::VerifyAndClearExpectations(cache_.get());
}
{
SCOPED_TRACE("Cancellable future");
const auto apis =
mockserver::DefaultResponses::GenerateResourceApisResponse(catalog);
olp::http::RequestId request_id;
NetworkCallback send_mock;
CancelCallback cancel_mock;
auto wait_for_cancel = std::make_shared<std::promise<void>>();
auto pause_for_cancel = std::make_shared<std::promise<void>>();
std::tie(request_id, send_mock, cancel_mock) =
GenerateNetworkMockActions(wait_for_cancel, pause_for_cancel,
{olp::http::HttpStatusCode::OK,
olp::serializer::serialize(apis).c_str()});
EXPECT_CALL(*network_, Send(_, _, _, _, _))
.WillOnce(testing::Invoke(std::move(send_mock)));
EXPECT_CALL(*network_, Cancel(_))
.WillOnce(testing::Invoke(std::move(cancel_mock)));
// mock apis caching
EXPECT_CALL(*cache_, Get(_, _)).Times(1);
write::VersionedLayerClientImpl write_client(kHrn, settings_);
const auto batch_request = model::StartBatchRequest().WithLayers({kLayer});
const auto cancellable = write_client.StartBatch(batch_request);
auto token = cancellable.GetCancellationToken();
wait_for_cancel->get_future().get();
token.Cancel();
pause_for_cancel->set_value();
const auto response = cancellable.GetFuture().get();
ASSERT_FALSE(response.IsSuccessful());
ASSERT_EQ(response.GetError().GetErrorCode(), client::ErrorCode::Cancelled);
Mock::VerifyAndClearExpectations(network_.get());
Mock::VerifyAndClearExpectations(cache_.get());
}
}
TEST_F(VersionedLayerClientImplTest, CompleteBatch) {
const auto catalog = kHrn.ToCatalogHRNString();
const auto api = CreateApiResponse(kPublishApiName);
const auto publication =
mockserver::DefaultResponses::GeneratePublicationResponse({kLayer}, {});
ASSERT_FALSE(api.empty());
ASSERT_TRUE(publication.GetId());
const auto publication_publish_url =
kPublishUrl + "/" + publication.GetId().get();
// auth token should be valid till the end of all tests
EXPECT_CALL(
*network_,
Send(IsPostRequest(olp::authentication::kHereAccountProductionTokenUrl),
_, _, _, _))
.WillOnce(ReturnHttpResponse(olp::http::NetworkResponse().WithStatus(
olp::http::HttpStatusCode::OK),
kUserSigninResponse));
{
SCOPED_TRACE("Successful request, future");
EXPECT_CALL(*network_, Send(IsGetRequest(kLookupPublishApiUrl), _, _, _, _))
.WillOnce(ReturnHttpResponse(olp::http::NetworkResponse().WithStatus(
olp::http::HttpStatusCode::OK),
olp::serializer::serialize(api)));
EXPECT_CALL(*network_,
Send(IsPutRequest(publication_publish_url), _, _, _, _))
.WillOnce(ReturnHttpResponse(olp::http::NetworkResponse().WithStatus(
olp::http::HttpStatusCode::NO_CONTENT),
{}));
// mock apis caching
EXPECT_CALL(*cache_, Get(_, _)).Times(1);
EXPECT_CALL(*cache_, Put(_, _, _, _))
.WillOnce([](const std::string& /*key*/, const boost::any& /*value*/,
const olp::cache::Encoder& /*encoder*/,
time_t /*expiry*/) { return true; });
write::VersionedLayerClientImpl write_client(kHrn, settings_);
const auto batch_request = model::StartBatchRequest().WithLayers({kLayer});
auto future = write_client.CompleteBatch(publication).GetFuture();
const auto response = future.get();
EXPECT_TRUE(response.IsSuccessful());
Mock::VerifyAndClearExpectations(network_.get());
Mock::VerifyAndClearExpectations(cache_.get());
}
{
SCOPED_TRACE("Successful request, callback");
EXPECT_CALL(*network_, Send(IsGetRequest(kLookupPublishApiUrl), _, _, _, _))
.WillOnce(ReturnHttpResponse(olp::http::NetworkResponse().WithStatus(
olp::http::HttpStatusCode::OK),
olp::serializer::serialize(api)));
EXPECT_CALL(*network_,
Send(IsPutRequest(publication_publish_url), _, _, _, _))
.WillOnce(ReturnHttpResponse(olp::http::NetworkResponse().WithStatus(
olp::http::HttpStatusCode::NO_CONTENT),
{}));
// mock apis caching
EXPECT_CALL(*cache_, Get(_, _)).Times(1);
EXPECT_CALL(*cache_, Put(_, _, _, _))
.WillOnce([](const std::string& /*key*/, const boost::any& /*value*/,
const olp::cache::Encoder& /*encoder*/,
time_t /*expiry*/) { return true; });
std::promise<write::CompleteBatchResponse> promise;
write::VersionedLayerClientImpl write_client(kHrn, settings_);
const auto batch_request = model::StartBatchRequest().WithLayers({kLayer});
const auto token = write_client.CompleteBatch(
publication, [&promise](write::CompleteBatchResponse response) {
promise.set_value(std::move(response));
});
auto future = promise.get_future();
const auto response = future.get();
EXPECT_TRUE(response.IsSuccessful());
Mock::VerifyAndClearExpectations(network_.get());
Mock::VerifyAndClearExpectations(cache_.get());
}
{
SCOPED_TRACE("Apis load from cache");
EXPECT_CALL(*network_,
Send(IsPutRequest(publication_publish_url), _, _, _, _))
.WillOnce(ReturnHttpResponse(olp::http::NetworkResponse().WithStatus(
olp::http::HttpStatusCode::NO_CONTENT),
{}));
// mock apis caching
EXPECT_CALL(*cache_, Get(_, _))
.WillOnce([&api](const std::string&, const olp::cache::Decoder&) {
return api[0].GetBaseUrl();
});
write::VersionedLayerClientImpl write_client(kHrn, settings_);
const auto batch_request = model::StartBatchRequest().WithLayers({kLayer});
auto future = write_client.CompleteBatch(publication).GetFuture();
const auto response = future.get();
EXPECT_TRUE(response.IsSuccessful());
Mock::VerifyAndClearExpectations(network_.get());
Mock::VerifyAndClearExpectations(cache_.get());
}
{
SCOPED_TRACE("No publication id");
model::Publication invalid_publication;
write::VersionedLayerClientImpl write_client(kHrn, settings_);
const auto batch_request = model::StartBatchRequest().WithLayers({kLayer});
auto future = write_client.CompleteBatch(invalid_publication).GetFuture();
const auto response = future.get();
const auto& error = response.GetError();
EXPECT_FALSE(response.IsSuccessful());
EXPECT_EQ(error.GetErrorCode(), client::ErrorCode::InvalidArgument);
Mock::VerifyAndClearExpectations(network_.get());
Mock::VerifyAndClearExpectations(cache_.get());
}
}
TEST_F(VersionedLayerClientImplTest, CompleteBatchCancel) {
const auto catalog = kHrn.ToCatalogHRNString();
const auto apis =
mockserver::DefaultResponses::GenerateResourceApisResponse(catalog);
const auto apis_response = olp::serializer::serialize(apis).c_str();
const auto publication =
mockserver::DefaultResponses::GeneratePublicationResponse({kLayer}, {});
ASSERT_TRUE(publication.GetId());
// auth token should be valid till the end of all test cases
EXPECT_CALL(
*network_,
Send(IsPostRequest(olp::authentication::kHereAccountProductionTokenUrl),
_, _, _, _))
.WillOnce(ReturnHttpResponse(olp::http::NetworkResponse().WithStatus(
olp::http::HttpStatusCode::OK),
kUserSigninResponse));
{
SCOPED_TRACE("Cancel");
olp::http::RequestId request_id;
NetworkCallback send_mock;
CancelCallback cancel_mock;
auto wait_for_cancel = std::make_shared<std::promise<void>>();
auto pause_for_cancel = std::make_shared<std::promise<void>>();
std::tie(request_id, send_mock, cancel_mock) = GenerateNetworkMockActions(
wait_for_cancel, pause_for_cancel,
{olp::http::HttpStatusCode::OK, apis_response});
EXPECT_CALL(*network_, Send(IsGetRequest(kLookupPublishApiUrl), _, _, _, _))
.WillOnce(testing::Invoke(std::move(send_mock)));
EXPECT_CALL(*network_, Cancel(_))
.WillOnce(testing::Invoke(std::move(cancel_mock)));
// mock apis caching
EXPECT_CALL(*cache_, Get(_, _)).Times(1);
std::promise<write::CompleteBatchResponse> promise;
write::VersionedLayerClientImpl write_client(kHrn, settings_);
const auto token = write_client.CompleteBatch(
publication, [&promise](write::CompleteBatchResponse response) {
promise.set_value(std::move(response));
});
wait_for_cancel->get_future().get();
token.Cancel();
pause_for_cancel->set_value();
auto future = promise.get_future();
const auto response = future.get();
ASSERT_FALSE(response.IsSuccessful());
ASSERT_EQ(response.GetError().GetErrorCode(), client::ErrorCode::Cancelled);
Mock::VerifyAndClearExpectations(network_.get());
Mock::VerifyAndClearExpectations(cache_.get());
}
{
SCOPED_TRACE("On client deletion");
olp::http::RequestId request_id;
NetworkCallback send_mock;
CancelCallback cancel_mock;
auto wait_for_cancel = std::make_shared<std::promise<void>>();
auto pause_for_cancel = std::make_shared<std::promise<void>>();
std::tie(request_id, send_mock, cancel_mock) = GenerateNetworkMockActions(
wait_for_cancel, pause_for_cancel,
{olp::http::HttpStatusCode::OK, apis_response});
EXPECT_CALL(*network_, Send(IsGetRequest(kLookupPublishApiUrl), _, _, _, _))
.WillOnce(testing::Invoke(std::move(send_mock)));
EXPECT_CALL(*network_, Cancel(_))
.WillOnce(testing::Invoke(std::move(cancel_mock)));
// mock apis caching
EXPECT_CALL(*cache_, Get(_, _)).Times(1);
auto write_client =
std::make_shared<write::VersionedLayerClientImpl>(kHrn, settings_);
auto future = write_client->CompleteBatch(publication).GetFuture();
wait_for_cancel->get_future().get();
write_client.reset();
pause_for_cancel->set_value();
const auto response = future.get();
ASSERT_FALSE(response.IsSuccessful());
ASSERT_EQ(response.GetError().GetErrorCode(), client::ErrorCode::Cancelled);
Mock::VerifyAndClearExpectations(network_.get());
Mock::VerifyAndClearExpectations(cache_.get());
}
{
SCOPED_TRACE("Cancellable future");
olp::http::RequestId request_id;
NetworkCallback send_mock;
CancelCallback cancel_mock;
auto wait_for_cancel = std::make_shared<std::promise<void>>();
auto pause_for_cancel = std::make_shared<std::promise<void>>();
std::tie(request_id, send_mock, cancel_mock) = GenerateNetworkMockActions(
wait_for_cancel, pause_for_cancel,
{olp::http::HttpStatusCode::OK, apis_response});
EXPECT_CALL(*network_, Send(_, _, _, _, _))
.WillOnce(testing::Invoke(std::move(send_mock)));
EXPECT_CALL(*network_, Cancel(_))
.WillOnce(testing::Invoke(std::move(cancel_mock)));
// mock apis caching
EXPECT_CALL(*cache_, Get(_, _)).Times(1);
write::VersionedLayerClientImpl write_client(kHrn, settings_);
const auto cancellable = write_client.CompleteBatch(publication);
auto token = cancellable.GetCancellationToken();
wait_for_cancel->get_future().get();
token.Cancel();
pause_for_cancel->set_value();
const auto response = cancellable.GetFuture().get();
ASSERT_FALSE(response.IsSuccessful());
ASSERT_EQ(response.GetError().GetErrorCode(), client::ErrorCode::Cancelled);
Mock::VerifyAndClearExpectations(network_.get());
Mock::VerifyAndClearExpectations(cache_.get());
}
}
} // namespace
| 38.469897 | 177 | 0.666921 |
73dbe8d52ddfcb290557627b769dc34ceefb418c | 663 | cpp | C++ | uva/340.cpp | dk00/old-stuff | e1184684c85fe9bbd1ceba58b94d4da84c67784e | [
"Unlicense"
] | null | null | null | uva/340.cpp | dk00/old-stuff | e1184684c85fe9bbd1ceba58b94d4da84c67784e | [
"Unlicense"
] | null | null | null | uva/340.cpp | dk00/old-stuff | e1184684c85fe9bbd1ceba58b94d4da84c67784e | [
"Unlicense"
] | null | null | null | #include<cstdio>
main()
{
int i,j,a,b,n,s0[1001],s1[1001],u0[15],u1[15],C=1;
while(scanf("%d",&n) && n)
{
for(i=0;i<10;i++)u0[i]=0;
for(i=0;i<n;i++)
scanf("%d",s0+i),u0[s0[i]]++;
printf("Game %d:\n",C++);
while(1)
{
for(i=0;i<n;i++)
scanf("%d",s1+i);
if(!s1[0])break;
for(i=0;i<10;i++)u1[i]=0;
for(i=a=b=0;i<n;i++)
{
if(s0[i]==s1[i])a++;
u1[s1[i]]++;
}
for(i=0;i<10;i++)
b+=(u0[i]<?u1[i]);
printf(" (%d,%d)\n",a,b-a);
}
}
}
| 23.678571 | 54 | 0.310709 |
73dcc4a6d9d75eb6749c6bc36247865f8eaec465 | 23,001 | cpp | C++ | backend/pipeline/PipelineUBO.cpp | Xrysnow/cocos2d-x-gfx | 54bc8264b15d9fc0e86c731a029d1b9b8b99b5b8 | [
"MIT"
] | null | null | null | backend/pipeline/PipelineUBO.cpp | Xrysnow/cocos2d-x-gfx | 54bc8264b15d9fc0e86c731a029d1b9b8b99b5b8 | [
"MIT"
] | null | null | null | backend/pipeline/PipelineUBO.cpp | Xrysnow/cocos2d-x-gfx | 54bc8264b15d9fc0e86c731a029d1b9b8b99b5b8 | [
"MIT"
] | null | null | null | /****************************************************************************
Copyright (c) 2020-2022 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "PipelineUBO.h"
#include "RenderPipeline.h"
#include "SceneCulling.h"
#include "application/ApplicationManager.h"
#include "forward/ForwardPipeline.h"
#include "gfx-base/GFXDevice.h"
#include "scene/RenderScene.h"
namespace cc {
namespace pipeline {
#define TO_VEC3(dst, src, offset) \
(dst)[(offset) + 0] = (src).x; \
(dst)[(offset) + 1] = (src).y; \
(dst)[(offset) + 2] = (src).z;
#define TO_VEC4(dst, src, offset) \
(dst)[(offset) + 0] = (src).x; \
(dst)[(offset) + 1] = (src).y; \
(dst)[(offset) + 2] = (src).z; \
(dst)[(offset) + 3] = (src).w;
Mat4 matShadowViewProj;
void PipelineUBO::updateGlobalUBOView(const scene::Camera *camera, std::array<float, UBOGlobal::COUNT> *bufferView) {
const scene::Root * root = scene::Root::instance;
const gfx::Device * device = gfx::Device::getInstance();
std::array<float, UBOGlobal::COUNT> &uboGlobalView = *bufferView;
const auto shadingWidth = std::floor(camera->window->getWidth());
const auto shadingHeight = std::floor(camera->window->getHeight());
// update UBOGlobal
uboGlobalView[UBOGlobal::TIME_OFFSET + 0] = root->cumulativeTime;
uboGlobalView[UBOGlobal::TIME_OFFSET + 1] = root->frameTime;
uboGlobalView[UBOGlobal::TIME_OFFSET + 2] = static_cast<float>(CC_CURRENT_ENGINE()->getTotalFrames());
uboGlobalView[UBOGlobal::SCREEN_SIZE_OFFSET + 0] = static_cast<float>(shadingWidth);
uboGlobalView[UBOGlobal::SCREEN_SIZE_OFFSET + 1] = static_cast<float>(shadingHeight);
uboGlobalView[UBOGlobal::SCREEN_SIZE_OFFSET + 2] = 1.0F / uboGlobalView[UBOGlobal::SCREEN_SIZE_OFFSET];
uboGlobalView[UBOGlobal::SCREEN_SIZE_OFFSET + 3] = 1.0F / uboGlobalView[UBOGlobal::SCREEN_SIZE_OFFSET + 1];
uboGlobalView[UBOGlobal::NATIVE_SIZE_OFFSET + 0] = static_cast<float>(shadingWidth);
uboGlobalView[UBOGlobal::NATIVE_SIZE_OFFSET + 1] = static_cast<float>(shadingHeight);
uboGlobalView[UBOGlobal::NATIVE_SIZE_OFFSET + 2] = 1.0F / uboGlobalView[UBOGlobal::NATIVE_SIZE_OFFSET];
uboGlobalView[UBOGlobal::NATIVE_SIZE_OFFSET + 3] = 1.0F / uboGlobalView[UBOGlobal::NATIVE_SIZE_OFFSET + 1];
}
void PipelineUBO::updateCameraUBOView(const RenderPipeline *pipeline, float *output, const scene::Camera *camera) {
const auto * scene = camera->scene;
const scene::DirectionalLight *mainLight = scene->getMainLight();
const auto * sceneData = pipeline->getPipelineSceneData();
const auto * sharedData = sceneData->getSharedData();
const auto * descriptorSet = pipeline->getDescriptorSet();
const auto * ambient = sharedData->ambient;
const auto * fog = sharedData->fog;
const auto * shadowInfo = sharedData->shadow;
const auto isHDR = sharedData->isHDR;
auto *device = gfx::Device::getInstance();
const auto shadingWidth = static_cast<float>(std::floor(camera->window->getWidth()));
const auto shadingHeight = static_cast<float>(std::floor(camera->window->getHeight()));
output[UBOCamera::SCREEN_SCALE_OFFSET + 0] = sharedData->shadingScale;
output[UBOCamera::SCREEN_SCALE_OFFSET + 1] = sharedData->shadingScale;
output[UBOCamera::SCREEN_SCALE_OFFSET + 2] = 1.0F / output[UBOCamera::SCREEN_SCALE_OFFSET];
output[UBOCamera::SCREEN_SCALE_OFFSET + 3] = 1.0F / output[UBOCamera::SCREEN_SCALE_OFFSET + 1];
const auto exposure = camera->exposure;
output[UBOCamera::EXPOSURE_OFFSET + 0] = exposure;
output[UBOCamera::EXPOSURE_OFFSET + 1] = 1.0F / exposure;
output[UBOCamera::EXPOSURE_OFFSET + 2] = isHDR ? 1.0F : 0.0F;
output[UBOCamera::EXPOSURE_OFFSET + 3] = 0.0F;
if (mainLight) {
const float shadowEnable = (mainLight->getShadowEnabled() && shadowInfo->shadowType == scene::ShadowType::SHADOWMAP) ? 1.0F : 0.0F;
const Vec4 lightDir(mainLight->getDirection().x, mainLight->getDirection().y, mainLight->getDirection().z, shadowEnable);
TO_VEC4(output, lightDir, UBOCamera::MAIN_LIT_DIR_OFFSET)
TO_VEC3(output, mainLight->getColor(), UBOCamera::MAIN_LIT_COLOR_OFFSET)
if (mainLight->getUseColorTemperature()) {
const auto &colorTempRGB = mainLight->getColorTemperatureRGB();
output[UBOCamera::MAIN_LIT_COLOR_OFFSET + 0] *= colorTempRGB.x;
output[UBOCamera::MAIN_LIT_COLOR_OFFSET + 1] *= colorTempRGB.y;
output[UBOCamera::MAIN_LIT_COLOR_OFFSET + 2] *= colorTempRGB.z;
}
if (isHDR) {
output[UBOCamera::MAIN_LIT_COLOR_OFFSET + 3] = mainLight->getIlluminanceHDR() * exposure;
} else {
output[UBOCamera::MAIN_LIT_COLOR_OFFSET + 3] = mainLight->getIlluminanceLDR();
}
} else {
const Vec4 lightDir(0.0F, 0.0F, 1.0F, 0.0F);
TO_VEC4(output, lightDir, UBOCamera::MAIN_LIT_DIR_OFFSET);
TO_VEC4(output, Vec4::ZERO, UBOCamera::MAIN_LIT_COLOR_OFFSET);
}
Vec4 skyColor = ambient->skyColor;
if (isHDR) {
skyColor.w = ambient->skyIllum * exposure;
} else {
skyColor.w = ambient->skyIllum;
}
TO_VEC4(output, skyColor, UBOCamera::AMBIENT_SKY_OFFSET)
output[UBOCamera::AMBIENT_GROUND_OFFSET + 0] = ambient->groundAlbedo.x;
output[UBOCamera::AMBIENT_GROUND_OFFSET + 1] = ambient->groundAlbedo.y;
output[UBOCamera::AMBIENT_GROUND_OFFSET + 2] = ambient->groundAlbedo.z;
auto *const envmap = descriptorSet->getTexture(static_cast<uint>(PipelineGlobalBindings::SAMPLER_ENVIRONMENT));
if (envmap) {
output[UBOCamera::AMBIENT_GROUND_OFFSET + 3] = static_cast<float>(envmap->getViewInfo().levelCount);
}
memcpy(output + UBOCamera::MAT_VIEW_OFFSET, camera->matView.m, sizeof(cc::Mat4));
memcpy(output + UBOCamera::MAT_VIEW_INV_OFFSET, camera->node->getWorldMatrix().m, sizeof(cc::Mat4));
TO_VEC3(output, camera->position, UBOCamera::CAMERA_POS_OFFSET)
memcpy(output + UBOCamera::MAT_PROJ_OFFSET, camera->matProj.m, sizeof(cc::Mat4));
memcpy(output + UBOCamera::MAT_PROJ_INV_OFFSET, camera->matProjInv.m, sizeof(cc::Mat4));
memcpy(output + UBOCamera::MAT_VIEW_PROJ_OFFSET, camera->matViewProj.m, sizeof(cc::Mat4));
memcpy(output + UBOCamera::MAT_VIEW_PROJ_INV_OFFSET, camera->matViewProjInv.m, sizeof(cc::Mat4));
output[UBOCamera::CAMERA_POS_OFFSET + 3] = getCombineSignY();
if (fog->enabled) {
TO_VEC4(output, fog->color, UBOCamera::GLOBAL_FOG_COLOR_OFFSET)
output[UBOCamera::GLOBAL_FOG_BASE_OFFSET + 0] = fog->start;
output[UBOCamera::GLOBAL_FOG_BASE_OFFSET + 1] = fog->end;
output[UBOCamera::GLOBAL_FOG_BASE_OFFSET + 2] = fog->density;
output[UBOCamera::GLOBAL_FOG_ADD_OFFSET + 0] = fog->top;
output[UBOCamera::GLOBAL_FOG_ADD_OFFSET + 1] = fog->range;
output[UBOCamera::GLOBAL_FOG_ADD_OFFSET + 2] = fog->atten;
}
output[UBOCamera::GLOBAL_NEAR_FAR_OFFSET + 0] = static_cast<float>(camera->nearClip);
output[UBOCamera::GLOBAL_NEAR_FAR_OFFSET + 1] = static_cast<float>(camera->farClip);
output[UBOCamera::GLOBAL_VIEW_PORT_OFFSET + 0] = sharedData->shadingScale * camera->window->getWidth() * camera->viewPort.x;
output[UBOCamera::GLOBAL_VIEW_PORT_OFFSET + 1] = sharedData->shadingScale * camera->window->getHeight() * camera->viewPort.y;
output[UBOCamera::GLOBAL_VIEW_PORT_OFFSET + 2] = sharedData->shadingScale * camera->window->getWidth() * camera->viewPort.z;
output[UBOCamera::GLOBAL_VIEW_PORT_OFFSET + 3] = sharedData->shadingScale * camera->window->getHeight() * camera->viewPort.w;
}
void PipelineUBO::updateShadowUBOView(const RenderPipeline *pipeline, std::array<float, UBOShadow::COUNT> *bufferView, const scene::Camera *camera) {
const scene::RenderScene *const scene = camera->scene;
const scene::DirectionalLight * mainLight = scene->getMainLight();
gfx::Device * device = gfx::Device::getInstance();
const PipelineSceneData * sceneData = pipeline->getPipelineSceneData();
scene::Shadow *const shadowInfo = sceneData->getSharedData()->shadow;
std::array<float, UBOShadow::COUNT> &shadowUBO = *bufferView;
const bool hFTexture = supportsR32FloatTexture(device);
if (shadowInfo->enabled) {
if (mainLight && shadowInfo->shadowType == scene::ShadowType::SHADOWMAP) {
const Mat4 &matShadowView = sceneData->getMatShadowView();
const Mat4 &matShadowProj = sceneData->getMatShadowProj();
const Mat4 &matShadowViewProj = sceneData->getMatShadowViewProj();
float nearClamp;
float farClamp;
if (mainLight->getShadowFixedArea()) {
nearClamp = mainLight->getShadowNear();
farClamp = mainLight->getShadowFar();
} else {
nearClamp = mainLight->getShadowNear();
farClamp = sceneData->getShadowCameraFar();
}
memcpy(shadowUBO.data() + UBOShadow::MAT_LIGHT_VIEW_OFFSET, matShadowView.m, sizeof(matShadowView));
const float shadowProjDepthInfos[4] = {matShadowProj.m[10], matShadowProj.m[14], matShadowProj.m[11], matShadowProj.m[15]};
memcpy(shadowUBO.data() + UBOShadow::SHADOW_PROJ_DEPTH_INFO_OFFSET, &shadowProjDepthInfos, sizeof(shadowProjDepthInfos));
const float shadowProjInfos[4] = {matShadowProj.m[00], matShadowProj.m[05], 1.0F / matShadowProj.m[00], 1.0F / matShadowProj.m[05]};
memcpy(shadowUBO.data() + UBOShadow::SHADOW_PROJ_INFO_OFFSET, &shadowProjInfos, sizeof(shadowProjInfos));
memcpy(shadowUBO.data() + UBOShadow::MAT_LIGHT_VIEW_PROJ_OFFSET, matShadowViewProj.m, sizeof(matShadowViewProj));
const float linear = 0.0F;
const float shadowNFLSInfos[4] = {nearClamp, farClamp, linear, 1.0F - mainLight->getShadowSaturation()};
memcpy(shadowUBO.data() + UBOShadow::SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET, &shadowNFLSInfos, sizeof(shadowNFLSInfos));
const float shadowWHPBInfos[4] = {shadowInfo->size.x, shadowInfo->size.y, static_cast<float>(mainLight->getShadowPcf()), mainLight->getShadowBias()};
memcpy(shadowUBO.data() + UBOShadow::SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET, &shadowWHPBInfos, sizeof(shadowWHPBInfos));
const float packing = hFTexture ? 0.0F : 1.0F;
const float shadowLPNNInfos[4] = {0.0F, packing, mainLight->getShadowNormalBias(), 0.0F};
memcpy(shadowUBO.data() + UBOShadow::SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET, &shadowLPNNInfos, sizeof(shadowLPNNInfos));
} else if (mainLight && shadowInfo->shadowType == scene::ShadowType::PLANAR) {
updateDirLight(shadowInfo, mainLight, &shadowUBO);
updatePlanarNormalAndDistance(shadowInfo, &shadowUBO);
}
const float color[4] = {shadowInfo->color.x, shadowInfo->color.y, shadowInfo->color.z, shadowInfo->color.w};
memcpy(shadowUBO.data() + UBOShadow::SHADOW_COLOR_OFFSET, &color, sizeof(float) * 4);
}
}
void PipelineUBO::updateShadowUBOLightView(const RenderPipeline *pipeline, std::array<float, UBOShadow::COUNT> *bufferView,
const scene::Light *light) {
const auto *sceneData = pipeline->getPipelineSceneData();
const auto *shadowInfo = sceneData->getSharedData()->shadow;
auto * device = gfx::Device::getInstance();
auto & shadowUBO = *bufferView;
const bool hFTexture = supportsR32FloatTexture(device);
const float linear = 0.0F;
const float packing = hFTexture ? 0.0F : 1.0F;
switch (light->getType()) {
case scene::LightType::DIRECTIONAL: {
const auto *mainLight = static_cast<const scene::DirectionalLight *>(light);
const Mat4 &matShadowView = sceneData->getMatShadowView();
const Mat4 &matShadowProj = sceneData->getMatShadowProj();
const Mat4 &matShadowViewProj = sceneData->getMatShadowViewProj();
float nearClamp;
float farClamp;
if (mainLight->getShadowFixedArea()) {
nearClamp = mainLight->getShadowNear();
farClamp = mainLight->getShadowFar();
} else {
nearClamp = 0.1F;
farClamp = sceneData->getShadowCameraFar();
}
memcpy(shadowUBO.data() + UBOShadow::MAT_LIGHT_VIEW_OFFSET, matShadowView.m, sizeof(matShadowView));
const float shadowProjDepthInfos[4] = {matShadowProj.m[10], matShadowProj.m[14], matShadowProj.m[11], matShadowProj.m[15]};
memcpy(shadowUBO.data() + UBOShadow::SHADOW_PROJ_DEPTH_INFO_OFFSET, &shadowProjDepthInfos, sizeof(shadowProjDepthInfos));
const float shadowProjInfos[4] = {matShadowProj.m[00], matShadowProj.m[05], 1.0F / matShadowProj.m[00], 1.0F / matShadowProj.m[05]};
memcpy(shadowUBO.data() + UBOShadow::SHADOW_PROJ_INFO_OFFSET, &shadowProjInfos, sizeof(shadowProjInfos));
memcpy(shadowUBO.data() + UBOShadow::MAT_LIGHT_VIEW_PROJ_OFFSET, matShadowViewProj.m, sizeof(matShadowViewProj));
const float shadowNFLSInfos[4] = {nearClamp, farClamp, linear, 1.0F - mainLight->getShadowSaturation()};
memcpy(shadowUBO.data() + UBOShadow::SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET, &shadowNFLSInfos, sizeof(shadowNFLSInfos));
const float shadowLPNNInfos[4] = {0.0F, packing, mainLight->getShadowNormalBias(), 0.0F};
memcpy(shadowUBO.data() + UBOShadow::SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET, &shadowLPNNInfos, sizeof(shadowLPNNInfos));
const float shadowWHPBInfos[4] = {shadowInfo->size.x, shadowInfo->size.y, static_cast<float>(mainLight->getShadowPcf()), mainLight->getShadowBias()};
memcpy(shadowUBO.data() + UBOShadow::SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET, &shadowWHPBInfos, sizeof(shadowWHPBInfos));
} break;
case scene::LightType::SPOT: {
const auto *spotLight = static_cast<const scene::SpotLight *>(light);
const auto &matShadowCamera = spotLight->getNode()->getWorldMatrix();
const auto matShadowView = matShadowCamera.getInversed();
memcpy(shadowUBO.data() + UBOShadow::MAT_LIGHT_VIEW_OFFSET, matShadowView.m, sizeof(matShadowView));
Mat4::createPerspective(spotLight->getSpotAngle(), spotLight->getAspect(), 0.001F, spotLight->getRange(), &matShadowViewProj);
matShadowViewProj.multiply(matShadowView);
memcpy(shadowUBO.data() + UBOShadow::MAT_LIGHT_VIEW_PROJ_OFFSET, matShadowViewProj.m, sizeof(matShadowViewProj));
const float shadowNFLSInfos[4] = {0.01F, spotLight->getRange(), linear, 0.0F};
memcpy(shadowUBO.data() + UBOShadow::SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET, &shadowNFLSInfos, sizeof(shadowNFLSInfos));
const float shadowLPNNInfos[4] = {1.0F, packing, spotLight->getShadowNormalBias(), 0.0F};
memcpy(shadowUBO.data() + UBOShadow::SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET, &shadowLPNNInfos, sizeof(shadowLPNNInfos));
const float shadowWHPBInfos[4] = {shadowInfo->size.x, shadowInfo->size.y, static_cast<float>(spotLight->getShadowPcf()), spotLight->getShadowBias()};
memcpy(shadowUBO.data() + UBOShadow::SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET, &shadowWHPBInfos, sizeof(shadowWHPBInfos));
} break;
case scene::LightType::SPHERE: break;
case scene::LightType::UNKNOWN: break;
default:
break;
}
const float color[4] = {shadowInfo->color.x, shadowInfo->color.y, shadowInfo->color.z, shadowInfo->color.w};
memcpy(shadowUBO.data() + UBOShadow::SHADOW_COLOR_OFFSET, &color, sizeof(color));
}
static uint8_t combineSignY = 0;
uint8_t PipelineUBO::getCombineSignY() {
return combineSignY;
}
void PipelineUBO::initCombineSignY() {
const float screenSpaceSignY = _device->getCapabilities().screenSpaceSignY * 0.5F + 0.5F;
const float clipSpaceSignY = _device->getCapabilities().clipSpaceSignY * 0.5F + 0.5F;
combineSignY = static_cast<uint8_t>(screenSpaceSignY) << 1 | static_cast<uint8_t>(clipSpaceSignY);
}
void PipelineUBO::activate(gfx::Device *device, RenderPipeline *pipeline) {
_device = device;
_pipeline = pipeline;
auto *descriptorSet = pipeline->getDescriptorSet();
initCombineSignY();
auto *globalUBO = _device->createBuffer({
gfx::BufferUsageBit::UNIFORM | gfx::BufferUsageBit::TRANSFER_DST,
gfx::MemoryUsageBit::HOST | gfx::MemoryUsageBit::DEVICE,
UBOGlobal::SIZE,
UBOGlobal::SIZE,
gfx::BufferFlagBit::NONE,
});
descriptorSet->bindBuffer(UBOGlobal::BINDING, globalUBO);
_ubos.push_back(globalUBO);
_alignedCameraUBOSize = utils::alignTo(UBOCamera::SIZE, _device->getCapabilities().uboOffsetAlignment);
_cameraBuffer = _device->createBuffer({
gfx::BufferUsageBit::UNIFORM | gfx::BufferUsageBit::TRANSFER_DST,
gfx::MemoryUsageBit::HOST | gfx::MemoryUsageBit::DEVICE,
_alignedCameraUBOSize,
_alignedCameraUBOSize,
});
_ubos.push_back(_cameraBuffer);
_cameraUBOs.resize(_alignedCameraUBOSize / sizeof(float));
auto *cameraUBO = _device->createBuffer({
_cameraBuffer,
0,
UBOCamera::SIZE,
});
descriptorSet->bindBuffer(UBOCamera::BINDING, cameraUBO);
_ubos.push_back(cameraUBO);
auto *shadowUBO = _device->createBuffer({
gfx::BufferUsageBit::UNIFORM | gfx::BufferUsageBit::TRANSFER_DST,
gfx::MemoryUsageBit::DEVICE,
UBOShadow::SIZE,
UBOShadow::SIZE,
gfx::BufferFlagBit::NONE,
});
descriptorSet->bindBuffer(UBOShadow::BINDING, shadowUBO);
_ubos.push_back(shadowUBO);
}
void PipelineUBO::destroy() {
for (auto &ubo : _ubos) {
CC_SAFE_DESTROY(ubo)
}
_ubos.clear();
}
void PipelineUBO::updateGlobalUBO(const scene::Camera *camera) {
auto *const globalDSManager = _pipeline->getGlobalDSManager();
auto *const ds = _pipeline->getDescriptorSet();
ds->update();
PipelineUBO::updateGlobalUBOView(camera, &_globalUBO);
ds->getBuffer(UBOGlobal::BINDING)->update(_globalUBO.data(), UBOGlobal::SIZE);
globalDSManager->bindBuffer(UBOGlobal::BINDING, ds->getBuffer(UBOGlobal::BINDING));
globalDSManager->update();
}
void PipelineUBO::updateCameraUBO(const scene::Camera *camera) {
auto *const cmdBuffer = _pipeline->getCommandBuffers()[0];
PipelineUBO::updateCameraUBOView(_pipeline, _cameraUBOs.data(), camera);
cmdBuffer->updateBuffer(_cameraBuffer, _cameraUBOs.data());
}
void PipelineUBO::updateMultiCameraUBO(const vector<scene::Camera *> &cameras) {
const auto cameraCount = cameras.size();
const auto totalUboSize = static_cast<uint>(_alignedCameraUBOSize * cameraCount);
if (_cameraBuffer->getSize() < totalUboSize) {
_cameraBuffer->resize(totalUboSize);
_cameraUBOs.resize(totalUboSize / sizeof(float));
}
for (uint cameraIdx = 0; cameraIdx < cameraCount; ++cameraIdx) {
const auto *camera = cameras[cameraIdx];
const auto offset = cameraIdx * _alignedCameraUBOSize / sizeof(float);
PipelineUBO::updateCameraUBOView(_pipeline, &_cameraUBOs[offset], camera);
}
_cameraBuffer->update(_cameraUBOs.data());
_currentCameraUBOOffset = 0;
}
void PipelineUBO::updateShadowUBO(const scene::Camera *camera) {
auto *const ds = _pipeline->getDescriptorSet();
auto *const cmdBuffer = _pipeline->getCommandBuffers()[0];
const auto * sceneData = _pipeline->getPipelineSceneData();
const auto * shadowInfo = sceneData->getSharedData()->shadow;
const auto *const scene = camera->scene;
if (!shadowInfo->enabled) return;
const auto & shadowFrameBufferMap = sceneData->getShadowFramebufferMap();
const scene::DirectionalLight *mainLight = scene->getMainLight();
if (mainLight && shadowInfo->shadowType == scene::ShadowType::SHADOWMAP) {
if (shadowFrameBufferMap.count(mainLight) > 0) {
auto *texture = shadowFrameBufferMap.at(mainLight)->getColorTextures()[0];
if (texture) {
ds->bindTexture(SHADOWMAP::BINDING, texture);
}
}
}
PipelineUBO::updateShadowUBOView(_pipeline, &_shadowUBO, camera);
ds->update();
cmdBuffer->updateBuffer(ds->getBuffer(UBOShadow::BINDING), _shadowUBO.data(), UBOShadow::SIZE);
}
void PipelineUBO::updateShadowUBOLight(gfx::DescriptorSet *globalDS, const scene::Light *light) {
auto *const cmdBuffer = _pipeline->getCommandBuffers()[0];
PipelineUBO::updateShadowUBOLightView(_pipeline, &_shadowUBO, light);
globalDS->update();
cmdBuffer->updateBuffer(globalDS->getBuffer(UBOShadow::BINDING), _shadowUBO.data(), UBOShadow::SIZE);
}
void PipelineUBO::updateShadowUBORange(uint offset, const Mat4 *data) {
memcpy(_shadowUBO.data() + offset, data->m, sizeof(*data));
}
uint PipelineUBO::getCurrentCameraUBOOffset() const {
return _currentCameraUBOOffset;
}
void PipelineUBO::incCameraUBOOffset() {
_currentCameraUBOOffset += _alignedCameraUBOSize;
}
} // namespace pipeline
} // namespace cc
| 51.804054 | 161 | 0.676884 |
73dd78bb27495e5502f72f159af60d0ef4c69170 | 8,545 | cpp | C++ | LocalManUtils/IXmlSerializeable.cpp | xuepingiw/open_source_startalk | 44d962b04039f5660ec47a10313876a0754d3e72 | [
"MIT"
] | 34 | 2019-03-18T08:09:24.000Z | 2022-03-15T02:03:25.000Z | LocalManUtils/IXmlSerializeable.cpp | venliong/open_source_startalk | 51fda091a932a8adea626c312692836555753a9a | [
"MIT"
] | 5 | 2019-05-29T09:32:05.000Z | 2019-08-29T03:01:33.000Z | LocalManUtils/IXmlSerializeable.cpp | venliong/open_source_startalk | 51fda091a932a8adea626c312692836555753a9a | [
"MIT"
] | 32 | 2019-03-15T09:43:22.000Z | 2021-08-10T08:26:02.000Z | #include "IXmlSerializeable.h"
const QString mainNode = "item";
const QString argsNode = "args";
const QString classNode = "className";
const QString argNode = "arg";
const QString argNode_Attribute = "attribute";
const QString argNode_Type = "type";
const QString argNode_Value = "value";
#define CompType(x, y) x.typeName() == QString::fromStdString(y)
IXmlSerializeable::IXmlSerializeable(QObject *parent)
: ISerializeable(parent)
{
}
IXmlSerializeable::~IXmlSerializeable()
{
}
void IXmlSerializeable::initNotifycation()
{
auto count = metaObject()->propertyCount();
for(int i=0; i<count; ++i)
{
auto pro = metaObject()->property(i);
const char *name = pro.name();
auto signalIndex = pro.notifySignalIndex();
auto slotIndex = metaObject()->indexOfMethod("onNotifycation()");
auto ret = this->metaObject()->connect(this, pro.notifySignalIndex(), this, metaObject()->indexOfMethod("NotifyConnection()"));
}
}
void IXmlSerializeable::onNotifycation()
{
auto count = metaObject()->propertyCount();
for(int i=0; i<count; ++i)
{
auto pro = metaObject()->property(i);
if( !pro.hasNotifySignal() || pro.notifySignalIndex() != senderSignalIndex() )
continue;
//auto a = pro.typeName();
//auto proName = pro.name();
//auto proValue = pro.read(this);
mChangeList.push_back(pro.name());
break;
}
}
bool IXmlSerializeable::compare( IXmlSerializeable& other )
{
auto tmp1 = seralizeToString();
auto tmp2 = other.seralizeToString();
return tmp1.compare(tmp2) == 0;
}
QDomDocument IXmlSerializeable::seralizeToDocument()
{
QDomDocument doc;
innerSerialize(doc);
return doc;
}
QString IXmlSerializeable::seralizeToString()
{
return seralizeToDocument().toString();
}
QString IXmlSerializeable::seralizeChangedList()
{
QDomDocument doc;
innerSerializeChangedLst(doc);
return doc.toString();
}
void IXmlSerializeable::unserializeFromString( const QString& content )
{
QDomDocument doc;
doc.setContent(content);
auto elemRoot = doc.firstChildElement(mainNode);
innerUnserialize(elemRoot);
}
void IXmlSerializeable::unserialize( QDomElement& elem )
{
//auto elemRoot = elem.firstChildElement(mainNode);
innerUnserialize(elem);
}
void IXmlSerializeable::innerSerializeChangedLst( QDomDocument& doc )
{
auto elemClassName = doc.createElement(mainNode);
elemClassName.setAttribute(classNode, metaObject()->className());
auto elemArgs = doc.createElement(argsNode);
foreach(auto itor, mChangeList){
auto count = metaObject()->propertyCount();
for(int i=0; i<count; ++i)
{
auto pro = metaObject()->property(i);
auto a = pro.typeName();
auto b = pro.read(this);
auto c = pro.name();
if(strcmp(pro.name(), "objectName")==0)
continue;
if(QString::compare(pro.name(), itor) != 0)
continue;
auto elemArg = doc.createElement( argNode );
elemArg.setAttribute( argNode_Attribute, pro.name() );
elemArg.setAttribute( argNode_Type, pro.typeName());
if( CompType(pro, "QString") )
elemArg.setAttribute( argNode_Value, pro.read(this).toString() );
else if( CompType(pro, "int") )
elemArg.setAttribute( argNode_Value, pro.read(this).toInt() );
else if( CompType(pro, "bool") )
elemArg.setAttribute( argNode_Value, pro.read(this).toBool() );
else if( CompType(pro, "QUrl") )
continue;
else
{
Q_ASSERT(false);
continue;
}
elemArgs.appendChild(elemArg);
}
elemClassName.appendChild(elemArgs);
doc.appendChild(elemClassName);
}
}
void IXmlSerializeable::innerSerialize( QDomDocument& doc )
{
auto elemClassName = doc.createElement(mainNode);
elemClassName.setAttribute(classNode, metaObject()->className());
auto elemArgs = doc.createElement(argsNode);
auto count = metaObject()->propertyCount();
for(int i=0; i<count; ++i)
{
auto pro = metaObject()->property(i);
auto a = pro.typeName();
//auto b = pro.read(this);
auto c = pro.name();
if(strcmp(pro.name(), "objectName")==0)
continue;
auto elemArg = doc.createElement( argNode );
elemArg.setAttribute( argNode_Attribute, pro.name() );
elemArg.setAttribute( argNode_Type, pro.typeName());
if( CompType(pro, "QString") )
elemArg.setAttribute( argNode_Value, pro.read(this).toString() );
else if( CompType(pro, "int") )
elemArg.setAttribute( argNode_Value, pro.read(this).toInt() );
else if( CompType(pro, "bool") )
elemArg.setAttribute( argNode_Value, pro.read(this).toBool() );
else if( CompType(pro, "QUrl") )
continue;
else if( CompType(pro, "qreal") || CompType(pro, "double") )
elemArg.setAttribute( argNode_Value, pro.read(this).toDouble() );
else if( CompType(pro, "qint64") || CompType(pro, "qlonglong") )
elemArg.setAttribute( argNode_Value, pro.read(this).toLongLong() );
else if( CompType(pro, "quint64") || CompType(pro, "qulonglong") )
elemArg.setAttribute( argNode_Value, pro.read(this).toULongLong() );
else if( CompType(pro, "QStringList"))
{
auto datas = pro.read(this).toStringList();
foreach(auto item, datas){
auto elemListItem = doc.createElement("item");
elemListItem.appendChild(doc.createTextNode(item));
elemArg.appendChild(elemListItem);
}
}
else if( CompType(pro, "QList<IXmlSerializeable*>")){
auto datas = pro.read(this).value<QList<IXmlSerializeable*>>();
//auto datas = pro.read(this).toList();
foreach(auto item, datas){
elemArg.appendChild(item->seralizeToDocument());
}
}
else
{
// Q_ASSERT(false);
continue;
}
elemArgs.appendChild(elemArg);
}
elemClassName.appendChild(elemArgs);
doc.appendChild(elemClassName);
childSerialize(doc, elemClassName);
}
void IXmlSerializeable::innerUnserialize( QDomElement& elemRoot )
{
do
{
auto className = metaObject()->className();
auto xmlClassName = elemRoot.attribute(classNode);
if(xmlClassName.isEmpty()){
return;
}
if(elemRoot.attribute(classNode) != metaObject()->className())
break;
auto elemArgs = elemRoot.firstChildElement(argsNode);
if(!elemArgs.isElement())
break;
auto elemArg = elemArgs.firstChildElement(argNode);
while(elemArg.isElement())
{
auto elemType = elemArg.attribute(argNode_Attribute);
auto count = metaObject()->propertyCount();
for(int i=0; i<count; ++i)
{
auto pro = metaObject()->property(i);
auto tn = pro.name();
if(elemType != pro.name())
continue;
auto pn = pro.typeName();
if(CompType(pro, "QList<IXmlSerializeable*>"))
{
auto itemArg = elemArg.firstChildElement(mainNode);
while(itemArg.isElement())
{
unserializeItem(pro.name(), itemArg);
itemArg = itemArg.nextSiblingElement(mainNode);
}
}
else if( CompType(pro, "QStringList"))
{
}
else
{
auto attr = elemArg.attribute(argNode_Value);
pro.write(this, elemArg.attribute(argNode_Value));
}
emit pro.notifySignalIndex();
break;
}
elemArg = elemArg.nextSiblingElement();
}
childUnserialize(elemRoot);
return;
} while (false);
Q_ASSERT(false);
}
void IXmlSerializeable::childSerialize( QDomDocument& doc, QDomElement& elem ) const
{
}
void IXmlSerializeable::childUnserialize( QDomElement& elemRoot )
{
}
void IXmlSerializeable::unserializeItem( const QString&name, QDomElement& elem )
{
}
| 29.263699 | 135 | 0.590053 |
73de8ff45894187821fa3fd7844a623e398d9b1b | 1,422 | cc | C++ | tests/runtime/kernel_exec_context_test.cc | weisk/ppl.nn | 7dd75a1077867fc9a762449953417088446ae2f8 | [
"Apache-2.0"
] | 1 | 2021-10-06T14:39:58.000Z | 2021-10-06T14:39:58.000Z | tests/runtime/kernel_exec_context_test.cc | wolf15/ppl.nn | ac23e5eb518039536f1ef39b43c63d6bda900e77 | [
"Apache-2.0"
] | null | null | null | tests/runtime/kernel_exec_context_test.cc | wolf15/ppl.nn | ac23e5eb518039536f1ef39b43c63d6bda900e77 | [
"Apache-2.0"
] | null | null | null | #include "ppl/nn/runtime/kernel_exec_context.h"
#include "tests/ir/graph_builder.h"
#include "tests/runtime/test_barrier.h"
#include "gtest/gtest.h"
#include <vector>
using namespace std;
using namespace ppl::nn;
using namespace ppl::nn::test;
using namespace ppl::common;
class KernelExecContextTest : public testing::Test {
protected:
void SetUp() override {
builder_.AddNode("a", ir::Node::Type("test", "op1"), {"input_of_a"}, {"output_of_a"});
builder_.AddNode("b", ir::Node::Type("test", "op2"), {"output_of_a"}, {"output_of_b"});
builder_.AddNode("c", ir::Node::Type("test", "op3"), {"output_of_b"}, {"output_of_c"});
builder_.Finalize();
barriers_.resize(builder_.GetGraph()->topo->GetMaxEdgeId());
}
protected:
GraphBuilder builder_;
vector<TestBarrier> barriers_;
};
TEST_F(KernelExecContextTest, misc) {
auto topo = builder_.GetGraph()->topo.get();
auto node = topo->GetNodeById(0);
EXPECT_EQ("a", node->GetName());
KernelExecContext ctx;
ctx.SetNode(node);
ctx.SetGetBarrierFunc([this](edgeid_t eid) -> Barrier* {
return &barriers_[eid];
});
auto edge = topo->GetEdgeByName("input_of_a");
EXPECT_NE(nullptr, edge);
EXPECT_EQ(&barriers_[0], ctx.GetInputBarrier(0));
edge = topo->GetEdgeByName("output_of_a");
EXPECT_NE(nullptr, edge);
EXPECT_EQ(&barriers_[1], ctx.GetOutputBarrier(0));
}
| 30.255319 | 95 | 0.666667 |
73deb90e17605e524b783b1be083b0bf6f659a3d | 29,826 | cc | C++ | gazebo/gui/MainWindow_TEST.cc | yinnglu/gazebo | 3a5618a2a18873141e3cac734a692b778cec4fc0 | [
"ECL-2.0",
"Apache-2.0"
] | 3 | 2018-07-17T00:17:13.000Z | 2020-05-26T08:39:25.000Z | gazebo/gui/MainWindow_TEST.cc | yinnglu/gazebo | 3a5618a2a18873141e3cac734a692b778cec4fc0 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2022-02-03T18:32:35.000Z | 2022-02-03T18:32:35.000Z | gazebo/gui/MainWindow_TEST.cc | mingfeisun/gazebo | f3eae789c738f040b8fb27c2dc16dc4c06f2495c | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2016-04-25T22:05:09.000Z | 2020-03-08T08:45:12.000Z | /*
* Copyright (C) 2012 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <boost/filesystem.hpp>
#include <ignition/math/Helpers.hh>
#include <ignition/math/Pose3.hh>
#include <ignition/math/Vector2.hh>
#include "gazebo/msgs/msgs.hh"
#include "gazebo/transport/transport.hh"
#include "gazebo/gui/Actions.hh"
#include "gazebo/gui/GuiEvents.hh"
#include "gazebo/gui/GuiIface.hh"
#include "gazebo/gui/MainWindow.hh"
#include "gazebo/gui/GLWidget.hh"
#include "gazebo/gui/MainWindow_TEST.hh"
#include "test_config.h"
bool g_gotSetWireframe = false;
void OnRequest(ConstRequestPtr &_msg)
{
if (_msg->request() == "set_wireframe")
g_gotSetWireframe = true;
}
/////////////////////////////////////////////////
void MainWindow_TEST::MinimizeMaximize()
{
this->resMaxPercentChange = 5.0;
this->shareMaxPercentChange = 2.0;
this->Load("worlds/empty.world", false, false, false);
gazebo::gui::MainWindow *mainWindow = new gazebo::gui::MainWindow();
QVERIFY(mainWindow != NULL);
// Create the main window.
mainWindow->Load();
mainWindow->Init();
mainWindow->show();
// repeat minimize and maximize a couple of times
this->ProcessEventsAndDraw(mainWindow);
mainWindow->showMinimized();
this->ProcessEventsAndDraw(mainWindow);
mainWindow->showMaximized();
this->ProcessEventsAndDraw(mainWindow);
mainWindow->showMinimized();
this->ProcessEventsAndDraw(mainWindow);
mainWindow->showMaximized();
this->ProcessEventsAndDraw(mainWindow);
mainWindow->close();
delete mainWindow;
}
/////////////////////////////////////////////////
void MainWindow_TEST::StepState()
{
this->resMaxPercentChange = 5.0;
this->shareMaxPercentChange = 2.0;
this->Load("worlds/shapes.world", false, false, false);
gazebo::gui::MainWindow *mainWindow = new gazebo::gui::MainWindow();
QVERIFY(mainWindow != NULL);
// Create the main window.
mainWindow->Load();
mainWindow->Init();
mainWindow->show();
this->ProcessEventsAndDraw(mainWindow);
QVERIFY(gazebo::gui::g_stepAct != NULL);
QVERIFY(!gazebo::gui::g_stepAct->isEnabled());
QVERIFY(!mainWindow->IsPaused());
// toggle pause and play step and check if the step action is properly
// enabled / disabled.
mainWindow->Pause();
this->ProcessEventsAndDraw(mainWindow);
QVERIFY(mainWindow->IsPaused());
QVERIFY(gazebo::gui::g_stepAct->isEnabled());
mainWindow->Play();
this->ProcessEventsAndDraw(mainWindow);
QVERIFY(!mainWindow->IsPaused());
QVERIFY(!gazebo::gui::g_stepAct->isEnabled());
mainWindow->Pause();
this->ProcessEventsAndDraw(mainWindow);
QVERIFY(mainWindow->IsPaused());
QVERIFY(gazebo::gui::g_stepAct->isEnabled());
mainWindow->close();
delete mainWindow;
}
/////////////////////////////////////////////////
void MainWindow_TEST::Selection()
{
this->resMaxPercentChange = 5.0;
this->shareMaxPercentChange = 2.0;
this->Load("worlds/shapes.world", false, false, false);
gazebo::gui::MainWindow *mainWindow = new gazebo::gui::MainWindow();
QVERIFY(mainWindow != NULL);
// Create the main window.
mainWindow->Load();
mainWindow->Init();
mainWindow->show();
this->ProcessEventsAndDraw(mainWindow);
// Get the user camera and scene
gazebo::rendering::UserCameraPtr cam = gazebo::gui::get_active_camera();
QVERIFY(cam != NULL);
gazebo::gui::GLWidget *glWidget =
mainWindow->findChild<gazebo::gui::GLWidget *>("GLWidget");
QVERIFY(glWidget != NULL);
ignition::math::Vector2i glWidgetCenter(
glWidget->width()*0.5, glWidget->height()*0.5);
// get model at center of window - should get the box
gazebo::rendering::VisualPtr vis =
cam->Visual(glWidgetCenter);
QVERIFY(vis != NULL);
QVERIFY(vis->GetRootVisual()->Name() == "box");
// move camera to look at the box
ignition::math::Pose3d cameraPose(ignition::math::Vector3d(-1, 0, 0.5),
ignition::math::Quaterniond(0, 0, 0));
cam->SetWorldPose(cameraPose);
QVERIFY(cam->WorldPose() == cameraPose);
// verify we get a box
gazebo::rendering::VisualPtr vis2 =
cam->Visual(ignition::math::Vector2i(0, 0));
QVERIFY(vis2 != NULL);
QVERIFY(vis2->GetRootVisual()->Name() == "box");
// look upwards
ignition::math::Quaterniond pitch90(ignition::math::Vector3d(0, -1.57, 0));
cam->SetWorldRotation(pitch90);
QVERIFY(cam->WorldRotation() == pitch90);
// verify there is nothing in the middle of the window
gazebo::rendering::VisualPtr vis3 = cam->Visual(glWidgetCenter);
QVERIFY(vis3 == NULL);
// reset orientation
ignition::math::Quaterniond identityRot(ignition::math::Vector3d(0, 0, 0));
cam->SetWorldRotation(identityRot);
QVERIFY(cam->WorldRotation() == identityRot);
// verify we can still get the box
gazebo::rendering::VisualPtr vis4 =
cam->Visual(ignition::math::Vector2i(0, 0));
QVERIFY(vis4 != NULL);
QVERIFY(vis4->GetRootVisual()->Name() == "box");
// hide the box
vis4->SetVisible(false);
gazebo::rendering::VisualPtr vis5 = cam->Visual(glWidgetCenter);
// verify we don't get anything now
QVERIFY(vis5 == NULL);
cam->Fini();
mainWindow->close();
delete mainWindow;
}
/////////////////////////////////////////////////
void MainWindow_TEST::SceneDestruction()
{
this->resMaxPercentChange = 5.0;
this->shareMaxPercentChange = 2.0;
this->Load("worlds/shapes.world", false, false, false);
gazebo::gui::MainWindow *mainWindow = new gazebo::gui::MainWindow();
QVERIFY(mainWindow != NULL);
// Create the main window.
mainWindow->Load();
mainWindow->Init();
mainWindow->show();
this->ProcessEventsAndDraw(mainWindow);
// Get the user camera and scene
gazebo::rendering::UserCameraPtr cam = gazebo::gui::get_active_camera();
QVERIFY(cam != NULL);
gazebo::rendering::ScenePtr scene = cam->GetScene();
QVERIFY(scene != NULL);
cam->Fini();
mainWindow->close();
delete mainWindow;
// verify that this test case has the only scene shared pointer remaining.
QVERIFY(scene.use_count() == 1u);
}
/////////////////////////////////////////////////
void MainWindow_TEST::UserCameraFPS()
{
this->resMaxPercentChange = 5.0;
this->shareMaxPercentChange = 2.0;
this->Load("worlds/shapes.world", false, false, false);
gazebo::gui::MainWindow *mainWindow = new gazebo::gui::MainWindow();
QVERIFY(mainWindow != NULL);
// Create the main window.
mainWindow->Load();
mainWindow->Init();
mainWindow->show();
this->ProcessEventsAndDraw(mainWindow);
// Get the user camera and scene
gazebo::rendering::UserCameraPtr cam = gazebo::gui::get_active_camera();
QVERIFY(cam != NULL);
// some machines are unable to hit the target FPS
// sample update time and determine whether to skip FPS lower bound check
bool skipFPSTest = false;
gazebo::common::Time t = gazebo::common::Time::GetWallTime();
QCoreApplication::processEvents();
double dt = (gazebo::common::Time::GetWallTime()-t).Double();
if (dt >= 0.01)
{
std::cerr << "Skipping lower bound FPS check" << std::endl;
skipFPSTest = true;
}
unsigned int iterations = skipFPSTest ? 500 : 5000;
double lowerFPSBound = skipFPSTest ? 0 : 45;
// Wait a little bit for the average FPS to even out.
this->ProcessEventsAndDraw(NULL, iterations, 1);
std::cerr << "\nFPS[" << cam->AvgFPS() << "]\n" << std::endl;
QVERIFY(cam->AvgFPS() > lowerFPSBound);
QVERIFY(cam->AvgFPS() < 75.0);
cam->Fini();
mainWindow->close();
delete mainWindow;
}
/////////////////////////////////////////////////
void MainWindow_TEST::CopyPaste()
{
this->resMaxPercentChange = 5.0;
this->shareMaxPercentChange = 2.0;
this->Load("worlds/shapes.world", false, false, false);
gazebo::gui::MainWindow *mainWindow = new gazebo::gui::MainWindow();
QVERIFY(mainWindow != NULL);
// Create the main window.
mainWindow->Load();
mainWindow->Init();
mainWindow->show();
// Get the user camera and scene
gazebo::rendering::UserCameraPtr cam = gazebo::gui::get_active_camera();
QVERIFY(cam != NULL);
gazebo::rendering::ScenePtr scene = cam->GetScene();
QVERIFY(scene != NULL);
// Get GLWidget
gazebo::gui::GLWidget *glWidget =
mainWindow->findChild<gazebo::gui::GLWidget *>("GLWidget");
QVERIFY(glWidget != NULL);
// Test model copy
{
std::string modelName = "cylinder";
// trigger selection to initialize wirebox's vertex buffer creation first.
// Otherwise test segfaults later when selecting a model due to making
// this call outside the rendering thread.
gazebo::event::Events::setSelectedEntity(modelName, "normal");
this->ProcessEventsAndDraw(mainWindow);
gazebo::rendering::VisualPtr modelVis = scene->GetVisual(modelName);
QVERIFY(modelVis != NULL);
// Select the model
gazebo::event::Events::setSelectedEntity(modelName, "normal");
// Wait until the model is selected
int sleep = 0;
int maxSleep = 100;
while (!modelVis->GetHighlighted() && sleep < maxSleep)
{
gazebo::common::Time::MSleep(30);
sleep++;
}
QVERIFY(modelVis->GetHighlighted());
this->ProcessEventsAndDraw(mainWindow);
QVERIFY(gazebo::gui::g_copyAct != NULL);
QVERIFY(gazebo::gui::g_pasteAct != NULL);
// Copy the model
QTest::keyClick(glWidget, Qt::Key_C, Qt::ControlModifier, 100);
// Move to center of the screen
QPoint moveTo(glWidget->width()/2, glWidget->height()/2);
QTest::mouseMove(glWidget, moveTo, 100);
// Paste the model
QTest::keyClick(glWidget, Qt::Key_V, Qt::ControlModifier, 100);
// Release and spawn the model
QTest::mouseClick(glWidget, Qt::LeftButton, Qt::NoModifier, moveTo, 100);
QCoreApplication::processEvents();
// Verify there is a clone of the model
gazebo::rendering::VisualPtr modelVisClone;
sleep = 0;
maxSleep = 100;
while (!modelVisClone && sleep < maxSleep)
{
modelVisClone = scene->GetVisual(modelName + "_clone");
QTest::qWait(100);
sleep++;
}
QVERIFY(modelVisClone != NULL);
}
// Test light copy
{
std::string lightName = "sun";
// Select the light
gazebo::event::Events::setSelectedEntity(lightName, "normal");
gazebo::rendering::VisualPtr lightVis = scene->GetVisual(lightName);
QVERIFY(lightVis != NULL);
// Wait until the light is selected
int sleep = 0;
int maxSleep = 100;
while (!lightVis->GetHighlighted() && sleep < maxSleep)
{
gazebo::common::Time::MSleep(30);
sleep++;
}
QVERIFY(lightVis->GetHighlighted());
// Copy the light
QTest::keyClick(glWidget, Qt::Key_C, Qt::ControlModifier, 500);
QCoreApplication::processEvents();
// Move to center of the screen
QPoint moveTo(glWidget->width()/2, glWidget->height()/2);
QTest::mouseMove(glWidget, moveTo, 500);
QCoreApplication::processEvents();
// Paste the light
QTest::keyClick(glWidget, Qt::Key_V, Qt::ControlModifier, 500);
QCoreApplication::processEvents();
// Release and spawn the model
QTest::mouseClick(glWidget, Qt::LeftButton, Qt::NoModifier, moveTo, 500);
QCoreApplication::processEvents();
// Verify there is a clone of the light
gazebo::rendering::LightPtr lightClone;
sleep = 0;
maxSleep = 100;
while (!lightClone && sleep < maxSleep)
{
lightClone = scene->GetLight(lightName + "_clone");
QTest::qWait(30);
sleep++;
}
QVERIFY(lightClone != NULL);
lightClone.reset();
}
cam->Fini();
mainWindow->close();
delete mainWindow;
}
/////////////////////////////////////////////////
void MainWindow_TEST::Wireframe()
{
this->resMaxPercentChange = 5.0;
this->shareMaxPercentChange = 2.0;
boost::filesystem::path path = TEST_PATH;
path = path / "worlds" / "empty_dark_plane.world";
this->Load(path.string(), false, false, false);
gazebo::transport::NodePtr node;
gazebo::transport::SubscriberPtr sub;
node = gazebo::transport::NodePtr(new gazebo::transport::Node());
node->Init();
sub = node->Subscribe("~/request", &OnRequest, true);
// Create the main window.
gazebo::gui::MainWindow *mainWindow = new gazebo::gui::MainWindow();
QVERIFY(mainWindow != NULL);
mainWindow->Load();
mainWindow->Init();
mainWindow->show();
this->ProcessEventsAndDraw(mainWindow);
// Get the user camera, and tell it to save frames
gazebo::rendering::UserCameraPtr cam = gazebo::gui::get_active_camera();
if (!cam)
return;
cam->SetCaptureData(true);
this->ProcessEventsAndDraw(mainWindow);
// Get the image data
const unsigned char *image = cam->ImageData();
unsigned int height = cam->ImageHeight();
unsigned int width = cam->ImageWidth();
unsigned int depth = 3;
// Calculate the average color.
unsigned int sum = 0;
for (unsigned int y = 0; y < height; ++y)
{
for (unsigned int x = 0; x < width*depth; ++x)
{
unsigned int a = image[(y*width*depth)+x];
sum += a;
}
}
double avgPreWireframe = static_cast<double>(sum) / (height*width*depth);
// Trigger the wireframe request.
gazebo::gui::g_viewWireframeAct->trigger();
double avgPostWireframe = avgPreWireframe;
// Redraw the screen
for (unsigned int i = 0; i < 100 &&
ignition::math::equal(avgPostWireframe, avgPreWireframe, 1e-3); ++i)
{
gazebo::common::Time::MSleep(30);
QCoreApplication::processEvents();
mainWindow->repaint();
// Get the new image data, and calculate the new average color
image = cam->ImageData();
sum = 0;
for (unsigned int y = 0; y < height; ++y)
{
for (unsigned int x = 0; x < width*depth; ++x)
{
unsigned int a = image[(y*width*depth)+x];
sum += a;
}
}
avgPostWireframe = static_cast<double>(sum) / (height*width*depth);
}
// Make sure the request was set.
QVERIFY(g_gotSetWireframe);
gzdbg << "AvgPrewireframe [" << avgPreWireframe
<< "] AvgPostWireframe[" << avgPostWireframe << "]\n";
// Removing the grey ground plane should change the image.
QVERIFY(!ignition::math::equal(avgPreWireframe, avgPostWireframe));
cam->Fini();
mainWindow->close();
delete mainWindow;
}
/////////////////////////////////////////////////
void MainWindow_TEST::NonDefaultWorld()
{
this->resMaxPercentChange = 5.0;
this->shareMaxPercentChange = 2.0;
boost::filesystem::path path = TEST_PATH;
path = path / "worlds" / "empty_different_name.world";
this->Load(path.string(), false, false, false);
// Create the main window.
gazebo::gui::MainWindow *mainWindow = new gazebo::gui::MainWindow();
QVERIFY(mainWindow != NULL);
mainWindow->Load();
mainWindow->Init();
mainWindow->show();
this->ProcessEventsAndDraw(mainWindow);
// Get the user camera, and tell it to save frames
gazebo::rendering::UserCameraPtr cam = gazebo::gui::get_active_camera();
QVERIFY(cam != nullptr);
cam->SetCaptureData(true);
this->ProcessEventsAndDraw(mainWindow);
// Get the image data
const unsigned char *image = cam->ImageData();
unsigned int height = cam->ImageHeight();
unsigned int width = cam->ImageWidth();
unsigned int depth = 3;
unsigned int sum = 0;
for (unsigned int y = 0; y < height; ++y)
{
for (unsigned int x = 0; x < width*depth; ++x)
{
unsigned int a = image[(y*width*depth)+x];
sum += a;
}
}
QVERIFY(sum > 0);
cam->Fini();
mainWindow->close();
delete mainWindow;
}
/////////////////////////////////////////////////
void MainWindow_TEST::UserCameraJoystick()
{
this->resMaxPercentChange = 5.0;
this->shareMaxPercentChange = 2.0;
this->Load("worlds/shapes.world", false, false, false);
gazebo::gui::MainWindow *mainWindow = new gazebo::gui::MainWindow();
QVERIFY(mainWindow != NULL);
// Create the main window.
mainWindow->Load();
mainWindow->Init();
mainWindow->show();
this->ProcessEventsAndDraw(mainWindow);
// Get the user camera and scene
gazebo::rendering::UserCameraPtr cam = gazebo::gui::get_active_camera();
QVERIFY(cam != NULL);
ignition::math::Pose3d startPose = cam->WorldPose();
QVERIFY(startPose == ignition::math::Pose3d(5, -5, 2, 0, 0.275643, 2.35619));
gazebo::transport::NodePtr node = gazebo::transport::NodePtr(
new gazebo::transport::Node());
node->Init();
gazebo::transport::PublisherPtr joyPub =
node->Advertise<gazebo::msgs::Joystick>("~/user_camera/joy_twist");
// Test with just translation
{
gazebo::msgs::Joystick joystickMsg;
joystickMsg.mutable_translation()->set_x(0.1);
joystickMsg.mutable_translation()->set_y(0.2);
joystickMsg.mutable_translation()->set_z(0.3);
joyPub->Publish(joystickMsg);
this->ProcessEventsAndDraw(mainWindow);
ignition::math::Pose3d endPose = cam->WorldPose();
QVERIFY(endPose == ignition::math::Pose3d(4.98664, -5.00091, 2.01306,
0, 0.275643, 2.35619));
}
// Test with just rotation
{
gazebo::msgs::Joystick joystickMsg;
joystickMsg.mutable_rotation()->set_x(0.0);
joystickMsg.mutable_rotation()->set_y(0.1);
joystickMsg.mutable_rotation()->set_z(0.2);
joyPub->Publish(joystickMsg);
this->ProcessEventsAndDraw(mainWindow);
ignition::math::Pose3d endPose = cam->WorldPose();
QVERIFY(endPose == ignition::math::Pose3d(4.98664, -5.00091, 2.01306,
0, 0.276643, 2.36619));
}
// Test with both translation and rotation
{
gazebo::msgs::Joystick joystickMsg;
joystickMsg.mutable_translation()->set_x(1.0);
joystickMsg.mutable_translation()->set_y(2.1);
joystickMsg.mutable_translation()->set_z(3.2);
joystickMsg.mutable_rotation()->set_x(1.0);
joystickMsg.mutable_rotation()->set_y(2.1);
joystickMsg.mutable_rotation()->set_z(3.2);
joyPub->Publish(joystickMsg);
this->ProcessEventsAndDraw(mainWindow);
ignition::math::Pose3d endPose = cam->WorldPose();
QVERIFY(endPose == ignition::math::Pose3d(4.84758, -5.01151, 2.15333,
0, 0.297643, 2.52619));
}
cam->Fini();
mainWindow->close();
delete mainWindow;
}
/////////////////////////////////////////////////
void MainWindow_TEST::ActionCreationDestruction()
{
this->resMaxPercentChange = 5.0;
this->shareMaxPercentChange = 2.0;
this->Load("worlds/empty.world", false, false, false);
gazebo::gui::MainWindow *mainWindow = new gazebo::gui::MainWindow();
QVERIFY(mainWindow != NULL);
// Create the main window.
mainWindow->Load();
mainWindow->Init();
QVERIFY(gazebo::gui::g_topicVisAct);
QVERIFY(gazebo::gui::g_openAct);
QVERIFY(gazebo::gui::g_saveAct);
QVERIFY(gazebo::gui::g_saveAsAct);
QVERIFY(gazebo::gui::g_saveCfgAct);
QVERIFY(gazebo::gui::g_cloneAct);
QVERIFY(gazebo::gui::g_aboutAct);
QVERIFY(gazebo::gui::g_hotkeyChartAct);
QVERIFY(gazebo::gui::g_quitAct);
QVERIFY(gazebo::gui::g_resetModelsAct);
QVERIFY(gazebo::gui::g_resetWorldAct);
QVERIFY(gazebo::gui::g_editBuildingAct);
QVERIFY(gazebo::gui::g_editTerrainAct);
QVERIFY(gazebo::gui::g_editModelAct);
QVERIFY(gazebo::gui::g_stepAct);
QVERIFY(gazebo::gui::g_playAct);
QVERIFY(gazebo::gui::g_pauseAct);
QVERIFY(gazebo::gui::g_arrowAct);
QVERIFY(gazebo::gui::g_translateAct);
QVERIFY(gazebo::gui::g_rotateAct);
QVERIFY(gazebo::gui::g_scaleAct);
QVERIFY(gazebo::gui::g_boxCreateAct);
QVERIFY(gazebo::gui::g_sphereCreateAct);
QVERIFY(gazebo::gui::g_cylinderCreateAct);
QVERIFY(gazebo::gui::g_pointLghtCreateAct);
QVERIFY(gazebo::gui::g_spotLghtCreateAct);
QVERIFY(gazebo::gui::g_dirLghtCreateAct);
QVERIFY(gazebo::gui::g_resetAct);
QVERIFY(gazebo::gui::g_showCollisionsAct);
QVERIFY(gazebo::gui::g_showGridAct);
QVERIFY(gazebo::gui::g_showOriginAct);
QVERIFY(gazebo::gui::g_showLinkFrameAct);
QVERIFY(gazebo::gui::g_showSkeletonAct);
QVERIFY(gazebo::gui::g_transparentAct);
QVERIFY(gazebo::gui::g_viewWireframeAct);
QVERIFY(gazebo::gui::g_showCOMAct);
QVERIFY(gazebo::gui::g_showInertiaAct);
QVERIFY(gazebo::gui::g_showContactsAct);
QVERIFY(gazebo::gui::g_showJointsAct);
QVERIFY(gazebo::gui::g_showToolbarsAct);
QVERIFY(gazebo::gui::g_fullScreenAct);
QVERIFY(gazebo::gui::g_fpsAct);
QVERIFY(gazebo::gui::g_orbitAct);
QVERIFY(gazebo::gui::g_overlayAct);
QVERIFY(gazebo::gui::g_viewOculusAct);
QVERIFY(gazebo::gui::g_dataLoggerAct);
QVERIFY(gazebo::gui::g_screenshotAct);
QVERIFY(gazebo::gui::g_copyAct);
QVERIFY(gazebo::gui::g_pasteAct);
QVERIFY(gazebo::gui::g_snapAct);
QVERIFY(gazebo::gui::g_alignAct);
QVERIFY(gazebo::gui::g_viewAngleAct);
QVERIFY(gazebo::gui::g_cameraOrthoAct);
QVERIFY(gazebo::gui::g_cameraPerspectiveAct);
QVERIFY(gazebo::gui::g_undoAct);
QVERIFY(gazebo::gui::g_undoHistoryAct);
QVERIFY(gazebo::gui::g_redoAct);
QVERIFY(gazebo::gui::g_plotAct);
QVERIFY(gazebo::gui::g_redoHistoryAct);
this->ProcessEventsAndDraw(mainWindow);
mainWindow->close();
delete mainWindow;
QVERIFY(!gazebo::gui::g_topicVisAct);
QVERIFY(!gazebo::gui::g_openAct);
QVERIFY(!gazebo::gui::g_saveAct);
QVERIFY(!gazebo::gui::g_saveAsAct);
QVERIFY(!gazebo::gui::g_saveCfgAct);
QVERIFY(!gazebo::gui::g_cloneAct);
QVERIFY(!gazebo::gui::g_aboutAct);
QVERIFY(!gazebo::gui::g_hotkeyChartAct);
QVERIFY(!gazebo::gui::g_quitAct);
QVERIFY(!gazebo::gui::g_resetModelsAct);
QVERIFY(!gazebo::gui::g_resetWorldAct);
QVERIFY(!gazebo::gui::g_editBuildingAct);
QVERIFY(!gazebo::gui::g_editTerrainAct);
QVERIFY(!gazebo::gui::g_editModelAct);
QVERIFY(!gazebo::gui::g_stepAct);
QVERIFY(!gazebo::gui::g_playAct);
QVERIFY(!gazebo::gui::g_pauseAct);
QVERIFY(!gazebo::gui::g_arrowAct);
QVERIFY(!gazebo::gui::g_translateAct);
QVERIFY(!gazebo::gui::g_rotateAct);
QVERIFY(!gazebo::gui::g_scaleAct);
QVERIFY(!gazebo::gui::g_boxCreateAct);
QVERIFY(!gazebo::gui::g_sphereCreateAct);
QVERIFY(!gazebo::gui::g_cylinderCreateAct);
QVERIFY(!gazebo::gui::g_pointLghtCreateAct);
QVERIFY(!gazebo::gui::g_spotLghtCreateAct);
QVERIFY(!gazebo::gui::g_dirLghtCreateAct);
QVERIFY(!gazebo::gui::g_resetAct);
QVERIFY(!gazebo::gui::g_showCollisionsAct);
QVERIFY(!gazebo::gui::g_showGridAct);
QVERIFY(!gazebo::gui::g_showOriginAct);
QVERIFY(!gazebo::gui::g_showLinkFrameAct);
QVERIFY(!gazebo::gui::g_showSkeletonAct);
QVERIFY(!gazebo::gui::g_transparentAct);
QVERIFY(!gazebo::gui::g_viewWireframeAct);
QVERIFY(!gazebo::gui::g_showCOMAct);
QVERIFY(!gazebo::gui::g_showInertiaAct);
QVERIFY(!gazebo::gui::g_showContactsAct);
QVERIFY(!gazebo::gui::g_showJointsAct);
QVERIFY(!gazebo::gui::g_showToolbarsAct);
QVERIFY(!gazebo::gui::g_fullScreenAct);
QVERIFY(!gazebo::gui::g_fpsAct);
QVERIFY(!gazebo::gui::g_orbitAct);
QVERIFY(!gazebo::gui::g_overlayAct);
QVERIFY(!gazebo::gui::g_viewOculusAct);
QVERIFY(!gazebo::gui::g_dataLoggerAct);
QVERIFY(!gazebo::gui::g_screenshotAct);
QVERIFY(!gazebo::gui::g_copyAct);
QVERIFY(!gazebo::gui::g_pasteAct);
QVERIFY(!gazebo::gui::g_snapAct);
QVERIFY(!gazebo::gui::g_alignAct);
QVERIFY(!gazebo::gui::g_viewAngleAct);
QVERIFY(!gazebo::gui::g_cameraOrthoAct);
QVERIFY(!gazebo::gui::g_cameraPerspectiveAct);
QVERIFY(!gazebo::gui::g_undoAct);
QVERIFY(!gazebo::gui::g_undoHistoryAct);
QVERIFY(!gazebo::gui::g_redoAct);
QVERIFY(!gazebo::gui::g_redoHistoryAct);
QVERIFY(!gazebo::gui::g_plotAct);
}
/////////////////////////////////////////////////
void MainWindow_TEST::SetUserCameraPoseSDF()
{
this->resMaxPercentChange = 5.0;
this->shareMaxPercentChange = 2.0;
this->Load("worlds/usercamera_test.world", false, false, false);
gazebo::gui::MainWindow *mainWindow = new gazebo::gui::MainWindow();
QVERIFY(mainWindow != NULL);
// Create the main window.
mainWindow->Load();
mainWindow->Init();
mainWindow->show();
// Get the user camera and scene
gazebo::rendering::UserCameraPtr cam = gazebo::gui::get_active_camera();
QVERIFY(cam != NULL);
cam->SetCaptureData(true);
this->ProcessEventsAndDraw(mainWindow);
const unsigned char *data = cam->ImageData();
unsigned int width = cam->ImageWidth();
unsigned int height = cam->ImageHeight();
unsigned int depth = cam->ImageDepth();
// Part 1 : The user camera should be positioned so that it sees only
// a white box
{
int blackCount = 0;
// Get the number of black pixels
for (unsigned int y = 0; y < height; ++y)
{
for (unsigned int x = 0; x < width*depth; ++x)
{
if (data[y*(width*depth) + x] <= 10)
blackCount++;
}
}
// Make sure the black count is zero. This means the camera is
// positioned correctly
QVERIFY(blackCount == 0);
}
cam->Fini();
mainWindow->close();
delete mainWindow;
}
/////////////////////////////////////////////////
void MainWindow_TEST::MenuBar()
{
this->resMaxPercentChange = 5.0;
this->shareMaxPercentChange = 2.0;
this->Load("worlds/empty.world", false, false, false);
gazebo::gui::MainWindow *mainWindow = new gazebo::gui::MainWindow();
QVERIFY(mainWindow != NULL);
// Create the main window.
mainWindow->Load();
mainWindow->Init();
mainWindow->show();
// Get the user camera
gazebo::rendering::UserCameraPtr cam = gazebo::gui::get_active_camera();
QVERIFY(cam != NULL);
QList<QMenuBar *> menuBars = mainWindow->findChildren<QMenuBar *>();
QVERIFY(!menuBars.empty());
std::set<std::string> mainMenus;
mainMenus.insert("&File");
mainMenus.insert("&Edit");
mainMenus.insert("&Camera");
mainMenus.insert("&View");
mainMenus.insert("&Window");
mainMenus.insert("&Help");
// verify all menus are created in the menu bar.
std::set<std::string> mainMenusCopy = mainMenus;
QMenuBar *menuBar = menuBars[0];
QList<QMenu *> menus = menuBar->findChildren<QMenu *>();
for (auto &m : menus)
{
auto it = mainMenusCopy.find(m->title().toStdString());
QVERIFY(it != mainMenus.end());
mainMenusCopy.erase(it);
}
// test adding a new menu to the menu bar
QMenu newMenu(tr("&TEST"));
mainWindow->AddMenu(&newMenu);
QList<QMenu *> newMenus = menuBar->findChildren<QMenu *>();
mainMenusCopy = mainMenus;
mainMenusCopy.insert("&TEST");
for (auto &m : menus)
{
std::string title = m->title().toStdString();
auto it = mainMenusCopy.find(title);
QVERIFY(it != mainMenus.end());
mainMenusCopy.erase(it);
}
// test calling ShowMenuBar and verify all menus remain the same
mainWindow->ShowMenuBar();
menus = menuBar->findChildren<QMenu *>();
mainMenusCopy = mainMenus;
mainMenusCopy.insert("TEST");
for (auto &m : menus)
{
std::string title = m->title().toStdString();
auto it = mainMenusCopy.find(title);
QVERIFY(it != mainMenus.end());
mainMenusCopy.erase(title);
}
cam->Fini();
mainWindow->close();
delete mainWindow;
}
/////////////////////////////////////////////////
void MainWindow_TEST::WindowModes()
{
this->resMaxPercentChange = 5.0;
this->shareMaxPercentChange = 2.0;
this->Load("worlds/empty.world", false, false, false);
// Create the main window.
gazebo::gui::MainWindow *mainWindow = new gazebo::gui::MainWindow();
QVERIFY(mainWindow != NULL);
mainWindow->Load();
mainWindow->Init();
mainWindow->show();
this->ProcessEventsAndDraw(mainWindow);
// Check edit actions are visible
QVERIFY(gazebo::gui::g_resetModelsAct->isVisible());
QVERIFY(gazebo::gui::g_resetWorldAct->isVisible());
QVERIFY(gazebo::gui::g_editBuildingAct->isVisible());
QVERIFY(gazebo::gui::g_editModelAct->isVisible());
// Change to Model Editor mode
gazebo::gui::Events::windowMode("ModelEditor");
// Check edit actions are not visible
QVERIFY(!gazebo::gui::g_resetModelsAct->isVisible());
QVERIFY(!gazebo::gui::g_resetWorldAct->isVisible());
QVERIFY(!gazebo::gui::g_editBuildingAct->isVisible());
QVERIFY(!gazebo::gui::g_editModelAct->isVisible());
// Terminate
mainWindow->close();
delete mainWindow;
}
/////////////////////////////////////////////////
void MainWindow_TEST::MinimumSize()
{
this->resMaxPercentChange = 5.0;
this->shareMaxPercentChange = 2.0;
this->Load("worlds/empty.world", false, false, false);
gazebo::gui::MainWindow *mainWindow = new gazebo::gui::MainWindow();
QVERIFY(mainWindow != NULL);
// Create the main window.
mainWindow->Load();
mainWindow->Init();
// Check that minimum size is smaller then a predefined size
// This desired values are arbitrary, but increasing the minimum
// size could create problems on small screens (such as laptop's).
// See https://bitbucket.org/osrf/gazebo/issues/1706 for more info.
int desiredMinimumWidth = 700;
int desiredMinimumHeight = 710;
QVERIFY(mainWindow->minimumSize().width() <= desiredMinimumWidth);
QVERIFY(mainWindow->minimumSize().height() <= desiredMinimumHeight);
// Check that resizing to a small window (10x10) actually result
// in a size that is smaller then desiredMinimum*
mainWindow->resize(10, 10);
QVERIFY(mainWindow->width() <= desiredMinimumWidth);
QVERIFY(mainWindow->height() <= desiredMinimumHeight);
mainWindow->close();
delete mainWindow;
}
// Generate a main function for the test
QTEST_MAIN(MainWindow_TEST)
| 26.70188 | 79 | 0.667974 |
73e19b361341c44b0f1055ac366ff7077cfa0be4 | 1,803 | hpp | C++ | include/codegen/include/GlobalNamespace/Signal.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/GlobalNamespace/Signal.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/GlobalNamespace/Signal.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: UnityEngine.ScriptableObject
#include "UnityEngine/ScriptableObject.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Action
class Action;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Autogenerated type: Signal
class Signal : public UnityEngine::ScriptableObject {
public:
// private System.Action _event
// Offset: 0x18
System::Action* event;
// private System.Void add__event(System.Action value)
// Offset: 0xCBCAC0
void add__event(System::Action* value);
// private System.Void remove__event(System.Action value)
// Offset: 0xCBCB64
void remove__event(System::Action* value);
// public System.Void Raise()
// Offset: 0xCBCC08
void Raise();
// public System.Void Subscribe(System.Action foo)
// Offset: 0xCBCC1C
void Subscribe(System::Action* foo);
// public System.Void Unsubscribe(System.Action foo)
// Offset: 0xCBCC48
void Unsubscribe(System::Action* foo);
// public System.Void .ctor()
// Offset: 0xCBCC4C
// Implemented from: UnityEngine.ScriptableObject
// Base method: System.Void ScriptableObject::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
static Signal* New_ctor();
}; // Signal
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::Signal*, "", "Signal");
#pragma pack(pop)
| 34.018868 | 76 | 0.681642 |
73e1cf080b36f9cefe704a37fb5c7e8772e8978e | 28,726 | cc | C++ | DQMServices/FwkIO/plugins/DQMRootSource.cc | CeliaFernandez/cmssw | bec73cc7eebb30608c73685df0ff07025d838dd2 | [
"Apache-2.0"
] | 13 | 2015-11-30T15:49:45.000Z | 2022-02-08T16:11:30.000Z | DQMServices/FwkIO/plugins/DQMRootSource.cc | CeliaFernandez/cmssw | bec73cc7eebb30608c73685df0ff07025d838dd2 | [
"Apache-2.0"
] | 640 | 2015-02-11T18:55:47.000Z | 2022-03-31T14:12:23.000Z | DQMServices/FwkIO/plugins/DQMRootSource.cc | CeliaFernandez/cmssw | bec73cc7eebb30608c73685df0ff07025d838dd2 | [
"Apache-2.0"
] | 51 | 2015-08-11T21:01:40.000Z | 2022-03-30T07:31:34.000Z | // -*- C++ -*-
//
// Package: FwkIO
// Class : DQMRootSource
//
// Implementation:
// [Notes on implementation]
//
// Original Author: Chris Jones
// Created: Tue May 3 11:13:47 CDT 2011
//
// system include files
#include <memory>
#include "TFile.h"
#include "TString.h"
#include "TTree.h"
#include <map>
#include <string>
#include <vector>
#include "DQMServices/Core/interface/DQMStore.h"
#include "DataFormats/Histograms/interface/DQMToken.h"
#include "FWCore/ServiceRegistry/interface/Service.h"
#include "FWCore/Framework/interface/InputSource.h"
#include "FWCore/Sources/interface/PuttableSourceBase.h"
#include "FWCore/Catalog/interface/InputFileCatalog.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/Utilities/interface/ExceptionPropagate.h"
#include "FWCore/Framework/interface/RunPrincipal.h"
#include "FWCore/Framework/interface/LuminosityBlockPrincipal.h"
#include "FWCore/Framework/interface/Run.h"
#include "FWCore/Framework/interface/LuminosityBlock.h"
#include "DataFormats/Provenance/interface/LuminosityBlockID.h"
#include "DataFormats/Provenance/interface/LuminosityBlockRange.h"
#include "DataFormats/Provenance/interface/ProcessHistoryRegistry.h"
#include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h"
#include "FWCore/ParameterSet/interface/ParameterSetDescription.h"
#include "FWCore/Framework/interface/InputSourceMacros.h"
#include "FWCore/Framework/interface/FileBlock.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "FWCore/MessageLogger/interface/JobReport.h"
#include "FWCore/Utilities/interface/TimeOfDay.h"
#include "format.h"
// class rather than namespace so we can make this a friend of the
// MonitorElement to get access to constructors etc.
struct DQMTTreeIO {
typedef dqm::harvesting::MonitorElement MonitorElement;
typedef dqm::harvesting::DQMStore DQMStore;
// TODO: this should probably be moved somewhere else
class DQMMergeHelper {
public:
// Utility function to check the consistency of the axis labels
// Taken from TH1::CheckBinLabels which is not public
static bool CheckBinLabels(const TAxis* a1, const TAxis* a2) {
// Check that axis have same labels
THashList* l1 = (const_cast<TAxis*>(a1))->GetLabels();
THashList* l2 = (const_cast<TAxis*>(a2))->GetLabels();
if (!l1 && !l2)
return true;
if (!l1 || !l2) {
return false;
}
// Check now labels sizes are the same
if (l1->GetSize() != l2->GetSize()) {
return false;
}
for (int i = 1; i <= a1->GetNbins(); ++i) {
std::string_view label1 = a1->GetBinLabel(i);
std::string_view label2 = a2->GetBinLabel(i);
if (label1 != label2) {
return false;
}
}
return true;
}
// NOTE: the merge logic comes from DataFormats/Histograms/interface/MEtoEDMFormat.h
static void mergeTogether(TH1* original, TH1* toAdd) {
if (original->CanExtendAllAxes() && toAdd->CanExtendAllAxes()) {
TList list;
list.Add(toAdd);
if (original->Merge(&list) == -1) {
edm::LogError("MergeFailure") << "Failed to merge DQM element " << original->GetName();
}
} else {
// TODO: Redo. This is both more strict than what ROOT checks for yet
// allows cases where ROOT fails with merging.
if (original->GetNbinsX() == toAdd->GetNbinsX() &&
original->GetXaxis()->GetXmin() == toAdd->GetXaxis()->GetXmin() &&
original->GetXaxis()->GetXmax() == toAdd->GetXaxis()->GetXmax() &&
original->GetNbinsY() == toAdd->GetNbinsY() &&
original->GetYaxis()->GetXmin() == toAdd->GetYaxis()->GetXmin() &&
original->GetYaxis()->GetXmax() == toAdd->GetYaxis()->GetXmax() &&
original->GetNbinsZ() == toAdd->GetNbinsZ() &&
original->GetZaxis()->GetXmin() == toAdd->GetZaxis()->GetXmin() &&
original->GetZaxis()->GetXmax() == toAdd->GetZaxis()->GetXmax() &&
CheckBinLabels(original->GetXaxis(), toAdd->GetXaxis()) &&
CheckBinLabels(original->GetYaxis(), toAdd->GetYaxis()) &&
CheckBinLabels(original->GetZaxis(), toAdd->GetZaxis())) {
original->Add(toAdd);
} else {
edm::LogError("MergeFailure") << "Found histograms with different axis limits or different labels '"
<< original->GetName() << "' not merged.";
}
}
}
};
// This struct allows to find all MEs belonging to a run-lumi pair
// All files will be open at once so m_file property indicates the file where data is saved.
struct FileMetadata {
unsigned int m_run;
unsigned int m_lumi;
ULong64_t m_beginTime;
ULong64_t m_endTime;
ULong64_t m_firstIndex;
ULong64_t m_lastIndex; // Last is inclusive
unsigned int m_type;
TFile* m_file;
// This will be used when sorting a vector
bool operator<(const FileMetadata& obj) const {
if (m_run == obj.m_run)
return m_lumi < obj.m_lumi;
else
return m_run < obj.m_run;
}
void describe() {
std::cout << "read r:" << m_run << " l:" << m_lumi << " bt:" << m_beginTime << " et:" << m_endTime
<< " fi:" << m_firstIndex << " li:" << m_lastIndex << " type:" << m_type << " file: " << m_file
<< std::endl;
}
};
class TreeReaderBase {
public:
TreeReaderBase(MonitorElementData::Kind kind, MonitorElementData::Scope rescope)
: m_kind(kind), m_rescope(rescope) {}
virtual ~TreeReaderBase() {}
MonitorElementData::Key makeKey(std::string const& fullname, int run, int lumi) {
MonitorElementData::Key key;
key.kind_ = m_kind;
key.path_.set(fullname, MonitorElementData::Path::Type::DIR_AND_NAME);
if (m_rescope == MonitorElementData::Scope::LUMI) {
// no rescoping
key.scope_ = lumi == 0 ? MonitorElementData::Scope::RUN : MonitorElementData::Scope::LUMI;
key.id_ = edm::LuminosityBlockID(run, lumi);
} else if (m_rescope == MonitorElementData::Scope::RUN) {
// everything becomes run, we'll never see Scope::JOB inside DQMIO files.
key.scope_ = MonitorElementData::Scope::RUN;
key.id_ = edm::LuminosityBlockID(run, 0);
} else if (m_rescope == MonitorElementData::Scope::JOB) {
// Everything is aggregated over the entire job.
key.scope_ = MonitorElementData::Scope::JOB;
key.id_ = edm::LuminosityBlockID(0, 0);
} else {
assert(!"Invalid Scope in rescope option.");
}
return key;
}
virtual void read(ULong64_t iIndex, DQMStore* dqmstore, int run, int lumi) = 0;
virtual void setTree(TTree* iTree) = 0;
protected:
MonitorElementData::Kind m_kind;
MonitorElementData::Scope m_rescope;
};
template <class T>
class TreeObjectReader : public TreeReaderBase {
public:
TreeObjectReader(MonitorElementData::Kind kind, MonitorElementData::Scope rescope) : TreeReaderBase(kind, rescope) {
assert(m_kind != MonitorElementData::Kind::INT);
assert(m_kind != MonitorElementData::Kind::REAL);
assert(m_kind != MonitorElementData::Kind::STRING);
}
void read(ULong64_t iIndex, DQMStore* dqmstore, int run, int lumi) override {
// This will populate the fields as defined in setTree method
m_tree->GetEntry(iIndex);
auto key = makeKey(*m_fullName, run, lumi);
auto existing = dqmstore->findOrRecycle(key);
if (existing) {
// TODO: make sure there is sufficient locking here.
DQMMergeHelper::mergeTogether(existing->getTH1(), m_buffer);
} else {
// We make our own MEs here, to avoid a round-trip through the booking API.
MonitorElementData meData;
meData.key_ = key;
meData.value_.object_ = std::unique_ptr<T>((T*)(m_buffer->Clone()));
auto me = new MonitorElement(std::move(meData));
dqmstore->putME(me);
}
}
void setTree(TTree* iTree) override {
m_tree = iTree;
m_tree->SetBranchAddress(kFullNameBranch, &m_fullName);
m_tree->SetBranchAddress(kFlagBranch, &m_tag);
m_tree->SetBranchAddress(kValueBranch, &m_buffer);
}
private:
TTree* m_tree = nullptr;
std::string* m_fullName = nullptr;
T* m_buffer = nullptr;
uint32_t m_tag = 0;
};
class TreeStringReader : public TreeReaderBase {
public:
TreeStringReader(MonitorElementData::Kind kind, MonitorElementData::Scope rescope) : TreeReaderBase(kind, rescope) {
assert(m_kind == MonitorElementData::Kind::STRING);
}
void read(ULong64_t iIndex, DQMStore* dqmstore, int run, int lumi) override {
// This will populate the fields as defined in setTree method
m_tree->GetEntry(iIndex);
auto key = makeKey(*m_fullName, run, lumi);
auto existing = dqmstore->findOrRecycle(key);
if (existing) {
existing->Fill(*m_value);
} else {
// We make our own MEs here, to avoid a round-trip through the booking API.
MonitorElementData meData;
meData.key_ = key;
meData.value_.scalar_.str = *m_value;
auto me = new MonitorElement(std::move(meData));
dqmstore->putME(me);
}
}
void setTree(TTree* iTree) override {
m_tree = iTree;
m_tree->SetBranchAddress(kFullNameBranch, &m_fullName);
m_tree->SetBranchAddress(kFlagBranch, &m_tag);
m_tree->SetBranchAddress(kValueBranch, &m_value);
}
private:
TTree* m_tree = nullptr;
std::string* m_fullName = nullptr;
std::string* m_value = nullptr;
uint32_t m_tag = 0;
};
template <class T>
class TreeSimpleReader : public TreeReaderBase {
public:
TreeSimpleReader(MonitorElementData::Kind kind, MonitorElementData::Scope rescope) : TreeReaderBase(kind, rescope) {
assert(m_kind == MonitorElementData::Kind::INT || m_kind == MonitorElementData::Kind::REAL);
}
void read(ULong64_t iIndex, DQMStore* dqmstore, int run, int lumi) override {
// This will populate the fields as defined in setTree method
m_tree->GetEntry(iIndex);
auto key = makeKey(*m_fullName, run, lumi);
auto existing = dqmstore->findOrRecycle(key);
if (existing) {
existing->Fill(m_buffer);
} else {
// We make our own MEs here, to avoid a round-trip through the booking API.
MonitorElementData meData;
meData.key_ = key;
if (m_kind == MonitorElementData::Kind::INT)
meData.value_.scalar_.num = m_buffer;
else if (m_kind == MonitorElementData::Kind::REAL)
meData.value_.scalar_.real = m_buffer;
auto me = new MonitorElement(std::move(meData));
dqmstore->putME(me);
}
}
void setTree(TTree* iTree) override {
m_tree = iTree;
m_tree->SetBranchAddress(kFullNameBranch, &m_fullName);
m_tree->SetBranchAddress(kFlagBranch, &m_tag);
m_tree->SetBranchAddress(kValueBranch, &m_buffer);
}
private:
TTree* m_tree = nullptr;
std::string* m_fullName = nullptr;
T m_buffer = 0;
uint32_t m_tag = 0;
};
};
class DQMRootSource : public edm::PuttableSourceBase, DQMTTreeIO {
public:
DQMRootSource(edm::ParameterSet const&, const edm::InputSourceDescription&);
~DQMRootSource() override;
// ---------- const member functions ---------------------
// ---------- static member functions --------------------
// ---------- member functions ---------------------------
static void fillDescriptions(edm::ConfigurationDescriptions& descriptions);
private:
DQMRootSource(const DQMRootSource&) = delete;
edm::InputSource::ItemType getNextItemType() override;
std::shared_ptr<edm::FileBlock> readFile_() override;
std::shared_ptr<edm::RunAuxiliary> readRunAuxiliary_() override;
std::shared_ptr<edm::LuminosityBlockAuxiliary> readLuminosityBlockAuxiliary_() override;
void readRun_(edm::RunPrincipal& rpCache) override;
void readLuminosityBlock_(edm::LuminosityBlockPrincipal& lbCache) override;
void readEvent_(edm::EventPrincipal&) override;
// Read MEs from m_fileMetadatas to DQMStore till run or lumi transition
void readElements();
// True if m_currentIndex points to an element that has a different
// run or lumi than the previous element (a transition needs to happen).
// False otherwise.
bool isRunOrLumiTransition() const;
void readNextItemType();
// These methods will be called by the framework.
// MEs in DQMStore will be put to products.
void beginRun(edm::Run& run) override;
void beginLuminosityBlock(edm::LuminosityBlock& lumi) override;
// If the run matches the filterOnRun configuration parameter, the run
// (and all its lumis) will be kept.
// Otherwise, check if a run and a lumi are in the range that needs to be processed.
// Range is retrieved from lumisToProcess configuration parameter.
// If at least one lumi of a run needs to be kept, per run MEs of that run will also be kept.
bool keepIt(edm::RunNumber_t, edm::LuminosityBlockNumber_t) const;
void logFileAction(char const* msg, char const* fileName) const;
const DQMRootSource& operator=(const DQMRootSource&) = delete; // stop default
// ---------- member data --------------------------------
// Properties from python config
bool m_skipBadFiles;
unsigned int m_filterOnRun;
edm::InputFileCatalog m_catalog;
std::vector<edm::LuminosityBlockRange> m_lumisToProcess;
MonitorElementData::Scope m_rescope;
edm::InputSource::ItemType m_nextItemType;
// Each ME type gets its own reader
std::vector<std::shared_ptr<TreeReaderBase>> m_treeReaders;
// Index of currenlty processed row in m_fileMetadatas
unsigned int m_currentIndex;
// All open DQMIO files
std::vector<TFile*> m_openFiles;
// An item here is a row read from DQMIO indices (metadata) table
std::vector<FileMetadata> m_fileMetadatas;
};
//
// constants, enums and typedefs
//
//
// static data member definitions
//
void DQMRootSource::fillDescriptions(edm::ConfigurationDescriptions& descriptions) {
edm::ParameterSetDescription desc;
desc.addUntracked<std::vector<std::string>>("fileNames")->setComment("Names of files to be processed.");
desc.addUntracked<unsigned int>("filterOnRun", 0)->setComment("Just limit the process to the selected run.");
desc.addUntracked<std::string>("reScope", "JOB")
->setComment(
"Accumulate histograms more coarsely."
" Options: \"\": keep unchanged, \"RUN\": turn LUMI histograms into RUN histograms, \"JOB\": turn everything "
"into JOB histograms.");
desc.addUntracked<bool>("skipBadFiles", false)->setComment("Skip the file if it is not valid");
desc.addUntracked<std::string>("overrideCatalog", std::string())
->setComment("An alternate file catalog to use instead of the standard site one.");
std::vector<edm::LuminosityBlockRange> defaultLumis;
desc.addUntracked<std::vector<edm::LuminosityBlockRange>>("lumisToProcess", defaultLumis)
->setComment("Skip any lumi inside the specified run:lumi range.");
descriptions.addDefault(desc);
}
//
// constructors and destructor
//
DQMRootSource::DQMRootSource(edm::ParameterSet const& iPSet, const edm::InputSourceDescription& iDesc)
: edm::PuttableSourceBase(iPSet, iDesc),
m_skipBadFiles(iPSet.getUntrackedParameter<bool>("skipBadFiles", false)),
m_filterOnRun(iPSet.getUntrackedParameter<unsigned int>("filterOnRun", 0)),
m_catalog(iPSet.getUntrackedParameter<std::vector<std::string>>("fileNames"),
iPSet.getUntrackedParameter<std::string>("overrideCatalog")),
m_lumisToProcess(iPSet.getUntrackedParameter<std::vector<edm::LuminosityBlockRange>>(
"lumisToProcess", std::vector<edm::LuminosityBlockRange>())),
m_rescope(std::map<std::string, MonitorElementData::Scope>{
{"", MonitorElementData::Scope::LUMI},
{"LUMI", MonitorElementData::Scope::LUMI},
{"RUN", MonitorElementData::Scope::RUN},
{"JOB", MonitorElementData::Scope::JOB}}[iPSet.getUntrackedParameter<std::string>("reScope", "JOB")]),
m_nextItemType(edm::InputSource::IsFile),
m_treeReaders(kNIndicies, std::shared_ptr<TreeReaderBase>()),
m_currentIndex(0),
m_openFiles(std::vector<TFile*>()),
m_fileMetadatas(std::vector<FileMetadata>()) {
edm::sortAndRemoveOverlaps(m_lumisToProcess);
if (m_catalog.fileNames(0).empty()) {
m_nextItemType = edm::InputSource::IsStop;
} else {
m_treeReaders[kIntIndex].reset(new TreeSimpleReader<Long64_t>(MonitorElementData::Kind::INT, m_rescope));
m_treeReaders[kFloatIndex].reset(new TreeSimpleReader<double>(MonitorElementData::Kind::REAL, m_rescope));
m_treeReaders[kStringIndex].reset(new TreeStringReader(MonitorElementData::Kind::STRING, m_rescope));
m_treeReaders[kTH1FIndex].reset(new TreeObjectReader<TH1F>(MonitorElementData::Kind::TH1F, m_rescope));
m_treeReaders[kTH1SIndex].reset(new TreeObjectReader<TH1S>(MonitorElementData::Kind::TH1S, m_rescope));
m_treeReaders[kTH1DIndex].reset(new TreeObjectReader<TH1D>(MonitorElementData::Kind::TH1D, m_rescope));
m_treeReaders[kTH2FIndex].reset(new TreeObjectReader<TH2F>(MonitorElementData::Kind::TH2F, m_rescope));
m_treeReaders[kTH2SIndex].reset(new TreeObjectReader<TH2S>(MonitorElementData::Kind::TH2S, m_rescope));
m_treeReaders[kTH2DIndex].reset(new TreeObjectReader<TH2D>(MonitorElementData::Kind::TH2D, m_rescope));
m_treeReaders[kTH3FIndex].reset(new TreeObjectReader<TH3F>(MonitorElementData::Kind::TH3F, m_rescope));
m_treeReaders[kTProfileIndex].reset(new TreeObjectReader<TProfile>(MonitorElementData::Kind::TPROFILE, m_rescope));
m_treeReaders[kTProfile2DIndex].reset(
new TreeObjectReader<TProfile2D>(MonitorElementData::Kind::TPROFILE2D, m_rescope));
}
produces<DQMToken, edm::Transition::BeginRun>("DQMGenerationRecoRun");
produces<DQMToken, edm::Transition::BeginLuminosityBlock>("DQMGenerationRecoLumi");
}
DQMRootSource::~DQMRootSource() {
for (auto& file : m_openFiles) {
if (file != nullptr && file->IsOpen()) {
file->Close();
logFileAction("Closed file", "");
}
}
}
//
// member functions
//
edm::InputSource::ItemType DQMRootSource::getNextItemType() { return m_nextItemType; }
// We will read the metadata of all files and fill m_fileMetadatas vector
std::shared_ptr<edm::FileBlock> DQMRootSource::readFile_() {
const int numFiles = m_catalog.fileNames(0).size();
m_openFiles.reserve(numFiles);
for (auto& fileitem : m_catalog.fileCatalogItems()) {
TFile* file;
std::list<std::string> exInfo;
//loop over names of a file, each of them corresponds to a data catalog
bool isGoodFile(true);
//get all names of a file, each of them corresponds to a data catalog
const std::vector<std::string>& fNames = fileitem.fileNames();
for (std::vector<std::string>::const_iterator it = fNames.begin(); it != fNames.end(); ++it) {
// Try to open a file
try {
file = TFile::Open(it->c_str());
// Exception will be trapped so we pull it out ourselves
std::exception_ptr e = edm::threadLocalException::getException();
if (e != std::exception_ptr()) {
edm::threadLocalException::setException(std::exception_ptr());
std::rethrow_exception(e);
}
} catch (cms::Exception const& e) {
file = nullptr; // is there anything we need to free?
if (std::next(it) == fNames.end()) { //last name corresponding to the last data catalog to try
if (!m_skipBadFiles) {
edm::Exception ex(edm::errors::FileOpenError, "", e);
ex.addContext("Opening DQM Root file");
ex << "\nInput file " << it->c_str() << " was not found, could not be opened, or is corrupted.\n";
//report previous exceptions when use other names to open file
for (auto const& s : exInfo)
ex.addAdditionalInfo(s);
throw ex;
}
isGoodFile = false;
}
// save in case of error when trying next name
for (auto const& s : e.additionalInfo())
exInfo.push_back(s);
}
// Check if a file is usable
if (file && !file->IsZombie()) {
logFileAction("Successfully opened file ", it->c_str());
break;
} else {
if (std::next(it) == fNames.end()) {
if (!m_skipBadFiles) {
edm::Exception ex(edm::errors::FileOpenError);
ex << "Input file " << it->c_str() << " could not be opened.\n";
ex.addContext("Opening DQM Root file");
//report previous exceptions when use other names to open file
for (auto const& s : exInfo)
ex.addAdditionalInfo(s);
throw ex;
}
isGoodFile = false;
}
if (file) {
delete file;
file = nullptr;
}
}
} //end loop over names of the file
if (!isGoodFile && m_skipBadFiles)
continue;
m_openFiles.insert(m_openFiles.begin(), file);
// Check file format version, which is encoded in the Title of the TFile
if (strcmp(file->GetTitle(), "1") != 0) {
edm::Exception ex(edm::errors::FileReadError);
ex << "Input file " << fNames[0].c_str() << " does not appear to be a DQM Root file.\n";
}
// Read metadata from the file
TTree* indicesTree = dynamic_cast<TTree*>(file->Get(kIndicesTree));
assert(indicesTree != nullptr);
FileMetadata temp;
// Each line of metadata will be read into the coresponding fields of temp.
indicesTree->SetBranchAddress(kRunBranch, &temp.m_run);
indicesTree->SetBranchAddress(kLumiBranch, &temp.m_lumi);
indicesTree->SetBranchAddress(kBeginTimeBranch, &temp.m_beginTime);
indicesTree->SetBranchAddress(kEndTimeBranch, &temp.m_endTime);
indicesTree->SetBranchAddress(kTypeBranch, &temp.m_type);
indicesTree->SetBranchAddress(kFirstIndex, &temp.m_firstIndex);
indicesTree->SetBranchAddress(kLastIndex, &temp.m_lastIndex);
for (Long64_t index = 0; index != indicesTree->GetEntries(); ++index) {
indicesTree->GetEntry(index);
temp.m_file = file;
if (keepIt(temp.m_run, temp.m_lumi)) {
m_fileMetadatas.push_back(temp);
}
}
} //end loop over files
// Sort to make sure runs and lumis appear in sequential order
std::stable_sort(m_fileMetadatas.begin(), m_fileMetadatas.end());
// If we have lumisections without matching runs, insert dummy runs here.
unsigned int run = 0;
auto toadd = std::vector<FileMetadata>();
for (auto& metadata : m_fileMetadatas) {
if (run < metadata.m_run && metadata.m_lumi != 0) {
// run transition and lumi transition at the same time!
FileMetadata dummy{}; // zero initialize
dummy.m_run = metadata.m_run;
dummy.m_lumi = 0;
dummy.m_type = kNoTypesStored;
toadd.push_back(dummy);
}
run = metadata.m_run;
}
if (!toadd.empty()) {
// rather than trying to insert at the right places, just append and sort again.
m_fileMetadatas.insert(m_fileMetadatas.end(), toadd.begin(), toadd.end());
std::stable_sort(m_fileMetadatas.begin(), m_fileMetadatas.end());
}
//for (auto& metadata : m_fileMetadatas)
// metadata.describe();
// Stop if there's nothing to process. Otherwise start the run.
if (m_fileMetadatas.empty())
m_nextItemType = edm::InputSource::IsStop;
else
m_nextItemType = edm::InputSource::IsRun;
// We have to return something but not sure why
return std::make_shared<edm::FileBlock>();
}
std::shared_ptr<edm::RunAuxiliary> DQMRootSource::readRunAuxiliary_() {
FileMetadata metadata = m_fileMetadatas[m_currentIndex];
auto runAux =
edm::RunAuxiliary(metadata.m_run, edm::Timestamp(metadata.m_beginTime), edm::Timestamp(metadata.m_endTime));
return std::make_shared<edm::RunAuxiliary>(runAux);
}
std::shared_ptr<edm::LuminosityBlockAuxiliary> DQMRootSource::readLuminosityBlockAuxiliary_() {
FileMetadata metadata = m_fileMetadatas[m_currentIndex];
auto lumiAux = edm::LuminosityBlockAuxiliary(edm::LuminosityBlockID(metadata.m_run, metadata.m_lumi),
edm::Timestamp(metadata.m_beginTime),
edm::Timestamp(metadata.m_endTime));
return std::make_shared<edm::LuminosityBlockAuxiliary>(lumiAux);
}
void DQMRootSource::readRun_(edm::RunPrincipal& rpCache) {
// Read elements of a current run.
do {
FileMetadata metadata = m_fileMetadatas[m_currentIndex];
if (metadata.m_lumi == 0) {
readElements();
}
m_currentIndex++;
} while (!isRunOrLumiTransition());
readNextItemType();
edm::Service<edm::JobReport> jr;
jr->reportInputRunNumber(rpCache.id().run());
rpCache.fillRunPrincipal(processHistoryRegistryForUpdate());
}
void DQMRootSource::readLuminosityBlock_(edm::LuminosityBlockPrincipal& lbCache) {
// Read elements of a current lumi.
do {
readElements();
m_currentIndex++;
} while (!isRunOrLumiTransition());
readNextItemType();
edm::Service<edm::JobReport> jr;
jr->reportInputLumiSection(lbCache.id().run(), lbCache.id().luminosityBlock());
lbCache.fillLuminosityBlockPrincipal(processHistoryRegistry().getMapped(lbCache.aux().processHistoryID()));
}
void DQMRootSource::readEvent_(edm::EventPrincipal&) {}
void DQMRootSource::readElements() {
FileMetadata metadata = m_fileMetadatas[m_currentIndex];
if (metadata.m_type != kNoTypesStored) {
std::shared_ptr<TreeReaderBase> reader = m_treeReaders[metadata.m_type];
TTree* tree = dynamic_cast<TTree*>(metadata.m_file->Get(kTypeNames[metadata.m_type]));
// The Reset() below screws up the tree, so we need to re-read it from file
// before use here.
tree->Refresh();
reader->setTree(tree);
ULong64_t index = metadata.m_firstIndex;
ULong64_t endIndex = metadata.m_lastIndex + 1;
for (; index != endIndex; ++index) {
reader->read(index, edm::Service<DQMStore>().operator->(), metadata.m_run, metadata.m_lumi);
}
// Drop buffers in the TTree. This reduces memory consuption while the tree
// just sits there and waits for the next block to be read.
tree->Reset();
}
}
bool DQMRootSource::isRunOrLumiTransition() const {
if (m_currentIndex == 0) {
return false;
}
if (m_currentIndex > m_fileMetadatas.size() - 1) {
// We reached the end
return true;
}
FileMetadata previousMetadata = m_fileMetadatas[m_currentIndex - 1];
FileMetadata metadata = m_fileMetadatas[m_currentIndex];
return previousMetadata.m_run != metadata.m_run || previousMetadata.m_lumi != metadata.m_lumi;
}
void DQMRootSource::readNextItemType() {
if (m_currentIndex == 0) {
m_nextItemType = edm::InputSource::IsRun;
} else if (m_currentIndex > m_fileMetadatas.size() - 1) {
// We reached the end
m_nextItemType = edm::InputSource::IsStop;
} else {
FileMetadata previousMetadata = m_fileMetadatas[m_currentIndex - 1];
FileMetadata metadata = m_fileMetadatas[m_currentIndex];
if (previousMetadata.m_run != metadata.m_run) {
m_nextItemType = edm::InputSource::IsRun;
} else if (previousMetadata.m_lumi != metadata.m_lumi) {
m_nextItemType = edm::InputSource::IsLumi;
}
}
}
void DQMRootSource::beginRun(edm::Run& run) {
std::unique_ptr<DQMToken> product = std::make_unique<DQMToken>();
run.put(std::move(product), "DQMGenerationRecoRun");
}
void DQMRootSource::beginLuminosityBlock(edm::LuminosityBlock& lumi) {
std::unique_ptr<DQMToken> product = std::make_unique<DQMToken>();
lumi.put(std::move(product), "DQMGenerationRecoLumi");
}
bool DQMRootSource::keepIt(edm::RunNumber_t run, edm::LuminosityBlockNumber_t lumi) const {
if (m_filterOnRun != 0 && run != m_filterOnRun) {
return false;
}
if (m_lumisToProcess.empty()) {
return true;
}
for (edm::LuminosityBlockRange const& lumiToProcess : m_lumisToProcess) {
if (run >= lumiToProcess.startRun() && run <= lumiToProcess.endRun()) {
if (lumi >= lumiToProcess.startLumi() && lumi <= lumiToProcess.endLumi()) {
return true;
} else if (lumi == 0) {
return true;
}
}
}
return false;
}
void DQMRootSource::logFileAction(char const* msg, char const* fileName) const {
edm::LogAbsolute("fileAction") << std::setprecision(0) << edm::TimeOfDay() << msg << fileName;
edm::FlushMessageLog();
}
//
// const member functions
//
//
// static member functions
//
DEFINE_FWK_INPUT_SOURCE(DQMRootSource);
| 37.94716 | 120 | 0.673641 |
73e91ae21e15576fe964195706b03b050e612660 | 4,527 | cpp | C++ | RP_PCA9554/src/RP_PCA9554.cpp | rapola/RP_PCA9554 | c6186c17ab0666418f0ae695a9be45a202aa5e0d | [
"MIT"
] | null | null | null | RP_PCA9554/src/RP_PCA9554.cpp | rapola/RP_PCA9554 | c6186c17ab0666418f0ae695a9be45a202aa5e0d | [
"MIT"
] | null | null | null | RP_PCA9554/src/RP_PCA9554.cpp | rapola/RP_PCA9554 | c6186c17ab0666418f0ae695a9be45a202aa5e0d | [
"MIT"
] | null | null | null |
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include "RP_PCA9554.h"
#include "Wire.h"
/* ###########################################################################
* constructor
*/
PCA9554::PCA9554() {
Wire.begin(); // start I2C communication
}
/* ###########################################################################
* initialisation
*/
uint8_t PCA9554::init(uint8_t i2caddr){
uint8_t err;
uint8_t input;
_i2caddr = i2caddr;
//set the input to zero
_inPort0Level = 0x00;
//_inPort1Level = 0x00;
//read the status of port direction register
_cfgPort0Direction = 0xFF; //default: all input (1)
//_cfgPort1Direction = 0xFF;
Wire.beginTransmission(_i2caddr);
Wire.write(PCA9554_CONFIG);
err = Wire.endTransmission();
if(err != 0){ //sucess
return err;
}
err = Wire.requestFrom(_i2caddr, 0x01);
if(Wire.available() > 0){
_cfgPort0Direction = Wire.read();
}
else{
return err;
}
//read the status of port level register
_cfgPort0Level = 0xFF; //default: all high (1)
//_cfgPort1Level = 0xFF;
Wire.beginTransmission(_i2caddr);
Wire.write(PCA9554_OUTPUT);
err = Wire.endTransmission();
if(err != 0){ //sucess
return err;
}
err = Wire.requestFrom(_i2caddr, 0x01);
if(Wire.available() > 0){
_cfgPort0Level = Wire.read();
}
else{
return err;
}
return 0;
}
/* ###########################################################################
* pinModeBuf
*/
uint8_t PCA9554::pinModeBuf(uint8_t pin, uint8_t Mode){
if(Mode == OUTPUT){
if(pin < 8){
_cfgPort0Direction &= ~(1 << pin); //set pin bit to zero
return 0;
}
}
if(Mode == INPUT){
if(pin < 8){
_cfgPort0Direction |= (1 << pin); //set pin bit to one
return 0;
}
}
return 0xFF;
}
/* ###########################################################################
* pinModeUpdate
*/
uint8_t PCA9554::pinModeUpdate(){
uint8_t err;
Wire.beginTransmission(_i2caddr);
Wire.write(PCA9554_CONFIG);
Wire.write(_cfgPort0Direction);
//Wire.write(_cfgPort1Direction);
err = Wire.endTransmission();
if(err != 0){ //sucess
return err;
}
}
/* ###########################################################################
* pinMode
*/
uint8_t PCA9554::pinMode(uint8_t pin, uint8_t Mode){
uint8_t err;
err = pinModeBuf(pin, Mode);
if(err != 0){
return err;
}
err = pinModeUpdate();
return err;
}
/* ###########################################################################
* digitalWriteBuf
*/
uint8_t PCA9554::digitalWriteBuf(uint8_t pin, uint8_t level){
uint8_t err;
if(level == 0x00){
if(pin < 8){
_cfgPort0Level &= ~(1 << pin); //set pin bit to zero
return 0;
}
}
else{
if(pin < 8){
_cfgPort0Level |= (1 << pin); //set pin bit to one
return 0;
}
}
return 0xFF;
}
/* ###########################################################################
* writeBufUpdate
*/
uint8_t PCA9554::writeBufUpdate(){
uint8_t err;
Wire.beginTransmission(_i2caddr);
Wire.write(PCA9554_OUTPUT);
Wire.write(_cfgPort0Level);
//Wire.write(_cfgPort1Level);
err = Wire.endTransmission();
if(err != 0){ //sucess
return err;
}
}
/* ###########################################################################
* digitalWrite
*/
uint8_t PCA9554::digitalWrite(uint8_t pin, uint8_t level){
uint8_t err;
err = digitalWriteBuf(pin, level);
if(err != 0){
return err;
}
err = writeBufUpdate();
return err;
}
/* ###########################################################################
* readBufUpdate
*/
uint8_t PCA9554::readBufUpdate(){
uint8_t err;
Wire.beginTransmission(_i2caddr);
Wire.write(PCA9554_INPUT);
err = Wire.endTransmission();
if(err != 0){ //sucess
return err;
}
err = Wire.requestFrom(_i2caddr, 0x01);
if(Wire.available() > 0){
_inPort0Level = Wire.read();
}
else{
return err;
}
return 0;
}
/* ###########################################################################
* digitalReadBuf
*/
uint8_t PCA9554::digitalReadBuf(uint8_t pin){
if(pin < 8){
return IS_SET(_inPort0Level, pin);
}
return 0;
}
/* ###########################################################################
* digitalRead
*/
uint8_t PCA9554::digitalRead(uint8_t pin){
readBufUpdate();
return digitalReadBuf(pin);
}
/* ###########################################################################
* readPortA
*/
uint8_t PCA9554::readPortA(){
readBufUpdate();
return _inPort0Level;
}
| 21.154206 | 79 | 0.513364 |
73e9728faae82223bb5b054b96e91de9c9fd6ea7 | 1,231 | cpp | C++ | src/parser.cpp | orlp/kwik | c1cb6c98e29bbf681ebbb486f33509794c426fe9 | [
"Zlib"
] | null | null | null | src/parser.cpp | orlp/kwik | c1cb6c98e29bbf681ebbb486f33509794c426fe9 | [
"Zlib"
] | 1 | 2015-10-28T11:54:46.000Z | 2015-10-28T12:07:08.000Z | src/parser.cpp | orlp/kwik | c1cb6c98e29bbf681ebbb486f33509794c426fe9 | [
"Zlib"
] | null | null | null | #include "precompile.h"
#include "token.h"
#include "parser.h"
#include "lexer.h"
void* KwikParseAlloc(void* (*alloc_proc)(size_t));
void KwikParse(void* state, int token_id, kwik::Token* token_data, kwik::ParseState* s);
void KwikParseFree(void*, void(*free_proc)(void*));
namespace kwik {
void parse(const Source& src) {
auto parser = KwikParseAlloc(malloc);
OP_SCOPE_EXIT { KwikParseFree(parser, free); };
auto state = ParseState{src};
auto lex = Lexer{state};
while (true) {
try {
auto token = lex.get_token();
KwikParse(parser, token.type, new Token(token), &state);
if (token.type == 0) break;
} catch (const CompilationError& e) {
state.errors.emplace_back(e.clone());
}
}
ast::Environment global_env(nullptr);
try {
state.program->check(global_env);
} catch (const CompilationError& e) {
state.errors.emplace_back(e.clone());
}
op::printf("Finished parse with {} error(s).\n", state.errors.size());
for (auto& error : state.errors) {
op::print(error->what());
}
}
}
| 27.977273 | 88 | 0.562957 |
73e9a0fbdf15fa564c69ca95f58af05dfe50ec65 | 4,764 | cpp | C++ | FarLight/src/FarLight/ConfigurationSystem/LocalConfigurations/Serializers/Entity/EntitySerializerConfiguration.cpp | NewBediver/FarLight | 1ffaf127f51bb88ea3f5eb8d05c04458532d5389 | [
"Apache-2.0"
] | null | null | null | FarLight/src/FarLight/ConfigurationSystem/LocalConfigurations/Serializers/Entity/EntitySerializerConfiguration.cpp | NewBediver/FarLight | 1ffaf127f51bb88ea3f5eb8d05c04458532d5389 | [
"Apache-2.0"
] | null | null | null | FarLight/src/FarLight/ConfigurationSystem/LocalConfigurations/Serializers/Entity/EntitySerializerConfiguration.cpp | NewBediver/FarLight | 1ffaf127f51bb88ea3f5eb8d05c04458532d5389 | [
"Apache-2.0"
] | null | null | null | #include "flpch.h"
#include "FarLight/ConfigurationSystem/LocalConfigurations/Serializers/Entity/EntitySerializerConfiguration.h"
#include "FarLight/ConfigurationSystem/ConfigurationManager.h"
#include "FarLight/EntityComponentSystem/Components/Tag/TagComponent.h"
#include "FarLight/EntityComponentSystem/Components/Transform/TransformComponent.h"
#include "FarLight/EntityComponentSystem/Components/Render/RenderComponent.h"
#include "FarLight/EntityComponentSystem/Components/Camera/CameraComponent.h"
namespace FarLight
{
bool EntitySerializerConfiguration::IsEntityExists(const EngineID& id) const noexcept
{
for (auto& node = m_PropertyTree.begin(); node != m_PropertyTree.end(); ++node)
{
if (node->first == m_EntityNodeName && node->second.get<std::string>("<xmlattr>.id") == id.ToString())
{
return true;
}
}
return false;
}
void EntitySerializerConfiguration::EraseEntity(const EngineID& id) noexcept
{
if (!IsEntityExists(id)) return;
for (auto& node = m_PropertyTree.begin(); node != m_PropertyTree.end(); ++node)
{
if (node->first == m_EntityNodeName && node->second.get<std::string>("<xmlattr>.id") == id.ToString())
{
node = m_PropertyTree.erase(node);
break;
}
}
}
Ref<Entity> EntitySerializerConfiguration::LoadEntity(const EngineID& id, Ref<Scene> scene) const noexcept
{
if (!IsEntityExists(id))
{
FL_CORE_ERROR("Entity with id = \"{0}\" doesn't exists!", id.ToString());
return nullptr;
}
Ref<Entity> entity = scene->CreateEntity(id);
for (auto& node = m_PropertyTree.begin(); node != m_PropertyTree.end(); ++node)
{
if (node->first == m_EntityNodeName && node->second.get<std::string>("<xmlattr>.id") == id.ToString())
{
LoadComponentIfExist<TagComponent>(node->second, "TagComponent", entity);
LoadComponentIfExist<TransformComponent>(node->second, "TransformComponent", entity);
LoadComponentIfExist<RenderComponent>(node->second, "RenderComponent", entity);
LoadComponentIfExist<CameraComponent>(node->second, "CameraComponent", entity);
break;
}
}
return entity;
}
void EntitySerializerConfiguration::SaveEntity(Ref<Entity> entity) noexcept
{
if (IsEntityExists(entity->GetId()))
{
FL_CORE_WARN("Try to save entity with the existent id = \"{0}\"!", entity->GetId().ToString());
EraseEntity(entity->GetId());
}
std::string id = entity->GetId().ToString();
boost::property_tree::ptree tmpTree;
tmpTree.put<std::string>(m_EntityNodeName + ".<xmlattr>.id", id);
SaveComponentIfExist<TagComponent>(tmpTree, "TagComponent", entity);
SaveComponentIfExist<TransformComponent>(tmpTree, "TransformComponent", entity);
SaveComponentIfExist<RenderComponent>(tmpTree, "RenderComponent", entity);
SaveComponentIfExist<CameraComponent>(tmpTree, "CameraComponent", entity);
ConfigurationManager::GetInstance().GetComponentSerializerConfiguration()->Save();
m_PropertyTree.add_child(m_EntityNodeName, tmpTree.get_child(m_EntityNodeName));
}
template<typename T>
inline void EntitySerializerConfiguration::LoadComponentIfExist(const boost::property_tree::ptree& tree, const std::string& name, Ref<Entity> entity) const noexcept
{
if (tree.find(name) != tree.not_found() && ConfigurationManager::GetInstance().GetComponentSerializerConfiguration()->IsComponentExists(EngineID(tree.get<std::string>(name))))
{
Ref<T> component = ConfigurationManager::GetInstance().GetComponentSerializerConfiguration()->LoadComponent<T>(EngineID(tree.get<std::string>(name)));
if (entity->HasAllComponents<T>())
{
entity->ReplaceComponent<T>(*(component.get()));
}
else
{
entity->AddComponent<T>(*(component.get()));
}
}
}
template<typename T>
inline void EntitySerializerConfiguration::SaveComponentIfExist(boost::property_tree::ptree& tree, const std::string& name, Ref<Entity> entity) noexcept
{
if (entity->HasAllComponents<T>())
{
tree.put<std::string>(m_EntityNodeName + "." + name, entity->GetComponent<T>().GetId().ToString());
ConfigurationManager::GetInstance().GetComponentSerializerConfiguration()->SaveComponent<T>(CreateRef<T>(entity->GetComponent<T>()));
}
}
}
| 42.535714 | 183 | 0.642317 |
73ec1a59a2f45435fe90e290b716d43d63f4d332 | 1,253 | cpp | C++ | 110. Balanced Binary Tree/solution.cpp | zlsun/leetcode | 438d0020a701d7aa6a82eee0e46e5b11305abfda | [
"MIT"
] | null | null | null | 110. Balanced Binary Tree/solution.cpp | zlsun/leetcode | 438d0020a701d7aa6a82eee0e46e5b11305abfda | [
"MIT"
] | null | null | null | 110. Balanced Binary Tree/solution.cpp | zlsun/leetcode | 438d0020a701d7aa6a82eee0e46e5b11305abfda | [
"MIT"
] | null | null | null | /** 110. Balanced Binary Tree
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
**/
#include <iostream>
#include "../utils.h"
using namespace std;
/**
* 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:
bool isBalanced(TreeNode* root) {
bool balanced;
judge(root, balanced);
return balanced;
}
int judge(TreeNode* root, bool& balanced) {
if (!root) {
balanced = true;
return 0;
}
bool lb = false, rb = false;
int lh = judge(root->left, lb);
int rh = judge(root->right, rb);
balanced = lb && rb && abs(lh - rh) <= 1;
return max(lh, rh) + 1;
}
};
int main() {
Solution s;
ASSERT s.isBalanced(TreeNode::Builder {});
ASSERT s.isBalanced(TreeNode::Builder {
1, {2, 3, 4}, 2
});
ASSERT !s.isBalanced(TreeNode::Builder {
1, {2, 3, {4, 5, 6}}, 2
});
return 0;
}
| 24.096154 | 157 | 0.567438 |
73ef53385daff78ff49599e30b156dbbf2ce0afd | 9,111 | cpp | C++ | host/RASDRproc/src/Logic/src/data_FreqVsCap.cpp | mfkiwl/RASDR | 2e4f7c3b368aa4d596f573433f8c998246444394 | [
"CC-BY-3.0"
] | 41 | 2015-01-25T08:13:12.000Z | 2021-06-24T18:39:33.000Z | host/RASDRproc/src/Logic/src/data_FreqVsCap.cpp | mfkiwl/RASDR | 2e4f7c3b368aa4d596f573433f8c998246444394 | [
"CC-BY-3.0"
] | 18 | 2015-09-30T16:07:03.000Z | 2020-08-05T12:28:50.000Z | host/RASDRproc/src/Logic/src/data_FreqVsCap.cpp | mfkiwl/RASDR | 2e4f7c3b368aa4d596f573433f8c998246444394 | [
"CC-BY-3.0"
] | 10 | 2015-04-01T00:28:41.000Z | 2021-05-31T14:08:22.000Z | // -----------------------------------------------------------------------------
// FILE: Data_FreqVsCap.cpp
// DESCRIPTION:
// DATE:
// AUTHOR(s): Lime Microsystems
// REVISIONS:
// -----------------------------------------------------------------------------
// ---------------------------------------------------------------------
#include "data_FreqVsCap.h"
// ---------------------------------------------------------------------
Data_FreqVsCap::Data_FreqVsCap()
{
sVco1.iRef = 0;
sVco1.dFreq = NULL;
sVco1.iCap = NULL;
sVco2.iRef = 0;
sVco2.dFreq = NULL;
sVco2.iCap = NULL;
sVco3.iRef = 0;
sVco3.dFreq = NULL;
sVco3.iCap = NULL;
sVco4.iRef = 0;
sVco4.dFreq = NULL;
sVco4.iCap = NULL;
DestroyValues(sVco1);
sVco1.iRef = 3;
sVco1.dFreq = new double[sVco1.iRef];
sVco1.iCap = new double[sVco1.iRef];
sVco1.dFreq[0] = 3.76;
sVco1.dFreq[1] = 4.20;
sVco1.dFreq[2] = 4.84;
sVco1.iCap[0] = 0;
sVco1.iCap[1] = 31;
sVco1.iCap[2] = 63;
DestroyValues(sVco2);
sVco2.iRef = 3;
sVco2.dFreq = new double[sVco2.iRef];
sVco2.iCap = new double[sVco2.iRef];
sVco2.dFreq[0] = 4.68;
sVco2.dFreq[1] = 5.32;
sVco2.dFreq[2] = 6.04;
sVco2.iCap[0] = 0;
sVco2.iCap[1] = 31;
sVco2.iCap[2] = 63;
DestroyValues(sVco3);
sVco3.iRef = 3;
sVco3.dFreq = new double[sVco3.iRef];
sVco3.iCap = new double[sVco3.iRef];
sVco3.dFreq[0] = 5.72;
sVco3.dFreq[1] = 6.44;
sVco3.dFreq[2] = 7.36;
sVco3.iCap[0] = 0;
sVco3.iCap[1] = 31;
sVco3.iCap[2] = 63;
DestroyValues(sVco4);
sVco4.iRef = 3;
sVco4.dFreq = new double[sVco4.iRef];
sVco4.iCap = new double[sVco4.iRef];
sVco4.dFreq[0] = 6.92;
sVco4.dFreq[1] = 7.36;
sVco4.dFreq[2] = 8.398;
sVco4.iCap[0] = 0;
sVco4.iCap[1] = 31;
sVco4.iCap[2] = 63;
m_sLastUsedVCOFile = "";
}
sVcoVsCap* Data_FreqVsCap::getVco1()
{
return &sVco1;
}
sVcoVsCap* Data_FreqVsCap::getVco2()
{
return &sVco2;
}
sVcoVsCap* Data_FreqVsCap::getVco3()
{
return &sVco3;
}
sVcoVsCap* Data_FreqVsCap::getVco4()
{
return &sVco4;
}
void Data_FreqVsCap::setVco1(sVcoVsCap *pSource)
{
DestroyValues(sVco1);
sVco1.iRef = pSource->iRef;
sVco1.dFreq = new double[sVco1.iRef];
sVco1.iCap = new double[sVco1.iRef];
int temp = 0;
for (int i = 0; i < sVco1.iRef; i++)
{
sVco1.dFreq[i] = pSource->dFreq[i];
sVco1.iCap[i] = pSource->iCap[i];
}
}
void Data_FreqVsCap::setVco2(sVcoVsCap *pSource)
{
DestroyValues(sVco2);
sVco2.iRef = pSource->iRef;
sVco2.dFreq = new double[sVco2.iRef];
sVco2.iCap = new double[sVco2.iRef];
for (int i = 0; i < sVco2.iRef; i++)
{
sVco2.dFreq[i] = pSource->dFreq[i];
sVco2.iCap[i] = pSource->iCap[i];
}
}
void Data_FreqVsCap::setVco3(sVcoVsCap *pSource)
{
DestroyValues(sVco3);
sVco3.iRef = pSource->iRef;
sVco3.dFreq = new double[sVco3.iRef];
sVco3.iCap = new double[sVco3.iRef];
for (int i = 0; i < sVco3.iRef; i++)
{
sVco3.dFreq[i] = pSource->dFreq[i];
sVco3.iCap[i] = pSource->iCap[i];
}
}
void Data_FreqVsCap::setVco4(sVcoVsCap *pSource)
{
DestroyValues(sVco4);
sVco4.iRef = pSource->iRef;
sVco4.dFreq = new double[sVco4.iRef];
sVco4.iCap = new double[sVco4.iRef];
for (int i = 0; i < sVco4.iRef; i++)
{
sVco4.dFreq[i] = pSource->dFreq[i];
sVco4.iCap[i] = pSource->iCap[i];
}
}
Data_FreqVsCap::~Data_FreqVsCap()
{
DestroyValues(sVco1);
DestroyValues(sVco2);
DestroyValues(sVco3);
DestroyValues(sVco4);
}
// ---------------------------------------------------------------------------
void Data_FreqVsCap::Save(string fname)
{
int iCnt;
double dTmp;
fstream pfItems;
pfItems.open(fname.c_str(), ios::out | ios::binary);
if (!pfItems.is_open())
{
return;
}
// VCO1 Values
iCnt = sVco1.iRef;
pfItems.write((const char*)&iCnt, sizeof(iCnt));
for (int i = 1; i <= iCnt; i++)
{
dTmp = sVco1.dFreq[i];
pfItems.write((const char*)&dTmp, sizeof(dTmp));
dTmp = sVco1.iCap[i];
pfItems.write((const char*)&dTmp, sizeof(dTmp));
};
// VCO2 Values
iCnt = sVco2.iRef;
pfItems.write((const char*)&iCnt, sizeof(iCnt));
for (int i = 1; i <= iCnt; i++)
{
dTmp = sVco2.dFreq[i];
pfItems.write((const char*)&dTmp, sizeof(dTmp));
dTmp = sVco2.iCap[i];
pfItems.write((const char*)&dTmp, sizeof(dTmp));
};
// VCO3 Values
iCnt = sVco3.iRef;
pfItems.write((const char*)&iCnt, sizeof(iCnt));
for (int i = 1; i <= iCnt; i++)
{
dTmp = sVco3.dFreq[i];
pfItems.write((const char*)&dTmp, sizeof(dTmp));
dTmp = sVco3.iCap[i];
pfItems.write((const char*)&dTmp, sizeof(dTmp));
};
// VCO4 Values
iCnt = sVco4.iRef;
pfItems.write((const char*)&iCnt, sizeof(iCnt));
for (int i = 1; i <= iCnt; i++)
{
dTmp = sVco4.dFreq[i];
pfItems.write((const char*)&dTmp, sizeof(dTmp));
dTmp = sVco4.iCap[i];
pfItems.write((const char*)&dTmp, sizeof(dTmp));
};
pfItems.close();
}
// ---------------------------------------------------------------------------
void Data_FreqVsCap::DestroyValues(sVcoVsCap &Vco)
{
if (Vco.iRef)
{
Vco.iRef = 0;
if (Vco.dFreq != NULL)
delete[]Vco.dFreq;
Vco.dFreq = NULL;
if (Vco.iCap != NULL)
delete[]Vco.iCap;
Vco.iCap = NULL;
};
};
// ---------------------------------------------------------------------------
void Data_FreqVsCap::Initialize(string Name)
{
string FName;
string Str;
m_sName = Name;
// Load VCO calibration values from last used file
// FName = ReadPathFromReg();
if (!FileExists(FName))
{
if (m_sName == "TxVCOFile")
{
// FName = ChangeFileExt(ApplicationExeName,".tco");
FName = "6002Dr2_Test.tco";
}
else
{
// FName = ChangeFileExt(ApplicationExeName,".rco");
FName = "6002Dr2_Test.rco";
};
};
if (FileExists(FName))
{
LoadValuesFromFile(FName);
}
else
{
Str = "Can't find VCO calibration values file for" + Name;
Str = Str + "\nDefault values are used.";
};
};
// ---------------------------------------------------------------------------
void Data_FreqVsCap::SavePathToReg(string Path)
{
/*
TRegistry* reg = new TRegistry;
//reg->OpenKey("Software\\ctr_6002d\\Settings", true);
reg->OpenKey(RegistryString, true);
reg->WriteString(m_sName, Path);
//reg->WriteString("LastDirectory", "C:\\");
//reg->WriteInteger("Data", 1);
delete reg;
*/
};
// ---------------------------------------------------------------------------
string Data_FreqVsCap::ReadPathFromReg()
{
/*
string FileName;
TRegistry* reg = new TRegistry;
//reg->OpenKey("Software\\ctr_6002d\\Settings", true);
reg->OpenKey(RegistryString, true);
FileName = reg->ReadString(m_sName);
delete reg;
return FileName;
*/
return string("Error");
};
// ---------------------------------------------------------------------------
void Data_FreqVsCap::LoadValuesFromFile(string FName)
{
int iCnt;
double dTmp;
sVcoVsCap VcoVsCap;
fstream pfItems;
pfItems.open(FName.c_str(), ios::in | ios::binary);
if (!pfItems.is_open())
{
return;
}
// --===== Save path to registry. BEGIN =====--
// SavePathToReg(FName);
m_sLastUsedVCOFile = FName;
// --===== Save path to registry. END =====--
// VCO1 Values
pfItems.read((char *)&iCnt, sizeof(iCnt));
VcoVsCap.iRef = iCnt;
VcoVsCap.dFreq = new double[iCnt];
VcoVsCap.iCap = new double[iCnt];
for (int i = 1; i <= iCnt; i++)
{
pfItems.read((char*)&dTmp, sizeof(dTmp));
VcoVsCap.dFreq[i - 1] = dTmp;
pfItems.read((char*)&dTmp, sizeof(dTmp));
VcoVsCap.iCap[i - 1] = dTmp;
};
setVco(&VcoVsCap, &sVco1);
delete[]VcoVsCap.dFreq;
delete[]VcoVsCap.iCap;
// VCO2 Values
pfItems.read((char *)&iCnt, sizeof(iCnt));
VcoVsCap.iRef = iCnt;
VcoVsCap.dFreq = new double[iCnt];
VcoVsCap.iCap = new double[iCnt];
for (int i = 1; i <= iCnt; i++)
{
pfItems.read((char*)&dTmp, sizeof(dTmp));
VcoVsCap.dFreq[i - 1] = dTmp;
pfItems.read((char*)&dTmp, sizeof(dTmp));
VcoVsCap.iCap[i - 1] = dTmp;
};
setVco(&VcoVsCap, &sVco2);
delete[]VcoVsCap.dFreq;
delete[]VcoVsCap.iCap;
// VCO3 Values
pfItems.read((char *)&iCnt, sizeof(iCnt));
VcoVsCap.iRef = iCnt;
VcoVsCap.dFreq = new double[iCnt];
VcoVsCap.iCap = new double[iCnt];
for (int i = 1; i <= iCnt; i++)
{
pfItems.read((char*)&dTmp, sizeof(dTmp));
VcoVsCap.dFreq[i - 1] = dTmp;
pfItems.read((char*)&dTmp, sizeof(dTmp));
VcoVsCap.iCap[i - 1] = dTmp;
};
setVco(&VcoVsCap, &sVco3);
delete[]VcoVsCap.dFreq;
delete[]VcoVsCap.iCap;
// VCO4 Values
pfItems.read((char *)&iCnt, sizeof(iCnt));
VcoVsCap.iRef = iCnt;
VcoVsCap.dFreq = new double[iCnt];
VcoVsCap.iCap = new double[iCnt];
for (int i = 1; i <= iCnt; i++)
{
pfItems.read((char*)&dTmp, sizeof(dTmp));
VcoVsCap.dFreq[i - 1] = dTmp;
pfItems.read((char*)&dTmp, sizeof(dTmp));
VcoVsCap.iCap[i - 1] = dTmp;
};
setVco(&VcoVsCap, &sVco4);
delete[]VcoVsCap.dFreq;
delete[]VcoVsCap.iCap;
pfItems.close();
};
void Data_FreqVsCap::setVco(sVcoVsCap *source, sVcoVsCap *destination)
{
destination->iRef = source->iRef;
for (int i = 0; i < source->iRef; i++)
{
destination->dFreq[i] = source->dFreq[i];
destination->iCap[i] = source->iCap[i];
}
}
bool Data_FreqVsCap::FileExists(string filename)
{
bool exists = false;
fstream fin;
fin.open(filename.c_str(), ios::in);
if (fin.is_open())
{
exists = true;
}
fin.close();
return exists;
}
| 22.60794 | 80 | 0.592251 |
73efb305f2fc9d060f8e139e9db8fcaa7a1e34e5 | 2,356 | hpp | C++ | src/interfaces/vectorInterfaces.hpp | lhb8125/HSF | f0cea44691a0e41bdeb5613a2d5a6cd7cda0a999 | [
"Apache-2.0"
] | null | null | null | src/interfaces/vectorInterfaces.hpp | lhb8125/HSF | f0cea44691a0e41bdeb5613a2d5a6cd7cda0a999 | [
"Apache-2.0"
] | null | null | null | src/interfaces/vectorInterfaces.hpp | lhb8125/HSF | f0cea44691a0e41bdeb5613a2d5a6cd7cda0a999 | [
"Apache-2.0"
] | null | null | null | /*
* @author: liu hongbin
* @brief: vector interfaces
* @email: lhb8134@foxmail.com
* @date: 2020-02-22 12:09:40
* @last Modified by: lhb8125
* @last Modified time: 2020-02-22 14:48:06
*/
#ifndef VECTORINTERFACES_HPP
#define VECTORINTERFACES_HPP
#include "mpi.h"
// #include "voidtor.hpp"
// using namespace HSF;
// #define void Vector<double>
#define HSF_COMM MPI_COMM_WORLD
/**
* @brief 给串行向量v开辟空间
* @param[in] v 待开辟空间向量
* @param[in] n 向量大小
*/
void VecConstrSeq (void* v, int n);
/**
* @brief 给并行向量v开辟空间
* @param[in] v 待开辟空间向量
* @param[in] n 向量大小
* @param[in] nbghosts ghost元素个数
* @param[in] ghosts ghost元素的全局位置
*/
void VecConstrPar (void* v, int n, int nbghosts, int* ghosts);
/**
* @brief 释放向量空间
*/
void VecDestr (void* v);
/**
* @brief 给向量指定位置赋值
*/
void VecSetCmp (void* v, int ind, double value);
/**
* @brief 给向量所有位置赋相同的值
*/
void VecSetAllCmp (void* v, double value);
/**
* @brief 获得向量指定位置的值,当前进程上
* @param[in] v 取值向量
* @param[in] ind 取值位置
* @return 返回向量指定位置的值
*/
double VecGetCmp (void* v, int ind);
/**
* @brief Obtains the local ghosted representation of a parallel vector
* @param[in] vg the global vector
* @param[out] vl the local (ghosted) representation, NULL if g is not ghosted
*/
void VecGhostGetLocalForm(void* vg, void* vl);
/**
* @brief Restores the local ghosted representation of a parallel vector obtained with V_GhostGetLocalForm()
* @param[in] vg the global vector
* @param[out] vl the local (ghosted) representation
*/
void VecGhostRestoreLocalForm(void* vg, void* vl);
/**
* @brief 启动向量ghost部分更新
* @param[in] v 被更新向量
*/
void VecGhostUpdate(void* v);
/**
* @brief 复制向量
* @param[in] vfrom 被复制向量
* @param[out] vto 结果向量
*/
void VecCopy(void* vfrom, void* vto);
/**
* @brief 计算向量第二范数
* @param[in] v 被求向量
* @param[out] norm2 v的第二范数
*/
void VecNorm2(void* v, double *norm2);
/**
* @brief w = alpha * x + y
* @param[out] w 结果向量
*/
void VecWAXPY(void* w, double alpha, void* x, void* y);
/**
* @brief y = alpha * x + y
* @param[out] y 结果向量
*/
void VecAXPY(void* y, double alpha, void* x);
/**
* @brief 点乘 w = x*y
* @param[out] w 点乘后返回的结果向量
*/
void VecPointwiseMult(void* w, void* x, void* y);
/**
* @brief 获取向量的最大值及其位置
* @param[in] x 目标向量
* @param[out] loc 最大值位置
* @param[out] val 最大值
*/
void VecMax(void* v, int *loc, double *val);
/**
* @brief 向量写入到文件
*/
void VecWrite(void* x);
#endif | 18.698413 | 107 | 0.663837 |
73f1486954537fdcef284a0819d92cbdb4b35bd6 | 950 | hpp | C++ | include/Animador.hpp | rickylh/Medieval-Game | 2e818ab09cdd6158b59133c56cfca8e31d1f8f3a | [
"MIT"
] | null | null | null | include/Animador.hpp | rickylh/Medieval-Game | 2e818ab09cdd6158b59133c56cfca8e31d1f8f3a | [
"MIT"
] | null | null | null | include/Animador.hpp | rickylh/Medieval-Game | 2e818ab09cdd6158b59133c56cfca8e31d1f8f3a | [
"MIT"
] | null | null | null | #pragma once
#include "Std.hpp"
class Fase;
class Animador {
private:
sf::Texture textura;
sf::IntRect sprite;
int colunas;
int coluna_atual;
float tempo_contabilizado;
float tempo_por_quadro;
bool ja_terminou;
bool ativa;
void carregarTextura(std::string caminho);
public:
Animador();
Animador(const Animador& copia);
~Animador();
//configura valores iniciais para a anima�ao
bool setConfig(std::string caminho, int colunas, float tempo_por_quadro);
void atualiza(bool para_direita, sf::RectangleShape& corpo, float tempo = -1);
//retorna booleano caso a anima�ao tenha atinjido o quadro de execu�ao
bool executou(int coluna_especifica) const;
//retorna booleano case a anima�ao tenha terminado (chegou ao ultimo sprite)
bool terminou() const;
//volta a anima�ao para o primeiro quadro
void zerar();
int getLargura() const;
void reiniciar();
bool estaAtiva() const;
};
| 23.170732 | 80 | 0.712632 |
73f18f7b6c9ff41a9d2300929d39dbe7e218c56b | 21,468 | cc | C++ | model/std_cells/MUX2.cc | gyb1325/Desent_modification | ff0a146bddfb97269b7874092dd203be3633f97c | [
"MIT"
] | 94 | 2015-02-21T09:44:03.000Z | 2022-03-13T03:06:19.000Z | model/std_cells/MUX2.cc | gyb1325/Desent_modification | ff0a146bddfb97269b7874092dd203be3633f97c | [
"MIT"
] | null | null | null | model/std_cells/MUX2.cc | gyb1325/Desent_modification | ff0a146bddfb97269b7874092dd203be3633f97c | [
"MIT"
] | 36 | 2015-01-09T16:48:18.000Z | 2022-03-13T03:06:21.000Z | #include "model/std_cells/MUX2.h"
#include <cmath>
#include "model/PortInfo.h"
#include "model/TransitionInfo.h"
#include "model/EventInfo.h"
#include "model/std_cells/StdCellLib.h"
#include "model/std_cells/CellMacros.h"
#include "model/timing_graph/ElectricalNet.h"
#include "model/timing_graph/ElectricalDriver.h"
#include "model/timing_graph/ElectricalLoad.h"
#include "model/timing_graph/ElectricalDelay.h"
namespace DSENT
{
using std::ceil;
using std::max;
MUX2::MUX2(const String& instance_name_, const TechModel* tech_model_)
: StdCell(instance_name_, tech_model_)
{
initProperties();
}
MUX2::~MUX2()
{}
void MUX2::initProperties()
{
return;
}
void MUX2::constructModel()
{
// All constructModel should do is create Area/NDDPower/Energy Results as
// well as instantiate any sub-instances using only the hard parameters
createInputPort("A");
createInputPort("B");
createInputPort("S0");
createOutputPort("Y");
createLoad("A_Cap");
createLoad("B_Cap");
createLoad("S0_Cap");
createDelay("A_to_Y_delay");
createDelay("B_to_Y_delay");
createDelay("S0_to_Y_delay");
createDriver("Y_Ron", true);
ElectricalLoad* a_cap = getLoad("A_Cap");
ElectricalLoad* b_cap = getLoad("B_Cap");
ElectricalLoad* s0_cap = getLoad("S0_Cap");
ElectricalDelay* a_to_y_delay = getDelay("A_to_Y_delay");
ElectricalDelay* b_to_y_delay = getDelay("B_to_Y_delay");
ElectricalDelay* s0_to_y_delay = getDelay("S0_to_Y_delay");
ElectricalDriver* y_ron = getDriver("Y_Ron");
getNet("A")->addDownstreamNode(a_cap);
getNet("B")->addDownstreamNode(b_cap);
getNet("S0")->addDownstreamNode(s0_cap);
a_cap->addDownstreamNode(a_to_y_delay);
b_cap->addDownstreamNode(b_to_y_delay);
s0_cap->addDownstreamNode(s0_to_y_delay);
a_to_y_delay->addDownstreamNode(y_ron);
b_to_y_delay->addDownstreamNode(y_ron);
s0_to_y_delay->addDownstreamNode(y_ron);
y_ron->addDownstreamNode(getNet("Y"));
// Create Area result
createElectricalAtomicResults();
getEventInfo("Idle")->setStaticTransitionInfos();
// Create MUX2 Event Energy Result
createElectricalEventAtomicResult("MUX2");
return;
}
void MUX2::updateModel()
{
// Get parameters
double drive_strength = getDrivingStrength();
Map<double>* cache = getTechModel()->getStdCellLib()->getStdCellCache();
// Standard cell cache string
String cell_name = "MUX2_X" + (String) drive_strength;
// Get timing parameters
getLoad("A_Cap")->setLoadCap(cache->get(cell_name + "->Cap->A"));
getLoad("B_Cap")->setLoadCap(cache->get(cell_name + "->Cap->B"));
getLoad("S0_Cap")->setLoadCap(cache->get(cell_name + "->Cap->S0"));
getDelay("A_to_Y_delay")->setDelay(cache->get(cell_name + "->Delay->A_to_Y"));
getDelay("B_to_Y_delay")->setDelay(cache->get(cell_name + "->Delay->B_to_Y"));
getDelay("S0_to_Y_delay")->setDelay(cache->get(cell_name + "->Delay->S0_to_Y"));
getDriver("Y_Ron")->setOutputRes(cache->get(cell_name + "->DriveRes->Y"));
// Set the cell area
getAreaResult("Active")->setValue(cache->get(cell_name + "->ActiveArea"));
getAreaResult("Metal1Wire")->setValue(cache->get(cell_name + "->ActiveArea"));
return;
}
void MUX2::evaluateModel()
{
return;
}
void MUX2::useModel()
{
// Get parameters
double drive_strength = getDrivingStrength();
Map<double>* cache = getTechModel()->getStdCellLib()->getStdCellCache();
// Standard cell cache string
String cell_name = "MUX2_X" + (String) drive_strength;
// Propagate the transition and get the 0->1 transition count
propagateTransitionInfo();
double P_A = getInputPort("A")->getTransitionInfo().getProbability1();
double P_B = getInputPort("B")->getTransitionInfo().getProbability1();
double P_S0 = getInputPort("S0")->getTransitionInfo().getProbability1();
double S0_num_trans_01 = getInputPort("S0")->getTransitionInfo().getNumberTransitions01();
double Y_num_trans_01 = getOutputPort("Y")->getTransitionInfo().getNumberTransitions01();
// Calculate leakage
double leakage = 0;
leakage += cache->get(cell_name + "->Leakage->!A!B!S0") * (1 - P_A) * (1 - P_B) * (1 - P_S0);
leakage += cache->get(cell_name + "->Leakage->!A!BS0") * (1 - P_A) * (1 - P_B) * P_S0;
leakage += cache->get(cell_name + "->Leakage->!AB!S0") * (1 - P_A) * P_B * (1 - P_S0);
leakage += cache->get(cell_name + "->Leakage->!ABS0") * (1 - P_A) * P_B * P_S0;
leakage += cache->get(cell_name + "->Leakage->A!B!S0") * P_A * (1 - P_B) * (1 - P_S0);
leakage += cache->get(cell_name + "->Leakage->A!BS0") * P_A * (1 - P_B) * P_S0;
leakage += cache->get(cell_name + "->Leakage->AB!S0") * P_A * P_B * (1 - P_S0);
leakage += cache->get(cell_name + "->Leakage->ABS0") * P_A * P_B * P_S0;
getNddPowerResult("Leakage")->setValue(leakage);
// Get VDD
double vdd = getTechModel()->get("Vdd");
// Get capacitances
double s0_b_cap = cache->get(cell_name + "->Cap->S0_b");
double y_bar_cap = cache->get(cell_name + "->Cap->Y_b");
double y_cap = cache->get(cell_name + "->Cap->Y");
double y_load_cap = getNet("Y")->getTotalDownstreamCap();
// Create mux2 event energy
double mux2_event_energy = 0.0;
mux2_event_energy += (s0_b_cap) * S0_num_trans_01;
mux2_event_energy += (y_bar_cap + y_cap + y_load_cap) * Y_num_trans_01;
mux2_event_energy *= vdd * vdd;
getEventResult("MUX2")->setValue(mux2_event_energy);
return;
}
void MUX2::propagateTransitionInfo()
{
// Get input signal transition info
const TransitionInfo& trans_A = getInputPort("A")->getTransitionInfo();
const TransitionInfo& trans_B = getInputPort("B")->getTransitionInfo();
const TransitionInfo& trans_S0 = getInputPort("S0")->getTransitionInfo();
// Scale all transition information to the highest freq multiplier
double max_freq_mult = max(max(trans_A.getFrequencyMultiplier(), trans_B.getFrequencyMultiplier()), trans_S0.getFrequencyMultiplier());
const TransitionInfo& scaled_trans_A = trans_A.scaleFrequencyMultiplier(max_freq_mult);
const TransitionInfo& scaled_trans_B = trans_B.scaleFrequencyMultiplier(max_freq_mult);
const TransitionInfo& scaled_trans_S0 = trans_S0.scaleFrequencyMultiplier(max_freq_mult);
// Compute the probability of each transition on a given cycle
double A_prob_00 = scaled_trans_A.getNumberTransitions00() / max_freq_mult;
double A_prob_01 = scaled_trans_A.getNumberTransitions01() / max_freq_mult;
double A_prob_10 = A_prob_01;
double A_prob_11 = scaled_trans_A.getNumberTransitions11() / max_freq_mult;
double B_prob_00 = scaled_trans_B.getNumberTransitions00() / max_freq_mult;
double B_prob_01 = scaled_trans_B.getNumberTransitions01() / max_freq_mult;
double B_prob_10 = B_prob_01;
double B_prob_11 = scaled_trans_B.getNumberTransitions11() / max_freq_mult;
double S0_prob_00 = scaled_trans_S0.getNumberTransitions00() / max_freq_mult;
double S0_prob_01 = scaled_trans_S0.getNumberTransitions01() / max_freq_mult;
double S0_prob_10 = S0_prob_01;
double S0_prob_11 = scaled_trans_S0.getNumberTransitions11() / max_freq_mult;
// Compute output probabilities
double Y_prob_00 = S0_prob_00 * A_prob_00 +
S0_prob_01 * (A_prob_00 + A_prob_01) * (B_prob_00 + B_prob_10) +
S0_prob_10 * (A_prob_00 + A_prob_10) * (B_prob_00 + B_prob_01) +
S0_prob_11 * B_prob_00;
double Y_prob_01 = S0_prob_00 * A_prob_01 +
S0_prob_01 * (A_prob_00 + A_prob_01) * (B_prob_01 + B_prob_11) +
S0_prob_10 * (A_prob_01 + A_prob_11) * (B_prob_00 + B_prob_01) +
S0_prob_11 * B_prob_01;
double Y_prob_11 = S0_prob_00 * A_prob_11 +
S0_prob_01 * (A_prob_10 + A_prob_11) * (B_prob_01 + B_prob_11) +
S0_prob_10 * (A_prob_01 + A_prob_11) * (B_prob_10 + B_prob_11) +
S0_prob_11 * B_prob_11;
// Check that probabilities add up to 1.0 with some finite tolerance
ASSERT(LibUtil::Math::isEqual((Y_prob_00 + Y_prob_01 + Y_prob_01 + Y_prob_11), 1.0),
"[Error] " + getInstanceName() + "Output transition probabilities must add up to 1 (" +
(String) Y_prob_00 + ", " + (String) Y_prob_01 + ", " + (String) Y_prob_11 + ")!");
// Turn probability of transitions per cycle into number of transitions per time unit
TransitionInfo trans_Y(Y_prob_00 * max_freq_mult, Y_prob_01 * max_freq_mult, Y_prob_11 * max_freq_mult);
getOutputPort("Y")->setTransitionInfo(trans_Y);
return;
}
// Creates the standard cell, characterizes and abstracts away the details
void MUX2::cacheStdCell(StdCellLib* cell_lib_, double drive_strength_)
{
// Get parameters
double gate_pitch = cell_lib_->getTechModel()->get("Gate->PitchContacted");
Map<double>* cache = cell_lib_->getStdCellCache();
// Standard cell cache string
String cell_name = "MUX2_X" + (String) drive_strength_;
Log::printLine("=== " + cell_name + " ===");
// Now actually build the full standard cell model
createInputPort("A");
createInputPort("B");
createInputPort("S0");
createOutputPort("Y");
createNet("S0_b");
createNet("Y_b");
// Adds macros
CellMacros::addInverter(this, "INV1", false, true, "S0", "S0_b");
CellMacros::addInverter(this, "INV2", false, true, "Y_b", "Y");
CellMacros::addTristate(this, "INVZ1", true, true, true, true, "A", "S0_b", "S0", "Y_b");
CellMacros::addTristate(this, "INVZ2", true, true, true, true, "B", "S0", "S0_b", "Y_b");
// I have no idea how to size each of the parts haha
CellMacros::updateInverter(this, "INV1", drive_strength_ * 0.250);
CellMacros::updateInverter(this, "INV2", drive_strength_ * 1.000);
CellMacros::updateTristate(this, "INVZ1", drive_strength_ * 0.500);
CellMacros::updateTristate(this, "INVZ2", drive_strength_ * 0.500);
// Cache area result
double area = 0.0;
area += gate_pitch * getTotalHeight() * 1;
area += gate_pitch * getTotalHeight() * getGenProperties()->get("INV1_GatePitches").toDouble();
area += gate_pitch * getTotalHeight() * getGenProperties()->get("INV2_GatePitches").toDouble();
area += gate_pitch * getTotalHeight() * getGenProperties()->get("INVZ1_GatePitches").toDouble();
area += gate_pitch * getTotalHeight() * getGenProperties()->get("INVZ2_GatePitches").toDouble();
cache->set(cell_name + "->ActiveArea", area);
Log::printLine(cell_name + "->ActiveArea=" + (String) area);
// --------------------------------------------------------------------
// Cache Leakage Power (for every single signal combination)
// --------------------------------------------------------------------
double leakage_000 = 0; //!A, !B, !S0
double leakage_001 = 0; //!A, !B, S0
double leakage_010 = 0; //!A, B, !S0
double leakage_011 = 0; //!A, B, S0
double leakage_100 = 0; //A, !B, !S0
double leakage_101 = 0; //A, !B, S0
double leakage_110 = 0; //A, B, !S0
double leakage_111 = 0; //A, B, S0
//This is so painful...
leakage_000 += getGenProperties()->get("INV1_LeakagePower_0").toDouble();
leakage_000 += getGenProperties()->get("INV2_LeakagePower_1").toDouble();
leakage_000 += getGenProperties()->get("INVZ1_LeakagePower_100_1").toDouble();
leakage_000 += getGenProperties()->get("INVZ2_LeakagePower_010_1").toDouble();
leakage_001 += getGenProperties()->get("INV1_LeakagePower_1").toDouble();
leakage_001 += getGenProperties()->get("INV2_LeakagePower_1").toDouble();
leakage_001 += getGenProperties()->get("INVZ1_LeakagePower_010_1").toDouble();
leakage_001 += getGenProperties()->get("INVZ2_LeakagePower_100_1").toDouble();
leakage_010 += getGenProperties()->get("INV1_LeakagePower_0").toDouble();
leakage_010 += getGenProperties()->get("INV2_LeakagePower_1").toDouble();
leakage_010 += getGenProperties()->get("INVZ1_LeakagePower_100_1").toDouble();
leakage_010 += getGenProperties()->get("INVZ2_LeakagePower_011_1").toDouble();
leakage_011 += getGenProperties()->get("INV1_LeakagePower_1").toDouble();
leakage_011 += getGenProperties()->get("INV2_LeakagePower_0").toDouble();
leakage_011 += getGenProperties()->get("INVZ1_LeakagePower_010_0").toDouble();
leakage_011 += getGenProperties()->get("INVZ2_LeakagePower_101_0").toDouble();
leakage_100 += getGenProperties()->get("INV1_LeakagePower_0").toDouble();
leakage_100 += getGenProperties()->get("INV2_LeakagePower_0").toDouble();
leakage_100 += getGenProperties()->get("INVZ1_LeakagePower_101_0").toDouble();
leakage_100 += getGenProperties()->get("INVZ2_LeakagePower_010_0").toDouble();
leakage_101 += getGenProperties()->get("INV1_LeakagePower_1").toDouble();
leakage_101 += getGenProperties()->get("INV2_LeakagePower_0").toDouble();
leakage_101 += getGenProperties()->get("INVZ1_LeakagePower_011_1").toDouble();
leakage_101 += getGenProperties()->get("INVZ2_LeakagePower_100_1").toDouble();
leakage_110 += getGenProperties()->get("INV1_LeakagePower_1").toDouble();
leakage_110 += getGenProperties()->get("INV2_LeakagePower_1").toDouble();
leakage_110 += getGenProperties()->get("INVZ1_LeakagePower_101_0").toDouble();
leakage_110 += getGenProperties()->get("INVZ2_LeakagePower_011_0").toDouble();
leakage_111 += getGenProperties()->get("INV1_LeakagePower_1").toDouble();
leakage_111 += getGenProperties()->get("INV2_LeakagePower_1").toDouble();
leakage_111 += getGenProperties()->get("INVZ1_LeakagePower_011_0").toDouble();
leakage_111 += getGenProperties()->get("INVZ2_LeakagePower_101_0").toDouble();
cache->set(cell_name + "->Leakage->!A!B!S0", leakage_000);
cache->set(cell_name + "->Leakage->!A!BS0", leakage_001);
cache->set(cell_name + "->Leakage->!AB!S0", leakage_010);
cache->set(cell_name + "->Leakage->!ABS0", leakage_011);
cache->set(cell_name + "->Leakage->A!B!S0", leakage_100);
cache->set(cell_name + "->Leakage->A!BS0", leakage_101);
cache->set(cell_name + "->Leakage->AB!S0", leakage_110);
cache->set(cell_name + "->Leakage->ABS0", leakage_111);
Log::printLine(cell_name + "->Leakage->!A!B!S0=" + (String) leakage_000);
Log::printLine(cell_name + "->Leakage->!A!BS0=" + (String) leakage_001);
Log::printLine(cell_name + "->Leakage->!AB!S0=" + (String) leakage_010);
Log::printLine(cell_name + "->Leakage->!ABS0=" + (String) leakage_011);
Log::printLine(cell_name + "->Leakage->A!B!S0=" + (String) leakage_100);
Log::printLine(cell_name + "->Leakage->A!BS0=" + (String) leakage_101);
Log::printLine(cell_name + "->Leakage->AB!S0=" + (String) leakage_110);
Log::printLine(cell_name + "->Leakage->ABS0=" + (String) leakage_111);
// Cache event energy results
/*
double event_a_flip = 0.0;
event_a_flip += getGenProperties()->get("INVZ1_A_Flip").toDouble();
cache->set(cell_name + "->Event_A_Flip", event_a_flip);
Log::printLine(cell_name + "->Event_A_Flip=" + (String) event_a_flip);
double event_b_flip = 0.0;
event_b_flip += getGenProperties()->get("INVZ1_A_Flip").toDouble();
cache->set(cell_name + "->Event_B_Flip", event_b_flip);
Log::printLine(cell_name + "->Event_B_Flip=" + (String) event_b_flip);
double event_s0_flip = 0.0;
event_s0_flip += getGenProperties()->get("INV1_A_Flip").toDouble();
event_s0_flip += getGenProperties()->get("INV1_ZN_Flip").toDouble();
event_s0_flip += getGenProperties()->get("INVZ1_OE_Flip").toDouble() + getGenProperties()->get("INVZ1_OEN_Flip").toDouble();
event_s0_flip += getGenProperties()->get("INVZ2_OE_Flip").toDouble() + getGenProperties()->get("INVZ2_OEN_Flip").toDouble();
cache->set(cell_name + "->Event_S0_Flip", event_s0_flip);
Log::printLine(cell_name + "->Event_S0_Flip=" + (String) event_s0_flip);
double event_y_flip = 0.0;
event_y_flip += getGenProperties()->get("INVZ1_ZN_Flip").toDouble();
event_y_flip += getGenProperties()->get("INVZ2_ZN_Flip").toDouble();
event_y_flip += getGenProperties()->get("INV2_A_Flip").toDouble();
event_y_flip += getGenProperties()->get("INV2_ZN_Flip").toDouble();
cache->set(cell_name + "->Event_Y_Flip", event_y_flip);
Log::printLine(cell_name + "->Event_Y_Flip=" + (String) event_y_flip);
double a_cap = getLoad("INVZ1_CgA")->getLoadCap();
double b_cap = getLoad("INVZ2_CgA")->getLoadCap();
double s0_cap = getLoad("INV1_CgA")->getLoadCap() + getLoad("INVZ1_CgOEN")->getLoadCap() + getLoad("INVZ2_CgOE")->getLoadCap();
double y_ron = getDriver("INV2_RonZN")->getOutputRes();
*/
// --------------------------------------------------------------------
// --------------------------------------------------------------------
// Get Node capacitances
// --------------------------------------------------------------------
double a_cap = getNet("A")->getTotalDownstreamCap();
double b_cap = getNet("B")->getTotalDownstreamCap();
double s0_cap = getNet("S0")->getTotalDownstreamCap();
double s0_b_cap = getNet("S0_b")->getTotalDownstreamCap();
double y_b_cap = getNet("Y_b")->getTotalDownstreamCap();
double y_cap = getNet("Y")->getTotalDownstreamCap();
cache->set(cell_name + "->Cap->A", a_cap);
cache->set(cell_name + "->Cap->B", b_cap);
cache->set(cell_name + "->Cap->S0", s0_cap);
cache->set(cell_name + "->Cap->S0_b", s0_b_cap);
cache->set(cell_name + "->Cap->Y_b", y_b_cap);
cache->set(cell_name + "->Cap->Y", y_cap);
Log::printLine(cell_name + "->Cap->A=" + (String) a_cap);
Log::printLine(cell_name + "->Cap->B=" + (String) b_cap);
Log::printLine(cell_name + "->Cap->S0=" + (String) s0_cap);
Log::printLine(cell_name + "->Cap->S0_b=" + (String) s0_b_cap);
Log::printLine(cell_name + "->Cap->Y_b=" + (String) y_b_cap);
Log::printLine(cell_name + "->Cap->Y=" + (String) y_cap);
// --------------------------------------------------------------------
// --------------------------------------------------------------------
// Build Internal Delay Model
// --------------------------------------------------------------------
// Build abstracted timing model
double y_ron = getDriver("INV2_RonZN")->getOutputRes();
double a_to_y_delay = 0.0;
a_to_y_delay += getDriver("INVZ1_RonZN")->calculateDelay();
a_to_y_delay += getDriver("INV2_RonZN")->calculateDelay();
double b_to_y_delay = 0.0;
b_to_y_delay += getDriver("INVZ1_RonZN")->calculateDelay();
b_to_y_delay += getDriver("INV2_RonZN")->calculateDelay();
double s0_to_y_delay = 0.0;
s0_to_y_delay += getDriver("INV1_RonZN")->calculateDelay();
s0_to_y_delay += max(getDriver("INVZ1_RonZN")->calculateDelay(), getDriver("INVZ1_RonZN")->calculateDelay());
s0_to_y_delay += getDriver("INV2_RonZN")->calculateDelay();
cache->set(cell_name + "->DriveRes->Y", y_ron);
cache->set(cell_name + "->Delay->A_to_Y", a_to_y_delay);
cache->set(cell_name + "->Delay->B_to_Y", b_to_y_delay);
cache->set(cell_name + "->Delay->S0_to_Y", s0_to_y_delay);
Log::printLine(cell_name + "->DriveRes->Y=" + (String) y_ron);
Log::printLine(cell_name + "->Delay->A_to_Y=" + (String) a_to_y_delay);
Log::printLine(cell_name + "->Delay->B_to_Y=" + (String) b_to_y_delay);
Log::printLine(cell_name + "->Delay->S0_to_Y=" + (String) s0_to_y_delay);
// --------------------------------------------------------------------
return;
}
} // namespace DSENT
| 50.992874 | 143 | 0.602851 |
73f33b62a323bf26a419c2541deecbc0cec561ef | 4,824 | cc | C++ | chromium/chrome/browser/autofill/autofill_cc_infobar_delegate_unittest.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/chrome/browser/autofill/autofill_cc_infobar_delegate_unittest.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/chrome/browser/autofill/autofill_cc_infobar_delegate_unittest.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/autofill/core/browser/autofill_cc_infobar_delegate.h"
#include "base/macros.h"
#include "base/memory/scoped_ptr.h"
#include "base/test/histogram_tester.h"
#include "chrome/browser/autofill/personal_data_manager_factory.h"
#include "chrome/browser/ui/autofill/chrome_autofill_client.h"
#include "chrome/test/base/chrome_render_view_host_test_harness.h"
#include "chrome/test/base/testing_profile.h"
#include "components/autofill/core/browser/autofill_test_utils.h"
#include "components/autofill/core/browser/personal_data_manager.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using testing::_;
namespace autofill {
namespace {
class TestPersonalDataManager : public PersonalDataManager {
public:
TestPersonalDataManager() : PersonalDataManager("en-US") {}
using PersonalDataManager::set_database;
using PersonalDataManager::SetPrefService;
// Overridden to avoid a trip to the database.
void LoadProfiles() override {}
void LoadCreditCards() override {}
MOCK_METHOD1(SaveImportedCreditCard,
std::string(const CreditCard& imported_credit_card));
private:
DISALLOW_COPY_AND_ASSIGN(TestPersonalDataManager);
};
} // namespace
class AutofillCCInfobarDelegateTest : public ChromeRenderViewHostTestHarness {
public:
AutofillCCInfobarDelegateTest();
~AutofillCCInfobarDelegateTest() override;
void SetUp() override;
void TearDown() override;
protected:
scoped_ptr<ConfirmInfoBarDelegate> CreateDelegate();
scoped_ptr<TestPersonalDataManager> personal_data_;
private:
DISALLOW_COPY_AND_ASSIGN(AutofillCCInfobarDelegateTest);
};
AutofillCCInfobarDelegateTest::AutofillCCInfobarDelegateTest() {
}
AutofillCCInfobarDelegateTest::~AutofillCCInfobarDelegateTest() {}
void AutofillCCInfobarDelegateTest::SetUp() {
ChromeRenderViewHostTestHarness::SetUp();
// Ensure Mac OS X does not pop up a modal dialog for the Address Book.
test::DisableSystemServices(profile()->GetPrefs());
PersonalDataManagerFactory::GetInstance()->SetTestingFactory(profile(), NULL);
ChromeAutofillClient::CreateForWebContents(web_contents());
ChromeAutofillClient* autofill_client =
ChromeAutofillClient::FromWebContents(web_contents());
personal_data_.reset(new TestPersonalDataManager());
personal_data_->set_database(autofill_client->GetDatabase());
personal_data_->SetPrefService(profile()->GetPrefs());
}
void AutofillCCInfobarDelegateTest::TearDown() {
personal_data_.reset();
ChromeRenderViewHostTestHarness::TearDown();
}
scoped_ptr<ConfirmInfoBarDelegate>
AutofillCCInfobarDelegateTest::CreateDelegate() {
base::HistogramTester histogram_tester;
CreditCard credit_card;
scoped_ptr<ConfirmInfoBarDelegate> delegate(AutofillCCInfoBarDelegate::Create(
base::Bind(
base::IgnoreResult(&TestPersonalDataManager::SaveImportedCreditCard),
base::Unretained(personal_data_.get()), credit_card)));
histogram_tester.ExpectUniqueSample("Autofill.CreditCardInfoBar",
AutofillMetrics::INFOBAR_SHOWN, 1);
return delegate;
}
// Test that credit card infobar metrics are logged correctly.
TEST_F(AutofillCCInfobarDelegateTest, Metrics) {
::testing::InSequence dummy;
// Accept the infobar.
{
scoped_ptr<ConfirmInfoBarDelegate> infobar(CreateDelegate());
EXPECT_CALL(*personal_data_, SaveImportedCreditCard(_));
base::HistogramTester histogram_tester;
EXPECT_TRUE(infobar->Accept());
histogram_tester.ExpectUniqueSample("Autofill.CreditCardInfoBar",
AutofillMetrics::INFOBAR_ACCEPTED, 1);
}
// Cancel the infobar.
{
scoped_ptr<ConfirmInfoBarDelegate> infobar(CreateDelegate());
base::HistogramTester histogram_tester;
EXPECT_TRUE(infobar->Cancel());
histogram_tester.ExpectUniqueSample("Autofill.CreditCardInfoBar",
AutofillMetrics::INFOBAR_DENIED, 1);
}
// Dismiss the infobar.
{
scoped_ptr<ConfirmInfoBarDelegate> infobar(CreateDelegate());
base::HistogramTester histogram_tester;
infobar->InfoBarDismissed();
histogram_tester.ExpectUniqueSample("Autofill.CreditCardInfoBar",
AutofillMetrics::INFOBAR_DENIED, 1);
}
// Ignore the infobar.
{
scoped_ptr<ConfirmInfoBarDelegate> infobar(CreateDelegate());
base::HistogramTester histogram_tester;
infobar.reset();
histogram_tester.ExpectUniqueSample("Autofill.CreditCardInfoBar",
AutofillMetrics::INFOBAR_IGNORED, 1);
}
}
} // namespace autofill
| 32.375839 | 80 | 0.751036 |
73f36b14922041ca588a53c2303aabd62200aeb4 | 3,349 | cpp | C++ | src/globals.cpp | mad-mix/my-little-investigations | 8d40d117a4de44c337dd4d015cfcfa44c9de29e7 | [
"MIT"
] | null | null | null | src/globals.cpp | mad-mix/my-little-investigations | 8d40d117a4de44c337dd4d015cfcfa44c9de29e7 | [
"MIT"
] | null | null | null | src/globals.cpp | mad-mix/my-little-investigations | 8d40d117a4de44c337dd4d015cfcfa44c9de29e7 | [
"MIT"
] | null | null | null | /**
* Provides global variables for use in the game's source code.
*
* @author GabuEx, dawnmew
* @since 1.0
*
* Licensed under the MIT License.
*
* Copyright (c) 2014 Equestrian Dreamers
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "globals.h"
#ifdef GAME_EXECUTABLE
#include "MLIException.h"
#include <SDL2/SDL.h>
#endif
SDL_Window *gpWindow = NULL;
SDL_Renderer *gpRenderer = NULL;
Uint16 gScreenWidth = 0;
Uint16 gScreenHeight = 0;
int gMaxTextureWidth = 0;
int gMaxTextureHeight = 0;
#ifdef GAME_EXECUTABLE
bool gIsFullscreen = false;
double gScreenScale = 0.0;
Uint16 gHorizontalOffset = 0;
Uint16 gVerticalOffset = 0;
int gTexturesRecreatedCount = 0;
bool gIsSavingScreenshot = false;
Uint16 gScreenshotWidth = 0;
Uint16 gScreenshotHeight = 0;
#endif
double gFramerate = 0.0;
string gTitle = "";
#ifdef GAME_EXECUTABLE
SDL_threadID gUiThreadId = 0;
string gCaseFilePath = "";
string gSaveFilePath = "";
bool gEnableTutorials = true;
bool gEnableHints = true;
bool gEnableFullscreen = false;
bool gEnableSkippingUnseenDialog = false;
#ifdef ENABLE_DEBUG_MODE
bool gEnableDebugMode = false;
#endif
double gBackgroundMusicVolume = 0.2;
double gSoundEffectsVolume = 0.67;
double gVoiceVolume = 0.5;
bool gEnableTutorialsDefault = gEnableTutorials;
bool gEnableHintsDefault = gEnableHints;
bool gEnableFullscreenDefault = gEnableFullscreen;
bool gEnableSkippingUnseenDialogDefault = gEnableSkippingUnseenDialog;
#ifdef ENABLE_DEBUG_MODE
bool gEnableDebugModeDefault = gEnableDebugMode;
#endif
double gBackgroundMusicVolumeDefault = gBackgroundMusicVolume;
double gSoundEffectsVolumeDefault = gSoundEffectsVolume;
double gVoiceVolumeDefault = gVoiceVolume;
vector<string> gCompletedCaseGuidList;
map<string, bool> gCaseIsSignedByFilePathMap;
vector<string> gDialogsSeenList;
bool gToggleFullscreen = false;
#else
CURL *gpCurlHandle = NULL;
#endif
bool gIsQuitting = false;
Version gVersion(1, 0, 0);
#ifdef UPDATER
string gVersionsXmlFilePath = "";
#endif
#ifdef GAME_EXECUTABLE
LocalizableContent *pgLocalizableContent = NULL;
#endif
void EnsureUIThread()
{
#ifdef GAME_EXECUTABLE
SDL_threadID currentThreadId = SDL_ThreadID();
if (currentThreadId != gUiThreadId)
{
throw new MLIException("This method can only be called on the UI thread.");
}
#endif
}
| 27.677686 | 83 | 0.776351 |
73f5d37c848c88088ac7fd1c24e98c0bc7ea3dc6 | 1,540 | cpp | C++ | src/lib/OpenEXR/ImfRational.cpp | msercheli/openexr | 9912f6b3886f6c695547747d70e19b98c0e38d59 | [
"BSD-3-Clause"
] | 517 | 2018-08-11T02:18:47.000Z | 2022-03-27T05:31:40.000Z | src/lib/OpenEXR/ImfRational.cpp | msercheli/openexr | 9912f6b3886f6c695547747d70e19b98c0e38d59 | [
"BSD-3-Clause"
] | 391 | 2018-07-31T21:28:52.000Z | 2022-03-28T16:51:18.000Z | src/lib/OpenEXR/ImfRational.cpp | msercheli/openexr | 9912f6b3886f6c695547747d70e19b98c0e38d59 | [
"BSD-3-Clause"
] | 189 | 2018-12-22T15:39:26.000Z | 2022-03-16T17:03:20.000Z | //
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) Contributors to the OpenEXR Project.
//
//-----------------------------------------------------------------------------
//
// Rational numbers
//
// The double-to-Rational conversion code below
// was contributed to OpenEXR by Greg Ward.
//
//-----------------------------------------------------------------------------
#include <ImfRational.h>
#include <cmath>
using namespace std;
#include "ImfNamespace.h"
OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER
namespace {
double
frac (double x, double e)
{
return x - floor (x + e);
}
double
square (double x)
{
return x * x;
}
double
denom (double x, double e)
{
if (e > frac (x, e))
{
return 1;
}
else
{
double r = frac (1 / x, e);
if (e > r)
{
return floor (1 / x + e);
}
else
{
return denom (frac (1 / r, e), e / square (x * r)) +
floor (1 / x + e) * denom (frac (1 / x, e), e / square (x));
}
}
}
} // namespace
Rational::Rational (double x)
{
int sign;
if (x >= 0)
{
sign = 1; // positive
}
else if (x < 0)
{
sign = -1; // negative
x = -x;
}
else
{
n = 0; // NaN
d = 0;
return;
}
if (x >= (1U << 31) - 0.5)
{
n = sign; // infinity
d = 0;
return;
}
double e = (x < 1? 1: x) / (1U << 30);
d = (unsigned int) denom (x, e);
n = sign * (int) floor (x * d + 0.5);
}
OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_EXIT
| 15.555556 | 79 | 0.453247 |
73f6a3b9c1109b0d7ddb9bf54156dfe992327db7 | 1,974 | cpp | C++ | net/Connection.cpp | l4l/rl | 7b72f5a7a4e0a0160d4ef1b3a1839d760b9cb2ce | [
"WTFPL"
] | 1 | 2015-10-08T18:58:23.000Z | 2015-10-08T18:58:23.000Z | net/Connection.cpp | l4l/rl | 7b72f5a7a4e0a0160d4ef1b3a1839d760b9cb2ce | [
"WTFPL"
] | null | null | null | net/Connection.cpp | l4l/rl | 7b72f5a7a4e0a0160d4ef1b3a1839d760b9cb2ce | [
"WTFPL"
] | null | null | null | #include "boost/array.hpp"
#include "Connection.h"
using boost::asio::ip::tcp;
Connection::Connection(std::string host, short port) :
_host(host), _port(port),
_io_service(), _socket(_io_service) {}
Connection::~Connection() {
close();
}
bool Connection::connect() {
std::clog << "Starting connect to " << _host << ":" << _port << std::endl;
try {
tcp::resolver::iterator endpoint_iterator =
tcp::resolver(_io_service).resolve(
tcp::resolver::query(_host,
std::string(std::to_string(_port))));
tcp::endpoint endpoint = *endpoint_iterator;
boost::system::error_code error;
_socket.connect(endpoint, error);
if (error)
throw boost::system::system_error(error);
} catch (std::exception& e) {
std::cerr << "Connection failed (Error: " << e.what() << ')' << std::endl;
return false;
}
return true;
}
bool Connection::recv(char bytes[], unsigned int size) {
boost::array<char, 128> buf;
boost::system::error_code error;
size_t len = _socket.read_some(boost::asio::buffer(buf), error);
for (int i = 0; i < len; ++i)
std::clog<<buf.elems[i];
return true;
}
bool Connection::send(const char bytes[], int size) {
int tmp = 0;
boost::system::error_code error;
try {
while (!error && size > tmp ) {
tmp += _socket.write_some(boost::asio::buffer(bytes + tmp, size - tmp), error);
}
if(error)
throw boost::system::system_error(error);
} catch (std::exception& e) {
std::cerr << "recv failed (Error: " << e.what() << ')' << std::endl;
return false;
}
return true;
}
// Close down the connection properly.
void Connection::close() {
try{
_socket.close();
} catch (...) {
std::clog << "closing failed: connection already closed" << std::endl;
}
} | 29.909091 | 91 | 0.56231 |
73f6e4bc65509bde6d165c9b47c363c947c09932 | 5,637 | cpp | C++ | src/wiring/ads1115.cpp | Yanick-Salzmann/grower-controller-rpi | 30f279e960a3cc8125f112c76ee943b1fa766191 | [
"MIT"
] | null | null | null | src/wiring/ads1115.cpp | Yanick-Salzmann/grower-controller-rpi | 30f279e960a3cc8125f112c76ee943b1fa766191 | [
"MIT"
] | null | null | null | src/wiring/ads1115.cpp | Yanick-Salzmann/grower-controller-rpi | 30f279e960a3cc8125f112c76ee943b1fa766191 | [
"MIT"
] | null | null | null | #include "ads1115.hpp"
#include <stdexcept>
#include <chrono>
#include <thread>
#include <wiringPiI2C.h>
#include <netinet/in.h>
namespace grower::wiring {
enum conversion_delay : uint32_t {
ADS1115_CONVERSION_DELAY_8 = 128000,
ADS1115_CONVERSION_DELAY_16 = 64000,
ADS1115_CONVERSION_DELAY_32 = 32000,
ADS1115_CONVERSION_DELAY_64 = 16000,
ADS1115_CONVERSION_DELAY_128 = 8000,
ADS1115_CONVERSION_DELAY_250 = 4000,
ADS1115_CONVERSION_DELAY_475 = 2200,
ADS1115_CONVERSION_DELAY_860 = 1200
};
enum pointer_register : uint8_t {
ADS1115_REG_POINTER_MASK = 0x03,
ADS1115_REG_POINTER_CONVERT = 0x00,
ADS1115_REG_POINTER_CONFIG = 0x01,
ADS1115_REG_POINTER_LOWTHRESH = 0x02,
ADS1115_REG_POINTER_HITHRESH = 0x03
};
enum config_register : uint16_t {
ADS1115_REG_CONFIG_OS_MASK = 0x8000,
ADS1115_REG_CONFIG_OS_SINGLE = 0x8000,
ADS1115_REG_CONFIG_OS_BUSY = 0x0000,
ADS1115_REG_CONFIG_OS_NOTBUSY = 0x8000,
ADS1115_REG_CONFIG_MUX_MASK = 0x7000,
ADS1115_REG_CONFIG_MUX_DIFF_0_1 = 0x0000,
ADS1115_REG_CONFIG_MUX_DIFF_0_3 = 0x1000,
ADS1115_REG_CONFIG_MUX_DIFF_1_3 = 0x2000,
ADS1115_REG_CONFIG_MUX_DIFF_2_3 = 0x3000,
ADS1115_REG_CONFIG_MUX_SINGLE_0 = 0x4000,
ADS1115_REG_CONFIG_MUX_SINGLE_1 = 0x5000,
ADS1115_REG_CONFIG_MUX_SINGLE_2 = 0x6000,
ADS1115_REG_CONFIG_MUX_SINGLE_3 = 0x7000,
ADS1115_REG_CONFIG_PGA_MASK = 0x0E00,
ADS1115_REG_CONFIG_PGA_6_144V = 0x0000,
ADS1115_REG_CONFIG_PGA_4_096V = 0x0200,
ADS1115_REG_CONFIG_PGA_2_048V = 0x0400,
ADS1115_REG_CONFIG_PGA_1_024V = 0x0600,
ADS1115_REG_CONFIG_PGA_0_512V = 0x0800,
ADS1115_REG_CONFIG_PGA_0_256V = 0x0A00,
ADS1115_REG_CONFIG_MODE_MASK = 0x0100,
ADS1115_REG_CONFIG_MODE_CONTIN = 0x0000,
ADS1115_REG_CONFIG_MODE_SINGLE = 0x0100,
ADS1115_REG_CONFIG_DR_MASK = 0x00E0,
ADS1115_REG_CONFIG_DR_8SPS = 0x0000,
ADS1115_REG_CONFIG_DR_16SPS = 0x0020,
ADS1115_REG_CONFIG_DR_32SPS = 0x0040,
ADS1115_REG_CONFIG_DR_64SPS = 0x0060,
ADS1115_REG_CONFIG_DR_128SPS = 0x0080,
ADS1115_REG_CONFIG_DR_250SPS = 0x00A0,
ADS1115_REG_CONFIG_DR_475SPS = 0x00C0,
ADS1115_REG_CONFIG_DR_860SPS = 0x00E0,
ADS1115_REG_CONFIG_CMODE_MASK = 0x0010,
ADS1115_REG_CONFIG_CMODE_TRAD = 0x0000,
ADS1115_REG_CONFIG_CMODE_WINDOW = 0x0010,
ADS1115_REG_CONFIG_CPOL_MASK = 0x0008,
ADS1115_REG_CONFIG_CPOL_ACTVLOW = 0x0000,
ADS1115_REG_CONFIG_CPOL_ACTVHI = 0x0008,
ADS1115_REG_CONFIG_CLAT_MASK = 0x0004,
ADS1115_REG_CONFIG_CLAT_NONLAT = 0x0000,
ADS1115_REG_CONFIG_CLAT_LATCH = 0x0004,
ADS1115_REG_CONFIG_CQUE_MASK = 0x0003,
ADS1115_REG_CONFIG_CQUE_1CONV = 0x0000,
ADS1115_REG_CONFIG_CQUE_2CONV = 0x0001,
ADS1115_REG_CONFIG_CQUE_4CONV = 0x0002,
ADS1115_REG_CONFIG_CQUE_NONE = 0x0003,
};
enum ads_gain : uint16_t {
GAIN_TWOTHIRDS = ADS1115_REG_CONFIG_PGA_6_144V,
GAIN_ONE = ADS1115_REG_CONFIG_PGA_4_096V,
GAIN_TWO = ADS1115_REG_CONFIG_PGA_2_048V,
GAIN_FOUR = ADS1115_REG_CONFIG_PGA_1_024V,
GAIN_EIGHT = ADS1115_REG_CONFIG_PGA_0_512V,
GAIN_SIXTEEN = ADS1115_REG_CONFIG_PGA_0_256V
};
enum ads_sps : uint16_t {
SPS_8 = ADS1115_REG_CONFIG_DR_8SPS,
SPS_16 = ADS1115_REG_CONFIG_DR_16SPS,
SPS_32 = ADS1115_REG_CONFIG_DR_32SPS,
SPS_64 = ADS1115_REG_CONFIG_DR_64SPS,
SPS_128 = ADS1115_REG_CONFIG_DR_128SPS,
SPS_250 = ADS1115_REG_CONFIG_DR_250SPS,
SPS_475 = ADS1115_REG_CONFIG_DR_475SPS,
SPS_860 = ADS1115_REG_CONFIG_DR_860SPS
};
ads1115::ads1115(int device_id) {
_device = wiringPiI2CSetup(device_id);
if (_device < 0) {
throw std::runtime_error{"Error opening I2C device"};
}
_gain = GAIN_ONE;
_sps = SPS_860;
_conversion_delay = ADS1115_CONVERSION_DELAY_860;
}
uint16_t ads1115::read_single_channel(uint8_t channel) {
if (channel > 3) {
throw std::runtime_error{"Invalid channel, must be < 4"};
}
auto config = static_cast<uint16_t>(ADS1115_REG_CONFIG_CQUE_NONE |
ADS1115_REG_CONFIG_CLAT_NONLAT |
ADS1115_REG_CONFIG_CPOL_ACTVLOW |
ADS1115_REG_CONFIG_CMODE_TRAD |
ADS1115_REG_CONFIG_MODE_SINGLE);
config |= _gain;
config |= _sps;
switch(channel) {
case 0:
config |= ADS1115_REG_CONFIG_MUX_SINGLE_0;
break;
case 1:
config |= ADS1115_REG_CONFIG_MUX_SINGLE_1;
break;
case 2:
config |= ADS1115_REG_CONFIG_MUX_SINGLE_2;
break;
case 3:
config |= ADS1115_REG_CONFIG_MUX_SINGLE_3;
break;
default:
throw std::runtime_error{"Channel must be <= 3"};
}
config |= ADS1115_REG_CONFIG_OS_SINGLE;
wiringPiI2CWriteReg16(_device, ADS1115_REG_POINTER_CONFIG, htons(config));
std::this_thread::sleep_for(std::chrono::microseconds{_conversion_delay});
const auto value = (uint16_t) wiringPiI2CReadReg16(_device, ADS1115_REG_POINTER_CONVERT);
return htons(value);
}
} | 35.23125 | 97 | 0.66099 |
73f8dc4c074982a878f59716c078a9ac87a3b08f | 5,525 | cpp | C++ | src/plugins/follow_me/follow_me.cpp | rworrall/MAVSDK | 634f171bb5b492e2d5bd6453f54e7e88c603899e | [
"BSD-3-Clause"
] | 275 | 2019-06-13T17:50:40.000Z | 2022-03-28T01:03:01.000Z | src/plugins/follow_me/follow_me.cpp | rworrall/MAVSDK | 634f171bb5b492e2d5bd6453f54e7e88c603899e | [
"BSD-3-Clause"
] | 655 | 2019-06-07T13:08:12.000Z | 2022-03-23T04:51:21.000Z | src/plugins/follow_me/follow_me.cpp | SEESAI/MAVSDK | 5a9289eb09eb6b13f24e9d8d69f5644d2210d6b2 | [
"BSD-3-Clause"
] | 299 | 2019-06-10T06:58:58.000Z | 2022-03-25T04:14:34.000Z | // WARNING: THIS FILE IS AUTOGENERATED! As such, it should not be edited.
// Edits need to be made to the proto files
// (see https://github.com/mavlink/MAVSDK-Proto/blob/master/protos/follow_me/follow_me.proto)
#include <iomanip>
#include "follow_me_impl.h"
#include "plugins/follow_me/follow_me.h"
namespace mavsdk {
using Config = FollowMe::Config;
using TargetLocation = FollowMe::TargetLocation;
FollowMe::FollowMe(System& system) : PluginBase(), _impl{std::make_unique<FollowMeImpl>(system)} {}
FollowMe::FollowMe(std::shared_ptr<System> system) :
PluginBase(),
_impl{std::make_unique<FollowMeImpl>(system)}
{}
FollowMe::~FollowMe() {}
FollowMe::Config FollowMe::get_config() const
{
return _impl->get_config();
}
FollowMe::Result FollowMe::set_config(Config config) const
{
return _impl->set_config(config);
}
bool FollowMe::is_active() const
{
return _impl->is_active();
}
FollowMe::Result FollowMe::set_target_location(TargetLocation location) const
{
return _impl->set_target_location(location);
}
FollowMe::TargetLocation FollowMe::get_last_location() const
{
return _impl->get_last_location();
}
FollowMe::Result FollowMe::start() const
{
return _impl->start();
}
FollowMe::Result FollowMe::stop() const
{
return _impl->stop();
}
std::ostream&
operator<<(std::ostream& str, FollowMe::Config::FollowDirection const& follow_direction)
{
switch (follow_direction) {
case FollowMe::Config::FollowDirection::None:
return str << "None";
case FollowMe::Config::FollowDirection::Behind:
return str << "Behind";
case FollowMe::Config::FollowDirection::Front:
return str << "Front";
case FollowMe::Config::FollowDirection::FrontRight:
return str << "Front Right";
case FollowMe::Config::FollowDirection::FrontLeft:
return str << "Front Left";
default:
return str << "Unknown";
}
}
bool operator==(const FollowMe::Config& lhs, const FollowMe::Config& rhs)
{
return ((std::isnan(rhs.min_height_m) && std::isnan(lhs.min_height_m)) ||
rhs.min_height_m == lhs.min_height_m) &&
((std::isnan(rhs.follow_distance_m) && std::isnan(lhs.follow_distance_m)) ||
rhs.follow_distance_m == lhs.follow_distance_m) &&
(rhs.follow_direction == lhs.follow_direction) &&
((std::isnan(rhs.responsiveness) && std::isnan(lhs.responsiveness)) ||
rhs.responsiveness == lhs.responsiveness);
}
std::ostream& operator<<(std::ostream& str, FollowMe::Config const& config)
{
str << std::setprecision(15);
str << "config:" << '\n' << "{\n";
str << " min_height_m: " << config.min_height_m << '\n';
str << " follow_distance_m: " << config.follow_distance_m << '\n';
str << " follow_direction: " << config.follow_direction << '\n';
str << " responsiveness: " << config.responsiveness << '\n';
str << '}';
return str;
}
bool operator==(const FollowMe::TargetLocation& lhs, const FollowMe::TargetLocation& rhs)
{
return ((std::isnan(rhs.latitude_deg) && std::isnan(lhs.latitude_deg)) ||
rhs.latitude_deg == lhs.latitude_deg) &&
((std::isnan(rhs.longitude_deg) && std::isnan(lhs.longitude_deg)) ||
rhs.longitude_deg == lhs.longitude_deg) &&
((std::isnan(rhs.absolute_altitude_m) && std::isnan(lhs.absolute_altitude_m)) ||
rhs.absolute_altitude_m == lhs.absolute_altitude_m) &&
((std::isnan(rhs.velocity_x_m_s) && std::isnan(lhs.velocity_x_m_s)) ||
rhs.velocity_x_m_s == lhs.velocity_x_m_s) &&
((std::isnan(rhs.velocity_y_m_s) && std::isnan(lhs.velocity_y_m_s)) ||
rhs.velocity_y_m_s == lhs.velocity_y_m_s) &&
((std::isnan(rhs.velocity_z_m_s) && std::isnan(lhs.velocity_z_m_s)) ||
rhs.velocity_z_m_s == lhs.velocity_z_m_s);
}
std::ostream& operator<<(std::ostream& str, FollowMe::TargetLocation const& target_location)
{
str << std::setprecision(15);
str << "target_location:" << '\n' << "{\n";
str << " latitude_deg: " << target_location.latitude_deg << '\n';
str << " longitude_deg: " << target_location.longitude_deg << '\n';
str << " absolute_altitude_m: " << target_location.absolute_altitude_m << '\n';
str << " velocity_x_m_s: " << target_location.velocity_x_m_s << '\n';
str << " velocity_y_m_s: " << target_location.velocity_y_m_s << '\n';
str << " velocity_z_m_s: " << target_location.velocity_z_m_s << '\n';
str << '}';
return str;
}
std::ostream& operator<<(std::ostream& str, FollowMe::Result const& result)
{
switch (result) {
case FollowMe::Result::Unknown:
return str << "Unknown";
case FollowMe::Result::Success:
return str << "Success";
case FollowMe::Result::NoSystem:
return str << "No System";
case FollowMe::Result::ConnectionError:
return str << "Connection Error";
case FollowMe::Result::Busy:
return str << "Busy";
case FollowMe::Result::CommandDenied:
return str << "Command Denied";
case FollowMe::Result::Timeout:
return str << "Timeout";
case FollowMe::Result::NotActive:
return str << "Not Active";
case FollowMe::Result::SetConfigFailed:
return str << "Set Config Failed";
default:
return str << "Unknown";
}
}
} // namespace mavsdk | 35.416667 | 99 | 0.631131 |
73fa3659a1b7033d445a1a9baae14eb5aed32c57 | 9,925 | cpp | C++ | Tutorials/ForkJoin/MLMG/main.cpp | ylunalin/amrex | 5715b2fc8a77e0db17bfe7907982e29ec44811ca | [
"BSD-3-Clause-LBNL"
] | null | null | null | Tutorials/ForkJoin/MLMG/main.cpp | ylunalin/amrex | 5715b2fc8a77e0db17bfe7907982e29ec44811ca | [
"BSD-3-Clause-LBNL"
] | null | null | null | Tutorials/ForkJoin/MLMG/main.cpp | ylunalin/amrex | 5715b2fc8a77e0db17bfe7907982e29ec44811ca | [
"BSD-3-Clause-LBNL"
] | null | null | null | #include <sstream>
#include <AMReX_Vector.H>
#include <AMReX_MultiFab.H>
#include <AMReX_ParmParse.H>
#include <AMReX_VisMF.H>
#include <AMReX_Geometry.H>
#include <AMReX_MLMG.H>
#include <AMReX_MLABecLaplacian.H>
#include <AMReX_ParallelContext.H>
#include <AMReX_ForkJoin.H>
using namespace amrex;
namespace {
int ntasks = 2;
int ncomp = 8;
Real a = 1.e-3;
Real b = 1.0;
Real sigma = 10.0; // controls the size of jump
Real w = 0.05; // contols the width of the jump
int fj_verbose = 0;
int mlmg_verbose = 0;
Real tolerance_rel = 1.e-8;
Real tolerance_abs = 0.0;
int flag_modify_split = 0;
std::string task_output_dir = "";
}
extern "C"
{
void fort_set_rhs(double*, const int*, const int*, int,
const double*, double, double, double, double);
void fort_set_coef(double*, const int*, const int*,
double*, const int*, const int*,
int, const double*, double, double);
}
void setup_rhs(MultiFab& rhs, const Geometry& geom);
void setup_coeffs(MultiFab& alpha, const Vector<MultiFab*>& beta, const Geometry& geom);
void top_fork(MultiFab& soln, const MultiFab& rhs,
const MultiFab& alpha, const Vector<MultiFab*>& beta,
const Geometry& geom);
void fork_solve(MultiFab& soln, const MultiFab& rhs,
const MultiFab& alpha, const Vector<MultiFab*>& beta,
const Geometry& geom);
void solve_all(MultiFab& soln, const MultiFab& rhs,
const MultiFab& alpha, const Vector<MultiFab*>& beta,
const Geometry& geom);
void single_component_solve(MultiFab& soln, const MultiFab& rhs,
const MultiFab& alpha, const Vector<MultiFab*>& beta,
const Geometry& geom);
int main(int argc, char* argv[])
{
amrex::Initialize(argc,argv);
{
BoxArray ba;
Geometry geom;
{
ParmParse pp;
pp.query("ntasks", ntasks);
pp.query("fj_verbose", fj_verbose);
pp.query("mlmg_verbose", mlmg_verbose);
pp.query("ncomp", ncomp);
pp.query("modify_split", flag_modify_split);
pp.query("task_output_dir", task_output_dir);
int n_cell, max_grid_size;
pp.get("n_cell", n_cell);
pp.get("max_grid_size", max_grid_size);
AMREX_ALWAYS_ASSERT_WITH_MESSAGE(
ParallelDescriptor::NProcs() >= ntasks + 1,
"Need at least ntasks + 1 ranks");
Box domain(IntVect(AMREX_D_DECL( 0, 0, 0)),
IntVect(AMREX_D_DECL(n_cell-1,n_cell-1,n_cell-1)));
ba.define(domain);
ba.maxSize(max_grid_size);
RealBox real_box;
for (int n = 0; n < BL_SPACEDIM; n++) {
real_box.setLo(n, 0.0);
real_box.setHi(n, 1.0);
}
int coord = 0;
geom.define(domain,&real_box,coord);
}
DistributionMapping dm{ba};
MultiFab rhs(ba, dm, ncomp, 0);
setup_rhs(rhs, geom);
MultiFab alpha(ba, dm, ncomp, 0);
Vector<MultiFab> beta(BL_SPACEDIM);
for (int i = 0; i < BL_SPACEDIM; ++i) {
beta[i].define(amrex::convert(ba, IntVect::TheDimensionVector(i)),
dm, ncomp, 0);
}
setup_coeffs(alpha, amrex::GetVecOfPtrs(beta), geom);
MultiFab soln(ba, dm, ncomp, 0);
top_fork(soln, rhs, alpha, amrex::GetVecOfPtrs(beta), geom);
VisMF::Write(soln, "soln");
} // MultiFab destructors called before amrex::Finalize()
amrex::Finalize();
}
void setup_rhs(MultiFab& rhs, const Geometry& geom)
{
const Real* dx = geom.CellSize();
for ( MFIter mfi(rhs); mfi.isValid(); ++mfi )
{
const int* rlo = rhs[mfi].loVect();
const int* rhi = rhs[mfi].hiVect();
fort_set_rhs(rhs[mfi].dataPtr(),rlo, rhi, rhs.nComp(),
dx, a, b, sigma, w);
}
}
void setup_coeffs(MultiFab& alpha, const Vector<MultiFab*>& beta, const Geometry& geom)
{
const Real* dx = geom.CellSize();
alpha.setVal(1.0);
#if (BL_SPACEDIM == 3)
amrex::Abort("2D only");
#endif
for ( MFIter mfi(alpha); mfi.isValid(); ++mfi )
{
FArrayBox& betax = (*beta[0])[mfi];
FArrayBox& betay = (*beta[1])[mfi];
fort_set_coef(betax.dataPtr(), betax.loVect(), betax.hiVect(),
betay.dataPtr(), betay.loVect(), betay.hiVect(),
beta[0]->nComp(), dx, sigma, w);
}
}
void top_fork(MultiFab& soln, const MultiFab& rhs,
const MultiFab& alpha, const Vector<MultiFab*>& beta, const Geometry& geom)
{
auto proc_n = ParallelContext::NProcsSub();
ForkJoin fj(Vector<int> {1, proc_n - 1});
fj.SetVerbose(fj_verbose);
fj.set_task_output_dir(task_output_dir);
// these multifabs go to task 0 only
fj.reg_mf (rhs , "rhs" , ForkJoin::Strategy::single, ForkJoin::Intent::in , 1);
fj.reg_mf (alpha, "alpha", ForkJoin::Strategy::single, ForkJoin::Intent::in , 1);
fj.reg_mf_vec(beta , "beta" , ForkJoin::Strategy::single, ForkJoin::Intent::in , 1);
fj.reg_mf (soln , "soln" , ForkJoin::Strategy::single, ForkJoin::Intent::out, 1);
// issue top-level fork-join
fj.fork_join(
[&geom] (ForkJoin &f) {
if (f.MyTask() == 0) {
// Do some non-MLMG tasks
amrex::Print() << "Pretending to do some chemistry ...\n";
} else {
// Do some MLMG solves
amrex::Print() << "Do some linear solves ...\n";
fork_solve(f.get_mf("soln"), f.get_mf("rhs"), f.get_mf("alpha"),
f.get_mf_vec("beta"), geom);
}
}
);
}
void fork_solve(MultiFab& soln, const MultiFab& rhs,
const MultiFab& alpha, const Vector<MultiFab*>& beta, const Geometry& geom)
{
// evenly split ranks among ntasks tasks
ForkJoin fj(ntasks);
fj.SetVerbose(fj_verbose);
fj.set_task_output_dir(task_output_dir);
// register how to copy multifabs to/from tasks
fj.reg_mf (rhs , "rhs" , ForkJoin::Strategy::split, ForkJoin::Intent::in);
fj.reg_mf (alpha, "alpha", ForkJoin::Strategy::split, ForkJoin::Intent::in);
fj.reg_mf_vec(beta , "beta" , ForkJoin::Strategy::split, ForkJoin::Intent::in);
fj.reg_mf (soln , "soln" , ForkJoin::Strategy::split, ForkJoin::Intent::out);
if (flag_modify_split) {
auto comp_n = soln.nComp();
if (comp_n > ntasks) {
amrex::Print() << "Doing a custom split where first component is ignored\n";
// test custom split, skip the first component
Vector<ForkJoin::ComponentSet> comp_split(ntasks);
for (int i = 0; i < ntasks; ++i) {
// split components across tasks
comp_split[i].lo = 1 + (comp_n-1) * i / ntasks;
comp_split[i].hi = 1 + (comp_n-1) * (i+1) / ntasks;
}
fj.modify_split("rhs", comp_split);
fj.modify_split("alpha", comp_split);
for (int i = 0; i < beta.size(); ++i) {
fj.modify_split("beta", i, comp_split);
}
fj.modify_split("soln", comp_split);
}
}
// can reuse ForkJoin object for multiple fork-join invocations
// creates forked multifabs only first time around, reuses them thereafter
for (int i = 0; i < 2; ++i) {
// issue fork-join
fj.fork_join(
[&geom, i] (ForkJoin &f) {
solve_all(f.get_mf("soln"), f.get_mf("rhs"), f.get_mf("alpha"),
f.get_mf_vec("beta"), geom);
}
);
}
}
void solve_all(MultiFab& soln, const MultiFab& rhs,
const MultiFab& alpha, const Vector<MultiFab*>& beta,
const Geometry& geom)
{
const BoxArray& ba = soln.boxArray();
const DistributionMapping& dm = soln.DistributionMap();
if (rhs.nComp() == 1)
{
single_component_solve(soln, rhs, alpha, beta, geom);
}
else
{
for (int i = 0; i < soln.nComp(); ++i) {
MultiFab ssoln (ba, dm, 1, 1);
ssoln.setVal(0.0);
MultiFab srhs (rhs, amrex::make_alias, i, 1);
MultiFab salpha(alpha, amrex::make_alias, i, 1);
Vector<std::unique_ptr<MultiFab> > sbeta(AMREX_SPACEDIM);
for (int idim = 0; idim < AMREX_SPACEDIM; ++idim) {
sbeta[idim].reset(new MultiFab(*beta[idim], amrex::make_alias, i, 1));
}
single_component_solve(ssoln, srhs, salpha,
amrex::GetVecOfPtrs(sbeta), geom);
MultiFab::Copy(soln, ssoln, 0, i, 1, 0);
}
}
}
void single_component_solve(MultiFab& soln, const MultiFab& rhs,
const MultiFab& alpha, const Vector<MultiFab*>& beta,
const Geometry& geom)
{
const BoxArray& ba = soln.boxArray();
const DistributionMapping& dm = soln.DistributionMap();
MLABecLaplacian mlabec({geom}, {ba}, {dm});
mlabec.setDomainBC({AMREX_D_DECL(LinOpBCType::Dirichlet,
LinOpBCType::Dirichlet,
LinOpBCType::Dirichlet)},
{AMREX_D_DECL(LinOpBCType::Dirichlet,
LinOpBCType::Dirichlet,
LinOpBCType::Dirichlet)});
mlabec.setLevelBC(0, &soln);
mlabec.setScalars(a, b);
mlabec.setACoeffs(0, alpha);
mlabec.setBCoeffs(0, {AMREX_D_DECL(beta[0], beta[1], beta[2])});
MLMG mlmg(mlabec);
mlmg.setVerbose(mlmg_verbose);
mlmg.solve({&soln}, {&rhs}, tolerance_rel, tolerance_abs);
}
| 33.758503 | 91 | 0.559496 |
73fbab9e4e3fd2e51524449a52051cf952fc847a | 11,265 | hpp | C++ | include/System/Security/Cryptography/AesTransform.hpp | marksteward/BeatSaber-Quest-Codegen | a76f063f71cef207a9f048ad7613835f554911a7 | [
"Unlicense"
] | null | null | null | include/System/Security/Cryptography/AesTransform.hpp | marksteward/BeatSaber-Quest-Codegen | a76f063f71cef207a9f048ad7613835f554911a7 | [
"Unlicense"
] | null | null | null | include/System/Security/Cryptography/AesTransform.hpp | marksteward/BeatSaber-Quest-Codegen | a76f063f71cef207a9f048ad7613835f554911a7 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: Mono.Security.Cryptography.SymmetricTransform
#include "Mono/Security/Cryptography/SymmetricTransform.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Security::Cryptography
namespace System::Security::Cryptography {
// Forward declaring type: Aes
class Aes;
}
// Completed forward declares
// Type namespace: System.Security.Cryptography
namespace System::Security::Cryptography {
// Size: 0x68
#pragma pack(push, 1)
// Autogenerated type: System.Security.Cryptography.AesTransform
// [TokenAttribute] Offset: FFFFFFFF
class AesTransform : public Mono::Security::Cryptography::SymmetricTransform {
public:
// private System.UInt32[] expandedKey
// Size: 0x8
// Offset: 0x58
::Array<uint>* expandedKey;
// Field size check
static_assert(sizeof(::Array<uint>*) == 0x8);
// private System.Int32 Nk
// Size: 0x4
// Offset: 0x60
int Nk;
// Field size check
static_assert(sizeof(int) == 0x4);
// private System.Int32 Nr
// Size: 0x4
// Offset: 0x64
int Nr;
// Field size check
static_assert(sizeof(int) == 0x4);
// Creating value type constructor for type: AesTransform
AesTransform(::Array<uint>* expandedKey_ = {}, int Nk_ = {}, int Nr_ = {}) noexcept : expandedKey{expandedKey_}, Nk{Nk_}, Nr{Nr_} {}
// Get static field: static private readonly System.UInt32[] Rcon
static ::Array<uint>* _get_Rcon();
// Set static field: static private readonly System.UInt32[] Rcon
static void _set_Rcon(::Array<uint>* value);
// Get static field: static private readonly System.Byte[] SBox
static ::Array<uint8_t>* _get_SBox();
// Set static field: static private readonly System.Byte[] SBox
static void _set_SBox(::Array<uint8_t>* value);
// Get static field: static private readonly System.Byte[] iSBox
static ::Array<uint8_t>* _get_iSBox();
// Set static field: static private readonly System.Byte[] iSBox
static void _set_iSBox(::Array<uint8_t>* value);
// Get static field: static private readonly System.UInt32[] T0
static ::Array<uint>* _get_T0();
// Set static field: static private readonly System.UInt32[] T0
static void _set_T0(::Array<uint>* value);
// Get static field: static private readonly System.UInt32[] T1
static ::Array<uint>* _get_T1();
// Set static field: static private readonly System.UInt32[] T1
static void _set_T1(::Array<uint>* value);
// Get static field: static private readonly System.UInt32[] T2
static ::Array<uint>* _get_T2();
// Set static field: static private readonly System.UInt32[] T2
static void _set_T2(::Array<uint>* value);
// Get static field: static private readonly System.UInt32[] T3
static ::Array<uint>* _get_T3();
// Set static field: static private readonly System.UInt32[] T3
static void _set_T3(::Array<uint>* value);
// Get static field: static private readonly System.UInt32[] iT0
static ::Array<uint>* _get_iT0();
// Set static field: static private readonly System.UInt32[] iT0
static void _set_iT0(::Array<uint>* value);
// Get static field: static private readonly System.UInt32[] iT1
static ::Array<uint>* _get_iT1();
// Set static field: static private readonly System.UInt32[] iT1
static void _set_iT1(::Array<uint>* value);
// Get static field: static private readonly System.UInt32[] iT2
static ::Array<uint>* _get_iT2();
// Set static field: static private readonly System.UInt32[] iT2
static void _set_iT2(::Array<uint>* value);
// Get static field: static private readonly System.UInt32[] iT3
static ::Array<uint>* _get_iT3();
// Set static field: static private readonly System.UInt32[] iT3
static void _set_iT3(::Array<uint>* value);
// Get instance field: private System.UInt32[] expandedKey
::Array<uint>* _get_expandedKey();
// Set instance field: private System.UInt32[] expandedKey
void _set_expandedKey(::Array<uint>* value);
// Get instance field: private System.Int32 Nk
int _get_Nk();
// Set instance field: private System.Int32 Nk
void _set_Nk(int value);
// Get instance field: private System.Int32 Nr
int _get_Nr();
// Set instance field: private System.Int32 Nr
void _set_Nr(int value);
// public System.Void .ctor(System.Security.Cryptography.Aes algo, System.Boolean encryption, System.Byte[] key, System.Byte[] iv)
// Offset: 0x1DE7F60
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static AesTransform* New_ctor(System::Security::Cryptography::Aes* algo, bool encryption, ::Array<uint8_t>* key, ::Array<uint8_t>* iv) {
static auto ___internal__logger = ::Logger::get().WithContext("System::Security::Cryptography::AesTransform::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<AesTransform*, creationType>(algo, encryption, key, iv)));
}
// static private System.Void .cctor()
// Offset: 0x1DECD74
static void _cctor();
// private System.UInt32 SubByte(System.UInt32 a)
// Offset: 0x1DE905C
uint SubByte(uint a);
// private System.Void Encrypt128(System.Byte[] indata, System.Byte[] outdata, System.UInt32[] ekey)
// Offset: 0x1DE914C
void Encrypt128(::Array<uint8_t>* indata, ::Array<uint8_t>* outdata, ::Array<uint>* ekey);
// private System.Void Decrypt128(System.Byte[] indata, System.Byte[] outdata, System.UInt32[] ekey)
// Offset: 0x1DEAF64
void Decrypt128(::Array<uint8_t>* indata, ::Array<uint8_t>* outdata, ::Array<uint>* ekey);
// protected override System.Void ECB(System.Byte[] input, System.Byte[] output)
// Offset: 0x1DE9138
// Implemented from: Mono.Security.Cryptography.SymmetricTransform
// Base method: System.Void SymmetricTransform::ECB(System.Byte[] input, System.Byte[] output)
void ECB(::Array<uint8_t>* input, ::Array<uint8_t>* output);
}; // System.Security.Cryptography.AesTransform
#pragma pack(pop)
static check_size<sizeof(AesTransform), 100 + sizeof(int)> __System_Security_Cryptography_AesTransformSizeCheck;
static_assert(sizeof(AesTransform) == 0x68);
}
DEFINE_IL2CPP_ARG_TYPE(System::Security::Cryptography::AesTransform*, "System.Security.Cryptography", "AesTransform");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: System::Security::Cryptography::AesTransform::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::Security::Cryptography::AesTransform::_cctor
// Il2CppName: .cctor
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&System::Security::Cryptography::AesTransform::_cctor)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::AesTransform*), ".cctor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::AesTransform::SubByte
// Il2CppName: SubByte
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<uint (System::Security::Cryptography::AesTransform::*)(uint)>(&System::Security::Cryptography::AesTransform::SubByte)> {
static const MethodInfo* get() {
static auto* a = &::il2cpp_utils::GetClassFromName("System", "UInt32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::AesTransform*), "SubByte", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{a});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::AesTransform::Encrypt128
// Il2CppName: Encrypt128
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Security::Cryptography::AesTransform::*)(::Array<uint8_t>*, ::Array<uint8_t>*, ::Array<uint>*)>(&System::Security::Cryptography::AesTransform::Encrypt128)> {
static const MethodInfo* get() {
static auto* indata = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg;
static auto* outdata = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg;
static auto* ekey = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "UInt32"), 1)->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::AesTransform*), "Encrypt128", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{indata, outdata, ekey});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::AesTransform::Decrypt128
// Il2CppName: Decrypt128
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Security::Cryptography::AesTransform::*)(::Array<uint8_t>*, ::Array<uint8_t>*, ::Array<uint>*)>(&System::Security::Cryptography::AesTransform::Decrypt128)> {
static const MethodInfo* get() {
static auto* indata = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg;
static auto* outdata = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg;
static auto* ekey = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "UInt32"), 1)->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::AesTransform*), "Decrypt128", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{indata, outdata, ekey});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::AesTransform::ECB
// Il2CppName: ECB
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Security::Cryptography::AesTransform::*)(::Array<uint8_t>*, ::Array<uint8_t>*)>(&System::Security::Cryptography::AesTransform::ECB)> {
static const MethodInfo* get() {
static auto* input = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg;
static auto* output = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::AesTransform*), "ECB", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{input, output});
}
};
| 59.289474 | 241 | 0.706791 |
73fdb289f3e3b20d509023560c8bc7606bcf8bc1 | 60 | cpp | C++ | src/demo_skia.cpp | jiangkang/renderer-dog | 8081732e2b4dbdb97c8d1f5e23f9e52c6362ff85 | [
"MIT"
] | null | null | null | src/demo_skia.cpp | jiangkang/renderer-dog | 8081732e2b4dbdb97c8d1f5e23f9e52c6362ff85 | [
"MIT"
] | 1 | 2020-09-13T11:08:17.000Z | 2020-09-13T11:08:17.000Z | src/demo_skia.cpp | jiangkang/renderer-dog | 8081732e2b4dbdb97c8d1f5e23f9e52c6362ff85 | [
"MIT"
] | null | null | null | //
// Created by 姜康 on 2020/9/14.
//
void drawBasic(){
}
| 6.666667 | 30 | 0.55 |
73fe6bde5d5525aca9815814dc44113b5550f331 | 10,790 | hxx | C++ | Modules/Filtering/ChangeDetection/include/otbMultivariateAlterationDetectorImageFilter.hxx | kikislater/OTB | 8271c62b5891d3da9cb2e9ba3a2706a26de8c323 | [
"Apache-2.0"
] | null | null | null | Modules/Filtering/ChangeDetection/include/otbMultivariateAlterationDetectorImageFilter.hxx | kikislater/OTB | 8271c62b5891d3da9cb2e9ba3a2706a26de8c323 | [
"Apache-2.0"
] | null | null | null | Modules/Filtering/ChangeDetection/include/otbMultivariateAlterationDetectorImageFilter.hxx | kikislater/OTB | 8271c62b5891d3da9cb2e9ba3a2706a26de8c323 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef otbMultivariateAlterationDetectorImageFilter_hxx
#define otbMultivariateAlterationDetectorImageFilter_hxx
#include "otbMultivariateAlterationDetectorImageFilter.h"
#include "otbMath.h"
#include "vnl/algo/vnl_matrix_inverse.h"
#include "vnl/algo/vnl_generalized_eigensystem.h"
#include "itkImageRegionIterator.h"
#include "itkProgressReporter.h"
namespace otb
{
template <class TInputImage, class TOutputImage>
MultivariateAlterationDetectorImageFilter<TInputImage, TOutputImage>
::MultivariateAlterationDetectorImageFilter()
{
this->SetNumberOfRequiredInputs(2);
m_CovarianceEstimator = CovarianceEstimatorType::New();
}
template <class TInputImage, class TOutputImage>
void
MultivariateAlterationDetectorImageFilter<TInputImage, TOutputImage>
::SetInput1(const TInputImage * image1)
{
// Process object is not const-correct so the const casting is required.
this->SetNthInput(0, const_cast<TInputImage *>(image1));
}
template <class TInputImage, class TOutputImage>
const typename MultivariateAlterationDetectorImageFilter<TInputImage, TOutputImage>
::InputImageType *
MultivariateAlterationDetectorImageFilter<TInputImage, TOutputImage>
::GetInput1()
{
if (this->GetNumberOfInputs() < 1)
{
return nullptr;
}
return static_cast<const TInputImage *>(this->itk::ProcessObject::GetInput(0));
}
template <class TInputImage, class TOutputImage>
void
MultivariateAlterationDetectorImageFilter<TInputImage, TOutputImage>
::SetInput2(const TInputImage * image2)
{
// Process object is not const-correct so the const casting is required.
this->SetNthInput(1, const_cast<TInputImage *>(image2));
}
template <class TInputImage, class TOutputImage>
const typename MultivariateAlterationDetectorImageFilter<TInputImage, TOutputImage>
::InputImageType *
MultivariateAlterationDetectorImageFilter<TInputImage, TOutputImage>
::GetInput2()
{
if (this->GetNumberOfInputs() < 2)
{
return nullptr;
}
return static_cast<const TInputImage *>(this->itk::ProcessObject::GetInput(1));
}
template <class TInputImage, class TOutputImage>
void
MultivariateAlterationDetectorImageFilter<TInputImage, TOutputImage>
::GenerateOutputInformation()
{
// Call superclass implementation
Superclass::GenerateOutputInformation();
// Retrieve input images pointers
const TInputImage * input1Ptr = this->GetInput1();
const TInputImage * input2Ptr = this->GetInput2();
TOutputImage * outputPtr = const_cast<TOutputImage *>(this->GetOutput());
// Get the number of components for each image
unsigned int nbComp1 = input1Ptr->GetNumberOfComponentsPerPixel();
unsigned int nbComp2 = input2Ptr->GetNumberOfComponentsPerPixel();
unsigned int outNbComp = std::max(nbComp1, nbComp2);
outputPtr->SetNumberOfComponentsPerPixel(outNbComp);
if(input1Ptr->GetLargestPossibleRegion() != input2Ptr->GetLargestPossibleRegion())
{
itkExceptionMacro(<<"Input images does not have the same size!");
}
// First concatenate both images
ConcatenateImageFilterPointer concatenateFilter = ConcatenateImageFilterType::New();
concatenateFilter->SetInput1(input1Ptr);
concatenateFilter->SetInput2(input2Ptr);
// The compute covariance matrix
// TODO: implement switch off of this computation
m_CovarianceEstimator->SetInput(concatenateFilter->GetOutput());
m_CovarianceEstimator->Update();
m_CovarianceMatrix = m_CovarianceEstimator->GetCovariance();
m_MeanValues = m_CovarianceEstimator->GetMean();
// Extract sub-matrices of the covariance matrix
VnlMatrixType s11 = m_CovarianceMatrix.GetVnlMatrix().extract(nbComp1, nbComp1);
VnlMatrixType s22 = m_CovarianceMatrix.GetVnlMatrix().extract(nbComp2, nbComp2, nbComp1, nbComp1);
VnlMatrixType s12 = m_CovarianceMatrix.GetVnlMatrix().extract(nbComp1, nbComp2, 0, nbComp1);
VnlMatrixType s21 = s12.transpose();
// Extract means
m_Mean1 = VnlVectorType(nbComp1, 0);
m_Mean2 = VnlVectorType(nbComp2, 0);
for(unsigned int i = 0; i<nbComp1; ++i)
{
m_Mean1[i] = m_MeanValues[i];
}
for(unsigned int i = 0; i<nbComp2; ++i)
{
m_Mean2[i] = m_MeanValues[nbComp1+i];
}
if(nbComp1 == nbComp2)
{
// Case where nbbands1 == nbbands2
VnlMatrixType invs22 = vnl_matrix_inverse<RealType>(s22);
// Build the generalized eigensystem
VnlMatrixType s12s22is21 = s12 * invs22 *s21;
vnl_generalized_eigensystem ges(s12s22is21, s11);
m_V1 = ges.V;
// Compute canonical correlation matrix
m_Rho = ges.D.get_diagonal();
m_Rho = m_Rho.apply(&std::sqrt);
// We do not need to scale v1 since the
// vnl_generalized_eigensystem already gives unit variance
VnlMatrixType invstderr1 = s11.apply(&std::sqrt);
invstderr1 = invstderr1.apply(&InverseValue);
VnlVectorType diag1 = invstderr1.get_diagonal();
invstderr1.fill(0);
invstderr1.set_diagonal(diag1);
VnlMatrixType sign1 = VnlMatrixType(nbComp1, nbComp1, 0);
VnlMatrixType aux4 = invstderr1 * s11 * m_V1;
VnlVectorType aux5 = VnlVectorType(nbComp1, 0);
for(unsigned int i = 0; i < nbComp1; ++i)
{
aux5=aux5 + aux4.get_row(i);
}
sign1.set_diagonal(aux5);
sign1 = sign1.apply(&SignOfValue);
m_V1 = m_V1 * sign1;
m_V2 = invs22*s21*m_V1;
// Scale v2 for unit variance
VnlMatrixType aux1 = m_V2.transpose() * (s22 * m_V2);
VnlVectorType aux2 = aux1.get_diagonal();
aux2 = aux2.apply(&std::sqrt);
aux2 = aux2.apply(&InverseValue);
VnlMatrixType aux3 = VnlMatrixType(aux2.size(), aux2.size(), 0);
aux3.fill(0);
aux3.set_diagonal(aux2);
m_V2 = m_V2 * aux3;
}
else
{
VnlMatrixType sl(nbComp1+nbComp2, nbComp1+nbComp2, 0);
VnlMatrixType sr(nbComp1+nbComp2, nbComp1+nbComp2, 0);
sl.update(s12, 0, nbComp1);
sl.update(s21, nbComp1, 0);
sr.update(s11, 0, 0);
sr.update(s22, nbComp1, nbComp1);
vnl_generalized_eigensystem ges(sl, sr);
VnlMatrixType V = ges.V;
V.fliplr();
m_V1 = V.extract(nbComp1, nbComp1);
m_V2 = V.extract(nbComp2, nbComp2, nbComp1, 0);
m_Rho = ges.D.get_diagonal().flip().extract(std::max(nbComp1, nbComp2), 0);
//Scale v1 to get a unit variance
VnlMatrixType aux1 = m_V1.transpose() * (s11 * m_V1);
VnlVectorType aux2 = aux1.get_diagonal();
aux2 = aux2.apply(&std::sqrt);
aux2 = aux2.apply(&InverseValue);
VnlMatrixType aux3 = VnlMatrixType(aux2.size(), aux2.size(), 0);
aux3.set_diagonal(aux2);
m_V1 = m_V1 * aux3;
VnlMatrixType invstderr1 = s11.apply(&std::sqrt);
invstderr1 = invstderr1.apply(&InverseValue);
VnlVectorType diag1 = invstderr1.get_diagonal();
invstderr1.fill(0);
invstderr1.set_diagonal(diag1);
VnlMatrixType sign1 = VnlMatrixType(nbComp1, nbComp1, 0);
VnlMatrixType aux4 = invstderr1 * s11 * m_V1;
VnlVectorType aux5 = VnlVectorType(nbComp1, 0);
for(unsigned int i = 0; i < nbComp1; ++i)
{
aux5=aux5 + aux4.get_row(i);
}
sign1.set_diagonal(aux5);
sign1 = sign1.apply(&SignOfValue);
m_V1 = m_V1 * sign1;
// Scale v2 for unit variance
aux1 = m_V2.transpose() * (s22 * m_V2);
aux2 = aux1.get_diagonal();
aux2 = aux2.apply(&std::sqrt);
aux2 = aux2.apply(&InverseValue);
aux3 = VnlMatrixType(aux2.size(), aux2.size(), 0);
aux3.fill(0);
aux3.set_diagonal(aux2);
m_V2 = m_V2 * aux3;
VnlMatrixType sign2 = VnlMatrixType(nbComp2, nbComp2, 0);
aux5 = (m_V1.transpose() * s12 * m_V2).transpose().get_diagonal();
sign2.set_diagonal(aux5);
sign2 = sign2.apply(&SignOfValue);
m_V2 = m_V2 * sign2;
}
}
template <class TInputImage, class TOutputImage>
void
MultivariateAlterationDetectorImageFilter<TInputImage, TOutputImage>
::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, itk::ThreadIdType threadId)
{
// Retrieve input images pointers
const TInputImage * input1Ptr = this->GetInput1();
const TInputImage * input2Ptr = this->GetInput2();
TOutputImage * outputPtr = this->GetOutput();
typedef itk::ImageRegionConstIterator<InputImageType> ConstIteratorType;
typedef itk::ImageRegionIterator<OutputImageType> IteratorType;
IteratorType outIt(outputPtr, outputRegionForThread);
ConstIteratorType inIt1(input1Ptr, outputRegionForThread);
ConstIteratorType inIt2(input2Ptr, outputRegionForThread);
inIt1.GoToBegin();
inIt2.GoToBegin();
outIt.GoToBegin();
// Get the number of components for each image
unsigned int nbComp1 = input1Ptr->GetNumberOfComponentsPerPixel();
unsigned int nbComp2 = input2Ptr->GetNumberOfComponentsPerPixel();
unsigned int outNbComp = outputPtr->GetNumberOfComponentsPerPixel();
itk::ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels());
while(!inIt1.IsAtEnd() && !inIt2.IsAtEnd() && !outIt.IsAtEnd())
{
VnlVectorType x1(nbComp1, 0);
VnlVectorType x1bis(outNbComp, 0);
VnlVectorType x2(nbComp2, 0);
VnlVectorType x2bis(outNbComp, 0);
VnlVectorType mad(outNbComp, 0);
for(unsigned int i = 0; i < nbComp1; ++i)
{
x1[i] = inIt1.Get()[i];
}
for(unsigned int i = 0; i < nbComp2; ++i)
{
x2[i] = inIt2.Get()[i];
}
VnlVectorType first = (x1-m_Mean1)*m_V1;
VnlVectorType second = (x2-m_Mean2)*m_V2;
for(unsigned int i = 0; i < nbComp1; ++i)
{
x1bis[i] = first[i];
}
for(unsigned int i = 0; i < nbComp2; ++i)
{
x2bis[i] = second[i];
}
mad = x1bis - x2bis;
typename OutputImageType::PixelType outPixel(outNbComp);
if(nbComp1 == nbComp2)
{
for(unsigned int i = 0; i<outNbComp; ++i)
{
outPixel[i]=mad[i];
}
}
else
{
for(unsigned int i = 0; i<outNbComp; ++i)
{
outPixel[i]=mad[outNbComp - i - 1];
if(i < outNbComp - std::min(nbComp1, nbComp2))
{
outPixel[i]*=std::sqrt(2.);
}
}
}
outIt.Set(outPixel);
++inIt1;
++inIt2;
++outIt;
progress.CompletedPixel();
}
}
}
#endif
| 29.320652 | 102 | 0.702132 |
73ff736684f88a5c01544e52ad77ef76a7ac6a9f | 1,276 | cpp | C++ | Chapter 10. Generic Algorithms/Codes/10.25 Solution.cpp | Yunxiang-Li/Cpp_Primer | b5c857e3f6be993b2ff8fc03f634141ae24925fc | [
"MIT"
] | null | null | null | Chapter 10. Generic Algorithms/Codes/10.25 Solution.cpp | Yunxiang-Li/Cpp_Primer | b5c857e3f6be993b2ff8fc03f634141ae24925fc | [
"MIT"
] | null | null | null | Chapter 10. Generic Algorithms/Codes/10.25 Solution.cpp | Yunxiang-Li/Cpp_Primer | b5c857e3f6be993b2ff8fc03f634141ae24925fc | [
"MIT"
] | 1 | 2021-09-30T14:08:03.000Z | 2021-09-30T14:08:03.000Z | #include <functional>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
void elimdups(std::vector<std::string>& vs)
{
std::sort(vs.begin(), vs.end());
auto new_end = std::unique(vs.begin(), vs.end());
vs.erase(new_end, vs.end());
}
bool check_size(const std::string& s, const std::string::size_type& sz)
{
return s.size() >= sz;
}
void biggies(std::vector<std::string>& vs, std::size_t sz)
{
elimdups(vs);
//! sort by size, but maintain alphabetical order for same size.
std::stable_sort(vs.begin(), vs.end(),
[](std::string const& lhs, std::string const& rhs) {
return lhs.size() < rhs.size();
});
//! get an iterator to the first one whose size() is >= sz
auto wc = std::partition(vs.begin(), vs.end(), std::bind(check_size, std::placeholders::_1, sz));
//! print the biggies
std::for_each(wc, vs.end(), [](const std::string& s) { std::cout << s << " "; });
}
int main()
{
std::vector<std::string> v{"a", "a", "in", "dog", "dog", "drivers", "deliver",
"fridge", "forever", "provide"};
std::cout << "The string which has no duplicates and less than 3 letters are: ";
biggies(v, 3);
std::cout << std::endl;
return 0;
}
| 26.583333 | 99 | 0.582288 |
bab5e503d2d46177aaad2fa52c2a017e0bbe2c66 | 14,755 | cpp | C++ | libEyeRenderer3/libEyeRenderer.cpp | BrainsOnBoard/eye-renderer | 59ae026fcb08e029500d1d0a8f152a37200ba260 | [
"MIT"
] | 2 | 2021-10-07T07:08:47.000Z | 2021-11-02T15:52:14.000Z | libEyeRenderer3/libEyeRenderer.cpp | BrainsOnBoard/eye-renderer | 59ae026fcb08e029500d1d0a8f152a37200ba260 | [
"MIT"
] | 1 | 2021-10-07T09:21:51.000Z | 2021-11-01T21:52:30.000Z | libEyeRenderer3/libEyeRenderer.cpp | BrainsOnBoard/compound-ray | 59ae026fcb08e029500d1d0a8f152a37200ba260 | [
"MIT"
] | 1 | 2021-11-07T12:51:58.000Z | 2021-11-07T12:51:58.000Z | //
// Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#include "libEyeRenderer.h"
#include <glad/glad.h> // Needs to be included before gl_interop
#include <cuda_runtime.h>
#include <cuda_gl_interop.h>
#include <optix.h>
#include <optix_stubs.h>
#include <sampleConfig.h>
#include <cuda/Light.h>
#include <sutil/Camera.h>
#include <sutil/CUDAOutputBuffer.h>
#include <sutil/Exception.h>
#include <sutil/GLDisplay.h>
#include <sutil/Matrix.h>
#include <sutil/sutil.h>
#include <sutil/vec_math.h>
#include "MulticamScene.h"
#include "GlobalParameters.h"
#include "cameras/CompoundEyeDataTypes.h"
#include <GLFW/glfw3.h>
#include <array>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
//#define USE_IAS // WAR for broken direct intersection of GAS on non-RTX cards
#ifdef BUFFER_TYPE_CUDA_DEVICE
#define BUFFER_TYPE 0
#endif
#ifdef BUFFER_TYPE_GL_INTEROP
#define BUFFER_TYPE 1
#endif
#ifdef BUFFER_TYPE_ZERO_COPY
#define BUFFER_TYPE 2
#endif
#ifdef BUFFER_TYPE_CUDA_P2P
#define BUFFER_TYPE 3
#endif
MulticamScene scene;
globalParameters::LaunchParams* d_params = nullptr;
globalParameters::LaunchParams params = {};
int32_t width = 400;
int32_t height = 400;
GLFWwindow* window = sutil::initUI( "Eye Renderer 3.0", width, height );
sutil::CUDAOutputBuffer<uchar4> outputBuffer(static_cast<sutil::CUDAOutputBufferType>(BUFFER_TYPE), width, height);
sutil::GLDisplay gl_display; // Stores the frame buffer to swap in and out
bool notificationsActive = true;
void initLaunchParams( const MulticamScene& scene ) {
params.frame_buffer = nullptr; // Will be set when output buffer is mapped
params.frame = 0;
params.lighting = false;
const float loffset = scene.aabb().maxExtent();
std::vector<Light::Point> lights(4);
lights[0].color = { 1.0f, 1.0f, 0.8f };
lights[0].intensity = 5.0f;
lights[0].position = scene.aabb().center() + make_float3( loffset );
lights[0].falloff = Light::Falloff::QUADRATIC;
lights[1].color = { 0.8f, 0.8f, 1.0f };
lights[1].intensity = 3.0f;
lights[1].position = scene.aabb().center() + make_float3( -loffset, 0.5f*loffset, -0.5f*loffset );
lights[1].falloff = Light::Falloff::QUADRATIC;
lights[2].color = { 1.0f, 1.0f, 0.8f };
lights[2].intensity = 5.0f;
lights[2].position = scene.aabb().center() + make_float3( 0.0f, 4.0f, -5.0f);
lights[2].falloff = Light::Falloff::QUADRATIC;
lights[3].color = { 1.0f, 1.0f, 0.8f };
lights[3].intensity = 0.5f;
lights[3].position = scene.aabb().center() + make_float3( 1.0f, -6.0f, 0.0f);
lights[3].falloff = Light::Falloff::QUADRATIC;
params.lights.count = static_cast<uint32_t>( lights.size() );
CUDA_CHECK( cudaMalloc(
reinterpret_cast<void**>( ¶ms.lights.data ),
lights.size() * sizeof( Light::Point )
) );
CUDA_CHECK( cudaMemcpy(
reinterpret_cast<void*>( params.lights.data ),
lights.data(),
lights.size() * sizeof( Light::Point ),
cudaMemcpyHostToDevice
) );
params.miss_color = make_float3( 0.1f );
//CUDA_CHECK( cudaStreamCreate( &stream ) );
CUDA_CHECK( cudaMalloc( reinterpret_cast<void**>( &d_params ), sizeof( globalParameters::LaunchParams ) ) );
params.handle = scene.traversableHandle();
}
// Updates the params to acurately reflect the currently selected camera
void handleCameraUpdate( globalParameters::LaunchParams& params )
{
//GenericCamera* camera = scene.getCamera();
// Make sure the SBT of the scene is updated for the newly selected camera before launch,
// also push any changed host-side camera SBT data over to the device.
scene.reconfigureSBTforCurrentCamera(false);
}
void launchFrame( sutil::CUDAOutputBuffer<uchar4>& output_buffer, MulticamScene& scene )
{
uchar4* result_buffer_data = output_buffer.map();
params.frame_buffer = result_buffer_data;
CUDA_CHECK( cudaMemcpyAsync( reinterpret_cast<void*>( d_params ),
¶ms,
sizeof( globalParameters::LaunchParams ),
cudaMemcpyHostToDevice,
0 // stream
) );
if(scene.hasCompoundEyes() && scene.isCompoundEyeActive())
{
CompoundEye* camera = (CompoundEye*) scene.getCamera();
// Launch the ommatidial renderer
OPTIX_CHECK( optixLaunch(
scene.compoundPipeline(),
0, // stream
reinterpret_cast<CUdeviceptr>( d_params ),
sizeof( globalParameters::LaunchParams ),
scene.compoundSbt(),
camera->getOmmatidialCount(), // launch width
camera->getSamplesPerOmmatidium(), // launch height
1 // launch depth
) );
CUDA_SYNC_CHECK();
params.frame++;// Increase the frame number
camera->setRandomsAsConfigured();// Make sure that random stream initialization is only ever done once
}
// Launch render
OPTIX_CHECK( optixLaunch(
scene.pipeline(),
0, // stream
reinterpret_cast<CUdeviceptr>( d_params ),
sizeof( globalParameters::LaunchParams ),
scene.sbt(),
width, // launch width
height, // launch height
1//scene.getCamera()->samplesPerPixel // launch depth
) );
output_buffer.unmap();
CUDA_SYNC_CHECK();
}
void cleanup()
{
CUDA_CHECK( cudaFree( reinterpret_cast<void*>( params.lights.data ) ) );
CUDA_CHECK( cudaFree( reinterpret_cast<void*>( d_params ) ) );
scene.cleanup();
}
//------------------------------------------------------------------------------
//
// API functions
//
//------------------------------------------------------------------------------
// General Running
//------------------------------------------------------------------------------
void setVerbosity(bool v)
{
notificationsActive = v;
}
void loadGlTFscene(const char* filepath)
{
loadScene(filepath, scene);
scene.finalize();
initLaunchParams(scene);
}
void setRenderSize(int w, int h)
{
width = w;
height = h;
if(notificationsActive)
std::cout<<"[PyEye] Resizing rendering buffer to ("<<w<<", "<<h<<")."<<std::endl;
outputBuffer.resize(width, height);
}
double renderFrame(void)
{
handleCameraUpdate(params);// Update the params to accurately reflect the currently selected camera
auto then = std::chrono::steady_clock::now();
launchFrame( outputBuffer, scene );
std::chrono::duration<double, std::milli> render_time = std::chrono::steady_clock::now() - then;
if(notificationsActive)
std::cout<<"[PyEye] Rendered frame in "<<render_time.count()<<"ms."<<std::endl;
CUDA_SYNC_CHECK();
return(render_time.count());
}
void displayFrame(void)
{
int framebuf_res_x = 0; // The display's resolution (could be HDPI res)
int framebuf_res_y = 0; //
glfwGetFramebufferSize( window, &framebuf_res_x, &framebuf_res_y );
gl_display.display(
outputBuffer.width(),
outputBuffer.height(),
framebuf_res_x,
framebuf_res_y,
outputBuffer.getPBO()
);
// Swap the buffer
glfwSwapBuffers(window);
}
void saveFrameAs(char* ppmFilename)
{
sutil::ImageBuffer buffer;
buffer.data = outputBuffer.getHostPointer();
buffer.width = outputBuffer.width();
buffer.height = outputBuffer.height();
buffer.pixel_format = sutil::BufferImageFormat::UNSIGNED_BYTE4;
sutil::displayBufferFile(ppmFilename, buffer, false);
if(notificationsActive)
std::cout<<"[PyEye] Saved render as '"<<ppmFilename<<"'"<<std::endl;
}
unsigned char* getFramePointer(void)
{
if(notificationsActive)
std::cout<<"[PyEye] Retrieving frame pointer..."<<std::endl;
return (unsigned char*)outputBuffer.getHostPointer();
}
void getFrame(unsigned char* frame)
{
if(notificationsActive)
std::cout<<"[PyEye] Retrieving frame..."<<std::endl;
size_t displaySize = outputBuffer.width()*outputBuffer.height();
for(size_t i = 0; i<displaySize; i++)
{
unsigned char val = (unsigned char)(((float)i/(float)displaySize)*254);
frame[displaySize*3 + 0] = val;
frame[displaySize*3 + 1] = val;
frame[displaySize*3 + 2] = val;
}
}
void stop(void)
{
if(notificationsActive)
std::cout<<"[PyEye] Cleaning eye renderer resources."<<std::endl;
sutil::cleanupUI(window);
cleanup();
}
// C-level only
void * getWindowPointer()
{
return (void*)window;
}
//------------------------------------------------------------------------------
// Camera Control
//------------------------------------------------------------------------------
size_t getCameraCount()
{
return(scene.getCameraCount());
}
void nextCamera(void)
{
scene.nextCamera();
}
size_t getCurrentCameraIndex(void)
{
return(scene.getCameraIndex());
}
const char* getCurrentCameraName(void)
{
return(scene.getCamera()->getCameraName());
}
void previousCamera(void)
{
scene.previousCamera();
}
void gotoCamera(int index)
{
scene.setCurrentCamera(index);
}
bool gotoCameraByName(char* name)
{
scene.setCurrentCamera(0);
for(auto i = 0; i<scene.getCameraCount(); i++)
{
if(strcmp(name, scene.getCamera()->getCameraName()) == 0)
return true;
scene.nextCamera();
}
return false;
}
void setCameraPosition(float x, float y, float z)
{
scene.getCamera()->setPosition(make_float3(x,y,z));
}
void getCameraPosition(float& x, float& y, float& z)
{
const float3& camPos = scene.getCamera()->getPosition();
x = camPos.x;
y = camPos.y;
z = camPos.z;
}
void setCameraLocalSpace(float lxx, float lxy, float lxz,
float lyx, float lyy, float lyz,
float lzx, float lzy, float lzz)
{
scene.getCamera()->setLocalSpace(make_float3(lxx, lxy, lxz),
make_float3(lyx, lyy, lyz),
make_float3(lzx, lzy, lzz));
}
void rotateCameraAround(float angle, float x, float y, float z)
{
scene.getCamera()->rotateAround(angle, make_float3(x,y,z));
}
void rotateCameraLocallyAround(float angle, float x, float y, float z)
{
scene.getCamera()->rotateLocallyAround(angle, make_float3(x,y,z));
}
void translateCamera(float x, float y, float z)
{
scene.getCamera()->move(make_float3(x, y, z));
}
void translateCameraLocally(float x, float y, float z)
{
scene.getCamera()->moveLocally(make_float3(x, y, z));
}
void resetCameraPose()
{
scene.getCamera()->resetPose();
}
void setCameraPose(float posX, float posY, float posZ, float rotX, float rotY, float rotZ)
{
GenericCamera* c = scene.getCamera();
c->resetPose();
c->rotateAround(rotX, make_float3(1,0,0));
c->rotateAround(rotY, make_float3(0,1,0));
c->rotateAround(rotZ, make_float3(0,0,1));
c->move(make_float3(posX, posY, posZ));
}
//------------------------------------------------------------------------------
// Ommatidial Camera Control
//------------------------------------------------------------------------------
bool isCompoundEyeActive(void)
{
return scene.isCompoundEyeActive();
}
void setCurrentEyeSamplesPerOmmatidium(int s)
{
if(scene.isCompoundEyeActive())
{
((CompoundEye*)scene.getCamera())->setSamplesPerOmmatidium(s);
}
}
int getCurrentEyeSamplesPerOmmatidium(void)
{
if(scene.isCompoundEyeActive())
{
return(((CompoundEye*)scene.getCamera())->getSamplesPerOmmatidium());
}
return -1;
}
void changeCurrentEyeSamplesPerOmmatidiumBy(int s)
{
if(scene.isCompoundEyeActive())
{
((CompoundEye*)scene.getCamera())->changeSamplesPerOmmatidiumBy(s);
}
}
size_t getCurrentEyeOmmatidialCount(void)
{
if(scene.isCompoundEyeActive())
{
return ((CompoundEye*)scene.getCamera())->getOmmatidialCount();
}
return 0;
}
void setOmmatidia(OmmatidiumPacket* omms, size_t count)
{
// Break out if the current eye isn't compound
if(!scene.isCompoundEyeActive())
return;
// First convert the OmmatidiumPacket list into an array of Ommatidium objects
Ommatidium ommObjectArray[count];
for(size_t i = 0; i<count; i++)
{
OmmatidiumPacket& omm = omms[i];
ommObjectArray[i].relativePosition = make_float3(omm.posX, omm.posY, omm.posZ);
ommObjectArray[i].relativeDirection = make_float3(omm.dirX, omm.dirY, omm.dirZ);
ommObjectArray[i].acceptanceAngleRadians = omm.acceptanceAngle;
ommObjectArray[i].focalPointOffset = omm.focalpointOffset;
}
// Actually set the new ommatidial structure
((CompoundEye*)scene.getCamera())->setOmmatidia(ommObjectArray, count);
}
const char* getCurrentEyeDataPath(void)
{
if(scene.isCompoundEyeActive())
{
return ((CompoundEye*)scene.getCamera())->eyeDataPath.c_str();
}
return "\0";
}
void setCurrentEyeShaderName(char* name)
{
if(scene.isCompoundEyeActive())
{
((CompoundEye*)scene.getCamera())->setShaderName(std::string(name)); // Set the shader
scene.reconfigureSBTforCurrentCamera(true); // Reconfigure for the new shader
}
}
| 32.006508 | 115 | 0.648729 |
bab68c309a9f3d41e60621cdfe3bc50336058c3e | 722 | cpp | C++ | ArithmeticEvalulator/HedronLoggerTestBranch/TokenType.cpp | Gabriel-Baril/arithmetic-evaluator | 171acdbf5ebde61b486833f64c8e1d48e5816540 | [
"Apache-2.0"
] | null | null | null | ArithmeticEvalulator/HedronLoggerTestBranch/TokenType.cpp | Gabriel-Baril/arithmetic-evaluator | 171acdbf5ebde61b486833f64c8e1d48e5816540 | [
"Apache-2.0"
] | null | null | null | ArithmeticEvalulator/HedronLoggerTestBranch/TokenType.cpp | Gabriel-Baril/arithmetic-evaluator | 171acdbf5ebde61b486833f64c8e1d48e5816540 | [
"Apache-2.0"
] | null | null | null | #include "TokenType.hpp"
void print_token_type(const token_type& type)
{
switch (type)
{
case token_type::null:
std::cout << "NULL" << std::endl;
break;
case token_type::text:
std::cout << "TEXT" << std::endl;
break;
case token_type::number:
std::cout << "NUMBER" << std::endl;
break;
case token_type::op:
std::cout << "OPERATOR" << std::endl;
break;
case token_type::opening_parenthesis:
std::cout << "OPENING_PARENTHESIS" << std::endl;
break;
case token_type::closing_parenthesis:
std::cout << "CLOSING_PARENTHESIS" << std::endl;
break;
case token_type::arg_separator:
std::cout << "ARGUMENT_PARENTHESIS" << std::endl;
break;
default:
std::cout << "UNDEFINED" << std::endl;
}
}
| 22.5625 | 51 | 0.65928 |
bab69c1c253d0c7dcf56aa04f811fd66d57a5f66 | 245 | hpp | C++ | uart/Uart.hpp | PhischDotOrg/phisch-lib | 26df59d78533d3220a46e077ead5a5180a84d57a | [
"MIT"
] | null | null | null | uart/Uart.hpp | PhischDotOrg/phisch-lib | 26df59d78533d3220a46e077ead5a5180a84d57a | [
"MIT"
] | null | null | null | uart/Uart.hpp | PhischDotOrg/phisch-lib | 26df59d78533d3220a46e077ead5a5180a84d57a | [
"MIT"
] | null | null | null | /*-
* $Copyright$
-*/
#ifndef __UART_HPP_ba3914c2_b82e_482b_ad80_f21cfb95d989
#define __UART_HPP_ba3914c2_b82e_482b_ad80_f21cfb95d989
namespace uart {
}; /* namespace uart */
#endif /* __UART_HPP_ba3914c2_b82e_482b_ad80_f21cfb95d989 */
| 18.846154 | 60 | 0.787755 |
bab82fb7a332e5c5b9ffc499aa0971e477ba5a05 | 4,130 | hpp | C++ | northstar/include/driver/Optics.hpp | BryanChrisBrown/project_northstar_openvr_driver | cf16e98e24804aee699805dca766b8153f4e52e5 | [
"Unlicense"
] | null | null | null | northstar/include/driver/Optics.hpp | BryanChrisBrown/project_northstar_openvr_driver | cf16e98e24804aee699805dca766b8153f4e52e5 | [
"Unlicense"
] | null | null | null | northstar/include/driver/Optics.hpp | BryanChrisBrown/project_northstar_openvr_driver | cf16e98e24804aee699805dca766b8153f4e52e5 | [
"Unlicense"
] | null | null | null | #pragma once
#include "driver/IOptics.hpp"
#include "math/Types.hpp"
#include "math/IVectorFactory.hpp"
#include "math/IMatrixFactory.hpp"
#include "math/IGeometry.hpp"
#include "math/ISpaceAdapter.hpp"
#include "math/IWorldAdapter.hpp"
#include "openvr_driver.h"
#include "driver/Settings.hpp"
#include "utility/ILogger.hpp"
#include <memory>
namespace northstar {
namespace driver {
class COptics : public IOptics {
public:
COptics(
vr::IVRSettings* pVRSettings,
std::shared_ptr<northstar::math::IWorldAdapter> pWorldAdapter,
std::shared_ptr<northstar::math::ISpaceAdapter> pSpaceAdapter,
std::shared_ptr<northstar::math::IGeometry> pGeometry,
std::shared_ptr<northstar::math::IMatrixFactory> pMatrixFactory,
std::shared_ptr<northstar::math::IVectorFactory> pVectorFactory,
std::shared_ptr<northstar::utility::ILogger> pLogger);
virtual northstar::math::types::Vector2d EyeUVToScreenUV(const vr::EVREye& eEye, const northstar::math::types::Vector2d& v2dEyeUV) override final;
virtual northstar::math::types::Vector4d GetEyeProjectionLRTB(const vr::EVREye& eEye) override final;
private:
static constexpr size_t x_nNumberOfSolverIterations = 7;
static constexpr std::array<double, 2> x_daInitialWarpGuess = { 0.5, 0.5 };
static constexpr std::array<double, 2> x_daIterativeSolverErrorResult = { 0.0, 0.0 };
static constexpr std::array<double, 3> x_daLensProxySphereOrigin = { 0.0, 0.0, 0.0 };
static constexpr double x_dLensProxySphereRadius = 0.5;
static constexpr double x_dIterativeSolverGradiantEpsilon = 0.0001;
static constexpr double x_dIterativeSolverStepWeight = 1.0 / 7.0;
struct SEllipsisAxis {
double dMinor;
double dMajor;
};
struct SEyeConfiguration {
SEllipsisAxis sEllipsisAxis = { 0 };
northstar::math::types::Vector3d v3dScreenForward;
northstar::math::types::Vector3d v3dScreenPosition;
northstar::math::types::Vector3d v3dEyePosition;
northstar::math::types::Quaterniond qdEyeRotation;
northstar::math::types::Vector4d v4dCameraProjectionFrustumExtentsLRTB;
northstar::math::types::AffineMatrix4d m4dSphereToWorldSpace;
northstar::math::types::AffineMatrix4d m4dWorldToScreenSpace;
northstar::math::types::AffineMatrix4d m4dWorldToSphereSpace;
northstar::math::types::ProjMatrix4d m4dCameraProjection;
northstar::math::types::ProjMatrix4d m4dClipToWorld;
};
typedef std::unordered_map<
northstar::math::types::Vector2d,
northstar::math::types::Vector2d,
northstar::math::types::SHasher<northstar::math::types::Vector2d>> UVWarpMap;
SEyeConfiguration LoadConfigFromEye(const vr::EVREye& eEye);
northstar::math::types::Vector2d ReverseProjectEyeUVToDisplayUV(const vr::EVREye& eEye, const northstar::math::types::Vector2d& v2dTargetEyeUV);
northstar::math::types::Vector2d IterativeGradientUVWarpSolve(const vr::EVREye& eEye, const northstar::math::types::Vector2d& v2dEyeUV, const northstar::math::types::Vector2d& v2dWarpUVGuess);
vr::IVRSettings* m_pVRSettings;
std::shared_ptr<northstar::math::IVectorFactory> m_pVectorFactory;
std::shared_ptr<northstar::math::IMatrixFactory> m_pMatrixFactory;
std::shared_ptr<northstar::math::IGeometry> m_pGeometry;
std::shared_ptr<northstar::math::IWorldAdapter> m_pWorldAdapter;
std::shared_ptr<northstar::math::ISpaceAdapter> m_pSpaceAdapter;
std::shared_ptr<northstar::utility::ILogger> m_pLogger;
std::unordered_map<vr::EVREye, SEyeConfiguration> m_umEyeConfigs;
std::unordered_map<vr::EVREye, UVWarpMap> m_umUVWarps;
};
}
}
| 51.625 | 204 | 0.659806 |
bab91f654799f7d5ca85465bc1a9a0f5e5a9500d | 3,461 | cpp | C++ | base/cluster/mgmt/cluscfg/wizard/namedcookie.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | base/cluster/mgmt/cluscfg/wizard/namedcookie.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | base/cluster/mgmt/cluscfg/wizard/namedcookie.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2001 Microsoft Corporation
//
// Module Name:
// NamedCookie.cpp
//
// Description:
// This file contains the definition of the SNamedCookie struct.
//
// Maintained By:
// John Franco (jfranco) 23-AUG-2001
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// Include Files
//////////////////////////////////////////////////////////////////////////////
#include "Pch.h"
#include "NamedCookie.h"
//////////////////////////////////////////////////////////////////////////////
// Constant Definitions
//////////////////////////////////////////////////////////////////////////////
DEFINE_THISCLASS( "SNamedCookie" );
//*************************************************************************//
/////////////////////////////////////////////////////////////////////////////
// SNamedCookie struct
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//++
//
// SNamedCookie::SNamedCookie
//
// Description:
//
// Arguments:
// None.
//
// Return Values:
// None.
//
// Remarks:
//
//--
//////////////////////////////////////////////////////////////////////////////
SNamedCookie::SNamedCookie():
bstrName( NULL )
, ocObject( 0 )
, punkObject( NULL )
{
TraceFunc( "" );
TraceFuncExit();
}
//////////////////////////////////////////////////////////////////////////////
//++
//
// SNamedCookie::~SNamedCookie
//
// Description:
//
// Arguments:
// None.
//
// Return Values:
// None.
//
// Remarks:
//
//--
//////////////////////////////////////////////////////////////////////////////
SNamedCookie::~SNamedCookie()
{
TraceFunc( "" );
Erase();
TraceFuncExit();
}
//////////////////////////////////////////////////////////////////////////////
//++
//
// SNamedCookie::HrAssign
//
// Description:
//
// Arguments:
// crSourceIn
//
// Return Values:
// S_OK
// E_OUTOFMEMORY
//
// Remarks:
//
//--
//////////////////////////////////////////////////////////////////////////////
HRESULT SNamedCookie::HrAssign( const SNamedCookie& crSourceIn )
{
TraceFunc( "" );
HRESULT hr = S_OK;
if ( this != &crSourceIn )
{
BSTR bstrNameCache = NULL;
if ( crSourceIn.bstrName != NULL )
{
bstrNameCache = TraceSysAllocString( crSourceIn.bstrName );
if ( bstrNameCache == NULL )
{
hr = E_OUTOFMEMORY;
goto Cleanup;
}
}
if ( bstrName != NULL )
{
TraceSysFreeString( bstrName );
}
bstrName = bstrNameCache;
bstrNameCache = NULL;
if ( punkObject != NULL )
{
punkObject->Release();
}
punkObject = crSourceIn.punkObject;
if ( punkObject != NULL )
{
punkObject->AddRef();
}
ocObject = crSourceIn.ocObject;
Cleanup:
TraceSysFreeString( bstrNameCache );
}
HRETURN( hr );
} //*** SNamedCookie::HrAssign
| 22.474026 | 79 | 0.324762 |
babcc15f3399c374704c2c2861c1e0010c6fee50 | 30,051 | cpp | C++ | layer/dispatch.cpp | jpark37/Fossilize | 4af65358c66a032ddb500df3341788277e32d56a | [
"MIT"
] | null | null | null | layer/dispatch.cpp | jpark37/Fossilize | 4af65358c66a032ddb500df3341788277e32d56a | [
"MIT"
] | null | null | null | layer/dispatch.cpp | jpark37/Fossilize | 4af65358c66a032ddb500df3341788277e32d56a | [
"MIT"
] | null | null | null | /* Copyright (c) 2018 Hans-Kristian Arntzen
*
* 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.
*/
#define VK_NO_PROTOTYPES // VALVE: So that vulkan_core.h definitions lacking dllexport don't conflict with our exported functions
#include "dispatch_helper.hpp"
#include "utils.hpp"
#include "device.hpp"
#include "instance.hpp"
#include "fossilize_errors.hpp"
#include <mutex>
// VALVE: do exports without .def file, see vk_layer.h for definition on non-Windows platforms
#ifdef _MSC_VER
#if defined(_WIN32) && !defined(_WIN64)
// Josh: We need to match the export names up to the functions to avoid stdcall aliasing
#pragma comment(linker, "/EXPORT:VK_LAYER_fossilize_GetInstanceProcAddr=_VK_LAYER_fossilize_GetInstanceProcAddr@8")
#pragma comment(linker, "/EXPORT:VK_LAYER_fossilize_GetDeviceProcAddr=_VK_LAYER_fossilize_GetDeviceProcAddr@8")
#endif
#undef VK_LAYER_EXPORT
#define VK_LAYER_EXPORT extern "C" __declspec(dllexport)
#endif
extern "C"
{
#ifdef ANDROID
#define VK_LAYER_fossilize_GetInstanceProcAddr vkGetInstanceProcAddr
#define VK_LAYER_fossilize_GetDeviceProcAddr vkGetDeviceProcAddr
#endif
VK_LAYER_EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL VK_LAYER_fossilize_GetInstanceProcAddr(VkInstance instance, const char *pName);
VK_LAYER_EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL VK_LAYER_fossilize_GetDeviceProcAddr(VkDevice device, const char *pName);
}
using namespace std;
namespace Fossilize
{
// Global data structures to remap VkInstance and VkDevice to internal data structures.
static mutex globalLock;
static InstanceTable instanceDispatch;
static DeviceTable deviceDispatch;
static unordered_map<void *, unique_ptr<Instance>> instanceData;
static unordered_map<void *, unique_ptr<Device>> deviceData;
static Device *get_device_layer(VkDevice device)
{
// Need to hold a lock while querying the global hashmap, but not after it.
Device *layer = nullptr;
void *key = getDispatchKey(device);
lock_guard<mutex> holder{ globalLock };
layer = getLayerData(key, deviceData);
return layer;
}
static Instance *get_instance_layer(VkPhysicalDevice gpu)
{
lock_guard<mutex> holder{ globalLock };
return getLayerData(getDispatchKey(gpu), instanceData);
}
static VKAPI_ATTR VkResult VKAPI_CALL CreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkDevice *pDevice)
{
auto *layer = get_instance_layer(gpu);
auto *chainInfo = getChainInfo(pCreateInfo, VK_LAYER_LINK_INFO);
auto fpGetInstanceProcAddr = chainInfo->u.pLayerInfo->pfnNextGetInstanceProcAddr;
auto fpGetDeviceProcAddr = chainInfo->u.pLayerInfo->pfnNextGetDeviceProcAddr;
auto fpCreateDevice =
reinterpret_cast<PFN_vkCreateDevice>(fpGetInstanceProcAddr(layer->getInstance(), "vkCreateDevice"));
if (!fpCreateDevice)
return VK_ERROR_INITIALIZATION_FAILED;
// Advance the link info for the next element on the chain
chainInfo->u.pLayerInfo = chainInfo->u.pLayerInfo->pNext;
auto res = fpCreateDevice(gpu, pCreateInfo, pAllocator, pDevice);
if (res != VK_SUCCESS)
return res;
// Build a physical device features 2 struct if we cannot find it in pCreateInfo.
auto *pdf2 = static_cast<const VkPhysicalDeviceFeatures2 *>(findpNext(pCreateInfo, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2));
VkPhysicalDeviceFeatures2 physicalDeviceFeatures2 = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2 };
if (!pdf2)
{
pdf2 = &physicalDeviceFeatures2;
if (pCreateInfo->pEnabledFeatures)
physicalDeviceFeatures2.features = *pCreateInfo->pEnabledFeatures;
}
{
lock_guard<mutex> holder{globalLock};
auto *device = createLayerData(getDispatchKey(*pDevice), deviceData);
device->init(gpu, *pDevice, layer, *pdf2, initDeviceTable(*pDevice, fpGetDeviceProcAddr, deviceDispatch));
}
return VK_SUCCESS;
}
static VKAPI_ATTR VkResult VKAPI_CALL CreateInstance(const VkInstanceCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkInstance *pInstance)
{
auto *chainInfo = getChainInfo(pCreateInfo, VK_LAYER_LINK_INFO);
auto fpGetInstanceProcAddr = chainInfo->u.pLayerInfo->pfnNextGetInstanceProcAddr;
auto fpCreateInstance = reinterpret_cast<PFN_vkCreateInstance>(fpGetInstanceProcAddr(nullptr, "vkCreateInstance"));
if (!fpCreateInstance)
return VK_ERROR_INITIALIZATION_FAILED;
chainInfo->u.pLayerInfo = chainInfo->u.pLayerInfo->pNext;
auto res = fpCreateInstance(pCreateInfo, pAllocator, pInstance);
if (res != VK_SUCCESS)
return res;
{
lock_guard<mutex> holder{globalLock};
auto *layer = createLayerData(getDispatchKey(*pInstance), instanceData);
layer->init(*pInstance, pCreateInfo->pApplicationInfo,
initInstanceTable(*pInstance, fpGetInstanceProcAddr, instanceDispatch), fpGetInstanceProcAddr);
}
return VK_SUCCESS;
}
static VKAPI_ATTR void VKAPI_CALL DestroyInstance(VkInstance instance, const VkAllocationCallbacks *pAllocator)
{
lock_guard<mutex> holder{ globalLock };
void *key = getDispatchKey(instance);
auto *layer = getLayerData(key, instanceData);
layer->getTable()->DestroyInstance(instance, pAllocator);
destroyLayerData(key, instanceData);
}
static VKAPI_ATTR VkResult VKAPI_CALL CreateGraphicsPipelinesNormal(Device *layer,
VkDevice device, VkPipelineCache pipelineCache,
uint32_t createInfoCount,
const VkGraphicsPipelineCreateInfo *pCreateInfos,
const VkAllocationCallbacks *pAllocator,
VkPipeline *pPipelines)
{
// Have to create all pipelines here, in case the application makes use of basePipelineIndex.
auto res = layer->getTable()->CreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos, pAllocator, pPipelines);
if (res < 0)
return res;
for (uint32_t i = 0; i < createInfoCount; i++)
{
if (!layer->getRecorder().record_graphics_pipeline(pPipelines[i], pCreateInfos[i], pPipelines, createInfoCount))
LOGW_LEVEL("Recording graphics pipeline failed, usually caused by unsupported pNext.\n");
}
return res;
}
static VKAPI_ATTR VkResult VKAPI_CALL CreateGraphicsPipelinesParanoid(Device *layer,
VkDevice device, VkPipelineCache pipelineCache,
uint32_t createInfoCount,
const VkGraphicsPipelineCreateInfo *pCreateInfos,
const VkAllocationCallbacks *pAllocator,
VkPipeline *pPipelines)
{
for (uint32_t i = 0; i < createInfoCount; i++)
{
// Fixup base pipeline index since we unroll the Create call.
auto info = pCreateInfos[i];
if ((info.flags & VK_PIPELINE_CREATE_DERIVATIVE_BIT) != 0 &&
info.basePipelineHandle == VK_NULL_HANDLE &&
info.basePipelineIndex >= 0)
{
info.basePipelineHandle = pPipelines[info.basePipelineIndex];
info.basePipelineIndex = -1;
}
bool eager = layer->getInstance()->capturesEagerly();
if (eager && !layer->getRecorder().record_graphics_pipeline(VK_NULL_HANDLE, info, nullptr, 0))
LOGW_LEVEL("Failed to capture eagerly.\n");
// Have to create all pipelines here, in case the application makes use of basePipelineIndex.
// Write arguments in TLS in-case we crash here.
Instance::braceForGraphicsPipelineCrash(&layer->getRecorder(), &info);
auto res = layer->getTable()->CreateGraphicsPipelines(device, pipelineCache, 1, &info,
pAllocator, &pPipelines[i]);
Instance::completedPipelineCompilation();
// Record failing pipelines for repro.
if (!layer->getRecorder().record_graphics_pipeline(res == VK_SUCCESS ? pPipelines[i] : VK_NULL_HANDLE, info, nullptr, 0))
LOGW_LEVEL("Failed to record graphics pipeline, usually caused by unsupported pNext.\n");
// FIXME: Unsure how to deal with divergent success codes.
if (res < 0)
{
for (uint32_t j = 0; j < i; j++)
layer->getTable()->DestroyPipeline(device, pPipelines[j], pAllocator);
return res;
}
}
return VK_SUCCESS;
}
static VKAPI_ATTR VkResult VKAPI_CALL CreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache,
uint32_t createInfoCount,
const VkGraphicsPipelineCreateInfo *pCreateInfos,
const VkAllocationCallbacks *pAllocator,
VkPipeline *pPipelines)
{
auto *layer = get_device_layer(device);
if (layer->getInstance()->capturesParanoid())
return CreateGraphicsPipelinesParanoid(layer, device, pipelineCache, createInfoCount, pCreateInfos, pAllocator, pPipelines);
else
return CreateGraphicsPipelinesNormal(layer, device, pipelineCache, createInfoCount, pCreateInfos, pAllocator, pPipelines);
}
static VKAPI_ATTR VkResult VKAPI_CALL CreateComputePipelinesNormal(Device *layer,
VkDevice device, VkPipelineCache pipelineCache,
uint32_t createInfoCount,
const VkComputePipelineCreateInfo *pCreateInfos,
const VkAllocationCallbacks *pAllocator,
VkPipeline *pPipelines)
{
// Have to create all pipelines here, in case the application makes use of basePipelineIndex.
auto res = layer->getTable()->CreateComputePipelines(device, pipelineCache, createInfoCount, pCreateInfos, pAllocator, pPipelines);
if (res < 0)
return res;
for (uint32_t i = 0; i < createInfoCount; i++)
{
if (!layer->getRecorder().record_compute_pipeline(pPipelines[i], pCreateInfos[i], pPipelines, createInfoCount))
LOGW_LEVEL("Failed to record compute pipeline, usually caused by unsupported pNext.\n");
}
return res;
}
static VKAPI_ATTR VkResult VKAPI_CALL CreateComputePipelinesParanoid(Device *layer,
VkDevice device, VkPipelineCache pipelineCache,
uint32_t createInfoCount,
const VkComputePipelineCreateInfo *pCreateInfos,
const VkAllocationCallbacks *pAllocator,
VkPipeline *pPipelines)
{
for (uint32_t i = 0; i < createInfoCount; i++)
{
// Fixup base pipeline index since we unroll the Create call.
auto info = pCreateInfos[i];
if ((info.flags & VK_PIPELINE_CREATE_DERIVATIVE_BIT) != 0 &&
info.basePipelineHandle == VK_NULL_HANDLE &&
info.basePipelineIndex >= 0)
{
info.basePipelineHandle = pPipelines[info.basePipelineIndex];
info.basePipelineIndex = -1;
}
bool eager = layer->getInstance()->capturesEagerly();
if (eager && !layer->getRecorder().record_compute_pipeline(VK_NULL_HANDLE, info, nullptr, 0))
LOGW_LEVEL("Failed to capture eagerly.\n");
// Have to create all pipelines here, in case the application makes use of basePipelineIndex.
// Write arguments in TLS in-case we crash here.
Instance::braceForComputePipelineCrash(&layer->getRecorder(), &info);
auto res = layer->getTable()->CreateComputePipelines(device, pipelineCache, 1, &info,
pAllocator, &pPipelines[i]);
Instance::completedPipelineCompilation();
// Record failing pipelines for repro.
if (!layer->getRecorder().record_compute_pipeline(res == VK_SUCCESS ? pPipelines[i] : VK_NULL_HANDLE, info, nullptr, 0))
LOGW_LEVEL("Failed to record compute pipeline, usually caused by unsupported pNext.\n");
// FIXME: Unsure how to deal with divergent success codes.
if (res < 0)
{
for (uint32_t j = 0; j < i; j++)
layer->getTable()->DestroyPipeline(device, pPipelines[j], pAllocator);
return res;
}
}
return VK_SUCCESS;
}
static VKAPI_ATTR VkResult VKAPI_CALL CreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache,
uint32_t createInfoCount,
const VkComputePipelineCreateInfo *pCreateInfos,
const VkAllocationCallbacks *pAllocator,
VkPipeline *pPipelines)
{
auto *layer = get_device_layer(device);
if (layer->getInstance()->capturesParanoid())
return CreateComputePipelinesParanoid(layer, device, pipelineCache, createInfoCount, pCreateInfos, pAllocator, pPipelines);
else
return CreateComputePipelinesNormal(layer, device, pipelineCache, createInfoCount, pCreateInfos, pAllocator, pPipelines);
}
static VKAPI_ATTR VkResult VKAPI_CALL CreateRayTracingPipelinesNormal(Device *layer,
VkDevice device, VkDeferredOperationKHR deferredOperation,
VkPipelineCache pipelineCache,
uint32_t createInfoCount,
const VkRayTracingPipelineCreateInfoKHR *pCreateInfos,
const VkAllocationCallbacks *pAllocator,
VkPipeline *pPipelines)
{
// Have to create all pipelines here, in case the application makes use of basePipelineIndex.
auto res = layer->getTable()->CreateRayTracingPipelinesKHR(
device, deferredOperation, pipelineCache,
createInfoCount, pCreateInfos, pAllocator, pPipelines);
if (res < 0)
return res;
for (uint32_t i = 0; i < createInfoCount; i++)
{
if (!layer->getRecorder().record_raytracing_pipeline(pPipelines[i], pCreateInfos[i], pPipelines, createInfoCount))
LOGW_LEVEL("Failed to record compute pipeline, usually caused by unsupported pNext.\n");
}
return res;
}
static VKAPI_ATTR VkResult VKAPI_CALL CreateRayTracingPipelinesParanoid(Device *layer,
VkDevice device, VkDeferredOperationKHR deferredOperation,
VkPipelineCache pipelineCache,
uint32_t createInfoCount,
const VkRayTracingPipelineCreateInfoKHR *pCreateInfos,
const VkAllocationCallbacks *pAllocator,
VkPipeline *pPipelines)
{
for (uint32_t i = 0; i < createInfoCount; i++)
{
// Fixup base pipeline index since we unroll the Create call.
auto info = pCreateInfos[i];
if ((info.flags & VK_PIPELINE_CREATE_DERIVATIVE_BIT) != 0 &&
info.basePipelineHandle == VK_NULL_HANDLE &&
info.basePipelineIndex >= 0)
{
info.basePipelineHandle = pPipelines[info.basePipelineIndex];
info.basePipelineIndex = -1;
}
bool eager = layer->getInstance()->capturesEagerly();
if (eager && !layer->getRecorder().record_raytracing_pipeline(VK_NULL_HANDLE, info, nullptr, 0))
LOGW_LEVEL("Failed to capture eagerly.\n");
// Have to create all pipelines here, in case the application makes use of basePipelineIndex.
// Write arguments in TLS in-case we crash here.
Instance::braceForRayTracingPipelineCrash(&layer->getRecorder(), &info);
// FIXME: Can we meaningfully deal with deferredOperation here?
auto res = layer->getTable()->CreateRayTracingPipelinesKHR(device, deferredOperation, pipelineCache, 1, &info,
pAllocator, &pPipelines[i]);
Instance::completedPipelineCompilation();
// Record failing pipelines for repro.
if (!layer->getRecorder().record_raytracing_pipeline(res == VK_SUCCESS ? pPipelines[i] : VK_NULL_HANDLE, info, nullptr, 0))
LOGW_LEVEL("Failed to record compute pipeline, usually caused by unsupported pNext.\n");
// FIXME: Unsure how to deal with divergent success codes.
if (res < 0)
{
for (uint32_t j = 0; j < i; j++)
layer->getTable()->DestroyPipeline(device, pPipelines[j], pAllocator);
return res;
}
}
return VK_SUCCESS;
}
static VKAPI_ATTR VkResult VKAPI_CALL CreateRayTracingPipelinesKHR(
VkDevice device, VkDeferredOperationKHR deferredOperation,
VkPipelineCache pipelineCache, uint32_t createInfoCount,
const VkRayTracingPipelineCreateInfoKHR *pCreateInfos,
const VkAllocationCallbacks *pAllocator,
VkPipeline *pPipelines)
{
auto *layer = get_device_layer(device);
if (layer->getInstance()->capturesParanoid())
{
return CreateRayTracingPipelinesParanoid(layer, device, deferredOperation, pipelineCache,
createInfoCount, pCreateInfos, pAllocator, pPipelines);
}
else
{
return CreateRayTracingPipelinesNormal(layer, device, deferredOperation, pipelineCache,
createInfoCount, pCreateInfos, pAllocator, pPipelines);
}
}
static VKAPI_ATTR VkResult VKAPI_CALL CreatePipelineLayout(VkDevice device,
const VkPipelineLayoutCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator,
VkPipelineLayout *pLayout)
{
auto *layer = get_device_layer(device);
VkResult result = layer->getTable()->CreatePipelineLayout(device, pCreateInfo, pAllocator, pLayout);
if (result == VK_SUCCESS)
{
if (!layer->getRecorder().record_pipeline_layout(*pLayout, *pCreateInfo))
LOGW_LEVEL("Failed to record pipeline layout, usually caused by unsupported pNext.\n");
}
return result;
}
static VKAPI_ATTR VkResult VKAPI_CALL CreateDescriptorSetLayout(VkDevice device,
const VkDescriptorSetLayoutCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator,
VkDescriptorSetLayout *pSetLayout)
{
auto *layer = get_device_layer(device);
VkResult result = layer->getTable()->CreateDescriptorSetLayout(device, pCreateInfo, pAllocator, pSetLayout);
// No point in recording a host only layout since we will never be able to use it in a pipeline layout.
if (result == VK_SUCCESS && (pCreateInfo->flags & VK_DESCRIPTOR_SET_LAYOUT_CREATE_HOST_ONLY_POOL_BIT_VALVE) == 0)
{
if (!layer->getRecorder().record_descriptor_set_layout(*pSetLayout, *pCreateInfo))
LOGW_LEVEL("Failed to record descriptor set layout, usually caused by unsupported pNext.\n");
}
return result;
}
static PFN_vkVoidFunction interceptCoreInstanceCommand(const char *pName)
{
static const struct
{
const char *name;
PFN_vkVoidFunction proc;
} coreInstanceCommands[] = {
{ "vkCreateInstance", reinterpret_cast<PFN_vkVoidFunction>(CreateInstance) },
{ "vkDestroyInstance", reinterpret_cast<PFN_vkVoidFunction>(DestroyInstance) },
{ "vkGetInstanceProcAddr", reinterpret_cast<PFN_vkVoidFunction>(VK_LAYER_fossilize_GetInstanceProcAddr) },
{ "vkCreateDevice", reinterpret_cast<PFN_vkVoidFunction>(CreateDevice) },
};
for (auto &cmd : coreInstanceCommands)
if (strcmp(cmd.name, pName) == 0)
return cmd.proc;
return nullptr;
}
static VKAPI_ATTR void VKAPI_CALL DestroyDevice(VkDevice device, const VkAllocationCallbacks *pAllocator)
{
lock_guard<mutex> holder{ globalLock };
void *key = getDispatchKey(device);
auto *layer = getLayerData(key, deviceData);
layer->getTable()->DestroyDevice(device, pAllocator);
destroyLayerData(key, deviceData);
}
static VKAPI_ATTR VkResult VKAPI_CALL CreateSampler(VkDevice device, const VkSamplerCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pCallbacks, VkSampler *pSampler)
{
auto *layer = get_device_layer(device);
auto res = layer->getTable()->CreateSampler(device, pCreateInfo, pCallbacks, pSampler);
if (res == VK_SUCCESS)
{
if (!layer->getRecorder().record_sampler(*pSampler, *pCreateInfo))
LOGW_LEVEL("Failed to record sampler, usually caused by unsupported pNext.\n");
}
return res;
}
static VKAPI_ATTR VkResult VKAPI_CALL CreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pCallbacks,
VkShaderModule *pShaderModule)
{
auto *layer = get_device_layer(device);
*pShaderModule = VK_NULL_HANDLE;
auto res = layer->getTable()->CreateShaderModule(device, pCreateInfo, pCallbacks, pShaderModule);
if (res == VK_SUCCESS)
{
if (!layer->getRecorder().record_shader_module(*pShaderModule, *pCreateInfo))
LOGW_LEVEL("Failed to record shader module, usually caused by unsupported pNext.\n");
}
return res;
}
static VKAPI_ATTR VkResult VKAPI_CALL CreateRenderPass(VkDevice device, const VkRenderPassCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pCallbacks, VkRenderPass *pRenderPass)
{
auto *layer = get_device_layer(device);
auto res = layer->getTable()->CreateRenderPass(device, pCreateInfo, pCallbacks, pRenderPass);
if (res == VK_SUCCESS)
{
if (!layer->getRecorder().record_render_pass(*pRenderPass, *pCreateInfo))
LOGW_LEVEL("Failed to record render pass, usually caused by unsupported pNext.\n");
}
return res;
}
static VKAPI_ATTR VkResult VKAPI_CALL CreateRenderPass2(VkDevice device, const VkRenderPassCreateInfo2 *pCreateInfo,
const VkAllocationCallbacks *pCallbacks, VkRenderPass *pRenderPass)
{
auto *layer = get_device_layer(device);
// Split calls since 2 and KHR variants might not be present even if the other one is.
auto res = layer->getTable()->CreateRenderPass2(device, pCreateInfo, pCallbacks, pRenderPass);
if (res == VK_SUCCESS)
{
if (!layer->getRecorder().record_render_pass2(*pRenderPass, *pCreateInfo))
LOGW_LEVEL("Failed to record render pass, usually caused by unsupported pNext.\n");
}
return res;
}
static VKAPI_ATTR VkResult VKAPI_CALL CreateRenderPass2KHR(VkDevice device, const VkRenderPassCreateInfo2 *pCreateInfo,
const VkAllocationCallbacks *pCallbacks, VkRenderPass *pRenderPass)
{
auto *layer = get_device_layer(device);
// Split calls since 2 and KHR variants might not be present even if the other one is.
auto res = layer->getTable()->CreateRenderPass2KHR(device, pCreateInfo, pCallbacks, pRenderPass);
if (res == VK_SUCCESS)
{
if (!layer->getRecorder().record_render_pass2(*pRenderPass, *pCreateInfo))
LOGW_LEVEL("Failed to record render pass, usually caused by unsupported pNext.\n");
}
return res;
}
static PFN_vkVoidFunction interceptCoreDeviceCommand(const char *pName)
{
static const struct
{
const char *name;
PFN_vkVoidFunction proc;
} coreDeviceCommands[] = {
{ "vkGetDeviceProcAddr", reinterpret_cast<PFN_vkVoidFunction>(VK_LAYER_fossilize_GetDeviceProcAddr) },
{ "vkDestroyDevice", reinterpret_cast<PFN_vkVoidFunction>(DestroyDevice) },
{ "vkCreateDescriptorSetLayout", reinterpret_cast<PFN_vkVoidFunction>(CreateDescriptorSetLayout) },
{ "vkCreatePipelineLayout", reinterpret_cast<PFN_vkVoidFunction>(CreatePipelineLayout) },
{ "vkCreateGraphicsPipelines", reinterpret_cast<PFN_vkVoidFunction>(CreateGraphicsPipelines) },
{ "vkCreateComputePipelines", reinterpret_cast<PFN_vkVoidFunction>(CreateComputePipelines) },
{ "vkCreateSampler", reinterpret_cast<PFN_vkVoidFunction>(CreateSampler) },
{ "vkCreateShaderModule", reinterpret_cast<PFN_vkVoidFunction>(CreateShaderModule) },
{ "vkCreateRenderPass", reinterpret_cast<PFN_vkVoidFunction>(CreateRenderPass) },
{ "vkCreateRenderPass2", reinterpret_cast<PFN_vkVoidFunction>(CreateRenderPass2) },
{ "vkCreateRenderPass2KHR", reinterpret_cast<PFN_vkVoidFunction>(CreateRenderPass2KHR) },
{ "vkCreateRayTracingPipelinesKHR", reinterpret_cast<PFN_vkVoidFunction>(CreateRayTracingPipelinesKHR) },
};
for (auto &cmd : coreDeviceCommands)
if (strcmp(cmd.name, pName) == 0)
return cmd.proc;
return nullptr;
}
}
using namespace Fossilize;
extern "C"
{
VK_LAYER_EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL VK_LAYER_fossilize_GetDeviceProcAddr(VkDevice device, const char *pName)
{
Device *layer;
{
lock_guard<mutex> holder{globalLock};
layer = getLayerData(getDispatchKey(device), deviceData);
}
auto proc = layer->getTable()->GetDeviceProcAddr(device, pName);
// If the underlying implementation returns nullptr, we also need to return nullptr.
// This means we never expose wrappers which will end up dispatching into nullptr.
if (proc)
{
auto wrapped_proc = interceptCoreDeviceCommand(pName);
if (wrapped_proc)
proc = wrapped_proc;
}
return proc;
}
VK_LAYER_EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL VK_LAYER_fossilize_GetInstanceProcAddr(VkInstance instance, const char *pName)
{
// We only wrap core Vulkan 1.0 instance commands, no need to check for availability of underlying implementation.
auto proc = interceptCoreInstanceCommand(pName);
if (proc)
return proc;
Instance *layer;
{
lock_guard<mutex> holder{globalLock};
layer = getLayerData(getDispatchKey(instance), instanceData);
}
proc = layer->getProcAddr(pName);
// If the underlying implementation returns nullptr, we also need to return nullptr.
// This means we never expose wrappers which will end up dispatching into nullptr.
if (proc)
{
auto wrapped_proc = interceptCoreDeviceCommand(pName);
if (wrapped_proc)
proc = wrapped_proc;
}
return proc;
}
#ifdef ANDROID
static const VkLayerProperties layerProps[] = {
{ VK_LAYER_fossilize, VK_MAKE_VERSION(1, 2, 136), 1, "Fossilize capture layer" },
};
VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL
vkEnumerateInstanceExtensionProperties(const char *pLayerName, uint32_t *pPropertyCount,
VkExtensionProperties *pProperties)
{
if (!pLayerName || strcmp(pLayerName, layerProps[0].layerName))
return VK_ERROR_LAYER_NOT_PRESENT;
if (pProperties && *pPropertyCount != 0)
{
*pPropertyCount = 0;
return VK_INCOMPLETE;
}
*pPropertyCount = 0;
return VK_SUCCESS;
}
VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL
vkEnumerateDeviceExtensionProperties(VkPhysicalDevice, const char *pLayerName,
uint32_t *pPropertyCount,
VkExtensionProperties *pProperties)
{
if (pLayerName && !strcmp(pLayerName, layerProps[0].layerName))
{
if (pProperties && *pPropertyCount > 0)
return VK_INCOMPLETE;
*pPropertyCount = 0;
return VK_SUCCESS;
}
else
return VK_ERROR_LAYER_NOT_PRESENT;
}
VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkEnumerateInstanceLayerProperties(uint32_t *pPropertyCount,
VkLayerProperties *pProperties)
{
if (pProperties)
{
uint32_t count = std::min(1u, *pPropertyCount);
memcpy(pProperties, layerProps, count * sizeof(VkLayerProperties));
VkResult res = count < *pPropertyCount ? VK_INCOMPLETE : VK_SUCCESS;
*pPropertyCount = count;
return res;
}
else
{
*pPropertyCount = sizeof(layerProps) / sizeof(VkLayerProperties);
return VK_SUCCESS;
}
}
VK_LAYER_EXPORT VKAPI_ATTR VkResult VKAPI_CALL
vkEnumerateDeviceLayerProperties(VkPhysicalDevice, uint32_t *pPropertyCount,
VkLayerProperties *pProperties)
{
if (pProperties)
{
uint32_t count = std::min(1u, *pPropertyCount);
memcpy(pProperties, layerProps, count * sizeof(VkLayerProperties));
VkResult res = count < *pPropertyCount ? VK_INCOMPLETE : VK_SUCCESS;
*pPropertyCount = count;
return res;
}
else
{
*pPropertyCount = sizeof(layerProps) / sizeof(VkLayerProperties);
return VK_SUCCESS;
}
}
#endif
}
| 42.147265 | 136 | 0.677349 |
babd605a1be0c0dbd007f74b3305b025dee04f9d | 17,439 | cpp | C++ | src/dx11/CD3DSystemDX11.cpp | sarkankur/Plugin_D3D | b96c39cf1cee3cb7c65d4b31bec9d0723cfd957c | [
"BSD-2-Clause"
] | 3 | 2017-11-27T21:44:05.000Z | 2021-04-13T21:04:23.000Z | src/dx11/CD3DSystemDX11.cpp | sarkankur/Plugin_D3D | b96c39cf1cee3cb7c65d4b31bec9d0723cfd957c | [
"BSD-2-Clause"
] | null | null | null | src/dx11/CD3DSystemDX11.cpp | sarkankur/Plugin_D3D | b96c39cf1cee3cb7c65d4b31bec9d0723cfd957c | [
"BSD-2-Clause"
] | 5 | 2016-03-23T06:49:00.000Z | 2021-04-13T21:04:26.000Z | /* D3D_Plugin - for licensing and copyright see license.txt */
#include <StdAfx.h>
#include "CD3DSystemDX11.h"
#include "d3d11hook.h"
#include <CPluginD3D.h>
//#pragma comment(lib, "dxerr.lib") // not needed atm
D3DPlugin::CD3DSystem11* D3DPlugin::gD3DSystem11 = NULL;
#undef METHOD
#undef INTERFACE
#define INTERFACE IDXGISwapChain
#define METHOD Present
GEN_HOOK( UINT SyncInterval, UINT Flags )
{
if ( !D3DPlugin::gD3DSystem11->m_pSwapChain && D3DPlugin::gD3DSystem11->m_pDevice )
{
ID3D11Device* pSwapChainDevice = NULL;
HRESULT hrg = This->GetDevice( __uuidof( ID3D11Device ), ( void** )&pSwapChainDevice );
if ( pSwapChainDevice == D3DPlugin::gD3DSystem11->m_pDevice )
{
D3DPlugin::gD3DSystem11->m_pSwapChain = This;
D3DPlugin::gPlugin->LogAlways( "DXGI swap chain retrieved" );
}
}
bool bEngineSwapChain = D3DPlugin::gD3DSystem11->m_pSwapChain == This;
if ( bEngineSwapChain )
{
D3DPlugin::gD3DSystem11->OnPrePresent();
}
CALL_ORGINAL( SyncInterval, Flags );
if ( bEngineSwapChain )
{
D3DPlugin::gD3DSystem11->OnPostPresent();
D3DPlugin::gD3DSystem11->OnPostBeginScene(); // doesn't exist in dx11, but keep for compatibility
}
rehookVT( This, IDXGISwapChain, Present );
return hr;
}
#undef METHOD
#undef INTERFACE
#define INTERFACE ID3D11DeviceContext
#define METHOD GSSetShader
GEN_HOOK_( void, __in_opt ID3D11GeometryShader* pShader, __in_ecount_opt( NumClassInstances ) ID3D11ClassInstance* const* ppClassInstances, UINT NumClassInstances )
{
CALL_ORGINAL_( , pShader, ppClassInstances, NumClassInstances );
//FIXME:
// Note: this is more of a hack since access to swap chain not yet implemented
// (multiple calls for each frame will come through the listener must handle it by registering a OnPostUpdate and setting a dirty flag)
if ( pShader == NULL && ppClassInstances == NULL && NumClassInstances == 0 )
{
//D3DPlugin::gD3DSystem11->OnPostBeginScene();
if ( D3DPlugin::gD3DSystem11->m_pSwapChain )
{
rehookVT( D3DPlugin::gD3DSystem11->m_pSwapChain, IDXGISwapChain, Present );
}
}
rehookVT( This, ID3D11DeviceContext, GSSetShader );
}
#undef METHOD
#define METHOD ClearRenderTargetView
GEN_HOOK_( void, __in ID3D11RenderTargetView* pRenderTargetView, __in const FLOAT ColorRGBA[ 4 ] )
{
CALL_ORGINAL_( , pRenderTargetView, ColorRGBA );
//D3DPlugin::gD3DSystem11->OnPostBeginScene();
rehookVT( This, ID3D11DeviceContext, ClearRenderTargetView );
};
#undef METHOD
#define METHOD End
GEN_HOOK_( void, __in ID3D11Asynchronous* pAsync )
{
CALL_ORGINAL_( , pAsync );
//D3DPlugin::gD3DSystem11->OnPostBeginScene();
rehookVT( This, ID3D11DeviceContext, ClearRenderTargetView );
rehookVT( This, ID3D11DeviceContext, End );
}
#undef METHOD
#undef INTERFACE
#define INTERFACE ID3D11Device
#define METHOD CreateTexture2D
GEN_HOOK( __in const D3D11_TEXTURE2D_DESC* pDesc, __in_xcount_opt( pDesc->MipLevels * pDesc->ArraySize ) const D3D11_SUBRESOURCE_DATA* pInitialData, __out_opt ID3D11Texture2D** ppTexture2D )
{
if ( D3DPlugin::gD3DSystem11->m_nTextureMode == HTM_INJECT )
{
goto INJECTTEXTURE;
}
CALL_ORGINAL( pDesc, pInitialData, ppTexture2D );
if ( SUCCEEDED( hr ) )
{
switch ( D3DPlugin::gD3DSystem11->m_nTextureMode )
{
case HTM_INJECT:
INJECTTEXTURE:
if ( pDesc && pDesc->ArraySize == 1 && ppTexture2D )
{
ppTexture2D[0] = ( ID3D11Texture2D* )( D3DPlugin::gD3DSystem11->m_pTempTex );
ppTexture2D[0]->AddRef();
}
hr = S_OK;
break;
case HTM_CREATE:
D3DPlugin::gD3DSystem11->m_pTempTex = NULL;
if ( pDesc && pDesc->ArraySize == 1 && ppTexture2D )
{
D3DPlugin::gD3DSystem11->m_pTempTex = ( void* )( ppTexture2D[0] );
}
break;
}
D3DPlugin::gD3DSystem11->m_nTextureMode = HTM_NONE;
}
return hr;
}
#undef METHOD
#define METHOD GetImmediateContext
GEN_HOOK_( void, __out ID3D11DeviceContext** ppImmediateContext )
{
CALL_ORGINAL_( , ppImmediateContext );
rehookVT( *ppImmediateContext, ID3D11DeviceContext, ClearRenderTargetView );
rehookVT( *ppImmediateContext, ID3D11DeviceContext, End );
rehookVT( *ppImmediateContext, ID3D11DeviceContext, GSSetShader );
}
#undef METHOD
#undef INTERFACE
bool BootstrapD3D11SwapChainHook( )
{
bool bRet = false;
HWND hWndDummy = CreateWindowEx( NULL, TEXT( "Message" ), TEXT( "DummyWindow" ), WS_MINIMIZE, 0, 0, 8, 8, HWND_MESSAGE, NULL, 0, NULL );
HMODULE hModule = NULL;
hModule = GetModuleHandle( "d3d11.dll" );
typedef HRESULT ( WINAPI * fD3D11CreateDeviceAndSwapChain )(
_In_ IDXGIAdapter * pAdapter,
_In_ D3D_DRIVER_TYPE DriverType,
_In_ HMODULE Software,
_In_ UINT Flags,
_In_ const D3D_FEATURE_LEVEL * pFeatureLevels,
_In_ UINT FeatureLevels,
_In_ UINT SDKVersion,
_In_ const DXGI_SWAP_CHAIN_DESC * pSwapChainDesc,
_Out_ IDXGISwapChain** ppSwapChain,
_Out_ ID3D11Device** ppDevice,
_Out_ D3D_FEATURE_LEVEL * pFeatureLevel,
_Out_ ID3D11DeviceContext** ppImmediateContext );
fD3D11CreateDeviceAndSwapChain D3D11CreateDeviceAndSwapChain = ( fD3D11CreateDeviceAndSwapChain )GetProcAddress( hModule, "D3D11CreateDeviceAndSwapChain" );
IDXGISwapChain* pSwapChain = NULL;
ID3D11Device* pDevice = NULL;
ID3D11DeviceContext* pDeviceContext = NULL;
// dummy swap chain description struct
DXGI_SWAP_CHAIN_DESC sSwapChainDesc;
ZeroMemory( &sSwapChainDesc, sizeof( DXGI_SWAP_CHAIN_DESC ) );
sSwapChainDesc.Windowed = TRUE;
sSwapChainDesc.OutputWindow = hWndDummy;
sSwapChainDesc.BufferCount = 1;
sSwapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
sSwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sSwapChainDesc.SampleDesc.Count = 1;
// create a device, device context and swap chain using the information in the scd struct
HRESULT hr = D3D11CreateDeviceAndSwapChain(
NULL,
D3D_DRIVER_TYPE_HARDWARE,
NULL,
NULL,
NULL,
NULL,
D3D11_SDK_VERSION,
&sSwapChainDesc,
&pSwapChain,
&pDevice,
NULL,
&pDeviceContext );
if ( SUCCEEDED( hr ) )
{
bRet = true;
hookVT( pSwapChain, IDXGISwapChain, Present );
}
/*
INT_PTR* unkdata, int nDatalen, void* pParam;
if ( bRet && nDatalen > 0 && unkdata )
{
void** vt = getVT( pSwapChain );
if ( vt )
{
memcpy( unkdata, vt, nDatalen );
}
else
{
bRet = false;
}
}
*/
SAFE_RELEASE( pSwapChain );
SAFE_RELEASE( pDevice );
SAFE_RELEASE( pDeviceContext );
DestroyWindow( hWndDummy );
return bRet;
}
namespace D3DPlugin
{
IDXGISwapChain* FindDXGISwapChain( INT_PTR nRelativeBase )
{
INT_PTR nModuleOffset = ( INT_PTR )GetModuleHandle( TEXT( "dxgi.dll" ) );
if ( !nModuleOffset )
{
gPlugin->LogWarning( "DX11/DXGI not active" );
return NULL;
}
// atm search is not needed since we receive swap chain through present
return NULL;
/*
// Not needed anymore DX11/DXGI is easier to handle (by creating Dummy SwapChain)
// Set Defaults
static INT_PTR dxoffset = 0xC00 + sizeof( INT_PTR );
static DWORD dxoffsetlen = sizeof( dxoffset );
static INT_PTR dxdata[3];
static DWORD dxdatalen = sizeof( dxdata );
static bool bFirstCall = true;
#ifdef _WIN64
static LPCTSTR sSubKeyData = D3D_DATA SEP D3D_TARGETX64 SEP D3D_TARGETDX11;
static LPCTSTR sSubKeyOffset = D3D_OFFSET SEP D3D_TARGETX64 SEP D3D_TARGETDX11;
if ( bFirstCall )
{
dxdata[0] = 0x0;
dxdata[1] = 0x0;
dxdata[2] = 0x0;
}
#else
static LPCTSTR sSubKeyData = D3D_DATA SEP D3D_TARGETX86 SEP D3D_TARGETDX11;
static LPCTSTR sSubKeyOffset = D3D_OFFSET SEP D3D_TARGETX86 SEP D3D_TARGETDX11;
if ( bFirstCall )
{
dxdata[0] = 0x0;
dxdata[1] = 0x0;
dxdata[2] = 0x0;
}
#endif
int nFunctioncount = 18;
return FindInterface<IDXGISwapChain, IUnknown>(
nModuleOffset,
nRelativeBase,
nFunctioncount,
0xFFF,
"",
dxdata,
dxdatalen,
"",
dxoffset,
dxoffsetlen,
&GetD3D11DeviceData );
*/
}
ID3D11Device* FindD3D11Device( INT_PTR nRelativeBase, void* pTrialDevice )
{
INT_PTR nModuleOffset = ( INT_PTR )GetModuleHandle( TEXT( "d3d11.dll" ) );
if ( !nModuleOffset )
{
gPlugin->LogWarning( "DX11 not active" );
return NULL;
}
return ( ID3D11Device* )pTrialDevice;
/*
// Not required for DX11, Device can be retrieved via SwapChain
// Set Defaults
static INT_PTR dxoffset = 0xC00 + sizeof(INT_PTR);
static DWORD dxoffsetlen = sizeof(dxoffset);
static INT_PTR dxdata[3];
static DWORD dxdatalen = sizeof(dxdata);
static bool bFirstCall = true;
#ifdef _WIN64
static LPCTSTR sSubKeyData = D3D_DATA SEP D3D_TARGETX64 SEP D3D_TARGETDX11;
static LPCTSTR sSubKeyOffset = D3D_OFFSET SEP D3D_TARGETX64 SEP D3D_TARGETDX11;
if(bFirstCall)
{
dxdata[0] = 0x000000000001ce3c;
dxdata[1] = 0x0000000000002f30;
dxdata[2] = 0x0000000000002f00;
}
#else
static LPCTSTR sSubKeyData = D3D_DATA SEP D3D_TARGETX86 SEP D3D_TARGETDX11;
static LPCTSTR sSubKeyOffset = D3D_OFFSET SEP D3D_TARGETX86 SEP D3D_TARGETDX11;
if(bFirstCall)
{
dxdata[0] = 0x00006F19;
dxdata[1] = 0x00006992;
dxdata[2] = 0x00006969;
}
#endif
bFirstCall = false;
void* pInterfaceClass = (void*)(nRelativeBase + dxoffset);
int nFunctioncount = 43;
// Calculate Offsets of IUnknown Interface VTable
dxdata[0] += nModuleOffset;
dxdata[1] += nModuleOffset;
dxdata[2] += nModuleOffset;
bool bInterfaceOk = CheckForInterface<IUnknown>(pInterfaceClass, dxdata, dxdatalen, __uuidof(ID3D11Device), nFunctioncount);
dxdata[0] -= nModuleOffset;
dxdata[1] -= nModuleOffset;
dxdata[2] -= nModuleOffset;
// Offset already found
if(bInterfaceOk)
return *(ID3D11Device**)pInterfaceClass;
// Search for offset
return FindInterface<ID3D11Device, IUnknown>(
nModuleOffset,
nRelativeBase,
nFunctioncount,
0xFFF,
sSubKeyData,
dxdata,
dxdatalen,
sSubKeyOffset,
dxoffset,
dxoffsetlen,
&GetD3D11DeviceData);
*/
}
CD3DSystem11::CD3DSystem11()
{
gD3DSystem11 = this;
m_bD3DHookInstalled = false;
m_nTextureMode = HTM_NONE;
m_pTempTex = NULL;
m_pDeviceCtx = NULL;
m_pSwapChain = NULL; // FindDXGISwapChain( ( INT_PTR )gEnv->pRenderer );
m_pDevice = FindD3D11Device( ( INT_PTR )gEnv->pRenderer, gEnv->pRenderer->EF_Query( EFQ_D3DDevice ) );
// Hook Swap Chain
if ( m_pDevice )
{
if ( BootstrapD3D11SwapChainHook() )
{
gPlugin->LogAlways( "DXGI swap chain hook set" );
}
else
{
gPlugin->LogAlways( "DXGI swap chain hook couldn't be installed" );
}
}
if ( m_pDevice )
{
ID3D11Device* pDevice = ( ID3D11Device* )m_pDevice;
pDevice->GetImmediateContext( ( ID3D11DeviceContext** )&m_pDeviceCtx );
if ( m_pDeviceCtx )
{
( ( ID3D11DeviceContext* )( m_pDeviceCtx ) )->Release();
gPlugin->LogAlways( "DX11 device context found" );
}
else
{
gPlugin->LogWarning( "DX11 device context not found" );
}
gPlugin->LogAlways( "DX11 device found" );
}
else
{
gPlugin->LogWarning( "DX11 device not found" );
}
/*
// Alternative Method would only work on Debug devices..
ID3D11Debug* pDbgDevice = NULL;
HRESULT hr = pDevice->QueryInterface(__uuidof(ID3D11Debug), (void**)&pDbgDevice);
IDXGISwapChain* pSwapChain = NULL;
if(pDbgDevice)
hr = pDbgDevice->GetSwapChain(&pSwapChain);
*/
}
CD3DSystem11::~CD3DSystem11()
{
hookD3D( false );
gD3DSystem11 = NULL;
}
void CD3DSystem11::hookD3D( bool bHook )
{
#if defined(D3D_DISABLE_HOOK)
return;
#endif
if ( m_pDevice && m_pDeviceCtx )
{
if ( bHook && m_bD3DHookInstalled )
{
if ( m_pSwapChain )
{
rehookVT( m_pSwapChain, IDXGISwapChain, Present );
}
rehookVT( m_pDevice, ID3D11Device, CreateTexture2D );
rehookVT( m_pDevice, ID3D11Device, GetImmediateContext );
rehookVT( m_pDeviceCtx, ID3D11DeviceContext, ClearRenderTargetView );
rehookVT( m_pDeviceCtx, ID3D11DeviceContext, End );
rehookVT( m_pDeviceCtx, ID3D11DeviceContext, GSSetShader );
}
else if ( bHook )
{
// This way isn't possible. Only via bootstrap
//if ( m_pSwapChain )
//{
// hookVT( m_pSwapChain, IDXGISwapChain, Present );
//}
hookVT( m_pDevice, ID3D11Device, CreateTexture2D );
hookVT( m_pDevice, ID3D11Device, GetImmediateContext );
hookVT( m_pDeviceCtx, ID3D11DeviceContext, ClearRenderTargetView );
hookVT( m_pDeviceCtx, ID3D11DeviceContext, End );
hookVT( m_pDeviceCtx, ID3D11DeviceContext, GSSetShader );
}
else if ( m_bD3DHookInstalled )
{
// For Unloading
if ( m_pSwapChain )
{
unhookVT( m_pSwapChain, IDXGISwapChain, Present, false );
}
unhookVT( m_pDevice, ID3D11Device, CreateTexture2D, false );
unhookVT( m_pDevice, ID3D11Device, GetImmediateContext, false );
unhookVT( m_pDeviceCtx, ID3D11DeviceContext, ClearRenderTargetView, false );
unhookVT( m_pDeviceCtx, ID3D11DeviceContext, End, false );
unhookVT( m_pDeviceCtx, ID3D11DeviceContext, GSSetShader, false );
}
m_bD3DHookInstalled = bHook;
}
}
ITexture* CD3DSystem11::CreateTexture( void** pD3DTextureDst, int width, int height, int numMips, ETEX_Format eTF, int flags )
{
gD3DSystem11->m_nTextureMode = HTM_CREATE;
int iTex = gEnv->pRenderer->SF_CreateTexture( width, height, numMips, NULL, eTF, flags ); // Create Texture
*pD3DTextureDst = m_pTempTex;
m_pTempTex = NULL;
return gEnv->pRenderer->EF_GetTextureByID( iTex );
}
ITexture* CD3DSystem11::InjectTexture( void* pD3DTextureSrc, int nWidth, int nHeight, ETEX_Format eTF, int flags )
{
gD3DSystem11->m_nTextureMode = HTM_INJECT;
m_pTempTex = pD3DTextureSrc;
int iTex = gEnv->pRenderer->SF_CreateTexture( nWidth, nHeight, 1, NULL, eTF, flags ); // Create Dummytexture and replace it to trick CE3 into using our texture.
m_pTempTex = NULL;
return gEnv->pRenderer->EF_GetTextureByID( iTex );
}
} | 32.780075 | 190 | 0.567349 |
babd9511e71c0c9bf712fba7e8bb9e5847aeacee | 1,503 | cpp | C++ | TargetSystem/Source/TargetSystem/Private/TargetSystemLockOnWidget.cpp | william-anderson/ue4-targetsystemplugin | fc9671384c359da012c8663a3ceb60bb205058dd | [
"MIT"
] | null | null | null | TargetSystem/Source/TargetSystem/Private/TargetSystemLockOnWidget.cpp | william-anderson/ue4-targetsystemplugin | fc9671384c359da012c8663a3ceb60bb205058dd | [
"MIT"
] | null | null | null | TargetSystem/Source/TargetSystem/Private/TargetSystemLockOnWidget.cpp | william-anderson/ue4-targetsystemplugin | fc9671384c359da012c8663a3ceb60bb205058dd | [
"MIT"
] | null | null | null | // Copyright 2018-2019 Mickael Daniel. All Rights Reserved.
#include "TargetSystemLockOnWidget.h"
#include "Components/CanvasPanel.h"
#include "Components/CanvasPanelSlot.h"
#include "Blueprint/WidgetTree.h"
UTargetSystemLockOnWidget::UTargetSystemLockOnWidget(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
UE_LOG(LogTemp, Warning, TEXT("UTargetLockOnWidget initialization"));
}
TSharedRef<SWidget> UTargetSystemLockOnWidget::RebuildWidget()
{
UE_LOG(LogTemp, Warning, TEXT("UTargetLockOnWidget RebuildWidget()"));
UPanelWidget* RootWidget = Cast<UPanelWidget>(GetRootWidget());
if (!RootWidget)
{
UE_LOG(LogTemp, Warning, TEXT("UTargetLockOnWidget RebuildWidget() No root widget create it"));
// Construct the root widget. Root widgets are UCanvasPanels by default in UMG
RootWidget = WidgetTree->ConstructWidget<UCanvasPanel>(UCanvasPanel::StaticClass(), TEXT("RootWidget"));
// Set it as the root widget
WidgetTree->RootWidget = RootWidget;
}
// The root widget needs to be set before claling Super::RebuildWidget()
TSharedRef<SWidget> Widget = Super::RebuildWidget();
if (WidgetTree && RootWidget)
{
UE_LOG(LogTemp, Warning, TEXT("WidgetTree && RootWidget"));
TextWidget = WidgetTree->ConstructWidget<UTextBlock>(UTextBlock::StaticClass(), TEXT("TextBox"));
TextWidget->Font.Size = 24;
TextWidget->SetText(FText::FromString("O"));
RootWidget->AddChild(TextWidget);
}
return Widget;
}
| 33.4 | 107 | 0.74318 |
bac1170359dcbd3a2d9f8b93934541c73c1adff0 | 1,623 | cc | C++ | src/parse.cc | realzhangm/dpdk_port_test | b5546a57df243ba86c8c3330cce3905e61d15ff2 | [
"MIT"
] | null | null | null | src/parse.cc | realzhangm/dpdk_port_test | b5546a57df243ba86c8c3330cce3905e61d15ff2 | [
"MIT"
] | null | null | null | src/parse.cc | realzhangm/dpdk_port_test | b5546a57df243ba86c8c3330cce3905e61d15ff2 | [
"MIT"
] | null | null | null | #include <rte_mbuf.h>
#include <rte_ether.h>
#include <rte_ip.h>
#include <rte_tcp.h>
#include <rte_udp.h>
bool PreparePacket(rte_mbuf* m, int port_id, int ring_id) {
char* pkt_data = rte_ctrlmbuf_data(m);
uint16_t* eth_type = (uint16_t*)(pkt_data + 2 * ETHER_ADDR_LEN);
m->l2_len = 2 * ETHER_ADDR_LEN;
ipv4_hdr* ipv4 = NULL;
tcp_hdr* tcp = NULL;
while (*eth_type == rte_cpu_to_be_16(ETHER_TYPE_VLAN) ||
*eth_type == rte_cpu_to_be_16(ETHER_TYPE_QINQ)) {
eth_type += 2;
m->l2_len += 4;
}
m->l2_len += 2;
uint8_t ip_proto = 0;
switch (rte_cpu_to_be_16(*eth_type)) {
case ETHER_TYPE_IPv4: {
ipv4 = (ipv4_hdr*)(eth_type + 1);
m->l3_len = 4 * (ipv4->version_ihl & 0x0F);
ip_proto = ipv4->next_proto_id;
break;
}
case ETHER_TYPE_IPv6: {
m->l3_len = sizeof(ipv6_hdr); //
ip_proto = ((ipv6_hdr*)(eth_type + 1))->proto;
break;
}
default: {
printf("%s\n", "Packet is not IP - not supported");
return false;
}
}
// If it's not TCP or UDP packet - skip it
switch (ip_proto) {
case IPPROTO_TCP: {
tcp = rte_pktmbuf_mtod_offset(m, tcp_hdr*, m->l2_len + m->l3_len);
m->l4_len = 4 * ((tcp->data_off & 0xF0) >> 4);
printf(
"port_id=%02d, ring_num=%02d, hash=%x, sip=%u, dip=%u, sport=%d, "
"dport=%d\n",
port_id, ring_id, m->hash.rss, ipv4->src_addr, ipv4->dst_addr,
tcp->src_port, tcp->dst_port);
break;
}
case IPPROTO_UDP: {
m->l4_len = sizeof(udp_hdr); //
break;
}
default: { return false; }
}
return true;
} | 26.606557 | 76 | 0.586568 |
bac13f0941380ccf228c0ba9d6e1f3d82e7819cf | 3,509 | cpp | C++ | code_reading/oceanbase-master/src/share/ob_task_define.cpp | wangcy6/weekly_read | 3a8837ee9cd957787ee1785e4066dd623e02e13a | [
"Apache-2.0"
] | null | null | null | code_reading/oceanbase-master/src/share/ob_task_define.cpp | wangcy6/weekly_read | 3a8837ee9cd957787ee1785e4066dd623e02e13a | [
"Apache-2.0"
] | null | null | null | code_reading/oceanbase-master/src/share/ob_task_define.cpp | wangcy6/weekly_read | 3a8837ee9cd957787ee1785e4066dd623e02e13a | [
"Apache-2.0"
] | 1 | 2020-10-18T12:59:31.000Z | 2020-10-18T12:59:31.000Z | /**
* Copyright (c) 2021 OceanBase
* OceanBase CE is licensed under Mulan PubL v2.
* You can use this software according to the terms and conditions of the Mulan PubL v2.
* You may obtain a copy of Mulan PubL v2 at:
* http://license.coscl.org.cn/MulanPubL-2.0
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PubL v2 for more details.
*/
#include "ob_task_define.h"
#include "lib/allocator/ob_malloc.h"
#include "lib/utility/ob_simple_rate_limiter.h"
#include "lib/oblog/ob_log.h"
using namespace oceanbase::lib;
using namespace oceanbase::common;
namespace oceanbase {
namespace share {
class ObLogRateLimiter : public lib::ObSimpleRateLimiter {
friend class ObTaskController;
public:
bool is_force_allows() const override
{
return OB_UNLIKELY(allows_ > 0);
}
void reset_force_allows() override
{
if (is_force_allows()) {
allows_--;
}
}
private:
static RLOCAL(int64_t, allows_);
};
RLOCAL(int64_t, ObLogRateLimiter::allows_);
// class ObTaskController
ObTaskController ObTaskController::instance_;
ObTaskController::ObTaskController() : limiters_(), rate_pctgs_(), log_rate_limit_(LOG_RATE_LIMIT)
{}
ObTaskController::~ObTaskController()
{
destroy();
}
int ObTaskController::init()
{
int ret = OB_SUCCESS;
for (int i = 0; OB_SUCC(ret) && i < MAX_TASK_ID; i++) {
limiters_[i] = OB_NEW(ObLogRateLimiter, ObModIds::OB_LOG);
if (nullptr == limiters_[i]) {
ret = OB_ALLOCATE_MEMORY_FAILED;
break;
}
}
if (OB_SUCC(ret)) {
#define LOG_PCTG(ID, PCTG) \
do { \
set_log_rate_pctg<ID>(PCTG); \
get_limiter(ID)->set_name(#ID); \
} while (0)
// Set percentage of each task here.
// @NOTE: Inquire @ before any change.
LOG_PCTG(ObTaskType::GENERIC, 100.0); // default limiter
LOG_PCTG(ObTaskType::USER_REQUEST, 100.0); // default limiter
LOG_PCTG(ObTaskType::DATA_MAINTAIN, 100.0); // default limiter
LOG_PCTG(ObTaskType::ROOT_SERVICE, 100.0); // default limiter
LOG_PCTG(ObTaskType::SCHEMA, 100.0); // default limiter
#undef LOG_PCTG
calc_log_rate();
ObLogger::set_default_limiter(*limiters_[toUType(ObTaskType::GENERIC)]);
ObLogger::set_tl_type(0);
} else {
destroy();
}
return ret;
}
void ObTaskController::destroy()
{
for (int i = 0; i < MAX_TASK_ID; i++) {
if (nullptr != limiters_[i]) {
ob_delete(limiters_[i]);
limiters_[i] = nullptr;
}
}
}
void ObTaskController::switch_task(ObTaskType task_id)
{
ObLogger::set_tl_limiter(*limiters_[toUType(task_id)]);
ObLogger::set_tl_type(static_cast<int32_t>(toUType(task_id)));
}
void ObTaskController::allow_next_syslog(int64_t count)
{
ObLogRateLimiter::allows_ += count;
}
void ObTaskController::set_log_rate_limit(int64_t limit)
{
if (limit != log_rate_limit_) {
log_rate_limit_ = limit;
calc_log_rate();
}
}
void ObTaskController::calc_log_rate()
{
const double total = std::accumulate(rate_pctgs_, rate_pctgs_ + MAX_TASK_ID, .0);
for (int i = 0; total != 0 && i < MAX_TASK_ID; i++) {
limiters_[i]->set_rate(static_cast<int64_t>(rate_pctgs_[i] / total * static_cast<double>(log_rate_limit_)));
}
}
ObTaskController& ObTaskController::get()
{
return instance_;
}
} // namespace share
} // namespace oceanbase
| 25.613139 | 112 | 0.68766 |
bac18c89cb712144e3f8cb81cb67002a2f7e7279 | 1,311 | hh | C++ | Cayley.hh | steelbrain/Cayley-HHVM | a774f83a4a84f7d37592bc16e8f6336a31f34ce3 | [
"MIT"
] | 1 | 2015-04-25T06:09:20.000Z | 2015-04-25T06:09:20.000Z | Cayley.hh | steelbrain/Cayley-HHVM | a774f83a4a84f7d37592bc16e8f6336a31f34ce3 | [
"MIT"
] | null | null | null | Cayley.hh | steelbrain/Cayley-HHVM | a774f83a4a84f7d37592bc16e8f6336a31f34ce3 | [
"MIT"
] | null | null | null | <?hh //strict
require(__DIR__.'/CayleyQuery.hh');
type TypeCayleyEntry = shape(
'subject' => string,
'predicate' => string,
'object' => string,
'label' => string
);
enum CayleyOp:string as string{
WRITE = 'write';
DELETE = 'delete';
}
class Cayley{
public function __construct(public string $URL){
}
public function g():CayleyQuery{
return new CayleyQuery($this);
}
public function write(string $subject, string $predicate, string $object, string $label = ''):void{
$this->ProcessMulti(CayleyOp::WRITE, [shape(
'subject' => $subject,
'predicate' => $predicate,
'object' => $object,
'label' => $label
)]);
}
public function delete(string $subject, string $predicate, string $object, string $label = ''):void{
$this->ProcessMulti(CayleyOp::DELETE, [shape(
'subject' => $subject,
'predicate' => $predicate,
'object' => $object,
'label' => $label
)]);
}
public function ProcessMulti(CayleyOp $Op, Traversable<TypeCayleyEntry> $Items):void{
$Items = json_encode($Items);
$CH = curl_init('http://'.$this->URL.'/api/v1/'.$Op);
curl_setopt_array($CH,[
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $Items
]);
curl_exec($CH);
curl_close($CH);
}
}
| 27.3125 | 102 | 0.620137 |
bac2e2e9d40c39311ee92df03b2eeeae10a908cd | 7,158 | cpp | C++ | src/vsg/state/Image.cpp | liliolett/VulkanSceneGraph | 882e05a68f64cc20f9c13a30dd1bc072e7c32b7d | [
"MIT"
] | null | null | null | src/vsg/state/Image.cpp | liliolett/VulkanSceneGraph | 882e05a68f64cc20f9c13a30dd1bc072e7c32b7d | [
"MIT"
] | null | null | null | src/vsg/state/Image.cpp | liliolett/VulkanSceneGraph | 882e05a68f64cc20f9c13a30dd1bc072e7c32b7d | [
"MIT"
] | null | null | null | /* <editor-fold desc="MIT License">
Copyright(c) 2018 Robert Osfield
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.
</editor-fold> */
#include <vsg/core/Exception.h>
#include <vsg/io/Options.h>
#include <vsg/state/Image.h>
#include <vsg/vk/Context.h>
using namespace vsg;
void Image::VulkanData::release()
{
if (image)
{
vkDestroyImage(*device, image, device->getAllocationCallbacks());
image = VK_NULL_HANDLE;
}
if (deviceMemory)
{
deviceMemory->release(memoryOffset, size);
deviceMemory = {};
}
}
Image::Image(ref_ptr<Data> in_data) :
data(in_data)
{
if (data)
{
auto layout = data->getLayout();
auto mipmapOffsets = data->computeMipmapOffsets();
auto dimensions = data->dimensions();
uint32_t width = data->width() * layout.blockWidth;
uint32_t height = data->height() * layout.blockHeight;
uint32_t depth = data->depth() * layout.blockDepth;
switch (layout.imageViewType)
{
case (VK_IMAGE_VIEW_TYPE_1D):
imageType = VK_IMAGE_TYPE_1D;
arrayLayers = 1;
break;
case (VK_IMAGE_VIEW_TYPE_2D):
imageType = VK_IMAGE_TYPE_2D;
arrayLayers = 1;
break;
case (VK_IMAGE_VIEW_TYPE_3D):
imageType = VK_IMAGE_TYPE_3D;
arrayLayers = 1;
break;
case (VK_IMAGE_VIEW_TYPE_CUBE):
imageType = VK_IMAGE_TYPE_2D;
flags = VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;
arrayLayers = depth;
depth = 1;
break;
case (VK_IMAGE_VIEW_TYPE_1D_ARRAY):
imageType = VK_IMAGE_TYPE_1D;
arrayLayers = height * depth;
height = 1;
depth = 1;
/* flags = VK_IMAGE_CREATE_1D_ARRAY_COMPATIBLE_BIT; // comment out as Vulkan headers don't yet provide this. */
break;
case (VK_IMAGE_VIEW_TYPE_2D_ARRAY):
imageType = VK_IMAGE_TYPE_2D;
flags = VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT;
arrayLayers = depth;
depth = 1;
break;
case (VK_IMAGE_VIEW_TYPE_CUBE_ARRAY):
imageType = VK_IMAGE_TYPE_2D;
flags = VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;
arrayLayers = depth;
depth = 1;
break;
default:
imageType = dimensions >= 3 ? VK_IMAGE_TYPE_3D : (dimensions == 2 ? VK_IMAGE_TYPE_2D : VK_IMAGE_TYPE_1D);
arrayLayers = 1;
break;
}
format = layout.format;
mipLevels = static_cast<uint32_t>(mipmapOffsets.size());
extent = VkExtent3D{width, height, depth};
// remap RGB to RGBA
if (format >= VK_FORMAT_R8G8B8_UNORM && format <= VK_FORMAT_B8G8R8_SRGB)
format = static_cast<VkFormat>(format + 14);
else if (format >= VK_FORMAT_R16G16B16_UNORM && format <= VK_FORMAT_R16G16B16_SFLOAT)
format = static_cast<VkFormat>(format + 7);
else if (format >= VK_FORMAT_R32G32B32_UINT && format <= VK_FORMAT_R32G32B32_SFLOAT)
format = static_cast<VkFormat>(format + 3);
}
}
Image::Image(VkImage image, Device* device)
{
VulkanData& vd = _vulkanData[device->deviceID];
vd.image = image;
vd.device = device;
}
Image::~Image()
{
for (auto& vd : _vulkanData) vd.release();
}
VkResult Image::bind(DeviceMemory* deviceMemory, VkDeviceSize memoryOffset)
{
VulkanData& vd = _vulkanData[deviceMemory->getDevice()->deviceID];
VkResult result = vkBindImageMemory(*vd.device, vd.image, *deviceMemory, memoryOffset);
if (result == VK_SUCCESS)
{
vd.deviceMemory = deviceMemory;
vd.memoryOffset = memoryOffset;
}
return result;
}
VkResult Image::allocateAndBindMemory(Device* device, VkMemoryPropertyFlags memoryProperties, void* pNextAllocInfo)
{
auto memRequirements = getMemoryRequirements(device->deviceID);
auto memory = DeviceMemory::create(device, memRequirements, memoryProperties, pNextAllocInfo);
auto [allocated, offset] = memory->reserve(memRequirements.size);
if (!allocated)
{
throw Exception{"Error: Failed to allocate DeviceMemory."};
}
return bind(memory, offset);
}
VkMemoryRequirements Image::getMemoryRequirements(uint32_t deviceID) const
{
const VulkanData& vd = _vulkanData[deviceID];
VkMemoryRequirements memRequirements;
vkGetImageMemoryRequirements(*vd.device, vd.image, &memRequirements);
return memRequirements;
}
void Image::compile(Device* device)
{
auto& vd = _vulkanData[device->deviceID];
if (vd.image != VK_NULL_HANDLE) return;
VkImageCreateInfo info = {};
info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
info.pNext = nullptr;
info.flags = flags;
info.imageType = imageType;
info.format = format;
info.extent = extent;
info.mipLevels = mipLevels;
info.arrayLayers = arrayLayers;
info.samples = samples;
info.tiling = tiling;
info.usage = usage;
info.sharingMode = sharingMode;
info.queueFamilyIndexCount = static_cast<uint32_t>(queueFamilyIndices.size());
info.pQueueFamilyIndices = queueFamilyIndices.data();
info.initialLayout = initialLayout;
vd.device = device;
vd.requiresDataCopy = data.valid();
if (VkResult result = vkCreateImage(*vd.device, &info, vd.device->getAllocationCallbacks(), &vd.image); result != VK_SUCCESS)
{
throw Exception{"Error: Failed to create vkImage.", result};
}
}
void Image::compile(Context& context)
{
auto& vd = _vulkanData[context.deviceID];
if (vd.image != VK_NULL_HANDLE) return;
compile(context.device);
VkMemoryRequirements memRequirements;
vkGetImageMemoryRequirements(*vd.device, vd.image, &memRequirements);
auto [deviceMemory, offset] = context.deviceMemoryBufferPools->reserveMemory(memRequirements, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
if (!deviceMemory)
{
throw Exception{"Error: allocate memory to reserve slot.", VK_ERROR_OUT_OF_DEVICE_MEMORY};
}
vd.requiresDataCopy = data.valid();
bind(deviceMemory, offset);
}
| 34.747573 | 460 | 0.672953 |
bac3247d079e96a32b58c32aa87c2f2665545707 | 164 | cc | C++ | src/DetectorHit.cc | skscurious/Geant4_JPET | a5846af20b8b4b886f33c54552631623e1749fac | [
"Apache-2.0"
] | null | null | null | src/DetectorHit.cc | skscurious/Geant4_JPET | a5846af20b8b4b886f33c54552631623e1749fac | [
"Apache-2.0"
] | null | null | null | src/DetectorHit.cc | skscurious/Geant4_JPET | a5846af20b8b4b886f33c54552631623e1749fac | [
"Apache-2.0"
] | null | null | null | #include "DetectorHit.hh"
DetectorHit::DetectorHit()
: G4VHit(), fScinID(0), fTrackID(-1), fEdep(0.0), fTime(0), fPos(0)
{}
DetectorHit::~DetectorHit()
{}
| 14.909091 | 72 | 0.640244 |
bac50e1c285675028a116f04c0065e3dcea125c5 | 5,596 | cpp | C++ | ch17/ex17_4_5_6_7_8.cpp | 0iui0/Cpp-Primer | ff8530a202ac0340a3e8de6bb9726cf0516c50fc | [
"CC0-1.0"
] | null | null | null | ch17/ex17_4_5_6_7_8.cpp | 0iui0/Cpp-Primer | ff8530a202ac0340a3e8de6bb9726cf0516c50fc | [
"CC0-1.0"
] | null | null | null | ch17/ex17_4_5_6_7_8.cpp | 0iui0/Cpp-Primer | ff8530a202ac0340a3e8de6bb9726cf0516c50fc | [
"CC0-1.0"
] | null | null | null | /***************************************************************************
* @file main.cpp
* @author Alan.W
* @date 3 Mar 2014
* @remark This code is for the exercises from C++ Primer 5th Edition
* @note
***************************************************************************/
//
// Exercise 17.4:
// Write and test your own version of the findBook function.
//
// Exercise 17.5:
// Rewrite findBook to return a pair that holds an index and a pair of iterators.
//
// Exercise 17.6:
// Rewrite findBook so that it does not use tuple or pair.
//
// Exercise 17.7:
// Explain which version of findBook you prefer and why.
//
// The version using tuple is prefered.It's more flexible, campared to other versions.
//
// Exercise 17.8:
// What would happen if we passed Sales_data() as the third parameter to accumulate
// in the last code example in this section?
//
// If so, the output should be 0, as the Sales_data is default constructed.
//
#include <iostream>
#include <tuple>
#include <string>
#include <vector>
#include <algorithm>
#include <utility>
#include <numeric>
#include "ex17_4_5_6_7_8_SalesData.h"
// for ex17.4
// maches has 3 members:
// an index of a store and iterators into that store's vector
typedef std::tuple<std::vector<Sales_data>::size_type,
std::vector<Sales_data>::const_iterator,
std::vector<Sales_data>::const_iterator>
matches;
// for ex17.5
// return a pair that holds an index and a pair of iterators.
typedef std::pair<std::vector<Sales_data>::size_type,
std::pair<std::vector<Sales_data>::const_iterator,
std::vector<Sales_data>::const_iterator>>
matches_pair;
// for ex17.6
// return a struct that holds an index of a store and iterators into that store's vector
struct matches_struct {
std::vector<Sales_data>::size_type st;
std::vector<Sales_data>::const_iterator first;
std::vector<Sales_data>::const_iterator last;
matches_struct(std::vector<Sales_data>::size_type s,
std::vector<Sales_data>::const_iterator f,
std::vector<Sales_data>::const_iterator l) : st(s), first(f), last(l) {}
};
// for ex17.4
// return a vector with an entry for each store that sold the given book.
std::vector<matches>
findBook(const std::vector<std::vector<Sales_data>> &files,
const std::string &book);
// print the result using the given iostream
void reportResults(std::istream &in, std::ostream os,
const std::vector<std::vector<Sales_data>> &files);
// for ex17.5
// return a vector with an entry for each store that sold the given book.
std::vector<matches_pair>
findBook_pair(const std::vector<std::vector<Sales_data> > &files,
const std::string &book);
// for ex17.6
// return a vector with an entry for each store that sold the given book.
std::vector<matches_struct>
findBook_struct(const std::vector<std::vector<Sales_data> > &files,
const std::string &book);
int main() {
return 0;
}
// for ex17.4
// return a vector with an entry for each store that sold the given book.
std::vector<matches>
findBook(const std::vector<std::vector<Sales_data>> &files,
const std::string &book) {
std::vector<matches> ret;
// for each strore find the range of matching books, if any
for (auto it = files.cbegin(); it != files.cend(); ++it) {
// find the range of Sales_data tat have the same ISBN
auto found = std::equal_range(it->cbegin(), it->cend(), book, compareIsbn);
if (found.first != found.second)
ret.push_back(std::make_tuple(it - files.cbegin(),
found.first, found.second));
}
return ret;
}
// for ex17.4
// print the result using the given iostream
void reportResults(std::istream &in, std::ostream os,
const std::vector<std::vector<Sales_data>> &files) {
std::string s;
while (in >> s) {
auto trans = findBook(files, s);
if (trans.empty()) {
std::cout << s << "not found in any stores" << std::endl;
continue;
}
for (const auto &store :trans)
os << "store " << std::get<0>(store) << " sales: "
<< std::accumulate(std::get<1>(store), std::get<2>(store),
Sales_data(s))
<< std::endl;
}
}
// for ex17.5
// return a vector with an entry for each store that sold the given book
std::vector<matches_pair>
findBook_pair(const std::vector<std::vector<Sales_data> > &files,
const std::string &book) {
std::vector<matches_pair> ret;
for (auto it = files.cbegin(); it != files.cend(); ++it) {
auto found = std::equal_range(it->cbegin(), it->cend(), book, compareIsbn);
if (found.first != found.second)
ret.push_back(std::make_pair(it - files.cbegin(),
std::make_pair(found.first, found.second)));
}
return ret;
}
// for ex17.6
// return a vector with an entry for each store that sold the given book.
std::vector<matches_struct>
findBook_struct(const std::vector<std::vector<Sales_data> > &files,
const std::string &book) {
std::vector<matches_struct> ret;
for (auto it = files.cbegin(); it != files.cend(); ++it) {
auto found = std::equal_range(it->cbegin(), it->cend(), book, compareIsbn);
if (found.first != found.second)
ret.push_back(matches_struct(it - files.cbegin(), found.first, found.second));
}
return ret;
}
| 34.757764 | 91 | 0.615797 |
bac6990524fa666fb91476b5fa1f97f74a4fa4b1 | 474 | cpp | C++ | Leetcode/1000-2000/1828. Queries on Number of Points Inside a Circle/1828.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | Leetcode/1000-2000/1828. Queries on Number of Points Inside a Circle/1828.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | Leetcode/1000-2000/1828. Queries on Number of Points Inside a Circle/1828.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | class Solution {
public:
vector<int> countPoints(vector<vector<int>>& points,
vector<vector<int>>& queries) {
vector<int> ans;
auto squared = [](int x) { return x * x; };
for (const auto& q : queries) {
const int rSquared = q[2] * q[2];
int count = 0;
for (const auto& p : points)
count += squared(p[0] - q[0]) + squared(p[1] - q[1]) <= rSquared;
ans.push_back(count);
}
return ans;
}
};
| 23.7 | 73 | 0.518987 |
baca68818975db51c621809679ffc250c1989c91 | 7,775 | cpp | C++ | libsensors/AkmSensor.cpp | kbc-developers/android_device_samsung_sc02e | debb9dbb8f9868a52cb705d6b6d3f5ddf8640e06 | [
"FTL"
] | null | null | null | libsensors/AkmSensor.cpp | kbc-developers/android_device_samsung_sc02e | debb9dbb8f9868a52cb705d6b6d3f5ddf8640e06 | [
"FTL"
] | null | null | null | libsensors/AkmSensor.cpp | kbc-developers/android_device_samsung_sc02e | debb9dbb8f9868a52cb705d6b6d3f5ddf8640e06 | [
"FTL"
] | null | null | null | /*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <fcntl.h>
#include <errno.h>
#include <math.h>
#include <poll.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/select.h>
#include <dlfcn.h>
#include <cutils/log.h>
#include "AkmSensor.h"
#define LOGTAG "AkmSensor"
//#define ALOG_NDEBUG 0
/*****************************************************************************/
int (*akm_is_sensor_enabled)(uint32_t sensor_type);
int (*akm_enable_sensor)(uint32_t sensor_type);
int (*akm_disable_sensor)(uint32_t sensor_type);
int (*akm_set_delay)(uint32_t sensor_type, uint64_t delay);
int stub_is_sensor_enabled(uint32_t sensor_type) {
return 0;
}
int stub_enable_disable_sensor(uint32_t sensor_type) {
return -ENODEV;
}
int stub_set_delay(uint32_t sensor_type, uint64_t delay) {
return -ENODEV;
}
AkmSensor::AkmSensor()
: SensorBase(NULL, NULL),
mEnabled(0),
mPendingMask(0),
mInputReader(32)
{
/* Open the library before opening the input device. The library
* creates a uinput device.
*/
if (loadAKMLibrary() == 0) {
data_name = "compass_sensor";
data_fd = openInput("compass_sensor");
}
//Incase first time fails
if(data_fd < 0){
ALOGI("%s: retrying to open compass sensor", LOGTAG);
data_fd = openInput("compass_sensor");
}
if(data_fd > 0){
ALOGI("%s: compass sensor successfully opened: %i", LOGTAG, data_fd);
}else{
ALOGI("%s: failed to open compass sensor", LOGTAG);
}
memset(mPendingEvents, 0, sizeof(mPendingEvents));
mPendingEvents[MagneticField].version = sizeof(sensors_event_t);
mPendingEvents[MagneticField].sensor = ID_M;
mPendingEvents[MagneticField].type = SENSOR_TYPE_MAGNETIC_FIELD;
mPendingEvents[MagneticField].magnetic.status = SENSOR_STATUS_ACCURACY_HIGH;
// read the actual value of all sensors if they're enabled already
struct input_absinfo absinfo;
short flags = 0;
if (akm_is_sensor_enabled(SENSOR_TYPE_MAGNETIC_FIELD)) {
mEnabled |= 1<<MagneticField;
if (!ioctl(data_fd, EVIOCGABS(EVENT_TYPE_MAGV_X), &absinfo)) {
mPendingEvents[MagneticField].magnetic.x = absinfo.value * CONVERT_M_X;
}
if (!ioctl(data_fd, EVIOCGABS(EVENT_TYPE_MAGV_Y), &absinfo)) {
mPendingEvents[MagneticField].magnetic.y = absinfo.value * CONVERT_M_Y;
}
if (!ioctl(data_fd, EVIOCGABS(EVENT_TYPE_MAGV_Z), &absinfo)) {
mPendingEvents[MagneticField].magnetic.z = absinfo.value * CONVERT_M_Z;
}
}
}
AkmSensor::~AkmSensor()
{
if (mLibAKM) {
unsigned ref = ::dlclose(mLibAKM);
}
}
int AkmSensor::setInitialState()
{
return 0;
}
int AkmSensor::enable(int32_t handle, int en)
{
int what = -1;
switch (handle) {
case ID_M: what = MagneticField; break;
case ID_O: what = Orientation; break;
}
if (uint32_t(what) >= numSensors)
return -EINVAL;
int newState = en ? 1 : 0;
int err = 0;
if ((uint32_t(newState)<<what) != (mEnabled & (1<<what))) {
uint32_t sensor_type;
switch (what) {
case MagneticField: sensor_type = SENSOR_TYPE_MAGNETIC_FIELD; break;
}
short flags = newState;
if (en){
err = akm_enable_sensor(sensor_type);
}else{
err = akm_disable_sensor(sensor_type);
}
err = sspEnable(LOGTAG, SSP_MAG, en);
setInitialState();
ALOGE_IF(err, "Could not change sensor state (%s)", strerror(-err));
if (!err) {
mEnabled &= ~(1<<what);
mEnabled |= (uint32_t(flags)<<what);
}
}
return err;
}
int AkmSensor::setDelay(int32_t handle, int64_t ns)
{
int what = -1;
int fd;
uint32_t sensor_type = 0;
if (ns < 0)
return -EINVAL;
switch (handle) {
case ID_M: sensor_type = SENSOR_TYPE_MAGNETIC_FIELD; break;
}
if (sensor_type == 0)
return -EINVAL;
fd = open("/sys/class/sensors/ssp_sensor/mag_poll_delay", O_RDWR);
if (fd >= 0) {
char buf[80];
sprintf(buf, "%lld", ns);
write(fd, buf, strlen(buf)+1);
close(fd);
}
fd = open("/sys/class/sensors/ssp_sensor/ori_poll_delay", O_RDWR);
if (fd >= 0) {
char buf[80];
sprintf(buf, "%lld", ns);
write(fd, buf, strlen(buf)+1);
close(fd);
}
mDelays[what] = ns;
return 0;
}
int AkmSensor::loadAKMLibrary()
{
mLibAKM = dlopen("libakm.so", RTLD_NOW);
if (!mLibAKM) {
akm_is_sensor_enabled = stub_is_sensor_enabled;
akm_enable_sensor = stub_enable_disable_sensor;
akm_disable_sensor = stub_enable_disable_sensor;
akm_set_delay = stub_set_delay;
ALOGE("%s: unable to load AKM Library, %s", LOGTAG, dlerror());
return -ENOENT;
}
*(void **)&akm_is_sensor_enabled = dlsym(mLibAKM, "akm_is_sensor_enabled");
*(void **)&akm_enable_sensor = dlsym(mLibAKM, "akm_enable_sensor");
*(void **)&akm_disable_sensor = dlsym(mLibAKM, "akm_disable_sensor");
*(void **)&akm_set_delay = dlsym(mLibAKM, "akm_set_delay");
return 0;
}
int AkmSensor::readEvents(sensors_event_t* data, int count)
{
if (count < 1)
return -EINVAL;
ssize_t n = mInputReader.fill(data_fd);
if (n < 0)
return n;
int numEventReceived = 0;
input_event const* event;
while (count && mInputReader.readEvent(&event)) {
int type = event->type;
if (type == EV_REL) {
processEvent(event->code, event->value);
mInputReader.next();
} else if (type == EV_ABS) {
processEvent(event->code, event->value);
mInputReader.next();
} else if (type == EV_SYN) {
int64_t time = timevalToNano(event->time);
for (int j=0 ; count && mPendingMask && j<numSensors ; j++) {
if (mPendingMask & (1<<j)) {
mPendingMask &= ~(1<<j);
mPendingEvents[j].timestamp = time;
if (mEnabled & (1<<j)) {
*data++ = mPendingEvents[j];
count--;
numEventReceived++;
}
}
}
if (!mPendingMask) {
mInputReader.next();
}
} else {
ALOGE("%s: unknown event (type=%d, code=%d)", LOGTAG,
type, event->code);
mInputReader.next();
}
}
return numEventReceived;
}
void AkmSensor::processEvent(int code, int value)
{
switch (code) {
case EVENT_TYPE_MAGV_X:
mPendingMask |= 1<<MagneticField;
mPendingEvents[MagneticField].magnetic.x = value * CONVERT_M_X;
break;
case EVENT_TYPE_MAGV_Y:
mPendingMask |= 1<<MagneticField;
mPendingEvents[MagneticField].magnetic.y = value * CONVERT_M_Y;
break;
case EVENT_TYPE_MAGV_Z:
mPendingMask |= 1<<MagneticField;
mPendingEvents[MagneticField].magnetic.z = value * CONVERT_M_Z;
break;
}
}
| 28.272727 | 83 | 0.59717 |
bace3891a327416cd367e230de6bf75a85aca29a | 3,832 | cpp | C++ | wpb_mani_description/src/wpb_mani_test.cpp | 6-robot/wpb_mani | 6aa6e2d8713c8d018a422e4665ff8fcd7e299ad0 | [
"BSD-3-Clause"
] | 4 | 2021-02-08T03:55:26.000Z | 2021-12-13T12:06:34.000Z | wpb_mani_description/src/wpb_mani_test.cpp | 6-robot/wpb_mani | 6aa6e2d8713c8d018a422e4665ff8fcd7e299ad0 | [
"BSD-3-Clause"
] | null | null | null | wpb_mani_description/src/wpb_mani_test.cpp | 6-robot/wpb_mani | 6aa6e2d8713c8d018a422e4665ff8fcd7e299ad0 | [
"BSD-3-Clause"
] | 1 | 2021-06-08T01:17:54.000Z | 2021-06-08T01:17:54.000Z | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2017-2020, Waterplus http://www.6-robot.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the WaterPlus nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* FOOTPRINTAL, 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.
*********************************************************************/
/*!******************************************************************
@author ZhangWanjie
********************************************************************/
#include <ros/ros.h>
#include <sensor_msgs/JointState.h>
#include <math.h>
#include <vector>
#include <string>
static double fDegToAng = 3.1415926/180;
static double fAngToDeg = 180/3.1415926;
static double fJointAngle[6];
static int nJointSpeed[6];
int main(int argc, char** argv)
{
ros::init(argc,argv,"wpb_mani_test");
ROS_INFO("[wpb_mani_test]");
ros::NodeHandle n;
for(int i=0;i<5;i++)
{
fJointAngle[i] = 0;
nJointSpeed[i] = 1500;
}
ros::Publisher joint_state_pub = n.advertise<sensor_msgs::JointState>("/joint_states",10);
sensor_msgs::JointState msg;
std::vector<std::string> joint_name(11);
std::vector<double> joint_pos(11);
joint_name[0] = "front_left_wheel_joint";
joint_name[1] = "front_right_wheel_joint";
joint_name[2] = "back_right_wheel_joint";
joint_name[3] = "back_left_wheel_joint";
joint_name[4] = "kinect_height";
joint_name[5] = "kinect_pitch";
joint_name[6] = "joint1";
joint_name[7] = "joint2";
joint_name[8] = "joint3";
joint_name[9] = "joint4";
joint_name[10] = "gripper";
joint_pos[0] = 0.0f;
joint_pos[1] = 0.0f;
joint_pos[2] = 0.0f;
joint_pos[3] = 0.0f;
joint_pos[4] = 0.0f;
joint_pos[5] = 0.0f;
joint_pos[6] = 0.0f;
joint_pos[7] = 0.0f;
joint_pos[8] = 0.0f;
joint_pos[9] = 0.0f;
joint_pos[10] = 0.0f;
int nCount = 0;
ros::Rate r(30);
while(n.ok())
{
nCount += 5;
joint_pos[0] = (float)nCount*0.01;
joint_pos[1] = (float)nCount*-0.01;
joint_pos[2] = (float)nCount*-0.01;
joint_pos[3] = (float)nCount*0.01;
msg.header.stamp = ros::Time::now();
msg.header.seq ++;
msg.name = joint_name;
msg.position = joint_pos;
joint_state_pub.publish(msg);
ros::spinOnce();
r.sleep();
}
} | 35.813084 | 94 | 0.625 |
bacecdee6338b7f7be7809e6720c6657bd8ef62d | 3,855 | cpp | C++ | src/Pyros3D/Rendering/PostEffects/Effects/MotionBlurEffect.cpp | Peixinho/Pyros3D | d6857ce99f3731a851ca5e7d67afbb13aafd18e0 | [
"MIT"
] | 20 | 2016-02-15T23:22:06.000Z | 2021-12-07T00:13:49.000Z | src/Pyros3D/Rendering/PostEffects/Effects/MotionBlurEffect.cpp | Peixinho/Pyros3D | d6857ce99f3731a851ca5e7d67afbb13aafd18e0 | [
"MIT"
] | 1 | 2017-09-04T00:28:19.000Z | 2017-09-05T11:00:12.000Z | src/Pyros3D/Rendering/PostEffects/Effects/MotionBlurEffect.cpp | Peixinho/Pyros3D | d6857ce99f3731a851ca5e7d67afbb13aafd18e0 | [
"MIT"
] | 3 | 2016-08-10T02:44:08.000Z | 2021-05-28T23:03:10.000Z | //============================================================================
// Name : MotionBlur.h
// Author : Duarte Peixinho
// Version :
// Copyright : ;)
// Description : MotionBlur Effect
//============================================================================
#include <Pyros3D/Rendering/PostEffects/Effects/MotionBlurEffect.h>
namespace p3d {
MotionBlurEffect::MotionBlurEffect(const uint32 Tex1, Texture* VelocityMap, const uint32 Width, const uint32 Height) : IEffect(Width, Height)
{
// Set RTT
UseRTT(Tex1);
UseCustomTexture(VelocityMap);
//Vec2 res = Vec2(Width, Height);
f32 vel = 3.25f;
//texResHandle = AddUniform(Uniform("uTexResolution", Uniforms::DataType::Vec2, &res));
velHandle = AddUniform(Uniform("uVelocityScale", Uniforms::DataType::Float, &vel));
VertexShaderString =
#if defined(GLES2)
"#define varying_in varying\n"
"#define varying_out varying\n"
"#define attribute_in attribute\n"
"#define texture_2D texture2D\n"
"#define texture_cube textureCube\n"
"precision mediump float;"
#else
"#define varying_in in\n"
"#define varying_out out\n"
"#define attribute_in in\n"
"#define texture_2D texture\n"
"#define texture_cube texture\n"
#if defined(GLES3)
"precision mediump float;\n"
#endif
#endif
"varying_out vec2 vTexcoord;\n"
"void main() {\n"
"gl_Position = vec4(-1.0 + vec2((gl_VertexID & 1) << 2, (gl_VertexID & 2) << 1), 0.0, 1.0);\n"
"vTexcoord = (gl_Position.xy+1.0)*0.5;\n"
"}";
// Create Fragment Shader
FragmentShaderString =
"#define MAX_SAMPLES 32\n"
#if defined(GLES2)
"#define varying_in varying\n"
"#define varying_out varying\n"
"#define attribute_in attribute\n"
"#define texture_2D texture2D\n"
"#define texture_cube textureCube\n"
"precision mediump float;"
#else
"#define varying_in in\n"
"#define varying_out out\n"
"#define attribute_in in\n"
"#define texture_2D texture\n"
"#define texture_cube texture\n"
#if defined(GLES3)
"precision mediump float;\n"
#endif
#endif
#if defined(GLES2)
"vec4 FragColor;\n"
#else
"out vec4 FragColor;\n"
#endif
"varying_in vec2 vTexcoord;\n"
"uniform sampler2D uTex0;\n"
"uniform sampler2D uTex1;\n"
"uniform vec2 uTexResolution;\n"
"uniform float uVelocityScale;\n"
"void main() {\n"
"vec2 texelSize = 1.0 / vec2(textureSize(uTex0, 0));\n"
"vec2 screenTexCoords = gl_FragCoord.xy * texelSize;\n"
"vec2 velocity = texture(uTex1, screenTexCoords).rg;\n"
"velocity *= uVelocityScale;\n"
"float speed = length(velocity / texelSize);\n"
"float nSamples = clamp(int(speed), 1, MAX_SAMPLES);\n"
"vec4 oResult = texture(uTex0, screenTexCoords);\n"
"for (int i = 1; i < nSamples; ++i) {\n"
" vec2 offset = velocity * (float(i) / float(nSamples - 1) - 0.5);\n"
" oResult += texture(uTex0, screenTexCoords + offset);\n"
"}\n"
"FragColor = oResult / float(nSamples);\n"
#if defined(GLES2)
"gl_FragColor = FragColor;\n"
#endif
"}";
CompileShaders();
}
MotionBlurEffect::~MotionBlurEffect() {
}
void MotionBlurEffect::SetCurrentFPS(const f32 ¤tfps) {
this->cfps = currentfps;
f32 v = cfps/tfps;
velHandle->SetValue(&v);
}
void MotionBlurEffect::SetTargetFPS(const f32 &targetfps) {
this->tfps = targetfps;
f32 v = cfps/tfps;
velHandle->SetValue(&v);
}
};
| 33.232759 | 146 | 0.563684 |
bad2205c1145c3e50a827c1857e29df7e7cfb777 | 11,867 | cc | C++ | src/rewriter/calculator_rewriter_test.cc | mcognetta/mozc | 1f4fa17372bd196e87042738a16ab08bf904bcbf | [
"BSD-3-Clause"
] | null | null | null | src/rewriter/calculator_rewriter_test.cc | mcognetta/mozc | 1f4fa17372bd196e87042738a16ab08bf904bcbf | [
"BSD-3-Clause"
] | null | null | null | src/rewriter/calculator_rewriter_test.cc | mcognetta/mozc | 1f4fa17372bd196e87042738a16ab08bf904bcbf | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2010-2020, Google 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:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "rewriter/calculator_rewriter.h"
#include <memory>
#include <string>
#include "base/logging.h"
#include "base/system_util.h"
#include "config/config_handler.h"
#include "converter/converter_interface.h"
#include "converter/converter_mock.h"
#include "converter/segments.h"
#include "engine/engine_interface.h"
#include "engine/mock_data_engine_factory.h"
#include "protocol/commands.pb.h"
#include "protocol/config.pb.h"
#include "request/conversion_request.h"
#include "rewriter/calculator/calculator_interface.h"
#include "rewriter/calculator/calculator_mock.h"
#include "testing/base/public/googletest.h"
#include "testing/base/public/gunit.h"
namespace mozc {
namespace {
void AddCandidate(const std::string &key, const std::string &value,
Segment *segment) {
Segment::Candidate *candidate = segment->add_candidate();
candidate->Init();
candidate->value = value;
candidate->content_value = value;
candidate->content_key = key;
}
void AddSegment(const std::string &key, const std::string &value,
Segments *segments) {
Segment *segment = segments->push_back_segment();
segment->set_key(key);
AddCandidate(key, value, segment);
}
void SetSegment(const std::string &key, const std::string &value,
Segments *segments) {
segments->Clear();
AddSegment(key, value, segments);
}
const char kCalculationDescription[] = "計算結果";
bool ContainsCalculatedResult(const Segment::Candidate &candidate) {
return candidate.description.find(kCalculationDescription) !=
std::string::npos;
}
// If the segment has a candidate which was inserted by CalculatorRewriter,
// then return its index. Otherwise return -1.
int GetIndexOfCalculatedCandidate(const Segments &segments) {
CHECK_EQ(segments.segments_size(), 1);
for (size_t i = 0; i < segments.segment(0).candidates_size(); ++i) {
const Segment::Candidate &candidate = segments.segment(0).candidate(i);
if (ContainsCalculatedResult(candidate)) {
return i;
}
}
return -1;
}
} // namespace
class CalculatorRewriterTest : public ::testing::Test {
protected:
CalculatorRewriterTest() {
convreq_.set_request(&request_);
convreq_.set_config(&config_);
}
static bool InsertCandidate(const CalculatorRewriter &calculator_rewriter,
const std::string &value, size_t insert_pos,
Segment *segment) {
return calculator_rewriter.InsertCandidate(value, insert_pos, segment);
}
CalculatorMock &calculator_mock() { return calculator_mock_; }
CalculatorRewriter *BuildCalculatorRewriterWithConverterMock() {
converter_mock_.reset(new ConverterMock);
return new CalculatorRewriter(converter_mock_.get());
}
void SetUp() override {
SystemUtil::SetUserProfileDirectory(FLAGS_test_tmpdir);
// use mock
CalculatorFactory::SetCalculator(&calculator_mock_);
request_.Clear();
config::ConfigHandler::GetDefaultConfig(&config_);
config_.set_use_calculator(true);
}
void TearDown() override {
// Clear the mock test calculator
CalculatorFactory::SetCalculator(nullptr);
}
ConversionRequest convreq_;
commands::Request request_;
config::Config config_;
private:
CalculatorMock calculator_mock_;
std::unique_ptr<ConverterInterface> converter_mock_;
};
TEST_F(CalculatorRewriterTest, InsertCandidateTest) {
std::unique_ptr<CalculatorRewriter> calculator_rewriter(
BuildCalculatorRewriterWithConverterMock());
{
Segment segment;
segment.set_key("key");
// Insertion should be failed if segment has no candidate beforehand
EXPECT_FALSE(InsertCandidate(*calculator_rewriter, "value", 0, &segment));
}
// Test insertion at each position of candidates list
for (int i = 0; i <= 2; ++i) {
Segment segment;
segment.set_key("key");
AddCandidate("key", "test", &segment);
AddCandidate("key", "test2", &segment);
EXPECT_TRUE(InsertCandidate(*calculator_rewriter, "value", i, &segment));
const Segment::Candidate &candidate = segment.candidate(i);
EXPECT_EQ(candidate.value, "value");
EXPECT_EQ(candidate.content_value, "value");
EXPECT_EQ(candidate.content_key, "key");
EXPECT_NE(0, candidate.attributes & Segment::Candidate::NO_LEARNING);
// Description should be "計算結果"
EXPECT_EQ(candidate.description, kCalculationDescription);
}
}
TEST_F(CalculatorRewriterTest, BasicTest) {
// Pretend "key" is calculated to "value".
calculator_mock().SetCalculatePair("key", "value", true);
std::unique_ptr<CalculatorRewriter> calculator_rewriter(
BuildCalculatorRewriterWithConverterMock());
const int counter_at_first = calculator_mock().calculation_counter();
Segments segments;
SetSegment("test", "test", &segments);
calculator_rewriter->Rewrite(convreq_, &segments);
EXPECT_EQ(GetIndexOfCalculatedCandidate(segments), -1);
EXPECT_EQ(calculator_mock().calculation_counter(), counter_at_first + 1);
SetSegment("key", "key", &segments);
calculator_rewriter->Rewrite(convreq_, &segments);
int index = GetIndexOfCalculatedCandidate(segments);
EXPECT_NE(index, -1);
EXPECT_EQ(segments.segment(0).candidate(index).value, "value");
EXPECT_EQ(calculator_mock().calculation_counter(), counter_at_first + 2);
}
// CalculatorRewriter should convert an expression which is separated to
// multiple conversion segments. This test verifies it.
TEST_F(CalculatorRewriterTest, SeparatedSegmentsTest) {
// Pretend "1+1=" is calculated to "2".
calculator_mock().SetCalculatePair("1+1=", "2", true);
// Since this test depends on the actual implementation of
// Converter::ResizeSegments(), we cannot use converter mock here. However,
// the test itself is independent of data.
std::unique_ptr<EngineInterface> engine_(MockDataEngineFactory::Create());
std::unique_ptr<CalculatorRewriter> calculator_rewriter(
new CalculatorRewriter(engine_->GetConverter()));
// Push back separated segments.
Segments segments;
AddSegment("1", "1", &segments);
AddSegment("+", "+", &segments);
AddSegment("1", "1", &segments);
AddSegment("=", "=", &segments);
calculator_rewriter->Rewrite(convreq_, &segments);
EXPECT_EQ(segments.segments_size(), 1); // merged
int index = GetIndexOfCalculatedCandidate(segments);
EXPECT_NE(index, -1);
// Secondary result with expression (description: "1+1=2");
EXPECT_TRUE(
ContainsCalculatedResult(segments.segment(0).candidate(index + 1)));
EXPECT_EQ("2", segments.segment(0).candidate(index).value);
EXPECT_EQ("1+1=2", segments.segment(0).candidate(index + 1).value);
}
// CalculatorRewriter should convert an expression starting with '='.
TEST_F(CalculatorRewriterTest, ExpressionStartingWithEqualTest) {
// Pretend "=1+1" is calculated to "2".
calculator_mock().SetCalculatePair("=1+1", "2", true);
std::unique_ptr<CalculatorRewriter> calculator_rewriter(
BuildCalculatorRewriterWithConverterMock());
const ConversionRequest request;
Segments segments;
SetSegment("=1+1", "=1+1", &segments);
calculator_rewriter->Rewrite(request, &segments);
int index = GetIndexOfCalculatedCandidate(segments);
EXPECT_NE(-1, index);
EXPECT_EQ("2", segments.segment(0).candidate(index).value);
EXPECT_TRUE(
ContainsCalculatedResult(segments.segment(0).candidate(index + 1)));
// CalculatorRewriter should append the result to the side '=' exists.
EXPECT_EQ("2=1+1", segments.segment(0).candidate(index + 1).value);
}
// Verify the description of calculator candidate.
TEST_F(CalculatorRewriterTest, DescriptionCheckTest) {
const char kExpression[] = "5・(8/4)ー7%3+6^−1*9=";
// Expected description
const std::string description = kCalculationDescription;
// Pretend kExpression is calculated to "3"
calculator_mock().SetCalculatePair(kExpression, "3", true);
std::unique_ptr<CalculatorRewriter> calculator_rewriter(
BuildCalculatorRewriterWithConverterMock());
Segments segments;
AddSegment(kExpression, kExpression, &segments);
calculator_rewriter->Rewrite(convreq_, &segments);
const int index = GetIndexOfCalculatedCandidate(segments);
EXPECT_EQ(segments.segment(0).candidate(index).description, description);
EXPECT_TRUE(
ContainsCalculatedResult(segments.segment(0).candidate(index + 1)));
}
TEST_F(CalculatorRewriterTest, ConfigTest) {
calculator_mock().SetCalculatePair("1+1=", "2", true);
// Since this test depends on the actual implementation of
// Converter::ResizeSegments(), we cannot use converter mock here. However,
// the test itself is independent of data.
std::unique_ptr<EngineInterface> engine_(MockDataEngineFactory::Create());
std::unique_ptr<CalculatorRewriter> calculator_rewriter(
new CalculatorRewriter(engine_->GetConverter()));
{
Segments segments;
AddSegment("1", "1", &segments);
AddSegment("+", "+", &segments);
AddSegment("1", "1", &segments);
AddSegment("=", "=", &segments);
config_.set_use_calculator(true);
EXPECT_TRUE(calculator_rewriter->Rewrite(convreq_, &segments));
}
{
Segments segments;
AddSegment("1", "1", &segments);
AddSegment("+", "+", &segments);
AddSegment("1", "1", &segments);
AddSegment("=", "=", &segments);
config_.set_use_calculator(false);
EXPECT_FALSE(calculator_rewriter->Rewrite(convreq_, &segments));
}
}
TEST_F(CalculatorRewriterTest, MobileEnvironmentTest) {
std::unique_ptr<EngineInterface> engine_(MockDataEngineFactory::Create());
std::unique_ptr<CalculatorRewriter> rewriter(
new CalculatorRewriter(engine_->GetConverter()));
{
request_.set_mixed_conversion(true);
EXPECT_EQ(RewriterInterface::ALL, rewriter->capability(convreq_));
}
{
request_.set_mixed_conversion(false);
EXPECT_EQ(RewriterInterface::CONVERSION, rewriter->capability(convreq_));
}
}
TEST_F(CalculatorRewriterTest, EmptyKeyTest) {
std::unique_ptr<EngineInterface> engine_(MockDataEngineFactory::Create());
std::unique_ptr<CalculatorRewriter> calculator_rewriter(
new CalculatorRewriter(engine_->GetConverter()));
{
Segments segments;
AddSegment("", "1", &segments);
config_.set_use_calculator(true);
EXPECT_FALSE(calculator_rewriter->Rewrite(convreq_, &segments));
}
}
} // namespace mozc
| 36.179878 | 78 | 0.733884 |
bad44eb45c38c0009b04cd2f484bcf1b438c9396 | 3,670 | hpp | C++ | 3rd-party/apache/xsec/src/xsec/enc/XSECCryptoX509.hpp | okean/cpputils | 812cf41f04d66c28a5eb46dedab6e782c49e0f7a | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 1 | 2019-08-30T02:34:29.000Z | 2019-08-30T02:34:29.000Z | 3rd-party/apache/xsec/src/xsec/enc/XSECCryptoX509.hpp | okean/cpputils | 812cf41f04d66c28a5eb46dedab6e782c49e0f7a | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | 3rd-party/apache/xsec/src/xsec/enc/XSECCryptoX509.hpp | okean/cpputils | 812cf41f04d66c28a5eb46dedab6e782c49e0f7a | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* XSEC
*
* XSECCryptoX509:= A base class for handling X509 (V3) certificates
*
* Author(s): Berin Lautenbach
*
* $Id: XSECCryptoX509.hpp 1125514 2011-05-20 19:08:33Z scantor $
*
*/
#ifndef XSECCRYPTOX509_INCLUDE
#define XSECCRYPTOX509_INCLUDE
#include <xsec/framework/XSECDefs.hpp>
#include <xsec/enc/XSECCryptoKey.hpp>
#include <xsec/utils/XSECSafeBuffer.hpp>
/**
* \brief Interface class for X509 certificates.
* @ingroup crypto
*
* The library uses classes derived from this to process X509 Certificates.
*
* Strictly speaking, this class is not required (and is completely
* <em>Optional</em>. However it is used by
* XSECKeyInfoResolverDefault to extract a key from a certificate in cases
* where the caller is not worried about the trust level of the certificate.
*
*/
class DSIG_EXPORT XSECCryptoX509 {
public :
/** @name Constructors and Destructors */
//@{
XSECCryptoX509() {};
virtual ~XSECCryptoX509() {};
//@}
/** @name Key Interface methods */
//@{
/**
* \brief Return the type of the key stored in the certificate.
*
* The implementation is expected to extract the key from the
* certificate and determine the type.
*
*/
virtual XSECCryptoKey::KeyType getPublicKeyType() const = 0;
/**
* \brief Get a copy of the public key.
*
* The implementation should extract the key from the certificate,
* create an instance of the appropriate key type, and return it.
*
*/
virtual XSECCryptoKey * clonePublicKey() const = 0;
/**
* \brief Returns a string that identifies the crypto owner of this library.
*/
virtual const XMLCh * getProviderName() const = 0;
//@}
/** @name Load and Get the certificate */
//@{
/**
* \brief Load a certificate into the object.
*
* Take a base64 DER encoded certificate and load.
*
* @param buf A buffer containing the Base64 encoded certificate
* @param len The number of bytes of data in the certificate.
*/
virtual void loadX509Base64Bin(const char * buf, unsigned int len) = 0;
/**
* \brief Load a PEM encoded certificate into the object.
*
* Take a PEM encoded certificate and load.
*
* @param buf A buffer containing the PEM encoded certificate
* @param len The number of bytes of data in the certificate.
* (0 if the string is null terminated.)
*/
void loadX509PEM(const char * buf, unsigned int len = 0);
/**
* \brief Get a Base64 DER encoded copy of the certificate
*
* @returns A safeBuffer containing the DER encoded certificate
*/
virtual safeBuffer &getDEREncodingSB(void) = 0; // Get the DER string
/**
* \brief Get a Base64 DER encoded copy of the certificate
*
* @returns A safeBuffer containing the DER encoded certificate
*/
virtual const safeBuffer &getDEREncodingSB(void) const = 0; // Get the DER string
//@}
};
#endif /* XSECCRYPTOX509_INCLUDE */
| 25.486111 | 83 | 0.708992 |
bad5c2147b8f8a6ea7de87d310289fb411af4bf1 | 9,926 | cpp | C++ | Moco/Moco/Components/PositionMotion.cpp | zhengsizehrb/opensim-moco | 9844abc640a34d818a4bb21ef4fea3c3cb0f34ed | [
"Apache-2.0"
] | 41 | 2019-11-13T10:29:20.000Z | 2022-03-10T17:42:30.000Z | Moco/Moco/Components/PositionMotion.cpp | zhengsizehrb/opensim-moco | 9844abc640a34d818a4bb21ef4fea3c3cb0f34ed | [
"Apache-2.0"
] | 165 | 2019-11-13T00:55:57.000Z | 2022-03-04T19:02:26.000Z | Moco/Moco/Components/PositionMotion.cpp | zhengsizehrb/opensim-moco | 9844abc640a34d818a4bb21ef4fea3c3cb0f34ed | [
"Apache-2.0"
] | 15 | 2020-01-24T23:57:57.000Z | 2021-12-10T21:59:46.000Z | /* -------------------------------------------------------------------------- *
* OpenSim Moco: PositionMotion.cpp *
* -------------------------------------------------------------------------- *
* Copyright (c) 2019 Stanford University and the Authors *
* *
* Author(s): Christopher Dembia *
* *
* 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 "PositionMotion.h"
#include "../MocoUtilities.h"
#include <OpenSim/Common/Function.h>
#include <OpenSim/Common/GCVSplineSet.h>
#include <OpenSim/Simulation/Model/Model.h>
#include <OpenSim/Simulation/SimbodyEngine/Coordinate.h>
#include <OpenSim/Simulation/StatesTrajectory.h>
using namespace OpenSim;
class SimTKPositionMotionImplementation
: public SimTK::Motion::Custom::Implementation {
public:
void setFunctions(std::vector<Function*> functions) {
m_functions = std::move(functions);
}
SimTK::Motion::Level getLevel(const SimTK::State&) const override {
return SimTK::Motion::Level::Position;
}
/// nq: The number of generalized coordinates for this MobilizedBody.
/// q: The values of the generalized coordinates to set, with length nq.
void calcPrescribedPosition(
const SimTK::State& s, int nq, SimTK::Real* q) const override {
if (m_functions.size()) {
for (int i = 0; i < nq; ++i) {
m_funcArgs[0] = s.getTime();
q[i] = m_functions[i]->calcValue(m_funcArgs);
}
}
}
void calcPrescribedPositionDot(
const SimTK::State& s, int nq, SimTK::Real* qdot) const override {
if (m_functions.size()) {
for (int i = 0; i < nq; ++i) {
m_funcArgs[0] = s.getTime();
qdot[i] = m_functions[i]->calcDerivative(
m_qdotDerivComponents, m_funcArgs);
}
}
}
void calcPrescribedPositionDotDot(const SimTK::State& s, int nq,
SimTK::Real* qdotdot) const override {
if (m_functions.size()) {
for (int i = 0; i < nq; ++i) {
m_funcArgs[0] = s.getTime();
qdotdot[i] = m_functions[i]->calcDerivative(
m_qdotdotDerivComponents, m_funcArgs);
}
}
}
private:
std::vector<Function*> m_functions;
mutable SimTK::Vector m_funcArgs = SimTK::Vector(1);
static const std::vector<int> m_qdotDerivComponents;
static const std::vector<int> m_qdotdotDerivComponents;
};
const std::vector<int>
SimTKPositionMotionImplementation::m_qdotDerivComponents = {0};
const std::vector<int>
SimTKPositionMotionImplementation::m_qdotdotDerivComponents = {0, 0};
class SimTKPositionMotion : public SimTK::Motion::Custom {
public:
SimTKPositionMotion(SimTK::MobilizedBody& mobod)
: Motion::Custom(mobod, new SimTKPositionMotionImplementation()) {}
void setFunctions(std::vector<Function*> functions) {
static_cast<SimTKPositionMotionImplementation&>(updImplementation())
.setFunctions(std::move(functions));
}
};
void PositionMotion::setPositionForCoordinate(
const Coordinate& coord, const Function& position) {
const auto path = coord.getAbsolutePathString();
auto pos = std::unique_ptr<Function>(position.clone());
pos->setName(path);
if (get_functions().contains(path)) {
upd_functions().set(get_functions().getIndex(path), *pos);
} else {
upd_functions().adoptAndAppend(pos.release());
}
}
void PositionMotion::setEnabled(SimTK::State& state, bool enabled) const {
for (auto& motion : m_motions) {
if (enabled) {
motion.enable(state);
} else {
motion.disable(state);
}
}
}
bool PositionMotion::getEnabled(const SimTK::State& state) const {
if (m_motions.size() && !m_motions[0].isDisabled(state)) return true;
return false;
}
std::unique_ptr<PositionMotion> PositionMotion::createFromTable(
const Model& model, const TimeSeriesTable& table,
bool allowExtraColumns) {
auto posmot = std::unique_ptr<PositionMotion>(new PositionMotion());
const auto& labels = table.getColumnLabels();
// TODO: Avoid splining extra columns.
GCVSplineSet splines(table);
for (auto label : labels) {
std::string coordPath = label;
if (endsWith(label, "/value")) {
// This assumes that the coordinate is not named "value".
coordPath = label.substr(0, label.find("/value"));
const auto& coord = model.getComponent<Coordinate>(coordPath);
const auto path = coord.getAbsolutePathString();
posmot->setPositionForCoordinate(coord, splines.get(label));
} else {
OPENSIM_THROW_IF(!model.findComponent<Component>(coordPath) &&
!allowExtraColumns,
Exception, "Column '{}' is not a coordinate.", label);
}
}
return posmot;
}
std::unique_ptr<PositionMotion> PositionMotion::createFromStatesTrajectory(
const Model& model, const StatesTrajectory& statesTraj) {
const auto coords = model.getCoordinatesInMultibodyTreeOrder();
std::vector<std::string> coordSVNames;
for (const auto& coord : coords) {
coordSVNames.push_back(coord->getStateVariableNames()[0]);
}
return createFromTable(
model, statesTraj.exportToTable(model, coordSVNames));
}
TimeSeriesTable PositionMotion::exportToTable(
const std::vector<double>& time) const {
TimeSeriesTable table(time);
std::vector<std::string> labels;
SimTK::Vector value((int)time.size());
SimTK::Vector speed((int)time.size());
SimTK::Vector thisTime(1);
for (int ifunc = 0; ifunc < get_functions().getSize(); ++ifunc) {
for (int itime = 0; itime < (int)time.size(); ++itime) {
thisTime[0] = time[itime];
value[itime] = get_functions().get(ifunc).calcValue(thisTime);
speed[itime] = get_functions().get(ifunc).calcDerivative(
std::vector<int>{0}, thisTime);
}
const std::string& name = get_functions().get(ifunc).getName();
table.appendColumn(name + "/value", value);
table.appendColumn(name + "/speed", speed);
}
return table;
}
void PositionMotion::extendAddToSystem(SimTK::MultibodySystem& system) const {
Super::extendAddToSystem(system);
auto& matter = system.updMatterSubsystem();
m_motions.clear();
for (int imb = 0; imb < matter.getNumBodies(); ++imb) {
auto& mobod = matter.updMobilizedBody(SimTK::MobilizedBodyIndex(imb));
m_motions.push_back(SimTKPositionMotion(mobod));
m_motions.back().setDisabledByDefault(!get_default_enabled());
}
}
void PositionMotion::extendRealizeTopology(SimTK::State& state) const {
Super::extendRealizeTopology(state);
// Ensure all coordinates are prescribed.
const auto coords = getModel().getComponentList<Coordinate>();
for (const auto& coord : coords) {
const auto& path = coord.getAbsolutePathString();
OPENSIM_THROW_IF(!get_functions().contains(path), Exception,
"No function provided for coordinate '{}'.", path);
}
// Create a mapping from SimTK position DOFs to OpenSim Coordinates.
// We identify a SimTK DOF as a MobilizedBodyIndex and a Q index.
std::map<std::pair<SimTK::MobilizedBodyIndex, int>, std::string>
indicesToCoordName;
for (int i = 0; i < get_functions().getSize(); ++i) {
const auto& path = get_functions().get(i).getName();
const auto& coord = getModel().getComponent<Coordinate>(path);
const auto mbi = coord.getBodyIndex();
const auto qIndex = coord.getMobilizerQIndex();
indicesToCoordName[std::make_pair(mbi, qIndex)] = path;
}
auto& matter = getSystem().getMatterSubsystem();
for (SimTK::MobilizedBodyIndex mbi(0); mbi < matter.getNumBodies(); ++mbi) {
auto& mobod = matter.getMobilizedBody(mbi);
// Create the vector of functions to provide to the SimTK::Motion for
// this MobilizedBody.
std::vector<Function*> mobodFunctions;
for (int iq = 0; iq < mobod.getNumQ(state); ++iq) {
const auto key = std::make_pair(mbi, iq);
// This skips over unused quaternion slots, as indicesToCoordName
// doesn't have entries for such slots.
if (indicesToCoordName.count(key)) {
const auto& coordName = indicesToCoordName.at(key);
mobodFunctions.push_back(
const_cast<Function*>(&get_functions().get(coordName)));
}
}
auto& motion = const_cast<SimTK::Motion&>(m_motions[mbi]);
auto& customMotion = static_cast<SimTKPositionMotion&>(motion);
customMotion.setFunctions(std::move(mobodFunctions));
}
}
| 42.969697 | 80 | 0.600544 |
bad6779f3a43d884ba1d4858e69817cc2f488bb3 | 437 | hpp | C++ | src/util.hpp | alissonmoura/roc_namedpipe | 4f3078c9248520d1ce30f0d31fe0058e07a55998 | [
"MIT"
] | null | null | null | src/util.hpp | alissonmoura/roc_namedpipe | 4f3078c9248520d1ce30f0d31fe0058e07a55998 | [
"MIT"
] | null | null | null | src/util.hpp | alissonmoura/roc_namedpipe | 4f3078c9248520d1ce30f0d31fe0058e07a55998 | [
"MIT"
] | null | null | null | #pragma once
#include <string>
namespace util
{
/**
* @brief Get the namedpipe path. It will get the namedpipe path from the
* environment variable NAMED_PIPE_PATH. If it doesn't exist it will use the
* path: \\\\.\\pipe\\mynamedpipe
*
* @return std::string It returns the namedpipe path as string. The move
* semantics is done implicitly.
*/
std::string get_namedpipe_path();
constexpr auto BUFSIZE = 4096;
} // namespace util
| 24.277778 | 76 | 0.723112 |
bad6f1f81faf2ecb629adeb3a6be1f57467647e6 | 37,502 | cc | C++ | sws/modules/common/osacache.cc | ut-osa/syncchar | eba20da163260b6ae1ef3e334ad2137873a8d625 | [
"BSD-3-Clause"
] | null | null | null | sws/modules/common/osacache.cc | ut-osa/syncchar | eba20da163260b6ae1ef3e334ad2137873a8d625 | [
"BSD-3-Clause"
] | null | null | null | sws/modules/common/osacache.cc | ut-osa/syncchar | eba20da163260b6ae1ef3e334ad2137873a8d625 | [
"BSD-3-Clause"
] | 1 | 2019-05-14T16:36:45.000Z | 2019-05-14T16:36:45.000Z | // MetaTM Project
// File Name: osacache.cc
//
// Description:
//
// Operating Systems & Architecture Group
// University of Texas at Austin - Department of Computer Sciences
// Copyright 2006, 2007. All Rights Reserved.
// See LICENSE file for license terms.
#include "memaccess.h"
#include "osaassert.h"
#include "simulator.h"
#include "osacache.h"
#include "osacommon.h"
int gnCacheAttrs = -1;
const char ** gvszCacheStats = NULL;
// g-cache and tx-cache support a different
// set of statistics. Output of stats for
// caches is table-driven, so we just need
// different attribute tables for each.
// -------------------------------------
// G-CACHE statistics attributes:
// -------------------------------------
int gnGCacheAttrs = 17;
const char * gvszGCacheStats[] = {
"stat_copy_back",
"stat_data_read",
"stat_data_read_miss",
"stat_data_write",
"stat_data_write_miss",
"stat_dev_data_read",
"stat_dev_data_write",
"stat_inst_fetch",
"stat_inst_fetch_miss",
"stat_lost_stall_cycles",
"stat_mesi_exclusive_to_shared",
"stat_mesi_invalidate",
"stat_mesi_modified_to_shared",
"stat_transaction",
"stat_uc_data_read",
"stat_uc_data_write",
"stat_uc_inst_fetch",
NULL
};
// -------------------------------------
// TX-CACHE statistics attributes:
// -------------------------------------
int gnTxCacheAttrs = 66;
const char * gvszTxCacheStats[] = {
"stat_transactions",
"stat_dev_data_read",
"stat_dev_data_write",
"stat_uc_inst_fetch",
"stat_uc_data_read",
"stat_uc_data_write",
"stat_lost_stall_cycles",
"stat_data_read_miss",
"stat_inst_fetch_miss",
"stat_tmesi_invalidate",
"stat_tmesi_modified_to_shared",
"stat_tmesi_shared_to_modified",
"stat_tmesi_exclusive_to_shared",
"stat_tmesi_tm_to_ts",
"stat_tmesi_tm_to_tmi",
"stat_tmesi_ts_to_tmi",
"stat_tmesi_m_to_tm",
"stat_tmesi_m_to_tmi",
"stat_tmesi_m_to_ts",
"stat_tmesi_exclusive_to_modified",
"stat_tmesi_e_to_tmi",
"stat_tmesi_e_to_te",
"stat_tmesi_e_to_ts",
"stat_tmesi_s_to_tmi",
"stat_tmesi_s_to_ts",
"stat_tmesi_tm_to_m",
"stat_tmesi_tm_to_s",
"stat_tmesi_tmi_to_m",
"stat_tmesi_tmi_to_e",
"stat_tmesi_tmi_to_s",
"stat_tmesi_te_to_m",
"stat_tmesi_te_to_e",
"stat_tmesi_te_to_s",
"stat_tmesi_te_to_tmi",
"stat_tmesi_te_to_ts",
"stat_tmesi_ts_to_m",
"stat_tmesi_ts_to_e",
"stat_tmesi_ts_to_s",
"stat_conflicting_reads",
"stat_conflicting_write",
"stat_detected_conflicts",
"stat_local_undetected_conflicts",
"stat_predicted_conflicts",
"stat_unpredicted_conflicts",
"stat_asymmetric_conflicts",
"stat_data_write",
"stat_data_write_miss",
"stat_write_back",
"stat_overflow_count",
"stat_ov_conflicts",
"stat_data_read",
"stat_inst_fetch",
"stat_copy_back",
"stat_txR_miss",
"stat_txR_hit",
"stat_txW_miss",
"stat_txW_hit",
"stat_tx_upgrade",
"stat_tx_upgrade_noblock",
"stat_tx_commits",
"stat_tx_aborts",
"stat_tx_references",
"stat_tx_reads",
"stat_tx_writes",
"stat_stack_asymmetric_conflicts",
"stat_tx_early_releases",
NULL
};
const char * gvszTxsbStats[] = {
"stat_tx_memops",
"stat_tx_loads",
"stat_tx_stores",
"stat_tx_commits",
"stat_tx_aborts",
"stat_tx_overflows",
"stat_tx_conflicts",
"stat_tx_asymmetric_conflicts",
"stat_tx_coherence_inv",
"stat_memops",
"stat_unstallable",
"stat_loads",
"stat_stores",
"stat_coherence_inv",
"stat_loads_from_q",
"stat_tx_loads_from_q",
"stat_repeat_stores",
"stat_tx_repeat_stores",
"stat_total_latency",
"stat_cumulative_len",
"stat_cumulative_deferred",
"stat_enqueued_memops",
"stat_tx_enqueued_memops",
"stat_qfull_memops",
"stat_tx_qfull_memops",
"stat_max_qlen",
"stat_min_qlen",
"stat_qsamples",
NULL
};
/**
* initialize_cache_stats()
* Tx-cache and g-cache report a different set of statistics.
* We drive the reporting with a global table of stats attributes,
* so we select the proper table based on whether we're using
* a cache with transaction support.
*/
void initialize_cache_stats(bool busetx) {
gnCacheAttrs = busetx ? gnTxCacheAttrs : gnGCacheAttrs;
gvszCacheStats = busetx ? gvszTxCacheStats : gvszGCacheStats;
}
/**
* reset_one_cache_stats()
* Reset (by brute force!) all the statistics
* for a given cache pointed to by the conf_object_t *
* pCache.
*/
void reset_one_cache_stats( system_component_object_t * pCache )
{
integer_attribute_t av;
int nCacheAttrs = 0;
while( gvszCacheStats[nCacheAttrs] != NULL ) {
// av.u.integer = 0;
// av.kind = Sim_Val_Integer;
av = INT_ATTRIFY(0);
osa_sim_set_integer_attribute( pCache, gvszCacheStats[nCacheAttrs], &av );
nCacheAttrs++;
}
}
/**
* reset_one_storebuffer_stats()
* Reset all the statistics
* for a given store buffer
*/
void reset_one_storebuffer_stats(system_component_object_t * psb) {
integer_attribute_t av;
int nattrs = 0;
while(gvszTxsbStats[nattrs]) {
av = INT_ATTRIFY(0);
osa_sim_set_integer_attribute(psb, gvszTxsbStats[nattrs], &av);
nattrs++;
}
}
/**
* reset_cache_statistics()
* Called when OSA_CLEARSTATS magic breakpoint
* occurs--iterates over caches defined on the
* timing model chain, and resets statistics for
* devices on that chain.
*/
void reset_cache_statistics( int nCaches, const char *prefix )
{
int i;
char szICacheName[OSATXM_BUFSIZE];
char szDCacheName[OSATXM_BUFSIZE];
char szL2CacheName[OSATXM_BUFSIZE];
char szStorebufferName[OSATXM_BUFSIZE];
system_component_object_t * picache = NULL;
system_component_object_t * pdcache = NULL;
system_component_object_t * pl2cache = NULL;
system_component_object_t * pstorebuffer = NULL;
for (i=0; i<nCaches; i++) {
sprintf( szICacheName, "%sicache%d", prefix, i );
sprintf( szDCacheName, "%sdcache%d", prefix, i );
sprintf( szL2CacheName, "%sl2cache%d", prefix, i );
sprintf( szStorebufferName, "%ssb%d", prefix, i );
picache = osa_get_object_by_name( szICacheName );
pdcache = osa_get_object_by_name( szDCacheName );
pl2cache = osa_get_object_by_name( szL2CacheName );
pstorebuffer = osa_get_object_by_name( szStorebufferName );
if(picache != NULL)
reset_one_cache_stats( picache );
if(pdcache != NULL)
reset_one_cache_stats( pdcache );
if(pl2cache != NULL)
reset_one_cache_stats( pl2cache );
if(pstorebuffer != NULL)
reset_one_cache_stats( pstorebuffer );
// Clear the general exception that may have arisen if the
// caches don't exist
//OSA_TODO: SimExc_General??
if(osa_sim_get_error() == SimExc_General){
osa_sim_clear_error();
}
}
system_component_object_t * staller = NULL;
if(NULL != (staller = osa_get_object_by_name("staller"))) {
string_attribute_t av = STRING_ATTRIFY("");
osa_sim_set_string_attribute(staller, "statistics", &av );
}
}
/**
* dump_cache_stat_attrs()
* Iterate over the list of cache stats attrs
* available for caches, and print to the output
* stream the cache name, attribute name, and attribute
* value for the cache specified by the conf_object_t * pCache.
*/
void dump_cache_stat_attrs( ostream * pStream,
system_component_object_t * pCache,
char * lpszCacheName ) {
// integer_attribute_t av;
// integer_attribute_t *pAttrValue = &av;
int nCacheAttrs = 0;
while( gvszCacheStats[nCacheAttrs] != NULL ) {
//av = osa_sim_get_integer_attribute( pCache, gvszCacheStats[nCacheAttrs] );
int arg = osa_sim_get_integer_attribute( pCache, gvszCacheStats[nCacheAttrs] );
*pStream << lpszCacheName << ": " << gvszCacheStats[nCacheAttrs];
*pStream << ":\t" << arg << endl;
nCacheAttrs++;
// SIM_free_attribute(av);
}
}
/**
* tabular_cache_stat_attrs()
* Iterate over the list of cache stats attrs
* available for caches, and print to the output
* stream the cache name, attribute name, and attribute
* value for the cache specified by the conf_object_t * pCache.
* Output is in tabular form, with the delimiter
* specified.
*/
void tabular_cache_stat_attrs( ostream * pStream,
system_component_object_t * pCache,
char * lpszCacheName,
const char * lpszDelimiter,
bool bRowNames ) {
// integer_attribute_t av;
//integer_attribute_t *pAttrValue = &av;
int nCacheAttrs = 0;
if( bRowNames )
*pStream << lpszCacheName << lpszDelimiter;
while( gvszCacheStats[nCacheAttrs] != NULL ) {
//av = osa_sim_get_integer_attribute( pCache, gvszCacheStats[nCacheAttrs] );
int arg = osa_sim_get_integer_attribute( pCache, gvszCacheStats[nCacheAttrs] );
//*pStream << INTEGER_ARGUMENT << lpszDelimiter;
*pStream << arg << lpszDelimiter;
nCacheAttrs++;
// osa_sim_free_attribute(av);
}
*pStream << endl;
}
/**
* dump_cache_table_headers()
* Dump a delimiter-separated list of column
* names. If the bRowNames flag is set, this
* means the number of columns needs to be shifted
* one to accomodate the extra column
*/
void dump_cache_table_headers( ostream * pStream,
const char * lpszDelimiter,
bool bRowNames,
bool bColNames ) {
if( !bColNames )
return;
int nCacheAttrs = 0;
if( bRowNames )
*pStream << "" << lpszDelimiter;
while( gvszCacheStats[nCacheAttrs] != NULL ) {
*pStream << gvszCacheStats[nCacheAttrs] << lpszDelimiter;
nCacheAttrs++;
}
*pStream << endl;
}
/**
* dump_sb_stat_attrs()
* Iterate over the list of storebuffer stats attrs
* available for caches, and print to the output
* stream the cache name, attribute name, and attribute
* value for the cache specified by the conf_object_t * ptxsb.
*/
void dump_sb_stat_attrs(ostream * pStream,
system_component_object_t * ptxsb,
char * lpsz) {
int nCacheAttrs = 0;
while(gvszTxsbStats[nCacheAttrs] != NULL ) {
int arg = osa_sim_get_integer_attribute( ptxsb, gvszTxsbStats[nCacheAttrs] );
*pStream << lpsz << ": " << gvszTxsbStats[nCacheAttrs];
*pStream << ":\t" << arg << endl;
nCacheAttrs++;
}
}
/**
* tabular_sb_stat_attrs()
* Iterate over the list of storebuffer stats attrs
* available for caches, and print to the output
* stream the store buffer name, attribute name, and attribute.
* Output is in tabular form, with the delimiter
* specified.
*/
void tabular_sb_stat_attrs(ostream * pStream,
system_component_object_t * ptxsb,
char * lpsz,
const char * lpszDelimiter,
bool bRowNames) {
int nCacheAttrs = 0;
if( bRowNames )
*pStream << lpsz << lpszDelimiter;
while( gvszTxsbStats[nCacheAttrs] != NULL ) {
int arg = osa_sim_get_integer_attribute(ptxsb, gvszTxsbStats[nCacheAttrs] );
*pStream << arg << lpszDelimiter;
nCacheAttrs++;
}
*pStream << endl;
}
/**
* dump_sb_table_headers()
* Dump a delimiter-separated list of column
* names. If the bRowNames flag is set, this
* means the number of columns needs to be shifted
* one to accomodate the extra column
*/
void dump_sb_table_headers(ostream * pStream,
const char * lpszDelimiter,
bool bRowNames,
bool bColNames ) {
if( !bColNames )
return;
int nCacheAttrs = 0;
if( bRowNames )
*pStream << "" << lpszDelimiter;
while( gvszTxsbStats[nCacheAttrs] != NULL ) {
*pStream << gvszTxsbStats[nCacheAttrs] << lpszDelimiter;
nCacheAttrs++;
}
*pStream << endl;
}
/**
* dump_cache_statistics()
* Called when OSA_DUMPSTATS magic breakpoint
* occurs--iterates over caches defined on the
* timing model chain, and dumps statistics for
* devices on that chain to the ostream supplied.
*/
void dump_cache_statistics( int nCaches,
ostream * pStream,
int bTabular,
const char * lpszDelim,
bool bRowNames,
bool bColNames,
const char *prefix) {
int i;
char szsb[OSATXM_BUFSIZE];
char szICacheName[OSATXM_BUFSIZE];
char szDCacheName[OSATXM_BUFSIZE];
char szL2CacheName[OSATXM_BUFSIZE];
system_component_object_t * picache = NULL;
system_component_object_t * pdcache = NULL;
system_component_object_t * pl2cache = NULL;
system_component_object_t * pstorebuffer = NULL;
system_component_object_t * pstaller = NULL;
for (i=0; i<nCaches; i++) {
sprintf( szICacheName, "%sicache%d", prefix, i );
sprintf( szDCacheName, "%sdcache%d", prefix, i );
sprintf( szL2CacheName, "%sl2cache%d", prefix, i );
picache = osa_get_object_by_name( szICacheName );
pdcache = osa_get_object_by_name( szDCacheName );
pl2cache = osa_get_object_by_name( szL2CacheName );
*pStream << "Cache Statistics for CPU " << i << ": (";
if(picache) *pStream << szICacheName << ",";
if(pdcache) *pStream << szDCacheName;
if(pl2cache) *pStream << ", " << szL2CacheName;
*pStream << ")" << endl;
*pStream << "--------------------------------------------------" << endl;
if( bTabular ) {
dump_cache_table_headers( pStream, lpszDelim, true, true );
if(picache != NULL)
tabular_cache_stat_attrs( pStream, picache, szICacheName, lpszDelim, true );
if(pdcache != NULL){
tabular_cache_stat_attrs( pStream, pdcache, szDCacheName, lpszDelim, true );
}
if(pl2cache != NULL)
tabular_cache_stat_attrs( pStream, pl2cache, szL2CacheName, lpszDelim, true );
} else {
if(picache != NULL)
dump_cache_stat_attrs( pStream, picache, szICacheName );
if(pdcache != NULL)
dump_cache_stat_attrs( pStream, pdcache, szDCacheName );
if(pl2cache != NULL)
dump_cache_stat_attrs( pStream, pl2cache, szL2CacheName );
}
// Clear the general exception that may have arisen if the
// caches don't exist
if (osa_sim_get_error() != NO_ERROR){
osa_sim_clear_error();
}
}
*pStream << "--------------------------------------------------" << endl;
for (i=0; i<nCaches; i++) {
sprintf( szsb, "%ssb%d", prefix, i );
pstorebuffer = osa_get_object_by_name( szsb );
if(!pstorebuffer)
continue;
*pStream << "Store Buffer Statistics for CPU " << i << ": (";
if(pstorebuffer) *pStream << szsb;
*pStream << ")" << endl;
*pStream << "--------------------------------------------------" << endl;
if( bTabular ) {
dump_sb_table_headers( pStream, lpszDelim, true, true );
tabular_sb_stat_attrs( pStream, pstorebuffer, szsb, lpszDelim, true );
} else {
dump_sb_stat_attrs( pStream, pstorebuffer, szsb );
}
// Clear the general exception that may have arisen if the
// caches don't exist
if (osa_sim_get_error() != NO_ERROR){
osa_sim_clear_error();
}
}
*pStream << "--------------------------------------------------" << endl;
pstaller = osa_get_object_by_name("staller");
if(pstaller) {
attr_value_t statsattr = SIM_get_attribute(pstaller, "statistics");
string ststats = statsattr.u.string;
*pStream << "Staller statistics" << endl;
*pStream << ststats;
*pStream << "Staller time series" << endl;
attr_value_t epochlist;
attr_value_t avlist = SIM_get_attribute(pstaller, "epoch_time_series");
for(int i=0; i<avlist.u.list.size; i++) {
epochlist = avlist.u.list.vector[i];
int epochsize = epochlist.u.list.size;
*pStream << "[";
for(int j=0; j<epochsize; j++) {
*pStream << epochlist.u.list.vector[j].u.floating;
if(j!=epochsize-1) *pStream << ",";
}
*pStream << "]" << endl;
}
*pStream << "--------------------------------------------------" << endl;
}
}
/*
* If the timing_model attribute is set, we need to
* also pass the memory transaction on to it, and
* add any cycle cost estimates it returns to the
* current penalty. We cannot, however, return 0 and
* expect consistent results. If the rest of the timing
* chain fails to come up with anything reasonable,
* return a 1 cycle penalty to ensure forward progress.
*/
osa_cycles_t
collect_cache_timing( TIMING_SIGNATURE )
{
int penalty = 0;
osamod_t * pOsaTxm = (osamod_t *) pConfObject;
/*
* Here we distribute the memory transaction to
* any attribute/interface that is registered as
* interested in the the timing_model interface
* half of memory transactions. For osatxm, there
* are two such attributes:
* 1) timing_model
* 2) caches.
* ---------------------------
* Collect mem-transaction penalty in cycles
* for both (Both should probably not be set or
* we will over-charge for the memory operation!).
*/
if( pOsaTxm->ppCaches != NULL
&& !((pOsaTxm->type == SYNCCHAR ||
pOsaTxm->type == SYNCCOUNT ||
pOsaTxm->type == COMMON
)// Don't "double-count" cycles if modules are chained
&& pOsaTxm->timing_model != NULL)) {
int nProcessor = pOsaTxm->minfo->getCpuNum(OSA_get_sim_cpu());
int nCaches = pOsaTxm->nCaches;
if( nProcessor >= nCaches ) {
cout << "collect_cache_timing: SEVERE ERROR: nCaches = " << nCaches << "\n";
}
if( pOsaTxm->tx_trace && false ) {
cout << "mem tx src cpu:" << nProcessor << "-> cache timing chain\n";
}
timing_model_interface_t * pTIfc = pOsaTxm->ppCachesIfc[nProcessor];
conf_object_t * pCache = pOsaTxm->ppCaches[nProcessor];
OSA_assert( pTIfc != NULL , pOsaTxm);
OSA_assert( pCache != NULL , pOsaTxm);
penalty += pTIfc->operate( TIMING_ARGUMENTS_1 );
}
if( pOsaTxm->timing_model != NULL ) {
if( pOsaTxm->tx_trace ) {
// Before uncommenting this, know that it build breaks on 64-bit..
// fprintf( stdout, "pOsaTxm = %08x, g_osatxm = %08x\n",
// (unsigned int) pOsaTxm,
// (unsigned int) g_osatxm );
// fprintf( stdout, "pOsaTxm->timing_ifc = %08x, pOsaTxm->timing_model = %08x\n",
// (unsigned int) pOsaTxm->timing_ifc,
// (unsigned int) pOsaTxm->timing_model );
}
penalty += pOsaTxm->timing_ifc->operate( TIMING_ARGUMENTS_2 );
}
return penalty;
}
/**
* set_timing_model()
* set the timing model attribute
* which allows timing model chaining
*/
osa_attr_set_t
set_timing_model( SIMULATOR_SET_GENERIC_ATTRIBUTE_SIGNATURE )
{
osamod_t *pOsaTxm = (osamod_t *) obj;
#ifdef _USE_SIMICS //OSA_TODO What about QEMU?
if( pAttrValue->kind == Sim_Val_Nil) {
pOsaTxm->timing_model = NULL;
pOsaTxm->timing_ifc = NULL;
} else
#endif
{
pOsaTxm->timing_ifc = (timing_model_interface_t *)
osa_sim_get_interface( GENERIC_ARGUMENT,
TIMING_MODEL_INTERFACE);
if( osa_sim_clear_error() ) {
//OSA_TODO
#ifdef _USE_SIMICS
SIM_log_error( &pOsaTxm->log, 1,
"osatxm::set_timing_model: "
"object '%s' does not provide the timing model "
"interface.", pAttrValue->u.object->name );
#endif
return INTERFACE_NOT_FOUND_ERR;
}
pOsaTxm->timing_model = GENERIC_ARGUMENT;
}
return ATTR_OK;
}
/**
* get_timing_model()
* get the timing model attribute
* which allows timing model chaining
*/
generic_attribute_t
get_timing_model( SIMULATOR_GET_ATTRIBUTE_SIGNATURE )
{
osamod_t *pOsaTxm = (osamod_t *)obj;
return GENERIC_ATTRIFY(pOsaTxm->timing_model);
}
/**
* set_caches()
* set the list of caches,
* which is a simics list attribute
* containing per-cpu caches interested
* in knowing about memory transactions
* the bus.
*/
osa_attr_set_t //OSA_TODO: Lots of work needed here
set_caches( SIMULATOR_SET_LIST_ATTRIBUTE_SIGNATURE )
{
int i;
generic_attribute_t *pCache = NULL;
osamod_t * pOsaTxm = (osamod_t*) obj;
int nCaches = LIST_ARGUMENT_SIZE;
MM_FREE( pOsaTxm->ppCaches );
MM_FREE( pOsaTxm->ppCachesIfc );
pOsaTxm->nCaches = nCaches;
pOsaTxm->ppCaches = MM_MALLOC( nCaches, system_component_object_t *);
pOsaTxm->ppCachesIfc = MM_MALLOC( nCaches, timing_model_interface_t * );
for( i=0; i<nCaches; i++ ) {
pCache = &LIST_ARGUMENT(i);
pOsaTxm->ppCachesIfc[i] = (timing_model_interface_t *)
osa_sim_get_interface( GENERIC_ATTR(*pCache),
TIMING_MODEL_INTERFACE );
if( osa_sim_clear_error()) {
#ifdef _USE_SIMICS
SIM_log_error( &pOsaTxm->log, 1,
"set_caches: "
"object %d does not provide the timing model "
"listen interface.", i);
#else
std::cout << "\nset caches: object "
<< i <<" does not provide the timing model listen interface.";
#endif
pOsaTxm->nCaches = 0;
MM_FREE(pOsaTxm->ppCaches);
MM_FREE(pOsaTxm->ppCachesIfc);
pOsaTxm->ppCaches = NULL;
pOsaTxm->ppCachesIfc = NULL;
return INTERFACE_NOT_FOUND_ERR;
}
pOsaTxm->ppCaches[i] = pCache->u.object;
}
return ATTR_OK;
}
/**
* get_caches()
* get the list of caches,
* which is a simics list attribute
* containing per-cpu cache objects interested
* in knowing about memory transactions
* the bus.
*/
list_attribute_t
get_caches( SIMULATOR_GET_ATTRIBUTE_SIGNATURE )
{
int i;
list_attribute_t avReturn;
osamod_t * pOsaTxm = (osamod_t *) obj;
#ifdef _USE_SIMICS
avReturn.kind = Sim_Val_Nil;
#endif
if( pOsaTxm->ppCaches ) {
avReturn = osa_sim_allocate_list(pOsaTxm->nCaches);
/*
avReturn.kind = Sim_Val_List;
avReturn.u.list.vector = MM_MALLOC( pOsaTxm->nCaches, attr_value_t);
avReturn.u.list.size = pOsaTxm->nCaches;
*/
for (i=0; i<pOsaTxm->nCaches; i++) {
/*avReturn.u.list.vector[i].kind = Sim_Val_Object;
avReturn.u.list.vector[i].u.object = pOsaTxm->ppCaches[i];
*/
LIST_ATTR(avReturn, i) = GENERIC_ATTRIFY(pOsaTxm->ppCaches[i]);
}
}
return avReturn;
}
/*
* find_staller
* chase through the cache hierarchy until we find a staller
* object, or conclude that one is not present. Don't assume
* a particular structure to the hierarchy, other than that
* there must be a splitter at the cpu (for i/d).
*/
system_component_object_t *
find_staller(system_component_object_t *pConfObject, int procNum) {
osamod_t * osamod = (osamod_t *) pConfObject;
system_component_object_t *pstorebuffer = NULL;
system_component_object_t *pcache = NULL;
system_component_object_t *pstaller = NULL;
system_component_object_t *psplitter = NULL;
system_component_object_t *pbranch = NULL;
if(NULL == osamod->ppCaches) return NULL;
if(NULL == (psplitter = osamod->ppCaches[procNum]))
goto clear_exception;
if(NULL == (pbranch = osa_sim_get_generic_attribute(psplitter, "dbranch")))
goto clear_exception;
if(NULL == (pstorebuffer = osa_sim_get_generic_attribute(pbranch, "cache")))
goto clear_exception;
if(NULL == (pcache = osa_sim_get_generic_attribute(pstorebuffer, "timing_model")))
goto clear_exception;
do {
/* follow timing_model connections until we find a staller */
if(NULL == (pstaller = osa_sim_get_generic_attribute(pcache, "timing_model")))
goto clear_exception;
pcache = pstaller;
} while(strncmp(pstaller->name, "staller", strlen("staller")));
return pstaller;
clear_exception:
if (osa_sim_get_error ()!= NO_ERROR)
osa_sim_clear_error();
return NULL;
}
/*
* find_l1_dcache
* chase through the cache hierarchy until we find a staller
* object, or conclude that one is not present. Don't assume
* a particular structure to the hierarchy, other than that
* there must be a splitter at the cpu (for i/d).
*/
system_component_object_t *
find_l1_dcache(system_component_object_t *pConfObject, int procNum) {
osamod_t * osamod = (osamod_t *) pConfObject;
system_component_object_t *pstorebuffer = NULL;
system_component_object_t *pcache = NULL;
system_component_object_t *psplitter = NULL;
system_component_object_t *pbranch = NULL;
if(NULL == osamod->ppCaches) return NULL;
if(NULL == (psplitter = osamod->ppCaches[procNum]))
goto clear_exception;
if(NULL == (pbranch = osa_sim_get_generic_attribute(psplitter, "dbranch")))
goto clear_exception;
if(NULL == (pstorebuffer = osa_sim_get_generic_attribute(pbranch, "cache")))
goto clear_exception;
if(NULL == (pcache = osa_sim_get_generic_attribute(pstorebuffer, "timing_model")))
goto clear_exception;
return pcache;
clear_exception:
if (osa_sim_get_error ()!= NO_ERROR)
osa_sim_clear_error();
return NULL;
}
/*
* hierarchy_entry
* get a pointer to the object at the top
* of the cache hierarchy.
*/
system_component_object_t *
hierarchy_entry(system_component_object_t *pConfObject, int procNum) {
osamod_t * osamod = (osamod_t *) pConfObject;
system_component_object_t *psplitter = NULL;
if(NULL == osamod->ppCaches) return NULL;
if(NULL == (psplitter = osamod->ppCaches[procNum]))
goto clear_exception;
return psplitter;
clear_exception:
if (osa_sim_get_error ()!= NO_ERROR)
osa_sim_clear_error();
return NULL;
}
/*
* memhier_exercise
* perform a load or store in the memory hierarchy--
* this only exercises the traffic and computes latency. No data are
* actually read or written to or from physmem. NB: caller must
* provide logical to physical mapping!
*/
osa_cycles_t
memhier_exercise(system_component_object_t * obj,
osa_logical_address_t laddr,
osa_physical_address_t paddr,
unsigned int bytes,
int procNum,
bool isread) {
osa_cycles_t latency = 0;
timing_model_interface_t * ifc = NULL;
system_component_object_t * top = hierarchy_entry(obj, procNum);
if(top) {
generic_transaction_t mt;
memset(&mt, 0, sizeof mt);
mt.logical_address = laddr;
mt.physical_address = paddr;
mt.size = bytes;
mt.may_stall = 1;
mt.ini_type = Sim_Initiator_CPU;
mt.ini_ptr = (conf_object_t *) obj;
mt.exception = Sim_PE_No_Exception;
SIM_set_mem_op_type(&mt, isread ? Sim_Trans_Load : Sim_Trans_Store);
ifc = (timing_model_interface_t *) SIM_get_interface(top,
TIMING_MODEL_INTERFACE);
if(ifc) {
latency += ifc->operate(top, NULL, NULL, &mt);
}
if(osa_sim_get_error ()!= NO_ERROR)
osa_sim_clear_error();
}
return latency;
}
/*
* memhier_load()
* perform a load in the memory hierarchy.
*/
osa_cycles_t
memhier_load(system_component_object_t * obj,
osa_logical_address_t laddr,
osa_physical_address_t paddr,
unsigned int bytes,
int procNum) {
return memhier_exercise(obj,
laddr,
paddr,
bytes,
procNum,
true);
}
/*
* memhier_store()
* perform a store in the memory hierarchy.
*/
osa_cycles_t
memhier_store(system_component_object_t * obj,
osa_logical_address_t laddr,
osa_physical_address_t paddr,
unsigned int bytes,
int procNum) {
return memhier_exercise(obj,
laddr,
paddr,
bytes,
procNum,
false);
}
/*
* memhier_load_block
* perform a load in the memory hierarchy with
* given granularity--this only exercises the traffic
* and computes latency. No data are actually read from
* physmem. WARNING: if the memop crosses a cache line
* boundary, this routine will miss it--achtung!
*/
osa_cycles_t
memhier_load_block(system_component_object_t * obj,
osa_logical_address_t laddr,
osa_physical_address_t paddr,
unsigned int granularity,
unsigned int bytes,
int procNum) {
return memhier_load(obj,
laddr & ~(granularity-1),
paddr & ~(granularity-1),
granularity,
procNum);
}
/*
* memhier_store_block
* perform a store in the memory hierarchy with
* given granularity--this only exercises the traffic
* and computes latency. No data are actually written to
* physmem. WARNING: if the memop crosses a cache line
* boundary, this routine will miss it!
*/
osa_cycles_t
memhier_store_block(system_component_object_t * obj,
osa_logical_address_t laddr,
osa_physical_address_t paddr,
unsigned int granularity,
unsigned int bytes,
int procNum) {
return memhier_store(obj,
laddr & ~(granularity-1),
paddr & ~(granularity-1),
granularity,
procNum);
}
/*
* find_storebuffer
* chase through the cache hierarchy until we find a storebuffer
*/
system_component_object_t *
find_storebuffer(system_component_object_t *pConfObject, int procNum) {
osamod_t * osamod = (osamod_t *) pConfObject;
system_component_object_t *pstorebuffer = NULL;
system_component_object_t *psplitter = NULL;
system_component_object_t *pbranch = NULL;
if(NULL == osamod->ppCaches) return NULL;
if(NULL == (psplitter = osamod->ppCaches[procNum]))
goto clear_exception;
if(NULL == (pbranch = osa_sim_get_generic_attribute(psplitter, "dbranch")))
goto clear_exception;
if(NULL == (pstorebuffer = osa_sim_get_generic_attribute(pbranch, "cache")))
goto clear_exception;
return pstorebuffer;
clear_exception:
if (osa_sim_get_error ()!= NO_ERROR)
osa_sim_clear_error();
return NULL;
}
int get_l1_dcache_size(system_component_object_t *pConfObject, int procNum) {
int size = 0;
osamod_t * osamod = (osamod_t *) pConfObject;
if(!osamod->ppCaches) return size;
conf_object_t *pdcache = find_l1_dcache(pConfObject, procNum);
if (pdcache != NULL) {
int line_number = osa_sim_get_integer_attribute(pdcache, "config_line_number");
int line_size = osa_sim_get_integer_attribute(pdcache, "config_line_size");
size = line_number * line_size;
} else {
if (osa_sim_get_error ()!= NO_ERROR) {
osa_sim_clear_error();
}
}
return size;
}
unsigned int
get_txcache_size(system_component_object_t *pConfObject, int procNum) {
return get_l1_dcache_size(pConfObject, procNum);
}
unsigned int
get_txcache_block_size(system_component_object_t *pConfObject, int procNum) {
int size = 0;
osamod_t * osamod = (osamod_t *) pConfObject;
if(!osamod->ppCaches || !osamod->ppCaches[procNum]) return 0;
conf_object_t * pdcache = find_l1_dcache(pConfObject, procNum);
if (pdcache != NULL) {
size = osa_sim_get_integer_attribute(pdcache, "config_line_size");
} else {
if(osa_sim_get_error ()!= NO_ERROR) {
osa_sim_clear_error();
}
}
return size;
}
/*
* get_cache_perturb
* chase down the cache hierarchy until we find a staller,
* which is assumed to be a trans-staller-plus, from which
* we can extract the cache perturbation attributes.
* Technically, we could probably just use the global
* staller object, but this technique is more general,
* and since we're only going to do this once at startup,
* the performance hit of traversing the whole heirarchy
* is not such a big deal.
*/
void get_cache_perturb(system_component_object_t *pConfObject,
int procNum,
int *pcache_perturb,
int *pcache_seed) {
osamod_t * osamod = (osamod_t *) pConfObject;
system_component_object_t *pstaller = NULL;
OSA_assert((pcache_perturb && pcache_seed), osamod);
*pcache_perturb = *pcache_seed = 0;
if(NULL == osamod->ppCaches) return;
if(NULL == (pstaller = find_staller(pConfObject, procNum)))
return;
*pcache_perturb = osa_sim_get_integer_attribute(pstaller, "cache_perturb");
*pcache_seed = osa_sim_get_integer_attribute(pstaller, "seed");
return;
}
void enable_cache_perturb(system_component_object_t *pConfObject, int procNum){
osamod_t * osamod = (osamod_t *) pConfObject;
if(!osamod->nCaches)
return; // nothing to do!
system_component_object_t *pstaller = NULL;
boolean_attribute_t av = BOOL_ATTRIFY(1);
if(NULL == osamod->ppCaches){
cout << "Warning - cannot enable cache perturbation without the cache hierarchy" << endl;
return;
}
if(NULL == (pstaller = find_staller(pConfObject, procNum)))
return;
if(ATTR_OK != osa_sim_set_boolean_attribute(pstaller, "past_bios", &av))
goto clear_exception;
return;
clear_exception:
if (osa_sim_get_error ()!= NO_ERROR)
osa_sim_clear_error();
}
osa_cycles_t commitTxCache(system_component_object_t *obj,
int currentTxID) {
osa_cycles_t latency = 0;
abort_commit_interface_t * ifc = NULL;
system_component_object_t * pdcache = NULL;
system_component_object_t * pstorebuffer = NULL;
osamod_t * osamod = (osamod_t *) obj;
int procNum = osamod->minfo->getCpuNum(OSA_get_sim_cpu());
if(!osamod->use_txcache ||
!osamod->ppCaches ||
!osamod->ppCaches[procNum])
goto clear_exception;
if(NULL == (pdcache = find_l1_dcache(obj, procNum)))
goto clear_exception;
osamod->abort_commit_ifc = (abort_commit_interface_t *) osa_sim_get_interface(pdcache, "abort-commit-interface");
latency += osamod->abort_commit_ifc->commitTx(pdcache, currentTxID);
if(NULL == (pstorebuffer = find_storebuffer(obj, procNum)))
goto clear_exception;
ifc = (abort_commit_interface_t *) osa_sim_get_interface(pstorebuffer, "abort-commit-interface");
latency += ifc->commitTx(pstorebuffer, currentTxID);
return latency;
clear_exception:
if (osa_sim_get_error ()!= NO_ERROR)
osa_sim_clear_error();
return latency;
}
osa_cycles_t abortTxCache(conf_object_t * obj, int currentTxID, int procNum) {
osa_cycles_t latency = 0;
osamod_t * osamod = (osamod_t *) obj;
conf_object_t *pdcache = NULL;
conf_object_t *pstorebuffer = NULL;
abort_commit_interface_t * ifc = NULL;
if(!osamod->use_txcache || !osamod->ppCaches)
goto clear_exception;
if(NULL == (pdcache = find_l1_dcache(obj, procNum)))
goto clear_exception;
osamod->abort_commit_ifc = (abort_commit_interface_t *) osa_sim_get_interface(pdcache, "abort-commit-interface");
latency += osamod->abort_commit_ifc->abortTx(pdcache, currentTxID);
if(NULL == (pstorebuffer = find_storebuffer(obj, procNum)))
goto clear_exception;
ifc = (abort_commit_interface_t *) osa_sim_get_interface(pstorebuffer, "abort-commit-interface");
latency += ifc->abortTx(pstorebuffer, currentTxID);
return latency;
clear_exception:
if (SIM_get_pending_exception ()!= NO_ERROR)
SIM_clear_exception();
return latency;
}
void earlyRelease(system_component_object_t *obj,
osa_physical_address_t paddr,
osa_logical_address_t laddr,
int currentTxID) {
abort_commit_interface_t * ifc = NULL;
system_component_object_t *pdcache = NULL;
system_component_object_t *pstorebuffer = NULL;
osamod_t * osamod = (osamod_t *) obj;
int procNum = osamod->minfo->getCpuNum(OSA_get_sim_cpu());
if(!osamod->use_txcache ||
!osamod->ppCaches ||
!osamod->ppCaches[procNum])
goto clear_exception;
if(NULL == (pdcache = find_l1_dcache(obj, procNum)))
goto clear_exception;
osamod->abort_commit_ifc = (abort_commit_interface_t *) osa_sim_get_interface(pdcache, "abort-commit-interface");
osamod->abort_commit_ifc->earlyRelease(pdcache, paddr, laddr, currentTxID);
if(NULL == (pstorebuffer = find_storebuffer(obj, procNum)))
goto clear_exception;
ifc = (abort_commit_interface_t *) osa_sim_get_interface(pstorebuffer, "abort-commit-interface");
ifc->earlyRelease(pstorebuffer, paddr, laddr, currentTxID);
return;
clear_exception:
if (osa_sim_get_error ()!= NO_ERROR)
osa_sim_clear_error();
}
/*
* Local variables:
* c-indent-level: 3
* c-basic-offset: 3
* indent-tabs-mode: nil
* tab-width: 3
* End:
*
* vim: ts=3 sw=3 expandtab
*/
| 33.070547 | 116 | 0.646259 |