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
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
00940a2d2a02f324c3845e9a512067369e849058
570
cpp
C++
src/treeitem.cpp
jakobtroidl/Barrio
55c447325f2e83a21b39c54cdca37b2779d0569c
[ "MIT" ]
null
null
null
src/treeitem.cpp
jakobtroidl/Barrio
55c447325f2e83a21b39c54cdca37b2779d0569c
[ "MIT" ]
3
2021-11-02T22:24:04.000Z
2021-11-29T18:01:51.000Z
src/treeitem.cpp
jakobtroidl/Barrio
55c447325f2e83a21b39c54cdca37b2779d0569c
[ "MIT" ]
null
null
null
#include "treeitem.h" TreeItem::TreeItem(const QVector<QVariant>& data, TreeItem* parentItem) :m_itemData(data), m_parentItem(parentItem) { } TreeItem::~TreeItem() { } void TreeItem::appendChild(TreeItem* child) { m_childItems.append(child); } TreeItem* TreeItem::child(int row) { return nullptr; } int TreeItem::childCount() const { return 0; } int TreeItem::columnCount() const { return 0; } QVariant TreeItem::data(int column) const { return QVariant(); } int TreeItem::row() const { return 0; } TreeItem* TreeItem::parentItem() { return nullptr; }
12.12766
71
0.710526
jakobtroidl
0099f28213d21ba94b8f4663d000f92f5a22538c
2,403
cpp
C++
PDFImagesExample/src/ofApp.cpp
emodz/DM-GY-9103-Advanced-Creative-Coding
b1298ed6b0f067715437e51ca5e8f99b95ace01a
[ "MIT" ]
29
2018-01-26T00:34:06.000Z
2022-02-15T18:51:49.000Z
PDFImagesExample/src/ofApp.cpp
emodz/DM-GY-9103-Advanced-Creative-Coding
b1298ed6b0f067715437e51ca5e8f99b95ace01a
[ "MIT" ]
2
2018-02-16T00:50:17.000Z
2018-02-16T01:15:34.000Z
PDFImagesExample/src/ofApp.cpp
emodz/DM-GY-9103-Advanced-Creative-Coding
b1298ed6b0f067715437e51ca5e8f99b95ace01a
[ "MIT" ]
11
2018-01-26T00:08:46.000Z
2019-05-30T05:15:15.000Z
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ pdfRendering = false; ofBackground(225,225,225); ofSetVerticalSync(true); grabber.setup(ofGetWidth()/2, ofGetHeight()/2); } //-------------------------------------------------------------- void ofApp::update(){ grabber.update(); frame.setFromPixels(grabber.getPixels()); } //-------------------------------------------------------------- void ofApp::draw(){ ofSetRectMode(OF_RECTMODE_CENTER); //you need to draw the ofImage in order //for it to render in the PDF frame.draw(ofGetWidth()/2, ofGetHeight()/2, ofGetWidth(), ofGetHeight()); ofSetColor(54); if( pdfRendering ){ ofDrawBitmapString("press r to stop pdf multipage rendering", 32, 92); }else{ ofDrawBitmapString("press r to start pdf multipage rendering", 32, 92); ofSetHexColor(0xffffff); } } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ if( key=='r'){ pdfRendering = !pdfRendering; if( pdfRendering ){ ofSetFrameRate(12); // so it doesn't generate tons of pages ofBeginSaveScreenAsPDF("recording-"+ofGetTimestampString()+".pdf", true); }else{ ofSetFrameRate(60); ofEndSaveScreenAsPDF(); } } } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
23.330097
76
0.427382
emodz
009d7e145e2cf11aecf3eeb91baf1623cc474051
41,098
cpp
C++
tx2-setup/robust_pose_graph_optimization/buzz_slam/src/slam/buzz_slam_closures.cpp
SnowCarter/DOOR-SLAM
cf56d2b4b7a21ed7c6445f01600408c9dd5235c6
[ "MIT" ]
3
2021-07-05T17:59:01.000Z
2022-03-31T12:46:25.000Z
tx2-setup/robust_pose_graph_optimization/buzz_slam/src/slam/buzz_slam_closures.cpp
SnowCarter/DOOR-SLAM
cf56d2b4b7a21ed7c6445f01600408c9dd5235c6
[ "MIT" ]
null
null
null
tx2-setup/robust_pose_graph_optimization/buzz_slam/src/slam/buzz_slam_closures.cpp
SnowCarter/DOOR-SLAM
cf56d2b4b7a21ed7c6445f01600408c9dd5235c6
[ "MIT" ]
3
2020-03-25T16:21:25.000Z
2021-07-05T16:37:34.000Z
#include "buzz_slam_singleton.h" namespace buzz_slam { /****************************************/ /************ Buzz Closures *************/ /****************************************/ static int BuzzInitOptimizer(buzzvm_t vm){ // Initialize optimizer buzzvm_pushs(vm, buzzvm_string_register(vm, "controller", 1)); buzzvm_gload(vm); BuzzSLAMSingleton::GetInstance().GetBuzzSLAM<BuzzSLAM>(vm->robot)->InitOptimizer(); return buzzvm_ret0(vm); } /****************************************/ /****************************************/ static int BuzzOptimizerState(buzzvm_t vm){ buzzvm_pushs(vm, buzzvm_string_register(vm, "controller", 1)); buzzvm_gload(vm); int state = BuzzSLAMSingleton::GetInstance().GetBuzzSLAM<BuzzSLAM>(vm->robot)->GetOptimizerState(); buzzvm_pushi(vm, state); // Log transmitted information BuzzSLAMSingleton::GetInstance().GetBuzzSLAM<BuzzSLAM>(vm->robot)->AddNbByteTransmitted(sizeof state); return buzzvm_ret1(vm); } /****************************************/ /****************************************/ static int BuzzOptimizerTick(buzzvm_t vm) { buzzvm_pushs(vm, buzzvm_string_register(vm, "controller", 1)); buzzvm_gload(vm); BuzzSLAMSingleton::GetInstance().GetBuzzSLAM<BuzzSLAM>(vm->robot)->OptimizerTick(); return buzzvm_ret0(vm); } /****************************************/ /****************************************/ static int BuzzOptimizerPhase(buzzvm_t vm){ buzzvm_pushs(vm, buzzvm_string_register(vm, "controller", 1)); buzzvm_gload(vm); int phase = BuzzSLAMSingleton::GetInstance().GetBuzzSLAM<BuzzSLAM>(vm->robot)->GetOptimizerPhase(); buzzvm_pushi(vm, phase); return buzzvm_ret1(vm); } /****************************************/ /****************************************/ static int BuzzCheckIfAllEstimationDoneAndReset(buzzvm_t vm) { buzzvm_pushs(vm, buzzvm_string_register(vm, "controller", 1)); buzzvm_gload(vm); BuzzSLAMSingleton::GetInstance().GetBuzzSLAM<BuzzSLAM>(vm->robot)->CheckIfAllEstimationDoneAndReset(); return buzzvm_ret0(vm); } /****************************************/ /****************************************/ static int BuzzAddNeighborWithinCommunicationRange(buzzvm_t vm){ buzzvm_lload(vm, 1); buzzobj_t buzz_rid = buzzvm_stack_at(vm, 1); int rid; if(buzz_rid->o.type == BUZZTYPE_INT) rid = buzz_rid->i.value; else { buzzvm_seterror(vm, BUZZVM_ERROR_TYPE, "AddNeighborWithinCommunicationRange: expected %s, got %s in first argument", buzztype_desc[BUZZTYPE_INT], buzztype_desc[buzz_rid->o.type] ); return vm->state; } /* Get pointer to the controller */ buzzvm_pushs(vm, buzzvm_string_register(vm, "controller", 1)); buzzvm_gload(vm); /* Call function */ BuzzSLAMSingleton::GetInstance().GetBuzzSLAM<BuzzSLAM>(vm->robot)->AddNeighborWithinCommunicationRange(rid); return buzzvm_ret0(vm); } /****************************************/ /****************************************/ static int BuzzComputeAndUpdateRotationEstimatesToSend(buzzvm_t vm){ buzzvm_lload(vm, 1); buzzobj_t buzz_rid = buzzvm_stack_at(vm, 1); int rid; if(buzz_rid->o.type == BUZZTYPE_INT) rid = buzz_rid->i.value; else { buzzvm_seterror(vm, BUZZVM_ERROR_TYPE, "BuzzComputeAndUpdateRotationEstimatesToSend: expected %s, got %s in first argument", buzztype_desc[BUZZTYPE_INT], buzztype_desc[buzz_rid->o.type] ); return vm->state; } /* Get pointer to the controller */ buzzvm_pushs(vm, buzzvm_string_register(vm, "controller", 1)); buzzvm_gload(vm); /* Call function */ BuzzSLAMSingleton::GetInstance().GetBuzzSLAM<BuzzSLAM>(vm->robot)->ComputeAndUpdateRotationEstimatesToSend(rid); return buzzvm_ret0(vm); } /****************************************/ /****************************************/ static int BuzzUpdateNeighborRotationEstimates(buzzvm_t vm){ buzzvm_lnum_assert(vm, 1); buzzvm_lload(vm, 1); buzzvm_type_assert(vm, 1, BUZZTYPE_TABLE); std::vector<std::vector<rotation_estimate_t>> received_rotation_estimates; buzzobj_t b_rotation_estimates_table = buzzvm_stack_at(vm, 1); for (int32_t i = 0; i < buzzdict_size(b_rotation_estimates_table->t.value); ++i) { buzzvm_dup(vm); buzzvm_pushi(vm, i); buzzvm_tget(vm); buzzobj_t b_rotation_estimates_from_robot_i = buzzvm_stack_at(vm, 1); received_rotation_estimates.emplace_back(std::vector<rotation_estimate_t>()); for (int32_t j = 0; j < buzzdict_size(b_rotation_estimates_from_robot_i->t.value); ++j) { buzzvm_dup(vm); buzzvm_pushi(vm, j); buzzvm_tget(vm); buzzobj_t b_individual_rotation_estimate_j = buzzvm_stack_at(vm, 1); rotation_estimate_t rotation_estimate; buzzvm_dup(vm); buzzvm_pushs(vm, buzzvm_string_register(vm, "sender_robot_id", 1)); buzzvm_tget(vm); buzzobj_t b_sender_robot_id = buzzvm_stack_at(vm, 1); rotation_estimate.sender_robot_id = b_sender_robot_id->i.value; buzzvm_pop(vm); buzzvm_dup(vm); buzzvm_pushs(vm, buzzvm_string_register(vm, "receiver_robot_id", 1)); buzzvm_tget(vm); buzzobj_t b_receiver_robot_id = buzzvm_stack_at(vm, 1); rotation_estimate.receiver_robot_id = b_receiver_robot_id->i.value; buzzvm_pop(vm); buzzvm_dup(vm); buzzvm_pushs(vm, buzzvm_string_register(vm, "sender_pose_id", 1)); buzzvm_tget(vm); buzzobj_t b_sender_pose_id = buzzvm_stack_at(vm, 1); buzzvm_pop(vm); rotation_estimate.sender_pose_id = b_sender_pose_id->i.value; buzzvm_dup(vm); buzzvm_pushs(vm, buzzvm_string_register(vm, "sender_robot_is_initialized", 1)); buzzvm_tget(vm); buzzobj_t b_sender_robot_is_initialized = buzzvm_stack_at(vm, 1); buzzvm_pop(vm); rotation_estimate.sender_robot_is_initialized = (bool)b_sender_robot_is_initialized->i.value; buzzvm_dup(vm); buzzvm_pushs(vm, buzzvm_string_register(vm, "sender_estimation_is_done", 1)); buzzvm_tget(vm); buzzobj_t b_sender_estimation_is_done = buzzvm_stack_at(vm, 1); buzzvm_pop(vm); rotation_estimate.sender_estimation_is_done = (bool)b_sender_estimation_is_done->i.value; buzzvm_dup(vm); buzzvm_pushs(vm, buzzvm_string_register(vm, "rotation_estimate", 1)); buzzvm_tget(vm); buzzobj_t b_rotation_estimate = buzzvm_stack_at(vm, 1); for (int32_t k = 0; k < buzzdict_size(b_rotation_estimate->t.value); ++k) { buzzvm_dup(vm); buzzvm_pushi(vm, k); buzzvm_tget(vm); buzzobj_t b_rotation_matrix_elem = buzzvm_stack_at(vm, 1); buzzvm_pop(vm); rotation_estimate.rotation_matrix[k] = b_rotation_matrix_elem->f.value; } buzzvm_pop(vm); buzzvm_pop(vm); received_rotation_estimates.at(i).emplace_back(rotation_estimate); } buzzvm_pop(vm); } /* Get pointer to the controller */ buzzvm_pushs(vm, buzzvm_string_register(vm, "controller", 1)); buzzvm_gload(vm); /* Call function */ BuzzSLAMSingleton::GetInstance().GetBuzzSLAM<BuzzSLAM>(vm->robot)->UpdateNeighborRotationEstimates(received_rotation_estimates); return buzzvm_ret0(vm); } /****************************************/ /****************************************/ static int BuzzEstimateRotationAndUpdateRotation(buzzvm_t vm) { buzzvm_pushs(vm, buzzvm_string_register(vm, "controller", 1)); buzzvm_gload(vm); BuzzSLAMSingleton::GetInstance().GetBuzzSLAM<BuzzSLAM>(vm->robot)->EstimateRotationAndUpdateRotation(); return buzzvm_ret0(vm); } /****************************************/ /****************************************/ static int BuzzComputeAndUpdatePoseEstimatesToSend(buzzvm_t vm){ buzzvm_lload(vm, 1); buzzobj_t buzz_rid = buzzvm_stack_at(vm, 1); int rid; if(buzz_rid->o.type == BUZZTYPE_INT) rid = buzz_rid->i.value; else { buzzvm_seterror(vm, BUZZVM_ERROR_TYPE, "BuzzComputeAndUpdatePoseEstimatesToSend: expected %s, got %s in first argument", buzztype_desc[BUZZTYPE_INT], buzztype_desc[buzz_rid->o.type] ); return vm->state; } /* Get pointer to the controller */ buzzvm_pushs(vm, buzzvm_string_register(vm, "controller", 1)); buzzvm_gload(vm); /* Call function */ BuzzSLAMSingleton::GetInstance().GetBuzzSLAM<BuzzSLAM>(vm->robot)->ComputeAndUpdatePoseEstimatesToSend(rid); return buzzvm_ret0(vm); } /****************************************/ /****************************************/ static int BuzzUpdateNeighborPoseEstimates(buzzvm_t vm){ buzzvm_lnum_assert(vm, 1); buzzvm_lload(vm, 1); buzzvm_type_assert(vm, 1, BUZZTYPE_TABLE); std::vector<std::vector<pose_estimate_t>> received_pose_estimates; buzzobj_t b_pose_estimates_table = buzzvm_stack_at(vm, 1); for (int32_t i = 0; i < buzzdict_size(b_pose_estimates_table->t.value); ++i) { buzzvm_dup(vm); buzzvm_pushi(vm, i); buzzvm_tget(vm); buzzobj_t b_pose_estimates_from_robot_i = buzzvm_stack_at(vm, 1); received_pose_estimates.emplace_back(std::vector<pose_estimate_t>()); for (int32_t j = 0; j < buzzdict_size(b_pose_estimates_from_robot_i->t.value); ++j) { buzzvm_dup(vm); buzzvm_pushi(vm, j); buzzvm_tget(vm); buzzobj_t b_individual_pose_estimate_j = buzzvm_stack_at(vm, 1); pose_estimate_t pose_estimate; buzzvm_dup(vm); buzzvm_pushs(vm, buzzvm_string_register(vm, "sender_robot_id", 1)); buzzvm_tget(vm); buzzobj_t b_sender_robot_id = buzzvm_stack_at(vm, 1); pose_estimate.sender_robot_id = b_sender_robot_id->i.value; buzzvm_pop(vm); buzzvm_dup(vm); buzzvm_pushs(vm, buzzvm_string_register(vm, "receiver_robot_id", 1)); buzzvm_tget(vm); buzzobj_t b_receiver_robot_id = buzzvm_stack_at(vm, 1); pose_estimate.receiver_robot_id = b_receiver_robot_id->i.value; buzzvm_pop(vm); buzzvm_dup(vm); buzzvm_pushs(vm, buzzvm_string_register(vm, "sender_pose_id", 1)); buzzvm_tget(vm); buzzobj_t b_sender_pose_id = buzzvm_stack_at(vm, 1); buzzvm_pop(vm); pose_estimate.sender_pose_id = b_sender_pose_id->i.value; buzzvm_dup(vm); buzzvm_pushs(vm, buzzvm_string_register(vm, "sender_robot_is_initialized", 1)); buzzvm_tget(vm); buzzobj_t b_sender_robot_is_initialized = buzzvm_stack_at(vm, 1); buzzvm_pop(vm); pose_estimate.sender_robot_is_initialized = (bool)b_sender_robot_is_initialized->i.value; buzzvm_dup(vm); buzzvm_pushs(vm, buzzvm_string_register(vm, "sender_estimation_is_done", 1)); buzzvm_tget(vm); buzzobj_t b_sender_estimation_is_done = buzzvm_stack_at(vm, 1); buzzvm_pop(vm); pose_estimate.sender_estimation_is_done = (bool)b_sender_estimation_is_done->i.value; buzzvm_dup(vm); buzzvm_pushs(vm, buzzvm_string_register(vm, "pose_estimate", 1)); buzzvm_tget(vm); buzzobj_t b_pose_estimate = buzzvm_stack_at(vm, 1); for (int32_t k = 0; k < buzzdict_size(b_pose_estimate->t.value); ++k) { buzzvm_dup(vm); buzzvm_pushi(vm, k); buzzvm_tget(vm); buzzobj_t b_pose_matrix_elem = buzzvm_stack_at(vm, 1); buzzvm_pop(vm); pose_estimate.pose_data[k] = b_pose_matrix_elem->f.value; } buzzvm_pop(vm); buzzvm_pop(vm); received_pose_estimates.at(i).emplace_back(pose_estimate); } buzzvm_pop(vm); } /* Get pointer to the controller */ buzzvm_pushs(vm, buzzvm_string_register(vm, "controller", 1)); buzzvm_gload(vm); /* Call function */ BuzzSLAMSingleton::GetInstance().GetBuzzSLAM<BuzzSLAM>(vm->robot)->UpdateNeighborPoseEstimates(received_pose_estimates); return buzzvm_ret0(vm); } /****************************************/ /****************************************/ static int BuzzEstimatePoseAndUpdatePose(buzzvm_t vm) { buzzvm_pushs(vm, buzzvm_string_register(vm, "controller", 1)); buzzvm_gload(vm); BuzzSLAMSingleton::GetInstance().GetBuzzSLAM<BuzzSLAM>(vm->robot)->EstimatePoseAndUpdatePose(); return buzzvm_ret0(vm); } /****************************************/ /****************************************/ static int BuzzUpdateCurrentPoseEstimate(buzzvm_t vm) {buzzvm_lload(vm, 1); buzzobj_t buzz_pose_id = buzzvm_stack_at(vm, 1); int pose_id; if(buzz_pose_id->o.type == BUZZTYPE_INT) pose_id = buzz_pose_id->i.value; else { buzzvm_seterror(vm, BUZZVM_ERROR_TYPE, "BuzzUpdateCurrentPoseEstimate: expected %s, got %s in first argument", buzztype_desc[BUZZTYPE_INT], buzztype_desc[buzz_pose_id->o.type] ); return vm->state; } buzzvm_pushs(vm, buzzvm_string_register(vm, "controller", 1)); buzzvm_gload(vm); BuzzSLAMSingleton::GetInstance().GetBuzzSLAM<BuzzSLAM>(vm->robot)->UpdateCurrentPoseEstimate(pose_id); return buzzvm_ret0(vm); } /****************************************/ /****************************************/ static int BuzzUpdatePoseEstimateFromNeighbor(buzzvm_t vm){ buzzvm_lnum_assert(vm, 3); buzzvm_lload(vm, 1); buzzvm_lload(vm, 2); buzzvm_lload(vm, 3); buzzobj_t b_rid = buzzvm_stack_at(vm, 3); buzzobj_t b_pose_id = buzzvm_stack_at(vm, 2); buzzvm_type_assert(vm, 3, BUZZTYPE_INT); buzzvm_type_assert(vm, 2, BUZZTYPE_INT); buzzvm_type_assert(vm, 1, BUZZTYPE_TABLE); buzzobj_t b_estimate = buzzvm_stack_at(vm, 1); int table_size = buzzdict_size(b_estimate->t.value); double estimate_elem; std::vector<double> pose_estimate; for (int32_t i = 0; i < table_size; ++i) { buzzvm_dup(vm); buzzvm_pushi(vm, i); buzzvm_tget(vm); buzzvm_type_assert(vm, 1, BUZZTYPE_FLOAT); buzzobj_t b_estimate_elem = buzzvm_stack_at(vm, 1); buzzvm_pop(vm); estimate_elem = b_estimate_elem->f.value; pose_estimate.emplace_back(estimate_elem); } gtsam::Matrix4 estimate_matrix; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { estimate_matrix(i,j) = pose_estimate.at(i*4+j); } } gtsam::Pose3 pose(estimate_matrix); gtsam::Matrix6 covariance_matrix; for (int i = 0; i < 6; i++) { for (int j = 0; j < 6; j++) { covariance_matrix(i,j) = pose_estimate.at(16+i*6+j); } } graph_utils::PoseWithCovariance pose_with_covariance; pose_with_covariance.pose = pose; pose_with_covariance.covariance_matrix = covariance_matrix; int rid = b_rid->i.value; int pose_id = b_pose_id->i.value; buzzvm_pushs(vm, buzzvm_string_register(vm, "controller", 1)); buzzvm_gload(vm); BuzzSLAMSingleton::GetInstance().GetBuzzSLAM<BuzzSLAM>(vm->robot)->UpdatePoseEstimateFromNeighbor(rid, pose_id, pose_with_covariance); return buzzvm_ret0(vm); } /****************************************/ /****************************************/ static int BuzzSRand(buzzvm_t vm){ buzzvm_lload(vm, 1); buzzobj_t buzz_seed = buzzvm_stack_at(vm, 1); int seed; if(buzz_seed->o.type == BUZZTYPE_INT) seed = buzz_seed->i.value; else { buzzvm_seterror(vm, BUZZVM_ERROR_TYPE, "srand(x,y): expected %s, got %s in first argument", buzztype_desc[BUZZTYPE_INT], buzztype_desc[buzz_seed->o.type] ); return vm->state; } srand(time(NULL)+seed); return buzzvm_ret0(vm); } /****************************************/ /****************************************/ static int BuzzRandUniform(buzzvm_t vm){ buzzvm_lload(vm, 1); buzzvm_lload(vm, 2); buzzobj_t buzz_range_lowest = buzzvm_stack_at(vm, 2); buzzobj_t buzz_range_highest = buzzvm_stack_at(vm, 1); int range_lowest, range_highest; if(buzz_range_lowest->o.type == BUZZTYPE_INT) range_lowest = buzz_range_lowest->i.value; else if(buzz_range_lowest->o.type == BUZZTYPE_FLOAT) range_lowest = (int)buzz_range_lowest->f.value; else { buzzvm_seterror(vm, BUZZVM_ERROR_TYPE, "rand_uniform(x,y): expected %s, got %s in first argument", buzztype_desc[BUZZTYPE_INT], buzztype_desc[buzz_range_lowest->o.type] ); return vm->state; } if(buzz_range_highest->o.type == BUZZTYPE_INT) range_highest = buzz_range_highest->i.value; else if(buzz_range_highest->o.type == BUZZTYPE_FLOAT) range_highest = (int)buzz_range_highest->f.value; else { buzzvm_seterror(vm, BUZZVM_ERROR_TYPE, "rand_uniform(x,y): expected %s, got %s in first argument", buzztype_desc[BUZZTYPE_INT], buzztype_desc[buzz_range_highest->o.type] ); return vm->state; } float random_value = (rand()%(range_highest-range_lowest)+range_lowest); buzzvm_pushf(vm, random_value); return buzzvm_ret1(vm); } /****************************************/ /****************************************/ static int BuzzAddSeparatorToLocalGraph(buzzvm_t vm) { /* Push the vector components */ buzzvm_lload(vm, 1); buzzvm_lload(vm, 2); buzzvm_lload(vm, 3); buzzvm_lload(vm, 4); buzzvm_lload(vm, 5); buzzvm_lload(vm, 6); buzzvm_lload(vm, 7); buzzvm_lload(vm, 8); buzzvm_lload(vm, 9); buzzvm_lload(vm, 10); buzzvm_lload(vm, 11); buzzvm_lload(vm, 12); /* Retrieve parameters and check their types */ buzzobj_t b_robot_1_id = buzzvm_stack_at(vm, 12); buzzobj_t b_robot_2_id = buzzvm_stack_at(vm, 11); buzzobj_t b_robot_1_pose_id = buzzvm_stack_at(vm, 10); buzzobj_t b_robot_2_pose_id = buzzvm_stack_at(vm, 9); buzzobj_t b_x = buzzvm_stack_at(vm, 8); buzzobj_t b_y = buzzvm_stack_at(vm, 7); buzzobj_t b_z = buzzvm_stack_at(vm, 6); buzzobj_t b_q_x = buzzvm_stack_at(vm, 5); buzzobj_t b_q_y = buzzvm_stack_at(vm, 4); buzzobj_t b_q_z = buzzvm_stack_at(vm, 3); buzzobj_t b_q_w = buzzvm_stack_at(vm, 2); buzzobj_t b_covariance_matrix = buzzvm_stack_at(vm, 1); int robot_1_id, robot_2_id, robot_1_pose_id, robot_2_pose_id; float x, y, z, q_x, q_y, q_z, q_w; std::vector<double> covariance_values; if(b_robot_1_id->o.type == BUZZTYPE_INT && b_robot_2_id->o.type == BUZZTYPE_INT && b_robot_1_pose_id->o.type == BUZZTYPE_INT && b_robot_2_pose_id->o.type == BUZZTYPE_INT && b_x->o.type == BUZZTYPE_FLOAT && b_y->o.type == BUZZTYPE_FLOAT && b_z->o.type == BUZZTYPE_FLOAT && b_q_x->o.type == BUZZTYPE_FLOAT && b_q_y->o.type == BUZZTYPE_FLOAT && b_q_z->o.type == BUZZTYPE_FLOAT && b_q_w->o.type == BUZZTYPE_FLOAT && b_covariance_matrix->o.type == BUZZTYPE_TABLE) { // Fill in variables robot_1_id = b_robot_1_id->i.value; robot_2_id = b_robot_2_id->i.value; robot_1_pose_id = b_robot_1_pose_id->i.value; robot_2_pose_id = b_robot_2_pose_id->i.value; x = b_x->f.value; y = b_y->f.value; z = b_z->f.value; q_x = b_q_x->f.value; q_y = b_q_y->f.value; q_z = b_q_z->f.value; q_w = b_q_w->f.value; int table_size = buzzdict_size(b_covariance_matrix->t.value); double covariance_elem; for (int32_t i = 0; i < table_size; ++i) { buzzvm_dup(vm); buzzvm_pushi(vm, i); buzzvm_tget(vm); buzzvm_type_assert(vm, 1, BUZZTYPE_FLOAT); buzzobj_t b_covariance_value = buzzvm_stack_at(vm, 1); buzzvm_pop(vm); covariance_elem = b_covariance_value->f.value; covariance_values.emplace_back(covariance_elem); } } else { buzzvm_seterror(vm, BUZZVM_ERROR_TYPE, "wrong parameter type for add_separator_to_local_graph." ); return vm->state; } gtsam::Matrix6 covariance_matrix; for (int i = 0; i < 6; i++) { for (int j = 0; j < 6; j++) { covariance_matrix(i,j) = covariance_values.at(i*6+j); } } /* Get pointer to the controller */ buzzvm_pushs(vm, buzzvm_string_register(vm, "controller", 1)); buzzvm_gload(vm); /* Call function */ BuzzSLAMSingleton::GetInstance().GetBuzzSLAM<BuzzSLAM>(vm->robot)->AddSeparatorToLocalGraph( robot_1_id, robot_2_id, robot_1_pose_id, robot_2_pose_id, x, y, z, q_x, q_y, q_z, q_w, covariance_matrix ); return buzzvm_ret0(vm); } /****************************************/ /****************************************/ static int BuzzLoadParameters(buzzvm_t vm) { /* Push the vector components */ buzzvm_lload(vm, 1); buzzvm_lload(vm, 2); buzzvm_lload(vm, 3); buzzvm_lload(vm, 4); buzzvm_lload(vm, 5); buzzvm_lload(vm, 6); buzzvm_lload(vm, 7); buzzvm_lload(vm, 8); buzzvm_lload(vm, 9); buzzvm_lload(vm, 10); buzzvm_lload(vm, 11); buzzvm_lload(vm, 12); buzzvm_lload(vm, 13); buzzvm_lload(vm, 14); buzzvm_lload(vm, 15); buzzvm_lload(vm, 16); buzzvm_lload(vm, 17); buzzvm_lload(vm, 18); /* Retrieve parameters and check their types */ buzzobj_t b_use_heuristics = buzzvm_stack_at(vm, 18); buzzobj_t b_log_folder = buzzvm_stack_at(vm, 17); buzzobj_t b_optimizer_period = buzzvm_stack_at(vm, 16); buzzobj_t b_max_steps_rotation = buzzvm_stack_at(vm, 15); buzzobj_t b_max_steps_pose = buzzvm_stack_at(vm, 14); buzzobj_t b_number_of_steps_before_failsafe = buzzvm_stack_at(vm, 13); buzzobj_t b_use_pcm = buzzvm_stack_at(vm, 12); buzzobj_t b_pcm_threshold = buzzvm_stack_at(vm, 11); buzzobj_t b_incremental_solving = buzzvm_stack_at(vm, 10); buzzobj_t b_debug = buzzvm_stack_at(vm, 9); buzzobj_t b_rotation_noise_std = buzzvm_stack_at(vm, 8); buzzobj_t b_translation_noise_std = buzzvm_stack_at(vm, 7); buzzobj_t b_rotation_estimate_change_threshold = buzzvm_stack_at(vm, 6); buzzobj_t b_pose_estimate_change_threshold = buzzvm_stack_at(vm, 5); buzzobj_t b_use_flagged_initialization = buzzvm_stack_at(vm, 4); buzzobj_t b_is_simulation = buzzvm_stack_at(vm, 3); buzzobj_t b_number_of_robots = buzzvm_stack_at(vm, 2); buzzobj_t b_error_file_name = buzzvm_stack_at(vm, 1); float rotation_noise_std, translation_noise_std, rotation_estimate_change_threshold, pose_estimate_change_threshold; bool use_flagged_initialization, is_simulation, incremental_solving; int number_of_robots, debug_level; double pcm_threshold; std::string error_file_name, log_folder; bool use_pcm; int number_of_steps_before_failsafe; int max_steps_rotation, max_steps_pose; int optimizer_period; bool use_heuristics; if(b_rotation_noise_std->o.type == BUZZTYPE_FLOAT && b_translation_noise_std->o.type == BUZZTYPE_FLOAT && b_rotation_estimate_change_threshold->o.type == BUZZTYPE_FLOAT && b_pose_estimate_change_threshold->o.type == BUZZTYPE_FLOAT && b_use_flagged_initialization->o.type == BUZZTYPE_INT && b_is_simulation->o.type == BUZZTYPE_INT && b_number_of_robots->o.type == BUZZTYPE_INT && b_error_file_name->o.type == BUZZTYPE_STRING && b_log_folder->o.type == BUZZTYPE_STRING && b_debug->o.type == BUZZTYPE_INT && b_incremental_solving->o.type == BUZZTYPE_INT && b_pcm_threshold->o.type == BUZZTYPE_FLOAT && b_use_pcm->o.type == BUZZTYPE_INT && b_number_of_steps_before_failsafe->o.type == BUZZTYPE_INT && b_max_steps_rotation->o.type == BUZZTYPE_INT && b_max_steps_pose->o.type == BUZZTYPE_INT && b_optimizer_period->o.type == BUZZTYPE_INT && b_use_heuristics->o.type == BUZZTYPE_INT) { // Fill in variables rotation_noise_std = b_rotation_noise_std->f.value; translation_noise_std = b_translation_noise_std->f.value; rotation_estimate_change_threshold = b_rotation_estimate_change_threshold->f.value; pose_estimate_change_threshold = b_pose_estimate_change_threshold->f.value; use_flagged_initialization = (bool) b_use_flagged_initialization->i.value; is_simulation = (bool) b_is_simulation->i.value; number_of_robots = b_number_of_robots->i.value; error_file_name = b_error_file_name->s.value.str; log_folder = b_log_folder->s.value.str; debug_level = b_debug->i.value; incremental_solving = b_incremental_solving->i.value; pcm_threshold = b_pcm_threshold->f.value; use_pcm = (bool) b_use_pcm->i.value; number_of_steps_before_failsafe = b_number_of_steps_before_failsafe->i.value; max_steps_rotation = b_max_steps_rotation->i.value; max_steps_pose = b_max_steps_pose->i.value; optimizer_period = b_optimizer_period->i.value; use_heuristics = (bool) b_use_heuristics->i.value; } else { buzzvm_seterror(vm, BUZZVM_ERROR_TYPE, "wrong parameter type for load_cpp_controller_parameters." ); return vm->state; } /* Get pointer to the controller */ buzzvm_pushs(vm, buzzvm_string_register(vm, "controller", 1)); buzzvm_gload(vm); /* Call function */ BuzzSLAMSingleton::GetInstance().GetBuzzSLAM<BuzzSLAM>(vm->robot)->LoadParameters(log_folder, optimizer_period, number_of_steps_before_failsafe, use_pcm, pcm_threshold, incremental_solving, debug_level, rotation_noise_std, translation_noise_std, rotation_estimate_change_threshold, pose_estimate_change_threshold, use_flagged_initialization, is_simulation, number_of_robots, error_file_name, max_steps_rotation, max_steps_pose, use_heuristics); return buzzvm_ret0(vm); } /****************************************/ /****************************************/ static int BuzzRotationEstimationStoppingConditions(buzzvm_t vm){ buzzvm_pushs(vm, buzzvm_string_register(vm, "controller", 1)); buzzvm_gload(vm); bool is_finished = BuzzSLAMSingleton::GetInstance().GetBuzzSLAM<BuzzSLAM>(vm->robot)->RotationEstimationStoppingConditions(); buzzvm_pushi(vm, is_finished); // Log transmitted information BuzzSLAMSingleton::GetInstance().GetBuzzSLAM<BuzzSLAM>(vm->robot)->AddNbByteTransmitted(sizeof is_finished); return buzzvm_ret1(vm); } /****************************************/ /****************************************/ static int BuzzPoseEstimationStoppingConditions(buzzvm_t vm){ buzzvm_pushs(vm, buzzvm_string_register(vm, "controller", 1)); buzzvm_gload(vm); bool is_finished = BuzzSLAMSingleton::GetInstance().GetBuzzSLAM<BuzzSLAM>(vm->robot)->PoseEstimationStoppingConditions(); buzzvm_pushi(vm, is_finished); // Log transmitted information BuzzSLAMSingleton::GetInstance().GetBuzzSLAM<BuzzSLAM>(vm->robot)->AddNbByteTransmitted(sizeof is_finished); return buzzvm_ret1(vm); } /****************************************/ /****************************************/ static int BuzzNeighborRotationEstimationIsFinished(buzzvm_t vm){ buzzvm_lload(vm, 1); buzzobj_t buzz_rid = buzzvm_stack_at(vm, 1); int rid; if(buzz_rid->o.type == BUZZTYPE_INT) rid = buzz_rid->i.value; else { buzzvm_seterror(vm, BUZZVM_ERROR_TYPE, "BuzzNeighborRotationEstimationIsFinished: expected %s, got %s in first argument", buzztype_desc[BUZZTYPE_INT], buzztype_desc[buzz_rid->o.type] ); return vm->state; } /* Get pointer to the controller */ buzzvm_pushs(vm, buzzvm_string_register(vm, "controller", 1)); buzzvm_gload(vm); /* Call function */ BuzzSLAMSingleton::GetInstance().GetBuzzSLAM<BuzzSLAM>(vm->robot)->NeighborRotationEstimationIsFinished(rid); return buzzvm_ret0(vm); } /****************************************/ /****************************************/ static int BuzzNeighborPoseEstimationIsFinished(buzzvm_t vm){ buzzvm_lload(vm, 1); buzzvm_lload(vm, 2); buzzobj_t buzz_rid = buzzvm_stack_at(vm, 2); int rid; buzzobj_t buzz_anchor_offset = buzzvm_stack_at(vm, 1); gtsam::Point3 anchor_offset; if(buzz_rid->o.type == BUZZTYPE_INT && buzz_anchor_offset->o.type == BUZZTYPE_TABLE) { rid = buzz_rid->i.value; int table_size = buzzdict_size(buzz_anchor_offset->t.value); double anchor_elem; std::vector<double> anchor_elems; for (int32_t i = 0; i < table_size; ++i) { buzzvm_dup(vm); buzzvm_pushi(vm, i); buzzvm_tget(vm); buzzvm_type_assert(vm, 1, BUZZTYPE_FLOAT); buzzobj_t b_anchor_value = buzzvm_stack_at(vm, 1); buzzvm_pop(vm); anchor_elem = b_anchor_value->f.value; anchor_elems.emplace_back(anchor_elem); } anchor_offset = gtsam::Point3(anchor_elems[0], anchor_elems[1], anchor_elems[2]); } else { buzzvm_seterror(vm, BUZZVM_ERROR_TYPE, "BuzzNeighborPoseEstimationIsFinished: expected %s, got %s in first argument", buzztype_desc[BUZZTYPE_INT], buzztype_desc[buzz_rid->o.type] ); return vm->state; } /* Get pointer to the controller */ buzzvm_pushs(vm, buzzvm_string_register(vm, "controller", 1)); buzzvm_gload(vm); /* Call function */ BuzzSLAMSingleton::GetInstance().GetBuzzSLAM<BuzzSLAM>(vm->robot)->NeighborPoseEstimationIsFinished(rid, anchor_offset); return buzzvm_ret0(vm); } /****************************************/ /****************************************/ static int BuzzNeighborState(buzzvm_t vm){ buzzvm_lload(vm, 1); buzzvm_lload(vm, 2); buzzvm_lload(vm, 3); buzzobj_t buzz_rid = buzzvm_stack_at(vm, 3); int rid; buzzobj_t buzz_state = buzzvm_stack_at(vm, 2); int state; buzzobj_t buzz_lowest_id = buzzvm_stack_at(vm, 1); int lowest_id; if(buzz_rid->o.type == BUZZTYPE_INT && buzz_state->o.type == BUZZTYPE_INT && buzz_lowest_id->o.type == BUZZTYPE_INT) { rid = buzz_rid->i.value; state = buzz_state->i.value; lowest_id = buzz_lowest_id->i.value; } else { buzzvm_seterror(vm, BUZZVM_ERROR_TYPE, "BuzzNeighborState: expected %s, got %s in first argument", buzztype_desc[BUZZTYPE_INT], buzztype_desc[buzz_rid->o.type] ); return vm->state; } /* Get pointer to the controller */ buzzvm_pushs(vm, buzzvm_string_register(vm, "controller", 1)); buzzvm_gload(vm); /* Call function */ BuzzSLAMSingleton::GetInstance().GetBuzzSLAM<BuzzSLAM>(vm->robot)->NeighborState(rid, (buzz_slam::OptimizerState) state, lowest_id); return buzzvm_ret0(vm); } /****************************************/ /****************************************/ static int BuzzUpdateHasSentStartOptimizationFlag(buzzvm_t vm) { buzzvm_pushs(vm, buzzvm_string_register(vm, "controller", 1)); buzzvm_gload(vm); BuzzSLAMSingleton::GetInstance().GetBuzzSLAM<BuzzSLAM>(vm->robot)->UpdateHasSentStartOptimizationFlag(true); } /****************************************/ /****************************************/ static int BuzzUpdateAdjacencyVector(buzzvm_t vm) { buzzvm_pushs(vm, buzzvm_string_register(vm, "controller", 1)); buzzvm_gload(vm); BuzzSLAMSingleton::GetInstance().GetBuzzSLAM<BuzzSLAM>(vm->robot)->UpdateAdjacencyVector(); } /****************************************/ /****************************************/ static int BuzzReceiveAdjacencyVectorFromNeighbor(buzzvm_t vm) { buzzvm_lload(vm, 1); buzzvm_lload(vm, 2); buzzobj_t buzz_rid = buzzvm_stack_at(vm, 2); int rid; buzzobj_t buzz_adjacency_vector = buzzvm_stack_at(vm, 1); std::vector<int> adjacency_vector; if(buzz_rid->o.type == BUZZTYPE_INT && buzz_adjacency_vector->o.type == BUZZTYPE_TABLE) { rid = buzz_rid->i.value; int table_size = buzzdict_size(buzz_adjacency_vector->t.value); int elem; for (int32_t i = 0; i < table_size; ++i) { buzzvm_dup(vm); buzzvm_pushi(vm, i); buzzvm_tget(vm); buzzvm_type_assert(vm, 1, BUZZTYPE_INT); buzzobj_t b_adjacency_value = buzzvm_stack_at(vm, 1); buzzvm_pop(vm); elem = b_adjacency_value->i.value; adjacency_vector.emplace_back(elem); } } else { buzzvm_seterror(vm, BUZZVM_ERROR_TYPE, "BuzzNeighborPoseEstimationIsFinished: expected %s, got %s in first argument", buzztype_desc[BUZZTYPE_INT], buzztype_desc[buzz_rid->o.type] ); return vm->state; } /* Get pointer to the controller */ buzzvm_pushs(vm, buzzvm_string_register(vm, "controller", 1)); buzzvm_gload(vm); /* Call function */ BuzzSLAMSingleton::GetInstance().GetBuzzSLAM<BuzzSLAM>(vm->robot)->ReceiveAdjacencyVectorFromNeighbor(rid, adjacency_vector); return buzzvm_ret0(vm); } /****************************************/ /****************************************/ static int BuzzUpdateNeighborHasStartedOptimizationFlag(buzzvm_t vm) { buzzvm_lload(vm, 1); buzzobj_t buzz_rid = buzzvm_stack_at(vm, 1); int rid; if(buzz_rid->o.type == BUZZTYPE_INT) { rid = buzz_rid->i.value; } else { buzzvm_seterror(vm, BUZZVM_ERROR_TYPE, "BuzzUpdateNeighborHasStartedOptimizationFlag: expected %s, got %s in first argument", buzztype_desc[BUZZTYPE_INT], buzztype_desc[buzz_rid->o.type] ); return vm->state; } buzzvm_pushs(vm, buzzvm_string_register(vm, "controller", 1)); buzzvm_gload(vm); BuzzSLAMSingleton::GetInstance().GetBuzzSLAM<BuzzSLAM>(vm->robot)->UpdateNeighborHasStartedOptimizationFlag(true, rid); return buzzvm_ret0(vm); } /****************************************/ /************ Registration **************/ /****************************************/ buzzvm_state BuzzSLAM::RegisterSLAMFunctions(buzzvm_t buzz_vm) { /* Register mapping specific functions */ buzzvm_pushs(buzz_vm, buzzvm_string_register(buzz_vm, "load_parameters", 1)); buzzvm_pushcc(buzz_vm, buzzvm_function_register(buzz_vm, BuzzLoadParameters)); buzzvm_gstore(buzz_vm); buzzvm_pushs(buzz_vm, buzzvm_string_register(buzz_vm, "srand", 1)); buzzvm_pushcc(buzz_vm, buzzvm_function_register(buzz_vm, BuzzSRand)); buzzvm_gstore(buzz_vm); buzzvm_pushs(buzz_vm, buzzvm_string_register(buzz_vm, "rand_uniform", 1)); buzzvm_pushcc(buzz_vm, buzzvm_function_register(buzz_vm, BuzzRandUniform)); buzzvm_gstore(buzz_vm); buzzvm_pushs(buzz_vm, buzzvm_string_register(buzz_vm, "add_separator_to_local_graph", 1)); buzzvm_pushcc(buzz_vm, buzzvm_function_register(buzz_vm, BuzzAddSeparatorToLocalGraph)); buzzvm_gstore(buzz_vm); buzzvm_pushs(buzz_vm, buzzvm_string_register(buzz_vm, "init_optimizer", 1)); buzzvm_pushcc(buzz_vm, buzzvm_function_register(buzz_vm, BuzzInitOptimizer)); buzzvm_gstore(buzz_vm); buzzvm_pushs(buzz_vm, buzzvm_string_register(buzz_vm, "optimizer_state", 1)); buzzvm_pushcc(buzz_vm, buzzvm_function_register(buzz_vm, BuzzOptimizerState)); buzzvm_gstore(buzz_vm); buzzvm_pushs(buzz_vm, buzzvm_string_register(buzz_vm, "optimizer_tick", 1)); buzzvm_pushcc(buzz_vm, buzzvm_function_register(buzz_vm, BuzzOptimizerTick)); buzzvm_gstore(buzz_vm); buzzvm_pushs(buzz_vm, buzzvm_string_register(buzz_vm, "add_neighbor_within_communication_range", 1)); buzzvm_pushcc(buzz_vm, buzzvm_function_register(buzz_vm, BuzzAddNeighborWithinCommunicationRange)); buzzvm_gstore(buzz_vm); buzzvm_pushs(buzz_vm, buzzvm_string_register(buzz_vm, "compute_and_update_rotation_estimates_to_send", 1)); buzzvm_pushcc(buzz_vm, buzzvm_function_register(buzz_vm, BuzzComputeAndUpdateRotationEstimatesToSend)); buzzvm_gstore(buzz_vm); buzzvm_pushs(buzz_vm, buzzvm_string_register(buzz_vm, "compute_and_update_pose_estimates_to_send", 1)); buzzvm_pushcc(buzz_vm, buzzvm_function_register(buzz_vm, BuzzComputeAndUpdatePoseEstimatesToSend)); buzzvm_gstore(buzz_vm); buzzvm_pushs(buzz_vm, buzzvm_string_register(buzz_vm, "update_neighbor_rotation_estimates", 1)); buzzvm_pushcc(buzz_vm, buzzvm_function_register(buzz_vm, BuzzUpdateNeighborRotationEstimates)); buzzvm_gstore(buzz_vm); buzzvm_pushs(buzz_vm, buzzvm_string_register(buzz_vm, "update_neighbor_pose_estimates", 1)); buzzvm_pushcc(buzz_vm, buzzvm_function_register(buzz_vm, BuzzUpdateNeighborPoseEstimates)); buzzvm_gstore(buzz_vm); buzzvm_pushs(buzz_vm, buzzvm_string_register(buzz_vm, "estimate_rotation_and_update_rotation", 1)); buzzvm_pushcc(buzz_vm, buzzvm_function_register(buzz_vm, BuzzEstimateRotationAndUpdateRotation)); buzzvm_gstore(buzz_vm); buzzvm_pushs(buzz_vm, buzzvm_string_register(buzz_vm, "estimate_pose_and_update_pose", 1)); buzzvm_pushcc(buzz_vm, buzzvm_function_register(buzz_vm, BuzzEstimatePoseAndUpdatePose)); buzzvm_gstore(buzz_vm); buzzvm_pushs(buzz_vm, buzzvm_string_register(buzz_vm, "rotation_estimation_stopping_conditions", 1)); buzzvm_pushcc(buzz_vm, buzzvm_function_register(buzz_vm, BuzzRotationEstimationStoppingConditions)); buzzvm_gstore(buzz_vm); buzzvm_pushs(buzz_vm, buzzvm_string_register(buzz_vm, "pose_estimation_stopping_conditions", 1)); buzzvm_pushcc(buzz_vm, buzzvm_function_register(buzz_vm, BuzzPoseEstimationStoppingConditions)); buzzvm_gstore(buzz_vm); buzzvm_pushs(buzz_vm, buzzvm_string_register(buzz_vm, "neighbor_rotation_estimation_is_finished", 1)); buzzvm_pushcc(buzz_vm, buzzvm_function_register(buzz_vm, BuzzNeighborRotationEstimationIsFinished)); buzzvm_gstore(buzz_vm); buzzvm_pushs(buzz_vm, buzzvm_string_register(buzz_vm, "neighbor_pose_estimation_is_finished", 1)); buzzvm_pushcc(buzz_vm, buzzvm_function_register(buzz_vm, BuzzNeighborPoseEstimationIsFinished)); buzzvm_gstore(buzz_vm); buzzvm_pushs(buzz_vm, buzzvm_string_register(buzz_vm, "optimizer_phase", 1)); buzzvm_pushcc(buzz_vm, buzzvm_function_register(buzz_vm, BuzzOptimizerPhase)); buzzvm_gstore(buzz_vm); buzzvm_pushs(buzz_vm, buzzvm_string_register(buzz_vm, "check_if_all_estimation_done_and_reset", 1)); buzzvm_pushcc(buzz_vm, buzzvm_function_register(buzz_vm, BuzzCheckIfAllEstimationDoneAndReset)); buzzvm_gstore(buzz_vm); buzzvm_pushs(buzz_vm, buzzvm_string_register(buzz_vm, "neighbor_state", 1)); buzzvm_pushcc(buzz_vm, buzzvm_function_register(buzz_vm, BuzzNeighborState)); buzzvm_gstore(buzz_vm); buzzvm_pushs(buzz_vm, buzzvm_string_register(buzz_vm, "update_current_pose_estimate", 1)); buzzvm_pushcc(buzz_vm, buzzvm_function_register(buzz_vm, BuzzUpdateCurrentPoseEstimate)); buzzvm_gstore(buzz_vm); buzzvm_pushs(buzz_vm, buzzvm_string_register(buzz_vm, "update_pose_estimate_from_neighbor", 1)); buzzvm_pushcc(buzz_vm, buzzvm_function_register(buzz_vm, BuzzUpdatePoseEstimateFromNeighbor)); buzzvm_gstore(buzz_vm); buzzvm_pushs(buzz_vm, buzzvm_string_register(buzz_vm, "update_has_sent_start_optimization_flag", 1)); buzzvm_pushcc(buzz_vm, buzzvm_function_register(buzz_vm, BuzzUpdateHasSentStartOptimizationFlag)); buzzvm_gstore(buzz_vm); buzzvm_pushs(buzz_vm, buzzvm_string_register(buzz_vm, "update_adjacency_vector", 1)); buzzvm_pushcc(buzz_vm, buzzvm_function_register(buzz_vm, BuzzUpdateAdjacencyVector)); buzzvm_gstore(buzz_vm); buzzvm_pushs(buzz_vm, buzzvm_string_register(buzz_vm, "receive_adjacency_vector_from_neighbor", 1)); buzzvm_pushcc(buzz_vm, buzzvm_function_register(buzz_vm, BuzzReceiveAdjacencyVectorFromNeighbor)); buzzvm_gstore(buzz_vm); buzzvm_pushs(buzz_vm, buzzvm_string_register(buzz_vm, "update_neighbor_has_started_optimization_flag", 1)); buzzvm_pushcc(buzz_vm, buzzvm_function_register(buzz_vm, BuzzUpdateNeighborHasStartedOptimizationFlag)); buzzvm_gstore(buzz_vm); return buzz_vm->state; } }
37.260199
147
0.648036
SnowCarter
00a39073167ee47f048a4d633df7158f0a803aad
2,863
cpp
C++
src/image_proc_chain/flexible_chain_executor.cpp
fugashy/image_proc_chain
176210c4b3b74f58f5a73b5cca07268bcb13c961
[ "BSD-3-Clause" ]
null
null
null
src/image_proc_chain/flexible_chain_executor.cpp
fugashy/image_proc_chain
176210c4b3b74f58f5a73b5cca07268bcb13c961
[ "BSD-3-Clause" ]
null
null
null
src/image_proc_chain/flexible_chain_executor.cpp
fugashy/image_proc_chain
176210c4b3b74f58f5a73b5cca07268bcb13c961
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2019 fugashy #include <string> #include "image_proc_chain/flexible_chain_executor.hpp" namespace image_proc_chain { FlexibleChainExecutor::FlexibleChainExecutor( rclcpp::Node::SharedPtr& node, const uint32_t default_num) : node_(node) { piece_nodes_.resize(default_num); chain_pieces_.resize(default_num); executor_.reset(new rclcpp::executors::SingleThreadedExecutor()); // サービスのコールバックを受けるためには,このnode_もexecutorに登録する必要がある executor_->add_node(node_); for (uint32_t i = 0; i < default_num; ++i) { const std::string node_name = "chain_piece_" + std::to_string(i); piece_nodes_[i].reset(new rclcpp::Node(node_name)); if (i == 0) { chain_pieces_[i].reset(new ChainPiece(piece_nodes_[i])); } else { const std::string pre_node_name = "chain_piece_" + std::to_string(i - 1); chain_pieces_[i].reset(new ChainPiece(piece_nodes_[i], pre_node_name + "/image_out")); } executor_->add_node(piece_nodes_[i]); } RCLCPP_INFO(node_->get_logger(), "flexible_chain_executor is ready"); } bool FlexibleChainExecutor::ChangeNumTo(const uint32_t num) { if (num == 0) { RCLCPP_WARN(node_->get_logger(), "0 num is requested, we ignore this request"); return false; } const int current_num = piece_nodes_.size(); if (static_cast<int>(num) == current_num) { RCLCPP_WARN(node_->get_logger(), "Requested chain-num is the same as current one(%d)", num); return false; } else if (static_cast<int>(num) > current_num) { RCLCPP_INFO(node_->get_logger(), "Request(%d) is greater than current one", num); const int diff = num - current_num; for (int i = 0; i < diff; ++i) { // 現在のノード数に足し合わせる // idとしては0数え // current_numは1数え // iは0数え // よって,current_num + iによって次のnode_idが計算できる const int node_id = current_num + i; const std::string node_name = "chain_piece_" + std::to_string(node_id); const std::string pre_node_name = "chain_piece_" + std::to_string(node_id - 1); piece_nodes_.emplace_back(rclcpp::Node::SharedPtr(new rclcpp::Node(node_name))); chain_pieces_.emplace_back( ChainPiece::SharedPtr( new ChainPiece(piece_nodes_[node_id], pre_node_name + "/image_out"))); executor_->add_node((piece_nodes_[current_num + i])); } return true; } else { RCLCPP_INFO(node_->get_logger(), "Request(%d) is less than current one", num); const int diff = num - current_num; for (int i = 0; i < std::abs(diff); ++i) { // 現在のノード数を減らす // idとしては0数え // current_numは1数え // iは0数え // よって,current_num + i - 1によって現在のnode_idが計算できる const int node_id = current_num - i - 1; executor_->remove_node((piece_nodes_[node_id])); chain_pieces_.pop_back(); piece_nodes_.pop_back(); } return true; } } } // namespace image_proc_chain
36.705128
96
0.671324
fugashy
00a4f618a9af55e0fa62c0b0aa5e29b58496b295
3,935
cpp
C++
PhysBody3D.cpp
CITMProject3/Project3
5076dbaf4eced4eb69bb43b811684206e62eded4
[ "MIT" ]
3
2017-04-02T19:37:52.000Z
2018-11-06T13:37:33.000Z
PhysBody3D.cpp
CITMProject3/Project3
5076dbaf4eced4eb69bb43b811684206e62eded4
[ "MIT" ]
74
2017-04-03T14:32:09.000Z
2017-06-08T10:12:56.000Z
PhysBody3D.cpp
CITMProject3/Project3
5076dbaf4eced4eb69bb43b811684206e62eded4
[ "MIT" ]
3
2017-06-06T17:10:46.000Z
2019-10-28T16:25:27.000Z
#include "PhysBody3D.h" #include "Globals.h" #include "Bullet\include\btBulletDynamicsCommon.h" // ================================================= PhysBody3D::PhysBody3D(btRigidBody* body, ComponentCollider* col) : body(body) { collider = col; body->setUserPointer(this); } PhysBody3D::PhysBody3D(btRigidBody* body, ComponentCar* col) : body(body) { car = col; body->setUserPointer(this); SetCar(true); } // --------------------------------------------------------- PhysBody3D::~PhysBody3D() { if (body != nullptr) { delete body; body = nullptr; } } // --------------------------------------------------------- void PhysBody3D::Push(float x, float y, float z) { body->applyCentralImpulse(btVector3(x, y, z)); } // --------------------------------------------------------- float4x4 PhysBody3D::GetTransform() const { float4x4 ret = float4x4::identity; if(body != NULL) { float tmp[16]; body->getWorldTransform().getOpenGLMatrix(tmp); ret.Set(tmp); } return ret; } // --------------------------------------------------------- void PhysBody3D::SetTransform(const float* matrix) const { if(body != nullptr && matrix != nullptr) { btTransform t; t.setFromOpenGLMatrix(matrix); //body->setWorldTransform(t); body->getMotionState()->setWorldTransform(t); } } // --------------------------------------------------------- void PhysBody3D::SetPos(float x, float y, float z) { btTransform t = body->getWorldTransform(); t.setOrigin(btVector3(x, y, z)); body->setWorldTransform(t); } //---------------------------------------------------------- void PhysBody3D::SetRotation(float x, float y, float z) { btTransform t = body->getWorldTransform(); btQuaternion q; q.setEulerZYX(z, y, x); t.setRotation(q); body->setWorldTransform(t); } void PhysBody3D::SetRotation(Quat rot) { btTransform t = body->getWorldTransform(); btQuaternion q(rot.x, rot.y, rot.z, rot.w); t.setRotation(q); body->setWorldTransform(t); } // --------------------------------------------------------- void PhysBody3D::Stop() { body->setLinearVelocity(btVector3(0, 0, 0)); body->setAngularVelocity(btVector3(0, 0, 0)); body->clearForces(); } // --------------------------------------------------------- btTransform PhysBody3D::GetRealTransform()const { return body->getWorldTransform(); } //---------------------------------------------------------- void PhysBody3D::ApplyCentralForce(btVector3& force) { body->applyCentralForce(force); } //--------------------------------------------------------- void PhysBody3D::SetFriction(float friction) { body->setFriction(friction); } void PhysBody3D::SetBounciness(float restitution, float friction) { body->setFriction(friction); body->setRestitution(restitution); } //---------------------------------------------------------- void PhysBody3D::SetAngularSpeed(float x, float y, float z) { body->setAngularVelocity(btVector3(x, y, z)); } //---------------------------------------------------------- void PhysBody3D::SetLinearSpeed(float x, float y, float z) { body->setLinearVelocity(btVector3(x, y, z)); } void PhysBody3D::SetModularSpeed(float s) { btVector3 sp = body->getLinearVelocity(); if (sp.length2() > 0.0f) { sp.normalize(); sp *= s; body->setLinearVelocity(sp); } } //---------------------------------------------------------- math::vec PhysBody3D::GetPosition()const { math::vec ret; ret.x = body->getWorldTransform().getOrigin().getX(); ret.y = body->getWorldTransform().getOrigin().getY(); ret.z = body->getWorldTransform().getOrigin().getZ(); return ret; } void PhysBody3D::SetTrigger(bool value, TriggerType t_type) { is_trigger = value; trigger_type = t_type; } void PhysBody3D::SetCar(bool value) { is_car = value; } bool PhysBody3D::IsCar() const { return is_car; } bool PhysBody3D::IsTrigger() const { return is_trigger; } void PhysBody3D::SetActivationState(int state) { body->forceActivationState(state); }
22.231638
78
0.561372
CITMProject3
00a788356014c40a4cf86c082ef042798fc7ea47
3,314
cpp
C++
apps/MCManager/src/MCClientID.cpp
FleX-d/RSM
fa6eb54bd0377ddb63fe023a3b73bc893938f1fa
[ "BSD-3-Clause" ]
null
null
null
apps/MCManager/src/MCClientID.cpp
FleX-d/RSM
fa6eb54bd0377ddb63fe023a3b73bc893938f1fa
[ "BSD-3-Clause" ]
1
2018-05-25T11:05:02.000Z
2018-05-25T11:05:02.000Z
apps/MCManager/src/MCClientID.cpp
FleX-d/RSM
fa6eb54bd0377ddb63fe023a3b73bc893938f1fa
[ "BSD-3-Clause" ]
2
2018-05-25T11:02:10.000Z
2018-06-19T09:44:28.000Z
/* Copyright (c) 2017, Globallogic s.r.o. 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 Globallogic s.r.o. 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 GLOBALLOGIC S.R.O. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * File: MCClientConf.cpp * Author: Matus Bodorik * * Created on January 19, 2018, 9:36 AM */ #include "MCClientID.h" namespace rsm { namespace msq { namespace com { MCClientID::~MCClientID() { } MCClientID::MCClientID(const std::string& id, const std::string& externalID, const std::string& requester, const std::string& topic) : m_ID(id), m_externalID(externalID), m_requester(requester), m_topic(topic), m_uniqueID(m_ID + m_requester) { } MCClientID::MCClientID(const std::string& id, const std::string& externalID, const std::string& requester, const std::string& topic, const std::string& uniqueID) : m_ID(id), m_externalID(externalID), m_requester(requester), m_topic(topic), m_uniqueID(uniqueID) { } MCClientID::MCClientID() { } const std::string& MCClientID::getID() const { return m_ID; } const std::string& MCClientID::getExternalID() const { return m_externalID; } const std::string& MCClientID::getRequester() const { return m_requester; } const std::string& MCClientID::getTopic() const { return m_topic; } const std::string& MCClientID::getUniqueID() const { return m_uniqueID; } } } }
34.884211
91
0.605914
FleX-d
00a8e8bfac26c1b692e05ae33bed080a8548d2c2
7,911
cpp
C++
OneCodeTeam/How to pick and manipulate a 3D object using DirectX in universal Windows apps/[C++]-How to pick and manipulate a 3D object using DirectX in universal Windows apps/C++/CppWindowsStoreGameAppManipulate3DObjects/DirectXPage.xaml.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
2
2022-01-21T01:40:58.000Z
2022-01-21T01:41:10.000Z
OneCodeTeam/How to pick and manipulate a 3D object using DirectX in universal Windows apps/[C++]-How to pick and manipulate a 3D object using DirectX in universal Windows apps/C++/CppWindowsStoreGameAppManipulate3DObjects/DirectXPage.xaml.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
1
2022-03-15T04:21:41.000Z
2022-03-15T04:21:41.000Z
OneCodeTeam/How to pick and manipulate a 3D object using DirectX in universal Windows apps/[C++]-How to pick and manipulate a 3D object using DirectX in universal Windows apps/C++/CppWindowsStoreGameAppManipulate3DObjects/DirectXPage.xaml.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
null
null
null
/****************************** Module Header ******************************\ * Module Name: DirectXPage.xaml.cpp * Project: CppWindowsStoreAppManipulate3DObjects * Copyright (c) Microsoft Corporation. * * This sample shows how to pick and manipulate 3D object in Windows Store DirectX game app. * * This source is subject to the Microsoft Public License. * See http://www.microsoft.com/en-us/openness/licenses.aspx#MPL * All other rights reserved. * * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. \***************************************************************************/ #include "pch.h" #include "DirectXPage.xaml.h" using namespace CppWindowsStoreAppManipulate3DObjects; using namespace Platform; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::Graphics::Display; using namespace Windows::UI::Input; using namespace Windows::UI::Core; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Controls::Primitives; using namespace Windows::UI::Xaml::Data; using namespace Windows::UI::Xaml::Input; using namespace Windows::UI::Xaml::Media; using namespace Windows::UI::Xaml::Navigation; DirectXPage::DirectXPage() : m_isNeedUpdate(false) { InitializeComponent(); DirectX::XMStoreFloat4x4(&m_transform, DirectX::XMMatrixIdentity()); m_cubeRenderer = ref new CubeRenderer(); DisplayInformation^ currentDisplayInformation = DisplayInformation::GetForCurrentView(); m_cubeRenderer->Initialize( Window::Current->CoreWindow, SwapChainPanel, currentDisplayInformation->LogicalDpi ); m_accessibilitySettings = ref new Windows::UI::ViewManagement::AccessibilitySettings; m_accessibilitySettings->HighContrastChanged += ref new TypedEventHandler<Windows::UI::ViewManagement::AccessibilitySettings^, Object^>(this, &DirectXPage::OnHighContrastChanged); if (m_accessibilitySettings->HighContrast) { LogoImage->Visibility = Windows::UI::Xaml::Visibility::Collapsed; } Window::Current->CoreWindow->SizeChanged += ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &DirectXPage::OnWindowSizeChanged); Window::Current->CoreWindow->PointerPressed += ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &DirectXPage::OnPointerPressed); currentDisplayInformation->DpiChanged += ref new TypedEventHandler<DisplayInformation^, Object^>(this, &DirectXPage::OnDpiChanged); currentDisplayInformation->OrientationChanged += ref new TypedEventHandler<DisplayInformation^, Object^>(this, &DirectXPage::OnOrientationChanged); DisplayInformation::DisplayContentsInvalidated += ref new TypedEventHandler<DisplayInformation^, Object^>(this, &DirectXPage::OnDisplayContentsInvalidated); m_eventToken = CompositionTarget::Rendering::add(ref new EventHandler<Object^>(this, &DirectXPage::OnRendering)); m_timer = ref new BasicTimer(); Windows::UI::Xaml::Media::SolidColorBrush^ br = (Windows::UI::Xaml::Media::SolidColorBrush^)Windows::UI::Xaml::Application::Current->Resources-> Lookup( "ApplicationPageBackgroundThemeBrush" ); Windows::UI::Color Color = br->Color; m_renderTargetColor[0] = Color.R; m_renderTargetColor[1] = Color.G; m_renderTargetColor[2] = Color.B; m_renderTargetColor[3] = Color.A; } void DirectXPage::OnPointerPressed(CoreWindow^ sender, PointerEventArgs^ args) { m_currentPoint = args->CurrentPoint->Position; Point pt = m_cubeRenderer->TransformToOrientation(m_currentPoint, true); bool isIntersects = m_cubeRenderer->IsIntersectsTriangle( pt.X, pt.Y); if (isIntersects) { m_pointerMoveToken = Window::Current->CoreWindow->PointerMoved += ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &DirectXPage::OnPointerMoved); sender->PointerCursor = ref new CoreCursor(CoreCursorType::SizeAll, 0); } m_lastPoint = m_currentPoint; } void DirectXPage::OnPointerMoved(CoreWindow^ sender, PointerEventArgs^ args) { m_currentPoint = args->CurrentPoint->Position; m_transform = m_cubeRenderer->TransformWithMouse(m_transType, m_lastPoint.X, m_lastPoint.Y, 0.0f, m_currentPoint.X, m_currentPoint.Y, 0.0f); m_isNeedUpdate = true; Window::Current->CoreWindow->PointerReleased += ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &DirectXPage::OnPointerReleased); m_lastPoint = m_currentPoint; } void DirectXPage::OnPointerReleased(CoreWindow^ sender, PointerEventArgs^ args) { m_isNeedUpdate = false; sender->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0); sender->PointerMoved -= m_pointerMoveToken; } void DirectXPage::OnHighContrastChanged(Windows::UI::ViewManagement::AccessibilitySettings^ sender, Object^ args) { if (sender->HighContrast) { LogoImage->Visibility = Windows::UI::Xaml::Visibility::Collapsed; } else { LogoImage->Visibility = Windows::UI::Xaml::Visibility::Visible; } // Update render target color. Windows::UI::Xaml::Media::SolidColorBrush^ br = (Windows::UI::Xaml::Media::SolidColorBrush^)Windows::UI::Xaml::Application::Current->Resources-> Lookup( "ApplicationPageBackgroundThemeBrush" ); Windows::UI::Color Color = br->Color; m_renderTargetColor[0] = Color.R; m_renderTargetColor[1] = Color.G; m_renderTargetColor[2] = Color.B; m_renderTargetColor[3] = Color.A; } void DirectXPage::OnWindowSizeChanged(CoreWindow^ sender, WindowSizeChangedEventArgs^ args) { m_cubeRenderer->UpdateForWindowSizeChange(); if (args->Size.Width <= 600) { VisualStateManager::GoToState(this, "MinimalLayout", true); } else if (args->Size.Width < args->Size.Height) { VisualStateManager::GoToState(this, "PortraitLayout", true); } else { VisualStateManager::GoToState(this, "DefaultLayout", true); } } void DirectXPage::OnDpiChanged(DisplayInformation^ sender, Object^ args) { m_cubeRenderer->SetDpi(sender->LogicalDpi); } void DirectXPage::OnOrientationChanged(DisplayInformation^ sender, Object^ args) { m_cubeRenderer->UpdateForWindowSizeChange(); } void DirectXPage::OnDisplayContentsInvalidated(DisplayInformation^ sender, Object^ args) { m_cubeRenderer->ValidateDevice(); } void DirectXPage::OnRendering(Object^ sender, Object^ args) { if (m_isNeedUpdate) { m_cubeRenderer->Update(m_transform); m_isNeedUpdate = false; } m_cubeRenderer->Render(m_renderTargetColor); m_cubeRenderer->Present(); } void CppWindowsStoreAppManipulate3DObjects::DirectXPage::RotateRB_Checked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { m_transType = TransformTypeEnum::Rotate; } void CppWindowsStoreAppManipulate3DObjects::DirectXPage::RotateRB_Unchecked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { m_transType = TransformTypeEnum::None; } void CppWindowsStoreAppManipulate3DObjects::DirectXPage::TranslateRB_Checked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { m_transType = TransformTypeEnum::Translate; } void CppWindowsStoreAppManipulate3DObjects::DirectXPage::TranslateRB_Unchecked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { m_transType = TransformTypeEnum::None; } void CppWindowsStoreAppManipulate3DObjects::DirectXPage::ScaleRB_Checked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { m_transType = TransformTypeEnum::Scale; } void CppWindowsStoreAppManipulate3DObjects::DirectXPage::ScaleRB_Unchecked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { m_transType = TransformTypeEnum::None; } void CppWindowsStoreAppManipulate3DObjects::DirectXPage::Footer_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { Windows::System::Launcher::LaunchUriAsync(ref new Uri((String^)((HyperlinkButton^)sender)->Tag)); }
33.66383
143
0.766148
zzgchina888
00a91f84c3c4a030231dfe34ccd9920cc2f4fa2e
1,456
cpp
C++
Source/AllProjects/LangUtils/CIDMacroEng/CIDMacroEng_DebugIntf.cpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
216
2019-03-09T06:41:28.000Z
2022-02-25T16:27:19.000Z
Source/AllProjects/LangUtils/CIDMacroEng/CIDMacroEng_DebugIntf.cpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
9
2020-09-27T08:00:52.000Z
2021-07-02T14:27:31.000Z
Source/AllProjects/LangUtils/CIDMacroEng/CIDMacroEng_DebugIntf.cpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
29
2019-03-09T10:12:24.000Z
2021-03-03T22:25:29.000Z
// // FILE NAME: CIDMacroEng_DebugIntf.cpp // // AUTHOR: Dean Roddey // // CREATED: 02/17/2003 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2019 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This file implements MMEngDebugIntf mixin class. Most of it is virtuals // that are implemented by the mixer inner. // // CAVEATS/GOTCHAS: // // LOG: // // $_CIDLib_Log_$ // // --------------------------------------------------------------------------- // Facility specific includes // --------------------------------------------------------------------------- #include "CIDMacroEng_.hpp" // --------------------------------------------------------------------------- // CLASS: MMEngDebugIntf // PREFIX: medbg // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // MMEngDebugIntf: Constructors and Destructor // --------------------------------------------------------------------------- MMEngDebugIntf::~MMEngDebugIntf() { } // --------------------------------------------------------------------------- // MMEngDebugIntf: Hidden constructors // --------------------------------------------------------------------------- MMEngDebugIntf::MMEngDebugIntf() { }
26
78
0.394231
MarkStega
00aff3b2a52f5102202db557b8d4647f818c7bc0
137
cpp
C++
src/polkawin.cpp
touhonoob/polkadot_api_cpp
65f0bddf3e9d64b773cfb8632d8b2d995bb143d8
[ "Apache-2.0" ]
null
null
null
src/polkawin.cpp
touhonoob/polkadot_api_cpp
65f0bddf3e9d64b773cfb8632d8b2d995bb143d8
[ "Apache-2.0" ]
null
null
null
src/polkawin.cpp
touhonoob/polkadot_api_cpp
65f0bddf3e9d64b773cfb8632d8b2d995bb143d8
[ "Apache-2.0" ]
null
null
null
#ifdef _WIN32 #include "polkadot.h" void usleep(__int64 usec) { std::this_thread::sleep_for(std::chrono::microseconds(usec)); } #endif
17.125
62
0.737226
touhonoob
00b02e610e8d9f42f84aadd1e42fd10505eb4908
778
cpp
C++
mathProb.cpp
ckronber/CPlusPlusCode
889e9301031217b37641d94e7ea52200e06e5862
[ "Unlicense" ]
null
null
null
mathProb.cpp
ckronber/CPlusPlusCode
889e9301031217b37641d94e7ea52200e06e5862
[ "Unlicense" ]
null
null
null
mathProb.cpp
ckronber/CPlusPlusCode
889e9301031217b37641d94e7ea52200e06e5862
[ "Unlicense" ]
null
null
null
#include <iostream> #include <cmath> #include <ctime> #define TIMES 10000000 using namespace std; int sequence(int n,int* arr) { int sum = 0; if(n == 1) { arr[0] = 0; return arr[0]; } else if(n == 2) { arr[1] = 1; return arr[1]; } else { sum = (arr[0]+arr[1])%3; arr[0] = arr[1]; arr[1] = sum; return sum; } } int main() { clock_t begin = clock(); int arr[2] = {0}; for(int i = 1;i<TIMES;i++) { sequence(i,arr); if(i == 1004) { cout <<"sequence("<<i <<") = " <<arr[i]; } } clock_t end = clock(); double elapsed_secs = double(end-begin)/CLOCKS_PER_SEC; cout <<endl <<"This code took " <<elapsed_secs <<" Seconds to execute." <<endl; return 0; }
14.961538
83
0.498715
ckronber
00b6f44979e07ad5cd603aad9d505830300c0ea9
9,289
cpp
C++
Source/processcontainers/implementations/RunCImplementation/RunCImplementation.cpp
zrash/Thunder
12d0021dc4aa49c9e3656178ef6485e2b1c8fecf
[ "Apache-2.0" ]
1
2020-10-29T18:10:27.000Z
2020-10-29T18:10:27.000Z
Source/processcontainers/implementations/RunCImplementation/RunCImplementation.cpp
zrash/Thunder
12d0021dc4aa49c9e3656178ef6485e2b1c8fecf
[ "Apache-2.0" ]
null
null
null
Source/processcontainers/implementations/RunCImplementation/RunCImplementation.cpp
zrash/Thunder
12d0021dc4aa49c9e3656178ef6485e2b1c8fecf
[ "Apache-2.0" ]
1
2020-08-13T06:26:43.000Z
2020-08-13T06:26:43.000Z
/* * If not stated otherwise in this file or this component's LICENSE file the * following copyright and licenses apply: * * Copyright 2020 Metrological * * 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 "RunCImplementation.h" #include "JSON.h" #include <thread> namespace WPEFramework { uint32_t callRunC(Core::Process::Options& options, string* output, uint32_t timeout = Core::infinite) { uint32_t result = Core::ERROR_NONE; bool capture = (output != nullptr); Core::Process process(capture); uint32_t pid; if (process.Launch(options, &pid) != Core::ERROR_NONE) { TRACE_L1("[RunC] Failed to launch runc"); result = Core::ERROR_UNAVAILABLE; } else { if (process.WaitProcessCompleted(timeout) != Core::ERROR_NONE) { TRACE_L1("[RunC] Call to runc timed out (%u ms)", timeout); result = Core::ERROR_TIMEDOUT; } else { if (process.ExitCode() != 0) { TRACE_L1("[RunC] Call to runc resulted in non-zero exit code: %d", process.ExitCode()); result = Core::ERROR_GENERAL; } else if (capture) { char buffer[2048]; while (process.Output(reinterpret_cast<uint8_t*>(buffer), sizeof(buffer)) > 0) { *output += buffer; } } } } return result; } class RunCStatus : public Core::JSON::Container { private: RunCStatus(const RunCStatus&); RunCStatus& operator=(const RunCStatus&); public: RunCStatus() : Core::JSON::Container() , Pid(0) , Status() { Add(_T("pid"), &Pid); Add(_T("status"), &Status); } ~RunCStatus() override = default; public: Core::JSON::DecUInt32 Pid; Core::JSON::String Status; }; class RunCListEntry : public Core::JSON::Container { private: RunCListEntry(const RunCListEntry&); RunCListEntry& operator=(const RunCListEntry&); public: RunCListEntry() : Core::JSON::Container() , Id() { Add(_T("id"), &Id); } ~RunCListEntry() override = default; public: Core::JSON::String Id; }; namespace ProcessContainers { // Container administrator // ---------------------------------- IContainerAdministrator& ProcessContainers::IContainerAdministrator::Instance() { static RunCContainerAdministrator& runCContainerAdministrator = Core::SingletonType<RunCContainerAdministrator>::Instance(); return runCContainerAdministrator; } IContainer* RunCContainerAdministrator::Container(const string& id, IStringIterator& searchpaths, const string& logpath, const string& configuration) { searchpaths.Reset(0); while (searchpaths.Next()) { auto path = searchpaths.Current(); Core::File configFile(path + "/Container/config.json"); if (configFile.Exists()) { // Make sure no leftover will interfere... if (ContainerNameTaken(id)) { DestroyContainer(id); } this->InternalLock(); RunCContainer* container = new RunCContainer(id, path + "/Container", logpath); InsertContainer(container); this->InternalUnlock(); return container; } } return nullptr; } RunCContainerAdministrator::RunCContainerAdministrator() : BaseContainerAdministrator() { } RunCContainerAdministrator::~RunCContainerAdministrator() { } void RunCContainerAdministrator::Logging(const string& logPath, const string& loggingOptions) { // Only container-scope logging } void RunCContainerAdministrator::DestroyContainer(const string& name) { if (callRunC(Core::Process::Options("/usr/bin/runc").Add("delete").Add("-f").Add(name), nullptr) != Core::ERROR_NONE) { TRACE_L1("Failed do destroy a container named %s", name.c_str()); } } bool RunCContainerAdministrator::ContainerNameTaken(const string& name) { bool result = false; string output = ""; if (callRunC(Core::Process::Options("/usr/bin/runc").Add("list").Add("-q"), &output) != Core::ERROR_NONE) { result = false; } else { result = (output.find(name) != std::string::npos); } return result; } // Container // ------------------------------------ RunCContainer::RunCContainer(const string& name, const string& path, const string& logPath) : _adminLock() , _name(name) , _path(path) , _logPath(logPath) , _pid() { } RunCContainer::~RunCContainer() { auto& admin = static_cast<RunCContainerAdministrator&>(RunCContainerAdministrator::Instance()); if (admin.ContainerNameTaken(_name) == true) { Stop(Core::infinite); } admin.RemoveContainer(this); } const string& RunCContainer::Id() const { return _name; } uint32_t RunCContainer::Pid() const { uint32_t returnedPid = 0; if (_pid.IsSet() == false) { Core::Process::Options options("/usr/bin/runc"); options.Add("state").Add(_name); Core::Process process(true); uint32_t tmp; if (process.Launch(options, &tmp) != Core::ERROR_NONE) { TRACE_L1("Failed to create RunC container with name: %s", _name.c_str()); returnedPid = 0; } else { process.WaitProcessCompleted(Core::infinite); if (process.ExitCode() != 0) { returnedPid = 0; } else { char data[1024]; process.Output((uint8_t*)data, 2048); RunCStatus info; info.FromString(string(data)); _pid = info.Pid.Value(); returnedPid = _pid; } } } return returnedPid; } IMemoryInfo* RunCContainer::Memory() const { CGroupMetrics containerMetrics(_name); return containerMetrics.Memory(); } IProcessorInfo* RunCContainer::ProcessorInfo() const { CGroupMetrics containerMetrics(_name); return containerMetrics.ProcessorInfo(); } INetworkInterfaceIterator* RunCContainer::NetworkInterfaces() const { return nullptr; } bool RunCContainer::IsRunning() const { bool result = false; string output = ""; if (callRunC(Core::Process::Options("/usr/bin/runc").Add("state").Add(_name), &output) != Core::ERROR_NONE) { result = false; } else { RunCStatus info; info.FromString(string(output)); result = info.Status.Value() == "running"; } return result; } bool RunCContainer::Start(const string& command, IStringIterator& parameters) { Core::JSON::ArrayType<Core::JSON::String> paramsJSON; Core::JSON::String tmp; bool result = false; _adminLock.Lock(); tmp = command; paramsJSON.Add(tmp); while (parameters.Next()) { tmp = parameters.Current(); paramsJSON.Add(tmp); } string paramsFormated; paramsJSON.ToString(paramsFormated); Core::Process::Options options("/usr/bin/runc"); if (_logPath.empty() == false) { // Create logging directory Core::Directory(_logPath.c_str()).CreatePath(); options.Add("-log").Add(_logPath + "container.log"); } options.Add("run") .Add("-d") .Add("--args") .Add(paramsFormated) .Add("-b") .Add(_path) .Add("--no-new-keyring") .Add(_name) .Add(command); if (callRunC(options, nullptr) != Core::ERROR_NONE) { TRACE_L1("Failed to create RunC container with name: %s", _name.c_str()); } else { result = true; } _adminLock.Unlock(); return result; } bool RunCContainer::Stop(const uint32_t timeout /*ms*/) { bool result = false; _adminLock.Lock(); if (callRunC(Core::Process::Options("/usr/bin/runc").Add("delete").Add("-f").Add(_name), nullptr, timeout) != Core::ERROR_NONE) { TRACE_L1("Failed to destroy RunC container named: %s", _name.c_str()); } else { result = true; } _adminLock.Unlock(); return result; } } // namespace ProcessContainers } // namespace WPEFramework
28.320122
153
0.57229
zrash
00b76c1e6e408c40c33875708a76d6e9d7bd3cac
1,450
cc
C++
P9-DataStructures(tuples)/P85696.cc
srmeeseeks/PRO1-jutge-FIB
3af3d28c77ff14a5dbff20b1b5ddc4178462d8a1
[ "MIT" ]
null
null
null
P9-DataStructures(tuples)/P85696.cc
srmeeseeks/PRO1-jutge-FIB
3af3d28c77ff14a5dbff20b1b5ddc4178462d8a1
[ "MIT" ]
null
null
null
P9-DataStructures(tuples)/P85696.cc
srmeeseeks/PRO1-jutge-FIB
3af3d28c77ff14a5dbff20b1b5ddc4178462d8a1
[ "MIT" ]
null
null
null
//Racionals (1) #include <iostream> using namespace std; struct Racional { int num, den; }; Racional racional(int n, int d) { Racional rac_norm; if (n == 0) { rac_norm.den = 1; rac_norm.num = 0; return rac_norm; } else { bool negar; if (n*d > 0) { if (n < 0) { n *= -1; d *= -1; } negar = false; } else { if (d < 0) d *= -1; else n *= -1; negar = true; } int petit; if (n < d) petit = n; else petit = d; for (int div = petit; div >= 2; --div) { if (n%div == 0 && d%div == 0) { n /= div; d /= div; } } if (not negar) rac_norm.num = n; else if (negar) rac_norm.num = n * -1; rac_norm.den = d; return rac_norm; } } int main() { int n, d; cin >> n >> d; Racional frac_norm = racional(n, d); cout << frac_norm.num << "/" << frac_norm.den << endl; }
26.363636
62
0.293103
srmeeseeks
00beb1058089007c94531eceeb5a4f322560b22f
4,218
cpp
C++
Uebung02/Main.cpp
Kaeltis/NAC
05b12fa4ebe44c41cc873dfa791fd8cbe1ed038f
[ "MIT" ]
null
null
null
Uebung02/Main.cpp
Kaeltis/NAC
05b12fa4ebe44c41cc873dfa791fd8cbe1ed038f
[ "MIT" ]
null
null
null
Uebung02/Main.cpp
Kaeltis/NAC
05b12fa4ebe44c41cc873dfa791fd8cbe1ed038f
[ "MIT" ]
null
null
null
#include "Matrix.h" #include "Vektor.h" #include "Vektor2D.h" #include "Gerade2D.h" #include "Funktion2D.h" #include <iostream> #include "NSFunktion2D.h" using namespace std; //#define UEBUNG1u2 //#define UEBUNG3 //#define UEBUNG4 //#define UEBUNG5 //#define UEBUNG6 //#define UEBUNG7 //#define UEBUNG8 #define UEBUNG9 int main() { { #ifdef UEBUNG1u2 // Anfang Uebung 2 cout << "--- Uebung 1/2 ---" << endl; Matrix myMatrix(2,1); myMatrix.ausgabe(true); Vektor myVektor(2); cout << "Betrag von Vektor: " << myVektor.betrag() << endl; Vektor2D a(3, 1), b(1, 2), c; a.ausgabe(true); b.ausgabe(true); c.ausgabe(true); c.addiere(a); b.addiere(c); cout << "Betrag von Vektor2D b: " << b.betrag() << endl; b.ausgabe(true); #endif #ifdef UEBUNG3 // Anfang Uebung 3 cout << endl << "--- Uebung 3 ---" << endl; Vektor2D* z = new Vektor2D(-3, 1); Vektor2D* w = new Vektor2D; a.addiere(*z); a.ausgabe(true); w->addiere(*z); w->ausgabe(true); w->addiere(b); w->ausgabe(true); Vektor2D u(1, 2); u.kopiereIn(w); u.kopiereIn(&a); w->ausgabe(true); a.ausgabe(true); z->ausgabe(true); a.ausgabe(true); cout << "Tausche z und a" << endl; tausche(z, &a); z->ausgabe(true); a.ausgabe(true); #endif #ifdef UEBUNG4 // Anfang Uebung 4 cout << endl << "--- Uebung 4 ---" << endl; Vektor2D v(1, 2), w(3, 4); Matrix M(2,1); Matrix* Mpointer; M = v; Mpointer = &v; std::cout << "Ausgabe von M und mit Mpointer" << std::endl; M.ausgabe(true); Mpointer->ausgabe(true); v.addiere(w); std::cout << "Ausgabe von v nach Addieren" << std::endl; v.ausgabe(true); std::cout << "Ausgabe von M/Mpointer nach Add." << std::endl; M.ausgabe(true); Mpointer->ausgabe(true); Vektor2D o(1, 1), p(-5, 0); cout << "Winkel: " << o.winkel(p) << endl; #endif #ifdef UEBUNG5 Vektor2D vektorArray[3]; Vektor2D* varr[2]; varr[0] = new Vektor2D(2, 3); varr[1] = new Vektor2D(-2, 1); varr[0]->addiere(*varr[1]); varr[0]->ausgabe(true); delete varr[0]; delete varr[1]; Gerade2D g(Vektor2D(-3, -4), Vektor2D(0, 0)); cout << g.gerichteterAbstand(Vektor2D(4,3)) << endl; #endif #ifdef UEBUNG6 cout << Gerade2D(Vektor2D(-3, -4)).aufGerade(Vektor2D(4, -3)) << endl; void geradenTest(const Gerade2D& g); geradenTest(Gerade2D(Vektor2D(-3, -4), Vektor2D(2, 3))); #endif #ifdef UEBUNG7 Matrix M(1, 2); M(1, 1) = 1; M(1, 2) = 125; Matrix N(2, 1); N(1, 1) = 2; N(2, 1) = 255; cout << M(1, 1) << endl; cout << M(1, 2) << endl; cout << N(1, 1) << endl; cout << N(2, 1) << endl; Vektor2D v(1, 2), w(3, 4); cout << w(2) << endl; void matrixTest(); matrixTest(); #endif #ifdef UEBUNG8 Funktion2D f; minimieren2D(f, Vektor2D(4, 0), 0.85); cout << "----------------------------------" << endl; minimieren2D(f, Vektor2D(4, 1), 0.75); cout << "----------------------------------" << endl; minimieren2D(f, Vektor2D(3.0, 1.0), 0.4); cout << "----------------------------------" << endl; #endif #ifdef UEBUNG9 NSFunktion2D ns; cout << "Bisektion" << endl; cout << "----------------------------------" << endl; cout << bisektion(ns, 3, 4.5) << endl; cout << "----------------------------------" << endl; cout << bisektion(ns, -3.5, 4.5) << endl; cout << "----------------------------------" << endl; cout << bisektion(ns, 0.1, 2) << endl; cout << "----------------------------------" << endl; cout << bisektion(ns, 1.4, 2) << endl; cout << "----------------------------------" << endl; cout << endl; cout << "Sekantenmethode" << endl; cout << "----------------------------------" << endl; cout << sekantenmethode(ns, 3, 4.5) << endl; cout << "----------------------------------" << endl; cout << sekantenmethode(ns, -3.5, 4.5) << endl; cout << "----------------------------------" << endl; cout << sekantenmethode(ns, 0.1, 2) << endl; cout << "----------------------------------" << endl; cout << sekantenmethode(ns, 1.4, 2) << endl; cout << "----------------------------------" << endl; #endif cout << endl << "--- ENDE ---" << endl; } cout << "Anzahl der Matrix Instanzen: " << Matrix::getCounter() << endl; return 0; }
20.985075
73
0.511854
Kaeltis
00bf4ebd0d5de66d3659cafe89bab97bef778aa3
17,390
cpp
C++
tools/paint/splinetransferfunction.cpp
stranddw/drishti
63973422fd0272e55f755aa51378ee1da0f4ef8a
[ "MIT" ]
118
2016-11-01T06:01:44.000Z
2022-03-30T05:20:19.000Z
tools/paint/splinetransferfunction.cpp
stranddw/drishti
63973422fd0272e55f755aa51378ee1da0f4ef8a
[ "MIT" ]
56
2016-09-30T09:29:36.000Z
2022-03-31T17:15:32.000Z
tools/paint/splinetransferfunction.cpp
stranddw/drishti
63973422fd0272e55f755aa51378ee1da0f4ef8a
[ "MIT" ]
28
2016-07-31T23:48:51.000Z
2021-05-25T05:32:47.000Z
#include <math.h> #include "splinetransferfunction.h" #include "staticfunctions.h" #include "global.h" QImage SplineTransferFunction::colorMapImage() { return m_colorMapImage; } int SplineTransferFunction::size() { return m_points.size(); } QGradientStops SplineTransferFunction::gradientStops() { return m_gradientStops; } QString SplineTransferFunction::name() {return m_name;} void SplineTransferFunction::setName(QString name) {m_name = name;} void SplineTransferFunction::setOn(int i, bool f) { while(m_on.count() <= i) m_on << false; m_on[i] = f; } bool SplineTransferFunction::on(int i) { if (m_on.count() <= i) return false; else return m_on[i]; } void SplineTransferFunction::switch1D() { if (Global::use1D() == false) return; QPointF pt = m_points[0]; m_points.clear(); pt.setY(1.0); m_points << pt; pt.setY(0.0); m_points << pt; pt = m_normalWidths[0]; m_normalWidths.clear(); m_normalWidths << pt; m_normalWidths << pt; m_normalRotations.clear(); m_normalRotations << 0.0 << 0.0; updateNormals(); updateColorMapImage(); } SplineTransferFunction::SplineTransferFunction() : QObject() { m_name = "TF"; m_on.clear(); m_points.clear(); m_points << QPointF(0.5, 1.0) << QPointF(0.5, 0.0); m_normals.clear(); m_rightNormals.clear(); m_leftNormals.clear(); m_normalWidths.clear(); m_normalWidths << QPointF(0.4, 0.4) << QPointF(0.4, 0.4); m_normalRotations.clear(); m_normalRotations << 0.0 << 0.0; m_gradientStops.clear(); m_gradientStops << QGradientStop(0.0, QColor(200,200,200,128)) << QGradientStop(1.0, QColor(255,255,255,128)); m_colorMapImage = QImage(256, 256, QImage::Format_ARGB32); m_colorMapImage.fill(0); switch1D(); updateNormals(); updateColorMapImage(); } SplineTransferFunction::~SplineTransferFunction() { m_on.clear(); m_name.clear(); m_points.clear(); m_normals.clear(); m_rightNormals.clear(); m_leftNormals.clear(); m_normalWidths.clear(); m_normalRotations.clear(); m_gradientStops.clear(); } QDomElement SplineTransferFunction::domElement(QDomDocument& doc) { QDomElement de = doc.createElement("transferfunction"); QString str; // -- name QDomText tn0 = doc.createTextNode(m_name); // -- points str.clear(); for(int i=0; i<m_points.count(); i++) str += QString("%1 %2 ").arg(m_points[i].x()).arg(m_points[i].y()); QDomText tn1 = doc.createTextNode(str); // -- normalWidths str.clear(); for(int i=0; i<m_points.count(); i++) str += QString("%1 %2 ").arg(m_normalWidths[i].x()).arg(m_normalWidths[i].y()); QDomText tn2 = doc.createTextNode(str); // -- normalRotations str.clear(); for(int i=0; i<m_points.count(); i++) str += QString("%1 ").arg(m_normalRotations[i]); QDomText tn3 = doc.createTextNode(str); // -- gradientStops str.clear(); for(int i=0; i<m_gradientStops.count(); i++) { float pos = m_gradientStops[i].first; QColor color = m_gradientStops[i].second; str += QString("%1 %2 %3 %4 %5 ").arg(pos). \ arg(color.red()).arg(color.green()).arg(color.blue()).arg(color.alpha()); } QDomText tn4 = doc.createTextNode(str); // -- sets str.clear(); for(int i=0; i<m_on.count(); i++) str += QString("%1 ").arg(m_on[i]); QDomText tn5 = doc.createTextNode(str); QDomElement de0 = doc.createElement("name"); QDomElement de1 = doc.createElement("points"); QDomElement de2 = doc.createElement("normalwidths"); QDomElement de3 = doc.createElement("normalrotations"); QDomElement de4 = doc.createElement("gradientstops"); QDomElement de5 = doc.createElement("sets"); de0.appendChild(tn0); de1.appendChild(tn1); de2.appendChild(tn2); de3.appendChild(tn3); de4.appendChild(tn4); de5.appendChild(tn5); de.appendChild(de0); de.appendChild(de1); de.appendChild(de2); de.appendChild(de3); de.appendChild(de4); de.appendChild(de5); return de; } void SplineTransferFunction::fromDomElement(QDomElement de) { m_on.clear(); m_name.clear(); m_points.clear(); m_normals.clear(); m_rightNormals.clear(); m_leftNormals.clear(); m_normalWidths.clear(); m_normalRotations.clear(); m_gradientStops.clear(); QDomNodeList dlist = de.childNodes(); for(int i=0; i<dlist.count(); i++) { QDomElement dnode = dlist.at(i).toElement(); if (dnode.tagName() == "name") { m_name = dnode.toElement().text(); } else if (dnode.tagName() == "points") { QString str = dnode.toElement().text(); QStringList strlist = str.split(" ", QString::SkipEmptyParts); for(int j=0; j<strlist.count()/2; j++) { float x,y; x = strlist[2*j].toFloat(); y = strlist[2*j+1].toFloat(); m_points << QPointF(x,y); } } else if (dnode.tagName() == "normalwidths") { QString str = dnode.toElement().text(); QStringList strlist = str.split(" ", QString::SkipEmptyParts); for(int j=0; j<strlist.count()/2; j++) { float x,y; x = strlist[2*j].toFloat(); y = strlist[2*j+1].toFloat(); m_normalWidths << QPointF(x,y); } } else if (dnode.tagName() == "normalrotations") { QString str = dnode.toElement().text(); QStringList strlist = str.split(" ", QString::SkipEmptyParts); for(int j=0; j<strlist.count(); j++) m_normalRotations << strlist[j].toFloat(); } else if (dnode.tagName() == "gradientstops") { QString str = dnode.toElement().text(); QStringList strlist = str.split(" ", QString::SkipEmptyParts); for(int j=0; j<strlist.count()/5; j++) { float pos, r,g,b,a; pos = strlist[5*j].toFloat(); r = strlist[5*j+1].toInt(); g = strlist[5*j+2].toInt(); b = strlist[5*j+3].toInt(); a = strlist[5*j+4].toInt(); m_gradientStops << QGradientStop(pos, QColor(r,g,b,a)); } } else if (dnode.tagName() == "sets") { QString str = dnode.toElement().text(); QStringList strlist = str.split(" ", QString::SkipEmptyParts); for(int j=0; j<strlist.count(); j++) m_on.append(strlist[j].toInt() > 0); } } updateNormals(); updateColorMapImage(); } SplineInformation SplineTransferFunction::getSpline() { SplineInformation splineInfo; splineInfo.setName(m_name); splineInfo.setOn(m_on); splineInfo.setPoints(m_points); splineInfo.setNormalWidths(m_normalWidths); splineInfo.setNormalRotations(m_normalRotations); splineInfo.setGradientStops(m_gradientStops); return splineInfo; } void SplineTransferFunction::setSpline(SplineInformation splineInfo) { m_name = splineInfo.name(); m_on = splineInfo.on(); m_points = splineInfo.points(); m_normalWidths = splineInfo.normalWidths(); m_normalRotations = splineInfo.normalRotations(); m_gradientStops = splineInfo.gradientStops(); updateNormals(); updateColorMapImage(); } void SplineTransferFunction::updateNormals() { m_normals.clear(); m_rightNormals.clear(); m_leftNormals.clear(); for (int i=0; i<m_points.size(); ++i) { QLineF ln; if (i == 0) ln = QLineF(m_points[i], m_points[i+1]); else if (i == m_points.size()-1) ln = QLineF(m_points[i-1], m_points[i]); else ln = QLineF(m_points[i-1], m_points[i+1]); QLineF unitVec; if (ln.length() > 0) unitVec = ln.normalVector().unitVector(); else unitVec = QLineF(QPointF(0,0), QPointF(1,0)); unitVec.translate(-unitVec.p1()); float a = m_normalRotations[i]; QPointF p1 = unitVec.p2(); QPointF p2; p2.setX(p1.x()*cos(a) + p1.y()*sin(a)); p2.setY(-p1.x()*sin(a) + p1.y()*cos(a)); unitVec = QLineF(QPointF(0,0), p2); QPointF v1, v2; v1 = m_points[i] + m_normalWidths[i].x()*unitVec.p2(); v2 = m_points[i] - m_normalWidths[i].y()*unitVec.p2(); m_normals << unitVec.p2(); m_rightNormals << v1; m_leftNormals << v2; } } void SplineTransferFunction::updateColorMapImage() { updateColorMapImageFor16bit(); return; m_colorMapImage.fill(0); QPainter colorMapPainter(&m_colorMapImage); colorMapPainter.setCompositionMode(QPainter::CompositionMode_Source); QPolygonF pointsLeft; pointsLeft.clear(); for (int i=0; i<m_points.size(); i++) { QPointF pt = m_leftNormals[i]; pointsLeft << QPointF(pt.x()*255, pt.y()*255); } QPolygonF pointsRight; pointsRight.clear(); for (int i=0; i<m_points.size(); i++) { QPointF pt = m_rightNormals[i]; pointsRight << QPointF(pt.x()*255, pt.y()*255); } QGradientStops gstops = StaticFunctions::resampleGradientStops(m_gradientStops); for (int i=1; i<m_points.size(); i++) { QPainterPath pathRight, pathLeft; getPainterPathSegment(&pathRight, pointsRight, i); getPainterPathSegment(&pathLeft, pointsLeft, i); float pathLen = 1.5*qMax(pathRight.length(), pathLeft.length()); for (int l=0; l<pathLen+1; l++) { QPointF vLeft, vRight; float frc = (float)l/(float)pathLen; vLeft = pathLeft.pointAtPercent(frc); vRight = pathRight.pointAtPercent(frc); QLinearGradient lg(vRight.x(), vRight.y(), vLeft.x(), vLeft.y()); lg.setStops(gstops); QPen pen; pen.setBrush(QBrush(lg)); pen.setWidth(2); colorMapPainter.setPen(pen); colorMapPainter.drawLine(vRight, vLeft); } } } void SplineTransferFunction::updateColorMapImageFor16bit() { m_colorMapImage.fill(0); int val0, val1; if (Global::bytesPerVoxel() == 1) { val0 = m_leftNormals[0].x()*255; val1 = m_rightNormals[0].x()*255; } else { val0 = m_leftNormals[0].x()*65535; val1 = m_rightNormals[0].x()*65535; } if (val1 < val0) { int vtmp = val0; val0 = val1; val1 = vtmp; } QGradientStops gstops; // // limit opacity to 252 to avoid overflow // for(int i=0; i<m_gradientStops.size(); i++) // { // float pos = m_gradientStops[i].first; // QColor color = m_gradientStops[i].second; // int r = color.red(); // int g = color.green(); // int b = color.blue(); // int a = color.alpha(); // a = qMin(252, a); // gstops << QGradientStop(pos, QColor(r,g,b,a)); // } // gstops = StaticFunctions::resampleGradientStops(gstops, 101); gstops = StaticFunctions::resampleGradientStops(m_gradientStops, 101); for (int i=val0; i<=val1; i++) { float frc = (float)(i-val0)/(float)(val1-val0); int g0 = frc*100; int g1 = qMin(100, g0+1); frc = frc*100 - g0; if (g0 == g1) frc = 0.0; QColor color0 = gstops[g0].second; QColor color1 = gstops[g1].second; float rb,gb,bb,ab, re,ge,be,ae,r,g,b,a; rb = color0.red(); gb = color0.green(); bb = color0.blue(); ab = color0.alpha(); re = color1.red(); ge = color1.green(); be = color1.blue(); ae = color1.alpha(); r = rb + frc*(re-rb); g = gb + frc*(ge-gb); b = bb + frc*(be-bb); a = ab + frc*(ae-ab); QColor finalColor = QColor(r, g, b, a); int x = i/256; int y = i%256; m_colorMapImage.setPixel(y,255-x, qRgba(r,g,b,a)); } } void SplineTransferFunction::getPainterPathSegment(QPainterPath *path, QPolygonF points, int i) { path->moveTo(points[i-1]); QPointF p1, c1, c2, p2; QPointF midpt; p1 = points[i-1]; p2 = points[i]; midpt = (p1+p2)/2; QLineF l0, l1, l2; float dotp; l1 = QLineF(p1, p2); if (i > 1) l1 = QLineF(points[i-2], p2); if (l1.length() > 0) l1 = l1.unitVector(); else l1 = QLineF(l1.p1(), l1.p1()+QPointF(1,0)); l0 = QLineF(p1, midpt); dotp = l0.dx()*l1.dx() + l0.dy()*l1.dy(); if (dotp < 0) l1.setLength(-dotp); else l1.setLength(dotp); c1 = p1 + QPointF(l1.dx(), l1.dy()); l2 = QLineF(p1, p2);; if (i < m_points.size()-1) l2 = QLineF(p1, points[i+1]); if (l2.length() > 0) l2 = l2.unitVector(); else l2 = QLineF(l2.p1(), l2.p1()+QPointF(1,0)); l0 = QLineF(p2, midpt); dotp = l0.dx()*l2.dx() + l0.dy()*l2.dy(); if (dotp < 0) l2.setLength(-dotp); else l2.setLength(dotp); c2 = p2 - QPointF(l2.dx(), l2.dy()); path->cubicTo(c1, c2, p2); } void SplineTransferFunction::setGradientStops(QGradientStops stop) { m_gradientStops = stop; updateColorMapImage(); } QPointF SplineTransferFunction::pointAt(int i) { if (i < m_points.size()) return m_points[i]; else return QPointF(-1,-1); } QPointF SplineTransferFunction::rightNormalAt(int i) { if (i < m_points.size()) return m_rightNormals[i]; else return QPointF(-1,-1); } QPointF SplineTransferFunction::leftNormalAt(int i) { if (i < m_points.size()) return m_leftNormals[i]; else return QPointF(-1,-1); } void SplineTransferFunction::removePointAt(int index) { if (Global::use1D()) return; m_points.remove(index); m_normalRotations.remove(index); m_normalWidths.remove(index); updateNormals(); updateColorMapImage(); } void SplineTransferFunction::appendPoint(QPointF sp) { if (Global::use1D()) return; m_points.push_back(sp); float rot = m_normalRotations[m_normalRotations.size()-1]; m_normalRotations.push_back(rot); QPointF nw = m_normalWidths[m_normalWidths.size()-1]; m_normalWidths.push_back(nw); updateNormals(); updateColorMapImage(); } void SplineTransferFunction::insertPointAt(int i, QPointF sp) { if (Global::use1D()) return; if (i == 0) { m_points.insert(i, sp); float rot = m_normalRotations[i]; m_normalRotations.insert(i, rot); QPointF nw = m_normalWidths[i]; m_normalWidths.insert(i, nw); } else { m_points.insert(i, sp); float rot = (m_normalRotations[i]+m_normalRotations[i-1])/2; m_normalRotations.insert(i, rot); QPointF nw = (m_normalWidths[i]+m_normalWidths[i-1])/2; m_normalWidths.insert(i, nw); } updateNormals(); updateColorMapImage(); } void SplineTransferFunction::moveAllPoints(const QPointF diff) { for (int i=0; i<m_points.size(); i++) m_points[i] += diff; updateNormals(); updateColorMapImage(); } void SplineTransferFunction::movePointAt(int index, QPointF point) { if (Global::use1D()) { m_points[0].setX(point.x()); m_points[1].setX(point.x()); } else m_points[index] = point; updateNormals(); updateColorMapImage(); } void SplineTransferFunction::rotateNormalAt(int idxCenter, int idxNormal, QPointF point) { if (Global::use1D()) return; QLineF dir, normVec, ln; if (idxCenter == 0) dir = QLineF(m_points[idxCenter], m_points[idxCenter+1]); else if (idxCenter == m_points.size()-1) dir = QLineF(m_points[idxCenter-1], m_points[idxCenter]); else dir = QLineF(m_points[idxCenter-1], m_points[idxCenter+1]); if (dir.length() > 0) dir = dir.unitVector(); else dir = QLineF(dir.p1(), dir.p1()+QPointF(1,0)); normVec = dir.normalVector(); ln = QLineF(m_points[idxCenter], point); ln.translate(-ln.p1()); float angle = 0;; if (idxNormal == RightNormal) { float angle1, angle2; angle1 = atan2(-ln.dy(), ln.dx()); angle2 = atan2(-normVec.dy(), normVec.dx()); angle = angle1-angle2; } else // LeftNormal { float angle1, angle2; angle1 = atan2(-ln.dy(), ln.dx()); angle2 = atan2(normVec.dy(), -normVec.dx()); angle = angle1-angle2; } m_normalRotations[idxCenter] = angle; updateNormals(); updateColorMapImage(); } void SplineTransferFunction::moveNormalAt(int idxCenter, int idxNormal, QPointF point, bool shiftModifier) { if (idxNormal == RightNormal) // move rigntNormal { QLineF l0 = QLineF(m_points[idxCenter], point); float dotp = (m_normals[idxCenter].x()*l0.dx() + m_normals[idxCenter].y()*l0.dy()); if (dotp >= 0) m_normalWidths[idxCenter].setX(dotp); else m_normalWidths[idxCenter].setX(0); if (shiftModifier) { float w = m_normalWidths[idxCenter].x(); m_normalWidths[idxCenter].setY(w); } } else if (idxNormal == LeftNormal) // move rigntNormal { QLineF l0 = QLineF(point, m_points[idxCenter]); float dotp = (m_normals[idxCenter].x()*l0.dx() + m_normals[idxCenter].y()*l0.dy()); if (dotp >= 0) m_normalWidths[idxCenter].setY(dotp); else m_normalWidths[idxCenter].setY(0); if (shiftModifier) { float w = m_normalWidths[idxCenter].y(); m_normalWidths[idxCenter].setX(w); } } if (Global::use1D()) { if (idxCenter == 0) m_normalWidths[1] = m_normalWidths[0]; else m_normalWidths[0] = m_normalWidths[1]; } updateNormals(); updateColorMapImage(); } void SplineTransferFunction::set16BitPoint(float tmin, float tmax) { float tmid = (tmax+tmin)*0.5; float tlen2 = (tmax-tmin)*0.5; m_points.clear(); m_points << QPointF(tmid, 1.0) << QPointF(tmid, 0.0); m_normalWidths.clear(); m_normalWidths << QPointF(tlen2,tlen2) << QPointF(tlen2,tlen2); m_normalRotations.clear(); m_normalRotations << 0.0 << 0.0; updateNormals(); updateColorMapImage(); }
22.911726
84
0.621392
stranddw
00c7dbd1e57280223ee6562dfb67b3bc4a788034
536
hpp
C++
src/LibCraft/coreEngine/include/Map.hpp
Kenny38GH/Test
24c0277de8f98a3b0b3b8a90a300a321a485684c
[ "MIT" ]
null
null
null
src/LibCraft/coreEngine/include/Map.hpp
Kenny38GH/Test
24c0277de8f98a3b0b3b8a90a300a321a485684c
[ "MIT" ]
null
null
null
src/LibCraft/coreEngine/include/Map.hpp
Kenny38GH/Test
24c0277de8f98a3b0b3b8a90a300a321a485684c
[ "MIT" ]
null
null
null
// // Created by leodlplq on 22/11/2021. // #pragma once #include "LibCraft/renderEngine/include/Cube.hpp" #include "LibCraft/tools/include/filePath.hpp" #include "LibCraft/tools/include/getFIleContent.hpp" #include <vector> #include <fstream> #include <iostream> class Map { private: std::vector<Cube> _map; public: Map(); explicit Map(FilePath pathToMap); ~Map() = default; inline const std::vector<Cube> getMap() const {return _map;} void generateCubeMap(FilePath pathToMap); void display() const; };
20.615385
64
0.705224
Kenny38GH
00ccd2bfcbee92d1b2a2593415c45b99f13ad9dc
6,712
cpp
C++
Userland/Applications/SoundPlayer/main.cpp
andrigamerita/serenity
cf44bbdd0d5f1aaa58fd8c8f40de57addc65e858
[ "BSD-2-Clause" ]
1
2021-06-11T03:11:11.000Z
2021-06-11T03:11:11.000Z
Userland/Applications/SoundPlayer/main.cpp
andrigamerita/serenity
cf44bbdd0d5f1aaa58fd8c8f40de57addc65e858
[ "BSD-2-Clause" ]
null
null
null
Userland/Applications/SoundPlayer/main.cpp
andrigamerita/serenity
cf44bbdd0d5f1aaa58fd8c8f40de57addc65e858
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org> * 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 HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "NoVisualizationWidget.h" #include "Player.h" #include "SampleWidget.h" #include "SoundPlayerWidgetAdvancedView.h" #include <LibAudio/ClientConnection.h> #include <LibGUI/Action.h> #include <LibGUI/Application.h> #include <LibGUI/FilePicker.h> #include <LibGUI/Menu.h> #include <LibGUI/MenuBar.h> #include <LibGUI/Window.h> #include <LibGfx/CharacterBitmap.h> #include <stdio.h> int main(int argc, char** argv) { if (pledge("stdio recvfd sendfd accept rpath thread unix cpath fattr", nullptr) < 0) { perror("pledge"); return 1; } auto app = GUI::Application::construct(argc, argv); if (pledge("stdio recvfd sendfd accept rpath thread unix", nullptr) < 0) { perror("pledge"); return 1; } auto audio_client = Audio::ClientConnection::construct(); audio_client->handshake(); if (pledge("stdio recvfd sendfd accept rpath thread", nullptr) < 0) { perror("pledge"); return 1; } PlaybackManager playback_manager(audio_client); PlayerState initial_player_state { true, true, false, false, false, 44100, 1.0, audio_client, playback_manager, "" }; auto app_icon = GUI::Icon::default_icon("app-sound-player"); auto window = GUI::Window::construct(); window->set_title("Sound Player"); window->set_icon(app_icon.bitmap_for_size(16)); auto menubar = GUI::MenuBar::construct(); auto& app_menu = menubar->add_menu("File"); auto& playlist_menu = menubar->add_menu("Playlist"); String path = argv[1]; // start in advanced view by default Player* player = &window->set_main_widget<SoundPlayerWidgetAdvancedView>(window, initial_player_state); if (argc > 1) { player->open_file(path); } app_menu.add_action(GUI::CommonActions::make_open_action([&](auto&) { Optional<String> path = GUI::FilePicker::get_open_filepath(window, "Open sound file..."); if (path.has_value()) { player->open_file(path.value()); } })); auto linear_volume_slider = GUI::Action::create_checkable("Nonlinear volume slider", [&](auto& action) { static_cast<SoundPlayerWidgetAdvancedView*>(player)->set_nonlinear_volume_slider(action.is_checked()); }); app_menu.add_action(linear_volume_slider); auto playlist_toggle = GUI::Action::create_checkable("Show playlist", [&](auto& action) { static_cast<SoundPlayerWidgetAdvancedView*>(player)->set_playlist_visible(action.is_checked()); }); playlist_menu.add_action(playlist_toggle); if (path.ends_with(".m3u") || path.ends_with(".m3u8")) playlist_toggle->set_checked(true); playlist_menu.add_separator(); auto playlist_loop_toggle = GUI::Action::create_checkable("Loop playlist", [&](auto& action) { static_cast<SoundPlayerWidgetAdvancedView*>(player)->set_looping_playlist(action.is_checked()); }); playlist_menu.add_action(playlist_loop_toggle); app_menu.add_separator(); app_menu.add_action(GUI::CommonActions::make_quit_action([&](auto&) { app->quit(); })); auto& playback_menu = menubar->add_menu("Playback"); auto loop = GUI::Action::create_checkable("Loop", { Mod_Ctrl, Key_R }, [&](auto& action) { player->set_looping_file(action.is_checked()); }); playback_menu.add_action(move(loop)); auto& visualization_menu = menubar->add_menu("Visualization"); Vector<NonnullRefPtr<GUI::Action>> visualization_checkmarks; GUI::Action* checked_vis = nullptr; auto uncheck_all_but = [&](GUI::Action& one) {for (auto& a : visualization_checkmarks) if (a != &one) a->set_checked(false); }; auto bars = GUI::Action::create_checkable("Bars", [&](auto& action) { uncheck_all_but(action); if (checked_vis == &action) { action.set_checked(true); return; } checked_vis = &action; static_cast<SoundPlayerWidgetAdvancedView*>(player)->set_visualization<BarsVisualizationWidget>(); }); bars->set_checked(true); visualization_menu.add_action(bars); visualization_checkmarks.append(bars); auto samples = GUI::Action::create_checkable("Samples", [&](auto& action) { uncheck_all_but(action); if (checked_vis == &action) { action.set_checked(true); return; } checked_vis = &action; static_cast<SoundPlayerWidgetAdvancedView*>(player)->set_visualization<SampleWidget>(); }); visualization_menu.add_action(samples); visualization_checkmarks.append(samples); auto none = GUI::Action::create_checkable("None", [&](auto& action) { uncheck_all_but(action); if (checked_vis == &action) { action.set_checked(true); return; } checked_vis = &action; static_cast<SoundPlayerWidgetAdvancedView*>(player)->set_visualization<NoVisualizationWidget>(); }); visualization_menu.add_action(none); visualization_checkmarks.append(none); auto& help_menu = menubar->add_menu("Help"); help_menu.add_action(GUI::CommonActions::make_about_action("Sound Player", app_icon, window)); window->set_menubar(move(menubar)); window->show(); return app->exec(); }
36.281081
131
0.684148
andrigamerita
00cce04dd60404fee9e05e8f3f6a04dae9e294fd
12,398
cpp
C++
NextEngine/src/physics/btWrapper.cpp
CompilerLuke/NextEngine
aa1a8e9d9370bce004dba00854701597cab74989
[ "MIT" ]
1
2021-09-10T18:19:16.000Z
2021-09-10T18:19:16.000Z
NextEngine/src/physics/btWrapper.cpp
CompilerLuke/NextEngine
aa1a8e9d9370bce004dba00854701597cab74989
[ "MIT" ]
null
null
null
NextEngine/src/physics/btWrapper.cpp
CompilerLuke/NextEngine
aa1a8e9d9370bce004dba00854701597cab74989
[ "MIT" ]
2
2020-04-02T06:46:56.000Z
2021-06-17T16:47:57.000Z
/* #include "stdafx.h" #include "physics/btWrapper.h" #include <iostream> #include <btBulletDynamicsCommon.h> #include <LinearMath/btVector3.h> #include <LinearMath/btAlignedObjectArray.h> #include <BulletCollision\CollisionShapes/btHeightfieldTerrainShape.h> struct BulletWrapper { btDefaultCollisionConfiguration* collisionConfiguration; btCollisionDispatcher* dispatcher; btBroadphaseInterface* overlappingPairCache; btSequentialImpulseConstraintSolver* solver; btDiscreteDynamicsWorld* dynamicsWorld; }; BulletWrapper* make_BulletWrapper() { BulletWrapper* self = new BulletWrapper; self->overlappingPairCache = new btDbvtBroadphase(); self->collisionConfiguration = new btDefaultCollisionConfiguration(); self->dispatcher = new btCollisionDispatcher(self->collisionConfiguration); self->solver = new btSequentialImpulseConstraintSolver(); self->dynamicsWorld = new btDiscreteDynamicsWorld(self->dispatcher, self->overlappingPairCache, self->solver, self->collisionConfiguration); self->dynamicsWorld->setGravity(btVector3(0, -9.81f, 0)); return self; } btCollisionShape* make_BoxShape(glm::vec3 position) { btCollisionShape* shape = new btBoxShape(btVector3(position.x, position.y, position.z)); return shape; } btCollisionShape* make_SphereShape(float r) { btCollisionShape* shape = new btSphereShape(btScalar(r)); return shape; } btCollisionShape* make_CapsuleShape(float r, float height) { btCapsuleShape* shape = new btCapsuleShape(r, height); return shape; } btCollisionShape* make_Heightfield(int heightStickWidth, int heightStickLength, const float* heightfieldData, float heightScale, float minHeight, float maxHeight ) { return new btHeightfieldTerrainShape(heightStickWidth, heightStickLength, heightfieldData, heightScale, minHeight, maxHeight, 1, PHY_FLOAT, false); } btCollisionShape* make_PlaneShape(glm::vec3 normal) { return new btStaticPlaneShape(btVector3(normal.x, normal.y, normal.z), 0); } btRigidBody* make_RigidBody(BulletWrapper* self, RigidBodySettings* settings) { btTransform groundTransform; groundTransform.setIdentity(); groundTransform.setOrigin(btVector3(settings->origin.x, settings->origin.y, settings->origin.z)); //rigidbody is dynamic if and only if mass is non zero, otherwise static bool isDynamic = (settings->mass != 0.f); btVector3 localInertia; if (isDynamic) { settings->shape->calculateLocalInertia(settings->mass, localInertia); } //using motionstate is optional, it provides interpolation capabilities, and only synchronizes 'active' objects btDefaultMotionState* myMotionState = new btDefaultMotionState(groundTransform); //todo use this to sync objects btRigidBody::btRigidBodyConstructionInfo rbInfo(settings->mass, myMotionState, settings->shape, localInertia); btRigidBody* body = new btRigidBody(rbInfo); if (settings->lock_rotation) { body->setAngularFactor(btVector3(0, 0, 0)); } if (settings->sweep_radius > 0) { body->setCcdMotionThreshold(1e-7f); body->setCcdSweptSphereRadius(settings->sweep_radius); } btVector3 velocity(settings->velocity.x, settings->velocity.y, settings->velocity.z); body->setLinearVelocity(velocity); int* id = new int; *id = settings->id; body->setUserPointer(id); //add the body to the dynamics world self->dynamicsWorld->addRigidBody(body); return body; } void free_RigidBody(BulletWrapper* self, btRigidBody* body) { if (body && body->getMotionState()) { delete body->getMotionState(); } self->dynamicsWorld->removeCollisionObject(body); } unsigned int id_of_RigidBody(btRigidBody* body) { return *((unsigned int*)body->getUserPointer()); } void transform_of_RigidBody(btRigidBody* body, BulletWrapperTransform* wrapper_transform) { btTransform trans; if (body && body->getMotionState()) { body->getMotionState()->getWorldTransform(trans); } else { trans = body->getWorldTransform(); } wrapper_transform->position.x = trans.getOrigin().getX(); wrapper_transform->position.y = trans.getOrigin().getY(); wrapper_transform->position.z = trans.getOrigin().getZ(); wrapper_transform->rotation.w = trans.getRotation().getW(); wrapper_transform->rotation.x = trans.getRotation().getX(); wrapper_transform->rotation.y = trans.getRotation().getY(); wrapper_transform->rotation.z = trans.getRotation().getZ(); wrapper_transform->velocity.x = body->getLinearVelocity().getX(); wrapper_transform->velocity.y = body->getLinearVelocity().getY(); wrapper_transform->velocity.z = body->getLinearVelocity().getZ(); } void set_transform_of_RigidBody(btRigidBody* body, BulletWrapperTransform* wrapper_transform) { btTransform trans; if (body && body->getMotionState()) { body->getMotionState()->getWorldTransform(trans); } else { trans = body->getWorldTransform(); } body->activate(); btVector3 position(wrapper_transform->position.x, wrapper_transform->position.y, wrapper_transform->position.z); btQuaternion rotation; rotation.setX(wrapper_transform->rotation.x); rotation.setY(wrapper_transform->rotation.y); rotation.setZ(wrapper_transform->rotation.z); //std::cout << "Set object to position" << position.x() << "," << position.y() << "," << position.z() << std::endl; trans.setOrigin(position); trans.setRotation(rotation); btVector3 velocity(wrapper_transform->velocity.x, wrapper_transform->velocity.y, wrapper_transform->velocity.z); body->setLinearVelocity(velocity); } void step_BulletWrapper(BulletWrapper* self, double delta) { self->dynamicsWorld->stepSimulation(delta); } void free_BulletWrapper(BulletWrapper* self) { //remove the rigidbodies from the dynamics world and delete them for (int i = self->dynamicsWorld->getNumCollisionObjects() - 1; i >= 0; i--) { btCollisionObject* obj = self->dynamicsWorld->getCollisionObjectArray()[i]; btRigidBody* body = btRigidBody::upcast(obj); if (body && body->getMotionState()) { delete body->getMotionState(); } self->dynamicsWorld->removeCollisionObject(obj); delete obj; } delete self->dynamicsWorld; delete self->overlappingPairCache; delete self->collisionConfiguration; delete self->dispatcher; delete self; } void free_collision_shape(btCollisionShape* shape) { delete shape; }#include "stdafx.h" #include "physics/btWrapper.h" #include <iostream> #include <btBulletDynamicsCommon.h> #include <LinearMath/btVector3.h> #include <LinearMath/btAlignedObjectArray.h> #include <BulletCollision\CollisionShapes/btHeightfieldTerrainShape.h> struct BulletWrapper { btDefaultCollisionConfiguration* collisionConfiguration; btCollisionDispatcher* dispatcher; btBroadphaseInterface* overlappingPairCache; btSequentialImpulseConstraintSolver* solver; btDiscreteDynamicsWorld* dynamicsWorld; }; BulletWrapper* make_BulletWrapper() { BulletWrapper* self = new BulletWrapper; self->overlappingPairCache = new btDbvtBroadphase(); self->collisionConfiguration = new btDefaultCollisionConfiguration(); self->dispatcher = new btCollisionDispatcher(self->collisionConfiguration); self->solver = new btSequentialImpulseConstraintSolver(); self->dynamicsWorld = new btDiscreteDynamicsWorld(self->dispatcher, self->overlappingPairCache, self->solver, self->collisionConfiguration); self->dynamicsWorld->setGravity(btVector3(0, -9.81f, 0)); return self; } btCollisionShape* make_BoxShape(glm::vec3 position) { btCollisionShape* shape = new btBoxShape(btVector3(position.x, position.y, position.z)); return shape; } btCollisionShape* make_SphereShape(float r) { btCollisionShape* shape = new btSphereShape(btScalar(r)); return shape; } btCollisionShape* make_CapsuleShape(float r, float height) { btCapsuleShape* shape = new btCapsuleShape(r, height); return shape; } btCollisionShape* make_Heightfield(int heightStickWidth, int heightStickLength, const float* heightfieldData, float heightScale, float minHeight, float maxHeight ) { return new btHeightfieldTerrainShape(heightStickWidth, heightStickLength, heightfieldData, heightScale, minHeight, maxHeight, 1, PHY_FLOAT, false); } btCollisionShape* make_PlaneShape(glm::vec3 normal) { return new btStaticPlaneShape(btVector3(normal.x, normal.y, normal.z), 0); } btRigidBody* make_RigidBody(BulletWrapper* self, RigidBodySettings* settings) { btTransform groundTransform; groundTransform.setIdentity(); groundTransform.setOrigin(btVector3(settings->origin.x, settings->origin.y, settings->origin.z)); //rigidbody is dynamic if and only if mass is non zero, otherwise static bool isDynamic = (settings->mass != 0.f); btVector3 localInertia; if (isDynamic) { settings->shape->calculateLocalInertia(settings->mass, localInertia); } //using motionstate is optional, it provides interpolation capabilities, and only synchronizes 'active' objects btDefaultMotionState* myMotionState = new btDefaultMotionState(groundTransform); //todo use this to sync objects btRigidBody::btRigidBodyConstructionInfo rbInfo(settings->mass, myMotionState, settings->shape, localInertia); btRigidBody* body = new btRigidBody(rbInfo); if (settings->lock_rotation) { body->setAngularFactor(btVector3(0, 0, 0)); } if (settings->sweep_radius > 0) { body->setCcdMotionThreshold(1e-7f); body->setCcdSweptSphereRadius(settings->sweep_radius); } btVector3 velocity(settings->velocity.x, settings->velocity.y, settings->velocity.z); body->setLinearVelocity(velocity); int* id = new int; *id = settings->id; body->setUserPointer(id); //add the body to the dynamics world self->dynamicsWorld->addRigidBody(body); return body; } void free_RigidBody(BulletWrapper* self, btRigidBody* body) { if (body && body->getMotionState()) { delete body->getMotionState(); } self->dynamicsWorld->removeCollisionObject(body); } unsigned int id_of_RigidBody(btRigidBody* body) { return *((unsigned int*)body->getUserPointer()); } void transform_of_RigidBody(btRigidBody* body, BulletWrapperTransform* wrapper_transform) { btTransform trans; if (body && body->getMotionState()) { body->getMotionState()->getWorldTransform(trans); } else { trans = body->getWorldTransform(); } wrapper_transform->position.x = trans.getOrigin().getX(); wrapper_transform->position.y = trans.getOrigin().getY(); wrapper_transform->position.z = trans.getOrigin().getZ(); wrapper_transform->rotation.w = trans.getRotation().getW(); wrapper_transform->rotation.x = trans.getRotation().getX(); wrapper_transform->rotation.y = trans.getRotation().getY(); wrapper_transform->rotation.z = trans.getRotation().getZ(); wrapper_transform->velocity.x = body->getLinearVelocity().getX(); wrapper_transform->velocity.y = body->getLinearVelocity().getY(); wrapper_transform->velocity.z = body->getLinearVelocity().getZ(); } void set_transform_of_RigidBody(btRigidBody* body, BulletWrapperTransform* wrapper_transform) { btTransform trans; if (body && body->getMotionState()) { body->getMotionState()->getWorldTransform(trans); } else { trans = body->getWorldTransform(); } body->activate(); btVector3 position(wrapper_transform->position.x, wrapper_transform->position.y, wrapper_transform->position.z); btQuaternion rotation; rotation.setX(wrapper_transform->rotation.x); rotation.setY(wrapper_transform->rotation.y); rotation.setZ(wrapper_transform->rotation.z); //std::cout << "Set object to position" << position.x() << "," << position.y() << "," << position.z() << std::endl; trans.setOrigin(position); trans.setRotation(rotation); btVector3 velocity(wrapper_transform->velocity.x, wrapper_transform->velocity.y, wrapper_transform->velocity.z); body->setLinearVelocity(velocity); } void step_BulletWrapper(BulletWrapper* self, double delta) { self->dynamicsWorld->stepSimulation(delta); } void free_BulletWrapper(BulletWrapper* self) { //remove the rigidbodies from the dynamics world and delete them for (int i = self->dynamicsWorld->getNumCollisionObjects() - 1; i >= 0; i--) { btCollisionObject* obj = self->dynamicsWorld->getCollisionObjectArray()[i]; btRigidBody* body = btRigidBody::upcast(obj); if (body && body->getMotionState()) { delete body->getMotionState(); } self->dynamicsWorld->removeCollisionObject(obj); delete obj; } delete self->dynamicsWorld; delete self->overlappingPairCache; delete self->collisionConfiguration; delete self->dispatcher; delete self; } void free_collision_shape(btCollisionShape* shape) { delete shape; } */
31.547074
141
0.767543
CompilerLuke
00ce2dcdf5287aaee131abca098a547dfa007202
1,688
cpp
C++
engine/decision_strategies/deity/source/UncurseDeityDecisionStrategyHandler.cpp
sidav/shadow-of-the-wyrm
747afdeebed885b1a4f7ab42f04f9f756afd3e52
[ "MIT" ]
1
2020-05-24T22:44:03.000Z
2020-05-24T22:44:03.000Z
engine/decision_strategies/deity/source/UncurseDeityDecisionStrategyHandler.cpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
null
null
null
engine/decision_strategies/deity/source/UncurseDeityDecisionStrategyHandler.cpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
null
null
null
#include "DeityTextKeys.hpp" #include "CombatManager.hpp" #include "Game.hpp" #include "MapUtils.hpp" #include "UncurseDeityDecisionStrategyHandler.hpp" using namespace std; UncurseDeityDecisionStrategyHandler::UncurseDeityDecisionStrategyHandler(const string& new_deity_id) : DeityDecisionStrategyHandler(new_deity_id) { } bool UncurseDeityDecisionStrategyHandler::decide(CreaturePtr creature) { bool uncurse_creature = false; if (creature != nullptr) { Equipment& eq = creature->get_equipment(); EquipmentMap em = eq.get_equipment(); for (const auto& eq_pair : em) { if (eq_pair.second != nullptr && eq_pair.second->get_status() == ItemStatus::ITEM_STATUS_CURSED) { uncurse_creature = true; break; } } } return uncurse_creature; } // When a deity lifts a curse, they set all the cursed worn equipment to // uncursed and identified. DeityDecisionImplications UncurseDeityDecisionStrategyHandler::handle_decision(CreaturePtr creature, TilePtr tile) { if (creature != nullptr) { EquipmentMap em = creature->get_equipment().get_equipment(); for (auto& em_pair : em) { if (em_pair.second && em_pair.second->get_status() == ItemStatus::ITEM_STATUS_CURSED) { em_pair.second->set_status(ItemStatus::ITEM_STATUS_UNCURSED); em_pair.second->set_status_identified(true); } } } return get_deity_decision_implications(creature, tile); } int UncurseDeityDecisionStrategyHandler::get_piety_loss() const { return 800; } string UncurseDeityDecisionStrategyHandler::get_message_sid() const { string message_sid = DeityTextKeys::PRAYER_UNCURSE; return message_sid; }
25.19403
114
0.73282
sidav
00d06feb1c54bb9add303a4847d017b1f1a2ffbe
519
cpp
C++
source/VK_Buffer.cpp
ccsdu2004/vulkan-cpp-demo
72eb10974e40173aad67f307714f7ce919c8217a
[ "Zlib" ]
6
2021-12-04T17:21:29.000Z
2022-03-03T03:00:26.000Z
source/VK_Buffer.cpp
ccsdu2004/vulkan-cpp-demo
72eb10974e40173aad67f307714f7ce919c8217a
[ "Zlib" ]
null
null
null
source/VK_Buffer.cpp
ccsdu2004/vulkan-cpp-demo
72eb10974e40173aad67f307714f7ce919c8217a
[ "Zlib" ]
1
2021-12-05T04:18:51.000Z
2021-12-05T04:18:51.000Z
#include "VK_Buffer.h" #include "VK_Context.h" #include <iostream> VK_Buffer::VK_Buffer(VK_Context* vkContext): context(vkContext) { } VK_Buffer::~VK_Buffer() { } VK_Context *VK_Buffer::getContext() const { return context; } void VK_Buffer::release() { if(buffer) vkDestroyBuffer(context->getDevice(), buffer, context->getAllocation()); if(bufferMemory) vkFreeMemory(context->getDevice(), bufferMemory, context->getAllocation()); context->removeBuffer(this); delete this; }
17.896552
83
0.693642
ccsdu2004
00d1b99b73c8913c633b890ccdad471280e1802e
401
hxx
C++
ltnvm/memory/Float.hxx
JeneLitsch/litan
4eb37378c41226d1299aa695da85056fd548730e
[ "MIT" ]
14
2021-07-27T17:26:20.000Z
2022-02-23T23:29:55.000Z
ltnvm/memory/Float.hxx
JeneLitsch/litan
4eb37378c41226d1299aa695da85056fd548730e
[ "MIT" ]
35
2021-11-24T23:36:49.000Z
2022-03-23T15:45:41.000Z
ltnvm/memory/Float.hxx
JeneLitsch/litan
4eb37378c41226d1299aa695da85056fd548730e
[ "MIT" ]
3
2022-01-24T07:20:42.000Z
2022-01-25T00:48:56.000Z
#pragma once #include <limits> #include <cstdint> #include "ltn/Bitcast.hxx" // 64-bit ieee only static_assert(std::numeric_limits<double>::is_iec559); static_assert(sizeof(double) == sizeof(std::uint64_t)); namespace ltn::vm { inline std::uint64_t toUint(double value) { return bitcast<std::uint64_t>(value); } inline double toFloat(std::uint64_t value) { return bitcast<double>(value); } }
23.588235
55
0.730673
JeneLitsch
00d6a3728f9cd4d7dbeac818c5b14b9b1d9ba9cb
2,055
hpp
C++
libs/cegui/include/sge/cegui/load_context.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/cegui/include/sge/cegui/load_context.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/cegui/include/sge/cegui/load_context.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // 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) #ifndef SGE_CEGUI_LOAD_CONTEXT_HPP_INCLUDED #define SGE_CEGUI_LOAD_CONTEXT_HPP_INCLUDED #include <sge/cegui/default_font.hpp> #include <sge/cegui/load_context_fwd.hpp> #include <sge/cegui/scheme_file.hpp> #include <sge/cegui/detail/symbol.hpp> #include <fcppt/optional/object_impl.hpp> #include <fcppt/config/external_begin.hpp> #include <filesystem> #include <fcppt/config/external_end.hpp> namespace sge::cegui { class load_context { public: SGE_CEGUI_DETAIL_SYMBOL explicit load_context(sge::cegui::scheme_file &&); [[nodiscard]] std::filesystem::path const &scheme_file() const; SGE_CEGUI_DETAIL_SYMBOL sge::cegui::load_context &font_directory(std::filesystem::path &&); SGE_CEGUI_DETAIL_SYMBOL sge::cegui::load_context &looknfeel_directory(std::filesystem::path &&); SGE_CEGUI_DETAIL_SYMBOL sge::cegui::load_context &imageset_directory(std::filesystem::path &&); SGE_CEGUI_DETAIL_SYMBOL sge::cegui::load_context &default_font(sge::cegui::default_font &&); using optional_path = fcppt::optional::object<std::filesystem::path>; using optional_default_font = fcppt::optional::object<sge::cegui::default_font>; [[nodiscard]] sge::cegui::load_context::optional_path const &font_directory() const; [[nodiscard]] sge::cegui::load_context::optional_path const &looknfeel_directory() const; [[nodiscard]] sge::cegui::load_context::optional_path const &imageset_directory() const; [[nodiscard]] sge::cegui::load_context::optional_default_font const &default_font() const; private: sge::cegui::scheme_file scheme_file_; sge::cegui::load_context::optional_path font_directory_; sge::cegui::load_context::optional_path looknfeel_directory_; sge::cegui::load_context::optional_path imageset_directory_; sge::cegui::load_context::optional_default_font default_font_; }; } #endif
30.220588
92
0.76691
cpreh
00def896c95587de24395c64fc7d8b2db84b0870
3,128
cpp
C++
CardReaderLibrary/TransformHelper.cpp
klanderfri/CardReaderLibrary
71fc4b7fc6052a9ec3fb477fccd9b3fcfa0b9c60
[ "MIT" ]
4
2019-03-18T14:06:59.000Z
2021-07-17T18:36:12.000Z
CardReaderLibrary/TransformHelper.cpp
klanderfri/ReadMagicCard
71fc4b7fc6052a9ec3fb477fccd9b3fcfa0b9c60
[ "MIT" ]
17
2018-04-12T18:03:16.000Z
2018-05-09T18:33:07.000Z
CardReaderLibrary/TransformHelper.cpp
klanderfri/ReadMagicCard
71fc4b7fc6052a9ec3fb477fccd9b3fcfa0b9c60
[ "MIT" ]
1
2019-03-25T18:31:17.000Z
2019-03-25T18:31:17.000Z
#include "stdafx.h" #include "TransformHelper.h" #include "AlgorithmHelper.h" #include <opencv2\opencv.hpp> using namespace cv; using namespace std; TransformHelper::TransformHelper() { } TransformHelper::~TransformHelper() { } Mat TransformHelper::TransformToRectangle(const Mat rawImage, vector<Point2d> fourCornerPoints, double widthMarginFactor, double heightMarginFactor) { //Implemented according to: //https://www.pyimagesearch.com/2014/08/25/4-point-opencv-getperspective-transform-example/ if (fourCornerPoints.size() != 4) { throw new ParameterException("The method was not provided exactly four corner points!", "fourCornerPoints"); } vector<Point2d> originalCorners = orderCornerPointsForTransform(fourCornerPoints); Point2d tl = originalCorners[0]; Point2d tr = originalCorners[1]; Point2d br = originalCorners[2]; Point2d bl = originalCorners[3]; double width = max(AlgorithmHelper::FindDistance(tl, tr), AlgorithmHelper::FindDistance(bl, br)); double height = max(AlgorithmHelper::FindDistance(tl, bl), AlgorithmHelper::FindDistance(tr, br)); double widthMargin = width * widthMarginFactor; double heightMargin = height * heightMarginFactor; Size2d newImageSize(width + 2 * widthMargin, height + 2 * heightMargin); Point2f oldCorners[] = { tl, tr, br, bl }; Point2f newCorners[] = { Point2d(0 + widthMargin, 0 + heightMargin), Point2d(width - 1 + widthMargin, 0 + heightMargin), Point2d(width - 1 + widthMargin, height - 1 + heightMargin), Point2d(0 + widthMargin, height - 1 + heightMargin) }; Mat transformedImage; Mat transformationMatrix = getPerspectiveTransform(oldCorners, newCorners); warpPerspective(rawImage, transformedImage, transformationMatrix, newImageSize); return transformedImage; } vector<Point2d> TransformHelper::orderCornerPointsForTransform(vector<Point2d> fourUnorderedCornerPoints) { //Implemented according to: //https://www.pyimagesearch.com/2014/08/25/4-point-opencv-getperspective-transform-example/ Point2d topLeft = fourUnorderedCornerPoints[0]; Point2d bottomRight = fourUnorderedCornerPoints[1]; Point2d topRight = fourUnorderedCornerPoints[2]; Point2d bottomLeft = fourUnorderedCornerPoints[3]; for (Point2d p : fourUnorderedCornerPoints) { double pSum = pointCoordinateSum(p); double pDifference = pointCoordinateDifference(p); double tlSum = pointCoordinateSum(topLeft); double brSum = pointCoordinateSum(bottomRight); double trDifference = pointCoordinateDifference(topRight); double blDifference = pointCoordinateDifference(bottomLeft); if (pSum < tlSum) { topLeft = p; } if (pSum > brSum) { bottomRight = p; } if (pDifference < blDifference) { bottomLeft = p; } if (pDifference > trDifference) { topRight = p; } } vector<Point2d> corners; corners.push_back(topLeft); corners.push_back(topRight); corners.push_back(bottomRight); corners.push_back(bottomLeft); return corners; } double TransformHelper::pointCoordinateSum(Point2d point) { return point.x + point.y; } double TransformHelper::pointCoordinateDifference(Point2d point) { return point.x - point.y; }
28.962963
150
0.761189
klanderfri
00e51de226e6c674e33aca642a7a7012fe56e0c3
3,025
cpp
C++
tests/StringWriteBatchTest.cpp
LPetrlik/karindb
8fe2b953c13f1d1aed9bb550799f7cfaf13b50ea
[ "MIT" ]
null
null
null
tests/StringWriteBatchTest.cpp
LPetrlik/karindb
8fe2b953c13f1d1aed9bb550799f7cfaf13b50ea
[ "MIT" ]
null
null
null
tests/StringWriteBatchTest.cpp
LPetrlik/karindb
8fe2b953c13f1d1aed9bb550799f7cfaf13b50ea
[ "MIT" ]
null
null
null
/* Copyright (c) 2015 Kerio Technologies s.r.o. * * 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 OF THIRD PARTY RIGHTS. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE * LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR * ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * Except as contained in this notice, the name of a copyright holder shall not * be used in advertising or otherwise to promote the sale, use or other * dealings in this Software without prior written authorization of the * copyright holder. */ #include "stdafx.h" #include <kerio/hashdb/HashDB.h> #include <kerio/hashdbHelpers/StringWriteBatch.h> #include "StringWriteBatchTest.h" using namespace kerio::hashdb; void StringWriteBatchTest::testMultipleWrites() { const std::string expectedKey1("TTHyRxwZw7nbrTL1g3\005L5rl9mSE24G2FUA0RSPjKrA\1"); const partNum_t expectedPartNum1 = 13; const std::string expectedValue1("l42OJZmo52O7jkRdaSPwGHledilbvs7Vkfi7nEE/oM0NIrZHBnxgiHWKEw=="); const std::string expectedKey2("ad;skd;d;lqkdlqd;cdl;ckd;lc;l;kd;lcfkd"); const partNum_t expectedPartNum2 = 99; const std::string expectedValue2("0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"); boost::scoped_ptr<StringWriteBatch> writeBatch(new StringWriteBatch); TS_ASSERT_EQUALS(0U, writeBatch->approxDataSize()); writeBatch->add(expectedKey1, expectedPartNum1, expectedValue1); writeBatch->add(expectedKey2, expectedPartNum2, expectedValue2); TS_ASSERT(writeBatch->approxDataSize() != 0U); TS_ASSERT_EQUALS(writeBatch->count(), 2U); TS_ASSERT_EQUALS(writeBatch->keyAt(0).getRef(), expectedKey1); TS_ASSERT_EQUALS(writeBatch->partNumAt(0), expectedPartNum1); TS_ASSERT_EQUALS(writeBatch->valueAt(0).getRef(), expectedValue1); TS_ASSERT_EQUALS(writeBatch->keyAt(1).getRef(), expectedKey2); TS_ASSERT_EQUALS(writeBatch->partNumAt(1), expectedPartNum2); TS_ASSERT_EQUALS(writeBatch->valueAt(1).getRef(), expectedValue2); writeBatch->clear(); TS_ASSERT_EQUALS(writeBatch->count(), 0U); }
45.833333
138
0.787438
LPetrlik
00f5aa571f72775b671c3176cae847391548883d
3,156
cpp
C++
Train/Sheet/Sheet-B/extra/extra 01 - 15/02.[Trees on the level].cpp
mohamedGamalAbuGalala/Practice
2a5fa3bdaf995d0c304f04231e1a69e6960f72c8
[ "MIT" ]
1
2019-12-19T06:51:20.000Z
2019-12-19T06:51:20.000Z
Train/Sheet/Sheet-B/extra/extra 01 - 15/02.[Trees on the level].cpp
mohamedGamalAbuGalala/Practice
2a5fa3bdaf995d0c304f04231e1a69e6960f72c8
[ "MIT" ]
null
null
null
Train/Sheet/Sheet-B/extra/extra 01 - 15/02.[Trees on the level].cpp
mohamedGamalAbuGalala/Practice
2a5fa3bdaf995d0c304f04231e1a69e6960f72c8
[ "MIT" ]
null
null
null
#include <iostream> #include <stdio.h> #include <math.h> #include <vector> #include <algorithm> #include <string.h> #include <array> #include <iterator> #include <set> #include <cmath> #include<iomanip> // Stew(10) :: 12 ........ 8 spaces and 2 digits in 10 padding right #define pb push_back #define up upper_bound #define lp lower_bound #define pr pair<int,int> #define ll long long int using namespace std; vector<pair<int, string>> ar[257]; vector<string> dat; int mx; void split(const string &s, const char* delim, vector<string> & v) { // to avoid modifying original string // first duplicate the original string and return a char pointer then free the memory char * dup = strdup(s.c_str()); char * token = strtok(dup, delim); while (token != NULL) { v.push_back(string(token)); // the call is treated as a subsequent calls to strtok: // the function continues from where it left in previous invocation token = strtok(NULL, delim); } free(dup); } int calc(string s) { int res = 0; for (int i = 0, si = s.size(); i < si; ++i) { if (s[i] == 'R') res = (res * 2) + 1; else res = (res * 2); } return res; } bool dubl(string v, int i) { vector<string>::iterator it = find(dat.begin(), dat.end(), v); int ind = it - dat.begin(); if (it != dat.end() && ind != i) return 1; return 0; } bool found_parent(string v) { vector<string>::iterator it = find(dat.begin(), dat.end(), v); if (it != dat.end()) return 1; return 0; } bool ok() { bool ft = 0, pnf = 0; for (int i = 0, siz = dat.size(); i < siz; ++i) { string cur = dat[i]; if (dubl(cur, i)) ft = 1; string p = cur.substr(0, cur.size() - 1); if (p.size() == 0) p = "r"; if (cur != "r") if (!found_parent(p)) pnf = 1; } return (!ft && !pnf); } bool cmp(pair<int, string> b, pair<int, string> a) { if (a.first > b.first) return 1; return 0; } void print() { if (ok()) { if (ar[0].size() != 0) cout << ar[0][0].second; for (int i = 1; i <= mx; ++i) { sort(ar[i].begin(), ar[i].end(), cmp); for (int j = 0, si = ar[i].size(); j < si; ++j) cout << ' ' << ar[i][j].second; } cout << '\n'; } else cout << "not complete\n"; vector<pair<int, string>> tmp; memset(ar, 0, sizeof ar); dat.clear(); mx = 0; } int main() { string inp; while (cin >> inp) { if (inp == "()") print(); vector<string> sp; split(inp, "(,)", sp); pair<int, string> tmp; if (sp.size() == 1) { dat.pb("r"); tmp.first = 0, tmp.second = sp[0]; ar[0].pb(tmp); mx = max(0, mx); } else if (sp.size() == 2) { dat.pb(sp[1]); tmp.first = calc(sp[1]), tmp.second = sp[0]; ar[sp[1].size()].pb(tmp); int length = sp[1].size(); mx = max(length, mx); } } return 0; } /* Test-Cases * * (11,LL) (7,LLL) (8,R) (5,) (4,L) (13,RL) (2,LLR) (1,RRR) (4,RR) (20,LR) (19,LRL) (18,LRR) (17,RLL) (16,RLR) (15,RRL) () (3,L) (4,R) () (11,LL) (7,LLL) (8,R) (5,) (4,L) (13,RL) (2,LLR) (2,LLR) (1,RRR) (4,RR) (20,LR) (19,LRL) (18,LRR) (17,RLL) (16,RLR) (15,RRL) () (3,L) (4,R) (4,) () (5,) () () 5 4 8 11 20 13 4 7 2 19 18 17 16 15 1 not complete not complete 4 3 4 5 not complete * */
21.04
106
0.556717
mohamedGamalAbuGalala
00f7683f5fc55e88997d8a93b199d6512cf3204d
2,384
cpp
C++
src/AppInstallerRepositoryCore/ManifestJSONParser.cpp
ryfu-msft/winget-cli
9f8ceea4fb8959552075d7c6f8679abc6a310306
[ "MIT" ]
null
null
null
src/AppInstallerRepositoryCore/ManifestJSONParser.cpp
ryfu-msft/winget-cli
9f8ceea4fb8959552075d7c6f8679abc6a310306
[ "MIT" ]
null
null
null
src/AppInstallerRepositoryCore/ManifestJSONParser.cpp
ryfu-msft/winget-cli
9f8ceea4fb8959552075d7c6f8679abc6a310306
[ "MIT" ]
1
2022-01-18T19:23:34.000Z
2022-01-18T19:23:34.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "pch.h" #include "Public/winget/ManifestJSONParser.h" #include "Rest/Schema/1_0/Json/ManifestDeserializer.h" #include "Rest/Schema/1_1/Json/ManifestDeserializer.h" namespace AppInstaller::Repository::JSON { struct ManifestJSONParser::impl { // The deserializer. We only have one lineage (1.0+) right now. std::unique_ptr<Rest::Schema::V1_0::Json::ManifestDeserializer> m_deserializer; }; ManifestJSONParser::ManifestJSONParser(const Utility::Version& responseSchemaVersion) { const auto& parts = responseSchemaVersion.GetParts(); THROW_HR_IF(E_INVALIDARG, parts.empty()); m_pImpl = std::make_unique<impl>(); if (parts[0].Integer == 1) { if (parts.size() == 1 || parts[1].Integer == 0) { m_pImpl->m_deserializer = std::make_unique<Rest::Schema::V1_0::Json::ManifestDeserializer>(); } else { m_pImpl->m_deserializer = std::make_unique<Rest::Schema::V1_1::Json::ManifestDeserializer>(); } } else { THROW_HR(HRESULT_FROM_WIN32(ERROR_UNSUPPORTED_TYPE)); } } ManifestJSONParser::ManifestJSONParser(ManifestJSONParser&&) noexcept = default; ManifestJSONParser& ManifestJSONParser::operator=(ManifestJSONParser&&) noexcept = default; ManifestJSONParser::~ManifestJSONParser() = default; std::vector<Manifest::Manifest> ManifestJSONParser::Deserialize(const web::json::value& response) const { return m_pImpl->m_deserializer->Deserialize(response); } std::vector<Manifest::Manifest> ManifestJSONParser::DeserializeData(const web::json::value& data) const { return m_pImpl->m_deserializer->DeserializeData(data); } std::vector<Manifest::AppsAndFeaturesEntry> ManifestJSONParser::DeserializeAppsAndFeaturesEntries(const web::json::array& data) const { return m_pImpl->m_deserializer->DeserializeAppsAndFeaturesEntries(data); } std::optional<Manifest::ManifestLocalization> ManifestJSONParser::DeserializeLocale(const web::json::value& locale) const { return m_pImpl->m_deserializer->DeserializeLocale(locale); } }
36.121212
138
0.657718
ryfu-msft
00fc039e11d72fbd50f8d2e9e542853f518a8967
1,626
hh
C++
src/windows/libraries/ws2_32/types/WSABUF_IMPL.hh
IntroVirt/IntroVirt
917f735f3430d0855d8b59c814bea7669251901c
[ "Apache-2.0" ]
23
2021-02-17T16:58:52.000Z
2022-02-12T17:01:06.000Z
src/windows/libraries/ws2_32/types/WSABUF_IMPL.hh
IntroVirt/IntroVirt
917f735f3430d0855d8b59c814bea7669251901c
[ "Apache-2.0" ]
1
2021-04-01T22:41:32.000Z
2021-09-24T14:14:17.000Z
src/windows/libraries/ws2_32/types/WSABUF_IMPL.hh
IntroVirt/IntroVirt
917f735f3430d0855d8b59c814bea7669251901c
[ "Apache-2.0" ]
4
2021-02-17T16:53:18.000Z
2021-04-13T16:51:10.000Z
/* * Copyright 2021 Assured Information Security, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <introvirt/windows/libraries/ws2_32/types/WSABUF.hh> namespace introvirt { namespace windows { namespace ws2_32 { namespace structs { template <typename PtrType> struct _WSABUF { uint32_t len; PtrType buf; }; } // namespace structs template <typename PtrType> class WSABUF_IMPL final : public WSABUF { public: uint32_t len() const override { return ptr_->len; } void len(uint32_t len) override { ptr_->len = len; } guest_ptr<const uint8_t[]> buf() const override { return const_cast<WSABUF_IMPL<PtrType>*>(this)->buf(); } guest_ptr<uint8_t[]> buf() override { return guest_ptr<uint8_t[]>(ptr_.domain(), ptr_->buf, ptr_.page_directory(), len()); } void buf(const guest_ptr<uint8_t[]>& buf) override { ptr_->buf = buf.address(); } WSABUF_IMPL(const guest_ptr<void>& ptr) : ptr_(ptr) {} private: guest_ptr<structs::_WSABUF<PtrType>> ptr_; }; } // namespace ws2_32 } // namespace windows } // namespace introvirt
29.035714
92
0.702337
IntroVirt
2e0307c3a32675cb8a349d8b80b2eb8dc25f9874
4,758
hpp
C++
output/include/core/fs/io_device.hpp
picofox/pilo
59e12c947307d664c4ca9dcc232b481d06be104a
[ "MIT" ]
1
2019-07-31T06:44:46.000Z
2019-07-31T06:44:46.000Z
src/pilo/core/fs/io_device.hpp
picofox/pilo
59e12c947307d664c4ca9dcc232b481d06be104a
[ "MIT" ]
null
null
null
src/pilo/core/fs/io_device.hpp
picofox/pilo
59e12c947307d664c4ca9dcc232b481d06be104a
[ "MIT" ]
null
null
null
#pragma once #include "core/coredefs.hpp" #define MB_IO_DEV_OPEN_FLAG_APPEND (1<<0) #define MB_IO_DEV_OPEN_SYNC (1<<1) #define MB_IO_DEV_OPEN_NO_OS_CACHE (1<<2) #define MB_IO_DEV_OPEN_REOPEN (1<<3) #define MB_IO_DEV_INIT_FLAG_AUTO_CREATE (1<<0) #define MB_IO_DEV_INIT_FLAG_FORCE_DELETE_DIR (1<<1) #define MB_IO_DEV_INIT_FLAG_FORCE_DELETE_FILE (1<<2) #define MB_IO_DEV_INIT_FLAG_AUTO_DELETE (1<<3) #define MB_IO_DEV_INIT_FLAG_AUTO_DELETE_ON_FINALIZE (1<<4) namespace pilo { namespace core { namespace fs { typedef enum { # ifdef WINDOWS eDAM_CreateAlways = CREATE_ALWAYS,/**< Creates a new file, always. */ eDAM_CreateNew = CREATE_NEW,/**< Creates a new file, only if it does not already exist. */ eDAM_OpenAlways = OPEN_ALWAYS, /**< Opens a file, always.*/ eDAM_OpenExisting = OPEN_EXISTING, /**< Opens a file or device, only if it exists. */ eDAM_TruncateExisting = TRUNCATE_EXISTING, /**< Opens a file and truncates it so that its size is zero bytes, only if it exists.*/ # else eDAM_CreateAlways = (O_CREAT | O_TRUNC),/**< Creates a new file, always. */ eDAM_CreateNew = (O_EXCL | O_CREAT),/**< Creates a new file, only if it does not already exist. */ eDAM_OpenAlways = O_CREAT, /**< Opens a file, always.*/ eDAM_OpenExisting = 0, /**< Opens a file or device, only if it exists. */ eDAM_TruncateExisting = O_TRUNC, /**< Opens a file and truncates it so that its size is zero bytes, only if it exists.*/ # endif } DeviceAccessModeEnumeration; typedef enum { # ifdef WINDOWS eDRWM_None = 0, eDRWM_Read = GENERIC_READ, eDRWM_Write = GENERIC_WRITE, eDRWM_ReadWrite = (GENERIC_READ | GENERIC_WRITE), # else eDRWM_None = 0, eDRWM_Read = O_RDONLY, eDRWM_Write = O_WRONLY, eDRWM_ReadWrite = O_RDWR, # endif } DeviceRWModeEnumeration; typedef enum { # ifdef WINDOWS eDSW_Begin = FILE_BEGIN, eDSW_Current = FILE_CURRENT, eDSW_END = FILE_CURRENT, # else eDSW_Begin = SEEK_SET, eDSW_Current = SEEK_CUR, eDSW_END = SEEK_END, # endif } DeviceSeekWhenceEnumeration; class io_device { public: enum EnumIODeviceState { eIODS_Uninitialized = 0, eIODS_Initialized = 1, eIODS_Opend = 2, }; io_device() { _m_context = nullptr; _m_state = eIODS_Uninitialized; _m_init_flags = 0; _m_access_mode = eDAM_OpenExisting; _m_rw_mode = eDRWM_None; _m_open_flag = 0; } virtual ~io_device() { } virtual ::pilo::error_number_t initialize(const char* path, ::pilo::u32_t flag, void* context) = 0; virtual ::pilo::error_number_t finalize() = 0; virtual ::pilo::error_number_t open(DeviceAccessModeEnumeration dev_acc_mode, DeviceRWModeEnumeration rw_mode, ::pilo::u32_t flag) = 0; virtual ::pilo::error_number_t close() = 0; virtual ::pilo::error_number_t read(void* buffer, size_t len, size_t* read_len) = 0; virtual ::pilo::error_number_t write(const void* buffer, size_t len, size_t* written_len) = 0; virtual ::pilo::error_number_t flush(::pilo::i32_t mode) = 0; virtual ::pilo::error_number_t seek(::pilo::i64_t offset, DeviceSeekWhenceEnumeration eWhence, ::pilo::i64_t* r_offset) = 0; inline void set_context(void* context) { _m_context = context; } protected: void* _m_context; volatile EnumIODeviceState _m_state; ::pilo::u32_t _m_init_flags; DeviceAccessModeEnumeration _m_access_mode; DeviceRWModeEnumeration _m_rw_mode; ::pilo::u32_t _m_open_flag; }; } } }
39.322314
151
0.519756
picofox
2e03f529a57225cb29ee158fc39249c2fea07d33
5,585
cc
C++
google/cloud/dataproc/cluster_controller_connection.cc
sydney-munro/google-cloud-cpp
374b52e5cec78962358bdd5913d4118a47af1952
[ "Apache-2.0" ]
null
null
null
google/cloud/dataproc/cluster_controller_connection.cc
sydney-munro/google-cloud-cpp
374b52e5cec78962358bdd5913d4118a47af1952
[ "Apache-2.0" ]
null
null
null
google/cloud/dataproc/cluster_controller_connection.cc
sydney-munro/google-cloud-cpp
374b52e5cec78962358bdd5913d4118a47af1952
[ "Apache-2.0" ]
null
null
null
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated by the Codegen C++ plugin. // If you make any local changes, they will be lost. // source: google/cloud/dataproc/v1/clusters.proto #include "google/cloud/dataproc/cluster_controller_connection.h" #include "google/cloud/dataproc/cluster_controller_options.h" #include "google/cloud/dataproc/internal/cluster_controller_connection_impl.h" #include "google/cloud/dataproc/internal/cluster_controller_option_defaults.h" #include "google/cloud/dataproc/internal/cluster_controller_stub_factory.h" #include "google/cloud/background_threads.h" #include "google/cloud/common_options.h" #include "google/cloud/grpc_options.h" #include "google/cloud/internal/pagination_range.h" #include <memory> namespace google { namespace cloud { namespace dataproc { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN ClusterControllerConnection::~ClusterControllerConnection() = default; future<StatusOr<google::cloud::dataproc::v1::Cluster>> ClusterControllerConnection::CreateCluster( google::cloud::dataproc::v1::CreateClusterRequest const&) { return google::cloud::make_ready_future< StatusOr<google::cloud::dataproc::v1::Cluster>>( Status(StatusCode::kUnimplemented, "not implemented")); } future<StatusOr<google::cloud::dataproc::v1::Cluster>> ClusterControllerConnection::UpdateCluster( google::cloud::dataproc::v1::UpdateClusterRequest const&) { return google::cloud::make_ready_future< StatusOr<google::cloud::dataproc::v1::Cluster>>( Status(StatusCode::kUnimplemented, "not implemented")); } future<StatusOr<google::cloud::dataproc::v1::Cluster>> ClusterControllerConnection::StopCluster( google::cloud::dataproc::v1::StopClusterRequest const&) { return google::cloud::make_ready_future< StatusOr<google::cloud::dataproc::v1::Cluster>>( Status(StatusCode::kUnimplemented, "not implemented")); } future<StatusOr<google::cloud::dataproc::v1::Cluster>> ClusterControllerConnection::StartCluster( google::cloud::dataproc::v1::StartClusterRequest const&) { return google::cloud::make_ready_future< StatusOr<google::cloud::dataproc::v1::Cluster>>( Status(StatusCode::kUnimplemented, "not implemented")); } future<StatusOr<google::cloud::dataproc::v1::ClusterOperationMetadata>> ClusterControllerConnection::DeleteCluster( google::cloud::dataproc::v1::DeleteClusterRequest const&) { return google::cloud::make_ready_future< StatusOr<google::cloud::dataproc::v1::ClusterOperationMetadata>>( Status(StatusCode::kUnimplemented, "not implemented")); } StatusOr<google::cloud::dataproc::v1::Cluster> ClusterControllerConnection::GetCluster( google::cloud::dataproc::v1::GetClusterRequest const&) { return Status(StatusCode::kUnimplemented, "not implemented"); } StreamRange<google::cloud::dataproc::v1::Cluster> ClusterControllerConnection::ListClusters( google::cloud::dataproc::v1:: ListClustersRequest) { // NOLINT(performance-unnecessary-value-param) return google::cloud::internal::MakeUnimplementedPaginationRange< StreamRange<google::cloud::dataproc::v1::Cluster>>(); } future<StatusOr<google::cloud::dataproc::v1::DiagnoseClusterResults>> ClusterControllerConnection::DiagnoseCluster( google::cloud::dataproc::v1::DiagnoseClusterRequest const&) { return google::cloud::make_ready_future< StatusOr<google::cloud::dataproc::v1::DiagnoseClusterResults>>( Status(StatusCode::kUnimplemented, "not implemented")); } std::shared_ptr<ClusterControllerConnection> MakeClusterControllerConnection( Options options) { internal::CheckExpectedOptions<CommonOptionList, GrpcOptionList, ClusterControllerPolicyOptionList>(options, __func__); options = dataproc_internal::ClusterControllerDefaultOptions(std::move(options)); auto background = internal::MakeBackgroundThreadsFactory(options)(); auto stub = dataproc_internal::CreateDefaultClusterControllerStub( background->cq(), options); return std::make_shared<dataproc_internal::ClusterControllerConnectionImpl>( std::move(background), std::move(stub), std::move(options)); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace dataproc } // namespace cloud } // namespace google namespace google { namespace cloud { namespace dataproc_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN std::shared_ptr<dataproc::ClusterControllerConnection> MakeClusterControllerConnection(std::shared_ptr<ClusterControllerStub> stub, Options options) { options = ClusterControllerDefaultOptions(std::move(options)); auto background = internal::MakeBackgroundThreadsFactory(options)(); return std::make_shared<dataproc_internal::ClusterControllerConnectionImpl>( std::move(background), std::move(stub), std::move(options)); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace dataproc_internal } // namespace cloud } // namespace google
41.066176
82
0.755058
sydney-munro
2e05ffbdcfc0058fbc589b079f97fab11807e86c
22,737
hpp
C++
selene/base/Kernel.hpp
kmhofmann/selene
11718e1a7de6ff6251c46e4ef429a7cfb1bdb9eb
[ "MIT" ]
284
2017-11-20T08:23:54.000Z
2022-03-30T12:52:00.000Z
selene/base/Kernel.hpp
kmhofmann/selene
11718e1a7de6ff6251c46e4ef429a7cfb1bdb9eb
[ "MIT" ]
9
2018-02-14T08:21:41.000Z
2021-07-27T19:52:12.000Z
selene/base/Kernel.hpp
kmhofmann/selene
11718e1a7de6ff6251c46e4ef429a7cfb1bdb9eb
[ "MIT" ]
17
2018-03-10T00:01:36.000Z
2021-06-29T10:44:27.000Z
// This file is part of the `Selene` library. // Copyright 2017-2019 Michael Hofmann (https://github.com/kmhofmann). // Distributed under MIT license. See accompanying LICENSE file in the top-level directory. #ifndef SELENE_BASE_KERNEL_HPP #define SELENE_BASE_KERNEL_HPP /// @file #include <selene/base/Assert.hpp> #include <selene/base/Round.hpp> #include <selene/base/Types.hpp> #include <selene/base/Utils.hpp> #include <selene/base/_impl/ExplicitType.hpp> #include <algorithm> #include <array> #include <cstdint> #include <limits> #include <vector> #include <cmath> namespace sln { /// \addtogroup group-base /// @{ using KernelSize = std::ptrdiff_t; constexpr static auto kernel_size_dynamic = KernelSize{-1}; template <typename ValueType_, KernelSize k_ = kernel_size_dynamic> class Kernel; /** \brief 1-dimensional kernel class. * * This class represents a 1-dimensional kernel, for use in image convolutions. * * @tparam ValueType_ The value type of the kernel elements. * @tparam k_ The kernel size. If it is set to `kernel_size_dynamic`, the data used to store the kernel elements * will be allocated dynamically (i.e. using a `std::vector`); otherwise, it will be allocated on the stack * (i.e. using a `std::array`). */ template <typename ValueType_, KernelSize k_> class Kernel { public: using value_type = ValueType_; using iterator = typename std::array<ValueType_, k_>::iterator; using const_iterator = typename std::array<ValueType_, k_>::const_iterator; constexpr Kernel() = default; ///< Default constructor. constexpr Kernel(const std::array<ValueType_, k_>& data); ~Kernel() = default; ///< Defaulted destructor. constexpr Kernel(const Kernel&) = default; ///< Defaulted copy constructor. constexpr Kernel& operator=(const Kernel&) = default; ///< Defaulted copy assignment operator. constexpr Kernel(Kernel&&) noexcept = default; ///< Defaulted move constructor. constexpr Kernel& operator=(Kernel&&) noexcept = default; ///< Defaulted move assignment operator. iterator begin() noexcept; const_iterator begin() const noexcept; const_iterator cbegin() const noexcept; iterator end() noexcept; const_iterator end() const noexcept; const_iterator cend() const noexcept; [[nodiscard]] constexpr std::size_t size() const noexcept; constexpr value_type operator[](std::size_t idx) const noexcept; constexpr void normalize(value_type sum) noexcept; constexpr void normalize() noexcept; private: std::array<ValueType_, k_> data_; static_assert(k_ >= 0, "Kernel size must be non-negative"); static_assert(std::is_trivial_v<ValueType_>, "Value type of kernel is not trivial"); }; /** \brief 1-dimensional kernel class. Partial specialization for k_ == kernel_size_dynamic. * * @tparam ValueType_ The value type of the kernel elements. */ template <typename ValueType_> class Kernel<ValueType_, kernel_size_dynamic> { public: using value_type = ValueType_; using iterator = typename std::vector<ValueType_>::iterator; using const_iterator = typename std::vector<ValueType_>::const_iterator; Kernel() = default; ///< Default constructor. Kernel(std::initializer_list<ValueType_> init); explicit Kernel(std::vector<value_type>&& vec); ~Kernel() = default; ///< Defaulted destructor. Kernel(const Kernel&) = default; ///< Defaulted copy constructor. Kernel& operator=(const Kernel&) = default; ///< Defaulted copy assignment operator. Kernel(Kernel&&) noexcept = default; ///< Defaulted move constructor. Kernel& operator=(Kernel&&) noexcept = default; ///< Defaulted move assignment operator. iterator begin() noexcept; const_iterator begin() const noexcept; const_iterator cbegin() const noexcept; iterator end() noexcept; const_iterator end() const noexcept; const_iterator cend() const noexcept; std::size_t size() const noexcept; value_type operator[](std::size_t idx) const noexcept; void normalize(value_type sum) noexcept; void normalize() noexcept; private: std::vector<ValueType_> data_; static_assert(std::is_trivial_v<ValueType_>, "Value type of kernel is not trivial"); }; template <typename ValueType, KernelSize k> constexpr Kernel<ValueType, k> normalize(const Kernel<ValueType, k>& kernel, ValueType sum); template <typename ValueType, KernelSize k> constexpr Kernel<ValueType, k> normalize(const Kernel<ValueType, k>& kernel); template <KernelSize kernel_size, typename ValueType = default_float_t> auto gaussian_kernel(default_float_t sigma, bool renormalize = true); template <typename ValueType = default_float_t> auto gaussian_kernel(default_float_t sigma, KernelSize size, bool renormalize = true); template <typename ValueType = default_float_t> auto gaussian_kernel(default_float_t sigma, default_float_t range_nr_std_deviations, bool renormalize = true); template <KernelSize kernel_size, typename ValueType = default_float_t> constexpr auto uniform_kernel(); template <typename ValueType = default_float_t> auto uniform_kernel(KernelSize size); template <typename OutValueType, std::ptrdiff_t scale_factor, typename ValueType, KernelSize k, typename = std::enable_if_t<k != kernel_size_dynamic>> constexpr Kernel<OutValueType, k> integer_kernel(const Kernel<ValueType, k>& kernel); template <typename OutValueType, std::ptrdiff_t scale_factor, typename ValueType> Kernel<OutValueType, kernel_size_dynamic> integer_kernel(const Kernel<ValueType, kernel_size_dynamic>& kernel); /// @} // ---------- // Implementation: /** \brief Constructor from a `std::array`. * * @tparam ValueType_ The value type of the kernel elements. * @tparam k_ The number of kernel elements. * @param data The data the kernel should contain. */ template <typename ValueType_, KernelSize k_> constexpr Kernel<ValueType_, k_>::Kernel(const std::array<ValueType_, k_>& data) : data_(data) { } /** \brief Returns an iterator to the beginning of the kernel data. * * @tparam ValueType_ The value type of the kernel elements. * @tparam k_ The number of kernel elements. * @return An iterator to the beginning of the kernel data. */ template <typename ValueType_, KernelSize k_> auto Kernel<ValueType_, k_>::begin() noexcept -> iterator { return data_.begin(); } /** \brief Returns a constant iterator to the beginning of the kernel data. * * @tparam ValueType_ The value type of the kernel elements. * @tparam k_ The number of kernel elements. * @return A constant iterator to the beginning of the kernel data. */ template <typename ValueType_, KernelSize k_> auto Kernel<ValueType_, k_>::begin() const noexcept -> const_iterator { return data_.begin(); } /** \brief Returns a constant iterator to the beginning of the kernel data. * * @tparam ValueType_ The value type of the kernel elements. * @tparam k_ The number of kernel elements. * @return A constant iterator to the beginning of the kernel data. */ template <typename ValueType_, KernelSize k_> auto Kernel<ValueType_, k_>::cbegin() const noexcept -> const_iterator { return data_.cbegin(); } /** \brief Returns an iterator to the end of the kernel data. * * @tparam ValueType_ The value type of the kernel elements. * @tparam k_ The number of kernel elements. * @return An iterator to the end of the kernel data. */ template <typename ValueType_, KernelSize k_> auto Kernel<ValueType_, k_>::end() noexcept -> iterator { return data_.end(); } /** \brief Returns a constant iterator to the end of the kernel data. * * @tparam ValueType_ The value type of the kernel elements. * @tparam k_ The number of kernel elements. * @return A constant iterator to the end of the kernel data. */ template <typename ValueType_, KernelSize k_> auto Kernel<ValueType_, k_>::end() const noexcept -> const_iterator { return data_.end(); } /** \brief Returns a constant iterator to the end of the kernel data. * * @tparam ValueType_ The value type of the kernel elements. * @tparam k_ The number of kernel elements. * @return A constant iterator to the end of the kernel data. */ template <typename ValueType_, KernelSize k_> auto Kernel<ValueType_, k_>::cend() const noexcept -> const_iterator { return data_.cend(); } /** \brief Returns the size (length) of the kernel. * * @tparam ValueType_ The value type of the kernel elements. * @tparam k_ The number of kernel elements. * @return The kernel size. */ template <typename ValueType_, KernelSize k_> constexpr std::size_t Kernel<ValueType_, k_>::size() const noexcept { return static_cast<std::size_t>(k_); } /** \brief Access the n-th kernel element. * * @tparam ValueType_ The value type of the kernel elements. * @tparam k_ The number of kernel elements. * @param idx The index of the element to access. * @return The n-th kernel element, speficied by `idx`. */ template <typename ValueType_, KernelSize k_> constexpr auto Kernel<ValueType_, k_>::operator[](std::size_t idx) const noexcept -> value_type { SELENE_ASSERT(idx < k_); return data_[idx]; } /** \brief Normalizes the kernel by dividing each element by the specified sum. * * @tparam ValueType_ The value type of the kernel elements. * @tparam k_ The number of kernel elements. * @param sum The value that each element will be divided by. */ template <typename ValueType_, KernelSize k_> constexpr void Kernel<ValueType_, k_>::normalize(value_type sum) noexcept { for (std::size_t i = 0; i < data_.size(); ++i) { data_[i] /= sum; } } /** \brief Normalizes the kernel such that the sum of (absolute) elements is 1. * * @tparam ValueType_ The value type of the kernel elements. * @tparam k_ The number of kernel elements. */ template <typename ValueType_, KernelSize k_> constexpr void Kernel<ValueType_, k_>::normalize() noexcept { auto abs_sum = value_type{0}; for (std::size_t i = 0; i < data_.size(); ++i) { abs_sum += (data_[i] >= 0) ? data_[i] : -data_[i]; } normalize(abs_sum); } // ----- /** \brief Constructor from an initializer list. * * @tparam ValueType_ The value type of the kernel elements. * @param init The data the kernel should contain, in form of an initializer list. */ template <typename ValueType_> Kernel<ValueType_, kernel_size_dynamic>::Kernel(std::initializer_list<ValueType_> init) : data_(init) { } /** \brief Constructor from a `std::vector`. * * @tparam ValueType_ The value type of the kernel elements. * @param vec The data the kernel should contain. */ template <typename ValueType_> Kernel<ValueType_, kernel_size_dynamic>::Kernel(std::vector<value_type>&& vec) : data_(std::move(vec)) { } /** \brief Returns an iterator to the beginning of the kernel data. * * @tparam ValueType_ The value type of the kernel elements. * @return An iterator to the beginning of the kernel data. */ template <typename ValueType_> auto Kernel<ValueType_, kernel_size_dynamic>::begin() noexcept -> iterator { return data_.begin(); } /** \brief Returns a constant iterator to the beginning of the kernel data. * * @tparam ValueType_ The value type of the kernel elements. * @return A constant iterator to the beginning of the kernel data. */ template <typename ValueType_> auto Kernel<ValueType_, kernel_size_dynamic>::begin() const noexcept -> const_iterator { return data_.begin(); } /** \brief Returns a constant iterator to the beginning of the kernel data. * * @tparam ValueType_ The value type of the kernel elements. * @return A constant iterator to the beginning of the kernel data. */ template <typename ValueType_> auto Kernel<ValueType_, kernel_size_dynamic>::cbegin() const noexcept -> const_iterator { return data_.cbegin(); } /** \brief Returns an iterator to the end of the kernel data. * * @tparam ValueType_ The value type of the kernel elements. * @return An iterator to the end of the kernel data. */ template <typename ValueType_> auto Kernel<ValueType_, kernel_size_dynamic>::end() noexcept -> iterator { return data_.end(); } /** \brief Returns a constant iterator to the end of the kernel data. * * @tparam ValueType_ The value type of the kernel elements. * @return A constant iterator to the end of the kernel data. */ template <typename ValueType_> auto Kernel<ValueType_, kernel_size_dynamic>::end() const noexcept -> const_iterator { return data_.end(); } /** \brief Returns a constant iterator to the end of the kernel data. * * @tparam ValueType_ The value type of the kernel elements. * @return A constant iterator to the end of the kernel data. */ template <typename ValueType_> auto Kernel<ValueType_, kernel_size_dynamic>::cend() const noexcept -> const_iterator { return data_.cend(); } /** \brief Returns the size (length) of the kernel. * * @tparam ValueType_ The value type of the kernel elements. * @return The kernel size. */ template <typename ValueType_> std::size_t Kernel<ValueType_, kernel_size_dynamic>::size() const noexcept { return data_.size(); } /** \brief Access the n-th kernel element. * * @tparam ValueType_ The value type of the kernel elements. * @param idx The index of the element to access. * @return The n-th kernel element, speficied by `idx`. */ template <typename ValueType_> auto Kernel<ValueType_, kernel_size_dynamic>::operator[](std::size_t idx) const noexcept -> value_type { SELENE_ASSERT(idx < data_.size()); return data_[idx]; } /** \brief Normalizes the kernel by dividing each element by the specified sum. * * @tparam ValueType_ The value type of the kernel elements. * @param sum The value that each element will be divided by. */ template <typename ValueType_> void Kernel<ValueType_, kernel_size_dynamic>::normalize(value_type sum) noexcept { for (std::size_t i = 0; i < data_.size(); ++i) { data_[i] /= sum; } } /** \brief Normalizes the kernel such that the sum of (absolute) elements is 1. * * @tparam ValueType_ The value type of the kernel elements. */ template <typename ValueType_> void Kernel<ValueType_, kernel_size_dynamic>::normalize() noexcept { auto abs_sum = value_type{0}; for (std::size_t i = 0; i < data_.size(); ++i) { abs_sum += std::abs(data_[i]); } normalize(abs_sum); } // ----- namespace impl { template <typename ValueType = default_float_t> inline auto gaussian_pdf(ValueType x, ValueType mu, ValueType sigma) { constexpr auto f = ValueType(0.3989422804014326779); // 1.0 / sqrt(2.0 * M_PI) const auto diff = x - mu; return (f / sigma) * std::exp(-(diff * diff / (ValueType{2} * sigma * sigma))); } template <typename Container> inline auto fill_with_gaussian_pdf(Container& c, std::ptrdiff_t center_idx, default_float_t sigma) { using size_type = std::ptrdiff_t; using value_type = typename Container::value_type; auto sum = value_type{0}; for (std::size_t i = 0; i < c.size(); ++i) { const auto x = value_type(static_cast<size_type>(i) - center_idx); const auto g = gaussian_pdf(x, value_type{0}, sigma); c[i] = g; sum += g; } return sum; } } // namespace impl /** \brief Returns a normalized kernel, where each element of the input kernel has been divided by the specified sum. * * @tparam ValueType_ The value type of the kernel elements. * @tparam k_ The number of kernel elements. * @param kernel The input kernel. * @param sum The value that each element of the input kernel will be divided by. * @return The normalized kernel. */ template <typename ValueType, KernelSize k> constexpr Kernel<ValueType, k> normalize(const Kernel<ValueType, k>& kernel, ValueType sum) { auto normalized_kernel = kernel; normalized_kernel.normalize(sum); return normalized_kernel; } /** \brief Returns a normalized kernel, such that the sum of (absolute) elements is 1. * * @tparam ValueType_ The value type of the kernel elements. * @tparam k_ The number of kernel elements. * @param kernel The input kernel. * @return The normalized kernel. */ template <typename ValueType, KernelSize k> constexpr Kernel<ValueType, k> normalize(const Kernel<ValueType, k>& kernel) { auto normalized_kernel = kernel; normalized_kernel.normalize(); return normalized_kernel; } /** \brief Returns a kernel discretely sampled from a Gaussian (normal) distribution. * * @tparam kernel_size The kernel size. * @tparam ValueType The value type of the kernel elements. * @param sigma The standard deviation of the Gaussian distribution. * @param renormalize If true, the kernel will be normalized after sampling, such the the sum of its elements is 1. * @return A kernel representing a sampled Gaussian distribution. */ template <KernelSize kernel_size, typename ValueType> inline auto gaussian_kernel(default_float_t sigma, bool renormalize) { static_assert(kernel_size % 2 == 1, "Gaussian kernel size must be odd"); constexpr auto center_idx = kernel_size / 2; static_assert(center_idx == (kernel_size - 1) / 2); auto arr = std::array<ValueType, kernel_size>(); const auto sum = impl::fill_with_gaussian_pdf(arr, center_idx, sigma); auto kernel = Kernel<ValueType, kernel_size>(arr); if (renormalize) { kernel.normalize(sum); } return kernel; } /** \brief Returns a kernel discretely sampled from a Gaussian (normal) distribution. * * @tparam ValueType The value type of the kernel elements. * @param sigma The standard deviation of the Gaussian distribution. * @param size The kernel size. * @param renormalize If true, the kernel will be normalized after sampling, such the the sum of its elements is 1. * @return A kernel representing a sampled Gaussian distribution. */ template <typename ValueType> inline auto gaussian_kernel(default_float_t sigma, KernelSize size, bool renormalize) { //SELENE_ASSERT(size % 2 == 1); const auto full_size = (size % 2 == 0) ? size + 1 : size; // ensure kernel size is odd const auto center_idx = full_size / 2; SELENE_ASSERT(center_idx == (full_size - 1) / 2); auto vec = std::vector<ValueType>(static_cast<std::size_t>(full_size)); const auto sum = impl::fill_with_gaussian_pdf(vec, center_idx, sigma); auto kernel = Kernel<ValueType, kernel_size_dynamic>(std::move(vec)); if (renormalize) { kernel.normalize(sum); } return kernel; } /** \brief Returns a kernel discretely sampled from a Gaussian (normal) distribution. * * Using this overload, the kernel size will be determined by the given range in times of standard deviation. * * @tparam ValueType The value type of the kernel elements. * @param sigma The standard deviation of the Gaussian distribution. * @param range_nr_std_deviations How many standard deviations should be represented. * @param renormalize If true, the kernel will be normalized after sampling, such the the sum of its elements is 1. * @return A kernel representing a sampled Gaussian distribution. */ template <typename ValueType> inline auto gaussian_kernel(default_float_t sigma, default_float_t range_nr_std_deviations, bool renormalize) { using size_type = std::ptrdiff_t; const auto half_size = static_cast<size_type>(std::ceil(sigma * range_nr_std_deviations)); const auto full_size = 2 * std::max(size_type{1}, half_size) + 1; const auto center_idx = full_size / 2; SELENE_ASSERT(center_idx == (full_size - 1) / 2); auto vec = std::vector<ValueType>(static_cast<std::size_t>(full_size)); const auto sum = impl::fill_with_gaussian_pdf(vec, center_idx, sigma); auto kernel = Kernel<ValueType, kernel_size_dynamic>(std::move(vec)); if (renormalize) { kernel.normalize(sum); } return kernel; } /** \brief Returns a kernel representing a discrete uniform distribution. * * @tparam kernel_size The kernel size. * @tparam ValueType The value type of the kernel elements. * @return A kernel representing a discrete uniform distribution. */ template <KernelSize kernel_size, typename ValueType> constexpr auto uniform_kernel() { static_assert(kernel_size > 0, "Kernel size must be >0."); constexpr auto value = ValueType(1.0) / ValueType(kernel_size); constexpr auto arr = sln::make_array_n_equal<ValueType, kernel_size>(value); return Kernel<ValueType, kernel_size>(arr); } /** \brief Returns a kernel representing a discrete uniform distribution. * * @tparam ValueType The value type of the kernel elements. * @param size The kernel size. * @return A kernel representing a discrete uniform distribution. */ template <typename ValueType> inline auto uniform_kernel(KernelSize size) { if (size == 0) { return Kernel<ValueType, kernel_size_dynamic>(); } const auto value = ValueType(1.0) / ValueType(size); auto vec = std::vector<ValueType>(static_cast<std::size_t>(size), value); return Kernel<ValueType, kernel_size_dynamic>(std::move(vec)); } /** \brief Converts a floating point kernel into a kernel containing scaled integral values. * * @tparam OutValueType The output element type of the kernel to be returned. * @tparam scale_factor The multiplication factor for scaling the input kernel elements with. * @tparam ValueType The value type of the input kernel elements. * @tparam k The kernel size. * @param kernel The input floating point kernel. * @return An integer kernel, scaled by the respective factor */ template <typename OutValueType, std::ptrdiff_t scale_factor, typename ValueType, KernelSize k, typename> constexpr auto integer_kernel(const Kernel<ValueType, k>& kernel) -> Kernel<OutValueType, k> { static_assert(std::is_integral_v<OutValueType>, "Output type has to be integral"); std::array<OutValueType, k> arr = {{OutValueType{}}}; for (std::size_t i = 0; i < arr.size(); ++i) { arr[i] = sln::constexpr_round<OutValueType>(kernel[i] * scale_factor); } return Kernel<OutValueType, k>(arr); } /** \brief Converts a floating point kernel into a kernel containing scaled integral values. * * @tparam OutValueType The output element type of the kernel to be returned. * @tparam scale_factor The multiplication factor for scaling the input kernel elements with. * @tparam ValueType The value type of the input kernel elements. * @param kernel The input floating point kernel. * @return An integer kernel, scaled by the respective factor */ template <typename OutValueType, std::ptrdiff_t scale_factor, typename ValueType> inline auto integer_kernel(const Kernel<ValueType, kernel_size_dynamic>& kernel) -> Kernel<OutValueType, kernel_size_dynamic> { static_assert(std::is_integral_v<OutValueType>, "Output type has to be integral"); std::vector<OutValueType> vec(kernel.size()); for (std::size_t i = 0; i < vec.size(); ++i) { vec[i] = sln::round<OutValueType>(kernel[i] * scale_factor); } return Kernel<OutValueType, kernel_size_dynamic>(std::move(vec)); } } // namespace sln #endif // SELENE_BASE_KERNEL_HPP
33.584934
118
0.734881
kmhofmann
2e073496ac144b8a6bfddb35875375faa5b602d8
701
hpp
C++
include/srpc/net/client/Client.hpp
ISSuh/SimpleRPC
429f14d26a783ff092f326a49576d945f82ad610
[ "MIT" ]
null
null
null
include/srpc/net/client/Client.hpp
ISSuh/SimpleRPC
429f14d26a783ff092f326a49576d945f82ad610
[ "MIT" ]
null
null
null
include/srpc/net/client/Client.hpp
ISSuh/SimpleRPC
429f14d26a783ff092f326a49576d945f82ad610
[ "MIT" ]
null
null
null
/** * * Copyright: Copyright (c) 2020, ISSuh * */ #ifndef SRPC_NET_CLIENT_CLIENT_HPP_ #define SRPC_NET_CLIENT_CLIENT_HPP_ #include <string> namespace srpc { class Client { public: Client() = default; virtual ~Client() = default; virtual void connect(const std::string& host, const std::string& port) = 0; virtual void close() = 0; virtual void request(const std::string& serviceName, const std::string& rpcName, const std::string& params) = 0; virtual void onConnect() = 0; virtual void onRead(std::string serializedMessage) = 0; virtual void onWrite() = 0; }; } // namespace srpc #endif // SRPC_NET_CLIENT_CLIENT_HPP_
20.617647
77
0.650499
ISSuh
2e0b091088cf71f68a084d4552744de6ae5d4717
1,017
cpp
C++
Projects/RealityEngine/source/Core/Tools/Logger.cpp
Volta948/RealityEngine
1a9e4b7db00617176d06004af934d6602dd5920a
[ "BSD-3-Clause" ]
null
null
null
Projects/RealityEngine/source/Core/Tools/Logger.cpp
Volta948/RealityEngine
1a9e4b7db00617176d06004af934d6602dd5920a
[ "BSD-3-Clause" ]
null
null
null
Projects/RealityEngine/source/Core/Tools/Logger.cpp
Volta948/RealityEngine
1a9e4b7db00617176d06004af934d6602dd5920a
[ "BSD-3-Clause" ]
1
2021-11-05T02:55:27.000Z
2021-11-05T02:55:27.000Z
// Copyright Reality Engine. All Rights Reserved. #include "Core/Tools/Logger.h" #include <cstdarg> #include <fstream> Reality::Logger::Logger() : m_File{ std::make_unique<std::ofstream>(L"Logs/Logs.txt", std::ios::out | std::ios::trunc) } {} Reality::Logger::~Logger() = default; void Reality::Logger::Log(const char*, int line, const char* func, LogVerbosity, unsigned severity, const char* message, ...) { if (severity < Severity) { return; } std::lock_guard guard{ m_Lock }; static constexpr auto s_BufferSize{ 512ull }; char buffer[s_BufferSize]; const auto charSize{ std::snprintf(buffer, s_BufferSize, "Function %s line %d at %s.\n", func, line, __TIME__) }; m_File->write(buffer, charSize); std::va_list args{}; va_start(args, message); const auto messageSize{ std::vsnprintf(buffer, s_BufferSize, message, args) }; va_end(args); m_File->write(buffer, messageSize); if (Callback) { Callback(buffer); } else { std::puts(buffer); } }
24.214286
115
0.6647
Volta948
2e0d0122bacb5ad04230aba27e3e9ecbf382b718
502
cpp
C++
libs/renderer/src/renderer/plugin/collection.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/renderer/src/renderer/plugin/collection.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/renderer/src/renderer/plugin/collection.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // 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) #include <sge/plugin/impl/instantiate_collection.hpp> #include <sge/renderer/core.hpp> #include <sge/renderer/plugin/collection.hpp> #include <sge/renderer/plugin/iterator.hpp> #include <sge/renderer/plugin/traits.hpp> SGE_PLUGIN_IMPL_INSTANTIATE_COLLECTION(sge::renderer::core);
38.615385
61
0.750996
cpreh
2e0ee15dff2c766adf01350b6a9fdd5048e8f91d
1,066
cpp
C++
source/physics/private/internal/simulation/frameparts/framebody.cpp
fpuma/Physics2dModule
c329e45d05c77b81a45e0d509fe8deb1d327c686
[ "MIT" ]
null
null
null
source/physics/private/internal/simulation/frameparts/framebody.cpp
fpuma/Physics2dModule
c329e45d05c77b81a45e0d509fe8deb1d327c686
[ "MIT" ]
null
null
null
source/physics/private/internal/simulation/frameparts/framebody.cpp
fpuma/Physics2dModule
c329e45d05c77b81a45e0d509fe8deb1d327c686
[ "MIT" ]
null
null
null
#include <precompiledphysics.h> #include "framebody.h" #include <utils/geometry/shapes/shape.h> #include <box2d/b2_body.h> #include <box2d/b2_fixture.h> namespace puma::physics { FrameBody::FrameBody( FramePartID _id ) : m_framePart( _id ) { } /*Vec2 Body::getOffset() const { return m_offset; }*/ float FrameBody::getFriction() const { return m_framePart.getFriction(); } void FrameBody::setFriction( float _friction ) { m_framePart.setFriction( _friction ); } float FrameBody::getDensity() const { return m_framePart.getDensity(); } void FrameBody::setDensity( float _density ) { m_framePart.setDensity( _density ); } float FrameBody::getRestitution() const { return m_framePart.getRestitution(); } void FrameBody::setRestitution( float _restitution ) { m_framePart.setRestitution( _restitution ); } bool FrameBody::isValid() const { return m_framePart.isValid(); } }
19.035714
56
0.621013
fpuma
2e1485ad2f45fde33689f4fb8ab88f2ad53fa067
774
cpp
C++
src/Game.cpp
Hello56721/wars
d8fb1b88fbb8e863e95d17a2ff96cd5dc197f026
[ "MIT" ]
1
2021-09-29T14:33:37.000Z
2021-09-29T14:33:37.000Z
src/Game.cpp
Hello56721/wars
d8fb1b88fbb8e863e95d17a2ff96cd5dc197f026
[ "MIT" ]
null
null
null
src/Game.cpp
Hello56721/wars
d8fb1b88fbb8e863e95d17a2ff96cd5dc197f026
[ "MIT" ]
null
null
null
#include <pch.hpp> #include <Game.hpp> #include <scenes/TestScene.hpp> using wars::Game; using wars::scenes::TestScene; Game::Game(): m_input(m_window) { std::cout << "[INFO]: Using OpenGL " << glGetString(GL_VERSION) << "\n"; int maximumTextureSize = 0; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maximumTextureSize); std::cout << "[INFO]: Maximum Texture size is " << maximumTextureSize << "\n"; Scene::setActiveScene<TestScene>(); } void Game::mainLoop() { // Show the window only when the main loop has began. m_window.show(); while (m_window.isOpen()) { Scene::updateActiveScene(); Scene::renderActiveScene(); m_window.update(); } } Game::~Game() { Scene::removeActiveScene(); }
18.428571
82
0.621447
Hello56721
2e178db7e33c163e0cccdfc46c70386814872ce8
3,842
hpp
C++
boost/xml/dom/node.hpp
stefanseefeld/boost.xml
f68b661566b1e8a487295f63c846bd8012c1eb94
[ "BSL-1.0" ]
1
2018-03-22T14:23:28.000Z
2018-03-22T14:23:28.000Z
boost/xml/dom/node.hpp
stefanseefeld/boost.xml
f68b661566b1e8a487295f63c846bd8012c1eb94
[ "BSL-1.0" ]
null
null
null
boost/xml/dom/node.hpp
stefanseefeld/boost.xml
f68b661566b1e8a487295f63c846bd8012c1eb94
[ "BSL-1.0" ]
null
null
null
#ifndef boost_xml_dom_node_hpp_ #define boost_xml_dom_node_hpp_ #include <boost/xml/dom/nodefwd.hpp> #include <boost/xml/dom/iterator.hpp> #include <stdexcept> namespace boost { namespace xml { namespace dom { enum node_type { INTERNAL = 0, ELEMENT, ATTRIBUTE, TEXT, CDATA, PI, COMMENT, }; template <typename N> class node_ptr { public: node_ptr() : impl_(0) {} node_ptr(N const &n) : impl_(n) {} //. downcasting copy-constructor (e.g. element_ptr -> node_ptr) template <typename N2> node_ptr(node_ptr<N2> n) : impl_(*n.get()) {} N &operator*() { return this->impl_;} N *operator->() { return &this->impl_;} N *get() { return &this->impl_;} operator bool() const { return this->impl_.impl();} private: N impl_; }; template <typename T, typename N> inline T cast(node_ptr<N> n); template <typename S> class node : public detail::wrapper<xmlNode*> { template <typename N> friend class iterator; friend class node_ptr<node<S> >; friend class node_ptr<node<S> const>; friend class element<S>; friend class xpath<S>; friend node_ptr<node<S> > detail::ptr_factory<node<S> >(xmlNode *); friend node_ptr<node<S> const> detail::ptr_factory<node<S> const>(xmlNode *); template <typename T, typename N> friend T cast(node_ptr<N>); public: bool operator== (node<S> const &n) { return impl() == impl(n);} node_type type() const { return types[this->impl()->type];} //. Return the node's name. S name() const { return converter<S>::out(this->impl()->name);} //. Return the node's path within its document. S path() const; //. Return the node's active base (See XBase). S base() const; //. Return the node's active language. S lang() const; //. Return the parent node, if any. node_ptr<element<S> const> parent() const { return detail::ptr_factory<element<S> >(this->impl()->parent);} node_ptr<element<S> > parent() { return detail::ptr_factory<element<S> >(this->impl()->parent);} protected: node(xmlNode *n) : detail::wrapper<xmlNode*>(n) {} node(node<S> const &n) : detail::wrapper<xmlNode*>(n) {} node<S> &operator=(node<S> const &n) { detail::wrapper<xmlNode*>::operator=(n); return *this; } private: static node_type const types[22]; static char const *names[7]; }; template <typename S> inline S node<S>::path() const { xmlChar *path = xmlGetNodePath(this->impl()); S retn = converter<S>::out(path); xmlFree(path); return retn; } template <typename S> inline S node<S>::base() const { xmlChar *path = xmlNodeGetBase(0, this->impl()); S retn = converter<S>::out(path); xmlFree(path); return retn; } template <typename S> inline S node<S>::lang() const { xmlChar *path = xmlNodeGetLang(this->impl()); S retn = converter<S>::out(path); xmlFree(path); return retn; } template <typename S> node_type const node<S>::types[22] = { INTERNAL, ELEMENT, //XML_ELEMENT_NODE ATTRIBUTE, //XML_ATTRIBUTE_NODE TEXT, //XML_TEXT_NODE CDATA, //XML_CDATA_SECTION_NODE INTERNAL, //XML_ENTITY_REF_NODE INTERNAL, //XML_ENTITY_NODE PI, //XML_PI_NODE COMMENT, //XML_COMMENT_NODE INTERNAL, //XML_DOCUMENT_NODE INTERNAL, //XML_DOCUMENT_TYPE_NODE INTERNAL, //XML_DOCUMENT_FRAG_NODE INTERNAL, //XML_NOTATION_NODE INTERNAL, //XML_HTML_DOCUMENT_NODE INTERNAL, //XML_DTD_NODE INTERNAL, //XML_ELEMENT_DECL INTERNAL, //XML_ATTRIBUTE_DECL INTERNAL, //XML_ENTITY_DECL INTERNAL, //XML_NAMESPACE_DECL INTERNAL, //XML_XINCLUDE_START INTERNAL, //XML_XINCLUDE_END INTERNAL, //XML_DOCB_DOCUMENT_NODE }; template <typename S> char const *node<S>::names[7] = { "internal node", "element", "attribute", "text node", "cdata block", "processing instruction", "comment" }; } // namespace boost::xml::dom } // namespace boost::xml } // namespace boost #endif
23.716049
79
0.675169
stefanseefeld
2e1b6b4a494dffcd58c5feac28e4afb5e1d26dbc
14,091
hpp
C++
include/gbBase/Allocator/AllocationStrategyRing.hpp
ComicSansMS/GhulbusBase
9d07e0ab6e80c93121d261605d0f3c859af149da
[ "MIT" ]
22
2016-02-01T03:52:29.000Z
2020-12-11T18:43:42.000Z
include/gbBase/Allocator/AllocationStrategyRing.hpp
ComicSansMS/GhulbusBase
9d07e0ab6e80c93121d261605d0f3c859af149da
[ "MIT" ]
null
null
null
include/gbBase/Allocator/AllocationStrategyRing.hpp
ComicSansMS/GhulbusBase
9d07e0ab6e80c93121d261605d0f3c859af149da
[ "MIT" ]
7
2017-02-13T15:25:58.000Z
2019-05-10T19:54:31.000Z
#ifndef GHULBUS_LIBRARY_INCLUDE_GUARD_BASE_ALLOCATOR_ALLOCATION_STRATEGY_RING_HPP #define GHULBUS_LIBRARY_INCLUDE_GUARD_BASE_ALLOCATOR_ALLOCATION_STRATEGY_RING_HPP /** @file * * @brief Ring allocation strategy. * @author Andreas Weis (der_ghulbus@ghulbus-inc.de) */ #include <gbBase/config.hpp> #include <gbBase/Allocator/DebugPolicy.hpp> #include <gbBase/Allocator/StorageView.hpp> #include <gbBase/Assert.hpp> #include <cstddef> #include <cstring> #include <limits> #include <memory> #include <new> namespace GHULBUS_BASE_NAMESPACE { namespace Allocator { namespace AllocationStrategy { /** The ring allocation strategy. * A ring is an extension of the Stack allocation strategy, that uses a doubly-linked list of Headers, instead of * the singly-linked list used by Stack. This allows memory to be reclaimed from both ends of the list, not just * the top, enabling both LIFO and FIFO style allocations, as well as mixes of the two. * Reclaiming memory from the beginning will leave a gap of free memory at the start of the storage buffer. * In order to make use of that memory, the ring will attempt to *wrap-around* when it runs out of memory * towards the end of the storage buffer. The wrap-around is imperfect in that a contiguous block cannot be wrapped, * thus the end of the storage buffer acts as a natural fragmentation point in the conceptually circular memory space. * * The following picture shows the internal state after 4 allocations p1 through p4. This state is very similar * to that of a Stack allocator, except that all Headers also maintain pointers to the next element. * - Each allocated block is preceded by a Header and optionally by a padding region * to satisfy alignment requirements. * - Padding is performed such that each pN meets the requested alignment requirement *and* * the preceding header meets the natural alignment requirement for Header. * - Each header contains a pointer to the start of the previous header, the start of the next header, * and a flag indicating whether the corresponding block was deallocated. * - m_topHeader points to the top-most header that has not been deallocated. * - m_bottomHeader points to the bottom-most header that has not been deallocated. * - The start of the free memory is pointed to by m_freeMemoryOffset. * - Memory can be reclaimed from both sides by moving the m_bottomHeader pointer to the right, or the * m_topHeader pointer to the left. * - Note that since headers do not track the size of their blocks, deallocation can only move * the free memory offset back to the start of the header of the deallocated block, leaving the * padding bytes in the unavailable memory region. If the next allocation now has a weaker alignment * requirement, those bytes will be effectively lost. It would be possible to use a few additional * bits in the header to store the alignment of the block, but this was not deemed worth the * resulting runtime overhead. The lost bytes will get reclaimed when the previous block is freed. * Padding bytes before the very first block will never be reclaimed. This only applies to deallocation * from the top. Deallocation from the bottom always forwards the m_bottomHeader pointer to the * next header, effectively reclaiming the padding area preceding that header. * * <pre> * +----------------------<<-next_header-<<-------------------------------------+ * | +--<<-prev_header-<<--+ | * +--<<-prev_header-<<-------|----+ +----|--<<-prev_header-<<------ +| * | +-->>-next_header->>+ | +-next_h->+ | +->>-next_header->>-+ || * v | v | | v | | v || * +--------+-------+---------+--------+-------+--------+-------+---------+--------+-------+-------------+ * | Header | Block | Padding | Header | Block | Header | Block | Padding | Header | Block | Free Memory | * +--------+-------+---------+--------+-------+--------+-------+---------+--------+-------+-------------+ * ^ ^ ^ ^ ^ ^ ^ * | p1 p2 p3 | p4 | * m_storage.ptr m_bottomHeader m_topHeader m_freeMemoryOffset * * </pre> * * The following picture illustrates the internal state of a wrapped-around ring. An allocation p5 is located * near the end of the ring, but all allocations preceding it have already been freed. The new allocation * p6 is too big to fit in the remaining free memory area to the right of p5, so the ring wraps around, * placing p6 at the beginning of the storage instead. * - Once a ring has been wrapped around, the free memory at the end of the buffer becomes unavailable, * until all of the bottom allocations preceding it have been freed. * - In the wrapped-around case, m_freeMemoryOffset cannot grow bigger than m_bottomHeader. * * <pre> * +--------------->>--prev_header-->>---------------------+ * +----|-------------------------<<--next_header--<<-----------|-----+ * +--<<|prev_header-<<--+ | | * | |+-next_h->-+ | | | * v || v | v | * +--------+-------+--------+-------+--------------------------+--------+----------+--------------------+ * | Header | Block | Header | Block | Free Memory | Header | Block | Free Memory (unav.)| * +--------+-------+--------+-------+--------------------------+--------+----------+--------------------+ * ^ ^ ^ ^ ^ ^ ^ * | p6 | p7 | | p5 * m_storage.ptr m_topHeader m_freeMemoryOffset m_bottomHeader * * </pre> * * Upon deallocation: * - The header for the corresponding allocation is marked as free. * - The m_topHeader will be moved to the left along the list of previous headers until * it no longer points to a header that is marked free. * - The m_bottomHeader will be moved to the right along the list of next headers until * it no longer points to a header that is marked free. * - The m_freeMemoryOffset will point to the beginning of the last free header encountered * from the top, or to the beginning of the storage if no more headers remain. * * @tparam Debug_T One of the DebugPolicy policies. */ template<typename Debug_T = Allocator::DebugPolicy::AllocateDeallocateCounter> class Ring : private Debug_T { public: /** Header used for internal bookkeeping of allocations. * Each block of memory returned by allocate() is preceded by a header. */ class Header { private: /** Packed data field. * The header needs to store the following information: * - pointer to the next Header * - pointer to the previous Header * - flag indicating whether the block was freed * The flag is packed into the least significant bit of the previous pointer, * as that one is always 0 due to Header's own alignment requirements. */ std::uintptr_t m_data[2]; public: explicit Header(Header* previous_header) { static_assert(sizeof(Header*) == sizeof(std::uintptr_t)); static_assert(alignof(Header) >= 2); m_data[0] = 0; std::memcpy(&m_data[1], &previous_header, sizeof(Header*)); } void setNextHeader(Header* header) { GHULBUS_PRECONDITION_DBG(header && !m_data[0]); std::memcpy(&m_data, &header, sizeof(Header*)); } void clearPreviousHeader() { GHULBUS_PRECONDITION_DBG((m_data[1] & ~(std::uintptr_t(0x01) )) != 0); std::uintptr_t const tmp = (m_data[1] & 0x01); std::memcpy(&m_data[1], &tmp, sizeof(Header*)); } void clearNextHeader() { GHULBUS_PRECONDITION_DBG(m_data[0] != 0); m_data[0] = 0; } Header* nextHeader() const { Header* ret; std::memcpy(&ret, &m_data, sizeof(Header*)); return ret; } Header* previousHeader() const { std::uintptr_t const tmp = m_data[1] & ~(std::uintptr_t(0x01)); Header* ret; std::memcpy(&ret, &tmp, sizeof(Header*)); return ret; } void markFree() { m_data[1] |= 0x01; } bool wasFreed() const { return ((m_data[1] & 0x01) != 0); } }; private: StorageView m_storage; Header* m_topHeader; ///< Header of the top-most (most-recent) allocation. Header* m_bottomHeader; ///< Header of the bottom-most (oldest) allocation. std::size_t m_freeMemoryOffset; ///< Offset to the start of the free memory region in bytes public: /** @tparam Storage_T A Storage type that can be used as an argument to makeStorageView(). */ template<typename Storage_T> explicit Ring(Storage_T& storage) noexcept :m_storage(makeStorageView(storage)), m_topHeader(nullptr), m_bottomHeader(nullptr), m_freeMemoryOffset(0) {} std::byte* allocate(std::size_t n, std::size_t alignment) { auto const getFreeMemoryContiguous = [this](std::size_t offs) -> std::size_t { std::byte* offs_ptr = (m_storage.ptr + offs); std::byte* bottom_ptr = reinterpret_cast<std::byte*>(m_bottomHeader); if(bottom_ptr < offs_ptr) { // linear case: free space from offset to end of storage return m_storage.size - offs; } else { // wrap-around case: free space from offset to bottom header return bottom_ptr - offs_ptr; } }; // we have to leave room for the header before the pointer that we return std::size_t free_space = getFreeMemoryContiguous(m_freeMemoryOffset); bool const out_of_memory = (free_space < sizeof(Header)); free_space -= (out_of_memory) ? 0 : sizeof(Header); void* ptr = reinterpret_cast<void*>(m_storage.ptr + getFreeMemoryOffset() + sizeof(Header)); // the alignment has to be at least alignof(Header) to guarantee that the header is // stored at its natural alignment. // As usual, this assumes that all alignments are powers of two. if(out_of_memory || (!std::align(std::max(alignment, alignof(Header)), n, ptr, free_space))) { // we are out of memory, so try wrap around the ring if(isWrappedAround() || ((free_space = getFreeMemoryContiguous(0)) < sizeof(Header))) { // already wrapped, or not enough space for header even after wrapping throw std::bad_alloc(); } free_space -= sizeof(Header); ptr = reinterpret_cast<void*>(m_storage.ptr + sizeof(Header)); if(!std::align(std::max(alignment, alignof(Header)), n, ptr, free_space)) { // not enough free space in the beginning either throw std::bad_alloc(); } } std::byte* ret = reinterpret_cast<std::byte*>(ptr); // setup a header in the memory region immediately preceding ret Header* new_header = new (ret - sizeof(Header)) Header(m_topHeader); if(m_topHeader == nullptr) { m_bottomHeader = new_header; } else { m_topHeader->setNextHeader(new_header); } m_topHeader = new_header; GHULBUS_ASSERT_DBG(m_bottomHeader); m_freeMemoryOffset = (ret - m_storage.ptr) + n; this->onAllocate(n, alignment, ret); return ret; } void deallocate(std::byte* p, std::size_t n) { this->onDeallocate(p, n); // mark the deallocated block as freed in the header Header* header_start = reinterpret_cast<Header*>(p - sizeof(Header)); header_start->markFree(); // advance the top header to the left until it no longer points to a freed header while(m_topHeader && (m_topHeader->wasFreed())) { header_start = m_topHeader; m_topHeader = header_start->previousHeader(); if(m_topHeader) { m_topHeader->clearNextHeader(); m_freeMemoryOffset = (reinterpret_cast<std::byte*>(header_start) - m_storage.ptr); } else { GHULBUS_ASSERT_DBG(m_bottomHeader == header_start); m_bottomHeader = nullptr; m_freeMemoryOffset = 0; } header_start->~Header(); } // advance the bottom header to the right until it no longer points to a freed header while(m_bottomHeader && (m_bottomHeader->wasFreed())) { header_start = m_bottomHeader; m_bottomHeader = header_start->nextHeader(); if(m_bottomHeader) { m_bottomHeader->clearPreviousHeader(); } header_start->~Header(); } } /** Returns the offset in bytes from the start of the storage to the start of the free memory region. */ std::size_t getFreeMemoryOffset() const noexcept { return m_freeMemoryOffset; } /** Indicated whether the allocator is currently in the wrapped-around state. * A ring is wrapped if new allocations are taken from the beginning of the storage, * while there are still active allocations at the end of the storage. */ bool isWrappedAround() const { // we are wrapped iff the current offset is left of the bottom header return (m_storage.ptr + getFreeMemoryOffset()) <= reinterpret_cast<std::byte*>(m_bottomHeader); } }; } } } #endif
47.285235
118
0.59137
ComicSansMS
2e1c6bd9ceb3e4b41686c7cca9d6089458bf7366
1,596
cc
C++
lib/xz-coder.cc
tkubotake/nwc-toolkit
0f15669cf70b767724a11cb73f8e634765fee365
[ "BSD-3-Clause" ]
6
2017-04-06T01:49:36.000Z
2021-03-14T15:01:59.000Z
lib/xz-coder.cc
tkubotake/nwc-toolkit
0f15669cf70b767724a11cb73f8e634765fee365
[ "BSD-3-Clause" ]
null
null
null
lib/xz-coder.cc
tkubotake/nwc-toolkit
0f15669cf70b767724a11cb73f8e634765fee365
[ "BSD-3-Clause" ]
1
2021-12-24T22:23:29.000Z
2021-12-24T22:23:29.000Z
// Copyright 2010 Susumu Yata <syata@acm.org> #include <nwc-toolkit/xz-coder.h> namespace nwc_toolkit { bool XzCoder::OpenEncoder(int preset) { if (is_open()) { return false; } int xz_preset = preset; switch (preset) { case DEFAULT_PRESET: { xz_preset = 6; break; } case BEST_SPEED_PRESET: { xz_preset = 0; break; } case BEST_COMPRESSION_PRESET: { xz_preset = 9 | LZMA_PRESET_EXTREME; break; } default: { xz_preset = preset & ~EXTREME_PRESET_FLAG; if ((xz_preset < 0) || (xz_preset > 9)) { return false; } else if ((preset & EXTREME_PRESET_FLAG) == EXTREME_PRESET_FLAG) { xz_preset |= LZMA_PRESET_EXTREME; } } } ::lzma_ret ret = ::lzma_easy_encoder(&stream_, xz_preset, LZMA_CHECK_CRC64); if (ret != LZMA_OK) { return false; } mode_ = ENCODER_MODE; return true; } bool XzCoder::OpenDecoder() { if (is_open()) { return false; } ::lzma_ret ret = ::lzma_stream_decoder(&stream_, 128 << 20, 0); if (ret != LZMA_OK) { return false; } mode_ = DECODER_MODE; return true; } bool XzCoder::Close() { if (!is_open()) { return false; } ::lzma_end(&stream_); InitStream(); mode_ = NO_MODE; is_end_ = false; return true; } bool XzCoder::Code(::lzma_action action) { if (!is_open() || is_end()) { return false; } ::lzma_ret ret = ::lzma_code(&stream_, action); if (ret == LZMA_STREAM_END) { is_end_ = true; return true; } return (ret == LZMA_OK) || (ret == LZMA_BUF_ERROR); } } // namespace nwc_toolkit
20.461538
78
0.60589
tkubotake
2e1fbed4203bb08d6c4fc90530683bd6e89f6993
6,016
hpp
C++
src/libgit2xx/git2xx/Git.hpp
DrFrankenstein/goot
2ea08283bd2fb52360ecd6a36d210fcc19332334
[ "MIT" ]
null
null
null
src/libgit2xx/git2xx/Git.hpp
DrFrankenstein/goot
2ea08283bd2fb52360ecd6a36d210fcc19332334
[ "MIT" ]
null
null
null
src/libgit2xx/git2xx/Git.hpp
DrFrankenstein/goot
2ea08283bd2fb52360ecd6a36d210fcc19332334
[ "MIT" ]
null
null
null
#pragma once #include "Buffer.hpp" #include "Error.hpp" #include "Repository.hpp" #include "StrArray.hpp" #include <cstddef> #include <git2/config.h> #include <git2/global.h> #include <git2/repository.h> #include <git2/sys/alloc.h> #include <git2/types.h> #include <string> #include <utility> #ifdef _MSC_VER # include <BaseTsd.h> using ssize_t = SSIZE_T; #endif namespace Git { /** * A RAII wrapper around libgit2's init and shutdown functions, and a central * entry point to the library. */ class Git { public: Git() { git_libgit2_init(); } ~Git() { git_libgit2_shutdown(); } // we _could_ allow copying since libgit2 uses refcounting, but it might // also lead to too many unnecessary calls to init and shutdown if best // practices aren't followed. Git(const Git& other) = delete; auto operator=(const Git& other) -> Git& = delete; // no moving: there's no such thing as a null instance of this class, so // destroying the donor instance will still cause a call to shutdown. Git(Git&& other) = delete; auto operator=(Git&& other) -> Git& = delete; auto features() { return git_libgit2_features(); } auto maxWindowSize() { return getOpt<std::size_t>(GIT_OPT_GET_MWINDOW_SIZE); } auto setMaxWindowSize(std::size_t size) { setOpt(GIT_OPT_SET_MWINDOW_SIZE, size); } auto maxWindowMappedLimit() { return getOpt<std::size_t>(GIT_OPT_GET_MWINDOW_MAPPED_LIMIT); } auto setMaxWindowMappedLimit(std::size_t size) { setOpt(GIT_OPT_SET_MWINDOW_MAPPED_LIMIT, size); } auto maxWindowFileLimit() { return getOpt<std::size_t>(GIT_OPT_GET_MWINDOW_FILE_LIMIT); } auto setMaxWindowFileLimit(std::size_t size) { setOpt(GIT_OPT_SET_MWINDOW_FILE_LIMIT, size); } auto searchPath(git_config_level_t level) { return getOpt(GIT_OPT_GET_SEARCH_PATH, level); } auto setSearchPath(git_config_level_t level, const std::string& path) { setOpt(GIT_OPT_SET_SEARCH_PATH, level, path.c_str()); } auto setCacheObjectLimit(git_object_t type, std::size_t size) { setOpt(GIT_OPT_SET_CACHE_OBJECT_LIMIT, type, size); } auto setCacheMaxSize(ssize_t max_storage_bytes) { setOpt(GIT_OPT_SET_CACHE_MAX_SIZE, max_storage_bytes); } auto enableCaching(bool enable) { setOpt(GIT_OPT_ENABLE_CACHING, static_cast<int>(enable)); } auto cachedMemory() { ssize_t current, allowed; git_libgit2_opts(GIT_OPT_GET_CACHED_MEMORY, &current, &allowed); return std::tuple { current, allowed }; } auto templatePath() { return getOpt(GIT_OPT_GET_TEMPLATE_PATH); } auto setTemplatePath(const std::string& path) { setOpt(GIT_OPT_SET_TEMPLATE_PATH, path.c_str()); } auto setSslCertFile(const std::string& file) { setOpt(GIT_OPT_SET_SSL_CERT_LOCATIONS, file.c_str(), nullptr); } auto setSslCertPath(const std::string& path) { setOpt(GIT_OPT_SET_SSL_CERT_LOCATIONS, nullptr, path.c_str()); } auto setSslCiphers(const std::string& ciphers) { setOpt(GIT_OPT_SET_SSL_CIPHERS, ciphers.c_str()); } auto userAgent() { return getOpt(GIT_OPT_GET_USER_AGENT); } auto setUserAgent(const std::string& user_agent) { setOpt(GIT_OPT_SET_USER_AGENT, user_agent.c_str()); } auto windowsShareMode() { return getOpt<unsigned long>(GIT_OPT_GET_WINDOWS_SHAREMODE); } auto setWindowsShareMode(unsigned long value) { setOpt(GIT_OPT_SET_WINDOWS_SHAREMODE, value); } auto enableStrictObjectCreation(bool enable) { setOpt(GIT_OPT_ENABLE_STRICT_OBJECT_CREATION, static_cast<int>(enable)); } auto enableStrictSymbolicRefCreation(bool enable) { setOpt(GIT_OPT_ENABLE_STRICT_SYMBOLIC_REF_CREATION, static_cast<int>(enable)); } auto enableStrictHashVerification(bool enable) { setOpt(GIT_OPT_ENABLE_STRICT_HASH_VERIFICATION, static_cast<int>(enable)); } auto enableOffsetDelta(bool enable) { setOpt(GIT_OPT_ENABLE_OFS_DELTA, static_cast<int>(enable)); } auto enableFsyncGitdir(bool enable) { setOpt(GIT_OPT_ENABLE_FSYNC_GITDIR, static_cast<int>(enable)); } auto setAllocator(git_allocator* allocator) { setOpt(GIT_OPT_SET_ALLOCATOR, allocator); } auto enableUnsavedIndexSafety(bool enable) { setOpt(GIT_OPT_ENABLE_UNSAVED_INDEX_SAFETY, static_cast<int>(enable)); } auto packMaxObjects() { return getOpt<std::size_t>(GIT_OPT_GET_PACK_MAX_OBJECTS); } auto setPackMaxObjects(std::size_t objects) { setOpt(GIT_OPT_SET_PACK_MAX_OBJECTS, objects); } auto disablePackKeepFileChecks(bool disable) { setOpt(GIT_OPT_DISABLE_PACK_KEEP_FILE_CHECKS, static_cast<int>(disable)); } auto enableHttpExpectContinue(bool enable) { setOpt(GIT_OPT_ENABLE_HTTP_EXPECT_CONTINUE, static_cast<int>(enable)); } auto setOdbPackedPriority(int priority) { setOpt(GIT_OPT_SET_ODB_PACKED_PRIORITY, priority); } auto setOdbLoosePriority(int priority) { setOpt(GIT_OPT_SET_ODB_LOOSE_PRIORITY, priority); } auto extensions() { return getOptStrs(GIT_OPT_GET_EXTENSIONS); } auto setExtensions(std::span<const char*> extensions) { setOpt(GIT_OPT_SET_EXTENSIONS, extensions.data(), extensions.size()); } auto openRepository( const std::string& path, git_repository_open_flag_t flags = GIT_REPOSITORY_OPEN_NO_SEARCH, const std::string& ceiling_dirs = {}) { Repository repo; const auto status = git_repository_open_ext( &repo, path.c_str(), flags, ceiling_dirs.empty() ? nullptr : ceiling_dirs.c_str()); ensureOk(status); return repo; } private: template<class Out, class... Args> auto getOpt(git_libgit2_opt_t opt, Args... args) { Out retval; const auto status = git_libgit2_opts(opt, args..., &retval); ensureOk(status); return retval; } template<class... Args> auto getOpt(git_libgit2_opt_t opt, Args... args) { Buffer buf; const auto status = git_libgit2_opts(opt, args..., &buf); ensureOk(status); return buf; } template<class... Args> auto getOptStrs(git_libgit2_opt_t opt, Args... args) { StrArray array; const auto status = git_libgit2_opts(opt, args..., &array); ensureOk(status); return array; } template<class... Args> auto setOpt(git_libgit2_opt_t opt, Args... args) { const auto status = git_libgit2_opts(opt, args...); ensureOk(status); } }; }
36.907975
133
0.759641
DrFrankenstein
2e205baea6d122bbb0340dba71649a40cba55445
1,556
cpp
C++
src/SignalSlotFactory.cpp
Joeasaurus/spina
00a331aec57c3d18adc9eed02d992b44c659ea10
[ "MIT" ]
null
null
null
src/SignalSlotFactory.cpp
Joeasaurus/spina
00a331aec57c3d18adc9eed02d992b44c659ea10
[ "MIT" ]
null
null
null
src/SignalSlotFactory.cpp
Joeasaurus/spina
00a331aec57c3d18adc9eed02d992b44c659ea10
[ "MIT" ]
1
2021-12-26T17:12:08.000Z
2021-12-26T17:12:08.000Z
#include "SignalSlotFactory.hpp" namespace spina { // Create typename SignalSlotFactory::signal_ptr SignalSlotFactory::createSignal(const std::string& name) { signals[name] = std::shared_ptr<signal_t>(new signal_t); return signals[name]; }; void SignalSlotFactory::createSlot(const std::string& name, const SignalSlotFactory::slot_t subscriber) { slots.insert({ name, subscriber }); }; // Connect typename SignalSlotFactory::conn_t SignalSlotFactory::connect(const std::string& name, const SignalSlotFactory::slot_t &subscriber, const int& index) { auto sig = assert_signal_exists(name); return sig->second->connect(index, subscriber); }; typename SignalSlotFactory::conn_t SignalSlotFactory::connect(const std::string& signal_name, const std::string& slot_name, const int& index) { auto sl = assert_slot_exists(slot_name); return connect(signal_name, sl->second, index); }; // Asserts typename SignalSlotFactory::signal_map::iterator SignalSlotFactory::assert_signal_exists(const std::string& name) { auto sig = signals.find(name); if (sig == signals.end()) throw 50; return sig; }; typename SignalSlotFactory::slot_map::iterator SignalSlotFactory::assert_slot_exists(const std::string& name) { auto sig = slots.find(name); if (sig == slots.end()) throw 50; return sig; }; // Raise void SignalSlotFactory::raise(const std::string& signal_name, const std::string& data) { auto sig = assert_signal_exists(signal_name); auto p = sig->second.get(); (*p)(data); }; }
29.358491
151
0.720437
Joeasaurus
2e20d4f01525e78ddaa507048601ed6a56e9a05b
996
cpp
C++
tests/Day21.cpp
willkill07/AdventOfCode2021
06e62cd8a8c7f1e99374075b7302f6dcfb770bb0
[ "Apache-2.0" ]
12
2021-12-02T01:44:53.000Z
2022-02-02T17:22:23.000Z
tests/Day21.cpp
willkill07/AdventOfCode2021
06e62cd8a8c7f1e99374075b7302f6dcfb770bb0
[ "Apache-2.0" ]
null
null
null
tests/Day21.cpp
willkill07/AdventOfCode2021
06e62cd8a8c7f1e99374075b7302f6dcfb770bb0
[ "Apache-2.0" ]
1
2021-12-03T04:25:32.000Z
2021-12-03T04:25:32.000Z
#include <catch2/catch_all.hpp> #include "AdventTest.hpp" #include "AdventDay.hpp" #include "Day21.hpp" using namespace day21; namespace { char const* input = R"MULTILINE(Player 1 starting position: 4 Player 2 starting position: 8)MULTILINE"; auto const expected_part1 = 739785u; auto const expected_part2 = 444356092776315lu; using Day = AdventDay<id, parsed, result1, result2>; } SCENARIO("2021.day.21","[2021][21]") { GIVEN("Sample input") { tmp_file sample{id}; sample.append(input); auto parsed = Day::parse(sample.name()); WHEN("Running Part 1") { auto actual = Day::solve<false>(parsed); THEN("We get the correct answer") { REQUIRE(actual == expected_part1); } } AND_WHEN("Running Part 2") { auto actual = Day::solve<true>(parsed); THEN("We get the correct answer") { REQUIRE(actual == expected_part2); } } } }
23.714286
61
0.596386
willkill07
2e223b660845b5275acf039b08fd8bfa13cb2ef8
1,164
cpp
C++
discrete-maths/matroids/a_schedule.cpp
nothingelsematters/university
5561969b1b11678228aaf7e6660e8b1a93d10294
[ "WTFPL" ]
1
2018-06-03T17:48:50.000Z
2018-06-03T17:48:50.000Z
discrete-maths/matroids/a_schedule.cpp
nothingelsematters/University
b1e188cb59e5a436731b92c914494626a99e1ae0
[ "WTFPL" ]
null
null
null
discrete-maths/matroids/a_schedule.cpp
nothingelsematters/University
b1e188cb59e5a436731b92c914494626a99e1ae0
[ "WTFPL" ]
14
2019-04-07T21:27:09.000Z
2021-12-05T13:37:25.000Z
#include <fstream> #include <iostream> #include <algorithm> #include <vector> #include <set> int main() { std::ifstream fin("schedule.in"); size_t quantity; fin >> quantity; std::vector<std::pair<long long, long long>> task; for (size_t i = 0; i < quantity; ++i) { long long a, b; fin >> a >> b; task.emplace_back(a, b); } fin.close(); std::sort(task.begin(), task.end()); long long penalty = 0; long long time = 0; std::multiset<long long> punish; for (long long i = 0; i < quantity; ++i) { // std::cout << last << ' ' << task[i].first << '\n'; if (time >= task[i].first) { if (!punish.empty() && *(punish.begin()) < task[i].second) { penalty += *(punish.begin()); punish.erase(punish.begin()); punish.insert(task[i].second); } else { penalty += task[i].second; } } else { // std::cout << task[i].first << ' '; punish.insert(task[i].second); ++time; } } std::ofstream fout("schedule.out"); fout << penalty; }
27.714286
72
0.485395
nothingelsematters
2e24f22ba791b2431b901fb6a773c4b54a471a06
524
hpp
C++
src/core/Texture.hpp
Xnork/Project-Engine-SDL2
c49b2c1d83373f027624b3e5ff2f52633100db73
[ "MIT" ]
null
null
null
src/core/Texture.hpp
Xnork/Project-Engine-SDL2
c49b2c1d83373f027624b3e5ff2f52633100db73
[ "MIT" ]
null
null
null
src/core/Texture.hpp
Xnork/Project-Engine-SDL2
c49b2c1d83373f027624b3e5ff2f52633100db73
[ "MIT" ]
null
null
null
#ifndef TEXTURE_H #define TEXTURE_H #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <iostream> #include <cstring> #include "math/Vector2.hpp" using namespace std; class Texture { public: Texture(); explicit Texture(const string, SDL_Renderer*); virtual SDL_Texture *getTextureSDL() noexcept; const Vector2i getTextureSize() const; virtual void loadFromFile(const string, SDL_Renderer*); virtual ~Texture(); private: SDL_Texture *texture; Vector2i texture_size; }; #endif
18.068966
59
0.719466
Xnork
2e26951b789d18a2b4ca0ddb3fca67cce92bff4e
2,501
cpp
C++
Veri/VeriSiniflari/tekmarketbilgileri.cpp
mtc61/techmarket
64533703db4256686abe428c007fd4a784ad2b5b
[ "Apache-2.0" ]
null
null
null
Veri/VeriSiniflari/tekmarketbilgileri.cpp
mtc61/techmarket
64533703db4256686abe428c007fd4a784ad2b5b
[ "Apache-2.0" ]
null
null
null
Veri/VeriSiniflari/tekmarketbilgileri.cpp
mtc61/techmarket
64533703db4256686abe428c007fd4a784ad2b5b
[ "Apache-2.0" ]
null
null
null
#include "tekmarketbilgileri.h" TEKMarketBilgileri::TEKMarketBilgileri(QObject *parent) : QObject(parent) { } IdTuru TEKMarketBilgileri::getId() const { return TeknoMarketId; } void TEKMarketBilgileri::setId(const IdTuru &value) { if(value == TeknoMarketId) return; TeknoMarketId = value; emit IdDegisti(TeknoMarketId); } Metin TEKMarketBilgileri::getTeknoMarketAdi() const { return TeknoMarketAdi; } void TEKMarketBilgileri::setTeknoMarketAdi(const Metin &value) { if(value == TeknoMarketAdi) return; TeknoMarketAdi = value; emit TeknoMarketAdiDegisti(TeknoMarketAdi); } Metin TEKMarketBilgileri::getTeknoMarketAdresi() const { return TeknoMarketAdresi; } void TEKMarketBilgileri::setTeknoMarketAdresi(const Metin &value) { if(value == TeknoMarketAdresi) return; TeknoMarketAdresi = value; emit TeknoMarketAdresiDegisti(TeknoMarketAdresi); } Metin TEKMarketBilgileri::getTeknoMarketYetkilisi() const { return TeknoMarketYetkilisi; } void TEKMarketBilgileri::setTeknoMarketYetkilisi(const Metin &value) { if(value == TeknoMarketYetkilisi) return; TeknoMarketYetkilisi = value; emit TeknoMarketYetkilisiDegisti(TeknoMarketYetkilisi); } Tamsayi TEKMarketBilgileri::getTeknoMarketTelefonu() const { return TeknoMarketTelefonu; } void TEKMarketBilgileri::setTeknoMarketTelefonu(const Tamsayi &value) { if(value == TeknoMarketTelefonu) return; TeknoMarketTelefonu = value; emit TeknoMarketTelefonuDegisti(TeknoMarketTelefonu); } QDataStream &operator<<(QDataStream &stream , TEKMarketBilgileriptr &veri){ stream << veri->getId() << veri->getTeknoMarketAdi() << veri->getTeknoMarketAdresi() << veri->getTeknoMarketYetkilisi() << veri->getTeknoMarketTelefonu() ; return stream; } QDataStream &operator>>(QDataStream &stream, TEKMarketBilgileriptr &veri){ IdTuru TeknoMarketId; Metin TeknoMarketAdi,TeknoMarketAdresi,TeknoMarketYetkilisi; Tamsayi TeknoMarketTelefonu; stream >> TeknoMarketId >> TeknoMarketAdi >> TeknoMarketAdresi >> TeknoMarketYetkilisi >> TeknoMarketTelefonu ; veri= std :: make_shared<TEKMarketBilgileri>(); veri ->setId(TeknoMarketId); veri ->setTeknoMarketAdi(TeknoMarketAdi); veri ->setTeknoMarketAdresi(TeknoMarketAdresi); veri ->setTeknoMarketYetkilisi(TeknoMarketYetkilisi); veri ->setTeknoMarketTelefonu(TeknoMarketTelefonu); return stream; }
24.281553
123
0.738505
mtc61
2e2c43a247a6e7ad72376193ecffea9d265b1364
533
hpp
C++
obelus/client/interfaces/i_app_system.hpp
monthyx1337/obelus-hack
8e83eb89ef56788c1b9c5af66b815824d17f309d
[ "MIT" ]
36
2021-07-08T01:30:44.000Z
2022-03-25T13:16:59.000Z
obelus/client/interfaces/i_app_system.hpp
monthyx1337/obelus-hack
8e83eb89ef56788c1b9c5af66b815824d17f309d
[ "MIT" ]
2
2021-09-11T05:11:55.000Z
2022-01-28T07:49:39.000Z
obelus/client/interfaces/i_app_system.hpp
monthyx1337/obelus-hack
8e83eb89ef56788c1b9c5af66b815824d17f309d
[ "MIT" ]
14
2021-07-08T00:11:12.000Z
2022-03-20T11:10:17.000Z
#pragma once class i_app_system; typedef void* (*create_interface_fn)(const char* name, int* return_code); class i_app_system { public: virtual bool connect(create_interface_fn factory) = 0; virtual void disconnect() = 0; virtual void* query_interface(const char* interface_name) = 0; virtual int init() = 0; virtual void shutdown() = 0; virtual const void* get_client() = 0; virtual int get_tier() = 0; virtual void reconnect(create_interface_fn factory, const char* interface_name) = 0; virtual void unknown() = 0; };
28.052632
85
0.739212
monthyx1337
aa31c875a706c5943757ad2fcc8eca2e72b9d66d
1,952
hpp
C++
gmsl_camera/src/DataPath.hpp
vehicularkech/gmsl-camera-ros-driver
1dfadb91c4b5829ca562e362911f1b3dcb7ab083
[ "MIT" ]
2
2018-04-20T02:26:18.000Z
2018-10-11T03:20:36.000Z
gmsl_camera/src/DataPath.hpp
vehicularkech/gmsl-camera-ros-driver
1dfadb91c4b5829ca562e362911f1b3dcb7ab083
[ "MIT" ]
1
2018-07-12T08:19:31.000Z
2018-07-12T08:19:31.000Z
gmsl_camera/src/DataPath.hpp
vehicularkech/gmsl-camera-ros-driver
1dfadb91c4b5829ca562e362911f1b3dcb7ab083
[ "MIT" ]
1
2019-01-24T03:02:45.000Z
2019-01-24T03:02:45.000Z
// This code contains NVIDIA Confidential Information and is disclosed // under the Mutual Non-Disclosure Agreement. // // Notice // ALL NVIDIA DESIGN SPECIFICATIONS AND CODE ("MATERIALS") ARE PROVIDED "AS IS" NVIDIA MAKES // NO REPRESENTATIONS, WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO // THE MATERIALS, AND EXPRESSLY DISCLAIMS ANY IMPLIED WARRANTIES OF NONINFRINGEMENT, // MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. // // NVIDIA Corporation assumes no responsibility for the consequences of use of such // information or for any infringement of patents or other rights of third parties that may // result from its use. No license is granted by implication or otherwise under any patent // or patent rights of NVIDIA Corporation. No third party distribution is allowed unless // expressly authorized by NVIDIA. Details are subject to change without notice. // This code supersedes and replaces all information previously supplied. // NVIDIA Corporation products are not authorized for use as critical // components in life support devices or systems without express written approval of // NVIDIA Corporation. // // Copyright (c) 2015-2016 NVIDIA Corporation. All rights reserved. // // NVIDIA Corporation and its licensors retain all intellectual property and proprietary // rights in and to this software and related documentation and any modifications thereto. // Any use, reproduction, disclosure or distribution of this software and related // documentation without an express license agreement from NVIDIA Corporation is // strictly prohibited. // ///////////////////////////////////////////////////////////////////////////////////////// #ifndef SAMPLES_COMMON_DATAPATH_HPP__ #define SAMPLES_COMMON_DATAPATH_HPP__ #include <string> class DataPath { public: // Base path for all data static std::string get() { return "../data"; } }; #endif // SAMPLES_COMMON_DATAPATH_HPP__
42.434783
94
0.745389
vehicularkech
aa334f86237f31707fde90f5165981665b96d318
3,259
cpp
C++
Grammars/Lab02/Lab02/main.cpp
IceNerd/hogwarts
df1f3e1a94688fd728f6b54653a36a47671293da
[ "Unlicense" ]
null
null
null
Grammars/Lab02/Lab02/main.cpp
IceNerd/hogwarts
df1f3e1a94688fd728f6b54653a36a47671293da
[ "Unlicense" ]
null
null
null
Grammars/Lab02/Lab02/main.cpp
IceNerd/hogwarts
df1f3e1a94688fd728f6b54653a36a47671293da
[ "Unlicense" ]
null
null
null
#include <conio.h> #include <iostream> #include <fstream> #include <string> #include <algorithm> #include <vector> #include "STable.h" std::string CreateStringFromFile( const std::string& ); std::vector<std::string> Tokenize( const std::string&, const std::string& = " " ); void Analyze( std::vector<std::string>& ); int main() { std::vector<std::string> vctTokens; std::string strAnalyze( CreateStringFromFile( "tester.txt" ) ); vctTokens = Tokenize( strAnalyze, ":'\"<>+%&=.-*/~(){}[];, " ); Analyze( vctTokens ); _getch(); } std::string CreateStringFromFile( const std::string& strFile ) { std::ifstream inFile( strFile.c_str() ); char strLine; std::string strReturn; if( inFile.is_open() ) { while( !inFile.eof() ) { inFile.get( strLine ); //ignore tabs and linebreaks if( (strLine != '\n') && (strLine != '\t') && (!inFile.eof()) ) { strReturn += strLine; } } } inFile.close(); return strReturn; } std::vector<std::string> Tokenize( const std::string& strTok, const std::string& strDelim ) { std::vector<std::string> vctReturn; std::string::size_type lastPos = strTok.find_first_not_of( strDelim, 0 ); std::string::size_type Pos = strTok.find_first_of( strDelim, lastPos ); vctReturn.clear(); while( strTok[lastPos + 1] ) { if( lastPos == 0 ) { vctReturn.push_back( strTok.substr( lastPos, Pos - lastPos ) ); } else { if( strTok.substr( lastPos, 1 ) != " " ) { vctReturn.push_back( strTok.substr( lastPos, 1 ) ); } if( Pos - lastPos != 1 ) { vctReturn.push_back( strTok.substr( lastPos + 1, (Pos - lastPos) - 1 ) ); } } lastPos = strTok.find_first_of( strDelim, Pos ); Pos = strTok.find_first_of( strDelim, lastPos + 1 ); } vctReturn.push_back( strTok.substr( lastPos, 1 ) ); return vctReturn; } void Analyze( std::vector<std::string>& vctTokens ) { if( !vctTokens.empty() ) { STable SymbolTable( "clegal.txt" ); char chBuffer[100]; //--- propogate our Keywords( 1 ) std::ifstream inKeyFile( "keywords.txt" ); if( inKeyFile.is_open() ) { while( !inKeyFile.eof() ) { inKeyFile.getline( chBuffer, 100 ); SymbolTable.Add( chBuffer, 1 ); } } inKeyFile.close(); //--- //--- propogate our Operators( 2 ) std::ifstream inOpFile( "operators.txt" ); if( inOpFile.is_open() ) { while( !inOpFile.eof() ) { inOpFile.getline( chBuffer, 100 ); SymbolTable.Add( chBuffer, 2 ); } } inOpFile.close(); //--- //--- propogate our Symbols( 3 ) std::ifstream inSymFile( "symbols.txt" ); if( inSymFile.is_open() ) { while( !inSymFile.eof() ) { inSymFile.getline( chBuffer, 100 ); SymbolTable.Add( chBuffer, 3 ); } } inSymFile.close(); //--- for( std::vector<std::string>::iterator iter_i = vctTokens.begin(); iter_i != vctTokens.end(); ++iter_i ) { std::cout.width(13); switch( SymbolTable.Find( (*iter_i) ) ) { case 0: std::cout<<"IDENTIFIER: "; break; case 1: std::cout<<"KEYWORD: "; break; case 2: std::cout<<"OPERATOR: "; break; case 3: std::cout<<"SYMBOL: "; break; default: std::cout<<"UNKNOWN: "; break; } std::cout<<(*iter_i)<<"\n"; } } }
20.496855
107
0.597423
IceNerd
aa382ae061a2609f8c4eb5e7b32e7a96f8354d7f
10,374
cpp
C++
src/main.cpp
d99kris/nchat
2c51cf2ff7ab7b655067ba290071d9b005544e68
[ "MIT" ]
82
2019-02-19T15:00:19.000Z
2022-03-24T20:22:43.000Z
src/main.cpp
d99kris/nchat
2c51cf2ff7ab7b655067ba290071d9b005544e68
[ "MIT" ]
47
2019-03-07T13:07:36.000Z
2022-03-27T14:32:09.000Z
src/main.cpp
d99kris/nchat
2c51cf2ff7ab7b655067ba290071d9b005544e68
[ "MIT" ]
12
2019-03-06T18:58:41.000Z
2022-03-26T17:41:31.000Z
// main.cpp // // Copyright (c) 2019-2021 Kristofer Berggren // All rights reserved. // // nchat is distributed under the MIT license, see LICENSE for details. #include <iostream> #include <map> #include <regex> #include <set> #include <string> #include <path.hpp> #include "appconfig.h" #include "apputil.h" #include "fileutil.h" #include "log.h" #include "messagecache.h" #include "profiles.h" #include "scopeddirlock.h" #include "tgchat.h" #include "ui.h" #include "uiconfig.h" #ifdef HAS_DUMMY #include "duchat.h" #endif #ifdef HAS_WHATSAPP #include "wachat.h" #endif static bool SetupProfile(); static void ShowHelp(); static void ShowVersion(); static std::vector<std::shared_ptr<Protocol>> GetProtocols() { std::vector<std::shared_ptr<Protocol>> protocols = { #ifdef HAS_DUMMY std::make_shared<DuChat>(), #endif std::make_shared<TgChat>(), #ifdef HAS_WHATSAPP std::make_shared<WaChat>(), #endif }; return protocols; } int main(int argc, char* argv[]) { // Defaults umask(S_IRWXG | S_IRWXO); FileUtil::SetApplicationDir(std::string(getenv("HOME")) + std::string("/.nchat")); Log::SetVerboseLevel(Log::INFO_LEVEL); // Argument handling std::string exportDir; bool isSetup = false; std::vector<std::string> args(argv + 1, argv + argc); for (auto it = args.begin(); it != args.end(); ++it) { if (((*it == "-d") || (*it == "--configdir")) && (std::distance(it + 1, args.end()) > 0)) { ++it; FileUtil::SetApplicationDir(*it); } else if ((*it == "-e") || (*it == "--verbose")) { Log::SetVerboseLevel(Log::DEBUG_LEVEL); } else if ((*it == "-ee") || (*it == "--extra-verbose")) { Log::SetVerboseLevel(Log::TRACE_LEVEL); } else if ((*it == "-h") || (*it == "--help")) { ShowHelp(); return 0; } else if (*it == "-m") { AppUtil::SetDeveloperMode(true); } else if ((*it == "-s") || (*it == "--setup")) { isSetup = true; } else if ((*it == "-v") || (*it == "--version")) { ShowVersion(); return 0; } else if (((*it == "-x") || (*it == "--export")) && (std::distance(it + 1, args.end()) > 0)) { ++it; exportDir = *it; } else { ShowHelp(); return 1; } } bool isDirInited = false; static const int dirVersion = 1; if (!apathy::Path(FileUtil::GetApplicationDir()).exists()) { FileUtil::InitDirVersion(FileUtil::GetApplicationDir(), dirVersion); isDirInited = true; } ScopedDirLock dirLock(FileUtil::GetApplicationDir()); if (!dirLock.IsLocked()) { std::cerr << "error: unable to acquire lock for " << FileUtil::GetApplicationDir() << "\n" << " only one nchat session per account/confdir is supported.\n"; return 1; } if (!isDirInited) { int storedVersion = FileUtil::GetDirVersion(FileUtil::GetApplicationDir()); if (storedVersion != dirVersion) { if (isSetup) { FileUtil::InitDirVersion(FileUtil::GetApplicationDir(), dirVersion); } else { std::cout << "Config dir " << FileUtil::GetApplicationDir() << " is incompatible with this version of nchat\n"; if ((storedVersion == -1) && FileUtil::Exists(FileUtil::GetApplicationDir() + "/tdlib")) { std::cout << "Attempt to migrate config dir to new version (y/n)? "; std::string migrateYesNo; std::getline(std::cin, migrateYesNo); if (migrateYesNo != "y") { std::cout << "Migration cancelled, exiting.\n"; return 1; } std::cout << "Enter phone number (optional, ex. +6511111111): "; std::string phoneNumber = ""; std::getline(std::cin, phoneNumber); std::string profileName = "Telegram_" + phoneNumber; std::string tmpDir = "/tmp/" + profileName; FileUtil::RmDir(tmpDir); FileUtil::MkDir(tmpDir); FileUtil::Move(FileUtil::GetApplicationDir() + "/tdlib", tmpDir + "/tdlib"); FileUtil::Move(FileUtil::GetApplicationDir() + "/telegram.conf", tmpDir + "/telegram.conf"); FileUtil::InitDirVersion(FileUtil::GetApplicationDir(), dirVersion); Profiles::Init(); FileUtil::Move(tmpDir, FileUtil::GetApplicationDir() + "/profiles/" + profileName); } else { std::cerr << "error: invalid config dir content, exiting.\n"; return 1; } } } } // Init profiles dir Profiles::Init(); // Init logging const std::string& logPath = FileUtil::GetApplicationDir() + std::string("/log.txt"); Log::SetPath(logPath); std::string appNameVersion = AppUtil::GetAppNameVersion(); LOG_INFO("starting %s", appNameVersion.c_str()); // Run setup if required if (isSetup) { bool rv = SetupProfile(); return rv ? 0 : 1; } // Init app config AppConfig::Init(); // Init ui std::shared_ptr<Ui> ui = std::make_shared<Ui>(); // Init message cache const bool cacheEnabled = AppConfig::GetBool("cache_enabled"); std::function<void(std::shared_ptr<ServiceMessage>)> messageHandler = std::bind(&Ui::MessageHandler, std::ref(*ui), std::placeholders::_1); MessageCache::Init(cacheEnabled, messageHandler); // Load profile(s) std::string profilesDir = FileUtil::GetApplicationDir() + "/profiles"; const std::vector<apathy::Path>& profilePaths = apathy::Path::listdir(profilesDir); for (auto& profilePath : profilePaths) { std::stringstream ss(profilePath.filename()); std::string protocolName; if (!std::getline(ss, protocolName, '_')) { LOG_WARNING("invalid profile name, skipping."); continue; } std::vector<std::shared_ptr<Protocol>> allProtocols = GetProtocols(); for (auto& protocol : allProtocols) { if (protocol->GetProfileId() == protocolName) { protocol->LoadProfile(profilesDir, profilePath.filename()); ui->AddProtocol(protocol); MessageCache::AddProfile(profilePath.filename()); } } #ifndef HAS_MULTIPROTOCOL if (!ui->GetProtocols().empty()) { break; } #endif } // Protocol config params std::string isAttachmentPrefetchAll = (UiConfig::GetNum("attachment_prefetch") == AttachmentPrefetchAll) ? "1" : "0"; // Start protocol(s) and ui std::unordered_map<std::string, std::shared_ptr<Protocol>>& protocols = ui->GetProtocols(); bool hasProtocols = !protocols.empty(); if (hasProtocols && exportDir.empty()) { // Login for (auto& protocol : protocols) { protocol.second->SetMessageHandler(messageHandler); protocol.second->SetProperty(PropertyAttachmentPrefetchAll, isAttachmentPrefetchAll); protocol.second->Login(); } // Ui main loop ui->Run(); // Logout for (auto& protocol : protocols) { protocol.second->Logout(); protocol.second->CloseProfile(); } } // Cleanup ui ui.reset(); // Perform export if requested if (!exportDir.empty()) { MessageCache::Export(exportDir); } // Cleanup MessageCache::Cleanup(); AppConfig::Cleanup(); Profiles::Cleanup(); // Exit code int rv = 0; if (!hasProtocols) { std::cout << "no profiles setup, exiting.\n"; rv = 1; } return rv; } bool SetupProfile() { std::vector<std::shared_ptr<Protocol>> p_Protocols = GetProtocols(); std::cout << "Protocols:" << std::endl; size_t idx = 0; for (auto it = p_Protocols.begin(); it != p_Protocols.end(); ++it, ++idx) { std::cout << idx << ". " << (*it)->GetProfileId() << std::endl; } std::cout << idx << ". Exit setup" << std::endl; size_t selectidx = idx; std::cout << "Select protocol (" << selectidx << "): "; std::string line; std::getline(std::cin, line); if (!line.empty()) { selectidx = stoi(line); } if (selectidx >= p_Protocols.size()) { std::cout << "Setup aborted, exiting." << std::endl; return false; } std::string profileId; std::string profilesDir = FileUtil::GetApplicationDir() + std::string("/profiles"); #ifndef HAS_MULTIPROTOCOL FileUtil::RmDir(profilesDir); FileUtil::MkDir(profilesDir); Profiles::Init(); #endif bool rv = p_Protocols.at(selectidx)->SetupProfile(profilesDir, profileId); if (rv) { std::cout << "Succesfully set up profile " << profileId << "\n"; } else { std::cout << "Setup failed\n"; } return rv; } void ShowHelp() { std::cout << "nchat is a minimalistic terminal-based chat client with support for\n" "telegram.\n" "\n" "Usage: nchat [OPTION]\n" "\n" "Command-line Options:\n" " -d, --confdir <DIR> use a different directory than ~/.nchat\n" " -e, --verbose enable verbose logging\n" " -ee, --extra-verbose enable extra verbose logging\n" " -h, --help display this help and exit\n" " -s, --setup set up chat protocol account\n" " -v, --version output version information and exit\n" " -x, --export <DIR> export message cache to specified dir\n" "\n" "Interactive Commands:\n" " PageDn history next page\n" " PageUp history previous page\n" " Tab next chat\n" " Sh-Tab previous chat\n" " Ctrl-e insert emoji\n" " Ctrl-g toggle show help bar\n" " Ctrl-l toggle show contact list\n" " Ctrl-p toggle show top bar\n" " Ctrl-q quit\n" " Ctrl-s search contacts\n" " Ctrl-t send file\n" " Ctrl-u jump to unread chat\n" " Ctrl-x send message\n" " Ctrl-y toggle show emojis\n" " KeyUp select message\n" "\n" "Interactive Commands for Selected Message:\n" " Ctrl-d delete selected message\n" " Ctrl-r download attached file\n" " Ctrl-v open/view attached file\n" " Ctrl-x reply to selected message\n" "\n" "Report bugs at https://github.com/d99kris/nchat\n" "\n"; } void ShowVersion() { std::cout << "nchat v" << AppUtil::GetAppVersion() << "\n" "\n" "Copyright (c) 2019-2021 Kristofer Berggren\n" "\n" "nchat is distributed under the MIT license.\n" "\n" "Written by Kristofer Berggren.\n"; }
26.329949
119
0.591768
d99kris
aa3cf804ebd650fa05fdf9ce18400749aad0059f
298
cpp
C++
src/Request/BalanceCheck.cpp
ZavierJin/AccountManager
b09235e71fa43a2c6ece1d6739ef44885d28af34
[ "Apache-2.0" ]
null
null
null
src/Request/BalanceCheck.cpp
ZavierJin/AccountManager
b09235e71fa43a2c6ece1d6739ef44885d28af34
[ "Apache-2.0" ]
null
null
null
src/Request/BalanceCheck.cpp
ZavierJin/AccountManager
b09235e71fa43a2c6ece1d6739ef44885d28af34
[ "Apache-2.0" ]
null
null
null
// BalanceCheck.cpp // Brief introduction: the implementation of BalanceCheck's method // Create by Zhang Zhecheng 2020/5/18 #include "Request.h" namespace request { BalanceCheck::BalanceCheck(const string &username) : UserRequest(username, Kind::BalanceCheck){} } // namespace request
29.8
66
0.748322
ZavierJin
aa3d370266bba86ba940dbe0f1f26b7b6dd23bfb
14,765
cpp
C++
sumo-wrapper/code/par-sumo-wrapper.cpp
esegredo/Optimisation-Real-world-Traffic-Light-Cycle-Programs-Evolutionary-Computation
cfe6e3e8f333f906430d668f4f2b475dfdd71d9e
[ "MIT" ]
null
null
null
sumo-wrapper/code/par-sumo-wrapper.cpp
esegredo/Optimisation-Real-world-Traffic-Light-Cycle-Programs-Evolutionary-Computation
cfe6e3e8f333f906430d668f4f2b475dfdd71d9e
[ "MIT" ]
null
null
null
sumo-wrapper/code/par-sumo-wrapper.cpp
esegredo/Optimisation-Real-world-Traffic-Light-Cycle-Programs-Evolutionary-Computation
cfe6e3e8f333f906430d668f4f2b475dfdd71d9e
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <fstream> #include <vector> #include <cstdlib> #include <ctime> #include <sstream> #include <map> #include <chrono> #include <sys/wait.h> #include "cInstance.hpp" #include "simpleXMLParser.hpp" using namespace std; typedef struct { double GvR; // Original Green vs Red double nGvR; // Normalized GvR double duration; // Total duration unsigned numVeh; // Vehicles arriving unsigned remVeh; // Vehicles not arriving double stops; // Number of stops (waiting counts and not planned stops) double waitingTime; // Total time that vehicles have been waiting (at a speed lower than 0.1 m/s) double fitness; // Fitness // New stats double meanTravelTime; // Mean Travel Time double meanWaitingTime; // Mean Waiting Time long double CO2; // CO2 long double CO; // CO long double HC; // HC long double NOx; // NOx long double PMx; // PMx long double fuel; // fuel long double noise; // noise } tStatistics; // Auxiliar functions // Convert a number to string // string to_string(unsigned long v); // Build XML additional file with new tlLogic tags from TL configuration void buildXMLfile(const cInstance &c, const vector<unsigned> &tl_times, unsigned long long t, string dir); // Deletes the created files void deleteFiles(const cInstance &c, unsigned long long t, string dir); // Read TL configuration (generated by the algorithm) void readTLtime(string tl_filename, vector<unsigned> &tl); // Build command for executing SUMO string buildCommand(const cInstance &c, unsigned long long t, string dir, unsigned int numRep, vector<int> seeds); // Write the result file void writeResults(const tStatistics &s, string filename, unsigned int numRep); // Executes a command with a pipe string execCommandPipe(string command); // Calculating statistics // Calculate GvR value void calculateGvR(const cInstance &c, const vector<unsigned> & tl_times, tStatistics &s); // Analyze trip info obtaining how many vehicle arriving, number of stops, total duration, ... void analyzeTripInfo(const cInstance &c, unsigned long long t, tStatistics &s, string dir, unsigned int numRep); // Analyze Summary File void analyzeSummary(const cInstance &c, unsigned long long t, tStatistics &s, string dir, unsigned int numRep); // Calculate Fitness double calculateFitness(const tStatistics &s, unsigned simTime); // Analyze emission file void analyzeEmissions(const cInstance &c, unsigned long long t, tStatistics &s, string dir, unsigned int numRep); int main(int argc, char **argv) { //time_t current_time = time(0), t2, t3, t4; auto start = chrono::high_resolution_clock::now(); auto current_time = chrono::duration_cast<chrono::nanoseconds>(start.time_since_epoch()).count(); if(argc != 7) { cout << "Usage: " << argv[0] << " <instance_file> <dir> <traffic light configuration> <result files> <delete generated files> <number of repetitions>" << endl; exit(-1); } cInstance instance; instance.read(argv[1]); vector<unsigned> tl_times; readTLtime(argv[3], tl_times); srand(time(NULL)); vector<int> seeds; for (int i = 0; i < atoi(argv[6]); i++) { seeds.push_back(rand()); } buildXMLfile(instance, tl_times, current_time, argv[2]); // The parallelisation should start herein #pragma omp parallel for for (int i = 0; i < atoi(argv[6]); i++) { string cmd = buildCommand(instance, current_time, argv[2], i, seeds); cout << "Executing sumo ..." << endl; auto t2 = chrono::high_resolution_clock::now(); execCommandPipe(cmd); auto t3 = chrono::duration_cast<chrono::milliseconds>(chrono::high_resolution_clock::now() - t2).count(); cout << "SUMO time: " << t3 << endl; cout << "Obtaining statistics ..." << endl; // Obtaining statistics tStatistics s; calculateGvR(instance, tl_times, s); analyzeTripInfo(instance, current_time, s, argv[2], i); analyzeSummary(instance, current_time, s, argv[2], i); //analyzeEmissions(*instance, current_time, s, i); // Calculates fitness based on the statistics s.fitness = calculateFitness(s, instance.getSimulationTime()); writeResults(s, argv[4], i); } auto t4 = chrono::duration_cast<chrono::milliseconds>(chrono::high_resolution_clock::now() - start).count(); cout << "Total time: " << t4 << endl; cout << endl; if (stoi(argv[5]) == 1) deleteFiles(instance, current_time, argv[2]); return 0; } // Convert a number to string /*string to_string(unsigned long v) { stringstream ss; ss << v; return ss.str(); }*/ void buildXMLfile(const cInstance &c, const vector<unsigned> &tl_times, unsigned long long t, string dir) { // string xmlfile = c.getPath() + dir + "/" + to_string(t) + "-" + c.getName() + ".add.xml"; string xmlfile = c.getPath() + dir + "/" + c.getName() + ".add.xml"; ofstream fout_xml(xmlfile.c_str()); unsigned nTL = c.getNumberOfTLlogics(); vector<string> phases; unsigned nPhases; unsigned tl_times_counter = 0; fout_xml << "<additional>" << endl; for (int i=0;i<nTL;i++) { //fout_xml << "\t<tlLogic id=\"" << c.getTLID(i) << "\" type=\"static\" programID=\"1\" offset=\"0\">" << endl; fout_xml << "\t<tlLogic id=\"" << c.getTLID(i) << "\" type=\"static\" programID=\"1\" offset=\"" << tl_times[tl_times_counter] << "\">" << endl; tl_times_counter++; phases = c.getPhases(i); nPhases = phases.size(); for (int j=0;j<nPhases;j++) { fout_xml << "\t\t<phase duration=\"" << tl_times[tl_times_counter] << "\" state=\"" << phases[j] << "\"/>" << endl; tl_times_counter++; } fout_xml << "\t</tlLogic>" << endl; } fout_xml << "</additional>" << endl; fout_xml.close(); } void deleteFiles(const cInstance &c, unsigned long long t, string dir) { // string baseName = c.getPath() + dir + "/" + to_string(t) + "-" + c.getName(); string baseName = c.getPath() + dir + "/" + c.getName(); string cmd = "rm " + baseName + ".add.xml"; execCommandPipe(cmd); cmd = "rm " + baseName + "-*-summary.xml"; execCommandPipe(cmd); cmd = "rm " + baseName + "-*-tripinfo.xml"; execCommandPipe(cmd); cmd = "rm " + baseName + "-*-vehicles.xml"; execCommandPipe(cmd); } void readTLtime(string tl_filename, vector<unsigned> &tl) { ifstream fin_tl(tl_filename.c_str()); unsigned t; fin_tl >> t; while(!fin_tl.eof()) { tl.push_back(t); fin_tl >> t; } fin_tl.close(); } string buildCommand(const cInstance &c, unsigned long long t, string dir, unsigned int numRep, vector<int> seeds) { //string cmd = "sumo "; string cmd = "sumo -W "; string name1 = c.getPath() + c.getName(); // Required instace files //string name2 = c.getPath() + dir + "/" + to_string(t) + "-" + c.getName(); // generated files by this application string name2 = c.getPath() + dir + "/" + c.getName(); // generated files by this application // Input files: cmd += "-n " + name1 + ".net.xml "; // Network file cmd += "-r " + name1 + ".rou.xml "; // Routes file cmd += "-a " + name2 + ".add.xml "; // TL file // Output files: //cmd += "--save-configuration " + name2 + ".cfg "; // Save configuration <= With this option configuration file is generated but no SUMO execution is performed //cmd += "--emission-output " + name1 + "-emissions.xml "; // Emissions result cmd += "--summary-output " + name2 + "-" + to_string(numRep) + "-summary.xml "; // Summary result cmd += "--vehroute-output " + name2 + "-" + to_string(numRep) + "-vehicles.xml "; // Vehicle routes result cmd += "--tripinfo-output " + name2 + "-" + to_string(numRep) + "-tripinfo.xml "; // tripinfo result // Options: cmd += "-b 0 "; // Begin time cmd += "-e " + to_string(c.getSimulationTime()) + " "; // End time cmd += "-s 0 "; // route steps (with value 0, the whole routes file is loaded) cmd += "--time-to-teleport -1 "; // Disable teleporting cmd += "--no-step-log "; // Disable console output //cmd += "--device.hbefa.probability 1.0 "; // Tripinfo file will include emissions stats cmd += "--device.emissions.probability 1.0 "; //cmd += "--seed " + to_string(t); // random seed //cmd += "--seed 23432 "; //cmd += "--random true "; //cmd += "--thread-rngs 8 "; cmd += "--seed " + to_string(seeds[numRep]) + " "; // THIS IS NEW!!!! No validation cmd += "--xml-validation never"; return cmd; } // GvR (Green vs Red) // Requires tl configuration (no sumo simulation required) // GvR = \sum_{i=0}^{totalPhases}{GvR_phase(i)} // GvR_phase(i) = duration(i) * (number_of_greens(i) / number_of_reds(i)) // Larger values are better // Disadvantages: - No normalized - yellow/red phases are not counted // Alternatives: // Normaziled GvR: nGvR // nGVR = 1/number_of_TL * \sum_{i = 0}^{number_of_TL}{ (\sum_{j=0}^{phases_TL(i)}{GvR_phase(j)})/ (\sum_{j=0}^{phases_TL(i)}{duration(j)}) } // Larger values are better // Advantages: - Normalized (0/1) - All phases are taken into account void calculateGvR(const cInstance &c, const vector<unsigned> & tl_times, tStatistics &s) { unsigned nTL = c.getNumberOfTLlogics(); // Number of TL logics unsigned nPhases; // Number of phases of a TL unsigned nt; // Number of tl in a TL logic // auxiliar variables vector<string> phases; unsigned tl_times_counter = 0; double gvr, dur, red, green; s.GvR = s.nGvR = 0; for (int i=0;i<nTL;i++) { phases = c.getPhases(i); nPhases = phases.size(); tl_times_counter++; gvr = 0; dur = 0; for (int j=0;j<nPhases;j++) { red = green = 0; nt = phases[j].size(); for(int k = 0; k < nt; k++) { if(phases[j][k] == 'r') red++; else if(toupper(phases[j][k]) == 'G') green++; } if(red == 0) red++; gvr += (green/red)*tl_times[tl_times_counter]; dur += tl_times[tl_times_counter]; tl_times_counter++; } s.GvR += gvr; s.nGvR += (gvr/dur); } s.nGvR /= nTL; } void analyzeTripInfo(const cInstance &c, unsigned long long t, tStatistics &s, string dir, unsigned int numRep) { // string filename = c.getPath() + dir + "/" + to_string(t) + "-" + c.getName() + "-tripinfo.xml"; string filename = c.getPath() + dir + "/" + c.getName() + "-" + to_string(numRep) + "-tripinfo.xml"; string line; ifstream fin(filename.c_str()); map<string, string> m; int position; s.numVeh = 0; s.duration = 0; s.stops = 0; s.waitingTime = 0; s.CO2 = 0; s.CO = 0; s.HC = 0; s.NOx = 0; s.PMx = 0; s.fuel = 0; s.noise = 0; getline(fin, line); while(!fin.eof()) { if(isSubString(line,"id=",position)) { // get map getPairMap(line, m); s.numVeh++; s.duration += atof(m["duration"].c_str()); // It is the number of times vehicles have been waiting (at a speed lower than 0.1 m/s) // It does not include the number of planned stops s.stops += atof(m["waitingCount"].c_str()); // It is the times a vehicle has been waiting (at a speed lower than 0.1 m/s) // It does not include the planned stops time s.waitingTime += atof(m["waitingTime"].c_str()); } else if(isSubString(line,"CO_abs=",position)) { getPairMap(line, m); s.CO2 += atof(m["CO2_abs"].c_str()); s.CO += atof(m["CO_abs"].c_str()); s.HC += atof(m["HC_abs"].c_str()); s.NOx += atof(m["NOx_abs"].c_str()); s.PMx += atof(m["PMx_abs"].c_str()); s.fuel += atof(m["fuel_abs"].c_str()); //s.noise += atof(m["noise"].c_str()); } getline(fin, line); } s.remVeh = c.getNumberOfVehicles() - s.numVeh; fin.close(); } void analyzeSummary(const cInstance &c, unsigned long long t, tStatistics &s, string dir, unsigned int numRep) { // string filename = c.getPath() + dir + "/" + to_string(t) + "-" + c.getName() + "-summary.xml"; string filename = c.getPath() + dir + "/" + c.getName() + "-" + to_string(numRep) + "-summary.xml"; string line,last_line; ifstream fin(filename.c_str()); map<string, string> m; int position; getline(fin, line); while(!fin.eof()) { if(isSubString(line,"time=",position)) { last_line = line; } getline(fin, line); } // get map getPairMap(last_line, m); s.meanTravelTime = atof(m["meanTravelTime"].c_str()); s.meanWaitingTime = atof(m["meanWaitingTime"].c_str()); fin.close(); } double calculateFitness(const tStatistics &s, unsigned simTime) { return (s.duration + (s.remVeh * simTime) + s.waitingTime) / (s.numVeh * s.numVeh + s.GvR); } void analyzeEmissions(const cInstance &c, unsigned long long t, tStatistics &s, string dir, unsigned int numRep) { // string filename = c.getPath() + dir + "/" + to_string(t) + "-" + c.getName() + "-emissions.xml"; string filename = c.getPath() + dir + "/" + c.getName() + "-" + to_string(numRep) + "-emissions.xml"; string line; ifstream fin(filename.c_str()); map<string, string> m; int position; s.CO2 = 0; s.CO = 0; s.HC = 0; s.NOx = 0; s.PMx = 0; s.fuel = 0; s.noise = 0; getline(fin, line); while(!fin.eof()) { if(isSubString(line,"id=",position)) { // get map getPairMap(line, m); s.CO2 += atof(m["CO2"].c_str()); s.CO += atof(m["CO"].c_str()); s.HC += atof(m["HC"].c_str()); s.NOx += atof(m["NOx"].c_str()); s.PMx += atof(m["PMx"].c_str()); s.fuel += atof(m["fuel"].c_str()); s.noise += atof(m["noise"].c_str()); } getline(fin, line); } fin.close(); } void writeResults(const tStatistics &s, string filename, unsigned int numRep) { filename += "." + to_string(numRep); ofstream fout(filename.c_str()); fout << s.GvR << " // Original Green vs Red" << endl; fout << s.nGvR << " // Normalized GvR" << endl; fout << s.duration << " // Total duration" << endl; fout << s.numVeh << " // Vehicles arriving" << endl; fout << s.remVeh << " // Vehicles not arriving" << endl; fout << s.stops << " // Number of stops (waiting counts)" << endl; fout << s.waitingTime << " // Total waiting time (at a speed lower than 0.1 m/s)" << endl; fout << s.fitness << " // Fitness" << endl; fout << s.meanTravelTime << " // Mean Travel Time" << endl; fout << s.meanWaitingTime << " // Mean Waiting Time" << endl; fout << s.CO2 << " // CO2 " << endl; fout << s.CO << " // CO" << endl; fout << s.HC << " // HC" << endl; fout << s.NOx << " // NOx" << endl; fout << s.PMx << " // PMx" << endl; fout << s.fuel << " // fuel" << endl; fout << s.noise << " // noise" << endl; fout.close(); } string execCommandPipe(string command) { const int MAX_BUFFER_SIZE = 128; FILE* pipe = popen(command.c_str(), "r"); // Waits until the execution ends if (wait(NULL) == -1){ //cerr << "Error waiting for simulator results" << endl; return "Error waiting for simulator results"; } char buffer[MAX_BUFFER_SIZE]; string result = ""; while (!feof(pipe)) { if (fgets(buffer, MAX_BUFFER_SIZE, pipe) != NULL) result += buffer; } pclose(pipe); return result; }
30.256148
162
0.634338
esegredo
aa420e5a2d10e61e1f527d8a68b3453adc373880
5,787
cpp
C++
src/string.cpp
surreal-Ceres/image32
0aabb8aa2f8e45dafea6249a9873080b048183b1
[ "MIT" ]
2
2020-12-23T16:42:52.000Z
2021-04-13T20:41:09.000Z
src/string.cpp
surreal-Ceres/image32
0aabb8aa2f8e45dafea6249a9873080b048183b1
[ "MIT" ]
null
null
null
src/string.cpp
surreal-Ceres/image32
0aabb8aa2f8e45dafea6249a9873080b048183b1
[ "MIT" ]
null
null
null
#include "string.h" #include <iterator> #include <cstdarg> #include <vector> std::string string_to_lower(const std::string& str) { std::string result(str); for(auto it = result.begin(); it != result.end(); it++) *it = std::tolower(*it); return result; } std::string format_to_string(const char* format, ...) { va_list args; va_start(args, format); std::size_t required_size = vsnprintf(nullptr, 0, format, args); std::vector<char> buf(++required_size); vsnprintf(&buf[0], buf.size(), format, args); va_end(args); return std::string(&buf[0]); } static size_t insert_utf8_char(std::string* result, wchar_t wchr) { int size, bits, b, i; if (wchr < 128) { if (result) result->push_back(wchr); return 1; } bits = 7; while (wchr >= (1<<bits)) bits++; size = 2; b = 11; while (b < bits) { size++; b += 5; } if (result) { b -= (7-size); int firstbyte = wchr>>b; for (i=0; i<size; i++) firstbyte |= (0x80>>i); result->push_back(firstbyte); for (i=1; i<size; i++) { b -= 6; result->push_back(0x80 | ((wchr>>b)&0x3F)); } } return size; } std::string to_utf8(const wchar_t* wsrc, const int n) { size_t required_size = 0; const wchar_t* p = wsrc; for(int i = 0; i < n; i++, ++p) required_size += insert_utf8_char(nullptr, *p); if(!required_size) return std::string(); std::string result; result.reserve(++required_size); for(int i = 0; i < n; i++, ++wsrc) insert_utf8_char(&result, *wsrc); return result; } template<typename BaseIterator> class utf8_iterator_t : public std::iterator<std::forward_iterator_tag, std::string::value_type, std::string::difference_type, typename BaseIterator::pointer, typename BaseIterator::reference> { public: typedef typename BaseIterator::pointer pointer; utf8_iterator_t() {} explicit utf8_iterator_t(const BaseIterator& it) : m_internal(it) {} utf8_iterator_t& operator++() { int c = *m_internal; ++m_internal; if (c & 0x80) { int n = 1; while (c & (0x80>>n)) n++; c &= (1<<(8-n))-1; while (--n > 0) { int t = *m_internal; ++m_internal; if ((!(t & 0x80)) || (t & 0x40)) { --m_internal; return *this; } c = (c<<6) | (t & 0x3F); } } return *this; } utf8_iterator_t& operator+=(int sum) { while(sum--) operator++(); return *this; } utf8_iterator_t operator+(int i) { utf8_iterator_t it(*this); it += i; return it; } const int operator*() const { BaseIterator it = m_internal; int c = *it; ++it; if (c & 0x80) { int n = 1; while (c & (0x80>>n)) n++; c &= (1<<(8-n))-1; while (--n > 0) { int t = *it; ++it; if ((!(t & 0x80)) || (t & 0x40)) return '^'; c = (c<<6) | (t & 0x3F); } } return c; } bool operator==(const utf8_iterator_t& it) const { return m_internal == it.m_internal; } bool operator!=(const utf8_iterator_t& it) const { return m_internal != it.m_internal; } pointer operator->() { return m_internal.operator->(); } std::string::difference_type operator-(const utf8_iterator_t& it) const { return m_internal - it.m_internal; } private: BaseIterator m_internal; }; class utf8_iterator : public utf8_iterator_t<std::string::iterator> { public: utf8_iterator() { } utf8_iterator(const utf8_iterator_t<std::string::iterator>& it) : utf8_iterator_t<std::string::iterator>(it) { } explicit utf8_iterator(const std::string::iterator& it) : utf8_iterator_t<std::string::iterator>(it) { } }; class utf8_const_iterator : public utf8_iterator_t<std::string::const_iterator> { public: utf8_const_iterator() { } utf8_const_iterator(const utf8_iterator_t<std::string::const_iterator>& it) : utf8_iterator_t<std::string::const_iterator>(it) { } explicit utf8_const_iterator(const std::string::const_iterator& it) : utf8_iterator_t<std::string::const_iterator>(it) { } }; class utf8 { public: utf8(std::string& s) : m_begin(utf8_iterator(s.begin())), m_end(utf8_iterator(s.end())) { } const utf8_iterator& begin() const { return m_begin; } const utf8_iterator& end() const { return m_end; } private: utf8_iterator m_begin; utf8_iterator m_end; }; class utf8_const { public: utf8_const(const std::string& s) : m_begin(utf8_const_iterator(s.begin())), m_end(utf8_const_iterator(s.end())) { } const utf8_const_iterator& begin() const { return m_begin; } const utf8_const_iterator& end() const { return m_end; } private: utf8_const_iterator m_begin; utf8_const_iterator m_end; }; int utf8_length(const std::string& str) { utf8_const_iterator it(str.begin()); utf8_const_iterator end(str.end()); int size = 0; while(it != end) ++it, ++size; return size; } std::wstring from_utf8(const std::string& str) { int required_size = utf8_length(str); std::vector<wchar_t> buf(++required_size); std::vector<wchar_t>::iterator buf_it = buf.begin(); utf8_const_iterator it(str.begin()); utf8_const_iterator end(str.end()); while (it != end) { *buf_it = *it; ++buf_it; ++it; } return std::wstring(&buf[0]); }
22.257692
81
0.563332
surreal-Ceres
aa4e4438391c48eb8eb8351320b2ba86b86e9bc4
9,263
cpp
C++
qt/imageDisplay/RasterResource.cpp
e-foto/e-foto
cf143a1076c03c7bdf5a2f41efad2c98e9272722
[ "FTL" ]
3
2021-06-28T21:07:58.000Z
2021-07-02T11:21:49.000Z
qt/imageDisplay/RasterResource.cpp
e-foto/e-foto
cf143a1076c03c7bdf5a2f41efad2c98e9272722
[ "FTL" ]
null
null
null
qt/imageDisplay/RasterResource.cpp
e-foto/e-foto
cf143a1076c03c7bdf5a2f41efad2c98e9272722
[ "FTL" ]
null
null
null
#include "RasterResource.h" #include <QMessageBox> RasterResource::RasterResource(QString filepath, bool withSmoothIn, bool withSmoothOut) { // Abrir a imagem e testar se é válida QImage* srcImage = new QImage(); _isValid = srcImage->load(filepath); _levels = 0; _useSmoothIn = withSmoothIn; _useSmoothOut = withSmoothOut; if (!_isValid || srcImage->width() == 0 || srcImage->height() == 0) { if (filepath != "") emitLoadError(); return; } // Calcular o numero de niveis da piramide _imageDim = srcImage->size(); _levels = log(_imageDim.width() < _imageDim.height() ? _imageDim.width() : _imageDim.height() ) / log(2) -4; // Alocando espaço para a piramide _pyramid = (QImage**) calloc(_levels, sizeof(QImage*)); // Atribui a imagem original ao primeiro nível _pyramid[0] = new QImage(srcImage->convertToFormat(QImage::Format_ARGB32)); delete(srcImage); if (_pyramid[0]->width() == 0 || _pyramid[0]->height() == 0) { _isValid = false; delete(_pyramid[0]); free(_pyramid); emitLoadError(); return; } // Construindo imagens for(int l = 1; l < _levels; l++) { // Cada imagem do novo nível é igual ao nível anterior reduzida pela metade int w = _pyramid[l-1]->width()/2; int h = _pyramid[l-1]->height()/2; _pyramid[l] = new QImage(_pyramid[l-1]->scaled(w,h,Qt::KeepAspectRatioByExpanding, _useSmoothOut ? Qt::SmoothTransformation : Qt::FastTransformation)); if (_pyramid[l]->width() == 0 || _pyramid[l]->height() == 0) { _isValid = false; for (int k = l; l >= 0; l--) delete(_pyramid[k]); free(_pyramid); emitLoadError(); return; } } } RasterResource::~RasterResource() { if (!_isValid) return; for(int l = 0; l < _levels; l++) delete(_pyramid[l]); free(_pyramid); } void RasterResource::emitLoadError() { QMessageBox* msgBox = new QMessageBox(); msgBox->setText("Error: The image loading process."); msgBox->exec(); } void RasterResource::useSmoothIn(bool useSmooth) { _useSmoothIn = useSmooth; } void RasterResource::transformImage(double H[9]) { if (_isValid) { QImage newImage(*_pyramid[0]); QTransform h(H[0],H[3],H[6],H[1],H[4],H[7],H[2],H[5],H[8]); //qDebug("\n%f %f %f\n%f %f %f\n%f %f %f",H[0],H[3],H[6],H[1],H[4],H[7],H[2],H[5],H[8]); load(newImage.transformed(h)); } } bool RasterResource::load(QImage image) { // Impede carga de imagem nula if (image.isNull()) { emitLoadError(); return false; } // Remove imagem pré-existente if (_isValid) { for(int l = 0; l < _levels; l++) delete(_pyramid[l]); free(_pyramid); } _isValid = true; // Calcular o numero de niveis da piramide _imageDim = image.size(); _levels = log(_imageDim.width() < _imageDim.height() ? _imageDim.width() : _imageDim.height() ) / log(2) -4; if (_levels < 0) _levels = 0; // Alocando espaço para a piramide _pyramid = (QImage**) calloc(_levels, sizeof(QImage*)); // Atribui a imagem original ao primeiro nível _pyramid[0] = new QImage(image.convertToFormat(QImage::Format_ARGB32)); if (_pyramid[0]->width() == 0 || _pyramid[0]->height() == 0) { _isValid = false; delete(_pyramid[0]); free(_pyramid); emitLoadError(); return false; } // Construindo imagens for(int l = 1; l < _levels; l++) { // Cada imagem do novo nível é igual ao nível anterior reduzida pela metade int w = _pyramid[l-1]->width()/2; int h = _pyramid[l-1]->height()/2; _pyramid[l] = new QImage(_pyramid[l-1]->scaled(w,h,Qt::IgnoreAspectRatio, _useSmoothOut ? Qt::SmoothTransformation : Qt::FastTransformation)); if (_pyramid[l]->width() == 0 || _pyramid[l]->height() == 0) { _isValid = false; for (int k = l; l >= 0; l--) delete(_pyramid[k]); free(_pyramid); emitLoadError(); return false; } } return _isValid; } bool RasterResource::load(QString filepath) { // Abrir a imagem e testar se é válida QImage image; if (image.load(filepath)) { for(int l = 0; l < _levels; l++) delete(_pyramid[l]); free(_pyramid); _isValid = true; } else { return false; } // Calcular o numero de niveis da piramide _imageDim = image.size(); _levels = log(_imageDim.width() < _imageDim.height() ? _imageDim.width() : _imageDim.height() ) / log(2) -4; if (_levels < 0) _levels = 0; // Alocando espaço para a piramide _pyramid = (QImage**) calloc(_levels, sizeof(QImage*)); // Atribui a imagem original ao primeiro nível _pyramid[0] = new QImage(image.convertToFormat(QImage::Format_ARGB32)); if (_pyramid[0]->width() == 0 || _pyramid[0]->height() == 0) { _isValid = false; delete(_pyramid[0]); free(_pyramid); emitLoadError(); return false; } // Construindo imagens for(int l = 1; l < _levels; l++) { // Cada imagem do novo nível é igual ao nível anterior reduzida pela metade int w = _pyramid[l-1]->width()/2; int h = _pyramid[l-1]->height()/2; _pyramid[l] = new QImage(_pyramid[l-1]->scaled(w,h,Qt::IgnoreAspectRatio, _useSmoothOut ? Qt::SmoothTransformation : Qt::FastTransformation)); if (_pyramid[l]->width() == 0 || _pyramid[l]->height() == 0) { _isValid = false; for (int k = l; l >= 0; l--) delete(_pyramid[k]); free(_pyramid); emitLoadError(); return false; } } return _isValid; } bool RasterResource::save(QString filepath, QString format) { if (_pyramid && _pyramid[0]->save(filepath,format.toLocal8Bit().constData())) return true; return false; } bool RasterResource::isValid() { return _isValid; } int RasterResource::width() { return _imageDim.width(); } int RasterResource::height() { return _imageDim.height(); } QSize RasterResource::size() { return _imageDim; } int RasterResource::levels() { return _levels; } QPointF RasterResource::center() { return QPointF(width()/2.0,height()/2.0); } QImage RasterResource::getImageCut(QSize targetSize, QRectF imageCut) { // Este método poderia possuir a assinatura getImageCut(QSize targetSize, QPointF viewPoint, double scale) // Contudo devido a possível incompatibilidade com o TeCanvas ele ficou da forma atual QImage result; if (_isValid) { // Inicialização de variáveis para o recorte na imagem do topo da pilha QRect rectToCut = imageCut.toRect(); QImage* img = _pyramid[0]; int l = 0; // Na prática, qualquer corte deveria possuir a mesma escala em width e height // mas isso não ocorre para o recorte de Overview. Por isso recuperamos a escala assim: double wscale = targetSize.width() / imageCut.width(); double hscale = targetSize.height() / imageCut.height(); double scale = (wscale > hscale) ? wscale : hscale; // Seleciona a imagem correta a recortar, faz o recorte e ajustes para perfeito encaixe do centro do recorte na imagem com a imagem resultante if (scale > 1.0) { // Este caso precisa ser tratado com atenção. // Precisamos manter o aspécto da imagem, o zoom correto e o ponto central do recorte corretamente alinhado // Primeiro evitamos problemas com o espaço recortado aumentando ligeiramente a área de recorte //comentar depois rectToCut.setLeft(rectToCut.left()-1); rectToCut.setTop(rectToCut.top()-1); rectToCut.setWidth(rectToCut.width()+2); rectToCut.setHeight(rectToCut.height()+2); // Criamos um newTargetSize para a nova escala com o aspécto do primeiro recorte QSize newTargetSize = rectToCut.size() * scale; // Um recorte final vai garantir a posição corretamente alinhada e o targetSize pedido QRect finalCut(((imageCut.topLeft() - QPointF(rectToCut.topLeft())) * scale).toPoint(), targetSize); result = img->copy(rectToCut).scaled(newTargetSize,Qt::KeepAspectRatioByExpanding, _useSmoothIn ? Qt::SmoothTransformation : Qt::FastTransformation).copy(finalCut); } else if (scale > 0.5) { // Corta e reduz a imagem a partir do primeiro nível da pirâmide. Este é o caso mais simples result = img->copy(rectToCut).scaled(targetSize,Qt::KeepAspectRatioByExpanding, _useSmoothOut ? Qt::SmoothTransformation : Qt::FastTransformation); } else { // Procura o nível correto da pirâmide que será utilizado e o novo imageCut while (scale <= 0.5 && l<_levels-1) { scale *= 2; l++; QPointF center(QPointF(imageCut.center().x()/2.0,imageCut.center().y()/2.0)); imageCut.setSize(imageCut.size()/2.0); imageCut.moveCenter(center); } // Troca a imagem pela imagem do nível correto, seleciona o novo corte e recorta. img = _pyramid[l]; rectToCut = imageCut.toRect(); result = img->copy(rectToCut).scaled(targetSize,Qt::KeepAspectRatioByExpanding, _useSmoothOut ? Qt::SmoothTransformation : Qt::FastTransformation); } } //Nem toda tela tem 96 dpi, refazer depois result.setDotsPerMeterX(3780); result.setDotsPerMeterY(3780); return result; } QColor RasterResource::getColor(QPoint at) { if (_isValid && at.x() >= 0 && at.y() >= 0 && at.x() < width() -1 && at.y() < height() - 1) return QColor(_pyramid[0]->pixel(at)); else return QColor(); } unsigned int RasterResource::getGrayColor(QPointF at, bool linear) { unsigned int result = 0; if (_isValid && at.x() >= 0 && at.y() >= 0 && at.x() < width() -1 && at.y() < height() - 1) { if (linear) { // adicionar a parte linear aqui depois. } else result = qGray(_pyramid[0]->pixel((int)floor(at.x()),(int)floor(at.y()))); } return result; }
27.900602
167
0.675159
e-foto
aa52f3f111e963b54ded8bd3b1c171624d6797d5
5,388
hpp
C++
headers/server_enum.hpp
DynasticSponge/Frederick2
410ad4a3ca43547d645248e13d27497e6c5b5f26
[ "MIT" ]
null
null
null
headers/server_enum.hpp
DynasticSponge/Frederick2
410ad4a3ca43547d645248e13d27497e6c5b5f26
[ "MIT" ]
null
null
null
headers/server_enum.hpp
DynasticSponge/Frederick2
410ad4a3ca43547d645248e13d27497e6c5b5f26
[ "MIT" ]
null
null
null
// // server_enum.hpp // ~~~~~~~~~~~~~~~ // // Author: Joseph Adomatis // Copyright (c) 2020 Joseph R Adomatis (joseph dot adomatis at gmail dot com) // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef SERVER_ENUM_HPP #define SERVER_ENUM_HPP #include "frederick2_namespace.hpp" enum class frederick2::httpEnums::httpMethod { ENUMERROR, CONNECT, DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT, TRACE }; enum class frederick2::httpEnums::httpProtocol { ENUMERROR, HTTP }; enum class frederick2::httpEnums::httpStatus { ENUMERROR = -1, /////////////////////////////////////////////////////////////////////////////// // INFORMATIONAL_RESPONSE /////////////////////////////////////////////////////////////////////////////// CONTINUE = 100, SWITCHING_PROTOCOLS = 101, PROCESSING = 102, EARLY_HINTS = 103, /////////////////////////////////////////////////////////////////////////////// // SUCCESS /////////////////////////////////////////////////////////////////////////////// OK = 200, CREATED = 201, ACCEPTED = 202, NON_AUTHORITATIVE_INFORMATION = 203, NO_CONTENT = 204, RESET_CONTENT = 205, PARTIAL_CONTENT = 206, MULTI_STATUS = 207, ALREADY_REPORTED = 208, IM_USED = 226, /////////////////////////////////////////////////////////////////////////////// // REDIRECTION /////////////////////////////////////////////////////////////////////////////// MULTIPLE_CHOICES = 300, MOVED_PERMANENTLY = 301, FOUND = 302, SEE_OTHER = 303, NOT_MODIFIED = 304, USE_PROXY = 305, SWITCH_PROXY = 306, TEMPORARY_REDIRECT = 307, PERMANENT_REDIRECT = 308, /////////////////////////////////////////////////////////////////////////////// // CLIENT ERRORS /////////////////////////////////////////////////////////////////////////////// BAD_REQUEST = 400, UNAUTHORIZED = 401, FORBIDDEN = 403, NOT_FOUND = 404, METHOD_NOT_ALLOWED = 405, NOT_ACCEPTABLE = 406, PROXY_AUTHENTICATION_REQUIRED = 407, REQUEST_TIMEOUT = 408, CONFLICT = 409, GONE = 410, LENGTH_REQUIRED = 411, PRECONDITION_FAILED = 412, PAYLOAD_TOO_LARGE = 413, URI_TOO_LONG = 414, UNSUPPORTED_MEDIA_TYPE = 415, RANGE_NOT_SATISFIABLE = 416, EXPECTATION_FAILED = 417, IM_A_TEAPOT = 418, MISDIRECTED_REQUEST = 421, UNPROCESSABLE_ENTITY = 422, LOCKED = 423, FAILED_DEPENDENCY = 424, TOO_EARLY = 425, UPGRADE_REQUIRED = 426, PRECONDITION_REQUIRED = 428, TOO_MANY_REQUESTS = 429, REQUEST_HEADER_FIELDS_TOO_LARGE = 431, UNAVAILABLE_FOR_LEGAL_REASONS = 451, /////////////////////////////////////////////////////////////////////////////// // SERVER ERRORS /////////////////////////////////////////////////////////////////////////////// INTERNAL_SERVER_ERROR = 500, NOT_IMPLEMENTED = 501, BAD_GATEWAY = 502, SERVICE_UNAVAILABLE = 503, GATEWAY_TIMEOUT = 504, HTTP_VERSION_NOT_SUPPORTED = 505, VARIANT_ALSO_NEGOTIATES = 506, INSUFFICIENT_STORAGE = 507, LOOP_DETECTED = 508, NOT_EXTENDED = 510, NETWORK_AUTHENTICATION_REQUIRED = 511 }; enum class frederick2::httpEnums::resourceType { ENUMERROR, DYNAMIC, FILESYSTEM, STATIC }; enum class frederick2::httpEnums::uriHostType { ENUMERROR, IPV4_ADDRESS, IPV6_ADDRESS, REGISTERED_NAME }; enum class frederick2::httpEnums::uriScheme { ENUMERROR, http, https }; class frederick2::httpEnums::converter { public: converter(); static std::string method2str(frederick2::httpEnums::httpMethod); static std::string protocol2str(frederick2::httpEnums::httpProtocol); static std::string status2str(frederick2::httpEnums::httpStatus); static frederick2::httpEnums::httpMethod str2method(const std::string&); static frederick2::httpEnums::httpProtocol str2protocol(const std::string&); static frederick2::httpEnums::uriScheme str2scheme(const std::string&); ~converter(); protected: private: /////////////////////////////////////////////////////////////////////////////// // Private Functions /////////////////////////////////////////////////////////////////////////////// static void initValidMethods(); static void initValidProtocols(); static void initValidSchemes(); static void initValidMethodStrings(); static void initValidProtocolStrings(); static void initValidStatusStrings(); /////////////////////////////////////////////////////////////////////////////// // Private Properties /////////////////////////////////////////////////////////////////////////////// static inline bool isInitVM = false; static inline bool isInitVP = false; static inline bool isInitVS = false; static inline bool isInitVMS = false; static inline bool isInitVPS = false; static inline bool isInitVSS = false; static inline strMAPmethod validMethods; static inline strMAPprotocol validProtocols; static inline strMAPscheme validSchemes; static inline methodMAPstr validMethodStrings; static inline protocolMAPstr validProtocolStrings; static inline statusMAPstr validStatusStrings; }; #endif
30.100559
119
0.522086
DynasticSponge
aa570e94789ea2eb8d8da55e79805a91cf5f1b09
20,497
cpp
C++
Assets/FrameCapturer-master/Plugin/fccore/Foundation/PixelFormat.cpp
Okashiou/VJx
491cc37e3d6eddd78e4c99d5f211c5e2b2d498f0
[ "MIT" ]
null
null
null
Assets/FrameCapturer-master/Plugin/fccore/Foundation/PixelFormat.cpp
Okashiou/VJx
491cc37e3d6eddd78e4c99d5f211c5e2b2d498f0
[ "MIT" ]
null
null
null
Assets/FrameCapturer-master/Plugin/fccore/Foundation/PixelFormat.cpp
Okashiou/VJx
491cc37e3d6eddd78e4c99d5f211c5e2b2d498f0
[ "MIT" ]
null
null
null
#include "pch.h" #include "fcInternal.h" #include "Buffer.h" #include "PixelFormat.h" #define fcEnableISPCKernel int fcGetPixelSize(fcPixelFormat format) { switch (format) { case fcPixelFormat_RGBAu8: return 4; case fcPixelFormat_RGBu8: return 3; case fcPixelFormat_RGu8: return 2; case fcPixelFormat_Ru8: return 1; case fcPixelFormat_RGBAf16: case fcPixelFormat_RGBAi16: return 8; case fcPixelFormat_RGBf16: case fcPixelFormat_RGBi16: return 6; case fcPixelFormat_RGf16: case fcPixelFormat_RGi16: return 4; case fcPixelFormat_Rf16: case fcPixelFormat_Ri16: return 2; case fcPixelFormat_RGBAf32: case fcPixelFormat_RGBAi32: return 16; case fcPixelFormat_RGBf32: case fcPixelFormat_RGBi32: return 12; case fcPixelFormat_RGf32: case fcPixelFormat_RGi32: return 8; case fcPixelFormat_Rf32: case fcPixelFormat_Ri32: return 4; } return 0; } void fcImageFlipY(void *image_, int width, int height, fcPixelFormat fmt) { size_t pitch = width * fcGetPixelSize(fmt); Buffer buf_((size_t)pitch); char *image = (char*)image_; char *buf = &buf_[0]; for (int y = 0; y < height / 2; ++y) { int iy = height - y - 1; memcpy(buf, image + (pitch*y), pitch); memcpy(image + (pitch*y), image + (pitch*iy), pitch); memcpy(image + (pitch*iy), buf, pitch); } } #ifdef fcEnableISPCKernel #include "ConvertKernel.h" void fcScaleArray(uint8_t *data, size_t size, float scale) { ispc::ScaleU8(data, (uint32_t)size, scale); } void fcScaleArray(uint16_t *data, size_t size, float scale) { ispc::ScaleI16(data, (uint32_t)size, scale); } void fcScaleArray(int32_t *data, size_t size, float scale) { ispc::ScaleI32(data, (uint32_t)size, scale); } void fcScaleArray(half *data, size_t size, float scale) { ispc::ScaleF16((int16_t*)data, (uint32_t)size, scale); } void fcScaleArray(float *data, size_t size, float scale) { ispc::ScaleF32(data, (uint32_t)size, scale); } const void* fcConvertPixelFormat_ISPC(void *dst, fcPixelFormat dstfmt, const void *src, fcPixelFormat srcfmt, size_t size_) { uint32_t size = (uint32_t)size_; switch (srcfmt) { case fcPixelFormat_RGBAu8: switch (dstfmt) { case fcPixelFormat_RGBAu8: return src; case fcPixelFormat_RGBu8: ispc::RGBAu8ToRGBu8((uint8_t*)dst, (uint8_t*)src, size); break; case fcPixelFormat_RGu8: ispc::RGBAu8ToRGu8((uint8_t*)dst, (uint8_t*)src, size); break; case fcPixelFormat_Ru8: ispc::RGBAu8ToRu8((uint8_t*)dst, (uint8_t*)src, size); break; case fcPixelFormat_RGBAf16: ispc::RGBAu8ToRGBAf16((int16_t*)dst, (uint8_t*)src, size); break; case fcPixelFormat_RGBf16: ispc::RGBAu8ToRGBf16((int16_t*)dst, (uint8_t*)src, size); break; case fcPixelFormat_RGf16: ispc::RGBAu8ToRGf16((int16_t*)dst, (uint8_t*)src, size); break; case fcPixelFormat_Rf16: ispc::RGBAu8ToRf16((int16_t*)dst, (uint8_t*)src, size); break; case fcPixelFormat_RGBAf32: ispc::RGBAu8ToRGBAf32((float*)dst, (uint8_t*)src, size); break; case fcPixelFormat_RGBf32: ispc::RGBAu8ToRGBf32((float*)dst, (uint8_t*)src, size); break; case fcPixelFormat_RGf32: ispc::RGBAu8ToRGf32((float*)dst, (uint8_t*)src, size); break; case fcPixelFormat_Rf32: ispc::RGBAu8ToRf32((float*)dst, (uint8_t*)src, size); break; } break; case fcPixelFormat_RGBu8: switch (dstfmt) { case fcPixelFormat_RGBAu8: ispc::RGBu8ToRGBAu8((uint8_t*)dst, (uint8_t*)src, size); break; case fcPixelFormat_RGBu8: return src; case fcPixelFormat_RGu8: ispc::RGBu8ToRGu8((uint8_t*)dst, (uint8_t*)src, size); break; case fcPixelFormat_Ru8: ispc::RGBu8ToRu8((uint8_t*)dst, (uint8_t*)src, size); break; case fcPixelFormat_RGBAf16: ispc::RGBu8ToRGBAf16((int16_t*)dst, (uint8_t*)src, size); break; case fcPixelFormat_RGBf16: ispc::RGBu8ToRGBf16((int16_t*)dst, (uint8_t*)src, size); break; case fcPixelFormat_RGf16: ispc::RGBu8ToRGf16((int16_t*)dst, (uint8_t*)src, size); break; case fcPixelFormat_Rf16: ispc::RGBu8ToRf16((int16_t*)dst, (uint8_t*)src, size); break; case fcPixelFormat_RGBAf32: ispc::RGBu8ToRGBAf32((float*)dst, (uint8_t*)src, size); break; case fcPixelFormat_RGBf32: ispc::RGBu8ToRGBf32((float*)dst, (uint8_t*)src, size); break; case fcPixelFormat_RGf32: ispc::RGBu8ToRGf32((float*)dst, (uint8_t*)src, size); break; case fcPixelFormat_Rf32: ispc::RGBu8ToRf32((float*)dst, (uint8_t*)src, size); break; } break; case fcPixelFormat_RGu8: switch (dstfmt) { case fcPixelFormat_RGBAu8: ispc::RGu8ToRGBAu8((uint8_t*)dst, (uint8_t*)src, size); break; case fcPixelFormat_RGBu8: ispc::RGu8ToRGBu8((uint8_t*)dst, (uint8_t*)src, size); break; case fcPixelFormat_RGu8: return src; case fcPixelFormat_Ru8: ispc::RGu8ToRu8((uint8_t*)dst, (uint8_t*)src, size); break; case fcPixelFormat_RGBAf16: ispc::RGu8ToRGBAf16((int16_t*)dst, (uint8_t*)src, size); break; case fcPixelFormat_RGBf16: ispc::RGu8ToRGBf16((int16_t*)dst, (uint8_t*)src, size); break; case fcPixelFormat_RGf16: ispc::RGu8ToRGf16((int16_t*)dst, (uint8_t*)src, size); break; case fcPixelFormat_Rf16: ispc::RGu8ToRf16((int16_t*)dst, (uint8_t*)src, size); break; case fcPixelFormat_RGBAf32: ispc::RGu8ToRGBAf32((float*)dst, (uint8_t*)src, size); break; case fcPixelFormat_RGBf32: ispc::RGu8ToRGBf32((float*)dst, (uint8_t*)src, size); break; case fcPixelFormat_RGf32: ispc::RGu8ToRGf32((float*)dst, (uint8_t*)src, size); break; case fcPixelFormat_Rf32: ispc::RGu8ToRf32((float*)dst, (uint8_t*)src, size); break; } break; case fcPixelFormat_Ru8: switch (dstfmt) { case fcPixelFormat_RGBAu8: ispc::Ru8ToRGBAu8((uint8_t*)dst, (uint8_t*)src, size); break; case fcPixelFormat_RGBu8: ispc::Ru8ToRGBu8((uint8_t*)dst, (uint8_t*)src, size); break; case fcPixelFormat_RGu8: ispc::Ru8ToRGu8((uint8_t*)dst, (uint8_t*)src, size); break; case fcPixelFormat_Ru8: return src; case fcPixelFormat_RGBAf16: ispc::Ru8ToRGBAf16((int16_t*)dst, (uint8_t*)src, size); break; case fcPixelFormat_RGBf16: ispc::Ru8ToRGBf16((int16_t*)dst, (uint8_t*)src, size); break; case fcPixelFormat_RGf16: ispc::Ru8ToRGf16((int16_t*)dst, (uint8_t*)src, size); break; case fcPixelFormat_Rf16: ispc::Ru8ToRf16((int16_t*)dst, (uint8_t*)src, size); break; case fcPixelFormat_RGBAf32: ispc::Ru8ToRGBAf32((float*)dst, (uint8_t*)src, size); break; case fcPixelFormat_RGBf32: ispc::Ru8ToRGBf32((float*)dst, (uint8_t*)src, size); break; case fcPixelFormat_RGf32: ispc::Ru8ToRGf32((float*)dst, (uint8_t*)src, size); break; case fcPixelFormat_Rf32: ispc::Ru8ToRf32((float*)dst, (uint8_t*)src, size); break; } break; case fcPixelFormat_RGBAf16: switch (dstfmt) { case fcPixelFormat_RGBAu8: ispc::RGBAf16ToRGBAu8((uint8_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGBu8: ispc::RGBAf16ToRGBu8((uint8_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGu8: ispc::RGBAf16ToRGu8((uint8_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_Ru8: ispc::RGBAf16ToRu8((uint8_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGBAi16: ispc::RGBAf16ToRGBAi16((uint16_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGBi16: ispc::RGBAf16ToRGBi16((uint16_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGi16: ispc::RGBAf16ToRGi16((uint16_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_Ri16: ispc::RGBAf16ToRi16((uint16_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGBAf16: return src; case fcPixelFormat_RGBf16: ispc::RGBAf16ToRGBf16((int16_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGf16: ispc::RGBAf16ToRGf16((int16_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_Rf16: ispc::RGBAf16ToRf16((int16_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGBAf32: ispc::RGBAf16ToRGBAf32((float*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGBf32: ispc::RGBAf16ToRGBf32((float*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGf32: ispc::RGBAf16ToRGf32((float*)dst, (int16_t*)src, size); break; case fcPixelFormat_Rf32: ispc::RGBAf16ToRf32((float*)dst, (int16_t*)src, size); break; } break; case fcPixelFormat_RGBf16: switch (dstfmt) { case fcPixelFormat_RGBAu8: ispc::RGBf16ToRGBAu8((uint8_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGBu8: ispc::RGBf16ToRGBu8((uint8_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGu8: ispc::RGBf16ToRGu8((uint8_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_Ru8: ispc::RGBf16ToRu8((uint8_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGBAi16: ispc::RGBf16ToRGBAi16((uint16_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGBi16: ispc::RGBf16ToRGBi16((uint16_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGi16: ispc::RGBf16ToRGi16((uint16_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_Ri16: ispc::RGBf16ToRi16((uint16_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGBAf16: ispc::RGBf16ToRGBAf16((int16_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGBf16: return src; case fcPixelFormat_RGf16: ispc::RGBf16ToRGf16((int16_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_Rf16: ispc::RGBf16ToRf16((int16_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGBAf32: ispc::RGBf16ToRGBAf32((float*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGBf32: ispc::RGBf16ToRGBf32((float*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGf32: ispc::RGBf16ToRGf32((float*)dst, (int16_t*)src, size); break; case fcPixelFormat_Rf32: ispc::RGBf16ToRf32((float*)dst, (int16_t*)src, size); break; } break; case fcPixelFormat_RGf16: switch (dstfmt) { case fcPixelFormat_RGBAu8: ispc::RGf16ToRGBAu8((uint8_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGBu8: ispc::RGf16ToRGBu8((uint8_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGu8: ispc::RGf16ToRGu8((uint8_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_Ru8: ispc::RGf16ToRu8((uint8_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGBAi16: ispc::RGf16ToRGBAi16((uint16_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGBi16: ispc::RGf16ToRGBi16((uint16_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGi16: ispc::RGf16ToRGi16((uint16_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_Ri16: ispc::RGf16ToRi16((uint16_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGBAf16: ispc::RGf16ToRGBAf16((int16_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGBf16: ispc::RGf16ToRGBf16((int16_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGf16: return src; case fcPixelFormat_Rf16: ispc::RGf16ToRf16((int16_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGBAf32: ispc::RGf16ToRGBAf32((float*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGBf32: ispc::RGf16ToRGBf32((float*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGf32: ispc::RGf16ToRGf32((float*)dst, (int16_t*)src, size); break; case fcPixelFormat_Rf32: ispc::RGf16ToRf32((float*)dst, (int16_t*)src, size); break; } break; case fcPixelFormat_Rf16: switch (dstfmt) { case fcPixelFormat_RGBAu8: ispc::Rf16ToRGBAu8((uint8_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGBu8: ispc::Rf16ToRGBu8((uint8_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGu8: ispc::Rf16ToRGu8((uint8_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_Ru8: ispc::Rf16ToRu8((uint8_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGBAi16: ispc::Rf16ToRGBAi16((uint16_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGBi16: ispc::Rf16ToRGBi16((uint16_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGi16: ispc::Rf16ToRGi16((uint16_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_Ri16: ispc::Rf16ToRi16((uint16_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGBAf16: ispc::Rf16ToRGBAf16((int16_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGBf16: ispc::Rf16ToRGBf16((int16_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGf16: ispc::Rf16ToRGf16((int16_t*)dst, (int16_t*)src, size); break; case fcPixelFormat_Rf16: return src; case fcPixelFormat_RGBAf32: ispc::Rf16ToRGBAf32((float*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGBf32: ispc::Rf16ToRGBf32((float*)dst, (int16_t*)src, size); break; case fcPixelFormat_RGf32: ispc::Rf16ToRGf32((float*)dst, (int16_t*)src, size); break; case fcPixelFormat_Rf32: ispc::Rf16ToRf32((float*)dst, (int16_t*)src, size); break; } break; case fcPixelFormat_RGBAf32: switch (dstfmt) { case fcPixelFormat_RGBAu8: ispc::RGBAf32ToRGBAu8((uint8_t*)dst, (float*)src, size); break; case fcPixelFormat_RGBu8: ispc::RGBAf32ToRGBu8((uint8_t*)dst, (float*)src, size); break; case fcPixelFormat_RGu8: ispc::RGBAf32ToRGu8((uint8_t*)dst, (float*)src, size); break; case fcPixelFormat_Ru8: ispc::RGBAf32ToRu8((uint8_t*)dst, (float*)src, size); break; case fcPixelFormat_RGBAi16: ispc::RGBAf32ToRGBAi16((uint16_t*)dst, (float*)src, size); break; case fcPixelFormat_RGBi16: ispc::RGBAf32ToRGBi16((uint16_t*)dst, (float*)src, size); break; case fcPixelFormat_RGi16: ispc::RGBAf32ToRGi16((uint16_t*)dst, (float*)src, size); break; case fcPixelFormat_Ri16: ispc::RGBAf32ToRi16((uint16_t*)dst, (float*)src, size); break; case fcPixelFormat_RGBAf16: ispc::RGBAf32ToRGBAf16((int16_t*)dst, (float*)src, size); break; case fcPixelFormat_RGBf16: ispc::RGBAf32ToRGBf16((int16_t*)dst, (float*)src, size); break; case fcPixelFormat_RGf16: ispc::RGBAf32ToRGf16((int16_t*)dst, (float*)src, size); break; case fcPixelFormat_Rf16: ispc::RGBAf32ToRf16((int16_t*)dst, (float*)src, size); break; case fcPixelFormat_RGBAf32: return src; case fcPixelFormat_RGBf32: ispc::RGBAf32ToRGBf32((float*)dst, (float*)src, size); break; case fcPixelFormat_RGf32: ispc::RGBAf32ToRGf32((float*)dst, (float*)src, size); break; case fcPixelFormat_Rf32: ispc::RGBAf32ToRf32((float*)dst, (float*)src, size); break; } break; case fcPixelFormat_RGBf32: switch (dstfmt) { case fcPixelFormat_RGBAu8: ispc::RGBf32ToRGBAu8((uint8_t*)dst, (float*)src, size); break; case fcPixelFormat_RGBu8: ispc::RGBf32ToRGBu8((uint8_t*)dst, (float*)src, size); break; case fcPixelFormat_RGu8: ispc::RGBf32ToRGu8((uint8_t*)dst, (float*)src, size); break; case fcPixelFormat_Ru8: ispc::RGBf32ToRu8((uint8_t*)dst, (float*)src, size); break; case fcPixelFormat_RGBAi16: ispc::RGBf32ToRGBAi16((uint16_t*)dst, (float*)src, size); break; case fcPixelFormat_RGBi16: ispc::RGBf32ToRGBi16((uint16_t*)dst, (float*)src, size); break; case fcPixelFormat_RGi16: ispc::RGBf32ToRGi16((uint16_t*)dst, (float*)src, size); break; case fcPixelFormat_Ri16: ispc::RGBf32ToRi16((uint16_t*)dst, (float*)src, size); break; case fcPixelFormat_RGBAf16: ispc::RGBf32ToRGBAf16((int16_t*)dst, (float*)src, size); break; case fcPixelFormat_RGBf16: ispc::RGBf32ToRGBf16((int16_t*)dst, (float*)src, size); break; case fcPixelFormat_RGf16: ispc::RGBf32ToRGf16((int16_t*)dst, (float*)src, size); break; case fcPixelFormat_Rf16: ispc::RGBf32ToRf16((int16_t*)dst, (float*)src, size); break; case fcPixelFormat_RGBAf32: ispc::RGBf32ToRGBAf32((float*)dst, (float*)src, size); break; case fcPixelFormat_RGBf32: return src; case fcPixelFormat_RGf32: ispc::RGBf32ToRGf32((float*)dst, (float*)src, size); break; case fcPixelFormat_Rf32: ispc::RGBf32ToRf32((float*)dst, (float*)src, size); break; } break; case fcPixelFormat_RGf32: switch (dstfmt) { case fcPixelFormat_RGBAu8: ispc::RGf32ToRGBAu8((uint8_t*)dst, (float*)src, size); break; case fcPixelFormat_RGBu8: ispc::RGf32ToRGBu8((uint8_t*)dst, (float*)src, size); break; case fcPixelFormat_RGu8: ispc::RGf32ToRGu8((uint8_t*)dst, (float*)src, size); break; case fcPixelFormat_Ru8: ispc::RGf32ToRu8((uint8_t*)dst, (float*)src, size); break; case fcPixelFormat_RGBAi16: ispc::RGf32ToRGBAi16((uint16_t*)dst, (float*)src, size); break; case fcPixelFormat_RGBi16: ispc::RGf32ToRGBi16((uint16_t*)dst, (float*)src, size); break; case fcPixelFormat_RGi16: ispc::RGf32ToRGi16((uint16_t*)dst, (float*)src, size); break; case fcPixelFormat_Ri16: ispc::RGf32ToRi16((uint16_t*)dst, (float*)src, size); break; case fcPixelFormat_RGBAf16: ispc::RGf32ToRGBAf16((int16_t*)dst, (float*)src, size); break; case fcPixelFormat_RGBf16: ispc::RGf32ToRGBf16((int16_t*)dst, (float*)src, size); break; case fcPixelFormat_RGf16: ispc::RGf32ToRGf16((int16_t*)dst, (float*)src, size); break; case fcPixelFormat_Rf16: ispc::RGf32ToRf16((int16_t*)dst, (float*)src, size); break; case fcPixelFormat_RGBAf32: ispc::RGf32ToRGBAf32((float*)dst, (float*)src, size); break; case fcPixelFormat_RGBf32: ispc::RGf32ToRGBf32((float*)dst, (float*)src, size); break; case fcPixelFormat_RGf32: return src; case fcPixelFormat_Rf32: ispc::RGf32ToRf32((float*)dst, (float*)src, size); break; } break; case fcPixelFormat_Rf32: switch (dstfmt) { case fcPixelFormat_RGBAu8: ispc::Rf32ToRGBAu8((uint8_t*)dst, (float*)src, size); break; case fcPixelFormat_RGBu8: ispc::Rf32ToRGBu8((uint8_t*)dst, (float*)src, size); break; case fcPixelFormat_RGu8: ispc::Rf32ToRGu8((uint8_t*)dst, (float*)src, size); break; case fcPixelFormat_Ru8: ispc::Rf32ToRu8((uint8_t*)dst, (float*)src, size); break; case fcPixelFormat_RGBAi16: ispc::Rf32ToRGBAi16((uint16_t*)dst, (float*)src, size); break; case fcPixelFormat_RGBi16: ispc::Rf32ToRGBi16((uint16_t*)dst, (float*)src, size); break; case fcPixelFormat_RGi16: ispc::Rf32ToRGi16((uint16_t*)dst, (float*)src, size); break; case fcPixelFormat_Ri16: ispc::Rf32ToRi16((uint16_t*)dst, (float*)src, size); break; case fcPixelFormat_RGBAf16: ispc::Rf32ToRGBAf16((int16_t*)dst, (float*)src, size); break; case fcPixelFormat_RGBf16: ispc::Rf32ToRGBf16((int16_t*)dst, (float*)src, size); break; case fcPixelFormat_RGf16: ispc::Rf32ToRGf16((int16_t*)dst, (float*)src, size); break; case fcPixelFormat_Rf16: ispc::Rf32ToRf16((int16_t*)dst, (float*)src, size); break; case fcPixelFormat_RGBAf32: ispc::Rf32ToRGBAf32((float*)dst, (float*)src, size); break; case fcPixelFormat_RGBf32: ispc::Rf32ToRGBf32((float*)dst, (float*)src, size); break; case fcPixelFormat_RGf32: ispc::Rf32ToRGf32((float*)dst, (float*)src, size); break; case fcPixelFormat_Rf32: return src; } break; } return dst; } fcAPI const void* fcConvertPixelFormat(void *dst, fcPixelFormat dstfmt, const void *src, fcPixelFormat srcfmt, size_t size) { return fcConvertPixelFormat_ISPC(dst, dstfmt, src, srcfmt, size); } void fcF32ToU8Samples(uint8_t *dst, const float *src, size_t size) { ispc::F32ToU8Samples(dst, src, (uint32_t)size); } void fcF32ToI16Samples(int16_t *dst, const float *src, size_t size) { ispc::F32ToI16Samples(dst, src, (uint32_t)size); } void fcF32ToI24Samples(uint8_t *dst, const float *src, size_t size) { ispc::F32ToI24Samples(dst, src, (uint32_t)size); } void fcF32ToI32Samples(int32_t *dst, const float *src, size_t size) { ispc::F32ToI32Samples(dst, src, (uint32_t)size); } void fcF32ToI32ScaleSamples(int32_t *dst, const float *src, size_t size, float scale) { ispc::F32ToI32ScaleSamples(dst, src, (uint32_t)size, scale); } #endif // fcEnableISPCKernel
62.874233
123
0.690784
Okashiou
aa5b53057aedea3d92c9887b302923faca18e753
25,676
cpp
C++
Editor/src/gdeditor.cpp
guilmont/GDManager
dedb0b6c5e1c55886def5360837cbce2485c0d78
[ "Apache-2.0" ]
null
null
null
Editor/src/gdeditor.cpp
guilmont/GDManager
dedb0b6c5e1c55886def5360837cbce2485c0d78
[ "Apache-2.0" ]
null
null
null
Editor/src/gdeditor.cpp
guilmont/GDManager
dedb0b6c5e1c55886def5360837cbce2485c0d78
[ "Apache-2.0" ]
null
null
null
#include "gdeditor.h" static std::string type2Label(GDM::Type type) { switch (type) { case GDM::Type::GROUP: return "GROUP"; case GDM::Type::INT32: return "INT32"; case GDM::Type::INT64: return "INT64"; case GDM::Type::UINT8: return "UINT8"; case GDM::Type::UINT16: return "UINT16"; case GDM::Type::UINT32: return "UINT32"; case GDM::Type::UINT64: return "UINT64"; case GDM::Type::FLOAT: return "FLOAT"; case GDM::Type::DOUBLE: return "DOUBLE"; default: GRender::pout("Type unkown"); assert(false); return ""; } } static GDM::Type label2Type(const std::string &label) { if (label.compare("GROUP") == 0) return GDM::Type::GROUP; else if (label.compare("INT32") == 0) return GDM::Type::INT32; else if (label.compare("INT64") == 0) return GDM::Type::INT64; else if (label.compare("UINT8") == 0) return GDM::Type::UINT8; else if (label.compare("UINT16") == 0) return GDM::Type::UINT16; else if (label.compare("UINT32") == 0) return GDM::Type::UINT32; else if (label.compare("UINT64") == 0) return GDM::Type::UINT64; else if (label.compare("FLOAT") == 0) return GDM::Type::FLOAT; else if (label.compare("DOUBLE") == 0) return GDM::Type::DOUBLE; else { GRender::pout("Type unkown"); assert(false); return GDM::Type::NONE; } } static bool SliderU64(const char* label, uint64_t* val, uint64_t low, uint64_t high) { return ImGui::SliderScalar(label, ImGuiDataType_U64, val, &low, &high); } template <typename TP> static void rewrite(const char *buf, uint64_t pos, uint8_t *ptr) { TP val = static_cast<TP>(std::stod(buf)); uint8_t *vv = reinterpret_cast<uint8_t *>(&val); std::copy(vv, vv + sizeof(TP), ptr + pos * sizeof(TP)); } template <typename TP> static void lineFunction(GDM::Data* data, int selected, uint64_t id) { GDM::Shape sp = data->getShape(); const TP* ptr = data->getArray<TP>(); uint64_t N = selected == 0 ? sp.width : sp.height; std::vector<TP> vecX(N), vecY(N); for (uint64_t k = 0; k < N; k++) { vecX[k] = TP(k); vecY[k] = selected == 0 ? ptr[id * sp.width + k] : ptr[k * sp.width + id]; } ImPlot::PlotLine("function",vecX.data(), vecY.data(), int(N)); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// GDEditor::GDEditor(void) { fs::current_path(INSTALL_PATH); GRender::pout("Welcome to my GDEditor!!"); initialize("GDEditor", 1200, 800, "assets/GDEditor/layout.ini"); } GDEditor::~GDEditor(void) {} void GDEditor::onUserUpdate(float deltaTime) { if (close_file.size() > 0) { vFile.erase(close_file); close_file = ""; if (vFile.size() > 0) currentFile = &(vFile.begin()->second); else currentFile = nullptr; currentObj = nullptr; addObj.view = false; addObj.group = nullptr; } bool ctrl = (keyboard[GKey::LEFT_CONTROL] == GEvent::PRESS) || (keyboard[GKey::RIGHT_CONTROL] == GEvent::PRESS), shift = (keyboard[GKey::LEFT_SHIFT] == GEvent::PRESS) || (keyboard[GKey::RIGHT_SHIFT] == GEvent::PRESS), I = keyboard['I'] == GEvent::PRESS, P = keyboard['P'] == GEvent::PRESS, N = keyboard['N'] == GEvent::PRESS, O = keyboard['O'] == GEvent::PRESS, S = keyboard['S'] == GEvent::PRESS; if ((ctrl & shift) & I) view_imguidemo = true; if ((ctrl & shift) & P) view_implotdemo = true; if (ctrl & N) dialog.createDialog(GDialog::SAVE, "New file...", {"gdm", "gd"}, this, [](const fs::path &path, void *ptr) -> void { reinterpret_cast<GDEditor *>(ptr)->openFile(path); }); if (ctrl & O) dialog.createDialog(GDialog::OPEN, "Open file...", {"gdm", "gd"}, this, [](const fs::path &path, void *ptr) -> void { reinterpret_cast<GDEditor *>(ptr)->openFile(path); }); } void GDEditor::ImGuiLayer(void) { if (view_imguidemo) ImGui::ShowDemoWindow(&view_imguidemo); if (view_implotdemo) ImPlot::ShowDemoWindow(&view_implotdemo); if (plotPointer) (this->*plotWindow)(); if (addObj.view) addObject(addObj.group); if (currentFile) { treeViewWindow(); detailWindow(); } } void GDEditor::ImGuiMenuLayer(void) { if (ImGui::BeginMenu("File")) { if (ImGui::MenuItem("New file...", "Ctrl+N")) dialog.createDialog(GDialog::SAVE, "New file...", {"gdm", "gd"}, this, [](const fs::path &path, void *ptr) -> void { reinterpret_cast<GDEditor *>(ptr)->openFile(path); }); if (ImGui::MenuItem("Open...", "Ctrl+O")) dialog.createDialog(GDialog::OPEN, "Open file...", {"gdm", "gd"}, this, [](const fs::path &path, void *ptr) -> void { reinterpret_cast<GDEditor *>(ptr)->openFile(path); }); if (ImGui::MenuItem("Save")) saveFile(); if (ImGui::MenuItem("Exit")) closeApp(); ImGui::EndMenu(); } if (ImGui::BeginMenu("Tools")) { if (ImGui::MenuItem("Show mailbox")) mailbox.setActive(); if (ImGui::MenuItem("Release memory")) for (auto &[name, arq] : vFile) releaseMemory(&arq); ImGui::EndMenu(); } // file-menu } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// void GDEditor::recursiveTreeLoop(GDM::Group *group, ImGuiTreeNodeFlags nodeFlags) { std::string remove = ""; for (auto &[label, obj] : group->children()) { ImGui::PushID(label.c_str()); if (obj->getType() == GDM::Type::GROUP) { ImGui::SetNextTreeNodeOpen(false, ImGuiCond_Once); // it will run the first time bool openTree = ImGui::TreeNodeEx(label.c_str(), nodeFlags); float fSize = ImGui::GetWindowContentRegionWidth() - 8.5f * ImGui::GetFontSize(); ImGui::SameLine(fSize); if (ImGui::Button("Details", {3.5f * ImGui::GetFontSize(), 0})) currentObj = obj; ImGui::SameLine(); if (ImGui::Button("+", {2.0f * ImGui::GetFontSize(), 0})) { addObj.view = true; addObj.group = reinterpret_cast<GDM::Group *>(obj); } ImGui::SameLine(); if (ImGui::Button("-", {2.0f * ImGui::GetFontSize(), 0})) remove = label; if (openTree) { recursiveTreeLoop(reinterpret_cast<GDM::Group *>(obj), nodeFlags); ImGui::TreePop(); } } else { bool selected = false; if (ImGui::Selectable(label.c_str(), &selected)) currentObj = obj; } ImGui::PopID(); } // loop-children // Removing group if necessary if (remove.size() > 0) group->remove(remove); } void GDEditor::treeViewWindow(void) { const ImVec2 workpos = ImGui::GetMainViewport()->WorkPos; ImGui::SetNextWindowPos({workpos.x + 20, workpos.y + 40}, ImGuiCond_FirstUseEver); ImGui::SetNextWindowSize({400, 700}, ImGuiCond_FirstUseEver); ImGui::Begin("Tree view"); if (ImGui::BeginTabBar("MyTabBar")) { for (auto &[label, arq] : vFile) { const std::string &name = label.filename().string(); if (ImGui::BeginTabItem(name.c_str())) { currentFile = &arq; ImGui::EndTabItem(); } } ImGui::EndTabBar(); } ImGuiTreeNodeFlags nodeFlags = ImGuiTreeNodeFlags_None; nodeFlags |= ImGuiTreeNodeFlags_DefaultOpen; nodeFlags |= ImGuiTreeNodeFlags_Framed; nodeFlags |= ImGuiTreeNodeFlags_FramePadding; nodeFlags |= ImGuiTreeNodeFlags_SpanAvailWidth; nodeFlags |= ImGuiTreeNodeFlags_AllowItemOverlap; ImGui::PushID(currentFile->getLabel().c_str()); std::string name = currentFile->getFilePath().filename().string(); bool openTree = ImGui::TreeNodeEx(name.c_str(), nodeFlags); float fSize = ImGui::GetWindowContentRegionWidth() - 10.0f * ImGui::GetFontSize(); ImGui::SameLine(fSize); if (ImGui::Button("+", {2.0f * ImGui::GetFontSize(), 0})) { addObj.view = true; addObj.group = currentFile; } ImGui::SameLine(); if (ImGui::Button("Details", {3.5f * ImGui::GetFontSize(), 0})) currentObj = currentFile; ImGui::SameLine(); if (ImGui::Button("Close", { 3.5f * ImGui::GetFontSize(), 0 })) { plotPointer = nullptr; plotWindow = nullptr; close_file = currentFile->getFilePath().string(); mailbox.createInfo("Closing file " + close_file); } if (openTree) { recursiveTreeLoop(reinterpret_cast<GDM::Group *>(currentFile), nodeFlags); ImGui::TreePop(); } ImGui::PopID(); ImGui::End(); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// void GDEditor::detailWindow(void) { const ImVec2 workpos = ImGui::GetMainViewport()->WorkPos; ImGui::SetNextWindowPos({workpos.x + 450, workpos.y + 40}, ImGuiCond_FirstUseEver); ImGui::SetNextWindowSize({700, 700}, ImGuiCond_FirstUseEver); ImGui::Begin("Details"); if (currentObj == nullptr) { ImGui::Text("No object selected"); ImGui::End(); return; } auto text = [&](const std::string &title, const std::string &txt) -> void { fonts.text(title.c_str(), "bold"); ImGui::SameLine(); ImGui::Text(txt.c_str()); }; fonts.text("Label:", "bold"); ImGui::SameLine(); static char locLabel[GDM::MAX_LABEL_SIZE] = {0x00}; sprintf(locLabel, "%s", currentObj->getLabel().c_str()); if (ImGui::InputText("##label", locLabel, GDM::MAX_LABEL_SIZE, ImGuiInputTextFlags_EnterReturnsTrue)) currentObj->rename(locLabel); if (currentObj->parent) { std::string par = ""; GDM::Object *obj = currentObj; while (obj->parent) { obj = obj->parent; par = "/" + obj->getLabel() + par; } text("Path:", par.c_str()); } text("Type:", type2Label(currentObj->getType()).c_str()); if (currentObj->getType() == GDM::Type::GROUP) text("Number of children:", std::to_string(reinterpret_cast<GDM::Group *>(currentObj)->getNumChildren())); else { GDM::Data *dt = reinterpret_cast<GDM::Data *>(currentObj); GDM::Shape shape = dt->getShape(); text("Shape:", "{ " + std::to_string(shape.height) + ", " + std::to_string(shape.width) + " }"); } ImGui::Spacing(); if (ImGui::Button("Delete")) { GDM::Group *ptr = currentObj->parent; ptr->remove(currentObj->getLabel()); currentObj = ptr; ImGui::End(); return; } ImGui::Spacing(); ImGui::Spacing(); ImGui::Separator(); ImGui::Spacing(); ImGui::Spacing(); ////////////////////////////////////////////////////////// // All types have descriptions GDM::Description &description = currentObj->descriptions(); fonts.text("Description:", "bold"); ImGui::SameLine(); if (ImGui::Button("Add")) { description["---"] = "---"; } if (description.size() > 0) { // Creatign table to display description ImGuiTableFlags flags = ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY | ImGuiTableFlags_ScrollX | ImGuiTableFlags_Borders; if (ImGui::BeginTable("descriptionTable", 3, flags, {0, std::min<float>(256, 1.5f * (description.size() + 1) * ImGui::GetFontSize())})) { // Header ImGui::TableSetupColumn("Label"); ImGui::TableSetupColumn("Description"); ImGui::TableHeadersRow(); // Main body std::string remove = "", add = ""; for (auto &[label, desc] : description) { ImGui::TableNextRow(); ImGui::PushID(label.c_str()); ImGui::TableSetColumnIndex(0); static char loc1[GDM::MAX_LABEL_SIZE]; sprintf(loc1, "%s", label.c_str()); ImGui::SetNextItemWidth(10.0f * ImGui::GetFontSize()); if (ImGui::InputText("##label", loc1, GDM::MAX_LABEL_SIZE, ImGuiInputTextFlags_EnterReturnsTrue)) { add = std::string(loc1); remove = label; } ImGui::TableSetColumnIndex(1); static char loc2[512] = {0x00}; sprintf(loc2, "%s", desc.c_str()); ImGui::SetNextItemWidth(ImGui::GetWindowWidth() - 18.0f * ImGui::GetFontSize()); if (ImGui::InputText("##desc", loc2, 512, ImGuiInputTextFlags_EnterReturnsTrue)) description[label] = std::string(loc2); ImGui::TableSetColumnIndex(2); if (ImGui::Button("Remove")) remove = label; ImGui::PopID(); } // Removing description if necessary if (add.size() > 0) description[add] = description[remove]; if (remove.size() > 0) description.erase(remove); ImGui::EndTable(); } } if (currentObj->getType() == GDM::Type::GROUP) { ImGui::End(); return; } ////////////////////////////////////////////////////////// // We have a data type, so we should display its values if demanded ImGui::Spacing(); ImGui::Spacing(); ImGui::Separator(); ImGui::Spacing(); ImGui::Spacing(); GDM::Data *dt = reinterpret_cast<GDM::Data *>(currentObj); fonts.text("Value:", "bold"); if (dt->getSizeBytes() > sizeof(uint64_t)) { ImGui::SameLine(); if (ImGui::Button(dt->isLoaded() ? "Hide" : "View")) { if (dt->isLoaded()) dt->release(); else dt->load(); // this will load data } } if (dt->isLoaded()) { if (dt->getSizeBytes() > sizeof(uint64_t)) { ImGui::SameLine(); if (ImGui::Button("Heatmap")) { plotPointer = dt; plotWindow = &GDEditor::plotHeatmap; } ImGui::SameLine(); if (ImGui::Button("Line plot")) { plotPointer = dt; plotWindow = &GDEditor::plotLines; } } } else { ImGui::End(); return; } GDM::Shape shape = dt->getShape(); GDM::Type type = dt->getType(); uint8_t *ptr = dt->getRawBuffer(); // This is the raw buffer pointer uint64_t maxRows = std::min<uint64_t>(32, shape.height); uint64_t maxCols = std::min<uint64_t>(32, shape.width); static uint64_t rowZero = 0, rowTop = maxRows; static uint64_t colZero = 0, colTop = maxCols; if (maxRows < shape.height) { int64_t val = static_cast<int64_t>(rowZero); SliderU64("Rows", &rowZero, 0, shape.height - 32); rowZero = std::min(rowZero, shape.height); rowTop = std::min(rowZero + 32, shape.height); } else { rowZero = 0; rowTop = maxRows; } if (maxCols < shape.width) { SliderU64("Cols", &colZero, 0, shape.width - 32); colZero = std::min(colZero, shape.width); colTop = std::min(colZero + 32, shape.width); } else { colZero = 0; colTop = maxCols; } ImGuiTableFlags flags = ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY | ImGuiTableFlags_ScrollX | ImGuiTableFlags_Borders | ImGuiTableFlags_NoHostExtendX | ImGuiTableFlags_NoHostExtendY; if (ImGui::BeginTable("dataTable", int(maxCols + 1), flags)) { ImGui::TableNextRow(); for (uint64_t column = 1; column <= maxCols; column++) { ImGui::TableSetColumnIndex(int(column)); fonts.text(std::to_string(colZero + column - 1).c_str(), "bold"); } // Main body for (uint64_t row = rowZero; row < rowTop; row++) { ImGui::TableNextRow(); ImGui::TableSetColumnIndex(0); fonts.text(std::to_string(row).c_str(), "bold"); for (uint64_t column = colZero; column < colTop; column++) { uint64_t ct = row * shape.width + column; ImGui::TableSetColumnIndex(int(column + 1 - colZero)); char buf[64] = {0x00}; switch (type) { case GDM::Type::INT32: sprintf(buf, "%d", reinterpret_cast<int32_t *>(ptr)[ct]); break; case GDM::Type::INT64: sprintf(buf, "%jd", reinterpret_cast<int64_t *>(ptr)[ct]); break; case GDM::Type::UINT8: sprintf(buf, "%u", reinterpret_cast<uint8_t *>(ptr)[ct]); break; case GDM::Type::UINT16: sprintf(buf, "%u", reinterpret_cast<uint16_t *>(ptr)[ct]); break; case GDM::Type::UINT32: sprintf(buf, "%u", reinterpret_cast<uint32_t *>(ptr)[ct]); break; case GDM::Type::UINT64: sprintf(buf, "%ju", reinterpret_cast<uint64_t *>(ptr)[ct]); break; case GDM::Type::FLOAT: sprintf(buf, "%.6f", reinterpret_cast<float *>(ptr)[ct]); break; case GDM::Type::DOUBLE: sprintf(buf, "%.6lf", reinterpret_cast<double *>(ptr)[ct]); break; } ImGui::PushID(std::to_string(row * shape.width + column).c_str()); ImGui::SetNextItemWidth(5.0f * ImGui::GetFontSize()); if (ImGui::InputText("##decimal", buf, 64, ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_EnterReturnsTrue)) { switch (type) { case GDM::Type::INT32: rewrite<int32_t>(buf, ct, ptr); break; case GDM::Type::INT64: rewrite<int64_t>(buf, ct, ptr); break; case GDM::Type::UINT8: rewrite<uint8_t>(buf, ct, ptr); break; case GDM::Type::UINT16: rewrite<uint16_t>(buf, ct, ptr); break; case GDM::Type::UINT32: rewrite<uint32_t>(buf, ct, ptr); break; case GDM::Type::UINT64: rewrite<uint64_t>(buf, ct, ptr); break; case GDM::Type::FLOAT: rewrite<float>(buf, ct, ptr); break; case GDM::Type::DOUBLE: rewrite<double>(buf, ct, ptr); break; } } ImGui::PopID(); // Seeking next element in array ct++; } } ImGui::EndTable(); } ImGui::End(); } void GDEditor::plotHeatmap(void) { const ImVec2 workpos = ImGui::GetMainViewport()->WorkPos; ImGui::SetNextWindowPos({ workpos.x + 40, workpos.y + 40}, ImGuiCond_FirstUseEver); ImGui::SetNextWindowSize({ 700, 700 }, ImGuiCond_FirstUseEver); bool is_open = true; // So we can close this window from this function ImGui::Begin("Plots", &is_open); static float scale_min = 0; static float scale_max = 1.0f; static ImPlotColormap map = ImPlotColormap_Viridis; if (ImPlot::ColormapButton(ImPlot::GetColormapName(map), ImVec2(225, 0), map)) { map = (map + 1) % ImPlot::GetColormapCount(); ImPlot::BustColorCache("##Heatmap1"); } ImGui::SameLine(); ImGui::LabelText("##Colormap Index", "%s", "Change Colormap"); ImGui::SetNextItemWidth(225); ImGui::DragFloatRange2("Min / Max", &scale_min, &scale_max, 0.01f, -20, 20); GDM::Shape sp = plotPointer->getShape(); const uint8_t* ptr = plotPointer->getRawBuffer(); float ratio = float(sp.height) / float(sp.width); float width = 0.8f * ImGui::GetContentRegionAvailWidth(), height = width * ratio; ImPlot::PushColormap(map); if (ImPlot::BeginPlot("##Heatmap1", NULL, NULL, {width, height }, ImPlotFlags_NoLegend)) { int width = static_cast<int>(sp.width), height = static_cast<int>(sp.height); switch (plotPointer->getType()) { case GDM::Type::INT32: ImPlot::PlotHeatmap("heat", reinterpret_cast<const ImS32*>(ptr), height, width, scale_min, scale_max, NULL); break; case GDM::Type::INT64: ImPlot::PlotHeatmap("heat", reinterpret_cast<const ImS64*>(ptr), height, width, scale_min, scale_max, NULL); break; case GDM::Type::UINT8: ImPlot::PlotHeatmap("heat", reinterpret_cast<const ImU8*>(ptr), height, width, scale_min, scale_max, NULL); break; case GDM::Type::UINT16: ImPlot::PlotHeatmap("heat", reinterpret_cast<const ImU16*>(ptr), height, width, scale_min, scale_max, NULL); break; case GDM::Type::UINT32: ImPlot::PlotHeatmap("heat", reinterpret_cast<const ImU32*>(ptr), height, width, scale_min, scale_max, NULL); break; case GDM::Type::UINT64: ImPlot::PlotHeatmap("heat", reinterpret_cast<const ImU64*>(ptr), height, width, scale_min, scale_max, NULL); break; case GDM::Type::FLOAT: ImPlot::PlotHeatmap("heat", reinterpret_cast<const float*>(ptr), height, width, scale_min, scale_max, NULL); break; case GDM::Type::DOUBLE: ImPlot::PlotHeatmap("heat", reinterpret_cast<const double*>(ptr), height, width, scale_min, scale_max, NULL); break; default: throw "Type not recognized!!"; break; } ImPlot::EndPlot(); } ImGui::SameLine(); ImPlot::ColormapScale("##HeatScale", scale_min, scale_max, { 0.15f * width, height }); ImGui::End(); if (!is_open) plotPointer = nullptr; } void GDEditor::plotLines(void) { const ImVec2 workpos = ImGui::GetMainViewport()->WorkPos; ImGui::SetNextWindowPos({ workpos.x + 40, workpos.y + 40 }, ImGuiCond_FirstUseEver); ImGui::SetNextWindowSize({ 700, 700 }, ImGuiCond_FirstUseEver); GDM::Shape sp = plotPointer->getShape(); bool is_open = true; // So we can close this window from this function ImGui::Begin("Plots", &is_open); static int selected = 0; ImGui::RadioButton("Rows", &selected, 0); ImGui::SameLine(); ImGui::RadioButton("Columns", &selected, 1); static int id = 0; ImGui::DragInt("ID", &id, 1.0f, 0, selected == 0 ? int(sp.height)-1 : int(sp.width)-1); const char* labx = "Index"; char laby[64] = { 0 }; sprintf(laby, "%s %d", (selected == 0 ? "Row" : "Column"), id); float width = 0.95f * ImGui::GetContentRegionAvailWidth(), height = 0.7f * width; if (ImPlot::BeginPlot(plotPointer->getLabel().c_str(), labx, laby, { width, height }, ImPlotFlags_NoLegend)) { ImPlot::SetNextMarkerStyle(ImPlotMarker_Circle); switch (plotPointer->getType()) { case GDM::Type::INT32: lineFunction<ImS32>(plotPointer, selected, id); break; case GDM::Type::INT64: lineFunction<ImS64>(plotPointer, selected, id); break; case GDM::Type::UINT8: lineFunction<ImU8>(plotPointer, selected, id); break; case GDM::Type::UINT16: lineFunction<ImU16>(plotPointer, selected, id); break; case GDM::Type::UINT32: lineFunction<ImU32>(plotPointer, selected, id); break; case GDM::Type::UINT64: lineFunction<ImU64>(plotPointer, selected, id); break; case GDM::Type::FLOAT: lineFunction<float>(plotPointer, selected, id); break; case GDM::Type::DOUBLE: lineFunction<double>(plotPointer, selected, id); break; default: throw "Type not recognized!!"; break; } ImPlot::EndPlot(); } ImGui::PopID(); ImGui::End(); if (!is_open) plotPointer = nullptr; } void GDEditor::addObject(GDM::Group *group) { ImGui::Begin("Add object", &addObj.view); fonts.text("Label:", "bold"); ImGui::SameLine(); bool check = false; static char buf[GDM::MAX_LABEL_SIZE] = {0x00}; if (ImGui::InputText("##addLabel", buf, GDM::MAX_LABEL_SIZE, ImGuiInputTextFlags_EnterReturnsTrue)) check = true; const char *items[] = {"GROUP", "INT32", "INT64", "UINT8", "UINT16", "UINT32", "UINT64", "FLOAT", "DOUBLE"}; static int item_current_idx = 0; // Here we store our selection data as an index. const char *combo_label = items[item_current_idx]; // Label to preview before opening the combo (technically it could be anything) fonts.text("Type:", "bold"); ImGui::SameLine(); if (ImGui::BeginCombo("##type", combo_label)) { for (int n = 0; n < IM_ARRAYSIZE(items); n++) { const bool is_selected = (item_current_idx == n); if (ImGui::Selectable(items[n], is_selected)) item_current_idx = n; // Set the initial focus when opening the combo (scrolling + keyboard navigation focus) if (is_selected) ImGui::SetItemDefaultFocus(); } ImGui::EndCombo(); } GDM::Type type = label2Type(items[item_current_idx]); static int32_t dim[2] = {1, 1}; if (type != GDM::Type::GROUP) { // Determinining fonts.text("Shape:", "bold"); ImGui::SameLine(); ImGui::DragInt2("##shape", dim, 0.1f, 1); } if (ImGui::Button("Add") || check) { if (type == GDM::Type::GROUP) addObj.group->addGroup(buf); // TODO: Check if label already exists else { GDM::Shape shape = {static_cast<uint32_t>(dim[0]), static_cast<uint32_t>(dim[1])}; switch (type) { case GDM::Type::INT32: addObj.group->add<int32_t>(buf, nullptr, shape); break; case GDM::Type::INT64: addObj.group->add<int64_t>(buf, nullptr, shape); break; case GDM::Type::UINT8: addObj.group->add<uint8_t>(buf, nullptr, shape); break; case GDM::Type::UINT16: addObj.group->add<uint16_t>(buf, nullptr, shape); break; case GDM::Type::UINT32: addObj.group->add<uint32_t>(buf, nullptr, shape); break; case GDM::Type::UINT64: addObj.group->add<uint64_t>(buf, nullptr, shape); break; case GDM::Type::FLOAT: addObj.group->add<float>(buf, nullptr, shape); break; case GDM::Type::DOUBLE: addObj.group->add<double>(buf, nullptr, shape); break; } } addObj.view = false; } ImGui::SameLine(); if (ImGui::Button("Cancel")) addObj.view = false; ImGui::End(); } void GDEditor::releaseMemory(GDM::Group* group) { for (auto& [label, obj] : group->children()) { if (obj->getType() == GDM::Type::GROUP) { releaseMemory(reinterpret_cast<GDM::Group*>(obj)); } else { GDM::Data* ptr = reinterpret_cast<GDM::Data*>(obj); if (ptr->isLoaded()) ptr->release(); } } } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// void GDEditor::openFile(const fs::path &inPath) { if (vFile.find(inPath) != vFile.end()) mailbox.createWarn("File already openned!!"); else { mailbox.createInfo("Openning file: " + inPath.string()); vFile.emplace(inPath, inPath); currentFile = &vFile[inPath]; } } void GDEditor::saveFile(void) { if (currentFile) { mailbox.createInfo("Saving file to " + currentFile->getFilePath().string()); currentFile->save(); } }
26.226762
190
0.601418
guilmont
aa5cb80d29873cd202b9e6d1c585e14ab78e793f
2,666
cpp
C++
tests/lsscript_sequencing.cpp
hamsham/LightScript
22af688178067ebdb6f053e3916307ed799b3fb9
[ "BSD-3-Clause" ]
1
2015-11-07T03:59:57.000Z
2015-11-07T03:59:57.000Z
tests/lsscript_sequencing.cpp
hamsham/LightScript
22af688178067ebdb6f053e3916307ed799b3fb9
[ "BSD-3-Clause" ]
null
null
null
tests/lsscript_sequencing.cpp
hamsham/LightScript
22af688178067ebdb6f053e3916307ed799b3fb9
[ "BSD-3-Clause" ]
1
2015-10-16T06:07:54.000Z
2015-10-16T06:07:54.000Z
/* * File: sequence_test.cpp * Author: hammy * * Created on Feb 26, 2015, 12:38:57 AM */ #include <cassert> #include <iostream> #include "lightsky/script/Script.h" template <class data_t> using lsPointer = ls::script::Pointer_t<data_t>; using lsVariable = ls::script::Variable; using ls::script::create_variable; using ls::script::destroy_variable; using lsFunctor = ls::script::Functor; using ls::script::create_functor; using ls::script::destroy_functor; using ls::script::ScriptRunner; int main() { lsPointer<lsFunctor> testFunc1 = create_functor(ScriptHash_AddInts); lsPointer<lsFunctor> testFunc2 = create_functor(ScriptHash_SubInts); lsPointer<lsFunctor> testFunc3 = create_functor(ScriptHash_MulInts); lsPointer<lsFunctor> testFunc4 = create_functor(ScriptHash_DivInts); lsPointer<lsVariable> testVar1 = create_variable(ScriptHash_int); lsPointer<lsVariable> testVar2 = create_variable(ScriptHash_int); lsPointer<lsVariable> testVar3 = create_variable(ScriptHash_int); lsPointer<lsVariable> testVar5 = create_variable(ScriptHash_string); if (!testVar5) { std::cout << "Unable to create a string variable." << std::endl; } LS_SCRIPT_VAR_DATA(testVar1, int) = 1; LS_SCRIPT_VAR_DATA(testVar2, int) = 2; LS_SCRIPT_VAR_DATA(testVar3, int) = 0; // dummy value testFunc1->arg(0, testVar1.get()); // param 1 = 1 testFunc1->arg(1, testVar2.get()); // param 2 = 2 testFunc1->arg(2, testVar3.get()); // return value should equal 1+2=3 testFunc1->next_func_ptr(testFunc2.get()); testFunc2->arg(0, testVar1.get()); testFunc2->arg(1, testVar2.get()); testFunc2->arg(2, testVar2.get()); // should equal 1-2=-3 testFunc2->next_func_ptr(testFunc3.get()); testFunc3->arg(0, testVar1.get()); testFunc3->arg(1, testVar2.get()); testFunc3->arg(2, testVar2.get()); // should equal 1*2=2 testFunc3->next_func_ptr(testFunc4.get()); testFunc4->arg(0, testVar1.get()); testFunc4->arg(1, testVar2.get()); testFunc4->arg(2, testVar2.get()); // should equal 1/2=1 (int division) testFunc4->next_func_ptr(nullptr); ScriptRunner runner {}; runner.run(testFunc1.get()); assert(LS_SCRIPT_VAR_DATA(testVar3, int) == 1 / 2); std::cout << "Successfully ran the script tests." << std::endl; std::cout << "The final variable values are:" << std::endl; std::cout << "\tVariable 1: " << LS_SCRIPT_VAR_DATA(testVar1, int) << std::endl; std::cout << "\tVariable 2: " << LS_SCRIPT_VAR_DATA(testVar2, int) << std::endl; std::cout << "\tVariable 3: " << LS_SCRIPT_VAR_DATA(testVar3, int) << std::endl; return 0; }
33.325
84
0.684546
hamsham
aa5d110c209eafb80b53e1df4929bed17b2a523b
114
hpp
C++
test/old_tests/Composable/precomp.hpp
sylveon/cppwinrt
4d5c5ae3de386ce1f18c3410a27b9ceb40aa524d
[ "MIT" ]
859
2016-10-13T00:11:52.000Z
2019-05-06T15:45:46.000Z
test/old_tests/Composable/precomp.hpp
shinsetsu/cppwinrt
ae0378373d2318d91448b8697a91d5b65a1fb2e5
[ "MIT" ]
655
2019-10-08T12:15:16.000Z
2022-03-31T18:26:40.000Z
test/old_tests/Composable/precomp.hpp
shinsetsu/cppwinrt
ae0378373d2318d91448b8697a91d5b65a1fb2e5
[ "MIT" ]
137
2016-10-13T04:19:59.000Z
2018-11-09T05:08:03.000Z
#pragma once #pragma warning(disable:4100) #include "winrt/Windows.Foundation.h" #include "winrt/Composable.h"
16.285714
37
0.763158
sylveon
aa6384a49df1d137e7cfc1c1b7f7957242c33d9a
935
cpp
C++
test/utilities/template.bitset/bitset.members/any.pass.cpp
caiohamamura/libcxx
27c836ff3a9c505deb9fd1616012924de8ff9279
[ "MIT" ]
1,244
2015-01-02T21:08:56.000Z
2022-03-22T21:34:16.000Z
test/utilities/template.bitset/bitset.members/any.pass.cpp
caiohamamura/libcxx
27c836ff3a9c505deb9fd1616012924de8ff9279
[ "MIT" ]
125
2015-01-22T01:08:00.000Z
2020-05-25T08:28:17.000Z
test/utilities/template.bitset/bitset.members/any.pass.cpp
caiohamamura/libcxx
27c836ff3a9c505deb9fd1616012924de8ff9279
[ "MIT" ]
124
2015-01-12T15:06:17.000Z
2022-03-26T07:48:53.000Z
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // test bool any() const; #include <bitset> #include <cassert> template <std::size_t N> void test_any() { std::bitset<N> v; v.reset(); assert(v.any() == false); v.set(); assert(v.any() == (N != 0)); if (N > 1) { v[N/2] = false; assert(v.any() == true); v.reset(); v[N/2] = true; assert(v.any() == true); } } int main() { test_any<0>(); test_any<1>(); test_any<31>(); test_any<32>(); test_any<33>(); test_any<63>(); test_any<64>(); test_any<65>(); test_any<1000>(); }
20.777778
80
0.427807
caiohamamura
aa65398a61e1b17699300f3639089ecf03236630
779
cpp
C++
src/debug_gui/types/camera3d.cpp
degarashi/revenant
9e671320a5c8790f6bdd1b14934f81c37819f7b3
[ "MIT" ]
null
null
null
src/debug_gui/types/camera3d.cpp
degarashi/revenant
9e671320a5c8790f6bdd1b14934f81c37819f7b3
[ "MIT" ]
null
null
null
src/debug_gui/types/camera3d.cpp
degarashi/revenant
9e671320a5c8790f6bdd1b14934f81c37819f7b3
[ "MIT" ]
null
null
null
#include "../../camera3d.hpp" #include "../entry_field.hpp" namespace rev { const char* Camera3D::getDebugName() const noexcept { return "Camera3D"; } bool Camera3D::property(const bool edit) { auto f = debug::EntryField("Camera3D", edit); ImGui::Columns(1); if(f.entry("pose", _rflag.ref<Pose>())) refPose(); ImGui::Columns(2); if(f.entry("Fov", _rflag.ref<Fov>())) refFov(); if(f.entry("Aspect", _rflag.ref<Aspect>())) refAspect(); if(f.entry("NearZ", _rflag.ref<NearZ>())) refNearZ(); if(f.entry("FarZ", _rflag.ref<FarZ>())) refFarZ(); f.show("Accum", uint64_t(getAccum())); auto& rot = getPose().getRotation(); f.show("Right", rot.getRight()); f.show("Up", rot.getUp()); f.show("Dir", rot.getDir()); return f.modified(); } }
25.966667
54
0.620026
degarashi
aa6bc184df9da1b35fe983d11f2779acaa978ee4
1,154
cpp
C++
WA/UVa-10410.cpp
chenhw26/OnlineJudgeByChw
112560816a34062ddaf502d81f25dbb9a2ccd7d5
[ "MIT" ]
null
null
null
WA/UVa-10410.cpp
chenhw26/OnlineJudgeByChw
112560816a34062ddaf502d81f25dbb9a2ccd7d5
[ "MIT" ]
null
null
null
WA/UVa-10410.cpp
chenhw26/OnlineJudgeByChw
112560816a34062ddaf502d81f25dbb9a2ccd7d5
[ "MIT" ]
null
null
null
#include <iostream> #include <set> using namespace std; int find(int a, int n, int *arr, int begin = 1){ for(int i = begin; i <= n; ++i) if(arr[i] == a) return i; return 0; } int main(){ int n; while(cin >> n){ int bfs[n + 5] = {0}, dfs[n + 5] = {0}; set<int> ans[n + 5]; bool findAns[n + 5] = {0}; for (int i = 1; i <= n; ++i) cin >> bfs[i]; for (int i = 1; i <= n; ++i) cin >> dfs[i]; for (int i = 1; i <= n; ++i){ int indexInDFS = find(bfs[i], n, dfs); int firstSon = dfs[indexInDFS + 1]; int firstSonIndexInBFS = find(firstSon, n, bfs, i + 1); if(firstSonIndexInBFS){ int subling = bfs[i + 1]; int sublingSon = dfs[find(subling, n, dfs) + 1]; int sublingSonIndexInBFS = find(sublingSon, n, bfs, i + 2); int endIndex = sublingSonIndexInBFS && !findAns[sublingSon]? sublingSonIndexInBFS: n + 1; for (int j = firstSonIndexInBFS; j < endIndex; ++j){ if(!findAns[bfs[j]]){ ans[bfs[i]].insert(bfs[j]); findAns[bfs[j]] = true; } } } } for (int i = 1; i <= n; ++i){ cout << i << ':'; for (auto son: ans[i]) cout << ' ' << son; cout << endl; } } return 0; }
26.227273
93
0.533795
chenhw26
aa6ccc40393607ba110b06791af3732e152a2448
15,500
inl
C++
c++/Palm/PalmField.inl
aamshukov/miscellaneous
6fc0d2cb98daff70d14f87b2dfc4e58e61d2df60
[ "MIT" ]
null
null
null
c++/Palm/PalmField.inl
aamshukov/miscellaneous
6fc0d2cb98daff70d14f87b2dfc4e58e61d2df60
[ "MIT" ]
null
null
null
c++/Palm/PalmField.inl
aamshukov/miscellaneous
6fc0d2cb98daff70d14f87b2dfc4e58e61d2df60
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////////////// //...................................................................................... // This is a part of AI Library [Arthur's Interfaces Library]. . // 1998-2001 Arthur Amshukov . //...................................................................................... // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND . // DO NOT REMOVE MY NAME AND THIS NOTICE FROM THE SOURCE . //...................................................................................... //////////////////////////////////////////////////////////////////////////////////////// #ifndef __PALM_FIELD_INL__ #define __PALM_FIELD_INL__ #ifdef __PALM_OS__ #pragma once __BEGIN_NAMESPACE__ //////////////////////////////////////////////////////////////////////////////////////// // class PalmField // ----- --------- __INLINE__ PalmField::operator FieldType* () { return static_cast<FieldType*>(Control); } __INLINE__ PalmField::operator const FieldType* () const { return const_cast<const FieldType*>(Control); } __INLINE__ char* PalmField::GetTextPtr() { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); return ::FldGetTextPtr(static_cast<FieldType*>(Control)); } __INLINE__ void PalmField::SetTextPtr(const char* _text) { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); palmxassert(_text != null, Error::eInvalidArg, PalmField::XPalmField); ::FldSetTextPtr(static_cast<FieldType*>(Control), const_cast<char*>(_text)); } __INLINE__ void PalmField::SetText(MemHandle _handle, uint16 _offset, uint16 _size) { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); palmxassert(_handle != 0, Error::eInvalidArg, PalmField::XPalmField); ::FldSetText(static_cast<FieldType*>(Control), _handle, _offset, _size); } __INLINE__ MemHandle PalmField::GetTextHandle() { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); return ::FldGetTextHandle(static_cast<FieldType*>(Control)); } __INLINE__ void PalmField::SetTextHandle(MemHandle _handle) { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); palmxassert(_handle != 0, Error::eInvalidArg, PalmField::XPalmField); ::FldSetTextHandle(static_cast<FieldType*>(Control), _handle); } __INLINE__ uint16 PalmField::GetTextLength() { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); return ::FldGetTextLength(static_cast<FieldType*>(Control)); } __INLINE__ uint16 PalmField::GetTextHeight() { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); return ::FldGetTextHeight(static_cast<FieldType*>(Control)); } __INLINE__ uint16 PalmField::CalcFieldHeight(const char* _chars, uint16 _width) { palmxassert(_chars != null, Error::eInvalidArg, PalmField::XPalmField); return ::FldCalcFieldHeight(_chars, _width); } __INLINE__ uint16 PalmField::GetMaxChars() { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); return ::FldGetMaxChars(static_cast<FieldType*>(Control)); } __INLINE__ void PalmField::SetMaxChars(uint16 _max_chars) { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); ::FldSetMaxChars(static_cast<FieldType*>(Control), _max_chars); } __INLINE__ void PalmField::RecalculateField(bool _redraw) { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); ::FldRecalculateField(static_cast<FieldType*>(Control), _redraw); } __INLINE__ void PalmField::CompactText() { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); ::FldCompactText(static_cast<FieldType*>(Control)); } __INLINE__ void PalmField::FreeMemory() { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); ::FldFreeMemory(static_cast<FieldType*>(Control)); } __INLINE__ uint16 PalmField::GetTextAllocatedSize() { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); return ::FldGetTextAllocatedSize(static_cast<FieldType*>(Control)); } __INLINE__ void PalmField::SetTextAllocatedSize(uint16 _size) { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); palmxassert(_size > 0, Error::eInvalidArg, PalmField::XPalmField); ::FldSetTextAllocatedSize(static_cast<FieldType*>(Control), _size); } __INLINE__ void PalmField::GetAttributes(FieldAttrType& _attr) { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); ::FldGetAttributes(static_cast<FieldType*>(Control), &_attr); } __INLINE__ void PalmField::SetAttributes(const FieldAttrType& _attr) { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); ::FldSetAttributes(static_cast<FieldType*>(Control), &_attr); } __INLINE__ bool PalmField::Insert(const char* _text, uint16 _len) { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); palmxassert(_text != null && _len > 0, Error::eInvalidArg, PalmField::XPalmField); return ::FldInsert(static_cast<FieldType*>(Control), _text, _len); } __INLINE__ void PalmField::Delete(uint16 _start, uint16 _end) { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); palmxassert(_start <= _end, Error::eInvalidArg, PalmField::XPalmField); ::FldDelete(static_cast<FieldType*>(Control), _start, _end); } __INLINE__ void PalmField::Copy() { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); ::FldCopy(static_cast<FieldType*>(Control)); } __INLINE__ void PalmField::Cut() { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); ::FldCut(static_cast<FieldType*>(Control)); } __INLINE__ void PalmField::Paste() { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); ::FldPaste(static_cast<FieldType*>(Control)); } __INLINE__ void PalmField::Undo() { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); ::FldUndo(static_cast<FieldType*>(Control)); } __INLINE__ void PalmField::DrawField() { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); ::FldDrawField(static_cast<FieldType*>(Control)); } __INLINE__ void PalmField::EraseField() { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); ::FldEraseField(static_cast<FieldType*>(Control)); } __INLINE__ void PalmField::GetBounds(Rect& _r) { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); ::FldGetBounds(static_cast<FieldType*>(Control), &_r); } __INLINE__ void PalmField::SetBounds(const Rect& _r) { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); ::FldSetBounds(static_cast<FieldType*>(Control), &_r); } __INLINE__ FontID PalmField::GetFont() { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); return ::FldGetFont(static_cast<FieldType*>(Control)); } __INLINE__ void PalmField::SetFont(FontID _id) { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); ::FldSetFont(static_cast<FieldType*>(Control), _id); } __INLINE__ void PalmField::SetUsable(bool _usable) { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); ::FldSetUsable(static_cast<FieldType*>(Control), _usable); } __INLINE__ bool PalmField::MakeFullyVisible() { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); return ::FldMakeFullyVisible(static_cast<FieldType*>(Control)); } __INLINE__ uint16 PalmField::GetNumberOfBlankLines() { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); return ::FldGetNumberOfBlankLines(static_cast<FieldType*>(Control)); } __INLINE__ void PalmField::GrabFocus() { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); ::FldGrabFocus(static_cast<FieldType*>(Control)); } __INLINE__ void PalmField::ReleaseFocus() { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); ::FldReleaseFocus(static_cast<FieldType*>(Control)); } __INLINE__ void PalmField::GetSelection(uint16& _start, uint16& _end) { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); ::FldGetSelection(static_cast<FieldType*>(Control), &_start, &_end); } __INLINE__ void PalmField::SetSelection(uint16 _start, uint16 _end) { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); palmxassert(_start <= _end, Error::eInvalidArg, PalmField::XPalmField); ::FldSetSelection(static_cast<FieldType*>(Control), _start, _end); } __INLINE__ uint16 PalmField::GetInsPtPosition() { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); return ::FldGetInsPtPosition(static_cast<FieldType*>(Control)); } __INLINE__ void PalmField::SetInsPtPosition(uint16 _pos) { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); ::FldSetInsPtPosition(static_cast<FieldType*>(Control), _pos); } __INLINE__ void PalmField::SetInsertionPoint(uint16 _pos) { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); ::FldSetInsertionPoint(static_cast<FieldType*>(Control), _pos); } __INLINE__ bool PalmField::IsScrollable(WinDirectionType _dir) { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); return ::FldScrollable(static_cast<FieldType*>(Control), _dir); } __INLINE__ void PalmField::ScrollField(uint16 _count, WinDirectionType _dir) { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); ::FldScrollField(static_cast<FieldType*>(Control), _count, _dir); } __INLINE__ uint16 PalmField::GetScrollPosition() { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); return ::FldGetScrollPosition(static_cast<FieldType*>(Control)); } __INLINE__ void PalmField::SetScrollPosition(uint16 _pos) { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); ::FldSetScrollPosition(static_cast<FieldType*>(Control), _pos); } __INLINE__ void PalmField::GetScrollValues(uint16& _scroll_pos, uint16& _text_height, uint16& _field_height) { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); ::FldGetScrollValues(static_cast<FieldType*>(Control), &_scroll_pos, &_text_height, &_field_height); } __INLINE__ uint16 PalmField::GetVisibleLines() { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); return ::FldGetVisibleLines(static_cast<FieldType*>(Control)); } __INLINE__ uint16 PalmField::WordWrap(const char* _text, int16 _len) { palmxassert(_text != null, Error::eInvalidArg, PalmField::XPalmField); return ::FldWordWrap(_text, _len); } __INLINE__ bool PalmField::Dirty() { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); return ::FldDirty(static_cast<FieldType*>(Control)); } __INLINE__ void PalmField::SetDirty(bool _dirty) { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); ::FldSetDirty(static_cast<FieldType*>(Control), _dirty); } __INLINE__ void PalmField::SendChangeNotification() { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); ::FldSendChangeNotification(static_cast<FieldType*>(Control)); } __INLINE__ void PalmField::SendHeightChangeNotification(uint16 _pos, int16 _num_lines) { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); ::FldSendHeightChangeNotification(static_cast<FieldType*>(Control), _pos, _num_lines); } __INLINE__ bool PalmField::HandleEvent(EventType& _event) { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); return ::FldHandleEvent(static_cast<FieldType*>(Control), &_event); } #if (__PALM_OS__ >= 0x0400) __INLINE__ void PalmField::SetMaxVisibleLines(uint8 _max_lines) { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); ::FldSetMaxVisibleLines(static_cast<FieldType*>(Control), _max_lines); } #endif __INLINE__ FieldType* PalmField::Clone(uint16 _id, Coord _x, Coord _y, Coord _w, Coord _h, FontID _font_id, uint32 _max_chars, bool _editable, bool _underlined, bool _single_line, bool _dynamic, JustificationType _justification, bool _autoshift, bool _has_scrollbars, bool _numeric) { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); return ::FldNewField(&Control, _id, _x, _y, _w, _h, _font_id, _max_chars, _editable, _underlined, _single_line, _dynamic, _justification, _autoshift, _has_scrollbars, _numeric); } __INLINE__ FieldType* PalmField::Clone(uint16 _id, const Point& _pt, const Size& _sz, FontID _font_id, uint32 _max_chars, bool _editable, bool _underlined, bool _single_line, bool _dynamic, JustificationType _justification, bool _autoshift, bool _has_scrollbars, bool _numeric) { palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField); return ::FldNewField(&Control, _id, _pt.x, _pt.y, _sz.cx, _sz.cy, _font_id, _max_chars, _editable, _underlined, _single_line, _dynamic, _justification, _autoshift, _has_scrollbars, _numeric); } __INLINE__ FieldType* PalmField::Clone(void** _form, uint16 _id, Coord _x, Coord _y, Coord _w, Coord _h, FontID _font_id, uint32 _max_chars, bool _editable, bool _underlined, bool _single_line, bool _dynamic, JustificationType _justification, bool _autoshift, bool _has_scrollbars, bool _numeric) { palmxassert(_form != null, Error::eInvalidArg, PalmField::XPalmField); return ::FldNewField(_form, _id, _x, _y, _w, _h, _font_id, _max_chars, _editable, _underlined, _single_line, _dynamic, _justification, _autoshift, _has_scrollbars, _numeric); } __INLINE__ FieldType* PalmField::Clone(void** _form, uint16 _id, const Point& _pt, const Size& _sz, FontID _font_id, uint32 _max_chars, bool _editable, bool _underlined, bool _single_line, bool _dynamic, JustificationType _justification, bool _autoshift, bool _has_scrollbars, bool _numeric) { palmxassert(_form != null, Error::eInvalidArg, PalmField::XPalmField); return ::FldNewField(_form, _id, _pt.x, _pt.y, _sz.cx, _sz.cy, _font_id, _max_chars, _editable, _underlined, _single_line, _dynamic, _justification, _autoshift, _has_scrollbars, _numeric); } //////////////////////////////////////////////////////////////////////////////////////// __END_NAMESPACE__ #endif // __PALM_OS__ #endif // __PALM_FIELD_INL__
38.75
195
0.684839
aamshukov
aa70d7599f31fced9d60ef5bb7c1d4e64bed6af5
274
hh
C++
extern/clean-core/src/clean-core/stringhash.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
null
null
null
extern/clean-core/src/clean-core/stringhash.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
null
null
null
extern/clean-core/src/clean-core/stringhash.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
null
null
null
#pragma once #include <clean-core/hash_combine.hh> namespace cc { constexpr hash_t stringhash(char const* s) { if (!s) return 0; hash_t h = hash_combine(); while (*s) { h = hash_combine(h, hash_t(*s)); s++; } return h; } }
13.047619
42
0.547445
rovedit
aa729a6109d216204055f776fa7ca358c67e985b
53,767
cpp
C++
join/sax/tests/packreader_test.cpp
mrabine/join
63c6193f2cc229328c36748d7f9ef8aca915bec3
[ "MIT" ]
1
2021-09-14T13:53:07.000Z
2021-09-14T13:53:07.000Z
join/sax/tests/packreader_test.cpp
joinframework/join
63c6193f2cc229328c36748d7f9ef8aca915bec3
[ "MIT" ]
15
2021-08-09T23:55:02.000Z
2021-11-22T11:05:41.000Z
join/sax/tests/packreader_test.cpp
mrabine/join
63c6193f2cc229328c36748d7f9ef8aca915bec3
[ "MIT" ]
null
null
null
/** * MIT License * * Copyright (c) 2021 Mathieu Rabine * * 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. */ // libjoin. #include <join/pack.hpp> // libraries. #include <gtest/gtest.h> // C++. #include <sstream> // C. #include <cmath> using join::Array; using join::Member; using join::Object; using join::Value; using join::SaxErrc; using join::PackReader; /** * @brief Test deserialize method. */ TEST (PackReader, deserialize) { std::stringstream stream; Value value; stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x00'})); std::string str ({'\xdd', '\x00', '\x00', '\x00', '\x00'}); char data[] = {'\xdd', '\x00', '\x00', '\x00', '\x00', '\x00'}; ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_TRUE (value.empty ()); ASSERT_EQ (value.deserialize <PackReader> (str), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_TRUE (value.empty ()); ASSERT_EQ (value.deserialize <PackReader> (data, sizeof (data) - 1), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_TRUE (value.empty ()); ASSERT_EQ (value.deserialize <PackReader> (&data[0], &data[sizeof (data) - 1]), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_TRUE (value.empty ()); ASSERT_EQ (value.deserialize <PackReader> (&data[0], &data[sizeof (data)]), -1); ASSERT_EQ (join::lastError, SaxErrc::ExtraData); } /** * @brief Test MessagePack parsing pass. */ TEST (PackReader, pass) { std::stringstream stream; Value value; stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x00'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_TRUE (value.empty ()); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xce', '\x49', '\x96', '\x02', '\xd2'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isInt ()); ASSERT_EQ (value[0], 1234567890); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\xc0', '\xc3', '\x4a', '\x45', '\x87', '\xe7', '\xc0', '\x6e'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); ASSERT_DOUBLE_EQ (value[0].getDouble (), -9876.543210); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x3d', '\x41', '\x5f', '\xff', '\xe5', '\x3a', '\x68', '\x5d'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); ASSERT_DOUBLE_EQ (value[0].getDouble (), 0.123456789e-12); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x47', '\x03', '\x05', '\x82', '\xff', '\xd7', '\x14', '\x75'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); ASSERT_DOUBLE_EQ (value[0].getDouble (), 1.234567890E+34); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xc3'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isBool ()); ASSERT_EQ (value[0], true); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xc2'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isBool ()); ASSERT_EQ (value[0], false); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xc0'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isNull ()); ASSERT_EQ (value[0], nullptr); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x0b', '\xcb', '\x3f', '\xe0', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\xcb', '\x40', '\x58', '\xa6', '\x66', '\x66', '\x66', '\x66', '\x66', '\xcb', '\x40', '\x58', '\xdc', '\x28', '\xf5', '\xc2', '\x8f', '\x5c', '\xcd', '\x04', '\x2a', '\xcb', '\x40', '\x24', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\xcb', '\x3f', '\xf0', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\xcb', '\x3f', '\xb9', '\x99', '\x99', '\x99', '\x99', '\x99', '\x9a', '\xcb', '\x3f', '\xf0', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\xcb', '\x40', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\xcb', '\x40', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\xa7', '\x72', '\x6f', '\x73', '\x65', '\x62', '\x75', '\x64'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_EQ (value.size (), 11); ASSERT_TRUE (value[0].isDouble ()); ASSERT_DOUBLE_EQ (value[0].getDouble (), 0.5); ASSERT_TRUE (value[1].isDouble ()); ASSERT_DOUBLE_EQ (value[1].getDouble (), 98.6); ASSERT_TRUE (value[2].isDouble ()); ASSERT_DOUBLE_EQ (value[2].getDouble (), 99.44); ASSERT_TRUE (value[3].isInt ()); ASSERT_EQ (value[3].getInt (), 1066); ASSERT_TRUE (value[4].isDouble ()); ASSERT_DOUBLE_EQ (value[4].getDouble (), 1e1); ASSERT_TRUE (value[5].isDouble ()); ASSERT_DOUBLE_EQ (value[5].getDouble (), 0.1e1); ASSERT_TRUE (value[6].isDouble ()); ASSERT_DOUBLE_EQ (value[6].getDouble (), 1e-1); ASSERT_TRUE (value[7].isDouble ()); ASSERT_DOUBLE_EQ (value[7].getDouble (), 1e00); ASSERT_TRUE (value[8].isDouble ()); ASSERT_DOUBLE_EQ (value[8].getDouble (), 2e+00); ASSERT_TRUE (value[9].isDouble ()); ASSERT_DOUBLE_EQ (value[9].getDouble (), 2e-00); ASSERT_TRUE (value[10].isString ()); ASSERT_EQ (value[10], "rosebud"); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xac', '\x4e', '\x6f', '\x74', '\x20', '\x74', '\x6f', '\x6f', '\x20', '\x64', '\x65', '\x65', '\x70'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); stream.clear (); stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x00'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isObject ()); ASSERT_TRUE (value.empty ()); stream.clear (); stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa7', '\x69', '\x6e', '\x74', '\x65', '\x67', '\x65', '\x72', '\xce', '\x49', '\x96', '\x02', '\xd2'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isObject ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value["integer"].isInt ()); ASSERT_EQ (value["integer"], 1234567890); stream.clear (); stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa4', '\x72', '\x65', '\x61', '\x6c', '\xcb', '\xc0', '\xc3', '\x4a', '\x45', '\x87', '\xe7', '\xc0', '\x6e'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isObject ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value["real"].isDouble ()); ASSERT_DOUBLE_EQ (value["real"].getDouble (), -9876.543210); stream.clear (); stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa1', '\x65', '\xcb', '\x3d', '\x41', '\x5f', '\xff', '\xe5', '\x3a', '\x68', '\x5d'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isObject ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value["e"].isDouble ()); ASSERT_DOUBLE_EQ (value["e"].getDouble (), 0.123456789e-12); stream.clear (); stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa1', '\x45', '\xcb', '\x47', '\x03', '\x05', '\x82', '\xff', '\xd7', '\x14', '\x75'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isObject ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value["E"].isDouble ()); ASSERT_DOUBLE_EQ (value["E"].getDouble (), 1.234567890E+34); stream.clear (); stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa0', '\xcb', '\x4f', '\xc9', '\xee', '\x09', '\x3a', '\x64', '\xb8', '\x54'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isObject ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[""].isDouble ()); ASSERT_DOUBLE_EQ (value[""].getDouble (), 23456789012E66); stream.clear (); stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa4', '\x7a', '\x65', '\x72', '\x6f', '\x00'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isObject ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value["zero"].isInt ()); ASSERT_EQ (value["zero"], 0); stream.clear (); stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa3', '\x6f', '\x6e', '\x65', '\x01'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isObject ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value["one"].isInt ()); ASSERT_EQ (value["one"], 1); stream.clear (); stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa5', '\x73', '\x70', '\x61', '\x63', '\x65', '\xa1', '\x20'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isObject ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value["space"].isString ()); ASSERT_EQ (value["space"], " "); stream.clear (); stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa5', '\x71', '\x75', '\x6f', '\x74', '\x65', '\xa1', '\x22'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isObject ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value["quote"].isString ()); ASSERT_EQ (value["quote"], "\""); stream.clear (); stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa9', '\x62', '\x61', '\x63', '\x6b', '\x73', '\x6c', '\x61', '\x73', '\x68', '\xa1', '\x5c'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isObject ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value["backslash"].isString ()); ASSERT_EQ (value["backslash"], "\\"); stream.clear (); stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa8', '\x63', '\x6f', '\x6e', '\x74', '\x72', '\x6f', '\x6c', '\x73', '\xa5', '\x08', '\x0c', '\x0a', '\x0d', '\x09'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isObject ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value["controls"].isString ()); ASSERT_EQ (value["controls"], "\b\f\n\r\t"); stream.clear (); stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa5', '\x73', '\x6c', '\x61', '\x73', '\x68', '\xa6', '\x2f', '\x20', '\x26', '\x20', '\x5c', '\x2f'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isObject ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value["slash"].isString ()); ASSERT_EQ (value["slash"], "/ & \\/"); stream.clear (); stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa5', '\x61', '\x6c', '\x70', '\x68', '\x61', '\xb9', '\x61', '\x62', '\x63', '\x64', '\x65', '\x66', '\x67', '\x68', '\x69', '\x6a', '\x6b', '\x6c', '\x6d', '\x6e', '\x6f', '\x70', '\x71', '\x72', '\x73', '\x74', '\x75', '\x76', '\x77', '\x79', '\x7a'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isObject ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value["alpha"].isString ()); ASSERT_EQ (value["alpha"], "abcdefghijklmnopqrstuvwyz"); stream.clear (); stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa5', '\x41', '\x4c', '\x50', '\x48', '\x41', '\xb9', '\x41', '\x42', '\x43', '\x44', '\x45', '\x46', '\x47', '\x48', '\x49', '\x4a', '\x4b', '\x4c', '\x4d', '\x4e', '\x4f', '\x50', '\x51', '\x52', '\x53', '\x54', '\x55', '\x56', '\x57', '\x59', '\x5a'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isObject ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value["ALPHA"].isString ()); ASSERT_EQ (value["ALPHA"], "ABCDEFGHIJKLMNOPQRSTUVWYZ"); stream.clear (); stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa5', '\x64', '\x69', '\x67', '\x69', '\x74', '\xaa', '\x30', '\x31', '\x32', '\x33', '\x34', '\x35', '\x36', '\x37', '\x38', '\x39'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isObject ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value["digit"].isString ()); ASSERT_EQ (value["digit"], "0123456789"); stream.clear (); stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xaa', '\x30', '\x31', '\x32', '\x33', '\x34', '\x35', '\x36', '\x37', '\x38', '\x39', '\xa5', '\x64', '\x69', '\x67', '\x69', '\x74'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isObject ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value["0123456789"].isString ()); ASSERT_EQ (value["0123456789"], "digit"); stream.clear (); stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa7', '\x73', '\x70', '\x65', '\x63', '\x69', '\x61', '\x6c', '\xbf', '\x60', '\x31', '\x7e', '\x21', '\x40', '\x23', '\x24', '\x25', '\x5e', '\x26', '\x2a', '\x28', '\x29', '\x5f', '\x2b', '\x2d', '\x3d', '\x7b', '\x27', '\x3a', '\x5b', '\x2c', '\x5d', '\x7d', '\x7c', '\x3b', '\x2e', '\x3c', '\x2f', '\x3e', '\x3f'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isObject ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value["special"].isString ()); ASSERT_EQ (value["special"], "`1~!@#$%^&*()_+-={':[,]}|;.</>?"); stream.clear (); stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa3', '\x68', '\x65', '\x78', '\xb1', '\xc4', '\xa3', '\xe4', '\x95', '\xa7', '\xe8', '\xa6', '\xab', '\xec', '\xb7', '\xaf', '\xea', '\xaf', '\x8d', '\xee', '\xbd', '\x8a'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isObject ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value["hex"].isString ()); ASSERT_EQ (value["hex"].getString (), std::string ({'\xC4', '\xA3', '\xE4', '\x95', '\xA7', '\xE8', '\xA6', '\xAB', '\xEC', '\xB7', '\xAF', '\xEA', '\xAF', '\x8D', '\xEE', '\xBD', '\x8A'})); stream.clear (); stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa4', '\x74', '\x72', '\x75', '\x65', '\xc3'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isObject ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value["true"].isBool ()); ASSERT_EQ (value["true"], true); stream.clear (); stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa5', '\x66', '\x61', '\x6c', '\x73', '\x65', '\xc2'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isObject ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value["false"].isBool ()); ASSERT_EQ (value["false"], false); stream.clear (); stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa4', '\x6e', '\x75', '\x6c', '\x6c', '\xc0'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isObject ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value["null"].isNull ()); ASSERT_EQ (value["null"], nullptr); stream.clear (); stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa5', '\x61', '\x72', '\x72', '\x61', '\x79', '\xdd', '\x00', '\x00', '\x00', '\x00'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isObject ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value["array"].isArray ()); ASSERT_TRUE (value["array"].empty ()); stream.clear (); stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa6', '\x6f', '\x62', '\x6a', '\x65', '\x63', '\x74', '\xdf', '\x00', '\x00', '\x00', '\x00'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isObject ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value["object"].isObject ()); ASSERT_TRUE (value["object"].empty ()); stream.clear (); stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa7', '\x61', '\x64', '\x64', '\x72', '\x65', '\x73', '\x73', '\xb3', '\x35', '\x30', '\x20', '\x53', '\x74', '\x2e', '\x20', '\x4a', '\x61', '\x6d', '\x65', '\x73', '\x20', '\x53', '\x74', '\x72', '\x65', '\x65', '\x74'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isObject ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value["address"].isString ()); ASSERT_EQ (value["address"], "50 St. James Street"); stream.clear (); stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa3', '\x75', '\x72', '\x6c', '\xbe', '\x68', '\x74', '\x74', '\x70', '\x73', '\x3a', '\x2f', '\x2f', '\x77', '\x77', '\x77', '\x2e', '\x6a', '\x6f', '\x69', '\x6e', '\x66', '\x72', '\x61', '\x6d', '\x65', '\x77', '\x6f', '\x72', '\x6b', '\x2e', '\x6e', '\x65', '\x74', '\x2f'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isObject ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value["url"].isString ()); ASSERT_EQ (value["url"], "https://www.joinframework.net/"); stream.clear (); stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x02', '\xa7', '\x63', '\x6f', '\x6d', '\x6d', '\x65', '\x6e', '\x74', '\xad', '\x2f', '\x2f', '\x20', '\x2f', '\x2a', '\x20', '\x3c', '\x21', '\x2d', '\x2d', '\x20', '\x2d', '\x2d', '\xab', '\x23', '\x20', '\x2d', '\x2d', '\x20', '\x2d', '\x2d', '\x3e', '\x20', '\x2a', '\x2f', '\xa1', '\x20'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isObject ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value["comment"].isString ()); ASSERT_EQ (value["comment"], "// /* <!-- --"); ASSERT_TRUE (value["# -- --> */"].isString ()); ASSERT_EQ (value["# -- --> */"], " "); stream.clear (); stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x02', '\xad', '\x20', '\x73', '\x20', '\x70', '\x20', '\x61', '\x20', '\x63', '\x20', '\x65', '\x20', '\x64', '\x20', '\xdd', '\x00', '\x00', '\x00', '\x07', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07', '\xa7', '\x63', '\x6f', '\x6d', '\x70', '\x61', '\x63', '\x74', '\xdd', '\x00', '\x00', '\x00', '\x07', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isObject ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[" s p a c e d "].isArray ()); ASSERT_EQ (value[" s p a c e d "][0], 1); ASSERT_EQ (value[" s p a c e d "][1], 2); ASSERT_EQ (value[" s p a c e d "][2], 3); ASSERT_EQ (value[" s p a c e d "][3], 4); ASSERT_EQ (value[" s p a c e d "][4], 5); ASSERT_EQ (value[" s p a c e d "][5], 6); ASSERT_EQ (value[" s p a c e d "][6], 7); ASSERT_TRUE (value["compact"].isArray ()); ASSERT_EQ (value["compact"][0], 1); ASSERT_EQ (value["compact"][1], 2); ASSERT_EQ (value["compact"][2], 3); ASSERT_EQ (value["compact"][3], 4); ASSERT_EQ (value["compact"][4], 5); ASSERT_EQ (value["compact"][5], 6); ASSERT_EQ (value["compact"][6], 7); stream.clear (); stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xb4', '\x6f', '\x62', '\x6a', '\x65', '\x63', '\x74', '\x20', '\x77', '\x69', '\x74', '\x68', '\x20', '\x31', '\x20', '\x6d', '\x65', '\x6d', '\x62', '\x65', '\x72', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xb4', '\x61', '\x72', '\x72', '\x61', '\x79', '\x20', '\x77', '\x69', '\x74', '\x68', '\x20', '\x31', '\x20', '\x65', '\x6c', '\x65', '\x6d', '\x65', '\x6e', '\x74'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isObject ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value["object with 1 member"].isArray ()); ASSERT_EQ (value["object with 1 member"][0], "array with 1 element"); stream.clear (); stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa6', '\x71', '\x75', '\x6f', '\x74', '\x65', '\x73', '\xbb', '\x26', '\x23', '\x33', '\x34', '\x3b', '\x20', '\x22', '\x20', '\x25', '\x32', '\x32', '\x20', '\x30', '\x78', '\x32', '\x32', '\x20', '\x30', '\x33', '\x34', '\x20', '\x26', '\x23', '\x78', '\x32', '\x32', '\x3b'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isObject ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value["quotes"].isString ()); ASSERT_EQ (value["quotes"], "&#34; \" %22 0x22 034 &#x22;"); stream.clear (); stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xd9', '\x25', '\x22', '\x08', '\x0c', '\x0a', '\x0d', '\x09', '\x60', '\x31', '\x7e', '\x21', '\x40', '\x23', '\x24', '\x25', '\x5e', '\x26', '\x2a', '\x28', '\x29', '\x5f', '\x2b', '\x2d', '\x3d', '\x5b', '\x5d', '\x7b', '\x7d', '\x7c', '\x3b', '\x3a', '\x27', '\x2c', '\x2e', '\x2f', '\x3c', '\x3e', '\x3f', '\xb7', '\x41', '\x20', '\x6b', '\x65', '\x79', '\x20', '\x63', '\x61', '\x6e', '\x20', '\x62', '\x65', '\x20', '\x61', '\x6e', '\x79', '\x20', '\x73', '\x74', '\x72', '\x69', '\x6e', '\x67'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isObject ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value["\"\b\f\n\r\t`1~!@#$%^&*()_+-=[]{}|;:',./<>?"].isString ()); ASSERT_EQ (value["\"\b\f\n\r\t`1~!@#$%^&*()_+-=[]{}|;:',./<>?"], "A key can be any string"); } /** * @brief Test MessagePack parsing fail. */ TEST (PackReader, fail) { std::stringstream stream; Value value; stream.clear (); stream.str (std::string ({'\xd9', '\x32', '\x70', '\x61', '\x79', '\x6c', '\x6f', '\x61', '\x64', '\x20', '\x73', '\x68', '\x6f', '\x75', '\x6c', '\x64', '\x20', '\x62', '\x65', '\x20', '\x61', '\x6e', '\x20', '\x6f', '\x62', '\x6a', '\x65', '\x63', '\x74', '\x20', '\x6f', '\x72', '\x20', '\x61', '\x72', '\x72', '\x61', '\x79', '\x2c', '\x20', '\x6e', '\x6f', '\x74', '\x20', '\x61', '\x20', '\x73', '\x74', '\x72', '\x69', '\x6e', '\x67'})); ASSERT_NE (value.deserialize <PackReader> (stream), 0); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xa8', '\x54', '\x6f', '\x6f', '\x20', '\x64', '\x65', '\x65', '\x70'})); ASSERT_NE (value.deserialize <PackReader> (stream), 0); } /** * @brief Test MessagePack parse double. */ TEST (PackReader, dbl) { std::stringstream stream; Value value; stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 0.0); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x80', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), -0.0); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x3f', '\xf0', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 1.0); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\xbf', '\xf0', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), -1.0); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x3f', '\xf8', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 1.5); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\xbf', '\xf8', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), -1.5); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x40', '\x09', '\x21', '\xff', '\x2e', '\x48', '\xe8', '\xa7'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 3.1416); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x42', '\x02', '\xa0', '\x5f', '\x20', '\x00', '\x00', '\x00'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 1E10); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x3d', '\xdb', '\x7C', '\xdf', '\xd9', '\xd7', '\xbd', '\xbb'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 1E-10); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\xc2', '\x02', '\xa0', '\x5f', '\x20', '\x00', '\x00', '\x00'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), -1E10); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\xbd', '\xdb', '\x7c', '\xdf', '\xd9', '\xd7', '\xbd', '\xbb'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), -1E-10); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x42', '\x06', '\xfc', '\x2b', '\xa8', '\x00', '\x00', '\x00'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 1.234E+10); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x3d', '\xe0', '\xf5', '\xc0', '\x63', '\x56', '\x43', '\xa8'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 1.234E-10); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x7f', '\xef', '\xff', '\xfc', '\x57', '\xca', '\x82', '\xae'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 1.79769e+308); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x00', '\x0f', '\xff', '\xfe', '\x2e', '\x81', '\x59', '\xd0'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 2.22507e-308); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\xff', '\xef', '\xff', '\xfc', '\x57', '\xca', '\x82', '\xae'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), -1.79769e+308); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x80', '\x0f', '\xff', '\xfe', '\x2e', '\x81', '\x59', '\xd0'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), -2.22507e-308); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x80', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x01'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), -4.9406564584124654e-324); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x00', '\x0f', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 2.2250738585072009e-308); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x00', '\x10', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 2.2250738585072014e-308); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x7f', '\xef', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 1.7976931348623157e+308); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 0.0); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x3f', '\xef', '\x93', '\xe0', '\x00', '\x00', '\x00', '\x00'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 0.9868011474609375); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x47', '\x6d', '\x9c', '\x75', '\xd3', '\xac', '\x07', '\x2b'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 123e34); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x44', '\x03', '\xe9', '\x61', '\xfa', '\x3b', '\xa6', '\xa0'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 45913141877270640000.0); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x00', '\x0f', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 2.2250738585072011e-308); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 0.0); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 0.0); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x7f', '\xef', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 1.7976931348623157e+308); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x00', '\x10', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 2.2250738585072014e-308); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x3f', '\xf0', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 1.0); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x3f', '\xef', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 0.99999999999999989); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x3f', '\xf0', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 1.0); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x3f', '\xf0', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 1.0); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x3f', '\xf0', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 1.0); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x3f', '\xf0', '\x00', '\x00', '\x00', '\x00', '\x00', '\x01'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 1.00000000000000022); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x43', '\x6f', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 72057594037927928.0); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x43', '\x70', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 72057594037927936.0); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x43', '\x70', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 72057594037927936.0); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x43', '\x6f', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 72057594037927928.0); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x43', '\x70', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 72057594037927936.0); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x43', '\xdf', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 9223372036854774784.0); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x43', '\xe0', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 9223372036854775808.0); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x43', '\xe0', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 9223372036854775808.0); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x43', '\xdf', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 9223372036854774784.0); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x43', '\xe0', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 9223372036854775808.0); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x46', '\x5f', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 10141204801825834086073718800384.0); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x46', '\x60', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 10141204801825835211973625643008.0); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x49', '\x6f', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 5708990770823838890407843763683279797179383808.0); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x49', '\x70', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 5708990770823839524233143877797980545530986496.0); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x00', '\x10', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isDouble ()); EXPECT_EQ (value[0].getDouble (), 2.2250738585072014e-308); } /** * @brief Test JSON parse string. */ TEST (PackReader, str) { std::stringstream stream; Value value; stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xa0'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isString ()); EXPECT_STREQ (value[0].getString ().c_str (), ""); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xa5', '\x48', '\x65', '\x6c', '\x6c', '\x6f'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isString ()); EXPECT_STREQ (value[0].getString ().c_str (), "Hello"); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xab', '\x48', '\x65', '\x6c', '\x6c', '\x6f', '\x0a', '\x57', '\x6f', '\x72', '\x6c', '\x64'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isString ()); EXPECT_STREQ (value[0].getString ().c_str (), "Hello\nWorld"); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xab', '\x48', '\x65', '\x6c', '\x6c', '\x6f', '\x00', '\x57', '\x6f', '\x72', '\x6c', '\x64'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isString ()); EXPECT_STREQ (value[0].getString ().c_str (), "Hello\0World"); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xa8', '\x22', '\x5c', '\x2f', '\x08', '\x0c', '\x0a', '\x0d', '\x09'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isString ()); EXPECT_STREQ (value[0].getString ().c_str (), "\"\\/\b\f\n\r\t"); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xa1', '\x24'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isString ()); EXPECT_STREQ (value[0].getString ().c_str (), "\x24"); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xa2', '\xc2', '\xa2'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isString ()); EXPECT_STREQ (value[0].getString ().c_str (), "\xC2\xA2"); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xa3', '\xe2', '\x82', '\xac'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isString ()); EXPECT_STREQ (value[0].getString ().c_str (), "\xE2\x82\xAC"); stream.clear (); stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xa4', '\xf0', '\x9d', '\x84', '\x9e'})); ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message (); ASSERT_TRUE (value.isArray ()); ASSERT_FALSE (value.empty ()); ASSERT_TRUE (value[0].isString ()); EXPECT_STREQ (value[0].getString ().c_str (), "\xF0\x9D\x84\x9E"); } /** * @brief main function. */ int main (int argc, char **argv) { testing::InitGoogleTest (&argc, argv); return RUN_ALL_TESTS (); }
53.659681
194
0.541168
mrabine
aa7c59166aa6c18afa7647f939283201e04d1acc
1,155
hpp
C++
test/core/fakes/util_fake_string.hpp
pit-ray/win-vind
7386f6f7528d015ce7f1a5ae230d6e63f9492df9
[ "MIT" ]
731
2020-05-07T06:22:59.000Z
2022-03-31T16:36:03.000Z
test/core/fakes/util_fake_string.hpp
pit-ray/win-vind
7386f6f7528d015ce7f1a5ae230d6e63f9492df9
[ "MIT" ]
67
2020-07-20T19:46:42.000Z
2022-03-31T15:34:47.000Z
test/core/fakes/util_fake_string.hpp
pit-ray/win-vind
7386f6f7528d015ce7f1a5ae230d6e63f9492df9
[ "MIT" ]
15
2021-01-29T04:49:11.000Z
2022-03-04T22:16:31.000Z
#ifndef _UTIL_FAKE_STRING_HPP #define _UTIL_FAKE_STRING_HPP #include "util/string.hpp" #include <cstring> #include <cwchar> #include <string> namespace vind { namespace util { // // The output string of std::wstring is the fake converted string. // It is the same bytes as before-string. // std::wstring s_to_ws(const std::string& str) { std::wstring fakestr ; fakestr.resize(str.size()) ; std::memcpy(fakestr.data(), str.data(), sizeof(char) * str.size()) ; return fakestr ; } std::string ws_to_s(const std::wstring& wstr) { std::string out ; out.resize(wstr.length()) ; return out ; } } } // stub function namespace { std::string from_fake_wstr(const std::wstring& str) { std::string truestr{} ; auto expected_true_str_length = sizeof(wchar_t) * str.capacity() ; truestr.resize(expected_true_str_length) ; std::memcpy(truestr.data(), str.data(), expected_true_str_length) ; return truestr ; } } #endif
26.860465
81
0.571429
pit-ray
aa838803d3c90f97d190a710bf84c303df627919
4,477
hpp
C++
frontend/services/lua_service_wrapper/Lua_Service_Wrapper.hpp
xge/megamol
1e298dd3d8b153d7468ed446f6b2ed3ac49f0d5b
[ "BSD-3-Clause" ]
49
2017-08-23T13:24:24.000Z
2022-03-16T09:10:58.000Z
frontend/services/lua_service_wrapper/Lua_Service_Wrapper.hpp
xge/megamol
1e298dd3d8b153d7468ed446f6b2ed3ac49f0d5b
[ "BSD-3-Clause" ]
200
2018-07-20T15:18:26.000Z
2022-03-31T11:01:44.000Z
frontend/services/lua_service_wrapper/Lua_Service_Wrapper.hpp
xge/megamol
1e298dd3d8b153d7468ed446f6b2ed3ac49f0d5b
[ "BSD-3-Clause" ]
31
2017-07-31T16:19:29.000Z
2022-02-14T23:41:03.000Z
/* * Lua_Service_Wrapper.hpp * * Copyright (C) 2020 by MegaMol Team * Alle Rechte vorbehalten. */ #pragma once #include "AbstractFrontendService.hpp" #include "ScriptPaths.h" #include "mmcore/LuaAPI.h" #include "LuaCallbacksCollection.h" namespace megamol { namespace frontend { // the Lua Service Wrapper wraps the LuaAPI for use as a frontend service // the main problem this wrapper addresses is the requirement that Lua scripts // want to issue a "render frame" (mmFlush, mmRenderNextFrame) command that needs to be executed as a callback in the Lua context, // the flush has to advance the rendering for one frame, which is the job of the main loop // but since Lua is itself part of the main loop there arises the problem of Lua recursively calling itself // // thus the LuaAPI has two conflicting goals: // 1) we want it to be a frontend service like all other services // 2) it (sometimes) needs to take control of the megamol main loop and issue a series of frame flushes from inside a // Lua callback, without recursively calling itself // // this wrapper solves this issue by recognizing when it is executed from inside a Lua callback // if executed from the normal main loop, the wrapper executes lua // if executed from inside the lua frame flush callback, it does not call the wrapped LuaAPI object, thus eliminating // risk of recursive Lua calls // // also, the wrapper manages communication with the lua remote console by // receiving lua requests and executing them via the wrapped LuaAPI object // the multithreaded ZMQ networking logic is implemented in LuaHostService.h in the core class Lua_Service_Wrapper final : public AbstractFrontendService { public: struct Config { std::string host_address; megamol::core::LuaAPI* lua_api_ptr = nullptr; // lua api object that will be used/called by the service wrapper only one level deep bool retry_socket_port = false; bool show_version_notification = true; }; // sometimes somebody wants to know the name of the service std::string serviceName() const override { return "Lua_Service_Wrapper"; } // constructor should not take arguments, actual object initialization deferred until init() Lua_Service_Wrapper(); ~Lua_Service_Wrapper(); // your service will be constructed and destructed, but not copy-constructed or move-constructed // so no need to worry about copy or move constructors. // init service with input config data, e.g. init GLFW with OpenGL and open window with certain decorations/hints // if init() fails return false (this will terminate program execution), on success return true bool init(const Config& config); bool init(void* configPtr) override; void close() override; std::vector<FrontendResource>& getProvidedResources() override; const std::vector<std::string> getRequestedResourceNames() const override; void setRequestedResources(std::vector<FrontendResource> resources) override; void updateProvidedResources() override; void digestChangedRequestedResources() override; void resetProvidedResources() override; void preGraphRender() override; void postGraphRender() override; // int setPriority(const int p) // priority initially 0 // int getPriority() const; // bool shouldShutdown() const; // shutdown initially false // void setShutdown(const bool s = true); private: Config m_config; int m_service_recursion_depth = 0; // auto-deleted opaque ZMQ networking object from LuaHostService.h std::unique_ptr<void, std::function<void(void*)>> m_network_host_pimpl; std::vector<FrontendResource> m_providedResourceReferences; std::vector<std::string> m_requestedResourcesNames; std::vector<FrontendResource> m_requestedResourceReferences; std::list<megamol::frontend_resources::LuaCallbacksCollection> m_callbacks; megamol::frontend_resources::ScriptPaths m_scriptpath_resource; std::function<std::tuple<bool, std::string>(std::string const&)> m_executeLuaScript_resource; std::function<void(std::string const&)> m_setScriptPath_resource; std::function<void(megamol::frontend_resources::LuaCallbacksCollection const&)> m_registerLuaCallbacks_resource; void fill_frontend_resources_callbacks(void* callbacks_collection_ptr); void fill_graph_manipulation_callbacks(void* callbacks_collection_ptr); }; } // namespace frontend } // namespace megamol
41.841121
130
0.755193
xge
aa88b67294f221a8b29910587df848b66fafbbe6
936
hpp
C++
LinearAlgebra/operation/equal/equal.hpp
suiyili/Algorithms
d6ddc8262c5d681ecc78938b6140510793a29d91
[ "MIT" ]
null
null
null
LinearAlgebra/operation/equal/equal.hpp
suiyili/Algorithms
d6ddc8262c5d681ecc78938b6140510793a29d91
[ "MIT" ]
null
null
null
LinearAlgebra/operation/equal/equal.hpp
suiyili/Algorithms
d6ddc8262c5d681ecc78938b6140510793a29d91
[ "MIT" ]
null
null
null
#pragma once #include "equal.h" #include "operation/utility.hpp" #include <type_traits> #include <cmath> namespace algebra::arithmetic { template <typename T> inline bool are_equal(const algebra_vector<T> &left, const algebra_vector<T> &right) { ensure_match(left, right); if constexpr (std::is_floating_point_v<T>) return std::abs((left - right).min()) < epsilon<T>; else return (left == right).min(); } template <typename T> inline bool operator==(const matrix<T> &left, const matrix<T> &right) { ensure_match(left, right); for (size_t i = 0U; i < left.columns(); ++i) { for (size_t j = 0U; j < left.rows(); ++j) { pixel id{i, j}; if constexpr (std::is_integral_v<T>) { if (left[id] != right[id]) return false; } else { if (epsilon<T> <= std::abs(left[id] - right[id])) return false; } } } return true; } } // namespace algebra::arithmetic
26
86
0.617521
suiyili
aa895fed680a6d5af9e6b8fd0ebc1a0f60d95832
1,192
cpp
C++
CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/Lab7(Array Based Queue)/quetype(2).cpp
diptu/Teaching
20655bb2c688ae29566b0a914df4a3e5936a2f61
[ "MIT" ]
null
null
null
CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/Lab7(Array Based Queue)/quetype(2).cpp
diptu/Teaching
20655bb2c688ae29566b0a914df4a3e5936a2f61
[ "MIT" ]
null
null
null
CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/Lab7(Array Based Queue)/quetype(2).cpp
diptu/Teaching
20655bb2c688ae29566b0a914df4a3e5936a2f61
[ "MIT" ]
null
null
null
#include"quetype.h" #include <iostream> using namespace std; template<class ItemType> QueType<ItemType>::QueType(int max) { maxQue=max+1; front=maxQue-1; rear=maxQue-1; items=new ItemType[maxQue]; } template<class ItemType> QueType<ItemType>::QueType() { maxQue=501; front=maxQue-1; rear=maxQue-1; items=new ItemType[maxQue]; } template<class ItemType> QueType<ItemType>::~QueType() { delete [] items; } template<class ItemType> void QueType<ItemType>::MakeEmpty() { front=maxQue-1; rear=maxQue-1; } template<class ItemType> bool QueType<ItemType>::IsEmpty() { return (front==rear); } template<class ItemType> bool QueType<ItemType>::IsFull() { return (((rear+1)%maxQue==front)); } template<class ItemType> void QueType<ItemType>::Enqueue(ItemType newItem) { try { if(IsFull()) throw FullQueue(); rear=(rear+1)%maxQue; items[rear]=newItem; } catch(FullQueue f) { cout<<"Queue Overflow"<<endl; } } template<class ItemType> void QueType<ItemType>::Dequeue(ItemType& item) { if(IsEmpty()) throw EmptyQueue(); front=(front+1)%maxQue; item=items[front]; }
16.328767
49
0.647651
diptu
aa8a6dd9e66a1cc30715a03dc91c0460308b3560
14,899
hpp
C++
src/Core/CommandBuffer.hpp
Shmaug/Stratum
036eccb824867b019c6ed3c589cfb171e9350c0c
[ "MIT" ]
4
2019-12-13T19:29:39.000Z
2022-02-15T05:51:47.000Z
src/Core/CommandBuffer.hpp
Shmaug/Stratum
036eccb824867b019c6ed3c589cfb171e9350c0c
[ "MIT" ]
2
2020-04-08T19:59:31.000Z
2021-06-14T04:29:42.000Z
src/Core/CommandBuffer.hpp
Shmaug/Stratum
036eccb824867b019c6ed3c589cfb171e9350c0c
[ "MIT" ]
4
2020-03-03T01:29:10.000Z
2022-02-15T05:51:52.000Z
#pragma once #include "Fence.hpp" #include "Framebuffer.hpp" #include "Pipeline.hpp" #include <Common/Profiler.hpp> namespace stm { class CommandBuffer : public DeviceResource { public: // assumes a CommandPool has been created for this_thread in queueFamily STRATUM_API CommandBuffer(Device& device, const string& name, Device::QueueFamily* queueFamily, vk::CommandBufferLevel level = vk::CommandBufferLevel::ePrimary); STRATUM_API ~CommandBuffer(); inline vk::CommandBuffer& operator*() { return mCommandBuffer; } inline vk::CommandBuffer* operator->() { return &mCommandBuffer; } inline const vk::CommandBuffer& operator*() const { return mCommandBuffer; } inline const vk::CommandBuffer* operator->() const { return &mCommandBuffer; } inline Fence& completion_fence() const { return *mCompletionFence; } inline Device::QueueFamily* queue_family() const { return mQueueFamily; } inline const shared_ptr<Framebuffer>& bound_framebuffer() const { return mBoundFramebuffer; } inline uint32_t subpass_index() const { return mSubpassIndex; } inline const shared_ptr<Pipeline>& bound_pipeline() const { return mBoundPipeline; } inline const shared_ptr<DescriptorSet>& bound_descriptor_set(uint32_t index) const { return mBoundDescriptorSets[index]; } // Label a region for a tool such as RenderDoc STRATUM_API void begin_label(const string& label, const Array4f& color = { 1,1,1,0 }); STRATUM_API void end_label(); STRATUM_API void reset(const string& name = "Command Buffer"); inline bool clear_if_done() { if (mState == CommandBufferState::eInFlight) if (mCompletionFence->status() == vk::Result::eSuccess) { mState = CommandBufferState::eDone; clear(); return true; } return mState == CommandBufferState::eDone; } // Add a resource to the device's resource pool after this commandbuffer finishes executing template<derived_from<DeviceResource> T> inline T& hold_resource(const shared_ptr<T>& r) { r->mTracking.emplace(this); return *static_cast<T*>(mHeldResources.emplace( static_pointer_cast<DeviceResource>(r) ).first->get()); } template<typename T> inline const Buffer::View<T>& hold_resource(const Buffer::View<T>& v) { hold_resource(v.buffer()); return v; } inline const Buffer::TexelView& hold_resource(const Buffer::TexelView& v) { hold_resource(v.buffer()); return v; } inline const Buffer::StrideView& hold_resource(const Buffer::StrideView& v) { hold_resource(v.buffer()); return v; } inline const Image::View& hold_resource(const Image::View& v) { hold_resource(v.image()); return v; } inline void barrier(const vk::ArrayProxy<const vk::MemoryBarrier>& b, vk::PipelineStageFlags srcStage, vk::PipelineStageFlags dstStage) { mCommandBuffer.pipelineBarrier(srcStage, dstStage, {}, b, {}, {}); } inline void barrier(const vk::ArrayProxy<const vk::BufferMemoryBarrier>& b, vk::PipelineStageFlags srcStage, vk::PipelineStageFlags dstStage) { mCommandBuffer.pipelineBarrier(srcStage, dstStage, {}, {}, b, {}); } inline void barrier(const vk::ArrayProxy<const vk::ImageMemoryBarrier>& b, vk::PipelineStageFlags srcStage, vk::PipelineStageFlags dstStage) { mCommandBuffer.pipelineBarrier(srcStage, dstStage, {}, {}, {}, b); } template<typename T = byte> inline void barrier(const Buffer::View<T>& buffer, vk::PipelineStageFlags srcStage, vk::AccessFlags srcAccessMask, vk::PipelineStageFlags dstStage, vk::AccessFlags dstAccessMask) { barrier(vk::BufferMemoryBarrier(srcAccessMask, dstAccessMask, VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED, **buffer.buffer(), buffer.offset(), buffer.size_bytes()), srcStage, dstStage); } template<typename T = byte, typename S = T> inline const Buffer::View<S>& copy_buffer(const Buffer::View<T>& src, const Buffer::View<S>& dst) { if (src.size_bytes() > dst.size_bytes()) throw invalid_argument("src size must be less than or equal to dst size"); mCommandBuffer.copyBuffer(*hold_resource(src.buffer()), *hold_resource(dst.buffer()), { vk::BufferCopy(src.offset(), dst.offset(), src.size_bytes()) }); return dst; } template<typename T = byte> inline Buffer::View<T> copy_buffer(const Buffer::View<T>& src, vk::BufferUsageFlagBits bufferUsage, VmaMemoryUsage memoryUsage = VMA_MEMORY_USAGE_GPU_ONLY) { shared_ptr<Buffer> dst = make_shared<Buffer>(mDevice, src.buffer()->name(), src.size_bytes(), bufferUsage|vk::BufferUsageFlagBits::eTransferDst, memoryUsage); mCommandBuffer.copyBuffer(*hold_resource(src.buffer()), *hold_resource(dst), { vk::BufferCopy(src.offset(), 0, src.size_bytes()) }); return Buffer::View<T>(dst); } template<typename T = byte> inline Buffer::View<T> copy_buffer(const buffer_vector<T>& src, vk::BufferUsageFlagBits bufferUsage, VmaMemoryUsage memoryUsage = VMA_MEMORY_USAGE_GPU_ONLY) { shared_ptr<Buffer> dst = make_shared<Buffer>(mDevice, src.buffer()->name(), src.size_bytes(), bufferUsage|vk::BufferUsageFlagBits::eTransferDst, memoryUsage); mCommandBuffer.copyBuffer(*hold_resource(src.buffer()), *hold_resource(dst), { vk::BufferCopy(0, 0, src.size_bytes()) }); return Buffer::View<T>(dst); } inline const Image::View& clear_color_image(const Image::View& img, const vk::ClearColorValue& clear) { img.transition_barrier(*this, vk::ImageLayout::eTransferDstOptimal); mCommandBuffer.clearColorImage(*hold_resource(img.image()), vk::ImageLayout::eTransferDstOptimal, clear, img.subresource_range()); return img; } inline const Image::View& clear_color_image(const Image::View& img, const vk::ClearDepthStencilValue& clear) { img.transition_barrier(*this, vk::ImageLayout::eTransferDstOptimal); mCommandBuffer.clearDepthStencilImage(*hold_resource(img.image()), vk::ImageLayout::eTransferDstOptimal, clear, img.subresource_range()); return img; } inline const Image::View& blit_image(const Image::View& src, const Image::View& dst, vk::Filter filter = vk::Filter::eLinear) { src.transition_barrier(*this, vk::ImageLayout::eTransferSrcOptimal); dst.transition_barrier(*this, vk::ImageLayout::eTransferDstOptimal); vector<vk::ImageBlit> blits(src.subresource_range().levelCount); for (uint32_t i = 0; i < blits.size(); i++) { array<vk::Offset3D,2> srcOffset; srcOffset[1].x = src.extent().width; srcOffset[1].y = src.extent().height; srcOffset[1].z = src.extent().depth; array<vk::Offset3D,2> dstOffset; dstOffset[1].x = dst.extent().width; dstOffset[1].y = dst.extent().height; dstOffset[1].z = dst.extent().depth; blits[i] = vk::ImageBlit(src.subresource(i), srcOffset, src.subresource(i), dstOffset); } mCommandBuffer.blitImage(*hold_resource(src.image()), vk::ImageLayout::eTransferSrcOptimal, *hold_resource(dst.image()), vk::ImageLayout::eTransferDstOptimal, blits, filter); return dst; } inline const Image::View& copy_image(const Image::View& src, const Image::View& dst) { src.transition_barrier(*this, vk::ImageLayout::eTransferSrcOptimal); dst.transition_barrier(*this, vk::ImageLayout::eTransferDstOptimal); vector<vk::ImageCopy> copies(src.subresource_range().levelCount); for (uint32_t i = 0; i < copies.size(); i++) copies[i] = vk::ImageCopy(src.subresource(i), vk::Offset3D{}, src.subresource(i), vk::Offset3D{}, src.extent()); mCommandBuffer.copyImage(*hold_resource(src.image()), vk::ImageLayout::eTransferSrcOptimal, *hold_resource(dst.image()), vk::ImageLayout::eTransferDstOptimal, copies); return dst; } inline const Image::View& resolve_image(const Image::View& src, const Image::View& dst) { src.transition_barrier(*this, vk::ImageLayout::eTransferSrcOptimal); dst.transition_barrier(*this, vk::ImageLayout::eTransferDstOptimal); vector<vk::ImageResolve> resolves(src.subresource_range().levelCount); for (uint32_t i = 0; i < resolves.size(); i++) resolves[i] = vk::ImageResolve(src.subresource(i), vk::Offset3D{}, src.subresource(i), vk::Offset3D{}, src.extent()); mCommandBuffer.resolveImage(*hold_resource(src.image()), vk::ImageLayout::eTransferSrcOptimal, *hold_resource(dst.image()), vk::ImageLayout::eTransferDstOptimal, resolves); return dst; } template<typename T = byte> inline const Image::View& copy_buffer_to_image(const Buffer::View<T>& src, const Image::View& dst) { vector<vk::BufferImageCopy> copies(dst.subresource_range().levelCount); for (uint32_t i = 0; i < dst.subresource_range().levelCount; i++) copies[i] = vk::BufferImageCopy(src.offset(), 0, 0, dst.subresource(i), {}, dst.extent()); dst.transition_barrier(*this, vk::ImageLayout::eTransferDstOptimal); mCommandBuffer.copyBufferToImage(*hold_resource(src.buffer()), *hold_resource(dst.image()), vk::ImageLayout::eTransferDstOptimal, copies); return dst; } inline void dispatch(const vk::Extent2D& dim) { mCommandBuffer.dispatch(dim.width, dim.height, 1); } inline void dispatch(const vk::Extent3D& dim) { mCommandBuffer.dispatch(dim.width, dim.height, dim.depth); } inline void dispatch(uint32_t x, uint32_t y=1, uint32_t z=1) { mCommandBuffer.dispatch(x, y, z); } // dispatch on ceil(size / workgroupSize) inline void dispatch_over(const vk::Extent2D& dim) { auto cp = dynamic_pointer_cast<ComputePipeline>(mBoundPipeline); mCommandBuffer.dispatch( (dim.width + cp->workgroup_size()[0] - 1) / cp->workgroup_size()[0], (dim.height + cp->workgroup_size()[1] - 1) / cp->workgroup_size()[1], 1); } inline void dispatch_over(const vk::Extent3D& dim) { auto cp = dynamic_pointer_cast<ComputePipeline>(mBoundPipeline); mCommandBuffer.dispatch( (dim.width + cp->workgroup_size()[0] - 1) / cp->workgroup_size()[0], (dim.height + cp->workgroup_size()[1] - 1) / cp->workgroup_size()[1], (dim.depth + cp->workgroup_size()[2] - 1) / cp->workgroup_size()[2]); } inline void dispatch_over(uint32_t x, uint32_t y = 1, uint32_t z = 1) { return dispatch_over(vk::Extent3D(x,y,z)); } STRATUM_API void begin_render_pass(const shared_ptr<RenderPass>& renderPass, const shared_ptr<Framebuffer>& framebuffer, const vk::Rect2D& renderArea, const vk::ArrayProxyNoTemporaries<const vk::ClearValue>& clearValues, vk::SubpassContents contents = vk::SubpassContents::eInline); STRATUM_API void next_subpass(vk::SubpassContents contents = vk::SubpassContents::eInline); STRATUM_API void end_render_pass(); inline bool bind_pipeline(const shared_ptr<Pipeline>& pipeline) { if (mBoundPipeline == pipeline) return false; mCommandBuffer.bindPipeline(pipeline->bind_point(), **pipeline); mBoundPipeline = pipeline; hold_resource(pipeline); return true; } template<typename T> inline void push_constant(const string& name, const T& value) { auto it = mBoundPipeline->push_constants().find(name); if (it == mBoundPipeline->push_constants().end()) throw invalid_argument("push constant not found"); const auto& range = it->second; if constexpr (ranges::contiguous_range<T>) { if (range.size != ranges::size(value)*sizeof(ranges::range_value_t<T>)) throw invalid_argument("argument size must match push constant size (" + to_string(range.size) +")"); mCommandBuffer.pushConstants(mBoundPipeline->layout(), range.stageFlags, range.offset, range.size, ranges::data(value)); } else { if (range.size != sizeof(T)) throw invalid_argument("argument size must match push constant size (" + to_string(range.size) +")"); mCommandBuffer.pushConstants(mBoundPipeline->layout(), range.stageFlags, range.offset, sizeof(T), &value); } } STRATUM_API void bind_descriptor_set(uint32_t index, const shared_ptr<DescriptorSet>& descriptorSet, const vk::ArrayProxy<const uint32_t>& dynamicOffsets); inline void bind_descriptor_set(uint32_t index, const shared_ptr<DescriptorSet>& descriptorSet) { if (index < mBoundDescriptorSets.size() && mBoundDescriptorSets[index] == descriptorSet) return; bind_descriptor_set(index, descriptorSet, {}); } template<typename T=byte> inline void bind_vertex_buffer(uint32_t index, const Buffer::View<T>& view) { auto& b = mBoundVertexBuffers[index]; if (b != view) { b = view; mCommandBuffer.bindVertexBuffers(index, **view.buffer(), view.offset()); hold_resource(view); } } template<ranges::input_range R> inline void bind_vertex_buffers(uint32_t index, const R& views) { vector<vk::Buffer> bufs(views.size()); vector<vk::DeviceSize> offsets(views.size()); bool needBind = false; uint32_t i = 0; for (const auto& v : views) { bufs[i] = **v.buffer(); offsets[i] = v.offset(); if (mBoundVertexBuffers[index + i] != v) { needBind = true; mBoundVertexBuffers[index + i] = v; hold_resource(v); } i++; } if (needBind) mCommandBuffer.bindVertexBuffers(index, bufs, offsets); } inline void bind_index_buffer(const Buffer::StrideView& view) { if (mBoundIndexBuffer != view) { mBoundIndexBuffer = view; vk::IndexType type; if (view.stride() == sizeof(uint32_t)) type = vk::IndexTypeValue<uint32_t>::value; else if (view.stride() == sizeof(uint16_t)) type = vk::IndexTypeValue<uint16_t>::value; else if (view.stride() == sizeof(uint8_t)) type = vk::IndexTypeValue<uint8_t>::value; else throw invalid_argument("invalid stride for index buffer"); mCommandBuffer.bindIndexBuffer(**view.buffer(), view.offset(), type); hold_resource(view); } } inline Buffer::View<byte> current_vertex_buffer(uint32_t index) { auto it = mBoundVertexBuffers.find(index); if (it == mBoundVertexBuffers.end()) return {}; else return it->second; } inline const Buffer::StrideView& current_index_buffer() { return mBoundIndexBuffer; } size_t mPrimitiveCount; private: friend class Device; enum class CommandBufferState { eRecording, eInFlight, eDone }; STRATUM_API void clear(); vk::CommandBuffer mCommandBuffer; Device::QueueFamily* mQueueFamily; vk::CommandPool mCommandPool; CommandBufferState mState; unique_ptr<Fence> mCompletionFence; unordered_set<shared_ptr<DeviceResource>> mHeldResources; // Currently bound objects shared_ptr<Framebuffer> mBoundFramebuffer; uint32_t mSubpassIndex = 0; shared_ptr<Pipeline> mBoundPipeline = nullptr; unordered_map<uint32_t, Buffer::View<byte>> mBoundVertexBuffers; Buffer::StrideView mBoundIndexBuffer; vector<shared_ptr<DescriptorSet>> mBoundDescriptorSets; }; inline bool DeviceResource::in_use() { while (!mTracking.empty()) { if (!(*mTracking.begin())->clear_if_done()) return true; } return !mTracking.empty(); } class ProfilerRegion { private: CommandBuffer* mCommandBuffer; public: inline ProfilerRegion(const string& label) : ProfilerRegion(label, nullptr) {} inline ProfilerRegion(const string& label, CommandBuffer& cmd) : ProfilerRegion(label, &cmd) {} inline ProfilerRegion(const string& label, CommandBuffer* cmd) : mCommandBuffer(cmd) { Profiler::begin_sample(label); if (mCommandBuffer) mCommandBuffer->begin_label(label); } inline ~ProfilerRegion() { if (mCommandBuffer) mCommandBuffer->end_label(); Profiler::end_sample(); } }; }
47.906752
283
0.739177
Shmaug
aa8af9ea3459db52b692e8c8a1708ae27e1f1964
346
cpp
C++
docs/atl-mfc-shared/reference/codesnippet/CPP/cfile-class_12.cpp
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
965
2017-06-25T23:57:11.000Z
2022-03-31T14:17:32.000Z
docs/atl-mfc-shared/reference/codesnippet/CPP/cfile-class_12.cpp
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
3,272
2017-06-24T00:26:34.000Z
2022-03-31T22:14:07.000Z
docs/atl-mfc-shared/reference/codesnippet/CPP/cfile-class_12.cpp
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
951
2017-06-25T12:36:14.000Z
2022-03-26T22:49:06.000Z
//example for CFile::Remove TCHAR* pFileName = _T("Remove_File.dat"); try { CFile::Remove(pFileName); } catch (CFileException* pEx) { TRACE(_T("File %20s cannot be removed\n"), pFileName); pEx->Delete(); }
31.454545
69
0.416185
bobbrow
aa8c47b70bc69e0039c64ad542d5321b16783173
7,906
cpp
C++
ChaosEngine/MaterialImporter.cpp
adrianam4/Chaos-Engine
2bc5693c0c25118ec58331c4311eac68c94d4d19
[ "MIT" ]
null
null
null
ChaosEngine/MaterialImporter.cpp
adrianam4/Chaos-Engine
2bc5693c0c25118ec58331c4311eac68c94d4d19
[ "MIT" ]
null
null
null
ChaosEngine/MaterialImporter.cpp
adrianam4/Chaos-Engine
2bc5693c0c25118ec58331c4311eac68c94d4d19
[ "MIT" ]
null
null
null
#include "Application.h" #include "MaterialImporter.h" #include "ResourceMaterial.h" #include "DevIL/include/il.h" #include "DevIL/include/ilu.h" #include "DevIL/include/ilut.h" #include <string> MaterialImporter::MaterialImporter() { } MaterialImporter::~MaterialImporter() { } void MaterialImporter::SaveMaterial(std::string sourcePath, std::string compression) { ILuint size; ILubyte* data; ILint compressionMethod = IL_DXT5; if (compression == "IL_DXT_NO_COMP") compressionMethod = IL_DXT_NO_COMP; if (compression == "IL_DXT1") compressionMethod = IL_DXT1; if (compression == "IL_DXT2") compressionMethod = IL_DXT2; if (compression == "IL_DXT3") compressionMethod = IL_DXT3; if (compression == "IL_DXT4") compressionMethod = IL_DXT4; if (compression == "IL_DXT5") compressionMethod = IL_DXT5; ilSetInteger(IL_DXTC_FORMAT, compressionMethod); size = ilSaveL(IL_DDS, nullptr, 0); std::string auxPath = std::string(sourcePath); unsigned auxCreateLast = auxPath.find_last_of("."); std::string auxCreatePath = auxPath.substr(auxCreateLast, auxPath.length() - auxCreateLast); if (auxCreatePath != ".dds") { unsigned start = auxPath.find_last_of("\\"); if (start > 10000) start = auxPath.find_last_of("/"); auxPath = "Library/Textures/" + auxPath.substr(start + 1, auxPath.length() - start - 4) + "dds"; if (size > 0) { data = new ILubyte[size]; if (ilSaveL(IL_DDS, data, size) > 0) App->fileSystem->Save(auxPath.c_str(), data, size); delete[] data; } } ddsPath = auxPath; } std::vector<int> MaterialImporter::ImportMaterial(std::string sourcePath, bool isDropped, ResourceMatertial* resource) { std::vector<int> toReturn; ILboolean success; glGenTextures(1, &textId); glBindTexture(GL_TEXTURE_2D, textId); toReturn.push_back(textId); ilGenImages(1, &imageId); ilBindImage(imageId); success = ilLoadImage(sourcePath.c_str()); if (resource != nullptr) { SaveMaterial(sourcePath.c_str(), resource->metaData.compression); if (resource->metaData.mipMap) iluBuildMipmaps(); if (resource->metaData.alienifying) iluAlienify(); if (resource->metaData.avgBlurring) iluBlurAvg(resource->metaData.amountAvBlur); if (resource->metaData.gausianBlurring) iluBlurGaussian(resource->metaData.amountGausianBlur); if (resource->metaData.contrast) iluContrast(resource->metaData.amountContrast); if (resource->metaData.equalization) iluEqualize(); if (resource->metaData.gammaCorrection) iluGammaCorrect(resource->metaData.amountGammaCorrection); if (resource->metaData.negativity) iluNegative(); if (resource->metaData.noise) iluNoisify(resource->metaData.amountNoise); if (resource->metaData.pixelization) iluPixelize(resource->metaData.amountPixelation); if (resource->metaData.sharpering) iluSharpen(resource->metaData.sharpenFactor, resource->metaData.sharpenIters); } else SaveMaterial(sourcePath.c_str(), "IL_DXT5"); w = ilGetInteger(IL_IMAGE_WIDTH); h = ilGetInteger(IL_IMAGE_HEIGHT); toReturn.push_back(w); toReturn.push_back(h); if (success) { success = ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE); if (!success) { std::cout << "Could not convert image :: " << sourcePath << std::endl; ilDeleteImages(1, &imageId); } } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); data = ilGetData(); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); glBindTexture(GL_TEXTURE_2D, 0); unsigned start = sourcePath.find_last_of("."); if (sourcePath.substr(start,sourcePath.length()-start) != ".dds") { glDeleteTextures(1, &textId); } ilDeleteImages(1, &imageId); int toFound; int a; if (!isDropped) { for (a = 0; a < App->renderer3D->models.size(); a++) { if (App->editor->objectSelected->id == App->renderer3D->models[a].id) { for (int b = 0; b < App->renderer3D->models[a].meshes.size(); b++) { glDeleteTextures(1, &App->renderer3D->models[a].meshes[b].textureId); ilDeleteImages(1, &imageId); App->renderer3D->models[a].meshes[b].textureId = textId; } break; } } } if (isDropped) { toFound = App->editor->objectSelected->SearchComponent(App->editor->objectSelected, ComponentType::CUBE); if (toFound != -1) { for (a = 0; a < App->scene->gameObjects.size() - 1; a++) { if (App->editor->objectSelected->id == App->editor->cubes[a]->id) { break; } } glDeleteTextures(1, &App->editor->cubes[a]->aTextureId); ilDeleteImages(1, &App->editor->cubes[a]->imageID); App->editor->cubes[a]->aTextureId = textId; } else { toFound = App->editor->objectSelected->SearchComponent(App->editor->objectSelected, ComponentType::CYLINDER); if (toFound != -1) { for (a = 0; a < App->scene->gameObjects.size() - 1; a++) { if (App->editor->objectSelected->id == App->editor->cylinders[a]->id) { break; } } glDeleteTextures(1, &App->editor->cylinders[a]->aTextureId); ilDeleteImages(1, &App->editor->cylinders[a]->imageID); App->editor->cylinders[a]->aTextureId = textId; } else { toFound = App->editor->objectSelected->SearchComponent(App->editor->objectSelected, ComponentType::PYRAMID); if (toFound != -1) { for (a = 0; a < App->scene->gameObjects.size() - 1; a++) { if (App->editor->objectSelected->id == App->editor->pyramids[a]->id) { break; } } glDeleteTextures(1, &App->editor->pyramids[a]->aTextureId); ilDeleteImages(1, &App->editor->pyramids[a]->imageID); App->editor->pyramids[a]->aTextureId = textId; } else { toFound = App->editor->objectSelected->SearchComponent(App->editor->objectSelected, ComponentType::SPHERE); if (toFound != -1) { for (a = 0; a < App->scene->gameObjects.size() - 1; a++) { if (App->editor->objectSelected->id == App->editor->spheres[a]->id) { break; } } glDeleteTextures(1, &App->editor->spheres[a]->aTextureId); ilDeleteImages(1, &App->editor->spheres[a]->imageID); App->editor->spheres[a]->aTextureId = textId; } else { toFound = App->editor->objectSelected->SearchComponent(App->editor->objectSelected, ComponentType::MESH); if (toFound != -1) { for (a = 0; a < App->scene->gameObjects.size() - 1; a++) { if (App->editor->objectSelected->id == App->renderer3D->models[a].id) { break; } } for (int b = 0; b < App->renderer3D->models[a].meshes.size(); b++) { glDeleteTextures(1, &App->renderer3D->models[a].meshes[b].textureId); ilDeleteImages(1, &imageId); App->renderer3D->models[a].meshes[b].textureId = textId; } } else { toFound = App->editor->objectSelected->SearchComponent(App->editor->objectSelected, ComponentType::PLANE); if (toFound != -1) { for (a = 0; a < App->scene->gameObjects.size() - 1; a++) { if (App->editor->objectSelected->id == App->editor->planes[a]->id) { break; } } glDeleteTextures(1, &App->editor->planes[a]->aTextureId); ilDeleteImages(1, &App->editor->planes[a]->imageID); App->editor->planes[a]->aTextureId = textId; } } } } } } } return toReturn; } std::vector<int> MaterialImporter::LoadMaterial(std::string sourcePath, bool isDropped) { ImportMaterial(sourcePath, isDropped, nullptr); std::vector<int> aux = ImportMaterial(ddsPath, isDropped, nullptr); return aux; } std::vector<int> MaterialImporter::GetMaterialData() { return std::vector<int>(); }
28.644928
118
0.656969
adrianam4
aa8e09d4c4a77647fbda85f91f892ba622a2bc4e
681
cpp
C++
final/pointers/wk3-functions.cpp
coderica/effective_cpp
456d30cf42c6c71dc7187d88e362651dd79ac3fe
[ "MIT" ]
null
null
null
final/pointers/wk3-functions.cpp
coderica/effective_cpp
456d30cf42c6c71dc7187d88e362651dd79ac3fe
[ "MIT" ]
null
null
null
final/pointers/wk3-functions.cpp
coderica/effective_cpp
456d30cf42c6c71dc7187d88e362651dd79ac3fe
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace std; #include "wk3-user.h" #include "wk3-utilities.h" void displayUser(const user &user1) { cout << "Name: " << user1.name << endl; cout << "Gender: " << (user1.gender == male ? "male" : "female") << endl; cout << "Age: " << user1.age << endl; if (user1.hasfriends) cout << "Friends: " << user1.friends[0] << " " << user1.friends[1] << endl; cout << endl; } void updateUserName(user &user1, string name) { user1.name = name; } void addUserFriends(user & user1, string friend1, string friend2) { user1.friends[0] = friend1; user1.friends[1] = friend2; user1.hasfriends = true; }
21.28125
78
0.610866
coderica
aa9964468d6aa4c54aaf83ac6e4a28db73680e87
11,531
cpp
C++
Benchmarks/leukocyte/lc_dilate/dilate_7_multiddr/src/dilate.cpp
LemonAndRabbit/rodinia-hls
097e8cf572a9ab04403c4eb0cfdb042f233f4aea
[ "BSD-2-Clause" ]
16
2020-12-28T15:07:53.000Z
2022-02-16T08:55:40.000Z
Benchmarks/leukocyte/lc_dilate/dilate_7_multiddr/src/dilate.cpp
LemonAndRabbit/rodinia-hls
097e8cf572a9ab04403c4eb0cfdb042f233f4aea
[ "BSD-2-Clause" ]
null
null
null
Benchmarks/leukocyte/lc_dilate/dilate_7_multiddr/src/dilate.cpp
LemonAndRabbit/rodinia-hls
097e8cf572a9ab04403c4eb0cfdb042f233f4aea
[ "BSD-2-Clause" ]
6
2020-12-28T07:33:08.000Z
2022-01-13T16:31:22.000Z
#include "dilate.h" extern "C" { const int PARA_FACTOR=16; float lc_dilate_stencil_core(float img_sample[STREL_ROWS * STREL_COLS]) { float max = 0.0; for (int i = 0; i < STREL_ROWS; i++) #pragma HLS unroll for (int j = 0; j < STREL_COLS; j++) { #pragma HLS unroll float temp = img_sample[i * STREL_COLS + j]; if (temp > max) max = temp; } return max; } void lc_dilate(int flag, float result[TILE_ROWS * (TILE_COLS+2*MAX_RADIUS)], float img [(TILE_ROWS + 2 * MAX_RADIUS) * (TILE_COLS + 2 * MAX_RADIUS)], int which_boundary) { if (flag){ bool strel[25] = { 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0 }; int radius_p = STREL_ROWS / 2; float img_rf[(TILE_COLS+2*MAX_RADIUS) * (2 * MAX_RADIUS) + MAX_RADIUS * 2 + PARA_FACTOR]; #pragma HLS array_partition variable=img_rf complete dim=0 LOAD_WORKING_IMG_SET_BLANK : for (int i = 0; i < MAX_RADIUS; i++) { #pragma HLS pipeline II=1 #pragma HLS unroll img_rf[i] = 0.0; } LOAD_WORKING_IMG_SET : for (int i = 0; i < (TILE_COLS+2*MAX_RADIUS) * (2 * MAX_RADIUS) + MAX_RADIUS + PARA_FACTOR; i++) { #pragma HLS pipeline II=1 #pragma HLS unroll img_rf[i + MAX_RADIUS] = img[i]; } COMPUTE_EACH_OUTPUT : for (int i = 0; i < ((TILE_COLS+2*MAX_RADIUS) * TILE_ROWS) / PARA_FACTOR ; i++) { #pragma HLS pipeline II=1 UNROLL_PE : for (int k = 0; k < PARA_FACTOR; k++) { #pragma HLS unroll float img_sample[STREL_ROWS * STREL_COLS]; #pragma HLS array_partition variable=img_sample complete dim=0 FILTER_ROW : for (int m = 0; m < STREL_ROWS; m++) { #pragma HLS unroll FILTER_COL : for (int n = 0; n < STREL_COLS; n++) { #pragma HLS unroll if ( strel[m * STREL_COLS + n] != 1 ) { img_sample[m * STREL_COLS + n] = 0; } else { img_sample[m * STREL_COLS + n] = img_rf[(TILE_COLS+2*MAX_RADIUS) * m + n + k]; } } } result[i * PARA_FACTOR + k] = lc_dilate_stencil_core(img_sample); } SHIFT_AHEAD_BODY_INDEX : for (int k = 0; k < (TILE_COLS+2*MAX_RADIUS) * (2 * MAX_RADIUS) + MAX_RADIUS * 2; k++) { #pragma HLS unroll img_rf[k] = img_rf[k + PARA_FACTOR]; } SHIFT_AHEAD_LAST_INDEX : for (int k = 0; k < PARA_FACTOR; k++) { #pragma HLS unroll if ((TILE_COLS+2*MAX_RADIUS) * (2 * MAX_RADIUS) + MAX_RADIUS + (i + 1) * PARA_FACTOR + k < (TILE_ROWS + 2 * MAX_RADIUS) * (TILE_COLS + 2 * MAX_RADIUS)){ img_rf[(TILE_COLS+2*MAX_RADIUS) * (2 * MAX_RADIUS) + MAX_RADIUS * 2 + k] = img[(TILE_COLS+2*MAX_RADIUS) * (2 * MAX_RADIUS) + MAX_RADIUS + (i + 1) * PARA_FACTOR + k]; }else{ img_rf[(TILE_COLS+2*MAX_RADIUS) * (2 * MAX_RADIUS) + MAX_RADIUS * 2 + k] = 0.0; } } } } return; } void load_col_tile (int flag, int col_tile_idx, float col_tile [(TILE_ROWS + 2 * MAX_RADIUS) * (TILE_COLS + 2 * MAX_RADIUS)], float row_tile [(TILE_ROWS + 2 * MAX_RADIUS) * GRID_COLS]) { if (flag){ int start_col = 0; if (col_tile_idx == 0){ start_col = 0; LOAD_IMG_ROW_LEFTMOST : for (int row=0; row<(TILE_ROWS + 2 * MAX_RADIUS); ++row){ #pragma HLS PIPELINE II=1 LOAD_IMG_COL_LEFTMOST : for (int col=0; col<(TILE_COLS + MAX_RADIUS); ++col){ #pragma HLS UNROLL col_tile[row*(TILE_COLS + 2 * MAX_RADIUS)+MAX_RADIUS+col] = row_tile[row*GRID_COLS+col]; } } LOAD_IMG_ROW_LEFTMOST_BLANK : for (int row=0; row<(TILE_ROWS + 2 * MAX_RADIUS); ++row){ #pragma HLS PIPELINE II=1 LOAD_IMG_COL_LEFTMOST_BLANK : for (int col=0; col<MAX_RADIUS; ++col){ #pragma HLS UNROLL col_tile[row*(TILE_COLS + 2 * MAX_RADIUS)+col] = 0.0; } } } else if (col_tile_idx == GRID_COLS / TILE_COLS-1){ start_col = col_tile_idx * TILE_COLS - MAX_RADIUS; LOAD_IMG_ROW_RIGHTMOST : for (int row=0; row<(TILE_ROWS + 2 * MAX_RADIUS); ++row){ #pragma HLS PIPELINE II=1 LOAD_IMG_COL_RIGHTMOST : for (int col=0; col<(TILE_COLS + MAX_RADIUS); ++col){ #pragma HLS UNROLL col_tile[row*(TILE_COLS + 2 * MAX_RADIUS)+col] = row_tile[row*GRID_COLS+start_col+col]; } } LOAD_IMG_ROW_RIGHTMOST_BLANK : for (int row=0; row<(TILE_ROWS + 2 * MAX_RADIUS); ++row){ #pragma HLS PIPELINE II=1 LOAD_IMG_COL_RIGHTMOST_BLANK : for (int col=0; col<MAX_RADIUS; ++col){ #pragma HLS UNROLL col_tile[row*(TILE_COLS + 2 * MAX_RADIUS)+(TILE_COLS + MAX_RADIUS)+col] = 0.0; } } } else{ start_col = col_tile_idx * TILE_COLS - MAX_RADIUS; LOAD_IMG_ROW_REST : for (int row=0; row<(TILE_ROWS + 2 * MAX_RADIUS); ++row){ #pragma HLS PIPELINE II=1 LOAD_IMG_COL_REST : for (int col=0; col<(TILE_COLS + 2 * MAX_RADIUS); ++col){ #pragma HLS UNROLL col_tile[row*(TILE_COLS + 2 * MAX_RADIUS)+col] = row_tile[row*GRID_COLS+start_col+col]; } } } } } void store_col_tile (int flag, int col_tile_idx, float row_tile_result [TILE_ROWS * GRID_COLS], float col_tile_result [TILE_ROWS * (TILE_COLS+2*MAX_RADIUS)]) { if (flag){ int start_col = col_tile_idx * TILE_COLS; STORE_RST_ROW : for (int row=0; row<TILE_ROWS; ++row){ #pragma HLS PIPELINE II=1 STORE_RST_COL : for (int col=0; col<TILE_COLS; ++col){ #pragma HLS UNROLL row_tile_result[row*GRID_COLS+start_col+col] = col_tile_result[row*(TILE_COLS+2*MAX_RADIUS)+MAX_RADIUS+col]; } } } } void load_row_tile(int flag, float img_bram[(TILE_ROWS+2*MAX_RADIUS)*GRID_COLS], ap_uint<LARGE_BUS> *img, int tile_index) { if (flag){ int starting_index = tile_index * TILE_ROWS * GRID_COLS / 16; // for (int row=0; row<TILE_ROWS+2*MAX_RADIUS; ++row){ // for (int col=0; col<GRID_COLS / 16; ++col){ // #pragma HLS PIPELINE II=1 // memcpy_wide_bus_read_float(img_bram+(row*GRID_COLS+col*16), (class ap_uint<LARGE_BUS> *)(img+(starting_index+row*GRID_COLS/16+col)), 0, sizeof(float) * 16); // } // } memcpy_wide_bus_read_float(img_bram, (class ap_uint<LARGE_BUS> *)(img+starting_index), 0, sizeof(float) *((unsigned long)(TILE_ROWS+2*MAX_RADIUS)* GRID_COLS )); } } void compute_row_tile(int flag, int row_tile_idx, float row_tile_img [(TILE_ROWS + 2 * MAX_RADIUS) * GRID_COLS], float row_tile_result [TILE_ROWS * GRID_COLS]) { if (flag){ float col_tile_img_0 [(TILE_ROWS + 2 * MAX_RADIUS) * (TILE_COLS + 2 * MAX_RADIUS)]; #pragma HLS array_partition variable=col_tile_img_0 cyclic factor=PARA_FACTOR float col_tile_result_0 [TILE_ROWS * (TILE_COLS+2*MAX_RADIUS)]; #pragma HLS array_partition variable=col_tile_result_0 cyclic factor=PARA_FACTOR float col_tile_img_1 [(TILE_ROWS + 2 * MAX_RADIUS) * (TILE_COLS + 2 * MAX_RADIUS)]; #pragma HLS array_partition variable=col_tile_img_1 cyclic factor=PARA_FACTOR float col_tile_result_1 [TILE_ROWS * (TILE_COLS+2*MAX_RADIUS)]; #pragma HLS array_partition variable=col_tile_result_1 cyclic factor=PARA_FACTOR float col_tile_img_2 [(TILE_ROWS + 2 * MAX_RADIUS) * (TILE_COLS + 2 * MAX_RADIUS)]; #pragma HLS array_partition variable=col_tile_img_2 cyclic factor=PARA_FACTOR float col_tile_result_2 [TILE_ROWS * (TILE_COLS+2*MAX_RADIUS)]; #pragma HLS array_partition variable=col_tile_result_2 cyclic factor=PARA_FACTOR int NUM_COL_TILES = GRID_COLS / TILE_COLS; COL_TILES : for (int j = 0; j < NUM_COL_TILES + 2; ++j) { int load_img_flag = j >= 0 && j < NUM_COL_TILES; int compute_flag = j >= 1 && j < NUM_COL_TILES + 1; int store_flag = j >= 2 && j < NUM_COL_TILES + 2; if (j % 3 == 0){ load_col_tile(load_img_flag, j, col_tile_img_0, row_tile_img); lc_dilate(compute_flag, col_tile_result_2, col_tile_img_2, row_tile_idx); store_col_tile(store_flag, j-2, row_tile_result, col_tile_result_1); } else if (j % 3 == 1){ load_col_tile(load_img_flag, j, col_tile_img_1, row_tile_img); lc_dilate(compute_flag, col_tile_result_0, col_tile_img_0, row_tile_idx); store_col_tile(store_flag, j-2, row_tile_result, col_tile_result_2); } else{ load_col_tile(load_img_flag, j, col_tile_img_2, row_tile_img); lc_dilate(compute_flag, col_tile_result_1, col_tile_img_1, row_tile_idx); store_col_tile(store_flag, j-2, row_tile_result, col_tile_result_0); } } } } void store_row_tile(int flag, float result_bram[TILE_ROWS * GRID_COLS], ap_uint<LARGE_BUS>* result, int tile_index) { if (flag){ int starting_index = tile_index * TILE_ROWS * GRID_COLS / 16; // for (int row=0; row<TILE_ROWS; ++row){ // for (int col=0; col<GRID_COLS / 16; ++col){ // #pragma HLS PIPELINE II=1 // //memcpy_wide_bus_write_float((class ap_uint<LARGE_BUS> *)(result+(starting_index+row*GRID_COLS/16+col)), result_bram+(row*GRID_COLS+col*16), 0, 64); // memcpy_wide_bus_write_float((class ap_uint<LARGE_BUS> *)(result+(starting_index+row*GRID_COLS/16+col)), result_bram+(row*GRID_COLS+col*16), 0, sizeof(float) * 16); // } // } memcpy_wide_bus_write_float((class ap_uint<LARGE_BUS> *)(result+starting_index), result_bram, 0, sizeof(float) * ((unsigned long) TILE_ROWS * GRID_COLS)); } } void workload(ap_uint<LARGE_BUS> *result, ap_uint<LARGE_BUS>* img) { #pragma HLS INTERFACE m_axi port=result offset=slave bundle=result1 #pragma HLS INTERFACE m_axi port=img offset=slave bundle=img1 #pragma HLS INTERFACE s_axilite port=result bundle=control #pragma HLS INTERFACE s_axilite port=img bundle=control #pragma HLS INTERFACE s_axilite port=return bundle=control float row_tile_img_0 [(TILE_ROWS + 2 * MAX_RADIUS) * GRID_COLS]; #pragma HLS array_partition variable=row_tile_img_0 cyclic factor=PARA_FACTOR float row_tile_result_0 [TILE_ROWS * GRID_COLS]; #pragma HLS array_partition variable=row_tile_result_0 cyclic factor=PARA_FACTOR float row_tile_img_1 [(TILE_ROWS + 2 * MAX_RADIUS) * GRID_COLS]; #pragma HLS array_partition variable=row_tile_img_1 cyclic factor=PARA_FACTOR float row_tile_result_1 [TILE_ROWS * GRID_COLS]; #pragma HLS array_partition variable=row_tile_result_1 cyclic factor=PARA_FACTOR float row_tile_img_2 [(TILE_ROWS + 2 * MAX_RADIUS) * GRID_COLS]; #pragma HLS array_partition variable=row_tile_img_2 cyclic factor=PARA_FACTOR float row_tile_result_2 [TILE_ROWS * GRID_COLS]; #pragma HLS array_partition variable=row_tile_result_2 cyclic factor=PARA_FACTOR int NUM_ROW_TILES = GRID_ROWS / TILE_ROWS; ROW_TILES : for (int k = 0; k < NUM_ROW_TILES + 2; k++) { int load_img_flag = k >= 0 && k < NUM_ROW_TILES; int compute_flag = k >= 1 && k < NUM_ROW_TILES + 1; int store_flag = k >= 2 && k < NUM_ROW_TILES + 2; if (k % 3 == 0){ load_row_tile(load_img_flag, row_tile_img_0, img, k); compute_row_tile(compute_flag, k-1, row_tile_img_2, row_tile_result_2); store_row_tile(store_flag, row_tile_result_1, result, k-2); } else if (k % 3 == 1){ load_row_tile(load_img_flag, row_tile_img_1, img, k); compute_row_tile(compute_flag, k-1, row_tile_img_0, row_tile_result_0); store_row_tile(store_flag, row_tile_result_2, result, k-2); } else{ load_row_tile(load_img_flag, row_tile_img_2, img, k); compute_row_tile(compute_flag, k-1, row_tile_img_1, row_tile_result_1); store_row_tile(store_flag, row_tile_result_0, result, k-2); } } return; } }
39.62543
170
0.66447
LemonAndRabbit
aa998be3d5886b10d7a197f61b4c004e56109d05
2,348
cc
C++
cetlib/test/PluginFactory_t.cc
jcfreeman2/cetlib
2ad242f6d9ec99f23c9730c60ef84036a9b8d8ca
[ "BSD-3-Clause" ]
null
null
null
cetlib/test/PluginFactory_t.cc
jcfreeman2/cetlib
2ad242f6d9ec99f23c9730c60ef84036a9b8d8ca
[ "BSD-3-Clause" ]
null
null
null
cetlib/test/PluginFactory_t.cc
jcfreeman2/cetlib
2ad242f6d9ec99f23c9730c60ef84036a9b8d8ca
[ "BSD-3-Clause" ]
1
2022-03-30T15:12:49.000Z
2022-03-30T15:12:49.000Z
#define BOOST_TEST_MODULE (PluginFactory_t) #include "boost/test/unit_test.hpp" #include "cetlib/BasicPluginFactory.h" #include "cetlib/PluginTypeDeducer.h" #include "cetlib/test/TestPluginBase.h" #include "cetlib_except/exception.h" #include <memory> #include <string> using namespace cet; // PluginFactory tests are independent of how its search path is // constructed. // Make test fixture creation compile time generated so we can // generated one test for the system default, and one for a // user-supplied search path. #if defined(PLUGIN_FACTORY_SEARCH_PATH) struct PluginFactoryTestFixture { explicit PluginFactoryTestFixture() { pf.setDiagReleaseVersion("ETERNAL"); } BasicPluginFactory pf{search_path{"PLUGIN_FACTORY_SEARCH_PATH"}}; }; #else struct PluginFactoryTestFixture { explicit PluginFactoryTestFixture() { pf.setDiagReleaseVersion("ETERNAL"); } BasicPluginFactory pf{}; }; #endif using namespace std::string_literals; BOOST_FIXTURE_TEST_SUITE(PluginFactory_t, PluginFactoryTestFixture) BOOST_AUTO_TEST_CASE(checkType) { BOOST_TEST_REQUIRE("TestPluginBase"s == PluginTypeDeducer_v<cettest::TestPluginBase>); BOOST_TEST_REQUIRE(pf.pluginType("TestPlugin") == PluginTypeDeducer_v<cettest::TestPluginBase>); } BOOST_AUTO_TEST_CASE(checkMaker) { auto p = pf.makePlugin<std::unique_ptr<cettest::TestPluginBase>, std::string>( "TestPlugin", "Hi"); BOOST_TEST_REQUIRE(p->message() == "Hi"s); } BOOST_AUTO_TEST_CASE(CheckFinder) { auto fptr = pf.find<std::string>( "TestPlugin", "pluginType", cet::PluginFactory::nothrow); BOOST_TEST_REQUIRE(fptr); BOOST_TEST_REQUIRE(fptr() == PluginTypeDeducer_v<cettest::TestPluginBase>); BOOST_TEST_REQUIRE( pf.find<std::string>("TestPlugin", "oops", cet::PluginFactory::nothrow) == nullptr); } BOOST_AUTO_TEST_CASE(checkError) { BOOST_CHECK_EXCEPTION(pf.makePlugin<std::unique_ptr<cettest::TestPluginBase>>( "TestPluginX"s, "Hi"s), cet::exception, [](cet::exception const& e) { return e.category() == "Configuration" && std::string{e.what()}.find("ETERNAL") != std::string::npos; }); } BOOST_AUTO_TEST_SUITE_END()
31.306667
80
0.689097
jcfreeman2
aa9f3c50eba90d00a967fb0d858f6642eba3f888
4,169
cpp
C++
src/text/freetype/wrap.cpp
degarashi/revenant
9e671320a5c8790f6bdd1b14934f81c37819f7b3
[ "MIT" ]
null
null
null
src/text/freetype/wrap.cpp
degarashi/revenant
9e671320a5c8790f6bdd1b14934f81c37819f7b3
[ "MIT" ]
null
null
null
src/text/freetype/wrap.cpp
degarashi/revenant
9e671320a5c8790f6bdd1b14934f81c37819f7b3
[ "MIT" ]
null
null
null
#include "wrap.hpp" #include "error.hpp" #include "../../sdl/rw.hpp" namespace rev { namespace { constexpr unsigned int FTUnit = 64; } // ---------------------- FTLibrary ---------------------- FTLibrary::FTLibrary() { FTAssert(FT_Init_FreeType, &_lib); } FTLibrary::~FTLibrary() { if(_lib) D_FTAssert(FT_Done_FreeType, _lib); } HFT FTLibrary::newFace(const HRW& hRW, const int index) { FT_Face face; HRW ret; // 中身がメモリじゃなければ一旦コピーする if(!hRW->isMemory()) ret = mgr_rw.fromVector(hRW->readAll()); else ret = hRW; auto m = ret->getMemoryC(); FTAssert(FT_New_Memory_Face, _lib, reinterpret_cast<const uint8_t*>(m.data), m.length, index, &face); return emplace(face, ret); } // ---------------------- FTFace ---------------------- FTFace::FTFace(const FT_Face face, const HRW& hRW): _face(face), _hRW(hRW) {} FTFace::FTFace(FTFace&& f): _face(f._face), _hRW(std::move(f._hRW)), _faceInfo(f._faceInfo), _glyphInfo(f._glyphInfo) { f._face = nullptr; } FTFace::~FTFace() { if(_face) D_FTAssert(FT_Done_Face, _face); } void FTFace::prepareGlyph(const char32_t code, const RenderMode::e mode, const bool bBold, const bool bItalic) { uint32_t gindex = FT_Get_Char_Index(_face, code); int loadflag = mode==RenderMode::Mono ? FT_LOAD_MONOCHROME : FT_LOAD_DEFAULT; if(bBold || bItalic) loadflag |= FT_LOAD_NO_BITMAP; FTAssert(FT_Load_Glyph, _face, gindex, loadflag); auto* slot = _face->glyph; if(!bBold && !bItalic) { if(slot->format != FT_GLYPH_FORMAT_BITMAP) FTAssert(FT_Render_Glyph, slot, static_cast<FT_Render_Mode>(mode)); } else { if(bBold) { int strength = 1 * FTUnit; FTAssert(FT_Outline_Embolden, &slot->outline, strength); FTAssert(FT_Render_Glyph, slot, static_cast<FT_Render_Mode>(mode)); } if(bItalic) { FT_Matrix mat; mat.xx = 1 << 16; mat.xy = 0x5800; mat.yx = 0; mat.yy = 1 << 16; FT_Outline_Transform(&slot->outline, &mat); } } Assert0(slot->format == FT_GLYPH_FORMAT_BITMAP); /* met.width / FTUnit == bitmap.width met.height / FTUnit == bitmap.height met.horiBearingX / FTUnit == bitmap_left met.horiBearingY / FTUnit == bitmap_top assert(_info.width == _info.bmp_width && _info.height == _info.bmp_height && _info.horiBearingX == _info.bmp_left && _info.horiBearingY == _info.bmp_top); */ auto& met = slot->metrics; auto& bm = slot->bitmap; _glyphInfo.data = static_cast<const uint8_t*>(bm.buffer); _glyphInfo.advanceX = slot->advance.x / FTUnit; _glyphInfo.nlevel = mode==RenderMode::Mono ? 2 : bm.num_grays; _glyphInfo.pitch = bm.pitch; _glyphInfo.height = bm.rows; _glyphInfo.width = bm.width; _glyphInfo.horiBearingX = met.horiBearingX / FTUnit; _glyphInfo.horiBearingY = met.horiBearingY / FTUnit; } const FTFace::GlyphInfo& FTFace::getGlyphInfo() const { return _glyphInfo; } const FTFace::FaceInfo& FTFace::getFaceInfo() const { return _faceInfo; } void FTFace::setPixelSizes(const lubee::SizeI s) { FTAssert(FT_Set_Pixel_Sizes, _face, s.width, s.height); _updateFaceInfo(); } void FTFace::setCharSize(const lubee::SizeI s, const lubee::SizeI dpi) { FTAssert(FT_Set_Char_Size, _face, s.width * FTUnit, s.height * FTUnit, dpi.width, dpi.height ); _updateFaceInfo(); } void FTFace::setSizeFromLine(const unsigned int lineHeight) { FT_Size_RequestRec req; req.height = lineHeight * FTUnit; req.width = 0; req.type = FT_SIZE_REQUEST_TYPE_CELL; req.horiResolution = 0; req.vertResolution = 0; FTAssert(FT_Request_Size, _face, &req); _updateFaceInfo(); } void FTFace::_updateFaceInfo() { auto& met = _face->size->metrics; _faceInfo.baseline = (_face->height + _face->descender) * met.y_ppem / _face->units_per_EM; _faceInfo.height = met.height / FTUnit; _faceInfo.maxWidth = met.max_advance / FTUnit; } const char* FTFace::getFamilyName() const { return _face->family_name; } const char* FTFace::getStyleName() const { return _face->style_name; } size_t FTFace::getNFace() const { return _face->num_faces; } int FTFace::getFaceIndex() const { return _face->face_index; } }
28.751724
113
0.673063
degarashi
aaa0112e550b865ce0a2d2946b2ac2a5c9099c23
1,564
cpp
C++
snippets/cpp/VS_Snippets_Winforms/Classic DefaultEventAttribute Example/CPP/source.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
834
2017-06-24T10:40:36.000Z
2022-03-31T19:48:51.000Z
snippets/cpp/VS_Snippets_Winforms/Classic DefaultEventAttribute Example/CPP/source.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
7,042
2017-06-23T22:34:47.000Z
2022-03-31T23:05:23.000Z
snippets/cpp/VS_Snippets_Winforms/Classic DefaultEventAttribute Example/CPP/source.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
1,640
2017-06-23T22:31:39.000Z
2022-03-31T02:45:37.000Z
#using <System.dll> #using <System.Windows.Forms.dll> using namespace System; using namespace System::ComponentModel; using namespace System::Windows::Forms; namespace DefaultEventAttributeExample { // <Snippet1> [DefaultEvent("CollectionChanged")] public ref class TestCollection: public BaseCollection { private: CollectionChangeEventHandler^ onCollectionChanged; public: event CollectionChangeEventHandler^ CollectionChanged { public: void add(CollectionChangeEventHandler^ eventHandler) { onCollectionChanged += eventHandler; } protected: void remove(CollectionChangeEventHandler^ eventHandler) { onCollectionChanged -= eventHandler; } } // Insert additional code. }; // </Snippet1> } // <Snippet2> int main() { // Creates a new collection. DefaultEventAttributeExample::TestCollection^ newCollection = gcnew DefaultEventAttributeExample::TestCollection; // Gets the attributes for the collection. AttributeCollection^ attributes = TypeDescriptor::GetAttributes(newCollection); // Prints the name of the default event by retrieving the // DefaultEventAttribute from the AttributeCollection. DefaultEventAttribute^ attribute = (DefaultEventAttribute^) attributes[DefaultEventAttribute::typeid]; Console::WriteLine("The default event is: {0}", attribute->Name); } // </Snippet2>
27.928571
69
0.661765
BohdanMosiyuk
aaa247e81f79f2589581a3e0995f94ebcccca378
1,371
cpp
C++
src/parser/expression/lambda_expression.cpp
nbenn/duckdb
a7493fec044a3d652389039fc942a3d331cf2c16
[ "MIT" ]
1
2021-12-13T06:00:18.000Z
2021-12-13T06:00:18.000Z
src/parser/expression/lambda_expression.cpp
nbenn/duckdb
a7493fec044a3d652389039fc942a3d331cf2c16
[ "MIT" ]
32
2021-09-24T23:50:09.000Z
2022-03-29T09:37:26.000Z
src/parser/expression/lambda_expression.cpp
nbenn/duckdb
a7493fec044a3d652389039fc942a3d331cf2c16
[ "MIT" ]
null
null
null
#include "duckdb/parser/expression/lambda_expression.hpp" #include "duckdb/common/field_writer.hpp" #include "duckdb/common/types/hash.hpp" namespace duckdb { LambdaExpression::LambdaExpression(unique_ptr<ParsedExpression> lhs, unique_ptr<ParsedExpression> rhs) : ParsedExpression(ExpressionType::LAMBDA, ExpressionClass::LAMBDA), lhs(move(lhs)), rhs(move(rhs)) { } string LambdaExpression::ToString() const { return lhs->ToString() + " -> " + rhs->ToString(); } bool LambdaExpression::Equals(const LambdaExpression *a, const LambdaExpression *b) { return a->lhs->Equals(b->lhs.get()) && a->rhs->Equals(b->rhs.get()); } hash_t LambdaExpression::Hash() const { hash_t result = lhs->Hash(); ParsedExpression::Hash(); result = CombineHash(result, rhs->Hash()); return result; } unique_ptr<ParsedExpression> LambdaExpression::Copy() const { return make_unique<LambdaExpression>(lhs->Copy(), rhs->Copy()); } void LambdaExpression::Serialize(FieldWriter &writer) const { writer.WriteSerializable(*lhs); writer.WriteSerializable(*rhs); } unique_ptr<ParsedExpression> LambdaExpression::Deserialize(ExpressionType type, FieldReader &reader) { auto lhs = reader.ReadRequiredSerializable<ParsedExpression>(); auto rhs = reader.ReadRequiredSerializable<ParsedExpression>(); return make_unique<LambdaExpression>(move(lhs), move(rhs)); } } // namespace duckdb
32.642857
105
0.757112
nbenn
aaa773dbc0c43b8c14227438b71557ccd8d501f6
6,932
cc
C++
src/apps/vod/VoDUDPServer.cc
talal00/Simu5G
ffbdda3e4cd873b49d7022912fe25e39d1a503e8
[ "Intel" ]
58
2021-04-15T09:20:26.000Z
2022-03-31T08:52:23.000Z
src/apps/vod/VoDUDPServer.cc
talal00/Simu5G
ffbdda3e4cd873b49d7022912fe25e39d1a503e8
[ "Intel" ]
34
2021-05-14T15:05:36.000Z
2022-03-31T20:51:33.000Z
src/apps/vod/VoDUDPServer.cc
talal00/Simu5G
ffbdda3e4cd873b49d7022912fe25e39d1a503e8
[ "Intel" ]
30
2021-04-16T05:46:13.000Z
2022-03-28T15:26:29.000Z
// // Simu5G // // Authors: Giovanni Nardini, Giovanni Stea, Antonio Virdis (University of Pisa) // // This file is part of a software released under the license included in file // "license.pdf". Please read LICENSE and README files before using it. // The above files and the present reference are part of the software itself, // and cannot be removed from it. // #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <inet/common/TimeTag_m.h> #include "apps/vod/VoDUDPServer.h" Define_Module(VoDUDPServer); using namespace std; using namespace inet; VoDUDPServer::VoDUDPServer() { } VoDUDPServer::~VoDUDPServer() { } void VoDUDPServer::initialize(int stage) { cSimpleModule::initialize(stage); if (stage != INITSTAGE_APPLICATION_LAYER) return; EV << "VoD Server initialize: stage " << stage << endl; serverPort = par("localPort"); inputFileName = par("vod_trace_file").stringValue(); traceType = par("traceType").stringValue(); fps = par("fps"); double one = 1.0; TIME_SLOT = one / fps; numStreams = 0; // set up Udp socket socket.setOutputGate(gate("socketOut")); socket.bind(serverPort); int tos = par("tos"); if (tos != -1) socket.setTos(tos); if (!inputFileName.empty()) { // Check whether string is empty if (traceType.compare("SVC") != 0) throw cRuntimeError("VoDUDPServer::initialize - only SVC trace is currently available. Abort."); infile.open(inputFileName.c_str(), ios::in); if (infile.bad()) /* Or file is bad */ throw cRuntimeError("Error while opening input file (File not found or incorrect type)"); infile.seekg(0, ios::beg); long int i = 0; while (!infile.eof()) { svcPacket tmp; tmp.index = i; infile >> tmp.memoryAdd >> tmp.length >> tmp.lid >> tmp.tid >> tmp.qid >> tmp.frameType >> tmp.isDiscardable >> tmp.isTruncatable >> tmp.frameNumber >> tmp.timestamp >> tmp.isControl; svcTrace_.push_back(tmp); i++; } svcPacket tmp; tmp.index = LONG_MAX; svcTrace_.push_back(tmp); } /* Initialize parameters after the initialize() method */ EV << "VoD Server initialize: Trace: " << inputFileName << " trace type " << traceType << endl; cMessage* timer = new cMessage("Timer"); double start = par("startTime"); double offset = (double) start + simTime().dbl(); scheduleAt(offset, timer); } void VoDUDPServer::finish() { if (infile.is_open()) infile.close(); } void VoDUDPServer::handleMessage(cMessage *msg) { if (msg->isSelfMessage()) { if (!strcmp(msg->getName(), "Timer")) { clientsPort = par("destPort"); // vclientsPort = cStringTokenizer(clientsPort).asIntVector(); clientsStartStreamTime = par("clientsStartStreamTime").doubleValue(); //vclientsStartStreamTime = cStringTokenizer(clientsStartStreamTime).asDoubleVector(); clientsReqTime = par("clientsReqTime"); vclientsReqTime = cStringTokenizer(clientsReqTime).asDoubleVector(); int size = 0; const char *destAddrs = par("destAddresses"); cStringTokenizer tokenizer(destAddrs); const char *token; while ((token = tokenizer.nextToken()) != nullptr) { clientAddr.push_back(L3AddressResolver().resolve(token)); size++; } /* Register video streams*/ for (int i = 0; i < size; i++) { M1Message* M1 = new M1Message(); M1->setClientAddr(clientAddr[i]); M1->setClientPort(clientsPort); double npkt; npkt = clientsStartStreamTime; M1->setNumPkSent((int) (npkt * fps)); numStreams++; EV << "VoD Server self message: Dest IP: " << clientAddr[i] << " port: " << clientsPort << " start stream: " << (int)(npkt* fps) << endl; // scheduleAt(simTime() + vclientsReqTime[i], M1); scheduleAt(simTime(), M1); } delete msg; return; } else handleSVCMessage(msg); } else delete msg; } void VoDUDPServer::handleSVCMessage(cMessage *msg) { M1Message* msgNew = (M1Message*) msg; long numPkSentApp = msgNew->getNumPkSent(); if (svcTrace_[numPkSentApp].index == LONG_MAX) { /* End of file, send finish packet */ Packet* fm = new Packet("VoDFinishPacket"); socket.sendTo(fm, msgNew->getClientAddr(), msgNew->getClientPort()); return; } else { int seq_num = numPkSentApp; int currentFrame = svcTrace_[numPkSentApp].frameNumber; Packet* packet = new Packet("VoDPacket"); auto frame = makeShared<VoDPacket>(); frame->setFrameSeqNum(seq_num); frame->setPayloadTimestamp(simTime()); frame->setChunkLength(B(svcTrace_[numPkSentApp].length)); frame->setFrameLength(svcTrace_[numPkSentApp].length + 2 * sizeof(int)); /* Seq_num plus frame length plus payload */ frame->setTid(svcTrace_[numPkSentApp].tid); frame->setQid(svcTrace_[numPkSentApp].qid); frame->addTag<CreationTimeTag>()->setCreationTime(simTime()); packet->insertAtBack(frame); socket.sendTo(packet, msgNew->getClientAddr(), msgNew->getClientPort()); numPkSentApp++; while (1) { /* Get infos about the frame from file */ if (svcTrace_[numPkSentApp].index == LONG_MAX) break; int seq_num = numPkSentApp; if (svcTrace_[numPkSentApp].frameNumber != currentFrame) break; // Finish sending packets belonging to the current frame Packet* packet = new Packet("VoDPacket"); auto frame = makeShared<VoDPacket>(); frame->setTid(svcTrace_[numPkSentApp].tid); frame->setQid(svcTrace_[numPkSentApp].qid); frame->setFrameSeqNum(seq_num); frame->setPayloadTimestamp(simTime()); frame->setChunkLength(B(svcTrace_[numPkSentApp].length)); frame->setFrameLength(svcTrace_[numPkSentApp].length + 2 * sizeof(int)); /* Seq_num plus frame length plus payload */ frame->addTag<CreationTimeTag>()->setCreationTime(simTime()); packet->insertAtBack(frame); socket.sendTo(packet, msgNew->getClientAddr(), msgNew->getClientPort()); EV << " VoDUDPServer::handleSVCMessage sending frame " << seq_num << std::endl; numPkSentApp++; } msgNew->setNumPkSent(numPkSentApp); scheduleAt(simTime() + TIME_SLOT, msgNew); } }
33.814634
153
0.594201
talal00
aaacd4d00260bf51d9070e3beb6b473c489b7652
8,724
cpp
C++
core/ir/node.cpp
lqwang1025/Eutopia
5ecb47805fd650bd7580cd3702032a98378e334f
[ "Apache-2.0" ]
2
2021-08-29T00:22:23.000Z
2021-09-13T13:16:52.000Z
core/ir/node.cpp
lqwang1025/Eutopia
5ecb47805fd650bd7580cd3702032a98378e334f
[ "Apache-2.0" ]
null
null
null
core/ir/node.cpp
lqwang1025/Eutopia
5ecb47805fd650bd7580cd3702032a98378e334f
[ "Apache-2.0" ]
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. */ /* * (C) COPYRIGHT Daniel Wang Limited. * File : node.cpp * Authors : Daniel Wang * Create Time: 2021-08-09:22:02:38 * Email : wangliquan21@qq.com * Description: */ #include "core/ir/node.h" #include "core/ir/tensor.h" #include "op/op.h" #include "op/ops_param.h" #include "op/cpu/op_register.h" #include "utils/filler.h" #include <iostream> namespace eutopia { namespace core { namespace ir { using InputShapes = std::vector< std::vector<uint32_t> >; Node::Node(Graph* graph): graph_(graph) { op_ = nullptr; name_ = ""; index_ = -1; op_type_ = ""; output_shape_.resize(0); is_trainning_ = false; is_quantize_ = false; weight_shared_ = false; is_sparse_ = false; is_first_node_ = false; is_last_node_ = false; dynamic_shape_ = false; in_place_ = false; device_ = "cpu"; producers_.resize(0); consumers_.resize(0); weight_ = nullptr; bias_ = nullptr; output_tensor_ = nullptr; diff_tensor_ = nullptr; weight_filler_ = nullptr; bias_filler_ = nullptr; set_is_trainning(false); set_dynamic_shape(false); } Node::Node(Graph* graph, const op::BaseParam* param): Node(graph) { setup(param); } void Node::setup(const op::BaseParam* param) { set_op_type(param->op_type); set_name(param->op_name); set_is_sparse(param->sparse); set_is_quantize(param->quantize); set_weight_shared(param->weight_shared); set_is_first_node(param->first_op); set_is_last_node(param->last_op); op_ = op::Holder::get_op_creator(op_type_)(param); op_->set_node(this); output_tensor_ = new Tensor; CHECK(output_tensor_!=nullptr, "Alloc mem failed.") output_tensor_->set_name(param->op_name); diff_tensor_ = new Tensor; CHECK(diff_tensor_!=nullptr, "Alloc mem failed."); diff_tensor_->set_name(param->op_name); } void Node::infer_shape(const InputShapes& input_shapes) { op_->infer_shape(input_shapes, output_shape_); } void Node::set_graph(Graph* graph) { graph_ = graph; } const Graph* Node::get_graph(void) const { return graph_; } void Node::set_weight_filler(utils::Filler* filler) { weight_filler_ = filler; } void Node::set_bias_filler(utils::Filler* filler) { bias_filler_ = filler; } const std::string& Node::get_name(void) const { return name_; } void Node::set_name(const std::string& name) { name_ = name; } const Tensor* Node::get_output_tensor(void) const { return output_tensor_; } int32_t Node::get_index(void) const { return index_; } void Node::set_index(const int32_t index) { index_ = index; } const std::string& Node::get_op_type(void) const { return op_type_; } void Node::set_op_type(const std::string& op_type) { op_type_ = op_type; } void Node::set_output_shape(const std::vector<uint32_t>& output_shape) { output_shape_ = output_shape; } const std::vector<uint32_t>& Node::get_output_shape(void) const { return output_shape_; } void Node::add_producer(const std::string& producer) { producers_.push_back(producer); } const std::vector<std::string>& Node::get_producers(void) const { return producers_; } void Node::add_consumer(const std::string& consumer) { consumers_.push_back(consumer); } const std::vector<std::string>& Node::get_consumers(void) const { return consumers_; } void Node::set_is_first_node(bool is_first_node) { is_first_node_ = is_first_node; } void Node::set_is_last_node(bool is_last_node) { is_last_node_ = is_last_node; } bool Node::is_last_node(void) const { return is_last_node_; } bool Node::is_first_node(void) const { return is_first_node_; } void Node::set_dynamic_shape(bool dynamic_shape) { dynamic_shape_ = dynamic_shape; } bool Node::dynamic_shape(void) const { return dynamic_shape_; } void Node::set_is_sparse(bool is_sparse) { is_sparse_ = is_sparse; } bool Node::is_sparse(void) const { return is_sparse_; } void Node::set_is_quantize(bool is_quantize) { is_quantize_ = is_quantize; } bool Node::is_quantize(void) const { return is_quantize_; } void Node::set_in_place(bool in_place) { in_place_ = in_place; } bool Node::in_place(void) const { return in_place_; } void Node::set_weight_shared(bool weight_shared) { weight_shared_ = weight_shared; } bool Node::weight_shared(void) const { return weight_shared_; } bool Node::is_trainning(void) const { return is_trainning_; } void Node::set_is_trainning(bool is_trainning) { is_trainning_ = is_trainning; } void Node::set_weight(Tensor* weight) { weight_ = weight; } Tensor* Node::get_weight(void) const { return weight_; } void Node::set_bias(Tensor* bias) { bias_ = bias; } Tensor* Node::get_bias(void) const { return bias_; } void Node::set_input_shape(const std::vector<uint32_t>& input_shape) { input_shapes_.push_back(input_shape); } const InputShapes& Node::get_input_shapes(void) const { return input_shapes_; } void Node::_conv2d_filler() { CHECK(weight_filler_!=nullptr, "Please assign weight filler."); CHECK(bias_filler_!=nullptr, "Please assign bias filler."); op::cpu::Convolution2DOperator* conv2d_op = static_cast<op::cpu::Convolution2DOperator*>(op_); op::Convolution2DParam* op_param = conv2d_op->op_param_; std::vector<uint32_t> kernel_shape = op_param->kernel_shape; CHECK(kernel_shape.size() == 4, ""); if (kernel_shape[1] == 0) { // weight distribution: OcIcHW uint32_t ic = 0; for (int i = 0; i < input_shapes_.size(); ++i) { CHECK(input_shapes_[i].size()==4,""); ic += input_shapes_[i][1]; // feature distribution: NCHW } op_param->kernel_shape[1] = ic; kernel_shape[1] = ic; } weight_ = new Tensor(kernel_shape, DataType::EUTOPIA_DT_FP32); weight_->set_name(get_name()+"_const_1"); weight_filler_->fill(weight_); delete weight_filler_; bias_ = new Tensor({kernel_shape[0]}, DataType::EUTOPIA_DT_FP32); bias_->set_name(get_name()+"_const_2"); bias_filler_->fill(bias_); delete bias_filler_; } void Node::_fc_filler() { CHECK(weight_filler_!=nullptr, "Please assign weight filler."); CHECK(bias_filler_!=nullptr, "Please assign bias filler."); op::cpu::FullyConnectedOperator* fc_op = static_cast<op::cpu::FullyConnectedOperator*>(op_); op::FullyConnectedParam* op_param = fc_op->op_param_; uint32_t num_outputs = op_param->num_outputs; uint32_t num_inputs = 0; for (int i = 0; i < (int)input_shapes_.size(); ++i) { uint32_t flatten = 1; for (int _i = 1; _i < (int)input_shapes_[i].size(); ++_i) { flatten *= input_shapes_[i][_i]; } num_inputs += flatten; } CHECK(num_inputs!=0,""); std::vector<uint32_t> kernel_shape = {num_outputs, num_inputs, 1, 1}; // // weight distribution: OcIcHW weight_ = new Tensor(kernel_shape, DataType::EUTOPIA_DT_FP32); weight_->set_name(get_name()+"_const_1"); weight_filler_->fill(weight_); delete weight_filler_; bias_ = new Tensor({num_outputs}, DataType::EUTOPIA_DT_FP32); bias_->set_name(get_name()+"_const_2"); bias_filler_->fill(bias_); delete bias_filler_; } void Node::fill_weight_bias() { if (fill_func_map_.count(op_type_) != 0) { (this->*fill_func_map_[op_type_])(); } } void Node::forward(const std::vector<const Tensor*> input_tensors) { op_->forward(input_tensors, output_tensor_); } void Node::backward(void) { //TODO } void Node::update(void) { //TODO } void Node::run(void) { //todo } void Node::dump(void) { //todo } Node::~Node(void) { if (weight_ != nullptr) { delete weight_; } if (bias_ != nullptr) { delete bias_; } delete op_; delete output_tensor_; delete diff_tensor_; } } // namespace ir } // namespace core } // namespace eutopia
25.14121
107
0.685695
lqwang1025
aab0b70d332efe7a18e716c2ad86348b07e41e71
805
cpp
C++
src/Tokenizer.cpp
eldermyoshida/Potato-Master
31efa37b0f2cb4cbf44afda2b38b80053cc89d7f
[ "MIT" ]
null
null
null
src/Tokenizer.cpp
eldermyoshida/Potato-Master
31efa37b0f2cb4cbf44afda2b38b80053cc89d7f
[ "MIT" ]
null
null
null
src/Tokenizer.cpp
eldermyoshida/Potato-Master
31efa37b0f2cb4cbf44afda2b38b80053cc89d7f
[ "MIT" ]
null
null
null
// // Tokenizer.cpp // Potato-Master // // Created by Elder Yoshida on 4/23/15. // Copyright (c) 2015 Elder Yoshida. All rights reserved. // #include "Tokenizer.h" void Tokenize(const string& str, vector<string>& tokens, const string& delimiters = " ") { // Skip delimiters at beginning. string::size_type lastPos = str.find_first_not_of(delimiters, 0); // Find first "non-delimiter". string::size_type pos = str.find_first_of(delimiters, lastPos); while (string::npos != pos || string::npos != lastPos) { // Found a token, add it to the vector. tokens.push_back(str.substr(lastPos, pos - lastPos)); // Skip delimiters. Note the "not_of" lastPos = str.find_first_not_of(delimiters, pos); // Find next "non-delimiter" pos = str.find_first_of(delimiters, lastPos); }
29.814815
68
0.686957
eldermyoshida
aab155f3c6d981d9e9afb90b50db0b888f252313
445
cpp
C++
wwi-2019/choinka.cpp
Aleshkev/algoritmika
fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189
[ "MIT" ]
2
2019-05-04T09:37:09.000Z
2019-05-22T18:07:28.000Z
wwi-2019/choinka.cpp
Aleshkev/algoritmika
fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189
[ "MIT" ]
null
null
null
wwi-2019/choinka.cpp
Aleshkev/algoritmika
fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef intmax_t I; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr), cout.tie(nullptr); I n; cin >> n; for (I k = 0; k < 2; ++k) for (I i = 0; i < n + k; ++i) cout << string(n - i, ' ') << string(2 * i + 1, '*') << '\n'; for (I k = 0; k < 2; ++k) cout << string(n, ' ') << '*' << '\n'; #ifdef UNITEST cout.flush(); system("pause"); #endif return 0; }
19.347826
67
0.501124
Aleshkev
82b686cf7b10218ba123f71635a7a4dc38dddfaf
2,834
cpp
C++
breeze/conversion/test/roman_test.cpp
gennaroprota/breeze
7afe88a30dc8ac8b97a76a192dc9b189d9752e8b
[ "BSD-3-Clause" ]
1
2021-04-03T22:35:52.000Z
2021-04-03T22:35:52.000Z
breeze/conversion/test/roman_test.cpp
gennaroprota/breeze
f1dfd7154222ae358f5ece936c2897a3ae110003
[ "BSD-3-Clause" ]
null
null
null
breeze/conversion/test/roman_test.cpp
gennaroprota/breeze
f1dfd7154222ae358f5ece936c2897a3ae110003
[ "BSD-3-Clause" ]
1
2021-10-01T04:26:48.000Z
2021-10-01T04:26:48.000Z
// =========================================================================== // Copyright 2016 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>.) // ___________________________________________________________________________ #include "breeze/conversion/roman.hpp" #include "breeze/environment/get_environment_variable.hpp" #include "breeze/testing/testing.hpp" #include <algorithm> #include <fstream> #include <ios> #include <iterator> #include <locale> #include <sstream> #include <string> int test_roman() ; namespace { std::string classic_to_lower( std::string const & s ) { std::locale const loc = std::locale::classic() ; std::string result ; std::transform( s.cbegin(), s.cend(), std::back_inserter( result ), [ &loc ]( char c ) { return std::tolower( c, loc ) ; } ) ; return result ; } void check() { std::string const breeze_root = breeze::get_environment_variable( "BREEZE_ROOT" ).value() ; std::ifstream is( breeze_root + "/breeze/conversion/test/a006968.txt" ) ; BREEZE_CHECK( is.good() ) ; // Skip the first lines. // ----------------------------------------------------------------------- int const lines_to_skip = 14 ; for ( int i = 0 ; i < lines_to_skip ; ++ i ) { std::string line ; std::getline( is, line ) ; } int const max_roman = 3999 ; int n ; do { is >> n ; char equal_sign ; is >> equal_sign ; std::string upper_expected ; is >> upper_expected ; BREEZE_CHECK( is.good() ) ; std::ostringstream strm ; breeze::roman const roman( n ) ; strm << std::uppercase << roman ; std::string const upper_actual = strm.str() ; strm.str( "" ) ; strm << std::nouppercase << roman ; std::string const lower_actual = strm.str() ; BREEZE_CHECK( upper_actual == upper_expected ) ; BREEZE_CHECK( lower_actual == classic_to_lower( upper_expected ) ) ; } while ( n != max_roman ) ; } void out_of_range_integer_causes_assert() { BREEZE_CHECK_THROWS( breeze::assert_failure, breeze::roman( 0 ) ) ; BREEZE_CHECK_THROWS( breeze::assert_failure, breeze::roman( 4000 ) ) ; } } int test_roman() { return breeze::test_runner::instance().run( "roman", { check, out_of_range_integer_causes_assert } ) ; }
27.784314
78
0.51976
gennaroprota
82b82cd7ee2ee6bbb0c0be93f62c980894f13e20
239
hpp
C++
include/Node.hpp
behluluysal/sau-data-structures-2020-midterm
39b21a77943dcdbc9223b8f22690bac766050861
[ "MIT" ]
null
null
null
include/Node.hpp
behluluysal/sau-data-structures-2020-midterm
39b21a77943dcdbc9223b8f22690bac766050861
[ "MIT" ]
null
null
null
include/Node.hpp
behluluysal/sau-data-structures-2020-midterm
39b21a77943dcdbc9223b8f22690bac766050861
[ "MIT" ]
null
null
null
#ifndef Node_hpp #define Node_hpp #pragma once #include "iostream" class Node { public: Node(); Node(int data, Node *prevnew, Node *nextnew); int getData(); ~Node(); Node *next; Node *prev; int data; }; #endif
13.277778
49
0.615063
behluluysal
82b9bb8fa03488e86044b2df5eeba361aec3b249
2,552
cpp
C++
Classic Algorithms/Columnar cypher/columnar.cpp
IulianOctavianPreda/EncryptionAlgorithms
3cbaec3f5a6b9b7c615a20bfd3c6206469deb8f4
[ "MIT" ]
null
null
null
Classic Algorithms/Columnar cypher/columnar.cpp
IulianOctavianPreda/EncryptionAlgorithms
3cbaec3f5a6b9b7c615a20bfd3c6206469deb8f4
[ "MIT" ]
null
null
null
Classic Algorithms/Columnar cypher/columnar.cpp
IulianOctavianPreda/EncryptionAlgorithms
3cbaec3f5a6b9b7c615a20bfd3c6206469deb8f4
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> std::map<int, int> keyMap; void orderColumns(const std::string &key) { for (unsigned int i = 0; i < key.length(); i++) { keyMap[key[i]] = i; } } std::string encrypt(std::string text, const std::string &key) { unsigned int row, column; std::string cipher; column = key.length(); row = text.length() / column; if (text.length() % column) { row += 1; } char matrix[row][column]; for (unsigned int i = 0, k = 0; i < row; i++) { for (unsigned int j = 0; j < column;) { if (text[k] == '\0') { matrix[i][j] = '_'; j++; } if (isalpha(text[k]) || text[k] == ' ') { matrix[i][j] = text[k]; j++; } k++; } } unsigned int j = 0; for (auto &iterator : keyMap) { j = iterator.second; for (unsigned int i = 0; i < row; i++) { if (isalpha(matrix[i][j]) || matrix[i][j] == ' ' || matrix[i][j] == '_') cipher += matrix[i][j]; } } return cipher; } std::string decrypt(std::string encryptedText, const std::string &key) { unsigned int column = key.length(); unsigned int row = encryptedText.length() / column; char cipherMatrix[row][column]; for (unsigned int j = 0, k = 0; j < column; j++) { for (unsigned int i = 0; i < row; i++) { cipherMatrix[i][j] = encryptedText[k++]; } } int index = 0; for (auto &iterator : keyMap) { iterator.second = index++; } char decryptedText[row][column]; auto ii = keyMap.begin(); int k = 0; for (int l = 0, j; key[l] != '\0'; k++) { j = keyMap[key[l++]]; for (unsigned int i = 0; i < row; i++) { decryptedText[i][k] = cipherMatrix[i][j]; } } std::string decrypted; for (unsigned int i = 0; i < row; i++) { for (unsigned int j = 0; j < column; j++) { if (decryptedText[i][j] != '_') decrypted += decryptedText[i][j]; } } return decrypted; } int main() { int choice; std::string text; std::string key; std::cout << "1)Encrypt" << std::endl << "2)Decrypt"; std::cin >> choice; std::cout << "Insert plaintext"; std::cin >> text; std::cout << "Plain text: " << text << std::endl; std::cout << "Insert key"; std::cin >> key; std::cout << "key: " << key << std::endl; orderColumns(key); if (choice == 1) { std::string cipher = encrypt(text, key); std::cout << "Encrypted Message: " << cipher << std::endl; } else { std::string decryptedText = decrypt(text, key); std::cout << "Decrypted Message: " << decryptedText << std::endl; } return 0; }
24.538462
78
0.53605
IulianOctavianPreda
82bce099e057cee96fc162bb5fd79780a10a99fd
2,273
hh
C++
include/xpgom/gomwrappedelement.hh
jberkman/gom
4bccfec5e5ada830a4c5f076dfefb9ad9baab6a5
[ "MIT" ]
null
null
null
include/xpgom/gomwrappedelement.hh
jberkman/gom
4bccfec5e5ada830a4c5f076dfefb9ad9baab6a5
[ "MIT" ]
null
null
null
include/xpgom/gomwrappedelement.hh
jberkman/gom
4bccfec5e5ada830a4c5f076dfefb9ad9baab6a5
[ "MIT" ]
null
null
null
/* The MIT License Copyright (c) 2008 jacob berkman <jacob@ilovegom.org> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef GOM_WRAPPED_ELEMENT_HH #define GOM_WRAPPED_ELEMENT_HH #include <glib/gmacros.h> G_BEGIN_DECLS typedef struct _GomWrappedElement GomWrappedElement; typedef struct _GomWrappedElementClass GomWrappedElementClass; G_END_DECLS #include <xpgom/gomwrappednode.hh> G_BEGIN_DECLS #define GOM_TYPE_WRAPPED_ELEMENT (gom_wrapped_element_get_type ()) #define GOM_WRAPPED_ELEMENT(i) (G_TYPE_CHECK_INSTANCE_CAST ((i), GOM_TYPE_WRAPPED_ELEMENT, GomWrappedElement)) #define GOM_WRAPPED_ELEMENT_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), GOM_TYPE_WRAPPED_ELEMENT, GomWrappedElementClass)) #define GOM_IS_WRAPPED_ELEMENT(i) (G_TYPE_CHECK_INSTANCE_TYPE ((i), GOM_TYPE_WRAPPED_ELEMENT)) #define GOM_IS_WRAPPED_ELEMENT_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GOM_TYPE_WRAPPED_ELEMENT)) #define GOM_WRAPPED_ELEMENT_GET_CLASS(i) (G_TYPE_INSTANCE_GET_CLASS ((i), GOM_TYPE_WRAPPED_ELEMENT, GomWrappedElementClass)) struct _GomWrappedElement { GomWrappedNode parent; }; struct _GomWrappedElementClass { GomWrappedNodeClass parent_class; }; GType gom_wrapped_element_get_type (void); G_END_DECLS #endif /* GOM_WRAPPED_ELEMENT_HH */
37.262295
125
0.805543
jberkman
82c2f5b6572143f3919473671e6ed190fcc7e086
2,729
cc
C++
emplnofusion/employee2.cc
jorgeventura/spirit
3ad8ebee54bb294486fe8eead44691bec89532e6
[ "BSL-1.0" ]
null
null
null
emplnofusion/employee2.cc
jorgeventura/spirit
3ad8ebee54bb294486fe8eead44691bec89532e6
[ "BSL-1.0" ]
null
null
null
emplnofusion/employee2.cc
jorgeventura/spirit
3ad8ebee54bb294486fe8eead44691bec89532e6
[ "BSL-1.0" ]
null
null
null
#define BOOST_SPIRIT_X3_DEBUG #include <iostream> #include <boost/spirit/home/x3.hpp> #include <boost/fusion/include/adapt_struct.hpp> #include <string> #include <vector> #include <variant> namespace x3 = boost::spirit::x3; namespace ast { struct employee { int age; std::string gname; std::string sname; float sal; employee() : age(0), sal(0.0) {} friend std::ostream& operator<<(std::ostream& os, employee const& e) { os << "[ " << e.age << ", \"" << e.gname << "\", \"" << e.sname << "\", " << float(e.sal) << " ]" << std::endl; return os; } }; } BOOST_FUSION_ADAPT_STRUCT(ast::employee, age, gname, sname, sal); namespace parser { namespace x3 = boost::spirit::x3; x3::rule<struct employee_class, ast::employee> const employee_ = "employee"; x3::real_parser<float, x3::strict_real_policies<float> > float_; auto const quoted_string = x3::lexeme['"' >> +(x3::char_ - '"') >> '"']; const auto employee__def = x3::lit("employee") >> '{' >> (x3::int_ >> ',') >> (quoted_string >> ',') >> (quoted_string >> ',') >> float_ >> '}' ; BOOST_SPIRIT_DEFINE(employee_) const auto entry_point = x3::skip(x3::space) [ employee_ ]; } int main() { namespace x3 = boost::spirit::x3; std::cout << "/////////////////////////////////////////////////////////\n\n"; std::cout << "\t\tAn employee parser for Spirit...\n\n"; std::cout << "/////////////////////////////////////////////////////////\n\n"; std::cout << "Give me an employee of the form :" << "employee{age, \"forename\", \"surname\", salary } \n"; std::cout << "Type [q or Q] to quit\n\n"; using iterator_type = std::string::const_iterator; std::string str; while (getline(std::cin, str)) { if (str.empty() || str[0] == 'q' || str[0] == 'Q') break; ast::employee emp; iterator_type iter = str.begin(); iterator_type const end = str.end(); bool r = phrase_parse(iter, end, parser::entry_point, x3::space, emp); if (r && iter == end) { std::cout << "-------------------------\n"; std::cout << "Parsing succeeded\n"; std::cout << "got: " << emp << std::endl; std::cout << "\n-------------------------\n"; } else { std::cout << "-------------------------\n"; std::cout << "Parsing failed\n"; std::cout << "-------------------------\n"; } } std::cout << "Bye... :-) \n\n"; return 0; }
25.036697
115
0.45841
jorgeventura
82c372258db90a8bb6ad993843f33ed140153e3a
1,560
cc
C++
pb/protobuf_dump.cc
corrupt-stack/protobuf-super-lite
c9c0c90721756b9208f6bfccfdc40838316edf2c
[ "BSD-3-Clause" ]
null
null
null
pb/protobuf_dump.cc
corrupt-stack/protobuf-super-lite
c9c0c90721756b9208f6bfccfdc40838316edf2c
[ "BSD-3-Clause" ]
null
null
null
pb/protobuf_dump.cc
corrupt-stack/protobuf-super-lite
c9c0c90721756b9208f6bfccfdc40838316edf2c
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2022 Yuri Wiitala. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <cstdint> #include <fstream> #include <iostream> #include <limits> #include <vector> #include "pb/codec/limits.h" #include "pb/inspection.h" int main(int argc, char* argv[]) { // If a path was provided on the command line, open a file. Else, read from // stdin. std::istream* in; std::fstream fs; if (argc > 1) { fs.open(argv[1], std::fstream::in); in = &fs; } else { in = &std::cin; } if (!*in) { std::cerr << "Failed to open file.\n"; return 1; } // Read the whole file into memory. static constexpr int32_t kChunkSize = 4096; std::vector<uint8_t> buffer; while (static_cast<int64_t>(buffer.size()) < pb::codec::kMaxSerializedSize) { buffer.resize(buffer.size() + kChunkSize); in->read( reinterpret_cast<char*>(buffer.data() + buffer.size() - kChunkSize), kChunkSize); if (!*in) { const auto num_read = static_cast<std::size_t>(in->gcount()); buffer.resize(buffer.size() - kChunkSize + num_read); break; } } // Interpret and print the results to stdout. pb::InspectionRenderingContext(buffer.data(), static_cast<std::ptrdiff_t>(buffer.size())) .Print(pb::ScanForMessageFields(buffer.data(), buffer.data() + buffer.size(), true), std::cout); if (argc > 1) { fs.close(); } return 0; }
26.896552
79
0.605128
corrupt-stack
82c851fe3f10a27336cd8670fcb72b466a71e0f1
647
hpp
C++
include/chesham/cppext/functional.hpp
Chesham/cppext
9fb0326fcfcb737797ed9ece4a88688d996ec615
[ "MIT" ]
3
2020-05-25T03:39:05.000Z
2022-01-11T16:55:18.000Z
include/chesham/cppext/functional.hpp
Chesham/cppext
9fb0326fcfcb737797ed9ece4a88688d996ec615
[ "MIT" ]
null
null
null
include/chesham/cppext/functional.hpp
Chesham/cppext
9fb0326fcfcb737797ed9ece4a88688d996ec615
[ "MIT" ]
null
null
null
#pragma once #include <algorithm> #include <cctype> #include <functional> namespace chesham { template<class T> struct string_no_case_comparer { T& to_lower(T& s) const { transform(s.begin(), s.end(), s.begin(), [](const auto& i) { return ::tolower(i); }); return s; } std::size_t operator()(T s) const { using namespace std; return std::hash<T>()(to_lower(s)); } bool operator()(T x, T y) const { using namespace std; return to_lower(x) == to_lower(y); } }; }
23.962963
98
0.483771
Chesham
82c931d036489bb1edf04731319c35afa727d4b3
1,805
cpp
C++
CardGame/Classes/Social/SocialJNI.cpp
GuruDev0807/CardGame
e14c71b9833b38d97266678810d1800cb7880ea6
[ "MIT" ]
2
2022-03-10T00:18:44.000Z
2022-03-26T12:26:19.000Z
CardGame/Classes/Social/SocialJNI.cpp
GuruDev0807/CardGame
e14c71b9833b38d97266678810d1800cb7880ea6
[ "MIT" ]
null
null
null
CardGame/Classes/Social/SocialJNI.cpp
GuruDev0807/CardGame
e14c71b9833b38d97266678810d1800cb7880ea6
[ "MIT" ]
2
2019-12-18T15:55:48.000Z
2020-02-16T15:02:10.000Z
#include "../Common/Common.h" #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) #include <jni.h> #include "platform/android/jni/JniHelper.h" #include <android/log.h> #endif #include "SocialJni.h" #include "../Layer/SettingLayer.h" #define CLASS_NAME "com/mcmahon/cardgame/AppActivity" extern "C" { std::string getIMEI() { #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) JniMethodInfo methodInfo; #ifdef ANDROID_AMAZON #else if(! JniHelper::getStaticMethodInfo(methodInfo, CLASS_NAME, "getIMEI", "()Ljava/lang/String;")) #endif return ""; jstring device_id = (jstring)methodInfo.env->CallStaticObjectMethod(methodInfo.classID, methodInfo.methodID); std::string result = JniHelper::jstring2string(device_id); methodInfo.env->DeleteLocalRef(methodInfo.classID); return result; #endif } void captureAvatar(std::string user_id) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) JniMethodInfo methodInfo; #ifdef ANDROID_AMAZON #else if(! JniHelper::getStaticMethodInfo(methodInfo, CLASS_NAME, "captureAvatar", "(Ljava/lang/String;)V")) #endif return; jstring param = methodInfo.env->NewStringUTF(user_id.c_str()); methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, param); methodInfo.env->DeleteLocalRef(param); methodInfo.env->DeleteLocalRef(methodInfo.classID); #endif } void nativeCompletedCaptureAvatar(JNIEnv *env, jobject obj, jstring file_path) { jboolean isCopy; const char* path; path = env->GetStringUTFChars(file_path, &isCopy); if(g_pCurrentLayer != NULL && g_pCurrentLayer->m_nType == LAYER_SETTING) ((SettingLayer*)g_pCurrentLayer)->updateProfile(path); } }
27.769231
117
0.693075
GuruDev0807
82cb697fa829ffbb50bf5892b434d01a7efef170
116
hh
C++
src/Environment.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
null
null
null
src/Environment.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
null
null
null
src/Environment.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
null
null
null
#pragma once #include <glow/fwd.hh> #include <typed-geometry/tg.hh> namespace gamedev { class Environment { }; }
8.923077
31
0.706897
rovedit
82d38d5722252f23dcd2c1cfd3ecebcf36cb67b1
1,239
cpp
C++
leetcode/binarytreepostordertravesal.cpp
WIZARD-CXY/pl
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
[ "Apache-2.0" ]
1
2016-01-20T08:26:34.000Z
2016-01-20T08:26:34.000Z
leetcode/binarytreepostordertravesal.cpp
WIZARD-CXY/pl
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
[ "Apache-2.0" ]
1
2015-10-21T05:38:17.000Z
2015-11-02T07:42:55.000Z
leetcode/binarytreepostordertravesal.cpp
WIZARD-CXY/pl
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
[ "Apache-2.0" ]
null
null
null
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> postorderTraversal(TreeNode* root) { vector<int> res; //p is the current visiting pointer,q is just visited poointer TreeNode *p,*q; stack<TreeNode*> ss; p=root; do{ while(p!=NULL){ //go left; ss.push(p); p=p->left; } q=NULL; while(!ss.empty()){ p=ss.top(); ss.pop(); if(p->right==q){ //right child is visited or no exist //add to res res.push_back(p->val); q=p; }else{ //not ready yet.push it back ss.push(p); p=p->right; break; } } }while(!ss.empty()); return res; } };
23.377358
70
0.357546
WIZARD-CXY
82d6a6123fcf3664d4a8f2e930bda06514fdff6f
320
cpp
C++
vs_plrlsght_cpp_fndmntls/vs_plrlsght_cpp_fndmntls/Resource.cpp
mugofjoe/cpp-journal
8b9f4d14343a2241ebe7def8b1f03062dae9caf6
[ "MIT" ]
null
null
null
vs_plrlsght_cpp_fndmntls/vs_plrlsght_cpp_fndmntls/Resource.cpp
mugofjoe/cpp-journal
8b9f4d14343a2241ebe7def8b1f03062dae9caf6
[ "MIT" ]
null
null
null
vs_plrlsght_cpp_fndmntls/vs_plrlsght_cpp_fndmntls/Resource.cpp
mugofjoe/cpp-journal
8b9f4d14343a2241ebe7def8b1f03062dae9caf6
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "Resource.h" #include <iostream> using std::cout; using std::endl; using std::string; Resource::Resource(string n) :name(n) { cout << "constructing Resource object: " << name << endl; } Resource::~Resource(void) { cout << "destructing Resource object: " << name << endl; }
20
59
0.64375
mugofjoe
82d9ec8e2f7e34826104e47fa7794f403330e2cd
6,048
cpp
C++
Tests/UnitTests/Sources/FunctionTest/BroadcastTest.cpp
sukim96/Sapphire
7eba047a376d2bfa6cc3182daa143cbe659a1c18
[ "MIT" ]
6
2021-07-06T10:52:33.000Z
2021-12-30T11:30:04.000Z
Tests/UnitTests/Sources/FunctionTest/BroadcastTest.cpp
sukim96/Sapphire
7eba047a376d2bfa6cc3182daa143cbe659a1c18
[ "MIT" ]
1
2022-01-07T12:18:03.000Z
2022-01-08T12:23:13.000Z
Tests/UnitTests/Sources/FunctionTest/BroadcastTest.cpp
sukim96/Sapphire
7eba047a376d2bfa6cc3182daa143cbe659a1c18
[ "MIT" ]
3
2021-12-05T06:21:50.000Z
2022-01-09T12:44:23.000Z
// Copyright (c) 2021, Justin Kim // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include <FunctionTest/BroadcastTest.hpp> #include <Sapphire/compute/BasicOps.hpp> #include <Sapphire/compute/Initialize.hpp> #include <Sapphire/util/Shape.hpp> #include <Sapphire/tensor/TensorData.hpp> #include <Sapphire/util/CudaDevice.hpp> #include <Sapphire/util/ResourceManager.hpp> #include <TestUtil.hpp> #include <iostream> #include <random> namespace Sapphire::Test { void BroadcastWithOneDimension(bool print) { std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> distrib(1, 10); const int M = distrib(gen); const int N = distrib(gen); const int K = distrib(gen); const int batchSize = distrib(gen) % 3 + 1; //! Set shape so they can be broadcasted const Shape shapeA({ batchSize, 1, M, K }); const Shape shapeB({ batchSize, M, K, N }); const Shape shapeOut({ batchSize, M, M, N }); std::cout << "M : " << M << " N: " << N << " K: " << K << " batchSize : " << batchSize << std::endl; const CudaDevice cuda(0, "device0"); //! Initialize tensors with cuda mode TensorUtil::TensorData A(shapeA, Type::Dense, cuda); TensorUtil::TensorData B(shapeB, Type::Dense, cuda); TensorUtil::TensorData Out(shapeOut, Type::Dense, cuda); A.SetMode(ComputeMode::Host); B.SetMode(ComputeMode::Host); Out.SetMode(ComputeMode::Host); //! Initialize input tensors with normal distribution and output tensors as zeros Compute::Initialize::Normal(A, 10, 5); Compute::Initialize::Normal(B, 10, 5); Compute::Initialize::Zeros(Out); Compute::Gemm(Out, A, B); //! Set temporary buffer and copy the result auto* cpuGemmResult = new float[Out.HostTotalSize]; std::memcpy(cpuGemmResult, Out.HostRawPtr(), Out.HostTotalSize * sizeof(float)); //! Initialize output with zeros Compute::Initialize::Zeros(Out); //! Send data to cuda A.ToCuda(); B.ToCuda(); Out.ToCuda(); //! Perform Gemm on cuda Compute::Gemm(Out, A, B); //! Send output data to host Out.ToHost(); //! Check for non zero equality CheckNoneZeroEquality(cpuGemmResult, Out.HostRawPtr(), Out.HostTotalSize, print, 1.5f); delete[] cpuGemmResult; } void BroadcastWithMissingDimension(bool print) { std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> distrib(1, 10); const int M = distrib(gen); const int N = distrib(gen); const int K = distrib(gen); //! Set shape so they can be broadcasted const Shape shapeA({ M, K }); const Shape shapeB({ M, K, N }); const Shape shapeOut({ M, M, N }); std::cout << "M : " << M << " N: " << N << " K: " << K << std::endl; const CudaDevice cuda(0, "device0"); //! Initialize tensors with cuda mode TensorUtil::TensorData A(shapeA, Type::Dense, cuda); TensorUtil::TensorData B(shapeB, Type::Dense, cuda); TensorUtil::TensorData Out(shapeOut, Type::Dense, cuda); A.SetMode(ComputeMode::Host); B.SetMode(ComputeMode::Host); Out.SetMode(ComputeMode::Host); //! Initialize input tensors with normal distribution and output tensors as //! zeros Compute::Initialize::Normal(A, 10, 5); Compute::Initialize::Normal(B, 10, 5); Compute::Initialize::Zeros(Out); //! Perform Gemm on host Compute::Gemm(Out, A, B); //! Set temporary buffer and copy the result auto* cpuGemmResult = new float[Out.HostTotalSize]; std::memcpy(cpuGemmResult, Out.HostRawPtr(), Out.HostTotalSize * sizeof(float)); //! Initialize output with zeros Compute::Initialize::Zeros(Out); //! Send data to cuda A.ToCuda(); B.ToCuda(); Out.ToCuda(); //! Perform Gemm on cuda Compute::Gemm(Out, A, B); //! Send output data to host Out.ToHost(); //! Check for non zero equality CheckNoneZeroEquality(cpuGemmResult, Out.HostRawPtr(), Out.HostTotalSize, print, 1.5f); delete[] cpuGemmResult; } void BroadcastMixed(bool print) { std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> distrib(1, 10); const int M = distrib(gen); const int N = distrib(gen); const int K = distrib(gen); //! Set shape so they can be broadcasted const Shape shapeA({ M, K }); const Shape shapeB({ N, M, K, N }); const Shape shapeOut({ N, M, M, N }); std::cout << "M : " << M << " N: " << N << " K: " << K << std::endl; const CudaDevice cuda(0, "device0"); //! Initialize tensors with cuda mode TensorUtil::TensorData A(shapeA, Type::Dense, cuda); TensorUtil::TensorData B(shapeB, Type::Dense, cuda); TensorUtil::TensorData Out(shapeOut, Type::Dense, cuda); A.SetMode(ComputeMode::Host); B.SetMode(ComputeMode::Host); Out.SetMode(ComputeMode::Host); //! Initialize input tensors with normal distribution and output tensors //! as zeros Compute::Initialize::Normal(A, 10, 5); Compute::Initialize::Normal(B, 10, 5); Compute::Initialize::Zeros(Out); //! Perform Gemm on host Compute::Gemm(Out, A, B); //! Set temporary buffer and copy the result auto* cpuGemmResult = new float[Out.HostTotalSize]; std::memcpy(cpuGemmResult, Out.HostRawPtr(), Out.HostTotalSize * sizeof(float)); //! Initialize output with zeros Compute::Initialize::Zeros(Out); //! Send data to cuda A.ToCuda(); B.ToCuda(); Out.ToCuda(); //! Perform Gemm on cuda Compute::Gemm(Out, A, B); //! Send output data to host Out.ToHost(); //! Check for non zero equality CheckNoneZeroEquality(cpuGemmResult, Out.HostRawPtr(), Out.HostTotalSize, print, 1.5f); delete[] cpuGemmResult; } } // namespace Sapphire::Test
29.647059
85
0.636409
sukim96
82e1671d75e2ef454b2c17af1df7a2ffcab632f9
4,118
cpp
C++
discoFever/main.cpp
oskrs111/pimcw
6b40830b97ca7b6d2e5e7c50227ac7b2f5981749
[ "MIT" ]
2
2017-11-01T01:18:12.000Z
2017-12-13T06:04:00.000Z
discoFever/main.cpp
oskrs111/pimcw
6b40830b97ca7b6d2e5e7c50227ac7b2f5981749
[ "MIT" ]
null
null
null
discoFever/main.cpp
oskrs111/pimcw
6b40830b97ca7b6d2e5e7c50227ac7b2f5981749
[ "MIT" ]
1
2019-12-01T23:40:25.000Z
2019-12-01T23:40:25.000Z
#include "main.h" #include "networkthread.h" #include "../qtkVirtualMIDI/qtkvirtualmidi.h" void debugLogger(QtMsgType type, const QMessageLogContext &context, const QString &msg) { QByteArray localMsg = msg.toLocal8Bit(); switch (type) { default: case QtInfoMsg: case QtDebugMsg: localMsg.prepend("DEBUG: "); fprintf(stderr, "Debug: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function); break; case QtWarningMsg: localMsg.prepend("WARNING: "); fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function); break; case QtCriticalMsg: localMsg.prepend("CRITICAL: "); fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function); break; case QtFatalMsg: localMsg.prepend("FATAL: "); fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function); abort(); } localMsg.append("\r\n"); QFile f("debug.log"); f.open(QIODevice::Append); f.write(localMsg); f.close(); } static QtKApplicationParameters* g_appParameters = 0; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); qDebug() << "discoFever starting..."; g_appParameters = new QtKApplicationParameters(0,QString("discoFever")); if(g_appParameters->fileLoad(false)) { setDefaultParameters(); QString msg = "discoFever.cfg not found!\r\nSetting default configuration."; qDebug() << msg; a.exit(); } if(!g_appParameters->loadParam(QString("aplicacion"),QString("fileLog"),0).compare("1")) { qInstallMessageHandler(debugLogger); } qtkVirtualMIDI midi; networkThread network(QHostAddress(g_appParameters->loadParam(QString("network"),QString("udpHost"),0)), (quint16)g_appParameters->loadParam(QString("network"),QString("udpPort"),0).toInt(), (quint8)g_appParameters->loadParam(QString("network"),QString("statusRepeat"),0).toInt(), (quint8)g_appParameters->loadParam(QString("network"),QString("midiOffIgnore"),0).toInt(), (quint8)g_appParameters->loadParam(QString("network"),QString("midiChannelFilter"),0).toInt(), (quint8)g_appParameters->loadParam(QString("network"),QString("midiChannelFilterEnable"),0).toInt(), (quint8)g_appParameters->loadParam(QString("network"),QString("midiNoteOffset"),0).toInt()); switch(midi.getStatus()) { case stReady: QObject::connect(&midi,SIGNAL(midiReceived(midiMessage)),&network, SLOT(OnMidiReceived(midiMessage))); network.start(); qDebug() << "discoFever is ready to dance!"; return a.exec(); break; case stUnknown: case stClosed: case stError: default: qDebug() << "qtkVirtualMIDI error, status: " << midi.getStatus(); qDebug() << "discoFever will exit now..."; break; } return 0; } void setDefaultParameters() { //fileLog->Enables "1" or disables "0" debug log to file. g_appParameters->saveParam(QString("aplicacion"),QString("fileLog"),QString("0")); g_appParameters->saveParam(QString("network"),QString("udpHost"),QString("192.168.0.100")); g_appParameters->saveParam(QString("network"),QString("udpPort"),QString("12340")); g_appParameters->saveParam(QString("network"),QString("statusRepeat"),QString("3")); g_appParameters->saveParam(QString("network"),QString("midiOffIgnore"),QString("0")); g_appParameters->saveParam(QString("network"),QString("midiChannelFilter"),QString("0")); g_appParameters->saveParam(QString("network"),QString("midiChannelFilterEnable"),QString("0")); g_appParameters->saveParam(QString("network"),QString("midiNoteOffset"),QString("0")); g_appParameters->fileSave(); }
38.849057
126
0.63356
oskrs111
82e247eeecf88645ed78f119061fa3b1cf88ce6e
1,970
cpp
C++
src/test.cpp
tonyganchev/stoyozipxx
a19493d53a8c118e06003480b1614e5fa1cacb72
[ "Apache-2.0" ]
1
2019-11-25T17:02:51.000Z
2019-11-25T17:02:51.000Z
src/test.cpp
tonyganchev/stoyozipxx
a19493d53a8c118e06003480b1614e5fa1cacb72
[ "Apache-2.0" ]
null
null
null
src/test.cpp
tonyganchev/stoyozipxx
a19493d53a8c118e06003480b1614e5fa1cacb72
[ "Apache-2.0" ]
1
2019-11-11T11:11:02.000Z
2019-11-11T11:11:02.000Z
#include <iostream> #include <sstream> #include "buffer.hpp" #include "oligorithm.hpp" using namespace std; void test_find_longest_match(string needle, string haystack, size_t expected_length, size_t expected_start_idx) { auto m = szxx::find_longest_prefix(needle.begin(), needle.end(), haystack.begin(), haystack.end()); if (expected_length != m.second - m.first || (expected_length > 0 && expected_start_idx != m.first - haystack.begin())) { cout << "FAIL finding the expected prefix of '" << needle << "' in '" << haystack << "'.\n"; cout << "Instead matched '"; copy(m.first, m.second, ostream_iterator<char>(cout)); cout << "' of length " << m.second - m.first << "." << endl; } } int main() { stringstream is("sum dolor sit amet gatsi gatsi."); szxx::buffer buf{ 4u, 4u }; buf.push_back('L'); buf.push_back('o'); buf.push_back('r'); buf.push_back('e'); buf.push_back('m'); buf.push_back(' '); buf.push_back('i'); buf.push_back('p'); cout << buf << endl; while (!buf.lookahead_empty()) { cout << "--------------------------" << endl; cout << buf << endl; buf.forward(1u, is); cout << buf << endl; } test_find_longest_match("abc", "efghijk", 0, 0); test_find_longest_match("cde", "efghijk", 0, 0); test_find_longest_match("exyz", "efghijk", 1, 0); test_find_longest_match("efghijk", "efghijk", 7, 0); test_find_longest_match("abc", "efghijk", 0, 0); test_find_longest_match("", "efghijk", 0, 0); test_find_longest_match("efghijklmnop", "efghijk", 7, 0); test_find_longest_match("efghij", "efghijk", 6, 0); test_find_longest_match("ghij", "efghijk", 4, 2); test_find_longest_match("ghijk", "efghijk", 5, 2); test_find_longest_match("ghijkl", "efghijk", 5, 2); test_find_longest_match("kl", "efghijk", 1, 6); test_find_longest_match("f", "efghijk efghijk efghijk", 1, 1); return 0; }
32.833333
82
0.614721
tonyganchev
82e2cb8aaacffae8dbcfa3f9c0fb6cd461f1f59e
1,031
cpp
C++
Development_Platformer/Development_Platformer/GUIThumb.cpp
vsRushy/Development_Platformer
b9b6d3ce1611bd3e83d0dab2485c55d5acb32afe
[ "MIT" ]
1
2018-10-10T12:09:31.000Z
2018-10-10T12:09:31.000Z
Development_Platformer/Development_Platformer/GUIThumb.cpp
vsRushy/Development_Platformer
b9b6d3ce1611bd3e83d0dab2485c55d5acb32afe
[ "MIT" ]
null
null
null
Development_Platformer/Development_Platformer/GUIThumb.cpp
vsRushy/Development_Platformer
b9b6d3ce1611bd3e83d0dab2485c55d5acb32afe
[ "MIT" ]
null
null
null
#include "j1App.h" #include "j1Input.h" #include "j1GUIManager.h" #include "GUIElement.h" #include "GUIThumb.h" #include "p2Log.h" GUIThumb::GUIThumb(int x, int y, SDL_Rect image_area, SDL_Rect image_area_hover, SDL_Rect image_area_pressed, GUIElement* son) : GUIElement(type, x, y, area, son) { type = GUI_ELEMENT_TYPE::GUI_THUMB; initial_area = image_area; area = initial_area; img_area_hover = image_area_hover; img_area_pressed = image_area_pressed; } void GUIThumb::Update(float dt) { Click(); Move(); } void GUIThumb::Click() { int x, y; App->input->GetMousePosition(x, y); bool is_inside = x > position.x && x < position.x + initial_area.w && y > position.y && y < position.y + initial_area.h; if (is_inside) { if (App->input->GetMouseButtonDown(1) == SDL_PRESSED) { is_clicked = true; area = img_area_pressed; } else if (App->input->GetMouseButtonDown(1) == SDL_RELEASED) { is_clicked = false; area = img_area_hover; } } else { is_clicked = false; area = initial_area; } }
20.62
162
0.691562
vsRushy
82e7dfaa6b8e56ed5cda49b057e9012cb81bbe82
14,113
cpp
C++
src/temporal_diff.cpp
uwmri/mri_recon
c74780d56c87603fb935744bf312e8c59d415997
[ "BSD-3-Clause" ]
null
null
null
src/temporal_diff.cpp
uwmri/mri_recon
c74780d56c87603fb935744bf312e8c59d415997
[ "BSD-3-Clause" ]
2
2020-11-06T19:45:34.000Z
2020-11-07T03:22:25.000Z
src/temporal_diff.cpp
uwmri/mri_recon
c74780d56c87603fb935744bf312e8c59d415997
[ "BSD-3-Clause" ]
null
null
null
/************************************************ 3D Wavlet Libraries for pcvipr.e Initial Author: Kevin M. Johnson Description: This code controls transfroms in the non-spatial dimensions *************************************************/ #include "temporal_diff.h" using namespace NDarray; using arma::cx_mat; using arma::cx_vec; TRANSFORMS::TRANSFORMS() { reinit_pca = true; pca_count = 0; } void TRANSFORMS::get_difference_transform(cx_mat &A, cx_mat &Ai, int N) { A.zeros(N, N); Ai.zeros(N, N); for (int i = 0; i < N; i++) { A(0, i) = 1.0; } for (int i = 1; i < N; i++) { A(i, i - 1) = 1.0; A(i, i) = -1.0; } Ai = A.i(); return; } void TRANSFORMS::get_wavelet_transform(cx_mat &A, cx_mat &Ai, int N) { A.zeros(N, N); Ai.zeros(N, N); int levels = (int)log2((double)N); // cout << "Levels = " << levels << endl; for (int level = 0; level < levels; level++) { // R is the center of the matrix int R = (int)(0.5 * (float)N / pow((float)2.0, (float)level)); int span = (int)pow(2.0f, (float)level); for (int i = 0; i < R; i++) { int offset = 2 * span * i; // Zero the rows for (int j = 0; j < N; j++) { A(i, j) = complex<float>(0.0, 0.0); A(i + R, j) = complex<float>(0.0, 0.0); } // Set the average for (int j = offset; j < offset + 2 * span; j++) { A(i, j) = 1.0; } // Set the difference for (int j = offset; j < offset + span; j++) { A(i + R, j) = 1.0; A(i + R, j + span) = -1.0; } } // A.print("A-wavelet"); } // Normalize for (int i = 0; i < N; i++) { float temp = 0.0; for (int j = 0; j < N; j++) { temp += norm(A(i, j)); } temp = sqrt(temp); for (int j = 0; j < N; j++) { A(i, j) /= temp; } } // A.print("A-noramlize wavelet"); Ai = A.i(); return; } void TRANSFORMS::tdiff(Array<Array<complex<float>, 3>, 2> &temp) { if (temp.length(firstDim) == 1) { return; } cx_mat A; cx_mat Ai; get_difference_transform(A, Ai, temp.length(firstDim)); multiply_in_time(temp, A); return; } void TRANSFORMS::inv_tdiff(Array<Array<complex<float>, 3>, 2> &temp) { if (temp.length(firstDim) == 1) { return; } cx_mat A; cx_mat Ai; get_difference_transform(A, Ai, temp.length(firstDim)); multiply_in_time(temp, Ai); return; } void TRANSFORMS::twave(Array<Array<complex<float>, 3>, 2> &temp) { if (temp.length(firstDim) == 1) { return; } cx_mat A; cx_mat Ai; get_wavelet_transform(A, Ai, temp.length(firstDim)); multiply_in_time(temp, A); return; } void TRANSFORMS::inv_twave(Array<Array<complex<float>, 3>, 2> &temp) { if (temp.length(firstDim) == 1) { return; } cx_mat A; cx_mat Ai; get_wavelet_transform(A, Ai, temp.length(firstDim)); multiply_in_time(temp, Ai); return; } void TRANSFORMS::ediff(Array<Array<complex<float>, 3>, 2> &temp) { if (temp.length(secondDim) == 1) { return; } cx_mat A; cx_mat Ai; get_difference_transform(A, Ai, temp.length(secondDim)); multiply_in_encode(temp, A); return; } void TRANSFORMS::inv_ediff(Array<Array<complex<float>, 3>, 2> &temp) { if (temp.length(secondDim) == 1) { return; } cx_mat A; cx_mat Ai; get_difference_transform(A, Ai, temp.length(secondDim)); multiply_in_encode(temp, Ai); return; } void TRANSFORMS::ewave(Array<Array<complex<float>, 3>, 2> &temp) { if (temp.length(secondDim) == 1) { return; } cx_mat A; cx_mat Ai; get_wavelet_transform(A, Ai, temp.length(secondDim)); multiply_in_encode(temp, A); return; } void TRANSFORMS::inv_ewave(Array<Array<complex<float>, 3>, 2> &temp) { if (temp.length(secondDim) == 1) { return; } cx_mat A; cx_mat Ai; get_wavelet_transform(A, Ai, temp.length(secondDim)); multiply_in_encode(temp, Ai); return; } //----------------------------------------------------- // Clear Threshold Call //----------------------------------------------------- void TRANSFORMS::eigen(Array<Array<complex<float>, 3>, 2> &image, int dim, int direction) { pca_count++; if (reinit_pca && (direction == FORWARD)) { if (pca_count > 5) { reinit_pca = false; } // Shorthand int Nt = image.extent(firstDim); int Ne = image.extent(secondDim); int Nx = image(0, 0).extent(firstDim); int Ny = image(0, 0).extent(secondDim); int Nz = image(0, 0).extent(thirdDim); int block_size_x = 8; int block_size_y = 8; int block_size_z = 8; block_size_x = (block_size_x > Nx) ? (Nx) : (block_size_x); block_size_y = (block_size_y > Ny) ? (Ny) : (block_size_y); block_size_z = (block_size_z > Nz) ? (Nz) : (block_size_z); int block_Nx = (int)(Nx / block_size_x); int block_Ny = (int)(Ny / block_size_y); int block_Nz = (int)(Nz / block_size_z); int total_blocks = block_Nx * block_Ny * block_Nz; /* Get Image Size*/ int N = image.extent(dim); int Np = total_blocks; cout << " Learning Eigen Mat (N=" << N << ")(Np = " << Np << ")" << endl; // For nested parallelism fix int count = 0; arma::Col<int> act_i(total_blocks); arma::Col<int> act_j(total_blocks); arma::Col<int> act_k(total_blocks); for (int i = 0; i < block_Nx; i++) { for (int j = 0; j < block_Ny; j++) { for (int k = 0; k < block_Nz; k++) { act_i(count) = i; act_j(count) = j; act_k(count) = k; count++; } } } // Storage Block arma::cx_mat A; A.zeros(Np, N); cout << "Collecting Blocks" << endl; #pragma omp parallel for for (int block = 0; block < total_blocks; block++) { // Nested parallelism workaround int i = act_i(block) * block_size_x; int j = act_j(block) * block_size_y; int k = act_k(block) * block_size_z; //----------------------------------------------------- // Block Gather //----------------------------------------------------- switch (dim) { case (0): { for (int t = 0; t < Nt; t++) { for (int e = 0; e < Ne; e++) { for (int kk = (k); kk < (k + block_size_z); kk++) { for (int jj = (j); jj < (j + block_size_y); jj++) { for (int ii = (i); ii < (i + block_size_x); ii++) { int px = (ii + Nx) % Nx; int py = (jj + Ny) % Ny; int pz = (kk + Nz) % Nz; A(block, t) += image(t, e)(px, py, pz); } } } } } } break; case (1): { for (int e = 0; e < Ne; e++) { for (int t = 0; t < Nt; t++) { for (int kk = (k); kk < (k + block_size_z); kk++) { for (int jj = (j); jj < (j + block_size_y); jj++) { for (int ii = (i); ii < (i + block_size_x); ii++) { int px = (ii + Nx) % Nx; int py = (jj + Ny) % Ny; int pz = (kk + Nz) % Nz; A(block, e) += image(t, e)(px, py, pz); } } } } } } break; } // Switch Dim } // Block Loop cout << "Learning PCA " << endl; arma::cx_mat U; arma::cx_mat V; arma::vec s; arma::svd_econ(U, s, V, A); cx_mat wV = diagmat(s) * V.t(); E = wV; Ei = wV.i(); } /* Reinit PCA*/ if (dim == 0) { if (direction == FORWARD) { multiply_in_time(image, E); } else { multiply_in_time(image, Ei); } } else { if (direction == FORWARD) { multiply_in_encode(image, E); } else { multiply_in_encode(image, Ei); } } if (direction == FORWARD) { if (image.numElements() > 1) { int count = 0; for (Array<Array<complex<float>, 3>, 2>::iterator miter = image.begin(); miter != image.end(); miter++) { Array<complex<float>, 2> Xf = (*miter)(Range::all(), Range::all(), image(0, 0).length(2) / 2); if (count == 0) { ArrayWriteMag(Xf, "Xtrans_frames.dat"); } else { ArrayWriteMagAppend(Xf, "Xtrans_frames.dat"); } count++; } } } } void TRANSFORMS::multiply_in_time(Array<Array<complex<float>, 3>, 2> &temp, cx_mat A) { int Nt = temp.length(firstDim); int Ne = temp.length(secondDim); int Nx = temp(0).length(firstDim); int Ny = temp(0).length(secondDim); int Nz = temp(0).length(thirdDim); for (int e = 0; e < Ne; e++) { #pragma omp parallel for for (int k = 0; k < Nz; k++) { cx_vec s(Nt); cx_vec ss(Nt); for (int j = 0; j < Ny; j++) { for (int i = 0; i < Nx; i++) { // Copy for (int t = 0; t < Nt; t++) { s(t) = temp(t, e)(i, j, k); } // Transform ss = A * s; // Copy Back for (int t = 0; t < Nt; t++) { temp(t, e)(i, j, k) = ss(t); } } } } } return; } void TRANSFORMS::multiply_in_encode(Array<Array<complex<float>, 3>, 2> &temp, cx_mat A) { int Nt = temp.length(firstDim); int Ne = temp.length(secondDim); int Nx = temp(0).length(firstDim); int Ny = temp(0).length(secondDim); int Nz = temp(0).length(thirdDim); for (int t = 0; t < Nt; t++) { #pragma omp parallel for for (int k = 0; k < Nz; k++) { cx_vec s(Ne); cx_vec ss(Ne); for (int j = 0; j < Ny; j++) { for (int i = 0; i < Nx; i++) { // Copy for (int e = 0; e < Ne; e++) { s(e) = temp(t, e)(i, j, k); } // Transform ss = A * s; // Copy Back for (int e = 0; e < Ne; e++) { temp(t, e)(i, j, k) = ss(e); } } } } } return; } void TRANSFORMS::fft_t(Array<Array<complex<float>, 3>, 2> &temp) { int Nt = temp.length(firstDim); int Ne = temp.length(secondDim); int Nx = temp(0).length(firstDim); int Ny = temp(0).length(secondDim); int Nz = temp(0).length(thirdDim); fftwf_plan p; complex<float> *in = new complex<float>[Nt]; // fftwf_init_threads(); // fftwf_plan_with_nthreads(1); p = fftwf_plan_dft_1d(Nt, (fftwf_complex *)in, (fftwf_complex *)in, FFTW_FORWARD, FFTW_MEASURE); float fft_scale = 1 / sqrt(Nt); for (int e = 0; e < Ne; e++) { for (int k = 0; k < Nz; k++) { for (int j = 0; j < Ny; j++) { for (int i = 0; i < Nx; i++) { // Copy for (int t = 0; t < Nt; t++) { in[t] = temp(t, e)(i, j, k); } fftwf_execute(p); // Copy Back for (int t = 0; t < Nt; t++) { temp(t, e)(i, j, k) = (fft_scale * in[t]); } } } } } fftwf_destroy_plan(p); delete[] in; return; } void TRANSFORMS::ifft_t(Array<Array<complex<float>, 3>, 2> &temp) { int Nt = temp.length(firstDim); int Ne = temp.length(secondDim); int Nx = temp(0).length(firstDim); int Ny = temp(0).length(secondDim); int Nz = temp(0).length(thirdDim); fftwf_plan p; complex<float> *in = new complex<float>[Nt]; // fftwf_init_threads(); // fftwf_plan_with_nthreads(1); p = fftwf_plan_dft_1d(Nt, (fftwf_complex *)in, (fftwf_complex *)in, FFTW_BACKWARD, FFTW_MEASURE); float fft_scale = 1 / sqrt(Nt); for (int e = 0; e < Ne; e++) { for (int k = 0; k < Nz; k++) { for (int j = 0; j < Ny; j++) { for (int i = 0; i < Nx; i++) { // Copy for (int t = 0; t < Nt; t++) { in[t] = temp(t, e)(i, j, k); } fftwf_execute(p); // Copy Back for (int t = 0; t < Nt; t++) { temp(t, e)(i, j, k) = (fft_scale * in[t]); } } } } } fftwf_destroy_plan(p); delete[] in; return; } void TRANSFORMS::fft_e(Array<Array<complex<float>, 3>, 2> &temp) { int Nt = temp.length(firstDim); int Ne = temp.length(secondDim); int Nx = temp(0).length(firstDim); int Ny = temp(0).length(secondDim); int Nz = temp(0).length(thirdDim); fftwf_plan p; complex<float> *in = new complex<float>[Ne]; // fftwf_init_threads(); // fftwf_plan_with_nthreads(1); p = fftwf_plan_dft_1d(Ne, (fftwf_complex *)in, (fftwf_complex *)in, FFTW_FORWARD, FFTW_MEASURE); float fft_scale = 1 / sqrt(Ne); for (int t = 0; t < Nt; t++) { for (int k = 0; k < Nz; k++) { for (int j = 0; j < Ny; j++) { for (int i = 0; i < Nx; i++) { // Copy for (int e = 0; e < Ne; e++) { in[e] = temp(t, e)(i, j, k); } fftwf_execute(p); // Copy Back for (int e = 0; e < Ne; e++) { temp(t, e)(i, j, k) = (fft_scale * in[e]); } } } } } fftwf_destroy_plan(p); delete[] in; return; } void TRANSFORMS::ifft_e(Array<Array<complex<float>, 3>, 2> &temp) { int Nt = temp.length(firstDim); int Ne = temp.length(secondDim); int Nx = temp(0).length(firstDim); int Ny = temp(0).length(secondDim); int Nz = temp(0).length(thirdDim); fftwf_plan p; complex<float> *in = new complex<float>[Ne]; // fftwf_init_threads(); // fftwf_plan_with_nthreads(1); p = fftwf_plan_dft_1d(Ne, (fftwf_complex *)in, (fftwf_complex *)in, FFTW_BACKWARD, FFTW_MEASURE); float fft_scale = 1 / sqrt(Ne); for (int t = 0; t < Nt; t++) { for (int k = 0; k < Nz; k++) { for (int j = 0; j < Ny; j++) { for (int i = 0; i < Nx; i++) { // Copy for (int e = 0; e < Ne; e++) { in[e] = temp(t, e)(i, j, k); } fftwf_execute(p); // Copy Back for (int e = 0; e < Ne; e++) { temp(t, e)(i, j, k) = (fft_scale * in[e]); } } } } } fftwf_destroy_plan(p); delete[] in; return; }
24.416955
78
0.489124
uwmri
82e9519183a5fb683af7b80b261fdcc518f15543
12,327
cpp
C++
src/wrapper/store/provider_cryptopro.cpp
microshine/trusted-crypto
22a6496bd390ebe2ed516a15636d911fae4c6407
[ "Apache-2.0" ]
null
null
null
src/wrapper/store/provider_cryptopro.cpp
microshine/trusted-crypto
22a6496bd390ebe2ed516a15636d911fae4c6407
[ "Apache-2.0" ]
null
null
null
src/wrapper/store/provider_cryptopro.cpp
microshine/trusted-crypto
22a6496bd390ebe2ed516a15636d911fae4c6407
[ "Apache-2.0" ]
1
2020-07-01T16:32:57.000Z
2020-07-01T16:32:57.000Z
#include "../stdafx.h" #include "provider_cryptopro.h" ProviderCryptopro::ProviderCryptopro(){ LOGGER_FN(); try{ type = new std::string("CRYPTOPRO"); providerItemCollection = new PkiItemCollection(); init(); } catch (Handle<Exception> e){ THROW_EXCEPTION(0, ProviderCryptopro, e, "Cannot be constructed ProviderCryptopro"); } } void ProviderCryptopro::init(){ LOGGER_FN(); try{ std::string listStore[] = { "MY", "AddressBook", "ROOT", "TRUST", "CA", "Request" }; HCERTSTORE hCertStore; for (int i = 0, c = sizeof(listStore) / sizeof(*listStore); i < c; i++){ std::wstring widestr = std::wstring(listStore[i].begin(), listStore[i].end()); hCertStore = CertOpenStore( CERT_STORE_PROV_SYSTEM, PKCS_7_ASN_ENCODING | X509_ASN_ENCODING, NULL, CERT_SYSTEM_STORE_CURRENT_USER, widestr.c_str() ); if (!hCertStore) { THROW_EXCEPTION(0, ProviderCryptopro, NULL, "Error open store"); } enumCertificates(hCertStore, &listStore[i]); enumCrls(hCertStore, &listStore[i]); if (hCertStore) { CertCloseStore(hCertStore, 0); } } } catch (Handle<Exception> e){ THROW_EXCEPTION(0, ProviderCryptopro, e, "Error init CryptoPRO provider"); } } void ProviderCryptopro::enumCertificates(HCERTSTORE hCertStore, std::string *category){ LOGGER_FN(); try{ X509 *cert = NULL; const unsigned char *p; if (!hCertStore){ THROW_EXCEPTION(0, ProviderCryptopro, NULL, "Certificate store not opened"); } PCCERT_CONTEXT pCertContext = NULL; do { pCertContext = CertEnumCertificatesInStore(hCertStore, pCertContext); if (pCertContext){ p = pCertContext->pbCertEncoded; LOGGER_OPENSSL(d2i_X509); if (!(cert = d2i_X509(NULL, &p, pCertContext->cbCertEncoded))) { THROW_OPENSSL_EXCEPTION(0, ProviderCryptopro, NULL, "'d2i_X509' Error decode len bytes"); } Handle<PkiItem> item = objectToPKIItem(new Certificate(cert)); item->category = new std::string(*category); DWORD * pdwKeySpec; BOOL * pfCallerFreeProv; HCRYPTPROV m_hProv; if (CryptAcquireCertificatePrivateKey(pCertContext, NULL, NULL, &m_hProv, pdwKeySpec, pfCallerFreeProv)){ item->certKey = new std::string("1"); } providerItemCollection->push(item); } } while (pCertContext != NULL); if (pCertContext){ CertFreeCertificateContext(pCertContext); } } catch (Handle<Exception> e){ THROW_EXCEPTION(0, ProviderCryptopro, e, "Error enum certificates in store"); } } void ProviderCryptopro::enumCrls(HCERTSTORE hCertStore, std::string *category){ LOGGER_FN(); try{ X509_CRL *crl = NULL; const unsigned char *p; if (!hCertStore){ THROW_EXCEPTION(0, ProviderCryptopro, NULL, "Certificate store not opened"); } PCCRL_CONTEXT pCrlContext = NULL; do { pCrlContext = CertEnumCRLsInStore(hCertStore, pCrlContext); if (pCrlContext){ p = pCrlContext->pbCrlEncoded; LOGGER_OPENSSL(d2i_X509_CRL); if (!(crl = d2i_X509_CRL(NULL, &p, pCrlContext->cbCrlEncoded))) { THROW_OPENSSL_EXCEPTION(0, ProviderCryptopro, NULL, "'d2i_X509_CRL' Error decode len bytes"); } Handle<PkiItem> item = objectToPKIItem(new CRL(crl)); item->category = new std::string(*category); providerItemCollection->push(item); } } while (pCrlContext != NULL); if (pCrlContext){ CertFreeCRLContext(pCrlContext); } } catch (Handle<Exception> e){ THROW_EXCEPTION(0, ProviderCryptopro, e, "Error enum CRLs in store"); } } Handle<PkiItem> ProviderCryptopro::objectToPKIItem(Handle<Certificate> cert){ LOGGER_FN(); try{ if (cert.isEmpty()){ THROW_EXCEPTION(0, ProviderCryptopro, NULL, "Certificate empty"); } Handle<PkiItem> item = new PkiItem(); item->format = new std::string("DER"); item->type = new std::string("CERTIFICATE"); item->provider = new std::string("CRYPTOPRO"); char * hexHash; Handle<std::string> hhash = cert->getThumbprint(); PkiStore::bin_to_strhex((unsigned char *)hhash->c_str(), hhash->length(), &hexHash); item->hash = new std::string(hexHash); item->certSubjectName = cert->getSubjectName(); item->certSubjectFriendlyName = cert->getSubjectFriendlyName(); item->certIssuerName = cert->getIssuerName(); item->certIssuerFriendlyName = cert->getIssuerFriendlyName(); item->certSerial = cert->getSerialNumber(); item->certOrganizationName = cert->getOrganizationName(); item->certSignatureAlgorithm = cert->getSignatureAlgorithm(); item->certNotBefore = cert->getNotBefore(); item->certNotAfter = cert->getNotAfter(); return item; } catch (Handle<Exception> e){ THROW_EXCEPTION(0, ProviderCryptopro, e, "Error create PkiItem from certificate"); } } Handle<PkiItem> ProviderCryptopro::objectToPKIItem(Handle<CRL> crl){ LOGGER_FN(); try{ if (crl.isEmpty()){ THROW_EXCEPTION(0, ProviderCryptopro, NULL, "CRL empty"); } Handle<PkiItem> item = new PkiItem(); item->format = new std::string("DER"); item->type = new std::string("CRL"); item->provider = new std::string("CRYPTOPRO"); char * hexHash; Handle<std::string> hhash = crl->getThumbprint(); PkiStore::bin_to_strhex((unsigned char *)hhash->c_str(), hhash->length(), &hexHash); item->hash = new std::string(hexHash); item->crlIssuerName = crl->issuerName(); item->crlIssuerFriendlyName = crl->issuerFriendlyName(); item->crlLastUpdate = crl->getThisUpdate(); item->crlNextUpdate = crl->getNextUpdate(); return item; } catch (Handle<Exception> e){ THROW_EXCEPTION(0, ProviderCryptopro, e, "Error create PkiItem from crl"); } } Handle<Certificate> ProviderCryptopro::getCert(Handle<std::string> hash, Handle<std::string> category){ LOGGER_FN(); X509 *hcert = NULL; try{ HCERTSTORE hCertStore; PCCERT_CONTEXT pCertContext = NULL; const unsigned char *p; std::wstring wCategory = std::wstring(category->begin(), category->end()); char cHash[20] = { 0 }; hex2bin(hash->c_str(), cHash); CRYPT_HASH_BLOB cblobHash; cblobHash.pbData = (BYTE *)cHash; cblobHash.cbData = (DWORD)20; hCertStore = CertOpenStore( CERT_STORE_PROV_SYSTEM, PKCS_7_ASN_ENCODING | X509_ASN_ENCODING, NULL, CERT_SYSTEM_STORE_CURRENT_USER, wCategory.c_str() ); if (!hCertStore) { THROW_EXCEPTION(0, ProviderCryptopro, NULL, "Error open store"); } pCertContext = CertFindCertificateInStore( hCertStore, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, CERT_FIND_HASH, &cblobHash, NULL); if (pCertContext) { p = pCertContext->pbCertEncoded; LOGGER_OPENSSL(d2i_X509); if (!(hcert = d2i_X509(NULL, &p, pCertContext->cbCertEncoded))) { THROW_OPENSSL_EXCEPTION(0, ProviderCryptopro, NULL, "'d2i_X509' Error decode len bytes"); } if (pCertContext){ CertFreeCertificateContext(pCertContext); } if (hCertStore) { CertCloseStore(hCertStore, 0); } return new Certificate(hcert); } else{ THROW_EXCEPTION(0, ProviderCryptopro, NULL, "Cannot find certificate in store"); } } catch (Handle<Exception> e){ THROW_EXCEPTION(0, ProviderCryptopro, e, "Error get certificate"); } } Handle<CRL> ProviderCryptopro::getCRL(Handle<std::string> hash, Handle<std::string> category){ LOGGER_FN(); try{ HCERTSTORE hCertStore; PCCRL_CONTEXT pCrlContext = NULL; const unsigned char *p; std::wstring wCategory = std::wstring(category->begin(), category->end()); hCertStore = CertOpenStore( CERT_STORE_PROV_SYSTEM, PKCS_7_ASN_ENCODING | X509_ASN_ENCODING, NULL, CERT_SYSTEM_STORE_CURRENT_USER, wCategory.c_str() ); if (!hCertStore) { THROW_EXCEPTION(0, ProviderCryptopro, NULL, "Error open store"); } do { pCrlContext = CertEnumCRLsInStore(hCertStore, pCrlContext); if (pCrlContext){ X509_CRL *tempCrl = NULL; p = pCrlContext->pbCrlEncoded; LOGGER_OPENSSL(d2i_X509_CRL); if (!(tempCrl = d2i_X509_CRL(NULL, &p, pCrlContext->cbCrlEncoded))) { THROW_OPENSSL_EXCEPTION(0, ProviderCryptopro, NULL, "'d2i_X509_CRL' Error decode len bytes"); } Handle<CRL> hTempCrl = new CRL(tempCrl); char * hexHash; Handle<std::string> hhash = hTempCrl->getThumbprint(); PkiStore::bin_to_strhex((unsigned char *)hhash->c_str(), hhash->length(), &hexHash); std::string sh(hexHash); if (strcmp(sh.c_str(), hash->c_str()) == 0){ return hTempCrl; } } } while (pCrlContext != NULL); if (pCrlContext){ CertFreeCRLContext(pCrlContext); } if (hCertStore) { CertCloseStore(hCertStore, 0); } THROW_EXCEPTION(0, ProviderCryptopro, NULL, "Cannot find CRL in store"); } catch (Handle<Exception> e){ THROW_EXCEPTION(0, ProviderCryptopro, e, "Error get CRL"); } } Handle<Key> ProviderCryptopro::getKey(Handle<Certificate> cert) { LOGGER_FN(); EVP_PKEY_CTX *pctx = NULL; EVP_PKEY *pkey = NULL; EVP_MD_CTX *mctx = NULL; try{ #ifndef OPENSSL_NO_CTGOSTCP #define MAX_SIGNATURE_LEN 128 size_t len; unsigned char buf[MAX_SIGNATURE_LEN]; ENGINE *e = ENGINE_by_id("ctgostcp"); if (e == NULL) { THROW_OPENSSL_EXCEPTION(0, ProviderCryptopro, NULL, "CTGSOTCP is not loaded"); } LOGGER_OPENSSL(EVP_PKEY_CTX_new_id); pctx = EVP_PKEY_CTX_new_id(NID_id_GostR3410_2001, e); LOGGER_OPENSSL(EVP_PKEY_keygen_init); if (EVP_PKEY_keygen_init(pctx) <= 0){ THROW_OPENSSL_EXCEPTION(0, ProviderCryptopro, NULL, "EVP_PKEY_keygen_init"); } LOGGER_OPENSSL(EVP_PKEY_CTX_ctrl_str); if (EVP_PKEY_CTX_ctrl_str(pctx, CTGOSTCP_PKEY_CTRL_STR_PARAM_KEYSET, "all") <= 0){ THROW_OPENSSL_EXCEPTION(0, ProviderCryptopro, NULL, "EVP_PKEY_CTX_ctrl_str CTGOSTCP_PKEY_CTRL_STR_PARAM_KEYSET 'all'"); } LOGGER_OPENSSL(EVP_PKEY_CTX_ctrl_str); if (EVP_PKEY_CTX_ctrl_str(pctx, CTGOSTCP_PKEY_CTRL_STR_PARAM_EXISTING, "true") <= 0){ THROW_OPENSSL_EXCEPTION(0, ProviderCryptopro, NULL, "EVP_PKEY_CTX_ctrl_str CTGOSTCP_PKEY_CTRL_STR_PARAM_EXISTING 'true'"); } LOGGER_OPENSSL(CTGOSTCP_EVP_PKEY_CTX_init_key_by_cert); if (CTGOSTCP_EVP_PKEY_CTX_init_key_by_cert(pctx, cert->internal()) <= 0){ THROW_OPENSSL_EXCEPTION(0, ProviderCryptopro, NULL, "Can not init key context by certificate"); } LOGGER_OPENSSL(EVP_PKEY_CTX_ctrl_str); if (EVP_PKEY_CTX_ctrl_str(pctx, CTGOSTCP_PKEY_CTRL_STR_PARAM_EXISTING, "true") <= 0){ THROW_OPENSSL_EXCEPTION(0, ProviderCryptopro, NULL, "Parameter 'existing' setting error"); } LOGGER_OPENSSL(EVP_PKEY_keygen); if (EVP_PKEY_keygen(pctx, &pkey) <= 0){ THROW_OPENSSL_EXCEPTION(0, ProviderCryptopro, NULL, "Can not init key by certificate"); } int md_type = 0; const EVP_MD *md = NULL; LOGGER_OPENSSL(EVP_PKEY_get_default_digest_nid); if (EVP_PKEY_get_default_digest_nid(pkey, &md_type) <= 0) { THROW_OPENSSL_EXCEPTION(0, ProviderCryptopro, NULL, "default digest for key type not found"); } LOGGER_OPENSSL(EVP_get_digestbynid); md = EVP_get_digestbynid(md_type); LOGGER_OPENSSL(EVP_MD_CTX_create); if (!(mctx = EVP_MD_CTX_create())) { THROW_OPENSSL_EXCEPTION(0, ProviderCryptopro, NULL, "Error creating digest context"); } len = sizeof(buf); LOGGER_OPENSSL(EVP_DigestSignInit); if (!EVP_DigestSignInit(mctx, NULL, md, e, pkey) || (EVP_DigestSignUpdate(mctx, "123", 3) <= 0) || !EVP_DigestSignFinal(mctx, buf, &len)) { THROW_OPENSSL_EXCEPTION(0, ProviderCryptopro, NULL, "Error testing private key (via signing data)"); } return new Key(pkey); #else THROW_EXCEPTION(0, ProviderCryptopro, NULL, "Only with CTGSOTCP"); #endif } catch (Handle<Exception> e){ THROW_EXCEPTION(0, ProviderCryptopro, e, "Error get key"); } if (mctx) EVP_MD_CTX_destroy(mctx); if (pkey) EVP_PKEY_free(pkey); if (pctx) EVP_PKEY_CTX_free(pctx); } int ProviderCryptopro::char2int(char input) { LOGGER_FN(); try{ if (input >= '0' && input <= '9'){ return input - '0'; } if (input >= 'A' && input <= 'F'){ return input - 'A' + 10; } if (input >= 'a' && input <= 'f'){ return input - 'a' + 10; } THROW_EXCEPTION(0, ProviderCryptopro, NULL, "Invalid input string"); } catch (Handle<Exception> e){ THROW_EXCEPTION(0, ProviderCryptopro, e, "Error char to int"); } } void ProviderCryptopro::hex2bin(const char* src, char* target) { LOGGER_FN(); while (*src && src[1]){ *(target++) = char2int(*src) * 16 + char2int(src[1]); src += 2; } }
26.739696
125
0.699602
microshine
82ea8dd36206e5b09d557281591a37ecd9cfdd00
560
hpp
C++
src/utils/hittable.hpp
Kingfish404/ray-tracing-cpp
d4c2e3d32df0febd028e7e0ba36d21c3abc25664
[ "MIT" ]
1
2022-03-25T10:46:34.000Z
2022-03-25T10:46:34.000Z
src/utils/hittable.hpp
Kingfish404/ray-tracing-cpp
d4c2e3d32df0febd028e7e0ba36d21c3abc25664
[ "MIT" ]
null
null
null
src/utils/hittable.hpp
Kingfish404/ray-tracing-cpp
d4c2e3d32df0febd028e7e0ba36d21c3abc25664
[ "MIT" ]
null
null
null
#pragma once #ifndef HITTABLE_HPP #define HITTABLE_HPP #include "../common.hpp" class material; struct hit_record { point3 p; vec3 normal; shared_ptr<material> mat_ptr; double t; bool front_face; inline void set_face_normal(const ray &r, const vec3 &outward_normal) { front_face = r.direction().dot(outward_normal) < 0; normal = front_face ? outward_normal : -outward_normal; } }; class hittable { public: virtual bool hit(const ray &r, double t_min, double t_max, hit_record &rec) const = 0; }; #endif
18.666667
90
0.680357
Kingfish404
82efaacf949fc75362d7bcbca2c0dc2e6c935856
24,115
cxx
C++
src/openlcb/EventHandlerTemplates.cxx
TrainzLuvr/openmrn
b3bb9d4995e49aa39856740d292d38cf4a99845b
[ "BSD-2-Clause" ]
null
null
null
src/openlcb/EventHandlerTemplates.cxx
TrainzLuvr/openmrn
b3bb9d4995e49aa39856740d292d38cf4a99845b
[ "BSD-2-Clause" ]
null
null
null
src/openlcb/EventHandlerTemplates.cxx
TrainzLuvr/openmrn
b3bb9d4995e49aa39856740d292d38cf4a99845b
[ "BSD-2-Clause" ]
null
null
null
/** \copyright * Copyright (c) 2013, Balazs Racz * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * \file EventHandlerTemplates.cxx * * Implementations of common event handlers. * * @author Balazs Racz * @date 6 November 2013 */ #include <unistd.h> #include "utils/logging.h" #include "openlcb/EventHandlerTemplates.hxx" #include "openlcb/EventService.hxx" #ifdef __linux__ //#define DESCRIBE_VAR #endif #ifdef DESCRIBE_VAR extern int debug_variables; int debug_variables = 0; #include <string> namespace openlcb { extern const string &GetNameForEvent(uint64_t); __attribute__((weak)) const string &GetNameForEvent(uint64_t) { static string empty; return empty; } } #endif namespace openlcb { BitRangeEventPC::BitRangeEventPC(Node *node, uint64_t event_base, uint32_t *backing_store, unsigned size) : event_base_(event_base) , node_(node) , data_(backing_store) , size_(size) { unsigned mask = EventRegistry::align_mask(&event_base, size * 2); EventRegistry::instance()->register_handler( EventRegistryEntry(this, event_base), mask); } BitRangeEventPC::~BitRangeEventPC() { EventRegistry::instance()->unregister_handler(this); } void BitRangeEventPC::GetBitAndMask(unsigned bit, uint32_t **data, uint32_t *mask) const { *data = nullptr; if (bit >= size_) return; *data = data_ + (bit >> 5); *mask = 1 << (bit & 31); } bool BitRangeEventPC::Get(unsigned bit) const { HASSERT(bit < size_); uint32_t *ofs; uint32_t mask; GetBitAndMask(bit, &ofs, &mask); if (!ofs) return false; return (*ofs) & mask; } void BitRangeEventPC::Set(unsigned bit, bool new_value, WriteHelper *writer, BarrierNotifiable *done) { HASSERT(bit < size_); uint32_t *ofs; uint32_t mask; GetBitAndMask(bit, &ofs, &mask); bool old_value = new_value; HASSERT(ofs); if (ofs) old_value = (*ofs) & mask; if (old_value != new_value) { #ifdef DESCRIBE_VAR if (debug_variables) { fprintf(stderr, "BitRange: OUT bit %x (%s) to %d\n", bit, GetNameForEvent(event_base_ + (bit * 2)).c_str(), new_value); } #else LOG(VERBOSE, "BitRange: set bit %x to %d", bit, new_value); #endif if (new_value) { *ofs |= mask; } else { *ofs &= ~mask; } uint64_t event = event_base_ + bit * 2; if (!new_value) event++; writer->WriteAsync(node_, Defs::MTI_EVENT_REPORT, WriteHelper::global(), eventid_to_buffer(event), done); #ifndef TARGET_LPC11Cxx if (!done) { // We wait for the sent-out event to come back. Otherwise there is a // race // condition where the automata processing could have gone further, // but // the "set" message will arrive. while (EventService::instance->event_processing_pending()) { usleep(100); } } #endif } else { #ifdef DESCRIBE_VAR if (debug_variables > 2) { fprintf(stderr, "BitRange: out bit %x (%s) to %d\n", bit, GetNameForEvent(event_base_ + (bit * 2)).c_str(), new_value); } #endif if (done) done->notify(); } } void BitRangeEventPC::handle_event_report(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { done->notify(); if (event->event < event_base_) return; uint64_t d = (event->event - event_base_); bool new_value = !(d & 1); d >>= 1; if (d >= size_) return; int bit = d; #ifdef DESCRIBE_VAR if (debug_variables) { fprintf(stderr, "BitRange: IN bit %x (%s) to %d\n", bit, GetNameForEvent(event_base_ + (2 * bit)).c_str(), new_value); } #else LOG(VERBOSE, "BitRange: evt bit %x to %d", bit, new_value); #endif uint32_t *ofs = nullptr; uint32_t mask = 0; GetBitAndMask(bit, &ofs, &mask); if (new_value) { *ofs |= mask; } else { *ofs &= ~mask; } } void BitRangeEventPC::handle_identify_producer(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { HandleIdentifyBase(Defs::MTI_PRODUCER_IDENTIFIED_VALID, event, done); } void BitRangeEventPC::handle_identify_consumer(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { HandleIdentifyBase(Defs::MTI_CONSUMER_IDENTIFIED_VALID, event, done); } void BitRangeEventPC::HandleIdentifyBase(Defs::MTI mti_valid, EventReport *event, BarrierNotifiable *done) { if (event->event < event_base_) return done->notify(); uint64_t d = (event->event - event_base_); bool new_value = !(d & 1); d >>= 1; if (d >= size_) return done->notify(); uint32_t *ofs = nullptr; uint32_t mask = 0; GetBitAndMask(d, &ofs, &mask); Defs::MTI mti = mti_valid; bool old_value = *ofs & mask; if (old_value != new_value) { mti++; // mti INVALID } event->event_write_helper<1>()->WriteAsync(node_, mti, WriteHelper::global(), eventid_to_buffer(event->event), done); } uint64_t EncodeRange(uint64_t begin, unsigned size) { // We assemble a valid event range identifier that covers our block. uint64_t end = begin + size - 1; uint64_t shift = 1; while ((begin + shift) < end) { begin &= ~shift; shift <<= 1; } if (begin & shift) { // last real bit is 1 => range ends with zero. return begin; } else { // last real bit is zero. Set all lower bits to 1. begin |= shift - 1; return begin; } } void BitRangeEventPC::handle_identify_global(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { if (event->dst_node && event->dst_node != node_) { return done->notify(); } uint64_t range = EncodeRange(event_base_, size_ * 2); event->event_write_helper<1>()->WriteAsync(node_, Defs::MTI_PRODUCER_IDENTIFIED_RANGE, WriteHelper::global(), eventid_to_buffer(range), done->new_child()); event->event_write_helper<2>()->WriteAsync(node_, Defs::MTI_CONSUMER_IDENTIFIED_RANGE, WriteHelper::global(), eventid_to_buffer(range), done->new_child()); done->maybe_done(); } void BitRangeEventPC::SendIdentified(WriteHelper *writer, BarrierNotifiable *done) { uint64_t range = EncodeRange(event_base_, size_ * 2); writer->WriteAsync(node_, Defs::MTI_PRODUCER_IDENTIFIED_RANGE, WriteHelper::global(), eventid_to_buffer(range), done); } ByteRangeEventC::ByteRangeEventC(Node *node, uint64_t event_base, uint8_t *backing_store, unsigned size) : event_base_(event_base) , node_(node) , data_(backing_store) , size_(size) { unsigned mask = EventRegistry::align_mask(&event_base, size * 256); EventRegistry::instance()->register_handler( EventRegistryEntry(this, event_base), mask); } ByteRangeEventC::~ByteRangeEventC() { EventRegistry::instance()->unregister_handler(this); } void ByteRangeEventC::handle_event_report(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { done->notify(); uint8_t *storage; uint8_t value; if (!DecodeEventId(event->event, &storage, &value)) return; #ifdef DESCRIBE_VAR if (debug_variables) { fprintf(stderr, "ByteRange: IN byte %" PRIxPTR " to %d\n", storage - data_, value); } #else LOG(VERBOSE, "ByteRange: evt %x to %d", (unsigned)(storage - data_), value); #endif *storage = value; notify_changed(storage - data_); } bool ByteRangeEventC::DecodeEventId(uint64_t event, uint8_t **storage, uint8_t *value) { *storage = nullptr; *value = 0; if (event < event_base_) return false; event -= event_base_; *value = event & 0xff; event >>= 8; if (event >= size_) return false; *storage = data_ + event; return true; } void ByteRangeEventC::handle_identify_consumer(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { uint8_t *storage; uint8_t value; if (!DecodeEventId(event->event, &storage, &value)) { return done->notify(); } Defs::MTI mti = Defs::MTI_CONSUMER_IDENTIFIED_VALID; if (*storage != value) { mti++; // mti INVALID } event->event_write_helper<1>()->WriteAsync(node_, mti, WriteHelper::global(), eventid_to_buffer(event->event), done); } void ByteRangeEventC::handle_identify_global(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { if (event->dst_node && event->dst_node != node_) { return done->notify(); } uint64_t range = EncodeRange(event_base_, size_ * 256); event->event_write_helper<1>()->WriteAsync(node_, Defs::MTI_CONSUMER_IDENTIFIED_RANGE, WriteHelper::global(), eventid_to_buffer(range), done->new_child()); done->maybe_done(); } void ByteRangeEventC::SendIdentified(WriteHelper *writer, BarrierNotifiable *done) { uint64_t range = EncodeRange(event_base_, size_ * 256); writer->WriteAsync(node_, Defs::MTI_CONSUMER_IDENTIFIED_RANGE, WriteHelper::global(), eventid_to_buffer(range), done); } ByteRangeEventP::ByteRangeEventP(Node *node, uint64_t event_base, uint8_t *backing_store, unsigned size) : ByteRangeEventC(node, event_base, backing_store, size) { } void ByteRangeEventP::handle_event_report(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { // Nothing to do for producers. done->notify(); } void ByteRangeEventP::handle_identify_consumer(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { // Nothing to do for producers. done->notify(); } uint64_t ByteRangeEventP::CurrentEventId(unsigned byte) { return event_base_ + (byte << 8) + data_[byte]; } void ByteRangeEventP::handle_identify_producer(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { uint8_t *storage; uint8_t value; if (!DecodeEventId(event->event, &storage, &value)) { return done->notify(); } Defs::MTI mti = Defs::MTI_PRODUCER_IDENTIFIED_VALID; if (*storage != value) { mti++; // mti INVALID // We also send off the currently valid value. Update( storage - data_, event->event_write_helper<2>(), done->new_child()); } event->event_write_helper<1>()->WriteAsync(node_, mti, WriteHelper::global(), eventid_to_buffer(event->event), done->new_child()); done->maybe_done(); } void ByteRangeEventP::handle_identify_global(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { if (event->dst_node && event->dst_node != node_) { return done->notify(); } uint64_t range = EncodeRange(event_base_, size_ * 256); event->event_write_helper<1>()->WriteAsync(node_, Defs::MTI_PRODUCER_IDENTIFIED_RANGE, WriteHelper::global(), eventid_to_buffer(range), done); } void ByteRangeEventP::SendIdentified(WriteHelper *writer, BarrierNotifiable *done) { uint64_t range = EncodeRange(event_base_, size_ * 256); writer->WriteAsync(node_, Defs::MTI_PRODUCER_IDENTIFIED_RANGE, WriteHelper::global(), eventid_to_buffer(range), done); } void ByteRangeEventP::Update(unsigned byte, WriteHelper *writer, BarrierNotifiable *done) { // @TODO(balazs.racz): Should we use producer identified valid or event // report here? writer->WriteAsync(node_, Defs::MTI_EVENT_REPORT, WriteHelper::global(), eventid_to_buffer(CurrentEventId(byte)), done); } // Responses to possible queries. void ByteRangeEventP::handle_consumer_identified(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { uint8_t *storage; uint8_t value; if (!DecodeEventId(event->event, &storage, &value)) { return done->notify(); } Update(storage - data_, event->event_write_helper<1>(), done); } void ByteRangeEventP::handle_consumer_range_identified(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { /** @TODO(balazs.racz): We should respond with the correct signal aspect * for each offset that we offer. */ if (event->event + event->mask < event_base_) { return done->notify(); } if (event->event >= event_base_ + size_ * 256) { return done->notify(); } unsigned start_offset = 0; unsigned end_offset = 0; uint8_t *storage; uint8_t value; if (!DecodeEventId(event->event, &storage, &value)) { start_offset = 0; } else { start_offset = storage - data_; } if (!DecodeEventId(event->event + event->mask, &storage, &value)) { end_offset = size_; } else { end_offset = storage - data_ + 1; } unsigned cur = start_offset; if (cur < end_offset) { Update(cur++, event->event_write_helper<1>(), done->new_child()); } if (cur < end_offset) { Update(cur++, event->event_write_helper<2>(), done->new_child()); } if (cur < end_offset) { Update(cur++, event->event_write_helper<3>(), done->new_child()); } if (cur < end_offset) { Update(cur++, event->event_write_helper<4>(), done->new_child()); } // This will crash if more than four packets are to be produced. The above // code should be replaced by a background iteration in that case. HASSERT(cur >= end_offset); done->maybe_done(); } BitEventHandler::BitEventHandler(BitEventInterface *bit) : bit_(bit) { } void BitEventHandler::register_handler(uint64_t event_on, uint64_t event_off) { if ((event_on ^ event_off) == 1ULL) { // Register once for two eventids. uint64_t id = event_on & (~1ULL); unsigned user_data = 0; if (event_on & 1) { user_data |= BOTH_OFF_IS_ZERO; } else { user_data |= BOTH_ON_IS_ZERO; } EventRegistry::instance()->register_handler( EventRegistryEntry(this, id, user_data), 1); } else { EventRegistry::instance()->register_handler( EventRegistryEntry(this, event_on, EVENT_ON), 0); EventRegistry::instance()->register_handler( EventRegistryEntry(this, event_off, EVENT_OFF), 0); } } void BitEventHandler::unregister_handler() { EventRegistry::instance()->unregister_handler(this); } void BitEventHandler::SendProducerIdentified( EventReport *event, BarrierNotifiable *done) { EventState state = bit_->get_current_state(); Defs::MTI mti = Defs::MTI_PRODUCER_IDENTIFIED_VALID + state; event->event_write_helper<1>()->WriteAsync(bit_->node(), mti, WriteHelper::global(), eventid_to_buffer(bit_->event_on()), done->new_child()); mti = Defs::MTI_PRODUCER_IDENTIFIED_VALID + invert_event_state(state); event->event_write_helper<2>()->WriteAsync(bit_->node(), mti, WriteHelper::global(), eventid_to_buffer(bit_->event_off()), done->new_child()); } void BitEventHandler::SendConsumerIdentified( EventReport *event, BarrierNotifiable *done) { EventState state = bit_->get_current_state(); Defs::MTI mti = Defs::MTI_CONSUMER_IDENTIFIED_VALID + state; event->event_write_helper<3>()->WriteAsync(bit_->node(), mti, WriteHelper::global(), eventid_to_buffer(bit_->event_on()), done->new_child()); mti = Defs::MTI_CONSUMER_IDENTIFIED_VALID + invert_event_state(state); event->event_write_helper<4>()->WriteAsync(bit_->node(), mti, WriteHelper::global(), eventid_to_buffer(bit_->event_off()), done->new_child()); } void BitEventHandler::SendEventReport(WriteHelper *writer, Notifiable *done) { EventState value = bit_->get_requested_state(); uint64_t event; if (value == EventState::VALID) { event = bit_->event_on(); } else if (value == EventState::INVALID) { event = bit_->event_off(); } else { DIE("Requested sending event report for a bit event that is in unknown " "state."); } writer->WriteAsync(bit_->node(), Defs::MTI_EVENT_REPORT, WriteHelper::global(), eventid_to_buffer(event), done); } void BitEventHandler::HandlePCIdentify(Defs::MTI mti, EventReport *event, BarrierNotifiable *done) { if (event->src_node.id == bit_->node()->node_id()) { // We don't respond to queries from our own node. This is not nice, but // we // want to avoid to answering our own Query command. done->notify(); return; } EventState active; if (event->event == bit_->event_on()) { active = bit_->get_current_state(); } else if (event->event == bit_->event_off()) { active = invert_event_state(bit_->get_current_state()); } else { done->notify(); return; } mti = mti + active; event->event_write_helper<1>()->WriteAsync(bit_->node(), mti, WriteHelper::global(), eventid_to_buffer(event->event), done); } void BitEventConsumer::handle_producer_identified(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { done->notify(); bool value; if (event->state == EventState::VALID) { value = true; } else if (event->state == EventState::INVALID) { value = false; } else { return; // nothing to learn from this message. } if (event->event == bit_->event_on()) { bit_->set_state(value); } else if (event->event == bit_->event_off()) { bit_->set_state(!value); } else { return; // uninteresting event id. } } void BitEventConsumer::SendQuery(WriteHelper *writer, BarrierNotifiable *done) { writer->WriteAsync(bit_->node(), Defs::MTI_PRODUCER_IDENTIFY, WriteHelper::global(), eventid_to_buffer(bit_->event_on()), done); } void BitEventConsumer::handle_event_report(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { if (event->event == bit_->event_on()) { bit_->set_state(true); } else if (event->event == bit_->event_off()) { bit_->set_state(false); } done->notify(); } void BitEventProducer::SendQuery(WriteHelper *writer, BarrierNotifiable *done) { writer->WriteAsync(bit_->node(), Defs::MTI_CONSUMER_IDENTIFY, WriteHelper::global(), eventid_to_buffer(bit_->event_on()), done); } void BitEventProducer::handle_identify_global(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { if (event->dst_node && event->dst_node != bit_->node()) { return done->notify(); } SendProducerIdentified(event, done); done->maybe_done(); } void BitEventProducer::handle_identify_producer(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { HandlePCIdentify(Defs::MTI_PRODUCER_IDENTIFIED_VALID, event, done); } void BitEventPC::handle_identify_producer(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { HandlePCIdentify(Defs::MTI_PRODUCER_IDENTIFIED_VALID, event, done); } void BitEventConsumer::handle_identify_consumer(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { HandlePCIdentify(Defs::MTI_CONSUMER_IDENTIFIED_VALID, event, done); } void BitEventConsumer::handle_identify_global(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { if (event->dst_node && event->dst_node != bit_->node()) { return done->notify(); } SendConsumerIdentified(event, done); done->maybe_done(); } void BitEventPC::SendQueryConsumer(WriteHelper *writer, BarrierNotifiable *done) { writer->WriteAsync(bit_->node(), Defs::MTI_CONSUMER_IDENTIFY, WriteHelper::global(), eventid_to_buffer(bit_->event_on()), done); } void BitEventPC::handle_identify_global(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { if (event->dst_node && event->dst_node != bit_->node()) { return done->notify(); } SendProducerIdentified(event, done); SendConsumerIdentified(event, done); done->maybe_done(); } void BitEventPC::handle_consumer_identified(const EventRegistryEntry& entry, EventReport *event, BarrierNotifiable *done) { done->notify(); bool value; if (event->state == EventState::VALID) { value = true; } else if (event->state == EventState::INVALID) { value = false; } else { return; // nothing to learn from this message. } if (event->event == bit_->event_on()) { bit_->set_state(value); } else if (event->event == bit_->event_off()) { bit_->set_state(!value); } else { return; // uninteresting event id. } } }; /* namespace openlcb */
30.758929
107
0.612109
TrainzLuvr
82f1902a27eef2878a10b22fbe3abbddd49a5e4e
4,366
cpp
C++
src/shadereditor/src/shadereditor/nodes/vnode_matrices.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/shadereditor/src/shadereditor/nodes/vnode_matrices.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/shadereditor/src/shadereditor/nodes/vnode_matrices.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
 #include "cbase.h" #include "editorCommon.h" CNodeMatrix_MVP::CNodeMatrix_MVP(CNodeView *p) : BaseClass("Matrix MVP", p) { GenerateJacks_Output(1); LockJackOutput_Flags(0, HLSLVAR_MATRIX4X4, "Model View Projection"); } bool CNodeMatrix_MVP::CreateSolvers(GenericShaderData *ShaderData) { CJack *pJ_Out = GetJack_Out(0); const int res = pJ_Out->GetResourceType(); SetAllocating(false); CHLSL_Var *tg = pJ_Out->AllocateVarFromSmartType(); pJ_Out->SetTemporaryVarTarget(tg); CHLSL_Solver_MVP *solver = new CHLSL_Solver_MVP(GetUniqueIndex()); solver->SetResourceType(res); solver->AddTargetVar(tg); AddSolver(solver); return true; } CNodeMatrix_VP::CNodeMatrix_VP(CNodeView *p) : BaseClass("Matrix VP", p) { GenerateJacks_Output(1); LockJackOutput_Flags(0, HLSLVAR_MATRIX4X4, "View Projection"); } bool CNodeMatrix_VP::CreateSolvers(GenericShaderData *ShaderData) { CJack *pJ_Out = GetJack_Out(0); const int res = pJ_Out->GetResourceType(); SetAllocating(false); CHLSL_Var *tg = pJ_Out->AllocateVarFromSmartType(); pJ_Out->SetTemporaryVarTarget(tg); CHLSL_Solver_VP *solver = new CHLSL_Solver_VP(GetUniqueIndex()); solver->SetResourceType(res); solver->AddTargetVar(tg); AddSolver(solver); return true; } CNodeMatrix_M::CNodeMatrix_M(CNodeView *p) : BaseClass("Matrix Model", p) { GenerateJacks_Output(1); LockJackOutput_Flags(0, HLSLVAR_MATRIX4X3, "Model transform"); } bool CNodeMatrix_M::CreateSolvers(GenericShaderData *ShaderData) { CJack *pJ_Out = GetJack_Out(0); const int res = pJ_Out->GetResourceType(); SetAllocating(false); CHLSL_Var *tg = pJ_Out->AllocateVarFromSmartType(); pJ_Out->SetTemporaryVarTarget(tg); CHLSL_Solver_M *solver = new CHLSL_Solver_M(GetUniqueIndex()); solver->SetResourceType(res); solver->AddTargetVar(tg); AddSolver(solver); return true; } CNodeMatrix_VM::CNodeMatrix_VM(CNodeView *p) : BaseClass("Matrix VP", p) { GenerateJacks_Output(1); LockJackOutput_Flags(0, HLSLVAR_MATRIX4X4, "View Model"); } bool CNodeMatrix_VM::CreateSolvers(GenericShaderData *ShaderData) { CJack *pJ_Out = GetJack_Out(0); const int res = pJ_Out->GetResourceType(); SetAllocating(false); CHLSL_Var *tg = pJ_Out->AllocateVarFromSmartType(); pJ_Out->SetTemporaryVarTarget(tg); CHLSL_Solver_VM *solver = new CHLSL_Solver_VM(GetUniqueIndex()); solver->SetResourceType(res); solver->AddTargetVar(tg); AddSolver(solver); return true; } CNodeMatrix_FVP::CNodeMatrix_FVP(CNodeView *p) : BaseClass("Flashlight VP", p) { GenerateJacks_Output(1); LockJackOutput_Flags(0, HLSLVAR_MATRIX4X4, "Flashlight View Proj"); } bool CNodeMatrix_FVP::CreateSolvers(GenericShaderData *ShaderData) { CJack *pJ_Out = GetJack_Out(0); const int res = pJ_Out->GetResourceType(); SetAllocating(false); CHLSL_Var *tg = pJ_Out->AllocateVarFromSmartType(); pJ_Out->SetTemporaryVarTarget(tg); CHLSL_Solver_FVP *solver = new CHLSL_Solver_FVP(GetUniqueIndex()); solver->SetResourceType(res); solver->AddTargetVar(tg); AddSolver(solver); return true; } CNodeMatrix_Custom::CNodeMatrix_Custom(CNodeView *p) : BaseClass("Custom matrix", p) { m_iCustomID = CMATRIX_VIEW; GenerateJacks_Output(1); UpdateNode(); } void CNodeMatrix_Custom::UpdateNode() { const customMatrix_t *data = GetCMatrixInfo(m_iCustomID); LockJackOutput_Flags(0, data->iHLSLVarFlag, data->szCanvasName); } KeyValues *CNodeMatrix_Custom::AllocateKeyValues(int NodeIndex) { KeyValues *pKV = BaseClass::AllocateKeyValues(NodeIndex); pKV->SetInt("i_c_matrix", m_iCustomID); return pKV; } void CNodeMatrix_Custom::RestoreFromKeyValues_Specific(KeyValues *pKV) { m_iCustomID = pKV->GetInt("i_c_matrix"); UpdateNode(); } bool CNodeMatrix_Custom::CreateSolvers(GenericShaderData *ShaderData) { CJack *pJ_Out = GetJack_Out(0); const int res = pJ_Out->GetResourceType(); SetAllocating(false); CHLSL_Var *tg = pJ_Out->AllocateVarFromSmartType(); pJ_Out->SetTemporaryVarTarget(tg); CHLSL_Solver_CMatrix *solver = new CHLSL_Solver_CMatrix(GetUniqueIndex()); solver->SetMatrixID(m_iCustomID); solver->SetResourceType(res); solver->AddTargetVar(tg); AddSolver(solver); return true; }
29.70068
86
0.72721
cstom4994
82f4383c4b8b94f7530e5383d774075ffc28df0d
634
cpp
C++
Nowcoder/64J/implementation.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
2
2018-02-14T01:59:31.000Z
2018-03-28T03:30:45.000Z
Nowcoder/64J/implementation.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
null
null
null
Nowcoder/64J/implementation.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
2
2017-12-30T02:46:35.000Z
2018-03-28T03:30:49.000Z
#include <iostream> #include <cstdio> #include <cmath> #include <algorithm> #include <cstring> #include <string> #include <iomanip> #include <climits> using namespace std; int mapping[26]; int main() { ios::sync_with_stdio(false); for (int i = 0; i < 26; i++) { mapping[i] = i; } string s; cin >> s; int queryNum; cin >> queryNum; while (queryNum--) { char a, b; cin >> a >> b; swap(mapping[b - 'a'], mapping[a - 'a']); } for (int i = 0; i < s.length(); i++) { s[i] = mapping[s[i] - 'a'] + 'a'; } cout << s << endl; return 0; }
17.135135
49
0.498423
codgician